loadCodeUnit<T extends Object> method

Future<bool> loadCodeUnit<T extends Object>(
  1. CodeUnit<T> codeUnit
)

Loads codeUnit, parsing the CodeUnit.source to the corresponding AST (Abstract Syntax Tree).

  • Returns false if there's no parser for the codeUnit language.
  • Throws a SyntaxError if the code can't be parsed.

Implementation

Future<bool> loadCodeUnit<T extends Object>(CodeUnit<T> codeUnit) async {
  var language = codeUnit.language;

  ApolloCodeParser<T>? parser;
  if (codeUnit.root == null) {
    parser = getParser<T>(codeUnit.language);

    if (parser != null) {
      language = parser.language;

      var result = await parser.parse(codeUnit);

      if (!result.isOK) {
        throw SyntaxError(result.errorMessageExtended, parseResult: result);
      }

      var root = result.root!;
      codeUnit.root = root;

      codeUnit.namespace ??= root.namespace;
    }
  }

  var namespace = codeUnit.namespace;
  if (namespace == null) {
    throw StateError("`CodeUnit` namespace NOT defined. Parser: $parser");
  }

  // Reject a unit with null-safety errors before it is registered, so the
  // failure lands at resolution time rather than partway through a run. A
  // `BinaryCodeUnit` (Wasm) carries no AST, so there is nothing to analyze.
  _checkNullSafety(codeUnit);

  var langNamespaces = getLanguageNamespaces(language);
  var codeNamespace = langNamespaces.get(namespace);

  codeNamespace.addCodeUnit(codeUnit);

  // Incremental hook: (re)loading a unit invalidates the affected subgraph so
  // the next resolution re-resolves only what changed.
  _resolutionEngine?.invalidate(codeUnit.id);

  return true;
}