Exemplo n.º 1
0
    public void BeforeCompile(IBeforeCompileContext context)
    {
        // Firstly, I need to resolve the namespace of the ModuleProvider instance in this current compilation.
        string ns = GetModuleProviderNamespace(context.Compilation.SyntaxTrees);
        // Next, get all the available modules in assembly and compilation references.
        var modules = GetAvailableModules(context.Compilation).ToList();
        // Map them to a collection of statements
        var statements = modules.Select(m => F.ParseStatement("AddModule<" + module + ">();")).ToList();
        // Now, I'll create the dynamic implementation as a private class.
        var cu = F.CompilationUnit()
                 .AddMembers(
            F.NamespaceDeclaration(F.IdentifierName(ns))
            .AddMembers(
                F.ClassDeclaration("ModuleProvider")
                .WithModifiers(F.TokenList(F.Token(K.PartialKeyword)))
                .AddMembers(
                    F.MethodDeclaration(F.PredefinedType(F.Token(K.VoidKeyword)), "Setup")
                    .WithModifiers(
                        F.TokenList(
                            F.Token(K.ProtectedKeyword),
                            F.Token(K.OverrideKeyword)))
                    .WithBody(F.Block(statements))
                    )
                )
            )
                 .NormalizeWhitespace(indentation("\t"));
        var tree = T.Create(cu);

        context.Compilation = context.Compilation.AddSyntaxTrees(tree);
    }
        public void BeforeCompile(IBeforeCompileContext context)
        {
            JObject rawProjectFile = null;
            using (var fs = File.OpenRead(context.ProjectContext.ProjectFilePath))
            {
                rawProjectFile = JObject.Load(new JsonTextReader(new StreamReader(fs)));
            }

            var excludePatterns = PatternsCollectionHelper.GetPatternsCollection(
                rawProjectFile,
                context.ProjectContext.ProjectDirectory,
                context.ProjectContext.ProjectFilePath,
                "exclude",
                DefaultExcludePatterns);

            var matcher = new Matcher();
            matcher.AddInclude("**/*.resx").AddExcludePatterns(excludePatterns);

            var resXFiles = matcher.GetResultsInFullPath(context.ProjectContext.ProjectDirectory);

            foreach (var resXFile in resXFiles)
            {
                WriteResourceFile(resXFile);
            }
        }
        public void BeforeCompile(IBeforeCompileContext context)
        {
            JObject rawProjectFile = null;

            using (var fs = File.OpenRead(context.ProjectContext.ProjectFilePath))
            {
                rawProjectFile = JObject.Load(new JsonTextReader(new StreamReader(fs)));
            }

            var excludePatterns = PatternsCollectionHelper.GetPatternsCollection(
                rawProjectFile,
                context.ProjectContext.ProjectDirectory,
                context.ProjectContext.ProjectFilePath,
                "exclude",
                DefaultExcludePatterns);

            var matcher = new Matcher();

            matcher.AddInclude("**/*.resx").AddExcludePatterns(excludePatterns);

            var resXFiles = matcher.GetResultsInFullPath(context.ProjectContext.ProjectDirectory);

            foreach (var resXFile in resXFiles)
            {
                WriteResourceFile(resXFile);
            }
        }
        public void BeforeCompile(IBeforeCompileContext context)
        {
            string keyPath         = Environment.GetEnvironmentVariable("NUGET_BUILD_KEY_PATH");
            string delaySignString = Environment.GetEnvironmentVariable("NUGET_BUILD_DELAY_SIGN");

            if (!string.IsNullOrEmpty(keyPath))
            {
                FileInfo keyFile = new FileInfo(keyPath);

                if (keyFile.Exists)
                {
                    bool delaySign = delaySignString != null && StringComparer.OrdinalIgnoreCase.Equals("true", delaySignString);

                    // Console.WriteLine("Signing assembly with: {0} Delay sign: {1}", keyFile.FullName, delaySign ? "true" : "false");

                    var parms = new CspParameters();
                    parms.KeyNumber = 2;

                    var    provider = new RSACryptoServiceProvider(parms);
                    byte[] array    = provider.ExportCspBlob(!provider.PublicOnly);

                    var strongNameProvider = new DesktopStrongNameProvider();


                    var options = context.Compilation.Options.WithStrongNameProvider(strongNameProvider)
                                  .WithCryptoKeyFile(keyFile.FullName)
                                  .WithDelaySign(delaySign);

                    // Enfore viral strong naming
                    var specificDiagnosticOptions = new Dictionary <string, ReportDiagnostic>(options.SpecificDiagnosticOptions);
                    specificDiagnosticOptions["CS8002"] = ReportDiagnostic.Error;
                    options = options.WithSpecificDiagnosticOptions(specificDiagnosticOptions);

                    context.Compilation = context.Compilation.WithOptions(options);
                }
                else
                {
                    // The key was not found. Throw a compile error.
                    var descriptor = new DiagnosticDescriptor(
                        id: "SN1001",
                        title: "Missing key file",
                        messageFormat: "Key file '{0}' could not be found",
                        category: "CA1001: \"StrongNaming\"",
                        defaultSeverity: DiagnosticSeverity.Error,
                        isEnabledByDefault: true);

                    // TODO: what should this reference for the location?
                    var textSpan = new TextSpan();
                    var position = new LinePosition(0, 0);
                    var span     = new LinePositionSpan(position, position);

                    var location = Location.Create(context.ProjectContext.ProjectFilePath, textSpan, span);

                    var diagnsotic = Diagnostic.Create(descriptor, location, keyPath);

                    context.Diagnostics.Add(diagnsotic);
                }
            }
        }
        public void BeforeCompile(IBeforeCompileContext context)
        {
            string keyPath = Environment.GetEnvironmentVariable("NUGET_BUILD_KEY_PATH");
            string delaySignString = Environment.GetEnvironmentVariable("NUGET_BUILD_DELAY_SIGN");

            if (!string.IsNullOrEmpty(keyPath))
            {
                FileInfo keyFile = new FileInfo(keyPath);

                if (keyFile.Exists)
                {
                    bool delaySign = delaySignString != null && StringComparer.OrdinalIgnoreCase.Equals("true", delaySignString);

                    // Console.WriteLine("Signing assembly with: {0} Delay sign: {1}", keyFile.FullName, delaySign ? "true" : "false");

                    var parms = new CspParameters();
                    parms.KeyNumber = 2;

                    var provider = new RSACryptoServiceProvider(parms);
                    byte[] array = provider.ExportCspBlob(!provider.PublicOnly);

                    var strongNameProvider = new DesktopStrongNameProvider();


                    var options = context.Compilation.Options.WithStrongNameProvider(strongNameProvider)
                                                                   .WithCryptoKeyFile(keyFile.FullName)
                                                                   .WithDelaySign(delaySign);

                    // Enfore viral strong naming
                    var specificDiagnosticOptions = new Dictionary<string, ReportDiagnostic>(options.SpecificDiagnosticOptions);
                    specificDiagnosticOptions["CS8002"] = ReportDiagnostic.Error;
                    options = options.WithSpecificDiagnosticOptions(specificDiagnosticOptions);

                    context.Compilation = context.Compilation.WithOptions(options);
                }
                else
                {
                    // The key was not found. Throw a compile error.
                    var descriptor = new DiagnosticDescriptor(
                    id: "SN1001",
                    title: "Missing key file",
                    messageFormat: "Key file '{0}' could not be found",
                    category: "CA1001: \"StrongNaming\"",
                    defaultSeverity: DiagnosticSeverity.Error,
                    isEnabledByDefault: true);

                    // TODO: what should this reference for the location?
                    var textSpan = new TextSpan();
                    var position = new LinePosition(0, 0);
                    var span = new LinePositionSpan(position, position);

                    var location = Location.Create(context.ProjectContext.ProjectFilePath, textSpan, span);

                    var diagnsotic = Diagnostic.Create(descriptor, location, keyPath);

                    context.Diagnostics.Add(diagnsotic);
                }
            }
        }
Exemplo n.º 6
0
 public void BeforeCompile(IBeforeCompileContext context)
 {
     var options = CSharpParseOptions.Default
         .WithLanguageVersion(context.CSharpCompilation.LanguageVersion);
     context.CSharpCompilation = context.CSharpCompilation.AddSyntaxTrees(CSharpSyntaxTree.ParseText(@"
     public class Foo
     {
     public string Message
     {
     get { return ""Metaprogrammg!""; }
     }
     }", options));
 }
Exemplo n.º 7
0
 public RazorPreCompiler(
     [NotNull] IBeforeCompileContext 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);
 }
Exemplo n.º 8
0
        public virtual void CompileViews([NotNull] IBeforeCompileContext context)
        {
            var descriptors = CreateCompilationDescriptors(context);

            if (descriptors.Any())
            {
                var collectionGenerator = new RazorFileInfoCollectionGenerator(
                    descriptors,
                    CompilationSettings);

                var tree = collectionGenerator.GenerateCollection();
                context.CSharpCompilation = context.CSharpCompilation.AddSyntaxTrees(tree);
            }
        }
Exemplo n.º 9
0
        public virtual void BeforeCompile(IBeforeCompileContext context)
        {
            var appEnv = _appServices.GetRequiredService <IApplicationEnvironment>();

            var setup = new RazorViewEngineOptionsSetup(appEnv);
            var sc    = new ServiceCollection();

            sc.ConfigureOptions(setup);
            sc.AddMvc();

            var viewCompiler = new RazorPreCompiler(BuildFallbackServiceProvider(sc, _appServices));

            viewCompiler.CompileViews(context);
        }
Exemplo n.º 10
0
        public void BeforeCompile(IBeforeCompileContext context)
        {
            var options = CSharpParseOptions.Default
                          .WithLanguageVersion(context.CSharpCompilation.LanguageVersion);

            context.CSharpCompilation = context.CSharpCompilation.AddSyntaxTrees(CSharpSyntaxTree.ParseText(@"
public class Foo 
{
    public string Message
    {
        get { return ""Metaprogrammg!""; } 
    }
}", options));
        }
Exemplo n.º 11
0
        public virtual void CompileViews([NotNull] IBeforeCompileContext context)
        {
            var descriptors = CreateCompilationDescriptors(context);

            if (descriptors.Count > 0)
            {
                var collectionGenerator = new RazorFileInfoCollectionGenerator(
                    descriptors,
                    SyntaxTreeGenerator.GetParseOptions(context.CSharpCompilation));

                var tree = collectionGenerator.GenerateCollection();
                context.CSharpCompilation = context.CSharpCompilation.AddSyntaxTrees(tree);
            }
        }
Exemplo n.º 12
0
        public virtual void BeforeCompile(IBeforeCompileContext context)
        {
            var sc     = new ServiceCollection();
            var appEnv = _appServices.GetRequiredService <IApplicationEnvironment>();

            var setup    = new RazorViewEngineOptionsSetup(appEnv);
            var accessor = new OptionsManager <RazorViewEngineOptions>(new[] { setup });

            sc.AddInstance <IOptions <RazorViewEngineOptions> >(accessor);
            sc.Add(MvcServices.GetDefaultServices());
            var sp = sc.BuildServiceProvider(_appServices);

            var viewCompiler = new RazorPreCompiler(sp);

            viewCompiler.CompileViews(context);
        }
Exemplo n.º 13
0
        public virtual void BeforeCompile(IBeforeCompileContext context)
        {
            var applicationEnvironment  = _appServices.GetRequiredService <IApplicationEnvironment>();
            var compilerOptionsProvider = _appServices.GetRequiredService <ICompilerOptionsProvider>();
            var compilationSettings     = compilerOptionsProvider.GetCompilationSettings(applicationEnvironment);

            var setup = new RazorViewEngineOptionsSetup(applicationEnvironment);
            var sc    = new ServiceCollection();

            sc.ConfigureOptions(setup);
            sc.AddMvc();

            var serviceProvider = BuildFallbackServiceProvider(sc, _appServices);
            var viewCompiler    = new RazorPreCompiler(serviceProvider, _memoryCache, compilationSettings);

            viewCompiler.CompileViews(context);
        }
Exemplo n.º 14
0
        protected virtual IEnumerable <RazorFileInfo> CreateCompilationDescriptors(
            [NotNull] IBeforeCompileContext context)
        {
            var filesToProcess = new List <RelativeFileInfo>();

            GetFileInfosRecursive(root: string.Empty, razorFiles: filesToProcess);

            var razorFiles      = new RazorFileInfo[filesToProcess.Count];
            var syntaxTrees     = new SyntaxTree[filesToProcess.Count];
            var parallelOptions = new ParallelOptions {
                MaxDegreeOfParallelism = MaxDegreesOfParallelism
            };
            var diagnosticsLock = new object();

            Parallel.For(0, filesToProcess.Count, parallelOptions, index =>
            {
                var file       = filesToProcess[index];
                var cacheEntry = PreCompilationCache.GetOrSet(file.RelativePath,
                                                              file,
                                                              OnCacheMiss);
                if (cacheEntry != null)
                {
                    if (cacheEntry.Success)
                    {
                        syntaxTrees[index] = cacheEntry.SyntaxTree;
                        razorFiles[index]  = cacheEntry.FileInfo;
                    }
                    else
                    {
                        lock (diagnosticsLock)
                        {
                            foreach (var diagnostic in cacheEntry.Diagnostics)
                            {
                                context.Diagnostics.Add(diagnostic);
                            }
                        }
                    }
                }
            });

            context.CSharpCompilation = context.CSharpCompilation
                                        .AddSyntaxTrees(syntaxTrees.Where(tree => tree != null));
            return(razorFiles.Where(file => file != null));
        }
Exemplo n.º 15
0
        /// <inheritdoc />
        /// <remarks>Pre-compiles all Razor views in the application.</remarks>
        public virtual void BeforeCompile(IBeforeCompileContext 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();
        }
Exemplo n.º 16
0
        /// <inheritdoc />
        /// <remarks>Pre-compiles all Razor views in the application.</remarks>
        public virtual void BeforeCompile(IBeforeCompileContext 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();
        }
Exemplo n.º 17
0
        protected virtual IReadOnlyList <RazorFileInfo> CreateCompilationDescriptors(
            [NotNull] IBeforeCompileContext context)
        {
            var options = SyntaxTreeGenerator.GetParseOptions(context.CSharpCompilation);
            var list    = new List <RazorFileInfo>();

            foreach (var info in GetFileInfosRecursive(string.Empty))
            {
                var descriptor = ParseView(info,
                                           context,
                                           options);

                if (descriptor != null)
                {
                    list.Add(descriptor);
                }
            }

            return(list);
        }
Exemplo n.º 18
0
        protected virtual RazorFileInfo ParseView([NotNull] RelativeFileInfo fileInfo,
                                                  [NotNull] IBeforeCompileContext context,
                                                  [NotNull] CSharpParseOptions options)
        {
            using (var stream = fileInfo.FileInfo.CreateReadStream())
            {
                var results = _host.GenerateCode(fileInfo.RelativePath, stream);

                foreach (var parserError in results.ParserErrors)
                {
                    var diagnostic = parserError.ToDiagnostics(fileInfo.FileInfo.PhysicalPath);
                    context.Diagnostics.Add(diagnostic);
                }

                var generatedCode = results.GeneratedCode;

                if (generatedCode != null)
                {
                    var syntaxTree   = SyntaxTreeGenerator.Generate(generatedCode, fileInfo.FileInfo.PhysicalPath, options);
                    var fullTypeName = results.GetMainClassName(_host, syntaxTree);

                    if (fullTypeName != null)
                    {
                        context.CSharpCompilation = context.CSharpCompilation.AddSyntaxTrees(syntaxTree);

                        var hash = RazorFileHash.GetHash(fileInfo.FileInfo);

                        return(new RazorFileInfo()
                        {
                            FullTypeName = fullTypeName,
                            RelativePath = fileInfo.RelativePath,
                            LastModified = fileInfo.FileInfo.LastModified,
                            Length = fileInfo.FileInfo.Length,
                            Hash = hash,
                        });
                    }
                }
            }

            return(null);
        }
        public void BeforeCompile(IBeforeCompileContext context)
        {
            // Find all the class containers we care about.
            var containers = context.CSharpCompilation.SyntaxTrees
                             .Select(tree => new
            {
                Model      = context.CSharpCompilation.GetSemanticModel(tree),
                SyntaxTree = tree,
                Root       = tree.GetRoot()
            });


            var addAssemblyMethodCalls = containers
                                         .SelectMany(ctx => GetAddAssemblyMethodCall(ctx.SyntaxTree, ctx.Model));

            // Build the registration statements out of the containers.
            var nodes = GetStatements(context, containers.SelectMany(ctx => GetClassesWithImplementationAttribute(ctx.SyntaxTree, ctx.Model)))
                        .ToArray();

            var newCompilation = context.CSharpCompilation;

            foreach (var method in addAssemblyMethodCalls)
            {
                var identifierName = ((MemberAccessExpressionSyntax)method.Declaration.Expression).Expression.ToString();

                var methodNodes = nodes.SelectMany(x => x(identifierName));

                var oldSyntaxRoot = method.Declaration.SyntaxTree.GetRoot();
                var newSyntaxRoot = oldSyntaxRoot
                                    .ReplaceNode(method.Declaration.Parent, methodNodes)
                                    .NormalizeWhitespace();

                var oldSyntaxTree = method.Declaration.SyntaxTree;
                var newSyntaxTree = oldSyntaxTree.WithRootAndOptions(newSyntaxRoot, oldSyntaxTree.Options);

                newCompilation = newCompilation.ReplaceSyntaxTree(oldSyntaxTree, newSyntaxTree);
            }

            context.CSharpCompilation = newCompilation;
        }
Exemplo n.º 20
0
        public void BeforeCompile(IBeforeCompileContext context)
        {
            //Debugger.Launch();

            var project = ((CompilationContext)(context)).Project;
            var settings = LoadSettings(project);

            // HACK to make project available to default view
            _defaultRazorViewLocator.ProjectDelegate = () => project;
            _defaultStaticFileLocator.ProjectDelegate = () => project;

            // generate r4mvc syntaxtree
            var generator = _serviceProvider.GetService<R4MvcGenerator>();
            var generatedNode = generator.Generate((CompilationContext)context, settings);

            // out to file
            var generatedFilePath = Path.Combine(project.ProjectDirectory, R4MvcGenerator.R4MvcFileName);
            generatedNode.WriteFile(generatedFilePath);

            // update compilation
            context.Compilation.AddSyntaxTrees(generatedNode.SyntaxTree);
        }
Exemplo n.º 21
0
        public void BeforeCompile(IBeforeCompileContext context)
        {
            //Debugger.Launch();

            var project  = ((CompilationContext)(context)).Project;
            var settings = LoadSettings(project);

            // HACK to make project available to default view
            _defaultRazorViewLocator.ProjectDelegate  = () => project;
            _defaultStaticFileLocator.ProjectDelegate = () => project;

            // generate r4mvc syntaxtree
            var generator     = _serviceProvider.GetService <R4MvcGenerator>();
            var generatedNode = generator.Generate((CompilationContext)context, settings);

            // out to file
            var generatedFilePath = Path.Combine(project.ProjectDirectory, R4MvcGenerator.R4MvcFileName);

            generatedNode.WriteFile(generatedFilePath);

            // update compilation
            context.Compilation.AddSyntaxTrees(generatedNode.SyntaxTree);
        }
 public void BeforeCompile(IBeforeCompileContext context)
 {
 }
        public Func <string, IEnumerable <StatementSyntax> > GetStatement(IBeforeCompileContext context, INamedTypeSymbol symbol, ClassDeclarationSyntax declaration)
        {
            var attributeSymbol      = symbol.GetAttributes().Single(x => x.AttributeClass.Name.ToString().Contains("ServiceDescriptorAttribute"));
            var attributeDeclaration = declaration.AttributeLists
                                       .SelectMany(z => z.Attributes)
                                       .Single(z => z.Name.ToString().Contains("ServiceDescriptor"));

            var implementationType          = symbol.ConstructUnboundGenericType().ToDisplayString();
            var implementationQualifiedName = BuildQualifiedName(implementationType, symbol.TypeParameters.Count());

            string serviceType = null;
            IEnumerable <NameSyntax> serviceQualifiedNames = symbol.AllInterfaces
                                                             .Select(z => BuildQualifiedName(z.ConstructUnboundGenericType().ToDisplayString(), z.TypeParameters.Count()));

            if (declaration.Modifiers.Any(z => z.RawKind == (int)SyntaxKind.PublicKeyword))
            {
                // TODO:  Should this include all base types?  Should it be the lowest base type (HttpContext for example)?
                serviceQualifiedNames = serviceQualifiedNames.Union(new NameSyntax[] { implementationQualifiedName });
            }

            if (attributeSymbol.ConstructorArguments.Count() > 0 && attributeSymbol.ConstructorArguments[0].Value != null)
            {
                var serviceNameTypedSymbol = (INamedTypeSymbol)attributeSymbol.ConstructorArguments[0].Value;
                if (serviceNameTypedSymbol == null)
                {
                    throw new Exception("Could not infer service symbol");
                }
                serviceType           = serviceNameTypedSymbol.ConstructUnboundGenericType().ToString();
                serviceQualifiedNames = new NameSyntax[] { BuildQualifiedName(serviceType, serviceNameTypedSymbol.TypeParameters.Count()) };
            }


            var baseTypes = new List <string>();
            var impType   = symbol;

            while (impType != null)
            {
                baseTypes.Add(impType.ToDisplayString());
                impType = impType.BaseType;
            }

            // TODO: Enforce implementation is assignable to service
            // Diagnostic error?
            var potentialBaseTypes = baseTypes.Concat(
                symbol.AllInterfaces.Select(z => z.ConstructUnboundGenericType().ToDisplayString())
                );

            // This is where some of the power comes out.
            // We now have the ability to throw compile time errors if we believe something is wrong.
            // This could be extended to support generic types, and potentially matching compatible open generic types together to build a list.
            if (serviceType != null && !potentialBaseTypes.Any(z => serviceType.Equals(z, StringComparison.OrdinalIgnoreCase)))
            {
                var serviceName        = serviceType.Split('.').Last();
                var implementationName = implementationType.Split('.').Last();

                context.Diagnostics.Add(
                    Diagnostic.Create(
                        new DiagnosticDescriptor(
                            "DI0001",
                            "Implementation miss-match",
                            "The implementation '{0}' does not implement the service '{1}'",
                            "DependencyInjection",
                            DiagnosticSeverity.Error,
                            true
                            ),
                        Location.Create(attributeDeclaration.SyntaxTree, attributeDeclaration.Span),
                        implementationName,
                        serviceName
                        )
                    );
            }

            var hasLifecycle = attributeSymbol.NamedArguments.Any(z => z.Key == "Lifecycle");
            var lifecycle    = "Transient";

            if (hasLifecycle)
            {
                lifecycle = GetLifecycle((int)attributeSymbol.NamedArguments.Single(z => z.Key == "Lifecycle").Value.Value);
            }

            // Build the Statement
            return(GetCollectionExpressionStatement(lifecycle, serviceQualifiedNames, implementationQualifiedName));
        }
 public IEnumerable <Func <string, IEnumerable <StatementSyntax> > > GetStatements(IBeforeCompileContext context, IEnumerable <Container <ClassDeclarationSyntax, INamedTypeSymbol> > containers)
 {
     foreach (var container in containers)
     {
         yield return(GetStatement(context, container.Symbol, container.Declaration));
     }
 }
Exemplo n.º 25
0
        public void BeforeCompile(IBeforeCompileContext 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);
            }
        }
Exemplo n.º 26
0
        public void BeforeCompile(IBeforeCompileContext 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);
            }
        }
Exemplo n.º 27
0
 /// <summary>
 /// Initializes a new instance of <see cref="PrecompilationTagHelperTypeResolver"/>.
 /// </summary>
 /// <param name="compileContext">The <see cref="IBeforeCompileContext"/>.</param>
 /// <param name="loadContext">The <see cref="IAssemblyLoadContext"/>.</param>
 public PrecompilationTagHelperTypeResolver([NotNull] IBeforeCompileContext compileContext,
                                            [NotNull] IAssemblyLoadContext loadContext)
 {
     _compileContext = compileContext;
     _loadContext    = loadContext;
 }
 /// <summary>
 /// Initializes a new instance of <see cref="PrecompilationTagHelperTypeResolver"/>.
 /// </summary>
 /// <param name="compileContext">The <see cref="IBeforeCompileContext"/>.</param>
 /// <param name="loadContext">The <see cref="IAssemblyLoadContext"/>.</param>
 public PrecompilationTagHelperTypeResolver([NotNull] IBeforeCompileContext compileContext,
                                            [NotNull] IAssemblyLoadContext loadContext)
 {
     _compileContext = compileContext;
     _loadContext = loadContext;
 }