예제 #1
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})]");
            }
        }
        /// <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();
        }
예제 #3
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());
            }
        }
예제 #4
0
        public override void Execute(SourceGeneratorContext context)
        {
            if (
                context.GetProjectInstance().GetPropertyValue("Configuration") == "Debug" &&
                IsRemoteControlClientInstalled(context) &&
                IsApplication(context.GetProjectInstance()))
            {
                var sb = new IndentedStringBuilder();

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

                context.AddCompilationUnit("RemoteControl", sb.ToString());
            }
        }
예제 #5
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($")]");
        }
예제 #6
0
        public override void Execute(SourceGeneratorContext context)
        {
            var project = context.GetProjectInstance();

            _bindingsPaths = project.GetPropertyValue("TSBindingsPath")?.ToString();

            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 sym != null
                                        from module in sym.Modules
                                        select module;

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

                GenerateTSMarshallingLayouts(modules);
            }
        }
예제 #7
0
        public override void Execute(SourceGeneratorContext context)
        {
            Debugger.Launch();

            var project = context.GetProjectInstance();

            context.AddCompilationUnit("Test", "namespace MyGeneratedCode { class TestGeneration { } }");
        }
예제 #8
0
        public static bool IsValidPlatform(SourceGeneratorContext context)
        {
            string evaluatedValue = context
                                    .GetProjectInstance()
                                    .GetProperty("TargetPlatformIdentifier")
                                    ?.EvaluatedValue ?? "";

            return(!evaluatedValue.Equals("UAP", StringComparison.OrdinalIgnoreCase));
        }
        public override void Execute(SourceGeneratorContext context)
        {
            var project = context.GetProjectInstance();

            var testClasses = context.Compilation.SourceModule.GlobalNamespace.GetNamedTypes().Where(
                t => t.AllInterfaces.Any(i => i.Name == "IContainSimpleTests"));

            foreach (var item in testClasses)
            {
                var members = item.GetMembers()
                              .OfType <IMethodSymbol>()
                              .Where(m => !m.IsAbstract &&
                                     !m.ReturnsVoid &&
                                     !m.Parameters.Any() &&
                                     m.MethodKind != MethodKind.PropertyGet &&
                                     (m.DeclaredAccessibility == Accessibility.Public ||
                                      m.DeclaredAccessibility == Accessibility.Internal));

                var memberText = new StringBuilder();

                foreach (var member in members)
                {
                    var returnType = member.ReturnType;

                    if (returnType.MetadataName.Equals("Boolean"))
                    {
                        memberText.Append(GetTest(item.MetadataName, member.Name, member.IsStatic));
                    }
                    else if (returnType.MetadataName.Equals("Task`1") && returnType is INamedTypeSymbol nts)
                    {
                        if (nts.Arity.Equals(1) && nts.TypeArguments.First().MetadataName.Equals("Boolean"))
                        {
                            memberText.Append(GetAsyncTest(item.MetadataName, member.Name, member.IsStatic));
                        }
                    }
                    else
                    {
                        // output nothing as not an inferred test
                    }
                }

                var memberOutput = memberText.ToString();

                if (!string.IsNullOrWhiteSpace(memberOutput))
                {
                    var classOpening = GetClassOpening(item.ContainingNamespace, item.MetadataName);
                    context.AddCompilationUnit(
                        $"{item.ContainingNamespace}.{item.MetadataName}",
                        $"{classOpening}{memberOutput}{GetClassClosing()}");
                }
            }
        }
        public override void Execute(SourceGeneratorContext context)
        {
            try
            {
                if (PlatformHelper.IsValidPlatform(context))
                {
                    var project = context.GetProjectInstance();

                    if (IsApplication(project))
                    {
                        _defaultNamespace = project.GetPropertyValue("RootNamespace");

                        _bindableAttributeSymbol  = FindBindableAttributes(context);
                        _dependencyPropertySymbol = context.Compilation.GetTypeByMetadataName(XamlConstants.Types.DependencyProperty);

                        _objectSymbol      = context.Compilation.GetTypeByMetadataName("System.Object");
                        _javaObjectSymbol  = context.Compilation.GetTypeByMetadataName("Java.Lang.Object");
                        _nsObjectSymbol    = context.Compilation.GetTypeByMetadataName("Foundation.NSObject");
                        _stringSymbol      = context.Compilation.GetTypeByMetadataName("System.String");
                        _nonBindableSymbol = context.Compilation.GetTypeByMetadataName("Windows.UI.Xaml.Data.NonBindableAttribute");

                        _currentModule = context.Compilation.SourceModule;

                        AnalyzerSuppressions = new string[0];

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

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

                        context.AddCompilationUnit("BindableMetadata", GenerateTypeProviders(modules));
                    }
                }
            }
            catch (Exception e)
            {
                var message = e.Message + e.StackTrace;

                if (e is AggregateException)
                {
                    message = (e as AggregateException).InnerExceptions.Select(ex => ex.Message + e.StackTrace).JoinBy("\r\n");
                }

                this.Log().Error("Failed to generate type providers.", new Exception("Failed to generate type providers." + message, e));
            }
        }
        public override void Execute(SourceGeneratorContext context)
        {
            var project = context.GetProjectInstance();

            context.AddCompilationUnit(
                "Test",
                $@"
namespace Test {{
	class MyGeneratedType 
	{{
		// Project: {project?.FullPath}
	}}
}}"
                );
        }
        public override void Execute(SourceGeneratorContext context)
        {
            _project         = context.Project;
            _projectInstance = context.GetProjectInstance();
            _compilation     = context.Compilation;

            // Debugger.Launch();

            GenerateSerializers();

            foreach (var files in _generatedFiles)
            {
                context.AddCompilationUnit(files.Item1, files.Item2);
            }
        }
예제 #13
0
        public static bool IsValidPlatform(SourceGeneratorContext context)
        {
            var projectInstance = context.GetProjectInstance();

            var evaluatedValue = projectInstance
                                 .GetProperty("TargetPlatformIdentifier")
                                 ?.EvaluatedValue ?? "";

            var isUAP            = evaluatedValue.Equals("UAP", StringComparison.OrdinalIgnoreCase);
            var isNetCoreWPF     = !string.IsNullOrEmpty(projectInstance.GetProperty("UseWPF")?.EvaluatedValue);
            var isNetCoreDesktop = projectInstance
                                   .GetProperty("ProjectTypeGuids")
                                   ?.EvaluatedValue == "{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}";

            return(!isUAP && !isNetCoreWPF && !isNetCoreDesktop);
        }
예제 #14
0
        public override void Execute(SourceGeneratorContext context)
        {
            var project = context.GetProjectInstance();

            context.AddCompilationUnit(
                "Test2",
                $@"
namespace AdditionalPropertiesGeneratorTest {{
	public static class TestType
	{{
		// Project: {project?.FullPath}
		// reusing the compiled code form other generator
		public const int Project = {project.GetProperty("MyTestProperty").EvaluatedValue};
	}}
}}");
        }
예제 #15
0
        public override void Execute(SourceGeneratorContext context)
        {
            var project = context.GetProjectInstance();

            context.AddCompilationUnit(
                "Test2",
                $@"
namespace Test {{
	public static class MyGeneratedType2
	{{
		// Project: {project?.FullPath}
		// reusing the compiled code form other generator
		public const string Project = MyGeneratedType.Project;
	}}
}}");
        }
예제 #16
0
        public override void Execute(SourceGeneratorContext context)
        {
            var gen = new XamlCodeGeneration(
                context.Compilation,
                context.GetProjectInstance(),
                context.Project
                );

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

                foreach (var tree in genereratedTrees)
                {
                    context.AddCompilationUnit(tree.Key, tree.Value);
                }
            }
        }
예제 #17
0
        public override void Execute(SourceGeneratorContext context)
        {
            var project = context.GetProjectInstance();

            context.GetLogger().Debug($"{nameof(MyCustomSourceGenerator)}: This is a DEBUG logging");
            context.GetLogger().Info($"{nameof(MyCustomSourceGenerator)}: This is an INFO logging");

#if DEBUG // Only in DEBUG to prevent breaking the CI build.
            context.GetLogger().Warn($"{nameof(MyCustomSourceGenerator)}: This is a WARN logging");
            context.GetLogger().Error($"{nameof(MyCustomSourceGenerator)}: This is an ERROR logging");
#endif

            // This test ensures that dependent libraries are included in the compilation
            // generated from the AdHoc workspace.
            var dependentString = BuildVariableFromType(context, DependentTypeName, "_dependent");

            // This test ensures that linked files included in the project are included
            // in the Compilation instance used by the generators.
            var linkedString = BuildVariableFromType(context, LinkedTypeName, "_linked");

            // This test validates that some duplicate files do not interfere wi
            var objectString = BuildVariableFromType(context, SystemObject, "_object");

            var stringTypeString = BuildVariableFromType(context, "System.String", "_aString");

            context.AddCompilationUnit(
                "Test",
                $@"
#pragma warning disable 169
namespace Test {{
	public static class MyGeneratedType 
	{{
		// Project: {project?.FullPath}
		public const string Project = @""{ project?.FullPath}"";
		{dependentString}
		{linkedString}
		{objectString}
		{stringTypeString}
	}}
}}"
                );
        }
        public override void Execute(SourceGeneratorContext context)
        {
            var project = context.GetProjectInstance();

            context.GetLogger().Debug($"{nameof(MyCustomSourceGenerator)}: This is a DEBUG logging");
            context.GetLogger().Info($"{nameof(MyCustomSourceGenerator)}: This is an INFO logging");

#if DEBUG // Only in DEBUG to prevent breaking the CI build.
            context.GetLogger().Warn($"{nameof(MyCustomSourceGenerator)}: This is a WARN logging");
            context.GetLogger().Error($"{nameof(MyCustomSourceGenerator)}: This is an ERROR logging");
#endif

            context.AddCompilationUnit(
                "Test",
                $@"
namespace Test {{
	public static class MyGeneratedType 
	{{
		// Project: {project?.FullPath}
		public const string Project = @""{ project?.FullPath}"";
	}}
}}"
                );
        }
        public override void Execute(SourceGeneratorContext context)
        {
            // Debugger.Launch();

            var project = context.GetProjectInstance();

            _objectSymbol     = context.Compilation.GetTypeByMetadataName("System.Object");
            _iListSymbol      = context.Compilation.GetTypeByMetadataName("System.Collections.Generic.IList`1");
            _uiElementSymbol  = context.Compilation.GetTypeByMetadataName("Windows.UI.Xaml.UIElement");
            _dependencyObject = context.Compilation.GetTypeByMetadataName("Windows.UI.Xaml.DependencyObject");

            QueueType(context, "Windows.UI.Xaml.Controls.TextBlock");
            QueueType(context, "Windows.UI.Xaml.Controls.Panel");
            QueueType(context, "Windows.UI.Xaml.Controls.StackPanel");
            QueueType(context, "Windows.UI.Xaml.Controls.Button");

            while (_queue.Any())
            {
                if (_queue.TryTake(out var symbol))
                {
                    BuildType(context, symbol);
                }
            }
        }