/*
 * 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/.
 */
#ifndef _include_jc_code_h_
#define _include_jc_code_h_

#include "Opcodes.h"
#include "Barriers.h"
#include "Heap.h"
#include "Types.h"
#include "FixedArray.h"

namespace jc {

class Module;
class Type;

// A code object contains the bytecode compiled from a function (or global
// script), as well as all information needed to interpret or JIT-compile
// the bytecode.
class Code : public Object
{
    Module *module_;
    Unbarriered<ByteArray> bytecode_;
    Unbarriered<FixedArray> locals_;
    Unbarriered<FixedArray> args_;
    Unbarriered<FixedArray> maps_;
    unsigned maxStackDepth_;

  public:
    // :TODO: use handles
    static Code *New(Zone *zone, ByteArray *bytecode, FixedArray *locals, FixedArray *args,
                     FixedArray *maps, unsigned maxStackDepth, Module *module);

    Module *module() {
        return module_;
    }
    bytecode *start() {
        return bytecode_->raw();
    }
    unsigned length() {
        return bytecode_->length();
    }
    Type *localType(size_t index) {
        return Type::cast(locals_->at(index));
    }
    Type *argType(size_t index) {
        return Type::cast(args_->at(index));
    }
    unsigned nlocals() {
        return locals_->length();
    }
    unsigned nargs() {
        return args_->length();
    }
    unsigned maxStackDepth() {
        return maxStackDepth_;
    }
    Map *map(size_t index) {
        return Map::cast(maps_->at(index));
    }

    static Code *cast(Object *obj) {
        assert(!obj || obj->is(MapKind_Code));
        return reinterpret_cast<Code *>(obj);
    }
};

}

#endif // _include_jc_code_h_
