Comments (11)
Summary: The user requests a method to determine if a Dart type is a built-in type, like int
, String
, or double
. They also want this functionality added to the FieldDeclaration
class in the analyzer package for code generation purposes.
from sdk.
Why?
Dart doesn't have primitive types like Java or JavaScript, built-in types are just classes that happen to be in the platform libraries.
Some of them are final
or sealed
and cannot be implemented. User defined types can be final
or sealed
too, so that's not special either.
Other platform library defined types can be subtyped, so telling you whether a type is a built-in type doesn't tell you anything about the type of an actual value of that type.
If it's for fromJson
, knowing that the type is declared in the platform libraries won't help you, you still need to know how to handle it, which means you should recognize the types you support individually, no matter where they come from.
from sdk.
As of why, so many times i needed that feature, i guess the intention of dart is to facilitate things for developers .
A simple bool isBuiltIn() function would be a life saving. So that when i am analyzing the fields of a class i can differentiate what is built from a class created by me or other packages.
If its on a normal dart project (not the generator), i can do this manually
bool isBuiltIn(type){
if(type is String){
}
if(type is int){
}
//etc...
}
but i feel like that should already be a part of dart
The bigger problem for me is on the generator project
When i get to analyze the Fields of a class, i get a list of FieldDeclaration
on a class like this
class Foo{
String desc = "";
User user = User();
SomeEnum thing = SomeEnum.thing;
}
i can extract the whole line of a field like this String desc = "" or User user = User()
But it only gives me the text not the actual type of the Field.
I need a way to get the type from FieldDeclaration so i can analyze it.
from sdk.
As for the analyzer side of the question, given a resolved instance of FieldDeclaration
named declaration
, you ought to be able to access the type of the i
th field by using declaration.fields[i].type.type
. You can then use getters like isDartCoreBool
to determine whether the type is one of the types you're interested in.
So that when i am analyzing the fields of a class i can differentiate what is built from a class created by me or other packages.
Knowing whether the type is from an SDK library doesn't really answer the question of whether the type is defined in the package being analyzed (unless you can assume that the package being analyzed does not depend on any other packages). For that you really need to ask the type for its element.source.uri
, then check to see whether that's a package:
uri for the package being analyzed.
from sdk.
@bwilkerson
Weird, declaration.fields.type?.type always returns null for me.
Does it have something to do with the way i get the fields?
class MyCustomGenerator extends GeneratorForAnnotation<SerialAnnotation> {
@override
generateForAnnotatedElement( Element element, ConstantReader annotation, BuildStep buildStep) async {
var list = fields(element);
//...
}
}
List<FieldDeclaration> fields(Element element) {
AnalysisSession? session = element.session;
var library = element.library;
if (library != null) {
var parsedLibraryByElement = session?.getParsedLibraryByElement(library);
if (parsedLibraryByElement != null) {
parsedLibraryByElement as ParsedLibraryResult;
var elementDeclaration = parsedLibraryByElement.getElementDeclaration(
element);
if (elementDeclaration != null) {
var node = elementDeclaration.node;
var childEntities = node.childEntities;
List<FieldDeclaration> fields = [];
for (var obj in childEntities) {
if (obj is FieldDeclaration) {
fields.add(obj);
}
}
return fields;
}
}
}
final libraryCompilationUnit = (element.library!.session
.getParsedLibraryByElement(element.library!) as ParsedLibraryResult)
.units[0]
.unit;
Iterable<SyntacticEntity> childEntities =
libraryCompilationUnit.declarations.first.childEntities;
List<FieldDeclaration> fields = [];
for (var obj in childEntities) {
if (obj is FieldDeclaration) {
fields.add(obj);
}
}
return fields;
}
i got this method from https://stackoverflow.com/questions/57030992/how-do-i-get-the-astnode-from-some-element-in-dart-analyzer-source-gen
from sdk.
Yes. You need to use AnalysisSession.getResolvedLibraryByElement
rather than AnalysisSession.getParsedLibraryByElement
.
See https://github.com/dart-lang/sdk/blob/main/pkg/analyzer/doc/tutorial/ast.md#the-states-of-an-ast for a description of the difference between a parsed and a resolved AST.
from sdk.
Thanks! its working now with the getResolvedLibraryByElement.
Now regarding the first part o the issue, i still feel like there should be a isBuiltin method or a isDartCore method.
Whatever you guys think its best : isBuiltin(Type) or type.isBuiltin.
from sdk.
You could (perhaps, if I understood the explanation) do type.element.library?.isInSdk ?? false
.
It's a little longer, but something you could easily make your own extension getter for:
extension on DartType {
bool isPlatformType => this.element.library?.isInSdk ?? false;
}
(Completely untested.)
from sdk.
i tried the type.element.library?.isInSdk, but for enums i created it returns false,. Also i guess it should have a way on a normal project too.where i could get a object.runtimeType and maybe have isInSdk or isDartCore.
...maybe i am just beeing lazy as it can be done manually
from sdk.
i could get a object.runtimeType and maybe have isInSdk or isDartCore.
Absolutely won't happen, you'll have to use dart:mirrors
to get information out of a Type
object.
Dart Type
objects don't know anything other than whether they're ==
to another Type
object, and being able to do more than that requires retaining more information in the program than necessary.
Generally that kind of runtime reflection of source properties interact very badly with AoT compilation and tree shaking, and it's something the language actively tries to avoid.
from sdk.
Given that the analyzer is able to answer the question, and that the sdk libraries won't be enhanced, I think we can close this issue.
from sdk.
Related Issues (20)
- Consider dropping instructions after return, throw, unreachable, br in wasm_builder
- Consider optimizing `x < 0 || x > positiveInt` to single unsigned comparison
- Analyzer Feedback from IntelliJ HOT 4
- Failures on [dart2wasm] Use unsafeCast in a few places...Reland "[vm] Move `ResolveUri` to bin" HOT 1
- Analyzer data-based fix request HOT 2
- `dart compile js` fails with the newest SDK HOT 17
- Cannot resolve top-level methods with docimports HOT 3
- [Wildcard Variables] Update `DUPLICATE_DEFINTION` reporting
- CFE fails to report error when `super` is used in a redirecting constructor. HOT 1
- DevTools not serving properly on app refresh HOT 1
- [Wildcard Variables] Update `DUPLICATE_FIELD_FORMAL_PARAMETER` reporting
- `@internal` annotation does not supress `public_member_api_docs` lint on functions HOT 1
- Dart analyzer does not infer the correct type for generic record HOT 2
- Having true cancelable future HOT 2
- Simplify branch conditions based on ranges & simplify control flow afterwards if condition turns out to be constant
- Issue in number multiplication with 10, 20, etc HOT 2
- Feature Request: Add `--insert-ignore-comments` flag to `dart fix` command for existing code HOT 1
- [vm/core] `_GrowableList.add` has unnecessary bounds check
- docImports failing to allow for resolution in some flutter animation library code HOT 1
- Implement augmentations HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from sdk.