Skip to content

Commit 91d34c6

Browse files
authored
[record_use] Use update_snippets.dart (dart-lang#3087)
Fix the doc comments in this package. * Fixes the docs to be up to date with current usage. * Adds a pirate themed API doc. * Ignores the use cases for now. * In the future we should make these full fledged examples in the examples/ dir. * Makes the snippets tool more powerful with anchors and nested snippets.
1 parent 73ba13f commit 91d34c6

10 files changed

Lines changed: 241 additions & 120 deletions

File tree

‎pkgs/hooks/tool/update_snippets.dart‎

Lines changed: 57 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ void main(List<String> args) {
2121
final counts = Counts();
2222
final errors = <String>[];
2323
final hooksPackageRoot = findPackageRoot('hooks');
24-
for (final package in ['hooks', 'code_assets', 'data_assets']) {
24+
for (final package in ['hooks', 'code_assets', 'data_assets', 'record_use']) {
2525
final packageRoot = hooksPackageRoot.resolve('../$package/');
2626

2727
final files = Directory.fromUri(packageRoot)
@@ -141,7 +141,7 @@ String updateSnippets(String oldContent, Uri fileUri, List<String> errors) {
141141
final lineBeforeText = oldContent.split('\n')[lastLineOfContentBefore];
142142

143143
final fileLineMatch = RegExp(
144-
r'^(.*?)<!-- (?:file://./(\S+)|(no-source-file)) -->\s*$',
144+
r'^(.*?)<!-- (?:file://./(\S+?)(?:#(\S+))?|(no-source-file)) -->\s*$',
145145
).firstMatch(lineBeforeText);
146146

147147
if (fileLineMatch == null) {
@@ -163,7 +163,8 @@ String updateSnippets(String oldContent, Uri fileUri, List<String> errors) {
163163
}
164164

165165
final filePath = fileLineMatch.group(2);
166-
final noSourceFile = fileLineMatch.group(3) != null;
166+
final anchor = fileLineMatch.group(3);
167+
final noSourceFile = fileLineMatch.group(4) != null;
167168

168169
if (noSourceFile || filePath == null) continue;
169170

@@ -179,14 +180,42 @@ String updateSnippets(String oldContent, Uri fileUri, List<String> errors) {
179180
);
180181

181182
var newSnippetText = snippetContent;
183+
final String startMarker;
184+
final String endMarker;
185+
if (anchor == null) {
186+
startMarker = '// snippet-start';
187+
endMarker = '// snippet-end';
188+
} else {
189+
startMarker = '// snippet-start#$anchor';
190+
endMarker = '// snippet-end#$anchor';
191+
}
192+
182193
final anchorRegex = RegExp(
183-
r'// snippet-start\n([\s\S]*?)// snippet-end',
194+
'${RegExp.escape(startMarker)}\\n([\\s\\S]*?)${RegExp.escape(endMarker)}',
184195
multiLine: true,
185196
);
186197
final extractedMatch = anchorRegex.firstMatch(snippetContent);
187198
if (extractedMatch != null) {
188199
newSnippetText = extractedMatch.group(1)!;
200+
} else {
201+
if (anchor != null) {
202+
errors.add('Error: Anchor "$anchor" not found in $snippetUri.');
203+
continue;
204+
}
205+
// If no anchor was specified and // snippet-start wasn't found,
206+
// we use the whole file (original behavior).
189207
}
208+
209+
// Strip any (nested) snippet markers from the extracted content.
210+
final markerRegex = RegExp(
211+
r'^[ \t]*// snippet-(?:start|end)(?:#\S+)?[ \t]*\n?',
212+
multiLine: true,
213+
);
214+
newSnippetText = newSnippetText.replaceAll(markerRegex, '');
215+
216+
newSnippetText = _dedent(newSnippetText);
217+
newSnippetText = newSnippetText.trim();
218+
190219
final copyrightRegex = RegExp(r'''
191220
// Copyright \(c\) [0-9]*, the Dart project authors. Please see the AUTHORS file
192221
// for details. All rights reserved. Use of this source code is governed by a
@@ -216,3 +245,27 @@ String updateSnippets(String oldContent, Uri fileUri, List<String> errors) {
216245

217246
return newContent;
218247
}
248+
249+
String _dedent(String text) {
250+
final lines = text.split('\n');
251+
if (lines.isEmpty) return text;
252+
253+
// Find minimum indentation of non-empty lines.
254+
int? minIndent;
255+
for (final line in lines) {
256+
if (line.trim().isEmpty) continue;
257+
final indent = line.length - line.trimLeft().length;
258+
if (minIndent == null || indent < minIndent) {
259+
minIndent = indent;
260+
}
261+
}
262+
263+
if (minIndent == null || minIndent == 0) return text;
264+
265+
return lines
266+
.map((line) {
267+
if (line.trim().isEmpty) return '';
268+
return line.substring(minIndent!);
269+
})
270+
.join('\n');
271+
}

‎pkgs/record_use/README.md‎

Lines changed: 34 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,7 @@ being recorded.
1212
- If placed on a static method, the annotation means that arguments passed to
1313
the method will be recorded, as far as they can be inferred at compile time.
1414
- If placed on a class with a constant constructor, the annotation means that
15-
any constant instance of the class will be recorded. This is particularly useful
16-
when using the class as an annotation.
15+
any constant instance of the class will be recorded.
1716

1817
> [!NOTE]
1918
> The `@RecordUse` annotation is only allowed on definitions within a package's
@@ -22,102 +21,62 @@ when using the class as an annotation.
2221
2322
## Example
2423

24+
<!-- file://./example/api/usage.dart#usage -->
2525
```dart
26-
import 'package:meta/meta.dart' show RecordUse;
27-
2826
void main() {
29-
print(SomeClass.stringMetadata(42));
30-
print(SomeClass.doubleMetadata(42));
31-
print(SomeClass.intMetadata(42));
32-
print(SomeClass.boolMetadata(42));
27+
PirateTranslator.speak('Hello');
28+
print(const PirateShip('Black Pearl', 50));
3329
}
3430
35-
class SomeClass {
36-
@RecordMetadata('leroyjenkins')
37-
@RecordUse()
38-
static stringMetadata(int i) {
39-
return i + 1;
40-
}
41-
42-
@RecordMetadata(3.14)
43-
@RecordUse()
44-
static doubleMetadata(int i) {
45-
return i + 1;
46-
}
47-
48-
@RecordMetadata(42)
49-
@RecordUse()
50-
static intMetadata(int i) {
51-
return i + 1;
52-
}
53-
54-
@RecordMetadata(true)
31+
abstract class PirateTranslator {
5532
@RecordUse()
56-
static boolMetadata(int i) {
57-
return i + 1;
58-
}
33+
static String speak(String english) => 'Ahoy $english';
5934
}
6035
6136
@RecordUse()
62-
class RecordMetadata {
63-
final Object metadata;
37+
class PirateShip {
38+
final String name;
39+
final int cannons;
6440
65-
const RecordMetadata(this.metadata);
41+
const PirateShip(this.name, this.cannons);
6642
}
67-
6843
```
69-
This code will generate a data file that contains both the `metadata` values of
70-
the `RecordMetadata` instances, as well as the arguments for the different
71-
methods annotated with `@RecordUse()`.
44+
This code will generate a data file that contains both the field values of
45+
the `PirateShip` instances, as well as the arguments for the `speak`
46+
method annotated with `@RecordUse()`.
7247

7348
This information can then be accessed in a link hook as follows:
49+
<!-- file://./example/api/usage_link.dart#link -->
7450
```dart
75-
import 'dart:convert';
76-
77-
import 'package:hooks/hooks.dart';
78-
import 'package:record_use/record_use_internal.dart';
79-
80-
final methodId = Definition(
81-
'package:mypackage/myfile.dart',
82-
[Name('myMethod')],
83-
);
84-
85-
final classId = Definition(
86-
'package:mypackage/myfile.dart',
87-
[Name('myClass')],
88-
);
89-
90-
void main(List<String> arguments){
51+
void main(List<String> arguments) {
9152
link(arguments, (input, output) async {
9253
final usesUri = input.recordedUsagesFile;
9354
if (usesUri == null) return;
9455
final usesJson = await File.fromUri(usesUri).readAsString();
95-
final uses = RecordedUsages.fromJson(jsonDecode(usesJson));
56+
final uses = RecordedUsages.fromJson(
57+
jsonDecode(usesJson) as Map<String, Object?>,
58+
);
9659
9760
final args = uses.constArgumentsFor(methodId);
98-
//[args] is an iterable of arguments, in this case containing "42"
99-
100-
final fields = uses.constantsOf(classId);
101-
//[fields] is an iterable of the constants of the class, in this case
102-
//containing
103-
// {"metadata": "leroyjenkins"}
104-
// {"metadata": 3.14}
105-
// {"metadata": 42}
106-
// {"metadata": true}
107-
108-
... // Do something with the information, such as tree-shaking native assets
61+
for (final arg in args) {
62+
if (arg.positional[0] case StringConstant(value: final english)) {
63+
print('Translating to pirate: $english');
64+
// Shrink a translations file based on all the different translation
65+
// keys.
66+
}
67+
}
68+
69+
final ships = uses.constantsOf(classId);
70+
for (final ship in ships) {
71+
if (ship.fields['name'] case StringConstant(value: final name)) {
72+
print('Pirate ship found: $name');
73+
// Include the 3d model for this ship in the application but not
74+
// bundle the other ships.
75+
}
76+
}
10977
});
11078
}
11179
```
11280

113-
## Limitations
114-
As this is designed to work on both web and native platforms, we have to adapt
115-
to the platform pecularities. One of them is that javascript does not support
116-
named arguments, so the dart2js compiler rewrites functions to only accept named
117-
parameters.
118-
While you can use named parameters to record functions, we advise caution as the
119-
retrieval behavior might change once we work around this dart2js limitation and
120-
implement separate positional and named parameters.
121-
12281
## Contributing
12382
Contributions are welcome! Please open an issue or submit a pull request.

‎pkgs/record_use/doc/use_cases/icon_data.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ package.
66

77
Dart API and use:
88

9+
<!-- no-source-file -->
910
```dart
1011
class IconData {
1112
const IconData(
@@ -18,6 +19,7 @@ class IconData {
1819
}
1920
```
2021

22+
<!-- no-source-file -->
2123
```dart
2224
abstract final class GalleryIcons {
2325
static const IconData tooltip = IconData(0xe900, fontFamily: 'GalleryIcons');
@@ -45,6 +47,7 @@ the const instances.
4547
Since this API is already in active use, we cannot simply change the API to
4648
static getters, as that would prevent const:
4749

50+
<!-- no-source-file -->
4851
```dart
4952
abstract final class GalleryIcons {
5053
static IconData get tooltip => IconData(0xe900, fontFamily: 'GalleryIcons');

‎pkgs/record_use/doc/use_cases/icu4x.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ MBs.
88

99
The native symbols that are reachable:
1010

11+
<!-- no-source-file -->
1112
```dart
1213
@ffi.Native<ffi.Pointer<ffi.Void> Function(ffi.Size, ffi.Size)>(
1314
symbol: 'diplomat_alloc',
@@ -28,6 +29,7 @@ The file containing the external static functions is a generated file.
2829

2930
The link hook could import a generated file that contains the mapping:
3031

32+
<!-- no-source-file -->
3133
```dart
3234
const dartStaticCallToNativeSymbol = {
3335
'diplomat_alloc': '_diplomat_alloc',

‎pkgs/record_use/doc/use_cases/jaspr.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use style utilities and the final CSS is tree-shaken.
99
For example, a `Column` component might have styling options passed to its
1010
constructor:
1111

12+
<!-- no-source-file -->
1213
```dart
1314
class Column extends Component {
1415
@RecordUse()
@@ -24,6 +25,7 @@ class Column extends Component {
2425
When this component is used, we want to record the constructor call, including
2526
the arguments:
2627

28+
<!-- no-source-file -->
2729
```dart
2830
class MyComponent extends Component {
2931
@override

‎pkgs/record_use/doc/use_cases/jnigen.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ reachable Java/Kotlin classes, methods, and fields.
99

1010
### 1. Which classes are possibly instantiated.
1111

12+
<!-- no-source-file -->
1213
```dart
1314
class PDDocument extends jni$_.JObject {
1415
PDDocument.fromReference(
@@ -36,6 +37,7 @@ generated classes will ever have const constructors.
3637

3738
### 2. Which methods, getters and setters are reachable.
3839

40+
<!-- no-source-file -->
3941
```dart
4042
class PDDocument extends jni$_.JObject {
4143
void addPage(
@@ -48,6 +50,7 @@ This requires tracking instance calls, or generating a static call inside the
4850
instance call. JNIgen already generates a static field (with a static getter)
4951
that could be annotated to record a static call:
5052

53+
<!-- no-source-file -->
5154
```dart
5255
class PDDocument extends jni$_.JObject {
5356
static final _addPage = jni$_.ProtectedJniExtensions.lookup<
@@ -82,6 +85,7 @@ the original Java/Kotlin unique name.
8285
Since JNIgen is already a code generator, this can be achieved by generating a
8386
file that maps Dart identifiers to Java identifiers:
8487

88+
<!-- no-source-file -->
8589
```dart
8690
const dartToJava = {
8791
DartMethodIdentifer(

‎pkgs/record_use/doc/use_cases/messages.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
The goal of this package is to provide translation. The goal of using link hooks
44
is to be able to shrink the translation files based on use.
55

6+
<!-- no-source-file -->
67
```dart
78
class MessageTable {
89
@RecordUse()
@@ -14,6 +15,7 @@ class MessageTable {
1415
}
1516
```
1617

18+
<!-- no-source-file -->
1719
```dart
1820
String translateFoo() => lookup(/*int id of foo*/0, 'baz');
1921
@@ -26,6 +28,7 @@ the API for the translations.
2628

2729
If a transformer is used, the pre-transform code looks something like:
2830

31+
<!-- no-source-file -->
2932
```dart
3033
class Intl {
3134
static String message(String messageText,
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Copyright (c) 2026, the Dart project authors. Please see the AUTHORS file
2+
// for details. All rights reserved. Use of this source code is governed by a
3+
// BSD-style license that can be found in the LICENSE file.
4+
5+
// ignore_for_file: experimental_member_use, unreachable_from_main
6+
7+
import 'package:meta/meta.dart' show RecordUse;
8+
9+
// snippet-start#usage
10+
void main() {
11+
PirateTranslator.speak('Hello');
12+
print(const PirateShip('Black Pearl', 50));
13+
}
14+
15+
// snippet-start#static-call
16+
abstract class PirateTranslator {
17+
@RecordUse()
18+
static String speak(String english) => 'Ahoy $english';
19+
}
20+
// snippet-end#static-call
21+
22+
// snippet-start#const-instance
23+
@RecordUse()
24+
class PirateShip {
25+
final String name;
26+
final int cannons;
27+
28+
const PirateShip(this.name, this.cannons);
29+
}
30+
31+
// snippet-end#const-instance
32+
// snippet-end#usage

0 commit comments

Comments
 (0)