Skip to content

Commit f55d649

Browse files
authored
Merge pull request #22992 from github/unified/conditional-compilation
Unified: Support Swift conditional compilation blocks
2 parents fbf9fca + 4904b25 commit f55d649

31 files changed

Lines changed: 1647 additions & 64 deletions

‎shared/namebinding/codeql/namebinding/LocalNameBinding.qll‎

Lines changed: 168 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,10 @@ signature module LocalNameBindingInputSig<LocationSig Location> {
3434
AstNode getChild(AstNode n, int index);
3535

3636
/**
37-
* A conditional where any local declarations in the condition are in scope
38-
* in the then-branch but not the else-branch.
37+
* A conditional with a condition, a then-branch, and an optional else-branch.
38+
*
39+
* Unless `isUnscopedConditional` holds, local declarations in the condition
40+
* are in scope in the then-branch but not the else-branch.
3941
*
4042
* Example:
4143
*
@@ -62,6 +64,25 @@ signature module LocalNameBindingInputSig<LocationSig Location> {
6264
AstNode getElse();
6365
}
6466

67+
/**
68+
* Holds if local declarations in a branch of `cond` are in scope in the
69+
* remainder of the branch _and_ following the conditional itself.
70+
*
71+
* Example:
72+
*
73+
* ```swift
74+
* #if DEBUG
75+
* let x = def1
76+
* // x is in scope here and refers to `def1`
77+
* #else
78+
* let x = def2
79+
* // x is in scope here and refers to `def2`
80+
* #endif
81+
* // x is in scope here and refers to either `def1` or `def2`
82+
* ```
83+
*/
84+
default predicate isUnscopedConditional(Conditional cond) { none() }
85+
6586
/**
6687
* A declaration where all local declarations in the left-hand side are in
6788
* scope _after_ the declaration, and where any sibling declarations with
@@ -195,17 +216,23 @@ module LocalNameBinding<LocationSig Location, LocalNameBindingInputSig<Location>
195216
*/
196217
private AstNode getChildAdj(AstNode parent, int index) {
197218
result = getChild(parent, index) and
198-
not exists(Conditional cond | result = [cond.getElse(), cond.getThen()])
219+
not exists(Conditional cond |
220+
not isUnscopedConditional(cond) and
221+
result = [cond.getElse(), cond.getThen()]
222+
)
199223
or
200224
exists(Conditional cond |
201-
parent = cond and
202-
result = cond.getElse() and
203-
index = -1
204-
or
205-
exists(int last |
206-
result = cond.getThen() and
207-
last = max(int i | conditionHasChildAt(cond, parent, i)) and
208-
index = last + 1
225+
not isUnscopedConditional(cond) and
226+
(
227+
parent = cond and
228+
result = cond.getElse() and
229+
index = -1
230+
or
231+
exists(int last |
232+
result = cond.getThen() and
233+
last = max(int i | conditionHasChildAt(cond, parent, i)) and
234+
index = last + 1
235+
)
209236
)
210237
)
211238
}
@@ -217,31 +244,137 @@ module LocalNameBinding<LocationSig Location, LocalNameBindingInputSig<Location>
217244

218245
int getRank(C parent, Ranked child) {
219246
child = getChildAdj(parent, result) and
220-
getChildAdj(parent, _) instanceof SiblingShadowingDecl
247+
// Only rank children when necessary, i.e., when there are sibling
248+
// shadowing declarations or unscoped conditionals among the children.
249+
(
250+
getChildAdj(parent, _) instanceof SiblingShadowingDecl
251+
or
252+
isUnscopedConditional(getChildAdj(parent, _))
253+
)
221254
}
222255
}
223256

224257
private predicate getRankedChild = DenseRank1<DenseRankInput>::denseRank/2;
225258

259+
/** Holds if `decl` is a possible final declaration introduced by `node`. */
260+
private predicate lastDeclAfter(AstNode node, SiblingShadowingDecl decl) {
261+
node = decl
262+
or
263+
node = any(Conditional cond | isUnscopedConditional(cond) and lastDeclInBranch(cond, decl))
264+
}
265+
266+
private predicate lastDeclInBranch(Conditional cond, SiblingShadowingDecl decl) {
267+
exists(AstNode branch | branch = [cond.getThen(), cond.getElse()] |
268+
// An `#elseif` is itself a conditional rather than a block of statements.
269+
isUnscopedConditional(branch) and lastDeclAfter(branch, decl)
270+
or
271+
not isUnscopedConditional(branch) and
272+
lastDeclInPrefix(branch, max(int i | exists(getRankedChild(branch, i))), decl)
273+
)
274+
}
275+
226276
/**
227-
* Holds if `n` is the `i`th child of `parent`, but should instead be considered
228-
* a child of a shadowing sibling declaration `decl` when resolving accesses.
277+
* Holds if the unscoped conditional `cond` might not introduce any shadowing
278+
* declarations. We need this property to determine whether declarations prior
279+
* to the conditional are still in scope following the conditional.
229280
*
230-
* This is the case when `decl` is the nearest shadowing sibling declaration
231-
* preceding `n` amongst all the children of `parent`.
281+
* For instance, in
282+
* ```swift
283+
* let x = 1
284+
* #if DEBUG
285+
* let x = 2
286+
* #else
287+
* let x = 3
288+
* #endif
289+
* print(x) // prints 2 or 3
290+
* ```
291+
* the initial declaration of `x` is certain to be shadowed after the
292+
* conditional.
232293
*
233-
* Note that `decl` may itself also have to be nested under another shadowing
234-
* sibling declaration.
294+
* If the conditional instead had no else branch or had one of the branches
295+
* not declared any shadowing declarations, then the initial declaration of
296+
* `x` might not have been shadowed after the conditional.
235297
*/
236-
private predicate shouldBeShadowingDeclChild(
237-
AstNode parent, SiblingShadowingDecl decl, int i, AstNode n
238-
) {
239-
n = getRankedChild(parent, i) and
298+
private predicate unscopedConditionalPreservesIncoming(Conditional cond) {
299+
isUnscopedConditional(cond) and
300+
(
301+
not exists(cond.getElse())
302+
or
303+
branchPreservesIncoming([cond.getThen(), cond.getElse()])
304+
)
305+
}
306+
307+
pragma[inline]
308+
private predicate branchPreservesIncoming(AstNode branch) {
309+
unscopedConditionalPreservesIncoming(branch)
310+
or
311+
not isUnscopedConditional(branch) and
240312
(
241-
decl = getRankedChild(parent, i - 1)
313+
// If the children are not ranked, then they do not contain any sibling
314+
// shadowing declarations.
315+
not exists(getRankedChild(branch, _))
242316
or
243-
shouldBeShadowingDeclChild(parent, decl, i - 1,
244-
any(AstNode prev | not prev instanceof SiblingShadowingDecl))
317+
prefixPreservesIncoming(branch, max(int i | exists(getRankedChild(branch, i))))
318+
)
319+
}
320+
321+
/**
322+
* Holds if `child` is a ranked child and might not introduce any shadowing
323+
* declaration.
324+
*
325+
* For example, the following satisfies the predicate since the declaration
326+
* might be removed at compile time.
327+
* ```swift
328+
* #if DEBUG
329+
* let value = 1
330+
* #endif
331+
* ```
332+
*/
333+
private predicate preservesIncoming(AstNode child) {
334+
child = getRankedChild(_, _) and
335+
(
336+
// A shadowing declaration always introduces a shadowing declaration.
337+
not child instanceof SiblingShadowingDecl and
338+
not isUnscopedConditional(child)
339+
or
340+
unscopedConditionalPreservesIncoming(child)
341+
)
342+
}
343+
344+
/** Summarizes the first `i` ranked children without entering ordinary nested scopes. */
345+
private predicate lastDeclInPrefix(AstNode parent, int i, SiblingShadowingDecl decl) {
346+
exists(AstNode child | child = getRankedChild(parent, i) |
347+
lastDeclAfter(child, decl)
348+
or
349+
preservesIncoming(child) and lastDeclInPrefix(parent, i - 1, decl)
350+
)
351+
}
352+
353+
/**
354+
* Holds if the first `i` children might not introduce any shadowing
355+
* declarations.
356+
*/
357+
private predicate prefixPreservesIncoming(AstNode parent, int i) {
358+
i = 0 and exists(getRankedChild(parent, _))
359+
or
360+
prefixPreservesIncoming(parent, i - 1) and
361+
preservesIncoming(getRankedChild(parent, i))
362+
}
363+
364+
/**
365+
* Holds if, instead of its parent, `n` should be considered a child of a
366+
* shadowing sibling declaration `decl` when resolving accesses.
367+
*
368+
* Each alternative through preceding unscoped conditionals contributes its own
369+
* nearest shadowing declaration.
370+
*
371+
* Note that `decl` may itself also have to be nested under another shadowing
372+
* sibling declaration.
373+
*/
374+
private predicate shouldBeShadowingDeclChild(SiblingShadowingDecl decl, AstNode n) {
375+
exists(AstNode parent, int i |
376+
n = getRankedChild(parent, i) and
377+
lastDeclInPrefix(parent, i - 1, decl)
245378
)
246379
}
247380

@@ -289,11 +422,18 @@ module LocalNameBinding<LocationSig Location, LocalNameBindingInputSig<Location>
289422
* ```
290423
*/
291424
private AstNode getParentForScoping(AstNode n) {
292-
not shouldBeShadowingDeclChild(_, _, _, n) and
293425
not exists(SiblingShadowingDecl decl | n = [decl.getRhs(), decl.getElse()]) and
294-
n = getChildAdj(result, _)
426+
n = getChildAdj(result, _) and
427+
(
428+
not n = getRankedChild(result, _)
429+
or
430+
exists(int i |
431+
n = getRankedChild(result, i) and
432+
prefixPreservesIncoming(result, i - 1)
433+
)
434+
)
295435
or
296-
shouldBeShadowingDeclChild(_, result, _, n)
436+
shouldBeShadowingDeclChild(result, n)
297437
or
298438
exists(SiblingShadowingDecl decl |
299439
result = getParentForScoping(decl) and

‎unified/extractor/ast_types.yml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,10 @@ named:
261261
block:
262262
stmt*: stmt
263263

264+
# An if expression or a conditional compilation directive (which we view as a
265+
# compile-time evaluated if expression).
264266
if_expr:
267+
modifier*: modifier
265268
condition: expr
266269
then?: expr
267270
else?: expr

‎unified/extractor/src/languages/swift/swift.rs‎

Lines changed: 69 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,12 @@ struct SwiftContext {
3838
/// True while translating a pattern. Optional chaining in this context is
3939
/// represented as an `Optional.some` call rather than being unwrapped.
4040
in_pattern: bool,
41+
/// True when a conditional compilation block should be translated into an
42+
/// if expression.
43+
conditional_compilation_as_expr: bool,
44+
/// When iterating over the clauses of a conditional compilation block, this
45+
/// holds the tail of the clauses that have already been translated.
46+
conditional_compilation_tail: Option<yeast::OutputId>,
4147
}
4248

4349
impl SwiftContext {
@@ -163,6 +169,14 @@ fn translation_rules() -> Vec<Rule<SwiftContext>> {
163169
// but a single wrapped `variableDecl` can translate to *several*
164170
// declarations (`let x = 1, y = 2`), so the wrapped node is captured with
165171
// `_*` and the result annotated `stmt*` to splice all of them.
172+
rule!(
173+
(codeBlockItem item: (ifConfigDecl) @@item)
174+
=>
175+
stmt* {
176+
ctx.conditional_compilation_as_expr = true;
177+
ctx.translate(item)
178+
}
179+
),
166180
rule!((codeBlockItem item: _* @item) => stmt* { item }),
167181
// ---- Literals ----
168182
// swift-syntax does not distinguish the lexical integer/string forms
@@ -877,6 +891,61 @@ fn translation_rules() -> Vec<Rule<SwiftContext>> {
877891
=>
878892
(parameter pattern: {parameter_pattern(&mut ctx, name)})
879893
),
894+
// ---- Conditional compilation blocks ----
895+
// Conditional compilation blocks (`#if … #elseif … #else … #endif`) are
896+
// represented with a `ifConfigDecl` node for the entire block and an
897+
// `ifConfigClause` for each branch.
898+
899+
// When a conditional compilation block is not in a context where it
900+
// should be translated into an if expression we simply extract the
901+
// first branch (for now).
902+
rule!(
903+
(ifConfigDecl
904+
clauses: (ifConfigClause elements: _* @items)
905+
clauses: _* @@rest)
906+
where !ctx.conditional_compilation_as_expr
907+
=>
908+
_* { items }
909+
),
910+
// A conditional compilation block is translated into `if_expr` nodes
911+
// with branches occurring nested within the else branch.
912+
rule!(
913+
(ifConfigDecl clauses: _* @@clauses) @@declaration
914+
=>
915+
expr {
916+
// Revert `conditional_compilation_as_expr` before processing
917+
// clauses. Note that if a clause contains a nested conditional
918+
// compilation block, then that block will be wrapped in another
919+
// `codeBlockItem` which will flip this back to `true`.
920+
ctx.conditional_compilation_as_expr = false;
921+
ctx.conditional_compilation_tail = None;
922+
for clause in clauses.into_iter().rev() {
923+
ctx.conditional_compilation_tail = ctx.translate(clause).into_iter().next();
924+
}
925+
let result = ctx.conditional_compilation_tail.expect("conditional compilation has no clauses");
926+
ctx.set_node_source_range(result, ctx.source_range(declaration))
927+
}
928+
),
929+
// A single clause is mapped to an if expression with the tail of
930+
// already processed clauses (stored in `conditional_compilation_tail`)
931+
// inserted into the else branch.
932+
rule!(
933+
(ifConfigClause condition: @condition elements: _* @items)
934+
=>
935+
(if_expr
936+
// Mark this `if_expr` as coming from conditional compilation.
937+
modifier: (modifier "conditional_compilation")
938+
condition: {condition}
939+
then: (block stmt: {items})
940+
else: {ctx.conditional_compilation_tail})
941+
),
942+
// A conditional compilation clause without a condition (a final `#else`
943+
// block).
944+
rule!(
945+
(ifConfigClause elements: _* @items)
946+
=>
947+
(block stmt: {items})
948+
),
880949
// ---- Control flow ----
881950
// An `if`/`else` expression. Conditions are joined via `and_chain`; the
882951
// then-body and optional else-body (another block, or an `ifExpr` for an
@@ -1550,7 +1619,6 @@ fn translation_rules() -> Vec<Rule<SwiftContext>> {
15501619
rule!((copyExpr) => (unsupported_node "")),
15511620
rule!((discardStmt) => (unsupported_node "")),
15521621
rule!((fallThroughStmt) => (unsupported_node "")),
1553-
rule!((ifConfigDecl) => (unsupported_node "")),
15541622
rule!((implicitlyUnwrappedOptionalType) => (unsupported_node "")),
15551623
rule!((inlineArrayType) => (unsupported_node "")),
15561624
rule!((keyPathExpr) => (unsupported_node "")),

0 commit comments

Comments
 (0)