public virtual void ShouldEncodeUInt() { IntType intType = new IntType("uint"); uint given = 1234567; var result = intType.Encode(given).ToHex(); Assert.Equal("000000000000000000000000000000000000000000000000000000000012d687", result); }
public virtual void ShouldDecodeNegativeByteArray() { IntType intType = new IntType("int"); var bytes = intType.Encode(-100000569); var result = intType.Decode<BigInteger>(bytes); Assert.Equal(new BigInteger(-100000569), result); }
public async Task InvokeCustomAPIGetWithODataParams() { TestHttpHandler hijack = new TestHttpHandler(); hijack.SetResponseContent("{\"id\":3}"); MobileServiceClient service = new MobileServiceClient(MobileAppUriValidator.DummyMobileApp, hijack); var myParams = new Dictionary <string, string>() { { "$select", "one,two" }, { "$take", "1" } }; IntType expected = await service.InvokeApiAsync <IntType>("calculator/add", HttpMethod.Get, myParams); Assert.Contains("?%24select=one%2Ctwo&%24take=1", hijack.Request.RequestUri.Query); }
public async Task InvokeCustomAPIGetWithParams() { TestHttpHandler hijack = new TestHttpHandler(); hijack.SetResponseContent("{\"id\":3}"); MobileServiceClient service = new MobileServiceClient(MobileAppUriValidator.DummyMobileApp, hijack); var myParams = new Dictionary <string, string>() { { "a", "1" }, { "b", "2" } }; IntType expected = await service.InvokeApiAsync <IntType>("calculator/add", HttpMethod.Get, myParams); Assert.Equal("?a=1&b=2", hijack.Request.RequestUri.Query); }
public async Task InvokeGenericCustomAPIWithNullResponse_Success() { TestHttpHandler hijack = new TestHttpHandler(); hijack.Response = new HttpResponseMessage(HttpStatusCode.OK); hijack.Response.Content = null; MobileServiceClient service = new MobileServiceClient(MobileAppUriValidator.DummyMobileApp, hijack); MobileAppUriValidator mobileAppUriValidator = new MobileAppUriValidator(service); IntType expected = await service.InvokeApiAsync <IntType>("testapi"); Assert.Equal(mobileAppUriValidator.GetApiUriPath("testapi"), hijack.Request.RequestUri.LocalPath); Assert.Null(expected); }
public void ParseWithNumberStylesAndFormatProviderShouldReturnOptionIntNone() { // Arrange var s = "p1$234"; IFormatProvider formatProvider = new NumberFormatInfo() { PositiveSign = "p" }; Option <int> expected = None; // Act var result = IntType.Parse(s, NumberStyles.Integer, formatProvider); // Assert result.Should().Be(expected); }
public static AtomType Consume(Parser parser) { AtomType atomType = null; switch (parser.LookAhead().Type) { case TokenInfo.TokenType.BOOL: parser.Eat(TokenInfo.TokenType.BOOL); atomType = new BoolType(); break; case TokenInfo.TokenType.CHAR: parser.Eat(TokenInfo.TokenType.CHAR); atomType = new CharType(); break; case TokenInfo.TokenType.DOUBLE: parser.Eat(TokenInfo.TokenType.DOUBLE); atomType = new DoubleType(); break; case TokenInfo.TokenType.INT: parser.Eat(TokenInfo.TokenType.INT); atomType = new IntType(); break; case TokenInfo.TokenType.STRING: parser.Eat(TokenInfo.TokenType.STRING); atomType = new StringType(); break; case TokenInfo.TokenType.VOID: parser.Eat(TokenInfo.TokenType.VOID); atomType = new VoidType(); break; default: break; } if (atomType == null) { throw new ParserError(new FailedConsumer(), parser.Cursor); } return(atomType); }
public void ParseWithFormatProviderShouldReturnOptionIntSome() { // Arrange var s = "p1234"; IFormatProvider formatProvider = new NumberFormatInfo() { PositiveSign = "p" }; Option <int> expected = Some(1234); // Act var result = IntType.Parse(s, formatProvider); // Assert result.Should().Be(expected); }
public BenchmarkImplementation() { _results = new int[NumberOfOperations]; _previousResults = new int[NumberOfOperations]; /* Set up EnumFlags benchmark */ _enumComponentMasks = new ComponentType[NumberOfOperations]; _componentBitMasks = new BitMask[NumberOfOperations]; _wantedEnumMask = ComponentType.None; _wantedBitMask = new BitMask(bits: WantedBits); _intComponentMasks = new IntType[NumberOfOperations]; _wantedIntMask = 0; var random = new Random(); for (int i = 0; i < WantedBits.Length; ++i) { var bit = WantedBits[i]; _wantedEnumMask |= (ComponentType)((IntType)1 << bit); _wantedIntMask |= (IntType)1 << bit; } for (int i = 0; i < NumberOfOperations; ++i) { ComponentType enumComponentMask = ComponentType.None; BitMask componentBitMask = BitMask.None; IntType intComponentMask = 0; for (int b = 0; b < NumberOfBits; ++b) { var bit = random.Next(0, 31); enumComponentMask |= (ComponentType)((IntType)1 << bit); componentBitMask |= new BitMask(bits: new[] { bit }); intComponentMask |= (IntType)1 << bit; } _enumComponentMasks[i] = enumComponentMask; _componentBitMasks[i] = componentBitMask; _intComponentMasks[i] = intComponentMask; } }
public virtual void ShouldEncodeDecodeEnum() { var intType = new IntType("int"); var result1 = intType.Encode(TestEnum.Monkey).ToHex(); var decresult1 = intType.Decode <TestEnum>(result1); Assert.Equal(TestEnum.Monkey, decresult1); var result2 = intType.Encode(TestEnum.Elephant).ToHex(); var decresult2 = intType.Decode <TestEnum>(result2); Assert.Equal(TestEnum.Elephant, decresult2); var result3 = intType.Encode(TestEnum.Lion).ToHex(); var decresult3 = intType.Decode <TestEnum>(result3); Assert.Equal(TestEnum.Lion, decresult3); }
public async Task SchemaTypeReference_With_Type() { // arrange StringType stringType = await CreateTypeAsync <StringType>(); IntType intType = await CreateTypeAsync <IntType>(); SchemaTypeReference typeReference1 = TypeReference.Create( stringType, scope: "foo"); // act SchemaTypeReference typeReference2 = typeReference1.With(intType); // assert Assert.Equal(intType, typeReference2.Type); Assert.Equal(typeReference1.Context, typeReference2.Context); Assert.Equal(typeReference1.Scope, typeReference2.Scope); }
/// <summary> /// The promotion could be to a IntType /// </summary> /// <param name="operand"></param> /// <returns></returns> public override object Exec(IntType operand, object arg) { string notACharLabel = this.codeGenerator.NewLabel; string endLabel = this.codeGenerator.NewLabel; // * char to int // * If we could promote to an integer, a Char could be on the stack this.codeGenerator.dup(this.indent); this.codeGenerator.isinst(this.indent, CharType.Instance); this.codeGenerator.dup(this.indent); this.codeGenerator.brfalse(this.indent, notACharLabel); this.codeGenerator.br(this.indent, endLabel); this.codeGenerator.WriteLabel(this.indent, notACharLabel); this.codeGenerator.pop(this.indent); this.codeGenerator.dup(this.indent); this.codeGenerator.isinst(this.indent, IntType.Instance); this.codeGenerator.WriteLabel(this.indent, endLabel); return(null); }
public override (IType ReturnType, bool IsConstant) Invocation(IExpression[] args, SourceRange source, DiagnosticsReport diagnostics) { var returnType = new IntType(source); if (args.Length != 1) { diagnostics.AddError($"Expected 1 argument, found {args.Length}", source); } if (args.Length < 1) { return(returnType, false); } var isConstant = false; var arg = args[0]; if (arg.Type is IArrayType) { if (!arg.IsLValue) { Debug.Assert(false, "There is no way for an array to be non-lvalue"); } } else if (arg.Type is TypeNameType typeName) { if (typeName.TypeDeclaration is not EnumDeclaration) { diagnostics.AddError($"Argument 1: cannot pass non-enum type '{typeName.TypeDeclaration.Name}' to COUNT_OF parameter", arg.Source); } else { isConstant = true; } } else if (arg.Type is not ErrorType) { diagnostics.AddError($"Argument 1: cannot pass '{arg.Type}' to COUNT_OF parameter, expected array reference or enum type name", arg.Source); } return(returnType, isConstant); }
public static byte[] ConvertIntegerToByteArray(object integer, IntType intType) { byte[] intBytes = null; switch (intType) { case IntType.Int16: intBytes = BitConverter.GetBytes((short)integer); break; case IntType.Int32: intBytes = BitConverter.GetBytes((int)integer); break; case IntType.Int64: intBytes = BitConverter.GetBytes((long)integer); break; } return(intBytes); }
public BaseAnalysisTest(IPythonInterpreter interpreter) { Interpreter = interpreter; PyObjectType = Interpreter.GetBuiltinType(BuiltinTypeId.Object); IntType = Interpreter.GetBuiltinType(BuiltinTypeId.Int); ComplexType = Interpreter.GetBuiltinType(BuiltinTypeId.Complex); StringType = Interpreter.GetBuiltinType(BuiltinTypeId.Str); FloatType = Interpreter.GetBuiltinType(BuiltinTypeId.Float); TypeType = Interpreter.GetBuiltinType(BuiltinTypeId.Type); ListType = Interpreter.GetBuiltinType(BuiltinTypeId.List); TupleType = Interpreter.GetBuiltinType(BuiltinTypeId.Tuple); BoolType = Interpreter.GetBuiltinType(BuiltinTypeId.Bool); FunctionType = Interpreter.GetBuiltinType(BuiltinTypeId.Function); GeneratorType = Interpreter.GetBuiltinType(BuiltinTypeId.Generator); _objectMembers = PyObjectType.GetMemberNames(IronPythonModuleContext.DontShowClrInstance).ToArray(); _strMembers = StringType.GetMemberNames(IronPythonModuleContext.DontShowClrInstance).ToArray(); _listMembers = ListType.GetMemberNames(IronPythonModuleContext.DontShowClrInstance).ToArray(); _intMembers = IntType.GetMemberNames(IronPythonModuleContext.DontShowClrInstance).ToArray(); _functionMembers = FunctionType.GetMemberNames(IronPythonModuleContext.DontShowClrInstance).ToArray(); }
public static Operand GetExtendedM(ArmEmitterContext context, int rm, IntType type) { Operand value = GetIntOrZR(context, rm); switch (type) { case IntType.UInt8: value = context.ZeroExtend8(value.Type, value); break; case IntType.UInt16: value = context.ZeroExtend16(value.Type, value); break; case IntType.UInt32: value = context.ZeroExtend32(value.Type, value); break; case IntType.Int8: value = context.SignExtend8(value.Type, value); break; case IntType.Int16: value = context.SignExtend16(value.Type, value); break; case IntType.Int32: value = context.SignExtend32(value.Type, value); break; } return(value); }
/// <summary> /// Int Setting /// </summary> public Setting(IntType Type, string Name, Func <int> Get, Action <int> Set, int?Min = null, int?Max = null, Action <Action <int> > GetSetMin = null, Action <Action <int> > GetSetMax = null, int?Standart = null) { this.Name = Name; this.Type = Type switch { IntType.Picker => SetType.IntPicker, IntType.Slider => SetType.IntSlider, _ => throw new Exception() }; this.GetInt = Get; this.SetInt = Set; if (Standart.HasValue) { this.Reset = () => Set(Standart.Value); } this.Param1 = Min; this.Param2 = Max; this.GetSetMinInt = GetSetMin; this.GetSetMaxInt = GetSetMax; }
static SupportTypeUtil() { IType type = new IntType(); _supportTypeMap.Add(type.lowerName, type); _suportTypeList.Add(type.realName); type = new FloatType(); _supportTypeMap.Add(type.lowerName, type); _suportTypeList.Add(type.realName); type = new StringType(); _supportTypeMap.Add(type.lowerName, type); _suportTypeList.Add(type.realName); type = new ListIntType(); _supportTypeMap.Add(type.lowerName, type); _suportTypeList.Add(type.realName); type = new ListStringType(); _supportTypeMap.Add(type.lowerName, type); _suportTypeList.Add(type.realName); type = new ListFloatType(); _supportTypeMap.Add(type.lowerName, type); _suportTypeList.Add(type.realName); type = new Vector2Type(); _supportTypeMap.Add(type.lowerName, type); _suportTypeList.Add(type.realName); type = new Vector3Type(); _supportTypeMap.Add(type.lowerName, type); _suportTypeList.Add(type.realName); type = new DesType(); _supportTypeMap.Add(type.lowerName, type); _suportTypeList.Add(type.realName); type = new DictionaryIntIntType(); _supportTypeMap.Add(type.lowerName, type); _suportTypeList.Add(type.realName); type = new DictionaryIntStringType(); _supportTypeMap.Add(type.lowerName, type); _suportTypeList.Add(type.realName); type = new ListListStringType(); _supportTypeMap.Add(type.lowerName, type); _suportTypeList.Add(type.realName); }
public void EmitCast(IntType intType) { switch (intType) { case IntType.UInt8: Emit(OpCodes.Conv_U1); break; case IntType.UInt16: Emit(OpCodes.Conv_U2); break; case IntType.UInt32: Emit(OpCodes.Conv_U4); break; case IntType.UInt64: Emit(OpCodes.Conv_U8); break; case IntType.Int8: Emit(OpCodes.Conv_I1); break; case IntType.Int16: Emit(OpCodes.Conv_I2); break; case IntType.Int32: Emit(OpCodes.Conv_I4); break; case IntType.Int64: Emit(OpCodes.Conv_I8); break; } bool sz64 = CurrOp.RegisterSize != RegisterSize.Int32; if (sz64 == (intType == IntType.UInt64 || intType == IntType.Int64)) { return; } if (sz64) { Emit(intType >= IntType.Int8 ? OpCodes.Conv_I8 : OpCodes.Conv_U8); } else { Emit(OpCodes.Conv_U4); } }
// Update is used to set features regardless the active behaviour. void Update() { // Activate/deactivate aim by input. if (Input.GetAxisRaw(aimButton) != 0 && !aim) { StartCoroutine(ToggleAimOn()); if (!item.activeInHierarchy && data.database.GetData <IntType>("Data", "Player", "Pokeballs").Value > 0) { item.SetActive(true); } } else if (aim && Input.GetAxisRaw(aimButton) == 0) { StartCoroutine(ToggleAimOff()); item.SetActive(false); } if (Input.GetButton("Fire1") && item.activeInHierarchy) { value = data.database.GetData <IntType>("Data", "Player", "Pokeballs"); value.Value = value.Value - 1; item.SetActive(false); GameObject pokeBall = Instantiate(pokeBallContainer, item.transform.position, item.transform.rotation); pokeBall.GetComponent <Rigidbody>().AddForce(Camera.main.ViewportPointToRay(new Vector3(0.47f, 0.55f, 0f)).direction *throwForce, ForceMode.Impulse); StartCoroutine(PokeballCheck(pokeBall)); } // No sprinting while aiming. canSprint = !aim; // Toggle camera aim position left or right, switching shoulders. if (aim && Input.GetButtonDown(shoulderButton)) { aimCamOffset.x = aimCamOffset.x * (-1); aimPivotOffset.x = aimPivotOffset.x * (-1); } // Set aim boolean on the Animator Controller. behaviourManager.GetAnim.SetBool(aimBool, aim); }
public override (IType ReturnType, bool IsConstant) Invocation(IExpression[] args, SourceRange source, DiagnosticsReport diagnostics) { var returnType = new IntType(source); if (args.Length != 1) { diagnostics.AddError($"Expected 1 argument, found {args.Length}", source); } if (args.Length < 1) { return(returnType, false); } var arg = args[0]; if (arg.Type is not(EnumType or ErrorType)) { diagnostics.AddError($"Argument 1: cannot pass '{arg.Type}' to ENUM_TO_INT parameter, expected enum value", arg.Source); } return(returnType, arg.IsConstant); }
/// <summary> /// The first Operand is a IntType so the second must be promotable in such way that the whole operation must have sense. /// Implements a double dispatch pattern. /// </summary> /// <param name="firstOperand">an IntType to perform a binary arithmetical operatin with. The second operator must /// be promotable to IntType, StringType, or DoubleType</param> /// <returns>A TypeExpression if the operation makes sense, otherwise if showMessages is true, an error is raised</returns> public override object Exec(IntType firstOperand, object arg) { if ((int)this.secondOperand.AcceptOperation(new PromotionLevelOperation(firstOperand), arg) != -1) { if (secondOperand is TypeVariable && ((TypeVariable)secondOperand).Substitution == null) { if (methodAnalyzed != null) { // * A constraint is added to the method analyzed ArithmeticConstraint constraint = new ArithmeticConstraint(firstOperand, secondOperand, binaryOperator, location); methodAnalyzed.AddConstraint(constraint); return(constraint.ReturnType); } } return(IntType.Instance); } if (this.binaryOperator.Equals(ArithmeticOperator.Plus) && (bool)this.secondOperand.AcceptOperation(new EquivalentOperation(StringType.Instance), arg)) { return(StringType.Instance); } return(this.secondOperand.AcceptOperation(ArithmeticalOperation.Create(firstOperand, this.binaryOperator, this.methodAnalyzed, this.showErrorMessage, this.location), arg)); }
public IOperand EvaluateExpression(IEnumerable <string> tokens) { this.machineStack.Clear(); if (tokens == null) { throw new ArgumentNullException(); } foreach (var token in tokens) { if (operationTable.Contains(token)) { var operation = operationFactory.CreateOperation(token); EvaluateOperation(operation); continue; } try { var operand = IntType.Parse(token); this.machineStack.Push(operand); } catch (ArgumentException) { throw new InvalidMathematicalExpressionException( string.Format(ErrorMessages.UnrecognizedElement, token)); } } if (this.machineStack.Count != 1) { throw new InvalidMathematicalExpressionException(); } return(this.machineStack.Pop()); }
public void InstallComponent(Control textBox, DataType dtype) { if (typeof(StringType).IsAssignableFrom(dtype.GetType())) { StringType itype = (StringType)dtype; int max = itype.GetMaxLength(); SetControlTextLen(textBox, max); return; } else if (typeof(IntType).IsAssignableFrom(dtype.GetType())) { IntType itype = (IntType)dtype; SetControlTextLen(textBox, (int)Math.Ceiling(Math.Log10(itype.GetMaxValue()))); return; } else if (typeof(DoubleType).IsAssignableFrom(dtype.GetType())) { //DoubleType dbltype=(DoubleType)dtype; SetControlTextLen(textBox, 50); //textBox.KeyPress+=new KeyPressEventHandler(DoubleTextBox_KeyPress); return; } else if (typeof(DateTimeType).IsAssignableFrom(dtype.GetType())) { return; } else if (typeof(TimeType).IsAssignableFrom(dtype.GetType())) { return; } else if (typeof(BooleanType).IsAssignableFrom(dtype.GetType())) { return; } throw new UnsupportedOperationException(); }
public async Task SchemaTypeReference_With() { // arrange StringType stringType = await CreateTypeAsync <StringType>(); IntType intType = await CreateTypeAsync <IntType>(); SchemaTypeReference typeReference1 = TypeReference.Create( stringType, scope: "foo", nullable: new[] { true }); // act SchemaTypeReference typeReference2 = typeReference1.With( intType, scope: "bar", nullable: new[] { false }); // assert Assert.Equal(intType, typeReference2.Type); Assert.Equal(TypeContext.None, typeReference2.Context); Assert.Equal("bar", typeReference2.Scope); Assert.Collection(typeReference2.Nullable !, Assert.False); }
public override object Exec(IntType firstOperand, object arg) { // * Int type and bounded type variable if (TypeExpression.As <IntType>(this.secondOperand) != null) { return(0); } // * Double type and bounded type variable if (TypeExpression.As <DoubleType>(this.secondOperand) != null) { return(1); } // * WriteType variable TypeVariable typeVariable = this.secondOperand as TypeVariable; if (typeVariable != null && typeVariable.Substitution == null) { return(0); } // * Union type UnionType unionType = TypeExpression.As <UnionType>(this.secondOperand); if (unionType != null) { return(unionType.SuperType(firstOperand)); } // * Field type and bounded type variable FieldType fieldType = TypeExpression.As <FieldType>(this.secondOperand); if (fieldType != null) { return(firstOperand.AcceptOperation(new PromotionLevelOperation(fieldType.FieldTypeExpression), arg)); } // * Use the BCL object oriented approach return(firstOperand.AsClassType().AcceptOperation(this, arg)); }
private static void EmitF2i(ShaderIrBlock Block, long OpCode, ShaderOper Oper) { IntType Type = GetIntType(OpCode); if (Type == IntType.U64 || Type == IntType.S64) { //TODO: 64-bits support. //Note: GLSL doesn't support 64-bits integers. throw new NotImplementedException(); } bool NegA = ((OpCode >> 45) & 1) != 0; bool AbsA = ((OpCode >> 49) & 1) != 0; ShaderIrNode OperA; switch (Oper) { case ShaderOper.CR: OperA = GetOperCbuf34(OpCode); break; case ShaderOper.Immf: OperA = GetOperImmf19_20(OpCode); break; case ShaderOper.RR: OperA = GetOperGpr20(OpCode); break; default: throw new ArgumentException(nameof(Oper)); } OperA = GetAluFabsFneg(OperA, AbsA, NegA); ShaderIrInst RoundInst = GetRoundInst(OpCode); if (RoundInst != ShaderIrInst.Invalid) { OperA = new ShaderIrOp(RoundInst, OperA); } bool Signed = Type >= IntType.S8; int Size = 8 << ((int)Type & 3); if (Size < 32) { uint Mask = uint.MaxValue >> (32 - Size); float CMin = 0; float CMax = Mask; if (Signed) { uint HalfMask = Mask >> 1; CMin -= HalfMask + 1; CMax = HalfMask; } ShaderIrOperImmf IMin = new ShaderIrOperImmf(CMin); ShaderIrOperImmf IMax = new ShaderIrOperImmf(CMax); OperA = new ShaderIrOp(ShaderIrInst.Fclamp, OperA, IMin, IMax); } ShaderIrInst Inst = Signed ? ShaderIrInst.Ftos : ShaderIrInst.Ftou; ShaderIrNode Op = new ShaderIrOp(Inst, OperA); Block.AddNode(GetPredNode(new ShaderIrAsg(GetOperGpr0(OpCode), Op), OpCode)); }
private static void EmitI2i(ShaderIrBlock Block, long OpCode, ShaderOper Oper) { IntType Type = GetIntType(OpCode); if (Type == IntType.U64 || Type == IntType.S64) { //TODO: 64-bits support. //Note: GLSL doesn't support 64-bits integers. throw new NotImplementedException(); } int Sel = (int)(OpCode >> 41) & 3; bool NegA = ((OpCode >> 45) & 1) != 0; bool AbsA = ((OpCode >> 49) & 1) != 0; bool SatA = ((OpCode >> 50) & 1) != 0; ShaderIrNode OperA; switch (Oper) { case ShaderOper.CR: OperA = GetOperCbuf34(OpCode); break; case ShaderOper.Immf: OperA = GetOperImmf19_20(OpCode); break; case ShaderOper.RR: OperA = GetOperGpr20(OpCode); break; default: throw new ArgumentException(nameof(Oper)); } OperA = GetAluIabsIneg(OperA, AbsA, NegA); bool Signed = Type >= IntType.S8; int Shift = Sel * 8; int Size = 8 << ((int)Type & 3); if (Shift != 0) { OperA = new ShaderIrOp(ShaderIrInst.Asr, OperA, new ShaderIrOperImm(Shift)); } if (Size < 32) { uint Mask = uint.MaxValue >> (32 - Size); if (SatA) { uint CMin = 0; uint CMax = Mask; if (Signed) { uint HalfMask = Mask >> 1; CMin -= HalfMask + 1; CMax = HalfMask; } ShaderIrOperImm IMin = new ShaderIrOperImm((int)CMin); ShaderIrOperImm IMax = new ShaderIrOperImm((int)CMax); OperA = new ShaderIrOp(Signed ? ShaderIrInst.Clamps : ShaderIrInst.Clampu, OperA, IMin, IMax); } else { OperA = ExtendTo32(OperA, Signed, Size); } } Block.AddNode(GetPredNode(new ShaderIrAsg(GetOperGpr0(OpCode), OperA), OpCode)); }
public virtual TReturn Visit(IntType node, TParam param) { return(DefaultReturn); }
public virtual TReturn Visit(IntType node, TParam param) => throw new NotImplementedException();
public virtual void ShouldDecodeStringLength() { IntType intType = new IntType("int"); var result = intType.Decode<BigInteger>("0x0000000000000000000000000000000000000000000000000000000000000020"); Assert.Equal(new BigInteger(32), result); }
public virtual void ShouldEncode(string value, string hexExpected) { IntType intType = new IntType("int"); var result = intType.Encode(BigInteger.Parse(value)); Assert.Equal(hexExpected, "0x" + result.ToHex()); }
void ConstAtomExpression(out Expression e, bool allowSemi, bool allowLambda) { Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ x; BigInteger n; Basetypes.BigDec d; e = dummyExpr; Type toType = null; switch (la.kind) { case 131: { Get(); e = new LiteralExpr(t, false); break; } case 132: { Get(); e = new LiteralExpr(t, true); break; } case 133: { Get(); e = new LiteralExpr(t); break; } case 2: case 3: { Nat(out n); e = new LiteralExpr(t, n); break; } case 4: { Dec(out d); e = new LiteralExpr(t, d); break; } case 19: { Get(); e = new CharLiteralExpr(t, t.val.Substring(1, t.val.Length - 2)); break; } case 20: { Get(); bool isVerbatimString; string s = Util.RemoveParsedStringQuotes(t.val, out isVerbatimString); e = new StringLiteralExpr(t, s, isVerbatimString); break; } case 134: { Get(); e = new ThisExpr(t); break; } case 135: { Get(); x = t; Expect(50); Expression(out e, true, true); Expect(51); e = new UnaryOpExpr(x, UnaryOpExpr.Opcode.Fresh, e); break; } case 136: { Get(); x = t; Expect(50); Expression(out e, true, true); Expect(51); e = new OldExpr(x, e); break; } case 23: { Get(); x = t; Expression(out e, true, true); e = new UnaryOpExpr(x, UnaryOpExpr.Opcode.Cardinality, e); Expect(23); break; } case 8: case 10: { if (la.kind == 8) { Get(); x = t; toType = new IntType(); } else { Get(); x = t; toType = new RealType(); } Expect(50); Expression(out e, true, true); Expect(51); e = new ConversionExpr(x, e, toType); break; } case 50: { ParensExpression(out e, allowSemi, allowLambda); break; } default: SynErr(234); break; } }
Interval[] getInterval(IntType type, Func<Intervals> defValue, Func<Admin.IntervalsConfig, Intervals> cfgValue) { Interval[] res; using (SqlConnection conn = new SqlConnection(connString)) { conn.Open(); using (var rdr = getReader(sql_company_IntervalsConfig, companyId, conn)) { var row = rdr.Cast<IDataRecord>().First(); if (row.IsDBNull(0)) res = defValue().Items; else res = cfgValue(IntervalsConfig.fromString(rdr.GetString(0))).Items; } } for (int i = 0; i <= res.Length - 1; i++) { res[i].id = i; res[i].type = type; res[i].items = res; } return res; }
public virtual void ShouldEncodeInt() { IntType intType = new IntType("int"); var result = intType.Encode(69).ToHex(); Assert.Equal("0000000000000000000000000000000000000000000000000000000000000045", result); }
public virtual void ShouldDecode(string expected, string hex) { IntType intType = new IntType("int"); var result = intType.Decode<BigInteger>(hex); Assert.Equal(expected, result.ToString()); }
public virtual void ShouldEncodeNegativeInt() { IntType intType = new IntType("int"); var result = intType.Encode(-1234567).ToHex(); Assert.Equal("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed2979", result); }
public virtual void ShouldDecodeNegativeIntString() { IntType intType = new IntType("int"); var result = intType.Decode<BigInteger>("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed2979"); Assert.Equal(new BigInteger(-1234567), result); }
void TypeAndToken(out IToken tok, out Type ty, bool inExpressionContext) { Contract.Ensures(Contract.ValueAtReturn(out tok)!=null); Contract.Ensures(Contract.ValueAtReturn(out ty) != null); tok = Token.NoToken; ty = new BoolType(); /*keep compiler happy*/ List<Type> gt; List<Type> tupleArgTypes = null; switch (la.kind) { case 7: { Get(); tok = t; break; } case 8: { Get(); tok = t; ty = new CharType(); break; } case 9: { Get(); tok = t; ty = new IntType(); break; } case 10: { Get(); tok = t; ty = new UserDefinedType(tok, tok.val, null); break; } case 11: { Get(); tok = t; ty = new RealType(); break; } case 6: { Get(); tok = t; int w = StringToInt(tok.val.Substring(2), 0, "bitvectors that wide"); ty = new BitvectorType(w); break; } case 12: { Get(); tok = t; ty = new ObjectType(); break; } case 14: { Get(); tok = t; OptGenericInstantiation(out gt, inExpressionContext); if (gt != null && gt.Count > 1) { SemErr("set type expects only one type argument"); } ty = new SetType(true, gt != null ?gt[0] : null); break; } case 15: { Get(); tok = t; OptGenericInstantiation(out gt, inExpressionContext); if (gt != null && gt.Count > 1) { SemErr("set type expects only one type argument"); } ty = new SetType(false, gt != null ? gt[0] : null); break; } case 16: { Get(); tok = t; OptGenericInstantiation(out gt, inExpressionContext); if (gt != null && gt.Count > 1) { SemErr("multiset type expects only one type argument"); } ty = new MultiSetType(gt != null ? gt[0] : null); break; } case 17: { Get(); tok = t; OptGenericInstantiation(out gt, inExpressionContext); if (gt != null && gt.Count > 1) { SemErr("seq type expects only one type argument"); } ty = new SeqType(gt != null ? gt[0] : null); break; } case 13: { Get(); tok = t; ty = new UserDefinedType(tok, tok.val, null); break; } case 18: { Get(); tok = t; OptGenericInstantiation(out gt, inExpressionContext); if (gt == null) { ty = new MapType(true, null, null); } else if (gt.Count != 2) { SemErr("map type expects two type arguments"); ty = new MapType(true, gt[0], gt.Count == 1 ? new InferredTypeProxy() : gt[1]); } else { ty = new MapType(true, gt[0], gt[1]); } break; } case 19: { Get(); tok = t; OptGenericInstantiation(out gt, inExpressionContext); if (gt == null) { ty = new MapType(false, null, null); } else if (gt.Count != 2) { SemErr("imap type expects two type arguments"); ty = new MapType(false, gt[0], gt.Count == 1 ? new InferredTypeProxy() : gt[1]); } else { ty = new MapType(false, gt[0], gt[1]); } break; } case 5: { Get(); tok = t; OptGenericInstantiation(out gt, inExpressionContext); int dims = StringToInt(tok.val.Substring(5), 1, "arrays of that many dimensions"); ty = theBuiltIns.ArrayType(tok, dims, gt, true); break; } case 54: { Get(); tok = t; tupleArgTypes = new List<Type>(); if (StartOf(6)) { Type(out ty); tupleArgTypes.Add(ty); while (la.kind == 23) { Get(); Type(out ty); tupleArgTypes.Add(ty); } } Expect(55); if (tupleArgTypes.Count == 1) { // just return the type 'ty' } else { var dims = tupleArgTypes.Count; var tmp = theBuiltIns.TupleType(tok, dims, true); // make sure the tuple type exists ty = new UserDefinedType(tok, BuiltIns.TupleTypeName(dims), dims == 0 ? null : tupleArgTypes); } break; } case 1: { Expression e; NameSegmentForTypeName(out e, inExpressionContext); tok = t; while (la.kind == 28) { Get(); Expect(1); tok = t; List<Type> typeArgs; OptGenericInstantiation(out typeArgs, inExpressionContext); e = new ExprDotName(tok, e, tok.val, typeArgs); } ty = new UserDefinedType(e.tok, e); break; } default: SynErr(182); break; } if (IsArrow()) { Expect(32); tok = t; Type t2; Type(out t2); if (tupleArgTypes != null) { gt = tupleArgTypes; } else { gt = new List<Type>{ ty }; } ty = new ArrowType(tok, gt, t2); theBuiltIns.CreateArrowTypeDecl(gt.Count); } }
public void ValidateValue(BigInteger value) { if (_signed && value > IntType.GetMaxSignedValue(_size)) { throw new ArgumentOutOfRangeException(nameof(value), $"Signed SmartContract integer must not exceed maximum value for int{_size}: {IntType.GetMaxSignedValue(_size).ToString()}. Current value is: {value}"); } if (_signed && value < IntType.GetMinSignedValue(_size)) { throw new ArgumentOutOfRangeException(nameof(value), $"Signed SmartContract integer must not be less than the minimum value for int{_size}: {IntType.GetMinSignedValue(_size)}. Current value is: {value}"); } if (!_signed && value > IntType.GetMaxUnSignedValue(_size)) { throw new ArgumentOutOfRangeException(nameof(value), $"Unsigned SmartContract integer must not exceed maximum value for uint{_size}: {IntType.GetMaxUnSignedValue(_size)}. Current value is: {value}"); } if (!_signed && value < IntType.MIN_UINT_VALUE) { throw new ArgumentOutOfRangeException(nameof(value), $"Unsigned SmartContract integer must not be less than the minimum value of uint: {IntType.MIN_UINT_VALUE.ToString()}. Current value is: {value}"); } }
void TypeAndToken(out IToken tok, out Type ty) { Contract.Ensures(Contract.ValueAtReturn(out tok)!=null); Contract.Ensures(Contract.ValueAtReturn(out ty) != null); tok = Token.NoToken; ty = new BoolType(); /*keep compiler happy*/ List<Type> gt; List<Type> tupleArgTypes = null; switch (la.kind) { case 6: { Get(); tok = t; break; } case 7: { Get(); tok = t; ty = new CharType(); break; } case 9: { Get(); tok = t; ty = new NatType(); break; } case 8: { Get(); tok = t; ty = new IntType(); break; } case 10: { Get(); tok = t; ty = new RealType(); break; } case 11: { Get(); tok = t; ty = new ObjectType(); break; } case 13: { Get(); tok = t; gt = new List<Type>(); if (la.kind == 52) { GenericInstantiation(gt); } if (gt.Count > 1) { SemErr("set type expects only one type argument"); } ty = new SetType(true, gt.Count == 1 ? gt[0] : null); break; } case 14: { Get(); tok = t; gt = new List<Type>(); if (la.kind == 52) { GenericInstantiation(gt); } if (gt.Count > 1) { SemErr("set type expects only one type argument"); } ty = new SetType(false, gt.Count == 1 ? gt[0] : null); break; } case 15: { Get(); tok = t; gt = new List<Type>(); if (la.kind == 52) { GenericInstantiation(gt); } if (gt.Count > 1) { SemErr("multiset type expects only one type argument"); } ty = new MultiSetType(gt.Count == 1 ? gt[0] : null); break; } case 16: { Get(); tok = t; gt = new List<Type>(); if (la.kind == 52) { GenericInstantiation(gt); } if (gt.Count > 1) { SemErr("seq type expects only one type argument"); } ty = new SeqType(gt.Count == 1 ? gt[0] : null); break; } case 12: { Get(); tok = t; ty = new UserDefinedType(tok, tok.val, null); break; } case 17: { Get(); tok = t; gt = new List<Type>(); if (la.kind == 52) { GenericInstantiation(gt); } if (gt.Count == 0) { ty = new MapType(true, null, null); } else if (gt.Count != 2) { SemErr("map type expects two type arguments"); ty = new MapType(true, gt[0], gt.Count == 1 ? new InferredTypeProxy() : gt[1]); } else { ty = new MapType(true, gt[0], gt[1]); } break; } case 18: { Get(); tok = t; gt = new List<Type>(); if (la.kind == 52) { GenericInstantiation(gt); } if (gt.Count == 0) { ty = new MapType(false, null, null); } else if (gt.Count != 2) { SemErr("imap type expects two type arguments"); ty = new MapType(false, gt[0], gt.Count == 1 ? new InferredTypeProxy() : gt[1]); } else { ty = new MapType(false, gt[0], gt[1]); } break; } case 5: { Get(); tok = t; gt = null; if (la.kind == 52) { gt = new List<Type>(); GenericInstantiation(gt); } int dims = tok.val.Length == 5 ? 1 : int.Parse(tok.val.Substring(5)); ty = theBuiltIns.ArrayType(tok, dims, gt, true); break; } case 50: { Get(); tok = t; tupleArgTypes = new List<Type>(); if (StartOf(3)) { Type(out ty); tupleArgTypes.Add(ty); while (la.kind == 22) { Get(); Type(out ty); tupleArgTypes.Add(ty); } } Expect(51); if (tupleArgTypes.Count == 1) { // just return the type 'ty' } else { var dims = tupleArgTypes.Count; var tmp = theBuiltIns.TupleType(tok, dims, true); // make sure the tuple type exists ty = new UserDefinedType(tok, BuiltIns.TupleTypeName(dims), dims == 0 ? null : tupleArgTypes); } break; } case 1: { Expression e; tok = t; NameSegmentForTypeName(out e); tok = t; while (la.kind == 27) { Get(); Expect(1); tok = t; List<Type> typeArgs = null; if (la.kind == 52) { typeArgs = new List<Type>(); GenericInstantiation(typeArgs); } e = new ExprDotName(tok, e, tok.val, typeArgs); } ty = new UserDefinedType(e.tok, e); break; } default: SynErr(164); break; } if (la.kind == 30) { Type t2; Get(); tok = t; Type(out t2); if (tupleArgTypes != null) { gt = tupleArgTypes; } else { gt = new List<Type>{ ty }; } ty = new ArrowType(tok, gt, t2); theBuiltIns.CreateArrowTypeDecl(gt.Count); } }
public IValue Visit(IntType intType) { return(null); }
public virtual void ShouldDecode0x989680() { IntType intType = new IntType("int"); var bytes = "0x00989680".HexToByteArray(); var result = intType.Decode<BigInteger>(bytes); Assert.Equal(new BigInteger(10000000), result); }
void ConstAtomExpression(out Expression e, bool allowSemi, bool allowLambda) { Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ x; BigInteger n; Basetypes.BigDec d; e = dummyExpr; Type toType = null; switch (la.kind) { case 138: { Get(); e = new LiteralExpr(t, false); break; } case 139: { Get(); e = new LiteralExpr(t, true); break; } case 140: { Get(); e = new LiteralExpr(t); break; } case 2: case 3: { Nat(out n); e = new LiteralExpr(t, n); break; } case 4: { Dec(out d); e = new LiteralExpr(t, d); break; } case 20: { Get(); e = new CharLiteralExpr(t, t.val.Substring(1, t.val.Length - 2)); break; } case 21: { Get(); bool isVerbatimString; string s = Util.RemoveParsedStringQuotes(t.val, out isVerbatimString); e = new StringLiteralExpr(t, s, isVerbatimString); break; } case 141: { Get(); e = new ThisExpr(t); break; } case 142: { Get(); x = t; Expect(54); Expression(out e, true, true); Expect(55); e = new UnaryOpExpr(x, UnaryOpExpr.Opcode.Fresh, e); break; } case 143: { Get(); x = t; Expect(54); Expression(out e, true, true); Expect(55); e = new UnaryOpExpr(x, UnaryOpExpr.Opcode.Allocated, e); break; } case 144: { Get(); x = t; FrameExpression fe; var mod = new List<FrameExpression>(); Expect(54); FrameExpression(out fe, false, false); mod.Add(fe); while (la.kind == 23) { Get(); FrameExpression(out fe, false, false); mod.Add(fe); } Expect(55); e = new UnchangedExpr(x, mod); break; } case 145: { Get(); x = t; Expect(54); Expression(out e, true, true); Expect(55); e = new OldExpr(x, e); break; } case 24: { Get(); x = t; Expression(out e, true, true, false); e = new UnaryOpExpr(x, UnaryOpExpr.Opcode.Cardinality, e); Expect(24); break; } case 9: case 11: { if (la.kind == 9) { Get(); x = t; toType = new IntType(); } else { Get(); x = t; toType = new RealType(); } errors.Deprecated(t, string.Format("the syntax \"{0}(expr)\" for type conversions has been deprecated; the new syntax is \"expr as {0}\"", x.val)); Expect(54); Expression(out e, true, true); Expect(55); e = new ConversionExpr(x, e, toType); break; } case 54: { ParensExpression(out e, allowSemi, allowLambda); break; } default: SynErr(262); break; } }
public virtual void ShouldEncodeStrings() { IntType intType = new IntType("int"); var result2 = intType.Encode("1234567890abcdef1234567890abcdef12345678").ToHex(); Assert.Equal("0000000000000000000000001234567890abcdef1234567890abcdef12345678", result2); }