parseString function Null safety

ParseStringResult parseString(
  1. {required String content,
  2. FeatureSet? featureSet,
  3. String? path,
  4. bool throwIfDiagnostics = true}

Returns the result of parsing the given content as a compilation unit.

If a featureSet is provided, it will be the default set of features that will be assumed by the parser.

If a path is provided, it will be used as the name of the file when reporting errors.

If throwIfDiagnostics is true (the default), then if any diagnostics are produced because of syntactic errors in the content an ArgumentError will be thrown. This behavior is not intended as a way for the client to find out about errors--it is intended to avoid causing problems for naive clients that might not be thinking about the possibility of parse errors (and might therefore make assumptions about the returned AST that don't hold in the presence of parse errors). Clients interested in details about parse errors should pass false and check result.errors to determine what parse errors, if any, have occurred.


ParseStringResult parseString(
    {required String content,
    FeatureSet? featureSet,
    String? path,
    bool throwIfDiagnostics = true}) {
  featureSet ??= FeatureSet.latestLanguageVersion();
  var source = StringSource(content, path ?? '');
  var reader = CharSequenceReader(content);
  var errorCollector = RecordingErrorListener();
  var scanner = Scanner(source, reader, errorCollector)
      featureSetForOverriding: featureSet,
      featureSet: featureSet,
  var token = scanner.tokenize();
  var parser = Parser(
    featureSet: scanner.featureSet,
  var unit = parser.parseCompilationUnit(token);
  var lineInfo = LineInfo(scanner.lineStarts);
  unit.lineInfo = lineInfo;
  ParseStringResult result =
      ParseStringResultImpl(content, unit, errorCollector.errors);
  if (throwIfDiagnostics && result.errors.isNotEmpty) {
    var buffer = StringBuffer();
    for (var error in result.errors) {
      var location = lineInfo.getLocation(error.offset);
      buffer.writeln('  ${}: ${error.message} - '
    throw ArgumentError('Content produced diagnostics when parsed:\n$buffer');
  return result;