Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions lib/src/constants.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import 'package:analyzer/dart/constant/value.dart';
import 'package:analyzer/dart/element/element.dart';

import 'type_checker.dart';

/// Throws an exception if [root] or its super(s) does not contain [name].
void _assertHasField(ClassElement root, String name) {
var element = root;
Expand Down Expand Up @@ -95,6 +97,9 @@ abstract class ConstantReader {
/// Returns whether this constant represents `null`.
bool get isNull;

/// Returns whether this constant matches [checker].
bool instanceOf(TypeChecker checker);

/// Reads[ field] from the constant as another constant value.
ConstantReader read(String field);
}
Expand Down Expand Up @@ -140,6 +145,9 @@ class _NullConstant implements ConstantReader {
@override
bool get isString => false;

@override
bool instanceOf(TypeChecker checker) => false;

@override
ConstantReader read(_) => throw new UnsupportedError('Null');
}
Expand Down Expand Up @@ -176,17 +184,21 @@ class _Constant implements ConstantReader {
bool get isInt => _object.toIntValue() != null;

@override
bool get isList => _object?.toListValue() != null;
bool get isList => _object.toListValue() != null;

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

@override
bool get isMap => _object?.toMapValue() != null;
bool get isMap => _object.toMapValue() != null;

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

@override
bool instanceOf(TypeChecker checker) =>
checker.isAssignableFromType(_object.type);

@override
ConstantReader read(String field) {
final constant = new ConstantReader(_getFieldRecursive(_object, field));
Expand Down
7 changes: 7 additions & 0 deletions test/constants_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ void main() {
@Super() // [5]
@aList // [6]
@aMap // [7]
@deprecated // [8]
class Example {
final String aString;
final int aInt;
Expand Down Expand Up @@ -120,5 +121,11 @@ void main() {
final $super = constants[5];
expect(() => $super.read('foo'), throwsFormatException);
});

test('should compare using TypeChecker', () {
final $deprecated = constants[8];
final check = new TypeChecker.fromRuntime(Deprecated);
expect($deprecated.instanceOf(check), isTrue, reason: '$deprecated');
});
});
}