Skip to content

Commit 5ebb68a

Browse files
asgerfCopilot
andcommitted
Unified: Support Swift subscript calls and declarations
Extract subscript accesses as calls to a 'subscript' member, and subscript declarations as a 'subscript' getter function followed by a 'subscript' setter function. The setter clones the subscript parameters and takes the new value as an extra parameter with the reserved external name '#newValue', which identifies it as a setter method. A call appearing as an assignment target, or written back after an in-place update, now invokes the corresponding setter method, generalizing the existing property setter call logic. MaD models refer to setter methods by their argument labels, including '#newValue:', e.g. 'subscript(_:#newValue:)'. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent 698dc3a commit 5ebb68a

35 files changed

Lines changed: 1576 additions & 78 deletions

‎unified/extractor/ast_types.yml‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -342,6 +342,13 @@ named:
342342
type: expr
343343

344344
# A top-level function declaration.
345+
#
346+
# A function with a parameter whose external name is the reserved name
347+
# `#newValue` is a setter method, such as the setter of a Swift subscript. A
348+
# call `x.foo(...)` that is the target of an assignment, or is otherwise
349+
# updated in place, invokes the setter method named `foo` (whereas a call in
350+
# a read position invokes the ordinary method `foo`), passing the new value
351+
# as the `#newValue` argument.
345352
function_declaration:
346353
modifier*: modifier
347354
name_node: identifier

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

Lines changed: 214 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,25 @@ struct SwiftContext {
5151
/// When iterating over the clauses of a conditional compilation block, this
5252
/// holds the tail of the clauses that have already been translated.
5353
conditional_compilation_tail: Option<yeast::OutputId>,
54+
/// The enclosing `subscriptDecl`, set while translating its accessor
55+
/// block so the inner `accessorDecl` rule emits `subscript` methods
56+
/// rather than property accessors.
57+
subscript: Option<SubscriptContext>,
58+
/// True while translating the parameters of a subscript. Unlike function
59+
/// parameters, a subscript parameter with a single name has no argument
60+
/// label.
61+
in_subscript_parameters: bool,
62+
}
63+
64+
/// The parts of a `subscriptDecl` shared by its getter and setter. These are
65+
/// kept untranslated so that each emitted method gets its own copy.
66+
#[derive(Clone)]
67+
struct SubscriptContext {
68+
keyword: yeast::Id,
69+
modifiers: Vec<yeast::Id>,
70+
type_params: Vec<yeast::Id>,
71+
params: Vec<yeast::Id>,
72+
return_type: yeast::Id,
5473
}
5574

5675
impl SwiftContext {
@@ -153,6 +172,81 @@ fn member_chain(
153172
)
154173
}
155174

175+
/// The accessor-specific parts of a subscript getter or setter.
176+
struct SubscriptAccessor {
177+
/// Modifiers written on the accessor itself, such as `nonmutating`.
178+
modifiers: Vec<yeast::OutputId>,
179+
/// For a setter, the explicit name of its new-value parameter (`set(v)`),
180+
/// if any, and the token at which to locate an implicit `newValue`.
181+
setter: Option<(Option<yeast::Id>, yeast::Id)>,
182+
/// The raw accessor body, if any.
183+
body: Option<yeast::Id>,
184+
}
185+
186+
/// Emit a `function_declaration` named `subscript` for one accessor of a
187+
/// subscript. The shared parts of the subscript (modifiers, generic and value
188+
/// parameters and the element type) are translated afresh for each accessor,
189+
/// so a getter/setter pair each get their own copy. A setter takes the new
190+
/// value as an extra trailing parameter named `#newValue` and has no return
191+
/// type.
192+
fn subscript_method(
193+
ctx: &mut yeast::build::BuildCtx<'_, SwiftContext>,
194+
sub: SubscriptContext,
195+
accessor: SubscriptAccessor,
196+
) -> yeast::OutputId {
197+
let is_chained = ctx.is_chained;
198+
let (mods, type_params, params, element_type, body) = ctx.scoped(|ctx| {
199+
ctx.reset();
200+
let mods = ctx.translate(sub.modifiers);
201+
let type_params = ctx.translate(sub.type_params);
202+
let element_type = ctx.translate(sub.return_type).into_iter().next();
203+
let body = ctx.translate(accessor.body).into_iter().next();
204+
ctx.in_subscript_parameters = true;
205+
let params = ctx.translate(sub.params);
206+
(mods, type_params, params, element_type, body)
207+
});
208+
let body = body.unwrap_or_else(|| tree!((block)));
209+
let kw = sub.keyword;
210+
match accessor.setter {
211+
Some((param_name, spec)) => {
212+
let implicit_param_name = param_name.is_none().then_some("newValue");
213+
tree!((function_declaration
214+
modifier: {mods}
215+
modifier: {accessor.modifiers}
216+
modifier: [(modifier "chained_declaration") if { is_chained }]
217+
name_node: (identifier #{kw})
218+
type_parameter: {type_params}
219+
parameter: {params}
220+
// The new value is passed as a named parameter with the reserved
221+
// external name `#newValue`, so it can't clash with the index
222+
// parameters (including omitted defaults).
223+
parameter: [
224+
(parameter
225+
external_name_node: (identifier "#newValue" location: {spec})
226+
pattern: (identifier #{param_name})
227+
type: {element_type}
228+
location: {param_name})
229+
(parameter
230+
modifier: (modifier "generated")
231+
external_name_node: (identifier "#newValue" location: {spec})
232+
pattern: (identifier #{implicit_param_name} location: {spec})
233+
type: {element_type}
234+
location: {spec})
235+
]
236+
body: {body}))
237+
}
238+
None => tree!((function_declaration
239+
modifier: {mods}
240+
modifier: {accessor.modifiers}
241+
modifier: [(modifier "chained_declaration") if { is_chained }]
242+
name_node: (identifier #{kw})
243+
type_parameter: {type_params}
244+
parameter: {params}
245+
return_type: {element_type}
246+
body: {body})),
247+
}
248+
}
249+
156250
#[allow(clippy::too_many_lines)]
157251
fn translation_rules() -> Vec<Rule<SwiftContext>> {
158252
yeast::rules! {
@@ -419,6 +513,89 @@ fn translation_rules() -> Vec<Rule<SwiftContext>> {
419513
result
420514
}
421515
),
516+
// ---- Subscripts ----
517+
// A subscript declaration becomes a `function_declaration` named
518+
// `subscript` for its getter and, if it has a setter, another one for
519+
// the setter, which is identified by its `#newValue` parameter.
520+
// A subscript with an explicit accessor block publishes its shared parts
521+
// in `ctx` and lets the `accessorDecl` rule below emit one method per
522+
// accessor; each one after the first is tagged `chained_declaration`.
523+
rule!(
524+
(subscriptDecl
525+
modifiers: _* @@mods
526+
subscriptKeyword: @@kw
527+
genericParameterClause: (genericParameterClause parameters: _* @@type_params)?
528+
parameterClause: (functionParameterClause parameters: _* @@params)
529+
returnClause: (returnClause type: @@ret)
530+
accessorBlock: (accessorBlock accessors: (accessorDecl)+ @@accessors))
531+
=>
532+
member* {
533+
ctx.subscript = Some(SubscriptContext {
534+
keyword: kw,
535+
modifiers: mods,
536+
type_params,
537+
params,
538+
return_type: ret,
539+
});
540+
let mut result = Vec::new();
541+
for acc in accessors.into_iter() {
542+
ctx.is_chained = !result.is_empty();
543+
result.extend(ctx.translate(acc));
544+
}
545+
result
546+
}
547+
),
548+
// A subscript with a getter-only body (`subscript(i: Int) -> T { … }`).
549+
rule!(
550+
(subscriptDecl
551+
modifiers: _* @@mods
552+
subscriptKeyword: @@kw
553+
genericParameterClause: (genericParameterClause parameters: _* @@type_params)?
554+
parameterClause: (functionParameterClause parameters: _* @@params)
555+
returnClause: (returnClause type: @@ret)
556+
accessorBlock: _? @@body)
557+
=>
558+
function_declaration {
559+
let sub = SubscriptContext {
560+
keyword: kw,
561+
modifiers: mods,
562+
type_params,
563+
params,
564+
return_type: ret,
565+
};
566+
ctx.is_chained = false;
567+
subscript_method(&mut ctx, sub, SubscriptAccessor {
568+
modifiers: Vec::new(),
569+
setter: None,
570+
body,
571+
})
572+
}
573+
),
574+
// An accessor of a subscript (see above). Accessor kinds other than
575+
// `get` and `set` (such as `_modify`) are not supported.
576+
rule!(
577+
(accessorDecl
578+
modifiers: _* @acc_mods
579+
accessorSpecifier: @@spec
580+
parameters: (accessorParameters name: @@param_name)?
581+
body: _? @@body)
582+
where ctx.subscript.is_some()
583+
=>
584+
member {
585+
let sub = ctx.subscript.clone().expect("checked by guard");
586+
let spec_text = ctx.source_text(spec);
587+
if spec_text == "get" || spec_text == "set" {
588+
let setter = (spec_text == "set").then_some((param_name, spec));
589+
subscript_method(&mut ctx, sub, SubscriptAccessor {
590+
modifiers: acc_mods,
591+
setter,
592+
body,
593+
})
594+
} else {
595+
tree!((unsupported_node ""))
596+
}
597+
}
598+
),
422599
// Each `accessorDecl` becomes an `accessor_declaration`, reading the
423600
// property name/type and the modifiers from `ctx`. The
424601
// accessor kind comes straight from the specifier keyword
@@ -688,6 +865,27 @@ fn translation_rules() -> Vec<Rule<SwiftContext>> {
688865
return_type: {ret}
689866
body: (block))
690867
),
868+
// A subscript parameter with a single name has no argument label
869+
// (`subscript(i: Int)` is called as `x[0]`). It is translated in a reset
870+
// context so its type and default value are not affected.
871+
rule!(
872+
(functionParameter
873+
firstName: @@first
874+
secondName: _? @@second
875+
type: @@ty
876+
defaultValue: (initializerClause value: @@val)?)
877+
where ctx.in_subscript_parameters && second.is_none()
878+
=>
879+
parameter {
880+
ctx.reset();
881+
let ty = ctx.translate(ty).into_iter().next();
882+
let val = ctx.translate(val).into_iter().next();
883+
tree!((parameter
884+
pattern: {parameter_pattern(&mut ctx, first)}
885+
type: {ty}
886+
default: {val}))
887+
}
888+
),
691889
// A function parameter. With two names (`firstName`+`secondName`) the
692890
// first is the external argument label and the second the internal name;
693891
// with one name it is both the external and internal name.
@@ -1122,22 +1320,29 @@ fn translation_rules() -> Vec<Rule<SwiftContext>> {
11221320
=>
11231321
(key_value_pair key: {key} value: {value})
11241322
),
1125-
// A subscript access (`xs[0]`) is modelled as a call. swift-syntax does
1126-
// report a distinct `subscriptCallExpr`, so giving
1127-
// subscripts their own shape needs only a `subscript_expr` node in
1128-
// ast_types.yml and a remap here.
1323+
// A subscript access (`xs[0]`) is modelled as a call to a member named
1324+
// `subscript` on the subscripted value, i.e. `xs.subscript(0)`. This
1325+
// matches the `subscript` methods emitted for `subscriptDecl`s.
11291326
rule!(
11301327
(subscriptCallExpr
11311328
calledExpression: @callee
1329+
leftSquare: @@left_square
11321330
arguments: _* @args
11331331
trailingClosure: _? @trailing
11341332
additionalTrailingClosures: _* @additional)
11351333
=>
1136-
(call_expr
1137-
callee: {callee}
1138-
argument: {args}
1139-
argument: {trailing.map(|trailing| tree!((argument value: {trailing})))}
1140-
argument: {additional})
1334+
call_expr {
1335+
let member = tree!((member_access_expr
1336+
base: {callee}
1337+
member_name_node: (identifier "subscript" location: {left_square})
1338+
location: {callee}
1339+
location: {left_square}));
1340+
tree!((call_expr
1341+
callee: {member}
1342+
argument: {args}
1343+
argument: {trailing.map(|trailing| tree!((argument value: {trailing})))}
1344+
argument: {additional}))
1345+
}
11411346
),
11421347
// ---- Optionals and errors ----
11431348
// Optional chaining — unwrap the marker
@@ -1650,7 +1855,6 @@ fn translation_rules() -> Vec<Rule<SwiftContext>> {
16501855
rule!((postfixIfConfigExpr) => (unsupported_node "")),
16511856
rule!((poundSourceLocation) => (unsupported_node "")),
16521857
rule!((precedenceGroupDecl) => (unsupported_node "")),
1653-
rule!((subscriptDecl) => (unsupported_node "")),
16541858
rule!((suppressedType) => (unsupported_node "")),
16551859
rule!((typeExpr) => (unsupported_node "")),
16561860
rule!((yieldStmt) => (unsupported_node "")),

‎unified/extractor/tests/corpus/swift/collections/dictionary-subscript.output‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,11 @@ top_level source="⟨body⟩"
4949
modifier: modifier "let" source="let"
5050
pattern: identifier "v" source="v"
5151
value:
52-
call_expr source="⟨callee⟩[⟨argument⟩]"
53-
callee: identifier "d" source="d"
52+
call_expr source="⟨callee⟩⟨argument⟩]"
53+
callee:
54+
member_access_expr source="⟨base⟩⟨member_name_node⟩"
55+
base: identifier "d" source="d"
56+
member_name_node: identifier "subscript" source="["
5457
argument:
5558
argument source="⟨value⟩"
5659
value: string_literal "\"key\"" source="\"key\""

‎unified/extractor/tests/corpus/swift/collections/subscript-access.output‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,11 @@ top_level source="⟨body⟩"
4646
modifier: modifier "let" source="let"
4747
pattern: identifier "first" source="first"
4848
value:
49-
call_expr source="⟨callee⟩[⟨argument⟩]"
50-
callee: identifier "xs" source="xs"
49+
call_expr source="⟨callee⟩⟨argument⟩]"
50+
callee:
51+
member_access_expr source="⟨base⟩⟨member_name_node⟩"
52+
base: identifier "xs" source="xs"
53+
member_name_node: identifier "subscript" source="["
5154
argument:
5255
argument source="⟨value⟩"
5356
value: int_literal "0" source="0"

‎unified/extractor/tests/corpus/swift/expressions/subscript-call.output‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -99,13 +99,19 @@ top_level source="⟨body⟩"
9999
body:
100100
block source="⟨stmt⟩\n\n⟨stmt⟩"
101101
stmt:
102-
call_expr source="⟨callee⟩[⟨argument⟩]"
103-
callee: identifier "handlers" source="handlers"
102+
call_expr source="⟨callee⟩⟨argument⟩]"
103+
callee:
104+
member_access_expr source="⟨base⟩⟨member_name_node⟩"
105+
base: identifier "handlers" source="handlers"
106+
member_name_node: identifier "subscript" source="["
104107
argument:
105108
argument source="⟨value⟩"
106109
value: int_literal "0" source="0"
107-
call_expr source="⟨callee⟩[⟨argument⟩] ⟨argument⟩ ⟨argument⟩ ⟨argument⟩"
108-
callee: identifier "handlers" source="handlers"
110+
call_expr source="⟨callee⟩⟨argument⟩] ⟨argument⟩ ⟨argument⟩ ⟨argument⟩"
111+
callee:
112+
member_access_expr source="⟨base⟩⟨member_name_node⟩"
113+
base: identifier "handlers" source="handlers"
114+
member_name_node: identifier "subscript" source="["
109115
argument:
110116
argument source="⟨value⟩"
111117
value: int_literal "0" source="0"

0 commit comments

Comments
 (0)