private static string ToCode(object val, Type targetType) { if (val == null) return "null"; if (val.Equals(CsDb.CodeGen.Statics.DateTimeNowFunction)) return $"\"DateTime.Now\""; if (val.Equals(CsDb.CodeGen.Statics.NewGuidFunction)) return $"\"Guid.NewGuid()\""; if (targetType == typeof (string)) return $"\"{val}\""; if (targetType == typeof (DateTime)) return $"\"{val}\""; if (targetType == typeof (TimeSpan)) return $"\"{((TimeSpan)val).ToString("hh\\:mm\\:ss")}\""; if (targetType == typeof (bool)) return $"{val.ToString().ToLower()}"; if (targetType == typeof (Guid)) return $"\"{val}\""; if (targetType.IsNumericType()) return val.ToString(); throw new NotImplementedException("Type is not implemented"); }
/// <summary> /// Converts a value to the specified type using a <see cref="TypeConverter"/>, if one is available. /// </summary> /// <param name="value">The value to convert.</param> /// <param name="originalType">The value's original type.</param> /// <param name="conversionType">The type to which to convert the value.</param> /// <returns>The converted value.</returns> private static Object ConvertUsingTypeConverter(Object value, Type originalType, Type conversionType) { var converter = TypeDescriptor.GetConverter(conversionType); if (converter != null && converter.CanConvertFrom(originalType)) { /* HACK: converter.IsValid() will throw an exception for null/empty strings * in some circumstances. It's handled in System.dll but ultimately a pointless * inefficiency, so we prevent that here. */ var assumeInvalid = false; if (originalType == typeof(String) && conversionType.IsNumericType()) { if (String.IsNullOrEmpty((String)value)) assumeInvalid = true; } if (!assumeInvalid && converter.IsValid(value)) { return converter.ConvertFrom(value); } } if (conversionType.IsAssignableFrom(originalType)) return value; return conversionType.IsClass ? null : Activator.CreateInstance(conversionType); }
public override IEnumerable<PatternNameBinding> Resolve(Context ctx, Type expressionType) { var startType = RangeStartRule.Literal.LiteralType; var endType = RangeEndRule.Literal.LiteralType; if(!startType.IsNumericType() || !endType.IsNumericType()) Error(CompilerMessages.PatternRangeNotNumeric); if(!expressionType.IsNumericType()) Error(CompilerMessages.PatternTypeMismatch, expressionType, "int"); return NoBindings(); }
// All other types should attempt to do a resolution via self binding. protected override bool TypeIsSelfBindable(Type service) { return !service.IsInterface && !service.IsAbstract && !service.ContainsGenericParameters && !service.IsEnum && !service.IsArray && !service.IsNumericType() && !service.IsString() && !service.IsBoolean() && !service.IsDateTime() && service != typeof(char); }
public override string ToQuotedString(Type fieldType, object value) { var isEnumFlags = fieldType.IsEnumFlags() || (!fieldType.IsEnum && fieldType.IsNumericType()); //i.e. is real int && not Enum long enumValue; if (!isEnumFlags && long.TryParse(value.ToString(), out enumValue)) value = Enum.ToObject(fieldType, enumValue); var enumString = DialectProvider.StringSerializer.SerializeToString(value); if (enumString == null || enumString == "null") enumString = value.ToString(); return !isEnumFlags ? DialectProvider.GetQuotedValue(enumString.Trim('"')) : enumString; }
public override string ToQuotedString(Type fieldType, object value) { var isEnumAsInt = fieldType.HasAttribute<EnumAsIntAttribute>(); if (isEnumAsInt) return this.ConvertNumber(Enum.GetUnderlyingType(fieldType), value).ToString(); var isEnumFlags = fieldType.IsEnumFlags() || (!fieldType.IsEnum() && fieldType.IsNumericType()); //i.e. is real int && not Enum long enumValue; if (!isEnumFlags && long.TryParse(value.ToString(), out enumValue)) value = Enum.ToObject(fieldType, enumValue); var enumString = DialectProvider.StringSerializer.SerializeToString(value); if (enumString == null || enumString == "null") enumString = value.ToString(); return !isEnumFlags ? DialectProvider.GetQuotedValue(enumString.Trim('"')) : enumString; }
public override object ToDbValue(Type fieldType, object value) { var isEnumFlags = fieldType.IsEnumFlags() || (!fieldType.IsEnum && fieldType.IsNumericType()); //i.e. is real int && not Enum if (isEnumFlags && value.GetType().IsEnum) return Convert.ChangeType(value, fieldType.GetTypeCode()); long enumValue; if (long.TryParse(value.ToString(), out enumValue)) { if (isEnumFlags) return enumValue; value = Enum.ToObject(fieldType, enumValue); } var enumString = DialectProvider.StringSerializer.SerializeToString(value); return enumString != null && enumString != "null" ? enumString.Trim('"') : value.ToString(); }
private static string GetDafaultValueCode(object def, Type targetType) { if (def.Equals(CsDb.CodeGen.Statics.DateTimeNowFunction)) return "DateTime.Now"; if (def.Equals(CsDb.CodeGen.Statics.NewGuidFunction)) return "Guid.NewGuid()"; if (targetType.IsNumericType()) return def.ToString(); if (targetType == typeof (DateTime)) return $"new DateTime({((DateTime) def).Ticks})"; if (targetType == typeof (TimeSpan)) return $"new TimeSpan({((TimeSpan) def).Ticks})"; if (targetType == typeof (bool)) return def.ToString().ToLower(); if (targetType == typeof (string)) return $"\"{def}\""; throw new Exception("Unknown data format"); }
private static void WidenNumeric(ref Object value, ref Type valueType) { if (!valueType.IsNumericType() || (valueType == typeof(Double))) return; value = TypeHelper.Convert<Double>(value); valueType = typeof(Double); }
private static int distanceFrom(Type varType, Type exprType, bool exactly = false) { if (varType == exprType) return 0; if (varType.IsByRef) return varType.GetElementType() == exprType ? 0 : int.MaxValue; if (!exactly) { if (varType.IsNullableType() && exprType == Nullable.GetUnderlyingType(varType)) return 1; if ((varType.IsClass || varType.IsNullableType()) && exprType == typeof (NullType)) return 1; if (varType.IsNumericType() && exprType.IsNumericType()) return NumericTypeConversion(varType, exprType); } if (varType == typeof (object)) { if (exprType.IsValueType) return exactly ? int.MaxValue : 1; if (exprType.IsInterface) return 1; } if (varType.IsInterface) { if (exprType.IsInterface) return InterfaceDistance(varType, new[] { exprType }.Union(GenericHelper.GetInterfaces(exprType))); // casting expression to interface takes 1 step var dist = InterfaceDistance(varType, GenericHelper.GetInterfaces(exprType)); if (dist < int.MaxValue) return dist + 1; } if (varType.IsGenericParameter || exprType.IsGenericParameter) return GenericParameterDistance(varType, exprType); if (varType.IsGenericType && exprType.IsGenericType) return GenericDistance(varType, exprType); int result; if (IsDerivedFrom(exprType, varType, out result)) return result; if (varType.IsArray && exprType.IsArray) { var varElType = varType.GetElementType(); var exprElType = exprType.GetElementType(); var areRefs = !varElType.IsValueType && !exprElType.IsValueType; var generic = varElType.IsGenericParameter || exprElType.IsGenericParameter; if(areRefs || generic) return varElType.DistanceFrom(exprElType, exactly); } return int.MaxValue; }
private void AddTypeOptions(Dictionary<string, object> options, Type type) { if (type.IsNumericType()) { options["type"] = type.Name.ToLower(); } else if (Nullable.GetUnderlyingType(type)?.IsNumericType() == true) { options["type"] = Nullable.GetUnderlyingType(type).Name.ToLower() + "?"; } }
private static object ToDefaultValue(string defaultValue, Type dotNetType) { if (defaultValue == null) return null; if (dotNetType.IsNumericType()) return Convert.ChangeType(defaultValue.Trim('(', ')'), dotNetType); if (dotNetType == typeof (DateTime)) { if (defaultValue.ToLower() == "(getdate())") return CsDb.CodeGen.Statics.DateTimeNowFunction; return Convert.ToDateTime(defaultValue.Trim('(', ')', '\'')); } if (dotNetType == typeof (TimeSpan)) { return TimeSpan.Parse(defaultValue.Trim('(', ')', '\'')); } if (dotNetType == typeof (Guid)) { if (defaultValue.ToLower() == "(newid())") return CsDb.CodeGen.Statics.NewGuidFunction; throw new InvalidOperationException("Unknown Default value found. Include a conversion to a valid C# instance. If it is a function please use the 'CsDb.CodeGen.Statics' name space to set the value to a string."); } if (dotNetType == typeof (string)) { var lower = defaultValue.ToLower(); if (lower == "(null)") return null; if (lower.StartsWith("('") && lower.EndsWith("')")) return defaultValue.Substring(2, defaultValue.Length - 4); if (lower.StartsWith("(n'") && lower.EndsWith("')")) return defaultValue.Substring(3, defaultValue.Length - 5); throw new InvalidOperationException("Unknown Default value found. Include a conversion to a valid C# instance. If it is a function please use the 'CsDb.CodeGen.Statics' name space to set the value to a string."); } if (dotNetType == typeof (bool)) { if (defaultValue.ToLower() == "((0))") return false; if (defaultValue.ToLower() == "((1))") return true; } // Include a conversion to a valid C# instance. // If it is a function please use the 'CsDb.CodeGen.Statics' name space // Other exception in code generation will follow. Use description there to include conversion logic. throw new InvalidOperationException("Unknown Default value found. Include a conversion to a valid C# instance. If it is a function please use the 'CsDb.CodeGen.Statics' name space to set the value to a string."); }
/// <summary> /// Checks if two types can be compared. /// </summary> private bool canCompare(Type left, Type right, bool equalityOnly) { // there's an overridden method if (m_OverloadedMethod != null) return true; // string .. string if (left == typeof(string) && right == left) return true; // numeric .. numeric if (left.IsNumericType() && right.IsNumericType()) return left.IsUnsignedIntegerType() == right.IsUnsignedIntegerType(); if (equalityOnly) { // Nullable<T> .. (Nullable<T> | T | null) if (left.IsNullableType()) return left == right || Nullable.GetUnderlyingType(left) == right || right == typeof (NullType); if (right.IsNullableType()) return Nullable.GetUnderlyingType(right) == left || left == typeof (NullType); // ref type .. null if ((right == typeof (NullType) && !left.IsValueType) || (left == typeof (NullType) && !right.IsValueType)) return true; if (left is TypeBuilder && left == right) return true; } return false; }
/// <summary> /// Emits code for equality and inequality comparison. /// </summary> private void compileEquality(Context ctx, Type left, Type right) { var gen = ctx.CurrentILGenerator; // compare two strings if (left == typeof (string) && right == typeof (string)) { LeftOperand.Compile(ctx, true); RightOperand.Compile(ctx, true); var method = typeof (string).GetMethod("Equals", new[] {typeof (string), typeof (string)}); gen.EmitCall(method); if (Kind == ComparisonOperatorKind.NotEquals) emitInversion(gen); return; } // compare two numerics if (left.IsNumericType() && right.IsNumericType()) { loadAndConvertNumerics(ctx); gen.EmitCompareEqual(); if(Kind == ComparisonOperatorKind.NotEquals) emitInversion(gen); return; } // compare nullable against another nullable, it's base type or null if (left.IsNullableType()) { if(left == right || Nullable.GetUnderlyingType(left) == right) compileNullable(ctx, LeftOperand, RightOperand); else if(right == typeof(NullType)) compileHasValue(ctx, LeftOperand); return; } if (right.IsNullableType()) { if (Nullable.GetUnderlyingType(right) == left) compileNullable(ctx, RightOperand, LeftOperand); else if (left == typeof(NullType)) compileHasValue(ctx, RightOperand); return; } // compare a reftype against a null if (left == typeof(NullType) || right == typeof(NullType)) { LeftOperand.Compile(ctx, true); RightOperand.Compile(ctx, true); gen.EmitCompareEqual(); if (Kind == ComparisonOperatorKind.NotEquals) emitInversion(gen); return; } if (left is TypeBuilder && left == right) { var equals = ctx.ResolveMethod(left, "Equals", new [] { typeof (object) }); LeftOperand.Compile(ctx, true); RightOperand.Compile(ctx, true); gen.EmitCall(equals.MethodInfo); if (Kind == ComparisonOperatorKind.NotEquals) emitInversion(gen); return; } }
/// <summary> /// Emits code for equality and inequality comparison. /// </summary> private void emitEqualityComparison(Context ctx, Type left, Type right) { var gen = ctx.CurrentMethod.Generator; // compare two strings if (left == right && left == typeof (string)) { LeftOperand.Emit(ctx, true); RightOperand.Emit(ctx, true); var method = typeof (string).GetMethod("Equals", new[] {typeof (string), typeof (string)}); gen.EmitCall(method); if (Kind == ComparisonOperatorKind.NotEquals) emitInversion(gen); return; } // compare primitive types if ((left.IsNumericType() && right.IsNumericType()) || (left == right && left == typeof(bool))) { if (left == typeof (bool)) { LeftOperand.Emit(ctx, true); RightOperand.Emit(ctx, true); } else { loadAndConvertNumerics(ctx); } gen.EmitCompareEqual(); if(Kind == ComparisonOperatorKind.NotEquals) emitInversion(gen); return; } // compare nullable against another nullable, it's base type or null if (left.IsNullableType()) { if(left == right || Nullable.GetUnderlyingType(left) == right) emitNullableComparison(ctx, LeftOperand, RightOperand); else if(right == typeof(NullType)) emitHasValueCheck(ctx, LeftOperand); return; } if (right.IsNullableType()) { if (Nullable.GetUnderlyingType(right) == left) emitNullableComparison(ctx, RightOperand, LeftOperand); else if (left == typeof(NullType)) emitHasValueCheck(ctx, RightOperand); return; } // compare a reftype against a null if (left == typeof(NullType) || right == typeof(NullType)) { LeftOperand.Emit(ctx, true); RightOperand.Emit(ctx, true); gen.EmitCompareEqual(); if (Kind == ComparisonOperatorKind.NotEquals) emitInversion(gen); return; } if (left is TypeBuilder && left == right) { var equals = ctx.ResolveMethod(left, "Equals", new [] { typeof (object) }); LeftOperand.Emit(ctx, true); RightOperand.Emit(ctx, true); gen.EmitCall(equals.MethodInfo); if (Kind == ComparisonOperatorKind.NotEquals) emitInversion(gen); return; } throw new ArgumentException("Unknown types to compare!"); }
/// <summary> /// Assign the default value of a given Type /// </summary> /// <param name="assignment"><see cref="Assignment"/> to assign to</param> /// <param name="type">The type of which to create a default for</param> /// <returns>The <see cref="Assignment"/> to build on</returns> public static Assignment WithDefaultNumericValue(this Assignment assignment, Type type) { if(type == null) throw new ArgumentException("Type cannot be null"); if(!type.IsNumericType()) throw new ArgumentException(string.Concat("Type must be a numeric type. Type is: ",type.ToString())); var defaultValue = Activator.CreateInstance(type); assignment.WithLiteral(string.Format("{0}", defaultValue)); return assignment; }
public static bool IsObjcValueType(Type type) { return type.IsNumericType() || type == typeof(bool) || type.IsEnum; }
/// <summary> /// Gets the most common type between two. /// </summary> private static Type getMostCommonType(Type left, Type right) { // corner case if (left == null || left == right) return right; if (right.IsInterface) return typeof (object); // valuetype & null if (left == typeof (NullType) && right.IsValueType) return typeof (Nullable<>).MakeGenericType(right); if (right == typeof(NullType) && left.IsValueType) return typeof(Nullable<>).MakeGenericType(left); // valuetype & Nullable<valuetype> if (left.IsNullableType() && left.GetGenericArguments()[0] == right) return left; if (right.IsNullableType() && right.GetGenericArguments()[0] == left) return right; // numeric extensions if (left.IsNumericType() && right.IsNumericType()) return GetNumericOperationType(left, right) ?? typeof(object); // arrays if (left.IsArray && right.IsArray) { var leftElem = left.GetElementType(); var rightElem = right.GetElementType(); return leftElem.IsValueType || rightElem.IsValueType ? typeof (object) : getMostCommonType(leftElem, rightElem).MakeArrayType(); } // inheritance var currLeft = left; while (currLeft != null) { var currRight = right; while (currRight != null) { if (currLeft == currRight) return currLeft; currRight = currRight.BaseType; } currLeft = currLeft.BaseType; } return typeof(object); }
public static bool ValueResponseValueNeedsBoxing(Type type) { return type.IsNumericType() || type == typeof(bool); }
protected override Type resolveOperatorType(Context ctx, Type leftType, Type rightType) { return leftType.IsNumericType() && rightType.IsNumericType() ? typeof (double) : null; }
protected virtual MethodDefinitionExpression CreateNormalizeRequestObjectMethod(Type forType, string format) { var requestObject = Expression.Parameter(FickleType.Define("id"), "serializeRequest"); var paramName = Expression.Parameter(typeof(string), "paramName"); var newArray = FickleExpression.Variable("NSMutableArray", "newArray"); var name = this.GetNormalizeRequestMethodName(forType, format); var value = FickleExpression.Variable("id", "value"); var item = Expression.Variable(FickleType.Define("id"), "item"); var formatIsForm = format == "form"; var complexType = ((forType as FickleType)?.ServiceClass != null); Expression processing; if (forType == typeof(TimeSpan)) { processing = FickleExpression.Call(Expression.Convert(item, typeof(TimeSpan)), typeof(string), "ToString", null); } else if (forType == typeof(Guid)) { processing = FickleExpression.Call(Expression.Convert(item, typeof(Guid)), typeof(string), "ToString", null); } else if (forType.IsEnum) { processing = Expression.Convert(FickleExpression.Call(item, typeof(int), "intValue", null), forType); if (this.CodeGenerationContext.Options.SerializeEnumsAsStrings) { processing = FickleExpression.StaticCall((Type)null, typeof(string), forType.Name + "ToString", processing); } else { processing = Expression.Convert(processing, typeof(object)); } } else if (forType == typeof(bool)) { processing = Expression.Condition ( Expression.Equal(FickleExpression.Call(item, typeof(bool), "boolValue", null), Expression.Constant(true)), Expression.Constant("true"), Expression.Constant("false") ); } else if (forType.IsNumericType()) { processing = Expression.Convert(item, FickleType.Define("NSNumber")); if (formatIsForm) { processing = FickleExpression.Call(processing, "stringValue", null); } } else { if (formatIsForm) { processing = FickleExpression.Call(item, "NSDictionary", "scalarPropertiesAsFormEncodedString", null); } else { processing = FickleExpression.Call(item, "NSString", "allPropertiesAsDictionary", null); } } var isArray = Expression.Variable(typeof(bool), "isArray"); var array = Expression.Variable(FickleType.Define("NSArray"), "array"); var urlEncodedValue = FickleExpression.Call(processing, typeof(string), "stringByAddingPercentEscapesUsingEncoding", Expression.Variable(typeof(int), "NSUTF8StringEncoding")); var joined = FickleExpression.Call(newArray, typeof(string), "componentsJoinedByString", Expression.Constant("&")); if (formatIsForm && !complexType) { processing = FickleExpression.Call(FickleExpression.Call(paramName, "stringByAppendingString", Expression.Constant("=")), typeof(string), "stringByAppendingString", urlEncodedValue); } var arrayProcessing = processing; if (formatIsForm) { arrayProcessing = FickleExpression.Call(FickleExpression.Call(paramName, "stringByAppendingString", Expression.Constant("=")), typeof(string), "stringByAppendingString", urlEncodedValue); } processing = Expression.IfThenElse ( isArray, FickleExpression.Block ( new [] { newArray }, Expression.Assign(array, requestObject), Expression.Assign(newArray, FickleExpression.New("NSMutableArray", "initWithCapacity", FickleExpression.Call(array, typeof(int), "count", null))), FickleExpression.ForEach ( item, array, FickleExpression.Call(newArray, typeof(void), "addObject", arrayProcessing).ToStatement().ToBlock() ), Expression.Assign(value, formatIsForm ? joined : (Expression)newArray), FickleExpression.Return(value) ), FickleExpression.Block ( new [] { item }, Expression.Assign(item, requestObject), Expression.Assign(value, processing), FickleExpression.Return(value) ) ); var body = FickleExpression.Block ( new[] { array, isArray, value }, Expression.Assign(isArray, Expression.TypeIs(requestObject, typeof(Array))), processing ); return new MethodDefinitionExpression ( name, new[] { requestObject, paramName }.ToReadOnlyCollection<Expression>(), FickleType.Define("id"), body, false, null ); }
/// <summary> /// Assign the default value of a given Type /// </summary> /// <param name="assignment"><see cref="Assignment"/> to assign to</param> /// <param name="type">The type of which to create a default for</param> /// <returns>The <see cref="Assignment"/> to build on</returns> public static Assignment WithDefaultValue(this Assignment assignment, Type type) { if( type == typeof(Guid) ) return assignment.WithGuidEmpty(); else if (type.IsValueType) { if (type.IsNumericType()) return assignment.WithDefaultNumericValue(type); if (type.IsDate()) return assignment.WithDate(); if (type.IsBoolean()) return assignment.WithBoolean(); } else { if( type == typeof(string) )return assignment.WithLiteral("\"\""); return assignment.WithNullValue(); } return assignment; }
private string GetNormalizeRequestMethodName(Type forType, string format = "json") { format = format.Capitalize(); forType = forType.GetFickleListElementType() ?? forType; forType = forType.GetUnwrappedNullableType(); if (forType == typeof(TimeSpan) || forType == typeof(Guid) || forType == typeof(bool) || forType.IsEnum) { return "normalizeRequest" + forType.Name + format; } else if (forType.IsNumericType()) { return "normalizeRequestNumber" + format; } else { return "normalizeRequestObject" + format; } }
public virtual string GetQuotedValue(object value, Type fieldType) { if (value == null) return "NULL"; //var dialectProvider = OrmLiteConfig.DialectProvider; //if (fieldType.IsRefType()) //{ // return dialectProvider.GetQuotedValue(dialectProvider.StringSerializer.SerializeToString(value)); //} var typeCode = fieldType.GetTypeCode(); switch (typeCode) { case TypeCode.Single: return ((float)value).ToString(CultureInfo.InvariantCulture); case TypeCode.Double: return ((double)value).ToString(CultureInfo.InvariantCulture); case TypeCode.Decimal: return ((decimal)value).ToString(CultureInfo.InvariantCulture); case TypeCode.Byte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.SByte: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: if (fieldType.IsNumericType()) return Convert.ChangeType(value, fieldType).ToString(); break; } if (fieldType == typeof(TimeSpan)) return ((TimeSpan)value).Ticks.ToString(CultureInfo.InvariantCulture); return ShouldQuoteValue(fieldType) ? DialectProvider.Instance.GetQuotedValue(value.ToString()) : value.ToString(); }
private List<IComparisonOperator> GetDefaultOperators(Type propertyType) { if (propertyType == typeof(String)) { return new List<IComparisonOperator> { ComparisonOperators.Equals, ComparisonOperators.NotEquals, ComparisonOperators.Contains, ComparisonOperators.NotContains }; } else if (propertyType.IsEnum || IsNullableEnum(propertyType)) { return new List<IComparisonOperator> { ComparisonOperators.Equals, ComparisonOperators.NotEquals }; } else if (propertyType.IsNumericType()) { return new List<IComparisonOperator> { ComparisonOperators.Equals, ComparisonOperators.NotEquals, ComparisonOperators.LessThan, ComparisonOperators.LessThanOrEqual, ComparisonOperators.GreaterThan, ComparisonOperators.GreaterThanOrEqual }; } return new List<IComparisonOperator>(); }