-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathcelest_analyzer.dart
More file actions
647 lines (601 loc) · 20.8 KB
/
celest_analyzer.dart
File metadata and controls
647 lines (601 loc) · 20.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
import 'dart:async';
import 'dart:io';
import 'package:analyzer/dart/analysis/results.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/diagnostic/diagnostic.dart';
import 'package:analyzer/error/error.dart';
import 'package:analyzer/error/listener.dart';
import 'package:analyzer/src/dart/analysis/analysis_context_collection.dart';
import 'package:analyzer/src/dart/analysis/driver_based_analysis_context.dart';
import 'package:analyzer/src/error/codes.dart';
import 'package:celest_ast/celest_ast.dart' as ast;
import 'package:celest_cli/src/analyzer/analysis_error.dart';
import 'package:celest_cli/src/analyzer/analysis_result.dart';
import 'package:celest_cli/src/analyzer/celest_analysis_helpers.dart';
import 'package:celest_cli/src/analyzer/resolver/project_resolver.dart';
import 'package:celest_cli/src/ast/ast.dart';
import 'package:celest_cli/src/config/feature_flags.dart';
import 'package:celest_cli/src/context.dart';
import 'package:celest_cli/src/database/cache/cache_database.dart';
import 'package:celest_cli/src/init/edits/source_edit_applier.dart';
import 'package:celest_cli/src/pub/project_dependency.dart';
import 'package:celest_cli/src/pub/pub_action.dart';
import 'package:celest_cli/src/pub/pub_environment.dart';
import 'package:celest_cli/src/pub/pubspec.dart';
import 'package:celest_cli/src/sdk/dart_sdk.dart';
import 'package:celest_cli/src/types/type_helper.dart';
import 'package:celest_cli/src/utils/analyzer.dart';
import 'package:celest_cli/src/utils/reference.dart';
import 'package:logging/logging.dart';
import 'package:pubspec_parse/pubspec_parse.dart';
import 'package:source_span/source_span.dart';
import 'package:stream_transform/stream_transform.dart';
final class CelestAnalyzer
with CelestAnalysisHelpers
implements AnalysisErrorListener {
CelestAnalyzer._();
factory CelestAnalyzer() => _instance ??= CelestAnalyzer._();
static CelestAnalyzer? _instance;
static final Logger _logger = Logger('CelestAnalyzer');
/// Warms up the analyzer caches by resolving the core libraries and types
/// in a background thread.
///
/// The results will be persisted to the byte store so that they can be
/// reused in subsequent analyzer instances.
static Future<void> warmUp(String projectRoot) async {
final database = await CacheDatabase.open(projectRoot, verbose: false);
var projectDir = fileSystem.directory(projectRoot);
final Iterable<String> dependencies;
if (!fileSystem.file(p.join(projectRoot, 'pubspec.lock')).existsSync()) {
// If the project hasn't been created yet, create a dummy project to warm
// up the caches.
projectDir = fileSystem.systemTempDirectory.createTempSync('celest_');
dependencies = ProjectDependency.backendDependencies.keys;
final pubspec = Pubspec(
'warmup_celest_cache',
environment: {'sdk': PubEnvironment.dartSdkConstraint},
dependencies: ProjectDependency.backendDependencies.toPub(),
);
await [
projectDir.childFile('pubspec.yaml').writeAsString(pubspec.toYaml()),
projectDir.childFile('project.dart').writeAsString('''
import 'package:celest/celest.dart';
const project = Project(name: 'cache_warmup');
'''),
].wait;
await runPub(action: PubAction.get, workingDirectory: projectDir.path);
} else {
// Otherwise, cache the dependencies of the existing project.
final pubspec = Pubspec.parse(
projectDir.childFile('pubspec.yaml').readAsStringSync(),
);
dependencies = pubspec.dependencies.keys;
}
final contextCollection = AnalysisContextCollectionImpl(
includedPaths: [projectDir.path],
sdkPath: Sdk.current.sdkPath,
// Needed for collecting subtypes.
enableIndex: true,
byteStore: database.byteStore,
);
final context = contextCollection.contextFor(
p.join(projectDir.path, 'project.dart'),
);
final libraries = {
'dart:core',
'dart:typed_data',
'package:celest_core/celest_core.dart',
'package:celest_core/src/exception/cloud_exception.dart',
'package:celest_core/src/auth/user.dart',
...dependencies.map((dep) => 'package:$dep/$dep.dart'),
};
await Future.wait(libraries.map(context.currentSession.getLibraryByUri));
}
@override
DriverBasedAnalysisContext get context => celestProject.analysisContext;
final List<CelestAnalysisError> _errors = [];
final List<CelestAnalysisError> _warnings = [];
final List<CelestAnalysisError> _infos = [];
final List<CelestAnalysisError> _debugs = [];
late _ScopedWidgetCollector _widgetCollector;
late ast.ProjectBuilder _project;
CelestProjectResolver? _resolver;
CelestProjectResolver get resolver => _resolver!;
/// Whether [code] and [message] represent a possible false-positive for
/// missing code generation.
bool _missingCodegenError(AnalysisError error) {
switch (error.errorCode) {
case CompileTimeErrorCode.URI_DOES_NOT_EXIST:
final regex = RegExp(r'''Target of URI doesn't exist: '(.+?)'\.''');
final match = regex.firstMatch(error.message);
final uri = match?.group(1);
if (uri == null) {
return false;
}
final path =
context.currentSession.uriConverter.uriToPath(Uri.parse(uri));
if (path == null) {
_logger.fine('Failed to convert URI to path: $uri');
return false;
}
return p.isWithin(projectPaths.generatedDir, path);
}
return false;
}
@override
void reportError(
String error, {
AnalysisErrorSeverity? severity,
SourceSpan? location,
}) {
switch (severity) {
case AnalysisErrorSeverity.error || null:
_errors.add(
CelestAnalysisError(
message: error,
location: location,
severity: severity,
),
);
case AnalysisErrorSeverity.warning:
_warnings.add(
CelestAnalysisError(
message: error,
location: location,
severity: severity,
),
);
case AnalysisErrorSeverity.info:
_infos.add(
CelestAnalysisError(
message: error,
location: location,
severity: severity,
),
);
case AnalysisErrorSeverity.debug:
_debugs.add(
CelestAnalysisError(
message: error,
location: location,
severity: severity,
),
);
}
}
@override
void onError(AnalysisError error) {
// TODO:
}
@override
void reset() {
_logger.finest('Clearing analyzer caches...');
super.reset();
_initFuture = null;
_resolver = null;
typeHelper.reset();
}
Future<void> init({required bool migrateProject}) async {
_errors.clear();
_warnings.clear();
_infos.clear();
_debugs.clear();
_resolver ??= CelestProjectResolver(
featureFlags: await FeatureFlags.load(),
migrateProject: migrateProject,
errorReporter: this,
context: context,
);
await Future.wait([
_initFuture ??= _init(),
_resolver!.resolveCustomTypes(),
]);
}
Future<void>? _initFuture;
Future<void> _init() async {
final (
dartCore as LibraryElementResult,
dartTypedData as LibraryElementResult,
celestCoreExceptions,
celestCoreUser,
celestConfigValues,
jsonAnnotation,
) = await (
context.currentSession.getLibraryByUri('dart:core'),
context.currentSession.getLibraryByUri('dart:typed_data'),
// Resolve the specific URIs instead of resolving the whole package
// (which takes much much longer).
context.currentSession.getLibraryByUri(
'package:celest_core/src/exception/cloud_exception.dart',
),
context.currentSession.getLibraryByUri(
'package:celest_core/src/auth/user.dart',
),
context.currentSession.getLibraryByUri(
'package:celest/src/config/config_values.dart',
),
// `package:json_annotation/json_annotation.dart` is used in the
// generated code when serializing/deserializing models.
context.currentSession.getLibraryByUri(
'package:json_annotation/src/json_key.dart',
),
).wait;
if (celestCoreExceptions is! LibraryElementResult ||
celestCoreUser is! LibraryElementResult) {
await dumpPackageConfig();
throw StateError('Failed to resolve celest_core');
}
if (celestConfigValues is! LibraryElementResult) {
await dumpPackageConfig();
throw StateError('Failed to resolve celest');
}
final jsonAnnotationLib = switch (jsonAnnotation) {
LibraryElementResult() => jsonAnnotation,
_ => null,
};
if (jsonAnnotationLib == null) {
await dumpPackageConfig();
_logger.fine(
'Failed to resolve package:json_annotation',
jsonAnnotation,
StackTrace.current,
);
}
final envElement = celestConfigValues.getClassElement('env');
final secretElement = celestConfigValues.getClassElement('secret');
typeHelper
..coreTypes = CoreTypes(
typeProvider: dartCore.element.typeProvider,
coreExceptionType: dartCore.getClassType('Exception'),
coreErrorType: dartCore.getClassType('Error'),
coreBigIntType: dartCore.getClassType('BigInt'),
dateTimeType: dartCore.getClassType('DateTime'),
durationType: dartCore.getClassType('Duration'),
coreRegExpType: dartCore.getClassType('RegExp'),
coreStackTraceType: dartCore.getClassType('StackTrace'),
coreUriType: dartCore.getClassType('Uri'),
coreUriDataType: dartCore.getClassType('UriData'),
typedDataUint8ListType: dartTypedData.getClassType('Uint8List'),
badRequestExceptionType: celestCoreExceptions.getClassType(
'BadRequestException',
),
internalServerErrorType: celestCoreExceptions.getClassType(
'InternalServerError',
),
userType: celestCoreUser.getClassType('User'),
cloudExceptionType: celestCoreExceptions.getClassType('CloudException'),
celestEnvType: envElement.thisType,
celestEnvElement: envElement,
celestSecretType: secretElement.thisType,
celestSecretElement: secretElement,
jsonKeyElement: jsonAnnotationLib?.getClassElement('JsonKey'),
)
..typeSystem = dartCore.element.typeSystem
..typeProvider = dartCore.element.typeProvider;
}
@override
Set<InterfaceElement> get customModelTypes =>
_resolver?.customModelTypes ?? const {};
@override
Set<InterfaceElement> get customExceptionTypes =>
_resolver?.customExceptionTypes ?? const {};
Future<CelestAnalysisResult> analyzeProject({
bool migrateProject = false,
bool updateResources = true,
}) async {
await performance.trace(
'CelestAnalyzer',
'init',
() => init(migrateProject: migrateProject),
);
if (_errors.isNotEmpty) {
return CelestAnalysisResult.failure(
_errors,
warnings: _warnings,
infos: _infos,
);
}
final project = await performance.trace(
'CelestAnalyzer',
'findProject',
_findProject,
);
if (project == null || _errors.isNotEmpty) {
return CelestAnalysisResult.failure(
_errors,
warnings: _warnings,
infos: _infos,
);
}
_project = project.toBuilder();
_widgetCollector = _ScopedWidgetCollector(errorReporter: reportError);
final variables = await performance.trace(
'CelestAnalyzer',
'resolveEnvVariables',
resolver.resolveVariables,
);
final secrets = await performance.trace(
'CelestAnalyzer',
'resolveSecrets',
resolver.resolveSecrets,
);
final auth = await performance.trace(
'CelestAnalyzer',
'collectAuth',
() => _collectAuth(migrateProject: migrateProject),
);
if (auth != null) {
_project.auth.replace(auth);
variables.addAll(auth.variables.values);
secrets.addAll(auth.secrets.values);
}
await performance.trace(
'CelestAnalyzer',
'collectApis',
() => _collectApis(
hasAuth: auth != null,
variables: variables,
secrets: secrets,
),
);
final hasCloudAuth = auth?.providers.isNotEmpty ?? false;
final databases = await performance.trace(
'CelestAnalyzer',
'resolveDatabases',
() => _resolveDatabases(hasCloudAuth: hasCloudAuth),
);
if (databases.isNotEmpty) {
for (final database in databases) {
_project.databases[database.name] = database;
}
} else if (hasCloudAuth) {
final cloudAuthElement = await helper.getClass(
'package:celest_cloud_auth/src/database/auth_database.dart',
'CloudAuthDatabase',
);
if (cloudAuthElement == null) {
throw StateError('Failed to resolve CloudAuthDatabase');
}
_project.databases['CloudAuthDatabase'] = ast.Database(
name: 'CloudAuthDatabase',
dartName: 'cloudAuth',
schema: ast.DriftDatabaseSchema(
declaration:
typeHelper.toReference(cloudAuthElement.thisType).toTypeReference,
version: await resolveSchemaVersion(cloudAuthElement),
location: cloudAuthElement.sourceLocation!,
),
config: ast.CelestDatabaseConfig(
hostname: ast.Variable(
'CLOUD_AUTH_DATABASE_HOST',
location: cloudAuthElement.sourceLocation!,
),
token: ast.Secret(
'CLOUD_AUTH_DATABASE_TOKEN',
location: cloudAuthElement.sourceLocation!,
),
),
location: auth!.location,
);
}
await performance.trace(
'CelestAnalyzer',
'applyMigrations',
_applyMigrations,
);
// Add config values only at the end since other components may contribute
// to them.
_project.variables.replace(variables);
_project.secrets.replace(secrets);
return CelestAnalysisResult.success(
project: _project.build(),
errors: _errors,
warnings: _warnings,
infos: _infos,
);
}
Future<ast.Project?> _findProject() async {
_logger.fine('Analyzing project...');
final projectFilePath = projectPaths.projectDart;
if (!fileSystem.file(projectFilePath).existsSync()) {
reportError('No project file found at $projectFilePath');
return null;
}
_logger.finer('Found project file at $projectFilePath');
final projectLibrary = context.currentSession.getParsedLibrary(
projectFilePath,
);
if (projectLibrary is! ParsedLibraryResult) {
reportError('Failed to parse project.dart file');
return null;
}
final projectErrors = projectLibrary.units
.expand((unit) => unit.errors)
.where((error) => error.severity == Severity.error)
.toList();
if (projectErrors.isNotEmpty) {
for (final projectError in projectErrors) {
_logger.finest(
'ERROR (project.dart): type=${projectError.errorCode.type} '
'name=${projectError.errorCode.name}',
);
reportError(
projectError.message,
location: projectError.source.toSpan(
projectError.problemMessage.offset,
projectError.problemMessage.offset +
projectError.problemMessage.length,
),
);
}
return null;
}
_logger.finer('Resolved project file');
// TODO(dnys1): Some errors are okay, for example if `resources.dart` hasn't
// been updated yet and references a resource that doesn't exist yet.
// if (projectFile.errors.isNotEmpty) {
// reportError(
// 'Project file has errors:\n${projectFile.errors.join('\n')}',
// SourceLocation(
// path: projectFileRelativePath,
// line: 0,
// column: 0,
// ),
// );
// }
return resolver.resolveProject(projectLibrary: projectLibrary);
}
Future<void> _collectApis({
required bool hasAuth,
required Set<ast.Variable> variables,
required Set<ast.Secret> secrets,
}) async {
final apiDir = fileSystem.directory(projectPaths.apisDir);
if (!await apiDir.exists()) {
return;
}
final apiFiles = await apiDir
.list(followLinks: true)
.whereType<File>()
.map((file) => file.path)
.where((path) => path.endsWith('.dart'))
.toList();
final apiDeclarations = _widgetCollector.collect(
apiFiles,
scope: 'API',
placeholder: '<api_name>',
);
for (final MapEntry(key: apiName, value: apiPath)
in apiDeclarations.entries) {
if (apiName.startsWith('_')) {
// This would lead to private fields being generated in the client. It
// also allows us to reserve all `_` paths for internal usage.
reportError(
'API names may not start with an underscore (`_`)',
location: SourceFile.fromString(
await fileSystem.file(apiPath).readAsString(),
url: p.toUri(apiPath),
).span(0, 0),
);
continue;
}
final apiLibraryResult = await resolveLibrary(apiPath);
final apiErrors = apiLibraryResult.units
.expand((unit) => unit.errors)
.where((error) => error.severity == Severity.error)
.toList();
// If there's a false positive from missing generated code, which can
// happen for example when starting from a template proejct, then skip
// reporting errors since they may be resolved through generation, and if
// not, they'll be caught by the frontend compiler.
final falsePositiveForGeneratedCode =
apiErrors.isNotEmpty && apiErrors.any(_missingCodegenError);
if (apiErrors.isNotEmpty && !falsePositiveForGeneratedCode) {
for (final apiError in apiErrors) {
reportError(
apiError.message,
location: apiError.source.toSpan(
apiError.problemMessage.offset,
apiError.problemMessage.offset + apiError.problemMessage.length,
),
);
}
continue;
}
final baseApi = await resolver.resolveApi(
apiFilepath: apiPath,
apiName: apiName,
apiLibrary: apiLibraryResult,
variables: variables,
secrets: secrets,
hasAuth: hasAuth,
);
if (baseApi == null) {
return;
}
_project.apis.update((apis) => apis[apiName] = baseApi);
}
}
Future<ast.Auth?> _collectAuth({required bool migrateProject}) async {
final potentialAuthFiles = [
projectPaths.authDart,
projectPaths.projectDart,
];
final authLibraries = await Future.wait(
potentialAuthFiles
.where((it) => fileSystem.file(it).existsSync())
.map(resolveLibrary),
);
final authErrors = authLibraries
.expand((library) => library.units)
.expand((unit) => unit.errors)
.where((error) => error.severity == Severity.error)
.toList();
if (authErrors.isNotEmpty) {
for (final authError in authErrors) {
reportError(
authError.message,
location: authError.source.toSpan(
authError.problemMessage.offset,
authError.problemMessage.offset + authError.problemMessage.length,
),
);
}
return null;
}
for (final library in authLibraries) {
final auth = await resolver.resolveAuth(
authFilepath: context.currentSession.uriConverter.uriToPath(
library.element.source.uri,
)!,
authLibrary: library,
);
if (auth != null) {
return auth;
}
}
return null;
}
Future<List<ast.Database>> _resolveDatabases({
required bool hasCloudAuth,
}) async {
final databaseFile = fileSystem.file(projectPaths.projectDart);
if (!databaseFile.existsSync()) {
return const [];
}
final databaseLibrary = await resolveLibrary(databaseFile.path);
final database = await resolver.resolveDatabase(
databaseFilepath: databaseFile.path,
databaseLibrary: databaseLibrary,
hasCloudAuth: hasCloudAuth,
);
return database == null ? const [] : [database];
}
Future<void> _applyMigrations() async {
await SourceEditApplier(resolver.pendingEdits).apply();
resolver.pendingEdits.clear();
}
}
final class _ScopedWidgetCollector {
_ScopedWidgetCollector({required this.errorReporter});
final AnalysisErrorReporter errorReporter;
Map<String, String> collect(
List<String> files, {
required String scope,
required String placeholder,
}) {
final declarations = <String, String>{};
for (final file in files) {
switch (p.basename(file).split('.')) {
case [final baseName, 'dart']:
declarations[baseName] = file;
default:
errorReporter(
'$scope files must be named as follows: $placeholder.dart',
);
continue;
}
}
return declarations;
}
}