file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
DelayedEvalBshMethod.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/DelayedEvalBshMethod.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
public class DelayedEvalBshMethod extends BSHMethod {
String returnTypeDescriptor;
BSHReturnType returnTypeNode;
String[] paramTypeDescriptors;
BSHFormalParameters paramTypesNode;
// used for the delayed evaluation...
transient CallStack callstack;
transient Interpreter interpreter;
/**
* This constructor is used in class generation. It supplies String type
* descriptors for return and parameter class types and allows delay of the
* evaluation of those types until they are requested. It does this by
* holding BSHType nodes, as well as an evaluation callstack, and
* interpreter which are called when the class types are requested.
*/
/*
Note: technically I think we could get by passing in only the
current namespace or perhaps BshClassManager here instead of
CallStack and Interpreter. However let's just play it safe in case
of future changes - anywhere you eval a node you need these.
*/
DelayedEvalBshMethod(
String name,
String returnTypeDescriptor, BSHReturnType returnTypeNode,
String[] paramNames,
String[] paramTypeDescriptors, BSHFormalParameters paramTypesNode,
BSHBlock methodBody,
NameSpace declaringNameSpace, Modifiers modifiers,
CallStack callstack, Interpreter interpreter
) {
super(name, null/*returnType*/, paramNames, null/*paramTypes*/,
methodBody, declaringNameSpace, modifiers);
this.returnTypeDescriptor = returnTypeDescriptor;
this.returnTypeNode = returnTypeNode;
this.paramTypeDescriptors = paramTypeDescriptors;
this.paramTypesNode = paramTypesNode;
this.callstack = callstack;
this.interpreter = interpreter;
}
public String getReturnTypeDescriptor() {
return returnTypeDescriptor;
}
@Override
public Class getReturnType() {
if (returnTypeNode == null) {
return null;
}
// BSHType will cache the type for us
try {
return returnTypeNode.evalReturnType(callstack, interpreter);
} catch (EvalError e) {
throw new InterpreterError("can't eval return type: " + e);
}
}
public String[] getParamTypeDescriptors() {
return paramTypeDescriptors;
}
@Override
public Class[] getParameterTypes() {
// BSHFormalParameters will cache the type for us
try {
return (Class[]) paramTypesNode.eval(callstack, interpreter);
} catch (EvalError e) {
throw new InterpreterError("can't eval param types: " + e);
}
}
}
| 5,235 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
CodeVisitor.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/CodeVisitor.java | /** *
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (C) 2000 INRIA, France Telecom
* Copyright (C) 2002 France Telecom
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact: [email protected]
*
* Author: Eric Bruneton
*/
package ehacks.bsh;
/**
* A visitor to visit the bytecode instructions of a Java method. The methods of
* this visitor must be called in the sequential order of the bytecode
* instructions of the visited code. The {@link #visitMaxs visitMaxs} method
* must be called after all the instructions have been visited. The {@link
* #visitTryCatchBlock visitTryCatchBlock}, {@link #visitLocalVariable
* visitLocalVariable} and {@link #visitLineNumber visitLineNumber} methods may
* be called in any order, at any time (provided the labels passed as arguments
* have already been visited with {@link #visitLabel visitLabel}).
*/
public interface CodeVisitor {
/**
* Visits a zero operand instruction.
*
* @param opcode the opcode of the instruction to be visited. This opcode is
* either NOP, ACONST_NULL, ICONST_M1, ICONST_0, ICONST_1, ICONST_2,
* ICONST_3, ICONST_4, ICONST_5, LCONST_0, LCONST_1, FCONST_0, FCONST_1,
* FCONST_2, DCONST_0, DCONST_1,
*
* IALOAD, LALOAD, FALOAD, DALOAD, AALOAD, BALOAD, CALOAD, SALOAD, IASTORE,
* LASTORE, FASTORE, DASTORE, AASTORE, BASTORE, CASTORE, SASTORE,
*
* POP, POP2, DUP, DUP_X1, DUP_X2, DUP2, DUP2_X1, DUP2_X2, SWAP,
*
* IADD, LADD, FADD, DADD, ISUB, LSUB, FSUB, DSUB, IMUL, LMUL, FMUL, DMUL,
* IDIV, LDIV, FDIV, DDIV, IREM, LREM, FREM, DREM, INEG, LNEG, FNEG, DNEG,
* ISHL, LSHL, ISHR, LSHR, IUSHR, LUSHR, IAND, LAND, IOR, LOR, IXOR, LXOR,
*
* I2L, I2F, I2D, L2I, L2F, L2D, F2I, F2L, F2D, D2I, D2L, D2F, I2B, I2C,
* I2S,
*
* LCMP, FCMPL, FCMPG, DCMPL, DCMPG,
*
* IRETURN, LRETURN, FRETURN, DRETURN, ARETURN, RETURN,
*
* ARRAYLENGTH,
*
* ATHROW,
*
* MONITORENTER, or MONITOREXIT.
*/
void visitInsn(int opcode);
/**
* Visits an instruction with a single int operand.
*
* @param opcode the opcode of the instruction to be visited. This opcode is
* either BIPUSH, SIPUSH or NEWARRAY.
* @param operand the operand of the instruction to be visited.
*/
void visitIntInsn(int opcode, int operand);
/**
* Visits a local variable instruction. A local variable instruction is an
* instruction that loads or stores the value of a local variable.
*
* @param opcode the opcode of the local variable instruction to be visited.
* This opcode is either ILOAD, LLOAD, FLOAD, DLOAD, ALOAD, ISTORE, LSTORE,
* FSTORE, DSTORE, ASTORE or RET.
* @param var the operand of the instruction to be visited. This operand is
* the index of a local variable.
*/
void visitVarInsn(int opcode, int var);
/**
* Visits a type instruction. A type instruction is an instruction that
* takes a type descriptor as parameter.
*
* @param opcode the opcode of the type instruction to be visited. This
* opcode is either NEW, ANEWARRAY, CHECKCAST or INSTANCEOF.
* @param desc the operand of the instruction to be visited. This operand is
* must be a fully qualified class name in internal form, or the type
* descriptor of an array type (see {@link Type Type}).
*/
void visitTypeInsn(int opcode, String desc);
/**
* Visits a field instruction. A field instruction is an instruction that
* loads or stores the value of a field of an object.
*
* @param opcode the opcode of the type instruction to be visited. This
* opcode is either GETSTATIC, PUTSTATIC, GETFIELD or PUTFIELD.
* @param owner the internal name of the field's owner class (see {@link
* Type#getInternalName getInternalName}).
* @param name the field's name.
* @param desc the field's descriptor (see {@link Type Type}).
*/
void visitFieldInsn(int opcode, String owner, String name, String desc);
/**
* Visits a method instruction. A method instruction is an instruction that
* invokes a method.
*
* @param opcode the opcode of the type instruction to be visited. This
* opcode is either INVOKEVIRTUAL, INVOKESPECIAL, INVOKESTATIC or
* INVOKEINTERFACE.
* @param owner the internal name of the method's owner class (see {@link
* Type#getInternalName getInternalName}).
* @param name the method's name.
* @param desc the method's descriptor (see {@link Type Type}).
*/
void visitMethodInsn(int opcode, String owner, String name, String desc);
/**
* Visits a jump instruction. A jump instruction is an instruction that may
* jump to another instruction.
*
* @param opcode the opcode of the type instruction to be visited. This
* opcode is either IFEQ, IFNE, IFLT, IFGE, IFGT, IFLE, IF_ICMPEQ,
* IF_ICMPNE, IF_ICMPLT, IF_ICMPGE, IF_ICMPGT, IF_ICMPLE, IF_ACMPEQ,
* IF_ACMPNE, GOTO, JSR, IFNULL or IFNONNULL.
* @param label the operand of the instruction to be visited. This operand
* is a label that designates the instruction to which the jump instruction
* may jump.
*/
void visitJumpInsn(int opcode, Label label);
/**
* Visits a label. A label designates the instruction that will be visited
* just after it.
*
* @param label a {@link Label Label} object.
*/
void visitLabel(Label label);
// -------------------------------------------------------------------------
// Special instructions
// -------------------------------------------------------------------------
/**
* Visits a LDC instruction.
*
* @param cst the constant to be loaded on the stack. This parameter must be
* a non null {@link java.lang.Integer Integer}, a {@link java.lang.Float
* Float}, a {@link java.lang.Long Long}, a {@link java.lang.Double
* Double} or a {@link String String}.
*/
void visitLdcInsn(Object cst);
/**
* Visits an IINC instruction.
*
* @param var index of the local variable to be incremented.
* @param increment amount to increment the local variable by.
*/
void visitIincInsn(int var, int increment);
/**
* Visits a TABLESWITCH instruction.
*
* @param min the minimum key value.
* @param max the maximum key value.
* @param dflt beginning of the default handler block.
* @param labels beginnings of the handler blocks. <tt>labels[i]</tt> is the
* beginning of the handler block for the <tt>min + i</tt> key.
*/
void visitTableSwitchInsn(int min, int max, Label dflt, Label labels[]);
/**
* Visits a LOOKUPSWITCH instruction.
*
* @param dflt beginning of the default handler block.
* @param keys the values of the keys.
* @param labels beginnings of the handler blocks. <tt>labels[i]</tt> is the
* beginning of the handler block for the <tt>keys[i]</tt> key.
*/
void visitLookupSwitchInsn(Label dflt, int keys[], Label labels[]);
/**
* Visits a MULTIANEWARRAY instruction.
*
* @param desc an array type descriptor (see {@link Type Type}).
* @param dims number of dimensions of the array to allocate.
*/
void visitMultiANewArrayInsn(String desc, int dims);
// -------------------------------------------------------------------------
// Exceptions table entries, max stack size and max locals
// -------------------------------------------------------------------------
/**
* Visits a try catch block.
*
* @param start beginning of the exception handler's scope (inclusive).
* @param end end of the exception handler's scope (exclusive).
* @param handler beginning of the exception handler's code.
* @param type internal name of the type of exceptions handled by the
* handler, or <tt>null</tt> to catch any exceptions (for "finally" blocks).
* @throws IllegalArgumentException if one of the labels has not already
* been visited by this visitor (by the {@link #visitLabel visitLabel}
* method).
*/
void visitTryCatchBlock(Label start, Label end, Label handler, String type);
/**
* Visits the maximum stack size and the maximum number of local variables
* of the method.
*
* @param maxStack maximum stack size of the method.
* @param maxLocals maximum number of local variables for the method.
*/
void visitMaxs(int maxStack, int maxLocals);
// -------------------------------------------------------------------------
// Debug information
// -------------------------------------------------------------------------
/**
* Visits a local variable declaration.
*
* @param name the name of a local variable.
* @param desc the type descriptor of this local variable.
* @param start the first instruction corresponding to the scope of this
* local variable (inclusive).
* @param end the last instruction corresponding to the scope of this local
* variable (exclusive).
* @param index the local variable's index.
* @throws IllegalArgumentException if one of the labels has not already
* been visited by this visitor (by the {@link #visitLabel visitLabel}
* method).
*/
void visitLocalVariable(
String name,
String desc,
Label start,
Label end,
int index);
/**
* Visits a line number declaration.
*
* @param line a line number. This number refers to the source file from
* which the class was compiled.
* @param start the first instruction corresponding to this line number.
* @throws IllegalArgumentException if <tt>start</tt> has not already been
* visited by this visitor (by the {@link #visitLabel visitLabel} method).
*/
void visitLineNumber(int line, Label start);
}
| 10,763 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
ClassGeneratorUtil.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/ClassGeneratorUtil.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.List;
/**
* ClassGeneratorUtil utilizes the ASM (www.objectweb.org) bytecode generator by
* Eric Bruneton in order to generate class "stubs" for BeanShell at runtime.
* <p/>
* <p/>
* Stub classes contain all of the fields of a BeanShell scripted class as well
* as two "callback" references to BeanShell namespaces: one for static methods
* and one for instance methods. Methods of the class are delegators which
* invoke corresponding methods on either the static or instance bsh object and
* then unpack and return the results. The static namespace utilizes a static
* import to delegate variable access to the class' static fields. The instance
* namespace utilizes a dynamic import (i.e. mixin) to delegate variable access
* to the class' instance variables.
* <p/>
* <p/>
* Constructors for the class delegate to the static initInstance() method of
* ClassGeneratorUtil to initialize new instances of the object. initInstance()
* invokes the instance intializer code (init vars and instance blocks) and then
* delegates to the corresponding scripted constructor method in the instance
* namespace. Constructors contain special switch logic which allows the
* BeanShell to control the calling of alternate constructors (this() or super()
* references) at runtime.
* <p/>
* <p/>
* Specially named superclass delegator methods are also generated in order to
* allow BeanShell to access overridden methods of the superclass (which
* reflection does not normally allow).
* <p/>
*
* @author Pat Niemeyer
*/
/*
Notes:
It would not be hard to eliminate the use of org.objectweb.asm.Type from
this class, making the distribution a tiny bit smaller.
*/
public class ClassGeneratorUtil implements Constants {
/**
* The name of the static field holding the reference to the bsh static This
* (the callback namespace for static methods)
*/
static final String BSHSTATIC = "_bshStatic";
/**
* The name of the instance field holding the reference to the bsh instance
* This (the callback namespace for instance methods)
*/
private static final String BSHTHIS = "_bshThis";
/**
* The prefix for the name of the super delegate methods. e.g.
* _bshSuperfoo() is equivalent to super.foo()
*/
static final String BSHSUPER = "_bshSuper";
/**
* The bsh static namespace variable name of the instance initializer
*/
static final String BSHINIT = "_bshInstanceInitializer";
/**
* The bsh static namespace variable that holds the constructor methods
*/
private static final String BSHCONSTRUCTORS = "_bshConstructors";
/**
* The switch branch number for the default constructor. The value -1 will
* cause the default branch to be taken.
*/
private static final int DEFAULTCONSTRUCTOR = -1;
private static final String OBJECT = "Ljava/lang/Object;";
private final String className;
/**
* fully qualified class name (with package) e.g. foo/bar/Blah
*/
private final String fqClassName;
private final Class superClass;
private final String superClassName;
private final Class[] interfaces;
private final Variable[] vars;
private final Constructor[] superConstructors;
private final DelayedEvalBshMethod[] constructors;
private final DelayedEvalBshMethod[] methods;
private final NameSpace classStaticNameSpace;
private final Modifiers classModifiers;
private boolean isInterface;
/**
* @param packageName e.g. "com.foo.bar"
*/
public ClassGeneratorUtil(Modifiers classModifiers, String className, String packageName, Class superClass, Class[] interfaces, Variable[] vars, DelayedEvalBshMethod[] bshmethods, NameSpace classStaticNameSpace, boolean isInterface) {
this.classModifiers = classModifiers;
this.className = className;
if (packageName != null) {
this.fqClassName = packageName.replace('.', '/') + "/" + className;
} else {
this.fqClassName = className;
}
if (superClass == null) {
superClass = Object.class;
}
this.superClass = superClass;
this.superClassName = Type.getInternalName(superClass);
if (interfaces == null) {
interfaces = new Class[0];
}
this.interfaces = interfaces;
this.vars = vars;
this.classStaticNameSpace = classStaticNameSpace;
this.superConstructors = superClass.getDeclaredConstructors();
// Split the methods into constructors and regular method lists
List consl = new ArrayList();
List methodsl = new ArrayList();
String classBaseName = getBaseName(className); // for inner classes
for (DelayedEvalBshMethod bshmethod : bshmethods) {
if (bshmethod.getName().equals(classBaseName)) {
consl.add(bshmethod);
} else {
methodsl.add(bshmethod);
}
}
this.constructors = (DelayedEvalBshMethod[]) consl.toArray(new DelayedEvalBshMethod[consl.size()]);
this.methods = (DelayedEvalBshMethod[]) methodsl.toArray(new DelayedEvalBshMethod[methodsl.size()]);
try {
classStaticNameSpace.setLocalVariable(BSHCONSTRUCTORS, constructors, false/*strict*/);
} catch (UtilEvalError e) {
throw new InterpreterError("can't set cons var");
}
this.isInterface = isInterface;
}
/**
* Generate the class bytecode for this class.
*/
public byte[] generateClass() {
// Force the class public for now...
int classMods = getASMModifiers(classModifiers) | ACC_PUBLIC;
if (isInterface) {
classMods |= ACC_INTERFACE;
}
String[] interfaceNames = new String[interfaces.length + (isInterface ? 0 : 1)]; // one more interface for instance init callback
for (int i = 0; i < interfaces.length; i++) {
interfaceNames[i] = Type.getInternalName(interfaces[i]);
}
if (!isInterface) {
interfaceNames[interfaces.length] = Type.getInternalName(GeneratedClass.class);
}
String sourceFile = "BeanShell Generated via ASM (www.objectweb.org)";
ClassWriter cw = new ClassWriter(false);
cw.visit(classMods, fqClassName, superClassName, interfaceNames, sourceFile);
if (!isInterface) {
// Generate the bsh instance 'This' reference holder field
generateField(BSHTHIS + className, "Lbsh/This;", ACC_PUBLIC, cw);
// Generate the static bsh static reference holder field
generateField(BSHSTATIC + className, "Lbsh/This;", ACC_PUBLIC + ACC_STATIC, cw);
}
// Generate the fields
for (Variable var : vars) {
String type = var.getTypeDescriptor();
// Don't generate private or loosely typed fields
// Note: loose types aren't currently parsed anyway...
if (var.hasModifier("private") || type == null) {
continue;
}
int modifiers;
if (isInterface) {
modifiers = ACC_PUBLIC | ACC_STATIC | ACC_FINAL;
} else {
modifiers = getASMModifiers(var.getModifiers());
}
generateField(var.getName(), type, modifiers, cw);
}
// Generate the constructors
boolean hasConstructor = false;
for (int i = 0; i < constructors.length; i++) {
// Don't generate private constructors
if (constructors[i].hasModifier("private")) {
continue;
}
int modifiers = getASMModifiers(constructors[i].getModifiers());
generateConstructor(i, constructors[i].getParamTypeDescriptors(), modifiers, cw);
hasConstructor = true;
}
// If no other constructors, generate a default constructor
if (!isInterface && !hasConstructor) {
generateConstructor(DEFAULTCONSTRUCTOR/*index*/, new String[0], ACC_PUBLIC, cw);
}
// Generate the delegate methods
for (DelayedEvalBshMethod method : methods) {
String returnType = method.getReturnTypeDescriptor();
// Don't generate private /*or loosely return typed */ methods
if (method.hasModifier("private") /*|| returnType == null*/) {
continue;
}
int modifiers = getASMModifiers(method.getModifiers());
if (isInterface) {
modifiers |= (ACC_PUBLIC | ACC_ABSTRACT);
}
generateMethod(className, fqClassName, method.getName(), returnType, method.getParamTypeDescriptors(), modifiers, cw);
boolean isStatic = (modifiers & ACC_STATIC) > 0;
boolean overridden = classContainsMethod(superClass, method.getName(), method.getParamTypeDescriptors());
if (!isStatic && overridden) {
generateSuperDelegateMethod(superClassName, method.getName(), returnType, method.getParamTypeDescriptors(), modifiers, cw);
}
}
return cw.toByteArray();
}
/**
* Translate bsh.Modifiers into ASM modifier bitflags.
*/
private static int getASMModifiers(Modifiers modifiers) {
int mods = 0;
if (modifiers == null) {
return mods;
}
if (modifiers.hasModifier("public")) {
mods += ACC_PUBLIC;
}
if (modifiers.hasModifier("protected")) {
mods += ACC_PROTECTED;
}
if (modifiers.hasModifier("static")) {
mods += ACC_STATIC;
}
if (modifiers.hasModifier("synchronized")) {
mods += ACC_SYNCHRONIZED;
}
if (modifiers.hasModifier("abstract")) {
mods += ACC_ABSTRACT;
}
return mods;
}
/**
* Generate a field - static or instance.
*/
private static void generateField(String fieldName, String type, int modifiers, ClassWriter cw) {
cw.visitField(modifiers, fieldName, type, null/*value*/);
}
/**
* Generate a delegate method - static or instance. The generated code packs
* the method arguments into an object array (wrapping primitive types in
* bsh.Primitive), invokes the static or instance namespace invokeMethod()
* method, and then unwraps / returns the result.
*/
private static void generateMethod(String className, String fqClassName, String methodName, String returnType, String[] paramTypes, int modifiers, ClassWriter cw) {
String[] exceptions = null;
boolean isStatic = (modifiers & ACC_STATIC) != 0;
if (returnType == null) // map loose return type to Object
{
returnType = OBJECT;
}
String methodDescriptor = getMethodDescriptor(returnType, paramTypes);
// Generate method body
CodeVisitor cv = cw.visitMethod(modifiers, methodName, methodDescriptor, exceptions);
if ((modifiers & ACC_ABSTRACT) != 0) {
return;
}
// Generate code to push the BSHTHIS or BSHSTATIC field
if (isStatic) {
cv.visitFieldInsn(GETSTATIC, fqClassName, BSHSTATIC + className, "Lbsh/This;");
} else {
// Push 'this'
cv.visitVarInsn(ALOAD, 0);
// Get the instance field
cv.visitFieldInsn(GETFIELD, fqClassName, BSHTHIS + className, "Lbsh/This;");
}
// Push the name of the method as a constant
cv.visitLdcInsn(methodName);
// Generate code to push arguments as an object array
generateParameterReifierCode(paramTypes, isStatic, cv);
// Push nulls for various args of invokeMethod
cv.visitInsn(ACONST_NULL); // interpreter
cv.visitInsn(ACONST_NULL); // callstack
cv.visitInsn(ACONST_NULL); // callerinfo
// Push the boolean constant 'true' (for declaredOnly)
cv.visitInsn(ICONST_1);
// Invoke the method This.invokeMethod( name, Class [] sig, boolean )
cv.visitMethodInsn(INVOKEVIRTUAL, "bsh/This", "invokeMethod", Type.getMethodDescriptor(Type.getType(Object.class), new Type[]{Type.getType(String.class), Type.getType(Object[].class), Type.getType(Interpreter.class), Type.getType(CallStack.class), Type.getType(SimpleNode.class), Type.getType(Boolean.TYPE)}));
// Generate code to unwrap bsh Primitive types
cv.visitMethodInsn(INVOKESTATIC, "bsh/Primitive", "unwrap", "(Ljava/lang/Object;)Ljava/lang/Object;");
// Generate code to return the value
generateReturnCode(returnType, cv);
// Need to calculate this... just fudging here for now.
cv.visitMaxs(20, 20);
}
/**
* Generate a constructor.
*/
void generateConstructor(int index, String[] paramTypes, int modifiers, ClassWriter cw) {
/**
* offset after params of the args object [] var
*/
final int argsVar = paramTypes.length + 1;
/**
* offset after params of the ConstructorArgs var
*/
final int consArgsVar = paramTypes.length + 2;
String[] exceptions = null;
String methodDescriptor = getMethodDescriptor("V", paramTypes);
// Create this constructor method
CodeVisitor cv = cw.visitMethod(modifiers, "<init>", methodDescriptor, exceptions);
// Generate code to push arguments as an object array
generateParameterReifierCode(paramTypes, false/*isStatic*/, cv);
cv.visitVarInsn(ASTORE, argsVar);
// Generate the code implementing the alternate constructor switch
generateConstructorSwitch(index, argsVar, consArgsVar, cv);
// Generate code to invoke the ClassGeneratorUtil initInstance() method
// push 'this'
cv.visitVarInsn(ALOAD, 0);
// Push the class/constructor name as a constant
cv.visitLdcInsn(className);
// Push arguments as an object array
cv.visitVarInsn(ALOAD, argsVar);
// invoke the initInstance() method
cv.visitMethodInsn(INVOKESTATIC, "bsh/ClassGeneratorUtil", "initInstance", "(L" + GeneratedClass.class.getName().replace('.', '/') + ";Ljava/lang/String;[Ljava/lang/Object;)V");
cv.visitInsn(RETURN);
// Need to calculate this... just fudging here for now.
cv.visitMaxs(20, 20);
}
/**
* Generate a switch with a branch for each possible alternate constructor.
* This includes all superclass constructors and all constructors of this
* class. The default branch of this switch is the default superclass
* constructor.
* <p/>
* This method also generates the code to call the static ClassGeneratorUtil
* getConstructorArgs() method which inspects the scripted constructor to
* find the alternate constructor signature (if any) and evalute the
* arguments at runtime. The getConstructorArgs() method returns the actual
* arguments as well as the index of the constructor to call.
*/
void generateConstructorSwitch(int consIndex, int argsVar, int consArgsVar, CodeVisitor cv) {
Label defaultLabel = new Label();
Label endLabel = new Label();
int cases = superConstructors.length + constructors.length;
Label[] labels = new Label[cases];
for (int i = 0; i < cases; i++) {
labels[i] = new Label();
}
// Generate code to call ClassGeneratorUtil to get our switch index
// and give us args...
// push super class name
cv.visitLdcInsn(superClass.getName()); // use superClassName var?
// push class static This object
cv.visitFieldInsn(GETSTATIC, fqClassName, BSHSTATIC + className, "Lbsh/This;");
// push args
cv.visitVarInsn(ALOAD, argsVar);
// push this constructor index number onto stack
cv.visitIntInsn(BIPUSH, consIndex);
// invoke the ClassGeneratorUtil getConstructorsArgs() method
cv.visitMethodInsn(INVOKESTATIC, "bsh/ClassGeneratorUtil", "getConstructorArgs", "(Ljava/lang/String;Lbsh/This;[Ljava/lang/Object;I)" + "Lbsh/ClassGeneratorUtil$ConstructorArgs;");
// store ConstructorArgs in consArgsVar
cv.visitVarInsn(ASTORE, consArgsVar);
// Get the ConstructorArgs selector field from ConstructorArgs
// push ConstructorArgs
cv.visitVarInsn(ALOAD, consArgsVar);
cv.visitFieldInsn(GETFIELD, "bsh/ClassGeneratorUtil$ConstructorArgs", "selector", "I");
// start switch
cv.visitTableSwitchInsn(0/*min*/, cases - 1/*max*/, defaultLabel, labels);
// generate switch body
int index = 0;
for (int i = 0; i < superConstructors.length; i++, index++) {
doSwitchBranch(index, superClassName, getTypeDescriptors(superConstructors[i].getParameterTypes()), endLabel, labels, consArgsVar, cv);
}
for (int i = 0; i < constructors.length; i++, index++) {
doSwitchBranch(index, fqClassName, constructors[i].getParamTypeDescriptors(), endLabel, labels, consArgsVar, cv);
}
// generate the default branch of switch
cv.visitLabel(defaultLabel);
// default branch always invokes no args super
cv.visitVarInsn(ALOAD, 0); // push 'this'
cv.visitMethodInsn(INVOKESPECIAL, superClassName, "<init>", "()V");
// done with switch
cv.visitLabel(endLabel);
}
/*
Generate a branch of the constructor switch. This method is called by
generateConstructorSwitch.
The code generated by this method assumes that the argument array is
on the stack.
*/
private static void doSwitchBranch(int index, String targetClassName, String[] paramTypes, Label endLabel, Label[] labels, int consArgsVar, CodeVisitor cv) {
cv.visitLabel(labels[index]);
//cv.visitLineNumber( index, labels[index] );
cv.visitVarInsn(ALOAD, 0); // push this before args
// Unload the arguments from the ConstructorArgs object
for (String type : paramTypes) {
final String method;
switch (type) {
case "Z":
method = "getBoolean";
break;
case "B":
method = "getByte";
break;
case "C":
method = "getChar";
break;
case "S":
method = "getShort";
break;
case "I":
method = "getInt";
break;
case "J":
method = "getLong";
break;
case "D":
method = "getDouble";
break;
case "F":
method = "getFloat";
break;
default:
method = "getObject";
break;
}
// invoke the iterator method on the ConstructorArgs
cv.visitVarInsn(ALOAD, consArgsVar); // push the ConstructorArgs
String className = "bsh/ClassGeneratorUtil$ConstructorArgs";
String retType;
if (method.equals("getObject")) {
retType = OBJECT;
} else {
retType = type;
}
cv.visitMethodInsn(INVOKEVIRTUAL, className, method, "()" + retType);
// if it's an object type we must do a check cast
if (method.equals("getObject")) {
cv.visitTypeInsn(CHECKCAST, descriptorToClassName(type));
}
}
// invoke the constructor for this branch
String descriptor = getMethodDescriptor("V", paramTypes);
cv.visitMethodInsn(INVOKESPECIAL, targetClassName, "<init>", descriptor);
cv.visitJumpInsn(GOTO, endLabel);
}
private static String getMethodDescriptor(String returnType, String[] paramTypes) {
StringBuilder sb = new StringBuilder("(");
for (String paramType : paramTypes) {
sb.append(paramType);
}
sb.append(')').append(returnType);
return sb.toString();
}
/**
* Generate a superclass method delegate accessor method. These methods are
* specially named methods which allow access to overridden methods of the
* superclass (which the Java reflection API normally does not allow).
*/
// Maybe combine this with generateMethod()
private static void generateSuperDelegateMethod(String superClassName, String methodName, String returnType, String[] paramTypes, int modifiers, ClassWriter cw) {
String[] exceptions = null;
if (returnType == null) // map loose return to Object
{
returnType = OBJECT;
}
String methodDescriptor = getMethodDescriptor(returnType, paramTypes);
// Add method body
CodeVisitor cv = cw.visitMethod(modifiers, "_bshSuper" + methodName, methodDescriptor, exceptions);
cv.visitVarInsn(ALOAD, 0);
// Push vars
int localVarIndex = 1;
for (String paramType : paramTypes) {
if (isPrimitive(paramType)) {
cv.visitVarInsn(ILOAD, localVarIndex);
} else {
cv.visitVarInsn(ALOAD, localVarIndex);
}
localVarIndex += ((paramType.equals("D") || paramType.equals("J")) ? 2 : 1);
}
cv.visitMethodInsn(INVOKESPECIAL, superClassName, methodName, methodDescriptor);
generatePlainReturnCode(returnType, cv);
// Need to calculate this... just fudging here for now.
cv.visitMaxs(20, 20);
}
boolean classContainsMethod(Class clas, String methodName, String[] paramTypes) {
while (clas != null) {
Method[] methods = clas.getDeclaredMethods();
for (Method method : methods) {
if (method.getName().equals(methodName)) {
String[] methodParamTypes = getTypeDescriptors(method.getParameterTypes());
boolean found = true;
for (int j = 0; j < methodParamTypes.length; j++) {
if (!paramTypes[j].equals(methodParamTypes[j])) {
found = false;
break;
}
}
if (found) {
return true;
}
}
}
clas = clas.getSuperclass();
}
return false;
}
/**
* Generate return code for a normal bytecode
*/
private static void generatePlainReturnCode(String returnType, CodeVisitor cv) {
if (returnType.equals("V")) {
cv.visitInsn(RETURN);
} else if (isPrimitive(returnType)) {
int opcode = IRETURN;
switch (returnType) {
case "D":
opcode = DRETURN;
break;
case "F":
opcode = FRETURN;
break;
//long
case "J":
opcode = LRETURN;
break;
default:
break;
}
cv.visitInsn(opcode);
} else {
cv.visitTypeInsn(CHECKCAST, descriptorToClassName(returnType));
cv.visitInsn(ARETURN);
}
}
/**
* Generates the code to reify the arguments of the given method. For a
* method "int m (int i, String s)", this code is the bytecode corresponding
* to the "new Object[] { new bsh.Primitive(i), s }" expression.
*
* @param cv the code visitor to be used to generate the bytecode.
* @param isStatic the enclosing methods is static
* @author Eric Bruneton
* @author Pat Niemeyer
*/
private static void generateParameterReifierCode(String[] paramTypes, boolean isStatic, final CodeVisitor cv) {
cv.visitIntInsn(SIPUSH, paramTypes.length);
cv.visitTypeInsn(ANEWARRAY, "java/lang/Object");
int localVarIndex = isStatic ? 0 : 1;
for (int i = 0; i < paramTypes.length; ++i) {
String param = paramTypes[i];
cv.visitInsn(DUP);
cv.visitIntInsn(SIPUSH, i);
if (isPrimitive(param)) {
int opcode;
switch (param) {
case "F":
opcode = FLOAD;
break;
case "D":
opcode = DLOAD;
break;
case "J":
opcode = LLOAD;
break;
default:
opcode = ILOAD;
break;
}
String type = "bsh/Primitive";
cv.visitTypeInsn(NEW, type);
cv.visitInsn(DUP);
cv.visitVarInsn(opcode, localVarIndex);
String desc = param; // ok?
cv.visitMethodInsn(INVOKESPECIAL, type, "<init>", "(" + desc + ")V");
} else {
// Technically incorrect here - we need to wrap null values
// as bsh.Primitive.NULL. However the This.invokeMethod()
// will do that much for us.
// We need to generate a conditional here to test for null
// and return Primitive.NULL
cv.visitVarInsn(ALOAD, localVarIndex);
}
cv.visitInsn(AASTORE);
localVarIndex += ((param.equals("D") || param.equals("J")) ? 2 : 1);
}
}
/**
* Generates the code to unreify the result of the given method. For a
* method "int m (int i, String s)", this code is the bytecode corresponding
* to the "((Integer)...).intValue()" expression.
*
* @param cv the code visitor to be used to generate the bytecode.
* @author Eric Bruneton
* @author Pat Niemeyer
*/
private static void generateReturnCode(String returnType, CodeVisitor cv) {
if (returnType.equals("V")) {
cv.visitInsn(POP);
cv.visitInsn(RETURN);
} else if (isPrimitive(returnType)) {
int opcode = IRETURN;
String type;
String meth;
switch (returnType) {
case "B":
type = "java/lang/Byte";
meth = "byteValue";
break;
case "I":
type = "java/lang/Integer";
meth = "intValue";
break;
case "Z":
type = "java/lang/Boolean";
meth = "booleanValue";
break;
case "D":
opcode = DRETURN;
type = "java/lang/Double";
meth = "doubleValue";
break;
case "F":
opcode = FRETURN;
type = "java/lang/Float";
meth = "floatValue";
break;
case "J":
opcode = LRETURN;
type = "java/lang/Long";
meth = "longValue";
break;
case "C":
type = "java/lang/Character";
meth = "charValue";
break;
/*if (returnType.equals("S") )*/
default:
type = "java/lang/Short";
meth = "shortValue";
break;
}
String desc = returnType;
cv.visitTypeInsn(CHECKCAST, type); // type is correct here
cv.visitMethodInsn(INVOKEVIRTUAL, type, meth, "()" + desc);
cv.visitInsn(opcode);
} else {
cv.visitTypeInsn(CHECKCAST, descriptorToClassName(returnType));
cv.visitInsn(ARETURN);
}
}
/**
* Evaluate the arguments (if any) for the constructor specified by the
* constructor index. Return the ConstructorArgs object which contains the
* actual arguments to the alternate constructor and also the index of that
* constructor for the constructor switch.
*
* @param consArgs the arguments to the constructor. These are necessary in
* the evaluation of the alt constructor args. e.g. Foo(a) { super(a); }
* @return the ConstructorArgs object containing a constructor selector and
* evaluated arguments for the alternate constructor
*/
public static ConstructorArgs getConstructorArgs(String superClassName, This classStaticThis, Object[] consArgs, int index) {
DelayedEvalBshMethod[] constructors;
try {
constructors = (DelayedEvalBshMethod[]) classStaticThis.getNameSpace().getVariable(BSHCONSTRUCTORS);
} catch (Exception e) {
throw new InterpreterError("unable to get instance initializer: " + e);
}
if (index == DEFAULTCONSTRUCTOR) // auto-gen default constructor
{
return ConstructorArgs.DEFAULT;
} // use default super constructor
DelayedEvalBshMethod constructor = constructors[index];
if (constructor.methodBody.jjtGetNumChildren() == 0) {
return ConstructorArgs.DEFAULT;
} // use default super constructor
// Determine if the constructor calls this() or super()
String altConstructor = null;
BSHArguments argsNode = null;
SimpleNode firstStatement = (SimpleNode) constructor.methodBody.jjtGetChild(0);
if (firstStatement instanceof BSHPrimaryExpression) {
firstStatement = (SimpleNode) firstStatement.jjtGetChild(0);
}
if (firstStatement instanceof BSHMethodInvocation) {
BSHMethodInvocation methodNode = (BSHMethodInvocation) firstStatement;
BSHAmbiguousName methodName = methodNode.getNameNode();
if (methodName.text.equals("super") || methodName.text.equals("this")) {
altConstructor = methodName.text;
argsNode = methodNode.getArgsNode();
}
}
if (altConstructor == null) {
return ConstructorArgs.DEFAULT;
} // use default super constructor
// Make a tmp namespace to hold the original constructor args for
// use in eval of the parameters node
NameSpace consArgsNameSpace = new NameSpace(classStaticThis.getNameSpace(), "consArgs");
String[] consArgNames = constructor.getParameterNames();
Class[] consArgTypes = constructor.getParameterTypes();
for (int i = 0; i < consArgs.length; i++) {
try {
consArgsNameSpace.setTypedVariable(consArgNames[i], consArgTypes[i], consArgs[i], null/*modifiers*/);
} catch (UtilEvalError e) {
throw new InterpreterError("err setting local cons arg:" + e);
}
}
// evaluate the args
CallStack callstack = new CallStack();
callstack.push(consArgsNameSpace);
Object[] args;
Interpreter interpreter = classStaticThis.declaringInterpreter;
try {
args = argsNode.getArguments(callstack, interpreter);
} catch (EvalError e) {
throw new InterpreterError("Error evaluating constructor args: " + e);
}
Class[] argTypes = Types.getTypes(args);
args = Primitive.unwrap(args);
Class superClass = interpreter.getClassManager().classForName(superClassName);
if (superClass == null) {
throw new InterpreterError("can't find superclass: " + superClassName);
}
Constructor[] superCons = superClass.getDeclaredConstructors();
// find the matching super() constructor for the args
if (altConstructor.equals("super")) {
int i = Reflect.findMostSpecificConstructorIndex(argTypes, superCons);
if (i == -1) {
throw new InterpreterError("can't find constructor for args!");
}
return new ConstructorArgs(i, args);
}
// find the matching this() constructor for the args
Class[][] candidates = new Class[constructors.length][];
for (int i = 0; i < candidates.length; i++) {
candidates[i] = constructors[i].getParameterTypes();
}
int i = Reflect.findMostSpecificSignature(argTypes, candidates);
if (i == -1) {
throw new InterpreterError("can't find constructor for args 2!");
}
// this() constructors come after super constructors in the table
int selector = i + superCons.length;
int ourSelector = index + superCons.length;
// Are we choosing ourselves recursively through a this() reference?
if (selector == ourSelector) {
throw new InterpreterError("Recusive constructor call.");
}
return new ConstructorArgs(selector, args);
}
private static final ThreadLocal<NameSpace> CONTEXT_NAMESPACE = new ThreadLocal<NameSpace>();
private static final ThreadLocal<Interpreter> CONTEXT_INTERPRETER = new ThreadLocal<Interpreter>();
/**
* Register actual context, used by generated class constructor, which calls
* {@link #initInstance(GeneratedClass, String, Object[])}.
*/
static void registerConstructorContext(CallStack callstack, Interpreter interpreter) {
if (callstack != null) {
CONTEXT_NAMESPACE.set(callstack.top());
} else {
CONTEXT_NAMESPACE.remove();
}
if (interpreter != null) {
CONTEXT_INTERPRETER.set(interpreter);
} else {
CONTEXT_INTERPRETER.remove();
}
}
/**
* Initialize an instance of the class. This method is called from the
* generated class constructor to evaluate the instance initializer and
* scripted constructor in the instance namespace.
*/
public static void initInstance(GeneratedClass instance, String className, Object[] args) {
Class[] sig = Types.getTypes(args);
CallStack callstack = new CallStack();
Interpreter interpreter;
NameSpace instanceNameSpace;
// check to see if the instance has already been initialized
// (the case if using a this() alternate constuctor)
// todo PeJoBo70 write test for this
This instanceThis = getClassInstanceThis(instance, className);
// XXX clean up this conditional
if (instanceThis == null) {
// Create the instance 'This' namespace, set it on the object
// instance and invoke the instance initializer
// Get the static This reference from the proto-instance
This classStaticThis = getClassStaticThis(instance.getClass(), className);
interpreter = CONTEXT_INTERPRETER.get();
if (interpreter == null) {
interpreter = classStaticThis.declaringInterpreter;
}
// Get the instance initializer block from the static This
BSHBlock instanceInitBlock;
try {
instanceInitBlock = (BSHBlock) classStaticThis.getNameSpace().getVariable(BSHINIT);
} catch (Exception e) {
throw new InterpreterError("unable to get instance initializer: " + e);
}
// Create the instance namespace
if (CONTEXT_NAMESPACE.get() != null) {
instanceNameSpace = classStaticThis.getNameSpace().copy();
instanceNameSpace.setParent(CONTEXT_NAMESPACE.get());
} else {
instanceNameSpace = new NameSpace(classStaticThis.getNameSpace(), className); // todo: old code
}
instanceNameSpace.isClass = true;
// Set the instance This reference on the instance
instanceThis = instanceNameSpace.getThis(interpreter);
try {
LHS lhs = Reflect.getLHSObjectField(instance, BSHTHIS + className);
lhs.assign(instanceThis, false/*strict*/);
} catch (Exception e) {
throw new InterpreterError("Error in class gen setup: " + e);
}
// Give the instance space its object import
instanceNameSpace.setClassInstance(instance);
// should use try/finally here to pop ns
callstack.push(instanceNameSpace);
// evaluate the instance portion of the block in it
try { // Evaluate the initializer block
instanceInitBlock.evalBlock(callstack, interpreter, true/*override*/, ClassGenerator.ClassNodeFilter.CLASSINSTANCE);
} catch (Exception e) {
throw new InterpreterError("Error in class initialization: " + e, e);
}
callstack.pop();
} else {
// The object instance has already been initialzed by another
// constructor. Fall through to invoke the constructor body below.
interpreter = instanceThis.declaringInterpreter;
instanceNameSpace = instanceThis.getNameSpace();
}
// invoke the constructor method from the instanceThis
String constructorName = getBaseName(className);
try {
// Find the constructor (now in the instance namespace)
BSHMethod constructor = instanceNameSpace.getMethod(constructorName, sig, true/*declaredOnly*/);
// if args, we must have constructor
if (args.length > 0 && constructor == null) {
throw new InterpreterError("Can't find constructor: " + className);
}
// Evaluate the constructor
if (constructor != null) {
constructor.invoke(args, interpreter, callstack, null/*callerInfo*/, false/*overrideNameSpace*/);
}
} catch (Exception e) {
if (e instanceof TargetError) {
e = (Exception) ((TargetError) e).getTarget();
}
if (e instanceof InvocationTargetException) {
e = (Exception) ((InvocationTargetException) e).getTargetException();
}
throw new InterpreterError("Error in class initialization.", e);
}
}
/**
* Get the static bsh namespace field from the class.
*
* @param className may be the name of clas itself or a superclass of clas.
*/
private static This getClassStaticThis(Class clas, String className) {
try {
return (This) Reflect.getStaticFieldValue(clas, BSHSTATIC + className);
} catch (Exception e) {
throw new InterpreterError("Unable to get class static space: " + e);
}
}
/**
* Get the instance bsh namespace field from the object instance.
*
* @return the class instance This object or null if the object has not been
* initialized.
*/
static This getClassInstanceThis(Object instance, String className) {
try {
Object o = Reflect.getObjectFieldValue(instance, BSHTHIS + className);
return (This) Primitive.unwrap(o); // unwrap Primitive.Null to null
} catch (Exception e) {
throw new InterpreterError("Generated class: Error getting This" + e);
}
}
/**
* Does the type descriptor string describe a primitive type?
*/
private static boolean isPrimitive(String typeDescriptor) {
return typeDescriptor.length() == 1; // right?
}
private static String[] getTypeDescriptors(Class[] cparams) {
String[] sa = new String[cparams.length];
for (int i = 0; i < sa.length; i++) {
sa[i] = BSHType.getTypeDescriptor(cparams[i]);
}
return sa;
}
/**
* If a non-array object type, remove the prefix "L" and suffix ";".
*/
// Can this be factored out...?
// Should be be adding the L...; here instead?
private static String descriptorToClassName(String s) {
if (s.startsWith("[") || !s.startsWith("L")) {
return s;
}
return s.substring(1, s.length() - 1);
}
private static String getBaseName(String className) {
int i = className.indexOf('$');
if (i == -1) {
return className;
}
return className.substring(i + 1);
}
/**
* A ConstructorArgs object holds evaluated arguments for a constructor call
* as well as the index of a possible alternate selector to invoke. This
* object is used by the constructor switch.
*
* @see bsh.ClassGeneratorUtil#generateConstructor(int, String[], int,
* bsh.org.objectweb.asm.ClassWriter)
*/
public static class ConstructorArgs {
/**
* A ConstructorArgs which calls the default constructor
*/
public static final ConstructorArgs DEFAULT = new ConstructorArgs();
public int selector = DEFAULTCONSTRUCTOR;
Object[] args;
int arg;
/**
* The index of the constructor to call.
*/
ConstructorArgs() {
}
ConstructorArgs(int selector, Object[] args) {
this.selector = selector;
this.args = args;
}
Object next() {
return args[arg++];
}
public boolean getBoolean() {
return (Boolean) next();
}
public byte getByte() {
return (Byte) next();
}
public char getChar() {
return (Character) next();
}
public short getShort() {
return (Short) next();
}
public int getInt() {
return (Integer) next();
}
public long getLong() {
return (Long) next();
}
public double getDouble() {
return (Double) next();
}
public float getFloat() {
return (Float) next();
}
public Object getObject() {
return next();
}
}
}
| 45,008 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
NameSource.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/NameSource.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
/**
* This interface supports name completion, which is used primarily for command
* line tools, etc. It provides a flat source of "names" in a space. For example
* all of the classes in the classpath or all of the variables in a namespace
* (or all of those).
* <p>
* NameSource is the lightest weight mechanism for sources which wish to support
* name completion. In the future it might be better for NameSpace to implement
* NameCompletion directly in a more native and efficient fasion. However in
* general name competion is used for human interaction and therefore does not
* require high performance.
* <p>
* @see bsh.util.NameCompletion
* @see bsh.util.NameCompletionTable
*/
public interface NameSource {
public String[] getAllNames();
public void addNameSourceListener(NameSource.Listener listener);
public static interface Listener {
public void nameSourceChanged(NameSource src);
/**
* Provide feedback on the progress of mapping a namespace
*
* @param msg is an update about what's happening
* @perc is an integer in the range 0-100 indicating percentage done
* public void nameSourceMapping( NameSource src, String msg, int perc
* );
*/
}
}
| 3,820 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
This.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/This.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
import java.lang.reflect.*;
import java.util.HashMap;
import java.util.Map;
/**
* 'This' is the type of bsh scripted objects. A 'This' object is a bsh scripted
* object context. It holds a namespace reference and implements event listeners
* and various other interfaces.
*
* This holds a reference to the declaring interpreter for callbacks from
* outside of bsh.
*/
public class This implements java.io.Serializable, Runnable {
/**
* The namespace that this This reference wraps.
*/
final NameSpace namespace;
/**
* This is the interpreter running when the This ref was created. It's used
* as a default interpreter for callback through the This where there is no
* current interpreter instance e.g. interface proxy or event call backs
* from outside of bsh.
*/
transient Interpreter declaringInterpreter;
/**
* A cache of proxy interface handlers. Currently just one per interface.
*/
private Map<Integer, Object> interfaces;
private final InvocationHandler invocationHandler = new Handler();
/**
* getThis() is a factory for bsh.This type references. The capabilities of
* ".this" references in bsh are version dependent up until jdk1.3. The
* version dependence was to support different default interface
* implementations. i.e. different sets of listener interfaces which
* scripted objects were capable of implementing. In jdk1.3 the reflection
* proxy mechanism was introduced which allowed us to implement arbitrary
* interfaces. This is fantastic.
*
* A This object is a thin layer over a namespace, comprising a bsh object
* context. We create it here only if needed for the namespace.
*
* Note: this method could be considered slow because of the way it
* dynamically factories objects. However I've also done tests where I
* hard-code the factory to return JThis and see no change in the rough test
* suite time. This references are also cached in NameSpace.
*/
static This getThis(
NameSpace namespace, Interpreter declaringInterpreter) {
return new This(namespace, declaringInterpreter);
}
/**
* Get a version of this scripted object implementing the specified
* interface.
*/
/**
* Get dynamic proxy for interface, caching those it creates.
*/
public Object getInterface(Class clas) {
return getInterface(new Class[]{clas});
}
/**
* Get dynamic proxy for interface, caching those it creates.
*/
public Object getInterface(Class[] ca) {
if (interfaces == null) {
interfaces = new HashMap<>();
}
// Make a hash of the interface hashcodes in order to cache them
int hash = 21;
for (int i = 0; i < ca.length; i++) {
hash *= ca[i].hashCode() + 3;
}
Integer hashKey = hash;
Object interf = interfaces.get(hashKey);
if (interf == null) {
ClassLoader classLoader = ca[0].getClassLoader(); // ?
interf = Proxy.newProxyInstance(
classLoader, ca, invocationHandler);
interfaces.put(hashKey, interf);
}
return interf;
}
/**
* This is the invocation handler for the dynamic proxy.
* <p>
*
* Notes: Inner class for the invocation handler seems to shield this
* unavailable interface from JDK1.2 VM... * I don't understand this. JThis
* works just fine even if those classes aren't there (doesn't it?) This
* class shouldn't be loaded if an XThis isn't instantiated in
* NameSpace.java, should it?
*/
class Handler implements InvocationHandler, java.io.Serializable {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
try {
return invokeImpl(proxy, method, args);
} catch (TargetError te) {
// Unwrap target exception. If the interface declares that
// it throws the ex it will be delivered. If not it will be
// wrapped in an UndeclaredThrowable
// This isn't simple because unwrapping this loses all context info.
// So rewrap is better than unwrap. - fschmidt
Throwable t = te.getTarget();
Class<? extends Throwable> c = t.getClass();
String msg = t.getMessage();
try {
Throwable t2 = msg == null
? c.getConstructor().newInstance()
: c.getConstructor(String.class).newInstance(msg);
t2.initCause(te);
throw t2;
} catch (NoSuchMethodException e) {
throw t;
}
} catch (EvalError ee) {
// Ease debugging...
// XThis.this refers to the enclosing class instance
if (Interpreter.DEBUG) {
Interpreter.debug("EvalError in scripted interface: "
+ This.this.toString() + ": " + ee);
}
throw ee;
}
}
public Object invokeImpl(Object proxy, Method method, Object[] args)
throws EvalError {
String methodName = method.getName();
CallStack callstack = new CallStack(namespace);
/*
If equals() is not explicitly defined we must override the
default implemented by the This object protocol for scripted
object. To support XThis equals() must test for equality with
the generated proxy object, not the scripted bsh This object;
otherwise callers from outside in Java will not see a the
proxy object as equal to itself.
*/
BSHMethod equalsMethod = null;
try {
equalsMethod = namespace.getMethod(
"equals", new Class[]{Object.class});
} catch (UtilEvalError e) {/*leave null*/ }
if (methodName.equals("equals") && equalsMethod == null) {
Object obj = args[0];
return proxy == obj;
}
/*
If toString() is not explicitly defined override the default
to show the proxy interfaces.
*/
BSHMethod toStringMethod = null;
try {
toStringMethod
= namespace.getMethod("toString", new Class[]{});
} catch (UtilEvalError e) {/*leave null*/ }
if (methodName.equals("toString") && toStringMethod == null) {
Class[] ints = proxy.getClass().getInterfaces();
// XThis.this refers to the enclosing class instance
StringBuilder sb = new StringBuilder(
This.this.toString() + "\nimplements:");
for (int i = 0; i < ints.length; i++) {
sb.append(" ").append(ints[i].getName()).append((ints.length > 1) ? "," : "");
}
return sb.toString();
}
Class[] paramTypes = method.getParameterTypes();
return Primitive.unwrap(
invokeMethod(methodName, Primitive.wrap(args, paramTypes)));
}
}
This(NameSpace namespace, Interpreter declaringInterpreter) {
this.namespace = namespace;
this.declaringInterpreter = declaringInterpreter;
//initCallStack( namespace );
}
public NameSpace getNameSpace() {
return namespace;
}
@Override
public String toString() {
return "'this' reference to Bsh object: " + namespace;
}
@Override
public void run() {
try {
invokeMethod("run", new Object[0]);
} catch (EvalError e) {
declaringInterpreter.error(
"Exception in runnable:" + e);
}
}
/**
* Invoke specified method as from outside java code, using the declaring
* interpreter and current namespace. The call stack will indicate that the
* method is being invoked from outside of bsh in native java code. Note:
* you must still wrap/unwrap args/return values using
* Primitive/Primitive.unwrap() for use outside of BeanShell.
*
* @see ehacks.bsh.Primitive
*/
public Object invokeMethod(String name, Object[] args)
throws EvalError {
// null callstack, one will be created for us
return invokeMethod(
name, args, null/*declaringInterpreter*/, null, null,
false/*declaredOnly*/);
}
/**
* Invoke a method in this namespace with the specified args, interpreter
* reference, callstack, and caller info.
* <p>
*
* Note: If you use this method outside of the bsh package and wish to use
* variables with primitive values you will have to wrap them using
* bsh.Primitive. Consider using This getInterface() to make a true Java
* interface for invoking your scripted methods.
* <p>
*
* This method also implements the default object protocol of toString(),
* hashCode() and equals() and the invoke() meta-method handling as a last
* resort.
* <p>
*
* Note: The invoke() meta-method will not catch the Object protocol methods
* (toString(), hashCode()...). If you want to override them you have to
* script them directly.
* <p>
*
* @param callstack if callStack is null a new CallStack will be created and
* initialized with this namespace.
* @param declaredOnly if true then only methods declared directly in the
* namespace will be visible - no inherited or imported methods will be
* visible.
* @see ehacks.bsh.Primitive
*/
/*
invokeMethod() here is generally used by outside code to callback
into the bsh interpreter. e.g. when we are acting as an interface
for a scripted listener, etc. In this case there is no real call stack
so we make a default one starting with the special JAVACODE namespace
and our namespace as the next.
*/
public Object invokeMethod(
String methodName, Object[] args,
Interpreter interpreter, CallStack callstack, SimpleNode callerInfo,
boolean declaredOnly)
throws EvalError {
/*
Wrap nulls.
This is a bit of a cludge to address a deficiency in the class
generator whereby it does not wrap nulls on method delegate. See
Class Generator.java. If we fix that then we can remove this.
(just have to generate the code there.)
*/
if (args == null) {
args = new Object[0];
} else {
Object[] oa = new Object[args.length];
for (int i = 0; i < args.length; i++) {
oa[i] = (args[i] == null ? Primitive.NULL : args[i]);
}
args = oa;
}
if (interpreter == null) {
interpreter = declaringInterpreter;
}
if (callstack == null) {
callstack = new CallStack(namespace);
}
if (callerInfo == null) {
callerInfo = SimpleNode.JAVACODE;
}
// Find the bsh method
Class[] types = Types.getTypes(args);
BSHMethod bshMethod = null;
try {
bshMethod = namespace.getMethod(methodName, types, declaredOnly);
} catch (UtilEvalError e) {
// leave null
}
if (bshMethod != null) {
return bshMethod.invoke(args, interpreter, callstack, callerInfo);
}
/*
No scripted method of that name.
Implement the required part of the Object protocol:
public int hashCode();
public boolean equals(java.lang.Object);
public java.lang.String toString();
if these were not handled by scripted methods we must provide
a default impl.
*/
// a default toString() that shows the interfaces we implement
if (methodName.equals("toString") && args.length == 0) {
return toString();
}
// a default hashCode()
if (methodName.equals("hashCode") && args.length == 0) {
return this.hashCode();
}
// a default equals() testing for equality with the This reference
if (methodName.equals("equals") && args.length == 1) {
Object obj = args[0];
return this == obj;
}
// a default clone()
if (methodName.equals("clone") && args.length == 0) {
NameSpace ns = new NameSpace(namespace, namespace.getName() + " clone");
try {
for (String varName : namespace.getVariableNames()) {
ns.setLocalVariable(varName, namespace.getVariable(varName, false), false);
}
for (BSHMethod method : namespace.getMethods()) {
ns.setMethod(method);
}
} catch (UtilEvalError e) {
throw e.toEvalError(SimpleNode.JAVACODE, callstack);
}
return ns.getThis(declaringInterpreter);
}
// Look for a default invoke() handler method in the namespace
// Note: this code duplicates that in NameSpace getCommand()
// is that ok?
try {
bshMethod = namespace.getMethod(
"invoke", new Class[]{null, null});
} catch (UtilEvalError e) {
/*leave null*/ }
// Call script "invoke( String methodName, Object [] args );
if (bshMethod != null) {
return bshMethod.invoke(new Object[]{methodName, args},
interpreter, callstack, callerInfo);
}
throw new EvalError("Method "
+ StringUtil.methodString(methodName, types)
+ " not found in bsh scripted object: " + namespace.getName(),
callerInfo, callstack);
}
/**
* Bind a This reference to a parent's namespace with the specified
* declaring interpreter. Also re-init the callstack. It's necessary to bind
* a This reference before it can be used after deserialization. This is
* used by the bsh load() command.
* <p>
*
* This is a static utility method because it's used by a bsh command bind()
* and the interpreter doesn't currently allow access to direct methods of
* This objects (small hack)
*/
public static void bind(
This ths, NameSpace namespace, Interpreter declaringInterpreter) {
ths.namespace.setParent(namespace);
ths.declaringInterpreter = declaringInterpreter;
}
/**
* Allow invocations of these method names on This type objects. Don't give
* bsh.This a chance to override their behavior.
* <p>
*
* If the method is passed here the invocation will actually happen on the
* bsh.This object via the regular reflective method invocation mechanism.
* If not, then the method is evaluated by bsh.This itself as a scripted
* method call.
*/
static boolean isExposedThisMethod(String name) {
return name.equals("getClass")
|| name.equals("invokeMethod")
|| name.equals("getInterface")
// These are necessary to let us test synchronization from scripts
|| name.equals("wait")
|| name.equals("notify")
|| name.equals("notifyAll");
}
}
| 18,165 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHVariableDeclarator.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHVariableDeclarator.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
/**
* name [ = initializer ] evaluate name and return optional initializer
*/
class BSHVariableDeclarator extends SimpleNode {
// The token.image text of the name... never changes.
public String name;
BSHVariableDeclarator(int id) {
super(id);
}
/**
* Evaluate the optional initializer value. (The name was set at parse
* time.)
*
* A variable declarator can be evaluated with or without preceding type
* information. Currently the type info is only used by array initializers
* in the case where there is no explicitly declared type.
*
* @param typeNode is the BSHType node. Its info is passed through to any
* variable intializer children for the case where the array initializer
* does not declare the type explicitly. e.g. int [] a = { 1, 2 }; typeNode
* may be null to indicate no type information available.
*/
public Object eval(
BSHType typeNode, CallStack callstack, Interpreter interpreter)
throws EvalError {
// null value means no value
Object value = null;
if (jjtGetNumChildren() > 0) {
SimpleNode initializer = (SimpleNode) jjtGetChild(0);
/*
If we have type info and the child is an array initializer
pass it along... Else use the default eval style.
(This allows array initializer to handle the problem...
allowing for future enhancements in loosening types there).
*/
if ((typeNode != null)
&& initializer instanceof BSHArrayInitializer) {
value = ((BSHArrayInitializer) initializer).eval(
typeNode.getBaseType(), typeNode.getArrayDims(),
callstack, interpreter);
} else {
value = initializer.eval(callstack, interpreter);
}
}
if (value == Primitive.VOID) {
throw new EvalError("Void initializer.", this, callstack);
}
return value;
}
@Override
public String toString() {
return "BSHVariableDeclarator " + name;
}
}
| 4,696 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
Reflect.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/Reflect.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
/**
* All of the reflection API code lies here. It is in the form of static
* utilities. Maybe this belongs in LHS.java or a generic object wrapper class.
*/
/*
Note: This class is messy. The method and field resolution need to be
rewritten. Various methods in here catch NoSuchMethod or NoSuchField
exceptions during their searches. These should be rewritten to avoid
having to catch the exceptions. Method lookups are now cached at a high
level so they are less important, however the logic is messy.
*/
class Reflect {
/**
* Invoke method on arbitrary object instance. invocation may be static
* (through the object instance) or dynamic. Object may be a bsh scripted
* object (bsh.This type).
*
* @return the result of the method call
*/
public static Object invokeObjectMethod(Object object, String methodName, Object[] args, Interpreter interpreter, CallStack callstack, SimpleNode callerInfo) throws ReflectError, EvalError, InvocationTargetException {
// Bsh scripted object
if (object instanceof This && !This.isExposedThisMethod(methodName)) {
return ((This) object).invokeMethod(methodName, args, interpreter, callstack, callerInfo, false/*delcaredOnly*/);
}
// Plain Java object, find the java method
try {
BSHClassManager bcm = interpreter == null ? null : interpreter.getClassManager();
Class clas = object.getClass();
Method method = resolveExpectedJavaMethod(bcm, clas, object, methodName, args, false);
return invokeMethod(method, object, args);
} catch (UtilEvalError e) {
throw e.toEvalError(callerInfo, callstack);
}
}
/**
* Invoke a method known to be static. No object instance is needed and
* there is no possibility of the method being a bsh scripted method.
*/
public static Object invokeStaticMethod(BSHClassManager bcm, Class clas, String methodName, Object[] args) throws ReflectError, UtilEvalError, InvocationTargetException {
Interpreter.debug("invoke static Method");
Method method = resolveExpectedJavaMethod(bcm, clas, null, methodName, args, true);
return invokeMethod(method, null, args);
}
/**
* Invoke the Java method on the specified object, performing needed type
* mappings on arguments and return values.
*
* @param args may be null
*/
static Object invokeMethod(Method method, Object object, Object[] args) throws ReflectError, InvocationTargetException {
if (args == null) {
args = new Object[0];
}
logInvokeMethod("Invoking method (entry): ", method, args);
boolean isVarArgs = method.isVarArgs();
// Map types to assignable forms, need to keep this fast...
Class[] types = method.getParameterTypes();
Object[] tmpArgs = new Object[types.length];
int fixedArgLen = types.length;
if (isVarArgs) {
if (fixedArgLen == args.length && types[fixedArgLen - 1].isAssignableFrom(args[fixedArgLen - 1].getClass())) {
isVarArgs = false;
} else {
fixedArgLen--;
}
}
try {
for (int i = 0; i < fixedArgLen; i++) {
tmpArgs[i] = Types.castObject(args[i]/*rhs*/, types[i]/*lhsType*/, Types.ASSIGNMENT);
}
if (isVarArgs) {
Class varType = types[fixedArgLen].getComponentType();
Object varArgs = Array.newInstance(varType, args.length - fixedArgLen);
for (int i = fixedArgLen, j = 0; i < args.length; i++, j++) {
Array.set(varArgs, j, Primitive.unwrap(Types.castObject(args[i]/*rhs*/, varType/*lhsType*/, Types.ASSIGNMENT)));
}
tmpArgs[fixedArgLen] = varArgs;
}
} catch (UtilEvalError e) {
throw new InterpreterError("illegal argument type in method invocation: " + e);
}
// unwrap any primitives
tmpArgs = Primitive.unwrap(tmpArgs);
logInvokeMethod("Invoking method (after massaging values): ", method, tmpArgs);
try {
Object returnValue = method.invoke(object, tmpArgs);
if (returnValue == null) {
returnValue = Primitive.NULL;
}
Class returnType = method.getReturnType();
return Primitive.wrap(returnValue, returnType);
} catch (IllegalAccessException e) {
throw new ReflectError("Cannot access method " + StringUtil.methodString(method.getName(), method.getParameterTypes()) + " in '" + method.getDeclaringClass() + "' :" + e, e);
}
}
public static Object getIndex(Object array, int index) throws ReflectError, UtilTargetError {
if (Interpreter.DEBUG) {
Interpreter.debug("getIndex: " + array + ", index=" + index);
}
try {
Object val = Array.get(array, index);
return Primitive.wrap(val, array.getClass().getComponentType());
} catch (ArrayIndexOutOfBoundsException e1) {
throw new UtilTargetError(e1);
} catch (Exception e) {
throw new ReflectError("Array access:" + e);
}
}
public static void setIndex(Object array, int index, Object val) throws ReflectError, UtilTargetError {
try {
val = Primitive.unwrap(val);
Array.set(array, index, val);
} catch (ArrayStoreException e2) {
throw new UtilTargetError(e2);
} catch (IllegalArgumentException e1) {
//noinspection ThrowableInstanceNeverThrown
throw new UtilTargetError(new ArrayStoreException(e1.toString()));
} catch (Exception e) {
throw new ReflectError("Array access:" + e);
}
}
public static Object getStaticFieldValue(Class clas, String fieldName) throws UtilEvalError, ReflectError {
return getFieldValue(clas, null, fieldName, true/*onlystatic*/);
}
/**
*/
public static Object getObjectFieldValue(Object object, String fieldName) throws UtilEvalError, ReflectError {
if (object instanceof This) {
return ((This) object).namespace.getVariable(fieldName);
} else if (object == Primitive.NULL) {
//noinspection ThrowableInstanceNeverThrown
throw new UtilTargetError(new NullPointerException("Attempt to access field '" + fieldName + "' on null value"));
} else {
try {
return getFieldValue(object.getClass(), object, fieldName, false/*onlystatic*/);
} catch (ReflectError e) {
// no field, try property acces
if (hasObjectPropertyGetter(object.getClass(), fieldName)) {
return getObjectProperty(object, fieldName);
} else {
throw e;
}
}
}
}
static LHS getLHSStaticField(Class clas, String fieldName) throws UtilEvalError, ReflectError {
Field f = resolveExpectedJavaField(clas, fieldName, true/*onlystatic*/);
return new LHS(f);
}
/**
* Get an LHS reference to an object field.
* <p/>
* This method also deals with the field style property access. In the field
* does not exist we check for a property setter.
*/
static LHS getLHSObjectField(Object object, String fieldName) throws UtilEvalError, ReflectError {
if (object instanceof This) {
// I guess this is when we pass it as an argument?
// Setting locally
boolean recurse = false;
return new LHS(((This) object).namespace, fieldName, recurse);
}
try {
Field f = resolveExpectedJavaField(object.getClass(), fieldName, false/*staticOnly*/);
return new LHS(object, f);
} catch (ReflectError e) {
// not a field, try property access
if (hasObjectPropertySetter(object.getClass(), fieldName)) {
return new LHS(object, fieldName);
} else {
throw e;
}
}
}
private static Object getFieldValue(Class clas, Object object, String fieldName, boolean staticOnly) throws UtilEvalError, ReflectError {
try {
Field f = resolveExpectedJavaField(clas, fieldName, staticOnly);
Object value = f.get(object);
Class returnType = f.getType();
return Primitive.wrap(value, returnType);
} catch (NullPointerException e) { // shouldn't happen
throw new ReflectError("???" + fieldName + " is not a static field.");
} catch (IllegalAccessException e) {
throw new ReflectError("Can't access field: " + fieldName);
}
}
/*
Note: this method and resolveExpectedJavaField should be rewritten
to invert this logic so that no exceptions need to be caught
unecessarily. This is just a temporary impl.
@return the field or null if not found
*/
static Field resolveJavaField(Class clas, String fieldName, boolean staticOnly) throws UtilEvalError {
try {
return resolveExpectedJavaField(clas, fieldName, staticOnly);
} catch (ReflectError e) {
return null;
}
}
/**
* @throws ReflectError if the field is not found.
*/
/*
Note: this should really just throw NoSuchFieldException... need
to change related signatures and code.
*/
static Field resolveExpectedJavaField(Class clas, String fieldName, boolean staticOnly) throws UtilEvalError, ReflectError {
Field field;
try {
field = clas.getDeclaredField(fieldName);
field.setAccessible(true);
} catch (NoSuchFieldException e) {
throw new ReflectError("No such field: " + fieldName, e);
} catch (SecurityException e) {
throw new UtilTargetError("Security Exception while searching fields of: " + clas, e);
}
if (staticOnly && !Modifier.isStatic(field.getModifiers())) {
throw new UtilEvalError("Can't reach instance field: " + fieldName + " from static context: " + clas.getName());
}
return field;
}
/**
* This method wraps resolveJavaMethod() and expects a non-null method
* result. If the method is not found it throws a descriptive ReflectError.
*/
static Method resolveExpectedJavaMethod(BSHClassManager bcm, Class clas, Object object, String name, Object[] args, boolean staticOnly) throws ReflectError, UtilEvalError {
if (object == Primitive.NULL) {
//noinspection ThrowableInstanceNeverThrown
throw new UtilTargetError(new NullPointerException("Attempt to invoke method " + name + " on null value"));
}
Class[] types = Types.getTypes(args);
Method method = resolveJavaMethod(bcm, clas, name, types, staticOnly);
if (method == null) {
throw new ReflectError((staticOnly ? "Static method " : "Method ") + StringUtil.methodString(name, types) + " not found in class'" + clas.getName() + "'");
}
return method;
}
/**
* The full blown resolver method. All other method invocation methods
* delegate to this. The method may be static or dynamic unless staticOnly
* is set (in which case object may be null). If staticOnly is set then only
* static methods will be located.
* <p/>
* <p/>
* This method performs caching (caches discovered methods through the class
* manager and utilizes cached methods.)
* <p/>
* <p/>
* This method determines whether to attempt to use non-public methods based
* on Capabilities.haveAccessibility() and will set the accessibilty flag on
* the method as necessary.
* <p/>
* <p/>
* If, when directed to find a static method, this method locates a more
* specific matching instance method it will throw a descriptive exception
* analogous to the error that the Java compiler would produce. Note: as of
* 2.0.x this is a problem because there is no way to work around this with
* a cast.
* <p/>
*
* @param staticOnly The method located must be static, the object param may
* be null.
* @return the method or null if no matching method was found.
*/
static Method resolveJavaMethod(BSHClassManager bcm, Class clas, String name, Class[] types, boolean staticOnly) throws UtilEvalError {
if (clas == null) {
throw new InterpreterError("null class");
}
// Lookup previously cached method
Method method = null;
if (bcm == null) {
Interpreter.debug("resolveJavaMethod UNOPTIMIZED lookup");
} else {
method = bcm.getResolvedMethod(clas, name, types, staticOnly);
}
if (method == null) {
boolean publicOnly = !Capabilities.haveAccessibility();
// Searching for the method may, itself be a priviledged action
try {
method = findOverloadedMethod(clas, name, types, publicOnly);
} catch (SecurityException e) {
throw new UtilTargetError("Security Exception while searching methods of: " + clas, e);
}
checkFoundStaticMethod(method, staticOnly, clas);
// This is the first time we've seen this method, set accessibility
// Note: even if it's a public method, we may have found it in a
// non-public class
if (method != null) {
try {
method.setAccessible(true);
} catch (SecurityException e) {
method = null;
}
}
// If succeeded cache the resolved method.
if (method != null && bcm != null) {
bcm.cacheResolvedMethod(clas, types, method);
}
}
return method;
}
/**
* Get the candidate methods by searching the class and interface graph of
* baseClass and resolve the most specific.
*
* @return the method or null for not found
*/
private static Method findOverloadedMethod(Class baseClass, String methodName, Class[] types, boolean publicOnly) {
if (Interpreter.DEBUG) {
Interpreter.debug("Searching for method: " + StringUtil.methodString(methodName, types) + " in '" + baseClass.getName() + "'");
}
List<Method> publicMethods = new ArrayList<>();
List<Method> nonPublicMethods = publicOnly ? null : new ArrayList<>();
gatherMethodsRecursive(baseClass, methodName, types.length, publicMethods, nonPublicMethods);
if (Interpreter.DEBUG) {
Interpreter.debug("Looking for most specific method: " + methodName);
}
Method method = findMostSpecificMethod(types, publicMethods);
if (method == null && nonPublicMethods != null) {
method = findMostSpecificMethod(types, nonPublicMethods);
}
return method;
}
/*
Climb the class and interface inheritence graph of the type and collect
all methods matching the specified name and criterion. If publicOnly
is true then only public methods in *public* classes or interfaces will
be returned. In the normal (non-accessible) case this addresses the
problem that arises when a package private class or private inner class
implements a public interface or derives from a public type.
<p/>
preseving old comments for deleted getCandidateMethods() - fschmidt
*/
/**
* Accumulate all methods, optionally including non-public methods, class
* and interface, in the inheritence tree of baseClass.
* <p/>
* This method is analogous to Class getMethods() which returns all public
* methods in the inheritence tree.
* <p/>
* In the normal (non-accessible) case this also addresses the problem that
* arises when a package private class or private inner class implements a
* public interface or derives from a public type. In other words, sometimes
* we'll find public methods that we can't use directly and we have to find
* the same public method in a parent class or interface.
*
* @return the candidate methods vector
*/
private static void gatherMethodsRecursive(Class baseClass, String methodName, int numArgs, List<Method> publicMethods, List<Method> nonPublicMethods) {
// Do we have a superclass? (interfaces don't, etc.)
Class superclass = baseClass.getSuperclass();
if (superclass != null) {
gatherMethodsRecursive(superclass, methodName, numArgs, publicMethods, nonPublicMethods);
}
// Add methods of the current class to the list.
// In public case be careful to only add methods from a public class
// and to use getMethods() instead of getDeclaredMethods()
// (This addresses secure environments)
boolean isPublicClass = isPublic(baseClass);
if (isPublicClass || nonPublicMethods != null) {
Method[] methods = baseClass.getDeclaredMethods();
for (Method m : methods) {
if (m.getName().equals(methodName) && (m.isVarArgs() ? m.getParameterTypes().length - 1 <= numArgs : m.getParameterTypes().length == numArgs)) {
if (isPublicClass && isPublic(m)) {
publicMethods.add(m);
} else if (nonPublicMethods != null) {
nonPublicMethods.add(m);
}
}
}
}
// Does the class or interface implement interfaces?
for (Class intf : baseClass.getInterfaces()) {
gatherMethodsRecursive(intf, methodName, numArgs, publicMethods, nonPublicMethods);
}
}
/**
* Primary object constructor This method is simpler than those that must
* resolve general method invocation because constructors are not inherited.
* <p/>
* This method determines whether to attempt to use non-public constructors
* based on Capabilities.haveAccessibility() and will set the accessibilty
* flag on the method as necessary.
* <p/>
*/
static Object constructObject(Class clas, Object[] args) throws ReflectError, InvocationTargetException {
if (clas.isInterface()) {
throw new ReflectError("Can't create instance of an interface: " + clas);
}
Class[] types = Types.getTypes(args);
// Find the constructor.
// (there are no inherited constructors to worry about)
Constructor[] constructors = Capabilities.haveAccessibility() ? clas.getDeclaredConstructors() : clas.getConstructors();
if (Interpreter.DEBUG) {
Interpreter.debug("Looking for most specific constructor: " + clas);
}
Constructor con = findMostSpecificConstructor(types, constructors);
if (con == null) {
// RRB: added for BEAST
if (con == null) {
throw cantFindConstructor(clas, types);
}
}
if (!isPublic(con) && Capabilities.haveAccessibility()) {
con.setAccessible(true);
}
args = Primitive.unwrap(args);
try {
// RRB: added for BEAST
return con.newInstance(args);
} catch (InstantiationException e) {
throw new ReflectError("The class " + clas + " is abstract ");
} catch (IllegalAccessException e) {
throw new ReflectError("We don't have permission to create an instance." + "Use setAccessibility(true) to enable access.");
} catch (IllegalArgumentException e) {
throw new ReflectError("The number of arguments was wrong");
}
}
/*
This method should parallel findMostSpecificMethod()
The only reason it can't be combined is that Method and Constructor
don't have a common interface for their signatures
*/
static Constructor findMostSpecificConstructor(Class[] idealMatch, Constructor[] constructors) {
int match = findMostSpecificConstructorIndex(idealMatch, constructors);
return (match == -1) ? null : constructors[match];
}
static int findMostSpecificConstructorIndex(Class[] idealMatch, Constructor[] constructors) {
Class[][] candidates = new Class[constructors.length][];
for (int i = 0; i < candidates.length; i++) {
candidates[i] = constructors[i].getParameterTypes();
}
return findMostSpecificSignature(idealMatch, candidates);
}
/**
* Find the best match for signature idealMatch. It is assumed that the
* methods array holds only valid candidates (e.g. method name and number of
* args already matched). This method currently does not take into account
* Java 5 covariant return types... which I think will require that we find
* the most derived return type of otherwise identical best matches.
*
* @param methods the set of candidate method which differ only in the types
* of their arguments.
* @see #findMostSpecificSignature(Class[], Class[][])
*/
private static Method findMostSpecificMethod(Class[] idealMatch, List<Method> methods) {
// copy signatures into array for findMostSpecificMethod()
List<Class[]> candidateSigs = new ArrayList<>();
List<Method> methodList = new ArrayList<>();
methods.forEach((method) -> {
Class[] parameterTypes = method.getParameterTypes();
methodList.add(method);
candidateSigs.add(parameterTypes);
if (method.isVarArgs()) {
Class[] candidateSig = new Class[idealMatch.length];
int j = 0;
for (; j < parameterTypes.length - 1; j++) {
candidateSig[j] = parameterTypes[j];
}
Class varType = parameterTypes[j].getComponentType();
for (; j < idealMatch.length; j++) {
candidateSig[j] = varType;
}
methodList.add(method);
candidateSigs.add(candidateSig);
}
});
int match = findMostSpecificSignature(idealMatch, candidateSigs.toArray(new Class[candidateSigs.size()][]));
return match == -1 ? null : methodList.get(match);
}
/**
* Implement JLS 15.11.2 Return the index of the most specific arguments
* match or -1 if no match is found. This method is used by both methods and
* constructors (which unfortunately don't share a common interface for
* signature info).
*
* @return the index of the most specific candidate
*/
/*
Note: Two methods which are equally specific should not be allowed by
the Java compiler. In this case BeanShell currently chooses the first
one it finds. We could add a test for this case here (I believe) by
adding another isSignatureAssignable() in the other direction between
the target and "best" match. If the assignment works both ways then
neither is more specific and they are ambiguous. I'll leave this test
out for now because I'm not sure how much another test would impact
performance. Method selection is now cached at a high level, so a few
friendly extraneous tests shouldn't be a problem.
*/
static int findMostSpecificSignature(Class[] idealMatch, Class[][] candidates) {
for (int round = Types.FIRST_ROUND_ASSIGNABLE; round <= Types.LAST_ROUND_ASSIGNABLE; round++) {
Class[] bestMatch = null;
int bestMatchIndex = -1;
for (int i = 0; i < candidates.length; i++) {
Class[] targetMatch = candidates[i];
// If idealMatch fits targetMatch and this is the first match
// or targetMatch is more specific than the best match, make it
// the new best match.
if (Types.isSignatureAssignable(idealMatch, targetMatch, round) && ((bestMatch == null) || Types.isSignatureAssignable(targetMatch, bestMatch, Types.JAVA_BASE_ASSIGNABLE))) {
bestMatch = targetMatch;
bestMatchIndex = i;
}
}
if (bestMatch != null) {
return bestMatchIndex;
}
}
return -1;
}
private static String accessorName(String getorset, String propName) {
return getorset + String.valueOf(Character.toUpperCase(propName.charAt(0))) + propName.substring(1);
}
public static boolean hasObjectPropertyGetter(Class clas, String propName) {
if (clas == Primitive.class) {
return false;
}
String getterName = accessorName("get", propName);
try {
clas.getMethod(getterName, new Class[0]);
return true;
} catch (NoSuchMethodException e) {
/* fall through */ }
getterName = accessorName("is", propName);
try {
Method m = clas.getMethod(getterName, new Class[0]);
return (m.getReturnType() == Boolean.TYPE);
} catch (NoSuchMethodException e) {
return false;
}
}
public static boolean hasObjectPropertySetter(Class clas, String propName) {
String setterName = accessorName("set", propName);
Method[] methods = clas.getMethods();
// we don't know the right hand side of the assignment yet.
// has at least one setter of the right name?
for (Method method : methods) {
if (method.getName().equals(setterName)) {
return true;
}
}
return false;
}
public static Object getObjectProperty(Object obj, String propName) throws UtilEvalError, ReflectError {
Object[] args = new Object[]{};
Interpreter.debug("property access: ");
Method method = null;
Exception e1 = null, e2 = null;
try {
String accessorName = accessorName("get", propName);
method = resolveExpectedJavaMethod(null/*bcm*/, obj.getClass(), obj, accessorName, args, false);
} catch (Exception e) {
e1 = e;
}
if (method == null) {
try {
String accessorName = accessorName("is", propName);
method = resolveExpectedJavaMethod(null/*bcm*/, obj.getClass(), obj, accessorName, args, false);
if (method.getReturnType() != Boolean.TYPE) {
method = null;
}
} catch (Exception e) {
e2 = e;
}
}
if (method == null) {
throw new ReflectError("Error in property getter: " + e1 + (e2 != null ? " : " + e2 : ""));
}
try {
return invokeMethod(method, obj, args);
} catch (InvocationTargetException e) {
throw new UtilEvalError("Property accessor threw exception: " + e.getTargetException());
}
}
public static void setObjectProperty(Object obj, String propName, Object value) throws ReflectError, UtilEvalError {
String accessorName = accessorName("set", propName);
Object[] args = new Object[]{value};
Interpreter.debug("property access: ");
try {
Method method = resolveExpectedJavaMethod(null/*bcm*/, obj.getClass(), obj, accessorName, args, false);
invokeMethod(method, obj, args);
} catch (InvocationTargetException e) {
throw new UtilEvalError("Property accessor threw exception: " + e.getTargetException());
}
}
/**
* Return a more human readable version of the type name. Specifically,
* array types are returned with postfix "[]" dimensions. e.g. return "int
* []" for integer array instead of "class [I" as would be returned by Class
* getName() in that case.
*/
public static String normalizeClassName(Class type) {
if (!type.isArray()) {
return type.getName();
}
StringBuilder className = new StringBuilder();
try {
className.append(getArrayBaseType(type).getName()).append(' ');
for (int i = 0; i < getArrayDimensions(type); i++) {
className.append("[]");
}
} catch (ReflectError e) {
/*shouldn't happen*/
}
return className.toString();
}
/**
* returns the dimensionality of the Class returns 0 if the Class is not an
* array class
*/
public static int getArrayDimensions(Class arrayClass) {
if (!arrayClass.isArray()) {
return 0;
}
return arrayClass.getName().lastIndexOf('[') + 1; // why so cute?
}
/**
* Returns the base type of an array Class. throws ReflectError if the Class
* is not an array class.
*/
public static Class getArrayBaseType(Class arrayClass) throws ReflectError {
if (!arrayClass.isArray()) {
throw new ReflectError("The class is not an array.");
}
return arrayClass.getComponentType();
}
/**
* A command may be implemented as a compiled Java class containing one or
* more static invoke() methods of the correct signature. The invoke()
* methods must accept two additional leading arguments of the interpreter
* and callstack, respectively. e.g. invoke(interpreter, callstack, ... )
* This method adds the arguments and invokes the static method, returning
* the result.
*/
public static Object invokeCompiledCommand(Class commandClass, Object[] args, Interpreter interpreter, CallStack callstack) throws UtilEvalError {
// add interpereter and namespace to args list
Object[] invokeArgs = new Object[args.length + 2];
invokeArgs[0] = interpreter;
invokeArgs[1] = callstack;
System.arraycopy(args, 0, invokeArgs, 2, args.length);
BSHClassManager bcm = interpreter.getClassManager();
try {
return Reflect.invokeStaticMethod(bcm, commandClass, "invoke", invokeArgs);
} catch (InvocationTargetException e) {
throw new UtilEvalError("Error in compiled command: " + e.getTargetException(), e);
} catch (ReflectError e) {
throw new UtilEvalError("Error invoking compiled command: " + e, e);
}
}
private static void logInvokeMethod(String msg, Method method, Object[] args) {
if (Interpreter.DEBUG) {
Interpreter.debug(msg + method + " with args:");
for (int i = 0; i < args.length; i++) {
final Object arg = args[i];
Interpreter.debug("args[" + i + "] = " + arg + " type = " + (arg == null ? "<unkown>" : arg.getClass()));
}
}
}
private static void checkFoundStaticMethod(Method method, boolean staticOnly, Class clas) throws UtilEvalError {
// We're looking for a static method but found an instance method
if (method != null && staticOnly && !isStatic(method)) {
throw new UtilEvalError("Cannot reach instance method: " + StringUtil.methodString(method.getName(), method.getParameterTypes()) + " from static context: " + clas.getName());
}
}
private static ReflectError cantFindConstructor(Class clas, Class[] types) {
if (types.length == 0) {
return new ReflectError("Can't find default constructor for: " + clas);
} else {
return new ReflectError("Can't find constructor: " + StringUtil.methodString(clas.getName(), types) + " in class: " + clas.getName());
}
}
private static boolean isPublic(Member member) {
return Modifier.isPublic(member.getModifiers());
}
private static boolean isPublic(Class clazz) {
return Modifier.isPublic(clazz.getModifiers());
}
private static boolean isStatic(Method m) {
return Modifier.isStatic(m.getModifiers());
}
static void setAccessible(final Field field) {
if (!isPublic(field) && Capabilities.haveAccessibility()) {
field.setAccessible(true);
}
}
}
| 35,308 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
LHS.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/LHS.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
import java.lang.reflect.Field;
/**
* An LHS is a wrapper for an variable, field, or property. It ordinarily holds
* the "left hand side" of an assignment and may be either resolved to a value
* or assigned a value.
* <p>
*
* There is one special case here termed METHOD_EVAL where the LHS is used in an
* intermediate evaluation of a chain of suffixes and wraps a method invocation.
* In this case it may only be resolved to a value and cannot be assigned. (You
* can't assign a value to the result of a method call e.g. "foo() = 5;").
* <p>
*/
class LHS implements ParserConstants, java.io.Serializable {
NameSpace nameSpace;
/**
* The assignment should be to a local variable
*/
boolean localVar;
/**
* Identifiers for the various types of LHS.
*/
static final int VARIABLE = 0,
FIELD = 1,
PROPERTY = 2,
INDEX = 3,
METHOD_EVAL = 4;
int type;
String varName;
String propName;
Field field;
Object object;
int index;
/**
* Variable LHS constructor.
*/
LHS(NameSpace nameSpace, String varName) {
throw new Error("namespace lhs");
/*
type = VARIABLE;
this.varName = varName;
this.nameSpace = nameSpace;
*/
}
/**
* @param localVar if true the variable is set directly in the This
* reference's local scope. If false recursion to look for the variable
* definition in parent's scope is allowed. (e.g. the default case for
* undefined vars going to global).
*/
LHS(NameSpace nameSpace, String varName, boolean localVar) {
type = VARIABLE;
this.localVar = localVar;
this.varName = varName;
this.nameSpace = nameSpace;
}
/**
* Static field LHS Constructor. This simply calls Object field constructor
* with null object.
*/
LHS(Field field) {
type = FIELD;
this.object = null;
this.field = field;
}
/**
* Object field LHS Constructor.
*/
LHS(Object object, Field field) {
if (object == null) {
throw new NullPointerException("constructed empty LHS");
}
type = FIELD;
this.object = object;
this.field = field;
}
/**
* Object property LHS Constructor.
*/
LHS(Object object, String propName) {
if (object == null) {
throw new NullPointerException("constructed empty LHS");
}
type = PROPERTY;
this.object = object;
this.propName = propName;
}
/**
* Array index LHS Constructor.
*/
LHS(Object array, int index) {
if (array == null) {
throw new NullPointerException("constructed empty LHS");
}
type = INDEX;
this.object = array;
this.index = index;
}
public Object getValue() throws UtilEvalError {
if (type == VARIABLE) {
return nameSpace.getVariable(varName);
}
if (type == FIELD) {
try {
Object o = field.get(object);
return Primitive.wrap(o, field.getType());
} catch (IllegalAccessException e2) {
throw new UtilEvalError("Can't read field: " + field);
}
}
if (type == PROPERTY) {
try {
return Reflect.getObjectProperty(object, propName);
} catch (ReflectError e) {
Interpreter.debug(e.getMessage());
throw new UtilEvalError("No such property: " + propName);
}
}
if (type == INDEX) {
try {
return Reflect.getIndex(object, index);
} catch (Exception e) {
throw new UtilEvalError("Array access: " + e);
}
}
throw new InterpreterError("LHS type");
}
/**
* Assign a value to the LHS.
*/
public Object assign(Object val, boolean strictJava)
throws UtilEvalError {
switch (type) {
case VARIABLE:
// Set the variable in namespace according to localVar flag
if (localVar) {
nameSpace.setLocalVariable(varName, val, strictJava);
} else {
nameSpace.setVariable(varName, val, strictJava);
}
break;
case FIELD:
try {
Object fieldVal = val instanceof Primitive
? ((Primitive) val).getValue() : val;
// This should probably be in Reflect.java
Reflect.setAccessible(field);
field.set(object, fieldVal);
return val;
} catch (NullPointerException e) {
throw new UtilEvalError(
"LHS (" + field.getName() + ") not a static field.", e);
} catch (IllegalAccessException e2) {
throw new UtilEvalError(
"LHS (" + field.getName() + ") can't access field: " + e2, e2);
} catch (IllegalArgumentException e3) {
String type = val instanceof Primitive
? ((Primitive) val).getType().getName()
: val.getClass().getName();
throw new UtilEvalError(
"Argument type mismatch. " + (val == null ? "null" : type)
+ " not assignable to field " + field.getName());
}
case PROPERTY:
/*
if ( object instanceof Hashtable )
((Hashtable)object).put(propName, val);
*/
CollectionManager cm = CollectionManager.getCollectionManager();
if (cm.isMap(object)) {
cm.putInMap(object/*map*/, propName, val);
} else {
try {
Reflect.setObjectProperty(object, propName, val);
} catch (ReflectError e) {
Interpreter.debug("Assignment: " + e.getMessage());
throw new UtilEvalError("No such property: " + propName);
}
}
break;
case INDEX:
try {
Reflect.setIndex(object, index, val);
} catch (UtilTargetError e1) { // pass along target error
throw e1;
} catch (Exception e) {
throw new UtilEvalError("Assignment: " + e.getMessage());
}
break;
default:
throw new InterpreterError("unknown lhs");
}
return val;
}
@Override
public String toString() {
return "LHS: "
+ ((field != null) ? "field = " + field.toString() : "")
+ (varName != null ? " varName = " + varName : "")
+ (nameSpace != null ? " nameSpace = " + nameSpace.toString() : "");
}
}
| 9,718 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
ByteVector.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/ByteVector.java | /** *
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (C) 2000 INRIA, France Telecom
* Copyright (C) 2002 France Telecom
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact: [email protected]
*
* Author: Eric Bruneton
*/
package ehacks.bsh;
/**
* A dynamically extensible vector of bytes. This class is roughly equivalent to
* a DataOutputStream on top of a ByteArrayOutputStream, but is more efficient.
*/
class ByteVector {
/**
* The content of this vector.
*/
byte[] data;
/**
* Actual number of bytes in this vector.
*/
int length;
/**
* Constructs a new {@link ByteVector ByteVector} with a default initial
* size.
*/
public ByteVector() {
data = new byte[64];
}
/**
* Constructs a new {@link ByteVector ByteVector} with the given initial
* size.
*
* @param initialSize the initial size of the byte vector to be constructed.
*/
public ByteVector(final int initialSize) {
data = new byte[initialSize];
}
/**
* Puts a byte into this byte vector. The byte vector is automatically
* enlarged if necessary.
*
* @param b a byte.
* @return this byte vector.
*/
public ByteVector put1(final int b) {
int length = this.length;
if (length + 1 > data.length) {
enlarge(1);
}
data[length++] = (byte) b;
this.length = length;
return this;
}
/**
* Puts two bytes into this byte vector. The byte vector is automatically
* enlarged if necessary.
*
* @param b1 a byte.
* @param b2 another byte.
* @return this byte vector.
*/
public ByteVector put11(final int b1, final int b2) {
int length = this.length;
if (length + 2 > data.length) {
enlarge(2);
}
byte[] data = this.data;
data[length++] = (byte) b1;
data[length++] = (byte) b2;
this.length = length;
return this;
}
/**
* Puts a short into this byte vector. The byte vector is automatically
* enlarged if necessary.
*
* @param s a short.
* @return this byte vector.
*/
public ByteVector put2(final int s) {
int length = this.length;
if (length + 2 > data.length) {
enlarge(2);
}
byte[] data = this.data;
data[length++] = (byte) (s >>> 8);
data[length++] = (byte) s;
this.length = length;
return this;
}
/**
* Puts a byte and a short into this byte vector. The byte vector is
* automatically enlarged if necessary.
*
* @param b a byte.
* @param s a short.
* @return this byte vector.
*/
public ByteVector put12(final int b, final int s) {
int length = this.length;
if (length + 3 > data.length) {
enlarge(3);
}
byte[] data = this.data;
data[length++] = (byte) b;
data[length++] = (byte) (s >>> 8);
data[length++] = (byte) s;
this.length = length;
return this;
}
/**
* Puts an int into this byte vector. The byte vector is automatically
* enlarged if necessary.
*
* @param i an int.
* @return this byte vector.
*/
public ByteVector put4(final int i) {
int length = this.length;
if (length + 4 > data.length) {
enlarge(4);
}
byte[] data = this.data;
data[length++] = (byte) (i >>> 24);
data[length++] = (byte) (i >>> 16);
data[length++] = (byte) (i >>> 8);
data[length++] = (byte) i;
this.length = length;
return this;
}
/**
* Puts a long into this byte vector. The byte vector is automatically
* enlarged if necessary.
*
* @param l a long.
* @return this byte vector.
*/
public ByteVector put8(final long l) {
int length = this.length;
if (length + 8 > data.length) {
enlarge(8);
}
byte[] data = this.data;
int i = (int) (l >>> 32);
data[length++] = (byte) (i >>> 24);
data[length++] = (byte) (i >>> 16);
data[length++] = (byte) (i >>> 8);
data[length++] = (byte) i;
i = (int) l;
data[length++] = (byte) (i >>> 24);
data[length++] = (byte) (i >>> 16);
data[length++] = (byte) (i >>> 8);
data[length++] = (byte) i;
this.length = length;
return this;
}
/**
* Puts a String in UTF format into this byte vector. The byte vector is
* automatically enlarged if necessary.
*
* @param s a String.
* @return this byte vector.
*/
public ByteVector putUTF(final String s) {
int charLength = s.length();
int byteLength = 0;
for (int i = 0; i < charLength; ++i) {
char c = s.charAt(i);
if (c >= '\001' && c <= '\177') {
byteLength++;
} else if (c > '\u07FF') {
byteLength += 3;
} else {
byteLength += 2;
}
}
if (byteLength > 65535) {
throw new IllegalArgumentException();
}
int length = this.length;
if (length + 2 + byteLength > data.length) {
enlarge(2 + byteLength);
}
byte[] data = this.data;
data[length++] = (byte) (byteLength >>> 8);
data[length++] = (byte) (byteLength);
for (int i = 0; i < charLength; ++i) {
char c = s.charAt(i);
if (c >= '\001' && c <= '\177') {
data[length++] = (byte) c;
} else if (c > '\u07FF') {
data[length++] = (byte) (0xE0 | c >> 12 & 0xF);
data[length++] = (byte) (0x80 | c >> 6 & 0x3F);
data[length++] = (byte) (0x80 | c & 0x3F);
} else {
data[length++] = (byte) (0xC0 | c >> 6 & 0x1F);
data[length++] = (byte) (0x80 | c & 0x3F);
}
}
this.length = length;
return this;
}
/**
* Puts an array of bytes into this byte vector. The byte vector is
* automatically enlarged if necessary.
*
* @param b an array of bytes. May be <tt>null</tt> to put <tt>len</tt> null
* bytes into this byte vector.
* @param off index of the fist byte of b that must be copied.
* @param len number of bytes of b that must be copied.
* @return this byte vector.
*/
public ByteVector putByteArray(
final byte[] b,
final int off,
final int len) {
if (length + len > data.length) {
enlarge(len);
}
if (b != null) {
System.arraycopy(b, off, data, length, len);
}
length += len;
return this;
}
/**
* Enlarge this byte vector so that it can receive n more bytes.
*
* @param size number of additional bytes that this byte vector should be
* able to receive.
*/
private void enlarge(final int size) {
byte[] newData = new byte[Math.max(2 * data.length, length + size)];
System.arraycopy(data, 0, newData, 0, length);
data = newData;
}
}
| 8,025 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
UtilTargetError.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/UtilTargetError.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
/**
* UtilTargetError is an error corresponding to a TargetError but thrown by a
* utility or other class that does not have the caller context (Node) available
* to it. See UtilEvalError for an explanation of the difference between
* UtilEvalError and EvalError.
* <p>
*
* @see UtilEvalError
*/
public class UtilTargetError extends UtilEvalError {
public Throwable t;
public UtilTargetError(String message, Throwable t) {
super(message);
this.t = t;
}
public UtilTargetError(Throwable t) {
this(null, t);
}
/**
* Override toEvalError to throw TargetError type.
*/
@Override
public EvalError toEvalError(
String msg, SimpleNode node, CallStack callstack) {
if (msg == null) {
msg = getMessage();
} else {
msg = msg + ": " + getMessage();
}
return new TargetError(msg, t, node, callstack, false);
}
}
| 3,503 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHIfStatement.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHIfStatement.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
class BSHIfStatement extends SimpleNode {
BSHIfStatement(int id) {
super(id);
}
@Override
public Object eval(CallStack callstack, Interpreter interpreter)
throws EvalError {
Object ret = null;
if (evaluateCondition(
(SimpleNode) jjtGetChild(0), callstack, interpreter)) {
ret = ((SimpleNode) jjtGetChild(1)).eval(callstack, interpreter);
} else if (jjtGetNumChildren() > 2) {
ret = ((SimpleNode) jjtGetChild(2)).eval(callstack, interpreter);
}
if (ret instanceof ReturnControl) {
return ret;
} else {
return Primitive.VOID;
}
}
public static boolean evaluateCondition(
SimpleNode condExp, CallStack callstack, Interpreter interpreter)
throws EvalError {
Object obj = condExp.eval(callstack, interpreter);
if (obj instanceof Primitive) {
if (obj == Primitive.VOID) {
throw new EvalError("Condition evaluates to void type",
condExp, callstack);
}
obj = ((Primitive) obj).getValue();
}
if (obj instanceof Boolean) {
return ((Boolean) obj);
} else {
throw new EvalError(
"Condition must evaluate to a Boolean or boolean.",
condExp, callstack);
}
}
}
| 3,984 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
ClassWriter.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/ClassWriter.java | /** *
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (C) 2000 INRIA, France Telecom
* Copyright (C) 2002 France Telecom
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact: [email protected]
*
* Author: Eric Bruneton
*/
package ehacks.bsh;
/**
* A {@link ClassVisitor ClassVisitor} that generates Java class files. More
* precisely this visitor generates a byte array conforming to the Java class
* file format. It can be used alone, to generate a Java class "from scratch",
* or with one or more {@link ClassReader ClassReader} and adapter class visitor
* to generate a modified class from one or more existing Java classes.
*/
public class ClassWriter implements ClassVisitor {
/**
* The type of CONSTANT_Class constant pool items.
*/
final static int CLASS = 7;
/**
* The type of CONSTANT_Fieldref constant pool items.
*/
final static int FIELD = 9;
/**
* The type of CONSTANT_Methodref constant pool items.
*/
final static int METH = 10;
/**
* The type of CONSTANT_InterfaceMethodref constant pool items.
*/
final static int IMETH = 11;
/**
* The type of CONSTANT_String constant pool items.
*/
final static int STR = 8;
/**
* The type of CONSTANT_Integer constant pool items.
*/
final static int INT = 3;
/**
* The type of CONSTANT_Float constant pool items.
*/
final static int FLOAT = 4;
/**
* The type of CONSTANT_Long constant pool items.
*/
final static int LONG = 5;
/**
* The type of CONSTANT_Double constant pool items.
*/
final static int DOUBLE = 6;
/**
* The type of CONSTANT_NameAndType constant pool items.
*/
final static int NAME_TYPE = 12;
/**
* The type of CONSTANT_Utf8 constant pool items.
*/
final static int UTF8 = 1;
/**
* Index of the next item to be added in the constant pool.
*/
private short index;
/**
* The constant pool of this class.
*/
private final ByteVector pool;
/**
* The constant pool's hash table data.
*/
private Item[] table;
/**
* The threshold of the constant pool's hash table.
*/
private int threshold;
/**
* The access flags of this class.
*/
private int access;
/**
* The constant pool item that contains the internal name of this class.
*/
private int name;
/**
* The constant pool item that contains the internal name of the super class
* of this class.
*/
private int superName;
/**
* Number of interfaces implemented or extended by this class or interface.
*/
private int interfaceCount;
/**
* The interfaces implemented or extended by this class or interface. More
* precisely, this array contains the indexes of the constant pool items
* that contain the internal names of these interfaces.
*/
private int[] interfaces;
/**
* The constant pool item that contains the name of the source file from
* which this class was compiled.
*/
private Item sourceFile;
/**
* Number of fields of this class.
*/
private int fieldCount;
/**
* The fields of this class.
*/
private ByteVector fields;
/**
* <tt>true</tt> if the maximum stack size and number of local variables
* must be automatically computed.
*/
private final boolean computeMaxs;
/**
* The methods of this class. These methods are stored in a linked list of
* {@link CodeWriter CodeWriter} objects, linked to each other by their {@link
* CodeWriter#next} field. This field stores the first element of this list.
*/
CodeWriter firstMethod;
/**
* The methods of this class. These methods are stored in a linked list of
* {@link CodeWriter CodeWriter} objects, linked to each other by their {@link
* CodeWriter#next} field. This field stores the last element of this list.
*/
CodeWriter lastMethod;
/**
* The number of entries in the InnerClasses attribute.
*/
private int innerClassesCount;
/**
* The InnerClasses attribute.
*/
private ByteVector innerClasses;
/**
* A reusable key used to look for items in the hash {@link #table table}.
*/
Item key;
/**
* A reusable key used to look for items in the hash {@link #table table}.
*/
Item key2;
/**
* A reusable key used to look for items in the hash {@link #table table}.
*/
Item key3;
/**
* The type of instructions without any label.
*/
final static int NOARG_INSN = 0;
/**
* The type of instructions with an signed byte label.
*/
final static int SBYTE_INSN = 1;
/**
* The type of instructions with an signed short label.
*/
final static int SHORT_INSN = 2;
/**
* The type of instructions with a local variable index label.
*/
final static int VAR_INSN = 3;
/**
* The type of instructions with an implicit local variable index label.
*/
final static int IMPLVAR_INSN = 4;
/**
* The type of instructions with a type descriptor argument.
*/
final static int TYPE_INSN = 5;
/**
* The type of field and method invocations instructions.
*/
final static int FIELDORMETH_INSN = 6;
/**
* The type of the INVOKEINTERFACE instruction.
*/
final static int ITFMETH_INSN = 7;
/**
* The type of instructions with a 2 bytes bytecode offset label.
*/
final static int LABEL_INSN = 8;
/**
* The type of instructions with a 4 bytes bytecode offset label.
*/
final static int LABELW_INSN = 9;
/**
* The type of the LDC instruction.
*/
final static int LDC_INSN = 10;
/**
* The type of the LDC_W and LDC2_W instructions.
*/
final static int LDCW_INSN = 11;
/**
* The type of the IINC instruction.
*/
final static int IINC_INSN = 12;
/**
* The type of the TABLESWITCH instruction.
*/
final static int TABL_INSN = 13;
/**
* The type of the LOOKUPSWITCH instruction.
*/
final static int LOOK_INSN = 14;
/**
* The type of the MULTIANEWARRAY instruction.
*/
final static int MANA_INSN = 15;
/**
* The type of the WIDE instruction.
*/
final static int WIDE_INSN = 16;
/**
* The instruction types of all JVM opcodes.
*/
static byte[] TYPE;
// --------------------------------------------------------------------------
// Static initializer
// --------------------------------------------------------------------------
/**
* Computes the instruction types of JVM opcodes.
*/
static {
int i;
byte[] b = new byte[220];
String s
= "AAAAAAAAAAAAAAAABCKLLDDDDDEEEEEEEEEEEEEEEEEEEEAAAAAAAADDDDDEEEEEEEEE"
+ "EEEEEEEEEEEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA"
+ "AAAAAAAAAAAAAAAAAIIIIIIIIIIIIIIIIDNOAAAAAAGGGGGGGHAFBFAAFFAAQPIIJJII"
+ "IIIIIIIIIIIIIIII";
for (i = 0; i < b.length; ++i) {
b[i] = (byte) (s.charAt(i) - 'A');
}
TYPE = b;
/* code to generate the above string
// SBYTE_INSN instructions
b[Constants.NEWARRAY] = SBYTE_INSN;
b[Constants.BIPUSH] = SBYTE_INSN;
// SHORT_INSN instructions
b[Constants.SIPUSH] = SHORT_INSN;
// (IMPL)VAR_INSN instructions
b[Constants.RET] = VAR_INSN;
for (i = Constants.ILOAD; i <= Constants.ALOAD; ++i) {
b[i] = VAR_INSN;
}
for (i = Constants.ISTORE; i <= Constants.ASTORE; ++i) {
b[i] = VAR_INSN;
}
for (i = 26; i <= 45; ++i) { // ILOAD_0 to ALOAD_3
b[i] = IMPLVAR_INSN;
}
for (i = 59; i <= 78; ++i) { // ISTORE_0 to ASTORE_3
b[i] = IMPLVAR_INSN;
}
// TYPE_INSN instructions
b[Constants.NEW] = TYPE_INSN;
b[Constants.ANEWARRAY] = TYPE_INSN;
b[Constants.CHECKCAST] = TYPE_INSN;
b[Constants.INSTANCEOF] = TYPE_INSN;
// (Set)FIELDORMETH_INSN instructions
for (i = Constants.GETSTATIC; i <= Constants.INVOKESTATIC; ++i) {
b[i] = FIELDORMETH_INSN;
}
b[Constants.INVOKEINTERFACE] = ITFMETH_INSN;
// LABEL(W)_INSN instructions
for (i = Constants.IFEQ; i <= Constants.JSR; ++i) {
b[i] = LABEL_INSN;
}
b[Constants.IFNULL] = LABEL_INSN;
b[Constants.IFNONNULL] = LABEL_INSN;
b[200] = LABELW_INSN; // GOTO_W
b[201] = LABELW_INSN; // JSR_W
// temporary opcodes used internally by ASM - see Label and CodeWriter
for (i = 202; i < 220; ++i) {
b[i] = LABEL_INSN;
}
// LDC(_W) instructions
b[Constants.LDC] = LDC_INSN;
b[19] = LDCW_INSN; // LDC_W
b[20] = LDCW_INSN; // LDC2_W
// special instructions
b[Constants.IINC] = IINC_INSN;
b[Constants.TABLESWITCH] = TABL_INSN;
b[Constants.LOOKUPSWITCH] = LOOK_INSN;
b[Constants.MULTIANEWARRAY] = MANA_INSN;
b[196] = WIDE_INSN; // WIDE
for (i = 0; i < b.length; ++i) {
System.err.print((char)('A' + b[i]));
}
System.err.println();
*/
}
// --------------------------------------------------------------------------
// Constructor
// --------------------------------------------------------------------------
/**
* Constructs a new {@link ClassWriter ClassWriter} object.
*
* @param computeMaxs <tt>true</tt> if the maximum stack size and the
* maximum number of local variables must be automatically computed. If this
* flag is <tt>true</tt>, then the arguments of the {@link
* CodeVisitor#visitMaxs visitMaxs} method of the {@link CodeVisitor
* CodeVisitor} returned by the {@link #visitMethod visitMethod} method will
* be ignored, and computed automatically from the signature and the
* bytecode of each method.
*/
public ClassWriter(final boolean computeMaxs) {
index = 1;
pool = new ByteVector();
table = new Item[64];
threshold = (int) (0.75d * table.length);
key = new Item();
key2 = new Item();
key3 = new Item();
this.computeMaxs = computeMaxs;
}
// --------------------------------------------------------------------------
// Implementation of the ClassVisitor interface
// --------------------------------------------------------------------------
@Override
public void visit(
final int access,
final String name,
final String superName,
final String[] interfaces,
final String sourceFile) {
this.access = access;
this.name = newClass(name).index;
this.superName = superName == null ? 0 : newClass(superName).index;
if (interfaces != null && interfaces.length > 0) {
interfaceCount = interfaces.length;
this.interfaces = new int[interfaceCount];
for (int i = 0; i < interfaceCount; ++i) {
this.interfaces[i] = newClass(interfaces[i]).index;
}
}
if (sourceFile != null) {
newUTF8("SourceFile");
this.sourceFile = newUTF8(sourceFile);
}
if ((access & Constants.ACC_DEPRECATED) != 0) {
newUTF8("Deprecated");
}
}
@Override
public void visitInnerClass(
final String name,
final String outerName,
final String innerName,
final int access) {
if (innerClasses == null) {
newUTF8("InnerClasses");
innerClasses = new ByteVector();
}
++innerClassesCount;
innerClasses.put2(name == null ? 0 : newClass(name).index);
innerClasses.put2(outerName == null ? 0 : newClass(outerName).index);
innerClasses.put2(innerName == null ? 0 : newUTF8(innerName).index);
innerClasses.put2(access);
}
@Override
public void visitField(
final int access,
final String name,
final String desc,
final Object value) {
++fieldCount;
if (fields == null) {
fields = new ByteVector();
}
fields.put2(access).put2(newUTF8(name).index).put2(newUTF8(desc).index);
int attributeCount = 0;
if (value != null) {
++attributeCount;
}
if ((access & Constants.ACC_SYNTHETIC) != 0) {
++attributeCount;
}
if ((access & Constants.ACC_DEPRECATED) != 0) {
++attributeCount;
}
fields.put2(attributeCount);
if (value != null) {
fields.put2(newUTF8("ConstantValue").index);
fields.put4(2).put2(newCst(value).index);
}
if ((access & Constants.ACC_SYNTHETIC) != 0) {
fields.put2(newUTF8("Synthetic").index).put4(0);
}
if ((access & Constants.ACC_DEPRECATED) != 0) {
fields.put2(newUTF8("Deprecated").index).put4(0);
}
}
@Override
public CodeVisitor visitMethod(
final int access,
final String name,
final String desc,
final String[] exceptions) {
CodeWriter cw = new CodeWriter(this, computeMaxs);
cw.init(access, name, desc, exceptions);
return cw;
}
@Override
public void visitEnd() {
}
// --------------------------------------------------------------------------
// Other public methods
// --------------------------------------------------------------------------
/**
* Returns the bytecode of the class that was build with this class writer.
*
* @return the bytecode of the class that was build with this class writer.
*/
public byte[] toByteArray() {
// computes the real size of the bytecode of this class
int size = 24 + 2 * interfaceCount;
if (fields != null) {
size += fields.length;
}
int nbMethods = 0;
CodeWriter cb = firstMethod;
while (cb != null) {
++nbMethods;
size += cb.getSize();
cb = cb.next;
}
size += pool.length;
int attributeCount = 0;
if (sourceFile != null) {
++attributeCount;
size += 8;
}
if ((access & Constants.ACC_DEPRECATED) != 0) {
++attributeCount;
size += 6;
}
if (innerClasses != null) {
++attributeCount;
size += 8 + innerClasses.length;
}
// allocates a byte vector of this size, in order to avoid unnecessary
// arraycopy operations in the ByteVector.enlarge() method
ByteVector out = new ByteVector(size);
out.put4(0xCAFEBABE).put2(3).put2(45);
out.put2(index).putByteArray(pool.data, 0, pool.length);
out.put2(access).put2(name).put2(superName);
out.put2(interfaceCount);
for (int i = 0; i < interfaceCount; ++i) {
out.put2(interfaces[i]);
}
out.put2(fieldCount);
if (fields != null) {
out.putByteArray(fields.data, 0, fields.length);
}
out.put2(nbMethods);
cb = firstMethod;
while (cb != null) {
cb.put(out);
cb = cb.next;
}
out.put2(attributeCount);
if (sourceFile != null) {
out.put2(newUTF8("SourceFile").index).put4(2).put2(sourceFile.index);
}
if ((access & Constants.ACC_DEPRECATED) != 0) {
out.put2(newUTF8("Deprecated").index).put4(0);
}
if (innerClasses != null) {
out.put2(newUTF8("InnerClasses").index);
out.put4(innerClasses.length + 2).put2(innerClassesCount);
out.putByteArray(innerClasses.data, 0, innerClasses.length);
}
return out.data;
}
// --------------------------------------------------------------------------
// Utility methods: constant pool management
// --------------------------------------------------------------------------
/**
* Adds a number or string constant to the constant pool of the class being
* build. Does nothing if the constant pool already contains a similar item.
*
* @param cst the value of the constant to be added to the constant pool.
* This parameter must be an {@link java.lang.Integer Integer}, a {@link
* java.lang.Float Float}, a {@link java.lang.Long Long}, a {@link
* java.lang.Double Double} or a {@link String String}.
* @return a new or already existing constant item with the given value.
*/
Item newCst(final Object cst) {
if (cst instanceof Integer) {
int val = ((int) cst);
return newInteger(val);
} else if (cst instanceof Float) {
float val = ((float) cst);
return newFloat(val);
} else if (cst instanceof Long) {
long val = ((long) cst);
return newLong(val);
} else if (cst instanceof Double) {
double val = ((double) cst);
return newDouble(val);
} else if (cst instanceof String) {
return newString((String) cst);
} else {
throw new IllegalArgumentException("value " + cst);
}
}
/**
* Adds an UTF string to the constant pool of the class being build. Does
* nothing if the constant pool already contains a similar item.
*
* @param value the String value.
* @return a new or already existing UTF8 item.
*/
Item newUTF8(final String value) {
key.set(UTF8, value, null, null);
Item result = get(key);
if (result == null) {
pool.put1(UTF8).putUTF(value);
result = new Item(index++, key);
put(result);
}
return result;
}
/**
* Adds a class reference to the constant pool of the class being build.
* Does nothing if the constant pool already contains a similar item.
*
* @param value the internal name of the class.
* @return a new or already existing class reference item.
*/
Item newClass(final String value) {
key2.set(CLASS, value, null, null);
Item result = get(key2);
if (result == null) {
pool.put12(CLASS, newUTF8(value).index);
result = new Item(index++, key2);
put(result);
}
return result;
}
/**
* Adds a field reference to the constant pool of the class being build.
* Does nothing if the constant pool already contains a similar item.
*
* @param owner the internal name of the field's owner class.
* @param name the field's name.
* @param desc the field's descriptor.
* @return a new or already existing field reference item.
*/
Item newField(
final String owner,
final String name,
final String desc) {
key3.set(FIELD, owner, name, desc);
Item result = get(key3);
if (result == null) {
put122(FIELD, newClass(owner).index, newNameType(name, desc).index);
result = new Item(index++, key3);
put(result);
}
return result;
}
/**
* Adds a method reference to the constant pool of the class being build.
* Does nothing if the constant pool already contains a similar item.
*
* @param owner the internal name of the method's owner class.
* @param name the method's name.
* @param desc the method's descriptor.
* @return a new or already existing method reference item.
*/
Item newMethod(
final String owner,
final String name,
final String desc) {
key3.set(METH, owner, name, desc);
Item result = get(key3);
if (result == null) {
put122(METH, newClass(owner).index, newNameType(name, desc).index);
result = new Item(index++, key3);
put(result);
}
return result;
}
/**
* Adds an interface method reference to the constant pool of the class
* being build. Does nothing if the constant pool already contains a similar
* item.
*
* @param ownerItf the internal name of the method's owner interface.
* @param name the method's name.
* @param desc the method's descriptor.
* @return a new or already existing interface method reference item.
*/
Item newItfMethod(
final String ownerItf,
final String name,
final String desc) {
key3.set(IMETH, ownerItf, name, desc);
Item result = get(key3);
if (result == null) {
put122(IMETH, newClass(ownerItf).index, newNameType(name, desc).index);
result = new Item(index++, key3);
put(result);
}
return result;
}
/**
* Adds an integer to the constant pool of the class being build. Does
* nothing if the constant pool already contains a similar item.
*
* @param value the int value.
* @return a new or already existing int item.
*/
private Item newInteger(final int value) {
key.set(value);
Item result = get(key);
if (result == null) {
pool.put1(INT).put4(value);
result = new Item(index++, key);
put(result);
}
return result;
}
/**
* Adds a float to the constant pool of the class being build. Does nothing
* if the constant pool already contains a similar item.
*
* @param value the float value.
* @return a new or already existing float item.
*/
private Item newFloat(final float value) {
key.set(value);
Item result = get(key);
if (result == null) {
pool.put1(FLOAT).put4(Float.floatToIntBits(value));
result = new Item(index++, key);
put(result);
}
return result;
}
/**
* Adds a long to the constant pool of the class being build. Does nothing
* if the constant pool already contains a similar item.
*
* @param value the long value.
* @return a new or already existing long item.
*/
private Item newLong(final long value) {
key.set(value);
Item result = get(key);
if (result == null) {
pool.put1(LONG).put8(value);
result = new Item(index, key);
put(result);
index += 2;
}
return result;
}
/**
* Adds a double to the constant pool of the class being build. Does nothing
* if the constant pool already contains a similar item.
*
* @param value the double value.
* @return a new or already existing double item.
*/
private Item newDouble(final double value) {
key.set(value);
Item result = get(key);
if (result == null) {
pool.put1(DOUBLE).put8(Double.doubleToLongBits(value));
result = new Item(index, key);
put(result);
index += 2;
}
return result;
}
/**
* Adds a string to the constant pool of the class being build. Does nothing
* if the constant pool already contains a similar item.
*
* @param value the String value.
* @return a new or already existing string item.
*/
private Item newString(final String value) {
key2.set(STR, value, null, null);
Item result = get(key2);
if (result == null) {
pool.put12(STR, newUTF8(value).index);
result = new Item(index++, key2);
put(result);
}
return result;
}
/**
* Adds a name and type to the constant pool of the class being build. Does
* nothing if the constant pool already contains a similar item.
*
* @param name a name.
* @param desc a type descriptor.
* @return a new or already existing name and type item.
*/
private Item newNameType(final String name, final String desc) {
key2.set(NAME_TYPE, name, desc, null);
Item result = get(key2);
if (result == null) {
put122(NAME_TYPE, newUTF8(name).index, newUTF8(desc).index);
result = new Item(index++, key2);
put(result);
}
return result;
}
/**
* Returns the constant pool's hash table item which is equal to the given
* item.
*
* @param key a constant pool item.
* @return the constant pool's hash table item which is equal to the given
* item, or <tt>null</tt> if there is no such item.
*/
private Item get(final Item key) {
Item tab[] = table;
int hashCode = key.hashCode;
int index = (hashCode & 0x7FFFFFFF) % tab.length;
for (Item i = tab[index]; i != null; i = i.next) {
if (i.hashCode == hashCode && key.isEqualTo(i)) {
return i;
}
}
return null;
}
/**
* Puts the given item in the constant pool's hash table. The hash table
* <i>must</i> not already contains this item.
*
* @param i the item to be added to the constant pool's hash table.
*/
private void put(final Item i) {
if (index > threshold) {
int oldCapacity = table.length;
Item oldMap[] = table;
int newCapacity = oldCapacity * 2 + 1;
Item newMap[] = new Item[newCapacity];
threshold = (int) (newCapacity * 0.75);
table = newMap;
for (int j = oldCapacity; j-- > 0;) {
for (Item old = oldMap[j]; old != null;) {
Item e = old;
old = old.next;
int index = (e.hashCode & 0x7FFFFFFF) % newCapacity;
e.next = newMap[index];
newMap[index] = e;
}
}
}
int index = (i.hashCode & 0x7FFFFFFF) % table.length;
i.next = table[index];
table[index] = i;
}
/**
* Puts one byte and two shorts into the constant pool.
*
* @param b a byte.
* @param s1 a short.
* @param s2 another short.
*/
private void put122(final int b, final int s1, final int s2) {
pool.put12(b, s1).put2(s2);
}
}
| 27,271 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
Capabilities.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/Capabilities.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
import java.lang.reflect.Field;
import java.util.Hashtable;
/**
* The map of extended features supported by the runtime in which we live.
* <p>
*
* This class should be independent of all other bsh classes!
* <p>
*
* Note that tests for class existence here do *not* use the BshClassManager, as
* it may require other optional class files to be loaded.
*/
public class Capabilities {
private static volatile boolean accessibility = true;
public static boolean haveSwing() {
// classExists caches info for us
return classExists("javax.swing.JButton");
}
/**
* If accessibility is enabled determine if the accessibility mechanism
* exists and if we have the optional bsh package to use it. Note that even
* if both are true it does not necessarily mean that we have runtime
* permission to access the fields... Java security has a say in it.
*
* @see bsh.ReflectManager
*/
public static boolean haveAccessibility() {
return accessibility;
}
public static void setAccessibility(boolean b)
throws Unavailable {
if (b == false) {
accessibility = false;
} else {
// test basic access
try {
String.class.getDeclaredMethods();
try {
final Field field = Capabilities.class.getField("classes");
field.setAccessible(true);
field.setAccessible(false);
} catch (NoSuchFieldException e) {
// ignore
}
} catch (SecurityException e) {
throw new Unavailable("Accessibility unavailable: " + e);
}
accessibility = true;
}
BSHClassManager.clearResolveCache();
}
private static final Hashtable classes = new Hashtable();
/**
* Use direct Class.forName() to test for the existence of a class. We
* should not use BshClassManager here because: a) the systems using these
* tests would probably not load the classes through it anyway. b)
* bshclassmanager is heavy and touches other class files. this capabilities
* code must be light enough to be used by any system **including the remote
* applet**.
*/
public static boolean classExists(String name) {
Object c = classes.get(name);
if (c == null) {
try {
/*
Note: do *not* change this to
BshClassManager plainClassForName() or equivalent.
This class must not touch any other bsh classes.
*/
c = Class.forName(name);
} catch (ClassNotFoundException e) {
}
if (c != null) {
classes.put(c, "unused");
}
}
return c != null;
}
/**
* An attempt was made to use an unavailable capability supported by an
* optional package. The normal operation is to test before attempting to
* use these packages... so this is runtime exception.
*/
public static class Unavailable extends UtilEvalError {
public Unavailable(String s) {
super(s);
}
}
}
| 5,784 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
ClassVisitor.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/ClassVisitor.java | /** *
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (C) 2000 INRIA, France Telecom
* Copyright (C) 2002 France Telecom
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact: [email protected]
*
* Author: Eric Bruneton
*/
package ehacks.bsh;
/**
* A visitor to visit a Java class. The methods of this interface must be called
* in the following order: <tt>visit</tt> (<tt>visitField</tt> |
* <tt>visitMethod</tt> | <tt>visitInnerClass</tt>)* <tt>visitEnd</tt>.
*/
public interface ClassVisitor {
/**
* Visits the header of the class.
*
* @param access the class's access flags (see {@link Constants}). This
* parameter also indicates if the class is deprecated.
* @param name the internal name of the class (see {@link Type#getInternalName
* getInternalName}).
* @param superName the internal of name of the super class (see {@link
* Type#getInternalName getInternalName}). For interfaces, the super class
* is {@link Object}. May be <tt>null</tt>, but only for the {@link
* Object java.lang.Object} class.
* @param interfaces the internal names of the class's interfaces (see {@link
* Type#getInternalName getInternalName}). May be <tt>null</tt>.
* @param sourceFile the name of the source file from which this class was
* compiled. May be <tt>null</tt>.
*/
void visit(
int access,
String name,
String superName,
String[] interfaces,
String sourceFile);
/**
* Visits information about an inner class. This inner class is not
* necessarily a member of the class being visited.
*
* @param name the internal name of an inner class (see {@link
* Type#getInternalName getInternalName}).
* @param outerName the internal name of the class to which the inner class
* belongs (see {@link Type#getInternalName getInternalName}). May be
* <tt>null</tt>.
* @param innerName the (simple) name of the inner class inside its
* enclosing class. May be <tt>null</tt> for anonymous inner classes.
* @param access the access flags of the inner class as originally declared
* in the enclosing class.
*/
void visitInnerClass(
String name,
String outerName,
String innerName,
int access);
/**
* Visits a field of the class.
*
* @param access the field's access flags (see {@link Constants}). This
* parameter also indicates if the field is synthetic and/or deprecated.
* @param name the field's name.
* @param desc the field's descriptor (see {@link Type Type}).
* @param value the field's initial value. This parameter, which may be
* <tt>null</tt> if the field does not have an initial value, must be an
* {@link java.lang.Integer Integer}, a {@link java.lang.Float Float}, a
* {@link java.lang.Long Long}, a {@link java.lang.Double Double} or a
* {@link String String}.
*/
void visitField(int access, String name, String desc, Object value);
/**
* Visits a method of the class. This method <i>must</i> return a new
* {@link CodeVisitor CodeVisitor} instance (or <tt>null</tt>) each time it
* is called, i.e., it should not return a previously returned visitor.
*
* @param access the method's access flags (see {@link Constants}). This
* parameter also indicates if the method is synthetic and/or deprecated.
* @param name the method's name.
* @param desc the method's descriptor (see {@link Type Type}).
* @param exceptions the internal names of the method's exception classes
* (see {@link Type#getInternalName getInternalName}). May be
* <tt>null</tt>.
* @return an object to visit the byte code of the method, or <tt>null</tt>
* if this class visitor is not interested in visiting the code of this
* method.
*/
CodeVisitor visitMethod(
int access,
String name,
String desc,
String[] exceptions);
/**
* Visits the end of the class. This method, which is the last one to be
* called, is used to inform the visitor that all the fields and methods of
* the class have been visited.
*/
void visitEnd();
}
| 5,062 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
ReturnControl.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/ReturnControl.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
/**
* Represents a Return, Break, or Continue statement
*/
class ReturnControl implements ParserConstants {
public int kind;
public Object value;
/**
* The node where we returned... for printing error messages correctly
*/
public SimpleNode returnPoint;
public ReturnControl(int kind, Object value, SimpleNode returnPoint) {
this.kind = kind;
this.value = value;
this.returnPoint = returnPoint;
}
}
| 3,013 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
ReflectError.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/ReflectError.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
class ReflectError extends Exception {
public ReflectError() {
super();
}
public ReflectError(String s) {
super(s);
}
public ReflectError(String s, Throwable t) {
super(s, t);
}
}
| 2,783 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHArrayInitializer.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHArrayInitializer.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
import java.lang.reflect.Array;
class BSHArrayInitializer extends SimpleNode {
BSHArrayInitializer(int id) {
super(id);
}
@Override
public Object eval(CallStack callstack, Interpreter interpreter)
throws EvalError {
throw new EvalError("Array initializer has no base type.",
this, callstack);
}
/**
* Construct the array from the initializer syntax.
*
* @param baseType the base class type of the array (no dimensionality)
* @param dimensions the top number of dimensions of the array e.g. 2 for a
* String [][];
*/
public Object eval(Class baseType, int dimensions,
CallStack callstack, Interpreter interpreter)
throws EvalError {
int numInitializers = jjtGetNumChildren();
// allocate the array to store the initializers
int[] dima = new int[dimensions]; // description of the array
// The other dimensions default to zero and are assigned when
// the values are set.
dima[0] = numInitializers;
Object initializers = Array.newInstance(baseType, dima);
// Evaluate the initializers
for (int i = 0; i < numInitializers; i++) {
SimpleNode node = (SimpleNode) jjtGetChild(i);
Object currentInitializer;
if (node instanceof BSHArrayInitializer) {
if (dimensions < 2) {
throw new EvalError(
"Invalid Location for Intializer, position: " + i,
this, callstack);
}
currentInitializer
= ((BSHArrayInitializer) node).eval(
baseType, dimensions - 1, callstack, interpreter);
} else {
currentInitializer = node.eval(callstack, interpreter);
}
if (currentInitializer == Primitive.VOID) {
throw new EvalError(
"Void in array initializer, position" + i, this, callstack);
}
// Determine if any conversion is necessary on the initializers.
//
// Quick test to see if conversions apply:
// If the dimensionality of the array is 1 then the elements of
// the initializer can be primitives or boxable types. If it is
// greater then the values must be array (object) types and there
// are currently no conversions that we do on those.
// If we have conversions on those in the future then we need to
// get the real base type here instead of the dimensionless one.
Object value = currentInitializer;
if (dimensions == 1) {
// We do a bsh cast here. strictJava should be able to affect
// the cast there when we tighten control
try {
value = Types.castObject(
currentInitializer, baseType, Types.CAST);
} catch (UtilEvalError e) {
throw e.toEvalError(
"Error in array initializer", this, callstack);
}
// unwrap any primitive, map voids to null, etc.
value = Primitive.unwrap(value);
}
// store the value in the array
try {
Array.set(initializers, i, value);
} catch (IllegalArgumentException e) {
Interpreter.debug("illegal arg" + e);
throwTypeError(baseType, currentInitializer, i, callstack);
} catch (ArrayStoreException e) { // I think this can happen
Interpreter.debug("arraystore" + e);
throwTypeError(baseType, currentInitializer, i, callstack);
}
}
return initializers;
}
private void throwTypeError(
Class baseType, Object initializer, int argNum, CallStack callstack)
throws EvalError {
String rhsType;
if (initializer instanceof Primitive) {
rhsType
= ((Primitive) initializer).getType().getName();
} else {
rhsType = Reflect.normalizeClassName(
initializer.getClass());
}
throw new EvalError("Incompatible type: " + rhsType
+ " in initializer of array type: " + baseType
+ " at position: " + argNum, this, callstack);
}
}
| 7,083 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHLiteral.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHLiteral.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
public class BSHLiteral extends SimpleNode {
public static volatile boolean internStrings = true;
public Object value;
BSHLiteral(int id) {
super(id);
}
@Override
public Object eval(CallStack callstack, Interpreter interpreter)
throws EvalError {
if (value == null) {
throw new InterpreterError("Null in bsh literal: " + value);
}
return value;
}
private char getEscapeChar(char ch) {
switch (ch) {
case 'b':
ch = '\b';
break;
case 't':
ch = '\t';
break;
case 'n':
ch = '\n';
break;
case 'f':
ch = '\f';
break;
case 'r':
ch = '\r';
break;
// do nothing - ch already contains correct character
case '"':
case '\'':
case '\\':
break;
}
return ch;
}
public void charSetup(String str) {
char ch = str.charAt(0);
if (ch == '\\') {
// get next character
ch = str.charAt(1);
if (Character.isDigit(ch)) {
ch = (char) Integer.parseInt(str.substring(1), 8);
} else {
ch = getEscapeChar(ch);
}
}
value = new Primitive(new Character(ch));
}
void stringSetup(String str) {
StringBuilder buffer = new StringBuilder();
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if (ch == '\\') {
// get next character
ch = str.charAt(++i);
if (Character.isDigit(ch)) {
int endPos = i;
// check the next two characters
int max = Math.min(i + 2, len - 1);
while (endPos < max) {
if (Character.isDigit(str.charAt(endPos + 1))) {
endPos++;
} else {
break;
}
}
ch = (char) Integer.parseInt(str.substring(i, endPos + 1), 8);
i = endPos;
} else {
ch = getEscapeChar(ch);
}
}
buffer.append(ch);
}
String s = buffer.toString();
if (internStrings) {
s = s.intern();
}
value = s;
}
}
| 5,185 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHArguments.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHArguments.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
class BSHArguments extends SimpleNode {
BSHArguments(int id) {
super(id);
}
/**
* This node holds a set of arguments for a method invocation or constructor
* call.
*
* Note: arguments are not currently allowed to be VOID.
*/
/*
Disallowing VOIDs here was an easy way to support the throwing of a
more descriptive error message on use of an undefined argument to a
method call (very common). If it ever turns out that we need to
support that for some reason we'll have to re-evaluate how we get
"meta-information" about the arguments in the various invoke() methods
that take Object []. We could either pass BSHArguments down to
overloaded forms of the methods or throw an exception subtype
including the argument position back up, where the error message would
be compounded.
*/
public Object[] getArguments(CallStack callstack, Interpreter interpreter)
throws EvalError {
// evaluate each child
Object[] args = new Object[jjtGetNumChildren()];
for (int i = 0; i < args.length; i++) {
args[i] = ((SimpleNode) jjtGetChild(i)).eval(callstack, interpreter);
if (args[i] == Primitive.VOID) {
throw new EvalError("Undefined argument: "
+ ((SimpleNode) jjtGetChild(i)).getText(), this, callstack);
}
}
return args;
}
public Object[] getArgumentsNames(CallStack callstack, Interpreter interpreter)
throws EvalError {
// evaluate each child
Object[] args = new Object[jjtGetNumChildren()];
for (int i = 0; i < args.length; i++) {
try {
BSHPrimaryExpression lhsNode = (BSHPrimaryExpression) jjtGetChild(i).jjtGetChild(0);
args[i] = lhsNode.firstToken.toString();
if (args[i] == Primitive.VOID) {
throw new EvalError("Undefined argument: "
+ ((SimpleNode) jjtGetChild(i)).getText(), this, callstack);
}
} catch (ClassCastException e) {
args[i] = null;
}
}
return args;
}
}
| 4,761 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHBlock.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHBlock.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
class BSHBlock extends SimpleNode {
public boolean isSynchronized = false;
BSHBlock(int id) {
super(id);
}
@Override
public Object eval(CallStack callstack, Interpreter interpreter)
throws EvalError {
return eval(callstack, interpreter, false);
}
/**
* @param overrideNamespace if set to true the block will be executed in the
* current namespace (not a subordinate one).
* <p>
* If true *no* new BlockNamespace will be swapped onto the stack and the
* eval will happen in the current top namespace. This is used by BshMethod,
* TryStatement, etc. which must intialize the block first and also for
* those that perform multiple passes in the same block.
*/
public Object eval(
CallStack callstack, Interpreter interpreter,
boolean overrideNamespace)
throws EvalError {
Object syncValue = null;
if (isSynchronized) {
// First node is the expression on which to sync
SimpleNode exp = ((SimpleNode) jjtGetChild(0));
syncValue = exp.eval(callstack, interpreter);
}
Object ret;
if (isSynchronized) // Do the actual synchronization
{
synchronized (syncValue) {
ret = evalBlock(
callstack, interpreter, overrideNamespace, null/*filter*/);
}
} else {
ret = evalBlock(
callstack, interpreter, overrideNamespace, null/*filter*/);
}
return ret;
}
Object evalBlock(
CallStack callstack, Interpreter interpreter,
boolean overrideNamespace, NodeFilter nodeFilter)
throws EvalError {
Object ret = Primitive.VOID;
NameSpace enclosingNameSpace = null;
if (!overrideNamespace) {
enclosingNameSpace = callstack.top();
BlockNameSpace bodyNameSpace
= new BlockNameSpace(enclosingNameSpace);
callstack.swap(bodyNameSpace);
}
int startChild = isSynchronized ? 1 : 0;
int numChildren = jjtGetNumChildren();
try {
/*
Evaluate block in two passes:
First do class declarations then do everything else.
*/
for (int i = startChild; i < numChildren; i++) {
SimpleNode node = ((SimpleNode) jjtGetChild(i));
if (nodeFilter != null && !nodeFilter.isVisible(node)) {
continue;
}
if (node instanceof BSHClassDeclaration) {
node.eval(callstack, interpreter);
}
}
for (int i = startChild; i < numChildren; i++) {
SimpleNode node = ((SimpleNode) jjtGetChild(i));
if (node instanceof BSHClassDeclaration) {
continue;
}
// filter nodes
if (nodeFilter != null && !nodeFilter.isVisible(node)) {
continue;
}
ret = node.eval(callstack, interpreter);
// statement or embedded block evaluated a return statement
if (ret instanceof ReturnControl) {
break;
}
}
} finally {
// make sure we put the namespace back when we leave.
if (!overrideNamespace) {
callstack.swap(enclosingNameSpace);
}
}
return ret;
}
public interface NodeFilter {
public boolean isVisible(SimpleNode node);
}
}
| 6,220 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
Variable.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/Variable.java | package ehacks.bsh;
public class Variable implements java.io.Serializable {
static final int DECLARATION = 0, ASSIGNMENT = 1;
/**
* A null type means an untyped variable
*/
String name;
Class type = null;
String typeDescriptor;
Object value;
Modifiers modifiers;
LHS lhs;
Variable(String name, Class type, LHS lhs) {
this.name = name;
this.lhs = lhs;
this.type = type;
}
Variable(String name, Object value, Modifiers modifiers)
throws UtilEvalError {
this(name, (Class) null/*type*/, value, modifiers);
}
/**
* This constructor is used in class generation.
*/
Variable(
String name, String typeDescriptor, Object value, Modifiers modifiers
)
throws UtilEvalError {
this(name, (Class) null/*type*/, value, modifiers);
this.typeDescriptor = typeDescriptor;
}
/**
* @param value may be null if this
*/
Variable(String name, Class type, Object value, Modifiers modifiers)
throws UtilEvalError {
this.name = name;
this.type = type;
this.modifiers = modifiers;
setValue(value, DECLARATION);
}
/**
* Set the value of the typed variable.
*
* @param value should be an object or wrapped bsh Primitive type. if value
* is null the appropriate default value will be set for the type: e.g.
* false for boolean, zero for integer types.
*/
public void setValue(Object value, int context)
throws UtilEvalError {
// check this.value
if (hasModifier("final") && this.value != null) {
throw new UtilEvalError("Final variable, can't re-assign.");
}
if (value == null) {
value = Primitive.getDefaultValue(type);
}
if (lhs != null) {
lhs.assign(value, false/*strictjava*/);
return;
}
// TODO: should add isJavaCastable() test for strictJava
// (as opposed to isJavaAssignable())
if (type != null) {
value = Types.castObject(value, type,
context == DECLARATION ? Types.CAST : Types.ASSIGNMENT
);
}
this.value = value;
}
/*
Note: UtilEvalError here comes from lhs.getValue().
A Variable can represent an LHS for the case of an imported class or
object field.
*/
public Object getValue()
throws UtilEvalError {
if (lhs != null) {
return lhs.getValue();
}
return value;
}
/**
* A type of null means loosely typed variable
*/
public Class getType() {
return type;
}
public String getTypeDescriptor() {
return typeDescriptor;
}
public Modifiers getModifiers() {
return modifiers;
}
public String getName() {
return name;
}
public boolean hasModifier(String name) {
return modifiers != null && modifiers.hasModifier(name);
}
@Override
public String toString() {
return "Variable: " + super.toString() + " " + name + ", type:" + type
+ ", value:" + value + ", lhs = " + lhs;
}
}
| 3,248 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHMethodDeclaration.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHMethodDeclaration.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
class BSHMethodDeclaration extends SimpleNode {
public String name;
// Begin Child node structure evaluated by insureNodesParsed
BSHReturnType returnTypeNode;
BSHFormalParameters paramsNode;
BSHBlock blockNode;
// index of the first throws clause child node
int firstThrowsClause;
// End Child node structure evaluated by insureNodesParsed
public Modifiers modifiers;
// Unsafe caching of type here.
Class returnType; // null (none), Void.TYPE, or a Class
int numThrows = 0;
BSHMethodDeclaration(int id) {
super(id);
}
/**
* Set the returnTypeNode, paramsNode, and blockNode based on child node
* structure. No evaluation is done here.
*/
synchronized void insureNodesParsed() {
if (paramsNode != null) // there is always a paramsNode
{
return;
}
Object firstNode = jjtGetChild(0);
firstThrowsClause = 1;
if (firstNode instanceof BSHReturnType) {
returnTypeNode = (BSHReturnType) firstNode;
paramsNode = (BSHFormalParameters) jjtGetChild(1);
if (jjtGetNumChildren() > 2 + numThrows) {
blockNode = (BSHBlock) jjtGetChild(2 + numThrows); // skip throws
}
++firstThrowsClause;
} else {
paramsNode = (BSHFormalParameters) jjtGetChild(0);
blockNode = (BSHBlock) jjtGetChild(1 + numThrows); // skip throws
}
}
/**
* Evaluate the return type node.
*
* @return the type or null indicating loosely typed return
*/
Class evalReturnType(CallStack callstack, Interpreter interpreter)
throws EvalError {
insureNodesParsed();
if (returnTypeNode != null) {
return returnTypeNode.evalReturnType(callstack, interpreter);
} else {
return null;
}
}
String getReturnTypeDescriptor(
CallStack callstack, Interpreter interpreter, String defaultPackage) {
insureNodesParsed();
if (returnTypeNode == null) {
return null;
} else {
return returnTypeNode.getTypeDescriptor(
callstack, interpreter, defaultPackage);
}
}
BSHReturnType getReturnTypeNode() {
insureNodesParsed();
return returnTypeNode;
}
/**
* Evaluate the declaration of the method. That is, determine the structure
* of the method and install it into the caller's namespace.
*/
@Override
public Object eval(CallStack callstack, Interpreter interpreter)
throws EvalError {
returnType = evalReturnType(callstack, interpreter);
evalNodes(callstack, interpreter);
// Install an *instance* of this method in the namespace.
// See notes in BshMethod
// This is not good...
// need a way to update eval without re-installing...
// so that we can re-eval params, etc. when classloader changes
// look into this
NameSpace namespace = callstack.top();
BSHMethod bshMethod = new BSHMethod(this, namespace, modifiers);
try {
namespace.setMethod(bshMethod);
} catch (UtilEvalError e) {
throw e.toEvalError(this, callstack);
}
return Primitive.VOID;
}
private void evalNodes(CallStack callstack, Interpreter interpreter)
throws EvalError {
insureNodesParsed();
// validate that the throws names are class names
for (int i = firstThrowsClause; i < numThrows + firstThrowsClause; i++) {
((BSHAmbiguousName) jjtGetChild(i)).toClass(
callstack, interpreter);
}
paramsNode.eval(callstack, interpreter);
// if strictJava mode, check for loose parameters and return type
if (interpreter.getStrictJava()) {
for (int i = 0; i < paramsNode.paramTypes.length; i++) {
if (paramsNode.paramTypes[i] == null) // Warning: Null callstack here. Don't think we need
// a stack trace to indicate how we sourced the method.
{
throw new EvalError(
"(Strict Java Mode) Undeclared argument type, parameter: "
+ paramsNode.getParamNames()[i] + " in method: "
+ name, this, null);
}
}
if (returnType == null) // Warning: Null callstack here. Don't think we need
// a stack trace to indicate how we sourced the method.
{
throw new EvalError(
"(Strict Java Mode) Undeclared return type for method: "
+ name, this, null);
}
}
}
@Override
public String toString() {
return "MethodDeclaration: " + name;
}
}
| 7,450 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHThrowStatement.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHThrowStatement.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
class BSHThrowStatement extends SimpleNode {
BSHThrowStatement(int id) {
super(id);
}
@Override
public Object eval(CallStack callstack, Interpreter interpreter)
throws EvalError {
Object obj = ((SimpleNode) jjtGetChild(0)).eval(callstack, interpreter);
// need to loosen this to any throwable... do we need to handle
// that in interpreter somewhere? check first...
if (!(obj instanceof Exception)) {
throw new EvalError("Expression in 'throw' must be Exception type",
this, callstack);
}
// wrap the exception in a TargetException to propogate it up
throw new TargetError((Throwable) obj, this, callstack);
}
}
| 3,297 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
ConsoleInterface.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/ConsoleInterface.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
import java.io.*;
/**
* The capabilities of a minimal console for BeanShell. Stream I/O and optimized
* print for output.
*
* A simple console may ignore some of these or map them to trivial
* implementations. e.g. print() with color can be mapped to plain text.
*
* @see bsh.util.GUIConsoleInterface
*/
public interface ConsoleInterface {
public Reader getIn();
public PrintStream getOut();
public PrintStream getErr();
public void println(Object o);
public void print(Object o);
public void error(Object o);
}
| 3,103 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
Parser.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/Parser.java | /* Generated By:JJTree&JavaCC: Do not edit this line. Parser.java */
package ehacks.bsh;
import java.io.*;
/**
* This is the BeanShell parser. It is used internally by the Interpreter class
* (which is probably what you are looking for). The parser knows only how to
* parse the structure of the language, it does not understand names, commands,
* etc.
* <p>
* You can use the Parser from the command line to do basic structural
* validation of BeanShell files without actually executing them. e.g. <code><pre>
* java bsh.Parser [ -p ] file [ file ] [ ... ]
* </pre></code>
* <p>
* The -p option causes the abstract syntax to be printed.
* <p>
*
* From code you'd use the Parser like this: <p <code><pre>
* Parser parser = new Parser(in);
* while( !(eof=parser.Line()) ) {
* SimpleNode node = parser.popNode();
* // use the node, etc. (See bsh.BSH* classes)
* }
* </pre></code>
*/
public class Parser/*@bgen(jjtree)*/ implements ParserTreeConstants, ParserConstants {/*@bgen(jjtree)*/
protected JJTParserState jjtree = new JJTParserState();
boolean retainComments = false;
public void setRetainComments(boolean b) {
retainComments = b;
}
void jjtreeOpenNodeScope(Node n) {
((SimpleNode) n).firstToken = getToken(1);
}
void jjtreeCloseNodeScope(Node n) {
((SimpleNode) n).lastToken = getToken(0);
}
/**
* Re-initialize the input stream and token source.
*/
void reInitInput(Reader in) {
ReInit(in);
}
public SimpleNode popNode() {
if (jjtree.nodeArity() > 0) // number of child nodes
{
return (SimpleNode) jjtree.popNode();
} else {
return null;
}
}
/**
* Explicitly re-initialize just the token reader. This seems to be
* necessary to avoid certain looping errors when reading bogus input. See
* Interpreter.
*/
void reInitTokenInput(Reader in) {
jj_input_stream.ReInit(in,
jj_input_stream.getEndLine(),
jj_input_stream.getEndColumn());
}
/**
* Lookahead for the enhanced for statement. Expect "for" "(" and then see
* whether we hit ":" or a ";" first.
*/
boolean isRegularForStatement() {
int curTok = 1;
Token tok;
tok = getToken(curTok++);
if (tok.kind != FOR) {
return false;
}
tok = getToken(curTok++);
if (tok.kind != LPAREN) {
return false;
}
while (true) {
tok = getToken(curTok++);
switch (tok.kind) {
case COLON:
return false;
case SEMICOLON:
return true;
case EOF:
return false;
}
}
}
/**
* Generate a ParseException with the specified message, pointing to the
* current token. The auto-generated Parser.generateParseException() method
* does not provide line number info, therefore we do this.
*/
ParseException createParseException(String message, Exception e) {
Token errortok = token;
int line = errortok.beginLine, column = errortok.beginColumn;
String mess = (errortok.kind == 0) ? tokenImage[0] : errortok.image;
return new ParseException("Parse error at line " + line
+ ", column " + column + " : " + message, e);
}
int parseInt(String s) throws NumberFormatException {
int radix;
int i;
if (s.startsWith("0x") || s.startsWith("0X")) {
radix = 16;
i = 2;
} else if (s.startsWith("0") && s.length() > 1) {
radix = 8;
i = 1;
} else {
radix = 10;
i = 0;
}
int result = 0;
int len = s.length();
for (; i < len; i++) {
if (result < 0) {
throw new NumberFormatException("Number too big for integer type: " + s);
}
result *= radix;
int digit = Character.digit(s.charAt(i), radix);
if (digit < 0) {
throw new NumberFormatException("Invalid integer type: " + s);
}
result += digit;
}
return result;
}
long parseLong(String s) throws NumberFormatException {
int radix;
int i;
if (s.startsWith("0x") || s.startsWith("0X")) {
radix = 16;
i = 2;
} else if (s.startsWith("0") && s.length() > 1) {
radix = 8;
i = 1;
} else {
radix = 10;
i = 0;
}
long result = 0;
int len = s.length();
for (; i < len; i++) {
if (result < 0L) {
throw new NumberFormatException("Number too big for long type: " + s);
}
result *= radix;
int digit = Character.digit(s.charAt(i), radix);
if (digit < 0) {
throw new NumberFormatException("Invalid long type: " + s);
}
result += digit;
}
return result;
}
/*
Thanks to Sreenivasa Viswanadha for suggesting how to get rid of expensive
lookahead here.
*/
public boolean Line() throws ParseException {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case 0:
jj_consume_token(0);
Interpreter.debug("End of File!");
{
if (true) {
return true;
}
}
break;
default:
if (jj_2_1(1)) {
BlockStatement();
{
if (true) {
return false;
}
}
} else {
jj_consume_token(-1);
throw new ParseException();
}
}
throw new Error("Missing return statement in function");
}
/**
* ***************************************
* THE JAVA LANGUAGE GRAMMAR STARTS HERE *
* ***************************************
*/
/*
Gather modifiers for a class, method, or field.
I lookahead is true then we are being called as part of a lookahead and we
should not enforce any rules. Otherwise we validate based on context
(field, method, class)
*/
public Modifiers Modifiers(int context, boolean lookahead) throws ParseException {
Modifiers mods = null;
label_1:
while (true) {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case ABSTRACT:
case FINAL:
case NATIVE:
case PRIVATE:
case PROTECTED:
case PUBLIC:
case STATIC:
case STRICTFP:
case SYNCHRONIZED:
case TRANSIENT:
case VOLATILE:
;
break;
default:
break label_1;
}
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case PRIVATE:
jj_consume_token(PRIVATE);
break;
case PROTECTED:
jj_consume_token(PROTECTED);
break;
case PUBLIC:
jj_consume_token(PUBLIC);
break;
case SYNCHRONIZED:
jj_consume_token(SYNCHRONIZED);
break;
case FINAL:
jj_consume_token(FINAL);
break;
case NATIVE:
jj_consume_token(NATIVE);
break;
case TRANSIENT:
jj_consume_token(TRANSIENT);
break;
case VOLATILE:
jj_consume_token(VOLATILE);
break;
case ABSTRACT:
jj_consume_token(ABSTRACT);
break;
case STATIC:
jj_consume_token(STATIC);
break;
case STRICTFP:
jj_consume_token(STRICTFP);
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
if (!lookahead) {
try {
if (mods == null) {
mods = new Modifiers();
}
mods.addModifier(context, getToken(0).image);
} catch (IllegalStateException e) {
{
if (true) {
throw createParseException(e.getMessage(), e);
}
}
}
}
}
{
if (true) {
return mods;
}
}
throw new Error("Missing return statement in function");
}
/**
*/
public void ClassDeclaration() throws ParseException {
/*@bgen(jjtree) ClassDeclaration */
BSHClassDeclaration jjtn000 = new BSHClassDeclaration(JJTCLASSDECLARATION);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
Modifiers mods;
Token name;
int numInterfaces;
try {
mods = Modifiers(Modifiers.CLASS, false);
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case CLASS:
jj_consume_token(CLASS);
break;
case INTERFACE:
jj_consume_token(INTERFACE);
jjtn000.isInterface = true;
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
name = jj_consume_token(IDENTIFIER);
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case EXTENDS:
jj_consume_token(EXTENDS);
AmbiguousName();
jjtn000.extend = true;
break;
default:
;
}
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case IMPLEMENTS:
jj_consume_token(IMPLEMENTS);
numInterfaces = NameList();
jjtn000.numInterfaces = numInterfaces;
break;
default:
;
}
Block();
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.modifiers = mods;
jjtn000.name = name.image;
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public void MethodDeclaration() throws ParseException {
/*@bgen(jjtree) MethodDeclaration */
BSHMethodDeclaration jjtn000 = new BSHMethodDeclaration(JJTMETHODDECLARATION);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
Token t = null;
Modifiers mods;
int count;
try {
mods = Modifiers(Modifiers.METHOD, false);
jjtn000.modifiers = mods;
if (jj_2_2(2147483647)) {
t = jj_consume_token(IDENTIFIER);
jjtn000.name = t.image;
} else {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case BOOLEAN:
case BYTE:
case CHAR:
case DOUBLE:
case FLOAT:
case INT:
case LONG:
case SHORT:
case VOID:
case IDENTIFIER:
ReturnType();
t = jj_consume_token(IDENTIFIER);
jjtn000.name = t.image;
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
}
FormalParameters();
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case THROWS:
jj_consume_token(THROWS);
count = NameList();
jjtn000.numThrows = count;
break;
default:
;
}
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case LBRACE:
Block();
break;
case SEMICOLON:
jj_consume_token(SEMICOLON);
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public void PackageDeclaration() throws ParseException {
/*@bgen(jjtree) PackageDeclaration */
BSHPackageDeclaration jjtn000 = new BSHPackageDeclaration(JJTPACKAGEDECLARATION);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
try {
jj_consume_token(PACKAGE);
AmbiguousName();
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public void ImportDeclaration() throws ParseException {
/*@bgen(jjtree) ImportDeclaration */
BSHImportDeclaration jjtn000 = new BSHImportDeclaration(JJTIMPORTDECLARATION);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
Token s = null;
Token t = null;
try {
if (jj_2_3(3)) {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case STATIC:
s = jj_consume_token(STATIC);
break;
default:
;
}
jj_consume_token(IMPORT);
AmbiguousName();
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case DOT:
t = jj_consume_token(DOT);
jj_consume_token(STAR);
break;
default:
;
}
jj_consume_token(SEMICOLON);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
if (s != null) {
jjtn000.staticImport = true;
}
if (t != null) {
jjtn000.importPackage = true;
}
} else {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case IMPORT:
jj_consume_token(IMPORT);
jj_consume_token(STAR);
jj_consume_token(SEMICOLON);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.superImport = true;
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
}
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public void VariableDeclarator() throws ParseException {
/*@bgen(jjtree) VariableDeclarator */
BSHVariableDeclarator jjtn000 = new BSHVariableDeclarator(JJTVARIABLEDECLARATOR);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
Token t;
try {
t = jj_consume_token(IDENTIFIER);
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case ASSIGN:
jj_consume_token(ASSIGN);
VariableInitializer();
break;
default:
;
}
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.name = t.image;
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
/*
this originally handled postfix array dimensions...
void VariableDeclaratorId() #VariableDeclaratorId :
{ Token t; }
{
t=<IDENTIFIER> { jjtThis.name = t.image; }
( "[" "]" { jjtThis.addUndefinedDimension(); } )*
}
*/
public void VariableInitializer() throws ParseException {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case LBRACE:
ArrayInitializer();
break;
case BOOLEAN:
case BYTE:
case CHAR:
case DOUBLE:
case FALSE:
case FLOAT:
case INT:
case LONG:
case NEW:
case NULL:
case SHORT:
case TRUE:
case VOID:
case INTEGER_LITERAL:
case FLOATING_POINT_LITERAL:
case CHARACTER_LITERAL:
case STRING_LITERAL:
case LONG_STRING_LITERAL:
case IDENTIFIER:
case LPAREN:
case BANG:
case TILDE:
case INCR:
case DECR:
case PLUS:
case MINUS:
Expression();
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
}
public void ArrayInitializer() throws ParseException {
/*@bgen(jjtree) ArrayInitializer */
BSHArrayInitializer jjtn000 = new BSHArrayInitializer(JJTARRAYINITIALIZER);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
try {
jj_consume_token(LBRACE);
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case BOOLEAN:
case BYTE:
case CHAR:
case DOUBLE:
case FALSE:
case FLOAT:
case INT:
case LONG:
case NEW:
case NULL:
case SHORT:
case TRUE:
case VOID:
case INTEGER_LITERAL:
case FLOATING_POINT_LITERAL:
case CHARACTER_LITERAL:
case STRING_LITERAL:
case LONG_STRING_LITERAL:
case IDENTIFIER:
case LPAREN:
case LBRACE:
case BANG:
case TILDE:
case INCR:
case DECR:
case PLUS:
case MINUS:
VariableInitializer();
label_2:
while (true) {
if (jj_2_4(2)) {
} else {
break;
}
jj_consume_token(COMMA);
VariableInitializer();
}
break;
default:
;
}
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case COMMA:
jj_consume_token(COMMA);
break;
default:
;
}
jj_consume_token(RBRACE);
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public void FormalParameters() throws ParseException {
/*@bgen(jjtree) FormalParameters */
BSHFormalParameters jjtn000 = new BSHFormalParameters(JJTFORMALPARAMETERS);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
try {
jj_consume_token(LPAREN);
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case BOOLEAN:
case BYTE:
case CHAR:
case DOUBLE:
case FLOAT:
case INT:
case LONG:
case SHORT:
case IDENTIFIER:
FormalParameter();
label_3:
while (true) {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case COMMA:
;
break;
default:
break label_3;
}
jj_consume_token(COMMA);
FormalParameter();
}
break;
default:
;
}
jj_consume_token(RPAREN);
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public void FormalParameter() throws ParseException {
/*@bgen(jjtree) FormalParameter */
BSHFormalParameter jjtn000 = new BSHFormalParameter(JJTFORMALPARAMETER);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
Token t;
try {
if (jj_2_5(2)) {
Type();
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case LT:
TypeArguments();
break;
default:
;
}
t = jj_consume_token(IDENTIFIER);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.name = t.image;
} else {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case IDENTIFIER:
t = jj_consume_token(IDENTIFIER);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.name = t.image;
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
}
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
/*
Type, name and expression syntax follows.
*/
public void Type() throws ParseException {
/*@bgen(jjtree) Type */
BSHType jjtn000 = new BSHType(JJTTYPE);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
try {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case BOOLEAN:
case BYTE:
case CHAR:
case DOUBLE:
case FLOAT:
case INT:
case LONG:
case SHORT:
PrimitiveType();
break;
case IDENTIFIER:
AmbiguousName();
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
label_4:
while (true) {
if (jj_2_6(2)) {
} else {
break;
}
jj_consume_token(LBRACKET);
jj_consume_token(RBRACKET);
jjtn000.addArrayDimension();
}
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
/*
Originally called ResultType in the grammar
*/
public void ReturnType() throws ParseException {
/*@bgen(jjtree) ReturnType */
BSHReturnType jjtn000 = new BSHReturnType(JJTRETURNTYPE);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
try {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case VOID:
jj_consume_token(VOID);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.isVoid = true;
break;
case BOOLEAN:
case BYTE:
case CHAR:
case DOUBLE:
case FLOAT:
case INT:
case LONG:
case SHORT:
case IDENTIFIER:
Type();
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case LT:
TypeArguments();
break;
default:
;
}
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public void PrimitiveType() throws ParseException {
/*@bgen(jjtree) PrimitiveType */
BSHPrimitiveType jjtn000 = new BSHPrimitiveType(JJTPRIMITIVETYPE);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
try {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case BOOLEAN:
jj_consume_token(BOOLEAN);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.type = Boolean.TYPE;
break;
case CHAR:
jj_consume_token(CHAR);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.type = Character.TYPE;
break;
case BYTE:
jj_consume_token(BYTE);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.type = Byte.TYPE;
break;
case SHORT:
jj_consume_token(SHORT);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.type = Short.TYPE;
break;
case INT:
jj_consume_token(INT);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.type = Integer.TYPE;
break;
case LONG:
jj_consume_token(LONG);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.type = Long.TYPE;
break;
case FLOAT:
jj_consume_token(FLOAT);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.type = Float.TYPE;
break;
case DOUBLE:
jj_consume_token(DOUBLE);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.type = Double.TYPE;
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public void AmbiguousName() throws ParseException {
/*@bgen(jjtree) AmbiguousName */
BSHAmbiguousName jjtn000 = new BSHAmbiguousName(JJTAMBIGUOUSNAME);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
Token t;
StringBuilder s;
try {
t = jj_consume_token(IDENTIFIER);
s = new StringBuilder(t.image);
label_5:
while (true) {
if (jj_2_7(2)) {
} else {
break;
}
jj_consume_token(DOT);
t = jj_consume_token(IDENTIFIER);
s.append(".").append(t.image);
}
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.text = s.toString();
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public int NameList() throws ParseException {
int count = 0;
AmbiguousName();
++count;
label_6:
while (true) {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case COMMA:
;
break;
default:
break label_6;
}
jj_consume_token(COMMA);
AmbiguousName();
++count;
}
{
if (true) {
return count;
}
}
throw new Error("Missing return statement in function");
}
/*
* Expression syntax follows.
*/
public void Expression() throws ParseException {
if (jj_2_8(2147483647)) {
Assignment();
} else {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case BOOLEAN:
case BYTE:
case CHAR:
case DOUBLE:
case FALSE:
case FLOAT:
case INT:
case LONG:
case NEW:
case NULL:
case SHORT:
case TRUE:
case VOID:
case INTEGER_LITERAL:
case FLOATING_POINT_LITERAL:
case CHARACTER_LITERAL:
case STRING_LITERAL:
case LONG_STRING_LITERAL:
case IDENTIFIER:
case LPAREN:
case BANG:
case TILDE:
case INCR:
case DECR:
case PLUS:
case MINUS:
ConditionalExpression();
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
}
}
public void Assignment() throws ParseException {
/*@bgen(jjtree) Assignment */
BSHAssignment jjtn000 = new BSHAssignment(JJTASSIGNMENT);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
int op;
try {
PrimaryExpression();
op = AssignmentOperator();
jjtn000.operator = op;
Expression();
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public int AssignmentOperator() throws ParseException {
Token t;
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case ASSIGN:
jj_consume_token(ASSIGN);
break;
case STARASSIGN:
jj_consume_token(STARASSIGN);
break;
case SLASHASSIGN:
jj_consume_token(SLASHASSIGN);
break;
case MODASSIGN:
jj_consume_token(MODASSIGN);
break;
case PLUSASSIGN:
jj_consume_token(PLUSASSIGN);
break;
case MINUSASSIGN:
jj_consume_token(MINUSASSIGN);
break;
case ANDASSIGN:
jj_consume_token(ANDASSIGN);
break;
case XORASSIGN:
jj_consume_token(XORASSIGN);
break;
case ORASSIGN:
jj_consume_token(ORASSIGN);
break;
case LSHIFTASSIGN:
jj_consume_token(LSHIFTASSIGN);
break;
case LSHIFTASSIGNX:
jj_consume_token(LSHIFTASSIGNX);
break;
case RSIGNEDSHIFTASSIGN:
jj_consume_token(RSIGNEDSHIFTASSIGN);
break;
case RSIGNEDSHIFTASSIGNX:
jj_consume_token(RSIGNEDSHIFTASSIGNX);
break;
case RUNSIGNEDSHIFTASSIGN:
jj_consume_token(RUNSIGNEDSHIFTASSIGN);
break;
case RUNSIGNEDSHIFTASSIGNX:
jj_consume_token(RUNSIGNEDSHIFTASSIGNX);
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
t = getToken(0);
{
if (true) {
return t.kind;
}
}
throw new Error("Missing return statement in function");
}
public void ConditionalExpression() throws ParseException {
ConditionalOrExpression();
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case HOOK:
jj_consume_token(HOOK);
Expression();
jj_consume_token(COLON);
BSHTernaryExpression jjtn001 = new BSHTernaryExpression(JJTTERNARYEXPRESSION);
boolean jjtc001 = true;
jjtree.openNodeScope(jjtn001);
jjtreeOpenNodeScope(jjtn001);
try {
ConditionalExpression();
} catch (Throwable jjte001) {
if (jjtc001) {
jjtree.clearNodeScope(jjtn001);
jjtc001 = false;
} else {
jjtree.popNode();
}
if (jjte001 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte001;
}
}
}
if (jjte001 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte001;
}
}
}
{
if (true) {
throw (Error) jjte001;
}
}
} finally {
if (jjtc001) {
jjtree.closeNodeScope(jjtn001, 3);
jjtreeCloseNodeScope(jjtn001);
}
}
break;
default:
;
}
}
public void ConditionalOrExpression() throws ParseException {
Token t = null;
ConditionalAndExpression();
label_7:
while (true) {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case BOOL_OR:
case BOOL_ORX:
;
break;
default:
break label_7;
}
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case BOOL_OR:
t = jj_consume_token(BOOL_OR);
break;
case BOOL_ORX:
t = jj_consume_token(BOOL_ORX);
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
ConditionalAndExpression();
BSHBinaryExpression jjtn001 = new BSHBinaryExpression(JJTBINARYEXPRESSION);
boolean jjtc001 = true;
jjtree.openNodeScope(jjtn001);
jjtreeOpenNodeScope(jjtn001);
try {
jjtree.closeNodeScope(jjtn001, 2);
jjtc001 = false;
jjtreeCloseNodeScope(jjtn001);
jjtn001.kind = t.kind;
} finally {
if (jjtc001) {
jjtree.closeNodeScope(jjtn001, 2);
jjtreeCloseNodeScope(jjtn001);
}
}
}
}
public void ConditionalAndExpression() throws ParseException {
Token t = null;
InclusiveOrExpression();
label_8:
while (true) {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case BOOL_AND:
case BOOL_ANDX:
;
break;
default:
break label_8;
}
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case BOOL_AND:
t = jj_consume_token(BOOL_AND);
break;
case BOOL_ANDX:
t = jj_consume_token(BOOL_ANDX);
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
InclusiveOrExpression();
BSHBinaryExpression jjtn001 = new BSHBinaryExpression(JJTBINARYEXPRESSION);
boolean jjtc001 = true;
jjtree.openNodeScope(jjtn001);
jjtreeOpenNodeScope(jjtn001);
try {
jjtree.closeNodeScope(jjtn001, 2);
jjtc001 = false;
jjtreeCloseNodeScope(jjtn001);
jjtn001.kind = t.kind;
} finally {
if (jjtc001) {
jjtree.closeNodeScope(jjtn001, 2);
jjtreeCloseNodeScope(jjtn001);
}
}
}
}
public void InclusiveOrExpression() throws ParseException {
Token t = null;
ExclusiveOrExpression();
label_9:
while (true) {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case BIT_OR:
case BIT_ORX:
;
break;
default:
break label_9;
}
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case BIT_OR:
t = jj_consume_token(BIT_OR);
break;
case BIT_ORX:
t = jj_consume_token(BIT_ORX);
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
ExclusiveOrExpression();
BSHBinaryExpression jjtn001 = new BSHBinaryExpression(JJTBINARYEXPRESSION);
boolean jjtc001 = true;
jjtree.openNodeScope(jjtn001);
jjtreeOpenNodeScope(jjtn001);
try {
jjtree.closeNodeScope(jjtn001, 2);
jjtc001 = false;
jjtreeCloseNodeScope(jjtn001);
jjtn001.kind = t.kind;
} finally {
if (jjtc001) {
jjtree.closeNodeScope(jjtn001, 2);
jjtreeCloseNodeScope(jjtn001);
}
}
}
}
public void ExclusiveOrExpression() throws ParseException {
Token t = null;
AndExpression();
label_10:
while (true) {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case XOR:
;
break;
default:
break label_10;
}
t = jj_consume_token(XOR);
AndExpression();
BSHBinaryExpression jjtn001 = new BSHBinaryExpression(JJTBINARYEXPRESSION);
boolean jjtc001 = true;
jjtree.openNodeScope(jjtn001);
jjtreeOpenNodeScope(jjtn001);
try {
jjtree.closeNodeScope(jjtn001, 2);
jjtc001 = false;
jjtreeCloseNodeScope(jjtn001);
jjtn001.kind = t.kind;
} finally {
if (jjtc001) {
jjtree.closeNodeScope(jjtn001, 2);
jjtreeCloseNodeScope(jjtn001);
}
}
}
}
public void AndExpression() throws ParseException {
Token t = null;
EqualityExpression();
label_11:
while (true) {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case BIT_AND:
case BIT_ANDX:
;
break;
default:
break label_11;
}
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case BIT_AND:
t = jj_consume_token(BIT_AND);
break;
case BIT_ANDX:
t = jj_consume_token(BIT_ANDX);
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
EqualityExpression();
BSHBinaryExpression jjtn001 = new BSHBinaryExpression(JJTBINARYEXPRESSION);
boolean jjtc001 = true;
jjtree.openNodeScope(jjtn001);
jjtreeOpenNodeScope(jjtn001);
try {
jjtree.closeNodeScope(jjtn001, 2);
jjtc001 = false;
jjtreeCloseNodeScope(jjtn001);
jjtn001.kind = t.kind;
} finally {
if (jjtc001) {
jjtree.closeNodeScope(jjtn001, 2);
jjtreeCloseNodeScope(jjtn001);
}
}
}
}
public void EqualityExpression() throws ParseException {
Token t = null;
InstanceOfExpression();
label_12:
while (true) {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case EQ:
case NE:
;
break;
default:
break label_12;
}
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case EQ:
t = jj_consume_token(EQ);
break;
case NE:
t = jj_consume_token(NE);
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
InstanceOfExpression();
BSHBinaryExpression jjtn001 = new BSHBinaryExpression(JJTBINARYEXPRESSION);
boolean jjtc001 = true;
jjtree.openNodeScope(jjtn001);
jjtreeOpenNodeScope(jjtn001);
try {
jjtree.closeNodeScope(jjtn001, 2);
jjtc001 = false;
jjtreeCloseNodeScope(jjtn001);
jjtn001.kind = t.kind;
} finally {
if (jjtc001) {
jjtree.closeNodeScope(jjtn001, 2);
jjtreeCloseNodeScope(jjtn001);
}
}
}
}
public void InstanceOfExpression() throws ParseException {
Token t = null;
RelationalExpression();
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case INSTANCEOF:
t = jj_consume_token(INSTANCEOF);
Type();
BSHBinaryExpression jjtn001 = new BSHBinaryExpression(JJTBINARYEXPRESSION);
boolean jjtc001 = true;
jjtree.openNodeScope(jjtn001);
jjtreeOpenNodeScope(jjtn001);
try {
jjtree.closeNodeScope(jjtn001, 2);
jjtc001 = false;
jjtreeCloseNodeScope(jjtn001);
jjtn001.kind = t.kind;
} finally {
if (jjtc001) {
jjtree.closeNodeScope(jjtn001, 2);
jjtreeCloseNodeScope(jjtn001);
}
}
break;
default:
;
}
}
public void RelationalExpression() throws ParseException {
Token t = null;
ShiftExpression();
label_13:
while (true) {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case GT:
case GTX:
case LT:
case LTX:
case LE:
case LEX:
case GE:
case GEX:
;
break;
default:
break label_13;
}
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case LT:
t = jj_consume_token(LT);
break;
case LTX:
t = jj_consume_token(LTX);
break;
case GT:
t = jj_consume_token(GT);
break;
case GTX:
t = jj_consume_token(GTX);
break;
case LE:
t = jj_consume_token(LE);
break;
case LEX:
t = jj_consume_token(LEX);
break;
case GE:
t = jj_consume_token(GE);
break;
case GEX:
t = jj_consume_token(GEX);
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
ShiftExpression();
BSHBinaryExpression jjtn001 = new BSHBinaryExpression(JJTBINARYEXPRESSION);
boolean jjtc001 = true;
jjtree.openNodeScope(jjtn001);
jjtreeOpenNodeScope(jjtn001);
try {
jjtree.closeNodeScope(jjtn001, 2);
jjtc001 = false;
jjtreeCloseNodeScope(jjtn001);
jjtn001.kind = t.kind;
} finally {
if (jjtc001) {
jjtree.closeNodeScope(jjtn001, 2);
jjtreeCloseNodeScope(jjtn001);
}
}
}
}
public void ShiftExpression() throws ParseException {
Token t = null;
AdditiveExpression();
label_14:
while (true) {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case LSHIFT:
case LSHIFTX:
case RSIGNEDSHIFT:
case RSIGNEDSHIFTX:
case RUNSIGNEDSHIFT:
case RUNSIGNEDSHIFTX:
;
break;
default:
break label_14;
}
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case LSHIFT:
t = jj_consume_token(LSHIFT);
break;
case LSHIFTX:
t = jj_consume_token(LSHIFTX);
break;
case RSIGNEDSHIFT:
t = jj_consume_token(RSIGNEDSHIFT);
break;
case RSIGNEDSHIFTX:
t = jj_consume_token(RSIGNEDSHIFTX);
break;
case RUNSIGNEDSHIFT:
t = jj_consume_token(RUNSIGNEDSHIFT);
break;
case RUNSIGNEDSHIFTX:
t = jj_consume_token(RUNSIGNEDSHIFTX);
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
AdditiveExpression();
BSHBinaryExpression jjtn001 = new BSHBinaryExpression(JJTBINARYEXPRESSION);
boolean jjtc001 = true;
jjtree.openNodeScope(jjtn001);
jjtreeOpenNodeScope(jjtn001);
try {
jjtree.closeNodeScope(jjtn001, 2);
jjtc001 = false;
jjtreeCloseNodeScope(jjtn001);
jjtn001.kind = t.kind;
} finally {
if (jjtc001) {
jjtree.closeNodeScope(jjtn001, 2);
jjtreeCloseNodeScope(jjtn001);
}
}
}
}
public void AdditiveExpression() throws ParseException {
Token t = null;
MultiplicativeExpression();
label_15:
while (true) {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case PLUS:
case MINUS:
;
break;
default:
break label_15;
}
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case PLUS:
t = jj_consume_token(PLUS);
break;
case MINUS:
t = jj_consume_token(MINUS);
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
MultiplicativeExpression();
BSHBinaryExpression jjtn001 = new BSHBinaryExpression(JJTBINARYEXPRESSION);
boolean jjtc001 = true;
jjtree.openNodeScope(jjtn001);
jjtreeOpenNodeScope(jjtn001);
try {
jjtree.closeNodeScope(jjtn001, 2);
jjtc001 = false;
jjtreeCloseNodeScope(jjtn001);
jjtn001.kind = t.kind;
} finally {
if (jjtc001) {
jjtree.closeNodeScope(jjtn001, 2);
jjtreeCloseNodeScope(jjtn001);
}
}
}
}
public void MultiplicativeExpression() throws ParseException {
Token t = null;
UnaryExpression();
label_16:
while (true) {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case STAR:
case SLASH:
case MOD:
;
break;
default:
break label_16;
}
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case STAR:
t = jj_consume_token(STAR);
break;
case SLASH:
t = jj_consume_token(SLASH);
break;
case MOD:
t = jj_consume_token(MOD);
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
UnaryExpression();
BSHBinaryExpression jjtn001 = new BSHBinaryExpression(JJTBINARYEXPRESSION);
boolean jjtc001 = true;
jjtree.openNodeScope(jjtn001);
jjtreeOpenNodeScope(jjtn001);
try {
jjtree.closeNodeScope(jjtn001, 2);
jjtc001 = false;
jjtreeCloseNodeScope(jjtn001);
jjtn001.kind = t.kind;
} finally {
if (jjtc001) {
jjtree.closeNodeScope(jjtn001, 2);
jjtreeCloseNodeScope(jjtn001);
}
}
}
}
public void UnaryExpression() throws ParseException {
Token t = null;
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case PLUS:
case MINUS:
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case PLUS:
t = jj_consume_token(PLUS);
break;
case MINUS:
t = jj_consume_token(MINUS);
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
UnaryExpression();
BSHUnaryExpression jjtn001 = new BSHUnaryExpression(JJTUNARYEXPRESSION);
boolean jjtc001 = true;
jjtree.openNodeScope(jjtn001);
jjtreeOpenNodeScope(jjtn001);
try {
jjtree.closeNodeScope(jjtn001, 1);
jjtc001 = false;
jjtreeCloseNodeScope(jjtn001);
jjtn001.kind = t.kind;
} finally {
if (jjtc001) {
jjtree.closeNodeScope(jjtn001, 1);
jjtreeCloseNodeScope(jjtn001);
}
}
break;
case INCR:
PreIncrementExpression();
break;
case DECR:
PreDecrementExpression();
break;
case BOOLEAN:
case BYTE:
case CHAR:
case DOUBLE:
case FALSE:
case FLOAT:
case INT:
case LONG:
case NEW:
case NULL:
case SHORT:
case TRUE:
case VOID:
case INTEGER_LITERAL:
case FLOATING_POINT_LITERAL:
case CHARACTER_LITERAL:
case STRING_LITERAL:
case LONG_STRING_LITERAL:
case IDENTIFIER:
case LPAREN:
case BANG:
case TILDE:
UnaryExpressionNotPlusMinus();
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
}
public void PreIncrementExpression() throws ParseException {
Token t = null;
t = jj_consume_token(INCR);
PrimaryExpression();
BSHUnaryExpression jjtn001 = new BSHUnaryExpression(JJTUNARYEXPRESSION);
boolean jjtc001 = true;
jjtree.openNodeScope(jjtn001);
jjtreeOpenNodeScope(jjtn001);
try {
jjtree.closeNodeScope(jjtn001, 1);
jjtc001 = false;
jjtreeCloseNodeScope(jjtn001);
jjtn001.kind = t.kind;
} finally {
if (jjtc001) {
jjtree.closeNodeScope(jjtn001, 1);
jjtreeCloseNodeScope(jjtn001);
}
}
}
public void PreDecrementExpression() throws ParseException {
Token t = null;
t = jj_consume_token(DECR);
PrimaryExpression();
BSHUnaryExpression jjtn001 = new BSHUnaryExpression(JJTUNARYEXPRESSION);
boolean jjtc001 = true;
jjtree.openNodeScope(jjtn001);
jjtreeOpenNodeScope(jjtn001);
try {
jjtree.closeNodeScope(jjtn001, 1);
jjtc001 = false;
jjtreeCloseNodeScope(jjtn001);
jjtn001.kind = t.kind;
} finally {
if (jjtc001) {
jjtree.closeNodeScope(jjtn001, 1);
jjtreeCloseNodeScope(jjtn001);
}
}
}
public void UnaryExpressionNotPlusMinus() throws ParseException {
Token t = null;
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case BANG:
case TILDE:
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case TILDE:
t = jj_consume_token(TILDE);
break;
case BANG:
t = jj_consume_token(BANG);
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
UnaryExpression();
BSHUnaryExpression jjtn001 = new BSHUnaryExpression(JJTUNARYEXPRESSION);
boolean jjtc001 = true;
jjtree.openNodeScope(jjtn001);
jjtreeOpenNodeScope(jjtn001);
try {
jjtree.closeNodeScope(jjtn001, 1);
jjtc001 = false;
jjtreeCloseNodeScope(jjtn001);
jjtn001.kind = t.kind;
} finally {
if (jjtc001) {
jjtree.closeNodeScope(jjtn001, 1);
jjtreeCloseNodeScope(jjtn001);
}
}
break;
default:
if (jj_2_9(2147483647)) {
CastExpression();
} else {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case BOOLEAN:
case BYTE:
case CHAR:
case DOUBLE:
case FALSE:
case FLOAT:
case INT:
case LONG:
case NEW:
case NULL:
case SHORT:
case TRUE:
case VOID:
case INTEGER_LITERAL:
case FLOATING_POINT_LITERAL:
case CHARACTER_LITERAL:
case STRING_LITERAL:
case LONG_STRING_LITERAL:
case IDENTIFIER:
case LPAREN:
PostfixExpression();
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
}
}
}
// This production is to determine lookahead only.
public void CastLookahead() throws ParseException {
if (jj_2_10(2)) {
jj_consume_token(LPAREN);
PrimitiveType();
} else if (jj_2_11(2147483647)) {
jj_consume_token(LPAREN);
AmbiguousName();
jj_consume_token(LBRACKET);
jj_consume_token(RBRACKET);
} else {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case LPAREN:
jj_consume_token(LPAREN);
AmbiguousName();
jj_consume_token(RPAREN);
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case TILDE:
jj_consume_token(TILDE);
break;
case BANG:
jj_consume_token(BANG);
break;
case LPAREN:
jj_consume_token(LPAREN);
break;
case IDENTIFIER:
jj_consume_token(IDENTIFIER);
break;
case NEW:
jj_consume_token(NEW);
break;
case FALSE:
case NULL:
case TRUE:
case VOID:
case INTEGER_LITERAL:
case FLOATING_POINT_LITERAL:
case CHARACTER_LITERAL:
case STRING_LITERAL:
case LONG_STRING_LITERAL:
Literal();
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
}
}
public void PostfixExpression() throws ParseException {
Token t = null;
if (jj_2_12(2147483647)) {
PrimaryExpression();
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case INCR:
t = jj_consume_token(INCR);
break;
case DECR:
t = jj_consume_token(DECR);
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
BSHUnaryExpression jjtn001 = new BSHUnaryExpression(JJTUNARYEXPRESSION);
boolean jjtc001 = true;
jjtree.openNodeScope(jjtn001);
jjtreeOpenNodeScope(jjtn001);
try {
jjtree.closeNodeScope(jjtn001, 1);
jjtc001 = false;
jjtreeCloseNodeScope(jjtn001);
jjtn001.kind = t.kind;
jjtn001.postfix = true;
} finally {
if (jjtc001) {
jjtree.closeNodeScope(jjtn001, 1);
jjtreeCloseNodeScope(jjtn001);
}
}
} else {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case BOOLEAN:
case BYTE:
case CHAR:
case DOUBLE:
case FALSE:
case FLOAT:
case INT:
case LONG:
case NEW:
case NULL:
case SHORT:
case TRUE:
case VOID:
case INTEGER_LITERAL:
case FLOATING_POINT_LITERAL:
case CHARACTER_LITERAL:
case STRING_LITERAL:
case LONG_STRING_LITERAL:
case IDENTIFIER:
case LPAREN:
PrimaryExpression();
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
}
}
public void CastExpression() throws ParseException {
/*@bgen(jjtree) CastExpression */
BSHCastExpression jjtn000 = new BSHCastExpression(JJTCASTEXPRESSION);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
try {
if (jj_2_13(2147483647)) {
jj_consume_token(LPAREN);
Type();
jj_consume_token(RPAREN);
UnaryExpression();
} else {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case LPAREN:
jj_consume_token(LPAREN);
Type();
jj_consume_token(RPAREN);
UnaryExpressionNotPlusMinus();
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
}
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public void PrimaryExpression() throws ParseException {
/*@bgen(jjtree) PrimaryExpression */
BSHPrimaryExpression jjtn000 = new BSHPrimaryExpression(JJTPRIMARYEXPRESSION);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
try {
PrimaryPrefix();
label_17:
while (true) {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case LBRACE:
case LBRACKET:
case DOT:
;
break;
default:
break label_17;
}
PrimarySuffix();
}
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public void MethodInvocation() throws ParseException {
/*@bgen(jjtree) MethodInvocation */
BSHMethodInvocation jjtn000 = new BSHMethodInvocation(JJTMETHODINVOCATION);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
try {
AmbiguousName();
Arguments();
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public void PrimaryPrefix() throws ParseException {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case FALSE:
case NULL:
case TRUE:
case VOID:
case INTEGER_LITERAL:
case FLOATING_POINT_LITERAL:
case CHARACTER_LITERAL:
case STRING_LITERAL:
case LONG_STRING_LITERAL:
Literal();
break;
case LPAREN:
jj_consume_token(LPAREN);
Expression();
jj_consume_token(RPAREN);
break;
case NEW:
AllocationExpression();
break;
default:
if (jj_2_14(2147483647)) {
MethodInvocation();
} else if (jj_2_15(2147483647)) {
Type();
} else {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case IDENTIFIER:
AmbiguousName();
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
}
}
}
public void PrimarySuffix() throws ParseException {
/*@bgen(jjtree) PrimarySuffix */
BSHPrimarySuffix jjtn000 = new BSHPrimarySuffix(JJTPRIMARYSUFFIX);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
Token t = null;
try {
if (jj_2_16(2)) {
jj_consume_token(DOT);
jj_consume_token(CLASS);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.operation = BSHPrimarySuffix.CLASS;
} else {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case LBRACKET:
jj_consume_token(LBRACKET);
Expression();
jj_consume_token(RBRACKET);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.operation = BSHPrimarySuffix.INDEX;
break;
case DOT:
jj_consume_token(DOT);
t = jj_consume_token(IDENTIFIER);
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case LPAREN:
Arguments();
break;
default:
;
}
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.operation = BSHPrimarySuffix.NAME;
jjtn000.field = t.image;
break;
case LBRACE:
jj_consume_token(LBRACE);
Expression();
jj_consume_token(RBRACE);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.operation = BSHPrimarySuffix.PROPERTY;
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
}
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public void Literal() throws ParseException {
/*@bgen(jjtree) Literal */
BSHLiteral jjtn000 = new BSHLiteral(JJTLITERAL);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
Token x;
boolean b;
String literal;
char ch;
try {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case INTEGER_LITERAL:
x = jj_consume_token(INTEGER_LITERAL);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
literal = x.image;
ch = literal.charAt(literal.length() - 1);
if (ch == 'l' || ch == 'L') {
literal = literal.substring(0, literal.length() - 1);
try {
jjtn000.value = new Primitive(parseLong(literal));
} catch (NumberFormatException e) {
{
if (true) {
throw createParseException(e.getMessage(), e);
}
}
}
} else {
try {
jjtn000.value = new Primitive(parseInt(literal));
} catch (NumberFormatException e) {
{
if (true) {
throw createParseException(e.getMessage(), e);
}
}
}
}
break;
case FLOATING_POINT_LITERAL:
x = jj_consume_token(FLOATING_POINT_LITERAL);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
literal = x.image;
ch = literal.charAt(literal.length() - 1);
if (ch == 'f' || ch == 'F') {
literal = literal.substring(0, literal.length() - 1);
jjtn000.value = new Primitive(Float.parseFloat(literal));
} else {
if (ch == 'd' || ch == 'D') {
literal = literal.substring(0, literal.length() - 1);
}
jjtn000.value = new Primitive(Double.parseDouble(literal));
}
break;
case CHARACTER_LITERAL:
x = jj_consume_token(CHARACTER_LITERAL);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
try {
jjtn000.charSetup(x.image.substring(1, x.image.length() - 1));
} catch (Exception e) {
{
if (true) {
throw createParseException("Error parsing character: " + x.image, e);
}
}
}
break;
case STRING_LITERAL:
x = jj_consume_token(STRING_LITERAL);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
try {
jjtn000.stringSetup(x.image.substring(1, x.image.length() - 1));
} catch (Exception e) {
{
if (true) {
throw createParseException("Error parsing string: " + x.image, e);
}
}
}
break;
case LONG_STRING_LITERAL:
x = jj_consume_token(LONG_STRING_LITERAL);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
try {
jjtn000.value = x.image.substring(3, x.image.length() - 3);
} catch (Exception e) {
{
if (true) {
throw createParseException("Error parsing long string: " + x.image, e);
}
}
}
break;
case FALSE:
case TRUE:
b = BooleanLiteral();
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.value = new Primitive(b);
break;
case NULL:
NullLiteral();
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.value = Primitive.NULL;
break;
case VOID:
VoidLiteral();
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.value = Primitive.VOID;
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public boolean BooleanLiteral() throws ParseException {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case TRUE:
jj_consume_token(TRUE);
{
if (true) {
return true;
}
}
break;
case FALSE:
jj_consume_token(FALSE);
{
if (true) {
return false;
}
}
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
throw new Error("Missing return statement in function");
}
public void NullLiteral() throws ParseException {
jj_consume_token(NULL);
}
public void VoidLiteral() throws ParseException {
jj_consume_token(VOID);
}
public void Arguments() throws ParseException {
/*@bgen(jjtree) Arguments */
BSHArguments jjtn000 = new BSHArguments(JJTARGUMENTS);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
try {
jj_consume_token(LPAREN);
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case BOOLEAN:
case BYTE:
case CHAR:
case DOUBLE:
case FALSE:
case FLOAT:
case INT:
case LONG:
case NEW:
case NULL:
case SHORT:
case TRUE:
case VOID:
case INTEGER_LITERAL:
case FLOATING_POINT_LITERAL:
case CHARACTER_LITERAL:
case STRING_LITERAL:
case LONG_STRING_LITERAL:
case IDENTIFIER:
case LPAREN:
case BANG:
case TILDE:
case INCR:
case DECR:
case PLUS:
case MINUS:
ArgumentList();
break;
default:
;
}
jj_consume_token(RPAREN);
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
// leave these on the stack for Arguments() to handle
public void ArgumentList() throws ParseException {
Expression();
label_18:
while (true) {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case COMMA:
;
break;
default:
break label_18;
}
jj_consume_token(COMMA);
Expression();
}
}
public void TypeArguments() throws ParseException {
jj_consume_token(LT);
jj_consume_token(IDENTIFIER);
jj_consume_token(GT);
}
public void AllocationExpression() throws ParseException {
/*@bgen(jjtree) AllocationExpression */
BSHAllocationExpression jjtn000 = new BSHAllocationExpression(JJTALLOCATIONEXPRESSION);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
try {
if (jj_2_18(2)) {
jj_consume_token(NEW);
PrimitiveType();
ArrayDimensions();
} else {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case NEW:
jj_consume_token(NEW);
AmbiguousName();
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case LT:
TypeArguments();
break;
default:
;
}
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case LBRACKET:
ArrayDimensions();
break;
case LPAREN:
Arguments();
if (jj_2_17(2)) {
Block();
} else {
}
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
}
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public void ArrayDimensions() throws ParseException {
/*@bgen(jjtree) ArrayDimensions */
BSHArrayDimensions jjtn000 = new BSHArrayDimensions(JJTARRAYDIMENSIONS);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
try {
if (jj_2_21(2)) {
label_19:
while (true) {
jj_consume_token(LBRACKET);
Expression();
jj_consume_token(RBRACKET);
jjtn000.addDefinedDimension();
if (jj_2_19(2)) {
} else {
break;
}
}
label_20:
while (true) {
if (jj_2_20(2)) {
} else {
break;
}
jj_consume_token(LBRACKET);
jj_consume_token(RBRACKET);
jjtn000.addUndefinedDimension();
}
} else {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case LBRACKET:
label_21:
while (true) {
jj_consume_token(LBRACKET);
jj_consume_token(RBRACKET);
jjtn000.addUndefinedDimension();
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case LBRACKET:
;
break;
default:
break label_21;
}
}
ArrayInitializer();
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
}
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
/*
* Statement syntax follows.
*/
public void Statement() throws ParseException {
if (jj_2_22(2)) {
LabeledStatement();
} else {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case LBRACE:
Block();
break;
case SEMICOLON:
EmptyStatement();
break;
case BOOLEAN:
case BYTE:
case CHAR:
case DOUBLE:
case FALSE:
case FLOAT:
case INT:
case LONG:
case NEW:
case NULL:
case SHORT:
case TRUE:
case VOID:
case INTEGER_LITERAL:
case FLOATING_POINT_LITERAL:
case CHARACTER_LITERAL:
case STRING_LITERAL:
case LONG_STRING_LITERAL:
case IDENTIFIER:
case LPAREN:
case BANG:
case TILDE:
case INCR:
case DECR:
case PLUS:
case MINUS:
StatementExpression();
jj_consume_token(SEMICOLON);
break;
case SWITCH:
SwitchStatement();
break;
case IF:
IfStatement();
break;
case WHILE:
WhileStatement();
break;
case DO:
DoStatement();
break;
default:
if (isRegularForStatement()) {
ForStatement();
} else {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case FOR:
EnhancedForStatement();
break;
case BREAK:
BreakStatement();
break;
case CONTINUE:
ContinueStatement();
break;
case RETURN:
ReturnStatement();
break;
case SYNCHRONIZED:
SynchronizedStatement();
break;
case THROW:
ThrowStatement();
break;
case TRY:
TryStatement();
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
}
}
}
}
public void LabeledStatement() throws ParseException {
jj_consume_token(IDENTIFIER);
jj_consume_token(COLON);
Statement();
}
public void Block() throws ParseException {
/*@bgen(jjtree) Block */
BSHBlock jjtn000 = new BSHBlock(JJTBLOCK);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
try {
jj_consume_token(LBRACE);
label_22:
while (true) {
if (jj_2_23(1)) {
} else {
break;
}
BlockStatement();
}
jj_consume_token(RBRACE);
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public void BlockStatement() throws ParseException {
if (jj_2_24(2147483647)) {
ClassDeclaration();
} else if (jj_2_25(2147483647)) {
MethodDeclaration();
} else if (jj_2_26(2147483647)) {
MethodDeclaration();
} else if (jj_2_27(2147483647)) {
TypedVariableDeclaration();
jj_consume_token(SEMICOLON);
} else if (jj_2_28(1)) {
Statement();
} else {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case IMPORT:
case STATIC:
ImportDeclaration();
break;
case PACKAGE:
PackageDeclaration();
break;
case FORMAL_COMMENT:
FormalComment();
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
}
}
public void FormalComment() throws ParseException {
/*@bgen(jjtree) #FormalComment( retainComments) */
BSHFormalComment jjtn000 = new BSHFormalComment(JJTFORMALCOMMENT);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
Token t;
try {
t = jj_consume_token(FORMAL_COMMENT);
jjtree.closeNodeScope(jjtn000, retainComments);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.text = t.image;
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, retainComments);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public void EmptyStatement() throws ParseException {
jj_consume_token(SEMICOLON);
}
public void StatementExpression() throws ParseException {
Expression();
}
public void SwitchStatement() throws ParseException {
/*@bgen(jjtree) SwitchStatement */
BSHSwitchStatement jjtn000 = new BSHSwitchStatement(JJTSWITCHSTATEMENT);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
try {
jj_consume_token(SWITCH);
jj_consume_token(LPAREN);
Expression();
jj_consume_token(RPAREN);
jj_consume_token(LBRACE);
label_23:
while (true) {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case CASE:
case _DEFAULT:
;
break;
default:
break label_23;
}
SwitchLabel();
label_24:
while (true) {
if (jj_2_29(1)) {
} else {
break;
}
BlockStatement();
}
}
jj_consume_token(RBRACE);
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public void SwitchLabel() throws ParseException {
/*@bgen(jjtree) SwitchLabel */
BSHSwitchLabel jjtn000 = new BSHSwitchLabel(JJTSWITCHLABEL);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
try {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case CASE:
jj_consume_token(CASE);
Expression();
jj_consume_token(COLON);
break;
case _DEFAULT:
jj_consume_token(_DEFAULT);
jj_consume_token(COLON);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.isDefault = true;
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public void IfStatement() throws ParseException {
/*@bgen(jjtree) IfStatement */
BSHIfStatement jjtn000 = new BSHIfStatement(JJTIFSTATEMENT);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
try {
jj_consume_token(IF);
jj_consume_token(LPAREN);
Expression();
jj_consume_token(RPAREN);
Statement();
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case ELSE:
jj_consume_token(ELSE);
Statement();
break;
default:
;
}
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public void WhileStatement() throws ParseException {
/*@bgen(jjtree) WhileStatement */
BSHWhileStatement jjtn000 = new BSHWhileStatement(JJTWHILESTATEMENT);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
try {
jj_consume_token(WHILE);
jj_consume_token(LPAREN);
Expression();
jj_consume_token(RPAREN);
Statement();
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
/*
Do statement is just a While statement with a special hook to execute
at least once.
*/
public void DoStatement() throws ParseException {
/*@bgen(jjtree) WhileStatement */
BSHWhileStatement jjtn000 = new BSHWhileStatement(JJTWHILESTATEMENT);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
try {
jj_consume_token(DO);
Statement();
jj_consume_token(WHILE);
jj_consume_token(LPAREN);
Expression();
jj_consume_token(RPAREN);
jj_consume_token(SEMICOLON);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.isDoStatement = true;
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public void ForStatement() throws ParseException {
/*@bgen(jjtree) ForStatement */
BSHForStatement jjtn000 = new BSHForStatement(JJTFORSTATEMENT);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
Token t = null;
try {
jj_consume_token(FOR);
jj_consume_token(LPAREN);
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case ABSTRACT:
case BOOLEAN:
case BYTE:
case CHAR:
case DOUBLE:
case FALSE:
case FINAL:
case FLOAT:
case INT:
case LONG:
case NATIVE:
case NEW:
case NULL:
case PRIVATE:
case PROTECTED:
case PUBLIC:
case SHORT:
case STATIC:
case STRICTFP:
case SYNCHRONIZED:
case TRANSIENT:
case TRUE:
case VOID:
case VOLATILE:
case INTEGER_LITERAL:
case FLOATING_POINT_LITERAL:
case CHARACTER_LITERAL:
case STRING_LITERAL:
case LONG_STRING_LITERAL:
case IDENTIFIER:
case LPAREN:
case BANG:
case TILDE:
case INCR:
case DECR:
case PLUS:
case MINUS:
ForInit();
jjtn000.hasForInit = true;
break;
default:
;
}
jj_consume_token(SEMICOLON);
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case BOOLEAN:
case BYTE:
case CHAR:
case DOUBLE:
case FALSE:
case FLOAT:
case INT:
case LONG:
case NEW:
case NULL:
case SHORT:
case TRUE:
case VOID:
case INTEGER_LITERAL:
case FLOATING_POINT_LITERAL:
case CHARACTER_LITERAL:
case STRING_LITERAL:
case LONG_STRING_LITERAL:
case IDENTIFIER:
case LPAREN:
case BANG:
case TILDE:
case INCR:
case DECR:
case PLUS:
case MINUS:
Expression();
jjtn000.hasExpression = true;
break;
default:
;
}
jj_consume_token(SEMICOLON);
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case BOOLEAN:
case BYTE:
case CHAR:
case DOUBLE:
case FALSE:
case FLOAT:
case INT:
case LONG:
case NEW:
case NULL:
case SHORT:
case TRUE:
case VOID:
case INTEGER_LITERAL:
case FLOATING_POINT_LITERAL:
case CHARACTER_LITERAL:
case STRING_LITERAL:
case LONG_STRING_LITERAL:
case IDENTIFIER:
case LPAREN:
case BANG:
case TILDE:
case INCR:
case DECR:
case PLUS:
case MINUS:
ForUpdate();
jjtn000.hasForUpdate = true;
break;
default:
;
}
jj_consume_token(RPAREN);
Statement();
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
/*
The new JDK1.5 enhanced for statement.
e.g. for( int a : arrayOfInts ) { }
We also support loose typing of the iterator var for BeanShell
e.g. for( a : arrayOfInts ) { }
*/
public void EnhancedForStatement() throws ParseException {
/*@bgen(jjtree) EnhancedForStatement */
BSHEnhancedForStatement jjtn000 = new BSHEnhancedForStatement(JJTENHANCEDFORSTATEMENT);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
Token t = null;
try {
if (jj_2_30(4)) {
jj_consume_token(FOR);
jj_consume_token(LPAREN);
t = jj_consume_token(IDENTIFIER);
jj_consume_token(COLON);
Expression();
jj_consume_token(RPAREN);
Statement();
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.varName = t.image;
} else {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case FOR:
jj_consume_token(FOR);
jj_consume_token(LPAREN);
Type();
t = jj_consume_token(IDENTIFIER);
jj_consume_token(COLON);
Expression();
jj_consume_token(RPAREN);
Statement();
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.varName = t.image;
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
}
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public void ForInit() throws ParseException {
Token t = null;
if (jj_2_31(2147483647)) {
TypedVariableDeclaration();
} else {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case BOOLEAN:
case BYTE:
case CHAR:
case DOUBLE:
case FALSE:
case FLOAT:
case INT:
case LONG:
case NEW:
case NULL:
case SHORT:
case TRUE:
case VOID:
case INTEGER_LITERAL:
case FLOATING_POINT_LITERAL:
case CHARACTER_LITERAL:
case STRING_LITERAL:
case LONG_STRING_LITERAL:
case IDENTIFIER:
case LPAREN:
case BANG:
case TILDE:
case INCR:
case DECR:
case PLUS:
case MINUS:
StatementExpressionList();
break;
default:
jj_consume_token(-1);
throw new ParseException();
}
}
}
/**
* Declared a typed variable. Untyped variables are not declared per-se but
* are handled by the part of the grammar that deals with assignments.
*/
public void TypedVariableDeclaration() throws ParseException {
/*@bgen(jjtree) TypedVariableDeclaration */
BSHTypedVariableDeclaration jjtn000 = new BSHTypedVariableDeclaration(JJTTYPEDVARIABLEDECLARATION);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
Token t = null;
Modifiers mods;
try {
mods = Modifiers(Modifiers.FIELD, false);
Type();
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case LT:
TypeArguments();
break;
default:
;
}
VariableDeclarator();
label_25:
while (true) {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case COMMA:
;
break;
default:
break label_25;
}
jj_consume_token(COMMA);
VariableDeclarator();
}
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.modifiers = mods;
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public void StatementExpressionList() throws ParseException {
/*@bgen(jjtree) StatementExpressionList */
BSHStatementExpressionList jjtn000 = new BSHStatementExpressionList(JJTSTATEMENTEXPRESSIONLIST);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
try {
StatementExpression();
label_26:
while (true) {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case COMMA:
;
break;
default:
break label_26;
}
jj_consume_token(COMMA);
StatementExpression();
}
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public void ForUpdate() throws ParseException {
StatementExpressionList();
}
public void BreakStatement() throws ParseException {
/*@bgen(jjtree) ReturnStatement */
BSHReturnStatement jjtn000 = new BSHReturnStatement(JJTRETURNSTATEMENT);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
try {
jj_consume_token(BREAK);
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case IDENTIFIER:
jj_consume_token(IDENTIFIER);
break;
default:
;
}
jj_consume_token(SEMICOLON);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.kind = BREAK;
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public void ContinueStatement() throws ParseException {
/*@bgen(jjtree) ReturnStatement */
BSHReturnStatement jjtn000 = new BSHReturnStatement(JJTRETURNSTATEMENT);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
try {
jj_consume_token(CONTINUE);
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case IDENTIFIER:
jj_consume_token(IDENTIFIER);
break;
default:
;
}
jj_consume_token(SEMICOLON);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.kind = CONTINUE;
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public void ReturnStatement() throws ParseException {
/*@bgen(jjtree) ReturnStatement */
BSHReturnStatement jjtn000 = new BSHReturnStatement(JJTRETURNSTATEMENT);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
try {
jj_consume_token(RETURN);
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case BOOLEAN:
case BYTE:
case CHAR:
case DOUBLE:
case FALSE:
case FLOAT:
case INT:
case LONG:
case NEW:
case NULL:
case SHORT:
case TRUE:
case VOID:
case INTEGER_LITERAL:
case FLOATING_POINT_LITERAL:
case CHARACTER_LITERAL:
case STRING_LITERAL:
case LONG_STRING_LITERAL:
case IDENTIFIER:
case LPAREN:
case BANG:
case TILDE:
case INCR:
case DECR:
case PLUS:
case MINUS:
Expression();
break;
default:
;
}
jj_consume_token(SEMICOLON);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.kind = RETURN;
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public void SynchronizedStatement() throws ParseException {
/*@bgen(jjtree) Block */
BSHBlock jjtn000 = new BSHBlock(JJTBLOCK);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
try {
jj_consume_token(SYNCHRONIZED);
jj_consume_token(LPAREN);
Expression();
jj_consume_token(RPAREN);
Block();
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
jjtn000.isSynchronized = true;
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public void ThrowStatement() throws ParseException {
/*@bgen(jjtree) ThrowStatement */
BSHThrowStatement jjtn000 = new BSHThrowStatement(JJTTHROWSTATEMENT);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
try {
jj_consume_token(THROW);
Expression();
jj_consume_token(SEMICOLON);
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
public void TryStatement() throws ParseException {
/*@bgen(jjtree) TryStatement */
BSHTryStatement jjtn000 = new BSHTryStatement(JJTTRYSTATEMENT);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);
boolean closed = false;
try {
jj_consume_token(TRY);
Block();
label_27:
while (true) {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case CATCH:
;
break;
default:
break label_27;
}
jj_consume_token(CATCH);
jj_consume_token(LPAREN);
FormalParameter();
jj_consume_token(RPAREN);
Block();
closed = true;
}
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case FINALLY:
jj_consume_token(FINALLY);
Block();
closed = true;
break;
default:
;
}
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtreeCloseNodeScope(jjtn000);
if (!closed) {
if (true) {
throw generateParseException();
}
}
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{
if (true) {
throw (RuntimeException) jjte000;
}
}
}
if (jjte000 instanceof ParseException) {
{
if (true) {
throw (ParseException) jjte000;
}
}
}
{
if (true) {
throw (Error) jjte000;
}
}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
private boolean jj_2_1(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_1();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_2(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_2();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_3(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_3();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_4(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_4();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_5(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_5();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_6(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_6();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_7(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_7();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_8(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_8();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_9(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_9();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_10(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_10();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_11(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_11();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_12(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_12();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_13(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_13();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_14(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_14();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_15(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_15();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_16(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_16();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_17(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_17();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_18(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_18();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_19(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_19();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_20(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_20();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_21(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_21();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_22(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_22();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_23(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_23();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_24(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_24();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_25(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_25();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_26(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_26();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_27(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_27();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_28(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_28();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_29(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_29();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_30(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_30();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_2_31(int xla) {
jj_la = xla;
jj_lastpos = jj_scanpos = token;
try {
return !jj_3_31();
} catch (LookaheadSuccess ls) {
return true;
}
}
private boolean jj_3_8() {
if (jj_3R_34()) {
return true;
}
return jj_3R_35();
}
private boolean jj_3R_110() {
if (jj_3R_34()) {
return true;
}
if (jj_3R_35()) {
return true;
}
return jj_3R_40();
}
private boolean jj_3R_150() {
if (jj_scan_token(NEW)) {
return true;
}
if (jj_3R_29()) {
return true;
}
Token xsp;
xsp = jj_scanpos;
if (jj_3R_156()) {
jj_scanpos = xsp;
}
xsp = jj_scanpos;
if (jj_3R_157()) {
jj_scanpos = xsp;
if (jj_3R_158()) {
return true;
}
}
return false;
}
private boolean jj_3R_59() {
if (jj_scan_token(LT)) {
return true;
}
if (jj_scan_token(IDENTIFIER)) {
return true;
}
return jj_scan_token(GT);
}
private boolean jj_3_18() {
if (jj_scan_token(NEW)) {
return true;
}
if (jj_3R_37()) {
return true;
}
return jj_3R_155();
}
private boolean jj_3R_134() {
Token xsp;
xsp = jj_scanpos;
if (jj_3_18()) {
jj_scanpos = xsp;
if (jj_3R_150()) {
return true;
}
}
return false;
}
private boolean jj_3R_74() {
return jj_3R_111();
}
private boolean jj_3R_40() {
Token xsp;
xsp = jj_scanpos;
if (jj_3R_73()) {
jj_scanpos = xsp;
if (jj_3R_74()) {
return true;
}
}
return false;
}
private boolean jj_3R_73() {
return jj_3R_110();
}
private boolean jj_3R_152() {
if (jj_scan_token(COMMA)) {
return true;
}
return jj_3R_40();
}
private boolean jj_3R_138() {
if (jj_3R_40()) {
return true;
}
Token xsp;
while (true) {
xsp = jj_scanpos;
if (jj_3R_152()) {
jj_scanpos = xsp;
break;
}
}
return false;
}
private boolean jj_3R_109() {
return jj_3R_138();
}
private boolean jj_3R_79() {
if (jj_3R_29()) {
return true;
}
Token xsp;
while (true) {
xsp = jj_scanpos;
if (jj_3R_115()) {
jj_scanpos = xsp;
break;
}
}
return false;
}
private boolean jj_3R_72() {
if (jj_scan_token(LPAREN)) {
return true;
}
Token xsp;
xsp = jj_scanpos;
if (jj_3R_109()) {
jj_scanpos = xsp;
}
return jj_scan_token(RPAREN);
}
private boolean jj_3_7() {
if (jj_scan_token(DOT)) {
return true;
}
return jj_scan_token(IDENTIFIER);
}
private boolean jj_3R_29() {
if (jj_scan_token(IDENTIFIER)) {
return true;
}
Token xsp;
while (true) {
xsp = jj_scanpos;
if (jj_3_7()) {
jj_scanpos = xsp;
break;
}
}
return false;
}
private boolean jj_3R_161() {
return jj_scan_token(FALSE);
}
private boolean jj_3R_160() {
return jj_scan_token(TRUE);
}
private boolean jj_3R_154() {
Token xsp;
xsp = jj_scanpos;
if (jj_3R_160()) {
jj_scanpos = xsp;
if (jj_3R_161()) {
return true;
}
}
return false;
}
private boolean jj_3R_71() {
return jj_scan_token(DOUBLE);
}
private boolean jj_3R_70() {
return jj_scan_token(FLOAT);
}
private boolean jj_3R_69() {
return jj_scan_token(LONG);
}
private boolean jj_3R_68() {
return jj_scan_token(INT);
}
private boolean jj_3R_112() {
return jj_3R_59();
}
private boolean jj_3R_67() {
return jj_scan_token(SHORT);
}
private boolean jj_3R_58() {
return jj_3R_29();
}
private boolean jj_3R_149() {
return jj_scan_token(57);
}
private boolean jj_3R_66() {
return jj_scan_token(BYTE);
}
private boolean jj_3R_65() {
return jj_scan_token(CHAR);
}
private boolean jj_3R_64() {
return jj_scan_token(BOOLEAN);
}
private boolean jj_3R_37() {
Token xsp;
xsp = jj_scanpos;
if (jj_3R_64()) {
jj_scanpos = xsp;
if (jj_3R_65()) {
jj_scanpos = xsp;
if (jj_3R_66()) {
jj_scanpos = xsp;
if (jj_3R_67()) {
jj_scanpos = xsp;
if (jj_3R_68()) {
jj_scanpos = xsp;
if (jj_3R_69()) {
jj_scanpos = xsp;
if (jj_3R_70()) {
jj_scanpos = xsp;
if (jj_3R_71()) {
return true;
}
}
}
}
}
}
}
}
return false;
}
private boolean jj_3R_148() {
return jj_scan_token(41);
}
private boolean jj_3R_147() {
return jj_3R_154();
}
private boolean jj_3R_77() {
if (jj_3R_32()) {
return true;
}
Token xsp;
xsp = jj_scanpos;
if (jj_3R_112()) {
jj_scanpos = xsp;
}
return false;
}
private boolean jj_3R_43() {
Token xsp;
xsp = jj_scanpos;
if (jj_3R_76()) {
jj_scanpos = xsp;
if (jj_3R_77()) {
return true;
}
}
return false;
}
private boolean jj_3R_76() {
return jj_scan_token(VOID);
}
private boolean jj_3_6() {
if (jj_scan_token(LBRACKET)) {
return true;
}
return jj_scan_token(RBRACKET);
}
private boolean jj_3R_146() {
return jj_scan_token(LONG_STRING_LITERAL);
}
private boolean jj_3R_33() {
return jj_3R_59();
}
private boolean jj_3R_57() {
return jj_3R_37();
}
private boolean jj_3R_114() {
if (jj_scan_token(COMMA)) {
return true;
}
return jj_3R_113();
}
private boolean jj_3R_197() {
if (jj_scan_token(FINALLY)) {
return true;
}
return jj_3R_39();
}
private boolean jj_3R_196() {
if (jj_scan_token(CATCH)) {
return true;
}
if (jj_scan_token(LPAREN)) {
return true;
}
if (jj_3R_113()) {
return true;
}
if (jj_scan_token(RPAREN)) {
return true;
}
return jj_3R_39();
}
private boolean jj_3R_145() {
return jj_scan_token(STRING_LITERAL);
}
private boolean jj_3R_32() {
Token xsp;
xsp = jj_scanpos;
if (jj_3R_57()) {
jj_scanpos = xsp;
if (jj_3R_58()) {
return true;
}
}
while (true) {
xsp = jj_scanpos;
if (jj_3_6()) {
jj_scanpos = xsp;
break;
}
}
return false;
}
private boolean jj_3R_128() {
if (jj_scan_token(TRY)) {
return true;
}
if (jj_3R_39()) {
return true;
}
Token xsp;
while (true) {
xsp = jj_scanpos;
if (jj_3R_196()) {
jj_scanpos = xsp;
break;
}
}
xsp = jj_scanpos;
if (jj_3R_197()) {
jj_scanpos = xsp;
}
return false;
}
private boolean jj_3R_144() {
return jj_scan_token(CHARACTER_LITERAL);
}
private boolean jj_3R_184() {
if (jj_scan_token(COMMA)) {
return true;
}
return jj_3R_183();
}
private boolean jj_3_4() {
if (jj_scan_token(COMMA)) {
return true;
}
return jj_3R_31();
}
private boolean jj_3R_140() {
return jj_scan_token(IDENTIFIER);
}
private boolean jj_3_5() {
if (jj_3R_32()) {
return true;
}
Token xsp;
xsp = jj_scanpos;
if (jj_3R_33()) {
jj_scanpos = xsp;
}
return jj_scan_token(IDENTIFIER);
}
private boolean jj_3R_78() {
if (jj_3R_113()) {
return true;
}
Token xsp;
while (true) {
xsp = jj_scanpos;
if (jj_3R_114()) {
jj_scanpos = xsp;
break;
}
}
return false;
}
private boolean jj_3R_113() {
Token xsp;
xsp = jj_scanpos;
if (jj_3_5()) {
jj_scanpos = xsp;
if (jj_3R_140()) {
return true;
}
}
return false;
}
private boolean jj_3R_127() {
if (jj_scan_token(THROW)) {
return true;
}
if (jj_3R_40()) {
return true;
}
return jj_scan_token(SEMICOLON);
}
private boolean jj_3R_44() {
if (jj_scan_token(LPAREN)) {
return true;
}
Token xsp;
xsp = jj_scanpos;
if (jj_3R_78()) {
jj_scanpos = xsp;
}
return jj_scan_token(RPAREN);
}
private boolean jj_3R_195() {
return jj_3R_40();
}
private boolean jj_3R_169() {
if (jj_3R_31()) {
return true;
}
Token xsp;
while (true) {
xsp = jj_scanpos;
if (jj_3_4()) {
jj_scanpos = xsp;
break;
}
}
return false;
}
private boolean jj_3R_143() {
return jj_scan_token(FLOATING_POINT_LITERAL);
}
private boolean jj_3R_126() {
if (jj_scan_token(SYNCHRONIZED)) {
return true;
}
if (jj_scan_token(LPAREN)) {
return true;
}
if (jj_3R_40()) {
return true;
}
if (jj_scan_token(RPAREN)) {
return true;
}
return jj_3R_39();
}
private boolean jj_3R_100() {
if (jj_scan_token(LBRACE)) {
return true;
}
Token xsp;
xsp = jj_scanpos;
if (jj_3R_169()) {
jj_scanpos = xsp;
}
xsp = jj_scanpos;
if (jj_scan_token(80)) {
jj_scanpos = xsp;
}
return jj_scan_token(RBRACE);
}
private boolean jj_3R_30() {
if (jj_scan_token(DOT)) {
return true;
}
return jj_scan_token(STAR);
}
private boolean jj_3R_217() {
if (jj_scan_token(COMMA)) {
return true;
}
return jj_3R_116();
}
private boolean jj_3R_187() {
if (jj_scan_token(ASSIGN)) {
return true;
}
return jj_3R_31();
}
private boolean jj_3R_125() {
if (jj_scan_token(RETURN)) {
return true;
}
Token xsp;
xsp = jj_scanpos;
if (jj_3R_195()) {
jj_scanpos = xsp;
}
return jj_scan_token(SEMICOLON);
}
private boolean jj_3R_56() {
return jj_3R_40();
}
private boolean jj_3R_55() {
return jj_3R_100();
}
private boolean jj_3R_31() {
Token xsp;
xsp = jj_scanpos;
if (jj_3R_55()) {
jj_scanpos = xsp;
if (jj_3R_56()) {
return true;
}
}
return false;
}
private boolean jj_3R_124() {
if (jj_scan_token(CONTINUE)) {
return true;
}
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(70)) {
jj_scanpos = xsp;
}
return jj_scan_token(SEMICOLON);
}
private boolean jj_3R_123() {
if (jj_scan_token(BREAK)) {
return true;
}
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(70)) {
jj_scanpos = xsp;
}
return jj_scan_token(SEMICOLON);
}
private boolean jj_3R_142() {
return jj_scan_token(INTEGER_LITERAL);
}
private boolean jj_3R_133() {
Token xsp;
xsp = jj_scanpos;
if (jj_3R_142()) {
jj_scanpos = xsp;
if (jj_3R_143()) {
jj_scanpos = xsp;
if (jj_3R_144()) {
jj_scanpos = xsp;
if (jj_3R_145()) {
jj_scanpos = xsp;
if (jj_3R_146()) {
jj_scanpos = xsp;
if (jj_3R_147()) {
jj_scanpos = xsp;
if (jj_3R_148()) {
jj_scanpos = xsp;
if (jj_3R_149()) {
return true;
}
}
}
}
}
}
}
}
return false;
}
private boolean jj_3R_151() {
return jj_3R_72();
}
private boolean jj_3R_183() {
if (jj_scan_token(IDENTIFIER)) {
return true;
}
Token xsp;
xsp = jj_scanpos;
if (jj_3R_187()) {
jj_scanpos = xsp;
}
return false;
}
private boolean jj_3R_202() {
return jj_3R_212();
}
private boolean jj_3R_182() {
return jj_3R_59();
}
private boolean jj_3R_108() {
return jj_3R_133();
}
private boolean jj_3R_212() {
if (jj_3R_116()) {
return true;
}
Token xsp;
while (true) {
xsp = jj_scanpos;
if (jj_3R_217()) {
jj_scanpos = xsp;
break;
}
}
return false;
}
private boolean jj_3R_96() {
if (jj_3R_42()) {
return true;
}
if (jj_3R_32()) {
return true;
}
Token xsp;
xsp = jj_scanpos;
if (jj_3R_182()) {
jj_scanpos = xsp;
}
if (jj_3R_183()) {
return true;
}
while (true) {
xsp = jj_scanpos;
if (jj_3R_184()) {
jj_scanpos = xsp;
break;
}
}
return false;
}
private boolean jj_3R_132() {
if (jj_scan_token(IMPORT)) {
return true;
}
if (jj_scan_token(STAR)) {
return true;
}
return jj_scan_token(SEMICOLON);
}
private boolean jj_3R_137() {
if (jj_scan_token(LBRACE)) {
return true;
}
if (jj_3R_40()) {
return true;
}
return jj_scan_token(RBRACE);
}
private boolean jj_3R_136() {
if (jj_scan_token(DOT)) {
return true;
}
if (jj_scan_token(IDENTIFIER)) {
return true;
}
Token xsp;
xsp = jj_scanpos;
if (jj_3R_151()) {
jj_scanpos = xsp;
}
return false;
}
private boolean jj_3_31() {
if (jj_3R_42()) {
return true;
}
if (jj_3R_32()) {
return true;
}
return jj_scan_token(IDENTIFIER);
}
private boolean jj_3_3() {
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(48)) {
jj_scanpos = xsp;
}
if (jj_scan_token(IMPORT)) {
return true;
}
if (jj_3R_29()) {
return true;
}
xsp = jj_scanpos;
if (jj_3R_30()) {
jj_scanpos = xsp;
}
return jj_scan_token(SEMICOLON);
}
private boolean jj_3R_97() {
Token xsp;
xsp = jj_scanpos;
if (jj_3_3()) {
jj_scanpos = xsp;
if (jj_3R_132()) {
return true;
}
}
return false;
}
private boolean jj_3R_135() {
if (jj_scan_token(LBRACKET)) {
return true;
}
if (jj_3R_40()) {
return true;
}
return jj_scan_token(RBRACKET);
}
private boolean jj_3R_98() {
if (jj_scan_token(PACKAGE)) {
return true;
}
return jj_3R_29();
}
private boolean jj_3_2() {
if (jj_scan_token(IDENTIFIER)) {
return true;
}
return jj_scan_token(LPAREN);
}
private boolean jj_3R_211() {
return jj_3R_212();
}
private boolean jj_3R_181() {
return jj_3R_39();
}
private boolean jj_3_16() {
if (jj_scan_token(DOT)) {
return true;
}
return jj_scan_token(CLASS);
}
private boolean jj_3R_107() {
Token xsp;
xsp = jj_scanpos;
if (jj_3_16()) {
jj_scanpos = xsp;
if (jj_3R_135()) {
jj_scanpos = xsp;
if (jj_3R_136()) {
jj_scanpos = xsp;
if (jj_3R_137()) {
return true;
}
}
}
}
return false;
}
private boolean jj_3R_180() {
if (jj_scan_token(THROWS)) {
return true;
}
return jj_3R_79();
}
private boolean jj_3R_210() {
return jj_3R_96();
}
private boolean jj_3R_201() {
Token xsp;
xsp = jj_scanpos;
if (jj_3R_210()) {
jj_scanpos = xsp;
if (jj_3R_211()) {
return true;
}
}
return false;
}
private boolean jj_3_15() {
if (jj_3R_32()) {
return true;
}
if (jj_scan_token(DOT)) {
return true;
}
return jj_scan_token(CLASS);
}
private boolean jj_3_14() {
return jj_3R_38();
}
private boolean jj_3R_130() {
return jj_scan_token(IDENTIFIER);
}
private boolean jj_3R_141() {
if (jj_scan_token(FOR)) {
return true;
}
if (jj_scan_token(LPAREN)) {
return true;
}
if (jj_3R_32()) {
return true;
}
if (jj_scan_token(IDENTIFIER)) {
return true;
}
if (jj_scan_token(COLON)) {
return true;
}
if (jj_3R_40()) {
return true;
}
if (jj_scan_token(RPAREN)) {
return true;
}
return jj_3R_47();
}
private boolean jj_3R_131() {
if (jj_3R_43()) {
return true;
}
return jj_scan_token(IDENTIFIER);
}
private boolean jj_3R_95() {
if (jj_3R_42()) {
return true;
}
Token xsp;
xsp = jj_scanpos;
if (jj_3R_130()) {
jj_scanpos = xsp;
if (jj_3R_131()) {
return true;
}
}
if (jj_3R_44()) {
return true;
}
xsp = jj_scanpos;
if (jj_3R_180()) {
jj_scanpos = xsp;
}
xsp = jj_scanpos;
if (jj_3R_181()) {
jj_scanpos = xsp;
if (jj_scan_token(79)) {
return true;
}
}
return false;
}
private boolean jj_3R_191() {
if (jj_scan_token(ELSE)) {
return true;
}
return jj_3R_47();
}
private boolean jj_3R_106() {
return jj_3R_29();
}
private boolean jj_3_30() {
if (jj_scan_token(FOR)) {
return true;
}
if (jj_scan_token(LPAREN)) {
return true;
}
if (jj_scan_token(IDENTIFIER)) {
return true;
}
if (jj_scan_token(COLON)) {
return true;
}
if (jj_3R_40()) {
return true;
}
if (jj_scan_token(RPAREN)) {
return true;
}
return jj_3R_47();
}
private boolean jj_3R_122() {
Token xsp;
xsp = jj_scanpos;
if (jj_3_30()) {
jj_scanpos = xsp;
if (jj_3R_141()) {
return true;
}
}
return false;
}
private boolean jj_3R_105() {
return jj_3R_32();
}
private boolean jj_3R_192() {
return jj_3R_201();
}
private boolean jj_3R_61() {
return jj_3R_107();
}
private boolean jj_3R_129() {
return jj_scan_token(INTERFACE);
}
private boolean jj_3R_104() {
return jj_3R_38();
}
private boolean jj_3R_194() {
return jj_3R_202();
}
private boolean jj_3R_193() {
return jj_3R_40();
}
private boolean jj_3R_103() {
return jj_3R_134();
}
private boolean jj_3R_102() {
if (jj_scan_token(LPAREN)) {
return true;
}
if (jj_3R_40()) {
return true;
}
return jj_scan_token(RPAREN);
}
private boolean jj_3R_179() {
if (jj_scan_token(IMPLEMENTS)) {
return true;
}
return jj_3R_79();
}
private boolean jj_3R_60() {
Token xsp;
xsp = jj_scanpos;
if (jj_3R_101()) {
jj_scanpos = xsp;
if (jj_3R_102()) {
jj_scanpos = xsp;
if (jj_3R_103()) {
jj_scanpos = xsp;
if (jj_3R_104()) {
jj_scanpos = xsp;
if (jj_3R_105()) {
jj_scanpos = xsp;
if (jj_3R_106()) {
return true;
}
}
}
}
}
}
return false;
}
private boolean jj_3R_101() {
return jj_3R_133();
}
private boolean jj_3R_178() {
if (jj_scan_token(EXTENDS)) {
return true;
}
return jj_3R_29();
}
private boolean jj_3R_38() {
if (jj_3R_29()) {
return true;
}
return jj_3R_72();
}
private boolean jj_3R_121() {
if (jj_scan_token(FOR)) {
return true;
}
if (jj_scan_token(LPAREN)) {
return true;
}
Token xsp;
xsp = jj_scanpos;
if (jj_3R_192()) {
jj_scanpos = xsp;
}
if (jj_scan_token(SEMICOLON)) {
return true;
}
xsp = jj_scanpos;
if (jj_3R_193()) {
jj_scanpos = xsp;
}
if (jj_scan_token(SEMICOLON)) {
return true;
}
xsp = jj_scanpos;
if (jj_3R_194()) {
jj_scanpos = xsp;
}
if (jj_scan_token(RPAREN)) {
return true;
}
return jj_3R_47();
}
private boolean jj_3R_94() {
if (jj_3R_42()) {
return true;
}
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(13)) {
jj_scanpos = xsp;
if (jj_3R_129()) {
return true;
}
}
if (jj_scan_token(IDENTIFIER)) {
return true;
}
xsp = jj_scanpos;
if (jj_3R_178()) {
jj_scanpos = xsp;
}
xsp = jj_scanpos;
if (jj_3R_179()) {
jj_scanpos = xsp;
}
return jj_3R_39();
}
private boolean jj_3_13() {
if (jj_scan_token(LPAREN)) {
return true;
}
return jj_3R_37();
}
private boolean jj_3R_34() {
if (jj_3R_60()) {
return true;
}
Token xsp;
while (true) {
xsp = jj_scanpos;
if (jj_3R_61()) {
jj_scanpos = xsp;
break;
}
}
return false;
}
private boolean jj_3R_120() {
if (jj_scan_token(DO)) {
return true;
}
if (jj_3R_47()) {
return true;
}
if (jj_scan_token(WHILE)) {
return true;
}
if (jj_scan_token(LPAREN)) {
return true;
}
if (jj_3R_40()) {
return true;
}
if (jj_scan_token(RPAREN)) {
return true;
}
return jj_scan_token(SEMICOLON);
}
private boolean jj_3R_224() {
if (jj_scan_token(LPAREN)) {
return true;
}
if (jj_3R_32()) {
return true;
}
if (jj_scan_token(RPAREN)) {
return true;
}
return jj_3R_215();
}
private boolean jj_3R_223() {
if (jj_scan_token(LPAREN)) {
return true;
}
if (jj_3R_32()) {
return true;
}
if (jj_scan_token(RPAREN)) {
return true;
}
return jj_3R_198();
}
private boolean jj_3R_221() {
Token xsp;
xsp = jj_scanpos;
if (jj_3R_223()) {
jj_scanpos = xsp;
if (jj_3R_224()) {
return true;
}
}
return false;
}
private boolean jj_3_12() {
if (jj_3R_34()) {
return true;
}
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(101)) {
jj_scanpos = xsp;
if (jj_scan_token(102)) {
return true;
}
}
return false;
}
private boolean jj_3R_119() {
if (jj_scan_token(WHILE)) {
return true;
}
if (jj_scan_token(LPAREN)) {
return true;
}
if (jj_3R_40()) {
return true;
}
if (jj_scan_token(RPAREN)) {
return true;
}
return jj_3R_47();
}
private boolean jj_3R_226() {
return jj_3R_34();
}
private boolean jj_3_11() {
if (jj_scan_token(LPAREN)) {
return true;
}
if (jj_3R_29()) {
return true;
}
return jj_scan_token(LBRACKET);
}
private boolean jj_3_29() {
return jj_3R_28();
}
private boolean jj_3R_118() {
if (jj_scan_token(IF)) {
return true;
}
if (jj_scan_token(LPAREN)) {
return true;
}
if (jj_3R_40()) {
return true;
}
if (jj_scan_token(RPAREN)) {
return true;
}
if (jj_3R_47()) {
return true;
}
Token xsp;
xsp = jj_scanpos;
if (jj_3R_191()) {
jj_scanpos = xsp;
}
return false;
}
private boolean jj_3R_225() {
if (jj_3R_34()) {
return true;
}
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(101)) {
jj_scanpos = xsp;
if (jj_scan_token(102)) {
return true;
}
}
return false;
}
private boolean jj_3R_222() {
Token xsp;
xsp = jj_scanpos;
if (jj_3R_225()) {
jj_scanpos = xsp;
if (jj_3R_226()) {
return true;
}
}
return false;
}
private boolean jj_3R_75() {
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(43)) {
jj_scanpos = xsp;
if (jj_scan_token(44)) {
jj_scanpos = xsp;
if (jj_scan_token(45)) {
jj_scanpos = xsp;
if (jj_scan_token(51)) {
jj_scanpos = xsp;
if (jj_scan_token(27)) {
jj_scanpos = xsp;
if (jj_scan_token(39)) {
jj_scanpos = xsp;
if (jj_scan_token(52)) {
jj_scanpos = xsp;
if (jj_scan_token(58)) {
jj_scanpos = xsp;
if (jj_scan_token(10)) {
jj_scanpos = xsp;
if (jj_scan_token(48)) {
jj_scanpos = xsp;
if (jj_scan_token(49)) {
return true;
}
}
}
}
}
}
}
}
}
}
}
return false;
}
private boolean jj_3R_63() {
if (jj_scan_token(LPAREN)) {
return true;
}
if (jj_3R_29()) {
return true;
}
if (jj_scan_token(RPAREN)) {
return true;
}
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(88)) {
jj_scanpos = xsp;
if (jj_scan_token(87)) {
jj_scanpos = xsp;
if (jj_scan_token(73)) {
jj_scanpos = xsp;
if (jj_scan_token(70)) {
jj_scanpos = xsp;
if (jj_scan_token(40)) {
jj_scanpos = xsp;
if (jj_3R_108()) {
return true;
}
}
}
}
}
}
return false;
}
private boolean jj_3R_209() {
if (jj_scan_token(_DEFAULT)) {
return true;
}
return jj_scan_token(COLON);
}
private boolean jj_3R_62() {
if (jj_scan_token(LPAREN)) {
return true;
}
if (jj_3R_29()) {
return true;
}
if (jj_scan_token(LBRACKET)) {
return true;
}
return jj_scan_token(RBRACKET);
}
private boolean jj_3_9() {
return jj_3R_36();
}
private boolean jj_3R_208() {
if (jj_scan_token(CASE)) {
return true;
}
if (jj_3R_40()) {
return true;
}
return jj_scan_token(COLON);
}
private boolean jj_3R_200() {
Token xsp;
xsp = jj_scanpos;
if (jj_3R_208()) {
jj_scanpos = xsp;
if (jj_3R_209()) {
return true;
}
}
return false;
}
private boolean jj_3R_42() {
Token xsp;
while (true) {
xsp = jj_scanpos;
if (jj_3R_75()) {
jj_scanpos = xsp;
break;
}
}
return false;
}
private boolean jj_3R_36() {
Token xsp;
xsp = jj_scanpos;
if (jj_3_10()) {
jj_scanpos = xsp;
if (jj_3R_62()) {
jj_scanpos = xsp;
if (jj_3R_63()) {
return true;
}
}
}
return false;
}
private boolean jj_3_10() {
if (jj_scan_token(LPAREN)) {
return true;
}
return jj_3R_37();
}
private boolean jj_3R_190() {
if (jj_3R_200()) {
return true;
}
Token xsp;
while (true) {
xsp = jj_scanpos;
if (jj_3_29()) {
jj_scanpos = xsp;
break;
}
}
return false;
}
private boolean jj_3R_220() {
return jj_3R_222();
}
private boolean jj_3R_117() {
if (jj_scan_token(SWITCH)) {
return true;
}
if (jj_scan_token(LPAREN)) {
return true;
}
if (jj_3R_40()) {
return true;
}
if (jj_scan_token(RPAREN)) {
return true;
}
if (jj_scan_token(LBRACE)) {
return true;
}
Token xsp;
while (true) {
xsp = jj_scanpos;
if (jj_3R_190()) {
jj_scanpos = xsp;
break;
}
}
return jj_scan_token(RBRACE);
}
private boolean jj_3R_219() {
return jj_3R_221();
}
private boolean jj_3R_218() {
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(88)) {
jj_scanpos = xsp;
if (jj_scan_token(87)) {
return true;
}
}
return jj_3R_198();
}
private boolean jj_3R_215() {
Token xsp;
xsp = jj_scanpos;
if (jj_3R_218()) {
jj_scanpos = xsp;
if (jj_3R_219()) {
jj_scanpos = xsp;
if (jj_3R_220()) {
return true;
}
}
}
return false;
}
private boolean jj_3R_46() {
return jj_3R_59();
}
private boolean jj_3R_214() {
if (jj_scan_token(DECR)) {
return true;
}
return jj_3R_34();
}
private boolean jj_3_1() {
return jj_3R_28();
}
private boolean jj_3R_216() {
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(105)) {
jj_scanpos = xsp;
if (jj_scan_token(106)) {
jj_scanpos = xsp;
if (jj_scan_token(112)) {
return true;
}
}
}
return jj_3R_198();
}
private boolean jj_3R_213() {
if (jj_scan_token(INCR)) {
return true;
}
return jj_3R_34();
}
private boolean jj_3R_45() {
if (jj_scan_token(THROWS)) {
return true;
}
return jj_3R_79();
}
private boolean jj_3R_116() {
return jj_3R_40();
}
private boolean jj_3R_206() {
return jj_3R_215();
}
private boolean jj_3R_205() {
return jj_3R_214();
}
private boolean jj_3R_204() {
return jj_3R_213();
}
private boolean jj_3R_203() {
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(103)) {
jj_scanpos = xsp;
if (jj_scan_token(104)) {
return true;
}
}
return jj_3R_198();
}
private boolean jj_3R_198() {
Token xsp;
xsp = jj_scanpos;
if (jj_3R_203()) {
jj_scanpos = xsp;
if (jj_3R_204()) {
jj_scanpos = xsp;
if (jj_3R_205()) {
jj_scanpos = xsp;
if (jj_3R_206()) {
return true;
}
}
}
}
return false;
}
private boolean jj_3R_99() {
return jj_scan_token(FORMAL_COMMENT);
}
private boolean jj_3R_188() {
if (jj_3R_198()) {
return true;
}
Token xsp;
while (true) {
xsp = jj_scanpos;
if (jj_3R_216()) {
jj_scanpos = xsp;
break;
}
}
return false;
}
private boolean jj_3R_207() {
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(103)) {
jj_scanpos = xsp;
if (jj_scan_token(104)) {
return true;
}
}
return jj_3R_188();
}
private boolean jj_3R_185() {
if (jj_3R_188()) {
return true;
}
Token xsp;
while (true) {
xsp = jj_scanpos;
if (jj_3R_207()) {
jj_scanpos = xsp;
break;
}
}
return false;
}
private boolean jj_3R_54() {
return jj_3R_99();
}
private boolean jj_3_27() {
if (jj_3R_42()) {
return true;
}
if (jj_3R_32()) {
return true;
}
Token xsp;
xsp = jj_scanpos;
if (jj_3R_46()) {
jj_scanpos = xsp;
}
return jj_scan_token(IDENTIFIER);
}
private boolean jj_3R_53() {
return jj_3R_98();
}
private boolean jj_3R_199() {
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(113)) {
jj_scanpos = xsp;
if (jj_scan_token(114)) {
jj_scanpos = xsp;
if (jj_scan_token(115)) {
jj_scanpos = xsp;
if (jj_scan_token(116)) {
jj_scanpos = xsp;
if (jj_scan_token(117)) {
jj_scanpos = xsp;
if (jj_scan_token(118)) {
return true;
}
}
}
}
}
}
return jj_3R_185();
}
private boolean jj_3R_52() {
return jj_3R_97();
}
private boolean jj_3_26() {
if (jj_3R_42()) {
return true;
}
if (jj_scan_token(IDENTIFIER)) {
return true;
}
if (jj_3R_44()) {
return true;
}
Token xsp;
xsp = jj_scanpos;
if (jj_3R_45()) {
jj_scanpos = xsp;
}
return jj_scan_token(LBRACE);
}
private boolean jj_3R_177() {
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(91)) {
jj_scanpos = xsp;
if (jj_scan_token(96)) {
return true;
}
}
return jj_3R_172();
}
private boolean jj_3R_176() {
if (jj_3R_185()) {
return true;
}
Token xsp;
while (true) {
xsp = jj_scanpos;
if (jj_3R_199()) {
jj_scanpos = xsp;
break;
}
}
return false;
}
private boolean jj_3_28() {
return jj_3R_47();
}
private boolean jj_3_25() {
if (jj_3R_42()) {
return true;
}
if (jj_3R_43()) {
return true;
}
if (jj_scan_token(IDENTIFIER)) {
return true;
}
return jj_scan_token(LPAREN);
}
private boolean jj_3R_51() {
if (jj_3R_96()) {
return true;
}
return jj_scan_token(SEMICOLON);
}
private boolean jj_3R_189() {
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(85)) {
jj_scanpos = xsp;
if (jj_scan_token(86)) {
jj_scanpos = xsp;
if (jj_scan_token(83)) {
jj_scanpos = xsp;
if (jj_scan_token(84)) {
jj_scanpos = xsp;
if (jj_scan_token(92)) {
jj_scanpos = xsp;
if (jj_scan_token(93)) {
jj_scanpos = xsp;
if (jj_scan_token(94)) {
jj_scanpos = xsp;
if (jj_scan_token(95)) {
return true;
}
}
}
}
}
}
}
}
return jj_3R_176();
}
private boolean jj_3_24() {
if (jj_3R_42()) {
return true;
}
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(13)) {
jj_scanpos = xsp;
if (jj_scan_token(37)) {
return true;
}
}
return false;
}
private boolean jj_3R_174() {
if (jj_3R_176()) {
return true;
}
Token xsp;
while (true) {
xsp = jj_scanpos;
if (jj_3R_189()) {
jj_scanpos = xsp;
break;
}
}
return false;
}
private boolean jj_3R_50() {
return jj_3R_95();
}
private boolean jj_3R_186() {
if (jj_scan_token(INSTANCEOF)) {
return true;
}
return jj_3R_32();
}
private boolean jj_3R_49() {
return jj_3R_95();
}
private boolean jj_3R_172() {
if (jj_3R_174()) {
return true;
}
Token xsp;
xsp = jj_scanpos;
if (jj_3R_186()) {
jj_scanpos = xsp;
}
return false;
}
private boolean jj_3R_48() {
return jj_3R_94();
}
private boolean jj_3R_28() {
Token xsp;
xsp = jj_scanpos;
if (jj_3R_48()) {
jj_scanpos = xsp;
if (jj_3R_49()) {
jj_scanpos = xsp;
if (jj_3R_50()) {
jj_scanpos = xsp;
if (jj_3R_51()) {
jj_scanpos = xsp;
if (jj_3_28()) {
jj_scanpos = xsp;
if (jj_3R_52()) {
jj_scanpos = xsp;
if (jj_3R_53()) {
jj_scanpos = xsp;
if (jj_3R_54()) {
return true;
}
}
}
}
}
}
}
}
return false;
}
private boolean jj_3_23() {
return jj_3R_28();
}
private boolean jj_3R_173() {
if (jj_scan_token(XOR)) {
return true;
}
return jj_3R_167();
}
private boolean jj_3R_170() {
if (jj_3R_172()) {
return true;
}
Token xsp;
while (true) {
xsp = jj_scanpos;
if (jj_3R_177()) {
jj_scanpos = xsp;
break;
}
}
return false;
}
private boolean jj_3R_39() {
if (jj_scan_token(LBRACE)) {
return true;
}
Token xsp;
while (true) {
xsp = jj_scanpos;
if (jj_3_23()) {
jj_scanpos = xsp;
break;
}
}
return jj_scan_token(RBRACE);
}
private boolean jj_3R_175() {
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(107)) {
jj_scanpos = xsp;
if (jj_scan_token(108)) {
return true;
}
}
return jj_3R_170();
}
private boolean jj_3R_41() {
if (jj_scan_token(IDENTIFIER)) {
return true;
}
if (jj_scan_token(COLON)) {
return true;
}
return jj_3R_47();
}
private boolean jj_3R_167() {
if (jj_3R_170()) {
return true;
}
Token xsp;
while (true) {
xsp = jj_scanpos;
if (jj_3R_175()) {
jj_scanpos = xsp;
break;
}
}
return false;
}
private boolean jj_3R_93() {
return jj_3R_128();
}
private boolean jj_3R_92() {
return jj_3R_127();
}
private boolean jj_3R_164() {
if (jj_3R_167()) {
return true;
}
Token xsp;
while (true) {
xsp = jj_scanpos;
if (jj_3R_173()) {
jj_scanpos = xsp;
break;
}
}
return false;
}
private boolean jj_3R_91() {
return jj_3R_126();
}
private boolean jj_3R_90() {
return jj_3R_125();
}
private boolean jj_3R_162() {
if (jj_scan_token(HOOK)) {
return true;
}
if (jj_3R_40()) {
return true;
}
if (jj_scan_token(COLON)) {
return true;
}
return jj_3R_111();
}
private boolean jj_3R_89() {
return jj_3R_124();
}
private boolean jj_3R_171() {
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(109)) {
jj_scanpos = xsp;
if (jj_scan_token(110)) {
return true;
}
}
return jj_3R_164();
}
private boolean jj_3R_88() {
return jj_3R_123();
}
private boolean jj_3R_159() {
if (jj_3R_164()) {
return true;
}
Token xsp;
while (true) {
xsp = jj_scanpos;
if (jj_3R_171()) {
jj_scanpos = xsp;
break;
}
}
return false;
}
private boolean jj_3R_87() {
return jj_3R_122();
}
private boolean jj_3R_86() {
return jj_3R_121();
}
private boolean jj_3R_85() {
return jj_3R_120();
}
private boolean jj_3R_168() {
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(99)) {
jj_scanpos = xsp;
if (jj_scan_token(100)) {
return true;
}
}
return jj_3R_159();
}
private boolean jj_3R_84() {
return jj_3R_119();
}
private boolean jj_3R_153() {
if (jj_3R_159()) {
return true;
}
Token xsp;
while (true) {
xsp = jj_scanpos;
if (jj_3R_168()) {
jj_scanpos = xsp;
break;
}
}
return false;
}
private boolean jj_3R_83() {
return jj_3R_118();
}
private boolean jj_3R_82() {
return jj_3R_117();
}
private boolean jj_3R_81() {
if (jj_3R_116()) {
return true;
}
return jj_scan_token(SEMICOLON);
}
private boolean jj_3R_165() {
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(97)) {
jj_scanpos = xsp;
if (jj_scan_token(98)) {
return true;
}
}
return jj_3R_153();
}
private boolean jj_3_17() {
return jj_3R_39();
}
private boolean jj_3R_80() {
return jj_3R_39();
}
private boolean jj_3R_139() {
if (jj_3R_153()) {
return true;
}
Token xsp;
while (true) {
xsp = jj_scanpos;
if (jj_3R_165()) {
jj_scanpos = xsp;
break;
}
}
return false;
}
private boolean jj_3R_47() {
Token xsp;
xsp = jj_scanpos;
if (jj_3_22()) {
jj_scanpos = xsp;
if (jj_3R_80()) {
jj_scanpos = xsp;
if (jj_scan_token(79)) {
jj_scanpos = xsp;
if (jj_3R_81()) {
jj_scanpos = xsp;
if (jj_3R_82()) {
jj_scanpos = xsp;
if (jj_3R_83()) {
jj_scanpos = xsp;
if (jj_3R_84()) {
jj_scanpos = xsp;
if (jj_3R_85()) {
jj_scanpos = xsp;
lookingAhead = true;
jj_semLA = isRegularForStatement();
lookingAhead = false;
if (!jj_semLA || jj_3R_86()) {
jj_scanpos = xsp;
if (jj_3R_87()) {
jj_scanpos = xsp;
if (jj_3R_88()) {
jj_scanpos = xsp;
if (jj_3R_89()) {
jj_scanpos = xsp;
if (jj_3R_90()) {
jj_scanpos = xsp;
if (jj_3R_91()) {
jj_scanpos = xsp;
if (jj_3R_92()) {
jj_scanpos = xsp;
if (jj_3R_93()) {
return true;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
return false;
}
private boolean jj_3_22() {
return jj_3R_41();
}
private boolean jj_3R_156() {
return jj_3R_59();
}
private boolean jj_3R_111() {
if (jj_3R_139()) {
return true;
}
Token xsp;
xsp = jj_scanpos;
if (jj_3R_162()) {
jj_scanpos = xsp;
}
return false;
}
private boolean jj_3R_166() {
if (jj_scan_token(LBRACKET)) {
return true;
}
return jj_scan_token(RBRACKET);
}
private boolean jj_3R_158() {
if (jj_3R_72()) {
return true;
}
Token xsp;
xsp = jj_scanpos;
if (jj_3_17()) {
jj_scanpos = xsp;
}
return false;
}
private boolean jj_3R_163() {
Token xsp;
if (jj_3R_166()) {
return true;
}
while (true) {
xsp = jj_scanpos;
if (jj_3R_166()) {
jj_scanpos = xsp;
break;
}
}
return jj_3R_100();
}
private boolean jj_3_20() {
if (jj_scan_token(LBRACKET)) {
return true;
}
return jj_scan_token(RBRACKET);
}
private boolean jj_3R_157() {
return jj_3R_155();
}
private boolean jj_3_19() {
if (jj_scan_token(LBRACKET)) {
return true;
}
if (jj_3R_40()) {
return true;
}
return jj_scan_token(RBRACKET);
}
private boolean jj_3R_35() {
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(82)) {
jj_scanpos = xsp;
if (jj_scan_token(121)) {
jj_scanpos = xsp;
if (jj_scan_token(122)) {
jj_scanpos = xsp;
if (jj_scan_token(128)) {
jj_scanpos = xsp;
if (jj_scan_token(119)) {
jj_scanpos = xsp;
if (jj_scan_token(120)) {
jj_scanpos = xsp;
if (jj_scan_token(123)) {
jj_scanpos = xsp;
if (jj_scan_token(127)) {
jj_scanpos = xsp;
if (jj_scan_token(125)) {
jj_scanpos = xsp;
if (jj_scan_token(129)) {
jj_scanpos = xsp;
if (jj_scan_token(130)) {
jj_scanpos = xsp;
if (jj_scan_token(131)) {
jj_scanpos = xsp;
if (jj_scan_token(132)) {
jj_scanpos = xsp;
if (jj_scan_token(133)) {
jj_scanpos = xsp;
if (jj_scan_token(134)) {
return true;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
return false;
}
private boolean jj_3_21() {
Token xsp;
if (jj_3_19()) {
return true;
}
while (true) {
xsp = jj_scanpos;
if (jj_3_19()) {
jj_scanpos = xsp;
break;
}
}
while (true) {
xsp = jj_scanpos;
if (jj_3_20()) {
jj_scanpos = xsp;
break;
}
}
return false;
}
private boolean jj_3R_155() {
Token xsp;
xsp = jj_scanpos;
if (jj_3_21()) {
jj_scanpos = xsp;
if (jj_3R_163()) {
return true;
}
}
return false;
}
private boolean jj_3R_115() {
if (jj_scan_token(COMMA)) {
return true;
}
return jj_3R_29();
}
public ParserTokenManager token_source;
JavaCharStream jj_input_stream;
public Token token, jj_nt;
private int jj_ntk;
private Token jj_scanpos, jj_lastpos;
private int jj_la;
public boolean lookingAhead = false;
private boolean jj_semLA;
public Parser(java.io.InputStream stream) {
jj_input_stream = new JavaCharStream(stream, 1, 1);
token_source = new ParserTokenManager(jj_input_stream);
token = new Token();
jj_ntk = -1;
}
public void ReInit(java.io.InputStream stream) {
jj_input_stream.ReInit(stream, 1, 1);
token_source.ReInit(jj_input_stream);
token = new Token();
jj_ntk = -1;
jjtree.reset();
}
public Parser(java.io.Reader stream) {
jj_input_stream = new JavaCharStream(stream, 1, 1);
token_source = new ParserTokenManager(jj_input_stream);
token = new Token();
jj_ntk = -1;
}
public void ReInit(java.io.Reader stream) {
jj_input_stream.ReInit(stream, 1, 1);
token_source.ReInit(jj_input_stream);
token = new Token();
jj_ntk = -1;
jjtree.reset();
}
public Parser(ParserTokenManager tm) {
token_source = tm;
token = new Token();
jj_ntk = -1;
}
public void ReInit(ParserTokenManager tm) {
token_source = tm;
token = new Token();
jj_ntk = -1;
jjtree.reset();
}
private Token jj_consume_token(int kind) throws ParseException {
Token oldToken;
if ((oldToken = token).next != null) {
token = token.next;
} else {
token = token.next = token_source.getNextToken();
}
jj_ntk = -1;
if (token.kind == kind) {
return token;
}
token = oldToken;
throw generateParseException();
}
private static class LookaheadSuccess extends java.lang.Error {
}
final private LookaheadSuccess jj_ls = new LookaheadSuccess();
private boolean jj_scan_token(int kind) {
if (jj_scanpos == jj_lastpos) {
jj_la--;
if (jj_scanpos.next == null) {
jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken();
} else {
jj_lastpos = jj_scanpos = jj_scanpos.next;
}
} else {
jj_scanpos = jj_scanpos.next;
}
if (jj_scanpos.kind != kind) {
return true;
}
if (jj_la == 0 && jj_scanpos == jj_lastpos) {
throw jj_ls;
}
return false;
}
public Token getNextToken() {
if (token.next != null) {
token = token.next;
} else {
token = token.next = token_source.getNextToken();
}
jj_ntk = -1;
return token;
}
public Token getToken(int index) {
Token t = lookingAhead ? jj_scanpos : token;
for (int i = 0; i < index; i++) {
if (t.next != null) {
t = t.next;
} else {
t = t.next = token_source.getNextToken();
}
}
return t;
}
private int jj_ntk() {
if ((jj_nt = token.next) == null) {
return (jj_ntk = (token.next = token_source.getNextToken()).kind);
} else {
return (jj_ntk = jj_nt.kind);
}
}
public ParseException generateParseException() {
Token errortok = token.next;
int line = errortok.beginLine, column = errortok.beginColumn;
String mess = (errortok.kind == 0) ? tokenImage[0] : errortok.image;
return new ParseException("Parse error at line " + line + ", column " + column + ". Encountered: " + mess);
}
public void enable_tracing() {
}
public void disable_tracing() {
}
}
| 201,872 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
GeneratedClass.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/GeneratedClass.java | package ehacks.bsh;
/**
* Marker interface for generated classes
*/
public interface GeneratedClass {
}
| 108 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
Edge.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/Edge.java | /** *
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (C) 2000 INRIA, France Telecom
* Copyright (C) 2002 France Telecom
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact: [email protected]
*
* Author: Eric Bruneton
*/
package ehacks.bsh;
/**
* An edge in the control flow graph of a method body. See {@link Label Label}.
*/
class Edge {
/**
* The (relative) stack size in the basic block from which this edge
* originates. This size is equal to the stack size at the "jump"
* instruction to which this edge corresponds, relatively to the stack size
* at the beginning of the originating basic block.
*/
int stackSize;
/**
* The successor block of the basic block from which this edge originates.
*/
Label successor;
/**
* The next edge in the list of successors of the originating basic block.
* See {@link Label#successors successors}.
*/
Edge next;
/**
* The next available edge in the pool. See {@link CodeWriter#pool pool}.
*/
Edge poolNext;
}
| 1,802 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
Item.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/Item.java | /** *
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (C) 2000 INRIA, France Telecom
* Copyright (C) 2002 France Telecom
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact: [email protected]
*
* Author: Eric Bruneton
*/
package ehacks.bsh;
/**
* A constant pool item. Constant pool items can be created with the 'newXXX'
* methods in the {@link ClassWriter} class.
*/
class Item {
/**
* Index of this item in the constant pool.
*/
short index;
/**
* Type of this constant pool item. A single class is used to represent all
* constant pool item types, in order to minimize the bytecode size of this
* package. The value of this field is one of the constants defined in the
* {@link ClassWriter ClassWriter} class.
*/
int type;
/**
* Value of this item, for a {@link ClassWriter#INT INT} item.
*/
int intVal;
/**
* Value of this item, for a {@link ClassWriter#LONG LONG} item.
*/
long longVal;
/**
* Value of this item, for a {@link ClassWriter#FLOAT FLOAT} item.
*/
float floatVal;
/**
* Value of this item, for a {@link ClassWriter#DOUBLE DOUBLE} item.
*/
double doubleVal;
/**
* First part of the value of this item, for items that do not hold a
* primitive value.
*/
String strVal1;
/**
* Second part of the value of this item, for items that do not hold a
* primitive value.
*/
String strVal2;
/**
* Third part of the value of this item, for items that do not hold a
* primitive value.
*/
String strVal3;
/**
* The hash code value of this constant pool item.
*/
int hashCode;
/**
* Link to another constant pool item, used for collision lists in the
* constant pool's hash table.
*/
Item next;
/**
* Constructs an uninitialized {@link Item Item} object.
*/
Item() {
}
/**
* Constructs a copy of the given item.
*
* @param index index of the item to be constructed.
* @param i the item that must be copied into the item to be constructed.
*/
Item(final short index, final Item i) {
this.index = index;
type = i.type;
intVal = i.intVal;
longVal = i.longVal;
floatVal = i.floatVal;
doubleVal = i.doubleVal;
strVal1 = i.strVal1;
strVal2 = i.strVal2;
strVal3 = i.strVal3;
hashCode = i.hashCode;
}
/**
* Sets this item to an {@link ClassWriter#INT INT} item.
*
* @param intVal the value of this item.
*/
void set(final int intVal) {
this.type = ClassWriter.INT;
this.intVal = intVal;
this.hashCode = type + intVal;
}
/**
* Sets this item to a {@link ClassWriter#LONG LONG} item.
*
* @param longVal the value of this item.
*/
void set(final long longVal) {
this.type = ClassWriter.LONG;
this.longVal = longVal;
this.hashCode = type + (int) longVal;
}
/**
* Sets this item to a {@link ClassWriter#FLOAT FLOAT} item.
*
* @param floatVal the value of this item.
*/
void set(final float floatVal) {
this.type = ClassWriter.FLOAT;
this.floatVal = floatVal;
this.hashCode = type + (int) floatVal;
}
/**
* Sets this item to a {@link ClassWriter#DOUBLE DOUBLE} item.
*
* @param doubleVal the value of this item.
*/
void set(final double doubleVal) {
this.type = ClassWriter.DOUBLE;
this.doubleVal = doubleVal;
this.hashCode = type + (int) doubleVal;
}
/**
* Sets this item to an item that do not hold a primitive value.
*
* @param type the type of this item.
* @param strVal1 first part of the value of this item.
* @param strVal2 second part of the value of this item.
* @param strVal3 third part of the value of this item.
*/
void set(
final int type,
final String strVal1,
final String strVal2,
final String strVal3) {
this.type = type;
this.strVal1 = strVal1;
this.strVal2 = strVal2;
this.strVal3 = strVal3;
switch (type) {
case ClassWriter.UTF8:
case ClassWriter.STR:
case ClassWriter.CLASS:
hashCode = type + strVal1.hashCode();
return;
case ClassWriter.NAME_TYPE:
hashCode = type + strVal1.hashCode() * strVal2.hashCode();
return;
//case ClassWriter.FIELD:
//case ClassWriter.METH:
//case ClassWriter.IMETH:
default:
hashCode = type + strVal1.hashCode() * strVal2.hashCode() * strVal3.hashCode();
}
}
/**
* Indicates if the given item is equal to this one.
*
* @param i the item to be compared to this one.
* @return <tt>true</tt> if the given item if equal to this one,
* <tt>false</tt> otherwise.
*/
boolean isEqualTo(final Item i) {
if (i.type == type) {
switch (type) {
case ClassWriter.INT:
return i.intVal == intVal;
case ClassWriter.LONG:
return i.longVal == longVal;
case ClassWriter.FLOAT:
return i.floatVal == floatVal;
case ClassWriter.DOUBLE:
return i.doubleVal == doubleVal;
case ClassWriter.UTF8:
case ClassWriter.STR:
case ClassWriter.CLASS:
return i.strVal1.equals(strVal1);
case ClassWriter.NAME_TYPE:
return i.strVal1.equals(strVal1)
&& i.strVal2.equals(strVal2);
//case ClassWriter.FIELD:
//case ClassWriter.METH:
//case ClassWriter.IMETH:
default:
return i.strVal1.equals(strVal1)
&& i.strVal2.equals(strVal2)
&& i.strVal3.equals(strVal3);
}
}
return false;
}
}
| 6,974 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
Token.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/Token.java | /* Generated By:JavaCC: Do not edit this line. Token.java Version 3.0 */
package ehacks.bsh;
/*
This file has been modified for BeanShell to make Token serializable.
If this file is regenerated please make this change.
All BeanShell modifications are demarcated by "Begin BeanShell
Modification - ... " and "End BeanShell Modification - ..."
*/
/**
* Describes the input token stream.
*/
// Begin BeanShell Modification - serializable
public class Token implements java.io.Serializable {
// End BeanShell Modification - serializable
/**
* An integer that describes the kind of this token. This numbering system
* is determined by JavaCCParser, and a table of these numbers is stored in
* the file ...Constants.java.
*/
public int kind;
/**
* beginLine and beginColumn describe the position of the first character of
* this token; endLine and endColumn describe the position of the last
* character of this token.
*/
public int beginLine, beginColumn, endLine, endColumn;
/**
* The string image of the token.
*/
public String image;
/**
* A reference to the next regular (non-special) token from the input
* stream. If this is the last token from the input stream, or if the token
* manager has not read tokens beyond this one, this field is set to null.
* This is true only if this token is also a regular token. Otherwise, see
* below for a description of the contents of this field.
*/
public Token next;
/**
* This field is used to access special tokens that occur prior to this
* token, but after the immediately preceding regular (non-special) token.
* If there are no such special tokens, this field is set to null. When
* there are more than one such special token, this field refers to the last
* of these special tokens, which in turn refers to the next previous
* special token through its specialToken field, and so on until the first
* special token (whose specialToken field is null). The next fields of
* special tokens refer to other special tokens that immediately follow it
* (without an intervening regular token). If there is no such token, this
* field is null.
*/
public Token specialToken;
/**
* Returns the image.
*/
@Override
public String toString() {
return image;
}
/**
* Returns a new Token object, by default. However, if you want, you can
* create and return subclass objects based on the value of ofKind. Simply
* add the cases to the switch for all those special cases. For example, if
* you have a subclass of Token called IDToken that you want to create if
* ofKind is ID, simlpy add something like :
*
* case MyParserConstants.ID : return new IDToken();
*
* to the following switch statement. Then you can cast matchedToken
* variable to the appropriate type and use it in your lexical actions.
*/
public static Token newToken(int ofKind) {
switch (ofKind) {
default:
return new Token();
}
}
}
| 3,171 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHAmbiguousName.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHAmbiguousName.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
class BSHAmbiguousName extends SimpleNode {
public String text;
BSHAmbiguousName(int id) {
super(id);
}
public Name getName(NameSpace namespace) {
return namespace.getNameResolver(text);
}
public Object toObject(CallStack callstack, Interpreter interpreter)
throws EvalError {
return toObject(callstack, interpreter, false);
}
Object toObject(
CallStack callstack, Interpreter interpreter, boolean forceClass)
throws EvalError {
try {
return getName(callstack.top()).toObject(
callstack, interpreter, forceClass);
} catch (UtilEvalError e) {
throw e.toEvalError(this, callstack);
}
}
public Class toClass(CallStack callstack, Interpreter interpreter)
throws EvalError {
try {
return getName(callstack.top()).toClass();
} catch (ClassNotFoundException e) {
throw new EvalError(e.getMessage(), this, callstack, e);
} catch (UtilEvalError e2) {
// ClassPathException is a type of UtilEvalError
throw e2.toEvalError(this, callstack);
}
}
public LHS toLHS(CallStack callstack, Interpreter interpreter)
throws EvalError {
try {
return getName(callstack.top()).toLHS(callstack, interpreter);
} catch (UtilEvalError e) {
throw e.toEvalError(this, callstack);
}
}
/*
The interpretation of an ambiguous name is context sensitive.
We disallow a generic eval( ).
*/
@Override
public Object eval(CallStack callstack, Interpreter interpreter)
throws EvalError {
throw new InterpreterError(
"Don't know how to eval an ambiguous name!"
+ " Use toObject() if you want an object.");
}
@Override
public String toString() {
return "AmbigousName: " + text;
}
}
| 4,531 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHWhileStatement.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHWhileStatement.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
/**
* This class handles both {@code while} statements and {@code do..while}
* statements.
*/
class BSHWhileStatement extends SimpleNode implements ParserConstants {
/**
* Set by Parser, default {@code false}
*/
boolean isDoStatement;
BSHWhileStatement(int id) {
super(id);
}
@Override
public Object eval(CallStack callstack, Interpreter interpreter) throws EvalError {
int numChild = jjtGetNumChildren();
// Order of body and condition is swapped for do / while
final SimpleNode condExp;
final SimpleNode body;
if (isDoStatement) {
condExp = (SimpleNode) jjtGetChild(1);
body = (SimpleNode) jjtGetChild(0);
} else {
condExp = (SimpleNode) jjtGetChild(0);
if (numChild > 1) {
body = (SimpleNode) jjtGetChild(1);
} else {
body = null;
}
}
boolean doOnceFlag = isDoStatement;
while (doOnceFlag || BSHIfStatement.evaluateCondition(condExp, callstack, interpreter)) {
doOnceFlag = false;
// no body?
if (body == null) {
continue;
}
Object ret = body.eval(callstack, interpreter);
if (ret instanceof ReturnControl) {
switch (((ReturnControl) ret).kind) {
case RETURN:
return ret;
case CONTINUE:
break;
case BREAK:
return Primitive.VOID;
}
}
}
return Primitive.VOID;
}
}
| 4,232 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHReturnStatement.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHReturnStatement.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
class BSHReturnStatement extends SimpleNode implements ParserConstants {
public int kind;
BSHReturnStatement(int id) {
super(id);
}
@Override
public Object eval(CallStack callstack, Interpreter interpreter)
throws EvalError {
Object value;
if (jjtGetNumChildren() > 0) {
value = ((SimpleNode) jjtGetChild(0)).eval(callstack, interpreter);
} else {
value = Primitive.VOID;
}
return new ReturnControl(kind, value, this);
}
}
| 3,087 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BlockNameSpace.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BlockNameSpace.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
/**
* A specialized namespace for Blocks (e.g. the body of a "for" statement). The
* Block acts like a child namespace but only for typed variables declared
* within it (block local scope) or untyped variables explicitly set in it via
* setBlockVariable(). Otherwise variable assignment (including untyped variable
* usage) acts like it is part of the containing block.
* <p>
*/
/*
Note: This class essentially just delegates most of its methods to its
parent. The setVariable() indirection is very small. We could probably
fold this functionality back into the base NameSpace as a special case.
But this has changed a few times so I'd like to leave this abstraction for
now.
*/
class BlockNameSpace extends NameSpace {
public BlockNameSpace(NameSpace parent)
throws EvalError {
super(parent, parent.getName() + "/BlockNameSpace");
}
/**
* Override the standard namespace behavior to make assignments happen in
* our parent (enclosing) namespace, unless the variable has already been
* assigned here via a typed declaration or through the special
* setBlockVariable() (used for untyped args in try/catch).
* <p>
* i.e. only allow typed var declaration to happen in this namespace. Typed
* vars are handled in the ordinary way local scope. All untyped assignments
* are delegated to the enclosing context.
*/
/*
Note: it may see like with the new 1.3 scoping this test could be
removed, but it cannot. When recurse is false we still need to set the
variable in our parent, not here.
*/
@Override
public void setVariable(
String name, Object value, boolean strictJava, boolean recurse)
throws UtilEvalError {
if (weHaveVar(name)) // set the var here in the block namespace
{
super.setVariable(name, value, strictJava, false);
} else // set the var in the enclosing (parent) namespace
{
getParent().setVariable(name, value, strictJava, recurse);
}
}
/**
* Set an untyped variable in the block namespace. The BlockNameSpace would
* normally delegate this set to the parent. Typed variables are naturally
* set locally. This is used in try/catch block argument.
*/
public void setBlockVariable(String name, Object value)
throws UtilEvalError {
super.setVariable(name, value, false/*strict?*/, false);
}
/**
* We have the variable: either it was declared here with a type, giving it
* block local scope or an untyped var was explicitly set here via
* setBlockVariable().
*/
private boolean weHaveVar(String name) {
// super.variables.containsKey( name ) not any faster, I checked
try {
return super.getVariableImpl(name, false) != null;
} catch (UtilEvalError e) {
return false;
}
}
/**
* Get the actual BlockNameSpace 'this' reference.
* <p/>
* Normally a 'this' reference to a BlockNameSpace (e.g. if () { } )
* resolves to the parent namespace (e.g. the namespace containing the "if"
* statement). However when code inside the BlockNameSpace needs to resolve
* things relative to 'this' we must use the actual block's 'this'
* reference. Name.java is smart enough to handle this using getBlockThis().
*
* @see #getThis( Interpreter ) This getBlockThis( Interpreter
* declaringInterpreter ) { return super.getThis( declaringInterpreter ); }
*/
//
// Begin methods which simply delegate to our parent (enclosing scope)
//
/**
* This method recurses to find the nearest non-BlockNameSpace parent.
*
* public NameSpace getParent() { NameSpace parent = super.getParent(); if (
* parent instanceof BlockNameSpace ) return parent.getParent(); else return
* parent; }
*/
/**
* do we need this?
*/
private NameSpace getNonBlockParent() {
NameSpace parent = super.getParent();
if (parent instanceof BlockNameSpace) {
return ((BlockNameSpace) parent).getNonBlockParent();
} else {
return parent;
}
}
/**
* Get a 'this' reference is our parent's 'this' for the object closure.
* e.g. Normally a 'this' reference to a BlockNameSpace (e.g. if () { } )
* resolves to the parent namespace (e.g. the namespace containing the "if"
* statement).
*
* @see #getBlockThis( Interpreter )
*/
@Override
public This getThis(Interpreter declaringInterpreter) {
return getNonBlockParent().getThis(declaringInterpreter);
}
/**
* super is our parent's super
*/
@Override
public This getSuper(Interpreter declaringInterpreter) {
return getNonBlockParent().getSuper(declaringInterpreter);
}
/**
* delegate import to our parent
*/
@Override
public void importClass(String name) {
getParent().importClass(name);
}
/**
* delegate import to our parent
*/
@Override
public void importPackage(String name) {
getParent().importPackage(name);
}
@Override
public void setMethod(BSHMethod method)
throws UtilEvalError {
getParent().setMethod(method);
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone(); //To change body of generated methods, choose Tools | Templates.
}
}
| 8,075 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
ParserConstants.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/ParserConstants.java | /* Generated By:JJTree&JavaCC: Do not edit this line. ParserConstants.java */
package ehacks.bsh;
public interface ParserConstants {
int EOF = 0;
int NONPRINTABLE = 6;
int SINGLE_LINE_COMMENT = 7;
int HASH_BANG_COMMENT = 8;
int MULTI_LINE_COMMENT = 9;
int ABSTRACT = 10;
int BOOLEAN = 11;
int BREAK = 12;
int CLASS = 13;
int BYTE = 14;
int CASE = 15;
int CATCH = 16;
int CHAR = 17;
int CONST = 18;
int CONTINUE = 19;
int _DEFAULT = 20;
int DO = 21;
int DOUBLE = 22;
int ELSE = 23;
int ENUM = 24;
int EXTENDS = 25;
int FALSE = 26;
int FINAL = 27;
int FINALLY = 28;
int FLOAT = 29;
int FOR = 30;
int GOTO = 31;
int IF = 32;
int IMPLEMENTS = 33;
int IMPORT = 34;
int INSTANCEOF = 35;
int INT = 36;
int INTERFACE = 37;
int LONG = 38;
int NATIVE = 39;
int NEW = 40;
int NULL = 41;
int PACKAGE = 42;
int PRIVATE = 43;
int PROTECTED = 44;
int PUBLIC = 45;
int RETURN = 46;
int SHORT = 47;
int STATIC = 48;
int STRICTFP = 49;
int SWITCH = 50;
int SYNCHRONIZED = 51;
int TRANSIENT = 52;
int THROW = 53;
int THROWS = 54;
int TRUE = 55;
int TRY = 56;
int VOID = 57;
int VOLATILE = 58;
int WHILE = 59;
int INTEGER_LITERAL = 60;
int DECIMAL_LITERAL = 61;
int HEX_LITERAL = 62;
int OCTAL_LITERAL = 63;
int FLOATING_POINT_LITERAL = 64;
int EXPONENT = 65;
int CHARACTER_LITERAL = 66;
int STRING_LITERAL = 67;
int LONG_STRING_LITERAL = 68;
int FORMAL_COMMENT = 69;
int IDENTIFIER = 70;
int LETTER = 71;
int DIGIT = 72;
int LPAREN = 73;
int RPAREN = 74;
int LBRACE = 75;
int RBRACE = 76;
int LBRACKET = 77;
int RBRACKET = 78;
int SEMICOLON = 79;
int COMMA = 80;
int DOT = 81;
int ASSIGN = 82;
int GT = 83;
int GTX = 84;
int LT = 85;
int LTX = 86;
int BANG = 87;
int TILDE = 88;
int HOOK = 89;
int COLON = 90;
int EQ = 91;
int LE = 92;
int LEX = 93;
int GE = 94;
int GEX = 95;
int NE = 96;
int BOOL_OR = 97;
int BOOL_ORX = 98;
int BOOL_AND = 99;
int BOOL_ANDX = 100;
int INCR = 101;
int DECR = 102;
int PLUS = 103;
int MINUS = 104;
int STAR = 105;
int SLASH = 106;
int BIT_AND = 107;
int BIT_ANDX = 108;
int BIT_OR = 109;
int BIT_ORX = 110;
int XOR = 111;
int MOD = 112;
int LSHIFT = 113;
int LSHIFTX = 114;
int RSIGNEDSHIFT = 115;
int RSIGNEDSHIFTX = 116;
int RUNSIGNEDSHIFT = 117;
int RUNSIGNEDSHIFTX = 118;
int PLUSASSIGN = 119;
int MINUSASSIGN = 120;
int STARASSIGN = 121;
int SLASHASSIGN = 122;
int ANDASSIGN = 123;
int ANDASSIGNX = 124;
int ORASSIGN = 125;
int ORASSIGNX = 126;
int XORASSIGN = 127;
int MODASSIGN = 128;
int LSHIFTASSIGN = 129;
int LSHIFTASSIGNX = 130;
int RSIGNEDSHIFTASSIGN = 131;
int RSIGNEDSHIFTASSIGNX = 132;
int RUNSIGNEDSHIFTASSIGN = 133;
int RUNSIGNEDSHIFTASSIGNX = 134;
int DEFAULT = 0;
String[] tokenImage = {
"<EOF>",
"\" \"",
"\"\\t\"",
"\"\\r\"",
"\"\\f\"",
"\"\\n\"",
"<NONPRINTABLE>",
"<SINGLE_LINE_COMMENT>",
"<HASH_BANG_COMMENT>",
"<MULTI_LINE_COMMENT>",
"\"abstract\"",
"\"boolean\"",
"\"break\"",
"\"class\"",
"\"byte\"",
"\"case\"",
"\"catch\"",
"\"char\"",
"\"const\"",
"\"continue\"",
"\"default\"",
"\"do\"",
"\"double\"",
"\"else\"",
"\"enum\"",
"\"extends\"",
"\"false\"",
"\"final\"",
"\"finally\"",
"\"float\"",
"\"for\"",
"\"goto\"",
"\"if\"",
"\"implements\"",
"\"import\"",
"\"instanceof\"",
"\"int\"",
"\"interface\"",
"\"long\"",
"\"native\"",
"\"new\"",
"\"null\"",
"\"package\"",
"\"private\"",
"\"protected\"",
"\"public\"",
"\"return\"",
"\"short\"",
"\"static\"",
"\"strictfp\"",
"\"switch\"",
"\"synchronized\"",
"\"transient\"",
"\"throw\"",
"\"throws\"",
"\"true\"",
"\"try\"",
"\"void\"",
"\"volatile\"",
"\"while\"",
"<INTEGER_LITERAL>",
"<DECIMAL_LITERAL>",
"<HEX_LITERAL>",
"<OCTAL_LITERAL>",
"<FLOATING_POINT_LITERAL>",
"<EXPONENT>",
"<CHARACTER_LITERAL>",
"<STRING_LITERAL>",
"<LONG_STRING_LITERAL>",
"<FORMAL_COMMENT>",
"<IDENTIFIER>",
"<LETTER>",
"<DIGIT>",
"\"(\"",
"\")\"",
"\"{\"",
"\"}\"",
"\"[\"",
"\"]\"",
"\";\"",
"\",\"",
"\".\"",
"\"=\"",
"\">\"",
"\"@gt\"",
"\"<\"",
"\"@lt\"",
"\"!\"",
"\"~\"",
"\"?\"",
"\":\"",
"\"==\"",
"\"<=\"",
"\"@lteq\"",
"\">=\"",
"\"@gteq\"",
"\"!=\"",
"\"||\"",
"\"@or\"",
"\"&&\"",
"\"@and\"",
"\"++\"",
"\"--\"",
"\"+\"",
"\"-\"",
"\"*\"",
"\"/\"",
"\"&\"",
"\"@bitwise_and\"",
"\"|\"",
"\"@bitwise_or\"",
"\"^\"",
"\"%\"",
"\"<<\"",
"\"@left_shift\"",
"\">>\"",
"\"@right_shift\"",
"\">>>\"",
"\"@right_unsigned_shift\"",
"\"+=\"",
"\"-=\"",
"\"*=\"",
"\"/=\"",
"\"&=\"",
"\"@and_assign\"",
"\"|=\"",
"\"@or_assign\"",
"\"^=\"",
"\"%=\"",
"\"<<=\"",
"\"@left_shift_assign\"",
"\">>=\"",
"\"@right_shift_assign\"",
"\">>>=\"",
"\"@right_unsigned_shift_assign\"",};
}
| 6,071 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
JavaCharStream.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/JavaCharStream.java | /* Generated By:JavaCC: Do not edit this line. JavaCharStream.java Version 3.0 */
package ehacks.bsh;
/**
* An implementation of interface CharStream, where the stream is assumed to
* contain only ASCII characters (with java-like unicode escape processing).
*/
public class JavaCharStream {
public static final boolean staticFlag = false;
static int hexval(char c) throws java.io.IOException {
switch (c) {
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
case 'a':
case 'A':
return 10;
case 'b':
case 'B':
return 11;
case 'c':
case 'C':
return 12;
case 'd':
case 'D':
return 13;
case 'e':
case 'E':
return 14;
case 'f':
case 'F':
return 15;
}
throw new java.io.IOException(); // Should never come here
}
public int bufpos = -1;
int bufsize;
int available;
int tokenBegin;
protected int bufline[];
protected int bufcolumn[];
protected int column = 0;
protected int line = 1;
protected boolean prevCharIsCR = false;
protected boolean prevCharIsLF = false;
protected java.io.Reader inputStream;
protected char[] nextCharBuf;
protected char[] buffer;
protected int maxNextCharInd = 0;
protected int nextCharInd = -1;
protected int inBuf = 0;
protected void ExpandBuff(boolean wrapAround) {
char[] newbuffer = new char[bufsize + 2048];
int newbufline[] = new int[bufsize + 2048];
int newbufcolumn[] = new int[bufsize + 2048];
try {
if (wrapAround) {
System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
System.arraycopy(buffer, 0, newbuffer,
bufsize - tokenBegin, bufpos);
buffer = newbuffer;
System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos);
bufline = newbufline;
System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos);
bufcolumn = newbufcolumn;
bufpos += (bufsize - tokenBegin);
} else {
System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
buffer = newbuffer;
System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
bufline = newbufline;
System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
bufcolumn = newbufcolumn;
bufpos -= tokenBegin;
}
} catch (Throwable t) {
throw new Error(t.getMessage());
}
available = (bufsize += 2048);
tokenBegin = 0;
}
protected void FillBuff() throws java.io.IOException {
int i;
if (maxNextCharInd == 4096) {
maxNextCharInd = nextCharInd = 0;
}
try {
if ((i = inputStream.read(nextCharBuf, maxNextCharInd,
4096 - maxNextCharInd)) == -1) {
inputStream.close();
throw new java.io.IOException();
} else {
maxNextCharInd += i;
}
} catch (java.io.IOException e) {
if (bufpos != 0) {
--bufpos;
backup(0);
} else {
bufline[bufpos] = line;
bufcolumn[bufpos] = column;
}
throw e;
}
}
protected char ReadByte() throws java.io.IOException {
if (++nextCharInd >= maxNextCharInd) {
FillBuff();
}
return nextCharBuf[nextCharInd];
}
public char BeginToken() throws java.io.IOException {
if (inBuf > 0) {
--inBuf;
if (++bufpos == bufsize) {
bufpos = 0;
}
tokenBegin = bufpos;
return buffer[bufpos];
}
tokenBegin = 0;
bufpos = -1;
return readChar();
}
protected void AdjustBuffSize() {
if (available == bufsize) {
if (tokenBegin > 2048) {
bufpos = 0;
available = tokenBegin;
} else {
ExpandBuff(false);
}
} else if (available > tokenBegin) {
available = bufsize;
} else if ((tokenBegin - available) < 2048) {
ExpandBuff(true);
} else {
available = tokenBegin;
}
}
protected void UpdateLineColumn(char c) {
column++;
if (prevCharIsLF) {
prevCharIsLF = false;
line += (column = 1);
} else if (prevCharIsCR) {
prevCharIsCR = false;
if (c == '\n') {
prevCharIsLF = true;
} else {
line += (column = 1);
}
}
switch (c) {
case '\r':
prevCharIsCR = true;
break;
case '\n':
prevCharIsLF = true;
break;
case '\t':
column--;
column += (8 - (column & 07));
break;
default:
break;
}
bufline[bufpos] = line;
bufcolumn[bufpos] = column;
}
public char readChar() throws java.io.IOException {
if (inBuf > 0) {
--inBuf;
if (++bufpos == bufsize) {
bufpos = 0;
}
return buffer[bufpos];
}
char c;
if (++bufpos == available) {
AdjustBuffSize();
}
if ((buffer[bufpos] = c = ReadByte()) == '\\') {
UpdateLineColumn(c);
int backSlashCnt = 1;
for (;;) // Read all the backslashes
{
if (++bufpos == available) {
AdjustBuffSize();
}
try {
if ((buffer[bufpos] = c = ReadByte()) != '\\') {
UpdateLineColumn(c);
// found a non-backslash char.
if ((c == 'u') && ((backSlashCnt & 1) == 1)) {
if (--bufpos < 0) {
bufpos = bufsize - 1;
}
break;
}
backup(backSlashCnt);
return '\\';
}
} catch (java.io.IOException e) {
if (backSlashCnt > 1) {
backup(backSlashCnt);
}
return '\\';
}
UpdateLineColumn(c);
backSlashCnt++;
}
// Here, we have seen an odd number of backslash's followed by a 'u'
try {
while ((c = ReadByte()) == 'u') {
++column;
}
buffer[bufpos] = c = (char) (hexval(c) << 12
| hexval(ReadByte()) << 8
| hexval(ReadByte()) << 4
| hexval(ReadByte()));
column += 4;
} catch (java.io.IOException e) {
throw new Error("Invalid escape character at line " + line
+ " column " + column + ".");
}
if (backSlashCnt == 1) {
return c;
} else {
backup(backSlashCnt - 1);
return '\\';
}
} else {
UpdateLineColumn(c);
return (c);
}
}
/**
* @deprecated @see #getEndColumn
*/
public int getColumn() {
return bufcolumn[bufpos];
}
/**
* @deprecated @see #getEndLine
*/
public int getLine() {
return bufline[bufpos];
}
public int getEndColumn() {
return bufcolumn[bufpos];
}
public int getEndLine() {
return bufline[bufpos];
}
public int getBeginColumn() {
return bufcolumn[tokenBegin];
}
public int getBeginLine() {
return bufline[tokenBegin];
}
public void backup(int amount) {
inBuf += amount;
if ((bufpos -= amount) < 0) {
bufpos += bufsize;
}
}
public JavaCharStream(java.io.Reader dstream,
int startline, int startcolumn, int buffersize) {
inputStream = dstream;
line = startline;
column = startcolumn - 1;
available = bufsize = buffersize;
buffer = new char[buffersize];
bufline = new int[buffersize];
bufcolumn = new int[buffersize];
nextCharBuf = new char[4096];
}
public JavaCharStream(java.io.Reader dstream,
int startline, int startcolumn) {
this(dstream, startline, startcolumn, 4096);
}
public JavaCharStream(java.io.Reader dstream) {
this(dstream, 1, 1, 4096);
}
public void ReInit(java.io.Reader dstream,
int startline, int startcolumn, int buffersize) {
inputStream = dstream;
line = startline;
column = startcolumn - 1;
if (buffer == null || buffersize != buffer.length) {
available = bufsize = buffersize;
buffer = new char[buffersize];
bufline = new int[buffersize];
bufcolumn = new int[buffersize];
nextCharBuf = new char[4096];
}
prevCharIsLF = prevCharIsCR = false;
tokenBegin = inBuf = maxNextCharInd = 0;
nextCharInd = bufpos = -1;
}
public void ReInit(java.io.Reader dstream,
int startline, int startcolumn) {
ReInit(dstream, startline, startcolumn, 4096);
}
public void ReInit(java.io.Reader dstream) {
ReInit(dstream, 1, 1, 4096);
}
public JavaCharStream(java.io.InputStream dstream, int startline,
int startcolumn, int buffersize) {
this(new java.io.InputStreamReader(dstream), startline, startcolumn, 4096);
}
public JavaCharStream(java.io.InputStream dstream, int startline,
int startcolumn) {
this(dstream, startline, startcolumn, 4096);
}
public JavaCharStream(java.io.InputStream dstream) {
this(dstream, 1, 1, 4096);
}
public void ReInit(java.io.InputStream dstream, int startline,
int startcolumn, int buffersize) {
ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, 4096);
}
public void ReInit(java.io.InputStream dstream, int startline,
int startcolumn) {
ReInit(dstream, startline, startcolumn, 4096);
}
public void ReInit(java.io.InputStream dstream) {
ReInit(dstream, 1, 1, 4096);
}
public String GetImage() {
if (bufpos >= tokenBegin) {
return new String(buffer, tokenBegin, bufpos - tokenBegin + 1);
} else {
return new String(buffer, tokenBegin, bufsize - tokenBegin)
+ new String(buffer, 0, bufpos + 1);
}
}
public char[] GetSuffix(int len) {
char[] ret = new char[len];
if ((bufpos + 1) >= len) {
System.arraycopy(buffer, bufpos - len + 1, ret, 0, len);
} else {
System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0,
len - bufpos - 1);
System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1);
}
return ret;
}
public void Done() {
nextCharBuf = null;
buffer = null;
bufline = null;
bufcolumn = null;
}
/**
* Method to adjust line and column numbers for the start of a token.<BR>
*/
public void adjustBeginLineColumn(int newLine, int newCol) {
int start = tokenBegin;
int len;
if (bufpos >= tokenBegin) {
len = bufpos - tokenBegin + inBuf + 1;
} else {
len = bufsize - tokenBegin + bufpos + 1 + inBuf;
}
int i = 0, j = 0, k = 0;
int nextColDiff = 0, columnDiff = 0;
while (i < len
&& bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) {
bufline[j] = newLine;
nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j];
bufcolumn[j] = newCol + columnDiff;
columnDiff = nextColDiff;
i++;
}
if (i < len) {
bufline[j] = newLine++;
bufcolumn[j] = newCol + columnDiff;
while (i++ < len) {
if (bufline[j = start % bufsize] != bufline[++start % bufsize]) {
bufline[j] = newLine++;
} else {
bufline[j] = newLine;
}
}
}
line = bufline[j];
column = bufcolumn[j];
}
}
| 13,735 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
Types.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/Types.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
/**
* Static routines supporing type comparison and conversion in BeanShell.
*
* The following are notes on type comparison and conversion in BeanShell.
*
*
*/
class Types {
/*
Type conversion identifiers. An ASSIGNMENT allows conversions that would
normally happen on assignment. A CAST performs numeric conversions to smaller
types (as in an explicit Java cast) and things allowed only in variable and array
declarations (e.g. byte b = 42;)
*/
static final int CAST = 0, ASSIGNMENT = 1;
static final int JAVA_BASE_ASSIGNABLE = 1,
JAVA_BOX_TYPES_ASSIGABLE = 2,
JAVA_VARARGS_ASSIGNABLE = 3,
BSH_ASSIGNABLE = 4;
static final int FIRST_ROUND_ASSIGNABLE = JAVA_BASE_ASSIGNABLE,
LAST_ROUND_ASSIGNABLE = BSH_ASSIGNABLE;
/**
* Special value that indicates by identity that the result of a cast
* operation was a valid cast. This is used by castObject() and
* castPrimitive() in the checkOnly mode of operation. This value is a
* Primitive type so that it can be returned by castPrimitive.
*/
static Primitive VALID_CAST = new Primitive(1);
static Primitive INVALID_CAST = new Primitive(-1);
/**
* Get the Java types of the arguments.
*/
public static Class[] getTypes(Object[] args) {
if (args == null) {
return new Class[0];
}
Class[] types = new Class[args.length];
for (int i = 0; i < args.length; i++) {
if (args[i] == null) {
types[i] = null;
} else if (args[i] instanceof Primitive) {
types[i] = ((Primitive) args[i]).getType();
} else {
types[i] = args[i].getClass();
}
}
return types;
}
/**
* Is the 'from' signature (argument types) assignable to the 'to' signature
* (candidate method types) This method handles the special case of null
* values in 'to' types indicating a loose type and matching anything.
*/
/* Should check for strict java here and limit to isJavaAssignable() */
static boolean isSignatureAssignable(Class[] from, Class[] to, int round) {
if (round != JAVA_VARARGS_ASSIGNABLE && from.length != to.length) {
return false;
}
switch (round) {
case JAVA_BASE_ASSIGNABLE:
for (int i = 0; i < from.length; i++) {
if (!isJavaBaseAssignable(to[i], from[i])) {
return false;
}
}
return true;
case JAVA_BOX_TYPES_ASSIGABLE:
for (int i = 0; i < from.length; i++) {
if (!isJavaBoxTypesAssignable(to[i], from[i])) {
return false;
}
}
return true;
case JAVA_VARARGS_ASSIGNABLE:
return isSignatureVarargsAssignable(from, to);
case BSH_ASSIGNABLE:
for (int i = 0; i < from.length; i++) {
if (!isBshAssignable(to[i], from[i])) {
return false;
}
}
return true;
default:
throw new InterpreterError("bad case");
}
}
private static boolean isSignatureVarargsAssignable(
Class[] from, Class[] to) {
return false;
}
/**
* Test if a conversion of the rhsType type to the lhsType type is legal via
* standard Java assignment conversion rules (i.e. without a cast). The
* rules include Java 5 autoboxing/unboxing.
* <p/>
*
* For Java primitive TYPE classes this method takes primitive promotion
* into account. The ordinary Class.isAssignableFrom() does not take
* primitive promotion conversions into account. Note that Java allows
* additional assignments without a cast in combination with variable
* declarations and array allocations. Those are handled elsewhere (maybe
* should be here with a flag?)
* <p/>
* This class accepts a null rhsType type indicating that the rhsType was
* the value Primitive.NULL and allows it to be assigned to any reference
* lhsType type (non primitive).
* <p/>
*
* Note that the getAssignableForm() method is the primary bsh method for
* checking assignability. It adds additional bsh conversions, etc.
*
* @see #isBshAssignable( Class, Class )
* @param lhsType assigning from rhsType to lhsType
* @param rhsType assigning from rhsType to lhsType
*/
static boolean isJavaAssignable(Class lhsType, Class rhsType) {
return isJavaBaseAssignable(lhsType, rhsType)
|| isJavaBoxTypesAssignable(lhsType, rhsType);
}
/**
* Is the assignment legal via original Java (up to version 1.4) assignment
* rules, not including auto-boxing/unboxing.
*
* @param rhsType may be null to indicate primitive null value
*/
static boolean isJavaBaseAssignable(Class<?> lhsType, Class<?> rhsType) {
/*
Assignment to loose type, defer to bsh extensions
Note: we could shortcut this here:
if ( lhsType == null ) return true;
rather than forcing another round. It's not strictly a Java issue,
so does it belong here?
*/
if (lhsType == null) {
return false;
}
// null rhs type corresponds to type of Primitive.NULL
// assignable to any object type
if (rhsType == null) {
return !lhsType.isPrimitive();
}
if (lhsType.isPrimitive() && rhsType.isPrimitive()) {
if (lhsType == rhsType) {
return true;
}
// handle primitive widening conversions - JLS 5.1.2
if ((rhsType == Byte.TYPE)
&& (lhsType == Short.TYPE || lhsType == Integer.TYPE
|| lhsType == Long.TYPE || lhsType == Float.TYPE
|| lhsType == Double.TYPE)) {
return true;
}
if ((rhsType == Short.TYPE)
&& (lhsType == Integer.TYPE || lhsType == Long.TYPE
|| lhsType == Float.TYPE || lhsType == Double.TYPE)) {
return true;
}
if ((rhsType == Character.TYPE)
&& (lhsType == Integer.TYPE || lhsType == Long.TYPE
|| lhsType == Float.TYPE || lhsType == Double.TYPE)) {
return true;
}
if ((rhsType == Integer.TYPE)
&& (lhsType == Long.TYPE || lhsType == Float.TYPE
|| lhsType == Double.TYPE)) {
return true;
}
if ((rhsType == Long.TYPE)
&& (lhsType == Float.TYPE || lhsType == Double.TYPE)) {
return true;
}
if ((rhsType == Float.TYPE) && (lhsType == Double.TYPE)) {
return true;
}
} else if (lhsType.isAssignableFrom(rhsType)) {
return true;
}
return false;
}
/**
* Determine if the type is assignable via Java boxing/unboxing rules.
*/
static boolean isJavaBoxTypesAssignable(
Class lhsType, Class rhsType) {
// Assignment to loose type... defer to bsh extensions
if (lhsType == null) {
return false;
}
// prim can be boxed and assigned to Object
if (lhsType == Object.class) {
return true;
}
// prim numeric type can be boxed and assigned to number
if (lhsType == Number.class
&& rhsType != Character.TYPE
&& rhsType != Boolean.TYPE) {
return true;
}
// General case prim type to wrapper or vice versa.
// I don't know if this is faster than a flat list of 'if's like above.
// wrapperMap maps both prim to wrapper and wrapper to prim types,
// so this test is symmetric
return Primitive.wrapperMap.get(lhsType) == rhsType;
}
/**
* Test if a type can be converted to another type via BeanShell extended
* syntax rules (a superset of Java conversion rules).
*/
static boolean isBshAssignable(Class toType, Class fromType) {
try {
return castObject(
toType, fromType, null/*fromValue*/,
ASSIGNMENT, true/*checkOnly*/
) == VALID_CAST;
} catch (UtilEvalError e) {
// This should not happen with checkOnly true
throw new InterpreterError("err in cast check: " + e);
}
}
/**
* Attempt to cast an object instance to a new type if possible via
* BeanShell extended syntax rules. These rules are always a superset of
* Java conversion rules. If you wish to impose context sensitive conversion
* rules then you must test before calling this method.
* <p/>
*
* This method can handle fromValue Primitive types (representing primitive
* casts) as well as fromValue object casts requiring interface generation,
* etc.
*
* @param toType the class type of the cast result, which may include
* primitive types, e.g. Byte.TYPE
*
* @param fromValue an Object or bsh.Primitive primitive value (including
* Primitive.NULL or Primitive.VOID )
*
* @see #isBshAssignable( Class, Class )
*/
public static Object castObject(
Object fromValue, Class toType, int operation)
throws UtilEvalError {
if (fromValue == null) {
throw new InterpreterError("null fromValue");
}
Class fromType
= fromValue instanceof Primitive
? ((Primitive) fromValue).getType()
: fromValue.getClass();
return castObject(
toType, fromType, fromValue, operation, false/*checkonly*/);
}
/**
* Perform a type conversion or test if a type conversion is possible with
* respect to BeanShell extended rules. These rules are always a superset of
* the Java language rules, so this method can also perform (but not test)
* any Java language assignment or cast conversion.
* <p/>
*
* This method can perform the functionality of testing if an assignment or
* cast is ultimately possible (with respect to BeanShell) as well as the
* functionality of performing the necessary conversion of a value based on
* the specified target type. This combined functionality is done for
* expediency and could be separated later.
* <p/>
*
* Other methods such as isJavaAssignable() should be used to determine the
* suitability of an assignment in a fine grained or restrictive way based
* on context before calling this method
* <p/>
*
* A CAST is stronger than an ASSIGNMENT operation in that it will attempt
* to perform primtive operations that cast to a smaller type. e.g.
* (byte)myLong; These are used in explicit primitive casts, primitive
* delclarations and array declarations. I don't believe there are any
* object conversions which are different between ASSIGNMENT and CAST (e.g.
* scripted object to interface proxy in bsh is done on assignment as well
* as cast).
* <p/>
*
* This method does not obey strictJava(), you must test first before using
* this method if you care. (See #isJavaAssignable()).
* <p/>
*
* @param toType the class type of the cast result, which may include
* primitive types, e.g. Byte.TYPE. toType may be null to indicate a loose
* type assignment (which matches any fromType).
*
* @param fromType is the class type of the value to be cast including java
* primitive TYPE classes for primitives. If fromValue is (or would be)
* Primitive.NULL then fromType should be null.
*
* @param fromValue an Object or bsh.Primitive primitive value (including
* Primitive.NULL or Primitive.VOID )
*
* @param checkOnly If checkOnly is true then fromValue must be null.
* FromType is checked for the cast to toType... If checkOnly is false then
* fromValue must be non-null (Primitive.NULL is ok) and the actual cast is
* performed.
*
* @throws UtilEvalError on invalid assignment (when operation is assignment
* ).
*
* @throws UtilTargetError wrapping ClassCastException on cast error (when
* operation is cast)
*
* @param operation is Types.CAST or Types.ASSIGNMENT
*
* @see bsh.Primitive.getType()
*/
/*
Notes: This method is currently responsible for auto-boxing/unboxing
conversions... Where does that need to go?
*/
private static Object castObject(
Class<?> toType, Class<?> fromType, Object fromValue,
int operation, boolean checkOnly)
throws UtilEvalError {
/*
Lots of preconditions checked here...
Once things are running smoothly we might comment these out
(That's what assertions are for).
*/
if (checkOnly && fromValue != null) {
throw new InterpreterError("bad cast params 1");
}
if (!checkOnly && fromValue == null) {
throw new InterpreterError("bad cast params 2");
}
if (fromType == Primitive.class) {
throw new InterpreterError("bad from Type, need to unwrap");
}
if (fromValue == Primitive.NULL && fromType != null) {
throw new InterpreterError("inconsistent args 1");
}
if (fromValue == Primitive.VOID && fromType != Void.TYPE) {
throw new InterpreterError("inconsistent args 2");
}
if (toType == Void.TYPE) {
throw new InterpreterError("loose toType should be null");
}
// assignment to loose type, void type, or exactly same type
if (toType == null || toType == fromType) {
return checkOnly ? VALID_CAST
: fromValue;
}
// Casting to primitive type
if (toType.isPrimitive()) {
if (fromType == Void.TYPE || fromType == null
|| fromType.isPrimitive()) {
// Both primitives, do primitive cast
return Primitive.castPrimitive(
toType, fromType, (Primitive) fromValue,
checkOnly, operation);
} else {
if (Primitive.isWrapperType(fromType)) {
// wrapper to primitive
// Convert value to Primitive and check/cast it.
//Object r = checkOnly ? VALID_CAST :
Class unboxedFromType = Primitive.unboxType(fromType);
Primitive primFromValue;
if (checkOnly) {
primFromValue = null; // must be null in checkOnly
} else {
primFromValue = (Primitive) Primitive.wrap(
fromValue, unboxedFromType);
}
return Primitive.castPrimitive(
toType, unboxedFromType, primFromValue,
checkOnly, operation);
} else {
// Cannot cast from arbitrary object to primitive
if (checkOnly) {
return INVALID_CAST;
} else {
throw castError(toType, fromType, operation);
}
}
}
}
// Else, casting to reference type
// Casting from primitive or void (to reference type)
if (fromType == Void.TYPE || fromType == null
|| fromType.isPrimitive()) {
// cast from primitive to wrapper type
if (Primitive.isWrapperType(toType)
&& fromType != Void.TYPE && fromType != null) {
// primitive to wrapper type
return checkOnly ? VALID_CAST
: Primitive.castWrapper(
Primitive.unboxType(toType),
((Primitive) fromValue).getValue());
}
// Primitive (not null or void) to Object.class type
if (toType == Object.class
&& fromType != Void.TYPE && fromType != null) {
// box it
return checkOnly ? VALID_CAST
: ((Primitive) fromValue).getValue();
}
// Primitive to arbitrary object type.
// Allow Primitive.castToType() to handle it as well as cases of
// Primitive.NULL and Primitive.VOID
return Primitive.castPrimitive(
toType, fromType, (Primitive) fromValue, checkOnly, operation);
}
// If type already assignable no cast necessary
// We do this last to allow various errors above to be caught.
// e.g cast Primitive.Void to Object would pass this
if (toType.isAssignableFrom(fromType)) {
return checkOnly ? VALID_CAST
: fromValue;
}
// Can we use the proxy mechanism to cast a bsh.This to
// the correct interface?
if (toType.isInterface()
&& ehacks.bsh.This.class.isAssignableFrom(fromType)) {
return checkOnly ? VALID_CAST
: ((ehacks.bsh.This) fromValue).getInterface(toType);
}
// Both numeric wrapper types?
// Try numeric style promotion wrapper cast
if (Primitive.isWrapperType(toType)
&& Primitive.isWrapperType(fromType)) {
return checkOnly ? VALID_CAST
: Primitive.castWrapper(toType, fromValue);
}
if (checkOnly) {
return INVALID_CAST;
} else {
throw castError(toType, fromType, operation);
}
}
/**
* Return a UtilEvalError or UtilTargetError wrapping a ClassCastException
* describing an illegal assignment or illegal cast, respectively.
*/
static UtilEvalError castError(
Class lhsType, Class rhsType, int operation) {
return castError(
Reflect.normalizeClassName(lhsType),
Reflect.normalizeClassName(rhsType), operation);
}
static UtilEvalError castError(
String lhs, String rhs, int operation) {
if (operation == ASSIGNMENT) {
return new UtilEvalError(
"Can't assign " + rhs + " to " + lhs);
}
Exception cce = new ClassCastException(
"Cannot cast " + rhs + " to " + lhs);
return new UtilTargetError(cce);
}
}
| 21,572 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
InterpreterError.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/InterpreterError.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
// part of beanshell fork at http://code.google.com/p/beanshell2
// licensed unter GNU Lesser GPL, see http://www.gnu.org/licenses/lgpl.html
package ehacks.bsh;
/**
* An internal error in the interpreter has occurred.
*/
public class InterpreterError extends RuntimeException {
public InterpreterError(final String s) {
super(s);
}
public InterpreterError(final String s, final Throwable cause) {
super(s, cause);
}
}
| 2,987 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
Modifiers.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/Modifiers.java | package ehacks.bsh;
import java.util.Hashtable;
/**
*
* @author Pat Niemeyer ([email protected])
*/
/*
Note: which of these things should be checked at parse time vs. run time?
*/
public class Modifiers implements java.io.Serializable {
public static final int CLASS = 0, METHOD = 1, FIELD = 2;
Hashtable modifiers;
/**
* @param context is METHOD or FIELD
*/
public void addModifier(int context, String name) {
if (modifiers == null) {
modifiers = new Hashtable();
}
Object existing = modifiers.put(name, Void.TYPE/*arbitrary flag*/);
if (existing != null) {
throw new IllegalStateException("Duplicate modifier: " + name);
}
int count = 0;
if (hasModifier("private")) {
++count;
}
if (hasModifier("protected")) {
++count;
}
if (hasModifier("public")) {
++count;
}
if (count > 1) {
throw new IllegalStateException(
"public/private/protected cannot be used in combination.");
}
switch (context) {
case CLASS:
validateForClass();
break;
case METHOD:
validateForMethod();
break;
case FIELD:
validateForField();
break;
}
}
public boolean hasModifier(String name) {
if (modifiers == null) {
modifiers = new Hashtable();
}
return modifiers.get(name) != null;
}
// could refactor these a bit
private void validateForMethod() {
insureNo("volatile", "Method");
insureNo("transient", "Method");
}
private void validateForField() {
insureNo("synchronized", "Variable");
insureNo("native", "Variable");
insureNo("abstract", "Variable");
}
private void validateForClass() {
validateForMethod(); // volatile, transient
insureNo("native", "Class");
insureNo("synchronized", "Class");
}
private void insureNo(String modifier, String context) {
if (hasModifier(modifier)) {
throw new IllegalStateException(
context + " cannot be declared '" + modifier + "'");
}
}
@Override
public String toString() {
return "Modifiers: " + modifiers;
}
}
| 2,428 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHArrayDimensions.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHArrayDimensions.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
import java.lang.reflect.Array;
/**
* The name of this class is somewhat misleading. This covers both the case
* where there is an array initializer and
*/
class BSHArrayDimensions extends SimpleNode {
public Class baseType;
public int numDefinedDims;
public int numUndefinedDims;
/**
* The Length in each defined dimension. This value set by the eval() Since
* the values can come from Expressions we should be re-eval()d each time.
*/
public int[] definedDimensions;
BSHArrayDimensions(int id) {
super(id);
}
public void addDefinedDimension() {
numDefinedDims++;
}
public void addUndefinedDimension() {
numUndefinedDims++;
}
public Object eval(
Class type, CallStack callstack, Interpreter interpreter)
throws EvalError {
if (Interpreter.DEBUG) {
Interpreter.debug("array base type = " + type);
}
baseType = type;
return eval(callstack, interpreter);
}
/**
* Evaluate the structure of the array in one of two ways:
*
* a) an initializer exists, evaluate it and return the fully constructed
* array object, also record the dimensions of that array
*
* b) evaluate and record the lengths in each dimension and return void.
*
* The structure of the array dims is maintained in dimensions.
*/
@Override
public Object eval(CallStack callstack, Interpreter interpreter)
throws EvalError {
SimpleNode child = (SimpleNode) jjtGetChild(0);
/*
Child is array initializer. Evaluate it and fill in the
dimensions it returns. Initialized arrays are always fully defined
(no undefined dimensions to worry about).
The syntax uses the undefinedDimension count.
e.g. int [][] { 1, 2 };
*/
if (child instanceof BSHArrayInitializer) {
if (baseType == null) {
throw new EvalError(
"Internal Array Eval err: unknown base type",
this, callstack);
}
Object initValue = ((BSHArrayInitializer) child).eval(
baseType, numUndefinedDims, callstack, interpreter);
Class arrayClass = initValue.getClass();
int actualDimensions = Reflect.getArrayDimensions(arrayClass);
definedDimensions = new int[actualDimensions];
// Compare with number of dimensions actually created with the
// number specified (syntax uses the undefined ones here)
if (definedDimensions.length != numUndefinedDims) {
throw new EvalError(
"Incompatible initializer. Allocation calls for a "
+ numUndefinedDims + " dimensional array, but initializer is a "
+ actualDimensions + " dimensional array", this, callstack);
}
// fill in definedDimensions [] lengths
Object arraySlice = initValue;
for (int i = 0; i < definedDimensions.length; i++) {
definedDimensions[i] = Array.getLength(arraySlice);
if (definedDimensions[i] > 0) {
arraySlice = Array.get(arraySlice, 0);
}
}
return initValue;
} else // Evaluate the defined dimensions of the array
{
definedDimensions = new int[numDefinedDims];
for (int i = 0; i < numDefinedDims; i++) {
try {
Object length = ((SimpleNode) jjtGetChild(i)).eval(
callstack, interpreter);
definedDimensions[i] = ((Primitive) length).intValue();
} catch (Exception e) {
throw new EvalError(
"Array index: " + i
+ " does not evaluate to an integer", this, callstack);
}
}
}
return Primitive.VOID;
}
}
| 6,605 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHFormalParameter.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHFormalParameter.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
/**
* A formal parameter declaration. For loose variable declaration type is null.
*/
class BSHFormalParameter extends SimpleNode {
public static final Class UNTYPED = null;
public String name;
// unsafe caching of type here
public Class type;
BSHFormalParameter(int id) {
super(id);
}
public String getTypeDescriptor(
CallStack callstack, Interpreter interpreter, String defaultPackage) {
if (jjtGetNumChildren() > 0) {
return ((BSHType) jjtGetChild(0)).getTypeDescriptor(
callstack, interpreter, defaultPackage);
} else // this will probably not get used
{
return "Ljava/lang/Object;"; // Object type
}
}
/**
* Evaluate the type.
*/
@Override
public Object eval(CallStack callstack, Interpreter interpreter)
throws EvalError {
if (jjtGetNumChildren() > 0) {
type = ((BSHType) jjtGetChild(0)).getType(callstack, interpreter);
} else {
type = UNTYPED;
}
return type;
}
}
| 3,653 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHStatementExpressionList.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHStatementExpressionList.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
class BSHStatementExpressionList extends SimpleNode {
BSHStatementExpressionList(int id) {
super(id);
}
@Override
public Object eval(CallStack callstack, Interpreter interpreter)
throws EvalError {
int n = jjtGetNumChildren();
for (int i = 0; i < n; i++) {
SimpleNode node = ((SimpleNode) jjtGetChild(i));
node.eval(callstack, interpreter);
}
return Primitive.VOID;
}
}
| 3,020 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
Node.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/Node.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
/* Generated By:JJTree: Do not edit this line. Node.java */
package ehacks.bsh;
/*
All BSH nodes must implement this interface. It provides basic
machinery for constructing the parent and child relationships
between nodes.
*/
interface Node extends java.io.Serializable {
/**
* This method is called after the node has been made the current node. It
* indicates that child nodes can now be added to it.
*/
public void jjtOpen();
/**
* This method is called after all the child nodes have been added.
*/
public void jjtClose();
/**
* This pair of methods are used to inform the node of its parent.
*/
public void jjtSetParent(Node n);
public Node jjtGetParent();
/**
* This method tells the node to add its argument to the node's list of
* children.
*/
public void jjtAddChild(Node n, int i);
/**
* This method returns a child node. The children are numbered from zero,
* left to right.
*/
public Node jjtGetChild(int i);
/**
* Return the number of children the node has.
*/
public int jjtGetNumChildren();
}
| 3,679 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHPrimaryExpression.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHPrimaryExpression.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
class BSHPrimaryExpression extends SimpleNode {
BSHPrimaryExpression(int id) {
super(id);
}
/**
* Evaluate to a value object.
*/
@Override
public Object eval(CallStack callstack, Interpreter interpreter)
throws EvalError {
return eval(false, callstack, interpreter);
}
/**
* Evaluate to a value object.
*/
public LHS toLHS(CallStack callstack, Interpreter interpreter)
throws EvalError {
Object obj = eval(true, callstack, interpreter);
if (!(obj instanceof LHS)) {
throw new EvalError("Can't assign to:", this, callstack);
} else {
return (LHS) obj;
}
}
/*
Our children are a prefix expression and any number of suffixes.
<p>
We don't eval() any nodes until the suffixes have had an
opportunity to work through them. This lets the suffixes decide
how to interpret an ambiguous name (e.g. for the .class operation).
*/
private Object eval(boolean toLHS,
CallStack callstack, Interpreter interpreter)
throws EvalError {
Object obj = jjtGetChild(0);
int numChildren = jjtGetNumChildren();
for (int i = 1; i < numChildren; i++) {
obj = ((BSHPrimarySuffix) jjtGetChild(i)).doSuffix(
obj, toLHS, callstack, interpreter);
}
/*
If the result is a Node eval() it to an object or LHS
(as determined by toLHS)
*/
if (obj instanceof SimpleNode) {
if (obj instanceof BSHAmbiguousName) {
if (toLHS) {
obj = ((BSHAmbiguousName) obj).toLHS(
callstack, interpreter);
} else {
obj = ((BSHAmbiguousName) obj).toObject(
callstack, interpreter);
}
} else // Some arbitrary kind of node
if (toLHS) // is this right?
{
throw new EvalError("Can't assign to prefix.",
this, callstack);
} else {
obj = ((SimpleNode) obj).eval(callstack, interpreter);
}
}
// return LHS or value object as determined by toLHS
if (obj instanceof LHS) {
if (toLHS) {
return obj;
} else {
try {
return ((LHS) obj).getValue();
} catch (UtilEvalError e) {
throw e.toEvalError(this, callstack);
}
}
} else {
return obj;
}
}
}
| 5,201 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
TargetError.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/TargetError.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
/**
* TargetError is an EvalError that wraps an exception thrown by the script (or
* by code called from the script). TargetErrors indicate exceptions which can
* be caught within the script itself, whereas a general EvalError indicates
* that the script cannot be evaluated further for some reason.
*
* If the exception is caught within the script it is automatically unwrapped,
* so the code looks like normal Java code. If the TargetError is thrown from
* the eval() or interpreter.eval() method it may be caught and unwrapped to
* determine what exception was thrown.
*/
public class TargetError extends EvalError {
private final boolean inNativeCode;
public TargetError(
String msg, Throwable t, SimpleNode node, CallStack callstack,
boolean inNativeCode) {
super(msg, node, callstack, t);
this.inNativeCode = inNativeCode;
}
public TargetError(Throwable t, SimpleNode node, CallStack callstack) {
this("TargetError", t, node, callstack, false);
}
public Throwable getTarget() {
// check for easy mistake
Throwable target = getCause();
if (target instanceof InvocationTargetException) {
return ((InvocationTargetException) target).getTargetException();
} else {
return target;
}
}
@Override
public String getMessage() {
return super.getMessage()
+ "\nTarget exception: "
+ printTargetError(getCause());
}
public void printStackTrace(boolean debug, PrintStream out) {
if (debug) {
super.printStackTrace(out);
out.println("--- Target Stack Trace ---");
}
getCause().printStackTrace(out);
}
/**
* Generate a printable string showing the wrapped target exception. If the
* proxy mechanism is available, allow the extended print to check for
* UndeclaredThrowableException and print that embedded error.
*/
private String printTargetError(Throwable t) {
return getCause().toString() + "\n" + xPrintTargetError(t);
}
/**
* Extended form of print target error. This indirection is used to print
* UndeclaredThrowableExceptions which are possible when the proxy mechanism
* is available.
*
* We are shielded from compile problems by using a bsh script. This is
* acceptable here because we're not in a critical path... Otherwise we'd
* need yet another dynamically loaded module just for this.
*/
private String xPrintTargetError(Throwable t) {
String getTarget
= "import java.lang.reflect.UndeclaredThrowableException;"
+ "String result=\"\";"
+ "while ( target instanceof UndeclaredThrowableException ) {"
+ " target=target.getUndeclaredThrowable(); "
+ " result+=\"Nested: \"+target.toString();"
+ "}"
+ "return result;";
Interpreter i = new Interpreter();
try {
i.set("target", t);
return (String) i.eval(getTarget);
} catch (EvalError e) {
throw new InterpreterError("xprintarget: " + e.toString());
}
}
/**
* Return true if the TargetError was generated from native code. e.g. if
* the script called into a compiled java class which threw the excpetion.
* We distinguish so that we can print the stack trace for the native code
* case... the stack trace would not be useful if the exception was
* generated by the script. e.g. if the script explicitly threw an
* exception... (the stack trace would simply point to the bsh internals
* which generated the exception).
*/
public boolean inNativeCode() {
return inNativeCode;
}
}
| 6,470 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
Primitive.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/Primitive.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
import java.io.ObjectStreamException;
import java.util.HashMap;
import java.util.Map;
/**
* Wrapper for primitive types in Bsh. This is package public because it is used
* in the implementation of some bsh commands.
*
* See the note in LHS.java about wrapping objects.
*/
/*
Note: this class is final because we may test == Primitive.class in places.
If we need to change that search for those tests.
*/
public class Primitive implements ParserConstants, java.io.Serializable {
/*
static Hashtable primitiveToWrapper = new Hashtable();
static Hashtable wrapperToPrimitive = new Hashtable();
static {
primitiveToWrapper.put( Boolean.TYPE, Boolean.class );
primitiveToWrapper.put( Byte.TYPE, Byte.class );
primitiveToWrapper.put( Short.TYPE, Short.class );
primitiveToWrapper.put( Character.TYPE, Character.class );
primitiveToWrapper.put( Integer.TYPE, Integer.class );
primitiveToWrapper.put( Long.TYPE, Long.class );
primitiveToWrapper.put( Float.TYPE, Float.class );
primitiveToWrapper.put( Double.TYPE, Double.class );
wrapperToPrimitive.put( Boolean.class, Boolean.TYPE );
wrapperToPrimitive.put( Byte.class, Byte.TYPE );
wrapperToPrimitive.put( Short.class, Short.TYPE );
wrapperToPrimitive.put( Character.class, Character.TYPE );
wrapperToPrimitive.put( Integer.class, Integer.TYPE );
wrapperToPrimitive.put( Long.class, Long.TYPE );
wrapperToPrimitive.put( Float.class, Float.TYPE );
wrapperToPrimitive.put( Double.class, Double.TYPE );
}
*/
static final Map<Class, Class> wrapperMap = new HashMap<Class, Class>();
static {
wrapperMap.put(Boolean.TYPE, Boolean.class);
wrapperMap.put(Byte.TYPE, Byte.class);
wrapperMap.put(Short.TYPE, Short.class);
wrapperMap.put(Character.TYPE, Character.class);
wrapperMap.put(Integer.TYPE, Integer.class);
wrapperMap.put(Long.TYPE, Long.class);
wrapperMap.put(Float.TYPE, Float.class);
wrapperMap.put(Double.TYPE, Double.class);
wrapperMap.put(Boolean.class, Boolean.TYPE);
wrapperMap.put(Byte.class, Byte.TYPE);
wrapperMap.put(Short.class, Short.TYPE);
wrapperMap.put(Character.class, Character.TYPE);
wrapperMap.put(Integer.class, Integer.TYPE);
wrapperMap.put(Long.class, Long.TYPE);
wrapperMap.put(Float.class, Float.TYPE);
wrapperMap.put(Double.class, Double.TYPE);
}
/**
* The primitive value stored in its java.lang wrapper class
*/
private Object value;
private static class Special implements java.io.Serializable {
private Special() {
}
public static final Special NULL_VALUE = new Special() {
private Object readResolve() throws ObjectStreamException {
return Special.NULL_VALUE;
}
};
public static final Special VOID_TYPE = new Special() {
private Object readResolve() throws ObjectStreamException {
return Special.VOID_TYPE;
}
};
}
/*
NULL means "no value".
This ia a placeholder for primitive null value.
*/
public static final Primitive NULL = new Primitive(Special.NULL_VALUE);
/**
* VOID means "no type". Strictly speaking, this makes no sense here. But
* for practical reasons we'll consider the lack of a type to be a special
* value.
*/
public static final Primitive VOID = new Primitive(Special.VOID_TYPE);
private Object readResolve() throws ObjectStreamException {
if (value == Special.NULL_VALUE) {
return Primitive.NULL;
} else if (value == Special.VOID_TYPE) {
return Primitive.VOID;
} else {
return this;
}
}
// private to prevent invocation with param that isn't a primitive-wrapper
public Primitive(Object value) {
if (value == null) {
throw new InterpreterError(
"Use Primitve.NULL instead of Primitive(null)");
}
if (value != Special.NULL_VALUE
&& value != Special.VOID_TYPE
&& !isWrapperType(value.getClass())) {
throw new InterpreterError("Not a wrapper type: " + value);
}
this.value = value;
}
public Primitive(boolean value) {
this(new Boolean(value));
}
public Primitive(byte value) {
this(new Byte(value));
}
public Primitive(short value) {
this(new Short(value));
}
public Primitive(char value) {
this(new Character(value));
}
public Primitive(int value) {
this(new Integer(value));
}
public Primitive(long value) {
this(new Long(value));
}
public Primitive(float value) {
this(new Float(value));
}
public Primitive(double value) {
this(new Double(value));
}
/**
* Return the primitive value stored in its java.lang wrapper class
*/
public Object getValue() {
if (value == Special.NULL_VALUE) {
return null;
} else if (value == Special.VOID_TYPE) {
throw new InterpreterError("attempt to unwrap void type");
} else {
return value;
}
}
@Override
public String toString() {
if (value == Special.NULL_VALUE) {
return "null";
} else if (value == Special.VOID_TYPE) {
return "void";
} else {
return value.toString();
}
}
/**
* Get the corresponding Java primitive TYPE class for this Primitive.
*
* @return the primitive TYPE class type of the value or Void.TYPE for
* Primitive.VOID or null value for type of Primitive.NULL
*/
public Class getType() {
if (this == Primitive.VOID) {
return Void.TYPE;
}
// NULL return null as type... we currently use null type to indicate
// loose typing throughout bsh.
if (this == Primitive.NULL) {
return null;
}
return unboxType(value.getClass());
}
/**
* Perform a binary operation on two Primitives or wrapper types. If both
* original args were Primitives return a Primitive result else it was mixed
* (wrapper/primitive) return the wrapper type. The exception is for boolean
* operations where we will return the primitive type either way.
*/
public static Object binaryOperation(
Object obj1, Object obj2, int kind)
throws UtilEvalError {
// special primitive types
if (obj1 == NULL || obj2 == NULL) {
throw new UtilEvalError(
"Null value or 'null' literal in binary operation");
}
if (obj1 == VOID || obj2 == VOID) {
throw new UtilEvalError(
"Undefined variable, class, or 'void' literal in binary operation");
}
// keep track of the original types
Class lhsOrgType = obj1.getClass();
Class rhsOrgType = obj2.getClass();
// Unwrap primitives
if (obj1 instanceof Primitive) {
obj1 = ((Primitive) obj1).getValue();
}
if (obj2 instanceof Primitive) {
obj2 = ((Primitive) obj2).getValue();
}
Object[] operands = promotePrimitives(obj1, obj2);
Object lhs = operands[0];
Object rhs = operands[1];
if (lhs.getClass() != rhs.getClass()) {
throw new UtilEvalError("Type mismatch in operator. "
+ lhs.getClass() + " cannot be used with " + rhs.getClass());
}
Object result;
try {
result = binaryOperationImpl(lhs, rhs, kind);
} catch (ArithmeticException e) {
throw new UtilTargetError("Arithemetic Exception in binary op", e);
}
// If both original args were Primitives return a Primitive result
// else it was mixed (wrapper/primitive) return the wrapper type
// Exception is for boolean result, return the primitive
if ((lhsOrgType == Primitive.class && rhsOrgType == Primitive.class)
|| result instanceof Boolean) {
return new Primitive(result);
} else {
return result;
}
}
static Object binaryOperationImpl(Object lhs, Object rhs, int kind)
throws UtilEvalError {
if (lhs instanceof Boolean) {
return booleanBinaryOperation((Boolean) lhs, (Boolean) rhs, kind);
} else if (lhs instanceof Integer) {
return intBinaryOperation((Integer) lhs, (Integer) rhs, kind);
} else if (lhs instanceof Long) {
return longBinaryOperation((Long) lhs, (Long) rhs, kind);
} else if (lhs instanceof Float) {
return floatBinaryOperation((Float) lhs, (Float) rhs, kind);
} else if (lhs instanceof Double) {
return doubleBinaryOperation((Double) lhs, (Double) rhs, kind);
} else {
throw new UtilEvalError("Invalid types in binary operator");
}
}
static Boolean booleanBinaryOperation(Boolean B1, Boolean B2, int kind) {
boolean lhs = B1;
boolean rhs = B2;
switch (kind) {
case EQ:
return lhs == rhs;
case NE:
return lhs != rhs;
case BOOL_OR:
case BOOL_ORX:
case BIT_OR:
return lhs || rhs;
case BOOL_AND:
case BOOL_ANDX:
case BIT_AND:
return lhs && rhs;
case XOR:
return lhs ^ rhs;
default:
throw new InterpreterError("unimplemented binary operator");
}
}
// returns Object covering both Long and Boolean return types
static Object longBinaryOperation(Long L1, Long L2, int kind) {
long lhs = L1;
long rhs = L2;
switch (kind) {
// boolean
case LT:
case LTX:
return lhs < rhs;
case GT:
case GTX:
return lhs > rhs;
case EQ:
return lhs == rhs;
case LE:
case LEX:
return lhs <= rhs;
case GE:
case GEX:
return lhs >= rhs;
case NE:
return lhs != rhs;
// arithmetic
case PLUS:
return lhs + rhs;
case MINUS:
return lhs - rhs;
case STAR:
return lhs * rhs;
case SLASH:
return lhs / rhs;
case MOD:
return lhs % rhs;
// bitwise
case LSHIFT:
case LSHIFTX:
return lhs << rhs;
case RSIGNEDSHIFT:
case RSIGNEDSHIFTX:
return lhs >> rhs;
case RUNSIGNEDSHIFT:
case RUNSIGNEDSHIFTX:
return lhs >>> rhs;
case BIT_AND:
case BIT_ANDX:
return lhs & rhs;
case BIT_OR:
case BIT_ORX:
return lhs | rhs;
case XOR:
return lhs ^ rhs;
default:
throw new InterpreterError(
"Unimplemented binary long operator");
}
}
// returns Object covering both Integer and Boolean return types
static Object intBinaryOperation(Integer I1, Integer I2, int kind) {
int lhs = I1;
int rhs = I2;
switch (kind) {
// boolean
case LT:
case LTX:
return lhs < rhs;
case GT:
case GTX:
return lhs > rhs;
case EQ:
return lhs == rhs;
case LE:
case LEX:
return lhs <= rhs;
case GE:
case GEX:
return lhs >= rhs;
case NE:
return lhs != rhs;
// arithmetic
case PLUS:
return lhs + rhs;
case MINUS:
return lhs - rhs;
case STAR:
return lhs * rhs;
case SLASH:
return lhs / rhs;
case MOD:
return lhs % rhs;
// bitwise
case LSHIFT:
case LSHIFTX:
return lhs << rhs;
case RSIGNEDSHIFT:
case RSIGNEDSHIFTX:
return lhs >> rhs;
case RUNSIGNEDSHIFT:
case RUNSIGNEDSHIFTX:
return lhs >>> rhs;
case BIT_AND:
case BIT_ANDX:
return lhs & rhs;
case BIT_OR:
case BIT_ORX:
return lhs | rhs;
case XOR:
return lhs ^ rhs;
default:
throw new InterpreterError(
"Unimplemented binary integer operator");
}
}
// returns Object covering both Double and Boolean return types
static Object doubleBinaryOperation(Double D1, Double D2, int kind)
throws UtilEvalError {
double lhs = D1;
double rhs = D2;
switch (kind) {
// boolean
case LT:
case LTX:
return lhs < rhs;
case GT:
case GTX:
return lhs > rhs;
case EQ:
return lhs == rhs;
case LE:
case LEX:
return lhs <= rhs;
case GE:
case GEX:
return lhs >= rhs;
case NE:
return lhs != rhs;
// arithmetic
case PLUS:
return lhs + rhs;
case MINUS:
return lhs - rhs;
case STAR:
return lhs * rhs;
case SLASH:
return lhs / rhs;
case MOD:
return lhs % rhs;
// can't shift floating-point values
case LSHIFT:
case LSHIFTX:
case RSIGNEDSHIFT:
case RSIGNEDSHIFTX:
case RUNSIGNEDSHIFT:
case RUNSIGNEDSHIFTX:
throw new UtilEvalError("Can't shift doubles");
default:
throw new InterpreterError(
"Unimplemented binary double operator");
}
}
// returns Object covering both Long and Boolean return types
static Object floatBinaryOperation(Float F1, Float F2, int kind)
throws UtilEvalError {
float lhs = F1;
float rhs = F2;
switch (kind) {
// boolean
case LT:
case LTX:
return lhs < rhs;
case GT:
case GTX:
return lhs > rhs;
case EQ:
return lhs == rhs;
case LE:
case LEX:
return lhs <= rhs;
case GE:
case GEX:
return lhs >= rhs;
case NE:
return lhs != rhs;
// arithmetic
case PLUS:
return lhs + rhs;
case MINUS:
return lhs - rhs;
case STAR:
return lhs * rhs;
case SLASH:
return lhs / rhs;
case MOD:
return lhs % rhs;
// can't shift floats
case LSHIFT:
case LSHIFTX:
case RSIGNEDSHIFT:
case RSIGNEDSHIFTX:
case RUNSIGNEDSHIFT:
case RUNSIGNEDSHIFTX:
throw new UtilEvalError("Can't shift floats ");
default:
throw new InterpreterError(
"Unimplemented binary float operator");
}
}
/**
* Promote primitive wrapper type to to Integer wrapper type
*/
static Object promoteToInteger(Object wrapper) {
if (wrapper instanceof Character) {
return new Integer(((Character) wrapper));
} else if ((wrapper instanceof Byte) || (wrapper instanceof Short)) {
return ((Number) wrapper).intValue();
}
return wrapper;
}
/**
* Promote the pair of primitives to the maximum type of the two. e.g.
* [int,long]->[long,long]
*/
static Object[] promotePrimitives(Object lhs, Object rhs) {
lhs = promoteToInteger(lhs);
rhs = promoteToInteger(rhs);
if ((lhs instanceof Number) && (rhs instanceof Number)) {
Number lnum = (Number) lhs;
Number rnum = (Number) rhs;
boolean b;
if ((b = (lnum instanceof Double)) || (rnum instanceof Double)) {
if (b) {
rhs = rnum.doubleValue();
} else {
lhs = lnum.doubleValue();
}
} else if ((b = (lnum instanceof Float)) || (rnum instanceof Float)) {
if (b) {
rhs = rnum.floatValue();
} else {
lhs = lnum.floatValue();
}
} else if ((b = (lnum instanceof Long)) || (rnum instanceof Long)) {
if (b) {
rhs = rnum.longValue();
} else {
lhs = lnum.longValue();
}
}
}
return new Object[]{lhs, rhs};
}
public static Primitive unaryOperation(Primitive val, int kind)
throws UtilEvalError {
if (val == NULL) {
throw new UtilEvalError(
"illegal use of null object or 'null' literal");
}
if (val == VOID) {
throw new UtilEvalError(
"illegal use of undefined object or 'void' literal");
}
Class operandType = val.getType();
Object operand = promoteToInteger(val.getValue());
if (operand instanceof Boolean) {
return new Primitive(booleanUnaryOperation((Boolean) operand, kind));
} else if (operand instanceof Integer) {
int result = intUnaryOperation((Integer) operand, kind);
// ++ and -- must be cast back the original type
if (kind == INCR || kind == DECR) {
if (operandType == Byte.TYPE) {
return new Primitive((byte) result);
}
if (operandType == Short.TYPE) {
return new Primitive((short) result);
}
if (operandType == Character.TYPE) {
return new Primitive((char) result);
}
}
return new Primitive(result);
} else if (operand instanceof Long) {
return new Primitive(longUnaryOperation((Long) operand, kind));
} else if (operand instanceof Float) {
return new Primitive(floatUnaryOperation((Float) operand, kind));
} else if (operand instanceof Double) {
return new Primitive(doubleUnaryOperation((Double) operand, kind));
} else {
throw new InterpreterError(
"An error occurred. Please call technical support.");
}
}
static boolean booleanUnaryOperation(Boolean B, int kind)
throws UtilEvalError {
boolean operand = B;
switch (kind) {
case BANG:
return !operand;
default:
throw new UtilEvalError("Operator inappropriate for boolean");
}
}
static int intUnaryOperation(Integer I, int kind) {
int operand = I;
switch (kind) {
case PLUS:
return operand;
case MINUS:
return -operand;
case TILDE:
return ~operand;
case INCR:
return operand + 1;
case DECR:
return operand - 1;
default:
throw new InterpreterError("bad integer unaryOperation");
}
}
static long longUnaryOperation(Long L, int kind) {
long operand = L;
switch (kind) {
case PLUS:
return operand;
case MINUS:
return -operand;
case TILDE:
return ~operand;
case INCR:
return operand + 1;
case DECR:
return operand - 1;
default:
throw new InterpreterError("bad long unaryOperation");
}
}
static float floatUnaryOperation(Float F, int kind) {
float operand = F;
switch (kind) {
case PLUS:
return operand;
case MINUS:
return -operand;
case INCR:
return operand + 1;
case DECR:
return operand - 1;
default:
throw new InterpreterError("bad float unaryOperation");
}
}
static double doubleUnaryOperation(Double D, int kind) {
double operand = D;
switch (kind) {
case PLUS:
return operand;
case MINUS:
return -operand;
case INCR:
return operand + 1;
case DECR:
return operand - 1;
default:
throw new InterpreterError("bad double unaryOperation");
}
}
public int intValue() throws UtilEvalError {
if (value instanceof Number) {
return ((Number) value).intValue();
} else {
throw new UtilEvalError("Primitive not a number");
}
}
public boolean booleanValue() throws UtilEvalError {
if (value instanceof Boolean) {
return ((Boolean) value);
} else {
throw new UtilEvalError("Primitive not a boolean");
}
}
/**
* Determine if this primitive is a numeric type. i.e. not boolean, null, or
* void (but including char)
*/
public boolean isNumber() {
return (!(value instanceof Boolean)
&& !(this == NULL) && !(this == VOID));
}
public Number numberValue() throws UtilEvalError {
Object value = this.value;
// Promote character to Number type for these purposes
if (value instanceof Character) {
value = new Integer(((Character) value));
}
if (value instanceof Number) {
return (Number) value;
} else {
throw new UtilEvalError("Primitive not a number");
}
}
/**
* Primitives compare equal with other Primitives containing an equal
* wrapped value.
*/
@Override
public boolean equals(Object obj) {
if (obj instanceof Primitive) {
return ((Primitive) obj).value.equals(this.value);
} else {
return false;
}
}
/**
* The hash of the Primitive is tied to the hash of the wrapped value but
* shifted so that they are not the same.
*/
@Override
public int hashCode() {
return this.value.hashCode() * 21; // arbitrary
}
/**
* Unwrap primitive values and map voids to nulls. Non Primitive types
* remain unchanged.
*
* @param obj object type which may be bsh.Primitive
* @return corresponding "normal" Java type, "unwrapping" any bsh.Primitive
* types to their wrapper types.
*/
public static Object unwrap(Object obj) {
// map voids to nulls for the outside world
if (obj == Primitive.VOID) {
return null;
}
// unwrap primitives
if (obj instanceof Primitive) {
return ((Primitive) obj).getValue();
} else {
return obj;
}
}
/*
Unwrap Primitive wrappers to their java.lang wrapper values.
e.g. Primitive(42) becomes Integer(42)
@see #unwrap( Object )
*/
public static Object[] unwrap(Object[] args) {
Object[] oa = new Object[args.length];
for (int i = 0; i < args.length; i++) {
oa[i] = unwrap(args[i]);
}
return oa;
}
/*
*/
public static Object[] wrap(Object[] args, Class[] paramTypes) {
if (args == null) {
return null;
}
Object[] oa = new Object[args.length];
for (int i = 0; i < args.length; i++) {
oa[i] = wrap(args[i], paramTypes[i]);
}
return oa;
}
/**
* Wrap primitive values (as indicated by type param) and nulls in the
* Primitive class. Values not primitive or null are left unchanged.
* Primitive values are represented by their wrapped values in param value.
* <p/>
* The value null is mapped to Primitive.NULL. Any value specified with type
* Void.TYPE is mapped to Primitive.VOID.
*/
public static Object wrap(
Object value, Class type) {
if (type == Void.TYPE) {
return Primitive.VOID;
}
if (value == null) {
return Primitive.NULL;
}
if (type.isPrimitive()) {
return new Primitive(value);
}
return value;
}
/**
* Get the appropriate default value per JLS 4.5.4
*/
public static Primitive getDefaultValue(Class type) {
if (type == null || !type.isPrimitive()) {
return Primitive.NULL;
}
if (type == Boolean.TYPE) {
return new Primitive(false);
}
// non boolean primitive, get appropriate flavor of zero
try {
return new Primitive(0).castToType(type, Types.CAST);
} catch (UtilEvalError e) {
throw new InterpreterError("bad cast");
}
}
/**
* Get the corresponding java.lang wrapper class for the primitive TYPE
* class. e.g. Integer.TYPE -> Integer.class
*/
public static Class boxType(Class primitiveType) {
Class c = wrapperMap.get(primitiveType);
if (c != null) {
return c;
}
throw new InterpreterError(
"Not a primitive type: " + primitiveType);
}
/**
* Get the corresponding primitive TYPE class for the java.lang wrapper
* class type. e.g. Integer.class -> Integer.TYPE
*/
public static Class unboxType(Class wrapperType) {
Class c = wrapperMap.get(wrapperType);
if (c != null) {
return c;
}
throw new InterpreterError(
"Not a primitive wrapper type: " + wrapperType);
}
/**
* Cast this bsh.Primitive value to a new bsh.Primitive value This is
* usually a numeric type cast. Other cases include: A boolean can be cast
* to boolen null can be cast to any object type and remains null Attempting
* to cast a void causes an exception
*
* @param toType is the java object or primitive TYPE class
*/
public Primitive castToType(Class toType, int operation)
throws UtilEvalError {
return castPrimitive(
toType, getType()/*fromType*/, this/*fromValue*/,
false/*checkOnly*/, operation);
}
/*
Cast or check a cast of a primitive type to another type.
Normally both types are primitive (e.g. numeric), but a null value
(no type) may be cast to any type.
<p/>
@param toType is the target type of the cast. It is normally a
java primitive TYPE, but in the case of a null cast can be any object
type.
@param fromType is the java primitive TYPE type of the primitive to be
cast or null, to indicate that the fromValue was null or void.
@param fromValue is, optionally, the value to be converted. If
checkOnly is true fromValue must be null. If checkOnly is false,
fromValue must be non-null (Primitive.NULL is of course valid).
*/
static Primitive castPrimitive(
Class toType, Class fromType, Primitive fromValue,
boolean checkOnly, int operation)
throws UtilEvalError {
/*
Lots of preconditions checked here...
Once things are running smoothly we might comment these out
(That's what assertions are for).
*/
if (checkOnly && fromValue != null) {
throw new InterpreterError("bad cast param 1");
}
if (!checkOnly && fromValue == null) {
throw new InterpreterError("bad cast param 2");
}
if (fromType != null && !fromType.isPrimitive()) {
throw new InterpreterError("bad fromType:" + fromType);
}
if (fromValue == Primitive.NULL && fromType != null) {
throw new InterpreterError("inconsistent args 1");
}
if (fromValue == Primitive.VOID && fromType != Void.TYPE) {
throw new InterpreterError("inconsistent args 2");
}
// can't cast void to anything
if (fromType == Void.TYPE) {
if (checkOnly) {
return Types.INVALID_CAST;
} else {
throw Types.castError(Reflect.normalizeClassName(toType),
"void value", operation);
}
}
// unwrap Primitive fromValue to its wrapper value, etc.
Object value = null;
if (fromValue != null) {
value = fromValue.getValue();
}
if (toType.isPrimitive()) {
// Trying to cast null to primitive type?
if (fromType == null) {
if (checkOnly) {
return Types.INVALID_CAST;
} else {
throw Types.castError(
"primitive type:" + toType, "Null value", operation);
}
}
// fall through
} else {
// Trying to cast primitive to an object type
// Primitive.NULL can be cast to any object type
if (fromType == null) {
return checkOnly ? Types.VALID_CAST
: Primitive.NULL;
}
if (checkOnly) {
return Types.INVALID_CAST;
} else {
throw Types.castError(
"object type:" + toType, "primitive value", operation);
}
}
// can only cast boolean to boolean
if (fromType == Boolean.TYPE) {
if (toType != Boolean.TYPE) {
if (checkOnly) {
return Types.INVALID_CAST;
} else {
throw Types.castError(toType, fromType, operation);
}
}
return checkOnly ? Types.VALID_CAST
: fromValue;
}
// Do numeric cast
// Only allow legal Java assignment unless we're a CAST operation
if (operation == Types.ASSIGNMENT
&& !Types.isJavaAssignable(toType, fromType)) {
if (checkOnly) {
return Types.INVALID_CAST;
} else {
throw Types.castError(toType, fromType, operation);
}
}
return checkOnly ? Types.VALID_CAST
: new Primitive(castWrapper(toType, value));
}
public static boolean isWrapperType(Class type) {
return wrapperMap.get(type) != null && !type.isPrimitive();
}
/**
* Cast a primitive value represented by its java.lang wrapper type to the
* specified java.lang wrapper type. e.g. Byte(5) to Integer(5) or
* Integer(5) to Byte(5)
*
* @param toType is the java TYPE type
* @param value is the value in java.lang wrapper. value may not be null.
*/
static Object castWrapper(
Class toType, Object value) {
if (!toType.isPrimitive()) {
throw new InterpreterError("invalid type in castWrapper: " + toType);
}
if (value == null) {
throw new InterpreterError("null value in castWrapper, guard");
}
if (value instanceof Boolean) {
if (toType != Boolean.TYPE) {
throw new InterpreterError("bad wrapper cast of boolean");
} else {
return value;
}
}
// first promote char to Number type to avoid duplicating code
if (value instanceof Character) {
value = new Integer(((Character) value));
}
if (!(value instanceof Number)) {
throw new InterpreterError("bad type in cast");
}
Number number = (Number) value;
if (toType == Byte.TYPE) {
return number.byteValue();
}
if (toType == Short.TYPE) {
return number.shortValue();
}
if (toType == Character.TYPE) {
return (char) number.intValue();
}
if (toType == Integer.TYPE) {
return number.intValue();
}
if (toType == Long.TYPE) {
return number.longValue();
}
if (toType == Float.TYPE) {
return number.floatValue();
}
if (toType == Double.TYPE) {
return number.doubleValue();
}
throw new InterpreterError("error in wrapper cast");
}
}
| 36,078 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
ClassGenerator.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/ClassGenerator.java | package ehacks.bsh;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
public class ClassGenerator {
private static ClassGenerator cg;
private static final String DEBUG_DIR = System.getProperty("bsh.debugClasses");
public static ClassGenerator getClassGenerator() {
if (cg == null) {
cg = new ClassGeneratorImpl();
}
return cg;
}
/**
* Parse the BSHBlock for the class definition and generate the class.
*/
public Class generateClass(String name, Modifiers modifiers, Class[] interfaces, Class superClass, BSHBlock block, boolean isInterface, CallStack callstack, Interpreter interpreter) throws EvalError {
// Delegate to the static method
return generateClassImpl(name, modifiers, interfaces, superClass, block, isInterface, callstack, interpreter);
}
/**
* Invoke a super.method() style superclass method on an object instance.
* This is not a normal function of the Java reflection API and is provided
* by generated class accessor methods.
*/
public Object invokeSuperclassMethod(BSHClassManager bcm, Object instance, String methodName, Object[] args) throws UtilEvalError, ReflectError, InvocationTargetException {
// Delegate to the static method
return invokeSuperclassMethodImpl(bcm, instance, methodName, args);
}
/**
* Change the parent of the class instance namespace. This is currently used
* for inner class support. Note: This method will likely be removed in the
* future.
*/
// This could be static
public void setInstanceNameSpaceParent(Object instance, String className, NameSpace parent) {
This ithis = ClassGeneratorUtil.getClassInstanceThis(instance, className);
ithis.getNameSpace().setParent(parent);
}
/**
* Parse the BSHBlock for for the class definition and generate the class
* using ClassGenerator.
*/
public static Class generateClassImpl(String name, Modifiers modifiers, Class[] interfaces, Class superClass, BSHBlock block, boolean isInterface, CallStack callstack, Interpreter interpreter) throws EvalError {
// Scripting classes currently requires accessibility
// This can be eliminated with a bit more work.
try {
Capabilities.setAccessibility(true);
} catch (Capabilities.Unavailable e) {
throw new EvalError("Defining classes currently requires reflective Accessibility.", block, callstack);
}
NameSpace enclosingNameSpace = callstack.top();
String packageName = enclosingNameSpace.getPackage();
String className = enclosingNameSpace.isClass ? (enclosingNameSpace.getName() + "$" + name) : name;
String fqClassName = packageName == null ? className : packageName + "." + className;
BSHClassManager bcm = interpreter.getClassManager();
// Race condition here...
bcm.definingClass(fqClassName);
// Create the class static namespace
NameSpace classStaticNameSpace = new NameSpace(enclosingNameSpace, className);
classStaticNameSpace.isClass = true;
callstack.push(classStaticNameSpace);
// Evaluate any inner class class definitions in the block
// effectively recursively call this method for contained classes first
block.evalBlock(callstack, interpreter, true/*override*/, ClassNodeFilter.CLASSCLASSES);
// Generate the type for our class
Variable[] variables = getDeclaredVariables(block, callstack, interpreter, packageName);
DelayedEvalBshMethod[] methods = getDeclaredMethods(block, callstack, interpreter, packageName);
ClassGeneratorUtil classGenerator = new ClassGeneratorUtil(modifiers, className, packageName, superClass, interfaces, variables, methods, classStaticNameSpace, isInterface);
byte[] code = classGenerator.generateClass();
// if debug, write out the class file to debugClasses directory
if (DEBUG_DIR != null) {
try {
try (FileOutputStream out = new FileOutputStream(DEBUG_DIR + '/' + className + ".class")) {
out.write(code);
}
} catch (IOException e) {
throw new IllegalStateException("cannot create file " + DEBUG_DIR + '/' + className + ".class", e);
}
}
// Define the new class in the classloader
Class genClass = bcm.defineClass(fqClassName, code);
// import the unq name into parent
enclosingNameSpace.importClass(fqClassName.replace('$', '.'));
try {
classStaticNameSpace.setLocalVariable(ClassGeneratorUtil.BSHINIT, block, false/*strictJava*/);
} catch (UtilEvalError e) {
throw new InterpreterError("unable to init static: " + e);
}
// Give the static space its class static import
// important to do this after all classes are defined
classStaticNameSpace.setClassStatic(genClass);
// evaluate the static portion of the block in the static space
block.evalBlock(callstack, interpreter, true/*override*/, ClassNodeFilter.CLASSSTATIC);
callstack.pop();
if (!genClass.isInterface()) {
// Set the static bsh This callback
String bshStaticFieldName = ClassGeneratorUtil.BSHSTATIC + className;
try {
LHS lhs = Reflect.getLHSStaticField(genClass, bshStaticFieldName);
lhs.assign(classStaticNameSpace.getThis(interpreter), false/*strict*/);
} catch (Exception e) {
throw new InterpreterError("Error in class gen setup: " + e);
}
}
bcm.doneDefiningClass(fqClassName);
return genClass;
}
static Variable[] getDeclaredVariables(BSHBlock body, CallStack callstack, Interpreter interpreter, String defaultPackage) {
List<Variable> vars = new ArrayList<>();
for (int child = 0; child < body.jjtGetNumChildren(); child++) {
SimpleNode node = (SimpleNode) body.jjtGetChild(child);
if (node instanceof BSHTypedVariableDeclaration) {
BSHTypedVariableDeclaration tvd = (BSHTypedVariableDeclaration) node;
Modifiers modifiers = tvd.modifiers;
String type = tvd.getTypeDescriptor(callstack, interpreter, defaultPackage);
BSHVariableDeclarator[] vardec = tvd.getDeclarators();
for (BSHVariableDeclarator aVardec : vardec) {
String name = aVardec.name;
try {
Variable var = new Variable(name, type, null/*value*/, modifiers);
vars.add(var);
} catch (UtilEvalError e) {
// value error shouldn't happen
}
}
}
}
return vars.toArray(new Variable[vars.size()]);
}
static DelayedEvalBshMethod[] getDeclaredMethods(BSHBlock body, CallStack callstack, Interpreter interpreter, String defaultPackage) throws EvalError {
List<DelayedEvalBshMethod> methods = new ArrayList<>();
for (int child = 0; child < body.jjtGetNumChildren(); child++) {
SimpleNode node = (SimpleNode) body.jjtGetChild(child);
if (node instanceof BSHMethodDeclaration) {
BSHMethodDeclaration md = (BSHMethodDeclaration) node;
md.insureNodesParsed();
Modifiers modifiers = md.modifiers;
String name = md.name;
String returnType = md.getReturnTypeDescriptor(callstack, interpreter, defaultPackage);
BSHReturnType returnTypeNode = md.getReturnTypeNode();
BSHFormalParameters paramTypesNode = md.paramsNode;
String[] paramTypes = paramTypesNode.getTypeDescriptors(callstack, interpreter, defaultPackage);
DelayedEvalBshMethod bm = new DelayedEvalBshMethod(name, returnType, returnTypeNode, md.paramsNode.getParamNames(), paramTypes, paramTypesNode, md.blockNode, null/*declaringNameSpace*/, modifiers, callstack, interpreter);
methods.add(bm);
}
}
return methods.toArray(new DelayedEvalBshMethod[methods.size()]);
}
/**
* A node filter that filters nodes for either a class body static
* initializer or instance initializer. In the static case only static
* members are passed, etc.
*/
static class ClassNodeFilter implements BSHBlock.NodeFilter {
public static final int STATIC = 0, INSTANCE = 1, CLASSES = 2;
public static ClassNodeFilter CLASSSTATIC = new ClassNodeFilter(STATIC);
public static ClassNodeFilter CLASSINSTANCE = new ClassNodeFilter(INSTANCE);
public static ClassNodeFilter CLASSCLASSES = new ClassNodeFilter(CLASSES);
int context;
private ClassNodeFilter(int context) {
this.context = context;
}
@Override
public boolean isVisible(SimpleNode node) {
if (context == CLASSES) {
return node instanceof BSHClassDeclaration;
}
// Only show class decs in CLASSES
if (node instanceof BSHClassDeclaration) {
return false;
}
if (context == STATIC) {
return isStatic(node);
}
if (context == INSTANCE) {
return !isStatic(node);
}
// ALL
return true;
}
boolean isStatic(SimpleNode node) {
if (node instanceof BSHTypedVariableDeclaration) {
return ((BSHTypedVariableDeclaration) node).modifiers != null && ((BSHTypedVariableDeclaration) node).modifiers.hasModifier("static");
}
if (node instanceof BSHMethodDeclaration) {
return ((BSHMethodDeclaration) node).modifiers != null && ((BSHMethodDeclaration) node).modifiers.hasModifier("static");
}
// need to add static block here
if (node instanceof BSHBlock) {
return false;
}
return false;
}
}
public static Object invokeSuperclassMethodImpl(BSHClassManager bcm, Object instance, String methodName, Object[] args) throws UtilEvalError, ReflectError, InvocationTargetException {
String superName = ClassGeneratorUtil.BSHSUPER + methodName;
// look for the specially named super delegate method
Class clas = instance.getClass();
Method superMethod = Reflect.resolveJavaMethod(bcm, clas, superName, Types.getTypes(args), false/*onlyStatic*/);
if (superMethod != null) {
return Reflect.invokeMethod(superMethod, instance, args);
}
// No super method, try to invoke regular method
// could be a superfluous "super." which is legal.
Class superClass = clas.getSuperclass();
superMethod = Reflect.resolveExpectedJavaMethod(bcm, superClass, instance, methodName, args, false/*onlyStatic*/);
return Reflect.invokeMethod(superMethod, instance, args);
}
}
| 11,303 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHTypedVariableDeclaration.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHTypedVariableDeclaration.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
class BSHTypedVariableDeclaration extends SimpleNode {
public Modifiers modifiers;
BSHTypedVariableDeclaration(int id) {
super(id);
}
private BSHType getTypeNode() {
return ((BSHType) jjtGetChild(0));
}
Class evalType(CallStack callstack, Interpreter interpreter)
throws EvalError {
BSHType typeNode = getTypeNode();
return typeNode.getType(callstack, interpreter);
}
BSHVariableDeclarator[] getDeclarators() {
int n = jjtGetNumChildren();
int start = 1;
BSHVariableDeclarator[] bvda = new BSHVariableDeclarator[n - start];
for (int i = start; i < n; i++) {
bvda[i - start] = (BSHVariableDeclarator) jjtGetChild(i);
}
return bvda;
}
/**
* evaluate the type and one or more variable declarators, e.g.: int a, b=5,
* c;
*/
@Override
public Object eval(CallStack callstack, Interpreter interpreter)
throws EvalError {
try {
NameSpace namespace = callstack.top();
BSHType typeNode = getTypeNode();
Class type = typeNode.getType(callstack, interpreter);
BSHVariableDeclarator[] bvda = getDeclarators();
for (int i = 0; i < bvda.length; i++) {
BSHVariableDeclarator dec = bvda[i];
// Type node is passed down the chain for array initializers
// which need it under some circumstances
Object value = dec.eval(typeNode, callstack, interpreter);
try {
namespace.setTypedVariable(
dec.name, type, value, modifiers);
} catch (UtilEvalError e) {
throw e.toEvalError(this, callstack);
}
}
} catch (EvalError e) {
e.reThrow("Typed variable declaration");
}
return Primitive.VOID;
}
public String getTypeDescriptor(
CallStack callstack, Interpreter interpreter, String defaultPackage) {
return getTypeNode().getTypeDescriptor(
callstack, interpreter, defaultPackage);
}
}
| 4,743 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHImportDeclaration.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHImportDeclaration.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
class BSHImportDeclaration extends SimpleNode {
public boolean importPackage;
public boolean staticImport;
public boolean superImport;
BSHImportDeclaration(int id) {
super(id);
}
@Override
public Object eval(CallStack callstack, Interpreter interpreter)
throws EvalError {
NameSpace namespace = callstack.top();
if (superImport) {
try {
namespace.doSuperImport();
} catch (UtilEvalError e) {
throw e.toEvalError(this, callstack);
}
} else {
if (staticImport) {
if (importPackage) {
Class clas = ((BSHAmbiguousName) jjtGetChild(0)).toClass(
callstack, interpreter);
namespace.importStatic(clas);
} else {
throw new EvalError(
"static field imports not supported yet",
this, callstack);
}
} else {
String name = ((BSHAmbiguousName) jjtGetChild(0)).text;
if (importPackage) {
namespace.importPackage(name);
} else {
namespace.importClass(name);
}
}
}
return Primitive.VOID;
}
}
| 3,923 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHMethod.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHMethod.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* This represents an instance of a bsh method declaration in a particular
* namespace. This is a thin wrapper around the BSHMethodDeclaration with a
* pointer to the declaring namespace.
* <p>
*
* When a method is located in a subordinate namespace or invoked from an
* arbitrary namespace it must nontheless execute with its 'super' as the
* context in which it was declared.
* <p/>
*/
/*
Note: this method incorrectly caches the method structure. It needs to
be cleared when the classloader changes.
*/
public class BSHMethod
implements java.io.Serializable {
/*
This is the namespace in which the method is set.
It is a back-reference for the node, which needs to execute under this
namespace. It is not necessary to declare this transient, because
we can only be saved as part of our namespace anyway... (currently).
*/
NameSpace declaringNameSpace;
// Begin Method components
Modifiers modifiers;
private String name;
private Class creturnType;
// Arguments
private String[] paramNames;
private int numArgs;
private Class[] cparamTypes;
// Scripted method body
BSHBlock methodBody;
// Java Method, for a BshObject that delegates to a real Java method
private Method javaMethod;
private Object javaObject;
// End method components
BSHMethod(
BSHMethodDeclaration method,
NameSpace declaringNameSpace, Modifiers modifiers) {
this(method.name, method.returnType, method.paramsNode.getParamNames(),
method.paramsNode.paramTypes, method.blockNode, declaringNameSpace,
modifiers);
}
BSHMethod(
String name, Class returnType, String[] paramNames,
Class[] paramTypes, BSHBlock methodBody,
NameSpace declaringNameSpace, Modifiers modifiers
) {
this.name = name;
this.creturnType = returnType;
this.paramNames = paramNames;
if (paramNames != null) {
this.numArgs = paramNames.length;
}
this.cparamTypes = paramTypes;
this.methodBody = methodBody;
this.declaringNameSpace = declaringNameSpace;
this.modifiers = modifiers;
}
/*
Create a BshMethod that delegates to a real Java method upon invocation.
This is used to represent imported object methods.
*/
BSHMethod(Method method, Object object) {
this(method.getName(), method.getReturnType(), null/*paramNames*/,
method.getParameterTypes(), null/*method.block*/,
null/*declaringNameSpace*/, null/*modifiers*/);
this.javaMethod = method;
this.javaObject = object;
}
/**
* Get the argument types of this method. loosely typed (untyped) arguments
* will be represented by null argument types.
*/
/*
Note: bshmethod needs to re-evaluate arg types here
This is broken.
*/
public Class[] getParameterTypes() {
return cparamTypes;
}
public String[] getParameterNames() {
return paramNames;
}
/**
* Get the return type of the method.
*
* @return Returns null for a loosely typed return value, Void.TYPE for a
* void return type, or the Class of the type.
*/
/*
Note: bshmethod needs to re-evaluate the method return type here.
This is broken.
*/
public Class getReturnType() {
return creturnType;
}
public Modifiers getModifiers() {
return modifiers;
}
public String getName() {
return name;
}
/**
* Invoke the declared method with the specified arguments and interpreter
* reference. This is the simplest form of invoke() for BshMethod intended
* to be used in reflective style access to bsh scripts.
*/
public Object invoke(
Object[] argValues, Interpreter interpreter)
throws EvalError {
return invoke(argValues, interpreter, null, null, false);
}
/**
* Invoke the bsh method with the specified args, interpreter ref, and
* callstack. callerInfo is the node representing the method invocation It
* is used primarily for debugging in order to provide access to the text of
* the construct that invoked the method through the namespace.
*
* @param callerInfo is the BeanShell AST node representing the method
* invocation. It is used to print the line number and text of errors in
* EvalError exceptions. If the node is null here error messages may not be
* able to point to the precise location and text of the error.
* @param callstack is the callstack. If callstack is null a new one will be
* created with the declaring namespace of the method on top of the stack
* (i.e. it will look for purposes of the method invocation like the method
* call occurred in the declaring (enclosing) namespace in which the method
* is defined).
*/
public Object invoke(
Object[] argValues, Interpreter interpreter, CallStack callstack,
SimpleNode callerInfo)
throws EvalError {
return invoke(argValues, interpreter, callstack, callerInfo, false);
}
/**
* Invoke the bsh method with the specified args, interpreter ref, and
* callstack. callerInfo is the node representing the method invocation It
* is used primarily for debugging in order to provide access to the text of
* the construct that invoked the method through the namespace.
*
* @param callerInfo is the BeanShell AST node representing the method
* invocation. It is used to print the line number and text of errors in
* EvalError exceptions. If the node is null here error messages may not be
* able to point to the precise location and text of the error.
* @param callstack is the callstack. If callstack is null a new one will be
* created with the declaring namespace of the method on top of the stack
* (i.e. it will look for purposes of the method invocation like the method
* call occurred in the declaring (enclosing) namespace in which the method
* is defined).
* @param overrideNameSpace When true the method is executed in the
* namespace on the top of the stack instead of creating its own local
* namespace. This allows it to be used in constructors.
*/
Object invoke(
Object[] argValues, Interpreter interpreter, CallStack callstack,
SimpleNode callerInfo, boolean overrideNameSpace)
throws EvalError {
if (argValues != null) {
for (int i = 0; i < argValues.length; i++) {
if (argValues[i] == null) {
throw new Error("HERE!");
}
}
}
if (javaMethod != null) {
try {
return Reflect.invokeMethod(
javaMethod, javaObject, argValues);
} catch (ReflectError e) {
throw new EvalError(
"Error invoking Java method: " + e, callerInfo, callstack);
} catch (InvocationTargetException e2) {
throw new TargetError(
"Exception invoking imported object method.",
e2, callerInfo, callstack, true/*isNative*/);
}
}
// is this a syncrhonized method?
if (modifiers != null && modifiers.hasModifier("synchronized")) {
// The lock is our declaring namespace's This reference
// (the method's 'super'). Or in the case of a class it's the
// class instance.
Object lock;
if (declaringNameSpace.isClass) {
try {
lock = declaringNameSpace.getClassInstance();
} catch (UtilEvalError e) {
throw new InterpreterError(
"Can't get class instance for synchronized method.");
}
} else {
lock = declaringNameSpace.getThis(interpreter); // ???
}
synchronized (lock) {
return invokeImpl(
argValues, interpreter, callstack,
callerInfo, overrideNameSpace);
}
} else {
return invokeImpl(argValues, interpreter, callstack, callerInfo,
overrideNameSpace);
}
}
private Object invokeImpl(
Object[] argValues, Interpreter interpreter, CallStack callstack,
SimpleNode callerInfo, boolean overrideNameSpace)
throws EvalError {
Class returnType = getReturnType();
Class[] paramTypes = getParameterTypes();
// If null callstack
if (callstack == null) {
callstack = new CallStack(declaringNameSpace);
}
if (argValues == null) {
argValues = new Object[]{};
}
// Cardinality (number of args) mismatch
if (argValues.length != numArgs) {
/*
// look for help string
try {
// should check for null namespace here
String help =
(String)declaringNameSpace.get(
"bsh.help."+name, interpreter );
interpreter.println(help);
return Primitive.VOID;
} catch ( Exception e ) {
throw eval error
}
*/
throw new EvalError(
"Wrong number of arguments for local method: "
+ name, callerInfo, callstack);
}
// Make the local namespace for the method invocation
NameSpace localNameSpace;
if (overrideNameSpace) {
localNameSpace = callstack.top();
} else {
localNameSpace = new NameSpace(declaringNameSpace, name);
localNameSpace.isMethod = true;
}
// should we do this for both cases above?
localNameSpace.setNode(callerInfo);
// set the method parameters in the local namespace
for (int i = 0; i < numArgs; i++) {
// Set typed variable
if (paramTypes[i] != null) {
try {
argValues[i]
= //Types.getAssignableForm( argValues[i], paramTypes[i] );
Types.castObject(argValues[i], paramTypes[i], Types.ASSIGNMENT);
} catch (UtilEvalError e) {
throw new EvalError(
"Invalid argument: "
+ "`" + paramNames[i] + "'" + " for method: "
+ name + " : "
+ e.getMessage(), callerInfo, callstack);
}
try {
localNameSpace.setTypedVariable(paramNames[i],
paramTypes[i], argValues[i], null/*modifiers*/);
} catch (UtilEvalError e2) {
throw e2.toEvalError("Typed method parameter assignment",
callerInfo, callstack);
}
} // Set untyped variable
else // untyped param
{
// getAssignable would catch this for typed param
if (argValues[i] == Primitive.VOID) {
throw new EvalError(
"Undefined variable or class name, parameter: "
+ paramNames[i] + " to method: "
+ name, callerInfo, callstack);
} else {
try {
localNameSpace.setLocalVariable(
paramNames[i], argValues[i],
interpreter.getStrictJava());
} catch (UtilEvalError e3) {
throw e3.toEvalError(callerInfo, callstack);
}
}
}
}
// Push the new namespace on the call stack
if (!overrideNameSpace) {
callstack.push(localNameSpace);
}
// Invoke the block, overriding namespace with localNameSpace
Object ret = methodBody.eval(
callstack, interpreter, true/*override*/);
// save the callstack including the called method, just for error mess
CallStack returnStack = callstack.copy();
// Get back to caller namespace
if (!overrideNameSpace) {
callstack.pop();
}
ReturnControl retControl = null;
if (ret instanceof ReturnControl) {
retControl = (ReturnControl) ret;
// Method body can only use 'return' statment type return control.
if (retControl.kind == ReturnControl.RETURN) {
ret = ((ReturnControl) ret).value;
} else // retControl.returnPoint is the Node of the return statement
{
throw new EvalError("'continue' or 'break' in method body",
retControl.returnPoint, returnStack);
}
// Check for explicit return of value from void method type.
// retControl.returnPoint is the Node of the return statement
if (returnType == Void.TYPE && ret != Primitive.VOID) {
throw new EvalError("Cannot return value from void method",
retControl.returnPoint, returnStack);
}
}
if (returnType != null) {
// If return type void, return void as the value.
if (returnType == Void.TYPE) {
return Primitive.VOID;
}
// return type is a class
try {
ret
= // Types.getAssignableForm( ret, (Class)returnType );
Types.castObject(ret, returnType, Types.ASSIGNMENT);
} catch (UtilEvalError e) {
// Point to return statement point if we had one.
// (else it was implicit return? What's the case here?)
SimpleNode node = callerInfo;
if (retControl != null) {
node = retControl.returnPoint;
}
throw e.toEvalError(
"Incorrect type returned from method: "
+ name + e.getMessage(), node, callstack);
}
}
return ret;
}
public boolean hasModifier(String name) {
return modifiers != null && modifiers.hasModifier(name);
}
@Override
public String toString() {
return "Scripted Method: "
+ StringUtil.methodString(name, getParameterTypes());
}
// equal signature
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (o == this) {
return true;
}
if (o.getClass() == this.getClass()) {
BSHMethod m = (BSHMethod) o;
if (!name.equals(m.name) || numArgs != m.numArgs) {
return false;
}
for (int i = 0; i < numArgs; i++) {
if (!equal(cparamTypes[i], m.cparamTypes[i])) {
return false;
}
}
return true;
}
return false;
}
private static boolean equal(Object obj1, Object obj2) {
return obj1 == null ? obj2 == null : obj1.equals(obj2);
}
@Override
public int hashCode() {
int h = name.hashCode();
for (Class<?> cparamType : cparamTypes) {
h = h * 31 + cparamType.hashCode();
}
return h;
}
}
| 18,323 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
UtilEvalError.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/UtilEvalError.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
/**
* UtilEvalError is an error corresponding to an EvalError but thrown by a
* utility or other class that does not have the caller context (Node) available
* to it. A normal EvalError must supply the caller Node in order for error
* messages to be pinned to the correct line and location in the script.
* UtilEvalError is a checked exception that is *not* a subtype of EvalError,
* but instead must be caught and rethrown as an EvalError by the a nearest
* location with context. The method toEvalError( Node ) should be used to throw
* the EvalError, supplying the node.
* <p>
*
* To summarize: Utilities throw UtilEvalError. ASTs throw EvalError. ASTs catch
* UtilEvalError and rethrow it as EvalError using toEvalError( Node ).
* <p>
*
* Philosophically, EvalError and UtilEvalError corrospond to RuntimeException.
* However they are constrained in this way in order to add the context for
* error reporting.
*
* @see UtilTargetError
*/
public class UtilEvalError extends Exception {
protected UtilEvalError() {
}
public UtilEvalError(String s) {
super(s);
}
public UtilEvalError(String s, Throwable cause) {
super(s, cause);
}
/**
* Re-throw as an eval error, prefixing msg to the message and specifying
* the node. If a node already exists the addNode is ignored.
*
* @see #setNode( bsh.SimpleNode )
* <p>
* @param msg may be null for no additional message.
*/
public EvalError toEvalError(
String msg, SimpleNode node, CallStack callstack) {
if (Interpreter.DEBUG) {
}
if (msg == null) {
msg = "";
} else {
msg += ": ";
}
return new EvalError(msg + getMessage(), node, callstack, this);
}
public EvalError toEvalError(SimpleNode node, CallStack callstack) {
return toEvalError(null, node, callstack);
}
}
| 4,479 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
ExternalNameSpace.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/ExternalNameSpace.java | package ehacks.bsh;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* A namespace which maintains an external map of values held in variables in
* its scope. This mechanism provides a standard collections based interface to
* the namespace as well as a convenient way to export and view values of the
* namespace without the ordinary BeanShell wrappers.
* </p>
*
* Variables are maintained internally in the normal fashion to support
* meta-information (such as variable type and visibility modifiers), but
* exported and imported in a synchronized way. Variables are exported each time
* they are written by BeanShell. Imported variables from the map appear in the
* BeanShell namespace as untyped variables with no modifiers and shadow any
* previously defined variables in the scope.
* <p/>
*
* Note: this class is inherentely dependent on Java 1.2, however it is not used
* directly by the core as other than type NameSpace, so no dependency is
* introduced.
*/
/*
Implementation notes: bsh methods are not currently exported to the
external namespace. All that would be required to add this is to override
setMethod() and provide a friendlier view than vector (currently used) for
overloaded forms (perhaps a map by method SignatureKey).
*/
public class ExternalNameSpace extends NameSpace {
private Map<String, Object> externalMap;
public ExternalNameSpace() {
this(null, "External Map Namespace", null);
}
/**
*/
public ExternalNameSpace(NameSpace parent, String name, Map<String, Object> externalMap) {
super(parent, name);
if (externalMap == null) {
externalMap = new HashMap<>();
}
this.externalMap = externalMap;
}
/**
* Get the map view of this namespace.
*/
public Map<String, Object> getMap() {
return Collections.unmodifiableMap(externalMap);
}
/**
* Set the external Map which to which this namespace synchronizes. The
* previous external map is detached from this namespace. Previous map
* values are retained in the external map, but are removed from the
* BeanShell namespace.
*/
public void setMap(Map<String, Object> map) {
// Detach any existing namespace to preserve it, then clear this
// namespace and set the new one
this.externalMap = null;
clear();
this.externalMap = map;
}
/**
*/
@Override
void setVariable(
String name, Object value, boolean strictJava, boolean recurse)
throws UtilEvalError {
super.setVariable(name, value, strictJava, recurse);
putExternalMap(name, value);
}
/**
*/
@Override
public void unsetVariable(String name) {
super.unsetVariable(name);
externalMap.remove(name);
}
/**
*/
@Override
public String[] getVariableNames() {
// union of the names in the internal namespace and external map
Set<String> nameSet = new HashSet<>();
String[] nsNames = super.getVariableNames();
nameSet.addAll(Arrays.asList(nsNames));
nameSet.addAll(externalMap.keySet());
return nameSet.toArray(new String[nameSet.size()]);
}
/**
*/
/*
Notes: This implmenetation of getVariableImpl handles the following
cases:
1) var in map not in local scope - var was added through map
2) var in map and in local scope - var was added through namespace
3) var not in map but in local scope - var was removed via map
4) var not in map and not in local scope - non-existent var
*/
@Override
protected Variable getVariableImpl(String name, boolean recurse)
throws UtilEvalError {
// check the external map for the variable name
Object value = externalMap.get(name);
if (value == null && externalMap.containsKey(name)) {
value = Primitive.NULL;
}
Variable var;
if (value == null) {
// The var is not in external map and it should therefore not be
// found in local scope (it may have been removed via the map).
// Clear it prophalactically.
super.unsetVariable(name);
// Search parent for var if applicable.
var = super.getVariableImpl(name, recurse);
} else {
// Var in external map may be found in local scope with type and
// modifier info.
Variable localVar = super.getVariableImpl(name, false);
// If not in local scope then it was added via the external map,
// we'll wrap it and pass it along. Else we'll use the local
// version.
if (localVar == null) {
var = new Variable(name, (Class) null, value, null);
} else {
var = localVar;
}
}
return var;
}
/**
*/
/*
Note: the meaning of getDeclaredVariables() is not entirely clear, but
the name (and current usage in class generation support) suggests that
untyped variables should not be inclueded. Therefore we do not
currently have to add the external names here.
*/
@Override
public Variable[] getDeclaredVariables() {
return super.getDeclaredVariables();
}
/**
*/
@Override
public void setTypedVariable(
String name, Class type, Object value, Modifiers modifiers)
throws UtilEvalError {
super.setTypedVariable(name, type, value, modifiers);
putExternalMap(name, value);
}
/*
Note: we could override this method to allow bsh methods to appear in
the external map.
*/
@Override
public void setMethod(BSHMethod method)
throws UtilEvalError {
super.setMethod(method);
}
/*
Note: kind of far-fetched, but... we could override this method to
allow bsh methods to be inserted into this namespace via the map.
*/
@Override
public BSHMethod getMethod(
String name, Class[] sig, boolean declaredOnly)
throws UtilEvalError {
return super.getMethod(name, sig, declaredOnly);
}
/*
Note: this method should be overridden to add the names from the
external map, as is done in getVariableNames();
*/
@Override
protected void getAllNamesAux(List<String> list) {
super.getAllNamesAux(list);
}
/**
* Clear all variables, methods, and imports from this namespace and clear
* all values from the external map (via Map clear()).
*/
@Override
public void clear() {
super.clear();
externalMap.clear();
}
/**
* Place an unwrapped value in the external map. BeanShell primitive types
* are represented by their object wrappers, so it is not possible to
* differentiate between wrapper types and primitive types via the external
* Map.
*/
protected void putExternalMap(String name, Object value) {
if (value instanceof Variable) {
try {
value = unwrapVariable((Variable) value);
} catch (UtilEvalError ute) {
// There should be no case for this. unwrapVariable throws
// UtilEvalError in some cases where it holds an LHS or array
// index.
throw new InterpreterError("unexpected UtilEvalError");
}
}
if (value instanceof Primitive) {
value = Primitive.unwrap(value);
}
externalMap.put(name, value);
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone(); //To change body of generated methods, choose Tools | Templates.
}
}
| 7,913 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
Constants.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/Constants.java | /** *
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (C) 2000 INRIA, France Telecom
* Copyright (C) 2002 France Telecom
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact: [email protected]
*
* Author: Eric Bruneton
*/
package ehacks.bsh;
/**
* Defines the JVM opcodes, access flags and array type codes. This interface
* does not define all the JVM opcodes because some opcodes are automatically
* handled. For example, the xLOAD and xSTORE opcodes are automatically replaced
* by xLOAD_n and xSTORE_n opcodes when possible. The xLOAD_n and xSTORE_n
* opcodes are therefore not defined in this interface. Likewise for LDC,
* automatically replaced by LDC_W or LDC2_W when necessary, WIDE, GOTO_W and
* JSR_W.
*/
public interface Constants {
// access flags
int ACC_PUBLIC = 1;
int ACC_PRIVATE = 2;
int ACC_PROTECTED = 4;
int ACC_STATIC = 8;
int ACC_FINAL = 16;
int ACC_SYNCHRONIZED = 32;
int ACC_VOLATILE = 64;
int ACC_TRANSIENT = 128;
int ACC_NATIVE = 256;
int ACC_INTERFACE = 512;
int ACC_ABSTRACT = 1024;
int ACC_STRICT = 2048;
int ACC_SUPER = 32;
int ACC_SYNTHETIC = 65536;
int ACC_DEPRECATED = 131072;
// types for NEWARRAY
int T_BOOLEAN = 4;
int T_CHAR = 5;
int T_FLOAT = 6;
int T_DOUBLE = 7;
int T_BYTE = 8;
int T_SHORT = 9;
int T_INT = 10;
int T_LONG = 11;
// opcodes // visit method (- = idem)
int NOP = 0; // visitInsn
int ACONST_NULL = 1; // -
int ICONST_M1 = 2; // -
int ICONST_0 = 3; // -
int ICONST_1 = 4; // -
int ICONST_2 = 5; // -
int ICONST_3 = 6; // -
int ICONST_4 = 7; // -
int ICONST_5 = 8; // -
int LCONST_0 = 9; // -
int LCONST_1 = 10; // -
int FCONST_0 = 11; // -
int FCONST_1 = 12; // -
int FCONST_2 = 13; // -
int DCONST_0 = 14; // -
int DCONST_1 = 15; // -
int BIPUSH = 16; // visitIntInsn
int SIPUSH = 17; // -
int LDC = 18; // visitLdcInsn
//int LDC_W = 19; // -
//int LDC2_W = 20; // -
int ILOAD = 21; // visitVarInsn
int LLOAD = 22; // -
int FLOAD = 23; // -
int DLOAD = 24; // -
int ALOAD = 25; // -
//int ILOAD_0 = 26; // -
//int ILOAD_1 = 27; // -
//int ILOAD_2 = 28; // -
//int ILOAD_3 = 29; // -
//int LLOAD_0 = 30; // -
//int LLOAD_1 = 31; // -
//int LLOAD_2 = 32; // -
//int LLOAD_3 = 33; // -
//int FLOAD_0 = 34; // -
//int FLOAD_1 = 35; // -
//int FLOAD_2 = 36; // -
//int FLOAD_3 = 37; // -
//int DLOAD_0 = 38; // -
//int DLOAD_1 = 39; // -
//int DLOAD_2 = 40; // -
//int DLOAD_3 = 41; // -
//int ALOAD_0 = 42; // -
//int ALOAD_1 = 43; // -
//int ALOAD_2 = 44; // -
//int ALOAD_3 = 45; // -
int IALOAD = 46; // visitInsn
int LALOAD = 47; // -
int FALOAD = 48; // -
int DALOAD = 49; // -
int AALOAD = 50; // -
int BALOAD = 51; // -
int CALOAD = 52; // -
int SALOAD = 53; // -
int ISTORE = 54; // visitVarInsn
int LSTORE = 55; // -
int FSTORE = 56; // -
int DSTORE = 57; // -
int ASTORE = 58; // -
//int ISTORE_0 = 59; // -
//int ISTORE_1 = 60; // -
//int ISTORE_2 = 61; // -
//int ISTORE_3 = 62; // -
//int LSTORE_0 = 63; // -
//int LSTORE_1 = 64; // -
//int LSTORE_2 = 65; // -
//int LSTORE_3 = 66; // -
//int FSTORE_0 = 67; // -
//int FSTORE_1 = 68; // -
//int FSTORE_2 = 69; // -
//int FSTORE_3 = 70; // -
//int DSTORE_0 = 71; // -
//int DSTORE_1 = 72; // -
//int DSTORE_2 = 73; // -
//int DSTORE_3 = 74; // -
//int ASTORE_0 = 75; // -
//int ASTORE_1 = 76; // -
//int ASTORE_2 = 77; // -
//int ASTORE_3 = 78; // -
int IASTORE = 79; // visitInsn
int LASTORE = 80; // -
int FASTORE = 81; // -
int DASTORE = 82; // -
int AASTORE = 83; // -
int BASTORE = 84; // -
int CASTORE = 85; // -
int SASTORE = 86; // -
int POP = 87; // -
int POP2 = 88; // -
int DUP = 89; // -
int DUP_X1 = 90; // -
int DUP_X2 = 91; // -
int DUP2 = 92; // -
int DUP2_X1 = 93; // -
int DUP2_X2 = 94; // -
int SWAP = 95; // -
int IADD = 96; // -
int LADD = 97; // -
int FADD = 98; // -
int DADD = 99; // -
int ISUB = 100; // -
int LSUB = 101; // -
int FSUB = 102; // -
int DSUB = 103; // -
int IMUL = 104; // -
int LMUL = 105; // -
int FMUL = 106; // -
int DMUL = 107; // -
int IDIV = 108; // -
int LDIV = 109; // -
int FDIV = 110; // -
int DDIV = 111; // -
int IREM = 112; // -
int LREM = 113; // -
int FREM = 114; // -
int DREM = 115; // -
int INEG = 116; // -
int LNEG = 117; // -
int FNEG = 118; // -
int DNEG = 119; // -
int ISHL = 120; // -
int LSHL = 121; // -
int ISHR = 122; // -
int LSHR = 123; // -
int IUSHR = 124; // -
int LUSHR = 125; // -
int IAND = 126; // -
int LAND = 127; // -
int IOR = 128; // -
int LOR = 129; // -
int IXOR = 130; // -
int LXOR = 131; // -
int IINC = 132; // visitIincInsn
int I2L = 133; // visitInsn
int I2F = 134; // -
int I2D = 135; // -
int L2I = 136; // -
int L2F = 137; // -
int L2D = 138; // -
int F2I = 139; // -
int F2L = 140; // -
int F2D = 141; // -
int D2I = 142; // -
int D2L = 143; // -
int D2F = 144; // -
int I2B = 145; // -
int I2C = 146; // -
int I2S = 147; // -
int LCMP = 148; // -
int FCMPL = 149; // -
int FCMPG = 150; // -
int DCMPL = 151; // -
int DCMPG = 152; // -
int IFEQ = 153; // visitJumpInsn
int IFNE = 154; // -
int IFLT = 155; // -
int IFGE = 156; // -
int IFGT = 157; // -
int IFLE = 158; // -
int IF_ICMPEQ = 159; // -
int IF_ICMPNE = 160; // -
int IF_ICMPLT = 161; // -
int IF_ICMPGE = 162; // -
int IF_ICMPGT = 163; // -
int IF_ICMPLE = 164; // -
int IF_ACMPEQ = 165; // -
int IF_ACMPNE = 166; // -
int GOTO = 167; // -
int JSR = 168; // -
int RET = 169; // visitVarInsn
int TABLESWITCH = 170; // visiTableSwitchInsn
int LOOKUPSWITCH = 171; // visitLookupSwitch
int IRETURN = 172; // visitInsn
int LRETURN = 173; // -
int FRETURN = 174; // -
int DRETURN = 175; // -
int ARETURN = 176; // -
int RETURN = 177; // -
int GETSTATIC = 178; // visitFieldInsn
int PUTSTATIC = 179; // -
int GETFIELD = 180; // -
int PUTFIELD = 181; // -
int INVOKEVIRTUAL = 182; // visitMethodInsn
int INVOKESPECIAL = 183; // -
int INVOKESTATIC = 184; // -
int INVOKEINTERFACE = 185; // -
//int UNUSED = 186; // NOT VISITED
int NEW = 187; // visitTypeInsn
int NEWARRAY = 188; // visitIntInsn
int ANEWARRAY = 189; // visitTypeInsn
int ARRAYLENGTH = 190; // visitInsn
int ATHROW = 191; // -
int CHECKCAST = 192; // visitTypeInsn
int INSTANCEOF = 193; // -
int MONITORENTER = 194; // visitInsn
int MONITOREXIT = 195; // -
//int WIDE = 196; // NOT VISITED
int MULTIANEWARRAY = 197; // visitMultiANewArrayInsn
int IFNULL = 198; // visitJumpInsn
int IFNONNULL = 199; // -
//int GOTO_W = 200; // -
//int JSR_W = 201; // -
}
| 9,965 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
NameSpace.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/NameSpace.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A namespace in which methods, variables, and imports (class names) live. This
* is package public because it is used in the implementation of some bsh
* commands. However for normal use you should be using methods on
* bsh.Interpreter to interact with your scripts.
* <p>
*
* A bsh.This object is a thin layer over a NameSpace that associates it with an
* Interpreter instance. Together they comprise a Bsh scripted object context.
* <p>
*/
/*
Thanks to Slava Pestov (of jEdit fame) for import caching enhancements.
Note: This class has gotten too big. It should be broken down a bit.
*/
// not at all thread-safe - fschmidt
public class NameSpace implements Serializable, BSHClassManager.Listener, NameSource, Cloneable {
private static final long serialVersionUID = 5004976946651004751L;
public static final NameSpace JAVACODE
= new NameSpace((BSHClassManager) null, "Called from compiled Java code.");
static {
JAVACODE.isMethod = true;
}
// Begin instance data
// Note: if we add something here we should reset it in the clear() method.
/**
* The name of this namespace. If the namespace is a method body namespace
* then this is the name of the method. If it's a class or class instance
* then it's the name of the class.
*/
private String nsName;
private NameSpace parent;
private Map<String, Variable> variables;
private Map<String, List<BSHMethod>> methods;
protected Map<String, String> importedClasses;
private List<String> importedPackages;
private List<String> importedCommands;
private List<Object> importedObjects;
private List<Class> importedStatic;
private String packageName;
transient private BSHClassManager classManager;
// See notes in getThis()
private This thisReference;
/**
* Name resolver objects
*/
private Map<String, Name> names;
/**
* The node associated with the creation of this namespace. This is used
* support getInvocationLine() and getInvocationText().
*/
SimpleNode callerInfoNode;
/**
* Note that the namespace is a method body namespace. This is used for
* printing stack traces in exceptions.
*/
boolean isMethod;
/**
* Note that the namespace is a class body or class instance namespace. This
* is used for controlling static/object import precedence, etc.
*/
/*
Note: We will ll move this behavior out to a subclass of
NameSpace, but we'll start here.
*/
boolean isClass;
Class classStatic;
Object classInstance;
void setClassStatic(Class clas) {
this.classStatic = clas;
importStatic(clas);
}
void setClassInstance(Object instance) {
this.classInstance = instance;
importObject(instance);
}
Object getClassInstance()
throws UtilEvalError {
if (classInstance != null) {
return classInstance;
}
if (classStatic != null //|| ( getParent()!=null && getParent().classStatic != null )
) {
throw new UtilEvalError(
"Can't refer to class instance from static context.");
} else {
throw new InterpreterError(
"Can't resolve class instance 'this' in: " + this);
}
}
/**
* Local class cache for classes resolved through this namespace using
* getClass() (taking into account imports). Only unqualified class names
* are cached here (those which might be imported). Qualified names are
* always absolute and are cached by BSHClassManager.
*/
transient private Map<String, Class> classCache;
// End instance data
// Begin constructors
/**
* @parent the parent namespace of this namespace. Child namespaces inherit
* all variables and methods of their parent and can (of course) override /
* shadow them.
*/
public NameSpace(NameSpace parent, String name) {
// Note: in this case parent must have a class manager.
this(parent, null, name);
}
public NameSpace(BSHClassManager classManager, String name) {
this(null, classManager, name);
}
public NameSpace(
NameSpace parent, BSHClassManager classManager, String name) {
// We might want to do this here rather than explicitly in Interpreter
// for global (see also prune())
//if ( classManager == null && (parent == null ) )
// create our own class manager?
setName(name);
setParent(parent);
setClassManager(classManager);
// Register for notification of classloader change
if (classManager != null) {
classManager.addListener(this);
}
}
// End constructors
public void setName(String name) {
this.nsName = name;
}
/**
* The name of this namespace. If the namespace is a method body namespace
* then this is the name of the method. If it's a class or class instance
* then it's the name of the class.
*/
public String getName() {
return this.nsName;
}
/**
* Set the node associated with the creation of this namespace. This is used
* in debugging and to support the getInvocationLine() and
* getInvocationText() methods.
*/
void setNode(SimpleNode node) {
callerInfoNode = node;
}
/**
*/
SimpleNode getNode() {
if (callerInfoNode != null) {
return callerInfoNode;
}
if (parent != null) {
return parent.getNode();
} else {
return null;
}
}
/**
* Resolve name to an object through this namespace.
*/
public Object get(String name, Interpreter interpreter)
throws UtilEvalError {
CallStack callstack = new CallStack(this);
return getNameResolver(name).toObject(callstack, interpreter);
}
/**
* Set the variable through this namespace. This method obeys the
* LOCALSCOPING property to determine how variables are set.
* <p>
* Note: this method is primarily intended for use internally. If you use
* this method outside of the bsh package and wish to set variables with
* primitive values you will have to wrap them using bsh.Primitive.
*
* @see ehacks.bsh.Primitive
* <p>
* Setting a new variable (which didn't exist before) or removing a variable
* causes a namespace change.
*
* @param strictJava specifies whether strict java rules are applied.
*/
public void setVariable(String name, Object value, boolean strictJava)
throws UtilEvalError {
// if localscoping switch follow strictJava, else recurse
boolean recurse = Interpreter.LOCALSCOPING ? strictJava : true;
setVariable(name, value, strictJava, recurse);
}
/**
* Set a variable explicitly in the local scope.
*/
void setLocalVariable(
String name, Object value, boolean strictJava)
throws UtilEvalError {
setVariable(name, value, strictJava, false/*recurse*/);
}
/**
* Set the value of a the variable 'name' through this namespace. The
* variable may be an existing or non-existing variable. It may live in this
* namespace or in a parent namespace if recurse is true.
* <p>
* Note: This method is not public and does *not* know about LOCALSCOPING.
* Its caller methods must set recurse intelligently in all situations
* (perhaps based on LOCALSCOPING).
*
* <p>
* Note: this method is primarily intended for use internally. If you use
* this method outside of the bsh package and wish to set variables with
* primitive values you will have to wrap them using bsh.Primitive.
*
* @see ehacks.bsh.Primitive
* <p>
* Setting a new variable (which didn't exist before) or removing a variable
* causes a namespace change.
*
* @param strictJava specifies whether strict java rules are applied.
* @param recurse determines whether we will search for the variable in our
* parent's scope before assigning locally.
*/
void setVariable(
String name, Object value, boolean strictJava, boolean recurse)
throws UtilEvalError {
ensureVariables();
// primitives should have been wrapped
if (value == null) {
throw new InterpreterError("null variable value");
}
// Locate the variable definition if it exists.
Variable existing = getVariableImpl(name, recurse);
// Found an existing variable here (or above if recurse allowed)
if (existing != null) {
try {
existing.setValue(value, Variable.ASSIGNMENT);
} catch (UtilEvalError e) {
throw new UtilEvalError(
"Variable assignment: " + name + ": " + e.getMessage());
}
} else // No previous variable definition found here (or above if recurse)
{
if (strictJava) {
throw new UtilEvalError(
"(Strict Java mode) Assignment to undeclared variable: "
+ name);
}
// If recurse, set global untyped var, else set it here.
//NameSpace varScope = recurse ? getGlobal() : this;
// This modification makes default allocation local
NameSpace varScope = this;
varScope.variables.put(
name, new Variable(name, value, null/*modifiers*/));
// nameSpaceChanged() on new variable addition
nameSpaceChanged();
}
}
private void ensureVariables() {
if (variables == null) {
variables = new HashMap<>();
}
}
/**
* Remove the variable from the namespace.
*/
public void unsetVariable(String name) {
if (variables != null) {
variables.remove(name);
nameSpaceChanged();
}
}
/**
* Get the names of variables defined in this namespace. (This does not show
* variables in parent namespaces).
*/
public String[] getVariableNames() {
if (variables == null) {
return new String[0];
} else {
return variables.keySet().toArray(new String[0]);
}
}
/**
* Get the names of methods declared in this namespace. (This does not
* include methods in parent namespaces).
*/
public String[] getMethodNames() {
if (methods == null) {
return new String[0];
} else {
return methods.keySet().toArray(new String[0]);
}
}
/**
* Get the methods defined in this namespace. (This does not show methods in
* parent namespaces). Note: This will probably be renamed
* getDeclaredMethods()
*/
public BSHMethod[] getMethods() {
if (methods == null) {
return new BSHMethod[0];
} else {
List<BSHMethod> ret = new ArrayList<>();
methods.values().forEach((list) -> {
ret.addAll(list);
});
return ret.toArray(new BSHMethod[ret.size()]);
}
}
/**
* Get the parent namespace. Note: this isn't quite the same as getSuper().
* getSuper() returns 'this' if we are at the root namespace.
*/
public NameSpace getParent() {
return parent;
}
/**
* Get the parent namespace' This reference or this namespace' This
* reference if we are the top.
*/
public This getSuper(Interpreter declaringInterpreter) {
if (parent != null) {
return parent.getThis(declaringInterpreter);
} else {
return getThis(declaringInterpreter);
}
}
/**
* Get the top level namespace or this namespace if we are the top. Note:
* this method should probably return type bsh.This to be consistent with
* getThis();
*/
public This getGlobal(Interpreter declaringInterpreter) {
if (parent != null) {
return parent.getGlobal(declaringInterpreter);
} else {
return getThis(declaringInterpreter);
}
}
/**
* A This object is a thin layer over a namespace, comprising a bsh object
* context. It handles things like the interface types the bsh object
* supports and aspects of method invocation on it.
* <p>
*
* The declaringInterpreter is here to support callbacks from Java through
* generated proxies. The scripted object "remembers" who created it for
* things like printing messages and other per-interpreter phenomenon when
* called externally from Java.
*/
/*
Note: we need a singleton here so that things like 'this == this' work
(and probably a good idea for speed).
Caching a single instance here seems technically incorrect,
considering the declaringInterpreter could be different under some
circumstances. (Case: a child interpreter running a source() / eval()
command ). However the effect is just that the main interpreter that
executes your script should be the one involved in call-backs from Java.
I do not know if there are corner cases where a child interpreter would
be the first to use a This reference in a namespace or if that would
even cause any problems if it did... We could do some experiments
to find out... and if necessary we could cache on a per interpreter
basis if we had weak references... We might also look at skipping
over child interpreters and going to the parent for the declaring
interpreter, so we'd be sure to get the top interpreter.
*/
public This getThis(Interpreter declaringInterpreter) {
if (thisReference == null) {
thisReference = This.getThis(this, declaringInterpreter);
}
return thisReference;
}
public BSHClassManager getClassManager() {
if (classManager != null) {
return classManager;
}
if (parent != null && parent != JAVACODE) {
return parent.getClassManager();
}
classManager = BSHClassManager.createClassManager(null/*interp*/);
//Interpreter.debug("No class manager namespace:" +this);
return classManager;
}
void setClassManager(BSHClassManager classManager) {
this.classManager = classManager;
}
/**
* Used for serialization
*/
public void prune() {
// Cut off from parent, we must have our own class manager.
// Can't do this in the run() command (needs to resolve stuff)
// Should we do it by default when we create a namespace will no
// parent of class manager?
if (this.classManager == null) // XXX if we keep the createClassManager in getClassManager then we can axe
// this?
{
setClassManager(
BSHClassManager.createClassManager(null/*interp*/));
}
setParent(null);
}
public void setParent(NameSpace parent) {
this.parent = parent;
// If we are disconnected from root we need to handle the def imports
if (parent == null) {
loadDefaultImports();
}
}
/**
* Get the specified variable in this namespace or a parent namespace.
* <p>
* Note: this method is primarily intended for use internally. If you use
* this method outside of the bsh package you will have to use
* Primitive.unwrap() to get primitive values.
*
* @see Primitive#unwrap( Object )
*
* @return The variable value or Primitive.VOID if it is not defined.
*/
public Object getVariable(String name)
throws UtilEvalError {
return getVariable(name, true);
}
/**
* Get the specified variable in this namespace.
*
* @param recurse If recurse is true then we recursively search through
* parent namespaces for the variable.
* <p>
* Note: this method is primarily intended for use internally. If you use
* this method outside of the bsh package you will have to use
* Primitive.unwrap() to get primitive values.
* @see Primitive#unwrap( Object )
*
* @return The variable value or Primitive.VOID if it is not defined.
*/
public Object getVariable(String name, boolean recurse)
throws UtilEvalError {
Variable var = getVariableImpl(name, recurse);
return unwrapVariable(var);
}
/**
* Locate a variable and return the Variable object with optional recursion
* through parent name spaces.
* <p/>
* If this namespace is static, return only static variables.
*
* @return the Variable value or null if it is not defined
*/
protected Variable getVariableImpl(String name, boolean recurse)
throws UtilEvalError {
Variable var = null;
// Change import precedence if we are a class body/instance
// Get imported first.
if (var == null && isClass) {
var = getImportedVar(name);
}
if (var == null && variables != null) {
var = variables.get(name);
}
// Change import precedence if we are a class body/instance
if (var == null && !isClass) {
var = getImportedVar(name);
}
// try parent
if (recurse && (var == null) && (parent != null)) {
var = parent.getVariableImpl(name, recurse);
}
return var;
}
/*
Get variables declared in this namespace.
*/
public Variable[] getDeclaredVariables() {
if (variables == null) {
return new Variable[0];
}
return variables.values().toArray(new Variable[0]);
}
/**
* Unwrap a variable to its value.
*
* @return return the variable value. A null var is mapped to Primitive.VOID
*/
protected Object unwrapVariable(Variable var)
throws UtilEvalError {
return (var == null) ? Primitive.VOID : var.getValue();
}
/**
* @deprecated See #setTypedVariable( String, Class, Object, Modifiers )
*/
public void setTypedVariable(
String name, Class type, Object value, boolean isFinal)
throws UtilEvalError {
Modifiers modifiers = new Modifiers();
if (isFinal) {
modifiers.addModifier(Modifiers.FIELD, "final");
}
setTypedVariable(name, type, value, modifiers);
}
/**
* Declare a variable in the local scope and set its initial value. Value
* may be null to indicate that we would like the default value for the
* variable type. (e.g. 0 for integer types, null for object types). An
* existing typed variable may only be set to the same type. If an untyped
* variable of the same name exists it will be overridden with the new typed
* var. The set will perform a Types.getAssignableForm() on the value if
* necessary.
*
* <p>
* Note: this method is primarily intended for use internally. If you use
* this method outside of the bsh package and wish to set variables with
* primitive values you will have to wrap them using bsh.Primitive.
*
* @see ehacks.bsh.Primitive
*
* @param value If value is null, you'll get the default value for the type
* @param modifiers may be null
*/
public void setTypedVariable(
String name, Class type, Object value, Modifiers modifiers)
throws UtilEvalError {
//checkVariableModifiers( name, modifiers );
ensureVariables();
// Setting a typed variable is always a local operation.
Variable existing = getVariableImpl(name, false/*recurse*/);
// Null value is just a declaration
// Note: we might want to keep any existing value here instead of reset
/*
// Moved to Variable
if ( value == null )
value = Primitive.getDefaultValue( type );
*/
// does the variable already exist?
if (existing != null) {
// Is it typed?
if (existing.getType() != null) {
// If it had a different type throw error.
// This allows declaring the same var again, but not with
// a different (even if assignable) type.
if (existing.getType() != type) {
throw new UtilEvalError("Typed variable: " + name
+ " was previously declared with type: "
+ existing.getType());
} else {
// else set it and return
existing.setValue(value, Variable.DECLARATION);
return;
}
}
// Careful here:
// else fall through to override and install the new typed version
}
// Add the new typed var
variables.put(name, new Variable(name, type, value, modifiers));
}
/**
* Dissallow static vars outside of a class
*
* @param name is here just to allow the error message to use it protected
* void checkVariableModifiers( String name, Modifiers modifiers ) throws
* UtilEvalError { if ( modifiers!=null && modifiers.hasModifier("static") )
* throw new UtilEvalError( "Can't declare static variable outside of class:
* "+name ); }
*/
/**
* Note: this is primarily for internal use.
*
* @see Interpreter#source( String )
* @see Interpreter#eval( String )
*/
public void setMethod(BSHMethod method)
throws UtilEvalError {
//checkMethodModifiers( method );
if (methods == null) {
methods = new HashMap<>();
}
String name = method.getName();
List<BSHMethod> list = methods.get(name);
if (list == null) {
methods.put(name, Collections.singletonList(method));
} else {
if (!(list instanceof ArrayList)) {
list = new ArrayList<>(list);
methods.put(name, list);
}
list.remove(method);
list.add(method);
}
}
/**
* @see #getMethod( String, Class [], boolean )
* @see #getMethod( String, Class [] )
*/
public BSHMethod getMethod(String name, Class[] sig)
throws UtilEvalError {
return getMethod(name, sig, false/*declaredOnly*/);
}
/**
* Get the bsh method matching the specified signature declared in this name
* space or a parent.
* <p>
* Note: this method is primarily intended for use internally. If you use
* this method outside of the bsh package you will have to be familiar with
* BeanShell's use of the Primitive wrapper class.
*
* @see ehacks.bsh.Primitive
* @return the BSHMethod or null if not found
* @param declaredOnly if true then only methods declared directly in this
* namespace will be found and no inherited or imported methods will be
* visible.
*/
public BSHMethod getMethod(
String name, Class[] sig, boolean declaredOnly)
throws UtilEvalError {
BSHMethod method = null;
// Change import precedence if we are a class body/instance
// Get import first.
if (method == null && isClass && !declaredOnly) {
method = getImportedMethod(name, sig);
}
if (method == null && methods != null) {
List<BSHMethod> list = methods.get(name);
if (list != null) {
// Apply most specific signature matching
Class[][] candidates = new Class[list.size()][];
for (int i = 0; i < candidates.length; i++) {
candidates[i] = list.get(i).getParameterTypes();
}
int match
= Reflect.findMostSpecificSignature(sig, candidates);
if (match != -1) {
method = list.get(match);
}
}
}
if (method == null && !isClass && !declaredOnly) {
method = getImportedMethod(name, sig);
}
// try parent
if (!declaredOnly && (method == null) && (parent != null)) {
return parent.getMethod(name, sig);
}
return method;
}
/**
* Import a class name. Subsequent imports override earlier ones
*/
public void importClass(String name) {
if (importedClasses == null) {
importedClasses = new HashMap<>();
}
importedClasses.put(Name.suffix(name, 1), name);
nameSpaceChanged();
}
/**
* subsequent imports override earlier ones
*/
public void importPackage(String name) {
if (importedPackages == null) {
importedPackages = new ArrayList<>();
}
// If it exists, remove it and add it at the end (avoid memory leak)
importedPackages.remove(name);
importedPackages.add(name);
nameSpaceChanged();
}
/**
* Import scripted or compiled BeanShell commands in the following package
* in the classpath. You may use either "/" path or "." package notation.
* e.g. importCommands("/bsh/commands") or importCommands("bsh.commands")
* are equivalent. If a relative path style specifier is used then it is
* made into an absolute path by prepending "/".
*/
public void importCommands(String name) {
if (importedCommands == null) {
importedCommands = new ArrayList<>();
}
// dots to slashes
name = name.replace('.', '/');
// absolute
if (!name.startsWith("/")) {
name = "/" + name;
}
// remove trailing (but preserve case of simple "/")
if (name.length() > 1 && name.endsWith("/")) {
name = name.substring(0, name.length() - 1);
}
// If it exists, remove it and add it at the end (avoid memory leak)
importedCommands.remove(name);
importedCommands.add(name);
nameSpaceChanged();
}
/**
* A command is a scripted method or compiled command class implementing a
* specified method signature. Commands are loaded from the classpath and
* may be imported using the importCommands() method.
* <p/>
*
* This method searches the imported commands packages for a script or
* command object corresponding to the name of the method. If it is a script
* the script is sourced into this namespace and the BSHMethod for the
* requested signature is returned. If it is a compiled class the class is
* returned. (Compiled command classes implement static invoke() methods).
* <p/>
*
* The imported packages are searched in reverse order, so that later
* imports take priority. Currently only the first object (script or class)
* with the appropriate name is checked. If another, overloaded form, is
* located in another package it will not currently be found. This could be
* fixed.
* <p/>
*
* @return a BSHMethod, Class, or null if no such command is found.
* @param name is the name of the desired command method
* @param argTypes is the signature of the desired command method.
* @throws UtilEvalError if loadScriptedCommand throws UtilEvalError i.e. on
* errors loading a script that was found
*/
public Object getCommand(
String name, Class[] argTypes, Interpreter interpreter)
throws UtilEvalError {
if (Interpreter.DEBUG) {
Interpreter.debug("getCommand: " + name);
}
BSHClassManager bcm = interpreter.getClassManager();
if (importedCommands != null) {
// loop backwards for precedence
for (int i = importedCommands.size() - 1; i >= 0; i--) {
String path = importedCommands.get(i);
String scriptPath;
if (path.equals("/")) {
scriptPath = path + name + ".bsh";
} else {
scriptPath = path + "/" + name + ".bsh";
}
Interpreter.debug("searching for script: " + scriptPath);
InputStream in = bcm.getResourceAsStream(scriptPath);
if (in != null) {
return loadScriptedCommand(
in, name, argTypes, scriptPath, interpreter);
}
// Chop leading "/" and change "/" to "."
String className;
if (path.equals("/")) {
className = name;
} else {
className = path.substring(1).replace('/', '.') + "." + name;
}
Interpreter.debug("searching for class: " + className);
Class clas = bcm.classForName(className);
if (clas != null) {
return clas;
}
}
}
if (parent != null) {
return parent.getCommand(name, argTypes, interpreter);
} else {
return null;
}
}
protected BSHMethod getImportedMethod(String name, Class[] sig)
throws UtilEvalError {
// Try object imports
if (importedObjects != null) {
for (int i = 0; i < importedObjects.size(); i++) {
Object object = importedObjects.get(i);
Class clas = object.getClass();
Method method = Reflect.resolveJavaMethod(
getClassManager(), clas, name, sig, false/*onlyStatic*/);
if (method != null) {
return new BSHMethod(method, object);
}
}
}
// Try static imports
if (importedStatic != null) {
for (int i = 0; i < importedStatic.size(); i++) {
Class clas = importedStatic.get(i);
Method method = Reflect.resolveJavaMethod(
getClassManager(), clas, name, sig, true/*onlyStatic*/);
if (method != null) {
return new BSHMethod(method, null/*object*/);
}
}
}
return null;
}
protected Variable getImportedVar(String name)
throws UtilEvalError {
// Try object imports
if (importedObjects != null) {
for (int i = 0; i < importedObjects.size(); i++) {
Object object = importedObjects.get(i);
Class clas = object.getClass();
Field field = Reflect.resolveJavaField(
clas, name, false/*onlyStatic*/);
if (field != null) {
return new Variable(
name, field.getType(), new LHS(object, field));
}
}
}
// Try static imports
if (importedStatic != null) {
for (int i = 0; i < importedStatic.size(); i++) {
Class clas = importedStatic.get(i);
Field field = Reflect.resolveJavaField(
clas, name, true/*onlyStatic*/);
if (field != null) {
return new Variable(name, field.getType(), new LHS(field));
}
}
}
return null;
}
/**
* Load a command script from the input stream and find the BSHMethod in the
* target namespace.
*
* @throws UtilEvalError on error in parsing the script or if the the method
* is not found after parsing the script.
*/
/*
If we want to support multiple commands in the command path we need to
change this to not throw the exception.
*/
private BSHMethod loadScriptedCommand(
InputStream in, String name, Class[] argTypes, String resourcePath,
Interpreter interpreter)
throws UtilEvalError {
try {
interpreter.eval(
new InputStreamReader(in), this, resourcePath);
} catch (EvalError e) {
/*
Here we catch any EvalError from the interpreter because we are
using it as a tool to load the command, not as part of the
execution path.
*/
Interpreter.debug(e.toString());
throw new UtilEvalError(
"Error loading script: " + e.getMessage(), e);
}
// Look for the loaded command
BSHMethod meth = getMethod(name, argTypes);
/*
if ( meth == null )
throw new UtilEvalError("Loaded resource: " + resourcePath +
"had an error or did not contain the correct method" );
*/
return meth;
}
/**
* Helper that caches class.
*/
void cacheClass(String name, Class c) {
if (classCache == null) {
classCache = new HashMap<>();
//cacheCount++; // debug
}
classCache.put(name, c);
}
/**
* Load a class through this namespace taking into account imports. The
* class search will proceed through the parent namespaces if necessary.
*
* @return null if not found.
*/
public Class getClass(String name)
throws UtilEvalError {
Class c = getClassImpl(name);
if (c != null) {
return c;
} else // implement the recursion for getClassImpl()
if (parent != null) {
return parent.getClass(name);
} else {
return null;
}
}
/**
* Implementation of getClass() * Load a class through this namespace taking
* into account imports.
* <p>
*
* Check the cache first. If an unqualified name look for imported class or
* package. Else try to load absolute name.
* <p>
*
* This method implements caching of unqualified names (normally imports).
* Qualified names are cached by the BSHClassManager. Unqualified absolute
* class names (e.g. unpackaged Foo) are cached too so that we don't go
* searching through the imports for them each time.
*
* @return null if not found.
*/
private Class getClassImpl(String name)
throws UtilEvalError {
Class c = null;
// Check the cache
if (classCache != null) {
c = classCache.get(name);
if (c != null) {
return c;
}
}
// Unqualified (simple, non-compound) name
boolean unqualifiedName = !Name.isCompound(name);
// Unqualified name check imported
if (unqualifiedName) {
// Try imported class
if (c == null) {
c = getImportedClassImpl(name);
}
// if found as imported also cache it
if (c != null) {
cacheClass(name, c);
return c;
}
}
// Try absolute
c = classForName(name);
if (c != null) {
// Cache unqualified names to prevent import check again
if (unqualifiedName) {
cacheClass(name, c);
}
return c;
}
// Not found
if (Interpreter.DEBUG) {
Interpreter.debug("getClass(): " + name + " not found in " + this);
}
return null;
}
/**
* Try to make the name into an imported class. This method takes into
* account only imports (class or package) found directly in this NameSpace
* (no parent chain).
*/
private Class getImportedClassImpl(String name)
throws UtilEvalError {
// Try explicitly imported class, e.g. import foo.Bar;
String fullname = null;
if (importedClasses != null) {
fullname = importedClasses.get(name);
}
// not sure if we should really recurse here for explicitly imported
// class in parent...
if (fullname != null) {
/*
Found the full name in imported classes.
*/
// Try to make the full imported name
Class clas = classForName(fullname);
if (clas != null) {
return clas;
}
// Handle imported inner class case
// Imported full name wasn't found as an absolute class
// If it is compound, try to resolve to an inner class.
// (maybe this should happen in the BSHClassManager?)
if (Name.isCompound(fullname)) {
try {
clas = getNameResolver(fullname).toClass();
} catch (ClassNotFoundException e) {
/* not a class */ }
} else if (Interpreter.DEBUG) {
Interpreter.debug(
"imported unpackaged name not found:" + fullname);
}
// If found cache the full name in the BSHClassManager
if (clas != null) {
// (should we cache info in not a class case too?)
getClassManager().cacheClassInfo(fullname, clas);
return clas;
}
// It was explicitly imported, but we don't know what it is.
// should we throw an error here??
return null;
}
/*
Try imported packages, e.g. "import foo.bar.*;"
in reverse order of import...
(give later imports precedence...)
*/
if (importedPackages != null) {
for (int i = importedPackages.size() - 1; i >= 0; i--) {
String s = importedPackages.get(i) + "." + name;
Class c = classForName(s);
if (c != null) {
return c;
}
}
}
BSHClassManager bcm = getClassManager();
/*
Try super import if available
Note: we do this last to allow explicitly imported classes
and packages to take priority. This method will also throw an
error indicating ambiguity if it exists...
*/
if (bcm.hasSuperImport()) {
String s = bcm.getClassNameByUnqName(name);
if (s != null) {
return classForName(s);
}
}
return null;
}
private Class classForName(String name) {
return getClassManager().classForName(name);
}
/**
* Implements NameSource
*
* @return all variable and method names in this and all parent namespaces
*/
@Override
public String[] getAllNames() {
List<String> list = new ArrayList<>();
getAllNamesAux(list);
return list.toArray(new String[list.size()]);
}
/**
* Helper for implementing NameSource
*/
protected void getAllNamesAux(List<String> list) {
list.addAll(variables.keySet());
if (methods != null) {
list.addAll(methods.keySet());
}
if (parent != null) {
parent.getAllNamesAux(list);
}
}
List<NameSource.Listener> nameSourceListeners;
/**
* Implements NameSource Add a listener who is notified upon changes to
* names in this space.
*/
@Override
public void addNameSourceListener(NameSource.Listener listener) {
if (nameSourceListeners == null) {
nameSourceListeners = new ArrayList<>();
}
nameSourceListeners.add(listener);
}
/**
* Perform "import *;" causing the entire classpath to be mapped. This can
* take a while.
*/
public void doSuperImport()
throws UtilEvalError {
getClassManager().doSuperImport();
}
@Override
public String toString() {
return "NameSpace: "
+ (nsName == null
? super.toString()
: nsName + " (" + super.toString() + ")")
+ (isClass ? " (isClass) " : "")
+ (isMethod ? " (method) " : "")
+ (classStatic != null ? " (class static) " : "")
+ (classInstance != null ? " (class instance) " : "");
}
/*
For serialization.
Don't serialize non-serializable objects.
*/
private synchronized void writeObject(java.io.ObjectOutputStream s)
throws IOException {
// clear name resolvers... don't know if this is necessary.
names = null;
s.defaultWriteObject();
}
/**
* Invoke a method in this namespace with the specified args and interpreter
* reference. No caller information or call stack is required. The method
* will appear as if called externally from Java.
* <p>
*
* @see bsh.This.invokeMethod( String methodName, Object [] args,
* Interpreter interpreter, CallStack callstack, SimpleNode callerInfo,
* boolean )
*/
public Object invokeMethod(
String methodName, Object[] args, Interpreter interpreter)
throws EvalError {
return invokeMethod(
methodName, args, interpreter, null, null);
}
/**
* This method simply delegates to This.invokeMethod();
* <p>
* @see bsh.This.invokeMethod( String methodName, Object [] args,
* Interpreter interpreter, CallStack callstack, SimpleNode callerInfo )
*/
public Object invokeMethod(
String methodName, Object[] args, Interpreter interpreter,
CallStack callstack, SimpleNode callerInfo)
throws EvalError {
return getThis(interpreter).invokeMethod(
methodName, args, interpreter, callstack, callerInfo,
false/*declaredOnly*/);
}
/**
* Clear all cached classes and names
*/
@Override
public void classLoaderChanged() {
nameSpaceChanged();
}
/**
* Clear all cached classes and names
*/
public void nameSpaceChanged() {
classCache = null;
names = null;
}
/**
* Import standard packages. Currently:
* <pre>
* importClass("bsh.EvalError");
* importClass("bsh.Interpreter");
* importPackage("javax.swing.event");
* importPackage("javax.swing");
* importPackage("java.awt.event");
* importPackage("java.awt");
* importPackage("java.net");
* importPackage("java.util");
* importPackage("java.io");
* importPackage("java.lang");
* importCommands("/bsh/commands");
* </pre>
*/
public void loadDefaultImports() {
/**
* Note: the resolver looks through these in reverse order, per
* precedence rules... so for max efficiency put the most common ones
* later.
*/
importClass("bsh.EvalError");
importClass("bsh.Interpreter");
importPackage("java.util");
importPackage("java.io");
importPackage("java.lang");
importPackage("javax.swing.event");
importPackage("javax.swing");
importPackage("java.awt.event");
importPackage("java.awt");
importPackage("java.net");
// RRB: added for BEAST
importCommands("/beast/commands");
importCommands("/bsh/commands");
}
/**
* This is the factory for Name objects which resolve names within this
* namespace (e.g. toObject(), toClass(), toLHS()).
* <p>
*
* This was intended to support name resolver caching, allowing Name objects
* to cache info about the resolution of names for performance reasons.
* However this not proven useful yet.
* <p>
*
* We'll leave the caching as it will at least minimize Name object
* creation.
* <p>
*
* (This method would be called getName() if it weren't already used for the
* simple name of the NameSpace)
* <p>
*
* This method was public for a time, which was a mistake. Use get()
* instead.
*/
Name getNameResolver(String ambigname) {
if (names == null) {
names = new HashMap<>();
}
Name name = names.get(ambigname);
if (name == null) {
name = new Name(this, ambigname);
names.put(ambigname, name);
}
return name;
}
public int getInvocationLine() {
SimpleNode node = getNode();
if (node != null) {
return node.getLineNumber();
} else {
return -1;
}
}
public String getInvocationText() {
SimpleNode node = getNode();
if (node != null) {
return node.getText();
} else {
return "<invoked from Java code>";
}
}
/**
* This is a helper method for working inside of bsh scripts and commands.
* In that context it is impossible to see a ClassIdentifier object for what
* it is. Attempting to access a method on a ClassIdentifier will look like
* a static method invocation. * This method is in NameSpace for convenience
* (you don't have to import bsh.ClassIdentifier to use it );
*/
public static Class identifierToClass(ClassIdentifier ci) {
return ci.getTargetClass();
}
/**
* Clear all variables, methods, and imports from this namespace. If this
* namespace is the root, it will be reset to the default imports.
*
* @see #loadDefaultImports()
*/
public void clear() {
variables = null;
methods = null;
importedClasses = null;
importedPackages = null;
importedCommands = null;
importedObjects = null;
if (parent == null) {
loadDefaultImports();
}
classCache = null;
names = null;
}
/**
* Import a compiled Java object's methods and variables into this
* namespace. When no scripted method / command or variable is found locally
* in this namespace method / fields of the object will be checked. Objects
* are checked in the order of import with later imports taking precedence.
* <p/>
*/
/*
Note: this impor pattern is becoming common... could factor it out into
an importedObject Vector class.
*/
public void importObject(Object obj) {
if (importedObjects == null) {
importedObjects = new ArrayList<>();
}
// If it exists, remove it and add it at the end (avoid memory leak)
importedObjects.remove(obj);
importedObjects.add(obj);
nameSpaceChanged();
}
/**
*/
public void importStatic(Class clas) {
if (importedStatic == null) {
importedStatic = new ArrayList<>();
}
// If it exists, remove it and add it at the end (avoid memory leak)
importedStatic.remove(clas);
importedStatic.add(clas);
nameSpaceChanged();
}
/**
* Set the package name for classes defined in this namespace. Subsequent
* sets override the package.
*/
void setPackage(String packageName) {
this.packageName = packageName;
}
String getPackage() {
if (packageName != null) {
return packageName;
}
if (parent != null) {
return parent.getPackage();
}
return null;
}
NameSpace copy() {
try {
final NameSpace clone = (NameSpace) clone();
clone.thisReference = null;
clone.variables = clone(variables);
clone.methods = clone(methods);
clone.importedClasses = clone(importedClasses);
clone.importedPackages = clone(importedPackages);
clone.importedCommands = clone(importedCommands);
clone.importedObjects = clone(importedObjects);
clone.importedStatic = clone(importedStatic);
clone.names = clone(names);
return clone;
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
}
private <K, V> Map<K, V> clone(final Map<K, V> map) {
if (map == null) {
return null;
}
return new HashMap<>(map);
}
private <T> List<T> clone(final List<T> list) {
if (list == null) {
return null;
}
return new ArrayList<>(list);
}
public List<String> getImportedCommands() {
return Collections.unmodifiableList(importedCommands);
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone(); //To change body of generated methods, choose Tools | Templates.
}
}
| 51,814 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
SimpleNode.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/SimpleNode.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
/*
Note: great care (and lots of typing) were taken to insure that the
namespace and interpreter references are passed on the stack and not
(as they were erroneously before) installed in instance variables...
Each of these node objects must be re-entrable to allow for recursive
situations.
The only data which should really be stored in instance vars here should
be parse tree data... features of the node which should never change (e.g.
the number of arguments, etc.)
Exceptions would be public fields of simple classes that just publish
data produced by the last eval()... data that is used immediately. We'll
try to remember to mark these as transient to highlight them.
*/
class SimpleNode implements Node {
public static SimpleNode JAVACODE
= new SimpleNode(-1) {
@Override
public String getSourceFile() {
return "<Called from Java Code>";
}
@Override
public int getLineNumber() {
return -1;
}
@Override
public String getText() {
return "<Compiled Java Code>";
}
};
protected Node parent;
protected Node[] children;
protected int id;
Token firstToken, lastToken;
/**
* the source of the text from which this was parsed
*/
String sourceFile;
public SimpleNode(int i) {
id = i;
}
@Override
public void jjtOpen() {
}
@Override
public void jjtClose() {
}
@Override
public void jjtSetParent(Node n) {
parent = n;
}
@Override
public Node jjtGetParent() {
return parent;
}
//public SimpleNode getParent() { return (SimpleNode)parent; }
@Override
public void jjtAddChild(Node n, int i) {
if (children == null) {
children = new Node[i + 1];
} else if (i >= children.length) {
Node c[] = new Node[i + 1];
System.arraycopy(children, 0, c, 0, children.length);
children = c;
}
children[i] = n;
}
@Override
public Node jjtGetChild(int i) {
return children[i];
}
public SimpleNode getChild(int i) {
return (SimpleNode) jjtGetChild(i);
}
@Override
public int jjtGetNumChildren() {
return (children == null) ? 0 : children.length;
}
/*
You can override these two methods in subclasses of SimpleNode to
customize the way the node appears when the tree is dumped. If
your output uses more than one line you should override
toString(String), otherwise overriding toString() is probably all
you need to do.
*/
@Override
public String toString() {
return ParserTreeConstants.jjtNodeName[id];
}
public String toString(String prefix) {
return prefix + toString();
}
/*
Override this method if you want to customize how the node dumps
out its children.
*/
public void dump(String prefix) {
if (children != null) {
for (int i = 0; i < children.length; ++i) {
SimpleNode n = (SimpleNode) children[i];
if (n != null) {
n.dump(prefix + " ");
}
}
}
}
// ---- BeanShell specific stuff hereafter ---- //
/**
* Detach this node from its parent. This is primarily useful in node
* serialization. (see BSHMethodDeclaration)
*/
public void prune() {
jjtSetParent(null);
}
/**
* This is the general signature for evaluation of a node.
*/
public Object eval(CallStack callstack, Interpreter interpreter)
throws EvalError {
throw new InterpreterError(
"Unimplemented or inappropriate for " + getClass().getName());
}
/**
* Set the name of the source file (or more generally source) of the text
* from which this node was parsed.
*/
public void setSourceFile(String sourceFile) {
this.sourceFile = sourceFile;
}
/**
* Get the name of the source file (or more generally source) of the text
* from which this node was parsed. This will recursively search up the
* chain of parent nodes until a source is found or return a string
* indicating that the source is unknown.
*/
public String getSourceFile() {
if (sourceFile == null) {
if (parent != null) {
return ((SimpleNode) parent).getSourceFile();
} else {
return "<unknown file>";
}
} else {
return sourceFile;
}
}
/**
* Get the line number of the starting token
*/
public int getLineNumber() {
return firstToken.beginLine;
}
/**
* Get the ending line number of the starting token public int
* getEndLineNumber() { return lastToken.endLine; }
*/
/**
* Get the text of the tokens comprising this node.
*/
public String getText() {
StringBuilder text = new StringBuilder();
Token t = firstToken;
while (t != null) {
text.append(t.image);
if (!t.image.equals(".")) {
text.append(" ");
}
if (t == lastToken
|| t.image.equals("{") || t.image.equals(";")) {
break;
}
t = t.next;
}
return text.toString();
}
}
| 8,005 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
Name.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/Name.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
/**
* What's in a name? I'll tell you... Name() is a somewhat ambiguous thing in
* the grammar and so is this.
* <p>
*
* This class is a name resolver. It holds a possibly ambiguous dot separated
* name and reference to a namespace in which it allegedly lives. It provides
* methods that attempt to resolve the name to various types of entities: e.g.
* an Object, a Class, a declared scripted BeanShell method.
* <p>
*
* Name objects are created by the factory method NameSpace getNameResolver(),
* which caches them subject to a class namespace change. This means that we can
* cache information about various types of resolution here. Currently very
* little if any information is cached. However with a future "optimize" setting
* that defeats certain dynamic behavior we might be able to cache quite a bit.
*/
/*
<strong>Implementation notes</strong>
<pre>
Thread safety: all of the work methods in this class must be synchronized
because they share the internal intermediate evaluation state.
Note about invokeMethod(): We could simply use resolveMethod and return
the MethodInvoker (BshMethod or JavaMethod) however there is no easy way
for the AST (BSHMehodInvocation) to use this as it doesn't have type
information about the target to resolve overloaded methods.
(In Java, overloaded methods are resolved at compile time... here they
are, of necessity, dynamic). So it would have to do what we do here
and cache by signature. We now do that for the client in Reflect.java.
Note on this.caller resolution:
Although references like these do work:
this.caller.caller.caller... // works
the equivalent using successive calls:
// does *not* work
for( caller=this.caller; caller != null; caller = caller.caller );
is prohibited by the restriction that you can only call .caller on a
literal this or caller reference. The effect is that magic caller
reference only works through the current 'this' reference.
The real explanation is that This referernces do not really know anything
about their depth on the call stack. It might even be hard to define
such a thing...
For those purposes we provide :
this.callstack
</pre>
*/
class Name implements java.io.Serializable {
// These do not change during evaluation
public NameSpace namespace;
String value = null;
// ---------------------------------------------------------
// The following instance variables mutate during evaluation and should
// be reset by the reset() method where necessary
// For evaluation
/**
* Remaining text to evaluate
*/
private String evalName;
/**
* The last part of the name evaluated. This is really only used for this,
* caller, and super resolution.
*/
private String lastEvalName;
private static final String FINISHED = null; // null evalname and we're finished
private Object evalBaseObject; // base object for current eval
private int callstackDepth; // number of times eval hit 'this.caller'
//
// End mutable instance variables.
// ---------------------------------------------------------
// Begin Cached result structures
// These are optimizations
// Note: it's ok to cache class resolution here because when the class
// space changes the namespace will discard cached names.
/**
* The result is a class
*/
Class asClass;
/**
* The result is a static method call on the following class
*/
Class classOfStaticMethod;
// End Cached result structures
private void reset() {
evalName = value;
evalBaseObject = null;
callstackDepth = 0;
}
/**
* This constructor should *not* be used in general. Use NameSpace
* getNameResolver() which supports caching.
*
* @see NameSpace getNameResolver().
*/
// I wish I could make this "friendly" to only NameSpace
Name(NameSpace namespace, String s) {
this.namespace = namespace;
value = s;
}
/**
* Resolve possibly complex name to an object value.
*
* Throws EvalError on various failures. A null object value is indicated by
* a Primitive.NULL. A return type of Primitive.VOID comes from attempting
* to access an undefined variable.
*
* Some cases: myVariable myVariable.foo myVariable.foo.bar
* java.awt.GridBagConstraints.BOTH
* my.package.stuff.MyClass.someField.someField...
*
* Interpreter reference is necessary to allow resolution of
* "this.interpreter" magic field. CallStack reference is necessary to allow
* resolution of "this.caller" magic field. "this.callstack" magic field.
*/
public Object toObject(CallStack callstack, Interpreter interpreter)
throws UtilEvalError {
return toObject(callstack, interpreter, false);
}
/**
* @see #toObject(CallStack, Interpreter)
* @param forceClass if true then resolution will only produce a class. This
* is necessary to disambiguate in cases where the grammar knows that we
* want a class; where in general the var path may be taken.
*/
synchronized public Object toObject(
CallStack callstack, Interpreter interpreter, boolean forceClass)
throws UtilEvalError {
reset();
Object obj = null;
while (evalName != null) {
obj = consumeNextObjectField(
callstack, interpreter, forceClass, false/*autoalloc*/);
}
if (obj == null) {
throw new InterpreterError("null value in toObject()");
}
return obj;
}
private Object completeRound(
String lastEvalName, String nextEvalName, Object returnObject) {
if (returnObject == null) {
throw new InterpreterError("lastEvalName = " + lastEvalName);
}
this.lastEvalName = lastEvalName;
this.evalName = nextEvalName;
this.evalBaseObject = returnObject;
return returnObject;
}
/**
* Get the next object by consuming one or more components of evalName.
* Often this consumes just one component, but if the name is a classname it
* will consume all of the components necessary to make the class
* identifier.
*/
private Object consumeNextObjectField(
CallStack callstack, Interpreter interpreter,
boolean forceClass, boolean autoAllocateThis)
throws UtilEvalError {
/*
Is it a simple variable name?
Doing this first gives the correct Java precedence for vars
vs. imported class names (at least in the simple case - see
tests/precedence1.bsh). It should also speed things up a bit.
*/
if ((evalBaseObject == null && !isCompound(evalName))
&& !forceClass) {
Object obj = resolveThisFieldReference(
callstack, namespace, interpreter, evalName, false);
if (obj != Primitive.VOID) {
return completeRound(evalName, FINISHED, obj);
}
}
/*
Is it a bsh script variable reference?
If we're just starting the eval of name (no base object)
or we're evaluating relative to a This type reference check.
*/
String varName = prefix(evalName, 1);
if ((evalBaseObject == null || evalBaseObject instanceof This)
&& !forceClass) {
if (Interpreter.DEBUG) {
Interpreter.debug("trying to resolve variable: " + varName);
}
Object obj;
// switch namespace and special var visibility
if (evalBaseObject == null) {
obj = resolveThisFieldReference(
callstack, namespace, interpreter, varName, false);
} else {
obj = resolveThisFieldReference(
callstack, ((This) evalBaseObject).namespace,
interpreter, varName, true);
}
if (obj != Primitive.VOID) {
// Resolved the variable
if (Interpreter.DEBUG) {
Interpreter.debug("resolved variable: " + varName
+ " in namespace: " + namespace);
}
return completeRound(varName, suffix(evalName), obj);
}
}
/*
Is it a class name?
If we're just starting eval of name try to make it, else fail.
*/
if (evalBaseObject == null) {
if (Interpreter.DEBUG) {
Interpreter.debug("trying class: " + evalName);
}
/*
Keep adding parts until we have a class
*/
Class clas = null;
int i = 1;
String className = null;
for (; i <= countParts(evalName); i++) {
className = prefix(evalName, i);
if ((clas = namespace.getClass(className)) != null) {
break;
}
}
if (clas != null) {
return completeRound(
className,
suffix(evalName, countParts(evalName) - i),
new ClassIdentifier(clas)
);
}
// not a class (or variable per above)
if (Interpreter.DEBUG) {
Interpreter.debug("not a class, trying var prefix " + evalName);
}
}
// No variable or class found in 'this' type ref.
// if autoAllocateThis then create one; a child 'this'.
if ((evalBaseObject == null || evalBaseObject instanceof This)
&& !forceClass && autoAllocateThis) {
NameSpace targetNameSpace
= (evalBaseObject == null)
? namespace : ((This) evalBaseObject).namespace;
Object obj = new NameSpace(
targetNameSpace, "auto: " + varName).getThis(interpreter);
targetNameSpace.setVariable(varName, obj, false);
return completeRound(varName, suffix(evalName), obj);
}
/*
If we didn't find a class or variable name (or prefix) above
there are two possibilities:
- If we are a simple name then we can pass as a void variable
reference.
- If we are compound then we must fail at this point.
*/
if (evalBaseObject == null) {
if (!isCompound(evalName)) {
return completeRound(evalName, FINISHED, Primitive.VOID);
} else {
throw new UtilEvalError(
"Class or variable not found: " + evalName);
}
}
/*
--------------------------------------------------------
After this point we're definitely evaluating relative to
a base object.
--------------------------------------------------------
*/
/*
Do some basic validity checks.
*/
if (evalBaseObject == Primitive.NULL) // previous round produced null
{
throw new UtilTargetError(new NullPointerException(
"Null Pointer while evaluating: " + value));
}
if (evalBaseObject == Primitive.VOID) // previous round produced void
{
throw new UtilEvalError(
"Undefined variable or class name while evaluating: " + value);
}
if (evalBaseObject instanceof Primitive) {
throw new UtilEvalError("Can't treat primitive like an object. "
+ "Error while evaluating: " + value);
}
/*
Resolve relative to a class type
static field, inner class, ?
*/
if (evalBaseObject instanceof ClassIdentifier) {
Class clas = ((ClassIdentifier) evalBaseObject).getTargetClass();
String field = prefix(evalName, 1);
// Class qualified 'this' reference from inner class.
// e.g. 'MyOuterClass.this'
if (field.equals("this")) {
// find the enclosing class instance space of the class name
NameSpace ns = namespace;
while (ns != null) {
// getClassInstance() throws exception if not there
if (ns.classInstance != null
&& ns.classInstance.getClass() == clas) {
return completeRound(
field, suffix(evalName), ns.classInstance);
}
ns = ns.getParent();
}
throw new UtilEvalError(
"Can't find enclosing 'this' instance of class: " + clas);
}
Object obj = null;
// static field?
try {
if (Interpreter.DEBUG) {
Interpreter.debug("Name call to getStaticFieldValue, class: "
+ clas + ", field:" + field);
}
obj = Reflect.getStaticFieldValue(clas, field);
} catch (ReflectError e) {
if (Interpreter.DEBUG) {
Interpreter.debug("field reflect error: " + e);
}
}
// inner class?
if (obj == null) {
String iclass = clas.getName() + "$" + field;
Class c = namespace.getClass(iclass);
if (c != null) {
obj = new ClassIdentifier(c);
}
}
if (obj == null) {
throw new UtilEvalError(
"No static field or inner class: "
+ field + " of " + clas);
}
return completeRound(field, suffix(evalName), obj);
}
/*
If we've fallen through here we are no longer resolving to
a class type.
*/
if (forceClass) {
throw new UtilEvalError(
value + " does not resolve to a class name.");
}
/*
Some kind of field access?
*/
String field = prefix(evalName, 1);
// length access on array?
if (field.equals("length") && evalBaseObject.getClass().isArray()) {
Object obj = new Primitive(Array.getLength(evalBaseObject));
return completeRound(field, suffix(evalName), obj);
}
// Check for field on object
// Note: could eliminate throwing the exception somehow
try {
Object obj = Reflect.getObjectFieldValue(evalBaseObject, field);
return completeRound(field, suffix(evalName), obj);
} catch (ReflectError e) {
/* not a field */ }
// if we get here we have failed
throw new UtilEvalError(
"Cannot access field: " + field + ", on object: " + evalBaseObject);
}
/**
* Resolve a variable relative to a This reference.
*
* This is the general variable resolution method, accomodating special
* fields from the This context. Together the namespace and interpreter
* comprise the This context. The callstack, if available allows for the
* this.caller construct. Optionally interpret special "magic" field names:
* e.g. interpreter.
* <p/>
*
* @param callstack may be null, but this is only legitimate in special
* cases where we are sure resolution will not involve this.caller.
*
* @param namespace the namespace of the this reference (should be the same
* as the top of the stack?
*/
Object resolveThisFieldReference(
CallStack callstack, NameSpace thisNameSpace, Interpreter interpreter,
String varName, boolean specialFieldsVisible)
throws UtilEvalError {
if (varName.equals("this")) {
/*
Somewhat of a hack. If the special fields are visible (we're
operating relative to a 'this' type already) dissallow further
.this references to prevent user from skipping to things like
super.this.caller
*/
if (specialFieldsVisible) {
throw new UtilEvalError("Redundant to call .this on This type");
}
// Allow getThis() to work through BlockNameSpace to the method
// namespace
// XXX re-eval this... do we need it?
This ths = thisNameSpace.getThis(interpreter);
thisNameSpace = ths.getNameSpace();
Object result = ths;
NameSpace classNameSpace = getClassNameSpace(thisNameSpace);
if (classNameSpace != null) {
if (isCompound(evalName)) {
result = classNameSpace.getThis(interpreter);
} else {
result = classNameSpace.getClassInstance();
}
}
return result;
}
/*
Some duplication for "super". See notes for "this" above
If we're in an enclsing class instance and have a superclass
instance our super is the superclass instance.
*/
if (varName.equals("super")) {
//if ( specialFieldsVisible )
//throw new UtilEvalError("Redundant to call .this on This type");
// Allow getSuper() to through BlockNameSpace to the method's super
This ths = thisNameSpace.getSuper(interpreter);
thisNameSpace = ths.getNameSpace();
// super is now the closure's super or class instance
// XXXX re-evaluate this
// can getSuper work by itself now?
// If we're a class instance and the parent is also a class instance
// then super means our parent.
if (thisNameSpace.getParent() != null
&& thisNameSpace.getParent().isClass) {
ths = thisNameSpace.getParent().getThis(interpreter);
}
return ths;
}
Object obj = null;
if (varName.equals("global")) {
obj = thisNameSpace.getGlobal(interpreter);
}
if (obj == null && specialFieldsVisible) {
switch (varName) {
case "namespace":
obj = thisNameSpace;
break;
case "variables":
obj = thisNameSpace.getVariableNames();
break;
case "methods":
obj = thisNameSpace.getMethodNames();
break;
case "interpreter":
if (lastEvalName.equals("this")) {
obj = interpreter;
} else {
throw new UtilEvalError(
"Can only call .interpreter on literal 'this'");
}
break;
default:
break;
}
}
if (obj == null && specialFieldsVisible && varName.equals("caller")) {
if (lastEvalName.equals("this") || lastEvalName.equals("caller")) {
// get the previous context (see notes for this class)
if (callstack == null) {
throw new InterpreterError("no callstack");
}
obj = callstack.get(++callstackDepth).getThis(
interpreter);
} else {
throw new UtilEvalError(
"Can only call .caller on literal 'this' or literal '.caller'");
}
// early return
return obj;
}
if (obj == null && specialFieldsVisible
&& varName.equals("callstack")) {
if (lastEvalName.equals("this")) {
// get the previous context (see notes for this class)
if (callstack == null) {
throw new InterpreterError("no callstack");
}
obj = callstack;
} else {
throw new UtilEvalError(
"Can only call .callstack on literal 'this'");
}
}
if (obj == null) {
obj = thisNameSpace.getVariable(varName);
}
if (obj == null) {
throw new InterpreterError("null this field ref:" + varName);
}
return obj;
}
/**
* @return the enclosing class body namespace or null if not in a class.
*/
static NameSpace getClassNameSpace(NameSpace thisNameSpace) {
// is a class instance
//if ( thisNameSpace.classInstance != null )
if (thisNameSpace.isClass) {
return thisNameSpace;
}
if (thisNameSpace.isMethod
&& thisNameSpace.getParent() != null
//&& thisNameSpace.getParent().classInstance != null
&& thisNameSpace.getParent().isClass) {
return thisNameSpace.getParent();
}
return null;
}
/**
* Check the cache, else use toObject() to try to resolve to a class
* identifier.
*
*
* @throws ClassNotFoundException on class not found.
* @throws ClassPathException (type of EvalError) on special case of
* ambiguous unqualified name after super import.
*/
synchronized public Class toClass()
throws ClassNotFoundException, UtilEvalError {
if (asClass != null) {
return asClass;
}
reset();
// "var" means untyped, return null class
if (evalName.equals("var")) {
return asClass = null;
}
/* Try straightforward class name first */
Class clas = namespace.getClass(evalName);
if (clas == null) {
/*
Try toObject() which knows how to work through inner classes
and see what we end up with
*/
Object obj = null;
try {
// Null interpreter and callstack references.
// class only resolution should not require them.
obj = toObject(null, null, true);
} catch (UtilEvalError e) {
}
// couldn't resolve it
if (obj instanceof ClassIdentifier) {
clas = ((ClassIdentifier) obj).getTargetClass();
}
}
if (clas == null) {
throw new ClassNotFoundException(
"Class: " + value + " not found in namespace");
}
asClass = clas;
return asClass;
}
/*
*/
synchronized public LHS toLHS(
CallStack callstack, Interpreter interpreter)
throws UtilEvalError {
// Should clean this up to a single return statement
reset();
LHS lhs;
// Simple (non-compound) variable assignment e.g. x=5;
if (!isCompound(evalName)) {
if (evalName.equals("this")) {
throw new UtilEvalError("Can't assign to 'this'.");
}
// Interpreter.debug("Simple var LHS...");
lhs = new LHS(namespace, evalName, false/*bubble up if allowed*/);
return lhs;
}
// Field e.g. foo.bar=5;
Object obj = null;
try {
while (evalName != null && isCompound(evalName)) {
obj = consumeNextObjectField(callstack, interpreter,
false/*forcclass*/, true/*autoallocthis*/);
}
} catch (UtilEvalError e) {
throw new UtilEvalError("LHS evaluation: " + e.getMessage());
}
// Finished eval and its a class.
if (evalName == null && obj instanceof ClassIdentifier) {
throw new UtilEvalError("Can't assign to class: " + value);
}
if (obj == null) {
throw new UtilEvalError("Error in LHS: " + value);
}
// e.g. this.x=5; or someThisType.x=5;
if (obj instanceof This) {
// dissallow assignment to magic fields
if (evalName.equals("namespace")
|| evalName.equals("variables")
|| evalName.equals("methods")
|| evalName.equals("caller")) {
throw new UtilEvalError(
"Can't assign to special variable: " + evalName);
}
Interpreter.debug("found This reference evaluating LHS");
/*
If this was a literal "super" reference then we allow recursion
in setting the variable to get the normal effect of finding the
nearest definition starting at the super scope. On any other
resolution qualified by a 'this' type reference we want to set
the variable directly in that scope. e.g. this.x=5; or
someThisType.x=5;
In the old scoping rules super didn't do this.
*/
boolean localVar = !lastEvalName.equals("super");
return new LHS(((This) obj).namespace, evalName, localVar);
}
if (evalName != null) {
try {
if (obj instanceof ClassIdentifier) {
Class clas = ((ClassIdentifier) obj).getTargetClass();
lhs = Reflect.getLHSStaticField(clas, evalName);
return lhs;
} else {
lhs = Reflect.getLHSObjectField(obj, evalName);
return lhs;
}
} catch (ReflectError e) {
throw new UtilEvalError("Field access: " + e);
}
}
throw new InterpreterError("Internal error in lhs...");
}
/**
* Invoke the method identified by this name. Performs caching of method
* resolution using SignatureKey.
* <p>
*
* Name contains a wholely unqualfied messy name; resolve it to ( object |
* static prefix ) + method name and invoke.
* <p>
*
* The interpreter is necessary to support 'this.interpreter' references in
* the called code. (e.g. debug());
* <p>
*
* <pre>
* Some cases:
*
* // dynamic
* local();
* myVariable.foo();
* myVariable.bar.blah.foo();
* // static
* java.lang.Integer.getInteger("foo");
* </pre>
*/
public Object invokeMethod(
Interpreter interpreter, Object[] args, CallStack callstack,
SimpleNode callerInfo
)
throws UtilEvalError, EvalError, ReflectError, InvocationTargetException {
String methodName = Name.suffix(value, 1);
BSHClassManager bcm = interpreter.getClassManager();
NameSpace namespace = callstack.top();
// Optimization - If classOfStaticMethod is set then we have already
// been here and determined that this is a static method invocation.
// Note: maybe factor this out with path below... clean up.
if (classOfStaticMethod != null) {
return Reflect.invokeStaticMethod(
bcm, classOfStaticMethod, methodName, args);
}
if (!Name.isCompound(value)) {
return invokeLocalMethod(
interpreter, args, callstack, callerInfo);
}
// Note: if we want methods declared inside blocks to be accessible via
// this.methodname() inside the block we could handle it here as a
// special case. See also resolveThisFieldReference() special handling
// for BlockNameSpace case. They currently work via the direct name
// e.g. methodName().
String prefix = Name.prefix(value);
// Superclass method invocation? (e.g. super.foo())
if (prefix.equals("super") && Name.countParts(value) == 2) {
// Allow getThis() to work through block namespaces first
This ths = namespace.getThis(interpreter);
NameSpace thisNameSpace = ths.getNameSpace();
NameSpace classNameSpace = getClassNameSpace(thisNameSpace);
if (classNameSpace != null) {
Object instance = classNameSpace.getClassInstance();
return ClassGenerator.getClassGenerator()
.invokeSuperclassMethod(bcm, instance, methodName, args);
}
}
// Find target object or class identifier
Name targetName = namespace.getNameResolver(prefix);
Object obj = targetName.toObject(callstack, interpreter);
if (obj == Primitive.VOID) {
throw new UtilEvalError("Attempt to resolve method: " + methodName
+ "() on undefined variable or class name: " + targetName);
}
// if we've got an object, resolve the method
if (!(obj instanceof ClassIdentifier)) {
if (obj instanceof Primitive) {
if (obj == Primitive.NULL) {
throw new UtilTargetError(new NullPointerException(
"Null Pointer in Method Invocation of " + methodName
+ "() on variable: " + targetName));
}
// some other primitive
// should avoid calling methods on primitive, as we do
// in Name (can't treat primitive like an object message)
// but the hole is useful right now.
if (Interpreter.DEBUG) {
Interpreter.debug(
"Attempt to access method on primitive..."
+ " allowing bsh.Primitive to peek through for debugging");
}
}
// found an object and it's not an undefined variable
return Reflect.invokeObjectMethod(
obj, methodName, args, interpreter, callstack, callerInfo);
}
// It's a class
// try static method
if (Interpreter.DEBUG) {
Interpreter.debug("invokeMethod: trying static - " + targetName);
}
Class clas = ((ClassIdentifier) obj).getTargetClass();
// cache the fact that this is a static method invocation on this class
classOfStaticMethod = clas;
if (clas != null) {
return Reflect.invokeStaticMethod(bcm, clas, methodName, args);
}
// return null; ???
throw new UtilEvalError("invokeMethod: unknown target: " + targetName);
}
/**
* Invoke a locally declared method or a bsh command. If the method is not
* already declared in the namespace then try to load it as a resource from
* the imported command path (e.g. /bsh/commands)
*/
/*
Note: the bsh command code should probably not be here... we need to
scope it by the namespace that imported the command... so it probably
needs to be integrated into NameSpace.
*/
private Object invokeLocalMethod(
Interpreter interpreter, Object[] args, CallStack callstack,
SimpleNode callerInfo
)
throws EvalError/*, ReflectError, InvocationTargetException*/ {
if (Interpreter.DEBUG) {
Interpreter.debug("invokeLocalMethod: " + value);
}
if (interpreter == null) {
throw new InterpreterError(
"invokeLocalMethod: interpreter = null");
}
String commandName = value;
Class[] argTypes = Types.getTypes(args);
// Check for existing method
BSHMethod meth = null;
try {
meth = namespace.getMethod(commandName, argTypes);
} catch (UtilEvalError e) {
throw e.toEvalError(
"Local method invocation", callerInfo, callstack);
}
// If defined, invoke it
if (meth != null) {
return meth.invoke(args, interpreter, callstack, callerInfo);
}
BSHClassManager bcm = interpreter.getClassManager();
// Look for a BeanShell command
Object commandObject;
try {
commandObject = namespace.getCommand(
commandName, argTypes, interpreter);
} catch (UtilEvalError e) {
throw e.toEvalError("Error loading command: ",
callerInfo, callstack);
}
// should try to print usage here if nothing found
if (commandObject == null) {
// Look for a default invoke() handler method in the namespace
// Note: this code duplicates that in This.java... should it?
// Call on 'This' can never be a command
BSHMethod invokeMethod = null;
try {
invokeMethod = namespace.getMethod(
"invoke", new Class[]{null, null});
} catch (UtilEvalError e) {
throw e.toEvalError(
"Local method invocation", callerInfo, callstack);
}
if (invokeMethod != null) {
return invokeMethod.invoke(
new Object[]{commandName, args},
interpreter, callstack, callerInfo);
}
throw new EvalError("Command not found: "
+ StringUtil.methodString(commandName, argTypes),
callerInfo, callstack);
}
if (commandObject instanceof BSHMethod) {
return ((BSHMethod) commandObject).invoke(
args, interpreter, callstack, callerInfo);
}
if (commandObject instanceof Class) {
try {
return Reflect.invokeCompiledCommand(
((Class) commandObject), args, interpreter, callstack);
} catch (UtilEvalError e) {
throw e.toEvalError("Error invoking compiled command: ",
callerInfo, callstack);
}
}
throw new InterpreterError("invalid command type");
}
/*
private String getHelp( String name )
throws UtilEvalError
{
try {
// should check for null namespace here
return get( "bsh.help."+name, null/interpreter/ );
} catch ( Exception e ) {
return "usage: "+name;
}
}
private String getHelp( Class commandClass )
throws UtilEvalError
{
try {
return (String)Reflect.invokeStaticMethod(
null/bcm/, commandClass, "usage", null );
} catch( Exception e )
return "usage: "+name;
}
}
*/
// Static methods that operate on compound ('.' separated) names
// I guess we could move these to StringUtil someday
public static boolean isCompound(String value) {
return value.indexOf('.') != -1;
//return countParts(value) > 1;
}
static int countParts(String value) {
if (value == null) {
return 0;
}
int count = 0;
int index = -1;
while ((index = value.indexOf('.', index + 1)) != -1) {
count++;
}
return count + 1;
}
static String prefix(String value) {
if (!isCompound(value)) {
return null;
}
return prefix(value, countParts(value) - 1);
}
static String prefix(String value, int parts) {
if (parts < 1) {
return null;
}
int count = 0;
int index = -1;
while (((index = value.indexOf('.', index + 1)) != -1)
&& (++count < parts)) {
}
return (index == -1) ? value : value.substring(0, index);
}
static String suffix(String name) {
if (!isCompound(name)) {
return null;
}
return suffix(name, countParts(name) - 1);
}
public static String suffix(String value, int parts) {
if (parts < 1) {
return null;
}
int count = 0;
int index = value.length() + 1;
while (((index = value.lastIndexOf('.', index - 1)) != -1)
&& (++count < parts));
return (index == -1) ? value : value.substring(index + 1);
}
// end compound name routines
@Override
public String toString() {
return value;
}
}
| 38,785 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHUnaryExpression.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHUnaryExpression.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
class BSHUnaryExpression extends SimpleNode implements ParserConstants {
public int kind;
public boolean postfix = false;
BSHUnaryExpression(int id) {
super(id);
}
@Override
public Object eval(CallStack callstack, Interpreter interpreter)
throws EvalError {
SimpleNode node = (SimpleNode) jjtGetChild(0);
// If this is a unary increment of decrement (either pre or postfix)
// then we need an LHS to which to assign the result. Otherwise
// just do the unary operation for the value.
try {
if (kind == INCR || kind == DECR) {
LHS lhs = ((BSHPrimaryExpression) node).toLHS(
callstack, interpreter);
return lhsUnaryOperation(lhs, interpreter.getStrictJava());
} else {
return unaryOperation(node.eval(callstack, interpreter), kind);
}
} catch (UtilEvalError e) {
throw e.toEvalError(this, callstack);
}
}
private Object lhsUnaryOperation(LHS lhs, boolean strictJava)
throws UtilEvalError {
if (Interpreter.DEBUG) {
Interpreter.debug("lhsUnaryOperation");
}
Object prevalue, postvalue;
prevalue = lhs.getValue();
postvalue = unaryOperation(prevalue, kind);
Object retVal;
if (postfix) {
retVal = prevalue;
} else {
retVal = postvalue;
}
lhs.assign(postvalue, strictJava);
return retVal;
}
private Object unaryOperation(Object op, int kind) throws UtilEvalError {
if (op instanceof Boolean || op instanceof Character
|| op instanceof Number) {
return primitiveWrapperUnaryOperation(op, kind);
}
if (!(op instanceof Primitive)) {
throw new UtilEvalError("Unary operation " + tokenImage[kind]
+ " inappropriate for object");
}
return Primitive.unaryOperation((Primitive) op, kind);
}
private Object primitiveWrapperUnaryOperation(Object val, int kind)
throws UtilEvalError {
Class operandType = val.getClass();
Object operand = Primitive.promoteToInteger(val);
if (operand instanceof Boolean) {
return Primitive.booleanUnaryOperation((Boolean) operand, kind);
} else if (operand instanceof Integer) {
int result = Primitive.intUnaryOperation((Integer) operand, kind);
// ++ and -- must be cast back the original type
if (kind == INCR || kind == DECR) {
if (operandType == Byte.TYPE) {
return (byte) result;
}
if (operandType == Short.TYPE) {
return (short) result;
}
if (operandType == Character.TYPE) {
return (char) result;
}
}
return result;
} else if (operand instanceof Long) {
return Primitive.longUnaryOperation((Long) operand, kind);
} else if (operand instanceof Float) {
return Primitive.floatUnaryOperation((Float) operand, kind);
} else if (operand instanceof Double) {
return Primitive.doubleUnaryOperation((Double) operand, kind);
} else {
throw new InterpreterError("An error occurred. Please call technical support.");
}
}
}
| 6,047 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHReturnType.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHReturnType.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
class BSHReturnType extends SimpleNode {
public boolean isVoid;
BSHReturnType(int id) {
super(id);
}
BSHType getTypeNode() {
return (BSHType) jjtGetChild(0);
}
public String getTypeDescriptor(
CallStack callstack, Interpreter interpreter, String defaultPackage) {
if (isVoid) {
return "V";
} else {
return getTypeNode().getTypeDescriptor(
callstack, interpreter, defaultPackage);
}
}
public Class evalReturnType(
CallStack callstack, Interpreter interpreter) throws EvalError {
if (isVoid) {
return Void.TYPE;
} else {
return getTypeNode().getType(callstack, interpreter);
}
}
}
| 3,328 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
ClassIdentifier.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/ClassIdentifier.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
public class ClassIdentifier {
Class clas;
public ClassIdentifier(Class clas) {
this.clas = clas;
}
// Can't call it getClass()
public Class getTargetClass() {
return clas;
}
@Override
public String toString() {
return "Class Identifier: " + clas.getName();
}
}
| 2,878 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHClassDeclaration.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHClassDeclaration.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
/**
*/
class BSHClassDeclaration extends SimpleNode {
/**
* The class instance initializer method name. A BshMethod by this name is
* installed by the class delcaration into the static class body namespace.
* It is called once to initialize the static members of the class space and
* each time an instances is created to initialize the instance members.
*/
static final String CLASSINITNAME = "_bshClassInit";
String name;
Modifiers modifiers;
int numInterfaces;
boolean extend;
boolean isInterface;
private Class<?> generatedClass;
BSHClassDeclaration(int id) {
super(id);
}
/**
*/
@Override
public synchronized Object eval(final CallStack callstack, final Interpreter interpreter) throws EvalError {
if (generatedClass == null) {
generatedClass = generateClass(callstack, interpreter);
}
return generatedClass;
}
private Class<?> generateClass(final CallStack callstack, final Interpreter interpreter) throws EvalError {
int child = 0;
// resolve superclass if any
Class superClass = null;
if (extend) {
BSHAmbiguousName superNode = (BSHAmbiguousName) jjtGetChild(child++);
superClass = superNode.toClass(callstack, interpreter);
}
// Get interfaces
Class[] interfaces = new Class[numInterfaces];
for (int i = 0; i < numInterfaces; i++) {
BSHAmbiguousName node = (BSHAmbiguousName) jjtGetChild(child++);
interfaces[i] = node.toClass(callstack, interpreter);
if (!interfaces[i].isInterface()) {
throw new EvalError(
"Type: " + node.text + " is not an interface!",
this, callstack);
}
}
BSHBlock block;
// Get the class body BSHBlock
if (child < jjtGetNumChildren()) {
block = (BSHBlock) jjtGetChild(child);
} else {
block = new BSHBlock(ParserTreeConstants.JJTBLOCK);
}
return ClassGenerator.getClassGenerator().generateClass(
name, modifiers, interfaces, superClass, block, isInterface,
callstack, interpreter);
}
@Override
public String toString() {
return "ClassDeclaration: " + name;
}
}
| 4,927 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHFormalParameters.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHFormalParameters.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
class BSHFormalParameters extends SimpleNode {
private String[] paramNames;
/**
* For loose type parameters the paramTypes are null.
*/
// unsafe caching of types
Class[] paramTypes;
int numArgs;
String[] typeDescriptors;
BSHFormalParameters(int id) {
super(id);
}
void insureParsed() {
if (paramNames != null) {
return;
}
this.numArgs = jjtGetNumChildren();
String[] paramNames = new String[numArgs];
for (int i = 0; i < numArgs; i++) {
BSHFormalParameter param = (BSHFormalParameter) jjtGetChild(i);
paramNames[i] = param.name;
}
this.paramNames = paramNames;
}
public String[] getParamNames() {
insureParsed();
return paramNames;
}
public String[] getTypeDescriptors(
CallStack callstack, Interpreter interpreter, String defaultPackage) {
if (typeDescriptors != null) {
return typeDescriptors;
}
insureParsed();
String[] typeDesc = new String[numArgs];
for (int i = 0; i < numArgs; i++) {
BSHFormalParameter param = (BSHFormalParameter) jjtGetChild(i);
typeDesc[i] = param.getTypeDescriptor(
callstack, interpreter, defaultPackage);
}
this.typeDescriptors = typeDesc;
return typeDesc;
}
/**
* Evaluate the types. Note that type resolution does not require the
* interpreter instance.
*/
@Override
public Object eval(CallStack callstack, Interpreter interpreter)
throws EvalError {
if (paramTypes != null) {
return paramTypes;
}
insureParsed();
Class[] paramTypes = new Class[numArgs];
for (int i = 0; i < numArgs; i++) {
BSHFormalParameter param = (BSHFormalParameter) jjtGetChild(i);
paramTypes[i] = (Class) param.eval(callstack, interpreter);
}
this.paramTypes = paramTypes;
return paramTypes;
}
}
| 4,628 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHAssignment.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHAssignment.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
class BSHAssignment extends SimpleNode implements ParserConstants {
public int operator;
BSHAssignment(int id) {
super(id);
}
@Override
public Object eval(
CallStack callstack, Interpreter interpreter)
throws EvalError {
BSHPrimaryExpression lhsNode
= (BSHPrimaryExpression) jjtGetChild(0);
if (lhsNode == null) {
throw new InterpreterError("Error, null LHSnode");
}
boolean strictJava = interpreter.getStrictJava();
LHS lhs = lhsNode.toLHS(callstack, interpreter);
if (lhs == null) {
throw new InterpreterError("Error, null LHS");
}
// For operator-assign operations save the lhs value before evaluating
// the rhs. This is correct Java behavior for postfix operations
// e.g. i=1; i+=i++; // should be 2 not 3
Object lhsValue = null;
if (operator != ASSIGN) // assign doesn't need the pre-value
{
try {
lhsValue = lhs.getValue();
} catch (UtilEvalError e) {
throw e.toEvalError(this, callstack);
}
}
SimpleNode rhsNode = (SimpleNode) jjtGetChild(1);
Object rhs;
// implement "blocks" foo = { };
// if ( rhsNode instanceof BSHBlock )
// rsh =
// else
rhs = rhsNode.eval(callstack, interpreter);
if (rhs == Primitive.VOID) {
throw new EvalError("Void assignment.", this, callstack);
}
try {
switch (operator) {
case ASSIGN:
return lhs.assign(rhs, strictJava);
case PLUSASSIGN:
return lhs.assign(
operation(lhsValue, rhs, PLUS), strictJava);
case MINUSASSIGN:
return lhs.assign(
operation(lhsValue, rhs, MINUS), strictJava);
case STARASSIGN:
return lhs.assign(
operation(lhsValue, rhs, STAR), strictJava);
case SLASHASSIGN:
return lhs.assign(
operation(lhsValue, rhs, SLASH), strictJava);
case ANDASSIGN:
case ANDASSIGNX:
return lhs.assign(
operation(lhsValue, rhs, BIT_AND), strictJava);
case ORASSIGN:
case ORASSIGNX:
return lhs.assign(
operation(lhsValue, rhs, BIT_OR), strictJava);
case XORASSIGN:
return lhs.assign(
operation(lhsValue, rhs, XOR), strictJava);
case MODASSIGN:
return lhs.assign(
operation(lhsValue, rhs, MOD), strictJava);
case LSHIFTASSIGN:
case LSHIFTASSIGNX:
return lhs.assign(
operation(lhsValue, rhs, LSHIFT), strictJava);
case RSIGNEDSHIFTASSIGN:
case RSIGNEDSHIFTASSIGNX:
return lhs.assign(
operation(lhsValue, rhs, RSIGNEDSHIFT), strictJava);
case RUNSIGNEDSHIFTASSIGN:
case RUNSIGNEDSHIFTASSIGNX:
return lhs.assign(
operation(lhsValue, rhs, RUNSIGNEDSHIFT),
strictJava);
default:
throw new InterpreterError(
"unimplemented operator in assignment BSH");
}
} catch (UtilEvalError e) {
throw e.toEvalError(this, callstack);
}
}
private Object operation(Object lhs, Object rhs, int kind)
throws UtilEvalError {
/*
Implement String += value;
According to the JLS, value may be anything.
In BeanShell, we'll disallow VOID (undefined) values.
(or should we map them to the empty string?)
*/
if (lhs instanceof String && rhs != Primitive.VOID) {
if (kind != PLUS) {
throw new UtilEvalError(
"Use of non + operator with String LHS");
}
return (String) lhs + rhs;
}
if (lhs instanceof Primitive || rhs instanceof Primitive) {
if (lhs == Primitive.VOID || rhs == Primitive.VOID) {
throw new UtilEvalError(
"Illegal use of undefined object or 'void' literal");
} else if (lhs == Primitive.NULL || rhs == Primitive.NULL) {
throw new UtilEvalError(
"Illegal use of null object or 'null' literal");
}
}
if ((lhs instanceof Boolean || lhs instanceof Character
|| lhs instanceof Number || lhs instanceof Primitive)
&& (rhs instanceof Boolean || rhs instanceof Character
|| rhs instanceof Number || rhs instanceof Primitive)) {
return Primitive.binaryOperation(lhs, rhs, kind);
}
throw new UtilEvalError("Non primitive value in operator: "
+ lhs.getClass() + " " + tokenImage[kind] + " " + rhs.getClass());
}
}
| 7,910 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
Type.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/Type.java | /** *
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (C) 2000 INRIA, France Telecom
* Copyright (C) 2002 France Telecom
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact: [email protected]
*
* Author: Eric Bruneton
*/
package ehacks.bsh;
import java.lang.reflect.Method;
/**
* A Java type. This class can be used to make it easier to manipulate type and
* method descriptors.
*/
public class Type {
/**
* The sort of the <tt>void</tt> type. See {@link #getSort getSort}.
*/
public final static int VOID = 0;
/**
* The sort of the <tt>boolean</tt> type. See {@link #getSort getSort}.
*/
public final static int BOOLEAN = 1;
/**
* The sort of the <tt>char</tt> type. See {@link #getSort getSort}.
*/
public final static int CHAR = 2;
/**
* The sort of the <tt>byte</tt> type. See {@link #getSort getSort}.
*/
public final static int BYTE = 3;
/**
* The sort of the <tt>short</tt> type. See {@link #getSort getSort}.
*/
public final static int SHORT = 4;
/**
* The sort of the <tt>int</tt> type. See {@link #getSort getSort}.
*/
public final static int INT = 5;
/**
* The sort of the <tt>float</tt> type. See {@link #getSort getSort}.
*/
public final static int FLOAT = 6;
/**
* The sort of the <tt>long</tt> type. See {@link #getSort getSort}.
*/
public final static int LONG = 7;
/**
* The sort of the <tt>double</tt> type. See {@link #getSort getSort}.
*/
public final static int DOUBLE = 8;
/**
* The sort of array reference types. See {@link #getSort getSort}.
*/
public final static int ARRAY = 9;
/**
* The sort of object reference type. See {@link #getSort getSort}.
*/
public final static int OBJECT = 10;
/**
* The <tt>void</tt> type.
*/
public final static Type VOID_TYPE = new Type(VOID);
/**
* The <tt>boolean</tt> type.
*/
public final static Type BOOLEAN_TYPE = new Type(BOOLEAN);
/**
* The <tt>char</tt> type.
*/
public final static Type CHAR_TYPE = new Type(CHAR);
/**
* The <tt>byte</tt> type.
*/
public final static Type BYTE_TYPE = new Type(BYTE);
/**
* The <tt>short</tt> type.
*/
public final static Type SHORT_TYPE = new Type(SHORT);
/**
* The <tt>int</tt> type.
*/
public final static Type INT_TYPE = new Type(INT);
/**
* The <tt>float</tt> type.
*/
public final static Type FLOAT_TYPE = new Type(FLOAT);
/**
* The <tt>long</tt> type.
*/
public final static Type LONG_TYPE = new Type(LONG);
/**
* The <tt>double</tt> type.
*/
public final static Type DOUBLE_TYPE = new Type(DOUBLE);
// --------------------------------------------------------------------------
// Fields
// --------------------------------------------------------------------------
/**
* The sort of this Java type.
*/
private final int sort;
/**
* A buffer containing the descriptor of this Java type. This field is only
* used for reference types.
*/
private char[] buf;
/**
* The offset of the descriptor of this Java type in {@link #buf buf}. This
* field is only used for reference types.
*/
private int off;
/**
* The length of the descriptor of this Java type.
*/
private int len;
// --------------------------------------------------------------------------
// Constructors
// --------------------------------------------------------------------------
/**
* Constructs a primitive type.
*
* @param sort the sort of the primitive type to be constructed.
*/
private Type(final int sort) {
this.sort = sort;
this.len = 1;
}
/**
* Constructs a reference type.
*
* @param sort the sort of the reference type to be constructed.
* @param buf a buffer containing the descriptor of the previous type.
* @param off the offset of this descriptor in the previous buffer.
* @param len the length of this descriptor.
*/
private Type(
final int sort,
final char[] buf,
final int off,
final int len) {
this.sort = sort;
this.buf = buf;
this.off = off;
this.len = len;
}
/**
* Returns the Java type corresponding to the given type descriptor.
*
* @param typeDescriptor a type descriptor.
* @return the Java type corresponding to the given type descriptor.
*/
public static Type getType(final String typeDescriptor) {
return getType(typeDescriptor.toCharArray(), 0);
}
/**
* Returns the Java type corresponding to the given class.
*
* @param c a class.
* @return the Java type corresponding to the given class.
*/
public static Type getType(final Class c) {
if (c.isPrimitive()) {
if (c == Integer.TYPE) {
return INT_TYPE;
} else if (c == Void.TYPE) {
return VOID_TYPE;
} else if (c == Boolean.TYPE) {
return BOOLEAN_TYPE;
} else if (c == Byte.TYPE) {
return BYTE_TYPE;
} else if (c == Character.TYPE) {
return CHAR_TYPE;
} else if (c == Short.TYPE) {
return SHORT_TYPE;
} else if (c == Double.TYPE) {
return DOUBLE_TYPE;
} else if (c == Float.TYPE) {
return FLOAT_TYPE;
} else /*if (c == Long.TYPE)*/ {
return LONG_TYPE;
}
} else {
return getType(getDescriptor(c));
}
}
/**
* Returns the Java types corresponding to the argument types of the given
* method descriptor.
*
* @param methodDescriptor a method descriptor.
* @return the Java types corresponding to the argument types of the given
* method descriptor.
*/
public static Type[] getArgumentTypes(final String methodDescriptor) {
char[] buf = methodDescriptor.toCharArray();
int off = 1;
int size = 0;
while (true) {
char car = buf[off++];
if (car == ')') {
break;
} else if (car == 'L') {
while (buf[off++] != ';') {
}
++size;
} else if (car != '[') {
++size;
}
}
Type[] args = new Type[size];
off = 1;
size = 0;
while (buf[off] != ')') {
args[size] = getType(buf, off);
off += args[size].len;
size += 1;
}
return args;
}
/**
* Returns the Java types corresponding to the argument types of the given
* method.
*
* @param method a method.
* @return the Java types corresponding to the argument types of the given
* method.
*/
public static Type[] getArgumentTypes(final Method method) {
Class[] classes = method.getParameterTypes();
Type[] types = new Type[classes.length];
for (int i = classes.length - 1; i >= 0; --i) {
types[i] = getType(classes[i]);
}
return types;
}
/**
* Returns the Java type corresponding to the return type of the given
* method descriptor.
*
* @param methodDescriptor a method descriptor.
* @return the Java type corresponding to the return type of the given
* method descriptor.
*/
public static Type getReturnType(final String methodDescriptor) {
char[] buf = methodDescriptor.toCharArray();
return getType(buf, methodDescriptor.indexOf(')') + 1);
}
/**
* Returns the Java type corresponding to the return type of the given
* method.
*
* @param method a method.
* @return the Java type corresponding to the return type of the given
* method.
*/
public static Type getReturnType(final Method method) {
return getType(method.getReturnType());
}
/**
* Returns the Java type corresponding to the given type descriptor.
*
* @param buf a buffer containing a type descriptor.
* @param off the offset of this descriptor in the previous buffer.
* @return the Java type corresponding to the given type descriptor.
*/
private static Type getType(final char[] buf, final int off) {
int len;
switch (buf[off]) {
case 'V':
return VOID_TYPE;
case 'Z':
return BOOLEAN_TYPE;
case 'C':
return CHAR_TYPE;
case 'B':
return BYTE_TYPE;
case 'S':
return SHORT_TYPE;
case 'I':
return INT_TYPE;
case 'F':
return FLOAT_TYPE;
case 'J':
return LONG_TYPE;
case 'D':
return DOUBLE_TYPE;
case '[':
len = 1;
while (buf[off + len] == '[') {
++len;
}
if (buf[off + len] == 'L') {
++len;
while (buf[off + len] != ';') {
++len;
}
}
return new Type(ARRAY, buf, off, len + 1);
//case 'L':
default:
len = 1;
while (buf[off + len] != ';') {
++len;
}
return new Type(OBJECT, buf, off, len + 1);
}
}
// --------------------------------------------------------------------------
// Accessors
// --------------------------------------------------------------------------
/**
* Returns the sort of this Java type.
*
* @return {@link #VOID VOID}, {@link #BOOLEAN BOOLEAN}, {@link #CHAR CHAR},
* {@link #BYTE BYTE}, {@link #SHORT SHORT}, {@link #INT INT}, {@link
* #FLOAT FLOAT}, {@link #LONG LONG}, {@link #DOUBLE DOUBLE}, {@link
* #ARRAY ARRAY} or {@link #OBJECT OBJECT}.
*/
public int getSort() {
return sort;
}
/**
* Returns the number of dimensions of this array type. This method should
* only be used for an array type.
*
* @return the number of dimensions of this array type.
*/
public int getDimensions() {
int i = 1;
while (buf[off + i] == '[') {
++i;
}
return i;
}
/**
* Returns the type of the elements of this array type. This method should
* only be used for an array type.
*
* @return Returns the type of the elements of this array type.
*/
public Type getElementType() {
return getType(buf, off + getDimensions());
}
/**
* Returns the name of the class corresponding to this object type. This
* method should only be used for an object type.
*
* @return the fully qualified name of the class corresponding to this
* object type.
*/
public String getClassName() {
return new String(buf, off + 1, len - 2).replace('/', '.');
}
/**
* Returns the internal name of the class corresponding to this object type.
* The internal name of a class is its fully qualified name, where '.' are
* replaced by '/'. * This method should only be used for an object type.
*
* @return the internal name of the class corresponding to this object type.
*/
public String getInternalName() {
return new String(buf, off + 1, len - 2);
}
// --------------------------------------------------------------------------
// Conversion to type descriptors
// --------------------------------------------------------------------------
/**
* Returns the descriptor corresponding to this Java type.
*
* @return the descriptor corresponding to this Java type.
*/
public String getDescriptor() {
StringBuffer buf = new StringBuffer();
getDescriptor(buf);
return buf.toString();
}
/**
* Returns the descriptor corresponding to the given argument and return
* types.
*
* @param returnType the return type of the method.
* @param argumentTypes the argument types of the method.
* @return the descriptor corresponding to the given argument and return
* types.
*/
public static String getMethodDescriptor(
final Type returnType,
final Type[] argumentTypes) {
StringBuffer buf = new StringBuffer();
buf.append('(');
for (int i = 0; i < argumentTypes.length; ++i) {
argumentTypes[i].getDescriptor(buf);
}
buf.append(')');
returnType.getDescriptor(buf);
return buf.toString();
}
/**
* Appends the descriptor corresponding to this Java type to the given
* string buffer.
*
* @param buf the string buffer to which the descriptor must be appended.
*/
private void getDescriptor(final StringBuffer buf) {
switch (sort) {
case VOID:
buf.append('V');
return;
case BOOLEAN:
buf.append('Z');
return;
case CHAR:
buf.append('C');
return;
case BYTE:
buf.append('B');
return;
case SHORT:
buf.append('S');
return;
case INT:
buf.append('I');
return;
case FLOAT:
buf.append('F');
return;
case LONG:
buf.append('J');
return;
case DOUBLE:
buf.append('D');
return;
//case ARRAY:
//case OBJECT:
default:
buf.append(this.buf, off, len);
}
}
// --------------------------------------------------------------------------
// Direct conversion from classes to type descriptors,
// without intermediate Type objects
// --------------------------------------------------------------------------
/**
* Returns the internal name of the given class. The internal name of a
* class is its fully qualified name, where '.' are replaced by '/'.
*
* @param c an object class.
* @return the internal name of the given class.
*/
public static String getInternalName(final Class c) {
return c.getName().replace('.', '/');
}
/**
* Returns the descriptor corresponding to the given Java type.
*
* @param c an object class, a primitive class or an array class.
* @return the descriptor corresponding to the given class.
*/
public static String getDescriptor(final Class c) {
StringBuffer buf = new StringBuffer();
getDescriptor(buf, c);
return buf.toString();
}
/**
* Returns the descriptor corresponding to the given method.
*
* @param m a {@link Method Method} object.
* @return the descriptor of the given method.
*/
public static String getMethodDescriptor(final Method m) {
Class[] parameters = m.getParameterTypes();
StringBuffer buf = new StringBuffer();
buf.append('(');
for (int i = 0; i < parameters.length; ++i) {
getDescriptor(buf, parameters[i]);
}
buf.append(')');
getDescriptor(buf, m.getReturnType());
return buf.toString();
}
/**
* Appends the descriptor of the given class to the given string buffer.
*
* @param buf the string buffer to which the descriptor must be appended.
* @param c the class whose descriptor must be computed.
*/
private static void getDescriptor(final StringBuffer buf, final Class c) {
Class d = c;
while (true) {
if (d.isPrimitive()) {
char car;
if (d == Integer.TYPE) {
car = 'I';
} else if (d == Void.TYPE) {
car = 'V';
} else if (d == Boolean.TYPE) {
car = 'Z';
} else if (d == Byte.TYPE) {
car = 'B';
} else if (d == Character.TYPE) {
car = 'C';
} else if (d == Short.TYPE) {
car = 'S';
} else if (d == Double.TYPE) {
car = 'D';
} else if (d == Float.TYPE) {
car = 'F';
} else /*if (d == Long.TYPE)*/ {
car = 'J';
}
buf.append(car);
return;
} else if (d.isArray()) {
buf.append('[');
d = d.getComponentType();
} else {
buf.append('L');
String name = d.getName();
int len = name.length();
for (int i = 0; i < len; ++i) {
char car = name.charAt(i);
buf.append(car == '.' ? '/' : car);
}
buf.append(';');
return;
}
}
}
// --------------------------------------------------------------------------
// Corresponding size and opcodes
// --------------------------------------------------------------------------
/**
* Returns the size of values of this type.
*
* @return the size of values of this type, i.e., 2 for <tt>long</tt> and
* <tt>double</tt>, and 1 otherwise.
*/
public int getSize() {
return (sort == LONG || sort == DOUBLE ? 2 : 1);
}
/**
* Returns a JVM instruction opcode adapted to this Java type.
*
* @param opcode a JVM instruction opcode. This opcode must be one of ILOAD,
* ISTORE, IALOAD, IASTORE, IADD, ISUB, IMUL, IDIV, IREM, INEG, ISHL, ISHR,
* IUSHR, IAND, IOR, IXOR and IRETURN.
* @return an opcode that is similar to the given opcode, but adapted to
* this Java type. For example, if this type is <tt>float</tt> and
* <tt>opcode</tt> is IRETURN, this method returns FRETURN.
*/
public int getOpcode(final int opcode) {
if (opcode == Constants.IALOAD || opcode == Constants.IASTORE) {
switch (sort) {
case VOID:
return opcode + 5;
case BOOLEAN:
case BYTE:
return opcode + 6;
case CHAR:
return opcode + 7;
case SHORT:
return opcode + 8;
case INT:
return opcode;
case FLOAT:
return opcode + 2;
case LONG:
return opcode + 1;
case DOUBLE:
return opcode + 3;
//case ARRAY:
//case OBJECT:
default:
return opcode + 4;
}
} else {
switch (sort) {
case VOID:
return opcode + 5;
case BOOLEAN:
case CHAR:
case BYTE:
case SHORT:
case INT:
return opcode;
case FLOAT:
return opcode + 2;
case LONG:
return opcode + 1;
case DOUBLE:
return opcode + 3;
//case ARRAY:
//case OBJECT:
default:
return opcode + 4;
}
}
}
}
| 20,721 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
CollectionManager.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/CollectionManager.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
import java.lang.reflect.Array;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
/**
* The default CollectionManager supports iteration over objects of type:
* Enumeration, Iterator, Iterable, CharSequence, and array.
*/
public class CollectionManager {
private static final CollectionManager manager = new CollectionManager();
public synchronized static CollectionManager getCollectionManager() {
return manager;
}
/**
*/
public boolean isBshIterable(Object obj) {
// This could be smarter...
try {
getBshIterator(obj);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
public Iterator getBshIterator(Object obj)
throws IllegalArgumentException {
if (obj == null) {
throw new NullPointerException("Cannot iterate over null.");
}
if (obj instanceof Enumeration) {
final Enumeration enumeration = (Enumeration) obj;
return new Iterator<Object>() {
@Override
public boolean hasNext() {
return enumeration.hasMoreElements();
}
@Override
public Object next() {
return enumeration.nextElement();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
if (obj instanceof Iterator) {
return (Iterator) obj;
}
if (obj instanceof Iterable) {
return ((Iterable) obj).iterator();
}
if (obj.getClass().isArray()) {
final Object array = obj;
return new Iterator() {
private int index = 0;
private final int length = Array.getLength(array);
@Override
public boolean hasNext() {
return index < length;
}
@Override
public Object next() {
return Array.get(array, index++);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
if (obj instanceof CharSequence) {
return getBshIterator(
obj.toString().toCharArray());
}
throw new IllegalArgumentException(
"Cannot iterate over object of type " + obj.getClass());
}
public boolean isMap(Object obj) {
return obj instanceof Map;
}
public Object getFromMap(Object map, Object key) {
return ((Map) map).get(key);
}
public Object putInMap(Object map, Object key, Object value) {
return ((Map) map).put(key, value);
}
}
| 5,504 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
ParserTreeConstants.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/ParserTreeConstants.java | /* Generated By:JJTree: Do not edit this line. src/bsh/ParserTreeConstants.java */
package ehacks.bsh;
public interface ParserTreeConstants {
public int JJTVOID = 0;
public int JJTCLASSDECLARATION = 1;
public int JJTMETHODDECLARATION = 2;
public int JJTPACKAGEDECLARATION = 3;
public int JJTIMPORTDECLARATION = 4;
public int JJTVARIABLEDECLARATOR = 5;
public int JJTARRAYINITIALIZER = 6;
public int JJTFORMALPARAMETERS = 7;
public int JJTFORMALPARAMETER = 8;
public int JJTTYPE = 9;
public int JJTRETURNTYPE = 10;
public int JJTPRIMITIVETYPE = 11;
public int JJTAMBIGUOUSNAME = 12;
public int JJTASSIGNMENT = 13;
public int JJTTERNARYEXPRESSION = 14;
public int JJTBINARYEXPRESSION = 15;
public int JJTUNARYEXPRESSION = 16;
public int JJTCASTEXPRESSION = 17;
public int JJTPRIMARYEXPRESSION = 18;
public int JJTMETHODINVOCATION = 19;
public int JJTPRIMARYSUFFIX = 20;
public int JJTLITERAL = 21;
public int JJTARGUMENTS = 22;
public int JJTALLOCATIONEXPRESSION = 23;
public int JJTARRAYDIMENSIONS = 24;
public int JJTBLOCK = 25;
public int JJTFORMALCOMMENT = 26;
public int JJTSWITCHSTATEMENT = 27;
public int JJTSWITCHLABEL = 28;
public int JJTIFSTATEMENT = 29;
public int JJTWHILESTATEMENT = 30;
public int JJTFORSTATEMENT = 31;
public int JJTENHANCEDFORSTATEMENT = 32;
public int JJTTYPEDVARIABLEDECLARATION = 33;
public int JJTSTATEMENTEXPRESSIONLIST = 34;
public int JJTRETURNSTATEMENT = 35;
public int JJTTHROWSTATEMENT = 36;
public int JJTTRYSTATEMENT = 37;
public String[] jjtNodeName = {
"void",
"ClassDeclaration",
"MethodDeclaration",
"PackageDeclaration",
"ImportDeclaration",
"VariableDeclarator",
"ArrayInitializer",
"FormalParameters",
"FormalParameter",
"Type",
"ReturnType",
"PrimitiveType",
"AmbiguousName",
"Assignment",
"TernaryExpression",
"BinaryExpression",
"UnaryExpression",
"CastExpression",
"PrimaryExpression",
"MethodInvocation",
"PrimarySuffix",
"Literal",
"Arguments",
"AllocationExpression",
"ArrayDimensions",
"Block",
"FormalComment",
"SwitchStatement",
"SwitchLabel",
"IfStatement",
"WhileStatement",
"ForStatement",
"EnhancedForStatement",
"TypedVariableDeclaration",
"StatementExpressionList",
"ReturnStatement",
"ThrowStatement",
"TryStatement",};
}
| 2,651 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHFormalComment.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHFormalComment.java | /* Generated By:JJTree: Do not edit this line. BSHFormalComment.java */
package ehacks.bsh;
public class BSHFormalComment extends SimpleNode {
public String text;
public BSHFormalComment(int id) {
super(id);
}
}
| 236 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHEnhancedForStatement.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHEnhancedForStatement.java | package ehacks.bsh;
// Just testing...
import java.util.*;
/**
* Implementation of the enhanced for(:) statement. This statement uses Iterator
* to support iteration over a wide variety of iterable types.
*
* @author Daniel Leuck
* @author Pat Niemeyer
*/
class BSHEnhancedForStatement extends SimpleNode implements ParserConstants {
String varName;
BSHEnhancedForStatement(int id) {
super(id);
}
@Override
public Object eval(CallStack callstack, Interpreter interpreter)
throws EvalError {
Class elementType = null;
SimpleNode expression, statement = null;
NameSpace enclosingNameSpace = callstack.top();
SimpleNode firstNode = ((SimpleNode) jjtGetChild(0));
int nodeCount = jjtGetNumChildren();
if (firstNode instanceof BSHType) {
elementType = ((BSHType) firstNode).getType(callstack, interpreter);
expression = ((SimpleNode) jjtGetChild(1));
if (nodeCount > 2) {
statement = ((SimpleNode) jjtGetChild(2));
}
} else {
expression = firstNode;
if (nodeCount > 1) {
statement = ((SimpleNode) jjtGetChild(1));
}
}
BlockNameSpace eachNameSpace = new BlockNameSpace(enclosingNameSpace);
callstack.swap(eachNameSpace);
final Object iteratee = expression.eval(callstack, interpreter);
if (iteratee == Primitive.NULL) {
throw new EvalError("The collection, array, map, iterator, or "
+ "enumeration portion of a for statement cannot be null.",
this, callstack);
}
CollectionManager cm = CollectionManager.getCollectionManager();
if (!cm.isBshIterable(iteratee)) {
throw new EvalError("Can't iterate over type: "
+ iteratee.getClass(), this, callstack);
}
Iterator iterator = cm.getBshIterator(iteratee);
Object returnControl = Primitive.VOID;
while (iterator.hasNext()) {
try {
Object value = iterator.next();
if (value == null) {
value = Primitive.NULL;
}
if (elementType != null) {
eachNameSpace.setTypedVariable(
varName/*name*/, elementType/*type*/,
value, new Modifiers()/*none*/);
} else {
eachNameSpace.setVariable(varName, value, false);
}
} catch (UtilEvalError e) {
throw e.toEvalError(
"for loop iterator variable:" + varName, this, callstack);
}
boolean breakout = false; // switch eats a multi-level break here?
if (statement != null) // not empty statement
{
Object ret = statement.eval(callstack, interpreter);
if (ret instanceof ReturnControl) {
switch (((ReturnControl) ret).kind) {
case RETURN:
returnControl = ret;
breakout = true;
break;
case CONTINUE:
break;
case BREAK:
breakout = true;
break;
}
}
}
if (breakout) {
break;
}
}
callstack.swap(enclosingNameSpace);
return returnControl;
}
}
| 3,653 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
ParserTokenManager.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/ParserTokenManager.java | /* Generated By:JJTree&JavaCC: Do not edit this line. ParserTokenManager.java */
package ehacks.bsh;
public class ParserTokenManager implements ParserConstants {
public java.io.PrintStream debugStream = System.out;
public void setDebugStream(java.io.PrintStream ds) {
debugStream = ds;
}
private int jjStopStringLiteralDfa_0(int pos, long active0, long active1, long active2) {
switch (pos) {
case 0:
if ((active0 & 0x3eL) != 0L) {
return 0;
}
if ((active1 & 0x20000L) != 0L) {
return 11;
}
if ((active1 & 0x400040000000000L) != 0L) {
return 65;
}
if ((active0 & 0xffffffffffffc00L) != 0L) {
jjmatchedKind = 70;
return 44;
}
return -1;
case 1:
if ((active0 & 0xffffffeff9ffc00L) != 0L) {
if (jjmatchedPos != 1) {
jjmatchedKind = 70;
jjmatchedPos = 1;
}
return 44;
}
if ((active0 & 0x100600000L) != 0L) {
return 44;
}
return -1;
case 2:
if ((active0 & 0xefffecebfdffc00L) != 0L) {
if (jjmatchedPos != 2) {
jjmatchedKind = 70;
jjmatchedPos = 2;
}
return 44;
}
if ((active0 & 0x100013040000000L) != 0L) {
return 44;
}
return -1;
case 3:
if ((active0 & 0x28002408182c000L) != 0L) {
return 44;
}
if ((active0 & 0xc7ffcae3e5d3c00L) != 0L) {
if (jjmatchedPos != 3) {
jjmatchedKind = 70;
jjmatchedPos = 3;
}
return 44;
}
return -1;
case 4:
if ((active0 & 0x41f7cae02580c00L) != 0L) {
if (jjmatchedPos != 4) {
jjmatchedKind = 70;
jjmatchedPos = 4;
}
return 44;
}
if ((active0 & 0x86080003c053000L) != 0L) {
return 44;
}
return -1;
case 5:
if ((active0 & 0x41a1c2a12180c00L) != 0L) {
jjmatchedKind = 70;
jjmatchedPos = 5;
return 44;
}
if ((active0 & 0x45608400400000L) != 0L) {
return 44;
}
return -1;
case 6:
if ((active0 & 0x41a102a00080400L) != 0L) {
jjmatchedKind = 70;
jjmatchedPos = 6;
return 44;
}
if ((active0 & 0xc0012100800L) != 0L) {
return 44;
}
return -1;
case 7:
if ((active0 & 0x18102a00000000L) != 0L) {
jjmatchedKind = 70;
jjmatchedPos = 7;
return 44;
}
if ((active0 & 0x402000000080400L) != 0L) {
return 44;
}
return -1;
case 8:
if ((active0 & 0x8000a00000000L) != 0L) {
jjmatchedKind = 70;
jjmatchedPos = 8;
return 44;
}
if ((active0 & 0x10102000000000L) != 0L) {
return 44;
}
return -1;
case 9:
if ((active0 & 0x8000000000000L) != 0L) {
jjmatchedKind = 70;
jjmatchedPos = 9;
return 44;
}
if ((active0 & 0xa00000000L) != 0L) {
return 44;
}
return -1;
case 10:
if ((active0 & 0x8000000000000L) != 0L) {
if (jjmatchedPos != 10) {
jjmatchedKind = 70;
jjmatchedPos = 10;
}
return 44;
}
return -1;
case 11:
if ((active0 & 0x8000000000000L) != 0L) {
return 44;
}
return -1;
default:
return -1;
}
}
private int jjStartNfa_0(int pos, long active0, long active1, long active2) {
return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0, active1, active2), pos + 1);
}
private int jjStopAtPos(int pos, int kind) {
jjmatchedKind = kind;
jjmatchedPos = pos;
return pos + 1;
}
private int jjStartNfaWithStates_0(int pos, int kind, int state) {
jjmatchedKind = kind;
jjmatchedPos = pos;
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
return pos + 1;
}
return jjMoveNfa_0(state, pos + 1);
}
private int jjMoveStringLiteralDfa0_0() {
switch (curChar) {
case 9:
return jjStartNfaWithStates_0(0, 2, 0);
case 10:
return jjStartNfaWithStates_0(0, 5, 0);
case 12:
return jjStartNfaWithStates_0(0, 4, 0);
case 13:
return jjStartNfaWithStates_0(0, 3, 0);
case 32:
return jjStartNfaWithStates_0(0, 1, 0);
case 33:
jjmatchedKind = 87;
return jjMoveStringLiteralDfa1_0(0x0L, 0x100000000L, 0x0L);
case 37:
jjmatchedKind = 112;
return jjMoveStringLiteralDfa1_0(0x0L, 0x0L, 0x1L);
case 38:
jjmatchedKind = 107;
return jjMoveStringLiteralDfa1_0(0x0L, 0x800000800000000L, 0x0L);
case 40:
return jjStopAtPos(0, 73);
case 41:
return jjStopAtPos(0, 74);
case 42:
jjmatchedKind = 105;
return jjMoveStringLiteralDfa1_0(0x0L, 0x200000000000000L, 0x0L);
case 43:
jjmatchedKind = 103;
return jjMoveStringLiteralDfa1_0(0x0L, 0x80002000000000L, 0x0L);
case 44:
return jjStopAtPos(0, 80);
case 45:
jjmatchedKind = 104;
return jjMoveStringLiteralDfa1_0(0x0L, 0x100004000000000L, 0x0L);
case 46:
return jjStartNfaWithStates_0(0, 81, 11);
case 47:
jjmatchedKind = 106;
return jjMoveStringLiteralDfa1_0(0x0L, 0x400000000000000L, 0x0L);
case 58:
return jjStopAtPos(0, 90);
case 59:
return jjStopAtPos(0, 79);
case 60:
jjmatchedKind = 85;
return jjMoveStringLiteralDfa1_0(0x0L, 0x2000010000000L, 0x2L);
case 61:
jjmatchedKind = 82;
return jjMoveStringLiteralDfa1_0(0x0L, 0x8000000L, 0x0L);
case 62:
jjmatchedKind = 83;
return jjMoveStringLiteralDfa1_0(0x0L, 0x28000040000000L, 0x28L);
case 63:
return jjStopAtPos(0, 89);
case 64:
return jjMoveStringLiteralDfa1_0(0x0L, 0x50545014a0500000L, 0x54L);
case 91:
return jjStopAtPos(0, 77);
case 93:
return jjStopAtPos(0, 78);
case 94:
jjmatchedKind = 111;
return jjMoveStringLiteralDfa1_0(0x0L, 0x8000000000000000L, 0x0L);
case 97:
return jjMoveStringLiteralDfa1_0(0x400L, 0x0L, 0x0L);
case 98:
return jjMoveStringLiteralDfa1_0(0x5800L, 0x0L, 0x0L);
case 99:
return jjMoveStringLiteralDfa1_0(0xfa000L, 0x0L, 0x0L);
case 100:
return jjMoveStringLiteralDfa1_0(0x700000L, 0x0L, 0x0L);
case 101:
return jjMoveStringLiteralDfa1_0(0x3800000L, 0x0L, 0x0L);
case 102:
return jjMoveStringLiteralDfa1_0(0x7c000000L, 0x0L, 0x0L);
case 103:
return jjMoveStringLiteralDfa1_0(0x80000000L, 0x0L, 0x0L);
case 105:
return jjMoveStringLiteralDfa1_0(0x3f00000000L, 0x0L, 0x0L);
case 108:
return jjMoveStringLiteralDfa1_0(0x4000000000L, 0x0L, 0x0L);
case 110:
return jjMoveStringLiteralDfa1_0(0x38000000000L, 0x0L, 0x0L);
case 112:
return jjMoveStringLiteralDfa1_0(0x3c0000000000L, 0x0L, 0x0L);
case 114:
return jjMoveStringLiteralDfa1_0(0x400000000000L, 0x0L, 0x0L);
case 115:
return jjMoveStringLiteralDfa1_0(0xf800000000000L, 0x0L, 0x0L);
case 116:
return jjMoveStringLiteralDfa1_0(0x1f0000000000000L, 0x0L, 0x0L);
case 118:
return jjMoveStringLiteralDfa1_0(0x600000000000000L, 0x0L, 0x0L);
case 119:
return jjMoveStringLiteralDfa1_0(0x800000000000000L, 0x0L, 0x0L);
case 123:
return jjStopAtPos(0, 75);
case 124:
jjmatchedKind = 109;
return jjMoveStringLiteralDfa1_0(0x0L, 0x2000000200000000L, 0x0L);
case 125:
return jjStopAtPos(0, 76);
case 126:
return jjStopAtPos(0, 88);
default:
return jjMoveNfa_0(6, 0);
}
}
private int jjMoveStringLiteralDfa1_0(long active0, long active1, long active2) {
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
jjStopStringLiteralDfa_0(0, active0, active1, active2);
return 1;
}
switch (curChar) {
case 38:
if ((active1 & 0x800000000L) != 0L) {
return jjStopAtPos(1, 99);
}
break;
case 43:
if ((active1 & 0x2000000000L) != 0L) {
return jjStopAtPos(1, 101);
}
break;
case 45:
if ((active1 & 0x4000000000L) != 0L) {
return jjStopAtPos(1, 102);
}
break;
case 60:
if ((active1 & 0x2000000000000L) != 0L) {
jjmatchedKind = 113;
jjmatchedPos = 1;
}
return jjMoveStringLiteralDfa2_0(active0, 0L, active1, 0L, active2, 0x2L);
case 61:
if ((active1 & 0x8000000L) != 0L) {
return jjStopAtPos(1, 91);
} else if ((active1 & 0x10000000L) != 0L) {
return jjStopAtPos(1, 92);
} else if ((active1 & 0x40000000L) != 0L) {
return jjStopAtPos(1, 94);
} else if ((active1 & 0x100000000L) != 0L) {
return jjStopAtPos(1, 96);
} else if ((active1 & 0x80000000000000L) != 0L) {
return jjStopAtPos(1, 119);
} else if ((active1 & 0x100000000000000L) != 0L) {
return jjStopAtPos(1, 120);
} else if ((active1 & 0x200000000000000L) != 0L) {
return jjStopAtPos(1, 121);
} else if ((active1 & 0x400000000000000L) != 0L) {
return jjStopAtPos(1, 122);
} else if ((active1 & 0x800000000000000L) != 0L) {
return jjStopAtPos(1, 123);
} else if ((active1 & 0x2000000000000000L) != 0L) {
return jjStopAtPos(1, 125);
} else if ((active1 & 0x8000000000000000L) != 0L) {
return jjStopAtPos(1, 127);
} else if ((active2 & 0x1L) != 0L) {
return jjStopAtPos(1, 128);
}
break;
case 62:
if ((active1 & 0x8000000000000L) != 0L) {
jjmatchedKind = 115;
jjmatchedPos = 1;
}
return jjMoveStringLiteralDfa2_0(active0, 0L, active1, 0x20000000000000L, active2, 0x28L);
case 97:
return jjMoveStringLiteralDfa2_0(active0, 0x48004018000L, active1, 0x1000001000000000L, active2, 0L);
case 98:
return jjMoveStringLiteralDfa2_0(active0, 0x400L, active1, 0x500000000000L, active2, 0L);
case 101:
return jjMoveStringLiteralDfa2_0(active0, 0x410000100000L, active1, 0L, active2, 0L);
case 102:
if ((active0 & 0x100000000L) != 0L) {
return jjStartNfaWithStates_0(1, 32, 44);
}
break;
case 103:
return jjMoveStringLiteralDfa2_0(active0, 0L, active1, 0x80100000L, active2, 0L);
case 104:
return jjMoveStringLiteralDfa2_0(active0, 0x860800000020000L, active1, 0L, active2, 0L);
case 105:
return jjMoveStringLiteralDfa2_0(active0, 0x18000000L, active1, 0L, active2, 0L);
case 108:
return jjMoveStringLiteralDfa2_0(active0, 0x20802000L, active1, 0x4000020400000L, active2, 0x4L);
case 109:
return jjMoveStringLiteralDfa2_0(active0, 0x600000000L, active1, 0L, active2, 0L);
case 110:
return jjMoveStringLiteralDfa2_0(active0, 0x3801000000L, active1, 0L, active2, 0L);
case 111:
if ((active0 & 0x200000L) != 0L) {
jjmatchedKind = 21;
jjmatchedPos = 1;
}
return jjMoveStringLiteralDfa2_0(active0, 0x6000040c04c0800L, active1, 0x4000000400000000L, active2, 0L);
case 114:
return jjMoveStringLiteralDfa2_0(active0, 0x190180000001000L, active1, 0x50000000000000L, active2, 0x50L);
case 116:
return jjMoveStringLiteralDfa2_0(active0, 0x3000000000000L, active1, 0L, active2, 0L);
case 117:
return jjMoveStringLiteralDfa2_0(active0, 0x220000000000L, active1, 0L, active2, 0L);
case 119:
return jjMoveStringLiteralDfa2_0(active0, 0x4000000000000L, active1, 0L, active2, 0L);
case 120:
return jjMoveStringLiteralDfa2_0(active0, 0x2000000L, active1, 0L, active2, 0L);
case 121:
return jjMoveStringLiteralDfa2_0(active0, 0x8000000004000L, active1, 0L, active2, 0L);
case 124:
if ((active1 & 0x200000000L) != 0L) {
return jjStopAtPos(1, 97);
}
break;
default:
break;
}
return jjStartNfa_0(0, active0, active1, active2);
}
private int jjMoveStringLiteralDfa2_0(long old0, long active0, long old1, long active1, long old2, long active2) {
if (((active0 &= old0) | (active1 &= old1) | (active2 &= old2)) == 0L) {
return jjStartNfa_0(0, old0, old1, old2);
}
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
jjStopStringLiteralDfa_0(1, active0, active1, active2);
return 2;
}
switch (curChar) {
case 61:
if ((active2 & 0x2L) != 0L) {
return jjStopAtPos(2, 129);
} else if ((active2 & 0x8L) != 0L) {
return jjStopAtPos(2, 131);
}
break;
case 62:
if ((active1 & 0x20000000000000L) != 0L) {
jjmatchedKind = 117;
jjmatchedPos = 2;
}
return jjMoveStringLiteralDfa3_0(active0, 0L, active1, 0L, active2, 0x20L);
case 97:
return jjMoveStringLiteralDfa3_0(active0, 0x11000000022000L, active1, 0L, active2, 0L);
case 98:
return jjMoveStringLiteralDfa3_0(active0, 0x200000000000L, active1, 0L, active2, 0L);
case 99:
return jjMoveStringLiteralDfa3_0(active0, 0x40000000000L, active1, 0L, active2, 0L);
case 101:
return jjMoveStringLiteralDfa3_0(active0, 0x1000L, active1, 0x4000000000000L, active2, 0x4L);
case 102:
return jjMoveStringLiteralDfa3_0(active0, 0x100000L, active1, 0L, active2, 0L);
case 105:
return jjMoveStringLiteralDfa3_0(active0, 0xa04080000000000L, active1, 0x50500000000000L, active2, 0x50L);
case 108:
return jjMoveStringLiteralDfa3_0(active0, 0x400020004000000L, active1, 0L, active2, 0L);
case 110:
return jjMoveStringLiteralDfa3_0(active0, 0x80040180c0000L, active1, 0x1000001000000000L, active2, 0L);
case 111:
return jjMoveStringLiteralDfa3_0(active0, 0x900020000800L, active1, 0L, active2, 0L);
case 112:
return jjMoveStringLiteralDfa3_0(active0, 0x600000000L, active1, 0L, active2, 0L);
case 114:
if ((active0 & 0x40000000L) != 0L) {
return jjStartNfaWithStates_0(2, 30, 44);
} else if ((active1 & 0x400000000L) != 0L) {
jjmatchedKind = 98;
jjmatchedPos = 2;
}
return jjMoveStringLiteralDfa3_0(active0, 0x62000000000000L, active1, 0x4000000000000000L, active2, 0L);
case 115:
return jjMoveStringLiteralDfa3_0(active0, 0x800808400L, active1, 0L, active2, 0L);
case 116:
if ((active0 & 0x1000000000L) != 0L) {
jjmatchedKind = 36;
jjmatchedPos = 2;
} else if ((active1 & 0x100000L) != 0L) {
jjmatchedKind = 84;
jjmatchedPos = 2;
} else if ((active1 & 0x400000L) != 0L) {
jjmatchedKind = 86;
jjmatchedPos = 2;
}
return jjMoveStringLiteralDfa3_0(active0, 0x40a082014000L, active1, 0xa0000000L, active2, 0L);
case 117:
return jjMoveStringLiteralDfa3_0(active0, 0x80000001400000L, active1, 0L, active2, 0L);
case 119:
if ((active0 & 0x10000000000L) != 0L) {
return jjStartNfaWithStates_0(2, 40, 44);
}
break;
case 121:
if ((active0 & 0x100000000000000L) != 0L) {
return jjStartNfaWithStates_0(2, 56, 44);
}
break;
default:
break;
}
return jjStartNfa_0(1, active0, active1, active2);
}
private int jjMoveStringLiteralDfa3_0(long old0, long active0, long old1, long active1, long old2, long active2) {
if (((active0 &= old0) | (active1 &= old1) | (active2 &= old2)) == 0L) {
return jjStartNfa_0(1, old0, old1, old2);
}
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
jjStopStringLiteralDfa_0(2, active0, active1, active2);
return 3;
}
switch (curChar) {
case 61:
if ((active2 & 0x20L) != 0L) {
return jjStopAtPos(3, 133);
}
break;
case 95:
return jjMoveStringLiteralDfa4_0(active0, 0L, active1, 0x4000000000000000L, active2, 0L);
case 97:
return jjMoveStringLiteralDfa4_0(active0, 0x400000038101000L, active1, 0L, active2, 0L);
case 98:
return jjMoveStringLiteralDfa4_0(active0, 0x400000L, active1, 0L, active2, 0L);
case 99:
return jjMoveStringLiteralDfa4_0(active0, 0x8000000010000L, active1, 0L, active2, 0L);
case 100:
if ((active0 & 0x200000000000000L) != 0L) {
return jjStartNfaWithStates_0(3, 57, 44);
} else if ((active1 & 0x1000000000L) != 0L) {
jjmatchedKind = 100;
jjmatchedPos = 3;
}
return jjMoveStringLiteralDfa4_0(active0, 0L, active1, 0x1000000000000000L, active2, 0L);
case 101:
if ((active0 & 0x4000L) != 0L) {
return jjStartNfaWithStates_0(3, 14, 44);
} else if ((active0 & 0x8000L) != 0L) {
return jjStartNfaWithStates_0(3, 15, 44);
} else if ((active0 & 0x800000L) != 0L) {
return jjStartNfaWithStates_0(3, 23, 44);
} else if ((active0 & 0x80000000000000L) != 0L) {
return jjStartNfaWithStates_0(3, 55, 44);
}
return jjMoveStringLiteralDfa4_0(active0, 0x2002000000L, active1, 0xa0000000L, active2, 0L);
case 102:
return jjMoveStringLiteralDfa4_0(active0, 0L, active1, 0x4000000000000L, active2, 0x4L);
case 103:
if ((active0 & 0x4000000000L) != 0L) {
return jjStartNfaWithStates_0(3, 38, 44);
}
return jjMoveStringLiteralDfa4_0(active0, 0L, active1, 0x50000000000000L, active2, 0x50L);
case 105:
return jjMoveStringLiteralDfa4_0(active0, 0x2008000000000L, active1, 0L, active2, 0L);
case 107:
return jjMoveStringLiteralDfa4_0(active0, 0x40000000000L, active1, 0L, active2, 0L);
case 108:
if ((active0 & 0x20000000000L) != 0L) {
return jjStartNfaWithStates_0(3, 41, 44);
}
return jjMoveStringLiteralDfa4_0(active0, 0x800200200000800L, active1, 0L, active2, 0L);
case 109:
if ((active0 & 0x1000000L) != 0L) {
return jjStartNfaWithStates_0(3, 24, 44);
}
break;
case 110:
return jjMoveStringLiteralDfa4_0(active0, 0x10000000000000L, active1, 0L, active2, 0L);
case 111:
if ((active0 & 0x80000000L) != 0L) {
return jjStartNfaWithStates_0(3, 31, 44);
}
return jjMoveStringLiteralDfa4_0(active0, 0x60000400000000L, active1, 0L, active2, 0L);
case 114:
if ((active0 & 0x20000L) != 0L) {
return jjStartNfaWithStates_0(3, 17, 44);
}
return jjMoveStringLiteralDfa4_0(active0, 0x800000000000L, active1, 0L, active2, 0L);
case 115:
return jjMoveStringLiteralDfa4_0(active0, 0x4042000L, active1, 0L, active2, 0L);
case 116:
return jjMoveStringLiteralDfa4_0(active0, 0x5100800080400L, active1, 0x500000000000L, active2, 0L);
case 117:
return jjMoveStringLiteralDfa4_0(active0, 0x400000000000L, active1, 0L, active2, 0L);
case 118:
return jjMoveStringLiteralDfa4_0(active0, 0x80000000000L, active1, 0L, active2, 0L);
default:
break;
}
return jjStartNfa_0(2, active0, active1, active2);
}
private int jjMoveStringLiteralDfa4_0(long old0, long active0, long old1, long active1, long old2, long active2) {
if (((active0 &= old0) | (active1 &= old1) | (active2 &= old2)) == 0L) {
return jjStartNfa_0(2, old0, old1, old2);
}
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
jjStopStringLiteralDfa_0(3, active0, active1, active2);
return 4;
}
switch (curChar) {
case 95:
return jjMoveStringLiteralDfa5_0(active0, 0L, active1, 0x1000000000000000L, active2, 0L);
case 97:
return jjMoveStringLiteralDfa5_0(active0, 0xc0800000000L, active1, 0x4000000000000000L, active2, 0L);
case 99:
return jjMoveStringLiteralDfa5_0(active0, 0x6000000000000L, active1, 0L, active2, 0L);
case 101:
if ((active0 & 0x4000000L) != 0L) {
return jjStartNfaWithStates_0(4, 26, 44);
} else if ((active0 & 0x800000000000000L) != 0L) {
return jjStartNfaWithStates_0(4, 59, 44);
}
return jjMoveStringLiteralDfa5_0(active0, 0x100200000800L, active1, 0L, active2, 0L);
case 104:
if ((active0 & 0x10000L) != 0L) {
return jjStartNfaWithStates_0(4, 16, 44);
}
return jjMoveStringLiteralDfa5_0(active0, 0x8000000000000L, active1, 0x50000000000000L, active2, 0x50L);
case 105:
return jjMoveStringLiteralDfa5_0(active0, 0x1200000080000L, active1, 0L, active2, 0L);
case 107:
if ((active0 & 0x1000L) != 0L) {
return jjStartNfaWithStates_0(4, 12, 44);
}
break;
case 108:
if ((active0 & 0x8000000L) != 0L) {
jjmatchedKind = 27;
jjmatchedPos = 4;
}
return jjMoveStringLiteralDfa5_0(active0, 0x10400000L, active1, 0L, active2, 0L);
case 110:
return jjMoveStringLiteralDfa5_0(active0, 0x2000000L, active1, 0L, active2, 0L);
case 113:
if ((active1 & 0x20000000L) != 0L) {
return jjStopAtPos(4, 93);
} else if ((active1 & 0x80000000L) != 0L) {
return jjStopAtPos(4, 95);
}
break;
case 114:
return jjMoveStringLiteralDfa5_0(active0, 0x402400000400L, active1, 0L, active2, 0L);
case 115:
if ((active0 & 0x2000L) != 0L) {
return jjStartNfaWithStates_0(4, 13, 44);
}
return jjMoveStringLiteralDfa5_0(active0, 0x10000000000000L, active1, 0L, active2, 0L);
case 116:
if ((active0 & 0x40000L) != 0L) {
return jjStartNfaWithStates_0(4, 18, 44);
} else if ((active0 & 0x20000000L) != 0L) {
return jjStartNfaWithStates_0(4, 29, 44);
} else if ((active0 & 0x800000000000L) != 0L) {
return jjStartNfaWithStates_0(4, 47, 44);
}
return jjMoveStringLiteralDfa5_0(active0, 0x400000000000000L, active1, 0x4000000000000L, active2, 0x4L);
case 117:
return jjMoveStringLiteralDfa5_0(active0, 0x100000L, active1, 0L, active2, 0L);
case 118:
return jjMoveStringLiteralDfa5_0(active0, 0x8000000000L, active1, 0L, active2, 0L);
case 119:
if ((active0 & 0x20000000000000L) != 0L) {
jjmatchedKind = 53;
jjmatchedPos = 4;
}
return jjMoveStringLiteralDfa5_0(active0, 0x40000000000000L, active1, 0x500000000000L, active2, 0L);
default:
break;
}
return jjStartNfa_0(3, active0, active1, active2);
}
private int jjMoveStringLiteralDfa5_0(long old0, long active0, long old1, long active1, long old2, long active2) {
if (((active0 &= old0) | (active1 &= old1) | (active2 &= old2)) == 0L) {
return jjStartNfa_0(3, old0, old1, old2);
}
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
jjStopStringLiteralDfa_0(4, active0, active1, active2);
return 5;
}
switch (curChar) {
case 95:
return jjMoveStringLiteralDfa6_0(active0, 0L, active1, 0x4000000000000L, active2, 0x4L);
case 97:
return jjMoveStringLiteralDfa6_0(active0, 0xc00L, active1, 0x1000000000000000L, active2, 0L);
case 99:
if ((active0 & 0x200000000000L) != 0L) {
return jjStartNfaWithStates_0(5, 45, 44);
} else if ((active0 & 0x1000000000000L) != 0L) {
return jjStartNfaWithStates_0(5, 48, 44);
}
return jjMoveStringLiteralDfa6_0(active0, 0x100000000000L, active1, 0L, active2, 0L);
case 100:
return jjMoveStringLiteralDfa6_0(active0, 0x2000000L, active1, 0L, active2, 0L);
case 101:
if ((active0 & 0x400000L) != 0L) {
return jjStartNfaWithStates_0(5, 22, 44);
} else if ((active0 & 0x8000000000L) != 0L) {
return jjStartNfaWithStates_0(5, 39, 44);
}
break;
case 102:
return jjMoveStringLiteralDfa6_0(active0, 0x2000000000L, active1, 0L, active2, 0L);
case 103:
return jjMoveStringLiteralDfa6_0(active0, 0x40000000000L, active1, 0L, active2, 0L);
case 104:
if ((active0 & 0x4000000000000L) != 0L) {
return jjStartNfaWithStates_0(5, 50, 44);
}
break;
case 105:
return jjMoveStringLiteralDfa6_0(active0, 0x410000000000000L, active1, 0x500000000000L, active2, 0L);
case 108:
return jjMoveStringLiteralDfa6_0(active0, 0x10100000L, active1, 0L, active2, 0L);
case 109:
return jjMoveStringLiteralDfa6_0(active0, 0x200000000L, active1, 0L, active2, 0L);
case 110:
if ((active0 & 0x400000000000L) != 0L) {
return jjStartNfaWithStates_0(5, 46, 44);
}
return jjMoveStringLiteralDfa6_0(active0, 0x800080000L, active1, 0L, active2, 0L);
case 114:
return jjMoveStringLiteralDfa6_0(active0, 0x8000000000000L, active1, 0L, active2, 0L);
case 115:
if ((active0 & 0x40000000000000L) != 0L) {
return jjStartNfaWithStates_0(5, 54, 44);
}
return jjMoveStringLiteralDfa6_0(active0, 0L, active1, 0x4000000000000000L, active2, 0L);
case 116:
if ((active0 & 0x400000000L) != 0L) {
return jjStartNfaWithStates_0(5, 34, 44);
}
return jjMoveStringLiteralDfa6_0(active0, 0x2080000000000L, active1, 0x50000000000000L, active2, 0x50L);
default:
break;
}
return jjStartNfa_0(4, active0, active1, active2);
}
private int jjMoveStringLiteralDfa6_0(long old0, long active0, long old1, long active1, long old2, long active2) {
if (((active0 &= old0) | (active1 &= old1) | (active2 &= old2)) == 0L) {
return jjStartNfa_0(4, old0, old1, old2);
}
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
jjStopStringLiteralDfa_0(5, active0, active1, active2);
return 6;
}
switch (curChar) {
case 95:
return jjMoveStringLiteralDfa7_0(active0, 0L, active1, 0x50000000000000L, active2, 0x50L);
case 97:
return jjMoveStringLiteralDfa7_0(active0, 0x2000000000L, active1, 0L, active2, 0L);
case 99:
return jjMoveStringLiteralDfa7_0(active0, 0x800000400L, active1, 0L, active2, 0L);
case 101:
if ((active0 & 0x40000000000L) != 0L) {
return jjStartNfaWithStates_0(6, 42, 44);
} else if ((active0 & 0x80000000000L) != 0L) {
return jjStartNfaWithStates_0(6, 43, 44);
}
return jjMoveStringLiteralDfa7_0(active0, 0x10000200000000L, active1, 0L, active2, 0L);
case 102:
return jjMoveStringLiteralDfa7_0(active0, 0x2000000000000L, active1, 0L, active2, 0L);
case 108:
return jjMoveStringLiteralDfa7_0(active0, 0x400000000000000L, active1, 0L, active2, 0L);
case 110:
if ((active0 & 0x800L) != 0L) {
return jjStartNfaWithStates_0(6, 11, 44);
}
break;
case 111:
return jjMoveStringLiteralDfa7_0(active0, 0x8000000000000L, active1, 0L, active2, 0L);
case 115:
if ((active0 & 0x2000000L) != 0L) {
return jjStartNfaWithStates_0(6, 25, 44);
}
return jjMoveStringLiteralDfa7_0(active0, 0L, active1, 0x5004500000000000L, active2, 0x4L);
case 116:
if ((active0 & 0x100000L) != 0L) {
return jjStartNfaWithStates_0(6, 20, 44);
}
return jjMoveStringLiteralDfa7_0(active0, 0x100000000000L, active1, 0L, active2, 0L);
case 117:
return jjMoveStringLiteralDfa7_0(active0, 0x80000L, active1, 0L, active2, 0L);
case 121:
if ((active0 & 0x10000000L) != 0L) {
return jjStartNfaWithStates_0(6, 28, 44);
}
break;
default:
break;
}
return jjStartNfa_0(5, active0, active1, active2);
}
private int jjMoveStringLiteralDfa7_0(long old0, long active0, long old1, long active1, long old2, long active2) {
if (((active0 &= old0) | (active1 &= old1) | (active2 &= old2)) == 0L) {
return jjStartNfa_0(5, old0, old1, old2);
}
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
jjStopStringLiteralDfa_0(6, active0, active1, active2);
return 7;
}
switch (curChar) {
case 99:
return jjMoveStringLiteralDfa8_0(active0, 0x2000000000L, active1, 0L, active2, 0L);
case 101:
if ((active0 & 0x80000L) != 0L) {
return jjStartNfaWithStates_0(7, 19, 44);
} else if ((active0 & 0x400000000000000L) != 0L) {
return jjStartNfaWithStates_0(7, 58, 44);
}
return jjMoveStringLiteralDfa8_0(active0, 0x100800000000L, active1, 0x500000000000L, active2, 0L);
case 104:
return jjMoveStringLiteralDfa8_0(active0, 0L, active1, 0x4000000000000L, active2, 0x4L);
case 105:
return jjMoveStringLiteralDfa8_0(active0, 0L, active1, 0x4000000000000000L, active2, 0L);
case 110:
return jjMoveStringLiteralDfa8_0(active0, 0x18000200000000L, active1, 0L, active2, 0L);
case 112:
if ((active0 & 0x2000000000000L) != 0L) {
return jjStartNfaWithStates_0(7, 49, 44);
}
break;
case 115:
return jjMoveStringLiteralDfa8_0(active0, 0L, active1, 0x1010000000000000L, active2, 0x10L);
case 116:
if ((active0 & 0x400L) != 0L) {
return jjStartNfaWithStates_0(7, 10, 44);
}
break;
case 117:
return jjMoveStringLiteralDfa8_0(active0, 0L, active1, 0x40000000000000L, active2, 0x40L);
default:
break;
}
return jjStartNfa_0(6, active0, active1, active2);
}
private int jjMoveStringLiteralDfa8_0(long old0, long active0, long old1, long active1, long old2, long active2) {
if (((active0 &= old0) | (active1 &= old1) | (active2 &= old2)) == 0L) {
return jjStartNfa_0(6, old0, old1, old2);
}
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
jjStopStringLiteralDfa_0(7, active0, active1, active2);
return 8;
}
switch (curChar) {
case 95:
return jjMoveStringLiteralDfa9_0(active0, 0L, active1, 0x500000000000L, active2, 0L);
case 100:
if ((active0 & 0x100000000000L) != 0L) {
return jjStartNfaWithStates_0(8, 44, 44);
}
break;
case 101:
if ((active0 & 0x2000000000L) != 0L) {
return jjStartNfaWithStates_0(8, 37, 44);
}
break;
case 103:
return jjMoveStringLiteralDfa9_0(active0, 0L, active1, 0x4000000000000000L, active2, 0L);
case 104:
return jjMoveStringLiteralDfa9_0(active0, 0L, active1, 0x10000000000000L, active2, 0x10L);
case 105:
return jjMoveStringLiteralDfa9_0(active0, 0x8000000000000L, active1, 0x1004000000000000L, active2, 0x4L);
case 110:
return jjMoveStringLiteralDfa9_0(active0, 0L, active1, 0x40000000000000L, active2, 0x40L);
case 111:
return jjMoveStringLiteralDfa9_0(active0, 0x800000000L, active1, 0L, active2, 0L);
case 116:
if ((active0 & 0x10000000000000L) != 0L) {
return jjStartNfaWithStates_0(8, 52, 44);
}
return jjMoveStringLiteralDfa9_0(active0, 0x200000000L, active1, 0L, active2, 0L);
default:
break;
}
return jjStartNfa_0(7, active0, active1, active2);
}
private int jjMoveStringLiteralDfa9_0(long old0, long active0, long old1, long active1, long old2, long active2) {
if (((active0 &= old0) | (active1 &= old1) | (active2 &= old2)) == 0L) {
return jjStartNfa_0(7, old0, old1, old2);
}
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
jjStopStringLiteralDfa_0(8, active0, active1, active2);
return 9;
}
switch (curChar) {
case 97:
return jjMoveStringLiteralDfa10_0(active0, 0L, active1, 0x100000000000L, active2, 0L);
case 102:
if ((active0 & 0x800000000L) != 0L) {
return jjStartNfaWithStates_0(9, 35, 44);
}
return jjMoveStringLiteralDfa10_0(active0, 0L, active1, 0x4000000000000L, active2, 0x4L);
case 103:
return jjMoveStringLiteralDfa10_0(active0, 0L, active1, 0x1000000000000000L, active2, 0L);
case 105:
return jjMoveStringLiteralDfa10_0(active0, 0L, active1, 0x10000000000000L, active2, 0x10L);
case 110:
if ((active1 & 0x4000000000000000L) != 0L) {
return jjStopAtPos(9, 126);
}
break;
case 111:
return jjMoveStringLiteralDfa10_0(active0, 0L, active1, 0x400000000000L, active2, 0L);
case 115:
if ((active0 & 0x200000000L) != 0L) {
return jjStartNfaWithStates_0(9, 33, 44);
}
return jjMoveStringLiteralDfa10_0(active0, 0L, active1, 0x40000000000000L, active2, 0x40L);
case 122:
return jjMoveStringLiteralDfa10_0(active0, 0x8000000000000L, active1, 0L, active2, 0L);
default:
break;
}
return jjStartNfa_0(8, active0, active1, active2);
}
private int jjMoveStringLiteralDfa10_0(long old0, long active0, long old1, long active1, long old2, long active2) {
if (((active0 &= old0) | (active1 &= old1) | (active2 &= old2)) == 0L) {
return jjStartNfa_0(8, old0, old1, old2);
}
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
jjStopStringLiteralDfa_0(9, active0, active1, active2);
return 10;
}
switch (curChar) {
case 101:
return jjMoveStringLiteralDfa11_0(active0, 0x8000000000000L, active1, 0L, active2, 0L);
case 102:
return jjMoveStringLiteralDfa11_0(active0, 0L, active1, 0x10000000000000L, active2, 0x10L);
case 105:
return jjMoveStringLiteralDfa11_0(active0, 0L, active1, 0x40000000000000L, active2, 0x40L);
case 110:
if ((active1 & 0x1000000000000000L) != 0L) {
return jjStopAtPos(10, 124);
}
return jjMoveStringLiteralDfa11_0(active0, 0L, active1, 0x100000000000L, active2, 0L);
case 114:
if ((active1 & 0x400000000000L) != 0L) {
return jjStopAtPos(10, 110);
}
break;
case 116:
if ((active1 & 0x4000000000000L) != 0L) {
jjmatchedKind = 114;
jjmatchedPos = 10;
}
return jjMoveStringLiteralDfa11_0(active0, 0L, active1, 0L, active2, 0x4L);
default:
break;
}
return jjStartNfa_0(9, active0, active1, active2);
}
private int jjMoveStringLiteralDfa11_0(long old0, long active0, long old1, long active1, long old2, long active2) {
if (((active0 &= old0) | (active1 &= old1) | (active2 &= old2)) == 0L) {
return jjStartNfa_0(9, old0, old1, old2);
}
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
jjStopStringLiteralDfa_0(10, active0, active1, active2);
return 11;
}
switch (curChar) {
case 95:
return jjMoveStringLiteralDfa12_0(active0, 0L, active1, 0L, active2, 0x4L);
case 100:
if ((active0 & 0x8000000000000L) != 0L) {
return jjStartNfaWithStates_0(11, 51, 44);
} else if ((active1 & 0x100000000000L) != 0L) {
return jjStopAtPos(11, 108);
}
break;
case 103:
return jjMoveStringLiteralDfa12_0(active0, 0L, active1, 0x40000000000000L, active2, 0x40L);
case 116:
if ((active1 & 0x10000000000000L) != 0L) {
jjmatchedKind = 116;
jjmatchedPos = 11;
}
return jjMoveStringLiteralDfa12_0(active0, 0L, active1, 0L, active2, 0x10L);
default:
break;
}
return jjStartNfa_0(10, active0, active1, active2);
}
private int jjMoveStringLiteralDfa12_0(long old0, long active0, long old1, long active1, long old2, long active2) {
if (((active0 &= old0) | (active1 &= old1) | (active2 &= old2)) == 0L) {
return jjStartNfa_0(10, old0, old1, old2);
}
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
jjStopStringLiteralDfa_0(11, 0L, active1, active2);
return 12;
}
switch (curChar) {
case 95:
return jjMoveStringLiteralDfa13_0(active1, 0L, active2, 0x10L);
case 97:
return jjMoveStringLiteralDfa13_0(active1, 0L, active2, 0x4L);
case 110:
return jjMoveStringLiteralDfa13_0(active1, 0x40000000000000L, active2, 0x40L);
default:
break;
}
return jjStartNfa_0(11, 0L, active1, active2);
}
private int jjMoveStringLiteralDfa13_0(long old1, long active1, long old2, long active2) {
if (((active1 &= old1) | (active2 &= old2)) == 0L) {
return jjStartNfa_0(11, 0L, old1, old2);
}
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
jjStopStringLiteralDfa_0(12, 0L, active1, active2);
return 13;
}
switch (curChar) {
case 97:
return jjMoveStringLiteralDfa14_0(active1, 0L, active2, 0x10L);
case 101:
return jjMoveStringLiteralDfa14_0(active1, 0x40000000000000L, active2, 0x40L);
case 115:
return jjMoveStringLiteralDfa14_0(active1, 0L, active2, 0x4L);
default:
break;
}
return jjStartNfa_0(12, 0L, active1, active2);
}
private int jjMoveStringLiteralDfa14_0(long old1, long active1, long old2, long active2) {
if (((active1 &= old1) | (active2 &= old2)) == 0L) {
return jjStartNfa_0(12, 0L, old1, old2);
}
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
jjStopStringLiteralDfa_0(13, 0L, active1, active2);
return 14;
}
switch (curChar) {
case 100:
return jjMoveStringLiteralDfa15_0(active1, 0x40000000000000L, active2, 0x40L);
case 115:
return jjMoveStringLiteralDfa15_0(active1, 0L, active2, 0x14L);
default:
break;
}
return jjStartNfa_0(13, 0L, active1, active2);
}
private int jjMoveStringLiteralDfa15_0(long old1, long active1, long old2, long active2) {
if (((active1 &= old1) | (active2 &= old2)) == 0L) {
return jjStartNfa_0(13, 0L, old1, old2);
}
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
jjStopStringLiteralDfa_0(14, 0L, active1, active2);
return 15;
}
switch (curChar) {
case 95:
return jjMoveStringLiteralDfa16_0(active1, 0x40000000000000L, active2, 0x40L);
case 105:
return jjMoveStringLiteralDfa16_0(active1, 0L, active2, 0x4L);
case 115:
return jjMoveStringLiteralDfa16_0(active1, 0L, active2, 0x10L);
default:
break;
}
return jjStartNfa_0(14, 0L, active1, active2);
}
private int jjMoveStringLiteralDfa16_0(long old1, long active1, long old2, long active2) {
if (((active1 &= old1) | (active2 &= old2)) == 0L) {
return jjStartNfa_0(14, 0L, old1, old2);
}
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
jjStopStringLiteralDfa_0(15, 0L, active1, active2);
return 16;
}
switch (curChar) {
case 103:
return jjMoveStringLiteralDfa17_0(active1, 0L, active2, 0x4L);
case 105:
return jjMoveStringLiteralDfa17_0(active1, 0L, active2, 0x10L);
case 115:
return jjMoveStringLiteralDfa17_0(active1, 0x40000000000000L, active2, 0x40L);
default:
break;
}
return jjStartNfa_0(15, 0L, active1, active2);
}
private int jjMoveStringLiteralDfa17_0(long old1, long active1, long old2, long active2) {
if (((active1 &= old1) | (active2 &= old2)) == 0L) {
return jjStartNfa_0(15, 0L, old1, old2);
}
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
jjStopStringLiteralDfa_0(16, 0L, active1, active2);
return 17;
}
switch (curChar) {
case 103:
return jjMoveStringLiteralDfa18_0(active1, 0L, active2, 0x10L);
case 104:
return jjMoveStringLiteralDfa18_0(active1, 0x40000000000000L, active2, 0x40L);
case 110:
if ((active2 & 0x4L) != 0L) {
return jjStopAtPos(17, 130);
}
break;
default:
break;
}
return jjStartNfa_0(16, 0L, active1, active2);
}
private int jjMoveStringLiteralDfa18_0(long old1, long active1, long old2, long active2) {
if (((active1 &= old1) | (active2 &= old2)) == 0L) {
return jjStartNfa_0(16, 0L, old1, old2);
}
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
jjStopStringLiteralDfa_0(17, 0L, active1, active2);
return 18;
}
switch (curChar) {
case 105:
return jjMoveStringLiteralDfa19_0(active1, 0x40000000000000L, active2, 0x40L);
case 110:
if ((active2 & 0x10L) != 0L) {
return jjStopAtPos(18, 132);
}
break;
default:
break;
}
return jjStartNfa_0(17, 0L, active1, active2);
}
private int jjMoveStringLiteralDfa19_0(long old1, long active1, long old2, long active2) {
if (((active1 &= old1) | (active2 &= old2)) == 0L) {
return jjStartNfa_0(17, 0L, old1, old2);
}
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
jjStopStringLiteralDfa_0(18, 0L, active1, active2);
return 19;
}
switch (curChar) {
case 102:
return jjMoveStringLiteralDfa20_0(active1, 0x40000000000000L, active2, 0x40L);
default:
break;
}
return jjStartNfa_0(18, 0L, active1, active2);
}
private int jjMoveStringLiteralDfa20_0(long old1, long active1, long old2, long active2) {
if (((active1 &= old1) | (active2 &= old2)) == 0L) {
return jjStartNfa_0(18, 0L, old1, old2);
}
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
jjStopStringLiteralDfa_0(19, 0L, active1, active2);
return 20;
}
switch (curChar) {
case 116:
if ((active1 & 0x40000000000000L) != 0L) {
jjmatchedKind = 118;
jjmatchedPos = 20;
}
return jjMoveStringLiteralDfa21_0(active1, 0L, active2, 0x40L);
default:
break;
}
return jjStartNfa_0(19, 0L, active1, active2);
}
private int jjMoveStringLiteralDfa21_0(long old1, long active1, long old2, long active2) {
if (((active1 &= old1) | (active2 &= old2)) == 0L) {
return jjStartNfa_0(19, 0L, old1, old2);
}
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
jjStopStringLiteralDfa_0(20, 0L, 0L, active2);
return 21;
}
switch (curChar) {
case 95:
return jjMoveStringLiteralDfa22_0(active2, 0x40L);
default:
break;
}
return jjStartNfa_0(20, 0L, 0L, active2);
}
private int jjMoveStringLiteralDfa22_0(long old2, long active2) {
if (((active2 &= old2)) == 0L) {
return jjStartNfa_0(20, 0L, 0L, old2);
}
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
jjStopStringLiteralDfa_0(21, 0L, 0L, active2);
return 22;
}
switch (curChar) {
case 97:
return jjMoveStringLiteralDfa23_0(active2, 0x40L);
default:
break;
}
return jjStartNfa_0(21, 0L, 0L, active2);
}
private int jjMoveStringLiteralDfa23_0(long old2, long active2) {
if (((active2 &= old2)) == 0L) {
return jjStartNfa_0(21, 0L, 0L, old2);
}
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
jjStopStringLiteralDfa_0(22, 0L, 0L, active2);
return 23;
}
switch (curChar) {
case 115:
return jjMoveStringLiteralDfa24_0(active2, 0x40L);
default:
break;
}
return jjStartNfa_0(22, 0L, 0L, active2);
}
private int jjMoveStringLiteralDfa24_0(long old2, long active2) {
if (((active2 &= old2)) == 0L) {
return jjStartNfa_0(22, 0L, 0L, old2);
}
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
jjStopStringLiteralDfa_0(23, 0L, 0L, active2);
return 24;
}
switch (curChar) {
case 115:
return jjMoveStringLiteralDfa25_0(active2, 0x40L);
default:
break;
}
return jjStartNfa_0(23, 0L, 0L, active2);
}
private int jjMoveStringLiteralDfa25_0(long old2, long active2) {
if (((active2 &= old2)) == 0L) {
return jjStartNfa_0(23, 0L, 0L, old2);
}
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
jjStopStringLiteralDfa_0(24, 0L, 0L, active2);
return 25;
}
switch (curChar) {
case 105:
return jjMoveStringLiteralDfa26_0(active2, 0x40L);
default:
break;
}
return jjStartNfa_0(24, 0L, 0L, active2);
}
private int jjMoveStringLiteralDfa26_0(long old2, long active2) {
if (((active2 &= old2)) == 0L) {
return jjStartNfa_0(24, 0L, 0L, old2);
}
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
jjStopStringLiteralDfa_0(25, 0L, 0L, active2);
return 26;
}
switch (curChar) {
case 103:
return jjMoveStringLiteralDfa27_0(active2, 0x40L);
default:
break;
}
return jjStartNfa_0(25, 0L, 0L, active2);
}
private int jjMoveStringLiteralDfa27_0(long old2, long active2) {
if (((active2 &= old2)) == 0L) {
return jjStartNfa_0(25, 0L, 0L, old2);
}
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
jjStopStringLiteralDfa_0(26, 0L, 0L, active2);
return 27;
}
switch (curChar) {
case 110:
if ((active2 & 0x40L) != 0L) {
return jjStopAtPos(27, 134);
}
break;
default:
break;
}
return jjStartNfa_0(26, 0L, 0L, active2);
}
private void jjCheckNAdd(int state) {
if (jjrounds[state] != jjround) {
jjstateSet[jjnewStateCnt++] = state;
jjrounds[state] = jjround;
}
}
private void jjAddStates(int start, int end) {
do {
jjstateSet[jjnewStateCnt++] = jjnextStates[start];
} while (start++ != end);
}
private void jjCheckNAddTwoStates(int state1, int state2) {
jjCheckNAdd(state1);
jjCheckNAdd(state2);
}
private void jjCheckNAddStates(int start, int end) {
do {
jjCheckNAdd(jjnextStates[start]);
} while (start++ != end);
}
private void jjCheckNAddStates(int start) {
jjCheckNAdd(jjnextStates[start]);
jjCheckNAdd(jjnextStates[start + 1]);
}
static final long[] jjbitVec0 = {
0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL
};
static final long[] jjbitVec1 = {
0xfffffffffffffffeL, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL
};
static final long[] jjbitVec3 = {
0x1ff00000fffffffeL, 0xffffffffffffc000L, 0xffffffffL, 0x600000000000000L
};
static final long[] jjbitVec4 = {
0x0L, 0x0L, 0x0L, 0xff7fffffff7fffffL
};
static final long[] jjbitVec5 = {
0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL
};
static final long[] jjbitVec6 = {
0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffL, 0x0L
};
static final long[] jjbitVec7 = {
0xffffffffffffffffL, 0xffffffffffffffffL, 0x0L, 0x0L
};
static final long[] jjbitVec8 = {
0x3fffffffffffL, 0x0L, 0x0L, 0x0L
};
private int jjMoveNfa_0(int startState, int curPos) {
int[] nextStates;
int startsAt = 0;
jjnewStateCnt = 83;
int i = 1;
jjstateSet[0] = startState;
int j, kind = 0x7fffffff;
for (;;) {
if (++jjround == 0x7fffffff) {
ReInitRounds();
}
if (curChar < 64) {
long l = 1L << curChar;
MatchLoop:
do {
switch (jjstateSet[--i]) {
case 65:
if (curChar == 42) {
jjstateSet[jjnewStateCnt++] = 76;
} else if (curChar == 47) {
if (kind > 7) {
kind = 7;
}
jjCheckNAddStates(0, 2);
}
if (curChar == 42) {
jjCheckNAdd(71);
}
break;
case 6:
if ((0x1ffffffffL & l) != 0L) {
if (kind > 6) {
kind = 6;
}
jjCheckNAdd(0);
} else if ((0x3ff000000000000L & l) != 0L) {
jjCheckNAddStates(3, 9);
} else if (curChar == 47) {
jjAddStates(10, 12);
} else if (curChar == 36) {
if (kind > 70) {
kind = 70;
}
jjCheckNAdd(44);
} else if (curChar == 34) {
jjstateSet[jjnewStateCnt++] = 41;
} else if (curChar == 39) {
jjAddStates(13, 14);
} else if (curChar == 46) {
jjCheckNAdd(11);
} else if (curChar == 35) {
jjstateSet[jjnewStateCnt++] = 1;
}
if ((0x3fe000000000000L & l) != 0L) {
if (kind > 60) {
kind = 60;
}
jjCheckNAddTwoStates(8, 9);
} else if (curChar == 48) {
if (kind > 60) {
kind = 60;
}
jjCheckNAddStates(15, 17);
} else if (curChar == 34) {
jjCheckNAddStates(18, 20);
}
break;
case 0:
if ((0x1ffffffffL & l) == 0L) {
break;
}
if (kind > 6) {
kind = 6;
}
jjCheckNAdd(0);
break;
case 1:
if (curChar == 33) {
jjCheckNAddStates(21, 23);
}
break;
case 2:
if ((0xffffffffffffdbffL & l) != 0L) {
jjCheckNAddStates(21, 23);
}
break;
case 3:
if ((0x2400L & l) != 0L && kind > 8) {
kind = 8;
}
break;
case 4:
if (curChar == 10 && kind > 8) {
kind = 8;
}
break;
case 5:
if (curChar == 13) {
jjstateSet[jjnewStateCnt++] = 4;
}
break;
case 7:
if ((0x3fe000000000000L & l) == 0L) {
break;
}
if (kind > 60) {
kind = 60;
}
jjCheckNAddTwoStates(8, 9);
break;
case 8:
if ((0x3ff000000000000L & l) == 0L) {
break;
}
if (kind > 60) {
kind = 60;
}
jjCheckNAddTwoStates(8, 9);
break;
case 10:
if (curChar == 46) {
jjCheckNAdd(11);
}
break;
case 11:
if ((0x3ff000000000000L & l) == 0L) {
break;
}
if (kind > 64) {
kind = 64;
}
jjCheckNAddStates(24, 26);
break;
case 13:
if ((0x280000000000L & l) != 0L) {
jjCheckNAdd(14);
}
break;
case 14:
if ((0x3ff000000000000L & l) == 0L) {
break;
}
if (kind > 64) {
kind = 64;
}
jjCheckNAddTwoStates(14, 15);
break;
case 16:
if (curChar == 39) {
jjAddStates(13, 14);
}
break;
case 17:
if ((0xffffff7fffffdbffL & l) != 0L) {
jjCheckNAdd(18);
}
break;
case 18:
if (curChar == 39 && kind > 66) {
kind = 66;
}
break;
case 20:
if ((0x8400000000L & l) != 0L) {
jjCheckNAdd(18);
}
break;
case 21:
if ((0xff000000000000L & l) != 0L) {
jjCheckNAddTwoStates(22, 18);
}
break;
case 22:
if ((0xff000000000000L & l) != 0L) {
jjCheckNAdd(18);
}
break;
case 23:
if ((0xf000000000000L & l) != 0L) {
jjstateSet[jjnewStateCnt++] = 24;
}
break;
case 24:
if ((0xff000000000000L & l) != 0L) {
jjCheckNAdd(22);
}
break;
case 25:
if (curChar == 34) {
jjCheckNAddStates(18, 20);
}
break;
case 26:
if ((0xfffffffbffffdbffL & l) != 0L) {
jjCheckNAddStates(18, 20);
}
break;
case 28:
if ((0x8400000000L & l) != 0L) {
jjCheckNAddStates(18, 20);
}
break;
case 29:
if (curChar == 34 && kind > 67) {
kind = 67;
}
break;
case 30:
if ((0xff000000000000L & l) != 0L) {
jjCheckNAddStates(27, 30);
}
break;
case 31:
if ((0xff000000000000L & l) != 0L) {
jjCheckNAddStates(18, 20);
}
break;
case 32:
if ((0xf000000000000L & l) != 0L) {
jjstateSet[jjnewStateCnt++] = 33;
}
break;
case 33:
if ((0xff000000000000L & l) != 0L) {
jjCheckNAdd(31);
}
break;
case 34:
case 40:
if (curChar == 34) {
jjCheckNAddTwoStates(35, 38);
}
break;
case 35:
if ((0xfffffffbffffffffL & l) != 0L) {
jjCheckNAddStates(31, 33);
}
break;
case 36:
if (curChar == 34 && kind > 68) {
kind = 68;
}
break;
case 37:
if (curChar == 34) {
jjstateSet[jjnewStateCnt++] = 36;
}
break;
case 38:
if (curChar == 34) {
jjstateSet[jjnewStateCnt++] = 37;
}
break;
case 39:
if (curChar == 34) {
jjCheckNAddStates(34, 36);
}
break;
case 41:
if (curChar == 34) {
jjstateSet[jjnewStateCnt++] = 34;
}
break;
case 42:
if (curChar == 34) {
jjstateSet[jjnewStateCnt++] = 41;
}
break;
case 43:
if (curChar != 36) {
break;
}
if (kind > 70) {
kind = 70;
}
jjCheckNAdd(44);
break;
case 44:
if ((0x3ff001000000000L & l) == 0L) {
break;
}
if (kind > 70) {
kind = 70;
}
jjCheckNAdd(44);
break;
case 45:
if ((0x3ff000000000000L & l) != 0L) {
jjCheckNAddStates(3, 9);
}
break;
case 46:
if ((0x3ff000000000000L & l) != 0L) {
jjCheckNAddTwoStates(46, 47);
}
break;
case 47:
if (curChar != 46) {
break;
}
if (kind > 64) {
kind = 64;
}
jjCheckNAddStates(37, 39);
break;
case 48:
if ((0x3ff000000000000L & l) == 0L) {
break;
}
if (kind > 64) {
kind = 64;
}
jjCheckNAddStates(37, 39);
break;
case 50:
if ((0x280000000000L & l) != 0L) {
jjCheckNAdd(51);
}
break;
case 51:
if ((0x3ff000000000000L & l) == 0L) {
break;
}
if (kind > 64) {
kind = 64;
}
jjCheckNAddTwoStates(51, 15);
break;
case 52:
if ((0x3ff000000000000L & l) != 0L) {
jjCheckNAddTwoStates(52, 53);
}
break;
case 54:
if ((0x280000000000L & l) != 0L) {
jjCheckNAdd(55);
}
break;
case 55:
if ((0x3ff000000000000L & l) == 0L) {
break;
}
if (kind > 64) {
kind = 64;
}
jjCheckNAddTwoStates(55, 15);
break;
case 56:
if ((0x3ff000000000000L & l) != 0L) {
jjCheckNAddStates(40, 42);
}
break;
case 58:
if ((0x280000000000L & l) != 0L) {
jjCheckNAdd(59);
}
break;
case 59:
if ((0x3ff000000000000L & l) != 0L) {
jjCheckNAddTwoStates(59, 15);
}
break;
case 60:
if (curChar != 48) {
break;
}
if (kind > 60) {
kind = 60;
}
jjCheckNAddStates(15, 17);
break;
case 62:
if ((0x3ff000000000000L & l) == 0L) {
break;
}
if (kind > 60) {
kind = 60;
}
jjCheckNAddTwoStates(62, 9);
break;
case 63:
if ((0xff000000000000L & l) == 0L) {
break;
}
if (kind > 60) {
kind = 60;
}
jjCheckNAddTwoStates(63, 9);
break;
case 64:
if (curChar == 47) {
jjAddStates(10, 12);
}
break;
case 66:
if ((0xffffffffffffdbffL & l) == 0L) {
break;
}
if (kind > 7) {
kind = 7;
}
jjCheckNAddStates(0, 2);
break;
case 67:
if ((0x2400L & l) != 0L && kind > 7) {
kind = 7;
}
break;
case 68:
if (curChar == 10 && kind > 7) {
kind = 7;
}
break;
case 69:
if (curChar == 13) {
jjstateSet[jjnewStateCnt++] = 68;
}
break;
case 70:
if (curChar == 42) {
jjCheckNAdd(71);
}
break;
case 71:
if ((0xfffffbffffffffffL & l) != 0L) {
jjCheckNAddTwoStates(71, 72);
}
break;
case 72:
if (curChar == 42) {
jjCheckNAddStates(43, 45);
}
break;
case 73:
if ((0xffff7bffffffffffL & l) != 0L) {
jjCheckNAddTwoStates(74, 72);
}
break;
case 74:
if ((0xfffffbffffffffffL & l) != 0L) {
jjCheckNAddTwoStates(74, 72);
}
break;
case 75:
if (curChar == 47 && kind > 9) {
kind = 9;
}
break;
case 76:
if (curChar == 42) {
jjCheckNAddTwoStates(77, 78);
}
break;
case 77:
if ((0xfffffbffffffffffL & l) != 0L) {
jjCheckNAddTwoStates(77, 78);
}
break;
case 78:
if (curChar == 42) {
jjCheckNAddStates(46, 48);
}
break;
case 79:
if ((0xffff7bffffffffffL & l) != 0L) {
jjCheckNAddTwoStates(80, 78);
}
break;
case 80:
if ((0xfffffbffffffffffL & l) != 0L) {
jjCheckNAddTwoStates(80, 78);
}
break;
case 81:
if (curChar == 47 && kind > 69) {
kind = 69;
}
break;
case 82:
if (curChar == 42) {
jjstateSet[jjnewStateCnt++] = 76;
}
break;
default:
break;
}
} while (i != startsAt);
} else if (curChar < 128) {
long l = 1L << (curChar & 077);
MatchLoop:
do {
switch (jjstateSet[--i]) {
case 6:
case 44:
if ((0x7fffffe87fffffeL & l) == 0L) {
break;
}
if (kind > 70) {
kind = 70;
}
jjCheckNAdd(44);
break;
case 2:
jjAddStates(21, 23);
break;
case 9:
if ((0x100000001000L & l) != 0L && kind > 60) {
kind = 60;
}
break;
case 12:
if ((0x2000000020L & l) != 0L) {
jjAddStates(49, 50);
}
break;
case 15:
if ((0x5000000050L & l) != 0L && kind > 64) {
kind = 64;
}
break;
case 17:
if ((0xffffffffefffffffL & l) != 0L) {
jjCheckNAdd(18);
}
break;
case 19:
if (curChar == 92) {
jjAddStates(51, 53);
}
break;
case 20:
if ((0x14404410000000L & l) != 0L) {
jjCheckNAdd(18);
}
break;
case 26:
if ((0xffffffffefffffffL & l) != 0L) {
jjCheckNAddStates(18, 20);
}
break;
case 27:
if (curChar == 92) {
jjAddStates(54, 56);
}
break;
case 28:
if ((0x14404410000000L & l) != 0L) {
jjCheckNAddStates(18, 20);
}
break;
case 35:
jjAddStates(31, 33);
break;
case 49:
if ((0x2000000020L & l) != 0L) {
jjAddStates(57, 58);
}
break;
case 53:
if ((0x2000000020L & l) != 0L) {
jjAddStates(59, 60);
}
break;
case 57:
if ((0x2000000020L & l) != 0L) {
jjAddStates(61, 62);
}
break;
case 61:
if ((0x100000001000000L & l) != 0L) {
jjCheckNAdd(62);
}
break;
case 62:
if ((0x7e0000007eL & l) == 0L) {
break;
}
if (kind > 60) {
kind = 60;
}
jjCheckNAddTwoStates(62, 9);
break;
case 66:
if (kind > 7) {
kind = 7;
}
jjAddStates(0, 2);
break;
case 71:
jjCheckNAddTwoStates(71, 72);
break;
case 73:
case 74:
jjCheckNAddTwoStates(74, 72);
break;
case 77:
jjCheckNAddTwoStates(77, 78);
break;
case 79:
case 80:
jjCheckNAddTwoStates(80, 78);
break;
default:
break;
}
} while (i != startsAt);
} else {
int hiByte = (curChar >> 8);
int i1 = hiByte >> 6;
long l1 = 1L << (hiByte & 077);
int i2 = (curChar & 0xff) >> 6;
long l2 = 1L << (curChar & 077);
MatchLoop:
do {
switch (jjstateSet[--i]) {
case 6:
if (jjCanMove_0(hiByte, i1, i2, l1, l2)) {
if (kind > 6) {
kind = 6;
}
jjCheckNAdd(0);
}
if (jjCanMove_2(hiByte, i1, i2, l1, l2)) {
if (kind > 70) {
kind = 70;
}
jjCheckNAdd(44);
}
break;
case 0:
if (!jjCanMove_0(hiByte, i1, i2, l1, l2)) {
break;
}
if (kind > 6) {
kind = 6;
}
jjCheckNAdd(0);
break;
case 2:
if (jjCanMove_1(hiByte, i1, i2, l1, l2)) {
jjAddStates(21, 23);
}
break;
case 17:
if (jjCanMove_1(hiByte, i1, i2, l1, l2)) {
jjstateSet[jjnewStateCnt++] = 18;
}
break;
case 26:
if (jjCanMove_1(hiByte, i1, i2, l1, l2)) {
jjAddStates(18, 20);
}
break;
case 35:
if (jjCanMove_1(hiByte, i1, i2, l1, l2)) {
jjAddStates(31, 33);
}
break;
case 43:
case 44:
if (!jjCanMove_2(hiByte, i1, i2, l1, l2)) {
break;
}
if (kind > 70) {
kind = 70;
}
jjCheckNAdd(44);
break;
case 66:
if (!jjCanMove_1(hiByte, i1, i2, l1, l2)) {
break;
}
if (kind > 7) {
kind = 7;
}
jjAddStates(0, 2);
break;
case 71:
if (jjCanMove_1(hiByte, i1, i2, l1, l2)) {
jjCheckNAddTwoStates(71, 72);
}
break;
case 73:
case 74:
if (jjCanMove_1(hiByte, i1, i2, l1, l2)) {
jjCheckNAddTwoStates(74, 72);
}
break;
case 77:
if (jjCanMove_1(hiByte, i1, i2, l1, l2)) {
jjCheckNAddTwoStates(77, 78);
}
break;
case 79:
case 80:
if (jjCanMove_1(hiByte, i1, i2, l1, l2)) {
jjCheckNAddTwoStates(80, 78);
}
break;
default:
break;
}
} while (i != startsAt);
}
if (kind != 0x7fffffff) {
jjmatchedKind = kind;
jjmatchedPos = curPos;
kind = 0x7fffffff;
}
++curPos;
if ((i = jjnewStateCnt) == (startsAt = 83 - (jjnewStateCnt = startsAt))) {
return curPos;
}
try {
curChar = input_stream.readChar();
} catch (java.io.IOException e) {
return curPos;
}
}
}
static final int[] jjnextStates = {
66, 67, 69, 46, 47, 52, 53, 56, 57, 15, 65, 70, 82, 17, 19, 61,
63, 9, 26, 27, 29, 2, 3, 5, 11, 12, 15, 26, 27, 31, 29, 35,
38, 39, 35, 40, 38, 48, 49, 15, 56, 57, 15, 72, 73, 75, 78, 79,
81, 13, 14, 20, 21, 23, 28, 30, 32, 50, 51, 54, 55, 58, 59,};
private static boolean jjCanMove_0(int hiByte, int i1, int i2, long l1, long l2) {
switch (hiByte) {
case 0:
return ((jjbitVec0[i2] & l2) != 0L);
default:
return false;
}
}
private static boolean jjCanMove_1(int hiByte, int i1, int i2, long l1, long l2) {
switch (hiByte) {
case 0:
return ((jjbitVec0[i2] & l2) != 0L);
default:
if ((jjbitVec1[i1] & l1) != 0L) {
return true;
}
return false;
}
}
private static boolean jjCanMove_2(int hiByte, int i1, int i2, long l1, long l2) {
switch (hiByte) {
case 0:
return ((jjbitVec4[i2] & l2) != 0L);
case 48:
return ((jjbitVec5[i2] & l2) != 0L);
case 49:
return ((jjbitVec6[i2] & l2) != 0L);
case 51:
return ((jjbitVec7[i2] & l2) != 0L);
case 61:
return ((jjbitVec8[i2] & l2) != 0L);
default:
if ((jjbitVec3[i1] & l1) != 0L) {
return true;
}
return false;
}
}
public static final String[] jjstrLiteralImages = {
"", null, null, null, null, null, null, null, null, null,
"\141\142\163\164\162\141\143\164", "\142\157\157\154\145\141\156", "\142\162\145\141\153",
"\143\154\141\163\163", "\142\171\164\145", "\143\141\163\145", "\143\141\164\143\150",
"\143\150\141\162", "\143\157\156\163\164", "\143\157\156\164\151\156\165\145",
"\144\145\146\141\165\154\164", "\144\157", "\144\157\165\142\154\145", "\145\154\163\145",
"\145\156\165\155", "\145\170\164\145\156\144\163", "\146\141\154\163\145",
"\146\151\156\141\154", "\146\151\156\141\154\154\171", "\146\154\157\141\164", "\146\157\162",
"\147\157\164\157", "\151\146", "\151\155\160\154\145\155\145\156\164\163",
"\151\155\160\157\162\164", "\151\156\163\164\141\156\143\145\157\146", "\151\156\164",
"\151\156\164\145\162\146\141\143\145", "\154\157\156\147", "\156\141\164\151\166\145", "\156\145\167",
"\156\165\154\154", "\160\141\143\153\141\147\145", "\160\162\151\166\141\164\145",
"\160\162\157\164\145\143\164\145\144", "\160\165\142\154\151\143", "\162\145\164\165\162\156",
"\163\150\157\162\164", "\163\164\141\164\151\143", "\163\164\162\151\143\164\146\160",
"\163\167\151\164\143\150", "\163\171\156\143\150\162\157\156\151\172\145\144",
"\164\162\141\156\163\151\145\156\164", "\164\150\162\157\167", "\164\150\162\157\167\163", "\164\162\165\145",
"\164\162\171", "\166\157\151\144", "\166\157\154\141\164\151\154\145",
"\167\150\151\154\145", null, null, null, null, null, null, null, null, null, null, null, null, null,
"\50", "\51", "\173", "\175", "\133", "\135", "\73", "\54", "\56", "\75", "\76",
"\100\147\164", "\74", "\100\154\164", "\41", "\176", "\77", "\72", "\75\75", "\74\75",
"\100\154\164\145\161", "\76\75", "\100\147\164\145\161", "\41\75", "\174\174", "\100\157\162",
"\46\46", "\100\141\156\144", "\53\53", "\55\55", "\53", "\55", "\52", "\57", "\46",
"\100\142\151\164\167\151\163\145\137\141\156\144", "\174", "\100\142\151\164\167\151\163\145\137\157\162", "\136", "\45",
"\74\74", "\100\154\145\146\164\137\163\150\151\146\164", "\76\76",
"\100\162\151\147\150\164\137\163\150\151\146\164", "\76\76\76",
"\100\162\151\147\150\164\137\165\156\163\151\147\156\145\144\137\163\150\151\146\164", "\53\75", "\55\75", "\52\75", "\57\75", "\46\75",
"\100\141\156\144\137\141\163\163\151\147\156", "\174\75", "\100\157\162\137\141\163\163\151\147\156", "\136\75", "\45\75",
"\74\74\75", "\100\154\145\146\164\137\163\150\151\146\164\137\141\163\163\151\147\156",
"\76\76\75",
"\100\162\151\147\150\164\137\163\150\151\146\164\137\141\163\163\151\147\156", "\76\76\76\75",
"\100\162\151\147\150\164\137\165\156\163\151\147\156\145\144\137\163\150\151\146\164\137\141\163\163\151\147\156",};
public static final String[] lexStateNames = {
"DEFAULT",};
static final long[] jjtoToken = {
0x1ffffffffffffc01L, 0xfffffffffffffe7dL, 0x7fL,};
static final long[] jjtoSkip = {
0x3feL, 0x0L, 0x0L,};
static final long[] jjtoSpecial = {
0x380L, 0x0L, 0x0L,};
protected JavaCharStream input_stream;
private final int[] jjrounds = new int[83];
private final int[] jjstateSet = new int[166];
protected char curChar;
public ParserTokenManager(JavaCharStream stream) {
if (JavaCharStream.staticFlag) {
throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer.");
}
input_stream = stream;
}
public ParserTokenManager(JavaCharStream stream, int lexState) {
this(stream);
SwitchTo(lexState);
}
public void ReInit(JavaCharStream stream) {
jjmatchedPos = jjnewStateCnt = 0;
curLexState = defaultLexState;
input_stream = stream;
ReInitRounds();
}
private void ReInitRounds() {
int i;
jjround = 0x80000001;
for (i = 83; i-- > 0;) {
jjrounds[i] = 0x80000000;
}
}
public void ReInit(JavaCharStream stream, int lexState) {
ReInit(stream);
SwitchTo(lexState);
}
public void SwitchTo(int lexState) {
if (lexState >= 1 || lexState < 0) {
throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE);
} else {
curLexState = lexState;
}
}
protected Token jjFillToken() {
Token t = Token.newToken(jjmatchedKind);
t.kind = jjmatchedKind;
String im = jjstrLiteralImages[jjmatchedKind];
t.image = (im == null) ? input_stream.GetImage() : im;
t.beginLine = input_stream.getBeginLine();
t.beginColumn = input_stream.getBeginColumn();
t.endLine = input_stream.getEndLine();
t.endColumn = input_stream.getEndColumn();
return t;
}
int curLexState = 0;
int defaultLexState = 0;
int jjnewStateCnt;
int jjround;
int jjmatchedPos;
int jjmatchedKind;
public Token getNextToken() {
int kind;
Token specialToken = null;
Token matchedToken;
int curPos = 0;
EOFLoop:
for (;;) {
try {
curChar = input_stream.BeginToken();
} catch (java.io.IOException e) {
jjmatchedKind = 0;
matchedToken = jjFillToken();
matchedToken.specialToken = specialToken;
return matchedToken;
}
jjmatchedKind = 0x7fffffff;
jjmatchedPos = 0;
curPos = jjMoveStringLiteralDfa0_0();
if (jjmatchedKind != 0x7fffffff) {
if (jjmatchedPos + 1 < curPos) {
input_stream.backup(curPos - jjmatchedPos - 1);
}
if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L) {
matchedToken = jjFillToken();
matchedToken.specialToken = specialToken;
return matchedToken;
} else {
if ((jjtoSpecial[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L) {
matchedToken = jjFillToken();
if (specialToken == null) {
specialToken = matchedToken;
} else {
matchedToken.specialToken = specialToken;
specialToken = (specialToken.next = matchedToken);
}
}
continue;
}
}
int error_line = input_stream.getEndLine();
int error_column = input_stream.getEndColumn();
String error_after = null;
boolean EOFSeen = false;
try {
input_stream.readChar();
input_stream.backup(1);
} catch (java.io.IOException e1) {
EOFSeen = true;
error_after = curPos <= 1 ? "" : input_stream.GetImage();
if (curChar == '\n' || curChar == '\r') {
error_line++;
error_column = 0;
} else {
error_column++;
}
}
if (!EOFSeen) {
input_stream.backup(1);
error_after = curPos <= 1 ? "" : input_stream.GetImage();
}
throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR);
}
}
}
| 96,596 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
ParseException.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/ParseException.java | /* Generated By:JavaCC: Do not edit this line. ParseException.java Version 3.0 */
/*
This file was auto generated, but has been modified since then. If we
need to regenerate it for some reason we should be careful to look at
the notes below.
All BeanShell modifications are demarcated by "Begin BeanShell
Modification - ... " and "End BeanShell Modification - ..."
Note: Please leave the ^M carriage return in the above auto-generated line
or JavaCC will complain about version on Win systems.
BeanShell Modification to generated file
----------------------------------------
- Added sourceFile attribute
setErrorSourceFile()
getErrorSourceFile()
- Modified getMessage() to print more tersely except on debug
(removed "Was expecting one of...)
- Added sourceFile info to getMessage()
- Made ParseException extend EvalError
- Modified constructors to use EvalError
- Override
getErrorLineNumber()
getErrorText()
*/
package ehacks.bsh;
/**
* This exception is thrown when parse errors are encountered. You can
* explicitly create objects of this exception type by calling the method
* generateParseException in the generated parser.
*
* You can modify this class to customize your error reporting mechanisms so
* long as you retain the public fields.
*/
// Begin BeanShell Modification - public, extend EvalError
public class ParseException extends EvalError {
// End BeanShell Modification - public, extend EvalError
// Begin BeanShell Modification - sourceFile
private String sourceFile = "<unknown>";
/**
* Used to add source file info to exception
*/
public void setErrorSourceFile(String file) {
this.sourceFile = file;
}
@Override
public String getErrorSourceFile() {
return sourceFile;
}
// End BeanShell Modification - sourceFile
/**
* This constructor is used by the method "generateParseException" in the
* generated parser. Calling this constructor generates a new object of this
* type with the fields "currentToken", "expectedTokenSequences", and
* "tokenImage" set. The boolean flag "specialConstructor" is also set to
* true to indicate that this constructor was used to create this object.
* This constructor calls its super class with the empty string to force the
* "toString" method of parent class "Throwable" to print the error message
* in the form: ParseException: <result of getMessage>
*/
public ParseException(Token currentTokenVal,
int[][] expectedTokenSequencesVal,
String[] tokenImageVal
) {
// Begin BeanShell Modification - constructor
this();
// End BeanShell Modification - constructor
specialConstructor = true;
currentToken = currentTokenVal;
expectedTokenSequences = expectedTokenSequencesVal;
tokenImage = tokenImageVal;
}
/**
* The following constructors are for use by you for whatever purpose you
* can think of. Constructing the exception in this manner makes the
* exception behave in the normal way - i.e., as documented in the class
* "Throwable". The fields "errorToken", "expectedTokenSequences", and
* "tokenImage" do not contain relevant information. The JavaCC generated
* code does not use these constructors.
*/
public ParseException() {
// Begin BeanShell Modification - constructor
this("");
// End BeanShell Modification - constructor
specialConstructor = false;
}
public ParseException(String message) {
// Begin BeanShell Modification - super constructor args
// null node, null callstack, ParseException knows where the error is.
super(message, null, null);
// End BeanShell Modification - super constructor args
specialConstructor = false;
}
public ParseException(String message, Throwable cause) {
// Begin BeanShell Modification - super constructor args
// null node, null callstack, ParseException knows where the error is.
super(message, null, null, cause);
// End BeanShell Modification - super constructor args
specialConstructor = false;
}
/**
* This variable determines which constructor was used to create this object
* and thereby affects the semantics of the "getMessage" method (see below).
* This is the same as "currentToken != null".
*/
boolean specialConstructor;
/**
* This is the last token that has been consumed successfully. If this
* object has been created due to a parse error, the token followng this
* token will (therefore) be the first error token.
*/
public Token currentToken;
/**
* Each entry in this array is an array of integers. Each array of integers
* represents a sequence of tokens (by their ordinal values) that is
* expected at this point of the parse.
*/
public int[][] expectedTokenSequences;
/**
* This is a reference to the "tokenImage" array of the generated parser
* within which the parse error occurred. This array is defined in the
* generated ...Constants interface.
*/
public String[] tokenImage;
// Begin BeanShell Modification - moved body to overloaded getMessage()
@Override
public String getMessage() {
return getMessage(false);
}
// End BeanShell Modification - moved body to overloaded getMessage()
/**
* This method has the standard behavior when this object has been created
* using the standard constructors. Otherwise, it uses "currentToken" and
* "expectedTokenSequences" to generate a parse error message and returns
* it. If this object has been created due to a parse error, and you do not
* catch it (it gets thrown from the parser), then this method is called
* during the printing of the final stack trace, and hence the correct error
* message gets displayed.
*/
// Begin BeanShell Modification - added debug param
public String getMessage(boolean debug) {
// End BeanShell Modification - added debug param
if (!specialConstructor) {
return super.getRawMessage();
}
String expected = "";
int maxSize = 0;
for (int i = 0; i < expectedTokenSequences.length; i++) {
if (maxSize < expectedTokenSequences[i].length) {
maxSize = expectedTokenSequences[i].length;
}
for (int j = 0; j < expectedTokenSequences[i].length; j++) {
expected += tokenImage[expectedTokenSequences[i][j]] + " ";
}
if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
expected += "...";
}
expected += eol + " ";
}
// Begin BeanShell Modification - added sourceFile info
String retval = "In file: " + sourceFile + " Encountered \"";
// End BeanShell Modification - added sourceFile info
Token tok = currentToken.next;
for (int i = 0; i < maxSize; i++) {
if (i != 0) {
retval += " ";
}
if (tok.kind == 0) {
retval += tokenImage[0];
break;
}
retval += add_escapes(tok.image);
tok = tok.next;
}
retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn + "." + eol;
// Begin BeanShell Modification - made conditional on debug
if (debug) {
if (expectedTokenSequences.length == 1) {
retval += "Was expecting:" + eol + " ";
} else {
retval += "Was expecting one of:" + eol + " ";
}
retval += expected;
}
// End BeanShell Modification - made conditional on debug
return retval;
}
/**
* The end of line string for this machine.
*/
String eol = System.getProperty("line.separator", "\n");
/**
* Used to convert raw characters to their escaped version when these raw
* version cannot be used as part of an ASCII string literal.
*/
String add_escapes(String str) {
StringBuilder retval = new StringBuilder();
char ch;
for (int i = 0; i < str.length(); i++) {
switch (str.charAt(i)) {
case 0:
continue;
case '\b':
retval.append("\\b");
continue;
case '\t':
retval.append("\\t");
continue;
case '\n':
retval.append("\\n");
continue;
case '\f':
retval.append("\\f");
continue;
case '\r':
retval.append("\\r");
continue;
case '\"':
retval.append("\\\"");
continue;
case '\'':
retval.append("\\\'");
continue;
case '\\':
retval.append("\\\\");
continue;
default:
if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
String s = "0000" + Integer.toString(ch, 16);
retval.append("\\u").append(s.substring(s.length() - 4, s.length()));
} else {
retval.append(ch);
}
}
}
return retval.toString();
}
// Begin BeanShell Modification - override error methods and toString
@Override
public int getErrorLineNumber() {
if (currentToken == null) {
String message = getMessage();
int index = message.indexOf(" at line ");
if (index > -1) {
message = message.substring(index + 9);
index = message.indexOf(',');
try {
if (index == -1) {
return Integer.parseInt(message);
}
return Integer.parseInt(message.substring(0, index));
} catch (NumberFormatException e) {
// ignore, we have no valid line information, just return -1 for now
}
}
return -1;
} else {
return currentToken.next.beginLine;
}
}
@Override
public String getErrorText() {
// copied from generated getMessage()
int maxSize = 0;
for (int i = 0; i < expectedTokenSequences.length; i++) {
if (maxSize < expectedTokenSequences[i].length) {
maxSize = expectedTokenSequences[i].length;
}
}
String retval = "";
Token tok = currentToken.next;
for (int i = 0; i < maxSize; i++) {
if (i != 0) {
retval += " ";
}
if (tok.kind == 0) {
retval += tokenImage[0];
break;
}
retval += add_escapes(tok.image);
tok = tok.next;
}
return retval;
}
// End BeanShell Modification - override error methods and toString
}
| 11,419 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHTryStatement.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHTryStatement.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
import java.util.ArrayList;
import java.util.List;
class BSHTryStatement extends SimpleNode {
BSHTryStatement(int id) {
super(id);
}
@Override
public Object eval(CallStack callstack, Interpreter interpreter)
throws EvalError {
BSHBlock tryBlock = ((BSHBlock) jjtGetChild(0));
List<BSHFormalParameter> catchParams = new ArrayList<>();
List<BSHBlock> catchBlocks = new ArrayList<>();
int nchild = jjtGetNumChildren();
Node node = null;
int i = 1;
while ((i < nchild) && ((node = jjtGetChild(i++)) instanceof BSHFormalParameter)) {
catchParams.add((BSHFormalParameter) node);
catchBlocks.add((BSHBlock) jjtGetChild(i++));
node = null;
}
// finaly block
BSHBlock finallyBlock = null;
if (node != null) {
finallyBlock = (BSHBlock) node;
}
// Why both of these?
TargetError target = null;
Throwable thrown = null;
Object ret = null;
/*
Evaluate the contents of the try { } block and catch any resulting
TargetErrors generated by the script.
We save the callstack depth and if an exception is thrown we pop
back to that depth before contiuing. The exception short circuited
any intervening method context pops.
Note: we the stack info... what do we do with it? append
to exception message?
*/
int callstackDepth = callstack.depth();
try {
ret = tryBlock.eval(callstack, interpreter);
} catch (TargetError e) {
target = e;
String stackInfo = "Bsh Stack: ";
while (callstack.depth() > callstackDepth) {
stackInfo += "\t" + callstack.pop() + "\n";
}
}
// unwrap the target error
if (target != null) {
thrown = target.getTarget();
}
// If we have an exception, find a catch
if (thrown != null) {
int n = catchParams.size();
for (i = 0; i < n; i++) {
// Get catch block
BSHFormalParameter fp = catchParams.get(i);
// Should cache this subject to classloader change message
// Evaluation of the formal parameter simply resolves its
// type via the specified namespace.. it doesn't modify the
// namespace.
fp.eval(callstack, interpreter);
if (fp.type == null && interpreter.getStrictJava()) {
throw new EvalError(
"(Strict Java) Untyped catch block", this, callstack);
}
// If the param is typed check assignability
if (fp.type != null) {
try {
thrown = (Throwable) Types.castObject(
thrown/*rsh*/, fp.type/*lhsType*/, Types.ASSIGNMENT);
} catch (UtilEvalError e) {
/*
Catch the mismatch and continue to try the next
Note: this is innefficient, should have an
isAssignableFrom() that doesn't throw
// TODO: we do now have a way to test assignment
// in castObject(), use it?
*/
continue;
}
}
// Found match, execute catch block
BSHBlock cb = catchBlocks.get(i);
// Prepare to execute the block.
// We must create a new BlockNameSpace to hold the catch
// parameter and swap it on the stack after initializing it.
NameSpace enclosingNameSpace = callstack.top();
BlockNameSpace cbNameSpace
= new BlockNameSpace(enclosingNameSpace);
try {
if (fp.type == BSHFormalParameter.UNTYPED) // set an untyped variable directly in the block
{
cbNameSpace.setBlockVariable(fp.name, thrown);
} else {
// set a typed variable (directly in the block)
Modifiers modifiers = new Modifiers();
cbNameSpace.setTypedVariable(
fp.name, fp.type, thrown, new Modifiers()/*none*/);
}
} catch (UtilEvalError e) {
throw new InterpreterError(
"Unable to set var in catch block namespace.");
}
// put cbNameSpace on the top of the stack
callstack.swap(cbNameSpace);
try {
ret = cb.eval(callstack, interpreter);
} finally {
// put it back
callstack.swap(enclosingNameSpace);
}
target = null; // handled target
break;
}
}
// evaluate finally block
if (finallyBlock != null) {
Object result = finallyBlock.eval(callstack, interpreter);
if (result instanceof ReturnControl) {
return result;
}
}
// exception fell through, throw it upward...
if (target != null) {
throw target;
}
if (ret instanceof ReturnControl) {
return ret;
} else {
return Primitive.VOID;
}
}
}
| 8,080 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
StringUtil.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/StringUtil.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
import java.util.*;
public class StringUtil {
public static String[] split(String s, String delim) {
List<String> v = new ArrayList<>();
StringTokenizer st = new StringTokenizer(s, delim);
while (st.hasMoreTokens()) {
v.add(st.nextToken());
}
return v.toArray(new String[v.size()]);
}
public static String maxCommonPrefix(String one, String two) {
int i = 0;
while (one.regionMatches(0, two, 0, i)) {
i++;
}
return one.substring(0, i - 1);
}
public static String methodString(String name, Class[] types) {
StringBuilder sb = new StringBuilder(name + "(");
if (types.length > 0) {
sb.append(" ");
}
for (int i = 0; i < types.length; i++) {
Class c = types[i];
sb.append((c == null) ? "null" : c.getName()).append(i < (types.length - 1) ? ", " : " ");
}
sb.append(")");
return sb.toString();
}
/**
* Split a filename into dirName, baseName
*
* @return String [] { dirName, baseName } public String [] splitFileName(
* String fileName ) { String dirName, baseName; int i =
* fileName.lastIndexOf( File.separator ); if ( i != -1 ) { dirName =
* fileName.substring(0, i); baseName = fileName.substring(i+1); } else
* baseName = fileName;
*
* return new String[] { dirName, baseName }; }
*
*/
/**
* Hack - The real method is in Reflect.java which is not public.
*/
public static String normalizeClassName(Class type) {
return Reflect.normalizeClassName(type);
}
}
| 4,216 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHType.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHType.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
import java.lang.reflect.Array;
class BSHType extends SimpleNode
implements BSHClassManager.Listener {
/**
* baseType is used during evaluation of full type and retained for the case
* where we are an array type. In the case where we are not an array this
* will be the same as type.
*/
private Class baseType;
/**
* If we are an array type this will be non zero and indicate the
* dimensionality of the array. e.g. 2 for String[][];
*/
private int arrayDims;
/**
* Internal cache of the type. Cleared on classloader change.
*/
private Class type;
String descriptor;
BSHType(int id) {
super(id);
}
/**
* Used by the grammar to indicate dimensions of array types during parsing.
*/
public void addArrayDimension() {
arrayDims++;
}
SimpleNode getTypeNode() {
return (SimpleNode) jjtGetChild(0);
}
/**
* Returns a class descriptor for this type. If the type is an ambiguous
* name (object type) evaluation is attempted through the namespace in order
* to resolve imports. If it is not found and the name is non-compound we
* assume the default package for the name.
*/
public String getTypeDescriptor(
CallStack callstack, Interpreter interpreter, String defaultPackage) {
// return cached type if available
if (descriptor != null) {
return descriptor;
}
String descriptor;
// first node will either be PrimitiveType or AmbiguousName
SimpleNode node = getTypeNode();
if (node instanceof BSHPrimitiveType) {
descriptor = getTypeDescriptor(((BSHPrimitiveType) node).type);
} else {
String clasName = ((BSHAmbiguousName) node).text;
BSHClassManager bcm = interpreter.getClassManager();
// Note: incorrect here - we are using the hack in bsh class
// manager that allows lookup by base name. We need to eliminate
// this limitation by working through imports. See notes in class
// manager.
String definingClass = bcm.getClassBeingDefined(clasName);
Class clas = null;
if (definingClass == null) {
try {
clas = ((BSHAmbiguousName) node).toClass(
callstack, interpreter);
} catch (EvalError e) {
//throw new InterpreterError("unable to resolve type: "+e);
// ignore and try default package
//System.out.println("BSHType: "+node+" class not found");
}
} else {
clasName = definingClass;
}
if (clas != null) {
//System.out.println("found clas: "+clas);
descriptor = getTypeDescriptor(clas);
} else {
if (defaultPackage == null || Name.isCompound(clasName)) {
descriptor = "L" + clasName.replace('.', '/') + ";";
} else {
descriptor
= "L" + defaultPackage.replace('.', '/') + "/" + clasName + ";";
}
}
}
for (int i = 0; i < arrayDims; i++) {
descriptor = "[" + descriptor;
}
this.descriptor = descriptor;
//System.out.println("BSHType: returning descriptor: "+descriptor);
return descriptor;
}
public Class getType(CallStack callstack, Interpreter interpreter)
throws EvalError {
// return cached type if available
if (type != null) {
return type;
}
// first node will either be PrimitiveType or AmbiguousName
SimpleNode node = getTypeNode();
if (node instanceof BSHPrimitiveType) {
baseType = ((BSHPrimitiveType) node).getType();
} else {
baseType = ((BSHAmbiguousName) node).toClass(
callstack, interpreter);
}
if (arrayDims > 0) {
try {
// Get the type by constructing a prototype array with
// arbitrary (zero) length in each dimension.
int[] dims = new int[arrayDims]; // int array default zeros
Object obj = Array.newInstance(baseType, dims);
type = obj.getClass();
} catch (Exception e) {
throw new EvalError("Couldn't construct array type",
this, callstack);
}
} else {
type = baseType;
}
// hack... sticking to first interpreter that resolves this
// see comments on type instance variable
interpreter.getClassManager().addListener(this);
return type;
}
/**
* baseType is used during evaluation of full type and retained for the case
* where we are an array type. In the case where we are not an array this
* will be the same as type.
*/
public Class getBaseType() {
return baseType;
}
/**
* If we are an array type this will be non zero and indicate the
* dimensionality of the array. e.g. 2 for String[][];
*/
public int getArrayDims() {
return arrayDims;
}
@Override
public void classLoaderChanged() {
type = null;
baseType = null;
}
public static String getTypeDescriptor(Class clas) {
if (clas == Boolean.TYPE) {
return "Z";
}
if (clas == Character.TYPE) {
return "C";
}
if (clas == Byte.TYPE) {
return "B";
}
if (clas == Short.TYPE) {
return "S";
}
if (clas == Integer.TYPE) {
return "I";
}
if (clas == Long.TYPE) {
return "J";
}
if (clas == Float.TYPE) {
return "F";
}
if (clas == Double.TYPE) {
return "D";
}
if (clas == Void.TYPE) {
return "V";
}
// Is getName() ok? test with 1.1
String name = clas.getName().replace('.', '/');
if (name.startsWith("[") || name.endsWith(";")) {
return name;
} else {
return "L" + name.replace('.', '/') + ";";
}
}
}
| 8,956 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHPrimitiveType.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHPrimitiveType.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
class BSHPrimitiveType extends SimpleNode {
public Class type;
BSHPrimitiveType(int id) {
super(id);
}
public Class getType() {
return type;
}
}
| 2,736 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
TokenMgrError.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/TokenMgrError.java | /* Generated By:JavaCC: Do not edit this line. TokenMgrError.java Version 3.0 */
package ehacks.bsh;
public class TokenMgrError extends Error {
/*
* Ordinals for various reasons why an Error of this type can be thrown.
*/
/**
* Lexical error occured.
*/
static final int LEXICAL_ERROR = 0;
/**
* An attempt wass made to create a second instance of a static token
* manager.
*/
static final int STATIC_LEXER_ERROR = 1;
/**
* Tried to change to an invalid lexical state.
*/
static final int INVALID_LEXICAL_STATE = 2;
/**
* Detected (and bailed out of) an infinite loop in the token manager.
*/
static final int LOOP_DETECTED = 3;
/**
* Indicates the reason why the exception is thrown. It will have one of the
* above 4 values.
*/
int errorCode;
/**
* Replaces unprintable characters by their espaced (or unicode escaped)
* equivalents in the given string
*/
protected static String addEscapes(String str) {
StringBuilder retval = new StringBuilder();
char ch;
for (int i = 0; i < str.length(); i++) {
switch (str.charAt(i)) {
case 0:
continue;
case '\b':
retval.append("\\b");
continue;
case '\t':
retval.append("\\t");
continue;
case '\n':
retval.append("\\n");
continue;
case '\f':
retval.append("\\f");
continue;
case '\r':
retval.append("\\r");
continue;
case '\"':
retval.append("\\\"");
continue;
case '\'':
retval.append("\\\'");
continue;
case '\\':
retval.append("\\\\");
continue;
default:
if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
String s = "0000" + Integer.toString(ch, 16);
retval.append("\\u").append(s.substring(s.length() - 4, s.length()));
} else {
retval.append(ch);
}
}
}
return retval.toString();
}
/**
* Returns a detailed message for the Error when it is thrown by the token
* manager to indicate a lexical error. Parameters : EOFSeen : indicates if
* EOF caused the lexicl error curLexState : lexical state in which this
* error occured errorLine : line number when the error occured errorColumn
* : column number when the error occured errorAfter : prefix that was seen
* before this error occured curchar : the offending character Note: You can
* customize the lexical error message by modifying this method.
*/
protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) {
return ("Lexical error at line "
+ errorLine + ", column "
+ errorColumn + ". Encountered: "
+ (EOFSeen ? "<EOF> " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int) curChar + "), ")
+ "after : \"" + addEscapes(errorAfter) + "\"");
}
/**
* You can also modify the body of this method to customize your error
* messages. For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE
* are not of end-users concern, so you can return something like :
*
* "Internal Error : Please file a bug report .... "
*
* from this method for such cases in the release version of your parser.
*/
@Override
public String getMessage() {
return super.getMessage();
}
/*
* Constructors of various flavors follow.
*/
public TokenMgrError() {
}
public TokenMgrError(String message, int reason) {
super(message);
errorCode = reason;
}
public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) {
this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason);
}
}
| 4,437 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHPackageDeclaration.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHPackageDeclaration.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
public class BSHPackageDeclaration extends SimpleNode {
public BSHPackageDeclaration(int id) {
super(id);
}
@Override
public Object eval(CallStack callstack, Interpreter interpreter)
throws EvalError {
BSHAmbiguousName name = (BSHAmbiguousName) jjtGetChild(0);
NameSpace namespace = callstack.top();
namespace.setPackage(name.text);
// import the package we're in by default...
namespace.importPackage(name.text);
return Primitive.VOID;
}
}
| 3,083 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHBinaryExpression.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHBinaryExpression.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
/**
* Implement binary expressions... Note: this is too complicated... need some
* cleanup and simplification.
*
* @see Primitive.binaryOperation
*/
class BSHBinaryExpression extends SimpleNode
implements ParserConstants {
public int kind;
BSHBinaryExpression(int id) {
super(id);
}
@Override
public Object eval(CallStack callstack, Interpreter interpreter)
throws EvalError {
Object lhs = ((SimpleNode) jjtGetChild(0)).eval(callstack, interpreter);
/*
Doing instanceof? Next node is a type.
*/
if (kind == INSTANCEOF) {
// null object ref is not instance of any type
if (lhs == Primitive.NULL) {
return new Primitive(false);
}
Class rhs = ((BSHType) jjtGetChild(1)).getType(
callstack, interpreter);
/*
// primitive (number or void) cannot be tested for instanceof
if (lhs instanceof Primitive)
throw new EvalError("Cannot be instance of primitive type." );
*/
/*
Primitive (number or void) is not normally an instanceof
anything. But for internal use we'll test true for the
bsh.Primitive class.
i.e. (5 instanceof bsh.Primitive) will be true
*/
if (lhs instanceof Primitive) {
if (rhs == ehacks.bsh.Primitive.class) {
return new Primitive(true);
} else {
return new Primitive(false);
}
}
// General case - performe the instanceof based on assignability
boolean ret = Types.isJavaBaseAssignable(rhs, lhs.getClass());
return new Primitive(ret);
}
// The following two boolean checks were tacked on.
// This could probably be smoothed out.
/*
Look ahead and short circuit evaluation of the rhs if:
we're a boolean AND and the lhs is false.
*/
if (kind == BOOL_AND || kind == BOOL_ANDX) {
Object obj = lhs;
if (isPrimitiveValue(lhs)) {
obj = ((Primitive) lhs).getValue();
}
if (obj instanceof Boolean
&& (((Boolean) obj) == false)) {
return new Primitive(false);
}
}
/*
Look ahead and short circuit evaluation of the rhs if:
we're a boolean AND and the lhs is false.
*/
if (kind == BOOL_OR || kind == BOOL_ORX) {
Object obj = lhs;
if (isPrimitiveValue(lhs)) {
obj = ((Primitive) lhs).getValue();
}
if (obj instanceof Boolean
&& (((Boolean) obj) == true)) {
return new Primitive(true);
}
}
// end stuff that was tacked on for boolean short-circuiting.
/*
Are both the lhs and rhs either wrappers or primitive values?
do binary op
*/
boolean isLhsWrapper = isWrapper(lhs);
Object rhs = ((SimpleNode) jjtGetChild(1)).eval(callstack, interpreter);
boolean isRhsWrapper = isWrapper(rhs);
if ((isLhsWrapper || isPrimitiveValue(lhs))
&& (isRhsWrapper || isPrimitiveValue(rhs))) {
// Special case for EQ on two wrapper objects
if ((isLhsWrapper && isRhsWrapper && kind == EQ)) {
/*
Don't auto-unwrap wrappers (preserve identity semantics)
FALL THROUGH TO OBJECT OPERATIONS BELOW.
*/
} else {
try {
return Primitive.binaryOperation(lhs, rhs, kind);
} catch (UtilEvalError e) {
throw e.toEvalError(this, callstack);
}
}
}
/*
Doing the following makes it hard to use untyped vars...
e.g. if ( arg == null ) ...what if arg is a primitive?
The answer is that we should test only if the var is typed...?
need to get that info here...
else
{
// Do we have a mixture of primitive values and non-primitives ?
// (primitiveValue = not null, not void)
int primCount = 0;
if ( isPrimitiveValue( lhs ) )
++primCount;
if ( isPrimitiveValue( rhs ) )
++primCount;
if ( primCount > 1 )
// both primitive types, should have been handled above
throw new InterpreterError("should not be here");
else
if ( primCount == 1 )
// mixture of one and the other
throw new EvalError("Operator: '" + tokenImage[kind]
+"' inappropriate for object / primitive combination.",
this, callstack );
// else fall through to handle both non-primitive types
// end check for primitive and non-primitive mix
}
*/
/*
Treat lhs and rhs as arbitrary objects and do the operation.
(including NULL and VOID represented by their Primitive types)
*/
//System.out.println("binary op arbitrary obj: {"+lhs+"}, {"+rhs+"}");
switch (kind) {
case EQ:
return new Primitive((lhs == rhs));
case NE:
return new Primitive((lhs != rhs));
case PLUS:
if (lhs instanceof String || rhs instanceof String) {
return lhs.toString() + rhs.toString();
}
// FALL THROUGH TO DEFAULT CASE!!!
default:
if (lhs instanceof Primitive || rhs instanceof Primitive) {
if (lhs == Primitive.VOID || rhs == Primitive.VOID) {
throw new EvalError(
"illegal use of undefined variable, class, or 'void' literal",
this, callstack);
} else if (lhs == Primitive.NULL || rhs == Primitive.NULL) {
throw new EvalError(
"illegal use of null value or 'null' literal", this, callstack);
}
}
throw new EvalError("Operator: '" + tokenImage[kind]
+ "' inappropriate for objects", this, callstack);
}
}
/*
object is a non-null and non-void Primitive type
*/
private boolean isPrimitiveValue(Object obj) {
return ((obj instanceof Primitive)
&& (obj != Primitive.VOID) && (obj != Primitive.NULL));
}
/*
object is a java.lang wrapper for boolean, char, or number type
*/
private boolean isWrapper(Object obj) {
return (obj instanceof Boolean
|| obj instanceof Character || obj instanceof Number);
}
}
| 9,188 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHTernaryExpression.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHTernaryExpression.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
/**
* This class needs logic to prevent the right hand side of boolean logical
* expressions from being naively evaluated... e.g. for "foo && bar" bar should
* not be evaluated in the case where foo is true.
*/
class BSHTernaryExpression extends SimpleNode {
BSHTernaryExpression(int id) {
super(id);
}
@Override
public Object eval(CallStack callstack, Interpreter interpreter)
throws EvalError {
SimpleNode cond = (SimpleNode) jjtGetChild(0),
evalTrue = (SimpleNode) jjtGetChild(1),
evalFalse = (SimpleNode) jjtGetChild(2);
if (BSHIfStatement.evaluateCondition(cond, callstack, interpreter)) {
return evalTrue.eval(callstack, interpreter);
} else {
return evalFalse.eval(callstack, interpreter);
}
}
}
| 3,391 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHCastExpression.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHCastExpression.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
/**
* Implement casts.
*
* I think it should be possible to simplify some of the code here by using the
* Types.getAssignableForm() method, but I haven't looked into it.
*/
class BSHCastExpression extends SimpleNode {
public BSHCastExpression(int id) {
super(id);
}
/**
* @return the result of the cast.
*/
@Override
public Object eval(
CallStack callstack, Interpreter interpreter) throws EvalError {
NameSpace namespace = callstack.top();
Class toType = ((BSHType) jjtGetChild(0)).getType(
callstack, interpreter);
SimpleNode expression = (SimpleNode) jjtGetChild(1);
// evaluate the expression
Object fromValue = expression.eval(callstack, interpreter);
Class fromType = fromValue.getClass();
// TODO: need to add isJavaCastable() test for strictJava
// (as opposed to isJavaAssignable())
try {
return Types.castObject(fromValue, toType, Types.CAST);
} catch (UtilEvalError e) {
throw e.toEvalError(this, callstack);
}
}
}
| 3,670 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
CodeWriter.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/CodeWriter.java | /** *
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (C) 2000 INRIA, France Telecom
* Copyright (C) 2002 France Telecom
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact: [email protected]
*
* Author: Eric Bruneton
*/
package ehacks.bsh;
/**
* A {@link CodeVisitor CodeVisitor} that generates Java bytecode instructions.
* Each visit method of this class appends the bytecode corresponding to the
* visited instruction to a byte vector, in the order these methods are called.
*/
public class CodeWriter implements CodeVisitor {
/**
* <tt>true</tt> if preconditions must be checked at runtime or not.
*/
final static boolean CHECK = false;
/**
* Next code writer (see {@link ClassWriter#firstMethod firstMethod}).
*/
CodeWriter next;
/**
* The class writer to which this method must be added.
*/
private final ClassWriter cw;
/**
* The constant pool item that contains the name of this method.
*/
private Item name;
/**
* The constant pool item that contains the descriptor of this method.
*/
private Item desc;
/**
* Access flags of this method.
*/
private int access;
/**
* Maximum stack size of this method.
*/
private int maxStack;
/**
* Maximum number of local variables for this method.
*/
private int maxLocals;
/**
* The bytecode of this method.
*/
private ByteVector code = new ByteVector();
/**
* Number of entries in the catch table of this method.
*/
private int catchCount;
/**
* The catch table of this method.
*/
private ByteVector catchTable;
/**
* Number of exceptions that can be thrown by this method.
*/
private int exceptionCount;
/**
* The exceptions that can be thrown by this method. More precisely, this
* array contains the indexes of the constant pool items that contain the
* internal names of these exception classes.
*/
private int[] exceptions;
/**
* Number of entries in the LocalVariableTable attribute.
*/
private int localVarCount;
/**
* The LocalVariableTable attribute.
*/
private ByteVector localVar;
/**
* Number of entries in the LineNumberTable attribute.
*/
private int lineNumberCount;
/**
* The LineNumberTable attribute.
*/
private ByteVector lineNumber;
/**
* Indicates if some jump instructions are too small and need to be resized.
*/
private boolean resize;
// --------------------------------------------------------------------------
// Fields for the control flow graph analysis algorithm (used to compute the
// maximum stack size). A control flow graph contains one node per "basic
// block", and one edge per "jump" from one basic block to another. Each node
// (i.e., each basic block) is represented by the Label object that
// corresponds to the first instruction of this basic block. Each node also
// stores the list of its successors in the graph, as a linked list of Edge
// objects.
// --------------------------------------------------------------------------
/**
* <tt>true</tt> if the maximum stack size and number of local variables
* must be automatically computed.
*/
private final boolean computeMaxs;
/**
* The (relative) stack size after the last visited instruction. This size
* is relative to the beginning of the current basic block, i.e., the true
* stack size after the last visited instruction is equal to the {@link
* Label#beginStackSize beginStackSize} of the current basic block plus
* <tt>stackSize</tt>.
*/
private int stackSize;
/**
* The (relative) maximum stack size after the last visited instruction.
* This size is relative to the beginning of the current basic block, i.e.,
* the true maximum stack size after the last visited instruction is equal
* to the {@link Label#beginStackSize beginStackSize} of the current basic
* block plus
* <tt>stackSize</tt>.
*/
private int maxStackSize;
/**
* The current basic block. This block is the basic block to which the next
* instruction to be visited must be added.
*/
private Label currentBlock;
/**
* The basic block stack used by the control flow analysis algorithm. This
* stack is represented by a linked list of {@link Label Label} objects,
* linked to each other by their {@link Label#next} field. This stack must
* not be confused with the JVM stack used to execute the JVM instructions!
*/
private Label blockStack;
/**
* The stack size variation corresponding to each JVM instruction. This
* stack variation is equal to the size of the values produced by an
* instruction, minus the size of the values consumed by this instruction.
*/
private final static int[] SIZE;
// --------------------------------------------------------------------------
// Fields to optimize the creation of {@link Edge Edge} objects by using a
// pool of reusable objects. The (shared) pool is a linked list of Edge
// objects, linked to each other by their {@link Edge#poolNext} field. Each
// time a CodeWriter needs to allocate an Edge, it removes the first Edge
// of the pool and adds it to a private list of Edge objects. After the end
// of the control flow analysis algorithm, the Edge objects in the private
// list of the CodeWriter are added back to the pool (by appending this
// private list to the pool list; in order to do this in constant time, both
// head and tail of the private list are stored in this CodeWriter).
// --------------------------------------------------------------------------
/**
* The head of the list of {@link Edge Edge} objects used by this {@link
* CodeWriter CodeWriter}. These objects, linked to each other by their
* {@link Edge#poolNext} field, are added back to the shared pool at the end
* of the control flow analysis algorithm.
*/
private Edge head;
/**
* The tail of the list of {@link Edge Edge} objects used by this {@link
* CodeWriter CodeWriter}. These objects, linked to each other by their
* {@link Edge#poolNext} field, are added back to the shared pool at the end
* of the control flow analysis algorithm.
*/
private Edge tail;
/**
* The shared pool of {@link Edge Edge} objects. This pool is a linked list
* of Edge objects, linked to each other by their {@link Edge#poolNext}
* field.
*/
private static Edge pool;
// --------------------------------------------------------------------------
// Static initializer
// --------------------------------------------------------------------------
/**
* Computes the stack size variation corresponding to each JVM instruction.
*/
static {
int i;
int[] b = new int[202];
String s
= "EFFFFFFFFGGFFFGGFFFEEFGFGFEEEEEEEEEEEEEEEEEEEEDEDEDDDDDCDCDEEEEEEEEE"
+ "EEEEEEEEEEEBABABBBBDCFFFGGGEDCDCDCDCDCDCDCDCDCDCEEEEDDDDDDDCDCDCEFEF"
+ "DDEEFFDEDEEEBDDBBDDDDDDCCCCCCCCEFEDDDCDCDEEEEEEEEEEFEEEEEEDDEEDDEE";
for (i = 0; i < b.length; ++i) {
b[i] = s.charAt(i) - 'E';
}
SIZE = b;
/* code to generate the above string
int NA = 0; // not applicable (unused opcode or variable size opcode)
b = new int[] {
0, //NOP, // visitInsn
1, //ACONST_NULL, // -
1, //ICONST_M1, // -
1, //ICONST_0, // -
1, //ICONST_1, // -
1, //ICONST_2, // -
1, //ICONST_3, // -
1, //ICONST_4, // -
1, //ICONST_5, // -
2, //LCONST_0, // -
2, //LCONST_1, // -
1, //FCONST_0, // -
1, //FCONST_1, // -
1, //FCONST_2, // -
2, //DCONST_0, // -
2, //DCONST_1, // -
1, //BIPUSH, // visitIntInsn
1, //SIPUSH, // -
1, //LDC, // visitLdcInsn
NA, //LDC_W, // -
NA, //LDC2_W, // -
1, //ILOAD, // visitVarInsn
2, //LLOAD, // -
1, //FLOAD, // -
2, //DLOAD, // -
1, //ALOAD, // -
NA, //ILOAD_0, // -
NA, //ILOAD_1, // -
NA, //ILOAD_2, // -
NA, //ILOAD_3, // -
NA, //LLOAD_0, // -
NA, //LLOAD_1, // -
NA, //LLOAD_2, // -
NA, //LLOAD_3, // -
NA, //FLOAD_0, // -
NA, //FLOAD_1, // -
NA, //FLOAD_2, // -
NA, //FLOAD_3, // -
NA, //DLOAD_0, // -
NA, //DLOAD_1, // -
NA, //DLOAD_2, // -
NA, //DLOAD_3, // -
NA, //ALOAD_0, // -
NA, //ALOAD_1, // -
NA, //ALOAD_2, // -
NA, //ALOAD_3, // -
-1, //IALOAD, // visitInsn
0, //LALOAD, // -
-1, //FALOAD, // -
0, //DALOAD, // -
-1, //AALOAD, // -
-1, //BALOAD, // -
-1, //CALOAD, // -
-1, //SALOAD, // -
-1, //ISTORE, // visitVarInsn
-2, //LSTORE, // -
-1, //FSTORE, // -
-2, //DSTORE, // -
-1, //ASTORE, // -
NA, //ISTORE_0, // -
NA, //ISTORE_1, // -
NA, //ISTORE_2, // -
NA, //ISTORE_3, // -
NA, //LSTORE_0, // -
NA, //LSTORE_1, // -
NA, //LSTORE_2, // -
NA, //LSTORE_3, // -
NA, //FSTORE_0, // -
NA, //FSTORE_1, // -
NA, //FSTORE_2, // -
NA, //FSTORE_3, // -
NA, //DSTORE_0, // -
NA, //DSTORE_1, // -
NA, //DSTORE_2, // -
NA, //DSTORE_3, // -
NA, //ASTORE_0, // -
NA, //ASTORE_1, // -
NA, //ASTORE_2, // -
NA, //ASTORE_3, // -
-3, //IASTORE, // visitInsn
-4, //LASTORE, // -
-3, //FASTORE, // -
-4, //DASTORE, // -
-3, //AASTORE, // -
-3, //BASTORE, // -
-3, //CASTORE, // -
-3, //SASTORE, // -
-1, //POP, // -
-2, //POP2, // -
1, //DUP, // -
1, //DUP_X1, // -
1, //DUP_X2, // -
2, //DUP2, // -
2, //DUP2_X1, // -
2, //DUP2_X2, // -
0, //SWAP, // -
-1, //IADD, // -
-2, //LADD, // -
-1, //FADD, // -
-2, //DADD, // -
-1, //ISUB, // -
-2, //LSUB, // -
-1, //FSUB, // -
-2, //DSUB, // -
-1, //IMUL, // -
-2, //LMUL, // -
-1, //FMUL, // -
-2, //DMUL, // -
-1, //IDIV, // -
-2, //LDIV, // -
-1, //FDIV, // -
-2, //DDIV, // -
-1, //IREM, // -
-2, //LREM, // -
-1, //FREM, // -
-2, //DREM, // -
0, //INEG, // -
0, //LNEG, // -
0, //FNEG, // -
0, //DNEG, // -
-1, //ISHL, // -
-1, //LSHL, // -
-1, //ISHR, // -
-1, //LSHR, // -
-1, //IUSHR, // -
-1, //LUSHR, // -
-1, //IAND, // -
-2, //LAND, // -
-1, //IOR, // -
-2, //LOR, // -
-1, //IXOR, // -
-2, //LXOR, // -
0, //IINC, // visitIincInsn
1, //I2L, // visitInsn
0, //I2F, // -
1, //I2D, // -
-1, //L2I, // -
-1, //L2F, // -
0, //L2D, // -
0, //F2I, // -
1, //F2L, // -
1, //F2D, // -
-1, //D2I, // -
0, //D2L, // -
-1, //D2F, // -
0, //I2B, // -
0, //I2C, // -
0, //I2S, // -
-3, //LCMP, // -
-1, //FCMPL, // -
-1, //FCMPG, // -
-3, //DCMPL, // -
-3, //DCMPG, // -
-1, //IFEQ, // visitJumpInsn
-1, //IFNE, // -
-1, //IFLT, // -
-1, //IFGE, // -
-1, //IFGT, // -
-1, //IFLE, // -
-2, //IF_ICMPEQ, // -
-2, //IF_ICMPNE, // -
-2, //IF_ICMPLT, // -
-2, //IF_ICMPGE, // -
-2, //IF_ICMPGT, // -
-2, //IF_ICMPLE, // -
-2, //IF_ACMPEQ, // -
-2, //IF_ACMPNE, // -
0, //GOTO, // -
1, //JSR, // -
0, //RET, // visitVarInsn
-1, //TABLESWITCH, // visiTableSwitchInsn
-1, //LOOKUPSWITCH, // visitLookupSwitch
-1, //IRETURN, // visitInsn
-2, //LRETURN, // -
-1, //FRETURN, // -
-2, //DRETURN, // -
-1, //ARETURN, // -
0, //RETURN, // -
NA, //GETSTATIC, // visitFieldInsn
NA, //PUTSTATIC, // -
NA, //GETFIELD, // -
NA, //PUTFIELD, // -
NA, //INVOKEVIRTUAL, // visitMethodInsn
NA, //INVOKESPECIAL, // -
NA, //INVOKESTATIC, // -
NA, //INVOKEINTERFACE, // -
NA, //UNUSED, // NOT VISITED
1, //NEW, // visitTypeInsn
0, //NEWARRAY, // visitIntInsn
0, //ANEWARRAY, // visitTypeInsn
0, //ARRAYLENGTH, // visitInsn
NA, //ATHROW, // -
0, //CHECKCAST, // visitTypeInsn
0, //INSTANCEOF, // -
-1, //MONITORENTER, // visitInsn
-1, //MONITOREXIT, // -
NA, //WIDE, // NOT VISITED
NA, //MULTIANEWARRAY, // visitMultiANewArrayInsn
-1, //IFNULL, // visitJumpInsn
-1, //IFNONNULL, // -
NA, //GOTO_W, // -
NA, //JSR_W, // -
};
for (i = 0; i < b.length; ++i) {
System.err.print((char)('E' + b[i]));
}
System.err.println();
*/
}
// --------------------------------------------------------------------------
// Constructor
// --------------------------------------------------------------------------
/**
* Constructs a CodeWriter.
*
* @param cw the class writer in which the method must be added.
* @param computeMaxs <tt>true</tt> if the maximum stack size and number of
* local variables must be automatically computed.
*/
protected CodeWriter(final ClassWriter cw, final boolean computeMaxs) {
if (cw.firstMethod == null) {
cw.firstMethod = this;
cw.lastMethod = this;
} else {
cw.lastMethod.next = this;
cw.lastMethod = this;
}
this.cw = cw;
this.computeMaxs = computeMaxs;
if (computeMaxs) {
// pushes the first block onto the stack of blocks to be visited
currentBlock = new Label();
currentBlock.pushed = true;
blockStack = currentBlock;
}
}
/**
* Initializes this CodeWriter to define the bytecode of the specified
* method.
*
* @param access the method's access flags (see {@link Constants}).
* @param name the method's name.
* @param desc the method's descriptor (see {@link Type Type}).
* @param exceptions the internal names of the method's exceptions. May be
* <tt>null</tt>.
*/
protected void init(
final int access,
final String name,
final String desc,
final String[] exceptions) {
this.access = access;
this.name = cw.newUTF8(name);
this.desc = cw.newUTF8(desc);
if (exceptions != null && exceptions.length > 0) {
exceptionCount = exceptions.length;
this.exceptions = new int[exceptionCount];
for (int i = 0; i < exceptionCount; ++i) {
this.exceptions[i] = cw.newClass(exceptions[i]).index;
}
}
if (computeMaxs) {
// updates maxLocals
int size = getArgumentsAndReturnSizes(desc) >> 2;
if ((access & Constants.ACC_STATIC) != 0) {
--size;
}
if (size > maxLocals) {
maxLocals = size;
}
}
}
// --------------------------------------------------------------------------
// Implementation of the CodeVisitor interface
// --------------------------------------------------------------------------
@Override
public void visitInsn(final int opcode) {
if (computeMaxs) {
// updates current and max stack sizes
int size = stackSize + SIZE[opcode];
if (size > maxStackSize) {
maxStackSize = size;
}
stackSize = size;
// if opcode == ATHROW or xRETURN, ends current block (no successor)
if ((opcode >= Constants.IRETURN && opcode <= Constants.RETURN)
|| opcode == Constants.ATHROW) {
if (currentBlock != null) {
currentBlock.maxStackSize = maxStackSize;
currentBlock = null;
}
}
}
// adds the instruction to the bytecode of the method
code.put1(opcode);
}
@Override
public void visitIntInsn(final int opcode, final int operand) {
if (computeMaxs && opcode != Constants.NEWARRAY) {
// updates current and max stack sizes only if opcode == NEWARRAY
// (stack size variation = 0 for BIPUSH or SIPUSH)
int size = stackSize + 1;
if (size > maxStackSize) {
maxStackSize = size;
}
stackSize = size;
}
// adds the instruction to the bytecode of the method
if (opcode == Constants.SIPUSH) {
code.put12(opcode, operand);
} else { // BIPUSH or NEWARRAY
code.put11(opcode, operand);
}
}
@Override
public void visitVarInsn(final int opcode, final int var) {
if (computeMaxs) {
// updates current and max stack sizes
if (opcode == Constants.RET) {
// no stack change, but end of current block (no successor)
if (currentBlock != null) {
currentBlock.maxStackSize = maxStackSize;
currentBlock = null;
}
} else { // xLOAD or xSTORE
int size = stackSize + SIZE[opcode];
if (size > maxStackSize) {
maxStackSize = size;
}
stackSize = size;
}
// updates max locals
int n;
if (opcode == Constants.LLOAD || opcode == Constants.DLOAD
|| opcode == Constants.LSTORE || opcode == Constants.DSTORE) {
n = var + 2;
} else {
n = var + 1;
}
if (n > maxLocals) {
maxLocals = n;
}
}
// adds the instruction to the bytecode of the method
if (var < 4 && opcode != Constants.RET) {
int opt;
if (opcode < Constants.ISTORE) {
opt = 26 /*ILOAD_0*/ + ((opcode - Constants.ILOAD) << 2) + var;
} else {
opt = 59 /*ISTORE_0*/ + ((opcode - Constants.ISTORE) << 2) + var;
}
code.put1(opt);
} else if (var >= 256) {
code.put1(196 /*WIDE*/).put12(opcode, var);
} else {
code.put11(opcode, var);
}
}
@Override
public void visitTypeInsn(final int opcode, final String desc) {
if (computeMaxs && opcode == Constants.NEW) {
// updates current and max stack sizes only if opcode == NEW
// (stack size variation = 0 for ANEWARRAY, CHECKCAST, INSTANCEOF)
int size = stackSize + 1;
if (size > maxStackSize) {
maxStackSize = size;
}
stackSize = size;
}
// adds the instruction to the bytecode of the method
code.put12(opcode, cw.newClass(desc).index);
}
@Override
public void visitFieldInsn(
final int opcode,
final String owner,
final String name,
final String desc) {
if (computeMaxs) {
int size;
// computes the stack size variation
char c = desc.charAt(0);
switch (opcode) {
case Constants.GETSTATIC:
size = stackSize + (c == 'D' || c == 'J' ? 2 : 1);
break;
case Constants.PUTSTATIC:
size = stackSize + (c == 'D' || c == 'J' ? -2 : -1);
break;
case Constants.GETFIELD:
size = stackSize + (c == 'D' || c == 'J' ? 1 : 0);
break;
//case Constants.PUTFIELD:
default:
size = stackSize + (c == 'D' || c == 'J' ? -3 : -2);
break;
}
// updates current and max stack sizes
if (size > maxStackSize) {
maxStackSize = size;
}
stackSize = size;
}
// adds the instruction to the bytecode of the method
code.put12(opcode, cw.newField(owner, name, desc).index);
}
@Override
public void visitMethodInsn(
final int opcode,
final String owner,
final String name,
final String desc) {
Item i;
if (opcode == Constants.INVOKEINTERFACE) {
i = cw.newItfMethod(owner, name, desc);
} else {
i = cw.newMethod(owner, name, desc);
}
int argSize = i.intVal;
if (computeMaxs) {
// computes the stack size variation. In order not to recompute several
// times this variation for the same Item, we use the intVal field of
// this item to store this variation, once it has been computed. More
// precisely this intVal field stores the sizes of the arguments and of
// the return value corresponding to desc.
if (argSize == 0) {
// the above sizes have not been computed yet, so we compute them...
argSize = getArgumentsAndReturnSizes(desc);
// ... and we save them in order not to recompute them in the future
i.intVal = argSize;
}
int size;
if (opcode == Constants.INVOKESTATIC) {
size = stackSize - (argSize >> 2) + (argSize & 0x03) + 1;
} else {
size = stackSize - (argSize >> 2) + (argSize & 0x03);
}
// updates current and max stack sizes
if (size > maxStackSize) {
maxStackSize = size;
}
stackSize = size;
}
// adds the instruction to the bytecode of the method
if (opcode == Constants.INVOKEINTERFACE) {
if (!computeMaxs) {
if (argSize == 0) {
argSize = getArgumentsAndReturnSizes(desc);
i.intVal = argSize;
}
}
code.put12(Constants.INVOKEINTERFACE, i.index).put11(argSize >> 2, 0);
} else {
code.put12(opcode, i.index);
}
}
@Override
public void visitJumpInsn(final int opcode, final Label label) {
if (CHECK) {
if (label.owner == null) {
label.owner = this;
} else if (label.owner != this) {
throw new IllegalArgumentException();
}
}
if (computeMaxs) {
switch (opcode) {
case Constants.GOTO:
// no stack change, but end of current block (with one new successor)
if (currentBlock != null) {
currentBlock.maxStackSize = maxStackSize;
addSuccessor(stackSize, label);
currentBlock = null;
}
break;
case Constants.JSR:
if (currentBlock != null) {
addSuccessor(stackSize + 1, label);
}
break;
default:
// updates current stack size (max stack size unchanged because stack
// size variation always negative in this case)
stackSize += SIZE[opcode];
if (currentBlock != null) {
addSuccessor(stackSize, label);
}
break;
}
}
// adds the instruction to the bytecode of the method
if (label.resolved && label.position - code.length < Short.MIN_VALUE) {
// case of a backward jump with an offset < -32768. In this case we
// automatically replace GOTO with GOTO_W, JSR with JSR_W and IFxxx <l>
// with IFNOTxxx <l'> GOTO_W <l>, where IFNOTxxx is the "opposite" opcode
// of IFxxx (i.e., IFNE for IFEQ) and where <l'> designates the
// instruction just after the GOTO_W.
switch (opcode) {
case Constants.GOTO:
code.put1(200); // GOTO_W
break;
case Constants.JSR:
code.put1(201); // JSR_W
break;
default:
code.put1(opcode <= 166 ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1);
code.put2(8); // jump offset
code.put1(200); // GOTO_W
break;
}
label.put(this, code, code.length - 1, true);
} else {
// case of a backward jump with an offset >= -32768, or of a forward jump
// with, of course, an unknown offset. In these cases we store the offset
// in 2 bytes (which will be increased in resizeInstructions, if needed).
code.put1(opcode);
label.put(this, code, code.length - 1, false);
}
}
@Override
public void visitLabel(final Label label) {
if (CHECK) {
if (label.owner == null) {
label.owner = this;
} else if (label.owner != this) {
throw new IllegalArgumentException();
}
}
if (computeMaxs) {
if (currentBlock != null) {
// ends current block (with one new successor)
currentBlock.maxStackSize = maxStackSize;
addSuccessor(stackSize, label);
}
// begins a new current block,
// resets the relative current and max stack sizes
currentBlock = label;
stackSize = 0;
maxStackSize = 0;
}
// resolves previous forward references to label, if any
resize |= label.resolve(this, code.length, code.data);
}
@Override
public void visitLdcInsn(final Object cst) {
Item i = cw.newCst(cst);
if (computeMaxs) {
int size;
// computes the stack size variation
if (i.type == ClassWriter.LONG || i.type == ClassWriter.DOUBLE) {
size = stackSize + 2;
} else {
size = stackSize + 1;
}
// updates current and max stack sizes
if (size > maxStackSize) {
maxStackSize = size;
}
stackSize = size;
}
// adds the instruction to the bytecode of the method
int index = i.index;
if (i.type == ClassWriter.LONG || i.type == ClassWriter.DOUBLE) {
code.put12(20 /*LDC2_W*/, index);
} else if (index >= 256) {
code.put12(19 /*LDC_W*/, index);
} else {
code.put11(Constants.LDC, index);
}
}
@Override
public void visitIincInsn(final int var, final int increment) {
if (computeMaxs) {
// updates max locals only (no stack change)
int n = var + 1;
if (n > maxLocals) {
maxLocals = n;
}
}
// adds the instruction to the bytecode of the method
if ((var > 255) || (increment > 127) || (increment < -128)) {
code.put1(196 /*WIDE*/).put12(Constants.IINC, var).put2(increment);
} else {
code.put1(Constants.IINC).put11(var, increment);
}
}
@Override
public void visitTableSwitchInsn(
final int min,
final int max,
final Label dflt,
final Label labels[]) {
if (computeMaxs) {
// updates current stack size (max stack size unchanged)
--stackSize;
// ends current block (with many new successors)
if (currentBlock != null) {
currentBlock.maxStackSize = maxStackSize;
addSuccessor(stackSize, dflt);
for (int i = 0; i < labels.length; ++i) {
addSuccessor(stackSize, labels[i]);
}
currentBlock = null;
}
}
// adds the instruction to the bytecode of the method
int source = code.length;
code.put1(Constants.TABLESWITCH);
while (code.length % 4 != 0) {
code.put1(0);
}
dflt.put(this, code, source, true);
code.put4(min).put4(max);
for (int i = 0; i < labels.length; ++i) {
labels[i].put(this, code, source, true);
}
}
@Override
public void visitLookupSwitchInsn(
final Label dflt,
final int keys[],
final Label labels[]) {
if (computeMaxs) {
// updates current stack size (max stack size unchanged)
--stackSize;
// ends current block (with many new successors)
if (currentBlock != null) {
currentBlock.maxStackSize = maxStackSize;
addSuccessor(stackSize, dflt);
for (int i = 0; i < labels.length; ++i) {
addSuccessor(stackSize, labels[i]);
}
currentBlock = null;
}
}
// adds the instruction to the bytecode of the method
int source = code.length;
code.put1(Constants.LOOKUPSWITCH);
while (code.length % 4 != 0) {
code.put1(0);
}
dflt.put(this, code, source, true);
code.put4(labels.length);
for (int i = 0; i < labels.length; ++i) {
code.put4(keys[i]);
labels[i].put(this, code, source, true);
}
}
@Override
public void visitMultiANewArrayInsn(final String desc, final int dims) {
if (computeMaxs) {
// updates current stack size (max stack size unchanged because stack
// size variation always negative or null)
stackSize += 1 - dims;
}
// adds the instruction to the bytecode of the method
Item classItem = cw.newClass(desc);
code.put12(Constants.MULTIANEWARRAY, classItem.index).put1(dims);
}
@Override
public void visitTryCatchBlock(
final Label start,
final Label end,
final Label handler,
final String type) {
if (CHECK) {
if (start.owner != this || end.owner != this || handler.owner != this) {
throw new IllegalArgumentException();
}
if (!start.resolved || !end.resolved || !handler.resolved) {
throw new IllegalArgumentException();
}
}
if (computeMaxs) {
// pushes handler block onto the stack of blocks to be visited
if (!handler.pushed) {
handler.beginStackSize = 1;
handler.pushed = true;
handler.next = blockStack;
blockStack = handler;
}
}
++catchCount;
if (catchTable == null) {
catchTable = new ByteVector();
}
catchTable.put2(start.position);
catchTable.put2(end.position);
catchTable.put2(handler.position);
catchTable.put2(type != null ? cw.newClass(type).index : 0);
}
@Override
public void visitMaxs(final int maxStack, final int maxLocals) {
if (computeMaxs) {
// true (non relative) max stack size
int max = 0;
// control flow analysis algorithm: while the block stack is not empty,
// pop a block from this stack, update the max stack size, compute
// the true (non relative) begin stack size of the successors of this
// block, and push these successors onto the stack (unless they have
// already been pushed onto the stack). Note: by hypothesis, the {@link
// Label#beginStackSize} of the blocks in the block stack are the true
// (non relative) beginning stack sizes of these blocks.
Label stack = blockStack;
while (stack != null) {
// pops a block from the stack
Label l = stack;
stack = stack.next;
// computes the true (non relative) max stack size of this block
int start = l.beginStackSize;
int blockMax = start + l.maxStackSize;
// updates the global max stack size
if (blockMax > max) {
max = blockMax;
}
// analyses the successors of the block
Edge b = l.successors;
while (b != null) {
l = b.successor;
// if this successor has not already been pushed onto the stack...
if (!l.pushed) {
// computes the true beginning stack size of this successor block
l.beginStackSize = start + b.stackSize;
// pushes this successor onto the stack
l.pushed = true;
l.next = stack;
stack = l;
}
b = b.next;
}
}
this.maxStack = max;
// releases all the Edge objects used by this CodeWriter
synchronized (SIZE) {
// appends the [head ... tail] list at the beginning of the pool list
if (tail != null) {
tail.poolNext = pool;
pool = head;
}
}
} else {
this.maxStack = maxStack;
this.maxLocals = maxLocals;
}
}
@Override
public void visitLocalVariable(
final String name,
final String desc,
final Label start,
final Label end,
final int index) {
if (CHECK) {
if (start.owner != this || !start.resolved) {
throw new IllegalArgumentException();
}
if (end.owner != this || !end.resolved) {
throw new IllegalArgumentException();
}
}
if (localVar == null) {
cw.newUTF8("LocalVariableTable");
localVar = new ByteVector();
}
++localVarCount;
localVar.put2(start.position);
localVar.put2(end.position - start.position);
localVar.put2(cw.newUTF8(name).index);
localVar.put2(cw.newUTF8(desc).index);
localVar.put2(index);
}
@Override
public void visitLineNumber(final int line, final Label start) {
if (CHECK) {
if (start.owner != this || !start.resolved) {
throw new IllegalArgumentException();
}
}
if (lineNumber == null) {
cw.newUTF8("LineNumberTable");
lineNumber = new ByteVector();
}
++lineNumberCount;
lineNumber.put2(start.position);
lineNumber.put2(line);
}
// --------------------------------------------------------------------------
// Utility methods: control flow analysis algorithm
// --------------------------------------------------------------------------
/**
* Computes the size of the arguments and of the return value of a method.
*
* @param desc the descriptor of a method.
* @return the size of the arguments of the method (plus one for the
* implicit this argument), argSize, and the size of its return value,
* retSize, packed into a single int i = <tt>(argSize << 2) | retSize</tt>
* (argSize is therefore equal to <tt>i >> 2</tt>, and retSize to
* <tt>i & 0x03</tt>).
*/
private static int getArgumentsAndReturnSizes(final String desc) {
int n = 1;
int c = 1;
while (true) {
char car = desc.charAt(c++);
switch (car) {
case ')':
car = desc.charAt(c);
return n << 2 | (car == 'V' ? 0 : (car == 'D' || car == 'J' ? 2 : 1));
case 'L':
while (desc.charAt(c++) != ';') {
}
n += 1;
break;
case '[':
while ((car = desc.charAt(c)) == '[') {
++c;
}
if (car == 'D' || car == 'J') {
n -= 1;
}
break;
case 'D':
case 'J':
n += 2;
break;
default:
n += 1;
break;
}
}
}
/**
* Adds a successor to the {@link #currentBlock currentBlock} block.
*
* @param stackSize the current (relative) stack size in the current block.
* @param successor the successor block to be added to the current block.
*/
private void addSuccessor(final int stackSize, final Label successor) {
Edge b;
// creates a new Edge object or reuses one from the shared pool
synchronized (SIZE) {
if (pool == null) {
b = new Edge();
} else {
b = pool;
// removes b from the pool
pool = pool.poolNext;
}
}
// adds the previous Edge to the list of Edges used by this CodeWriter
if (tail == null) {
tail = b;
}
b.poolNext = head;
head = b;
// initializes the previous Edge object...
b.stackSize = stackSize;
b.successor = successor;
// ...and adds it to the successor list of the currentBlock block
b.next = currentBlock.successors;
currentBlock.successors = b;
}
// --------------------------------------------------------------------------
// Utility methods: dump bytecode array
// --------------------------------------------------------------------------
/**
* Returns the size of the bytecode of this method.
*
* @return the size of the bytecode of this method.
*/
int getSize() {
if (resize) {
// replaces the temporary jump opcodes introduced by Label.resolve.
resizeInstructions(new int[0], new int[0], 0);
}
int size = 8;
if (code.length > 0) {
cw.newUTF8("Code");
size += 18 + code.length + 8 * catchCount;
if (localVar != null) {
size += 8 + localVar.length;
}
if (lineNumber != null) {
size += 8 + lineNumber.length;
}
}
if (exceptionCount > 0) {
cw.newUTF8("Exceptions");
size += 8 + 2 * exceptionCount;
}
if ((access & Constants.ACC_SYNTHETIC) != 0) {
cw.newUTF8("Synthetic");
size += 6;
}
if ((access & Constants.ACC_DEPRECATED) != 0) {
cw.newUTF8("Deprecated");
size += 6;
}
return size;
}
/**
* Puts the bytecode of this method in the given byte vector.
*
* @param out the byte vector into which the bytecode of this method must be
* copied.
*/
void put(final ByteVector out) {
out.put2(access).put2(name.index).put2(desc.index);
int attributeCount = 0;
if (code.length > 0) {
++attributeCount;
}
if (exceptionCount > 0) {
++attributeCount;
}
if ((access & Constants.ACC_SYNTHETIC) != 0) {
++attributeCount;
}
if ((access & Constants.ACC_DEPRECATED) != 0) {
++attributeCount;
}
out.put2(attributeCount);
if (code.length > 0) {
int size = 12 + code.length + 8 * catchCount;
if (localVar != null) {
size += 8 + localVar.length;
}
if (lineNumber != null) {
size += 8 + lineNumber.length;
}
out.put2(cw.newUTF8("Code").index).put4(size);
out.put2(maxStack).put2(maxLocals);
out.put4(code.length).putByteArray(code.data, 0, code.length);
out.put2(catchCount);
if (catchCount > 0) {
out.putByteArray(catchTable.data, 0, catchTable.length);
}
attributeCount = 0;
if (localVar != null) {
++attributeCount;
}
if (lineNumber != null) {
++attributeCount;
}
out.put2(attributeCount);
if (localVar != null) {
out.put2(cw.newUTF8("LocalVariableTable").index);
out.put4(localVar.length + 2).put2(localVarCount);
out.putByteArray(localVar.data, 0, localVar.length);
}
if (lineNumber != null) {
out.put2(cw.newUTF8("LineNumberTable").index);
out.put4(lineNumber.length + 2).put2(lineNumberCount);
out.putByteArray(lineNumber.data, 0, lineNumber.length);
}
}
if (exceptionCount > 0) {
out.put2(cw.newUTF8("Exceptions").index).put4(2 * exceptionCount + 2);
out.put2(exceptionCount);
for (int i = 0; i < exceptionCount; ++i) {
out.put2(exceptions[i]);
}
}
if ((access & Constants.ACC_SYNTHETIC) != 0) {
out.put2(cw.newUTF8("Synthetic").index).put4(0);
}
if ((access & Constants.ACC_DEPRECATED) != 0) {
out.put2(cw.newUTF8("Deprecated").index).put4(0);
}
}
// --------------------------------------------------------------------------
// Utility methods: instruction resizing (used to handle GOTO_W and JSR_W)
// --------------------------------------------------------------------------
/**
* Resizes the designated instructions, while keeping jump offsets and
* instruction addresses consistent. This may require to resize other
* existing instructions, or even to introduce new instructions: for
* example, increasing the size of an instruction by 2 at the middle of a
* method can increases the offset of an IFEQ instruction from 32766 to
* 32768, in which case IFEQ 32766 must be replaced with IFNEQ 8 GOTO_W
* 32765. This, in turn, may require to increase the size of another jump
* instruction, and so on... All these operations are handled automatically
* by this method.
* <p>
* <i>This method must be called after all the method that is being built
* has been visited</i>. In particular, the {@link Label Label} objects used
* to construct the method are no longer valid after this method has been
* called.
*
* @param indexes current positions of the instructions to be resized. Each
* instruction must be designated by the index of its <i>last</i> byte, plus
* one (or, in other words, by the index of the <i>first</i> byte of the
* <i>next</i> instruction).
* @param sizes the number of bytes to be <i>added</i> to the above
* instructions. More precisely, for each i < <tt>len</tt>,
* <tt>sizes</tt>[i] bytes will be added at the end of the instruction
* designated by <tt>indexes</tt>[i] or, if <tt>sizes</tt>[i] is negative,
* the <i>last</i> |<tt>sizes[i]</tt>| bytes of the instruction will be
* removed (the instruction size <i>must not</i> become negative or null).
* The gaps introduced by this method must be filled in "manually" in the
* array returned by the {@link #getCode getCode} method.
* @param len the number of instruction to be resized. Must be smaller than
* or equal to <tt>indexes</tt>.length and <tt>sizes</tt>.length.
* @return the <tt>indexes</tt> array, which now contains the new positions
* of the resized instructions (designated as above).
*/
protected int[] resizeInstructions(
final int[] indexes,
final int[] sizes,
final int len) {
byte[] b = code.data; // bytecode of the method
int u, v, label; // indexes in b
int i, j; // loop indexes
// 1st step:
// As explained above, resizing an instruction may require to resize another
// one, which may require to resize yet another one, and so on. The first
// step of the algorithm consists in finding all the instructions that
// need to be resized, without modifying the code. This is done by the
// following "fix point" algorithm:
// - parse the code to find the jump instructions whose offset will need
// more than 2 bytes to be stored (the future offset is computed from the
// current offset and from the number of bytes that will be inserted or
// removed between the source and target instructions). For each such
// instruction, adds an entry in (a copy of) the indexes and sizes arrays
// (if this has not already been done in a previous iteration!)
// - if at least one entry has been added during the previous step, go back
// to the beginning, otherwise stop.
// In fact the real algorithm is complicated by the fact that the size of
// TABLESWITCH and LOOKUPSWITCH instructions depends on their position in
// the bytecode (because of padding). In order to ensure the convergence of
// the algorithm, the number of bytes to be added or removed from these
// instructions is over estimated during the previous loop, and computed
// exactly only after the loop is finished (this requires another pass to
// parse the bytecode of the method).
int[] allIndexes = new int[len]; // copy of indexes
int[] allSizes = new int[len]; // copy of sizes
boolean[] resize; // instructions to be resized
int newOffset; // future offset of a jump instruction
System.arraycopy(indexes, 0, allIndexes, 0, len);
System.arraycopy(sizes, 0, allSizes, 0, len);
resize = new boolean[code.length];
int state = 3; // 3 = loop again, 2 = loop ended, 1 = last pass, 0 = done
do {
if (state == 3) {
state = 2;
}
u = 0;
while (u < b.length) {
int opcode = b[u] & 0xFF; // opcode of current instruction
int insert = 0; // bytes to be added after this instruction
switch (ClassWriter.TYPE[opcode]) {
case ClassWriter.NOARG_INSN:
case ClassWriter.IMPLVAR_INSN:
u += 1;
break;
case ClassWriter.LABEL_INSN:
if (opcode > 201) {
// converts temporary opcodes 202 to 217 (inclusive), 218 and 219
// to IFEQ ... JSR (inclusive), IFNULL and IFNONNULL
opcode = opcode < 218 ? opcode - 49 : opcode - 20;
label = u + readUnsignedShort(b, u + 1);
} else {
label = u + readShort(b, u + 1);
}
newOffset = getNewOffset(allIndexes, allSizes, u, label);
if (newOffset < Short.MIN_VALUE || newOffset > Short.MAX_VALUE) {
if (!resize[u]) {
if (opcode == Constants.GOTO || opcode == Constants.JSR) {
// two additional bytes will be required to replace this
// GOTO or JSR instruction with a GOTO_W or a JSR_W
insert = 2;
} else {
// five additional bytes will be required to replace this
// IFxxx <l> instruction with IFNOTxxx <l'> GOTO_W <l>, where
// IFNOTxxx is the "opposite" opcode of IFxxx (i.e., IFNE for
// IFEQ) and where <l'> designates the instruction just after
// the GOTO_W.
insert = 5;
}
resize[u] = true;
}
}
u += 3;
break;
case ClassWriter.LABELW_INSN:
u += 5;
break;
case ClassWriter.TABL_INSN:
if (state == 1) {
// true number of bytes to be added (or removed) from this
// instruction = (future number of padding bytes - current number
// of padding byte) - previously over estimated variation =
// = ((3 - newOffset%4) - (3 - u%4)) - u%4
// = (-newOffset%4 + u%4) - u%4
// = -(newOffset & 3)
newOffset = getNewOffset(allIndexes, allSizes, 0, u);
insert = -(newOffset & 3);
} else if (!resize[u]) {
// over estimation of the number of bytes to be added to this
// instruction = 3 - current number of padding bytes = 3 - (3 -
// u%4) = u%4 = u & 3
insert = u & 3;
resize[u] = true;
}
// skips instruction
u = u + 4 - (u & 3);
u += 4 * (readInt(b, u + 8) - readInt(b, u + 4) + 1) + 12;
break;
case ClassWriter.LOOK_INSN:
if (state == 1) {
// like TABL_INSN
newOffset = getNewOffset(allIndexes, allSizes, 0, u);
insert = -(newOffset & 3);
} else if (!resize[u]) {
// like TABL_INSN
insert = u & 3;
resize[u] = true;
}
// skips instruction
u = u + 4 - (u & 3);
u += 8 * readInt(b, u + 4) + 8;
break;
case ClassWriter.WIDE_INSN:
opcode = b[u + 1] & 0xFF;
if (opcode == Constants.IINC) {
u += 6;
} else {
u += 4;
}
break;
case ClassWriter.VAR_INSN:
case ClassWriter.SBYTE_INSN:
case ClassWriter.LDC_INSN:
u += 2;
break;
case ClassWriter.SHORT_INSN:
case ClassWriter.LDCW_INSN:
case ClassWriter.FIELDORMETH_INSN:
case ClassWriter.TYPE_INSN:
case ClassWriter.IINC_INSN:
u += 3;
break;
case ClassWriter.ITFMETH_INSN:
u += 5;
break;
// case ClassWriter.MANA_INSN:
default:
u += 4;
break;
}
if (insert != 0) {
// adds a new (u, insert) entry in the allIndexes and allSizes arrays
int[] newIndexes = new int[allIndexes.length + 1];
int[] newSizes = new int[allSizes.length + 1];
System.arraycopy(allIndexes, 0, newIndexes, 0, allIndexes.length);
System.arraycopy(allSizes, 0, newSizes, 0, allSizes.length);
newIndexes[allIndexes.length] = u;
newSizes[allSizes.length] = insert;
allIndexes = newIndexes;
allSizes = newSizes;
if (insert > 0) {
state = 3;
}
}
}
if (state < 3) {
--state;
}
} while (state != 0);
// 2nd step:
// copies the bytecode of the method into a new bytevector, updates the
// offsets, and inserts (or removes) bytes as requested.
ByteVector newCode = new ByteVector(code.length);
u = 0;
while (u < code.length) {
for (i = allIndexes.length - 1; i >= 0; --i) {
if (allIndexes[i] == u) {
if (i < len) {
if (sizes[i] > 0) {
newCode.putByteArray(null, 0, sizes[i]);
} else {
newCode.length += sizes[i];
}
indexes[i] = newCode.length;
}
}
}
int opcode = b[u] & 0xFF;
switch (ClassWriter.TYPE[opcode]) {
case ClassWriter.NOARG_INSN:
case ClassWriter.IMPLVAR_INSN:
newCode.put1(opcode);
u += 1;
break;
case ClassWriter.LABEL_INSN:
if (opcode > 201) {
// changes temporary opcodes 202 to 217 (inclusive), 218 and 219
// to IFEQ ... JSR (inclusive), IFNULL and IFNONNULL
opcode = opcode < 218 ? opcode - 49 : opcode - 20;
label = u + readUnsignedShort(b, u + 1);
} else {
label = u + readShort(b, u + 1);
}
newOffset = getNewOffset(allIndexes, allSizes, u, label);
if (newOffset < Short.MIN_VALUE || newOffset > Short.MAX_VALUE) {
// replaces GOTO with GOTO_W, JSR with JSR_W and IFxxx <l> with
// IFNOTxxx <l'> GOTO_W <l>, where IFNOTxxx is the "opposite" opcode
// of IFxxx (i.e., IFNE for IFEQ) and where <l'> designates the
// instruction just after the GOTO_W.
switch (opcode) {
case Constants.GOTO:
newCode.put1(200); // GOTO_W
break;
case Constants.JSR:
newCode.put1(201); // JSR_W
break;
default:
newCode.put1(opcode <= 166 ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1);
newCode.put2(8); // jump offset
newCode.put1(200); // GOTO_W
newOffset -= 3; // newOffset now computed from start of GOTO_W
break;
}
newCode.put4(newOffset);
} else {
newCode.put1(opcode);
newCode.put2(newOffset);
}
u += 3;
break;
case ClassWriter.LABELW_INSN:
label = u + readInt(b, u + 1);
newOffset = getNewOffset(allIndexes, allSizes, u, label);
newCode.put1(opcode);
newCode.put4(newOffset);
u += 5;
break;
case ClassWriter.TABL_INSN:
// skips 0 to 3 padding bytes
v = u;
u = u + 4 - (v & 3);
// reads and copies instruction
int source = newCode.length;
newCode.put1(Constants.TABLESWITCH);
while (newCode.length % 4 != 0) {
newCode.put1(0);
}
label = v + readInt(b, u);
u += 4;
newOffset = getNewOffset(allIndexes, allSizes, v, label);
newCode.put4(newOffset);
j = readInt(b, u);
u += 4;
newCode.put4(j);
j = readInt(b, u) - j + 1;
u += 4;
newCode.put4(readInt(b, u - 4));
for (; j > 0; --j) {
label = v + readInt(b, u);
u += 4;
newOffset = getNewOffset(allIndexes, allSizes, v, label);
newCode.put4(newOffset);
}
break;
case ClassWriter.LOOK_INSN:
// skips 0 to 3 padding bytes
v = u;
u = u + 4 - (v & 3);
// reads and copies instruction
source = newCode.length;
newCode.put1(Constants.LOOKUPSWITCH);
while (newCode.length % 4 != 0) {
newCode.put1(0);
}
label = v + readInt(b, u);
u += 4;
newOffset = getNewOffset(allIndexes, allSizes, v, label);
newCode.put4(newOffset);
j = readInt(b, u);
u += 4;
newCode.put4(j);
for (; j > 0; --j) {
newCode.put4(readInt(b, u));
u += 4;
label = v + readInt(b, u);
u += 4;
newOffset = getNewOffset(allIndexes, allSizes, v, label);
newCode.put4(newOffset);
}
break;
case ClassWriter.WIDE_INSN:
opcode = b[u + 1] & 0xFF;
if (opcode == Constants.IINC) {
newCode.putByteArray(b, u, 6);
u += 6;
} else {
newCode.putByteArray(b, u, 4);
u += 4;
}
break;
case ClassWriter.VAR_INSN:
case ClassWriter.SBYTE_INSN:
case ClassWriter.LDC_INSN:
newCode.putByteArray(b, u, 2);
u += 2;
break;
case ClassWriter.SHORT_INSN:
case ClassWriter.LDCW_INSN:
case ClassWriter.FIELDORMETH_INSN:
case ClassWriter.TYPE_INSN:
case ClassWriter.IINC_INSN:
newCode.putByteArray(b, u, 3);
u += 3;
break;
case ClassWriter.ITFMETH_INSN:
newCode.putByteArray(b, u, 5);
u += 5;
break;
// case MANA_INSN:
default:
newCode.putByteArray(b, u, 4);
u += 4;
break;
}
}
// updates the instructions addresses in the
// catch, local var and line number tables
if (catchTable != null) {
b = catchTable.data;
u = 0;
while (u < catchTable.length) {
writeShort(b, u, getNewOffset(
allIndexes, allSizes, 0, readUnsignedShort(b, u)));
writeShort(b, u + 2, getNewOffset(
allIndexes, allSizes, 0, readUnsignedShort(b, u + 2)));
writeShort(b, u + 4, getNewOffset(
allIndexes, allSizes, 0, readUnsignedShort(b, u + 4)));
u += 8;
}
}
if (localVar != null) {
b = localVar.data;
u = 0;
while (u < localVar.length) {
label = readUnsignedShort(b, u);
newOffset = getNewOffset(allIndexes, allSizes, 0, label);
writeShort(b, u, newOffset);
label += readUnsignedShort(b, u + 2);
newOffset = getNewOffset(allIndexes, allSizes, 0, label) - newOffset;
writeShort(b, u, newOffset);
u += 10;
}
}
if (lineNumber != null) {
b = lineNumber.data;
u = 0;
while (u < lineNumber.length) {
writeShort(b, u, getNewOffset(
allIndexes, allSizes, 0, readUnsignedShort(b, u)));
u += 4;
}
}
// replaces old bytecodes with new ones
code = newCode;
// returns the positions of the resized instructions
return indexes;
}
/**
* Reads an unsigned short value in the given byte array.
*
* @param b a byte array.
* @param index the start index of the value to be read.
* @return the read value.
*/
static int readUnsignedShort(final byte[] b, final int index) {
return ((b[index] & 0xFF) << 8) | (b[index + 1] & 0xFF);
}
/**
* Reads a signed short value in the given byte array.
*
* @param b a byte array.
* @param index the start index of the value to be read.
* @return the read value.
*/
static short readShort(final byte[] b, final int index) {
return (short) (((b[index] & 0xFF) << 8) | (b[index + 1] & 0xFF));
}
/**
* Reads a signed int value in the given byte array.
*
* @param b a byte array.
* @param index the start index of the value to be read.
* @return the read value.
*/
static int readInt(final byte[] b, final int index) {
return ((b[index] & 0xFF) << 24)
| ((b[index + 1] & 0xFF) << 16)
| ((b[index + 2] & 0xFF) << 8)
| (b[index + 3] & 0xFF);
}
/**
* Writes a short value in the given byte array.
*
* @param b a byte array.
* @param index where the first byte of the short value must be written.
* @param s the value to be written in the given byte array.
*/
static void writeShort(final byte[] b, final int index, final int s) {
b[index] = (byte) (s >>> 8);
b[index + 1] = (byte) s;
}
/**
* Computes the future value of a bytecode offset.
* <p>
* Note: it is possible to have several entries for the same instruction in
* the <tt>indexes</tt> and <tt>sizes</tt>: two entries (index=a,size=b) and
* (index=a,size=b') are equivalent to a single entry (index=a,size=b+b').
*
* @param indexes current positions of the instructions to be resized. Each
* instruction must be designated by the index of its <i>last</i> byte, plus
* one (or, in other words, by the index of the <i>first</i> byte of the
* <i>next</i> instruction).
* @param sizes the number of bytes to be <i>added</i> to the above
* instructions. More precisely, for each i < <tt>len</tt>,
* <tt>sizes</tt>[i] bytes will be added at the end of the instruction
* designated by <tt>indexes</tt>[i] or, if <tt>sizes</tt>[i] is negative,
* the <i>last</i> |<tt>sizes[i]</tt>| bytes of the instruction will be
* removed (the instruction size <i>must not</i> become negative or null).
* @param begin index of the first byte of the source instruction.
* @param end index of the first byte of the target instruction.
* @return the future value of the given bytecode offset.
*/
static int getNewOffset(
final int[] indexes,
final int[] sizes,
final int begin,
final int end) {
int offset = end - begin;
for (int i = 0; i < indexes.length; ++i) {
if (begin < indexes[i] && indexes[i] <= end) { // forward jump
offset += sizes[i];
} else if (end < indexes[i] && indexes[i] <= begin) { // backward jump
offset -= sizes[i];
}
}
return offset;
}
/**
* Returns the current size of the bytecode of this method. This size just
* includes the size of the bytecode instructions: it does not include the
* size of the Exceptions, LocalVariableTable, LineNumberTable, Synthetic
* and Deprecated attributes, if present.
*
* @return the current size of the bytecode of this method.
*/
protected int getCodeSize() {
return code.length;
}
/**
* Returns the current bytecode of this method. This bytecode only contains
* the instructions: it does not include the Exceptions, LocalVariableTable,
* LineNumberTable, Synthetic and Deprecated attributes, if present.
*
* @return the current bytecode of this method. The bytecode is contained
* between the index 0 (inclusive) and the index {@link #getCodeSize
* getCodeSize} (exclusive).
*/
protected byte[] getCode() {
return code.data;
}
}
| 68,566 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHClassManager.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHClassManager.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.Collections;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
/**
* BshClassManager manages all classloading in BeanShell. It also supports a
* dynamically loaded extension (bsh.classpath package) which allows classpath
* extension and class file reloading.
*
* Currently the extension relies on 1.2 for BshClassLoader and weak references.
* * See http://www.beanshell.org/manual/classloading.html for details on the
* bsh classloader architecture.
* <p>
*
* Bsh has a multi-tiered class loading architecture. No class loader is used
* unless/until the classpath is modified or a class is reloaded.
* <p>
*/
/*
Implementation notes:
Note: we may need some synchronization in here
Note on version dependency: This base class is JDK 1.1 compatible,
however we are forced to use weak references in the full featured
implementation (the optional bsh.classpath package) to accomodate all of
the fleeting namespace listeners as they fall out of scope. (NameSpaces
must be informed if the class space changes so that they can un-cache
names).
<p>
Perhaps a simpler idea would be to have entities that reference cached
types always perform a light weight check with a counter / reference
value and use that to detect changes in the namespace. This puts the
burden on the consumer to check at appropriate times, but could eliminate
the need for the listener system in many places and the necessity of weak
references in this package.
<p>
*/
public class BSHClassManager {
/**
* The interpreter which created the class manager This is used to load
* scripted classes from source files.
*/
private Interpreter declaringInterpreter;
/**
* An external classloader supplied by the setClassLoader() command.
*/
protected ClassLoader externalClassLoader;
/**
* Global cache for things we know are classes. Note: these should probably
* be re-implemented with Soft references. (as opposed to strong or Weak)
*/
protected transient Map<String, Class> absoluteClassCache = new Hashtable<String, Class>();
/**
* Global cache for things we know are *not* classes. Note: these should
* probably be re-implemented with Soft references. (as opposed to strong or
* Weak)
*/
protected transient Set<String> absoluteNonClasses = Collections.synchronizedSet(new HashSet<String>());
/**
* Caches for resolved object and static methods. We keep these maps
* separate to support fast lookup in the general case where the method may
* be either.
*/
protected transient volatile Map<SignatureKey, Method> resolvedObjectMethods = new Hashtable<SignatureKey, Method>();
protected transient volatile Map<SignatureKey, Method> resolvedStaticMethods = new Hashtable<SignatureKey, Method>();
private final transient Set<String> definingClasses = Collections.synchronizedSet(new HashSet<String>());
protected transient Map<String, String> definingClassesBaseNames = new Hashtable<String, String>();
private static final Map<BSHClassManager, Object> classManagers = Collections.synchronizedMap(new WeakHashMap<BSHClassManager, Object>());
static void clearResolveCache() {
BSHClassManager[] managers = classManagers.keySet().toArray(new BSHClassManager[0]);
for (BSHClassManager m : managers) {
m.resolvedObjectMethods = new Hashtable<>();
m.resolvedStaticMethods = new Hashtable<>();
}
}
/**
* Create a new instance of the class manager. Class manager instnaces are
* now associated with the interpreter.
*
* @see bsh.Interpreter.getClassManager()
* @see bsh.Interpreter.setClassLoader( ClassLoader )
*/
public static BSHClassManager createClassManager(Interpreter interpreter) {
BSHClassManager manager;
// Do we have the optional package?
manager = new BSHClassManager();
if (interpreter == null) {
interpreter = new Interpreter();
}
manager.declaringInterpreter = interpreter;
classManagers.put(manager, null);
return manager;
}
public boolean classExists(String name) {
return (classForName(name) != null);
}
/**
* Load the specified class by name, taking into account added classpath and
* reloaded classes, etc. Note: Again, this is just a trivial
* implementation. See bsh.classpath.ClassManagerImpl for the fully
* functional class management package.
*
* @return the class or null
*/
public Class classForName(String name) {
if (isClassBeingDefined(name)) {
throw new InterpreterError(
"Attempting to load class in the process of being defined: "
+ name);
}
Class clas = null;
try {
clas = plainClassForName(name);
} catch (ClassNotFoundException e) {
/*ignore*/ }
// try scripted class
if (clas == null && declaringInterpreter.getCompatibility()) {
clas = loadSourceClass(name);
}
return clas;
}
// Move me to classpath/ClassManagerImpl???
protected Class<?> loadSourceClass(final String name) {
final String fileName = '/' + name.replace('.', '/') + ".java";
final InputStream in = getResourceAsStream(fileName);
if (in == null) {
return null;
}
try {
Interpreter.debug("Loading class from source file: " + fileName);
declaringInterpreter.eval(new InputStreamReader(in));
} catch (EvalError e) {
if (Interpreter.DEBUG) {
}
}
try {
return plainClassForName(name);
} catch (final ClassNotFoundException e) {
Interpreter.debug("Class not found in source file: " + name);
return null;
}
}
/**
* Perform a plain Class.forName() or call the externally provided
* classloader. If a BshClassManager implementation is loaded the call will
* be delegated to it, to allow for additional hooks.
* <p/>
*
* This simply wraps that bottom level class lookup call and provides a
* central point for monitoring and handling certain Java version dependent
* bugs, etc.
*
* @see #classForName( String )
* @return the class
*/
public Class plainClassForName(String name)
throws ClassNotFoundException {
Class c = null;
if (externalClassLoader != null) {
c = externalClassLoader.loadClass(name);
} else {
c = Class.forName(name);
}
cacheClassInfo(name, c);
return c;
}
/**
* Get a resource URL using the BeanShell classpath
*
* @param path should be an absolute path
*/
public URL getResource(String path) {
URL url = null;
if (externalClassLoader != null) {
// classloader wants no leading slash
url = externalClassLoader.getResource(path.substring(1));
}
if (url == null) {
url = Interpreter.class.getResource(path);
}
return url;
}
/**
* Get a resource stream using the BeanShell classpath
*
* @param path should be an absolute path
*/
public InputStream getResourceAsStream(String path) {
InputStream in = null;
if (externalClassLoader != null) {
// classloader wants no leading slash
in = externalClassLoader.getResourceAsStream(path.substring(1));
}
if (in == null) {
in = Interpreter.class.getResourceAsStream(path);
}
return in;
}
/**
* Cache info about whether name is a class or not.
*
* @param value if value is non-null, cache the class if value is null, set
* the flag that it is *not* a class to speed later resolution
*/
public void cacheClassInfo(String name, Class value) {
if (value != null) {
absoluteClassCache.put(name, value);
} else {
absoluteNonClasses.add(name);
}
}
/**
* Cache a resolved (possibly overloaded) method based on the argument types
* used to invoke it, subject to classloader change. Static and Object
* methods are cached separately to support fast lookup in the general case
* where either will do.
*/
public void cacheResolvedMethod(
Class clas, Class[] types, Method method) {
if (Interpreter.DEBUG) {
Interpreter.debug(
"cacheResolvedMethod putting: " + clas + " " + method);
}
SignatureKey sk = new SignatureKey(clas, method.getName(), types);
if (Modifier.isStatic(method.getModifiers())) {
resolvedStaticMethods.put(sk, method);
} else {
resolvedObjectMethods.put(sk, method);
}
}
/**
* Return a previously cached resolved method.
*
* @param onlyStatic specifies that only a static method may be returned.
* @return the Method or null
*/
protected Method getResolvedMethod(
Class clas, String methodName, Class[] types, boolean onlyStatic) {
SignatureKey sk = new SignatureKey(clas, methodName, types);
// Try static and then object, if allowed
// Note that the Java compiler should not allow both.
Method method = resolvedStaticMethods.get(sk);
if (method == null && !onlyStatic) {
method = resolvedObjectMethods.get(sk);
}
if (Interpreter.DEBUG) {
if (method == null) {
Interpreter.debug(
"getResolvedMethod cache MISS: " + clas + " - " + methodName);
} else {
Interpreter.debug(
"getResolvedMethod cache HIT: " + clas + " - " + method);
}
}
return method;
}
/**
* Clear the caches in BshClassManager
*
* @see public void #reset() for external usage
*/
protected void clearCaches() {
absoluteNonClasses = Collections.synchronizedSet(new HashSet<>());
absoluteClassCache = new Hashtable<>();
resolvedObjectMethods = new Hashtable<>();
resolvedStaticMethods = new Hashtable<>();
}
/**
* Set an external class loader. BeanShell will use this at the same point
* it would otherwise use the plain Class.forName(). i.e. if no explicit
* classpath management is done from the script (addClassPath(),
* setClassPath(), reloadClasses()) then BeanShell will only use the
* supplied classloader. If additional classpath management is done then
* BeanShell will perform that in addition to the supplied external
* classloader. However BeanShell is not currently able to reload classes
* supplied through the external classloader.
*/
public void setClassLoader(ClassLoader externalCL) {
externalClassLoader = externalCL;
classLoaderChanged();
}
public void addClassPath(URL path)
throws IOException {
}
/**
* Clear all loaders and start over. No class loading.
*/
public void reset() {
clearCaches();
}
/**
* Set a new base classpath and create a new base classloader. This means
* all types change.
*/
public void setClassPath(URL[] cp)
throws UtilEvalError {
throw cmUnavailable();
}
/**
* Overlay the entire path with a new class loader. Set the base path to the
* user path + base path.
*
* No point in including the boot class path (can't reload thos).
*/
public void reloadAllClasses() throws UtilEvalError {
throw cmUnavailable();
}
/**
* Reloading classes means creating a new classloader and using it whenever
* we are asked for classes in the appropriate space. For this we use a
* DiscreteFilesClassLoader
*/
public void reloadClasses(String[] classNames)
throws UtilEvalError {
throw cmUnavailable();
}
/**
* Reload all classes in the specified package: e.g. "com.sun.tools"
*
* The special package name "<unpackaged>" can be used to refer to
* unpackaged classes.
*/
public void reloadPackage(String pack)
throws UtilEvalError {
throw cmUnavailable();
}
/**
* This has been removed from the interface to shield the core from the rest
* of the classpath package. If you need the classpath you will have to cast
* the classmanager to its impl.
*
* public BshClassPath getClassPath() throws ClassPathException;
*/
/**
* Support for "import *;" Hide details in here as opposed to NameSpace.
*/
protected void doSuperImport()
throws UtilEvalError {
throw cmUnavailable();
}
/**
* A "super import" ("import *") operation has been performed.
*/
protected boolean hasSuperImport() {
return false;
}
/**
* Return the name or null if none is found, Throw an ClassPathException
* containing detail if name is ambigous.
*/
protected String getClassNameByUnqName(String name)
throws UtilEvalError {
throw cmUnavailable();
}
public void addListener(Listener l) {
}
public void removeListener(Listener l) {
}
public void dump(PrintWriter pw) {
pw.println("BshClassManager: no class manager.");
}
/**
* Flag the class name as being in the process of being defined. The class
* manager will not attempt to load it.
*/
/*
Note: this implementation is temporary. We currently keep a flat
namespace of the base name of classes. i.e. BeanShell cannot be in the
process of defining two classes in different packages with the same
base name. To remove this limitation requires that we work through
namespace imports in an analogous (or using the same path) as regular
class import resolution. This workaround should handle most cases
so we'll try it for now.
*/
protected void definingClass(String className) {
String baseName = Name.suffix(className, 1);
int i = baseName.indexOf('$');
if (i != -1) {
baseName = baseName.substring(i + 1);
}
String cur = definingClassesBaseNames.get(baseName);
if (cur != null) {
throw new InterpreterError("Defining class problem: " + className
+ ": BeanShell cannot yet simultaneously define two or more "
+ "dependant classes of the same name. Attempt to define: "
+ className + " while defining: " + cur
);
}
definingClasses.add(className);
definingClassesBaseNames.put(baseName, className);
}
protected boolean isClassBeingDefined(String className) {
return definingClasses.contains(className);
}
/**
* This method is a temporary workaround used with definingClass. It is to
* be removed at some point.
*/
protected String getClassBeingDefined(String className) {
String baseName = Name.suffix(className, 1);
return definingClassesBaseNames.get(baseName);
}
/**
* Indicate that the specified class name has been defined and may be loaded
* normally.
*/
protected void doneDefiningClass(String className) {
String baseName = Name.suffix(className, 1);
definingClasses.remove(className);
definingClassesBaseNames.remove(baseName);
}
/*
The real implementation in the classpath.ClassManagerImpl handles
reloading of the generated classes.
*/
public Class defineClass(String name, byte[] code) {
throw new InterpreterError("Can't create class (" + name
+ ") without class manager package.");
/*
Old implementation injected classes into the parent classloader.
This was incorrect behavior for several reasons. The biggest problem
is that classes could therefore only be defined once across all
executions of the script...
ClassLoader cl = this.getClass().getClassLoader();
Class clas;
try {
clas = (Class)Reflect.invokeObjectMethod(
cl, "defineClass",
new Object [] {
name, code,
new Primitive( (int)0 )/offset/,
new Primitive( code.length )/len/
},
(Interpreter)null, (CallStack)null, (SimpleNode)null
);
} catch ( Exception e ) {
e.printStackTrace();
throw new InterpreterError("Unable to define class: "+ e );
}
absoluteNonClasses.remove( name ); // may have been axed previously
return clas;
*/
}
protected void classLoaderChanged() {
}
protected static UtilEvalError cmUnavailable() {
return new Capabilities.Unavailable(
"ClassLoading features unavailable.");
}
public static interface Listener {
public void classLoaderChanged();
}
/**
* SignatureKey serves as a hash of a method signature on a class for fast
* lookup of overloaded and general resolved Java methods.
* <p>
*/
/*
Note: is using SignatureKey in this way dangerous? In the pathological
case a user could eat up memory caching every possible combination of
argument types to an untyped method. Maybe we could be smarter about
it by ignoring the types of untyped parameter positions? The method
resolver could return a set of "hints" for the signature key caching?
There is also the overhead of creating one of these for every method
dispatched. What is the alternative?
*/
static class SignatureKey {
Class clas;
Class[] types;
String methodName;
int hashCode = 0;
SignatureKey(Class clas, String methodName, Class[] types) {
this.clas = clas;
this.methodName = methodName;
this.types = types;
}
@Override
public int hashCode() {
if (hashCode == 0) {
hashCode = clas.hashCode() * methodName.hashCode();
if (types == null) // no args method
{
return hashCode;
}
for (int i = 0; i < types.length; i++) {
int hc = types[i] == null ? 21 : types[i].hashCode();
hashCode = hashCode * (i + 1) + hc;
}
}
return hashCode;
}
@Override
public boolean equals(Object o) {
SignatureKey target = (SignatureKey) o;
if (types == null) {
return target.types == null;
}
if (clas != target.clas) {
return false;
}
if (!methodName.equals(target.methodName)) {
return false;
}
if (types.length != target.types.length) {
return false;
}
for (int i = 0; i < types.length; i++) {
if (types[i] == null) {
if (!(target.types[i] == null)) {
return false;
}
} else if (!types[i].equals(target.types[i])) {
return false;
}
}
return true;
}
}
}
| 22,372 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHSwitchLabel.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHSwitchLabel.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
class BSHSwitchLabel extends SimpleNode {
boolean isDefault;
public BSHSwitchLabel(int id) {
super(id);
}
@Override
public Object eval(
CallStack callstack, Interpreter interpreter) throws EvalError {
if (isDefault) {
return null; // should probably error
}
SimpleNode label = ((SimpleNode) jjtGetChild(0));
return label.eval(callstack, interpreter);
}
}
| 2,998 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
BSHSwitchStatement.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/bsh/BSHSwitchStatement.java | /** ***************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
**************************************************************************** */
package ehacks.bsh;
class BSHSwitchStatement
extends SimpleNode
implements ParserConstants {
public BSHSwitchStatement(int id) {
super(id);
}
@Override
public Object eval(CallStack callstack, Interpreter interpreter)
throws EvalError {
int numchild = jjtGetNumChildren();
int child = 0;
SimpleNode switchExp = ((SimpleNode) jjtGetChild(child++));
Object switchVal = switchExp.eval(callstack, interpreter);
/*
Note: this could be made clearer by adding an inner class for the
cases and an object context for the child traversal.
*/
// first label
BSHSwitchLabel label;
Object node;
ReturnControl returnControl = null;
// get the first label
if (child >= numchild) {
throw new EvalError("Empty switch statement.", this, callstack);
}
label = ((BSHSwitchLabel) jjtGetChild(child++));
// while more labels or blocks and haven't hit return control
while (child < numchild && returnControl == null) {
// if label is default or equals switchVal
if (label.isDefault
|| primitiveEquals(
switchVal, label.eval(callstack, interpreter),
callstack, switchExp)) {
// execute nodes, skipping labels, until a break or return
while (child < numchild) {
node = jjtGetChild(child++);
if (node instanceof BSHSwitchLabel) {
continue;
}
// eval it
Object value
= ((SimpleNode) node).eval(callstack, interpreter);
// should check to disallow continue here?
if (value instanceof ReturnControl) {
returnControl = (ReturnControl) value;
break;
}
}
} else {
// skip nodes until next label
while (child < numchild) {
node = jjtGetChild(child++);
if (node instanceof BSHSwitchLabel) {
label = (BSHSwitchLabel) node;
break;
}
}
}
}
if (returnControl != null && returnControl.kind == RETURN) {
return returnControl;
} else {
return Primitive.VOID;
}
}
/**
* Helper method for testing equals on two primitive or boxable objects.
* yuck: factor this out into Primitive.java
*/
private boolean primitiveEquals(
Object switchVal, Object targetVal,
CallStack callstack, SimpleNode switchExp)
throws EvalError {
if (switchVal instanceof Primitive || targetVal instanceof Primitive) {
try {
// binaryOperation can return Primitive or wrapper type
Object result = Primitive.binaryOperation(
switchVal, targetVal, ParserConstants.EQ);
result = Primitive.unwrap(result);
return result.equals(Boolean.TRUE);
} catch (UtilEvalError e) {
throw e.toEvalError(
"Switch value: " + switchExp.getText() + ": ",
this, callstack);
}
} else {
return switchVal.equals(targetVal);
}
}
}
| 6,108 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
Debug.java | /FileExtraction/Java_unseen/radioegor146_ehacks-pro/src/main/java/ehacks/debugme/Debug.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ehacks.debugme;
import cpw.mods.fml.common.network.ByteBufUtils;
import cpw.mods.fml.common.network.handshake.NetworkDispatcher;
import cpw.mods.fml.common.network.internal.FMLProxyPacket;
import cpw.mods.fml.relauncher.ReflectionHelper;
import ehacks.mod.util.InteropUtils;
import ehacks.mod.util.Mappings;
import ehacks.mod.util.Random;
import ehacks.mod.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.block.material.MaterialTransparent;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.multiplayer.ChunkProviderClient;
import net.minecraft.entity.Entity;
import net.minecraft.entity.effect.EntityLightningBolt;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.JsonToNBT;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.play.client.C14PacketTabComplete;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityChest;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.IChunkProvider;
/**
*
* @author radioegor146
*/
public class Debug {
public static Random random = new Random();
public static int[] getMop() {
MovingObjectPosition preMop = Wrapper.INSTANCE.mc().objectMouseOver;
Entity ent = Wrapper.INSTANCE.mc().pointedEntity;
int[] arrn = new int[5];
arrn[0] = preMop.blockX;
arrn[1] = preMop.blockY;
arrn[2] = preMop.blockZ;
arrn[3] = preMop.sideHit;
arrn[4] = ent != null ? ent.getEntityId() : 0;
int[] mop = arrn;
return mop;
}
public static int[] getMyCoords() {
return getCoords(getPlayer());
}
public static int[] getCoords(Entity entity) {
int[] coords = new int[]{(int) Math.floor(entity.posX), (int) Math.floor(entity.posY) - 2, (int) Math.floor(entity.posZ)};
return coords;
}
public static int[] getCoords(TileEntity tileEntity) {
int[] coords = new int[]{tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord};
return coords;
}
public static EntityPlayer getPlayer(String nick) {
return getWorld().getPlayerEntityByName(nick);
}
public static EntityPlayer getPlayer() {
return Wrapper.INSTANCE.player();
}
public static String getUUID(Entity entity) {
return entity.getUniqueID().toString();
}
public static void log(String data) {
InteropUtils.log(data, "DebugMe");
}
public static int getEntityId(Entity entity) {
return entity.getEntityId();
}
public static int getMyEntityId() {
return getEntityId(getPlayer());
}
public static World getWorld() {
return Wrapper.INSTANCE.world();
}
public static int getDimensionId() {
return getWorld().provider.dimensionId;
}
public static NBTTagCompound jsonToNBT(String json) {
NBTBase nbtTag = null;
try {
nbtTag = JsonToNBT.func_150315_a(json.replaceAll("'", "\""));
} catch (Exception err) {
return null;
}
return (NBTTagCompound) nbtTag;
}
public static String NBTToJson(NBTTagCompound nbt) {
return nbt.toString().replaceAll("\\s+", "").replaceAll("\"", "'").replaceAll(",}", "}").replaceAll(",]", "]");
}
public static ItemStack getItem() {
return getItem(null);
}
public static ItemStack getItem(NBTTagCompound tag) {
return getItem(getPlayer().getCurrentEquippedItem(), tag);
}
public static ItemStack getItem(ItemStack toItem, NBTTagCompound tag) {
if (toItem != null && tag != null) {
toItem.setTagCompound(tag);
}
return toItem;
}
public static TileEntity getTileEntity() {
return getTileEntity(null);
}
public static TileEntity getTileEntity(NBTTagCompound tag) {
int[] mop = getMop();
return getTileEntity(getTileEntity(mop[0], mop[1], mop[2]), tag);
}
public static TileEntity getTileEntity(TileEntity toTile, NBTTagCompound tag) {
if (toTile != null && tag != null) {
toTile.readFromNBT(tag);
}
return toTile;
}
public static TileEntity getTileEntity(int x, int y, int z) {
return getWorld().getTileEntity(x, y, z);
}
public static Entity getEntity() {
return getEntity(null);
}
public static Entity getEntity(NBTTagCompound tag) {
int[] mop = getMop();
return getEntity(getEntity(mop[4]), tag);
}
public static Entity getEntity(Entity toEntity, NBTTagCompound tag) {
if (toEntity != null && tag != null) {
toEntity.readFromNBT(tag);
}
return toEntity;
}
public static Entity getEntity(int id) {
return getWorld().getEntityByID(id);
}
public static List<Entity> getNearEntities() {
return getWorld().loadedEntityList;
}
public static List<EntityPlayer> getNearPlayers() {
return getWorld().playerEntities;
}
public static String getLongString(int len) {
return getLongString(random.str(), len);
}
public static String getLongString(String text, int len) {
String out = text;
for (int i = 1; i <= len; ++i) {
out += random.str();
}
return out;
}
public static void sendServerChatMessage(Object serverChatMessageText) {
Wrapper.INSTANCE.player().sendChatMessage(serverChatMessageText.toString());
}
public static int getWindowId() {
return getPlayer().openContainer.windowId;
}
public static void sendTabComplete(String in) {
Wrapper.INSTANCE.player().sendQueue.addToSendQueue(new C14PacketTabComplete(in));
}
public static void setFakeSlot(ItemStack item, int slot) {
getPlayer().inventory.setInventorySlotContents(slot, item);
}
public static GuiContainer getGuiContainer() {
return getGuiContainer(Wrapper.INSTANCE.mc().currentScreen);
}
public static GuiContainer getGuiContainer(GuiScreen screen) {
return screen instanceof GuiContainer ? (GuiContainer) screen : null;
}
public static boolean isDoubleChest(TileEntity tile) {
int y;
int z;
int[] pos;
int x;
return tile instanceof TileEntityChest && (getTileEntity((x = (pos = getCoords(tile))[0]) - 1, y = pos[1], z = pos[2]) instanceof TileEntityChest || getTileEntity(x + 1, y, z) instanceof TileEntityChest || getTileEntity(x, y, z - 1) instanceof TileEntityChest || getTileEntity(x, y, z + 1) instanceof TileEntityChest);
}
public static void dropSlots(int range) {
for (int slot = 0; slot < range; ++slot) {
dropSlot(slot);
}
}
public static void dropSlot(int slot) {
clickSlot(slot, 1, 4);
}
public static void clickSlot(int slot, int shift, int action) {
Wrapper.INSTANCE.mc().playerController.windowClick(getWindowId(), slot, shift, action, getPlayer());
}
public static int getCurrentSlot() {
return getPlayer().inventory.currentItem;
}
public static int getSlots() {
return getSlots(getTileEntity());
}
public static int getSlots(TileEntity tile) {
if (tile instanceof IInventory) {
IInventory inventory = (IInventory) tile;
return inventory.isUseableByPlayer(getPlayer()) ? inventory.getSizeInventory() : 0;
}
return 0;
}
public static String getEntityInfoString(Entity entity) {
return "[" + entity.getCommandSenderName() + ": UUID(" + getUUID(entity) + "), ID(" + getEntityId(entity) + ")]";
}
public static List<TileEntity> getNearTileEntities() {
ArrayList<TileEntity> out = new ArrayList<>();
IChunkProvider chunkProvider = getWorld().getChunkProvider();
if (chunkProvider instanceof ChunkProviderClient) {
List<Chunk> chunks = ReflectionHelper.getPrivateValue(ChunkProviderClient.class, (ChunkProviderClient) chunkProvider, Mappings.chunkListing);
chunks.forEach((chunk) -> {
chunk.chunkTileEntityMap.values().stream().filter((entityObj) -> !(!(entityObj instanceof TileEntity))).forEachOrdered((entityObj) -> {
out.add((TileEntity) entityObj);
});
});
}
return out;
}
public static NBTTagCompound getPackageNbt(ItemStack item) {
NBTTagCompound ROOT = new NBTTagCompound();
ROOT.setTag("Package", new NBTTagCompound());
NBTTagCompound Package2 = ROOT.getCompoundTag("Package");
NBTTagList list = new NBTTagList();
list.appendTag(getNbtItem(item));
Package2.setTag("Items", list);
return ROOT;
}
public static NBTTagCompound getNbtItem(ItemStack item) {
NBTTagCompound itemTag = new NBTTagCompound();
itemTag.setByte("Count", (byte) item.stackSize);
itemTag.setByte("Slot", (byte) 0);
item.getItem();
itemTag.setShort("id", (short) Item.getIdFromItem(item.getItem()));
itemTag.setShort("Damage", (short) item.getItemDamage());
if (item.hasTagCompound()) {
itemTag.setTag("tag", item.getTagCompound());
}
return itemTag;
}
public static List<int[]> getNukerList(int[] center, int radius) {
ArrayList<int[]> list = new ArrayList<>();
for (int i = radius; i >= -radius; --i) {
for (int k = radius; k >= -radius; --k) {
for (int j = -radius; j <= radius; ++j) {
int x = center[0] + i;
int y = center[1] + j;
int z = center[2] + k;
if (getWorld().getBlock(x, y, z).getMaterial() instanceof MaterialTransparent) {
continue;
}
list.add(new int[]{x, y, z});
}
}
}
return list;
}
public static List<int[]> getThorList(String filter) {
ArrayList<int[]> nearCoords = new ArrayList<>();
List<Entity> near = getNearEntities();
for (Entity entity : near) {
if (filter.equals("pl")) {
if (entity == getPlayer() || !(entity instanceof EntityPlayer)) {
continue;
}
nearCoords.add(getCoords(entity));
continue;
}
if (filter.equals("ent")) {
if (entity == getPlayer() || entity instanceof EntityLightningBolt) {
continue;
}
nearCoords.add(getCoords(entity));
continue;
}
EntityPlayer player = getPlayer(filter);
if (player == null) {
continue;
}
nearCoords.add(getCoords(player));
break;
}
return nearCoords;
}
public static void sendProxyPacket(String channel, Object... data) {
ByteBuf buf = Unpooled.buffer();
for (Object o : data) {
if (o instanceof Integer) {
buf.writeInt(((int) o));
continue;
}
if (o instanceof Byte) {
buf.writeByte(((byte) o));
continue;
}
if (o instanceof Short) {
buf.writeShort(((short) o));
continue;
}
if (o instanceof String) {
ByteBufUtils.writeUTF8String(buf, ((String) o));
continue;
}
if (o instanceof ItemStack) {
ByteBufUtils.writeItemStack(buf, ((ItemStack) o));
continue;
}
if (!(o instanceof NBTTagCompound)) {
continue;
}
ByteBufUtils.writeTag(buf, ((NBTTagCompound) o));
}
NetworkDispatcher.get(Wrapper.INSTANCE.mc().getNetHandler().getNetworkManager()).sendProxy(new FMLProxyPacket(buf, channel));
}
}
| 12,680 | Java | .java | radioegor146/ehacks-pro | 24 | 19 | 4 | 2018-07-08T13:24:10Z | 2022-12-06T08:08:58Z |
Timer.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/Scrambled Net/src/com/silentservices/netscramble/Timer.java |
/**
* NetScramble: unscramble a network and connect all the terminals.
* The player is given a network diagram with the parts of the network
* randomly rotated; he/she must rotate them to connect all the terminals
* to the server.
*
* This is an Android implementation of the KDE game "knetwalk" by
* Andi Peredri, Thomas Nagy, and Reinhold Kainhofer.
*
* © 2007-2010 Ian Cameron Smith <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package com.silentservices.netscramble;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
/**
* This class implements a simple periodic timer.
*/
abstract class Timer
extends Handler
{
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Construct a periodic timer with a given tick interval.
*
* @param ival Tick interval in ms.
*/
public Timer(long ival) {
tickInterval = ival;
isRunning = false;
accumTime = 0;
}
// ******************************************************************** //
// Timer Control.
// ******************************************************************** //
/**
* Start the timer. step() will be called at regular intervals
* until it returns true; then done() will be called.
*
* Subclasses may override this to do their own setup; but they
* must then call super.start().
*/
public void start() {
if (isRunning)
return;
isRunning = true;
long now = SystemClock.uptimeMillis();
// Start accumulating time again.
lastLogTime = now;
// Schedule the first event at once.
nextTime = now;
postAtTime(runner, nextTime);
}
/**
* Stop the timer. step() will not be called again until it is
* restarted.
*
* Subclasses may override this to do their own setup; but they
* must then call super.stop().
*/
public void stop() {
if (isRunning) {
isRunning = false;
long now = SystemClock.uptimeMillis();
accumTime += now - lastLogTime;
lastLogTime = now;
}
}
/**
* Stop the timer, and reset the accumulated time and tick count.
*/
public final void reset() {
stop();
tickCount = 0;
accumTime = 0;
}
/**
* Query whether this Timer is running.
*
* @return true iff we're running.
*/
public final boolean isRunning() {
return isRunning;
}
/**
* Get the accumulated time of this Timer.
*
* @return How long this timer has been running, in ms.
*/
public final long getTime() {
return accumTime;
}
// ******************************************************************** //
// Handlers.
// ******************************************************************** //
/**
* Subclasses override this to handle a timer tick.
*
* @param count The call count; 0 on the first call.
* @param time The total time for which this timer has been
* running, in ms. Reset by reset().
* @return true if the timer should stop; this will
* trigger a call to done(). false otherwise;
* we will continue calling step().
*/
protected abstract boolean step(int count, long time);
/**
* Subclasses may override this to handle completion of a run.
*/
protected void done() { }
// ******************************************************************** //
// Implementation.
// ******************************************************************** //
/**
* Handle a step of the animation.
*/
private final Runnable runner = new Runnable() {
public final void run() {
if (isRunning) {
long now = SystemClock.uptimeMillis();
// Add up the time since the last step.
accumTime += now - lastLogTime;
lastLogTime = now;
if (!step(tickCount++, accumTime)) {
// Schedule the next. If we've got behind, schedule
// it for a tick after now. (Otherwise we'd end
// up with a zillion events queued.)
nextTime += tickInterval;
if (nextTime <= now)
nextTime += tickInterval;
postAtTime(runner, nextTime);
} else {
isRunning = false;
done();
}
}
}
};
// ******************************************************************** //
// State Save/Restore.
// ******************************************************************** //
/**
* Save game state so that the user does not lose anything
* if the game process is killed while we are in the
* background.
*
* @param outState A Bundle in which to place any state
* information we wish to save.
*/
void saveState(Bundle outState) {
// Accumulate all time up to now, so we know where we're saving.
if (isRunning) {
long now = SystemClock.uptimeMillis();
accumTime += now - lastLogTime;
lastLogTime = now;
}
outState.putLong("tickInterval", tickInterval);
outState.putBoolean("isRunning", isRunning);
outState.putInt("tickCount", tickCount);
outState.putLong("accumTime", accumTime);
}
/**
* Restore our game state from the given Bundle. If the saved
* state was running, we will continue running.
*
* @param map A Bundle containing the saved state.
* @return true if the state was restored OK; false
* if the saved state was incompatible with the
* current configuration.
*/
boolean restoreState(Bundle map) {
return restoreState(map, true);
}
/**
* Restore our game state from the given Bundle.
*
* @param map A Bundle containing the saved state.
* @param run If true, restore the saved runnning state;
* otherwise restore to a stopped state.
* @return true if the state was restored OK; false
* if the saved state was incompatible with the
* current configuration.
*/
boolean restoreState(Bundle map, boolean run) {
tickInterval = map.getLong("tickInterval");
isRunning = map.getBoolean("isRunning");
tickCount = map.getInt("tickCount");
accumTime = map.getLong("accumTime");
lastLogTime = SystemClock.uptimeMillis();
// If we were running, restart if requested, else stop.
if (isRunning) {
if (run)
start();
else
isRunning = false;
}
return true;
}
// ******************************************************************** //
// Member Data.
// ******************************************************************** //
// The tick interval in ms.
private long tickInterval = 0;
// true iff the timer is running.
private boolean isRunning = false;
// Number of times step() has been called.
private int tickCount;
// Time at which to execute the next step. We schedule each
// step at this plus x ms; this gives us an even execution rate.
private long nextTime;
// The accumulated time in ms for which this timer has been running.
// Increments between start() and stop(); start(true) resets it.
private long accumTime;
// The time at which we last added to accumTime.
private long lastLogTime;
}
| 7,617 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Help.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/Scrambled Net/src/com/silentservices/netscramble/Help.java | /**
* NetScramble: unscramble a network and connect all the terminals.
* The player is given a network diagram with the parts of the network
* randomly rotated; he/she must rotate them to connect all the terminals
* to the server.
*
* This is an Android implementation of the KDE game "knetwalk" by
* Andi Peredri, Thomas Nagy, and Reinhold Kainhofer.
*
* © 2007-2010 Ian Cameron Smith <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package com.silentservices.netscramble;
import org.hermit.android.core.HelpActivity;
import android.os.Bundle;
/**
* Simple help activity for NetScramble.
*/
public class Help extends HelpActivity {
/**
* Called when the activity is starting. This is where most initialization
* should go: calling setContentView(int) to inflate the activity's UI, etc.
*/
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Load the preferences from an XML resource
addHelpFromArrays(R.array.help_titles, R.array.help_texts);
}
}
| 1,457 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
ScoreList.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/Scrambled Net/src/com/silentservices/netscramble/ScoreList.java | /**
* NetScramble: unscramble a network and connect all the terminals.
* The player is given a network diagram with the parts of the network
* randomly rotated; he/she must rotate them to connect all the terminals
* to the server.
*
* This is an Android implementation of the KDE game "knetwalk" by
* Andi Peredri, Thomas Nagy, and Reinhold Kainhofer.
*
* © 2007-2010 Ian Cameron Smith <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package com.silentservices.netscramble;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
/**
* An activity which displays the "high score list" (personal bests) for
* NetScramble.
*/
public class ScoreList extends Activity {
/**
* Called when the activity is starting. This is where most initialization
* should go: calling setContentView(int) to inflate the activity's UI, etc.
*
* You can call finish() from within this function, in which case
* onDestroy() will be immediately called without any of the rest of the
* activity lifecycle executing.
*
* Derived classes must call through to the super class's implementation of
* this method. If they do not, an exception will be thrown.
*
* @param icicle
* If the activity is being re-initialized after previously being
* shut down then this Bundle contains the data it most recently
* supplied in onSaveInstanceState(Bundle). Note: Otherwise it is
* null.
*/
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// We don't want a title bar.
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.score_layout);
// Display the best scores.
showScores();
}
// ******************************************************************** //
// Menu Management.
// ******************************************************************** //
/**
* Initialize the contents of the game's options menu by adding items to the
* given menu.
*
* This is only called once, the first time the options menu is displayed.
* To update the menu every time it is displayed, see
* onPrepareOptionsMenu(Menu).
*
* When we add items to the menu, we can either supply a Runnable to receive
* notification of selection, or we can implement the Activity's
* onOptionsItemSelected(Menu.Item) method to handle them there.
*
* @param menu
* The options menu in which we should place our items. We can
* safely hold on this (and any items created from it), making
* modifications to it as desired, until the next time
* onCreateOptionsMenu() is called.
* @return true for the menu to be displayed; false to suppress showing it.
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// We must call through to the base implementation.
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.scores_menu, menu);
return true;
}
/**
* This hook is called whenever an item in your options menu is selected.
* Derived classes should call through to the base class for it to perform
* the default menu handling. (True?)
*
* @param item
* The menu item that was selected.
* @return false to have the normal processing happen.
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_reset:
resetScores();
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
// ******************************************************************** //
// Scores Display.
// ******************************************************************** //
private void showScores() {
SharedPreferences scorePrefs = getSharedPreferences("scores",
MODE_PRIVATE);
BoardView.Skill[] skillVals = BoardView.Skill.values();
// Populate the best clicks table.
TableLayout clicksTable = (TableLayout) findViewById(R.id.clicksTable);
// Remove any existing scores rows, as we may be re-displaying.
int cc = clicksTable.getChildCount();
if (cc > 2)
for (int i = cc - 1; i >= 2; --i)
clicksTable.removeViewAt(i);
for (BoardView.Skill skill : skillVals) {
String sizeName = "size" + skill.toString();
String clickName = "clicks" + skill.toString();
// Get the best to date for this skill level.
int size = scorePrefs.getInt(sizeName, -1);
int clicks = scorePrefs.getInt(clickName, -1);
long date = scorePrefs.getLong(clickName + "Date", 0);
// Create a table row for this column.
TableRow row = new TableRow(this);
clicksTable.addView(row);
// Add a label field to display the skill level.
TextView skillLab = new TextView(this);
skillLab.setTextSize(16);
skillLab.setTextColor(0xff000000);
String stext = getString(skill.label);
if (size > 0)
stext += " (" + size + ")";
skillLab.setText(stext);
row.addView(skillLab);
// Add a field to display the clicks count.
TextView clickLab = new TextView(this);
clickLab.setTextSize(16);
clickLab.setTextColor(0xff000000);
clickLab.setText(clicks < 0 ? "--" : "" + clicks);
row.addView(clickLab);
// Add a field to display the date/time of this record.
TextView dateLab = new TextView(this);
dateLab.setTextSize(16);
dateLab.setTextColor(0xff000000);
dateLab.setText(dateString(date));
row.addView(dateLab);
}
// Populate the best times table.
TableLayout timeTable = (TableLayout) findViewById(R.id.timeTable);
// Remove any existing scores rows, as we may be re-displaying.
int tc = timeTable.getChildCount();
if (tc > 2)
for (int i = tc - 1; i >= 2; --i)
timeTable.removeViewAt(i);
for (BoardView.Skill skill : skillVals) {
String sizeName = "size" + skill.toString();
String timeName = "time" + skill.toString();
// Get the best to date for this skill level.
int size = scorePrefs.getInt(sizeName, -1);
int time = scorePrefs.getInt(timeName, -1);
long date = scorePrefs.getLong(timeName + "Date", 0);
// Create a table row for this column.
TableRow row = new TableRow(this);
timeTable.addView(row);
// Add a label field to display the skill level.
TextView skillLab = new TextView(this);
skillLab.setTextSize(16);
skillLab.setTextColor(0xff000000);
String stext = getString(skill.label);
if (size > 0)
stext += " (" + size + ")";
skillLab.setText(stext);
row.addView(skillLab);
// Add a field to display the time taken.
TextView timeLab = new TextView(this);
timeLab.setTextSize(16);
timeLab.setTextColor(0xff000000);
timeLab.setText(time < 0 ? "--" : String.format("%2d:%02d",
time / 60, time % 60));
row.addView(timeLab);
// Add a field to display the date/time of this record.
TextView dateLab = new TextView(this);
dateLab.setTextSize(16);
dateLab.setTextColor(0xff000000);
dateLab.setText(dateString(date));
row.addView(dateLab);
}
}
private String dateString(long date) {
if (date == 0)
return "--";
int flags = DateUtils.isToday(date) ? DateUtils.FORMAT_SHOW_TIME
: DateUtils.FORMAT_SHOW_DATE;
flags |= DateUtils.FORMAT_ABBREV_ALL;
return DateUtils.formatDateTime(this, date, flags);
}
// ******************************************************************** //
// Scores Management.
// ******************************************************************** //
private void resetScores() {
SharedPreferences scorePrefs = getSharedPreferences("scores",
MODE_PRIVATE);
SharedPreferences.Editor editor = scorePrefs.edit();
editor.clear();
editor.commit();
showScores();
}
}
| 8,556 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
NetScramble.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/Scrambled Net/src/com/silentservices/netscramble/NetScramble.java | /**
* NetScramble: unscramble a network and connect all the terminals.
* The player is given a network diagram with the parts of the network
* randomly rotated; he/she must rotate them to connect all the terminals
* to the server.
*
* This is an Android implementation of the KDE game "knetwalk" by
* Andi Peredri, Thomas Nagy, and Reinhold Kainhofer.
*
* © 2007-2010 Ian Cameron Smith <[email protected]>
*
* © 2014 Michael Mueller <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package com.silentservices.netscramble;
import org.hermit.android.core.AppUtils;
import org.hermit.android.core.MainActivity;
import org.hermit.android.core.OneTimeDialog;
import org.hermit.android.notice.InfoBox;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.ViewAnimator;
import com.silentservices.netscramble.BoardView.Skill;
/**
* Main NetScramble activity.
*/
public class NetScramble extends ActionBarActivity {
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// Application utilities instance, used to get app version.
private AppUtils appUtils = null;
// The EULA dialog. Null if the user hasn't set one up.
private OneTimeDialog eulaDialog = null;
// Dialog used to display about etc.
private InfoBox messageDialog = null;
// IDs of the button strings and URLs for "Home" and "License".
private int homeButton = 0;
private int homeLink = 0;
private int licButton = 0;
private int licLink = 0;
// ID of the about text.
private int aboutText = 0;
// ******************************************************************** //
// Public Types.
// ******************************************************************** //
/**
* Current state of the game.
*/
static enum State {
NEW, RESTORED, INIT, PAUSED, RUNNING, SOLVED, ABORTED;
static State getValue(int ordinal) {
return states[ordinal];
}
private static State[] states = values();
}
/**
* The sounds that we make.
*/
static enum Sound {
START(R.raw.start), CLICK(R.raw.click), TURN(R.raw.turn), CONNECT(
R.raw.connect), POP(R.raw.pop), WIN(R.raw.win);
private Sound(int res) {
soundRes = res;
}
private final int soundRes; // Resource ID for the sound file.
private int soundId = 0; // Sound ID for playing.
}
/**
* Sound play mode.
*/
static enum SoundMode {
NONE(R.id.sounds_off), QUIET(R.id.sounds_qt), FULL(R.id.sounds_on);
private SoundMode(int res) {
menuId = res;
}
private int menuId; // ID of the corresponding menu item.
}
// ******************************************************************** //
// EULA Dialog.
// ******************************************************************** //
/**
* Create a dialog for showing the EULA, or other warnings / disclaimers.
* When your app starts, call {@link #showFirstEula()} to display the dialog
* the first time your app runs. To display it on demand, call
* {@link #showEula()}.
*
* @param title
* Resource ID of the dialog title.
* @param text
* Resource ID of the EULA / warning text.
* @param close
* Resource ID of the close button.
*/
public void createEulaBox(int title, int text, int close) {
eulaDialog = new OneTimeDialog(this, "eula", title, text, close);
}
/**
* Show the EULA dialog if this is the first program run. You need to have
* created the dialog by calling {@link #createEulaBox(int, int, int)}.
*/
public void showFirstEula() {
if (eulaDialog != null)
eulaDialog.showFirst();
}
/**
* Show the EULA dialog unconditionally. You need to have created the dialog
* by calling {@link #createEulaBox(int, int, int)}.
*/
public void showEula() {
if (eulaDialog != null)
eulaDialog.show();
}
// ******************************************************************** //
// Help and About Boxes.
// ******************************************************************** //
/**
* Create a dialog for help / about boxes etc. If you want to display one of
* those, set up the info in it by calling {@link #setHomeInfo(int, int)},
* {@link #setAboutInfo(int)} and {@link #setLicenseInfo(int, int)}; then
* pop up a dialog by calling {@link #showAbout()}.
*
* @param close
* Resource ID of the close button.
* @deprecated The message box is now created automatically.
*/
@Deprecated
public void createMessageBox(int close) {
messageDialog = new InfoBox(this, close);
String version = appUtils.getVersionString();
messageDialog.setTitle(version);
}
/**
* Set up the about info for dialogs. See {@link #showAbout()}.
*
* @param about
* Resource ID of the about text.
*/
public void setAboutInfo(int about) {
aboutText = about;
}
/**
* Set up the homepage info for dialogs. See {@link #showAbout()}.
*
* @param link
* Resource ID of the URL the button links to.
*/
public void setHomeInfo(int link) {
homeButton = R.string.button_homepage;
homeLink = link;
}
/**
* Set up the homepage info for dialogs. See {@link #showAbout()}.
*
* @param button
* Resource ID of the button text.
* @param link
* Resource ID of the URL the button links to.
*/
@Deprecated
public void setHomeInfo(int button, int link) {
homeButton = button;
homeLink = link;
}
/**
* Set up the license info for dialogs. See {@link #showAbout()}.
*
* @param link
* Resource ID of the URL the button links to.
*/
public void setLicenseInfo(int link) {
licButton = R.string.button_license;
licLink = link;
}
/**
* Set up the license info for dialogs. See {@link #showAbout()}.
*
* @param button
* Resource ID of the button text.
* @param link
* Resource ID of the URL the button links to.
*/
@Deprecated
public void setLicenseInfo(int button, int link) {
licButton = button;
licLink = link;
}
/**
* Show an about dialog. You need to have configured it by calling
* {@link #setAboutInfo(int)}, {@link #setHomeInfo(int, int)} and
* {@link #setLicenseInfo(int, int)}.
*/
public void showAbout() {
// Create the dialog the first time.
if (messageDialog == null)
createMessageBox();
messageDialog.setLinkButton(1, homeButton, homeLink);
if (licButton != 0 && licLink != 0)
messageDialog.setLinkButton(2, licButton, licLink);
messageDialog.show(aboutText);
}
/**
* Create a dialog for help / about boxes etc. If you want to display one of
* those, set up the info in it by calling {@link #setHomeInfo(int, int)},
* {@link #setAboutInfo(int)} and {@link #setLicenseInfo(int, int)}; then
* pop up a dialog by calling {@link #showAbout()}.
*/
private void createMessageBox() {
messageDialog = new InfoBox(this);
String version = appUtils.getVersionString();
messageDialog.setTitle(version);
}
// ******************************************************************** //
// Activity Setup.
// ******************************************************************** //
/**
* Called when the activity is starting. This is where most initialization
* should go: calling setContentView(int) to inflate the activity's UI, etc.
*
* You can call finish() from within this function, in which case
* onDestroy() will be immediately called without any of the rest of the
* activity lifecycle executing.
*
* Derived classes must call through to the super class's implementation of
* this method. If they do not, an exception will be thrown.
*
* @param icicle
* If the activity is being re-initialized after previously being
* shut down then this Bundle contains the data it most recently
* supplied in onSaveInstanceState(Bundle). Note: Otherwise it is
* null.
*/
@Override
public void onCreate(Bundle icicle) {
Log.i(TAG, "onCreate(): "
+ (icicle == null ? "clean start" : "restart"));
super.onCreate(icicle);
appUtils = AppUtils.getInstance(this);
// Set up the standard dialogs.
setAboutInfo(R.string.about_text);
setHomeInfo(R.string.url_homepage);
setLicenseInfo(R.string.url_license);
// Create our EULA box.
createEulaBox(R.string.eula_title, R.string.eula_text,
R.string.button_close);
appResources = getResources();
gameTimer = new GameTimer();
// We don't want a title bar.
// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
// WindowManager.LayoutParams.FLAG_FULLSCREEN);
// requestWindowFeature(Window.FEATURE_NO_TITLE);
// We want the audio controls to control our sound volume.
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
// Create string formatting buffers.
clicksText = new StringBuilder(10);
timeText = new StringBuilder(10);
// Create the GUI for the game.
setContentView(R.layout.main);
setupGui();
// Restore our preferences.
SharedPreferences prefs = getPreferences(0);
// See if sounds are enabled and how. The old way was boolean
// soundMode, so look for that as a fallback.
soundMode = SoundMode.FULL;
{
String smode = prefs.getString("soundMode", null);
if (smode != null)
soundMode = SoundMode.valueOf(smode);
else {
String son = prefs.getString("soundEnable", null);
if (son != null)
soundMode = Boolean.valueOf(son) ? SoundMode.FULL
: SoundMode.NONE;
}
}
// See if animations are enabled.
animEnable = prefs.getBoolean("animEnable", true);
boardView.setAnimEnable(animEnable);
// Load the sounds.
soundPool = createSoundPool();
// If we have a previous state to restore, try to do so.
boolean restored = false;
if (icicle != null)
restored = restoreState(icicle);
// Get the current game skill level from the preferences, if we didn't
// get a saved game. Default to NOVICE if it's not there.
if (!restored) {
gameSkill = null;
String skill = prefs.getString("skillLevel", null);
if (skill != null)
gameSkill = Skill.valueOf(skill);
if (gameSkill == null)
gameSkill = Skill.NOVICE;
gameState = State.NEW;
} else {
// Save our restored game state.
restoredGameState = gameState;
gameState = State.RESTORED;
}
}
/**
* Called when the current activity is being re-displayed to the user (the
* user has navigated back to it). It will be followed by onStart().
*
* For activities that are using raw Cursor objects (instead of creating
* them through managedQuery(android.net.Uri, String[], String, String[],
* String), this is usually the place where the cursor should be requeried
* (because you had deactivated it in onStop().
*
* Derived classes must call through to the super class's implementation of
* this method. If they do not, an exception will be thrown.
*/
@Override
protected void onRestart() {
Log.i(TAG, "onRestart()");
super.onRestart();
}
/**
* Called after onCreate(Bundle) or onStop() when the current activity is
* now being displayed to the user. It will be followed by onResume() if the
* activity comes to the foreground, or onStop() if it becomes hidden.
*
* Derived classes must call through to the super class's implementation of
* this method. If they do not, an exception will be thrown.
*/
@Override
protected void onStart() {
Log.i(TAG, "onStart()");
super.onStart();
boardView.onStart();
}
/**
* This method is called after onStart() when the activity is being
* re-initialized from a previously saved state, given here in state. Most
* implementations will simply use onCreate(Bundle) to restore their state,
* but it is sometimes convenient to do it here after all of the
* initialization has been done or to allow subclasses to decide whether to
* use your default implementation. The default implementation of this
* method performs a restore of any view state that had previously been
* frozen by onSaveInstanceState(Bundle).
*
* This method is called between onStart() and onPostCreate(Bundle).
*
* @param inState
* The data most recently supplied in
* onSaveInstanceState(Bundle).
*/
@Override
protected void onRestoreInstanceState(Bundle inState) {
Log.i(TAG, "onRestoreInstanceState()");
super.onRestoreInstanceState(inState);
// Save the state.
// saveState(outState);
}
/**
* Called after onRestoreInstanceState(Bundle), onRestart(), or onPause(),
* for your activity to start interacting with the user. This is a good
* place to begin animations, open exclusive-access devices (such as the
* camera), etc.
*
* Keep in mind that onResume is not the best indicator that your activity
* is visible to the user; a system window such as the keyguard may be in
* front. Use onWindowFocusChanged(boolean) to know for certain that your
* activity is visible to the user (for example, to resume a game).
*
* Derived classes must call through to the super class's implementation of
* this method. If they do not, an exception will be thrown.
*/
@Override
protected void onResume() {
Log.i(TAG, "onResume()");
super.onResume();
// First time round, show the EULA.
showFirstEula();
// ActionBarActivity { //
// Display the skill level.
statusMode.setText(gameSkill.label);
// If we restored a state, go to that state. Otherwise start
// at the welcome screen.
if (gameState == State.NEW) {
Log.d(TAG, "onResume() NEW: init");
setState(State.INIT, true);
} else if (gameState == State.RESTORED) {
Log.d(TAG, "onResume() RESTORED: set " + restoredGameState);
setState(restoredGameState, true);
// If we restored an aborted state, that means we were starting
// a game. Kick it off again.
if (restoredGameState == State.ABORTED) {
Log.d(TAG, "onResume() RESTORED ABORTED: start");
startGame(null);
}
} else if (gameState == State.PAUSED) {
// We just paused without closing down. Resume.
setState(State.RUNNING, true);
} else {
Log.e(TAG, "onResume() !!" + gameState + "!!: init");
// setState(State.INIT); // Shouldn't get here.
}
boardView.onResume();
}
/**
* Called to retrieve per-instance state from an activity before being
* killed so that the state can be restored in onCreate(Bundle) or
* onRestoreInstanceState(Bundle) (the Bundle populated by this method will
* be passed to both).
*
* This method is called before an activity may be killed so that when it
* comes back some time in the future it can restore its state.
*
* Do not confuse this method with activity lifecycle callbacks such as
* onPause(), which is always called when an activity is being placed in the
* background or on its way to destruction, or onStop() which is called
* before destruction.
*
* The default implementation takes care of most of the UI per-instance
* state for you by calling onSaveInstanceState() on each view in the
* hierarchy that has an id, and by saving the id of the currently focused
* view (all of which is restored by the default implementation of
* onRestoreInstanceState(Bundle)). If you override this method to save
* additional information not captured by each individual view, you will
* likely want to call through to the default implementation, otherwise be
* prepared to save all of the state of each view yourself.
*
* If called, this method will occur before onStop(). There are no
* guarantees about whether it will occur before or after onPause().
*
* @param outState
* A Bundle in which to place any state information you wish to
* save.
*/
@Override
public void onSaveInstanceState(Bundle outState) {
Log.i(TAG, "onSaveInstanceState()");
super.onSaveInstanceState(outState);
// Save the state.
saveState(outState);
}
/**
* Called as part of the activity lifecycle when an activity is going into
* the background, but has not (yet) been killed. The counterpart to
* onResume().
*
* When activity B is launched in front of activity A, this callback will be
* invoked on A. B will not be created until A's onPause() returns, so be
* sure to not do anything lengthy here.
*
* This callback is mostly used for saving any persistent state the activity
* is editing, to present a "edit in place" model to the user and making
* sure nothing is lost if there are not enough resources to start the new
* activity without first killing this one. This is also a good place to do
* things like stop animations and other things that consume a noticeable
* mount of CPU in order to make the switch to the next activity as fast as
* possible, or to close resources that are exclusive access such as the
* camera.
*
* In situations where the system needs more memory it may kill paused
* processes to reclaim resources. Because of this, you should be sure that
* all of your state is saved by the time you return from this function. In
* general onSaveInstanceState(Bundle) is used to save per-instance state in
* the activity and this method is used to store global persistent data (in
* content providers, files, etc.).
*
* After receiving this call you will usually receive a following call to
* onStop() (after the next activity has been resumed and displayed),
* however in some cases there will be a direct call back to onResume()
* without going through the stopped state.
*
* Derived classes must call through to the super class's implementation of
* this method. If they do not, an exception will be thrown.
*/
@Override
protected void onPause() {
Log.i(TAG, "onPause()");
super.onPause();
boardView.onPause();
// Pause the game. Don't show a splash screen because the
// game is going away.
if (gameState == State.RUNNING)
setState(State.PAUSED, false);
}
/**
* Called when you are no longer visible to the user. You will next receive
* either onStart(), onDestroy(), or nothing, depending on later user
* activity.
*
* Note that this method may never be called, in low memory situations where
* the system does not have enough memory to keep your activity's process
* running after its onPause() method is called.
*
* Derived classes must call through to the super class's implementation of
* this method. If they do not, an exception will be thrown.
*/
@Override
protected void onStop() {
Log.i(TAG, "onStop()");
super.onStop();
boardView.onStop();
}
/**
* Perform any final cleanup before an activity is destroyed. This can
* happen either because the activity is finishing (someone called finish()
* on it, or because the system is temporarily destroying this instance of
* the activity to save space. You can distinguish between these two
* scenarios with the isFinishing() method.
*
* Note: do not count on this method being called as a place for saving
* data! For example, if an activity is editing data in a content provider,
* those edits should be committed in either onPause() or
* onSaveInstanceState(Bundle), not here. This method is usually implemented
* to free resources like threads that are associated with an activity, so
* that a destroyed activity does not leave such things around while the
* rest of its application is still running. There are situations where the
* system will simply kill the activity's hosting process without calling
* this method (or any others) in it, so it should not be used to do things
* that are intended to remain around after the process goes away.
*
* Derived classes must call through to the super class's implementation of
* this method. If they do not, an exception will be thrown.
*/
@Override
protected void onDestroy() {
Log.i(TAG, "onDestroy()");
super.onDestroy();
}
// ******************************************************************** //
// GUI Creation.
// ******************************************************************** //
/**
* Set up the GUI for the game. Add handlers and animations where needed.
*/
private void setupGui() {
viewSwitcher = (ViewAnimator) findViewById(R.id.view_switcher);
// Make the animations for the switcher.
animSlideInLeft = new TranslateAnimation(Animation.RELATIVE_TO_SELF,
1.0f, Animation.RELATIVE_TO_SELF, 0.0f,
Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
0.0f);
animSlideInLeft.setDuration(ANIM_TIME);
animSlideOutLeft = new TranslateAnimation(Animation.RELATIVE_TO_SELF,
0.0f, Animation.RELATIVE_TO_SELF, -1.0f,
Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
0.0f);
animSlideOutLeft.setDuration(ANIM_TIME);
animSlideInRight = new TranslateAnimation(Animation.RELATIVE_TO_SELF,
-1.0f, Animation.RELATIVE_TO_SELF, 0.0f,
Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
0.0f);
animSlideInRight.setDuration(ANIM_TIME);
animSlideOutRight = new TranslateAnimation(Animation.RELATIVE_TO_SELF,
0.0f, Animation.RELATIVE_TO_SELF, 1.0f,
Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
0.0f);
animSlideOutRight.setDuration(ANIM_TIME);
// Get handles on the important widgets.
splashText = (TextView) findViewById(R.id.splash_text);
boardView = (BoardView) findViewById(R.id.board_view);
// Create the left status field.
statusClicks = (TextView) findViewById(R.id.status_clicks);
statusMode = (TextView) findViewById(R.id.status_mode);
statusTime = (TextView) findViewById(R.id.status_time);
// Set up the splash text view to call wakeUp() when
// the user presses a key or taps the screen.
splashText.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
wakeUp();
return true;
} else
return false;
}
});
splashText.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
wakeUp();
return true;
}
return false;
}
});
// If we have a soft menu button (which depends on the screen size),
// then set it up.
ImageButton menuButton = (ImageButton) findViewById(R.id.menu_button);
if (menuButton != null) {
menuButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openOptionsMenu();
}
});
}
}
// ******************************************************************** //
// Menu Management.
// ******************************************************************** //
/**
* Initialize the contents of the game's options menu by adding items to the
* given menu.
*
* This is only called once, the first time the options menu is displayed.
* To update the menu every time it is displayed, see
* onPrepareOptionsMenu(Menu).
*
* When we add items to the menu, we can either supply a Runnable to receive
* notification of selection, or we can implement the Activity's
* onOptionsItemSelected(Menu.Item) method to handle them there.
*
* @param menu
* The options menu in which we should place our items. We can
* safely hold on this (and any items created from it), making
* modifications to it as desired, until the next time
* onCreateOptionsMenu() is called.
* @return true for the menu to be displayed; false to suppress showing it.
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
mainMenu = menu;
// We must call through to the base implementation.
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
// GUI is created, state is restored (if any) -- now is a good time
// to re-sync the options menus.
selectCurrentSkill();
selectSoundMode();
selectAnimEnable();
return true;
}
private void selectCurrentSkill() {
// Set the selected skill menu item to the current skill.
if (mainMenu != null) {
MenuItem skillItem = mainMenu.findItem(gameSkill.id);
if (skillItem != null)
skillItem.setChecked(true);
}
}
private void selectSoundMode() {
// Set the sound enable menu item to the current state.
if (mainMenu != null) {
int id = soundMode.menuId;
MenuItem soundItem = mainMenu.findItem(id);
if (soundItem != null)
soundItem.setChecked(true);
}
}
private void selectAnimEnable() {
// Set the animation enable menu item to the current state.
if (mainMenu != null) {
int id = animEnable ? R.id.anim_on : R.id.anim_off;
MenuItem animItem = mainMenu.findItem(id);
if (animItem != null)
animItem.setChecked(true);
}
}
void selectAutosolveMode(boolean solving) {
// Set the autosolve menu item to the current state.
if (mainMenu != null) {
MenuItem solveItem = mainMenu.findItem(R.id.menu_autosolve);
if (solveItem != null) {
if (solving) {
solveItem.setIcon(R.drawable.ic_menu_stop);
solveItem.setTitle(R.string.menu_stopsolve);
} else {
solveItem.setIcon(R.drawable.ic_menu_solve);
solveItem.setTitle(R.string.menu_autosolve);
}
}
}
}
/**
* This hook is called whenever an item in your options menu is selected.
* Derived classes should call through to the base class for it to perform
* the default menu handling. (True?)
*
* @param item
* The menu item that was selected.
* @return false to have the normal processing happen.
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_new:
startGame(null);
break;
case R.id.menu_pause:
setState(State.PAUSED, true);
break;
case R.id.menu_scores:
// Launch the high scores activity as a subactivity.
setState(State.PAUSED, false);
Intent sIntent = new Intent();
sIntent.setClass(this, ScoreList.class);
startActivity(sIntent);
break;
case R.id.menu_help:
// Launch the help activity as a subactivity.
setState(State.PAUSED, false);
Intent hIntent = new Intent();
hIntent.setClass(this, Help.class);
startActivity(hIntent);
break;
case R.id.menu_about:
showAbout();
break;
case R.id.skill_novice:
startGame(Skill.NOVICE);
break;
case R.id.skill_normal:
startGame(Skill.NORMAL);
break;
case R.id.skill_expert:
startGame(Skill.EXPERT);
break;
case R.id.skill_master:
startGame(Skill.MASTER);
break;
case R.id.skill_insane:
startGame(Skill.INSANE);
break;
case R.id.sounds_off:
setSoundMode(SoundMode.NONE);
break;
case R.id.sounds_qt:
setSoundMode(SoundMode.QUIET);
break;
case R.id.sounds_on:
setSoundMode(SoundMode.FULL);
break;
case R.id.anim_off:
setAnimEnable(false);
break;
case R.id.anim_on:
setAnimEnable(true);
break;
case R.id.menu_autosolve:
solverUsed = true;
boardView.autosolve();
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
private void setSoundMode(SoundMode mode) {
soundMode = mode;
// Save the new setting to prefs.
SharedPreferences prefs = getPreferences(0);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("soundMode", "" + soundMode);
editor.commit();
selectSoundMode();
}
private void setAnimEnable(boolean enable) {
animEnable = enable;
boardView.setAnimEnable(animEnable);
// Save the new setting to prefs.
SharedPreferences prefs = getPreferences(0);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("animEnable", animEnable);
editor.commit();
selectAnimEnable();
}
// ******************************************************************** //
// Game progress.
// ******************************************************************** //
/**
* This method is called each time the user clicks a cell.
*/
void cellClicked(Cell cell) {
// Count the click, but only if this isn't a repeat click on the
// same cell. This is because the tap interface only rotates
// clockwise, and it's not fair to count an anti-clockwise
// turn as 3 clicks.
if (!isSolved && cell != prevClickedCell) {
++clickCount;
updateStatus();
prevClickedCell = cell;
}
}
// ******************************************************************** //
// Game Control Functions.
// ******************************************************************** //
/**
* Wake up: the user has clicked the splash screen, so continue.
*/
private void wakeUp() {
// If we are paused, just go to running. Otherwise (in the
// welcome or game over screen), start a new game.
if (gameState == State.PAUSED)
setState(State.RUNNING, true);
else
startGame(null);
}
// Create a listener for the user starting the game.
private final DialogInterface.OnClickListener startGameListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
setState(State.RUNNING, true);
}
};
/**
* Start a game at a given skill level, or the previous skill level. The
* skill level chosen is saved to the preferences and becomes the default
* for next time.
*
* @param sk
* Skill level to start at; if null, use the previous skill from
* the preferences.
*/
public void startGame(BoardView.Skill sk) {
// Abort any existing game, so we know we're not just continuing.
setState(State.ABORTED, false);
// Sort out the previous and new skills. If we aren't
// given a new skill, default to previous.
BoardView.Skill prevSkill = gameSkill;
gameSkill = sk != null ? sk : prevSkill;
// Save the new skill setting in the prefs.
SharedPreferences prefs = getPreferences(0);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("skillLevel", gameSkill.toString());
editor.commit();
// Set the selected skill menu item to the current skill.
selectCurrentSkill();
statusMode.setText(gameSkill.label);
// OK, now get going!
Log.i(TAG, "startGame: " + gameSkill + " (was " + prevSkill + ")");
// If we're going up to master or insane level, set up a message
// to display the user to show him/her the new rules.
int msg = 0;
if (prevSkill != BoardView.Skill.INSANE) {
if (gameSkill == BoardView.Skill.INSANE)
msg = R.string.help_insane;
else if (gameSkill == BoardView.Skill.MASTER
&& prevSkill != BoardView.Skill.MASTER)
msg = R.string.help_master;
}
// If we have a help message to show, show it; the dialog will
// start the game (and hence the clock) when the user is ready.
// Otherwise, start the game now.
if (msg != 0)
new AlertDialog.Builder(this).setMessage(msg)
.setPositiveButton(R.string.button_ok, startGameListener)
.show();
else
setState(State.RUNNING, true);
}
// ******************************************************************** //
// Game State.
// ******************************************************************** //
/**
* Post a state change.
*
* @param which
* The state we want to go into.
*/
void postState(final State which) {
stateHandler.sendEmptyMessage(which.ordinal());
}
private Handler stateHandler = new Handler() {
@Override
public void handleMessage(Message m) {
setState(State.getValue(m.what), true);
}
};
/**
* Set the game state. Set the screen display and start/stop the clock as
* appropriate.
*
* @param state
* The state to go into.
* @param showSplash
* If true, show the "pause" screen if appropriate. Otherwise
* don't.
*/
private void setState(State state, boolean showSplash) {
Log.i(TAG, "setState: " + state + " (was " + gameState + ")");
// If we're not changing state, don't bother.
if (state == gameState)
return;
// Save the previous state, and change.
State prev = gameState;
gameState = state;
// Handle the state change.
switch (gameState) {
case NEW:
case RESTORED:
// Should never get these.
break;
case INIT:
gameTimer.stop();
if (showSplash)
showSplashText(R.string.splash_text);
break;
case SOLVED:
// This is a transient state, just used for signalling a win.
gameTimer.stop();
boardView.setSolved();
// We allow the user to keep playing after it's over, but
// don't keep reporting wins. Also don't brag or record a score
// if the user used the solver.
if (!isSolved && !solverUsed)
reportWin(boardView.unconnectedCells());
isSolved = true;
// Keep running.
gameState = State.RUNNING;
break;
case ABORTED:
// Aborted is followed by something else,
// so don't display anything.
gameTimer.stop();
break;
case PAUSED:
gameTimer.stop();
if (showSplash)
showSplashText(R.string.pause_text);
break;
case RUNNING:
// Set us going, if this is a new game.
if (prev != State.RESTORED && prev != State.PAUSED) {
boardView.setupBoard(gameSkill);
isSolved = false;
clickCount = 0;
prevClickedCell = null;
solverUsed = false;
gameTimer.reset();
updateStatus();
makeSound(Sound.START.soundId);
}
hideSplashText();
if (!isSolved)
gameTimer.start();
break;
}
}
// Create a listener for the user starting a new game.
private final DialogInterface.OnClickListener newGameListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
startGame(null);
}
};
/**
* Report that the user has won the game. Let the user continue to play with
* the layout, or start a new game.
*
* @param unused
* The number of unused cells. Normally zero, but it's sometimes
* possible to solve the board without using all the cable bits.
*/
private void reportWin(int unused) {
// Format the win message.
long time = gameTimer.getTime();
int titleId = R.string.win_title;
String msg;
if (unused != 0) {
String fmt = appResources.getString(R.string.win_spares_text);
msg = String.format(fmt, time / 60000, time / 1000 % 60,
clickCount, unused);
} else {
String fmt = appResources.getString(R.string.win_text);
msg = String
.format(fmt, time / 60000, time / 1000 % 60, clickCount);
}
// See if we have a new high score.
int ntiles = boardView.getBoardWidth() * boardView.getBoardHeight();
String score = registerScore(gameSkill, ntiles, clickCount,
(int) (time / 1000));
if (score != null) {
msg += "\n\n" + score;
titleId = R.string.win_pbest_title;
}
// Display the dialog.
String finish = appResources.getString(R.string.win_finish);
msg += "\n\n" + finish;
new AlertDialog.Builder(this).setTitle(titleId).setMessage(msg)
.setPositiveButton(R.string.win_new, newGameListener)
.setNegativeButton(R.string.win_continue, null).show();
}
// ******************************************************************** //
// User Input.
// ******************************************************************** //
/**
* Called when the activity has detected the user's press of the back key.
* The default implementation simply finishes the current activity, but you
* can override this to do whatever you want.
*
* Note: this is only called automatically on Android 2.0 on. On earlier
* versions, we call this ourselves from BoardView.onKeyDown().
*/
@Override
public void onBackPressed() {
// Go to the home screen. This causes our state to be saved, whereas
// the default of finish() discards it.
Intent homeIntent = new Intent();
homeIntent.setAction(Intent.ACTION_MAIN);
homeIntent.addCategory(Intent.CATEGORY_HOME);
this.startActivity(homeIntent);
return;
}
// ******************************************************************** //
// Status Display.
// ******************************************************************** //
/**
* Update the status line to the current game state.
*/
void updateStatus() {
// Use StringBuilders and a Formatter to avoid allocating new
// String objects every time -- this function is called often!
clicksText.setLength(3);
clicksText.setCharAt(0, (char) ('0' + clickCount / 100 % 10));
clicksText.setCharAt(1, (char) ('0' + clickCount / 10 % 10));
clicksText.setCharAt(2, (char) ('0' + clickCount % 10));
statusClicks.setText(clicksText);
timeText.setLength(5);
int time = (int) (gameTimer.getTime() / 1000);
int min = time / 60;
int sec = time % 60;
timeText.setCharAt(0, (char) ('0' + min / 10));
timeText.setCharAt(1, (char) ('0' + min % 10));
timeText.setCharAt(2, ':');
timeText.setCharAt(3, (char) ('0' + sec / 10));
timeText.setCharAt(4, (char) ('0' + sec % 10));
statusTime.setText(timeText);
}
/**
* Set the status text to the given text message. This hides the game board.
*
* @param msgId
* Resource ID of the message to set.
*/
private void showSplashText(int msgId) {
splashText.setText(msgId);
if (viewSwitcher.getDisplayedChild() != 1) {
// Stop the game.
boardView.surfaceStop();
viewSwitcher.setInAnimation(animSlideInRight);
viewSwitcher.setOutAnimation(animSlideOutRight);
viewSwitcher.setDisplayedChild(1);
}
// Any key dismisses it, so we need focus.
splashText.requestFocus();
}
/**
* Hide the status text, revealing the board.
*/
void hideSplashText() {
if (viewSwitcher.getDisplayedChild() != 0) {
viewSwitcher.setInAnimation(animSlideInLeft);
viewSwitcher.setOutAnimation(animSlideOutLeft);
viewSwitcher.setDisplayedChild(0);
// Start the game -- after the animation.
soundHandler.postDelayed(startRunner, ANIM_TIME);
} else {
// Make sure we're running -- we can get here after a restart.
boardView.surfaceStart();
}
}
private Runnable startRunner = new Runnable() {
@Override
public void run() {
boardView.surfaceStart();
}
};
// ******************************************************************** //
// High Scores.
// ******************************************************************** //
/**
* Check to see if we need to register a new "high score" (personal best).
*
* @param skill
* The skill level of the completed puzzle.
* @param ntiles
* The actual number of tiles in the board. This indicates the
* actual difficulty level on the specific device.
* @param clicks
* The user's click count.
* @param seconds
* The user's time in SECONDS.
* @return Message to display to the user. Null if nothing to report.
*/
private String registerScore(BoardView.Skill skill, int ntiles, int clicks,
int seconds) {
// Get the names of the prefs for the counts for this skill level.
String sizeName = "size" + skill.toString();
String clickName = "clicks" + skill.toString();
String timeName = "time" + skill.toString();
// Get the best to date for this skill level.
SharedPreferences scorePrefs = getSharedPreferences("scores",
MODE_PRIVATE);
int bestClicks = scorePrefs.getInt(clickName, -1);
int bestTime = scorePrefs.getInt(timeName, -1);
// See if we have a new best click count or time.
long now = System.currentTimeMillis();
SharedPreferences.Editor editor = scorePrefs.edit();
String msg = null;
if (clicks > 0 && (bestClicks < 0 || clicks < bestClicks)) {
editor.putInt(sizeName, ntiles);
editor.putInt(clickName, clicks);
editor.putLong(clickName + "Date", now);
msg = appResources.getString(R.string.best_clicks_text);
}
if (seconds > 0 && (bestTime < 0 || seconds < bestTime)) {
editor.putInt(sizeName, ntiles);
editor.putInt(timeName, seconds);
editor.putLong(timeName + "Date", now);
if (msg == null)
msg = appResources.getString(R.string.best_time_text);
else
msg = appResources.getString(R.string.best_both_text);
}
if (msg != null)
editor.commit();
return msg;
}
// ******************************************************************** //
// Sound.
// ******************************************************************** //
/**
* Create a SoundPool containing the app's sound effects.
*/
private SoundPool createSoundPool() {
SoundPool pool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);
for (Sound sound : Sound.values())
sound.soundId = pool.load(this, sound.soundRes, 1);
return pool;
}
/**
* Post a sound to be played on the main app thread.
*
* @param which
* ID of the sound to play.
*/
void postSound(final Sound which) {
soundHandler.sendEmptyMessage(which.soundId);
}
private Handler soundHandler = new Handler() {
@Override
public void handleMessage(Message m) {
makeSound(m.what);
}
};
/**
* Make a sound.
*
* @param soundId
* ID of the sound to play.
*/
void makeSound(int soundId) {
if (soundMode == SoundMode.NONE)
return;
float vol = 1.0f;
if (soundMode == SoundMode.QUIET)
vol = 0.3f;
soundPool.play(soundId, vol, vol, 1, 0, 1f);
}
// ******************************************************************** //
// State Save/Restore.
// ******************************************************************** //
/**
* Save game state so that the user does not lose anything if the game
* process is killed while we are in the background.
*
* @param outState
* A Bundle in which to place any state information we wish to
* save.
*/
private void saveState(Bundle outState) {
// Save the skill level and game state.
outState.putString("gameSkill", gameSkill.toString());
outState.putString("gameState", gameState.toString());
outState.putBoolean("isSolved", isSolved);
// Save the game state of the board.
boardView.saveState(outState);
// Restore the game timer and click count.
gameTimer.saveState(outState);
outState.putInt("clickCount", clickCount);
outState.putBoolean("solverUsed", solverUsed);
}
/**
* Restore our game state from the given Bundle.
*
* @param map
* A Bundle containing the saved state.
* @return true if the state was restored OK; false if the saved state was
* incompatible with the current configuration.
*/
private boolean restoreState(Bundle map) {
// Get the skill level and game state.
gameSkill = Skill.valueOf(map.getString("gameSkill"));
gameState = State.valueOf(map.getString("gameState"));
isSolved = map.getBoolean("isSolved");
// Restore the state of the game board.
boolean restored = boardView.restoreState(map, gameSkill);
// Restore the game timer and click count.
if (restored) {
restored = gameTimer.restoreState(map, false);
clickCount = map.getInt("clickCount");
solverUsed = map.getBoolean("solverUsed");
}
return restored;
}
// ******************************************************************** //
// Private Types.
// ******************************************************************** //
// This class implements the game clock. All it does is update the
// status each tick.
private final class GameTimer extends Timer {
GameTimer() {
// Tick every 0.25 s.
super(250);
}
@Override
protected boolean step(int count, long time) {
updateStatus();
// Run until explicitly stopped.
return false;
}
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Debugging tag.
private static final String TAG = "netscramble";
// Time in ms for slide in/out animations.
private static final int ANIM_TIME = 500;
// ******************************************************************** //
// Member Data.
// ******************************************************************** //
// The app's resources.
private Resources appResources;
// The game board.
private BoardView boardView = null;
// The status bar, consisting of 3 status fields.
private TextView statusClicks;
private TextView statusMode;
private TextView statusTime;
// Text buffers used to format the click count and time. We allocate
// these here, so we don't allocate new String objects every time
// we update the status -- which is very often.
private StringBuilder clicksText;
private StringBuilder timeText;
// Sound pool used for sound effects.
private SoundPool soundPool;
// The text widget used to display status messages. When visible,
// it covers the board.
private TextView splashText = null;
// View switcher used to switch between the splash text and
// board view.
private ViewAnimator viewSwitcher = null;
// Animations for the view switcher.
private TranslateAnimation animSlideInLeft;
private TranslateAnimation animSlideOutLeft;
private TranslateAnimation animSlideInRight;
private TranslateAnimation animSlideOutRight;
// The menu used to select the skill level. We keep this so we can
// set the selected item.
private Menu mainMenu;
// The state of the current game.
private State gameState;
// When gameState == State.RESTORED, this is our restored game state.
private State restoredGameState;
// Flag whether the board has been solved. Once solved, the user
// can keep playing, but we don't count score any more.
private boolean isSolved;
// The currently selected skill level.
private BoardView.Skill gameSkill;
// Timer used to time the game.
private GameTimer gameTimer;
// Current sound mode.
private SoundMode soundMode;
// True to enable the network animation.
private boolean animEnable;
// Number of times the user has clicked.
private int clickCount = 0;
// The previous cell that was clicked. Used to detect multiple clicks
// on the same cell.
private Cell prevClickedCell = null;
// Flag if the user has invoked the auto-solver for this game.
private boolean solverUsed = false;
}
| 47,192 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Cell.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/Scrambled Net/src/com/silentservices/netscramble/Cell.java | /**
* NetScramble: unscramble a network and connect all the terminals.
* The player is given a network diagram with the parts of the network
* randomly rotated; he/she must rotate them to connect all the terminals
* to the server.
*
* This is an Android implementation of the KDE game "knetwalk" by
* Andi Peredri, Thomas Nagy, and Reinhold Kainhofer.
*
* © 2007-2010 Ian Cameron Smith <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package com.silentservices.netscramble;
import java.security.SecureRandom;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
/**
* This class implements a cell in the game board. It handles the logic and
* state of the cell, and implements the visible view of the cell.
*/
class Cell {
// ******************************************************************** //
// Public Types.
// ******************************************************************** //
/**
* Define the connected direction combinations. The enum is carefully
* organised so that the ordinal() of each value is a bitmask representing
* the connected directions. This allows us to manipulate directions more
* easily.
*
* Each enum value also stores the ID of the bitmap representing it, or zero
* if none. Note that this is the bitmap for the cabling layer, not the
* background or foreground (terminal etc).
*/
enum Dir {
FREE(0), // Unconnected cell.
___L(R.drawable.cable0001), __D_(R.drawable.cable0010), __DL(
R.drawable.cable0011), _R__(R.drawable.cable0100), _R_L(
R.drawable.cable0101), _RD_(R.drawable.cable0110), _RDL(
R.drawable.cable0111), U___(R.drawable.cable1000), U__L(
R.drawable.cable1001), U_D_(R.drawable.cable1010), U_DL(
R.drawable.cable1011), UR__(R.drawable.cable1100), UR_L(
R.drawable.cable1101), URD_(R.drawable.cable1110), URDL(
R.drawable.cable1111), NONE(0); // Not a cell.
Dir(int img) {
imageId = img;
}
private static Dir getDir(int bits) {
return dirs[bits];
}
static final Dir[] dirs = values();
static final Dir[] cardinals = { ___L, __D_, _R__, U___ };
static final int[][] cardinalOffs = { { -1, 0 }, // ___L
{ 0, 1 }, // __D_
{ 1, 0 }, // _R__
{ 0, -1 }, // U___
};
// The direction which is the reverse of this one.
Dir reverse = null;
static {
U___.reverse = __D_;
_R__.reverse = ___L;
__D_.reverse = U___;
___L.reverse = _R__;
}
final int imageId;
private Bitmap normalImg = null;
private Bitmap greyImg = null;
}
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Set up this cell.
*
* @param parent
* Parent application context.
* @param board
* This cell's parent board.
* @param x
* This cell's x-position in the board grid.
* @param y
* This cell's y-position in the board grid.
*/
Cell(NetScramble parent, BoardView board, int x, int y) {
xindex = x;
yindex = y;
// Create the temp. objects used in drawing.
cellLeft = 0;
cellTop = 0;
cellWidth = 0;
cellHeight = 0;
cellPaint = new Paint();
// Reset the cell's state.
reset(Dir.NONE);
}
// ******************************************************************** //
// Image Setup.
// ******************************************************************** //
/**
* Initialise the pixmaps used by the Cell class.
*
* @param res
* Handle on the application resources.
* @param width
* The cell width.
* @param height
* The cell height.
* @param config
* The pixel format of the surface.
*/
static void initPixmaps(Resources res, int width, int height,
Bitmap.Config config) {
// Load all the cable pixmaps.
for (Dir d : Dir.dirs) {
if (d.imageId == 0)
continue;
// Load the pixmap for this cable configuration. Scale it to the
// right size.
Bitmap base = BitmapFactory.decodeResource(res, d.imageId);
Bitmap pixmap = Bitmap
.createScaledBitmap(base, width, height, true);
d.normalImg = pixmap;
// Create a greyed-out version of the image for the
// disconnected version of the node.
d.greyImg = greyOut(pixmap, config);
}
// Load the other pixmaps we use.
for (Image i : Image.values()) {
Bitmap base = BitmapFactory.decodeResource(res, i.resid);
Bitmap pixmap = Bitmap
.createScaledBitmap(base, width, height, true);
i.bitmap = pixmap;
}
}
/**
* Create a greyed-out version of the given pixmap.
*
* @param pixmap
* Base pixmap.
* @param config
* The pixel format of the surface.
* @return Greyed-out version of this pixmap.
*/
private static Bitmap greyOut(Bitmap pixmap, Bitmap.Config config) {
// Get the pixel data from the pixmap.
int w = pixmap.getWidth();
int h = pixmap.getHeight();
int[] pixels = new int[w * h];
pixmap.getPixels(pixels, 0, w, 0, 0, w, h);
// Grey-out the image in the pixel data.
for (int y = 0; y < h; ++y) {
for (int x = 0; x < w; ++x) {
int pix = pixels[y * w + x];
int r = (3 * Color.red(pix)) / 5 + 100;
int g = (3 * Color.green(pix)) / 5 + 100;
int b = (3 * Color.blue(pix)) / 5 + 100;
pixels[y * w + x] = Color.argb(Color.alpha(pix), r, g, b);
}
}
// Create and return a pixmap from the greyed-out pixel data.
return Bitmap.createBitmap(pixels, w, h, Bitmap.Config.ARGB_8888);
}
// ******************************************************************** //
// Public Methods.
// ******************************************************************** //
/**
* Reset the state of this cell, and set the cell's isConnected directions
* to the given value.
*
* @param d
* Connection directions to set for the cell.
*/
void reset(Dir d) {
connectedDirs = d;
isConnected = false;
isFullyConnected = false;
isRoot = false;
isLocked = false;
isBlind = false;
rotateTarget = 0;
rotateStart = 0;
rotateAngle = 0;
highlightOn = false;
highlightStart = 0;
highlightPos = 0;
blipsIncoming = 0;
blipsOutgoing = 0;
blipsTransfer = 0;
haveFocus = false;
invalidate();
}
// ******************************************************************** //
// Geometry.
// ******************************************************************** //
/**
* This is called during layout when the size of this view has changed. This
* is where we first discover our window size, so set our geometry to match.
*
* @param left
* Left X co-ordinate of this cell in the view.
* @param top
* Top Y co-ordinate of this cell in the view.
* @param width
* Current width of this view.
* @param height
* Current height of this view.
*/
protected void setGeometry(int left, int top, int width, int height) {
cellLeft = left;
cellTop = top;
cellWidth = width;
cellHeight = height;
invalidate();
}
// ******************************************************************** //
// Basic Cell Info.
// ******************************************************************** //
/**
* Get the x-position of this cell in the game board.
*
* @return The x-position of this cell in the game board.
*/
int x() {
return xindex;
}
/**
* Get the y-position of this cell in the game board.
*
* @return The y-position of this cell in the game board.
*/
int y() {
return yindex;
}
// ******************************************************************** //
// Neighbouring Cell Tracking.
// ******************************************************************** //
/**
* Set the cell's neighbours in the game matrix. A neighbour may be null if
* there is no neighbour in that direction. If wrapping is enabled, the
* neighbour setup should reflect this.
*
* This information can change between games, due to board size and wrapping
* changes.
*
* @param u
* Neighbouring cell up from this one.
* @param d
* Neighbouring cell down from this one.
* @param l
* Neighbouring cell left from this one.
* @param r
* Neighbouring cell right from this one.
*/
void setNeighbours(Cell u, Cell d, Cell l, Cell r) {
nextU = u;
nextD = d;
nextL = l;
nextR = r;
}
/**
* Get the neighbouring cell in the given direction from this cell.
*
* @param d
* The direction to look in.
* @return The next cell in the given direction; may be null, or may
* actually be at the other edge of the board if wrapping is on.
*/
Cell next(Dir d) {
switch (d) {
case U___:
return nextU;
case _R__:
return nextR;
case __D_:
return nextD;
case ___L:
return nextL;
default:
throw new RuntimeException("Cell.next() called with bad dir");
}
}
// ******************************************************************** //
// Connection State.
// ******************************************************************** //
/**
* Return the directions that this cell is connected to, outwards (ie.
* ignoring whether there is a matching inward connection in the next cell).
*
* @return The directions that this cell is connected to, outwards.
*/
Dir dirs() {
return connectedDirs;
}
/**
* Return the directions that this cell would be connected to, outwards, if
* it was rotated in the given direction.
*
* @param a
* The angle in degrees to rotate to; clockwise positive.
* @return The directions that this cell is connected to, outwards.
*/
Dir rotatedDirs(int a) {
int bits = connectedDirs.ordinal();
if (a == 90)
bits = ((bits & 0x01) << 3) | ((bits & 0x0e) >> 1);
else if (a == -90)
bits = ((bits & 0x08) >> 3) | ((bits & 0x07) << 1);
else if (a == 180 || a == -180)
bits = ((bits & 0x0c) >> 2) | ((bits & 0x03) << 2);
else
return null;
return Dir.getDir(bits);
}
/**
* Query whether this cell has a connection in the given direction(s).
*
* @param d
* Direction(s) to check.
* @return true iff the cell is connected in all the given directions; else
* false.
*/
boolean hasConnection(Dir d) {
return !isRotated()
&& (connectedDirs.ordinal() & d.ordinal()) == d.ordinal();
}
/**
* Determine how many connections this cell has outwards (ie. ignoring
* whether there is a matching inward connection in the next cell).
*
* @return The number of outward connections from this cell.
*/
int numDirs() {
if (connectedDirs == Dir.NONE)
return 0;
int bits = connectedDirs.ordinal();
int n = 0;
for (int i = 0; i < 4; ++i) {
n += bits & 0x01;
bits >>= 1;
}
return n;
}
/**
* Add the given direction as a direction this cell is connected to,
* outwards (ie. no attempt is made to make the reciprocal connection in the
* other cell).
*
* @param d
* New connected direction to add for this cell.
*/
void addDir(Dir d) {
int bits = connectedDirs.ordinal();
if ((bits & d.ordinal()) == d.ordinal())
return;
bits |= d.ordinal();
setDirs(Dir.getDir(bits));
}
/**
* Set the connected directions of this cell to the given value.
*
* @param d
* New connected directions for this cell.
*/
void setDirs(Dir d) {
if (d == connectedDirs)
return;
connectedDirs = d;
invalidate();
}
// ******************************************************************** //
// Display Options.
// ******************************************************************** //
/**
* Set the "root" flag on this cell. The root cell displays the server
* image.
*
* @param b
* New "root" flag for this cell.
*/
void setRoot(boolean b) {
if (isRoot == b)
return;
isRoot = b;
invalidate();
}
/**
* Set this cell's "blind" flag. A blind cell doesn't display its
* connections; it does display the server or terminal if appropriate. This
* is used to make the game harder.
*
* @param b
* The new "blind" flag (true = blind).
*/
void setBlind(boolean b) {
if (b != isBlind) {
isBlind = b;
invalidate();
}
}
/**
* Rotate this cell right now -- no animation. This is used during restore,
* when we need to adjust the state of the board for device rotations, not
* during play.
*
* @param a
* The angle in degrees to rotate to; clockwise positive.
*/
void rotateImmediate(int a) {
setDirs(rotatedDirs(a));
invalidate();
}
/**
* Determine whether this cell's "locked" flag is set.
*
* @return This cell's "locked" flag.
*/
boolean isLocked() {
return isLocked;
}
/**
* Set the "locked" flag on this cell. A locked cell is marked by a
* highlighted background.
*
* @param b
* New "locked" flag for this cell.
*/
void setLocked(boolean newlocked) {
if (isLocked == newlocked)
return;
isLocked = newlocked;
invalidate();
}
/**
* Determine whether this cell's "connected" flag is set.
*
* @return This cell's "connected" flag.
*/
boolean isConnected() {
return isConnected;
}
/**
* Set this cell's "connected" flag; this determines how the cell is
* displayed (cables are greyed-out if not connected).
*
* @param b
* New "connected" flag for this cell.
*/
void setConnected(boolean b) {
if (isConnected == b)
return;
isConnected = b;
invalidate();
}
/**
* Set this cell's "fully connected" flag; this determines how the cell is
* displayed. For the server, this is used to indicate victory.
*
* @param b
* New "fully connected" flag for this cell.
*/
void setSolved(boolean b) {
if (isFullyConnected == b)
return;
isFullyConnected = b;
invalidate();
}
/**
* Set whether this cell is focused or not.
*
* This is part of our own focus system; we don't use the system focus, as
* there's no way to make it wrap correctly in a dynamic layout.
* (focusSearch() isn't called.)
*/
void setFocused(boolean focused) {
// We do our own focus highlight in onDraw(), so when the focus
// state changes, we have to redraw.
haveFocus = focused;
invalidate();
}
/**
* Add a data blip on the incoming connection in the given direction, if we
* have one.
*
* @param d
* Direction the blip is in, from our point of view.
*/
void setBlip(Dir d) {
if (hasConnection(d))
blipsIncoming |= d.ordinal();
}
// ******************************************************************** //
// Animation Handling.
// ******************************************************************** //
/**
* Move the rotation currentAngle for this cell. This changes the cell's
* idea of its connections, and with fractions of 90 degrees, is used to
* animate rotation of the cell's connections. Setting this causes the
* cell's connections to be drawn at the given currentAngle; beyond +/- 45
* degrees, the connections are changed in accordance with the direction the
* cell is now facing.
*
* @param a
* The angle in degrees to rotate to; clockwise positive.
*/
void rotate(int a) {
rotate(a, ROTATE_DFLT_TIME);
}
/**
* Move the rotation currentAngle for this cell. This changes the cell's
* idea of its connections, and with fractions of 90 degrees, is used to
* animate rotation of the cell's connections. Setting this causes the
* cell's connections to be drawn at the given currentAngle; beyond +/- 45
* degrees, the connections are changed in accordance with the direction the
* cell is now facing.
*
* @param a
* The angle in degrees to rotate to; clockwise positive.
* @param time
* Time in ms over which to do the rotation.
*/
void rotate(int a, long time) {
// If we're not already rotating, set it up.
if (rotateTarget == 0) {
rotateStart = System.currentTimeMillis();
rotateAngle = 0f;
rotateTime = time;
}
// Add the given rotation in.
rotateTarget += a;
// All data blips are lost.
blipsIncoming = 0;
blipsOutgoing = 0;
blipsTransfer = 0;
}
/**
* Query whether this cell is currently rotated off the orthogonal.
*
* @return true iff the cell is not at its base angle.
*/
boolean isRotated() {
return rotateTarget != 0;
}
/**
* Set the highlight state of the cell.
*/
void doHighlight() {
// If one is currently running, just start over.
highlightOn = true;
highlightStart = System.currentTimeMillis();
highlightPos = 0;
}
/**
* Update the state of the application for the current frame.
*
* <p>
* Applications must override this, and can use it to update for example the
* physics of a game. This may be a no-op in some cases.
*
* <p>
* doDraw() will always be called after this method is called; however, the
* converse is not true, as we sometimes need to draw just to update the
* screen. Hence this method is useful for updates which are dependent on
* time rather than frames.
*
* @param now
* Current time in ms.
* @return true if this cell changed its connection state.
*/
protected boolean doUpdate(long now) {
// Flag if we changed our connection state.
boolean changed = false;
// If we've got a rotation going on, move it on.
if (rotateTarget != 0) {
// Calculate the angle based on how long we've been going.
rotateAngle = (float) (now - rotateStart) / (float) rotateTime
* 90f;
if (rotateTarget < 0)
rotateAngle = -rotateAngle;
// If we've gone past 90 degrees, change the connected directions.
// Rotate the directions bits (the bottom 4 bits of the ordinal)
// right or left, as appropriate.
if (Math.abs(rotateAngle) >= 90f) {
Dir dir = null;
if (rotateTarget > 0) {
dir = rotatedDirs(90);
if (rotateAngle >= rotateTarget)
rotateAngle = rotateTarget = 0f;
else {
rotateAngle -= 90f;
rotateTarget -= 90f;
rotateStart += rotateTime;
}
} else {
dir = rotatedDirs(-90);
if (rotateAngle <= rotateTarget)
rotateAngle = rotateTarget = 0f;
else {
rotateAngle += 90f;
rotateTarget += 90f;
rotateStart += rotateTime;
}
}
setDirs(dir);
changed = true;
}
invalidate();
}
// If there's a highlight showing, advance it.
if (highlightOn) {
// Calculate the position based on how long we've been going.
float frac = (float) (now - highlightStart)
/ (float) HIGHLIGHT_TIME;
highlightPos = (int) (frac * cellWidth * 2);
// See if we're done.
if (highlightPos >= cellWidth * 2) {
highlightOn = false;
highlightStart = 0;
highlightPos = 0;
}
invalidate();
}
return changed;
}
/**
* Move on all the data blips one step, i.e. half a cell width. This steps
* them from whichever connection leg they're on to the next one.
*
* @param count
* Blip generation count.
*/
void advanceBlips(int count) {
// See which outgoing blips need to be transferred onto the next
// cell. Accumulate their directions in blipsTransfer.
blipsTransfer = 0;
for (int c = 0; c < Dir.cardinals.length; ++c) {
Dir d = Dir.cardinals[c];
int ord = d.ordinal();
if ((blipsOutgoing & ord) != 0 && hasConnection(d))
blipsTransfer |= ord;
}
blipsOutgoing = 0;
// All incoming blips get deleted, and become outgoing blips on
// whatever directions did not have incoming blips.
if (blipsIncoming != 0) {
for (int c = 0; c < Dir.cardinals.length; ++c) {
Dir d = Dir.cardinals[c];
int ord = d.ordinal();
if ((blipsIncoming & ord) == 0 && hasConnection(d))
blipsOutgoing |= ord;
}
}
blipsIncoming = 0;
// If we're the server, create new outgoing blips once in a while.
if (isRoot && count % 6 == 0) {
for (int c = 0; c < Dir.cardinals.length; ++c) {
Dir d = Dir.cardinals[c];
int ord = d.ordinal();
if (hasConnection(d))
blipsOutgoing |= ord;
}
}
// Note that we don't invalidate(). Blips are drawn directly to
// the screen in a separate pass.
}
/**
* Pass on all blips which were outgoing onto their next cell.
*/
void transferBlips() {
for (int c = 0; c < Dir.cardinals.length; ++c) {
Dir d = Dir.cardinals[c];
int ord = d.ordinal();
if ((blipsTransfer & ord) != 0) {
Cell n = next(d);
if (n != null)
n.setBlip(d.reverse);
}
}
blipsTransfer = 0;
// Note that we don't invalidate(). Blips are drawn directly to
// the screen in a separate pass.
}
// ******************************************************************** //
// Cell Drawing.
// ******************************************************************** //
/**
* Set this cell's state to be invalid, forcing a redraw.
*/
void invalidate() {
stateValid = false;
}
/**
* This method is called to ask the cell to draw itself. Note that this
* draws the cell but not any data blips, which are drawn separately.
*
* @param canvas
* Canvas to draw into.
* @param now
* Current time in ms.
*/
protected void doDraw(Canvas canvas, long now) {
// Nothing to do if we're up to date.
if (stateValid)
return;
final int sx = cellLeft;
final int sy = cellTop;
final int ex = sx + cellWidth;
final int ey = sy + cellHeight;
final int midx = sx + cellWidth / 2;
final int midy = sy + cellHeight / 2;
canvas.save();
canvas.clipRect(sx, sy, ex, ey);
cellPaint.setStyle(Paint.Style.STROKE);
cellPaint.setColor(0xff000000);
// Draw the background tile.
{
Image bgImage = Image.BG;
if (connectedDirs == Dir.NONE)
bgImage = Image.NOTHING;
else if (connectedDirs == Dir.FREE)
bgImage = Image.EMPTY;
else if (isLocked)
bgImage = Image.LOCKED;
canvas.drawBitmap(bgImage.bitmap, sx, sy, null);
}
// Draw the highlight band, if active.
if (highlightOn) {
cellPaint.setStyle(Paint.Style.STROKE);
cellPaint.setStrokeWidth(5f);
cellPaint.setColor(Color.WHITE);
if (highlightPos < cellWidth)
canvas.drawLine(sx, sy + highlightPos, sx + highlightPos, sy,
cellPaint);
else {
int hp = highlightPos - cellWidth;
canvas.drawLine(sx + hp, ey, ex, sy + hp, cellPaint);
}
}
// If we're not empty, draw the cables / equipment.
if (connectedDirs != Dir.FREE && connectedDirs != Dir.NONE) {
if (!isBlind) {
// We need to rotate the drawing matrix if the cable is
// rotated.
canvas.save();
if (rotateTarget != 0)
canvas.rotate(rotateAngle, midx, midy);
// Draw the cable pixmap.
Bitmap pixmap = isConnected ? connectedDirs.normalImg
: connectedDirs.greyImg;
canvas.drawBitmap(pixmap, sx, sy, null);
canvas.restore();
}
// Draw the equipment (terminal, server) if any.
{
Image equipImage = null;
if (isRoot) {
if (isFullyConnected)
equipImage = Image.SERVER1;
else
equipImage = Image.SERVER;
} else if (numDirs() == 1) {
if (isConnected)
equipImage = Image.COMP2;
else
equipImage = Image.COMP1;
}
if (equipImage != null)
canvas.drawBitmap(equipImage.bitmap, sx, sy, null);
}
}
// If this is the focused cell, indicate this by drawing a red
// border around it.
if (haveFocus) {
cellPaint.setStyle(Paint.Style.STROKE);
cellPaint.setColor(0x60ff0000);
cellPaint.setStrokeWidth(cellWidth / 8);
canvas.drawRect(sx, sy, ex - 1, ey - 1, cellPaint);
}
canvas.restore();
stateValid = true;
}
/**
* This method is called to ask the cell to draw its active data blips. This
* happens in a separate pass, so that blips which are in transition from
* one cell to another don't get cropped by the drawing of the next cell.
*
* @param canvas
* Canvas to draw into.
* @param now
* Current time in ms.
* @param frac
* Fractional position of the data blips, if any, along whatever
* connection leg they're on.
*/
protected void doDrawBlips(Canvas canvas, long now, float frac) {
// Normal cable sections and the server get blips, including the
// section of cable going into a terminal cell. Otherwise, terminals
// get special treatment.
if (isRoot || numDirs() > 1 || (numDirs() == 1 && frac < 0.3f))
drawBlips(canvas, now, frac);
else
drawTermData(canvas, now, frac);
}
/**
* This method is called to ask the cell to draw its active data blips. This
* happens in a separate pass, so that blips which are in transition from
* one cell to another don't get cropped by the drawing of the next cell.
*
* @param canvas
* Canvas to draw into.
* @param now
* Current time in ms.
* @param frac
* Fractional position of the data blips, if any, along whatever
* connection leg they're on.
*/
private void drawBlips(Canvas canvas, long now, float frac) {
// We don't check stateValid. Blips are always drawn.
// But if this cell's wiring is invisible, then its blips need
// to be too.
if (isBlind)
return;
final int sx = cellLeft;
final int sy = cellTop;
// Note that we don't do any clipping. A blip which is passing
// from one cell to another needs to be drawn overlapping both
// cells.
// Now draw in all blips. We use "glow-in" / "glow-out" images
// for the server; otherwise blips, whose colour depends on whether
// this cell is connected.
final Image[] blips = isRoot ? BLIP_T_IMAGES
: isConnected ? BLIP_IMAGES : BLIP_G_IMAGES;
final int nblips = blips.length;
int indexIn = Math.round((float) (nblips - 1) * frac) % nblips;
if (indexIn < 0)
indexIn = 0;
int indexOut = Math.round((float) (nblips - 1) * (1 - frac)) % nblips;
if (indexOut < 0)
indexOut = 0;
for (int c = 0; c < Dir.cardinals.length; ++c) {
Dir d = Dir.cardinals[c];
int ord = d.ordinal();
final int xoff = Dir.cardinalOffs[c][0];
final int yoff = Dir.cardinalOffs[c][1];
if ((blipsIncoming & ord) != 0) {
final float inp = (1.0f - frac) * cellWidth / 2f;
final float x = sx + xoff * inp;
final float y = sy + yoff * inp;
Image blipImage = blips[indexIn];
canvas.drawBitmap(blipImage.bitmap, x, y, cellPaint);
}
if ((blipsOutgoing & ord) != 0) {
final float outp = frac * cellWidth / 2f;
final float x = sx + xoff * outp;
final float y = sy + yoff * outp;
Image blipImage = blips[indexOut];
canvas.drawBitmap(blipImage.bitmap, x, y, cellPaint);
}
}
}
/**
* This method is called to ask the cell to draw its active data blips. This
* happens in a separate pass, so that blips which are in transition from
* one cell to another don't get cropped by the drawing of the next cell.
*
* @param canvas
* Canvas to draw into.
* @param now
* Current time in ms.
* @param frac
* Fractional position of the data blips, if any, along whatever
* connection leg they're on.
*/
private void drawTermData(Canvas canvas, long now, float frac) {
// We don't check stateValid. Blips are always drawn.
// If this cell is invisible or not connected, or there's no
// blip, then nothing gets drawn.
if (isBlind || !isConnected || blipsIncoming == 0)
return;
final int sx = cellLeft;
final int sy = cellTop;
cellPaint.setStyle(Paint.Style.STROKE);
cellPaint.setStrokeWidth(1f);
cellPaint.setColor(0xff00ff00);
for (float y = cellHeight / 3f; y < cellHeight * 0.55f; y += 2f) {
float l = cellWidth / 3f;
float r = cellWidth / 3f * rng.nextFloat() + cellWidth / 3f;
canvas.drawLine(sx + l, sy + y, sx + r, sy + y, cellPaint);
}
}
// ******************************************************************** //
// State Save/Restore.
// ******************************************************************** //
/**
* Save the game state of this cell, as part of saving the overall game
* state.
*
* @return A Bundle containing the saved state.
*/
Bundle saveState() {
Bundle map = new Bundle();
// Save the aspects of the state which aren't part of the board
// configuration (that gets re-created on reload).
map.putString("connectedDirs", connectedDirs.toString());
map.putFloat("currentAngle", rotateAngle);
map.putInt("highlightPos", highlightPos);
map.putBoolean("isConnected", isConnected);
map.putBoolean("isFullyConnected", isFullyConnected);
map.putBoolean("isBlind", isBlind);
map.putBoolean("isRoot", isRoot);
map.putBoolean("isLocked", isLocked);
// Note: we don't save the focus state; focus save and restore
// is done in BoardView.
return map;
}
/**
* Restore the game state of this cell from the given Bundle, as part of
* restoring the overall game state.
*
* @param map
* A Bundle containing the saved state.
*/
void restoreState(Bundle map) {
connectedDirs = Dir.valueOf(map.getString("connectedDirs"));
rotateAngle = map.getFloat("currentAngle");
highlightPos = map.getInt("highlightPos");
isConnected = map.getBoolean("isConnected");
isFullyConnected = map.getBoolean("isFullyConnected");
isBlind = map.getBoolean("isBlind");
isRoot = map.getBoolean("isRoot");
isLocked = map.getBoolean("isLocked");
// Phew! Time for a redraw... but we'll invalidate() at the
// board level.
}
// ******************************************************************** //
// Private Types.
// ******************************************************************** //
/**
* This enumeration defines the images, other than the cable images, which
* we use.
*/
private enum Image {
NOTHING(R.drawable.nothing), EMPTY(R.drawable.empty), LOCKED(
R.drawable.background_locked), BG(R.drawable.background), COMP1(
R.drawable.computer1), COMP2(R.drawable.computer2), SERVER(
R.drawable.server), SERVER1(R.drawable.server1), BLIP_T01(
R.drawable.blip_t01), BLIP_T03(R.drawable.blip_t03), BLIP_T05(
R.drawable.blip_t05), BLIP_T07(R.drawable.blip_t07), BLIP_T08(
R.drawable.blip_t08), BLIP_T09(R.drawable.blip_t09), BLIP_T10(
R.drawable.blip_t10), BLOB_14(R.drawable.blob_14), BLOB_15(
R.drawable.blob_15), BLOB_16(R.drawable.blob_16), BLOB_17(
R.drawable.blob_17), BLOB_18(R.drawable.blob_18), BLOB_19(
R.drawable.blob_19), BLOB_20(R.drawable.blob_20), BLOBG_14(
R.drawable.blob_g_14), BLOBG_15(R.drawable.blob_g_15), BLOBG_16(
R.drawable.blob_g_16), BLOBG_17(R.drawable.blob_g_17), BLOBG_18(
R.drawable.blob_g_18), BLOBG_19(R.drawable.blob_g_19), BLOBG_20(
R.drawable.blob_g_20);
private Image(int r) {
resid = r;
}
public final int resid;
public Bitmap bitmap = null;
}
// Images to show network data blips.
private static final Image[] BLIP_IMAGES = { Image.BLOB_14, Image.BLOB_15,
Image.BLOB_16, Image.BLOB_17, Image.BLOB_18, Image.BLOB_19,
Image.BLOB_20, };
// Images to show network data blips.
private static final Image[] BLIP_G_IMAGES = { Image.BLOBG_14,
Image.BLOBG_15, Image.BLOBG_16, Image.BLOBG_17, Image.BLOBG_18,
Image.BLOBG_19, Image.BLOBG_20, };
// Images to show network data blips arriving at a terminal.
private static final Image[] BLIP_T_IMAGES = { Image.BLIP_T01,
Image.BLIP_T03, Image.BLIP_T05, Image.BLIP_T07, Image.BLIP_T08,
Image.BLIP_T09, Image.BLIP_T10, };
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Debugging tag.
@SuppressWarnings("unused")
private static final String TAG = "netscramble";
// Default time taken to rotate a cell, in ms.
private static final long ROTATE_DFLT_TIME = 250;
// Time taken to display a highlight flash, in ms.
private static final long HIGHLIGHT_TIME = 200;
// Random number generator for the game. We use a Mersenne Twister,
// which is a high-quality and fast implementation of java.util.Random.
// private static final Random rng = new MTRandom();
private static final SecureRandom rng = new SecureRandom();
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The cell's position in the board.
private final int xindex, yindex;
// Our neighbouring cells up, down, left and right. This changes
// from game to game as each skill level has its own board size
// and may or may not wrap. null if there is no neighbour in that
// direction.
private Cell nextU;
private Cell nextD;
private Cell nextL;
private Cell nextR;
// True iff this cell has the focus.
private boolean haveFocus;
// The directions in which this cell is isConnected. This is set up
// at the start of each game.
private Dir connectedDirs;
// If we're currently rotating, the rotation target angle -- clockwise
// positive, anti negative; the time in ms at which we started;
// and the current angle in degrees. rotateDirection == 0 if not
// rotating.
private float rotateTarget = 0;
private long rotateStart = 0;
private float rotateAngle = 0f;
// Duration of the current rotation, in ms.
private long rotateTime = 250;
// Status information for the highlight band across the cell.
// This is used to draw a diagonal band of highlightPos flicking across the
// cell, to highlight it when it is mis-clicked etc.
// Flag whether there is a highlight currently showing; and if so,
// the time in ms at which it started, and its current position across
// the cell. The range of the latter is zero to cellWidth * 2.
private boolean highlightOn = false;
private long highlightStart = 0;
private int highlightPos;
// Blips drawn over the network to indicate the flow of data. A
// blip moving in towards the centre of the cell is incoming; one
// moving out is outgoing. An incoming blip becomes outgoing when
// it hits the centre. Each connection direction can have one
// blip on it, so we use bitmasks to track where blips are: each of
// these values is just a bitmaps of which directions have a blip,
// incoming or outgoing respectively.
private int blipsIncoming = 0;
private int blipsOutgoing = 0;
// During a blip calculation pass, this value accumulates the data
// blips that need to be passed on to other cells.
private int blipsTransfer = 0;
// True iff the cell is currently isConnected (directly or not)
// to the server. This causes it to be displayed dark (not grey).
private boolean isConnected;
// True iff the cell is currently part of a fully connected network --
// in other words, a solved puzzle. This may cause it to be displayed
// differently; e.g. the server shows green LEDs.
private boolean isFullyConnected;
// True iff the cell is blind; ie. doesn't display its connections.
// This is a difficulty factor.
private boolean isBlind;
// True iff this is the root cell of the network; ie. the server.
private boolean isRoot;
// True iff the cell has been isLocked by the user; this causes the
// background to be highlighted.
private boolean isLocked;
// Cell's left X co-ordinate.
private int cellLeft;
// Cell's top Y co-ordinate.
private int cellTop;
// Cell's current width.
private int cellWidth;
// Cell's current height.
private int cellHeight;
// Painter used in onDraw().
private Paint cellPaint;
// True if the cell's rendered state is up to date.
private boolean stateValid = false;
}
| 36,134 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
BoardView.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/Scrambled Net/src/com/silentservices/netscramble/BoardView.java | /**
* NetScramble: unscramble a network and connect all the terminals.
* The player is given a network diagram with the parts of the network
* randomly rotated; he/she must rotate them to connect all the terminals
* to the server.
*
* This is an Android implementation of the KDE game "knetwalk" by
* Andi Peredri, Thomas Nagy, and Reinhold Kainhofer.
*
* © 2007-2010 Ian Cameron Smith <[email protected]>
*
* © 2014 Michael Mueller <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package com.silentservices.netscramble;
import java.security.SecureRandom;
import java.util.EnumMap;
import java.util.LinkedList;
import java.util.Vector;
import org.hermit.android.core.SurfaceRunner;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.WindowManager;
import com.silentservices.netscramble.NetScramble.Sound;
import com.silentservices.netscramble.NetScramble.State;
/**
* This implements the game board by laying out a grid of Cell objects.
*
* Unlike the original knetwalk, we have to deal with a physical display whose
* size can vary dramatically, but which we would like to fill; on the other
* hand, it may be too small for a "full-sized" game, particularly bearing in
* mind the minimum size a cell can be and still allow a finger to select it. We
* therefore put a lot of work into figuring out how big the board should be.
*/
public class BoardView extends SurfaceRunner {
// ******************************************************************** //
// Configuration Constants.
// ******************************************************************** //
/**
* The minimum cell size in pixels.
*/
private static final int CELL_MIN = 28;
/**
* The maximum cell size in pixels.
*/
private static final int CELL_MAX = 500;
// ******************************************************************** //
// Public Types.
// ******************************************************************** //
/**
* Enumeration defining a game skill level. Each enum member also stores the
* configuration parameters for that skill level. We also introduce the
* wrinkle of blind tiles, to make an insane level:
*/
enum Skill {
// Name id brch wrap blind
NOVICE(R.string.skill_novice, R.id.skill_novice, 2, false, 9), NORMAL(
R.string.skill_normal, R.id.skill_normal, 2, false, 9), EXPERT(
R.string.skill_expert, R.id.skill_expert, 2, false, 9), MASTER(
R.string.skill_master, R.id.skill_master, 3, true, 9), INSANE(
R.string.skill_insane, R.id.skill_insane, 3, true, 3);
private Skill(int lab, int i, int br, boolean w, int bd) {
label = lab;
id = i;
branches = br;
wrapped = w;
blind = bd;
}
public final int label; // Res. ID of the label for this skill.
public final int id; // Numeric ID for this skill level.
public final int branches; // Max branches off each square; at least 2.
public final boolean wrapped; // If true, network wraps around the
// edges.
public final int blind; // Squares with this many or more
// connections are blind.
}
/**
* This enum defines the board sizes for the supported screen layouts.
* Traditional knetwalk has these board sizes: Novice: 5x5 = 25 tiles = 31%
* Normal: 7x7 = 49 tiles = 60% Expert: 9x9 = 81 tiles = 100% Master: 9x9 =
* 81 tiles = 100% wrapped
*
* We have to deal with various screen sizes, and we want the cells to be
* big enough to touch. So, to set the board sizes, we choose either SMALL,
* MEDIUM, or LARGE based on the physical screen size. Then, sizes[skill][0]
* is the major grid size for that skill, and sizes[skill][1] is the minor
* grid size for that skill.
*/
enum Screen {
SMALL(8, 6, 8, 6, 6, 6, 6, 4), // Like HVGA.
WSMALL(9, 6, 9, 6, 5, 6, 5, 4), // Like HVGA.
MEDIUM(11, 7, 11, 7, 9, 7, 5, 5), // VGA plus.
WMEDIUM(12, 7, 10, 7, 8, 7, 6, 5), // Wide VGA plus.
HUGE(17, 10, 15, 8, 11, 8, 7, 6); // WSVGA etc.
Screen(int ml, int ms, int el, int es, int nl, int ns, int vl, int vs) {
major = ml;
minor = ms;
sizes[Skill.INSANE.ordinal()][0] = ml;
sizes[Skill.INSANE.ordinal()][1] = ms;
sizes[Skill.MASTER.ordinal()][0] = ml;
sizes[Skill.MASTER.ordinal()][1] = ms;
sizes[Skill.EXPERT.ordinal()][0] = el;
sizes[Skill.EXPERT.ordinal()][1] = es;
sizes[Skill.NORMAL.ordinal()][0] = nl;
sizes[Skill.NORMAL.ordinal()][1] = ns;
sizes[Skill.NOVICE.ordinal()][0] = vl;
sizes[Skill.NOVICE.ordinal()][1] = vs;
}
int getBoardWidth(Skill sk, int gw, int gh) {
if (gw > gh)
return sizes[sk.ordinal()][0];
else
return sizes[sk.ordinal()][1];
}
int getBoardHeight(Skill sk, int gw, int gh) {
if (gw > gh)
return sizes[sk.ordinal()][1];
else
return sizes[sk.ordinal()][0];
}
private final int major;
private final int minor;
private final int[][] sizes = new int[Skill.values().length][2];
}
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Construct a board view.
*
* @param context
* The context we're running in.
* @param attrs
* Our layout attributes.
*/
public BoardView(Context context, AttributeSet attrs) {
super(context, attrs);
try {
NetScramble parent = (NetScramble) context;
init(parent);
} catch (ClassCastException e) {
throw new IllegalStateException(
"BoardView must be part of NetScramble", e);
}
}
/**
* Construct a board view.
*
* @param parent
* The application context we're running in.
*/
public BoardView(NetScramble parent) {
super(parent);
init(parent);
}
/**
* Initialise this board view.
*
* @param parent
* The application context we're running in.
*/
private void init(NetScramble parent) {
parentApp = parent;
// Animation delay.
setDelay(30);
// Find out the device's screen dimensions and calculate the
// size and shape of the cell matrix.
findMatrix();
// Create all the cells in the calculated board. In appSize()
// we will take care of positioning them. Set the cell grid and root
// so we have a valid state to save.
Log.i(TAG, "Create board " + gridWidth + "x" + gridHeight);
cellMatrix = new Cell[gridWidth][gridHeight];
for (int y = 0; y < gridHeight; ++y) {
for (int x = 0; x < gridWidth; ++x) {
Cell cell = new Cell(parent, this, x, y);
cellMatrix[x][y] = cell;
}
}
rootCell = cellMatrix[0][0];
// Create the connected flags and connecting cell connectingCells
// (used in updateConnections()).
isConnected = new boolean[gridWidth][gridHeight];
connectingCells = new LinkedList<Cell>();
// Set the initial focus on the root cell.
focusedCell = null;
setFocus(rootCell);
}
/**
* Find the size of board that can fit in the window.
*/
private void findMatrix() {
WindowManager wm = (WindowManager) parentApp
.getSystemService(Context.WINDOW_SERVICE);
// Display disp = wm.getDefaultDisplay();
// int width = disp.getWidth();
// int height = disp.getHeight();
DisplayMetrics display = this.getResources().getDisplayMetrics();
int width = display.widthPixels;
int height = display.heightPixels;
int min = width < height ? width : height;
int max = width > height ? width : height;
float aspect = (float) max / (float) min;
if (min <= 400) {
if (aspect > 1.4f)
screenConfig = Screen.WSMALL;
else
screenConfig = Screen.SMALL;
} else if (min <= 500) {
if (aspect > 1.5f)
screenConfig = Screen.WMEDIUM;
else
screenConfig = Screen.MEDIUM;
} else
screenConfig = Screen.HUGE;
if (width > height) {
gridWidth = screenConfig.major;
gridHeight = screenConfig.minor;
} else {
gridWidth = screenConfig.minor;
gridHeight = screenConfig.major;
}
Log.v(TAG, "findMatrix: screen=" + width + "x" + height + " -> "
+ screenConfig);
}
// ******************************************************************** //
// Run Control.
// ******************************************************************** //
/**
* The application is starting. Perform any initial set-up prior to starting
* the application. We may not have a screen size yet, so this is not a good
* place to allocate resources which depend on that.
*/
@Override
protected void appStart() {
}
/**
* Set the screen size. This is guaranteed to be called before animStart(),
* but perhaps not before appStart().
*
* @param width
* The new width of the surface.
* @param height
* The new height of the surface.
* @param config
* The pixel format of the surface.
*/
@Override
protected void appSize(int width, int height, Bitmap.Config config) {
// We usually get a zero-sized resize, which is useless;
// ignore it.
if (width < 1 || height < 1)
return;
// Create our backing bitmap.
backingBitmap = getBitmap();
backingCanvas = new Canvas(backingBitmap);
// Calculate the cell size which makes the board fit. Make the cells
// square.
cellWidth = width / gridWidth;
cellHeight = height / gridHeight;
if (cellWidth < cellHeight)
cellHeight = cellWidth;
else if (cellHeight < cellWidth)
cellWidth = cellHeight;
// See if we have a usable size.
if (cellWidth < CELL_MIN || cellHeight < CELL_MIN)
throw new RuntimeException("Screen size is not playable.");
if (cellWidth > CELL_MAX || cellHeight > CELL_MAX) {
cellWidth = CELL_MAX;
cellHeight = CELL_MAX;
}
// Set up the board configuration.
Log.i(TAG, "Layout board " + gridWidth + "x" + gridHeight + ", "
+ "cells " + cellWidth + "x" + cellHeight);
// Center the board in the window.
paddingX = (width - gridWidth * cellWidth) / 2;
paddingY = (height - gridHeight * cellHeight) / 2;
// Set the cell geometries and positions.
for (int x = 0; x < gridWidth; ++x) {
for (int y = 0; y < gridHeight; ++y) {
int xPos = x * cellWidth + paddingX;
int yPos = y * cellHeight + paddingY;
cellMatrix[x][y].setGeometry(xPos, yPos, cellWidth, cellHeight);
}
}
// Load all the pixmaps for the game tiles etc.
Cell.initPixmaps(parentApp.getResources(), cellWidth, cellHeight,
config);
}
/**
* We are starting the animation loop. The screen size is known.
*
* <p>
* doUpdate() and doDraw() may be called from this point on.
*/
@Override
protected void animStart() {
}
/**
* We are stopping the animation loop, for example to pause the app.
*
* <p>
* doUpdate() and doDraw() will not be called from this point on.
*/
@Override
protected void animStop() {
}
/**
* The application is closing down. Clean up any resources.
*/
@Override
protected void appStop() {
}
// ******************************************************************** //
// Board Setup.
// ******************************************************************** //
/**
* Enable or disable the network animation.
*
* @param enable
* New network animation enablement state.
*/
void setAnimEnable(boolean enable) {
drawBlips = enable;
}
/**
* Set up the board for a new game.
*
* @param sk
* Skill level for the game; set the board up accordingly.
*/
public void setupBoard(Skill sk) {
autosolveStop();
gameSkill = sk;
// Reset the board for this game.
resetBoard(sk);
// Require at least 85% of the cells active.
int minCells = (int) (boardWidth * boardHeight * 0.85);
// Loop doing board setup until we get a valid board.
int tries = 0, cells = 0;
for (tries = 0; cells < minCells && tries < 10; ++tries)
cells = createNet(sk);
Log.i(TAG, "Created net in " + tries + " tries with " + cells
+ " cells (min " + minCells + ")");
// Now, save the "solved" state of the board.
solvedState = new Bundle();
saveBoard(solvedState);
// Jumble the board. Also, if we're in blind mode, tell the
// appropriate cells to go blind.
for (int x = boardStartX; x < boardEndX; x++) {
for (int y = boardStartY; y < boardEndY; y++) {
cellMatrix[x][y].rotate((rng.nextInt(4) - 2) * 90);
if (cellMatrix[x][y].numDirs() >= sk.blind)
cellMatrix[x][y].setBlind(true);
}
}
// Figure out the active connections.
updateConnections();
// Invalidate all the cells.
for (int x = 0; x < gridWidth; x++)
for (int y = 0; y < gridHeight; y++)
cellMatrix[x][y].invalidate();
}
/**
* Reset the board for a given skill level.
*
* @param sk
* Skill level for the game; set the board up accordingly.
*/
private void resetBoard(Skill sk) {
// Save the width and height of the playing board for this skill
// level, and the board placement within the overall cell grid.
boardWidth = screenConfig.getBoardWidth(sk, gridWidth, gridHeight);
boardHeight = screenConfig.getBoardHeight(sk, gridWidth, gridHeight);
boardStartX = (gridWidth - boardWidth) / 2;
boardEndX = boardStartX + boardWidth;
boardStartY = (gridHeight - boardHeight) / 2;
boardEndY = boardStartY + boardHeight;
// Reset the cells. If we're wrapped, set the surrounding cells
// to None; else Free, to show that there's no wraparound.
Log.i(TAG, "Reset board " + gridWidth + "x" + gridHeight);
boolean wrap = gameSkill.wrapped;
Cell u, d, l, r;
for (int x = 0; x < gridWidth; x++) {
for (int y = 0; y < gridHeight; y++) {
cellMatrix[x][y].reset(wrap ? Cell.Dir.NONE : Cell.Dir.FREE);
// Re-calculate who this cell's neighbours are.
u = d = l = r = null;
if (wrap || y > boardStartY)
u = cellMatrix[x][decr(y, boardStartY, boardEndY)];
if (wrap || y < boardEndY - 1)
d = cellMatrix[x][incr(y, boardStartY, boardEndY)];
if (wrap || x > boardStartX)
l = cellMatrix[decr(x, boardStartX, boardEndX)][y];
if (wrap || x < boardEndX - 1)
r = cellMatrix[incr(x, boardStartX, boardEndX)][y];
cellMatrix[x][y].setNeighbours(u, d, l, r);
}
}
}
/**
* Get the current playing area width. This varies with the skill level.
*
* @return Playing area width in tiles.
*/
int getBoardWidth() {
return boardWidth;
}
/**
* Get the current playing area height. This varies with the skill level.
*
* @return Playing area height in tiles.
*/
int getBoardHeight() {
return boardHeight;
}
/**
* Create a network layout. This function may be called multiple times after
* resetBoard(), to get a network with enough cells.
*
* @param sk
* Skill level for the game; create the network accordingly.
* @return The number of cells used in the layout.
*/
private int createNet(Skill sk) {
Log.i(TAG, "Create net " + boardStartX + "-" + boardEndX + ", "
+ boardStartY + "-" + boardEndY);
// Reset the cells' directions, and reset the root cell.
for (int x = boardStartX; x < boardEndX; x++) {
for (int y = boardStartY; y < boardEndY; y++) {
cellMatrix[x][y].setDirs(Cell.Dir.FREE);
cellMatrix[x][y].setRoot(false);
}
}
// Set the rootCell cell (the server) to a random cell.
int rootX = rng.nextInt(boardWidth) + boardStartX;
int rootY = rng.nextInt(boardHeight) + boardStartY;
rootCell = cellMatrix[rootX][rootY];
rootCell.setConnected(true);
rootCell.setRoot(true);
// Log.i(TAG, "Root cell " + rootCell.x() + "," + rootCell.y() + " (" +
// rootX + "," + rootY + ")");
setFocus(rootCell);
// Set up the connectingCells of cells awaiting connection. Start
// by adding the root cell.
Vector<Cell> list = new Vector<Cell>();
list.add(rootCell);
if (rng.nextBoolean())
addRandomDir(list);
// Loop while there are still cells to be connected, connecting
// them in random directions.
while (!list.isEmpty()) {
// Randomly do the first cell, or defer it and do the next one.
// This prevents unduly long, straight branches.
if (rng.nextBoolean()) {
// Add a random direction from this cell.
addRandomDir(list);
// 50% of the time, add a second direction, if we can
// find one.
if (rng.nextBoolean())
addRandomDir(list);
// A third pass makes networks more complex, but also
// introduces 4-way crosses.
if (sk.branches >= 3 && rng.nextInt(3) == 0)
addRandomDir(list);
} else
list.add(list.firstElement());
// Pop the first element off the connectingCells.
list.remove(0);
}
// Count the number of connected cells in this board.
int cells = 0;
for (int x = boardStartX; x < boardEndX; x++)
for (int y = boardStartY; y < boardEndY; y++)
if (cellMatrix[x][y].dirs() != Cell.Dir.FREE)
++cells;
Log.i(TAG, "Created net with " + cells + " cells");
return cells;
}
/**
* Add a connection in a random direction from the first cell in the given
* cell connectingCells. We enumerate the free adjacent cells around the
* starting cell, then pick one to connect to at random. If there is no free
* adjacent cell, we do nothing.
*
* If we connect to a cell, it is added to the passed-in connectingCells.
*
* @param list
* Current list of cells awaiting connection.
*/
private void addRandomDir(Vector<Cell> list) {
// Start with the first cell in the cell connectingCells.
Cell cell = list.firstElement();
// List the adjacent cells which are free.
EnumMap<Cell.Dir, Cell> freecells = new EnumMap<Cell.Dir, Cell>(
Cell.Dir.class);
for (Cell.Dir d : Cell.Dir.cardinals) {
Cell ucell = cell.next(d);
if (ucell != null && ucell.dirs() == Cell.Dir.FREE)
freecells.put(d, ucell);
}
if (freecells.isEmpty()) {
// Log.d(TAG, "addRandomDir: no free adjacents");
return;
}
// Pick one of the free adjacents at random.
Object[] keys = freecells.keySet().toArray();
Cell.Dir key = (Cell.Dir) keys[rng.nextInt(keys.length)];
Cell dest = freecells.get(key);
// Make a link to that cell, and a corresponding link back.
cell.addDir(key);
dest.addDir(key.reverse);
// Add the new cell to the outstanding connectingCells.
list.add(dest);
// Log.d(TAG, "addRandomDir: connected to " + dest.x() + "," +
// dest.y());
}
// ******************************************************************** //
// Board Logic.
// ******************************************************************** //
/**
* Scan the board to see which cells are connected to the server. Update the
* state of every cell accordingly. This function is called each time a cell
* is rotated, to re-compute the connectedness of every cell.
*
* @return true iff one or more cells have been connected that previously
* weren't.
*/
private synchronized boolean updateConnections() {
// Reset the array of connected flags per cell.
for (int x = 0; x < gridWidth; x++)
for (int y = 0; y < gridHeight; y++)
isConnected[x][y] = false;
// Clear the list of cells which are connected but
// haven't had their onward connections checked yet.
connectingCells.clear();
// If the root cell is rotated, then it's not connected to
// anything -- no-one is connected. Otherwise, flag the root
// cell as connected and add it to the connectingCells.
if (!rootCell.isRotated()) {
isConnected[rootCell.x()][rootCell.y()] = true;
connectingCells.add(rootCell);
}
// While there are still cells to investigate, check them for
// connections that we haven't flagged yet, and add those cells
// to the connectingCells.
while (!connectingCells.isEmpty()) {
Cell cell = connectingCells.remove();
for (Cell.Dir d : Cell.Dir.cardinals)
if (hasNewConnection(cell, d, isConnected))
connectingCells.add(cell.next(d));
}
// Finally, scan the connection flags. Set every cell's connected
// status accordingly. Count connected cells, and cells that are
// connected but weren't previously.
int newConnections = 0;
for (int x = 0; x < gridWidth; x++) {
for (int y = 0; y < gridHeight; y++) {
if (isConnected[x][y]) {
if (!cellMatrix[x][y].isConnected())
++newConnections;
}
cellMatrix[x][y].setConnected(isConnected[x][y]);
}
}
// Log.d(TAG, "updateConnections: " + connections +
// " connected (" + newConnections + " new)");
// Tell the caller whether we got a new one.
return newConnections != 0;
}
/**
* Determine whether we have a connection from the given cell in the given
* direction which hasn't already been logged in got[][].
*
* @param cell
* Starting cell.
* @param dir
* Direction to look in.
* @param got
* Array of flags showing which cells we have already found
* connections for. If we find a new connection, we will set the
* flag for it in here.
* @return true iff we found a new connection in the given direction.
*/
private boolean hasNewConnection(Cell cell, Cell.Dir dir, boolean got[][]) {
// Find the cell we're going to, if any.
Cell other = cell.next(dir);
Cell.Dir otherdir = dir.reverse;
// If there's no cell there, then there's no connection. If we
// have already marked it connected, we're done.
if (other == null || got[other.x()][other.y()])
return false;
// See if there's an actual connection. If either cell is rotated,
// there's no connection.
if (!cell.hasConnection(dir) || !other.hasConnection(otherdir))
return false;
// OK, there's a connection, and it's new. Mark it.
got[other.x()][other.y()] = true;
return true;
}
/**
* Determine whether the board is currently in a solved state -- i.e. all
* terminals are connected to the server.
*
* Note that in some layouts, it is possible to connect all the terminals
* without using all the cable sections. Since the game intro asks the user
* to connect all the terminals, which makes sense, we look for unconnected
* terminals specifically.
*
* NOTE: We assume that updateConnections() has been called to set the
* connected states of all cells correctly for the current board state.
*
* @return true iff the board is currently in a solved state -- ie. every
* terminal cell is connected to the server.
*/
synchronized boolean isSolved() {
// Scan the board; any non-connected non-empty cell means
// we're not done yet.
for (int x = boardStartX; x < boardEndX; x++) {
for (int y = boardStartY; y < boardEndY; y++) {
Cell cell = cellMatrix[x][y];
// If there's an unconnected terminal, we're not solved.
if (cell.numDirs() == 1 && !cell.isConnected())
return false;
}
}
return true;
}
/**
* Count the number of unconnected cells in the board.
*
* Note that in some layouts (particularly in Expert mode), it is possible
* to connect all the terminals without using all the cable sections, so the
* answer may be non-0 on a solved board.
*
* NOTE: We assume that updateConnections() has been called to set the
* connected states of all cells correctly for the current board state.
*
* @return The number of unconnected cells in the board.
*/
int unconnectedCells() {
int unused = 0;
for (int x = boardStartX; x < boardEndX; x++) {
for (int y = boardStartY; y < boardEndY; y++) {
Cell cell = cellMatrix[x][y];
if (cell.dirs() != Cell.Dir.FREE && !cell.isConnected())
++unused;
}
}
return unused;
}
// ******************************************************************** //
// Client Methods.
// ******************************************************************** //
/**
* Update the state of the application for the current frame.
*
* <p>
* Applications must override this, and can use it to update for example the
* physics of a game. This may be a no-op in some cases.
*
* <p>
* doDraw() will always be called after this method is called; however, the
* converse is not true, as we sometimes need to draw just to update the
* screen. Hence this method is useful for updates which are dependent on
* time rather than frames.
*
* @param now
* Current time in ms.
*/
@Override
protected void doUpdate(long now) {
// See if we have programmed moves to execute. If so, see if
// it's time for the next one.
if (programmedMoves != null && now - lastProgMove > SOLVE_STEP_TIME) {
if (programmedMoves.isEmpty()) {
// Since the last move has completed, we're now finished.
autosolveStop();
} else {
// Get the next move and execute it.
int[] move = programmedMoves.removeFirst();
Cell mc = cellMatrix[move[0]][move[1]];
int dirn = move[2];
// If the cell isn't focused, focus it, and that's our move.
// If the cell is locked, unlock it, and that's our move.
// Otherwise do the actual move and update the connection state.
if (mc != focusedCell) {
setFocus(mc);
programmedMoves.addFirst(move);
} else if (mc.isLocked()) {
mc.setLocked(false);
programmedMoves.addFirst(move);
} else {
// Make the cell's content visible. Do the move.
mc.setBlind(false);
mc.rotate(dirn, SOLVE_ROTATE_TIME);
updateConnections();
}
lastProgMove = now;
}
}
// Update all the cells. Flag if any cell changed its
// connection state.
Cell changedCell = null;
for (int x = 0; x < gridWidth; ++x)
for (int y = 0; y < gridHeight; ++y)
if (cellMatrix[x][y].doUpdate(now))
changedCell = cellMatrix[x][y];
// Update all the data blips.
if (drawBlips) {
if (now - blipsLastAdvance >= BLIPS_TIME) {
for (int x = 0; x < gridWidth; ++x)
for (int y = 0; y < gridHeight; ++y)
cellMatrix[x][y].advanceBlips(blipCount);
++blipCount;
for (int x = 0; x < gridWidth; ++x)
for (int y = 0; y < gridHeight; ++y)
cellMatrix[x][y].transferBlips();
blipsLastAdvance += BLIPS_TIME;
if (blipsLastAdvance < now)
blipsLastAdvance = now;
}
}
// If the connection state changed, update the network.
if (changedCell != null) {
if (updateConnections())
parentApp.postSound(Sound.CONNECT);
// If we're done, report it.
if (isSolved()) {
// Un-blind all cells.
for (int x = boardStartX; x < boardEndX; x++)
for (int y = boardStartY; y < boardEndY; y++)
cellMatrix[x][y].setBlind(false);
blink(changedCell);
parentApp.postState(State.SOLVED);
parentApp.postSound(Sound.WIN);
}
}
}
/**
* Draw the current frame of the application.
*
* <p>
* Applications must override this, and are expected to draw the entire
* screen into the provided canvas.
*
* <p>
* This method will always be called after a call to doUpdate(), and also
* when the screen needs to be re-drawn.
*
* @param canvas
* The Canvas to draw into.
* @param now
* Current time in ms. Will be the same as that passed to
* doUpdate(), if there was a preceding call to doUpdate().
*/
@Override
protected void doDraw(Canvas canvas, long now) {
// Draw all the cells into the backing bitmap. Only the
// dirty cells will redraw themselves.
for (int x = 0; x < gridWidth; ++x)
for (int y = 0; y < gridHeight; ++y)
cellMatrix[x][y].doDraw(backingCanvas, now);
// Now push the backing bitmap to the screen.
canvas.drawBitmap(backingBitmap, 0, 0, null);
// Draw the data blips in a separate pass so they can overlap
// adjacent cells without getting overdrawn. We draw directly
// to the screen.
if (drawBlips) {
float frac = (float) (now - blipsLastAdvance) / (float) BLIPS_TIME;
for (int x = 0; x < gridWidth; ++x)
for (int y = 0; y < gridHeight; ++y)
cellMatrix[x][y].doDrawBlips(canvas, now, frac);
}
}
// ******************************************************************** //
// Input Handling.
// ******************************************************************** //
/**
* Handle key input.
*
* @param keyCode
* The key code.
* @param event
* The KeyEvent object that defines the button action.
* @return True if the event was handled, false otherwise.
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Take care of calling onBackPressed() on earlier versions of
// the platform where it doesn't exist.
// TODO: delete this code when no longer supporting pre-2.0.
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ECLAIR
&& keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
parentApp.onBackPressed();
return true;
}
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_CENTER:
// DPAD_CENTER is special: handle like a screen press, and check
// for a long press.
pressDown();
return true;
case KeyEvent.KEYCODE_ENTER:
if (programmedMoves == null)
cellRotate(focusedCell, 1);
return true;
case KeyEvent.KEYCODE_Z:
case KeyEvent.KEYCODE_N:
case KeyEvent.KEYCODE_4:
if (programmedMoves == null)
cellRotate(focusedCell, -1);
return true;
case KeyEvent.KEYCODE_X:
case KeyEvent.KEYCODE_M:
case KeyEvent.KEYCODE_6:
if (programmedMoves == null)
cellRotate(focusedCell, 1);
return true;
case KeyEvent.KEYCODE_SPACE:
case KeyEvent.KEYCODE_0:
if (programmedMoves == null)
cellToggleLock(focusedCell);
return true;
case KeyEvent.KEYCODE_P:
case KeyEvent.KEYCODE_9:
pauseGame();
return true;
case KeyEvent.KEYCODE_DPAD_UP:
if (programmedMoves == null)
moveFocus(Cell.Dir.U___, 0, -1);
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (programmedMoves == null)
moveFocus(Cell.Dir._R__, 1, 0);
return true;
case KeyEvent.KEYCODE_DPAD_DOWN:
if (programmedMoves == null)
moveFocus(Cell.Dir.__D_, 0, 1);
return true;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (programmedMoves == null)
moveFocus(Cell.Dir.___L, -1, 0);
return true;
}
return false;
}
/**
* Handle key input.
*
* @param keyCode
* The key code.
* @param event
* The KeyEvent object that defines the button action.
* @return True if the event was handled, false otherwise.
*/
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_CENTER:
// Special handling for DPAD_CENTER: cancel long press handling.
pressUp();
return true;
}
return false;
}
/**
* Handle trackball motion events.
*
* @param event
* The motion event.
* @return True if the event was handled, false otherwise.
*/
@Override
public boolean onTrackballEvent(MotionEvent event) {
// Actually, just let these come through as D-pad events.
return false;
}
/**
* Handle MotionEvent events.
*
* @param event
* The motion event.
* @return True if the event was handled, false otherwise.
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
// Focus on the pressed cell.
pressedCell = findCell(event.getX(), event.getY());
if (pressedCell != null) {
if (programmedMoves == null)
setFocus(pressedCell);
pressDown();
}
} else if (event.getAction() == MotionEvent.ACTION_UP) {
if (pressedCell != null) {
pressedCell = null;
pressUp();
}
}
return true;
}
/**
* Find the cell corresponding to a screen location.
*
* @param x
* Location X.
* @param y
* Location Y.
* @return The cell at x,y; null if none.
*/
private Cell findCell(float x, float y) {
// Focus on the pressed cell.
int cx = (int) ((x - paddingX) / cellWidth);
int cy = (int) ((y - paddingY) / cellHeight);
if (cx < 0 || cx >= gridWidth || cy < 0 || cy >= gridHeight)
return null;
return cellMatrix[cx][cy];
}
/**
* Handle a screen or centre-button press.
*/
private void pressDown() {
// Get ready to detect a long press.
longPressed = false;
longPressHandler.postDelayed(longPress, LONG_PRESS);
}
/**
* Handle a screen or centre-button release. If we didn't get a long press,
* handle like a click.
*/
private void pressUp() {
if (!longPressed) {
// Cancel the long press handler.
longPressHandler.removeCallbacks(longPress);
// If we got here, rotate the cell -- except user input is ignored
// while executing programmed moves.
if (programmedMoves == null)
cellRotate(focusedCell, 1);
}
}
/**
* Handler for a screen or centre-button long press.
*/
private Runnable longPress = new Runnable() {
@Override
public void run() {
longPressed = true;
if (programmedMoves == null)
cellToggleLock(focusedCell);
}
};
/**
* Move the cell focus in the given direction.
*
* Note that this moves the variable focusedCell; we do our own focus,
* rather than using system focus, as there seems to be no way to make that
* wrap on a dynamic layout.
*
* @param dir
* The direction to move in.
* @param dx
* X-delta of that direction (for convenience).
* @param dy
* Y-delta of that direction (for convenience).
*/
private void moveFocus(Cell.Dir dir, int dx, int dy) {
if (focusedCell == null)
return;
// Try using the cell's idea of it's neighbour.
Cell goCell = focusedCell.next(dir);
// Otherwise wrap around the board.
if (goCell == null) {
int nx = (focusedCell.x() + dx + gridWidth) % gridWidth;
int ny = (focusedCell.y() + dy + gridHeight) % gridHeight;
goCell = cellMatrix[nx][ny];
}
setFocus(goCell);
}
// ******************************************************************** //
// Cell Actions.
// ******************************************************************** //
/**
* Set the focused cell to the given cell.
*
* Note that this moves the variable focusedCell; we do our own focus,
* rather than using system focus, as there seems to be no way to make that
* wrap on a dynamic layout. (focusSearchInDescendants doesn't get called.)
*
* @param cell
* The cell; null to clear focus.
*/
private void setFocus(Cell cell) {
if (focusedCell != null)
focusedCell.setFocused(false);
focusedCell = cell;
if (focusedCell != null)
focusedCell.setFocused(true);
}
/**
* The given cell has been told to rotate.
*
* @param cell
* The cell.
* @param dirn
* Direction: -1 for left, 1 for right.
*/
void cellRotate(Cell cell, int dirn) {
// See if the cell is empty or locked; give the user some negative
// feedback if so.
Cell.Dir d = cell.dirs();
if (d == Cell.Dir.FREE || d == Cell.Dir.NONE || cell.isLocked()) {
parentApp.postSound(Sound.CLICK);
blink(cell);
return;
}
// Give the user a click. Set up an animation to do the rotation.
parentApp.postSound(Sound.TURN);
cell.rotate(dirn * 90);
// This cell is no longer connected. Update the connection state.
updateConnections();
// Tell the parent we clicked this cell.
parentApp.cellClicked(cell);
}
/**
* Toggle the locked state of the given cell.
*
* @param cell
* The cell to toggle.
*/
void cellToggleLock(Cell cell) {
// See if the cell is empty; give the user some negative
// feedback if so.
Cell.Dir d = cell.dirs();
if (d == Cell.Dir.FREE || d == Cell.Dir.NONE) {
parentApp.postSound(Sound.CLICK);
blink(cell);
return;
}
cell.setLocked(!cell.isLocked());
parentApp.postSound(Sound.POP);
}
/**
* Pause the game.
*/
private void pauseGame() {
parentApp.postState(State.PAUSED);
}
/**
* Blink the given cell, to indicate a mis-click etc.
*
* @param cell
* The cell to blink.
*/
private void blink(Cell cell) {
cell.doHighlight();
}
/**
* Set the board to display the game as solved.
*/
void setSolved() {
// Display the fully-connected version of the server.
rootCell.setSolved(true);
}
// ******************************************************************** //
// Autosolver.
// ******************************************************************** //
/**
* Auto-solve the puzzle, by generating a list of programmed moves which
* will set each cell to the position it was in when the network was
* created.
*
* We generate the moves list in breadth-first order. This is harder to do,
* but looks nicer.
*/
void autosolve() {
// If we're already solving, just toggle the state.
if (programmedMoves != null) {
autosolveStop();
return;
}
Bundle solution = solvedState;
if (solution == null)
return;
// Read the solved state, accounting for device rotations etc.
GameState state = new GameState(gridWidth, gridHeight, gameSkill);
if (!restoreBoard(solution, state))
return;
// Create the programmed move list.
programmedMoves = new LinkedList<int[]>();
// Clear the list of cells which are connected but
// haven't had their onward connections checked yet.
connectingCells.clear();
// Reset the array of solved flags per cell.
for (int x = 0; x < gridWidth; x++)
for (int y = 0; y < gridHeight; y++)
isConnected[x][y] = false;
// Set the root cell up to be solved first.
connectingCells.add(state.root);
isConnected[state.root.x()][state.root.y()] = true;
// While there are still cells to investigate, solve them, check
// them for connections that we haven't flagged yet, and add those
// cells to the connectingCells.
while (!connectingCells.isEmpty()) {
Cell cell = connectingCells.removeFirst();
solveCell(cell, programmedMoves);
for (Cell.Dir d : Cell.Dir.cardinals) {
if (cell.hasConnection(d)) {
Cell next = cell.next(d);
if (next != null && !isConnected[next.x()][next.y()]) {
connectingCells.addLast(next);
isConnected[next.x()][next.y()] = true;
}
}
}
}
lastProgMove = 0;
parentApp.selectAutosolveMode(true);
}
/**
* Stop the autosolver.
*/
void autosolveStop() {
programmedMoves = null;
lastProgMove = 0;
parentApp.selectAutosolveMode(false);
}
/**
* Solve the given cell. This doesn't actually do anything, except add a
* move to the given moves list to put the cell into the solved state.
*
* @param sc
* The solved version of the cell.
* @param moves
* List of moves that we're building.
*/
private void solveCell(Cell sc, LinkedList<int[]> moves) {
Cell mc = cellMatrix[sc.x()][sc.y()];
Cell.Dir sd = sc.dirs();
Cell.Dir md = mc.dirs();
if (sc.dirs() != md) {
int[] move;
if (mc.rotatedDirs(90) == sd) {
move = new int[] { mc.x(), mc.y(), 90 };
moves.add(move);
} else if (mc.rotatedDirs(-90) == sd) {
move = new int[] { mc.x(), mc.y(), -90 };
moves.add(move);
} else if (mc.rotatedDirs(180) == sd) {
int rot = rng.nextBoolean() ? 90 : -90;
move = new int[] { mc.x(), mc.y(), rot };
moves.add(move);
move = new int[] { mc.x(), mc.y(), rot };
moves.add(move);
}
}
}
// ******************************************************************** //
// State Save/Restore.
// ******************************************************************** //
/**
* Save game state so that the user does not lose anything if the game
* process is killed while we are in the background.
*
* @param outState
* A Bundle in which to place any state information we wish to
* save.
*/
protected void saveState(Bundle outState) {
// Save the game state of the board.
saveBoard(outState);
// Also save the solved state, if any.
if (solvedState != null)
outState.putBundle("solvedState", solvedState);
}
/**
* Save game state so that the user does not lose anything if the game
* process is killed while we are in the background.
*
* @param outState
* A Bundle in which to place any state information we wish to
* save.
*/
private void saveBoard(Bundle outState) {
outState.putInt("gridWidth", gridWidth);
outState.putInt("gridHeight", gridHeight);
outState.putInt("rootX", rootCell.x());
outState.putInt("rootY", rootCell.y());
outState.putInt("focusX", focusedCell.x());
outState.putInt("focusY", focusedCell.y());
// Save the states of all the cells which are in use.
for (int x = 0; x < gridWidth; ++x) {
for (int y = 0; y < gridHeight; ++y) {
String key = "cell " + x + "," + y;
outState.putBundle(key, cellMatrix[x][y].saveState());
}
}
}
/**
* Restore our game state from the given Bundle.
*
* @param map
* A Bundle containing the saved state.
* @param skill
* Skill level of the saved game.
* @return true if the state was restored OK; false if the saved state was
* incompatible with the current configuration.
*/
boolean restoreState(Bundle map, Skill skill) {
// Restore the game state of the board.
gameSkill = skill;
resetBoard(skill);
// Restore the actual game state.
GameState state = new GameState(cellMatrix);
boolean ok = restoreBoard(map, state);
rootCell = state.root;
setFocus(state.focus);
// Also restore the solved state, if any.
if (ok && map.containsKey("solvedState")) {
solvedState = map.getBundle("solvedState");
ok = solvedState != null;
}
return ok;
}
/**
* Restore our game state from the given Bundle.
*
* @param map
* A Bundle containing the saved state.
* @param state
* Record to place the restored state in.
* @return true if the state was restored OK; false if the saved state was
* incompatible with the current configuration.
*/
private boolean restoreBoard(Bundle map, GameState state) {
// Check that the saved board size is compatible with what we
// have now. If it is identical, then do a straight restore; if
// it's rotated, then restore and rotate.
int sgw = map.getInt("gridWidth");
int sgh = map.getInt("gridHeight");
if (sgw == gridWidth && sgh == gridHeight)
return restoreNormal(map, state);
else if (sgw == gridHeight && sgh == gridWidth) {
if (gridWidth > gridHeight)
return restoreRotLeft(map, state);
else
return restoreRotRight(map, state);
} else
return false;
}
/**
* Restore our game state from the given Bundle.
*
* @param map
* A Bundle containing the saved state.
* @param state
* Record to place the restored state in.
* @return true if the state was restored OK; false if the saved state was
* incompatible with the current configuration.
*/
private boolean restoreNormal(Bundle map, GameState state) {
// Set up the root cell and focused cell.
int rx = map.getInt("rootX");
int ry = map.getInt("rootY");
state.root = state.matrix[rx][ry];
int fx = map.getInt("focusX");
int fy = map.getInt("focusY");
state.focus = state.matrix[fx][fy];
// Restore the states of all the cells which are in use.
for (int x = 0; x < gridWidth; ++x) {
for (int y = 0; y < gridHeight; ++y) {
String key = "cell " + x + "," + y;
state.matrix[x][y].restoreState(map.getBundle(key));
}
}
return true;
}
/**
* Restore our game state from the given Bundle, rotating the board left as
* we do so.
*
* @param map
* A Bundle containing the saved state.
* @param state
* Record to place the restored state in.
* @return true if the state was restored OK; false if the saved state was
* incompatible with the current configuration.
*/
private boolean restoreRotLeft(Bundle map, GameState state) {
// Set up the root cell. Flip the co-ordinates.
int rx = map.getInt("rootX");
int ry = map.getInt("rootY");
state.root = state.matrix[ry][gridHeight - rx - 1];
int fx = map.getInt("focusX");
int fy = map.getInt("focusY");
state.focus = state.matrix[fy][gridHeight - fx - 1];
// Restore the states of all the cells which are in use.
for (int y = 0; y < gridHeight; ++y) {
for (int x = 0; x < gridWidth; ++x) {
if (x >= state.matrix.length || y >= state.matrix[x].length)
return false;
String key = "cell " + y + "," + x;
Bundle cmap = map.getBundle(key);
if (cmap == null)
return false;
state.matrix[x][gridHeight - y - 1].restoreState(cmap);
state.matrix[x][gridHeight - y - 1].rotateImmediate(-90);
}
}
return true;
}
/**
* Restore our game state from the given Bundle, rotating the board right as
* we do so.
*
* @param map
* A Bundle containing the saved state.
* @param state
* Record to place the restored state in.
* @return true if the state was restored OK; false if the saved state was
* incompatible with the current configuration.
*/
private boolean restoreRotRight(Bundle map, GameState state) {
// Set up the root cell. Flip the co-ordinates.
int rx = map.getInt("rootX");
int ry = map.getInt("rootY");
state.root = state.matrix[gridWidth - ry - 1][rx];
int fx = map.getInt("focusX");
int fy = map.getInt("focusY");
state.focus = state.matrix[gridWidth - fy - 1][fx];
// Restore the states of all the cells which are in use.
for (int y = 0; y < gridHeight; ++y) {
for (int x = 0; x < gridWidth; ++x) {
if (x >= state.matrix.length || y >= state.matrix[x].length)
return false;
String key = "cell " + y + "," + x;
Bundle cmap = map.getBundle(key);
if (cmap == null)
return false;
state.matrix[gridWidth - x - 1][y].restoreState(cmap);
state.matrix[gridWidth - x - 1][y].rotateImmediate(90);
}
}
return true;
}
// ******************************************************************** //
// Utilities.
// ******************************************************************** //
/**
* Return the given value plus one, but wrapped within the given range.
*
* @param v
* Value to increment.
* @param min
* Minimum allowed value, inclusive.
* @param max
* Maximum allowed value, not inclusive.
* @return The incremented value, wrapped around to stay in range.
*/
private static final int incr(int v, int min, int max) {
return v < max - 1 ? ++v : min;
}
/**
* Return the given value minus one, but wrapped within the given range.
*
* @param v
* Value to decrement.
* @param min
* Minimum allowed value, inclusive.
* @param max
* Maximum allowed value, not inclusive.
* @return The decremented value, wrapped around to stay in range.
*/
private static final int decr(int v, int min, int max) {
return v > min ? --v : max - 1;
}
// ******************************************************************** //
// Private Classes.
// ******************************************************************** //
/**
* A game state. Saves a state of the game board, either to save where we
* are, or to record an initial or solved position.
*/
private class GameState {
// Create a game state based on the given cell matrix.
GameState(Cell[][] m) {
matrix = m;
}
// Create a game state with a new cell matrix.
GameState(int w, int h, Skill skill) {
matrix = new Cell[w][h];
for (int y = 0; y < h; ++y) {
for (int x = 0; x < w; ++x) {
Cell cell = new Cell(parentApp, BoardView.this, x, y);
matrix[x][y] = cell;
}
}
// Save the width and height of the playing board for this skill
// level, and the board placement within the overall cell grid.
int bw = screenConfig.getBoardWidth(skill, w, h);
int bh = screenConfig.getBoardHeight(skill, w, h);
int bsx = (w - bw) / 2;
int bex = bsx + bw;
int bsy = (h - bh) / 2;
int bey = bsy + bh;
boolean wrap = skill.wrapped;
Cell u, d, l, r;
for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {
matrix[x][y].reset(wrap ? Cell.Dir.NONE : Cell.Dir.FREE);
// Re-calculate who this cell's neighbours are.
u = d = l = r = null;
if (wrap || y > bsy)
u = matrix[x][decr(y, bsy, bey)];
if (wrap || y < bey - 1)
d = matrix[x][incr(y, bsy, bey)];
if (wrap || x > bsx)
l = matrix[decr(x, bsx, bex)][y];
if (wrap || x < bex - 1)
r = matrix[incr(x, bsx, bex)][y];
matrix[x][y].setNeighbours(u, d, l, r);
}
}
}
Cell root = null;
Cell focus = null;
Cell[][] matrix = null;
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Debugging tag.
private static final String TAG = "netscramble";
// Time in ms for a long screen or centre-button press.
private static final int LONG_PRESS = 650;
// Time a blip takes to cross half a cell, in ms.
private static final long BLIPS_TIME = 300;
// Rate at which we run moves in solve mode, in ms.
private static final long SOLVE_STEP_TIME = 800;
// Time taken to rotate a cell in solve mode, in ms.
private static final long SOLVE_ROTATE_TIME = 350;
// Random number generator for the game. We use a Mersenne Twister,
// which is a high-quality and fast implementation of java.util.Random.
// private static final Random rng = new MTRandom();
private static final SecureRandom rng = new SecureRandom();
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The parent application.
private NetScramble parentApp;
// Screen configuration which matches the physical screen size.
private Screen screenConfig = null;
// Iff true, draw blips representing data moving through the network.
private boolean drawBlips = true;
// Width and height of the playing board, in cells. This is tailored
// to suit the screen size and orientation. It should be invariant on
// any given device except that it will rotate 90 degrees when the
// screen rotates.
private int gridWidth;
private int gridHeight;
// The Cell objects which make up the board. This matrix is gridWidth
// by gridHeight, which is large enough to contain the game board at
// any skill level.
private Cell[][] cellMatrix;
// "Solved" (i.e. initial, pre-scrambled) state of the board. This
// is the canonical solution.
private Bundle solvedState = null;
// Width and height of the cells in the board, in pixels.
private int cellWidth;
private int cellHeight;
// Horizontal and vertical padding used to center the board in the window.
private int paddingX = 0;
private int paddingY = 0;
// Size of the game board, and offset of the first and last active cells.
// These are set up to define the actual board area in use for a given
// game. These change depending on the skill level.
private int boardWidth;
private int boardHeight;
private int boardStartX;
private int boardStartY;
private int boardEndX;
private int boardEndY;
// Backing bitmap for the board, and a Canvas to draw in it.
private Bitmap backingBitmap = null;
private Canvas backingCanvas = null;
// The skill level of the current game.
private Skill gameSkill;
// The rootCell cell of the layout; where the server is.
private Cell rootCell;
// The cell which currently has the focus.
private Cell focusedCell;
// Connected flags for each cell in the board; used in updateConnections().
private boolean isConnected[][];
// List of outstanding connected cells; used in updateConnections().
private LinkedList<Cell> connectingCells;
// Cell currently being pressed in a touch event.
private Cell pressedCell = null;
// Long press handling. The Handler gets notified after the long
// press time has elapsed; longPressed is set to true when a long
// press has been detected, so the subsequent up event can be ignored.
private Handler longPressHandler = new Handler();
private boolean longPressed = false;
// The time in ms at which we last completed a data blip move cycle.
private long blipsLastAdvance = 0;
// Count of data blip generations.
private int blipCount = 0;
// Programed moves -- if this list is non-null and non-empty,
// it contains a set of moves to be performed without user input.
// Each move consists of a cell X and Y, and the number of degrees
// to rotate the cell -- which must be either -180, -90, 90, or 180.
private LinkedList<int[]> programmedMoves = null;
// Time a which we executed the last move in the programme.
private long lastProgMove = 0;
}
| 53,111 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
NumericAsserts.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/test/org/hermit/test/NumericAsserts.java |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hermit.test;
import static java.lang.Math.abs;
import junit.framework.Assert;
/**
* Contains additional assertion methods not found in JUnit.
*/
public final class NumericAsserts {
private NumericAsserts() { }
/**
* Asserts that {@code value} is in the range {@code min .. @code max}
* inclusive.
*/
public static void assertRange(String message, double value, double min, double max) {
if (value < min || value > max)
failWithMessage(message, "expected to be in range [" +
min + "," + max + "] but was " + value);
}
/**
* Asserts that {@code value} is in the range
* {@code expect-maxerr .. @code expect+maxerr} inclusive.
*/
public static void assertTolerance(String message, double value, double expect, double maxerr) {
double err = abs(value - expect);
if (err > maxerr)
failWithMessage(message, "expected to be within " +
maxerr + " of " + expect +
" but was " + value);
}
/**
* Asserts that {@code value} is in the range
* {@code expect-maxerr .. @code expect+maxerr} inclusive, where maxerr is
* {@code expect*pcnt/100}.
*/
public static void assertPercent(String message, double value, double expect, double pcnt) {
double errpcnt = abs(value - expect) / expect * 100.0;
if (errpcnt > pcnt)
failWithMessage(message, "expected to be within " +
pcnt + "% of " + expect +
" but was " + value);
}
/**
* Asserts that a given angle {@code angle} is equal to {@code expect},
* plus or minus {@code maxerr} degrees. Takes care of angles going
* past 360 / 0.
*/
public static void assertDegrees(String message, double value, double expect, double maxerr) {
if (maxerr < 180.0 && value <= maxerr && expect >= 360.0 - maxerr)
value += 360.0;
else if (maxerr < 180.0 && expect <= maxerr && value >= 360.0 - maxerr)
expect += 360.0;
double err = abs(value - expect);
if (err > maxerr)
failWithMessage(message, "expected to be within " +
maxerr + " of " + expect +
" but was " + value);
}
private static void failWithMessage(String userMessage, String ourMessage) {
Assert.fail(userMessage == null ? ourMessage : userMessage + ' ' + ourMessage);
}
}
| 3,088 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
FormatterTests.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/test/org/hermit/test/utils/FormatterTests.java |
/**
* geo: geographical utilities.
* <br>Copyright 2004-2009 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.test.utils;
import junit.framework.TestCase;
import org.hermit.utils.CharFormatter;
/**
* Test geodetic calculations.
*
* @author Ian Cameron Smith
*/
public class FormatterTests
extends TestCase
{
// ******************************************************************** //
// Test Framework.
// ******************************************************************** //
@Override
protected void setUp() {
buf = new char[40];
}
private void run(int off, String val, int field, String expect) {
String res = null;
try {
CharFormatter.formatString(buf, off, val, field);
res = new String(buf, off, field);
} catch (ArrayIndexOutOfBoundsException e) {
res = "!OOB!";
} catch (IllegalArgumentException e) {
res = "!ILL!";
}
assertEquals(expect, res);
}
private void run(int off, String val, int field, boolean right, String expect) {
String res = null;
try {
CharFormatter.formatString(buf, off, val, field, right);
res = new String(buf, off, field);
} catch (ArrayIndexOutOfBoundsException e) {
res = "!OOB!";
} catch (IllegalArgumentException e) {
res = "!ILL!";
}
assertEquals(expect, res);
}
private void run(int off, int val, int field, boolean signed, String expect) {
String res = null;
try {
CharFormatter.formatInt(buf, off, val, field, signed);
res = new String(buf, off, field);
} catch (ArrayIndexOutOfBoundsException e) {
res = "!OOB!";
} catch (IllegalArgumentException e) {
res = "!ILL!";
}
assertEquals(expect, res);
}
private void runZ(int off, int val, int field, boolean signed, String expect) {
String res = null;
try {
CharFormatter.formatInt(buf, off, val, field, signed, true);
res = new String(buf, off, field);
} catch (ArrayIndexOutOfBoundsException e) {
res = "!OOB!";
} catch (IllegalArgumentException e) {
res = "!ILL!";
}
assertEquals(expect, res);
}
private void runL(int off, int val, int field, boolean signed, String expect) {
String res = null;
try {
CharFormatter.formatIntLeft(buf, off, val, field, signed);
res = new String(buf, off, field);
} catch (ArrayIndexOutOfBoundsException e) {
res = "!OOB!";
} catch (IllegalArgumentException e) {
res = "!ILL!";
}
assertEquals(expect, res);
}
private void run(int off, double val, int field, int frac, boolean signed, String expect) {
String res = null;
try {
CharFormatter.formatFloat(buf, off, val, field, frac, signed);
res = new String(buf, off, field);
} catch (ArrayIndexOutOfBoundsException e) {
res = "!OOB!";
} catch (IllegalArgumentException e) {
res = "!ILL!";
}
assertEquals(expect, res);
}
// ******************************************************************** //
// String Tests.
// ******************************************************************** //
public void testStringLeftFix() {
run(13, null, 7, " ");
run(13, "", 7, " ");
run(13, "ABCDE", 7, "ABCDE ");
run(13, "ABCDE", 7, false, "ABCDE ");
run(13, "ABCDE", 3, "ABC");
run(13, "ABCDE", 3, false, "ABC");
}
public void testStringRightFix() {
run(13, null, 7, true, " ");
run(13, "", 7, true, " ");
run(13, "ABCDE", 7, true, " ABCDE");
run(13, "ABCDE", 3, true, "CDE");
}
// ******************************************************************** //
// Right-Aligned Integer Tests.
// ******************************************************************** //
public void testPosIntUns() {
run(13, 173, 7, false, " 173");
run(13, 173, 3, false, "173");
run(13, 173, 2, false, " +");
run(35, 173, 7, false, "!OOB!");
}
public void testZeroIntUns() {
run(13, 0, 7, false, " 0");
run(13, 0, 1, false, "0");
}
public void testNegIntUns() {
run(13, -173, 7, false, " -");
run(13, -173, 3, false, " -");
}
public void testPosIntSgn() {
run(13, 173, 7, true, " 173");
run(13, 173, 4, true, " 173");
run(13, 173, 3, true, " +");
run(13, 173, 2, true, " +");
run(35, 173, 7, true, "!OOB!");
}
public void testZeroIntSgn() {
run(13, 0, 7, true, " 0");
run(13, 0, 2, true, " 0");
run(13, 0, 1, true, "!ILL!");
}
public void testNegIntSgn() {
run(13, -173, 7, true, " -173");
run(13, -173, 4, true, "-173");
run(13, -173, 3, true, " +");
run(13, -173, 2, true, " +");
}
// ******************************************************************** //
// Right-Aligned Zero-Padded Integer Tests.
// ******************************************************************** //
public void testZPosIntUns() {
runZ(13, 173, 7, false, "0000173");
runZ(13, 173, 3, false, "173");
runZ(13, 173, 2, false, " +");
runZ(35, 173, 7, false, "!OOB!");
}
public void testZZeroIntUns() {
runZ(13, 0, 7, false, "0000000");
runZ(13, 0, 1, false, "0");
}
public void testZNegIntUns() {
runZ(13, -173, 7, false, " -");
runZ(13, -173, 3, false, " -");
}
public void testZPosIntSgn() {
runZ(13, 173, 7, true, " 000173");
runZ(13, 173, 4, true, " 173");
runZ(13, 173, 3, true, " +");
runZ(13, 173, 2, true, " +");
runZ(35, 173, 7, true, "!OOB!");
}
public void testZZeroIntSgn() {
runZ(13, 0, 7, true, " 000000");
runZ(13, 0, 2, true, " 0");
runZ(13, 0, 1, true, "!ILL!");
}
public void testZNegIntSgn() {
runZ(13, -173, 7, true, "-000173");
runZ(13, -173, 4, true, "-173");
runZ(13, -173, 3, true, " +");
runZ(13, -173, 2, true, " +");
}
// ******************************************************************** //
// Left-Aligned Integer Tests.
// ******************************************************************** //
public void testLPosIntUns() {
runL(13, 173, 7, false, "173 ");
runL(13, 173, 3, false, "173");
runL(13, 173, 2, false, "+ ");
runL(35, 173, 7, false, "!OOB!");
}
public void testLZeroIntUns() {
runL(13, 0, 7, false, "0 ");
runL(13, 0, 1, false, "0");
}
public void testLNegIntUns() {
runL(13, -173, 7, false, "- ");
runL(13, -173, 3, false, "- ");
}
public void testLPosIntSgn() {
runL(13, 173, 7, true, " 173 ");
runL(13, 173, 4, true, " 173");
runL(13, 173, 3, true, "+ ");
runL(13, 173, 2, true, "+ ");
runL(35, 173, 7, true, "!OOB!");
}
public void testLZeroIntSgn() {
runL(13, 0, 7, true, " 0 ");
runL(13, 0, 2, true, " 0");
runL(13, 0, 1, true, "!ILL!");
}
public void testLNegIntSgn() {
runL(13, -173, 7, true, "-173 ");
runL(13, -173, 4, true, "-173");
runL(13, -173, 3, true, "+ ");
runL(13, -173, 2, true, "+ ");
}
// ******************************************************************** //
// Float Tests.
// ******************************************************************** //
public void testPosFloatUns() {
run(13, 173.45678, 7, 2, false, " 173.45");
run(13, 173.45678, 7, 3, false, "173.456");
run(13, 73.00678, 7, 4, false, "73.0067");
run(13, 173.45678, 7, 4, false, " +");
}
public void testZeroFloatUns() {
run(13, 0, 7, 2, false, " 0.00");
run(13, 0, 7, 3, false, " 0.000");
}
public void testNegFloatUns() {
run(13, -173.45678, 7, 2, false, " -");
run(13, -173.45678, 7, 3, false, " -");
run(13, -73.00678, 7, 4, false, " -");
}
public void testPosFloatSgn() {
run(13, 173.45678, 7, 2, true, " 173.45");
run(13, 73.00678, 7, 3, true, " 73.006");
run(13, 173.45678, 7, 3, true, " +");
run(13, 73.00678, 7, 4, true, " +");
}
public void testZeroFloatSgn() {
run(13, 0, 7, 2, true, " 0.00");
run(13, 0, 7, 3, true, " 0.000");
}
public void testNegFloatSgn() {
run(13, -173.45678, 7, 2, true, "-173.45");
run(13, -173.45678, 7, 2, true, "-173.45");
run(13, -73.00678, 7, 3, true, "-73.006");
run(13, -173.45678, 7, 3, true, " +");
run(13, -73.00678, 7, 4, true, " +");
}
// ******************************************************************** //
// Speed Tests.
// ******************************************************************** //
public void testSpeed() {
final int COUNT = 100000;
long j1 = System.currentTimeMillis();
for (int i = 0; i < COUNT; ++i)
String.format("%7.2f", -(i / 1345678f));
long j2 = System.currentTimeMillis();
long c1 = System.currentTimeMillis();
for (int i = 0; i < COUNT; ++i)
CharFormatter.formatFloat(buf, 13, -(i / 1345678f), 7, 2, true);
long c2 = System.currentTimeMillis();
// CharFormatter should be at least 10 times faster.
assertTrue((c2 - c1) * 10 < (j2 - j1));
}
// ******************************************************************** //
// Member Data.
// ******************************************************************** //
private char[] buf;
}
| 10,837 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
BitwiseTests.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/test/org/hermit/test/utils/BitwiseTests.java |
/**
* geo: geographical utilities.
* <br>Copyright 2004-2009 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.test.utils;
import junit.framework.TestCase;
import org.hermit.utils.Bitwise;
/**
* Test bitwise utility functions.
*
* @author Ian Cameron Smith
*/
public class BitwiseTests
extends TestCase
{
// ******************************************************************** //
// Test Framework.
// ******************************************************************** //
private void runBitrev(int val, int n, int expect) {
int res = Bitwise.bitrev(val, n);
assertEquals("bitrev", String.format("0x%08x", expect), String.format("0x%08x", res));
}
// ******************************************************************** //
// Tests.
// ******************************************************************** //
public void testSixteen() {
runBitrev(0xfda91235, 2, 0x00000002);
runBitrev(0xfda91235, 3, 0x00000005);
runBitrev(0xfda91233, 3, 0x00000006);
runBitrev(0xfda91235, 16, 0x0000ac48);
}
public void testCorners() {
runBitrev(0xfda91234, 0, 0x00000000);
runBitrev(0xfda91235, 1, 0x00000001);
runBitrev(0xfda91235, 32, 0xac4895bf);
}
}
| 1,955 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
GeodeticTests.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/test/org/hermit/test/geo/GeodeticTests.java |
/**
* geo: geographical utilities.
* <br>Copyright 2004-2009 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.test.geo;
import static java.lang.Math.toDegrees;
import static java.lang.Math.toRadians;
import static org.hermit.geo.GeoConstants.Ellipsoid.NAD27;
import static org.hermit.geo.GeoConstants.Ellipsoid.WGS84;
import static org.hermit.test.NumericAsserts.assertDegrees;
import static org.hermit.test.NumericAsserts.assertPercent;
import static org.hermit.test.NumericAsserts.assertRange;
import static org.hermit.test.NumericAsserts.assertTolerance;
import junit.framework.TestCase;
import org.hermit.geo.Azimuth;
import org.hermit.geo.Distance;
import org.hermit.geo.GeoCalculator;
import org.hermit.geo.Position;
import org.hermit.geo.Vector;
import org.hermit.geo.GeoConstants.Ellipsoid;
/**
* Test geodetic calculations.
*
* @author Ian Cameron Smith
*/
public class GeodeticTests
extends TestCase
{
// ******************************************************************** //
// Test Definitions.
// ******************************************************************** //
private static final class TestData {
public TestData(String name, Ellipsoid elip,
int ad1, int am1, double as1,
int nd1, int nm1, double ns1,
int ad2, int am2, double as2,
int nd2, int nm2, double ns2,
int zd12, int zm12, double zs12,
int zd21, int zm21, double zs21,
double dist)
{
testName = name;
ellipsoid = elip;
pos1 = new Position(dmsToRadians(ad1, am1, as1),
dmsToRadians(nd1, nm1, ns1));
pos2 = new Position(dmsToRadians(ad2, am2, as2),
dmsToRadians(nd2, nm2, ns2));
azimuth12 = new Azimuth(dmsToRadians(zd12, zm12, zs12));
azimuth21 = new Azimuth(dmsToRadians(zd21, zm21, zs21));
distance = new Distance(dist);
}
private static double dmsToRadians(int d, int m, double s) {
// Any component can be negative to make it all negative.
int sign = 1;
if (d < 0) {
sign = -1;
d = -d;
}
if (m < 0) {
sign = -1;
m = -m;
}
if (s < 0) {
sign = -1;
s = -s;
}
double deg = d + m/60.0 + s/3600.0;
return toRadians(deg) * sign;
}
// Name of the test.
String testName;
// Ellipsoid on which the test is defined.
Ellipsoid ellipsoid;
// Start and end stations.
Position pos1;
Position pos2;
// Azimuth from 1 to 2, and from 2 to 1.
Azimuth azimuth12;
Azimuth azimuth21;
// Distance between stations.
Distance distance;
}
/**
* Table of test data. Each row contains:
* - Test name, ellipsoid to use
* - Station 1 latitude, degrees; longitude, degrees
* - Station 2 latitude, degrees; longitude, degrees
* - Forward azimuth, degrees; back azimuth, degrees
* - Distance, metres
*/
private static final TestData[] testData = {
// Forward:
// 1->2:
// 33 22 11.54321 North 112 55 44.33333 West
// 2->1:
// 34 0 12.12345 North 111 0 12.12345 West
// Inverse:
// 1->2:
// Ellipsoidal distance = 191872.11903
// Forward azimuth = 249 3 16.4237
// Back azimuth = 67 59 11.1619
// 2->1:
// Ellipsoidal distance = 191872.11903
// Forward azimuth = 67 59 11.1619
// Back azimuth = 249 3 16.4237
new TestData("NGS Jones/Smith", WGS84,
34, 0,12.12345, -111, 0,12.12345,
33,22,11.54321, -112,55,44.33333,
249, 3,16.42370, 67,59,11.16190,
191872.1190
),
// Forward:
// 1->2:
// 44 33 0.00000 North 70 12 34.78900 West
// 2->1:
// 45 0 12.00000 North 68 0 0.00000 West
// Inverse:
// 1->2:
// Ellipsoidal distance = 182009.16792
// Forward azimuth = 254 42 44.6439
// Back azimuth = 73 9 21.3315
// 2->1:
// Ellipsoidal distance = 182009.16792
// Forward azimuth = 73 9 21.3315
// Back azimuth = 254 42 44.6439
new TestData("NGS Charlie/Sam", NAD27,
45, 0,12.00000, -68, 0, 0.00000,
44,33, 0.00000, -70,12,34.78900,
254,42,44.64390, 73, 9,21.33150,
182009.1679
),
// Forward:
// 1->2:
// 37 39 10.15612 South 143 55 35.38388 East
// 2->1:
// 37 57 3.72030 South 144 25 29.52440 East
// Inverse:
// 1->2:
// Ellipsoidal distance = 54972.27114
// Forward azimuth = 306 52 5.3731
// Back azimuth = 127 10 25.0703
// 2->1:
// Ellipsoidal distance = 54972.27114
// Forward azimuth = 127 10 25.0703
// Back azimuth = 306 52 5.3731
new TestData("Geoscience Australia", WGS84,
-37,57,03.72030, 144,25,29.52440,
-37,39,10.15610, 143,55,35.38390,
306,52,05.37, 127,10,25.07,
54972.271
),
// Forward:
// 1->2:
// 37 39 10.15612 South 143 55 35.38388 East
// 2->1:
// 37 57 3.72030 South 144 25 29.52440 East
// Inverse:
// 1->2:
// Ellipsoidal distance = 54972.27114
// Forward azimuth = 306 52 5.3731
// Back azimuth = 127 10 25.0703
// 2->1:
// Ellipsoidal distance = 54972.27114
// Forward azimuth = 127 10 25.0703
// Back azimuth = 306 52 5.3731
new TestData("Meeus sect. 11", WGS84,
48,50,11.00000, 2,20,14.00000,
38,55,17.00000, -77,03,56.00000,
291,50,01.08851, 51,47,36.87089,
6181631.68521
),
// Forward:
// 1->2:
// 4 33 0.00000 North 68 0 0.00000 West
// 2->1:
// 45 0 12.00000 North 68 0 0.00000 West
// Inverse:
// 1->2:
// longitudal difference is near zero
// Ellipsoidal distance = 4482191.25533
// Forward azimuth = 180 0 0.0000
// Back azimuth = 0 0 0.0000
// 2->1:
// longitudal difference is near zero
// Ellipsoidal distance = 4482191.25533
// Forward azimuth = 0 0 0.0000
// Back azimuth = 180 0 0.0000
new TestData("Meridional", WGS84,
45, 0,12.00000, -68, 0, 0.00000,
4,33, 0.00000, -68, 0, 0.00000,
180, 0, 0.00000, 0, 0, 0.00000,
4482191.25533
),
// Forward:
// 1->2:
// 4 33 0.00000 North 68 0 0.00000 West
// 2->1:
// 45 0 12.00000 North 68 0 0.00000 West
// Inverse:
// 1->2:
// Ellipsoidal distance = 4482191.25533
// Forward azimuth = 180 0 0.0000
// Back azimuth = 0 0 0.0000
// 2->1:
// Ellipsoidal distance = 4482191.25533
// Forward azimuth = 0 0 0.0000
// Back azimuth = 180 0 0.0000
new TestData("Near-Meridional", WGS84,
45, 0,12.00000, -68, 0, 0.00000,
4,33, 0.00000, -68, 0, 0.000001,
180, 0, 0.00000, 0, 0, 0.00000,
4482191.25533
),
// Forward:
// 1->2:
// 0 0 0.00000 North 23 0 0.00000 East
// 2->1:
// 0 0 0.00000 South 68 0 0.00000 West
// Inverse:
// 1->2:
// Ellipsoidal distance = 10130073.66219
// Forward azimuth = 90 0 0.0000
// Back azimuth = 270 0 0.0000
// 2->1:
// Ellipsoidal distance = 10130073.66219
// Forward azimuth = 270 0 0.0000
// Back azimuth = 90 0 0.0000
new TestData("Equatorial", WGS84,
0, 0, 0.00000, -68, 0, 0.00000,
0, 0, 0.00000, 23, 0, 0.00000,
90, 0, 0.00000, 270, 0, 0.00000,
10130073.66219
),
// Forward:
// 1->2:
// 0 0 0.00000 South 23 0 0.00000 East
// 2->1:
// 0 0 0.00000 North 68 0 0.00000 West
// Inverse:
// 1->2:
// Ellipsoidal distance = 10130073.66219
// Forward azimuth = 90 0 0.0000
// Back azimuth = 270 0 0.0000
// 2->1:
// Ellipsoidal distance = 10130073.66219
// Forward azimuth = 270 0 0.0000
// Back azimuth = 90 0 0.0000
new TestData("Near-Equatorial", WGS84,
0, 0, 0.000001, -68, 0, 0.00000,
0, 0,-0.000001, 23, 0, 0.00000,
90, 0, 0.00000, 270, 0, 0.00000,
10130073.66219
),
// Forward:
// 1->2:
// 0 25 0.00000 South 178 47 49.39063 West
// 2->1:
// 0 25 0.00000 North 1 12 10.60937 West
// Inverse:
// 1->2:
// Ellipsoidal distance = 19903598.64278
// Forward azimuth = 269 59 52.1531
// Back azimuth = 89 59 52.1531
// 2->1:
// Ellipsoidal distance = 19903598.64278
// Forward azimuth = 89 59 52.1531
// Back azimuth = 269 59 52.1531
new TestData("Near-anti-nodal", WGS84,
0, 25,0.00000, 0, 0, 0.00000,
0,-25,0.00000, 180, 0, 0.00000,
269,59,52.15310, 89,59,52.15310,
19903598.64278
),
// Forward:
// 1->2:
// 0 0 0.00000 South 180 0 0.00000 West
// 2->1:
// 0 0 0.00000 North 0 0 0.00000 East
// Inverse:
// 1->2:
// Ellipsoidal distance = 0.00000
// Forward azimuth = 0 0 0.0000
// Back azimuth = 0 0 0.0000
// 2->1:
// Ellipsoidal distance = 0.00000
// Forward azimuth = 0 0 0.0000
// Back azimuth = 0 0 0.0000
new TestData("Very near-anti-nodal", WGS84,
0, 0, 0.000001, 0, 0, 0.00000,
0, 0,-0.000001, 180, 0, 0.00000,
0, 0, 0.00000, 0, 0, 0.00000,
20003931.45846
),
// Forward:
// 1->2:
// 0 25 0.00000 North 180 0 0.00000 West
// 2->1:
// 0 0 0.00000 North 0 0 0.00000 East
// Inverse:
// 1->2:
// Ellipsoidal distance = 0.00000
// Forward azimuth = 0 0 0.0000
// Back azimuth = 0 0 0.0000
// 2->1:
// Ellipsoidal distance = 0.00000
// Forward azimuth = 0 0 0.0000
// Back azimuth = 0 0 0.0000
new TestData("Near-semi-anti-nodal", WGS84,
0,25, 0.00000, 0, 0, 0.00000,
0, 0,-0.000001, 180, 0, 0.00000,
0, 0, 0.00000, 0, 0, 0.00000,
19957858.83541
),
// Forward:
// 1->2:
// 0 25 0.00000 North 180 0 0.00000 West
// 2->1:
// 0 0 0.00000 South 0 0 0.00000 East
// Inverse:
// 1->2:
// Ellipsoidal distance = 19957858.83538
// Forward azimuth = 180 0 0.0000
// Back azimuth = 180 0 0.0000
// 2->1:
// Ellipsoidal distance = 19957858.83538
// Forward azimuth = 180 0 0.0000
// Back azimuth = 180 0 0.0000
new TestData("Semi-anti-nodal", WGS84,
0,25, 0.00000, 0, 0, 0.00000,
0, 0,-0.00000, 180, 0, 0.00000,
0, 0, 0.00000, 0, 0, 0.00000,
19957858.83538
),
// Forward:
// 1->2:
// 0 0 0.00000 South 180 0 0.00000 West
// 2->1:
// 0 0 0.00000 South 0 0 0.00000 East
// Inverse:
// 1->2:
// Ellipsoidal distance = 20003931.45846
// Forward azimuth = 0 0 0.0000
// Back azimuth = 0 0 0.0000
// 2->1:
// Ellipsoidal distance = 20003931.45846
// Forward azimuth = 0 0 0.0000
// Back azimuth = 0 0 0.0000
new TestData("Anti-nodal", WGS84,
0, 0, 0.00000, 0, 0, 0.00000,
0, 0,-0.00000, 180, 0, 0.00000,
0, 0, 0.00000, 0, 0, 0.00000,
20003931.45846
),
};
// ******************************************************************** //
// Test Code.
// ******************************************************************** //
private void doOffset(String msg, TestData test, double tol) {
msg = msg + ": " + test.testName;
Position p1 = test.pos1;
Position p2 = test.pos2;
double llTol = 360.0 * tol / 100.0;
if (test.testName.equals("Near-anti-nodal"))
llTol = 1.5;
// Try getting from 1 to 2.
Position efrom1 = p1.offset(new Vector(test.distance, test.azimuth12));
assertTolerance(msg + ": forward lat", efrom1.getLatDegs(), p2.getLatDegs(), llTol);
assertTolerance(msg + ": forward lon", efrom1.getLonDegs(), p2.getLonDegs(), llTol);
// Try getting from 2 to 1.
Position efrom2 = p2.offset(new Vector(test.distance, test.azimuth21));
assertTolerance(msg + ": reverse lat", efrom2.getLatDegs(), p1.getLatDegs(), llTol);
assertTolerance(msg + ": reverse lon", efrom2.getLonDegs(), p1.getLonDegs(), llTol);
}
private void doDistance(String msg, TestData test, double tol) {
msg = msg + ": " + test.testName;
Position p1 = test.pos1;
Position p2 = test.pos2;
if (test.testName.endsWith("ti-nodal"))
tol = Math.max(tol, 1);
// Getting the distance and azimuth from 1 to 2.
Distance d1 = p1.distance(p2);
assertPercent(msg + ": forward dst", d1.getMetres(), test.distance.getMetres(), tol);
// Getting the distance from 2 to 1.
Distance d2 = p2.distance(p1);
assertPercent(msg + ": reverse dst", d2.getMetres(), test.distance.getMetres(), tol);
}
private void doLatDistance(String msg, TestData test, double tol) {
msg = msg + ": " + test.testName;
Position p1 = test.pos1;
Position p2 = test.pos2;
// Getting the distance from 1 to the latitude of 2. We will
// calculate the same distance with the regular method as our
// reference.
Position ref1 = new Position(p2.getLatRads(), p1.getLonRads());
Distance r1 = p1.distance(ref1);
Distance d1 = p1.latDistance(p2.getLatRads());
assertPercent(msg + ": forward lat dst", d1.getMetres(), r1.getMetres(), tol);
// Getting the distance from 2 to the latitude of 1.
Position ref2 = new Position(p1.getLatRads(), p2.getLonRads());
Distance r2 = p2.distance(ref2);
Distance d2 = p2.latDistance(p1.getLatRads());
assertPercent(msg + ": reverse lat dst", d2.getMetres(), r2.getMetres(), tol);
}
private void doVector(String msg, TestData test, double tol) {
msg = msg + ": " + test.testName;
Position p1 = test.pos1;
Position p2 = test.pos2;
double azTol = 360.0 * tol / 100.0;
if (GeoCalculator.getCurrentAlgorithm() == GeoCalculator.Algorithm.HAVERSINE) {
if (test.testName.equals("Very near-anti-nodal"))
azTol = 91.0;
else if (test.testName.equals("Anti-nodal"))
azTol = 360.0;
}
// Getting the distance and azimuth from 1 to 2.
Vector vec1 = p1.vector(p2);
assertPercent(msg + ": forward dst", vec1.getDistanceMetres(), test.distance.getMetres(), tol);
assertDegrees(msg + ": forward azi", vec1.getAzimuthDegrees(), test.azimuth12.getDegrees(), azTol);
// Getting the distance from 2 to 1.
Vector vec2 = p2.vector(p1);
assertPercent(msg + ": reverse dst", vec2.getDistanceMetres(), test.distance.getMetres(), tol);
assertDegrees(msg + ": reverse azi", vec2.getAzimuthDegrees(), test.azimuth21.getDegrees(), azTol);
}
// ******************************************************************** //
// Tests.
// ******************************************************************** //
public void testHaversineOffset() {
GeoCalculator.setAlgorithm(GeoCalculator.Algorithm.HAVERSINE);
for (TestData test : testData)
doOffset("Haversine offset", test, 0.6);
}
public void testHaversineVector() {
GeoCalculator.setAlgorithm(GeoCalculator.Algorithm.HAVERSINE);
for (TestData test : testData)
doVector("Haversine vector", test, 0.6);
}
public void testHaversineLatDistance() {
GeoCalculator.setAlgorithm(GeoCalculator.Algorithm.HAVERSINE);
for (TestData test : testData)
doLatDistance("Haversine lat distance", test, 0.001);
}
public void testVincentyOffset() {
for (TestData test : testData) {
GeoCalculator.setAlgorithm(GeoCalculator.Algorithm.VINCENTY, test.ellipsoid);
doOffset("Vincenty offset", test, 0.00001);
}
}
public void testAndoyerDistance() {
for (TestData test : testData) {
GeoCalculator.setAlgorithm(GeoCalculator.Algorithm.ANDOYER, test.ellipsoid);
doDistance("Andoyer distance", test, 0.001);
}
}
public void testVincentyVector() {
for (TestData test : testData) {
GeoCalculator.setAlgorithm(GeoCalculator.Algorithm.VINCENTY, test.ellipsoid);
doVector("Vincenty vector", test, 0.00001);
}
}
public void testGeocentricLat() {
// Aside from the 45 degrees case, this is a weak test, but at
// least it tests for sane results. The 45 degrees case is a good
// one, from Meeus.
for (int lat = 0; lat <= 90; lat += 5) {
Position pos = Position.fromDegrees(lat, 0);
double gLat = toDegrees(pos.getGeocentricLat());
double delta = lat - gLat;
assertRange("Geo lat " + lat, delta, 0, 0.9125);
if (lat == 45)
assertTolerance("Geo lat " + lat, delta, 0.192425, 0.000001);
}
}
}
| 17,611 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
PoiTest.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/test/org/hermit/test/geo/PoiTest.java |
/**
* test: test code.
* <br>Copyright 2004-2009 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.test.geo;
import org.hermit.geo.PointOfInterest;
import org.hermit.geo.Position;
/**
* Test the PointOfInterest utils.
*/
public class PoiTest {
// ******************************************************************** //
// Main.
// ******************************************************************** //
/**
* @param args
*/
public static void main(String[] args) {
for (double latitude : LATS) {
for (double offset : OFFSETS) {
double lat = latitude + offset;
if (lat > HALFPI || lat < -HALFPI)
continue;
Position pos = new Position(lat, 12.34);
double deg = Math.toDegrees(lat);
String desc = PointOfInterest.describePosition(pos);
System.out.format("%8.3f -> %s\n", deg, desc);
}
}
System.out.println();
for (double[] latlon : POINTS) {
for (double offset : OFFSETS) {
double lat = latlon[0] + offset;
double lon = latlon[1] + offset;
if (lat > HALFPI || lat < -HALFPI)
continue;
if (lon > Math.PI || lon < -Math.PI)
continue;
Position pos = new Position(lat, lon);
double latd = Math.toDegrees(lat);
double lond = Math.toDegrees(lon);
String desc = PointOfInterest.describePosition(pos);
System.out.format("%8.3f,%8.3f -> %s\n", latd, lond, desc);
}
}
}
// ******************************************************************** //
// Private Constants.
// ******************************************************************** //
// Half pi = 90 degrees.
private static final double HALFPI = Math.PI / 2.0;
// The Earth's axial tilt in radians (approx).
private static final double EARTH_TILT = Math.toRadians(23.43944444);
// Interesting latitudes. Don't expose these as public constants
// because they are not constant; we need to calculate the correct
// axial tilt.
private static final double NPOLE = HALFPI;
private static final double ARCTIC = HALFPI - EARTH_TILT;
private static final double CANCER = EARTH_TILT;
private static final double EQUATOR = 0.0;
private static final double CAPRICORN = -EARTH_TILT;
private static final double ANTARC = -HALFPI + EARTH_TILT;
private static final double SPOLE = -HALFPI;
// One nautical mile over the Earth's surface, in radians.
private static final double NMILE = Math.toRadians(1.0 / 60.0);
// Table of offsets used to generate test positions.
private static final double[] OFFSETS = {
NMILE * 230, NMILE * 115.67, NMILE * 3.8765,
NMILE / 4.72, NMILE * 0.0323, NMILE * 0.0093,
0,
-NMILE * 0.0093, -NMILE * 0.0323, -NMILE / 4.72,
-NMILE * 3.8765, -NMILE * 115.67, -NMILE * 230,
};
// Table of test latitudes.
private static final double[] LATS = {
NPOLE, ARCTIC, CANCER, EQUATOR, CAPRICORN,
Math.toRadians(-40), Math.toRadians(-50), ANTARC, SPOLE
};
// Table of test latitudes.
private static final double[][] POINTS = {
{ -Math.toRadians(47d + 9d/60d), -Math.toRadians(126d + 43d/60d) },
};
}
| 3,747 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
PowerTest.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/test/org/hermit/test/dsp/PowerTest.java |
/**
* test: test code.
* <br>Copyright 2004-2009 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.test.dsp;
import org.hermit.dsp.FFTTransformer;
import org.hermit.dsp.SignalPower;
/**
* Test the signal power calculations.
*/
public class PowerTest {
// ******************************************************************** //
// Signal generation.
// ******************************************************************** //
private static short[] makeSine(double max, int rate, float freq, int buflen) {
// Make a buffer of the right length.
short[] buf = new short[buflen];
// The length of 1 cycle in samples.
int c = (int) (rate / freq);
// Fill it with a sine wave.
for (int i = 0; i < buflen; ++i) {
long val = Math.round(Math.sin((double) i / c * Math.PI * 2) * max);
if (val < Short.MIN_VALUE)
buf[i] = Short.MIN_VALUE;
else if (val > Short.MAX_VALUE)
buf[i] = Short.MAX_VALUE;
else
buf[i] = (short) val;
}
return buf;
}
// ******************************************************************** //
// Power Meter Testing.
// ******************************************************************** //
private static void runPowerTest(String name, double max, int rate, float freq, int buflen) {
// Test on a buffer of all zeroes.
short[] buf = makeSine(max, rate, freq, buflen);
double power = SignalPower.calculatePowerDb(buf, 0, buf.length);
System.out.format("%-8s@ %5dHz %5d/s: %10.5f\n", name, (int) freq, rate, power);
}
private static void runPowerAll(int rate, float freq) {
int buflen = (int) (rate * 1f);
// Test on a buffer of all zeroes.
runPowerTest("Zero", 0f, rate, freq, buflen);
// A truly miniscule signal; every 40th sample is 1, all others
// are zero.
runPowerTest("Tiny", 0.5f, rate, freq, buflen);
// A very small signal; 5 1s, 15 0s, 5 -1s, 15 0s.
runPowerTest("Small", 0.55f, rate, freq, buflen);
// Minimum "real" signal, oscillating between 1 and -1.
runPowerTest("Min", 1, rate, freq, buflen);
// A full-range sine wave, from -32768 to 32767.
runPowerTest("Full", 32768, rate, freq, buflen);
// Maximum saturated signal.
runPowerTest("Sat", 10000000, rate, freq, buflen);
// Maximum saturated signal at a low frequency to reduce the small
// values. This is an unrealistically over-saturated signal.
runPowerTest("Oversat", 10000000, rate, 80f, buflen);
}
// ******************************************************************** //
// Spectrum Analyser Testing.
// ******************************************************************** //
private static void runFftTest(String name, double max, int rate, float freq,
int buflen, FFTTransformer fft, float[] out)
{
// Test on a buffer of all zeroes.
short[] buf = makeSine(max, rate, freq, buflen);
fft.setInput(buf, 0, out.length * 2);
fft.transform();
fft.getResults(out);
float minv = Float.MAX_VALUE;
float maxv = Float.MIN_VALUE;
for (int i = 0; i < out.length; ++i) {
if (out[i] < minv)
minv = out[i];
if (out[i] > maxv)
maxv = out[i];
}
System.out.format("%-8s@ %5dHz %5d/s: MIN %10.5f MAX %10.5f\n", name, (int) freq, rate, minv, maxv);
}
private static void runFftAll(int rate, float freq, int fftBlock) {
int buflen = (int) (rate * 1f);
FFTTransformer fft = new FFTTransformer(fftBlock);
float[] out = new float[fftBlock / 2];
// Test on a buffer of all zeroes.
runFftTest("Zero", 0f, rate, freq, buflen, fft, out);
// A truly miniscule signal; every 40th sample is 1, all others
// are zero.
runFftTest("Tiny", 0.5f, rate, freq, buflen, fft, out);
// A very small signal; 5 1s, 15 0s, 5 -1s, 15 0s.
runFftTest("Small", 0.55f, rate, freq, buflen, fft, out);
// Minimum "real" signal, oscillating between 1 and -1.
runFftTest("Min", 1, rate, freq, buflen, fft, out);
// A full-range sine wave, from -32768 to 32767.
runFftTest("Full", 32768, rate, freq, buflen, fft, out);
// Maximum saturated signal.
runFftTest("Sat", 10000000, rate, freq, buflen, fft, out);
}
// ******************************************************************** //
// Main.
// ******************************************************************** //
/**
* @param args
*/
public static void main(String[] args) {
// Run the tests at a couple of different sample rates.
runPowerAll(8000, 1000);
runPowerAll(16000, 1000);
runFftAll(8000, 250, 512);
runFftAll(16000, 250, 512);
runFftAll(16000, 500, 512);
runFftAll(16000, 1000, 512);
runFftAll(16000, 2000, 512);
}
// ******************************************************************** //
// Private Constants.
// ******************************************************************** //
}
| 6,131 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
VoronoiTest.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/test/org/hermit/test/cluster/VoronoiTest.java |
/**
* cluster: Tests of cluster analysis algorithms.
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
package org.hermit.test.cluster;
import java.util.Arrays;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.hermit.geometry.Edge;
import org.hermit.geometry.Point;
import org.hermit.geometry.Graph;
import org.hermit.geometry.voronoi.Fortune;
/**
* Base class for tests of Voronoi diagram generation.
*/
public abstract class VoronoiTest
extends TestCase
{
/**
* Run a Voronoi test.
*
* @param sites Array of input sites.
* @param verts Array of expected vertices.
* @param lines Array of expected lines. These aren't the line
* segments of the final diagram; each entry is
* of the form { a, b, c }, indicating a line with
* the equation a*x + b*y = c. These lines are
* used in the description of the edges.
* @param edges Array of expected edges. Each entry is of the
* form { l, v1, v2 }, and indicates a Voronoi edge,
* which is the segment of the line with
* index l that extends from Voronoi vertex v1 to v2.
* If either vertex has the value -1, this indicates
* that the line segment is actually a semi-infinite
* ray, which extends to infinity on that side.
*/
public static void voronoiTest(Point[] sites, Point[] verts, double[][] lines, int[][] edges) {
// Compute the Voronoi graph based on the test sites.
Graph graph = Fortune.ComputeVoronoiGraph(sites);
// graph.dump("");
// Copy and sort the expected vertices array. We can NOT sort
// the original array, as the other arrays refer into it by index.
Point[] refPoints = new Point[verts.length];
for (int i = 0; i < verts.length; ++i)
refPoints[i] = verts[i];
Arrays.sort(refPoints);
// Convert the generated vertices to an array, and sort
// for comparison.
Point[] vPoints = graph.getVertexArray();
Arrays.sort(vPoints);
// Compare the vertices. Assume infinities to be equal.
assertEquals("number of vertices", refPoints.length, vPoints.length);
for (int i = 0; i < refPoints.length; ++i)
if (!(refPoints[i].isInfinite() && vPoints[i].isInfinite()))
assertEquals("vertex " + i, refPoints[i], vPoints[i]);
// Convert the expected edges to an array. Sort for comparison.
Edge[] refEdges = new Edge[edges.length];
for (int i = 0; i < edges.length; ++i) {
int[] d = edges[i];
Point v1 = d[1] >= 0 ? verts[d[1]] : Point.INFINITE;
Point v2 = d[2] >= 0 ? verts[d[2]] : Point.INFINITE;
// TODO: we're making up fake datum points here. Should do this
// based on the reference line equation.
refEdges[i] = new Edge(v1, v2, new Point(0, 0), new Point(0, 1));
}
Arrays.sort(refEdges);
// Convert the generated edges to an array and sort.
Edge[] vEdges = graph.getEdgeArray();
Arrays.sort(vEdges);
// Compare the non-infinite edges. Note that we're only checking
// the position of the vertices as yet; this is not a complete
// check in the case of semi-infinite or infinite edges.
assertEquals("number of edges", refEdges.length, vEdges.length);
for (int i = 0; i < refEdges.length; ++i)
if (refEdges[i].compareTo(vEdges[i]) != 0)
Assert.fail("edge " + i + ": expected " + refEdges[i] + "; got " + vEdges[i]);
}
}
| 4,039 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
DiamondTest.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/test/org/hermit/test/cluster/DiamondTest.java |
/**
* cluster: Tests of cluster analysis algorithms.
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
package org.hermit.test.cluster;
import org.hermit.geometry.Point;
/**
* Moderate Voronoi test scenario. This class runs a moderate Voronoi test
* on a diamond-pattern input, and does a fairly good check of the results.
*
* The input and output data came from here:
* http://people.sc.fsu.edu/~burkardt/c_src/sweep2/sweep2.html
*/
public class DiamondTest
extends VoronoiTest
{
// Input sites.
private static final Point[] DIAMOND_SITES = {
new Point(0.0, 0.0),
new Point(0.0, 1.0),
new Point(0.2, 0.5),
new Point(0.3, 0.6),
new Point(0.4, 0.5),
new Point(0.6, 0.3),
new Point(0.6, 0.5),
new Point(1.0, 0.0),
new Point(1.0, 1.0),
};
// Expected vertices. { x, y } indicates a Voronoi vertex at
// the point (x, y).
private static final Point[] DIAMOND_VERTS = {
new Point(0.500000, -0.250000),
new Point(0.287500, 0.175000),
new Point(0.300000, 0.200000),
new Point(0.500000, 0.400000),
new Point(0.300000, 0.500000),
new Point(0.987500, 0.400000),
new Point(0.500000, 0.700000),
new Point(0.06428571429, 0.73571428571),
new Point(1.112500, 0.500000),
new Point(-0.525000, 0.500000),
new Point(0.57631578947, 0.92894736842),
new Point(0.500000, 1.062500),
Point.INFINITE,
};
// Expected lines. Each entry { a, b, c } indicates a line with the
// equation a*x + b*y = c. These lines are used in the description
// of the edtges.
private static final double[][] DIAMOND_LINES = {
{ 1.000000, 0.000000, 0.500000 },
{ 1.000000, -0.750000, 0.687500 },
{ 1.000000, 0.500000, 0.375000 },
{ 0.400000, 1.000000, 0.290000 },
{ 1.000000, -1.000000, 0.100000 },
{ 0.000000, 1.000000, 0.400000 },
{ 1.000000, -0.500000, 0.200000 },
{ 1.000000, 0.000000, 0.300000 },
{ 1.000000, 0.000000, 0.500000 },
{ 1.000000, 1.000000, 0.800000 },
{ -1.000000, 1.000000, 0.200000 },
{ -0.800000, 1.000000, -0.390000 },
{ 1.000000, -0.333333, 0.266667 },
{ -0.400000, 1.000000, 0.710000 },
{ 0.800000, 1.000000, 1.390000 },
{ -0.750000, 1.000000, 0.687500 },
{ 0.000000, 1.000000, 0.500000 },
{ 0.000000, 1.000000, 0.500000 },
{ 1.000000, 0.571429, 1.107143 },
{ 1.000000, 0.000000, 0.500000 },
};
// Expected edges. Each entry { l, v1, v2 } indicates a Voronoi edge,
// which is the segment of the line with index l that extends from
// Voronoi vertex v1 to v2. If either vertex has the value -1,
// this indicates that the line segment is actually a semi-infinite
// ray, which extends to infinity on that side.
private static final int[][] DIAMOND_EDGES = {
{ 2, 1, 0 },
{ 6, 1, 2 },
{ 4, 2, 3 },
{ 7, 4, 2 },
{ 5, 3, 5 },
{ 1, 0, 5 },
{ 10, 4, 6 },
{ 8, 6, 3 },
{ 9, 7, 4 },
{ 11, 5, 8 },
{ 3, 9, 1 },
{ 13, 9, 7 },
{ 12, 6, 10 },
{ 14, 10, 8 },
{ 15, 7, 11 },
{ 18, 11, 10 },
{ 17, -1, 9 },
{ 19, -1, 11 },
{ 16, 8, -1 },
{ 0, 0, -1 },
};
/**
* Run a test on the diamond test data.
*/
public void testDiamond() {
voronoiTest(DIAMOND_SITES, DIAMOND_VERTS, DIAMOND_LINES, DIAMOND_EDGES);
}
}
| 3,769 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
SimpleTest.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/test/org/hermit/test/cluster/SimpleTest.java |
/**
* cluster: Tests of cluster analysis algorithms.
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
package org.hermit.test.cluster;
import java.util.Arrays;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.hermit.geometry.Edge;
import org.hermit.geometry.Point;
import org.hermit.geometry.Graph;
import org.hermit.geometry.voronoi.Fortune;
/**
* Simple Voronoi test scenario. This class runs a simple Voronoi test,
* and does a rough check of the results.
*/
public class SimpleTest
extends TestCase
{
/**
* Input test points, basically random.
*/
private static final Point[] INPUT_MEANS = {
new Point(235,366),
new Point(60,96),
new Point(208,194),
new Point(67,350),
new Point(192,48),
};
/**
* The edges we expect; generated by observation from a test run. This
* array doesn't include the slopes of the semi-infinite lines, so
* it's just a rough test.
*/
private static final Point[][] EXPECT_EDGES = {
{ new Point(82.70175581206308,222.47081775321087),
new Point(157.47133220910624,290.0510118043845) },
{ new Point(145.97125748502995,126.92095808383233),
Point.INFINITE },
{ new Point(82.70175581206308,222.47081775321087),
Point.INFINITE },
{ new Point(157.47133220910624,290.0510118043845),
Point.INFINITE },
{ new Point(145.97125748502995,126.92095808383233),
new Point(3626.5218487394955,-254.50924369747895) },
{ new Point(145.97125748502995,126.92095808383233),
new Point(82.70175581206308,222.47081775321087) },
{ new Point(3626.5218487394955,-254.50924369747895),
Point.INFINITE },
{ new Point(157.47133220910624,290.0510118043845),
new Point(3626.5218487394955,-254.50924369747895) },
};
/**
* Run a test on the simple test data.
*/
public void testSimple() {
Graph graph = Fortune.ComputeVoronoiGraph(INPUT_MEANS);
// Convert the expected edges to an array. Sort for comparison.
int nedges = EXPECT_EDGES.length;
Edge[] refEdges = new Edge[nedges];
for (int i = 0; i < nedges; ++i) {
Point v1 = EXPECT_EDGES[i][0];
Point v2 = EXPECT_EDGES[i][1];
// TODO: we're making up fake datum points here. Should do this
// based on the reference line equation.
refEdges[i] = new Edge(v1, v2, new Point(0, 0), new Point(0, 1));
}
Arrays.sort(refEdges);
// Convert the generated edges to an array and sort.
Edge[] vEdges = graph.getEdgeArray();
Arrays.sort(vEdges);
// Compare the non-infinite edges. Note that we're only checking
// the position of the vertices as yet; this is not a complete
// check in the case of semi-infinite or infinite edges.
assertEquals("number of edges", refEdges.length, vEdges.length);
for (int i = 0; i < refEdges.length; ++i)
if (refEdges[i].compareTo(vEdges[i]) != 0)
Assert.fail("edge " + i + ": expected " + refEdges[i] + "; got " + vEdges[i]);
}
}
| 3,477 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
BigVoronoiTest.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/test/org/hermit/test/cluster/BigVoronoiTest.java |
/**
* cluster: Tests of cluster analysis algorithms.
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
package org.hermit.test.cluster;
import org.hermit.geometry.MathTools;
import org.hermit.geometry.Point;
/**
* Big Voronoi test scenario. This class runs a large Voronoi test,
* with 100 input sites, and does a fairly good check of the results.
*
* The input and output data came from here:
* http://people.sc.fsu.edu/~burkardt/c_src/sweep2/sweep2.html
*/
public class BigVoronoiTest
extends VoronoiTest
{
// Input sites.
private static final Point[] BIG_SITES = {
new Point(0.532095, 0.894141),
new Point(0.189043, 0.613426),
new Point(0.550977, 0.415724),
new Point(0.00397384, 0.60576),
new Point(0.89423, 0.666812),
new Point(0.0730728, 0.740658),
new Point(0.64018, 0.926186),
new Point(0.389914, 0.553149),
new Point(0.046918, 0.172275),
new Point(0.820327, 0.578957),
new Point(0.166575, 0.597895),
new Point(0.587999, 0.824301),
new Point(0.184717, 0.0608049),
new Point(0.264707, 0.661072),
new Point(0.564959, 0.824897),
new Point(0.986991, 0.654621),
new Point(0.214221, 0.611877),
new Point(0.997171, 0.807318),
new Point(0.233578, 0.380796),
new Point(0.209772, 0.585171),
new Point(0.631619, 0.418295),
new Point(0.441601, 0.474479),
new Point(0.246242, 0.196578),
new Point(0.243191, 0.428592),
new Point(0.129101, 0.460463),
new Point(0.808454, 0.240363),
new Point(0.23591, 0.362678),
new Point(0.841259, 0.0182264),
new Point(0.825533, 0.867529),
new Point(0.780973, 0.282859),
new Point(0.492706, 0.0717757),
new Point(0.0641069, 0.0241644),
new Point(0.711451, 0.621806),
new Point(0.532239, 0.872561),
new Point(0.264527, 0.947361),
new Point(0.984485, 0.373498),
new Point(0.890788, 0.0900603),
new Point(0.81489, 0.765458),
new Point(0.656357, 0.383494),
new Point(0.161836, 0.878997),
new Point(0.789622, 0.367808),
new Point(0.00529994, 0.694075),
new Point(0.751558, 0.0541492),
new Point(0.315169, 0.989785),
new Point(0.0675723, 0.642346),
new Point(0.144209, 0.130059),
new Point(0.755242, 0.723929),
new Point(0.0258396, 0.306045),
new Point(0.00905612, 0.544864),
new Point(0.0917369, 0.0311395),
new Point(0.000120247, 0.760615),
new Point(0.599014, 0.406906),
new Point(0.0209242, 0.0676926),
new Point(0.402961, 0.743223),
new Point(0.536965, 0.776167),
new Point(0.791622, 0.4288),
new Point(0.0492686, 0.546021),
new Point(0.321031, 0.883358),
new Point(0.45994, 0.0493888),
new Point(0.306635, 0.920045),
new Point(0.290264, 0.480864),
new Point(0.117081, 0.709596),
new Point(0.663268, 0.827229),
new Point(0.25703, 0.908703),
new Point(0.138396, 0.712536),
new Point(0.37325, 0.578061),
new Point(0.792062, 0.598336),
new Point(0.761925, 0.679885),
new Point(0.498106, 0.0823257),
new Point(0.0791993, 0.879007),
new Point(0.389481, 0.161374),
new Point(0.909555, 0.33623),
new Point(0.78771, 0.527877),
new Point(0.87391, 0.282804),
new Point(0.914291, 0.579771),
new Point(0.126212, 0.635836),
new Point(0.962689, 0.412397),
new Point(0.662097, 0.205412),
new Point(0.514842, 0.35217),
new Point(0.573771, 0.571652),
new Point(0.541641, 0.302552),
new Point(0.880047, 0.447681),
new Point(0.854456, 0.455932),
new Point(0.882323, 0.00625933),
new Point(0.0835167, 0.817145),
new Point(0.868329, 0.54442),
new Point(0.211671, 0.598359),
new Point(0.169315, 0.4421),
new Point(0.116072, 0.753312),
new Point(0.900911, 0.0493624),
new Point(0.889781, 0.970528),
new Point(0.209244, 0.783234),
new Point(0.0556217, 0.973298),
new Point(0.787673, 0.0775736),
new Point(0.327654, 0.267293),
new Point(0.571657, 0.956988),
new Point(0.519674, 0.443726),
new Point(0.0206049, 0.472568),
new Point(0.00635056, 0.409455),
new Point(0.414254, 0.229849),
};
// Expected vertices. { x, y } indicates a Voronoi vertex at
// the point (x, y).
private static final Point[] BIG_VERTS = {
new Point(0.419582, -2.435700),
new Point(0.565847, -1.003264),
new Point(0.324966, -0.950947),
new Point(0.869151, 0.037499),
new Point(0.300812, -0.463619),
new Point(0.613461, -0.420642),
new Point(0.793528, 0.028994),
new Point(0.608770, -0.133270),
new Point(0.857338, 0.060132),
new Point(0.067141, 0.070358),
new Point(0.840710, 0.071597),
new Point(0.129055, 0.074721),
new Point(0.618791, 0.013896),
new Point(0.448758, 0.100928),
new Point(0.082218, 0.099566),
new Point(0.321727, 0.040586),
new Point(0.077349, 0.109190),
new Point(0.437804, 0.113620),
new Point(0.218773, 0.127199),
new Point(0.296482, 0.091986),
new Point(0.626385, 0.082205),
new Point(0.722244, 0.138898),
new Point(0.830634, 0.154811),
new Point(0.477547, 0.168232),
new Point(0.749045, 0.165226),
new Point(0.321189, 0.192515),
new Point(0.355334, 0.212446),
new Point(0.889503, 0.187059),
new Point(0.735216, 0.223136),
new Point(0.547788, 0.186921),
new Point(0.520067, 0.192401),
new Point(0.827441, 0.282775),
new Point(0.245294, 0.279890),
new Point(0.138555, 0.250245),
new Point(0.463117, 0.292187),
new Point(1.008234, 0.231789),
new Point(0.137955, 0.255166),
new Point(1.034507, 0.199756),
new Point(0.827464, 0.321040),
new Point(0.633847, 0.293635),
new Point(0.688146, 0.295385),
new Point(0.147205, 0.273789),
new Point(0.846367, 0.339784),
new Point(0.603676, 0.336394),
new Point(0.574582, 0.352390),
new Point(0.717875, 0.332198),
new Point(0.566469, 0.364866),
new Point(0.624295, 0.386896),
new Point(0.937997, 0.373006),
new Point(0.409040, 0.336655),
new Point(0.153601, 0.361293),
new Point(0.507367, 0.398470),
new Point(0.129143, 0.340785),
new Point(0.857504, 0.382081),
new Point(0.906422, 0.395032),
new Point(0.848176, 0.392641),
new Point(0.201987, 0.412015),
new Point(0.842804, 0.396593),
new Point(1.199456, 0.145229),
new Point(0.108630, 0.362417),
new Point(0.093729, 0.372381),
new Point(0.725906, 0.400426),
new Point(0.457785, 0.401087),
new Point(0.396472, 0.364372),
new Point(0.336883, 0.384883),
new Point(0.070569, 0.428117),
new Point(0.345321, 0.383951),
new Point(0.350844, 0.381411),
new Point(-0.258576, 0.192683),
new Point(0.361953, 0.383356),
new Point(0.710026, 0.447837),
new Point(0.807207, 0.479031),
new Point(0.881814, 0.496974),
new Point(0.030149, 0.511163),
new Point(0.077761, 0.492583),
new Point(0.834537, 0.504386),
new Point(0.366080, 0.481176),
new Point(0.589040, 0.487825),
new Point(0.708234, 0.475123),
new Point(0.588980, 0.489705),
new Point(0.589004, 0.489809),
new Point(0.217846, 0.498748),
new Point(0.827561, 0.538384),
new Point(0.936319, 0.503577),
new Point(0.215419, 0.506318),
new Point(0.951126, 0.499738),
new Point(0.179037, 0.516606),
new Point(0.329909, 0.531040),
new Point(0.168173, 0.523634),
new Point(0.788733, 0.563178),
new Point(0.506479, 0.524707),
new Point(0.123960, 0.535690),
new Point(0.187995, 0.590926),
new Point(0.192680, 0.594363),
new Point(0.028251, 0.577126),
new Point(0.201304, 0.607314),
new Point(0.678654, 0.517258),
new Point(0.738998, 0.566250),
new Point(0.670378, 0.520504),
new Point(0.106725, 0.574665),
new Point(0.867187, 0.593460),
new Point(0.052285, 0.595349),
new Point(0.091215, 0.587952),
new Point(0.290765, 0.564461),
new Point(0.482330, 0.557553),
new Point(0.291447, 0.580141),
new Point(-0.161545, 0.480541),
new Point(0.282872, 0.591927),
new Point(0.160033, 0.631376),
new Point(0.291962, 0.584240),
new Point(1.043941, 0.526576),
new Point(0.867003, 0.614704),
new Point(0.758188, 0.632161),
new Point(0.936674, 0.630762),
new Point(0.021036, 0.649671),
new Point(0.839768, 0.637614),
new Point(0.132837, 0.674101),
new Point(0.100332, 0.670078),
new Point(0.172997, 0.667722),
new Point(0.826502, 0.657407),
new Point(0.205257, 0.671579),
new Point(0.071305, 0.691447),
new Point(0.475217, 0.628239),
new Point(0.056430, 0.692279),
new Point(0.199241, 0.681133),
new Point(0.124900, 0.731646),
new Point(0.354953, 0.666606),
new Point(1.186539, 0.512269),
new Point(0.099261, 0.731054),
new Point(0.689921, 0.691489),
new Point(0.809479, 0.709630),
new Point(0.830384, 0.696690),
new Point(0.475748, 0.644876),
new Point(0.030824, 0.729533),
new Point(0.211183, 0.710443),
new Point(0.493778, 0.662825),
new Point(0.610858, 0.683896),
new Point(0.167016, 0.754704),
new Point(0.085468, 0.777922),
new Point(0.950210, 0.733761),
new Point(0.575492, 0.786441),
new Point(0.639225, 0.713227),
new Point(0.636173, 0.712511),
new Point(0.629386, 0.729299),
new Point(0.045552, 0.783372),
new Point(0.303894, 0.752535),
new Point(0.911624, 0.762031),
new Point(0.149132, 0.810391),
new Point(0.511453, 0.823229),
new Point(0.149972, 0.813508),
new Point(0.310186, 0.783000),
new Point(0.742780, 0.805428),
new Point(0.120514, 0.850809),
new Point(0.901053, 0.808064),
new Point(0.264479, 0.834032),
new Point(0.750260, 0.823787),
new Point(0.455024, 0.820463),
new Point(0.577619, 0.868650),
new Point(0.223193, 0.849756),
new Point(0.005291, 0.842767),
new Point(0.287126, 0.891222),
new Point(0.623904, 0.870217),
new Point(0.590680, 0.883741),
new Point(0.593340, 0.885871),
new Point(0.279542, 0.924393),
new Point(0.588385, 0.902582),
new Point(0.425219, 0.850254),
new Point(0.925199, 0.876897),
new Point(0.426875, 0.882648),
new Point(0.732439, 0.895540),
new Point(0.300192, 0.956226),
new Point(0.194772, 0.940833),
new Point(0.120525, 0.939434),
new Point(-0.800463, 0.203858),
new Point(-0.068622, 0.892137),
new Point(0.416510, 0.941992),
new Point(0.423822, 0.942395),
new Point(0.163488, 0.987825),
new Point(0.759290, 0.980387),
new Point(0.445834, 0.992318),
new Point(0.177717, 1.102425),
new Point(-0.942148, 0.496138),
new Point(0.720786, 1.197126),
new Point(-0.830797, 0.662462),
new Point(4.748839, 0.480514),
new Point(0.658662, 2.656735),
new Point(-13.741838, 0.341169),
Point.INFINITE,
};
// Expected lines. Each entry { a, b, c } indicates a line with the
// equation a*x + b*y = c. These lines are used in the description
// of the edtges.
private static final double[][] BIG_LINES = {
{ 1.000000, -0.291425, 0.858223 },
{ 1.000000, -0.021883, 0.472882 },
{ 1.000000, 0.252447, 0.084903 },
{ 0.431244, 1.000000, 0.412316 },
{ 1.000000, -0.102110, 0.668290 },
{ 1.000000, 0.063725, 0.264367 },
{ 1.000000, -0.400473, 0.781916 },
{ 1.000000, -0.081723, 0.647837 },
{ 1.000000, 0.049563, 0.277834 },
{ 1.000000, 0.319051, 0.152894 },
{ -0.992063, 1.000000, 0.003750 },
{ 1.000000, 0.521961, 0.888724 },
{ 1.000000, 0.683235, 0.517715 },
{ 1.000000, -0.041479, 0.320043 },
{ 1.000000, 0.016324, 0.606594 },
{ 1.000000, 0.648606, 0.812334 },
{ -0.902924, 1.000000, -0.687501 },
{ 0.511849, 1.000000, 0.330624 },
{ -0.248734, 1.000000, -0.153117 },
{ 1.000000, -0.068095, 0.617845 },
{ 0.689494, 1.000000, 0.651261 },
{ 1.000000, -0.516194, 0.030822 },
{ 1.000000, 0.121095, 0.849380 },
{ -0.584918, 1.000000, -0.000765 },
{ 0.530452, 1.000000, 0.143178 },
{ 1.000000, -0.111171, 0.617246 },
{ 1.000000, 0.862990, 0.535857 },
{ -0.629181, 1.000000, -0.161838 },
{ 1.000000, 0.505873, 0.132585 },
{ 0.248549, 1.000000, 0.128415 },
{ 1.000000, 0.491146, 0.341660 },
{ 1.000000, -0.433915, 0.029970 },
{ 1.000000, -0.727717, 0.355121 },
{ 0.453146, 1.000000, 0.226335 },
{ 1.000000, 0.651936, 0.301699 },
{ -0.591428, 1.000000, -0.288257 },
{ 1.000000, -0.245771, 0.273874 },
{ 1.000000, 0.750568, 0.688085 },
{ -0.982303, 1.000000, -0.570564 },
{ 0.361782, 1.000000, 0.341000 },
{ 0.127656, 1.000000, 0.260846 },
{ -0.547788, 1.000000, -0.300201 },
{ -0.568398, 1.000000, -0.103205 },
{ 1.000000, 0.238806, 0.788502 },
{ -0.583720, 1.000000, 0.005031 },
{ 1.000000, 0.868607, 0.488409 },
{ 1.000000, -0.432379, 0.263477 },
{ 1.000000, 0.648390, 1.010790 },
{ -0.646672, 1.000000, -0.252308 },
{ -0.087567, 1.000000, 0.109167 },
{ 1.000000, 0.651494, 0.880588 },
{ 0.197683, 1.000000, 0.295209 },
{ 1.000000, -0.806436, 0.397049 },
{ 1.000000, 0.570726, 0.629875 },
{ -0.157572, 1.000000, 0.233428 },
{ 1.000000, -0.000592, 0.827274 },
{ 0.667185, 1.000000, 0.904467 },
{ -0.540107, 1.000000, 0.042054 },
{ -0.062204, 1.000000, 0.264632 },
{ -0.961829, 1.000000, 0.043960 },
{ 0.101814, 1.000000, 0.405288 },
{ 1.000000, 0.121927, 0.169067 },
{ 0.822328, 1.000000, 0.673020 },
{ 1.000000, 0.497371, 1.123519 },
{ 1.000000, 0.820204, 1.198348 },
{ 1.000000, -0.496669, 0.011222 },
{ 0.330573, 1.000000, 0.541737 },
{ -0.128712, 1.000000, 0.341523 },
{ -0.991577, 1.000000, -0.499454 },
{ -0.032232, 1.000000, 0.273205 },
{ 1.000000, 0.705586, 0.841031 },
{ 1.000000, -0.807561, 0.449605 },
{ 1.000000, 0.269591, 0.221015 },
{ 1.000000, -0.263297, 0.756903 },
{ 0.549792, 1.000000, 0.668290 },
{ 1.000000, -0.408280, 0.466333 },
{ -0.188464, 1.000000, 0.354717 },
{ 1.000000, 0.650288, 0.803737 },
{ 1.000000, -0.117705, 0.678773 },
{ -0.560323, 1.000000, -0.152575 },
{ 0.568572, 1.000000, 0.686944 },
{ 1.000000, -0.183567, 0.499492 },
{ -0.710842, 1.000000, -0.056879 },
{ 1.000000, 0.349302, 0.759439 },
{ 0.697598, 1.000000, 1.027351 },
{ 0.201126, 1.000000, 0.452639 },
{ 0.032791, 1.000000, 0.424229 },
{ 1.000000, -0.953955, -0.191056 },
{ 1.000000, 0.453432, 0.561690 },
{ -0.838496, 1.000000, 0.232499 },
{ 1.000000, -0.894547, 0.150916 },
{ 0.052777, 1.000000, 0.425247 },
{ -0.264762, 1.000000, 0.155046 },
{ 1.000000, 0.948281, 0.452303 },
{ 1.000000, 0.883306, 1.194998 },
{ 1.000000, -0.426950, 0.737763 },
{ 1.000000, -0.322417, 0.721581 },
{ 0.735713, 1.000000, 1.016655 },
{ 1.000000, -0.182847, 0.126651 },
{ 1.000000, 0.431804, 1.014055 },
{ 0.257837, 1.000000, 0.454492 },
{ 1.000000, -0.456632, -0.056862 },
{ 0.668714, 1.000000, 0.435059 },
{ 1.000000, 0.415542, 0.248470 },
{ 1.000000, 0.334943, 0.860025 },
{ 0.225854, 1.000000, 0.444055 },
{ -0.598819, 1.000000, 0.126956 },
{ 1.000000, -0.393900, 0.299797 },
{ 0.900540, 1.000000, 0.694927 },
{ 0.549975, 1.000000, 0.582421 },
{ 0.110462, 1.000000, 0.422096 },
{ 1.000000, -0.111571, 0.022803 },
{ 0.459902, 1.000000, 0.542765 },
{ -0.175071, 1.000000, 0.319989 },
{ 0.020622, 1.000000, 0.187351 },
{ 1.000000, -0.042191, 0.345779 },
{ -0.039484, 1.000000, 0.447159 },
{ 1.000000, 0.065655, 0.739428 },
{ -0.927737, 1.000000, -0.269844 },
{ 0.156778, 1.000000, 0.635223 },
{ -0.159743, 1.000000, 0.506347 },
{ 0.390232, 1.000000, 0.522928 },
{ -0.121130, 1.000000, 0.390160 },
{ 1.000000, 0.028772, 0.044856 },
{ -0.933079, 1.000000, 0.420026 },
{ -0.657010, 1.000000, 0.240657 },
{ 1.000000, 0.205200, 0.938037 },
{ 1.000000, 0.725389, 0.715120 },
{ 1.000000, 0.031881, 0.604593 },
{ 1.000000, 0.702039, 1.041789 },
{ 0.422877, 1.000000, 0.738886 },
{ 1.000000, -0.227174, 0.477732 },
{ -0.377211, 1.000000, 0.267630 },
{ 1.000000, 0.320499, 0.377694 },
{ -0.668914, 1.000000, 0.310359 },
{ 0.638546, 1.000000, 1.066820 },
{ 1.000000, -0.719491, 0.440198 },
{ 1.000000, 0.769134, 1.323637 },
{ 0.259248, 1.000000, 0.746315 },
{ 0.282776, 1.000000, 0.567234 },
{ -0.771684, 1.000000, 0.340083 },
{ -0.289161, 1.000000, 0.224710 },
{ 0.646879, 1.000000, 0.632422 },
{ 0.853792, 1.000000, 0.812714 },
{ 0.272673, 1.000000, 0.569490 },
{ 1.000000, -0.294558, 0.013932 },
{ 1.000000, -0.685617, 0.402609 },
{ 0.143994, 1.000000, 0.622108 },
{ 0.061766, 1.000000, 0.611895 },
{ -0.083458, 1.000000, 0.574768 },
{ 1.000000, 0.735212, 0.892250 },
{ 1.000000, 0.442210, 0.360847 },
{ 0.188637, 1.000000, 0.645288 },
{ -0.733639, 1.000000, 0.453005 },
{ 1.000000, 0.691250, 0.596472 },
{ 1.000000, -0.665858, -0.203082 },
{ -0.758211, 1.000000, 0.555706 },
{ 1.000000, -0.061522, 0.163940 },
{ -0.811879, 1.000000, -0.033727 },
{ 0.392274, 1.000000, 0.783476 },
{ 1.000000, -0.291152, 0.574133 },
{ 1.000000, 0.364280, 0.859987 },
{ 1.000000, -0.939994, -0.433456 },
{ 0.856687, 1.000000, 0.666095 },
{ 0.190020, 1.000000, 0.605285 },
{ 1.000000, 0.008662, 0.872328 },
{ 1.000000, 0.575266, 0.394770 },
{ 1.000000, -0.111017, 0.025942 },
{ 1.000000, -0.043492, 0.266215 },
{ 1.000000, 0.100638, 0.538441 },
{ 0.971275, 1.000000, 1.540530 },
{ 1.000000, 0.974428, 0.859663 },
{ 1.000000, -0.125623, 0.218568 },
{ 0.019981, 1.000000, 0.477313 },
{ 0.845694, 1.000000, 0.831150 },
{ 1.000000, -0.356671, -0.065160 },
{ 1.000000, -0.764775, -0.154851 },
{ 0.100329, 1.000000, 0.631313 },
{ -0.230478, 1.000000, 0.414880 },
{ 0.841193, 1.000000, 1.344021 },
{ -0.369557, 1.000000, 0.351967 },
{ 0.869057, 1.000000, 1.291070 },
{ 1.000000, -0.131424, 0.853777 },
{ 0.015016, 1.000000, 0.649987 },
{ 1.000000, -0.830689, -0.518639 },
{ 1.000000, 0.670229, 1.267116 },
{ -0.123793, 1.000000, 0.657657 },
{ 0.158853, 1.000000, 0.695203 },
{ 1.000000, 0.137931, 0.225817 },
{ 0.736189, 1.000000, 0.743941 },
{ -0.151735, 1.000000, 0.586804 },
{ -0.511018, 1.000000, 0.579317 },
{ 1.000000, -0.098810, 0.761544 },
{ 1.000000, 0.629705, 0.628154 },
{ 1.000000, -0.705823, -0.416734 },
{ 0.055949, 1.000000, 0.695436 },
{ 1.000000, -0.031962, 0.455137 },
{ 0.179890, 1.000000, 0.730458 },
{ 1.000000, 0.687340, 0.532261 },
{ 1.000000, -0.407438, -0.078279 },
{ -0.023081, 1.000000, 0.728763 },
{ -0.547479, 1.000000, 0.663266 },
{ 1.000000, 0.594203, 0.751052 },
{ 0.008914, 1.000000, 0.522847 },
{ 1.000000, 0.294285, 0.314399 },
{ -0.077843, 1.000000, 0.727134 },
{ 0.428807, 1.000000, 0.987331 },
{ 0.618946, 1.000000, 1.210653 },
{ 1.000000, 0.696234, 1.303547 },
{ -0.804290, 1.000000, 0.028821 },
{ -0.995565, 1.000000, 0.171238 },
{ 1.000000, -0.273561, -0.168749 },
{ -0.179967, 1.000000, 0.573961 },
{ 1.000000, 0.997883, 0.920122 },
{ -0.454012, 1.000000, 0.614563 },
{ 1.000000, 0.245843, 0.656729 },
{ 1.000000, -0.884661, 0.005842 },
{ 1.000000, 0.321148, 0.409387 },
{ 0.066668, 1.000000, 0.797109 },
{ 0.136545, 1.000000, 0.789592 },
{ -0.510007, 1.000000, 0.734333 },
{ 0.732645, 1.000000, 1.429928 },
{ 1.000000, 0.943176, 1.317244 },
{ 0.574471, 1.000000, 1.117044 },
{ 1.000000, -0.025867, 0.555149 },
{ -0.890357, 1.000000, 0.144088 },
{ -0.234555, 1.000000, 0.563294 },
{ 1.000000, 0.404282, 0.924229 },
{ 1.000000, 0.038901, 0.657756 },
{ 1.000000, 0.677847, 0.576558 },
{ 1.000000, -0.206544, 0.148463 },
{ 1.000000, 0.229645, 1.086621 },
{ 0.104270, 1.000000, 0.902017 },
{ -0.686472, 1.000000, 0.472131 },
{ 1.000000, -0.269719, -0.069446 },
{ -0.049028, 1.000000, 0.798154 },
{ -0.495055, 1.000000, 0.739263 },
{ -0.069791, 1.000000, 0.842398 },
{ 1.000000, 0.789742, 0.792434 },
{ -0.584650, 1.000000, 0.601649 },
{ 1.000000, 0.895668, 1.011494 },
{ 1.000000, -0.407402, 0.414647 },
{ -0.006673, 1.000000, 0.879800 },
{ 1.000000, -0.000120, 0.120412 },
{ 1.000000, -0.350802, 0.617582 },
{ 0.380859, 1.000000, 0.934761 },
{ 1.000000, -0.396010, -0.065806 },
{ 1.000000, 0.248359, 0.954855 },
{ 0.999537, 1.000000, 1.275275 },
{ 1.000000, -0.865495, -0.174194 },
{ 1.000000, 0.312057, 0.488366 },
{ -0.392401, 1.000000, 0.778553 },
{ 0.667943, 1.000000, 0.846301 },
{ 1.000000, 0.228646, 0.490901 },
{ -0.233314, 1.000000, 0.724651 },
{ 0.512156, 1.000000, 1.189753 },
{ -0.800458, 1.000000, 0.410927 },
{ 0.193931, 1.000000, 0.978605 },
{ 1.000000, 0.296480, 0.855983 },
{ 1.000000, -0.648712, -0.320124 },
{ 0.629497, 1.000000, 1.272969 },
{ 1.000000, -0.449513, 0.182663 },
{ 1.000000, -0.051120, 0.381753 },
{ 0.623773, 1.000000, 1.454012 },
{ -0.250051, 1.000000, 0.909296 },
{ -0.657986, 1.000000, 0.268129 },
{ 1.000000, 0.051089, 0.471968 },
{ 0.122369, 1.000000, 0.992960 },
{ 1.000000, -0.316461, 0.449036 },
{ 1.000000, 0.837724, 1.101245 },
{ 1.000000, 0.665725, 0.821108 },
{ 1.000000, -0.887837, -0.713539 },
{ -0.042643, 1.000000, 0.237992 },
{ 0.260959, 1.000000, 0.874230 },
{ -0.055080, 1.000000, 0.919051 },
{ 1.000000, -0.440906, 0.008315 },
{ 1.000000, -0.124157, 0.040843 },
{ 1.000000, 0.177651, 0.933457 },
{ 1.000000, -0.127870, 0.318946 },
{ 1.000000, 0.063522, 0.247745 },
{ -0.012107, 1.000000, 0.507545 },
{ 1.000000, 0.042562, 0.771739 },
{ -0.024885, 1.000000, 0.683137 },
{ 0.029243, 1.000000, 0.619382 },
{ 1.000000, -0.033513, 0.569627 },
{ -0.017742, 1.000000, 0.584978 },
};
// Expected edges. Each entry { l, v1, v2 } indicates a Voronoi edge,
// which is the segment of the line with index l that extends from
// Voronoi vertex v1 to v2. If either vertex has the value -1,
// this indicates that the line segment is actually a semi-infinite
// ray, which extends to infinity on that side.
private static final int[][] BIG_EDGES = {
{ 4, 0, 1 },
{ 5, 2, 0 },
{ 0, 1, 3 },
{ 8, 4, 2 },
{ 7, 1, 5 },
{ 6, 5, 6 },
{ 14, 7, 5 },
{ 11, 8, 3 },
{ 2, 9, 2 },
{ 16, 6, 10 },
{ 20, 10, 8 },
{ 9, 11, 4 },
{ 19, 7, 12 },
{ 12, 13, 7 },
{ 17, 13, 12 },
{ 21, 9, 14 },
{ 24, 14, 11 },
{ 13, 4, 15 },
{ 28, 16, 14 },
{ 27, 15, 17 },
{ 26, 17, 13 },
{ 23, 11, 18 },
{ 33, 18, 19 },
{ 30, 19, 15 },
{ 25, 12, 20 },
{ 35, 20, 21 },
{ 15, 21, 6 },
{ 22, 22, 10 },
{ 32, 17, 23 },
{ 38, 21, 24 },
{ 40, 24, 22 },
{ 36, 19, 25 },
{ 44, 25, 26 },
{ 39, 26, 23 },
{ 41, 22, 27 },
{ 43, 28, 24 },
{ 37, 29, 20 },
{ 42, 23, 30 },
{ 51, 30, 29 },
{ 48, 28, 31 },
{ 47, 31, 27 },
{ 45, 32, 25 },
{ 31, 16, 33 },
{ 34, 33, 18 },
{ 53, 34, 30 },
{ 61, 36, 33 },
{ 64, 35, 37 },
{ 49, 27, 37 },
{ 55, 31, 38 },
{ 52, 29, 39 },
{ 69, 39, 40 },
{ 50, 40, 28 },
{ 65, 36, 41 },
{ 58, 41, 32 },
{ 68, 38, 42 },
{ 56, 42, 35 },
{ 70, 43, 39 },
{ 57, 34, 44 },
{ 74, 44, 43 },
{ 71, 40, 45 },
{ 60, 45, 38 },
{ 77, 46, 44 },
{ 75, 43, 47 },
{ 63, 48, 35 },
{ 46, 26, 49 },
{ 62, 49, 34 },
{ 80, 51, 46 },
{ 72, 52, 41 },
{ 89, 52, 50 },
{ 73, 42, 53 },
{ 92, 53, 54 },
{ 84, 54, 48 },
{ 94, 55, 53 },
{ 87, 50, 56 },
{ 97, 57, 55 },
{ 66, 37, 58 },
{ 18, 8, 58 },
{ 93, 59, 52 },
{ 102, 60, 59 },
{ 78, 45, 61 },
{ 86, 61, 57 },
{ 91, 62, 51 },
{ 88, 63, 49 },
{ 106, 63, 62 },
{ 85, 56, 64 },
{ 67, 50, 64 },
{ 103, 65, 60 },
{ 110, 64, 66 },
{ 112, 66, 67 },
{ 59, 32, 67 },
{ 29, 68, 16 },
{ 54, 68, 36 },
{ 113, 67, 69 },
{ 109, 69, 63 },
{ 82, 47, 70 },
{ 104, 70, 61 },
{ 99, 71, 57 },
{ 96, 55, 72 },
{ 121, 73, 74 },
{ 111, 65, 74 },
{ 118, 71, 75 },
{ 119, 75, 72 },
{ 115, 69, 76 },
{ 81, 46, 77 },
{ 83, 77, 47 },
{ 117, 78, 70 },
{ 116, 78, 71 },
{ 90, 51, 79 },
{ 128, 79, 77 },
{ 131, 79, 80 },
{ 98, 56, 81 },
{ 108, 81, 66 },
{ 126, 82, 75 },
{ 122, 72, 83 },
{ 133, 84, 81 },
{ 138, 83, 85 },
{ 95, 54, 85 },
{ 101, 59, 86 },
{ 139, 86, 84 },
{ 127, 87, 76 },
{ 142, 88, 86 },
{ 135, 89, 82 },
{ 107, 62, 90 },
{ 130, 90, 80 },
{ 124, 74, 91 },
{ 144, 91, 88 },
{ 145, 88, 92 },
{ 153, 92, 93 },
{ 123, 94, 73 },
{ 155, 93, 95 },
{ 129, 96, 78 },
{ 158, 96, 97 },
{ 148, 97, 89 },
{ 132, 80, 98 },
{ 159, 98, 96 },
{ 151, 99, 91 },
{ 136, 82, 100 },
{ 137, 100, 83 },
{ 156, 94, 101 },
{ 164, 101, 102 },
{ 163, 102, 99 },
{ 140, 84, 103 },
{ 143, 103, 87 },
{ 125, 76, 104 },
{ 150, 104, 90 },
{ 147, 93, 105 },
{ 168, 103, 105 },
{ 105, 106, 65 },
{ 120, 106, 73 },
{ 152, 95, 107 },
{ 162, 99, 108 },
{ 154, 108, 92 },
{ 174, 107, 109 },
{ 172, 105, 109 },
{ 141, 85, 110 },
{ 165, 111, 100 },
{ 160, 97, 112 },
{ 178, 111, 113 },
{ 170, 113, 110 },
{ 166, 114, 101 },
{ 146, 89, 115 },
{ 179, 115, 111 },
{ 167, 102, 117 },
{ 186, 117, 116 },
{ 187, 116, 118 },
{ 175, 108, 118 },
{ 180, 112, 119 },
{ 185, 119, 115 },
{ 157, 95, 120 },
{ 171, 120, 107 },
{ 189, 121, 117 },
{ 134, 87, 122 },
{ 169, 122, 104 },
{ 184, 114, 123 },
{ 195, 123, 121 },
{ 191, 118, 124 },
{ 193, 124, 120 },
{ 188, 125, 116 },
{ 176, 109, 126 },
{ 177, 110, 127 },
{ 79, 48, 127 },
{ 194, 121, 128 },
{ 200, 128, 125 },
{ 181, 129, 112 },
{ 190, 129, 130 },
{ 207, 130, 131 },
{ 192, 119, 131 },
{ 197, 126, 132 },
{ 196, 122, 132 },
{ 198, 133, 123 },
{ 199, 124, 134 },
{ 210, 132, 135 },
{ 212, 135, 136 },
{ 161, 136, 98 },
{ 201, 125, 137 },
{ 213, 137, 134 },
{ 204, 138, 128 },
{ 182, 113, 139 },
{ 206, 141, 129 },
{ 216, 136, 142 },
{ 226, 142, 141 },
{ 222, 140, 143 },
{ 227, 143, 142 },
{ 211, 133, 144 },
{ 219, 144, 138 },
{ 214, 134, 145 },
{ 202, 145, 126 },
{ 209, 131, 146 },
{ 221, 146, 139 },
{ 220, 138, 147 },
{ 217, 147, 137 },
{ 223, 148, 140 },
{ 234, 147, 149 },
{ 230, 145, 150 },
{ 225, 141, 151 },
{ 208, 151, 130 },
{ 238, 152, 149 },
{ 231, 153, 146 },
{ 240, 154, 150 },
{ 241, 151, 155 },
{ 232, 155, 153 },
{ 215, 156, 135 },
{ 235, 156, 148 },
{ 233, 148, 157 },
{ 224, 140, 157 },
{ 236, 149, 158 },
{ 245, 158, 154 },
{ 229, 159, 144 },
{ 237, 159, 152 },
{ 246, 154, 160 },
{ 228, 161, 143 },
{ 249, 157, 162 },
{ 256, 162, 163 },
{ 255, 163, 161 },
{ 253, 164, 160 },
{ 258, 165, 163 },
{ 239, 150, 166 },
{ 248, 166, 156 },
{ 244, 153, 167 },
{ 262, 166, 168 },
{ 242, 168, 162 },
{ 254, 161, 169 },
{ 247, 169, 155 },
{ 259, 164, 170 },
{ 250, 171, 158 },
{ 257, 171, 164 },
{ 243, 152, 172 },
{ 114, 173, 68 },
{ 76, 173, 60 },
{ 252, 174, 159 },
{ 264, 174, 172 },
{ 267, 170, 175 },
{ 251, 160, 175 },
{ 274, 175, 176 },
{ 266, 176, 168 },
{ 271, 172, 177 },
{ 270, 177, 171 },
{ 268, 169, 178 },
{ 263, 178, 167 },
{ 275, 176, 179 },
{ 260, 179, 165 },
{ 276, 177, 180 },
{ 269, 180, 170 },
{ 173, 181, 106 },
{ 149, 181, 94 },
{ 261, 165, 182 },
{ 277, 182, 178 },
{ 183, 183, 114 },
{ 205, 183, 133 },
{ 218, 139, 184 },
{ 203, 127, 184 },
{ 278, 179, 185 },
{ 281, 185, 182 },
{ 280, 186, 181 },
{ 282, 186, 183 },
{ 1, -1, 0 },
{ 10, -1, 9 },
{ 272, -1, 173 },
{ 285, -1, 186 },
{ 273, -1, 174 },
{ 279, -1, 180 },
{ 284, 185, -1 },
{ 265, 167, -1 },
{ 283, 184, -1 },
{ 100, 58, -1 },
{ 3, 3, -1 },
};
/**
* Run a test on the big test data.
*/
public void testBig() {
MathTools.setPrecision(100000.0);
voronoiTest(BIG_SITES, BIG_VERTS, BIG_LINES, BIG_EDGES);
}
}
| 32,436 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
TestParallax.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/test/org/hermit/test/astro/TestParallax.java |
/**
* astro: astronomical functions, utilities and data
*
* This package was created by Ian Cameron Smith in February 2009, based
* on the formulae in "Practical Astronomy with your Calculator" by
* Peter Duffett-Smith, ISBN-10: 0521356997.
*
* Note that the formulae have been converted to work in radians, to
* make it easier to work with java.lang.Math.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.test.astro;
import static java.lang.Math.toDegrees;
import static org.hermit.test.NumericAsserts.assertDegrees;
import static org.hermit.test.NumericAsserts.assertTolerance;
import junit.framework.TestCase;
import org.hermit.astro.AstroError;
import org.hermit.astro.Body;
import org.hermit.astro.Instant;
import org.hermit.astro.Observation;
import org.hermit.astro.Planet;
import org.hermit.astro.Body.Field;
import org.hermit.geo.Position;
/**
* Test code.
*/
public class TestParallax
extends TestCase
{
// ******************************************************************** //
// Test Code.
// ******************************************************************** //
private static void testParallax(Body b, double cα, double cδ) throws AstroError {
String n = b.getId().toString();
String lab = "Topo Position " + n;
// double α = toDegrees(b.get(Field.RIGHT_ASCENSION_AP));
// double δ = toDegrees(b.get(Field.DECLINATION_AP));
double αt = toDegrees(b.get(Field.RIGHT_ASCENSION_TOPO));
double δt = toDegrees(b.get(Field.DECLINATION_TOPO));
assertDegrees(lab + " α", αt, cα, 0.001);
assertTolerance(lab + " δ", δt, cδ, 0.001);
}
public void testParallax() throws AstroError {
// From Meeus chapter 40.
Instant instant = new Instant(2003, 8, 28.0 + (3.0+17.0/60.0)/24.0);
Observation o = new Observation(instant);
o.setObserverPosition(Position.fromDegrees(33.3561111, -116.8625));
o.setObserverAltitude(1706);
Planet mars = o.getPlanet(Planet.Name.MARS);
testParallax(mars, 339.530208 + 0.0053917, -15.7750000);
}
}
| 2,450 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
TestRiseSet.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/test/org/hermit/test/astro/TestRiseSet.java |
/**
* astro: astronomical functions, utilities and data
*
* This package was created by Ian Cameron Smith in February 2009, based
* on the formulae in "Practical Astronomy with your Calculator" by
* Peter Duffett-Smith, ISBN-10: 0521356997.
*
* Note that the formulae have been converted to work in radians, to
* make it easier to work with java.lang.Math.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.test.astro;
import static org.hermit.test.NumericAsserts.assertTolerance;
import junit.framework.TestCase;
import org.hermit.astro.AstroError;
import org.hermit.astro.Body;
import org.hermit.astro.Observation;
import org.hermit.geo.Position;
/**
* Test code.
*/
public class TestRiseSet
extends TestCase
{
// ******************************************************************** //
// Rise and Set.
// ******************************************************************** //
private static void testRiseSet(String lab, Body b,
double cr, double ct, double cs)
throws AstroError
{
double r = b.get(Body.Field.RISE_TIME);
double t = b.get(Body.Field.TRANSIT_TIME);
double s = b.get(Body.Field.SET_TIME);
assertTolerance(lab + " rise", r, cr, 0.0004);
assertTolerance(lab + " tran", t, ct, 0.0004);
assertTolerance(lab + " set", s, cs, 0.0004);
}
private static void testTwilight(String lab, Body b, double cr, double cs)
throws AstroError
{
double r = b.get(Body.Field.RISE_TWILIGHT);
double s = b.get(Body.Field.SET_TWILIGHT);
assertTolerance(lab + " rise t", r, cr, 0.02);
assertTolerance(lab + " set t", s, cs, 0.02);
}
public void testVenusRiseSet() throws AstroError {
Observation o = new Observation();
o.setDate(1988, 3, 20.0);
o.setObserverPosition(Position.fromDegrees(42.3333, -71.0833));
Body venus = o.getBody(Body.Name.VENUS);
testRiseSet("Meeus 15", venus, 24 * 0.51766, 24 * 0.81980, 24 * 0.12130);
}
public void testSunRiseSet() throws AstroError {
Observation o = new Observation();
o.setDate(1979, 9, 7.0);
o.setObserverPosition(Position.fromDegrees(52, 0));
Body sun = o.getBody(Body.Name.SUN);
testRiseSet("PAC 50", sun, 5.338, 11.9696, 18.583);
}
public void testTwilight() throws AstroError {
Observation o = new Observation();
o.setDate(1979, 9, 7.0);
o.setObserverPosition(Position.fromDegrees(52, 0));
Body sun = o.getBody(Body.Name.SUN);
testTwilight("PAC 50", sun, 3.283, 20.616667);
}
}
| 2,883 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.