Skip to content

Commit e17db6c

Browse files
committed
Infer type of extract index expressions.
R=paulberry@google.com BUG= Review URL: https://codereview.chromium.org/1878223002 .
1 parent a0375e5 commit e17db6c

File tree

2 files changed

+42
-3
lines changed

2 files changed

+42
-3
lines changed

pkg/analyzer/lib/src/summary/link.dart

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1791,9 +1791,7 @@ class ExprTypeComputer {
17911791
_doAssignToIndex();
17921792
break;
17931793
case UnlinkedConstOperation.extractIndex:
1794-
stack.length -= 2;
1795-
// TODO(paulberry): implement.
1796-
stack.add(DynamicTypeImpl.instance);
1794+
_doExtractIndex();
17971795
break;
17981796
case UnlinkedConstOperation.invokeMethodRef:
17991797
_doInvokeMethodRef();
@@ -1924,6 +1922,20 @@ class ExprTypeComputer {
19241922
stack.add(type);
19251923
}
19261924

1925+
void _doExtractIndex() {
1926+
stack.removeLast(); // index
1927+
DartType target = stack.removeLast();
1928+
stack.add(() {
1929+
if (target is InterfaceType) {
1930+
MethodElement method = target.lookUpMethod('[]', library);
1931+
if (method != null) {
1932+
return method.returnType;
1933+
}
1934+
}
1935+
return DynamicTypeImpl.instance;
1936+
}());
1937+
}
1938+
19271939
void _doExtractProperty() {
19281940
DartType target = stack.removeLast();
19291941
String propertyName = _getNextString();

pkg/analyzer/test/src/summary/resynthesize_ast_test.dart

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,33 @@ class AstInferredTypeTest extends AbstractResynthesizeTest
209209
super.test_genericMethods_inferJSBuiltin();
210210
}
211211

212+
void test_infer_extractIndex_custom() {
213+
var unit = checkFile('''
214+
class A {
215+
String operator [](_) => null;
216+
}
217+
var a = new A();
218+
var b = a[0];
219+
''');
220+
expect(unit.topLevelVariables[1].type.toString(), 'String');
221+
}
222+
223+
void test_infer_extractIndex_fromList() {
224+
var unit = checkFile('''
225+
var a = <int>[1, 2, 3];
226+
var b = a[0];
227+
''');
228+
expect(unit.topLevelVariables[1].type.toString(), 'int');
229+
}
230+
231+
void test_infer_extractIndex_fromMap() {
232+
var unit = checkFile('''
233+
var a = <int, double>{};
234+
var b = a[0];
235+
''');
236+
expect(unit.topLevelVariables[1].type.toString(), 'double');
237+
}
238+
212239
void test_infer_extractProperty_getter() {
213240
checkFile(r'''
214241
var a = 1.isEven;

0 commit comments

Comments
 (0)