ruby/engine/RubyEngine.cpp
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | /*********************************************************************************************************************** | ||
| 2 | * OpenStudio(R), Copyright (c) Alliance for Energy Innovation, LLC. | ||
| 3 | * See also https://openstudio.net/license | ||
| 4 | ***********************************************************************************************************************/ | ||
| 5 | |||
| 6 | #include "RubyEngine.hpp" | ||
| 7 | #include "../bindings/InitRubyBindings.hpp" | ||
| 8 | #include "../interpreter/RubyException.hpp" | ||
| 9 | #include <embedded_files.hxx> | ||
| 10 | #include <csignal> | ||
| 11 | #include <stdexcept> | ||
| 12 | #include <string> | ||
| 13 | #include <ctime> | ||
| 14 | |||
| 15 | #ifdef __GNUC__ | ||
| 16 | # pragma GCC diagnostic push | ||
| 17 | # pragma GCC diagnostic ignored "-Wregister" | ||
| 18 | # pragma GCC diagnostic ignored "-Wunused-parameter" | ||
| 19 | #endif | ||
| 20 | |||
| 21 | #ifdef __GNUC__ | ||
| 22 | # pragma GCC diagnostic pop | ||
| 23 | #endif | ||
| 24 | |||
| 25 | #include <fmt/format.h> | ||
| 26 | |||
| 27 | // TODO: We need to revisit this static initialization stuff | ||
| 28 | static int argc = 0; | ||
| 29 | static char** argv = nullptr; | ||
| 30 | |||
| 31 | 245 | unsigned init() { | |
| 32 | 245 | ruby_sysinit(&argc, &argv); | |
| 33 | 245 | ruby_setup(); | |
| 34 | 245 | return 0u; | |
| 35 | } | ||
| 36 | |||
| 37 | static unsigned i = init(); | ||
| 38 | |||
| 39 | extern "C" | ||
| 40 | { | ||
| 41 | void Init_EmbeddedScripting(void); | ||
| 42 | } | ||
| 43 | |||
| 44 | namespace openstudio { | ||
| 45 | |||
| 46 | 238 | VALUE initRestOfOpenStudio(...) { | |
| 47 | 238 | openstudio::ruby::initExtendedRubyBindings(); | |
| 48 | 238 | return Qtrue; | |
| 49 | }; | ||
| 50 | |||
| 51 |
1/1✓ Branch 3 taken 245 times.
|
245 | RubyEngine::RubyEngine(int argc, char* argv[]) : ScriptEngine(argc, argv) { |
| 52 | |||
| 53 |
1/1✓ Branch 1 taken 245 times.
|
245 | ruby_set_argv(argc, argv); |
| 54 |
1/1✓ Branch 1 taken 245 times.
|
245 | Init_EmbeddedScripting(); |
| 55 | |||
| 56 |
1/1✓ Branch 1 taken 245 times.
|
245 | initRubyEngine(); |
| 57 | |||
| 58 |
1/1✓ Branch 1 taken 245 times.
|
245 | openstudio::ruby::initBasicRubyBindings(); |
| 59 | |||
| 60 |
1/1✓ Branch 1 taken 245 times.
|
245 | auto rubymodule = rb_define_module("OpenStudio"); |
| 61 |
1/1✓ Branch 1 taken 245 times.
|
245 | rb_define_module_function(rubymodule, "init_rest_of_openstudio", initRestOfOpenStudio, 0); |
| 62 | |||
| 63 |
1/1✓ Branch 1 taken 245 times.
|
245 | ruby_set_argv(argc, argv); |
| 64 | |||
| 65 | // DLM: this will interpret any strings passed on the command line as UTF-8 | ||
| 66 | // can we be smarter and detect the correct encoding? use wmain on windows to get utf-16? | ||
| 67 | // or we might want to follow ruby and allow '--external-encoding=UTF-8' as an input argument? | ||
| 68 |
3/3✓ Branch 1 taken 245 times.
✓ Branch 4 taken 245 times.
✓ Branch 7 taken 245 times.
|
245 | rb_enc_set_default_external(rb_enc_from_encoding(rb_utf8_encoding())); |
| 69 | 245 | } | |
| 70 | |||
| 71 | 223 | void RubyEngine::setupEmbeddedGems(const std::vector<openstudio::path>& includeDirs, const std::vector<openstudio::path>& gemPathDirs, | |
| 72 | const openstudio::path& gemHomeDir, const openstudio::path& bundleGemFilePath, | ||
| 73 | const openstudio::path& bundleGemDirPath, const std::string& bundleWithoutGroups) { | ||
| 74 | 223 | openstudio::ruby::setupEmbeddedGems(includeDirs, gemPathDirs, gemHomeDir, bundleGemFilePath, bundleGemDirPath, bundleWithoutGroups); | |
| 75 | 222 | } | |
| 76 | |||
| 77 | 484 | RubyEngine::~RubyEngine() { | |
| 78 | // ruby_cleanup calls ruby_finalize | ||
| 79 | 242 | int ex = ruby_cleanup(0); | |
| 80 |
2/2✓ Branch 0 taken 6 times.
✓ Branch 1 taken 234 times.
|
240 | if (ex != 0) { |
| 81 | // fmt::print("RubyEngine return code was {}\n", ex); | ||
| 82 | 6 | exit(ex); | |
| 83 | } | ||
| 84 | //ruby_finalize(); | ||
| 85 | 476 | } | |
| 86 | |||
| 87 | 229 | ScriptObject RubyEngine::eval(std::string_view sv) { | |
| 88 |
1/1✓ Branch 1 taken 229 times.
|
229 | std::string str{sv}; |
| 89 |
2/2✓ Branch 1 taken 229 times.
✓ Branch 4 taken 229 times.
|
458 | return ScriptObject{openstudio::evalString(str)}; |
| 90 | 229 | } | |
| 91 | |||
| 92 | 323 | void RubyEngine::exec(std::string_view sv) { | |
| 93 |
1/1✓ Branch 1 taken 323 times.
|
323 | std::string str{sv}; |
| 94 |
1/1✓ Branch 1 taken 323 times.
|
323 | [[maybe_unused]] const auto result = openstudio::evalString(str); |
| 95 | 323 | } | |
| 96 | |||
| 97 | // convert the underlying object to the correct type, then return it as a void * | ||
| 98 | // so the above template function can provide it back to the caller. | ||
| 99 | 40 | void* RubyEngine::getAs_impl(ScriptObject& obj, const std::type_info& ti) { | |
| 100 |
1/1✓ Branch 1 taken 40 times.
|
40 | auto val = std::any_cast<VALUE>(obj.object); |
| 101 | |||
| 102 | 40 | void* return_value = nullptr; | |
| 103 | |||
| 104 |
1/1✓ Branch 1 taken 40 times.
|
40 | const auto& type_name = getRegisteredTypeName(ti); |
| 105 | |||
| 106 |
1/1✓ Branch 2 taken 40 times.
|
40 | auto* type = SWIG_TypeQuery(type_name.c_str()); |
| 107 | |||
| 108 |
1/2✗ Branch 0 not taken.
✓ Branch 1 taken 40 times.
|
40 | if (!type) { |
| 109 | ✗ | throw std::runtime_error("Unable to find type in SWIG"); | |
| 110 | } | ||
| 111 | |||
| 112 |
1/1✓ Branch 1 taken 40 times.
|
40 | const auto result = SWIG_ConvertPtr(val, &return_value, type, 0); |
| 113 | |||
| 114 |
1/2✗ Branch 0 not taken.
✓ Branch 1 taken 40 times.
|
40 | if (!SWIG_IsOK(result)) { |
| 115 | ✗ | throw std::runtime_error("Error getting object from SWIG/Ruby"); | |
| 116 | } | ||
| 117 | 40 | return return_value; | |
| 118 | } | ||
| 119 | |||
| 120 | ✗ | bool RubyEngine::getAs_impl_bool(ScriptObject& obj) { | |
| 121 | ✗ | auto val = std::any_cast<VALUE>(obj.object); | |
| 122 | ✗ | return RB_TEST(val); | |
| 123 | } | ||
| 124 | |||
| 125 | 187 | int RubyEngine::getAs_impl_int(ScriptObject& obj) { | |
| 126 | 187 | auto val = std::any_cast<VALUE>(obj.object); | |
| 127 |
1/2✗ Branch 0 not taken.
✓ Branch 1 taken 187 times.
|
187 | if (!RB_FIXNUM_P(val)) { |
| 128 | ✗ | throw std::runtime_error("VALUE is not a FIXNUM"); | |
| 129 | } | ||
| 130 | |||
| 131 | 187 | return RB_NUM2INT(val); | |
| 132 | } | ||
| 133 | ✗ | double RubyEngine::getAs_impl_double(ScriptObject& obj) { | |
| 134 | ✗ | auto val = std::any_cast<VALUE>(obj.object); | |
| 135 | ✗ | if (!RB_FLOAT_TYPE_P(val)) { | |
| 136 | ✗ | throw std::runtime_error("VALUE is not a FLOAT"); | |
| 137 | } | ||
| 138 | |||
| 139 | ✗ | return RB_NUM2INT(val); | |
| 140 | } | ||
| 141 | |||
| 142 | ✗ | std::string RubyEngine::getAs_impl_string(ScriptObject& obj) { | |
| 143 | ✗ | auto val = std::any_cast<VALUE>(obj.object); | |
| 144 | |||
| 145 | ✗ | if (!RB_TYPE_P(val, RUBY_T_STRING)) { | |
| 146 | ✗ | throw std::runtime_error("VALUE is not a String"); | |
| 147 | } | ||
| 148 | |||
| 149 | ✗ | char* cstr = StringValuePtr(val); | |
| 150 | ✗ | size_t size = RSTRING_LEN(val); // + 1; From trial and eror, if I had + 1 I get a string with one two many size | |
| 151 | ✗ | return std::string{cstr, size}; | |
| 152 | } | ||
| 153 | |||
| 154 | ✗ | std::string RubyEngine::inferMeasureClassName(const openstudio::path& measureScriptPath) { | |
| 155 | |||
| 156 | auto inferClassNameCmd = fmt::format(R"ruby( | ||
| 157 | ObjectSpace.garbage_collect | ||
| 158 | ObjectSpace.garbage_collect | ||
| 159 | # Measure should be at root level (not inside a module) so we can just get constants | ||
| 160 | measurePath = '{}' | ||
| 161 | prev = Object.constants | ||
| 162 | # puts "prev = #{{prev}}" | ||
| 163 | load measurePath # need load in case have seen this script before | ||
| 164 | just_defined = Object.constants - prev | ||
| 165 | # puts "just_defined = #{{just_defined}}" | ||
| 166 | just_defined.select!{{|c| Object.const_get(c).ancestors.include?(OpenStudio::Measure::OSMeasure)}} | ||
| 167 | # puts "just_defined, filtered = #{{just_defined}}" | ||
| 168 | |||
| 169 | if just_defined.empty? | ||
| 170 | raise "Unable to extract OpenStudio::Measure::OSMeasure object from " + | ||
| 171 | measurePath + ". The script should contain a class that derives " + | ||
| 172 | "from OpenStudio::Measure::OSMeasure and should close with a line stating " + | ||
| 173 | "the class name followed by .new.registerWithApplication." | ||
| 174 | end | ||
| 175 | if just_defined.size > 1 | ||
| 176 | raise "Found more than one OSMeasure at #{{measurePath}}: #{{just_defined}}" | ||
| 177 | end | ||
| 178 | c = just_defined[0] | ||
| 179 | class_info = Object.const_get(c) | ||
| 180 | $measure_name = class_info.to_s | ||
| 181 | |||
| 182 | # Undef what we loaded | ||
| 183 | just_defined.each {{|x| Object.send(:remove_const, x) }} | ||
| 184 | ObjectSpace.garbage_collect | ||
| 185 | ObjectSpace.garbage_collect | ||
| 186 | )ruby", | ||
| 187 | ✗ | measureScriptPath.generic_string()); | |
| 188 | |||
| 189 | ✗ | std::string className; | |
| 190 | |||
| 191 | try { | ||
| 192 | ✗ | exec(inferClassNameCmd); | |
| 193 | ✗ | ScriptObject measureClassNameObject = eval("$measure_name"); | |
| 194 | // measureClassNameObject = rubyEngine->eval(fmt::format("{}.new()", className)); | ||
| 195 | // ScriptObject measureClassNameObject = rubyEngine->eval(inferClassName); | ||
| 196 | ✗ | className = getAs<std::string>(measureClassNameObject); | |
| 197 | ✗ | } catch (const RubyException& e) { | |
| 198 | ✗ | auto msg = fmt::format("Failed to infer measure name from {}: {}\nlocation={}", measureScriptPath.generic_string(), e.what(), e.location()); | |
| 199 | ✗ | fmt::print(stderr, "{}\n", msg); | |
| 200 | ✗ | } | |
| 201 | |||
| 202 | ✗ | return className; | |
| 203 | ✗ | } | |
| 204 | |||
| 205 | // Ideally this would return a openstudio::measure::OSMeasure* or a shared_ptr<openstudio::measure::OSMeasure> but this poses memory management | ||
| 206 | // issue for the underlying ScriptObject (and VALUE or PyObject), so just return the ScriptObject | ||
| 207 | 42 | ScriptObject RubyEngine::loadMeasure(const openstudio::path& measureScriptPath, std::string_view className) { | |
| 208 | |||
| 209 | 42 | ScriptObject result; | |
| 210 | try { | ||
| 211 |
1/1✓ Branch 1 taken 42 times.
|
84 | auto importCmd = fmt::format("load '{}'", measureScriptPath.generic_string()); |
| 212 |
1/1✓ Branch 2 taken 42 times.
|
42 | exec(importCmd); |
| 213 |
0/2✗ Branch 2 not taken.
✗ Branch 3 not taken.
|
42 | } catch (const RubyException& e) { |
| 214 | auto msg = | ||
| 215 | ✗ | fmt::format("Failed to load measure '{}' from '{}': {}\nlocation={}", className, measureScriptPath.generic_string(), e.what(), e.location()); | |
| 216 | ✗ | fmt::print(stderr, "{}\n", msg); | |
| 217 | ✗ | } | |
| 218 | try { | ||
| 219 |
1/1✓ Branch 3 taken 42 times.
|
84 | result = eval(fmt::format("{}.new()", className)); |
| 220 | ✗ | } catch (const RubyException& e) { | |
| 221 | ✗ | auto msg = fmt::format("Failed to instantiate measure '{}' from '{}': {}\nlocation={}", className, measureScriptPath.generic_string(), e.what(), | |
| 222 | ✗ | e.location()); | |
| 223 | ✗ | fmt::print(stderr, "{}\n", msg); | |
| 224 | ✗ | } | |
| 225 | 42 | return result; | |
| 226 | ✗ | } | |
| 227 | |||
| 228 | 24 | int RubyEngine::numberOfArguments(ScriptObject& methodObject, std::string_view methodName) { | |
| 229 | 24 | auto val = std::any_cast<VALUE>(methodObject.object); | |
| 230 | 24 | ID method_id = rb_intern(methodName.data()); | |
| 231 | // Ruby IS SO WEIRD. This will return n for methods that take a fixed number of arguments, and -n - 1 where n is the number of required arguments... | ||
| 232 | // def f() => 0 | ||
| 233 | // def f(a) => 1 | ||
| 234 | // def f(a = nil) => -1! Because WHY NOT, right? | ||
| 235 | // def f(a, c = nil) => -2 | ||
| 236 | // def f(a, b = nil, c = nil) => also -2 | ||
| 237 | 24 | return rb_obj_method_arity(val, method_id); | |
| 238 | } | ||
| 239 | |||
| 240 | 12 | bool RubyEngine::hasMethod(ScriptObject& methodObject, std::string_view methodName, bool overriden_only) { | |
| 241 |
1/1✓ Branch 1 taken 12 times.
|
12 | auto val = std::any_cast<VALUE>(methodObject.object); |
| 242 |
1/1✓ Branch 2 taken 12 times.
|
12 | ID method_id = rb_intern(methodName.data()); |
| 243 |
3/3✓ Branch 1 taken 12 times.
✓ Branch 3 taken 2 times.
✓ Branch 4 taken 10 times.
|
12 | if (rb_respond_to(val, method_id) == 0) { |
| 244 | 2 | return false; | |
| 245 | } | ||
| 246 |
2/2✓ Branch 0 taken 2 times.
✓ Branch 1 taken 8 times.
|
10 | if (!overriden_only) { |
| 247 | 2 | return true; | |
| 248 | } | ||
| 249 | |||
| 250 | // I'd have prefered to do the equivalent of `instance_obj.method(:methodName).owner == instance_obj.class` but that is borderline impossible | ||
| 251 | // Instead, this is equivalent to `instance_obj.class.instance_methods(false).include?(:methodName)` | ||
| 252 |
1/1✓ Branch 1 taken 8 times.
|
8 | VALUE klass = rb_obj_class(val); |
| 253 | // include_methods_from_ancestors: false; | ||
| 254 | 8 | VALUE args[1] = {Qfalse}; | |
| 255 |
1/1✓ Branch 1 taken 8 times.
|
8 | VALUE methods_without_ancestors = rb_class_instance_methods(1, args, klass); |
| 256 |
2/2✓ Branch 1 taken 8 times.
✓ Branch 4 taken 8 times.
|
8 | return rb_ary_includes(methods_without_ancestors, ID2SYM(method_id)) == Qtrue; |
| 257 | } | ||
| 258 | |||
| 259 | } // namespace openstudio | ||
| 260 | |||
| 261 | extern "C" | ||
| 262 | { | ||
| 263 | 245 | openstudio::ScriptEngine* makeScriptEngine(int argc, char* argv[]) { | |
| 264 |
1/3✓ Branch 2 taken 245 times.
✗ Branch 4 not taken.
✗ Branch 5 not taken.
|
245 | return new openstudio::RubyEngine(argc, argv); |
| 265 | } | ||
| 266 | |||
| 267 | 1490 | int rb_hasFile(const char* t_filename) { | |
| 268 | // TODO Consider expanding this to use the path which we have artificially defined in embedded_help.rb | ||
| 269 | 1490 | std::string expandedName = fmt::format(":/ruby/3.2.0/{}.rb", t_filename); | |
| 270 |
3/3✓ Branch 1 taken 1490 times.
✓ Branch 3 taken 62 times.
✓ Branch 4 taken 1428 times.
|
2980 | return embedded_files::hasFile(expandedName) ? 1 : 0; |
| 271 | 1490 | } | |
| 272 | |||
| 273 | 62 | int rb_require_embedded(const char* t_filename) { | |
| 274 | 62 | std::string require_script = fmt::format("require '{}'", t_filename); | |
| 275 |
1/1✓ Branch 1 taken 62 times.
|
62 | openstudio::evalString(require_script); |
| 276 | 62 | return 0; | |
| 277 | 62 | } | |
| 278 | } | ||
| 279 |