|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +using System.Linq; |
| 5 | +using System.Text; |
| 6 | +using Microsoft.CodeAnalysis; |
| 7 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 8 | +using Microsoft.CodeAnalysis.Operations; |
| 9 | +using Microsoft.AspNetCore.Http.SourceGeneration.StaticRouteHandlerModel; |
| 10 | + |
| 11 | +namespace Microsoft.AspNetCore.Http.SourceGeneration; |
| 12 | + |
| 13 | +[Generator] |
| 14 | +public class RequestDelegateGenerator : IIncrementalGenerator |
| 15 | +{ |
| 16 | + private static readonly string[] _knownMethods = |
| 17 | + { |
| 18 | + "MapGet", |
| 19 | + "MapPost", |
| 20 | + "MapPut", |
| 21 | + "MapDelete", |
| 22 | + "MapPatch", |
| 23 | + "Map", |
| 24 | + }; |
| 25 | + |
| 26 | + public void Initialize(IncrementalGeneratorInitializationContext context) |
| 27 | + { |
| 28 | + var isGeneratorEnabled = context.AnalyzerConfigOptionsProvider.Select((provider, _) => |
| 29 | + provider.GlobalOptions.TryGetValue("build_property.EnableRequestDelegateGenerator", out var enableRequestDelegateGenerator) |
| 30 | + && enableRequestDelegateGenerator == "true"); |
| 31 | + |
| 32 | + var mapActionOperations = context.SyntaxProvider.CreateSyntaxProvider( |
| 33 | + predicate: (node, _) => node is InvocationExpressionSyntax |
| 34 | + { |
| 35 | + Expression: MemberAccessExpressionSyntax |
| 36 | + { |
| 37 | + Name: IdentifierNameSyntax |
| 38 | + { |
| 39 | + Identifier: { ValueText: var method } |
| 40 | + } |
| 41 | + }, |
| 42 | + ArgumentList: { Arguments: { Count: 2 } args } |
| 43 | + } && _knownMethods.Contains(method), |
| 44 | + transform: (context, token) => context.SemanticModel.GetOperation(context.Node, token) as IInvocationOperation); |
| 45 | + |
| 46 | + // Filter out any map actions if the generator is not enabled |
| 47 | + // via config |
| 48 | + var conditionalMapActionOperations = mapActionOperations.Combine(isGeneratorEnabled) |
| 49 | + .Where(pair => pair.Right) |
| 50 | + .Select((pair, _) => pair.Left); |
| 51 | + |
| 52 | + var endpoints = conditionalMapActionOperations |
| 53 | + .Select((operation, _) => StaticRouteHandlerModelParser.GetEndpointFromOperation(operation)) |
| 54 | + .WithTrackingName("EndpointModel"); |
| 55 | + |
| 56 | + var genericThunks = endpoints.Select((endpoint, token) => |
| 57 | + { |
| 58 | + var code = RequestDelegateGeneratorSources.GetGenericThunks(string.Empty); |
| 59 | + return code; |
| 60 | + }); |
| 61 | + |
| 62 | + var thunks = endpoints.Select((endpoint, _) => $@" [{StaticRouteHandlerModelEmitter.EmitSourceKey(endpoint)}] = ( |
| 63 | + (del, builder) => |
| 64 | + {{ |
| 65 | +builder.Metadata.Add(new SourceKey{StaticRouteHandlerModelEmitter.EmitSourceKey(endpoint)}); |
| 66 | + }}, |
| 67 | + (del, builder) => |
| 68 | + {{ |
| 69 | + var handler = ({StaticRouteHandlerModelEmitter.EmitHandlerDelegateType(endpoint)})del; |
| 70 | + EndpointFilterDelegate? filteredInvocation = null; |
| 71 | +
|
| 72 | + if (builder.FilterFactories.Count > 0) |
| 73 | + {{ |
| 74 | + filteredInvocation = BuildFilterDelegate(ic => |
| 75 | + {{ |
| 76 | + if (ic.HttpContext.Response.StatusCode == 400) |
| 77 | + {{ |
| 78 | + return System.Threading.Tasks.ValueTask.FromResult<object?>(Results.Empty); |
| 79 | + }} |
| 80 | + {StaticRouteHandlerModelEmitter.EmitFilteredInvocation()} |
| 81 | + }}, |
| 82 | + builder, |
| 83 | + handler.Method); |
| 84 | + }} |
| 85 | +
|
| 86 | + {StaticRouteHandlerModelEmitter.EmitRequestHandler()} |
| 87 | + {StaticRouteHandlerModelEmitter.EmitFilteredRequestHandler()} |
| 88 | +
|
| 89 | + return filteredInvocation is null ? RequestHandler : RequestHandlerFiltered; |
| 90 | + }}), |
| 91 | +"); |
| 92 | + |
| 93 | + var stronglyTypedEndpointDefinitions = endpoints.Select((endpoint, _) => |
| 94 | + { |
| 95 | + var code = new StringBuilder(); |
| 96 | + code.AppendLine($"internal static Microsoft.AspNetCore.Builder.RouteHandlerBuilder {endpoint.HttpMethod}"); |
| 97 | + code.Append("(this Microsoft.AspNetCore.Routing.IEndpointRouteBuilder endpoints, string pattern, "); |
| 98 | + code.Append(StaticRouteHandlerModelEmitter.EmitHandlerDelegateType(endpoint)); |
| 99 | + code.Append(@" handler, [System.Runtime.CompilerServices.CallerFilePath] string filePath = """", [System.Runtime.CompilerServices.CallerLineNumber]int lineNumber = 0)"); |
| 100 | + code.AppendLine("{"); |
| 101 | + code.AppendLine("return MapCore(endpoints, pattern, handler, GetVerb, filePath, lineNumber);"); |
| 102 | + code.AppendLine("}"); |
| 103 | + return code.ToString(); |
| 104 | + }); |
| 105 | + |
| 106 | + context.RegisterSourceOutput(genericThunks.Collect(), (context, sources) => |
| 107 | + { |
| 108 | + var code = new StringBuilder(); |
| 109 | + foreach (var source in sources) |
| 110 | + { |
| 111 | + code.AppendLine(source); |
| 112 | + } |
| 113 | + context.AddSource("GeneratedRouteBuilderExtensions.GenericThunks.g.cs", code.ToString()); |
| 114 | + }); |
| 115 | + |
| 116 | + context.RegisterSourceOutput(thunks.Collect(), (context, sources) => |
| 117 | + { |
| 118 | + var thunks = new StringBuilder(); |
| 119 | + foreach (var source in sources) |
| 120 | + { |
| 121 | + thunks.AppendLine(source); |
| 122 | + } |
| 123 | + var code = RequestDelegateGeneratorSources.GetThunks(thunks.ToString()); |
| 124 | + context.AddSource("GeneratedRouteBuilderExtensions.Thunks.g.cs", code); |
| 125 | + }); |
| 126 | + |
| 127 | + context.RegisterSourceOutput(stronglyTypedEndpointDefinitions.Collect(), (context, sources) => |
| 128 | + { |
| 129 | + var endpoints = new StringBuilder(); |
| 130 | + foreach (var source in sources) |
| 131 | + { |
| 132 | + endpoints.AppendLine(source); |
| 133 | + } |
| 134 | + var code = RequestDelegateGeneratorSources.GetEndpoints(endpoints.ToString()); |
| 135 | + context.AddSource("GeneratedRouteBuilderExtensions.Endpoints.g.cs", code); |
| 136 | + }); |
| 137 | + |
| 138 | + context.RegisterSourceOutput(isGeneratorEnabled, (context, isGeneratorEnabled) => |
| 139 | + { |
| 140 | + if (isGeneratorEnabled) |
| 141 | + { |
| 142 | + context.AddSource("GeneratedRouteBuilderExtensions.Helpers.g.cs", RequestDelegateGeneratorSources.GeneratedRouteBuilderExtensionsSource); |
| 143 | + } |
| 144 | + }); |
| 145 | + } |
| 146 | +} |
0 commit comments