Define clean up steps and clean up code

This commit is contained in:
Enrico Horn
2021-07-09 20:37:32 +02:00
parent 5465eff841
commit bf23883492
106 changed files with 2457 additions and 1412 deletions

138
.ide/cleanup.xml Normal file
View File

@@ -0,0 +1,138 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<profiles version="2">
<profile kind="CleanUpProfile" name="Default" version="2">
<setting id="cleanup.array_with_curly" value="true"/>
<setting id="cleanup.use_autoboxing" value="true"/>
<setting id="cleanup.always_use_this_for_non_static_method_access" value="false"/>
<setting id="cleanup.remove_trailing_whitespaces_ignore_empty" value="false"/>
<setting id="cleanup.primitive_comparison" value="false"/>
<setting id="cleanup.system_property_file_encoding" value="true"/>
<setting id="cleanup.format_source_code_changes_only" value="false"/>
<setting id="cleanup.remove_redundant_semicolons" value="true"/>
<setting id="cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class" value="true"/>
<setting id="cleanup.useless_continue" value="true"/>
<setting id="cleanup.remove_redundant_type_arguments" value="true"/>
<setting id="cleanup.remove_unused_imports" value="true"/>
<setting id="cleanup.break_loop" value="false"/>
<setting id="cleanup.pull_up_assignment" value="false"/>
<setting id="cleanup.stringbuilder" value="false"/>
<setting id="cleanup.no_super" value="true"/>
<setting id="cleanup.arrays_fill" value="false"/>
<setting id="cleanup.use_lambda" value="true"/>
<setting id="cleanup.operand_factorization" value="false"/>
<setting id="cleanup.simplify_lambda_expression_and_method_ref" value="true"/>
<setting id="cleanup.always_use_blocks" value="true"/>
<setting id="cleanup.sort_members_all" value="false"/>
<setting id="cleanup.system_property_path_separator" value="true"/>
<setting id="cleanup.instanceof" value="false"/>
<setting id="cleanup.add_missing_annotations" value="true"/>
<setting id="cleanup.precompile_regex" value="false"/>
<setting id="cleanup.always_use_this_for_non_static_field_access" value="false"/>
<setting id="cleanup.boolean_literal" value="true"/>
<setting id="cleanup.always_use_parentheses_in_expressions" value="false"/>
<setting id="cleanup.sort_members" value="false"/>
<setting id="cleanup.remove_unused_local_variables" value="false"/>
<setting id="cleanup.add_missing_deprecated_annotations" value="true"/>
<setting id="cleanup.no_string_creation" value="true"/>
<setting id="cleanup.use_unboxing" value="false"/>
<setting id="cleanup.use_blocks_only_for_return_and_throw" value="false"/>
<setting id="cleanup.standard_comparison" value="false"/>
<setting id="cleanup.if_condition" value="true"/>
<setting id="cleanup.system_property_line_separator" value="true"/>
<setting id="cleanup.remove_trailing_whitespaces" value="true"/>
<setting id="cleanup.map_cloning" value="true"/>
<setting id="cleanup.add_serial_version_id" value="false"/>
<setting id="cleanup.try_with_resource" value="true"/>
<setting id="cleanup.use_this_for_non_static_method_access" value="false"/>
<setting id="cleanup.use_this_for_non_static_method_access_only_if_necessary" value="true"/>
<setting id="cleanup.single_used_field" value="false"/>
<setting id="cleanup.reduce_indentation" value="false"/>
<setting id="cleanup.primitive_parsing" value="false"/>
<setting id="cleanup.make_local_variable_final" value="false"/>
<setting id="cleanup.add_missing_methods" value="false"/>
<setting id="cleanup.qualify_static_member_accesses_with_declaring_class" value="true"/>
<setting id="cleanup.add_missing_override_annotations" value="true"/>
<setting id="cleanup.use_blocks" value="false"/>
<setting id="cleanup.multi_catch" value="true"/>
<setting id="cleanup.pull_out_if_from_if_else" value="true"/>
<setting id="cleanup.collection_cloning" value="true"/>
<setting id="cleanup.convert_to_enhanced_for_loop_if_loop_var_used" value="true"/>
<setting id="cleanup.make_variable_declarations_final" value="true"/>
<setting id="cleanup.redundant_comparator" value="false"/>
<setting id="cleanup.remove_unused_private_types" value="true"/>
<setting id="cleanup.system_property_boolean" value="true"/>
<setting id="cleanup.qualify_static_method_accesses_with_declaring_class" value="false"/>
<setting id="cleanup.organize_imports" value="true"/>
<setting id="cleanup.lazy_logical_operator" value="true"/>
<setting id="cleanup.bitwise_conditional_expression" value="false"/>
<setting id="cleanup.use_directly_map_method" value="false"/>
<setting id="cleanup.add_all" value="false"/>
<setting id="cleanup.system_property_file_separator" value="true"/>
<setting id="cleanup.qualify_static_field_accesses_with_declaring_class" value="false"/>
<setting id="cleanup.add_generated_serial_version_id" value="false"/>
<setting id="cleanup.controlflow_merge" value="false"/>
<setting id="cleanup.primitive_serialization" value="false"/>
<setting id="cleanup.comparing_on_criteria" value="true"/>
<setting id="cleanup.comparison_statement" value="true"/>
<setting id="cleanup.extract_increment" value="false"/>
<setting id="cleanup.insert_inferred_type_arguments" value="false"/>
<setting id="cleanup.make_private_fields_final" value="true"/>
<setting id="cleanup.useless_return" value="true"/>
<setting id="cleanup.instanceof_keyword" value="true"/>
<setting id="cleanup.use_this_for_non_static_field_access_only_if_necessary" value="true"/>
<setting id="cleanup.remove_trailing_whitespaces_all" value="true"/>
<setting id="cleanup.one_if_rather_than_duplicate_blocks_that_fall_through" value="true"/>
<setting id="cleanup.valueof_rather_than_instantiation" value="true"/>
<setting id="cleanup.plain_replacement" value="false"/>
<setting id="cleanup.remove_unnecessary_array_creation" value="true"/>
<setting id="cleanup.remove_private_constructors" value="true"/>
<setting id="cleanup.make_parameters_final" value="false"/>
<setting id="cleanup.substring" value="false"/>
<setting id="cleanup.ternary_operator" value="false"/>
<setting id="cleanup.merge_conditional_blocks" value="false"/>
<setting id="cleanup.return_expression" value="true"/>
<setting id="cleanup.system_property" value="true"/>
<setting id="cleanup.unlooped_while" value="true"/>
<setting id="cleanup.convert_to_enhanced_for_loop" value="true"/>
<setting id="cleanup.remove_unused_private_fields" value="true"/>
<setting id="cleanup.never_use_blocks" value="false"/>
<setting id="cleanup.remove_redundant_modifiers" value="true"/>
<setting id="cleanup.unreachable_block" value="false"/>
<setting id="cleanup.redundant_falling_through_block_end" value="false"/>
<setting id="cleanup.switch" value="false"/>
<setting id="cleanup.number_suffix" value="true"/>
<setting id="cleanup.remove_unnecessary_nls_tags" value="true"/>
<setting id="cleanup.convert_to_switch_expressions" value="false"/>
<setting id="cleanup.use_this_for_non_static_field_access" value="false"/>
<setting id="cleanup.static_inner_class" value="false"/>
<setting id="cleanup.use_string_is_blank" value="true"/>
<setting id="cleanup.add_missing_nls_tags" value="false"/>
<setting id="cleanup.qualify_static_member_accesses_through_instances_with_declaring_class" value="true"/>
<setting id="cleanup.remove_unnecessary_casts" value="true"/>
<setting id="cleanup.objects_equals" value="false"/>
<setting id="cleanup.convert_functional_interfaces" value="true"/>
<setting id="cleanup.format_source_code" value="true"/>
<setting id="cleanup.else_if" value="false"/>
<setting id="cleanup.boolean_value_rather_than_comparison" value="true"/>
<setting id="cleanup.add_default_serial_version_id" value="true"/>
<setting id="cleanup.remove_unused_private_methods" value="true"/>
<setting id="cleanup.make_type_abstract_if_missing_method" value="false"/>
<setting id="cleanup.join" value="false"/>
<setting id="cleanup.embedded_if" value="false"/>
<setting id="cleanup.use_anonymous_class_creation" value="false"/>
<setting id="cleanup.invert_equals" value="false"/>
<setting id="cleanup.add_missing_override_annotations_interface_methods" value="true"/>
<setting id="cleanup.remove_unused_private_members" value="false"/>
<setting id="cleanup.strictly_equal_or_different" value="true"/>
<setting id="cleanup.never_use_parentheses_in_expressions" value="true"/>
<setting id="cleanup.push_down_negation" value="false"/>
<setting id="cleanup.evaluate_nullable" value="false"/>
<setting id="cleanup.use_parentheses_in_expressions" value="true"/>
<setting id="cleanup.hash" value="false"/>
<setting id="cleanup.double_negation" value="true"/>
<setting id="cleanup.overridden_assignment" value="true"/>
<setting id="cleanup.primitive_rather_than_wrapper" value="true"/>
<setting id="cleanup.correct_indentation" value="false"/>
<setting id="cleanup.use_var" value="false"/>
</profile>
</profiles>

View File

@@ -113,7 +113,7 @@ public final class Buffer {
*
* @return the value as a {@link LuaString}
*/
public final LuaString tostring() {
public LuaString tostring() {
realloc(length, 0);
return LuaString.valueOf(bytes, offset, length);
}
@@ -132,6 +132,7 @@ public final class Buffer {
*
* @return the value as a Java String
*/
@Override
public String toString() {
return tojstring();
}
@@ -141,7 +142,7 @@ public final class Buffer {
*
* @return {@code this} to allow call chaining
*/
public final Buffer append(byte b) {
public Buffer append(byte b) {
makeroom(0, 1);
bytes[offset+length++] = b;
return this;
@@ -152,7 +153,7 @@ public final class Buffer {
*
* @return {@code this} to allow call chaining
*/
public final Buffer append(LuaValue val) {
public Buffer append(LuaValue val) {
append(val.strvalue());
return this;
}
@@ -162,7 +163,7 @@ public final class Buffer {
*
* @return {@code this} to allow call chaining
*/
public final Buffer append(LuaString str) {
public Buffer append(LuaString str) {
final int n = str.m_length;
makeroom(0, n);
str.copyInto(0, bytes, offset+length, n);
@@ -177,7 +178,7 @@ public final class Buffer {
* @return {@code this} to allow call chaining
* @see LuaString#encodeToUtf8(char[], int, byte[], int)
*/
public final Buffer append(String str) {
public Buffer append(String str) {
char[] c = str.toCharArray();
final int n = LuaString.lengthAsUtf8(c);
makeroom(0, n);
@@ -246,7 +247,7 @@ public final class Buffer {
* @param nafter number of unused bytes which must follow the data after
* this completes
*/
public final void makeroom(int nbefore, int nafter) {
public void makeroom(int nbefore, int nafter) {
if (value != null) {
LuaString s = value.strvalue();
value = null;
@@ -267,7 +268,7 @@ public final class Buffer {
* @param newSize the size of the buffer to use
* @param newOffset the offset to use
*/
private final void realloc(int newSize, int newOffset) {
private void realloc(int newSize, int newOffset) {
if (newSize != bytes.length) {
byte[] newBytes = new byte[newSize];
System.arraycopy(bytes, offset, newBytes, newOffset, length);

View File

@@ -195,6 +195,7 @@ public class Globals extends LuaTable {
* Check that this object is a Globals object, and return it, otherwise
* throw an error.
*/
@Override
public Globals checkglobals() {
return this;
}
@@ -415,14 +416,17 @@ public class Globals extends LuaTable {
n = s.length();
}
@Override
public void close() throws IOException {
i = n;
}
@Override
public int read() throws IOException {
return i < n? s.charAt(i++): -1;
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
int j = 0;
for (; j < len && i < n; ++j, ++i)
@@ -444,15 +448,18 @@ public class Globals extends LuaTable {
abstract protected int avail() throws IOException;
@Override
public int read() throws IOException {
int a = avail();
return (a <= 0? -1: 0xff & b[i++]);
return a <= 0? -1: 0xff & b[i++];
}
@Override
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
@Override
public int read(byte[] b, int i0, int n) throws IOException {
int a = avail();
if (a <= 0)
@@ -463,12 +470,14 @@ public class Globals extends LuaTable {
return n_read;
}
@Override
public long skip(long n) throws IOException {
final long k = Math.min(n, j-i);
i += k;
return k;
}
@Override
public int available() throws IOException {
return j-i;
}
@@ -488,6 +497,7 @@ public class Globals extends LuaTable {
this.r = r;
}
@Override
protected int avail() throws IOException {
if (i < j)
return j-i;
@@ -505,6 +515,7 @@ public class Globals extends LuaTable {
return j;
}
@Override
public void close() throws IOException {
r.close();
}
@@ -529,6 +540,7 @@ public class Globals extends LuaTable {
this.s = s;
}
@Override
protected int avail() throws IOException {
if (i < j)
return j-i;
@@ -549,10 +561,12 @@ public class Globals extends LuaTable {
return n;
}
@Override
public void close() throws IOException {
s.close();
}
@Override
public synchronized void mark(int n) {
if (i > 0 || n > b.length) {
byte[] dest = n > b.length? new byte[n]: b;
@@ -563,10 +577,12 @@ public class Globals extends LuaTable {
}
}
@Override
public boolean markSupported() {
return true;
}
@Override
public synchronized void reset() throws IOException {
i = 0;
}

View File

@@ -124,8 +124,8 @@ public class LoadState {
public static final int NUMBER_FORMAT_NUM_PATCH_INT32 = 4;
// type constants
public static final int LUA_TINT = (-2);
public static final int LUA_TNONE = (-1);
public static final int LUA_TINT = -2;
public static final int LUA_TNONE = -1;
public static final int LUA_TNIL = 0;
public static final int LUA_TBOOLEAN = 1;
public static final int LUA_TLIGHTUSERDATA = 2;
@@ -201,8 +201,8 @@ public class LoadState {
**/
int loadInt() throws IOException {
is.readFully(buf, 0, 4);
return luacLittleEndian? (buf[3]<<24) | ((0xff & buf[2])<<16) | ((0xff & buf[1])<<8) | (0xff & buf[0])
: (buf[0]<<24) | ((0xff & buf[1])<<16) | ((0xff & buf[2])<<8) | (0xff & buf[3]);
return luacLittleEndian? buf[3]<<24 | (0xff & buf[2])<<16 | (0xff & buf[1])<<8 | 0xff & buf[0]
: buf[0]<<24 | (0xff & buf[1])<<16 | (0xff & buf[2])<<8 | 0xff & buf[3];
}
/**
@@ -222,9 +222,8 @@ public class LoadState {
is.readFully(buf, 0, m);
int[] array = new int[n];
for (int i = 0, j = 0; i < n; ++i, j += 4)
array[i] = luacLittleEndian
? (buf[j+3]<<24) | ((0xff & buf[j+2])<<16) | ((0xff & buf[j+1])<<8) | (0xff & buf[j+0])
: (buf[j+0]<<24) | ((0xff & buf[j+1])<<16) | ((0xff & buf[j+2])<<8) | (0xff & buf[j+3]);
array[i] = luacLittleEndian? buf[j+3]<<24 | (0xff & buf[j+2])<<16 | (0xff & buf[j+1])<<8 | 0xff & buf[j+0]
: buf[j+0]<<24 | (0xff & buf[j+1])<<16 | (0xff & buf[j+2])<<8 | 0xff & buf[j+3];
return array;
}
@@ -243,7 +242,7 @@ public class LoadState {
b = loadInt();
a = loadInt();
}
return (((long) b)<<32) | (((long) a) & 0xffffffffL);
return (long) b<<32 | a & 0xffffffffL;
}
/**
@@ -268,19 +267,19 @@ public class LoadState {
* to the bits provided.
*/
public static LuaValue longBitsToLuaNumber(long bits) {
if ((bits & ((1L<<63)-1)) == 0L) {
if ((bits & (1L<<63)-1) == 0L) {
return LuaValue.ZERO;
}
int e = (int) ((bits>>52) & 0x7ffL)-1023;
int e = (int) (bits>>52 & 0x7ffL)-1023;
if (e >= 0 && e < 31) {
long f = bits & 0xFFFFFFFFFFFFFL;
int shift = 52-e;
long intPrecMask = (1L<<shift)-1;
if ((f & intPrecMask) == 0) {
int intValue = (int) (f>>shift) | (1<<e);
return LuaInteger.valueOf(((bits>>63) != 0)? -intValue: intValue);
int intValue = (int) (f>>shift) | 1<<e;
return LuaInteger.valueOf(bits>>63 != 0? -intValue: intValue);
}
}
@@ -316,7 +315,7 @@ public class LoadState {
values[i] = LuaValue.NIL;
break;
case LUA_TBOOLEAN:
values[i] = (0 != is.readUnsignedByte()? LuaValue.TRUE: LuaValue.FALSE);
values[i] = 0 != is.readUnsignedByte()? LuaValue.TRUE: LuaValue.FALSE;
break;
case LUA_TINT:
values[i] = LuaInteger.valueOf(loadInt());
@@ -345,7 +344,7 @@ public class LoadState {
f.upvalues = n > 0? new Upvaldesc[n]: NOUPVALDESCS;
for (int i = 0; i < n; i++) {
boolean instack = is.readByte() != 0;
int idx = ((int) is.readByte()) & 0xff;
int idx = is.readByte() & 0xff;
f.upvalues[i] = new Upvaldesc(null, instack, idx);
}
}
@@ -412,7 +411,7 @@ public class LoadState {
public void loadHeader() throws IOException {
luacVersion = is.readByte();
luacFormat = is.readByte();
luacLittleEndian = (0 != is.readByte());
luacLittleEndian = 0 != is.readByte();
luacSizeofInt = is.readByte();
luacSizeofSizeT = is.readByte();
luacSizeofInstruction = is.readByte();
@@ -479,6 +478,7 @@ public class LoadState {
}
private static final class GlobalsUndumper implements Globals.Undumper {
@Override
public Prototype undump(InputStream stream, String chunkname) throws IOException {
return LoadState.undump(stream, chunkname);
}

View File

@@ -64,33 +64,33 @@ public class Lua {
*/
public static final int SIZE_C = 9;
public static final int SIZE_B = 9;
public static final int SIZE_Bx = (SIZE_C+SIZE_B);
public static final int SIZE_Bx = SIZE_C+SIZE_B;
public static final int SIZE_A = 8;
public static final int SIZE_Ax = (SIZE_C+SIZE_B+SIZE_A);
public static final int SIZE_Ax = SIZE_C+SIZE_B+SIZE_A;
public static final int SIZE_OP = 6;
public static final int POS_OP = 0;
public static final int POS_A = (POS_OP+SIZE_OP);
public static final int POS_C = (POS_A+SIZE_A);
public static final int POS_B = (POS_C+SIZE_C);
public static final int POS_A = POS_OP+SIZE_OP;
public static final int POS_C = POS_A+SIZE_A;
public static final int POS_B = POS_C+SIZE_C;
public static final int POS_Bx = POS_C;
public static final int POS_Ax = POS_A;
public static final int MAX_OP = ((1<<SIZE_OP)-1);
public static final int MAXARG_A = ((1<<SIZE_A)-1);
public static final int MAXARG_B = ((1<<SIZE_B)-1);
public static final int MAXARG_C = ((1<<SIZE_C)-1);
public static final int MAXARG_Bx = ((1<<SIZE_Bx)-1);
public static final int MAXARG_sBx = (MAXARG_Bx>>1); /* `sBx' is signed */
public static final int MAXARG_Ax = ((1<<SIZE_Ax)-1);
public static final int MAX_OP = (1<<SIZE_OP)-1;
public static final int MAXARG_A = (1<<SIZE_A)-1;
public static final int MAXARG_B = (1<<SIZE_B)-1;
public static final int MAXARG_C = (1<<SIZE_C)-1;
public static final int MAXARG_Bx = (1<<SIZE_Bx)-1;
public static final int MAXARG_sBx = MAXARG_Bx>>1; /* `sBx' is signed */
public static final int MAXARG_Ax = (1<<SIZE_Ax)-1;
public static final int MASK_OP = ((1<<SIZE_OP)-1)<<POS_OP;
public static final int MASK_A = ((1<<SIZE_A)-1)<<POS_A;
public static final int MASK_B = ((1<<SIZE_B)-1)<<POS_B;
public static final int MASK_C = ((1<<SIZE_C)-1)<<POS_C;
public static final int MASK_Bx = ((1<<SIZE_Bx)-1)<<POS_Bx;
public static final int MASK_Ax = ((1<<SIZE_Ax)-1)<<POS_Ax;
public static final int MASK_OP = (1<<SIZE_OP)-1<<POS_OP;
public static final int MASK_A = (1<<SIZE_A)-1<<POS_A;
public static final int MASK_B = (1<<SIZE_B)-1<<POS_B;
public static final int MASK_C = (1<<SIZE_C)-1<<POS_C;
public static final int MASK_Bx = (1<<SIZE_Bx)-1<<POS_Bx;
public static final int MASK_Ax = (1<<SIZE_Ax)-1<<POS_Ax;
public static final int MASK_NOT_OP = ~MASK_OP;
public static final int MASK_NOT_A = ~MASK_A;
@@ -102,31 +102,31 @@ public class Lua {
** the following macros help to manipulate instructions
*/
public static int GET_OPCODE(int i) {
return (i>>POS_OP) & MAX_OP;
return i>>POS_OP & MAX_OP;
}
public static int GETARG_A(int i) {
return (i>>POS_A) & MAXARG_A;
return i>>POS_A & MAXARG_A;
}
public static int GETARG_Ax(int i) {
return (i>>POS_Ax) & MAXARG_Ax;
return i>>POS_Ax & MAXARG_Ax;
}
public static int GETARG_B(int i) {
return (i>>POS_B) & MAXARG_B;
return i>>POS_B & MAXARG_B;
}
public static int GETARG_C(int i) {
return (i>>POS_C) & MAXARG_C;
return i>>POS_C & MAXARG_C;
}
public static int GETARG_Bx(int i) {
return (i>>POS_Bx) & MAXARG_Bx;
return i>>POS_Bx & MAXARG_Bx;
}
public static int GETARG_sBx(int i) {
return ((i>>POS_Bx) & MAXARG_Bx)-MAXARG_sBx;
return (i>>POS_Bx & MAXARG_Bx)-MAXARG_sBx;
}
/*
@@ -134,23 +134,23 @@ public class Lua {
*/
/** this bit 1 means constant (0 means register) */
public static final int BITRK = (1<<(SIZE_B-1));
public static final int BITRK = 1<<SIZE_B-1;
/** test whether value is a constant */
public static boolean ISK(int x) {
return 0 != ((x) & BITRK);
return 0 != (x & BITRK);
}
/** gets the index of the constant */
public static int INDEXK(int r) {
return ((int) (r) & ~BITRK);
return r & ~BITRK;
}
public static final int MAXINDEXRK = (BITRK-1);
public static final int MAXINDEXRK = BITRK-1;
/** code a constant index as a RK value */
public static int RKASK(int x) {
return ((x) | BITRK);
return x | BITRK;
}
/**
@@ -272,46 +272,46 @@ public class Lua {
public static final int[] luaP_opmodes = {
/* T A B C mode opcode */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iABC), /* OP_MOVE */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgN<<2) | (iABx), /* OP_LOADK */
(0<<7) | (1<<6) | (OpArgN<<4) | (OpArgN<<2) | (iABx), /* OP_LOADKX */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgU<<2) | (iABC), /* OP_LOADBOOL */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABC), /* OP_LOADNIL */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABC), /* OP_GETUPVAL */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgK<<2) | (iABC), /* OP_GETTABUP */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgK<<2) | (iABC), /* OP_GETTABLE */
(0<<7) | (0<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_SETTABUP */
(0<<7) | (0<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABC), /* OP_SETUPVAL */
(0<<7) | (0<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_SETTABLE */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgU<<2) | (iABC), /* OP_NEWTABLE */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgK<<2) | (iABC), /* OP_SELF */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_ADD */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_SUB */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_MUL */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_DIV */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_MOD */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_POW */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iABC), /* OP_UNM */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iABC), /* OP_NOT */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iABC), /* OP_LEN */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgR<<2) | (iABC), /* OP_CONCAT */
(0<<7) | (0<<6) | (OpArgR<<4) | (OpArgN<<2) | (iAsBx), /* OP_JMP */
(1<<7) | (0<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_EQ */
(1<<7) | (0<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_LT */
(1<<7) | (0<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_LE */
(1<<7) | (0<<6) | (OpArgN<<4) | (OpArgU<<2) | (iABC), /* OP_TEST */
(1<<7) | (1<<6) | (OpArgR<<4) | (OpArgU<<2) | (iABC), /* OP_TESTSET */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgU<<2) | (iABC), /* OP_CALL */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgU<<2) | (iABC), /* OP_TAILCALL */
(0<<7) | (0<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABC), /* OP_RETURN */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iAsBx), /* OP_FORLOOP */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iAsBx), /* OP_FORPREP */
(0<<7) | (0<<6) | (OpArgN<<4) | (OpArgU<<2) | (iABC), /* OP_TFORCALL */
(1<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iAsBx), /* OP_TFORLOOP */
(0<<7) | (0<<6) | (OpArgU<<4) | (OpArgU<<2) | (iABC), /* OP_SETLIST */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABx), /* OP_CLOSURE */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABC), /* OP_VARARG */
(0<<7) | (0<<6) | (OpArgU<<4) | (OpArgU<<2) | (iAx), /* OP_EXTRAARG */
0<<7 | 1<<6 | OpArgR<<4 | OpArgN<<2 | iABC, /* OP_MOVE */
0<<7 | 1<<6 | OpArgK<<4 | OpArgN<<2 | iABx, /* OP_LOADK */
0<<7 | 1<<6 | OpArgN<<4 | OpArgN<<2 | iABx, /* OP_LOADKX */
0<<7 | 1<<6 | OpArgU<<4 | OpArgU<<2 | iABC, /* OP_LOADBOOL */
0<<7 | 1<<6 | OpArgU<<4 | OpArgN<<2 | iABC, /* OP_LOADNIL */
0<<7 | 1<<6 | OpArgU<<4 | OpArgN<<2 | iABC, /* OP_GETUPVAL */
0<<7 | 1<<6 | OpArgU<<4 | OpArgK<<2 | iABC, /* OP_GETTABUP */
0<<7 | 1<<6 | OpArgR<<4 | OpArgK<<2 | iABC, /* OP_GETTABLE */
0<<7 | 0<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_SETTABUP */
0<<7 | 0<<6 | OpArgU<<4 | OpArgN<<2 | iABC, /* OP_SETUPVAL */
0<<7 | 0<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_SETTABLE */
0<<7 | 1<<6 | OpArgU<<4 | OpArgU<<2 | iABC, /* OP_NEWTABLE */
0<<7 | 1<<6 | OpArgR<<4 | OpArgK<<2 | iABC, /* OP_SELF */
0<<7 | 1<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_ADD */
0<<7 | 1<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_SUB */
0<<7 | 1<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_MUL */
0<<7 | 1<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_DIV */
0<<7 | 1<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_MOD */
0<<7 | 1<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_POW */
0<<7 | 1<<6 | OpArgR<<4 | OpArgN<<2 | iABC, /* OP_UNM */
0<<7 | 1<<6 | OpArgR<<4 | OpArgN<<2 | iABC, /* OP_NOT */
0<<7 | 1<<6 | OpArgR<<4 | OpArgN<<2 | iABC, /* OP_LEN */
0<<7 | 1<<6 | OpArgR<<4 | OpArgR<<2 | iABC, /* OP_CONCAT */
0<<7 | 0<<6 | OpArgR<<4 | OpArgN<<2 | iAsBx, /* OP_JMP */
1<<7 | 0<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_EQ */
1<<7 | 0<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_LT */
1<<7 | 0<<6 | OpArgK<<4 | OpArgK<<2 | iABC, /* OP_LE */
1<<7 | 0<<6 | OpArgN<<4 | OpArgU<<2 | iABC, /* OP_TEST */
1<<7 | 1<<6 | OpArgR<<4 | OpArgU<<2 | iABC, /* OP_TESTSET */
0<<7 | 1<<6 | OpArgU<<4 | OpArgU<<2 | iABC, /* OP_CALL */
0<<7 | 1<<6 | OpArgU<<4 | OpArgU<<2 | iABC, /* OP_TAILCALL */
0<<7 | 0<<6 | OpArgU<<4 | OpArgN<<2 | iABC, /* OP_RETURN */
0<<7 | 1<<6 | OpArgR<<4 | OpArgN<<2 | iAsBx, /* OP_FORLOOP */
0<<7 | 1<<6 | OpArgR<<4 | OpArgN<<2 | iAsBx, /* OP_FORPREP */
0<<7 | 0<<6 | OpArgN<<4 | OpArgU<<2 | iABC, /* OP_TFORCALL */
1<<7 | 1<<6 | OpArgR<<4 | OpArgN<<2 | iAsBx, /* OP_TFORLOOP */
0<<7 | 0<<6 | OpArgU<<4 | OpArgU<<2 | iABC, /* OP_SETLIST */
0<<7 | 1<<6 | OpArgU<<4 | OpArgN<<2 | iABx, /* OP_CLOSURE */
0<<7 | 1<<6 | OpArgU<<4 | OpArgN<<2 | iABC, /* OP_VARARG */
0<<7 | 0<<6 | OpArgU<<4 | OpArgU<<2 | iAx, /* OP_EXTRAARG */
};
public static int getOpMode(int m) {
@@ -319,19 +319,19 @@ public class Lua {
}
public static int getBMode(int m) {
return (luaP_opmodes[m]>>4) & 3;
return luaP_opmodes[m]>>4 & 3;
}
public static int getCMode(int m) {
return (luaP_opmodes[m]>>2) & 3;
return luaP_opmodes[m]>>2 & 3;
}
public static boolean testAMode(int m) {
return 0 != (luaP_opmodes[m] & (1<<6));
return 0 != (luaP_opmodes[m] & 1<<6);
}
public static boolean testTMode(int m) {
return 0 != (luaP_opmodes[m] & (1<<7));
return 0 != (luaP_opmodes[m] & 1<<7);
}
/* number of list items to accumulate before a SETLIST instruction */

View File

@@ -57,18 +57,22 @@ public final class LuaBoolean extends LuaValue {
this.v = b;
}
@Override
public int type() {
return LuaValue.TBOOLEAN;
}
@Override
public String typename() {
return "boolean";
}
@Override
public boolean isboolean() {
return true;
}
@Override
public LuaValue not() {
return v? FALSE: LuaValue.TRUE;
}
@@ -82,22 +86,27 @@ public final class LuaBoolean extends LuaValue {
return v;
}
@Override
public boolean toboolean() {
return v;
}
@Override
public String tojstring() {
return v? "true": "false";
}
@Override
public boolean optboolean(boolean defval) {
return this.v;
}
@Override
public boolean checkboolean() {
return v;
}
@Override
public LuaValue getmetatable() {
return s_metatable;
}

View File

@@ -97,7 +97,7 @@ import org.luaj.vm2.lib.DebugLib.CallFrame;
* @see Globals#compiler
*/
public class LuaClosure extends LuaFunction {
private static final UpValue[] NOUPVALUES = new UpValue[0];
private static final UpValue[] NOUPVALUES = {};
public final Prototype p;
@@ -119,6 +119,7 @@ public class LuaClosure extends LuaFunction {
globals = env instanceof Globals? (Globals) env: null;
}
@Override
public void initupvalue1(LuaValue env) {
if (p.upvalues == null || p.upvalues.length == 0)
this.upValues = NOUPVALUES;
@@ -128,18 +129,22 @@ public class LuaClosure extends LuaFunction {
}
}
@Override
public boolean isclosure() {
return true;
}
@Override
public LuaClosure optclosure(LuaClosure defval) {
return this;
}
@Override
public LuaClosure checkclosure() {
return this;
}
@Override
public String tojstring() {
return "function: " + p.toString();
}
@@ -151,11 +156,13 @@ public class LuaClosure extends LuaFunction {
return stack;
}
@Override
public final LuaValue call() {
LuaValue[] stack = getNewStack();
return execute(stack, NONE).arg1();
}
@Override
public final LuaValue call(LuaValue arg) {
LuaValue[] stack = getNewStack();
switch (p.numparams) {
@@ -167,6 +174,7 @@ public class LuaClosure extends LuaFunction {
}
}
@Override
public final LuaValue call(LuaValue arg1, LuaValue arg2) {
LuaValue[] stack = getNewStack();
switch (p.numparams) {
@@ -182,6 +190,7 @@ public class LuaClosure extends LuaFunction {
}
}
@Override
public final LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) {
LuaValue[] stack = getNewStack();
switch (p.numparams) {
@@ -202,10 +211,12 @@ public class LuaClosure extends LuaFunction {
}
}
@Override
public final Varargs invoke(Varargs varargs) {
return onInvoke(varargs).eval();
}
@Override
public final Varargs onInvoke(Varargs varargs) {
LuaValue[] stack = getNewStack();
for (int i = 0; i < p.numparams; i++)
@@ -237,7 +248,7 @@ public class LuaClosure extends LuaFunction {
// pull out instruction
i = code[pc];
a = ((i>>6) & 0xff);
a = i>>6 & 0xff;
// process the op code
switch (i & 0x3f) {
@@ -262,8 +273,8 @@ public class LuaClosure extends LuaFunction {
continue;
case Lua.OP_LOADBOOL:/* A B C R(A):= (Bool)B: if (C) pc++ */
stack[a] = (i>>>23 != 0)? LuaValue.TRUE: LuaValue.FALSE;
if ((i & (0x1ff<<14)) != 0)
stack[a] = i>>>23 != 0? LuaValue.TRUE: LuaValue.FALSE;
if ((i & 0x1ff<<14) != 0)
++pc; /* skip next instruction (if C) */
continue;
@@ -277,16 +288,16 @@ public class LuaClosure extends LuaFunction {
continue;
case Lua.OP_GETTABUP: /* A B C R(A) := UpValue[B][RK(C)] */
stack[a] = upValues[i>>>23].getValue().get((c = (i>>14) & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]);
stack[a] = upValues[i>>>23].getValue().get((c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]);
continue;
case Lua.OP_GETTABLE: /* A B C R(A):= R(B)[RK(C)] */
stack[a] = stack[i>>>23].get((c = (i>>14) & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]);
stack[a] = stack[i>>>23].get((c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]);
continue;
case Lua.OP_SETTABUP: /* A B C UpValue[A][RK(B)] := RK(C) */
upValues[a].getValue().set(((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b]),
(c = (i>>14) & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]);
upValues[a].getValue().set((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b],
(c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]);
continue;
case Lua.OP_SETUPVAL: /* A B UpValue[B]:= R(A) */
@@ -294,47 +305,47 @@ public class LuaClosure extends LuaFunction {
continue;
case Lua.OP_SETTABLE: /* A B C R(A)[RK(B)]:= RK(C) */
stack[a].set(((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b]),
(c = (i>>14) & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]);
stack[a].set((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b],
(c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]);
continue;
case Lua.OP_NEWTABLE: /* A B C R(A):= {} (size = B,C) */
stack[a] = new LuaTable(i>>>23, (i>>14) & 0x1ff);
stack[a] = new LuaTable(i>>>23, i>>14 & 0x1ff);
continue;
case Lua.OP_SELF: /* A B C R(A+1):= R(B): R(A):= R(B)[RK(C)] */
stack[a+1] = (o = stack[i>>>23]);
stack[a] = o.get((c = (i>>14) & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]);
stack[a+1] = o = stack[i>>>23];
stack[a] = o.get((c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]);
continue;
case Lua.OP_ADD: /* A B C R(A):= RK(B) + RK(C) */
stack[a] = ((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b])
.add((c = (i>>14) & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]);
.add((c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]);
continue;
case Lua.OP_SUB: /* A B C R(A):= RK(B) - RK(C) */
stack[a] = ((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b])
.sub((c = (i>>14) & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]);
.sub((c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]);
continue;
case Lua.OP_MUL: /* A B C R(A):= RK(B) * RK(C) */
stack[a] = ((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b])
.mul((c = (i>>14) & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]);
.mul((c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]);
continue;
case Lua.OP_DIV: /* A B C R(A):= RK(B) / RK(C) */
stack[a] = ((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b])
.div((c = (i>>14) & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]);
.div((c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]);
continue;
case Lua.OP_MOD: /* A B C R(A):= RK(B) % RK(C) */
stack[a] = ((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b])
.mod((c = (i>>14) & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]);
.mod((c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]);
continue;
case Lua.OP_POW: /* A B C R(A):= RK(B) ^ RK(C) */
stack[a] = ((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b])
.pow((c = (i>>14) & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]);
.pow((c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]);
continue;
case Lua.OP_UNM: /* A B R(A):= -R(B) */
@@ -351,7 +362,7 @@ public class LuaClosure extends LuaFunction {
case Lua.OP_CONCAT: /* A B C R(A):= R(B).. ... ..R(C) */
b = i>>>23;
c = (i>>14) & 0x1ff; {
c = i>>14 & 0x1ff; {
if (c > b+1) {
Buffer sb = stack[c].buffer();
while ( --c >= b )
@@ -376,30 +387,30 @@ public class LuaClosure extends LuaFunction {
case Lua.OP_EQ: /* A B C if ((RK(B) == RK(C)) ~= A) then pc++ */
if (((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b])
.eq_b((c = (i>>14) & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]) != (a != 0))
.eq_b((c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]) != (a != 0))
++pc;
continue;
case Lua.OP_LT: /* A B C if ((RK(B) < RK(C)) ~= A) then pc++ */
if (((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b])
.lt_b((c = (i>>14) & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]) != (a != 0))
.lt_b((c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]) != (a != 0))
++pc;
continue;
case Lua.OP_LE: /* A B C if ((RK(B) <= RK(C)) ~= A) then pc++ */
if (((b = i>>>23) > 0xff? k[b & 0x0ff]: stack[b])
.lteq_b((c = (i>>14) & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]) != (a != 0))
.lteq_b((c = i>>14 & 0x1ff) > 0xff? k[c & 0x0ff]: stack[c]) != (a != 0))
++pc;
continue;
case Lua.OP_TEST: /* A C if not (R(A) <=> C) then pc++ */
if (stack[a].toboolean() != ((i & (0x1ff<<14)) != 0))
if (stack[a].toboolean() != ((i & 0x1ff<<14) != 0))
++pc;
continue;
case Lua.OP_TESTSET: /* A B C if (R(B) <=> C) then R(A):= R(B) else pc++ */
/* note: doc appears to be reversed */
if ((o = stack[i>>>23]).toboolean() != ((i & (0x1ff<<14)) != 0))
if ((o = stack[i>>>23]).toboolean() != ((i & 0x1ff<<14) != 0))
++pc;
else
stack[a] = o; // TODO: should be sBx?
@@ -407,41 +418,41 @@ public class LuaClosure extends LuaFunction {
case Lua.OP_CALL: /* A B C R(A), ... ,R(A+C-2):= R(A)(R(A+1), ... ,R(A+B-1)) */
switch (i & (Lua.MASK_B | Lua.MASK_C)) {
case (1<<Lua.POS_B) | (0<<Lua.POS_C):
case 1<<Lua.POS_B | 0<<Lua.POS_C:
v = stack[a].invoke(NONE);
top = a+v.narg();
continue;
case (2<<Lua.POS_B) | (0<<Lua.POS_C):
case 2<<Lua.POS_B | 0<<Lua.POS_C:
v = stack[a].invoke(stack[a+1]);
top = a+v.narg();
continue;
case (1<<Lua.POS_B) | (1<<Lua.POS_C):
case 1<<Lua.POS_B | 1<<Lua.POS_C:
stack[a].call();
continue;
case (2<<Lua.POS_B) | (1<<Lua.POS_C):
case 2<<Lua.POS_B | 1<<Lua.POS_C:
stack[a].call(stack[a+1]);
continue;
case (3<<Lua.POS_B) | (1<<Lua.POS_C):
case 3<<Lua.POS_B | 1<<Lua.POS_C:
stack[a].call(stack[a+1], stack[a+2]);
continue;
case (4<<Lua.POS_B) | (1<<Lua.POS_C):
case 4<<Lua.POS_B | 1<<Lua.POS_C:
stack[a].call(stack[a+1], stack[a+2], stack[a+3]);
continue;
case (1<<Lua.POS_B) | (2<<Lua.POS_C):
case 1<<Lua.POS_B | 2<<Lua.POS_C:
stack[a] = stack[a].call();
continue;
case (2<<Lua.POS_B) | (2<<Lua.POS_C):
case 2<<Lua.POS_B | 2<<Lua.POS_C:
stack[a] = stack[a].call(stack[a+1]);
continue;
case (3<<Lua.POS_B) | (2<<Lua.POS_C):
case 3<<Lua.POS_B | 2<<Lua.POS_C:
stack[a] = stack[a].call(stack[a+1], stack[a+2]);
continue;
case (4<<Lua.POS_B) | (2<<Lua.POS_C):
case 4<<Lua.POS_B | 2<<Lua.POS_C:
stack[a] = stack[a].call(stack[a+1], stack[a+2], stack[a+3]);
continue;
default:
b = i>>>23;
c = (i>>14) & 0x1ff;
c = i>>14 & 0x1ff;
v = stack[a].invoke(b > 0? varargsOf(stack, a+1, b-1): // exact arg count
varargsOf(stack, a+1, top-v.narg()-(a+1), v)); // from prev top
if (c > 0) {
@@ -456,13 +467,13 @@ public class LuaClosure extends LuaFunction {
case Lua.OP_TAILCALL: /* A B C return R(A)(R(A+1), ... ,R(A+B-1)) */
switch (i & Lua.MASK_B) {
case (1<<Lua.POS_B):
case 1<<Lua.POS_B:
return new TailcallVarargs(stack[a], NONE);
case (2<<Lua.POS_B):
case 2<<Lua.POS_B:
return new TailcallVarargs(stack[a], stack[a+1]);
case (3<<Lua.POS_B):
case 3<<Lua.POS_B:
return new TailcallVarargs(stack[a], varargsOf(stack[a+1], stack[a+2]));
case (4<<Lua.POS_B):
case 4<<Lua.POS_B:
return new TailcallVarargs(stack[a], varargsOf(stack[a+1], stack[a+2], stack[a+3]));
default:
b = i>>>23;
@@ -511,7 +522,7 @@ public class LuaClosure extends LuaFunction {
case Lua.OP_TFORCALL: /* A C R(A+3), ... ,R(A+2+C) := R(A)(R(A+1), R(A+2)); */
v = stack[a].invoke(varargsOf(stack[a+1], stack[a+2]));
c = (i>>14) & 0x1ff;
c = i>>14 & 0x1ff;
while ( --c >= 0 )
stack[a+3+c] = v.arg(c+1);
v = NONE;
@@ -526,7 +537,7 @@ public class LuaClosure extends LuaFunction {
case Lua.OP_SETLIST: /* A B C R(A)[(C-1)*FPF+i]:= R(A+i), 1 <= i <= B */
{
if ((c = (i>>14) & 0x1ff) == 0)
if ((c = i>>14 & 0x1ff) == 0)
c = code[++pc];
int offset = (c-1)*Lua.LFIELDS_PER_FLUSH;
o = stack[a];
@@ -661,6 +672,7 @@ public class LuaClosure extends LuaFunction {
upValues[i].setValue(v);
}
@Override
public String name() {
return "<" + p.shortsource() + ":" + p.linedefined + ">";
}

View File

@@ -88,100 +88,143 @@ public class LuaDouble extends LuaNumber {
this.v = d;
}
@Override
public int hashCode() {
long l = Double.doubleToLongBits(v+1);
return ((int) (l>>32))+(int) l;
return (int) (l>>32)+(int) l;
}
@Override
public boolean islong() {
return v == (long) v;
}
@Override
public byte tobyte() { return (byte) (long) v; }
@Override
public char tochar() { return (char) (long) v; }
@Override
public double todouble() { return v; }
@Override
public float tofloat() { return (float) v; }
@Override
public int toint() { return (int) (long) v; }
@Override
public long tolong() { return (long) v; }
@Override
public short toshort() { return (short) (long) v; }
@Override
public double optdouble(double defval) { return v; }
@Override
public int optint(int defval) { return (int) (long) v; }
@Override
public LuaInteger optinteger(LuaInteger defval) { return LuaInteger.valueOf((int) (long) v); }
@Override
public long optlong(long defval) { return (long) v; }
@Override
public LuaInteger checkinteger() { return LuaInteger.valueOf((int) (long) v); }
// unary operators
@Override
public LuaValue neg() { return valueOf(-v); }
// object equality, used for key comparison
@Override
public boolean equals(Object o) { return o instanceof LuaDouble? ((LuaDouble) o).v == v: false; }
// equality w/ metatable processing
@Override
public LuaValue eq(LuaValue val) { return val.raweq(v)? TRUE: FALSE; }
@Override
public boolean eq_b(LuaValue val) { return val.raweq(v); }
// equality w/o metatable processing
@Override
public boolean raweq(LuaValue val) { return val.raweq(v); }
@Override
public boolean raweq(double val) { return v == val; }
@Override
public boolean raweq(int val) { return v == val; }
// basic binary arithmetic
@Override
public LuaValue add(LuaValue rhs) { return rhs.add(v); }
@Override
public LuaValue add(double lhs) { return LuaDouble.valueOf(lhs+v); }
@Override
public LuaValue sub(LuaValue rhs) { return rhs.subFrom(v); }
@Override
public LuaValue sub(double rhs) { return LuaDouble.valueOf(v-rhs); }
@Override
public LuaValue sub(int rhs) { return LuaDouble.valueOf(v-rhs); }
@Override
public LuaValue subFrom(double lhs) { return LuaDouble.valueOf(lhs-v); }
@Override
public LuaValue mul(LuaValue rhs) { return rhs.mul(v); }
@Override
public LuaValue mul(double lhs) { return LuaDouble.valueOf(lhs*v); }
@Override
public LuaValue mul(int lhs) { return LuaDouble.valueOf(lhs*v); }
@Override
public LuaValue pow(LuaValue rhs) { return rhs.powWith(v); }
@Override
public LuaValue pow(double rhs) { return MathLib.dpow(v, rhs); }
@Override
public LuaValue pow(int rhs) { return MathLib.dpow(v, rhs); }
@Override
public LuaValue powWith(double lhs) { return MathLib.dpow(lhs, v); }
@Override
public LuaValue powWith(int lhs) { return MathLib.dpow(lhs, v); }
@Override
public LuaValue div(LuaValue rhs) { return rhs.divInto(v); }
@Override
public LuaValue div(double rhs) { return LuaDouble.ddiv(v, rhs); }
@Override
public LuaValue div(int rhs) { return LuaDouble.ddiv(v, rhs); }
@Override
public LuaValue divInto(double lhs) { return LuaDouble.ddiv(lhs, v); }
@Override
public LuaValue mod(LuaValue rhs) { return rhs.modFrom(v); }
@Override
public LuaValue mod(double rhs) { return LuaDouble.dmod(v, rhs); }
@Override
public LuaValue mod(int rhs) { return LuaDouble.dmod(v, rhs); }
@Override
public LuaValue modFrom(double lhs) { return LuaDouble.dmod(lhs, v); }
/**
@@ -257,61 +300,87 @@ public class LuaDouble extends LuaNumber {
}
// relational operators
public LuaValue lt(LuaValue rhs) { return rhs instanceof LuaNumber? (rhs.gt_b(v)? TRUE: FALSE): super.lt(rhs); }
@Override
public LuaValue lt(LuaValue rhs) { return rhs instanceof LuaNumber? rhs.gt_b(v)? TRUE: FALSE: super.lt(rhs); }
@Override
public LuaValue lt(double rhs) { return v < rhs? TRUE: FALSE; }
@Override
public LuaValue lt(int rhs) { return v < rhs? TRUE: FALSE; }
@Override
public boolean lt_b(LuaValue rhs) { return rhs instanceof LuaNumber? rhs.gt_b(v): super.lt_b(rhs); }
@Override
public boolean lt_b(int rhs) { return v < rhs; }
@Override
public boolean lt_b(double rhs) { return v < rhs; }
@Override
public LuaValue lteq(LuaValue rhs) {
return rhs instanceof LuaNumber? (rhs.gteq_b(v)? TRUE: FALSE): super.lteq(rhs);
return rhs instanceof LuaNumber? rhs.gteq_b(v)? TRUE: FALSE: super.lteq(rhs);
}
@Override
public LuaValue lteq(double rhs) { return v <= rhs? TRUE: FALSE; }
@Override
public LuaValue lteq(int rhs) { return v <= rhs? TRUE: FALSE; }
@Override
public boolean lteq_b(LuaValue rhs) { return rhs instanceof LuaNumber? rhs.gteq_b(v): super.lteq_b(rhs); }
@Override
public boolean lteq_b(int rhs) { return v <= rhs; }
@Override
public boolean lteq_b(double rhs) { return v <= rhs; }
public LuaValue gt(LuaValue rhs) { return rhs instanceof LuaNumber? (rhs.lt_b(v)? TRUE: FALSE): super.gt(rhs); }
@Override
public LuaValue gt(LuaValue rhs) { return rhs instanceof LuaNumber? rhs.lt_b(v)? TRUE: FALSE: super.gt(rhs); }
@Override
public LuaValue gt(double rhs) { return v > rhs? TRUE: FALSE; }
@Override
public LuaValue gt(int rhs) { return v > rhs? TRUE: FALSE; }
@Override
public boolean gt_b(LuaValue rhs) { return rhs instanceof LuaNumber? rhs.lt_b(v): super.gt_b(rhs); }
@Override
public boolean gt_b(int rhs) { return v > rhs; }
@Override
public boolean gt_b(double rhs) { return v > rhs; }
@Override
public LuaValue gteq(LuaValue rhs) {
return rhs instanceof LuaNumber? (rhs.lteq_b(v)? TRUE: FALSE): super.gteq(rhs);
return rhs instanceof LuaNumber? rhs.lteq_b(v)? TRUE: FALSE: super.gteq(rhs);
}
@Override
public LuaValue gteq(double rhs) { return v >= rhs? TRUE: FALSE; }
@Override
public LuaValue gteq(int rhs) { return v >= rhs? TRUE: FALSE; }
@Override
public boolean gteq_b(LuaValue rhs) { return rhs instanceof LuaNumber? rhs.lteq_b(v): super.gteq_b(rhs); }
@Override
public boolean gteq_b(int rhs) { return v >= rhs; }
@Override
public boolean gteq_b(double rhs) { return v >= rhs; }
// string comparison
@Override
public int strcmp(LuaString rhs) { typerror("attempt to compare number with string"); return 0; }
@Override
public String tojstring() {
/*
if ( v == 0.0 ) { // never occurs in J2me
@@ -325,58 +394,73 @@ public class LuaDouble extends LuaNumber {
if (Double.isNaN(v))
return JSTR_NAN;
if (Double.isInfinite(v))
return (v < 0? JSTR_NEGINF: JSTR_POSINF);
return v < 0? JSTR_NEGINF: JSTR_POSINF;
return Float.toString((float) v);
}
@Override
public LuaString strvalue() {
return LuaString.valueOf(tojstring());
}
@Override
public LuaString optstring(LuaString defval) {
return LuaString.valueOf(tojstring());
}
@Override
public LuaValue tostring() {
return LuaString.valueOf(tojstring());
}
@Override
public String optjstring(String defval) {
return tojstring();
}
@Override
public LuaNumber optnumber(LuaNumber defval) {
return this;
}
@Override
public boolean isnumber() {
return true;
}
@Override
public boolean isstring() {
return true;
}
@Override
public LuaValue tonumber() {
return this;
}
@Override
public int checkint() { return (int) (long) v; }
@Override
public long checklong() { return (long) v; }
@Override
public LuaNumber checknumber() { return this; }
@Override
public double checkdouble() { return v; }
@Override
public String checkjstring() {
return tojstring();
}
@Override
public LuaString checkstring() {
return LuaString.valueOf(tojstring());
}
@Override
public boolean isvalidkey() {
return !Double.isNaN(v);
}

View File

@@ -54,6 +54,7 @@ public class LuaError extends RuntimeException {
* Get the string message if it was supplied, or a string representation of
* the message object if that was supplied.
*/
@Override
public String getMessage() {
if (traceback != null)
return traceback;
@@ -129,6 +130,7 @@ public class LuaError extends RuntimeException {
/**
* Get the cause, if any.
*/
@Override
public Throwable getCause() { return cause; }
}

View File

@@ -38,34 +38,42 @@ abstract public class LuaFunction extends LuaValue {
/** Shared static metatable for all functions and closures. */
public static LuaValue s_metatable;
@Override
public int type() {
return TFUNCTION;
}
@Override
public String typename() {
return "function";
}
@Override
public boolean isfunction() {
return true;
}
@Override
public LuaFunction checkfunction() {
return this;
}
@Override
public LuaFunction optfunction(LuaFunction defval) {
return this;
}
@Override
public LuaValue getmetatable() {
return s_metatable;
}
@Override
public String tojstring() {
return "function: " + classnamestub();
}
@Override
public LuaString strvalue() {
return valueOf(tojstring());
}

View File

@@ -50,7 +50,7 @@ public class LuaInteger extends LuaNumber {
public static LuaInteger valueOf(int i) {
return i <= 255 && i >= -256? intValues[i+256]: new LuaInteger(i);
};
}
// TODO consider moving this to LuaValue
/**
@@ -63,7 +63,7 @@ public class LuaInteger extends LuaNumber {
*/
public static LuaNumber valueOf(long l) {
int i = (int) l;
return l == i? (i <= 255 && i >= -256? intValues[i+256]: (LuaNumber) new LuaInteger(i))
return l == i? i <= 255 && i >= -256? intValues[i+256]: (LuaNumber) new LuaInteger(i)
: (LuaNumber) LuaDouble.valueOf(l);
}
@@ -79,62 +79,84 @@ public class LuaInteger extends LuaNumber {
this.v = i;
}
@Override
public boolean isint() { return true; }
@Override
public boolean isinttype() { return true; }
@Override
public boolean islong() { return true; }
@Override
public byte tobyte() { return (byte) v; }
@Override
public char tochar() { return (char) v; }
@Override
public double todouble() { return v; }
@Override
public float tofloat() { return v; }
@Override
public int toint() { return v; }
@Override
public long tolong() { return v; }
@Override
public short toshort() { return (short) v; }
@Override
public double optdouble(double defval) { return v; }
@Override
public int optint(int defval) { return v; }
@Override
public LuaInteger optinteger(LuaInteger defval) { return this; }
@Override
public long optlong(long defval) { return v; }
@Override
public String tojstring() {
return Integer.toString(v);
}
@Override
public LuaString strvalue() {
return LuaString.valueOf(Integer.toString(v));
}
@Override
public LuaString optstring(LuaString defval) {
return LuaString.valueOf(Integer.toString(v));
}
@Override
public LuaValue tostring() {
return LuaString.valueOf(Integer.toString(v));
}
@Override
public String optjstring(String defval) {
return Integer.toString(v);
}
@Override
public LuaInteger checkinteger() {
return this;
}
@Override
public boolean isstring() {
return true;
}
@Override
public int hashCode() {
return v;
}
@@ -144,144 +166,205 @@ public class LuaInteger extends LuaNumber {
}
// unary operators
@Override
public LuaValue neg() { return valueOf(-(long) v); }
// object equality, used for key comparison
@Override
public boolean equals(Object o) { return o instanceof LuaInteger? ((LuaInteger) o).v == v: false; }
// equality w/ metatable processing
@Override
public LuaValue eq(LuaValue val) { return val.raweq(v)? TRUE: FALSE; }
@Override
public boolean eq_b(LuaValue val) { return val.raweq(v); }
// equality w/o metatable processing
@Override
public boolean raweq(LuaValue val) { return val.raweq(v); }
@Override
public boolean raweq(double val) { return v == val; }
@Override
public boolean raweq(int val) { return v == val; }
// arithmetic operators
@Override
public LuaValue add(LuaValue rhs) { return rhs.add(v); }
@Override
public LuaValue add(double lhs) { return LuaDouble.valueOf(lhs+v); }
@Override
public LuaValue add(int lhs) { return LuaInteger.valueOf(lhs+(long) v); }
@Override
public LuaValue sub(LuaValue rhs) { return rhs.subFrom(v); }
@Override
public LuaValue sub(double rhs) { return LuaDouble.valueOf(v-rhs); }
public LuaValue sub(int rhs) { return LuaDouble.valueOf(v-rhs); }
@Override
public LuaValue sub(int rhs) { return LuaValue.valueOf(v-rhs); }
@Override
public LuaValue subFrom(double lhs) { return LuaDouble.valueOf(lhs-v); }
@Override
public LuaValue subFrom(int lhs) { return LuaInteger.valueOf(lhs-(long) v); }
@Override
public LuaValue mul(LuaValue rhs) { return rhs.mul(v); }
@Override
public LuaValue mul(double lhs) { return LuaDouble.valueOf(lhs*v); }
@Override
public LuaValue mul(int lhs) { return LuaInteger.valueOf(lhs*(long) v); }
@Override
public LuaValue pow(LuaValue rhs) { return rhs.powWith(v); }
@Override
public LuaValue pow(double rhs) { return MathLib.dpow(v, rhs); }
@Override
public LuaValue pow(int rhs) { return MathLib.dpow(v, rhs); }
@Override
public LuaValue powWith(double lhs) { return MathLib.dpow(lhs, v); }
@Override
public LuaValue powWith(int lhs) { return MathLib.dpow(lhs, v); }
@Override
public LuaValue div(LuaValue rhs) { return rhs.divInto(v); }
@Override
public LuaValue div(double rhs) { return LuaDouble.ddiv(v, rhs); }
@Override
public LuaValue div(int rhs) { return LuaDouble.ddiv(v, rhs); }
@Override
public LuaValue divInto(double lhs) { return LuaDouble.ddiv(lhs, v); }
@Override
public LuaValue mod(LuaValue rhs) { return rhs.modFrom(v); }
@Override
public LuaValue mod(double rhs) { return LuaDouble.dmod(v, rhs); }
@Override
public LuaValue mod(int rhs) { return LuaDouble.dmod(v, rhs); }
@Override
public LuaValue modFrom(double lhs) { return LuaDouble.dmod(lhs, v); }
// relational operators
public LuaValue lt(LuaValue rhs) { return rhs instanceof LuaNumber? (rhs.gt_b(v)? TRUE: FALSE): super.lt(rhs); }
@Override
public LuaValue lt(LuaValue rhs) { return rhs instanceof LuaNumber? rhs.gt_b(v)? TRUE: FALSE: super.lt(rhs); }
@Override
public LuaValue lt(double rhs) { return v < rhs? TRUE: FALSE; }
@Override
public LuaValue lt(int rhs) { return v < rhs? TRUE: FALSE; }
@Override
public boolean lt_b(LuaValue rhs) { return rhs instanceof LuaNumber? rhs.gt_b(v): super.lt_b(rhs); }
@Override
public boolean lt_b(int rhs) { return v < rhs; }
@Override
public boolean lt_b(double rhs) { return v < rhs; }
@Override
public LuaValue lteq(LuaValue rhs) {
return rhs instanceof LuaNumber? (rhs.gteq_b(v)? TRUE: FALSE): super.lteq(rhs);
return rhs instanceof LuaNumber? rhs.gteq_b(v)? TRUE: FALSE: super.lteq(rhs);
}
@Override
public LuaValue lteq(double rhs) { return v <= rhs? TRUE: FALSE; }
@Override
public LuaValue lteq(int rhs) { return v <= rhs? TRUE: FALSE; }
@Override
public boolean lteq_b(LuaValue rhs) { return rhs instanceof LuaNumber? rhs.gteq_b(v): super.lteq_b(rhs); }
@Override
public boolean lteq_b(int rhs) { return v <= rhs; }
@Override
public boolean lteq_b(double rhs) { return v <= rhs; }
public LuaValue gt(LuaValue rhs) { return rhs instanceof LuaNumber? (rhs.lt_b(v)? TRUE: FALSE): super.gt(rhs); }
@Override
public LuaValue gt(LuaValue rhs) { return rhs instanceof LuaNumber? rhs.lt_b(v)? TRUE: FALSE: super.gt(rhs); }
@Override
public LuaValue gt(double rhs) { return v > rhs? TRUE: FALSE; }
@Override
public LuaValue gt(int rhs) { return v > rhs? TRUE: FALSE; }
@Override
public boolean gt_b(LuaValue rhs) { return rhs instanceof LuaNumber? rhs.lt_b(v): super.gt_b(rhs); }
@Override
public boolean gt_b(int rhs) { return v > rhs; }
@Override
public boolean gt_b(double rhs) { return v > rhs; }
@Override
public LuaValue gteq(LuaValue rhs) {
return rhs instanceof LuaNumber? (rhs.lteq_b(v)? TRUE: FALSE): super.gteq(rhs);
return rhs instanceof LuaNumber? rhs.lteq_b(v)? TRUE: FALSE: super.gteq(rhs);
}
@Override
public LuaValue gteq(double rhs) { return v >= rhs? TRUE: FALSE; }
@Override
public LuaValue gteq(int rhs) { return v >= rhs? TRUE: FALSE; }
@Override
public boolean gteq_b(LuaValue rhs) { return rhs instanceof LuaNumber? rhs.lteq_b(v): super.gteq_b(rhs); }
@Override
public boolean gteq_b(int rhs) { return v >= rhs; }
@Override
public boolean gteq_b(double rhs) { return v >= rhs; }
// string comparison
@Override
public int strcmp(LuaString rhs) { typerror("attempt to compare number with string"); return 0; }
@Override
public int checkint() {
return v;
}
@Override
public long checklong() {
return v;
}
@Override
public double checkdouble() {
return v;
}
@Override
public String checkjstring() {
return String.valueOf(v);
}
@Override
public LuaString checkstring() {
return valueOf(String.valueOf(v));
}

View File

@@ -45,78 +45,104 @@ public class LuaNil extends LuaValue {
LuaNil() {}
@Override
public int type() {
return LuaValue.TNIL;
}
@Override
public String toString() {
return "nil";
}
@Override
public String typename() {
return "nil";
}
@Override
public String tojstring() {
return "nil";
}
@Override
public LuaValue not() {
return LuaValue.TRUE;
}
@Override
public boolean toboolean() {
return false;
}
@Override
public boolean isnil() {
return true;
}
@Override
public LuaValue getmetatable() {
return s_metatable;
}
@Override
public boolean equals(Object o) {
return o instanceof LuaNil;
}
@Override
public LuaValue checknotnil() {
return argerror("value");
}
@Override
public boolean isvalidkey() {
return false;
}
// optional argument conversions - nil alwas falls badk to default value
@Override
public boolean optboolean(boolean defval) { return defval; }
@Override
public LuaClosure optclosure(LuaClosure defval) { return defval; }
@Override
public double optdouble(double defval) { return defval; }
@Override
public LuaFunction optfunction(LuaFunction defval) { return defval; }
@Override
public int optint(int defval) { return defval; }
@Override
public LuaInteger optinteger(LuaInteger defval) { return defval; }
@Override
public long optlong(long defval) { return defval; }
@Override
public LuaNumber optnumber(LuaNumber defval) { return defval; }
@Override
public LuaTable opttable(LuaTable defval) { return defval; }
@Override
public LuaThread optthread(LuaThread defval) { return defval; }
@Override
public String optjstring(String defval) { return defval; }
@Override
public LuaString optstring(LuaString defval) { return defval; }
@Override
public Object optuserdata(Object defval) { return defval; }
@Override
public Object optuserdata(Class c, Object defval) { return defval; }
@Override
public LuaValue optvalue(LuaValue defval) { return defval; }
}

View File

@@ -37,48 +37,61 @@ abstract public class LuaNumber extends LuaValue {
/** Shared static metatable for all number values represented in lua. */
public static LuaValue s_metatable;
@Override
public int type() {
return TNUMBER;
}
@Override
public String typename() {
return "number";
}
@Override
public LuaNumber checknumber() {
return this;
}
@Override
public LuaNumber checknumber(String errmsg) {
return this;
}
@Override
public LuaNumber optnumber(LuaNumber defval) {
return this;
}
@Override
public LuaValue tonumber() {
return this;
}
@Override
public boolean isnumber() {
return true;
}
@Override
public boolean isstring() {
return true;
}
@Override
public LuaValue getmetatable() {
return s_metatable;
}
@Override
public LuaValue concat(LuaValue rhs) { return rhs.concatTo(this); }
@Override
public Buffer concat(Buffer rhs) { return rhs.concatTo(this); }
@Override
public LuaValue concatTo(LuaNumber lhs) { return strvalue().concatTo(lhs.strvalue()); }
@Override
public LuaValue concatTo(LuaString lhs) { return strvalue().concatTo(lhs); }
}

View File

@@ -147,7 +147,7 @@ public class LuaString extends LuaValue {
if (len > RECENT_STRINGS_MAX_LENGTH)
return valueFromCopy(bytes, off, len);
final int hash = hashCode(bytes, off, len);
final int bucket = hash & (RECENT_STRINGS_CACHE_SIZE-1);
final int bucket = hash & RECENT_STRINGS_CACHE_SIZE-1;
final LuaString t = RecentShortStrings.recent_short_strings[bucket];
if (t != null && t.m_hashcode == hash && t.byteseq(bytes, off, len))
return t;
@@ -180,7 +180,7 @@ public class LuaString extends LuaValue {
if (bytes.length > RECENT_STRINGS_MAX_LENGTH)
return new LuaString(bytes, off, len);
final int hash = hashCode(bytes, off, len);
final int bucket = hash & (RECENT_STRINGS_CACHE_SIZE-1);
final int bucket = hash & RECENT_STRINGS_CACHE_SIZE-1;
final LuaString t = RecentShortStrings.recent_short_strings[bucket];
if (t != null && t.m_hashcode == hash && t.byteseq(bytes, off, len))
return t;
@@ -280,142 +280,191 @@ public class LuaString extends LuaValue {
this.m_hashcode = hashCode(bytes, offset, length);
}
@Override
public boolean isstring() {
return true;
}
@Override
public LuaValue getmetatable() {
return s_metatable;
}
@Override
public int type() {
return LuaValue.TSTRING;
}
@Override
public String typename() {
return "string";
}
@Override
public String tojstring() {
return decodeAsUtf8(m_bytes, m_offset, m_length);
}
// unary operators
@Override
public LuaValue neg() { double d = scannumber(); return Double.isNaN(d)? super.neg(): valueOf(-d); }
// basic binary arithmetic
@Override
public LuaValue add(LuaValue rhs) {
double d = scannumber();
return Double.isNaN(d)? arithmt(ADD, rhs): rhs.add(d);
}
@Override
public LuaValue add(double rhs) { return valueOf(checkarith()+rhs); }
@Override
public LuaValue add(int rhs) { return valueOf(checkarith()+rhs); }
@Override
public LuaValue sub(LuaValue rhs) {
double d = scannumber();
return Double.isNaN(d)? arithmt(SUB, rhs): rhs.subFrom(d);
}
@Override
public LuaValue sub(double rhs) { return valueOf(checkarith()-rhs); }
@Override
public LuaValue sub(int rhs) { return valueOf(checkarith()-rhs); }
@Override
public LuaValue subFrom(double lhs) { return valueOf(lhs-checkarith()); }
@Override
public LuaValue mul(LuaValue rhs) {
double d = scannumber();
return Double.isNaN(d)? arithmt(MUL, rhs): rhs.mul(d);
}
@Override
public LuaValue mul(double rhs) { return valueOf(checkarith()*rhs); }
@Override
public LuaValue mul(int rhs) { return valueOf(checkarith()*rhs); }
@Override
public LuaValue pow(LuaValue rhs) {
double d = scannumber();
return Double.isNaN(d)? arithmt(POW, rhs): rhs.powWith(d);
}
@Override
public LuaValue pow(double rhs) { return MathLib.dpow(checkarith(), rhs); }
@Override
public LuaValue pow(int rhs) { return MathLib.dpow(checkarith(), rhs); }
@Override
public LuaValue powWith(double lhs) { return MathLib.dpow(lhs, checkarith()); }
@Override
public LuaValue powWith(int lhs) { return MathLib.dpow(lhs, checkarith()); }
@Override
public LuaValue div(LuaValue rhs) {
double d = scannumber();
return Double.isNaN(d)? arithmt(DIV, rhs): rhs.divInto(d);
}
@Override
public LuaValue div(double rhs) { return LuaDouble.ddiv(checkarith(), rhs); }
@Override
public LuaValue div(int rhs) { return LuaDouble.ddiv(checkarith(), rhs); }
@Override
public LuaValue divInto(double lhs) { return LuaDouble.ddiv(lhs, checkarith()); }
@Override
public LuaValue mod(LuaValue rhs) {
double d = scannumber();
return Double.isNaN(d)? arithmt(MOD, rhs): rhs.modFrom(d);
}
@Override
public LuaValue mod(double rhs) { return LuaDouble.dmod(checkarith(), rhs); }
@Override
public LuaValue mod(int rhs) { return LuaDouble.dmod(checkarith(), rhs); }
@Override
public LuaValue modFrom(double lhs) { return LuaDouble.dmod(lhs, checkarith()); }
// relational operators, these only work with other strings
@Override
public LuaValue lt(LuaValue rhs) {
return rhs.isstring()? (rhs.strcmp(this) > 0? LuaValue.TRUE: FALSE): super.lt(rhs);
return rhs.isstring()? rhs.strcmp(this) > 0? LuaValue.TRUE: FALSE: super.lt(rhs);
}
@Override
public boolean lt_b(LuaValue rhs) { return rhs.isstring()? rhs.strcmp(this) > 0: super.lt_b(rhs); }
@Override
public boolean lt_b(int rhs) { typerror("attempt to compare string with number"); return false; }
@Override
public boolean lt_b(double rhs) { typerror("attempt to compare string with number"); return false; }
@Override
public LuaValue lteq(LuaValue rhs) {
return rhs.isstring()? (rhs.strcmp(this) >= 0? LuaValue.TRUE: FALSE): super.lteq(rhs);
return rhs.isstring()? rhs.strcmp(this) >= 0? LuaValue.TRUE: FALSE: super.lteq(rhs);
}
@Override
public boolean lteq_b(LuaValue rhs) { return rhs.isstring()? rhs.strcmp(this) >= 0: super.lteq_b(rhs); }
@Override
public boolean lteq_b(int rhs) { typerror("attempt to compare string with number"); return false; }
@Override
public boolean lteq_b(double rhs) { typerror("attempt to compare string with number"); return false; }
@Override
public LuaValue gt(LuaValue rhs) {
return rhs.isstring()? (rhs.strcmp(this) < 0? LuaValue.TRUE: FALSE): super.gt(rhs);
return rhs.isstring()? rhs.strcmp(this) < 0? LuaValue.TRUE: FALSE: super.gt(rhs);
}
@Override
public boolean gt_b(LuaValue rhs) { return rhs.isstring()? rhs.strcmp(this) < 0: super.gt_b(rhs); }
@Override
public boolean gt_b(int rhs) { typerror("attempt to compare string with number"); return false; }
@Override
public boolean gt_b(double rhs) { typerror("attempt to compare string with number"); return false; }
@Override
public LuaValue gteq(LuaValue rhs) {
return rhs.isstring()? (rhs.strcmp(this) <= 0? LuaValue.TRUE: FALSE): super.gteq(rhs);
return rhs.isstring()? rhs.strcmp(this) <= 0? LuaValue.TRUE: FALSE: super.gteq(rhs);
}
@Override
public boolean gteq_b(LuaValue rhs) { return rhs.isstring()? rhs.strcmp(this) <= 0: super.gteq_b(rhs); }
@Override
public boolean gteq_b(int rhs) { typerror("attempt to compare string with number"); return false; }
@Override
public boolean gteq_b(double rhs) { typerror("attempt to compare string with number"); return false; }
// concatenation
@Override
public LuaValue concat(LuaValue rhs) { return rhs.concatTo(this); }
@Override
public Buffer concat(Buffer rhs) { return rhs.concatTo(this); }
@Override
public LuaValue concatTo(LuaNumber lhs) { return concatTo(lhs.strvalue()); }
@Override
public LuaValue concatTo(LuaString lhs) {
byte[] b = new byte[lhs.m_length+this.m_length];
System.arraycopy(lhs.m_bytes, lhs.m_offset, b, 0, lhs.m_length);
@@ -424,12 +473,14 @@ public class LuaString extends LuaValue {
}
// string comparison
@Override
public int strcmp(LuaValue lhs) { return -lhs.strcmp(this); }
@Override
public int strcmp(LuaString rhs) {
for (int i = 0, j = 0; i < m_length && j < rhs.m_length; ++i, ++j) {
if (m_bytes[m_offset+i] != rhs.m_bytes[rhs.m_offset+j]) {
return ((int) m_bytes[m_offset+i])-((int) rhs.m_bytes[rhs.m_offset+j]);
return m_bytes[m_offset+i]-rhs.m_bytes[rhs.m_offset+j];
}
}
return m_length-rhs.m_length;
@@ -443,18 +494,22 @@ public class LuaString extends LuaValue {
return d;
}
@Override
public int checkint() {
return (int) (long) checkdouble();
}
@Override
public LuaInteger checkinteger() {
return valueOf(checkint());
}
@Override
public long checklong() {
return (long) checkdouble();
}
@Override
public double checkdouble() {
double d = scannumber();
if (Double.isNaN(d))
@@ -462,10 +517,12 @@ public class LuaString extends LuaValue {
return d;
}
@Override
public LuaNumber checknumber() {
return valueOf(checkdouble());
}
@Override
public LuaNumber checknumber(String msg) {
double d = scannumber();
if (Double.isNaN(d))
@@ -473,11 +530,13 @@ public class LuaString extends LuaValue {
return valueOf(d);
}
@Override
public boolean isnumber() {
double d = scannumber();
return !Double.isNaN(d);
}
@Override
public boolean isint() {
double d = scannumber();
if (Double.isNaN(d))
@@ -486,6 +545,7 @@ public class LuaString extends LuaValue {
return i == d;
}
@Override
public boolean islong() {
double d = scannumber();
if (Double.isNaN(d))
@@ -494,52 +554,68 @@ public class LuaString extends LuaValue {
return l == d;
}
@Override
public byte tobyte() { return (byte) toint(); }
@Override
public char tochar() { return (char) toint(); }
@Override
public double todouble() { double d = scannumber(); return Double.isNaN(d)? 0: d; }
@Override
public float tofloat() { return (float) todouble(); }
@Override
public int toint() { return (int) tolong(); }
@Override
public long tolong() { return (long) todouble(); }
@Override
public short toshort() { return (short) toint(); }
@Override
public double optdouble(double defval) {
return checkdouble();
}
@Override
public int optint(int defval) {
return checkint();
}
@Override
public LuaInteger optinteger(LuaInteger defval) {
return checkinteger();
}
@Override
public long optlong(long defval) {
return checklong();
}
@Override
public LuaNumber optnumber(LuaNumber defval) {
return checknumber();
}
@Override
public LuaString optstring(LuaString defval) {
return this;
}
@Override
public LuaValue tostring() {
return this;
}
@Override
public String optjstring(String defval) {
return tojstring();
}
@Override
public LuaString strvalue() {
return this;
}
@@ -560,6 +636,7 @@ public class LuaString extends LuaValue {
return len >= m_length/2? valueUsing(m_bytes, off, len): valueOf(m_bytes, off, len);
}
@Override
public int hashCode() {
return m_hashcode;
}
@@ -579,11 +656,12 @@ public class LuaString extends LuaValue {
int h = length; /* seed */
int step = (length>>5)+1; /* if string is too long, don't hash all its chars */
for (int l1 = length; l1 >= step; l1 -= step) /* compute hash */
h = h ^ ((h<<5)+(h>>2)+(((int) bytes[offset+l1-1]) & 0x0FF));
h = h ^ (h<<5)+(h>>2)+(bytes[offset+l1-1] & 0x0FF);
return h;
}
// object comparison, used in key comparison
@Override
public boolean equals(Object o) {
if (o instanceof LuaString) {
return raweq((LuaString) o);
@@ -592,15 +670,19 @@ public class LuaString extends LuaValue {
}
// equality w/ metatable processing
@Override
public LuaValue eq(LuaValue val) { return val.raweq(this)? TRUE: FALSE; }
@Override
public boolean eq_b(LuaValue val) { return val.raweq(this); }
// equality w/o metatable processing
@Override
public boolean raweq(LuaValue val) {
return val.raweq(this);
}
@Override
public boolean raweq(LuaString s) {
if (this == s)
return true;
@@ -625,7 +707,7 @@ public class LuaString extends LuaValue {
* bytes.
*/
private boolean byteseq(byte[] bytes, int off, int len) {
return (m_length == len && equals(m_bytes, m_offset, bytes, off, len));
return m_length == len && equals(m_bytes, m_offset, bytes, off, len);
}
public static boolean equals(byte[] a, int i, byte[] b, int j, int n) {
@@ -641,14 +723,17 @@ public class LuaString extends LuaValue {
writer.write(m_bytes, m_offset+i, len);
}
@Override
public LuaValue len() {
return LuaInteger.valueOf(m_length);
}
@Override
public int length() {
return m_length;
}
@Override
public int rawlen() {
return m_length;
}
@@ -663,10 +748,12 @@ public class LuaString extends LuaValue {
return luaByte(index);
}
@Override
public String checkjstring() {
return tojstring();
}
@Override
public LuaString checkstring() {
return this;
}
@@ -786,9 +873,9 @@ public class LuaString extends LuaValue {
}
char[] chars = new char[n];
for (i = offset, j = offset+length, n = 0; i < j;) {
chars[n++] = (char) (((b = bytes[i++]) >= 0 || i >= j)? b
: (b < -32 || i+1 >= j)? (((b & 0x3f)<<6) | (bytes[i++] & 0x3f))
: (((b & 0xf)<<12) | ((bytes[i++] & 0x3f)<<6) | (bytes[i++] & 0x3f)));
chars[n++] = (char) ((b = bytes[i++]) >= 0 || i >= j? b
: b < -32 || i+1 >= j? (b & 0x3f)<<6 | bytes[i++] & 0x3f
: (b & 0xf)<<12 | (bytes[i++] & 0x3f)<<6 | bytes[i++] & 0x3f);
}
return new String(chars);
}
@@ -807,7 +894,7 @@ public class LuaString extends LuaValue {
char c;
for (i = b = chars.length; --i >= 0;)
if ((c = chars[i]) >= 0x80)
b += (c >= 0x800)? 2: 1;
b += c >= 0x800? 2: 1;
return b;
}
@@ -834,12 +921,12 @@ public class LuaString extends LuaValue {
if ((c = chars[i]) < 0x80) {
bytes[j++] = (byte) c;
} else if (c < 0x800) {
bytes[j++] = (byte) (0xC0 | ((c>>6) & 0x1f));
bytes[j++] = (byte) (0x80 | (c & 0x3f));
bytes[j++] = (byte) (0xC0 | c>>6 & 0x1f);
bytes[j++] = (byte) (0x80 | c & 0x3f);
} else {
bytes[j++] = (byte) (0xE0 | ((c>>12) & 0x0f));
bytes[j++] = (byte) (0x80 | ((c>>6) & 0x3f));
bytes[j++] = (byte) (0x80 | (c & 0x3f));
bytes[j++] = (byte) (0xE0 | c>>12 & 0x0f);
bytes[j++] = (byte) (0x80 | c>>6 & 0x3f);
bytes[j++] = (byte) (0x80 | c & 0x3f);
}
}
return j-off;
@@ -856,11 +943,9 @@ public class LuaString extends LuaValue {
public boolean isValidUtf8() {
for (int i = m_offset, j = m_offset+m_length; i < j;) {
int c = m_bytes[i++];
if (c >= 0)
if (c >= 0 || (c & 0xE0) == 0xC0 && i < j && (m_bytes[i++] & 0xC0) == 0x80)
continue;
if (((c & 0xE0) == 0xC0) && i < j && (m_bytes[i++] & 0xC0) == 0x80)
continue;
if (((c & 0xF0) == 0xE0) && i+1 < j && (m_bytes[i++] & 0xC0) == 0x80 && (m_bytes[i++] & 0xC0) == 0x80)
if ((c & 0xF0) == 0xE0 && i+1 < j && (m_bytes[i++] & 0xC0) == 0x80 && (m_bytes[i++] & 0xC0) == 0x80)
continue;
return false;
}
@@ -877,6 +962,7 @@ public class LuaString extends LuaValue {
* string.
* @see LuaValue#tonumber()
*/
@Override
public LuaValue tonumber() {
double d = scannumber();
return Double.isNaN(d)? NIL: valueOf(d);
@@ -945,10 +1031,10 @@ public class LuaString extends LuaValue {
*/
private double scanlong(int base, int start, int end) {
long x = 0;
boolean neg = (m_bytes[start] == '-');
for (int i = (neg? start+1: start); i < end; i++) {
int digit = m_bytes[i]-(base <= 10 || (m_bytes[i] >= '0' && m_bytes[i] <= '9')? '0'
: m_bytes[i] >= 'A' && m_bytes[i] <= 'Z'? ('A'-10): ('a'-10));
boolean neg = m_bytes[start] == '-';
for (int i = neg? start+1: start; i < end; i++) {
int digit = m_bytes[i]-(base <= 10 || m_bytes[i] >= '0' && m_bytes[i] <= '9'? '0'
: m_bytes[i] >= 'A' && m_bytes[i] <= 'Z'? 'A'-10: 'a'-10);
if (digit < 0 || digit >= base)
return Double.NaN;
x = x*base+digit;

View File

@@ -117,9 +117,9 @@ public class LuaTable extends LuaValue implements Metatable {
* @param lastarg Additional unnamed values beyond {@code unnamed.length}
*/
public LuaTable(LuaValue[] named, LuaValue[] unnamed, Varargs lastarg) {
int nn = (named != null? named.length: 0);
int nu = (unnamed != null? unnamed.length: 0);
int nl = (lastarg != null? lastarg.narg(): 0);
int nn = named != null? named.length: 0;
int nu = unnamed != null? unnamed.length: 0;
int nl = lastarg != null? lastarg.narg(): 0;
presize(nu+nl, nn>>1);
for (int i = 0; i < nu; i++)
rawset(i+1, unnamed[i]);
@@ -156,26 +156,32 @@ public class LuaTable extends LuaValue implements Metatable {
set(i, varargs.arg(i+nskip));
}
@Override
public int type() {
return LuaValue.TTABLE;
}
@Override
public String typename() {
return "table";
}
@Override
public boolean istable() {
return true;
}
@Override
public LuaTable checktable() {
return this;
}
@Override
public LuaTable opttable(LuaTable defval) {
return this;
}
@Override
public void presize(int narray) {
if (narray > array.length)
array = resize(array, 1<<log2(narray));
@@ -185,8 +191,8 @@ public class LuaTable extends LuaValue implements Metatable {
if (nhash > 0 && nhash < MIN_HASH_CAPACITY)
nhash = MIN_HASH_CAPACITY;
// Size of both parts must be a power of two.
array = (narray > 0? new LuaValue[1<<log2(narray)]: NOVALS);
hash = (nhash > 0? new Slot[1<<log2(nhash)]: NOBUCKETS);
array = narray > 0? new LuaValue[1<<log2(narray)]: NOVALS;
hash = nhash > 0? new Slot[1<<log2(nhash)]: NOBUCKETS;
hashEntries = 0;
}
@@ -213,32 +219,37 @@ public class LuaTable extends LuaValue implements Metatable {
*/
protected int getHashLength() { return hash.length; }
@Override
public LuaValue getmetatable() {
return (m_metatable != null)? m_metatable.toLuaValue(): null;
return m_metatable != null? m_metatable.toLuaValue(): null;
}
@Override
public LuaValue setmetatable(LuaValue metatable) {
boolean hadWeakKeys = m_metatable != null && m_metatable.useWeakKeys();
boolean hadWeakValues = m_metatable != null && m_metatable.useWeakValues();
m_metatable = metatableOf(metatable);
if ((hadWeakKeys != (m_metatable != null && m_metatable.useWeakKeys()))
|| (hadWeakValues != (m_metatable != null && m_metatable.useWeakValues()))) {
if (hadWeakKeys != (m_metatable != null && m_metatable.useWeakKeys())
|| hadWeakValues != (m_metatable != null && m_metatable.useWeakValues())) {
// force a rehash
rehash(0);
}
return this;
}
@Override
public LuaValue get(int key) {
LuaValue v = rawget(key);
return v.isnil() && m_metatable != null? gettable(this, valueOf(key)): v;
}
@Override
public LuaValue get(LuaValue key) {
LuaValue v = rawget(key);
return v.isnil() && m_metatable != null? gettable(this, key): v;
}
@Override
public LuaValue rawget(int key) {
if (key > 0 && key <= array.length) {
LuaValue v = m_metatable == null? array[key-1]: m_metatable.arrayget(array, key-1);
@@ -247,6 +258,7 @@ public class LuaTable extends LuaValue implements Metatable {
return hashget(LuaInteger.valueOf(key));
}
@Override
public LuaValue rawget(LuaValue key) {
if (key.isinttype()) {
int ikey = key.toint();
@@ -270,12 +282,14 @@ public class LuaTable extends LuaValue implements Metatable {
return NIL;
}
@Override
public void set(int key, LuaValue value) {
if (m_metatable == null || !rawget(key).isnil() || !settable(this, LuaInteger.valueOf(key), value))
rawset(key, value);
}
/** caller must ensure key is not nil */
@Override
public void set(LuaValue key, LuaValue value) {
if (key == null || !key.isvalidkey() && !metatag(NEWINDEX).isfunction())
throw new LuaError("value ('" + key + "') can not be used as a table index");
@@ -283,12 +297,14 @@ public class LuaTable extends LuaValue implements Metatable {
rawset(key, value);
}
@Override
public void rawset(int key, LuaValue value) {
if (!arrayset(key, value))
hashset(LuaInteger.valueOf(key), value);
}
/** caller must ensure key is not nil */
@Override
public void rawset(LuaValue key, LuaValue value) {
if (!key.isinttype() || !arrayset(key.toint(), value))
hashset(key, value);
@@ -297,7 +313,7 @@ public class LuaTable extends LuaValue implements Metatable {
/** Set an array element */
private boolean arrayset(int key, LuaValue value) {
if (key > 0 && key <= array.length) {
array[key-1] = value.isnil()? null: (m_metatable != null? m_metatable.wrap(value): value);
array[key-1] = value.isnil()? null: m_metatable != null? m_metatable.wrap(value): value;
return true;
}
return false;
@@ -359,6 +375,7 @@ public class LuaTable extends LuaValue implements Metatable {
return sb.tostring();
}
@Override
public int length() {
if (m_metatable != null) {
LuaValue len = len();
@@ -369,6 +386,7 @@ public class LuaTable extends LuaValue implements Metatable {
return rawlen();
}
@Override
public LuaValue len() {
final LuaValue h = metatag(LEN);
if (h.toboolean())
@@ -376,6 +394,7 @@ public class LuaTable extends LuaValue implements Metatable {
return LuaInteger.valueOf(rawlen());
}
@Override
public int rawlen() {
int a = getArrayLength();
int n = a+1, m = 0;
@@ -398,6 +417,7 @@ public class LuaTable extends LuaValue implements Metatable {
*
* @return key,value or nil
*/
@Override
public Varargs next(LuaValue key) {
int i = 0;
do {
@@ -461,6 +481,7 @@ public class LuaTable extends LuaValue implements Metatable {
*
* @return key,value or none
*/
@Override
public Varargs inext(LuaValue key) {
int k = key.checkint()+1;
LuaValue v = rawget(k);
@@ -499,8 +520,8 @@ public class LuaTable extends LuaValue implements Metatable {
}
index = hashSlot(key);
}
Slot entry = (m_metatable != null)? m_metatable.entry(key, value): defaultEntry(key, value);
hash[index] = (hash[index] != null)? hash[index].add(entry): entry;
Slot entry = m_metatable != null? m_metatable.entry(key, value): defaultEntry(key, value);
hash[index] = hash[index] != null? hash[index].add(entry): entry;
++hashEntries;
}
}
@@ -564,8 +585,8 @@ public class LuaTable extends LuaValue implements Metatable {
private int countHashKeys() {
int keys = 0;
for (int i = 0; i < hash.length; ++i) {
for (Slot slot = hash[i]; slot != null; slot = slot.rest()) {
for (Slot element : hash) {
for (Slot slot = element; slot != null; slot = slot.rest()) {
if (slot.first() != null)
keys++;
}
@@ -710,7 +731,7 @@ public class LuaTable extends LuaValue implements Metatable {
if (total*2 < 1<<log) {
// Not enough integer keys.
break;
} else if (keys >= (1<<(log-1))) {
} else if (keys >= 1<<log-1) {
newArraySize = 1<<log;
}
}
@@ -741,14 +762,14 @@ public class LuaTable extends LuaValue implements Metatable {
newArray = array;
}
final int newHashSize = hashEntries-movingToArray+((newKey < 0 || newKey > newArraySize)? 1: 0); // Make room for the new entry
final int newHashSize = hashEntries-movingToArray+(newKey < 0 || newKey > newArraySize? 1: 0); // Make room for the new entry
final int oldCapacity = oldHash.length;
final int newCapacity;
final int newHashMask;
if (newHashSize > 0) {
// round up to next power of 2.
newCapacity = (newHashSize < MIN_HASH_CAPACITY)? MIN_HASH_CAPACITY: 1<<log2(newHashSize);
newCapacity = newHashSize < MIN_HASH_CAPACITY? MIN_HASH_CAPACITY: 1<<log2(newHashSize);
newHashMask = newCapacity-1;
newHash = new Slot[newCapacity];
} else {
@@ -785,7 +806,7 @@ public class LuaTable extends LuaValue implements Metatable {
} else {
newEntry = defaultEntry(valueOf(i), v);
}
newHash[slot] = (newHash[slot] != null)? newHash[slot].add(newEntry): newEntry;
newHash[slot] = newHash[slot] != null? newHash[slot].add(newEntry): newEntry;
}
}
@@ -794,6 +815,7 @@ public class LuaTable extends LuaValue implements Metatable {
hashEntries -= movingToArray;
}
@Override
public Slot entry(LuaValue key, LuaValue value) {
return defaultEntry(key, value);
}
@@ -832,7 +854,7 @@ public class LuaTable extends LuaValue implements Metatable {
* @param comparator {@link LuaValue} to be called to compare elements.
*/
public void sort(LuaValue comparator) {
if (len().tolong() >= (long) Integer.MAX_VALUE)
if (len().tolong() >= Integer.MAX_VALUE)
throw new LuaError("array too big: " + len().tolong());
if (m_metatable != null && m_metatable.useWeakValues()) {
dropWeakArrayValues();
@@ -919,8 +941,10 @@ public class LuaTable extends LuaValue implements Metatable {
}
// equality w/ metatable processing
@Override
public LuaValue eq(LuaValue val) { return eq_b(val)? TRUE: FALSE; }
@Override
public boolean eq_b(LuaValue val) {
if (this == val)
return true;
@@ -1049,42 +1073,52 @@ public class LuaTable extends LuaValue implements Metatable {
this.next = next;
}
@Override
public LuaValue key() {
return entry.key();
}
@Override
public int keyindex(int hashMask) {
return entry.keyindex(hashMask);
}
@Override
public LuaValue value() {
return entry.value();
}
@Override
public Varargs toVarargs() {
return entry.toVarargs();
}
@Override
public StrongSlot first() {
return entry;
}
@Override
public StrongSlot find(LuaValue key) {
return entry.keyeq(key)? this: null;
}
@Override
public boolean keyeq(LuaValue key) {
return entry.keyeq(key);
}
@Override
public Slot rest() {
return next;
}
@Override
public int arraykey(int max) {
return entry.arraykey(max);
}
@Override
public Slot set(StrongSlot target, LuaValue value) {
if (target == this) {
entry = entry.set(value);
@@ -1094,10 +1128,12 @@ public class LuaTable extends LuaValue implements Metatable {
}
}
@Override
public Slot add(Slot entry) {
return setnext(next.add(entry));
}
@Override
public Slot remove(StrongSlot target) {
if (this == target) {
return new DeadSlot(key(), next);
@@ -1107,9 +1143,10 @@ public class LuaTable extends LuaValue implements Metatable {
return this;
}
@Override
public Slot relink(Slot rest) {
// This method is (only) called during rehash, so it must not change this.next.
return (rest != null)? new LinkSlot(entry, rest): (Slot) entry;
return rest != null? new LinkSlot(entry, rest): (Slot) entry;
}
// this method ensures that this.next is never set to null.
@@ -1122,6 +1159,7 @@ public class LuaTable extends LuaValue implements Metatable {
}
}
@Override
public String toString() {
return entry + "; " + next;
}
@@ -1135,20 +1173,26 @@ public class LuaTable extends LuaValue implements Metatable {
* overridden to handle that case.
*/
static abstract class Entry extends Varargs implements StrongSlot {
@Override
public abstract LuaValue key();
@Override
public abstract LuaValue value();
abstract Entry set(LuaValue value);
@Override
public abstract boolean keyeq(LuaValue key);
@Override
public abstract int keyindex(int hashMask);
@Override
public int arraykey(int max) {
return 0;
}
@Override
public LuaValue arg(int i) {
switch (i) {
case 1:
@@ -1159,6 +1203,7 @@ public class LuaTable extends LuaValue implements Metatable {
return NIL;
}
@Override
public int narg() {
return 2;
}
@@ -1166,14 +1211,17 @@ public class LuaTable extends LuaValue implements Metatable {
/**
* Subclasses should redefine as "return this;" whenever possible.
*/
@Override
public Varargs toVarargs() {
return varargsOf(key(), value());
}
@Override
public LuaValue arg1() {
return key();
}
@Override
public Varargs subargs(int start) {
switch (start) {
case 1:
@@ -1184,32 +1232,39 @@ public class LuaTable extends LuaValue implements Metatable {
return NONE;
}
@Override
public StrongSlot first() {
return this;
}
@Override
public Slot rest() {
return null;
}
@Override
public StrongSlot find(LuaValue key) {
return keyeq(key)? this: null;
}
@Override
public Slot set(StrongSlot target, LuaValue value) {
return set(value);
}
@Override
public Slot add(Slot entry) {
return new LinkSlot(this, entry);
}
@Override
public Slot remove(StrongSlot target) {
return new DeadSlot(key(), null);
}
@Override
public Slot relink(Slot rest) {
return (rest != null)? new LinkSlot(this, rest): (Slot) this;
return rest != null? new LinkSlot(this, rest): (Slot) this;
}
}
@@ -1222,27 +1277,33 @@ public class LuaTable extends LuaValue implements Metatable {
this.value = value;
}
@Override
public LuaValue key() {
return key;
}
@Override
public LuaValue value() {
return value;
}
@Override
public Entry set(LuaValue value) {
this.value = value;
return this;
}
@Override
public Varargs toVarargs() {
return this;
}
@Override
public int keyindex(int hashMask) {
return hashSlot(key, hashMask);
}
@Override
public boolean keyeq(LuaValue key) {
return key.raweq(this.key);
}
@@ -1257,27 +1318,33 @@ public class LuaTable extends LuaValue implements Metatable {
this.value = value;
}
@Override
public LuaValue key() {
return valueOf(key);
}
@Override
public int arraykey(int max) {
return (key >= 1 && key <= max)? key: 0;
return key >= 1 && key <= max? key: 0;
}
@Override
public LuaValue value() {
return value;
}
@Override
public Entry set(LuaValue value) {
this.value = value;
return this;
}
@Override
public int keyindex(int mask) {
return hashmod(LuaInteger.hashCode(key), mask);
}
@Override
public boolean keyeq(LuaValue key) {
return key.raweq(this.key);
}
@@ -1296,14 +1363,17 @@ public class LuaTable extends LuaValue implements Metatable {
this.value = value;
}
@Override
public LuaValue key() {
return key;
}
@Override
public LuaValue value() {
return valueOf(value);
}
@Override
public Entry set(LuaValue value) {
if (value.type() == TNUMBER) {
LuaValue n = value.tonumber();
@@ -1315,10 +1385,12 @@ public class LuaTable extends LuaValue implements Metatable {
return new NormalEntry(this.key, value);
}
@Override
public int keyindex(int mask) {
return hashSlot(key, mask);
}
@Override
public boolean keyeq(LuaValue key) {
return key.raweq(this.key);
}
@@ -1342,34 +1414,41 @@ public class LuaTable extends LuaValue implements Metatable {
return (LuaValue) (key instanceof WeakReference? ((WeakReference) key).get(): key);
}
@Override
public int keyindex(int hashMask) {
// Not needed: this entry will be dropped during rehash.
return 0;
}
@Override
public StrongSlot first() {
return null;
}
@Override
public StrongSlot find(LuaValue key) {
return null;
}
@Override
public boolean keyeq(LuaValue key) {
LuaValue k = key();
return k != null && key.raweq(k);
}
@Override
public Slot rest() {
return next;
}
@Override
public int arraykey(int max) {
return -1;
}
@Override
public Slot set(StrongSlot target, LuaValue value) {
Slot next = (this.next != null)? this.next.set(target, value): null;
Slot next = this.next != null? this.next.set(target, value): null;
if (key() != null) {
// if key hasn't been garbage collected, it is still potentially a valid argument
// to next(), so we can't drop this entry yet.
@@ -1380,10 +1459,12 @@ public class LuaTable extends LuaValue implements Metatable {
}
}
@Override
public Slot add(Slot newEntry) {
return (next != null)? next.add(newEntry): newEntry;
return next != null? next.add(newEntry): newEntry;
}
@Override
public Slot remove(StrongSlot target) {
if (key() != null) {
next = next.remove(target);
@@ -1393,10 +1474,12 @@ public class LuaTable extends LuaValue implements Metatable {
}
}
@Override
public Slot relink(Slot rest) {
return rest;
}
@Override
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("<dead");
@@ -1412,28 +1495,33 @@ public class LuaTable extends LuaValue implements Metatable {
}
return buf.toString();
}
};
}
private static final Slot[] NOBUCKETS = {};
// Metatable operations
@Override
public boolean useWeakKeys() {
return false;
}
@Override
public boolean useWeakValues() {
return false;
}
@Override
public LuaValue toLuaValue() {
return this;
}
@Override
public LuaValue wrap(LuaValue value) {
return value;
}
@Override
public LuaValue arrayget(LuaValue[] array, int index) {
return array[index];
}

View File

@@ -121,26 +121,32 @@ public class LuaThread extends LuaValue {
this.globals = globals;
}
@Override
public int type() {
return LuaValue.TTHREAD;
}
@Override
public String typename() {
return "thread";
}
@Override
public boolean isthread() {
return true;
}
@Override
public LuaThread optthread(LuaThread defval) {
return this;
}
@Override
public LuaThread checkthread() {
return this;
}
@Override
public LuaValue getmetatable() {
return s_metatable;
}
@@ -184,6 +190,7 @@ public class LuaThread extends LuaValue {
this.function = function;
}
@Override
public synchronized void run() {
try {
Varargs a = this.args;
@@ -212,8 +219,8 @@ public class LuaThread extends LuaValue {
previous_thread.state.status = STATUS_NORMAL;
this.status = STATUS_RUNNING;
this.wait();
return (this.error != null? LuaValue.varargsOf(LuaValue.FALSE, LuaValue.valueOf(this.error))
: LuaValue.varargsOf(LuaValue.TRUE, this.result));
return this.error != null? LuaValue.varargsOf(LuaValue.FALSE, LuaValue.valueOf(this.error))
: LuaValue.varargsOf(LuaValue.TRUE, this.result);
} catch (InterruptedException ie) {
throw new OrphanedThread();
} finally {

View File

@@ -35,18 +35,22 @@ public class LuaUserdata extends LuaValue {
m_metatable = metatable;
}
@Override
public String tojstring() {
return String.valueOf(m_instance);
}
@Override
public int type() {
return LuaValue.TUSERDATA;
}
@Override
public String typename() {
return "userdata";
}
@Override
public int hashCode() {
return m_instance.hashCode();
}
@@ -55,50 +59,63 @@ public class LuaUserdata extends LuaValue {
return m_instance;
}
@Override
public boolean isuserdata() { return true; }
@Override
public boolean isuserdata(Class c) { return c.isAssignableFrom(m_instance.getClass()); }
@Override
public Object touserdata() { return m_instance; }
@Override
public Object touserdata(Class c) { return c.isAssignableFrom(m_instance.getClass())? m_instance: null; }
@Override
public Object optuserdata(Object defval) { return m_instance; }
@Override
public Object optuserdata(Class c, Object defval) {
if (!c.isAssignableFrom(m_instance.getClass()))
typerror(c.getName());
return m_instance;
}
@Override
public LuaValue getmetatable() {
return m_metatable;
}
@Override
public LuaValue setmetatable(LuaValue metatable) {
this.m_metatable = metatable;
return this;
}
@Override
public Object checkuserdata() {
return m_instance;
}
@Override
public Object checkuserdata(Class c) {
if (c.isAssignableFrom(m_instance.getClass()))
return m_instance;
return typerror(c.getName());
}
@Override
public LuaValue get(LuaValue key) {
return m_metatable != null? gettable(this, key): NIL;
}
@Override
public void set(LuaValue key, LuaValue value) {
if (m_metatable == null || !settable(this, key, value))
error("cannot set " + key + " for userdata");
}
@Override
public boolean equals(Object val) {
if (this == val)
return true;
@@ -109,8 +126,10 @@ public class LuaUserdata extends LuaValue {
}
// equality w/ metatable processing
@Override
public LuaValue eq(LuaValue val) { return eq_b(val)? TRUE: FALSE; }
@Override
public boolean eq_b(LuaValue val) {
if (val.raweq(this))
return true;
@@ -121,10 +140,12 @@ public class LuaUserdata extends LuaValue {
}
// equality w/o metatable processing
@Override
public boolean raweq(LuaValue val) { return val.raweq(this); }
@Override
public boolean raweq(LuaUserdata val) {
return this == val || (m_metatable == val.m_metatable && m_instance.equals(val.m_instance));
return this == val || m_metatable == val.m_metatable && m_instance.equals(val.m_instance);
}
// __eq metatag processing

View File

@@ -135,13 +135,13 @@ abstract public class LuaValue extends Varargs {
* Type enumeration constant for lua numbers that are ints, for
* compatibility with lua 5.1 number patch only
*/
public static final int TINT = (-2);
public static final int TINT = -2;
/**
* Type enumeration constant for lua values that have no type, for example
* weak table entries
*/
public static final int TNONE = (-1);
public static final int TNONE = -1;
/** Type enumeration constant for lua nil */
public static final int TNIL = 0;
@@ -601,6 +601,7 @@ abstract public class LuaValue extends Varargs {
* @see #isstring()
* @see #TSTRING
*/
@Override
public String tojstring() { return typename() + ": " + Integer.toHexString(hashCode()); }
/**
@@ -636,6 +637,7 @@ abstract public class LuaValue extends Varargs {
* @see #checkstring()
* @see #toString()
*/
@Override
public String toString() { return tojstring(); }
/**
@@ -1631,10 +1633,13 @@ abstract public class LuaValue extends Varargs {
public LuaValue load(LuaValue library) { return library.call(EMPTYSTRING, this); }
// varargs references
@Override
public LuaValue arg(int index) { return index == 1? this: NIL; }
public int narg() { return 1; };
@Override
public int narg() { return 1; }
@Override
public LuaValue arg1() { return this; }
/**
@@ -2403,6 +2408,7 @@ abstract public class LuaValue extends Varargs {
public int rawlen() { typerror("table or string"); return 0; }
// object equality, used for key comparison
@Override
public boolean equals(Object obj) { return this == obj; }
/**
@@ -3625,7 +3631,7 @@ abstract public class LuaValue extends Varargs {
* @param b boolean value to convert
* @return {@link #TRUE} if not or {@link #FALSE} if false
*/
public static LuaBoolean valueOf(boolean b) { return b? LuaValue.TRUE: FALSE; };
public static LuaBoolean valueOf(boolean b) { return b? LuaValue.TRUE: FALSE; }
/**
* Convert java int to a {@link LuaValue}.
@@ -3642,7 +3648,7 @@ abstract public class LuaValue extends Varargs {
* @param d double value to convert
* @return {@link LuaNumber} instance, possibly pooled, whose value is d
*/
public static LuaNumber valueOf(double d) { return LuaDouble.valueOf(d); };
public static LuaNumber valueOf(double d) { return LuaDouble.valueOf(d); }
/**
* Convert java string to a {@link LuaValue}.
@@ -3825,7 +3831,7 @@ abstract public class LuaValue extends Varargs {
do {
if (t.istable()) {
LuaValue res = t.rawget(key);
if ((!res.isnil()) || (tm = t.metatag(INDEX)).isnil())
if (!res.isnil() || (tm = t.metatag(INDEX)).isnil())
return res;
} else if ((tm = t.metatag(INDEX)).isnil())
t.indexerror(key.tojstring());
@@ -3854,7 +3860,7 @@ abstract public class LuaValue extends Varargs {
int loop = 0;
do {
if (t.istable()) {
if ((!t.rawget(key).isnil()) || (tm = t.metatag(NEWINDEX)).isnil()) {
if (!t.rawget(key).isnil() || (tm = t.metatag(NEWINDEX)).isnil()) {
t.rawset(key, value);
return true;
}
@@ -4127,16 +4133,22 @@ abstract public class LuaValue extends Varargs {
private static final class None extends LuaNil {
static None _NONE = new None();
@Override
public LuaValue arg(int i) { return NIL; }
@Override
public int narg() { return 0; }
@Override
public LuaValue arg1() { return NIL; }
@Override
public String tojstring() { return "none"; }
@Override
public Varargs subargs(final int start) { return start > 0? this: argerror(1, "start must be > 0"); }
@Override
void copyto(LuaValue[] dest, int offset, int length) {
for (; length > 0; length--)
dest[offset++] = NIL;
@@ -4152,6 +4164,7 @@ abstract public class LuaValue extends Varargs {
* @return Varargs containing argument { start, start+1, ... , narg-start-1
* }
*/
@Override
public Varargs subargs(final int start) {
if (start == 1)
return this;

View File

@@ -29,23 +29,23 @@ import org.luaj.vm2.LuaTable.Slot;
interface Metatable {
/** Return whether or not this table's keys are weak. */
public boolean useWeakKeys();
boolean useWeakKeys();
/** Return whether or not this table's values are weak. */
public boolean useWeakValues();
boolean useWeakValues();
/** Return this metatable as a LuaValue. */
public LuaValue toLuaValue();
LuaValue toLuaValue();
/** Return an instance of Slot appropriate for the given key and value. */
public Slot entry(LuaValue key, LuaValue value);
Slot entry(LuaValue key, LuaValue value);
/** Returns the given value wrapped in a weak reference if appropriate. */
public LuaValue wrap(LuaValue value);
LuaValue wrap(LuaValue value);
/**
* Returns the value at the given index in the array, or null if it is a
* weak reference that has been dropped.
*/
public LuaValue arrayget(LuaValue[] array, int index);
LuaValue arrayget(LuaValue[] array, int index);
}

View File

@@ -10,26 +10,32 @@ class NonTableMetatable implements Metatable {
this.value = value;
}
@Override
public boolean useWeakKeys() {
return false;
}
@Override
public boolean useWeakValues() {
return false;
}
@Override
public LuaValue toLuaValue() {
return value;
}
@Override
public Slot entry(LuaValue key, LuaValue value) {
return LuaTable.defaultEntry(key, value);
}
@Override
public LuaValue wrap(LuaValue value) {
return value;
}
@Override
public LuaValue arrayget(LuaValue[] array, int index) {
return array[index];
}

View File

@@ -168,15 +168,15 @@ public class Print extends Lua {
case iABC:
ps.print(a);
if (getBMode(o) != OpArgN)
ps.print(" " + (ISK(b)? (-1-INDEXK(b)): b));
ps.print(" " + (ISK(b)? -1-INDEXK(b): b));
if (getCMode(o) != OpArgN)
ps.print(" " + (ISK(c)? (-1-INDEXK(c)): c));
ps.print(" " + (ISK(c)? -1-INDEXK(c): c));
break;
case iABx:
if (getBMode(o) == OpArgK) {
ps.print(a + " " + (-1-bx));
} else {
ps.print(a + " " + (bx));
ps.print(a + " " + bx);
}
break;
case iAsBx:
@@ -274,9 +274,9 @@ public class Print extends Lua {
break;
case OP_SETLIST:
if (c == 0)
ps.print(" ; " + ((int) code[++pc]) + " (stored in the next OP)");
ps.print(" ; " + code[++pc] + " (stored in the next OP)");
else
ps.print(" ; " + ((int) c));
ps.print(" ; " + c);
break;
case OP_VARARG:
ps.print(" ; is_vararg=" + f.is_vararg);
@@ -300,7 +300,7 @@ public class Print extends Lua {
s = "(bstring)";
else
s = "(string)";
String a = (f.linedefined == 0)? "main": "function";
String a = f.linedefined == 0? "main": "function";
ps.print("\n%" + a + " <" + s + ":" + f.linedefined + "," + f.lastlinedefined + "> (" + f.code.length
+ " instructions, " + f.code.length*4 + " bytes at " + id(f) + ")\n");
ps.print(f.numparams + " param, " + f.maxstacksize + " slot, " + f.upvalues.length + " upvalue, ");

View File

@@ -145,6 +145,7 @@ public class Prototype {
upvalues = new Upvaldesc[n_upvalues];
}
@Override
public String toString() {
return source + ":" + linedefined + "-" + lastlinedefined;
}

View File

@@ -55,8 +55,10 @@ public class TailcallVarargs extends Varargs {
this.args = LuaValue.varargsOf(object, args);
}
@Override
public boolean isTailcall() { return true; }
@Override
public Varargs eval() {
while ( result == null ) {
Varargs r = func.onInvoke(args);
@@ -73,24 +75,28 @@ public class TailcallVarargs extends Varargs {
return result;
}
@Override
public LuaValue arg(int i) {
if (result == null)
eval();
return result.arg(i);
}
@Override
public LuaValue arg1() {
if (result == null)
eval();
return result.arg1();
}
@Override
public int narg() {
if (result == null)
eval();
return result.narg();
}
@Override
public Varargs subargs(int start) {
if (result == null)
eval();

View File

@@ -44,6 +44,7 @@ public final class UpValue {
this.index = index;
}
@Override
public String toString() {
return index + "/" + array.length + " " + array[index];
}
@@ -63,19 +64,19 @@ public final class UpValue {
*
* @return the {@link LuaValue} for this upvalue
*/
public final LuaValue getValue() { return array[index]; }
public LuaValue getValue() { return array[index]; }
/**
* Set the value of the upvalue
*
* @param value the {@link LuaValue} to set it to
*/
public final void setValue(LuaValue value) { array[index] = value; }
public void setValue(LuaValue value) { array[index] = value; }
/**
* Close this upvalue so it is no longer on the stack
*/
public final void close() {
public void close() {
LuaValue[] old = array;
array = new LuaValue[] { old[index] };
old[index] = null;

View File

@@ -38,6 +38,7 @@ public class Upvaldesc {
this.idx = (short) idx;
}
@Override
public String toString() {
return idx+(instack? " instack ": " closed ")+String.valueOf(name);
}

View File

@@ -677,6 +677,7 @@ public abstract class Varargs {
* @return String value in human readable form.
* @see Varargs#tojstring()
*/
@Override
public String toString() { return tojstring(); }
/**
@@ -706,19 +707,23 @@ public abstract class Varargs {
this.end = end;
}
@Override
public LuaValue arg(int i) {
i += start-1;
return i >= start && i <= end? v.arg(i): LuaValue.NIL;
}
@Override
public LuaValue arg1() {
return v.arg(start);
}
@Override
public int narg() {
return end+1-start;
}
@Override
public Varargs subargs(final int start) {
if (start == 1)
return this;
@@ -761,18 +766,22 @@ public abstract class Varargs {
this.v2 = v2;
}
@Override
public LuaValue arg(int i) {
return i == 1? v1: v2.arg(i-1);
}
@Override
public int narg() {
return 1+v2.narg();
}
@Override
public LuaValue arg1() {
return v1;
}
@Override
public Varargs subargs(final int start) {
if (start == 1)
return this;
@@ -811,16 +820,20 @@ public abstract class Varargs {
this.r = r;
}
@Override
public LuaValue arg(int i) {
return i < 1? LuaValue.NIL: i <= v.length? v[i-1]: r.arg(i-v.length);
}
@Override
public int narg() {
return v.length+r.narg();
}
@Override
public LuaValue arg1() { return v.length > 0? v[0]: r.arg1(); }
@Override
public Varargs subargs(int start) {
if (start <= 0)
LuaValue.argerror(1, "start must be > 0");
@@ -831,6 +844,7 @@ public abstract class Varargs {
return LuaValue.varargsOf(v, start-1, v.length-(start-1), r);
}
@Override
void copyto(LuaValue[] dest, int offset, int length) {
int n = Math.min(v.length, length);
System.arraycopy(v, 0, dest, offset, n);
@@ -884,18 +898,22 @@ public abstract class Varargs {
this.more = more;
}
@Override
public LuaValue arg(final int i) {
return i < 1? LuaValue.NIL: i <= length? v[offset+i-1]: more.arg(i-length);
}
@Override
public int narg() {
return length+more.narg();
}
@Override
public LuaValue arg1() {
return length > 0? v[offset]: more.arg1();
}
@Override
public Varargs subargs(int start) {
if (start <= 0)
LuaValue.argerror(1, "start must be > 0");
@@ -906,6 +924,7 @@ public abstract class Varargs {
return LuaValue.varargsOf(v, offset+start-1, length-(start-1), more);
}
@Override
void copyto(LuaValue[] dest, int offset, int length) {
int n = Math.min(this.length, length);
System.arraycopy(this.v, this.offset, dest, offset, n);

View File

@@ -37,8 +37,8 @@ import org.luaj.vm2.LuaTable.StrongSlot;
*/
public class WeakTable implements Metatable {
private boolean weakkeys, weakvalues;
private LuaValue backing;
private final boolean weakkeys, weakvalues;
private final LuaValue backing;
public static LuaTable make(boolean weakkeys, boolean weakvalues) {
LuaString mode;
@@ -49,10 +49,10 @@ public class WeakTable implements Metatable {
} else if (weakvalues) {
mode = LuaString.valueOf("v");
} else {
return LuaTable.tableOf();
return LuaValue.tableOf();
}
LuaTable table = LuaTable.tableOf();
LuaTable mt = LuaTable.tableOf(new LuaValue[] { LuaValue.MODE, mode });
LuaTable table = LuaValue.tableOf();
LuaTable mt = LuaValue.tableOf(new LuaValue[] { LuaValue.MODE, mode });
table.setmetatable(mt);
return table;
}
@@ -69,18 +69,22 @@ public class WeakTable implements Metatable {
this.backing = backing;
}
@Override
public boolean useWeakKeys() {
return weakkeys;
}
@Override
public boolean useWeakValues() {
return weakvalues;
}
@Override
public LuaValue toLuaValue() {
return backing;
}
@Override
public Slot entry(LuaValue key, LuaValue value) {
value = value.strongvalue();
if (value == null)
@@ -110,10 +114,12 @@ public class WeakTable implements Metatable {
this.next = next;
}
@Override
public abstract int keyindex(int hashMask);
public abstract Slot set(LuaValue value);
@Override
public StrongSlot first() {
LuaValue key = strongkey();
LuaValue value = strongvalue();
@@ -126,25 +132,30 @@ public class WeakTable implements Metatable {
}
}
@Override
public StrongSlot find(LuaValue key) {
StrongSlot first = first();
return (first != null)? first.find(key): null;
return first != null? first.find(key): null;
}
@Override
public boolean keyeq(LuaValue key) {
StrongSlot first = first();
return (first != null) && first.keyeq(key);
return first != null && first.keyeq(key);
}
@Override
public Slot rest() {
return next;
}
@Override
public int arraykey(int max) {
// Integer keys can never be weak.
return 0;
}
@Override
public Slot set(StrongSlot target, LuaValue value) {
LuaValue key = strongkey();
if (key != null && target.find(key) != null) {
@@ -159,8 +170,9 @@ public class WeakTable implements Metatable {
}
}
@Override
public Slot add(Slot entry) {
next = (next != null)? next.add(entry): entry;
next = next != null? next.add(entry): entry;
if (strongkey() != null && strongvalue() != null) {
return this;
} else {
@@ -168,6 +180,7 @@ public class WeakTable implements Metatable {
}
}
@Override
public Slot remove(StrongSlot target) {
LuaValue key = strongkey();
if (key == null) {
@@ -181,6 +194,7 @@ public class WeakTable implements Metatable {
}
}
@Override
public Slot relink(Slot rest) {
if (strongkey() != null && strongvalue() != null) {
if (rest == null && this.next == null) {
@@ -218,19 +232,23 @@ public class WeakTable implements Metatable {
this.keyhash = copyFrom.keyhash;
}
@Override
public int keyindex(int mask) {
return LuaTable.hashmod(keyhash, mask);
}
@Override
public Slot set(LuaValue value) {
this.value = value;
return this;
}
@Override
public LuaValue strongkey() {
return strengthen(key);
}
@Override
protected WeakSlot copy(Slot rest) {
return new WeakKeySlot(this, rest);
}
@@ -246,19 +264,23 @@ public class WeakTable implements Metatable {
super(copyFrom.key, copyFrom.value, next);
}
@Override
public int keyindex(int mask) {
return LuaTable.hashSlot(strongkey(), mask);
}
@Override
public Slot set(LuaValue value) {
this.value = weaken(value);
return this;
}
@Override
public LuaValue strongvalue() {
return strengthen(value);
}
@Override
protected WeakSlot copy(Slot next) {
return new WeakValueSlot(this, next);
}
@@ -278,23 +300,28 @@ public class WeakTable implements Metatable {
keyhash = copyFrom.keyhash;
}
@Override
public int keyindex(int hashMask) {
return LuaTable.hashmod(keyhash, hashMask);
}
@Override
public Slot set(LuaValue value) {
this.value = weaken(value);
return this;
}
@Override
public LuaValue strongkey() {
return strengthen(key);
}
@Override
public LuaValue strongvalue() {
return strengthen(value);
}
@Override
protected WeakSlot copy(Slot next) {
return new WeakKeyAndValueSlot(this, next);
}
@@ -349,25 +376,30 @@ public class WeakTable implements Metatable {
ref = new WeakReference(value);
}
@Override
public int type() {
illegal("type", "weak value");
return 0;
}
@Override
public String typename() {
illegal("typename", "weak value");
return null;
}
@Override
public String toString() {
return "weak<" + ref.get() + ">";
}
@Override
public LuaValue strongvalue() {
Object o = ref.get();
return (LuaValue) o;
}
@Override
public boolean raweq(LuaValue rhs) {
Object o = ref.get();
return o != null && rhs.raweq((LuaValue) o);
@@ -389,6 +421,7 @@ public class WeakTable implements Metatable {
mt = value.getmetatable();
}
@Override
public LuaValue strongvalue() {
Object u = ref.get();
if (u != null)
@@ -404,10 +437,12 @@ public class WeakTable implements Metatable {
}
}
@Override
public LuaValue wrap(LuaValue value) {
return weakvalues? weaken(value): value;
}
@Override
public LuaValue arrayget(LuaValue[] array, int index) {
LuaValue value = array[index];
if (value != null) {

View File

@@ -59,27 +59,27 @@ public class Constants extends Lua {
}
static void SET_OPCODE(InstructionPtr i, int o) {
i.set((i.get() & (MASK_NOT_OP)) | ((o<<POS_OP) & MASK_OP));
i.set(i.get() & MASK_NOT_OP | o<<POS_OP & MASK_OP);
}
static void SETARG_A(int[] code, int index, int u) {
code[index] = (code[index] & (MASK_NOT_A)) | ((u<<POS_A) & MASK_A);
code[index] = code[index] & MASK_NOT_A | u<<POS_A & MASK_A;
}
static void SETARG_A(InstructionPtr i, int u) {
i.set((i.get() & (MASK_NOT_A)) | ((u<<POS_A) & MASK_A));
i.set(i.get() & MASK_NOT_A | u<<POS_A & MASK_A);
}
static void SETARG_B(InstructionPtr i, int u) {
i.set((i.get() & (MASK_NOT_B)) | ((u<<POS_B) & MASK_B));
i.set(i.get() & MASK_NOT_B | u<<POS_B & MASK_B);
}
static void SETARG_C(InstructionPtr i, int u) {
i.set((i.get() & (MASK_NOT_C)) | ((u<<POS_C) & MASK_C));
i.set(i.get() & MASK_NOT_C | u<<POS_C & MASK_C);
}
static void SETARG_Bx(InstructionPtr i, int u) {
i.set((i.get() & (MASK_NOT_Bx)) | ((u<<POS_Bx) & MASK_Bx));
i.set(i.get() & MASK_NOT_Bx | u<<POS_Bx & MASK_Bx);
}
static void SETARG_sBx(InstructionPtr i, int u) {
@@ -87,15 +87,15 @@ public class Constants extends Lua {
}
static int CREATE_ABC(int o, int a, int b, int c) {
return ((o<<POS_OP) & MASK_OP) | ((a<<POS_A) & MASK_A) | ((b<<POS_B) & MASK_B) | ((c<<POS_C) & MASK_C);
return o<<POS_OP & MASK_OP | a<<POS_A & MASK_A | b<<POS_B & MASK_B | c<<POS_C & MASK_C;
}
static int CREATE_ABx(int o, int a, int bc) {
return ((o<<POS_OP) & MASK_OP) | ((a<<POS_A) & MASK_A) | ((bc<<POS_Bx) & MASK_Bx);
return o<<POS_OP & MASK_OP | a<<POS_A & MASK_A | bc<<POS_Bx & MASK_Bx;
}
static int CREATE_Ax(int o, int a) {
return ((o<<POS_OP) & MASK_OP) | ((a<<POS_Ax) & MASK_Ax);
return o<<POS_OP & MASK_OP | a<<POS_Ax & MASK_Ax;
}
// vector reallocation

View File

@@ -131,9 +131,9 @@ public class DumpState {
void dumpInt(int x) throws IOException {
if (IS_LITTLE_ENDIAN) {
writer.writeByte(x & 0xff);
writer.writeByte((x>>8) & 0xff);
writer.writeByte((x>>16) & 0xff);
writer.writeByte((x>>24) & 0xff);
writer.writeByte(x>>8 & 0xff);
writer.writeByte(x>>16 & 0xff);
writer.writeByte(x>>24 & 0xff);
} else {
writer.writeInt(x);
}
@@ -312,7 +312,7 @@ public class DumpState {
DumpState D = new DumpState(w, stripDebug);
D.IS_LITTLE_ENDIAN = littleendian;
D.NUMBER_FORMAT = numberFormat;
D.SIZEOF_LUA_NUMBER = (numberFormat == NUMBER_FORMAT_INTS_ONLY? 4: 8);
D.SIZEOF_LUA_NUMBER = numberFormat == NUMBER_FORMAT_INTS_ONLY? 4: 8;
D.dumpHeader();
D.dumpFunction(f);
return D.status;

View File

@@ -43,7 +43,7 @@ public class FuncState extends Constants {
short nactvar; /* # active locals outside the breakable structure */
boolean upval; /* true if some variable in the block is an upvalue */
boolean isloop; /* true if `block' is a loop */
};
}
Prototype f; /* current function header */
Hashtable h; /* table to find (and reuse) elements in `k' */
@@ -106,7 +106,7 @@ public class FuncState extends Constants {
void errorlimit(int limit, String what) {
// TODO: report message logic.
String msg = (f.linedefined == 0)? ls.L.pushfstring("main function has more than " + limit + " " + what)
String msg = f.linedefined == 0? ls.L.pushfstring("main function has more than " + limit + " " + what)
: ls.L.pushfstring("function at line " + f.linedefined + " has more than " + limit + " " + what);
ls.lexerror(msg, 0);
}
@@ -118,7 +118,7 @@ public class FuncState extends Constants {
}
void removevars(int tolevel) {
ls.dyd.n_actvar -= (nactvar-tolevel);
ls.dyd.n_actvar -= nactvar-tolevel;
while ( nactvar > tolevel )
getlocvar(--nactvar).endpc = pc;
}
@@ -245,7 +245,7 @@ public class FuncState extends Constants {
}
boolean hasmultret(int k) {
return ((k) == LexState.VCALL || (k) == LexState.VVARARG);
return k == LexState.VCALL || k == LexState.VVARARG;
}
void lastlistfield(ConsControl cc) {
@@ -276,7 +276,7 @@ public class FuncState extends Constants {
if (GET_OPCODE(previous_code) == OP_LOADNIL) {
int pfrom = GETARG_A(previous_code);
int pl = pfrom+GETARG_B(previous_code);
if ((pfrom <= from && from <= pl+1) || (from <= pfrom && pfrom <= l+1)) { /* can connect both? */
if (pfrom <= from && from <= pl+1 || from <= pfrom && pfrom <= l+1) { /* can connect both? */
if (pfrom < from)
from = pfrom; /* from = min(from, pfrom) */
if (pl > l)
@@ -334,7 +334,7 @@ public class FuncState extends Constants {
return LexState.NO_JUMP;
else
/* turn offset into absolute position */
return (pc+1)+offset;
return pc+1+offset;
}
InstructionPtr getjumpcontrol(int pc) {
@@ -466,7 +466,7 @@ public class FuncState extends Constants {
return ((Integer) h.get(v)).intValue();
}
final int idx = this.nk;
this.h.put(v, new Integer(idx));
this.h.put(v, Integer.valueOf(idx));
final Prototype f = this.f;
if (f.k == null || nk+1 >= f.k.length)
f.k = realloc(f.k, nk*2+1);
@@ -482,14 +482,14 @@ public class FuncState extends Constants {
if (r instanceof LuaDouble) {
double d = r.todouble();
int i = (int) d;
if (d == (double) i)
if (d == i)
r = LuaInteger.valueOf(i);
}
return this.addk(r);
}
int boolK(boolean b) {
return this.addk((b? LuaValue.TRUE: LuaValue.FALSE));
return this.addk(b? LuaValue.TRUE: LuaValue.FALSE);
}
int nilK() {
@@ -562,7 +562,7 @@ public class FuncState extends Constants {
}
case LexState.VFALSE:
case LexState.VTRUE: {
this.codeABC(OP_LOADBOOL, reg, (e.k == LexState.VTRUE? 1: 0), 0);
this.codeABC(OP_LOADBOOL, reg, e.k == LexState.VTRUE? 1: 0, 0);
break;
}
case LexState.VK: {
@@ -608,7 +608,7 @@ public class FuncState extends Constants {
int p_f = LexState.NO_JUMP; /* position of an eventual LOAD false */
int p_t = LexState.NO_JUMP; /* position of an eventual LOAD true */
if (this.need_value(e.t.i) || this.need_value(e.f.i)) {
int fj = (e.k == LexState.VJMP)? LexState.NO_JUMP: this.jump();
int fj = e.k == LexState.VJMP? LexState.NO_JUMP: this.jump();
p_f = this.code_label(reg, 0, 1);
p_t = this.code_label(reg, 1, 0);
this.patchtohere(fj);
@@ -662,7 +662,7 @@ public class FuncState extends Constants {
case LexState.VFALSE:
case LexState.VNIL: {
if (this.nk <= MAXINDEXRK) { /* constant fit in RK operand? */
e.u.info = (e.k == LexState.VNIL)? this.nilK(): this.boolK((e.k == LexState.VTRUE));
e.u.info = e.k == LexState.VNIL? this.nilK(): this.boolK(e.k == LexState.VTRUE);
e.k = LexState.VK;
return RKASK(e.u.info);
} else
@@ -699,7 +699,7 @@ public class FuncState extends Constants {
break;
}
case LexState.VINDEXED: {
int op = (var.u.ind_vt == LexState.VLOCAL)? OP_SETTABLE: OP_SETTABUP;
int op = var.u.ind_vt == LexState.VLOCAL? OP_SETTABLE: OP_SETTABUP;
int e = this.exp2RK(ex);
this.codeABC(op, var.u.ind_t, var.u.ind_idx, e);
break;
@@ -730,7 +730,7 @@ public class FuncState extends Constants {
&& Lua.GET_OPCODE(pc.get()) != OP_TEST);
// SETARG_A(pc, !(GETARG_A(pc.get())));
int a = GETARG_A(pc.get());
int nota = (a != 0? 0: 1);
int nota = a != 0? 0: 1;
SETARG_A(pc, nota);
}
@@ -739,7 +739,7 @@ public class FuncState extends Constants {
int ie = this.getcode(e);
if (GET_OPCODE(ie) == OP_NOT) {
this.pc--; /* remove previous OP_NOT */
return this.condjump(OP_TEST, GETARG_B(ie), 0, (cond != 0? 0: 1));
return this.condjump(OP_TEST, GETARG_B(ie), 0, cond != 0? 0: 1);
}
/* else go through */
}
@@ -838,14 +838,14 @@ public class FuncState extends Constants {
}
static boolean vkisinreg(int k) {
return ((k) == LexState.VNONRELOC || (k) == LexState.VLOCAL);
return k == LexState.VNONRELOC || k == LexState.VLOCAL;
}
void indexed(expdesc t, expdesc k) {
t.u.ind_t = (short) t.u.info;
t.u.ind_idx = (short) this.exp2RK(k);
LuaC._assert(t.k == LexState.VUPVAL || vkisinreg(t.k));
t.u.ind_vt = (short) ((t.k == LexState.VUPVAL)? LexState.VUPVAL: LexState.VLOCAL);
Constants._assert(t.k == LexState.VUPVAL || vkisinreg(t.k));
t.u.ind_vt = (short) (t.k == LexState.VUPVAL? LexState.VUPVAL: LexState.VLOCAL);
t.k = LexState.VINDEXED;
}
@@ -895,10 +895,9 @@ public class FuncState extends Constants {
}
void codearith(int op, expdesc e1, expdesc e2, int line) {
if (constfolding(op, e1, e2))
return;
else {
int o2 = (op != OP_UNM && op != OP_LEN)? this.exp2RK(e2): 0;
if (constfolding(op, e1, e2)) {
} else {
int o2 = op != OP_UNM && op != OP_LEN? this.exp2RK(e2): 0;
int o1 = this.exp2RK(e1);
if (o1 > o2) {
this.freeexp(e1);
@@ -1068,11 +1067,11 @@ public class FuncState extends Constants {
this.dischargejpc(); /* `pc' will change */
/* put new instruction in code array */
if (f.code == null || this.pc+1 > f.code.length)
f.code = LuaC.realloc(f.code, this.pc*2+1);
f.code = Constants.realloc(f.code, this.pc*2+1);
f.code[this.pc] = instruction;
/* save corresponding line information */
if (f.lineinfo == null || this.pc+1 > f.lineinfo.length)
f.lineinfo = LuaC.realloc(f.lineinfo, this.pc*2+1);
f.lineinfo = Constants.realloc(f.lineinfo, this.pc*2+1);
f.lineinfo[this.pc] = line;
return this.pc++;
}
@@ -1108,7 +1107,7 @@ public class FuncState extends Constants {
void setlist(int base, int nelems, int tostore) {
int c = (nelems-1)/LFIELDS_PER_FLUSH+1;
int b = (tostore == LUA_MULTRET)? 0: tostore;
int b = tostore == LUA_MULTRET? 0: tostore;
_assert(tostore != 0);
if (c <= MAXARG_C)
this.codeABC(OP_SETLIST, base, b, c);

View File

@@ -45,16 +45,16 @@ public class LexState extends Constants {
protected static final String RESERVED_LOCAL_VAR_FOR_INDEX = "(for index)";
// keywords array
protected static final String[] RESERVED_LOCAL_VAR_KEYWORDS = new String[] { RESERVED_LOCAL_VAR_FOR_CONTROL,
protected static final String[] RESERVED_LOCAL_VAR_KEYWORDS = { RESERVED_LOCAL_VAR_FOR_CONTROL,
RESERVED_LOCAL_VAR_FOR_GENERATOR, RESERVED_LOCAL_VAR_FOR_INDEX, RESERVED_LOCAL_VAR_FOR_LIMIT,
RESERVED_LOCAL_VAR_FOR_STATE, RESERVED_LOCAL_VAR_FOR_STEP };
private static final Hashtable RESERVED_LOCAL_VAR_KEYWORDS_TABLE = new Hashtable();
static {
for (int i = 0; i < RESERVED_LOCAL_VAR_KEYWORDS.length; i++)
RESERVED_LOCAL_VAR_KEYWORDS_TABLE.put(RESERVED_LOCAL_VAR_KEYWORDS[i], Boolean.TRUE);
for (String element : RESERVED_LOCAL_VAR_KEYWORDS)
RESERVED_LOCAL_VAR_KEYWORDS_TABLE.put(element, Boolean.TRUE);
}
private static final int EOZ = (-1);
private static final int EOZ = -1;
private static final int MAX_INT = Integer.MAX_VALUE-2;
private static final int UCHAR_MAX = 255; // TODO, convert to unicode CHAR_MAX?
private static final int LUAI_MAXCCALLS = 200;
@@ -74,7 +74,7 @@ public class LexState extends Constants {
** Marks the end of a patch list. It is an invalid value both as an absolute
** address, and as a list link (would link an element to itself).
*/
static final int NO_JUMP = (-1);
static final int NO_JUMP = -1;
/*
** grep "ORDER OPR" if you change these enums
@@ -102,7 +102,7 @@ public class LexState extends Constants {
private static class SemInfo {
LuaValue r;
LuaString ts;
};
}
private static class Token {
int token;
@@ -113,7 +113,7 @@ public class LexState extends Constants {
this.seminfo.r = other.seminfo.r;
this.seminfo.ts = other.seminfo.ts;
}
};
}
int current; /* current character (charint) */
int linenumber; /* input line counter */
@@ -151,30 +151,30 @@ public class LexState extends Constants {
final static Hashtable RESERVED = new Hashtable();
static {
for (int i = 0; i < NUM_RESERVED; i++) {
LuaString ts = (LuaString) LuaValue.valueOf(luaX_tokens[i]);
RESERVED.put(ts, new Integer(FIRST_RESERVED+i));
LuaString ts = LuaValue.valueOf(luaX_tokens[i]);
RESERVED.put(ts, Integer.valueOf(FIRST_RESERVED+i));
}
}
private boolean isalnum(int c) {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c == '_');
return c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '_';
// return Character.isLetterOrDigit(c);
}
private boolean isalpha(int c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z';
}
private boolean isdigit(int c) {
return (c >= '0' && c <= '9');
return c >= '0' && c <= '9';
}
private boolean isxdigit(int c) {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
return c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F';
}
private boolean isspace(int c) {
return (c >= 0 && c <= ' ');
return c >= 0 && c <= ' ';
}
public LexState(LuaC.CompileState state, InputStream stream) {
@@ -209,8 +209,7 @@ public class LexState extends Constants {
String token2str(int token) {
if (token < FIRST_RESERVED) {
return iscntrl(token)? L.pushfstring("char(" + ((int) token) + ")")
: L.pushfstring(String.valueOf((char) token));
return iscntrl(token)? L.pushfstring("char(" + token + ")"): L.pushfstring(String.valueOf((char) token));
} else {
return luaX_tokens[token-FIRST_RESERVED];
}
@@ -299,7 +298,7 @@ public class LexState extends Constants {
void buffreplace(char from, char to) {
int n = nbuff;
char[] p = buff;
while ( (--n) >= 0 )
while ( --n >= 0 )
if (p[n] == from)
p[n] = to;
}
@@ -316,11 +315,7 @@ public class LexState extends Constants {
++s;
}
/* Check for "0x" */
if (s+2 >= c.length)
return LuaValue.ZERO;
if (c[s++] != '0')
return LuaValue.ZERO;
if (c[s] != 'x' && c[s] != 'X')
if (s+2 >= c.length || c[s++] != '0' || c[s] != 'x' && c[s] != 'X')
return LuaValue.ZERO;
++s;
@@ -328,11 +323,11 @@ public class LexState extends Constants {
double m = 0;
int e = 0;
while ( s < c.length && isxdigit(c[s]) )
m = (m*16)+hexvalue(c[s++]);
m = m*16+hexvalue(c[s++]);
if (s < c.length && c[s] == '.') {
++s; // skip dot
while ( s < c.length && isxdigit(c[s]) ) {
m = (m*16)+hexvalue(c[s++]);
m = m*16+hexvalue(c[s++]);
e -= 4; // Each fractional part shifts right by 2^4
}
}
@@ -396,7 +391,7 @@ public class LexState extends Constants {
save_and_next();
count++;
}
return (current == s)? count: (-count)-1;
return current == s? count: (-count)-1;
}
void read_long_string(SemInfo seminfo, int sep) {
@@ -407,7 +402,7 @@ public class LexState extends Constants {
for (boolean endloop = false; !endloop;) {
switch (current) {
case EOZ:
lexerror((seminfo != null)? "unfinished long string": "unfinished long comment", TK_EOS);
lexerror(seminfo != null? "unfinished long string": "unfinished long comment", TK_EOS);
break; /* to avoid warnings */
case '[': {
if (skip_sep() == sep) {
@@ -462,7 +457,7 @@ public class LexState extends Constants {
nextChar();
int c2 = current;
if (!isxdigit(c1) || !isxdigit(c2))
lexerror("hexadecimal digit expected 'x" + ((char) c1) + ((char) c2), TK_STRING);
lexerror("hexadecimal digit expected 'x" + (char) c1 + (char) c2, TK_STRING);
return (hexvalue(c1)<<4)+hexvalue(c2);
}
@@ -529,7 +524,7 @@ public class LexState extends Constants {
int i = 0;
c = 0;
do {
c = 10*c+(current-'0');
c = 10*c+current-'0';
nextChar();
} while ( ++i < 3 && isdigit(current) );
if (c > UCHAR_MAX)
@@ -724,11 +719,11 @@ public class LexState extends Constants {
// =============================================================
static final boolean vkisvar(final int k) {
return (VLOCAL <= (k) && (k) <= VINDEXED);
return VLOCAL <= k && k <= VINDEXED;
}
static final boolean vkisinreg(final int k) {
return ((k) == VNONRELOC || (k) == VLOCAL);
return k == VNONRELOC || k == VLOCAL;
}
static class expdesc {
@@ -744,9 +739,9 @@ public class LexState extends Constants {
public void setNval(LuaValue r) { _nval = r; }
public LuaValue nval() {
return (_nval == null? LuaInteger.valueOf(info): _nval);
return _nval == null? LuaInteger.valueOf(info): _nval;
}
};
}
final U u = new U();
final IntPtr t = new IntPtr(); /* patch list of `exit when true' */
@@ -760,11 +755,11 @@ public class LexState extends Constants {
}
boolean hasjumps() {
return (t.i != f.i);
return t.i != f.i;
}
boolean isnumeral() {
return (k == VKNUM && t.i == NO_JUMP && f.i == NO_JUMP);
return k == VKNUM && t.i == NO_JUMP && f.i == NO_JUMP;
}
public void setvalue(expdesc other) {
@@ -786,7 +781,7 @@ public class LexState extends Constants {
Vardesc(int idx) {
this.idx = (short) idx;
}
};
}
/* description of pending goto statements and label statements */
static class Labeldesc {
@@ -801,7 +796,7 @@ public class LexState extends Constants {
this.line = line;
this.nactvar = nactvar;
}
};
}
/* dynamic structures used by the parser */
static class Dyndata {
@@ -811,10 +806,10 @@ public class LexState extends Constants {
int n_gt = 0;
Labeldesc[] label; /* list of active labels */
int n_label = 0;
};
}
boolean hasmultret(int k) {
return ((k) == VCALL || (k) == VVARARG);
return k == VCALL || k == VVARARG;
}
/*----------------------------------------------------------------------
@@ -860,7 +855,7 @@ public class LexState extends Constants {
}
void check_condition(boolean c, String msg) {
if (!(c))
if (!c)
syntaxerror(msg);
}
@@ -902,7 +897,7 @@ public class LexState extends Constants {
void new_localvar(LuaString name) {
int reg = registerlocalvar(name);
fs.checklimit(dyd.n_actvar+1, FuncState.LUAI_MAXVARS, "local variables");
fs.checklimit(dyd.n_actvar+1, Constants.LUAI_MAXVARS, "local variables");
if (dyd.actvar == null || dyd.n_actvar+1 > dyd.actvar.length)
dyd.actvar = realloc(dyd.actvar, Math.max(1, dyd.n_actvar*2));
dyd.actvar[dyd.n_actvar++] = new Vardesc(reg);
@@ -1138,7 +1133,7 @@ public class LexState extends Constants {
int nh; /* total number of `record' elements */
int na; /* total number of array elements */
int tostore; /* number of array elements pending to be stored */
};
}
void recfield(ConsControl cc) {
/* recfield -> (NAME | `['exp1`]') = exp1 */
@@ -1219,13 +1214,13 @@ public class LexState extends Constants {
static int luaO_int2fb(int x) {
int e = 0; /* expoent */
while ( x >= 16 ) {
x = (x+1)>>1;
x = x+1>>1;
e++;
}
if (x < 8)
return x;
else
return ((e+1)<<3) | (((int) x)-8);
return e+1<<3 | x-8;
}
/* }====================================================================== */
@@ -1252,7 +1247,7 @@ public class LexState extends Constants {
default:
this.syntaxerror("<name> or " + LUA_QL("...") + " expected");
}
} while ( (f.is_vararg == 0) && this.testnext(',') );
} while ( f.is_vararg == 0 && this.testnext(',') );
}
this.adjustlocalvars(nparams);
f.numparams = fs.nactvar;
@@ -1359,8 +1354,7 @@ public class LexState extends Constants {
return;
}
default: {
this.syntaxerror("unexpected symbol " + t.token + " (" + ((char) t.token) + ")");
return;
this.syntaxerror("unexpected symbol " + t.token + " (" + (char) t.token + ")");
}
}
}
@@ -1513,7 +1507,7 @@ public class LexState extends Constants {
left = (byte) i;
right = (byte) j;
}
};
}
static Priority[] priority = { /* ORDER OPR */
new Priority(6, 6), new Priority(6, 6), new Priority(7, 7), new Priority(7, 7),
@@ -1601,7 +1595,7 @@ public class LexState extends Constants {
LHS_assign prev;
/* variable (global, local, upvalue, or indexed) */
expdesc v = new expdesc();
};
}
/*
** check whether, in an assignment to a local variable, the local variable
@@ -1611,7 +1605,7 @@ public class LexState extends Constants {
*/
void check_conflict(LHS_assign lh, expdesc v) {
FuncState fs = this.fs;
short extra = (short) fs.freereg; /* eventual position to save local variable */
short extra = fs.freereg; /* eventual position to save local variable */
boolean conflict = false;
for (; lh != null; lh = lh.prev) {
if (lh.v.k == VINDEXED) {
@@ -1630,7 +1624,7 @@ public class LexState extends Constants {
}
if (conflict) {
/* copy upvalue/local value to a temporary (in position 'extra') */
int op = (v.k == VLOCAL)? Lua.OP_MOVE: Lua.OP_GETUPVAL;
int op = v.k == VLOCAL? Lua.OP_MOVE: Lua.OP_GETUPVAL;
fs.codeABC(op, extra, v.u.info, 0);
fs.reserveregs(1);
}

View File

@@ -106,10 +106,12 @@ public class LuaC extends Constants implements Globals.Compiler, Globals.Loader
* @return Prototype representing the lua chunk for this source.
* @throws IOException
*/
@Override
public Prototype compile(InputStream stream, String chunkname) throws IOException {
return (new CompileState()).luaY_parser(stream, chunkname);
return new CompileState().luaY_parser(stream, chunkname);
}
@Override
public LuaFunction load(Prototype prototype, String chunkname, LuaValue env) throws IOException {
return new LuaClosure(prototype, env);
}
@@ -119,13 +121,14 @@ public class LuaC extends Constants implements Globals.Compiler, Globals.Loader
* LuaC.compile(InputStream, String) and construct LuaClosure
* directly.
*/
@Deprecated
public LuaValue load(InputStream stream, String chunkname, Globals globals) throws IOException {
return new LuaClosure(compile(stream, chunkname), globals);
}
static class CompileState {
int nCcalls = 0;
private Hashtable strings = new Hashtable();
int nCcalls = 0;
private final Hashtable strings = new Hashtable();
protected CompileState() {}
@@ -135,15 +138,15 @@ public class LuaC extends Constants implements Globals.Compiler, Globals.Loader
FuncState funcstate = new FuncState();
// lexstate.buff = buff;
lexstate.fs = funcstate;
lexstate.setinput(this, z.read(), z, (LuaString) LuaValue.valueOf(name));
lexstate.setinput(this, z.read(), z, LuaValue.valueOf(name));
/* main func. is always vararg */
funcstate.f = new Prototype();
funcstate.f.source = (LuaString) LuaValue.valueOf(name);
funcstate.f.source = LuaValue.valueOf(name);
lexstate.mainfunc(funcstate);
LuaC._assert(funcstate.prev == null);
Constants._assert(funcstate.prev == null);
/* all scopes should be correctly finished */
LuaC._assert(lexstate.dyd == null
|| (lexstate.dyd.n_actvar == 0 && lexstate.dyd.n_gt == 0 && lexstate.dyd.n_label == 0));
Constants._assert(lexstate.dyd == null
|| lexstate.dyd.n_actvar == 0 && lexstate.dyd.n_gt == 0 && lexstate.dyd.n_label == 0);
return funcstate.f;
}

View File

@@ -98,6 +98,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
* @param env the environment to load into, which must be a Globals
* instance.
*/
@Override
public LuaValue call(LuaValue modname, LuaValue env) {
globals = env.checkglobals();
globals.finder = this;
@@ -137,12 +138,14 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
*
* Tries to open the file as a resource, which can work for JSE and JME.
*/
@Override
public InputStream findResource(String filename) {
return getClass().getResourceAsStream(filename.startsWith("/")? filename: "/" + filename);
}
// "assert", // ( v [,message] ) -> v, message | ERR
static final class _assert extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
if (!args.arg1().toboolean())
error(args.narg() > 1? args.optjstring(2, "assertion failed!"): "assertion failed!");
@@ -152,6 +155,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "collectgarbage", // ( opt [,arg] ) -> value
static final class collectgarbage extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
String s = args.optjstring(1, "collect");
if ("collect".equals(s)) {
@@ -173,6 +177,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "dofile", // ( filename ) -> result1, ...
final class dofile extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
args.argcheck(args.isstring(1) || args.isnil(1), 1, "filename must be string or nil");
String filename = args.isstring(1)? args.tojstring(1): null;
@@ -184,6 +189,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "error", // ( message [,level] ) -> ERR
static final class error extends TwoArgFunction {
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2) {
if (arg1.isnil())
throw new LuaError(NIL);
@@ -195,10 +201,12 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "getmetatable", // ( object ) -> table
static final class getmetatable extends LibFunction {
@Override
public LuaValue call() {
return argerror(1, "value expected");
}
@Override
public LuaValue call(LuaValue arg) {
LuaValue mt = arg.getmetatable();
return mt != null? mt.rawget(METATABLE).optvalue(mt): NIL;
@@ -207,6 +215,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "load", // ( ld [, source [, mode [, env]]] ) -> chunk | nil, msg
final class load extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
LuaValue ld = args.arg1();
if (!ld.isstring() && !ld.isfunction()) {
@@ -223,6 +232,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "loadfile", // ( [filename [, mode [, env]]] ) -> chunk | nil, msg
final class loadfile extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
args.argcheck(args.isstring(1) || args.isnil(1), 1, "filename must be string or nil");
String filename = args.isstring(1)? args.tojstring(1): null;
@@ -234,6 +244,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "pcall", // (f, arg1, ...) -> status, result1, ...
final class pcall extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
LuaValue func = args.checkvalue(1);
if (globals != null && globals.debuglib != null)
@@ -261,6 +272,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
this.baselib = baselib;
}
@Override
public Varargs invoke(Varargs args) {
LuaValue tostring = globals.get("tostring");
for (int i = 1, n = args.narg(); i <= n; i++) {
@@ -276,14 +288,17 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "rawequal", // (v1, v2) -> boolean
static final class rawequal extends LibFunction {
@Override
public LuaValue call() {
return argerror(1, "value expected");
}
@Override
public LuaValue call(LuaValue arg) {
return argerror(2, "value expected");
}
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2) {
return valueOf(arg1.raweq(arg2));
}
@@ -291,10 +306,12 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "rawget", // (table, index) -> value
static final class rawget extends TableLibFunction {
@Override
public LuaValue call(LuaValue arg) {
return argerror(2, "value expected");
}
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2) {
return arg1.checktable().rawget(arg2);
}
@@ -302,6 +319,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "rawlen", // (v) -> value
static final class rawlen extends LibFunction {
@Override
public LuaValue call(LuaValue arg) {
return valueOf(arg.rawlen());
}
@@ -309,14 +327,17 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "rawset", // (table, index, value) -> table
static final class rawset extends TableLibFunction {
@Override
public LuaValue call(LuaValue table) {
return argerror(2, "value expected");
}
@Override
public LuaValue call(LuaValue table, LuaValue index) {
return argerror(3, "value expected");
}
@Override
public LuaValue call(LuaValue table, LuaValue index, LuaValue value) {
LuaTable t = table.checktable();
if (!index.isvalidkey())
@@ -328,6 +349,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "select", // (f, ...) -> value1, ...
static final class select extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
int n = args.narg()-1;
if (args.arg1().equals(valueOf("#")))
@@ -341,10 +363,12 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "setmetatable", // (table, metatable) -> table
static final class setmetatable extends TableLibFunction {
@Override
public LuaValue call(LuaValue table) {
return argerror(2, "nil or table expected");
}
@Override
public LuaValue call(LuaValue table, LuaValue metatable) {
final LuaValue mt0 = table.checktable().getmetatable();
if (mt0 != null && !mt0.rawget(METATABLE).isnil())
@@ -355,10 +379,12 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "tonumber", // (e [,base]) -> value
static final class tonumber extends LibFunction {
@Override
public LuaValue call(LuaValue e) {
return e.tonumber();
}
@Override
public LuaValue call(LuaValue e, LuaValue base) {
if (base.isnil())
return e.tonumber();
@@ -371,6 +397,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "tostring", // (e) -> value
static final class tostring extends LibFunction {
@Override
public LuaValue call(LuaValue arg) {
LuaValue h = arg.metatag(TOSTRING);
if (!h.isnil())
@@ -384,6 +411,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "type", // (v) -> value
static final class type extends LibFunction {
@Override
public LuaValue call(LuaValue arg) {
return valueOf(arg.typename());
}
@@ -391,6 +419,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "xpcall", // (f, err) -> result1, ...
final class xpcall extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
final LuaThread t = globals.running;
final LuaValue preverror = t.errorfunc;
@@ -424,6 +453,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
this.next = next;
}
@Override
public Varargs invoke(Varargs args) {
return varargsOf(next, args.checktable(1), NIL);
}
@@ -433,6 +463,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
static final class ipairs extends VarArgFunction {
inext inext = new inext();
@Override
public Varargs invoke(Varargs args) {
return varargsOf(inext, args.checktable(1), ZERO);
}
@@ -440,6 +471,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "next" ( table, [index] ) -> next-index, next-value
static final class next extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
return args.checktable(1).next(args.arg(2));
}
@@ -447,6 +479,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
// "inext" ( table, [int-index] ) -> next-index, next-value
static final class inext extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
return args.checktable(1).inext(args.arg(2));
}
@@ -493,6 +526,7 @@ public class BaseLib extends TwoArgFunction implements ResourceFinder {
this.func = func;
}
@Override
public int read() throws IOException {
if (remaining < 0)
return -1;

View File

@@ -79,6 +79,7 @@ public class Bit32Lib extends TwoArgFunction {
* @param env the environment to load into, which must be a Globals
* instance.
*/
@Override
public LuaValue call(LuaValue modname, LuaValue env) {
LuaTable t = new LuaTable();
bind(t, Bit32LibV.class, new String[] { "band", "bnot", "bor", "btest", "bxor", "extract", "replace" });
@@ -90,6 +91,7 @@ public class Bit32Lib extends TwoArgFunction {
}
static final class Bit32LibV extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
switch (opcode) {
case 0:
@@ -113,6 +115,7 @@ public class Bit32Lib extends TwoArgFunction {
static final class Bit32Lib2 extends TwoArgFunction {
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2) {
switch (opcode) {
case 0:
@@ -200,7 +203,7 @@ public class Bit32Lib extends TwoArgFunction {
return rrotate(x, -disp);
} else {
disp = disp & 31;
return bitsToValue((x<<disp) | (x>>>(32-disp)));
return bitsToValue(x<<disp | x>>>32-disp);
}
}
@@ -209,7 +212,7 @@ public class Bit32Lib extends TwoArgFunction {
return lrotate(x, -disp);
} else {
disp = disp & 31;
return bitsToValue((x>>>disp) | (x<<(32-disp)));
return bitsToValue(x>>>disp | x<<32-disp);
}
}
@@ -223,7 +226,7 @@ public class Bit32Lib extends TwoArgFunction {
if (field+width > 32) {
error("trying to access non-existent bits");
}
return bitsToValue((n>>>field) & (-1>>>(32-width)));
return bitsToValue(n>>>field & -1>>>32-width);
}
static LuaValue replace(int n, int v, int field, int width) {
@@ -236,12 +239,12 @@ public class Bit32Lib extends TwoArgFunction {
if (field+width > 32) {
error("trying to access non-existent bits");
}
int mask = (-1>>>(32-width))<<field;
n = (n & ~mask) | ((v<<field) & mask);
int mask = -1>>>32-width<<field;
n = n & ~mask | v<<field & mask;
return bitsToValue(n);
}
private static LuaValue bitsToValue(int x) {
return (x < 0)? valueOf((double) ((long) x & 0xFFFFFFFFL)): valueOf(x);
return x < 0? valueOf(x & 0xFFFFFFFFL): valueOf(x);
}
}

View File

@@ -87,6 +87,7 @@ public class CoroutineLib extends TwoArgFunction {
* @param env the environment to load into, which must be a Globals
* instance.
*/
@Override
public LuaValue call(LuaValue modname, LuaValue env) {
globals = env.checkglobals();
LuaTable coroutine = new LuaTable();
@@ -103,12 +104,14 @@ public class CoroutineLib extends TwoArgFunction {
}
final class create extends LibFunction {
@Override
public LuaValue call(LuaValue f) {
return new LuaThread(globals, f.checkfunction());
}
}
static final class resume extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
final LuaThread t = args.checkthread(1);
return t.resume(args.subargs(2));
@@ -116,6 +119,7 @@ public class CoroutineLib extends TwoArgFunction {
}
final class running extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
final LuaThread r = globals.running;
return varargsOf(r, valueOf(r.isMainThread()));
@@ -123,6 +127,7 @@ public class CoroutineLib extends TwoArgFunction {
}
static final class status extends LibFunction {
@Override
public LuaValue call(LuaValue t) {
LuaThread lt = t.checkthread();
return valueOf(lt.getStatus());
@@ -130,12 +135,14 @@ public class CoroutineLib extends TwoArgFunction {
}
final class yield extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
return globals.yield(args);
}
}
final class wrap extends LibFunction {
@Override
public LuaValue call(LuaValue f) {
final LuaValue func = f.checkfunction();
final LuaThread thread = new LuaThread(globals, func);
@@ -150,6 +157,7 @@ public class CoroutineLib extends TwoArgFunction {
this.luathread = luathread;
}
@Override
public Varargs invoke(Varargs args) {
final Varargs result = luathread.resume(args);
if (result.arg1().toboolean()) {

View File

@@ -90,11 +90,11 @@ public class DebugLib extends TwoArgFunction {
public static boolean TRACE;
static {
try {
CALLS = (null != System.getProperty("CALLS"));
CALLS = null != System.getProperty("CALLS");
} catch (Exception e) {
}
try {
TRACE = (null != System.getProperty("TRACE"));
TRACE = null != System.getProperty("TRACE");
} catch (Exception e) {
}
}
@@ -133,6 +133,7 @@ public class DebugLib extends TwoArgFunction {
* @param env the environment to load into, which must be a Globals
* instance.
*/
@Override
public LuaValue call(LuaValue modname, LuaValue env) {
globals = env.checkglobals();
globals.debuglib = this;
@@ -161,6 +162,7 @@ public class DebugLib extends TwoArgFunction {
// debug.debug()
static final class debug extends ZeroArgFunction {
@Override
public LuaValue call() {
return NONE;
}
@@ -168,6 +170,7 @@ public class DebugLib extends TwoArgFunction {
// debug.gethook ([thread])
final class gethook extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
LuaThread t = args.narg() > 0? args.checkthread(1): globals.running;
LuaThread.State s = t.state;
@@ -178,6 +181,7 @@ public class DebugLib extends TwoArgFunction {
// debug.getinfo ([thread,] f [, what])
final class getinfo extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
int a = 1;
LuaThread thread = args.isthread(a)? args.checkthread(a++): globals.running;
@@ -241,6 +245,7 @@ public class DebugLib extends TwoArgFunction {
// debug.getlocal ([thread,] f, local)
final class getlocal extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
int a = 1;
LuaThread thread = args.isthread(a)? args.checkthread(a++): globals.running;
@@ -253,6 +258,7 @@ public class DebugLib extends TwoArgFunction {
// debug.getmetatable (value)
static final class getmetatable extends LibFunction {
@Override
public LuaValue call(LuaValue v) {
LuaValue mt = v.getmetatable();
return mt != null? mt: NIL;
@@ -261,6 +267,7 @@ public class DebugLib extends TwoArgFunction {
// debug.getregistry ()
final class getregistry extends ZeroArgFunction {
@Override
public LuaValue call() {
return globals;
}
@@ -268,6 +275,7 @@ public class DebugLib extends TwoArgFunction {
// debug.getupvalue (f, up)
static final class getupvalue extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
LuaValue func = args.checkfunction(1);
int up = args.checkint(2);
@@ -284,6 +292,7 @@ public class DebugLib extends TwoArgFunction {
// debug.getuservalue (u)
static final class getuservalue extends LibFunction {
@Override
public LuaValue call(LuaValue u) {
return u.isuserdata()? u: NIL;
}
@@ -291,6 +300,7 @@ public class DebugLib extends TwoArgFunction {
// debug.sethook ([thread,] hook, mask [, count])
final class sethook extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
int a = 1;
LuaThread t = args.isthread(a)? args.checkthread(a++): globals.running;
@@ -322,6 +332,7 @@ public class DebugLib extends TwoArgFunction {
// debug.setlocal ([thread,] level, local, value)
final class setlocal extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
int a = 1;
LuaThread thread = args.isthread(a)? args.checkthread(a++): globals.running;
@@ -335,6 +346,7 @@ public class DebugLib extends TwoArgFunction {
// debug.setmetatable (value, table)
static final class setmetatable extends TwoArgFunction {
@Override
public LuaValue call(LuaValue value, LuaValue table) {
LuaValue mt = table.opttable(null);
switch (value.type()) {
@@ -365,6 +377,7 @@ public class DebugLib extends TwoArgFunction {
// debug.setupvalue (f, up, value)
static final class setupvalue extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
LuaValue func = args.checkfunction(1);
int up = args.checkint(2);
@@ -383,6 +396,7 @@ public class DebugLib extends TwoArgFunction {
// debug.setuservalue (udata, value)
static final class setuservalue extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
Object o = args.checkuserdata(1);
LuaValue v = args.checkvalue(2);
@@ -395,6 +409,7 @@ public class DebugLib extends TwoArgFunction {
// debug.traceback ([thread,] [message [, level]])
final class traceback extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
int a = 1;
LuaThread thread = args.isthread(a)? args.checkthread(a++): globals.running;
@@ -407,6 +422,7 @@ public class DebugLib extends TwoArgFunction {
// debug.upvalueid (f, n)
static final class upvalueid extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
LuaValue func = args.checkfunction(1);
int up = args.checkint(2);
@@ -422,6 +438,7 @@ public class DebugLib extends TwoArgFunction {
// debug.upvaluejoin (f1, n1, f2, n2)
static final class upvaluejoin extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
LuaClosure f1 = args.checkclosure(1);
int n1 = args.checkint(2);
@@ -536,7 +553,7 @@ public class DebugLib extends TwoArgFunction {
this.source = p.source != null? p.source.tojstring(): "=?";
this.linedefined = p.linedefined;
this.lastlinedefined = p.lastlinedefined;
this.what = (this.linedefined == 0)? "main": "Lua";
this.what = this.linedefined == 0? "main": "Lua";
this.short_src = p.shortsource();
} else {
this.source = "=[Java]";
@@ -886,9 +903,9 @@ public class DebugLib extends TwoArgFunction {
case Lua.OP_GETTABLE: {
int k = Lua.GETARG_C(i); /* key index */
int t = Lua.GETARG_B(i); /* table index */
LuaString vn = (Lua.GET_OPCODE(i) == Lua.OP_GETTABLE) /* name of indexed variable */
LuaString vn = Lua.GET_OPCODE(i) == Lua.OP_GETTABLE /* name of indexed variable */
? p.getlocalname(t+1, pc)
: (t < p.upvalues.length? p.upvalues[t].name: QMARK);
: t < p.upvalues.length? p.upvalues[t].name: QMARK;
String jname = kname(p, pc, k);
return new NameWhat(jname, vn != null && vn.eq_b(ENV)? "global": "field");
}
@@ -899,7 +916,7 @@ public class DebugLib extends TwoArgFunction {
}
case Lua.OP_LOADK:
case Lua.OP_LOADKX: {
int b = (Lua.GET_OPCODE(i) == Lua.OP_LOADK)? Lua.GETARG_Bx(i): Lua.GETARG_Ax(p.code[pc+1]);
int b = Lua.GET_OPCODE(i) == Lua.OP_LOADK? Lua.GETARG_Bx(i): Lua.GETARG_Ax(p.code[pc+1]);
if (p.k[b].isstring()) {
name = p.k[b].strvalue();
return new NameWhat(name.tojstring(), "constant");
@@ -976,7 +993,7 @@ public class DebugLib extends TwoArgFunction {
break;
}
case Lua.OP_SETLIST: { // Lua.testAMode(Lua.OP_SETLIST) == false
if (((i>>14) & 0x1ff) == 0)
if ((i>>14 & 0x1ff) == 0)
pc++; // if c == 0 then c stored in next op -> skip
break;
}

View File

@@ -86,35 +86,35 @@ import org.luaj.vm2.Varargs;
* @see <a href=
* "http://www.lua.org/manual/5.1/manual.html#5.7">http://www.lua.org/manual/5.1/manual.html#5.7</a>
*/
abstract public class IoLib extends TwoArgFunction {
public abstract class IoLib extends TwoArgFunction {
abstract protected class File extends LuaValue {
abstract public void write(LuaString string) throws IOException;
protected abstract class File extends LuaValue {
public abstract void write(LuaString string) throws IOException;
abstract public void flush() throws IOException;
public abstract void flush() throws IOException;
abstract public boolean isstdfile();
public abstract boolean isstdfile();
abstract public void close() throws IOException;
public abstract void close() throws IOException;
abstract public boolean isclosed();
public abstract boolean isclosed();
// returns new position
abstract public int seek(String option, int bytecount) throws IOException;
public abstract int seek(String option, int bytecount) throws IOException;
abstract public void setvbuf(String mode, int size);
public abstract void setvbuf(String mode, int size);
// get length remaining to read
abstract public int remaining() throws IOException;
public abstract int remaining() throws IOException;
// peek ahead one character
abstract public int peek() throws IOException, EOFException;
public abstract int peek() throws IOException, EOFException;
// return char if read, -1 if eof, throw IOException on other exception
abstract public int read() throws IOException, EOFException;
public abstract int read() throws IOException, EOFException;
// return number of bytes read if positive, false if eof, throw IOException on other exception
abstract public int read(byte[] bytes, int offset, int length) throws IOException;
public abstract int read(byte[] bytes, int offset, int length) throws IOException;
public boolean eof() throws IOException {
try {
@@ -125,24 +125,29 @@ abstract public class IoLib extends TwoArgFunction {
}
// delegate method access to file methods table
@Override
public LuaValue get(LuaValue key) {
return filemethods.get(key);
}
// essentially a userdata instance
@Override
public int type() {
return LuaValue.TUSERDATA;
}
@Override
public String typename() {
return "userdata";
}
// displays as "file" type
@Override
public String tojstring() {
return "file: " + Integer.toHexString(hashCode());
}
@Override
public void finalize() {
if (!isclosed()) {
try {
@@ -260,6 +265,7 @@ abstract public class IoLib extends TwoArgFunction {
protected Globals globals;
@Override
public LuaValue call(LuaValue modname, LuaValue env) {
globals = env.checkglobals();
@@ -310,13 +316,13 @@ abstract public class IoLib extends TwoArgFunction {
}
public IoLibV(File f, String name, int opcode, IoLib iolib) {
super();
this.f = f;
this.name = name;
this.opcode = opcode;
this.iolib = iolib;
}
@Override
public Varargs invoke(Varargs args) {
try {
switch (opcode) {
@@ -630,9 +636,7 @@ abstract public class IoLib extends TwoArgFunction {
int len = mode.length();
for (int i = 0; i < len; i++) { // [rwa][+]?b*
char ch = mode.charAt(i);
if (i == 0 && "rwa".indexOf(ch) >= 0)
continue;
if (i == 1 && ch == '+')
if ((i == 0 && "rwa".indexOf(ch) >= 0) || (i == 1 && ch == '+'))
continue;
if (i >= 1 && ch == 'b')
continue;

View File

@@ -152,6 +152,7 @@ abstract public class LibFunction extends LuaFunction {
protected LibFunction() {
}
@Override
public String tojstring() {
return name != null? "function: " + name: super.tojstring();
}
@@ -220,18 +221,22 @@ abstract public class LibFunction extends LuaFunction {
return new LuaValue[] { v };
}
@Override
public LuaValue call() {
return argerror(1, "value expected");
}
@Override
public LuaValue call(LuaValue a) {
return call();
}
@Override
public LuaValue call(LuaValue a, LuaValue b) {
return call(a);
}
@Override
public LuaValue call(LuaValue a, LuaValue b, LuaValue c) {
return call(a, b);
}
@@ -240,6 +245,7 @@ abstract public class LibFunction extends LuaFunction {
return call(a, b, c);
}
@Override
public Varargs invoke(Varargs args) {
switch (args.narg()) {
case 0:

View File

@@ -121,6 +121,7 @@ public class MathLib extends TwoArgFunction {
* @param env the environment to load into, typically a Globals
* instance.
*/
@Override
public LuaValue call(LuaValue modname, LuaValue env) {
LuaTable math = new LuaTable(0, 30);
math.set("abs", new abs());
@@ -152,6 +153,7 @@ public class MathLib extends TwoArgFunction {
}
abstract protected static class UnaryOp extends OneArgFunction {
@Override
public LuaValue call(LuaValue arg) {
return valueOf(call(arg.checkdouble()));
}
@@ -160,6 +162,7 @@ public class MathLib extends TwoArgFunction {
}
abstract protected static class BinaryOp extends TwoArgFunction {
@Override
public LuaValue call(LuaValue x, LuaValue y) {
return valueOf(call(x.checkdouble(), y.checkdouble()));
}
@@ -168,38 +171,47 @@ public class MathLib extends TwoArgFunction {
}
static final class abs extends UnaryOp {
@Override
protected double call(double d) { return Math.abs(d); }
}
static final class ceil extends UnaryOp {
@Override
protected double call(double d) { return Math.ceil(d); }
}
static final class cos extends UnaryOp {
@Override
protected double call(double d) { return Math.cos(d); }
}
static final class deg extends UnaryOp {
@Override
protected double call(double d) { return Math.toDegrees(d); }
}
static final class floor extends UnaryOp {
@Override
protected double call(double d) { return Math.floor(d); }
}
static final class rad extends UnaryOp {
@Override
protected double call(double d) { return Math.toRadians(d); }
}
static final class sin extends UnaryOp {
@Override
protected double call(double d) { return Math.sin(d); }
}
static final class sqrt extends UnaryOp {
@Override
protected double call(double d) { return Math.sqrt(d); }
}
static final class tan extends UnaryOp {
@Override
protected double call(double d) { return Math.tan(d); }
}
@@ -210,12 +222,14 @@ public class MathLib extends TwoArgFunction {
this.mathlib = mathlib;
}
@Override
protected double call(double d) {
return mathlib.dpow_lib(Math.E, d);
}
}
static final class fmod extends TwoArgFunction {
@Override
public LuaValue call(LuaValue xv, LuaValue yv) {
if (xv.islong() && yv.islong()) {
return valueOf(xv.tolong()%yv.tolong());
@@ -225,31 +239,35 @@ public class MathLib extends TwoArgFunction {
}
static final class ldexp extends BinaryOp {
@Override
protected double call(double x, double y) {
// This is the behavior on os-x, windows differs in rounding behavior.
return x*Double.longBitsToDouble((((long) y)+1023)<<52);
return x*Double.longBitsToDouble((long) y+1023<<52);
}
}
static final class pow extends BinaryOp {
@Override
protected double call(double x, double y) {
return MathLib.dpow_default(x, y);
}
}
static class frexp extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
double x = args.checkdouble(1);
if (x == 0)
return varargsOf(ZERO, ZERO);
long bits = Double.doubleToLongBits(x);
double m = ((bits & (~(-1L<<52)))+(1L<<52))*((bits >= 0)? (.5/(1L<<52)): (-.5/(1L<<52)));
double e = (((int) (bits>>52)) & 0x7ff)-1022;
double m = ((bits & ~(-1L<<52))+(1L<<52))*(bits >= 0? .5/(1L<<52): -.5/(1L<<52));
double e = ((int) (bits>>52) & 0x7ff)-1022;
return varargsOf(valueOf(m), valueOf(e));
}
}
static class max extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
LuaValue m = args.checkvalue(1);
for (int i = 2, n = args.narg(); i <= n; ++i) {
@@ -262,6 +280,7 @@ public class MathLib extends TwoArgFunction {
}
static class min extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
LuaValue m = args.checkvalue(1);
for (int i = 2, n = args.narg(); i <= n; ++i) {
@@ -274,6 +293,7 @@ public class MathLib extends TwoArgFunction {
}
static class modf extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
LuaValue n = args.arg1();
/* number is its own integer part, no fractional part */
@@ -281,7 +301,7 @@ public class MathLib extends TwoArgFunction {
return varargsOf(n, valueOf(0.0));
double x = n.checkdouble();
/* integer part (rounds toward zero) */
double intPart = (x > 0)? Math.floor(x): Math.ceil(x);
double intPart = x > 0? Math.floor(x): Math.ceil(x);
/* fractional part (test needed for inf/-inf) */
double fracPart = x == intPart? 0.0: x-intPart;
return varargsOf(valueOf(intPart), valueOf(fracPart));
@@ -291,10 +311,12 @@ public class MathLib extends TwoArgFunction {
static class random extends LibFunction {
Random random = new Random();
@Override
public LuaValue call() {
return valueOf(random.nextDouble());
}
@Override
public LuaValue call(LuaValue a) {
int m = a.checkint();
if (m < 1)
@@ -302,6 +324,7 @@ public class MathLib extends TwoArgFunction {
return valueOf(1+random.nextInt(m));
}
@Override
public LuaValue call(LuaValue a, LuaValue b) {
int m = a.checkint();
int n = b.checkint();
@@ -319,6 +342,7 @@ public class MathLib extends TwoArgFunction {
this.random = random;
}
@Override
public LuaValue call(LuaValue arg) {
long seed = arg.checklong();
random.random = new Random(seed);

View File

@@ -50,24 +50,29 @@ import org.luaj.vm2.Varargs;
*/
abstract public class OneArgFunction extends LibFunction {
@Override
abstract public LuaValue call(LuaValue arg);
/** Default constructor */
public OneArgFunction() {
}
@Override
public final LuaValue call() {
return call(NIL);
}
@Override
public final LuaValue call(LuaValue arg1, LuaValue arg2) {
return call(arg1);
}
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) {
return call(arg1);
}
@Override
public Varargs invoke(Varargs varargs) {
return call(varargs.arg1());
}

View File

@@ -132,6 +132,7 @@ public class OsLib extends TwoArgFunction {
* @param env the environment to load into, typically a Globals
* instance.
*/
@Override
public LuaValue call(LuaValue modname, LuaValue env) {
globals = env.checkglobals();
LuaTable os = new LuaTable();
@@ -149,6 +150,7 @@ public class OsLib extends TwoArgFunction {
this.name = name;
}
@Override
public Varargs invoke(Varargs args) {
try {
switch (opcode) {
@@ -297,7 +299,7 @@ public class OsLib extends TwoArgFunction {
result.append(String.valueOf(100+d.get(Calendar.HOUR_OF_DAY)).substring(1));
break;
case 'I':
result.append(String.valueOf(100+(d.get(Calendar.HOUR_OF_DAY)%12)).substring(1));
result.append(String.valueOf(100+d.get(Calendar.HOUR_OF_DAY)%12).substring(1));
break;
case 'j': { // day of year.
Calendar y0 = beginningOfYear(d);
@@ -525,7 +527,7 @@ public class OsLib extends TwoArgFunction {
*/
protected String tmpname() {
synchronized (OsLib.class) {
return TMP_PREFIX+(tmpnames++)+TMP_SUFFIX;
return TMP_PREFIX+tmpnames+++TMP_SUFFIX;
}
}
}

View File

@@ -22,6 +22,7 @@
package org.luaj.vm2.lib;
import java.io.InputStream;
import java.nio.file.FileSystems;
import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaFunction;
@@ -142,7 +143,7 @@ public class PackageLib extends TwoArgFunction {
private static final LuaString _SENTINEL = valueOf("\u0001");
private static final String FILE_SEP = System.getProperty("file.separator");
private static final String FILE_SEP = FileSystems.getDefault().getSeparator();
public PackageLib() {}
@@ -156,6 +157,7 @@ public class PackageLib extends TwoArgFunction {
* @param env the environment to load into, typically a Globals
* instance.
*/
@Override
public LuaValue call(LuaValue modname, LuaValue env) {
globals = env.checkglobals();
globals.set("require", new require());
@@ -190,6 +192,7 @@ public class PackageLib extends TwoArgFunction {
package_.set(_PATH, LuaValue.valueOf(newLuaPath));
}
@Override
public String tojstring() {
return "package";
}
@@ -229,6 +232,7 @@ public class PackageLib extends TwoArgFunction {
* any loader for the module, then require raises an error.
*/
public class require extends OneArgFunction {
@Override
public LuaValue call(LuaValue arg) {
LuaString name = arg.checkstring();
LuaValue loaded = package_.get(_LOADED);
@@ -269,6 +273,7 @@ public class PackageLib extends TwoArgFunction {
}
public static class loadlib extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
args.checkstring(1);
return varargsOf(NIL, valueOf("dynamic libraries not enabled"), valueOf("absent"));
@@ -276,6 +281,7 @@ public class PackageLib extends TwoArgFunction {
}
public class preload_searcher extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
LuaString name = args.checkstring(1);
LuaValue val = package_.get(_PRELOAD).get(name);
@@ -284,6 +290,7 @@ public class PackageLib extends TwoArgFunction {
}
public class lua_searcher extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
LuaString name = args.checkstring(1);
@@ -311,6 +318,7 @@ public class PackageLib extends TwoArgFunction {
}
public class searchpath extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
String name = args.checkjstring(1);
String path = args.checkjstring(2);
@@ -358,6 +366,7 @@ public class PackageLib extends TwoArgFunction {
}
public class java_searcher extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
String name = args.checkjstring(1);
String classname = toClassname(name);
@@ -385,11 +394,11 @@ public class PackageLib extends TwoArgFunction {
j -= 4;
for (int k = 0; k < j; k++) {
char c = filename.charAt(k);
if ((!isClassnamePart(c)) || (c == '/') || (c == '\\')) {
if (!isClassnamePart(c) || c == '/' || c == '\\') {
StringBuffer sb = new StringBuffer(j);
for (int i = 0; i < j; i++) {
c = filename.charAt(i);
sb.append((isClassnamePart(c))? c: ((c == '/') || (c == '\\'))? '.': '_');
sb.append(isClassnamePart(c)? c: c == '/' || c == '\\'? '.': '_');
}
return sb.toString();
}
@@ -398,7 +407,7 @@ public class PackageLib extends TwoArgFunction {
}
private static final boolean isClassnamePart(char c) {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9')
return true;
switch (c) {
case '.':

View File

@@ -56,5 +56,5 @@ public interface ResourceFinder {
* @param filename
* @return InputStream, or null if not found.
*/
public InputStream findResource(String filename);
InputStream findResource(String filename);
}

View File

@@ -98,6 +98,7 @@ public class StringLib extends TwoArgFunction {
* @param env the environment to load into, typically a Globals
* instance.
*/
@Override
public LuaValue call(LuaValue modname, LuaValue env) {
LuaTable string = new LuaTable();
string.set("byte", new _byte());
@@ -135,6 +136,7 @@ public class StringLib extends TwoArgFunction {
* @param args the calling args
*/
static final class _byte extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
LuaString s = args.checkstring(1);
int l = s.m_length;
@@ -147,7 +149,7 @@ public class StringLib extends TwoArgFunction {
pose = l;
if (posi > pose)
return NONE; /* empty interval; return no values */
n = (int) (pose-posi+1);
n = pose-posi+1;
if (posi+n <= pose) /* overflow? */
error("string slice too long");
LuaValue[] v = new LuaValue[n];
@@ -169,6 +171,7 @@ public class StringLib extends TwoArgFunction {
* @param args the calling VM
*/
static final class _char extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
int n = args.narg();
byte[] bytes = new byte[n];
@@ -194,6 +197,7 @@ public class StringLib extends TwoArgFunction {
* TODO: port dumping code as optional add-on
*/
static final class dump extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
LuaValue f = args.checkfunction(1);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
@@ -222,6 +226,7 @@ public class StringLib extends TwoArgFunction {
* values are also returned, after the two indices.
*/
static final class find extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
return str_find_aux(args, true);
}
@@ -250,6 +255,7 @@ public class StringLib extends TwoArgFunction {
* except as arguments to the q option.
*/
final class format extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
LuaString fmt = args.checkstring(1);
final int n = fmt.length();
@@ -375,7 +381,7 @@ public class StringLib extends TwoArgFunction {
boolean moreFlags = true;
while ( moreFlags ) {
switch (c = ((p < n)? strfrmt.luaByte(p++): 0)) {
switch (c = p < n? strfrmt.luaByte(p++): 0) {
case '-':
leftAdjust = true;
break;
@@ -402,22 +408,22 @@ public class StringLib extends TwoArgFunction {
width = -1;
if (Character.isDigit((char) c)) {
width = c-'0';
c = ((p < n)? strfrmt.luaByte(p++): 0);
c = p < n? strfrmt.luaByte(p++): 0;
if (Character.isDigit((char) c)) {
width = width*10+(c-'0');
c = ((p < n)? strfrmt.luaByte(p++): 0);
width = width*10+c-'0';
c = p < n? strfrmt.luaByte(p++): 0;
}
}
precision = -1;
if (c == '.') {
c = ((p < n)? strfrmt.luaByte(p++): 0);
c = p < n? strfrmt.luaByte(p++): 0;
if (Character.isDigit((char) c)) {
precision = c-'0';
c = ((p < n)? strfrmt.luaByte(p++): 0);
c = p < n? strfrmt.luaByte(p++): 0;
if (Character.isDigit((char) c)) {
precision = precision*10+(c-'0');
c = ((p < n)? strfrmt.luaByte(p++): 0);
precision = precision*10+c-'0';
c = p < n? strfrmt.luaByte(p++): 0;
}
}
}
@@ -544,6 +550,7 @@ public class StringLib extends TwoArgFunction {
* anchor, as this would prevent the iteration.
*/
static final class gmatch extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
LuaString src = args.checkstring(1);
LuaString pat = args.checkstring(2);
@@ -564,6 +571,7 @@ public class StringLib extends TwoArgFunction {
this.lastmatch = -1;
}
@Override
public Varargs invoke(Varargs args) {
for (; soffset <= srclen; soffset++) {
ms.reset();
@@ -624,6 +632,7 @@ public class StringLib extends TwoArgFunction {
* string.gsub("$name-$version.tar.gz", "%$(%w+)", t) --> x="lua-5.1.tar.gz"
*/
static final class gsub extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
LuaString src = args.checkstring(1);
final int srclen = src.length();
@@ -664,6 +673,7 @@ public class StringLib extends TwoArgFunction {
* 0. Embedded zeros are counted, so "a\000bc\000" has length 5.
*/
static final class len extends OneArgFunction {
@Override
public LuaValue call(LuaValue arg) {
return arg.checkstring().len();
}
@@ -678,6 +688,7 @@ public class StringLib extends TwoArgFunction {
* locale.
*/
static final class lower extends OneArgFunction {
@Override
public LuaValue call(LuaValue arg) {
return valueOf(arg.checkjstring().toLowerCase());
}
@@ -693,6 +704,7 @@ public class StringLib extends TwoArgFunction {
* search; its default value is 1 and may be negative.
*/
static final class match extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
return str_find_aux(args, false);
}
@@ -704,6 +716,7 @@ public class StringLib extends TwoArgFunction {
* Returns a string that is the concatenation of n copies of the string s.
*/
static final class rep extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
LuaString s = args.checkstring(1);
int n = args.checkint(2);
@@ -722,6 +735,7 @@ public class StringLib extends TwoArgFunction {
* Returns a string that is the string s reversed.
*/
static final class reverse extends OneArgFunction {
@Override
public LuaValue call(LuaValue arg) {
LuaString s = arg.checkstring();
int n = s.length();
@@ -742,6 +756,7 @@ public class StringLib extends TwoArgFunction {
* -i) returns a suffix of s with length i.
*/
static final class sub extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
final LuaString s = args.checkstring(1);
final int l = s.length();
@@ -771,6 +786,7 @@ public class StringLib extends TwoArgFunction {
* locale.
*/
static final class upper extends OneArgFunction {
@Override
public LuaValue call(LuaValue arg) {
return valueOf(arg.checkjstring().toUpperCase());
}
@@ -824,7 +840,7 @@ public class StringLib extends TwoArgFunction {
}
static int posrelat(int pos, int len) {
return (pos >= 0)? pos: len+pos+1;
return pos >= 0? pos: len+pos+1;
}
// Pattern matching implementation
@@ -856,11 +872,11 @@ public class StringLib extends TwoArgFunction {
final char c = (char) i;
CHAR_TABLE[i] = (byte) ((Character.isDigit(c)? MASK_DIGIT: 0)
| (Character.isLowerCase(c)? MASK_LOWERCASE: 0) | (Character.isUpperCase(c)? MASK_UPPERCASE: 0)
| ((c < ' ' || c == 0x7F)? MASK_CONTROL: 0));
if ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') || (c >= '0' && c <= '9')) {
| (c < ' ' || c == 0x7F? MASK_CONTROL: 0));
if (c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F' || c >= '0' && c <= '9') {
CHAR_TABLE[i] |= MASK_HEXDIGIT;
}
if ((c >= '!' && c <= '/') || (c >= ':' && c <= '@') || (c >= '[' && c <= '`') || (c >= '{' && c <= '~')) {
if (c >= '!' && c <= '/' || c >= ':' && c <= '@' || c >= '[' && c <= '`' || c >= '{' && c <= '~') {
CHAR_TABLE[i] |= MASK_PUNCT;
}
if ((CHAR_TABLE[i] & (MASK_LOWERCASE | MASK_UPPERCASE)) != 0) {
@@ -874,7 +890,7 @@ public class StringLib extends TwoArgFunction {
CHAR_TABLE['\t'] |= MASK_SPACE;
CHAR_TABLE[0x0B /* '\v' */ ] |= MASK_SPACE;
CHAR_TABLE['\f'] |= MASK_SPACE;
};
}
static class MatchState {
int matchdepth; /* control for recursive depth (to avoid C stack overflow) */
@@ -905,7 +921,7 @@ public class StringLib extends TwoArgFunction {
for (int i = 0; i < l; ++i) {
byte b = (byte) news.luaByte(i);
if (b != L_ESC) {
lbuf.append((byte) b);
lbuf.append(b);
} else {
++i; // skip ESC
b = (byte) (i < l? news.luaByte(i): 0);
@@ -955,7 +971,7 @@ public class StringLib extends TwoArgFunction {
}
Varargs push_captures(boolean wholeMatch, int soff, int end) {
int nlevels = (this.level == 0 && wholeMatch)? 1: this.level;
int nlevels = this.level == 0 && wholeMatch? 1: this.level;
switch (nlevels) {
case 0:
return NONE;
@@ -1067,12 +1083,12 @@ public class StringLib extends TwoArgFunction {
res = (cdata & MASK_HEXDIGIT) != 0;
break;
case 'z':
res = (c == 0);
res = c == 0;
break; /* deprecated option */
default:
return cl == c;
}
return (lcl == cl)? res: !res;
return lcl == cl == res;
}
boolean matchbracketclass(int c, int poff, int ec) {
@@ -1086,7 +1102,7 @@ public class StringLib extends TwoArgFunction {
poff++;
if (match_class(c, p.luaByte(poff)))
return sig;
} else if ((p.luaByte(poff+1) == '-') && (poff+2 < ec)) {
} else if (p.luaByte(poff+1) == '-' && poff+2 < ec) {
poff += 2;
if (p.luaByte(poff-2) <= c && c <= p.luaByte(poff))
return sig;
@@ -1147,8 +1163,8 @@ public class StringLib extends TwoArgFunction {
error("missing '[' after '%f' in pattern");
}
int ep = classend(poffset);
int previous = (soffset == 0)? '\0': s.luaByte(soffset-1);
int next = (soffset == s.length())? '\0': s.luaByte(soffset);
int previous = soffset == 0? '\0': s.luaByte(soffset-1);
int next = soffset == s.length()? '\0': s.luaByte(soffset);
if (matchbracketclass(previous, poffset, ep-1) || !matchbracketclass(next, poffset, ep-1))
return -1;
poffset = ep;
@@ -1166,23 +1182,23 @@ public class StringLib extends TwoArgFunction {
}
case '$':
if (poffset+1 == p.length())
return (soffset == s.length())? soffset: -1;
return soffset == s.length()? soffset: -1;
}
int ep = classend(poffset);
boolean m = soffset < s.length() && singlematch(s.luaByte(soffset), poffset, ep);
int pc = (ep < p.length())? p.luaByte(ep): '\0';
int pc = ep < p.length()? p.luaByte(ep): '\0';
switch (pc) {
case '?':
int res;
if (m && ((res = match(soffset+1, ep+1)) != -1))
if (m && (res = match(soffset+1, ep+1)) != -1)
return res;
poffset = ep+1;
continue;
case '*':
return max_expand(soffset, poffset, ep);
case '+':
return (m? max_expand(soffset+1, poffset, ep): -1);
return m? max_expand(soffset+1, poffset, ep): -1;
case '-':
return min_expand(soffset, poffset, ep);
default:
@@ -1190,7 +1206,6 @@ public class StringLib extends TwoArgFunction {
return -1;
soffset++;
poffset = ep;
continue;
}
}
} finally {
@@ -1249,7 +1264,7 @@ public class StringLib extends TwoArgFunction {
int match_capture(int soff, int l) {
l = check_capture(l);
int len = clen[l];
if ((s.length()-soff) >= len && LuaString.equals(s, cinit[l], s, soff, len))
if (s.length()-soff >= len && LuaString.equals(s, cinit[l], s, soff, len))
return soff+len;
else
return -1;

View File

@@ -77,6 +77,7 @@ public class TableLib extends TwoArgFunction {
* @param env the environment to load into, typically a Globals
* instance.
*/
@Override
public LuaValue call(LuaValue modname, LuaValue env) {
LuaTable table = new LuaTable();
table.set("concat", new concat());
@@ -93,18 +94,22 @@ public class TableLib extends TwoArgFunction {
// "concat" (table [, sep [, i [, j]]]) -> string
static class concat extends TableLibFunction {
@Override
public LuaValue call(LuaValue list) {
return list.checktable().concat(EMPTYSTRING, 1, list.length());
}
@Override
public LuaValue call(LuaValue list, LuaValue sep) {
return list.checktable().concat(sep.checkstring(), 1, list.length());
}
@Override
public LuaValue call(LuaValue list, LuaValue sep, LuaValue i) {
return list.checktable().concat(sep.checkstring(), i.checkint(), list.length());
}
@Override
public LuaValue call(LuaValue list, LuaValue sep, LuaValue i, LuaValue j) {
return list.checktable().concat(sep.checkstring(), i.checkint(), j.checkint());
}
@@ -112,6 +117,7 @@ public class TableLib extends TwoArgFunction {
// "insert" (table, [pos,] value)
static class insert extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
switch (args.narg()) {
case 2: {
@@ -137,6 +143,7 @@ public class TableLib extends TwoArgFunction {
// "pack" (...) -> table
static class pack extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
LuaValue t = tableOf(args, 1);
t.set("n", args.narg());
@@ -146,6 +153,7 @@ public class TableLib extends TwoArgFunction {
// "remove" (table [, pos]) -> removed-ele
static class remove extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
LuaTable table = args.checktable(1);
int size = table.length();
@@ -159,6 +167,7 @@ public class TableLib extends TwoArgFunction {
// "sort" (table [, comp])
static class sort extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
args.checktable(1).sort(args.isnil(2)? NIL: args.checkfunction(2));
return NONE;
@@ -167,6 +176,7 @@ public class TableLib extends TwoArgFunction {
// "unpack", // (list [,i [,j]]) -> result1, ...
static class unpack extends VarArgFunction {
@Override
public Varargs invoke(Varargs args) {
LuaTable t = args.checktable(1);
// do not waste resource for calc rawlen if arg3 is not nil

View File

@@ -3,6 +3,7 @@ package org.luaj.vm2.lib;
import org.luaj.vm2.LuaValue;
class TableLibFunction extends LibFunction {
@Override
public LuaValue call() {
return argerror(1, "table expected, got no value");
}

View File

@@ -51,24 +51,29 @@ import org.luaj.vm2.Varargs;
*/
abstract public class ThreeArgFunction extends LibFunction {
@Override
abstract public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3);
/** Default constructor */
public ThreeArgFunction() {
}
@Override
public final LuaValue call() {
return call(NIL, NIL, NIL);
}
@Override
public final LuaValue call(LuaValue arg) {
return call(arg, NIL, NIL);
}
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2) {
return call(arg1, arg2, NIL);
}
@Override
public Varargs invoke(Varargs varargs) {
return call(varargs.arg1(), varargs.arg(2), varargs.arg(3));
}

View File

@@ -51,24 +51,29 @@ import org.luaj.vm2.Varargs;
*/
abstract public class TwoArgFunction extends LibFunction {
@Override
abstract public LuaValue call(LuaValue arg1, LuaValue arg2);
/** Default constructor */
public TwoArgFunction() {
}
@Override
public final LuaValue call() {
return call(NIL, NIL);
}
@Override
public final LuaValue call(LuaValue arg) {
return call(arg, NIL);
}
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) {
return call(arg1, arg2);
}
@Override
public Varargs invoke(Varargs varargs) {
return call(varargs.arg1(), varargs.arg(2));
}

View File

@@ -53,18 +53,22 @@ abstract public class VarArgFunction extends LibFunction {
public VarArgFunction() {
}
@Override
public LuaValue call() {
return invoke(NONE).arg1();
}
@Override
public LuaValue call(LuaValue arg) {
return invoke(arg).arg1();
}
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2) {
return invoke(varargsOf(arg1, arg2)).arg1();
}
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) {
return invoke(varargsOf(arg1, arg2, arg3)).arg1();
}
@@ -76,10 +80,12 @@ abstract public class VarArgFunction extends LibFunction {
*
* @param args the arguments to the function call.
*/
@Override
public Varargs invoke(Varargs args) {
return onInvoke(args).eval();
}
@Override
public Varargs onInvoke(Varargs args) {
return invoke(args);
}

View File

@@ -48,24 +48,29 @@ import org.luaj.vm2.Varargs;
*/
abstract public class ZeroArgFunction extends LibFunction {
@Override
abstract public LuaValue call();
/** Default constructor */
public ZeroArgFunction() {
}
@Override
public LuaValue call(LuaValue arg) {
return call();
}
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2) {
return call();
}
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) {
return call();
}
@Override
public Varargs invoke(Varargs varargs) {
return call();
}

View File

@@ -83,25 +83,28 @@ import org.luaj.vm2.lib.LibFunction;
*/
public class JmeIoLib extends IoLib {
@Override
protected File wrapStdin() throws IOException {
return new FileImpl(globals.STDIN);
}
@Override
protected File wrapStdout() throws IOException {
return new FileImpl(globals.STDOUT);
}
@Override
protected File wrapStderr() throws IOException {
return new FileImpl(globals.STDERR);
}
@Override
protected File openFile(String filename, boolean readMode, boolean appendMode, boolean updateMode,
boolean binaryMode) throws IOException {
String url = "file:///" + filename;
int mode = readMode? Connector.READ: Connector.READ_WRITE;
StreamConnection conn = (StreamConnection) Connector.open(url, mode);
File f = readMode? new FileImpl(conn, conn.openInputStream(), null)
: new FileImpl(conn, conn.openInputStream(), conn.openOutputStream());
/*
if ( appendMode ) {
f.seek("end",0);
@@ -110,18 +113,21 @@ public class JmeIoLib extends IoLib {
conn.truncate(0);
}
*/
return f;
return readMode? new FileImpl(conn, conn.openInputStream(), null)
: new FileImpl(conn, conn.openInputStream(), conn.openOutputStream());
}
private static void notimplemented() throws IOException {
throw new IOException("not implemented");
}
@Override
protected File openProgram(String prog, String mode) throws IOException {
notimplemented();
return null;
}
@Override
protected File tmpFile() throws IOException {
notimplemented();
return null;
@@ -149,14 +155,17 @@ public class JmeIoLib extends IoLib {
this(null, null, o);
}
@Override
public String tojstring() {
return "file (" + this.hashCode() + ")";
}
@Override
public boolean isstdfile() {
return conn == null;
}
@Override
public void close() throws IOException {
closed = true;
if (conn != null) {
@@ -164,11 +173,13 @@ public class JmeIoLib extends IoLib {
}
}
@Override
public void flush() throws IOException {
if (os != null)
os.flush();
}
@Override
public void write(LuaString s) throws IOException {
if (os != null)
os.write(s.m_bytes, s.m_offset, s.m_length);
@@ -178,10 +189,12 @@ public class JmeIoLib extends IoLib {
flush();
}
@Override
public boolean isclosed() {
return closed;
}
@Override
public int seek(String option, int pos) throws IOException {
/*
if ( conn != null ) {
@@ -201,16 +214,19 @@ public class JmeIoLib extends IoLib {
return 0;
}
@Override
public void setvbuf(String mode, int size) {
nobuffer = "no".equals(mode);
}
// get length remaining to read
@Override
public int remaining() throws IOException {
return -1;
}
// peek ahead one character
@Override
public int peek() throws IOException {
if (lookahead < 0)
lookahead = is.read();
@@ -218,6 +234,7 @@ public class JmeIoLib extends IoLib {
}
// return char if read, -1 if eof, throw IOException on other exception
@Override
public int read() throws IOException {
if (lookahead >= 0) {
int c = lookahead;
@@ -231,6 +248,7 @@ public class JmeIoLib extends IoLib {
}
// return number of bytes read if positive, -1 if eof, throws IOException
@Override
public int read(byte[] bytes, int offset, int length) throws IOException {
int n, i = 0;
if (is != null) {
@@ -242,7 +260,7 @@ public class JmeIoLib extends IoLib {
for (; i < length;) {
n = is.read(bytes, offset+i, length-i);
if (n < 0)
return (i > 0? i: -1);
return i > 0? i: -1;
i += n;
}
} else {

View File

@@ -23,8 +23,6 @@ package org.luaj.vm2.lib.jme;
import org.luaj.vm2.Globals;
import org.luaj.vm2.LoadState;
import org.luaj.vm2.LuaThread;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.compiler.LuaC;
import org.luaj.vm2.lib.BaseLib;
import org.luaj.vm2.lib.Bit32Lib;

View File

@@ -65,7 +65,7 @@ public class lua {
public static void main(String[] args) throws IOException {
// process args
boolean interactive = (args.length == 0);
boolean interactive = args.length == 0;
boolean versioninfo = false;
boolean processing = true;
boolean nodebug = false;

View File

@@ -128,10 +128,8 @@ public class luac {
System.out.println(version);
// open output file
OutputStream fos = new FileOutputStream(output);
// process input files
try {
try (OutputStream fos = new FileOutputStream(output)) {
Globals globals = JsePlatform.standardGlobals();
processing = true;
for (int i = 0; i < args.length; i++) {
@@ -152,8 +150,6 @@ public class luac {
}
}
}
} finally {
fos.close();
}
} catch (IOException ioe) {

View File

@@ -55,16 +55,16 @@ public class luajc {
System.exit(-1);
}
private String srcdir = ".";
private String destdir = ".";
private boolean genmain = false;
private boolean recurse = false;
private boolean verbose = false;
private boolean loadclasses = false;
private String encoding = null;
private String pkgprefix = null;
private List files = new ArrayList();
private Globals globals;
private String srcdir = ".";
private String destdir = ".";
private boolean genmain = false;
private boolean recurse = false;
private boolean verbose = false;
private boolean loadclasses = false;
private String encoding = null;
private String pkgprefix = null;
private final List files = new ArrayList();
private final Globals globals;
public static void main(String[] args) throws IOException {
new luajc(args);
@@ -136,8 +136,8 @@ public class luajc {
}
// collect up files to process
for (int i = 0; i < seeds.size(); i++)
collectFiles(srcdir + "/" + seeds.get(i));
for (Object seed : seeds)
collectFiles(srcdir + "/" + seed);
// check for at least one file
if (files.size() <= 0) {
@@ -147,8 +147,8 @@ public class luajc {
// process input files
globals = JsePlatform.standardGlobals();
for (int i = 0, n = files.size(); i < n; i++)
processFile((InputFile) files.get(i));
for (Object file : files)
processFile((InputFile) file);
}
private void collectFiles(String path) {
@@ -164,14 +164,14 @@ public class luajc {
private void scandir(File dir, String javapackage) {
File[] f = dir.listFiles();
for (int i = 0; i < f.length; i++)
scanfile(dir, f[i], javapackage);
for (File element : f)
scanfile(dir, element, javapackage);
}
private void scanfile(File dir, File f, String javapackage) {
if (f.exists()) {
if (f.isDirectory() && recurse)
scandir(f, (javapackage != null? javapackage + "." + f.getName(): f.getName()));
scandir(f, javapackage != null? javapackage + "." + f.getName(): f.getName());
else if (f.isFile() && f.getName().endsWith(".lua"))
files.add(new InputFile(dir, f, javapackage));
}
@@ -184,6 +184,7 @@ public class luajc {
this.t = t;
}
@Override
public Class findClass(String classname) throws ClassNotFoundException {
byte[] bytes = (byte[]) t.get(classname);
if (bytes != null)

View File

@@ -26,7 +26,7 @@ import java.util.List;
public class Block extends Stat {
public List<Stat> stats = new ArrayList<Stat>();
public List<Stat> stats = new ArrayList<>();
public NameScope scope;
public void add(Stat s) {
@@ -35,6 +35,7 @@ public class Block extends Stat {
stats.add(s);
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}

View File

@@ -62,12 +62,12 @@ abstract public class Exp extends SyntaxElement {
// TODO: constant folding
if (lhs instanceof BinopExp) {
BinopExp b = (BinopExp) lhs;
if ((precedence(op) > precedence(b.op)) || ((precedence(op) == precedence(b.op)) && isrightassoc(op)))
if (precedence(op) > precedence(b.op) || precedence(op) == precedence(b.op) && isrightassoc(op))
return binaryexp(b.lhs, b.op, binaryexp(b.rhs, op, rhs));
}
if (rhs instanceof BinopExp) {
BinopExp b = (BinopExp) rhs;
if ((precedence(op) > precedence(b.op)) || ((precedence(op) == precedence(b.op)) && !isrightassoc(op)))
if (precedence(op) > precedence(b.op) || precedence(op) == precedence(b.op) && !isrightassoc(op))
return binaryexp(binaryexp(lhs, op, b.lhs), b.op, b.rhs);
}
return new BinopExp(lhs, op, rhs);
@@ -163,16 +163,19 @@ abstract public class Exp extends SyntaxElement {
}
abstract public static class PrimaryExp extends Exp {
@Override
public boolean isvarexp() {
return false;
}
@Override
public boolean isfunccall() {
return false;
}
}
abstract public static class VarExp extends PrimaryExp {
@Override
public boolean isvarexp() {
return true;
}
@@ -188,10 +191,12 @@ abstract public class Exp extends SyntaxElement {
this.name = new Name(name);
}
@Override
public void markHasAssignment() {
name.variable.hasassignments = true;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
@@ -204,6 +209,7 @@ abstract public class Exp extends SyntaxElement {
this.exp = exp;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
@@ -218,6 +224,7 @@ abstract public class Exp extends SyntaxElement {
this.name = new Name(name);
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
@@ -232,6 +239,7 @@ abstract public class Exp extends SyntaxElement {
this.exp = exp;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
@@ -246,14 +254,17 @@ abstract public class Exp extends SyntaxElement {
this.args = args;
}
@Override
public boolean isfunccall() {
return true;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
@Override
public boolean isvarargexp() {
return true;
}
@@ -267,10 +278,12 @@ abstract public class Exp extends SyntaxElement {
this.name = new String(name);
}
@Override
public boolean isfunccall() {
return true;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
@@ -283,6 +296,7 @@ abstract public class Exp extends SyntaxElement {
this.value = value;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
@@ -290,10 +304,12 @@ abstract public class Exp extends SyntaxElement {
public static class VarargsExp extends Exp {
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
@Override
public boolean isvarargexp() {
return true;
}
@@ -308,6 +324,7 @@ abstract public class Exp extends SyntaxElement {
this.rhs = rhs;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
@@ -323,6 +340,7 @@ abstract public class Exp extends SyntaxElement {
this.rhs = rhs;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
@@ -335,6 +353,7 @@ abstract public class Exp extends SyntaxElement {
this.body = funcbody;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}

View File

@@ -50,12 +50,12 @@ public class FuncArgs extends SyntaxElement {
}
public FuncArgs(LuaString string) {
this.exps = new ArrayList<Exp>();
this.exps = new ArrayList<>();
this.exps.add(Exp.constant(string));
}
public FuncArgs(TableConstructor table) {
this.exps = new ArrayList<Exp>();
this.exps = new ArrayList<>();
this.exps.add(table);
}

View File

@@ -42,7 +42,7 @@ public class FuncName extends SyntaxElement {
public void adddot(String dot) {
if (dots == null)
dots = new ArrayList<String>();
dots = new ArrayList<>();
dots.add(dot);
}

View File

@@ -30,9 +30,11 @@ public class NameResolver extends Visitor {
scope = scope.outerScope;
}
@Override
public void visit(NameScope scope) {
}
@Override
public void visit(Block block) {
pushScope();
block.scope = scope;
@@ -40,6 +42,7 @@ public class NameResolver extends Visitor {
popScope();
}
@Override
public void visit(FuncBody body) {
pushScope();
scope.functionNestingCount++;
@@ -48,11 +51,13 @@ public class NameResolver extends Visitor {
popScope();
}
@Override
public void visit(LocalFuncDef stat) {
defineLocalVar(stat.name);
super.visit(stat);
}
@Override
public void visit(NumericFor stat) {
pushScope();
stat.scope = scope;
@@ -61,6 +66,7 @@ public class NameResolver extends Visitor {
popScope();
}
@Override
public void visit(GenericFor stat) {
pushScope();
stat.scope = scope;
@@ -69,39 +75,44 @@ public class NameResolver extends Visitor {
popScope();
}
@Override
public void visit(NameExp exp) {
exp.name.variable = resolveNameReference(exp.name);
super.visit(exp);
}
@Override
public void visit(FuncDef stat) {
stat.name.name.variable = resolveNameReference(stat.name.name);
stat.name.name.variable.hasassignments = true;
super.visit(stat);
}
@Override
public void visit(Assign stat) {
super.visit(stat);
for (int i = 0, n = stat.vars.size(); i < n; i++) {
VarExp v = (VarExp) stat.vars.get(i);
for (VarExp element : stat.vars) {
VarExp v = element;
v.markHasAssignment();
}
}
@Override
public void visit(LocalAssign stat) {
visitExps(stat.values);
defineLocalVars(stat.names);
int n = stat.names.size();
int m = stat.values != null? stat.values.size(): 0;
boolean isvarlist = m > 0 && m < n && ((Exp) stat.values.get(m-1)).isvarargexp();
boolean isvarlist = m > 0 && m < n && stat.values.get(m-1).isvarargexp();
for (int i = 0; i < n && i < (isvarlist? m-1: m); i++)
if (stat.values.get(i) instanceof Constant)
((Name) stat.names.get(i)).variable.initialValue = ((Constant) stat.values.get(i)).value;
stat.names.get(i).variable.initialValue = ((Constant) stat.values.get(i)).value;
if (!isvarlist)
for (int i = m; i < n; i++)
((Name) stat.names.get(i)).variable.initialValue = LuaValue.NIL;
stat.names.get(i).variable.initialValue = LuaValue.NIL;
}
@Override
public void visit(ParList pars) {
if (pars.names != null)
defineLocalVars(pars.names);
@@ -111,8 +122,8 @@ public class NameResolver extends Visitor {
}
protected void defineLocalVars(List<Name> names) {
for (int i = 0, n = names.size(); i < n; i++)
defineLocalVar((Name) names.get(i));
for (Name name : names)
defineLocalVar(name);
}
protected void defineLocalVar(Name name) {

View File

@@ -28,16 +28,16 @@ import java.util.Set;
public class NameScope {
private static final Set<String> LUA_KEYWORDS = new HashSet<String>();
private static final Set<String> LUA_KEYWORDS = new HashSet<>();
static {
String[] k = new String[] { "and", "break", "do", "else", "elseif", "end", "false", "for", "function", "if",
"in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while" };
for (int i = 0; i < k.length; i++)
LUA_KEYWORDS.add(k[i]);
String[] k = { "and", "break", "do", "else", "elseif", "end", "false", "for", "function", "if", "in", "local",
"nil", "not", "or", "repeat", "return", "then", "true", "until", "while" };
for (String element : k)
LUA_KEYWORDS.add(element);
}
public final Map<String, Variable> namedVariables = new HashMap<String, Variable>();
public final Map<String, Variable> namedVariables = new HashMap<>();
public final NameScope outerScope;
@@ -63,7 +63,7 @@ public class NameScope {
validateIsNotKeyword(name);
for (NameScope n = this; n != null; n = n.outerScope)
if (n.namedVariables.containsKey(name))
return (Variable) n.namedVariables.get(name);
return n.namedVariables.get(name);
Variable value = new Variable(name);
this.namedVariables.put(name, value);
return value;

View File

@@ -25,7 +25,7 @@ import java.util.ArrayList;
import java.util.List;
public class ParList extends SyntaxElement {
public static final List<Name> EMPTY_NAMELIST = new ArrayList<Name>();
public static final List<Name> EMPTY_NAMELIST = new ArrayList<>();
public static final ParList EMPTY_PARLIST = new ParList(EMPTY_NAMELIST, false);
public final List<Name> names;

View File

@@ -96,6 +96,7 @@ abstract public class Stat extends SyntaxElement {
this.name = name;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
@@ -108,6 +109,7 @@ abstract public class Stat extends SyntaxElement {
this.name = name;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
@@ -122,6 +124,7 @@ abstract public class Stat extends SyntaxElement {
this.exps = exps;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
@@ -137,6 +140,7 @@ abstract public class Stat extends SyntaxElement {
this.block = block;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
@@ -151,12 +155,14 @@ abstract public class Stat extends SyntaxElement {
this.exp = exp;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
public static class Break extends Stat {
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
@@ -169,13 +175,14 @@ abstract public class Stat extends SyntaxElement {
this.values = values;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
public int nreturns() {
int n = values != null? values.size(): 0;
if (n > 0 && ((Exp) values.get(n-1)).isvarargexp())
if (n > 0 && values.get(n-1).isvarargexp())
n = -1;
return n;
}
@@ -188,6 +195,7 @@ abstract public class Stat extends SyntaxElement {
this.funccall = funccall;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
@@ -202,6 +210,7 @@ abstract public class Stat extends SyntaxElement {
this.body = body;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
@@ -216,6 +225,7 @@ abstract public class Stat extends SyntaxElement {
this.body = body;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
@@ -233,6 +243,7 @@ abstract public class Stat extends SyntaxElement {
this.block = block;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
@@ -252,6 +263,7 @@ abstract public class Stat extends SyntaxElement {
this.block = block;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
@@ -266,6 +278,7 @@ abstract public class Stat extends SyntaxElement {
this.values = values;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
@@ -286,6 +299,7 @@ abstract public class Stat extends SyntaxElement {
this.elseblock = elseblock;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}

View File

@@ -74,9 +74,9 @@ public class Str {
case '7':
case '8':
case '9':
int d = (int) (c[i++]-'0');
int d = c[i++]-'0';
for (int j = 0; i < n && j < 2 && c[i] >= '0' && c[i] <= '9'; i++, j++)
d = d*10+(int) (c[i]-'0');
d = d*10+c[i]-'0';
baos.write((byte) d);
--i;
continue;

View File

@@ -26,6 +26,7 @@ import java.util.List;
public class TableConstructor extends Exp {
public List<TableField> fields;
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}

View File

@@ -28,14 +28,14 @@ import org.luaj.vm2.ast.Exp.VarExp;
abstract public class Visitor {
public void visit(Chunk chunk) {
chunk.block.accept(this);
};
}
public void visit(Block block) {
visit(block.scope);
if (block.stats != null)
for (int i = 0, n = block.stats.size(); i < n; i++)
((Stat) block.stats.get(i)).accept(this);
};
for (Stat element : block.stats)
element.accept(this);
}
public void visit(Stat.Assign stat) {
visitVars(stat.vars);
@@ -65,8 +65,8 @@ abstract public class Visitor {
stat.ifblock.accept(this);
if (stat.elseifblocks != null)
for (int i = 0, n = stat.elseifblocks.size(); i < n; i++) {
((Exp) stat.elseifexps.get(i)).accept(this);
((Block) stat.elseifblocks.get(i)).accept(this);
stat.elseifexps.get(i).accept(this);
stat.elseifblocks.get(i).accept(this);
}
if (stat.elseblock != null)
visit(stat.elseblock);
@@ -178,26 +178,26 @@ abstract public class Visitor {
public void visit(TableConstructor table) {
if (table.fields != null)
for (int i = 0, n = table.fields.size(); i < n; i++)
((TableField) table.fields.get(i)).accept(this);
for (TableField element : table.fields)
element.accept(this);
}
public void visitVars(List<VarExp> vars) {
if (vars != null)
for (int i = 0, n = vars.size(); i < n; i++)
((Exp.VarExp) vars.get(i)).accept(this);
for (VarExp var : vars)
var.accept(this);
}
public void visitExps(List<Exp> exps) {
if (exps != null)
for (int i = 0, n = exps.size(); i < n; i++)
((Exp) exps.get(i)).accept(this);
for (Exp exp : exps)
exp.accept(this);
}
public void visitNames(List<Name> names) {
if (names != null)
for (int i = 0, n = names.size(); i < n; i++)
visit((Name) names.get(i));
for (Name name : names)
visit(name);
}
public void visit(Name name) {

View File

@@ -64,11 +64,12 @@ import org.luaj.vm2.LuaValue;
*/
public class CoerceJavaToLua {
static interface Coercion {
public LuaValue coerce(Object javaValue);
};
interface Coercion {
LuaValue coerce(Object javaValue);
}
private static final class BoolCoercion implements Coercion {
@Override
public LuaValue coerce(Object javaValue) {
Boolean b = (Boolean) javaValue;
return b.booleanValue()? LuaValue.TRUE: LuaValue.FALSE;
@@ -76,6 +77,7 @@ public class CoerceJavaToLua {
}
private static final class IntCoercion implements Coercion {
@Override
public LuaValue coerce(Object javaValue) {
Number n = (Number) javaValue;
return LuaInteger.valueOf(n.intValue());
@@ -83,6 +85,7 @@ public class CoerceJavaToLua {
}
private static final class CharCoercion implements Coercion {
@Override
public LuaValue coerce(Object javaValue) {
Character c = (Character) javaValue;
return LuaInteger.valueOf(c.charValue());
@@ -90,6 +93,7 @@ public class CoerceJavaToLua {
}
private static final class DoubleCoercion implements Coercion {
@Override
public LuaValue coerce(Object javaValue) {
Number n = (Number) javaValue;
return LuaDouble.valueOf(n.doubleValue());
@@ -97,30 +101,35 @@ public class CoerceJavaToLua {
}
private static final class StringCoercion implements Coercion {
@Override
public LuaValue coerce(Object javaValue) {
return LuaString.valueOf(javaValue.toString());
}
}
private static final class BytesCoercion implements Coercion {
@Override
public LuaValue coerce(Object javaValue) {
return LuaValue.valueOf((byte[]) javaValue);
}
}
private static final class ClassCoercion implements Coercion {
@Override
public LuaValue coerce(Object javaValue) {
return JavaClass.forClass((Class) javaValue);
}
}
private static final class InstanceCoercion implements Coercion {
@Override
public LuaValue coerce(Object javaValue) {
return new JavaInstance(javaValue);
}
}
private static final class ArrayCoercion implements Coercion {
@Override
public LuaValue coerce(Object javaValue) {
// should be userdata?
return new JavaArray(javaValue);
@@ -128,6 +137,7 @@ public class CoerceJavaToLua {
}
private static final class LuaCoercion implements Coercion {
@Override
public LuaValue coerce(Object javaValue) {
return (LuaValue) javaValue;
}

View File

@@ -63,11 +63,11 @@ public class CoerceLuaToJava {
static int SCORE_WRONG_TYPE = 0x100;
static int SCORE_UNCOERCIBLE = 0x10000;
static interface Coercion {
public int score(LuaValue value);
interface Coercion {
int score(LuaValue value);
public Object coerce(LuaValue value);
};
Object coerce(LuaValue value);
}
/**
* Coerce a LuaValue value to a specified java class
@@ -84,10 +84,12 @@ public class CoerceLuaToJava {
static final Map COERCIONS = Collections.synchronizedMap(new HashMap());
static final class BoolCoercion implements Coercion {
@Override
public String toString() {
return "BoolCoercion()";
}
@Override
public int score(LuaValue value) {
switch (value.type()) {
case LuaValue.TBOOLEAN:
@@ -96,6 +98,7 @@ public class CoerceLuaToJava {
return 1;
}
@Override
public Object coerce(LuaValue value) {
return value.toboolean()? Boolean.TRUE: Boolean.FALSE;
}
@@ -112,6 +115,7 @@ public class CoerceLuaToJava {
static final String[] TYPE_NAMES = { "byte", "char", "short", "int", "long", "float", "double" };
final int targetType;
@Override
public String toString() {
return "NumericCoercion(" + TYPE_NAMES[targetType] + ")";
}
@@ -120,6 +124,7 @@ public class CoerceLuaToJava {
this.targetType = targetType;
}
@Override
public int score(LuaValue value) {
int fromStringPenalty = 0;
if (value.type() == LuaValue.TSTRING) {
@@ -133,19 +138,19 @@ public class CoerceLuaToJava {
switch (targetType) {
case TARGET_TYPE_BYTE: {
int i = value.toint();
return fromStringPenalty+((i == (byte) i)? 0: SCORE_WRONG_TYPE);
return fromStringPenalty+(i == (byte) i? 0: SCORE_WRONG_TYPE);
}
case TARGET_TYPE_CHAR: {
int i = value.toint();
return fromStringPenalty+((i == (byte) i)? 1: (i == (char) i)? 0: SCORE_WRONG_TYPE);
return fromStringPenalty+(i == (byte) i? 1: i == (char) i? 0: SCORE_WRONG_TYPE);
}
case TARGET_TYPE_SHORT: {
int i = value.toint();
return fromStringPenalty+((i == (byte) i)? 1: (i == (short) i)? 0: SCORE_WRONG_TYPE);
return fromStringPenalty+(i == (byte) i? 1: i == (short) i? 0: SCORE_WRONG_TYPE);
}
case TARGET_TYPE_INT: {
int i = value.toint();
return fromStringPenalty+((i == (byte) i)? 2: ((i == (char) i) || (i == (short) i))? 1: 0);
return fromStringPenalty+(i == (byte) i? 2: i == (char) i || i == (short) i? 1: 0);
}
case TARGET_TYPE_FLOAT:
return fromStringPenalty+1;
@@ -168,15 +173,15 @@ public class CoerceLuaToJava {
return SCORE_WRONG_TYPE;
case TARGET_TYPE_LONG: {
double d = value.todouble();
return fromStringPenalty+((d == (long) d)? 0: SCORE_WRONG_TYPE);
return fromStringPenalty+(d == (long) d? 0: SCORE_WRONG_TYPE);
}
case TARGET_TYPE_FLOAT: {
double d = value.todouble();
return fromStringPenalty+((d == (float) d)? 0: SCORE_WRONG_TYPE);
return fromStringPenalty+(d == (float) d? 0: SCORE_WRONG_TYPE);
}
case TARGET_TYPE_DOUBLE: {
double d = value.todouble();
return fromStringPenalty+(((d == (long) d) || (d == (float) d))? 1: 0);
return fromStringPenalty+(d == (long) d || d == (float) d? 1: 0);
}
default:
return SCORE_WRONG_TYPE;
@@ -186,22 +191,23 @@ public class CoerceLuaToJava {
}
}
@Override
public Object coerce(LuaValue value) {
switch (targetType) {
case TARGET_TYPE_BYTE:
return new Byte((byte) value.toint());
return Byte.valueOf((byte) value.toint());
case TARGET_TYPE_CHAR:
return new Character((char) value.toint());
return Character.valueOf((char) value.toint());
case TARGET_TYPE_SHORT:
return new Short((short) value.toint());
return Short.valueOf((short) value.toint());
case TARGET_TYPE_INT:
return new Integer((int) value.toint());
return Integer.valueOf(value.toint());
case TARGET_TYPE_LONG:
return new Long((long) value.todouble());
return Long.valueOf((long) value.todouble());
case TARGET_TYPE_FLOAT:
return new Float((float) value.todouble());
return Float.valueOf((float) value.todouble());
case TARGET_TYPE_DOUBLE:
return new Double((double) value.todouble());
return Double.valueOf(value.todouble());
default:
return null;
}
@@ -217,15 +223,17 @@ public class CoerceLuaToJava {
this.targetType = targetType;
}
@Override
public String toString() {
return "StringCoercion(" + (targetType == TARGET_TYPE_STRING? "String": "byte[]") + ")";
}
@Override
public int score(LuaValue value) {
switch (value.type()) {
case LuaValue.TSTRING:
return value.checkstring().isValidUtf8()? (targetType == TARGET_TYPE_STRING? 0: 1)
: (targetType == TARGET_TYPE_BYTES? 0: SCORE_WRONG_TYPE);
return value.checkstring().isValidUtf8()? targetType == TARGET_TYPE_STRING? 0: 1
: targetType == TARGET_TYPE_BYTES? 0: SCORE_WRONG_TYPE;
case LuaValue.TNIL:
return SCORE_NULL_VALUE;
default:
@@ -233,6 +241,7 @@ public class CoerceLuaToJava {
}
}
@Override
public Object coerce(LuaValue value) {
if (value.isnil())
return null;
@@ -254,10 +263,12 @@ public class CoerceLuaToJava {
this.componentCoercion = getCoercion(componentType);
}
@Override
public String toString() {
return "ArrayCoercion(" + componentType.getName() + ")";
}
@Override
public int score(LuaValue value) {
switch (value.type()) {
case LuaValue.TTABLE:
@@ -271,6 +282,7 @@ public class CoerceLuaToJava {
}
}
@Override
public Object coerce(LuaValue value) {
switch (value.type()) {
case LuaValue.TTABLE: {
@@ -306,8 +318,8 @@ public class CoerceLuaToJava {
return 0;
int min = Math.min(SCORE_UNCOERCIBLE, inheritanceLevels(baseclass, subclass.getSuperclass())+1);
Class[] ifaces = subclass.getInterfaces();
for (int i = 0; i < ifaces.length; i++)
min = Math.min(min, inheritanceLevels(baseclass, ifaces[i])+1);
for (Class element : ifaces)
min = Math.min(min, inheritanceLevels(baseclass, element)+1);
return min;
}
@@ -318,10 +330,12 @@ public class CoerceLuaToJava {
this.targetType = targetType;
}
@Override
public String toString() {
return "ObjectCoercion(" + targetType.getName() + ")";
}
@Override
public int score(LuaValue value) {
switch (value.type()) {
case LuaValue.TNUMBER:
@@ -339,10 +353,12 @@ public class CoerceLuaToJava {
}
}
@Override
public Object coerce(LuaValue value) {
switch (value.type()) {
case LuaValue.TNUMBER:
return value.isint()? (Object) new Integer(value.toint()): (Object) new Double(value.todouble());
return value.isint()? (Object) Integer.valueOf(value.toint())
: (Object) Double.valueOf(value.todouble());
case LuaValue.TBOOLEAN:
return value.toboolean()? Boolean.TRUE: Boolean.FALSE;
case LuaValue.TSTRING:

View File

@@ -42,6 +42,7 @@ import org.luaj.vm2.lib.OneArgFunction;
class JavaArray extends LuaUserdata {
private static final class LenFunction extends OneArgFunction {
@Override
public LuaValue call(LuaValue u) {
return LuaValue.valueOf(Array.getLength(((LuaUserdata) u).m_instance));
}
@@ -60,6 +61,7 @@ class JavaArray extends LuaUserdata {
setmetatable(array_metatable);
}
@Override
public LuaValue get(LuaValue key) {
if (key.equals(LENGTH))
return valueOf(Array.getLength(m_instance));
@@ -72,6 +74,7 @@ class JavaArray extends LuaUserdata {
return super.get(key);
}
@Override
public void set(LuaValue key, LuaValue value) {
if (key.isint()) {
int i = key.toint()-1;

View File

@@ -68,6 +68,7 @@ class JavaClass extends JavaInstance implements CoerceJavaToLua.Coercion {
this.jclass = this;
}
@Override
public LuaValue coerce(Object javaValue) {
return this;
}
@@ -76,8 +77,7 @@ class JavaClass extends JavaInstance implements CoerceJavaToLua.Coercion {
if (fields == null) {
Map m = new HashMap();
Field[] f = ((Class) m_instance).getFields();
for (int i = 0; i < f.length; i++) {
Field fi = f[i];
for (Field fi : f) {
if (Modifier.isPublic(fi.getModifiers())) {
m.put(LuaValue.valueOf(fi.getName()), fi);
try {
@@ -96,8 +96,7 @@ class JavaClass extends JavaInstance implements CoerceJavaToLua.Coercion {
if (methods == null) {
Map namedlists = new HashMap();
Method[] m = ((Class) m_instance).getMethods();
for (int i = 0; i < m.length; i++) {
Method mi = m[i];
for (Method mi : m) {
if (Modifier.isPublic(mi.getModifiers())) {
String name = mi.getName();
List list = (List) namedlists.get(name);
@@ -109,9 +108,9 @@ class JavaClass extends JavaInstance implements CoerceJavaToLua.Coercion {
Map map = new HashMap();
Constructor[] c = ((Class) m_instance).getConstructors();
List list = new ArrayList();
for (int i = 0; i < c.length; i++)
if (Modifier.isPublic(c[i].getModifiers()))
list.add(JavaConstructor.forConstructor(c[i]));
for (Constructor element : c)
if (Modifier.isPublic(element.getModifiers()))
list.add(JavaConstructor.forConstructor(element));
switch (list.size()) {
case 0:
break;
@@ -140,8 +139,7 @@ class JavaClass extends JavaInstance implements CoerceJavaToLua.Coercion {
if (innerclasses == null) {
Map m = new HashMap();
Class[] c = ((Class) m_instance).getClasses();
for (int i = 0; i < c.length; i++) {
Class ci = c[i];
for (Class ci : c) {
String name = ci.getName();
String stub = name.substring(Math.max(name.lastIndexOf('$'), name.lastIndexOf('.'))+1);
m.put(LuaValue.valueOf(stub), ci);

View File

@@ -66,6 +66,7 @@ class JavaConstructor extends JavaMember {
this.constructor = c;
}
@Override
public Varargs invoke(Varargs args) {
Object[] a = convertArgs(args);
try {
@@ -93,14 +94,15 @@ class JavaConstructor extends JavaMember {
this.constructors = c;
}
@Override
public Varargs invoke(Varargs args) {
JavaConstructor best = null;
int score = CoerceLuaToJava.SCORE_UNCOERCIBLE;
for (int i = 0; i < constructors.length; i++) {
int s = constructors[i].score(args);
for (JavaConstructor constructor : constructors) {
int s = constructor.score(args);
if (s < score) {
score = s;
best = constructors[i];
best = constructor;
if (score == 0)
break;
}

View File

@@ -46,6 +46,7 @@ class JavaInstance extends LuaUserdata {
super(instance);
}
@Override
public LuaValue get(LuaValue key) {
if (jclass == null)
jclass = JavaClass.forClass(m_instance.getClass());
@@ -65,6 +66,7 @@ class JavaInstance extends LuaUserdata {
return super.get(key);
}
@Override
public void set(LuaValue key, LuaValue value) {
if (jclass == null)
jclass = JavaClass.forClass(m_instance.getClass());

View File

@@ -47,7 +47,7 @@ abstract class JavaMember extends VarArgFunction {
final Coercion varargs;
protected JavaMember(Class[] params, int modifiers) {
boolean isvarargs = ((modifiers & METHOD_MODIFIERS_VARARGS) != 0);
boolean isvarargs = (modifiers & METHOD_MODIFIERS_VARARGS) != 0;
fixedargs = new CoerceLuaToJava.Coercion[isvarargs? params.length-1: params.length];
for (int i = 0; i < fixedargs.length; i++)
fixedargs[i] = CoerceLuaToJava.getCoercion(params[i]);

View File

@@ -70,22 +70,27 @@ class JavaMethod extends JavaMember {
}
}
@Override
public LuaValue call() {
return error("method cannot be called without instance");
}
@Override
public LuaValue call(LuaValue arg) {
return invokeMethod(arg.checkuserdata(), LuaValue.NONE);
}
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2) {
return invokeMethod(arg1.checkuserdata(), arg2);
}
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) {
return invokeMethod(arg1.checkuserdata(), LuaValue.varargsOf(arg2, arg3));
}
@Override
public Varargs invoke(Varargs args) {
return invokeMethod(args.checkuserdata(1), args.subargs(2));
}
@@ -118,22 +123,27 @@ class JavaMethod extends JavaMember {
this.methods = methods;
}
@Override
public LuaValue call() {
return error("method cannot be called without instance");
}
@Override
public LuaValue call(LuaValue arg) {
return invokeBestMethod(arg.checkuserdata(), LuaValue.NONE);
}
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2) {
return invokeBestMethod(arg1.checkuserdata(), arg2);
}
@Override
public LuaValue call(LuaValue arg1, LuaValue arg2, LuaValue arg3) {
return invokeBestMethod(arg1.checkuserdata(), LuaValue.varargsOf(arg2, arg3));
}
@Override
public Varargs invoke(Varargs args) {
return invokeBestMethod(args.checkuserdata(1), args.subargs(2));
}
@@ -141,11 +151,11 @@ class JavaMethod extends JavaMember {
private LuaValue invokeBestMethod(Object instance, Varargs args) {
JavaMethod best = null;
int score = CoerceLuaToJava.SCORE_UNCOERCIBLE;
for (int i = 0; i < methods.length; i++) {
int s = methods[i].score(args);
for (JavaMethod method : methods) {
int s = method.score(args);
if (s < score) {
score = s;
best = methods[i];
best = method;
if (score == 0)
break;
}

View File

@@ -100,6 +100,7 @@ public class JseBaseLib extends org.luaj.vm2.lib.BaseLib {
* @param env the environment to load into, which must be a Globals
* instance.
*/
@Override
public LuaValue call(LuaValue modname, LuaValue env) {
super.call(modname, env);
env.checkglobals().STDIN = System.in;
@@ -120,6 +121,7 @@ public class JseBaseLib extends org.luaj.vm2.lib.BaseLib {
* @param filename
* @return InputStream, or null if not found.
*/
@Override
public InputStream findResource(String filename) {
File f = new File(filename);
if (!f.exists())

View File

@@ -84,18 +84,22 @@ import org.luaj.vm2.lib.LibFunction;
*/
public class JseIoLib extends IoLib {
@Override
protected File wrapStdin() throws IOException {
return new StdinFile();
}
@Override
protected File wrapStdout() throws IOException {
return new StdoutFile(FTYPE_STDOUT);
}
@Override
protected File wrapStderr() throws IOException {
return new StdoutFile(FTYPE_STDERR);
}
@Override
protected File openFile(String filename, boolean readMode, boolean appendMode, boolean updateMode,
boolean binaryMode) throws IOException {
RandomAccessFile f = new RandomAccessFile(filename, readMode? "r": "rw");
@@ -108,11 +112,13 @@ public class JseIoLib extends IoLib {
return new FileImpl(f);
}
@Override
protected File openProgram(String prog, String mode) throws IOException {
final Process p = Runtime.getRuntime().exec(prog);
return "w".equals(mode)? new FileImpl(p.getOutputStream()): new FileImpl(p.getInputStream());
}
@Override
protected File tmpFile() throws IOException {
java.io.File f = java.io.File.createTempFile(".luaj", "bin");
f.deleteOnExit();
@@ -148,14 +154,17 @@ public class JseIoLib extends IoLib {
this(null, null, o);
}
@Override
public String tojstring() {
return "file (" + (this.closed? "closed": String.valueOf(this.hashCode())) + ")";
}
@Override
public boolean isstdfile() {
return file == null;
}
@Override
public void close() throws IOException {
closed = true;
if (file != null) {
@@ -163,11 +172,13 @@ public class JseIoLib extends IoLib {
}
}
@Override
public void flush() throws IOException {
if (os != null)
os.flush();
}
@Override
public void write(LuaString s) throws IOException {
if (os != null)
os.write(s.m_bytes, s.m_offset, s.m_length);
@@ -179,10 +190,12 @@ public class JseIoLib extends IoLib {
flush();
}
@Override
public boolean isclosed() {
return closed;
}
@Override
public int seek(String option, int pos) throws IOException {
if (file != null) {
if ("set".equals(option)) {
@@ -198,16 +211,19 @@ public class JseIoLib extends IoLib {
return 0;
}
@Override
public void setvbuf(String mode, int size) {
nobuffer = "no".equals(mode);
}
// get length remaining to read
@Override
public int remaining() throws IOException {
return file != null? (int) (file.length()-file.getFilePointer()): -1;
}
// peek ahead one character
@Override
public int peek() throws IOException {
if (is != null) {
is.mark(1);
@@ -225,6 +241,7 @@ public class JseIoLib extends IoLib {
}
// return char if read, -1 if eof, throw IOException on other exception
@Override
public int read() throws IOException {
if (is != null)
return is.read();
@@ -236,6 +253,7 @@ public class JseIoLib extends IoLib {
}
// return number of bytes read if positive, -1 if eof, throws IOException
@Override
public int read(byte[] bytes, int offset, int length) throws IOException {
if (file != null) {
return file.read(bytes, offset, length);
@@ -255,51 +273,63 @@ public class JseIoLib extends IoLib {
this.file_type = file_type;
}
@Override
public String tojstring() {
return "file (" + this.hashCode() + ")";
}
private final PrintStream getPrintStream() { return file_type == FTYPE_STDERR? globals.STDERR: globals.STDOUT; }
private PrintStream getPrintStream() { return file_type == FTYPE_STDERR? globals.STDERR: globals.STDOUT; }
@Override
public void write(LuaString string) throws IOException {
getPrintStream().write(string.m_bytes, string.m_offset, string.m_length);
}
@Override
public void flush() throws IOException {
getPrintStream().flush();
}
@Override
public boolean isstdfile() {
return true;
}
@Override
public void close() throws IOException {
// do not close std files.
}
@Override
public boolean isclosed() {
return false;
}
@Override
public int seek(String option, int bytecount) throws IOException {
return 0;
}
@Override
public void setvbuf(String mode, int size) {
}
@Override
public int remaining() throws IOException {
return 0;
}
@Override
public int peek() throws IOException, EOFException {
return 0;
}
@Override
public int read() throws IOException, EOFException {
return 0;
}
@Override
public int read(byte[] bytes, int offset, int length) throws IOException {
return 0;
}
@@ -309,39 +339,49 @@ public class JseIoLib extends IoLib {
private StdinFile() {
}
@Override
public String tojstring() {
return "file (" + this.hashCode() + ")";
}
@Override
public void write(LuaString string) throws IOException {
}
@Override
public void flush() throws IOException {
}
@Override
public boolean isstdfile() {
return true;
}
@Override
public void close() throws IOException {
// do not close std files.
}
@Override
public boolean isclosed() {
return false;
}
@Override
public int seek(String option, int bytecount) throws IOException {
return 0;
}
@Override
public void setvbuf(String mode, int size) {
}
@Override
public int remaining() throws IOException {
return -1;
}
@Override
public int peek() throws IOException, EOFException {
globals.STDIN.mark(1);
int c = globals.STDIN.read();
@@ -349,10 +389,12 @@ public class JseIoLib extends IoLib {
return c;
}
@Override
public int read() throws IOException, EOFException {
return globals.STDIN.read();
}
@Override
public int read(byte[] bytes, int offset, int length) throws IOException {
return globals.STDIN.read(bytes, offset, length);
}

View File

@@ -90,6 +90,7 @@ public class JseMathLib extends org.luaj.vm2.lib.MathLib {
* @param env the environment to load into, which must be a Globals
* instance.
*/
@Override
public LuaValue call(LuaValue modname, LuaValue env) {
super.call(modname, env);
LuaValue math = env.get("math");
@@ -108,28 +109,34 @@ public class JseMathLib extends org.luaj.vm2.lib.MathLib {
}
static final class acos extends UnaryOp {
@Override
protected double call(double d) { return Math.acos(d); }
}
static final class asin extends UnaryOp {
@Override
protected double call(double d) { return Math.asin(d); }
}
static final class atan2 extends TwoArgFunction {
@Override
public LuaValue call(LuaValue x, LuaValue y) {
return valueOf(Math.atan2(x.checkdouble(), y.optdouble(1)));
}
}
static final class cosh extends UnaryOp {
@Override
protected double call(double d) { return Math.cosh(d); }
}
static final class exp extends UnaryOp {
@Override
protected double call(double d) { return Math.exp(d); }
}
static final class log extends TwoArgFunction {
@Override
public LuaValue call(LuaValue x, LuaValue base) {
double nat = Math.log(x.checkdouble());
double b = base.optdouble(Math.E);
@@ -140,18 +147,22 @@ public class JseMathLib extends org.luaj.vm2.lib.MathLib {
}
static final class pow extends BinaryOp {
@Override
protected double call(double x, double y) { return Math.pow(x, y); }
}
static final class sinh extends UnaryOp {
@Override
protected double call(double d) { return Math.sinh(d); }
}
static final class tanh extends UnaryOp {
@Override
protected double call(double d) { return Math.tanh(d); }
}
/** Faster, better version of pow() used by arithmetic operator ^ */
@Override
public double dpow_lib(double a, double b) {
return Math.pow(a, b);
}

View File

@@ -99,11 +99,13 @@ public class JseOsLib extends org.luaj.vm2.lib.OsLib {
public JseOsLib() {
}
@Override
protected String getenv(String varname) {
String s = System.getenv(varname);
return s != null? s: System.getProperty(varname);
}
@Override
protected Varargs execute(String command) {
int exitValue;
try {
@@ -120,6 +122,7 @@ public class JseOsLib extends org.luaj.vm2.lib.OsLib {
return varargsOf(NIL, valueOf("signal"), valueOf(exitValue));
}
@Override
protected void remove(String filename) throws IOException {
File f = new File(filename);
if (!f.exists())
@@ -128,6 +131,7 @@ public class JseOsLib extends org.luaj.vm2.lib.OsLib {
throw new IOException("Failed to delete");
}
@Override
protected void rename(String oldname, String newname) throws IOException {
File f = new File(oldname);
if (!f.exists())
@@ -136,6 +140,7 @@ public class JseOsLib extends org.luaj.vm2.lib.OsLib {
throw new IOException("Failed to rename");
}
@Override
protected String tmpname() {
try {
java.io.File f = java.io.File.createTempFile(TMP_PREFIX, TMP_SUFFIX);

View File

@@ -102,7 +102,7 @@ public class JseProcess {
/** Create a thread to copy bytes from input to output. */
private Thread copyBytes(final InputStream input, final OutputStream output, final InputStream ownedInput,
final OutputStream ownedOutput) {
Thread t = (new CopyThread(output, ownedOutput, ownedInput, input));
Thread t = new CopyThread(output, ownedOutput, ownedInput, input);
t.start();
return t;
}
@@ -120,6 +120,7 @@ public class JseProcess {
this.input = input;
}
@Override
public void run() {
try {
byte[] buf = new byte[1024];

View File

@@ -27,10 +27,11 @@ public class JseStringLib extends org.luaj.vm2.lib.StringLib {
public JseStringLib() {
}
@Override
protected String format(String src, double x) {
String out;
try {
out = String.format(src, new Object[] { Double.valueOf(x) });
out = String.format(src, Double.valueOf(x));
} catch (Throwable e) {
out = super.format(src, x);
}

View File

@@ -108,6 +108,7 @@ public class LuajavaLib extends VarArgFunction {
public LuajavaLib() {
}
@Override
public Varargs invoke(Varargs args) {
try {
switch (opcode) {
@@ -129,8 +130,8 @@ public class LuajavaLib extends VarArgFunction {
case NEW: {
// get constructor
final LuaValue c = args.checkvalue(1);
final Class clazz = (opcode == NEWINSTANCE? classForName(c.tojstring())
: (Class) c.checkuserdata(Class.class));
final Class clazz = opcode == NEWINSTANCE? classForName(c.tojstring())
: (Class) c.checkuserdata(Class.class);
final Varargs consargs = args.subargs(2);
return JavaClass.forClass(clazz).getConstructor().invoke(consargs);
}
@@ -160,8 +161,8 @@ public class LuajavaLib extends VarArgFunction {
String classname = args.checkjstring(1);
String methodname = args.checkjstring(2);
Class clazz = classForName(classname);
Method method = clazz.getMethod(methodname, new Class[] {});
Object result = method.invoke(clazz, new Object[] {});
Method method = clazz.getMethod(methodname);
Object result = method.invoke(clazz);
if (result instanceof LuaValue) {
return (LuaValue) result;
} else {
@@ -192,12 +193,13 @@ public class LuajavaLib extends VarArgFunction {
this.lobj = lobj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String name = method.getName();
LuaValue func = lobj.get(name);
if (func.isnil())
return null;
boolean isvarargs = ((method.getModifiers() & METHOD_MODIFIERS_VARARGS) != 0);
boolean isvarargs = (method.getModifiers() & METHOD_MODIFIERS_VARARGS) != 0;
int n = args != null? args.length: 0;
LuaValue[] v;
if (isvarargs) {

View File

@@ -18,9 +18,10 @@ public class BasicBlock {
this.pc0 = this.pc1 = pc0;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append((pc0+1) + "-" + (pc1+1) + (prev != null? " prv: " + str(prev, 1): "")
sb.append(pc0 + 1 + "-" + (pc1+1) + (prev != null? " prv: " + str(prev, 1): "")
+ (next != null? " nxt: " + str(next, 0): "") + "\n");
return sb.toString();
}
@@ -82,6 +83,7 @@ public class BasicBlock {
this.blocks = blocks;
}
@Override
public void visitBranch(int pc0, int pc1) {
if (blocks[pc0].next == null)
blocks[pc0].next = new BasicBlock[nnext[pc0]];
@@ -102,6 +104,7 @@ public class BasicBlock {
this.nprev = nprev;
}
@Override
public void visitBranch(int pc0, int pc1) {
nnext[pc0]++;
nprev[pc1]++;
@@ -116,11 +119,13 @@ public class BasicBlock {
this.isend = isend;
}
@Override
public void visitBranch(int pc0, int pc1) {
isend[pc0] = true;
isbeg[pc1] = true;
}
@Override
public void visitReturn(int pc) {
isend[pc] = true;
}

View File

@@ -177,11 +177,9 @@ public class JavaBuilder {
superclassType = p.numparams;
if (p.is_vararg != 0 || superclassType >= SUPERTYPE_VARARGS)
superclassType = SUPERTYPE_VARARGS;
for (int i = 0, n = p.code.length; i < n; i++) {
int inst = p.code[i];
for (int inst : p.code) {
int o = Lua.GET_OPCODE(inst);
if ((o == Lua.OP_TAILCALL)
|| ((o == Lua.OP_RETURN) && (Lua.GETARG_B(inst) < 1 || Lua.GETARG_B(inst) > 2))) {
if (o == Lua.OP_TAILCALL || o == Lua.OP_RETURN && (Lua.GETARG_B(inst) < 1 || Lua.GETARG_B(inst) > 2)) {
superclassType = SUPERTYPE_VARARGS;
break;
}
@@ -244,7 +242,7 @@ public class JavaBuilder {
} else {
// fixed arg function between 0 and 3 arguments
for (slot = 0; slot < p.numparams; slot++) {
this.plainSlotVars.put(Integer.valueOf(slot), Integer.valueOf(1+slot));
this.plainSlotVars.put(slot, 1+slot);
if (pi.isUpvalueCreate(-1, slot)) {
append(new ALOAD(1+slot));
storeLocal(-1, slot);
@@ -355,22 +353,22 @@ public class JavaBuilder {
}
public void loadBoolean(boolean b) {
String field = (b? "TRUE": "FALSE");
String field = b? "TRUE": "FALSE";
append(factory.createFieldAccess(STR_LUAVALUE, field, TYPE_LUABOOLEAN, Constants.GETSTATIC));
}
private Map<Integer, Integer> plainSlotVars = new HashMap<Integer, Integer>();
private Map<Integer, Integer> upvalueSlotVars = new HashMap<Integer, Integer>();
private Map<Integer, LocalVariableGen> localVarGenBySlot = new HashMap<Integer, LocalVariableGen>();
private final Map<Integer, Integer> plainSlotVars = new HashMap<>();
private final Map<Integer, Integer> upvalueSlotVars = new HashMap<>();
private final Map<Integer, LocalVariableGen> localVarGenBySlot = new HashMap<>();
private int findSlot(int slot, Map<Integer, Integer> map, String prefix, Type type) {
Integer islot = Integer.valueOf(slot);
Integer islot = slot;
if (map.containsKey(islot))
return ((Integer) map.get(islot)).intValue();
return map.get(islot).intValue();
String name = prefix+slot;
LocalVariableGen local = mg.addLocalVariable(name, type, null, null);
int index = local.getIndex();
map.put(islot, Integer.valueOf(index));
map.put(islot, index);
localVarGenBySlot.put(islot, local);
return index;
}
@@ -727,7 +725,7 @@ public class JavaBuilder {
append(factory.createFieldAccess(protoname, destname, uptype, Constants.PUTFIELD));
}
private Map<LuaValue, String> constants = new HashMap<LuaValue, String>();
private final Map<LuaValue, String> constants = new HashMap<>();
public void loadConstant(LuaValue value) {
switch (value.type()) {
@@ -739,7 +737,7 @@ public class JavaBuilder {
break;
case LuaValue.TNUMBER:
case LuaValue.TSTRING:
String name = (String) constants.get(value);
String name = constants.get(value);
if (name == null) {
name = value.type() == LuaValue.TNUMBER? value.isinttype()? createLuaIntegerField(value.checkint())
: createLuaDoubleField(value.checkdouble()): createLuaStringField(value.checkstring());
@@ -786,7 +784,7 @@ public class JavaBuilder {
} else {
char[] c = new char[ls.m_length];
for (int j = 0; j < ls.m_length; j++)
c[j] = (char) (0xff & (int) (ls.m_bytes[ls.m_offset+j]));
c[j] = (char) (0xff & ls.m_bytes[ls.m_offset+j]);
init.append(new PUSH(cp, new String(c)));
init.append(
factory.createInvoke(STR_STRING, "toCharArray", TYPE_CHARARRAY, Type.NO_ARGS, Constants.INVOKEVIRTUAL));
@@ -845,10 +843,10 @@ public class JavaBuilder {
}
public void setVarStartEnd(int slot, int start_pc, int end_pc, String name) {
Integer islot = Integer.valueOf(slot);
Integer islot = slot;
if (localVarGenBySlot.containsKey(islot)) {
name = name.replaceAll("[^a-zA-Z0-9]", "_");
LocalVariableGen l = (LocalVariableGen) localVarGenBySlot.get(islot);
LocalVariableGen l = localVarGenBySlot.get(islot);
l.setEnd(lastInstrHandles[end_pc-1]);
if (start_pc > 1)
l.setStart(lastInstrHandles[start_pc-2]);

View File

@@ -66,9 +66,7 @@ public class JavaGen {
Prototype p = pi.prototype;
int vresultbase = -1;
for (int bi = 0; bi < pi.blocklist.length; bi++) {
BasicBlock b0 = pi.blocklist[bi];
for (BasicBlock b0 : pi.blocklist) {
// convert upvalues that are phi-variables
for (int slot = 0; slot < p.maxstacksize; slot++) {
int pc = b0.pc0;
@@ -216,19 +214,19 @@ public class JavaGen {
loadLocalOrConstant(p, builder, pc, b);
loadLocalOrConstant(p, builder, pc, c);
builder.compareop(o);
builder.addBranch(pc, (a != 0? JavaBuilder.BRANCH_IFEQ: JavaBuilder.BRANCH_IFNE), pc+2);
builder.addBranch(pc, a != 0? JavaBuilder.BRANCH_IFEQ: JavaBuilder.BRANCH_IFNE, pc+2);
break;
case Lua.OP_TEST: /* A C if not (R(A) <=> C) then pc++ */
builder.loadLocal(pc, a);
builder.toBoolean();
builder.addBranch(pc, (c != 0? JavaBuilder.BRANCH_IFEQ: JavaBuilder.BRANCH_IFNE), pc+2);
builder.addBranch(pc, c != 0? JavaBuilder.BRANCH_IFEQ: JavaBuilder.BRANCH_IFNE, pc+2);
break;
case Lua.OP_TESTSET: /* A B C if (R(B) <=> C) then R(A):= R(B) else pc++ */
builder.loadLocal(pc, b);
builder.toBoolean();
builder.addBranch(pc, (c != 0? JavaBuilder.BRANCH_IFEQ: JavaBuilder.BRANCH_IFNE), pc+2);
builder.addBranch(pc, c != 0? JavaBuilder.BRANCH_IFEQ: JavaBuilder.BRANCH_IFNE, pc+2);
builder.loadLocal(pc, b);
builder.storeLocal(pc, a);
break;

View File

@@ -30,7 +30,7 @@ import org.luaj.vm2.Prototype;
******************************************************************************/
public class JavaLoader extends ClassLoader {
private Map<String, byte[]> unloaded = new HashMap<String, byte[]>();
private final Map<String, byte[]> unloaded = new HashMap<>();
public JavaLoader() {
}
@@ -63,8 +63,9 @@ public class JavaLoader extends ClassLoader {
include(jg.inners[i]);
}
@Override
public Class findClass(String classname) throws ClassNotFoundException {
byte[] bytes = (byte[]) unloaded.get(classname);
byte[] bytes = unloaded.get(classname);
if (bytes != null)
return defineClass(classname, bytes, 0, bytes.length);
return super.findClass(classname);

View File

@@ -107,6 +107,7 @@ public class LuaJC implements Globals.Loader {
insert(h, gen.inners[i]);
}
@Override
public LuaFunction load(Prototype p, String name, LuaValue globals) throws IOException {
String luaname = toStandardLuaFileName(name);
String classname = toStandardJavaClassName(luaname);
@@ -120,8 +121,7 @@ public class LuaJC implements Globals.Loader {
for (int i = 0, n = stub.length(); i < n; ++i) {
final char c = stub.charAt(i);
classname.append(
(((i == 0) && Character.isJavaIdentifierStart(c)) || ((i > 0) && Character.isJavaIdentifierPart(c)))? c
: '_');
i == 0 && Character.isJavaIdentifierStart(c) || i > 0 && Character.isJavaIdentifierPart(c)? c: '_');
}
return classname.toString();
}
@@ -133,7 +133,6 @@ public class LuaJC implements Globals.Loader {
}
private static String toStub(String s) {
String stub = s.endsWith(".lua")? s.substring(0, s.length()-4): s;
return stub;
return s.endsWith(".lua")? s.substring(0, s.length()-4): s;
}
}

View File

@@ -57,6 +57,7 @@ public class ProtoInfo {
findUpvalues();
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
@@ -64,12 +65,11 @@ public class ProtoInfo {
sb.append("proto '" + name + "'\n");
// upvalues from outer scopes
for (int i = 0, n = (upvals != null? upvals.length: 0); i < n; i++)
for (int i = 0, n = upvals != null? upvals.length: 0; i < n; i++)
sb.append(" up[" + i + "]: " + upvals[i] + "\n");
// basic blocks
for (int i = 0; i < blocklist.length; i++) {
BasicBlock b = blocklist[i];
for (BasicBlock b : blocklist) {
int pc0 = b.pc0;
sb.append(" block " + b.toString());
appendOpenUps(sb, -1);
@@ -84,9 +84,9 @@ public class ProtoInfo {
sb.append(" ");
for (int j = 0; j < prototype.maxstacksize; j++) {
VarInfo v = vars[j][pc];
String u = (v == null? ""
: v.upvalue != null? !v.upvalue.rw? "[C] ": (v.allocupvalue && v.pc == pc? "[*] ": "[] ")
: " ");
String u = v == null? ""
: v.upvalue != null? !v.upvalue.rw? "[C] ": v.allocupvalue && v.pc == pc? "[*] ": "[] "
: " ";
String s = v == null? "null ": String.valueOf(v);
sb.append(s+u);
}
@@ -115,7 +115,7 @@ public class ProtoInfo {
private void appendOpenUps(StringBuffer sb, int pc) {
for (int j = 0; j < prototype.maxstacksize; j++) {
VarInfo v = (pc < 0? params[j]: vars[j][pc]);
VarInfo v = pc < 0? params[j]: vars[j][pc];
if (v != null && v.pc == pc && v.allocupvalue) {
sb.append(" open: " + v.upvalue + "\n");
}
@@ -132,8 +132,8 @@ public class ProtoInfo {
v[i] = new VarInfo[n];
// process instructions
for (int bi = 0; bi < blocklist.length; bi++) {
BasicBlock b0 = blocklist[bi];
for (BasicBlock element : blocklist) {
BasicBlock b0 = element;
// input from previous blocks
int nprev = b0.prev != null? b0.prev.length: 0;
@@ -399,8 +399,7 @@ public class ProtoInfo {
}
private void replaceTrivialPhiVariables() {
for (int i = 0; i < blocklist.length; i++) {
BasicBlock b0 = blocklist[i];
for (BasicBlock b0 : blocklist) {
for (int slot = 0; slot < prototype.maxstacksize; slot++) {
VarInfo vold = vars[slot][b0.pc0];
VarInfo vnew = vold.resolvePhiVariableValues();

View File

@@ -60,8 +60,7 @@ public class UpvalInfo {
private boolean includePosteriorVarsCheckLoops(VarInfo prior) {
boolean loopDetected = false;
for (int i = 0, n = pi.blocklist.length; i < n; i++) {
BasicBlock b = pi.blocklist[i];
for (BasicBlock b : pi.blocklist) {
VarInfo v = pi.vars[slot][b.pc1];
if (v == prior) {
for (int j = 0, m = b.next != null? b.next.length: 0; j < m; j++) {
@@ -86,8 +85,7 @@ public class UpvalInfo {
}
private void includePriorVarsIgnoreLoops(VarInfo poster) {
for (int i = 0, n = pi.blocklist.length; i < n; i++) {
BasicBlock b = pi.blocklist[i];
for (BasicBlock b : pi.blocklist) {
VarInfo v = pi.vars[slot][b.pc0];
if (v == poster) {
for (int j = 0, m = b.prev != null? b.prev.length: 0; j < m; j++) {
@@ -118,6 +116,7 @@ public class UpvalInfo {
var[nvars++] = v;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(pi.name);
@@ -141,8 +140,8 @@ public class UpvalInfo {
if (v != null && v.upvalue != this)
return true;
} else {
for (int i = 0, n = b.prev.length; i < n; i++) {
v = pi.vars[slot][b.prev[i].pc1];
for (BasicBlock element : b.prev) {
v = pi.vars[slot][element.pc1];
if (v != null && v.upvalue != this)
return true;
}

View File

@@ -37,8 +37,9 @@ public class VarInfo {
this.pc = pc;
}
@Override
public String toString() {
return slot < 0? "x.x": (slot + "." + pc);
return slot < 0? "x.x": slot + "." + pc;
}
/**
@@ -64,6 +65,7 @@ public class VarInfo {
super(slot, pc);
}
@Override
public String toString() {
return slot + ".p";
}
@@ -74,6 +76,7 @@ public class VarInfo {
super(slot, pc);
}
@Override
public String toString() {
return "nil";
}
@@ -88,13 +91,15 @@ public class VarInfo {
this.pi = pi;
}
@Override
public boolean isPhiVar() { return true; }
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(super.toString());
sb.append("={");
for (int i = 0, n = (values != null? values.length: 0); i < n; i++) {
for (int i = 0, n = values != null? values.length: 0; i < n; i++) {
if (i > 0)
sb.append(",");
sb.append(String.valueOf(values[i]));
@@ -103,6 +108,7 @@ public class VarInfo {
return sb.toString();
}
@Override
public VarInfo resolvePhiVariableValues() {
Set visitedBlocks = new HashSet();
Set vars = new HashSet();
@@ -124,6 +130,7 @@ public class VarInfo {
return null;
}
@Override
protected void collectUniqueValues(Set visitedBlocks, Set vars) {
BasicBlock b = pi.blocks[pc];
if (pc == 0)

View File

@@ -21,11 +21,29 @@
******************************************************************************/
package org.luaj.vm2.script;
import java.io.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import javax.script.*;
import javax.script.AbstractScriptEngine;
import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptException;
import javax.script.SimpleBindings;
import org.luaj.vm2.*;
import org.luaj.vm2.Globals;
import org.luaj.vm2.Lua;
import org.luaj.vm2.LuaClosure;
import org.luaj.vm2.LuaError;
import org.luaj.vm2.LuaFunction;
import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;
import org.luaj.vm2.lib.ThreeArgFunction;
import org.luaj.vm2.lib.TwoArgFunction;
import org.luaj.vm2.lib.jse.CoerceJavaToLua;
@@ -53,7 +71,7 @@ public class LuaScriptEngine extends AbstractScriptEngine implements ScriptEngin
private static final ScriptEngineFactory myFactory = new LuaScriptEngineFactory();
private LuajContext context;
private final LuajContext context;
public LuaScriptEngine() {
// set up context
@@ -80,15 +98,12 @@ public class LuaScriptEngine extends AbstractScriptEngine implements ScriptEngin
@Override
public CompiledScript compile(Reader script) throws ScriptException {
try {
InputStream is = new Utf8Encoder(script);
try {
try (InputStream is = new Utf8Encoder(script)) {
final Globals g = context.globals;
final LuaFunction f = g.load(script, "script").checkfunction();
return new LuajCompiledScript(f, g);
} catch (LuaError lee) {
throw new ScriptException(lee.getMessage());
} finally {
is.close();
}
} catch (Exception e) {
throw new ScriptException("eval threw " + e.toString());
@@ -137,16 +152,20 @@ public class LuaScriptEngine extends AbstractScriptEngine implements ScriptEngin
this.compiling_globals = compiling_globals;
}
@Override
public ScriptEngine getEngine() { return LuaScriptEngine.this; }
@Override
public Object eval() throws ScriptException {
return eval(getContext());
}
@Override
public Object eval(Bindings bindings) throws ScriptException {
return eval(((LuajContext) getContext()).globals, bindings);
}
@Override
public Object eval(ScriptContext context) throws ScriptException {
return eval(((LuajContext) context).globals, context.getBindings(ScriptContext.ENGINE_SCOPE));
}
@@ -179,6 +198,7 @@ public class LuaScriptEngine extends AbstractScriptEngine implements ScriptEngin
this.r = r;
}
@Override
public int read() throws IOException {
if (n > 0)
return buf[--n];
@@ -187,12 +207,12 @@ public class LuaScriptEngine extends AbstractScriptEngine implements ScriptEngin
return c;
n = 0;
if (c < 0x800) {
buf[n++] = (0x80 | (c & 0x3f));
return (0xC0 | ((c>>6) & 0x1f));
buf[n++] = 0x80 | c & 0x3f;
return 0xC0 | c>>6 & 0x1f;
} else {
buf[n++] = (0x80 | (c & 0x3f));
buf[n++] = (0x80 | ((c>>6) & 0x3f));
return (0xE0 | ((c>>12) & 0x0f));
buf[n++] = 0x80 | c & 0x3f;
buf[n++] = 0x80 | c>>6 & 0x3f;
return 0xE0 | c>>12 & 0x0f;
}
}
}
@@ -201,6 +221,7 @@ public class LuaScriptEngine extends AbstractScriptEngine implements ScriptEngin
BindingsMetatable(final Bindings bindings) {
this.rawset(LuaValue.INDEX, new TwoArgFunction() {
@Override
public LuaValue call(LuaValue table, LuaValue key) {
if (key.isstring())
return toLua(bindings.get(key.tojstring()));
@@ -209,6 +230,7 @@ public class LuaScriptEngine extends AbstractScriptEngine implements ScriptEngin
}
});
this.rawset(LuaValue.NEWINDEX, new ThreeArgFunction() {
@Override
public LuaValue call(LuaValue table, LuaValue key, LuaValue value) {
if (key.isstring()) {
final String k = key.tojstring();
@@ -240,8 +262,8 @@ public class LuaScriptEngine extends AbstractScriptEngine implements ScriptEngin
case LuaValue.TUSERDATA:
return luajValue.checkuserdata(Object.class);
case LuaValue.TNUMBER:
return luajValue.isinttype()? (Object) new Integer(luajValue.toint())
: (Object) new Double(luajValue.todouble());
return luajValue.isinttype()? (Object) Integer.valueOf(luajValue.toint())
: (Object) Double.valueOf(luajValue.todouble());
default:
return luajValue;
}

View File

@@ -41,9 +41,9 @@ public class LuaScriptEngineFactory implements ScriptEngineFactory {
private static final String[] NAMES = { "lua", "luaj", };
private List<String> extensions;
private List<String> mimeTypes;
private List<String> names;
private final List<String> extensions;
private final List<String> mimeTypes;
private final List<String> names;
public LuaScriptEngineFactory() {
extensions = Arrays.asList(EXTENSIONS);
@@ -51,24 +51,33 @@ public class LuaScriptEngineFactory implements ScriptEngineFactory {
names = Arrays.asList(NAMES);
}
@Override
public String getEngineName() { return getScriptEngine().get(ScriptEngine.ENGINE).toString(); }
@Override
public String getEngineVersion() { return getScriptEngine().get(ScriptEngine.ENGINE_VERSION).toString(); }
@Override
public List<String> getExtensions() { return extensions; }
@Override
public List<String> getMimeTypes() { return mimeTypes; }
@Override
public List<String> getNames() { return names; }
@Override
public String getLanguageName() { return getScriptEngine().get(ScriptEngine.LANGUAGE).toString(); }
@Override
public String getLanguageVersion() { return getScriptEngine().get(ScriptEngine.LANGUAGE_VERSION).toString(); }
@Override
public Object getParameter(String key) {
return getScriptEngine().get(key).toString();
}
@Override
public String getMethodCallSyntax(String obj, String m, String... args) {
StringBuffer sb = new StringBuffer();
sb.append(obj + ":" + m + "(");
@@ -83,10 +92,12 @@ public class LuaScriptEngineFactory implements ScriptEngineFactory {
return sb.toString();
}
@Override
public String getOutputStatement(String toDisplay) {
return "print(" + toDisplay + ")";
}
@Override
public String getProgram(String... statements) {
StringBuffer sb = new StringBuffer();
int len = statements.length;
@@ -99,5 +110,6 @@ public class LuaScriptEngineFactory implements ScriptEngineFactory {
return sb.toString();
}
@Override
public ScriptEngine getScriptEngine() { return new LuaScriptEngine(); }
}

View File

@@ -106,22 +106,27 @@ public class LuajContext extends SimpleScriptContext implements ScriptContext {
this.w = w;
}
@Override
public void write(int b) throws IOException {
w.write(new String(new byte[] { (byte) b }));
}
@Override
public void write(byte[] b, int o, int l) throws IOException {
w.write(new String(b, o, l));
}
@Override
public void write(byte[] b) throws IOException {
w.write(new String(b));
}
@Override
public void close() throws IOException {
w.close();
}
@Override
public void flush() throws IOException {
w.flush();
}
@@ -134,6 +139,7 @@ public class LuajContext extends SimpleScriptContext implements ScriptContext {
this.r = r;
}
@Override
public int read() throws IOException {
return r.read();
}

View File

@@ -53,6 +53,7 @@ public class DefaultLauncher implements Launcher {
}
/** Launches the script with chunk name 'main' */
@Override
public Object[] launch(String script, Object[] arg) {
return launchChunk(g.load(script, "main"), arg);
}
@@ -60,11 +61,13 @@ public class DefaultLauncher implements Launcher {
/**
* Launches the script with chunk name 'main' and loading using modes 'bt'
*/
@Override
public Object[] launch(InputStream script, Object[] arg) {
return launchChunk(g.load(script, "main", "bt", g), arg);
}
/** Launches the script with chunk name 'main' */
@Override
public Object[] launch(Reader script, Object[] arg) {
return launchChunk(g.load(script, "main"), arg);
}

View File

@@ -54,7 +54,7 @@ public interface Launcher {
* @param arg Optional arguments supplied to the script.
* @return return values from the script.
*/
public Object[] launch(String script, Object[] arg);
Object[] launch(String script, Object[] arg);
/**
* Launch a script from an InputStream.
@@ -63,7 +63,7 @@ public interface Launcher {
* @param arg Optional arguments supplied to the script.
* @return return values from the script.
*/
public Object[] launch(InputStream script, Object[] arg);
Object[] launch(InputStream script, Object[] arg);
/**
* Launch a script from a Reader.
@@ -72,5 +72,5 @@ public interface Launcher {
* @param arg Optional arguments supplied to the script.
* @return return values from the script.
*/
public Object[] launch(Reader script, Object[] arg);
Object[] launch(Reader script, Object[] arg);
}

View File

@@ -72,7 +72,7 @@ public class LuajClassLoader extends ClassLoader {
static final String launcherInterfaceRoot = Launcher.class.getName();
/** Local cache of classes loaded by this loader. */
Map<String, Class<?>> classes = new HashMap<String, Class<?>>();
Map<String, Class<?>> classes = new HashMap<>();
/**
* Construct a default {@link Launcher} instance that will load classes in
@@ -127,6 +127,7 @@ public class LuajClassLoader extends ClassLoader {
return classname.startsWith(luajPackageRoot) && !classname.startsWith(launcherInterfaceRoot);
}
@Override
public Class<?> loadClass(String classname) throws ClassNotFoundException {
if (classes.containsKey(classname))
return classes.get(classname);