#pragma once
#include "Thread.h"
#include "Value.h"
#include "Core/Set.h"

namespace storm {
	STORM_PKG(core.lang);

	class Named;
	class NameSet;
	class Function;

	/**
	 * An object encapsulating various state that is required while reloading code.
	 *
	 * More specifically:
	 * - An equivalence relation between new and old types.
	 */
	class ReplaceContext : public ObjectOn<Compiler> {
		STORM_CLASS;
	public:
		// Create.
		STORM_CTOR ReplaceContext();

		// Are the two types actually the same?
		Bool STORM_FN same(Type *a, Type *b);

		// Normalize types and/or values.
		Type *STORM_FN normalize(Type *t);
		Value STORM_FN normalize(Value v);

		// Add a type that is equivalent to another.
		void STORM_FN addEquivalence(Type *oldType, Type *newType);

		// Build the type equivalence from two NameSets.
		void STORM_FN buildTypeEquivalence(NameSet *oldRoot, NameSet *newRoot);

		// Get all new types in here.
		Set<Type *> *STORM_FN allNewTypes();

	private:
		// Equivalence relation of types (new type -> old type).
		Map<Type *, Type *> *typeEq;

		// Current old root used when building a type equivalence. Used as an indicator for that situation.
		MAYBE(NameSet *) currentOldRoot;

		// Recursive helper for building 'typeEq'.
		void buildTypeEqRec(NameSet *currOld, NameSet *currNew);

		// Resolve parameters during type equivalence.
		Array<Value> *resolveParams(NameSet *root, Array<Value> *params);
		Value resolveParam(NameSet *root, Value param);
	};

}
