private bool InternalAddItem(TItem item, TOpEnum op, InsertionBehavior behavior) { if (item == null) { return(false); } var itemDataType = GetItemOrgDataType(item); if (itemDataType != null) { if (_matchedItemsType != null) //本块内所含各项与项,项与块整集之间的匹配类型 { var tmpType = TypeMatcher.MatchDataTtype(_matchedItemsType, itemDataType, out _); if (tmpType != null) { _matchedItemsType = tmpType; } else //匹配失败 { throw new ArithmeticException(MsgStrings.InvalidTypeConvert(itemDataType, _matchedItemsType)); } } else { _matchedItemsType = itemDataType; //首次加入的具有非空值项, } } ReMatchDataType(); _itemVersion++; _hashCodeVersion++; return(m_items.Add(op, item, behavior)); }
public void MatchMethod() { it("should return true if the given instance is an instance of the expected type", () => { typeMatcher = new TypeMatcher(typeof(string)); expect(typeMatcher.Match("Testing!")).toEqual(true); }); it("should return false if the given instance isn't an instance of the expected type", () => { typeMatcher = new TypeMatcher(typeof(int)); expect(typeMatcher.Match("Testing!")).toEqual(false); }); it("should set the actual property on the matcher", () => { Type stringType = typeof(string); EventArgs value = new EventArgs(); typeMatcher = new TypeMatcher(stringType); typeMatcher.Match(value); expect(typeMatcher.Expected).toBe(stringType); expect(typeMatcher.Actual).toBe(value); }); }
public void shouldMatchSimpleType() { TypeMatcher tm = new TypeMatcher(); bool result = tm.Match(typeof(MyClass), new TypeNameTree("IOCCTest.TypeMatcherTest+MyClass")); Assert.IsTrue(result); }
public void MatchesValueOfAssignableType() { Matcher m = new TypeMatcher(typeof(B)); Assert.IsTrue(m.Matches(new B()), "should match B"); Assert.IsTrue(m.Matches(new D()), "should match D"); }
internal void InferResultType(ComputationContext ctx) { if (!this.resultTypeCandidates.Any()) // no returns { setResultParameter(ctx.Env.UnitType.InstanceOf.NameOf); } else { IEntityInstance common = this.resultTypeCandidates.First(); foreach (IEntityInstance candidate in this.resultTypeCandidates.Skip(1)) { if (!TypeMatcher.LowestCommonAncestor(ctx, common, candidate, out common)) { ctx.AddError(ErrorCode.CannotInferResultType, this); setResultParameter(Environment.JokerInstance.NameOf); return; } } foreach (IEntityInstance candidate in this.resultTypeCandidates) { // it is tempting to allowing conversions here, but it would mean that we have back to all "returns" // to apply such conversions, besides such fluent result type is a bit of a stretch TypeMatch match = candidate.MatchesTarget(ctx, common, TypeMatching.Create(ctx.Env.Options.InterfaceDuckTyping, allowSlicing: false)); if (match != TypeMatch.Same && match != TypeMatch.Substitute) { ctx.AddError(ErrorCode.CannotInferResultType, this); setResultParameter(Environment.JokerInstance.NameOf); return; } } setResultParameter(common.NameOf); } }
public IErrorReporter LowestCommonAncestor() { NameResolver resolver = null; foreach (var mutability in Options.AllMutabilityModes) { var env = Language.Environment.Create(new Options() { }.SetMutability(mutability)); var root_ns = env.Root; var abc_type = root_ns.AddBuilder(TypeBuilder.Create("ABC")); var foo_type = root_ns.AddBuilder(TypeBuilder.Create("Foo").Parents(NameReference.Create("ABC"))); var bar_type = root_ns.AddBuilder(TypeBuilder.Create("Bar").Parents(NameReference.Create("ABC"))); var deriv_type = root_ns.AddBuilder(TypeBuilder.Create("Deriv").Parents(NameReference.Create("Foo"))); var deriv_ref = root_ns.AddNode(NameReference.Create("Deriv")); var bar_ref = root_ns.AddNode(NameReference.Create("Bar")); var abc_ref = root_ns.AddNode(NameReference.Create("ABC")); resolver = NameResolver.Create(env); Assert.AreEqual(bar_type, bar_ref.Binding.Match.Instance.Target); Assert.AreEqual(deriv_type, deriv_ref.Binding.Match.Instance.Target); Assert.AreEqual(abc_type, abc_ref.Binding.Match.Instance.Target); bool found = TypeMatcher.LowestCommonAncestor(resolver.Context, bar_ref.Binding.Match.Instance, deriv_ref.Binding.Match.Instance, out IEntityInstance common); Assert.IsTrue(found); Assert.IsTrue(abc_ref.Binding.Match.Instance.HasSameCore(common)); } return(resolver); }
private bool computeLowestCommonAncestor(ComputationContext ctx, ref IEntityInstance eval, ref IEntityInstance aggregate) { if (!TypeMatcher.LowestCommonAncestor(ctx, eval, Next.Evaluation.Components, out eval)) { return(false); } else if (!TypeMatcher.LowestCommonAncestor(ctx, aggregate, Next.Evaluation.Aggregate, out aggregate)) { return(false); } else { foreach (IEvaluable part in new IEvaluable[] { Body, Next }) { if (part.Evaluation.Components.MatchesTarget(ctx, eval, TypeMatching.Create(ctx.Env.Options.InterfaceDuckTyping, allowSlicing: false)).IsMismatch()) { return(false); } if (part.Evaluation.Aggregate.MatchesTarget(ctx, aggregate, TypeMatching.Create(ctx.Env.Options.InterfaceDuckTyping, allowSlicing: false)).IsMismatch()) { return(false); } } } return(true); }
public void ShouldRejectBadlyFormedTypeSpec() { TypeMatcher tm = new TypeMatcher(); bool result = tm.Match(typeof(MyDerived2).BaseType , new TypeNameTree("<<>>,abc")); Assert.IsFalse(result); }
public void DoesNotMatchValueOfNonAssignableType() { Matcher m = new TypeMatcher(typeof(D)); Assert.IsFalse(m.Matches(new B()), "should not match B"); Assert.IsFalse(m.Matches(123), "should not match B"); Assert.IsFalse(m.Matches("hello, world"), "should not match B"); }
public void ShouldRejectNonMatchingTypes() { TypeMatcher tm = new TypeMatcher(); bool result = tm.Match(typeof(MyDerived2).BaseType , new TypeNameTree("IOCCTest.TypeMatcherTest+MyGeneric<int,IOCCTest.TypeMatcherTest+MyGeneric<System.Int32>>")); Assert.IsFalse(result); }
public void ShowStackTraceProperty() { it("should return false", () => { typeMatcher = new TypeMatcher(null); expect(typeMatcher.ShowStackTrace).toEqual(false); }); }
public void ShouldMatchSimpleGeneric() { TypeMatcher tm = new TypeMatcher(); bool result = tm.Match(typeof(MyDerived).BaseType , new TypeNameTree("IOCCTest.TypeMatcherTest+MyGeneric<System.Int32>")); Assert.IsTrue(result); }
public void MapMatcher_To_Differing_TypeMatcher_Returns_Different_Mapper() { TypeMatcher matcher1 = new TypeMatcher().AllOf(typeof(SupportView)); TypeMatcher matcher2 = new TypeMatcher().AllOf(typeof(Event)); object mapper1 = mediatorMap.MapMatcher(matcher1); object mapper2 = mediatorMap.MapMatcher(matcher2); Assert.That(mapper1, Is.Not.EqualTo(mapper2)); }
public void SetUp() { logger = new Mock <ILogging>(); handler = new Mock <IMediatorViewHandler>(); TypeMatcher matcher = new TypeMatcher().AllOf(typeof(SupportView)); filter = matcher.CreateTypeFilter(); mapper = new MediatorMapper(matcher.CreateTypeFilter(), handler.Object, logger.Object); }
public void TypeShouldNotMatchWhenNoNamespaceIsGiven(Type type, string typeName) { // Arrange var sut = new TypeMatcher(); // Act var actual = sut.MatchesType(type, typeName); // Arrange Assert.False(actual); }
public void TypeShouldMatchWhenFullNameIsGiven(Type type, string typeName) { // Arrange var sut = new TypeMatcher(); // Act var actual = sut.MatchesType(type, typeName); // Arrange Assert.True(actual); }
public override void Validate(ComputationContext ctx) { base.Validate(ctx); // we can do whatever but we cannot shake off the const/neutral off TypeMutability lhs_mutability = this.Lhs.Evaluation.Components.MutabilityOfType(ctx); TypeMutability rhs_mutability = this.RhsTypeName.Evaluation.Components.MutabilityOfType(ctx); if (!TypeMatcher.MutabilityMatches(ctx.Env.Options, lhs_mutability, rhs_mutability)) { ctx.ErrorManager.AddError(ErrorCode.TypeMismatch, this); } }
/// <summary> /// Validates a given value to match specified type. The type can be defined as a /// Schema, type, a type name or TypeCode When type is a Schema, it executes /// validation recursively against that Schema. /// </summary> /// <param name="path">a dot notation path to the value.</param> /// <param name="type">a type to match the value type</param> /// <param name="value">a value to be validated.</param> /// <param name="results">a list with validation results to add new results.</param> protected void PerformTypeValidation(string path, object type, object value, List <ValidationResult> results) { // If type it not defined then skip if (type == null) { return; } // Perform validation against schema var schema = type as Schema; if (schema != null) { schema.PerformValidation(path, value, results); return; } // If value is null then skip value = ObjectReader.GetValue(value); if (value == null) { return; } // Match types if (TypeMatcher.MatchType(type, value.GetType(), value)) { return; } // Match enum if (TypeMatcher.MatchEnum(type, value)) { return; } var name = path ?? "value"; var valueType = value.GetType(); // Generate type mismatch error results.Add( new ValidationResult( path, ValidationResultType.Error, "TYPE_MISMATCH", name + " type must be " + type + " but found " + valueType.Name, type, valueType.Name ) ); }
public void AssemblyVersionShouldBeIgnored() { // Arrange var sut = new TypeMatcher(); var type = typeof(string); var typeName = "System.String, System.Private.CoreLib, Version=1234.2.3.4"; // Act var actual = sut.MatchesType(type, typeName); // Assert Assert.True(actual); }
public void PublicKeyTokenShouldBeIgnored() { // Arrange var sut = new TypeMatcher(); var type = typeof(string); var typeName = "System.String, System.Private.CoreLib, Version=4.0.0.0, PublicKeyToken=abcdef0123456789"; // Act var actual = sut.MatchesType(type, typeName); // Assert Assert.True(actual); }
/// <summary> /// 用于批量填充Items重新匹配类型 /// </summary> /// <param name="items"></param> private void ReMatchItemsDataType(NodeOperatorPair <TOpEnum, TItem>[] items) { if (items != null && items.Length > 0) { int start; var count = items.Length; var item = items[0]?.Node; for (start = 1; start < count; start++) //拿到第一个有效项 { item = items[start]?.Node; if (item != null) { break; } } Type tmpType, lastType; lastType = GetItemOrgDataType(item); for (int i = start - 1; i < count; i++) { item = items[i]?.Node; tmpType = GetItemOrgDataType(item); if (tmpType != null) { if (lastType != null) { tmpType = TypeMatcher.MatchDataTtype(lastType, tmpType, out _); if (tmpType != null) { lastType = tmpType; } else//匹配失败 { throw new ArithmeticException(MsgStrings.InvalidTypeConvert(lastType, GetItemOrgDataType(item))); } } else { lastType = tmpType; } }//else 空值没有类型匹配 } _matchedItemsType = lastType; } else { _matchedItemsType = null; } ReMatchDataType(); }
public void GetFailureMessageMethod() { it("should return the correct message when the match is inverted", () => { typeMatcher = new TypeMatcher(typeof(string)); typeMatcher.Actual = typeof(int); expect(typeMatcher.GetFailureMessage(true)).toEqual("Expected System.Int32 not to be type of String"); }); it("should return the correct message when the match isn't inverted", () => { typeMatcher = new TypeMatcher(typeof(string)); typeMatcher.Actual = typeof(int); expect(typeMatcher.GetFailureMessage(false)).toEqual("Expected System.Int32 to be type of String"); }); }
public void TestTypeMatching() { var m = new TypeMatcher <string> { { Case.Is <string>(), s => s }, { Case.Is <StringBuilder>(), s => s.ToString() } }; string test1 = "string"; Assert.AreEqual("string", m.Match(test1)); StringBuilder test2 = new StringBuilder("StringBuilder"); Assert.AreEqual("StringBuilder", m.Match(test2)); }
public void TestTypeMatchingFluentSyntax() { var m = new TypeMatcher <string> { { Case.Is <string>(), s => s }, { Case.Is <StringBuilder>(), s => s.ToString() } }; var test1 = ((object)"string").ToM().Match(m); Assert.AreEqual("string", test1.Value); var test2 = ((object)new StringBuilder("StringBuilder")).ToM().Match(m); Assert.AreEqual("StringBuilder", test2.Value); }
/// <summary> /// 块更改后,进行重新匹配 /// </summary> /// <param name="changedBlockDataType"></param> private void ReMatchForSubBlocksChanged(Type changedBlockDataType) { if (m_blocks.Count == 0) { _matchedSubBlocksDataType = null; _matchedDataType = _matchedItemsType; return; } if (changedBlockDataType != null) { if (TypeMatcher.MatchDataTtype(_matchedSubBlocksDataType, changedBlockDataType, out _) != _matchedSubBlocksDataType) { ReMatchSubBlocksDataType(GetBlocks()); } } }
public override void Validate(ComputationContext ctx) { base.Validate(ctx); if (!ctx.Env.IsPointerLikeOfType(this.Lhs.Evaluation.Components)) { ctx.AddError(ErrorCode.CannotUseValueExpression, this.Lhs); } if (!ctx.Env.IsPointerLikeOfType(this.Rhs.Evaluation.Components)) { ctx.AddError(ErrorCode.CannotUseValueExpression, this.Rhs); } if (!TypeMatcher.InterchangeableTypes(ctx, this.Lhs.Evaluation.Components, this.Rhs.Evaluation.Components)) { ctx.ErrorManager.AddError(ErrorCode.TypeMismatch, this); } }
public static IEnumerable <TypeDefinition> AvailableTraits(this EntityInstance instance, ComputationContext ctx) { IEntityScope scope = instance.Target.Cast <TemplateDefinition>(); if (scope is TypeDefinition typedef) { foreach (TypeDefinition trait in typedef.AssociatedTraits) { // todo: once computed which traits fit maybe we could cache them within given instance? ConstraintMatch match = TypeMatcher.ArgumentsMatchConstraintsOf(ctx, trait.Name.Parameters, instance); if (match != ConstraintMatch.Yes) { continue; } yield return(trait); } } }
/*============================================================================*/ /* Private Functions */ /*============================================================================*/ private ITypeFilter CreateTypeFilter(Type[] allOf, Type[] anyOf = null, Type[] noneOf = null) { TypeMatcher matcher = new TypeMatcher(); if (allOf != null) { matcher.AllOf(allOf); } if (anyOf != null) { matcher.AnyOf(anyOf); } if (noneOf != null) { matcher.NoneOf(noneOf); } return(matcher.CreateTypeFilter()); }
public GobUpdater(ClientSession session) { this.session = session; this.deltaMatcher = new TypeMatcher() .Case <GobDelta.AdjustMovement>(Apply) .Case <GobDelta.Avatar>(Apply) .Case <GobDelta.Buddy>(Apply) .Case <GobDelta.Clear>(Apply) .Case <GobDelta.DrawOffset>(Apply) .Case <GobDelta.Follow>(Apply) .Case <GobDelta.Health>(Apply) .Case <GobDelta.Homing>(Apply) .Case <GobDelta.Layers>(Apply) .Case <GobDelta.Light>(Apply) .Case <GobDelta.Overlay>(Apply) .Case <GobDelta.Position>(Apply) .Case <GobDelta.Resource>(Apply) .Case <GobDelta.Speech>(Apply) .Case <GobDelta.StartMovement>(Apply); }
public override void Validate(ComputationContext ctx) { base.Validate(ctx); if (this.RhsTypeName.Evaluation.Components is EntityInstance rhs_type) { if (MatchTypes(ctx, this.Lhs.Evaluation.Components, this.RhsTypeName.Evaluation.Components)) { // checking if x (of String) is Object does not make sense ctx.ErrorManager.AddError(ErrorCode.IsTypeOfKnownTypes, this); } else { if (!TypeMatcher.InterchangeableTypes(ctx, this.Lhs.Evaluation.Components, this.RhsTypeName.Evaluation.Components)) { ctx.ErrorManager.AddError(ErrorCode.TypeMismatch, this); } foreach (EntityInstance instance in this.Lhs.Evaluation.Components.EnumerateAll()) { if (!instance.Target.IsType()) { continue; } // this error is valid as long we don't allow mixes of value types, like "Int|Bool" if (!instance.TargetType.AllowSlicedSubstitution) { // value types are known in advance (in compilation time) so checking their types // in runtime does not make sense ctx.ErrorManager.AddError(ErrorCode.IsTypeOfKnownTypes, this); break; } } } } else { ctx.AddError(ErrorCode.TestingAgainstTypeSet, this.RhsTypeName); } }