encode method

Program encode(
  1. String source, {
  2. String name = 'encoded',
  3. String version = '1.0.0',
  4. String partResolver(
    1. String uri
    )?,
})

Encode Dart source into a ball program.

If partResolver is provided, the encoder will inline part 'X.dart'; directives by calling the resolver with the URI string and parsing the returned source as additional declarations of the same library. Without a resolver, parts are recorded as metadata only and their declarations are silently dropped — which breaks any encode of a multi-file library.

Implementation

Program encode(
  String source, {
  String name = 'encoded',
  String version = '1.0.0',
  String Function(String uri)? partResolver,
}) {
  _prefixToModule.clear();
  _importedModules.clear();
  _usedBaseFunctions.clear();
  _usedCollectionsFunctions.clear();
  _usedProtoFunctions.clear();
  _usedConvertFunctions.clear();
  _importDetails.clear();
  _exportDetails.clear();
  _partDetails.clear();
  _partOfUri = null;
  _tempVarCounter = 0;
  warnings.clear();
  // The encoded output always uses a single module named 'main'.
  _moduleName = 'main';

  final result = parseString(
    content: source,
    throwIfDiagnostics: false,
    featureSet: FeatureSet.latestLanguageVersion(),
  );
  final unit = result.unit;

  _resolveImports(unit);

  final partUnits = <ast.CompilationUnit>[];
  if (partResolver != null) {
    for (final directive in unit.directives) {
      if (directive is ast.PartDirective) {
        final uri = directive.uri.stringValue;
        if (uri == null) continue;
        final partSource = partResolver(uri);
        partUnits.add(
          parseString(
            content: partSource,
            throwIfDiagnostics: false,
            featureSet: FeatureSet.latestLanguageVersion(),
          ).unit,
        );
      }
    }
  }

  return _buildProgram(
    unit,
    name: name,
    version: version,
    partUnits: partUnits,
  );
}