private void GenerateCode(SourceGeneratorContext context)
        {
            foreach (CodeGenerationConfigBuilder builder in _config.Builders)
            {
                if (builder.Input == null || builder.Output == null)
                {
                    _logger.LogError("Skipping generation", "Input or ouput object is not provided.", null);
                    continue;
                }

                foreach (INamedItem @object in _renderEngine.GetMatchedObjects(context, _visitor, builder))
                {
                    RenderResultModel renderResult = _renderEngine.RenderMatch(@object, builder);

                    if (renderResult != null)
                    {
                        _generationEngine.AddToCurrentGeneration(renderResult);
                    }
                    else
                    {
                        _logger.LogError("Skipping generation", "File failed to render.", null);
                        continue;
                    }
                }

                _generationEngine.PublishGeneration(context);
            }
        }
Exemple #2
0
        public override void Execute(SourceGeneratorContext context)
        {
            var project = context.GetProjectInstance();

            _bindingsPaths    = project.GetPropertyValue("TSBindingsPath")?.ToString();
            _sourceAssemblies = project.GetItems("TSBindingAssemblySource").Select(s => s.EvaluatedInclude).ToArray();

            if (!string.IsNullOrEmpty(_bindingsPaths))
            {
                _stringSymbol         = context.Compilation.GetTypeByMetadataName("System.String");
                _intSymbol            = context.Compilation.GetTypeByMetadataName("System.Int32");
                _floatSymbol          = context.Compilation.GetTypeByMetadataName("System.Single");
                _doubleSymbol         = context.Compilation.GetTypeByMetadataName("System.Double");
                _byteSymbol           = context.Compilation.GetTypeByMetadataName("System.Byte");
                _shortSymbol          = context.Compilation.GetTypeByMetadataName("System.Int16");
                _intPtrSymbol         = context.Compilation.GetTypeByMetadataName("System.IntPtr");
                _boolSymbol           = context.Compilation.GetTypeByMetadataName("System.Boolean");
                _longSymbol           = context.Compilation.GetTypeByMetadataName("System.Int64");
                _structLayoutSymbol   = context.Compilation.GetTypeByMetadataName(typeof(System.Runtime.InteropServices.StructLayoutAttribute).FullName);
                _interopMessageSymbol = context.Compilation.GetTypeByMetadataName("Uno.Foundation.Interop.TSInteropMessageAttribute");

                var modules = from ext in context.Compilation.ExternalReferences
                              let sym = context.Compilation.GetAssemblyOrModuleSymbol(ext) as IAssemblySymbol
                                        where _sourceAssemblies.Contains(sym.Name)
                                        from module in sym.Modules
                                        select module;

                modules = modules.Concat(context.Compilation.SourceModule);

                GenerateTSMarshallingLayouts(modules);
            }
        }
        public void Execute(SourceGeneratorContext context)
        {
            _config = ConfigParser.GetConfig(_visitor, context);

            if (!string.IsNullOrEmpty(_config.Debugging?.LogOutput))
            {
                _logger.RegisterFactory(
                    new FileLogOutputFactory("Log Output",
                                             _config.Debugging.LogOutput,
                                             LogScope.Error | LogScope.Warning | LogScope.Information,
                                             LogScope.Objects,
                                             DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss"))
                    );
            }
            if (string.IsNullOrEmpty(_config.Debugging?.ObjectOutput))
            {
                _logger.RegisterFactory(
                    new FileLogOutputFactory("Object Output",
                                             _config.Debugging?.ObjectOutput,
                                             LogScope.Error | LogScope.Warning | LogScope.Information,
                                             LogScope.Objects,
                                             DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss"))
                    );
            }

            if (_config?.Builders == null)
            {
                _logger.LogError("Skipping generation", "No template config found.", null);
            }

            _generationEngine.NewGeneration();

            GenerateCode(context);
        }
Exemple #4
0
        private static void BuildSearchPaths(SourceGeneratorContext context, IndentedStringBuilder sb)
        {
            var projectInstance = context.GetProjectInstance();

            sb.AppendLineInvariant($"[assembly: global::Uno.UI.RemoteControl.ProjectConfigurationAttribute(");
            sb.AppendLineInvariant($"@\"{projectInstance.FullPath}\",\n");

            var sources = new[] {
                "Page",
                "ApplicationDefinition",
                "ProjectReference",
            };

            IEnumerable <string> BuildSearchPath(string s)
            => projectInstance
            .GetItems(s)
            .Select(v => v.EvaluatedInclude)
            .Select(v => Path.IsPathRooted(v) ? v : Path.Combine(projectInstance.Directory, v));

            var xamlPaths = from item in sources.SelectMany(BuildSearchPath)
                            select Path.GetDirectoryName(item);

            var distictPaths = string.Join(",\n", xamlPaths.Distinct().Select(p => $"@\"{p}\""));

            sb.AppendLineInvariant("{0}", $"new[]{{{distictPaths}}}");

            sb.AppendLineInvariant($")]");
        }
Exemple #5
0
        private static void BuildEndPointAttribute(SourceGeneratorContext context, IndentedStringBuilder sb)
        {
            var unoRemoteControlPort = context.GetProjectInstance().GetPropertyValue("UnoRemoteControlPort");

            if (string.IsNullOrEmpty(unoRemoteControlPort))
            {
                unoRemoteControlPort = "0";
            }

            var unoRemoteControlHost = context.GetProjectInstance().GetPropertyValue("UnoRemoteControlHost");

            if (string.IsNullOrEmpty(unoRemoteControlHost))
            {
                var addresses = NetworkInterface.GetAllNetworkInterfaces()
                                .SelectMany(x => x.GetIPProperties().UnicastAddresses)
                                .Where(x => !IPAddress.IsLoopback(x.Address));

                foreach (var addressInfo in addresses)
                {
                    sb.AppendLineInvariant($"[assembly: global::Uno.UI.RemoteControl.ServerEndpointAttribute(\"{addressInfo.Address}\", {unoRemoteControlPort})]");
                }
            }
            else
            {
                sb.AppendLineInvariant($"[assembly: global::Uno.UI.RemoteControl.ServerEndpointAttribute(\"{unoRemoteControlHost}\", {unoRemoteControlPort})]");
            }
        }
Exemple #6
0
        void CollectExtensionMethods(SourceGeneratorContext context)
        {
            logger.Info("Collecting extension methods with interface constraints!");

            foreach (var method in hyperlinqNamespace
                     .GetTypeMembers()
                     .Where(type => type.IsPublic() && type.IsStatic)
                     .SelectMany(type => type.GetMembers()
                                 .OfType <IMethodSymbol>()
                                 .Where(method =>
                                        method.IsPublic() &&
                                        method.IsExtensionMethod &&
                                        !method.ShouldIgnore(context.Compilation))))
            {
                var extensionType = method.Parameters[0].Type;
                var generic       = method.TypeParameters
                                    .FirstOrDefault(parameter =>
                                                    parameter.Name == extensionType.Name &&
                                                    parameter.ConstraintTypes.Length != 0);
                if (generic is object)
                {
                    var extendedType = generic.ConstraintTypes[0];
                    var key          = extendedType.OriginalDefinition.MetadataName;
                    if (!collectedExtensionMethods.TryGetValue(key, out var list))
                    {
                        list = new List <IMethodSymbol>();
                        collectedExtensionMethods.Add(key, list);
                    }
                    list.Add(method);
                }
            }
        }
        public void Execute(SourceGeneratorContext context)
        {
            context.AddCompiledOnMetadataAttribute();

            var compilation = context.Compilation;
            var types       = CompilationHelper.GetAllTypes(context.Compilation.Assembly);

            using (var stringWriter = new StringWriter())
                using (var indentedTextWriter = new IndentedTextWriter(stringWriter, "    "))
                {
                    var defaultToStringGenerator = new DefaultToStringGenerator(context);
                    foreach (var type in types)
                    {
                        if (DefaultToStringGenerator.ShouldUseGenerator(type))
                        {
                            defaultToStringGenerator.WriteType(type, indentedTextWriter);
                        }
                    }

                    indentedTextWriter.Flush();
                    stringWriter.Flush();

                    var sourceText = SourceText.From(stringWriter.ToString(), Encoding.UTF8);
                    var hintName   = $"AutoToString_{compilation.Assembly.Name}.g.cs";

                    context.AddSource(hintName, sourceText);
                }
        }
        /// <inheritdoc />
        public override void Execute(SourceGeneratorContext context)
        {
            var output = new StringBuilder();

            output.AppendLine("// This is the list of all external references used to compile this project:");

            var lines = context
                        .Compilation
                        .References
                        .OrderBy(r => r.Display, StringComparer.InvariantCultureIgnoreCase)
                        .Select((r, i) => $"// #{i}: {r.Display}");

            output.AppendLine(string.Join(Environment.NewLine, lines));

            context.AddCompilationUnit(nameof(CompilationReferencesListingGenerator), output.ToString());

            var projectReferences = context
                                    .GetProjectInstance()
                                    .Items
                                    .Where(i => i.ItemType.Equals("PackageReference", StringComparison.OrdinalIgnoreCase))
                                    .ToArray();

            var projectDependencies = context
                                      .GetProjectInstance()
                                      .Items
                                      .Where(i => i.ItemType.Equals("PackageDependencies", StringComparison.OrdinalIgnoreCase))
                                      .ToArray();

            projectReferences.ToString();
        }
        public override void Execute(SourceGeneratorContext context)
        {
#if DEBUG
            Debugger.Launch();
#endif

            _logger = context.GetLogger();

            DirectoryInfo projDir = new DirectoryInfo(Path.GetDirectoryName(context.Project.FilePath));

            string solutionFullName = null;

            while (projDir.Parent != null)
            {
                string filePath = Path.Combine(projDir.FullName, "BitConfigV1.json");

                if (File.Exists(filePath))
                {
                    solutionFullName = Directory.EnumerateFiles(projDir.FullName, "*.sln").FirstOrDefault();
                    break;
                }

                projDir = projDir.Parent;
            }

            CallGenerateCodes(context.Project.Solution.Workspace, solutionFullName);
        }
Exemple #10
0
 public void Execute(SourceGeneratorContext context)
 {
     foreach (var file in context.AdditionalFiles)
     {
         context.AddSource(GetGeneratedFileName(file.Path), SourceText.From("", Encoding.UTF8));
     }
 }
        public void Execute(SourceGeneratorContext context)
        {
            // retreive the populated receiver
            if (!(context.SyntaxReceiver is SyntaxReceiver receiver))
            {
                return;
            }
            try
            {
                // 简单测试aop 生成
                Action <StringBuilder, IMethodSymbol> beforeCall = (sb, method) => { };
                Action <StringBuilder, IMethodSymbol> afterCall  = (sb, method) => { sb.Append("r++;"); };

                // 获取生成结果
                var code = receiver.SyntaxNodes
                           .Select(i => context.Compilation.GetSemanticModel(i.SyntaxTree).GetDeclaredSymbol(i) as INamedTypeSymbol)
                           .Where(i => i != null && !i.IsStatic)
                           .Select(i => ProxyCodeGenerator.GenerateProxyCode(i, beforeCall, afterCall))
                           .First();

                context.AddSource("code.cs", SourceText.From(code, Encoding.UTF8));
            }
            catch (Exception ex)
            {
                // 失败汇报
                context.ReportDiagnostic(Diagnostic.Create(new DiagnosticDescriptor("n001", ex.ToString(), ex.ToString(), "AOP.Generate", DiagnosticSeverity.Warning, true), Location.Create("code.cs", TextSpan.FromBounds(0, 0), new LinePositionSpan())));
            }
        }
        public override void Execute(SourceGeneratorContext context)
        {
#if DEBUG
            Debugger.Launch();
#endif

            _logger = context.GetLogger();

            DirectoryInfo projDir = new DirectoryInfo(Path.GetDirectoryName(context.Project.FilePath) ?? throw new InvalidOperationException("Context's project's file path is null"));

            string solutionFullName = null;

            while (projDir.Parent != null)
            {
                string filePath = Path.Combine(projDir.FullName, "BitConfigV1.json");

                if (File.Exists(filePath))
                {
                    solutionFullName = Directory.EnumerateFiles(projDir.FullName, "*.sln").FirstOrDefault();
                    break;
                }

                projDir = projDir.Parent;
            }

            CallGenerateCodes((MSBuildWorkspace)context.Project.Solution.Workspace, context.Project, solutionFullName).GetAwaiter().GetResult();
        }
        public override void Execute(SourceGeneratorContext context)
        {
            var compilation = context.Compilation;
            var diags       = compilation.GetDiagnostics();

            Debugger.Launch();
        }
Exemple #14
0
        public void Execute(SourceGeneratorContext context)
        {
            StringBuilder sourceBuilder = new StringBuilder(@"
using System;

namespace SyntaxTreesGenerated
{
    public static class SyntaxTrees
    {
        public static void PrintSyntaxTrees() 
        {
            Console.WriteLine(""The following syntax trees existed in the compilation that created this program:"");
");

            foreach (SyntaxTree tree in context.Compilation.SyntaxTrees)
            {
                sourceBuilder.AppendLine($@"Console.WriteLine(@""{tree.FilePath}"");");
            }

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

            context.AddSource("syntaxTreesGenerator", SourceText.From(sourceBuilder.ToString(), Encoding.UTF8));
        }
Exemple #15
0
        public void Execute(SourceGeneratorContext context)
        {
            Compilation?compilation = context.Compilation;

            compilation = GenerateHelperClasses(context);

            INamedTypeSymbol?serviceLocatorClass = compilation.GetTypeByMetadataName("DI.ServiceLocator") !;
            INamedTypeSymbol?transientAttribute  = compilation.GetTypeByMetadataName("DI.TransientAttribute") !;

            INamedTypeSymbol?iEnumerableOfT = compilation.GetTypeByMetadataName("System.Collections.Generic.IEnumerable`1") !.ConstructUnboundGenericType();
            INamedTypeSymbol?listOfT        = compilation.GetTypeByMetadataName("System.Collections.Generic.List`1") !;

            var knownTypes = new KnownTypes(iEnumerableOfT, listOfT, transientAttribute);

            var services = new List <Service>();

            foreach (SyntaxTree?tree in compilation.SyntaxTrees)
            {
                SemanticModel?semanticModel = compilation.GetSemanticModel(tree);
                IEnumerable <INamedTypeSymbol>?typesToCreate = from i in tree.GetRoot().DescendantNodesAndSelf().OfType <InvocationExpressionSyntax>()
                                                               let symbol = semanticModel.GetSymbolInfo(i).Symbol as IMethodSymbol
                                                                            where symbol != null
                                                                            where SymbolEqualityComparer.Default.Equals(symbol.ContainingType, serviceLocatorClass)
                                                                            select symbol.ReturnType as INamedTypeSymbol;

                foreach (INamedTypeSymbol?typeToCreate in typesToCreate)
                {
                    CollectServices(context, typeToCreate, compilation, services, knownTypes);
                }
            }

            GenerateServiceLocator(context, services);
        }
Exemple #16
0
        public override void Execute(SourceGeneratorContext context)
        {
            if (
                context.GetProjectInstance().GetPropertyValue("Configuration") == "Debug" &&
                IsRemoteControlClientInstalled(context) &&
                IsApplication(context.GetProjectInstance()))
            {
                var sb = new IndentedStringBuilder();

                sb.AppendLineInvariant("// <auto-generated>");
                sb.AppendLineInvariant("// ***************************************************************************************");
                sb.AppendLineInvariant("// This file has been generated by the package Uno.UI.RemoteControl - for Xaml Hot Reload.");
                sb.AppendLineInvariant("// Documentation: https://platform.uno/docs/articles/features/working-with-xaml-hot-reload.html");
                sb.AppendLineInvariant("// ***************************************************************************************");
                sb.AppendLineInvariant("// </auto-generated>");
                sb.AppendLineInvariant("// <autogenerated />");
                sb.AppendLineInvariant("#pragma warning disable // Ignore code analysis warnings");

                sb.AppendLineInvariant("");

                BuildEndPointAttribute(context, sb);
                BuildSearchPaths(context, sb);

                context.AddCompilationUnit("RemoteControl", sb.ToString());
            }
        }
 public void Execute(SourceGeneratorContext context)
 {
     foreach (var file in context.AdditionalFiles)
     {
         AddSourceForAdditionalFile(context.AdditionalSources, file);
     }
 }
        /// <inheritdoc />
        public override void Execute(SourceGeneratorContext context)
        {
            _context          = context;
            _objectSymbol     = context.Compilation.GetTypeByMetadataName("System.Object");
            _valueTypeSymbol  = context.Compilation.GetTypeByMetadataName("System.ValueType");
            _boolSymbol       = context.Compilation.GetTypeByMetadataName("System.Bool");
            _intSymbol        = context.Compilation.GetTypeByMetadataName("System.Int32");
            _stringSymbol     = context.Compilation.GetTypeByMetadataName("System.String");
            _arraySymbol      = context.Compilation.GetTypeByMetadataName("System.Array");
            _collectionSymbol = context.Compilation.GetTypeByMetadataName("System.Collections.ICollection");
            _readonlyCollectionGenericSymbol = context.Compilation.GetTypeByMetadataName("System.Collections.Generic.IReadOnlyCollection`1");
            _collectionGenericSymbol         = context.Compilation.GetTypeByMetadataName("System.Collections.Generic.ICollection`1");
            _iEquatableSymbol                       = context.Compilation.GetTypeByMetadataName("System.IEquatable`1");
            _iKeyEquatableSymbol                    = context.Compilation.GetTypeByMetadataName("Uno.Equality.IKeyEquatable");
            _iKeyEquatableGenericSymbol             = context.Compilation.GetTypeByMetadataName("Uno.Equality.IKeyEquatable`1");
            _generatedEqualityAttributeSymbol       = context.Compilation.GetTypeByMetadataName("Uno.GeneratedEqualityAttribute");
            _ignoreForEqualityAttributeSymbol       = context.Compilation.GetTypeByMetadataName("Uno.EqualityIgnoreAttribute");
            _equalityHashAttributeSymbol            = context.Compilation.GetTypeByMetadataName("Uno.EqualityHashAttribute");
            _equalityKeyAttributeSymbol             = context.Compilation.GetTypeByMetadataName("Uno.EqualityKeyAttribute");
            _equalityComparerOptionsAttributeSymbol = context.Compilation.GetTypeByMetadataName("Uno.Equality.EqualityComparerOptionsAttribute");
            _dataAnnonationsKeyAttributeSymbol      = context.Compilation.GetTypeByMetadataName("System.ComponentModel.DataAnnotations.KeyAttribute");

            _generateKeyEqualityCode = _iKeyEquatableSymbol != null;

            foreach (var type in EnumerateEqualityTypesToGenerate())
            {
                GenerateEquality(type);
            }
        }
        public void Execute(SourceGeneratorContext context)
        {
            try
            {
                var registrationSymbols = RegistrationSymbols.FromCompilation(context.Compilation);
                var containerClasses    = context.LocateContainerSymbols(registrationSymbols.ContainerSymbol);
                var generator           = new ContainerClassContentGenerator(context, registrationSymbols);

                foreach (var containerClass in containerClasses)
                {
                    var hintName = $"Generated.{containerClass.FullyQualifiedName}";
                    var content  = generator.GenerateClassString(containerClass);

                    WriteOutDebugFile(hintName, content, context);
                    context.AddSource(hintName, SourceText.From(content, Encoding.UTF8));
                }
            }
            catch (DiagnosticException ex)
            {
                context.ReportDiagnostic(ex.Diagnostic);
            }
            catch (Exception ex)
            {
                var descriptor = new DiagnosticDescriptor(DiagnosticConstants.UnknownExceptionId, "Unexpected error", $"Unknown error during generation: {ex.GetType()} {ex.Message}", DiagnosticConstants.Category, DiagnosticSeverity.Error, true);
                context.ReportDiagnostic(Diagnostic.Create(descriptor, Location.None));
            }
        }
Exemple #20
0
        public void Execute(SourceGeneratorContext context)
        {
            //_ = Debugger.Launch(); // uncomment to debug this source generator

            // create a folder to serialize the generated source for debugging
            var generatedPath = default(string?);

            if (serializeSource)
            {
                // place it inside obj so that source is not added to the project
                generatedPath = Path.Combine("Generated", nameof(OverloadsGenerator));
                // delete source generated by previous build
                if (Directory.Exists(generatedPath))
                {
                    Directory.Delete(generatedPath, true);
                }
                _ = Directory.CreateDirectory(generatedPath);
            }

            try
            {
                var collectedExtensionMethods = CollectExtensionMethods(context);
                GenerateSource(context, collectedExtensionMethods, generatedPath);
            }
            catch (Exception ex)
            {
                context.ReportDiagnostic(Diagnostic.Create(UnhandledExceptionError, Location.None, ex.Message));
            }
        }
Exemple #21
0
        public void Execute(SourceGeneratorContext context)
        {
            var resources = context.GetMSBuildItems("PRIResource");

            if (resources.Any())
            {
                var sb = new IndentedStringBuilder();

                using (sb.BlockInvariant($"namespace {context.GetMSBuildProperty("RootNamespace")}"))
                {
                    using (sb.BlockInvariant($"internal enum PriResources"))
                    {
                        foreach (var item in resources)
                        {
                            //load document
                            XmlDocument doc = new XmlDocument();
                            doc.Load(item);

                            //extract all localization keys from Win10 resource file
                            var nodes = doc.SelectNodes("//data")
                                        .Cast <XmlElement>()
                                        .Select(node => node.GetAttribute("name"))
                                        .ToArray();

                            foreach (var node in nodes)
                            {
                                sb.AppendLineInvariant($"{node},");
                            }
                        }
                    }
                }

                context.AddSource("PriResources", SourceText.From(sb.ToString(), Encoding.UTF8));
            }
        }
Exemple #22
0
        public void Execute(SourceGeneratorContext context)
        {
            string attributeSource = @"
    [System.AttributeUsage(System.AttributeTargets.Assembly, AllowMultiple=true)]
    public class MustacheAttribute: System.Attribute
    {
        public string Name { get; }
        public string Template { get; }
        public string Hash { get; }
        public MustacheAttribute(string name, string template, string hash)
            => (Name, Template, Hash) = (name, template, hash);
    }
";

            context.AddSource("Mustache_MainAttributes__", SourceText.From(attributeSource, Encoding.UTF8));

            Compilation compilation = context.Compilation;

            IEnumerable <(string, string, string)> options      = GetMustacheOptions(compilation);
            IEnumerable <(string, string)>         namesSources = SourceFilesFromMustachePaths(options);

            foreach ((string name, string source) in namesSources)
            {
                context.AddSource($"Mustache{name}", SourceText.From(source, Encoding.UTF8));
            }
        }
Exemple #23
0
        protected override void Generate(SourceGeneratorContext context, INamedTypeSymbol symbol)
        {
            var equalsCandidates = symbol.GetMembers(nameof(Equals))
                                   .Where(member => member is IMethodSymbol method &&
                                          SymbolEqualityComparer.Default.Equals(method.ReturnType, context.Compilation.GetSpecialType(SpecialType.System_Boolean)) &&
                                          method.Parameters.Length == 1 &&
                                          SymbolEqualityComparer.Default.Equals(method.Parameters[0], symbol));

            var ghcCandidates = symbol.GetMembers(nameof(GetHashCode))
                                .Where(member => member is IMethodSymbol method &&
                                       SymbolEqualityComparer.Default.Equals(method.ReturnType, context.Compilation.GetSpecialType(SpecialType.System_Int32)) &&
                                       method.Parameters.Length == 0);

            var builder = new StringBuilder();

            if (equalsCandidates.Count() == 0)
            {
                var compString = GenerateComparisonOfAllFields(context, symbol);
                builder.AppendLine(string.Format(symbol.IsValueType ? ValueTypeStandardEqualsTemplate : RefTypeStandardEqualsTemplate, symbol.Name, compString));
            }

            if (ghcCandidates.Count() == 0)
            {
                var ghcString = GenerateHashCodeOfAllFields(context, symbol);
                builder.AppendLine(string.Format(GetHashCodeTemplate, ghcString));
            }

            builder.AppendLine(string.Format(symbol.IsValueType ? ValueTypeEqualsTemplate : RefTypeEqualsTemplate, symbol.Name));

            builder.AppendLine(string.Format(EquatableTemplate, symbol.Name));

            var source = string.Format(TypeTemplate, symbol.ContainingNamespace, symbol.IsValueType ? "struct" : "class", symbol.Name, builder.ToString());

            context.AddSource($"{symbol.Name}.EqualityMembers.cs", SourceText.From(source, Encoding.UTF8));
        }
        private void GenerateCategories(
            SourceGeneratorContext context,
            IEnumerable <INamedTypeSymbol> symbols,
            int bucketCount)
        {
            var sha1 = SHA1.Create();

            foreach (var type in symbols)
            {
                var builder = new IndentedStringBuilder();

                builder.AppendLineInvariant("using System;");

                using (builder.BlockInvariant($"namespace {type.ContainingNamespace}"))
                {
                    // Compute a stable hash of the full metadata name
                    var buffer     = Encoding.UTF8.GetBytes(type.GetFullMetadataName());
                    var hash       = sha1.ComputeHash(buffer);
                    var hashPart64 = BitConverter.ToUInt64(hash, 0);

                    var testCategoryBucket = (hashPart64 % (uint)bucketCount) + 1;

                    builder.AppendLineInvariant($"[global::NUnit.Framework.Category(\"testBucket:{testCategoryBucket}\")]");
                    using (builder.BlockInvariant($"partial class {type.Name}"))
                    {
                    }
                }

                context.AddCompilationUnit(Sanitize(type.GetFullMetadataName()), builder.ToString());
            }
        }
Exemple #25
0
        public void Execute(SourceGeneratorContext context)
        {
            // begin creating the source we'll inject into the users compilation
            StringBuilder sourceBuilder = new StringBuilder(@"
using System;
namespace HelloWorldGenerated
{
    public static class HelloWorld
    {
        public static void SayHello() 
        {
            Console.WriteLine(""Hello from generated code!"");
            Console.WriteLine(""The following syntax trees existed in the compilation that created this program:"");
");

            // using the context, get a list of syntax trees in the users compilation
            IEnumerable <SyntaxTree> syntaxTrees = context.Compilation.SyntaxTrees;

            // add the filepath of each tree to the class we're building
            foreach (SyntaxTree tree in syntaxTrees)
            {
                sourceBuilder.AppendLine($@"Console.WriteLine(@"" - {tree.FilePath}"");");
            }

            // finish creating the source to inject
            sourceBuilder.Append(@"
        }
    }
}");

            // inject the created source into the users compilation
            context.AddSource("helloWorldGenerated", SourceText.From(sourceBuilder.ToString(), Encoding.UTF8));
        }
Exemple #26
0
        public void Execute(GeneratorExecutionContext context)
        {
            // check that the users compilation references the expected library
            if (!context.Compilation.ReferencedAssemblyNames.Any(ai => ai.Name.Equals("SaltLakeCity.Framework.Alpakabroker", StringComparison.OrdinalIgnoreCase)))
            {
                //context.ReportDiagnostic();
            }

            using var sourceGenContext = SourceGeneratorContext <Generator> .Create(context);

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

            foreach (var @event in actorSyntaxReciver.Events)
            {
                var alpakaEventModel        = AlpakaEventModelFactory.From(@event, sourceGenContext.GeneratorExecutionContext.Compilation);
                var alpakaEventEmitter      = TemplateGenerator.GenerateAlpakaEventEmitter(alpakaEventModel);
                var alpakaEventReceiverBase =
                    TemplateGenerator.GenerateAlpakaEventEventReceiverBase(alpakaEventModel);


                context.AddSource(alpakaEventEmitter.FileName, alpakaEventEmitter.SourceCode);
                context.AddSource(alpakaEventReceiverBase.FileName, alpakaEventReceiverBase.SourceCode);
            }
        }
Exemple #27
0
        public void WritePrimitivesSerializerClass(SourceGeneratorContext context)
        {
            // Write out some functions that are  missing from the BinaryPrimitives class.
            var sourceBuilder = new StringBuilder();

            sourceBuilder.Append(@"
namespace BitSerialization.Generated
{
    internal static class BitPrimitivesSerializer
    {
        public static bool TryWriteByte(global::System.Span<byte> destination, byte value)
        {
            if (destination.Length < 1)
            {
                return false;
            }
            destination[0] = value;
            return true;
        }

        public static bool TryWriteSByte(global::System.Span<byte> destination, sbyte value)
        {
            if (destination.Length < 1)
            {
                return false;
            }
            destination[0] = (byte)value;
            return true;
        }

        public static bool TryReadByte(global::System.ReadOnlySpan<byte> source, out byte value)
        {
            if (source.Length < 1)
            {
                value = default;
                return false;
            }
            value = source[0];
            return true;
        }

        public static bool TryReadSByte(global::System.ReadOnlySpan<byte> source, out sbyte value)
        {
            if (source.Length < 1)
            {
                value = default;
                return false;
            }
            value = (sbyte)source[0];
            return true;
        }
    }
}
");

            string sourceCode = sourceBuilder.ToString();

            context.AddSource("BitPrimitivesSerializer.cs", SourceText.From(sourceCode, Encoding.UTF8));
        }
Exemple #28
0
        public void Execute(SourceGeneratorContext context)
        {
            Compilation?compilation = context.Compilation;

            string sourceBuilder = Generate(compilation);

            context.AddSource("ServiceLocator.cs", SourceText.From(sourceBuilder, Encoding.UTF8));
        }
 public void Execute(SourceGeneratorContext context)
 {
     _onExecute(context);
     if (!string.IsNullOrWhiteSpace(_sourceOpt))
     {
         context.AdditionalSources.Add("source.cs", SourceText.From(_sourceOpt, Encoding.UTF8));
     }
 }
 public override void Execute(SourceGeneratorContext context)
 {
     if (PlatformHelper.IsValidPlatform(context))
     {
         var visitor = new SerializationMethodsGenerator(context);
         visitor.Visit(context.Compilation.SourceModule);
     }
 }
Exemple #31
0
 public abstract void Execute(SourceGeneratorContext context);
 public override void Execute(SourceGeneratorContext context)
 {
     _execute(context);
 }