packages: Type-check artifact metadata

2f0ae73e45944a821cee1313a891f06dae24d6f83877214b429f7dcbf1487ae1
Check package metadata and lockfiles against a Radiance schema module,
compiler/radiance/artifact/schema.rad, which the compiler reads with
`@embed`. The build declares it with `-embed` and lists it as a
prerequisite, so an edit rebuilds the compiler.

Resolve each document with the normal front end, as the initializer of
a constant whose type is the expected schema declaration, with every
schema declaration in scope. Then read the value from the resolved tree
with the constant queries that lowering uses. Field projections and
subscripts lead to their literals, scalars come from resolved constant
values, and union fields from their variant symbols. Constant
expressions, repeat literals, and byte arrays are accepted where the
schema type accepts them. Write named FileRole variants and typed
constant slices.

The resolver exports the record field, array, and element steps of its
constant projections, so the reader shares them. Raise the module symbol
limit to 1024, because the resolver module reaches 512 symbols in the
test build.

Write content identities as hexadecimal strings, and parse them with
the new `blake3::parse`, which requires exactly 64 digits. Drop the size
fields: Full validation compares every hash, and Trusted cache entries
are published atomically, so a length check adds nothing.

Keep artifact path, content identity, and exact selection checks in the
loader. Reclaim the temporary frontend between reads and copy retained
descriptor strings into permanent storage. The reader takes the schema
source as an argument, so test/compiler/values.rad checks its typing
rules directly against a small schema.

Assisted-by: Codex:gpt-6
Assisted-by: Claude:opus-5.5
Change-Id: I783fbec371d5fe15964c4511087d810b6e8f4995
Alexis Sellier committed ago 1 parent ed7cb7b9
Makefile +10 -6
23 23
24 24
default: $(RAD_BIN)
25 25
26 26
# Compiler build
27 27
28 -
SEED         := seed/radiance.rv64
29 -
COMPILER_SRC := compiler/radiance.rad compiler/radiance/codegen.rad \
28 +
SEED              := seed/radiance.rv64
29 +
COMPILER_SRC      := compiler/radiance.rad compiler/radiance/codegen.rad \
30 30
    compiler/radiance/testgen.rad compiler/radiance/link.rad \
31 31
    compiler/radiance/artifact.rad compiler/radiance/metadata.rad \
32 -
    compiler/radiance/build.rad compiler/radiance/cache.rad compiler/radiance/locations.rad
32 +
    compiler/radiance/build.rad compiler/radiance/cache.rad compiler/radiance/locations.rad \
33 +
    compiler/radiance/artifact/value.rad
34 +
# Files that the compiler reads with `@embed`.
35 +
COMPILER_EMBED    := compiler/radiance/artifact/schema.rad
33 36
COMPILER_MANIFEST := $(STD_MANIFEST) compiler/radiance.manifest
34 -
SEED_OPTS    := $(STD) -pkg radiance $(patsubst %,-mod %,$(COMPILER_SRC)) \
35 -
    -entry radiance
37 +
SEED_OPTS         := $(STD) -pkg radiance $(patsubst %,-mod %,$(COMPILER_SRC)) \
38 +
    $(patsubst %,-embed %,$(COMPILER_EMBED)) -entry radiance
36 39
37 -
$(RAD_BIN): Makefile $(SEED) std.lib $(STD_LIB) $(COMPILER_SRC) $(COMPILER_MANIFEST) | $(BIN_DIR)
40 +
$(RAD_BIN): Makefile $(SEED) std.lib $(STD_LIB) $(COMPILER_SRC) $(COMPILER_EMBED) \
41 +
    $(COMPILER_MANIFEST) | $(BIN_DIR)
38 42
	@echo "radiance $(SEED) => $@"
39 43
	@$(HOSTED) $(SEED) $(SEED_OPTS) -o $@
40 44
41 45
# Compiler inputs shared by the normal build and bootstrap stages.
42 46
compiler-options:
compiler/radiance/artifact.rad +125 -185
1 1
//! Complete compiler interface trees paired with exact executable package images.
2 2
3 +
mod value;
4 +
3 5
use std::char;
4 -
use std::fmt;
5 6
use std::fs;
6 7
use std::io;
7 8
use std::hash::blake3;
8 9
use std::lang::alloc;
9 10
use std::lang::ast;
10 11
use std::lang::il::binary;
11 12
use std::lang::il::binary::linkage;
12 13
use std::lang::il::binary::program;
13 14
use std::lang::il::binary::reader;
14 15
use std::lang::layout;
15 -
use std::lang::parser;
16 16
use std::lang::pretty;
17 -
use std::lang::scanner;
18 17
use std::lang::sexpr;
19 18
use std::mem;
20 19
use std::mem::heap;
21 20
use std::sys;
22 21
23 -
/// Version of the artifact descriptor format.
22 +
/// Version of the artifact descriptor and lockfile formats. The image header
23 +
/// carries the RIL format and ABI versions.
24 24
constant VERSION: u32 = 1;
25 +
/// Declarations that artifact modules import, and that their typed consumer names.
26 +
constant SCHEMA: *[u8] = @embed("radiance/artifact/schema.rad");
25 27
/// Largest artifact metadata, including module and dependency descriptors.
26 28
constant MAX_METADATA: u32 = 1048576;
27 29
28 30
/// Content validation required when loading a package artifact set.
29 31
export union Validation: Copy {
61 63
    Debug,
62 64
    /// File contents that modules read with `@embed`.
63 65
    Embed,
64 66
}
65 67
66 -
/// File roles in the order of their encoded numbers.
68 +
/// File roles in the order of the schema's `FileRole` variants.
67 69
constant ROLES: [FileRole; 4] = [
68 70
    FileRole::Assembly, FileRole::Startup, FileRole::Debug, FileRole::Embed
69 71
];
72 +
/// Schema variant names of `ROLES`.
73 +
constant ROLE_NAMES: [*[u8]; 4] = ["Assembly", "Startup", "Debug", "Embed"];
70 74
71 75
/// An immutable non-Radiance artifact input.
72 76
export record File: Copy {
73 77
    /// Relative storage path inside the interface tree.
74 78
    path: *[u8],
212 216
    if let slash = mem::rfind(path, "/") {
213 217
        try fs::createDirAll(&path[.. slash]);
214 218
    }
215 219
}
216 220
217 -
/// Check a record's type, required fields, and unique field names.
218 -
fn readRecord(node: *ast::Node, name: *[u8], keys: &[*[u8]]) -> ast::RecordLit
219 -
    throws (binary::Error)
221 +
/// Read a 256-bit content identity from a hexadecimal string field.
222 +
fn readId(data: &value::Image, descriptor: value::Value, name: *[u8]) -> binary::Id
223 +
    throws (binary::Error, sys::Error)
220 224
{
221 -
    let case ast::NodeValue::RecordLit(literal) = node.value else throw binary::Error::Invalid;
222 -
    if literal.ignoreRest or literal.fields.len <> keys.len {
223 -
        throw binary::Error::Invalid;
224 -
    }
225 -
    if let type = literal.typeName {
226 -
        let case ast::NodeValue::Ident(text) = type.value else throw binary::Error::Invalid;
227 -
        if not mem::eq(text, name) {
228 -
            throw binary::Error::Invalid;
229 -
        }
230 -
    } else if name.len <> 0 {
225 +
    let hash = try blake3::parse(try data.bytes(descriptor, name)) catch {
231 226
        throw binary::Error::Invalid;
232 -
    }
233 -
    for key in keys {
234 -
        let mut count: u32 = 0;
235 -
        for field in literal.fields {
236 -
            let case ast::NodeValue::RecordLitField(arg) = field.value
237 -
                else throw binary::Error::Invalid;
238 -
            let label = arg.label else throw binary::Error::Invalid;
239 -
            let case ast::NodeValue::Ident(text) = label.value else throw binary::Error::Invalid;
240 -
            if mem::eq(text, key) {
241 -
                set count += 1;
242 -
            }
243 -
        }
244 -
        if count <> 1 {
245 -
            throw binary::Error::Invalid;
246 -
        }
247 -
    }
248 -
    return literal;
227 +
    };
228 +
    return binary::Id { bytes: hash.bytes };
249 229
}
250 230
251 -
/// Get a required record field by name.
252 -
fn fieldNode(literal: &ast::RecordLit, key: *[u8]) -> *ast::Node
253 -
    throws (binary::Error)
231 +
/// Build a slice of constant element nodes.
232 +
fn sliceValue(nodes: &mut ast::NodeArena, items: *[*ast::Node]) -> ast::NodeValue
233 +
    throws (alloc::AllocError)
254 234
{
255 -
    for field in literal.fields {
256 -
        let case ast::NodeValue::RecordLitField(arg) = field.value
257 -
            else throw binary::Error::Invalid;
258 -
        let label = arg.label else throw binary::Error::Invalid;
259 -
        let case ast::NodeValue::Ident(text) = label.value else throw binary::Error::Invalid;
260 -
        if mem::eq(text, key) {
261 -
            return arg.value;
262 -
        }
263 -
    }
264 -
    throw binary::Error::Invalid;
265 -
}
266 -
267 -
/// Read a decoded string literal.
268 -
fn readString(node: *ast::Node) -> *[u8] throws (binary::Error) {
269 -
    let case ast::NodeValue::String(text) = node.value else throw binary::Error::Invalid;
270 -
    return text;
235 +
    let target = try ast::synthNode(nodes, ast::arrayValue(items));
236 +
    return ast::NodeValue::AddressOf(ast::AddressOf { target, mutable: false });
271 237
}
272 238
273 -
/// Read an unsigned 32-bit integer literal.
274 -
fn readNumber(node: *ast::Node) -> u32 throws (binary::Error) {
275 -
    let case ast::NodeValue::Number(value) = node.value else throw binary::Error::Invalid;
276 -
    if value.magnitude > 0xffffffff {
277 -
        throw binary::Error::Invalid;
239 +
/// Format an artifact document, which is the value `root`.
240 +
fn render(root: *ast::Node, buffer: *mut [u8], arena: *heap::Heap) -> *[u8]
241 +
    throws (alloc::AllocError, binary::Error)
242 +
{
243 +
    let tree = try pretty::expression(root, arena);
244 +
    let mut out = sexpr::Buffer { buf: buffer, pos: 0 };
245 +
    {
246 +
        let sink: &mut opaque sexpr::Output = &mut out;
247 +
        layout::text::render(tree, layout::text::Options { width: 80, indent: 4 }, sink);
278 248
    }
279 -
    return value.magnitude as u32;
280 -
}
281 -
282 -
/// Read an array literal without evaluating expressions.
283 -
fn readArray(node: *ast::Node) -> *[*ast::Node] throws (binary::Error) {
284 -
    let case ast::NodeValue::ArrayLit(items) = node.value else throw binary::Error::Invalid;
285 -
    return items;
286 -
}
287 -
288 -
/// Read a 256-bit content identity from a hexadecimal string.
289 -
fn readId(node: *ast::Node) -> binary::Id throws (binary::Error) {
290 -
    let text = try readString(node);
291 -
    if text.len <> 64 {
292 -
        throw binary::Error::Invalid;
249 +
    if out.pos >= out.buf.len {
250 +
        throw binary::Error::Capacity;
293 251
    }
294 -
    let mut id = binary::Id { bytes: [0; 32] };
295 -
    try fmt::parseHex(text, &mut id.bytes[..]) catch {
296 -
        throw binary::Error::Invalid;
297 -
    };
298 -
    return id;
252 +
    return &out.buf[.. out.pos];
299 253
}
300 254
301 255
/// Format package metadata as a record literal.
302 256
/// The arena holds temporary AST nodes, literal text, and layout data.
303 257
export fn metadata(
304 258
    package: &Package,
305 259
    inputs: binary::Id,
306 260
    identity: binary::Id,
307 -
    imageSize: u32,
308 261
    buffer: *mut [u8],
309 262
    arena: *heap::Heap
310 263
) -> *[u8]
311 264
    throws (alloc::AllocError, binary::Error)
312 265
{
318 271
        let node = try ast::synthRecord(
319 272
            &mut nodes,
320 273
            "Module",
321 274
            &[
322 275
                ast::field("path", ast::stringValue(module.path)),
323 -
                ast::field("size", try ast::numberValue(module.text.len as u64, arena)),
324 276
                ast::field("hash", try ast::hexStringValue(&module.hash.bytes[..], arena)),
325 277
            ]
326 278
        );
327 279
        try modules.append(node, arena);
328 280
    }
329 281
    for file in package.files {
282 +
        let role = ROLE_NAMES[file.role as u32];
283 +
        let roleType = try ast::synthNode(&mut nodes, ast::NodeValue::Ident("FileRole"));
284 +
        let variant = try ast::synthNode(&mut nodes, ast::NodeValue::Ident(role));
330 285
        let node = try ast::synthRecord(
331 286
            &mut nodes,
332 287
            "File",
333 288
            &[
334 289
                ast::field("path", ast::stringValue(file.path)),
335 290
                ast::field("origin", ast::stringValue(file.origin)),
336 -
                ast::field("role", try ast::numberValue(file.role as u64, arena)),
337 -
                ast::field("size", try ast::numberValue(file.bytes.len as u64, arena)),
291 +
                ast::field("role", ast::NodeValue::ScopeAccess(ast::Access {
292 +
                    parent: roleType, child: variant
293 +
                })),
338 294
                ast::field("hash", try ast::hexStringValue(&digest(file.bytes).bytes[..], arena)),
339 295
            ]
340 296
        );
341 297
        try files.append(node, arena);
342 298
    }
352 308
                ),
353 309
            ]
354 310
        );
355 311
        try dependencies.append(node, arena);
356 312
    }
313 +
    let moduleValues = try sliceValue(&mut nodes, &modules[..]);
314 +
    let fileValues = try sliceValue(&mut nodes, &files[..]);
315 +
    let dependencyValues = try sliceValue(&mut nodes, &dependencies[..]);
357 316
    let root = try ast::synthRecord(
358 317
        &mut nodes,
359 318
        "Package",
360 319
        &[
361 320
            ast::field("version", try ast::numberValue(VERSION as u64, arena)),
362 321
            ast::field("name", ast::stringValue(package.name)),
363 -
            ast::field("exports", try ast::hexStringValue(&package.exports.bytes[..], arena)),
364 -
            ast::field("inputs",  try ast::hexStringValue(&inputs.bytes[..], arena)),
365 -
            ast::field("image",   try ast::hexStringValue(&identity.bytes[..], arena)),
366 -
            ast::field("size",    try ast::numberValue(imageSize as u64, arena)),
367 -
            ast::field("modules", ast::arrayValue(&modules[..])),
368 -
            ast::field("files", ast::arrayValue(&files[..])),
369 -
            ast::field("dependencies", ast::arrayValue(&dependencies[..])),
322 +
            ast::field("exports",      try ast::hexStringValue(&package.exports.bytes[..], arena)),
323 +
            ast::field("inputs",       try ast::hexStringValue(&inputs.bytes[..], arena)),
324 +
            ast::field("image",        try ast::hexStringValue(&identity.bytes[..], arena)),
325 +
            ast::field("modules",      moduleValues),
326 +
            ast::field("files",        fileValues),
327 +
            ast::field("dependencies", dependencyValues),
370 328
        ]
371 329
    );
372 -
    let tree = try pretty::expression(root, arena);
373 -
    let mut out = sexpr::Buffer { buf: buffer, pos: 0 };
374 -
    {
375 -
        let sink: &mut opaque sexpr::Output = &mut out;
376 -
        layout::text::render(tree, layout::text::Options { width: 80, indent: 4 }, sink);
377 -
    }
378 -
    if out.pos >= out.buf.len {
379 -
        throw binary::Error::Capacity;
380 -
    }
381 -
    return &out.buf[.. out.pos];
330 +
    return try render(root, buffer, arena);
382 331
}
383 332
384 333
/// Read package files and check their metadata with the selected content validation.
385 334
export fn read(
386 335
    root: *[u8],
387 336
    name: *[u8],
388 337
    validation: Validation,
389 -
    syntax: &mut parser::Parser,
338 +
    scratch: *heap::Heap,
390 339
    arena: &heap::Heap
391 340
) -> Package throws (sys::Error) {
392 341
    let tree = try join(arena, &[root, "/", name, ".interface/"]);
393 342
    let path = try join(arena, &[tree, "package.metadata"]);
394 343
    let info = try fs::stat(path) else throw sys::Error::NotFound;
395 344
    if info.size > MAX_METADATA as u64 {
396 345
        throw sys::Error::Invalid;
397 346
    }
398 -
    // Interned names point into metadata source for the life of the parser.
399 -
    let encoded = try readFile(path, syntax.arena.heap);
400 -
    return try locked(
401 -
        root, tree, name, encoded, validation, syntax, arena
347 +
    let encoded = try readFile(path, arena);
348 +
    // Decoded artifact fields own copies outside the temporary frontend storage.
349 +
    let mark = heap::mark(scratch);
350 +
    let result = try locked(
351 +
        root, tree, name, encoded, validation, scratch, arena
402 352
    ) catch err as binary::Error {
353 +
        unsafe {
354 +
            heap::rewind(scratch, mark);
355 +
        }
403 356
        if err == binary::Error::Storage {
404 357
            throw sys::Error::TooLarge;
405 358
        }
406 359
        throw sys::Error::Invalid;
407 360
    } catch err as sys::Error {
361 +
        unsafe {
362 +
            heap::rewind(scratch, mark);
363 +
        }
408 364
        throw err;
409 365
    };
366 +
    unsafe {
367 +
        heap::rewind(scratch, mark);
368 +
    }
369 +
    return result;
410 370
}
411 371
412 372
/// Decode metadata, check file structure, and apply the selected content validation.
413 373
fn decode(
414 374
    root: *[u8],
415 375
    tree: *[u8],
416 376
    name: *[u8],
417 377
    encoded: *[u8],
418 378
    validation: Validation,
419 -
    syntax: &mut parser::Parser,
379 +
    scratch: *heap::Heap,
420 380
    arena: &heap::Heap
421 381
) -> Package throws (binary::Error, sys::Error) {
422 -
    let value = try parser::parseValue(
423 -
        syntax, scanner::SourceLoc::String, encoded
424 -
    ) catch err {
425 -
        if err == parser::ParseError::AllocationFailed {
426 -
            throw binary::Error::Storage;
427 -
        }
428 -
        throw binary::Error::Invalid;
429 -
    };
430 -
    let literal = try readRecord(value, "Package", &[
431 -
        "version", "name", "exports", "inputs", "image", "size", "modules", "files", "dependencies"
432 -
    ]);
433 -
    if try readNumber(try fieldNode(&literal, "version")) <> VERSION
434 -
        or not mem::eq(try readString(try fieldNode(&literal, "name")), name)
382 +
    let data = try value::read(
383 +
        SCHEMA, encoded, try join(arena, &[tree, "package.metadata"]), "Package", scratch
384 +
    );
385 +
    let rootValue = data.root;
386 +
    if try data.number(rootValue, "version") <> VERSION
387 +
        or not mem::eq(try data.bytes(rootValue, "name"), name)
435 388
    {
436 389
        throw binary::Error::Invalid;
437 390
    }
438 -
    let exports = try readId(try fieldNode(&literal, "exports"));
439 -
    let inputs = try readId(try fieldNode(&literal, "inputs"));
440 -
    let identity = try readId(try fieldNode(&literal, "image"));
441 -
    let length = try readNumber(try fieldNode(&literal, "size"));
391 +
    let exports = try readId(&data, rootValue, "exports");
392 +
    let inputs = try readId(&data, rootValue, "inputs");
393 +
    let identity = try readId(&data, rootValue, "image");
442 394
    let image = try readFile(try join(arena, &[root, "/", name, ".ril"]), arena);
443 -
    if image.len <> length
444 -
        or image.len < 12
395 +
    if image.len < 12
445 396
        or mem::load32Le(image, 0) <> binary::MAGIC
446 397
        or mem::load32Le(image, 4) <> binary::FORMAT_VERSION
447 398
        or mem::load32Le(image, 8) <> binary::ABI_VERSION
448 399
        or (validation == Validation::Full and linkage::imageId(image) <> identity)
449 400
    {
450 401
        throw binary::Error::Invalid;
451 402
    }
452 -
    let moduleNodes = try readArray(try fieldNode(&literal, "modules"));
453 -
    if moduleNodes.len == 0 {
403 +
    let moduleValues = try data.items(rootValue, "modules");
404 +
    if moduleValues.len == 0 {
454 405
        throw binary::Error::Invalid;
455 406
    }
456 407
    let mut modules: *mut [Module] = &mut [];
457 -
    for node, i in moduleNodes {
458 -
        let descriptor = try readRecord(node, "Module", &["path", "size", "hash"]);
459 -
        let path = try readString(try fieldNode(&descriptor, "path"));
460 -
        let length = try readNumber(try fieldNode(&descriptor, "size"));
461 -
        let hash = try readId(try fieldNode(&descriptor, "hash"));
408 +
    for i in 0 .. moduleValues.len {
409 +
        let descriptor = try data.at(&moduleValues, i);
410 +
        let path = try join(arena, &[try data.bytes(descriptor, "path")]);
411 +
        let hash = try readId(&data, descriptor, "hash");
462 412
        if not validPath(path) or not mem::endsWith(path, ".rid") {
463 413
            throw binary::Error::Invalid;
464 414
        }
465 415
        if i == 0 {
466 416
            if not mem::eq(path, try join(arena, &[name, ".rid"])) {
468 418
            }
469 419
        } else if not mem::startsWith(path, try join(arena, &[name, "/"])) {
470 420
            throw binary::Error::Invalid;
471 421
        }
472 422
        let text = try readFile(try join(arena, &[tree, path]), arena);
473 -
        if text.len <> length or (validation == Validation::Full and digest(text) <> hash) {
423 +
        if validation == Validation::Full and digest(text) <> hash {
474 424
            throw binary::Error::Invalid;
475 425
        }
476 426
        try modules.append(Module { path, text, hash }, arena) catch {
477 427
            throw binary::Error::Storage;
478 428
        };
479 429
    }
480 -
    let fileNodes = try readArray(try fieldNode(&literal, "files"));
430 +
    let fileValues = try data.items(rootValue, "files");
481 431
    let mut files: *mut [File] = &mut [];
482 -
    for node in fileNodes {
483 -
        let descriptor = try readRecord(node, "File", &["path", "origin", "role", "size", "hash"]);
484 -
        let path = try readString(try fieldNode(&descriptor, "path"));
485 -
        let origin = try readString(try fieldNode(&descriptor, "origin"));
486 -
        let kind = try readNumber(try fieldNode(&descriptor, "role"));
432 +
    for i in 0 .. fileValues.len {
433 +
        let descriptor = try data.at(&fileValues, i);
434 +
        let path = try join(arena, &[try data.bytes(descriptor, "path")]);
435 +
        let origin = try join(arena, &[try data.bytes(descriptor, "origin")]);
436 +
        let kind = try data.variant(descriptor, "role");
487 437
        if not validPath(path) or kind >= ROLES.len {
488 438
            throw binary::Error::Invalid;
489 439
        }
490 -
        let length = try readNumber(try fieldNode(&descriptor, "size"));
491 -
        let hash = try readId(try fieldNode(&descriptor, "hash"));
440 +
        let hash = try readId(&data, descriptor, "hash");
492 441
        let bytes = try readFile(try join(arena, &[tree, path]), arena);
493 -
        if bytes.len <> length or (validation == Validation::Full and digest(bytes) <> hash) {
442 +
        if validation == Validation::Full and digest(bytes) <> hash {
494 443
            throw binary::Error::Invalid;
495 444
        }
496 445
        try files.append(File { path, origin, bytes, role: ROLES[kind] }, arena) catch {
497 446
            throw binary::Error::Storage;
498 447
        };
499 448
    }
500 -
    let dependencyNodes = try readArray(try fieldNode(&literal, "dependencies"));
449 +
    let dependencyValues = try data.items(rootValue, "dependencies");
501 450
    let mut dependencies: *mut [Dependency] = &mut [];
502 -
    for node in dependencyNodes {
503 -
        let descriptor = try readRecord(node, "Dependency", &["name", "declarations"]);
504 -
        let name = try readString(try fieldNode(&descriptor, "name"));
451 +
    for i in 0 .. dependencyValues.len {
452 +
        let descriptor = try data.at(&dependencyValues, i);
453 +
        let name = try join(arena, &[try data.bytes(descriptor, "name")]);
505 454
        if not validPath(name) {
506 455
            throw binary::Error::Invalid;
507 456
        }
508 -
        for i in 0 .. dependencies.len {
509 -
            if mem::eq(dependencies[i].name, name) {
457 +
        for j in 0 .. dependencies.len {
458 +
            if mem::eq(dependencies[j].name, name) {
510 459
                throw binary::Error::Invalid;
511 460
            }
512 461
        }
513 462
        for byte in name {
514 463
            if byte == '/' or byte == '.' {
515 464
                throw binary::Error::Invalid;
516 465
            }
517 466
        }
518 -
        let declarations = try readId(try fieldNode(&descriptor, "declarations"));
467 +
        let declarations = try readId(&data, descriptor, "declarations");
519 468
        try dependencies.append(Dependency { name, declarations }, arena) catch {
520 469
            throw binary::Error::Storage;
521 470
        };
522 471
    }
523 472
    let mut package = Package {
601 550
    root: *[u8],
602 551
    tree: *[u8],
603 552
    name: *[u8],
604 553
    encoded: *[u8],
605 554
    validation: Validation,
606 -
    syntax: &mut parser::Parser,
555 +
    scratch: *heap::Heap,
607 556
    arena: &heap::Heap
608 557
) -> Package throws (binary::Error, sys::Error) {
609 -
    let package = try decode(root, tree, name, encoded, validation, syntax, arena);
558 +
    let package = try decode(root, tree, name, encoded, validation, scratch, arena);
610 559
    let publication = package.publication else panic "locked: missing publication";
611 560
    if validation == Validation::Trusted {
612 561
        return package;
613 562
    }
614 563
    let path = try join(arena, &[root, "/package.lock"]);
615 564
    let info = try fs::stat(path) else return package;
616 565
    if info.size > MAX_METADATA as u64 {
617 566
        throw binary::Error::Invalid;
618 567
    }
619 -
    let encoded = try readFile(path, syntax.arena.heap);
620 -
    let node = try parser::parseValue(syntax, scanner::SourceLoc::String, encoded) catch error {
621 -
        if error == parser::ParseError::AllocationFailed {
622 -
            throw binary::Error::Storage;
623 -
        }
624 -
        throw binary::Error::Invalid;
625 -
    };
626 -
    let lock = try readRecord(node, "Lock", &["version", "packages"]);
627 -
    if try readNumber(try fieldNode(&lock, "version")) <> 1 {
568 +
    let encoded = try readFile(path, arena);
569 +
    let data = try value::read(SCHEMA, encoded, path, "Lock", scratch);
570 +
    if try data.number(data.root, "version") <> VERSION {
628 571
        throw binary::Error::Invalid;
629 572
    }
630 -
    let packages = try readArray(try fieldNode(&lock, "packages"));
573 +
    let packages = try data.items(data.root, "packages");
631 574
    let mut names: *mut [*[u8]] = &mut [];
632 575
    let mut found = false;
633 -
    for node in packages {
634 -
        let entry = try readRecord(node, "LockedPackage", &["name", "image", "metadata"]);
635 -
        let selected = try readString(try fieldNode(&entry, "name"));
636 -
        let image = try readId(try fieldNode(&entry, "image"));
637 -
        let metadata = try readId(try fieldNode(&entry, "metadata"));
638 -
        for i in 0 .. names.len {
639 -
            if mem::eq(names[i], selected) {
576 +
    for i in 0 .. packages.len {
577 +
        let entry = try data.at(&packages, i);
578 +
        let selected = try data.bytes(entry, "name");
579 +
        let image = try readId(&data, entry, "image");
580 +
        let metadata = try readId(&data, entry, "metadata");
581 +
        for j in 0 .. names.len {
582 +
            if mem::eq(names[j], selected) {
640 583
                throw binary::Error::Invalid;
641 584
            }
642 585
        }
643 -
        try names.append(selected, arena) catch {
586 +
        try names.append(selected, scratch) catch {
644 587
            throw binary::Error::Storage;
645 588
        };
646 589
        if mem::eq(selected, name) {
647 590
            if image <> publication.identity or metadata <> package.declarations {
648 591
                throw binary::Error::Invalid;
663 606
    let mut nodes = ast::NodeArena { heap: arena, nextId: 0 };
664 607
    let mut entries: *mut [*ast::Node] = &mut [];
665 608
    for package in packages {
666 609
        let publication = package.publication else panic "writeLock: missing publication";
667 610
        let identity = publication.identity;
611 +
        let image = try ast::hexStringValue(&identity.bytes[..], arena) catch {
612 +
            throw sys::Error::TooLarge;
613 +
        };
614 +
        let metadata = try ast::hexStringValue(&package.declarations.bytes[..], arena) catch {
615 +
            throw sys::Error::TooLarge;
616 +
        };
668 617
        let node = try ast::synthRecord(
669 618
            &mut nodes,
670 619
            "LockedPackage",
671 620
            &[
672 621
                ast::field("name", ast::stringValue(package.name)),
673 -
                ast::field("image", try ast::hexStringValue(&identity.bytes[..], arena)),
674 -
                ast::field(
675 -
                    "metadata", try ast::hexStringValue(&package.declarations.bytes[..], arena)
676 -
                ),
622 +
                ast::field("image",    image),
623 +
                ast::field("metadata", metadata),
677 624
            ]
678 625
        ) catch {
679 626
            throw sys::Error::TooLarge;
680 627
        };
681 628
        try entries.append(node, arena) catch {
682 629
            throw sys::Error::TooLarge;
683 630
        };
684 631
    }
632 +
    let packages = try sliceValue(&mut nodes, &entries[..]);
685 633
    let rootNode = try ast::synthRecord(
686 634
        &mut nodes,
687 635
        "Lock",
688 636
        &[
689 -
            ast::field("version", try ast::numberValue(1, arena)),
690 -
            ast::field("packages", ast::arrayValue(&entries[..])),
637 +
            ast::field("version",  try ast::numberValue(VERSION as u64, arena)),
638 +
            ast::field("packages", packages),
691 639
        ]
692 640
    ) catch {
693 641
        throw sys::Error::TooLarge;
694 642
    };
695 -
    let tree = try pretty::expression(rootNode, arena) catch {
696 -
        throw sys::Error::TooLarge;
697 -
    };
698 643
    let mut buffer: *mut [u8] = &mut [];
699 644
    try buffer.resize(MAX_METADATA, 0, arena) catch {
700 645
        throw sys::Error::TooLarge;
701 646
    };
702 -
    let mut out = sexpr::Buffer { buf: buffer.take(), pos: 0 };
703 -
    {
704 -
        let sink: &mut opaque sexpr::Output = &mut out;
705 -
        layout::text::render(tree, layout::text::Options { width: 80, indent: 4 }, sink);
706 -
    }
707 -
    if out.pos >= out.buf.len {
647 +
    let encoded = try render(rootNode, buffer.take(), arena) catch {
708 648
        throw sys::Error::TooLarge;
709 -
    }
710 -
    try fs::writeFile(try join(arena, &[root, "/package.lock"]), &out.buf[.. out.pos]);
649 +
    };
650 +
    try fs::writeFile(try join(arena, &[root, "/package.lock"]), encoded);
711 651
}
compiler/radiance/artifact/schema.rad added +82 -0
1 +
//! Compiler artifact descriptors and exact package selections.
2 +
//!
3 +
//! The compiler embeds this module and resolves package metadata and
4 +
//! lockfiles against it.
5 +
6 +
/// Use of a file stored with an artifact.
7 +
export union FileRole: Copy {
8 +
    /// Instructions after generated functions.
9 +
    Assembly,
10 +
    /// Entry instructions before generated functions.
11 +
    Startup,
12 +
    /// Source location tables.
13 +
    Debug,
14 +
    /// Contents read with `@embed`.
15 +
    Embed,
16 +
}
17 +
18 +
/// One compiler interface module.
19 +
export record Module: Copy {
20 +
    /// Relative interface path.
21 +
    path: *[u8],
22 +
    /// Content identity in hexadecimal.
23 +
    hash: *[u8],
24 +
}
25 +
26 +
/// One file stored with an artifact.
27 +
export record File: Copy {
28 +
    /// Relative storage path.
29 +
    path: *[u8],
30 +
    /// Diagnostic source path.
31 +
    origin: *[u8],
32 +
    /// Use of the contents.
33 +
    role: FileRole,
34 +
    /// Content identity in hexadecimal.
35 +
    hash: *[u8],
36 +
}
37 +
38 +
/// Required provider declarations.
39 +
export record Dependency: Copy {
40 +
    /// Provider package name.
41 +
    name: *[u8],
42 +
    /// Compiler metadata identity in hexadecimal.
43 +
    declarations: *[u8],
44 +
}
45 +
46 +
/// Complete artifact descriptor.
47 +
export record Package: Copy {
48 +
    /// Descriptor format version.
49 +
    version: u32,
50 +
    /// Root package name.
51 +
    name: *[u8],
52 +
    /// Exported contract identity in hexadecimal.
53 +
    exports: *[u8],
54 +
    /// Compilation request identity in hexadecimal.
55 +
    inputs: *[u8],
56 +
    /// Executable image identity in hexadecimal.
57 +
    image: *[u8],
58 +
    /// Interfaces in registration order.
59 +
    modules: *[Module],
60 +
    /// Native-link inputs and embedded files.
61 +
    files: *[File],
62 +
    /// Required provider declarations.
63 +
    dependencies: *[Dependency],
64 +
}
65 +
66 +
/// Exact selection of one package.
67 +
export record LockedPackage: Copy {
68 +
    /// Package name.
69 +
    name: *[u8],
70 +
    /// Executable image identity in hexadecimal.
71 +
    image: *[u8],
72 +
    /// Compiler metadata identity in hexadecimal.
73 +
    metadata: *[u8],
74 +
}
75 +
76 +
/// Exact selections for an exported package graph.
77 +
export record Lock: Copy {
78 +
    /// Lockfile format version.
79 +
    version: u32,
80 +
    /// Selected packages in compilation order.
81 +
    packages: *[LockedPackage],
82 +
}
compiler/radiance/artifact/value.rad added +264 -0
1 +
//! Typed constant values read from artifact documents.
2 +
3 +
use std::lang::alloc;
4 +
use std::lang::ast;
5 +
use std::lang::module;
6 +
use std::lang::parser;
7 +
use std::lang::resolver;
8 +
use std::lang::scanner;
9 +
use std::lang::strings;
10 +
use std::mem;
11 +
use std::mem::heap;
12 +
use std::sys;
13 +
14 +
/// Constant expression with its schema type.
15 +
export record Value: Copy {
16 +
    /// Expression after constant aliases and projections are followed.
17 +
    node: *ast::Node,
18 +
    /// Semantic type required by the schema.
19 +
    type: resolver::Type,
20 +
}
21 +
22 +
/// Ordered elements of a constant slice or array.
23 +
export record Elements: Copy {
24 +
    /// Semantic element type.
25 +
    type: resolver::Type,
26 +
    /// Array initializer holding the elements.
27 +
    array: resolver::ConstArray,
28 +
    /// Number of elements.
29 +
    len: u32,
30 +
}
31 +
32 +
/// Resolved artifact document and its value checked against the schema.
33 +
export record Image {
34 +
    /// Semantic information about the resolved modules.
35 +
    resolver: resolver::Resolver,
36 +
    /// Document value checked against the schema.
37 +
    root: Value,
38 +
    /// Storage for byte strings written as byte arrays.
39 +
    arena: *heap::Heap,
40 +
}
41 +
42 +
/// Parse with `parse` and preserve allocation errors as storage failures.
43 +
fn parse(
44 +
    syntax: &mut parser::Parser,
45 +
    path: *[u8],
46 +
    text: *[u8],
47 +
    parse: fn(&mut parser::Parser, scanner::SourceLoc, *[u8]) -> *ast::Node
48 +
        throws (parser::ParseError)
49 +
) -> *ast::Node throws (sys::Error) {
50 +
    return try parse(syntax, scanner::SourceLoc::File(path), text) catch error {
51 +
        if error == parser::ParseError::AllocationFailed {
52 +
            throw sys::Error::TooLarge;
53 +
        }
54 +
        throw sys::Error::Invalid;
55 +
    };
56 +
}
57 +
58 +
/// Build the document module around its value `value`: an import of every
59 +
/// `schema` declaration and the constant `VALUE` of the type named `expected`.
60 +
fn document(syntax: &mut parser::Parser, expected: *[u8], value: *ast::Node) -> *ast::Node
61 +
    throws (alloc::AllocError)
62 +
{
63 +
    let nodes = &mut syntax.arena;
64 +
    let schema = try ast::synthNode(nodes, ast::NodeValue::Ident(
65 +
        strings::intern(&mut syntax.pool, "schema")
66 +
    ));
67 +
    let import = try ast::synthNode(nodes, ast::NodeValue::Use(ast::Use {
68 +
        path: schema, wildcard: true, attrs: nil
69 +
    }));
70 +
    let name = try ast::synthNode(nodes, ast::NodeValue::Ident(
71 +
        strings::intern(&mut syntax.pool, expected)
72 +
    ));
73 +
    let type = try ast::synthNode(nodes, ast::NodeValue::TypeSig(ast::TypeSig::Nominal {
74 +
        path: name, regions: &[]
75 +
    }));
76 +
    let ident = try ast::synthNode(nodes, ast::NodeValue::Ident(
77 +
        strings::intern(&mut syntax.pool, "VALUE")
78 +
    ));
79 +
    let decl = try ast::synthNode(nodes, ast::NodeValue::ConstDecl(ast::ConstDecl {
80 +
        ident, type, value, attrs: nil
81 +
    }));
82 +
    let mut statements = try ast::nodeSlice(nodes, 2);
83 +
    try statements.append(import, nodes.heap);
84 +
    try statements.append(decl, nodes.heap);
85 +
    return try ast::synthNode(nodes, ast::NodeValue::Module(ast::Module { statements }));
86 +
}
87 +
88 +
/// Resolve the value in `text`, typed as the declaration `expected` of the
89 +
/// `schema` module source, and read it from the resolved tree. The text is one
90 +
/// expression, which names `schema` declarations directly. All returned storage
91 +
/// belongs to `arena`.
92 +
export fn read(
93 +
    schema: *[u8], text: *[u8], path: *[u8], expected: *[u8], arena: *heap::Heap
94 +
) -> Image throws (sys::Error) {
95 +
    let mut names: *mut [*[u8]] = &mut [];
96 +
    try names.resize(strings::TABLE_SIZE, "", arena) catch {
97 +
        throw sys::Error::TooLarge;
98 +
    };
99 +
    let mut syntax = parser::newParser(
100 +
        ast::NodeArena { heap: arena, nextId: 0 }, strings::freshPool(names.take())
101 +
    );
102 +
    let mut entries: *mut [module::ModuleEntry] = &mut [];
103 +
    try entries.reserve(2, arena) catch {
104 +
        throw sys::Error::TooLarge;
105 +
    };
106 +
    // Module registration initializes each reserved entry before it is read.
107 +
    unsafe {
108 +
        set entries.len = 2;
109 +
    }
110 +
    let mut graph = module::moduleGraph(entries.take());
111 +
    let schemaId = try module::registerRootWithName(
112 +
        &mut graph, &mut syntax.pool, 0, "schema", "schema.rad"
113 +
    ) catch {
114 +
        throw sys::Error::Invalid;
115 +
    };
116 +
    let documentId = try module::registerRootWithName(
117 +
        &mut graph, &mut syntax.pool, 1, "document", path
118 +
    ) catch {
119 +
        throw sys::Error::Invalid;
120 +
    };
121 +
    let schemaRoot = try parse(&mut syntax, "schema.rad", schema, parser::parseModule);
122 +
    let value = try parse(&mut syntax, path, text, parser::parseValue);
123 +
    let documentRoot = try document(&mut syntax, expected, value) catch {
124 +
        throw sys::Error::TooLarge;
125 +
    };
126 +
    let sources = [schema, text];
127 +
    let roots = [schemaRoot, documentRoot];
128 +
    for id, i in [schemaId, documentId] {
129 +
        set graph.entries[id as u32].ast = roots[i];
130 +
        set graph.entries[id as u32].source = sources[i];
131 +
        set graph.entries[id as u32].state = module::ModuleState::Parsed;
132 +
    }
133 +
    let modules = module::freeze(graph);
134 +
    let mut packages: *mut [resolver::Pkg] = &mut [];
135 +
    for entry in modules.entries {
136 +
        let root = entry.ast else panic "read: missing module AST";
137 +
        let owner = module::get(modules, entry.id) else panic "read: missing module";
138 +
        try packages.append(resolver::Pkg { rootEntry: owner, rootAst: root }, arena) catch {
139 +
            throw sys::Error::TooLarge;
140 +
        };
141 +
    }
142 +
    let nodeData = try resolver::nodeDataStorage(arena, syntax.arena.nextId) catch {
143 +
        throw sys::Error::TooLarge;
144 +
    };
145 +
    let mut errors: *mut [resolver::Error] = &mut [];
146 +
    try errors.resize(
147 +
        resolver::MAX_ERRORS,
148 +
        resolver::Error {
149 +
            kind: resolver::ErrorKind::DuplicateBinding(""), node: nil, moduleId: 0
150 +
        },
151 +
        arena
152 +
    ) catch {
153 +
        throw sys::Error::TooLarge;
154 +
    };
155 +
    let mut res = resolver::resolver(
156 +
        resolver::ResolverStorage { arena, nodeData, errors: errors.take() },
157 +
        resolver::Config { buildTest: false }
158 +
    );
159 +
    let diagnostics = try resolver::resolve(&mut res, modules, &packages[..]) catch {
160 +
        let diagnostics = resolver::diagnostics(&mut res);
161 +
        resolver::printer::printDiagnostics(&diagnostics, &res);
162 +
        throw sys::Error::Invalid;
163 +
    };
164 +
    if not resolver::success(&diagnostics) {
165 +
        resolver::printer::printDiagnostics(&diagnostics, &res);
166 +
        throw sys::Error::Invalid;
167 +
    }
168 +
    let case ast::NodeValue::Module(block) = documentRoot.value else panic "read: expected module";
169 +
    let declaration = block.statements[1];
170 +
    let type = resolver::typeFor(&res, declaration) else panic "read: missing value type";
171 +
    let node = res.constantNode(value) else throw sys::Error::Invalid;
172 +
    return Image { resolver: res, root: Value { node, type }, arena };
173 +
}
174 +
175 +
/// Select a record field. Record literals list fields in declaration order.
176 +
fn (image: &Image) field(value: Value, name: *[u8]) -> Value throws (sys::Error) {
177 +
    let info = resolver::getRecord(&image.resolver, value.type) else {
178 +
        throw sys::Error::Invalid;
179 +
    };
180 +
    for field, i in info.fields {
181 +
        if let label = field.name; mem::eq(label, name) {
182 +
            let node = image.resolver.constantField(value.node, i) else {
183 +
                throw sys::Error::Invalid;
184 +
            };
185 +
            return Value { node, type: field.fieldType };
186 +
        }
187 +
    }
188 +
    throw sys::Error::Invalid;
189 +
}
190 +
191 +
/// Read the elements of a constant slice or array value.
192 +
fn (image: &Image) elements(value: Value) -> Elements throws (sys::Error) {
193 +
    let mut type = resolver::Type::Unknown;
194 +
    match value.type {
195 +
        case resolver::Type::Slice { item, .. } => set type = *item,
196 +
        case resolver::Type::Array(info)        => set type = *info.item,
197 +
        else                                    => throw sys::Error::Invalid,
198 +
    }
199 +
    let array = image.resolver.constantArray(value.node) else throw sys::Error::Invalid;
200 +
    return Elements { type, array, len: array.len };
201 +
}
202 +
203 +
/// Read a slice field.
204 +
export fn (image: &Image) items(value: Value, name: *[u8]) -> Elements throws (sys::Error) {
205 +
    return try image.elements(try image.field(value, name));
206 +
}
207 +
208 +
/// Select one element from a constant slice.
209 +
export fn (image: &Image) at(elements: &Elements, index: u32) -> Value throws (sys::Error) {
210 +
    assert index < elements.len;
211 +
    let node = image.resolver.constantElement(elements.array, index) else {
212 +
        throw sys::Error::Invalid;
213 +
    };
214 +
    return Value { node, type: elements.type };
215 +
}
216 +
217 +
/// Read an unsigned integer from a constant expression.
218 +
fn (image: &Image) unsigned(value: Value) -> u32 throws (sys::Error) {
219 +
    let case resolver::ConstValue::Int(number) = resolver::constValueEntry(
220 +
        &image.resolver, value.node
221 +
    ) else throw sys::Error::Invalid;
222 +
    if number.negative or number.magnitude > mem::U32_MAX as u64 {
223 +
        throw sys::Error::Invalid;
224 +
    }
225 +
    return number.magnitude as u32;
226 +
}
227 +
228 +
/// Read a byte-slice or byte-array field from a string or from byte constants.
229 +
export fn (image: &Image) bytes(value: Value, name: *[u8]) -> *[u8] throws (sys::Error) {
230 +
    let field = try image.field(value, name);
231 +
    if let case resolver::ConstValue::String(text) = resolver::constValueEntry(
232 +
        &image.resolver, field.node
233 +
    ) {
234 +
        return text;
235 +
    }
236 +
    let elements = try image.elements(field);
237 +
    if elements.type <> resolver::Type::U8 {
238 +
        throw sys::Error::Invalid;
239 +
    }
240 +
    let mut bytes: *mut [u8] = &mut [];
241 +
    for i in 0 .. elements.len {
242 +
        let byte = try image.unsigned(try image.at(&elements, i));
243 +
        try bytes.append(byte as u8, image.arena) catch {
244 +
            throw sys::Error::TooLarge;
245 +
        };
246 +
    }
247 +
    return &bytes[..];
248 +
}
249 +
250 +
/// Read an unsigned integer field.
251 +
export fn (image: &Image) number(value: Value, name: *[u8]) -> u32 throws (sys::Error) {
252 +
    return try image.unsigned(try image.field(value, name));
253 +
}
254 +
255 +
/// Read the index of a union variant field.
256 +
export fn (image: &Image) variant(value: Value, name: *[u8]) -> u32 throws (sys::Error) {
257 +
    let field = try image.field(value, name);
258 +
    let symbol = resolver::symbolFor(&image.resolver, field.node) else {
259 +
        throw sys::Error::Invalid;
260 +
    };
261 +
    let case resolver::SymbolData::Variant { index, .. } = image.resolver.symbols[*symbol].data
262 +
        else throw sys::Error::Invalid;
263 +
    return index;
264 +
}
compiler/radiance/build.rad +16 -14
208 208
}
209 209
210 210
/// Capture source snapshots and load compiled package metadata.
211 211
fn snapshot(
212 212
    options: super::PackageInput,
213 -
    syntax: &mut parser::Parser,
213 +
    scratch: *heap::Heap,
214 214
    arena: &heap::Heap,
215 215
    artifacts: &heap::Heap
216 216
) -> Input
217 217
    throws (sys::Error)
218 218
{
219 219
    if let root = options.artifactRoot {
220 220
        let compiled = try artifact::read(
221 -
            root, options.name, artifact::Validation::Full, syntax, artifacts
221 +
            root, options.name, artifact::Validation::Full, scratch, artifacts
222 222
        );
223 223
        let mut dependencies: *mut [*[u8]] = &mut [];
224 224
        for dependency in compiled.dependencies {
225 225
            try dependencies.append(dependency.name, arena) catch {
226 226
                throw sys::Error::TooLarge;
351 351
    }
352 352
    return nil;
353 353
}
354 354
355 355
/// Resolve and sort the graph, including source-free transitive artifact providers.
356 -
fn inputs(ctx: &mut super::CompileContext, arena: &heap::Heap, artifacts: &heap::Heap) -> *[Input]
357 -
    throws (sys::Error)
358 -
{
356 +
fn inputs(
357 +
    ctx: &mut super::CompileContext,
358 +
    scratch: *heap::Heap,
359 +
    arena: &heap::Heap,
360 +
    artifacts: &heap::Heap
361 +
) -> *[Input] throws (sys::Error) {
359 362
    let mut selected: *mut [Input] = &mut [];
360 363
    for i in 0 .. ctx.packageCount {
361 364
        let checked = try dependencyNames(ctx.inputs[i].name, arena);
362 365
        if checked.len <> 1 or not mem::eq(checked[0], ctx.inputs[i].name) {
363 366
            throw sys::Error::Invalid;
366 369
            if mem::eq(ctx.inputs[j].name, ctx.inputs[i].name) {
367 370
                throw sys::Error::Invalid;
368 371
            }
369 372
        }
370 373
        try selected.append(
371 -
            try snapshot(ctx.inputs[i], &mut ctx.parser, arena, artifacts), arena
374 +
            try snapshot(ctx.inputs[i], scratch, arena, artifacts), arena
372 375
        ) catch {
373 376
            throw sys::Error::TooLarge;
374 377
        };
375 378
    }
376 379
    let mut i: u32 = 0;
389 392
            if selected.len >= package::MAX_PACKAGES {
390 393
                throw sys::Error::TooLarge;
391 394
            }
392 395
            let mut options = super::packageInput(name);
393 396
            set options.artifactRoot = root;
394 -
            let provider = try snapshot(options, &mut ctx.parser, arena, artifacts);
397 +
            let provider = try snapshot(options, scratch, arena, artifacts);
395 398
            try selected.append(provider, arena) catch {
396 399
                throw sys::Error::TooLarge;
397 400
            };
398 401
        }
399 402
        set i += 1;
599 602
    work: &mut Workspace,
600 603
    sourceArena: &heap::Heap,
601 604
    driverArena: &heap::Heap,
602 605
    compiler: binary::Id
603 606
) throws (super::Error) {
604 -
    set ctx.parser.arena.heap = work.artifacts;
605 -
    let selected = try inputs(ctx, sourceArena, work.artifacts) catch {
607 +
    let selected = try inputs(ctx, work.main, sourceArena, work.artifacts) catch {
606 608
        throw super::error(&["cannot read package inputs or dependency manifests"]);
607 609
    };
608 610
    let entryIndex = ctx.entryPkgIdx else panic "run: missing entry package";
609 611
    let entryName = ctx.inputs[entryIndex].name;
610 612
    let built = try buildPackages(
655 657
        let mut built: artifact::Package = undefined;
656 658
        let mut fresh = false;
657 659
        match input.contents {
658 660
            case Contents::Compiled(package) => set built = package,
659 661
            case Contents::Source(source) => {
662 +
                resetFrontend(ctx, graph, work.main);
660 663
                let request: ?binary::Id = key(
661 664
                    ctx,
662 665
                    input.options.name,
663 666
                    &source,
664 667
                    &compiled[..],
670 673
                    else nil;
671 674
                let mut cached: ?artifact::Package = nil;
672 675
                if let root = ctx.cacheDirectory {
673 676
                    let cacheKey = request else panic "buildPackages: missing cache key";
674 677
                    set cached = try cache::lookup(
675 -
                        root, input.options.name, cacheKey, &mut ctx.parser, work.artifacts
678 +
                        root, input.options.name, cacheKey, work.main, work.artifacts
676 679
                    ) catch {
677 680
                        throw super::error(&["cannot read package cache"]);
678 681
                    };
679 682
                }
680 683
                if let package = cached {
687 690
                        let provider = try readExports(&compiled[i], work);
688 691
                        try published.append(provider, work.emitter) catch {
689 692
                            throw super::Error::Other;
690 693
                        };
691 694
                    }
692 -
                    resetFrontend(ctx, graph, work.main);
693 695
                    try loadInterfaces(ctx, graph, selected, &compiled[..], driverArena);
694 696
                    let embeds = try embedded(source.files, driverArena);
695 697
                    try load(
696 698
                        ctx, graph, index, source.modules, module::Role::Source, providerIds, embeds
697 699
                    );
743 745
                        },
744 746
                        work.emitter
745 747
                    ) catch {
746 748
                        throw super::Error::Other;
747 749
                    };
748 -
                    set ctx.parser.arena.heap = work.artifacts;
750 +
                    resetFrontend(ctx, graph, work.main);
749 751
                    if let root = ctx.cacheDirectory {
750 752
                        // Function storage has no live IL after its sink consumed each function.
751 -
                        try cache::publish(root, &built, &mut ctx.parser, work.functions) catch {
753 +
                        try cache::publish(root, &built, work.main, work.functions) catch {
752 754
                            throw super::error(&["cannot publish package cache", built.name]);
753 755
                        };
754 756
                        unsafe {
755 757
                            heap::reset(work.functions);
756 758
                        }
1266 1268
            throw super::error(&["package encoding storage exhausted", pkg.name]);
1267 1269
        };
1268 1270
        let image: *[u8] = &finalImage[..];
1269 1271
        let identity = linkage::imageId(image);
1270 1272
        let metadata = try artifact::metadata(
1271 -
            &result, inputs, identity, image.len, head.take(), work.functions
1273 +
            &result, inputs, identity, head.take(), work.functions
1272 1274
        ) catch {
1273 1275
            throw super::error(&["package encoding storage exhausted", pkg.name]);
1274 1276
        };
1275 1277
        let text = try keep(work.artifacts, metadata) catch {
1276 1278
            throw super::error(&["package encoding storage exhausted", pkg.name]);
compiler/radiance/cache.rad +6 -7
2 2
3 3
use std::fmt;
4 4
use std::fs;
5 5
use std::lang::alloc;
6 6
use std::lang::il::binary;
7 -
use std::lang::parser;
8 7
use std::mem;
9 8
use std::mem::heap;
10 9
use std::sys;
11 10
use super::artifact;
12 11
27 26
/// Missing files and invalid metadata are misses; unrelated I/O errors propagate.
28 27
export fn lookup(
29 28
    root: *[u8],
30 29
    name: *[u8],
31 30
    key: binary::Id,
32 -
    syntax: &mut parser::Parser,
31 +
    scratch: *heap::Heap,
33 32
    arena: &heap::Heap
34 33
) -> ?artifact::Package throws (sys::Error) {
35 34
    let saved = heap::mark(arena);
36 35
    let path = try entry(root, key, arena);
37 36
    let result = try artifact::read(
38 -
        path, name, artifact::Validation::Trusted, syntax, arena
37 +
        path, name, artifact::Validation::Trusted, scratch, arena
39 38
    ) catch error {
40 39
        // Failed reads publish no pointers into their temporary allocations.
41 40
        unsafe {
42 41
            heap::rewind(arena, saved);
43 42
        }
79 78
    throw sys::Error::Limit;
80 79
}
81 80
82 81
/// Write a private complete set, then make it visible with one directory rename.
83 82
export fn publish(
84 -
    root: *[u8], package: &artifact::Package, syntax: &mut parser::Parser, arena: &heap::Heap
83 +
    root: *[u8], package: &artifact::Package, scratch: *heap::Heap, arena: &heap::Heap
85 84
)
86 85
    throws (sys::Error)
87 86
{
88 87
    let publication = package.publication else panic "publish: missing publication";
89 88
    let path = try entry(root, publication.inputs, arena);
91 90
    let stage = try temporary(path, arena);
92 91
    try artifact::write(package, stage, arena) catch error {
93 92
        try fs::removeTree(stage, arena) catch {};
94 93
        throw error;
95 94
    };
96 -
    try install(root, path, stage, package, syntax, arena) catch error {
95 +
    try install(root, path, stage, package, scratch, arena) catch error {
97 96
        try fs::removeTree(stage, arena) catch {};
98 97
        throw error;
99 98
    };
100 99
}
101 100
103 102
fn install(
104 103
    root: *[u8],
105 104
    path: *[u8],
106 105
    stage: *[u8],
107 106
    package: &artifact::Package,
108 -
    syntax: &mut parser::Parser,
107 +
    scratch: *heap::Heap,
109 108
    arena: &heap::Heap
110 109
) throws (sys::Error) {
111 110
    let publication = package.publication else panic "install: missing publication";
112 111
    for _ in 0 .. TEMPORARY_SLOTS {
113 112
        try fs::rename(stage, path) catch error {
119 118
            }
120 119
            if try fs::stat(path) == nil {
121 120
                continue;
122 121
            }
123 122
            let existing = try lookup(
124 -
                root, package.name, publication.inputs, syntax, arena
123 +
                root, package.name, publication.inputs, scratch, arena
125 124
            );
126 125
            if existing <> nil {
127 126
                try fs::removeTree(stage, arena);
128 127
                return;
129 128
            }
lib/std/hash/blake3.rad +11 -0
1 1
//! Streaming unkeyed BLAKE3 with 32-byte digests.
2 2
3 3
@test export mod tests;
4 4
5 5
use std::bits;
6 +
use std::fmt;
6 7
use std::mem;
7 8
8 9
/// Number of bytes in one BLAKE3 compression block.
9 10
constant BLOCK_BYTES: u32 = 64;
10 11
/// Number of 32-bit words in one BLAKE3 compression block.
239 240
export fn digest(bytes: &[u8]) -> Digest {
240 241
    let mut state = new();
241 242
    update(&mut state, bytes);
242 243
    return finish(state);
243 244
}
245 +
246 +
/// Parse a digest from exactly 64 hexadecimal digits, in either letter case.
247 +
export fn parse(text: &[u8]) -> Digest throws (fmt::ParseError) {
248 +
    let mut result = Digest { bytes: [0; DIGEST_BYTES] };
249 +
    if text.len <> result.bytes.len * 2 {
250 +
        throw fmt::ParseError::Invalid;
251 +
    }
252 +
    try fmt::parseHex(text, &mut result.bytes[..]);
253 +
    return result;
254 +
}
lib/std/hash/blake3/tests.rad +18 -0
262 262
        for i in 0 .. 8 {
263 263
            assert mem::load32Le(&actual.bytes[..], i * 4) == (state[i] ^ state[i + 8]);
264 264
        }
265 265
    }
266 266
}
267 +
268 +
/// A digest parses from its 64 hexadecimal digits and rejects other text.
269 +
@test fn parseDigest() throws (testing::TestError) {
270 +
    let text = "AF1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262";
271 +
    let parsed = try blake3::parse(text) catch {
272 +
        throw testing::TestError::Failed;
273 +
    };
274 +
    assert parsed == blake3::digest("");
275 +
    let invalid = [&text[.. 62], &text[.. 63], "", "g"];
276 +
    for candidate in invalid {
277 +
        let result = try? blake3::parse(candidate);
278 +
        assert result == nil;
279 +
    }
280 +
    let mut digit: [u8; 64] = [0; 64];
281 +
    try! mem::copy(&mut digit[..], text);
282 +
    set digit[63] = 'g';
283 +
    assert try? blake3::parse(&digit[..]) == nil;
284 +
}
lib/std/lang/resolver.rad +54 -16
36 36
export constant ANALYZE_EXPR_FN_NAME: *[u8] = "__expr__";
37 37
/// Synthetic function name used when wrapping a block for analysis.
38 38
export constant ANALYZE_BLOCK_FN_NAME: *[u8] = "__block__";
39 39
40 40
/// Maximum number of symbols stored within a module scope.
41 -
export constant MAX_MODULE_SYMBOLS: u32 = 512;
41 +
export constant MAX_MODULE_SYMBOLS: u32 = 1024;
42 42
43 43
/// Initial capacity of `Resolver.symbols`. The slice grows past it when a
44 44
/// package has more symbols, but each growth copies every symbol, so the
45 45
/// capacity covers the standard library and kernel test declarations. A growth copy
46 46
/// keeps the old table in the arena, so a smaller capacity costs more memory than this one.
1757 1757
fn setForLoopInfo(self: &mut Resolver, node: *ast::Node, info: ForLoopInfo) {
1758 1758
    set self.nodeData.getMut(node.id).extra =
1759 1759
        NodeExtra::ForLoop(info);
1760 1760
}
1761 1761
1762 +
/// Array initializer of a constant array or slice.
1763 +
export record ConstArray: Copy {
1764 +
    /// Array literal or repeat literal holding the elements.
1765 +
    node: *ast::Node,
1766 +
    /// Number of elements.
1767 +
    len: u32,
1768 +
}
1769 +
1762 1770
/// Find the constant initializer selected by a value, field, or array element.
1763 1771
/// Selections follow immutable record and fixed-size array initializers.
1764 1772
export fn (self: &Resolver) constantNode(node: *ast::Node) -> ?*ast::Node {
1765 1773
    match node.value {
1766 1774
        case ast::NodeValue::Ident(_), ast::NodeValue::ScopeAccess(_) => {
1773 1781
            return node if isConstExpr(self, node) else nil;
1774 1782
        }
1775 1783
        case ast::NodeValue::FieldAccess(access) => {
1776 1784
            let parent = self.constantNode(access.parent) else return nil;
1777 1785
            let index = recordFieldIndexFor(self, access.child) else return nil;
1778 -
            let case ast::NodeValue::RecordLit(lit) = parent.value else return nil;
1779 -
            if index >= lit.fields.len {
1780 -
                return nil;
1781 -
            }
1782 -
            let case ast::NodeValue::RecordLitField(arg) = lit.fields[index].value else return nil;
1783 -
            return self.constantNode(arg.value);
1786 +
            return self.constantField(parent, index);
1784 1787
        }
1785 1788
        case ast::NodeValue::Subscript { container, index } => {
1789 +
            let case Type::Array(_) = typeFor(self, container) else return nil;
1786 1790
            let parent = self.constantNode(container) else return nil;
1787 -
            let case Type::Array(info) = typeFor(self, container) else return nil;
1791 +
            let array = self.constantArray(parent) else return nil;
1788 1792
            let case ConstValue::Int(value) = constValueEntry(self, index) else return nil;
1789 -
            if value.negative or value.magnitude >= info.length as u64 {
1793 +
            if value.negative or value.magnitude >= array.len as u64 {
1790 1794
                return nil;
1791 1795
            }
1792 -
            match parent.value {
1793 -
                case ast::NodeValue::ArrayLit(items) =>
1794 -
                    return self.constantNode(items[value.magnitude as u32]),
1795 -
                case ast::NodeValue::ArrayRepeatLit(repeat) =>
1796 -
                    return self.constantNode(repeat.item),
1797 -
                else => return nil,
1798 -
            }
1796 +
            return self.constantElement(array, value.magnitude as u32);
1799 1797
        }
1800 1798
        else => return node if isConstExpr(self, node) else nil,
1801 1799
    }
1802 1800
}
1803 1801
1802 +
/// Select field `index` of a record initializer that [`constantNode`] returned.
1803 +
export fn (self: &Resolver) constantField(literal: *ast::Node, index: u32) -> ?*ast::Node {
1804 +
    let case ast::NodeValue::RecordLit(lit) = literal.value else return nil;
1805 +
    if index >= lit.fields.len {
1806 +
        return nil;
1807 +
    }
1808 +
    let case ast::NodeValue::RecordLitField(arg) = lit.fields[index].value else return nil;
1809 +
    return self.constantNode(arg.value);
1810 +
}
1811 +
1812 +
/// Find the array initializer of an array or slice initializer that
1813 +
/// [`constantNode`] returned.
1814 +
export fn (self: &Resolver) constantArray(node: *ast::Node) -> ?ConstArray {
1815 +
    let mut array = node;
1816 +
    if let case ast::NodeValue::AddressOf(address) = node.value {
1817 +
        let target = self.constantNode(address.target) else return nil;
1818 +
        set array = target;
1819 +
    }
1820 +
    match array.value {
1821 +
        case ast::NodeValue::ArrayLit(items) => return ConstArray { node: array, len: items.len },
1822 +
        case ast::NodeValue::ArrayRepeatLit(_) => {
1823 +
            let case Type::Array(info) = typeFor(self, array) else return nil;
1824 +
            return ConstArray { node: array, len: info.length };
1825 +
        }
1826 +
        else => return nil,
1827 +
    }
1828 +
}
1829 +
1830 +
/// Select element `index` of a constant array initializer.
1831 +
export fn (self: &Resolver) constantElement(array: ConstArray, index: u32) -> ?*ast::Node {
1832 +
    if index >= array.len {
1833 +
        return nil;
1834 +
    }
1835 +
    match array.node.value {
1836 +
        case ast::NodeValue::ArrayLit(items)        => return self.constantNode(items[index]),
1837 +
        case ast::NodeValue::ArrayRepeatLit(repeat) => return self.constantNode(repeat.item),
1838 +
        else                                        => return nil,
1839 +
    }
1840 +
}
1841 +
1804 1842
/// Retrieve the constant value associated with a node, if any.
1805 1843
export fn constValueEntry(self: &Resolver, node: *ast::Node) -> ?ConstValue {
1806 1844
    let value = self.nodeData.get(node.id).constValue;
1807 1845
    if value <> nil {
1808 1846
        return value;
test/Makefile +13 -2
62 62
	@$(call integration,host)
63 63
64 64
package-test: $(INTEGRATION)
65 65
	@$(call integration,packages)
66 66
67 -
module-test: $(RAD_BIN) test/compiler/discovery.rv64 test/compiler/metadata.rv64
67 +
module-test: $(RAD_BIN) test/compiler/discovery.rv64 test/compiler/metadata.rv64 \
68 +
    test/compiler/values.rv64
68 69
	@$(HOSTED) test/compiler/discovery.rv64
69 70
	@$(HOSTED) test/compiler/metadata.rv64
71 +
	@$(HOSTED) test/compiler/values.rv64
70 72
71 73
# Standard Library Tests
72 74
73 75
STD_LIB_TEST := lib/std.test.rv64
74 76
133 135
test/tests/%.rv64: test/tests/%.ras test/runner.rv64 test/Makefile
134 136
	@$(HOSTED) test/runner.rv64 assemble $< $@
135 137
136 138
clean-bin-test:
137 139
	@rm -f $(TEST_TOOLS) $(INTEGRATION) $(BIN_TEST_BIN) \
138 -
	    test/compiler/discovery.rv64 test/compiler/metadata.rv64 \
140 +
	    test/compiler/discovery.rv64 test/compiler/metadata.rv64 test/compiler/values.rv64 \
139 141
	    $(wildcard test/tests/*.rv64.debug test/tests/*.rv64.s) \
140 142
	    $(TEST_TOOLS:.rv64=.rv64.debug) $(TEST_TOOLS:.rv64=.rv64.s) \
141 143
	    $(TEST_TOOLS:.rv64=.rv64.o)
142 144
143 145
# Integer trap contexts and nested machine interrupts.
228 230
test/compiler/metadata.rv64: test/compiler/metadata.rad compiler/radiance/metadata.rad \
229 231
    test/compiler/metachecks.manifest $(STD_LIB) $(STD_MANIFEST) test/std.manifest $(RAD_BIN) test/Makefile
230 232
	@$(RADIANCE) $(STD) -pkg metadata -manifest test/std.manifest -mod compiler/radiance/metadata.rad \
231 233
	    -pkg metachecks -mod test/compiler/metadata.rad -entry metachecks -o $@
232 234
235 +
VALUE_FIXTURES := $(wildcard test/compiler/values/*)
236 +
237 +
# Read typed artifact documents through the production reader module.
238 +
test/compiler/values.rv64: $(VALUE_FIXTURES) test/compiler/values.rad compiler/radiance/artifact/value.rad \
239 +
    test/compiler/valuechecks.manifest $(STD_LIB) $(STD_MANIFEST) test/std.manifest $(RAD_BIN) test/Makefile
240 +
	@$(RADIANCE) $(STD) -pkg value -manifest test/std.manifest -mod compiler/radiance/artifact/value.rad \
241 +
	    -pkg valuechecks -mod test/compiler/values.rad \
242 +
	    $(patsubst %,-embed %,$(VALUE_FIXTURES)) -entry valuechecks -o $@
243 +
233 244
.PHONY: test $(TESTS) $(SMP_TESTS) $(CYCLES_TESTS) clean-std-test clean-bin-test
test/compiler/valuechecks.manifest added +2 -0
1 +
std
2 +
value
test/compiler/values.rad added +55 -0
1 +
//! Artifact document reader checks.
2 +
3 +
use std::mem;
4 +
use std::mem::heap;
5 +
use value;
6 +
7 +
/// Declarations of the test documents.
8 +
constant SCHEMA: *[u8] = @embed("values/schema.rad");
9 +
10 +
/// Documents that type-check as `Root` with count 3, name `ab`, and items named `a`.
11 +
constant ACCEPTED: [*[u8]; 4] = [
12 +
    @embed("values/typed.metadata"),
13 +
    @embed("values/inferred.metadata"),
14 +
    @embed("values/byte_arrays.metadata"),
15 +
    @embed("values/repeat.metadata"),
16 +
];
17 +
18 +
/// Documents that do not type-check as `Root`, or hold more than one expression.
19 +
constant REJECTED: [*[u8]; 8] = [
20 +
    @embed("values/string_count.metadata"),
21 +
    @embed("values/negative_count.metadata"),
22 +
    @embed("values/overflow_count.metadata"),
23 +
    @embed("values/duplicate_field.metadata"),
24 +
    @embed("values/extra_field.metadata"),
25 +
    @embed("values/wrong_record.metadata"),
26 +
    @embed("values/scalar.metadata"),
27 +
    @embed("values/trailing_semicolon.metadata"),
28 +
];
29 +
30 +
/// The reader follows byte arrays and repeat literals to typed values, and rejects
31 +
/// documents that do not type-check against the schema.
32 +
@default unsafe fn main() -> u32 {
33 +
    static storage: [u8; 8388608] = [0; 8388608];
34 +
    let arena = heap::over(&mut storage[..]);
35 +
    for document, i in ACCEPTED {
36 +
        let mark = heap::mark(arena);
37 +
        let image = try! value::read(SCHEMA, document, "document.rad", "Root", arena);
38 +
        assert try! image.number(image.root, "count") == 3;
39 +
        assert mem::eq(try! image.bytes(image.root, "name"), "ab");
40 +
        let items = try! image.items(image.root, "items");
41 +
        assert items.len == (2 if i == 3 else 1);
42 +
        for j in 0 .. items.len {
43 +
            let item = try! image.at(&items, j);
44 +
            assert mem::eq(try! image.bytes(item, "name"), "a");
45 +
            assert try! image.variant(item, "role") == 1;
46 +
        }
47 +
        heap::rewind(arena, mark);
48 +
    }
49 +
    for document in REJECTED {
50 +
        let mark = heap::mark(arena);
51 +
        assert try? value::read(SCHEMA, document, "document.rad", "Root", arena) == nil;
52 +
        heap::rewind(arena, mark);
53 +
    }
54 +
    return 0;
55 +
}
test/compiler/values/byte_arrays.metadata added +1 -0
1 +
Root { count: 3, name: &[97, 98], items: &[Item { name: &[97], role: Role::Second }] }
test/compiler/values/duplicate_field.metadata added +1 -0
1 +
Root { count: 3, count: 3, name: "ab", items: &[] }
test/compiler/values/extra_field.metadata added +1 -0
1 +
Root { count: 3, name: "ab", items: &[], extra: 1 }
test/compiler/values/inferred.metadata added +1 -0
1 +
{ count: 4 - 2 + 1, name: "ab", items: &[Item { name: "a", role: Role::Second }] }
test/compiler/values/negative_count.metadata added +1 -0
1 +
Root { count: -1, name: "ab", items: &[] }
test/compiler/values/overflow_count.metadata added +1 -0
1 +
Root { count: 4294967296, name: "ab", items: &[] }
test/compiler/values/repeat.metadata added +1 -0
1 +
Root { count: 3, name: "ab", items: &[Item { name: "a", role: Role::Second }; 2] }
test/compiler/values/scalar.metadata added +1 -0
1 +
42
test/compiler/values/schema.rad added +5 -0
1 +
export union Role: Copy {
2 +
    First, Second,
3 +
}
4 +
export record Item: Copy { name: *[u8], role: Role }
5 +
export record Root: Copy { count: u32, name: *[u8], items: *[Item] }
test/compiler/values/string_count.metadata added +1 -0
1 +
Root { count: "3", name: "ab", items: &[] }
test/compiler/values/trailing_semicolon.metadata added +1 -0
1 +
Root { count: 3, name: "ab", items: &[] };
test/compiler/values/typed.metadata added +1 -0
1 +
Root { count: 3, name: "ab", items: &[Item { name: "a", role: Role::Second }] }
test/compiler/values/wrong_record.metadata added +1 -0
1 +
Item { name: "a", role: Role::Second }
test/integration/packages.rad +27 -33
276 276
    h.expect(
277 277
        "metadata uses hex escapes",
278 278
        h.join(&[root, "/paths.interface/package.metadata"]),
279 279
        harness::Expect::Contains("\\xff\\x1f\\n.ras")
280 280
    );
281 +
    let metadataPath = h.join(&[root, "/paths.interface/package.metadata"]);
282 +
    let original = try h.load(metadataPath);
283 +
    let role = mem::find(original, "FileRole::Assembly") else panic;
284 +
    for selected in ["FileRole::Startup", "FileRole::Debug"] {
285 +
        try fs::writeFileParts(metadataPath, &[
286 +
            &original[.. role], selected, &original[role + "FileRole::Assembly".len ..]
287 +
        ]);
288 +
        h.add(&["-no-cache", "-pkg", "paths", "-artifact", root]);
289 +
        h.compile("read typed metadata file roles", h.out(&["role-value.log"]));
290 +
    }
291 +
    try fs::writeFile(metadataPath, original);
281 292
    let image = h.path(&["paths.rv64"]);
282 293
    h.add(&["-no-cache", "-pkg", "paths", "-artifact", root, "-o", image]);
283 294
    if h.compile("load escaped assembly paths", h.out(&["paths-load.log"])) {
284 295
        execute(h, image);
285 296
    }
286 297
}
287 298
288 -
/// Check record metadata and reject malformed fields before loading an artifact.
299 +
/// Reject malformed metadata and content identities before loading an artifact.
300 +
/// The reader's typing rules are checked in `test/compiler/values.rad`.
289 301
fn metadata(h: &mut Harness, root: *[u8]) throws (sys::Error) {
290 302
    let path = h.join(&[root, "/dep.interface/package.metadata"]);
291 303
    let original = try h.load(path);
292 304
    for byte in original {
293 305
        assert byte == '\n' or (byte >= 32 and byte <= 126);
294 306
    }
295 307
    assert mem::startsWith(original, "Package {\n");
296 -
    let size = mem::find(original, "    size: ") else panic;
297 -
    let length = mem::find(&original[size ..], "\n") else panic;
298 -
    let end = size + length;
299 -
    let invalid = [
300 -
        "    size: 4294967296,", "    size: -1,", "    size: ,",
301 -
        "    size: \"bad\",", "    size: 1 + 2,", "    size: 1, size: 1,",
302 -
        "    extra: 1,",
303 -
    ];
304 -
    for field in invalid {
305 -
        try fs::writeFileParts(path, &[&original[.. size], field, &original[end ..]]);
306 -
        h.add(&["-no-cache", "-pkg", "dep", "-artifact", root]);
307 -
        let command = h.cc(h.take(), h.out(&["invalid-metadata.log"]));
308 -
        h.run("reject malformed artifact metadata", command, process::Outcome::Exited(1), &[]);
309 -
    }
308 +
    let version = mem::find(original, "    version: 1,") else panic;
309 +
    try fs::writeFileParts(path, &[
310 +
        &original[.. version], "    version: \"1\",", &original[version + "    version: 1,".len ..]
311 +
    ]);
312 +
    h.add(&["-no-cache", "-pkg", "dep", "-artifact", root]);
313 +
    let mistyped = h.cc(h.take(), h.out(&["invalid-metadata.log"]));
314 +
    h.run("reject mistyped metadata fields", mistyped, process::Outcome::Exited(1), &[
315 +
        harness::Expect::Contains("type mismatch")
316 +
    ]);
310 317
    try fs::writeFileParts(path, &[original, "extra field\n"]);
311 318
    h.add(&["-no-cache", "-pkg", "dep", "-artifact", root]);
312 319
    let command = h.cc(h.take(), h.out(&["trailing-metadata.log"]));
313 -
    h.run("reject trailing metadata fields", command, process::Outcome::Exited(1), &[]);
320 +
    h.run("reject trailing metadata text", command, process::Outcome::Exited(1), &[]);
314 321
    let image = mem::find(original, "image: \"") else panic;
315 322
    let digit = image + "image: \"".len;
316 -
    for hex in ["g", "-"] {
317 -
        try fs::writeFileParts(path, &[&original[.. digit], hex, &original[digit + 1 ..]]);
323 +
    // An identity has exactly 64 hexadecimal digits.
324 +
    for replaced in ["g", "-", ""] {
325 +
        try fs::writeFileParts(path, &[&original[.. digit], replaced, &original[digit + 1 ..]]);
318 326
        h.add(&["-no-cache", "-pkg", "dep", "-artifact", root]);
319 327
        let command = h.cc(h.take(), h.out(&["invalid-hex.log"]));
320 -
        h.run("reject invalid metadata hex", command, process::Outcome::Exited(1), &[]);
328 +
        h.run("reject invalid metadata identities", command, process::Outcome::Exited(1), &[]);
321 329
    }
322 -
    let header = "Package {\n".len;
323 -
    let first = mem::find(&original[header ..], "\n") else panic;
324 -
    let secondStart = header + first + 1;
325 -
    let second = mem::find(&original[secondStart ..], "\n") else panic;
326 -
    let secondEnd = secondStart + second + 1;
327 -
    try fs::writeFileParts(
328 -
        path,
329 -
        &[
330 -
            &original[.. header], &original[secondStart .. secondEnd],
331 -
            &original[header .. secondStart], &original[secondEnd ..],
332 -
        ]
333 -
    );
334 -
    h.add(&["-no-cache", "-pkg", "dep", "-artifact", root]);
335 -
    h.compile("load reordered metadata fields", h.out(&["reordered-metadata.log"]));
336 330
    try fs::writeFile(path, original);
337 331
}
338 332
339 333
/// Implementation edits preserve client images across a transitive dependency graph.
340 334
fn metadataReuse(h: &mut Harness) throws (sys::Error) {