how to access the source code of built in methods of Dart? - dart

I would like to understand how built in methods work in Dart, therefore i would like to access the source code, any idea how to access a source code of built in methods? below is an example of one method map()
enter image description here

Well, it can be a little complicated to find the concrete implementation of all methods. There are several reasons for that:
Some implementations are different for Dart running as JavaScript and Dart running on the Dart VM.
Some methods are heavily dependent on C++ code for the Dart VM implementation.
Lots of classes in Dart are just interfaces like the Iterable which means the Iterable.map method can have different implementations for e.g. lists and maps.
However, all of the source code can be found in the GitHub repository if you browse through the code. But it takes some experience to know where to look for things:
https://github.com/dart-lang/sdk/tree/stable
So if we e.g. want to look for the default map method in Iterable we need to see if there are a default implementation. We can find the class here in the repo.:
https://github.com/dart-lang/sdk/blob/9a618e5661665b8d687a28e6b1ec25e9177ec2d7/sdk/lib/core/iterable.dart#L197
Iterable<T> map<T>(T f(E e)) => MappedIterable<E, T>(this, f);
By searching for class MappedIterable we can see this class is implemented in:
https://github.com/dart-lang/sdk/blob/stable/sdk/lib/internal/iterable.dart#L354
class MappedIterable<S, T> extends Iterable<T> {
final Iterable<S> _iterable;
final _Transformation<S, T> _f;
factory MappedIterable(Iterable<S> iterable, T function(S value)) {
if (iterable is EfficientLengthIterable) {
return new EfficientLengthMappedIterable<S, T>(iterable, function);
}
return new MappedIterable<S, T>._(iterable, function);
}
MappedIterable._(this._iterable, this._f);
Iterator<T> get iterator => new MappedIterator<S, T>(_iterable.iterator, _f);
// Length related functions are independent of the mapping.
int get length => _iterable.length;
bool get isEmpty => _iterable.isEmpty;
// Index based lookup can be done before transforming.
T get first => _f(_iterable.first);
T get last => _f(_iterable.last);
T get single => _f(_iterable.single);
T elementAt(int index) => _f(_iterable.elementAt(index));
}
One details you will see is that a lot of the SDK are duplicated right now in a sdk and sdk_nnbd version. This is temporarily while the Dart team are implementing the non-nullable by default feature and is not used unless you are running with this feature turned on.

Related

In Dart's Strong-Mode, can I leave off types from function definitions?

For example, I'd like to just be able to write:
class Dog {
final String name;
Dog(this.name);
bark() => 'Woof woof said $name';
}
But have #Dog.bark's type definition be () => String.
This previously wasn't possible in Dart 1.x, but I'm hoping type inference can save the day and avoid having to type trivial functions where the return type is inferable (the same as it does for closures today?)
The language team doesn't currently have any plans to do inference on member return types based on their bodies. There are definitely cases like this where it would be nice, but there are other cases (like recursive methods) where it doesn't work.
With inference, we have to balance a few opposing forces:
Having smart inference that handles lots of different cases to alleviate as much typing pain as we can.
Having some explicit type annotations so that things like API boundaries are well-defined. If you change a method body and that changes the inferred return type, now you've made a potentially breaking change to your API.
Having a simple boundary between code that is inferred and code that is not so that users can easily reason about which parts of their code are type safe and which need more attention.
The case you bring up is right at the intersection of those. Personally, I lean towards not inferring. I like my class APIs to be pretty explicitly typed anyway, since I find it makes them easier to read and maintain.
Keep in mind that there are similar cases where inference does come into play:
Dart will infer the return type of an anonymous function based on its body. That makes things like lambdas passed to map() do what you want.
It will infer the return type of a method override from the method it is overriding. You don't need to annotate the return type in Beagle.bark() here:
class Dog {
String bark() => "Bark!";
}
class Beagle extends Dog {
final String name;
Dog(this.name);
bark() => 'Woof woof said $name';
}

dart: wrap all function calls

I am attempting to write two versions of the same program:
a performant version; and
a slower version that lets the user know what's happening.
I imagine it's not entirely disimilar to how an IDE might implement a normal/debug mode.
My requirements, in decreasing order of importance, are as follows:
the slow version should produce the same results as the performant version;
the slow version should wrap a subset of public function calls made by the performant version;
the requirement for the slower version should not adversely effect the performance of the performant version;
preferably no code reproduction, but automated reproduction where necessary;
minimal increase in code-base size; and
ideally the slow version should be able to be packaged separately (presumably with a one-way dependence on the performant version)
I understand requirement 6 may be impossible, since requirement 2 requires access to a classes implementation details (for cases where a public function calls another public function).
For the sake of discussion, consider the following performant version of a program to tell a simple story.
class StoryTeller{
void tellBeginning() => print('This story involves many characters.');
void tellMiddle() => print('After a while, the plot thickens.');
void tellEnd() => print('The characters resolve their issues.');
void tellStory(){
tellBeginning();
tellMiddle();
tellEnd();
}
}
A naive implementation with mirrors such as the following:
class Wrapper{
_wrap(Function f, Symbol s){
var name = MirrorSystem.getName(s);
print('Entering $name');
var result = f();
print('Leaving $name');
return result;
}
}
#proxy
class StoryTellerProxy extends Wrapper implements StoryTeller{
final InstanceMirror mirror;
StoryTellerProxy(StoryTeller storyTeller): mirror = reflect(storyTeller);
#override
noSuchMethod(Invocation invocation) =>
_wrap(() => mirror.delegate(invocation), invocation.memberName);
}
I love the elegance of this solution, since I can change the interface of the performant version and this just works. Unfortunately, it fails to satisfy requirement 2, since the inner calls of tellStory() are not wrapped.
A simple though more verbose solution exists:
class StoryTellerVerbose extends StoryTeller with Wrapper{
void tellBeginning() => _wrap(() => super.tellBeginning(), #tellBeginning);
void tellMiddle() => _wrap(() => super.tellMiddle(), #tellMiddle);
void tellEnd() => _wrap(() => super.tellEnd(), #tellEnd);
void tellStory() => _wrap(() => super.tellStory(), #tellStory);
}
This code can easily be auto-generated using mirrors, but it can result in a large increase in the code-base size, particularly if the performant version has an extensive class hierarchy and I want to have a const analogue to const variables of a class deep in the class tree.
Also, if any class doesn't have a public constructor, this approach prevents the separation of the packages (I think).
I've also considered wrapping all methods of the base class with a wrap method, with the performant version having a trivial wrap function. However, I'm worried this will adversely effect the performant version's performance, particularly if the wrap method was to require, say, an invocation as an input. I also dislike the fact that this intrinsicly links my performant version to the slow version. In my head, I'm thinking there must be a way to make the slower version an extension of the performant version, rather than both versions being an extension of some more general super-version.
Am I missing something really obvious? Is there an in-built 'anySuchMethod' or some such? I'm hoping to combine the elegance of the proxy solution with the completeness of the verbose solution.
You could try to put the additional debugging code inside asserts(...). This gets automatically removed when not run in checked mode. See also
Is there a compiler preprocessor in Dart?
How to exclude debug code
How to achieve precompiler directive like functionality
Otherwise just make a global constant (const bool isSlow = true/false;) Use interfaces everywhere and factory constructors which return the slow or the fast implementation of an interface depending on the isSlow value.
The slow version can just extend the fast version to reuse its functionality and extend it by overriding its methods.
This way you don't have to use mirrors which causes code bloat, at least for client side code.
When you build all unnecessary code is removed by tree-shaking, depending on the setting of isSlow.
Using dependency injection helps simplify this way of developing different implementations.

Notify Observable-Watchers programmatically in Dart

Once again, a Dart/Polymer related question.
I wanted to use the Parse.com JavaScript library, but since it's not available in Dart I've written Wrapper classes which store a JsObject and delegate all calls from Dart to the corresponding JavaScript object. Basically it's like a proxy.
Guess what, it works pretty great.
However, my observables don't. To understand this, you have to take a look at the following structure of one of my "proxy"-classes.
class ParseObject extends Observable {
JsObject _jsDelegate = new JsObject(context['Parse']['ParseObject']);
void set(String key, dynamic value) {
_jsDelegate.callMethod('set', [key, jsify(value)];
}
dynamic get(String key) {
return dartify(_jsDelegate.callMethod('get', [key]));
}
}
The HTML code of my Polymer Element looks like this:
<div>Name: {{project.get('name')}}</div>
Since the data binding is only evaluate in case the parameter of the method changed, it will never be updated and thus even though the name is changed, the old one will stay in place.
The solution I came up with is to store all the values the user is setting in the ParseObject#set(String, dynamic) method into a Map which is observable. This works but I think it's quiete dirty since I have to make sure that both Maps, the one in Dart and the one in the ParseObject's JavaScript representation equal.
Thus I am looking for a better solution and I think of some kind of method to tell Polymer to reevaluate it's data bindings.
Does such a method exist or are there any other possibilities to address this problem?
Extending observable by itself does nothing yet.
You need to annotate the getters with #observable (and if you are not using Polymer, you also need to add the observable transformer to pubspec.yaml). You can't make functions observable (this works in Polymer elements but not in Observable model classes. For more details about observable see for example Implement an Observer pattern in Dart or Dart: #observable of getters

Attributes in Dart

Are there any plans to introduce attributes
for classes, methods, parameters of methods,
something like C# or Java attributes ?
[Test]
class SomeClass
{
[Test]
someMethod()
}
or
#Test
class SomeClass
{
#Test
someMethod(#Test int param)
}
For many frameworks it would be very useful
In dart, they are called metadata / annotation. The syntax is quite close to java. Here's a example :
#Test testMethod() {}
In Dart Specification you can read :
Metadata consists of a series of annotations, each of which begin with the character #, followed a constant expression that starts with an identifier. It is a compile time error if the expression is not one of the following:
A reference to a compile-time constant variable.
A call to a constant constructor.
[....]
Metadata can appear before a library, class, typedef, type parameter, constructor, factory, function, field, parameter, or variable declaration and before an import or export directive.
There're already some annotations predifined in dart:core. Particulary #override, #deprecated and #proxy.
Dart already has annotations, similar to Java in some ways, they're just not used in very many places yet, and they're not accessible from reflection yet either.
See this article: http://news.dartlang.org/2012/06/proposal-to-add-metadata-to-dart.html
Here's a brief introduction to the two metadata annotations currently available in the Dart meta library:
Dart Metadata is your friend.
This doesn't preclude you from using your own, but these are the two that have tooling integration with the Dart Editor.

How to get concrete object of a static method via mirror API?

I have something like this:
class MyClass
{
static void DoSomething(arg1, arg2){...}
}
Via reflection, I am able to get the ClassMirror of this class. From this point, how would I get to the concrete static function so I can call it.
Note that I tried to use:
ObjectMirror.invoke('DoSomething', [arg1, arg2]);
which would initially appear to work, but it doesn't support passing of complex types as arguments, This static function requires a complex type as one of it's arguments.
Ideally, I'd like to get the 'Function' object that represents the static method so I can invoke it directly.
a. The current state of affairs is temporary. The plan is that the mirror API will wrap the arguments with mirrors for you.
b. The API may eventually support a getProperty method that will give you a Future on the function object. However, you will not get a Function object directly, so this won't really make any difference in this case.
c. The core idea is that the API fundamentally works on mirrors. To make it more usable, it should accept non-mirrors as input and wrap them in mirrors for you. It will always return mirrors, and in some cases return futures on these. This is so the API works the same for remote and local cases.
d. Resources for understanding mirrors:
http://www.bracha.org/mirrors.pdf (academic paper, tough going)
http://www.hpi.uni-potsdam.de/hirschfeld/events/past/media/100105_Bracha_2010_LinguisticReflectionViaMirrors_HPI.mp4 (a video, pre-Dart, discusses earlier Mirror systems)
http://gbracha.blogspot.com/2010/03/through-looking-glass-darkly.html (an old, pre-dart, blog post of mine on mirrors)
http://www.wirfs-brock.com/allen/posts/228 (Allen Wirfs-Brock's blog. Allen was a mirror pioneer back in Smalltalk in the 90s)
http://www.wirfs-brock.com/allen/posts/245
You can also search my blog, or Allen Wirf-Brock's for posts on the topic.

Resources