private static SyntaxNode AddGeneratedHandlerMethodToSolution(
            SemanticDocument document,
            CSharpCodeGenerationOptions options,
            string eventHandlerMethodName,
            SyntaxAnnotation plusEqualsTokenAnnotation,
            CancellationToken cancellationToken)
        {
            var root = document.Root;
            var eventHookupExpression = root.GetAnnotatedNodesAndTokens(plusEqualsTokenAnnotation).Single().AsToken().GetAncestor <AssignmentExpressionSyntax>();

            var typeDecl = eventHookupExpression.GetAncestor <TypeDeclarationSyntax>();

            var generatedMethodSymbol = GetMethodSymbol(document, eventHandlerMethodName, eventHookupExpression, cancellationToken);

            if (generatedMethodSymbol == null)
            {
                return(null);
            }

            var container = (SyntaxNode)typeDecl ?? eventHookupExpression.GetAncestor <CompilationUnitSyntax>();

            var codeGenerator  = document.Document.GetRequiredLanguageService <ICodeGenerationService>();
            var codeGenOptions = options.GetInfo(new CodeGenerationContext(afterThisLocation: eventHookupExpression.GetLocation()), document.Project);
            var newContainer   = codeGenerator.AddMethod(container, generatedMethodSymbol, codeGenOptions, cancellationToken);

            return(root.ReplaceNode(container, newContainer));
        }
Exemplo n.º 2
0
 public ExpressionCodeGenerator(
     InsertionPoint insertionPoint,
     SelectionResult selectionResult,
     AnalyzerResult analyzerResult,
     CSharpCodeGenerationOptions options,
     bool localFunction)
     : base(insertionPoint, selectionResult, analyzerResult, options, localFunction)
 {
 }
 public MultipleStatementsCodeGenerator(
     InsertionPoint insertionPoint,
     SelectionResult selectionResult,
     AnalyzerResult analyzerResult,
     CSharpCodeGenerationOptions options,
     bool localFunction)
     : base(insertionPoint, selectionResult, analyzerResult, options, localFunction)
 {
 }
Exemplo n.º 4
0
 public MultipleStatementsCodeGenerator(
     InsertionPoint insertionPoint,
     SelectionResult selectionResult,
     AnalyzerResult analyzerResult,
     CSharpCodeGenerationOptions options,
     NamingStylePreferencesProvider namingPreferences,
     bool localFunction)
     : base(insertionPoint, selectionResult, analyzerResult, options, namingPreferences, localFunction)
 {
 }
        public static SyntaxNode ConvertMethodsToProperty(
            CSharpCodeGenerationOptions options, LanguageVersion languageVersion,
            SemanticModel semanticModel, SyntaxGenerator generator, GetAndSetMethods getAndSetMethods,
            string propertyName, bool nameChanged)
        {
            var propertyDeclaration = ConvertMethodsToPropertyWorker(
                options, languageVersion, semanticModel,
                generator, getAndSetMethods, propertyName, nameChanged);

            var expressionBodyPreference = options.PreferExpressionBodiedProperties.Value;

            if (expressionBodyPreference != ExpressionBodyPreference.Never)
            {
                if (propertyDeclaration.AccessorList?.Accessors.Count == 1 &&
                    propertyDeclaration.AccessorList?.Accessors[0].Kind() == SyntaxKind.GetAccessorDeclaration)
                {
                    var getAccessor = propertyDeclaration.AccessorList.Accessors[0];
                    if (getAccessor.ExpressionBody != null)
                    {
                        return(propertyDeclaration.WithExpressionBody(getAccessor.ExpressionBody)
                               .WithSemicolonToken(getAccessor.SemicolonToken)
                               .WithAccessorList(null));
                    }
                    else if (getAccessor.Body != null &&
                             getAccessor.Body.TryConvertToArrowExpressionBody(
                                 propertyDeclaration.Kind(), languageVersion, expressionBodyPreference,
                                 out var arrowExpression, out var semicolonToken))
                    {
                        return(propertyDeclaration.WithExpressionBody(arrowExpression)
                               .WithSemicolonToken(semicolonToken)
                               .WithAccessorList(null));
                    }
                }
            }
            else
            {
                if (propertyDeclaration.ExpressionBody != null &&
                    propertyDeclaration.ExpressionBody.TryConvertToBlock(
                        propertyDeclaration.SemicolonToken,
                        createReturnStatementForExpression: true,
                        block: out var block))
                {
                    var accessor =
                        SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                        .WithBody(block);

                    var accessorList = SyntaxFactory.AccessorList(SyntaxFactory.SingletonList(accessor));
                    return(propertyDeclaration.WithAccessorList(accessorList)
                           .WithExpressionBody(null)
                           .WithSemicolonToken(default));
        private static Diagnostic?AnalyzeSyntax(
            CSharpCodeGenerationOptions options, SyntaxNode declaration, UseExpressionBodyHelper helper)
        {
            var preference = helper.GetExpressionBodyPreference(options);
            var severity   = preference.Notification.Severity;

            if (helper.CanOfferUseExpressionBody(preference, declaration, forAnalyzer: true))
            {
                var location = severity.WithDefaultSeverity(DiagnosticSeverity.Hidden) == ReportDiagnostic.Hidden
                    ? declaration.GetLocation()
                    : helper.GetDiagnosticLocation(declaration);

                var additionalLocations = ImmutableArray.Create(declaration.GetLocation());
                var properties          = ImmutableDictionary <string, string?> .Empty.Add(nameof(UseExpressionBody), "");

                return(DiagnosticHelper.Create(
                           CreateDescriptorWithId(helper.DiagnosticId, helper.EnforceOnBuild, helper.UseExpressionBodyTitle, helper.UseExpressionBodyTitle),
                           location, severity, additionalLocations: additionalLocations, properties: properties));
            }

            if (helper.CanOfferUseBlockBody(preference, declaration, forAnalyzer: true, out var fixesError, out var expressionBody))
            {
                // They have an expression body.  Create a diagnostic to convert it to a block
                // if they don't want expression bodies for this member.
                var location = severity.WithDefaultSeverity(DiagnosticSeverity.Hidden) == ReportDiagnostic.Hidden
                    ? declaration.GetLocation()
                    : expressionBody.GetLocation();

                var properties = ImmutableDictionary <string, string?> .Empty;
                if (fixesError)
                {
                    properties = properties.Add(FixesError, "");
                }

                var additionalLocations = ImmutableArray.Create(declaration.GetLocation());
                return(DiagnosticHelper.Create(
                           CreateDescriptorWithId(helper.DiagnosticId, helper.EnforceOnBuild, helper.UseBlockBodyTitle, helper.UseBlockBodyTitle),
                           location, severity, additionalLocations: additionalLocations, properties: properties));
            }

            return(null);
        }
Exemplo n.º 7
0
 public abstract CodeStyleOption2 <ExpressionBodyPreference> GetExpressionBodyPreference(CSharpCodeGenerationOptions options);
Exemplo n.º 8
0
            public async Task <MetadataAsSourceFile> GenerateSourceAsync(
                string?symbolMetadataName = null,
                Project?project           = null,
                bool signaturesOnly       = true,
                bool fileScopedNamespaces = false)
            {
                symbolMetadataName ??= AbstractMetadataAsSourceTests.DefaultSymbolMetadataName;
                project ??= this.DefaultProject;

                // Get an ISymbol corresponding to the metadata name
                var compilation = await project.GetRequiredCompilationAsync(CancellationToken.None);

                var diagnostics = compilation.GetDiagnostics().ToArray();

                Assert.Equal(0, diagnostics.Length);
                var symbol = await ResolveSymbolAsync(symbolMetadataName, compilation);

                Contract.ThrowIfNull(symbol);

                if (!signaturesOnly)
                {
                    foreach (var reference in compilation.References)
                    {
                        if (AssemblyResolver.TestAccessor.ContainsInMemoryImage(reference))
                        {
                            continue;
                        }

                        if (reference is PortableExecutableReference portableExecutable)
                        {
                            Assert.True(File.Exists(portableExecutable.FilePath), $"'{portableExecutable.FilePath}' does not exist for reference '{portableExecutable.Display}'");
                            Assert.True(Path.IsPathRooted(portableExecutable.FilePath), $"'{portableExecutable.FilePath}' is not a fully-qualified file name");
                        }
                        else
                        {
                            Assert.True(File.Exists(reference.Display), $"'{reference.Display}' does not exist");
                            Assert.True(Path.IsPathRooted(reference.Display), $"'{reference.Display}' is not a fully-qualified file name");
                        }
                    }
                }

                var options = MetadataAsSourceOptions.GetDefault(project.LanguageServices);

                if (fileScopedNamespaces)
                {
                    options = options with
                    {
                        GenerationOptions = options.GenerationOptions with
                        {
                            GenerationOptions = new CSharpCodeGenerationOptions
                            {
                                NamespaceDeclarations = new CodeStyleOption2 <NamespaceDeclarationPreference>(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Silent)
                            }
                        }
                    };
                }

                // Generate and hold onto the result so it can be disposed of with this context
                var result = await _metadataAsSourceService.GetGeneratedFileAsync(project, symbol, signaturesOnly, options);

                return(result);
            }