Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nicer failures when an annotation is not resolvable #201

Merged
merged 4 commits into from
Jul 6, 2017
Merged
Show file tree
Hide file tree
Changes from 3 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
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
## 0.6.0

* **Breaking change**: `TypeChecker#annotationsOf|firstAnnotationOf` now
returns annotations that are _assignable_ to the `TypeChecker`'s type. As a
result we've added `#annotationsOfExact|firstAnnotationOfExact` which has the
old behavior for precise checks.

* `TypeChecker#annotations...`-methods now throw a `StateError` if one or more
annotations on an element are not resolvable. This is usually a sign of a
mispelling, missing import, or missing dependency.

## 0.5.10+1

* Update minimum `analyzer` package to `0.29.10`.
Expand Down
40 changes: 31 additions & 9 deletions lib/src/type_checker.dart
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ abstract class TypeChecker {
/// package like in the `dart:` SDK.
const factory TypeChecker.fromUrl(dynamic url) = _UriTypeChecker;

/// Returns the first constant annotating [element] that is this type.
/// Returns the first constant annotating [element] assignable to this type.
///
/// Otherwise returns `null`.
DartObject firstAnnotationOf(Element element) {
Expand All @@ -49,18 +49,40 @@ abstract class TypeChecker {
return results.isEmpty ? null : results.first;
}

/// Returns every constant annotating [element] that is this type.
/// Returns the first constant annotating [element] that is exactly this type.
DartObject firstAnnotationOfExact(Element element) {
if (element.metadata.isEmpty) {
return null;
}
final results = annotationsOfExact(element);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

or .single(orElse: () => null – or something like that

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be results.firstWhere((_) => true, orElse: () => null); IMO what is already in this PR is more readable.

return results.isEmpty ? null : results.first;
}

DartObject _checkedConstantValue(ElementAnnotation annotation) {
final result = annotation.computeConstantValue();
if (result == null) {
throw new StateError(
'Could not resolve $annotation. An import or dependency may be '
'missing or invalid.');
}
return result;
}

/// Returns annotating constants on [element] assignable to this type.
Iterable<DartObject> annotationsOf(Element element) => element.metadata
.map((a) => a.computeConstantValue())
.where((a) => isExactlyType(a.type));
.map(_checkedConstantValue)
.where((a) => a?.type != null && isAssignableFromType(a.type));

/// Returns annotating constants on [element] of exactly this type.
Iterable<DartObject> annotationsOfExact(Element element) => element.metadata
.map(_checkedConstantValue)
.where((a) => a?.type != null && isExactlyType(a.type));

/// Returns `true` if the type of [element] can be assigned to the type
/// represented by `this`.
/// Returns `true` if the type of [element] can be assigned to this type.
bool isAssignableFrom(Element element) =>
isExactly(element) || _getAllSupertypes(element).any(isExactlyType);

/// Returns `true` if [staticType] can be assigned to the type represented
/// by `this`.
/// Returns `true` if [staticType] can be assigned to this type.
bool isAssignableFromType(DartType staticType) =>
isAssignableFrom(staticType.element);

Expand Down Expand Up @@ -97,7 +119,7 @@ abstract class TypeChecker {
bool isSuperTypeOf(DartType staticType) => isSuperOf(staticType.element);
}

//TODO(kevmoo) Remove when bug with `ClassElement.allSupertypes` is fixed
// TODO(kevmoo) Remove when bug with `ClassElement.allSupertypes` is fixed
// https://github.com/dart-lang/sdk/issues/29767
Iterable<InterfaceType> _getAllSupertypes(Element element) sync* {
if (element is ClassElement) {
Expand Down
2 changes: 1 addition & 1 deletion pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: source_gen
version: 0.5.10+1
version: 0.6.0-dev
author: Dart Team <[email protected]>
description: Automated source code generation for Dart.
homepage: https://github.com/dart-lang/source_gen
Expand Down
17 changes: 17 additions & 0 deletions test/type_checker_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Increase timeouts on this test which resolves source code and can be slow.
@Timeout.factor(2.0)
import 'dart:collection';

import 'package:analyzer/dart/element/type.dart';
Expand Down Expand Up @@ -177,4 +179,19 @@ void main() {
checkGeneratorForAnnotation: () => const TypeChecker.fromUrl(
'package:source_gen/src/generator_for_annotation.dart#GeneratorForAnnotation'));
});

test('should gracefully when something is not resolvable', () async {
final resolver = await resolveSource(r'''
library _test;

@depracated // Intentionally mispelled.
class X {}
''');
final lib = resolver.getLibraryByName('_test');
final classX = lib.getType('X');
final $deprecated = const TypeChecker.fromRuntime(Deprecated);

expect(() => $deprecated.annotationsOf(classX), throwsStateError,
reason: 'deprecated was spelled wrong; no annotation can be resolved');
});
}