LocalRewriter_PatternSwitchStatement.cs 23.8 KB
Newer Older
N
Neal Gafter 已提交
1 2
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

3 4
using System;
using System.Collections.Generic;
N
Neal Gafter 已提交
5 6 7 8 9 10 11 12 13 14 15
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp
{
    internal partial class LocalRewriter
    {
        public override BoundNode VisitPatternSwitchStatement(BoundPatternSwitchStatement node)
        {
N
Neal Gafter 已提交
16
            _factory.Syntax = node.Syntax;
17
            var pslr = new PatternSwitchLocalRewriter(this, node);
N
Neal Gafter 已提交
18
            var expression = VisitExpression(node.Expression);
19
            var result = ArrayBuilder<BoundStatement>.GetInstance();
N
Neal Gafter 已提交
20 21

            // output the decision tree part
22
            pslr.LowerDecisionTree(expression, node.DecisionTree, result);
23 24

            // if the endpoint is reachable, we exit the switch
25 26 27 28
            if (!node.DecisionTree.MatchIsComplete)
            {
                result.Add(_factory.Goto(node.BreakLabel));
            }
29
            // at this point the end of result is unreachable.
N
Neal Gafter 已提交
30

31
            // output the sections of code
N
Neal Gafter 已提交
32 33
            foreach (var section in node.SwitchSections)
            {
34 35 36 37 38
                // Start with the part of the decision tree that is in scope of the section variables.
                // Its endpoint is not reachable (it jumps back into the decision tree code).
                var sectionBuilder = pslr.SwitchSections[section];

                // Add labels corresponding to the labels of the switch section.
N
Neal Gafter 已提交
39 40
                foreach (var label in section.SwitchLabels)
                {
41
                    sectionBuilder.Add(_factory.Label(label.Label));
N
Neal Gafter 已提交
42 43
                }

44 45 46 47 48
                // Add the translated body of the switch section
                sectionBuilder.AddRange(VisitList(section.Statements));
                sectionBuilder.Add(_factory.Goto(node.BreakLabel));
                result.Add(_factory.Block(section.Locals, sectionBuilder.ToImmutableAndFree()));
                // at this point the end of result is unreachable.
N
Neal Gafter 已提交
49 50 51
            }

            result.Add(_factory.Label(node.BreakLabel));
52 53
            var translatedSwitch = _factory.Block(pslr.DeclaredTemps.ToImmutableArray().Concat(node.InnerLocals), node.InnerLocalFunctions, result.ToImmutableAndFree());
            return translatedSwitch;
N
Neal Gafter 已提交
54 55
        }

56
        private class PatternSwitchLocalRewriter
N
Neal Gafter 已提交
57
        {
58 59 60 61
            public readonly LocalRewriter LocalRewriter;
            public readonly HashSet<LocalSymbol> DeclaredTempSet = new HashSet<LocalSymbol>();
            public readonly ArrayBuilder<LocalSymbol> DeclaredTemps = ArrayBuilder<LocalSymbol>.GetInstance();
            public readonly Dictionary<BoundPatternSwitchSection, ArrayBuilder<BoundStatement>> SwitchSections = new Dictionary<BoundPatternSwitchSection, ArrayBuilder<BoundStatement>>();
62 63

            private ArrayBuilder<BoundStatement> _loweredDecisionTree = ArrayBuilder<BoundStatement>.GetInstance();
64 65 66
            private readonly SyntheticBoundNodeFactory _factory;

            public PatternSwitchLocalRewriter(LocalRewriter localRewriter, BoundPatternSwitchStatement node)
N
Neal Gafter 已提交
67
            {
68 69 70 71
                this.LocalRewriter = localRewriter;
                this._factory = localRewriter._factory;
                foreach (var section in node.SwitchSections)
                {
72
                    SwitchSections.Add(section, ArrayBuilder<BoundStatement>.GetInstance());
73 74 75 76 77 78
                }
            }

            /// <summary>
            /// Lower the given decision tree into the given statement builder.
            /// </summary>
79
            public void LowerDecisionTree(BoundExpression expression, DecisionTree decisionTree, ArrayBuilder<BoundStatement> loweredDecisionTree)
80
            {
81 82
                var oldLoweredDecisionTree = this._loweredDecisionTree;
                this._loweredDecisionTree = loweredDecisionTree;
83
                LowerDecisionTree(expression, decisionTree);
84
                this._loweredDecisionTree = oldLoweredDecisionTree;
85 86
            }

87
            private void LowerDecisionTree(BoundExpression expression, DecisionTree decisionTree)
88
            {
89 90 91 92
                if (decisionTree == null)
                {
                    return;
                }
93 94 95 96 97 98 99 100

                // If the input expression was a constant or a simple read of a local, then that is the
                // decision tree's expression. Otherwise it is a newly created temp, to which we must
                // assign the switch expression.
                if (decisionTree.Temp != null)
                {
                    // Store the input expression into a temp
                    if (decisionTree.Expression != expression)
N
Neal Gafter 已提交
101
                    {
102
                        _loweredDecisionTree.Add(_factory.Assignment(decisionTree.Expression, expression));
N
Neal Gafter 已提交
103
                    }
104 105

                    if (DeclaredTempSet.Add(decisionTree.Temp))
N
Neal Gafter 已提交
106
                    {
107
                        DeclaredTemps.Add(decisionTree.Temp);
N
Neal Gafter 已提交
108
                    }
109
                    else
N
Neal Gafter 已提交
110
                    {
111 112
                        // we should only attempt to declare each temp once.
                        throw ExceptionUtilities.Unreachable;
N
Neal Gafter 已提交
113
                    }
114
                }
N
Neal Gafter 已提交
115

116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
                switch (decisionTree.Kind)
                {
                    case DecisionTree.DecisionKind.ByType:
                        {
                            LowerDecisionTree((DecisionTree.ByType)decisionTree);
                            return;
                        }
                    case DecisionTree.DecisionKind.ByValue:
                        {
                            LowerDecisionTree((DecisionTree.ByValue)decisionTree);
                            return;
                        }
                    case DecisionTree.DecisionKind.Guarded:
                        {
                            LowerDecisionTree((DecisionTree.Guarded)decisionTree);
                            return;
                        }
                    default:
                        throw ExceptionUtilities.UnexpectedValue(decisionTree.Kind);
                }
N
Neal Gafter 已提交
136 137
            }

138
            private void LowerDecisionTree(DecisionTree.ByType byType)
N
Neal Gafter 已提交
139
            {
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
                var inputConstant = byType.Expression.ConstantValue;
                if (inputConstant != null)
                {
                    if (inputConstant.IsNull)
                    {
                        // input is the constant null
                        LowerDecisionTree(byType.Expression, byType.WhenNull);
                        if (byType.WhenNull?.MatchIsComplete != true)
                        {
                            LowerDecisionTree(byType.Expression, byType.Default);
                        }
                    }
                    else
                    {
                        // input is a non-null constant
                        foreach (var kvp in byType.TypeAndDecision)
                        {
                            LowerDecisionTree(byType.Expression, kvp.Value);
158 159 160 161
                            if (kvp.Value.MatchIsComplete)
                            {
                                return;
                            }
162
                        }
163

164 165 166 167 168 169
                        LowerDecisionTree(byType.Expression, byType.Default);
                    }
                }
                else
                {
                    var defaultLabel = _factory.GenerateLabel("byTypeDefault");
N
Neal Gafter 已提交
170

171 172 173 174 175 176 177 178 179 180
                    // input is not a constant
                    if (byType.Type.CanBeAssignedNull())
                    {
                        // first test for null
                        var notNullLabel = _factory.GenerateLabel("notNull");
                        var inputExpression = byType.Expression;
                        var nullValue = _factory.Null(byType.Type);
                        BoundExpression notNull = byType.Type.IsNullableType()
                            ? LocalRewriter.RewriteNullableNullEquality(_factory.Syntax, BinaryOperatorKind.NullableNullNotEqual, byType.Expression, nullValue, _factory.SpecialType(SpecialType.System_Boolean))
                            : _factory.ObjectNotEqual(byType.Expression, nullValue);
181
                        _loweredDecisionTree.Add(_factory.ConditionalGoto(notNull, notNullLabel, true));
182
                        LowerDecisionTree(byType.Expression, byType.WhenNull);
183 184 185 186 187
                        if (byType.WhenNull?.MatchIsComplete != true)
                        {
                            _loweredDecisionTree.Add(_factory.Goto(defaultLabel));
                        }

188
                        _loweredDecisionTree.Add(_factory.Label(notNullLabel));
189 190 191 192 193
                    }
                    else
                    {
                        Debug.Assert(byType.WhenNull == null);
                    }
N
Neal Gafter 已提交
194

195 196 197 198 199 200 201
                    foreach (var td in byType.TypeAndDecision)
                    {
                        // then test for each type, sequentially
                        var type = td.Key;
                        var decision = td.Value;
                        var failLabel = _factory.GenerateLabel("failedDecision");
                        var testAndCopy = TypeTestAndCopyToTemp(byType.Expression, decision.Expression);
202
                        _loweredDecisionTree.Add(_factory.ConditionalGoto(testAndCopy, failLabel, false));
203
                        LowerDecisionTree(decision.Expression, decision);
204
                        _loweredDecisionTree.Add(_factory.Label(failLabel));
205 206 207
                    }

                    // finally, the default for when no type matches
208
                    _loweredDecisionTree.Add(_factory.Label(defaultLabel));
209 210
                    LowerDecisionTree(byType.Expression, byType.Default);
                }
N
Neal Gafter 已提交
211 212
            }

213 214 215 216 217 218 219
            private BoundExpression TypeTestAndCopyToTemp(BoundExpression input, BoundExpression temp)
            {
                // invariant: the input has already been tested, to ensure it is not null
                if (input == temp)
                {
                    return _factory.Literal(true);
                }
N
Neal Gafter 已提交
220

221 222 223 224 225
                Debug.Assert(temp.Kind == BoundKind.Local);
                return LocalRewriter.MakeDeclarationPattern(_factory.Syntax, input, ((BoundLocal)temp).LocalSymbol, requiresNullTest: false);
            }

            private void LowerDecisionTree(DecisionTree.ByValue byValue)
N
Neal Gafter 已提交
226
            {
227 228 229
                if (byValue.Expression.ConstantValue != null)
                {
                    LowerConstantValueDecision(byValue);
N
Neal Gafter 已提交
230
                    return;
231
                }
N
Neal Gafter 已提交
232

233 234 235 236 237 238
                if (byValue.ValueAndDecision.Count == 0)
                {
                    LowerDecisionTree(byValue.Expression, byValue.Default);
                    return;
                }

239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
                switch (byValue.Type.SpecialType)
                {
                    case SpecialType.System_Byte:
                    case SpecialType.System_Char:
                    case SpecialType.System_Int16:
                    case SpecialType.System_Int32:
                    case SpecialType.System_Int64:
                    case SpecialType.System_SByte:
                    case SpecialType.System_UInt16:
                    case SpecialType.System_UInt32:
                    case SpecialType.System_UInt64:
                    case SpecialType.System_String: // switch on a string
                                                    // switch on an integral or string type
                        LowerBasicSwitch(byValue);
                        return;
N
Neal Gafter 已提交
254

255 256 257
                    case SpecialType.System_Boolean: // switch on a boolean
                        LowerBooleanSwitch(byValue);
                        return;
N
Neal Gafter 已提交
258

259 260 261 262 263 264 265 266
                    // switch on a type requiring sequential comparisons. Note that we use constant.Equals(value), depending if
                    // possible on the one from IEquatable<T>. If that does not exist, we use instance method object.Equals(object)
                    // with the (now boxed) constant on the left.
                    case SpecialType.System_Decimal:
                    case SpecialType.System_Double:
                    case SpecialType.System_Single:
                        LowerOtherSwitch(byValue);
                        return;
N
Neal Gafter 已提交
267

268 269 270 271 272 273
                    default:
                        if (byValue.Type.TypeKind == TypeKind.Enum)
                        {
                            LowerBasicSwitch(byValue);
                            return;
                        }
N
Neal Gafter 已提交
274

275 276 277 278
                        // There are no other types of constants that could be used as patterns.
                        throw ExceptionUtilities.UnexpectedValue(byValue.Type);
                }
            }
N
Neal Gafter 已提交
279

280
            private void LowerConstantValueDecision(DecisionTree.ByValue byValue)
N
Neal Gafter 已提交
281
            {
282 283 284 285 286 287
                var value = byValue.Expression.ConstantValue.Value;
                Debug.Assert(value != null);
                DecisionTree onValue;
                if (byValue.ValueAndDecision.TryGetValue(value, out onValue))
                {
                    LowerDecisionTree(byValue.Expression, onValue);
288 289 290 291
                    if (onValue.MatchIsComplete)
                    {
                        return;
                    }
292
                }
293 294

                LowerDecisionTree(byValue.Expression, byValue.Default);
N
Neal Gafter 已提交
295 296
            }

297
            private void LowerDecisionTree(DecisionTree.Guarded guarded)
N
Neal Gafter 已提交
298
            {
299 300 301 302 303 304 305
                var sectionBuilder = this.SwitchSections[guarded.Section];
                var targetLabel = guarded.Label.Label;
                Debug.Assert(guarded.Guard?.ConstantValue != ConstantValue.False);
                if (guarded.Guard == null || guarded.Guard.ConstantValue == ConstantValue.True)
                {
                    // unconditional
                    if (guarded.Bindings.IsDefaultOrEmpty)
N
Neal Gafter 已提交
306
                    {
307
                        _loweredDecisionTree.Add(_factory.Goto(targetLabel));
N
Neal Gafter 已提交
308
                    }
309
                    else
N
Neal Gafter 已提交
310
                    {
311 312
                        // with bindings
                        var matched = _factory.GenerateLabel("matched");
313
                        _loweredDecisionTree.Add(_factory.Goto(matched));
314 315 316
                        sectionBuilder.Add(_factory.Label(matched));
                        AddBindings(sectionBuilder, guarded.Bindings);
                        sectionBuilder.Add(_factory.Goto(targetLabel));
N
Neal Gafter 已提交
317
                    }
318 319 320 321
                }
                else
                {
                    var checkGuard = _factory.GenerateLabel("checkGuard");
322
                    _loweredDecisionTree.Add(_factory.Goto(checkGuard));
323 324 325 326 327
                    sectionBuilder.Add(_factory.Label(checkGuard));
                    AddBindings(sectionBuilder, guarded.Bindings);
                    sectionBuilder.Add(_factory.ConditionalGoto(LocalRewriter.VisitExpression(guarded.Guard), targetLabel, true));
                    var guardFailed = _factory.GenerateLabel("guardFailed");
                    sectionBuilder.Add(_factory.Goto(guardFailed));
328
                    _loweredDecisionTree.Add(_factory.Label(guardFailed));
329
                }
N
Neal Gafter 已提交
330
            }
N
Neal Gafter 已提交
331

332 333
            private void AddBindings(ArrayBuilder<BoundStatement> sectionBuilder, ImmutableArray<KeyValuePair<BoundExpression, LocalSymbol>> bindings)
            {
334 335 336 337
                if (bindings.IsDefaultOrEmpty)
                {
                    return;
                }
N
Neal Gafter 已提交
338

339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
                foreach (var kv in bindings)
                {
                    var source = kv.Key;
                    var dest = kv.Value;
                    sectionBuilder.Add(_factory.Assignment(_factory.Local(dest), source));
                }
            }

            // For switch statements, we have an option of completely rewriting the switch header
            // and switch sections into simpler constructs, i.e. we can rewrite the switch header
            // using bound conditional goto statements and the rewrite the switch sections into
            // bound labeled statements.
            //
            // However, all the logic for emitting the switch jump tables is language agnostic
            // and includes IL optimizations. Hence we delay the switch jump table generation
            // till the emit phase. This way we also get additional benefit of sharing this code
            // between both VB and C# compilers.
            //
            // For string switch statements, we need to determine if we are generating a hash
            // table based jump table or a non hash jump table, i.e. linear string comparisons
            // with each case label. We use the Dev10 Heuristic to determine this
            // (see SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch() for details).
            // If we are generating a hash table based jump table, we use a simple
            // hash function to hash the string constants corresponding to the case labels.
            // See SwitchStringJumpTableEmitter.ComputeStringHash().
            // We need to emit this same function to compute the hash value into the compiler generated
            // <PrivateImplementationDetails> class.
            // If we have at least one string switch statement in a module that needs a
            // hash table based jump table, we generate a single public string hash synthesized method
            // that is shared across the module.
            private void LowerBasicSwitch(DecisionTree.ByValue byValue)
            {
                var switchSections = ArrayBuilder<BoundSwitchSection>.GetInstance();
                var noValueMatches = _factory.GenerateLabel("noValueMatches");
                var underlyingSwitchType = byValue.Type.IsEnumType() ? byValue.Type.GetEnumUnderlyingType() : byValue.Type;
                foreach (var vd in byValue.ValueAndDecision)
                {
                    var value = vd.Key;
                    var decision = vd.Value;
                    var constantValue = ConstantValue.Create(value, underlyingSwitchType.SpecialType);
                    var constantExpression = new BoundLiteral(_factory.Syntax, constantValue, underlyingSwitchType);
                    var label = _factory.GenerateLabel("case+" + value);
                    var switchLabel = new BoundSwitchLabel(_factory.Syntax, label, constantExpression, constantValue);
                    var forValue = ArrayBuilder<BoundStatement>.GetInstance();
                    LowerDecisionTree(byValue.Expression, decision, forValue);
384 385 386 387 388
                    if (!decision.MatchIsComplete)
                    {
                        forValue.Add(_factory.Goto(noValueMatches));
                    }

389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
                    var section = new BoundSwitchSection(_factory.Syntax, ImmutableArray.Create(switchLabel), forValue.ToImmutableAndFree());
                    switchSections.Add(section);
                }

                var rewrittenSections = switchSections.ToImmutableAndFree();
                MethodSymbol stringEquality = null;
                if (byValue.Type.SpecialType == SpecialType.System_String)
                {
                    LocalRewriter.EnsureStringHashFunction(rewrittenSections, _factory.Syntax);
                    stringEquality = LocalRewriter.GetSpecialTypeMethod(_factory.Syntax, SpecialMember.System_String__op_Equality);
                }

                // Emit requires a constant target when there are no sections, so we accomodate that here.
                // CONSIDER: can we get better code generated by giving a constant target more often here,
                // e.g. when the switch expression is a constant?
                var constantTarget = rewrittenSections.IsEmpty ? noValueMatches : null;
                var switchStatement = new BoundSwitchStatement(
                    _factory.Syntax, null, _factory.Convert(underlyingSwitchType, byValue.Expression),
                    constantTarget,
                    ImmutableArray<LocalSymbol>.Empty, ImmutableArray<LocalFunctionSymbol>.Empty,
                    rewrittenSections, noValueMatches, stringEquality);
410
                _loweredDecisionTree.Add(switchStatement);
411 412 413 414 415 416 417 418 419 420
                // The bound switch statement implicitly defines the label noValueMatches at the end, so we do not add it explicitly.
                LowerDecisionTree(byValue.Expression, byValue.Default);
            }

            private void LowerBooleanSwitch(DecisionTree.ByValue byValue)
            {
                switch (byValue.ValueAndDecision.Count)
                {
                    case 0:
                        {
421 422
                            // this should have been handled in the caller.
                            throw ExceptionUtilities.Unreachable;
423 424 425 426 427
                        }
                    case 1:
                        {
                            DecisionTree decision;
                            bool onBoolean = byValue.ValueAndDecision.TryGetValue(true, out decision);
428 429 430 431 432
                            if (!onBoolean)
                            {
                                byValue.ValueAndDecision.TryGetValue(false, out decision);
                            }

433 434
                            Debug.Assert(decision != null);
                            var onOther = _factory.GenerateLabel("on" + !onBoolean);
435
                            _loweredDecisionTree.Add(_factory.ConditionalGoto(byValue.Expression, onOther, !onBoolean));
436 437
                            LowerDecisionTree(byValue.Expression, decision);
                            // if we fall through here, that means the match was not complete and we invoke the default part
438
                            _loweredDecisionTree.Add(_factory.Label(onOther));
439 440 441 442 443 444 445 446 447 448 449
                            LowerDecisionTree(byValue.Expression, byValue.Default);
                            break;
                        }
                    case 2:
                        {
                            DecisionTree trueDecision, falseDecision;
                            bool hasTrue = byValue.ValueAndDecision.TryGetValue(true, out trueDecision);
                            bool hasFalse = byValue.ValueAndDecision.TryGetValue(false, out falseDecision);
                            Debug.Assert(hasTrue && hasFalse);
                            var tryAnother = _factory.GenerateLabel("tryAnother");
                            var onFalse = _factory.GenerateLabel("onFalse");
450
                            _loweredDecisionTree.Add(_factory.ConditionalGoto(byValue.Expression, onFalse, false));
451
                            LowerDecisionTree(byValue.Expression, trueDecision);
452 453
                            _loweredDecisionTree.Add(_factory.Goto(tryAnother));
                            _loweredDecisionTree.Add(_factory.Label(onFalse));
454
                            LowerDecisionTree(byValue.Expression, falseDecision);
455
                            _loweredDecisionTree.Add(_factory.Label(tryAnother));
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
                            // if both true and false (i.e. all values) are fully handled, there should be no default.
                            Debug.Assert(!trueDecision.MatchIsComplete || !falseDecision.MatchIsComplete || byValue.Default == null);
                            LowerDecisionTree(byValue.Expression, byValue.Default);
                            break;
                        }
                    default:
                        throw ExceptionUtilities.UnexpectedValue(byValue.ValueAndDecision.Count);
                }
            }

            /// <summary>
            /// We handle "other" types, such as float, double, and decimal here. We compare the constant values using IEquatable.
            /// For other value types, since there is no literal notation, there will be no constants to test.
            /// </summary>
            private void LowerOtherSwitch(DecisionTree.ByValue byValue)
            {
472
                this.LocalRewriter._diagnostics.Add(ErrorCode.ERR_FeatureIsUnimplemented, _factory.Syntax.GetLocation(), "switch on float, double, or decimal");
473 474
                throw new NotImplementedException();
            }
N
Neal Gafter 已提交
475 476 477
        }
    }
}