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)
- [CP] [ CLI ] Fix issue where 'dart build' would fail to find the 'dart' when run from PATH HOT 7
- `String.fromCharCode[s]` should be deprecated and renamed to `String.fromRune[s]` HOT 4
- "Error: The macro can only be applied to enums or enum values." - What interface to use instead? HOT 1
- Failures on [ CLI ] Fix issue where 'dart build' would fail to find the 'dart' when run from PATH
- Analyzer response to LSP requests extremely slow w/ high latency reported HOT 19
- [breaking change] On Windows refer to special `null` file as '\\?\nul' rather than 'nul'. HOT 16
- LSP Server fails to initialize if an inlayHints request is sent before the client responds to workspace/configuration HOT 24
- DateTime implementation on linux, dates before year 2020 return incorrect timezone HOT 8
- Inconsistent behavior of beginToken for some analyzer AST nodes with doc comments HOT 1
- [dart2js] Incorrect inference for override with default of widened type
- [ddc] Incorrect defaulting of named arguments with certain names
- DDC async function stepping improvements HOT 1
- When performing floating-point calculations, precision may be lost在进行浮点数计算时精度会丢失 HOT 7
- [typed_data] Add `Float16List` + [vm/ffi] Add `Float16` HOT 15
- Code completion contains many duplicated items for extensions HOT 5
- dart2wasm miscompilation around dynamic switch targets HOT 2
- Unexpected TypeError from js_interop only in DDC HOT 1
- Maybe ZoneSpecification's fork behavior is broken? HOT 3
- Attempt to start the daemon using the IPv6 loopback if the machine does not have 127.0.0.1 loopback IP address
- [ddc] Can we migrate all calls of `getReifiedType()` to a member of the dart:rti library?
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.