lang: Add @embed builtin
cdebab968aadfbcdc806a6aca8991af380ea3e58400814a62fc83d22ecd871d2
Programs that need text or binary data built in have to carry it as an
escaped string literal, which cannot be formatted or edited as the file
it stands for.
Add `@embed("path")`, a constant `*[u8]` with the contents of a file the
package declares with `-embed PATH`. The path is relative to the package
root and must lie under it. Declared files are read with the other
package inputs before parsing, so they enter the cache key, and the
resolver finds them on the root module entry instead of reading the
file system.
Generated interfaces keep the call. Artifacts store the files at their
paths from the package root with the new Embed file role, and the
declarations hash covers them, so source-free clients resolve the same
bytes and rebuild when a file changes. Writing an artifact rejects a
path that another stored file or module interface uses, as reading one
already did.
Group builtin diagnostics in one error variant, since the error union
is at its variant limit. Reject a file declared twice with its own
message.
Keep the embed provider and client in source fixture files.
Assisted-by: Claude:opus-5.5
Assisted-by: Codex:gpt-6
Change-Id: I813c352a27cf0668250c3425a16d24aad48eb9f8
1 parent
679002bb
compiler/radiance.rad
+26 -1
| 44 | 44 | /// includes the standard library tests, reads 4.2 MB of source, so 6 MB leaves |
|
| 45 | 45 | /// room for it to grow. |
|
| 46 | 46 | constant MAX_SOURCES_SIZE: u32 = 6291456; |
|
| 47 | 47 | /// Maximum number of assembly source paths we can load per package. |
|
| 48 | 48 | constant MAX_ASM_MODULES: u32 = 64; |
|
| 49 | + | /// Maximum number of files a package declares for `@embed`. |
|
| 50 | + | constant MAX_EMBEDS: u32 = 64; |
|
| 49 | 51 | ||
| 50 | 52 | /// Package frontend storage and decoded native data (268 MB). |
|
| 51 | 53 | constant FRONTEND_ARENA_SIZE: u32 = 281018368; |
|
| 52 | 54 | /// Function IL arena size (16 MB). Every lowering pass resets it after each |
|
| 53 | 55 | /// function. It must fit the largest function of the standard library, |
| 90 | 92 | /// Default directory for package cache entries. |
|
| 91 | 93 | constant DEFAULT_CACHE_DIR: *[u8] = "cache"; |
|
| 92 | 94 | ||
| 93 | 95 | /// Usage string. |
|
| 94 | 96 | constant USAGE: *[u8] = |
|
| 95 | - | "usage: radiance -pkg <name> [-start <input.ras>] -mod <input>.. [-pkg <name> -mod <input>..] -entry <pkg> [-o <output> | -ril <directory>]\n-artifact <directory> selects a compiled package tree.\n-manifest <path> selects dependency names; the default is <package>.manifest beside the root module.\n-cache <directory> selects cache storage; -no-cache bypasses cache reads and writes.\n-mod accepts a source path or logical/path=source.rad relative to the package root.\n radiance -fmt [-fmt.wrap <columns>] <input.rad>\n radiance -fmt.check [-fmt.wrap <columns>] <input.rad>\n-fmt prints the source of a module in the canonical style, wrapped at 100 columns unless -fmt.wrap sets another width.\n-fmt.check prints nothing and fails if the source of a module is not in the canonical style.\n"; |
|
| 97 | + | "usage: radiance -pkg <name> [-start <input.ras>] -mod <input>.. [-pkg <name> -mod <input>..] -entry <pkg> [-o <output> | -ril <directory>]\n-artifact <directory> selects a compiled package tree.\n-manifest <path> selects dependency names; the default is <package>.manifest beside the root module.\n-cache <directory> selects cache storage; -no-cache bypasses cache reads and writes.\n-mod accepts a source path or logical/path=source.rad relative to the package root.\n-embed <path> declares a file under the package root for @embed.\n radiance -fmt [-fmt.wrap <columns>] <input.rad>\n radiance -fmt.check [-fmt.wrap <columns>] <input.rad>\n-fmt prints the source of a module in the canonical style, wrapped at 100 columns unless -fmt.wrap sets another width.\n-fmt.check prints nothing and fails if the source of a module is not in the canonical style.\n"; |
|
| 96 | 98 | ||
| 97 | 99 | /// Compiler error. |
|
| 98 | 100 | export union Error: Copy { |
|
| 99 | 101 | Other, |
|
| 100 | 102 | } |
| 137 | 139 | radPathCount: u32, |
|
| 138 | 140 | /// Assembly source paths for this package. |
|
| 139 | 141 | asmPaths: [*[u8]; MAX_ASM_MODULES], |
|
| 140 | 142 | /// Number of assembly source paths. |
|
| 141 | 143 | asmPathCount: u32, |
|
| 144 | + | /// Files under the package root that its modules can embed. |
|
| 145 | + | embedPaths: [*[u8]; MAX_EMBEDS], |
|
| 146 | + | /// Number of embedded file paths. |
|
| 147 | + | embedPathCount: u32, |
|
| 142 | 148 | } |
|
| 143 | 149 | ||
| 144 | 150 | /// Compilation context. |
|
| 145 | 151 | export record CompileContext { |
|
| 146 | 152 | /// Array of packages to compile. |
| 313 | 319 | startupPath: nil, |
|
| 314 | 320 | radPaths: [""; MAX_LOADED_MODULES], |
|
| 315 | 321 | radPathCount: 0, |
|
| 316 | 322 | asmPaths: [""; MAX_ASM_MODULES], |
|
| 317 | 323 | asmPathCount: 0, |
|
| 324 | + | embedPaths: [""; MAX_EMBEDS], |
|
| 325 | + | embedPathCount: 0, |
|
| 318 | 326 | }; |
|
| 319 | 327 | } |
|
| 320 | 328 | ||
| 321 | 329 | /// Register, load, and parse a source path or `logical/path=source.rad` mapping. |
|
| 322 | 330 | fn processModule( |
| 465 | 473 | throw error(&["too many modules specified for package"]); |
|
| 466 | 474 | } |
|
| 467 | 475 | set input.radPaths[input.radPathCount] = args[idx]; |
|
| 468 | 476 | set input.radPathCount += 1; |
|
| 469 | 477 | } |
|
| 478 | + | } else if mem::eq(arg, "-embed") { |
|
| 479 | + | let path = try nextArg(args, &mut idx, &["`-embed` requires a file path"]); |
|
| 480 | + | let pkgIdx = currentPkgIdx else { |
|
| 481 | + | throw error(&["`-embed` must follow a `-pkg` argument"]); |
|
| 482 | + | }; |
|
| 483 | + | let input = &mut inputs[pkgIdx]; |
|
| 484 | + | if input.embedPathCount >= MAX_EMBEDS { |
|
| 485 | + | throw error(&["too many embedded files specified for package"]); |
|
| 486 | + | } |
|
| 487 | + | set input.embedPaths[input.embedPathCount] = path; |
|
| 488 | + | set input.embedPathCount += 1; |
|
| 470 | 489 | } else if mem::eq(arg, "-start") { |
|
| 471 | 490 | try nextArg(args, &mut idx, &["`-start` requires an assembly path"]); |
|
| 472 | 491 | let pkgIdx = currentPkgIdx else { |
|
| 473 | 492 | throw error(&["`-start` must follow a `-pkg` argument"]); |
|
| 474 | 493 | }; |
| 518 | 537 | throw error(&["no package specified"]); |
|
| 519 | 538 | } |
|
| 520 | 539 | for i in 0 .. pkgCount { |
|
| 521 | 540 | if inputs[i].artifactRoot <> nil and (inputs[i].radPathCount > 0 |
|
| 522 | 541 | or inputs[i].asmPathCount > 0 |
|
| 542 | + | or inputs[i].embedPathCount > 0 |
|
| 523 | 543 | or inputs[i].startupPath <> nil) |
|
| 524 | 544 | { |
|
| 525 | 545 | throw error(&["package", inputs[i].name, "has both source and artifact inputs"]); |
|
| 526 | 546 | } |
|
| 527 | 547 | if inputs[i].radPathCount == 0 and inputs[i].artifactRoot == nil { |
| 588 | 608 | } |
|
| 589 | 609 | for j in 0 .. ctx.inputs[i].radPathCount { |
|
| 590 | 610 | let path = ctx.inputs[i].radPaths[j]; |
|
| 591 | 611 | try processModule(&mut ctx.packages[i], graph, path, &mut ctx.parser, sourceArena); |
|
| 592 | 612 | } |
|
| 613 | + | let files = try build::embeds(ctx.inputs[i], sourceArena) catch { |
|
| 614 | + | throw error(&["cannot read embedded files of package", name]); |
|
| 615 | + | }; |
|
| 616 | + | let root = ctx.packages[i].rootModuleId else panic "processCommand: package has no root"; |
|
| 617 | + | set graph.entries[root as u32].embeds = try build::embedded(files, sourceArena); |
|
| 593 | 618 | } |
|
| 594 | 619 | return ctx; |
|
| 595 | 620 | } |
|
| 596 | 621 | ||
| 597 | 622 | /// Get the entry package from the context. |
compiler/radiance/artifact.rad
+66 -29
| 1 | 1 | //! Complete compiler interface trees paired with exact executable package images. |
|
| 2 | 2 | ||
| 3 | 3 | use std::char; |
|
| 4 | 4 | use std::fmt; |
|
| 5 | 5 | use std::fs; |
|
| 6 | + | use std::io; |
|
| 6 | 7 | use std::hash::blake3; |
|
| 7 | 8 | use std::lang::alloc; |
|
| 8 | 9 | use std::lang::ast; |
|
| 9 | 10 | use std::lang::il::binary; |
|
| 10 | 11 | use std::lang::il::binary::linkage; |
| 56 | 57 | Assembly, |
|
| 57 | 58 | /// Entry assembly linked before all generated functions. |
|
| 58 | 59 | Startup, |
|
| 59 | 60 | /// Source location tables for streamed functions. |
|
| 60 | 61 | Debug, |
|
| 62 | + | /// File contents that modules read with `@embed`. |
|
| 63 | + | Embed, |
|
| 61 | 64 | } |
|
| 62 | 65 | ||
| 66 | + | /// File roles in the order of their encoded numbers. |
|
| 67 | + | constant ROLES: [FileRole; 4] = [ |
|
| 68 | + | FileRole::Assembly, FileRole::Startup, FileRole::Debug, FileRole::Embed |
|
| 69 | + | ]; |
|
| 70 | + | ||
| 63 | 71 | /// An immutable non-Radiance artifact input. |
|
| 64 | 72 | export record File: Copy { |
|
| 65 | 73 | /// Relative storage path inside the interface tree. |
|
| 66 | 74 | path: *[u8], |
|
| 67 | 75 | /// Original diagnostic source path. |
| 121 | 129 | mem::store32Le(&mut size[..], 0, bytes.len); |
|
| 122 | 130 | blake3::update(state, &size[..]); |
|
| 123 | 131 | blake3::update(state, bytes); |
|
| 124 | 132 | } |
|
| 125 | 133 | ||
| 126 | - | /// Hash exported contracts, RID declarations, and dependency metadata. |
|
| 127 | - | /// Build provenance, source locations, and implementation-only files are separate inputs. |
|
| 134 | + | /// Hash exported contracts, RID declarations, embedded files, and dependency metadata. |
|
| 135 | + | /// RID declarations can read embedded files. Build provenance, source locations, and |
|
| 136 | + | /// native-link files are separate inputs. |
|
| 128 | 137 | export fn declarations(package: &Package) -> binary::Id { |
|
| 129 | 138 | let mut state = blake3::new(); |
|
| 130 | 139 | field(&mut state, package.name); |
|
| 131 | 140 | field(&mut state, &package.exports.bytes[..]); |
|
| 132 | - | let mut counts: [u8; 12] = [0; 12]; |
|
| 141 | + | let mut embeds: u32 = 0; |
|
| 142 | + | for file in package.files { |
|
| 143 | + | if file.role == FileRole::Embed { |
|
| 144 | + | set embeds += 1; |
|
| 145 | + | } |
|
| 146 | + | } |
|
| 147 | + | let mut counts: [u8; 16] = [0; 16]; |
|
| 133 | 148 | mem::store32Le(&mut counts[..], 0, VERSION); |
|
| 134 | 149 | mem::store32Le(&mut counts[..], 4, package.modules.len); |
|
| 135 | - | mem::store32Le(&mut counts[..], 8, package.dependencies.len); |
|
| 150 | + | mem::store32Le(&mut counts[..], 8, embeds); |
|
| 151 | + | mem::store32Le(&mut counts[..], 12, package.dependencies.len); |
|
| 136 | 152 | field(&mut state, &counts[..]); |
|
| 137 | 153 | for module in package.modules { |
|
| 138 | 154 | field(&mut state, module.path); |
|
| 139 | 155 | field(&mut state, &module.hash.bytes[..]); |
|
| 140 | 156 | } |
|
| 157 | + | for file in package.files { |
|
| 158 | + | if file.role == FileRole::Embed { |
|
| 159 | + | field(&mut state, file.path); |
|
| 160 | + | field(&mut state, &digest(file.bytes).bytes[..]); |
|
| 161 | + | } |
|
| 162 | + | } |
|
| 141 | 163 | for dependency in package.dependencies { |
|
| 142 | 164 | field(&mut state, dependency.name); |
|
| 143 | 165 | field(&mut state, &dependency.declarations.bytes[..]); |
|
| 144 | 166 | } |
|
| 145 | 167 | let hash = blake3::finish(state); |
| 438 | 460 | let length = try readNumber(try fieldNode(&descriptor, "size")); |
|
| 439 | 461 | let hash = try readId(try fieldNode(&descriptor, "hash")); |
|
| 440 | 462 | if not validPath(path) or not mem::endsWith(path, ".rid") { |
|
| 441 | 463 | throw binary::Error::Invalid; |
|
| 442 | 464 | } |
|
| 443 | - | for j in 0 .. modules.len { |
|
| 444 | - | if mem::eq(modules[j].path, path) { |
|
| 445 | - | throw binary::Error::Invalid; |
|
| 446 | - | } |
|
| 447 | - | } |
|
| 448 | 465 | if i == 0 { |
|
| 449 | 466 | if not mem::eq(path, try join(arena, &[name, ".rid"])) { |
|
| 450 | 467 | throw binary::Error::Invalid; |
|
| 451 | 468 | } |
|
| 452 | 469 | } else if not mem::startsWith(path, try join(arena, &[name, "/"])) { |
| 465 | 482 | for node in fileNodes { |
|
| 466 | 483 | let descriptor = try readRecord(node, "File", &["path", "origin", "role", "size", "hash"]); |
|
| 467 | 484 | let path = try readString(try fieldNode(&descriptor, "path")); |
|
| 468 | 485 | let origin = try readString(try fieldNode(&descriptor, "origin")); |
|
| 469 | 486 | let kind = try readNumber(try fieldNode(&descriptor, "role")); |
|
| 470 | - | if not validPath(path) or kind > 2 { |
|
| 471 | - | throw binary::Error::Invalid; |
|
| 472 | - | } |
|
| 473 | - | for i in 0 .. files.len { |
|
| 474 | - | if mem::eq(files[i].path, path) { |
|
| 475 | - | throw binary::Error::Invalid; |
|
| 476 | - | } |
|
| 477 | - | } |
|
| 478 | - | for i in 0 .. modules.len { |
|
| 479 | - | if mem::eq(modules[i].path, path) { |
|
| 480 | - | throw binary::Error::Invalid; |
|
| 481 | - | } |
|
| 482 | - | } |
|
| 483 | - | if mem::eq(path, "package.metadata") { |
|
| 487 | + | if not validPath(path) or kind >= ROLES.len { |
|
| 484 | 488 | throw binary::Error::Invalid; |
|
| 485 | 489 | } |
|
| 486 | 490 | let length = try readNumber(try fieldNode(&descriptor, "size")); |
|
| 487 | 491 | let hash = try readId(try fieldNode(&descriptor, "hash")); |
|
| 488 | 492 | let bytes = try readFile(try join(arena, &[tree, path]), arena); |
|
| 489 | 493 | if bytes.len <> length or (validation == Validation::Full and digest(bytes) <> hash) { |
|
| 490 | 494 | throw binary::Error::Invalid; |
|
| 491 | 495 | } |
|
| 492 | - | let role = FileRole::Startup |
|
| 493 | - | if kind == 1 |
|
| 494 | - | else FileRole::Debug |
|
| 495 | - | if kind == 2 |
|
| 496 | - | else FileRole::Assembly; |
|
| 497 | - | try files.append(File { path, origin, bytes, role }, arena) catch { |
|
| 496 | + | try files.append(File { path, origin, bytes, role: ROLES[kind] }, arena) catch { |
|
| 498 | 497 | throw binary::Error::Storage; |
|
| 499 | 498 | }; |
|
| 500 | 499 | } |
|
| 501 | 500 | let dependencyNodes = try readArray(try fieldNode(&literal, "dependencies")); |
|
| 502 | 501 | let mut dependencies: *mut [Dependency] = &mut []; |
| 528 | 527 | dependencies: &dependencies[..], |
|
| 529 | 528 | exports, |
|
| 530 | 529 | declarations: binary::Id { bytes: [0; 32] }, |
|
| 531 | 530 | publication: Publication { image, inputs, identity, metadata: encoded }, |
|
| 532 | 531 | }; |
|
| 532 | + | if conflict(&package) <> nil { |
|
| 533 | + | throw binary::Error::Invalid; |
|
| 534 | + | } |
|
| 533 | 535 | set package.declarations = declarations(&package); |
|
| 534 | 536 | let mut input = reader::new(image); |
|
| 535 | 537 | let header = try program::header(&mut input, arena); |
|
| 536 | 538 | if header.links.metadata <> package.declarations { |
|
| 537 | 539 | throw binary::Error::Invalid; |
|
| 538 | 540 | } |
|
| 539 | 541 | return package; |
|
| 540 | 542 | } |
|
| 541 | 543 | ||
| 544 | + | /// Path `index` of the interface tree: the modules, then the files, then the metadata. |
|
| 545 | + | fn storedPath(package: &Package, index: u32) -> *[u8] { |
|
| 546 | + | if index < package.modules.len { |
|
| 547 | + | return package.modules[index].path; |
|
| 548 | + | } |
|
| 549 | + | if index - package.modules.len < package.files.len { |
|
| 550 | + | return package.files[index - package.modules.len].path; |
|
| 551 | + | } |
|
| 552 | + | return "package.metadata"; |
|
| 553 | + | } |
|
| 554 | + | ||
| 555 | + | /// Find a path of the interface tree that repeats another one, or that names a file |
|
| 556 | + | /// where another path needs a directory. |
|
| 557 | + | fn conflict(package: &Package) -> ?*[u8] { |
|
| 558 | + | let count = package.modules.len + package.files.len + 1; |
|
| 559 | + | for i in 0 .. count { |
|
| 560 | + | for j in i + 1 .. count { |
|
| 561 | + | let a = storedPath(package, i); |
|
| 562 | + | let b = storedPath(package, j); |
|
| 563 | + | let short = a if a.len <= b.len else b; |
|
| 564 | + | let long = b if a.len <= b.len else a; |
|
| 565 | + | if mem::startsWith(long, short) and (long.len == short.len or long[short.len] == '/') { |
|
| 566 | + | return b; |
|
| 567 | + | } |
|
| 568 | + | } |
|
| 569 | + | } |
|
| 570 | + | return nil; |
|
| 571 | + | } |
|
| 572 | + | ||
| 542 | 573 | /// Write the complete set inside a private artifact root. The caller publishes that root. |
|
| 543 | 574 | export fn write(package: &Package, root: *[u8], arena: &heap::Heap) throws (sys::Error) { |
|
| 544 | 575 | let publication = package.publication else panic "write: missing publication"; |
|
| 576 | + | if let path = conflict(package) { |
|
| 577 | + | io::printError("radiance: artifact path conflicts with another stored path: "); |
|
| 578 | + | io::printError(path); |
|
| 579 | + | io::printError("\n"); |
|
| 580 | + | throw sys::Error::Invalid; |
|
| 581 | + | } |
|
| 545 | 582 | let tree = try join(arena, &[root, "/", package.name, ".interface/"]); |
|
| 546 | 583 | for module in package.modules { |
|
| 547 | 584 | let path = try join(arena, &[tree, module.path]); |
|
| 548 | 585 | try directories(path); |
|
| 549 | 586 | try fs::writeFile(path, module.text); |
compiler/radiance/build.rad
+72 -9
| 241 | 241 | Snapshot { path, text }, arena |
|
| 242 | 242 | ) catch { |
|
| 243 | 243 | throw sys::Error::TooLarge; |
|
| 244 | 244 | }; |
|
| 245 | 245 | } |
|
| 246 | - | let first = sourcePath(options.radPaths[0]); |
|
| 247 | - | let mut directory: u32 = 0; |
|
| 248 | - | if let slash = mem::rfind(first, "/") { |
|
| 249 | - | set directory = slash + 1; |
|
| 250 | - | } |
|
| 251 | 246 | let path = options.manifestPath else try artifact::join(arena, &[ |
|
| 252 | - | &first[.. directory], options.name, ".manifest" |
|
| 247 | + | rootDirectory(options), options.name, ".manifest" |
|
| 253 | 248 | ]); |
|
| 254 | 249 | let mut manifest: *[u8] = ""; |
|
| 255 | 250 | if try fs::stat(path) <> nil { |
|
| 256 | 251 | set manifest = try artifact::readFile(path, arena); |
|
| 257 | 252 | } else if options.manifestPath <> nil { |
| 277 | 272 | let bytes = try artifact::readFile(origin, arena); |
|
| 278 | 273 | try files.append(artifact::File { path, origin, bytes, role }, arena) catch { |
|
| 279 | 274 | throw sys::Error::TooLarge; |
|
| 280 | 275 | }; |
|
| 281 | 276 | } |
|
| 277 | + | try files.extend(try embeds(options, arena), arena) catch { |
|
| 278 | + | throw sys::Error::TooLarge; |
|
| 279 | + | }; |
|
| 282 | 280 | return Input { |
|
| 283 | 281 | options, |
|
| 284 | 282 | dependencies, |
|
| 285 | 283 | contents: Contents::Source(Source { |
|
| 286 | 284 | modules: &modules[..], files: &files[..], manifest |
|
| 287 | 285 | }), |
|
| 288 | 286 | }; |
|
| 289 | 287 | } |
|
| 290 | 288 | ||
| 289 | + | /// Return the package root: the directory of the root module, with its final `/`. |
|
| 290 | + | fn rootDirectory(options: super::PackageInput) -> *[u8] { |
|
| 291 | + | let first = sourcePath(options.radPaths[0]); |
|
| 292 | + | let slash = mem::rfind(first, "/") else return ""; |
|
| 293 | + | return &first[.. slash + 1]; |
|
| 294 | + | } |
|
| 295 | + | ||
| 296 | + | /// Read the files that a source package declares for `@embed`. Each one must lie |
|
| 297 | + | /// under the package root, and is stored at its path from the root in the interface |
|
| 298 | + | /// tree. |
|
| 299 | + | export fn embeds(options: super::PackageInput, arena: &heap::Heap) -> *[artifact::File] |
|
| 300 | + | throws (sys::Error) |
|
| 301 | + | { |
|
| 302 | + | let root = rootDirectory(options); |
|
| 303 | + | let mut files: *mut [artifact::File] = &mut []; |
|
| 304 | + | for origin in &options.embedPaths[.. options.embedPathCount] { |
|
| 305 | + | if not mem::startsWith(origin, root) or not artifact::validPath(&origin[root.len ..]) { |
|
| 306 | + | io::printError("radiance: embedded file is not a clean path under the package root: "); |
|
| 307 | + | io::printError(origin); |
|
| 308 | + | io::printError("\n"); |
|
| 309 | + | throw sys::Error::Invalid; |
|
| 310 | + | } |
|
| 311 | + | let path = &origin[root.len ..]; |
|
| 312 | + | for i in 0 .. files.len { |
|
| 313 | + | if mem::eq(files[i].path, path) { |
|
| 314 | + | io::printError("radiance: embedded file is declared twice: "); |
|
| 315 | + | io::printError(origin); |
|
| 316 | + | io::printError("\n"); |
|
| 317 | + | throw sys::Error::Invalid; |
|
| 318 | + | } |
|
| 319 | + | } |
|
| 320 | + | let bytes = try artifact::readFile(origin, arena); |
|
| 321 | + | try files.append( |
|
| 322 | + | artifact::File { path, origin, bytes, role: artifact::FileRole::Embed }, arena |
|
| 323 | + | ) catch { |
|
| 324 | + | throw sys::Error::TooLarge; |
|
| 325 | + | }; |
|
| 326 | + | } |
|
| 327 | + | return &files[..]; |
|
| 328 | + | } |
|
| 329 | + | ||
| 330 | + | /// Return the files that a package's modules can embed, keyed by path from the package root. |
|
| 331 | + | export fn embedded(files: &[artifact::File], arena: &heap::Heap) -> *[module::Embed] |
|
| 332 | + | throws (super::Error) |
|
| 333 | + | { |
|
| 334 | + | let mut result: *mut [module::Embed] = &mut []; |
|
| 335 | + | for file in files { |
|
| 336 | + | if file.role == artifact::FileRole::Embed { |
|
| 337 | + | try result.append(module::Embed { path: file.path, bytes: file.bytes }, arena) catch { |
|
| 338 | + | throw super::Error::Other; |
|
| 339 | + | }; |
|
| 340 | + | } |
|
| 341 | + | } |
|
| 342 | + | return &result[..]; |
|
| 343 | + | } |
|
| 344 | + | ||
| 291 | 345 | /// Find an explicitly selected provider by its package name. |
|
| 292 | 346 | fn find(inputs: &[Input], name: &[u8]) -> ?u32 { |
|
| 293 | 347 | for input, i in inputs { |
|
| 294 | 348 | if mem::eq(input.options.name, name) { |
|
| 295 | 349 | return i; |
| 406 | 460 | ctx: &mut super::CompileContext, |
|
| 407 | 461 | graph: &mut module::ModuleGraph, |
|
| 408 | 462 | id: u32, |
|
| 409 | 463 | modules: &[Snapshot], |
|
| 410 | 464 | role: module::Role, |
|
| 411 | - | dependencies: *[u16] |
|
| 465 | + | dependencies: *[u16], |
|
| 466 | + | embeds: *[module::Embed] |
|
| 412 | 467 | ) throws (super::Error) { |
|
| 413 | 468 | let name = ctx.inputs[id].name; |
|
| 414 | 469 | package::init(&mut ctx.packages[id], id as u16, name, &mut ctx.parser.pool); |
|
| 415 | 470 | for item in modules { |
|
| 416 | 471 | let mut path = item.path; |
| 454 | 509 | }; |
|
| 455 | 510 | try module::setSource(graph, moduleId, item.text) catch { |
|
| 456 | 511 | throw super::Error::Other; |
|
| 457 | 512 | }; |
|
| 458 | 513 | } |
|
| 514 | + | let root = ctx.packages[id].rootModuleId else panic "load: package has no root module"; |
|
| 515 | + | set graph.entries[root as u32].embeds = embeds; |
|
| 459 | 516 | } |
|
| 460 | 517 | ||
| 461 | 518 | /// Publish immutable module entry copies while the source graph appends new modules. |
|
| 462 | 519 | fn table(graph: &module::ModuleGraph, arena: &heap::Heap) -> module::ModuleTable |
|
| 463 | 520 | throws (super::Error) |
| 632 | 689 | throw super::Error::Other; |
|
| 633 | 690 | }; |
|
| 634 | 691 | } |
|
| 635 | 692 | resetFrontend(ctx, graph, work.main); |
|
| 636 | 693 | try loadInterfaces(ctx, graph, selected, &compiled[..], driverArena); |
|
| 637 | - | try load(ctx, graph, index, source.modules, module::Role::Source, providerIds); |
|
| 694 | + | let embeds = try embedded(source.files, driverArena); |
|
| 695 | + | try load( |
|
| 696 | + | ctx, graph, index, source.modules, module::Role::Source, providerIds, embeds |
|
| 697 | + | ); |
|
| 638 | 698 | if ctx.config.buildTest and mem::eq(input.options.name, entryName) { |
|
| 639 | 699 | try super::generateTestRunner(ctx, graph, driverArena); |
|
| 640 | 700 | } |
|
| 641 | 701 | let modules = try table(graph, ctx.parser.arena.heap); |
|
| 642 | 702 | let res = try super::runResolver( |
| 774 | 834 | Snapshot { path: item.path, text: item.text }, driverArena |
|
| 775 | 835 | ) catch { |
|
| 776 | 836 | throw super::Error::Other; |
|
| 777 | 837 | }; |
|
| 778 | 838 | } |
|
| 779 | - | try load(ctx, graph, i, &modules[..], module::Role::Interface, deps); |
|
| 839 | + | let embeds = try embedded(compiled[i].files, driverArena); |
|
| 840 | + | try load( |
|
| 841 | + | ctx, graph, i, &modules[..], module::Role::Interface, deps, embeds |
|
| 842 | + | ); |
|
| 780 | 843 | } |
|
| 781 | 844 | } |
|
| 782 | 845 | ||
| 783 | 846 | /// Write package artifact trees and the exact graph lockfile. |
|
| 784 | 847 | fn writePackages( |
lib/std/lang/ast.rad
+4 -0
| 222 | 222 | /// Alignment requirement of type (`@alignOf`). |
|
| 223 | 223 | AlignOf, |
|
| 224 | 224 | /// Construct a slice from pointer, length, and optional capacity (`@sliceOf`). |
|
| 225 | 225 | /// The pointer must not be null, even when the length is zero. |
|
| 226 | 226 | SliceOf, |
|
| 227 | + | /// Contents of a file that the package declares for embedding (`@embed`). |
|
| 228 | + | /// The path is a string literal relative to the package root. |
|
| 229 | + | Embed, |
|
| 227 | 230 | } |
|
| 228 | 231 | ||
| 229 | 232 | /// Source name of a builtin, eg. `@sizeOf`. |
|
| 230 | 233 | export fn builtinText(kind: Builtin) -> *[u8] { |
|
| 231 | 234 | match kind { |
|
| 232 | 235 | case Builtin::SizeOf => return "@sizeOf", |
|
| 233 | 236 | case Builtin::AlignOf => return "@alignOf", |
|
| 234 | 237 | case Builtin::SliceOf => return "@sliceOf", |
|
| 238 | + | case Builtin::Embed => return "@embed", |
|
| 235 | 239 | } |
|
| 236 | 240 | } |
|
| 237 | 241 | ||
| 238 | 242 | /// Source extent for a node measured in bytes. |
|
| 239 | 243 | export record Span: Copy { |
lib/std/lang/lower.rad
+1 -1
| 9289 | 9289 | kind: ast::Builtin, |
|
| 9290 | 9290 | args: *[*ast::Node] |
|
| 9291 | 9291 | ) -> il::Val throws (LowerError) { |
|
| 9292 | 9292 | match kind { |
|
| 9293 | 9293 | case ast::Builtin::SliceOf => return try lowerSliceOf(self, node, args), |
|
| 9294 | - | case ast::Builtin::SizeOf, ast::Builtin::AlignOf => { |
|
| 9294 | + | case ast::Builtin::SizeOf, ast::Builtin::AlignOf, ast::Builtin::Embed => { |
|
| 9295 | 9295 | let constVal = resolver::constValueEntry(&self.resolver, node) else { |
|
| 9296 | 9296 | throw LowerError::MissingConst(node); |
|
| 9297 | 9297 | }; |
|
| 9298 | 9298 | return try constValueToVal(self, constVal, node); |
|
| 9299 | 9299 | } |
lib/std/lang/module.rad
+26 -0
| 93 | 93 | childrenLen: u32, |
|
| 94 | 94 | /// Parsed AST root for this module when available. |
|
| 95 | 95 | ast: ?*ast::Node, |
|
| 96 | 96 | /// Source text for this module (for error reporting). |
|
| 97 | 97 | source: ?*[u8], |
|
| 98 | + | /// Files that the package's modules can embed. Only a root module has them. |
|
| 99 | + | embeds: *[Embed], |
|
| 100 | + | } |
|
| 101 | + | ||
| 102 | + | /// File that a package declares for `@embed`. |
|
| 103 | + | export record Embed: Copy { |
|
| 104 | + | /// Clean path relative to the package root. |
|
| 105 | + | path: *[u8], |
|
| 106 | + | /// Complete file contents. |
|
| 107 | + | bytes: *[u8], |
|
| 98 | 108 | } |
|
| 99 | 109 | ||
| 100 | 110 | /// Dense storage for all modules referenced by the compilation unit. |
|
| 101 | 111 | export record ModuleGraph { |
|
| 102 | 112 | /// Permanent storage for module entries. |
| 416 | 426 | state: ModuleState::Vacant, |
|
| 417 | 427 | children: [0; MAX_MODULES], |
|
| 418 | 428 | childrenLen: 0, |
|
| 419 | 429 | ast: nil, |
|
| 420 | 430 | source: nil, |
|
| 431 | + | embeds: &[], |
|
| 421 | 432 | }; |
|
| 422 | 433 | ||
| 423 | 434 | return idx as u16; |
|
| 424 | 435 | } |
|
| 425 | 436 | ||
| 437 | + | /// Find the contents of a file that the package of module `id` declares for `@embed`. |
|
| 438 | + | export fn embedded(modules: ModuleTable, id: u16, path: *[u8]) -> ?*[u8] { |
|
| 439 | + | let mut entry = get(modules, id) else panic "embedded: module is missing"; |
|
| 440 | + | while let parent = entry.parent { |
|
| 441 | + | let next = get(modules, parent) else panic "embedded: parent module is missing"; |
|
| 442 | + | set entry = next; |
|
| 443 | + | } |
|
| 444 | + | for file in entry.embeds { |
|
| 445 | + | if mem::eq(file.path, path) { |
|
| 446 | + | return file.bytes; |
|
| 447 | + | } |
|
| 448 | + | } |
|
| 449 | + | return nil; |
|
| 450 | + | } |
|
| 451 | + | ||
| 426 | 452 | /// Append a logical path segment (module identifier) to the entry. |
|
| 427 | 453 | fn appendPathSegment(entry: &mut ModuleEntry, segment: *[u8]) throws (ModuleError) { |
|
| 428 | 454 | if entry.pathDepth >= entry.path.len { |
|
| 429 | 455 | throw ModuleError::PathTooDeep; |
|
| 430 | 456 | } |
lib/std/lang/parser.rad
+3 -1
| 777 | 777 | set kind = ast::Builtin::SizeOf; |
|
| 778 | 778 | } else if ident == "@alignOf" { |
|
| 779 | 779 | set kind = ast::Builtin::AlignOf; |
|
| 780 | 780 | } else if ident == "@sliceOf" { |
|
| 781 | 781 | set kind = ast::Builtin::SliceOf; |
|
| 782 | + | } else if ident == "@embed" { |
|
| 783 | + | set kind = ast::Builtin::Embed; |
|
| 782 | 784 | } else { |
|
| 783 | 785 | throw failParsing(p, "unknown builtin"); |
|
| 784 | 786 | } |
|
| 785 | 787 | try expect(p, scanner::TokenKind::LParen, "expected `(` after builtin name"); |
|
| 786 | 788 | ||
| 787 | 789 | // Parse arguments into a list. Use capacity 4 to handle any valid argument count |
|
| 788 | 790 | // plus some extra for error recovery. |
|
| 789 | 791 | let mut args = try ast::nodeSlice(&mut p.arena, 4); |
|
| 790 | 792 | ||
| 791 | - | if kind == ast::Builtin::SliceOf { |
|
| 793 | + | if kind == ast::Builtin::SliceOf or kind == ast::Builtin::Embed { |
|
| 792 | 794 | // Parse comma-separated expressions until closing paren. |
|
| 793 | 795 | // Argument count validation is done in semantic analysis. |
|
| 794 | 796 | let mut outer = openList(p); |
|
| 795 | 797 | while not check(p, scanner::TokenKind::RParen) { |
|
| 796 | 798 | let leading = try takePending(p, &args[..]); |
lib/std/lang/parser/tests.rad
+11 -0
| 2301 | 2301 | try testing::expect(builtinKind == ast::Builtin::SliceOf); |
|
| 2302 | 2302 | try testing::expect(builtinArgs.len == 3); |
|
| 2303 | 2303 | } |
|
| 2304 | 2304 | } |
|
| 2305 | 2305 | ||
| 2306 | + | /// `@embed` takes its path as an expression. |
|
| 2307 | + | @test unsafe fn testParseBuiltinEmbed() throws (testing::TestError) { |
|
| 2308 | + | let expr = try! parseExprStr("@embed(\"data/schema.rad\")"); |
|
| 2309 | + | let case ast::NodeValue::BuiltinCall { kind, args } = expr.value |
|
| 2310 | + | else throw testing::TestError::Failed; |
|
| 2311 | + | assert kind == ast::Builtin::Embed; |
|
| 2312 | + | assert args.len == 1; |
|
| 2313 | + | let case ast::NodeValue::String(path) = args[0].value else throw testing::TestError::Failed; |
|
| 2314 | + | assert mem::eq(path, "data/schema.rad"); |
|
| 2315 | + | } |
|
| 2316 | + | ||
| 2306 | 2317 | /// Test parsing prefix unary operators. |
|
| 2307 | 2318 | @test unsafe fn testParseUnaryOperators() throws (testing::TestError) { |
|
| 2308 | 2319 | { |
|
| 2309 | 2320 | let notExpr = try! parseExprStr("not flag"); |
|
| 2310 | 2321 | let case ast::NodeValue::UnOp(notNode) = notExpr.value |
lib/std/lang/resolver.rad
+32 -8
| 8 | 8 | mod metadata; |
|
| 9 | 9 | /// Unit tests for the resolver. Shared helpers live in `tests`, and the test cases |
|
| 10 | 10 | /// are split into topic modules. |
|
| 11 | 11 | @test mod tests; |
|
| 12 | 12 | ||
| 13 | - | use std::io; |
|
| 14 | 13 | use std::lang::ast; |
|
| 15 | 14 | use std::lang::module; |
|
| 16 | 15 | use std::lang::parser; |
|
| 17 | 16 | use std::lang::resolver::refs::Region; |
|
| 18 | 17 | use std::lang::types; |
| 617 | 616 | node: ?*ast::Node, |
|
| 618 | 617 | /// Module ID where this error occurred. |
|
| 619 | 618 | moduleId: u16, |
|
| 620 | 619 | } |
|
| 621 | 620 | ||
| 621 | + | /// Invalid builtin call. |
|
| 622 | + | export union BuiltinError: Copy { |
|
| 623 | + | /// Wrong number of arguments. |
|
| 624 | + | ArgCount(CountMismatch), |
|
| 625 | + | /// The `@embed` path is not a string literal. |
|
| 626 | + | EmbedPath, |
|
| 627 | + | /// The package does not declare a file with this `@embed` path. |
|
| 628 | + | EmbedNotFound(*[u8]), |
|
| 629 | + | } |
|
| 630 | + | ||
| 622 | 631 | /// High-level classification for semantic diagnostics. |
|
| 623 | 632 | export union ErrorKind: Copy { |
|
| 624 | 633 | /// Identifier declared more than once in the same scope. |
|
| 625 | 634 | DuplicateBinding(*[u8]), |
|
| 626 | 635 | /// Union variants have the same discriminant. |
| 827 | 836 | AlternativeBinding, |
|
| 828 | 837 | /// `match` has a duplicate case pattern. |
|
| 829 | 838 | DuplicateMatchPattern, |
|
| 830 | 839 | /// `match` has an unreachable `else`: all cases are already handled. |
|
| 831 | 840 | UnreachableElse, |
|
| 832 | - | /// Builtin called with wrong number of arguments. |
|
| 833 | - | BuiltinArgCountMismatch(CountMismatch), |
|
| 841 | + | /// Invalid builtin call. |
|
| 842 | + | Builtin(BuiltinError), |
|
| 834 | 843 | /// Instance method receiver mutability does not match the trait declaration. |
|
| 835 | 844 | ReceiverMutabilityMismatch, |
|
| 836 | 845 | /// Duplicate instance declaration for the same (trait, type) pair. |
|
| 837 | 846 | DuplicateInstance, |
|
| 838 | 847 | /// Instance declaration is missing a required trait method. |
| 4155 | 4164 | return false; |
|
| 4156 | 4165 | } |
|
| 4157 | 4166 | case ast::NodeValue::FieldAccess(_), ast::NodeValue::Subscript { .. } => |
|
| 4158 | 4167 | return self.nodeData.get(node.id).constValue |
|
| 4159 | 4168 | <> nil or self.constantNode(node) <> nil, |
|
| 4169 | + | case ast::NodeValue::BuiltinCall { .. } => |
|
| 4170 | + | return self.nodeData.get(node.id).constValue |
|
| 4171 | + | <> nil, |
|
| 4160 | 4172 | case ast::NodeValue::Call(call) => { |
|
| 4161 | 4173 | if let case NodeExtra::StaticHeap(_) = self.nodeData.get(node.id).extra { |
|
| 4162 | 4174 | return true; |
|
| 4163 | 4175 | } |
|
| 4164 | 4176 | // Constructor calls (union variants, unlabeled records) are constant |
| 7747 | 7759 | ) -> Type throws (ResolveError) { |
|
| 7748 | 7760 | // Handle `@sliceOf(ptr, len)` and `@sliceOf(ptr, len, cap)`. It is unsafe |
|
| 7749 | 7761 | // because the pointer must be valid for the length and must not be null. |
|
| 7750 | 7762 | if kind == ast::Builtin::SliceOf { |
|
| 7751 | 7763 | if args.len <> 2 and args.len <> 3 { |
|
| 7752 | - | throw emitError(self, node, ErrorKind::BuiltinArgCountMismatch(CountMismatch { |
|
| 7764 | + | throw emitError(self, node, ErrorKind::Builtin(BuiltinError::ArgCount(CountMismatch { |
|
| 7753 | 7765 | expected: 2, |
|
| 7754 | 7766 | actual: args.len as u32, |
|
| 7755 | - | })); |
|
| 7767 | + | }))); |
|
| 7756 | 7768 | } |
|
| 7757 | 7769 | let ptrType = try visit(self, args[0], Type::Unknown); |
|
| 7758 | 7770 | let case Type::Pointer { class, target, mutable } = ptrType else { |
|
| 7759 | 7771 | throw emitError(self, node, ErrorKind::ExpectedPointer); |
|
| 7760 | 7772 | }; |
| 7764 | 7776 | } |
|
| 7765 | 7777 | try requireUnsafe(self, node); |
|
| 7766 | 7778 | return setNodeType(self, node, Type::Slice { class, item: target, mutable }); |
|
| 7767 | 7779 | } |
|
| 7768 | 7780 | if args.len <> 1 { |
|
| 7769 | - | throw emitError(self, node, ErrorKind::BuiltinArgCountMismatch(CountMismatch { |
|
| 7781 | + | throw emitError(self, node, ErrorKind::Builtin(BuiltinError::ArgCount(CountMismatch { |
|
| 7770 | 7782 | expected: 1, |
|
| 7771 | 7783 | actual: args.len as u32, |
|
| 7772 | - | })); |
|
| 7784 | + | }))); |
|
| 7785 | + | } |
|
| 7786 | + | // `@embed("path")` is a constant with the type of its string literal path. |
|
| 7787 | + | if kind == ast::Builtin::Embed { |
|
| 7788 | + | let case ast::NodeValue::String(path) = args[0].value else { |
|
| 7789 | + | throw emitError(self, args[0], ErrorKind::Builtin(BuiltinError::EmbedPath)); |
|
| 7790 | + | }; |
|
| 7791 | + | let type = try visit(self, args[0], Type::Unknown); |
|
| 7792 | + | let bytes = module::embedded(self.moduleTable, self.currentMod, path) else { |
|
| 7793 | + | throw emitError(self, args[0], ErrorKind::Builtin(BuiltinError::EmbedNotFound(path))); |
|
| 7794 | + | }; |
|
| 7795 | + | setNodeConstValue(self, node, ConstValue::String(bytes)); |
|
| 7796 | + | return setNodeType(self, node, type); |
|
| 7773 | 7797 | } |
|
| 7774 | 7798 | let ty = try resolveValueType(self, args[0]); |
|
| 7775 | 7799 | // Ensure the type body is resolved before computing layout. |
|
| 7776 | 7800 | // TODO: Somehow, ensuring the type is resolved should just happen all |
|
| 7777 | 7801 | // the time, lazily. |
| 7787 | 7811 | set value = layout.size; |
|
| 7788 | 7812 | } |
|
| 7789 | 7813 | case ast::Builtin::AlignOf => { |
|
| 7790 | 7814 | set value = layout.alignment; |
|
| 7791 | 7815 | } |
|
| 7792 | - | case ast::Builtin::SliceOf => { |
|
| 7816 | + | case ast::Builtin::SliceOf, ast::Builtin::Embed => { |
|
| 7793 | 7817 | panic "resolveBuiltinCall: unreachable: handled above"; |
|
| 7794 | 7818 | } |
|
| 7795 | 7819 | } |
|
| 7796 | 7820 | // Record as constant value for constant folding. |
|
| 7797 | 7821 | setNodeConstValue(self, node, ConstValue::Int(ConstInt { |
lib/std/lang/resolver/printer.rad
+9 -2
| 778 | 778 | io::print("opaque types cannot be dereferenced"); |
|
| 779 | 779 | } |
|
| 780 | 780 | case super::ErrorKind::OpaquePointerArithmetic => { |
|
| 781 | 781 | io::print("opaque pointer arithmetic is not allowed"); |
|
| 782 | 782 | } |
|
| 783 | - | case super::ErrorKind::BuiltinArgCountMismatch { .. } => { |
|
| 784 | - | io::print("built-in argument count mismatch"); |
|
| 783 | + | case super::ErrorKind::Builtin(error) => { |
|
| 784 | + | match error { |
|
| 785 | + | case super::BuiltinError::ArgCount(_) => |
|
| 786 | + | io::print("built-in argument count mismatch"), |
|
| 787 | + | case super::BuiltinError::EmbedPath => |
|
| 788 | + | io::print("`@embed` requires a string literal path"), |
|
| 789 | + | case super::BuiltinError::EmbedNotFound(path) => |
|
| 790 | + | printQuoted("embedded file not declared by the package: '", path), |
|
| 791 | + | } |
|
| 785 | 792 | } |
|
| 786 | 793 | } |
|
| 787 | 794 | io::print("\n"); |
|
| 788 | 795 | } |
|
| 789 | 796 |
lib/std/lang/resolver/tests.rad
+7 -0
| 366 | 366 | return mem::eq(n, name); |
|
| 367 | 367 | } |
|
| 368 | 368 | else => return actualRegion == expectedRegion, |
|
| 369 | 369 | } |
|
| 370 | 370 | } |
|
| 371 | + | if let case super::ErrorKind::Builtin(super::BuiltinError::EmbedNotFound(expectedPath)) = |
|
| 372 | + | expected |
|
| 373 | + | { |
|
| 374 | + | let case super::ErrorKind::Builtin(super::BuiltinError::EmbedNotFound(actualPath)) = *actual |
|
| 375 | + | else return false; |
|
| 376 | + | return mem::eq(actualPath, expectedPath); |
|
| 377 | + | } |
|
| 371 | 378 | if let case super::ErrorKind::DeclarationCycle(expectedName) = expected { |
|
| 372 | 379 | if let case super::ErrorKind::DeclarationCycle(actualName) = *actual { |
|
| 373 | 380 | return mem::eq(actualName, expectedName); |
|
| 374 | 381 | } |
|
| 375 | 382 | return false; |
lib/std/lang/resolver/tests/structure.rad
+71 -3
| 1 | 1 | //! Resolver tests: union and module declarations, imports, opaque pointers, match patterns, and |
|
| 2 | 2 | //! slice builtins. |
|
| 3 | 3 | ||
| 4 | 4 | use std::lang::ast; |
|
| 5 | + | use std::lang::module; |
|
| 5 | 6 | use std::lang::resolver; |
|
| 6 | 7 | use std::lang::resolver::tests::*; |
|
| 7 | 8 | use std::lang::types; |
|
| 8 | 9 | use std::mem; |
|
| 9 | 10 | use std::testing; |
| 2408 | 2409 | { |
|
| 2409 | 2410 | let mut a = testResolver(); |
|
| 2410 | 2411 | let program = "fn f() -> *[u8] { return @sliceOf(); }"; |
|
| 2411 | 2412 | let result = try resolveProgramStr(&mut a, program); |
|
| 2412 | 2413 | let err = try expectError(&result); |
|
| 2413 | - | let case resolver::ErrorKind::BuiltinArgCountMismatch(mismatch) = err.kind |
|
| 2414 | + | let case resolver::ErrorKind::Builtin(resolver::BuiltinError::ArgCount(mismatch)) = err.kind |
|
| 2414 | 2415 | else throw testing::TestError::Failed; |
|
| 2415 | 2416 | try testing::expect(mismatch.expected == 2); |
|
| 2416 | 2417 | try testing::expect(mismatch.actual == 0); |
|
| 2417 | 2418 | } |
|
| 2418 | 2419 | // Too few arguments. |
|
| 2419 | 2420 | { |
|
| 2420 | 2421 | let mut a = testResolver(); |
|
| 2421 | 2422 | let program = "fn f(ptr: *u8) -> *[u8] { return @sliceOf(ptr); }"; |
|
| 2422 | 2423 | let result = try resolveProgramStr(&mut a, program); |
|
| 2423 | 2424 | let err = try expectError(&result); |
|
| 2424 | - | let case resolver::ErrorKind::BuiltinArgCountMismatch(mismatch) = err.kind |
|
| 2425 | + | let case resolver::ErrorKind::Builtin(resolver::BuiltinError::ArgCount(mismatch)) = err.kind |
|
| 2425 | 2426 | else throw testing::TestError::Failed; |
|
| 2426 | 2427 | try testing::expect(mismatch.expected == 2); |
|
| 2427 | 2428 | try testing::expect(mismatch.actual == 1); |
|
| 2428 | 2429 | } |
|
| 2429 | 2430 | // Too many arguments. |
| 2431 | 2432 | let mut a = testResolver(); |
|
| 2432 | 2433 | let program = |
|
| 2433 | 2434 | "fn f(ptr: *u8, len: u32, cap: u32, extra: u32) -> *[u8] { return @sliceOf(ptr, len, cap, extra); }"; |
|
| 2434 | 2435 | let result = try resolveProgramStr(&mut a, program); |
|
| 2435 | 2436 | let err = try expectError(&result); |
|
| 2436 | - | let case resolver::ErrorKind::BuiltinArgCountMismatch(mismatch) = err.kind |
|
| 2437 | + | let case resolver::ErrorKind::Builtin(resolver::BuiltinError::ArgCount(mismatch)) = err.kind |
|
| 2437 | 2438 | else throw testing::TestError::Failed; |
|
| 2438 | 2439 | try testing::expect(mismatch.expected == 2); |
|
| 2439 | 2440 | try testing::expect(mismatch.actual == 4); |
|
| 2440 | 2441 | } |
|
| 2441 | 2442 | } |
| 3989 | 3990 | let root = try registerModule(&mut super::MODULE_GRAPH, nil, "root", source); |
|
| 3990 | 3991 | let result = try resolveModuleTree(&mut res, root); |
|
| 3991 | 3992 | try expectErrorKind(&result, resolver::ErrorKind::ConstExprRequired); |
|
| 3992 | 3993 | } |
|
| 3993 | 3994 | } |
|
| 3995 | + | ||
| 3996 | + | /// Files that a test package declares for `@embed`. |
|
| 3997 | + | constant EMBEDS: [module::Embed; 1] = [module::Embed { path: "data/text", bytes: "hello" }]; |
|
| 3998 | + | ||
| 3999 | + | /// Resolve a package whose root declares `EMBEDS`. |
|
| 4000 | + | unsafe fn resolveEmbedding(res: &mut resolver::Resolver, root: *[u8], child: ?*[u8]) -> TestResult |
|
| 4001 | + | throws (testing::TestError) |
|
| 4002 | + | { |
|
| 4003 | + | let id = try registerModule(&mut super::MODULE_GRAPH, nil, "root", root); |
|
| 4004 | + | if let code = child { |
|
| 4005 | + | try registerModule(&mut super::MODULE_GRAPH, id, "child", code); |
|
| 4006 | + | } |
|
| 4007 | + | set super::MODULE_GRAPH.entries[id as u32].embeds = &EMBEDS[..]; |
|
| 4008 | + | return try resolveModuleTree(res, id); |
|
| 4009 | + | } |
|
| 4010 | + | ||
| 4011 | + | /// `@embed` is a string constant from the package root, in every module and in |
|
| 4012 | + | /// constant aggregates and function bodies. |
|
| 4013 | + | @test unsafe fn testEmbedDeclaredFile() throws (testing::TestError) { |
|
| 4014 | + | let mut res = testResolver(); |
|
| 4015 | + | let result = try resolveEmbedding( |
|
| 4016 | + | &mut res, |
|
| 4017 | + | program( |
|
| 4018 | + | &[ |
|
| 4019 | + | "mod child; record Data { bytes: *[u8] } ", |
|
| 4020 | + | "constant TEXT: *[u8] = @embed(\"data/text\"); ", |
|
| 4021 | + | "constant DATA: Data = Data { bytes: @embed(\"data/text\") }; ", |
|
| 4022 | + | "fn text() -> *[u8] { return @embed(\"data/text\"); }", |
|
| 4023 | + | ] |
|
| 4024 | + | ), |
|
| 4025 | + | "export constant TEXT: *[u8] = @embed(\"data/text\");" |
|
| 4026 | + | ); |
|
| 4027 | + | try expectNoErrors(&result); |
|
| 4028 | + | let case ast::NodeValue::Module(module) = result.root.value |
|
| 4029 | + | else throw testing::TestError::Failed; |
|
| 4030 | + | let case ast::NodeValue::ConstDecl(decl) = module.statements[2].value |
|
| 4031 | + | else throw testing::TestError::Failed; |
|
| 4032 | + | let case resolver::ConstValue::String(text) = resolver::constValueEntry(&res, decl.value) |
|
| 4033 | + | else throw testing::TestError::Failed; |
|
| 4034 | + | assert mem::eq(text, "hello"); |
|
| 4035 | + | let type = try typeOf(&res, decl.value); |
|
| 4036 | + | try expectSliceType(type, false); |
|
| 4037 | + | } |
|
| 4038 | + | ||
| 4039 | + | /// `@embed` names a file that the package declares, with a string literal. |
|
| 4040 | + | @test unsafe fn testEmbedErrors() throws (testing::TestError) { |
|
| 4041 | + | { |
|
| 4042 | + | let mut res = testResolver(); |
|
| 4043 | + | let result = try resolveEmbedding( |
|
| 4044 | + | &mut res, "constant TEXT: *[u8] = @embed(\"data/missing\");", nil |
|
| 4045 | + | ); |
|
| 4046 | + | try expectErrorKind(&result, resolver::ErrorKind::Builtin( |
|
| 4047 | + | resolver::BuiltinError::EmbedNotFound("data/missing") |
|
| 4048 | + | )); |
|
| 4049 | + | } |
|
| 4050 | + | { |
|
| 4051 | + | let mut res = testResolver(); |
|
| 4052 | + | let result = try resolveEmbedding( |
|
| 4053 | + | &mut res, |
|
| 4054 | + | "constant PATH: *[u8] = \"data/text\"; constant TEXT: *[u8] = @embed(PATH);", |
|
| 4055 | + | nil |
|
| 4056 | + | ); |
|
| 4057 | + | try expectErrorKind(&result, resolver::ErrorKind::Builtin( |
|
| 4058 | + | resolver::BuiltinError::EmbedPath |
|
| 4059 | + | )); |
|
| 4060 | + | } |
|
| 4061 | + | } |
lib/std/lang/scanner.rad
+1 -0
| 235 | 235 | export fn scanner(sourceLoc: SourceLoc, source: *[u8], pool: &mut strings::Pool) -> Scanner { |
|
| 236 | 236 | // Intern built-in functions and attributes. |
|
| 237 | 237 | strings::intern(pool, "@sizeOf"); |
|
| 238 | 238 | strings::intern(pool, "@alignOf"); |
|
| 239 | 239 | strings::intern(pool, "@sliceOf"); |
|
| 240 | + | strings::intern(pool, "@embed"); |
|
| 240 | 241 | strings::intern(pool, "@default"); |
|
| 241 | 242 | strings::intern(pool, "@extern"); |
|
| 242 | 243 | strings::intern(pool, "@intrinsic"); |
|
| 243 | 244 | strings::intern(pool, "@language"); |
|
| 244 | 245 | strings::intern(pool, "@test"); |
test/integration/packages.rad
+102 -0
| 102 | 102 | if h.compile("use the large std artifact without source", h.out(&["large-client.log"])) { |
|
| 103 | 103 | execute(h, h.path(&["large.rv64"])); |
|
| 104 | 104 | } |
|
| 105 | 105 | } |
|
| 106 | 106 | ||
| 107 | + | /// Embed declared package files, and read them through generated interfaces. |
|
| 108 | + | fn embeds(h: &mut Harness) throws (sys::Error) { |
|
| 109 | + | let root = h.path(&["embeds"]); |
|
| 110 | + | try harness::makeDirs(h.join(&[root, "/data"])); |
|
| 111 | + | let provider = h.join(&[root, "/text.rad"]); |
|
| 112 | + | let data = h.join(&[root, "/data/hello.txt"]); |
|
| 113 | + | let app = h.join(&[root, "/app.rad"]); |
|
| 114 | + | let exported = h.join(&[root, "/exported"]); |
|
| 115 | + | let image = h.join(&[root, "/app.rv64"]); |
|
| 116 | + | let code = try h.load("test/packages/embeds/text.rad"); |
|
| 117 | + | try fs::writeFile(provider, code); |
|
| 118 | + | try fs::writeFile(data, "hello\n"); |
|
| 119 | + | try fs::writeFile(app, try h.load("test/packages/embeds/app.rad")); |
|
| 120 | + | try fs::writeFile(h.join(&[root, "/app.manifest"]), "text\n"); |
|
| 121 | + | let cache = h.join(&[root, "/cache"]); |
|
| 122 | + | for i in 0 .. 2 { |
|
| 123 | + | if i == 1 { |
|
| 124 | + | try fs::writeFile(data, "hullo\n"); |
|
| 125 | + | } |
|
| 126 | + | h.add( |
|
| 127 | + | &[ |
|
| 128 | + | "-cache", cache, "-pkg", "text", "-mod", provider, "-embed", data, |
|
| 129 | + | "-pkg", "app", "-mod", app, "-entry", "app", "-o", image, |
|
| 130 | + | ] |
|
| 131 | + | ); |
|
| 132 | + | if h.compile("compile embedded package files", h.out(&["embed.log"])) { |
|
| 133 | + | execute(h, image); |
|
| 134 | + | } |
|
| 135 | + | } |
|
| 136 | + | h.expect( |
|
| 137 | + | "embedded file edits invalidate clients", |
|
| 138 | + | h.path(&["embed.log"]), |
|
| 139 | + | harness::Expect::Matching { |
|
| 140 | + | text: "cache hit", count: 0 |
|
| 141 | + | } |
|
| 142 | + | ); |
|
| 143 | + | h.add( |
|
| 144 | + | &[ |
|
| 145 | + | "-no-cache", "-pkg", "text", "-mod", provider, "-embed", data, |
|
| 146 | + | "-pkg", "app", "-mod", app, "-entry", "app", "-ril", exported, |
|
| 147 | + | ] |
|
| 148 | + | ); |
|
| 149 | + | if not h.compile("export embedded package files", h.out(&["embed-export.log"])) { |
|
| 150 | + | return; |
|
| 151 | + | } |
|
| 152 | + | h.expect( |
|
| 153 | + | "interfaces keep embed calls", |
|
| 154 | + | h.join(&[exported, "/text.interface/text.rid"]), |
|
| 155 | + | harness::Expect::Contains("@embed(\"data/hello.txt\")") |
|
| 156 | + | ); |
|
| 157 | + | h.expect( |
|
| 158 | + | "interface trees hold embedded files", |
|
| 159 | + | h.join(&[exported, "/text.interface/data/hello.txt"]), |
|
| 160 | + | harness::Expect::Contains("hullo") |
|
| 161 | + | ); |
|
| 162 | + | try fs::remove(provider); |
|
| 163 | + | try fs::remove(data); |
|
| 164 | + | h.add( |
|
| 165 | + | &[ |
|
| 166 | + | "-no-cache", "-pkg", "text", "-artifact", exported, |
|
| 167 | + | "-pkg", "app", "-mod", app, "-entry", "app", "-o", image, |
|
| 168 | + | ] |
|
| 169 | + | ); |
|
| 170 | + | if h.compile("embed through an interface without source", h.out(&["embed-client.log"])) { |
|
| 171 | + | execute(h, image); |
|
| 172 | + | } |
|
| 173 | + | try fs::writeFile(provider, code); |
|
| 174 | + | try fs::writeFile(data, "hello\n"); |
|
| 175 | + | let rejected = h.join(&[root, "/rejected"]); |
|
| 176 | + | h.add( |
|
| 177 | + | &[ |
|
| 178 | + | "-no-cache", "-pkg", "text", "-mod", provider, "-embed", data, "-embed", data, |
|
| 179 | + | "-ril", rejected, |
|
| 180 | + | ] |
|
| 181 | + | ); |
|
| 182 | + | let twice = h.cc(h.take(), h.out(&["embed-twice.log"])); |
|
| 183 | + | h.run("reject embedded files declared twice", twice, process::Outcome::Exited(1), &[ |
|
| 184 | + | harness::Expect::Contains("embedded file is declared twice") |
|
| 185 | + | ]); |
|
| 186 | + | // An embedded file shares the interface tree with the generated module interfaces. |
|
| 187 | + | let interface = h.join(&[root, "/text.rid"]); |
|
| 188 | + | try fs::writeFile(interface, ""); |
|
| 189 | + | h.add( |
|
| 190 | + | &[ |
|
| 191 | + | "-no-cache", "-pkg", "text", "-mod", provider, "-embed", data, "-embed", interface, |
|
| 192 | + | "-ril", rejected, |
|
| 193 | + | ] |
|
| 194 | + | ); |
|
| 195 | + | let clash = h.cc(h.take(), h.out(&["embed-clash.log"])); |
|
| 196 | + | h.run("reject embedded files at interface paths", clash, process::Outcome::Exited(1), &[ |
|
| 197 | + | harness::Expect::Contains("artifact path conflicts with another stored path: text.rid") |
|
| 198 | + | ]); |
|
| 199 | + | let outside = h.path(&["outside.txt"]); |
|
| 200 | + | try fs::writeFile(outside, ""); |
|
| 201 | + | h.add(&["-no-cache", "-pkg", "text", "-mod", provider, "-embed", outside, "-ril", rejected]); |
|
| 202 | + | let escaped = h.cc(h.take(), h.out(&["embed-outside.log"])); |
|
| 203 | + | h.run("reject embedded files outside the package", escaped, process::Outcome::Exited(1), &[ |
|
| 204 | + | harness::Expect::Contains("not a clean path under the package root") |
|
| 205 | + | ]); |
|
| 206 | + | } |
|
| 207 | + | ||
| 107 | 208 | /// Check public package re-exports and private aliases through generated interfaces. |
|
| 108 | 209 | fn reexports(h: &mut Harness) throws (sys::Error) { |
|
| 109 | 210 | let root = h.path(&["reexports"]); |
|
| 110 | 211 | try harness::makeDirs(root); |
|
| 111 | 212 | let base = h.join(&[root, "/base.rad"]); |
| 528 | 629 | process::Outcome::Exited(1), |
|
| 529 | 630 | &[] |
|
| 530 | 631 | ); |
|
| 531 | 632 | try metadataReuse(h); |
|
| 532 | 633 | try reexports(h); |
|
| 634 | + | try embeds(h); |
|
| 533 | 635 | try paths(h); |
|
| 534 | 636 | try large(h); |
|
| 535 | 637 | h.done(mark, "packages: source-free linking, cache reuse, and integrity checks passed"); |
|
| 536 | 638 | } |
test/packages/embeds/app.rad
added
+9 -0
| 1 | + | use text; |
|
| 2 | + | ||
| 3 | + | @default fn main() -> u32 { |
|
| 4 | + | assert text::HELLO.len == 6; |
|
| 5 | + | assert text::HELLO[0] == 'h'; |
|
| 6 | + | assert text::hello()[4] == 'o'; |
|
| 7 | + | ||
| 8 | + | return 0; |
|
| 9 | + | } |
test/packages/embeds/text.rad
added
+5 -0
| 1 | + | export constant HELLO: *[u8] = @embed("data/hello.txt"); |
|
| 2 | + | ||
| 3 | + | export fn hello() -> *[u8] { |
|
| 4 | + | return @embed("data/hello.txt"); |
|
| 5 | + | } |