|
| 1 | +# Raw Syntax Validation for Macro Testing |
| 2 | + |
| 3 | +A guide to using `SWIFTSYNTAX_ENABLE_RAWSYNTAX_VALIDATION` in third-party Swift macro packages. |
| 4 | + |
| 5 | +## Introduction |
| 6 | + |
| 7 | +SwiftSyntax is designed with fault tolerance in mind. When developing macros, it's generally robust enough to handle |
| 8 | +incorrect syntax trees without major issues. However, for developers who want to ensure they're using the SwiftSyntax |
| 9 | +API as intended, there's an additional validation tool available: the `SWIFTSYNTAX_ENABLE_RAWSYNTAX_VALIDATION` |
| 10 | +environment variable. |
| 11 | + |
| 12 | +## What SWIFTSYNTAX_ENABLE_RAWSYNTAX_VALIDATION does? |
| 13 | + |
| 14 | +This environment variable enables extra validation in SwiftSyntax during runtime. When activated, it checks: |
| 15 | + |
| 16 | +1. The correctness of each syntax node's child kind. |
| 17 | +2. That tokens only use kinds specified in the CodeGeneration package's syntax tree layout. |
| 18 | + |
| 19 | + |
| 20 | +## How to Use It |
| 21 | + |
| 22 | +If you decide to use this feature for testing, you can enable it by setting the environment variable when running your |
| 23 | +tests: |
| 24 | + |
| 25 | +```sh |
| 26 | +SWIFTSYNTAX_ENABLE_RAWSYNTAX_VALIDATION=true swift test |
| 27 | +``` |
| 28 | + |
| 29 | +## Example |
| 30 | + |
| 31 | +Consider these two syntax examples: |
| 32 | + |
| 33 | +Incorrect syntax: |
| 34 | +```swift |
| 35 | +let asyncSpecifier: TokenSyntax = "async" |
| 36 | +``` |
| 37 | + |
| 38 | +Correct syntax: |
| 39 | +```swift |
| 40 | +let asyncSpecifier: TokenSyntax = .keyword(.async) |
| 41 | +``` |
| 42 | + |
| 43 | +With raw syntax validation enabled, the incorrect syntax might produce an error like: |
| 44 | + |
| 45 | +``` |
| 46 | +Fatal error: Error validating child at index 1 of typeEffectSpecifiers: |
| 47 | +Expected token with one of [keyword('async')] but received identifier with text 'async' |
| 48 | +``` |
| 49 | + |
| 50 | +This error helps identify that you're using an identifier where a keyword is expected. The correct syntax uses |
| 51 | +`.keyword(.async)`, which properly specifies that 'async' should be treated as a keyword rather than an identifier. |
| 52 | + |
| 53 | + |
| 54 | +## Conclusion |
| 55 | + |
| 56 | +While `SWIFTSYNTAX_ENABLE_RAWSYNTAX_VALIDATION` isn't necessary for third-party macro packages, it can be a useful tool |
| 57 | +during development and testing. It helps ensure you're using the SwiftSyntax API as intended and can catch subtle issues |
| 58 | +that might affect formatting. However, remember that it comes with a performance cost and isn't recommended for use in |
| 59 | +production environments. |
0 commit comments