From d9baed09d7f9d08209465fa9ba2975258357b706 Mon Sep 17 00:00:00 2001 From: Matan Lurey Date: Thu, 22 Jun 2017 09:09:13 -0700 Subject: [PATCH] Added instanceOf to ConstantReader. --- lib/src/constants.dart | 16 ++++++++++++++-- test/constants_test.dart | 7 +++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/lib/src/constants.dart b/lib/src/constants.dart index b4a9ee28..9cad6f20 100644 --- a/lib/src/constants.dart +++ b/lib/src/constants.dart @@ -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; @@ -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); } @@ -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'); } @@ -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)); diff --git a/test/constants_test.dart b/test/constants_test.dart index 531d66e1..5d75e44a 100644 --- a/test/constants_test.dart +++ b/test/constants_test.dart @@ -37,6 +37,7 @@ void main() { @Super() // [5] @aList // [6] @aMap // [7] + @deprecated // [8] class Example { final String aString; final int aInt; @@ -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'); + }); }); }