-
Notifications
You must be signed in to change notification settings - Fork 23
feat: add arbitrary-length #magic macro using InlineArray #39
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| //===----------------------------------------------------------------------===// | ||
| // | ||
| // This source file is part of the Swift Binary Parsing open source project | ||
| // | ||
| // Copyright (c) 2025 Apple Inc. and the Swift project authors | ||
| // Licensed under Apache License v2.0 with Runtime Library Exception | ||
| // | ||
| // See https://swift.org/LICENSE.txt for license information | ||
| // | ||
| //===----------------------------------------------------------------------===// | ||
|
|
||
| import SwiftDiagnostics | ||
| import SwiftSyntax | ||
| import SwiftSyntaxBuilder | ||
| import SwiftSyntaxMacros | ||
|
|
||
| public struct MagicMacro: ExpressionMacro { | ||
| public static func expansion( | ||
| of node: some FreestandingMacroExpansionSyntax, | ||
| in context: some MacroExpansionContext | ||
| ) -> ExprSyntax { | ||
| guard let argument = node.arguments.first?.expression, | ||
| let stringLiteral = argument.as(StringLiteralExprSyntax.self) | ||
| else { | ||
| context.diagnose( | ||
| .init( | ||
| node: node, | ||
| message: MacroExpansionErrorMessage( | ||
| "Magic bytes must be expressed as a string literal."))) | ||
| return "" | ||
| } | ||
|
|
||
| // Handle both single-segment and multi-segment strings (for escape sequences) | ||
| var string = "" | ||
| for segment in stringLiteral.segments { | ||
| switch segment { | ||
| case .stringSegment(let literalSegment): | ||
| string += literalSegment.content.text | ||
| case .expressionSegment(_): | ||
| context.diagnose( | ||
| .init( | ||
| node: node, | ||
| message: MacroExpansionErrorMessage( | ||
| "String interpolation not supported in magic bytes."))) | ||
| return "" | ||
| @unknown default: | ||
| context.diagnose( | ||
| .init( | ||
| node: node, | ||
| message: MacroExpansionErrorMessage( | ||
| "Unsupported string segment type."))) | ||
| return "" | ||
| } | ||
| } | ||
|
|
||
| guard string.allSatisfy(\.isASCII) else { | ||
| context.diagnose( | ||
| .init( | ||
| node: node, | ||
| message: MacroExpansionErrorMessage( | ||
| "Magic bytes must be ASCII only."))) | ||
| return "" | ||
| } | ||
|
|
||
| guard !string.isEmpty else { | ||
| context.diagnose( | ||
| .init( | ||
| node: node, | ||
| message: MacroExpansionErrorMessage( | ||
| "Magic bytes string cannot be empty."))) | ||
| return "" | ||
| } | ||
|
|
||
| var parsingExpr = "input" | ||
| if let parsingArg = node.arguments.first(where: { | ||
| $0.label?.text == "parsing" | ||
| }) { | ||
| parsingExpr = parsingArg.expression.description | ||
| } | ||
|
|
||
| let bytes = Array(string.utf8) | ||
| let byteValues = bytes.map { String($0) }.joined(separator: ", ") | ||
|
|
||
| return """ | ||
| _loadAndCheckInlineArrayBytes(\ | ||
| parsing: \(raw: parsingExpr), \ | ||
| expectedBytes: [\(raw: byteValues)]) | ||
| """ | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,133 @@ | ||
| //===----------------------------------------------------------------------===// | ||
| // | ||
| // This source file is part of the Swift Binary Parsing open source project | ||
| // | ||
| // Copyright (c) 2025 Apple Inc. and the Swift project authors | ||
| // Licensed under Apache License v2.0 with Runtime Library Exception | ||
| // | ||
| // See https://swift.org/LICENSE.txt for license information | ||
| // | ||
| //===----------------------------------------------------------------------===// | ||
|
|
||
| import BinaryParsing | ||
| import BinaryParsingMacros | ||
| import MacroTesting | ||
| import Testing | ||
|
|
||
| @Suite( | ||
| .macros(macros: ["magic": MagicMacro.self]) | ||
| ) | ||
| struct MagicMacroTests { | ||
| // MARK: Macro expansion tests | ||
| @Test | ||
| func magicStringAsciiOnly() { | ||
| assertMacro { | ||
| #"try #magic("test", parsing: &data)"# | ||
| } expansion: { | ||
| "try _loadAndCheckInlineArrayBytes(parsing: &data, expectedBytes: [116, 101, 115, 116])" | ||
| } | ||
| } | ||
|
|
||
| @Test | ||
| func magicStringLong() { | ||
| assertMacro { | ||
| #"try #magic("hello world", parsing: &data)"# | ||
| } expansion: { | ||
| "try _loadAndCheckInlineArrayBytes(parsing: &data, expectedBytes: [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100])" | ||
| } | ||
| } | ||
|
|
||
| @Test | ||
| func magicStringSingleByte() { | ||
| assertMacro { | ||
| #"try #magic("A", parsing: &data)"# | ||
| } expansion: { | ||
| "try _loadAndCheckInlineArrayBytes(parsing: &data, expectedBytes: [65])" | ||
| } | ||
| } | ||
|
|
||
| @Test | ||
| func magicStringWithLiteralBackslashN() { | ||
| // Note: \n is treated as literal backslash + n characters, not a newline | ||
| assertMacro { | ||
| #"try #magic("hello\nworld", parsing: &data)"# | ||
| } expansion: { | ||
| "try _loadAndCheckInlineArrayBytes(parsing: &data, expectedBytes: [104, 101, 108, 108, 111, 92, 110, 119, 111, 114, 108, 100])" | ||
| } | ||
|
Comment on lines
+51
to
+56
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think this would be very surprising behavior for users. Instead of using the literal backslash, what should the compiler response be? Should we ban backslashes? Also, how does the macro respond to a string literal like |
||
| } | ||
|
|
||
| @Test | ||
| func magicStringEmpty() { | ||
| assertMacro { | ||
| #"try #magic("", parsing: &data)"# | ||
| } diagnostics: { | ||
| """ | ||
| try #magic("", parsing: &data) | ||
| ┬───────────────────────── | ||
| ╰─ 🛑 Magic bytes string cannot be empty. | ||
| """ | ||
| } | ||
| } | ||
|
|
||
| @Test | ||
| func magicCustomParsingArgument() { | ||
| assertMacro { | ||
| #"try #magic("test", parsing: &mySpan)"# | ||
| } expansion: { | ||
| "try _loadAndCheckInlineArrayBytes(parsing: &mySpan, expectedBytes: [116, 101, 115, 116])" | ||
| } | ||
| } | ||
|
|
||
| // MARK: End-to-end runtime tests | ||
| @available(macOS 26, iOS 26, watchOS 26, tvOS 26, visionOS 26, *) | ||
| @Test | ||
| func magicEndToEndMatching() throws { | ||
| let testBytes: [UInt8] = [116, 101, 115, 116] // "test" | ||
|
|
||
| try testBytes.withParserSpan { span in | ||
| // This should succeed - bytes match | ||
| try #magic("test", parsing: &span) | ||
| #expect(span.count == 0) | ||
| } | ||
| } | ||
|
|
||
| @available(macOS 26, iOS 26, watchOS 26, tvOS 26, visionOS 26, *) | ||
| @Test | ||
| func magicEndToEndMismatched() throws { | ||
| let wrongBytes: [UInt8] = [74, 80, 69, 71] // "JPEG" | ||
|
|
||
| wrongBytes.withParserSpan { span in | ||
| // This should fail - bytes don't match | ||
| #expect(throws: ParsingError.self) { | ||
| try #magic("test", parsing: &span) | ||
| } | ||
| // Span should still be consumed even though comparison failed | ||
| #expect(span.count == 0) | ||
| } | ||
| } | ||
|
|
||
| @available(macOS 26, iOS 26, watchOS 26, tvOS 26, visionOS 26, *) | ||
| @Test | ||
| func magicEndToEndLongString() throws { | ||
| let longTestBytes: [UInt8] = Array("hello world".utf8) | ||
|
|
||
| try longTestBytes.withParserSpan { span in | ||
| // Test arbitrary length support | ||
| try #magic("hello world", parsing: &span) | ||
| #expect(span.count == 0) | ||
| } | ||
| } | ||
|
|
||
| @available(macOS 26, iOS 26, watchOS 26, tvOS 26, visionOS 26, *) | ||
| @Test | ||
| func magicEndToEndInsufficientBytes() throws { | ||
| let shortBytes: [UInt8] = [116, 101] // "te" (only 2 bytes) | ||
|
|
||
| shortBytes.withParserSpan { span in | ||
| // This should fail - not enough bytes | ||
| #expect(throws: ParsingError.self) { | ||
| try #magic("test", parsing: &span) // needs 4 bytes | ||
| } | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We don't want to add this conformance here, as it can cause problems if
InlineArrayactually gains its ownEquatableconformance in the future. Let's just have an internalisEqual(to:)method to handle this kind of comparison.