//
// 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.
//
// Expression.cc --
//
// Author           : Richard C. Bilson
// Created On       : Mon May 18 07:44:20 2015
// Last Modified By : Peter A. Buhr
// Last Modified On : Thu Mar 30 16:41:13 2017
// Update Count     : 52
//

#include <iostream>
#include <cassert>
#include <list>
#include <algorithm>

#include <iterator>

#include "Type.h"
#include "Initializer.h"
#include "Expression.h"
#include "Declaration.h"
#include "Statement.h"
#include "TypeSubstitution.h"
#include "Common/utility.h"
#include "InitTweak/InitTweak.h"


Expression::Expression( Expression *_aname ) : result( 0 ), env( 0 ), argName( _aname ) {}

Expression::Expression( const Expression &other ) : BaseSyntaxNode( other ), result( maybeClone( other.result ) ), env( maybeClone( other.env ) ), argName( maybeClone( other.get_argName() ) ), extension( other.extension ) {
}

Expression::~Expression() {
	delete env;
	delete argName;	// xxx -- there's a problem in cloning ConstantExpr I still don't know how to fix
	delete result;
}

void Expression::print( std::ostream &os, int indent ) const {
	if ( env ) {
		os << std::string( indent, ' ' ) << "with environment:" << std::endl;
		env->print( os, indent+2 );
	} // if

	if ( argName ) {
		os << std::string( indent, ' ' ) << "with designator:";
		argName->print( os, indent+2 );
	} // if

	if ( extension ) {
		os << std::string( indent, ' ' ) << "with extension:";
	} // if
}

ConstantExpr::ConstantExpr( Constant _c, Expression *_aname ) : Expression( _aname ), constant( _c ) {
	set_result( constant.get_type()->clone() );
}

ConstantExpr::ConstantExpr( const ConstantExpr &other) : Expression( other ), constant( other.constant ) {
}

ConstantExpr::~ConstantExpr() {}

void ConstantExpr::print( std::ostream &os, int indent ) const {
	os << "constant expression " ;
	constant.print( os );
	Expression::print( os, indent );
}

VariableExpr::VariableExpr( DeclarationWithType *_var, Expression *_aname ) : Expression( _aname ), var( _var ) {
	assert( var );
	assert( var->get_type() );
	Type * type = var->get_type()->clone();
	type->set_lvalue( true );
	set_result( type );
}

VariableExpr::VariableExpr( const VariableExpr &other ) : Expression( other ), var( other.var ) {
}

VariableExpr::~VariableExpr() {
	// don't delete the declaration, since it points somewhere else in the tree
}

void VariableExpr::print( std::ostream &os, int indent ) const {
	os << "Variable Expression: ";

	Declaration *decl = get_var();
	// if ( decl != 0) decl->print(os, indent + 2);
	if ( decl != 0) decl->printShort(os, indent + 2);
	os << std::endl;
	Expression::print( os, indent );
}

SizeofExpr::SizeofExpr( Expression *expr_, Expression *_aname ) :
		Expression( _aname ), expr(expr_), type(0), isType(false) {
	set_result( new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ) );
}

SizeofExpr::SizeofExpr( Type *type_, Expression *_aname ) :
		Expression( _aname ), expr(0), type(type_), isType(true) {
	set_result( new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ) );
}

SizeofExpr::SizeofExpr( const SizeofExpr &other ) :
	Expression( other ), expr( maybeClone( other.expr ) ), type( maybeClone( other.type ) ), isType( other.isType ) {
}

SizeofExpr::~SizeofExpr() {
	delete expr;
	delete type;
}

void SizeofExpr::print( std::ostream &os, int indent) const {
	os << "Sizeof Expression on: ";

	if (isType)
		type->print(os, indent + 2);
	else
		expr->print(os, indent + 2);

	os << std::endl;
	Expression::print( os, indent );
}

AlignofExpr::AlignofExpr( Expression *expr_, Expression *_aname ) :
		Expression( _aname ), expr(expr_), type(0), isType(false) {
	set_result( new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ) );
}

AlignofExpr::AlignofExpr( Type *type_, Expression *_aname ) :
		Expression( _aname ), expr(0), type(type_), isType(true) {
	set_result( new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ) );
}

AlignofExpr::AlignofExpr( const AlignofExpr &other ) :
	Expression( other ), expr( maybeClone( other.expr ) ), type( maybeClone( other.type ) ), isType( other.isType ) {
}

AlignofExpr::~AlignofExpr() {
	delete expr;
	delete type;
}

void AlignofExpr::print( std::ostream &os, int indent) const {
	os << std::string( indent, ' ' ) << "Alignof Expression on: ";

	if (isType)
		type->print(os, indent + 2);
	else
		expr->print(os, indent + 2);

	os << std::endl;
	Expression::print( os, indent );
}

UntypedOffsetofExpr::UntypedOffsetofExpr( Type *type_, const std::string &member_, Expression *_aname ) :
		Expression( _aname ), type(type_), member(member_) {
	set_result( new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ) );
}

UntypedOffsetofExpr::UntypedOffsetofExpr( const UntypedOffsetofExpr &other ) :
	Expression( other ), type( maybeClone( other.type ) ), member( other.member ) {}

UntypedOffsetofExpr::~UntypedOffsetofExpr() {
	delete type;
}

void UntypedOffsetofExpr::print( std::ostream &os, int indent) const {
	os << std::string( indent, ' ' ) << "Untyped Offsetof Expression on member " << member << " of ";

	if ( type ) {
		type->print(os, indent + 2);
	} else {
		os << "<NULL>";
	}

	os << std::endl;
	Expression::print( os, indent );
}

OffsetofExpr::OffsetofExpr( Type *type_, DeclarationWithType *member_, Expression *_aname ) :
		Expression( _aname ), type(type_), member(member_) {
	set_result( new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ) );
}

OffsetofExpr::OffsetofExpr( const OffsetofExpr &other ) :
	Expression( other ), type( maybeClone( other.type ) ), member( other.member ) {}

OffsetofExpr::~OffsetofExpr() {
	delete type;
}

void OffsetofExpr::print( std::ostream &os, int indent) const {
	os << std::string( indent, ' ' ) << "Offsetof Expression on member ";

	if ( member ) {
		os << member->get_name();
	} else {
		os << "<NULL>";
	}

	os << " of ";

	if ( type ) {
		type->print(os, indent + 2);
	} else {
		os << "<NULL>";
	}

	os << std::endl;
	Expression::print( os, indent );
}

OffsetPackExpr::OffsetPackExpr( StructInstType *type_, Expression *aname_ ) : Expression( aname_ ), type( type_ ) {
	set_result( new ArrayType( Type::Qualifiers(), new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), 0, false, false ) );
}

OffsetPackExpr::OffsetPackExpr( const OffsetPackExpr &other ) : Expression( other ), type( maybeClone( other.type ) ) {}

OffsetPackExpr::~OffsetPackExpr() { delete type; }

void OffsetPackExpr::print( std::ostream &os, int indent ) const {
	os << std::string( indent, ' ' ) << "Offset pack expression on ";

	if ( type ) {
		type->print(os, indent + 2);
	} else {
		os << "<NULL>";
	}

	os << std::endl;
	Expression::print( os, indent );
}

AttrExpr::AttrExpr( Expression *attr, Expression *expr_, Expression *_aname ) :
		Expression( _aname ), attr( attr ), expr(expr_), type(0), isType(false) {
}

AttrExpr::AttrExpr( Expression *attr, Type *type_, Expression *_aname ) :
		Expression( _aname ), attr( attr ), expr(0), type(type_), isType(true) {
}

AttrExpr::AttrExpr( const AttrExpr &other ) :
		Expression( other ), attr( maybeClone( other.attr ) ), expr( maybeClone( other.expr ) ), type( maybeClone( other.type ) ), isType( other.isType ) {
}

AttrExpr::~AttrExpr() {
	delete attr;
	delete expr;
	delete type;
}

void AttrExpr::print( std::ostream &os, int indent) const {
	os << std::string( indent, ' ' ) << "Attr ";
	attr->print( os, indent + 2 );
	if ( isType || expr ) {
		os << "applied to: ";

		if (isType)
			type->print(os, indent + 2);
		else
			expr->print(os, indent + 2);
	} // if

	os << std::endl;
	Expression::print( os, indent );
}

CastExpr::CastExpr( Expression *arg_, Type *toType, Expression *_aname ) : Expression( _aname ), arg(arg_) {
	set_result(toType);
}

CastExpr::CastExpr( Expression *arg_, Expression *_aname ) : Expression( _aname ), arg(arg_) {
	set_result( new VoidType( Type::Qualifiers() ) );
}

CastExpr::CastExpr( const CastExpr &other ) : Expression( other ), arg( maybeClone( other.arg ) ) {
}

CastExpr::~CastExpr() {
	delete arg;
}

// CastExpr *CastExpr::clone() const { return 0; }

void CastExpr::print( std::ostream &os, int indent ) const {
	os << "Cast of:" << std::endl << std::string( indent+2, ' ' );
	arg->print(os, indent+2);
	os << std::endl << std::string( indent, ' ' ) << "to:" << std::endl;
	os << std::string( indent+2, ' ' );
	if ( result->isVoid() ) {
		os << "nothing";
	} else {
		result->print( os, indent+2 );
	} // if
	os << std::endl;
	Expression::print( os, indent );
}

UntypedMemberExpr::UntypedMemberExpr( Expression * _member, Expression *_aggregate, Expression *_aname ) :
		Expression( _aname ), member(_member), aggregate(_aggregate) {}

UntypedMemberExpr::UntypedMemberExpr( const UntypedMemberExpr &other ) :
		Expression( other ), member( maybeClone( other.member ) ), aggregate( maybeClone( other.aggregate ) ) {
}

UntypedMemberExpr::~UntypedMemberExpr() {
	delete aggregate;
	delete member;
}

void UntypedMemberExpr::print( std::ostream &os, int indent ) const {
	os << "Untyped Member Expression, with field: " << std::endl;
	os << std::string( indent+2, ' ' );
	get_member()->print(os, indent+4);
	os << std::string( indent+2, ' ' );

	Expression *agg = get_aggregate();
	os << "from aggregate: " << std::endl;
	if (agg != 0) {
		os << std::string( indent + 4, ' ' );
		agg->print(os, indent + 4);
	}
	os << std::string( indent+2, ' ' );
	Expression::print( os, indent );
}

namespace {
	TypeSubstitution makeSub( Type * t ) {
		if ( StructInstType * aggInst = dynamic_cast< StructInstType * >( t ) ) {
			return TypeSubstitution( aggInst->get_baseParameters()->begin(), aggInst->get_baseParameters()->end(), aggInst->get_parameters().begin() );
		} else if ( UnionInstType * aggInst = dynamic_cast< UnionInstType * >( t ) ) {
			return TypeSubstitution( aggInst->get_baseParameters()->begin(), aggInst->get_baseParameters()->end(), aggInst->get_parameters().begin() );
		} else {
			assertf( false, "makeSub expects struct or union type for aggregate, but got: %s", toString( t ).c_str() );
		}
	}
}


MemberExpr::MemberExpr( DeclarationWithType *_member, Expression *_aggregate, Expression *_aname ) :
		Expression( _aname ), member(_member), aggregate(_aggregate) {

	TypeSubstitution sub( makeSub( aggregate->get_result() ) );
	Type * res = member->get_type()->clone();
	sub.apply( res );
	set_result( res );
	get_result()->set_lvalue( true );
}

//// is this right? It's cloning the member, but the member is a declaration so probably shouldn't be cloned...
MemberExpr::MemberExpr( const MemberExpr &other ) :
		Expression( other ), member( other.member ), aggregate( maybeClone( other.aggregate ) ) {
}

MemberExpr::~MemberExpr() {
	// delete member;
	delete aggregate;
}

void MemberExpr::print( std::ostream &os, int indent ) const {
	os << "Member Expression, with field: " << std::endl;

	assert( member );
	os << std::string( indent + 2, ' ' );
	member->print( os, indent + 2 );
	os << std::endl;

	Expression *agg = get_aggregate();
	os << std::string( indent, ' ' ) << "from aggregate: " << std::endl;
	if (agg != 0) {
		os << std::string( indent + 2, ' ' );
		agg->print(os, indent + 2);
	}
	os << std::string( indent+2, ' ' );
	Expression::print( os, indent );
}

UntypedExpr::UntypedExpr( Expression *_function, const std::list<Expression *> &_args, Expression *_aname ) :
		Expression( _aname ), function(_function), args(_args) {}

UntypedExpr::UntypedExpr( const UntypedExpr &other ) :
		Expression( other ), function( maybeClone( other.function ) ) {
	cloneAll( other.args, args );
}

UntypedExpr::~UntypedExpr() {
	delete function;
	deleteAll( args );
}

UntypedExpr * UntypedExpr::createDeref( Expression * expr ) {
	UntypedExpr * ret = new UntypedExpr( new NameExpr("*?"), std::list< Expression * >{ expr } );
	if ( Type * type = expr->get_result() ) {
		Type * base = InitTweak::getPointerBase( type );
		if ( ! base ) {
			std::cerr << type << std::endl;
		}
		assertf( base, "expected pointer type in dereference\n" );
		ret->set_result( maybeClone( base ) );
	}
	return ret;
}

UntypedExpr * UntypedExpr::createAssign( Expression * arg1, Expression * arg2 ) {
	assert( arg1 && arg2 );
	UntypedExpr * ret = new UntypedExpr( new NameExpr( "?=?" ), std::list< Expression * >{ arg1, arg2 } );
	if ( arg1->get_result() && arg2->get_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->set_result( arg2->get_result()->clone() );
	}
	return ret;
}


void UntypedExpr::print( std::ostream &os, int indent ) const {
	os << "Applying untyped: " << std::endl;
	os << std::string( indent+2, ' ' );
	function->print(os, indent + 2);
	os << std::string( indent, ' ' ) << "...to: " << std::endl;
	printAll(args, os, indent + 2);
	Expression::print( os, indent );
}

void UntypedExpr::printArgs( std::ostream &os, int indent ) const {
	std::list<Expression *>::const_iterator i;
	for (i = args.begin(); i != args.end(); i++) {
		os << std::string(indent, ' ' );
		(*i)->print(os, indent);
	}
}

NameExpr::NameExpr( std::string _name, Expression *_aname ) : Expression( _aname ), name(_name) {
	assertf(_name != "0", "Zero is not a valid name\n");
	assertf(_name != "1", "One is not a valid name\n");
}

NameExpr::NameExpr( const NameExpr &other ) : Expression( other ), name( other.name ) {
}

NameExpr::~NameExpr() {}

void NameExpr::print( std::ostream &os, int indent ) const {
	os << "Name: " << get_name() << std::endl;
	Expression::print( os, indent );
}

LogicalExpr::LogicalExpr( Expression *arg1_, Expression *arg2_, bool andp, Expression *_aname ) :
		Expression( _aname ), arg1(arg1_), arg2(arg2_), isAnd(andp) {
	set_result( new BasicType( Type::Qualifiers(), BasicType::SignedInt ) );
}

LogicalExpr::LogicalExpr( const LogicalExpr &other ) :
		Expression( other ), arg1( maybeClone( other.arg1 ) ), arg2( maybeClone( other.arg2 ) ), isAnd( other.isAnd ) {
}

LogicalExpr::~LogicalExpr() {
	delete arg1;
	delete arg2;
}

void LogicalExpr::print( std::ostream &os, int indent )const {
	os << std::string( indent, ' ' ) << "Short-circuited operation (" << (isAnd?"and":"or") << ") on: ";
	arg1->print(os);
	os << " and ";
	arg2->print(os);
	os << std::endl;
	Expression::print( os, indent );
}

ConditionalExpr::ConditionalExpr( Expression *arg1_, Expression *arg2_, Expression *arg3_, Expression *_aname ) :
		Expression( _aname ), arg1(arg1_), arg2(arg2_), arg3(arg3_) {}

ConditionalExpr::ConditionalExpr( const ConditionalExpr &other ) :
		Expression( other ), arg1( maybeClone( other.arg1 ) ), arg2( maybeClone( other.arg2 ) ), arg3( maybeClone( other.arg3 ) ) {
}

ConditionalExpr::~ConditionalExpr() {
	delete arg1;
	delete arg2;
	delete arg3;
}

void ConditionalExpr::print( std::ostream &os, int indent ) const {
	os << "Conditional expression on: " << std::endl;
	os << std::string( indent+2, ' ' );
	arg1->print( os, indent+2 );
	os << std::string( indent, ' ' ) << "First alternative:" << std::endl;
	os << std::string( indent+2, ' ' );
	arg2->print( os, indent+2 );
	os << std::string( indent, ' ' ) << "Second alternative:" << std::endl;
	os << std::string( indent+2, ' ' );
	arg3->print( os, indent+2 );
	os << std::endl;
	Expression::print( os, indent );
}

AsmExpr::AsmExpr( const AsmExpr & other ) : inout( maybeClone( other.inout ) ), constraint( maybeClone( other.constraint ) ), operand( maybeClone( other.operand ) ) {}


void AsmExpr::print( std::ostream &os, int indent ) const {
	os << "Asm Expression: " << std::endl;
	if ( inout ) inout->print( os, indent + 2 );
	if ( constraint ) constraint->print( os, indent + 2 );
	if ( operand ) operand->print( os, indent + 2 );
}


ImplicitCopyCtorExpr::ImplicitCopyCtorExpr( ApplicationExpr * callExpr ) : callExpr( callExpr ) {
	assert( callExpr );
	assert( callExpr->has_result() );
	set_result( callExpr->get_result()->clone() );
}

ImplicitCopyCtorExpr::ImplicitCopyCtorExpr( const ImplicitCopyCtorExpr & other ) : Expression( other ), callExpr( maybeClone( other.callExpr ) ) {
	cloneAll( other.tempDecls, tempDecls );
	cloneAll( other.returnDecls, returnDecls );
	cloneAll( other.dtors, dtors );
}

ImplicitCopyCtorExpr::~ImplicitCopyCtorExpr() {
	set_env( nullptr ); // ImplicitCopyCtorExpr does not take ownership of an environment
	delete callExpr;
	deleteAll( tempDecls );
	deleteAll( returnDecls );
	deleteAll( dtors );
}

void ImplicitCopyCtorExpr::print( std::ostream &os, int indent ) const {
	os <<  "Implicit Copy Constructor Expression: " << std::endl;
	assert( callExpr );
	os << std::string( indent+2, ' ' );
	callExpr->print( os, indent + 2 );
	os << std::endl << std::string( indent, ' ' ) << "with temporaries:" << std::endl;
	printAll(tempDecls, os, indent+2);
	os << std::endl << std::string( indent, ' ' ) << "with return temporaries:" << std::endl;
	printAll(returnDecls, os, indent+2);
	Expression::print( os, indent );
}


ConstructorExpr::ConstructorExpr( Expression * callExpr ) : callExpr( callExpr ) {
	// allow resolver to type a constructor used as an expression as if it has the same type as its first argument
	assert( callExpr );
	Expression * arg = InitTweak::getCallArg( callExpr, 0 );
	assert( arg );
	set_result( maybeClone( arg->get_result() ) );
}

ConstructorExpr::ConstructorExpr( const ConstructorExpr & other ) : Expression( other ), callExpr( maybeClone( other.callExpr ) ) {
}

ConstructorExpr::~ConstructorExpr() {
	delete callExpr;
}

void ConstructorExpr::print( std::ostream &os, int indent ) const {
	os <<  "Constructor Expression: " << std::endl;
	assert( callExpr );
	os << std::string( indent+2, ' ' );
	callExpr->print( os, indent + 2 );
	Expression::print( os, indent );
}


CompoundLiteralExpr::CompoundLiteralExpr( Type * type, Initializer * initializer ) : initializer( initializer ) {
	assert( type && initializer );
	set_result( type );
}

CompoundLiteralExpr::CompoundLiteralExpr( const CompoundLiteralExpr &other ) : Expression( other ), initializer( other.initializer->clone() ) {}

CompoundLiteralExpr::~CompoundLiteralExpr() {
	delete initializer;
}

void CompoundLiteralExpr::print( std::ostream &os, int indent ) const {
	os << "Compound Literal Expression: " << std::endl;
	os << std::string( indent+2, ' ' );
	get_result()->print( os, indent + 2 );
	os << std::string( indent+2, ' ' );
	initializer->print( os, indent + 2 );
	Expression::print( os, indent );
}

UntypedValofExpr::UntypedValofExpr( const UntypedValofExpr & other ) : Expression( other ), body ( maybeClone( other.body ) ) {}

UntypedValofExpr::~UntypedValofExpr() { delete body; }

void UntypedValofExpr::print( std::ostream &os, int indent ) const {
	os << std::string( indent, ' ' ) << "Valof Expression: " << std::endl;
	if ( get_body() != 0 )
		get_body()->print( os, indent + 2 );
}

RangeExpr::RangeExpr( Expression *low, Expression *high ) : low( low ), high( high ) {}
RangeExpr::RangeExpr( const RangeExpr &other ) : Expression( other ), low( other.low->clone() ), high( other.high->clone() ) {}
void RangeExpr::print( std::ostream &os, int indent ) const {
	os << "Range Expression: ";
	low->print( os, indent );
	os << " ... ";
	high->print( os, indent );
	Expression::print( os, indent );
}

StmtExpr::StmtExpr( CompoundStmt *statements ) : statements( statements ) {
	assert( statements );
	std::list< Statement * > & body = statements->get_kids();
	if ( ! body.empty() ) {
		if ( ExprStmt * exprStmt = dynamic_cast< ExprStmt * >( body.back() ) ) {
			set_result( maybeClone( exprStmt->get_expr()->get_result() ) );
		}
	}
}
StmtExpr::StmtExpr( const StmtExpr &other ) : Expression( other ), statements( other.statements->clone() ) {
	cloneAll( other.returnDecls, returnDecls );
	cloneAll( other.dtors, dtors );
}
StmtExpr::~StmtExpr() {
	delete statements;
	deleteAll( dtors );
	deleteAll( returnDecls );
}
void StmtExpr::print( std::ostream &os, int indent ) const {
	os << "Statement Expression: " << std::endl << std::string( indent, ' ' );
	statements->print( os, indent+2 );
	if ( ! returnDecls.empty() ) {
		os << std::string( indent+2, ' ' ) << "with returnDecls: ";
		printAll( returnDecls, os, indent+2 );
	}
	if ( ! dtors.empty() ) {
		os << std::string( indent+2, ' ' ) << "with dtors: ";
		printAll( dtors, os, indent+2 );
	}
	Expression::print( os, indent );
}


long long UniqueExpr::count = 0;
UniqueExpr::UniqueExpr( Expression *expr, long long idVal ) : expr( expr ), object( nullptr ), var( nullptr ), id( idVal ) {
	assert( expr );
	assert( count != -1 );
	if ( id == -1 ) id = count++;
	if ( expr->get_result() ) {
		set_result( expr->get_result()->clone() );
	}
}
UniqueExpr::UniqueExpr( const UniqueExpr &other ) : Expression( other ), expr( maybeClone( other.expr ) ), object( maybeClone( other.object ) ), var( maybeClone( other.var ) ), id( other.id ) {
}
UniqueExpr::~UniqueExpr() {
	delete expr;
	delete object;
	delete var;
}
void UniqueExpr::print( std::ostream &os, int indent ) const {
	os << "Unique Expression with id:" << id << std::endl << std::string( indent+2, ' ' );
	get_expr()->print( os, indent+2 );
	if ( get_object() ) {
		os << std::string( indent+2, ' ' ) << "with decl: ";
		get_object()->printShort( os, indent+2 );
	}
	Expression::print( os, indent );
}

std::ostream & operator<<( std::ostream & out, const Expression * expr ) {
	if ( expr ) {
		expr->print( out );
	} else {
		out << "nullptr";
	}
	return out;
}

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