/*
 * 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_jitcraft_scopes_h_
#define _include_jitcraft_scopes_h_

#include <vector>
#include "PoolAllocator.h"
#include "AST.h"
#include "NameBinding.h"

namespace jc {

class Scope : public PoolObject
{
    PoolAllocator &pool_;
    std::vector<BoundName *> names_;
    std::vector<Scope *> children_;
    std::vector<Variable *> parameters_;
    unsigned locals_;
    unsigned maxContainedLocals_;
    unsigned numFunctions_;

    bool empty() const {
        return names_.size() == 0;
    }
    void unlink();

  public:
    enum Kind {
        GLOBAL,
        FUNCTION,
        BLOCK
    };

  public:
    Scope(PoolAllocator &pool, Kind kind, Scope *enclosing);
    bool initialize();

    Kind kind() const {
        return kind_;
    }
    Scope *enclosing() const {
        return enclosing_;
    }
    unsigned locals() const {
        return locals_;
    }
    unsigned maxContainedLocals() const {
        return maxContainedLocals_;
    }
    unsigned numFunctions() const {
        return numFunctions_;
    }
    unsigned numArguments() const {
        return parameters_.size();
    }
    Variable *getArgument(size_t index) {
        return parameters_[index];
    }

    Scope *unlinkIfEmpty();
    BoundName *localLookup(Name *name);
    BoundName *lookup(Name *name);
    NamedFunction *declareFunction(Name *name);
    Variable *declareVariable(Name *name);
    Variable *declareArgument(Name *name);
    void allocate();
    void allocateGlobals();

  public:
    static bool BindAndAllocate(ParseTree *tree);

  private:
    Kind kind_;
    Scope *enclosing_;
};

}

#endif // _include_jitcraft_scopes_h_
