示例#1
0
 private RubyArray match_array(Ruby runtime, int start) {
   check();
   if (regs == null) {
     if (start != 0) return runtime.newEmptyArray();
     if (begin == -1) {
       return runtime.newArray(runtime.getNil());
     } else {
       RubyString ss = makeShared(runtime, str, begin, end - begin);
       if (isTaint()) ss.setTaint(true);
       return runtime.newArray(ss);
     }
   } else {
     RubyArray arr = runtime.newArray(regs.numRegs - start);
     for (int i = start; i < regs.numRegs; i++) {
       if (regs.beg[i] == -1) {
         arr.append(runtime.getNil());
       } else {
         RubyString ss = makeShared(runtime, str, regs.beg[i], regs.end[i] - regs.beg[i]);
         if (isTaint()) ss.setTaint(true);
         arr.append(ss);
       }
     }
     return arr;
   }
 }
示例#2
0
 @JRubyMethod(name = "_id2ref", required = 1, module = true, visibility = Visibility.PRIVATE)
 public static IRubyObject id2ref(IRubyObject recv, IRubyObject id) {
   Ruby runtime = id.getRuntime();
   if (!(id instanceof RubyFixnum)) {
     throw recv.getRuntime().newTypeError(id, recv.getRuntime().getFixnum());
   }
   RubyFixnum idFixnum = (RubyFixnum) id;
   long longId = idFixnum.getLongValue();
   if (longId == 0) {
     return runtime.getFalse();
   } else if (longId == 2) {
     return runtime.getTrue();
   } else if (longId == 4) {
     return runtime.getNil();
   } else if (longId % 2 != 0) {
     // odd
     return runtime.newFixnum((longId - 1) / 2);
   } else {
     if (runtime.isObjectSpaceEnabled()) {
       IRubyObject object = runtime.getObjectSpace().id2ref(longId);
       if (object == null) {
         return runtime.getNil();
       }
       return object;
     } else {
       runtime
           .getWarnings()
           .warn("ObjectSpace is disabled; _id2ref only supports immediates, pass -X+O to enable");
       return runtime.getNil();
     }
   }
 }
示例#3
0
  private IRubyObject internalGets(ThreadContext context, IRubyObject[] args) {
    Ruby runtime = context.getRuntime();

    if (pos < internal.getByteList().realSize && !eof) {
      boolean isParagraph = false;

      ByteList sep;
      if (args.length > 0) {
        if (args[0].isNil()) {
          ByteList buf =
              internal
                  .getByteList()
                  .makeShared((int) pos, internal.getByteList().realSize - (int) pos);
          pos += buf.realSize;
          return RubyString.newString(runtime, buf);
        }
        sep = args[0].convertToString().getByteList();
        if (sep.realSize == 0) {
          isParagraph = true;
          sep = Stream.PARAGRAPH_SEPARATOR;
        }
      } else {
        sep = ((RubyString) runtime.getGlobalVariables().get("$/")).getByteList();
      }

      ByteList ss = internal.getByteList();

      if (isParagraph) {
        swallowLF(ss);
        if (pos == ss.realSize) {
          return runtime.getNil();
        }
      }

      int ix = ss.indexOf(sep, (int) pos);

      ByteList add;
      if (-1 == ix) {
        ix = internal.getByteList().realSize;
        add = ByteList.EMPTY_BYTELIST;
      } else {
        add = isParagraph ? NEWLINE : sep;
      }

      ByteList line = new ByteList(ix - (int) pos + add.length());
      line.append(internal.getByteList(), (int) pos, ix - (int) pos);
      line.append(add);
      pos = ix + add.realSize;
      lineno++;

      return RubyString.newString(runtime, line);
    }
    return runtime.getNil();
  }
示例#4
0
  private static IRubyObject callCmpMethod(
      ThreadContext context, IRubyObject recv, IRubyObject other, IRubyObject returnValueOnError) {
    Ruby runtime = context.runtime;

    if (recv == other) return runtime.getTrue();

    try {
      IRubyObject result = invokedynamic(context, recv, OP_CMP, other);

      // This is only to prevent throwing exceptions by cmperr - it has poor performance
      if (result.isNil()) {
        return returnValueOnError;
      }

      return RubyBoolean.newBoolean(runtime, cmpint(context, result, recv, other) == 0);
    } catch (RaiseException e) {
      if (e.getException().kind_of_p(context, runtime.getStandardError()).isTrue()) {
        // clear error info resulting from failure to compare (JRUBY-3292)
        context.setErrorInfo(runtime.getNil());
        return returnValueOnError;
      } else {
        throw e;
      }
    }
  }
示例#5
0
 /** match_end */
 @JRubyMethod(name = "end", compat = CompatVersion.RUBY1_8)
 public IRubyObject end(ThreadContext context, IRubyObject index) {
   int i = RubyNumeric.num2int(index);
   Ruby runtime = context.getRuntime();
   int e = endCommon(runtime, i);
   return e < 0 ? runtime.getNil() : RubyFixnum.newFixnum(runtime, e);
 }
示例#6
0
  @JRubyMethod(name = "compatible?", meta = true)
  public static IRubyObject compatible_p(
      ThreadContext context, IRubyObject self, IRubyObject first, IRubyObject second) {
    Ruby runtime = context.runtime;
    Encoding enc = areCompatible(first, second);

    return enc == null ? runtime.getNil() : runtime.getEncodingService().getEncoding(enc);
  }
 private synchronized IRubyObject status(Ruby runtime) {
   if (threadImpl.isAlive()) {
     return RubyString.newStringShared(runtime, status.get().bytes);
   } else if (exitingException != null) {
     return runtime.getNil();
   } else {
     return runtime.getFalse();
   }
 }
示例#8
0
    @JRubyMethod(name = "open", required = 1, optional = 2, frame = true, meta = true)
    public static IRubyObject open(
        final ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block)
        throws IOException {
      Ruby runtime = recv.getRuntime();
      IRubyObject level = runtime.getNil();
      IRubyObject strategy = runtime.getNil();

      if (args.length > 1) {
        level = args[1];
        if (args.length > 2) strategy = args[2];
      }

      IRubyObject io =
          RuntimeHelpers.invoke(
              context, runtime.getFile(), "open", args[0], runtime.newString("wb"));
      RubyGzipWriter gzio = newGzipWriter(recv, new IRubyObject[] {io, level, strategy}, block);
      return RubyGzipFile.wrapBlock(context, gzio, block);
    }
示例#9
0
  private static void defineGlobalEnvConstants(Ruby runtime) {
    Map environmentVariableMap = null;
    OSEnvironment environment = new OSEnvironment();
    environmentVariableMap = environment.getEnvironmentVariableMap(runtime);

    if (environmentVariableMap == null) {
      // if the environment variables can't be obtained, define an empty ENV
      environmentVariableMap = new HashMap();
    }

    StringOnlyRubyHash h1 =
        new StringOnlyRubyHash(runtime, environmentVariableMap, runtime.getNil());
    h1.getSingletonClass().defineAnnotatedMethods(StringOnlyRubyHash.class);
    runtime.defineGlobalConstant("ENV", h1);

    // Define System.getProperties() in ENV_JAVA
    Map systemProps = environment.getSystemPropertiesMap(runtime);
    runtime.defineGlobalConstant(
        "ENV_JAVA", new StringOnlyRubyHash(runtime, systemProps, runtime.getNil()));
  }
示例#10
0
 private IRubyObject offsetCommon(ThreadContext context, int i, boolean is_19) {
   check();
   Ruby runtime = context.getRuntime();
   if (i < 0 || (regs == null ? 1 : regs.numRegs) <= i)
     throw runtime.newIndexError("index " + i + " out of matches");
   int b, e;
   if (regs == null) {
     b = begin;
     e = end;
   } else {
     b = regs.beg[i];
     e = regs.end[i];
   }
   if (b < 0) return runtime.newArray(runtime.getNil(), runtime.getNil());
   if (is_19 && !str.singleByteOptimizable()) {
     updateCharOffset();
     b = charOffsets.beg[i];
     e = charOffsets.end[i];
   }
   return runtime.newArray(RubyFixnum.newFixnum(runtime, b), RubyFixnum.newFixnum(runtime, e));
 }
示例#11
0
 @JRubyMethod(name = "end", compat = CompatVersion.RUBY1_9)
 public IRubyObject end19(ThreadContext context, IRubyObject index) {
   int i = backrefNumber(index);
   Ruby runtime = context.getRuntime();
   int e = endCommon(runtime, i);
   if (e < 0) return runtime.getNil();
   if (!str.singleByteOptimizable()) {
     updateCharOffset();
     e = charOffsets.end[i];
   }
   return RubyFixnum.newFixnum(runtime, e);
 }
示例#12
0
 @JRubyMethod(name = "begin")
 public IRubyObject begin19(ThreadContext context, IRubyObject index) {
   int i = backrefNumber(index);
   Ruby runtime = context.runtime;
   int b = beginCommon(runtime, i);
   if (b < 0) return runtime.getNil();
   if (!str.singleByteOptimizable()) {
     updateCharOffset();
     b = charOffsets.beg[i];
   }
   return RubyFixnum.newFixnum(runtime, b);
 }
示例#13
0
  @JRubyMethod(name = "each_byte", frame = true)
  public IRubyObject each_byte(ThreadContext context, Block block) {
    checkReadable();
    Ruby runtime = context.getRuntime();
    ByteList bytes = internal.getByteList();

    // Check the length every iteration, since
    // the block can modify this string.
    while (pos < bytes.length()) {
      block.yield(context, runtime.newFixnum(bytes.get((int) pos++) & 0xFF));
    }
    return runtime.getNil();
  }
示例#14
0
        public void marshalTo(Ruby runtime, Object obj, RubyClass type, MarshalStream marshalStream)
            throws IOException {
          RubySystemCallError exc = (RubySystemCallError) obj;
          marshalStream.registerLinkTarget(exc);

          List<Variable<Object>> attrs = exc.getVariableList();
          attrs.add(
              new VariableEntry<Object>(
                  "mesg", exc.message == null ? runtime.getNil() : exc.message));
          attrs.add(new VariableEntry<Object>("errno", exc.errno));
          attrs.add(new VariableEntry<Object>("bt", exc.getBacktrace()));
          marshalStream.dumpVariables(attrs);
        }
示例#15
0
 public WarningGlobalVariable(
     Ruby runtime, String name, RubyInstanceConfig.Verbosity verbosity) {
   super(
       runtime,
       name,
       verbosity == RubyInstanceConfig.Verbosity.NIL
           ? RubyFixnum.newFixnum(runtime, 0)
           : verbosity == RubyInstanceConfig.Verbosity.FALSE
               ? RubyFixnum.newFixnum(runtime, 1)
               : verbosity == RubyInstanceConfig.Verbosity.TRUE
                   ? RubyFixnum.newFixnum(runtime, 2)
                   : runtime.getNil());
 }
示例#16
0
  @SuppressWarnings("unchecked")
  private static void defineGlobalEnvConstants(Ruby runtime) {
    Map<RubyString, RubyString> environmentVariableMap =
        OSEnvironment.environmentVariableMap(runtime);
    RubyHash env =
        new CaseInsensitiveStringOnlyRubyHash(
            runtime,
            environmentVariableMap,
            runtime.getNil(),
            runtime.getInstanceConfig().isNativeEnabled()
                && runtime.getInstanceConfig().isUpdateNativeENVEnabled());
    env.getSingletonClass().defineAnnotatedMethods(CaseInsensitiveStringOnlyRubyHash.class);
    runtime.defineGlobalConstant("ENV", env);
    runtime.setENV(env);

    // Define System.getProperties() in ENV_JAVA
    Map<RubyString, RubyString> systemPropertiesMap = OSEnvironment.systemPropertiesMap(runtime);
    RubyHash envJava =
        new ReadOnlySystemPropertiesHash(runtime, systemPropertiesMap, runtime.getNil());
    envJava.setFrozen(true);
    runtime.defineGlobalConstant("ENV_JAVA", envJava);
  }
示例#17
0
 private static void fixnumDownto(ThreadContext context, long from, long to, Block block) {
   Ruby runtime = context.getRuntime();
   if (block.getBody().getArgumentType() == BlockBody.ZERO_ARGS) {
     final IRubyObject nil = runtime.getNil();
     for (long i = from; i >= to; i--) {
       block.yield(context, nil);
     }
   } else {
     for (long i = from; i >= to; i--) {
       block.yield(context, RubyFixnum.newFixnum(runtime, i));
     }
   }
 }
示例#18
0
  @JRubyMethod
  public IRubyObject source_location(ThreadContext context) {
    Ruby runtime = context.runtime;
    if (file != null)
      return runtime.newArray(runtime.newString(file), runtime.newFixnum(line + 1 /*zero-based*/));

    if (block != null) {
      Binding binding = block.getBinding();
      return runtime.newArray(
          runtime.newString(binding.getFile()),
          runtime.newFixnum(binding.getLine() + 1 /*zero-based*/));
    }

    return runtime.getNil();
  }
示例#19
0
  private void fixnumEach(ThreadContext context, Ruby runtime, Block block) {
    long lim = ((RubyFixnum) end).getLongValue();
    if (!isExclusive) lim++;

    if (block.getBody().getArgumentType() == BlockBody.ZERO_ARGS) {
      final IRubyObject nil = runtime.getNil();
      for (long i = ((RubyFixnum) begin).getLongValue(); i < lim; i++) {
        block.yield(context, nil);
      }
    } else {
      for (long i = ((RubyFixnum) begin).getLongValue(); i < lim; i++) {
        block.yield(context, RubyFixnum.newFixnum(runtime, i));
      }
    }
  }
示例#20
0
  @JRubyMethod(name = "source_location", compat = CompatVersion.RUBY1_9)
  public IRubyObject source_location(ThreadContext context) {
    Ruby runtime = context.getRuntime();
    if (sourcePosition != null) {
      return runtime.newArray(
          runtime.newString(sourcePosition.getFile()),
          runtime.newFixnum(sourcePosition.getLine() + 1 /*zero-based*/));
    } else if (block != null) {
      Binding binding = block.getBinding();
      return runtime.newArray(
          runtime.newString(binding.getFile()),
          runtime.newFixnum(binding.getLine() + 1 /*zero-based*/));
    }

    return runtime.getNil();
  }
示例#21
0
  // This returns a list of values in the order the names are defined (named capture local var
  // feature uses this).
  public IRubyObject[] getNamedBackrefValues(Ruby runtime) {
    if (pattern.numberOfNames() == 0) return NULL_ARRAY;

    IRubyObject[] values = new IRubyObject[pattern.numberOfNames()];

    int j = 0;
    for (Iterator<NameEntry> i = pattern.namedBackrefIterator(); i.hasNext(); ) {
      NameEntry e = i.next();
      int[] refs = e.getBackRefs();
      int length = refs.length;

      values[j++] = length == 0 ? runtime.getNil() : RubyRegexp.nth_match(refs[length - 1], this);
    }

    return values;
  }
示例#22
0
 @JRubyMethod(name = "max", frame = true, compat = CompatVersion.RUBY1_9)
 public IRubyObject max(ThreadContext context, Block block) {
   if (block.isGiven() || isExclusive && !(end instanceof RubyNumeric)) {
     return RuntimeHelpers.invokeSuper(context, this, block);
   } else {
     int c = RubyComparable.cmpint(context, begin.callMethod(context, "<=>", end), begin, end);
     Ruby runtime = context.getRuntime();
     if (isExclusive) {
       if (!(end instanceof RubyInteger))
         throw runtime.newTypeError("cannot exclude non Integer end value");
       if (c == 0) return runtime.getNil();
       if (end instanceof RubyFixnum)
         return RubyFixnum.newFixnum(runtime, ((RubyFixnum) end).getLongValue() - 1);
       return end.callMethod(context, "-", RubyFixnum.one(runtime));
     }
     return end;
   }
 }
示例#23
0
 private static void fixnumDownto(ThreadContext context, long from, long to, Block block) {
   // We must avoid "i--" integer overflow when (to == Long.MIN_VALUE).
   Ruby runtime = context.runtime;
   if (block.getBody().getArgumentType() == BlockBody.ZERO_ARGS) {
     IRubyObject nil = runtime.getNil();
     long i;
     for (i = from; i > to; i--) {
       block.yield(context, nil);
     }
     if (i >= to) {
       block.yield(context, nil);
     }
   } else {
     long i;
     for (i = from; i > to; i--) {
       block.yield(context, RubyFixnum.newFixnum(runtime, i));
     }
     if (i >= to) {
       block.yield(context, RubyFixnum.newFixnum(runtime, i));
     }
   }
 }
示例#24
0
  public static void createGlobals(ThreadContext context, Ruby runtime) {
    runtime.defineGlobalConstant("TOPLEVEL_BINDING", runtime.newBinding());

    runtime.defineGlobalConstant("TRUE", runtime.getTrue());
    runtime.defineGlobalConstant("FALSE", runtime.getFalse());
    runtime.defineGlobalConstant("NIL", runtime.getNil());

    // define ARGV and $* for this runtime
    RubyArray argvArray = runtime.newArray();
    String[] argv = runtime.getInstanceConfig().getArgv();
    for (int i = 0; i < argv.length; i++) {
      argvArray.append(RubyString.newStringShared(runtime, argv[i].getBytes()));
    }
    runtime.defineGlobalConstant("ARGV", argvArray);
    runtime.getGlobalVariables().defineReadonly("$*", new ValueAccessor(argvArray));

    IAccessor d =
        new ValueAccessor(runtime.newString(runtime.getInstanceConfig().displayedFileName()));
    runtime.getGlobalVariables().define("$PROGRAM_NAME", d);
    runtime.getGlobalVariables().define("$0", d);

    // Version information:
    IRubyObject version = null;
    IRubyObject patchlevel = null;
    IRubyObject release = runtime.newString(Constants.COMPILE_DATE).freeze(context);
    IRubyObject platform = runtime.newString(Constants.PLATFORM).freeze(context);
    IRubyObject engine = runtime.newString(Constants.ENGINE).freeze(context);

    switch (runtime.getInstanceConfig().getCompatVersion()) {
      case RUBY1_8:
        version = runtime.newString(Constants.RUBY_VERSION).freeze(context);
        patchlevel = runtime.newFixnum(Constants.RUBY_PATCHLEVEL).freeze(context);
        break;
      case RUBY1_9:
        version = runtime.newString(Constants.RUBY1_9_VERSION).freeze(context);
        patchlevel = runtime.newFixnum(Constants.RUBY1_9_PATCHLEVEL).freeze(context);
        break;
    }
    runtime.defineGlobalConstant("RUBY_VERSION", version);
    runtime.defineGlobalConstant("RUBY_PATCHLEVEL", patchlevel);
    runtime.defineGlobalConstant("RUBY_RELEASE_DATE", release);
    runtime.defineGlobalConstant("RUBY_PLATFORM", platform);
    runtime.defineGlobalConstant("RUBY_ENGINE", engine);

    IRubyObject description =
        runtime.newString(runtime.getInstanceConfig().getVersionString()).freeze(context);
    runtime.defineGlobalConstant("RUBY_DESCRIPTION", description);

    IRubyObject copyright =
        runtime.newString(runtime.getInstanceConfig().getCopyrightString()).freeze(context);
    runtime.defineGlobalConstant("RUBY_COPYRIGHT", copyright);

    runtime.defineGlobalConstant("VERSION", version);
    runtime.defineGlobalConstant("RELEASE_DATE", release);
    runtime.defineGlobalConstant("PLATFORM", platform);

    IRubyObject jrubyVersion = runtime.newString(Constants.VERSION).freeze(context);
    IRubyObject jrubyRevision = runtime.newString(Constants.REVISION).freeze(context);
    runtime.defineGlobalConstant("JRUBY_VERSION", jrubyVersion);
    runtime.defineGlobalConstant("JRUBY_REVISION", jrubyRevision);

    if (runtime.is1_9()) {
      // needs to be a fixnum, but our revision is a sha1 hash from git
      runtime.defineGlobalConstant("RUBY_REVISION", runtime.newFixnum(Constants.RUBY1_9_REVISION));
    }

    GlobalVariable kcodeGV = new KCodeGlobalVariable(runtime, "$KCODE", runtime.newString("NONE"));
    runtime.defineVariable(kcodeGV);
    runtime.defineVariable(new GlobalVariable.Copy(runtime, "$-K", kcodeGV));
    IRubyObject defaultRS =
        runtime.newString(runtime.getInstanceConfig().getRecordSeparator()).freeze(context);
    GlobalVariable rs = new StringGlobalVariable(runtime, "$/", defaultRS);
    runtime.defineVariable(rs);
    runtime.setRecordSeparatorVar(rs);
    runtime.getGlobalVariables().setDefaultSeparator(defaultRS);
    runtime.defineVariable(new StringGlobalVariable(runtime, "$\\", runtime.getNil()));
    runtime.defineVariable(new StringGlobalVariable(runtime, "$,", runtime.getNil()));

    runtime.defineVariable(new LineNumberGlobalVariable(runtime, "$."));
    runtime.defineVariable(new LastlineGlobalVariable(runtime, "$_"));
    runtime.defineVariable(new LastExitStatusVariable(runtime, "$?"));

    runtime.defineVariable(new ErrorInfoGlobalVariable(runtime, "$!", runtime.getNil()));
    runtime.defineVariable(new NonEffectiveGlobalVariable(runtime, "$=", runtime.getFalse()));

    if (runtime.getInstanceConfig().getInputFieldSeparator() == null) {
      runtime.defineVariable(new GlobalVariable(runtime, "$;", runtime.getNil()));
    } else {
      runtime.defineVariable(
          new GlobalVariable(
              runtime,
              "$;",
              RubyRegexp.newRegexp(
                  runtime, runtime.getInstanceConfig().getInputFieldSeparator(), 0)));
    }

    Boolean verbose = runtime.getInstanceConfig().getVerbose();
    IRubyObject verboseValue = null;
    if (verbose == null) {
      verboseValue = runtime.getNil();
    } else if (verbose == Boolean.TRUE) {
      verboseValue = runtime.getTrue();
    } else {
      verboseValue = runtime.getFalse();
    }
    runtime.defineVariable(new VerboseGlobalVariable(runtime, "$VERBOSE", verboseValue));

    IRubyObject debug = runtime.newBoolean(runtime.getInstanceConfig().isDebug());
    runtime.defineVariable(new DebugGlobalVariable(runtime, "$DEBUG", debug));
    runtime.defineVariable(new DebugGlobalVariable(runtime, "$-d", debug));

    runtime.defineVariable(new SafeGlobalVariable(runtime, "$SAFE"));

    runtime.defineVariable(new BacktraceGlobalVariable(runtime, "$@"));

    IRubyObject stdin = new RubyIO(runtime, STDIO.IN);
    IRubyObject stdout = new RubyIO(runtime, STDIO.OUT);
    IRubyObject stderr = new RubyIO(runtime, STDIO.ERR);

    runtime.defineVariable(new InputGlobalVariable(runtime, "$stdin", stdin));

    runtime.defineVariable(new OutputGlobalVariable(runtime, "$stdout", stdout));
    runtime.getGlobalVariables().alias("$>", "$stdout");
    runtime.getGlobalVariables().alias("$defout", "$stdout");

    runtime.defineVariable(new OutputGlobalVariable(runtime, "$stderr", stderr));
    runtime.getGlobalVariables().alias("$deferr", "$stderr");

    runtime.defineGlobalConstant("STDIN", stdin);
    runtime.defineGlobalConstant("STDOUT", stdout);
    runtime.defineGlobalConstant("STDERR", stderr);

    runtime.defineVariable(new LoadedFeatures(runtime, "$\""));
    runtime.defineVariable(new LoadedFeatures(runtime, "$LOADED_FEATURES"));

    runtime.defineVariable(new LoadPath(runtime, "$:"));
    runtime.defineVariable(new LoadPath(runtime, "$-I"));
    runtime.defineVariable(new LoadPath(runtime, "$LOAD_PATH"));

    runtime.defineVariable(new MatchMatchGlobalVariable(runtime, "$&"));
    runtime.defineVariable(new PreMatchGlobalVariable(runtime, "$`"));
    runtime.defineVariable(new PostMatchGlobalVariable(runtime, "$'"));
    runtime.defineVariable(new LastMatchGlobalVariable(runtime, "$+"));
    runtime.defineVariable(new BackRefGlobalVariable(runtime, "$~"));

    // On platforms without a c-library accessable through JNA, getpid will return hashCode
    // as $$ used to. Using $$ to kill processes could take down many runtimes, but by basing
    // $$ on getpid() where available, we have the same semantics as MRI.
    runtime.getGlobalVariables().defineReadonly("$$", new PidAccessor(runtime));

    // after defn of $stderr as the call may produce warnings
    defineGlobalEnvConstants(runtime);

    // Fixme: Do we need the check or does Main.java not call this...they should consolidate
    if (runtime.getGlobalVariables().get("$*").isNil()) {
      runtime.getGlobalVariables().defineReadonly("$*", new ValueAccessor(runtime.newArray()));
    }

    runtime
        .getGlobalVariables()
        .defineReadonly(
            "$-p",
            new ValueAccessor(runtime.newBoolean(runtime.getInstanceConfig().isAssumePrinting())));
    runtime
        .getGlobalVariables()
        .defineReadonly(
            "$-a", new ValueAccessor(runtime.newBoolean(runtime.getInstanceConfig().isSplit())));
    runtime
        .getGlobalVariables()
        .defineReadonly(
            "$-l",
            new ValueAccessor(runtime.newBoolean(runtime.getInstanceConfig().isProcessLineEnds())));

    // ARGF, $< object
    RubyArgsFile.initArgsFile(runtime);
  }
示例#25
0
  private static RubyTime createTime(IRubyObject recv, IRubyObject[] args, boolean gmt) {
    Ruby runtime = recv.getRuntime();
    int len = ARG_SIZE;
    Boolean isDst = null;

    DateTimeZone dtz;
    if (gmt) {
      dtz = DateTimeZone.UTC;
    } else if (args.length == 10 && args[9] instanceof RubyString) {
      dtz = getTimeZone(runtime, ((RubyString) args[9]).toString());
    } else {
      dtz = getLocalTimeZone(runtime);
    }

    if (args.length == 10) {
      if (args[8] instanceof RubyBoolean) {
        isDst = ((RubyBoolean) args[8]).isTrue();
      }
      args =
          new IRubyObject[] {
            args[5], args[4], args[3], args[2], args[1], args[0], runtime.getNil()
          };
    } else {
      // MRI accepts additional wday argument which appears to be ignored.
      len = args.length;

      if (len < ARG_SIZE) {
        IRubyObject[] newArgs = new IRubyObject[ARG_SIZE];
        System.arraycopy(args, 0, newArgs, 0, args.length);
        for (int i = len; i < ARG_SIZE; i++) {
          newArgs[i] = runtime.getNil();
        }
        args = newArgs;
        len = ARG_SIZE;
      }
    }

    if (args[0] instanceof RubyString) {
      args[0] = RubyNumeric.str2inum(runtime, (RubyString) args[0], 10, false);
    }

    int year = (int) RubyNumeric.num2long(args[0]);
    int month = 1;

    if (len > 1) {
      if (!args[1].isNil()) {
        IRubyObject tmp = args[1].checkStringType();
        if (!tmp.isNil()) {
          String monthString = tmp.toString().toLowerCase();
          Integer monthInt = MONTHS_MAP.get(monthString);

          if (monthInt != null) {
            month = monthInt;
          } else {
            try {
              month = Integer.parseInt(monthString);
            } catch (NumberFormatException nfExcptn) {
              throw runtime.newArgumentError("Argument out of range.");
            }
          }
        } else {
          month = (int) RubyNumeric.num2long(args[1]);
        }
      }
      if (1 > month || month > 12) {
        throw runtime.newArgumentError("Argument out of range: for month: " + month);
      }
    }

    int[] int_args = {1, 0, 0, 0, 0, 0};

    for (int i = 0; int_args.length >= i + 2; i++) {
      if (!args[i + 2].isNil()) {
        if (!(args[i + 2] instanceof RubyNumeric)) {
          args[i + 2] = args[i + 2].callMethod(runtime.getCurrentContext(), "to_i");
        }

        long value = RubyNumeric.num2long(args[i + 2]);
        if (time_min[i] > value || value > time_max[i]) {
          throw runtime.newArgumentError("argument out of range.");
        }
        int_args[i] = (int) value;
      }
    }

    if (!runtime.is1_9()) {
      if (0 <= year && year < 39) {
        year += 2000;
      } else if (69 <= year && year < 139) {
        year += 1900;
      }
    }

    DateTime dt;
    // set up with min values and then add to allow rolling over
    try {
      dt = new DateTime(year, 1, 1, 0, 0, 0, 0, DateTimeZone.UTC);

      dt =
          dt.plusMonths(month - 1)
              .plusDays(int_args[0] - 1)
              .plusHours(int_args[1])
              .plusMinutes(int_args[2])
              .plusSeconds(int_args[3]);
      if (runtime.is1_9() && !args[5].isNil()) {
        double millis = RubyFloat.num2dbl(args[5]);
        int int_millis = (int) (millis * 1000) % 1000;
        dt = dt.plusMillis(int_millis);
      }

      dt = dt.withZoneRetainFields(dtz);

      // we might need to perform a DST correction
      if (isDst != null) {
        // the instant at which we will ask dtz what the difference between DST and
        // standard time is
        long offsetCalculationInstant = dt.getMillis();

        // if we might be moving this time from !DST -> DST, the offset is assumed
        // to be the same as it was just before we last moved from DST -> !DST
        if (dtz.isStandardOffset(dt.getMillis())) {
          offsetCalculationInstant = dtz.previousTransition(offsetCalculationInstant);
        }

        int offset =
            dtz.getStandardOffset(offsetCalculationInstant)
                - dtz.getOffset(offsetCalculationInstant);

        if (!isDst && !dtz.isStandardOffset(dt.getMillis())) {
          dt = dt.minusMillis(offset);
        }
        if (isDst && dtz.isStandardOffset(dt.getMillis())) {
          dt = dt.plusMillis(offset);
        }
      }
    } catch (org.joda.time.IllegalFieldValueException e) {
      throw runtime.newArgumentError("time out of range");
    }

    RubyTime time = new RubyTime(runtime, (RubyClass) recv, dt);
    // Ignores usec if 8 args (for compatibility with parsedate) or if not supplied.
    if (args.length != 8 && !args[6].isNil()) {
      int usec = int_args[4] % 1000;
      int msec = int_args[4] / 1000;

      if (int_args[4] < 0) {
        msec -= 1;
        usec += 1000;
      }
      time.dt = dt.withMillis(dt.getMillis() + msec);
      time.setUSec(usec);
    }

    time.callInit(IRubyObject.NULL_ARRAY, Block.NULL_BLOCK);
    return time;
  }
示例#26
0
 public RubyGzipFile(Ruby runtime, RubyClass type) {
   super(runtime, type);
   mtime = runtime.getNil();
 }
示例#27
0
 public LastExitStatusVariable(Ruby runtime, String name) {
   super(runtime, name, runtime.getNil());
 }
示例#28
0
 public LastMatchGlobalVariable(Ruby runtime, String name) {
   super(runtime, name, runtime.getNil());
 }
示例#29
0
 public BackRefGlobalVariable(Ruby runtime, String name) {
   super(runtime, name, runtime.getNil());
 }
示例#30
0
 private RubyRange(Ruby runtime, RubyClass klass) {
   super(runtime, klass);
   begin = end = runtime.getNil();
 }