Пример #1
0
        protected override void Execute(
            GeneratorExecutionContext context, SyntaxReceiver syntaxReceiver, AddCacheSource <TypeDeclarationSyntax> addCacheSource,
            ReportCacheDiagnostic <TypeDeclarationSyntax> cacheDiagnostic
            )
        {
            var compilation = context.Compilation;

            var registrationOptionsInterfaceSymbol             = compilation.GetTypeByMetadataName("OmniSharp.Extensions.LanguageServer.Protocol.IRegistrationOptions") !;
            var textDocumentRegistrationOptionsInterfaceSymbol =
                compilation.GetTypeByMetadataName("OmniSharp.Extensions.LanguageServer.Protocol.Models.ITextDocumentRegistrationOptions") !;
            var workDoneProgressOptionsInterfaceSymbol   = compilation.GetTypeByMetadataName("OmniSharp.Extensions.LanguageServer.Protocol.Models.IWorkDoneProgressOptions") !;
            var staticRegistrationOptionsInterfaceSymbol = compilation.GetTypeByMetadataName("OmniSharp.Extensions.LanguageServer.Protocol.Models.IStaticRegistrationOptions") !;

            foreach (var registrationOptions in syntaxReceiver.RegistrationOptions)
            {
                try
                {
                    var semanticModel = context.Compilation.GetSemanticModel(registrationOptions.SyntaxTree);
                    var typeSymbol    = semanticModel.GetDeclaredSymbol(registrationOptions);

                    if (typeSymbol is not {
                    })
                    {
                        continue;
                    }
                    var data = RegistrationOptionAttributes.Parse(context, registrationOptions, typeSymbol);
                    if (data is not {
                    })
Пример #2
0
        protected override void Execute(
            GeneratorExecutionContext context, SyntaxReceiver syntaxReceiver, AddCacheSource <TypeDeclarationSyntax> addCacheSource,
            ReportCacheDiagnostic <TypeDeclarationSyntax> cacheDiagnostic
            )
        {
            var namespaces = new HashSet <string>()
            {
                "OmniSharp.Extensions.LanguageServer.Protocol"
            };
            var types = syntaxReceiver.FoundNodes
                        .Concat(syntaxReceiver.Handlers)
                        .Select(
                options => {
                var semanticModel = context.Compilation.GetSemanticModel(options.SyntaxTree);
                foreach (var item in options.SyntaxTree.GetCompilationUnitRoot()
                         .Usings
                         .Where(z => z.Alias == null)
                         .Select(z => z.Name.ToFullString()))
                {
                    namespaces.Add(item);
                }

                var typeSymbol = semanticModel.GetDeclaredSymbol(options) !;

                return(SyntaxFactory.Attribute(
                           SyntaxFactory.IdentifierName("AssemblyCapabilityKey"), SyntaxFactory.AttributeArgumentList(
                               SyntaxFactory.SeparatedList(
                                   new[] {
                    SyntaxFactory.AttributeArgument(
                        SyntaxFactory.TypeOfExpression(SyntaxFactory.ParseName(typeSymbol.ToDisplayString()))
                        ),
                }.Concat(options.AttributeLists.GetAttribute("CapabilityKey") !.ArgumentList !.Arguments)
                                   )
                               )
                           ));
            }
                )
                        .ToArray();

            if (types.Any())
            {
                var cu = SyntaxFactory.CompilationUnit()
                         .WithUsings(SyntaxFactory.List(namespaces.OrderBy(z => z).Select(z => SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(z)))))
                         .AddAttributeLists(
                    SyntaxFactory.AttributeList(
                        target: SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword)), SyntaxFactory.SeparatedList(types)
                        )
                    )
                         .WithLeadingTrivia(SyntaxFactory.Comment(Preamble.GeneratedByATool))
                         .WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed);

                context.AddSource("AssemblyCapabilityKeys.cs", cu.NormalizeWhitespace().GetText(Encoding.UTF8));
            }
        }
Пример #3
0
        protected override void Execute(
            GeneratorExecutionContext context, SyntaxReceiver syntaxReceiver, AddCacheSource <TypeDeclarationSyntax> addCacheSource,
            ReportCacheDiagnostic <TypeDeclarationSyntax> cacheDiagnostic
            )
        {
            foreach (var candidate in syntaxReceiver.Candidates)
            {
                var members = new List <MemberDeclarationSyntax>();
                var model   = context.Compilation.GetSemanticModel(candidate.SyntaxTree);
                var symbol  = model.GetDeclaredSymbol(candidate);
                if (symbol is null)
                {
                    continue;
                }

                var autoImplementProperties = AutoImplementInterfaces(candidate, symbol).ToArray();
                if (autoImplementProperties is { Length: > 0 })
Пример #4
0
        protected override void Execute(
            GeneratorExecutionContext context, SyntaxReceiver syntaxReceiver, AddCacheSource <TypeDeclarationSyntax> addCacheSource,
            ReportCacheDiagnostic <TypeDeclarationSyntax> cacheDiagnostic
            )
        {
            var generateTypedDataAttributeSymbol = context.Compilation.GetTypeByMetadataName("OmniSharp.Extensions.LanguageServer.Protocol.Generation.GenerateTypedDataAttribute");
            var generateContainerAttributeSymbol = context.Compilation.GetTypeByMetadataName("OmniSharp.Extensions.LanguageServer.Protocol.Generation.GenerateContainerAttribute");

            foreach (var classToContain in syntaxReceiver.CreateContainers)
            {
                var semanticModel = context.Compilation.GetSemanticModel(classToContain.SyntaxTree);
                var typeSymbol    = semanticModel.GetDeclaredSymbol(classToContain);
                var attribute     = typeSymbol?.GetAttributes().FirstOrDefault(z => SymbolEqualityComparer.Default.Equals(z.AttributeClass, generateContainerAttributeSymbol));
                if (typeSymbol == null || attribute is null)
                {
                    continue;
                }

                var containerName = attribute is { ConstructorArguments : { Length : > 0 } arguments } ? arguments[0].Value as string : null;
Пример #5
0
        protected override void Execute(
            GeneratorExecutionContext context, SyntaxReceiver syntaxReceiver, AddCacheSource <TypeDeclarationSyntax> addCacheSource,
            ReportCacheDiagnostic <TypeDeclarationSyntax> cacheDiagnostic
            )
        {
            var namespaces = new HashSet <string>()
            {
                "OmniSharp.Extensions.JsonRpc"
            };
            var types = syntaxReceiver.FoundNodes
                        .Concat(syntaxReceiver.Handlers)
                        .Select(
                options => {
                var semanticModel = context.Compilation.GetSemanticModel(options.SyntaxTree);
                var typeSymbol    = semanticModel.GetDeclaredSymbol(options) !;

                return(AttributeArgument(TypeOfExpression(ParseName(typeSymbol.ToDisplayString()))));
            }
                )
                        .ToArray();

            if (types.Any())
            {
                var cu = CompilationUnit()
                         .WithUsings(List(namespaces.OrderBy(z => z).Select(z => UsingDirective(ParseName(z)))))
                         .WithLeadingTrivia(Comment(Preamble.GeneratedByATool))
                         .WithTrailingTrivia(CarriageReturnLineFeed);
                while (types.Length > 0)
                {
                    var innerTypes = types.Take(10).ToArray();
                    types = types.Skip(10).ToArray();
                    cu    = cu.AddAttributeLists(
                        AttributeList(
                            target: AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)),
                            SingletonSeparatedList(Attribute(IdentifierName("AssemblyJsonRpcHandlers"), AttributeArgumentList(SeparatedList(innerTypes))))
                            )
                        );
                }
                context.AddSource("AssemblyJsonRpcHandlers.cs", cu.NormalizeWhitespace().GetText(Encoding.UTF8));
            }
        }
Пример #6
0
        protected override void Execute(
            GeneratorExecutionContext context, SyntaxReceiver syntaxReceiver, AddCacheSource <TypeDeclarationSyntax> addCacheSource,
            ReportCacheDiagnostic <TypeDeclarationSyntax> cacheDiagnostic
            )
        {
            var handlers = new List <AttributeArgumentSyntax>();

            foreach (var candidateClass in syntaxReceiver.Candidates)
            {
//                context.ReportDiagnostic(Diagnostic.Create(GeneratorDiagnostics.Message, null, $"candidate: {candidateClass.Identifier.ToFullString()}"));
                // can this be async???
                context.CancellationToken.ThrowIfCancellationRequested();

                var additionalUsings = new HashSet <string> {
                    "System",
                    "System.Collections.Generic",
                    "System.Threading",
                    "System.Threading.Tasks",
                    "MediatR",
                    "Microsoft.Extensions.DependencyInjection"
                };

                GeneratorData?actionItem = null;

                try
                {
                    actionItem = GeneratorData.Create(context, candidateClass, addCacheSource, cacheDiagnostic, additionalUsings);
                }
                catch (Exception e)
                {
                    context.ReportDiagnostic(Diagnostic.Create(GeneratorDiagnostics.Exception, candidateClass.GetLocation(), e.Message, e.StackTrace ?? string.Empty));
                    Debug.WriteLine(e);
                    Debug.WriteLine(e.StackTrace);
                }

                if (actionItem is null)
                {
                    continue;
                }

                var members = CompilationUnitGeneratorStrategies.Aggregate(
                    new List <MemberDeclarationSyntax>(), (m, strategy) => {
                    try
                    {
                        m.AddRange(strategy.Apply(actionItem));
                    }
                    catch (Exception e)
                    {
                        context.ReportDiagnostic(
                            Diagnostic.Create(
                                GeneratorDiagnostics.Exception, candidateClass.GetLocation(), $"Strategy {strategy.GetType().FullName} failed!" + " - " + e.Message,
                                e.StackTrace ?? string.Empty
                                )
                            );
                        Debug.WriteLine($"Strategy {strategy.GetType().FullName} failed!");
                        Debug.WriteLine(e);
                        Debug.WriteLine(e.StackTrace);
                    }

                    return(m);
                }
                    );

                if (!members.Any())
                {
                    continue;
                }

                var namespacesMapping = new Dictionary <string, string[]>()
                {
                    ["OmniSharp.Extensions.DebugAdapter"] = new[] {
                        "OmniSharp.Extensions.DebugAdapter.Protocol",
                        "OmniSharp.Extensions.DebugAdapter.Protocol.Models",
                        "OmniSharp.Extensions.DebugAdapter.Protocol.Events",
                        "OmniSharp.Extensions.DebugAdapter.Protocol.Requests"
                    },
                    ["OmniSharp.Extensions.LanguageProtocol"] = new[] {
                        "OmniSharp.Extensions.LanguageServer.Protocol",
                        "OmniSharp.Extensions.LanguageServer.Protocol.Models"
                    },
                };

                foreach (var assembly in actionItem.Context.Compilation.References
                         .Select(actionItem.Context.Compilation.GetAssemblyOrModuleSymbol)
                         .OfType <IAssemblySymbol>()
                         .Concat(new[] { actionItem.Context.Compilation.Assembly }))
                {
                    if (namespacesMapping.TryGetValue(assembly.Name, out var additionalNamespaceUsings))
                    {
                        foreach (var item in additionalNamespaceUsings)
                        {
                            additionalUsings.Add(item);
                        }
                    }
                }

                var existingUsings = candidateClass.SyntaxTree.GetCompilationUnitRoot()
                                     .Usings
                                     .Select(x => x.WithoutTrivia())
                                     .Union(
                    additionalUsings
                    .Except(
                        candidateClass.SyntaxTree.GetCompilationUnitRoot()
                        .Usings
                        .Where(z => z.Alias == null)
                        .Select(z => z.Name.ToFullString())
                        )
                    .Except(new [] { "<global namespace>" })                                        // I think there is a better way... but for now..
                    .Distinct()
                    .Select(z => UsingDirective(IdentifierName(z)))
                    )
                                     .OrderBy(x => x.Name.ToFullString())
                                     .ToImmutableArray();

                var cu = CompilationUnit(
                    List <ExternAliasDirectiveSyntax>(),
                    List(existingUsings),
                    List <AttributeListSyntax>(),
                    List(members)
                    )
                         .WithLeadingTrivia(Comment(Preamble.GeneratedByATool))
                         .WithTrailingTrivia(CarriageReturnLineFeed);

                addCacheSource(
                    $"{candidateClass.Identifier.Text}{( candidateClass.Arity > 0 ? candidateClass.Arity.ToString() : "" )}.cs",
                    candidateClass,
                    cu.NormalizeWhitespace().GetText(Encoding.UTF8)
                    );

                handlers.AddRange(actionItem.AssemblyJsonRpcHandlersAttributeArguments);
            }

            {
                var namespaces = new HashSet <string>()
                {
                    "OmniSharp.Extensions.JsonRpc"
                };
                if (handlers.Any())
                {
                    var types = handlers.ToArray();
                    var cu    = CompilationUnit()
                                .WithUsings(List(namespaces.OrderBy(z => z).Select(z => UsingDirective(ParseName(z)))))
                                .WithLeadingTrivia(Comment(Preamble.GeneratedByATool))
                                .WithTrailingTrivia(CarriageReturnLineFeed);
                    while (types.Length > 0)
                    {
                        var innerTypes = types.Take(10).ToArray();
                        types = types.Skip(10).ToArray();
                        cu    = cu.AddAttributeLists(
                            AttributeList(
                                target: AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)),
                                SingletonSeparatedList(Attribute(IdentifierName("AssemblyJsonRpcHandlers"), AttributeArgumentList(SeparatedList(innerTypes))))
                                )
                            );
                    }

                    context.AddSource("GeneratedAssemblyJsonRpcHandlers.cs", cu.NormalizeWhitespace().GetText(Encoding.UTF8));
                }
            }
        }
Пример #7
0
 protected abstract void Execute(
     GeneratorExecutionContext context, T syntaxReceiver, AddCacheSource <TSyntax> addCacheSource, ReportCacheDiagnostic <TSyntax> cacheDiagnostic
     );