Skip to content

Commit eeab6e5

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 method followed by a 'subscript' accessor of kind 'setter_method'. The setter clones the subscript parameters and takes the new value as an extra trailing positional parameter. 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 as 'name:set', with the value as the last argument label, e.g. 'subscript:set(_:_:)'. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent 698dc3a commit eeab6e5

37 files changed

Lines changed: 1509 additions & 82 deletions

‎unified/extractor/ast_types.yml‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -536,15 +536,23 @@ named:
536536
# downstream. Stored properties with observers are emitted as a
537537
# variable_declaration followed by one accessor_declaration per observer
538538
# (each observer also tagged with `chained_declaration`).
539+
#
540+
# An accessor of kind `setter_method` is a setter invoked via call syntax,
541+
# such as the setter of a Swift subscript. A call `x.foo(...)` that is the
542+
# target of an assignment, or is otherwise updated in place, invokes the
543+
# `setter_method` accessor named `foo` (whereas a call in a read position
544+
# invokes the ordinary method `foo`). The setter takes the new value as an
545+
# extra trailing positional parameter.
539546
accessor_declaration:
540547
modifier*: modifier
541548
name_node: identifier
542549
accessor_kind: accessor_kind
550+
type_parameter*: type_parameter
543551
parameter*: parameter
544552
return_type?: expr
545553
body?: block
546554

547-
# "get", "set", or a language-specific kind like "didSet"
555+
# "get", "set", "setter_method", or a language-specific kind like "didSet"
548556
accessor_kind:
549557

550558
# Static or instance initializer block. That is, code that runs at initialization time of either the class or an instance.

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

Lines changed: 210 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,77 @@ 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 the declaration for one accessor of a subscript: the getter is a
187+
/// `function_declaration` named `subscript`, and the setter an
188+
/// `accessor_declaration` of kind `setter_method`. The shared parts of the subscript (modifiers, generic and value
189+
/// parameters and the element type) are translated afresh for each accessor,
190+
/// so a getter/setter pair each get their own copy. A setter takes the new
191+
/// value as an extra trailing positional parameter and has no return 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!((accessor_declaration
214+
modifier: {mods}
215+
modifier: {accessor.modifiers}
216+
modifier: [(modifier "chained_declaration") if { is_chained }]
217+
name_node: (identifier #{kw})
218+
accessor_kind: (accessor_kind "setter_method" location: {spec})
219+
type_parameter: {type_params}
220+
parameter: {params}
221+
parameter: [
222+
(parameter
223+
pattern: (identifier #{param_name})
224+
type: {element_type}
225+
location: {param_name})
226+
(parameter
227+
modifier: (modifier "generated")
228+
pattern: (identifier #{implicit_param_name} location: {spec})
229+
type: {element_type}
230+
location: {spec})
231+
]
232+
body: {body}))
233+
}
234+
None => tree!((function_declaration
235+
modifier: {mods}
236+
modifier: {accessor.modifiers}
237+
modifier: [(modifier "chained_declaration") if { is_chained }]
238+
name_node: (identifier #{kw})
239+
type_parameter: {type_params}
240+
parameter: {params}
241+
return_type: {element_type}
242+
body: {body})),
243+
}
244+
}
245+
156246
#[allow(clippy::too_many_lines)]
157247
fn translation_rules() -> Vec<Rule<SwiftContext>> {
158248
yeast::rules! {
@@ -419,6 +509,89 @@ fn translation_rules() -> Vec<Rule<SwiftContext>> {
419509
result
420510
}
421511
),
512+
// ---- Subscripts ----
513+
// A subscript declaration becomes a `function_declaration` named
514+
// `subscript` for its getter and, if it has a setter, an
515+
// `accessor_declaration` of kind `setter_method` named `subscript`.
516+
// A subscript with an explicit accessor block publishes its shared parts
517+
// in `ctx` and lets the `accessorDecl` rule below emit one method per
518+
// accessor; each one after the first is tagged `chained_declaration`.
519+
rule!(
520+
(subscriptDecl
521+
modifiers: _* @@mods
522+
subscriptKeyword: @@kw
523+
genericParameterClause: (genericParameterClause parameters: _* @@type_params)?
524+
parameterClause: (functionParameterClause parameters: _* @@params)
525+
returnClause: (returnClause type: @@ret)
526+
accessorBlock: (accessorBlock accessors: (accessorDecl)+ @@accessors))
527+
=>
528+
member* {
529+
ctx.subscript = Some(SubscriptContext {
530+
keyword: kw,
531+
modifiers: mods,
532+
type_params,
533+
params,
534+
return_type: ret,
535+
});
536+
let mut result = Vec::new();
537+
for acc in accessors.into_iter() {
538+
ctx.is_chained = !result.is_empty();
539+
result.extend(ctx.translate(acc));
540+
}
541+
result
542+
}
543+
),
544+
// A subscript with a getter-only body (`subscript(i: Int) -> T { … }`).
545+
rule!(
546+
(subscriptDecl
547+
modifiers: _* @@mods
548+
subscriptKeyword: @@kw
549+
genericParameterClause: (genericParameterClause parameters: _* @@type_params)?
550+
parameterClause: (functionParameterClause parameters: _* @@params)
551+
returnClause: (returnClause type: @@ret)
552+
accessorBlock: _? @@body)
553+
=>
554+
function_declaration {
555+
let sub = SubscriptContext {
556+
keyword: kw,
557+
modifiers: mods,
558+
type_params,
559+
params,
560+
return_type: ret,
561+
};
562+
ctx.is_chained = false;
563+
subscript_method(&mut ctx, sub, SubscriptAccessor {
564+
modifiers: Vec::new(),
565+
setter: None,
566+
body,
567+
})
568+
}
569+
),
570+
// An accessor of a subscript (see above). Accessor kinds other than
571+
// `get` and `set` (such as `_modify`) are not supported.
572+
rule!(
573+
(accessorDecl
574+
modifiers: _* @acc_mods
575+
accessorSpecifier: @@spec
576+
parameters: (accessorParameters name: @@param_name)?
577+
body: _? @@body)
578+
where ctx.subscript.is_some()
579+
=>
580+
member {
581+
let sub = ctx.subscript.clone().expect("checked by guard");
582+
let spec_text = ctx.source_text(spec);
583+
if spec_text == "get" || spec_text == "set" {
584+
let setter = (spec_text == "set").then_some((param_name, spec));
585+
subscript_method(&mut ctx, sub, SubscriptAccessor {
586+
modifiers: acc_mods,
587+
setter,
588+
body,
589+
})
590+
} else {
591+
tree!((unsupported_node ""))
592+
}
593+
}
594+
),
422595
// Each `accessorDecl` becomes an `accessor_declaration`, reading the
423596
// property name/type and the modifiers from `ctx`. The
424597
// accessor kind comes straight from the specifier keyword
@@ -688,6 +861,27 @@ fn translation_rules() -> Vec<Rule<SwiftContext>> {
688861
return_type: {ret}
689862
body: (block))
690863
),
864+
// A subscript parameter with a single name has no argument label
865+
// (`subscript(i: Int)` is called as `x[0]`). It is translated in a reset
866+
// context so its type and default value are not affected.
867+
rule!(
868+
(functionParameter
869+
firstName: @@first
870+
secondName: _? @@second
871+
type: @@ty
872+
defaultValue: (initializerClause value: @@val)?)
873+
where ctx.in_subscript_parameters && second.is_none()
874+
=>
875+
parameter {
876+
ctx.reset();
877+
let ty = ctx.translate(ty).into_iter().next();
878+
let val = ctx.translate(val).into_iter().next();
879+
tree!((parameter
880+
pattern: {parameter_pattern(&mut ctx, first)}
881+
type: {ty}
882+
default: {val}))
883+
}
884+
),
691885
// A function parameter. With two names (`firstName`+`secondName`) the
692886
// first is the external argument label and the second the internal name;
693887
// with one name it is both the external and internal name.
@@ -1122,22 +1316,29 @@ fn translation_rules() -> Vec<Rule<SwiftContext>> {
11221316
=>
11231317
(key_value_pair key: {key} value: {value})
11241318
),
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.
1319+
// A subscript access (`xs[0]`) is modelled as a call to a member named
1320+
// `subscript` on the subscripted value, i.e. `xs.subscript(0)`. This
1321+
// matches the `subscript` methods emitted for `subscriptDecl`s.
11291322
rule!(
11301323
(subscriptCallExpr
11311324
calledExpression: @callee
1325+
leftSquare: @@left_square
11321326
arguments: _* @args
11331327
trailingClosure: _? @trailing
11341328
additionalTrailingClosures: _* @additional)
11351329
=>
1136-
(call_expr
1137-
callee: {callee}
1138-
argument: {args}
1139-
argument: {trailing.map(|trailing| tree!((argument value: {trailing})))}
1140-
argument: {additional})
1330+
call_expr {
1331+
let member = tree!((member_access_expr
1332+
base: {callee}
1333+
member_name_node: (identifier "subscript" location: {left_square})
1334+
location: {callee}
1335+
location: {left_square}));
1336+
tree!((call_expr
1337+
callee: {member}
1338+
argument: {args}
1339+
argument: {trailing.map(|trailing| tree!((argument value: {trailing})))}
1340+
argument: {additional}))
1341+
}
11411342
),
11421343
// ---- Optionals and errors ----
11431344
// Optional chaining — unwrap the marker
@@ -1650,7 +1851,6 @@ fn translation_rules() -> Vec<Rule<SwiftContext>> {
16501851
rule!((postfixIfConfigExpr) => (unsupported_node "")),
16511852
rule!((poundSourceLocation) => (unsupported_node "")),
16521853
rule!((precedenceGroupDecl) => (unsupported_node "")),
1653-
rule!((subscriptDecl) => (unsupported_node "")),
16541854
rule!((suppressedType) => (unsupported_node "")),
16551855
rule!((typeExpr) => (unsupported_node "")),
16561856
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)