shallowCopyFiltered method

Environment shallowCopyFiltered({
  1. Set<String>? showNames,
  2. Set<String>? hideNames,
})

Creates a shallow copy of this environment, optionally filtering symbols.

If showNames is provided, only symbols (values, bridged classes, enums, prefixed imports) whose names are in showNames will be included in the new environment. If hideNames is provided, all symbols will be included except those whose names are in hideNames.

It is an error to provide both showNames and hideNames. Unnamed extensions are always copied.

Implementation

Environment shallowCopyFiltered({
  Set<String>? showNames,
  Set<String>? hideNames,
}) {
  if (showNames != null && hideNames != null) {
    throw ArgumentD4rtException(
      'Cannot provide both showNames and hideNames to shallowCopyFiltered.',
    );
  }

  final newEnv = Environment(enclosing: _enclosing);

  // Filter _values
  _values.forEach((name, value) {
    bool include = true;
    if (showNames != null) {
      include = showNames.contains(name);
    } else if (hideNames != null) {
      include = !hideNames.contains(name);
    }
    if (include) {
      newEnv._values[name] = value;
    }
  });

  // Filter _bridgedClasses and rebuild _bridgedClassesLookupByType
  _bridgedClasses.forEach((name, bridgedClass) {
    bool include = true;
    if (showNames != null) {
      include = showNames.contains(name);
    } else if (hideNames != null) {
      include = !hideNames.contains(name);
    }
    if (include) {
      newEnv._bridgedClassesOrNew[name] = bridgedClass;
      newEnv._bridgedClassesLookupByTypeOrNew[bridgedClass.nativeType] =
          bridgedClass;
    }
  });

  // Filter _bridgedEnums
  _bridgedEnums.forEach((name, bridgedEnum) {
    bool include = true;
    if (showNames != null) {
      include = showNames.contains(name);
    } else if (hideNames != null) {
      include = !hideNames.contains(name);
    }
    if (include) {
      newEnv._bridgedEnumsOrNew[name] = bridgedEnum;
    }
  });

  // Filter _prefixedImports
  _prefixedImports.forEach((name, environment) {
    bool include = true;
    if (showNames != null) {
      include = showNames.contains(name);
    } else if (hideNames != null) {
      include = !hideNames.contains(name);
    }
    if (include) {
      newEnv._prefixedImportsOrNew[name] =
          environment; // Copy the reference to the prefixed environment
    }
  });

  // Copy unnamed extensions (cannot be filtered by name)
  newEnv._unnamedExtensionsOrNew.addAll(_unnamedExtensions);

  Logger.debug(
    "[Environment.shallowCopyFiltered] Created filtered environment. Original size: ${_values.length} values. New size: ${newEnv._values.length} values.",
  );
  return newEnv;
}