Coder Social home page Coder Social logo

Comments (11)

dart-github-bot avatar dart-github-bot commented on June 28, 2024

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.

lrhn avatar lrhn commented on June 28, 2024

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.

danteCarvalho avatar danteCarvalho commented on June 28, 2024

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.

bwilkerson avatar bwilkerson commented on June 28, 2024

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 ith 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.

danteCarvalho avatar danteCarvalho commented on June 28, 2024

@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.

bwilkerson avatar bwilkerson commented on June 28, 2024

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.

danteCarvalho avatar danteCarvalho commented on June 28, 2024

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.

lrhn avatar lrhn commented on June 28, 2024

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.

danteCarvalho avatar danteCarvalho commented on June 28, 2024

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.

lrhn avatar lrhn commented on June 28, 2024

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.

bwilkerson avatar bwilkerson commented on June 28, 2024

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.