package org.jruby.ir.instructions;
import org.jruby.RubySymbol;
import org.jruby.ir.IRVisitor;
import org.jruby.ir.Operation;
import org.jruby.ir.operands.Operand;
import org.jruby.ir.operands.UndefinedValue;
import org.jruby.ir.operands.Variable;
import org.jruby.ir.persistence.IRReaderDecoder;
import org.jruby.ir.persistence.IRWriterEncoder;
import org.jruby.ir.transformations.inlining.CloneInfo;
import org.jruby.parser.StaticScope;
import org.jruby.runtime.DynamicScope;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.opto.ConstantCache;
import org.jruby.runtime.opto.Invalidator;
public class LexicalSearchConstInstr extends OneOperandResultBaseInstr implements FixedArityInstr {
private RubySymbol constantName;
private volatile transient ConstantCache cache;
public LexicalSearchConstInstr(Variable result, Operand definingScope, RubySymbol constantName) {
super(Operation.LEXICAL_SEARCH_CONST, result, definingScope);
assert result != null: "LexicalSearchConstInstr result is null";
this.constantName = constantName;
}
public Operand getDefiningScope() {
return getOperand1();
}
public String getId() {
return constantName.idString();
}
public RubySymbol getName() {
return constantName;
}
@Override
public String[] toStringNonOperandArgs() {
return new String[] { "name: " + constantName};
}
@Override
public Instr clone(CloneInfo ii) {
return new LexicalSearchConstInstr(ii.getRenamedVariable(result), getDefiningScope().cloneForInlining(ii), constantName);
}
@Override
public void encode(IRWriterEncoder e) {
super.encode(e);
e.encode(getDefiningScope());
e.encode(getName());
}
public static LexicalSearchConstInstr decode(IRReaderDecoder d) {
return new LexicalSearchConstInstr(d.decodeVariable(), d.decodeOperand(), d.decodeSymbol());
}
private Object cache(ThreadContext context, StaticScope currScope, DynamicScope currDynScope, IRubyObject self, Object[] temp) {
StaticScope staticScope = (StaticScope) getDefiningScope().retrieve(context, self, currScope, currDynScope, temp);
String id = getId();
IRubyObject constant = staticScope.getConstantDefined(id);
if (constant == null) {
constant = UndefinedValue.UNDEFINED;
} else {
Invalidator invalidator = context.runtime.getConstantInvalidator(id);
cache = new ConstantCache(constant, invalidator.getData(), invalidator);
}
return constant;
}
@Override
public Object interpret(ThreadContext context, StaticScope currScope, DynamicScope currDynScope, IRubyObject self, Object[] temp) {
ConstantCache cache = this.cache;
if (!ConstantCache.isCached(cache)) return cache(context, currScope, currDynScope, self, temp);
return cache.value;
}
@Override
public void visit(IRVisitor visitor) {
visitor.LexicalSearchConstInstr(this);
}
}