Skip to content

Commit 8a57ce8

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=' setter method. The setter clones the subscript parameters and takes the new value as an extra trailing positional parameter. Calls appearing as assignment targets, or written back after an in-place update, now invoke the corresponding 'name=' setter, generalizing the existing property setter call logic. MaD models can target setter calls by the 'name=' method name. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent 339e991 commit 8a57ce8

29 files changed

Lines changed: 1407 additions & 72 deletions

‎unified/extractor/ast_types.yml‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,14 @@ named:
338338
type: expr
339339

340340
# A top-level function declaration.
341+
#
342+
# A function whose name is an identifier followed by `=` (such as `subscript=`)
343+
# is a setter invoked via call syntax: a call to `foo` (such as Swift's
344+
# `x[i]`, a call to `x.subscript`) in an assignment target or otherwise
345+
# updated in place invokes the setter `foo=`. The setter takes the new value
346+
# as an extra trailing positional parameter. A getter/setter pair is emitted
347+
# as two adjacent declarations, the second one tagged with a
348+
# `chained_declaration` modifier.
341349
function_declaration:
342350
modifier*: modifier
343351
name_node: identifier

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

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

4968
impl SwiftContext {
@@ -146,6 +165,75 @@ fn member_chain(
146165
)
147166
}
148167

168+
/// The accessor-specific parts of a subscript getter or setter.
169+
struct SubscriptAccessor {
170+
/// Modifiers written on the accessor itself, such as `nonmutating`.
171+
modifiers: Vec<yeast::OutputId>,
172+
/// For a setter, the explicit name of its new-value parameter (`set(v)`),
173+
/// if any, and the token at which to locate an implicit `newValue`.
174+
setter: Option<(Option<yeast::Id>, yeast::Id)>,
175+
/// The raw accessor body, if any.
176+
body: Option<yeast::Id>,
177+
}
178+
179+
/// Emit a `function_declaration` for one accessor of a subscript: the getter
180+
/// is named `subscript` and the setter `subscript=`. The shared parts of the subscript (modifiers, generic and value
181+
/// parameters and the element type) are translated afresh for each accessor,
182+
/// so a getter/setter pair each get their own copy. A setter takes the new
183+
/// value as an extra trailing positional parameter and has no return type.
184+
fn subscript_method(
185+
ctx: &mut yeast::build::BuildCtx<'_, SwiftContext>,
186+
sub: SubscriptContext,
187+
accessor: SubscriptAccessor,
188+
) -> yeast::OutputId {
189+
let is_chained = ctx.is_chained;
190+
let (mods, type_params, params, element_type, body) = ctx.scoped(|ctx| {
191+
ctx.reset();
192+
let mods = ctx.translate(sub.modifiers);
193+
let type_params = ctx.translate(sub.type_params);
194+
let element_type = ctx.translate(sub.return_type).into_iter().next();
195+
let body = ctx.translate(accessor.body).into_iter().next();
196+
ctx.in_subscript_parameters = true;
197+
let params = ctx.translate(sub.params);
198+
(mods, type_params, params, element_type, body)
199+
});
200+
let body = body.unwrap_or_else(|| tree!((block)));
201+
let kw = sub.keyword;
202+
match accessor.setter {
203+
Some((param_name, spec)) => {
204+
let implicit_param_name = param_name.is_none().then_some("newValue");
205+
tree!((function_declaration
206+
modifier: {mods}
207+
modifier: {accessor.modifiers}
208+
modifier: [(modifier "chained_declaration") if { is_chained }]
209+
name_node: (identifier "subscript=" location: {kw})
210+
type_parameter: {type_params}
211+
parameter: {params}
212+
parameter: [
213+
(parameter
214+
pattern: (identifier #{param_name})
215+
type: {element_type}
216+
location: {param_name})
217+
(parameter
218+
modifier: (modifier "generated")
219+
pattern: (identifier #{implicit_param_name} location: {spec})
220+
type: {element_type}
221+
location: {spec})
222+
]
223+
body: {body}))
224+
}
225+
None => tree!((function_declaration
226+
modifier: {mods}
227+
modifier: {accessor.modifiers}
228+
modifier: [(modifier "chained_declaration") if { is_chained }]
229+
name_node: (identifier #{kw})
230+
type_parameter: {type_params}
231+
parameter: {params}
232+
return_type: {element_type}
233+
body: {body})),
234+
}
235+
}
236+
149237
#[allow(clippy::too_many_lines)]
150238
fn translation_rules() -> Vec<Rule<SwiftContext>> {
151239
yeast::rules! {
@@ -412,6 +500,88 @@ fn translation_rules() -> Vec<Rule<SwiftContext>> {
412500
result
413501
}
414502
),
503+
// ---- Subscripts ----
504+
// A subscript declaration becomes a `function_declaration` named
505+
// `subscript` for its getter and, if it has a setter, one named
506+
// `subscript=` for the setter. A subscript with an explicit accessor block publishes its shared parts
507+
// in `ctx` and lets the `accessorDecl` rule below emit one method per
508+
// accessor; each one after the first is tagged `chained_declaration`.
509+
rule!(
510+
(subscriptDecl
511+
modifiers: _* @@mods
512+
subscriptKeyword: @@kw
513+
genericParameterClause: (genericParameterClause parameters: _* @@type_params)?
514+
parameterClause: (functionParameterClause parameters: _* @@params)
515+
returnClause: (returnClause type: @@ret)
516+
accessorBlock: (accessorBlock accessors: (accessorDecl)+ @@accessors))
517+
=>
518+
member* {
519+
ctx.subscript = Some(SubscriptContext {
520+
keyword: kw,
521+
modifiers: mods,
522+
type_params,
523+
params,
524+
return_type: ret,
525+
});
526+
let mut result = Vec::new();
527+
for acc in accessors.into_iter() {
528+
ctx.is_chained = !result.is_empty();
529+
result.extend(ctx.translate(acc));
530+
}
531+
result
532+
}
533+
),
534+
// A subscript with a getter-only body (`subscript(i: Int) -> T { … }`).
535+
rule!(
536+
(subscriptDecl
537+
modifiers: _* @@mods
538+
subscriptKeyword: @@kw
539+
genericParameterClause: (genericParameterClause parameters: _* @@type_params)?
540+
parameterClause: (functionParameterClause parameters: _* @@params)
541+
returnClause: (returnClause type: @@ret)
542+
accessorBlock: _? @@body)
543+
=>
544+
function_declaration {
545+
let sub = SubscriptContext {
546+
keyword: kw,
547+
modifiers: mods,
548+
type_params,
549+
params,
550+
return_type: ret,
551+
};
552+
ctx.is_chained = false;
553+
subscript_method(&mut ctx, sub, SubscriptAccessor {
554+
modifiers: Vec::new(),
555+
setter: None,
556+
body,
557+
})
558+
}
559+
),
560+
// An accessor of a subscript (see above). Accessor kinds other than
561+
// `get` and `set` (such as `_modify`) are not supported.
562+
rule!(
563+
(accessorDecl
564+
modifiers: _* @acc_mods
565+
accessorSpecifier: @@spec
566+
parameters: (accessorParameters name: @@param_name)?
567+
body: _? @@body)
568+
where ctx.subscript.is_some()
569+
=>
570+
member {
571+
let sub = ctx.subscript.clone().expect("checked by guard");
572+
let spec_text = ctx.source_text(spec);
573+
if spec_text == "get" || spec_text == "set" {
574+
let setter = (spec_text == "set").then_some((param_name, spec));
575+
subscript_method(&mut ctx, sub, SubscriptAccessor {
576+
modifiers: acc_mods,
577+
setter,
578+
body,
579+
})
580+
} else {
581+
tree!((unsupported_node ""))
582+
}
583+
}
584+
),
415585
// Each `accessorDecl` becomes an `accessor_declaration`, reading the
416586
// property name/type and the modifiers from `ctx`. The
417587
// accessor kind comes straight from the specifier keyword
@@ -681,6 +851,27 @@ fn translation_rules() -> Vec<Rule<SwiftContext>> {
681851
return_type: {ret}
682852
body: (block))
683853
),
854+
// A subscript parameter with a single name has no argument label
855+
// (`subscript(i: Int)` is called as `x[0]`). It is translated in a reset
856+
// context so its type and default value are not affected.
857+
rule!(
858+
(functionParameter
859+
firstName: @@first
860+
secondName: _? @@second
861+
type: @@ty
862+
defaultValue: (initializerClause value: @@val)?)
863+
where ctx.in_subscript_parameters && second.is_none()
864+
=>
865+
parameter {
866+
ctx.reset();
867+
let ty = ctx.translate(ty).into_iter().next();
868+
let val = ctx.translate(val).into_iter().next();
869+
tree!((parameter
870+
pattern: {parameter_pattern(&mut ctx, first)}
871+
type: {ty}
872+
default: {val}))
873+
}
874+
),
684875
// A function parameter. With two names (`firstName`+`secondName`) the
685876
// first is the external argument label and the second the internal name;
686877
// with one name it is both the external and internal name.
@@ -1114,22 +1305,29 @@ fn translation_rules() -> Vec<Rule<SwiftContext>> {
11141305
=>
11151306
(key_value_pair key: {key} value: {value})
11161307
),
1117-
// A subscript access (`xs[0]`) is modelled as a call. swift-syntax does
1118-
// report a distinct `subscriptCallExpr`, so giving
1119-
// subscripts their own shape needs only a `subscript_expr` node in
1120-
// ast_types.yml and a remap here.
1308+
// A subscript access (`xs[0]`) is modelled as a call to a member named
1309+
// `subscript` on the subscripted value, i.e. `xs.subscript(0)`. This
1310+
// matches the `subscript` methods emitted for `subscriptDecl`s.
11211311
rule!(
11221312
(subscriptCallExpr
11231313
calledExpression: @callee
1314+
leftSquare: @@left_square
11241315
arguments: _* @args
11251316
trailingClosure: _? @trailing
11261317
additionalTrailingClosures: _* @additional)
11271318
=>
1128-
(call_expr
1129-
callee: {callee}
1130-
argument: {args}
1131-
argument: {trailing.map(|trailing| tree!((argument value: {trailing})))}
1132-
argument: {additional})
1319+
call_expr {
1320+
let member = tree!((member_access_expr
1321+
base: {callee}
1322+
member_name_node: (identifier "subscript" location: {left_square})
1323+
location: {callee}
1324+
location: {left_square}));
1325+
tree!((call_expr
1326+
callee: {member}
1327+
argument: {args}
1328+
argument: {trailing.map(|trailing| tree!((argument value: {trailing})))}
1329+
argument: {additional}))
1330+
}
11331331
),
11341332
// ---- Optionals and errors ----
11351333
// Optional chaining — unwrap the marker
@@ -1634,7 +1832,6 @@ fn translation_rules() -> Vec<Rule<SwiftContext>> {
16341832
rule!((postfixIfConfigExpr) => (unsupported_node "")),
16351833
rule!((poundSourceLocation) => (unsupported_node "")),
16361834
rule!((precedenceGroupDecl) => (unsupported_node "")),
1637-
rule!((subscriptDecl) => (unsupported_node "")),
16381835
rule!((suppressedType) => (unsupported_node "")),
16391836
rule!((typeExpr) => (unsupported_node "")),
16401837
rule!((unsafeExpr) => (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)