Ejemplo n.º 1
0
 /**
  * Prints an entire subpopulation in a form readable by humans but also parseable by the computer
  * using readSubpopulation(EvolutionState, LineNumberReader) with a verbosity of
  * Output.V_NO_GENERAL.
  */
 public void printSubpopulation(final EvolutionState state, final int log) {
   state.output.println(NUM_INDIVIDUALS_PREAMBLE + Code.encode(individuals.length), log);
   for (int i = 0; i < individuals.length; i++) {
     state.output.println(INDIVIDUAL_INDEX_PREAMBLE + Code.encode(i), log);
     individuals[i].printIndividual(state, log);
   }
 }
Ejemplo n.º 2
0
 /**
  * Prints an entire subpopulation in a form readable by humans but also parseable by the computer
  * using readSubpopulation(EvolutionState, LineNumberReader).
  */
 public void printSubpopulation(final EvolutionState state, final PrintWriter writer) {
   writer.println(NUM_INDIVIDUALS_PREAMBLE + Code.encode(individuals.length));
   for (int i = 0; i < individuals.length; i++) {
     writer.println(INDIVIDUAL_INDEX_PREAMBLE + Code.encode(i));
     individuals[i].printIndividual(state, writer);
   }
 }
Ejemplo n.º 3
0
 private Code readEmpty(
     int opcode,
     boolean wideBase,
     boolean wideRest,
     int offset,
     HashMap<Integer, Code.Label> labels)
     throws IOException {
   switch (opcode) {
     case Code.OPCODE_const:
       {
         int target = readBase(wideBase);
         int idx = readRest(wideRest);
         Constant c = constantPool[idx];
         return Code.Const(target, c);
       }
     case Code.OPCODE_goto:
       {
         int target = readTarget(wideRest, offset);
         Code.Label lab = findLabel(target, labels);
         return Code.Goto(lab.label);
       }
     case Code.OPCODE_nop:
       return Code.Nop;
     case Code.OPCODE_returnv:
       return Code.Return();
   }
   throw new RuntimeException("unknown opcode encountered (" + opcode + ")");
 }
Ejemplo n.º 4
0
 private Code readBinaryOp(
     int opcode,
     boolean wideBase,
     boolean wideRest,
     int offset,
     HashMap<Integer, Code.Label> labels)
     throws IOException {
   int leftOperand = readBase(wideBase);
   int rightOperand = readBase(wideBase);
   int typeIdx = readRest(wideRest);
   Type type = typePool[typeIdx];
   switch (opcode) {
     case Code.OPCODE_asserteq:
     case Code.OPCODE_assertne:
     case Code.OPCODE_assertlt:
     case Code.OPCODE_assertle:
     case Code.OPCODE_assertgt:
     case Code.OPCODE_assertge:
     case Code.OPCODE_assertel:
     case Code.OPCODE_assertss:
     case Code.OPCODE_assertse:
       {
         int msgIdx = readRest(wideRest);
         String msg = stringPool[msgIdx];
         Code.Comparator cop = Code.Comparator.values()[opcode - Code.OPCODE_asserteq];
         return Code.Assert(type, leftOperand, rightOperand, cop, msg);
       }
     case Code.OPCODE_assumeeq:
     case Code.OPCODE_assumene:
     case Code.OPCODE_assumelt:
     case Code.OPCODE_assumele:
     case Code.OPCODE_assumegt:
     case Code.OPCODE_assumege:
     case Code.OPCODE_assumeel:
     case Code.OPCODE_assumess:
     case Code.OPCODE_assumese:
       {
         int msgIdx = readRest(wideRest);
         String msg = stringPool[msgIdx];
         Code.Comparator cop = Code.Comparator.values()[opcode - Code.OPCODE_assumeeq];
         return Code.Assume(type, leftOperand, rightOperand, cop, msg);
       }
     case Code.OPCODE_ifeq:
     case Code.OPCODE_ifne:
     case Code.OPCODE_iflt:
     case Code.OPCODE_ifle:
     case Code.OPCODE_ifgt:
     case Code.OPCODE_ifge:
     case Code.OPCODE_ifel:
     case Code.OPCODE_ifss:
     case Code.OPCODE_ifse:
       {
         int target = readTarget(wideRest, offset);
         Code.Label l = findLabel(target, labels);
         Code.Comparator cop = Code.Comparator.values()[opcode - Code.OPCODE_ifeq];
         return Code.If(type, leftOperand, rightOperand, cop, l.label);
       }
   }
   throw new RuntimeException("unknown opcode encountered (" + opcode + ")");
 }
Ejemplo n.º 5
0
 private static Code.LoopEnd findLoopLabel(int target, HashMap<Integer, Code.Label> labels) {
   Code.Label label = labels.get(target);
   if (label == null) {
     Code.LoopEnd end = Code.LoopEnd("label" + labelCount++);
     labels.put(target, end);
     return end;
   } else {
     Code.LoopEnd end = Code.LoopEnd(label.label);
     labels.put(target, end);
     return end;
   }
 }
  /**
   * Dumps the contents of the specified class to the specified directory. The file is named
   * dump_dir/[class].bcel. It contains a synopsis of the fields and methods followed by the jvm
   * code for each method.
   *
   * @param jc javaclass to dump
   * @param dump_dir directory in which to write the file
   */
  public static void dump(JavaClass jc, File dump_dir) {

    try {
      dump_dir.mkdir();
      File path = new File(dump_dir, jc.getClassName() + ".bcel");
      PrintStream p = new PrintStream(path);

      // Print the class, super class and interfaces
      p.printf("class %s extends %s\n", jc.getClassName(), jc.getSuperclassName());
      String[] inames = jc.getInterfaceNames();
      if ((inames != null) && (inames.length > 0)) {
        p.printf("   ");
        for (String iname : inames) p.printf("implements %s ", iname);
        p.printf("\n");
      }

      // Print each field
      p.printf("\nFields\n");
      for (Field f : jc.getFields()) p.printf("  %s\n", f);

      // Print the signature of each method
      p.printf("\nMethods\n");
      for (Method m : jc.getMethods()) p.printf("  %s\n", m);

      // If this is not an interface, print the code for each method
      if (!jc.isInterface()) {
        for (Method m : jc.getMethods()) {
          p.printf("\nMethod %s\n", m);
          Code code = m.getCode();
          if (code != null) p.printf("  %s\n", code.toString().replace("\n", "\n  "));
        }
      }

      // Print the details of the constant pool.
      p.printf("Constant Pool:\n");
      ConstantPool cp = jc.getConstantPool();
      Constant[] constants = cp.getConstantPool();
      for (int ii = 0; ii < constants.length; ii++) {
        p.printf("  %d %s\n", ii, constants[ii]);
      }

      p.close();

    } catch (Exception e) {
      throw new Error("Unexpected error dumping javaclass", e);
    }
  }
 /**
  * If debugging was enabled during compilation, this method returns the name of the given
  * parameter to this method. Otherwise, <code>null</code> is returned.
  *
  * @param index The index of the parameter.
  * @return The name of the parameter, or <code>null</code>.
  */
 public String getParameterName(int index) {
   if (index >= 0 && index < getParameterCount()) {
     if (codeAttr != null) {
       return codeAttr.getParameterName(index);
     }
   }
   return null;
 }
Ejemplo n.º 8
0
 private static Code.Label findLabel(int target, HashMap<Integer, Code.Label> labels) {
   Code.Label label = labels.get(target);
   if (label == null) {
     label = Code.Label("label" + labelCount++);
     labels.put(target, label);
   }
   return label;
 }
Ejemplo n.º 9
0
 private Code readOther(
     int opcode,
     boolean wideBase,
     boolean wideRest,
     int offset,
     HashMap<Integer, Code.Label> labels)
     throws IOException {
   switch (opcode) {
     case Code.OPCODE_trycatch:
       {
         int operand = readBase(wideBase);
         int target = readTarget(wideRest, offset);
         Code.Label l = findLabel(target, labels);
         int nCatches = readRest(wideRest);
         ArrayList<Pair<Type, String>> catches = new ArrayList<Pair<Type, String>>();
         for (int i = 0; i != nCatches; ++i) {
           Type type = typePool[readRest(wideRest)];
           Code.Label handler = findLabel(readTarget(wideRest, offset), labels);
           catches.add(new Pair<Type, String>(type, handler.label));
         }
         return Code.TryCatch(operand, l.label, catches);
       }
     case Code.OPCODE_update:
       {
         int target = readBase(wideBase);
         int nOperands = readBase(wideBase) - 1;
         int operand = readBase(wideBase);
         int[] operands = new int[nOperands];
         for (int i = 0; i != nOperands; ++i) {
           operands[i] = readBase(wideBase);
         }
         Type beforeType = typePool[readRest(wideRest)];
         Type afterType = typePool[readRest(wideRest)];
         int nFields = readRest(wideRest);
         ArrayList<String> fields = new ArrayList<String>();
         for (int i = 0; i != nFields; ++i) {
           String field = stringPool[readRest(wideRest)];
           fields.add(field);
         }
         return Code.Update(beforeType, target, operand, operands, afterType, fields);
       }
   }
   throw new RuntimeException("unknown opcode encountered (" + opcode + ")");
 }
Ejemplo n.º 10
0
 private Code readUnaryOp(
     int opcode,
     boolean wideBase,
     boolean wideRest,
     int offset,
     HashMap<Integer, Code.Label> labels)
     throws IOException {
   int operand = readBase(wideBase);
   int typeIdx = readRest(wideRest);
   Type type = typePool[typeIdx];
   switch (opcode) {
     case Code.OPCODE_debug:
       return Code.Debug(operand);
     case Code.OPCODE_ifis:
       {
         int resultIdx = readRest(wideRest);
         Type result = typePool[resultIdx];
         int target = readTarget(wideRest, offset);
         Code.Label l = findLabel(target, labels);
         return Code.IfIs(type, operand, result, l.label);
       }
     case Code.OPCODE_throw:
       return Code.Throw(type, operand);
     case Code.OPCODE_return:
       return Code.Return(type, operand);
     case Code.OPCODE_switch:
       {
         ArrayList<Pair<Constant, String>> cases = new ArrayList<Pair<Constant, String>>();
         int target = readTarget(wideRest, offset);
         Code.Label defaultLabel = findLabel(target, labels);
         int nCases = readRest(wideRest);
         for (int i = 0; i != nCases; ++i) {
           int constIdx = readRest(wideRest);
           Constant constant = constantPool[constIdx];
           target = readTarget(wideRest, offset);
           Code.Label l = findLabel(target, labels);
           cases.add(new Pair<Constant, String>(constant, l.label));
         }
         return Code.Switch(type, operand, defaultLabel.label, cases);
       }
   }
   throw new RuntimeException("unknown opcode encountered (" + opcode + ")");
 }
  protected void parseGenotype(final EvolutionState state, final LineNumberReader reader)
      throws IOException {
    // read in the next line.  The first item is the number of genes
    String s = reader.readLine();
    DecodeReturn d = new DecodeReturn(s);
    Code.decode(d);
    if (d.type != DecodeReturn.T_INTEGER) // uh oh
    state.output.fatal(
          "Individual with genome:\n"
              + s
              + "\n... does not have an integer at the beginning indicating the genome count.");
    int lll = (int) (d.l);

    genome = new boolean[lll];

    // read in the genes
    for (int i = 0; i < genome.length; i++) {
      Code.decode(d);
      genome[i] = (boolean) (d.l != 0);
    }
  }
Ejemplo n.º 12
0
  /**
   * Reads a subpopulation from the format generated by printSubpopulation(....). If the number of
   * individuals is not identical, the individuals array will be deleted and replaced with a new
   * array, and a warning will be generated as individuals will have to be created using
   * newIndividual(...) rather than readIndividual(...).
   */
  public void readSubpopulation(final EvolutionState state, final LineNumberReader reader)
      throws IOException {
    // read in number of individuals and check to see if this appears to be a valid subpopulation
    int numIndividuals = Code.readIntegerWithPreamble(NUM_INDIVIDUALS_PREAMBLE, state, reader);

    // read in individuals
    if (numIndividuals != individuals.length) {
      state.output.warnOnce(
          "On reading subpopulation from text stream, the subpopulation size didn't match.\n"
              + "Had to resize and use newIndividual() instead of readIndividual().");
      individuals = new Individual[numIndividuals];
      for (int i = 0; i < individuals.length; i++) {
        int j = Code.readIntegerWithPreamble(INDIVIDUAL_INDEX_PREAMBLE, state, reader);
        // sanity check
        if (j != i)
          state.output.warnOnce(
              "On reading subpopulation from text stream, some individual indexes in the subpopulation did not match.");
        individuals[i] = species.newIndividual(state, reader);
      }
    } else
      for (int i = 0; i < individuals.length; i++) {
        int j = Code.readIntegerWithPreamble(INDIVIDUAL_INDEX_PREAMBLE, state, reader);
        // sanity check
        if (j != i)
          state.output.warnOnce(
              "On reading subpopulation from text stream, some individual indexes in the subpopulation did not match.");
        if (individuals[i] != null) individuals[i].readIndividual(state, reader);
        else {
          state.output.warnOnce(
              "On reading subpopulation from text stream, some of the preexisting subpopulation's slots were null.\n"
                  + "Had to use newIndividual() instead of readIndividual().  If you're starting an evolutionary run by reading an\n"
                  + "existing population from a file, this is expected -- ignore this message.");
          individuals[i] = species.newIndividual(state, reader);
        }
      }
  }
  // While loop handles the basic cases like declare while loop for i<10, iterate until i less than
  // ten and j less than 20
  private void while_loop() {
    VarSymbol v = null;
    FuncSymbol f = null;
    int index =
        input.indexOf(
            words.get(wordLoc)); // Index in input string at which the word was encountered
    index += (words.get(wordLoc).length() + 1);
    String str = input.substring(index); // Further processing will be done on this string
    tokens = str.split("[ ]+");
    String expString = "";

    tIndex = 0;
    while (true) {
      if ((v = Controller.varSym.searchSymbol(tokens[tIndex]))
          != null /*TODO Check whether token is a number*/) {
        expString = searchExpression();
        if (words.get(wordLoc).indexOf("until") != -1)
          code.setCodeText("while(!(" + expString + "))");
        else code.setCodeText("while(" + expString + ")");
        code.setErrCode(IErrorCodes.SUCCESS);
        code.setErrParam(null);
        break;
      } else if ((f = Controller.funSym.searchSymbol(tokens[tIndex])) != null) {
        int tempIndex = input.indexOf(tokens[tIndex]);
        expString = exp.generateExpression(input.substring(tempIndex));
        if (words.get(wordLoc).indexOf("until") != -1)
          code.setCodeText("while(!(" + expString + "))");
        else code.setCodeText("while(" + expString + ")");
        code.setErrCode(IErrorCodes.SUCCESS);
        code.setErrParam(null);
        break;
      } else if ((tokens[tIndex].equals("true") || tokens[tIndex].equals("true"))
          && tIndex + 1 == tokens.length) {
        code.setCodeText("while(" + tokens[tIndex] + ")");
      }
    }
  }
Ejemplo n.º 14
0
 public void sendResponseHeaders(int rCode, long contentLen) throws IOException {
   if (sentHeaders) {
     throw new IOException("headers already sent");
   }
   this.rcode = rCode;
   String statusLine = "HTTP/1.1 " + rCode + Code.msg(rCode) + "\r\n";
   OutputStream tmpout = new BufferedOutputStream(ros);
   PlaceholderOutputStream o = getPlaceholderResponseBody();
   tmpout.write(bytes(statusLine, 0), 0, statusLine.length());
   boolean noContentToSend = false; // assume there is content
   rspHdrs.set("Date", df.format(new Date()));
   if (contentLen == 0) {
     if (http10) {
       o.setWrappedStream(new UndefLengthOutputStream(this, ros));
       close = true;
     } else {
       rspHdrs.set("Transfer-encoding", "chunked");
       o.setWrappedStream(new ChunkedOutputStream(this, ros));
     }
   } else {
     if (contentLen == -1) {
       noContentToSend = true;
       contentLen = 0;
     }
     /* content len might already be set, eg to implement HEAD resp */
     if (rspHdrs.getFirst("Content-length") == null) {
       rspHdrs.set("Content-length", Long.toString(contentLen));
     }
     o.setWrappedStream(new FixedLengthOutputStream(this, ros, contentLen));
   }
   write(rspHdrs, tmpout);
   this.rspContentLen = contentLen;
   tmpout.flush();
   tmpout = null;
   sentHeaders = true;
   if (noContentToSend) {
     WriteFinishedEvent e = new WriteFinishedEvent(this);
     server.addEvent(e);
     closed = true;
   }
   server.logReply(rCode, req.requestLine(), null);
 }
Ejemplo n.º 15
0
  public NewArray(int opcode, long start_byte, Code code) {
    super(opcode, start_byte, code);

    if (opcode == 188) // newarray
    {
      switch (params[0]) {
        case T_BOOLEAN:
          baseType = "boolean";
          break;
        case T_CHAR:
          baseType = "char";
          break;
        case T_FLOAT:
          baseType = "float";
          break;
        case T_DOUBLE:
          baseType = "double";
          break;
        case T_BYTE:
          baseType = "byte";
          break;
        case T_SHORT:
          baseType = "short";
          break;
        case T_INT:
          baseType = "int";
          break;
        case T_LONG:
          baseType = "long";
          break;
      }
    } else if (opcode == 189) {
      classType =
          ((CONSTANT_Class_info) code.getClazz().getConstant_pool()[(params[0] << 8) | params[1]])
              .getFullyQualifiedName();
    }
  }
  /**
   * Reads an attribute for this method from the specified input stream.
   *
   * @param in The input stream to read from.
   * @return The attribute read, possibly <code>null</code> if it was known to be unimportant for
   *     our purposes.
   * @throws IOException If an IO error occurs.
   */
  private AttributeInfo readAttribute(DataInputStream in) throws IOException {

    AttributeInfo ai = null;

    int attributeNameIndex = in.readUnsignedShort();
    int attributeLength = in.readInt();

    String attrName = cf.getUtf8ValueFromConstantPool(attributeNameIndex);

    if (CODE.equals(attrName)) { // 4.7.3
      ai = Code.read(this, in);
    } else if (EXCEPTIONS.equals(attrName)) { // 4.7.4
      int exceptionCount = in.readUnsignedShort();
      int[] exceptionIndexTable = null;
      if (exceptionCount > 0) {
        exceptionIndexTable = new int[exceptionCount];
        for (int i = 0; i < exceptionCount; i++) {
          exceptionIndexTable[i] = in.readUnsignedShort();
        }
      }
      Exceptions e = new Exceptions(this, exceptionIndexTable);
      ai = e;
    }

    // TODO: Handle other Attribute types.

    // Attributes common to all members, or unhandled attributes.
    else {
      ai = super.readAttribute(in, attrName, attributeLength);
      //			if (ai!=null) { // "Deprecated" attribute returns null
      //				System.out.println("-------------- " + ai.getName());
      //			}
    }

    return ai;
  }
Ejemplo n.º 17
0
  private Code readNaryOp(
      int opcode,
      boolean wideBase,
      boolean wideRest,
      int offset,
      HashMap<Integer, Code.Label> labels)
      throws IOException {
    int nOperands = readBase(wideBase);
    int[] operands = new int[nOperands];
    for (int i = 0; i != nOperands; ++i) {
      operands[i] = readBase(wideBase);
    }

    if (opcode == Code.OPCODE_loop) {
      // special case which doesn't have a type.
      int target = readTarget(wideRest, offset);
      Code.LoopEnd l = findLoopLabel(target, labels);
      return Code.Loop(l.label, operands);
    }

    int typeIdx = readRest(wideRest);
    Type type = typePool[typeIdx];

    switch (opcode) {
      case Code.OPCODE_forall:
        {
          if (!(type instanceof Type.EffectiveCollection)) {
            throw new RuntimeException("expected collection type");
          }
          int target = readTarget(wideRest, offset);
          Code.LoopEnd l = findLoopLabel(target, labels);
          int indexOperand = operands[0];
          int sourceOperand = operands[1];
          operands = Arrays.copyOfRange(operands, 2, operands.length);
          return Code.ForAll(
              (Type.EffectiveCollection) type, sourceOperand, indexOperand, operands, l.label);
        }
      case Code.OPCODE_indirectinvokefnv:
      case Code.OPCODE_indirectinvokemdv:
        {
          if (!(type instanceof Type.FunctionOrMethod)) {
            throw new RuntimeException("expected function or method type");
          }
          int operand = operands[0];
          operands = Arrays.copyOfRange(operands, 1, operands.length);
          return Code.IndirectInvoke(
              (Type.FunctionOrMethod) type, Code.NULL_REG, operand, operands);
        }
      case Code.OPCODE_invokefnv:
      case Code.OPCODE_invokemdv:
        {
          if (!(type instanceof Type.FunctionOrMethod)) {
            throw new RuntimeException("expected function or method type");
          }
          int nameIdx = readRest(wideRest);
          ;
          NameID nid = namePool[nameIdx];
          return Code.Invoke((Type.FunctionOrMethod) type, Code.NULL_REG, operands, nid);
        }
    }
    throw new RuntimeException("unknown opcode encountered (" + opcode + ")");
  }
Ejemplo n.º 18
0
 private Code readBinaryAssign(int opcode, boolean wideBase, boolean wideRest) throws IOException {
   int target = readBase(wideBase);
   int leftOperand = readBase(wideBase);
   int rightOperand = readBase(wideBase);
   int typeIdx = readRest(wideRest);
   Type type = typePool[typeIdx];
   switch (opcode) {
     case Code.OPCODE_append:
     case Code.OPCODE_appendl:
     case Code.OPCODE_appendr:
       {
         if (!(type instanceof Type.EffectiveList)) {
           throw new RuntimeException("expecting list type");
         }
         Code.BinListKind kind = Code.BinListKind.values()[opcode - Code.OPCODE_append];
         return Code.BinListOp((Type.EffectiveList) type, target, leftOperand, rightOperand, kind);
       }
     case Code.OPCODE_sappend:
     case Code.OPCODE_sappendl:
     case Code.OPCODE_sappendr:
       {
         if (!(type instanceof Type.Strung)) {
           throw new RuntimeException("expecting string type");
         }
         Code.BinStringKind kind = Code.BinStringKind.values()[opcode - Code.OPCODE_sappend];
         return Code.BinStringOp(target, leftOperand, rightOperand, kind);
       }
     case Code.OPCODE_indexof:
       {
         if (!(type instanceof Type.EffectiveIndexible)) {
           throw new RuntimeException("expecting indexible type");
         }
         return Code.IndexOf((Type.EffectiveIndexible) type, target, leftOperand, rightOperand);
       }
     case Code.OPCODE_add:
     case Code.OPCODE_sub:
     case Code.OPCODE_mul:
     case Code.OPCODE_div:
     case Code.OPCODE_rem:
     case Code.OPCODE_range:
     case Code.OPCODE_bitwiseor:
     case Code.OPCODE_bitwisexor:
     case Code.OPCODE_bitwiseand:
     case Code.OPCODE_lshr:
     case Code.OPCODE_rshr:
       {
         Code.BinArithKind kind = Code.BinArithKind.values()[opcode - Code.OPCODE_add];
         return Code.BinArithOp(type, target, leftOperand, rightOperand, kind);
       }
     case Code.OPCODE_union:
     case Code.OPCODE_unionl:
     case Code.OPCODE_unionr:
     case Code.OPCODE_intersect:
     case Code.OPCODE_intersectl:
     case Code.OPCODE_intersectr:
     case Code.OPCODE_difference:
     case Code.OPCODE_differencel:
       {
         if (!(type instanceof Type.EffectiveSet)) {
           throw new RuntimeException("expecting set type");
         }
         Code.BinSetKind kind = Code.BinSetKind.values()[opcode - Code.OPCODE_union];
         return Code.BinSetOp((Type.EffectiveSet) type, target, leftOperand, rightOperand, kind);
       }
   }
   throw new RuntimeException("unknown opcode encountered (" + opcode + ")");
 }
Ejemplo n.º 19
0
  private Code readUnaryAssign(int opcode, boolean wideBase, boolean wideRest) throws IOException {
    int target = readBase(wideBase);

    int operand = readBase(wideBase);
    int typeIdx = readRest(wideRest);
    Type type = typePool[typeIdx];
    switch (opcode) {
      case Code.OPCODE_convert:
        {
          int i = readRest(wideRest);
          Type t = typePool[i];
          return Code.Convert(type, target, operand, t);
        }
      case Code.OPCODE_assign:
        return Code.Assign(type, target, operand);
      case Code.OPCODE_dereference:
        {
          if (!(type instanceof Type.Reference)) {
            throw new RuntimeException("expected reference type");
          }
          return Code.Dereference((Type.Reference) type, target, operand);
        }
      case Code.OPCODE_fieldload:
        {
          if (!(type instanceof Type.EffectiveRecord)) {
            throw new RuntimeException("expected record type");
          }
          int i = readRest(wideRest);
          String field = stringPool[i];
          return Code.FieldLoad((Type.EffectiveRecord) type, target, operand, field);
        }
      case Code.OPCODE_invert:
        return Code.Invert(type, target, operand);
      case Code.OPCODE_newobject:
        {
          if (!(type instanceof Type.Reference)) {
            throw new RuntimeException("expected reference type");
          }
          return Code.NewObject((Type.Reference) type, target, operand);
        }
      case Code.OPCODE_lengthof:
        {
          if (!(type instanceof Type.EffectiveCollection)) {
            throw new RuntimeException("expected collection type");
          }
          return Code.LengthOf((Type.EffectiveCollection) type, target, operand);
        }
      case Code.OPCODE_move:
        return Code.Move(type, target, operand);
      case Code.OPCODE_neg:
        return Code.UnArithOp(type, target, operand, Code.UnArithKind.NEG);
      case Code.OPCODE_numerator:
        return Code.UnArithOp(type, target, operand, Code.UnArithKind.NUMERATOR);
      case Code.OPCODE_denominator:
        return Code.UnArithOp(type, target, operand, Code.UnArithKind.DENOMINATOR);
      case Code.OPCODE_not:
        {
          if (!(type instanceof Type.Bool)) {
            throw new RuntimeException("expected bool type");
          }
          return Code.Not(target, operand);
        }
      case Code.OPCODE_tupleload:
        {
          if (!(type instanceof Type.EffectiveTuple)) {
            throw new RuntimeException("expected tuple type");
          }
          int index = readRest(wideRest);
          return Code.TupleLoad((Type.Tuple) type, target, operand, index);
        }
    }
    throw new RuntimeException("unknown opcode encountered (" + opcode + ")");
  }
  private void for_loop() {
    VarSymbol v = null, tempVar = null;
    FuncSymbol f = null, tempFunc = null;
    int index =
        input.indexOf(
            words.get(wordLoc)); // Index in input string at which the word was encountered
    String expString = "";
    index += (words.get(wordLoc).length() + 1);
    String str = input.substring(index); // Further processing will be done on this string
    tokens = str.split("[ ]+");
    index = 0;
    boolean flag = false;
    String expression = null;
    String tempStr = null;
    String loopCounter = "";

    while (true) {
      if ((v = Controller.varSym.searchSymbol(tokens[tIndex]))
          != null) /*|| (f = Controller.funSym.searchSymbol(tokens[tIndex])) != null*/ {
        loopCounter = v.getVarName(); // Holds the loopCounter variable
        expString = searchExpression();
        expression = exp.generateExpression(expString);
        tempVar = v;
      } else if (tokens[tIndex].equalsIgnoreCase("to")) { // If next token is not an operator
        loopParams[0] = expression;
        tIndex++;
        int tempNum = NumberGenerator.stringToNum(tokens[tIndex]);
        // if((tempStr = String.valueOf(toNumber(tokens[tIndex++])))){			// TODO Method 'toNumber()'
        // to be added later
        if (String.valueOf(tempNum) != null) {
          condition = tempStr;
          loopParams[1] = loopCounter + "<" + condition;
        } else if ((v = Controller.varSym.searchSymbol(tokens[tIndex])) != null
            || (Controller.funSym.searchSymbol(tokens[tIndex]) != null)) {
          tempStr = searchExpression();
          String tempString = exp.generateExpression(tempStr);
          int len = v.getVarName().length();
          if (tempString.startsWith(loopCounter) && tempString.charAt(len) == '=') {
            condition = tempString.substring(len + 1);
            loopParams[1] = loopCounter + "<" + condition;
          } else {
            condition = tempString;
            loopParams[1] = condition;
          }
        }
      } else if (tokens[tIndex].equalsIgnoreCase("increment")
          || (tokens[tIndex] + tokens[tIndex + 1]).equalsIgnoreCase("plusplus")
          || tokens[tIndex].equalsIgnoreCase("postincrement")
          || tokens[tIndex].equalsIgnoreCase("preincrement")) {
        expression = exp.generateExpression((str.substring(str.indexOf(tokens[tIndex]))));
        loopParams[2] = expression;
        break;
      } else if (tokens[tIndex].equalsIgnoreCase("decrement")
          || (tokens[tIndex] + tokens[tIndex + 1]).equalsIgnoreCase("minus minus")
          || tokens[tIndex].equalsIgnoreCase("postdecrement")
          || tokens[tIndex].equalsIgnoreCase("predecrement")) {
        expression = exp.generateExpression((str.substring(str.indexOf(tokens[tIndex]))));
        loopParams[2] = expression;
        break;
      }
      /*if(searchOperator(tIndex) != -1){
      	//TODO Index variable missing error to be handled
      }*/
      /*
      if(token is number){
      	number handling logic.
      	e.g : for loop 0 to 100.
      }
      */
      if ((tIndex) == tokens.length) {
        break;
      }
    }
    if (loopParams[2] == null) {
      loopParams[2] = loopCounter + "++";
    }
    code.setCodeText("for(" + loopParams[0] + ";" + loopParams[1] + ";" + loopParams[2] + ")");
    code.setErrCode(IErrorCodes.SUCCESS);
    code.setErrParam(null);
  }
Ejemplo n.º 21
0
 private Code readNaryAssign(int opcode, boolean wideBase, boolean wideRest) throws IOException {
   int target = readBase(wideBase);
   int nOperands = readBase(wideBase);
   int[] operands = new int[nOperands];
   for (int i = 0; i != nOperands; ++i) {
     operands[i] = readBase(wideBase);
   }
   int typeIdx = readRest(wideRest);
   Type type = typePool[typeIdx];
   switch (opcode) {
     case Code.OPCODE_indirectinvokefn:
     case Code.OPCODE_indirectinvokemd:
       {
         if (!(type instanceof Type.FunctionOrMethod)) {
           throw new RuntimeException("expected function or method type");
         }
         int operand = operands[0];
         operands = Arrays.copyOfRange(operands, 1, operands.length);
         return Code.IndirectInvoke((Type.FunctionOrMethod) type, target, operand, operands);
       }
     case Code.OPCODE_invokefn:
     case Code.OPCODE_invokemd:
       {
         if (!(type instanceof Type.FunctionOrMethod)) {
           throw new RuntimeException("expected function or method type");
         }
         int nameIdx = readRest(wideRest);
         NameID nid = namePool[nameIdx];
         return Code.Invoke((Type.FunctionOrMethod) type, target, operands, nid);
       }
     case Code.OPCODE_lambdafn:
     case Code.OPCODE_lambdamd:
       {
         if (!(type instanceof Type.FunctionOrMethod)) {
           throw new RuntimeException("expected function or method type");
         }
         // Lambda's are the only instances of NULLABLENARYASSIGN's
         for (int i = 0; i != operands.length; ++i) {
           operands[i] -= 1;
         }
         int nameIdx = readRest(wideRest);
         NameID nid = namePool[nameIdx];
         return Code.Lambda((Type.FunctionOrMethod) type, target, operands, nid);
       }
     case Code.OPCODE_newmap:
       {
         if (!(type instanceof Type.Map)) {
           throw new RuntimeException("expected map type");
         }
         return Code.NewMap((Type.Map) type, target, operands);
       }
     case Code.OPCODE_newrecord:
       {
         if (!(type instanceof Type.Record)) {
           throw new RuntimeException("expected record type");
         }
         return Code.NewRecord((Type.Record) type, target, operands);
       }
     case Code.OPCODE_newlist:
       {
         if (!(type instanceof Type.List)) {
           throw new RuntimeException("expected list type");
         }
         return Code.NewList((Type.List) type, target, operands);
       }
     case Code.OPCODE_newset:
       {
         if (!(type instanceof Type.Set)) {
           throw new RuntimeException("expected set type");
         }
         return Code.NewSet((Type.Set) type, target, operands);
       }
     case Code.OPCODE_newtuple:
       {
         if (!(type instanceof Type.Tuple)) {
           throw new RuntimeException("expected tuple type");
         }
         return Code.NewTuple((Type.Tuple) type, target, operands);
       }
     case Code.OPCODE_sublist:
       {
         if (!(type instanceof Type.EffectiveList)) {
           throw new RuntimeException("expected list type");
         }
         return Code.SubList(
             (Type.EffectiveList) type, target, operands[0], operands[1], operands[2]);
       }
     case Code.OPCODE_substring:
       {
         if (!(type instanceof Type.Strung)) {
           throw new RuntimeException("expected string type");
         }
         return Code.SubString(target, operands[0], operands[1], operands[2]);
       }
   }
   throw new RuntimeException("unknown opcode encountered (" + opcode + ")");
 }
Ejemplo n.º 22
0
  final void writeAttribute(Attribute attribute, String anchor, int method_number)
      throws IOException {
    byte tag = attribute.getTag();
    int index;

    if (tag == ATTR_UNKNOWN) // Don't know what to do about this one
    return;

    attr_count++; // Increment number of attributes found so far

    if (attr_count % 2 == 0) file.print("<TR BGCOLOR=\"#C0C0C0\"><TD>");
    else file.print("<TR BGCOLOR=\"#A0A0A0\"><TD>");

    file.println(
        "<H4><A NAME=\"" + anchor + "\">" + attr_count + " " + ATTRIBUTE_NAMES[tag] + "</A></H4>");

    /* Handle different attributes
     */
    switch (tag) {
      case ATTR_CODE:
        Code c = (Code) attribute;

        // Some directly printable values
        file.print(
            "<UL><LI>Maximum stack size = "
                + c.getMaxStack()
                + "</LI>\n<LI>Number of local variables = "
                + c.getMaxLocals()
                + "</LI>\n<LI><A HREF=\""
                + class_name
                + "_code.html#method"
                + method_number
                + "\" TARGET=Code>Byte code</A></LI></UL>\n");

        // Get handled exceptions and list them
        CodeException[] ce = c.getExceptionTable();
        int len = ce.length;

        if (len > 0) {
          file.print("<P><B>Exceptions handled</B><UL>");

          for (int i = 0; i < len; i++) {
            int catch_type = ce[i].getCatchType(); // Index in constant pool

            file.print("<LI>");

            if (catch_type != 0)
              file.print(constant_html.referenceConstant(catch_type)); // Create Link to _cp.html
            else file.print("Any Exception");

            file.print(
                "<BR>(Ranging from lines "
                    + codeLink(ce[i].getStartPC(), method_number)
                    + " to "
                    + codeLink(ce[i].getEndPC(), method_number)
                    + ", handled at line "
                    + codeLink(ce[i].getHandlerPC(), method_number)
                    + ")</LI>");
          }
          file.print("</UL>");
        }
        break;

      case ATTR_CONSTANT_VALUE:
        index = ((ConstantValue) attribute).getConstantValueIndex();

        // Reference _cp.html
        file.print(
            "<UL><LI><A HREF=\""
                + class_name
                + "_cp.html#cp"
                + index
                + "\" TARGET=\"ConstantPool\">Constant value index("
                + index
                + ")</A></UL>\n");
        break;

      case ATTR_SOURCE_FILE:
        index = ((SourceFile) attribute).getSourceFileIndex();

        // Reference _cp.html
        file.print(
            "<UL><LI><A HREF=\""
                + class_name
                + "_cp.html#cp"
                + index
                + "\" TARGET=\"ConstantPool\">Source file index("
                + index
                + ")</A></UL>\n");
        break;

      case ATTR_EXCEPTIONS:
        // List thrown exceptions
        int[] indices = ((ExceptionTable) attribute).getExceptionIndexTable();

        file.print("<UL>");

        for (int i = 0; i < indices.length; i++)
          file.print(
              "<LI><A HREF=\""
                  + class_name
                  + "_cp.html#cp"
                  + indices[i]
                  + "\" TARGET=\"ConstantPool\">Exception class index("
                  + indices[i]
                  + ")</A>\n");

        file.print("</UL>\n");
        break;

      case ATTR_LINE_NUMBER_TABLE:
        LineNumber[] line_numbers = ((LineNumberTable) attribute).getLineNumberTable();

        // List line number pairs
        file.print("<P>");

        for (int i = 0; i < line_numbers.length; i++) {
          file.print(
              "("
                  + line_numbers[i].getStartPC()
                  + ",&nbsp;"
                  + line_numbers[i].getLineNumber()
                  + ")");

          if (i < line_numbers.length - 1) file.print(", "); // breakable
        }
        break;

      case ATTR_LOCAL_VARIABLE_TABLE:
        LocalVariable[] vars = ((LocalVariableTable) attribute).getLocalVariableTable();

        // List name, range and type
        file.print("<UL>");

        for (int i = 0; i < vars.length; i++) {
          index = vars[i].getSignatureIndex();
          String signature =
              ((ConstantUtf8) constant_pool.getConstant(index, CONSTANT_Utf8)).getBytes();
          signature = Utility.signatureToString(signature, false);
          int start = vars[i].getStartPC();
          int end = (start + vars[i].getLength());

          file.println(
              "<LI>"
                  + Class2HTML.referenceType(signature)
                  + "&nbsp;<B>"
                  + vars[i].getName()
                  + "</B> in slot %"
                  + vars[i].getIndex()
                  + "<BR>Valid from lines "
                  + "<A HREF=\""
                  + class_name
                  + "_code.html#code"
                  + method_number
                  + "@"
                  + start
                  + "\" TARGET=Code>"
                  + start
                  + "</A> to "
                  + "<A HREF=\""
                  + class_name
                  + "_code.html#code"
                  + method_number
                  + "@"
                  + end
                  + "\" TARGET=Code>"
                  + end
                  + "</A></LI>");
        }
        file.print("</UL>\n");

        break;

      case ATTR_INNER_CLASSES:
        InnerClass[] classes = ((InnerClasses) attribute).getInnerClasses();

        // List inner classes
        file.print("<UL>");

        for (int i = 0; i < classes.length; i++) {
          String name, access;

          index = classes[i].getInnerNameIndex();
          if (index > 0)
            name = ((ConstantUtf8) constant_pool.getConstant(index, CONSTANT_Utf8)).getBytes();
          else name = "&lt;anonymous&gt;";

          access = Utility.accessToString(classes[i].getInnerAccessFlags());

          file.print(
              "<LI><FONT COLOR=\"#FF0000\">"
                  + access
                  + "</FONT> "
                  + constant_html.referenceConstant(classes[i].getInnerClassIndex())
                  + " in&nbsp;class "
                  + constant_html.referenceConstant(classes[i].getOuterClassIndex())
                  + " named "
                  + name
                  + "</LI>\n");
        }

        file.print("</UL>\n");
        break;

      default: // Such as Unknown attribute or Deprecated
        file.print("<P>" + attribute.toString());
    }

    file.println("</TD></TR>");
    file.flush();
  }
 public String genotypeToString() {
   StringBuilder s = new StringBuilder();
   s.append(Code.encode(genome.length));
   for (int i = 0; i < genome.length; i++) s.append(Code.encode(genome[i]));
   return s.toString();
 }