writeRoot method

Uint8List writeRoot(
  1. ASTRoot root, {
  2. required String language,
  3. String? namespace,
  4. String id = '',
})

Encodes root directly.

language is recorded so the image knows which runner to use; pass the parser's own language id (java11, not the java alias), since a deserialized unit never goes through a parser to have it normalized.

Implementation

Uint8List writeRoot(
  ASTRoot root, {
  required String language,
  String? namespace,
  String id = '',
}) {
  var strings = ASTStringPoolWriter();
  var types = ASTTypePoolWriter(strings);
  var ast = ASTBinaryWriteContext(strings, types);

  // The AST is encoded first: it is what fills the pools, and the pool
  // sections have to be written already complete.
  ast.node(root);
  var astBytes = ast.toBytes();

  var metadata = BytesBuffer();
  metadata.writeLeb128String(ApolloVM.VERSION);
  metadata.writeLeb128String(language);
  metadata.writeLeb128String(id);
  metadata.writeLeb128String(namespace ?? root.namespace);

  return ASTBinaryContainerCodec.encode(
    sections: [
      ASTBinarySectionData(ASTBinarySection.metadata.id, metadata.toBytes()),
      ASTBinarySectionData(ASTBinarySection.stringTable.id, strings.encode()),
      ASTBinarySectionData(ASTBinarySection.typeTable.id, types.encode()),
      ASTBinarySectionData(ASTBinarySection.astRoot.id, astBytes),
    ],
    signer: signer,
  );
}