// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef BASE_FEATURE_LIST_H_
#define BASE_FEATURE_LIST_H_

#include <compare>
#include <functional>
#include <map>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

#include "base/base_export.h"
#include "base/compiler_specific.h"
#include "base/containers/flat_map.h"
#include "base/containers/flat_set.h"
#include "base/dcheck_is_on.h"
#include "base/feature.h"
#include "base/functional/callback_forward.h"
#include "base/gtest_prod_util.h"
#include "base/memory/raw_ptr.h"
#include "base/metrics/field_trial_params.h"
#include "base/sequence_checker.h"
#include "base/synchronization/lock.h"
#include "base/types/pass_key.h"
#include "build/build_config.h"

namespace variations {
class VariationsService;
}  // namespace variations

namespace metrics {
class RuntimeMutableFeaturesHandlerBase;
}

namespace base {

class FieldTrial;
class FieldTrialList;
class PersistentMemoryAllocator;
class FeatureVisitor;

namespace internal {
struct RuntimeMutableFeatureState;
}  // namespace internal

#if BUILDFLAG(DCHECK_IS_CONFIGURABLE)
// DCHECKs have been built-in, and are configurable at run-time to be fatal, or
// not, via a DcheckIsFatal feature. We define the Feature here since it is
// checked in FeatureList::SetInstance(). See https://crbug.com/596231.
BASE_EXPORT BASE_DECLARE_FEATURE(kDCheckIsFatalFeature);
#endif  // BUILDFLAG(DCHECK_IS_CONFIGURABLE)

// The FeatureList class is used to determine whether a given feature is on or
// off. It provides an authoritative answer, taking into account command-line
// overrides and experimental control.
//
// The basic use case is for any feature that can be toggled (e.g. through
// command-line or an experiment) to have a defined Feature struct, e.g.:
//
//   const base::Feature kMyGreatFeature {
//     "MyGreatFeature", base::FEATURE_ENABLED_BY_DEFAULT
//   };
//
// Then, client code that wishes to query the state of the feature would check:
//
//   if (base::FeatureList::IsEnabled(kMyGreatFeature)) {
//     // Feature code goes here.
//   }
//
// Behind the scenes, the above call would take into account any command-line
// flags to enable or disable the feature, any experiments that may control it
// and finally its default state (in that order of priority), to determine
// whether the feature is on.
//
// Features can be explicitly forced on or off by specifying a list of comma-
// separated feature names via the following command-line flags:
//
//   --enable-features=Feature5,Feature7
//   --disable-features=Feature1,Feature2,Feature3
//
// To enable/disable features in a test, do NOT append --enable-features or
// --disable-features to the command-line directly. Instead, use
// ScopedFeatureList. See base/test/scoped_feature_list.h for details.
//
// After initialization (which should be done single-threaded), the FeatureList
// API is thread safe.
//
// Note: This class is a singleton, but does not use base/memory/singleton.h in
// order to have control over its initialization sequence. Specifically, the
// intended use is to create an instance of this class and fully initialize it,
// before setting it as the singleton for a process, via SetInstance().
class BASE_EXPORT FeatureList {
 public:
  FeatureList();
  FeatureList(const FeatureList&) = delete;
  FeatureList& operator=(const FeatureList&) = delete;
  ~FeatureList();

  // Used by common test fixture classes to prevent abuse of ScopedFeatureList
  // after multiple threads have started.
  class BASE_EXPORT ScopedDisallowOverrides {
   public:
    explicit ScopedDisallowOverrides(const char* reason);
    ScopedDisallowOverrides(const ScopedDisallowOverrides&) = delete;
    ScopedDisallowOverrides& operator=(const ScopedDisallowOverrides&) = delete;
    ~ScopedDisallowOverrides();

   private:
#if DCHECK_IS_ON()
    const char* const previous_reason_;
#endif
  };

  // Specifies whether a feature override enables or disables the feature.
  enum OverrideState : uint32_t {
    OVERRIDE_USE_DEFAULT,
    OVERRIDE_DISABLE_FEATURE,
    OVERRIDE_ENABLE_FEATURE,
  };

  // Accessor class, used to look up features by _name_ rather than by Feature
  // object.
  // Should only be used in limited cases. See ConstructAccessor() for details.
  class BASE_EXPORT Accessor {
   public:
    Accessor(const Accessor&) = delete;
    Accessor& operator=(const Accessor&) = delete;

    // Looks up the feature, returning only its override state, rather than
    // falling back on a default value (since there is no default value given).
    // Callers of this MUST ensure that there is a consistent, compile-time
    // default value associated.
    FeatureList::OverrideState GetOverrideStateByFeatureName(
        std::string_view feature_name);

    // Look up the feature, and, if present, populate |params|.
    // See GetFieldTrialParams in field_trial_params.h for more documentation.
    bool GetParamsByFeatureName(std::string_view feature_name,
                                FieldTrialParams* params);

   private:
    // Allow FeatureList to construct this class.
    friend class FeatureList;

    explicit Accessor(FeatureList* feature_list);

    // Unowned pointer to the FeatureList object we use to look up feature
    // enablement.
    raw_ptr<FeatureList, DanglingUntriaged> feature_list_;
  };

  // Describes a feature override. The first member is a Feature that will be
  // overridden with the state given by the second member.
  using FeatureOverrideInfo =
      std::pair<const std::reference_wrapper<const Feature>, OverrideState>;

  // Describes information about the trial controlling a feature's state.
  struct ControllingTrialInfo {
    // Name of the trial controlling the feature. Empty string if the feature is
    // not being controlled by any trial.
    std::string trial_name;
    // Whether this trial is a runtime override or not. Defaults to false if
    // the feature is not being controlled by any trial.
    bool is_runtime_override = false;

    friend auto operator<=>(const ControllingTrialInfo&,
                            const ControllingTrialInfo&) = default;
  };

  // Callback to be invoked when a runtime mutable feature's OverrideState
  // changes at runtime.
  using OnRuntimeMutableFeatureStateChangedCallback =
      base::RepeatingCallback<void(
          std::reference_wrapper<const Feature> /*feature*/,
          std::string_view /*field_trial_name*/,
          std::string_view /*group_name*/,
          OverrideState /*override_state*/)>;

  // Encapsulates the 3-phase execution of updating a runtime mutable feature's
  // state (pre-mutation callback, state update, post-mutation callback).
  //
  // Callers are responsible for invoking `RunPreMutationCallback()`,
  // `UpdateState()`, and `RunPostMutationCallback()` in that exact order.
  // CHECKs enforce that all phases are called in order and complete before
  // destruction.
  class BASE_EXPORT [[nodiscard]] RuntimeMutableFeatureUpdate {
   public:
    enum class Stage {
      kInitial,
      kPreMutationRun,
      kStateUpdated,
      kPostMutationRun,
      kMovedFrom,
    };

    RuntimeMutableFeatureUpdate(RuntimeMutableFeatureUpdate&& other) noexcept;
    RuntimeMutableFeatureUpdate& operator=(
        RuntimeMutableFeatureUpdate&& other) noexcept;

    RuntimeMutableFeatureUpdate(const RuntimeMutableFeatureUpdate&) = delete;
    RuntimeMutableFeatureUpdate& operator=(const RuntimeMutableFeatureUpdate&) =
        delete;

    ~RuntimeMutableFeatureUpdate();

    // Runs the pre-mutation callback (if any was registered). Must be called
    // first.
    void RunPreMutationCallback();

    // Updates the feature's override state and associated field trial name.
    // Must be called after `RunPreMutationCallback()`.
    void UpdateState();

    // Runs the post-mutation callback (if any was registered). Must be called
    // after `UpdateState()`.
    void RunPostMutationCallback();

   private:
    friend class FeatureList;

    RuntimeMutableFeatureUpdate(
        internal::RuntimeMutableFeatureState& state_entry,
        std::string_view field_trial_name,
        std::string_view group_name,
        OverrideState override_state);

    raw_ptr<internal::RuntimeMutableFeatureState> state_entry_ = nullptr;
    std::string field_trial_name_;
    std::string group_name_;
    OverrideState override_state_ = OVERRIDE_USE_DEFAULT;
    Stage stage_ = Stage::kInitial;
  };

  // Initializes feature overrides via command-line flags `--enable-features=`
  // and `--disable-features=`, each of which is a comma-separated list of
  // features to enable or disable, respectively. This function also allows
  // users to set a feature's field trial params via `--enable-features=`. Must
  // only be invoked during the initialization phase (before
  // FinalizeInitialization() has been called).
  //
  // If a feature appears on both lists, then it will be disabled. If
  // a list entry has the format "FeatureName<TrialName" then this
  // initialization will also associate the feature state override with the
  // named field trial, if it exists. If a list entry has the format
  // "FeatureName:k1/v1/k2/v2", "FeatureName<TrialName:k1/v1/k2/v2" or
  // "FeatureName<TrialName.GroupName:k1/v1/k2/v2" then this initialization will
  // also associate the feature state override with the named field trial and
  // its params. If the feature params part is provided but trial and/or group
  // isn't, this initialization will also create a synthetic trial, named
  // "Study" followed by the feature name, i.e. "StudyFeature", and group, named
  // "Group" followed by the feature name, i.e. "GroupFeature", for the params.
  // If a feature name is prefixed with the '*' character, it will be created
  // with OVERRIDE_USE_DEFAULT - which is useful for associating with a trial
  // while using the default state.
  void InitFromCommandLine(const std::string& enable_features,
                           const std::string& disable_features);

  // Initializes feature overrides through the field trial allocator, which
  // we're using to store the feature names, their override state, and the name
  // of the associated field trial.
  void InitFromSharedMemory(PersistentMemoryAllocator* allocator);

  // Sets the `variation_country` that is used to determine whether
  // default-enabled features with country restrictions are enabled.
  void SetVariationCountry(std::string_view variation_country);

  // Enables runtime mutability for the given `feature` and registers the given
  // callbacks to be invoked when the feature's state changes at runtime.
  // `pre_mutation_callback` is invoked right before the feature's state
  // is about to change, and `post_mutation_callback` is invoked right after the
  // feature's state has changed.
  //
  // This method should only be called once per feature and *MUST* be
  // called before attempting to inspect the feature state of a runtime mutable
  // feature (i.e. calling `IsEnabled()` or looking up a FeatureParam value).
  //
  // This method may only be called during FeatureList initialization and on
  // the main sequence. Implementers of runtime-mutable features should update
  // the PlatformFieldTrials::RegisterRuntimeMutableFeatures() override for
  // their platform(s) to call this method for their runtime-mutable feature(s).
  void EnableRuntimeMutability(
      const Feature& feature,
      OnRuntimeMutableFeatureStateChangedCallback pre_mutation_callback,
      OnRuntimeMutableFeatureStateChangedCallback post_mutation_callback);
  // Convenience method for the above when only a post-mutation callback is
  // needed.
  void EnableRuntimeMutability(
      const Feature& feature,
      OnRuntimeMutableFeatureStateChangedCallback post_mutation_callback);

  // Returns the set of runtime mutable features and their current state.
  // Must be called on the main sequence.
  const base::flat_map<std::string, internal::RuntimeMutableFeatureState>&
  GetRuntimeMutableFeatureState(
      PassKey<metrics::RuntimeMutableFeaturesHandlerBase> pass_key) const;

  // Returns the override state for |feature|, without activating any associated
  // field trial.
  // Must be called on the main sequence.
  OverrideState GetOverrideStateWithoutActivation(
      const Feature& feature,
      PassKey<metrics::RuntimeMutableFeaturesHandlerBase> pass_key) const;

  // Returns true if the state of |feature_name| has been overridden (regardless
  // of whether the overridden value is the same as the default value) for any
  // reason (e.g. command line or field trial). Note: This will return true even
  // when a feature is overridden with OVERRIDE_USE_DEFAULT (default group).
  bool IsFeatureOverridden(std::string_view feature_name) const;

  // Returns true if the state of |feature_name| has been overridden via
  // |InitFromCommandLine()|. This includes features explicitly
  // disabled/enabled with --disable-features and --enable-features, as well as
  // any extra feature overrides that depend on command line switches.
  bool IsFeatureOverriddenFromCommandLine(std::string_view feature_name) const;

  // Returns true if the state |feature_name| has been overridden by
  // |InitFromCommandLine()| and the state matches |state|.
  bool IsFeatureOverriddenFromCommandLine(std::string_view feature_name,
                                          OverrideState state) const;

  // Associates a field trial for reporting purposes corresponding to the
  // command-line setting the feature state to |for_overridden_state|. The trial
  // will be activated when the state of the feature is first queried. This
  // should be called during registration, after InitFromCommandLine() has
  // been called but before the instance is registered via SetInstance().
  void AssociateReportingFieldTrial(const std::string& feature_name,
                                    OverrideState for_overridden_state,
                                    FieldTrial* field_trial);

  // Registers a field trial to override the enabled state of the specified
  // feature to `override_state`. Command-line overrides still take precedence
  // over field trials, so this will have no effect if the feature is being
  // overridden from the command-line. The associated field trial will be
  // activated when the feature state for this feature is queried. This should
  // be called during registration, after InitFromCommandLine() has been
  // called but before the instance is registered via SetInstance().
  void RegisterFieldTrialOverride(const std::string& feature_name,
                                  OverrideState override_state,
                                  FieldTrial* field_trial);

  // Prepares an update for the state of a runtime mutable feature.
  //
  // This method can only be called from the main sequence and is intended to
  // only be called by the field trials framework when the state of a runtime
  // mutable feature needs to be updated.
  //
  // Returns a RuntimeMutableFeatureUpdate object if the feature state update
  // was prepared successfully, or std::nullopt otherwise.
  //
  // The caller is responsible for invoking `RunPreMutationCallback()`,
  // `UpdateState()`, and `RunPostMutationCallback()` in order on the returned
  // update object.
  [[nodiscard]] std::optional<RuntimeMutableFeatureUpdate>
  PrepareRuntimeMutableFeatureStateUpdate(
      base::PassKey<variations::VariationsService>,
      std::string_view field_trial_name,
      std::string_view group_name,
      std::string_view feature_name,
      OverrideState override_state);

  // Returns whether the feature with the given `feature_name` has runtime
  // mutability enabled.
  bool HasRuntimeMutabilityEnabledByFeatureName(
      std::string_view feature_name) const;

  // Returns the name of the runtime FieldTrial override associated with the
  // given runtime-mutability-enabled `feature_name`. Returns an empty string
  // if there is currently no override.
  std::string_view GetAssociatedRuntimeFieldTrialOverrideByFeatureName(
      std::string_view feature_name) const;

  // Returns information about the field trial controlling or associated with
  // the given `feature_name`. If the feature has runtime mutability enabled and
  // has an active runtime override, returns the runtime override trial name and
  // sets `is_runtime_override` to true. Otherwise returns the associated field
  // trial name (if any) and `is_runtime_override` set to false. If no trial is
  // associated with the feature, `trial_name` will be empty. Must be called on
  // the main sequence.
  ControllingTrialInfo GetControllingTrialInfoByFeatureName(
      std::string_view feature_name) const;

  // Returns the names of all features associated with the field trial described
  // by `controlling_trial_info`.
  base::flat_set<std::string> GetFeaturesAssociatedWithTrial(
      const ControllingTrialInfo& controlling_trial_info) const;

  // Adds extra overrides (not associated with a field trial). Should be called
  // before SetInstance().
  // The ordering of calls with respect to InitFromCommandLine(),
  // RegisterFieldTrialOverride(), etc. matters. The first call wins out,
  // because the `overrides_` map uses emplace(), which retains the first
  // inserted entry and does not overwrite it on subsequent calls to emplace().
  //
  // If `replace_use_default_overrides` is true, if there is an existing entry
  // with type OVERRIDE_USE_DEFAULT, that entry will be replaced.
  void RegisterExtraFeatureOverrides(
      const std::vector<FeatureOverrideInfo>& extra_overrides,
      bool replace_use_default_overrides = false);

  // Loops through feature overrides and serializes them all into |allocator|.
  void AddFeaturesToAllocator(PersistentMemoryAllocator* allocator);

  // Returns comma-separated lists of feature names (in the same format that is
  // accepted by InitFromCommandLine()) corresponding to features that
  // have been overridden - either through command-line or via FieldTrials. For
  // those features that have an associated FieldTrial, the output entry will be
  // of the format "FeatureName<TrialName" (|include_group_name|=false) or
  // "FeatureName<TrialName.GroupName" (if |include_group_name|=true), where
  // "TrialName" is the name of the FieldTrial and "GroupName" is the group
  // name of the FieldTrial. Features that have overrides with
  // OVERRIDE_USE_DEFAULT will be added to |enable_overrides| with a '*'
  // character prefix. Must be called only after the instance has been
  // initialized and registered.
  void GetFeatureOverrides(std::string* enable_overrides,
                           std::string* disable_overrides,
                           bool include_group_names = false) const;

  // Like GetFeatureOverrides(), but only returns overrides that were specified
  // explicitly on the command-line, omitting the ones from field trials.
  void GetCommandLineFeatureOverrides(std::string* enable_overrides,
                                      std::string* disable_overrides) const;

  // Returns the field trial associated with the given feature |name|. Used for
  // getting the FieldTrial without requiring a struct Feature. For
  // runtime mutable features, this does not return the override trial, but
  // rather the "original" trial associated with the feature.
  base::FieldTrial* GetAssociatedFieldTrialByFeatureName(
      std::string_view name) const;

  // DO NOT USE outside of internal field trial implementation code. Instead use
  // GetAssociatedFieldTrialByFeatureName(), which performs some additional
  // validation.
  //
  // Returns whether the given feature |name| is associated with a field trial.
  // If the given feature |name| does not exist, return false. Unlike
  // GetAssociatedFieldTrialByFeatureName(), this function must be called during
  // |FeatureList| initialization; the returned value will report whether the
  // provided |name| has been used so far.
  bool HasAssociatedFieldTrialByFeatureName(std::string_view name) const;

  // Get associated field trial for the given feature |name| only if override
  // enables it.
  FieldTrial* GetEnabledFieldTrialByFeatureName(std::string_view name) const;

  // Construct an accessor allowing access to GetOverrideStateByFeatureName().
  // This can only be called before the FeatureList is initialized, and is
  // intended for very narrow use.
  // If you're tempted to use it, do so only in consultation with feature_list
  // OWNERS.
  std::unique_ptr<Accessor> ConstructAccessor();

  // Returns whether the given `feature` is enabled.
  //
  // If no `FeatureList` instance is registered, this will:
  // - DCHECK(), if FailOnFeatureAccessWithoutFeatureList() was called.
  //     TODO(crbug.com/40237050): Change the DCHECK to a CHECK when we're
  //     confident that all early accesses have been fixed. We don't want to
  //     get many crash reports from the field in the meantime.
  // - Return the default state, otherwise. Registering a `FeatureList` later
  //   will fail.
  //
  // TODO(crbug.com/40237050): Make early FeatureList access fail on iOS,
  // Android and ChromeOS. This currently only works on Windows, Mac and Linux.
  //
  // A feature with a given name must only have a single corresponding Feature
  // instance, which is checked in builds with DCHECKs enabled.
  //
  // For a feature defined as BASE_RUNTIME_MUTABLE_FEATURE, its enabled state
  // may only be queried from the main thread. Features defined as BASE_FEATURE
  // are effectively constants, and can be queried from any thread.
  static bool IsEnabled(const Feature& feature);

  // Some characters are not allowed to appear in feature names or the
  // associated field trial names, as they are used as special characters for
  // command-line serialization. This function checks that the strings are ASCII
  // (since they are used in command-line API functions that require ASCII) and
  // whether there are any reserved characters present, returning true if the
  // string is valid.
  static bool IsValidFeatureOrFieldTrialName(std::string_view name);

  // If the given |feature| is overridden, returns its enabled state; otherwise,
  // returns an empty optional. Must only be called after the singleton instance
  // has been registered via SetInstance(). Additionally, a feature with a given
  // name must only have a single corresponding Feature struct, which is checked
  // in builds with DCHECKs enabled.
  static std::optional<bool> GetStateIfOverridden(const Feature& feature);

  // Returns the field trial associated with the given |feature|. Must only be
  // called after the singleton instance has been registered via SetInstance().
  static FieldTrial* GetFieldTrial(const Feature& feature);

  // Splits a comma-separated string containing feature names into a vector. The
  // resulting pieces point to parts of |input|.
  static std::vector<std::string_view> SplitFeatureListString(
      std::string_view input);

  // Checks and parses the |enable_feature| (e.g.
  // FeatureName<Study.Group:param1/value1/) obtained by applying
  // SplitFeatureListString() to the |enable_features| flag, and sets
  // |feature_name| to be the feature's name, |study_name| and |group_name| to
  // be the field trial name and its group name if the field trial is specified
  // or field trial parameters are given, |params| to be the field trial
  // parameters if exists.
  static bool ParseEnableFeatureString(std::string_view enable_feature,
                                       std::string* feature_name,
                                       std::string* study_name,
                                       std::string* group_name,
                                       std::string* params);

  // Initializes and sets an instance of FeatureList with feature overrides via
  // command-line flags |enable_features| and |disable_features| if one has not
  // already been set from command-line flags. Returns true if an instance did
  // not previously exist. See InitFromCommandLine() for more details
  // about |enable_features| and |disable_features| parameters.
  static bool InitInstance(const std::string& enable_features,
                           const std::string& disable_features);

  // Like the above, but also adds extra overrides. If a feature appears in
  // |extra_overrides| and also |enable_features| or |disable_features|, the
  // disable/enable will supersede the extra overrides.
  static bool InitInstance(
      const std::string& enable_features,
      const std::string& disable_features,
      const std::vector<FeatureOverrideInfo>& extra_overrides);

  // Returns the singleton instance of FeatureList. Will return null until an
  // instance is registered via SetInstance().
  static FeatureList* GetInstance();

  // Registers the given |instance| to be the singleton feature list for this
  // process. This should only be called once and |instance| must not be null.
  // Note: If you are considering using this for the purposes of testing, take
  // a look at using base/test/scoped_feature_list.h instead.
  static void SetInstance(std::unique_ptr<FeatureList> instance);

  // Registers the given `instance` to be the temporary singleton feature list
  // for this process. While the given `instance` is the singleton feature list,
  // only the state of features matching `allowed_feature_names` can be checked.
  // Attempting to query other feature will behave as if no feature list was set
  // at all. It is expected that this instance is replaced using `SetInstance`
  // with an instance without limitations as soon as practical.
  static void SetEarlyAccessInstance(
      std::unique_ptr<FeatureList> instance,
      base::flat_set<std::string> allowed_feature_names);

  // Clears the previously-registered singleton instance for tests and returns
  // the old instance.
  // Note: Most tests should never call this directly. Instead consider using
  // base::test::ScopedFeatureList.
  static std::unique_ptr<FeatureList> ClearInstanceForTesting();

  // Sets a given (initialized) |instance| to be the singleton feature list,
  // for testing. Existing instance must be null. This is primarily intended
  // to support base::test::ScopedFeatureList helper class.
  static void RestoreInstanceForTesting(std::unique_ptr<FeatureList> instance);

  // After calling this, an attempt to access feature state when no FeatureList
  // is registered will DCHECK.
  //
  // TODO(crbug.com/40237050): Change the DCHECK to a CHECK when we're confident
  // that all early accesses have been fixed. We don't want to get many crash
  // reports from the field in the meantime.
  //
  // Note: This isn't the default behavior because accesses are tolerated in
  // processes that never register a FeatureList.
  static void FailOnFeatureAccessWithoutFeatureList();

  // Returns the first feature that was accessed before a FeatureList was
  // registered that allows accessing the feature.
  static const Feature* GetEarlyAccessedFeatureForTesting();

  // Resets the state of the early feature access tracker.
  static void ResetEarlyFeatureAccessTrackerForTesting();

  // Adds a feature to the early allowed feature access list for tests. Should
  // only be called on a FeatureList that was set with SetEarlyAccessInstance().
  void AddEarlyAllowedFeatureForTesting(std::string feature_name);

  // Clears the cached value of the given feature.
  static void ClearFeatureCachedValueForTesting(const Feature& feature);

  // Returns true if runtime mutability is enabled for the given feature.
  bool IsRuntimeMutabilityEnabledForTesting(const Feature& feature) const;

  // Allows a visitor to record override state, parameters, and field trial
  // associated with each feature. Optionally, provide a prefix which filters
  // the visited features.
  //
  // NOTE: This is intended only for the special case of needing to get all
  // overrides. This use case is specific to CrOS-Ash and V8. Most users should
  // call IsEnabled() to query a feature's state.
  static void VisitFeaturesAndParams(FeatureVisitor& visitor,
                                     std::string_view filter_prefix = "");

 private:
  FRIEND_TEST_ALL_PREFIXES(FeatureListTest, CheckFeatureIdentity);
  FRIEND_TEST_ALL_PREFIXES(FeatureListTest,
                           StoreAndRetrieveFeaturesFromSharedMemory);
  FRIEND_TEST_ALL_PREFIXES(FeatureListTest,
                           StoreAndRetrieveAssociatedFeaturesFromSharedMemory);
  FRIEND_TEST_ALL_PREFIXES(FeatureListTest, FeatureParamBypassCache);

  // Allow Accessor to access GetOverrideStateByFeatureName().
  friend class Accessor;

  struct OverrideEntry {
    // The overridden enable (on/off) state of the feature.
    OverrideState overridden_state;

    // An optional associated field trial, which will be activated when the
    // state of the feature is queried for the first time. Weak pointer to the
    // FieldTrial object that is owned by the FieldTrialList singleton.
    raw_ptr<base::FieldTrial> field_trial;

    // Specifies whether the feature's state is overridden by |field_trial|.
    // If it's not, and |field_trial| is not null, it means it is simply an
    // associated field trial for reporting purposes (and |overridden_state|
    // came from the command-line).
    bool overridden_by_field_trial;

    // TODO(asvitkine): Expand this as more support is added.

    // Constructs an OverrideEntry for the given |overridden_state|. If
    // |field_trial| is not null, it implies that |overridden_state| comes from
    // the trial, so |overridden_by_field_trial| will be set to true.
    OverrideEntry(OverrideState overridden_state, FieldTrial* field_trial);
  };

  // Registers the feature access to the appropriate histograms.
  static void RegisterFeatureAccess(const Feature& feature,
                                    Feature::FeatureStateCache logging_mask);

  // Returns the override for the field trial associated with the given feature
  // |name| or null if the feature is not found.
  const OverrideEntry* GetOverrideEntryByFeatureName(
      std::string_view name) const;

  // Finalizes the initialization state of the FeatureList, so that no further
  // overrides can be registered. This is called by SetInstance() on the
  // singleton feature list that is being registered.
  void FinalizeInitialization();

  // Returns whether the given |feature| is enabled. This is invoked by the
  // public FeatureList::IsEnabled() static function on the global singleton.
  // Requires the FeatureList to have already been fully initialized.
  bool IsFeatureEnabled(const Feature& feature) const;

  // Returns whether the given |feature| is enabled. This is invoked by the
  // public FeatureList::GetStateIfOverridden() static function on the global
  // singleton. Requires the FeatureList to have already been fully initialized.
  std::optional<bool> IsFeatureEnabledIfOverridden(
      const Feature& feature) const;

  // Returns the override state for |feature|. If the feature is not overridden,
  // returns OVERRIDE_USE_DEFAULT. Performs any necessary callbacks for when the
  // feature state has been observed, e.g. activating field trials.
  //
  // If |feature| is runtime-mutable, this method must be called from the main
  // sequence.
  OverrideState GetOverrideState(const Feature& feature) const;

  // Common implementation for GetOverrideState.
  OverrideState GetOverrideStateImpl(const Feature& feature,
                                     bool activate_trial) const;

  // Returns the runtime override state for |feature| if it is runtime-mutable
  // and a runtime override has been set. Otherwise returns std::nullopt.
  std::optional<OverrideState> MaybeGetRuntimeOverrideState(
      const Feature& feature,
      Feature::FeatureStateCache current_cached_value) const;

  // Returns the non-runtime override state for the given |feature_name|,
  // without falling back to any default state associated with the feature.
  //
  // TODO: http://crbug.com/482450776 - This function is used for non-runtime-
  // mutable features and runtime-mutable features that have not yet had a
  // runtime-mutable override applied. We should consider removing the by-name
  // lookup for non-runtime-mutable features to simplify the logic and force all
  // clients to use the by-feature lookup, where the identity of the feature and
  // its runtime mutability state are checked.
  OverrideState GetOverrideStateByFeatureName(
      std::string_view feature_name) const;

  // Common implementation for GetOverrideStateByFeatureName.
  OverrideState GetOverrideStateByFeatureNameImpl(std::string_view feature_name,
                                                  bool activate_trial) const;

  // Returns the field trial associated with the given |feature|. This is
  // invoked by the public FeatureList::GetFieldTrial() static function on the
  // global singleton. Requires the FeatureList to have already been fully
  // initialized.
  base::FieldTrial* GetAssociatedFieldTrial(const Feature& feature) const;

  // For each feature name in comma-separated list of strings |feature_list|,
  // registers an override with the specified |overridden_state|. Also, will
  // associate an optional named field trial if the entry is of the format
  // "FeatureName<TrialName".
  void RegisterOverridesFromCommandLine(const std::string& feature_list,
                                        OverrideState overridden_state);

  // Registers an override for feature |feature_name|. The override specifies
  // whether the feature should be on or off (via |overridden_state|), which
  // will take precedence over the feature's default state. If |field_trial| is
  // not null, registers the specified field trial object to be associated with
  // the feature, which will activate the field trial when the feature state is
  // queried.
  //
  // If an override is already registered for the given feature, it will not be
  // changed, unless `replace_use_default_overrides` is true and the existing
  // entry has type OVERRIDE_USE_DEFAULT.
  void RegisterOverride(std::string_view feature_name,
                        OverrideState overridden_state,
                        FieldTrial* field_trial,
                        bool replace_use_default_overrides = false);

  // Implementation of GetFeatureOverrides() with a parameter that specifies
  // whether only command-line enabled overrides should be emitted. See that
  // function's comments for more details.
  void GetFeatureOverridesImpl(std::string* enable_overrides,
                               std::string* disable_overrides,
                               bool command_line_only,
                               bool include_group_name = false) const;

  // Verifies that there's only a single definition of a Feature struct for a
  // given feature name. Keeps track of the first seen Feature struct for each
  // feature. Returns false when called on a Feature struct with a different
  // address than the first one it saw for that feature name. Used only from
  // DCHECKs and tests. This is const because it's called from const getters and
  // doesn't modify externally visible state.
  bool CheckFeatureIdentity(const Feature& feature) const;

  // Returns true if this feature list was set with SetEarlyAccessInstance().
  bool IsEarlyAccessInstance() const;

  // Returns if this feature list instance allows access to the given feature.
  // If a this feature list was set with SetEarlyAccessInstance(), only the
  // features in `allowed_feature_names_` can be checked.
  bool AllowFeatureAccess(const Feature& feature) const;

  // Map from feature name to an OverrideEntry struct for the feature, if it
  // exists. These overrides are logically const after initialization.
  base::flat_map<std::string, OverrideEntry> overrides_;

  // Map from feature name to the state of the feature, if it is a runtime
  // mutable feature and has been enabled for runtime mutability.
  base::flat_map<std::string, internal::RuntimeMutableFeatureState>
      runtime_mutable_overrides_ GUARDED_BY_CONTEXT(sequence_checker_);

  // Locked map that keeps track of seen features, to ensure a single feature is
  // only defined once. This verification is only done in builds with DCHECKs
  // enabled. This is mutable as it's not externally visible and needs to be
  // usable from const getters.
  mutable Lock feature_identity_tracker_lock_;
  mutable std::map<std::string, const Feature*, std::less<>>
      feature_identity_tracker_ GUARDED_BY(feature_identity_tracker_lock_);

  // Tracks the associated FieldTrialList for DCHECKs. This is used to catch
  // the scenario where multiple FieldTrialList are used with the same
  // FeatureList - which can lead to overrides pointing to invalid FieldTrial
  // objects.
  raw_ptr<base::FieldTrialList> field_trial_list_ = nullptr;

  // Whether this object has been fully initialized. This gets set to true as a
  // result of FinalizeInitialization().
  bool initialized_ = false;

  // Whether this object has been initialized from command line.
  bool initialized_from_command_line_ = false;

  // Used when querying `base::Feature` state to determine if the cached value
  // in the `Feature` object is populated and valid. See the comment on
  // `base::Feature::cached_value` for more details.
  const uint16_t caching_context_;

  // If this instance was set with SetEarlyAccessInstance(), this set contains
  // the names of the features whose state is allowed to be checked. Attempting
  // to check the state of a feature not on this list will behave as if no
  // feature list was initialized at all.
  base::flat_set<std::string> allowed_feature_names_;

  // Used when querying `base::Feature` state to determine whether a
  // default-enabled feature with country restrictions is enabled. Set via
  // `SetVariationCountry()` during initialization.
  std::string variation_country_;

  // Sequence checker for the main thread/sequence, used to ensure that runtime
  // mutable features are only accessed on the main thread.
  SEQUENCE_CHECKER(sequence_checker_);
};

}  // namespace base

#endif  // BASE_FEATURE_LIST_H_
