diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5d48eb81..9dfa1437 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2949,13 +2949,25 @@ jobs: run: | set -euo pipefail "$WAVE_TOOLS" prepare host --target "$WAVE_CI_TARGET" --provision + - name: Select pinned FreeBSD input cache + id: freebsd-cache + shell: bash + timeout-minutes: 5 + run: '"$WAVE_TOOLS" freebsd cache-key --github-output "$GITHUB_OUTPUT"' + - name: Restore pinned FreeBSD inputs from the package cache + uses: actions/cache/restore@v5 + with: + path: ${{ steps.freebsd-cache.outputs.path }} + key: ${{ steps.freebsd-cache.outputs.key }} - name: Fetch and verify pinned FreeBSD image id: image shell: bash timeout-minutes: 30 + env: + IMAGE_CACHE: ${{ steps.freebsd-cache.outputs.path }} run: | set -euo pipefail - "$WAVE_TOOLS" freebsd fetch-image --work-dir "$RUNNER_TEMP" --provision --github-env "$GITHUB_ENV" + "$WAVE_TOOLS" freebsd fetch-image --cache "$IMAGE_CACHE" --work-dir "$RUNNER_TEMP" --provision --github-env "$GITHUB_ENV" - name: Build compiler and validate VM reporting id: compiler shell: bash diff --git a/Cargo.lock b/Cargo.lock index 64decd08..97f416a0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -931,7 +931,7 @@ dependencies = [ [[package]] name = "wavec" -version = "0.0.1-alpha-dev" +version = "0.0.1-alpha" dependencies = [ "error", "hir", diff --git a/Cargo.toml b/Cargo.toml index eb87f225..5dc2593f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "wavec" -version = "0.0.1-alpha-dev" +version = "0.0.1-alpha" edition = "2021" [lib] diff --git a/README.md b/README.md index 11e9fea0..a906c290 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ Wave is not a C dialect and does not aim for C source compatibility. It is a new - **Cross-target compilation.** Generate code for x86-64, AArch64, RISC-V 64, LoongArch64, and WebAssembly from supported compiler hosts. - **Tool-friendly interfaces.** Query targets and compiler capabilities in human-readable or JSON form for build tools and editors. -Wave is under active alpha development (`0.0.1-alpha-dev`). Syntax and toolchain contracts are being stabilized and may still change between releases. +The current compiler version is `0.0.1-alpha`. Syntax and toolchain contracts are being stabilized and may still change between releases. ## A first Wave program @@ -295,7 +295,7 @@ compiler-diagnostic stream. ## Experimental Whale backend -Development is now `0.0.1-alpha-dev`. LLVM remains the default backend. The +LLVM is the default backend in `0.0.1-alpha`. The existing `--whale` flag selects the initial Linux amd64, O0 integration: ```shell diff --git a/VERSION.md b/VERSION.md index c01a5bac..dfa652e5 100644 --- a/VERSION.md +++ b/VERSION.md @@ -45,10 +45,8 @@ example, after the final `pre-beta` release, the first `alpha` release starts at `v0.2.1-pre-beta` is the final public `pre-beta` release. -The repository uses `v0.0.1-alpha-dev` while LLVM and Whale integration is under -development. LLVM remains the default backend; Whale is selected explicitly -with `--whale`. The `-dev` suffix is removed when the release is ready to publish -as `v0.0.1-alpha`. +The repository version for the first alpha is `v0.0.1-alpha`. LLVM remains the +default backend. Select Whale explicitly with `--whale`. The stage transition resets the release counter. Installers must determine the latest published release by publication order, not by comparing version numbers. diff --git a/front/hir/src/async_lower.rs b/front/hir/src/async_lower.rs index 525cf060..d70d52ed 100644 --- a/front/hir/src/async_lower.rs +++ b/front/hir/src/async_lower.rs @@ -645,6 +645,7 @@ fn function( ) -> FunctionNode { FunctionNode { is_async: false, + member_access: None, span: None, name, generic_params: vec![], @@ -679,6 +680,7 @@ fn emit_frame( name: frame_name, generic_params: vec![], field_spans: vec![None; fields.len()], + field_access: Vec::new(), fields, methods: vec![], visibility: Visibility::Private, diff --git a/front/hir/tests/named_proto_boundary.rs b/front/hir/tests/named_proto_boundary.rs index c24f2e22..12398165 100644 --- a/front/hir/tests/named_proto_boundary.rs +++ b/front/hir/tests/named_proto_boundary.rs @@ -11,6 +11,7 @@ fn syntax(source: &str) -> Vec { fn named_contracts_are_rejected_at_the_semantic_boundary_with_a_span() { for source in [ "struct Buffer {} proto MissingContract: Buffer { fun value(self) -> i32 { return 7; } } fun main() {}", + "struct Buffer {} proto graphics::Renderer: Buffer { fun draw(self) {} } fun main() {}", "struct Buffer {} proto First: Buffer { fun value(self) -> i32 { return 7; } } proto Second: Buffer { fun value(self) -> i32 { return 8; } } fun main() {}", ] { let error = TypedProgram::lower(syntax(source)).unwrap_err(); diff --git a/front/parser/src/ast.rs b/front/parser/src/ast.rs index cb3bb1e7..b21ef13d 100644 --- a/front/parser/src/ast.rs +++ b/front/parser/src/ast.rs @@ -67,6 +67,30 @@ pub enum Visibility { Public, } +/// An explicit member modifier, independent of a declaration's module visibility. +#[derive(Debug, Clone)] +pub struct MemberAccess { + pub kind: MemberAccessKind, + pub span: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MemberAccessKind { + Public, + Private, + Protected, +} + +impl MemberAccessKind { + pub fn spelling(self) -> &'static str { + match self { + Self::Public => "pub", + Self::Private => "priv", + Self::Protected => "protected", + } + } +} + #[derive(Debug, Clone)] pub struct TypeAliasNode { pub name: String, @@ -107,6 +131,7 @@ pub struct VariantCaseNode { #[derive(Debug, Clone)] pub struct FunctionNode { pub is_async: bool, + pub member_access: Option>, pub span: Option, pub name: String, pub generic_params: Vec, @@ -130,6 +155,8 @@ pub struct StructNode { pub generic_params: Vec, pub fields: Vec<(String, WaveType)>, pub field_spans: Vec>, + /// Explicit modifiers keyed by index in `fields`. Unmarked fields have no entry. + pub field_access: Vec<(usize, MemberAccess)>, pub methods: Vec, pub visibility: Visibility, } @@ -138,6 +165,8 @@ pub struct StructNode { pub struct ProtoImplNode { /// Named contract, or None for the existing inherent proto form. pub name: Option, + /// One span per segment of a named contract, in source order. Empty for inherent proto. + pub contract_segment_spans: Vec>, /// The target name includes generic arguments, e.g. Buffer. pub target: String, pub methods: Vec, diff --git a/front/parser/src/ast/cloning.rs b/front/parser/src/ast/cloning.rs index f92dd928..f65482f0 100644 --- a/front/parser/src/ast/cloning.rs +++ b/front/parser/src/ast/cloning.rs @@ -54,6 +54,7 @@ fn take(nodes: &mut std::vec::IntoIter, count: usize) -> Vec { fn function(n: &FunctionNode, nodes: &mut std::vec::IntoIter) -> FunctionNode { FunctionNode { is_async: n.is_async, + member_access: n.member_access.clone(), span: n.span.clone(), name: n.name.clone(), generic_params: n.generic_params.clone(), @@ -130,11 +131,13 @@ impl Clone for ASTNode { generic_params: n.generic_params.clone(), fields: n.fields.clone(), field_spans: n.field_spans.clone(), + field_access: n.field_access.clone(), methods: n.methods.iter().map(|n| function(n, &mut nodes)).collect(), visibility: n.visibility, }), ASTNode::ProtoImpl(n) => ASTNode::ProtoImpl(ProtoImplNode { name: n.name.clone(), + contract_segment_spans: n.contract_segment_spans.clone(), target: n.target.clone(), methods: n.methods.iter().map(|n| function(n, &mut nodes)).collect(), visibility: n.visibility, diff --git a/front/parser/src/ast_output.rs b/front/parser/src/ast_output.rs index 5c194a0a..a8cc59c6 100644 --- a/front/parser/src/ast_output.rs +++ b/front/parser/src/ast_output.rs @@ -279,7 +279,7 @@ impl Data for VariantCaseNode { } impl Data for FunctionNode { fn data(&self, cx: &Context) -> Value { - record( + let mut value = record( "function", vec![ ("is_async", self.is_async.data(cx)), @@ -293,7 +293,19 @@ impl Data for FunctionNode { ("export", self.export.data(cx)), ("visibility", self.visibility.data(cx)), ], - ) + ); + if let Some(access) = &self.member_access { + put(&mut value, "member_access", access.data(cx)); + } + value + } +} +impl Data for MemberAccess { + fn data(&self, cx: &Context) -> Value { + Value::object([ + ("modifier", Value::string(self.kind.spelling())), + ("span", self.span.data(cx)), + ]) } } impl Data for ExportAttribute { @@ -306,7 +318,7 @@ impl Data for ExportAttribute { } impl Data for StructNode { fn data(&self, cx: &Context) -> Value { - record( + let mut value = record( "struct", vec![ ("name", self.name.data(cx)), @@ -316,12 +328,16 @@ impl Data for StructNode { ("methods", self.methods.data(cx)), ("visibility", self.visibility.data(cx)), ], - ) + ); + if !self.field_access.is_empty() { + put(&mut value, "field_access", self.field_access.data(cx)); + } + value } } impl Data for ProtoImplNode { fn data(&self, cx: &Context) -> Value { - record( + let mut value = record( "proto_impl", vec![ ("name", self.name.data(cx)), @@ -329,7 +345,11 @@ impl Data for ProtoImplNode { ("methods", self.methods.data(cx)), ("visibility", self.visibility.data(cx)), ], - ) + ); + if self.contract_segment_spans.len() > 1 { + put(&mut value, "contract_segment_spans", self.contract_segment_spans.data(cx)); + } + value } } impl Data for FunctionSignature { diff --git a/front/parser/src/parser/functions.rs b/front/parser/src/parser/functions.rs index 40d61014..7bfe477d 100644 --- a/front/parser/src/parser/functions.rs +++ b/front/parser/src/parser/functions.rs @@ -231,6 +231,7 @@ fn parse_function_with_export_and_receiver( let body = extract_body(tokens)?; Ok(ASTNode::Function(FunctionNode { is_async, + member_access: None, span: lexer::consumed_span(before, tokens), name, generic_params, diff --git a/front/parser/src/parser/items.rs b/front/parser/src/parser/items.rs index edcfa692..f63964b4 100644 --- a/front/parser/src/parser/items.rs +++ b/front/parser/src/parser/items.rs @@ -17,7 +17,8 @@ //! generic, and return-type grammar stays consistent across item kinds. use crate::ast::{ - ASTNode, ImportNode, ProtoImplNode, StatementNode, StructNode, Visibility, WaveType, + ASTNode, FunctionNode, ImportNode, MemberAccess, MemberAccessKind, ProtoImplNode, + StatementNode, StructNode, Visibility, WaveType, }; use crate::parser::functions::{ parse_function, parse_function_with_receiver, parse_generic_param_names, @@ -101,17 +102,67 @@ pub fn parse_import(tokens: &mut Peekable>) -> Result>) -> Option { + let token = tokens.peek().copied()?; + let kind = match &token.token_type { + TokenType::Pub => MemberAccessKind::Public, + TokenType::Identifier(word) if word == "priv" => MemberAccessKind::Private, + TokenType::Identifier(word) if word == "protected" => MemberAccessKind::Protected, + _ => return None, + }; + let mut after = tokens.clone(); + after.next(); + skip_ws(&mut after); + // A contextual word followed by a colon is the field name itself. + if after.peek().is_some_and(|token| token.token_type == TokenType::Colon) { + return None; + } + *tokens = after; + Some(MemberAccess { kind, span: token.span.clone() }) +} + +fn parse_method( + tokens: &mut Peekable>, + receiver: Option, + access: Option, +) -> Result { + let parsed = match receiver { + Some(ty) => parse_function_with_receiver(tokens, ty)?, + None => parse_function(tokens)?, + }; + let ASTNode::Function(mut method) = parsed else { + unreachable!("function parser returns a function node"); + }; + method.return_type.get_or_insert(WaveType::Void); + method.member_access = access.map(Box::new); + Ok(method) +} + pub fn parse_proto(tokens: &mut Peekable>) -> Result { let anchor = tokens.peek().copied(); let context = "proto declaration"; skip_ws(tokens); - let first = crate::expr::identifier(tokens, anchor, "proto name")?; + let first_token = tokens.peek().copied(); + let mut first = crate::expr::identifier(tokens, anchor, "proto name")?; skip_ws(tokens); - // The colon distinguishes a named contract from the existing inherent - // method-attachment syntax, without changing how inherent targets lower. - let (name, target) = if tokens.peek().is_some_and(|t| t.token_type == TokenType::Colon) { - tokens.next(); + let mut contract_segment_spans = Vec::new(); + let (name, target) = if tokens + .peek() + .is_some_and(|t| matches!(t.token_type, TokenType::Colon | TokenType::DoubleColon)) + { + contract_segment_spans.push(first_token.and_then(|t| t.span.clone())); + while tokens.peek().is_some_and(|t| t.token_type == TokenType::DoubleColon) { + let separator = tokens.next(); + skip_ws(tokens); + let segment_token = tokens.peek().copied(); + let segment = crate::expr::identifier(tokens, separator, "proto contract path")?; + first.push_str("::"); + first.push_str(&segment); + contract_segment_spans.push(segment_token.and_then(|t| t.span.clone())); + skip_ws(tokens); + } + crate::expr::expect_token(tokens, anchor, TokenType::Colon, "':'", context)?; skip_ws(tokens); let target_anchor = tokens.peek().copied(); let target_type = crate::types::parse_type_checked(tokens, "proto target type")?; @@ -133,24 +184,15 @@ pub fn parse_proto(tokens: &mut Peekable>) -> Result { + Some(TokenType::Rbrace) if access.is_none() => { tokens.next(); break; }, Some(TokenType::Fun | TokenType::Async) => { - let parsed = if name.is_some() { - parse_function_with_receiver(tokens, WaveType::Struct(target.clone()))? - } else { - parse_function(tokens)? - }; - let ASTNode::Function(mut method) = parsed else { - unreachable!("function parser returns a function node"); - }; - if method.return_type.is_none() { - method.return_type = Some(WaveType::Void); - } - methods.push(method); + let receiver = name.as_ref().map(|_| WaveType::Struct(target.clone())); + methods.push(parse_method(tokens, receiver, access)?); }, None | Some(TokenType::Eof) if name.is_some() => { return Err(ParseError::expected_at( @@ -170,7 +212,13 @@ pub fn parse_proto(tokens: &mut Peekable>) -> Result>) -> Result { @@ -180,20 +228,18 @@ pub fn parse_struct(tokens: &mut Peekable>) -> Result { + Some(TokenType::Rbrace) if access.is_none() => { tokens.next(); break; }, Some(TokenType::Fun | TokenType::Async) => { - let ASTNode::Function(mut method) = parse_function(tokens)? else { unreachable!() }; - if method.return_type.is_none() { - method.return_type = Some(WaveType::Void); - } - methods.push(method); + methods.push(parse_method(tokens, None, access)?); }, Some(_) => { let before = tokens.clone(); @@ -209,6 +255,9 @@ pub fn parse_struct(tokens: &mut Peekable>) -> Result return Err(ParseError::expected_at(None, anchor, "'}'", "struct declaration")), @@ -219,6 +268,7 @@ pub fn parse_struct(tokens: &mut Peekable>) -> Result Result { crate::expression_depth::validate(nodes)?; + validate_member_access_modifiers(nodes)?; duplicates::validate(nodes, sources)?; let program = ProgramTypes::collect(nodes).map_err(|(index, message, primary)| { let mut diagnostic = semantic_diagnostic_for_top_level(nodes, index, message, primary); @@ -2245,6 +2246,30 @@ fn analyze_program_types( }) } +/// Explicit member access is syntax-only until the frontend can enforce it. +fn validate_member_access_modifiers(nodes: &[ASTNode]) -> Result<(), SemanticDiagnostic> { + for (index, node) in nodes.iter().enumerate() { + let (field, methods) = match node.unspanned() { + ASTNode::Struct(s) => (s.field_access.first().map(|(_, access)| access), &s.methods), + ASTNode::ProtoImpl(p) => (None, &p.methods), + _ => continue, + }; + if let Some(access) = + field.or_else(|| methods.iter().find_map(|m| m.member_access.as_deref())) + { + let message = format!( + "member access modifier `{}` is not supported by semantic checking yet", + access.kind.spelling() + ); + let mut diagnostic = semantic_diagnostic_for_top_level(nodes, index, message, None); + diagnostic.span = access.span.clone().or(diagnostic.span); + diagnostic.help = "inspect the parsed declaration with `build --emit=ast`".into(); + return Err(diagnostic); + } + } + Ok(()) +} + fn semantic_diagnostic_for_top_level( nodes: &[ASTNode], index: usize, diff --git a/front/parser/tests/proto_contracts.rs b/front/parser/tests/proto_contracts.rs index 6e97af81..bc100332 100644 --- a/front/parser/tests/proto_contracts.rs +++ b/front/parser/tests/proto_contracts.rs @@ -88,3 +88,87 @@ fn malformed_named_proto_syntax_has_located_diagnostics() { fn incomplete_inherent_proto_preserves_the_existing_diagnostic() { failure("proto Buffer {", "method declaration or '}'"); } + +#[test] +fn qualified_contracts_keep_target_and_each_segment_location() { + let source = "pub proto graphics :: render\n :: Renderer : Local { fun draw(r: ptr>) {} }"; + let nodes = parse(source); + let cloned = nodes[0].clone(); + for node in [&nodes[0], &cloned] { + let ASTNode::ProtoImpl(contract) = node.unspanned() else { panic!("named proto") }; + assert_eq!(contract.name.as_deref(), Some("graphics::render::Renderer")); + assert_eq!(contract.target, "Local"); + assert_eq!(contract.visibility, Visibility::Public); + let segments: Vec<_> = contract + .contract_segment_spans + .iter() + .map(|span| { + let span = span.as_ref().unwrap(); + &source[span.start..span.end] + }) + .collect(); + assert_eq!(segments, ["graphics", "render", "Renderer"]); + } + for (source, offending) in [ + ("proto gfx:: : Local {}", ": "), + ("proto gfx::123 : Local {}", "123"), + ("proto gfx::::Renderer : Local {}", "::Renderer"), + ("proto gfx::Renderer {}", "{"), + ] { + let tokens = Lexer::new_with_file(source, "proto.wave").tokenize().unwrap(); + let error = parse_syntax_with_spans(&tokens).unwrap_err(); + let span = error.span().unwrap(); + assert_eq!(span.start, source.rfind(offending).unwrap(), "{source}: {error:?}"); + } +} + +#[test] +fn member_modifiers_keep_their_own_spans_at_both_method_sites() { + let methods = "pub fun first(s: Item) {} priv fun second(s: Item) {} + protected async fun third(s: Item) {} fun protected(s: Item) {}"; + let source = format!( + "pub struct Item {{ + priv : i32; pub id: i32; priv flags: i32; protected enabled: bool; protected\n: bool; + {methods} + }} proto Item {{ {methods} }}" + ); + let nodes = parse(&source); + let cloned = nodes.clone(); + for tree in [&nodes, &cloned] { + let ASTNode::Struct(item) = tree[0].unspanned() else { panic!("struct") }; + let ASTNode::ProtoImpl(proto) = tree[1].unspanned() else { panic!("inherent proto") }; + assert!(proto.contract_segment_spans.is_empty()); + assert_eq!(item.visibility, Visibility::Public); + assert_eq!( + item.fields.iter().map(|(name, _)| name.as_str()).collect::>(), + ["priv", "id", "flags", "enabled", "protected"] + ); + let fields: Vec<_> = item + .field_access + .iter() + .map(|(index, access)| { + let span = access.span.as_ref().unwrap(); + assert_eq!(&source[span.start..span.end], access.kind.spelling()); + let field_span = item.field_spans[*index].as_ref().unwrap(); + assert!(span.end <= field_span.start); + (*index, access.kind.spelling()) + }) + .collect(); + assert_eq!(fields, [(1, "pub"), (2, "priv"), (3, "protected")]); + for (methods, offset) in + [(&item.methods, 0), (&proto.methods, source.find("proto Item").unwrap())] + { + assert_eq!(methods.len(), 4); + for (method, word) in methods.iter().zip(["pub", "priv", "protected"]) { + let access = method.member_access.as_ref().unwrap(); + let span = access.span.as_ref().unwrap(); + assert_eq!(access.kind.spelling(), word); + assert_eq!(&source[span.start..span.end], word); + assert!(span.start >= offset); + } + assert!(methods[2].is_async); + assert_eq!(methods[3].name, "protected"); + assert!(methods[3].member_access.is_none()); + } + } +} diff --git a/tests/cases/README.md b/tests/cases/README.md index 6206caec..3f71240d 100644 --- a/tests/cases/README.md +++ b/tests/cases/README.md @@ -6,6 +6,11 @@ supported targets and their CI execution. Run `build-tools/wave-tools test` from the repository root. +Case 144 executes contextual object words as identifiers. Case 145 uses +`emit=ast` to exercise syntax that semantic checking must reject. Its +`check-error` metadata gives the exact diagnostic code and label expected +from `wavec check`. The case runner also requires a valid parsed AST. + `shared/test142.wave` exercises `std::env` boundaries using only the variables in `tests/fixtures/env_boundaries.json`: missing and empty values, UTF-8 bytes, capacity errors, signed integer limits and defaults. Its `env-file` metadata diff --git a/tests/cases/shared/test144.wave b/tests/cases/shared/test144.wave new file mode 100644 index 00000000..2c385162 --- /dev/null +++ b/tests/cases/shared/test144.wave @@ -0,0 +1,29 @@ +// wave-test: mode=run, runtime=portable +// Contextual object-model words are ordinary names here. +struct Slot { + priv: i32; + protected: i32; + + fun init(self: Slot) -> i32 { + return self.priv + self.protected; + } +} + +proto Slot { + fun deinit(self: ptr, op: i32) { + self.protected += op; + } +} + +fun virtual(abstract: i32, override: i32) -> i32 { + var final: i32 = abstract + override; + return final; +} + +fun main() -> i32 { + var super: Slot = Slot { priv: 2, protected: 3 }; + var dyn: i32 = virtual(4, 5); + (&super).deinit(dyn); + if (super.init() != 14) { return 1; } + return 0; +} diff --git a/tests/cases/shared/test145.wave b/tests/cases/shared/test145.wave new file mode 100644 index 00000000..e86d373c --- /dev/null +++ b/tests/cases/shared/test145.wave @@ -0,0 +1,12 @@ +// wave-test: mode=build, runner=compile, runtime=compile, emit=ast +// wave-test: check-error=E3001: member access modifier `priv` is not supported by semantic checking yet +// Explicit member access and named contracts currently stop at the parsed AST. +struct Item { + id: i32; + priv value: i32; + pub fun read(s: Item) -> i32 { return s.value; } +} + +proto gfx::Renderer : Item { + protected fun render(s: ptr) {} +} diff --git a/tests/diagnostic_upgrades.rs b/tests/diagnostic_upgrades.rs index 1cc265b2..422e7e59 100644 --- a/tests/diagnostic_upgrades.rs +++ b/tests/diagnostic_upgrades.rs @@ -100,6 +100,83 @@ impl Drop for Case { } } +#[test] +fn explicit_member_access_is_syntax_only_in_check_and_build() { + let case = Case::new(); + for modifier in ["pub", "priv", "protected"] { + for declaration in [ + format!("struct Unused {{ {modifier} value: T; }}"), + format!("struct Item {{ {modifier} fun read(s: Item) {{}} }}"), + format!("struct Item {{}} proto Item {{ {modifier} fun read(s: Item) {{}} }}"), + ] { + let source = format!("{declaration}\nfun main() {{}}"); + let message = format!("member access modifier `{modifier}`"); + let error = case.error(&source, modifier, &message); + let detail = error.get("error").unwrap(); + assert_eq!(detail.get_str("code"), Some("E3001")); + assert_eq!( + detail.get("span").unwrap().get_u64("end"), + Some((source.find(modifier).unwrap() + modifier.len()) as u64) + ); + } + } + case.valid( + "pub struct Item { priv: i32; fun read(s: Item) -> i32 { return s.priv; } } + pub fun value() -> i32 { var s: Item = Item { priv: 4 }; return s.read(); } + fun main() {}", + ); +} + +#[test] +fn imported_member_access_reports_the_declaration_file() { + let case = Case::new(); + fs::write(case.root.join("library.wave"), "pub struct Item { protected value: i32; }").unwrap(); + fs::write( + case.root.join("main.wave"), + "import(\"./library\")::{Item}; fun main() { var x: Item; }", + ) + .unwrap(); + for command in ["check", "build"] { + let output = + case.run(&[command, "main.wave", "--target", &case.target, "--error-format=json"]); + assert_eq!(output.status.code(), Some(1), "{output:?}"); + let record = wson::parse_json(std::str::from_utf8(&output.stderr).unwrap().trim()).unwrap(); + let error = record.get("error").unwrap(); + assert!(error.get_str("message").unwrap().contains("member access modifier `protected`")); + assert!(error.get_str("file").unwrap().ends_with("library.wave")); + assert_eq!(error.get_u64("column"), Some(19)); + } +} + +#[test] +fn syntax_only_output_exposes_member_modifiers_and_qualified_contracts() { + let case = Case::new(); + let source = include_str!("cases/shared/test145.wave"); + fs::write(case.root.join("main.wave"), source).unwrap(); + let output = + case.run(&["build", "main.wave", "--emit=ast", "--ast-format=json", "--out-dir", "."]); + assert!(output.status.success(), "{output:?}"); + let ast = + wson::parse_json(&fs::read_to_string(case.root.join("main.ast.json")).unwrap()).unwrap(); + let nodes = ast.get_arr("nodes").unwrap(); + let fields = nodes[0].get_arr("field_access").unwrap(); + let Value::Array(entry) = &fields[0] else { panic!("field and modifier") }; + assert_eq!(entry[0], Value::integer(1)); + assert_eq!(entry[1].get_str("modifier"), Some("priv")); + assert_eq!(nodes[1].get_str("name"), Some("gfx::Renderer")); + let segments = nodes[1].get_arr("contract_segment_spans").unwrap(); + let names: Vec<_> = segments + .iter() + .map(|span| { + &source[span.get_u64("start").unwrap() as usize..span.get_u64("end").unwrap() as usize] + }) + .collect(); + assert_eq!(names, ["gfx", "Renderer"]); + let methods = nodes[1].get_arr("methods").unwrap(); + assert_eq!(methods[0].get("member_access").unwrap().get_str("modifier"), Some("protected")); + case.error(source, "priv value", "member access modifier `priv`"); +} + #[test] fn keyword_migrations_keep_the_original_token_and_help() { let case = Case::new(); diff --git a/tests/frontend_regressions.rs b/tests/frontend_regressions.rs index 339a4a69..07f007dd 100644 --- a/tests/frontend_regressions.rs +++ b/tests/frontend_regressions.rs @@ -50,6 +50,60 @@ fn successful(output: &Output) { ); } +#[cfg(any(feature = "llvm-target-core64", feature = "llvm-target-all"))] +#[test] +fn contextual_object_words_execute_as_existing_identifiers() { + use std::fmt::Write; + + let dir = directory(); + let path = dir.join("names.wave"); + let mut declarations = String::new(); + let mut main = String::from("fun main() -> i32 {\n"); + for (index, word) in [ + "init", + "deinit", + "priv", + "protected", + "virtual", + "abstract", + "override", + "final", + "super", + "dyn", + "op", + ] + .iter() + .enumerate() + { + let value = index + 1; + writeln!( + declarations, + "struct Slot{index} {{ {word}: i32; }} + fun {word}(s: ptr) -> i32 {{ return s.{word}; }} + fun arg{index}({word}: i32) -> i32 {{ return {word}; }} + fun local{index}() -> i32 {{ var {word}: i32 = {value}; return {word}; }}" + ) + .unwrap(); + writeln!( + main, + "var s{index}: Slot{index} = Slot{index} {{ {word}: local{index}() }}; + if (arg{index}({word}(&s{index})) != {value}) {{ return {value}; }}" + ) + .unwrap(); + } + main.push_str("return 0;\n}\n"); + declarations.push_str(&main); + std::fs::write(&path, declarations).unwrap(); + successful(&native_wave(&[ + OsStr::new("build"), + path.as_os_str(), + OsStr::new("--run"), + OsStr::new("--out-dir"), + dir.as_os_str(), + ])); + std::fs::remove_dir_all(dir).unwrap(); +} + #[test] fn runner_check_preserves_frontend_results_without_requesting_artifacts() { let dir = directory(); diff --git a/tools/src/checks.rs b/tools/src/checks.rs index 95394488..cf8d192a 100644 --- a/tools/src/checks.rs +++ b/tools/src/checks.rs @@ -332,6 +332,27 @@ pub fn main(arguments: &[OsString]) -> Result { } } +fn source_check_passed( + output: &crate::process::Output, + path: &Path, + expected: Option<&(String, String)>, +) -> bool { + if output.failure.is_some() { + return false; + } + let Some((code, label)) = expected else { return output.status == 0 }; + if output.status != 1 || !output.stdout.is_empty() { + return false; + } + let Ok(stderr) = std::str::from_utf8(&output.stderr) else { return false }; + let Ok(record) = config::parse_json(stderr) else { return false }; + record.get("error").is_some_and(|diagnostic| { + diagnostic.get_str("code") == Some(code.as_str()) + && diagnostic.get_str("label") == Some(label.as_str()) + && diagnostic.get_str("file").map(Path::new) == Some(path) + }) +} + fn source_checks(arguments: &[OsString]) -> Result { let mut args = Args::new(arguments); let compiler = args.path("--wavec")?.ok_or_else(|| error("missing --wavec"))?; @@ -350,6 +371,7 @@ fn source_checks(arguments: &[OsString]) -> Result { let manifest = crate::cases::Manifest::load(&crate::root(), true)?; let compiler = crate::runner::compiler(Some(compiler.clone()))?; for path in manifest.sources(None)? { + let metadata = crate::runner::Metadata::parse(&std::fs::read_to_string(&path)?)?; let name = path.strip_prefix(&manifest.root)?.to_string_lossy().replace('\\', "/"); let mut row = Value::object([ ("source", Value::string(&name)), @@ -363,6 +385,14 @@ fn source_checks(arguments: &[OsString]) -> Result { "--std-root".as_ref(), crate::root().join("std").as_os_str(), ]); + if let Some((code, label)) = &metadata.expected_check_error { + spec.args.push("--error-format=json".into()); + config::field( + &mut row, + "expected_error", + Value::string(format!("{code}: {label}")), + )?; + } spec.timeout = std::time::Duration::from_secs(15); match spec.run() { Ok(output) => { @@ -374,7 +404,11 @@ fn source_checks(arguments: &[OsString]) -> Result { "status", Value::string(if output.failure.as_deref() == Some("timeout") { "timeout" - } else if output.status == 0 && output.failure.is_none() { + } else if source_check_passed( + &output, + &path, + metadata.expected_check_error.as_ref(), + ) { "passed" } else { "failed" @@ -531,3 +565,34 @@ fn windows_host(arguments: &[OsString]) -> Result { } Ok(0) } + +#[cfg(test)] +mod tests { + use super::source_check_passed; + use crate::process::Output; + use std::{path::Path, time::Duration}; + + #[test] + fn a_negative_source_check_requires_the_exact_diagnostic_and_exit() { + let path = Path::new("test.wave"); + let expected = ("E3001".to_string(), "unsupported member".to_string()); + let mut output = Output { + status: 1, + stdout: Vec::new(), + stderr: + br#"{"error":{"file":"test.wave","code":"E3001","label":"unsupported member"}}"# + .to_vec(), + failure: None, + elapsed: Duration::ZERO, + }; + assert!(source_check_passed(&output, path, Some(&expected))); + assert!(!source_check_passed(&output, Path::new("other.wave"), Some(&expected))); + assert!(!source_check_passed(&output, path, Some(&("E3001".into(), "other".into())))); + assert!(!source_check_passed(&output, path, None)); + output.status = 0; + assert!(!source_check_passed(&output, path, Some(&expected))); + output.status = 1; + output.failure = Some("timeout".into()); + assert!(!source_check_passed(&output, path, Some(&expected))); + } +} diff --git a/tools/src/freebsd.rs b/tools/src/freebsd.rs index ee0cd334..0286083b 100644 --- a/tools/src/freebsd.rs +++ b/tools/src/freebsd.rs @@ -269,11 +269,6 @@ pub fn cache_identity() -> Result { Ok(storage::bytes_digest(config::json(&Value::object(values))?.as_bytes())) } -#[cfg(unix)] -fn image(work: &Path, provision: bool) -> Result { - image_to(work, work, provision) -} - #[cfg(unix)] fn image_to(cache: &Path, work: &Path, provision: bool) -> Result { let name = config::pin("FREEBSD_IMAGE")?; @@ -673,11 +668,12 @@ pub fn main(arguments: &[OsString]) -> Result { #[cfg(unix)] if command == "fetch-image" { let work = args.path("--work-dir")?.ok_or_else(|| error("missing --work-dir"))?; + let cache = args.path("--cache")?.unwrap_or_else(|| work.clone()); let provision = args.flag("--provision"); let output = args.path("--github-env")?; args.finish()?; fs::create_dir_all(&work)?; - let path = image(&work, provision)?; + let path = image_to(&cache, &work, provision)?; let name = path.file_name().unwrap().to_string_lossy(); if let Some(output) = output { storage::validate_output(&output, &crate::runner::protected_inputs(&[])?)?; @@ -918,6 +914,10 @@ fn validate_package_vm(work: &Path, cache: &Path) -> Result<()> { ]) .checked()?; let kvm = fs::OpenOptions::new().read(true).write(true).open("/dev/kvm").is_ok(); + let boot = Duration::from_secs(240); + let setup = Duration::from_secs(900); + let validation = Duration::from_secs(1200); + let shutdown = Duration::from_secs(60); let mut vm = Vm::start( vec![ "qemu-system-x86_64".into(), @@ -937,15 +937,21 @@ fn validate_package_vm(work: &Path, cache: &Path) -> Result<()> { "user,model=virtio-net-pci".into(), ], work, - Duration::from_secs(240), - Duration::from_secs(1800), + boot, + boot + setup + validation + shutdown, )?; vm.console.boot("amd64")?; vm.console.echo_output = true; - vm.console.send("mount -uw / && mkdir -p /wave-inputs && mount -t cd9660 /dev/vtbd1 /wave-inputs && sh /wave-inputs/validate.sh; printf '\\nWAVE-PACKAGE-STATUS %s\\n' \"$?\"\n")?; - let result = vm - .console - .expect(r"(?:^|\r?\n)WAVE-PACKAGE-STATUS ([0-9]+)\r?\n", Some(Duration::from_secs(1200)))?; + vm.console.send("mount -uw / && mkdir -p /wave-inputs && mount -t cd9660 /dev/vtbd1 /wave-inputs && sh /wave-inputs/provision.sh; printf '\\nWAVE-PROVISION-STATUS %s\\n' \"$?\"\n")?; + let result = + vm.console.expect(r"(?:^|\r?\n)WAVE-PROVISION-STATUS ([0-9]+)\r?\n", Some(setup))?; + if result[1] != "0" { + return Err(error(format!("FreeBSD guest provisioning failed (exit {})", result[1]))); + } + vm.console + .send("sh /wave-inputs/validate.sh; printf '\\nWAVE-PACKAGE-STATUS %s\\n' \"$?\"\n")?; + let result = + vm.console.expect(r"(?:^|\r?\n)WAVE-PACKAGE-STATUS ([0-9]+)\r?\n", Some(validation))?; if result[1] != "0" { return Err(error(format!( "FreeBSD package validation failed (exit {}); see {}", @@ -954,7 +960,7 @@ fn validate_package_vm(work: &Path, cache: &Path) -> Result<()> { ))); } vm.console.send("poweroff\n")?; - vm.shutdown(Duration::from_secs(60))?; + vm.shutdown(shutdown)?; Ok(()) } @@ -1152,15 +1158,24 @@ fn build_package(output: &Path, cache: &Path, provision: bool) -> Result<()> { .map(|path| format!("{}\n", quoted(&path.to_string_lossy()))) .collect::(); let source_root = quoted(&root.to_string_lossy()); - let script = format!( + // Installer regressions exercise real Git repositories. They need neither the + // optional Git tools nor pkg's remote file-ownership search index. + fs::write( + inputs.join("provision.sh"), r#"#!/bin/sh set -eu -export PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin export ASSUME_ALWAYS_YES=yes -# Git is a runtime prerequisite for the existing installer regression tests. dhclient vtnet0 -pkg bootstrap -f -pkg install -y git +pkg bootstrap +pkg -o PKG_RWHICH_DATABASE=no install -y -r FreeBSD git-tiny +/usr/local/bin/git --version +"#, + )?; + let script = format!( + r#"#!/bin/sh +set -eu +export PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin mkdir -p {source_root} /tmp/wave-runtime tar -xf /wave-inputs/source.tar -C {source_root} tar -xf /wave-inputs/validation.tar -C / diff --git a/tools/src/runner.rs b/tools/src/runner.rs index 65c8d93d..2a43205a 100644 --- a/tools/src/runner.rs +++ b/tools/src/runner.rs @@ -21,6 +21,7 @@ pub struct Metadata { pub emit: String, pub freestanding: bool, pub expected_exit: i32, + pub expected_check_error: Option<(String, String)>, pub udp_input: bool, pub stdin: Option, pub stdin_file: Option, @@ -46,6 +47,7 @@ impl Default for Metadata { emit: "obj".into(), freestanding: false, expected_exit: 0, + expected_check_error: None, udp_input: false, stdin: None, stdin_file: None, @@ -119,6 +121,19 @@ impl Metadata { "emit" => metadata.emit = value.to_lowercase(), "freestanding" => metadata.freestanding = boolean(value)?, "expected-exit" => metadata.expected_exit = value.parse()?, + "check-error" => { + let (code, label) = value.split_once(": ").ok_or_else(|| { + error("check-error requires a diagnostic code and an exact label") + })?; + if code.len() != 5 + || !code.starts_with('E') + || !code[1..].bytes().all(|b| b.is_ascii_digit()) + || label.is_empty() + { + return Err(error("invalid check-error diagnostic")); + } + metadata.expected_check_error = Some((code.to_string(), label.to_string())); + }, "udp-input" => metadata.udp_input = boolean(value)?, "stdin" => metadata.stdin = Some(value.to_string()), "stdin-file" => metadata.stdin_file = Some(value.to_string()), @@ -163,9 +178,12 @@ impl Metadata { { return Err(error("artifact metadata requires compile runner")); } - if !["obj", "asm", "ir", "bc"].contains(&metadata.emit.as_str()) { + if !["obj", "asm", "ir", "bc", "ast"].contains(&metadata.emit.as_str()) { return Err(error("invalid artifact emit mode")); } + if metadata.expected_check_error.is_some() && metadata.emit != "ast" { + return Err(error("check-error requires a syntax-only AST case")); + } let fixtures = [ &metadata.stdin_file, &metadata.stdout_file, @@ -451,6 +469,12 @@ fn verify_artifact(path: &Path, metadata: &Metadata, target: Option<&str>) -> Re if !path.is_file() { return Err(error(format!("compiler did not produce artifact {}", path.display()))); } + if metadata.emit == "ast" { + let ast = config::read_json(path)?; + if ast.get_str("stage") != Some("parsed") || ast.get_arr("nodes").is_none() { + return Err(error("expected a parsed Wave AST")); + } + } if metadata.emit == "obj" { if target.is_some_and(|v| v.starts_with("wasm")) || metadata.object_arch.as_deref().is_some_and(|a| a.starts_with("wasm")) @@ -560,6 +584,7 @@ fn run_one(source: &Path, metadata: &Metadata, options: &Options, row: &mut Valu } let emit = if compile { metadata.emit.as_str() } else { "exe" }; let suffix = match emit { + "ast" => "ast.json", "obj" => "o", "asm" => "s", "ir" => "ll", @@ -596,6 +621,9 @@ fn run_one(source: &Path, metadata: &Metadata, options: &Options, row: &mut Valu } if compile { args.push(format!("--emit={emit}").into()); + if emit == "ast" { + args.push("--ast-format=json".into()); + } } else if ["qemu", "wasm"].contains(&mode) { args.push("--emit=obj,bin".into()); } diff --git a/tools/tests/freebsd.rs b/tools/tests/freebsd.rs index 6f9d8b95..2acb216a 100644 --- a/tools/tests/freebsd.rs +++ b/tools/tests/freebsd.rs @@ -118,6 +118,48 @@ fn cache_outputs_identify_only_the_immutable_freebsd_inputs() { assert_eq!(fields["key"], prefix); } +#[cfg(target_os = "linux")] +#[test] +fn runtime_reuses_the_pinned_image_and_keeps_unpacked_bytes_out_of_the_cache() { + use std::{fs, process::Command}; + + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let cache = root.join("cache"); + let work = root.join("work"); + fs::create_dir(&cache).unwrap(); + fs::create_dir_all(root.join("tools/ci")).unwrap(); + let raw = root.join("image.qcow2"); + fs::write(&raw, b"image fixture").unwrap(); + let xz = Command::new("xz").arg("-c").arg(raw).output().unwrap(); + assert!(xz.status.success()); + let archive = cache.join("image.qcow2.xz"); + fs::write(&archive, &xz.stdout).unwrap(); + let digest = wave_tools::storage::digest(&archive).unwrap(); + fs::write( + root.join("tools/ci/toolchains.json"), + format!(r#"{{"FREEBSD_IMAGE":"image.qcow2.xz","FREEBSD_IMAGE_SHA256":"{digest}"}}"#), + ) + .unwrap(); + let mut fetch = Command::new(env!("CARGO_BIN_EXE_wave-tools")); + fetch + .env("WAVE_REPOSITORY", root) + .args(["freebsd", "fetch-image", "--cache"]) + .arg(&cache) + .arg("--work-dir") + .arg(&work); + let output = fetch.output().unwrap(); + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); + assert_eq!(fs::read(work.join("image.qcow2")).unwrap(), b"image fixture"); + assert_eq!(fs::read_dir(&cache).unwrap().count(), 1); + + fs::write(&archive, b"bad checksum").unwrap(); + let output = fetch.output().unwrap(); + assert!(!output.status.success()); + assert!(String::from_utf8_lossy(&output.stderr).contains("checksum mismatch")); + assert_eq!(fs::read(work.join("image.qcow2")).unwrap(), b"image fixture"); +} + #[test] #[cfg(target_os = "linux")] fn base_sysroot_expands_sparse_members_and_keeps_link_validation() {