|
| 1 | +--- |
| 2 | +category: End-users |
| 3 | +categoryindex: 1 |
| 4 | +index: 13 |
| 5 | +--- |
| 6 | +# Conditional Compilation Directives |
| 7 | + |
| 8 | +Fantomas supports formatting F# code that contains conditional compilation directives (`#if`, `#else`, `#endif`). |
| 9 | +However, there is an important limitation to be aware of. |
| 10 | + |
| 11 | +## How Fantomas handles directives |
| 12 | + |
| 13 | +Fantomas needs to parse your code into an abstract syntax tree (AST) before it can format it. |
| 14 | +The F# parser processes `#if` / `#else` / `#endif` directives at parse time, meaning it picks one branch based on which defines are active and ignores the other. |
| 15 | + |
| 16 | +To handle this, Fantomas: |
| 17 | + |
| 18 | +1. Parses your code without any defines to discover all conditional directives. |
| 19 | +2. Determines every possible combination of defines. |
| 20 | +3. Parses and formats the code once for each combination. |
| 21 | +4. Merges the results back together. |
| 22 | + |
| 23 | +## The limitation: all define combinations must produce valid syntax |
| 24 | + |
| 25 | +Because Fantomas parses your code under **every** define combination, **each combination must result in a valid syntax tree**. |
| 26 | + |
| 27 | +For example, the following code **cannot** be formatted: |
| 28 | + |
| 29 | +```fsharp |
| 30 | +module F = |
| 31 | + let a: string = |
| 32 | + #if FOO |
| 33 | + "" |
| 34 | + #endif |
| 35 | + #if BAR |
| 36 | + "a" |
| 37 | + #endif |
| 38 | +
|
| 39 | + let baz: unit = () |
| 40 | +``` |
| 41 | + |
| 42 | +When neither `FOO` nor `BAR` is defined, the code becomes: |
| 43 | + |
| 44 | +```fsharp |
| 45 | +module F = |
| 46 | + let a: string = |
| 47 | +
|
| 48 | + let baz: unit = () |
| 49 | +``` |
| 50 | + |
| 51 | +This is not valid F# — `let a` has no body — so the parser raises an error and Fantomas cannot proceed. |
| 52 | + |
| 53 | +## How to fix it |
| 54 | + |
| 55 | +Make sure that every combination of defines still produces valid F# code. The most common fix is to add an `#else` branch: |
| 56 | + |
| 57 | +```fsharp |
| 58 | +module F = |
| 59 | + let a: string = |
| 60 | + #if FOO |
| 61 | + "" |
| 62 | + #else |
| 63 | + "a" |
| 64 | + #endif |
| 65 | +
|
| 66 | + let baz: unit = () |
| 67 | +``` |
| 68 | + |
| 69 | +Now, regardless of whether `FOO` is defined, the parser always sees a complete `let` binding. |
| 70 | + |
| 71 | +## Using `.fantomasignore` |
| 72 | + |
| 73 | +If you cannot restructure the directives (e.g. because the code is generated or must match a particular pattern), you can exclude the file from formatting using a [`.fantomasignore`](https://fsprojects.github.io/fantomas/docs/end-users/IgnoreFiles.html) file. |
| 74 | + |
| 75 | +<fantomas-nav previous="{{fsdocs-previous-page-link}}" next="{{fsdocs-next-page-link}}"></fantomas-nav> |
0 commit comments