//
// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
//
// The contents of this file are covered under the licence agreement in the
// file "LICENCE" distributed with Cforall.
//
// Decl.hpp --
//
// Author           : Aaron B. Moss
// Created On       : Thu May 9 10:00:00 2019
// Last Modified By : Aaron B. Moss
// Last Modified On : Thu May 9 10:00:00 2019
// Update Count     : 1
//

#pragma once

#include <string>              // for string, to_string
#include <unordered_map>
#include <vector>

#include "FunctionSpec.hpp"
#include "Fwd.hpp"             // for UniqueId
#include "LinkageSpec.hpp"
#include "Node.hpp"            // for ptr, readonly
#include "ParseNode.hpp"
#include "StorageClasses.hpp"
#include "TypeVar.hpp"
#include "Visitor.hpp"
#include "Parser/ParseNode.h"  // for DeclarationNode::Aggregate

namespace ast {

class Attribute;
class Expr;
class Init;
class TypeDecl;

/// Base declaration class
class Decl : public ParseNode {
public:
	std::string name;
	Storage::Classes storage;
	Linkage::Spec linkage;
	UniqueId uniqueId = 0;
	bool extension = false;

	Decl( const CodeLocation& loc, const std::string& name, Storage::Classes storage,
		Linkage::Spec linkage )
	: ParseNode( loc ), name( name ), storage( storage ), linkage( linkage ) {}

	Decl* set_extension( bool ex ) { extension = ex; return this; }

	/// Ensures this node has a unique ID
	void fixUniqueId();
	/// Get canonical declaration for unique ID
	static readonly<Decl> fromId( UniqueId id );

	const Decl * accept( Visitor & v ) const override = 0;
private:
	Decl * clone() const override = 0;
};

/// Typed declaration base class
class DeclWithType : public Decl {
public:
	/// Represents the type with all types and typedefs expanded.
	/// This field is generated by SymTab::Validate::Pass2
	std::string mangleName;
	/// Stores the scope level at which the variable was declared.
	/// Used to access shadowed identifiers.
	int scopeLevel = 0;

	std::vector<ptr<Attribute>> attributes;
	Function::Specs funcSpec;
	ptr<Expr> asmName;
	bool isDeleted = false;

	DeclWithType( const CodeLocation& loc, const std::string& name, Storage::Classes storage,
		Linkage::Spec linkage, std::vector<ptr<Attribute>>&& attrs, Function::Specs fs )
	: Decl( loc, name, storage, linkage ), mangleName(), attributes( std::move(attrs) ),
		funcSpec(fs), asmName() {}

	std::string scopedMangleName() const { return mangleName + "_" + std::to_string(scopeLevel); }

	/// Get type of this declaration. May be generated by subclass
	virtual const Type * get_type() const = 0;
	/// Set type of this declaration. May be verified by subclass
	virtual void set_type(Type *) = 0;

	const DeclWithType * accept( Visitor & v ) const override = 0;
private:
	DeclWithType * clone() const override = 0;
};

/// Object declaration `Foo foo = 42;`
class ObjectDecl final : public DeclWithType {
public:
	ptr<Type> type;
	ptr<Init> init;
	ptr<Expr> bitfieldWidth;

	ObjectDecl( const CodeLocation& loc, const std::string& name, Type* type, Init* init = nullptr,
		Storage::Classes storage = {}, Linkage::Spec linkage = Linkage::C, Expr* bitWd = nullptr,
		std::vector<ptr<Attribute>>&& attrs = {}, Function::Specs fs = {})
	: DeclWithType( loc, name, storage, linkage, std::move(attrs), fs ), type( type ),
	  init( init ), bitfieldWidth( bitWd ) {}

	const Type* get_type() const override { return type; }
	void set_type( Type * ty ) override { type = ty; }

	const DeclWithType * accept( Visitor& v ) const override { return v.visit( this ); }
private:
	ObjectDecl * clone() const override { return new ObjectDecl{ *this }; }

	/// Must be copied in ALL derived classes
	template<typename node_t>
	friend auto mutate(const node_t * node);
};

class FunctionDecl : public DeclWithType {
public:
	ptr<FunctionType> type;
	ptr<CompoundStmt> stmts;
	std::list< ptr<Expr> > withExprs;

	FunctionDecl( const CodeLocation & loc, const std::string &name, FunctionType * type,
		CompoundStmt * stmts, Storage::Classes storage = {}, Linkage::Spec linkage = Linkage::C,
		std::vector<ptr<Attribute>>&& attrs = {}, Function::Specs fs = {})
	: DeclWithType( loc, name, storage, linkage, std::move(attrs), fs ), type( type ),
	  stmts( stmts ) {}

	const Type * get_type() const override { return type.get(); }
	void set_type(Type * t) override { type = strict_dynamic_cast< FunctionType* >( t ); }

	bool has_body() const { return stmts; }

	const DeclWithType * accept( Visitor &v ) const override { return v.visit( this ); }
private:
	FunctionDecl * clone() const override { return new FunctionDecl( *this ); }

	/// Must be copied in ALL derived classes
	template<typename node_t>
	friend auto mutate(const node_t * node);
};

/// Base class for named type aliases
class NamedTypeDecl : public Decl {
public:
	ptr<Type> base;
	std::vector<ptr<TypeDecl>> parameters;
	std::vector<ptr<DeclWithType>> assertions;

	NamedTypeDecl( const CodeLocation& loc, const std::string& name, Storage::Classes storage,
		Type* b, Linkage::Spec spec = Linkage::Cforall )
	: Decl( loc, name, storage, spec ), base( b ), parameters(), assertions() {}

	/// Produces a name for the kind of alias
	virtual std::string typeString() const = 0;

private:
	NamedTypeDecl* clone() const override = 0;
};

/// Cforall type variable: `dtype T`
class TypeDecl final : public NamedTypeDecl {
public:
	TypeVar::Kind kind;
	bool sized;
	ptr<Type> init;

	/// Data extracted from a type decl
	struct Data {
		TypeVar::Kind kind;
		bool isComplete;

		Data() : kind( (TypeVar::Kind)-1 ), isComplete( false ) {}
		Data( TypeDecl* d ) : kind( d->kind ), isComplete( d->sized ) {}
		Data( TypeVar::Kind k, bool c ) : kind( k ), isComplete( c ) {}
		Data( const Data& d1, const Data& d2 )
		: kind( d1.kind ), isComplete( d1.isComplete || d2.isComplete ) {}

		bool operator== ( const Data& o ) const {
			return kind == o.kind && isComplete == o.isComplete;
		}
		bool operator!= ( const Data& o ) const { return !(*this == o); }
	};

	TypeDecl( const CodeLocation& loc, const std::string& name, Storage::Classes storage, Type* b,
		TypeVar::Kind k, bool s, Type* i = nullptr )
	: NamedTypeDecl( loc, name, storage, b ), kind( k ), sized( k == TypeVar::Ttype || s ), 
	  init( i ) {}

	std::string typeString() const override;
	/// Produces a name for generated code
	std::string genTypeString() const;

	/// convenience accessor to match Type::isComplete()
	bool isComplete() { return sized; }

	const Decl * accept( Visitor & v ) const override { return v.visit( this ); }
private:
	TypeDecl * clone() const override { return new TypeDecl{ *this }; }

	/// Must be copied in ALL derived classes
	template<typename node_t>
	friend auto mutate(const node_t * node);
};

/// C-style typedef `typedef Foo Bar`
class TypedefDecl final : public NamedTypeDecl {
public:
	TypedefDecl( const CodeLocation& loc, const std::string& name, Storage::Classes storage,
		Type* b, Linkage::Spec spec = Linkage::Cforall )
	: NamedTypeDecl( loc, name, storage, b, spec ) {}

	std::string typeString() const override { return "typedef"; }

	const Decl * accept( Visitor & v ) const override { return v.visit( this ); }
private:
	TypedefDecl * clone() const override { return new TypedefDecl{ *this }; }

	/// Must be copied in ALL derived classes
	template<typename node_t>
	friend auto mutate(const node_t * node);
};

/// Aggregate type declaration base class
class AggregateDecl : public Decl {
public:
	std::vector<ptr<Decl>> members;
	std::vector<ptr<TypeDecl>> parameters;
	std::vector<ptr<Attribute>> attributes;
	bool body = false;
	readonly<AggregateDecl> parent = {};

	AggregateDecl( const CodeLocation& loc, const std::string& name,
		std::vector<ptr<Attribute>>&& attrs = {}, Linkage::Spec linkage = Linkage::Cforall )
	: Decl( loc, name, Storage::Classes{}, linkage ), members(), parameters(),
	  attributes( std::move(attrs) ) {}

	AggregateDecl* set_body( bool b ) { body = b; return this; }

protected:
	/// Produces a name for the kind of aggregate
	virtual std::string typeString() const = 0;
};

/// struct declaration `struct Foo { ... };`
class StructDecl final : public AggregateDecl {
public:
	DeclarationNode::Aggregate kind;

	StructDecl( const CodeLocation& loc, const std::string& name,
		DeclarationNode::Aggregate kind = DeclarationNode::Struct,
		std::vector<ptr<Attribute>>&& attrs = {}, Linkage::Spec linkage = Linkage::Cforall )
	: AggregateDecl( loc, name, std::move(attrs), linkage ), kind( kind ) {}

	bool is_coroutine() { return kind == DeclarationNode::Coroutine; }
	bool is_monitor() { return kind == DeclarationNode::Monitor; }
	bool is_thread() { return kind == DeclarationNode::Thread; }

	const Decl * accept( Visitor & v ) const override { return v.visit( this ); }
private:
	StructDecl * clone() const override { return new StructDecl{ *this }; }

	/// Must be copied in ALL derived classes
	template<typename node_t>
	friend auto mutate(const node_t * node);

	std::string typeString() const override { return "struct"; }
};

/// union declaration `union Foo { ... };`
class UnionDecl final : public AggregateDecl {
public:
	UnionDecl( const CodeLocation& loc, const std::string& name,
		std::vector<ptr<Attribute>>&& attrs = {}, Linkage::Spec linkage = Linkage::Cforall )
	: AggregateDecl( loc, name, std::move(attrs), linkage ) {}

	const Decl * accept( Visitor& v ) const override { return v.visit( this ); }
private:
	UnionDecl * clone() const override { return new UnionDecl{ *this }; }

	/// Must be copied in ALL derived classes
	template<typename node_t>
	friend auto mutate(const node_t * node);

	std::string typeString() const override { return "union"; }
};

/// enum declaration `enum Foo { ... };`
class EnumDecl final : public AggregateDecl {
public:
	EnumDecl( const CodeLocation& loc, const std::string& name,
		std::vector<ptr<Attribute>>&& attrs = {}, Linkage::Spec linkage = Linkage::Cforall )
	: AggregateDecl( loc, name, std::move(attrs), linkage ), enumValues() {}

	/// gets the integer value for this enumerator, returning true iff value found
	bool valueOf( Decl* enumerator, long long& value ) const;

	const Decl * accept( Visitor & v ) const override { return v.visit( this ); }
private:
	EnumDecl * clone() const override { return new EnumDecl{ *this }; }

	/// Must be copied in ALL derived classes
	template<typename node_t>
	friend auto mutate(const node_t * node);

	std::string typeString() const override { return "enum"; }

	/// Map from names to enumerator values; kept private for lazy initialization
	mutable std::unordered_map< std::string, long long > enumValues;
};

/// trait declaration `trait Foo( ... ) { ... };`
class TraitDecl final : public AggregateDecl {
public:
	TraitDecl( const CodeLocation& loc, const std::string& name,
		std::vector<ptr<Attribute>>&& attrs = {}, Linkage::Spec linkage = Linkage::Cforall )
	: AggregateDecl( loc, name, std::move(attrs), linkage ) {}

	const Decl * accept( Visitor & v ) const override { return v.visit( this ); }
private:
	TraitDecl * clone() const override { return new TraitDecl{ *this }; }

	/// Must be copied in ALL derived classes
	template<typename node_t>
	friend auto mutate(const node_t * node);

	std::string typeString() const override { return "trait"; }
};

class AsmDecl : public Decl {
public:
	ptr<AsmStmt> stmt;

	AsmDecl( const CodeLocation & loc, AsmStmt *stmt )
	: Decl( loc, "", {}, {} ), stmt(stmt) {}

	const AsmDecl * accept( Visitor &v ) const override { return v.visit( this ); }
private:
	AsmDecl *clone() const override { return new AsmDecl( *this ); }

	/// Must be copied in ALL derived classes
	template<typename node_t>
	friend auto mutate(const node_t * node);
};

class StaticAssertDecl : public Decl {
public:
	ptr<Expr> condition;
	ptr<ConstantExpr> msg;   // string literal

	StaticAssertDecl( const CodeLocation & loc, const Expr * condition, const ConstantExpr * msg )
	: Decl( loc, "", {}, {} ), condition( condition ), msg( msg ) {}

	const StaticAssertDecl * accept( Visitor &v ) const override { return v.visit( this ); }
private:
	StaticAssertDecl * clone() const override { return new StaticAssertDecl( *this ); }

	/// Must be copied in ALL derived classes
	template<typename node_t>
	friend auto mutate(const node_t * node);
};

//=================================================================================================
/// This disgusting and giant piece of boiler-plate is here to solve a cyclic dependency
/// remove only if there is a better solution
/// The problem is that ast::ptr< ... > uses increment/decrement which won't work well with
/// forward declarations
inline void increment( const class Decl * node, Node::ref_type ref ) { node->increment(ref); }
inline void decrement( const class Decl * node, Node::ref_type ref ) { node->decrement(ref); }
inline void increment( const class DeclWithType * node, Node::ref_type ref ) { node->increment(ref); }
inline void decrement( const class DeclWithType * node, Node::ref_type ref ) { node->decrement(ref); }
inline void increment( const class ObjectDecl * node, Node::ref_type ref ) { node->increment(ref); }
inline void decrement( const class ObjectDecl * node, Node::ref_type ref ) { node->decrement(ref); }
inline void increment( const class FunctionDecl * node, Node::ref_type ref ) { node->increment(ref); }
inline void decrement( const class FunctionDecl * node, Node::ref_type ref ) { node->decrement(ref); }
inline void increment( const class AggregateDecl * node, Node::ref_type ref ) { node->increment(ref); }
inline void decrement( const class AggregateDecl * node, Node::ref_type ref ) { node->decrement(ref); }
inline void increment( const class StructDecl * node, Node::ref_type ref ) { node->increment(ref); }
inline void decrement( const class StructDecl * node, Node::ref_type ref ) { node->decrement(ref); }
inline void increment( const class UnionDecl * node, Node::ref_type ref ) { node->increment(ref); }
inline void decrement( const class UnionDecl * node, Node::ref_type ref ) { node->decrement(ref); }
inline void increment( const class EnumDecl * node, Node::ref_type ref ) { node->increment(ref); }
inline void decrement( const class EnumDecl * node, Node::ref_type ref ) { node->decrement(ref); }
inline void increment( const class TraitDecl * node, Node::ref_type ref ) { node->increment(ref); }
inline void decrement( const class TraitDecl * node, Node::ref_type ref ) { node->decrement(ref); }
inline void increment( const class NamedTypeDecl * node, Node::ref_type ref ) { node->increment(ref); }
inline void decrement( const class NamedTypeDecl * node, Node::ref_type ref ) { node->decrement(ref); }
inline void increment( const class TypeDecl * node, Node::ref_type ref ) { node->increment(ref); }
inline void decrement( const class TypeDecl * node, Node::ref_type ref ) { node->decrement(ref); }
inline void increment( const class TypedefDecl * node, Node::ref_type ref ) { node->increment(ref); }
inline void decrement( const class TypedefDecl * node, Node::ref_type ref ) { node->decrement(ref); }
inline void increment( const class AsmDecl * node, Node::ref_type ref ) { node->increment(ref); }
inline void decrement( const class AsmDecl * node, Node::ref_type ref ) { node->decrement(ref); }
inline void increment( const class StaticAssertDecl * node, Node::ref_type ref ) { node->increment(ref); }
inline void decrement( const class StaticAssertDecl * node, Node::ref_type ref ) { node->decrement(ref); }

}

// Local Variables: //
// tab-width: 4 //
// mode: c++ //
// compile-command: "make install" //
// End: //
