Ejemplo n.º 1
0
		public static void Test()
		{
			var machine = new Region( "history" );

			var initial = new PseudoState( "initial", PseudoStateKind.Initial, machine );
			var shallow = new CompositeState( "shallow", machine );
			var deep = new SimpleState( "deep", machine );
			var final = new FinalState( "final", machine );

			var s1 = new SimpleState( "s1", shallow );
			var s2 = new SimpleState( "s2", shallow );

			new Transition( initial, shallow );
			new Transition( new PseudoState( "shallow", PseudoStateKind.ShallowHistory, shallow ), s1 );
			new Transition<String>( s1, s2, c => c.Equals( "move" ) );
			new Transition<String>( shallow, deep, c => c.Equals( "go deep" ) );
			new Transition<String>( deep, shallow, c => c.Equals( "go shallow" ) );
			new Transition<String>( s2, final, c => c.Equals( "end" ) );

			var state = new State();

			machine.Initialise( state );

			Trace.Assert( machine.Process( state, "move" ) );
			Trace.Assert( machine.Process( state, "go deep" ) );
			Trace.Assert( machine.Process( state, "go shallow" ) );
			Trace.Assert( !machine.Process( state, "go shallow" ) );
			Trace.Assert( machine.Process( state, "end" ) );
			Trace.Assert( machine.IsComplete( state ) );
		}
Ejemplo n.º 2
0
            /// <inheritdoc />
            public override IDictionary <char, State> NextStates()
            {
                if (this.nextstates == null)
                {
                    Charset context = this.Context;

                    // we are at the end of the word
                    // look into parent context for continuation
                    IDictionary <char, State> parentStates = this.ContextWordEnd ? context.Parent?.GetInitialState(context)?.NextStates() : null;

                    // if the context can be repeated
                    // look into next character
                    IDictionary <char, State> nextStates = null;

                    int repeatCount = this.RepeatCount + 1;
                    if (repeatCount <= context.MaxRepeatCount)
                    {
                        nextStates = CharsetState.NextStates(this.Char, context, repeatCount);
                    }

                    // combine next and parent states
                    this.nextstates = CompositeState.Merge(nextStates, parentStates);
                }

                return(this.nextstates);
            }
Ejemplo n.º 3
0
        protected virtual void NotifyPropertyChanged(string propertyName)
        {
            var property = GetType().GetProperty(propertyName);

            if (property == null)
            {
                throw new ArgumentException(propertyName);
            }

            State = State == CompositeState.New ? CompositeState.New : CompositeState.Modified;

            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        public void Execute_Corresponding_Inner_States_Methods_In_Its_Own_Methods()
        {
            var state = Substitute.For <IState>();

            var compositeState = new CompositeState(state);

            compositeState.Enter();
            compositeState.Update();
            compositeState.Exit();

            state.Received(1).Enter();
            state.Received(1).Update();
            state.Received(1).Exit();
        }
Ejemplo n.º 5
0
        async Task <object> IScorable <Score> .PrepareAsync <Item>(Item item, CancellationToken token)
        {
            CompositeState maximum = null;

            foreach (var scorable in this.scorables)
            {
                var state = await scorable.PrepareAsync(item, token);

                Score score;
                if (scorable.TryScore(state, out score))
                {
                    if (this.comparer.Compare(score, this.traits.Minimum) < 0)
                    {
                        throw new ArgumentOutOfRangeException(nameof(score));
                    }

                    if (this.comparer.Compare(score, this.traits.Maximum) > 0)
                    {
                        throw new ArgumentOutOfRangeException(nameof(score));
                    }

                    if (maximum == null)
                    {
                        maximum = new CompositeState();
                    }

                    var compare = this.comparer.Compare(score, maximum.Score);
                    if (maximum.Scorable == null || compare > 0)
                    {
                        maximum.Score    = score;
                        maximum.State    = state;
                        maximum.Scorable = scorable;

                        if (this.comparer.Compare(score, this.traits.Maximum) == 0)
                        {
                            break;
                        }
                    }
                }
            }

            return(maximum);
        }
Ejemplo n.º 6
0
        protected CompositeInstanceImpl(
            CompositeInstanceStructureOwner structureOwner,
            CompositeModel model,
            IEnumerable <Type> publicCompositeTypes,
            UsesContainerQuery usesContainer,
            MainCompositeConstructorArguments publicCtorArgsObject
            )
        {
            ArgumentValidator.ValidateNotNull("Structure owner", structureOwner);
            ArgumentValidator.ValidateNotNull("Composite model", model);
            ArgumentValidator.ValidateNotEmpty("Composite type", publicCompositeTypes);
            ArgumentValidator.ValidateNotNull("Container for objects to be used in fragment creation", usesContainer);

            this._structureOwner = structureOwner;
            var application = this._structureOwner.Application;

            this._modelInfo = this._structureOwner.ModelInfoContainer.GetCompositeModelInfo(model);
            if (publicCompositeTypes.Any(pcType => pcType.ContainsGenericParameters()))
            {
                throw new InternalException("With given public composite types {" + String.Join(", ", publicCompositeTypes) + "} and public composite type in model being [" + String.Join(", ", model.PublicTypes) + "], the public composite types contained non-closed generic parameters.");
            }
            this._usesContainer = usesContainer;

            this._isPrototype = (Int32)PrototypeState.PROTOTYPE;

            this._invocationInfos = new Lazy <ThreadLocal <Stack <InvocationInfo> > >(() => new ThreadLocal <Stack <InvocationInfo> >(() => new Stack <InvocationInfo>()), LazyThreadSafetyMode.PublicationOnly);

            var composites = application.CollectionsFactory.NewDictionaryProxy <Type, Object>();
            var cProps     = application.CollectionsFactory.NewListProxy(new List <CompositeProperty>(model.Methods.Count * 2));
            var cEvents    = application.CollectionsFactory.NewListProxy(new List <CompositeEvent>(model.Methods.Count * 2));

            var publicTypeGenResult = this._modelInfo.Types;
            var factory             = publicTypeGenResult.CompositeFactory;

            var gArgs = publicTypeGenResult.PublicCompositeGenericArguments.Count == 0 ? null : new Type[publicTypeGenResult.GeneratedMainPublicType.GetGenericArguments().Length];

            this._gArgs = gArgs;

            foreach (var pType in publicCompositeTypes)
            {
                ListQuery <Int32> gArgInfo = null;
                if (publicTypeGenResult.PublicCompositeGenericArguments.TryGetValue(pType.GetGenericDefinitionIfGenericType(), out gArgInfo))
                {
                    var declaredGArgs = pType.GetGenericArguments();
                    for (Int32 i = 0; i < declaredGArgs.Length; ++i)
                    {
                        gArgs[gArgInfo[i]] = declaredGArgs[i];
                    }
                }
            }

            if (gArgs != null && gArgs.Any(gArg => gArg == null))
            {
                throw new InvalidCompositeTypeException(publicCompositeTypes, "Could not find suitable generic argument for all public types of composite " + this._modelInfo.Model + ".");
            }

            Action prePrototypeAction = null;
            var    publicCtorArgs     = new Object[publicTypeGenResult.MaxParamCountForCtors];

            Object[] compositeCtorParams = null;
            foreach (var genType in publicTypeGenResult.GeneratedPublicTypes)
            {
                var isMainType  = genType.GeneratedType.Equals(this._modelInfo.Types.GeneratedMainPublicType);
                var curCtorArgs = isMainType ? publicCtorArgs : compositeCtorParams;
                this.SetCompositeCtorArgs(ref curCtorArgs, cProps.AO, cEvents.AO);
                var publicComposite = factory.CreateInstance(genType.GeneratedTypeID, gArgs, curCtorArgs);
                foreach (var cType in this.GetTypeKeysForGeneratedType(publicComposite.GetType(), true, isMainType))
                {
                    composites[cType] = publicComposite;
                }

                if (isMainType)
                {
                    if (publicCtorArgsObject != null)
                    {
                        publicCtorArgsObject.Arguments = curCtorArgs;
                    }
                    prePrototypeAction     = (Action)publicCtorArgs[COMPOSITE_CTOR_FIRST_ADDITIONAL_PARAM_IDX];
                    this._prototypeAction  = (Action)publicCtorArgs[COMPOSITE_CTOR_FIRST_ADDITIONAL_PARAM_IDX + 1];
                    this._checkStateFunc   = (Action <IDictionary <QualifiedName, IList <ConstraintViolationInfo> > >)publicCtorArgs[COMPOSITE_CTOR_FIRST_ADDITIONAL_PARAM_IDX + 2];
                    this._compositeMethods = new Lazy <MethodInfo[]>(() => ((CompositeCallbacks)publicComposite).GetCompositeMethods(), LazyThreadSafetyMode.ExecutionAndPublication);
                }
            }

            this._isPrototypeTransitionInProgress = null;

            this.SetCompositeCtorArgs(ref compositeCtorParams, cProps.AO, cEvents.AO);

            foreach (var typeGenResult in publicTypeGenResult.PrivateCompositeGenerationResults)
            {
                var privateComposite = factory.CreateInstance(typeGenResult.GeneratedTypeID, gArgs, compositeCtorParams);
                foreach (var cTypeOrParent in this.GetTypeKeysForGeneratedType(privateComposite.GetType(), false, false))
                {
                    composites.Add(cTypeOrParent, privateComposite);
                }
            }

            this._composites = composites.CQ;

            this._methodsToModels = new Lazy <DictionaryQuery <MethodInfo, CompositeMethodModel> >(() =>
            {
                var retVal   = new Dictionary <MethodInfo, CompositeMethodModel>();
                var cMethods = this._compositeMethods.Value;
                for (var i = 0; i < cMethods.Length; ++i)
                {
                    var cm = cMethods[i];
                    retVal.Add(cm, this._modelInfo.Model.Methods[i]);
                }
                return(application.CollectionsFactory.NewDictionaryProxy(retVal).CQ);
            }, LazyThreadSafetyMode.ExecutionAndPublication);

            this._state = new CompositeStateImpl(this._structureOwner.Application.CollectionsFactory, cProps.CQ, cEvents.CQ);

            this._fragmentInstancePools = this.CreatePoolDictionary <FragmentTypeGenerationResult, FragmentInstance>(
                gArgs,
                this._modelInfo.Types.FragmentGenerationResults.Where(fGenResult => fGenResult.InstancePoolRequired),
                application.CollectionsFactory);
            var fInstances = application.CollectionsFactory.NewDictionaryProxy(new Dictionary <Type, FragmentInstance>());

            foreach (var genResult in publicTypeGenResult.FragmentGenerationResults.Where(val => !val.InstancePoolRequired))
            {
                var genType = genResult.GeneratedType;
                if (gArgs != null)
                {
                    genType = genType.MakeGenericType(gArgs);
                }
                else if (genType.ContainsGenericParameters())
                {
                    throw new InternalException("Could not find generic arguments for fragment type " + genResult.DeclaredType + ".");
                }
                fInstances.Add(genType, new FragmentInstanceImpl());
            }
            this._fragmentInstances             = fInstances.CQ;
            this._concernInvocationInstances    = this.CreatePoolDictionary <TypeGenerationResult, FragmentDependant>(gArgs, publicTypeGenResult.ConcernInvocationGenerationResults, application.CollectionsFactory);
            this._sideEffectInvocationInstances = this.CreatePoolDictionary <TypeGenerationResult, FragmentDependant>(gArgs, publicTypeGenResult.SideEffectGenerationResults, application.CollectionsFactory);
            this._constructorsForFragments      = application.CollectionsFactory.NewDictionaryProxy <Type, ListQuery <FragmentConstructorInfo> >(this._fragmentInstancePools.Keys.Concat(this._fragmentInstances.Keys)
                                                                                                                                                 .ToDictionary(
                                                                                                                                                     fType => fType,
                                                                                                                                                     fType => application.CollectionsFactory.NewListProxy(fType
                                                                                                                                                                                                          .GetAllInstanceConstructors()
                                                                                                                                                                                                          .Select(fCtor =>
            {
                Int32 idx;
                return(fCtor.TryGetConstructorModelIndex(out idx) ?
                       new FragmentConstructorInfo(model.Constructors[idx], fCtor) :
                       null);
            })
                                                                                                                                                                                                          .Where(i => i != null)
                                                                                                                                                                                                          .ToList()
                                                                                                                                                                                                          ).CQ
                                                                                                                                                     )).CQ;

            if (prePrototypeAction != null)
            {
                prePrototypeAction();
            }
        }
Ejemplo n.º 7
0
            public override IDictionary <char, State> NextStates()
            {
                if (this.nextstates == null)
                {
                    Vocabulary context     = this.Context;
                    int        repeatCount = this.RepeatCount;

                    IDictionary <char, State> parentStates = null;
                    if (this.ContextWordEnd)
                    {
                        parentStates = context.Parent?.GetInitialState(context)?.NextStates();
                    }

                    IDictionary <char, State> repeatStates = null;
                    if (this.RepeatWordEnd && repeatCount < context.MaxRepeatCount)
                    {
                        /*if (Vocabulary.Separator != (char)0)
                         * {*/
                        VocabularyState state = new VocabularyState(
                            Vocabulary.Separator,
                            false,
                            false,
                            1.0f,
                            0.0f,
                            false,
                            repeatCount + 1,
                            context,
                            Vocabulary.SeekToBegin);

                        repeatStates = new Dictionary <char, State>();
                        repeatStates.Add(Vocabulary.Separator, state);

                        /*}
                         * else
                         * {
                         *  repeatStates = new VocabularyState(
                         *      (char)0,
                         *      false,
                         *      false,
                         *      0.0f,
                         *      0.0f,
                         *      false,
                         *      repeatCount + 1,
                         *      context,
                         *      Vocabulary.SeekToBegin).NextStates();
                         * }*/
                    }

                    // if the state does not point to the end
                    // look into next character
                    IDictionary <char, State> nextStates = null;

                    int seek = this.Seek;
                    if (seek != Vocabulary.SeekToEnd)
                    {
                        nextStates = VocabularyState.NextStates(seek, context, repeatCount);
                    }

                    // combine next and parent states
                    this.nextstates = CompositeState.Merge(nextStates, repeatStates, parentStates);
                }

                return(this.nextstates);
            }