Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add package:record_use #1

Closed
wants to merge 23 commits into from
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Add package:record_use
mosuem committed Jun 11, 2024
commit 28256b5529f5233a159e30da9c35835e7ef60685
Empty file removed pkgs/placeholder
Empty file.
34 changes: 34 additions & 0 deletions pkgs/record_use/.github/workflows/test.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
name: test
permissions: read-all

on:
pull_request:
branches: [ main ]
push:
branches: [ main ]
schedule:
- cron: '0 0 * * 0' # weekly

jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
sdk: [stable, dev]
steps:
- uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9
- uses: dart-lang/setup-dart@fedb1266e91cf51be2fdb382869461a434b920a3
with:
sdk: ${{matrix.sdk}}

- run: dart pub get

- run: dart analyze --fatal-infos

- run: dart format --output=none --set-exit-if-changed .

- run: dart test

- name: Run Chrome tests - wasm
run: dart test --platform chrome --compiler dart2wasm
if: always() && matrix.sdk == 'dev'
7 changes: 7 additions & 0 deletions pkgs/record_use/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# https://dart.dev/guides/libraries/private-files
# Created by `dart pub`
.dart_tool/

# Avoid committing pubspec.lock for library packages; see
# https://dart.dev/guides/libraries/private-files#pubspeclock.
pubspec.lock
3 changes: 3 additions & 0 deletions pkgs/record_use/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## 0.1.0

- Initial version.
27 changes: 27 additions & 0 deletions pkgs/record_use/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
Copyright 2024, the Dart project authors.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Google LLC nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
102 changes: 102 additions & 0 deletions pkgs/record_use/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
# `package:record_use`


> [!CAUTION]
> This is an experimental package, and it's API can break at any time. Use at
> your own discretion.

This package provides the data classes for the usage recording feature in the
Dart SDK.

Dart objects with the `@RecordUse` annotation are being recorded at compile
time, providing the user with information. The information depends on the object
being recorded.

- If placed on a static method, the annotation means that calls to the method
are being recorded. If the `arguments` parameter is set to `true`, then
arguments will also be recorded, as far as they can be inferred at compile time.
- If placed on a class with a constant constructor, the annotation means that
any constant instance of the class will be recorded. This is particularly useful
when placing

## Example
```dart
import 'package:meta/meta.dart' show RecordUse;

void main() {
print(SomeClass.stringMetadata(42));
print(SomeClass.doubleMetadata(42));
print(SomeClass.intMetadata(42));
print(SomeClass.boolMetadata(42));
}

class SomeClass {
@RecordMetadata('leroyjenkins')
@RecordUse()
static stringMetadata(int i) {
return i + 1;
}

@RecordMetadata(3.14)
@RecordUse()
static doubleMetadata(int i) {
return i + 1;
}

@RecordMetadata(42)
@RecordUse()
static intMetadata(int i) {
return i + 1;
}

@RecordMetadata(true)
@RecordUse()
static boolMetadata(int i) {
return i + 1;
}
}

@RecordUse()
class RecordMetadata {
final Object metadata;

const RecordMetadata(this.metadata);
}

```
This code will generate a JSON file that contains both the `metadata` values of
the `RecordMetadata` instances, as well as the arguments for the different
methods annotated with `@RecordUse()`.

This information can then be accessed in a link hook as follows:
```dart
import 'package:native_assets_cli/native_assets_cli.dart';

void main(List<String> arguments){
link(arguments, (config, output) async {
final uses = config.recordedUses;

final args = uses.callReferencesTo(boolMetadataId));
//[args] is an iterable of [Argument] classes, in this case containing "42"

final fields = uses.instanceReferencesTo(recordMetadataId);
//[fields] is an iterable of [Field] classes, in this case containing
// {"arguments": "leroyjenkins"}
// {"arguments": 3.14}
// {"arguments": 42}
// {"arguments": true}

... // Do something with the information, such as tree-shaking native assets
});
}
```

## Installation
To install the record_use package, run the following command:

```bash
dart pub add record_use
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typically (always?) this package will be added as a regular dependency?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was copied from a generic package readme - I think the only package using this will be native_assets_cli...

```

## Contributing
Contributions are welcome! Please open an issue or submit a pull request.
9 changes: 9 additions & 0 deletions pkgs/record_use/analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
include: package:dart_flutter_team_lints/analysis_options.yaml

linter:
rules:
- conditional_uri_does_not_exist
- prefer_const_constructors
- prefer_final_locals
- prefer_relative_imports
- unnecessary_parenthesis
12 changes: 12 additions & 0 deletions pkgs/record_use/example/record_use_example.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Copyright (c) 2024, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:record_use/record_use.dart';

void doStuff(RecordUse usage, Identifier callId, Identifier referenceId) {
print(usage.metadata);
print(usage.callReferencesTo(callId));
print(usage.instanceReferencesTo(referenceId));
print(usage.hasNonConstArguments(callId));
}
12 changes: 12 additions & 0 deletions pkgs/record_use/lib/record_use.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Copyright (c) 2024, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

export 'src/data_classes/arguments.dart'
show Arguments, ConstArguments, NonConstArguments;
export 'src/data_classes/field.dart' show Field;
export 'src/data_classes/identifier.dart' show Identifier;
export 'src/data_classes/location.dart' show Location;
export 'src/data_classes/metadata.dart' show Metadata;
export 'src/data_classes/reference.dart' show CallReference, InstanceReference;
export 'src/record_use.dart' show RecordUse;
14 changes: 14 additions & 0 deletions pkgs/record_use/lib/record_use_internal.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Copyright (c) 2024, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

export 'src/data_classes/annotation.dart';
export 'src/data_classes/arguments.dart';
export 'src/data_classes/definition.dart';
export 'src/data_classes/field.dart';
export 'src/data_classes/identifier.dart';
export 'src/data_classes/location.dart';
export 'src/data_classes/metadata.dart';
export 'src/data_classes/reference.dart';
export 'src/data_classes/usage.dart';
export 'src/data_classes/usage_record.dart';
44 changes: 44 additions & 0 deletions pkgs/record_use/lib/src/data_classes/annotation.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Copyright (c) 2024, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:collection/collection.dart';

import 'identifier.dart';

class Annotation {
final Identifier identifier;
final Map<String, dynamic> fields;

Annotation({
required this.identifier,
required this.fields,
});

factory Annotation.fromJson(
Map<String, dynamic> json,
List<Identifier> identifiers,
) =>
Annotation(
identifier: identifiers[json['id'] as int],
fields: json['fields'] as Map<String, dynamic>,
);

Map<String, dynamic> toJson(List<Identifier> identifiers) => {
'id': identifiers.indexOf(identifier),
'fields': fields,
};

@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
final mapEquals = const DeepCollectionEquality().equals;

return other is Annotation &&
other.identifier == identifier &&
mapEquals(other.fields, fields);
}

@override
int get hashCode => identifier.hashCode ^ fields.hashCode;
}
123 changes: 123 additions & 0 deletions pkgs/record_use/lib/src/data_classes/arguments.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
// Copyright (c) 2024, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:collection/collection.dart';

class Arguments {
ConstArguments constArguments;
NonConstArguments nonConstArguments;

Arguments({
ConstArguments? constArguments,
NonConstArguments? nonConstArguments,
}) : constArguments = constArguments ?? ConstArguments(),
nonConstArguments = nonConstArguments ?? NonConstArguments();

factory Arguments.fromJson(Map<String, dynamic> json) {
final constJson = json['const'] as Map<String, dynamic>?;
final nonConstJson = json['nonConst'] as Map<String, dynamic>?;
return Arguments(
constArguments:
constJson != null ? ConstArguments.fromJson(constJson) : null,
nonConstArguments: nonConstJson != null
? NonConstArguments.fromJson(nonConstJson)
: null,
);
}

Map<String, dynamic> toJson() {
final hasConst =
constArguments.named.isNotEmpty || constArguments.positional.isNotEmpty;
final hasNonConst = nonConstArguments.named.isNotEmpty ||
nonConstArguments.positional.isNotEmpty;
return {
if (hasConst) 'const': constArguments.toJson(),
if (hasNonConst) 'nonConst': nonConstArguments.toJson(),
};
}

@override
bool operator ==(Object other) {
if (identical(this, other)) return true;

return other is Arguments &&
other.constArguments == constArguments &&
other.nonConstArguments == nonConstArguments;
}

@override
int get hashCode => constArguments.hashCode ^ nonConstArguments.hashCode;
}

class ConstArguments {
Map<int, dynamic> positional;
Map<String, dynamic> named;

ConstArguments({Map<int, dynamic>? positional, Map<String, dynamic>? named})
: named = named ?? {},
positional = positional ?? {};

factory ConstArguments.fromJson(Map<String, dynamic> json) => ConstArguments(
positional: json['positional'] != null
? (json['positional'] as Map<String, dynamic>)
.map((key, value) => MapEntry(int.parse(key), value))
: {},
named:
json['named'] != null ? json['named'] as Map<String, dynamic> : {},
);

Map<String, dynamic> toJson() => {
if (positional.isNotEmpty)
'positional':
positional.map((key, value) => MapEntry(key.toString(), value)),
if (named.isNotEmpty) 'named': named,
};

@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
final mapEquals = const DeepCollectionEquality().equals;

return other is ConstArguments &&
mapEquals(other.positional, positional) &&
mapEquals(other.named, named);
}

@override
int get hashCode => positional.hashCode ^ named.hashCode;
}

class NonConstArguments {
List<int> positional;
List<String> named; // Assuming named arguments are strings (keys)

NonConstArguments({List<int>? positional, List<String>? named})
: named = named ?? [],
positional = positional ?? [];

factory NonConstArguments.fromJson(Map<String, dynamic> json) =>
NonConstArguments(
positional:
json['positional'] != null ? json['positional'] as List<int> : [],
named: json['named'] != null ? json['named'] as List<String> : [],
);

Map<String, dynamic> toJson() => {
if (positional.isNotEmpty) 'positional': positional,
if (named.isNotEmpty) 'named': named,
};

@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
final listEquals = const DeepCollectionEquality().equals;

return other is NonConstArguments &&
listEquals(other.positional, positional) &&
listEquals(other.named, named);
}

@override
int get hashCode => positional.hashCode ^ named.hashCode;
}
Loading