Example #1
0
  public void load(final Ruby ruby, boolean bln) {
    this.ruby = ruby;

    RubyModule nio = ruby.defineModule("NIO");

    RubyClass selector =
        ruby.defineClassUnder(
            "Selector",
            ruby.getObject(),
            new ObjectAllocator() {
              public IRubyObject allocate(Ruby ruby, RubyClass rc) {
                return new Selector(ruby, rc);
              }
            },
            nio);

    selector.defineAnnotatedMethods(Selector.class);

    RubyClass monitor =
        ruby.defineClassUnder(
            "Monitor",
            ruby.getObject(),
            new ObjectAllocator() {
              public IRubyObject allocate(Ruby ruby, RubyClass rc) {
                return new Monitor(ruby, rc);
              }
            },
            nio);

    monitor.defineAnnotatedMethods(Monitor.class);
  }
Example #2
0
 public static void createConfig(Ruby runtime, RubyModule mOSSL) {
   RubyClass cConfig =
       mOSSL.defineClassUnder("Config", runtime.getObject(), runtime.getObject().getAllocator());
   cConfig.defineAnnotatedMethods(Config.class);
   RubyClass openSSLError = mOSSL.getClass("OpenSSLError");
   mOSSL.defineClassUnder("ConfigError", openSSLError, openSSLError.getAllocator());
   // TODO: we should define this constant with proper path. (see above)
   // cConfig.setConstant("DEFAULT_CONFIG_FILE", runtime.newString(DEFAULT_CONFIG_FILE));
 }
Example #3
0
  public static void createTemplate(Ruby runtime, RubyModule mASN1) {
    mTemplate = runtime.defineModuleUnder("Template", mASN1);
    RubyModule mParser = runtime.defineModuleUnder("Parser", mTemplate);
    cTemplateValue =
        mTemplate.defineClassUnder(
            "Value", runtime.getObject(), ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR);

    CODEC = runtime.newSymbol("codec");
    OPTIONS = runtime.newSymbol("options");
    DEFAULT = runtime.newSymbol("default");
    NAME = runtime.newSymbol("name");
    TYPE = runtime.newSymbol("type");
    OPTIONAL = runtime.newSymbol("optional");
    TAG = runtime.newSymbol("tag");
    TAGGING = runtime.newSymbol("tagging");
    LAYOUT = runtime.newSymbol("layout");
    MIN_SIZE = runtime.newSymbol("min_size");

    CODEC_PRIMITIVE = runtime.newSymbol("PRIMITIVE");
    CODEC_TEMPLATE = runtime.newSymbol("TEMPLATE");
    CODEC_SEQUENCE = runtime.newSymbol("SEQUENCE");
    CODEC_SET = runtime.newSymbol("SET");
    CODEC_SEQUENCE_OF = runtime.newSymbol("SEQUENCE_OF");
    CODEC_SET_OF = runtime.newSymbol("SET_OF");
    CODEC_ANY = runtime.newSymbol("ANY");
    CODEC_CHOICE = runtime.newSymbol("CHOICE");

    mTemplate.defineAnnotatedMethods(RubyAsn1Template.class);
    mParser.defineAnnotatedMethods(TemplateParser.class);
    cTemplateValue.defineAnnotatedMethods(RubyAsn1Template.class);
  }
Example #4
0
  @Override
  public IRubyObject interpret(
      Ruby runtime, ThreadContext context, IRubyObject self, Block aBlock) {
    // Serialization killed our dynamic scope.  We can just create an empty one
    // since serialization cannot serialize an eval (which is the only thing
    // which is capable of having a non-empty dynamic scope).
    if (scope == null) {
      scope = DynamicScope.newDynamicScope(staticScope);
    }

    StaticScope theStaticScope = scope.getStaticScope();

    // Each root node has a top-level scope that we need to push
    context.preScopedBody(scope);

    if (theStaticScope.getModule() == null) {
      theStaticScope.setModule(runtime.getObject());
    }

    try {
      return bodyNode.interpret(runtime, context, self, aBlock);
    } finally {
      context.postScopedBody();
    }
  }
 private Object cache(
     ThreadContext context,
     DynamicScope currDynScope,
     IRubyObject self,
     Object[] temp,
     Ruby runtime,
     Object constant) {
   StaticScope staticScope =
       (StaticScope) definingScope.retrieve(context, self, currDynScope, temp);
   RubyModule object = runtime.getObject();
   // SSS FIXME: IRManager objects dont have a static-scope yet, so this hack of looking up the
   // module right away
   // This IR needs fixing!
   constant =
       (staticScope == null)
           ? object.getConstant(constName)
           : staticScope.getConstantInner(runtime, constName, object);
   if (constant == null) {
     constant = UndefinedValue.UNDEFINED;
   } else {
     // recache
     generation = runtime.getConstantInvalidator().getData();
     cachedConstant = constant;
   }
   return constant;
 }
Example #6
0
  public void load(Ruby runtime, boolean wrap) throws IOException {
    RubyModule timeout = runtime.defineModule("Timeout");
    RubyClass superclass = runtime.getRuntimeError();
    RubyClass timeoutError =
        runtime.defineClassUnder("Error", superclass, superclass.getAllocator(), timeout);
    runtime.defineClassUnder(
        "ExitException", runtime.getException(), runtime.getException().getAllocator(), timeout);

    // Here we create an "anonymous" exception type used for unrolling the stack.
    // MRI creates a new one for *every call* to timeout, which can be costly.
    // We opt to use a single exception type for all cases to avoid this overhead.
    RubyClass anonEx =
        runtime.defineClassUnder(
            "AnonymousException",
            runtime.getException(),
            runtime.getException().getAllocator(),
            timeout);
    anonEx.setBaseName(null); // clear basename so it's anonymous when raising

    // These are not really used by timeout, but exposed for compatibility
    timeout.defineConstant(
        "THIS_FILE", RubyRegexp.newRegexp(runtime, "timeout\\.rb", new RegexpOptions()));
    timeout.defineConstant("CALLER_OFFSET", RubyFixnum.newFixnum(runtime, 0));

    // Timeout module methods
    timeout.defineAnnotatedMethods(Timeout.class);

    // Toplevel defines
    runtime.getObject().defineConstant("TimeoutError", timeoutError);
    runtime.getObject().defineAnnotatedMethods(TimeoutToplevel.class);
  }
Example #7
0
  public static void createX509CRL(Ruby runtime, RubyModule mX509) {
    RubyClass cX509CRL = mX509.defineClassUnder("CRL", runtime.getObject(), X509CRL_ALLOCATOR);
    RubyClass openSSLError = runtime.getModule("OpenSSL").getClass("OpenSSLError");
    mX509.defineClassUnder("CRLError", openSSLError, openSSLError.getAllocator());

    cX509CRL.defineAnnotatedMethods(X509CRL.class);
  }
Example #8
0
  static void createTCPServer(Ruby runtime) {
    RubyClass rb_cTCPServer =
        runtime.defineClass("TCPServer", runtime.fastGetClass("TCPSocket"), TCPSERVER_ALLOCATOR);

    rb_cTCPServer.defineAnnotatedMethods(RubyTCPServer.class);

    runtime.getObject().fastSetConstant("TCPserver", rb_cTCPServer);
  }
Example #9
0
 public RubyHash getScriptLines(Ruby runtime) {
   IRubyObject scriptLines = runtime.getObject().getConstantAt("SCRIPT_LINES__");
   if (scriptLines instanceof RubyHash) {
     return (RubyHash) scriptLines;
   } else {
     return null;
   }
 }
Example #10
0
  @JRubyMethod(module = true)
  public static IRubyObject timeout(
      final ThreadContext context,
      IRubyObject timeout,
      IRubyObject seconds,
      IRubyObject exceptionType,
      Block block) {
    // No seconds, just yield
    if (seconds.isNil() || Helpers.invoke(context, seconds, "zero?").isTrue()) {
      return block.yieldSpecific(context);
    }

    final Ruby runtime = context.runtime;

    // No timeout in critical section
    if (runtime.getThreadService().getCritical()) {
      return raiseBecauseCritical(context);
    }

    final RubyThread currentThread = context.getThread();
    final AtomicBoolean latch = new AtomicBoolean(false);

    IRubyObject id = new RubyObject(runtime, runtime.getObject());
    RubyClass anonException = (RubyClass) runtime.getClassFromPath("Timeout::AnonymousException");
    Runnable timeoutRunnable =
        exceptionType.isNil()
            ? prepareRunnable(currentThread, runtime, latch, id)
            : prepareRunnableWithException(currentThread, exceptionType, runtime, latch);
    Future timeoutFuture = null;

    try {
      try {
        timeoutFuture =
            timeoutExecutor.schedule(
                timeoutRunnable,
                (long) (seconds.convertToFloat().getDoubleValue() * 1000000),
                TimeUnit.MICROSECONDS);

        return block.yield(context, seconds);
      } finally {
        killTimeoutThread(context, timeoutFuture, latch);
      }
    } catch (RaiseException re) {
      // if it's the exception we're expecting
      if (re.getException().getMetaClass() == anonException) {
        // and we were not given a specific exception
        if (exceptionType.isNil()) {
          // and it's the exception intended for us
          if (re.getException().getInternalVariable("__identifier__") == id) {
            return raiseTimeoutError(context, re);
          }
        }
      }

      // otherwise, rethrow
      throw re;
    }
  }
Example #11
0
  public static RubyClass createProviderClass(Ruby runtime, RubyModule module) {
    RubyClass result =
        module.defineClassUnder(
            CLASS_NAME, runtime.getObject(), ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR);
    result.defineAnnotatedMethods(FFIProvider.class);
    result.defineAnnotatedConstants(FFIProvider.class);

    return result;
  }
Example #12
0
  public static RubyClass createJavaProxyConstructorClass(Ruby runtime, RubyModule Java) {
    RubyClass JavaProxyConstructor =
        Java.defineClassUnder(
            "JavaProxyConstructor", runtime.getObject(), ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR);

    JavaProxyReflectionObject.registerRubyMethods(runtime, JavaProxyConstructor);
    JavaProxyConstructor.defineAnnotatedMethods(JavaProxyConstructor.class);
    return JavaProxyConstructor;
  }
Example #13
0
 public static void load(Ruby runtime) {
   RubyModule humboldtModule = runtime.defineModule("Humboldt");
   RubyModule typeConverterModule = runtime.defineModuleUnder("TypeConverter", humboldtModule);
   RubyClass binaryClass =
       runtime.defineClassUnder(
           "Binary", runtime.getObject(), BINARY_ALLOCATOR, typeConverterModule);
   binaryClass.defineAnnotatedMethods(BinaryConverter.class);
   runtime.defineClassUnder("Encoded", binaryClass, BINARY_ALLOCATOR, typeConverterModule);
   RubyClass textClass =
       runtime.defineClassUnder("Text", runtime.getObject(), TEXT_ALLOCATOR, typeConverterModule);
   textClass.defineAnnotatedMethods(TextConverter.class);
   runtime.defineClassUnder("Json", textClass, TEXT_ALLOCATOR, typeConverterModule);
   RubyClass longClass =
       runtime.defineClassUnder("Long", runtime.getObject(), LONG_ALLOCATOR, typeConverterModule);
   longClass.defineAnnotatedMethods(LongConverter.class);
   RubyClass noneClass =
       runtime.defineClassUnder("None", runtime.getObject(), NONE_ALLOCATOR, typeConverterModule);
   noneClass.defineAnnotatedMethods(NoneConverter.class);
 }
Example #14
0
  private RubyModule buildClassFromDescriptor(ThreadContext context) {
    Ruby runtime = context.runtime;

    ObjectAllocator allocator =
        new ObjectAllocator() {
          @Override
          public IRubyObject allocate(Ruby runtime, RubyClass klazz) {
            return new RubyMessage(runtime, klazz, descriptor);
          }
        };

    // rb_define_class_id
    RubyClass klass = RubyClass.newClass(runtime, runtime.getObject());
    klass.setAllocator(allocator);
    klass.makeMetaClass(runtime.getObject().getMetaClass());
    klass.inherit(runtime.getObject());
    klass.instance_variable_set(runtime.newString(Utils.DESCRIPTOR_INSTANCE_VAR), this);
    klass.defineAnnotatedMethods(RubyMessage.class);
    return klass;
  }
Example #15
0
  public static RubyClass createStringIOClass(final Ruby runtime) {
    RubyClass stringIOClass =
        runtime.defineClass("StringIO", runtime.getClass("Data"), STRINGIO_ALLOCATOR);

    stringIOClass.defineAnnotatedMethods(StringIO.class);
    stringIOClass.includeModule(runtime.getEnumerable());

    if (runtime.getObject().isConstantDefined("Java")) {
      stringIOClass.defineAnnotatedMethods(IOJavaAddons.AnyIO.class);
    }

    return stringIOClass;
  }
Example #16
0
  public static void createX509Store(Ruby runtime, RubyModule mX509) {
    RubyClass cX509Store =
        mX509.defineClassUnder("Store", runtime.getObject(), X509STORE_ALLOCATOR);
    RubyClass openSSLError = runtime.getModule("OpenSSL").getClass("OpenSSLError");
    mX509.defineClassUnder("StoreError", openSSLError, openSSLError.getAllocator());
    cX509Store.addReadWriteAttribute(runtime.getCurrentContext(), "verify_callback");
    cX509Store.addReadWriteAttribute(runtime.getCurrentContext(), "error");
    cX509Store.addReadWriteAttribute(runtime.getCurrentContext(), "error_string");
    cX509Store.addReadWriteAttribute(runtime.getCurrentContext(), "chain");
    cX509Store.defineAnnotatedMethods(X509Store.class);

    X509StoreCtx.createX509StoreCtx(runtime, mX509);
  }
Example #17
0
  public void init(List additionalDirectories) {
    loadPath = RubyArray.newArray(runtime);
    loadedFeatures = RubyArray.newArray(runtime);
    loadedFeaturesInternal = Collections.synchronizedList(loadedFeatures);

    // add all startup load paths to the list first
    for (Iterator iter = additionalDirectories.iterator(); iter.hasNext(); ) {
      addPath((String) iter.next());
    }

    // add $RUBYLIB paths
    RubyHash env = (RubyHash) runtime.getObject().fastGetConstant("ENV");
    RubyString env_rubylib = runtime.newString("RUBYLIB");
    if (env.has_key_p(env_rubylib).isTrue()) {
      String rubylib = env.op_aref(runtime.getCurrentContext(), env_rubylib).toString();
      String[] paths = rubylib.split(File.pathSeparator);
      for (int i = 0; i < paths.length; i++) {
        addPath(paths[i]);
      }
    }

    // wrap in try/catch for security exceptions in an applet
    if (!Ruby.isSecurityRestricted()) {
      try {
        String jrubyHome = runtime.getJRubyHome();
        if (jrubyHome != null) {
          char sep = '/';
          String rubyDir = jrubyHome + sep + "lib" + sep + "ruby" + sep;

          // If we're running in 1.9 compat mode, add Ruby 1.9 libs to path before 1.8 libs
          if (runtime.is1_9()) {
            addPath(rubyDir + "site_ruby" + sep + Constants.RUBY1_9_MAJOR_VERSION);
            addPath(rubyDir + "site_ruby" + sep + "shared");
            addPath(rubyDir + "site_ruby" + sep + Constants.RUBY_MAJOR_VERSION);
            addPath(rubyDir + Constants.RUBY1_9_MAJOR_VERSION);
          } else {
            // Add 1.8 libs
            addPath(rubyDir + "site_ruby" + sep + Constants.RUBY_MAJOR_VERSION);
            addPath(rubyDir + "site_ruby" + sep + "shared");
            addPath(rubyDir + Constants.RUBY_MAJOR_VERSION);
          }
        }
      } catch (SecurityException e) {
      }
    }

    // "." dir is used for relative path loads from a given file, as in require '../foo/bar'
    if (runtime.getSafeLevel() == 0) {
      addPath(".");
    }
  }
Example #18
0
  public static void setup(Ruby runtime) {
    RubyClass cMutex =
        runtime.defineClass(
            "Mutex",
            runtime.getObject(),
            new ObjectAllocator() {

              public IRubyObject allocate(Ruby runtime, RubyClass klass) {
                return new Mutex(runtime, klass);
              }
            });
    cMutex.setReifiedClass(Mutex.class);
    cMutex.defineAnnotatedMethods(Mutex.class);
  }
Example #19
0
  public static void createTracePointClass(Ruby runtime) {
    RubyClass tracePoint =
        runtime.defineClass(
            "TracePoint",
            runtime.getObject(),
            new ObjectAllocator() {
              @Override
              public IRubyObject allocate(Ruby runtime, RubyClass klazz) {
                return new TracePoint(runtime, klazz);
              }
            });

    tracePoint.defineAnnotatedMethods(TracePoint.class);
  }
Example #20
0
  public static void setup(Ruby runtime) {
    RubyClass cQueue =
        runtime.defineClass(
            "Queue",
            runtime.getObject(),
            new ObjectAllocator() {

              public IRubyObject allocate(Ruby runtime, RubyClass klass) {
                return new Queue(runtime, klass);
              }
            });
    cQueue.setReifiedClass(Queue.class);
    cQueue.defineAnnotatedMethods(Queue.class);
  }
Example #21
0
 public static void createRubyDescriptor(Ruby runtime) {
   RubyModule protobuf = runtime.getClassFromPath("Google::Protobuf");
   RubyClass cDescriptor =
       protobuf.defineClassUnder(
           "Descriptor",
           runtime.getObject(),
           new ObjectAllocator() {
             @Override
             public IRubyObject allocate(Ruby runtime, RubyClass klazz) {
               return new RubyDescriptor(runtime, klazz);
             }
           });
   cDescriptor.includeModule(runtime.getEnumerable());
   cDescriptor.defineAnnotatedMethods(RubyDescriptor.class);
 }
Example #22
0
  public static void createPKey(Ruby runtime, RubyModule ossl) {
    RubyModule _PKey = ossl.defineModuleUnder("PKey");
    _PKey.defineAnnotatedMethods(PKeyModule.class);
    // PKey is abstract
    RubyClass _PKeyPkey =
        _PKey.defineClassUnder(
            "PKey", runtime.getObject(), ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR);
    RubyClass _OpenSSLError = ossl.getClass("OpenSSLError");
    _PKey.defineClassUnder("PKeyError", _OpenSSLError, _OpenSSLError.getAllocator());

    _PKeyPkey.defineAnnotatedMethods(PKey.class);

    PKeyRSA.createPKeyRSA(runtime, _PKey);
    PKeyDSA.createPKeyDSA(runtime, _PKey);
    PKeyDH.createPKeyDH(runtime, _PKey, _PKeyPkey);
  }
Example #23
0
  public static IRubyObject searchConst(
      ThreadContext context,
      StaticScope staticScope,
      MutableCallSite site,
      String constName,
      boolean noPrivateConsts)
      throws Throwable {

    // Lexical lookup
    Ruby runtime = context.getRuntime();
    RubyModule object = runtime.getObject();
    IRubyObject constant =
        (staticScope == null)
            ? object.getConstant(constName)
            : staticScope.getConstantInner(constName);

    // Inheritance lookup
    RubyModule module = null;
    if (constant == null) {
      // SSS FIXME: Is this null check case correct?
      module = staticScope == null ? object : staticScope.getModule();
      constant =
          noPrivateConsts
              ? module.getConstantFromNoConstMissing(constName, false)
              : module.getConstantNoConstMissing(constName);
    }

    // Call const_missing or cache
    if (constant == null) {
      return module.callMethod(context, "const_missing", context.runtime.fastNewSymbol(constName));
    }

    SwitchPoint switchPoint = (SwitchPoint) runtime.getConstantInvalidator(constName).getData();

    // bind constant until invalidated
    MethodHandle target = Binder.from(site.type()).drop(0, 2).constant(constant);
    MethodHandle fallback =
        Binder.from(site.type())
            .append(site, constName)
            .append(noPrivateConsts)
            .invokeStatic(LOOKUP, Bootstrap.class, "searchConst");

    site.setTarget(switchPoint.guardWithTest(target, fallback));

    return constant;
  }
Example #24
0
  @Override
  public void init() {
    if (RubyContext.PRINT_RUNTIME) {
      runtime
          .getInstanceConfig()
          .getError()
          .println("jruby: using " + Truffle.getRuntime().getName());
    }

    // Bring in core method nodes

    CoreMethodNodeManager.addStandardMethods(truffleContext.getCoreLibrary().getObjectClass());

    // Give the core library manager a chance to tweak some of those methods

    truffleContext.getCoreLibrary().initializeAfterMethodsAdded();

    // Set program arguments

    for (IRubyObject arg :
        ((org.jruby.RubyArray) runtime.getObject().getConstant("ARGV")).toJavaArray()) {
      assert arg != null;

      truffleContext.getCoreLibrary().getArgv().slowPush(truffleContext.makeString(arg.toString()));
    }

    // Set the load path

    final RubyArray loadPath =
        (RubyArray)
            truffleContext.getCoreLibrary().getGlobalVariablesObject().getInstanceVariable("$:");

    for (IRubyObject path :
        ((org.jruby.RubyArray) runtime.getLoadService().getLoadPath()).toJavaArray()) {
      loadPath.slowPush(truffleContext.makeString(path.toString()));
    }

    // Hook

    if (truffleContext.getHooks() != null) {
      truffleContext.getHooks().afterInit(truffleContext);
    }
  }
Example #25
0
  public static void createReadline(Ruby runtime) throws IOException {
    ConsoleHolder holder = new ConsoleHolder();
    holder.history = new ReadlineHistory();
    holder.currentCompletor = null;
    COMPLETION_CASE_FOLD = runtime.getNil();

    RubyModule mReadline = runtime.defineModule("Readline");

    mReadline.dataWrapStruct(holder);

    mReadline.defineAnnotatedMethods(Readline.class);
    IRubyObject hist = runtime.getObject().callMethod(runtime.getCurrentContext(), "new");
    mReadline.fastSetConstant("HISTORY", hist);
    hist.getSingletonClass().includeModule(runtime.getEnumerable());
    hist.getSingletonClass().defineAnnotatedMethods(HistoryMethods.class);

    // MRI does similar thing on MacOS X with 'EditLine wrapper'.
    mReadline.fastSetConstant("VERSION", runtime.newString("JLine wrapper"));
  }
Example #26
0
  @JRubyMethod(module = true)
  public static IRubyObject timeout(
      final ThreadContext context, IRubyObject timeout, IRubyObject seconds, Block block) {
    // No seconds, just yield
    if (seconds.isNil() || Helpers.invoke(context, seconds, "zero?").isTrue()) {
      return block.yieldSpecific(context);
    }

    final Ruby runtime = context.runtime;

    // No timeout in critical section
    if (runtime.getThreadService().getCritical()) {
      return raiseBecauseCritical(context);
    }

    final RubyThread currentThread = context.getThread();
    final AtomicBoolean latch = new AtomicBoolean(false);

    IRubyObject id = new RubyObject(runtime, runtime.getObject());
    Runnable timeoutRunnable = prepareRunnable(currentThread, runtime, latch, id);
    Future timeoutFuture = null;

    try {
      try {
        timeoutFuture =
            timeoutExecutor.schedule(
                timeoutRunnable,
                (long) (seconds.convertToFloat().getDoubleValue() * 1000000),
                TimeUnit.MICROSECONDS);

        return block.yield(context, seconds);
      } finally {
        killTimeoutThread(context, timeoutFuture, latch);
      }
    } catch (RaiseException re) {
      if (re.getException().getInternalVariable("__identifier__") == id) {
        return raiseTimeoutError(context, re);
      } else {
        throw re;
      }
    }
  }
Example #27
0
  public static void createIconv(Ruby runtime) {
    RubyClass iconvClass = runtime.defineClass("Iconv", runtime.getObject(), ICONV_ALLOCATOR);

    iconvClass.defineAnnotatedMethods(RubyIconv.class);

    RubyModule failure = iconvClass.defineModuleUnder("Failure");
    RubyClass argumentError = runtime.getArgumentError();

    String[] iconvErrors = {
      "IllegalSequence", "InvalidCharacter", "InvalidEncoding", "OutOfRange", "BrokenLibrary"
    };

    for (int i = 0; i < iconvErrors.length; i++) {
      RubyClass subClass =
          iconvClass.defineClassUnder(
              iconvErrors[i], argumentError, RubyFailure.ICONV_FAILURE_ALLOCATOR);
      subClass.defineAnnotatedMethods(RubyFailure.class);
      subClass.includeModule(failure);
    }
  }
Example #28
0
  public static IRubyObject interpret(Ruby runtime, Node rootNode, IRubyObject self) {
    if (runtime.is1_9()) IRBuilder.setRubyVersion("1.9");

    IRScriptBody root =
        (IRScriptBody)
            IRBuilder.createIRBuilder(runtime, runtime.getIRManager())
                .buildRoot((RootNode) rootNode);

    // We get the live object ball rolling here.  This give a valid value for the top
    // of this lexical tree.  All new scope can then retrieve and set based on lexical parent.
    if (root.getStaticScope().getModule() == null) { // If an eval this may already be setup.
      root.getStaticScope().setModule(runtime.getObject());
    }

    RubyModule currModule = root.getStaticScope().getModule();

    // Scope state for root?
    IRStaticScopeFactory.newIRLocalScope(null).setModule(currModule);
    ThreadContext context = runtime.getCurrentContext();

    try {
      runBeginEndBlocks(
          root.getBeginBlocks(), context, self, null); // FIXME: No temp vars yet...not needed?
      InterpretedIRMethod method = new InterpretedIRMethod(root, currModule);
      IRubyObject rv = method.call(context, self, currModule, "(root)", IRubyObject.NULL_ARRAY);
      runBeginEndBlocks(
          root.getEndBlocks(), context, self, null); // FIXME: No temp vars yet...not needed?
      if ((IRRuntimeHelpers.isDebug() || IRRuntimeHelpers.inProfileMode())
          && interpInstrsCount > 10000) {
        LOG.info("-- Interpreted instructions: {}", interpInstrsCount);
        /*
        for (Operation o: opStats.keySet()) {
            System.out.println(o + " = " + opStats.get(o).count);
        }
        */
      }
      return rv;
    } catch (IRBreakJump bj) {
      throw IRException.BREAK_LocalJumpError.getException(context.runtime);
    }
  }
Example #29
0
  public static void initPsychParser(Ruby runtime, RubyModule psych) {
    RubyClass psychParser =
        runtime.defineClassUnder(
            "Parser",
            runtime.getObject(),
            new ObjectAllocator() {
              public IRubyObject allocate(Ruby runtime, RubyClass klazz) {
                return new PsychParser(runtime, klazz);
              }
            },
            psych);

    psychParser.defineConstant("ANY", runtime.newFixnum(YAML_ANY_ENCODING));
    psychParser.defineConstant("UTF8", runtime.newFixnum(YAML_UTF8_ENCODING));
    psychParser.defineConstant("UTF16LE", runtime.newFixnum(YAML_UTF16LE_ENCODING));
    psychParser.defineConstant("UTF16BE", runtime.newFixnum(YAML_UTF16BE_ENCODING));

    psychParser.defineAnnotatedMethods(PsychParser.class);

    psych.defineClassUnder("SyntaxError", runtime.getSyntaxError(), OBJECT_ALLOCATOR);
  }
Example #30
0
  public static IRubyObject interpretTop(Ruby runtime, IRScope scope, IRubyObject self) {
    assert scope instanceof IRScript : "Must be an IRScript scope at Top!!!";

    IRScript root = (IRScript) scope;

    // We get the live object ball rolling here.  This give a valid value for the top
    // of this lexical tree.  All new scope can then retrieve and set based on lexical parent.
    if (root.getStaticScope().getModule() == null) { // If an eval this may already be setup.
      root.getStaticScope().setModule(runtime.getObject());
    }

    RubyModule currModule = root.getStaticScope().getModule();
    IRMethod rootMethod = root.getRootClass().getRootMethod();
    InterpretedIRMethod method = new InterpretedIRMethod(rootMethod, currModule);
    ThreadContext context = runtime.getCurrentContext();

    IRubyObject rv = method.call(context, self, currModule, "", IRubyObject.NULL_ARRAY);
    if (isDebug()) LOG.debug("-- Interpreted instructions: {}", interpInstrsCount);

    return rv;
  }