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

View File

@@ -11,7 +11,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -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

@@ -11,7 +11,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -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

@@ -11,7 +11,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE

View File

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE

View File

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE

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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE

View File

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE

View File

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE

View File

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -58,17 +58,18 @@ import org.luaj.vm2.LuaValue;
* The method {@link CoerceJavaToLua#coerce(Object)} looks as the type and
* dimesioning of the argument and tries to guess the best fit for corrsponding
* lua scalar, table, or table of tables.
*
*
* @see CoerceJavaToLua#coerce(Object)
* @see org.luaj.vm2.lib.jse.LuajavaLib
*/
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,37 +101,43 @@ 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?
// should be userdata?
return new JavaArray(javaValue);
}
}
private static final class LuaCoercion implements Coercion {
@Override
public LuaValue coerce(Object javaValue) {
return (LuaValue) javaValue;
}
@@ -165,7 +175,7 @@ public class CoerceJavaToLua {
* {@code byte[]} will become {@link LuaString}; types inheriting from
* {@link LuaValue} will be returned without coercion; other types will
* become {@link LuaUserdata}.
*
*
* @param o Java object needing conversion
* @return {@link LuaValue} corresponding to the supplied Java value.
* @see LuaValue

View File

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -53,7 +53,7 @@ import org.luaj.vm2.LuaValue;
* <p>
* For data in lua tables, the various methods on {@link LuaTable} can be used
* directly to convert data to something more useful.
*
*
* @see org.luaj.vm2.lib.jse.LuajavaLib
* @see CoerceJavaToLua
*/
@@ -63,15 +63,15 @@ 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
*
*
* @param value LuaValue to coerce
* @param clazz Class to coerce into
* @return Object of type clazz (or a subclass) with the corresponding
@@ -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: {
@@ -293,7 +305,7 @@ public class CoerceLuaToJava {
/**
* Determine levels of inheritance between a base class and a subclass
*
*
* @param baseclass base class to look for
* @param subclass class from which to start looking
* @return number of inheritance levels between subclass and baseclass, or
@@ -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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -35,13 +35,14 @@ import org.luaj.vm2.lib.OneArgFunction;
* <p>
* This class is not used directly. It is returned by calls to
* {@link CoerceJavaToLua#coerce(Object)} when an array is supplied.
*
*
* @see CoerceJavaToLua
* @see CoerceLuaToJava
*/
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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -42,7 +42,7 @@ import org.luaj.vm2.LuaValue;
* <p>
* This class is not used directly. It is returned by calls to
* {@link CoerceJavaToLua#coerce(Object)} when a Class is supplied.
*
*
* @see CoerceJavaToLua
* @see CoerceLuaToJava
*/
@@ -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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -40,7 +40,7 @@ import org.luaj.vm2.lib.VarArgFunction;
* <p>
* This class is not used directly. It is returned by calls to
* {@link JavaClass#new(LuaValue key)} when the value of key is "new".
*
*
* @see CoerceJavaToLua
* @see CoerceLuaToJava
*/
@@ -66,6 +66,7 @@ class JavaConstructor extends JavaMember {
this.constructor = c;
}
@Override
public Varargs invoke(Varargs args) {
Object[] a = convertArgs(args);
try {
@@ -93,20 +94,21 @@ 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;
}
}
// any match?
// any match?
if (best == null)
LuaValue.error("no coercible public method");

View File

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -34,7 +34,7 @@ import org.luaj.vm2.LuaValue;
* <p>
* This class is not used directly. It is returned by calls to
* {@link CoerceJavaToLua#coerce(Object)} when a subclass of Object is supplied.
*
*
* @see CoerceJavaToLua
* @see CoerceLuaToJava
*/
@@ -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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -33,7 +33,7 @@ import org.luaj.vm2.lib.jse.CoerceLuaToJava.Coercion;
* <p>
* This class is not used directly. It is an abstract base class for
* {@link JavaConstructor} and {@link JavaMethod}.
*
*
* @see JavaConstructor
* @see JavaMethod
* @see CoerceJavaToLua
@@ -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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -39,7 +39,7 @@ import org.luaj.vm2.Varargs;
* <p>
* This class is not used directly. It is returned by calls to calls to
* {@link JavaInstance#get(LuaValue key)} when a method is named.
*
*
* @see CoerceJavaToLua
* @see CoerceLuaToJava
*/
@@ -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,17 +151,17 @@ 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;
}
}
// any match?
// any match?
if (best == null)
LuaValue.error("no coercible public method");

View File

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -47,7 +47,7 @@ import org.luaj.vm2.lib.ResourceFinder;
* <p>
* Typically, this library is included as part of a call to
* {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()}
*
*
* <pre>
* {
* &#64;code
@@ -59,7 +59,7 @@ import org.luaj.vm2.lib.ResourceFinder;
* For special cases where the smallest possible footprint is desired, a minimal
* set of libraries could be loaded directly via {@link Globals#load(LuaValue)}
* using code such as:
*
*
* <pre>
* {
* &#64;code
@@ -73,7 +73,7 @@ import org.luaj.vm2.lib.ResourceFinder;
* case.
* <p>
* This is a direct port of the corresponding library in C.
*
*
* @see Globals
* @see BaseLib
* @see ResourceFinder
@@ -95,11 +95,12 @@ public class JseBaseLib extends org.luaj.vm2.lib.BaseLib {
* <P>
* Specifically, extend the library loading to set the default value for
* {@link Globals#STDIN}
*
*
* @param modname the module name supplied if this is loaded via 'require'.
* @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;
@@ -109,17 +110,18 @@ public class JseBaseLib extends org.luaj.vm2.lib.BaseLib {
/**
* Try to open a file in the current working directory, or fall back to base
* opener if not found.
*
*
* This implementation attempts to open the file using new File(filename).
* It falls back to the base implementation that looks it up as a resource
* in the class path if not found as a plain file.
*
*
* @see org.luaj.vm2.lib.BaseLib
* @see org.luaj.vm2.lib.ResourceFinder
*
*
* @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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -44,7 +44,7 @@ import org.luaj.vm2.lib.LibFunction;
* <p>
* Typically, this library is included as part of a call to
* {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()}
*
*
* <pre>
* {
* &#64;code
@@ -56,7 +56,7 @@ import org.luaj.vm2.lib.LibFunction;
* For special cases where the smallest possible footprint is desired, a minimal
* set of libraries could be loaded directly via {@link Globals#load(LuaValue)}
* using code such as:
*
*
* <pre>
* {
* &#64;code
@@ -73,7 +73,7 @@ import org.luaj.vm2.lib.LibFunction;
* <p>
* This has been implemented to match as closely as possible the behavior in the
* corresponding library in C.
*
*
* @see LibFunction
* @see org.luaj.vm2.lib.jse.JsePlatform
* @see org.luaj.vm2.lib.jme.JmePlatform
@@ -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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -35,7 +35,7 @@ import org.luaj.vm2.lib.TwoArgFunction;
* <p>
* Typically, this library is included as part of a call to
* {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()}
*
*
* <pre>
* {
* &#64;code
@@ -47,7 +47,7 @@ import org.luaj.vm2.lib.TwoArgFunction;
* For special cases where the smallest possible footprint is desired, a minimal
* set of libraries could be loaded directly via {@link Globals#load(LuaValue)}
* using code such as:
*
*
* <pre>
* {
* &#64;code
@@ -64,7 +64,7 @@ import org.luaj.vm2.lib.TwoArgFunction;
* <p>
* This has been implemented to match as closely as possible the behavior in the
* corresponding library in C.
*
*
* @see LibFunction
* @see org.luaj.vm2.lib.jse.JsePlatform
* @see org.luaj.vm2.lib.jme.JmePlatform
@@ -85,11 +85,12 @@ public class JseMathLib extends org.luaj.vm2.lib.MathLib {
* Specifically, adds all library functions that can be implemented directly
* in JSE but not JME: acos, asin, atan, atan2, cosh, exp, log, pow, sinh,
* and tanh.
*
*
* @param modname the module name supplied if this is loaded via 'require'.
* @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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -49,7 +49,7 @@ import org.luaj.vm2.lib.OsLib;
* <p>
* Typically, this library is included as part of a call to
* {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()}
*
*
* <pre>
* {
* &#64;code
@@ -61,7 +61,7 @@ import org.luaj.vm2.lib.OsLib;
* For special cases where the smallest possible footprint is desired, a minimal
* set of libraries could be loaded directly via {@link Globals#load(LuaValue)}
* using code such as:
*
*
* <pre>
* {
* &#64;code
@@ -76,7 +76,7 @@ import org.luaj.vm2.lib.OsLib;
* However, other libraries such as <em>MathLib</em> are not loaded in this
* case.
* <p>
*
*
* @see LibFunction
* @see OsLib
* @see org.luaj.vm2.lib.jse.JsePlatform
@@ -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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -42,7 +42,7 @@ import org.luaj.vm2.lib.TableLib;
* {@link #standardGlobals()} or debug globals using {@link #debugGlobals()}
* <p>
* A simple example of initializing globals and using them from Java is:
*
*
* <pre>
* {
* &#64;code
@@ -52,7 +52,7 @@ import org.luaj.vm2.lib.TableLib;
* </pre>
* <p>
* Once globals are created, a simple way to load and run a script is:
*
*
* <pre>
* {@code
* globals.load( new FileInputStream("main.lua"), "main.lua" ).call();
@@ -60,13 +60,13 @@ import org.luaj.vm2.lib.TableLib;
* </pre>
* <p>
* although {@code require} could also be used:
*
*
* <pre>
* {@code
* globals.get("require").call(LuaValue.valueOf("main"));
* }
* </pre>
*
*
* For this to succeed, the file "main.lua" must be in the current directory or
* a resource. See {@link org.luaj.vm2.lib.jse.JseBaseLib} for details on
* finding scripts using {@link ResourceFinder}.
@@ -93,7 +93,7 @@ import org.luaj.vm2.lib.TableLib;
* library {@link DebugLib}.
* <p>
* The class ensures that initialization is done in the correct order.
*
*
* @see Globals
* @see org.luaj.vm2.lib.jme.JmePlatform
*/
@@ -101,7 +101,7 @@ public class JsePlatform {
/**
* Create a standard set of globals for JSE including all the libraries.
*
*
* @return Table of globals initialized with the standard JSE libraries
* @see #debugGlobals()
* @see org.luaj.vm2.lib.jse.JsePlatform
@@ -126,7 +126,7 @@ public class JsePlatform {
/**
* Create standard globals including the {@link DebugLib} library.
*
*
* @return Table of globals initialized with the standard JSE and debug
* libraries
* @see #standardGlobals()
@@ -144,7 +144,7 @@ public class JsePlatform {
* Simple wrapper for invoking a lua function with command line arguments.
* The supplied function is first given a new Globals object as its
* environment then the program is run with arguments.
*
*
* @return {@link Varargs} containing any values returned by mainChunk.
*/
public static Varargs luaMain(LuaValue mainChunk, String[] args) {

View File

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -36,7 +36,7 @@ public class JseProcess {
/**
* Construct a process around a command, with specified streams to redirect
* input and output to.
*
*
* @param cmd The command to execute, including arguments, if any
* @param stdin Optional InputStream to read from as process input, or null
* if input is not needed.
@@ -54,7 +54,7 @@ public class JseProcess {
/**
* Construct a process around a command, with specified streams to redirect
* input and output to.
*
*
* @param cmd The command to execute, including arguments, if any
* @param stdin Optional InputStream to read from as process input, or null
* if input is not needed.
@@ -83,7 +83,7 @@ public class JseProcess {
/**
* Wait for the process to complete, and all pending output to finish.
*
*
* @return The exit status.
* @throws InterruptedException
*/
@@ -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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -44,11 +44,11 @@ import org.luaj.vm2.lib.VarArgFunction;
* bind java classes and methods to lua dynamically. The API is documented on
* the <a href="http://www.keplerproject.org/luajava/">luajava</a> documentation
* pages.
*
*
* <p>
* Typically, this library is included as part of a call to
* {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()}
*
*
* <pre>
* {
* &#64;code
@@ -60,7 +60,7 @@ import org.luaj.vm2.lib.VarArgFunction;
* <p>
* To instantiate and use it directly, link it into your globals table via
* {@link Globals#load} using code such as:
*
*
* <pre>
* {
* &#64;code
@@ -73,7 +73,7 @@ import org.luaj.vm2.lib.VarArgFunction;
* }
* </pre>
* <p>
*
*
* The {@code luajava} library is available on all JSE platforms via the call to
* {@link org.luaj.vm2.lib.jse.JsePlatform#standardGlobals()} and the luajava
* api's are simply invoked from lua. Because it makes extensive use of Java's
@@ -82,7 +82,7 @@ import org.luaj.vm2.lib.VarArgFunction;
* <p>
* This has been implemented to match as closely as possible the behavior in the
* corresponding library in C.
*
*
* @see LibFunction
* @see org.luaj.vm2.lib.jse.JsePlatform
* @see org.luaj.vm2.lib.jme.JmePlatform
@@ -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

@@ -1,5 +1,5 @@
/**
*
*
*/
package org.luaj.vm2.luajc;
@@ -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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -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);
@@ -252,7 +250,7 @@ public class JavaBuilder {
}
}
// nil parameters
// nil parameters
// TODO: remove this for lua 5.2, not needed
for (; slot < p.maxstacksize; slot++) {
if (pi.isInitialValueUsed(slot)) {
@@ -264,7 +262,7 @@ public class JavaBuilder {
public byte[] completeClass(boolean genmain) {
// add class initializer
// add class initializer
if (!init.isEmpty()) {
MethodGen mg = new MethodGen(Constants.ACC_STATIC, Type.VOID, ARG_TYPES_NONE, new String[] {}, "<clinit>",
cg.getClassName(), init, cg.getConstantPool());
@@ -283,7 +281,7 @@ public class JavaBuilder {
cg.addMethod(mg.getMethod());
main.dispose();
// add initupvalue1(LuaValue env) to initialize environment for main chunk
// add initupvalue1(LuaValue env) to initialize environment for main chunk
if (p.upvalues.length == 1 && superclassType == SUPERTYPE_VARARGS) {
MethodGen mg = new MethodGen(Constants.ACC_PUBLIC | Constants.ACC_FINAL, // access flags
Type.VOID, // return type
@@ -307,7 +305,7 @@ public class JavaBuilder {
main.dispose();
}
// add main function so class is invokable from the java command line
// add main function so class is invokable from the java command line
if (genmain) {
MethodGen mg = new MethodGen(Constants.ACC_PUBLIC | Constants.ACC_STATIC, // access flags
Type.VOID, // return type
@@ -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]);
@@ -908,7 +906,7 @@ public class JavaBuilder {
public void closeUpvalue(int pc, int upindex) {
// TODO: assign the upvalue location the value null;
/*
boolean isrw = pi.isReadWriteUpvalue( pi.upvals[upindex] );
boolean isrw = pi.isReadWriteUpvalue( pi.upvals[upindex] );
append(InstructionConstants.THIS);
append(InstructionConstants.ACONST_NULL);
if ( isrw ) {

View File

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -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

@@ -19,7 +19,7 @@ import org.luaj.vm2.Prototype;
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -44,7 +44,7 @@ import org.luaj.vm2.compiler.LuaC;
* <p>
* To override the default compiling behavior with {@link LuaJC} lua-to-java
* bytecode compiler, install it before undumping code, for example:
*
*
* <pre>
* {@code
* LuaValue globals = JsePlatform.standardGlobals();
@@ -58,7 +58,7 @@ import org.luaj.vm2.compiler.LuaC;
* This requires the bcel library to be on the class path to work as expected.
* If the library is not found, the default {@link LuaC} lua-to-lua-bytecode
* compiler will be used.
*
*
* @see Globals#compiler
* @see #install(Globals)
* @see org.luaj.vm2.compiler.LuaC
@@ -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

@@ -1,5 +1,5 @@
/**
*
*
*/
package org.luaj.vm2.luajc;
@@ -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

@@ -1,5 +1,5 @@
/**
*
*
*/
package org.luaj.vm2.luajc;
@@ -37,15 +37,16 @@ public class VarInfo {
this.pc = pc;
}
@Override
public String toString() {
return slot < 0? "x.x": (slot + "." + pc);
return slot < 0? "x.x": slot + "." + pc;
}
/**
* Return replacement variable if there is exactly one value possible,
* otherwise compute entire collection of variables and return null.
* Computes the list of aall variable values, and saves it for the future.
*
*
* @return new Variable to replace with if there is only one value, or null
* to leave alone.
*/
@@ -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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -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;
@@ -33,7 +51,7 @@ import org.luaj.vm2.lib.jse.CoerceJavaToLua;
/**
* Implementation of the ScriptEngine interface which can compile and execute
* scripts using luaj.
*
*
* <p>
* This engine requires the types of the Bindings and ScriptContext to be
* compatible with the engine. For creating new client context use
@@ -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));
}
@@ -168,7 +187,7 @@ public class LuaScriptEngine extends AbstractScriptEngine implements ScriptEngin
}
}
// ------ convert char stream to byte stream for lua compiler -----
// ------ convert char stream to byte stream for lua compiler -----
private final class Utf8Encoder extends InputStream {
private final Reader r;
@@ -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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -29,7 +29,7 @@ import javax.script.ScriptEngineFactory;
/**
* Jsr 223 scripting engine factory.
*
*
* Exposes metadata to support the lua language, and constructs instances of
* LuaScriptEngine to handl lua scripts.
*/
@@ -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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -71,7 +71,7 @@ public class LuajContext extends SimpleScriptContext implements ScriptContext {
* If createDebugGlobals is set, the globals created will be a debug globals
* that includes the debug library. This may provide better stack traces,
* but may have negative impact on performance.
*
*
* @param createDebugGlobals true to create debug globals, false for
* standard globals.
* @param useLuaJCCompiler true to use the luajc compiler, reqwuires bcel
@@ -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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -38,7 +38,7 @@ import org.luaj.vm2.lib.jse.JsePlatform;
* <P>
* Return values with simple types are coerced into Java simple types. Tables,
* threads, and functions are returned as lua objects.
*
*
* @see Launcher
* @see LuajClassLoader
* @see LuajClassLoader#NewLauncher()
@@ -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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -49,28 +49,28 @@ public interface Launcher {
/**
* Launch a script contained in a String.
*
*
* @param script The script contents.
* @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.
*
*
* @param script The script as an InputStream.
* @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.
*
*
* @param script The script as a Reader.
* @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

@@ -10,7 +10,7 @@
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -52,7 +52,7 @@ import java.util.Map;
* and prints the return values. This behavior can be changed by supplying a
* different implementation class to {@link #NewLauncher(Class)} which must
* extend {@link Launcher}.
*
*
* @see Launcher
* @see #NewLauncher()
* @see #NewLauncher(Class)
@@ -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
@@ -83,7 +83,7 @@ public class LuajClassLoader extends ClassLoader {
* classes are loaded into this loader including static variables such as
* shared metatables, and should not be able to directly access variables
* from other Launcher instances.
*
*
* @return {@link Launcher} instance that can be used to launch scripts.
* @throws InstantiationException
* @throws IllegalAccessException
@@ -102,7 +102,7 @@ public class LuajClassLoader extends ClassLoader {
* classes are loaded into this loader including static variables such as
* shared metatables, and should not be able to directly access variables
* from other Launcher instances.
*
*
* @return instance of type 'launcher_class' that can be used to launch
* scripts.
* @throws InstantiationException
@@ -119,7 +119,7 @@ public class LuajClassLoader extends ClassLoader {
/**
* Test if a class name should be considered a user class and loaded by this
* loader, or a system class and loaded by the system loader.
*
*
* @param classname Class name to test.
* @return true if this should be loaded into this class loader.
*/
@@ -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);