Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
BEGIN LICENSE BLOCK ***** Version: CPL 1.0/GPL 2.0/LGPL 2.1 The contents of this file are subject to the Common Public License Version 1.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.eclipse.org/legal/cpl-v10.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Copyright (C) 2001 Chad Fowler <chadfowler@chadfowler.com> Copyright (C) 2001 Alan Moore <alan_moore@gmx.net> Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de> Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se> Copyright (C) 2002-2005 Thomas E Enebo <enebo@acm.org> Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de> Copyright (C) 2005 Charles O Nutter <headius@headius.com> Copyright (C) 2007 Miguel Covarrubias <mlcovarrubias@gmail.com> Alternatively, the contents of this file may be used under the terms of either of the GNU General Public License Version 2 or later (the "GPL"), or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), in which case the provisions of the GPL or the LGPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of either the GPL or the LGPL, and not to allow others to use your version of this file under the terms of the CPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL or the LGPL. If you do not delete the provisions above, a recipient may use your version of this file under the terms of any one of the CPL, the GPL or the LGPL. END LICENSE BLOCK ***
 
 package org.jruby;
 
 import java.util.List;
 import static org.jruby.CompatVersion.*;

Author(s):
jpetersen
 
 @JRubyClass(name="Proc")
 public class RubyProc extends RubyObject implements DataType {
     private Block block = .;
     private Block.Type type;
     private ISourcePosition sourcePosition;
 
     protected RubyProc(Ruby runtimeRubyClass rubyClassBlock.Type type) {
         super(runtimerubyClass);
         
         this. = type;
     }
 
     protected RubyProc(Ruby runtimeRubyClass rubyClassBlock.Type typeISourcePosition sourcePosition) {
         this(runtimerubyClasstype);
         this. = sourcePosition;
     }
 
     public static RubyClass createProcClass(Ruby runtime) {
         RubyClass procClass = runtime.defineClass("Proc"runtime.getObject(), .);
         runtime.setProc(procClass);
 
         procClass.index = .;
         procClass.setReifiedClass(RubyProc.class);
         
         procClass.defineAnnotatedMethods(RubyProc.class);
         
         return procClass;
     }
 
     public Block getBlock() {
         return ;
     }
 
     // Proc class
 
     @Deprecated
     public static RubyProc newProc(Ruby runtimeBlock.Type type) {
         throw runtime.newRuntimeError("deprecated RubyProc.newProc with no block; do not use");
     }
    public static RubyProc newProc(Ruby runtimeBlock blockBlock.Type type) {
        return newProc(runtimeblocktypenull);
    }
    public static RubyProc newProc(Ruby runtimeBlock blockBlock.Type typeISourcePosition sourcePosition) {
        RubyProc proc = new RubyProc(runtimeruntime.getProc(), typesourcePosition);
        proc.setup(block);
        return proc;
    }
    
    
Create a new instance of a Proc object. We override this method (from RubyClass) since we need to deal with special case of Proc.new with no arguments or block arg. In this case, we need to check previous frame for a block to consume.
    @JRubyMethod(name = "new", rest = true, meta = true)
    public static IRubyObject newInstance(ThreadContext contextIRubyObject recvIRubyObject[] argsBlock block) {
        // No passed in block, lets check next outer frame for one ('Proc.new')
        if (!block.isGiven()) block = context.getCurrentFrame().getBlock();
        // This metaclass == recv check seems gross, but MRI seems to do the same:
        // if (!proc && ruby_block->block_obj && CLASS_OF(ruby_block->block_obj) == klass) {
        if (block.isGiven() && block.getProcObject() != null && block.getProcObject().getMetaClass() == recv) {
            return block.getProcObject();
        }
        
        RubyProc obj = new RubyProc(context.runtime, (RubyClass)recv..);
        obj.setup(block);
        
        obj.callMethod(context"initialize"argsblock);
        return obj;
    }
    
    private void setup(Block procBlock) {
        if (!procBlock.isGiven()) {
            throw getRuntime().newArgumentError("tried to create Proc object without a block");
        }
        
        if (isLambda() && procBlock == null) {
            // TODO: warn "tried to create Proc object without a block"
        }
        
         = procBlock.cloneBlock();
        if (isThread()) {
            // modify the block with a new backref/lastline-grabbing scope
            StaticScope oldScope = .getBody().getStaticScope();
            StaticScope newScope = getRuntime().getStaticScopeFactory().newBlockScope(oldScope.getEnclosingScope(), oldScope.getVariables());
            newScope.setBackrefLastlineScope(true);
            newScope.setPreviousCRefScope(oldScope.getPreviousCRefScope());
            newScope.setModule(oldScope.getModule());
            .getBody().setStaticScope(newScope);
        }
        // force file/line info into the new block's binding
        . = ;
        .setProcObject(this);
    }
    
    @JRubyMethod(name = "clone")
    @Override
    public IRubyObject rbClone() {
    	RubyProc newProc = newProc(getRuntime(), );
    	// TODO: CLONE_SETUP here
    	return newProc;
    }
    @JRubyMethod(name = "dup")
    @Override
    public IRubyObject dup() {
        return newProc(getRuntime(), );
    }
    
    @JRubyMethod(name = "==", required = 1)
    public IRubyObject op_equal(IRubyObject other) {
        return getRuntime().newBoolean(other instanceof RubyProc &&
                (this == other || this..equals(((RubyProc)other).)));
    }
    
    @JRubyMethod(name = "to_s", compat = )
    @Override
    public IRubyObject to_s() {
        return RubyString.newString(
                getRuntime(),"#<Proc:0x" + Integer.toString(.hashCode(), 16) + "@" +
                .getBody().getFile() + ":" + (.getBody().getLine() + 1) + ">");
    }
    @JRubyMethod(name = "to_s", compat = )
    public IRubyObject to_s19() {
        StringBuilder sb = new StringBuilder("#<Proc:0x" + Integer.toString(.hashCode(), 16) + "@" +
                .getBody().getFile() + ":" + (.getBody().getLine() + 1));
        if (isLambda()) sb.append(" (lambda)");
        sb.append(">");
        
        return RubyString.newString(getRuntime(), sb.toString());
    }
    @JRubyMethod(name = "binding")
    public IRubyObject binding() {
        return getRuntime().newBinding(.getBinding());
    }
    @JRubyMethod(name = {"call""[]"}, rest = true, compat = )
    public IRubyObject call(ThreadContext contextIRubyObject[] argsBlock block) {
        return call(contextargsnullblock);
    }
    public IRubyObject call(ThreadContext contextIRubyObject[] args) {
        return call(contextargsnull.);
    }
    
    private IRubyObject[] prepareProcArgs(ThreadContext contextIRubyObject[] args) {
        Arity arity = .arity();
        
        // for procs and blocks, single array passed to multi-arg must be spread
        if (arity != . && arity.required() != 0 && 
                (arity.isFixed() || arity != .) &&
                args.length == 1 && args[0].respondsTo("to_ary")) {
            args = args[0].convertToArray().toJavaArray();
        }
        if (arity.isFixed()) {
            List<IRubyObjectlist = new ArrayList<IRubyObject>(Arrays.asList(args));
            int required = arity.required();
            if (required > args.length) {
                for (int i = args.lengthi < requiredi++) {
                    list.add(context.runtime.getNil());
                }
                args = list.toArray(args);
            } else if (required < args.length) {
                args = list.subList(0, required).toArray(args);
            }
        }
        return args;
    }
    @JRubyMethod(name = {"call""[]""yield""==="}, rest = true, compat = )
    public IRubyObject call19(ThreadContext contextIRubyObject[] argsBlock blockCallArg) {
        if (isLambda()) {
            .arity().checkArity(context.runtimeargs.length);
        }
        if (isProc()) args = prepareProcArgs(contextargs);
        return call(contextargsnullblockCallArg);
    }
    public IRubyObject call(ThreadContext contextIRubyObject[] argsIRubyObject selfBlock passedBlock) {
        assert args != null;
        
        Block newBlock = .cloneBlock();
        int jumpTarget = newBlock.getBinding().getFrame().getJumpTarget();
        
        try {
            if (self != nullnewBlock.getBinding().setSelf(self);
            
            return newBlock.call(contextargspassedBlock);
        } catch (JumpException.BreakJump bj) {
            return handleBreakJump(getRuntime(), newBlockbjjumpTarget);
        } catch (JumpException.ReturnJump rj) {
            return handleReturnJump(contextrjjumpTarget);
        } catch (JumpException.RetryJump rj) {
            return handleRetryJump(getRuntime(), rj);
        }
    }
    private IRubyObject handleBreakJump(Ruby runtimeBlock newBlockJumpException.BreakJump bjint jumpTarget) {
        switch(newBlock.type) {
            case 
                if (bj.getTarget() == jumpTargetreturn (IRubyObjectbj.getValue();
                
                throw runtime.newLocalJumpError(.., (IRubyObject)bj.getValue(), "unexpected break");
            case :
                if (newBlock.isEscaped()) throw runtime.newLocalJumpError(.., (IRubyObject)bj.getValue(), "break from proc-closure");
        }
        
        throw bj;
    }
    private IRubyObject handleReturnJump(ThreadContext contextJumpException.ReturnJump rjint jumpTarget) {
        int target = rj.getTarget();
        // lambda always just returns the value
        if (target == jumpTarget && isLambda()) return (IRubyObjectrj.getValue();
        // returns can't propagate out of threads. rethrow to let thread handle it
        if (isThread()) throw rj;
        // If the block-receiving method is not still active and the original
        // enclosing frame is no longer on the stack, it's a bad return.
        // FIXME: this is not very efficient for cases where it won't error
        if (target == jumpTarget && !context.isJumpTargetAlive(target, 0)) {
            throw context.runtime.newLocalJumpError(..,
                    (IRubyObjectrj.getValue(), "unexpected return");
        }
        // otherwise, let it propagate
        throw rj;
    }
    private IRubyObject handleRetryJump(Ruby runtimeJumpException.RetryJump rj) {
        throw runtime.newLocalJumpError(.., (IRubyObject)rj.getValue(), "retry not supported outside rescue");
    }
    @JRubyMethod(name = "arity")
    public RubyFixnum arity() {
        return getRuntime().newFixnum(.arity().getValue());
    }
    
    @JRubyMethod(name = "to_proc")
    public RubyProc to_proc() {
    	return this;
    }
    @JRubyMethod(name = "source_location", compat = )
    public IRubyObject source_location(ThreadContext context) {
        Ruby runtime = context.runtime;
        if ( != null) {
            return runtime.newArray(runtime.newString(.getFile()),
                    runtime.newFixnum(.getLine() + 1 /*zero-based*/));
        } else if ( != null) {
            Binding binding = .getBinding();
            return runtime.newArray(runtime.newString(binding.getFile()),
                    runtime.newFixnum(binding.getLine() + 1 /*zero-based*/));
        }
        return runtime.getNil();
    }
    @JRubyMethod(name = "parameters", compat = )
    public IRubyObject parameters(ThreadContext context) {
        BlockBody body = this.getBlock().getBody();
        if (body instanceof MethodBlockreturn ((MethodBlockbody).getMethod().parameters(context);
        return RuntimeHelpers.parameterListToParameters(context.runtime,
                body.getParameterList(), isLambda());
    }
    @JRubyMethod(name = "lambda?", compat = )
    public IRubyObject lambda_p(ThreadContext context) {
        return context.runtime.newBoolean(isLambda());
    }
    private boolean isLambda() {
        return .equals(..);
    }
    
    private boolean isProc() {
        return .equals(..);
    }
    private boolean isThread() {
        return .equals(..);
    }
New to GrepCode? Check out our FAQ X