<commit_before>﻿namespace FakeItEasy.Creation
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.CodeAnalysis;
    using System.Linq;
#if NET40
    using System.Linq.Expressions;
#endif
    using System.Reflection;
#if NET40
    using System.Threading.Tasks;
#endif
    using FakeItEasy.Core;

    internal class DummyValueCreationSession : IDummyValueCreationSession
    {
#if NET40
        private static readonly MethodInfo GenericFromResultMethodDefinition = CreateGenericFromResultMethodDefinition();
#endif
        private readonly ResolveStrategy[] strategies;
        private readonly HashSet<Type> typesCurrentlyBeingResolved;
        private readonly Dictionary<Type, ResolveStrategy> strategyCache;

        /// <summary>
        /// Initializes a new instance of the <see cref="DummyValueCreationSession"/> class.
        /// </summary>
        /// <param name="container">The container.</param>
        /// <param name="fakeObjectCreator">The fake object creator.</param>
        public DummyValueCreationSession(IFakeObjectContainer container, IFakeObjectCreator fakeObjectCreator)
        {
            this.typesCurrentlyBeingResolved = new HashSet<Type>();
            this.strategyCache = new Dictionary<Type, ResolveStrategy>();
            this.strategies = new ResolveStrategy[]
                {
                    new ResolveFromContainerSrategy { Container = container }, 
                    new ResolveByCreatingFakeStrategy { FakeCreator = fakeObjectCreator, Session = this }, 
                    new ResolveByActivatingValueTypeStrategy(), 
                    new ResolveByInstantiatingClassUsingDummyValuesAsConstructorArgumentsStrategy { Session = this }
                };
        }

        public bool TryResolveDummyValue(Type typeOfDummy, out object result)
        {
            result = default(object);
            if (!this.EnsureThatResolvedTypeIsNotRecursive(typeOfDummy))
            {
                return false;
            }

#if NET40
            if (this.TryResolveDummyValueWithAllAvailableStrategiesAndTaskWrapper(typeOfDummy, out result))
#else
            if (this.TryResolveDummyValueWithAllAvailableStrategies(typeOfDummy, out result))
#endif
            {
                this.OnSuccessfulResolve(typeOfDummy);
                return true;
            }

            return false;
        }

#if NET40
        private static MethodInfo CreateGenericFromResultMethodDefinition()
        {
            Expression<Action> templateExpression = () => FromResult(new object());
            var templateMethod = (templateExpression.Body as MethodCallExpression).Method;
            return templateMethod.GetGenericMethodDefinition();
        }

        private static Task<T> FromResult<T>(T result)
        {
            var source = new TaskCompletionSource<T>();
            source.SetResult(result);
            return source.Task;
        }
#endif

        private bool EnsureThatResolvedTypeIsNotRecursive(Type typeOfDummy)
        {
            if (this.typesCurrentlyBeingResolved.Contains(typeOfDummy))
            {
                return false;
            }

            this.typesCurrentlyBeingResolved.Add(typeOfDummy);
            return true;
        }

        private void OnSuccessfulResolve(Type typeOfDummy)
        {
            this.typesCurrentlyBeingResolved.Remove(typeOfDummy);
        }

#if NET40
        private bool TryResolveDummyValueWithAllAvailableStrategiesAndTaskWrapper(Type typeOfDummy, out object result)
        {
            result = default(object);

            if (typeOfDummy == typeof(Task))
            {
                var task = Task.Factory.StartNew(() => { });
                task.Wait();
                result = task;
                return true;
            }

            if (typeOfDummy.IsGenericType && typeOfDummy.GetGenericTypeDefinition() == typeof(Task<>))
            {
                var typeOfTaskResult = typeOfDummy.GetGenericArguments()[0];
                object taskResult;
                if (!this.TryResolveDummyValueWithAllAvailableStrategies(typeOfTaskResult, out taskResult))
                {
                    return false;
                }

                var method = GenericFromResultMethodDefinition.MakeGenericMethod(typeOfTaskResult);
                result = method.Invoke(null, new[] { taskResult });
                return true;
            }

            return this.TryResolveDummyValueWithAllAvailableStrategies(typeOfDummy, out result);
        }
#endif

        private bool TryResolveDummyValueWithAllAvailableStrategies(Type typeOfDummy, out object result)<commit_msg>#129 improved dummy void Task creation by using TaskCompletionSource<commit_after>﻿namespace FakeItEasy.Creation
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.CodeAnalysis;
    using System.Linq;
#if NET40
    using System.Linq.Expressions;
#endif
    using System.Reflection;
#if NET40
    using System.Threading.Tasks;
#endif
    using FakeItEasy.Core;

    internal class DummyValueCreationSession : IDummyValueCreationSession
    {
#if NET40
        private static readonly MethodInfo GenericFromResultMethodDefinition = CreateGenericFromResultMethodDefinition();
#endif
        private readonly ResolveStrategy[] strategies;
        private readonly HashSet<Type> typesCurrentlyBeingResolved;
        private readonly Dictionary<Type, ResolveStrategy> strategyCache;

        /// <summary>
        /// Initializes a new instance of the <see cref="DummyValueCreationSession"/> class.
        /// </summary>
        /// <param name="container">The container.</param>
        /// <param name="fakeObjectCreator">The fake object creator.</param>
        public DummyValueCreationSession(IFakeObjectContainer container, IFakeObjectCreator fakeObjectCreator)
        {
            this.typesCurrentlyBeingResolved = new HashSet<Type>();
            this.strategyCache = new Dictionary<Type, ResolveStrategy>();
            this.strategies = new ResolveStrategy[]
                {
                    new ResolveFromContainerSrategy { Container = container }, 
                    new ResolveByCreatingFakeStrategy { FakeCreator = fakeObjectCreator, Session = this }, 
                    new ResolveByActivatingValueTypeStrategy(), 
                    new ResolveByInstantiatingClassUsingDummyValuesAsConstructorArgumentsStrategy { Session = this }
                };
        }

        public bool TryResolveDummyValue(Type typeOfDummy, out object result)
        {
            result = default(object);
            if (!this.EnsureThatResolvedTypeIsNotRecursive(typeOfDummy))
            {
                return false;
            }

#if NET40
            if (this.TryResolveDummyValueWithAllAvailableStrategiesAndTaskWrapper(typeOfDummy, out result))
#else
            if (this.TryResolveDummyValueWithAllAvailableStrategies(typeOfDummy, out result))
#endif
            {
                this.OnSuccessfulResolve(typeOfDummy);
                return true;
            }

            return false;
        }

#if NET40
        private static MethodInfo CreateGenericFromResultMethodDefinition()
        {
            Expression<Action> templateExpression = () => FromResult(new object());
            var templateMethod = (templateExpression.Body as MethodCallExpression).Method;
            return templateMethod.GetGenericMethodDefinition();
        }

        private static Task<T> FromResult<T>(T result)
        {
            var source = new TaskCompletionSource<T>();
            source.SetResult(result);
            return source.Task;
        }
#endif

        private bool EnsureThatResolvedTypeIsNotRecursive(Type typeOfDummy)
        {
            if (this.typesCurrentlyBeingResolved.Contains(typeOfDummy))
            {
                return false;
            }

            this.typesCurrentlyBeingResolved.Add(typeOfDummy);
            return true;
        }

        private void OnSuccessfulResolve(Type typeOfDummy)
        {
            this.typesCurrentlyBeingResolved.Remove(typeOfDummy);
        }

#if NET40
        private bool TryResolveDummyValueWithAllAvailableStrategiesAndTaskWrapper(Type typeOfDummy, out object result)
        {
            result = default(object);

            if (typeOfDummy == typeof(Task))
            {
                var source = new TaskCompletionSource<object>();
                source.SetResult(default(object));
                result = source.Task;
                return true;
            }

            if (typeOfDummy.IsGenericType && typeOfDummy.GetGenericTypeDefinition() == typeof(Task<>))
            {
                var typeOfTaskResult = typeOfDummy.GetGenericArguments()[0];
                object taskResult;
                if (!this.TryResolveDummyValueWithAllAvailableStrategies(typeOfTaskResult, out taskResult))
                {
                    return false;
                }

                var method = GenericFromResultMethodDefinition.MakeGenericMethod(typeOfTaskResult);
                result = method.Invoke(null, new[] { taskResult });
                return true;
            }

            return this.TryResolveDummyValueWithAllAvailableStrategies(typeOfDummy, out result);
        }
#endif

        private bool TryResolveDummyValueWithAllAvailableStrategies(Type typeOfDummy, out object result)
{'fraction_non_alphanumeric': 0.07381408211018932, 'fraction_numerical': 0.003084450116996384, 'mean_word_length': 2.2491361437456807, 'pattern_counts': {'":': 0, '<': 36, '<?xml version=': 0, '>': 39, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4935893', 'n_tokens_mistral': 2356, 'n_tokens_neox': 2262, 'n_words': 476}