public void BeforeCompile(BeforeCompileContext context) { context.Diagnostics.Add( Diagnostic.Create( new DiagnosticDescriptor("TEST", "TEST", "Hello meta programming world!", "TEST", DiagnosticSeverity.Info, true), Location.None)); context.Compilation = context.Compilation.AddSyntaxTrees( SyntaxFactory.ParseSyntaxTree(@" namespace Test.Module { public static class Extensions { public static T Dump<T>(this T i) { if (i != null) { System.Console.WriteLine(i); } return i; } } } ")); }
public void Compiles() { var compilation = GetCSharpCompilation(); var context = new BeforeCompileContext() { Compilation = compilation, Diagnostics = new List <Diagnostic>() }; var unit = new PreprocessAnnotation(); unit.BeforeCompile(context); Assert.False(context.Diagnostics.Any()); //Console.WriteLine(context.Compilation.SyntaxTrees.First(x => x.GetText().ToString().Contains("class Startup")).GetText().ToString()); Assert.Equal(@"using Microsoft.Framework.DependencyInjection; namespace Temp { public class Startup { void Configure(IServiceCollection services) { } public static int Main() { return 0; } } }", context.Compilation.SyntaxTrees.First(x => x.GetText().ToString().Contains("class Startup")).GetText().ToString()); }
public void ConstructorWithParameters() { var compilation = CSharpCompilation.Create("nothing"); var projectContext = new ProjectContext(); var resourceDescriptorList = new List<ResourceDescriptor>(); var diagnosticList = new List<Diagnostic>(); var metadataReferenceList = new List<IMetadataReference>(); var target = new BeforeCompileContext( compilation, projectContext, () => { return resourceDescriptorList; }, () => { return diagnosticList; }, () => { return metadataReferenceList; }); Assert.Equal(compilation, target.Compilation); Assert.Equal(projectContext, target.ProjectContext); Assert.Equal(resourceDescriptorList, target.Resources); Assert.Equal(diagnosticList, target.Diagnostics); Assert.Equal(metadataReferenceList, target.MetadataReferences); }
public void BeforeCompile(BeforeCompileContext context) { foreach (var module in modules) { module.BeforeCompile(context); } }
public void BeforeCompile(BeforeCompileContext context) { // this can potentially run multiple times (for every view compiled at runtime) in RoslynRazorViewEngine; if (context.Compilation.GetTypeByMetadataName("Test.Module.Extensions") != null) { return; } context.Diagnostics.Add( Diagnostic.Create( new DiagnosticDescriptor("TEST", "TEST", "Hello meta programming world!", "TEST", DiagnosticSeverity.Info, true), Location.None)); context.Compilation = context.Compilation.AddSyntaxTrees( SyntaxFactory.ParseSyntaxTree(@" namespace Test.Module { public static class Extensions { public static T Dump<T>(this T i) { if (i != null) { System.Console.WriteLine(i); } return i; } } } ", context.Arguments.ParseOptions)); }
public RazorPreCompiler( BeforeCompileContext compileContext, IFileProvider fileProvider, IMemoryCache precompilationCache) { if (compileContext == null) { throw new ArgumentNullException(nameof(compileContext)); } if (fileProvider == null) { throw new ArgumentNullException(nameof(fileProvider)); } if (precompilationCache == null) { throw new ArgumentNullException(nameof(precompilationCache)); } CompileContext = compileContext; FileProvider = fileProvider; // There should always be a syntax tree even if there are no files (we generate one) Debug.Assert(compileContext.Compilation.SyntaxTrees.Length > 0); var defines = compileContext.Compilation.SyntaxTrees[0].Options.PreprocessorSymbolNames; CompilationSettings = new CompilationSettings { CompilationOptions = compileContext.Compilation.Options, Defines = defines, LanguageVersion = compileContext.Compilation.LanguageVersion }; PreCompilationCache = precompilationCache; TagHelperTypeResolver = new PrecompilationTagHelperTypeResolver(CompileContext.Compilation); }
public void ConstructorWithParameters() { var compilation = CSharpCompilation.Create("nothing"); var projectContext = new ProjectContext(); var resourceDescriptorList = new List <ResourceDescriptor>(); var diagnosticList = new List <Diagnostic>(); var metadataReferenceList = new List <IMetadataReference>(); var target = new BeforeCompileContext( compilation, projectContext, () => { return(resourceDescriptorList); }, () => { return(diagnosticList); }, () => { return(metadataReferenceList); }); Assert.Equal(compilation, target.Compilation); Assert.Equal(projectContext, target.ProjectContext); Assert.Equal(resourceDescriptorList, target.Resources); Assert.Equal(diagnosticList, target.Diagnostics); Assert.Equal(metadataReferenceList, target.MetadataReferences); }
public void BeforeCompile(BeforeCompileContext context) { var newCSharpCompilation = context.Compilation; // Find all the class containers we care about. var containers = newCSharpCompilation.SyntaxTrees .Select(tree => new { Model = newCSharpCompilation.GetSemanticModel(tree), SyntaxTree = tree, Root = tree.GetRoot() }); // Build the registration statements out of the containers. var addAssemblyNodes = GetStatements(context, containers.SelectMany(ctx => GetClassesWithImplementationAttribute(ctx.SyntaxTree, ctx.Model)).ToArray()).ToArray(); var addAssemblyMethodCalls = containers.SelectMany(ctx => GetAddAssemblyMethodCall(ctx.SyntaxTree, ctx.Model)); newCSharpCompilation = ProcessAddAssemblyMethodCalls(newCSharpCompilation, addAssemblyNodes, addAssemblyMethodCalls); containers = newCSharpCompilation.SyntaxTrees .Select(tree => new { Model = newCSharpCompilation.GetSemanticModel(tree), SyntaxTree = tree, Root = tree.GetRoot() }); context.Compilation = newCSharpCompilation; }
public void PropertyCompilationIsSettable() { var compilation = CSharpCompilation.Create("nothing"); var target = new BeforeCompileContext(); target.Compilation = compilation; Assert.Equal(compilation, target.Compilation); }
public BeforeCompileContextWrapper(BeforeCompileContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } this.context = context; }
public void DefaultConstructorSetAllPropertiesNull() { var target = new BeforeCompileContext(); // nothing is set Assert.Null(target.Compilation); Assert.Null(target.Diagnostics); Assert.Null(target.MetadataReferences); Assert.Null(target.ProjectContext); Assert.Null(target.Resources); }
public void BeforeCompile(BeforeCompileContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (precompChain != null) { precompChain.Process(new BeforeCompileContextWrapper(context)); } }
public void BeforeCompile(BeforeCompileContext context) { var options = context.Compilation.Options; var builder = options.SpecificDiagnosticOptions.ToBuilder(); // CS0649 Field is never assigned to, and will always have its default value null builder["CS0649"] = ReportDiagnostic.Suppress; context.Compilation = context.Compilation .WithOptions(options.WithSpecificDiagnosticOptions(builder.ToImmutable())); }
/// <summary> /// Determines if this instance of <see cref="RazorPreCompileModule"/> should enable /// compilation of views. /// </summary> /// <param name="context">The <see cref="BeforeCompileContext"/>.</param> /// <returns><c>true</c> if views should be precompiled; otherwise <c>false</c>.</returns> /// <remarks>Returns <c>true</c> if the current application is being built in <c>release</c> /// configuration.</remarks> protected virtual bool EnablePreCompilation(BeforeCompileContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } return(string.Equals( context.ProjectContext.Configuration, ReleaseConfiguration, StringComparison.OrdinalIgnoreCase)); }
public void UnderstandsSingleton() { var compilation = GetCSharpCompilation() .AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(SourceText.From(@"using Microsoft.Framework.DependencyInjection; namespace Temp.Providers { public interface IProviderA { decimal GetValue(); } [ServiceDescriptor(typeof(IProviderA), Lifetime = ServiceLifetime.Singleton)] public class ProviderA : IProviderA { public decimal GetValue() { return 9000.99M; } } }", Encoding.UTF8), CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6))); var context = new BeforeCompileContext() { Compilation = compilation, Diagnostics = new List <Diagnostic>() }; var unit = new PreprocessAnnotation(); unit.BeforeCompile(context); Assert.False(context.Diagnostics.Any()); //Console.WriteLine(context.Compilation.SyntaxTrees.First(x => x.GetText().ToString().Contains("class Startup")).GetText().ToString()); Assert.Equal(@"using Microsoft.Framework.DependencyInjection; namespace Temp { public class Startup { void Configure(IServiceCollection services) { services.AddSingleton(typeof (Temp.Providers.IProviderA), typeof (Temp.Providers.ProviderA)); } public static int Main() { return 0; } } }", context.Compilation.SyntaxTrees.First(x => x.GetText().ToString().Contains("class Startup")).GetText().ToString()); }
public static void AddError(this BeforeCompileContext ctx, string msg) { var dd = new DiagnosticDescriptor( id: "CSDERIVE001", messageFormat: msg, title: "", category: "", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: ""); ctx.Diagnostics.Add(Diagnostic.Create(dd, Location.None)); }
public RazorPreCompiler( [NotNull] BeforeCompileContext compileContext, [NotNull] IAssemblyLoadContextAccessor loadContextAccessor, [NotNull] IFileProvider fileProvider, [NotNull] IMemoryCache precompilationCache, [NotNull] CompilationSettings compilationSettings) { CompileContext = compileContext; LoadContext = loadContextAccessor.GetLoadContext(GetType().GetTypeInfo().Assembly); FileProvider = fileProvider; CompilationSettings = compilationSettings; PreCompilationCache = precompilationCache; TagHelperTypeResolver = new PrecompilationTagHelperTypeResolver(CompileContext, LoadContext); }
public void AddAssemblyWorksWithAssemblyExpression() { var compilation = GetCSharpCompilation(); compilation.AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(SourceText.From(@" using Microsoft.Framework.DependencyInjection; namespace Temp { public class Startup { void Configure(IServiceCollection services) { services.AddAssembly(typeof(Startup).GetTypeInfo().Assembly); } public static int Main() { return 0; } } }", Encoding.UTF8), CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6))); var context = new BeforeCompileContext() { Compilation = compilation, Diagnostics = new List <Diagnostic>() }; var unit = new PreprocessAnnotation(); unit.BeforeCompile(context); Assert.False(context.Diagnostics.Any()); //Console.WriteLine(context.Compilation.SyntaxTrees.First(x => x.GetText().ToString().Contains("class Startup")).GetText().ToString()); Assert.Equal(@"using Microsoft.Framework.DependencyInjection; namespace Temp { public class Startup { void Configure(IServiceCollection services) { } public static int Main() { return 0; } } }", context.Compilation.SyntaxTrees.Last().GetText().ToString()); }
public void BeforeCompile(BeforeCompileContext context) { context.Compilation = context.Compilation.AddSyntaxTrees( SyntaxFactory.ParseSyntaxTree(@" namespace " + context.ProjectContext.Name + @" { public class Foo { public void Bar() { System.Console.WriteLine(""Hello from generated code""); } } } ") ); }
/// <inheritdoc /> /// <remarks>Pre-compiles all Razor views in the application.</remarks> public virtual void BeforeCompile(BeforeCompileContext context) { if (!EnablePreCompilation(context)) { return; } MemoryCache memoryCache; lock (_memoryCacheLookupLock) { var cacheKey = new PrecompilationCacheKey { Configuration = context.ProjectContext.Configuration, TargetFramework = context.ProjectContext.TargetFramework }; if (!_memoryCacheLookup.TryGetValue(cacheKey, out memoryCache)) { // When CompactOnMemoryPressure is true, the MemoryCache evicts items at every gen2 collection. // In DTH, gen2 happens frequently enough to make it undesirable for caching precompilation results. We'll // disable listening for memory pressure for the MemoryCache instance used by precompilation. memoryCache = new MemoryCache(new MemoryCacheOptions { CompactOnMemoryPressure = false }); _memoryCacheLookup[cacheKey] = memoryCache; } } using (var fileProvider = new PhysicalFileProvider(context.ProjectContext.ProjectDirectory)) { var viewCompiler = new RazorPreCompiler( context, fileProvider, memoryCache) { GenerateSymbols = GenerateSymbols }; viewCompiler.CompileViews(); } }
/// <inheritdoc /> /// <remarks>Pre-compiles all Razor views in the application.</remarks> public virtual void BeforeCompile(BeforeCompileContext context) { var compilerOptionsProvider = _appServices.GetRequiredService <ICompilerOptionsProvider>(); var loadContextAccessor = _appServices.GetRequiredService <IAssemblyLoadContextAccessor>(); var compilationSettings = GetCompilationSettings(compilerOptionsProvider, context.ProjectContext); var fileProvider = new PhysicalFileProvider(context.ProjectContext.ProjectDirectory); var viewCompiler = new RazorPreCompiler( context, loadContextAccessor, fileProvider, _memoryCache, compilationSettings) { GenerateSymbols = GenerateSymbols }; viewCompiler.CompileViews(); }
public void AddAssemblyIsLeftAloneForOtherTypes() { var compilation = GetCSharpCompilation() .AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(SourceText.From(@" using Microsoft.Framework.DependencyInjection; namespace Temp { public class NotStartup { } public class Startup2 { void Configure(IServiceCollection collection) { collection.AddAssembly(typeof(NotStartup)); } } }", Encoding.UTF8), CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6))); var context = new BeforeCompileContext() { Compilation = compilation, Diagnostics = new List <Diagnostic>() }; var unit = new PreprocessAnnotation(); unit.BeforeCompile(context); Assert.False(context.Diagnostics.Any()); //Console.WriteLine(context.Compilation.SyntaxTrees.Last().GetText().ToString()); Assert.Equal(@" using Microsoft.Framework.DependencyInjection; namespace Temp { public class NotStartup { } public class Startup2 { void Configure(IServiceCollection collection) { collection.AddAssembly(typeof(NotStartup)); } } }", context.Compilation.SyntaxTrees.Last().GetText().ToString()); }
public static Assembly GetAssembly(string sourceCode) { if (sourceCode == null) { throw new ArgumentNullException(nameof(sourceCode)); } var compilation = CompilationFactory.CompileClassFromText(sourceCode); var context = new BeforeCompileContext { Compilation = compilation, Diagnostics = new List <Diagnostic>() }; var module = new TractionCompileModule(); module.BeforeCompile(context); return(GetAssembly(context.Compilation)); }
public static IEnumerable <Diagnostic> GetDiagnostics(CSharpCompilation compilation) { if (compilation == null) { throw new ArgumentNullException(nameof(compilation)); } //Arrange var context = new BeforeCompileContext { Compilation = compilation, Diagnostics = new List <Diagnostic>() }; var module = new TractionCompileModule(); //Act module.BeforeCompile(context); //Return data to be used by assertions return(context.Diagnostics); }
public void OpenDiagnosticsStillFunctionEvenIfReplacementNeverHappens() { var compilation = GetCSharpCompilation() .AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(SourceText.From(@"using Microsoft.Framework.DependencyInjection; namespace Temp.Providers { public interface IProviderA<T> { decimal GetValue(); } public interface IProviderB<T> { decimal GetValue(); } [ServiceDescriptor(typeof(IProviderA<>), Lifetime = ServiceLifetime.Singleton)] public class ProviderA<T> : IProviderB<T> { public decimal GetValue() { return 9000.99M; } } }", Encoding.UTF8), CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6))); var context = new BeforeCompileContext() { Compilation = compilation, Diagnostics = new List <Diagnostic>() }; var unit = new PreprocessAnnotation(); unit.BeforeCompile(context); //Console.WriteLine(context.Compilation.SyntaxTrees.First(x => x.GetText().ToString().Contains("class Startup")).GetText().ToString()); Assert.True(context.Diagnostics.Any()); }
public void BeforeCompile(BeforeCompileContext context) { var attrTypeCtor = context.Compilation .GetTypeByMetadataName(typeof(T).FullName) .InstanceConstructors.Single(); var classes = from tree in context.Compilation.SyntaxTrees from classDecl in tree.GetRoot().DescendantNodes().OfSubtype <SyntaxNode, ClassDeclarationSyntax>() let model = context.Compilation.GetSemanticModel(tree, true) where ( from attrList in classDecl.AttributeLists from attr in attrList.Attributes let symbol = model.GetSymbolInfo(attr).Symbol where symbol.Equals(attrTypeCtor) select symbol ).Any() select new { classDecl, tree, }; var classesList = classes.ToList(); if (classesList.Count == 0) { return; } var changes = from g in classesList.GroupBy(x => x.tree) select new { oldTree = g.Key, newTree = g.Aggregate(g.Key, (accTree, ctx) => ProcessClassTree(ctx.classDecl, accTree)) }; //Debugger.Launch(); context.Compilation = changes.Aggregate(context.Compilation, (compilation, change) => compilation.ReplaceSyntaxTree(change.oldTree, change.newTree)); }
/// <summary> /// Initializes a new instance of <see cref="PrecompilationTagHelperTypeResolver"/>. /// </summary> /// <param name="compileContext">The <see cref="BeforeCompileContext"/>.</param> /// <param name="loadContext">The <see cref="IAssemblyLoadContext"/>.</param> public PrecompilationTagHelperTypeResolver([NotNull] BeforeCompileContext compileContext, [NotNull] IAssemblyLoadContext loadContext) { _compileContext = compileContext; _loadContext = loadContext; }
protected override bool EnablePreCompilation(BeforeCompileContext context) { return(true); }
public void BeforeCompile(BeforeCompileContext context) { var candidates = new List <string>(); candidates.Add(Path.Combine(context.ProjectContext.ProjectDirectory, "..", "..", "submodules")); if (context.ProjectContext.Name != "Microsoft.Framework.Runtime") { candidates.Add(Path.Combine(context.ProjectContext.ProjectDirectory, "..", "Microsoft.Framework.Runtime.Hosting")); } var submodulesDir = Path.Combine(context.ProjectContext.ProjectDirectory, "..", "..", "submodules"); var replacementDict = new Dictionary <SyntaxTree, SyntaxTree>(); var removeList = new List <SyntaxTree>(); foreach (var tree in context.Compilation.SyntaxTrees) { if (string.IsNullOrEmpty(tree.FilePath) || !candidates.Any(c => IsChildOfDirectory(dir: c, candidate: tree.FilePath))) { continue; } if (string.Equals("AssemblyInfo.cs", Path.GetFileName(tree.FilePath), StringComparison.OrdinalIgnoreCase)) { removeList.Add(tree); continue; } var root = tree.GetRoot(); var targetSyntaxKinds = new[] { SyntaxKind.ClassDeclaration, SyntaxKind.InterfaceDeclaration, SyntaxKind.StructDeclaration, SyntaxKind.EnumDeclaration }; var typeDeclarations = root.DescendantNodes() .Where(x => targetSyntaxKinds.Contains(x.Kind())) .OfType <BaseTypeDeclarationSyntax>(); var publicKeywordTokens = new List <SyntaxToken>(); foreach (var declaration in typeDeclarations) { var publicKeywordToken = declaration.Modifiers .SingleOrDefault(x => x.Kind() == SyntaxKind.PublicKeyword); if (publicKeywordToken != default(SyntaxToken)) { publicKeywordTokens.Add(publicKeywordToken); } } if (publicKeywordTokens.Any()) { root = root.ReplaceTokens(publicKeywordTokens, (_, oldToken) => SyntaxFactory.ParseToken("internal").WithTriviaFrom(oldToken)); } replacementDict.Add(tree, SyntaxFactory.SyntaxTree(root, tree.Options, tree.FilePath, tree.GetText().Encoding)); } context.Compilation = context.Compilation.RemoveSyntaxTrees(removeList); foreach (var pair in replacementDict) { context.Compilation = context.Compilation.ReplaceSyntaxTree(pair.Key, pair.Value); } }
public virtual void BeforeCompile(BeforeCompileContext context) { var syntaxTree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(GeneratedFile()); context.Compilation = context.Compilation.AddSyntaxTrees(syntaxTree); }
public void BeforeCompile(BeforeCompileContext context) { }