public (SourceText?source, IReadOnlyList <Diagnostic> diagnostics) CreateImplementation(INamedTypeSymbol namedTypeSymbol)
        {
            // If we've got any symbols errors from just instantiating it, we're going to have a bad time. Give up now.
            if (this.symbolsDiagnosticReporter.HasErrors)
            {
                return(null, Array.Empty <Diagnostic>());
            }

            var diagnosticReporter = new DiagnosticReporter();
            var analyzer           = new RoslynTypeAnalyzer(this.compilation, namedTypeSymbol, this.wellKnownSymbols, this.attributeInstantiator, diagnosticReporter);
            var typeModel          = analyzer.Analyze();
            var generator          = new ImplementationGenerator(typeModel, this.emitter, diagnosticReporter);
            var emittedType        = generator.Generate();

            // If there are symbols diagnostic errors, we have to fail this type.
            // However, we'll then clear the symbols diagnostics, so we can move onto the next type
            // (which might succeed).
            // We'll report the symbols diagnostics in one go at the end. We might well end up with duplicates
            // (WellKnownSymbols will keep reporting the same diagnostics), so use a HashSet.

            this.symbolsDiagnostics.UnionWith(this.symbolsDiagnosticReporter.Diagnostics);
            bool hasSymbolsErrors = this.symbolsDiagnosticReporter.HasErrors;

            this.symbolsDiagnosticReporter.Clear();

            return(hasSymbolsErrors || diagnosticReporter.HasErrors
                ? null
                : emittedType.SourceText, diagnosticReporter.Diagnostics);
        }
Esempio n. 2
0
        public WellKnownSymbols(Compilation compilation, DiagnosticReporter diagnosticReporter)
        {
            this.compilation        = compilation;
            this.diagnosticReporter = diagnosticReporter;
            var restEaseAssembly = GetReferencedAssemblies(compilation.Assembly)
                                   .FirstOrDefault(x => x.Name == "RestEase");

            if (restEaseAssembly == null)
            {
                this.diagnosticReporter.ReportCouldNotFindRestEaseAssembly();
            }
            else
            {
                var versionRangeAttribute = typeof(WellKnownSymbols).Assembly.GetCustomAttribute <AllowedRestEaseVersionRangeAttribute>();
                var(minInclusive, maxExclusive) = (new Version(versionRangeAttribute.MinVersionInclusive), new Version(versionRangeAttribute.MaxVersionExclusive));
                var restEaseVersion = restEaseAssembly.Identity.Version;

                if (restEaseVersion < minInclusive)
                {
                    this.diagnosticReporter.ReportRestEaseVersionTooOld(restEaseVersion, minInclusive, maxExclusive);
                }
                else if (restEaseVersion >= maxExclusive)
                {
                    this.diagnosticReporter.ReportRestEaseVersionTooNew(restEaseVersion, minInclusive, maxExclusive);
                }
                else
                {
                    this.restEaseAssembly = restEaseAssembly;
                }
            }
        }
 public ProjectFileLoaderRegistry(Workspace workspace, DiagnosticReporter diagnosticReporter)
 {
     _workspace              = workspace;
     _diagnosticReporter     = diagnosticReporter;
     _extensionToLanguageMap = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
     _dataGuard              = new NonReentrantLock();
 }
Esempio n. 4
0
        public Type BuildEmitImplementation(Type interfaceType)
        {
            var analyzer           = new ReflectionTypeAnalyzer(interfaceType);
            var typeModel          = analyzer.Analyze();
            var diagnosticReporter = new DiagnosticReporter(typeModel);
            var generator          = new ImplementationGenerator(typeModel, this.emitter, diagnosticReporter);

            return(generator.Generate().Type);
        }
    internal DiagnosticSuppressorBenchmark()
    {
        analyzer   = new DiagnosticReporter();
        suppressor = new TDiagnosticSuppressor();
        analyzers  = ImmutableArray.Create <DiagnosticAnalyzer>(analyzer, suppressor);

        source      = null !;
        compilation = null !;
        syntaxTree  = null !;
    }
        public RoslynImplementationFactory(Compilation compilation)
        {
            this.compilation = compilation;
            this.symbolsDiagnosticReporter = new DiagnosticReporter();
            this.wellKnownSymbols          = new WellKnownSymbols(compilation, this.symbolsDiagnosticReporter);
            this.attributeInstantiator     = new AttributeInstantiator(this.wellKnownSymbols);
            this.emitter = new Emitter(this.wellKnownSymbols);

            // Catch any symbols errors from just instantiating WellKnownSymbols
            this.symbolsDiagnostics.UnionWith(this.symbolsDiagnosticReporter.Diagnostics);
        }
Esempio n. 7
0
 public WellKnownSymbols(Compilation compilation, DiagnosticReporter diagnosticReporter)
 {
     this.compilation        = compilation;
     this.diagnosticReporter = diagnosticReporter;
     this.restEaseAssembly   = GetReferencedAssemblies(compilation.Assembly)
                               .FirstOrDefault(x => x.Name == "RestEase");
     if (this.restEaseAssembly == null)
     {
         this.diagnosticReporter.ReportCouldNotFindRestEaseAssembly();
     }
 }
Esempio n. 8
0
 public ActionResult Diagnostics()
 {
     if (Request.IsLocal)
     {
         var verifier = new DiagnosticReporter();
         return(Content(verifier.GetVerificationReport(), "text/plain", Encoding.UTF8));
     }
     else
     {
         return(Content("You can only run the diagnostics locally to the server"));
     }
 }
Esempio n. 9
0
 public ActionResult Diagnostics()
 {
     if (Url.IsLocalUrl(Request.GetEncodedUrl()))
     {
         var verifier = new DiagnosticReporter(HttpContext.RequestServices.GetService <IHostingEnvironment>());
         return(Content(verifier.GetVerificationReport(HttpContext.RequestServices), "text/plain", Encoding.UTF8));
     }
     else
     {
         return(Content("You can only run the diagnostics locally to the server"));
     }
 }
Esempio n. 10
0
 public RoslynTypeAnalyzer(
     Compilation compilation,
     INamedTypeSymbol namedTypeSymbol,
     WellKnownSymbols wellKnownSymbols,
     AttributeInstantiator attributeInstantiator,
     DiagnosticReporter diagnosticReporter)
 {
     this.compilation           = compilation;
     this.namedTypeSymbol       = namedTypeSymbol;
     this.wellKnownSymbols      = wellKnownSymbols;
     this.attributeInstantiator = attributeInstantiator;
     this.diagnosticReporter    = diagnosticReporter;
 }
Esempio n. 11
0
 internal CandidateInterfacesProcessor(
     Compilation compilation,
     List <InterfaceDeclarationSyntax> interfaceDeclarationSyntaxList,
     INamedTypeSymbol interfaceAttributeSymbol,
     INamedTypeSymbol methodAttributeSymbol,
     DiagnosticReporter diagnosticReporter)
 {
     _compilation = compilation;
     _interfaceDeclarationSyntaxList = interfaceDeclarationSyntaxList;
     _interfaceAttributeSymbol       = interfaceAttributeSymbol;
     _methodAttributeSymbol          = methodAttributeSymbol;
     _diagnosticReporter             = diagnosticReporter;
 }
Esempio n. 12
0
        private Attribute?ParseRequestAttributeSubclass(
            AttributeData attributeData,
            ISymbol declaringSymbol,
            DiagnosticReporter diagnosticReporter,
            Func <RequestAttributeBase> parameterlessCtor,
            Func <string, RequestAttributeBase> pathCtor)
        {
            RequestAttributeBase?attribute = null;

            if (attributeData.ConstructorArguments.Length == 0)
            {
                attribute = parameterlessCtor();
            }
            else if (attributeData.ConstructorArguments.Length == 1 &&
                     attributeData.ConstructorArguments[0].Type?.SpecialType == SpecialType.System_String)
            {
                attribute = pathCtor((string)attributeData.ConstructorArguments[0].Value !);
            }

            if (attribute != null)

            {
                foreach (var namedArgument in attributeData.NamedArguments)
                {
                    if (namedArgument.Key == nameof(RequestAttributeBase.Path) &&
                        namedArgument.Value.Type?.SpecialType == SpecialType.System_String)
                    {
                        attribute.Path = (string?)namedArgument.Value.Value;
                    }
                    else
                    {
                        diagnosticReporter.ReportAttributePropertyNotRecognised(attributeData, namedArgument, declaringSymbol);
                    }
                }
            }
            else
            {
                diagnosticReporter.ReportAttributeConstructorNotRecognised(attributeData, declaringSymbol);
            }

            return(attribute);
        }
        public void Execute(GeneratorExecutionContext context)
        {
            if (!(context.SyntaxReceiver is SyntaxReceiver syntaxReceiver))
            {
                return;
            }

            var interfaceAttributeSymbol =
                context.Compilation.GetTypeByMetadataName(typeof(BlazorJSInteropSourceAttribute).FullName);
            var methodAttributeSymbol =
                context.Compilation.GetTypeByMetadataName(typeof(BlazorJSInteropMethodAttribute).FullName);

            var diagnosticReporter = new DiagnosticReporter(context);

            var candidateInterfacesProcessor = new CandidateInterfacesProcessor(
                context.Compilation,
                syntaxReceiver.CandidateInterfaces,
                interfaceAttributeSymbol,
                methodAttributeSymbol,
                diagnosticReporter);

            var validInterfaceInfoList = candidateInterfacesProcessor.GetValidInterfaceInfoList();

            if (diagnosticReporter.HasReported)
            {
                return;
            }

            var sourceCodeBuilder = new SourceCodeBuilder(methodAttributeSymbol);

            foreach (var validInterfaceInfo in validInterfaceInfoList)
            {
                var sourceCode = sourceCodeBuilder.BuildSourceCode(validInterfaceInfo);
                context.AddSource($"{validInterfaceInfo.InterfaceNamespace}.{validInterfaceInfo.InterfaceName}",
                                  SourceText.From(sourceCode, Encoding.UTF8));
            }
        }
Esempio n. 14
0
        private Attribute?ParseAllowAnyStatusCodeAttribute(AttributeData attributeData, ISymbol declaringSymbol, DiagnosticReporter diagnosticReporter)
        {
            AllowAnyStatusCodeAttribute?attribute = null;

            if (attributeData.ConstructorArguments.Length == 0)
            {
                attribute = new AllowAnyStatusCodeAttribute();
            }
            else if (attributeData.ConstructorArguments.Length == 1 &&
                     attributeData.ConstructorArguments[0].Type?.SpecialType == SpecialType.System_Boolean)
            {
                attribute = new AllowAnyStatusCodeAttribute((bool)attributeData.ConstructorArguments[0].Value !);
            }

            if (attribute != null)
            {
                foreach (var namedArgument in attributeData.NamedArguments)
                {
                    if (namedArgument.Key == nameof(AllowAnyStatusCodeAttribute.AllowAnyStatusCode) &&
                        namedArgument.Value.Type?.SpecialType == SpecialType.System_Boolean)
                    {
                        attribute.AllowAnyStatusCode = (bool)namedArgument.Value.Value !;
                    }
                    else
                    {
                        diagnosticReporter.ReportAttributePropertyNotRecognised(attributeData, namedArgument, declaringSymbol);
                    }
                }
            }
            else
            {
                diagnosticReporter.ReportAttributeConstructorNotRecognised(attributeData, declaringSymbol);
            }

            return(attribute);
        }
Esempio n. 15
0
        public Attribute?Instantiate(AttributeData attributeData, ISymbol declaringSymbol, DiagnosticReporter diagnosticReporter)
        {
            var attributeClass = attributeData.AttributeClass;

            if (attributeClass == null)
            {
                return(null);
            }

            if (this.lookup.TryGetValue(attributeClass, out var parser))
            {
                return(parser(attributeData, declaringSymbol, diagnosticReporter));
            }

            return(null);
        }
Esempio n. 16
0
 public IEnumerable <(Attribute attribute, AttributeData attributeData, ISymbol declaringSymbol)> Instantiate(ISymbol symbol, DiagnosticReporter diagnosticReporter)
 {
     return(symbol.GetAttributes()
            .Select(x => (this.Instantiate(x, symbol, diagnosticReporter), x, symbol))
            .Where(x => x.Item1 != null) !);
 }
Esempio n. 17
0
        private Attribute?ParseQueryMapAttribute(AttributeData attributeData, ISymbol declaringSymbol, DiagnosticReporter diagnosticReporter)
        {
            QueryMapAttribute?attribute = null;

            if (attributeData.ConstructorArguments.Length == 0)
            {
                attribute = new QueryMapAttribute();
            }
            else if (attributeData.ConstructorArguments.Length == 1 &&
                     SymbolEqualityComparer.Default.Equals(attributeData.ConstructorArguments[0].Type, this.wellKnownSymbols.QuerySerializationMethod))
            {
                attribute = new QueryMapAttribute((QuerySerializationMethod)attributeData.ConstructorArguments[0].Value !);
            }

            if (attribute != null)
            {
                foreach (var namedArgument in attributeData.NamedArguments)
                {
                    if (namedArgument.Key == nameof(QueryMapAttribute.SerializationMethod) &&
                        SymbolEqualityComparer.Default.Equals(namedArgument.Value.Type, this.wellKnownSymbols.QueryMapAttribute))
                    {
                        attribute.SerializationMethod = (QuerySerializationMethod)namedArgument.Value.Value !;
                    }
                    else
                    {
                        diagnosticReporter.ReportAttributePropertyNotRecognised(attributeData, namedArgument, declaringSymbol);
                    }
                }
            }
            else
            {
                diagnosticReporter.ReportAttributeConstructorNotRecognised(attributeData, declaringSymbol);
            }

            return(attribute);
        }
Esempio n. 18
0
        private Attribute?ParseHttpRequestMessagePropertyAttribute(AttributeData attributeData, ISymbol declaringSymbol, DiagnosticReporter diagnosticReporter)
        {
            HttpRequestMessagePropertyAttribute?attribute = null;

            if (attributeData.ConstructorArguments.Length == 0)
            {
                attribute = new HttpRequestMessagePropertyAttribute();
            }
            else if (attributeData.ConstructorArguments.Length == 1 &&
                     attributeData.ConstructorArguments[0].Type?.SpecialType == SpecialType.System_String)
            {
                attribute = new HttpRequestMessagePropertyAttribute((string)attributeData.ConstructorArguments[0].Value !);
            }

            if (attribute != null)
            {
                foreach (var namedArgument in attributeData.NamedArguments)
                {
                    if (namedArgument.Key == nameof(HttpRequestMessagePropertyAttribute.Key) &&
                        namedArgument.Value.Type?.SpecialType == SpecialType.System_String)
                    {
                        attribute.Key = (string?)namedArgument.Value.Value;
                    }
                    else
                    {
                        diagnosticReporter.ReportAttributePropertyNotRecognised(attributeData, namedArgument, declaringSymbol);
                    }
                }
            }
            else
            {
                diagnosticReporter.ReportAttributeConstructorNotRecognised(attributeData, declaringSymbol);
            }

            return(attribute);
        }
Esempio n. 19
0
        private Attribute?ParseRawQueryStringAttribute(AttributeData attributeData, ISymbol declaringSymbol, DiagnosticReporter diagnosticReporter)
        {
            RawQueryStringAttribute?attribute = null;

            if (attributeData.ConstructorArguments.Length == 0)
            {
                attribute = new RawQueryStringAttribute();
            }

            if (attribute != null)
            {
                foreach (var namedArgument in attributeData.NamedArguments)
                {
                    diagnosticReporter.ReportAttributePropertyNotRecognised(attributeData, namedArgument, declaringSymbol);
                }
            }
            else
            {
                diagnosticReporter.ReportAttributeConstructorNotRecognised(attributeData, declaringSymbol);
            }

            return(attribute);
        }
Esempio n. 20
0
        private Attribute?ParsePathAttribute(AttributeData attributeData, ISymbol declaringSymbol, DiagnosticReporter diagnosticReporter)
        {
            PathAttribute?attribute = null;

            if (attributeData.ConstructorArguments.Length == 0)
            {
                attribute = new PathAttribute();
            }
            else if (attributeData.ConstructorArguments.Length == 1)
            {
                if (attributeData.ConstructorArguments[0].Type?.SpecialType == SpecialType.System_String)
                {
                    attribute = new PathAttribute((string)attributeData.ConstructorArguments[0].Value !);
                }
                else if (SymbolEqualityComparer.Default.Equals(attributeData.ConstructorArguments[0].Type, this.wellKnownSymbols.PathSerializationMethod))
                {
                    attribute = new PathAttribute((PathSerializationMethod)attributeData.ConstructorArguments[0].Value !);
                }
            }
            else if (attributeData.ConstructorArguments.Length == 2)
            {
                if (attributeData.ConstructorArguments[0].Type?.SpecialType == SpecialType.System_String &&
                    SymbolEqualityComparer.Default.Equals(attributeData.ConstructorArguments[1].Type, this.wellKnownSymbols.PathSerializationMethod))
                {
                    attribute = new PathAttribute((string)attributeData.ConstructorArguments[0].Value !, (PathSerializationMethod)attributeData.ConstructorArguments[1].Value !);
                }
            }

            if (attribute != null)
            {
                foreach (var namedArgument in attributeData.NamedArguments)
                {
                    if (namedArgument.Key == nameof(PathAttribute.Name) &&
                        namedArgument.Value.Type?.SpecialType == SpecialType.System_String)
                    {
                        attribute.Name = (string?)namedArgument.Value.Value;
                    }
                    else if (namedArgument.Key == nameof(PathAttribute.SerializationMethod) &&
                             SymbolEqualityComparer.Default.Equals(namedArgument.Value.Type, this.wellKnownSymbols.PathSerializationMethod))
                    {
                        attribute.SerializationMethod = (PathSerializationMethod)namedArgument.Value.Value !;
                    }
                    else if (namedArgument.Key == nameof(PathAttribute.Format) &&
                             namedArgument.Value.Type?.SpecialType == SpecialType.System_String)
                    {
                        attribute.Format = (string?)namedArgument.Value.Value;
                    }
                    else if (namedArgument.Key == nameof(PathAttribute.UrlEncode) &&
                             namedArgument.Value.Type?.SpecialType == SpecialType.System_Boolean)
                    {
                        attribute.UrlEncode = (bool)namedArgument.Value.Value !;
                    }
                    else
                    {
                        diagnosticReporter.ReportAttributePropertyNotRecognised(attributeData, namedArgument, declaringSymbol);
                    }
                }
            }
            else
            {
                diagnosticReporter.ReportAttributeConstructorNotRecognised(attributeData, declaringSymbol);
            }

            return(attribute);
        }
Esempio n. 21
0
        private Attribute?ParseBasePathAttribute(AttributeData attributeData, ISymbol declaringSymbol, DiagnosticReporter diagnosticReporter)
        {
            BasePathAttribute?attribute = null;

            if (attributeData.ConstructorArguments.Length == 1 &&
                attributeData.ConstructorArguments[0].Type?.SpecialType == SpecialType.System_String)
            {
                attribute = new BasePathAttribute((string)attributeData.ConstructorArguments[0].Value !);
            }

            if (attribute != null)
            {
                foreach (var namedArgument in attributeData.NamedArguments)
                {
                    diagnosticReporter.ReportAttributePropertyNotRecognised(attributeData, namedArgument, declaringSymbol);
                }
            }
            else
            {
                diagnosticReporter.ReportAttributeConstructorNotRecognised(attributeData, declaringSymbol);
            }

            return(attribute);
        }
Esempio n. 22
0
        public void Execute(GeneratorExecutionContext context)
        {
            try
            {
                var diagnosticReporter = new DiagnosticReporter(
                    context
                    );

                var needToStoreGeneratedSources = context.AnalyzerConfigOptions.GlobalOptions.TryGetValue(
                    $"build_property.Dpdt_Generator_GeneratedSourceFolder",
                    out var generatedSourceFolder
                    );

                var generatedSourceFolderFullPath =
                    Path.GetFullPath(
                        generatedSourceFolder ?? "Dpdt.Pregenerated"
                        );

                var typeInfoContainer = new GeneratorTypeInfoContainer(
                    ref context,
                    needToStoreGeneratedSources,
                    generatedSourceFolderFullPath
                    );

                var internalGenerator = new DpdtInternalGenerator(
                    diagnosticReporter
                    );

                if (needToStoreGeneratedSources)
                {
                    if (Directory.Exists(generatedSourceFolderFullPath))
                    {
                        Directory.Delete(generatedSourceFolderFullPath, true);
                    }

                    Directory.CreateDirectory(generatedSourceFolderFullPath);
                }

                internalGenerator.Execute(
                    typeInfoContainer,
                    null
                    );

                diagnosticReporter.ReportWarning(
                    "Dpdt generator successfully finished its work",
                    $"Dpdt generator successfully finished its work, {typeInfoContainer.UnitsGenerated} compilation unit(s) generated."
                    );
            }
            catch (Exception excp)
            {
                context.ReportDiagnostic(
                    Diagnostic.Create(
                        new DiagnosticDescriptor(
                            id: "DPDTINJECT100",
                            title: "Couldn't generate a binding boilerplate code",
                            messageFormat: "Couldn't generate a binding boilerplate code '{0}' {1}",
                            category: "DpDtInject",
                            DiagnosticSeverity.Error,
                            isEnabledByDefault: true
                            ),
                        Location.None,
                        excp.Message,
                        excp.StackTrace
                        )
                    );
            }
        }
 public ImplementationGenerator(TypeModel typeModel, Emitter emitter, DiagnosticReporter diagnosticReporter)
 {
     this.typeModel   = typeModel;
     this.emitter     = emitter;
     this.diagnostics = diagnosticReporter;
 }
Esempio n. 24
0
        public void Execute(GeneratorExecutionContext context)
        {
            try
            {
                if (!(context.SyntaxReceiver is ClusterCandidateSyntaxReceiver receiver))
                {
                    return;
                }

                var doBeautify     = true;
                var beautifyExists = context.AnalyzerConfigOptions.GlobalOptions.TryGetValue(
                    $"build_property.Dpdt_Generator_Beautify",
                    out var beautify
                    );
                if (beautifyExists)
                {
                    if (bool.TryParse(beautify?.ToLower() ?? "false", out var parsed))
                    {
                        doBeautify = parsed;
                    }
                }

                var diagnosticReporter = new DiagnosticReporter(
                    context
                    );

                var sw = Stopwatch.StartNew();

                var typeInfoContainer = new GeneratorTypeInfoContainer(
                    ref context,
                    receiver.CandidateClasses
                    );

                var internalGenerator = new DpdtInternalGenerator(
                    diagnosticReporter,
                    doBeautify
                    );

                internalGenerator.Execute(
                    typeInfoContainer
                    );

                diagnosticReporter.ReportWarning(
                    "Dpdt generator successfully finished its work",
                    $"Dpdt generator successfully finished its work, {typeInfoContainer.UnitsGenerated} compilation unit(s) generated, taken {sw.Elapsed}."
                    );
            }
            catch (Exception excp)
            {
                Logging.LogGen(excp);

                context.ReportDiagnostic(
                    Diagnostic.Create(
                        new DiagnosticDescriptor(
                            id: "DPDTINJECT100",
                            title: "Couldn't generate a binding boilerplate code",
                            messageFormat: "Couldn't generate a binding boilerplate code '{0}' {1}",
                            category: "DpDtInject",
                            DiagnosticSeverity.Error,
                            isEnabledByDefault: true
                            ),
                        Location.None,
                        excp.Message,
                        excp.StackTrace
                        )
                    );
            }
        }
Esempio n. 25
0
        public static ParsedCommandLine parseConfigFile(string configFileName, CompilerOptions optionsToExtend,
                                                        DirectoryStructureHost system, DiagnosticReporter reportDiagnostic, DiagnosticReporter reportWatchDiagnostic)
        {
            string configFileText = null;

            try
            {
                configFileText = System.IO.File.ReadAllText(configFileName);
            }
            catch (Exception e)
            {
                throw (new Exception("Cannot_read_file_0_Colon_1", e));
                //const error = createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message);
                //reportWatchDiagnostic(error);
                //system.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
                //return;
            }
            if (null == configFileText)
            {
                throw (new Exception("File_0_not_found"));
                //const error = createCompilerDiagnostic(Diagnostics.File_0_not_found, configFileName);
                //reportDiagnostics([error], reportDiagnostic);
                //system.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
                //return;
            }

            var result = parseJsonText(configFileName, configFileText);
            //reportDiagnostics(result.parseDiagnostics, reportDiagnostic);

            //const cwd = system.getCurrentDirectory();
            //var configParseResult = new ParsedCommandLine();
            var configParseResult = parseJsonSourceFileConfigFileContent(result, system, System.IO.Path.GetDirectoryName(configFileName), optionsToExtend, configFileName);

            //reportDiagnostics(configParseResult.errors, reportDiagnostic);

            return(configParseResult);
        }
Esempio n. 26
0
        public void Execute(GeneratorExecutionContext context)
        {
            var diagnosticReporter = new DiagnosticReporter(context);

            try
            {
                // retrieve the populated receiver
                if (!(context.SyntaxContextReceiver is SyntaxReceiver receiver))
                {
                    return;
                }

                // If no project directory was detected then skip the generator.
                // This is most likely to happen when the project is empty and doesn't have any classes in it yet.
                if (string.IsNullOrEmpty(receiver.ProjectDirectory))
                {
                    return;
                }

                var semanticModelProvider = new SemanticModelProvider(context);
                if (receiver.StartupClasses.Count > 1)
                {
                    foreach (var startup in receiver.StartupClasses)
                    {
                        // If there are more than one startup class, report them as errors
                        diagnosticReporter.Report(Diagnostic.Create(DiagnosticDescriptors.MultipleStartupNotAllowed,
                                                                    Location.Create(startup.SyntaxTree, startup.Span),
                                                                    startup.SyntaxTree.FilePath));
                    }
                }

                var configureMethodModel = semanticModelProvider.GetConfigureMethodModel(receiver.StartupClasses.FirstOrDefault());

                var annotationReport = new AnnotationReport();

                var templateFinder = new CloudFormationTemplateFinder(_fileManager, _directoryManager);

                foreach (var lambdaMethod in receiver.LambdaMethods)
                {
                    var lambdaMethodModel = semanticModelProvider.GetMethodSemanticModel(lambdaMethod);

                    // Check for necessary references
                    if (lambdaMethodModel.HasAttribute(context, TypeFullNames.RestApiAttribute) ||
                        lambdaMethodModel.HasAttribute(context, TypeFullNames.HttpApiAttribute))
                    {
                        // Check for arbitrary type from "Amazon.Lambda.APIGatewayEvents"
                        if (context.Compilation.ReferencedAssemblyNames.FirstOrDefault(x => x.Name == "Amazon.Lambda.APIGatewayEvents") == null)
                        {
                            diagnosticReporter.Report(Diagnostic.Create(DiagnosticDescriptors.MissingDependencies,
                                                                        lambdaMethod.GetLocation(),
                                                                        "Amazon.Lambda.APIGatewayEvents"));
                        }
                    }

                    var model = LambdaFunctionModelBuilder.Build(lambdaMethodModel, configureMethodModel, context);

                    // If there are more than one event, report them as errors
                    if (model.LambdaMethod.Events.Count > 1)
                    {
                        foreach (var attribute in lambdaMethodModel.GetAttributes().Where(attribute => TypeFullNames.Events.Contains(attribute.AttributeClass.ToDisplayString())))
                        {
                            diagnosticReporter.Report(Diagnostic.Create(DiagnosticDescriptors.MultipleEventsNotSupported,
                                                                        Location.Create(attribute.ApplicationSyntaxReference.SyntaxTree, attribute.ApplicationSyntaxReference.Span),
                                                                        DiagnosticSeverity.Error));
                        }

                        // Skip multi-event lambda method from processing and check remaining lambda methods for diagnostics
                        continue;
                    }

                    var template   = new LambdaFunctionTemplate(model);
                    var sourceText = template.TransformText().ToEnvironmentLineEndings();
                    context.AddSource($"{model.GeneratedMethod.ContainingType.Name}.g.cs", SourceText.From(sourceText, Encoding.UTF8, SourceHashAlgorithm.Sha256));

                    // report every generated file to build output
                    diagnosticReporter.Report(Diagnostic.Create(DiagnosticDescriptors.CodeGeneration, Location.None, $"{model.GeneratedMethod.ContainingType.Name}.g.cs", sourceText));

                    annotationReport.LambdaFunctions.Add(model);
                }

                // Run the CloudFormation sync if any LambdaMethods exists. Also run if no LambdaMethods exists but there is a
                // CloudFormation template in case orphaned functions in the template need to be removed.
                // Both checks are required because if there is no template but there are LambdaMethods the CF template the template will be created.
                if (receiver.LambdaMethods.Any() || templateFinder.DoesCloudFormationTemplateExist(receiver.ProjectDirectory))
                {
                    annotationReport.CloudFormationTemplatePath = templateFinder.FindCloudFormationTemplate(receiver.ProjectDirectory);
                    annotationReport.ProjectRootDirectory       = receiver.ProjectDirectory;
                    var cloudFormationJsonWriter = new CloudFormationJsonWriter(_fileManager, _directoryManager, _jsonWriter, diagnosticReporter);
                    cloudFormationJsonWriter.ApplyReport(annotationReport);
                }
            }
            catch (Exception e)
            {
                // this is a generator failure, report this as error
                diagnosticReporter.Report(Diagnostic.Create(DiagnosticDescriptors.UnhandledException, Location.None, e.PrettyPrint()));
#if DEBUG
                throw;
#endif
            }
        }