Пример #1
0
        private static void AddAutoCloneableClasses(GeneratorExecutionContext context, ImmutableList <INamedTypeSymbol> types)
        {
            foreach (var type in types)
            {
                addSource($"{type.Name}.AutoCloneable.g", AutoCloneablePartialClassBuilder.Build(type));
                //NOTE: If this addition is disabled, the crashes to the Roslyn Analyzer process do not occur.
                //      What is it about these static extensions that causes the process to crash?
                addSource($"{type.Name}.AutoCloneableExtensions.g", AutoCloneableExtensionsClassBuilder.Build(type));

                void addSource(string sourceFileName, string sourceCode)
                {
                    var sourceText = CSharpSyntaxTree
                                     .ParseText(SourceText.From(sourceCode, Encoding.UTF8))
                                     .GetRoot().NormalizeWhitespace()
                                     .GetText(Encoding.UTF8);

                    context.AddSource(sourceFileName, sourceText);
                }
            }
        }
        /// <summary>
        /// Called to perform source generation. A generator can use the <paramref name="ctx" />
        /// to add source files via the <see cref="M:Microsoft.CodeAnalysis.GeneratorExecutionContext.AddSource(System.String,Microsoft.CodeAnalysis.Text.SourceText)" />
        /// method.
        /// </summary>
        /// <param name="ctx">The <see cref="T:Microsoft.CodeAnalysis.GeneratorExecutionContext" /> to add source to</param>
        /// <remarks>
        /// This call represents the main generation step. It is called after a <see cref="T:Microsoft.CodeAnalysis.Compilation" /> is
        /// created that contains the user written code.
        /// A generator can use the <see cref="P:Microsoft.CodeAnalysis.GeneratorExecutionContext.Compilation" /> property to
        /// discover information about the users compilation and make decisions on what source to
        /// provide.
        /// </remarks>
        public void Execute(GeneratorExecutionContext ctx)
        {
            var receiver = (MainReceiver)ctx.SyntaxReceiver;

            if (receiver == null || receiver.FoundItems.Count == 0)
            {
                return;
            }

            try
            {
                SourceText extensionsText = SourceText.From(GenerateSourceFile(receiver.FoundItems, ctx), Encoding.UTF8);
                ctx.AddSource("structpacker_extensions.cs", extensionsText);
            }
            catch (Exception e)
            {
                var diag = Diagnostic.Create("RKSPE", "StructPacker", $"StructPacker: {e.Message}", DiagnosticSeverity.Error, DiagnosticSeverity.Error, true, 0);
                ctx.ReportDiagnostic(diag);
            }
        }
Пример #3
0
        public void Execute(GeneratorExecutionContext context)
        {
            var Txts = context.AdditionalFiles.First(E => E.Path.EndsWith(".txt"))
                       .GetText(context.CancellationToken).ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
                       .Select(E => $@"Console.WriteLine(""From {E}"");");
            var Code =
                $@"
using System;
namespace CodeGenerateStarter{{
  public static class SampleCode{{
    public static void ReadTxt(){{
      Console.WriteLine(""StartTxt"");
      {string.Join(Environment.NewLine, Txts)}
    }}
  }}
}}
";

            context.AddSource("SampleCode1", SourceText.From(Code, new UTF8Encoding(false)));
        }
Пример #4
0
        public override void Execute(GeneratorExecutionContext context)
        {
            var contentBuilder = SBPool.Rent();

            Generate(context, contentBuilder);
            if (contentBuilder.Length == 0)
            {
                goto end;
            }

            string source = @$ "{Using}namespace {_CompileSettings.Namespace}
{{
{contentBuilder}
}}";

            // Wht not? Cuz it's f*****g suffering that using SourceGenerator In NetFX
            context.AddSource(UniqueName + ".cs", SourceText.From(source, Encoding.UTF8));
end:
            SBPool.Return(contentBuilder);
        }
        public void Execute(GeneratorExecutionContext context)
        {
            var syntaxReceiver = (AutoToStringSyntaxReciever)context.SyntaxReceiver;

            var userClass = syntaxReceiver.IdentifiedClass;

            if (userClass is null)
            {
                return;
            }


            var properties = userClass.DescendantNodes().OfType <PropertyDeclarationSyntax>();
            var code       = GetSource(userClass.Identifier.Text, properties);

            context.AddSource(
                $"{userClass.Identifier.Text}.generated",
                SourceText.From(code, Encoding.UTF8)
                );
        }
Пример #6
0
        private GeneratorExecutionContext GenerateEncoders(GeneratorData message, FrameParameters param, GeneratorExecutionContext context)
        {
            var strBuilder    = new StringBuilder();
            var fieldsBuilder = new StringBuilder();
            var getMethod     = new StringBuilder();

            AppendEncoderTemplate(strBuilder, param.Namespace, message.Name);

            getMethod.AppendLine($"            var bldr = new MessageFrameBuilder(alloc, {message.Id}, FrameType.{message.FrameType});");
            foreach (var fields in message.Params)
            {
                getMethod.AppendLine($"            bldr.Put(MessageType.{fields.Type}, DataOrder.{fields?.Order ?? DataOrder.Big}, DataTransformation.{fields?.Transform ?? DataTransformation.None}, {fields.Name});");
                fieldsBuilder.AppendLine($"        public {MessageTypeToString(fields.Type, fields.Signed)} {fields.Name} {{ get; set; }}");
            }
            getMethod.Append("            return bldr.ToMessageFrame();");
            strBuilder.Replace("{Fields}", fieldsBuilder.ToString());
            strBuilder.Replace("{GetMethod}", getMethod.ToString());
            context.AddSource($"{message.Name}.SourceGenerated.cs", SourceText.From(strBuilder.ToString(), Encoding.UTF8));
            return(context);
        }
Пример #7
0
        public void Execute(GeneratorExecutionContext context)
        {
            // No initialization required for this one
            //if (!Process.GetCurrentProcess().ProcessName.Equals("devenv", StringComparison.OrdinalIgnoreCase))
            //{
            //	Debugger.Launch();
            //}

            var gen = new XamlCodeGeneration(context);

            if (PlatformHelper.IsValidPlatform(context))
            {
                var genereratedTrees = gen.Generate();

                foreach (var tree in genereratedTrees)
                {
                    context.AddSource(tree.Key, tree.Value);
                }
            }
        }
Пример #8
0
        public void Execute(GeneratorExecutionContext context)
        {
            context.CheckDebugger("ThisAssemblyMetadata");

            var metadata = context.Compilation.Assembly.GetAttributes()
                           .Where(x => x.AttributeClass?.Name == nameof(System.Reflection.AssemblyMetadataAttribute) &&
                                  Microsoft.CodeAnalysis.CSharp.SyntaxFacts.IsValidIdentifier((string)x.ConstructorArguments[0].Value))
                           .Select(x => new KeyValuePair <string, string>((string)x.ConstructorArguments[0].Value, (string)x.ConstructorArguments[1].Value))
                           .Distinct(new KeyValueComparer())
                           .ToDictionary(x => x.Key, x => x.Value);

            var model    = new Model(metadata);
            var language = context.ParseOptions.Language;
            var file     = language.Replace("#", "Sharp") + ".sbntxt";
            var template = Template.Parse(EmbeddedResource.GetContent(file), file);
            var output   = template.Render(model, member => member.Name);

            context.ApplyDesignTimeFix(output, "ThisAssembly.Metadata", language);
            context.AddSource("ThisAssembly.Metadata", SourceText.From(output, Encoding.UTF8));
        }
Пример #9
0
        public void Execute(GeneratorExecutionContext context)
        {
            var compilation           = context.Compilation;
            var allTypes              = compilation.Assembly.GlobalNamespace.GetAllTypes();
            var membersWithAttributes = allTypes.SelectMany(x => x.GetMembers())
                                        .Where(x => x is IPropertySymbol || x is IFieldSymbol)
                                        .Select(x => (Member: x, AttributeData: x.GetAttributeData("global::Nuke.Common.ProjectModel.SolutionAttribute")))
                                        .Where(x => x.AttributeData != null).ToList();

            if (membersWithAttributes.Count == 0)
            {
                return;
            }

            var rootDirectory   = GetRootDirectoryFrom(compilation);
            var compilationUnit = CompilationUnit()
                                  .AddUsings(UsingDirective(IdentifierName("Nuke.Common.ProjectModel")));

            foreach (var(member, attributeData) in membersWithAttributes)
            {
                var attributeArguments = attributeData.NamedArguments;
                if (attributeArguments.SingleOrDefault(x => x.Key == "GenerateProjects").Value.Value as bool? != true)
                {
                    continue;
                }

                var solutionFile = GetSolutionFileFromParametersFile(rootDirectory, member.Name);
                var solution     = SolutionSerializer.DeserializeFromFile <Solution>(solutionFile);

                var classDeclaration = GetSolutionFolderDeclaration(member.Name, solution.SolutionFolders, solution.Projects, isSolution: true);
                compilationUnit = compilationUnit
                                  .AddMembers(member.ContainingType.ContainingNamespace.Equals(compilation.GlobalNamespace, SymbolEqualityComparer.Default)
                        ? NamespaceDeclaration(IdentifierName(member.ContainingType.ContainingNamespace.GetFullName()))
                                              .AddMembers(classDeclaration)
                        : classDeclaration);
            }

            var source = compilationUnit.NormalizeWhitespace().ToFullString();

            context.AddSource(nameof(StronglyTypedSolutionGenerator), source);
        }
        /// <summary>
        /// Adds generated support code for the given updateable record.
        /// </summary>
        /// <param name="context">The generation context.</param>
        /// <param name="updateableRecord">The updateable record.</param>
        private static void AddUpdateableRecordSource
        (
            GeneratorExecutionContext context,
            RecordDeclarationSyntax updateableRecord
        )
        {
            var syntaxTree          = updateableRecord.SyntaxTree;
            var model               = context.Compilation.GetSemanticModel(syntaxTree);
            var declaredSymbol      = model.GetDeclaredSymbol(updateableRecord);
            var containingNamespace = declaredSymbol?.ContainingNamespace;

            if (containingNamespace is null)
            {
                return;
            }

            var qualifiedNamespaceName = ParseName
                                         (
                containingNamespace.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat)
                                         );

            var generatedPart = CompilationUnit()
                                .AddMembers
                                (
                NamespaceDeclaration(qualifiedNamespaceName)
                .AddMembers
                (
                    CreatePartialRecordDeclaration(context, updateableRecord)
                )
                                )
                                .WithLeadingTrivia(Comment("// <auto-generated>"))
                                .AddUsings
                                (
                UsingDirective(IdentifierName("Remora.Discord.Generators.Support"))
                                )
                                .NormalizeWhitespace();

            var text = generatedPart.GetText(Encoding.UTF8);

            context.AddSource($"{updateableRecord.Identifier.ToString()}.g.cs", text);
        }
Пример #11
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));
            }
        }
Пример #12
0
        public void Execute(GeneratorExecutionContext context)
        {
#if DEBUG
            if (!Debugger.IsAttached)
            {
                Debugger.Launch();
            }
#endif

            if (context.SyntaxReceiver is not SyntaxReceiver receiver)
            {
                return;
            }

            var compilation  = context.Compilation;
            var classSymbols = new List <INamedTypeSymbol>();

            foreach (var cls in receiver.CandidateClasses)
            {
                var model = compilation.GetSemanticModel(cls.SyntaxTree);

                var symbol = model.GetDeclaredSymbol(cls);

                if (symbol.GetMembers().OfType <IFieldSymbol>()
                    .Any(x => x.CanBeReferencedByName && x.IsReadOnly && !x.IsStatic && !HasInitializer(x)))
                {
                    classSymbols.Add(symbol);
                }
            }

            var classConstructorsSource = new StringBuilder();

            foreach (var symbol in classSymbols)
            {
                classConstructorsSource.Append(CreateConstructor(symbol));
            }

            var source = new StringBuilder();

            context.AddSource("AutoDependencyInjection.g.cs", SourceText.From(classConstructorsSource.ToString(), Encoding.UTF8));
        }
Пример #13
0
        public void Execute(GeneratorExecutionContext context)
        {
            var pipeName = Guid.NewGuid().ToString();

            context.ReportDiagnostic(Diagnostic.Create("EFX-0", "EFX",
                                                       $"Starting EFX Pipe Generator Server...",
                                                       DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 1));

            var proc = Process.Start("dotnet", $"tool run efx -- pipe-gen --pipe-name {pipeName}");

            context.ReportDiagnostic(Diagnostic.Create("EFX-0", "EFX",
                                                       $"...STARTED: {pipeName} - {proc.Id}",
                                                       DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 1));

            using var client = OutProcGenProtocol.CreateClient(pipeName);

            context.ReportDiagnostic(Diagnostic.Create("EFX-0", "EFX",
                                                       "Connecting to EFX Pipe Generator Server...",
                                                       DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 1));
            client.Connect();
            context.ReportDiagnostic(Diagnostic.Create("EFX-0", "EFX",
                                                       "...CONNECTED",
                                                       DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 1));

            int sources = 0;

            client.BeginSession();
            client.ReadProfiles((profile, path, content) =>
            {
                var name = path
                           .Replace("\\", "__")
                           .Replace("/", "__")
                           .Replace(":", "__");
                context.AddSource(name, content);
                sources++;
            });

            context.ReportDiagnostic(Diagnostic.Create("EFX-0", "EFX",
                                                       $"Added source files: [{sources}]",
                                                       DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 1));
        }
        private static void AddSourceForAdditionalFile(
            GeneratorExecutionContext context,
            AdditionalText file
            )
        {
            // We're going to "comment" out the contents of the file when generating this
            var sourceText = file.GetText(context.CancellationToken);

            Contract.ThrowIfNull(sourceText, "Failed to fetch the text of an additional file.");

            var changes = sourceText.Lines.SelectAsArray(
                l => new TextChange(new TextSpan(l.Start, length: 0), "// ")
                );
            var generatedText = sourceText.WithChanges(changes);

            // TODO: remove the generatedText.ToString() when I don't have to specify the encoding
            context.AddSource(
                GetGeneratedFileName(file.Path),
                SourceText.From(generatedText.ToString(), encoding: Encoding.UTF8)
                );
        }
Пример #15
0
        private void GenerateIsFunctions_RecognizePlugins(GeneratorExecutionContext context)
        {
            var extensions = Extensions();
            var str        = "namespace RecognizerPlugin{";

            str += Environment.NewLine;
            str += "public partial class RecognizePlugins{";
            str += Environment.NewLine;
            foreach (var item in extensions)
            {
                str += $@"
                public RecognizeFileExtensionBL.Recognize  Is_{item}(byte[] content) 
                {{
                    return RecognizeTheFile(content, ""{item}"");
                }}";
            }
            str += "}";
            str += Environment.NewLine;
            str += "}";
            context.AddSource("RecognizePlugins_Is", str);
        }
Пример #16
0
        public void Execute(GeneratorExecutionContext context)
        {
            if (context.SyntaxContextReceiver is MapReceiver receiver)
            {
                var compilation = context.Compilation;
                var results     = MapGenerator.GenerateMappings(receiver, compilation, context.AnalyzerConfigOptions);

                foreach (var(diagnostics, name, text) in results)
                {
                    foreach (var diagnostic in diagnostics)
                    {
                        context.ReportDiagnostic(diagnostic);
                    }

                    if (name is not null && text is not null)
                    {
                        context.AddSource(name, text);
                    }
                }
            }
        }
Пример #17
0
        public void Execute(GeneratorExecutionContext context)
        {
            var compilation   = context.Compilation;
            var attributeName = nameof(InjectAttribute).Replace("Attribute", string.Empty);

            foreach (var syntaxTree in compilation.SyntaxTrees)
            {
                var semanticModel = compilation.GetSemanticModel(syntaxTree);
                var targetTypes   = syntaxTree.GetRoot().DescendantNodes()
                                    .OfType <ClassDeclarationSyntax>()
                                    .Where(x => x.ContainsClassAttribute(attributeName) || x.ContainsFieldAttribute(attributeName))
                                    .Select(x => semanticModel.GetDeclaredSymbol(x))
                                    .OfType <ITypeSymbol>();

                foreach (var targetType in targetTypes)
                {
                    string source = GenerateInjects(targetType);
                    context.AddSource($"{targetType.Name}.Constructor.cs", SourceText.From(source, Encoding.UTF8));
                }
            }
        }
Пример #18
0
 public void Execute(GeneratorExecutionContext context)
 {
     try
     {
         var compilation = context.Compilation;
         var coroutines  = compilation.SyntaxTrees.SelectMany(tree => new Coroutines(tree, compilation));
         foreach (var coroutine in coroutines)
         {
             var tree = coroutine.Document;
             context.AddSource(tree.FilePath.Replace(":", "."), tree.GetText());
         }
     }
     catch (NotImplementedException)
     {
         throw;
     }
     catch (Exception e)
     {
         throw new Exception(e.Message + "\n" + e.StackTrace);
     }
 }
Пример #19
0
        public void Execute(GeneratorExecutionContext context)
        {
            var attributeSource = GetAttributeSource();

            context.AddSource("Attribute.g.cs", attributeSource);

            if (attributeNodeCandidates.Any())
            {
                var compilation     = AddAttributeCompilation(attributeSource, context.Compilation);
                var attributeSymbol = compilation.GetTypeByMetadataName("Yousei.SourceGen.ParameterizedAttribute");
                if (attributeSymbol is null)
                {
                    throw new ArgumentNullException(nameof(attributeSymbol));
                }

                foreach (var attributeNode in attributeNodeCandidates)
                {
                    HandleNode(context, attributeNode, compilation, attributeSymbol);
                }
            }
        }
        public void Execute(GeneratorExecutionContext context)
        {
            var generatedCode = $@"
{SharedMeta.GeneratedByDataBuilderGeneratorPreamble}
using System;

namespace twMVC
{{
    public class HelloWorld
    {{
        public static void Print()
        {{
            Console.WriteLine(""Hello World from Source Generator~~~"");
        }}
    }}
}}
";

            context.AddSource("helloWorldGenerated",
                              SourceText.From(generatedCode, Encoding.UTF8));
        }
Пример #21
0
        /// <inheritdoc/>
        public void Execute(GeneratorExecutionContext context)
        {
            SyntaxReceiver receiver =
                context.SyntaxReceiver as SyntaxReceiver ??
                throw new ApplicationException("Unexpected syntax receiver registered.");
            var compilation = context.Compilation;

            foreach (var classSyntax in receiver.Classes)
            {
                SemanticModel?semanticModel = compilation.GetSemanticModel(classSyntax.SyntaxTree);
                ISymbol?      type          = semanticModel.GetDeclaredSymbol(classSyntax);

                if (type is INamedTypeSymbol symbol && symbol.Derives("BaseDefinition"))
                {
                    ClassInfo classInfo = new ClassInfo(symbol);
                    string    code      = CompiledClassFactory.Generate(classInfo);
                    context.AddSource($"{type.Name}.Compiled.Generated.cs", SourceText.From(code, Encoding.UTF8));
                    File.WriteAllText(Path.Combine(Path.GetTempPath(), $"{type.Name}.Compiled.Generated.cs"), code);
                }
            }
        }
Пример #22
0
    public void Execute(GeneratorExecutionContext context)
    {
        if (context.SyntaxContextReceiver is not BlazorParameterPropertySyntaxReceiver receiver)
        {
            return;
        }

        foreach (var group in receiver.Properties.GroupBy(symbol => symbol.ContainingType, SymbolEqualityComparer.Default))
        {
            var properties = group.Select(p => new BitProperty(p, false)).ToList();
            CheckTwoWayBoundParameter(properties);

            if (group.Key == null)
            {
                continue;
            }

            string classSource = GeneratePartialClassToOverrideSetParameters((INamedTypeSymbol)group.Key, properties);
            context.AddSource($"{group.Key.Name}_SetParametersAsync.AutoGenerated.cs", SourceText.From(classSource, Encoding.UTF8));
        }
    }
Пример #23
0
        public void Execute(GeneratorExecutionContext context)
        {
            var class1 = @"
                using System;

                namespace coverlet1099Console
                {
                    public partial class Class1
                    {
                        public static void Main3()
                        {
                            System.Console.WriteLine(""Hello World!"");
                        }
                    }
                }
            ";

            context.AddSource(
                "class1.generator",
                SourceText.From(class1, Encoding.UTF8));
        }
Пример #24
0
        public void Execute(GeneratorExecutionContext context)
        {
            var sourceBuilder = new StringBuilder();

            sourceBuilder.Append($@"
                using System;

                namespace PostCompilation
                {{
                    class PostCompiledClass
                    {{
                        public static void PrintCrap()
                        {{
                            Console.WriteLine(""It Worked!"");
                        }}
                    }}
                }}
            ");

            context.AddSource("test", SourceText.From(sourceBuilder.ToString(), Encoding.UTF8));
        }
Пример #25
0
        public void Execute(GeneratorExecutionContext context)
        {
            foreach (var f in context.AdditionalFiles)
            {
                var json = JsonConvert.DeserializeObject <List <Element> >(File.ReadAllText(f.Path));

                var sb = new StringBuilder();
                sb.AppendLine("public partial class UIds");
                sb.AppendLine("{");
                foreach (var j in json)
                {
                    sb.AppendLine("\t/// <summary>");
                    sb.AppendLine($"\t/// {j.Id}");
                    sb.AppendLine("\t/// </summary>");
                    sb.AppendLine($"\tpublic const string {j.Id}=\"{j.Id}\";");
                }
                sb.AppendLine("}");

                context.AddSource(Path.GetFileName(f.Path), sb.ToString());
            }
        }
Пример #26
0
        /// <inheritdoc/>
        public void Execute(GeneratorExecutionContext context)
        {
            // Retrieve the populated receiver
            if (!(context.SyntaxContextReceiver is SyntaxReceiver receiver))
            {
                return;
            }

            INamedTypeSymbol?attributeSymbol = context.Compilation.GetTypeByMetadataName("StoredProcedureGeneratedAttribute");

            if (attributeSymbol == null)
            {
                context.ReportDiagnostic(Diagnostic.Create(
                                             new DiagnosticDescriptor("SP0001", "No stored procedure attribute", "Internal analyzer error.", "Internal", DiagnosticSeverity.Error, true),
                                             null));
                return;
            }

            var hasNullableAnnotations = context.Compilation.Options.NullableContextOptions != NullableContextOptions.Disable;

            // Group the fields by class, and generate the source
            foreach (IGrouping <ISymbol?, IMethodSymbol> group in receiver.Methods.GroupBy(f => f.ContainingType, SymbolEqualityComparer.Default))
            {
                var key        = (INamedTypeSymbol)group.Key !;
                var sourceCode = this.ProcessClass(
                    (INamedTypeSymbol)group.Key !,
                    group.ToList(),
                    attributeSymbol,
                    hasNullableAnnotations);
                if (sourceCode == null)
                {
                    context.ReportDiagnostic(Diagnostic.Create(
                                                 new DiagnosticDescriptor("SP0002", "No source code generated attribute", "Internal analyzer error.", "Internal", DiagnosticSeverity.Error, true),
                                                 null));
                    continue;
                }

                context.AddSource($"{key.ToDisplayString().Replace(".", "_")}_sp.cs", SourceText.From(sourceCode, Encoding.UTF8));
            }
        }
Пример #27
0
        public void Execute(GeneratorExecutionContext context)
        {
            var effectFiles  = new List <string>();
            var contentFiles = context.AdditionalFiles.Where(file => file.Path.EndsWith(".mgcb")).ToList().AsReadOnly();

            try
            {
                foreach (var file in contentFiles)
                {
                    var directory = Path.GetDirectoryName(file.Path);
                    var content   = file.GetText(context.CancellationToken);

                    var parser = new MGCBParser();
                    parser.Parse(content.Lines);

                    var effects = parser.Blocks.Where(b => b.Importer.Argument.Equals("EffectImporter"));
                    foreach (var effect in effects)
                    {
                        var path = Path.GetFullPath(Path.Combine(directory, effect.Build.Argument));
                        effectFiles.Add(path);
                    }
                }

                var generator = new EffectWrapperGenerator();
                foreach (var effectFile in effectFiles)
                {
                    var effect     = new Effect(effectFile);
                    var sourceFile = generator.Generate(effect);
                    var sourceText = SourceWriter.ToString(sourceFile);

                    context.AddSource(sourceFile.FileName, sourceText);
                }

                Report(context, "GENG01", $"Generated {effectFiles.Count} effect wrappers", DiagnosticSeverity.Warning);
            }
            catch (Exception ex)
            {
                Report(context, "GENG0X", $"Error: {ex.Message}", DiagnosticSeverity.Error);
            }
        }
Пример #28
0
        public void Execute(GeneratorExecutionContext context)
        {
            if (context.AdditionalFiles.Where(
                    f => context.AnalyzerConfigOptions.GetOptions(f).TryGetValue(SourceItemGroupMetadata, out var sourceItemGroup) &&
                    sourceItemGroup == "PRIResource" &&
                    f.Path.EndsWith(".resw")).Distinct(new AdditionalTextEqualityComparer()).ToImmutableArray() is var resources &&
                resources.Any())
            {
                const char open          = '{';
                const char close         = '}';
                var        stringBuilder = new IndentedStringBuilder(4);
                using (var namespaceBuilder = stringBuilder.Block("namespace Pixeval", open, close))
                {
                    foreach (var additionalText in resources)
                    {
                        var className = $"{Path.GetFileNameWithoutExtension(additionalText.Path)}Resources";
                        using var classBuilder = namespaceBuilder.Block($"public class {className}", open, close);
                        classBuilder.AppendLine(@$ "public static readonly Microsoft.Windows.ApplicationModel.Resources.ResourceLoader ResourceLoader = new(Microsoft.Windows.ApplicationModel.Resources.ResourceLoader.GetDefaultResourceFilePath(), " "{Path.GetFileNameWithoutExtension(additionalText.Path)}" ");");
                        var doc = new XmlDocument();
                        doc.Load(additionalText.Path);
                        if (doc.SelectNodes("//data") is { } nodes)
                        {
                            var elements = nodes.Cast <XmlElement>();
                            foreach (var node in elements)
                            {
                                var name = node.GetAttribute("name");
                                if (name.Contains("["))
                                {
                                    continue;
                                }

                                classBuilder.AppendLine(@$ "public static readonly string {Regex.Replace(name, " \ \.| \ \ : | \ \[| \ \] ", string.Empty)} = ResourceLoader.GetString(" "{name.Replace('.', '/')}" ");");
                            }
                        }
                    }
                }

                context.AddSource("LocalizationResources.g", stringBuilder.ToString());
            }
        }
        public void Execute(GeneratorExecutionContext context)
        {
            StringBuilder sourceBuilder = new StringBuilder(@"// This file is auto-generated!

using Cysharp.Threading.Tasks;
using UnityEngine;

namespace Coimbra.Systems
{
    public partial class ApplicationSystem
    {
        protected void Awake()
        {
            ExecutePlayerLoopEvents();
        }
    
        private async UniTask ExecutePlayerLoopEvents()
        {
            while (gameObject != null)
            {");

            const int last = (int)PlayerLoopTiming.PostTimeUpdate;

            for (int i = (int)PlayerLoopTiming.PreInitialization; i <= last; i++)
            {
                sourceBuilder.Append($@"
                await Yield({i});

                Invoke(new {(PlayerLoopTiming)i}Event(Time.deltaTime));
");
            }

            sourceBuilder.Append(@"            }
        }
    }
}
");

            context.AddSource("ApplicationSystem.generated", SourceText.From(sourceBuilder.ToString(), Encoding.UTF8));
        }
Пример #30
0
        public void Execute(GeneratorExecutionContext context)
        {
            var engine = (SerializationEngine)context.SyntaxContextReceiver;

            if (engine == null)
            {
                return;
            }

            foreach (var item in engine.WorkItems)
            {
                var code = engine.Compile(item);

                foreach (var problem in engine.Problems)
                {
                    Location location = null;

                    foreach (var entry in problem.Locations)
                    {
                        location = entry;

                        if (!location.IsInMetadata)
                        {
                            break;
                        }
                    }

                    context.ReportDiagnostic(Diagnostic.Create(problem.Descriptor, location, problem.Format));
                }

                engine.Problems.Clear();
                context.AddSource($"{item.TypeSymbol.Name}.Serialization.cs",
                                  SourceText.From(code.ToString(), Encoding.UTF8));
            }

            // context.AddSource("Logs.cs",
            //     SourceText.From(
            //         $@"/*{Environment.NewLine + string.Join(Environment.NewLine, engine.Logs) + Environment.NewLine}*/",
            //         Encoding.UTF8));
        }