Skip to content

Commit cf9bd92

Browse files
authored
Added instanceOf to ConstantReader. (#181)
1 parent 60a4b38 commit cf9bd92

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

lib/src/constants.dart

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
import 'package:analyzer/dart/constant/value.dart';
66
import 'package:analyzer/dart/element/element.dart';
77

8+
import 'type_checker.dart';
9+
810
/// Throws an exception if [root] or its super(s) does not contain [name].
911
void _assertHasField(ClassElement root, String name) {
1012
var element = root;
@@ -95,6 +97,9 @@ abstract class ConstantReader {
9597
/// Returns whether this constant represents `null`.
9698
bool get isNull;
9799

100+
/// Returns whether this constant matches [checker].
101+
bool instanceOf(TypeChecker checker);
102+
98103
/// Reads[ field] from the constant as another constant value.
99104
ConstantReader read(String field);
100105
}
@@ -140,6 +145,9 @@ class _NullConstant implements ConstantReader {
140145
@override
141146
bool get isString => false;
142147

148+
@override
149+
bool instanceOf(TypeChecker checker) => false;
150+
143151
@override
144152
ConstantReader read(_) => throw new UnsupportedError('Null');
145153
}
@@ -176,17 +184,21 @@ class _Constant implements ConstantReader {
176184
bool get isInt => _object.toIntValue() != null;
177185

178186
@override
179-
bool get isList => _object?.toListValue() != null;
187+
bool get isList => _object.toListValue() != null;
180188

181189
@override
182190
bool get isNull => _isNull(_object);
183191

184192
@override
185-
bool get isMap => _object?.toMapValue() != null;
193+
bool get isMap => _object.toMapValue() != null;
186194

187195
@override
188196
bool get isString => _object.toStringValue() != null;
189197

198+
@override
199+
bool instanceOf(TypeChecker checker) =>
200+
checker.isAssignableFromType(_object.type);
201+
190202
@override
191203
ConstantReader read(String field) {
192204
final constant = new ConstantReader(_getFieldRecursive(_object, field));

test/constants_test.dart

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ void main() {
3737
@Super() // [5]
3838
@aList // [6]
3939
@aMap // [7]
40+
@deprecated // [8]
4041
class Example {
4142
final String aString;
4243
final int aInt;
@@ -120,5 +121,11 @@ void main() {
120121
final $super = constants[5];
121122
expect(() => $super.read('foo'), throwsFormatException);
122123
});
124+
125+
test('should compare using TypeChecker', () {
126+
final $deprecated = constants[8];
127+
final check = new TypeChecker.fromRuntime(Deprecated);
128+
expect($deprecated.instanceOf(check), isTrue, reason: '$deprecated');
129+
});
123130
});
124131
}

0 commit comments

Comments
 (0)