LocalRewriter.cs 25.3 KB
Newer Older
1
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
P
Pilchie 已提交
2

3
using System.Collections.Generic;
P
Pilchie 已提交
4 5
using System.Collections.Immutable;
using System.Diagnostics;
6
using Microsoft.CodeAnalysis.CodeGen;
P
Pilchie 已提交
7 8
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
9
using Microsoft.CodeAnalysis.CSharp.Syntax;
T
Tomas Matousek 已提交
10
using Microsoft.CodeAnalysis.PooledObjects;
P
Pilchie 已提交
11
using Microsoft.CodeAnalysis.RuntimeMembers;
J
Julien 已提交
12
using Roslyn.Utilities;
P
Pilchie 已提交
13 14 15

namespace Microsoft.CodeAnalysis.CSharp
{
16
    internal sealed partial class LocalRewriter : BoundTreeRewriterWithStackGuard
P
Pilchie 已提交
17
    {
18 19 20 21 22 23
        private readonly CSharpCompilation _compilation;
        private readonly SyntheticBoundNodeFactory _factory;
        private readonly SynthesizedSubmissionFields _previousSubmissionFields;
        private readonly bool _allowOmissionOfConditionalCalls;
        private readonly LoweredDynamicOperationFactory _dynamicFactory;
        private bool _sawLambdas;
E
Evan Hauck 已提交
24
        private bool _sawLocalFunctions;
25 26 27 28 29
        private bool _inExpressionLambda;

        private bool _sawAwait;
        private bool _sawAwaitInExceptionHandler;
        private readonly DiagnosticBag _diagnostics;
30
        private readonly Instrumenter _instrumenter;
J
John Hamby 已提交
31
        private readonly BoundStatement _rootStatement;
P
Pilchie 已提交
32

33 34
        private Dictionary<BoundValuePlaceholderBase, BoundExpression> _placeholderReplacementMapDoNotUseDirectly;

35 36 37
        private LocalRewriter(
            CSharpCompilation compilation,
            MethodSymbol containingMethod,
38
            int containingMethodOrdinal,
J
John Hamby 已提交
39
            BoundStatement rootStatement,
40 41 42
            NamedTypeSymbol containingType,
            SyntheticBoundNodeFactory factory,
            SynthesizedSubmissionFields previousSubmissionFields,
43
            bool allowOmissionOfConditionalCalls,
44 45
            DiagnosticBag diagnostics,
            Instrumenter instrumenter)
P
Pilchie 已提交
46
        {
47 48 49
            _compilation = compilation;
            _factory = factory;
            _factory.CurrentMethod = containingMethod;
50
            Debug.Assert(factory.CurrentType == (containingType ?? containingMethod.ContainingType));
51 52 53 54
            _dynamicFactory = new LoweredDynamicOperationFactory(factory, containingMethodOrdinal);
            _previousSubmissionFields = previousSubmissionFields;
            _allowOmissionOfConditionalCalls = allowOmissionOfConditionalCalls;
            _diagnostics = diagnostics;
55 56 57

            Debug.Assert(instrumenter != null);
            _instrumenter = instrumenter;
J
John Hamby 已提交
58
            _rootStatement = rootStatement;
P
Pilchie 已提交
59 60 61 62 63 64
        }

        /// <summary>
        /// Lower a block of code by performing local rewritings.
        /// </summary>
        public static BoundStatement Rewrite(
65
            CSharpCompilation compilation,
66 67
            MethodSymbol method,
            int methodOrdinal,
P
Pilchie 已提交
68 69 70 71
            NamedTypeSymbol containingType,
            BoundStatement statement,
            TypeCompilationState compilationState,
            SynthesizedSubmissionFields previousSubmissionFields,
72
            bool allowOmissionOfConditionalCalls,
73
            bool instrumentForDynamicAnalysis,
J
John Hamby 已提交
74
            ref ImmutableArray<SourceSpan> dynamicAnalysisSpans,
75
            DebugDocumentProvider debugDocumentProvider,
76
            DiagnosticBag diagnostics,
P
Pilchie 已提交
77
            out bool sawLambdas,
E
Evan Hauck 已提交
78
            out bool sawLocalFunctions,
P
Pilchie 已提交
79 80 81 82 83 84 85
            out bool sawAwaitInExceptionHandler)
        {
            Debug.Assert(statement != null);
            Debug.Assert(compilationState != null);

            try
            {
86
                var factory = new SyntheticBoundNodeFactory(method, statement.Syntax, compilationState, diagnostics);
J
John Hamby 已提交
87
                DynamicAnalysisInjector dynamicInstrumenter = instrumentForDynamicAnalysis ? DynamicAnalysisInjector.TryCreate(method, statement, factory, diagnostics, debugDocumentProvider, Instrumenter.NoOp) : null;
88 89 90

                // We don’t want IL to differ based upon whether we write the PDB to a file/stream or not.
                // Presence of sequence points in the tree affects final IL, therefore, we always generate them.
J
John Hamby 已提交
91 92
                var localRewriter = new LocalRewriter(compilation, method, methodOrdinal, statement, containingType, factory, previousSubmissionFields, allowOmissionOfConditionalCalls, diagnostics,
                                                      dynamicInstrumenter != null ? new DebugInfoInjector(dynamicInstrumenter) : DebugInfoInjector.Singleton);
93

P
Pilchie 已提交
94
                var loweredStatement = (BoundStatement)localRewriter.Visit(statement);
95
                sawLambdas = localRewriter._sawLambdas;
E
Evan Hauck 已提交
96
                sawLocalFunctions = localRewriter._sawLocalFunctions;
97
                sawAwaitInExceptionHandler = localRewriter._sawAwaitInExceptionHandler;
J
John Hamby 已提交
98
                if (dynamicInstrumenter != null)
99
                {
J
John Hamby 已提交
100
                    dynamicAnalysisSpans = dynamicInstrumenter.DynamicAnalysisSpans;
101 102
                }

103
                return loweredStatement;
P
Pilchie 已提交
104 105 106 107
            }
            catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex)
            {
                diagnostics.Add(ex.Diagnostic);
E
Evan Hauck 已提交
108
                sawLambdas = sawLocalFunctions = sawAwaitInExceptionHandler = false;
P
Pilchie 已提交
109 110 111 112
                return new BoundBadStatement(statement.Syntax, ImmutableArray.Create<BoundNode>(statement), hasErrors: true);
            }
        }

113
        private bool Instrument
114 115 116
        {
            get
            {
117
                return !_inExpressionLambda;
118 119 120
            }
        }

P
Pilchie 已提交
121 122
        private PEModuleBuilder EmitModule
        {
123
            get { return _factory.CompilationState.ModuleBuilderOpt; }
P
Pilchie 已提交
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
        }

        public override BoundNode Visit(BoundNode node)
        {
            if (node == null)
            {
                return node;
            }
            Debug.Assert(!node.HasErrors, "nodes with errors should not be lowered");

            BoundExpression expr = node as BoundExpression;
            if (expr != null)
            {
                return VisitExpressionImpl(expr);
            }

            return node.Accept(this);
        }

        private BoundExpression VisitExpression(BoundExpression node)
        {
            if (node == null)
            {
                return node;
            }
            Debug.Assert(!node.HasErrors, "nodes with errors should not be lowered");

            return VisitExpressionImpl(node);
        }

        private BoundStatement VisitStatement(BoundStatement node)
        {
            if (node == null)
            {
                return node;
            }
            Debug.Assert(!node.HasErrors, "nodes with errors should not be lowered");

            return (BoundStatement)node.Accept(this);
        }

        private BoundExpression VisitExpressionImpl(BoundExpression node)
        {
            ConstantValue constantValue = node.ConstantValue;
            if (constantValue != null)
            {
                TypeSymbol type = node.Type;
171
                if (type?.IsNullableType() != true)
P
Pilchie 已提交
172 173 174 175 176
                {
                    return MakeLiteral(node.Syntax, constantValue, type);
                }
            }

177
            var visited = VisitExpressionWithStackGuard(node);
P
Pilchie 已提交
178 179 180 181 182

            // If you *really* need to change the type, consider using an indirect method
            // like compound assignment does (extra flag only passed when it is an expression
            // statement means that this constraint is not violated).
            // Dynamic type will be erased in emit phase. It is considered equivalent to Object in lowered bound trees.
183
            // Unused deconstructions are lowered to produce a return value that isn't a tuple type.
184
            Debug.Assert(visited == null || visited.HasErrors || ReferenceEquals(visited.Type, node.Type) ||
185
                    visited.Type.Equals(node.Type, TypeCompareKind.IgnoreDynamicAndTupleNames) ||
186
                    IsUnusedDeconstruction(node));
P
Pilchie 已提交
187 188 189 190

            return visited;
        }

191 192 193 194 195
        private static bool IsUnusedDeconstruction(BoundExpression node)
        {
            return node.Kind == BoundKind.DeconstructionAssignmentOperator && !((BoundDeconstructionAssignmentOperator)node).IsUsed;
        }

P
Pilchie 已提交
196 197
        public override BoundNode VisitLambda(BoundLambda node)
        {
198
            _sawLambdas = true;
199 200
            CheckRefReadOnlySymbols(node.Symbol);

201
            var oldContainingSymbol = _factory.CurrentMethod;
P
Pilchie 已提交
202 203
            try
            {
204
                _factory.CurrentMethod = node.Symbol;
P
Pilchie 已提交
205 206 207 208
                return base.VisitLambda(node);
            }
            finally
            {
209
                _factory.CurrentMethod = oldContainingSymbol;
P
Pilchie 已提交
210 211 212
            }
        }

E
Evan Hauck 已提交
213 214 215
        public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node)
        {
            _sawLocalFunctions = true;
216 217
            CheckRefReadOnlySymbols(node.Symbol);

E
Evan Hauck 已提交
218 219 220
            var oldContainingSymbol = _factory.CurrentMethod;
            try
            {
221
                _factory.CurrentMethod = node.Symbol;
E
Evan Hauck 已提交
222 223 224 225 226 227 228 229
                return base.VisitLocalFunctionStatement(node);
            }
            finally
            {
                _factory.CurrentMethod = oldContainingSymbol;
            }
        }

230
        public override BoundNode VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node)
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
        {
            return PlaceholderReplacement(node);
        }

        /// <summary>
        /// Returns substitution currently used by the rewriter for a placeholder node.
        /// Each occurrence of the placeholder node is replaced with the node returned.
        /// Throws if there is no substitution.
        /// </summary>
        private BoundExpression PlaceholderReplacement(BoundValuePlaceholderBase placeholder)
        {
            var value = _placeholderReplacementMapDoNotUseDirectly[placeholder];
            AssertPlaceholderReplacement(placeholder, value);
            return value;
        }

        [Conditional("DEBUG")]
        private static void AssertPlaceholderReplacement(BoundValuePlaceholderBase placeholder, BoundExpression value)
        {
250
            Debug.Assert(value.Type.Equals(placeholder.Type, TypeCompareKind.AllIgnoreOptions));
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
        }

        /// <summary>
        /// Sets substitution used by the rewriter for a placeholder node.
        /// Each occurrence of the placeholder node is replaced with the node returned.
        /// Throws if there is already a substitution.
        /// </summary>
        private void AddPlaceholderReplacement(BoundValuePlaceholderBase placeholder, BoundExpression value)
        {
            AssertPlaceholderReplacement(placeholder, value);

            if ((object)_placeholderReplacementMapDoNotUseDirectly == null)
            {
                _placeholderReplacementMapDoNotUseDirectly = new Dictionary<BoundValuePlaceholderBase, BoundExpression>();
            }

            _placeholderReplacementMapDoNotUseDirectly.Add(placeholder, value);
        }

        /// <summary>
        /// Removes substitution currently used by the rewriter for a placeholder node.
        /// Asserts if there isn't already a substitution.
        /// </summary>
        private void RemovePlaceholderReplacement(BoundValuePlaceholderBase placeholder)
        {
            Debug.Assert((object)placeholder != null);
            bool removed = _placeholderReplacementMapDoNotUseDirectly.Remove(placeholder);

            Debug.Assert(removed);
        }

J
Julien 已提交
282 283 284 285 286 287
        public override sealed BoundNode VisitOutDeconstructVarPendingInference(OutDeconstructVarPendingInference node)
        {
            // OutDeconstructVarPendingInference nodes are only used within initial binding, but don't survive past that stage
            throw ExceptionUtilities.Unreachable;
        }

288
        public override BoundNode VisitDeconstructionVariablePendingInference(DeconstructionVariablePendingInference node)
289
        {
290
            // DeconstructionVariablePendingInference nodes are only used within initial binding, but don't survive past that stage
291 292 293
            throw ExceptionUtilities.Unreachable;
        }

P
Pilchie 已提交
294 295 296 297 298 299 300 301 302
        public override BoundNode VisitBadExpression(BoundBadExpression node)
        {
            // Cannot recurse into BadExpression children since the BadExpression
            // may represent being unable to use the child as an lvalue or rvalue.
            return node;
        }

        private static BoundExpression BadExpression(BoundExpression node)
        {
303
            return BadExpression(node.Syntax, node.Type, ImmutableArray.Create(node));
304 305
        }

306
        private static BoundExpression BadExpression(SyntaxNode syntax, TypeSymbol resultType, BoundExpression child)
307
        {
308
            return BadExpression(syntax, resultType, ImmutableArray.Create(child));
309 310
        }

311
        private static BoundExpression BadExpression(SyntaxNode syntax, TypeSymbol resultType, BoundExpression child1, BoundExpression child2)
312
        {
313
            return BadExpression(syntax, resultType, ImmutableArray.Create(child1, child2));
314 315
        }

316
        private static BoundExpression BadExpression(SyntaxNode syntax, TypeSymbol resultType, ImmutableArray<BoundExpression> children)
317 318
        {
            return new BoundBadExpression(syntax, LookupResultKind.NotReferencable, ImmutableArray<Symbol>.Empty, children, resultType);
P
Pilchie 已提交
319 320
        }

321
        private bool TryGetWellKnownTypeMember<TSymbol>(SyntaxNode syntax, WellKnownMember member, out TSymbol symbol, bool isOptional = false) where TSymbol : Symbol
P
Pilchie 已提交
322
        {
323
            symbol = (TSymbol)Binder.GetWellKnownTypeMember(_compilation, member, _diagnostics, syntax: syntax, isOptional: isOptional);
P
Pilchie 已提交
324 325 326
            return ((object)symbol != null);
        }

327 328
        /// <summary>
        /// This function provides a false sense of security, it is likely going to surprise you when the requested member is missing.
G
Gen Lu 已提交
329
        /// Recommendation: Do not use, use <see cref="TryGetSpecialTypeMethod(SyntaxNode, SpecialMember, out MethodSymbol)"/> instead! 
330 331 332
        /// If used, a unit-test with a missing member is absolutely a must have.
        /// </summary>
        private MethodSymbol UnsafeGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember)
333 334 335 336
        {
            return UnsafeGetSpecialTypeMethod(syntax, specialMember, _compilation, _diagnostics);
        }

337 338 339 340 341
        /// <summary>
        /// This function provides a false sense of security, it is likely going to surprise you when the requested member is missing.
        /// Recommendation: Do not use, use <see cref="TryGetSpecialTypeMethod(SyntaxNode, SpecialMember, CSharpCompilation, DiagnosticBag, out MethodSymbol)"/> instead! 
        /// If used, a unit-test with a missing member is absolutely a must have.
        /// </summary>
342
        private static MethodSymbol UnsafeGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember, CSharpCompilation compilation, DiagnosticBag diagnostics)
P
Pilchie 已提交
343 344
        {
            MethodSymbol method;
345
            if (TryGetSpecialTypeMethod(syntax, specialMember, compilation, diagnostics, out method))
P
Pilchie 已提交
346 347 348 349 350 351 352
            {
                return method;
            }
            else
            {
                MemberDescriptor descriptor = SpecialMembers.GetDescriptor(specialMember);
                SpecialType type = (SpecialType)descriptor.DeclaringTypeId;
353 354
                TypeSymbol container = compilation.Assembly.GetSpecialType(type);
                TypeSymbol returnType = new ExtendedErrorTypeSymbol(compilation: compilation, name: descriptor.Name, errorInfo: null, arity: descriptor.Arity);
P
Pilchie 已提交
355 356 357 358
                return new ErrorMethodSymbol(container, returnType, "Missing");
            }
        }

359 360
        private bool TryGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember, out MethodSymbol method)
        {
361 362 363 364 365 366
            return TryGetSpecialTypeMethod(syntax, specialMember, _compilation, _diagnostics, out method);
        }

        private static bool TryGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember, CSharpCompilation compilation, DiagnosticBag diagnostics, out MethodSymbol method)
        {
            return Binder.TryGetSpecialTypeMember(compilation, specialMember, syntax, diagnostics, out method);
367 368
        }

P
Pilchie 已提交
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
        public override BoundNode VisitTypeOfOperator(BoundTypeOfOperator node)
        {
            Debug.Assert((object)node.GetTypeFromHandle == null);

            var sourceType = (BoundTypeExpression)this.Visit(node.SourceType);
            var type = this.VisitType(node.Type);

            // Emit needs this helper
            MethodSymbol getTypeFromHandle;
            if (!TryGetWellKnownTypeMember(node.Syntax, WellKnownMember.System_Type__GetTypeFromHandle, out getTypeFromHandle))
            {
                return new BoundTypeOfOperator(node.Syntax, sourceType, null, type, hasErrors: true);
            }

            return node.Update(sourceType, getTypeFromHandle, type);
        }

        public override BoundNode VisitRefTypeOperator(BoundRefTypeOperator node)
        {
            Debug.Assert((object)node.GetTypeFromHandle == null);

            var operand = (BoundExpression)this.Visit(node.Operand);
            var type = this.VisitType(node.Type);

            // Emit needs this helper
            MethodSymbol getTypeFromHandle;
            if (!TryGetWellKnownTypeMember(node.Syntax, WellKnownMember.System_Type__GetTypeFromHandle, out getTypeFromHandle))
            {
                return new BoundRefTypeOperator(node.Syntax, operand, null, type, hasErrors: true);
            }

            return node.Update(operand, getTypeFromHandle, type);
        }
402 403 404

        public override BoundNode VisitTypeOrInstanceInitializers(BoundTypeOrInstanceInitializers node)
        {
405 406 407 408 409 410 411 412 413 414 415 416 417
            ImmutableArray<BoundStatement> originalStatements = node.Statements;
            ArrayBuilder<BoundStatement> statements = ArrayBuilder<BoundStatement>.GetInstance(node.Statements.Length);
            foreach (var initializer in originalStatements)
            {
                if (IsFieldOrPropertyInitializer(initializer))
                {
                    statements.Add(RewriteExpressionStatement((BoundExpressionStatement)initializer, suppressInstrumentation: true));
                }
                else
                {
                    statements.Add(VisitStatement(initializer));
                }
            }
418

419 420 421 422
            int optimizedInitializers = 0;
            bool optimize = _compilation.Options.OptimizationLevel == OptimizationLevel.Release;

            for (int i = 0; i < statements.Count; i++)
423
            {
424 425 426 427 428 429 430 431 432 433
                if (statements[i] == null || (optimize && IsFieldOrPropertyInitializer(originalStatements[i]) && ShouldOptimizeOutInitializer(statements[i])))
                {
                    optimizedInitializers++;
                    if (!_factory.CurrentMethod.IsStatic)
                    {
                        // NOTE: Dev11 removes static initializers if ONLY all of them are optimized out
                        statements[i] = null;
                    }
                }
            }
434

435 436 437 438 439 440 441 442 443 444 445 446 447
            ImmutableArray<BoundStatement> rewrittenStatements;

            if (optimizedInitializers == statements.Count)
            {
                // all are optimized away
                rewrittenStatements = ImmutableArray<BoundStatement>.Empty;
                statements.Free();
            }
            else
            {
                // instrument remaining statements 
                int remaining = 0;
                for (int i = 0; i < statements.Count; i++)
448
                {
449 450 451
                    BoundStatement rewritten = statements[i];

                    if (rewritten != null)
452
                    {
453
                        if (IsFieldOrPropertyInitializer(originalStatements[i]))
454
                        {
455 456 457 458 459
                            var original = (BoundExpressionStatement)originalStatements[i];
                            if (Instrument && !original.WasCompilerGenerated)
                            {
                                rewritten = _instrumenter.InstrumentFieldOrPropertyInitializer(original, rewritten);
                            }
460
                        }
461 462 463

                        statements[remaining] = rewritten;
                        remaining++;
464 465 466
                    }
                }

467 468
                statements.Count = remaining;
                rewrittenStatements = statements.ToImmutableAndFree();
469
            }
470 471 472 473 474 475 476 477 478

            return new BoundStatementList(node.Syntax, rewrittenStatements, node.HasErrors);
        }

        internal static bool IsFieldOrPropertyInitializer(BoundStatement initializer)
        {
            var syntax = initializer.Syntax;

            if (syntax is ExpressionSyntax && syntax?.Parent.Kind() == SyntaxKind.EqualsValueClause) // Should be the initial value.
479
            {
480 481 482 483 484 485
                switch (syntax.Parent?.Parent.Kind())
                {
                    case SyntaxKind.VariableDeclarator:
                    case SyntaxKind.PropertyDeclaration:
                        return (initializer as BoundExpressionStatement)?.Expression.Kind == BoundKind.AssignmentOperator;
                }
486 487
            }

488
            return false;
489 490 491 492 493 494 495 496 497
        }

        /// <summary>
        /// Returns true if the initializer is a field initializer which should be optimized out
        /// </summary>
        private static bool ShouldOptimizeOutInitializer(BoundStatement initializer)
        {
            BoundStatement statement = initializer;

498
            if (statement.Kind != BoundKind.ExpressionStatement)
499 500 501 502 503 504 505 506 507 508 509 510
            {
                return false;
            }

            BoundAssignmentOperator assignment = ((BoundExpressionStatement)statement).Expression as BoundAssignmentOperator;
            if (assignment == null)
            {
                return false;
            }

            Debug.Assert(assignment.Left.Kind == BoundKind.FieldAccess);

511 512 513 514 515 516
            var lhsField = ((BoundFieldAccess)assignment.Left).FieldSymbol;
            if (!lhsField.IsStatic && lhsField.ContainingType.IsStructType())
            {
                return false;
            }

517 518 519
            BoundExpression rhs = assignment.Right;
            return rhs.IsDefaultValue();
        }
520 521

        /// <summary>
V
vsadov 已提交
522
        /// Receivers of struct methods are required to be at least RValues but can be assignable variables.
523
        /// Whether the mutations from the method are propagated back to the 
V
vsadov 已提交
524
        /// receiver instance is conditional on whether the receiver is a variable that can be assigned. 
V
vsadov 已提交
525
        /// If not, then the invocation is performed on a copy.
526
        /// 
V
vsadov 已提交
527
        /// An inconvenient situation may arise when the receiver is an RValue expression (like a ternary operator),
528
        /// which is trivially reduced during lowering to one of its operands and 
V
vsadov 已提交
529
        /// such operand happens to be an assignable variable (like a local). That operation alone would 
530 531 532 533
        /// expose the operand to mutations while it would not be exposed otherwise.
        /// I.E. the transformation becomes semantically observable.
        /// 
        /// To prevent such situations, we will wrap the operand into a node whose only 
V
vsadov 已提交
534
        /// purpose is to never be an assignable expression.
535
        /// </summary>
V
vsadov 已提交
536
        private static BoundExpression EnsureNotAssignableIfUsedAsMethodReceiver(BoundExpression expr)
537 538
        {
            // Leave as-is where receiver mutations cannot happen.
V
vsadov 已提交
539
            if (!WouldBeAssignableIfUsedAsMethodReceiver(expr))
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
            {
                return expr;
            }

            return new BoundConversion(
                expr.Syntax,
                expr,
                Conversion.IdentityValue,
                @checked: false,
                explicitCastInCode: true,
                constantValueOpt: null,
                type: expr.Type)
            { WasCompilerGenerated = true };
        }

V
vsadov 已提交
555
        internal static bool WouldBeAssignableIfUsedAsMethodReceiver(BoundExpression receiver)
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
        {
            // - reference type receivers are byval
            // - special value types (int32, Nullable<T>, . .) do not have mutating members
            if (receiver.Type.IsReferenceType ||
                receiver.Type.OriginalDefinition.SpecialType != SpecialType.None)
            {
                return false;
            }

            switch (receiver.Kind)
            {
                case BoundKind.Parameter:
                case BoundKind.Local:
                case BoundKind.ArrayAccess:
                case BoundKind.ThisReference:
                case BoundKind.BaseReference:
                case BoundKind.PointerIndirectionOperator:
                case BoundKind.RefValueOperator:
V
vsadov 已提交
574
                case BoundKind.PseudoVariable:
575 576 577 578
                case BoundKind.FieldAccess:
                    return true;

                case BoundKind.Call:
V
vsadov 已提交
579
                    return ((BoundCall)receiver).Method.RefKind == RefKind.Ref;
580 581 582 583
            }

            return false;
        }
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609

        private void CheckRefReadOnlySymbols(MethodSymbol symbol)
        {
            var foundRefReadOnly = false;

            if (symbol.ReturnsByRefReadonly)
            {
                foundRefReadOnly = true;
            }
            else
            {
                foreach (var parameter in symbol.Parameters)
                {
                    if (parameter.RefKind == RefKind.RefReadOnly)
                    {
                        foundRefReadOnly = true;
                        break;
                    }
                }
            }

            if (foundRefReadOnly)
            {
                _factory.CompilationState.ModuleBuilderOpt?.EnsureIsReadOnlyAttributeExists();
            }
        }
P
Pilchie 已提交
610
    }
611
}