public
Description: Rubinius, the Ruby VM
Homepage: http://rubini.us
Clone URL: git://github.com/evanphx/rubinius.git
rubinius / vm / environment.cpp
100644 60 lines (45 sloc) 1.524 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include "environment.hpp"
#include "compiled_file.hpp"
 
#include <iostream>
#include <fstream>
#include <string>
 
namespace rubinius {
  Environment::Environment() {
    state = new VM();
  }
 
  Environment::~Environment() {
    delete state;
  }
 
 
  void Environment::load_argv(int argc, char** argv) {
    state->set_const("ARG0", String::create(state, argv[0]));
    
    Array* ary = Array::create(state, argc - 1);
    for(size_t i = 0; i < argc - 1; i++) {
      ary->set(state, i, String::create(state, argv[i + 1]));
    }
 
    state->set_const("ARGV", ary);
  }
 
  void Environment::load_directory(std::string dir) {
    std::string path = dir + "/.load_order.txt";
    std::ifstream stream(path.c_str());
    if(!stream) throw std::runtime_error("Unable to load directory");
 
    std::string line;
 
    while(!stream.eof()) {
      stream >> line;
      std::cout << "Loading: " << line << std::endl;
      run_file(dir + "/" + line);
    }
  }
 
  void Environment::run_file(std::string file) {
    std::ifstream stream(file.c_str());
    if(!stream) throw std::runtime_error("Unable to open file to run");
 
    CompiledFile* cf = CompiledFile::load(stream);
    if(cf->magic != "!RBIX") throw std::runtime_error("Invalid file");
 
    // TODO check version number
 
    if(CompiledMethod* cm = try_as<CompiledMethod>(cf->body(state))) {
      Task* task = Task::create(state, G(main), cm);
      task->execute();
    } else {
      throw std::runtime_error("Invalid file, body not a CompiledMethod.");
    }
  }
}