// file      : build/rule -*- C++ -*-
// copyright : Copyright (c) 2014-2015 Code Synthesis Tools CC
// license   : MIT; see accompanying LICENSE file

#ifndef BUILD_RULE
#define BUILD_RULE

#include <string>
#include <typeindex>
#include <functional>     // reference_wrapper
#include <unordered_map>

#include <build/target>
#include <build/operation>
#include <build/prefix-map>

namespace build
{
  class rule
  {
  public:
    virtual void*
    match (action, target&, const std::string& hint) const = 0;

    virtual recipe
    apply (action, target&, void*) const = 0;
  };

  using target_rule_map = std::unordered_map<
    std::type_index,
    prefix_multimap<std::string, std::reference_wrapper<rule>, '.'>>;

  using operation_rule_map = std::unordered_map<operation_id, target_rule_map>;

  extern operation_rule_map rules;

  // Fallback rule that on update verifies that the path exists and is
  // not older than any of its prerequisites.
  //
  class path_rule: public rule
  {
  public:
    virtual void*
    match (action, target&, const std::string& hint) const;

    virtual recipe
    apply (action, target&, void*) const;

    static target_state
    perform_update (action, target&);
  };

  class dir_rule: public rule
  {
  public:
    virtual void*
    match (action, target&, const std::string& hint) const;

    virtual recipe
    apply (action, target&, void*) const;
  };

  class fsdir_rule: public rule
  {
  public:
    virtual void*
    match (action, target&, const std::string& hint) const;

    virtual recipe
    apply (action, target&, void*) const;

    static target_state
    perform_update (action, target&);

    static target_state
    perform_clean (action, target&);
  };
}

#endif // BUILD_RULE