Ejemplo n.º 1
0
        private void AnalyzeForSingletonTakesCustomOrTransient(
            IDiagnosticReporter diagnosticReporter
            )
        {
            if (diagnosticReporter is null)
            {
                throw new ArgumentNullException(nameof(diagnosticReporter));
            }

            foreach (var pair in this.Box.Groups.Shuffle())
            {
                var group = pair.Value;
                foreach (var bindingExtender in group.BindingExtenders)
                {
                    if (bindingExtender.BindingContainer.Scope.In(BindScopeEnum.Singleton))
                    {
                        if (Box.TryGetChildren(bindingExtender.BindingContainer, true, out var cpairs))
                        {
                            foreach (var cpair in cpairs)
                            {
                                var childExtender = cpair.BindingExtender;

                                if (childExtender.BindingContainer.Scope.In(BindScopeEnum.Custom, BindScopeEnum.Transient))
                                {
                                    diagnosticReporter.ReportWarning(
                                        $"Singleton-{childExtender.BindingContainer.Scope} relationship has been found.",
                                        $"Searching for singleton-{childExtender.BindingContainer.Scope} relationship has been found: singleton parent [{bindingExtender.BindingContainer.TargetRepresentation}] takes {childExtender.BindingContainer.Scope} child [{childExtender.BindingContainer.TargetRepresentation}]."
                                        );
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 2
0
 public EmbedderRewriter(SemanticModel model, EmbedderConfig config, IDiagnosticReporter reporter, CancellationToken cancellationToken)
 {
     this.model             = model;
     this.config            = config;
     this.reporter          = reporter;
     this.cancellationToken = cancellationToken;
 }
Ejemplo n.º 3
0
 /// <summary>
 /// Generated a code file from a RESX file.
 /// </summary>
 /// <param name="path">The path to the RESX file to generate from.</param>
 /// <param name="reporter">An object used to communicate diagnostics back to the caller.</param>
 /// <returns>The content of the generated code file.</returns>
 public string RunOnFile(string path, IDiagnosticReporter reporter)
 {
     using (var reader = new ResXResourceReader(path))
     {
         return(GenerateCodeForResx(reader, reporter));
     }
 }
 public SourceValidation(IEnumerable <IGroupValidationProvider> groupValidationProviders, IEnumerable <ITypeValidationProvider> typeValidationProviders, ConditionAnalyzer conditions, IDiagnosticReporter diagnostics)
 {
     _groupProviders    = groupValidationProviders;
     _typeProviders     = typeValidationProviders;
     _conditionAnalyzer = conditions;
     _diagnostics       = diagnostics;
 }
Ejemplo n.º 5
0
 public SyntaxVerification(IGenerationStartupServices startupServices, IEnumerable <IGenerationStartup> startups, ISourceMetaAnalysis analysis, IDiagnosticReporter diagnostic)
 {
     _startupServices = startupServices;
     _analysis        = analysis;
     _diagnostic      = diagnostic;
     _startups        = startups.ToList();
 }
 public CloudFormationJsonWriter(IFileManager fileManager, IDirectoryManager directoryManager, IJsonWriter jsonWriter, IDiagnosticReporter diagnosticReporter)
 {
     _fileManager        = fileManager;
     _directoryManager   = directoryManager;
     _jsonWriter         = jsonWriter;
     _diagnosticReporter = diagnosticReporter;
 }
        public ConventionalBindExpressionFactory(
            ITypeInfoContainer typeInfoContainer,
            ConstructorArgumentFromSyntaxExtractor extractor,
            ConstructorArgumentDetector constructorArgumentDetector,
            IDiagnosticReporter diagnosticReporter
            )
        {
            if (typeInfoContainer is null)
            {
                throw new ArgumentNullException(nameof(typeInfoContainer));
            }

            if (extractor is null)
            {
                throw new ArgumentNullException(nameof(extractor));
            }

            if (constructorArgumentDetector is null)
            {
                throw new ArgumentNullException(nameof(constructorArgumentDetector));
            }

            if (diagnosticReporter is null)
            {
                throw new ArgumentNullException(nameof(diagnosticReporter));
            }

            _typeInfoContainer           = typeInfoContainer;
            _extractor                   = extractor;
            _constructorArgumentDetector = constructorArgumentDetector;
            _diagnosticReporter          = diagnosticReporter;
        }
Ejemplo n.º 8
0
 /// <summary>
 /// Generated a code file from a RESX file.
 /// </summary>
 /// <param name="resxContent">The content of the RESX file to generate from.</param>
 /// <param name="reporter">An object used to communicate diagnostics back to the caller.</param>
 /// <returns>The content of the generated code file.</returns>
 public string RunOnContent(string resxContent, IDiagnosticReporter reporter)
 {
     using (var reader = ResXResourceReader.FromFileContents(resxContent))
     {
         return(GenerateCodeForResx(reader, reporter));
     }
 }
Ejemplo n.º 9
0
 /// <summary>
 /// Analyze the built tree and raise diagnostics if needed.
 /// </summary>
 public void Analyze(
     IDiagnosticReporter diagnosticReporter
     )
 {
     AnalyzeForCircularDependencies(diagnosticReporter);
     AnalyzeForMultipleUnconditionalChildExists(diagnosticReporter);
     AnalyzeForSingletonTakesCustomOrTransient(diagnosticReporter);
 }
Ejemplo n.º 10
0
 public SourcebergHostBuilderBase(ITypeSymbolProvider symbolProvider,
                                  ISourceAddition sourceAddition,
                                  IDiagnosticReporter <THostBuilder> diagnosticReporter)
 {
     _source        = sourceAddition;
     _reporter      = diagnosticReporter;
     SymbolProvider = symbolProvider;
     Resolvable     = symbolProvider.Source.GetAssemblySymbol(typeof(SourcebergAnalyzerAttribute).Assembly) is not null;
 }
Ejemplo n.º 11
0
        public CycleChecker(
            IDiagnosticReporter reporter
            )
        {
            if (reporter is null)
            {
                throw new ArgumentNullException(nameof(reporter));
            }

            _reporter = reporter;
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Generates a code file from the given RESX reader.
        /// </summary>
        /// <param name="reader">The resx reader the generated class is based on.</param>
        /// <param name="reporter">An object used to communicate diagnostics back to the caller.</param>
        /// <returns>The content of the generated code file.</returns>
        private string GenerateCodeForResx(ResXResourceReader reader, IDiagnosticReporter reporter)
        {
            if (reporter == null)
            {
                reporter = new ConsoleReporter();
            }

            ResourceTemplate template = BuildTemplate(reader, reporter);

            return(template.TransformText());
        }
        public DpdtInternalGenerator(
            IDiagnosticReporter diagnosticReporter
            )
        {
            if (diagnosticReporter is null)
            {
                throw new ArgumentNullException(nameof(diagnosticReporter));
            }

            _diagnosticReporter = diagnosticReporter;
        }
Ejemplo n.º 14
0
        public DpdtInternalGenerator(
            IDiagnosticReporter diagnosticReporter,
            bool doBeautify
            )
        {
            if (diagnosticReporter is null)
            {
                throw new ArgumentNullException(nameof(diagnosticReporter));
            }

            _diagnosticReporter = diagnosticReporter;
            _doBeautify         = doBeautify;
        }
Ejemplo n.º 15
0
 public EmbeddingContext(
     CSharpCompilation compilation,
     CSharpParseOptions parseOptions,
     IDiagnosticReporter reporter,
     EmbedderConfig config,
     CancellationToken cancellationToken = default)
 {
     Compilation       = compilation;
     ParseOptions      = parseOptions;
     Reporter          = reporter;
     Config            = config;
     CancellationToken = cancellationToken;
 }
Ejemplo n.º 16
0
        private void AnalyzeForCircularDependencies(
            IDiagnosticReporter diagnosticReporter
            )
        {
            if (diagnosticReporter is null)
            {
                throw new ArgumentNullException(nameof(diagnosticReporter));
            }

            new CycleChecker(
                diagnosticReporter
                )
            .CheckForCycles(Box);
        }
Ejemplo n.º 17
0
 public EmbeddedLoader(
     CSharpCompilation compilation,
     CSharpParseOptions parseOptions,
     IDiagnosticReporter reporter,
     ExpandConfig config,
     CancellationToken cancellationToken = default)
 {
     this.reporter = reporter;
     this.compilation = compilation;
     this.ConcurrentBuild = compilation.Options.ConcurrentBuild;
     this.parseOptions = parseOptions.WithDocumentationMode(DocumentationMode.Diagnose);
     this.config = config;
     this.cancellationToken = cancellationToken;
     var embeddedDatas = new AssemblyMetadataResolver(compilation).GetEmbeddedSourceFiles(cancellationToken);
     container = new SourceFileContainer(WithCheck(embeddedDatas));
 }
Ejemplo n.º 18
0
        public TimedCycleChecker(
            IDiagnosticReporter diagnosticReporter,
            ICycleChecker cycleChecker
            )
        {
            if (diagnosticReporter is null)
            {
                throw new ArgumentNullException(nameof(diagnosticReporter));
            }

            if (cycleChecker is null)
            {
                throw new ArgumentNullException(nameof(cycleChecker));
            }
            _diagnosticReporter = diagnosticReporter;
            _cycleChecker       = cycleChecker;
        }
Ejemplo n.º 19
0
        public TimedTypeScanner(
            IDiagnosticReporter diagnosticReporter,
            ITypeScanner typeScanner
            )
        {
            if (diagnosticReporter is null)
            {
                throw new ArgumentNullException(nameof(diagnosticReporter));
            }

            if (typeScanner is null)
            {
                throw new ArgumentNullException(nameof(typeScanner));
            }

            _diagnosticReporter = diagnosticReporter;
            _typeScanner        = typeScanner;
        }
Ejemplo n.º 20
0
        public TimedBindExtractor(
            IDiagnosticReporter diagnosticReporter,
            DefaultBindExtractor bindExtractor
            )
        {
            if (diagnosticReporter is null)
            {
                throw new System.ArgumentNullException(nameof(diagnosticReporter));
            }

            if (bindExtractor is null)
            {
                throw new System.ArgumentNullException(nameof(bindExtractor));
            }

            _diagnosticReporter = diagnosticReporter;
            _bindExtractor      = bindExtractor;
        }
Ejemplo n.º 21
0
        public DTimer(
            IDiagnosticReporter diagnosticReporter,
            string message
            )
        {
            if (diagnosticReporter is null)
            {
                throw new ArgumentNullException(nameof(diagnosticReporter));
            }

            if (message is null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            _diagnosticReporter = diagnosticReporter;
            _message            = message;

            _before = DateTime.Now;
            _after  = _before;
        }
Ejemplo n.º 22
0
        private void AnalyzeForMultipleUnconditionalChildExists(
            IDiagnosticReporter diagnosticReporter
            )
        {
            if (diagnosticReporter is null)
            {
                throw new ArgumentNullException(nameof(diagnosticReporter));
            }

            foreach (var pair in this.Box.Groups.Shuffle())
            {
                var group = pair.Value;
                foreach (var bindingExtender in group.BindingExtenders)
                {
                    if (Box.TryGetChildren(bindingExtender.BindingContainer, true, out var cpairs))
                    {
                        var cgroups = (
                            from cpair in cpairs
                            where !cpair.ConstructorArgument.DefineInBindNode
                            group cpair by cpair.ConstructorArgument.Name into cgroup
                            select cgroup
                            ).ToList();

                        foreach (var cgroup in cgroups)
                        {
                            var cgpairs            = cgroup.ToList();
                            var unconditionalCount = cgpairs.Count(p => !p.BindingExtender.BindingContainer.IsConditional);
                            if (unconditionalCount > 1)
                            {
                                diagnosticReporter.ReportError(
                                    $"Multiple unconditional children has been found.",
                                    $"There are multiple unconditional children for [{bindingExtender.BindingContainer.TargetRepresentation}] and its constructor argument [{cgroup.Key}]."
                                    );
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 23
0
        public EmbeddingResolver(
            CSharpCompilation compilation,
            CSharpParseOptions parseOptions,
            IDiagnosticReporter reporter,
            EmbedderConfig config,
            CancellationToken cancellationToken = default)
        {
            var specificDiagnosticOptions = new Dictionary <string, ReportDiagnostic>
            {
                { "CS8019", ReportDiagnostic.Warn },
                { "CS0105", ReportDiagnostic.Warn },
            };
            var opts = compilation.Options
                       .WithSpecificDiagnosticOptions(specificDiagnosticOptions);

            this.ConcurrentBuild   = opts.ConcurrentBuild;
            this.parseOptions      = parseOptions.WithDocumentationMode(DocumentationMode.Diagnose);
            this.compilation       = compilation.WithOptions(opts);
            this.reporter          = reporter;
            this.config            = config;
            this.cancellationToken = cancellationToken;
        }
Ejemplo n.º 24
0
 public IndexOrderSelector(IDiagnosticReporter diagnostic, LayoutOrder order)
 {
     _declaredOrder = order;
     _diagnostic    = diagnostic;
 }
 public SourcebergGeneratorHostBuilder(ITypeSymbolProvider symbolProvider,
                                       ISourceAddition sourceAddition,
                                       IDiagnosticReporter <SourcebergGeneratorHostBuilder> diagnosticReporter)
     : base(symbolProvider, sourceAddition, diagnosticReporter)
 {
 }
        private static void EvaluateCondition(MemberMetaInfo targetMember, Location attributeLocation, ConditionExpression conditions, IDiagnosticReporter reporter)
        {
            switch (conditions.Condition)
            {
            // Since all objects contain Equals(object), this is the least we call back into
            // TODO : Note we might still want to warn user about that a returning type doesn't contain a correct signature
            // For example : If we try to evaluate the member equals to true,
            // even if the member returns a type that is obvious that wouldn't evaluate with true, then it would still evaluate, but just to false
            case Condition.Equal:
            case Condition.NotEqual:
                break;

            // In these cases we need to check if either the return type implements IComparable or IComparable<T>
            // We might also want to warn about boxing issue if the given compared type is a valuetype and returning type only has IComparable though
            case Condition.GreaterThan:
            case Condition.GreaterThanOrEqual:
            case Condition.LessThan:
            case Condition.LessThanOrEqual: {
                // Valid compare types
                // Value Types : bool, char, byte, sbyte, ushort, short, int, uint, ulong, long, float, double
                // Ref Types : Types (but why), string (but why)

                // We currently consider 'null' to be not comparable, so there's this
                if (conditions.ComparedValue is null)
                {
                    reporter.ReportDiagnostic(DiagnosticHelper.CompareValueInvalid(conditions, attributeLocation));
                    break;
                }

                // Valid implicit conversion for IComparable is matched with C# specification :
                // https://docs.microsoft.com/dotnet/csharp/language-reference/builtin-types/numeric-conversions
                //
                // [Possible Improvement]
                // TODO : We also don't support even if IComparation<T>'s T is implicit convertible from the compared type
                // We only support when it's primitive is implicitly convertible (supported by C# specification) to another primitive type
                // So types that only return IComparable<long> would work well with int numbers
                //
                // This can be done using a compilation extensions provided out of the box:
                // https://docs.microsoft.com/dotnet/api/microsoft.codeanalysis.csharp.csharpextensions.classifyconversion

                var returnType   = targetMember.ReturnType !;
                var comparedType = conditions.ComparedValue.GetType();

                if (!returnType.Implements(typeof(IComparable)) || !returnType.Implements(typeof(IComparable <>)))
                {
                    reporter.ReportDiagnostic(DiagnosticHelper.ReturnTypeNotComparable(targetMember, conditions.Condition, attributeLocation));
                    break;
                }
                if (!returnType.Implements(typeof(IComparable <>).MakeGenericType(comparedType)) ||
                    !returnType.GetInterfaces(typeof(IComparable <>)).Any(x => x.IsImplicitConvertibleFrom(comparedType)))
                {
                    reporter.ReportDiagnostic(DiagnosticHelper.ReturnTypeInvalidComparable(targetMember, comparedType, attributeLocation));
                    break;
                }
                break;
            }

            // Since all objects can be evaluated with is operator
            case Condition.IsTypeOf:
            case Condition.IsNotTypeOf: {
                if (!(conditions.ComparedValue is null) && conditions.ComparedValue.GetType() != typeof(Type))
                {
                    reporter.ReportDiagnostic(DiagnosticHelper.CompareValueInvalid(conditions, attributeLocation, ", it should be only a kind of Type and none other"));
                }
                break;
            }

            default:
                reporter.ReportDiagnostic(DiagnosticHelper.InvalidCondition(conditions.Condition, attributeLocation));
                break;
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Builds a code file template from the given RESX reader.
        /// </summary>
        /// <param name="reader">The resx reader the generated class is based on.</param>
        /// <param name="reporter">An object used to communicate diagnostics back to the caller.</param>
        /// <param name="typeResolver">An object used to resolve types by their name.</param>
        /// <returns>The completed code file template.</returns>
        private ResourceTemplate BuildTemplate(ResXResourceReader reader, IDiagnosticReporter reporter, ITypeResolutionService typeResolver = null)
        {
            var template = new ResourceTemplate
            {
                ClassName    = ClassName,
                Namespace    = Namespace,
                IsPublic     = IsPublic,
                ResourceName = Namespace + "." + ClassName,
            };

            reader.UseResXDataNodes = true;
            foreach (DictionaryEntry entry in reader)
            {
                if (entry.Value is ResXDataNode resxNode)
                {
                    try
                    {
                        string typeName = resxNode.GetValueTypeName(typeResolver);

                        bool isString = (typeName.Contains(typeof(string).FullName) == true);

                        if (isString &&
                            resxNode.FileRef == null)
                        {
                            string str = (string)resxNode.GetValue(typeResolver);
                            template.StringResources.Add(
                                new StringResource(resxNode.Name, str, resxNode.Comment)
                                );
                        }
                        else if (isString)
                        {
                            template.TextFileResources.Add(
                                new TextFileResource(resxNode.Name, resxNode.Comment)
                                );
                        }
                        else
                        {
                            string fullTypeName = typeName.Substring(0, typeName.IndexOf(','));

                            if (fullTypeName == typeof(MemoryStream).FullName)
                            {
                                template.StreamResources.Add(
                                    new StreamResource(resxNode.Name, resxNode.Comment)
                                    );
                            }
                            else
                            {
                                template.ObjectResources.Add(
                                    new ObjectResource(resxNode.Name, fullTypeName, resxNode.Comment)
                                    );
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteLine(
                            $"Caught exception while reading resource {entry.Key}: " + ex,
                            nameof(BetterResourceGenerator)
                            );

                        reporter.Report(
                            DiagnosticSeverity.Error,
                            $"Discarded resource {entry.Key} due to error: {ex.Message}."
                            );
                    }
                }
                else
                {
                    reporter.Report(
                        DiagnosticSeverity.Warning,
                        $"Discarded resource {entry.Key} as it is not a ResXDataNode."
                        );
                }
            }

            return(template);
        }
        public void ValidateExternal(TypeMetaSelection selection, IGroupValidationProvider groupValidation, IDiagnosticReporter reporter)
        {
            var groupValidator = new FluentTypeValidator(selection, _conditionAnalyzer);

            groupValidation.ConfigureValidation(groupValidator);
            groupValidator.Validate(reporter);
        }
        public void ValidateExternal(NamedTypeMetaInfo type, ITypeValidationProvider typeValidation, IDiagnosticReporter reporter)
        {
            var typeValidator = new FluentMemberValidator(TypeMetaSelection.Any(type), _conditionAnalyzer);

            typeValidation.ConfigureValidation(typeValidator);
            typeValidator.Validate(reporter);
        }
Ejemplo n.º 30
0
 public InjectionWorkspace(IDiagnosticReporter diagnosticReporter)
 {
     this.diagnosticReporter         = diagnosticReporter;
     diagnosticTimer                 = new SlidingTimer(TimeSpan.FromSeconds(1));
     diagnosticTimer.TimeoutElapsed += HandleDiagnosticUpdateTimeout;
 }