//
// 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.
//
// Expr.cpp --
//
// Author           : Aaron B. Moss
// Created On       : Wed May 15 17:00:00 2019
// Last Modified By : Peter A. Buhr
// Created On       : Thr Jun 13 13:38:00 2019
// Update Count     : 6
//

#include "Expr.hpp"

#include <cassert>                 // for strict_dynamic_cast
#include <string>                  // for to_string
#include <vector>

#include "GenericSubstitution.hpp"
#include "Stmt.hpp"
#include "Type.hpp"
#include "TypeSubstitution.hpp"
#include "Common/utility.h"
#include "Common/SemanticError.h"
#include "GenPoly/Lvalue.h"        // for referencesPermissable
#include "InitTweak/InitTweak.h"   // for getPointerBase
#include "ResolvExpr/typeops.h"    // for extractResultType
#include "Tuples/Tuples.h"         // for makeTupleType

namespace ast {

// --- ApplicationExpr

ApplicationExpr::ApplicationExpr( const CodeLocation & loc, const Expr * f,
	std::vector<ptr<Expr>> && as )
: Expr( loc ), func( f ), args( std::move(as) ) {
	// ensure that `ApplicationExpr` result type is `FuncExpr`
	const PointerType * pt = strict_dynamic_cast< const PointerType * >( f->result.get() );
	const FunctionType * fn = strict_dynamic_cast< const FunctionType * >( pt->base.get() );

	result = ResolvExpr::extractResultType( fn );
	assert( result );
}

// --- UntypedExpr

UntypedExpr * UntypedExpr::createDeref( const CodeLocation & loc, Expr * arg ) {
	assert( arg );

	UntypedExpr * ret = new UntypedExpr{
		loc, new NameExpr{loc, "*?"}, std::vector<ptr<Expr>>{ ptr<Expr>{ arg } }
	};
	if ( const Type * ty = arg->result ) {
		const Type * base = InitTweak::getPointerBase( ty );
		assertf( base, "expected pointer type in dereference (type was %s)", toString( ty ).c_str() );

		if ( GenPoly::referencesPermissable() ) {
			// if references are still allowed in the AST, dereference returns a reference
			ret->result = new ReferenceType{ base };
		} else {
			// references have been removed, in which case dereference returns an lvalue of the
			// base type
			ret->result = base;
			add_qualifiers( ret->result, CV::Lvalue );
		}
	}
	return ret;
}

UntypedExpr * UntypedExpr::createAssign( const CodeLocation & loc, Expr * lhs, Expr * rhs ) {
	assert( lhs && rhs );

	UntypedExpr * ret = new UntypedExpr{
		loc, new NameExpr{loc, "?=?"}, std::vector<ptr<Expr>>{ ptr<Expr>{ lhs }, ptr<Expr>{ rhs } }
	};
	if ( lhs->result && rhs->result ) {
		// if both expressions are typed, assumes that this assignment is a C bitwise assignment,
		// so the result is the type of the RHS
		ret->result = rhs->result;
	}
	return ret;
}

// --- AddressExpr

// Address expressions are typed based on the following inference rules:
//    E : lvalue T  &..& (n references)
//   &E :        T *&..& (n references)
//
//    E : T  &..&        (m references)
//   &E : T *&..&        (m-1 references)

namespace {
	/// The type of the address of a type.
	/// Caller is responsible for managing returned memory
	Type * addrType( const Type * type ) {
		if ( const ReferenceType * refType = dynamic_cast< const ReferenceType * >( type ) ) {
			return new ReferenceType{ addrType( refType->base ), refType->qualifiers };
		} else {
			return new PointerType{ type };
		}
	}
}

AddressExpr::AddressExpr( const CodeLocation & loc, const Expr * a ) : Expr( loc ), arg( a ) {
	if ( arg->result ) {
		if ( arg->result->is_lvalue() ) {
			// lvalue, retains all levels of reference, and gains a pointer inside the references
			Type * res = addrType( arg->result );
			res->set_lvalue( false ); // result of & is never an lvalue
			result = res;
		} else {
			// taking address of non-lvalue, must be a reference, loses one layer of reference
			if ( const ReferenceType * refType =
					dynamic_cast< const ReferenceType * >( arg->result.get() ) ) {
				Type * res = addrType( refType->base );
				res->set_lvalue( false ); // result of & is never an lvalue
				result = res;
			} else {
				SemanticError( loc, arg->result.get(),
					"Attempt to take address of non-lvalue expression: " );
			}
		}
	}
}

// --- LabelAddressExpr

// label address always has type `void*`
LabelAddressExpr::LabelAddressExpr( const CodeLocation & loc, Label && a )
: Expr( loc, new PointerType{ new VoidType{} } ), arg( a ) {}

// --- CastExpr

CastExpr::CastExpr( const CodeLocation & loc, const Expr * a, GeneratedFlag g )
: Expr( loc, new VoidType{} ), arg( a ), isGenerated( g ) {}

// --- KeywordCastExpr

const char * KeywordCastExpr::targetString() const {
	return AggregateDecl::aggrString( target );
}

// --- MemberExpr

MemberExpr::MemberExpr( const CodeLocation & loc, const DeclWithType * mem, const Expr * agg )
: Expr( loc ), member( mem ), aggregate( agg ) {
	assert( member );
	assert( aggregate );
	assert( aggregate->result );

	// take ownership of member type
	result = mem->get_type();
	// substitute aggregate generic parameters into member type
	genericSubstitution( aggregate->result ).apply( result );
	// ensure lvalue and appropriate restrictions from aggregate type
	add_qualifiers( result, aggregate->result->qualifiers | CV::Lvalue );
}

// --- VariableExpr

VariableExpr::VariableExpr( const CodeLocation & loc )
: Expr( loc ), var( nullptr ) {}

VariableExpr::VariableExpr( const CodeLocation & loc, const DeclWithType * v )
: Expr( loc ), var( v ) {
	assert( var );
	assert( var->get_type() );
	result = var->get_type();
	add_qualifiers( result, CV::Lvalue );
}

VariableExpr * VariableExpr::functionPointer(
		const CodeLocation & loc, const FunctionDecl * decl ) {
	// wrap usually-determined result type in a pointer
	VariableExpr * funcExpr = new VariableExpr{ loc, decl };
	funcExpr->result = new PointerType{ funcExpr->result };
	return funcExpr;
}

// --- ConstantExpr

long long int ConstantExpr::intValue() const {
	if ( const BasicType * bty = result.as< BasicType >() ) {
		if ( bty->isInteger() ) {
			assert(ival);
			return ival.value();
		}
	} else if ( result.as< ZeroType >() ) {
		return 0;
	} else if ( result.as< OneType >() ) {
		return 1;
	}
	SemanticError( this, "Constant expression of non-integral type " );
}

ConstantExpr * ConstantExpr::from_bool( const CodeLocation & loc, bool b ) {
	return new ConstantExpr{
		loc, new BasicType{ BasicType::Bool }, b ? "1" : "0", (unsigned long long)b };
}

ConstantExpr * ConstantExpr::from_int( const CodeLocation & loc, int i ) {
	return new ConstantExpr{
		loc, new BasicType{ BasicType::SignedInt }, std::to_string( i ), (unsigned long long)i };
}

ConstantExpr * ConstantExpr::from_ulong( const CodeLocation & loc, unsigned long i ) {
	return new ConstantExpr{
		loc, new BasicType{ BasicType::LongUnsignedInt }, std::to_string( i ),
		(unsigned long long)i };
}

ConstantExpr * ConstantExpr::null( const CodeLocation & loc, const Type * ptrType ) {
	return new ConstantExpr{
		loc, ptrType ? ptrType : new PointerType{ new VoidType{} }, "0", (unsigned long long)0 };
}

// --- SizeofExpr

SizeofExpr::SizeofExpr( const CodeLocation & loc, const Expr * e )
: Expr( loc, new BasicType{ BasicType::LongUnsignedInt } ), expr( e ), type( nullptr ) {}

SizeofExpr::SizeofExpr( const CodeLocation & loc, const Type * t )
: Expr( loc, new BasicType{ BasicType::LongUnsignedInt } ), expr( nullptr ), type( t ) {}

// --- AlignofExpr

AlignofExpr::AlignofExpr( const CodeLocation & loc, const Expr * e )
: Expr( loc, new BasicType{ BasicType::LongUnsignedInt } ), expr( e ), type( nullptr ) {}

AlignofExpr::AlignofExpr( const CodeLocation & loc, const Type * t )
: Expr( loc, new BasicType{ BasicType::LongUnsignedInt } ), expr( nullptr ), type( t ) {}

// --- OffsetofExpr

OffsetofExpr::OffsetofExpr( const CodeLocation & loc, const Type * ty, const DeclWithType * mem )
: Expr( loc, new BasicType{ BasicType::LongUnsignedInt } ), type( ty ), member( mem ) {
	assert( type );
	assert( member );
}

// --- OffsetPackExpr

OffsetPackExpr::OffsetPackExpr( const CodeLocation & loc, const StructInstType * ty )
: Expr( loc, new ArrayType{
	new BasicType{ BasicType::LongUnsignedInt }, nullptr, FixedLen, DynamicDim }
), type( ty ) {
	assert( type );
}

// --- LogicalExpr

LogicalExpr::LogicalExpr(
	const CodeLocation & loc, const Expr * a1, const Expr * a2, LogicalFlag ia )
: Expr( loc, new BasicType{ BasicType::SignedInt } ), arg1( a1 ), arg2( a2 ), isAnd( ia ) {}

// --- ConstructorExpr

ConstructorExpr::ConstructorExpr( const CodeLocation & loc, const Expr * call )
: Expr( loc ), callExpr( call ) {
	// allow resolver to type a constructor used as an expression if it has the same type as its
	// first argument
	assert( callExpr );
	const Expr * arg = InitTweak::getCallArg( callExpr, 0 );
	assert( arg );
	result = arg->result;
}

// --- CompoundLiteralExpr

CompoundLiteralExpr::CompoundLiteralExpr( const CodeLocation & loc, const Type * t, const Init * i )
: Expr( loc ), init( i ) {
	assert( t && i );
	result = t;
	add_qualifiers( result, CV::Lvalue );
}

// --- TupleExpr

TupleExpr::TupleExpr( const CodeLocation & loc, std::vector<ptr<Expr>> && xs )
: Expr( loc, Tuples::makeTupleType( xs ) ), exprs( xs ) {}

// --- TupleIndexExpr

TupleIndexExpr::TupleIndexExpr( const CodeLocation & loc, const Expr * t, unsigned i )
: Expr( loc ), tuple( t ), index( i ) {
	const TupleType * type = strict_dynamic_cast< const TupleType * >( tuple->result.get() );
	assertf( type->size() > index, "TupleIndexExpr index out of bounds: tuple size %d, requested "
		"index %d in expr %s", type->size(), index, toString( tuple ).c_str() );
	// like MemberExpr, TupleIndexExpr is always an lvalue
	result = type->types[ index ];
	add_qualifiers( result, CV::Lvalue );
}

// --- TupleAssignExpr

TupleAssignExpr::TupleAssignExpr(
	const CodeLocation & loc, std::vector<ptr<Expr>> && assigns,
	std::vector<ptr<ObjectDecl>> && tempDecls )
: Expr( loc, Tuples::makeTupleType( assigns ) ), stmtExpr() {
	// convert internally into a StmtExpr which contains the declarations and produces the tuple of
	// the assignments
	std::list<ptr<Stmt>> stmts;
	for ( const ObjectDecl * obj : tempDecls ) {
		stmts.emplace_back( new DeclStmt{ loc, obj } );
	}
	TupleExpr * tupleExpr = new TupleExpr{ loc, std::move(assigns) };
	assert( tupleExpr->result );
	stmts.emplace_back( new ExprStmt{ loc, tupleExpr } );
	stmtExpr = new StmtExpr{ loc, new CompoundStmt{ loc, std::move(stmts) } };
}

TupleAssignExpr::TupleAssignExpr(
	const CodeLocation & loc, const Type * result, const StmtExpr * s )
: Expr( loc, result ), stmtExpr() {
	stmtExpr = s;
}

// --- StmtExpr

StmtExpr::StmtExpr( const CodeLocation & loc, const CompoundStmt * ss )
: Expr( loc ), stmts( ss ), returnDecls(), dtors() { computeResult(); }

void StmtExpr::computeResult() {
	assert( stmts );
	const std::list<ptr<Stmt>> & body = stmts->kids;
	if ( ! returnDecls.empty() ) {
		// prioritize return decl for result type, since if a return decl exists, then the StmtExpr
		// is currently in an intermediate state where the body will always give a void result type
		result = returnDecls.front()->get_type();
	} else if ( ! body.empty() ) {
		if ( const ExprStmt * exprStmt = body.back().as< ExprStmt >() ) {
			result = exprStmt->expr->result;
		}
	}
	// ensure a result type exists
	if ( ! result ) { result = new VoidType{}; }
}

// --- UniqueExpr

unsigned long long UniqueExpr::nextId = 0;

UniqueExpr::UniqueExpr( const CodeLocation & loc, const Expr * e, unsigned long long i )
: Expr( loc, e->result ), expr( e ), id( i ) {
	assert( expr );
	if ( id == -1ull ) {
		assert( nextId != -1ull );
		id = nextId++;
	}
}

}

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