/* vim: set ts=4 sw=4 tw=99 et:
 *
 * Copyright (C) 2012 David Anderson
 *
 * This file is part of JITCraft.
 *
 * JITCraft is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 * 
 * Foobar 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. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * JITCraft. If not, see http://www.gnu.org/licenses/.
 */
#include <stdio.h>
#include <stdlib.h>
#include "RootScopes.h"

using namespace ke;

RootScopeManager::RootScopeManager()
  : blocks_(&first_),
    first_(NULL),
    scope_(NULL)
{
}

RootScopeManager::~RootScopeManager()
{
    while (blocks_ != &first_) {
        Block *temp = blocks_;
        delete blocks_;
        blocks_ = temp;
    }
}

bool
RootScopeManager::grow()
{
    assert(blocks_->cur == blocks_->end);

    Block *block = new Block(blocks_);
    if (!block) {
        // We are not prepared for this. We'll start dishing out NULL-valued
        // ScopedRoots, and the engine generally assumes infallbility. Rather
        // then NULL check all sorts of nodes on parse trees, or add boolean
        // setters, for now we just abort.
        fprintf(stderr, "Unrecoverable error: could not allocate a local root scope. Aborting!\n");
        abort();
        return false;
    }

    blocks_ = block;
    return true;
}

void
RootScopeManager::unwindSlow(Object **pos)
{
    for (;;) {
        if (pos >= blocks_->objects && pos <= blocks_->end)
            break;
        assert(blocks_ != &first_);
        Block *temp = blocks_;
        delete blocks_;
        blocks_ = temp;
    }

    blocks_->cur = pos;
}

void
RootScopeManager::accept(VirtualObjectVisitor *visitor)
{
    Block *block = blocks_;
    while (block) {
        for (Object **ptr = block->objects; ptr < block->cur; ptr++)
            visitor->visit(ptr);
        block = block->prev;
    }
}
