1 33 34 35 package bsh; 36 37 import java.lang.reflect.Array ; 38 39 class BSHArrayInitializer extends SimpleNode 40 { 41 BSHArrayInitializer(int id) { super(id); } 42 43 public Object eval( CallStack callstack, Interpreter interpreter ) 44 throws EvalError 45 { 46 throw new EvalError( "Array initializer has no base type.", 47 this, callstack ); 48 } 49 50 57 public Object eval( Class baseType, int dimensions, 58 CallStack callstack, Interpreter interpreter ) 59 throws EvalError 60 { 61 int numInitializers = jjtGetNumChildren(); 62 63 int [] dima = new int [dimensions]; dima[0] = numInitializers; 68 Object initializers = Array.newInstance( baseType, dima ); 69 70 for (int i = 0; i < numInitializers; i++) 72 { 73 SimpleNode node = (SimpleNode)jjtGetChild(i); 74 Object currentInitializer; 75 if ( node instanceof BSHArrayInitializer ) { 76 if ( dimensions < 2 ) 77 throw new EvalError( 78 "Invalid Location for Intializer, position: "+i, 79 this, callstack ); 80 currentInitializer = 81 ((BSHArrayInitializer)node).eval( 82 baseType, dimensions-1, callstack, interpreter); 83 } else 84 currentInitializer = node.eval( callstack, interpreter); 85 86 if ( currentInitializer == Primitive.VOID ) 87 throw new EvalError( 88 "Void in array initializer, position"+i, this, callstack ); 89 90 Object value = currentInitializer; 100 if ( dimensions == 1 ) 101 { 102 try { 105 value = Types.castObject( 106 currentInitializer, baseType, Types.CAST ); 107 } catch ( UtilEvalError e ) { 108 throw e.toEvalError( 109 "Error in array initializer", this, callstack ); 110 } 111 value = Primitive.unwrap( value ); 113 } 114 115 try { 117 Array.set(initializers, i, value); 118 } catch( IllegalArgumentException e ) { 119 Interpreter.debug("illegal arg"+e); 120 throwTypeError( baseType, currentInitializer, i, callstack ); 121 } catch( ArrayStoreException e ) { Interpreter.debug("arraystore"+e); 123 throwTypeError( baseType, currentInitializer, i, callstack ); 124 } 125 } 126 127 return initializers; 128 } 129 130 private void throwTypeError( 131 Class baseType, Object initializer, int argNum, CallStack callstack ) 132 throws EvalError 133 { 134 String rhsType; 135 if (initializer instanceof Primitive) 136 rhsType = 137 ((Primitive)initializer).getType().getName(); 138 else 139 rhsType = Reflect.normalizeClassName( 140 initializer.getClass()); 141 142 throw new EvalError ( "Incompatible type: " + rhsType 143 +" in initializer of array type: "+ baseType 144 +" at position: "+argNum, this, callstack ); 145 } 146 147 } 148 | Popular Tags |