Пример #1
0
        /// <summary>
        /// Indicates if the given type model is a nullable reference in the given context.
        /// </summary>
        /// <param name="typeModel">The type model.</param>
        /// <param name="context">The context (ie, table, struct, vector, etc)</param>
        public static ContextualTypeModelClassification ClassifyContextually(this ITypeModel typeModel, FlatBufferSchemaType context)
        {
            var flags = ContextualTypeModelClassification.Undefined;

            if (typeModel.ClrType.IsValueType)
            {
                flags |= ContextualTypeModelClassification.ValueType;

                if (Nullable.GetUnderlyingType(typeModel.ClrType) == null)
                {
                    flags |= ContextualTypeModelClassification.Required;
                }
                else
                {
                    flags |= ContextualTypeModelClassification.Optional;
                }
            }
            else
            {
                flags |= ContextualTypeModelClassification.ReferenceType;

                if (context == FlatBufferSchemaType.Table)
                {
                    flags |= ContextualTypeModelClassification.Optional;
                }
                else
                {
                    flags |= ContextualTypeModelClassification.Required;
                }
            }

            return(flags);
        }
 public KitComponentModel(ICustomFieldModel customFieldModel, IBaseContextModel contextModel, ITypeModel typeModel, IExternalIdModel externalIdModel)
 {
     _customFieldModel = customFieldModel;
     _externalIdModel  = externalIdModel;
     _typeModel        = typeModel;
     context           = contextModel;
 }
Пример #3
0
        /// <summary>
        /// Attempts to resolve a type model from the given type.
        /// </summary>
        public bool TryCreateTypeModel(Type type, out ITypeModel typeModel)
        {
            if (this.cache.TryGetValue(type, out typeModel))
            {
                return(true);
            }

            foreach (var provider in this.providers)
            {
                if (provider.TryCreateTypeModel(this, type, out typeModel))
                {
                    break;
                }
            }

            if (typeModel != null)
            {
                this.cache[type] = typeModel;

                try
                {
                    typeModel.Initialize();
                    return(true);
                }
                catch
                {
                    this.cache.TryRemove(type, out _);
                    throw;
                }
            }
            else
            {
                return(false);
            }
        }
Пример #4
0
        private static void GenerateCloneMethod(
            CodeWriter codeWriter,
            CompilerOptions options,
            ITypeModel typeModel,
            Dictionary <Type, string> methodNameMap)
        {
            string typeName            = CSharpHelpers.GetCompilableTypeName(typeModel.ClrType);
            CodeGeneratedMethod method = typeModel.CreateCloneMethodBody(new CloneCodeGenContext("item", methodNameMap));

            if (!typeModel.ClrType.IsValueType)
            {
                typeName += "?";

                if (options.NullableWarnings == true)
                {
                    codeWriter.AppendLine("[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(\"item\")]");
                }
            }

            codeWriter.AppendLine(method.GetMethodImplAttribute());
            codeWriter.AppendLine($"public static {typeName} Clone({typeName} item)");
            using (codeWriter.WithBlock())
            {
                codeWriter.AppendLine(method.MethodBody);
            }
        }
    internal static string CreateParseBody(
        ITypeModel itemTypeModel,
        string createFlatBufferVector,
        ParserCodeGenContext context)
    {
        FlatSharpInternal.Assert(!string.IsNullOrEmpty(context.TableFieldContextVariableName), "expecting table field context");

        if (context.Options.GreedyDeserialize)
        {
            string body = $"({createFlatBufferVector}).FlatBufferVectorToList()";
            if (!context.Options.GenerateMutableObjects)
            {
                body += ".AsReadOnly()";
            }

            return($"return {body};");
        }
        else if (context.Options.Lazy)
        {
            return($"return {createFlatBufferVector};");
        }
        else
        {
            FlatSharpInternal.Assert(context.Options.Progressive, "expecting progressive");
            return($"return new FlatBufferProgressiveVector<{itemTypeModel.GetGlobalCompilableTypeName()}, {context.InputBufferTypeName}>({createFlatBufferVector});");
        }
    }
Пример #6
0
    public StructMemberModel(
        ITypeModel propertyModel,
        PropertyInfo propertyInfo,
        FlatBufferItemAttribute attribute,
        int offset,
        int length) : base(propertyModel, propertyInfo, attribute)
    {
        this.Offset = offset;
        this.Length = length;

        if (!this.IsVirtual && this.IsWriteThrough)
        {
            throw new InvalidFlatBufferDefinitionException($"Struct member '{this.FriendlyName}' declared the WriteThrough attribute, but WriteThrough is only supported on virtual fields.");
        }

        if (propertyModel.SerializeMethodRequiresContext)
        {
            throw new InvalidFlatBufferDefinitionException($"The type model for struct member '{this.FriendlyName}' requires a serialization context, but Structs do not have one.");
        }

        if (attribute.Required)
        {
            throw new InvalidFlatBufferDefinitionException($"Struct member '{this.FriendlyName}' declared the Required attribute. Required is not valid inside structs.");
        }

        if (attribute.SharedString)
        {
            throw new InvalidFlatBufferDefinitionException($"Struct member '{this.FriendlyName}' declared the SharedString attribute. SharedString is not valid inside structs.");
        }
    }
Пример #7
0
        private IEnumerable <Assignment> TranslateAssignments(
            ITypeModel variableModel,
            ITypeModel valueModel)
        {
            if (variableModel == null || valueModel == null || variableModel.AssignmentLeft.Count == 0)
            {
                Contract.Assert(valueModel == null || valueModel.AssignmentRight.Count == 0);

                yield break;
            }

            var variables = variableModel.AssignmentLeft;
            var values    = valueModel.AssignmentRight;

            Contract.Assert(variables.Count == values.Count);

            for (int i = 0; i < variables.Count; i++)
            {
                Contract.Assert(variables[i].Sort == values[i].Sort);

                var translatedVariable = this.TranslateVariable(variables[i]);
                var translatedValue    = this.TranslateExpression(values[i]);
                Contract.Assert(translatedVariable.Sort == variables[i].Sort);
                Contract.Assert(translatedVariable.Sort == translatedValue.Sort);

                yield return(new Assignment(translatedVariable, translatedValue));
            }
        }
Пример #8
0
    internal static void ValidateWriteThrough(
        bool writeThroughSupported,
        ITypeModel model,
        IReadOnlyDictionary <ITypeModel, List <TableFieldContext> > contexts,
        FlatBufferSerializerOptions options)
    {
        if (!contexts.TryGetValue(model, out var fieldsForModel))
        {
            return;
        }

        var firstWriteThrough = fieldsForModel.Where(x => x.WriteThrough).FirstOrDefault();

        if (firstWriteThrough is not null)
        {
            if (options.GreedyDeserialize)
            {
                throw new InvalidFlatBufferDefinitionException($"Field '{firstWriteThrough.FullName}' declares the WriteThrough option. WriteThrough is not supported when using Greedy deserialization.");
            }

            if (!writeThroughSupported)
            {
                throw new InvalidFlatBufferDefinitionException($"Field '{firstWriteThrough.FullName}' declares the WriteThrough option. WriteThrough is only supported for IList vectors.");
            }
        }
    }
Пример #9
0
 internal StructMemberModel(
     ITypeModel propertyModel,
     PropertyInfo propertyInfo,
     ushort index,
     int offset) : base(propertyModel, propertyInfo, index)
 {
     this.Offset = offset;
 }
Пример #10
0
        protected ItemMemberModel(
            ITypeModel propertyModel,
            PropertyInfo propertyInfo,
            FlatBufferItemAttribute attribute)
        {
            var getMethod = propertyInfo.GetMethod;
            var setMethod = propertyInfo.SetMethod;

            this.ItemTypeModel = propertyModel;
            this.PropertyInfo  = propertyInfo;
            this.Index         = attribute.Index;
            this.CustomGetter  = attribute.CustomGetter;

            string declaringType = "";

            if (propertyInfo.DeclaringType is not null)
            {
                declaringType = CSharpHelpers.GetCompilableTypeName(propertyInfo.DeclaringType);
            }

            declaringType = $"{declaringType}.{propertyInfo.Name} (Index {attribute.Index})";

            if (getMethod == null)
            {
                throw new InvalidFlatBufferDefinitionException($"Property {declaringType} on did not declare a getter.");
            }

            if (!getMethod.IsPublic && string.IsNullOrEmpty(this.CustomGetter))
            {
                throw new InvalidFlatBufferDefinitionException($"Property {declaringType} must declare a public getter.");
            }

            if (CanBeOverridden(getMethod))
            {
                this.IsVirtual = true;
                if (!ValidateVirtualPropertyMethod(getMethod, false))
                {
                    throw new InvalidFlatBufferDefinitionException($"Property {declaringType} did not declare a public/protected virtual getter.");
                }

                if (!ValidateVirtualPropertyMethod(setMethod, true))
                {
                    throw new InvalidFlatBufferDefinitionException($"Property {declaringType} declared a set method, but it was not public/protected and virtual.");
                }
            }
            else
            {
                if (!ValidateNonVirtualMethod(getMethod))
                {
                    throw new InvalidFlatBufferDefinitionException($"Non-virtual property {declaringType} must declare a public and non-abstract getter.");
                }

                if (!ValidateNonVirtualMethod(setMethod))
                {
                    throw new InvalidFlatBufferDefinitionException($"Non-virtual property {declaringType} must declare a public/protected and non-abstract setter.");
                }
            }
        }
Пример #11
0
        private string convertToClientType(ITypeModel type, string source, string target, int level = 0)
        {
            if (type == null)
            {
                return(target + " = " + source + ";");
            }

            IndentedStringBuilder builder = new IndentedStringBuilder();

            SequenceTypeModel   sequenceType   = type as SequenceTypeModel;
            DictionaryTypeModel dictionaryType = type as DictionaryTypeModel;

            if (sequenceType != null)
            {
                var elementType = sequenceType.ElementTypeModel;
                var itemName    = string.Format(CultureInfo.InvariantCulture, "item{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture));
                var itemTarget  = string.Format(CultureInfo.InvariantCulture, "value{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture));
                builder.AppendLine("{0} = new ArrayList<{1}>();", target, elementType.ResponseVariant.Name)
                .AppendLine("for ({0} {1} : {2}) {{", elementType.Name, itemName, source)
                .Indent().AppendLine("{0} {1};", elementType.ResponseVariant.Name, itemTarget)
                .AppendLine(convertToClientType(elementType, itemName, itemTarget, level + 1))
                .AppendLine("{0}.add({1});", target, itemTarget)
                .Outdent().Append("}");
                _implImports.Add("java.util.ArrayList");
                return(builder.ToString());
            }
            else if (dictionaryType != null)
            {
                var valueType  = dictionaryType.ValueTypeModel;
                var itemName   = string.Format(CultureInfo.InvariantCulture, "entry{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture));
                var itemTarget = string.Format(CultureInfo.InvariantCulture, "value{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture));
                builder.AppendLine("{0} = new HashMap<String, {1}>();", target, valueType.ResponseVariant.Name)
                .AppendLine("for (Map.Entry<String, {0}> {1} : {2}.entrySet()) {{", valueType.Name, itemName, source)
                .Indent().AppendLine("{0} {1};", valueType.ResponseVariant.Name, itemTarget)
                .AppendLine(convertToClientType(valueType, itemName + ".getValue()", itemTarget, level + 1))
                .AppendLine("{0}.put({1}.getKey(), {2});", target, itemName, itemTarget)
                .Outdent().Append("}");
                _implImports.Add("java.util.HashMap");
                return(builder.ToString());
            }
            else if (type.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123))
            {
                return(target + " = " + source + ".getDateTime();");
            }
            else if (type.IsPrimaryType(KnownPrimaryType.UnixTime))
            {
                return(target + " = new DateTime(" + source + " * 1000L, DateTimeZone.UTC);");
            }
            else if (type.IsPrimaryType(KnownPrimaryType.Base64Url))
            {
                return(target + " = " + source + ".getDecodedBytes();");
            }
            else
            {
                return(target + " = " + source + ";");
            }
        }
Пример #12
0
 public StructMemberModel(
     ITypeModel propertyModel,
     PropertyInfo propertyInfo,
     FlatBufferItemAttribute attribute,
     int offset,
     int length) : base(propertyModel, propertyInfo, attribute)
 {
     this.Offset = offset;
     this.Length = length;
 }
Пример #13
0
        public override void OnInitialize()
        {
            if (this.ClrType != typeof(Memory <byte>) && this.ClrType != typeof(ReadOnlyMemory <byte>))
            {
                throw new InvalidFlatBufferDefinitionException($"Memory vectors may only be ReadOnlyMemory<byte> or Memory<byte>.");
            }

            this.isReadOnly    = this.ClrType == typeof(ReadOnlyMemory <byte>);
            this.itemTypeModel = new ByteTypeModel();
        }
Пример #14
0
 /// <summary>
 /// Recursively traverses the full object graph for the given type model.
 /// </summary>
 public static void TraverseObjectGraph(this ITypeModel model, HashSet <Type> seenTypes)
 {
     if (seenTypes.Add(model.ClrType))
     {
         foreach (var child in model.Children)
         {
             child.TraverseObjectGraph(seenTypes);
         }
     }
 }
Пример #15
0
        protected void WriteAttrTypes(ITypeModel typemodel)
        {
            String prefix = typemodel.IsNodeModel ? "NAT_" : "EAT_";

            foreach (AttributeType attrtype in typemodel.AttributeTypes)
            {
                String id = prefix + attrtype.OwnerType.Name + "_" + attrtype.Name;
                WriteGXLNode(id, "AttributeClass", new Attr("name", "string", attrtype.Name));
                WriteGXLEdge(id, GetDomainID(attrtype), "hasDomain");
            }
        }
Пример #16
0
    public override void Initialize()
    {
        base.Initialize();

        Type?under = Nullable.GetUnderlyingType(this.ClrType);

        FlatSharpInternal.Assert(under is not null, "Nullable type model created for a type that is not Nullable<T>.");

        this.underlyingType      = under;
        this.underlyingTypeModel = this.typeModelContainer.CreateTypeModel(this.underlyingType);
    }
Пример #17
0
 /// <summary>
 /// Returns a compile-time constant default expression for the given type model.
 /// </summary>
 public static string GetTypeDefaultExpression(this ITypeModel typeModel)
 {
     if (typeModel.IsNonNullableClrValueType())
     {
         return($"default({typeModel.GetCompilableTypeName()})");
     }
     else
     {
         return("null");
     }
 }
Пример #18
0
        public static string GetNullableAnnotationTypeName(this ITypeModel typeModel, FlatBufferSchemaType context)
        {
            var typeName = typeModel.GetCompilableTypeName();

            if (typeModel.ClassifyContextually(context).IsOptionalReference())
            {
                typeName += "?";
            }

            return(typeName);
        }
        /// <summary>
        /// Tries to resolve an FBS alias into a type model.
        /// </summary>
        public bool TryResolveFbsAlias(TypeModelContainer container, string alias, out ITypeModel typeModel)
        {
            typeModel = null;

            if (alias == "string")
            {
                typeModel = new StringTypeModel();
                return(true);
            }

            return(false);
        }
    public static (string classDef, string className) CreateFlatBufferVectorSubclass(
        ITypeModel itemTypeModel,
        ParserCodeGenContext parseContext)
    {
        Type   itemType  = itemTypeModel.ClrType;
        string className = $"FlatBufferVector_{Guid.NewGuid():n}";

        parseContext = parseContext with
        {
            InputBufferTypeName           = "TInputBuffer",
            InputBufferVariableName       = "memory",
            IsOffsetByRef                 = false,
            TableFieldContextVariableName = "fieldContext",
        };

        var    serializeContext = parseContext.GetWriteThroughContext("data", "item", "0");
        string writeThroughBody = serializeContext.GetSerializeInvocation(itemType);

        if (itemTypeModel.SerializeMethodRequiresContext)
        {
            writeThroughBody = "throw new NotSupportedException(\"write through is not available for this type\")";
        }

        string classDef = $@"
                public sealed class {className}<{parseContext.InputBufferTypeName}> : FlatBufferVector<{itemType.GetGlobalCompilableTypeName()}, {parseContext.InputBufferTypeName}>
                    where {parseContext.InputBufferTypeName} : {nameof(IInputBuffer)}
                {{
                    public {className}(
                        {parseContext.InputBufferTypeName} memory,
                        int offset,
                        int itemSize,
                        {nameof(TableFieldContext)} fieldContext) : base(memory, offset, itemSize, fieldContext)
                    {{
                    }}

                    protected override void ParseItem(
                        {parseContext.InputBufferTypeName} memory,
                        int offset,
                        {nameof(TableFieldContext)} fieldContext,
                        out {itemType.GetGlobalCompilableTypeName()} item)
                    {{
                        item = {parseContext.GetParseInvocation(itemType)};
                    }}

                    protected override void WriteThrough({itemType.GetGlobalCompilableTypeName()} {serializeContext.ValueVariableName}, Span<byte> {serializeContext.SpanVariableName})
                    {{
                        {writeThroughBody};
                    }}
                }}
            ";

        return(classDef, className);
    }
Пример #21
0
        public override void Initialize()
        {
            base.Initialize();

            Type?under = Nullable.GetUnderlyingType(this.ClrType);

            if (under is null)
            {
                throw new InvalidFlatBufferDefinitionException("Nullable type model created for a type that is not Nullable<T>.");
            }

            this.underlyingType      = under;
            this.underlyingTypeModel = this.typeModelContainer.CreateTypeModel(this.underlyingType);
        }
Пример #22
0
        private IEnumerable <Operation> TranslateHeapOperations(
            ITypeModel variableModel,
            ITypeModel valueModel,
            HeapOperation heapOp)
        {
            if (heapOp.Kind == SpecialOperationKind.FieldRead)
            {
                if (variableModel == null)
                {
                    yield break;
                }

                var translatedReference = this.TranslateVariable(heapOp.Reference.AssignmentLeft.Single());
                var variables           = variableModel.AssignmentLeft;
                Contract.Assert(variables.Count == heapOp.Fields.Length);

                for (int i = 0; i < variables.Count; i++)
                {
                    Contract.Assert(variables[i].Sort == heapOp.Fields[i].Sort);

                    yield return(new FieldRead(
                                     this.TranslateVariable(variables[i]),
                                     translatedReference,
                                     heapOp.Fields[i]));
                }
            }
            else
            {
                Contract.Assert(heapOp.Kind == SpecialOperationKind.FieldWrite);

                if (valueModel == null)
                {
                    yield break;
                }

                var translatedReference = this.TranslateVariable(heapOp.Reference.AssignmentLeft.Single());
                var values = valueModel.AssignmentRight;
                Contract.Assert(values.Count == heapOp.Fields.Length);

                for (int i = 0; i < values.Count; i++)
                {
                    Contract.Assert(values[i].Sort == heapOp.Fields[i].Sort);

                    yield return(new FieldWrite(
                                     translatedReference,
                                     heapOp.Fields[i],
                                     this.TranslateExpression(values[i])));
                }
            }
        }
Пример #23
0
        /// <summary>
        /// Attempts to resolve a type model from the given FBS type alias.
        /// </summary>
        public bool TryResolveFbsAlias(string alias, out ITypeModel typeModel)
        {
            typeModel = null;

            foreach (var provider in this.providers)
            {
                if (provider.TryResolveFbsAlias(this, alias, out typeModel))
                {
                    return(true);
                }
            }

            return(false);
        }
Пример #24
0
        public void ValidStructs(Type type, bool marshalSerialize, bool marshalParse)
        {
            ITypeModel typeModel = RuntimeTypeModel.CreateFrom(type);
            var        tm        = Assert.IsType <ValueStructTypeModel>(typeModel);

            var children = tm.Children.ToArray();

            Assert.Equal(typeof(byte), children[0].ClrType);
            Assert.Equal(typeof(short), children[1].ClrType);
            Assert.Equal(typeof(int), children[2].ClrType);
            Assert.Equal(typeof(long), children[3].ClrType);
            Assert.Equal(typeof(ValidStruct_Inner), children[4].ClrType);
            Assert.Equal(marshalSerialize, tm.CanMarshalOnSerialize);
            Assert.Equal(marshalParse, tm.CanMarshalOnParse);
        }
Пример #25
0
        // TODO: Somehow handle the different sizes and signed/unsigned variants using modulo etc.
        public void ModelOperation(IModellingContext context, IMethodSymbol method, IEnumerable <ITypeModel> arguments)
        {
            Contract.Requires(context != null);
            Contract.Requires(method != null);
            Contract.Requires(arguments != null);
            Contract.Requires(arguments.Count() == method.Parameters.Length);

            if (method.MethodKind != MethodKind.BuiltinOperator ||
                method.Parameters.Length == 0 ||
                (!BooleanModelFactory.Instance.IsTypeSupported(method.ReturnType) &&
                 !this.IsTypeSupported(method.ReturnType)))
            {
                // This might be the case of conversions to other types, static methods etc.
                context.SetUnsupported();
                return;
            }

            IntHandle  intResult;
            BoolHandle boolResult;

            this.GetOperationResult(context, method, arguments, out intResult, out boolResult);

            ITypeModel resultModel = null;

            if (intResult.Expression != null)
            {
                Contract.Assert(this.IsTypeSupported(method.ReturnType));
                resultModel = new IntegerModel(this, method.ReturnType, intResult);
            }
            else if (boolResult.Expression != null)
            {
                Contract.Assert(BooleanModelFactory.Instance.IsTypeSupported(method.ReturnType));

                // TODO: Properly manage the references to the other factories instead of using singletons for all types
                resultModel = BooleanModelFactory.Instance.GetExpressionModel(
                    method.ReturnType,
                    boolResult.Expression.ToSingular());
            }

            if (resultModel != null)
            {
                context.SetResultValue(resultModel);
            }
            else
            {
                context.SetUnsupported();
            }
        }
Пример #26
0
        internal ItemMemberModel(
            ITypeModel propertyModel,
            PropertyInfo propertyInfo,
            ushort index)
        {
            var getMethod = propertyInfo.GetMethod;
            var setMethod = propertyInfo.SetMethod;

            this.ItemTypeModel = propertyModel;
            this.PropertyInfo  = propertyInfo;
            this.Index         = index;

            if (getMethod == null)
            {
                throw new InvalidFlatBufferDefinitionException($"Property {propertyInfo.Name} did not declare a getter.");
            }

            if (!getMethod.IsPublic)
            {
                throw new InvalidFlatBufferDefinitionException($"Property {propertyInfo.Name} must declare a public getter.");
            }

            if (getMethod.IsVirtual)
            {
                this.IsVirtual = true;
                if (!ValidateVirtualPropertyMethod(getMethod, false))
                {
                    throw new InvalidFlatBufferDefinitionException($"Property {propertyInfo.Name} did not declare a public/protected virtual getter.");
                }

                if (!ValidateVirtualPropertyMethod(setMethod, true))
                {
                    throw new InvalidFlatBufferDefinitionException($"Property {propertyInfo.Name} declared a set method, but it was not public/protected and virtual.");
                }
            }
            else
            {
                if (!ValidateNonVirtualMethod(getMethod))
                {
                    throw new InvalidFlatBufferDefinitionException($"Non-virtual property {propertyInfo.Name} must declare a public and non-abstract getter.");
                }

                if (!ValidateNonVirtualMethod(setMethod))
                {
                    throw new InvalidFlatBufferDefinitionException($"Non-virtual property {propertyInfo.Name} must declare a public/protected and non-abstract setter.");
                }
            }
        }
Пример #27
0
 ////public ProductModel(ITypeModel typeModel, IAlternateIdModel alternateIdModel, IKitModel kitModel, ICustomFieldModel customFieldModel, IOptionModel optionModel, IUnitModel unitModel, IInventoryModel inventoryModel, IExternalIdModel externalIdModel, IVariantModel variantModel, IWebhookModel webHookModel, IBaseContextModel contextModel, ICategoryAssignmentModel categoryAssignmentModel)
 public ProductModel(ICustomFieldModel customFieldModel, ITypeModel typeModel, IAlternateIdModel alternateIdModel, IKitModel kitModel, IOptionModel optionModel, IUnitModel unitModel, IInventoryModel inventoryModel, IExternalIdModel externalIdModel, IVariantModel variantModel, IWebhookModel webHookModel, IBaseContextModel contextModel, ICategoryAssignmentModel categoryAssignmentModel, IOptions <Sheev.Common.Models.MongoDbSetting> mongoDbSettings, IOptions <Sheev.Common.Models.ApiUrlSetting> apiSettings)
 {
     _categoryAssignmentModel = categoryAssignmentModel;
     _webHookModel            = webHookModel;
     context = new Models.ContextModel(mongoDbSettings, apiSettings);
     ////context = contextModel;
     _variantModel     = variantModel;
     _externalIdModel  = externalIdModel;
     _inventoryModel   = inventoryModel;
     _unitModel        = unitModel;
     _optionModel      = optionModel;
     _customFieldModel = customFieldModel;
     _kitModel         = kitModel;
     _alternateIdModel = alternateIdModel;
     _typeModel        = typeModel;
 }
Пример #28
0
        public override void OnInitialize()
        {
            var genericDef = this.ClrType.GetGenericTypeDefinition();

            if (genericDef != typeof(IList <>) && genericDef != typeof(IReadOnlyList <>))
            {
                throw new InvalidFlatBufferDefinitionException($"Cannot build a vector from type: {this.ClrType}. Only List, ReadOnlyList, Memory, ReadOnlyMemory, and Arrays are supported.");
            }

            this.isReadOnly    = genericDef == typeof(IReadOnlyList <>);
            this.itemTypeModel = this.typeModelContainer.CreateTypeModel(this.ClrType.GetGenericArguments()[0]);

            if (!this.itemTypeModel.IsValidVectorMember)
            {
                throw new InvalidFlatBufferDefinitionException($"Type '{this.itemTypeModel.ClrType.Name}' is not a valid vector member.");
            }
        }
Пример #29
0
        public void MarshalConfigTests(Type type, bool marshalEnable, bool marshalSerialize, bool marshalParse)
        {
            ITypeModel typeModel = RuntimeTypeModel.CreateFrom(type);
            var        tm        = Assert.IsType <ValueStructTypeModel>(typeModel);

            Assert.Equal(marshalSerialize, tm.CanMarshalOnSerialize);
            Assert.Equal(marshalParse, tm.CanMarshalOnParse);

            var options = new FlatBufferSerializerOptions {
                EnableValueStructMemoryMarshalDeserialization = marshalEnable
            };

            CodeGeneratedMethod serializeMethod = tm.CreateSerializeMethodBody(ContextHelpers.CreateSerializeContext(options));
            CodeGeneratedMethod parseMethod     = tm.CreateParseMethodBody(ContextHelpers.CreateParserContext(options));

            Assert.Equal(parseMethod.MethodBody.Contains("MemoryMarshal.Cast"), marshalEnable && marshalParse);
            Assert.Equal(serializeMethod.MethodBody.Contains("MemoryMarshal.Cast"), marshalEnable && marshalSerialize);
        }
Пример #30
0
        public override void OnInitialize()
        {
            if (!this.ClrType.IsArray)
            {
                throw new InvalidFlatBufferDefinitionException($"Array vectors must contain be arrays. Type = {this.ClrType.FullName}.");
            }

            if (this.ClrType.GetArrayRank() != 1)
            {
                throw new InvalidFlatBufferDefinitionException($"Array vectors may only be single-dimensional.");
            }

            this.itemTypeModel = this.typeModelContainer.CreateTypeModel(this.ClrType.GetElementType() !);
            if (!this.itemTypeModel.IsValidVectorMember)
            {
                throw new InvalidFlatBufferDefinitionException($"Type '{this.itemTypeModel.GetCompilableTypeName()}' is not a valid vector member.");
            }
        }
Пример #31
0
        public void Generate(ITypeModel definition)
        {
            InterfaceModel interfaceModel = definition as InterfaceModel;
            if (interfaceModel != null)
            {
                ++InterfaceCount;
                Generate(interfaceModel);
                return;
            }

            EnumModel enumModel = definition as EnumModel;
            if (enumModel != null)
            {
                ++EnumCount;
                Generate(enumModel);
                return;
            }
        }
Пример #32
0
 internal static void RegisterType(ITypeModel model)
 {
     s_typeMap[model.Name] = model;
 }
Пример #33
0
 protected void WriteAttrTypes(ITypeModel typemodel)
 {
     String prefix = typemodel.IsNodeModel ? "NAT_" : "EAT_";
     foreach(AttributeType attrtype in typemodel.AttributeTypes)
     {
         String id = prefix + attrtype.OwnerType.Name + "_" + attrtype.Name;
         WriteGXLNode(id, "AttributeClass", new Attr("name", "string", attrtype.Name));
         WriteGXLEdge(id, GetDomainID(attrtype), "hasDomain");
     }
 }
Пример #34
0
 public AzureResponseModel(ITypeModel body, ITypeModel headers, AzureMethodTemplateModel method)
     : this(new Response(body, headers), method)
 {
 }
Пример #35
0
 private string convertClientTypeToWireType(ITypeModel wireType, string source, string target, string clientReference, int level = 0)
 {
     IndentedStringBuilder builder = new IndentedStringBuilder();
     if (wireType.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123))
     {
         if (!IsRequired)
         {
             builder.AppendLine("DateTimeRfc1123 {0} = {1};", target, wireType.DefaultValue(_method))
                 .AppendLine("if ({0} != null) {{", source).Indent();
         }
         builder.AppendLine("{0}{1} = new DateTimeRfc1123({2});", IsRequired ? "DateTimeRfc1123 " : "", target, source);
         if (!IsRequired)
         {
             builder.Outdent().AppendLine("}");
         }
     }
     else if (wireType.IsPrimaryType(KnownPrimaryType.UnixTime))
     {
         if (!IsRequired)
         {
             builder.AppendLine("Long {0} = {1};", target, wireType.DefaultValue(_method))
                 .AppendLine("if ({0} != null) {{", source).Indent();
         }
         builder.AppendLine("{0}{1} = {2}.toDateTime(DateTimeZone.UTC).getMillis() / 1000;", IsRequired ? "Long " : "", target, source);
     }
     else if (wireType.IsPrimaryType(KnownPrimaryType.Base64Url))
     {
         if (!IsRequired)
         {
             builder.AppendLine("Base64Url {0} = {1};", target, wireType.DefaultValue(_method))
                 .AppendLine("if ({0} != null) {{", source).Indent();
         }
         builder.AppendLine("{0}{1} = Base64Url.encode({2});", IsRequired ? "Base64Url " : "", target, source);
         if (!IsRequired)
         {
             builder.Outdent().AppendLine("}");
         }
     }
     else if (wireType.IsPrimaryType(KnownPrimaryType.Stream))
     {
         if (!IsRequired)
         {
             builder.AppendLine("RequestBody {0} = {1};", target, wireType.DefaultValue(_method))
                 .AppendLine("if ({0} != null) {{", source).Indent();
         }
         builder.AppendLine("{0}{1} = RequestBody.create(MediaType.parse(\"{2}\"), {3});",
             IsRequired ? "RequestBody " : "", target, _method.RequestContentType, source);
         if (!IsRequired)
         {
             builder.Outdent().AppendLine("}");
         }
     }
     else if (wireType is SequenceTypeModel)
     {
         if (!IsRequired)
         {
             builder.AppendLine("{0} {1} = {2};", WireType.Name, target, wireType.DefaultValue(_method))
                 .AppendLine("if ({0} != null) {{", source).Indent();
         }
         var sequenceType = wireType as SequenceTypeModel;
         var elementType = sequenceType.ElementTypeModel;
         var itemName = string.Format(CultureInfo.InvariantCulture, "item{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture));
         var itemTarget = string.Format(CultureInfo.InvariantCulture, "value{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture));
         builder.AppendLine("{0}{1} = new ArrayList<{2}>();", IsRequired ? wireType.Name + " " : "", target, elementType.Name)
             .AppendLine("for ({0} {1} : {2}) {{", elementType.ParameterVariant.Name, itemName, source)
             .Indent().AppendLine(convertClientTypeToWireType(elementType, itemName, itemTarget, clientReference, level + 1))
                 .AppendLine("{0}.add({1});", target, itemTarget)
             .Outdent().Append("}");
         _implImports.Add("java.util.ArrayList");
         if (!IsRequired)
         {
             builder.Outdent().AppendLine("}");
         }
     }
     else if (wireType is DictionaryTypeModel)
     {
         if (!IsRequired)
         {
             builder.AppendLine("{0} {1} = {2};", WireType.Name, target, wireType.DefaultValue(_method))
                 .AppendLine("if ({0} != null) {{", source).Indent();
         }
         var dictionaryType = wireType as DictionaryTypeModel;
         var valueType = dictionaryType.ValueTypeModel;
         var itemName = string.Format(CultureInfo.InvariantCulture, "entry{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture));
         var itemTarget = string.Format(CultureInfo.InvariantCulture, "value{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture));
         builder.AppendLine("{0}{1} = new HashMap<String, {2}>();", IsRequired ? wireType.Name + " " : "", target, valueType.Name)
             .AppendLine("for (Map.Entry<String, {0}> {1} : {2}.entrySet()) {{", valueType.ParameterVariant.Name, itemName, source)
             .Indent().AppendLine(convertClientTypeToWireType(valueType, itemName + ".getValue()", itemTarget, clientReference, level + 1))
                 .AppendLine("{0}.put({1}.getKey(), {2});", target, itemName, itemTarget)
             .Outdent().Append("}");
         _implImports.Add("java.util.HashMap");
         if (!IsRequired)
         {
             builder.Outdent().AppendLine("}");
         }
     }
     return builder.ToString();
 }
Пример #36
0
		public void AddType(ITypeModel type)
		{
			types.Add(type);
		}
Пример #37
0
        private string convertToClientType(ITypeModel type, string source, string target, int level = 0)
        {
            if (type == null)
            {
                return target + " = " + source + ";";
            }
            
            IndentedStringBuilder builder = new IndentedStringBuilder();

            SequenceTypeModel sequenceType = type as SequenceTypeModel;
            DictionaryTypeModel dictionaryType = type as DictionaryTypeModel;

            if (sequenceType != null)
            {
                var elementType = sequenceType.ElementTypeModel;
                var itemName = string.Format(CultureInfo.InvariantCulture, "item{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture));
                var itemTarget = string.Format(CultureInfo.InvariantCulture, "value{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture));
                builder.AppendLine("{0} = new ArrayList<{1}>();", target, elementType.ResponseVariant.Name)
                    .AppendLine("for ({0} {1} : {2}) {{", elementType.Name, itemName, source)
                    .Indent().AppendLine("{0} {1};", elementType.ResponseVariant.Name, itemTarget)
                        .AppendLine(convertToClientType(elementType, itemName, itemTarget, level + 1))
                        .AppendLine("{0}.add({1});", target, itemTarget)
                    .Outdent().Append("}");
                _implImports.Add("java.util.ArrayList");
                return builder.ToString();
            }
            else if (dictionaryType != null)
            {
                var valueType = dictionaryType.ValueTypeModel;
                var itemName = string.Format(CultureInfo.InvariantCulture, "entry{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture));
                var itemTarget = string.Format(CultureInfo.InvariantCulture, "value{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture));
                builder.AppendLine("{0} = new HashMap<String, {1}>();", target, valueType.ResponseVariant.Name)
                    .AppendLine("for (Map.Entry<String, {0}> {1} : {2}.entrySet()) {{", valueType.Name, itemName, source)
                    .Indent().AppendLine("{0} {1};", valueType.ResponseVariant.Name, itemTarget)
                        .AppendLine(convertToClientType(valueType, itemName + ".getValue()", itemTarget, level + 1))
                        .AppendLine("{0}.put({1}.getKey(), {2});", target, itemName, itemTarget)
                    .Outdent().Append("}");
                _implImports.Add("java.util.HashMap");
                return builder.ToString();
            }
            else if (type.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123))
            {
                return target + " = " + source + ".getDateTime();";
            }
            else
            {
                return target + " = " + source + ";";
            }
        }
Пример #38
0
 public ResponseModel(ITypeModel body, ITypeModel headers)
     : this(new Response(body, headers))
 {
 }