// ---------------------------------------------------------------------------
// - Stack.cpp                                                               -
// - standard object library - object stack class implementation             -
// ---------------------------------------------------------------------------
// - This program is free software;  you can redistribute it  and/or  modify -
// - it provided that this copyright notice is kept intact.                  -
// -                                                                         -
// - This program  is  distributed in  the hope  that it will be useful, but -
// - without  any  warranty;  without  even   the   implied    warranty   of -
// - merchantability or fitness for a particular purpose.  In no event shall -
// - the copyright holder be liable for any  direct, indirect, incidental or -
// - special damages arising in any way out of the use of this software.     -
// ---------------------------------------------------------------------------
// - copyright (c) 1999-2019 amaury darsch                                   -
// ---------------------------------------------------------------------------

#include "Stack.hpp"
#include "Vector.hpp"
#include "Boolean.hpp"
#include "Runnable.hpp"
#include "QuarkZone.hpp"
#include "Exception.hpp"
#include "cmem.hpp"

namespace afnix {
  
  // -------------------------------------------------------------------------
  // - class section                                                         -
  // -------------------------------------------------------------------------

  // create a default stack
  
  Stack::Stack (void) {
    d_size = 8 * c_pagesize ();
    p_base = (Object**) c_mmap (d_size * sizeof (Object*));
    p_top  = p_base + d_size - 1;
    p_sp   = p_base;
  }
  
  // destroy this stack

  Stack::~Stack (void) {
    unwind ();
    c_munmap (p_base, d_size * sizeof (Object*));
  }

  // return the class name

  String Stack::repr (void) const {
    return "Stack";
  }

  // push an object on top of the stack

  void Stack::push (Object* object) {
    wrlock ();
    try {
      // check for stack overflow
      if (p_sp >= p_top) resize (d_size * 2);
      // push the object
      *p_sp++ = Object::iref (object);
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // pop an object from the stack

  Object* Stack::pop (void) {
    wrlock ();
    try {
      if (p_sp == p_base) {
	throw Exception ("stack-error","out of bound stack pop");
      }
      Object* result = *--p_sp;
      Object::tref (result);
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // return true if the stack is empty

  bool Stack::empty (void) const {
    rdlock ();
    bool result = (p_sp == p_base);
    unlock ();
    return result;
  }

  // resize the stack by a certain amount

  void Stack::resize (const long size) {
    wrlock ();
    try {
      // check the requested size
      if ((size <= 0) || (size <= d_size)) {
	throw Exception ("stack-error", "invalid stack size requested");
      }
      // recompute the offset and remap
      long spoff = (long) (p_sp - p_base);
      p_base = (Object**) c_mremap (p_base, d_size * sizeof (Object*), 
				    size * sizeof (Object*));
      p_top  = p_base + size - 1;
      d_size = size;
      p_sp   = p_base + spoff;
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // unwind the stack to it base pointer

  void Stack::unwind (void) {
    wrlock ();
    try {
      while (p_sp != p_base) Object::cref (pop ());
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // -------------------------------------------------------------------------
  // - object section                                                        -
  // -------------------------------------------------------------------------

  // the quark zone
  static const long QUARK_ZONE_LENGTH = 4;
  static QuarkZone  zone (QUARK_ZONE_LENGTH);

  // the object supported quarks
  static const long QUARK_POP    = zone.intern ("pop");
  static const long QUARK_PUSH   = zone.intern ("push");
  static const long QUARK_UNWIND = zone.intern ("unwind");
  static const long QUARK_EMPTYP = zone.intern ("empty-p");

  // create a new object in a generic way

  Object* Stack::mknew (Vector* argv) {
    // get the number of arguments
    long argc = (argv == nullptr) ? 0 : argv->length ();
    // check for 0 argument
    if (argc == 0) return new Stack;
    // too many arguments
    throw Exception ("argument-error", 
		     "too many argument with stack constructor");
  }

  // return true if the given quark is defined

  bool Stack::isquark (const long quark, const bool hflg) const {
    rdlock ();
    if (zone.exists (quark) == true) {
      unlock ();
      return true;
    }
    bool result = hflg ? Object::isquark (quark, hflg) : false;
    unlock ();
    return result;
  }

  // apply this object with a set of arguments and a quark
  
  Object* Stack::apply (Runnable* robj, Nameset* nset, const long quark,
			 Vector* argv) {
    // get the number of arguments
    long argc = (argv == nullptr) ? 0 : argv->length ();
    
    // dispatch 0 argument
    if (argc == 0) {
      if (quark == QUARK_EMPTYP) return new Boolean (empty  ());
      if (quark == QUARK_UNWIND) {
	unwind ();
	return nullptr;
      }
      if (quark == QUARK_POP) {
	wrlock ();
	try {
	  Object* result = pop ();
	  robj->post (result);
	  unlock ();
	  return result;
	} catch (...) {
	  unlock ();
	  throw;
	}
      }
    }
    // dispatch 1 argument
    if (argc == 1) {
      if (quark == QUARK_PUSH) {
	Object* obj = argv->get (0);
	push (obj);
	return nullptr;
      }
    }
    // call the object method
    return Object::apply (robj, nset, quark, argv);
  }
}
