Just out of interest I recently tried to take a look at the source code of some basic mathematical functions in the dart programming language (more specifically, in the dart:math package).
Take e.g. the cosine function. It was easy enough to find its documentation
and click on the 'View source code' button in the top right corner. However, here the problems begin. In the respective file, the only related line of code is
/// Converts [radians] to a [double] and returns the cosine of the value.
///
/// If [radians] is not a finite number, the result is NaN.
external double cos(num radians);
with no hint whatsoever where to find the actual implementation. In fact, it seems that it is not at all contained in the sdk/lib/math directory as one might expect.
Has anyone an idea where to find it? Thank you in advance!
I am not a developer on the Dart project so I might get all of this wrong. So see my answer here as my best guess into what is going on. :)
When running native, Dart uses the libc version of
cos. The implementation are a bit tricky to find but let's try do an attempt. The definition you have found are defined asexternalwhich means the actual implementation are getting patched in depending on the running platform.So for native, we need to look at:
https://github.com/dart-lang/sdk/blob/3b128c5454834a1aaef37d9bb12595e7c217ab61/sdk/lib/_internal/vm/lib/math_patch.dart#L133-L135
The hint here is
vm:recognizedwhich tells the Dart compiler that it should handle this method call special. We can in the SDK find a list of methods it should recognize for special handling. And here we find:We can then later find trace of
MathCosinil.cc:https://github.com/dart-lang/sdk/blob/3b128c5454834a1aaef37d9bb12595e7c217ab61/runtime/vm/compiler/backend/il.cc#L6991-L7027
The name of this constant kinda gives away that we are using libc. But finding the definition of
kLibcCosRuntimeEntryis not obvious since this constant are getting generated using the following macro:https://github.com/dart-lang/sdk/blob/3b128c5454834a1aaef37d9bb12595e7c217ab61/runtime/vm/runtime_entry.h#L147-L150
And is then used here:
https://github.com/dart-lang/sdk/blob/3b128c5454834a1aaef37d9bb12595e7c217ab61/runtime/vm/runtime_entry.cc#L3894-L3898
Where
&cosrefer to thecosmethod that have been globally imported frommath.hhere:https://github.com/dart-lang/sdk/blob/3b128c5454834a1aaef37d9bb12595e7c217ab61/runtime/platform/globals.h#L83