CSharpGenerateTypeService.cs 40.9 KB
Newer Older
1 2 3 4 5 6 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
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor;
using Microsoft.CodeAnalysis.GenerateType;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp.GenerateType
{
    [ExportLanguageService(typeof(IGenerateTypeService), LanguageNames.CSharp), Shared]
    internal class CSharpGenerateTypeService :
        AbstractGenerateTypeService<CSharpGenerateTypeService, SimpleNameSyntax, ObjectCreationExpressionSyntax, ExpressionSyntax, TypeDeclarationSyntax, ArgumentSyntax>
    {
32
        private static readonly SyntaxAnnotation s_annotation = new SyntaxAnnotation();
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96

        protected override string DefaultFileExtension
        {
            get
            {
                return ".cs";
            }
        }

        protected override ExpressionSyntax GetLeftSideOfDot(SimpleNameSyntax simpleName)
        {
            return simpleName.GetLeftSideOfDot();
        }

        protected override bool IsInCatchDeclaration(ExpressionSyntax expression)
        {
            return expression.IsParentKind(SyntaxKind.CatchDeclaration);
        }

        protected override bool IsArrayElementType(ExpressionSyntax expression)
        {
            return expression.IsParentKind(SyntaxKind.ArrayType) &&
                expression.Parent.IsParentKind(SyntaxKind.ArrayCreationExpression);
        }

        protected override bool IsInValueTypeConstraintContext(
            SemanticModel semanticModel,
            ExpressionSyntax expression,
            CancellationToken cancellationToken)
        {
            if (expression is TypeSyntax && expression.IsParentKind(SyntaxKind.TypeArgumentList))
            {
                var typeArgumentList = (TypeArgumentListSyntax)expression.Parent;
                var symbolInfo = semanticModel.GetSymbolInfo(typeArgumentList.Parent, cancellationToken);
                var symbol = symbolInfo.GetAnySymbol();
                if (symbol.IsConstructor())
                {
                    symbol = symbol.ContainingType;
                }

                var parameterIndex = typeArgumentList.Arguments.IndexOf((TypeSyntax)expression);
                var type = symbol as INamedTypeSymbol;
                if (type != null)
                {
                    type = type.OriginalDefinition;
                    var typeParameter = parameterIndex < type.TypeParameters.Length ? type.TypeParameters[parameterIndex] : null;
                    return typeParameter != null && typeParameter.HasValueTypeConstraint;
                }

                var method = symbol as IMethodSymbol;
                if (method != null)
                {
                    method = method.OriginalDefinition;
                    var typeParameter = parameterIndex < method.TypeParameters.Length ? method.TypeParameters[parameterIndex] : null;
                    return typeParameter != null && typeParameter.HasValueTypeConstraint;
                }
            }

            return false;
        }

        protected override bool IsInInterfaceList(ExpressionSyntax expression)
        {
            if (expression is TypeSyntax &&
97
                expression.Parent is BaseTypeSyntax &&
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 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 171 172 173 174 175 176 177 178 179
                expression.Parent.IsParentKind(SyntaxKind.BaseList) &&
                ((BaseTypeSyntax)expression.Parent).Type == expression)
            {
                var baseList = (BaseListSyntax)expression.Parent.Parent;

                // If it's after the first item, then it's definitely an interface.
                if (baseList.Types[0] != expression.Parent)
                {
                    return true;
                }

                // If it's in the base list of an interface or struct, then it's definitely an
                // interface.
                return
                    baseList.IsParentKind(SyntaxKind.InterfaceDeclaration) ||
                    baseList.IsParentKind(SyntaxKind.StructDeclaration);
            }

            if (expression is TypeSyntax &&
                expression.IsParentKind(SyntaxKind.TypeConstraint) &&
                expression.Parent.IsParentKind(SyntaxKind.TypeParameterConstraintClause))
            {
                var typeConstraint = (TypeConstraintSyntax)expression.Parent;
                var constraintClause = (TypeParameterConstraintClauseSyntax)typeConstraint.Parent;
                var index = constraintClause.Constraints.IndexOf(typeConstraint);

                // If it's after the first item, then it's definitely an interface.
                return index > 0;
            }

            return false;
        }

        protected override bool TryGetNameParts(ExpressionSyntax expression, out IList<string> nameParts)
        {
            nameParts = new List<string>();
            return expression.TryGetNameParts(out nameParts);
        }

        protected override bool TryInitializeState(
            SemanticDocument document,
            SimpleNameSyntax simpleName,
            CancellationToken cancellationToken,
            out GenerateTypeServiceStateOptions generateTypeServiceStateOptions)
        {
            generateTypeServiceStateOptions = new GenerateTypeServiceStateOptions();

            if (simpleName.IsVar)
            {
                return false;
            }

            if (SyntaxFacts.IsAliasQualifier(simpleName))
            {
                return false;
            }

            // Never offer if we're in a using directive, unless its a static using.  The feeling here is that it's highly
            // unlikely that this would be a location where a user would be wanting to generate
            // something.  They're really just trying to reference something that exists but
            // isn't available for some reason (i.e. a missing reference).
            var usingDirectiveSyntax = simpleName.GetAncestorOrThis<UsingDirectiveSyntax>();
            if (usingDirectiveSyntax != null && usingDirectiveSyntax.StaticKeyword.Kind() != SyntaxKind.StaticKeyword)
            {
                return false;
            }

            ExpressionSyntax nameOrMemberAccessExpression = null;
            if (simpleName.IsRightSideOfDot())
            {
                // This simplename comes from the cref
                if (simpleName.IsParentKind(SyntaxKind.NameMemberCref))
                {
                    return false;
                }

                nameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression = (ExpressionSyntax)simpleName.Parent;

                // If we're on the right side of a dot, then the left side better be a name (and
                // not an arbitrary expression).
                var leftSideExpression = simpleName.GetLeftSideOfDot();
                if (!leftSideExpression.IsKind(
180 181 182 183
                    SyntaxKind.QualifiedName,
                    SyntaxKind.IdentifierName,
                    SyntaxKind.AliasQualifiedName,
                    SyntaxKind.GenericName,
184 185 186 187 188 189 190 191 192 193 194
                    SyntaxKind.SimpleMemberAccessExpression))
                {
                    return false;
                }
            }
            else
            {
                nameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression = simpleName;
            }

            // BUG(5712): Don't offer generate type in an enum's base list.
195
            if (nameOrMemberAccessExpression.Parent is BaseTypeSyntax &&
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
                nameOrMemberAccessExpression.Parent.IsParentKind(SyntaxKind.BaseList) &&
                ((BaseTypeSyntax)nameOrMemberAccessExpression.Parent).Type == nameOrMemberAccessExpression &&
                nameOrMemberAccessExpression.Parent.Parent.IsParentKind(SyntaxKind.EnumDeclaration))
            {
                return false;
            }

            // If we can guarantee it's a type only context, great.  Otherwise, we may not want to
            // provide this here.
            var semanticModel = document.SemanticModel;
            if (!SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression))
            {
                // Don't offer Generate Type in an expression context *unless* we're on the left
                // side of a dot.  In that case the user might be making a type that they're
                // accessing a static off of.
                var syntaxTree = semanticModel.SyntaxTree;
                var start = nameOrMemberAccessExpression.SpanStart;
                var tokenOnLeftOfStart = syntaxTree.FindTokenOnLeftOfPosition(start, cancellationToken);
                var isExpressionContext = syntaxTree.IsExpressionContext(start, tokenOnLeftOfStart, attributes: true, cancellationToken: cancellationToken, semanticModelOpt: semanticModel);
                var isStatementContext = syntaxTree.IsStatementContext(start, tokenOnLeftOfStart, cancellationToken);
                var isExpressionOrStatementContext = isExpressionContext || isStatementContext;

                // Delegate Type Creation is not allowed in Non Type Namespace Context
                generateTypeServiceStateOptions.IsDelegateAllowed = false;

                if (!isExpressionOrStatementContext)
                {
                    return false;
                }

                if (!simpleName.IsLeftSideOfDot() && !simpleName.IsInsideNameOf())
                {
                    if (nameOrMemberAccessExpression == null || !nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || !simpleName.IsRightSideOfDot())
                    {
                        return false;
                    }

233
                    var leftSymbol = semanticModel.GetSymbolInfo(((MemberAccessExpressionSyntax)nameOrMemberAccessExpression).Expression, cancellationToken).Symbol;
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 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
                    var token = simpleName.GetLastToken().GetNextToken();

                    // We let only the Namespace to be left of the Dot
                    if (leftSymbol == null ||
                        !leftSymbol.IsKind(SymbolKind.Namespace) ||
                        !token.IsKind(SyntaxKind.DotToken))
                    {
                        return false;
                    }
                    else
                    {
                        generateTypeServiceStateOptions.IsMembersWithModule = true;
                        generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = true;
                    }
                }

                // Global Namespace 
                if (!generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess &&
                    !SyntaxFacts.IsInNamespaceOrTypeContext(simpleName))
                {
                    var token = simpleName.GetLastToken().GetNextToken();
                    if (token.IsKind(SyntaxKind.DotToken) &&
                            simpleName.Parent == token.Parent)
                    {
                        generateTypeServiceStateOptions.IsMembersWithModule = true;
                        generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = true;
                    }
                }
            }

            var fieldDeclaration = simpleName.GetAncestor<FieldDeclarationSyntax>();
            if (fieldDeclaration != null &&
                fieldDeclaration.Parent is CompilationUnitSyntax &&
                document.Document.SourceCodeKind == SourceCodeKind.Regular)
            {
                return false;
            }

            // Check to see if Module could be an option in the Type Generation in Cross Language Generation
            var nextToken = simpleName.GetLastToken().GetNextToken();
            if (simpleName.IsLeftSideOfDot() ||
                nextToken.IsKind(SyntaxKind.DotToken))
            {
                if (simpleName.IsRightSideOfDot())
                {
                    var parent = simpleName.Parent as QualifiedNameSyntax;
                    if (parent != null)
                    {
282
                        var leftSymbol = semanticModel.GetSymbolInfo(parent.Left, cancellationToken).Symbol;
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 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 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472

                        if (leftSymbol != null && leftSymbol.IsKind(SymbolKind.Namespace))
                        {
                            generateTypeServiceStateOptions.IsMembersWithModule = true;
                        }
                    }
                }
            }

            if (SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression))
            {
                if (nextToken.IsKind(SyntaxKind.DotToken))
                {
                    // In Namespace or Type Context we cannot have Interface, Enum, Delegate as part of the Left Expression of a QualifiedName
                    generateTypeServiceStateOptions.IsDelegateAllowed = false;
                    generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = true;
                    generateTypeServiceStateOptions.IsMembersWithModule = true;
                }

                // case: class Foo<T> where T: MyType
                if (nameOrMemberAccessExpression.GetAncestors<TypeConstraintSyntax>().Any())
                {
                    generateTypeServiceStateOptions.IsClassInterfaceTypes = true;
                    return true;
                }

                // Events
                if (nameOrMemberAccessExpression.GetAncestors<EventFieldDeclarationSyntax>().Any() ||
                    nameOrMemberAccessExpression.GetAncestors<EventDeclarationSyntax>().Any())
                {
                    // Case : event foo name11
                    // Only Delegate
                    if (simpleName.Parent != null && !(simpleName.Parent is QualifiedNameSyntax))
                    {
                        generateTypeServiceStateOptions.IsDelegateOnly = true;
                        return true;
                    }

                    // Case : event SomeSymbol.foo name11
                    if (nameOrMemberAccessExpression is QualifiedNameSyntax)
                    {
                        // Only Namespace, Class, Struct and Module are allowed to contain Delegate
                        // Case : event Something.Mytype.<Delegate> Identifier
                        if (nextToken.IsKind(SyntaxKind.DotToken))
                        {
                            if (nameOrMemberAccessExpression.Parent != null && nameOrMemberAccessExpression.Parent is QualifiedNameSyntax)
                            {
                                return true;
                            }
                            else
                            {
                                Contract.Fail("Cannot reach this point");
                            }
                        }
                        else
                        {
                            // Case : event Something.<Delegate> Identifier
                            generateTypeServiceStateOptions.IsDelegateOnly = true;
                            return true;
                        }
                    }
                }
            }
            else
            {
                // MemberAccessExpression
                if ((nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || (nameOrMemberAccessExpression.Parent != null && nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)))
                    && nameOrMemberAccessExpression.IsLeftSideOfDot())
                {
                    // Check to see if the expression is part of Invocation Expression
                    ExpressionSyntax outerMostMemberAccessExpression = null;
                    if (nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression))
                    {
                        outerMostMemberAccessExpression = nameOrMemberAccessExpression;
                    }
                    else
                    {
                        Debug.Assert(nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression));
                        outerMostMemberAccessExpression = (ExpressionSyntax)nameOrMemberAccessExpression.Parent;
                    }

                    outerMostMemberAccessExpression = outerMostMemberAccessExpression.GetAncestorsOrThis<ExpressionSyntax>().SkipWhile((n) => n != null && n.IsKind(SyntaxKind.SimpleMemberAccessExpression)).FirstOrDefault();
                    if (outerMostMemberAccessExpression != null && outerMostMemberAccessExpression is InvocationExpressionSyntax)
                    {
                        generateTypeServiceStateOptions.IsEnumNotAllowed = true;
                    }
                }
            }

            // Cases:
            // // 1 - Function Address
            // var s2 = new MyD2(foo);

            // // 2 - Delegate
            // MyD1 d = null;
            // var s1 = new MyD2(d);

            // // 3 - Action
            // Action action1 = null;
            // var s3 = new MyD2(action1);

            // // 4 - Func
            // Func<int> lambda = () => { return 0; };
            // var s4 = new MyD3(lambda);

            if (nameOrMemberAccessExpression.Parent is ObjectCreationExpressionSyntax)
            {
                var objectCreationExpressionOpt = generateTypeServiceStateOptions.ObjectCreationExpressionOpt = (ObjectCreationExpressionSyntax)nameOrMemberAccessExpression.Parent;

                // Enum and Interface not Allowed in Object Creation Expression
                generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = true;

                if (objectCreationExpressionOpt.ArgumentList != null)
                {
                    if (objectCreationExpressionOpt.ArgumentList.CloseParenToken.IsMissing)
                    {
                        return false;
                    }

                    // Get the Method symbol for the Delegate to be created
                    if (generateTypeServiceStateOptions.IsDelegateAllowed &&
                        objectCreationExpressionOpt.ArgumentList.Arguments.Count == 1)
                    {
                        generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, objectCreationExpressionOpt.ArgumentList.Arguments[0].Expression, cancellationToken);
                    }
                    else
                    {
                        generateTypeServiceStateOptions.IsDelegateAllowed = false;
                    }
                }

                if (objectCreationExpressionOpt.Initializer != null)
                {
                    foreach (var expression in objectCreationExpressionOpt.Initializer.Expressions)
                    {
                        var simpleAssignmentExpression = expression as AssignmentExpressionSyntax;
                        if (simpleAssignmentExpression == null)
                        {
                            continue;
                        }

                        var name = simpleAssignmentExpression.Left as SimpleNameSyntax;
                        if (name == null)
                        {
                            continue;
                        }

                        generateTypeServiceStateOptions.PropertiesToGenerate.Add(name);
                    }
                }
            }

            if (generateTypeServiceStateOptions.IsDelegateAllowed)
            {
                // MyD1 z1 = foo;
                if (nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.VariableDeclaration))
                {
                    var variableDeclaration = (VariableDeclarationSyntax)nameOrMemberAccessExpression.Parent;
                    if (variableDeclaration.Variables.Count != 0)
                    {
                        var firstVarDeclWithInitializer = variableDeclaration.Variables.FirstOrDefault(var => var.Initializer != null && var.Initializer.Value != null);
                        if (firstVarDeclWithInitializer != null && firstVarDeclWithInitializer.Initializer != null && firstVarDeclWithInitializer.Initializer.Value != null)
                        {
                            generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, firstVarDeclWithInitializer.Initializer.Value, cancellationToken);
                        }
                    }
                }

                // var w1 = (MyD1)foo;
                if (nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.CastExpression))
                {
                    var castExpression = (CastExpressionSyntax)nameOrMemberAccessExpression.Parent;
                    if (castExpression.Expression != null)
                    {
                        generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, castExpression.Expression, cancellationToken);
                    }
                }
            }

            return true;
        }

        private IMethodSymbol GetMethodSymbolIfPresent(SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken)
        {
            if (expression == null)
            {
                return null;
            }

            var memberGroup = semanticModel.GetMemberGroup(expression, cancellationToken);
473
            if (memberGroup.Length != 0)
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
            {
                return memberGroup.ElementAt(0).IsKind(SymbolKind.Method) ? (IMethodSymbol)memberGroup.ElementAt(0) : null;
            }

            var expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type;
            if (expressionType.IsDelegateType())
            {
                return ((INamedTypeSymbol)expressionType).DelegateInvokeMethod;
            }

            var expressionSymbol = semanticModel.GetSymbolInfo(expression, cancellationToken).Symbol;
            if (expressionSymbol.IsKind(SymbolKind.Method))
            {
                return (IMethodSymbol)expressionSymbol;
            }

            return null;
        }

        private Accessibility DetermineAccessibilityConstraint(
            State state,
            SemanticModel semanticModel,
            CancellationToken cancellationToken)
        {
            return semanticModel.DetermineAccessibilityConstraint(
                state.NameOrMemberAccessExpression as TypeSyntax, cancellationToken);
        }

        protected override IList<ITypeParameterSymbol> GetTypeParameters(
            State state,
            SemanticModel semanticModel,
            CancellationToken cancellationToken)
        {
            if (state.SimpleName is GenericNameSyntax)
            {
                var genericName = (GenericNameSyntax)state.SimpleName;
                var typeArguments = state.SimpleName.Arity == genericName.TypeArgumentList.Arguments.Count
                    ? genericName.TypeArgumentList.Arguments.OfType<SyntaxNode>().ToList()
                    : Enumerable.Repeat<SyntaxNode>(null, state.SimpleName.Arity);
                return this.GetTypeParameters(state, semanticModel, typeArguments, cancellationToken);
            }

            return SpecializedCollections.EmptyList<ITypeParameterSymbol>();
        }

        protected override bool TryGetArgumentList(ObjectCreationExpressionSyntax objectCreationExpression, out IList<ArgumentSyntax> argumentList)
        {
            if (objectCreationExpression != null && objectCreationExpression.ArgumentList != null)
            {
                argumentList = objectCreationExpression.ArgumentList.Arguments.ToList();
                return true;
            }

            argumentList = null;
            return false;
        }

        protected override IList<string> GenerateParameterNames(
            SemanticModel semanticModel, IList<ArgumentSyntax> arguments)
        {
            return semanticModel.GenerateParameterNames(arguments);
        }

        public override string GetRootNamespace(CompilationOptions options)
        {
            return string.Empty;
        }

        protected override bool IsInVariableTypeContext(ExpressionSyntax expression)
        {
            return false;
        }

        protected override INamedTypeSymbol DetermineTypeToGenerateIn(SemanticModel semanticModel, SimpleNameSyntax simpleName, CancellationToken cancellationToken)
        {
            return semanticModel.GetEnclosingNamedType(simpleName.SpanStart, cancellationToken);
        }

        protected override Accessibility GetAccessibility(State state, SemanticModel semanticModel, bool intoNamespace, CancellationToken cancellationToken)
        {
            var accessibility = DetermineDefaultAccessibility(state, semanticModel, intoNamespace, cancellationToken);
            if (!state.IsTypeGeneratedIntoNamespaceFromMemberAccess)
            {
                var accessibilityConstraint = DetermineAccessibilityConstraint(state, semanticModel, cancellationToken);

                if (accessibilityConstraint == Accessibility.Public ||
                    accessibilityConstraint == Accessibility.Internal)
                {
                    accessibility = accessibilityConstraint;
                }
            }

            return accessibility;
        }

        protected override ITypeSymbol DetermineArgumentType(SemanticModel semanticModel, ArgumentSyntax argument, CancellationToken cancellationToken)
        {
            return argument.DetermineParameterType(semanticModel, cancellationToken);
        }

        protected override bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType)
        {
            return compilation.ClassifyConversion(sourceType, targetType).IsImplicit;
        }

        public override async Task<Tuple<INamespaceSymbol, INamespaceOrTypeSymbol, Location>> GetOrGenerateEnclosingNamespaceSymbol(INamedTypeSymbol namedTypeSymbol, string[] containers, Document selectedDocument, SyntaxNode selectedDocumentRoot, CancellationToken cancellationToken)
        {
            var compilationUnit = (CompilationUnitSyntax)selectedDocumentRoot;
            var semanticModel = await selectedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
            if (containers.Length != 0)
            {
                // Search the NS declaration in the root
                var containerList = new List<string>(containers);
                var enclosingNamespace = GetDeclaringNamespace(containerList, 0, compilationUnit);
                if (enclosingNamespace != null)
                {
590
                    var enclosingNamespaceSymbol = semanticModel.GetSymbolInfo(enclosingNamespace.Name, cancellationToken);
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
                    if (enclosingNamespaceSymbol.Symbol != null)
                    {
                        return Tuple.Create((INamespaceSymbol)enclosingNamespaceSymbol.Symbol,
                                            (INamespaceOrTypeSymbol)namedTypeSymbol,
                                            enclosingNamespace.CloseBraceToken.GetLocation());
                    }
                }
            }

            var globalNamespace = semanticModel.GetEnclosingNamespace(0, cancellationToken);
            var rootNamespaceOrType = namedTypeSymbol.GenerateRootNamespaceOrType(containers);
            var lastMember = compilationUnit.Members.LastOrDefault();
            Location afterThisLocation = null;
            if (lastMember != null)
            {
                afterThisLocation = semanticModel.SyntaxTree.GetLocation(new TextSpan(lastMember.Span.End, 0));
            }
            else
            {
                afterThisLocation = semanticModel.SyntaxTree.GetLocation(new TextSpan());
            }

            return Tuple.Create(globalNamespace,
                                rootNamespaceOrType,
                                afterThisLocation);
        }

        private NamespaceDeclarationSyntax GetDeclaringNamespace(List<string> containers, int indexDone, CompilationUnitSyntax compilationUnit)
        {
            foreach (var member in compilationUnit.Members)
            {
                var namespaceDeclaration = GetDeclaringNamespace(containers, 0, member);
                if (namespaceDeclaration != null)
                {
                    return namespaceDeclaration;
                }
            }

            return null;
        }

        private NamespaceDeclarationSyntax GetDeclaringNamespace(List<string> containers, int indexDone, SyntaxNode localRoot)
        {
            var namespaceDecl = localRoot as NamespaceDeclarationSyntax;
            if (namespaceDecl == null || namespaceDecl.Name is AliasQualifiedNameSyntax)
            {
                return null;
            }

            List<string> namespaceContainers = new List<string>();
            GetNamespaceContainers(namespaceDecl.Name, namespaceContainers);

            if (namespaceContainers.Count + indexDone > containers.Count ||
                !IdentifierMatches(indexDone, namespaceContainers, containers))
            {
                return null;
            }

            indexDone = indexDone + namespaceContainers.Count;
            if (indexDone == containers.Count)
            {
                return namespaceDecl;
            }

            foreach (var member in namespaceDecl.Members)
            {
                var resultant = GetDeclaringNamespace(containers, indexDone, member);
                if (resultant != null)
                {
                    return resultant;
                }
            }

            return null;
        }

        private bool IdentifierMatches(int indexDone, List<string> namespaceContainers, List<string> containers)
        {
            for (int i = 0; i < namespaceContainers.Count; ++i)
            {
                if (namespaceContainers[i] != containers[indexDone + i])
                {
                    return false;
                }
            }

            return true;
        }

        private void GetNamespaceContainers(NameSyntax name, List<string> namespaceContainers)
        {
            if (name is QualifiedNameSyntax)
            {
                GetNamespaceContainers(((QualifiedNameSyntax)name).Left, namespaceContainers);
                namespaceContainers.Add(((QualifiedNameSyntax)name).Right.Identifier.ValueText);
            }
            else
            {
                Debug.Assert(name is SimpleNameSyntax);
                namespaceContainers.Add(((SimpleNameSyntax)name).Identifier.ValueText);
            }
        }

        internal override bool TryGetBaseList(ExpressionSyntax expression, out TypeKindOptions typeKindValue)
        {
            typeKindValue = TypeKindOptions.AllOptions;

            if (expression == null)
            {
                return false;
            }

            var node = expression as SyntaxNode;

            while (node != null)
            {
                if (node is BaseListSyntax)
                {
                    if (node.Parent != null && (node.Parent is InterfaceDeclarationSyntax || node.Parent is StructDeclarationSyntax))
                    {
                        typeKindValue = TypeKindOptions.Interface;
                        return true;
                    }

                    typeKindValue = TypeKindOptions.BaseList;
                    return true;
                }

                node = node.Parent;
            }

            return false;
        }

        internal override bool IsPublicOnlyAccessibility(ExpressionSyntax expression, Project project)
        {
            if (expression == null)
            {
                return false;
            }

            if (GeneratedTypesMustBePublic(project))
            {
                return true;
            }

            var node = expression as SyntaxNode;
            SyntaxNode previousNode = null;

            while (node != null)
            {
                // Types in BaseList, Type Constraint or Member Types cannot be of restricter accessibility than the declaring type
                if ((node is BaseListSyntax || node is TypeParameterConstraintClauseSyntax) &&
                    node.Parent != null &&
                    node.Parent is TypeDeclarationSyntax)
                {
                    var typeDecl = node.Parent as TypeDeclarationSyntax;
                    if (typeDecl != null)
                    {
                        if (typeDecl.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword))
                        {
                            return IsAllContainingTypeDeclsPublic(typeDecl);
                        }
                        else
                        {
                            // The Type Decl which contains the BaseList does not contain Public
                            return false;
                        }
                    }

                    Contract.Fail("Cannot reach this point");
                }

                if ((node is EventDeclarationSyntax || node is EventFieldDeclarationSyntax) &&
                    node.Parent != null &&
                    node.Parent is TypeDeclarationSyntax)
                {
                    // Make sure the GFU is not inside the Accessors
                    if (previousNode != null && previousNode is AccessorListSyntax)
                    {
                        return false;
                    }

                    // Make sure that Event Declaration themselves are Public in the first place
                    if (!node.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword))
                    {
                        return false;
                    }

                    return IsAllContainingTypeDeclsPublic(node);
                }

                previousNode = node;
                node = node.Parent;
            }

            return false;
        }

        private bool IsAllContainingTypeDeclsPublic(SyntaxNode node)
        {
            // Make sure that all the containing Type Declarations are also Public
            var containingTypeDeclarations = node.GetAncestors<TypeDeclarationSyntax>();
            if (containingTypeDeclarations.Count() == 0)
            {
                return true;
            }
            else
            {
                return containingTypeDeclarations.All(typedecl => typedecl.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword));
            }
        }

        internal override bool IsGenericName(SimpleNameSyntax simpleName)
        {
            if (simpleName == null)
            {
                return false;
            }

            var genericName = simpleName as GenericNameSyntax;
            return genericName != null;
        }

        internal override bool IsSimpleName(ExpressionSyntax expression)
        {
            return expression is SimpleNameSyntax;
        }

        internal override Solution TryAddUsingsOrImportToDocument(Solution updatedSolution, SyntaxNode modifiedRoot, Document document, SimpleNameSyntax simpleName, string includeUsingsOrImports, CancellationToken cancellationToken)
        {
            // Nothing to include
            if (string.IsNullOrWhiteSpace(includeUsingsOrImports))
            {
                return updatedSolution;
            }

            var placeSystemNamespaceFirst = document.Project.Solution.Workspace.Options.GetOption(OrganizerOptions.PlaceSystemNamespaceFirst, document.Project.Language);

            SyntaxNode root = null;
            if (modifiedRoot == null)
            {
                root = document.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken);
            }
            else
            {
                root = modifiedRoot;
            }

            if (root is CompilationUnitSyntax)
            {
                var compilationRoot = (CompilationUnitSyntax)root;
                var usingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(includeUsingsOrImports));

                // Check if the usings is already present
                if (compilationRoot.Usings.Where(n => n != null && n.Alias == null)
                                          .Select(n => n.Name.ToString())
                                          .Any(n => n.Equals(includeUsingsOrImports)))
                {
                    return updatedSolution;
                }

                // Check if the GFU is triggered from the namespace same as the usings namespace
                if (IsWithinTheImportingNamespace(document, simpleName.SpanStart, includeUsingsOrImports, cancellationToken))
                {
                    return updatedSolution;
                }

                var addedCompilationRoot = compilationRoot.AddUsingDirectives(new[] { usingDirective }, placeSystemNamespaceFirst, Formatter.Annotation);
                updatedSolution = updatedSolution.WithDocumentSyntaxRoot(document.Id, addedCompilationRoot, PreservationMode.PreserveIdentity);
            }

            return updatedSolution;
        }

        private ITypeSymbol GetPropertyType(
            SimpleNameSyntax property,
            SemanticModel semanticModel,
            ITypeInferenceService typeInference,
            CancellationToken cancellationToken)
        {
            var parent = property.Parent as AssignmentExpressionSyntax;
            if (parent != null)
            {
                return typeInference.InferType(semanticModel, parent.Left, true, cancellationToken);
            }

            return null;
        }

        private IPropertySymbol CreatePropertySymbol(SimpleNameSyntax propertyName, ITypeSymbol propertyType)
        {
            return CodeGenerationSymbolFactory.CreatePropertySymbol(
                attributes: SpecializedCollections.EmptyList<AttributeData>(),
                accessibility: Accessibility.Public,
                modifiers: new DeclarationModifiers(),
                explicitInterfaceSymbol: null,
                name: propertyName.ToString(),
                type: propertyType,
                parameters: null,
891 892
                getMethod: s_accessor,
                setMethod: s_accessor,
893 894 895
                isIndexer: false);
        }

896
        private static readonly IMethodSymbol s_accessor = CodeGenerationSymbolFactory.CreateAccessorSymbol(
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
                    attributes: null,
                    accessibility: Accessibility.Public,
                    statements: null);

        internal override bool TryGenerateProperty(
            SimpleNameSyntax propertyName,
            SemanticModel semanticModel,
            ITypeInferenceService typeInference,
            CancellationToken cancellationToken,
            out IPropertySymbol property)
        {
            property = null;
            var propertyType = GetPropertyType(propertyName, semanticModel, typeInference, cancellationToken);
            if (propertyType == null || propertyType is IErrorTypeSymbol)
            {
                property = CreatePropertySymbol(propertyName, semanticModel.Compilation.ObjectType);
                return true;
            }

            property = CreatePropertySymbol(propertyName, propertyType);
            return true;
        }

920 921 922 923 924 925
        internal override IMethodSymbol GetDelegatingConstructor(
            SemanticDocument document,
            ObjectCreationExpressionSyntax objectCreation,
            INamedTypeSymbol namedType,
            ISet<IMethodSymbol> candidates,
            CancellationToken cancellationToken)
926
        {
927 928
            var model = document.SemanticModel;

929 930 931 932 933 934 935
            var oldNode = objectCreation
                    .AncestorsAndSelf(ascendOutOfTrivia: false)
                    .Where(node => SpeculationAnalyzer.CanSpeculateOnNode(node))
                    .LastOrDefault();

            var typeNameToReplace = objectCreation.Type;
            var newTypeName = namedType.GenerateTypeSyntax();
936
            var newObjectCreation = objectCreation.WithType(newTypeName).WithAdditionalAnnotations(s_annotation);
937
            var newNode = oldNode.ReplaceNode(objectCreation, newObjectCreation);
938

939 940 941
            var speculativeModel = SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(oldNode, newNode, model);
            if (speculativeModel != null)
            {
942
                newObjectCreation = (ObjectCreationExpressionSyntax)newNode.GetAnnotatedNodes(s_annotation).Single();
943
                var symbolInfo = speculativeModel.GetSymbolInfo(newObjectCreation, cancellationToken);
944 945 946
                var parameterTypes = newObjectCreation.ArgumentList.Arguments.Select(
                    a => speculativeModel.GetTypeInfo(a.Expression, cancellationToken).ConvertedType).ToList();

947 948
                return GenerateConstructorHelpers.GetDelegatingConstructor(
                    document, symbolInfo, candidates, namedType, parameterTypes);
949 950 951 952 953 954
            }

            return null;
        }
    }
}