//
// 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 <iosfwd>
#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

// Must be included in *all* AST classes; should be #undef'd at the end of the file
#define MUTATE_FRIEND template<typename node_t> friend node_t * mutate(const node_t * node);

namespace ast {

/// 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;
	MUTATE_FRIEND
};

/// 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;
	MUTATE_FRIEND
};

/// 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, const Type * type,
		const Init * init = nullptr, Storage::Classes storage = {},
		Linkage::Spec linkage = Linkage::C, const 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 }; }
	MUTATE_FRIEND
};

/// Object declaration `int foo()`
class FunctionDecl : public DeclWithType {
public:
	ptr<FunctionType> type;
	ptr<CompoundStmt> stmts;
	std::vector< 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;
	void set_type(Type * t) override;

	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 ); }
	MUTATE_FRIEND
};

/// Base class for named type aliases
class NamedTypeDecl : public Decl {
public:
	ptr<Type> base;
	std::vector<ptr<TypeDecl>> params;
	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 ), params(), assertions() {}

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

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

/// 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( const 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 }; }
	MUTATE_FRIEND
};

std::ostream & operator<< ( std::ostream &, const TypeDecl::Data & );

/// 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 }; }
	MUTATE_FRIEND
};

/// Aggregate type declaration base class
class AggregateDecl : public Decl {
public:
	std::vector<ptr<Decl>> members;
	std::vector<ptr<TypeDecl>> params;
	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(), params(),
	  attributes( std::move(attrs) ) {}

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

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

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

/// 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 ); }

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

private:
	StructDecl * clone() const override { return new StructDecl{ *this }; }
	MUTATE_FRIEND
};

/// 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 ); }

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

private:
	UnionDecl * clone() const override { return new UnionDecl{ *this }; }
	MUTATE_FRIEND
};

/// 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( const Decl * enumerator, long long& value ) const;

	const Decl * accept( Visitor & v ) const override { return v.visit( this ); }

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

private:
	EnumDecl * clone() const override { return new EnumDecl{ *this }; }
	MUTATE_FRIEND

	/// 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 ); }

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

private:
	TraitDecl * clone() const override { return new TraitDecl{ *this }; }
	MUTATE_FRIEND
};

/// With statement `with (...) ...`
class WithStmt final : public Decl {
public:
	std::vector<ptr<Expr>> exprs;
	ptr<Stmt> stmt;

	WithStmt( const CodeLocation & loc, std::vector<ptr<Expr>> && exprs, const Stmt * stmt )
	: Decl(loc, "", Storage::Auto, Linkage::Cforall), exprs(std::move(exprs)), stmt(stmt) {}

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

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 ); }
	MUTATE_FRIEND
};

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

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

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

}

#undef MUTATE_FRIEND

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