Examples of CodeStream


Examples of org.eclipse.jdt.internal.compiler.codegen.CodeStream

    } else if (this.targetJDK == ClassFileConstants.CLDC_1_1) {
      this.targetJDK = ClassFileConstants.JDK1_1; // put back 45.3
      this.produceAttributes |= ClassFileConstants.ATTR_STACK_MAP;
      this.codeStream = new StackMapFrameCodeStream(this);
    } else {
      this.codeStream = new CodeStream(this);
    }
    initByteArrays();
  }
View Full Code Here

Examples of org.eclipse.jdt.internal.compiler.codegen.CodeStream

    int constantPoolOffset = constantPool.currentOffset;
    int constantPoolIndex = constantPool.currentIndex;
    classFile.generateMethodInfoHeaderForClinit();
    int codeAttributeOffset = classFile.contentsOffset;
    classFile.generateCodeAttributeHeader();
    CodeStream codeStream = classFile.codeStream;
    resolve(classScope);

    codeStream.reset(this, classFile);
    TypeDeclaration declaringType = classScope.referenceContext;

    // initialize local positions - including initializer scope.
    MethodScope staticInitializerScope = declaringType.staticInitializerScope;
    staticInitializerScope.computeLocalVariablePositions(0, codeStream);

    // 1.4 feature
    // This has to be done before any other initialization
    if (this.assertionSyntheticFieldBinding != null) {
      // generate code related to the activation of assertion for this class
      codeStream.generateClassLiteralAccessForType(
          classScope.outerMostClassScope().enclosingSourceType(),
          this.classLiteralSyntheticField);
      codeStream.invokeJavaLangClassDesiredAssertionStatus();
      BranchLabel falseLabel = new BranchLabel(codeStream);
      codeStream.ifne(falseLabel);
      codeStream.iconst_1();
      BranchLabel jumpLabel = new BranchLabel(codeStream);
      codeStream.decrStackSize(1);
      codeStream.goto_(jumpLabel);
      falseLabel.place();
      codeStream.iconst_0();
      jumpLabel.place();
      codeStream.fieldAccess(Opcodes.OPC_putstatic, this.assertionSyntheticFieldBinding, null /* default declaringClass */);
    }
    // generate static fields/initializers/enum constants
    final FieldDeclaration[] fieldDeclarations = declaringType.fields;
    int sourcePosition = -1;
    int remainingFieldCount = 0;
    if (TypeDeclaration.kind(declaringType.modifiers) == TypeDeclaration.ENUM_DECL) {
      int enumCount = declaringType.enumConstantsCounter;
      if (enumCount > ENUM_CONSTANTS_THRESHOLD) {
        // generate synthetic methods to initialize all the enum constants
        int begin = -1;
        int count = 0;
        if (fieldDeclarations != null) {
          int max = fieldDeclarations.length;
          for (int i = 0; i < max; i++) {
            FieldDeclaration fieldDecl = fieldDeclarations[i];
            if (fieldDecl.isStatic()) {
              if (fieldDecl.getKind() == AbstractVariableDeclaration.ENUM_CONSTANT) {
                if (begin == -1) {
                  begin = i;
                }
                count++;
                if (count > ENUM_CONSTANTS_THRESHOLD) {
                  SyntheticMethodBinding syntheticMethod = declaringType.binding.addSyntheticMethodForEnumInitialization(begin, i);
                  codeStream.invoke(Opcodes.OPC_invokestatic, syntheticMethod, null /* default declaringClass */);
                  begin = i;
                  count = 1;
                }
              } else {
                remainingFieldCount++;
              }
            }
          }
          if (count != 0) {
            // add last synthetic method
            SyntheticMethodBinding syntheticMethod = declaringType.binding.addSyntheticMethodForEnumInitialization(begin, max);
            codeStream.invoke(Opcodes.OPC_invokestatic, syntheticMethod, null /* default declaringClass */);
          }
        }
      } else if (fieldDeclarations != null) {
        for (int i = 0, max = fieldDeclarations.length; i < max; i++) {
          FieldDeclaration fieldDecl = fieldDeclarations[i];
          if (fieldDecl.isStatic()) {
            if (fieldDecl.getKind() == AbstractVariableDeclaration.ENUM_CONSTANT) {
              fieldDecl.generateCode(staticInitializerScope, codeStream);
            } else {
              remainingFieldCount++;
            }
          }
        }
      }
      // enum need to initialize $VALUES synthetic cache of enum constants
      // $VALUES := new <EnumType>[<enumCount>]
      codeStream.generateInlinedValue(enumCount);
      codeStream.anewarray(declaringType.binding);
      if (enumCount > 0) {
        if (fieldDeclarations != null) {
          for (int i = 0, max = fieldDeclarations.length; i < max; i++) {
            FieldDeclaration fieldDecl = fieldDeclarations[i];
            // $VALUES[i] = <enum-constant-i>
            if (fieldDecl.getKind() == AbstractVariableDeclaration.ENUM_CONSTANT) {
              codeStream.dup();
              codeStream.generateInlinedValue(fieldDecl.binding.id);
              codeStream.fieldAccess(Opcodes.OPC_getstatic, fieldDecl.binding, null /* default declaringClass */);
              codeStream.aastore();
            }
          }
        }
      }
      codeStream.fieldAccess(Opcodes.OPC_putstatic, declaringType.enumValuesSyntheticfield, null /* default declaringClass */);
      if (remainingFieldCount != 0) {
        // if fields that are not enum constants need to be generated (static initializer/static field)
        for (int i = 0, max = fieldDeclarations.length; i < max && remainingFieldCount >= 0; i++) {
          FieldDeclaration fieldDecl = fieldDeclarations[i];
          switch (fieldDecl.getKind()) {
            case AbstractVariableDeclaration.ENUM_CONSTANT :
              break;
            case AbstractVariableDeclaration.INITIALIZER :
              if (!fieldDecl.isStatic()) {
                break;
              }
              remainingFieldCount--;
              sourcePosition = ((Initializer) fieldDecl).block.sourceEnd;
              fieldDecl.generateCode(staticInitializerScope, codeStream);
              break;
            case AbstractVariableDeclaration.FIELD :
              if (!fieldDecl.binding.isStatic()) {
                break;
              }
              remainingFieldCount--;
              sourcePosition = fieldDecl.declarationEnd;
              fieldDecl.generateCode(staticInitializerScope, codeStream);
              break;
          }
        }
      }
    } else {
      if (fieldDeclarations != null) {
        for (int i = 0, max = fieldDeclarations.length; i < max; i++) {
          FieldDeclaration fieldDecl = fieldDeclarations[i];
          switch (fieldDecl.getKind()) {
            case AbstractVariableDeclaration.INITIALIZER :
              if (!fieldDecl.isStatic())
                break;
              sourcePosition = ((Initializer) fieldDecl).block.sourceEnd;
              fieldDecl.generateCode(staticInitializerScope, codeStream);
              break;
            case AbstractVariableDeclaration.FIELD :
              if (!fieldDecl.binding.isStatic())
                break;
              sourcePosition = fieldDecl.declarationEnd;
              fieldDecl.generateCode(staticInitializerScope, codeStream);
              break;
          }
        }
      }
    }

    if (codeStream.position == 0) {
      // do not need to output a Clinit if no bytecodes
      // so we reset the offset inside the byte array contents.
      classFile.contentsOffset = clinitOffset;
      // like we don't addd a method we need to undo the increment on the method count
      classFile.methodCount--;
      // reset the constant pool to its state before the clinit
      constantPool.resetForClinit(constantPoolIndex, constantPoolOffset);
    } else {
      if ((this.bits & ASTNode.NeedFreeReturn) != 0) {
        int before = codeStream.position;
        codeStream.return_();
        if (sourcePosition != -1) {
          // expand the last initializer variables to include the trailing return
          codeStream.recordPositionsFrom(before, sourcePosition);
        }
      }
      // Record the end of the clinit: point to the declaration of the class
      codeStream.recordPositionsFrom(0, declaringType.sourceStart);
      classFile.completeCodeAttributeForClinit(codeAttributeOffset);
    }
  }
View Full Code Here

Examples of org.eclipse.jdt.internal.compiler.codegen.CodeStream

    classFile.generateMethodInfoHeader(this.binding);
    int methodAttributeOffset = classFile.contentsOffset;
    int attributeNumber = classFile.generateMethodInfoAttributes(this.binding);
    int codeAttributeOffset = classFile.contentsOffset;
    classFile.generateCodeAttributeHeader();
    CodeStream codeStream = classFile.codeStream;
    codeStream.reset(this, classFile);
    // initialize local positions
    this.scope.computeLocalVariablePositions(this.outerLocalVariablesSlotSize + (this.binding.isStatic() ? 0 : 1), codeStream);
    if (this.outerLocalVariables != null) {
      for (int i = 0, max = this.outerLocalVariables.length; i < max; i++) {
        LocalVariableBinding argBinding;
        codeStream.addVisibleLocalVariable(argBinding = this.outerLocalVariables[i]);
        codeStream.record(argBinding);
        argBinding.recordInitializationStartPC(0);
      }
    }
    // arguments initialization for local variable debug attributes
    if (this.arguments != null) {
      for (int i = 0, max = this.arguments.length; i < max; i++) {
        LocalVariableBinding argBinding;
        codeStream.addVisibleLocalVariable(argBinding = this.arguments[i].binding);
        argBinding.recordInitializationStartPC(0);
      }
    }
    if (this.body instanceof Block) {
      this.body.generateCode(this.scope, codeStream);
      if ((this.bits & ASTNode.NeedFreeReturn) != 0) {
        codeStream.return_();
      }
    } else {
      Expression expression = (Expression) this.body;
      expression.generateCode(this.scope, codeStream, true);
      if (this.binding.returnType == TypeBinding.VOID) {
        codeStream.return_();
      } else {
        codeStream.generateReturnBytecode(expression);
      }
    }
    // local variable attributes
    codeStream.exitUserScope(this.scope);
    codeStream.recordPositionsFrom(0, this.sourceEnd); // WAS declarationSourceEnd.
    try {
      classFile.completeCodeAttribute(codeAttributeOffset);
    } catch(NegativeArraySizeException e) {
      throw new AbortMethod(this.scope.referenceCompilationUnit().compilationResult, null);
    }
View Full Code Here

Examples of org.eclipse.jdt.internal.compiler.codegen.CodeStream

    int constantPoolOffset = constantPool.currentOffset;
    int constantPoolIndex = constantPool.currentIndex;
    classFile.generateMethodInfoHeaderForClinit();
    int codeAttributeOffset = classFile.contentsOffset;
    classFile.generateCodeAttributeHeader();
    CodeStream codeStream = classFile.codeStream;
    resolve(classScope);

    codeStream.reset(this, classFile);
    TypeDeclaration declaringType = classScope.referenceContext;

    // initialize local positions - including initializer scope.
    MethodScope staticInitializerScope = declaringType.staticInitializerScope;
    staticInitializerScope.computeLocalVariablePositions(0, codeStream);

    // 1.4 feature
    // This has to be done before any other initialization
    if (this.assertionSyntheticFieldBinding != null) {
      // generate code related to the activation of assertion for this class
      codeStream.generateClassLiteralAccessForType(
          classScope.outerMostClassScope().enclosingSourceType(),
          this.classLiteralSyntheticField);
      codeStream.invokeJavaLangClassDesiredAssertionStatus();
      BranchLabel falseLabel = new BranchLabel(codeStream);
      codeStream.ifne(falseLabel);
      codeStream.iconst_1();
      BranchLabel jumpLabel = new BranchLabel(codeStream);
      codeStream.decrStackSize(1);
      codeStream.goto_(jumpLabel);
      falseLabel.place();
      codeStream.iconst_0();
      jumpLabel.place();
      codeStream.fieldAccess(Opcodes.OPC_putstatic, this.assertionSyntheticFieldBinding, null /* default declaringClass */);
    }
    // generate static fields/initializers/enum constants
    final FieldDeclaration[] fieldDeclarations = declaringType.fields;
    int sourcePosition = -1;
    int remainingFieldCount = 0;
    if (TypeDeclaration.kind(declaringType.modifiers) == TypeDeclaration.ENUM_DECL) {
      int enumCount = declaringType.enumConstantsCounter;
      if (enumCount > ENUM_CONSTANTS_THRESHOLD) {
        // generate synthetic methods to initialize all the enum constants
        int begin = -1;
        int count = 0;
        if (fieldDeclarations != null) {
          int max = fieldDeclarations.length;
          for (int i = 0; i < max; i++) {
            FieldDeclaration fieldDecl = fieldDeclarations[i];
            if (fieldDecl.isStatic()) {
              if (fieldDecl.getKind() == AbstractVariableDeclaration.ENUM_CONSTANT) {
                if (begin == -1) {
                  begin = i;
                }
                count++;
                if (count > ENUM_CONSTANTS_THRESHOLD) {
                  SyntheticMethodBinding syntheticMethod = declaringType.binding.addSyntheticMethodForEnumInitialization(begin, i);
                  codeStream.invoke(Opcodes.OPC_invokestatic, syntheticMethod, null /* default declaringClass */);
                  begin = i;
                  count = 1;
                }
              } else {
                remainingFieldCount++;
              }
            }
          }
          if (count != 0) {
            // add last synthetic method
            SyntheticMethodBinding syntheticMethod = declaringType.binding.addSyntheticMethodForEnumInitialization(begin, max);
            codeStream.invoke(Opcodes.OPC_invokestatic, syntheticMethod, null /* default declaringClass */);
          }
        }
      } else if (fieldDeclarations != null) {
        for (int i = 0, max = fieldDeclarations.length; i < max; i++) {
          FieldDeclaration fieldDecl = fieldDeclarations[i];
          if (fieldDecl.isStatic()) {
            if (fieldDecl.getKind() == AbstractVariableDeclaration.ENUM_CONSTANT) {
              fieldDecl.generateCode(staticInitializerScope, codeStream);
            } else {
              remainingFieldCount++;
            }
          }
        }
      }
      // enum need to initialize $VALUES synthetic cache of enum constants
      // $VALUES := new <EnumType>[<enumCount>]
      codeStream.generateInlinedValue(enumCount);
      codeStream.anewarray(declaringType.binding);
      if (enumCount > 0) {
        if (fieldDeclarations != null) {
          for (int i = 0, max = fieldDeclarations.length; i < max; i++) {
            FieldDeclaration fieldDecl = fieldDeclarations[i];
            // $VALUES[i] = <enum-constant-i>
            if (fieldDecl.getKind() == AbstractVariableDeclaration.ENUM_CONSTANT) {
              codeStream.dup();
              codeStream.generateInlinedValue(fieldDecl.binding.id);
              codeStream.fieldAccess(Opcodes.OPC_getstatic, fieldDecl.binding, null /* default declaringClass */);
              codeStream.aastore();
            }
          }
        }
      }
      codeStream.fieldAccess(Opcodes.OPC_putstatic, declaringType.enumValuesSyntheticfield, null /* default declaringClass */);
      if (remainingFieldCount != 0) {
        // if fields that are not enum constants need to be generated (static initializer/static field)
        for (int i = 0, max = fieldDeclarations.length; i < max && remainingFieldCount >= 0; i++) {
          FieldDeclaration fieldDecl = fieldDeclarations[i];
          switch (fieldDecl.getKind()) {
            case AbstractVariableDeclaration.ENUM_CONSTANT :
              break;
            case AbstractVariableDeclaration.INITIALIZER :
              if (!fieldDecl.isStatic()) {
                break;
              }
              remainingFieldCount--;
              sourcePosition = ((Initializer) fieldDecl).block.sourceEnd;
              fieldDecl.generateCode(staticInitializerScope, codeStream);
              break;
            case AbstractVariableDeclaration.FIELD :
              if (!fieldDecl.binding.isStatic()) {
                break;
              }
              remainingFieldCount--;
              sourcePosition = fieldDecl.declarationEnd;
              fieldDecl.generateCode(staticInitializerScope, codeStream);
              break;
          }
        }
      }
    } else {
      if (fieldDeclarations != null) {
        for (int i = 0, max = fieldDeclarations.length; i < max; i++) {
          FieldDeclaration fieldDecl = fieldDeclarations[i];
          switch (fieldDecl.getKind()) {
            case AbstractVariableDeclaration.INITIALIZER :
              if (!fieldDecl.isStatic())
                break;
              sourcePosition = ((Initializer) fieldDecl).block.sourceEnd;
              fieldDecl.generateCode(staticInitializerScope, codeStream);
              break;
            case AbstractVariableDeclaration.FIELD :
              if (!fieldDecl.binding.isStatic())
                break;
              sourcePosition = fieldDecl.declarationEnd;
              fieldDecl.generateCode(staticInitializerScope, codeStream);
              break;
          }
        }
      }
    }

    if (codeStream.position == 0) {
      // do not need to output a Clinit if no bytecodes
      // so we reset the offset inside the byte array contents.
      classFile.contentsOffset = clinitOffset;
      // like we don't addd a method we need to undo the increment on the method count
      classFile.methodCount--;
      // reset the constant pool to its state before the clinit
      constantPool.resetForClinit(constantPoolIndex, constantPoolOffset);
    } else {
      if ((this.bits & ASTNode.NeedFreeReturn) != 0) {
        int before = codeStream.position;
        codeStream.return_();
        if (sourcePosition != -1) {
          // expand the last initializer variables to include the trailing return
          codeStream.recordPositionsFrom(before, sourcePosition);
        }
      }
      // Record the end of the clinit: point to the declaration of the class
      codeStream.recordPositionsFrom(0, declaringType.sourceStart);
      classFile.completeCodeAttributeForClinit(codeAttributeOffset);
    }
  }
View Full Code Here

Examples of ptolemy.codegen.kernel.CodeStream

            File directory = new File(FileUtilities.nameToURL(
                    "$CLASSPATH/ptolemy/codegen/c/kernel/type/polymorphic",
                    null, null).getFile());
            for (File file : directory.listFiles()) {
                String filename = file.getPath();
                CodeStream stream = new CodeStream(filename, null);

                TreeSet sortedSet = new TreeSet(stream
                        .getAllCodeBlockSignatures());

                String code = "";
                for (Object signature : sortedSet) {
                    code += stream.getCodeBlockTemplate(signature);
                }

                if (code.trim().length() > 0) {
                    FileWriter writer = new FileWriter(new File(filename));
                    writer.write(code);
View Full Code Here

Examples of ptolemy.codegen.kernel.CodeStream

                + comment("Generate type resolution code for "
                        + getContainer().getFullName()));

        // Include the constantsBlock at the top so that sharedBlocks from
        // actors can use true and false etc.  StringMatches needs this.
        CodeStream sharedStream = new CodeStream(
                "$CLASSPATH/ptolemy/codegen/c/kernel/SharedCode.c", this);
        sharedStream.appendCodeBlock("constantsBlock");
        code.append(sharedStream.toString());

        HashSet functions = _getReferencedFunctions();

        HashSet types = _getReferencedTypes(functions);

        Object[] typesArray = types.toArray();
        CodeStream[] typeStreams = new CodeStream[types.size()];

        // Generate type map.
        StringBuffer typeMembers = new StringBuffer();
        code.append("#define TYPE_Token -1 " + _eol);
        for (int i = 0; i < typesArray.length; i++) {
            // Open the .c file for each type.
            typeStreams[i] = new CodeStream(
                    "$CLASSPATH/ptolemy/codegen/c/kernel/type/" + typesArray[i]
                            + ".c", this);

            code.append("#define TYPE_" + typesArray[i] + " " + i + _eol);

            // Dynamically generate all the types within the union.
            if (i > 0) {
                typeMembers.append(_INDENT2);
            }
            typeMembers.append(typesArray[i] + "Token " + typesArray[i] + ";");
            if (i < typesArray.length - 1) {
                typeMembers.append(_eol);
            }
        }

        Object[] functionsArray = functions.toArray();

        // True if we have a delete function that needs to return a Token
        boolean defineEmptyToken = false;

        // Generate function map.
        for (int i = 0; i < functionsArray.length; i++) {

            code.append("#define FUNC_" + functionsArray[i] + " " + i + _eol);
            if (functionsArray[i].equals("delete")) {
                defineEmptyToken = true;
            }
        }

        code.append("typedef struct token Token;" + _eol);

        // Generate type and function definitions.
        for (int i = 0; i < typesArray.length; i++) {
            // The "declareBlock" contains all necessary declarations for the
            // type; thus, it is always read into the code stream when
            // accessing this particular type.
            typeStreams[i].appendCodeBlock("declareBlock");
            code.append(typeStreams[i].toString());
        }

        ArrayList args = new ArrayList();
        // Token declareBlock.
        if (typeMembers.length() != 0) {
            args.add(typeMembers.toString());
            sharedStream.clear();
            sharedStream.appendCodeBlock("tokenDeclareBlock", args);

            if (defineEmptyToken) {
                sharedStream.append("Token emptyToken; "
                        + comment("Used by *_delete() and others.") + _eol);
            }
        }

        // Set to true if we need the unsupportedFunction() method.
        boolean defineUnsupportedTypeFunctionMethod = false;

        // Set to true if we need to scalarDelete() method.
        boolean defineScalarDeleteMethod = false;

        // Append type-polymorphic functions included in the function table.
        for (int i = 0; i < types.size(); i++) {
            // The "funcDeclareBlock" contains all function declarations for
            // the type.
            for (int j = 0; j < functionsArray.length; j++) {
                String typeFunctionName = typesArray[i] + "_"
                        + functionsArray[j];
                if (_unsupportedTypeFunctions.contains(typeFunctionName)) {
                    defineUnsupportedTypeFunctionMethod = true;
                }
                if (_scalarDeleteTypes.contains(typesArray[i])
                        && functionsArray[j].equals("delete")) {
                    defineScalarDeleteMethod = true;
                }
                if (functionsArray[j].equals("isCloseTo")
                        && (typesArray[i].equals("Boolean") || typesArray[i]
                                .equals("String"))) {
                    boolean foundEquals = false;
                    for (int k = 0; k < functionsArray.length; k++) {
                        if (functionsArray[k].equals("equals")) {
                            foundEquals = true;
                        }
                    }
                    if (!foundEquals) {
                        // Boolean_isCloseTo and String_isCloseTo
                        // use Boolean_equals and String_equals.
                        args.clear();
                        args.add(typesArray[i] + "_equals");
                        sharedStream.appendCodeBlock("funcHeaderBlock", args);
                    }
                }
                if (!_scalarDeleteTypes.contains(typesArray[i])
                        || !functionsArray[j].equals("delete")) {
                    // Skip Boolean_delete etc.
                    args.clear();
                    args.add(typeFunctionName);
                    sharedStream.appendCodeBlock("funcHeaderBlock", args);
                }
            }
        }

        if (defineUnsupportedTypeFunctionMethod) {
            // Some type/function combos are not supported, so we
            // save space by defining only one method.
            sharedStream.appendCodeBlock("unsupportedTypeFunction");
        }

        if (defineScalarDeleteMethod) {
            // Types that share the scalarDelete() method, which does nothing.
            // We use one method so as to reduce code size.
            sharedStream.appendCodeBlock("scalarDeleteFunction");
        }

        code.append(sharedStream.toString());

        // Append functions that are specified used by this type (without
        // going through the function table).
        for (int i = 0; i < typesArray.length; i++) {
            typeStreams[i].clear();
            typeStreams[i].appendCodeBlock("funcDeclareBlock");
            code.append(typeStreams[i].toString());
        }

        // FIXME: in the future we need to load the convertPrimitivesBlock
        // dynamically, and maybe break it into multiple blocks to minimize
        // code size.
        sharedStream.clear();
        sharedStream.appendCodeBlock("convertPrimitivesBlock");
        code.append(sharedStream.toString());

        // Generate function type and token table.
        code.append(generateFunctionTable(typesArray, functionsArray));

        for (int i = 0; i < typesArray.length; i++) {
View Full Code Here

Examples of ptolemy.codegen.kernel.CodeStream

        super._analyzeTypeConversions();

        String typeDir = "$CLASSPATH/ptolemy/codegen/c/kernel/type/";
        String functionDir = typeDir + "polymorphic/";

        _overloadedFunctions = new CodeStream(functionDir + "add.c", this);
        _overloadedFunctions.parse(functionDir + "multiply.c");
        _overloadedFunctions.parse(functionDir + "divide.c");
        _overloadedFunctions.parse(functionDir + "subtract.c");
        _overloadedFunctions.parse(functionDir + "convert.c");
        _overloadedFunctions.parse(functionDir + "negate.c");
View Full Code Here

Examples of ptolemy.codegen.kernel.CodeStream

            File directory = new File(FileUtilities.nameToURL(
                    "$CLASSPATH/ptolemy/codegen/SystemC/kernel/type/polymorphic",
                    null, null).getFile());
            for (File file : directory.listFiles()) {
                String filename = file.getPath();
                CodeStream stream = new CodeStream(filename, null);

                TreeSet sortedSet = new TreeSet(stream
                        .getAllCodeBlockSignatures());

                String code = "";
                for (Object signature : sortedSet) {
                    code += stream.getCodeBlockTemplate(signature);
                }

                if (code.trim().length() > 0) {
                    FileWriter writer = new FileWriter(new File(filename));
                    writer.write(code);
View Full Code Here

Examples of ptolemy.codegen.kernel.CodeStream

                + comment("Generate type resolution code for "
                        + getContainer().getFullName()));

        // Include the constantsBlock at the top so that sharedBlocks from
        // actors can use true and false etc.  StringMatches needs this.
        CodeStream sharedStream = new CodeStream(
                "$CLASSPATH/ptolemy/codegen/SystemC/kernel/SharedCode.c", this);
        sharedStream.appendCodeBlock("constantsBlock");
        code.append(sharedStream.toString());

        HashSet functions = _getReferencedFunctions();

        HashSet types = _getReferencedTypes(functions);

        Object[] typesArray = types.toArray();
        CodeStream[] typeStreams = new CodeStream[types.size()];

        // Generate type map.
        StringBuffer typeMembers = new StringBuffer();
        code.append("#define TYPE_Token -1 " + _eol);

        for (int i = 0; i < typesArray.length; i++) {
            // Open the .c file for each type.
            typeStreams[i] = new CodeStream(
                    "$CLASSPATH/ptolemy/codegen/SystemC/kernel/type/" + typesArray[i]
                            + ".c", this);

            code.append("#define TYPE_" + typesArray[i] + " " + i + _eol);

            // Dynamically generate all the types within the union.
            if (i > 0) {
                typeMembers.append(_INDENT2);
            }
            typeMembers.append(typesArray[i] + "Token " + typesArray[i] + ";");
            if (i < typesArray.length - 1) {
                typeMembers.append(_eol);
            }
        }

        Object[] functionsArray = functions.toArray();

        // True if we have a delete function that needs to return a Token
        boolean defineEmptyToken = false;

        // Generate function map.
        for (int i = 0; i < functionsArray.length; i++) {

            code.append("#define FUNC_" + functionsArray[i] + " " + i + _eol);
            if (functionsArray[i].equals("delete")) {
                defineEmptyToken = true;
            }
        }

        code.append("typedef struct token Token;" + _eol);

        // Generate type and function definitions.
        for (int i = 0; i < typesArray.length; i++) {
            // The "declareBlock" contains all necessary declarations for the
            // type; thus, it is always read into the code stream when
            // accessing this particular type.
            typeStreams[i].appendCodeBlock("declareBlock");
            code.append(typeStreams[i].toString());
        }

        ArrayList args = new ArrayList();
        // Token declareBlock.
        if (typeMembers.length() != 0) {
            sharedStream.clear();
            args.add(typeMembers.toString());
            sharedStream.appendCodeBlock("tokenDeclareBlock", args);

            if (defineEmptyToken) {
                sharedStream.append("Token emptyToken; "
                        + comment("Used by *_delete() and others.") + _eol);
            }
        }

        // Set to true if we need the unsupportedFunction() method.
        boolean defineUnsupportedTypeFunctionMethod = false;

        // Set to true if we need to scalarDelete() method.
        boolean defineScalarDeleteMethod = false;

        // Append type-polymorphic functions included in the function table.
        for (int i = 0; i < types.size(); i++) {
            // The "funcDeclareBlock" contains all function declarations for
            // the type.
            for (int j = 0; j < functionsArray.length; j++) {
                String typeFunctionName = typesArray[i] + "_"
                        + functionsArray[j];
                if (_unsupportedTypeFunctions.contains(typeFunctionName)) {
                    defineUnsupportedTypeFunctionMethod = true;
                }
                if (_scalarDeleteTypes.contains(typesArray[i])
                        && functionsArray[j].equals("delete")) {
                    defineScalarDeleteMethod = true;
                }
                if (functionsArray[j].equals("isCloseTo")
                        && (typesArray[i].equals("Boolean") || typesArray[i]
                                .equals("String"))) {
                    boolean foundEquals = false;
                    for (int k = 0; k < functionsArray.length; k++) {
                        if (functionsArray[k].equals("equals")) {
                            foundEquals = true;
                        }
                    }
                    if (!foundEquals) {
                        // Boolean_isCloseTo and String_isCloseTo
                        // use Boolean_equals and String_equals.
                        args.clear();
                        args.add(typesArray[i] + "_equals");
                        sharedStream.appendCodeBlock("funcHeaderBlock", args);
                    }
                }
                if (!_scalarDeleteTypes.contains(typesArray[i])
                        || !functionsArray[j].equals("delete")) {
                    // Skip Boolean_delete etc.
                    args.clear();
                    args.add(typeFunctionName);
                    sharedStream.appendCodeBlock("funcHeaderBlock", args);
                }
            }
        }

        if (defineUnsupportedTypeFunctionMethod) {
            // Some type/function combos are not supported, so we
            // save space by defining only one method.
            sharedStream.appendCodeBlock("unsupportedTypeFunction");
        }

        if (defineScalarDeleteMethod) {
            // Types that share the scalarDelete() method, which does nothing.
            // We use one method so as to reduce code size.
            sharedStream.appendCodeBlock("scalarDeleteFunction");
        }

        code.append(sharedStream.toString());

        // Append functions that are specified used by this type (without
        // going through the function table).
        for (int i = 0; i < typesArray.length; i++) {
            typeStreams[i].clear();
            typeStreams[i].appendCodeBlock("funcDeclareBlock");
            code.append(typeStreams[i].toString());
        }

        // FIXME: in the future we need to load the convertPrimitivesBlock
        // dynamically, and maybe break it into multiple blocks to minimize
        // code size.
        sharedStream.clear();
        sharedStream.appendCodeBlock("convertPrimitivesBlock");
        code.append(sharedStream.toString());

        // Generate function type and token table.
        code.append(generateFunctionTable(typesArray, functionsArray));

        for (int i = 0; i < typesArray.length; i++) {
View Full Code Here

Examples of ptolemy.codegen.kernel.CodeStream

        String SystemCCodegenPath = "$CLASSPATH/ptolemy/codegen/SystemC/";
        String typeDir = SystemCCodegenPath + "kernel/type/";
        String functionDir = typeDir + "polymorphic/";

        _overloadedFunctions = new CodeStream(functionDir + "add.c", this);
        _overloadedFunctions.parse(functionDir + "multiply.c");
        _overloadedFunctions.parse(functionDir + "divide.c");
        _overloadedFunctions.parse(functionDir + "subtract.c");
        _overloadedFunctions.parse(functionDir + "convert.c");
        _overloadedFunctions.parse(functionDir + "negate.c");
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.