/*
* Copyright (C) 2011 René Jeschke <rene_jeschke@yahoo.de>
*
* Licensed under the Apache License, Version 2.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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.rjeschke.weel;
class InstrLoad implements Instr
{
Value value;
public InstrLoad()
{
this.value = new Value();
}
public InstrLoad(final double v)
{
this.value = new Value(v);
}
public InstrLoad(final String v)
{
this.value = new Value(v);
}
/** @see Instr#getType() */
@Override
public Op getType()
{
return Op.LOAD;
}
/** @see java.lang.Object#toString() */
@Override
public String toString()
{
return "LOAD " + escape(this.value.toString());
}
/** @see Instr#write(JvmMethodWriter) */
@Override
public void write(JvmMethodWriter mw)
{
mw.aload(0);
switch(this.value.getType())
{
case NULL:
mw.invokeVirtual("com.github.rjeschke.weel.WeelRuntime", "load", "()V");
break;
case STRING:
mw.ldc(this.value.getString());
mw.invokeVirtual("com.github.rjeschke.weel.WeelRuntime", "load", "(Ljava/lang/String;)V");
break;
case NUMBER:
{
final double val = this.value.getNumber();
final int iVal = (int) val;
if (iVal == val)
{
mw.ldc(iVal);
mw.invokeVirtual("com.github.rjeschke.weel.WeelRuntime", "load", "(I)V");
}
else
{
final float check = (float) val;
if (Double.compare(check, val) == 0)
{
mw.ldc(check);
mw.invokeVirtual("com.github.rjeschke.weel.WeelRuntime", "load", "(F)V");
}
else
{
mw.ldc(val);
mw.invokeVirtual("com.github.rjeschke.weel.WeelRuntime", "load", "(D)V");
}
}
break;
}
default:
throw new WeelException("Illegal value: " + this.value);
}
}
public final static String escape(final String input)
{
final StringBuilder sb = new StringBuilder(input.length());
for(int i = 0; i < input.length(); i++)
{
final char c = input.charAt(i);
switch(c)
{
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
default:
sb.append(c);
}
}
return sb.toString();
}
}