parseFile method

ParseResults parseFile(
  1. String inputPath, {
  2. String? sdkPath,
})

Reads the file located at path and generates ParseResults by parsing it. types optionally filters out what datatypes are actually parsed. sdkPath for specifying the Dart SDK path for AnalysisContextCollection.

Implementation

ParseResults parseFile(String inputPath, {String? sdkPath}) {
  final List<String> includedPaths = <String>[
    path.absolute(path.normalize(inputPath))
  ];
  final AnalysisContextCollection collection = AnalysisContextCollection(
    includedPaths: includedPaths,
    sdkPath: sdkPath,
  );

  final List<Error> compilationErrors = <Error>[];
  final _RootBuilder rootBuilder =
      _RootBuilder(File(inputPath).readAsStringSync());
  for (final AnalysisContext context in collection.contexts) {
    for (final String path in context.contextRoot.analyzedFiles()) {
      final AnalysisSession session = context.currentSession;
      final ParsedUnitResult result =
          session.getParsedUnit(path) as ParsedUnitResult;
      if (result.errors.isEmpty) {
        final dart_ast.CompilationUnit unit = result.unit;
        unit.accept(rootBuilder);
      } else {
        for (final AnalysisError error in result.errors) {
          compilationErrors.add(Error(
              message: error.message,
              filename: error.source.fullName,
              lineNumber: _calculateLineNumber(
                  error.source.contents.data, error.offset)));
        }
      }
    }
  }

  if (compilationErrors.isEmpty) {
    return rootBuilder.results();
  } else {
    return ParseResults(
      root: Root.makeEmpty(),
      errors: compilationErrors,
      pigeonOptions: null,
    );
  }
}