packages: Write metadata as Radiance values
3eb597b32d18587847ad6ecf33b9827db92e33441ed8985812f01cc32d2a34fe
Package metadata needs a textual format that the compiler can write and read without a separate parser. Write it as one Radiance expression, a `Package` record literal, and read it with `parser::parseValue`, which parses source text holding a single expression. Build the literal with shared AST literal and named-field constructors, and format it with the shared pretty printer through `pretty::expression`. Add shared hexadecimal byte conversion and byte escapes for artifact paths. Parse a module into a `Module` node rather than a block. Bind the function and constant names of every module before imports resolve. Use constant initializer nodes for field and array projections, including aggregate values. Keep the re-export provider and client in source fixture files. Assisted-by: Codex:gpt-6 Assisted-by: Claude:opus-5.5 Change-Id: I75b5bfc3a88c38439ebeaa71466f2e49dbb22a3d
1 parent
84f528bc
compiler/radiance.rad
+8 -8
| 809 | 809 | } |
|
| 810 | 810 | ||
| 811 | 811 | /// Inject a test runner into the entry package's root module. |
|
| 812 | 812 | /// |
|
| 813 | 813 | /// Scans the entry package for `@test fn` declarations, then appends |
|
| 814 | - | /// a synthetic entry point to the root module's AST block: |
|
| 814 | + | /// a synthetic entry point to the root module's AST: |
|
| 815 | 815 | /// |
|
| 816 | 816 | /// ``` |
|
| 817 | 817 | /// @default fn #testMain() -> i32 { |
|
| 818 | 818 | /// return testing::runAllTests(&[ |
|
| 819 | 819 | /// testing::TestInfo { module: "std::tests", name: "testFoo", func: tests::testFoo }, |
| 876 | 876 | let fnDecl = try synthTestMainFn( |
|
| 877 | 877 | &mut ctx.parser.arena, &mut ctx.parser.pool, &tests[..] |
|
| 878 | 878 | ) catch { |
|
| 879 | 879 | throw error(&["fatal: syntax tree arena is full"]); |
|
| 880 | 880 | }; |
|
| 881 | - | let updatedRoot = try injectIntoBlock(rootAst, &mut ctx.parser.arena, fnDecl) catch { |
|
| 881 | + | let updatedRoot = try injectIntoModule(rootAst, &mut ctx.parser.arena, fnDecl) catch { |
|
| 882 | 882 | throw error(&["fatal: syntax tree arena is full"]); |
|
| 883 | 883 | }; |
|
| 884 | 884 | try module::setAst(graph, rootId, updatedRoot) catch { |
|
| 885 | 885 | throw error(&["failed to set test runner AST"]); |
|
| 886 | 886 | }; |
| 944 | 944 | return try ast::synthNode(arena, ast::NodeValue::FnDecl(ast::FnDecl { |
|
| 945 | 945 | name: fnName, sig: fnSig, body: fnBody, attrs: fnAttrs |
|
| 946 | 946 | })); |
|
| 947 | 947 | } |
|
| 948 | 948 | ||
| 949 | - | /// Build a block node with a declaration appended to its statement list. |
|
| 950 | - | fn injectIntoBlock( |
|
| 949 | + | /// Build a module node with a declaration appended to its statement list. |
|
| 950 | + | fn injectIntoModule( |
|
| 951 | 951 | blockNode: *ast::Node, |
|
| 952 | 952 | arena: &mut ast::NodeArena, |
|
| 953 | 953 | decl: *ast::Node |
|
| 954 | 954 | ) -> *ast::Node throws (AllocError) { |
|
| 955 | - | let case ast::NodeValue::Block(block) = blockNode.value else { |
|
| 956 | - | panic "injectIntoBlock: expected Block node"; |
|
| 955 | + | let case ast::NodeValue::Module(block) = blockNode.value else { |
|
| 956 | + | panic "injectIntoModule: expected module node"; |
|
| 957 | 957 | }; |
|
| 958 | 958 | let mut stmts = try ast::nodeSlice(arena, block.statements.len + 1); |
|
| 959 | 959 | try stmts.extend(block.statements, arena.heap); |
|
| 960 | 960 | try stmts.append(decl, arena.heap); |
|
| 961 | - | return try ast::allocNode(arena, blockNode.span, ast::NodeValue::Block( |
|
| 962 | - | ast::Block { statements: stmts, isUnsafe: block.isUnsafe } |
|
| 961 | + | return try ast::allocNode(arena, blockNode.span, ast::NodeValue::Module( |
|
| 962 | + | ast::Module { statements: stmts } |
|
| 963 | 963 | )); |
|
| 964 | 964 | } |
|
| 965 | 965 | ||
| 966 | 966 | /// Write a hosted RV64 image: the native header for `layout`, then the code, |
|
| 967 | 967 | /// rodata, and rwdata payloads. |
compiler/radiance/artifact.rad
+175 -176
| 3 | 3 | use std::char; |
|
| 4 | 4 | use std::fmt; |
|
| 5 | 5 | use std::fs; |
|
| 6 | 6 | use std::hash::blake3; |
|
| 7 | 7 | use std::lang::alloc; |
|
| 8 | + | use std::lang::ast; |
|
| 8 | 9 | use std::lang::il::binary; |
|
| 9 | 10 | use std::lang::il::binary::linkage; |
|
| 10 | - | use std::lang::il::binary::writer; |
|
| 11 | + | use std::lang::layout; |
|
| 12 | + | use std::lang::parser; |
|
| 13 | + | use std::lang::pretty; |
|
| 14 | + | use std::lang::scanner; |
|
| 15 | + | use std::lang::sexpr; |
|
| 11 | 16 | use std::mem; |
|
| 12 | 17 | use std::mem::heap; |
|
| 13 | 18 | use std::sys; |
|
| 14 | 19 | ||
| 15 | 20 | /// Version of the artifact descriptor format. |
|
| 16 | 21 | constant VERSION: u32 = 1; |
|
| 17 | 22 | /// Largest artifact metadata, including module and dependency descriptors. |
|
| 18 | 23 | constant MAX_METADATA: u32 = 1048576; |
|
| 19 | 24 | ||
| 20 | - | /// Cursor over the lines of a package metadata file. |
|
| 21 | - | record MetadataReader { |
|
| 22 | - | /// Complete ASCII metadata text. |
|
| 23 | - | text: *[u8], |
|
| 24 | - | /// First unread byte. |
|
| 25 | - | offset: u32, |
|
| 26 | - | } |
|
| 27 | - | ||
| 28 | 25 | /// Content validation required when loading a package artifact set. |
|
| 29 | 26 | export union Validation { |
|
| 30 | 27 | /// Trust content identities recorded in a compiler cache entry. |
|
| 31 | 28 | Trusted, |
|
| 32 | 29 | /// Compare every recorded content identity with its file bytes. |
| 185 | 182 | if let slash = mem::rfind(path, "/") { |
|
| 186 | 183 | try fs::createDirAll(&path[.. slash]); |
|
| 187 | 184 | } |
|
| 188 | 185 | } |
|
| 189 | 186 | ||
| 190 | - | /// Write text into bounded metadata storage. |
|
| 191 | - | fn writeText(out: &mut writer::Writer, text: &[u8]) throws (binary::Error) { |
|
| 192 | - | if text.len > out.bytes.len - out.offset { |
|
| 193 | - | throw binary::Error::Capacity; |
|
| 194 | - | } |
|
| 195 | - | try! mem::copy(&mut out.bytes[out.offset .. out.offset + text.len], text); |
|
| 196 | - | set out.offset += text.len; |
|
| 197 | - | } |
|
| 198 | - | ||
| 199 | - | /// Write a named field. Percent escapes preserve arbitrary path bytes in ASCII. |
|
| 200 | - | fn writeField(out: &mut writer::Writer, key: &[u8], value: &[u8]) |
|
| 187 | + | /// Check a record's type, required fields, and unique field names. |
|
| 188 | + | fn readRecord(node: *ast::Node, name: *[u8], keys: &[*[u8]]) -> ast::RecordLit |
|
| 201 | 189 | throws (binary::Error) |
|
| 202 | 190 | { |
|
| 203 | - | try writeText(out, key); |
|
| 204 | - | try writeText(out, " "); |
|
| 205 | - | for byte in value { |
|
| 206 | - | if char::isPrint(byte) and byte <> '%' { |
|
| 207 | - | try writer::byte(out, byte as u64); |
|
| 208 | - | } else { |
|
| 209 | - | try writer::byte(out, '%' as u64); |
|
| 210 | - | let mut hex: [u8; 2] = [0; 2]; |
|
| 211 | - | try writeText(out, fmt::formatHex(&[byte], &mut hex[..])); |
|
| 191 | + | let case ast::NodeValue::RecordLit(literal) = node.value else throw binary::Error::Invalid; |
|
| 192 | + | if literal.ignoreRest or literal.fields.len <> keys.len { |
|
| 193 | + | throw binary::Error::Invalid; |
|
| 194 | + | } |
|
| 195 | + | if let type = literal.typeName { |
|
| 196 | + | let case ast::NodeValue::Ident(text) = type.value else throw binary::Error::Invalid; |
|
| 197 | + | if not mem::eq(text, name) { |
|
| 198 | + | throw binary::Error::Invalid; |
|
| 212 | 199 | } |
|
| 200 | + | } else if name.len <> 0 { |
|
| 201 | + | throw binary::Error::Invalid; |
|
| 213 | 202 | } |
|
| 214 | - | try writeText(out, "\n"); |
|
| 215 | - | } |
|
| 216 | - | ||
| 217 | - | /// Write an unsigned decimal metadata field. |
|
| 218 | - | fn writeNumber(out: &mut writer::Writer, key: &[u8], value: u32) |
|
| 219 | - | throws (binary::Error) |
|
| 220 | - | { |
|
| 221 | - | let mut buffer: [u8; fmt::U32_STR_LEN] = [0; fmt::U32_STR_LEN]; |
|
| 222 | - | try writeField(out, key, fmt::formatU32(value, &mut buffer[..])); |
|
| 223 | - | } |
|
| 224 | - | ||
| 225 | - | /// Write a content identity as lowercase hexadecimal text. |
|
| 226 | - | fn writeId(out: &mut writer::Writer, key: &[u8], id: binary::Id) |
|
| 227 | - | throws (binary::Error) |
|
| 228 | - | { |
|
| 229 | - | let mut buffer: [u8; 64] = [0; 64]; |
|
| 230 | - | fmt::formatHex(&id.bytes[..], &mut buffer[..]); |
|
| 231 | - | try writeField(out, key, &buffer[..]); |
|
| 232 | - | } |
|
| 233 | - | ||
| 234 | - | /// Read canonical lowercase hexadecimal bytes from a metadata field. |
|
| 235 | - | fn readHex(text: &[u8], bytes: &mut [u8]) throws (binary::Error) { |
|
| 236 | - | for byte in text { |
|
| 237 | - | if char::toLower(byte) <> byte { |
|
| 203 | + | for key in keys { |
|
| 204 | + | let mut count: u32 = 0; |
|
| 205 | + | for field in literal.fields { |
|
| 206 | + | let case ast::NodeValue::RecordLitField(arg) = field.value |
|
| 207 | + | else throw binary::Error::Invalid; |
|
| 208 | + | let label = arg.label else throw binary::Error::Invalid; |
|
| 209 | + | let case ast::NodeValue::Ident(text) = label.value else throw binary::Error::Invalid; |
|
| 210 | + | if mem::eq(text, key) { |
|
| 211 | + | set count += 1; |
|
| 212 | + | } |
|
| 213 | + | } |
|
| 214 | + | if count <> 1 { |
|
| 238 | 215 | throw binary::Error::Invalid; |
|
| 239 | 216 | } |
|
| 240 | 217 | } |
|
| 241 | - | try fmt::parseHex(text, bytes) catch { |
|
| 242 | - | throw binary::Error::Invalid; |
|
| 243 | - | }; |
|
| 218 | + | return literal; |
|
| 244 | 219 | } |
|
| 245 | 220 | ||
| 246 | - | /// Read a named ASCII field and decode its percent escapes. |
|
| 247 | - | fn readField(input: &mut MetadataReader, key: &[u8], arena: &heap::Heap) -> *[u8] |
|
| 221 | + | /// Get a required record field by name. |
|
| 222 | + | fn fieldNode(literal: &ast::RecordLit, key: *[u8]) -> *ast::Node |
|
| 248 | 223 | throws (binary::Error) |
|
| 249 | 224 | { |
|
| 250 | - | let start = input.offset; |
|
| 251 | - | while input.offset < input.text.len and input.text[input.offset] <> '\n' { |
|
| 252 | - | let byte = input.text[input.offset]; |
|
| 253 | - | if not char::isPrint(byte) { |
|
| 254 | - | throw binary::Error::Invalid; |
|
| 225 | + | for field in literal.fields { |
|
| 226 | + | let case ast::NodeValue::RecordLitField(arg) = field.value |
|
| 227 | + | else throw binary::Error::Invalid; |
|
| 228 | + | let label = arg.label else throw binary::Error::Invalid; |
|
| 229 | + | let case ast::NodeValue::Ident(text) = label.value else throw binary::Error::Invalid; |
|
| 230 | + | if mem::eq(text, key) { |
|
| 231 | + | return arg.value; |
|
| 255 | 232 | } |
|
| 256 | - | set input.offset += 1; |
|
| 257 | - | } |
|
| 258 | - | if input.offset == input.text.len { |
|
| 259 | - | throw binary::Error::Truncated; |
|
| 260 | - | } |
|
| 261 | - | let line = &input.text[start .. input.offset]; |
|
| 262 | - | set input.offset += 1; |
|
| 263 | - | if line.len <= key.len |
|
| 264 | - | or not mem::eq(&line[.. key.len], key) |
|
| 265 | - | or line[key.len] <> ' ' |
|
| 266 | - | { |
|
| 267 | - | throw binary::Error::Invalid; |
|
| 268 | - | } |
|
| 269 | - | let value = &line[key.len + 1 ..]; |
|
| 270 | - | if mem::find(value, "%") == nil { |
|
| 271 | - | return value; |
|
| 272 | 233 | } |
|
| 273 | - | let mut decoded: *mut [u8] = &mut []; |
|
| 274 | - | let mut i: u32 = 0; |
|
| 275 | - | while i < value.len { |
|
| 276 | - | let mut byte = value[i]; |
|
| 277 | - | if byte == '%' { |
|
| 278 | - | if value.len - i < 3 { |
|
| 279 | - | throw binary::Error::Invalid; |
|
| 280 | - | } |
|
| 281 | - | let mut escaped: [u8; 1] = [0; 1]; |
|
| 282 | - | try readHex(&value[i + 1 .. i + 3], &mut escaped[..]); |
|
| 283 | - | set byte = escaped[0]; |
|
| 284 | - | set i += 2; |
|
| 285 | - | } |
|
| 286 | - | try decoded.append(byte, arena) catch { |
|
| 287 | - | throw binary::Error::Storage; |
|
| 288 | - | }; |
|
| 289 | - | set i += 1; |
|
| 290 | - | } |
|
| 291 | - | return &decoded[..]; |
|
| 234 | + | throw binary::Error::Invalid; |
|
| 292 | 235 | } |
|
| 293 | 236 | ||
| 294 | - | /// Read an unsigned decimal field with checked 32-bit arithmetic. |
|
| 295 | - | fn readNumber(input: &mut MetadataReader, key: &[u8], arena: &heap::Heap) -> u32 |
|
| 296 | - | throws (binary::Error) |
|
| 297 | - | { |
|
| 298 | - | let value = try fmt::parseUint(try readField(input, key, arena), 10) catch { |
|
| 299 | - | throw binary::Error::Invalid; |
|
| 300 | - | }; |
|
| 301 | - | if value > mem::U32_MAX as u64 { |
|
| 237 | + | /// Read a decoded string literal. |
|
| 238 | + | fn readString(node: *ast::Node) -> *[u8] throws (binary::Error) { |
|
| 239 | + | let case ast::NodeValue::String(text) = node.value else throw binary::Error::Invalid; |
|
| 240 | + | return text; |
|
| 241 | + | } |
|
| 242 | + | ||
| 243 | + | /// Read an unsigned 32-bit integer literal. |
|
| 244 | + | fn readNumber(node: *ast::Node) -> u32 throws (binary::Error) { |
|
| 245 | + | let case ast::NodeValue::Number(value) = node.value else throw binary::Error::Invalid; |
|
| 246 | + | if value.magnitude > 0xffffffff { |
|
| 302 | 247 | throw binary::Error::Invalid; |
|
| 303 | 248 | } |
|
| 304 | - | return value as u32; |
|
| 249 | + | return value.magnitude as u32; |
|
| 305 | 250 | } |
|
| 306 | 251 | ||
| 307 | - | /// Bound a table count by the unread metadata before allocating entries. |
|
| 308 | - | fn readCount(input: &mut MetadataReader, key: &[u8], arena: &heap::Heap) -> u32 |
|
| 309 | - | throws (binary::Error) |
|
| 310 | - | { |
|
| 311 | - | let count = try readNumber(input, key, arena); |
|
| 312 | - | if count > input.text.len - input.offset { |
|
| 313 | - | throw binary::Error::Truncated; |
|
| 314 | - | } |
|
| 315 | - | return count; |
|
| 252 | + | /// Read an array literal without evaluating expressions. |
|
| 253 | + | fn readArray(node: *ast::Node) -> *[*ast::Node] throws (binary::Error) { |
|
| 254 | + | let case ast::NodeValue::ArrayLit(items) = node.value else throw binary::Error::Invalid; |
|
| 255 | + | return items; |
|
| 316 | 256 | } |
|
| 317 | 257 | ||
| 318 | - | /// Read a 256-bit content identity from lowercase hexadecimal text. |
|
| 319 | - | fn readId(input: &mut MetadataReader, key: &[u8], arena: &heap::Heap) -> binary::Id |
|
| 320 | - | throws (binary::Error) |
|
| 321 | - | { |
|
| 322 | - | let text = try readField(input, key, arena); |
|
| 258 | + | /// Read a 256-bit content identity from a hexadecimal string. |
|
| 259 | + | fn readId(node: *ast::Node) -> binary::Id throws (binary::Error) { |
|
| 260 | + | let text = try readString(node); |
|
| 323 | 261 | if text.len <> 64 { |
|
| 324 | 262 | throw binary::Error::Invalid; |
|
| 325 | 263 | } |
|
| 326 | 264 | let mut id = binary::Id { bytes: [0; 32] }; |
|
| 327 | - | try readHex(text, &mut id.bytes[..]); |
|
| 265 | + | try fmt::parseHex(text, &mut id.bytes[..]) catch { |
|
| 266 | + | throw binary::Error::Invalid; |
|
| 267 | + | }; |
|
| 328 | 268 | return id; |
|
| 329 | 269 | } |
|
| 330 | 270 | ||
| 331 | - | /// Encode the descriptors that bind all interface files and the image. |
|
| 332 | - | export fn metadata(package: &Package, buffer: *mut [u8]) -> *[u8] |
|
| 333 | - | throws (binary::Error) |
|
| 271 | + | /// Format package metadata as a record literal. |
|
| 272 | + | /// The arena holds temporary AST nodes, literal text, and layout data. |
|
| 273 | + | export fn metadata(package: &Package, buffer: *mut [u8], arena: *heap::Heap) -> *[u8] |
|
| 274 | + | throws (alloc::AllocError, binary::Error) |
|
| 334 | 275 | { |
|
| 335 | - | let mut out = writer::new(buffer); |
|
| 336 | - | try writeNumber(&mut out, "version", VERSION); |
|
| 337 | - | try writeField(&mut out, "package", package.name); |
|
| 338 | - | try writeId(&mut out, "inputs", package.inputs); |
|
| 339 | - | try writeId(&mut out, "image", package.identity); |
|
| 340 | - | try writeNumber(&mut out, "size", package.image.len); |
|
| 341 | - | try writeNumber(&mut out, "modules", package.modules.len); |
|
| 276 | + | let mut nodes = ast::NodeArena { heap: arena, nextId: 0 }; |
|
| 277 | + | let mut modules: *mut [*ast::Node] = &mut []; |
|
| 278 | + | let mut files: *mut [*ast::Node] = &mut []; |
|
| 279 | + | let mut dependencies: *mut [*ast::Node] = &mut []; |
|
| 342 | 280 | for module in package.modules { |
|
| 343 | - | try writeField(&mut out, "module", module.path); |
|
| 344 | - | try writeNumber(&mut out, "size", module.text.len); |
|
| 345 | - | try writeId(&mut out, "hash", module.hash); |
|
| 281 | + | let node = try ast::synthRecord( |
|
| 282 | + | &mut nodes, |
|
| 283 | + | "Module", |
|
| 284 | + | &[ |
|
| 285 | + | ast::field("path", ast::stringValue(module.path)), |
|
| 286 | + | ast::field("size", try ast::numberValue(module.text.len as u64, arena)), |
|
| 287 | + | ast::field("hash", try ast::hexStringValue(&module.hash.bytes[..], arena)), |
|
| 288 | + | ] |
|
| 289 | + | ); |
|
| 290 | + | try modules.append(node, arena); |
|
| 346 | 291 | } |
|
| 347 | - | try writeNumber(&mut out, "files", package.files.len); |
|
| 348 | 292 | for file in package.files { |
|
| 349 | - | try writeField(&mut out, "file", file.path); |
|
| 350 | - | try writeField(&mut out, "origin", file.origin); |
|
| 351 | - | try writeNumber(&mut out, "role", file.role as u32); |
|
| 352 | - | try writeNumber(&mut out, "size", file.bytes.len); |
|
| 353 | - | try writeId(&mut out, "hash", digest(file.bytes)); |
|
| 293 | + | let node = try ast::synthRecord( |
|
| 294 | + | &mut nodes, |
|
| 295 | + | "File", |
|
| 296 | + | &[ |
|
| 297 | + | ast::field("path", ast::stringValue(file.path)), |
|
| 298 | + | ast::field("origin", ast::stringValue(file.origin)), |
|
| 299 | + | ast::field("role", try ast::numberValue(file.role as u64, arena)), |
|
| 300 | + | ast::field("size", try ast::numberValue(file.bytes.len as u64, arena)), |
|
| 301 | + | ast::field("hash", try ast::hexStringValue(&digest(file.bytes).bytes[..], arena)), |
|
| 302 | + | ] |
|
| 303 | + | ); |
|
| 304 | + | try files.append(node, arena); |
|
| 354 | 305 | } |
|
| 355 | - | try writeNumber(&mut out, "dependencies", package.dependencies.len); |
|
| 356 | 306 | for dependency in package.dependencies { |
|
| 357 | - | try writeField(&mut out, "dependency", dependency.name); |
|
| 358 | - | try writeId(&mut out, "image", dependency.image); |
|
| 359 | - | try writeId(&mut out, "declarations", dependency.declarations); |
|
| 307 | + | let node = try ast::synthRecord( |
|
| 308 | + | &mut nodes, |
|
| 309 | + | "Dependency", |
|
| 310 | + | &[ |
|
| 311 | + | ast::field("name", ast::stringValue(dependency.name)), |
|
| 312 | + | ast::field("image", try ast::hexStringValue(&dependency.image.bytes[..], arena)), |
|
| 313 | + | ast::field( |
|
| 314 | + | "declarations", |
|
| 315 | + | try ast::hexStringValue(&dependency.declarations.bytes[..], arena) |
|
| 316 | + | ), |
|
| 317 | + | ] |
|
| 318 | + | ); |
|
| 319 | + | try dependencies.append(node, arena); |
|
| 320 | + | } |
|
| 321 | + | let root = try ast::synthRecord( |
|
| 322 | + | &mut nodes, |
|
| 323 | + | "Package", |
|
| 324 | + | &[ |
|
| 325 | + | ast::field("version", try ast::numberValue(VERSION as u64, arena)), |
|
| 326 | + | ast::field("name", ast::stringValue(package.name)), |
|
| 327 | + | ast::field("inputs", try ast::hexStringValue(&package.inputs.bytes[..], arena)), |
|
| 328 | + | ast::field("image", try ast::hexStringValue(&package.identity.bytes[..], arena)), |
|
| 329 | + | ast::field("size", try ast::numberValue(package.image.len as u64, arena)), |
|
| 330 | + | ast::field("modules", ast::arrayValue(&modules[..])), |
|
| 331 | + | ast::field("files", ast::arrayValue(&files[..])), |
|
| 332 | + | ast::field("dependencies", ast::arrayValue(&dependencies[..])), |
|
| 333 | + | ] |
|
| 334 | + | ); |
|
| 335 | + | let tree = try pretty::expression(root, arena); |
|
| 336 | + | let mut out = sexpr::Buffer { buf: buffer, pos: 0 }; |
|
| 337 | + | { |
|
| 338 | + | let sink: &mut opaque sexpr::Output = &mut out; |
|
| 339 | + | layout::text::render(tree, layout::text::Options { width: 80, indent: 4 }, sink); |
|
| 360 | 340 | } |
|
| 361 | - | return &out.bytes[.. out.offset]; |
|
| 341 | + | if out.pos >= out.buf.len { |
|
| 342 | + | throw binary::Error::Capacity; |
|
| 343 | + | } |
|
| 344 | + | return &out.buf[.. out.pos]; |
|
| 362 | 345 | } |
|
| 363 | 346 | ||
| 364 | 347 | /// Read package files and check their metadata with the selected content validation. |
|
| 365 | 348 | export fn read( |
|
| 366 | - | root: *[u8], name: *[u8], validation: Validation, arena: &heap::Heap |
|
| 349 | + | root: *[u8], |
|
| 350 | + | name: *[u8], |
|
| 351 | + | validation: Validation, |
|
| 352 | + | syntax: &mut parser::Parser, |
|
| 353 | + | arena: &heap::Heap |
|
| 367 | 354 | ) -> Package throws (sys::Error) { |
|
| 368 | 355 | let tree = try join(arena, &[root, "/", name, ".interface/"]); |
|
| 369 | 356 | let path = try join(arena, &[tree, "package.metadata"]); |
|
| 370 | 357 | let info = try fs::stat(path) else throw sys::Error::NotFound; |
|
| 371 | 358 | if info.size > MAX_METADATA as u64 { |
|
| 372 | 359 | throw sys::Error::Invalid; |
|
| 373 | 360 | } |
|
| 374 | - | let encoded = try readFile(path, arena); |
|
| 361 | + | // Interned names point into metadata source for the life of the parser. |
|
| 362 | + | let encoded = try readFile(path, syntax.arena.heap); |
|
| 375 | 363 | return try decode( |
|
| 376 | - | root, tree, name, encoded, validation, arena |
|
| 364 | + | root, tree, name, encoded, validation, syntax, arena |
|
| 377 | 365 | ) catch err as binary::Error { |
|
| 378 | 366 | if err == binary::Error::Storage { |
|
| 379 | 367 | throw sys::Error::TooLarge; |
|
| 380 | 368 | } |
|
| 381 | 369 | throw sys::Error::Invalid; |
| 389 | 377 | root: *[u8], |
|
| 390 | 378 | tree: *[u8], |
|
| 391 | 379 | name: *[u8], |
|
| 392 | 380 | encoded: *[u8], |
|
| 393 | 381 | validation: Validation, |
|
| 382 | + | syntax: &mut parser::Parser, |
|
| 394 | 383 | arena: &heap::Heap |
|
| 395 | 384 | ) -> Package throws (binary::Error, sys::Error) { |
|
| 396 | - | let mut input = MetadataReader { text: encoded, offset: 0 }; |
|
| 397 | - | if try readNumber(&mut input, "version", arena) <> VERSION |
|
| 398 | - | or not mem::eq(try readField(&mut input, "package", arena), name) |
|
| 385 | + | let value = try parser::parseValue( |
|
| 386 | + | syntax, scanner::SourceLoc::String, encoded |
|
| 387 | + | ) catch err { |
|
| 388 | + | if err == parser::ParseError::AllocationFailed { |
|
| 389 | + | throw binary::Error::Storage; |
|
| 390 | + | } |
|
| 391 | + | throw binary::Error::Invalid; |
|
| 392 | + | }; |
|
| 393 | + | let literal = try readRecord(value, "Package", &[ |
|
| 394 | + | "version", "name", "inputs", "image", "size", "modules", "files", "dependencies" |
|
| 395 | + | ]); |
|
| 396 | + | if try readNumber(try fieldNode(&literal, "version")) <> VERSION |
|
| 397 | + | or not mem::eq(try readString(try fieldNode(&literal, "name")), name) |
|
| 399 | 398 | { |
|
| 400 | 399 | throw binary::Error::Invalid; |
|
| 401 | 400 | } |
|
| 402 | - | let inputs = try readId(&mut input, "inputs", arena); |
|
| 403 | - | let identity = try readId(&mut input, "image", arena); |
|
| 404 | - | let length = try readNumber(&mut input, "size", arena); |
|
| 401 | + | let inputs = try readId(try fieldNode(&literal, "inputs")); |
|
| 402 | + | let identity = try readId(try fieldNode(&literal, "image")); |
|
| 403 | + | let length = try readNumber(try fieldNode(&literal, "size")); |
|
| 405 | 404 | let image = try readFile(try join(arena, &[root, "/", name, ".ril"]), arena); |
|
| 406 | 405 | if image.len <> length |
|
| 407 | 406 | or image.len < 12 |
|
| 408 | 407 | or mem::load32Le(image, 0) <> binary::MAGIC |
|
| 409 | 408 | or mem::load32Le(image, 4) <> binary::FORMAT_VERSION |
|
| 410 | 409 | or mem::load32Le(image, 8) <> binary::ABI_VERSION |
|
| 411 | 410 | or (validation == Validation::Full and linkage::imageId(image) <> identity) |
|
| 412 | 411 | { |
|
| 413 | 412 | throw binary::Error::Invalid; |
|
| 414 | 413 | } |
|
| 415 | - | let count = try readCount(&mut input, "modules", arena); |
|
| 416 | - | if count == 0 { |
|
| 414 | + | let moduleNodes = try readArray(try fieldNode(&literal, "modules")); |
|
| 415 | + | if moduleNodes.len == 0 { |
|
| 417 | 416 | throw binary::Error::Invalid; |
|
| 418 | 417 | } |
|
| 419 | 418 | let mut modules: *mut [Module] = &mut []; |
|
| 420 | - | for i in 0 .. count { |
|
| 421 | - | let path = try readField(&mut input, "module", arena); |
|
| 422 | - | let length = try readNumber(&mut input, "size", arena); |
|
| 423 | - | let hash = try readId(&mut input, "hash", arena); |
|
| 419 | + | for node, i in moduleNodes { |
|
| 420 | + | let descriptor = try readRecord(node, "Module", &["path", "size", "hash"]); |
|
| 421 | + | let path = try readString(try fieldNode(&descriptor, "path")); |
|
| 422 | + | let length = try readNumber(try fieldNode(&descriptor, "size")); |
|
| 423 | + | let hash = try readId(try fieldNode(&descriptor, "hash")); |
|
| 424 | 424 | if not validPath(path) or not mem::endsWith(path, ".rid") { |
|
| 425 | 425 | throw binary::Error::Invalid; |
|
| 426 | 426 | } |
|
| 427 | 427 | for j in 0 .. modules.len { |
|
| 428 | 428 | if mem::eq(modules[j].path, path) { |
| 442 | 442 | } |
|
| 443 | 443 | try modules.append(Module { path, text, hash }, arena) catch { |
|
| 444 | 444 | throw binary::Error::Storage; |
|
| 445 | 445 | }; |
|
| 446 | 446 | } |
|
| 447 | - | let fileCount = try readCount(&mut input, "files", arena); |
|
| 447 | + | let fileNodes = try readArray(try fieldNode(&literal, "files")); |
|
| 448 | 448 | let mut files: *mut [File] = &mut []; |
|
| 449 | - | for _ in 0 .. fileCount { |
|
| 450 | - | let path = try readField(&mut input, "file", arena); |
|
| 451 | - | let origin = try readField(&mut input, "origin", arena); |
|
| 452 | - | let kind = try readNumber(&mut input, "role", arena); |
|
| 449 | + | for node in fileNodes { |
|
| 450 | + | let descriptor = try readRecord(node, "File", &["path", "origin", "role", "size", "hash"]); |
|
| 451 | + | let path = try readString(try fieldNode(&descriptor, "path")); |
|
| 452 | + | let origin = try readString(try fieldNode(&descriptor, "origin")); |
|
| 453 | + | let kind = try readNumber(try fieldNode(&descriptor, "role")); |
|
| 453 | 454 | if not validPath(path) or kind > 2 { |
|
| 454 | 455 | throw binary::Error::Invalid; |
|
| 455 | 456 | } |
|
| 456 | 457 | for i in 0 .. files.len { |
|
| 457 | 458 | if mem::eq(files[i].path, path) { |
| 464 | 465 | } |
|
| 465 | 466 | } |
|
| 466 | 467 | if mem::eq(path, "package.metadata") { |
|
| 467 | 468 | throw binary::Error::Invalid; |
|
| 468 | 469 | } |
|
| 469 | - | let length = try readNumber(&mut input, "size", arena); |
|
| 470 | - | let hash = try readId(&mut input, "hash", arena); |
|
| 470 | + | let length = try readNumber(try fieldNode(&descriptor, "size")); |
|
| 471 | + | let hash = try readId(try fieldNode(&descriptor, "hash")); |
|
| 471 | 472 | let bytes = try readFile(try join(arena, &[tree, path]), arena); |
|
| 472 | 473 | if bytes.len <> length or (validation == Validation::Full and digest(bytes) <> hash) { |
|
| 473 | 474 | throw binary::Error::Invalid; |
|
| 474 | 475 | } |
|
| 475 | 476 | let role = FileRole::Startup |
| 479 | 480 | else FileRole::Assembly; |
|
| 480 | 481 | try files.append(File { path, origin, bytes, role }, arena) catch { |
|
| 481 | 482 | throw binary::Error::Storage; |
|
| 482 | 483 | }; |
|
| 483 | 484 | } |
|
| 484 | - | let depCount = try readCount(&mut input, "dependencies", arena); |
|
| 485 | + | let dependencyNodes = try readArray(try fieldNode(&literal, "dependencies")); |
|
| 485 | 486 | let mut dependencies: *mut [Dependency] = &mut []; |
|
| 486 | - | for _ in 0 .. depCount { |
|
| 487 | - | let name = try readField(&mut input, "dependency", arena); |
|
| 487 | + | for node in dependencyNodes { |
|
| 488 | + | let descriptor = try readRecord(node, "Dependency", &["name", "image", "declarations"]); |
|
| 489 | + | let name = try readString(try fieldNode(&descriptor, "name")); |
|
| 488 | 490 | if not validPath(name) { |
|
| 489 | 491 | throw binary::Error::Invalid; |
|
| 490 | 492 | } |
|
| 491 | 493 | for i in 0 .. dependencies.len { |
|
| 492 | 494 | if mem::eq(dependencies[i].name, name) { |
| 496 | 498 | for byte in name { |
|
| 497 | 499 | if byte == '/' or byte == '.' { |
|
| 498 | 500 | throw binary::Error::Invalid; |
|
| 499 | 501 | } |
|
| 500 | 502 | } |
|
| 501 | - | let image = try readId(&mut input, "image", arena); |
|
| 502 | - | let declarations = try readId(&mut input, "declarations", arena); |
|
| 503 | + | let image = try readId(try fieldNode(&descriptor, "image")); |
|
| 504 | + | let declarations = try readId(try fieldNode(&descriptor, "declarations")); |
|
| 503 | 505 | try dependencies.append(Dependency { name, image, declarations }, arena) catch { |
|
| 504 | 506 | throw binary::Error::Storage; |
|
| 505 | 507 | }; |
|
| 506 | 508 | } |
|
| 507 | - | if input.offset <> input.text.len { |
|
| 508 | - | throw binary::Error::Invalid; |
|
| 509 | - | } |
|
| 510 | 509 | let mut package = Package { |
|
| 511 | 510 | name, |
|
| 512 | 511 | image, |
|
| 513 | 512 | identity, |
|
| 514 | 513 | modules: &modules[..], |
compiler/radiance/build.rad
+20 -12
| 201 | 201 | }; |
|
| 202 | 202 | } |
|
| 203 | 203 | return &names[..]; |
|
| 204 | 204 | } |
|
| 205 | 205 | ||
| 206 | - | /// Capture immutable inputs without entering the implementation parser. |
|
| 207 | - | fn snapshot(options: super::PackageInput, arena: &heap::Heap, artifacts: &heap::Heap) -> Input |
|
| 206 | + | /// Capture source snapshots and load compiled package metadata. |
|
| 207 | + | fn snapshot( |
|
| 208 | + | options: super::PackageInput, |
|
| 209 | + | syntax: &mut parser::Parser, |
|
| 210 | + | arena: &heap::Heap, |
|
| 211 | + | artifacts: &heap::Heap |
|
| 212 | + | ) -> Input |
|
| 208 | 213 | throws (sys::Error) |
|
| 209 | 214 | { |
|
| 210 | 215 | if let root = options.artifactRoot { |
|
| 211 | 216 | let compiled = try artifact::read( |
|
| 212 | - | root, options.name, artifact::Validation::Full, artifacts |
|
| 217 | + | root, options.name, artifact::Validation::Full, syntax, artifacts |
|
| 213 | 218 | ); |
|
| 214 | 219 | let mut dependencies: *mut [*[u8]] = &mut []; |
|
| 215 | 220 | for dependency in compiled.dependencies { |
|
| 216 | 221 | try dependencies.append(dependency.name, arena) catch { |
|
| 217 | 222 | throw sys::Error::TooLarge; |
| 288 | 293 | } |
|
| 289 | 294 | return nil; |
|
| 290 | 295 | } |
|
| 291 | 296 | ||
| 292 | 297 | /// Resolve and sort the graph, including source-free transitive artifact providers. |
|
| 293 | - | fn inputs(ctx: &super::CompileContext, arena: &heap::Heap, artifacts: &heap::Heap) -> *[Input] |
|
| 298 | + | fn inputs(ctx: &mut super::CompileContext, arena: &heap::Heap, artifacts: &heap::Heap) -> *[Input] |
|
| 294 | 299 | throws (sys::Error) |
|
| 295 | 300 | { |
|
| 296 | 301 | let mut selected: *mut [Input] = &mut []; |
|
| 297 | 302 | for i in 0 .. ctx.packageCount { |
|
| 298 | 303 | let checked = try dependencyNames(ctx.inputs[i].name, arena); |
| 302 | 307 | for j in 0 .. i { |
|
| 303 | 308 | if mem::eq(ctx.inputs[j].name, ctx.inputs[i].name) { |
|
| 304 | 309 | throw sys::Error::Invalid; |
|
| 305 | 310 | } |
|
| 306 | 311 | } |
|
| 307 | - | try selected.append(try snapshot(ctx.inputs[i], arena, artifacts), arena) catch { |
|
| 312 | + | try selected.append( |
|
| 313 | + | try snapshot(ctx.inputs[i], &mut ctx.parser, arena, artifacts), arena |
|
| 314 | + | ) catch { |
|
| 308 | 315 | throw sys::Error::TooLarge; |
|
| 309 | 316 | }; |
|
| 310 | 317 | } |
|
| 311 | 318 | let mut i: u32 = 0; |
|
| 312 | 319 | while i < selected.len { |
| 324 | 331 | if selected.len >= package::MAX_PACKAGES { |
|
| 325 | 332 | throw sys::Error::TooLarge; |
|
| 326 | 333 | } |
|
| 327 | 334 | let mut options = super::packageInput(name); |
|
| 328 | 335 | set options.artifactRoot = root; |
|
| 329 | - | let provider = try snapshot(options, arena, artifacts); |
|
| 336 | + | let provider = try snapshot(options, &mut ctx.parser, arena, artifacts); |
|
| 330 | 337 | try selected.append(provider, arena) catch { |
|
| 331 | 338 | throw sys::Error::TooLarge; |
|
| 332 | 339 | }; |
|
| 333 | 340 | } |
|
| 334 | 341 | set i += 1; |
| 660 | 667 | compiler |
|
| 661 | 668 | ); |
|
| 662 | 669 | let mut cached: ?artifact::Package = nil; |
|
| 663 | 670 | if let root = ctx.cacheDirectory { |
|
| 664 | 671 | set cached = try cache::lookup( |
|
| 665 | - | root, input.options.name, request, work.artifacts |
|
| 672 | + | root, input.options.name, request, &mut ctx.parser, work.artifacts |
|
| 666 | 673 | ) catch { |
|
| 667 | 674 | throw super::error(&["cannot read package cache"]); |
|
| 668 | 675 | }; |
|
| 669 | 676 | } |
|
| 670 | 677 | if let package = cached { |
| 724 | 731 | throw super::error(&["native data storage exhausted"]); |
|
| 725 | 732 | }; |
|
| 726 | 733 | set fresh = true; |
|
| 727 | 734 | if let root = ctx.cacheDirectory { |
|
| 728 | 735 | // Function storage has no live IL after its sink consumed each function. |
|
| 729 | - | try cache::publish(root, &built, work.functions) catch { |
|
| 736 | + | try cache::publish(root, &built, &mut ctx.parser, work.functions) catch { |
|
| 730 | 737 | throw super::error(&["cannot publish package cache", built.name]); |
|
| 731 | 738 | }; |
|
| 732 | 739 | unsafe { |
|
| 733 | 740 | heap::reset(work.functions); |
|
| 734 | 741 | } |
| 845 | 852 | ||
| 846 | 853 | /// Format callable provider declarations and functions used by retained declarations. |
|
| 847 | 854 | fn interface( |
|
| 848 | 855 | root: *ast::Node, res: &resolver::Resolver, arena: *heap::Heap |
|
| 849 | 856 | ) -> *layout::Layout throws (alloc::AllocError) { |
|
| 850 | - | let case ast::NodeValue::Block(block) = root.value else panic "interface: expected module root"; |
|
| 857 | + | let case ast::NodeValue::Module(block) = root.value |
|
| 858 | + | else panic "interface: expected module root"; |
|
| 851 | 859 | let mut declarations: *mut [*ast::Node] = &mut []; |
|
| 852 | 860 | for node in block.statements { |
|
| 853 | 861 | if let case ast::NodeValue::FnDecl(decl) = node.value { |
|
| 854 | 862 | let symbol = resolver::symbolFor(res, node) else continue; |
|
| 855 | 863 | let attrs = res.symbols[*symbol].attrs; |
| 863 | 871 | } |
|
| 864 | 872 | } |
|
| 865 | 873 | try declarations.append(node, arena); |
|
| 866 | 874 | } |
|
| 867 | 875 | let mut nodes = ast::NodeArena { heap: arena, nextId: 0 }; |
|
| 868 | - | let module = try ast::synthNode(&mut nodes, ast::NodeValue::Block(ast::Block { |
|
| 869 | - | statements: &declarations[..], isUnsafe: false |
|
| 876 | + | let module = try ast::synthNode(&mut nodes, ast::NodeValue::Module(ast::Module { |
|
| 877 | + | statements: &declarations[..] |
|
| 870 | 878 | })); |
|
| 871 | 879 | return try pretty::interface(module, arena); |
|
| 872 | 880 | } |
|
| 873 | 881 | ||
| 874 | 882 | /// Produce an immutable package image and compiler declaration set. |
| 1114 | 1122 | inputs: request, |
|
| 1115 | 1123 | declarations: binary::Id { bytes: [0; linkage::ID_BYTES] }, |
|
| 1116 | 1124 | metadata: "", |
|
| 1117 | 1125 | }; |
|
| 1118 | 1126 | set result.declarations = artifact::declarations(&result); |
|
| 1119 | - | let metadata = try artifact::metadata(&result, head.take()) catch { |
|
| 1127 | + | let metadata = try artifact::metadata(&result, head.take(), work.functions) catch { |
|
| 1120 | 1128 | throw super::error(&["package encoding storage exhausted", pkg.name]); |
|
| 1121 | 1129 | }; |
|
| 1122 | 1130 | set result.metadata = try keep(work.artifacts, metadata) catch { |
|
| 1123 | 1131 | throw super::error(&["package encoding storage exhausted", pkg.name]); |
|
| 1124 | 1132 | }; |
compiler/radiance/cache.rad
+20 -6
| 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; |
|
| 7 | 8 | use std::mem; |
|
| 8 | 9 | use std::mem::heap; |
|
| 9 | 10 | use std::sys; |
|
| 10 | 11 | use super::artifact; |
|
| 11 | 12 |
| 23 | 24 | } |
|
| 24 | 25 | ||
| 25 | 26 | /// Load a cache entry using its recorded content identities. |
|
| 26 | 27 | /// Missing files and invalid metadata are misses; unrelated I/O errors propagate. |
|
| 27 | 28 | export fn lookup( |
|
| 28 | - | root: *[u8], name: *[u8], key: binary::Id, arena: &heap::Heap |
|
| 29 | + | root: *[u8], |
|
| 30 | + | name: *[u8], |
|
| 31 | + | key: binary::Id, |
|
| 32 | + | syntax: &mut parser::Parser, |
|
| 33 | + | arena: &heap::Heap |
|
| 29 | 34 | ) -> ?artifact::Package throws (sys::Error) { |
|
| 30 | 35 | let saved = heap::mark(arena); |
|
| 31 | 36 | let path = try entry(root, key, arena); |
|
| 32 | 37 | let result = try artifact::read( |
|
| 33 | - | path, name, artifact::Validation::Trusted, arena |
|
| 38 | + | path, name, artifact::Validation::Trusted, syntax, arena |
|
| 34 | 39 | ) catch error { |
|
| 35 | 40 | // Failed reads publish no pointers into their temporary allocations. |
|
| 36 | 41 | unsafe { |
|
| 37 | 42 | heap::rewind(arena, saved); |
|
| 38 | 43 | } |
| 72 | 77 | } |
|
| 73 | 78 | throw sys::Error::Limit; |
|
| 74 | 79 | } |
|
| 75 | 80 | ||
| 76 | 81 | /// Write a private complete set, then make it visible with one directory rename. |
|
| 77 | - | export fn publish(root: *[u8], package: &artifact::Package, arena: &heap::Heap) |
|
| 82 | + | export fn publish( |
|
| 83 | + | root: *[u8], package: &artifact::Package, syntax: &mut parser::Parser, arena: &heap::Heap |
|
| 84 | + | ) |
|
| 78 | 85 | throws (sys::Error) |
|
| 79 | 86 | { |
|
| 80 | 87 | let path = try entry(root, package.inputs, arena); |
|
| 81 | 88 | try artifact::directories(try artifact::join(arena, &[root, "/"])); |
|
| 82 | 89 | let stage = try temporary(path, arena); |
|
| 83 | 90 | try artifact::write(package, stage, arena) catch error { |
|
| 84 | 91 | try fs::removeTree(stage, arena) catch {}; |
|
| 85 | 92 | throw error; |
|
| 86 | 93 | }; |
|
| 87 | - | try install(root, path, stage, package, arena) catch error { |
|
| 94 | + | try install(root, path, stage, package, syntax, arena) catch error { |
|
| 88 | 95 | try fs::removeTree(stage, arena) catch {}; |
|
| 89 | 96 | throw error; |
|
| 90 | 97 | }; |
|
| 91 | 98 | } |
|
| 92 | 99 | ||
| 93 | 100 | /// Install one complete set, retrying a concurrent repair or publication. |
|
| 94 | 101 | fn install( |
|
| 95 | - | root: *[u8], path: *[u8], stage: *[u8], package: &artifact::Package, arena: &heap::Heap |
|
| 102 | + | root: *[u8], |
|
| 103 | + | path: *[u8], |
|
| 104 | + | stage: *[u8], |
|
| 105 | + | package: &artifact::Package, |
|
| 106 | + | syntax: &mut parser::Parser, |
|
| 107 | + | arena: &heap::Heap |
|
| 96 | 108 | ) throws (sys::Error) { |
|
| 97 | 109 | for _ in 0 .. TEMPORARY_SLOTS { |
|
| 98 | 110 | try fs::rename(stage, path) catch error { |
|
| 99 | 111 | if error <> sys::Error::NotEmpty |
|
| 100 | 112 | and error <> sys::Error::Exists |
| 103 | 115 | throw error; |
|
| 104 | 116 | } |
|
| 105 | 117 | if try fs::stat(path) == nil { |
|
| 106 | 118 | continue; |
|
| 107 | 119 | } |
|
| 108 | - | let existing = try lookup(root, package.name, package.inputs, arena); |
|
| 120 | + | let existing = try lookup( |
|
| 121 | + | root, package.name, package.inputs, syntax, arena |
|
| 122 | + | ); |
|
| 109 | 123 | if existing <> nil { |
|
| 110 | 124 | try fs::removeTree(stage, arena); |
|
| 111 | 125 | return; |
|
| 112 | 126 | } |
|
| 113 | 127 | // Quarantine the damaged set before installing its complete replacement. |
compiler/radiance/testgen.rad
+1 -1
| 31 | 31 | driverArena: &heap::Heap |
|
| 32 | 32 | ) throws (alloc::AllocError) { |
|
| 33 | 33 | let modAst = entry.ast else { |
|
| 34 | 34 | return; |
|
| 35 | 35 | }; |
|
| 36 | - | let case ast::NodeValue::Block(block) = modAst.value else { |
|
| 36 | + | let case ast::NodeValue::Module(block) = modAst.value else { |
|
| 37 | 37 | return; |
|
| 38 | 38 | }; |
|
| 39 | 39 | // The descriptors outlive the entry copy, so the qualified path is copied |
|
| 40 | 40 | // into permanent storage. |
|
| 41 | 41 | let mut modPath: *mut [*[u8]] = &mut []; |
lib/std/fmt.rad
+18 -1
| 299 | 299 | } |
|
| 300 | 300 | let value = try parseUint(&text[start ..], radix); |
|
| 301 | 301 | return IntLiteral { text, magnitude: value, radix: radixType }; |
|
| 302 | 302 | } |
|
| 303 | 303 | ||
| 304 | - | /// Process escape sequences in a raw string, writing the result into `dst`. |
|
| 304 | + | /// Decode ASCII escapes and `\xHH` byte escapes into `dst`. |
|
| 305 | 305 | /// Return the written bytes. The destination must have space for the result. |
|
| 306 | 306 | export fn unescapeString(raw: &[u8], dst: &'r mut [u8]) -> &'r [u8] { |
|
| 307 | 307 | let mut i: u32 = 0; |
|
| 308 | 308 | let mut j: u32 = 0; |
|
| 309 | 309 | ||
| 310 | 310 | while i < raw.len { |
|
| 311 | + | if raw[i] == '\\' and i + 3 < raw.len and raw[i + 1] == 'x' { |
|
| 312 | + | let high = digitFromAscii(raw[i + 2], 16); |
|
| 313 | + | let low = digitFromAscii(raw[i + 3], 16); |
|
| 314 | + | if let high = high { |
|
| 315 | + | if let low = low { |
|
| 316 | + | set dst[j] = ((high << 4) | low) as u8; |
|
| 317 | + | set i += 4; |
|
| 318 | + | set j += 1; |
|
| 319 | + | continue; |
|
| 320 | + | } |
|
| 321 | + | } |
|
| 322 | + | } |
|
| 311 | 323 | if raw[i] == '\\' and i + 1 < raw.len { |
|
| 312 | 324 | set dst[j] = decodeAsciiEscape(raw[i + 1]); |
|
| 313 | 325 | set i += 2; |
|
| 314 | 326 | } else { |
|
| 315 | 327 | set dst[j] = raw[i]; |
| 344 | 356 | let raw = &text[1 .. text.len - 1]; |
|
| 345 | 357 | if raw.len == 0 { |
|
| 346 | 358 | throw ParseError::Invalid; |
|
| 347 | 359 | } |
|
| 348 | 360 | if raw[0] == '\\' { |
|
| 361 | + | if raw.len == 4 and raw[1] == 'x' { |
|
| 362 | + | let mut byte: [u8; 1] = [0; 1]; |
|
| 363 | + | try parseHex(&raw[2 ..], &mut byte[..]); |
|
| 364 | + | return byte[0]; |
|
| 365 | + | } |
|
| 349 | 366 | if raw.len <> 2 { |
|
| 350 | 367 | throw ParseError::Invalid; |
|
| 351 | 368 | } |
|
| 352 | 369 | return decodeAsciiEscape(raw[1]); |
|
| 353 | 370 | } |
lib/std/lang/ast.rad
+80 -3
| 1 | 1 | //! Radiance AST modules. |
|
| 2 | 2 | export mod printer; |
|
| 3 | + | @test mod tests; |
|
| 3 | 4 | ||
| 4 | 5 | use std::fmt; |
|
| 5 | 6 | use std::io; |
|
| 6 | 7 | use std::lang::alloc::AllocError; |
|
| 7 | 8 | use std::lang::types; |
|
| 9 | + | use std::mem; |
|
| 8 | 10 | use std::mem::heap; |
|
| 9 | 11 | ||
| 10 | 12 | /// Maximum number of trait methods. |
|
| 11 | 13 | export constant MAX_TRAIT_METHODS: u32 = 8; |
|
| 12 | 14 |
| 603 | 605 | /// storage is reached only through it. The parser places it first in a |
|
| 604 | 606 | /// block of its own, followed by the body, so that both end there. |
|
| 605 | 607 | borrow: bool, |
|
| 606 | 608 | } |
|
| 607 | 609 | ||
| 610 | + | /// Parsed module. |
|
| 611 | + | export record Module: Copy { |
|
| 612 | + | /// Top-level statements in source order. |
|
| 613 | + | statements: *[*Node], |
|
| 614 | + | } |
|
| 615 | + | ||
| 608 | 616 | /// Constant declaration. |
|
| 609 | 617 | export record ConstDecl: Copy { |
|
| 610 | 618 | /// Identifier bound by the declaration. |
|
| 611 | 619 | ident: *Node, |
|
| 612 | 620 | /// Declared type annotation. |
| 646 | 654 | fields: *[*Node], |
|
| 647 | 655 | /// When true, remaining fields are discarded (`{ x, .. }`). |
|
| 648 | 656 | ignoreRest: bool, |
|
| 649 | 657 | } |
|
| 650 | 658 | ||
| 659 | + | /// A named value used to build a record literal. |
|
| 660 | + | /// Names and pointer data in values must outlive the generated AST. |
|
| 661 | + | export record FieldValue: Copy { |
|
| 662 | + | /// Field name. |
|
| 663 | + | name: *[u8], |
|
| 664 | + | /// Field initializer. |
|
| 665 | + | value: NodeValue, |
|
| 666 | + | } |
|
| 667 | + | ||
| 651 | 668 | /// Record declaration. |
|
| 652 | 669 | export record RecordDecl: Copy { |
|
| 653 | 670 | /// Identifier naming the record. |
|
| 654 | 671 | name: *Node, |
|
| 655 | 672 | /// Region parameters in declaration order. |
| 770 | 787 | value: *Node, |
|
| 771 | 788 | } |
|
| 772 | 789 | ||
| 773 | 790 | /// Tagged union describing every possible AST node payload. |
|
| 774 | 791 | export union NodeValue: Copy { |
|
| 792 | + | /// Module declarations. |
|
| 793 | + | Module(Module), |
|
| 775 | 794 | /// Placeholder `_` expression. |
|
| 776 | 795 | Placeholder, |
|
| 777 | 796 | /// Nil literal (`nil`). |
|
| 778 | 797 | Nil, |
|
| 779 | 798 | /// Undefined literal (`undefined`). |
| 1074 | 1093 | /// Throws `AllocError` if the arena is full. |
|
| 1075 | 1094 | export fn synthNode(arena: &mut NodeArena, value: NodeValue) -> *mut Node throws (AllocError) { |
|
| 1076 | 1095 | return try allocNode(arena, Span { offset: 0, length: 0 }, value); |
|
| 1077 | 1096 | } |
|
| 1078 | 1097 | ||
| 1098 | + | /// Pair a field name with its initializer for record construction. |
|
| 1099 | + | export fn field(name: *[u8], value: NodeValue) -> FieldValue { |
|
| 1100 | + | return FieldValue { name, value }; |
|
| 1101 | + | } |
|
| 1102 | + | ||
| 1103 | + | /// Build a string literal from decoded bytes that outlive the generated AST. |
|
| 1104 | + | export fn stringValue(text: *[u8]) -> NodeValue { |
|
| 1105 | + | return NodeValue::String(text); |
|
| 1106 | + | } |
|
| 1107 | + | ||
| 1108 | + | /// Build an array literal from its ordered element nodes. |
|
| 1109 | + | /// The element list and its nodes must outlive the generated AST. |
|
| 1110 | + | export fn arrayValue(items: *[*Node]) -> NodeValue { |
|
| 1111 | + | return NodeValue::ArrayLit(items); |
|
| 1112 | + | } |
|
| 1113 | + | ||
| 1114 | + | /// Build a decimal integer literal with arena-owned text. |
|
| 1115 | + | export fn numberValue(value: u64, arena: &heap::Heap) -> NodeValue throws (AllocError) { |
|
| 1116 | + | let mut text: *mut [u8] = &mut []; |
|
| 1117 | + | try text.resize(fmt::U64_STR_LEN, 0, arena); |
|
| 1118 | + | let length = fmt::formatU64(value, &mut text[..]).len; |
|
| 1119 | + | return NodeValue::Number(fmt::IntLiteral { |
|
| 1120 | + | text: &text[text.len - length ..], magnitude: value, radix: fmt::Radix::Decimal |
|
| 1121 | + | }); |
|
| 1122 | + | } |
|
| 1123 | + | ||
| 1124 | + | /// Build a lowercase hexadecimal string literal with arena-owned text. |
|
| 1125 | + | export fn hexStringValue(bytes: &[u8], arena: &heap::Heap) -> NodeValue throws (AllocError) { |
|
| 1126 | + | if bytes.len > mem::MAX_SIZE / 2 { |
|
| 1127 | + | throw AllocError::OutOfMemory; |
|
| 1128 | + | } |
|
| 1129 | + | let mut text: *mut [u8] = &mut []; |
|
| 1130 | + | try text.resize(bytes.len * 2, 0, arena); |
|
| 1131 | + | fmt::formatHex(bytes, &mut text[..]); |
|
| 1132 | + | return stringValue(&text[..]); |
|
| 1133 | + | } |
|
| 1134 | + | ||
| 1135 | + | /// Build a record literal from its ordered field names and values. |
|
| 1136 | + | /// Copy the field list into the arena. A nil name makes an anonymous record. |
|
| 1137 | + | export fn synthRecord( |
|
| 1138 | + | arena: &mut NodeArena, name: ?*[u8], fields: &[FieldValue] |
|
| 1139 | + | ) -> *Node throws (AllocError) { |
|
| 1140 | + | let mut initializers = try nodeSlice(arena, fields.len); |
|
| 1141 | + | for field in fields { |
|
| 1142 | + | let label = try synthNode(arena, NodeValue::Ident(field.name)); |
|
| 1143 | + | let value = try synthNode(arena, field.value); |
|
| 1144 | + | let node = try synthNode(arena, NodeValue::RecordLitField(Arg { label, value })); |
|
| 1145 | + | try initializers.append(node, arena.heap); |
|
| 1146 | + | } |
|
| 1147 | + | let mut typeName: ?*Node = nil; |
|
| 1148 | + | if let name = name { |
|
| 1149 | + | set typeName = try synthNode(arena, NodeValue::Ident(name)); |
|
| 1150 | + | } |
|
| 1151 | + | return try synthNode(arena, NodeValue::RecordLit(RecordLit { |
|
| 1152 | + | typeName, fields: initializers, ignoreRest: false |
|
| 1153 | + | })); |
|
| 1154 | + | } |
|
| 1155 | + | ||
| 1079 | 1156 | /// Synthetic module with a single function in it. |
|
| 1080 | 1157 | record SynthFnMod: Copy { |
|
| 1081 | - | /// The module block. |
|
| 1158 | + | /// The module root. |
|
| 1082 | 1159 | modBody: *Node, |
|
| 1083 | 1160 | /// The function block. |
|
| 1084 | 1161 | fnBody: *Node, |
|
| 1085 | 1162 | } |
|
| 1086 | 1163 |
| 1099 | 1176 | let fnDecl = try synthNode(arena, NodeValue::FnDecl(FnDecl { |
|
| 1100 | 1177 | name: fnName, sig: fnSig, body: fnBody, attrs: nil |
|
| 1101 | 1178 | })); |
|
| 1102 | 1179 | let mut rootStmts: *mut [*Node] = &mut []; |
|
| 1103 | 1180 | try rootStmts.append(fnDecl, arena.heap); |
|
| 1104 | - | let modBody = try synthNode(arena, NodeValue::Block( |
|
| 1105 | - | Block { statements: rootStmts, isUnsafe: false } |
|
| 1181 | + | let modBody = try synthNode(arena, NodeValue::Module( |
|
| 1182 | + | Module { statements: rootStmts } |
|
| 1106 | 1183 | )); |
|
| 1107 | 1184 | ||
| 1108 | 1185 | return SynthFnMod { modBody, fnBody }; |
|
| 1109 | 1186 | } |
lib/std/lang/ast/printer.rad
+4 -1
| 268 | 268 | ||
| 269 | 269 | /// Convert an AST node to an S-expression. |
|
| 270 | 270 | export fn toExpr(a: &heap::Heap, node: *super::Node) -> sexpr::Expr { |
|
| 271 | 271 | match node.value { |
|
| 272 | 272 | case |
|
| 273 | + | super::NodeValue::Module(_), |
|
| 273 | 274 | super::NodeValue::Block(_), |
|
| 274 | 275 | super::NodeValue::Let(_), |
|
| 275 | 276 | super::NodeValue::Assign(_), |
|
| 276 | 277 | super::NodeValue::Return { .. }, |
|
| 277 | 278 | super::NodeValue::Throw { .. }, |
| 441 | 442 | } |
|
| 442 | 443 | ||
| 443 | 444 | /// Convert a statement node to an S-expression. |
|
| 444 | 445 | fn statementToExpr(a: &heap::Heap, node: *super::Node) -> sexpr::Expr { |
|
| 445 | 446 | match node.value { |
|
| 447 | + | case super::NodeValue::Module(module) => |
|
| 448 | + | return sexpr::block(a, "module", &[], nodeListToExprs(a, module.statements)), |
|
| 446 | 449 | case super::NodeValue::Block(blk) => { |
|
| 447 | 450 | let children = nodeListToExprs(a, blk.statements); |
|
| 448 | 451 | let name = "unsafe" if blk.isUnsafe else "block"; |
|
| 449 | 452 | return sexpr::block(a, name, &[], children); |
|
| 450 | 453 | } |
| 717 | 720 | } |
|
| 718 | 721 | ||
| 719 | 722 | /// Dump the tree rooted at `root`, allocating the expression tree from `a`. |
|
| 720 | 723 | export fn printTree(root: *super::Node, a: &heap::Heap) { |
|
| 721 | 724 | match root.value { |
|
| 722 | - | case super::NodeValue::Block(blk) => { |
|
| 725 | + | case super::NodeValue::Module(blk) => { |
|
| 723 | 726 | for stmt, i in blk.statements { |
|
| 724 | 727 | sexpr::print(toExpr(a, stmt), 0); |
|
| 725 | 728 | if i < blk.statements.len - 1 { |
|
| 726 | 729 | io::print("\n\n"); |
|
| 727 | 730 | } |
lib/std/lang/ast/tests.rad
added
+99 -0
| 1 | + | //! Synthetic AST construction and allocation failures. |
|
| 2 | + | ||
| 3 | + | use std::fmt; |
|
| 4 | + | use std::lang::alloc::AllocError; |
|
| 5 | + | use std::lang::ast; |
|
| 6 | + | use std::mem; |
|
| 7 | + | use std::mem::heap; |
|
| 8 | + | use std::testing; |
|
| 9 | + | ||
| 10 | + | /// Arena storage for synthetic nodes and literal text. |
|
| 11 | + | static STORAGE: [u8; 8192] = [0; 8192]; |
|
| 12 | + | ||
| 13 | + | /// Decimal literals keep their complete unsigned magnitude and text. |
|
| 14 | + | @test unsafe fn numberValues() throws (testing::TestError) { |
|
| 15 | + | let arena = heap::over(&mut STORAGE[..]); |
|
| 16 | + | let values: [u64; 3] = [0, 42, fmt::U64_MAX]; |
|
| 17 | + | for value in values { |
|
| 18 | + | let case ast::NodeValue::Number(literal) = try! ast::numberValue(value, arena) else panic; |
|
| 19 | + | assert literal.magnitude == value; |
|
| 20 | + | assert literal.radix == fmt::Radix::Decimal; |
|
| 21 | + | assert (try! fmt::parseInt(literal.text)).magnitude == value; |
|
| 22 | + | } |
|
| 23 | + | } |
|
| 24 | + | ||
| 25 | + | /// Record construction copies temporary field lists and preserves their order. |
|
| 26 | + | @test unsafe fn recordFields() throws (testing::TestError) { |
|
| 27 | + | let mut arena = ast::nodeArena(&mut STORAGE[..]); |
|
| 28 | + | let mut fields = [ |
|
| 29 | + | ast::field("path", ast::stringValue("main.rad")), |
|
| 30 | + | ast::field("enabled", ast::NodeValue::Bool(true)), |
|
| 31 | + | ]; |
|
| 32 | + | let node = try! ast::synthRecord(&mut arena, "Module", &fields[..]); |
|
| 33 | + | set fields[0] = ast::field("changed", ast::NodeValue::Nil); |
|
| 34 | + | let case ast::NodeValue::RecordLit(literal) = node.value else panic; |
|
| 35 | + | let name = literal.typeName else panic; |
|
| 36 | + | let case ast::NodeValue::Ident(typeName) = name.value else panic; |
|
| 37 | + | assert mem::eq(typeName, "Module"); |
|
| 38 | + | assert literal.fields.len == 2 and not literal.ignoreRest; |
|
| 39 | + | let case ast::NodeValue::RecordLitField(first) = literal.fields[0].value else panic; |
|
| 40 | + | let label = first.label else panic; |
|
| 41 | + | let case ast::NodeValue::Ident(key) = label.value else panic; |
|
| 42 | + | let case ast::NodeValue::String(text) = first.value.value else panic; |
|
| 43 | + | assert mem::eq(key, "path") and mem::eq(text, "main.rad"); |
|
| 44 | + | let case ast::NodeValue::RecordLitField(second) = literal.fields[1].value else panic; |
|
| 45 | + | let other = second.label else panic; |
|
| 46 | + | let case ast::NodeValue::Ident(otherKey) = other.value else panic; |
|
| 47 | + | let case ast::NodeValue::Bool(enabled) = second.value.value else panic; |
|
| 48 | + | assert mem::eq(otherKey, "enabled") and enabled; |
|
| 49 | + | assert node.span.offset == 0 and node.span.length == 0; |
|
| 50 | + | let empty = try! ast::synthRecord(&mut arena, nil, &[]); |
|
| 51 | + | let case ast::NodeValue::RecordLit(anonymous) = empty.value else panic; |
|
| 52 | + | assert anonymous.typeName == nil and anonymous.fields.len == 0; |
|
| 53 | + | } |
|
| 54 | + | ||
| 55 | + | /// Build a record with literals that share the node arena. |
|
| 56 | + | fn example(arena: &mut ast::NodeArena) -> *ast::Node throws (AllocError) { |
|
| 57 | + | let number = try ast::numberValue(42, arena.heap); |
|
| 58 | + | let hex = try ast::hexStringValue("hi", arena.heap); |
|
| 59 | + | return try ast::synthRecord( |
|
| 60 | + | arena, |
|
| 61 | + | "Config", |
|
| 62 | + | &[ |
|
| 63 | + | ast::field("answer", number), |
|
| 64 | + | ast::field("label", ast::stringValue("hi")), |
|
| 65 | + | ast::field("hex", hex), |
|
| 66 | + | ast::field("items", ast::arrayValue(&[])), |
|
| 67 | + | ] |
|
| 68 | + | ); |
|
| 69 | + | } |
|
| 70 | + | ||
| 71 | + | /// Hexadecimal string literals own their encoded bytes and preserve leading zeroes. |
|
| 72 | + | @test unsafe fn hexStrings() throws (testing::TestError) { |
|
| 73 | + | let arena = heap::over(&mut STORAGE[..]); |
|
| 74 | + | let mut bytes: [u8; 4] = [0, 1, 0x7f, 0xff]; |
|
| 75 | + | let value = try! ast::hexStringValue(&bytes[..], arena); |
|
| 76 | + | set bytes[0] = 0x55; |
|
| 77 | + | let case ast::NodeValue::String(text) = value else panic; |
|
| 78 | + | assert mem::eq(text, "00017fff"); |
|
| 79 | + | let case ast::NodeValue::String(empty) = try! ast::hexStringValue("", arena) else panic; |
|
| 80 | + | assert empty.len == 0; |
|
| 81 | + | } |
|
| 82 | + | ||
| 83 | + | /// Every construction stage returns allocation failure when storage is too small. |
|
| 84 | + | @test unsafe fn allocationErrors() throws (testing::TestError) { |
|
| 85 | + | let mut capacity: u32 = 0; |
|
| 86 | + | loop { |
|
| 87 | + | let mut arena = ast::NodeArena { |
|
| 88 | + | heap: heap::withCapacity(&mut STORAGE[..], capacity), nextId: 0 |
|
| 89 | + | }; |
|
| 90 | + | try example(&mut arena) catch error { |
|
| 91 | + | assert error == AllocError::OutOfMemory; |
|
| 92 | + | set capacity += 16; |
|
| 93 | + | assert capacity < STORAGE.len - 48; |
|
| 94 | + | continue; |
|
| 95 | + | }; |
|
| 96 | + | assert capacity > 0; |
|
| 97 | + | break; |
|
| 98 | + | } |
|
| 99 | + | } |
lib/std/lang/lower.rad
+10 -4
| 1278 | 1278 | ) throws (LowerError) { |
|
| 1279 | 1279 | set low.currentMod = moduleId; |
|
| 1280 | 1280 | try lowerDecls(low, root, isRoot, sink); |
|
| 1281 | 1281 | } |
|
| 1282 | 1282 | ||
| 1283 | - | /// Lower all top-level declarations in a block. |
|
| 1283 | + | /// Lower all top-level declarations in a module. |
|
| 1284 | 1284 | fn lowerDecls( |
|
| 1285 | 1285 | low: &mut Lowerer, |
|
| 1286 | 1286 | root: *ast::Node, |
|
| 1287 | 1287 | isRoot: bool, |
|
| 1288 | 1288 | sink: &mut opaque FnSink |
|
| 1289 | 1289 | ) throws (LowerError) { |
|
| 1290 | - | let case ast::NodeValue::Block(block) = root.value else { |
|
| 1291 | - | throw LowerError::ExpectedBlock(root); |
|
| 1292 | - | }; |
|
| 1290 | + | let case ast::NodeValue::Module(block) = root.value else panic "lowerDecls: expected module"; |
|
| 1293 | 1291 | let stmtsList = block.statements; |
|
| 1294 | 1292 | ||
| 1295 | 1293 | for node in stmtsList { |
|
| 1296 | 1294 | match node.value { |
|
| 1297 | 1295 | case ast::NodeValue::FnDecl(decl) => { |
| 2556 | 2554 | try lowerConstDataInto(self, node, *inner, layout.size - offset, dataPrefix, b); |
|
| 2557 | 2555 | return b.values.len - start; |
|
| 2558 | 2556 | } |
|
| 2559 | 2557 | } |
|
| 2560 | 2558 | } |
|
| 2559 | + | match node.value { |
|
| 2560 | + | case ast::NodeValue::FieldAccess(_), ast::NodeValue::Subscript { .. } => { |
|
| 2561 | + | if let source = self.resolver.constantNode(node) { |
|
| 2562 | + | return try lowerConstDataPayloadInto(self, source, ty, dataPrefix, b); |
|
| 2563 | + | } |
|
| 2564 | + | } |
|
| 2565 | + | else => {} |
|
| 2566 | + | } |
|
| 2561 | 2567 | // Function pointer references in constant data. |
|
| 2562 | 2568 | if let case resolver::Type::Fn(fnType) = ty { |
|
| 2563 | 2569 | let sym = resolver::symbolFor(&self.resolver, node) |
|
| 2564 | 2570 | else throw LowerError::MissingSymbol(node); |
|
| 2565 | 2571 | let modId = resolver::moduleIdForSymbol(&self.resolver, sym); |
lib/std/lang/lower/tests.rad
+2 -1
| 117 | 117 | let mut res = tests::testResolver(); |
|
| 118 | 118 | let result = try tests::resolveProgramStr( |
|
| 119 | 119 | &mut res, "union First { Failure } union Second { Failure }" |
|
| 120 | 120 | ); |
|
| 121 | 121 | try tests::expectNoErrors(&result); |
|
| 122 | - | let case ast::NodeValue::Block(block) = result.root.value else throw testing::TestError::Failed; |
|
| 122 | + | let case ast::NodeValue::Module(block) = result.root.value |
|
| 123 | + | else throw testing::TestError::Failed; |
|
| 123 | 124 | let firstSym = resolver::symbolFor(&res, block.statements[0]) |
|
| 124 | 125 | else throw testing::TestError::Failed; |
|
| 125 | 126 | let secondSym = resolver::symbolFor(&res, block.statements[1]) |
|
| 126 | 127 | else throw testing::TestError::Failed; |
|
| 127 | 128 | let case resolver::SymbolData::Type(firstId) = res.symbols[*firstSym].data |
lib/std/lang/parser.rad
+31 -5
| 2899 | 2899 | try statements.append(body, p.arena.heap); |
|
| 2900 | 2900 | ||
| 2901 | 2901 | return try node(p, ast::NodeValue::Block(ast::Block { statements, isUnsafe: false })); |
|
| 2902 | 2902 | } |
|
| 2903 | 2903 | ||
| 2904 | - | /// Parse one module from source text into a block of top-level statements. |
|
| 2904 | + | /// Parse one module from source text. |
|
| 2905 | 2905 | /// |
|
| 2906 | 2906 | /// Scanner, token, and error state are reset for the module. Nodes and strings |
|
| 2907 | 2907 | /// accumulate in the parser's arena and pool, which the module's AST keeps using. |
|
| 2908 | 2908 | export fn parseModule(p: &mut Parser, sourceLoc: scanner::SourceLoc, input: *[u8]) -> *ast::Node |
|
| 2909 | 2909 | throws (ParseError) |
|
| 2910 | 2910 | { |
|
| 2911 | + | return try parseSource(p, sourceLoc, input, parseTopLevel); |
|
| 2912 | + | } |
|
| 2913 | + | ||
| 2914 | + | /// Parse source text that holds a single expression, such as a data document. |
|
| 2915 | + | /// State is reset and kept as by [`parseModule`]. |
|
| 2916 | + | export fn parseValue(p: &mut Parser, sourceLoc: scanner::SourceLoc, input: *[u8]) -> *ast::Node |
|
| 2917 | + | throws (ParseError) |
|
| 2918 | + | { |
|
| 2919 | + | return try parseSource(p, sourceLoc, input, parseWholeExpr); |
|
| 2920 | + | } |
|
| 2921 | + | ||
| 2922 | + | /// Parse `input` with `parse`, reporting its errors. |
|
| 2923 | + | fn parseSource( |
|
| 2924 | + | p: &mut Parser, |
|
| 2925 | + | sourceLoc: scanner::SourceLoc, |
|
| 2926 | + | input: *[u8], |
|
| 2927 | + | parse: fn(&mut Parser) -> *ast::Node throws (ParseError, AllocError) |
|
| 2928 | + | ) -> *ast::Node throws (ParseError) { |
|
| 2911 | 2929 | beginModule(p, sourceLoc, input); |
|
| 2912 | 2930 | ||
| 2913 | - | return try parseTopLevel(p) catch err as AllocError { |
|
| 2931 | + | return try parse(p) catch err as AllocError { |
|
| 2914 | 2932 | let token = p.current; |
|
| 2915 | 2933 | reportError(p, token, "syntax tree arena is full"); |
|
| 2916 | 2934 | printErrors(p); |
|
| 2917 | 2935 | throw ParseError::AllocationFailed; |
|
| 2918 | 2936 | } catch err as ParseError { |
| 2948 | 2966 | set p.pending = &mut []; |
|
| 2949 | 2967 | set p.base = 0; |
|
| 2950 | 2968 | set p.closing = &mut []; |
|
| 2951 | 2969 | } |
|
| 2952 | 2970 | ||
| 2953 | - | /// Parse the current module's tokens into a block of top-level statements. |
|
| 2971 | + | /// Parse the current module's declarations. |
|
| 2954 | 2972 | fn parseTopLevel(p: &mut Parser) -> *ast::Node |
|
| 2955 | 2973 | throws (ParseError, AllocError) |
|
| 2956 | 2974 | { |
|
| 2957 | 2975 | try advance(p); // Set the parser up with a first token. |
|
| 2958 | 2976 | ||
| 2959 | 2977 | let statements = try parseStmtsUntil( |
|
| 2960 | 2978 | p, scanner::TokenKind::Eof, INITIAL_MODULE_STATEMENTS |
|
| 2961 | 2979 | ); |
|
| 2962 | - | let blk = ast::Block { statements, isUnsafe: false }; |
|
| 2963 | 2980 | try consume(p, scanner::TokenKind::Eof); |
|
| 2964 | - | let block: *ast::Node = try node(p, ast::NodeValue::Block(blk)); |
|
| 2981 | + | let block: *ast::Node = try node(p, ast::NodeValue::Module(ast::Module { statements })); |
|
| 2965 | 2982 | try attachClosing(p, block); |
|
| 2966 | 2983 | ||
| 2967 | 2984 | return block; |
|
| 2968 | 2985 | } |
|
| 2969 | 2986 | ||
| 2987 | + | /// Parse the current input as one expression. |
|
| 2988 | + | fn parseWholeExpr(p: &mut Parser) -> *ast::Node throws (ParseError, AllocError) { |
|
| 2989 | + | try advance(p); |
|
| 2990 | + | let value = try parseExpr(p); |
|
| 2991 | + | try expect(p, scanner::TokenKind::Eof, "expected end of input after expression"); |
|
| 2992 | + | ||
| 2993 | + | return value; |
|
| 2994 | + | } |
|
| 2995 | + | ||
| 2970 | 2996 | /// Consume a token of the given kind if present. |
|
| 2971 | 2997 | export fn consume(p: &mut Parser, kind: scanner::TokenKind) -> bool throws (AllocError) { |
|
| 2972 | 2998 | if p.current.kind == kind { |
|
| 2973 | 2999 | try advance(p); |
|
| 2974 | 3000 | return true; |
lib/std/lang/parser/tests.rad
+42 -17
| 257 | 257 | } |
|
| 258 | 258 | } |
|
| 259 | 259 | panic "expectBlockExprStmt: comparing values we don't know how to compare"; |
|
| 260 | 260 | } |
|
| 261 | 261 | ||
| 262 | - | /// Get the first statement from a block node. |
|
| 262 | + | /// Get the first statement from a module or block node. |
|
| 263 | 263 | export fn getBlockFirstStmt(blk: *ast::Node) -> *ast::Node |
|
| 264 | 264 | throws (testing::TestError) |
|
| 265 | 265 | { |
|
| 266 | - | let case ast::NodeValue::Block(block) = blk.value else throw testing::TestError::Failed; |
|
| 266 | + | let statements = blockStmts(blk); |
|
| 267 | 267 | ||
| 268 | - | if block.statements.len == 0 { |
|
| 268 | + | if statements.len == 0 { |
|
| 269 | 269 | throw testing::TestError::Failed; |
|
| 270 | 270 | } |
|
| 271 | - | return block.statements[0]; |
|
| 271 | + | return statements[0]; |
|
| 272 | 272 | } |
|
| 273 | 273 | ||
| 274 | - | /// Get the last statement from a block node. |
|
| 274 | + | /// Get the last statement from a module or block node. |
|
| 275 | 275 | export fn getBlockLastStmt(blk: *ast::Node) -> *ast::Node |
|
| 276 | 276 | throws (testing::TestError) |
|
| 277 | 277 | { |
|
| 278 | - | let case ast::NodeValue::Block(block) = blk.value else throw testing::TestError::Failed; |
|
| 278 | + | let statements = blockStmts(blk); |
|
| 279 | 279 | ||
| 280 | - | if block.statements.len == 0 { |
|
| 280 | + | if statements.len == 0 { |
|
| 281 | 281 | throw testing::TestError::Failed; |
|
| 282 | 282 | } |
|
| 283 | - | return block.statements[block.statements.len - 1]; |
|
| 283 | + | return statements[statements.len - 1]; |
|
| 284 | 284 | } |
|
| 285 | 285 | ||
| 286 | 286 | /// Test parsing boolean literals (`true` and `false`). |
|
| 287 | 287 | @test unsafe fn testParseBool() throws (testing::TestError) { |
|
| 288 | 288 | let r1 = try! parseExprStr("true"); |
| 397 | 397 | let r2 = try! parseExprStr("\"\""); |
|
| 398 | 398 | let case ast::NodeValue::String(s2) = r2.value if s2.len == 0 |
|
| 399 | 399 | else throw testing::TestError::Failed; |
|
| 400 | 400 | } |
|
| 401 | 401 | ||
| 402 | + | /// Hex escapes preserve every byte in string and character literals. |
|
| 403 | + | @test unsafe fn testParseHexEscapes() throws (testing::TestError) { |
|
| 404 | + | let node = try! parseExprStr("\"\\x00\\x1f\\x7F\\xff\""); |
|
| 405 | + | let case ast::NodeValue::String(text) = node.value else throw testing::TestError::Failed; |
|
| 406 | + | assert mem::eq(text, &[0, 31, 127, 255]); |
|
| 407 | + | let ch = try! parseExprStr("'\\x80'"); |
|
| 408 | + | let case ast::NodeValue::Char(byte) = ch.value else throw testing::TestError::Failed; |
|
| 409 | + | assert byte == 128; |
|
| 410 | + | } |
|
| 411 | + | ||
| 412 | + | /// Hex escapes require two hexadecimal digits. |
|
| 413 | + | @test unsafe fn testInvalidHexEscapes() throws (testing::TestError) { |
|
| 414 | + | for text in ["\"\\x\"", "\"\\x0\"", "\"\\xgg\"", "'\\x0g'"] { |
|
| 415 | + | let mut p = mkParser(text); |
|
| 416 | + | try! super::advance(&mut p); |
|
| 417 | + | let mut rejected = false; |
|
| 418 | + | try super::parseExpr(&mut p) catch { |
|
| 419 | + | set rejected = true; |
|
| 420 | + | }; |
|
| 421 | + | assert rejected; |
|
| 422 | + | keepNodes(&p); |
|
| 423 | + | } |
|
| 424 | + | } |
|
| 425 | + | ||
| 402 | 426 | /// Test string escape sequence processing. |
|
| 403 | 427 | @test unsafe fn testParseStringEscape() throws (testing::TestError) { |
|
| 404 | 428 | // Tab and newline. |
|
| 405 | 429 | let r1 = try! parseExprStr("\"hello\\tworld\\n\""); |
|
| 406 | 430 | let case ast::NodeValue::String(s1) = r1.value if s1.len == 12 |
| 1758 | 1782 | } |
|
| 1759 | 1783 | ||
| 1760 | 1784 | /// Test that bare `return` and `panic` statements end at their semicolons. |
|
| 1761 | 1785 | @test unsafe fn testParseBareReturnPanicSemicolons() throws (testing::TestError) { |
|
| 1762 | 1786 | let root = try! parseStmtsStr("return; panic;"); |
|
| 1763 | - | let case ast::NodeValue::Block(module) = root.value else throw testing::TestError::Failed; |
|
| 1787 | + | let case ast::NodeValue::Module(module) = root.value else throw testing::TestError::Failed; |
|
| 1764 | 1788 | try testing::expect(module.statements.len == 2); |
|
| 1765 | 1789 | ||
| 1766 | 1790 | let case ast::NodeValue::Return(retValue) = module.statements[0].value |
|
| 1767 | 1791 | else throw testing::TestError::Failed; |
|
| 1768 | 1792 | try testing::expect(retValue == nil); |
| 2876 | 2900 | ||
| 2877 | 2901 | /// Unsafe statements have a block body. |
|
| 2878 | 2902 | @test unsafe fn testParseUnsafeBlock() throws (testing::TestError) { |
|
| 2879 | 2903 | let parsed = try? parseStmtsStr("fn run() { unsafe { return; } }"); |
|
| 2880 | 2904 | let root = parsed else throw testing::TestError::Failed; |
|
| 2881 | - | let case ast::NodeValue::Block(module) = root.value else throw testing::TestError::Failed; |
|
| 2905 | + | let case ast::NodeValue::Module(module) = root.value else throw testing::TestError::Failed; |
|
| 2882 | 2906 | let case ast::NodeValue::FnDecl(decl) = module.statements[0].value |
|
| 2883 | 2907 | else throw testing::TestError::Failed; |
|
| 2884 | 2908 | let fnBody = decl.body else throw testing::TestError::Failed; |
|
| 2885 | 2909 | let case ast::NodeValue::Block(body) = fnBody.value else throw testing::TestError::Failed; |
|
| 2886 | 2910 | let case ast::NodeValue::Block(inner) = body.statements[0].value |
| 2902 | 2926 | } |
|
| 2903 | 2927 | ||
| 2904 | 2928 | @test unsafe fn testParseModule() throws (testing::TestError) { |
|
| 2905 | 2929 | let r = try! parseStmtsStr("fn f() {} fn g() {}"); |
|
| 2906 | 2930 | ||
| 2907 | - | let case ast::NodeValue::Block(module) = r.value else throw testing::TestError::Failed; |
|
| 2931 | + | let case ast::NodeValue::Module(module) = r.value else throw testing::TestError::Failed; |
|
| 2908 | 2932 | try testing::expect(module.statements.len == 2); |
|
| 2909 | 2933 | ||
| 2910 | 2934 | let first = module.statements[0]; |
|
| 2911 | 2935 | let case ast::NodeValue::FnDecl(fDecl) = first.value else throw testing::TestError::Failed; |
|
| 2912 | 2936 | try expectIdent(fDecl.name, "f"); |
| 3097 | 3121 | return try super::parseModule(parser, scanner::SourceLoc::String, input) catch { |
|
| 3098 | 3122 | throw testing::TestError::Failed; |
|
| 3099 | 3123 | }; |
|
| 3100 | 3124 | } |
|
| 3101 | 3125 | ||
| 3102 | - | /// Return the statements of a block node. |
|
| 3126 | + | /// Return the statements of a module or block node. |
|
| 3103 | 3127 | fn blockStmts(block: *ast::Node) -> *[*ast::Node] { |
|
| 3104 | - | let case ast::NodeValue::Block(b) = block.value else { |
|
| 3105 | - | panic "blockStmts: expected block"; |
|
| 3106 | - | }; |
|
| 3107 | - | return b.statements; |
|
| 3128 | + | match block.value { |
|
| 3129 | + | case ast::NodeValue::Module(module) => return module.statements, |
|
| 3130 | + | case ast::NodeValue::Block(body) => return body.statements, |
|
| 3131 | + | else => panic "blockStmts: expected module or block", |
|
| 3132 | + | } |
|
| 3108 | 3133 | } |
|
| 3109 | 3134 | ||
| 3110 | 3135 | /// Return the body block of a function declaration statement. |
|
| 3111 | 3136 | fn fnBody(decl: *ast::Node) -> *ast::Node { |
|
| 3112 | 3137 | let case ast::NodeValue::FnDecl(f) = decl.value else { |
| 3813 | 3838 | let root = try! super::parseInterface( |
|
| 3814 | 3839 | &mut parser, |
|
| 3815 | 3840 | scanner::SourceLoc::String, |
|
| 3816 | 3841 | "export record Box { value: u32 } export fn get() -> Box; fn (b: &Box) read() -> u32; @extern export fn foreign() -> u32;" |
|
| 3817 | 3842 | ); |
|
| 3818 | - | let case ast::NodeValue::Block(block) = root.value else panic "interfaceDeclarations: block"; |
|
| 3843 | + | let case ast::NodeValue::Module(block) = root.value else panic "interfaceDeclarations: module"; |
|
| 3819 | 3844 | let case ast::NodeValue::FnDecl(decl) = block.statements[1].value |
|
| 3820 | 3845 | else panic "interfaceDeclarations: function"; |
|
| 3821 | 3846 | assert decl.body == nil; |
|
| 3822 | 3847 | if let attrs = decl.attrs { |
|
| 3823 | 3848 | assert not ast::attributesContains(&attrs, ast::Attribute::Extern); |
lib/std/lang/pretty.rad
+24 -4
| 15 | 15 | //! The AST does not record some source forms. Parentheses are placed where the |
|
| 16 | 16 | //! parser's precedence and context rules need them, and around mixed bitwise |
|
| 17 | 17 | //! operations for readability, `set x op= y` is printed |
|
| 18 | 18 | //! when the right side applies `op` to the very node on the left side, and |
|
| 19 | 19 | //! strings and characters are escaped again. |
|
| 20 | + | use std::char; |
|
| 21 | + | use std::fmt; |
|
| 20 | 22 | use std::lang::alloc; |
|
| 21 | 23 | use std::lang::ast; |
|
| 22 | 24 | use std::lang::layout; |
|
| 23 | 25 | use std::lang::module::Role; |
|
| 24 | 26 | use std::lang::types; |
| 147 | 149 | afterBlock: bool, |
|
| 148 | 150 | } |
|
| 149 | 151 | ||
| 150 | 152 | /// Format the module `root` with its `trivia`. |
|
| 151 | 153 | /// |
|
| 152 | - | /// `root` is the block that the parser returns for a module, and `trivia` is |
|
| 154 | + | /// `root` is the module that the parser returns, and `trivia` is |
|
| 153 | 155 | /// the parser's trivia for it. Every comment and blank line of `trivia` is |
|
| 154 | 156 | /// placed in the layout. The layout is allocated from `a`. |
|
| 155 | 157 | export fn module( |
|
| 156 | 158 | root: *ast::Node, trivia: *[ast::Trivia], a: &heap::Heap |
|
| 157 | 159 | ) -> *layout::Layout throws (alloc::AllocError) { |
|
| 158 | 160 | return try withRole(root, trivia, Role::Source, a); |
|
| 159 | 161 | } |
|
| 160 | 162 | ||
| 163 | + | /// Format the expression `node`, which has no trivia. |
|
| 164 | + | export fn expression( |
|
| 165 | + | node: *ast::Node, a: &heap::Heap |
|
| 166 | + | ) -> *layout::Layout throws (alloc::AllocError) { |
|
| 167 | + | let mut p = Printer { |
|
| 168 | + | role: Role::Source, trivia: &[], used: 0, fnDepth: 0, marks: 0, tableRecord: nil |
|
| 169 | + | }; |
|
| 170 | + | return try expr(a, &mut p, node, Ctx::Normal); |
|
| 171 | + | } |
|
| 172 | + | ||
| 161 | 173 | /// Format provider declarations without runtime bodies or compiler entry helpers. |
|
| 162 | 174 | /// Supporting declarations keep their source visibility and nominal ownership. |
|
| 163 | 175 | export fn interface(root: *ast::Node, a: &heap::Heap) -> *layout::Layout |
|
| 164 | 176 | throws (alloc::AllocError) |
|
| 165 | 177 | { |
| 168 | 180 | ||
| 169 | 181 | /// Build the layout of one module in its input role. |
|
| 170 | 182 | export fn withRole( |
|
| 171 | 183 | root: *ast::Node, trivia: *[ast::Trivia], role: Role, a: &heap::Heap |
|
| 172 | 184 | ) -> *layout::Layout throws (alloc::AllocError) { |
|
| 173 | - | let case ast::NodeValue::Block(blk) = root.value else { |
|
| 174 | - | panic "printModule: root is not a block"; |
|
| 185 | + | let case ast::NodeValue::Module(blk) = root.value else { |
|
| 186 | + | panic "withRole: expected module"; |
|
| 187 | + | }; |
|
| 188 | + | let mut p = Printer { |
|
| 189 | + | role, trivia, used: 0, fnDepth: 0, marks: 0, tableRecord: nil |
|
| 175 | 190 | }; |
|
| 176 | - | let mut p = Printer { role, trivia, used: 0, fnDepth: 0, marks: 0, tableRecord: nil }; |
|
| 177 | 191 | let mut kids: *mut [layout::Child] = &mut []; |
|
| 178 | 192 | try lines( |
|
| 179 | 193 | a, |
|
| 180 | 194 | &mut p, |
|
| 181 | 195 | &mut kids, |
| 635 | 649 | ||
| 636 | 650 | /// Whether a list with the container `container` puts one blank line between |
|
| 637 | 651 | /// functions: the top level of a module, and the methods of an instance. |
|
| 638 | 652 | fn spacesFunctions(p: &Printer, container: *ast::Node) -> bool { |
|
| 639 | 653 | match container.value { |
|
| 654 | + | case ast::NodeValue::Module(_) => return true, |
|
| 640 | 655 | case ast::NodeValue::Block(_) => return p.fnDepth == 0, |
|
| 641 | 656 | case ast::NodeValue::InstanceDecl { .. } => return true, |
|
| 642 | 657 | else => return false, |
|
| 643 | 658 | } |
|
| 644 | 659 | } |
| 986 | 1001 | try out.append(quote, a); |
|
| 987 | 1002 | for c in s { |
|
| 988 | 1003 | if let code = escapeCode(c, quote) { |
|
| 989 | 1004 | try out.append('\\', a); |
|
| 990 | 1005 | try out.append(code, a); |
|
| 1006 | + | } else if not char::isPrint(c) { |
|
| 1007 | + | let byte = [c]; |
|
| 1008 | + | let mut hex: [u8; 2] = [0; 2]; |
|
| 1009 | + | try out.extend("\\x", a); |
|
| 1010 | + | try out.extend(fmt::formatHex(&byte[..], &mut hex[..]), a); |
|
| 991 | 1011 | } else { |
|
| 992 | 1012 | try out.append(c, a); |
|
| 993 | 1013 | } |
|
| 994 | 1014 | } |
|
| 995 | 1015 | try out.append(quote, a); |
lib/std/lang/resolver.rad
+143 -72
| 1760 | 1760 | fn setForLoopInfo(self: &mut Resolver, node: *ast::Node, info: ForLoopInfo) { |
|
| 1761 | 1761 | set self.nodeData.getMut(node.id).extra = |
|
| 1762 | 1762 | NodeExtra::ForLoop(info); |
|
| 1763 | 1763 | } |
|
| 1764 | 1764 | ||
| 1765 | + | /// Find the constant initializer selected by a value, field, or array element. |
|
| 1766 | + | /// Selections follow immutable record and fixed-size array initializers. |
|
| 1767 | + | export fn (self: &Resolver) constantNode(node: *ast::Node) -> ?*ast::Node { |
|
| 1768 | + | match node.value { |
|
| 1769 | + | case ast::NodeValue::Ident(_), ast::NodeValue::ScopeAccess(_) => { |
|
| 1770 | + | let sym = symbolFor(self, node) else return nil; |
|
| 1771 | + | if let case SymbolData::Constant { .. } = self.symbols[*sym].data { |
|
| 1772 | + | let case ast::NodeValue::ConstDecl(decl) = self.symbols[*sym].node.value |
|
| 1773 | + | else return nil; |
|
| 1774 | + | return self.constantNode(decl.value); |
|
| 1775 | + | } |
|
| 1776 | + | return node if isConstExpr(self, node) else nil; |
|
| 1777 | + | } |
|
| 1778 | + | case ast::NodeValue::FieldAccess(access) => { |
|
| 1779 | + | let parent = self.constantNode(access.parent) else return nil; |
|
| 1780 | + | let index = recordFieldIndexFor(self, access.child) else return nil; |
|
| 1781 | + | let case ast::NodeValue::RecordLit(lit) = parent.value else return nil; |
|
| 1782 | + | if index >= lit.fields.len { |
|
| 1783 | + | return nil; |
|
| 1784 | + | } |
|
| 1785 | + | let case ast::NodeValue::RecordLitField(arg) = lit.fields[index].value else return nil; |
|
| 1786 | + | return self.constantNode(arg.value); |
|
| 1787 | + | } |
|
| 1788 | + | case ast::NodeValue::Subscript { container, index } => { |
|
| 1789 | + | let parent = self.constantNode(container) else return nil; |
|
| 1790 | + | let case Type::Array(info) = typeFor(self, container) else return nil; |
|
| 1791 | + | let case ConstValue::Int(value) = constValueEntry(self, index) else return nil; |
|
| 1792 | + | if value.negative or value.magnitude >= info.length as u64 { |
|
| 1793 | + | return nil; |
|
| 1794 | + | } |
|
| 1795 | + | match parent.value { |
|
| 1796 | + | case ast::NodeValue::ArrayLit(items) => |
|
| 1797 | + | return self.constantNode(items[value.magnitude as u32]), |
|
| 1798 | + | case ast::NodeValue::ArrayRepeatLit(repeat) => |
|
| 1799 | + | return self.constantNode(repeat.item), |
|
| 1800 | + | else => return nil, |
|
| 1801 | + | } |
|
| 1802 | + | } |
|
| 1803 | + | else => return node if isConstExpr(self, node) else nil, |
|
| 1804 | + | } |
|
| 1805 | + | } |
|
| 1806 | + | ||
| 1765 | 1807 | /// Retrieve the constant value associated with a node, if any. |
|
| 1766 | 1808 | export fn constValueEntry(self: &Resolver, node: *ast::Node) -> ?ConstValue { |
|
| 1767 | - | return self.nodeData.get(node.id).constValue; |
|
| 1809 | + | let value = self.nodeData.get(node.id).constValue; |
|
| 1810 | + | if value <> nil { |
|
| 1811 | + | return value; |
|
| 1812 | + | } |
|
| 1813 | + | match node.value { |
|
| 1814 | + | case ast::NodeValue::FieldAccess(_), ast::NodeValue::Subscript { .. } => {} |
|
| 1815 | + | else => return nil, |
|
| 1816 | + | } |
|
| 1817 | + | let type = typeFor(self, node) else return nil; |
|
| 1818 | + | if let case Type::Optional(_) = type { |
|
| 1819 | + | return nil; |
|
| 1820 | + | } |
|
| 1821 | + | let source = self.constantNode(node) else return nil; |
|
| 1822 | + | let result = constValueEntry(self, source) else return nil; |
|
| 1823 | + | if let case ConstValue::Int(int) = result; isNumericType(type) { |
|
| 1824 | + | return castConstInt(int, type); |
|
| 1825 | + | } |
|
| 1826 | + | return result; |
|
| 1768 | 1827 | } |
|
| 1769 | 1828 | ||
| 1770 | 1829 | /// Get the resolved record field index for a record literal field node. |
|
| 1771 | 1830 | export fn recordFieldIndexFor(self: &Resolver, node: *ast::Node) -> ?u32 { |
|
| 1772 | 1831 | if let case NodeExtra::RecordField { index } = self.nodeData.get(node.id).extra { |
| 3377 | 3436 | if path.len == 0 { |
|
| 3378 | 3437 | return sym; |
|
| 3379 | 3438 | } |
|
| 3380 | 3439 | let case SymbolData::Module { scope, .. } = self.symbols[*sym].data |
|
| 3381 | 3440 | else throw emitError(self, node, ErrorKind::InvalidModulePath); |
|
| 3382 | - | ||
| 3383 | 3441 | let childName = path[0]; |
|
| 3384 | 3442 | let childSym = findSymbolInScope(self, scope, childName) |
|
| 3385 | 3443 | else throw emitError(self, node, ErrorKind::UnresolvedSymbol(childName)); |
|
| 3386 | 3444 | ||
| 3387 | 3445 | if not isSymbolVisible(self, childSym, scope, self.scope) { |
| 3512 | 3570 | if not shouldAnalyzeModule(self, decl.attrs) { |
|
| 3513 | 3571 | return; |
|
| 3514 | 3572 | } |
|
| 3515 | 3573 | let modName = try nodeName(self, decl.name); |
|
| 3516 | 3574 | let submod = try enterSubModule(self, modName, node); |
|
| 3517 | - | let case ast::NodeValue::Block(block) = submod.root.value |
|
| 3518 | - | else panic "visitDef: expected block for module root"; |
|
| 3575 | + | let case ast::NodeValue::Module(block) = submod.root.value |
|
| 3576 | + | else panic "visitDef: expected module root"; |
|
| 3519 | 3577 | try resolveModuleDefs(self, &block) catch e { |
|
| 3520 | 3578 | exitModuleScope(self, submod); |
|
| 3521 | 3579 | throw e; |
|
| 3522 | 3580 | }; |
|
| 3523 | 3581 | exitModuleScope(self, submod); |
| 3640 | 3698 | case ast::NodeValue::BinOp(binop) => return try resolveBinOp(self, node, binop), |
|
| 3641 | 3699 | case ast::NodeValue::Block(block) => return try resolveBlock(self, node, block), |
|
| 3642 | 3700 | case ast::NodeValue::Let(decl) => return try resolveLet(self, node, decl), |
|
| 3643 | 3701 | case ast::NodeValue::FnDecl(decl) => |
|
| 3644 | 3702 | return try resolveFnDecl(self, node, decl), |
|
| 3645 | - | case ast::NodeValue::ConstDecl(decl) => |
|
| 3703 | + | case ast::NodeValue::ConstDecl(decl) => { |
|
| 3646 | 3704 | return try resolveConst( |
|
| 3647 | 3705 | self, node, decl.ident, decl.type, decl.value, decl.attrs |
|
| 3648 | - | ), |
|
| 3706 | + | ); |
|
| 3707 | + | } |
|
| 3649 | 3708 | case ast::NodeValue::StaticDecl(decl) => return try resolveStatic(self, node, decl), |
|
| 3650 | 3709 | case ast::NodeValue::FnParam(param) => return try resolveFnParam(self, node, param), |
|
| 3651 | 3710 | case ast::NodeValue::If(cond) => return try resolveIf(self, node, cond), |
|
| 3652 | 3711 | case ast::NodeValue::CondExpr(cond) => return try resolveCondExpr(self, node, cond, hint), |
|
| 3653 | 3712 | case ast::NodeValue::IfLet(cond) => return try resolveIfLet(self, node, cond), |
| 4003 | 4062 | /// value refers to a temporary or to constant data. |
|
| 4004 | 4063 | export fn isValueExpr(self: &Resolver, node: *ast::Node) -> bool { |
|
| 4005 | 4064 | match node.value { |
|
| 4006 | 4065 | case ast::NodeValue::Ident(_), ast::NodeValue::ScopeAccess(_) => |
|
| 4007 | 4066 | return isValueLiteral(self, node), |
|
| 4008 | - | case ast::NodeValue::FieldAccess(_) => |
|
| 4009 | - | return constValueEntry(self, node) <> nil, |
|
| 4067 | + | case ast::NodeValue::FieldAccess(access) => { |
|
| 4068 | + | let parent = typeFor(self, access.parent) else return false; |
|
| 4069 | + | if let case Type::Array(_) = autoDeref(parent) { |
|
| 4070 | + | return true; |
|
| 4071 | + | } |
|
| 4072 | + | return false; |
|
| 4073 | + | } |
|
| 4010 | 4074 | case ast::NodeValue::Subscript { .. }, ast::NodeValue::Deref(_) => |
|
| 4011 | 4075 | return false, |
|
| 4012 | 4076 | else => |
|
| 4013 | 4077 | return true, |
|
| 4014 | 4078 | } |
| 4100 | 4164 | else => {} |
|
| 4101 | 4165 | } |
|
| 4102 | 4166 | } |
|
| 4103 | 4167 | return false; |
|
| 4104 | 4168 | } |
|
| 4169 | + | case ast::NodeValue::FieldAccess(_), ast::NodeValue::Subscript { .. } => |
|
| 4170 | + | return self.nodeData.get(node.id).constValue |
|
| 4171 | + | <> nil or self.constantNode(node) <> nil, |
|
| 4105 | 4172 | case ast::NodeValue::Call(call) => { |
|
| 4106 | 4173 | if let case NodeExtra::StaticHeap(_) = self.nodeData.get(node.id).extra { |
|
| 4107 | 4174 | return true; |
|
| 4108 | 4175 | } |
|
| 4109 | 4176 | // Constructor calls (union variants, unlabeled records) are constant |
| 6324 | 6391 | ||
| 6325 | 6392 | // Bind the module symbol in the outer scope, ie. where the `mod` statement is. |
|
| 6326 | 6393 | try bindModuleIdent( |
|
| 6327 | 6394 | self, submod.entry, submod.newScope, submod.root, attrMask, submod.prevScope |
|
| 6328 | 6395 | ); |
|
| 6329 | - | let case ast::NodeValue::Block(block) = submod.root.value |
|
| 6330 | - | else panic "resolveModGraph: expected block for module root"; |
|
| 6396 | + | let case ast::NodeValue::Module(block) = submod.root.value |
|
| 6397 | + | else panic "resolveModGraph: expected module root"; |
|
| 6331 | 6398 | try resolveModuleGraph(self, &block); |
|
| 6332 | 6399 | ||
| 6333 | 6400 | exitModuleScope(self, submod); |
|
| 6334 | 6401 | } |
|
| 6335 | 6402 |
| 6341 | 6408 | return; |
|
| 6342 | 6409 | } |
|
| 6343 | 6410 | // Find module under the current module. |
|
| 6344 | 6411 | let modName = try nodeName(self, decl.name); |
|
| 6345 | 6412 | let submod = try enterSubModule(self, modName, node); |
|
| 6346 | - | let case ast::NodeValue::Block(block) = submod.root.value |
|
| 6347 | - | else panic "resolveModDecl: expected block for module root"; |
|
| 6413 | + | let case ast::NodeValue::Module(block) = submod.root.value |
|
| 6414 | + | else panic "resolveModDecl: expected module root"; |
|
| 6348 | 6415 | try declareModule(self, &block); |
|
| 6349 | 6416 | ||
| 6350 | 6417 | exitModuleScope(self, submod); |
|
| 6351 | 6418 | } |
|
| 6352 | 6419 |
| 10584 | 10651 | let exprStmt = try ast::synthNode(arena, ast::NodeValue::ExprStmt(expr)); |
|
| 10585 | 10652 | let mut bodyStmts = try ast::nodeSlice(arena, 1); |
|
| 10586 | 10653 | try bodyStmts.append(exprStmt, arena.heap); |
|
| 10587 | 10654 | let module = try ast::synthFnModule(arena, ANALYZE_EXPR_FN_NAME, bodyStmts); |
|
| 10588 | 10655 | ||
| 10589 | - | let case ast::NodeValue::Block(block) = module.modBody.value |
|
| 10590 | - | else panic "resolveExpr: expected block for module body"; |
|
| 10656 | + | let case ast::NodeValue::Module(block) = module.modBody.value |
|
| 10657 | + | else panic "resolveExpr: expected module"; |
|
| 10591 | 10658 | enterScope(self, module.modBody); |
|
| 10592 | 10659 | try resolveModuleDecls(self, &block) catch { |
|
| 10593 | 10660 | return diagnostics(self); |
|
| 10594 | 10661 | }; |
|
| 10595 | 10662 | try resolveModuleDefs(self, &block) catch { |
| 10598 | 10665 | exitScope(self); |
|
| 10599 | 10666 | ||
| 10600 | 10667 | return diagnostics(self); |
|
| 10601 | 10668 | } |
|
| 10602 | 10669 | ||
| 10603 | - | /// Analyze a parsed module root, ie. a block of top-level statements. |
|
| 10670 | + | /// Analyze a parsed module root. |
|
| 10604 | 10671 | export fn resolveModuleRoot(self: &mut Resolver, root: *ast::Node) -> Diagnostics |
|
| 10605 | 10672 | throws (ResolveError) |
|
| 10606 | 10673 | { |
|
| 10607 | - | let case ast::NodeValue::Block(block) = root.value |
|
| 10608 | - | else panic "resolveModuleRoot: expected block for module root"; |
|
| 10674 | + | let case ast::NodeValue::Module(block) = root.value |
|
| 10675 | + | else panic "resolveModuleRoot: expected module root"; |
|
| 10609 | 10676 | ||
| 10610 | 10677 | enterScope(self, root); |
|
| 10611 | 10678 | set self.phase = Phase::Declaration; |
|
| 10612 | 10679 | try resolveModuleDecls(self, &block) catch { |
|
| 10613 | 10680 | return diagnostics(self); |
| 10624 | 10691 | } |
|
| 10625 | 10692 | ||
| 10626 | 10693 | /// Analyze the module graph. This pass processes `mod` statements, creating symbols |
|
| 10627 | 10694 | /// and scopes for them, and also binds type names in each module so that cross-module |
|
| 10628 | 10695 | /// type references work regardless of declaration order. |
|
| 10629 | - | fn resolveModuleGraph(self: &mut Resolver, block: &ast::Block) throws (ResolveError) { |
|
| 10630 | - | try bindTypeNames(self, block); |
|
| 10696 | + | fn resolveModuleGraph(self: &mut Resolver, block: &ast::Module) throws (ResolveError) { |
|
| 10697 | + | try bindModuleNames(self, block); |
|
| 10631 | 10698 | ||
| 10632 | 10699 | for node in block.statements { |
|
| 10633 | 10700 | if let case ast::NodeValue::Mod(decl) = node.value { |
|
| 10634 | 10701 | try resolveModGraph(self, node, decl); |
|
| 10635 | 10702 | } |
|
| 10636 | 10703 | } |
|
| 10637 | 10704 | } |
|
| 10638 | 10705 | ||
| 10639 | - | /// Bind all type names in a module. |
|
| 10706 | + | /// Bind module declaration names and imports before their definitions. |
|
| 10640 | 10707 | /// Skips declarations that have already been bound. |
|
| 10641 | - | fn bindTypeNames(self: &mut Resolver, block: &ast::Block) throws (ResolveError) { |
|
| 10708 | + | fn bindModuleNames(self: &mut Resolver, block: &ast::Module) throws (ResolveError) { |
|
| 10642 | 10709 | for node in block.statements { |
|
| 10643 | 10710 | match node.value { |
|
| 10644 | 10711 | case ast::NodeValue::RecordDecl(decl) => { |
|
| 10645 | 10712 | if symbolFor(self, node) == nil { |
|
| 10646 | 10713 | try bindTypeName(self, node, decl.name, decl.attrs) catch {}; |
| 10657 | 10724 | } |
|
| 10658 | 10725 | } |
|
| 10659 | 10726 | else => {} |
|
| 10660 | 10727 | } |
|
| 10661 | 10728 | } |
|
| 10729 | + | // Functions and constants have symbols before their types or initializers resolve. |
|
| 10730 | + | for node in block.statements { |
|
| 10731 | + | if symbolFor(self, node) <> nil { |
|
| 10732 | + | continue; |
|
| 10733 | + | } |
|
| 10734 | + | let mut name: ?*ast::Node = nil; |
|
| 10735 | + | let mut attrs: ?ast::Attributes = nil; |
|
| 10736 | + | match node.value { |
|
| 10737 | + | case ast::NodeValue::FnDecl(decl) => { |
|
| 10738 | + | set name = decl.name; |
|
| 10739 | + | set attrs = decl.attrs; |
|
| 10740 | + | } |
|
| 10741 | + | case ast::NodeValue::ConstDecl(decl) => { |
|
| 10742 | + | set name = decl.ident; |
|
| 10743 | + | set attrs = decl.attrs; |
|
| 10744 | + | } |
|
| 10745 | + | else => {} |
|
| 10746 | + | } |
|
| 10747 | + | if let ident = name { |
|
| 10748 | + | let text = try nodeName(self, ident); |
|
| 10749 | + | let scope = self.scope; |
|
| 10750 | + | let attributes = resolveAttributes(self, attrs); |
|
| 10751 | + | try ensureLanguageAttrAllowed(self, node, attributes); |
|
| 10752 | + | let moduleId = self.currentMod; |
|
| 10753 | + | try bindIdent( |
|
| 10754 | + | self, |
|
| 10755 | + | text, |
|
| 10756 | + | node, |
|
| 10757 | + | SymbolData::Pending { scope, moduleId, resolving: false }, |
|
| 10758 | + | attributes, |
|
| 10759 | + | scope |
|
| 10760 | + | ); |
|
| 10761 | + | } |
|
| 10762 | + | } |
|
| 10763 | + | // Imports use the complete module graph and its declaration names. |
|
| 10764 | + | if self.phase == Phase::Graph { |
|
| 10765 | + | return; |
|
| 10766 | + | } |
|
| 10767 | + | for node in block.statements { |
|
| 10768 | + | if let case ast::NodeValue::Use(decl) = node.value { |
|
| 10769 | + | try resolveUse(self, node, decl); |
|
| 10770 | + | } |
|
| 10771 | + | } |
|
| 10662 | 10772 | } |
|
| 10663 | 10773 | ||
| 10664 | 10774 | /// Resolve all type bodies in a module. |
|
| 10665 | - | fn resolveTypeBodies(self: &mut Resolver, block: &ast::Block) throws (ResolveError) { |
|
| 10775 | + | fn resolveTypeBodies(self: &mut Resolver, block: &ast::Module) throws (ResolveError) { |
|
| 10666 | 10776 | for node in block.statements { |
|
| 10667 | 10777 | match node.value { |
|
| 10668 | 10778 | case ast::NodeValue::RecordDecl(decl) => { |
|
| 10669 | 10779 | try resolveRecordBody(self, node, decl) catch { |
|
| 10670 | 10780 | // Continue resolving other types even if one fails. |
| 10734 | 10844 | /// statements (`use`) are processed here, and make use of the module graph established in the |
|
| 10735 | 10845 | /// previous pass. |
|
| 10736 | 10846 | /// |
|
| 10737 | 10847 | /// Type bodies are resolved afterwards by [`resolveModuleTypes`], once every module |
|
| 10738 | 10848 | /// has its imports. |
|
| 10739 | - | fn declareModule(res: &mut Resolver, block: &ast::Block) throws (ResolveError) { |
|
| 10740 | - | // Phase 1: Bind all type names as placeholders. |
|
| 10741 | - | try bindTypeNames(res, block); |
|
| 10742 | - | // Module values have names before their signatures or initializers resolve. |
|
| 10743 | - | for node in block.statements { |
|
| 10744 | - | let mut name: ?*ast::Node = nil; |
|
| 10745 | - | let mut attrs: ?ast::Attributes = nil; |
|
| 10746 | - | match node.value { |
|
| 10747 | - | case ast::NodeValue::FnDecl(decl) => { |
|
| 10748 | - | set name = decl.name; |
|
| 10749 | - | set attrs = decl.attrs; |
|
| 10750 | - | } |
|
| 10751 | - | case ast::NodeValue::ConstDecl(decl) => { |
|
| 10752 | - | set name = decl.ident; |
|
| 10753 | - | set attrs = decl.attrs; |
|
| 10754 | - | } |
|
| 10755 | - | else => {} |
|
| 10756 | - | } |
|
| 10757 | - | if let ident = name { |
|
| 10758 | - | let text = try nodeName(res, ident); |
|
| 10759 | - | let scope = res.scope; |
|
| 10760 | - | let attributes = resolveAttributes(res, attrs); |
|
| 10761 | - | try ensureLanguageAttrAllowed(res, node, attributes); |
|
| 10762 | - | let moduleId = res.currentMod; |
|
| 10763 | - | try bindIdent( |
|
| 10764 | - | res, |
|
| 10765 | - | text, |
|
| 10766 | - | node, |
|
| 10767 | - | SymbolData::Pending { scope, moduleId, resolving: false }, |
|
| 10768 | - | attributes, |
|
| 10769 | - | scope |
|
| 10770 | - | ); |
|
| 10771 | - | } |
|
| 10772 | - | } |
|
| 10773 | - | // Phase 2: Process imports so names available from the module graph can |
|
| 10774 | - | // be used in function signatures. |
|
| 10775 | - | for node in block.statements { |
|
| 10776 | - | if let case ast::NodeValue::Use(decl) = node.value { |
|
| 10777 | - | try resolveUse(res, node, decl); |
|
| 10778 | - | } |
|
| 10779 | - | } |
|
| 10849 | + | fn declareModule(res: &mut Resolver, block: &ast::Module) throws (ResolveError) { |
|
| 10780 | 10850 | // Phase 3: Bind function signatures so that function references are |
|
| 10781 | 10851 | // available in constant and static initializers. |
|
| 10782 | 10852 | for node in block.statements { |
|
| 10783 | 10853 | if let case ast::NodeValue::FnDecl(_) = node.value { |
|
| 10784 | 10854 | let sym = symbolFor(res, node) else panic "declareModule: missing function"; |
| 10822 | 10892 | ||
| 10823 | 10893 | /// Analyze a module tree's declarations, then resolve its type bodies. |
|
| 10824 | 10894 | /// This includes the type bodies of each module and its sub-modules. |
|
| 10825 | 10895 | /// Type bodies run after every module's declarations are processed, so that |
|
| 10826 | 10896 | /// on-demand resolution in another module sees that module's imports. |
|
| 10827 | - | fn resolveModuleDecls(res: &mut Resolver, block: &ast::Block) throws (ResolveError) { |
|
| 10897 | + | fn resolveModuleDecls(res: &mut Resolver, block: &ast::Module) throws (ResolveError) { |
|
| 10898 | + | try resolveModuleTree(res, block, bindModuleNames); |
|
| 10828 | 10899 | try declareModule(res, block); |
|
| 10829 | 10900 | // Resolve type bodies (record fields, union variants). |
|
| 10830 | 10901 | try resolveModuleTree(res, block, resolveTypeBodies); |
|
| 10831 | 10902 | try resolveModuleTree(res, block, resolveModuleMembers); |
|
| 10832 | 10903 | } |
|
| 10833 | 10904 | ||
| 10834 | 10905 | /// Apply `resolveBody` to child modules before their parent. |
|
| 10835 | 10906 | fn resolveModuleTree( |
|
| 10836 | 10907 | res: &mut Resolver, |
|
| 10837 | - | block: &ast::Block, |
|
| 10838 | - | resolveBody: fn(&mut Resolver, &ast::Block) throws (ResolveError) |
|
| 10908 | + | block: &ast::Module, |
|
| 10909 | + | resolveBody: fn(&mut Resolver, &ast::Module) throws (ResolveError) |
|
| 10839 | 10910 | ) throws (ResolveError) { |
|
| 10840 | 10911 | for node in block.statements { |
|
| 10841 | 10912 | if let case ast::NodeValue::Mod(decl) = node.value { |
|
| 10842 | 10913 | if not shouldAnalyzeModule(res, decl.attrs) { |
|
| 10843 | 10914 | continue; |
|
| 10844 | 10915 | } |
|
| 10845 | 10916 | let name = try nodeName(res, decl.name); |
|
| 10846 | 10917 | let submod = try enterSubModule(res, name, node); |
|
| 10847 | - | let case ast::NodeValue::Block(child) = submod.root.value |
|
| 10848 | - | else panic "resolveModuleTree: expected module block"; |
|
| 10918 | + | let case ast::NodeValue::Module(child) = submod.root.value |
|
| 10919 | + | else panic "resolveModuleTree: expected module"; |
|
| 10849 | 10920 | try resolveModuleTree(res, &child, resolveBody) catch err { |
|
| 10850 | 10921 | exitModuleScope(res, submod); |
|
| 10851 | 10922 | throw err; |
|
| 10852 | 10923 | }; |
|
| 10853 | 10924 | exitModuleScope(res, submod); |
| 10855 | 10926 | } |
|
| 10856 | 10927 | try resolveBody(res, block); |
|
| 10857 | 10928 | } |
|
| 10858 | 10929 | ||
| 10859 | 10930 | /// Resolve constants, instances and methods after all module types are complete. |
|
| 10860 | - | fn resolveModuleMembers(res: &mut Resolver, block: &ast::Block) throws (ResolveError) { |
|
| 10931 | + | fn resolveModuleMembers(res: &mut Resolver, block: &ast::Module) throws (ResolveError) { |
|
| 10861 | 10932 | for stmt in block.statements { |
|
| 10862 | 10933 | try visitDecl(res, stmt); |
|
| 10863 | 10934 | } |
|
| 10864 | 10935 | } |
|
| 10865 | 10936 |
| 12492 | 12563 | // the next body starts with an empty list. |
|
| 12493 | 12564 | let _ = self.movedSources.take(); |
|
| 12494 | 12565 | } |
|
| 12495 | 12566 | ||
| 12496 | 12567 | /// Analyze module definitions. This pass analyzes function bodies, recursing into sub-modules. |
|
| 12497 | - | fn resolveModuleDefs(self: &mut Resolver, block: &ast::Block) throws (ResolveError) { |
|
| 12568 | + | fn resolveModuleDefs(self: &mut Resolver, block: &ast::Module) throws (ResolveError) { |
|
| 12498 | 12569 | for stmt in block.statements { |
|
| 12499 | 12570 | try visitDef(self, stmt); |
|
| 12500 | 12571 | } |
|
| 12501 | 12572 | } |
|
| 12502 | 12573 |
| 12545 | 12616 | let scope = self.moduleScopes[rootId as u32] |
|
| 12546 | 12617 | else panic "resolvePackage: module scope not found"; |
|
| 12547 | 12618 | // Set up the module scope for this package. |
|
| 12548 | 12619 | set self.scope = scope; |
|
| 12549 | 12620 | set self.currentMod = rootId; |
|
| 12550 | - | let case ast::NodeValue::Block(block) = node.value |
|
| 12551 | - | else panic "resolvePackage: expected block for module root"; |
|
| 12621 | + | let case ast::NodeValue::Module(block) = node.value |
|
| 12622 | + | else panic "resolvePackage: expected module root"; |
|
| 12552 | 12623 | // Module graph analysis phase: bind all module name symbols and scopes. |
|
| 12553 | 12624 | set self.phase = Phase::Graph; |
|
| 12554 | 12625 | try resolveModuleGraph(self, &block) catch { |
|
| 12555 | 12626 | assert self.errors.len > 0, "resolvePackage: failure should have diagnostics"; |
|
| 12556 | 12627 | return diagnostics(self); |
lib/std/lang/resolver/tests.rad
+13 -9
| 104 | 104 | let res = super::resolver(testStorage(), config); |
|
| 105 | 105 | ||
| 106 | 106 | return res; |
|
| 107 | 107 | } |
|
| 108 | 108 | ||
| 109 | - | /// Resolve a block of statements by wrapping them in a synthetic function. |
|
| 109 | + | /// Resolve parsed statements by wrapping them in a synthetic function. |
|
| 110 | 110 | export unsafe fn resolveStatements( |
|
| 111 | - | self: &mut super::Resolver, block: ast::Block, arena: &mut ast::NodeArena |
|
| 111 | + | self: &mut super::Resolver, block: ast::Module, arena: &mut ast::NodeArena |
|
| 112 | 112 | ) -> TestResult throws (super::ResolveError) { |
|
| 113 | 113 | let module = try! ast::synthFnModule(arena, super::ANALYZE_BLOCK_FN_NAME, block.statements); |
|
| 114 | 114 | let diagnostics = try super::resolveModuleRoot(self, module.modBody) catch { |
|
| 115 | 115 | return TestResult { diagnostics: super::diagnostics(self), root: module.modBody }; |
|
| 116 | 116 | }; |
| 157 | 157 | let parsed = try parser::parseModule( |
|
| 158 | 158 | &mut TEST_FRONTEND, scanner::SourceLoc::String, stmt |
|
| 159 | 159 | ) catch { |
|
| 160 | 160 | panic "resolveBlockStr: parsing failed"; |
|
| 161 | 161 | }; |
|
| 162 | - | let case ast::NodeValue::Block(block) = parsed.value |
|
| 163 | - | else panic "resolveBlockStr: expected block root"; |
|
| 162 | + | let case ast::NodeValue::Module(block) = parsed.value |
|
| 163 | + | else panic "resolveBlockStr: expected module root"; |
|
| 164 | 164 | ||
| 165 | 165 | let analysis = try resolveStatements(self, block, &mut TEST_FRONTEND.arena) catch { |
|
| 166 | 166 | throw testing::TestError::Failed; |
|
| 167 | 167 | }; |
|
| 168 | 168 | return TestResult { |
| 431 | 431 | let result = try resolveProgramStr(&mut a, program); |
|
| 432 | 432 | let err = try expectError(&result); |
|
| 433 | 433 | try expectTypeMismatch(err, expected, super::Type::Int); |
|
| 434 | 434 | } |
|
| 435 | 435 | ||
| 436 | - | /// Retrieve the nth statement from a block node. |
|
| 436 | + | /// Retrieve the nth statement from a module or block node. |
|
| 437 | 437 | export fn getBlockStmt(block: *ast::Node, index: u32) -> *ast::Node |
|
| 438 | 438 | throws (testing::TestError) |
|
| 439 | 439 | { |
|
| 440 | - | let case ast::NodeValue::Block(body) = block.value else throw testing::TestError::Failed; |
|
| 441 | - | ||
| 442 | - | if index >= body.statements.len { |
|
| 440 | + | let mut statements: *[*ast::Node] = &[]; |
|
| 441 | + | match block.value { |
|
| 442 | + | case ast::NodeValue::Module(module) => set statements = module.statements, |
|
| 443 | + | case ast::NodeValue::Block(body) => set statements = body.statements, |
|
| 444 | + | else => throw testing::TestError::Failed, |
|
| 445 | + | } |
|
| 446 | + | if index >= statements.len { |
|
| 443 | 447 | throw testing::TestError::Failed; |
|
| 444 | 448 | } |
|
| 445 | - | return body.statements[index]; |
|
| 449 | + | return statements[index]; |
|
| 446 | 450 | } |
|
| 447 | 451 | ||
| 448 | 452 | /// Retrieve a function body block by function name from the program scope. |
|
| 449 | 453 | export fn getFnBody(a: &super::Resolver, root: *ast::Node, name: *[u8]) -> ast::Block |
|
| 450 | 454 | throws (testing::TestError) |
lib/std/lang/resolver/tests/core.rad
+7 -7
| 58 | 58 | let result = try resolveProgramStr( |
|
| 59 | 59 | &mut res, |
|
| 60 | 60 | "fn unused() {} fn callback() {} constant HANDLERS: [fn(); 0] = [callback; 0]; fn body() { unused(); }" |
|
| 61 | 61 | ); |
|
| 62 | 62 | try expectNoErrors(&result); |
|
| 63 | - | let case ast::NodeValue::Block(block) = result.root.value |
|
| 63 | + | let case ast::NodeValue::Module(block) = result.root.value |
|
| 64 | 64 | else panic "interfaceFunctionUses: expected root"; |
|
| 65 | 65 | let unused = resolver::symbolFor(&res, block.statements[0]) |
|
| 66 | 66 | else panic "interfaceFunctionUses: missing private function"; |
|
| 67 | 67 | let callback = resolver::symbolFor(&res, block.statements[1]) |
|
| 68 | 68 | else panic "interfaceFunctionUses: missing callback"; |
| 2124 | 2124 | let mut a = testResolver(); |
|
| 2125 | 2125 | let result = try resolveProgramStr(&mut a, "fn f() {} f();"); |
|
| 2126 | 2126 | try expectNoErrors(&result); |
|
| 2127 | 2127 | ||
| 2128 | 2128 | let blockNode = result.root; |
|
| 2129 | - | let case ast::NodeValue::Block(block) = blockNode.value else throw testing::TestError::Failed; |
|
| 2129 | + | let case ast::NodeValue::Module(block) = blockNode.value else throw testing::TestError::Failed; |
|
| 2130 | 2130 | let fnNode = try getBlockStmt(blockNode, 0); |
|
| 2131 | 2131 | let callStmt = try getBlockStmt(blockNode, 1); |
|
| 2132 | 2132 | ||
| 2133 | 2133 | { |
|
| 2134 | 2134 | // Verify the function symbol captures an empty parameter list and void return. |
| 2154 | 2154 | let program = "fn f() -> i32 { return 1; } f();"; |
|
| 2155 | 2155 | let result = try resolveProgramStr(&mut a, program); |
|
| 2156 | 2156 | try expectNoErrors(&result); |
|
| 2157 | 2157 | ||
| 2158 | 2158 | let blockNode = result.root; |
|
| 2159 | - | let case ast::NodeValue::Block(block) = blockNode.value else throw testing::TestError::Failed; |
|
| 2159 | + | let case ast::NodeValue::Module(block) = blockNode.value else throw testing::TestError::Failed; |
|
| 2160 | 2160 | let fnNode = try getBlockStmt(blockNode, 0); |
|
| 2161 | 2161 | let callStmt = try getBlockStmt(blockNode, 1); |
|
| 2162 | 2162 | ||
| 2163 | 2163 | { |
|
| 2164 | 2164 | // Function returns i32 with no parameters. |
| 2184 | 2184 | let program = "fn f(x: i8) {} let x: i8 = 1; f(x);"; |
|
| 2185 | 2185 | let result = try resolveProgramStr(&mut a, program); |
|
| 2186 | 2186 | try expectNoErrors(&result); |
|
| 2187 | 2187 | ||
| 2188 | 2188 | let blockNode = result.root; |
|
| 2189 | - | let case ast::NodeValue::Block(block) = blockNode.value else throw testing::TestError::Failed; |
|
| 2189 | + | let case ast::NodeValue::Module(block) = blockNode.value else throw testing::TestError::Failed; |
|
| 2190 | 2190 | let fnNode = try getBlockStmt(blockNode, 0); |
|
| 2191 | 2191 | let callStmt = try getBlockStmt(blockNode, 2); |
|
| 2192 | 2192 | ||
| 2193 | 2193 | { |
|
| 2194 | 2194 | // Single parameter propagates nominal type onto the symbol and parameter node. |
| 2221 | 2221 | let program = "fn f(x: i8, y: i32) {} let x: i8 = 1; let y: i32 = 2; f(x, y);"; |
|
| 2222 | 2222 | let result = try resolveProgramStr(&mut a, program); |
|
| 2223 | 2223 | try expectNoErrors(&result); |
|
| 2224 | 2224 | ||
| 2225 | 2225 | let blockNode = result.root; |
|
| 2226 | - | let case ast::NodeValue::Block(block) = blockNode.value else throw testing::TestError::Failed; |
|
| 2226 | + | let case ast::NodeValue::Module(block) = blockNode.value else throw testing::TestError::Failed; |
|
| 2227 | 2227 | let fnNode = try getBlockStmt(blockNode, 0); |
|
| 2228 | 2228 | let callStmt = try getBlockStmt(blockNode, 3); |
|
| 2229 | 2229 | ||
| 2230 | 2230 | { |
|
| 2231 | 2231 | // Ensure multi-parameter signatures record both argument types. |
| 2261 | 2261 | let program = "fn flip(b: bool) -> bool { if b { return false; } return flip(false); }"; |
|
| 2262 | 2262 | let result = try resolveProgramStr(&mut a, program); |
|
| 2263 | 2263 | try expectNoErrors(&result); |
|
| 2264 | 2264 | ||
| 2265 | 2265 | let blockNode = result.root; |
|
| 2266 | - | let case ast::NodeValue::Block(block) = blockNode.value else throw testing::TestError::Failed; |
|
| 2266 | + | let case ast::NodeValue::Module(block) = blockNode.value else throw testing::TestError::Failed; |
|
| 2267 | 2267 | let fnNode = try getBlockStmt(blockNode, 0); |
|
| 2268 | 2268 | ||
| 2269 | 2269 | { |
|
| 2270 | 2270 | // Function symbol should be visible for recursive calls within its own body. |
|
| 2271 | 2271 | let sym = resolver::symbolFor(&a, fnNode) else throw testing::TestError::Failed; |
| 2901 | 2901 | let program = "let opt: ?i32 = 42; let value = opt else panic; value;"; |
|
| 2902 | 2902 | let result = try resolveProgramStr(&mut a, program); |
|
| 2903 | 2903 | try expectNoErrors(&result); |
|
| 2904 | 2904 | ||
| 2905 | 2905 | let blockNode = result.root; |
|
| 2906 | - | let case ast::NodeValue::Block(block) = blockNode.value else throw testing::TestError::Failed; |
|
| 2906 | + | let case ast::NodeValue::Module(block) = blockNode.value else throw testing::TestError::Failed; |
|
| 2907 | 2907 | let letElseNode = try getBlockStmt(blockNode, 1); |
|
| 2908 | 2908 | let valueStmt = try getBlockStmt(blockNode, 2); |
|
| 2909 | 2909 | ||
| 2910 | 2910 | { |
|
| 2911 | 2911 | // Ensure the bound identifier receives the inner optional type. |
lib/std/lang/resolver/tests/structure.rad
+14 -0
| 3975 | 3975 | ); |
|
| 3976 | 3976 | let result = try resolveModuleTree(&mut a, root); |
|
| 3977 | 3977 | try expectNoErrors(&result); |
|
| 3978 | 3978 | assert a.instances.len == 2; |
|
| 3979 | 3979 | } |
|
| 3980 | + | ||
| 3981 | + | /// Constant projections require immutable data and an in-bounds array index. |
|
| 3982 | + | @test unsafe fn testInvalidConstantProjections() throws (testing::TestError) { |
|
| 3983 | + | for source in [ |
|
| 3984 | + | "record S: Copy { n: u32 } static V: S = S { n: 2 }; fn f() { constant N: u32 = V.n; }", |
|
| 3985 | + | "constant A: [u32; 2] = [2; 2]; constant N: u32 = A[2];", |
|
| 3986 | + | "constant A: [u32; 0] = []; constant N: u32 = A[0];", |
|
| 3987 | + | ] { |
|
| 3988 | + | let mut res = testResolver(); |
|
| 3989 | + | let root = try registerModule(&mut super::MODULE_GRAPH, nil, "root", source); |
|
| 3990 | + | let result = try resolveModuleTree(&mut res, root); |
|
| 3991 | + | try expectErrorKind(&result, resolver::ErrorKind::ConstExprRequired); |
|
| 3992 | + | } |
|
| 3993 | + | } |
lib/std/lang/scanner.rad
+12 -0
| 373 | 373 | if consume(s, '\\') { |
|
| 374 | 374 | // Consume escapes |
|
| 375 | 375 | if isEof(s) { |
|
| 376 | 376 | return nil; |
|
| 377 | 377 | } |
|
| 378 | + | if consume(s, 'x') { |
|
| 379 | + | for _ in 0 .. 2 { |
|
| 380 | + | let digit = current(s) else { |
|
| 381 | + | return invalid(s.token, "incomplete hex escape"); |
|
| 382 | + | }; |
|
| 383 | + | if not char::isHexDigit(digit) { |
|
| 384 | + | return invalid(s.token, "invalid hex escape"); |
|
| 385 | + | } |
|
| 386 | + | advance(s); |
|
| 387 | + | } |
|
| 388 | + | continue; |
|
| 389 | + | } |
|
| 378 | 390 | } |
|
| 379 | 391 | advance(s); |
|
| 380 | 392 | } |
|
| 381 | 393 | if not consume(s, delim) { |
|
| 382 | 394 | return nil; |
std.lib.test
+1 -0
| 8 | 8 | lib/std/arch/rv64/asm/scanner/tests.rad |
|
| 9 | 9 | lib/std/lang/alloc/tests.rad |
|
| 10 | 10 | lib/std/lang/sexpr/tests.rad |
|
| 11 | 11 | lib/std/lang/layout/tests.rad |
|
| 12 | 12 | lib/std/lang/il/printer/tests.rad |
|
| 13 | + | lib/std/lang/ast/tests.rad |
|
| 13 | 14 | lib/std/lang/lower/tests.rad |
|
| 14 | 15 | lib/std/lang/parser/tests.rad |
|
| 15 | 16 | lib/std/lang/module/tests.rad |
|
| 16 | 17 | lib/std/lang/scanner/tests.rad |
|
| 17 | 18 | lib/std/lang/resolver/tests.rad |
test/format/input/escapes.rad
added
+1 -0
| 1 | + | constant BYTES: *[u8] = "\x00\x1f\x7F\xff"; |
test/format/output/escapes.rad
added
+1 -0
| 1 | + | constant BYTES: *[u8] = "\0\x1f\x7f\xff"; |
test/integration/packages.rad
+72 -13
| 101 | 101 | try harness::makeDirs(root); |
|
| 102 | 102 | let base = h.join(&[root, "/base.rad"]); |
|
| 103 | 103 | let facade = h.join(&[root, "/facade.rad"]); |
|
| 104 | 104 | let app = h.join(&[root, "/app.rad"]); |
|
| 105 | 105 | let exported = h.join(&[root, "/exported"]); |
|
| 106 | - | try fs::writeFile(base, "export fn answer() -> u32 { return 42; }\n"); |
|
| 106 | + | let provider = try h.load("test/packages/reexports/base.rad"); |
|
| 107 | + | try fs::writeFile(base, provider); |
|
| 107 | 108 | try fs::writeFile(facade, "export use base;\n"); |
|
| 108 | - | try fs::writeFile( |
|
| 109 | - | app, |
|
| 110 | - | "use facade::base; @default fn main() -> u32 { assert base::answer() == 42; return 0; }\n" |
|
| 111 | - | ); |
|
| 109 | + | try fs::writeFile(app, try h.load("test/packages/reexports/app.rad")); |
|
| 112 | 110 | try fs::writeFile(h.join(&[root, "/facade.manifest"]), "base\n"); |
|
| 113 | 111 | try fs::writeFile(h.join(&[root, "/app.manifest"]), "facade\n"); |
|
| 114 | 112 | h.add( |
|
| 115 | 113 | &[ |
|
| 116 | 114 | "-no-cache", "-pkg", "base", "-mod", base, "-pkg", "facade", "-mod", facade, |
| 129 | 127 | ] |
|
| 130 | 128 | ); |
|
| 131 | 129 | if h.compile("use a re-export without provider source", h.out(&["reexport-client.log"])) { |
|
| 132 | 130 | execute(h, h.join(&[root, "/app.rv64"])); |
|
| 133 | 131 | } |
|
| 134 | - | try fs::writeFile(base, "export fn answer() -> u32 { return 42; }\n"); |
|
| 132 | + | try fs::writeFile(base, provider); |
|
| 135 | 133 | try fs::writeFile(facade, "use base;\n"); |
|
| 136 | 134 | try fs::writeFile(h.join(&[root, "/app.manifest"]), "base\nfacade\n"); |
|
| 137 | 135 | h.add( |
|
| 138 | 136 | &[ |
|
| 139 | 137 | "-no-cache", "-pkg", "base", "-mod", base, "-pkg", "facade", "-mod", facade, |
| 142 | 140 | ); |
|
| 143 | 141 | let private = h.cc(h.take(), h.out(&["private-alias.log"])); |
|
| 144 | 142 | h.run("preserve private package alias visibility", private, process::Outcome::Exited(1), &[]); |
|
| 145 | 143 | } |
|
| 146 | 144 | ||
| 147 | - | /// Check ASCII output and reject malformed fields before loading an artifact. |
|
| 145 | + | /// Preserve assembly source paths through string escapes in metadata. |
|
| 146 | + | fn paths(h: &mut Harness) throws (sys::Error) { |
|
| 147 | + | let code = h.path(&["paths.rad"]); |
|
| 148 | + | let root = h.path(&["paths-exported"]); |
|
| 149 | + | let mut name: *mut [u8] = &mut []; |
|
| 150 | + | try! name.extend(h.path(&["assembly \"\\"]), h.arena); |
|
| 151 | + | try! name.append(255, h.arena); |
|
| 152 | + | try! name.append(31, h.arena); |
|
| 153 | + | try! name.extend("\n.ras", h.arena); |
|
| 154 | + | let assembly = &name[..]; |
|
| 155 | + | try fs::writeFile(code, "@default fn main() -> u32 { return 0; }\n"); |
|
| 156 | + | try fs::writeFile(assembly, ""); |
|
| 157 | + | h.add( |
|
| 158 | + | &[ |
|
| 159 | + | "-no-cache", "-pkg", "paths", "-mod", code, "-mod", assembly, |
|
| 160 | + | "-entry", "paths", "-ril", root, |
|
| 161 | + | ] |
|
| 162 | + | ); |
|
| 163 | + | if not h.compile("export escaped assembly paths", h.out(&["paths-export.log"])) { |
|
| 164 | + | return; |
|
| 165 | + | } |
|
| 166 | + | h.expect( |
|
| 167 | + | "metadata uses hex escapes", |
|
| 168 | + | h.join(&[root, "/paths.interface/package.metadata"]), |
|
| 169 | + | harness::Expect::Contains("\\xff\\x1f\\n.ras") |
|
| 170 | + | ); |
|
| 171 | + | let image = h.path(&["paths.rv64"]); |
|
| 172 | + | h.add(&["-no-cache", "-pkg", "paths", "-artifact", root, "-o", image]); |
|
| 173 | + | if h.compile("load escaped assembly paths", h.out(&["paths-load.log"])) { |
|
| 174 | + | execute(h, image); |
|
| 175 | + | } |
|
| 176 | + | } |
|
| 177 | + | ||
| 178 | + | /// Check record metadata and reject malformed fields before loading an artifact. |
|
| 148 | 179 | fn metadata(h: &mut Harness, root: *[u8]) throws (sys::Error) { |
|
| 149 | 180 | let path = h.join(&[root, "/dep.interface/package.metadata"]); |
|
| 150 | 181 | let original = try h.load(path); |
|
| 151 | 182 | for byte in original { |
|
| 152 | 183 | assert byte == '\n' or (byte >= 32 and byte <= 126); |
|
| 153 | 184 | } |
|
| 154 | - | let size = mem::find(original, "\nsize ") else panic; |
|
| 155 | - | let length = mem::find(&original[size + 1 ..], "\n") else panic; |
|
| 156 | - | let end = size + 1 + length; |
|
| 157 | - | let invalid = ["size 4294967296", "size -1", "size ", "size %zz"]; |
|
| 185 | + | assert mem::startsWith(original, "Package {\n"); |
|
| 186 | + | let size = mem::find(original, " size: ") else panic; |
|
| 187 | + | let length = mem::find(&original[size ..], "\n") else panic; |
|
| 188 | + | let end = size + length; |
|
| 189 | + | let invalid = [ |
|
| 190 | + | " size: 4294967296,", " size: -1,", " size: ,", |
|
| 191 | + | " size: \"bad\",", " size: 1 + 2,", " size: 1, size: 1,", |
|
| 192 | + | " extra: 1,", |
|
| 193 | + | ]; |
|
| 158 | 194 | for field in invalid { |
|
| 159 | - | try fs::writeFileParts(path, &[&original[.. size + 1], field, &original[end ..]]); |
|
| 195 | + | try fs::writeFileParts(path, &[&original[.. size], field, &original[end ..]]); |
|
| 160 | 196 | h.add(&["-no-cache", "-pkg", "dep", "-artifact", root]); |
|
| 161 | 197 | let command = h.cc(h.take(), h.out(&["invalid-metadata.log"])); |
|
| 162 | 198 | h.run("reject malformed artifact metadata", command, process::Outcome::Exited(1), &[]); |
|
| 163 | 199 | } |
|
| 164 | 200 | try fs::writeFileParts(path, &[original, "extra field\n"]); |
|
| 165 | 201 | h.add(&["-no-cache", "-pkg", "dep", "-artifact", root]); |
|
| 166 | 202 | let command = h.cc(h.take(), h.out(&["trailing-metadata.log"])); |
|
| 167 | 203 | h.run("reject trailing metadata fields", command, process::Outcome::Exited(1), &[]); |
|
| 204 | + | let image = mem::find(original, "image: \"") else panic; |
|
| 205 | + | let digit = image + "image: \"".len; |
|
| 206 | + | for hex in ["g", "-"] { |
|
| 207 | + | try fs::writeFileParts(path, &[&original[.. digit], hex, &original[digit + 1 ..]]); |
|
| 208 | + | h.add(&["-no-cache", "-pkg", "dep", "-artifact", root]); |
|
| 209 | + | let command = h.cc(h.take(), h.out(&["invalid-hex.log"])); |
|
| 210 | + | h.run("reject invalid metadata hex", command, process::Outcome::Exited(1), &[]); |
|
| 211 | + | } |
|
| 212 | + | let header = "Package {\n".len; |
|
| 213 | + | let first = mem::find(&original[header ..], "\n") else panic; |
|
| 214 | + | let secondStart = header + first + 1; |
|
| 215 | + | let second = mem::find(&original[secondStart ..], "\n") else panic; |
|
| 216 | + | let secondEnd = secondStart + second + 1; |
|
| 217 | + | try fs::writeFileParts( |
|
| 218 | + | path, |
|
| 219 | + | &[ |
|
| 220 | + | &original[.. header], &original[secondStart .. secondEnd], |
|
| 221 | + | &original[header .. secondStart], &original[secondEnd ..], |
|
| 222 | + | ] |
|
| 223 | + | ); |
|
| 224 | + | h.add(&["-no-cache", "-pkg", "dep", "-artifact", root]); |
|
| 225 | + | h.compile("load reordered metadata fields", h.out(&["reordered-metadata.log"])); |
|
| 168 | 226 | try fs::writeFile(path, original); |
|
| 169 | 227 | } |
|
| 170 | 228 | ||
| 171 | 229 | /// A different compiler image uses its own cache entries and reads compatible artifacts. |
|
| 172 | 230 | fn compilerImage(h: &mut Harness, exported: *[u8]) throws (sys::Error) { |
| 273 | 331 | } |
|
| 274 | 332 | try compilerImage(h, exported); |
|
| 275 | 333 | try metadata(h, exported); |
|
| 276 | 334 | let metadataPath = h.join(&[exported, "/dep.interface/package.metadata"]); |
|
| 277 | 335 | h.expect("artifact metadata is text", metadataPath, harness::Expect::Contains( |
|
| 278 | - | "version 1" |
|
| 336 | + | "version: 1," |
|
| 279 | 337 | )); |
|
| 280 | 338 | let declarations = h.join(&[exported, "/dep.interface/dep.rid"]); |
|
| 281 | 339 | h.expect("interface omits implementation helpers", declarations, harness::Expect::Matching { |
|
| 282 | 340 | text: "fn helper(", count: 0 |
|
| 283 | 341 | }); |
| 366 | 424 | rejected, |
|
| 367 | 425 | process::Outcome::Exited(1), |
|
| 368 | 426 | &[] |
|
| 369 | 427 | ); |
|
| 370 | 428 | try reexports(h); |
|
| 429 | + | try paths(h); |
|
| 371 | 430 | try large(h); |
|
| 372 | 431 | h.done(mark, "packages: source-free linking, cache reuse, and integrity checks passed"); |
|
| 373 | 432 | } |
test/packages/cache/app.rad
+3 -0
| 1 | 1 | //! Client exercises dynamic trait calls, opaque public methods, and borrowed results. |
|
| 2 | 2 | ||
| 3 | 3 | use dep; |
|
| 4 | 4 | ||
| 5 | + | constant EXPECTED: u32 = dep::ANSWER; |
|
| 6 | + | ||
| 5 | 7 | @default fn main() -> u32 { |
|
| 8 | + | assert dep::ANSWER == EXPECTED; |
|
| 6 | 9 | let item = dep::make(); |
|
| 7 | 10 | let readable: &opaque dep::Read = &item; |
|
| 8 | 11 | assert readable.get() == 42; |
|
| 9 | 12 | let hidden = dep::hidden(); |
|
| 10 | 13 | assert hidden.read() == 42; |
test/packages/reexports/app.rad
added
+14 -0
| 1 | + | use facade; |
|
| 2 | + | use facade::base; |
|
| 3 | + | use facade::base::*; |
|
| 4 | + | ||
| 5 | + | @default fn main() -> u32 { |
|
| 6 | + | let value: Config = base::CONFIG; |
|
| 7 | + | assert value.value == ANSWER; |
|
| 8 | + | assert base::CONFIG.value == 42; |
|
| 9 | + | assert facade::base::CONFIG.value == 42; |
|
| 10 | + | assert base::ANSWER == 42; |
|
| 11 | + | assert facade::base::answer() == 42; |
|
| 12 | + | ||
| 13 | + | return 0; |
|
| 14 | + | } |
test/packages/reexports/base.rad
added
+8 -0
| 1 | + | export constant ANSWER: u32 = 42; |
|
| 2 | + | export constant CONFIG: Config = Config { value: ANSWER }; |
|
| 3 | + | ||
| 4 | + | export record Config: Copy { value: u32 } |
|
| 5 | + | ||
| 6 | + | export fn answer() -> u32 { |
|
| 7 | + | return ANSWER; |
|
| 8 | + | } |
test/tests/const.array.record.ident.ril
+2 -8
| 18 | 18 | w32 4; |
|
| 19 | 19 | } |
|
| 20 | 20 | ||
| 21 | 21 | fn w32 $getSum() { |
|
| 22 | 22 | @entry0 |
|
| 23 | - | copy %0 $POINTS; |
|
| 24 | - | elem %1 %0 0 $L0 2; |
|
| 25 | - | sload w32 %2 %1 0; |
|
| 26 | - | copy %3 $POINTS; |
|
| 27 | - | elem %4 %3 1 $L0 2; |
|
| 28 | - | sload w32 %5 %4 4; |
|
| 29 | - | add w32 %6 %2 %5; |
|
| 30 | - | ret %6; |
|
| 23 | + | add w32 %0 1 4; |
|
| 24 | + | ret %0; |
|
| 31 | 25 | } |
test/tests/const.array.repeat.record.ril
+3 -13
| 1 | 1 | layout $L0 size 24 align 4 {} |
|
| 2 | - | layout $L1 size 8 align 4 {} |
|
| 3 | 2 | ||
| 4 | 3 | data $POINTS align 4 $L0 { |
|
| 5 | 4 | w32 1; |
|
| 6 | 5 | w32 2; |
|
| 7 | 6 | w32 1; |
| 10 | 9 | w32 2; |
|
| 11 | 10 | } |
|
| 12 | 11 | ||
| 13 | 12 | fn w32 $getSum() { |
|
| 14 | 13 | @entry0 |
|
| 15 | - | copy %0 $POINTS; |
|
| 16 | - | elem %1 %0 0 $L1 3; |
|
| 17 | - | sload w32 %2 %1 0; |
|
| 18 | - | copy %3 $POINTS; |
|
| 19 | - | elem %4 %3 1 $L1 3; |
|
| 20 | - | sload w32 %5 %4 4; |
|
| 21 | - | add w32 %6 %2 %5; |
|
| 22 | - | copy %7 $POINTS; |
|
| 23 | - | elem %8 %7 2 $L1 3; |
|
| 24 | - | sload w32 %9 %8 0; |
|
| 25 | - | add w32 %10 %6 %9; |
|
| 26 | - | ret %10; |
|
| 14 | + | add w32 %0 1 2; |
|
| 15 | + | add w32 %1 %0 1; |
|
| 16 | + | ret %1; |
|
| 27 | 17 | } |
test/tests/const.record.mutcopy.ril
+9 -13
| 15 | 15 | @entry0 |
|
| 16 | 16 | copy %1 $SCRATCH1; |
|
| 17 | 17 | reserve %2 $L0; |
|
| 18 | 18 | blit %2 %1 $L0; |
|
| 19 | 19 | load w8 %3 %0 0; |
|
| 20 | - | copy %4 $SCRATCH1; |
|
| 21 | - | load w8 %5 %4 0; |
|
| 22 | - | br.eq w8 %3 %5 @then1 @merge2; |
|
| 20 | + | br.eq w8 %3 30 @then1 @merge2; |
|
| 23 | 21 | @then1 |
|
| 24 | - | copy %6 $SCRATCH2; |
|
| 25 | - | blit %2 %6 $L0; |
|
| 22 | + | copy %4 $SCRATCH2; |
|
| 23 | + | blit %2 %4 $L0; |
|
| 26 | 24 | jmp @merge2; |
|
| 27 | 25 | @merge2 |
|
| 28 | - | reserve %8 $L1; |
|
| 29 | - | store w64 0 %8 0; |
|
| 30 | - | blit %8 %2 $L0; |
|
| 31 | - | load w64 %9 %8 0; |
|
| 32 | - | ret %9; |
|
| 26 | + | reserve %6 $L1; |
|
| 27 | + | store w64 0 %6 0; |
|
| 28 | + | blit %6 %2 $L0; |
|
| 29 | + | load w64 %7 %6 0; |
|
| 30 | + | ret %7; |
|
| 33 | 31 | } |
|
| 34 | 32 | ||
| 35 | 33 | fn w32 $main() { |
|
| 36 | 34 | @entry0 |
|
| 37 | 35 | reserve %0 $L0; |
| 73 | 71 | load w8 %12 %11 0; |
|
| 74 | 72 | br.ne w8 %12 7 @then9 @merge10; |
|
| 75 | 73 | @then9 |
|
| 76 | 74 | ret 5; |
|
| 77 | 75 | @merge10 |
|
| 78 | - | copy %13 $SCRATCH1; |
|
| 79 | - | load w8 %14 %13 0; |
|
| 80 | - | br.ne w8 %14 30 @then11 @merge12; |
|
| 76 | + | br.ne w8 30 30 @then11 @merge12; |
|
| 81 | 77 | @then11 |
|
| 82 | 78 | ret 6; |
|
| 83 | 79 | @merge12 |
|
| 84 | 80 | ret 0; |
|
| 85 | 81 | } |
test/tests/const.record.nested.ril
+4 -14
| 10 | 10 | undef * 3; |
|
| 11 | 11 | } |
|
| 12 | 12 | ||
| 13 | 13 | fn w8 $getX() { |
|
| 14 | 14 | @entry0 |
|
| 15 | - | copy %0 $O; |
|
| 16 | - | load w8 %1 %0 0; |
|
| 17 | - | ret %1; |
|
| 15 | + | ret 1; |
|
| 18 | 16 | } |
|
| 19 | 17 | ||
| 20 | 18 | fn w8 $getInnerA() { |
|
| 21 | 19 | @entry0 |
|
| 22 | - | copy %0 $O; |
|
| 23 | - | field %1 %0 4; |
|
| 24 | - | load w8 %2 %1 0; |
|
| 25 | - | ret %2; |
|
| 20 | + | ret 2; |
|
| 26 | 21 | } |
|
| 27 | 22 | ||
| 28 | 23 | fn w32 $getInnerB() { |
|
| 29 | 24 | @entry0 |
|
| 30 | - | copy %0 $O; |
|
| 31 | - | field %1 %0 4; |
|
| 32 | - | sload w32 %2 %1 4; |
|
| 33 | - | ret %2; |
|
| 25 | + | ret 3; |
|
| 34 | 26 | } |
|
| 35 | 27 | ||
| 36 | 28 | fn w8 $getY() { |
|
| 37 | 29 | @entry0 |
|
| 38 | - | copy %0 $O; |
|
| 39 | - | load w8 %1 %0 12; |
|
| 40 | - | ret %1; |
|
| 30 | + | ret 4; |
|
| 41 | 31 | } |
test/tests/const.record.packed.ril
+3 -9
| 6 | 6 | w8 3; |
|
| 7 | 7 | } |
|
| 8 | 8 | ||
| 9 | 9 | fn w8 $getA() { |
|
| 10 | 10 | @entry0 |
|
| 11 | - | copy %0 $P; |
|
| 12 | - | load w8 %1 %0 0; |
|
| 13 | - | ret %1; |
|
| 11 | + | ret 1; |
|
| 14 | 12 | } |
|
| 15 | 13 | ||
| 16 | 14 | fn w8 $getB() { |
|
| 17 | 15 | @entry0 |
|
| 18 | - | copy %0 $P; |
|
| 19 | - | load w8 %1 %0 1; |
|
| 20 | - | ret %1; |
|
| 16 | + | ret 2; |
|
| 21 | 17 | } |
|
| 22 | 18 | ||
| 23 | 19 | fn w8 $getC() { |
|
| 24 | 20 | @entry0 |
|
| 25 | - | copy %0 $P; |
|
| 26 | - | load w8 %1 %0 2; |
|
| 27 | - | ret %1; |
|
| 21 | + | ret 3; |
|
| 28 | 22 | } |
test/tests/const.record.padded.ril
+3 -9
| 8 | 8 | undef * 3; |
|
| 9 | 9 | } |
|
| 10 | 10 | ||
| 11 | 11 | fn w8 $getA() { |
|
| 12 | 12 | @entry0 |
|
| 13 | - | copy %0 $P; |
|
| 14 | - | load w8 %1 %0 0; |
|
| 15 | - | ret %1; |
|
| 13 | + | ret 1; |
|
| 16 | 14 | } |
|
| 17 | 15 | ||
| 18 | 16 | fn w32 $getB() { |
|
| 19 | 17 | @entry0 |
|
| 20 | - | copy %0 $P; |
|
| 21 | - | sload w32 %1 %0 4; |
|
| 22 | - | ret %1; |
|
| 18 | + | ret 2; |
|
| 23 | 19 | } |
|
| 24 | 20 | ||
| 25 | 21 | fn w8 $getC() { |
|
| 26 | 22 | @entry0 |
|
| 27 | - | copy %0 $P; |
|
| 28 | - | load w8 %1 %0 8; |
|
| 29 | - | ret %1; |
|
| 23 | + | ret 3; |
|
| 30 | 24 | } |
test/tests/const.record.ril
+3 -7
| 5 | 5 | w32 4; |
|
| 6 | 6 | } |
|
| 7 | 7 | ||
| 8 | 8 | fn w32 $main() { |
|
| 9 | 9 | @entry0 |
|
| 10 | - | copy %0 $ORIGIN; |
|
| 11 | - | sload w32 %1 %0 0; |
|
| 12 | - | copy %2 $ORIGIN; |
|
| 13 | - | sload w32 %3 %2 4; |
|
| 14 | - | add w32 %4 %1 %3; |
|
| 15 | - | sub w32 %5 %4 7; |
|
| 16 | - | ret %5; |
|
| 10 | + | add w32 %0 3 4; |
|
| 11 | + | sub w32 %1 %0 7; |
|
| 12 | + | ret %1; |
|
| 17 | 13 | } |
test/tests/const.record.union.ril
+2 -5
| 41 | 41 | undef * 7; |
|
| 42 | 42 | } |
|
| 43 | 43 | ||
| 44 | 44 | fn w32 $getFirstTag() { |
|
| 45 | 45 | @entry0 |
|
| 46 | - | copy %0 $KEYWORDS; |
|
| 47 | - | elem %1 %0 0 $L3 3; |
|
| 48 | - | load w8 %2 %1 16; |
|
| 49 | - | zext w8 %3 %2; |
|
| 50 | - | switch %3 (0 @case1) (1 @case2) @default3; |
|
| 46 | + | zext w8 %0 0; |
|
| 47 | + | switch %0 (0 @case1) (1 @case2) @default3; |
|
| 51 | 48 | @case1 |
|
| 52 | 49 | ret 0; |
|
| 53 | 50 | @case2 |
|
| 54 | 51 | ret 1; |
|
| 55 | 52 | @default3 |
test/tests/constant.projections.rad
added
+65 -0
| 1 | + | //! returns: 0 |
|
| 2 | + | ||
| 3 | + | /// Constant data repeated in an array. |
|
| 4 | + | constant CONFIGS: [Config; 2] = |
|
| 5 | + | [ |
|
| 6 | + | Config { |
|
| 7 | + | width: 2, flags: [false, true], small: 255, optional: 42, callback: answer, name: "ok" |
|
| 8 | + | }; |
|
| 9 | + | 2 |
|
| 10 | + | ]; |
|
| 11 | + | /// Copy an aggregate field selected through an array element. |
|
| 12 | + | constant FLAGS: [bool; 2] = CONFIGS[1].flags; |
|
| 13 | + | /// Select a scalar from an aggregate constant alias. |
|
| 14 | + | constant FLAG: bool = FLAGS[1]; |
|
| 15 | + | /// Preserve optional coercions in selected data. |
|
| 16 | + | constant OPTIONAL: ?u32 = CONFIGS[0].optional; |
|
| 17 | + | /// Narrow arithmetic uses the selected field type. |
|
| 18 | + | constant INVERT: u8 = ~CONFIGS[0].small; |
|
| 19 | + | /// Select a function address from constant data. |
|
| 20 | + | constant CALLBACK: fn() -> u32 = CONFIGS[0].callback; |
|
| 21 | + | /// Select a string address from constant data. |
|
| 22 | + | constant NAME: *[u8] = CONFIGS[1].name; |
|
| 23 | + | ||
| 24 | + | /// Nested constant data. |
|
| 25 | + | record Config: Copy { |
|
| 26 | + | /// Fixed storage size. |
|
| 27 | + | width: u32, |
|
| 28 | + | /// Boolean data copied into another constant. |
|
| 29 | + | flags: [bool; 2], |
|
| 30 | + | /// Narrow integer used by constant arithmetic. |
|
| 31 | + | small: u8, |
|
| 32 | + | /// Optional scalar value. |
|
| 33 | + | optional: ?u32, |
|
| 34 | + | /// Function referenced by constant data. |
|
| 35 | + | callback: fn() -> u32, |
|
| 36 | + | /// String referenced by constant data. |
|
| 37 | + | name: *[u8], |
|
| 38 | + | } |
|
| 39 | + | ||
| 40 | + | /// Return the test value. |
|
| 41 | + | fn answer() -> u32 { |
|
| 42 | + | return 42; |
|
| 43 | + | } |
|
| 44 | + | ||
| 45 | + | /// Check folded values and emitted constant data. |
|
| 46 | + | @default fn main() -> u32 { |
|
| 47 | + | let bytes: [u8; CONFIGS[0].width] = [0; 2]; |
|
| 48 | + | assert bytes.len == 2; |
|
| 49 | + | assert FLAG; |
|
| 50 | + | assert INVERT == 0; |
|
| 51 | + | if let value = CONFIGS[0].optional { |
|
| 52 | + | assert value == 42; |
|
| 53 | + | } else { |
|
| 54 | + | assert false; |
|
| 55 | + | } |
|
| 56 | + | assert CALLBACK() == 42; |
|
| 57 | + | assert NAME[0] == 'o'; |
|
| 58 | + | assert NAME[1] == 'k'; |
|
| 59 | + | if let value = OPTIONAL { |
|
| 60 | + | assert value == 42; |
|
| 61 | + | } else { |
|
| 62 | + | assert false; |
|
| 63 | + | } |
|
| 64 | + | return 0; |
|
| 65 | + | } |