Beispiel #1
0
// Set the value of a table's field.
static void BuildFieldOfTable(const StructDef &struct_def,
                              const FieldDef &field,
                              const size_t offset,
                              std::string *code_ptr) {
  std::string &code = *code_ptr;
  code += "func " + struct_def.name + "Add" + MakeCamel(field.name);
  code += "(builder *flatbuffers.Builder, ";
  code += MakeCamel(field.name, false) + " ";
  if (!IsScalar(field.value.type.base_type) && (!struct_def.fixed)) {
    code += "flatbuffers.UOffsetT";
  } else {
    code += GenTypeBasic(field.value.type);
  }
  code += ") {\n";
  code += "\tbuilder.Prepend";
  code += GenMethod(field) + "Slot(";
  code += NumToString(offset) + ", ";
  if (!IsScalar(field.value.type.base_type) && (!struct_def.fixed)) {
    code += "flatbuffers.UOffsetT";
    code += "(";
    code += MakeCamel(field.name, false) + ")";
  } else {
    code += MakeCamel(field.name, false);
  }
  code += ", " + field.value.constant;
  code += ")\n}\n";
}
//---------------------------------------------------------------------------
bool IValue::operator<=(const IValue &a_Val) const
{
    char_type type1 = GetType(),
        type2 = a_Val.GetType();

    if (type1 == type2 || (IsScalar() && a_Val.IsScalar()))
    {
        switch (GetType())
        {
        case 's': return GetString() <= a_Val.GetString();
        case 'i':
        case 'f':
        case 'c': return GetFloat() <= a_Val.GetFloat();
        case 'b': return GetBool() <= a_Val.GetBool();
        default:
            ErrorContext err;
            err.Errc = ecINTERNAL_ERROR;
            err.Pos = -1;
            err.Type1 = GetType();
            err.Type2 = a_Val.GetType();
            throw ParserError(err);

        } // switch this type
    }
    else
    {
        ErrorContext err;
        err.Errc = ecTYPE_CONFLICT_FUN;
        err.Arg = (type1 != 'f' && type1 != 'i') ? 1 : 2;
        err.Type1 = type2;
        err.Type2 = type1;
        throw ParserError(err);
    }
}
Beispiel #3
0
// Return a C++ type for any type (scalar/pointer) specifically for
// using a flatbuffer.
static std::string GenTypeGet(const Parser &parser, const Type &type,
                              const char *afterbasic, const char *beforeptr,
                              const char *afterptr, bool real_enum) {
  return IsScalar(type.base_type)
    ? GenTypeBasic(parser, type, real_enum) + afterbasic
    : beforeptr + GenTypePointer(parser, type) + afterptr;
}
Beispiel #4
0
// Return a C++ type for any type (scalar/pointer) that reflects its
// serialized size.
static std::string GenTypeSize(const Parser &parser, const Type &type) {
  return IsScalar(type.base_type)
    ? GenTypeBasic(parser, type, false)
    : IsStruct(type)
      ? GenTypePointer(parser, type)
      : "flatbuffers::uoffset_t";
}
Beispiel #5
0
// Generates a value with optionally a cast applied if the field has a
// different underlying type from its interface type (currently only the
// case for enums. "from" specify the direction, true meaning from the
// underlying type to the interface type.
std::string GenUnderlyingCast(const Parser &parser, const FieldDef &field,
                              bool from, const std::string &val) {
  return field.value.type.enum_def && IsScalar(field.value.type.base_type)
      ? "static_cast<" + GenTypeBasic(parser, field.value.type, from) + ">(" +
        val + ")"
      : val;
}
Beispiel #6
0
// Generate text for a struct or table, values separated by commas, indented,
// and bracketed by "{}"
static void GenStruct(const StructDef &struct_def, const Table *table,
                      int indent, const IDLOptions &opts,
                      std::string *_text) {
  std::string &text = *_text;
  text += "{";
  int fieldout = 0;
  StructDef *union_sd = nullptr;
  for (auto it = struct_def.fields.vec.begin();
       it != struct_def.fields.vec.end();
       ++it) {
    FieldDef &fd = **it;
    auto is_present = struct_def.fixed || table->CheckField(fd.value.offset);
    auto output_anyway = opts.output_default_scalars_in_json &&
                         IsScalar(fd.value.type.base_type) &&
                         !fd.deprecated;
    if (is_present || output_anyway) {
      if (fieldout++) {
        text += ",";
      }
      text += NewLine(opts);
      text.append(indent + Indent(opts), ' ');
      OutputIdentifier(fd.name, opts, _text);
      text += ": ";
      if (is_present) {
        switch (fd.value.type.base_type) {
           #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, \
             PTYPE) \
             case BASE_TYPE_ ## ENUM: \
                GenField<CTYPE>(fd, table, struct_def.fixed, \
                                opts, indent + Indent(opts), _text); \
                break;
            FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD)
          #undef FLATBUFFERS_TD
          // Generate drop-thru case statements for all pointer types:
          #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, \
            PTYPE) \
            case BASE_TYPE_ ## ENUM:
            FLATBUFFERS_GEN_TYPES_POINTER(FLATBUFFERS_TD)
          #undef FLATBUFFERS_TD
              GenFieldOffset(fd, table, struct_def.fixed, indent + Indent(opts),
                             union_sd, opts, _text);
              break;
        }
        if (fd.value.type.base_type == BASE_TYPE_UTYPE) {
          auto enum_val = fd.value.type.enum_def->ReverseLookup(
                                  table->GetField<uint8_t>(fd.value.offset, 0));
          assert(enum_val);
          union_sd = enum_val->struct_def;
        }
      }
      else
      {
        text += fd.value.constant;
      }
    }
  }
  text += NewLine(opts);
  text.append(indent, ' ');
  text += "}";
}
Beispiel #7
0
  //---------------------------------------------------------------------------
  IValue& Value::operator+=(const IValue &val)
  {
    if (IsScalar() && val.IsScalar())
    {
      // Scalar/Scalar addition
      m_val += val.GetComplex();
      m_cType = (m_val.imag()==0) ? ( (m_val.real()==(int)m_val.real()) ? 'i' : 'f' ) : 'c';
    }
    else if (IsMatrix() && val.IsMatrix())
    {
      // Matrix/Matrix addition
      assert(m_pvVal);
      *m_pvVal += val.GetArray();
    }
    else if (IsString() && val.IsString())
    {
      // string/string addition
      assert(m_psVal);
      *m_psVal += val.GetString();
    }
    else
    {
      // Type conflict
      throw ParserError(ErrorContext(ecTYPE_CONFLICT_FUN, -1, _T("+"), GetType(), val.GetType(), 2));
    }

    return *this;
  }
Beispiel #8
0
// Return a C++ type for any type (scalar/pointer) specifically for
// building a flatbuffer.
static std::string GenTypeWire(const Type &type, const char *postfix) {
  return IsScalar(type.base_type)
    ? GenTypeBasic(type) + postfix
    : IsStruct(type)
      ? "const " + GenTypePointer(type) + " *"
      : "flatbuffers::Offset<" + GenTypePointer(type) + ">" + postfix;
}
Beispiel #9
0
  /** \brief Get the imaginary part of the value. 
      \throw ParserError in case this value represents a string or a matrix
  */
  float_type Value::GetImag() const
  {
    if (!IsScalar())
    {
      ErrorContext err;
      err.Errc  = ecTYPE_CONFLICT;
      err.Type1 = m_cType;
      err.Type2 = 'c';
      
      if (GetIdent().length())
      {
        err.Ident = GetIdent();
      }
      else
      {
        stringstream_type ss;
        ss << *this;
        err.Ident = ss.str();
      }

      throw ParserError(err);
    }

    return m_val.imag();
  }
Beispiel #10
0
static Stmt *BuildProgramReturnAssignments( CgContext *cg, Stmt *fStmt, void *arg1, int arg2)
{
  struct BuildReturnAssignments *lstr;
  Symbol *program, *lSymb, *voutVar, *outSymb, *retSymb;
  Type *lType, *rettype;
  Expr *lExpr, *rexpr, *returnVar, *outputVar;
  Scope *lScope, *gScope, *voutScope;
  Stmt *lStmt, *stmtlist;
  int len;
	Atom lname;
  
  if (fStmt->kind == RETURN_STMT) {
    lstr = (struct BuildReturnAssignments *) arg1;
    gScope = lstr->globalScope;
    program = lstr->program;
    lType = program->type;
    rettype = static_cast< TypeFunction * >( lType )->rettype;
    TypeCategory category = rettype->category;
    if (IsVoid(rettype)) {
      fStmt = NULL;
    } else {
      if (category == TC_Struct) {
        stmtlist = NULL;
        voutVar = cg->theHal->varyingOut;
        voutScope = static_cast< TypeStruct * >( voutVar->type )->members;
        lScope = static_cast< TypeStruct * >( rettype )->members;
        lSymb = lScope->symbols;
        while (lSymb) {
          // Create an assignment statement of the bound variable to the $vout member:
          lname = lSymb->details.var.semantics.IsValid() ? lSymb->details.var.semantics : lSymb->name;
          outSymb = LookupLocalSymbol(cg, voutScope, lname);
          retSymb = LookupLocalSymbol(cg, lScope, lSymb->name);
          if (outSymb && retSymb) {
            // outSymb may not be in the symbol table if it's a "hidden" register.
            returnVar = DupExpr( cg, static_cast< ReturnStmt * >( fStmt )->expr);
            outputVar = (Expr *) NewSymbNode( cg, VARIABLE_OP, voutVar);
            lExpr = GenMemberReference( cg, outputVar, outSymb);
            rexpr = GenMemberReference( cg, returnVar, retSymb);
            if (IsScalar(lSymb->type) || IsVector(lSymb->type, &len)) {
              lStmt = NewSimpleAssignmentStmt( cg, &program->loc, lExpr, rexpr, 0);
              stmtlist = ConcatStmts(stmtlist, lStmt);
            } else {
              FatalError( cg, "Return of unsupported type");
              // xxx
            }
          }
          lSymb = lSymb->next;
        }
				delete fStmt;
        fStmt = stmtlist;
      } else {
        // Already reported:
        // SemanticError(&program->loc, ERROR_S_PROGRAM_MUST_RETURN_STRUCT,
        //               cg->GetString(program->name));
      }
    }
  }
  return fStmt;
} // BuildProgramReturnAssignments
Beispiel #11
0
// Return a C++ type for any type (scalar/pointer) specifically for
// building a flatbuffer.
static std::string GenTypeWire(const Parser &parser, const Type &type,
                               const char *postfix, bool real_enum) {
  return IsScalar(type.base_type)
    ? GenTypeBasic(parser, type, real_enum) + postfix
    : IsStruct(type)
      ? "const " + GenTypePointer(parser, type) + " *"
      : "flatbuffers::Offset<" + GenTypePointer(parser, type) + ">" + postfix;
}
Beispiel #12
0
			ExpressionType GetType() const {
				if (IsTensor()) return ExpressionType::TENSOR;
				else if (IsScalar()) return ExpressionType::SCALAR;
				else if (IsIndices()) return ExpressionType::INDICES;
				else if (IsBoolean()) return ExpressionType::BOOLEAN;
				else if (IsSubstitution()) return ExpressionType::SUBSTITUTION;
				else if (IsVoid()) return ExpressionType::VOID_TYPE;
				return ExpressionType::UNKNOWN;
			}
Beispiel #13
0
  /** \brief Assign a value with multiplication
      \param val The value to multiply to this

    When multiplying to values with each value representing a matrix type
    the result is checked whether it is a 1 x 1 matrix. If so the value is
    "unboxed" and stored directly in this value object. It is no longer 
    treated as a matrix internally.
  */
  IValue& Value::operator*=(const IValue &val)
  {
    if (IsScalar() && val.IsScalar())
    {
      // Scalar/Scalar multiplication
      m_val *= val.GetComplex();
      m_cType = (m_val.imag()==0) ? ( (m_val.real()==(int)m_val.real()) ? 'i' : 'f' ) : 'c';
    }
    else if (IsMatrix() && val.IsMatrix())
    {
      // Matrix/Matrix addition
      assert(m_pvVal);
      *m_pvVal *= val.GetArray();

      // The result may actually be a scalar value, i.e. the scalar product of
      // two vectors.
      if (m_pvVal->GetCols()==1 && m_pvVal->GetRows()==1)
      {
        Assign(m_pvVal->At(0,0));
      }
    }
    else if ( IsMatrix() && val.IsScalar() )
    {
      *m_pvVal *= val;
    }
    else if ( IsScalar() * val.IsMatrix() )
    {
      // transform this into a matrix and multiply with rhs
      Value prod = val * (*this);
      Assign(prod);
    }
    else
    {
      // Type conflict
      ErrorContext errc(ecTYPE_CONFLICT_FUN, -1, _T("*"));
      errc.Type1 = GetType();
      errc.Type2 = 'm'; //val.GetType();
      errc.Arg = 2;
      throw ParserError(errc);
    }

    return *this;
  }
Beispiel #14
0
// Generate a struct field setter, conditioned on its child type(s).
static void GenStructMutator(const StructDef &struct_def,
                              const FieldDef &field,
                              std::string *code_ptr) {
  GenComment(field.doc_comment, code_ptr, nullptr, "");
  if (IsScalar(field.value.type.base_type)) {
    if (struct_def.fixed) {
      MutateScalarFieldOfStruct(struct_def, field, code_ptr);
    } else {
      MutateScalarFieldOfTable(struct_def, field, code_ptr);
    }
  }
}
Beispiel #15
0
// Generate a struct field getter, conditioned on its child type(s).
static void GenStructAccessor(const StructDef &struct_def,
                              const FieldDef &field,
                              std::string *code_ptr) {
  GenComment(field.doc_comment, code_ptr, nullptr, "");
  if (IsScalar(field.value.type.base_type)) {
    if (struct_def.fixed) {
      GetScalarFieldOfStruct(struct_def, field, code_ptr);
    } else {
      GetScalarFieldOfTable(struct_def, field, code_ptr);
    }
  } else {
    switch (field.value.type.base_type) {
      case BASE_TYPE_STRUCT:
        if (struct_def.fixed) {
          GetStructFieldOfStruct(struct_def, field, code_ptr);
        } else {
          GetStructFieldOfTable(struct_def, field, code_ptr);
        }
        break;
      case BASE_TYPE_STRING:
        GetStringField(struct_def, field, code_ptr);
        break;
      case BASE_TYPE_VECTOR: {
        auto vectortype = field.value.type.VectorType();
        if (vectortype.base_type == BASE_TYPE_STRUCT) {
          GetMemberOfVectorOfStruct(struct_def, field, code_ptr);
        } else {
          GetMemberOfVectorOfNonStruct(struct_def, field, code_ptr);
        }
        break;
      }
      case BASE_TYPE_UNION:
        GetUnionField(struct_def, field, code_ptr);
        break;
      default:
        assert(0);
    }
  }
  if (field.value.type.base_type == BASE_TYPE_VECTOR) {
    GetVectorLen(struct_def, field, code_ptr);
    if (field.value.type.element == BASE_TYPE_UCHAR) {
      GetUByteSlice(struct_def, field, code_ptr);
    }
  }
}
//---------------------------------------------------------------------------
bool IValue::operator!=(const IValue &a_Val) const
{
    char_type type1 = GetType(),
        type2 = a_Val.GetType();

    if (type1 == type2 || (IsScalar() && a_Val.IsScalar()))
    {
        switch (GetType())
        {
        case 's': return GetString() != a_Val.GetString();
        case 'i':
        case 'f': return GetFloat() != a_Val.GetFloat();
        case 'c': return (GetFloat() != a_Val.GetFloat()) || (GetImag() != a_Val.GetImag());
        case 'b': return GetBool() != a_Val.GetBool();
        case 'v': return true;
        case 'm': if (GetRows() != a_Val.GetRows() || GetCols() != a_Val.GetCols())
        {
            return true;
        }
                  else
                  {
                      for (int i = 0; i < GetRows(); ++i)
                      {
                          if (const_cast<IValue*>(this)->At(i) != const_cast<IValue&>(a_Val).At(i))
                              return true;
                      }

                      return false;
                  }
        default:
            ErrorContext err;
            err.Errc = ecINTERNAL_ERROR;
            err.Pos = -1;
            err.Type2 = GetType();
            err.Type1 = a_Val.GetType();
            throw ParserError(err);
        } // switch this type
    }
    else
    {
        return true;
    }
}
Beispiel #17
0
bool HasAllSet(const llvm::Value* value)
{
    const llvm::Constant* c = llvm::dyn_cast<llvm::Constant>(value);
    if (! c)
        return false;

    if (IsScalar(c->getType())) {
        return GetConstantInt(c) == -1;
    } else {
        assert(llvm::isa<llvm::ConstantDataVector>(c) || llvm::isa<llvm::ConstantVector>(c));

        for (unsigned int op = 0; op < GetComponentCount(c); ++op) {
            if (GetConstantInt(c->getAggregateElement(op)) != -1)
                return false;
        }

        return true;
    }
}
Beispiel #18
0
LPPL_YYSTYPE PrimFnDydCircleSlope_EM_YY
    (LPTOKEN lptkLftArg,                // Ptr to left arg token
     LPTOKEN lptkFunc,                  // Ptr to function token
     LPTOKEN lptkRhtArg,                // Ptr to right arg token
     LPTOKEN lptkAxis)                  // Ptr to axis token (may be NULL)

{
    APLSTYPE      aplTypeLft,           // Left arg storage type
                  aplTypeRht,           // Right ...
                  aplTypeRes;           // Result   ...
    APLNELM       aplNELMLft,           // Left arg NELM
                  aplNELMRht,           // Right ...
                  aplNELMRes;           // Result   ...
    APLRANK       aplRankLft,           // Left arg rank
                  aplRankRht,           // Right ...
                  aplRankRes;           // Result   ...
    HGLOBAL       hGlbLft = NULL,       // Left arg global memory handle
                  hGlbRht = NULL,       // Right ...
                  hGlbRes = NULL,       // Result   ...
                  hGlbAxis = NULL,      // Axis     ...
                  hGlbWVec = NULL,      // Weighting vector ...
                  hGlbOdo = NULL;       // Odometer ...
    LPAPLDIM      lpMemDimRht,          // Ptr to right arg dimensions
                  lpMemDimRes;          // Ptr to result    ...
    APLDIM        uMinDim;              //
    LPVOID        lpMemLft = NULL,      // Ptr to left arg global memory
                  lpMemRht = NULL,      // Ptr to right ...
                  lpMemRes = NULL;      // Ptr to result   ...
    LPAPLUINT     lpMemAxisHead = NULL, // Ptr to axis values, fleshed out by CheckAxis_EM
                  lpMemAxisTail,        // Ptr to grade up of AxisHead
                  lpMemWVec = NULL,     // Ptr to weighting vector ...
                  lpMemOdo = NULL;      // Ptr to odometer ...
    APLUINT       ByteRes,              // # bytes in the result
                  uRht,                 // Right arg loop counter
                  uRes,                 // Result    ...
                  uOdo;                 // Odometer  ...
    LPPL_YYSTYPE  lpYYRes = NULL;       // Ptr to the result
    UINT          uBitIndex,            // Bit index for marching through Booleans
                  uBitMask;             // Bit mask  ...
    APLINT        iDim,                 // Dimension loop counter
                  apaOffRht,            // Right arg APA offset
                  apaMulRht;            // ...           multiplier
    LPPLLOCALVARS lpplLocalVars;        // Ptr to re-entrant vars
    LPUBOOL       lpbCtrlBreak;         // Ptr to Ctrl-Break flag
    LPVARARRAY_HEADER lpMemHdrRht;      // Ptr to right arg header

    // Get the thread's ptr to local vars
    lpplLocalVars = TlsGetValue (dwTlsPlLocalVars);

    // Get the ptr to the Ctrl-Break flag
    lpbCtrlBreak = &lpplLocalVars->bCtrlBreak;

    //***************************************************************
    // This function is not sensitive to the axis operator,
    //   so signal a syntax error if present
    //***************************************************************

    if (lptkAxis NE NULL)
        goto AXIS_SYNTAX_EXIT;

    // Get the attributes (Type, NELM, and Rank) of the left & right args
    AttrsOfToken (lptkLftArg, &aplTypeLft, &aplNELMLft, &aplRankLft, NULL);
    AttrsOfToken (lptkRhtArg, &aplTypeRht, &aplNELMRht, &aplRankRht, NULL);

    // Get left and right arg's global ptrs
    GetGlbPtrs_LOCK (lptkLftArg, &hGlbLft, &lpMemLft);
    GetGlbPtrs_LOCK (lptkRhtArg, &hGlbRht, &lpMemRht);

    // Check for RANK ERROR
    if (IsMultiRank (aplRankLft))
        goto RANK_EXIT;

    // Check for LENGTH ERROR
    if (aplNELMLft NE aplRankRht)
        goto LENGTH_EXIT;

    // Treat the left arg as an axis
    if (!CheckAxis_EM (lptkLftArg,      // The "axis" token
                       aplRankRht,      // All values less than this
                       FALSE,           // TRUE iff scalar or one-element vector only
                       FALSE,           // TRUE iff want sorted axes
                       TRUE,            // TRUE iff axes must be contiguous
                       TRUE,            // TRUE iff duplicate axes are allowed
                       NULL,            // TRUE iff fractional values allowed
                      &aplRankRes,      // Return last axis value
                       NULL,            // Return # elements in axis vector
                      &hGlbAxis))       // Return HGLOBAL with APLUINT axis values
        goto DOMAIN_EXIT;

    // Map APA right arg to INT result
    if (IsSimpleAPA (aplTypeRht))
        aplTypeRes = ARRAY_INT;
    else
        aplTypeRes = aplTypeRht;

    // Strip out the simple scalar right argument case
    if (IsScalar (aplRankRht) && IsSimpleNH (aplTypeRes))
    {
        // Allocate a new YYRes
        lpYYRes = YYAlloc ();

        // Split cases based upon the right arg's token type
        switch (lptkRhtArg->tkFlags.TknType)
        {
            case TKT_VARNAMED:
                // tkData is an LPSYMENTRY
                Assert (GetPtrTypeDir (lptkRhtArg->tkData.tkVoid) EQ PTRTYPE_STCONST);

                // If it's not immediate, we must look inside the array
                if (!lptkRhtArg->tkData.tkSym->stFlags.Imm)
                {
                    // stData is a valid HGLOBAL variable array
                    Assert (IsGlbTypeVarDir_PTB (lptkRhtArg->tkData.tkSym->stData.stGlbData));
#ifdef DEBUG
                    // If we ever get here, we must have missed a type demotion
                    DbgStop ();             // #ifdef DEBUG
#endif
                } // End IF

                // Handle the immediate case

                // Fill in the result token
                lpYYRes->tkToken.tkFlags.TknType   = TKT_VARIMMED;
                lpYYRes->tkToken.tkFlags.ImmType   = lptkRhtArg->tkData.tkSym->stFlags.ImmType;
////////////////lpYYRes->tkToken.tkFlags.NoDisplay = FALSE; // Already zero from YYAlloc
                lpYYRes->tkToken.tkData.tkLongest  = lptkRhtArg->tkData.tkSym->stData.stLongest;
                lpYYRes->tkToken.tkCharIndex       = lptkFunc->tkCharIndex;

                break;

            case TKT_VARIMMED:
                // Fill in the result token
                lpYYRes->tkToken = *lptkRhtArg;

                break;

            defstop
                break;
        } // End SWITCH

        goto NORMAL_EXIT;
    } // End IF
Beispiel #19
0
// Generate an accessor struct, builder structs & function for a table.
static void GenTable(StructDef &struct_def, std::string *code_ptr) {
  if (struct_def.generated) return;
  std::string &code = *code_ptr;

  // Generate an accessor struct, with methods of the form:
  // type name() const { return GetField<type>(offset, defaultval); }
  GenComment(struct_def.doc_comment, code_ptr);
  code += "struct " + struct_def.name + " : private flatbuffers::Table";
  code += " {\n";
  for (auto it = struct_def.fields.vec.begin();
       it != struct_def.fields.vec.end();
       ++it) {
    auto &field = **it;
    if (!field.deprecated) {  // Deprecated fields won't be accessible.
      GenComment(field.doc_comment, code_ptr, "  ");
      code += "  " + GenTypeGet(field.value.type, " ", "const ", " *");
      code += field.name + "() const { return ";
      // Call a different accessor for pointers, that indirects.
      code += IsScalar(field.value.type.base_type)
        ? "GetField<"
        : (IsStruct(field.value.type) ? "GetStruct<" : "GetPointer<");
      code += GenTypeGet(field.value.type, "", "const ", " *") + ">(";
      code += NumToString(field.value.offset);
      // Default value as second arg for non-pointer types.
      if (IsScalar(field.value.type.base_type))
        code += ", " + field.value.constant;
      code += "); }\n";
    }
  }
  // Generate a verifier function that can check a buffer from an untrusted
  // source will never cause reads outside the buffer.
  code += "  bool Verify(const flatbuffers::Verifier &verifier) const {\n";
  code += "    return VerifyTable(verifier)";
  std::string prefix = " &&\n           ";
  for (auto it = struct_def.fields.vec.begin();
       it != struct_def.fields.vec.end();
       ++it) {
    auto &field = **it;
    if (!field.deprecated) {
      code += prefix + "VerifyField<" + GenTypeSize(field.value.type);
      code += ">(verifier, " + NumToString(field.value.offset);
      code += " /* " + field.name + " */)";
      switch (field.value.type.base_type) {
        case BASE_TYPE_UNION:
          code += prefix + "Verify" + field.value.type.enum_def->name;
          code += "(verifier, " + field.name + "(), " + field.name + "_type())";
          break;
        case BASE_TYPE_STRUCT:
          if (!field.value.type.struct_def->fixed) {
            code += prefix + "verifier.VerifyTable(" + field.name;
            code += "())";
          }
          break;
        case BASE_TYPE_STRING:
          code += prefix + "verifier.Verify(" + field.name + "())";
          break;
        case BASE_TYPE_VECTOR:
          code += prefix + "verifier.Verify(" + field.name + "())";
          switch (field.value.type.element) {
            case BASE_TYPE_STRING: {
              code += prefix + "verifier.VerifyVectorOfStrings(" + field.name;
              code += "())";
              break;
            }
            case BASE_TYPE_STRUCT: {
              if (!field.value.type.struct_def->fixed) {
                code += prefix + "verifier.VerifyVectorOfTables(" + field.name;
                code += "())";
              }
              break;
            }
            default:
              break;
          }
          break;
        default:
          break;
      }
    }
  }
  code += ";\n  }\n";
  code += "};\n\n";

  // Generate a builder struct, with methods of the form:
  // void add_name(type name) { fbb_.AddElement<type>(offset, name, default); }
  code += "struct " + struct_def.name;
  code += "Builder {\n  flatbuffers::FlatBufferBuilder &fbb_;\n";
  code += "  flatbuffers::uoffset_t start_;\n";
  for (auto it = struct_def.fields.vec.begin();
       it != struct_def.fields.vec.end();
       ++it) {
    auto &field = **it;
    if (!field.deprecated) {
      code += "  void add_" + field.name + "(";
      code += GenTypeWire(field.value.type, " ") + field.name + ") { fbb_.Add";
      if (IsScalar(field.value.type.base_type))
        code += "Element<" + GenTypeWire(field.value.type, "") + ">";
      else if (IsStruct(field.value.type))
        code += "Struct";
      else
        code += "Offset";
      code += "(" + NumToString(field.value.offset) + ", " + field.name;
      if (IsScalar(field.value.type.base_type))
        code += ", " + field.value.constant;
      code += "); }\n";
    }
  }
  code += "  " + struct_def.name;
  code += "Builder(flatbuffers::FlatBufferBuilder &_fbb) : fbb_(_fbb) ";
  code += "{ start_ = fbb_.StartTable(); }\n";
  code += "  " + struct_def.name + "Builder &operator=(const ";
  code += struct_def.name + "Builder &);\n";
  code += "  flatbuffers::Offset<" + struct_def.name;
  code += "> Finish() { return flatbuffers::Offset<" + struct_def.name;
  code += ">(fbb_.EndTable(start_, ";
  code += NumToString(struct_def.fields.vec.size()) + ")); }\n};\n\n";

  // Generate a convenient CreateX function that uses the above builder
  // to create a table in one go.
  code += "inline flatbuffers::Offset<" + struct_def.name + "> Create";
  code += struct_def.name;
  code += "(flatbuffers::FlatBufferBuilder &_fbb";
  for (auto it = struct_def.fields.vec.begin();
       it != struct_def.fields.vec.end();
       ++it) {
    auto &field = **it;
    if (!field.deprecated) {
      code += ", " + GenTypeWire(field.value.type, " ") + field.name;
    }
  }
  code += ") {\n  " + struct_def.name + "Builder builder_(_fbb);\n";
  for (size_t size = struct_def.sortbysize ? sizeof(largest_scalar_t) : 1;
       size;
       size /= 2) {
    for (auto it = struct_def.fields.vec.rbegin();
         it != struct_def.fields.vec.rend();
         ++it) {
      auto &field = **it;
      if (!field.deprecated &&
          (!struct_def.sortbysize ||
           size == SizeOf(field.value.type.base_type))) {
        code += "  builder_.add_" + field.name + "(" + field.name + ");\n";
      }
    }
  }
  code += "  return builder_.Finish();\n}\n\n";
}
Beispiel #20
0
// Generate an accessor struct with constructor for a flatbuffers struct.
static void GenStruct(StructDef &struct_def, std::string *code_ptr) {
  if (struct_def.generated) return;
  std::string &code = *code_ptr;

  // Generate an accessor struct, with private variables of the form:
  // type name_;
  // Generates manual padding and alignment.
  // Variables are private because they contain little endian data on all
  // platforms.
  GenComment(struct_def.doc_comment, code_ptr);
  code += "MANUALLY_ALIGNED_STRUCT(" + NumToString(struct_def.minalign) + ") ";
  code += struct_def.name + " {\n private:\n";
  int padding_id = 0;
  for (auto it = struct_def.fields.vec.begin();
       it != struct_def.fields.vec.end();
       ++it) {
    auto &field = **it;
    code += "  " + GenTypeGet(field.value.type, " ", "", " ");
    code += field.name + "_;\n";
    if (field.padding) {
      for (int i = 0; i < 4; i++)
        if (static_cast<int>(field.padding) & (1 << i))
          code += "  int" + NumToString((1 << i) * 8) +
                  "_t __padding" + NumToString(padding_id++) + ";\n";
      assert(!(field.padding & ~0xF));
    }
  }

  // Generate a constructor that takes all fields as arguments.
  code += "\n public:\n  " + struct_def.name + "(";
  for (auto it = struct_def.fields.vec.begin();
       it != struct_def.fields.vec.end();
       ++it) {
    auto &field = **it;
    if (it != struct_def.fields.vec.begin()) code += ", ";
    code += GenTypeGet(field.value.type, " ", "const ", " &") + field.name;
  }
  code += ")\n    : ";
  padding_id = 0;
  for (auto it = struct_def.fields.vec.begin();
       it != struct_def.fields.vec.end();
       ++it) {
    auto &field = **it;
    if (it != struct_def.fields.vec.begin()) code += ", ";
    code += field.name + "_(";
    if (IsScalar(field.value.type.base_type))
      code += "flatbuffers::EndianScalar(" + field.name + "))";
    else
      code += field.name + ")";
    if (field.padding)
      code += ", __padding" + NumToString(padding_id++) + "(0)";
  }
  code += " {}\n\n";

  // Generate accessor methods of the form:
  // type name() const { return flatbuffers::EndianScalar(name_); }
  for (auto it = struct_def.fields.vec.begin();
       it != struct_def.fields.vec.end();
       ++it) {
    auto &field = **it;
    GenComment(field.doc_comment, code_ptr, "  ");
    code += "  " + GenTypeGet(field.value.type, " ", "const ", " &");
    code += field.name + "() const { return ";
    if (IsScalar(field.value.type.base_type))
      code += "flatbuffers::EndianScalar(" + field.name + "_)";
    else
      code += field.name + "_";
    code += "; }\n";
  }
  code += "};\nSTRUCT_END(" + struct_def.name + ", ";
  code += NumToString(struct_def.bytesize) + ");\n\n";
}
Beispiel #21
0
int commonarraysyntax(int &lexpos, int &lineno, int &arraynameid,
                      int &nindex, int indexarray[])
{
    int noerrorlocal=1;

    if (IsScalar(lexpos))
    {
        nindex=0;
        return scalarsyntax(lexpos, arraynameid);
    }

    if (id==outArray[lexpos])
    {
        arraynameid=idnosyn++;
        lexmovenext(lexpos);
    }
    else
    {
        outerror(lineno, "Arrayname is missing.");
        noerrorlocal=0;
    }

    if (lparen!=outArray[lexpos])
    {
        nindex=0;
        return noerrorlocal;
/*        outerror(lineno, "Array ( is missing.");//idname[arraynameid]
        noerrorlocal=0;*/
    }
    else
        lexmovenext(lexpos);

    nindex=0;
    while (id==outArray[lexpos] && !endofoutArray)
    {
        if (nindex<mx_array_dim)
        {
            indexarray[nindex]=idnosyn;
        }

        nindex++;

        idnosyn++;
        lexmovenext(lexpos);

        if (comma==outArray[lexpos])
            lexmovenext(lexpos);
        else if (rparen==outArray[lexpos])
        {
            lexmovenext(lexpos);
            break;
        }
        else
        {
            outerror(lineno, "error in array declaration.");
            noerrorlocal=0;
            break;
        }
    }

    if (nindex>mx_array_dim)
    {
        outerror(lineno, "Warning: Too many indices detected.");
        printf("Only the first %d are used.\n", mx_array_dim);
        printf("%d=nindex\n", nindex);
        printf("%s\n", idname[arraynameid].c_str());
        for (int i=arraynameid+1; i<idnosyn; i++)
            printf("%s, ", idname[i].c_str());
        printf("\n");
        noerrorlocal=0;
        nindex=mx_array_dim;
    }
    return noerrorlocal;
}
Beispiel #22
0
// Return a C++ type for any type (scalar/pointer) specifically for
// using a flatbuffer.
static std::string GenTypeGet(const Type &type, const char *afterbasic,
                              const char *beforeptr, const char *afterptr) {
  return IsScalar(type.base_type)
    ? GenTypeBasic(type) + afterbasic
    : beforeptr + GenTypePointer(type) + afterptr;
}
Beispiel #23
0
static void GenStruct(StructDef &struct_def,
                      std::string *code_ptr,
                      StructDef *root_struct_def) {
  if (struct_def.generated) return;
  std::string &code = *code_ptr;

  // Generate a struct accessor class, with methods of the form:
  // public type name() { return bb.getType(i + offset); }
  // or for tables of the form:
  // public type name() {
  //   int o = __offset(offset); return o != 0 ? bb.getType(o + i) : default;
  // }
  GenComment(struct_def.doc_comment, code_ptr);
  code += "public class " + struct_def.name + " extends ";
  code += struct_def.fixed ? "Struct" : "Table";
  code += " {\n";
  if (&struct_def == root_struct_def) {
    // Generate a special accessor for the table that has been declared as
    // the root type.
    code += "  public static " + struct_def.name + " getRootAs";
    code += struct_def.name;
    code += "(ByteBuffer _bb, int offset) { ";
    code += "_bb.order(ByteOrder.LITTLE_ENDIAN); ";
    code += "return (new " + struct_def.name;
    code += "()).__init(_bb.getInt(offset) + offset, _bb); }\n";
  }
  // Generate the __init method that sets the field in a pre-existing
  // accessor object. This is to allow object reuse.
  code += "  public " + struct_def.name;
  code += " __init(int _i, ByteBuffer _bb) ";
  code += "{ bb_pos = _i; bb = _bb; return this; }\n";
  for (auto it = struct_def.fields.vec.begin();
       it != struct_def.fields.vec.end();
       ++it) {
    auto &field = **it;
    if (field.deprecated) continue;
    GenComment(field.doc_comment, code_ptr, "  ");
    std::string type_name = GenTypeGet(field.value.type);
    std::string method_start = "  public " + type_name + " " +
                               MakeCamel(field.name, false);
    // Generate the accessors that don't do object reuse.
    if (field.value.type.base_type == BASE_TYPE_STRUCT) {
      // Calls the accessor that takes an accessor object with a new object.
      code += method_start + "() { return " + MakeCamel(field.name, false);
      code += "(new ";
      code += type_name + "()); }\n";
    } else if (field.value.type.base_type == BASE_TYPE_VECTOR &&
               field.value.type.element == BASE_TYPE_STRUCT) {
      // Accessors for vectors of structs also take accessor objects, this
      // generates a variant without that argument.
      code += method_start + "(int j) { return " + MakeCamel(field.name, false);
      code += "(new ";
      code += type_name + "(), j); }\n";
    }
    std::string getter = GenGetter(field.value.type);
    code += method_start + "(";
    // Most field accessors need to retrieve and test the field offset first,
    // this is the prefix code for that:
    auto offset_prefix = ") { int o = __offset(" +
                         NumToString(field.value.offset) +
                         "); return o != 0 ? ";
    if (IsScalar(field.value.type.base_type)) {
      if (struct_def.fixed) {
        code += ") { return " + getter;
        code += "(bb_pos + " + NumToString(field.value.offset) + ")";
      } else {
        code += offset_prefix + getter;
        code += "(o + bb_pos) : " + field.value.constant;
      }
    } else {
      switch (field.value.type.base_type) {
        case BASE_TYPE_STRUCT:
          code += type_name + " obj";
          if (struct_def.fixed) {
            code += ") { return obj.__init(bb_pos + ";
            code += NumToString(field.value.offset) + ", bb)";
          } else {
            code += offset_prefix;
            code += "obj.__init(";
            code += field.value.type.struct_def->fixed
                      ? "o + bb_pos"
                      : "__indirect(o + bb_pos)";
            code += ", bb) : null";
          }
          break;
        case BASE_TYPE_STRING:
          code += offset_prefix + getter +"(o) : null";
          break;
        case BASE_TYPE_VECTOR: {
          auto vectortype = field.value.type.VectorType();
          if (vectortype.base_type == BASE_TYPE_STRUCT) {
            code += type_name + " obj, ";
            getter = "obj.__init";
          }
          code += "int j" + offset_prefix + getter +"(";
          auto index = "__vector(o) + j * " +
                       NumToString(InlineSize(vectortype));
          if (vectortype.base_type == BASE_TYPE_STRUCT) {
            code += vectortype.struct_def->fixed
                      ? index
                      : "__indirect(" + index + ")";
            code += ", bb";
          } else {
            code += index;
          }
          code += ") : ";
          code += IsScalar(field.value.type.element) ? "0" : "null";
          break;
        }
        case BASE_TYPE_UNION:
          code += type_name + " obj" + offset_prefix + getter;
          code += "(obj, o) : null";
          break;
        default:
          assert(0);
      }
    }
    code += "; }\n";
    if (field.value.type.base_type == BASE_TYPE_VECTOR) {
      code += "  public int " + MakeCamel(field.name, false) + "Length(";
      code += offset_prefix;
      code += "__vector_len(o) : 0; }\n";
    }
  }
  code += "\n";
  if (struct_def.fixed) {
    // create a struct constructor function
    code += "  public static int create" + struct_def.name;
    code += "(FlatBufferBuilder builder";
    GenStructArgs(struct_def, code_ptr, "");
    code += ") {\n";
    GenStructBody(struct_def, code_ptr, "");
    code += "    return builder.offset();\n  }\n";
  } else {
    // Create a set of static methods that allow table construction,
    // of the form:
    // public static void addName(FlatBufferBuilder builder, short name)
    // { builder.addShort(id, name, default); }
    code += "  public static void start" + struct_def.name;
    code += "(FlatBufferBuilder builder) { builder.startObject(";
    code += NumToString(struct_def.fields.vec.size()) + "); }\n";
    for (auto it = struct_def.fields.vec.begin();
         it != struct_def.fields.vec.end();
         ++it) {
      auto &field = **it;
      if (field.deprecated) continue;
      code += "  public static void add" + MakeCamel(field.name);
      code += "(FlatBufferBuilder builder, " + GenTypeBasic(field.value.type);
      auto argname = MakeCamel(field.name, false);
      if (!IsScalar(field.value.type.base_type)) argname += "Offset";
      code += " " + argname + ") { builder.add";
      code += GenMethod(field) + "(";
      code += NumToString(it - struct_def.fields.vec.begin()) + ", ";
      code += argname + ", " + field.value.constant;
      code += "); }\n";
      if (field.value.type.base_type == BASE_TYPE_VECTOR) {
        code += "  public static void start" + MakeCamel(field.name);
        code += "Vector(FlatBufferBuilder builder, int numElems) ";
        code += "{ builder.startVector(";
        code += NumToString(InlineSize(field.value.type.VectorType()));
        code += ", numElems); }\n";
      }
    }
    code += "  public static int end" + struct_def.name;
    code += "(FlatBufferBuilder builder) { return builder.endObject(); }\n";
  }
  code += "};\n\n";
}
Beispiel #24
0
// Generate an accessor struct with constructor for a flatbuffers struct.
static void GenStruct(const Parser &parser, StructDef &struct_def,
                      std::string *code_ptr) {
  if (struct_def.generated) return;
  std::string &code = *code_ptr;

  // Generate an accessor struct, with private variables of the form:
  // type name_;
  // Generates manual padding and alignment.
  // Variables are private because they contain little endian data on all
  // platforms.
  GenComment(struct_def.doc_comment, code_ptr);
  code += "MANUALLY_ALIGNED_STRUCT(" + NumToString(struct_def.minalign) + ") ";
  code += struct_def.name + " FLATBUFFERS_FINAL_CLASS {\n private:\n";
  int padding_id = 0;
  for (auto it = struct_def.fields.vec.begin();
       it != struct_def.fields.vec.end();
       ++it) {
    auto &field = **it;
    code += "  " + GenTypeGet(parser, field.value.type, " ", "", " ", false);
    code += field.name + "_;\n";
    GenPadding(field, [&code, &padding_id](int bits) {
      code += "  int" + NumToString(bits) +
              "_t __padding" + NumToString(padding_id++) + ";\n";
    });
  }

  // Generate a constructor that takes all fields as arguments.
  code += "\n public:\n  " + struct_def.name + "(";
  for (auto it = struct_def.fields.vec.begin();
       it != struct_def.fields.vec.end();
       ++it) {
    auto &field = **it;
    if (it != struct_def.fields.vec.begin()) code += ", ";
    code += GenTypeGet(parser, field.value.type, " ", "const ", " &", true);
    code += field.name;
  }
  code += ")\n    : ";
  padding_id = 0;
  for (auto it = struct_def.fields.vec.begin();
       it != struct_def.fields.vec.end();
       ++it) {
    auto &field = **it;
    if (it != struct_def.fields.vec.begin()) code += ", ";
    code += field.name + "_(";
    if (IsScalar(field.value.type.base_type)) {
      code += "flatbuffers::EndianScalar(";
      code += GenUnderlyingCast(parser, field, false, field.name);
      code += "))";
    } else {
      code += field.name + ")";
    }
    GenPadding(field, [&code, &padding_id](int bits) {
      (void)bits;
      code += ", __padding" + NumToString(padding_id++) + "(0)";
    });
  }
  code += " {";
  padding_id = 0;
  for (auto it = struct_def.fields.vec.begin();
       it != struct_def.fields.vec.end();
       ++it) {
    auto &field = **it;
    GenPadding(field, [&code, &padding_id](int bits) {
      (void)bits;
      code += " (void)__padding" + NumToString(padding_id++) + ";";
    });
  }
  code += " }\n\n";

  // Generate accessor methods of the form:
  // type name() const { return flatbuffers::EndianScalar(name_); }
  for (auto it = struct_def.fields.vec.begin();
       it != struct_def.fields.vec.end();
       ++it) {
    auto &field = **it;
    GenComment(field.doc_comment, code_ptr, "  ");
    code += "  " + GenTypeGet(parser, field.value.type, " ", "const ", " &",
                              true);
    code += field.name + "() const { return ";
    code += GenUnderlyingCast(parser, field, true,
      IsScalar(field.value.type.base_type)
        ? "flatbuffers::EndianScalar(" + field.name + "_)"
        : field.name + "_");
    code += "; }\n";
  }
  code += "};\nSTRUCT_END(" + struct_def.name + ", ";
  code += NumToString(struct_def.bytesize) + ");\n\n";
}
Beispiel #25
0
// Generate an accessor struct, builder structs & function for a table.
static void GenTable(const Parser &parser, StructDef &struct_def,
                     const GeneratorOptions &opts, std::string *code_ptr) {
  if (struct_def.generated) return;
  std::string &code = *code_ptr;

  // Generate an accessor struct, with methods of the form:
  // type name() const { return GetField<type>(offset, defaultval); }
  GenComment(struct_def.doc_comment, code_ptr);
  code += "struct " + struct_def.name;
  code += " FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table";
  code += " {\n";
  for (auto it = struct_def.fields.vec.begin();
       it != struct_def.fields.vec.end();
       ++it) {
    auto &field = **it;
    if (!field.deprecated) {  // Deprecated fields won't be accessible.
      GenComment(field.doc_comment, code_ptr, "  ");
      code += "  " + GenTypeGet(parser, field.value.type, " ", "const ", " *",
                                true);
      code += field.name + "() const { return ";
      // Call a different accessor for pointers, that indirects.
      std::string call = IsScalar(field.value.type.base_type)
        ? "GetField<"
        : (IsStruct(field.value.type) ? "GetStruct<" : "GetPointer<");
      call += GenTypeGet(parser, field.value.type, "", "const ", " *", false);
      call += ">(" + NumToString(field.value.offset);
      // Default value as second arg for non-pointer types.
      if (IsScalar(field.value.type.base_type))
        call += ", " + field.value.constant;
      call += ")";
      code += GenUnderlyingCast(parser, field, true, call);
      code += "; }\n";
      auto nested = field.attributes.Lookup("nested_flatbuffer");
      if (nested) {
        auto nested_root = parser.structs_.Lookup(nested->constant);
        assert(nested_root);  // Guaranteed to exist by parser.
        code += "  const " + nested_root->name + " *" + field.name;
        code += "_nested_root() const { return flatbuffers::GetRoot<";
        code += nested_root->name + ">(" + field.name + "()->Data()); }\n";
      }
      // Generate a comparison function for this field if it is a key.
      if (field.key) {
        code += "  bool KeyCompareLessThan(const " + struct_def.name;
        code += " *o) const { return ";
        if (field.value.type.base_type == BASE_TYPE_STRING) code += "*";
        code += field.name + "() < ";
        if (field.value.type.base_type == BASE_TYPE_STRING) code += "*";
        code += "o->" + field.name + "(); }\n";
        code += "  int KeyCompareWithValue(";
        if (field.value.type.base_type == BASE_TYPE_STRING) {
          code += "const char *val) const { return strcmp(" + field.name;
          code += "()->c_str(), val); }\n";
        } else {
          code += GenTypeBasic(parser, field.value.type, false);
          code += " val) const { return " + field.name + "() < val ? -1 : ";
          code += field.name + "() > val; }\n";
        }
      }
    }
  }
  // Generate a verifier function that can check a buffer from an untrusted
  // source will never cause reads outside the buffer.
  code += "  bool Verify(flatbuffers::Verifier &verifier) const {\n";
  code += "    return VerifyTableStart(verifier)";
  std::string prefix = " &&\n           ";
  for (auto it = struct_def.fields.vec.begin();
       it != struct_def.fields.vec.end();
       ++it) {
    auto &field = **it;
    if (!field.deprecated) {
      code += prefix + "VerifyField";
      if (field.required) code += "Required";
      code += "<" + GenTypeSize(parser, field.value.type);
      code += ">(verifier, " + NumToString(field.value.offset);
      code += " /* " + field.name + " */)";
      switch (field.value.type.base_type) {
        case BASE_TYPE_UNION:
          code += prefix + "Verify" + field.value.type.enum_def->name;
          code += "(verifier, " + field.name + "(), " + field.name + "_type())";
          break;
        case BASE_TYPE_STRUCT:
          if (!field.value.type.struct_def->fixed) {
            code += prefix + "verifier.VerifyTable(" + field.name;
            code += "())";
          }
          break;
        case BASE_TYPE_STRING:
          code += prefix + "verifier.Verify(" + field.name + "())";
          break;
        case BASE_TYPE_VECTOR:
          code += prefix + "verifier.Verify(" + field.name + "())";
          switch (field.value.type.element) {
            case BASE_TYPE_STRING: {
              code += prefix + "verifier.VerifyVectorOfStrings(" + field.name;
              code += "())";
              break;
            }
            case BASE_TYPE_STRUCT: {
              if (!field.value.type.struct_def->fixed) {
                code += prefix + "verifier.VerifyVectorOfTables(" + field.name;
                code += "())";
              }
              break;
            }
            default:
              break;
          }
          break;
        default:
          break;
      }
    }
  }
  code += prefix + "verifier.EndTable()";
  code += ";\n  }\n";
  code += "};\n\n";

  // Generate a builder struct, with methods of the form:
  // void add_name(type name) { fbb_.AddElement<type>(offset, name, default); }
  code += "struct " + struct_def.name;
  code += "Builder {\n  flatbuffers::FlatBufferBuilder &fbb_;\n";
  code += "  flatbuffers::uoffset_t start_;\n";
  for (auto it = struct_def.fields.vec.begin();
       it != struct_def.fields.vec.end();
       ++it) {
    auto &field = **it;
    if (!field.deprecated) {
      code += "  void add_" + field.name + "(";
      code += GenTypeWire(parser, field.value.type, " ", true) + field.name;
      code += ") { fbb_.Add";
      if (IsScalar(field.value.type.base_type)) {
        code += "Element<" + GenTypeWire(parser, field.value.type, "", false);
        code += ">";
      } else if (IsStruct(field.value.type)) {
        code += "Struct";
      } else {
        code += "Offset";
      }
      code += "(" + NumToString(field.value.offset) + ", ";
      code += GenUnderlyingCast(parser, field, false, field.name);
      if (IsScalar(field.value.type.base_type))
        code += ", " + field.value.constant;
      code += "); }\n";
    }
  }
  code += "  " + struct_def.name;
  code += "Builder(flatbuffers::FlatBufferBuilder &_fbb) : fbb_(_fbb) ";
  code += "{ start_ = fbb_.StartTable(); }\n";
  code += "  " + struct_def.name + "Builder &operator=(const ";
  code += struct_def.name + "Builder &);\n";
  code += "  flatbuffers::Offset<" + struct_def.name;
  code += "> Finish() {\n    auto o = flatbuffers::Offset<" + struct_def.name;
  code += ">(fbb_.EndTable(start_, ";
  code += NumToString(struct_def.fields.vec.size()) + "));\n";
  for (auto it = struct_def.fields.vec.begin();
       it != struct_def.fields.vec.end();
       ++it) {
    auto &field = **it;
    if (!field.deprecated && field.required) {
      code += "    fbb_.Required(o, " + NumToString(field.value.offset);
      code += ");  // " + field.name + "\n";
    }
  }
  code += "    return o;\n  }\n};\n\n";

  // Generate a convenient CreateX function that uses the above builder
  // to create a table in one go.
  code += "inline flatbuffers::Offset<" + struct_def.name + "> Create";
  code += struct_def.name;
  code += "(flatbuffers::FlatBufferBuilder &_fbb";
  for (auto it = struct_def.fields.vec.begin();
       it != struct_def.fields.vec.end();
       ++it) {
    auto &field = **it;
    if (!field.deprecated) {
      code += ",\n   " + GenTypeWire(parser, field.value.type, " ", true);
      code += field.name + " = ";
      if (field.value.type.enum_def && IsScalar(field.value.type.base_type)) {
        auto ev = field.value.type.enum_def->ReverseLookup(
           static_cast<int>(StringToInt(field.value.constant.c_str())), false);
        if (ev) {
          code += WrapInNameSpace(parser,
                                  field.value.type.enum_def->defined_namespace,
                                  GenEnumVal(*field.value.type.enum_def, *ev,
                                             opts));
        } else {
          code += GenUnderlyingCast(parser, field, true, field.value.constant);
        }
      } else {
        code += field.value.constant;
      }
    }
  }
  code += ") {\n  " + struct_def.name + "Builder builder_(_fbb);\n";
  for (size_t size = struct_def.sortbysize ? sizeof(largest_scalar_t) : 1;
       size;
       size /= 2) {
    for (auto it = struct_def.fields.vec.rbegin();
         it != struct_def.fields.vec.rend();
         ++it) {
      auto &field = **it;
      if (!field.deprecated &&
          (!struct_def.sortbysize ||
           size == SizeOf(field.value.type.base_type))) {
        code += "  builder_.add_" + field.name + "(" + field.name + ");\n";
      }
    }
  }
  code += "  return builder_.Finish();\n}\n\n";
}
Beispiel #26
0
//
// Set the value of this according to the value parsed from s.
// Return true on success, false on failure.
// On successful return, index points to the character following the
// the last character in the successfully parsed value found in s.
// On failure, index is unchanged.
//
bool
DXTensor::setValue(const char *s, int& index)
{
    int j;
    int components = 0;
    int ndim = 1, loc_index = index;
    char c;
    bool saw_value = false, saw_right_bracket = false;
    bool saw_scalar =  false;
    DXTensor *subv = NUL(DXTensor*); 
    
    SkipWhiteSpace(s,loc_index);

    if (s[loc_index] != '[')
	return false;
    loc_index++;

    while (s[loc_index]) {
    	SkipWhiteSpace(s,loc_index);
 	c = s[loc_index];
	if (c == '[') {
	    /* Vectors are not allowed if we already saw a scalar  */
	    if (saw_scalar)
		goto error;
	    subv = new DXTensor;
	    if (!subv->setValue(s, loc_index)) {
		delete subv;
		goto error;
	    }
	    this->tensors = (DXTensor**)REALLOC(this->tensors,
					++components*sizeof(DXTensor*));
	    ASSERT(this->tensors);

	    this->tensors[components-1] = subv;
	    if (ndim == 1) {	/* First sub-component */
		/* Copy the sub-dimensions up to this vector */
		ndim += subv->dimensions;
		this->dim_sizes = (char*)REALLOC(this->dim_sizes, 
					ndim * sizeof(*dim_sizes));
		ASSERT(this->dim_sizes);
		for (j=0 ; j<subv->dimensions ; j++ )
		    this->dim_sizes[j+1] = subv->dim_sizes[j];
	    } else { 		
		/* Ensure that next elements have the correct dimensionality */
		if (subv->dimensions != ndim-1) {
		    delete subv;
		    goto error;
		}
		for (j=1 ; j<ndim ; j++) 
		    if (this->dim_sizes[j] != subv->dim_sizes[j-1]) {
			this->tensors[components-1] = NULL;
			delete subv;
			goto error;
		    }
	    }
	    saw_value = true;
	} else if (c == ']') {
	    if (saw_value == false)
		goto error;
	    saw_scalar = false;
	    saw_right_bracket = true;
	    loc_index++;
	    break;
	} else if (c == ',') {
	    if (!saw_value)	/* This checks for ',,' */
		goto error;
	    saw_value = false;
	    saw_scalar = false;
	    loc_index++;
	} else {
	    /* Scalars are not allowed if we already saw a sub-vector */
	    double val;
	    int matches, tmp = loc_index;
	    if (ndim != 1) goto error;
	    if (!IsScalar(s,tmp)) 
		goto error;

	    matches = sscanf(&s[loc_index],"%lg", &val);
	    if ((matches == 0) || (matches == EOF)) 
		goto error;
	    loc_index = tmp;

	    this->scalars =(double*)REALLOC(this->scalars,
				++components * sizeof(*scalars));
	    ASSERT(this->scalars);
	    this->scalars[components-1] = val;
	    saw_value = true;
	    saw_scalar = true;
	}
    }

    if ((components == 0) || !saw_right_bracket)
	goto error;

    /* Set the dimension at this level of brackets */
    if (!this->dim_sizes)
	this->dim_sizes = new char;
    this->dim_sizes[0] = components;
    this->dimensions = ndim;

    // Be sure that the string representation is cleared when the value changes.
    if (strval) {
	delete strval;
        this->strval = NUL(char*);
    }

    index = loc_index;
    return true;

error:
    return false;

}
Beispiel #27
0
static std::string GenTypeGet(const Type &type) {
  return IsScalar(type.base_type)
    ? GenTypeBasic(type)
    : GenTypePointer(type);
}
Beispiel #28
0
// Returns the method name for use with add/put calls.
static std::string GenMethod(const FieldDef &field) {
  return IsScalar(field.value.type.base_type)
    ? MakeCamel(GenTypeBasic(field.value.type))
    : (IsStruct(field.value.type) ? "Struct" : "UOffsetT");
}
Beispiel #29
0
 bool Type::CanImplicitCastToBool()
 {
     return IsScalar() || IsDArray() || IsSArray() || IsAArray() || IsDelegate();
 }