Skip to content

Instantly share code, notes, and snippets.

@osaxma
Created January 15, 2024 12:46
Show Gist options
  • Save osaxma/6f716d3ca37ac42a12c45f0dac9bd23a to your computer and use it in GitHub Desktop.
Save osaxma/6f716d3ca37ac42a12c45f0dac9bd23a to your computer and use it in GitHub Desktop.
generate a resolved AST fromString
import 'package:analyzer/dart/analysis/analysis_context_collection.dart';
import 'package:analyzer/dart/analysis/results.dart';
import 'package:analyzer/file_system/overlay_file_system.dart';
import 'package:analyzer/file_system/physical_file_system.dart';
final string = '''
class App {
final String id;
final String name;
App(this.id, this.name);
}
''';
// dart run resolve_ast_from_string.dart (~2097-ms)
// dart run resolve_ast_from_string.dart (~700-ms)
// dartaotruntime resolve_ast_from_string.aot (~305-ms)
Future<void> main() async {
final watch = Stopwatch()..start();
final filePath = '/it/does/not/matter/file.dart';
final collection = AnalysisContextCollection(
includedPaths: [filePath],
resourceProvider: OverlayResourceProvider(
PhysicalResourceProvider(),
)..setOverlay(
filePath,
content: string,
modificationStamp: 0,
),
);
final analysisSession = collection.contextFor(filePath).currentSession;
final libraryElement = await analysisSession
.getLibraryByUri('file://$filePath')
.then((libraryResult) => (libraryResult as LibraryElementResult).element);
final clazz = libraryElement.getClass('App');
print(clazz?.name); // prints App
watch.stop();
print('elapsed time ${watch.elapsedMilliseconds}-ms');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment