Exemple #1
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);
   }
 }
Exemple #2
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 + ")");
 }
Exemple #3
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);
   }
 }
 public DocumentReference copy() {
   DocumentReference dst = new DocumentReference();
   dst.masterIdentifier = masterIdentifier == null ? null : masterIdentifier.copy();
   dst.identifier = new ArrayList<Identifier>();
   for (Identifier i : identifier) dst.identifier.add(i.copy());
   dst.subject = subject == null ? null : subject.copy();
   dst.type = type == null ? null : type.copy();
   dst.subtype = subtype == null ? null : subtype.copy();
   dst.author = new ArrayList<ResourceReference>();
   for (ResourceReference i : author) dst.author.add(i.copy());
   dst.custodian = custodian == null ? null : custodian.copy();
   dst.authenticator = authenticator == null ? null : authenticator.copy();
   dst.created = created == null ? null : created.copy();
   dst.indexed = indexed == null ? null : indexed.copy();
   dst.status = status == null ? null : status.copy();
   dst.docStatus = docStatus == null ? null : docStatus.copy();
   dst.supercedes = supercedes == null ? null : supercedes.copy();
   dst.description = description == null ? null : description.copy();
   dst.confidentiality = confidentiality == null ? null : confidentiality.copy();
   dst.primaryLanguage = primaryLanguage == null ? null : primaryLanguage.copy();
   dst.mimeType = mimeType == null ? null : mimeType.copy();
   dst.format = format == null ? null : format.copy();
   dst.size = size == null ? null : size.copy();
   dst.hash = hash == null ? null : hash.copy();
   dst.location = location == null ? null : location.copy();
   dst.service = service == null ? null : service.copy(dst);
   dst.context = context == null ? null : context.copy(dst);
   return dst;
 }
Exemple #5
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 + ")");
 }
 private static Code emit(Code lc, Expression le, Code rc, Expression re) {
   if (lc.isNull()) {
     return emit(rc, re, "is", lc, le);
   } else if (rc.isNull()) {
     return emit(lc, le, "is", rc, re);
   } else {
     return emit(lc, le, "=", rc, re);
   }
 }
Exemple #7
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;
   }
 }
Exemple #8
0
 public SpecimenSourceComponent copy(Specimen e) {
   SpecimenSourceComponent dst = e.new SpecimenSourceComponent();
   dst.relationship = relationship == null ? null : relationship.copy();
   dst.target = new ArrayList<ResourceReference>();
   for (ResourceReference i : target) dst.target.add(i.copy());
   return dst;
 }
  /**
   * 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);
    }
  }
Exemple #10
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;
 }
 /**
  * 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;
 }
  /**
   * Create code from this definition
   *
   * @param defCode code definition
   * @return code object
   */
  private ProcCode createCode(Code defCode) {
    if (!defCode.hasPatterns()) {
      throw new IllegalStateException("Field pattern can't be null.");
    }

    if (defCode.getTemplate() == null) {
      throw new IllegalStateException("Field template can't be null.");
    }

    ProcCode code = codes.get(defCode);
    if (code == null) {
      List<Pattern> confPatterns = defCode.getPatterns();
      List<ProcPattern> procPatterns = new ArrayList<ProcPattern>(confPatterns.size());

      for (Pattern confPattern : confPatterns) {
        procPatterns.add(createPattern(confPattern));
      }

      code =
          new ProcCode(
              procPatterns,
              createTemplate(defCode.getTemplate()),
              defCode.getName(),
              defCode.getPriority(),
              defCode.isTransparent());
      codes.put(defCode, code);
    }
    return code;
  }
Exemple #13
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 + ")");
 }
 public Coding copy() {
   Coding dst = new Coding();
   dst.system = system == null ? null : system.copy();
   dst.version = version == null ? null : version.copy();
   dst.code = code == null ? null : code.copy();
   dst.display = display == null ? null : display.copy();
   dst.primary = primary == null ? null : primary.copy();
   dst.valueSet = valueSet == null ? null : valueSet.copy();
   return dst;
 }
Exemple #15
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 + ")");
 }
 public Supply copy() {
   Supply dst = new Supply();
   dst.name = name == null ? null : name.copy();
   dst.identifier = identifier == null ? null : identifier.copy();
   dst.status = status == null ? null : status.copy();
   dst.orderedItem = orderedItem == null ? null : orderedItem.copy();
   dst.patient = patient == null ? null : patient.copy();
   dst.dispense = new ArrayList<SupplyDispenseComponent>();
   for (SupplyDispenseComponent i : dispense) dst.dispense.add(i.copy(dst));
   return dst;
 }
  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);
    }
  }
 public SupplyDispenseComponent copy(Supply e) {
   SupplyDispenseComponent dst = e.new SupplyDispenseComponent();
   dst.identifier = identifier == null ? null : identifier.copy();
   dst.status = status == null ? null : status.copy();
   dst.type = type == null ? null : type.copy();
   dst.quantity = quantity == null ? null : quantity.copy();
   dst.suppliedItem = suppliedItem == null ? null : suppliedItem.copy();
   dst.supplier = supplier == null ? null : supplier.copy();
   dst.whenPrepared = whenPrepared == null ? null : whenPrepared.copy();
   dst.whenHandedOver = whenHandedOver == null ? null : whenHandedOver.copy();
   dst.destination = destination == null ? null : destination.copy();
   dst.receiver = new ArrayList<ResourceReference>();
   for (ResourceReference i : receiver) dst.receiver.add(i.copy());
   return dst;
 }
Exemple #19
0
 public String toString() {
   String r = code.toString();
   if (attributes().size() > 0) {
     r += " # ";
     boolean firstTime = true;
     for (Attribute a : attributes()) {
       if (!firstTime) {
         r += ", ";
       }
       firstTime = false;
       r += a;
     }
   }
   return r;
 }
Exemple #20
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] + ")");
      }
    }
  }
 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);
 }
Exemple #23
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;
  }
Exemple #25
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 + ")");
 }
Exemple #26
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 + ")");
  }
Exemple #27
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 + ")");
 }
Exemple #28
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 static void printMethodWithMultiType(
      ProcessingEnvironment env,
      TypeMap type_map,
      PrintWriter writer,
      TypeElement interface_decl,
      ExecutableElement method,
      Map<VariableElement, TypeInfo> typeinfos_instance,
      Mode mode,
      boolean generate_error_checks,
      boolean context_specific) {
    Utils.printDocComment(writer, method, env);
    if (method.getAnnotation(Deprecated.class) != null) {
      writer.println("\t@Deprecated");
    }
    if (interface_decl.getAnnotation(Private.class) == null
        && method.getAnnotation(Private.class) == null) {
      writer.print("\tpublic static ");
    } else {
      writer.print("\tstatic ");
    }
    writer.print(getResultType(method, false));
    StripPostfix strip_annotation = method.getAnnotation(StripPostfix.class);
    String method_name;
    Alternate alt_annotation = method.getAnnotation(Alternate.class);
    method_name =
        alt_annotation == null || alt_annotation.javaAlt()
            ? method.getSimpleName().toString()
            : alt_annotation.value();
    if (strip_annotation != null && mode == Mode.NORMAL) {
      method_name = getPostfixStrippedName(type_map, interface_decl, method);
    }
    writer.print(" " + method_name + "(");
    generateParametersJava(writer, method, typeinfos_instance, false, true, mode);
    writer.println(") {");

    final TypeMirror result_type = Utils.getMethodReturnType(method);
    boolean has_result = !result_type.equals(env.getTypeUtils().getNoType(TypeKind.VOID));

    final Reuse reuse_annotation = method.getAnnotation(Reuse.class);
    if (reuse_annotation != null) {
      writer.print("\t\t");
      if (has_result || method.getAnnotation(GLreturn.class) != null) {
        writer.print("return ");
      }

      writer.print(
          reuse_annotation.value()
              + "."
              + (reuse_annotation.method().length() > 0 ? reuse_annotation.method() : method_name)
              + "(");
      generateParametersJava(writer, method, typeinfos_instance, false, false, mode);
      writer.println(");\n\t}");
      return;
    }

    if (context_specific) {
      type_map.printCapabilitiesInit(writer);
      writer.print(
          "\t\tlong " + Utils.FUNCTION_POINTER_VAR_NAME + " = " + type_map.getCapabilities() + ".");
      writer.println(Utils.getFunctionAddressName(interface_decl, method, true) + ";");
      writer.print("\t\tBufferChecks.checkFunctionAddress(");
      writer.println(Utils.FUNCTION_POINTER_VAR_NAME + ");");
    }
    final Code code_annotation = method.getAnnotation(Code.class);
    if (code_annotation != null && code_annotation.value().length() > 0) {
      writer.println(code_annotation.value());
    }
    printBufferObjectChecks(writer, method, mode, context_specific);
    printParameterChecks(writer, method, typeinfos_instance, mode, generate_error_checks);
    printParameterCaching(writer, interface_decl, method, mode, context_specific);

    if (code_annotation != null && code_annotation.javaBeforeNative().length() > 0) {
      writer.println(code_annotation.javaBeforeNative());
    }
    writer.print("\t\t");

    final PointerWrapper pointer_wrapper_annotation = method.getAnnotation(PointerWrapper.class);
    if (has_result) {
      writer.print(getResultType(method, false) + " " + Utils.RESULT_VAR_NAME);

      if (code_annotation != null && code_annotation.tryBlock()) {
        writer.print(" = " + getDefaultResultValue(method));
        writer.println(";\n\t\ttry {");
        writer.print("\t\t\t" + Utils.RESULT_VAR_NAME);
      }

      writer.print(" = ");
      if (pointer_wrapper_annotation != null) {
        if (pointer_wrapper_annotation.factory().length() > 0) {
          writer.print(pointer_wrapper_annotation.factory() + "(");
        } else {
          writer.print("new " + getResultType(method, false) + "(");
        }
      }
    } else if (method.getAnnotation(GLreturn.class) != null) {
      has_result = true;
      Utils.printGLReturnPre(writer, method, method.getAnnotation(GLreturn.class), type_map);
    }
    writer.print(Utils.getSimpleNativeMethodName(method, generate_error_checks, context_specific));
    if (mode == Mode.BUFFEROBJECT) {
      writer.print(Utils.BUFFER_OBJECT_METHOD_POSTFIX);
    }
    writer.print("(");
    boolean first_parameter =
        printMethodCallArguments(writer, method, typeinfos_instance, mode, type_map);
    if (context_specific) {
      if (!first_parameter) {
        writer.print(", ");
      }
      writer.print(Utils.FUNCTION_POINTER_VAR_NAME);
    }
    if (has_result && pointer_wrapper_annotation != null) {
      writer.print(")");
      if (pointer_wrapper_annotation.params().length() > 0) {
        writer.print(", " + pointer_wrapper_annotation.params());
      }
    }
    writer.println(");");

    if (code_annotation != null && code_annotation.javaAfterNative().length() > 0) {
      writer.println(code_annotation.javaAfterNative());
    }

    final String tabs = code_annotation != null && code_annotation.tryBlock() ? "\t\t\t" : "\t\t";
    if (generate_error_checks && method.getAnnotation(NoErrorCheck.class) == null) {
      type_map.printErrorCheckMethod(writer, method, tabs);
    }
    // DISABLED: indirect buffer support
    // printNondirectParameterCopies(writer, method, mode);
    if (has_result) {
      if (method.getAnnotation(GLreturn.class) == null) {
        if (ByteBuffer.class.equals(Utils.getJavaType(result_type))) {
          writer.println(
              tabs
                  + "return LWJGLUtil.CHECKS && "
                  + Utils.RESULT_VAR_NAME
                  + " == null ? null : "
                  + Utils.RESULT_VAR_NAME
                  + ".order(ByteOrder.nativeOrder());"); // safeNewBuffer returns a direct
                                                         // ByteBuffer with BIG_ENDIAN order.
        } else {
          writer.println(tabs + "return " + Utils.RESULT_VAR_NAME + ";");
        }
      } else {
        Utils.printGLReturnPost(writer, method, method.getAnnotation(GLreturn.class), type_map);
      }
    }

    if (code_annotation != null && code_annotation.tryBlock()) {
      writer.println("\t\t} finally {");
      writer.println(code_annotation.javaFinally());
      writer.println("\t\t}");
    }
    writer.println("\t}");
  }
  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);
  }