ValueSetFactory.BoolValueSetFactory.cs 2.3 KB
Newer Older
1 2 3 4
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

5 6
#nullable enable

7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
using System;
using System.Diagnostics;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp
{
    using static BinaryOperatorKind;

    internal static partial class ValueSetFactory
    {
        /// <summary>
        /// A value set factory for boolean values.
        /// </summary>
        private sealed class BoolValueSetFactory : IValueSetFactory<bool>
        {
            public static readonly BoolValueSetFactory Instance = new BoolValueSetFactory();

            private BoolValueSetFactory() { }

            public IValueSet<bool> Related(BinaryOperatorKind relation, bool value)
            {
                switch (relation, value)
                {
                    case (Equal, true):
                        return BoolValueSet.OnlyTrue;
                    case (Equal, false):
                        return BoolValueSet.OnlyFalse;
                    default:
35 36
                        // for error recovery
                        return BoolValueSet.AllValues;
37 38 39
                }
            }

40
            IValueSet IValueSetFactory.Random(int expectedSize, Random random) => random.Next(4) switch
41 42 43 44 45 46 47 48
            {
                0 => BoolValueSet.None,
                1 => BoolValueSet.OnlyFalse,
                2 => BoolValueSet.OnlyTrue,
                3 => BoolValueSet.AllValues,
                _ => throw ExceptionUtilities.UnexpectedValue("random"),
            };

49 50
            ConstantValue IValueSetFactory.RandomValue(Random random) => ConstantValue.Create(random.NextDouble() < 0.5);

51 52
            IValueSet IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue value)
            {
53
                return value.IsBad ? BoolValueSet.AllValues : Related(relation, value.BooleanValue);
54
            }
55 56 57 58

            bool IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue left, ConstantValue right)
            {
                Debug.Assert(relation == BinaryOperatorKind.Equal);
59
                return left.IsBad || right.IsBad || left.BooleanValue == right.BooleanValue;
60
            }
61 62 63
        }
    }
}