diff --git a/BenchmarkDotNet.sln.DotSettings b/BenchmarkDotNet.sln.DotSettings index 7f5e287ce3..b81d1cbadc 100644 --- a/BenchmarkDotNet.sln.DotSettings +++ b/BenchmarkDotNet.sln.DotSettings @@ -12,12 +12,10 @@ DO_NOT_SHOW True - True True - DO_NOT_SHOW DO_NOT_SHOW DO_NOT_SHOW @@ -25,6 +23,10 @@ DO_NOT_SHOW DO_NOT_SHOW + DO_NOT_SHOW + DO_NOT_SHOW + DO_NOT_SHOW + DO_NOT_SHOW True NotRequired ExpressionBody diff --git a/src/BenchmarkDotNet/Analysers/AnalyserBase.cs b/src/BenchmarkDotNet/Analysers/AnalyserBase.cs index 1acf5cf1d1..81129dee04 100644 --- a/src/BenchmarkDotNet/Analysers/AnalyserBase.cs +++ b/src/BenchmarkDotNet/Analysers/AnalyserBase.cs @@ -18,11 +18,11 @@ public IEnumerable Analyse(Summary summary) yield return conclusion; } - public virtual IEnumerable AnalyseSummary(Summary summary) => Enumerable.Empty(); - public virtual IEnumerable AnalyseReport(BenchmarkReport report, Summary summary) => Enumerable.Empty(); + protected virtual IEnumerable AnalyseSummary(Summary summary) => Enumerable.Empty(); + protected virtual IEnumerable AnalyseReport(BenchmarkReport report, Summary summary) => Enumerable.Empty(); - public Conclusion CreateHint(string message, [CanBeNull] BenchmarkReport report = null) => Conclusion.CreateHint(Id, message, report); - public Conclusion CreateWarning(string message, [CanBeNull] BenchmarkReport report = null) => Conclusion.CreateWarning(Id, message, report); - public Conclusion CreateError(string message, [CanBeNull] BenchmarkReport report = null) => Conclusion.CreateError(Id, message, report); + protected Conclusion CreateHint(string message, [CanBeNull] BenchmarkReport report = null) => Conclusion.CreateHint(Id, message, report); + protected Conclusion CreateWarning(string message, [CanBeNull] BenchmarkReport report = null) => Conclusion.CreateWarning(Id, message, report); + protected Conclusion CreateError(string message, [CanBeNull] BenchmarkReport report = null) => Conclusion.CreateError(Id, message, report); } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Analysers/EnvironmentAnalyser.cs b/src/BenchmarkDotNet/Analysers/EnvironmentAnalyser.cs index d754bcf7a9..7b007327fb 100644 --- a/src/BenchmarkDotNet/Analysers/EnvironmentAnalyser.cs +++ b/src/BenchmarkDotNet/Analysers/EnvironmentAnalyser.cs @@ -18,13 +18,13 @@ private EnvironmentAnalyser() { } - public override IEnumerable AnalyseReport(BenchmarkReport report, Summary summary) + protected override IEnumerable AnalyseReport(BenchmarkReport report, Summary summary) { if (report.BenchmarkCase.Descriptor.Type.GetTypeInfo().Assembly.IsJitOptimizationDisabled().IsTrue()) yield return CreateWarning("Benchmark was built without optimization enabled (most probably a DEBUG configuration). Please, build it in RELEASE.", report); } - public override IEnumerable AnalyseSummary(Summary summary) + protected override IEnumerable AnalyseSummary(Summary summary) { if (summary.HostEnvironmentInfo.HasAttachedDebugger) yield return CreateWarning("Benchmark was executed with attached debugger"); diff --git a/src/BenchmarkDotNet/Analysers/MinIterationTimeAnalyser.cs b/src/BenchmarkDotNet/Analysers/MinIterationTimeAnalyser.cs index a696aaffea..c3b0b55e50 100644 --- a/src/BenchmarkDotNet/Analysers/MinIterationTimeAnalyser.cs +++ b/src/BenchmarkDotNet/Analysers/MinIterationTimeAnalyser.cs @@ -18,7 +18,7 @@ private MinIterationTimeAnalyser() { } - public override IEnumerable AnalyseReport(BenchmarkReport report, Summary summary) + protected override IEnumerable AnalyseReport(BenchmarkReport report, Summary summary) { var target = report.AllMeasurements.Where(m => m.Is(IterationMode.Workload, IterationStage.Actual)).ToArray(); if (target.IsEmpty()) diff --git a/src/BenchmarkDotNet/Analysers/MultimodalDistributionAnalyzer.cs b/src/BenchmarkDotNet/Analysers/MultimodalDistributionAnalyzer.cs index ee80d9e88c..08aeb824eb 100644 --- a/src/BenchmarkDotNet/Analysers/MultimodalDistributionAnalyzer.cs +++ b/src/BenchmarkDotNet/Analysers/MultimodalDistributionAnalyzer.cs @@ -15,7 +15,7 @@ private MultimodalDistributionAnalyzer() { } public override string Id => "MultimodalDistribution"; - public override IEnumerable AnalyseReport(BenchmarkReport report, Summary summary) + protected override IEnumerable AnalyseReport(BenchmarkReport report, Summary summary) { var statistics = report.ResultStatistics; if (statistics == null || statistics.N < EngineResolver.DefaultMinWorkloadIterationCount) diff --git a/src/BenchmarkDotNet/Analysers/OutliersAnalyser.cs b/src/BenchmarkDotNet/Analysers/OutliersAnalyser.cs index c7ff718bbe..9e17c3101d 100644 --- a/src/BenchmarkDotNet/Analysers/OutliersAnalyser.cs +++ b/src/BenchmarkDotNet/Analysers/OutliersAnalyser.cs @@ -15,7 +15,7 @@ public class OutliersAnalyser : AnalyserBase private OutliersAnalyser() { } - public override IEnumerable AnalyseReport(BenchmarkReport report, Summary summary) + protected override IEnumerable AnalyseReport(BenchmarkReport report, Summary summary) { var workloadActual = report.AllMeasurements.Where(m => m.Is(IterationMode.Workload, IterationStage.Actual)).ToArray(); if (workloadActual.IsEmpty()) diff --git a/src/BenchmarkDotNet/Analysers/RuntimeErrorAnalyser.cs b/src/BenchmarkDotNet/Analysers/RuntimeErrorAnalyser.cs index 11877dcff3..0955b22a4a 100644 --- a/src/BenchmarkDotNet/Analysers/RuntimeErrorAnalyser.cs +++ b/src/BenchmarkDotNet/Analysers/RuntimeErrorAnalyser.cs @@ -14,7 +14,7 @@ private RuntimeErrorAnalyser() { } - public override IEnumerable AnalyseReport(BenchmarkReport report, Summary summary) + protected override IEnumerable AnalyseReport(BenchmarkReport report, Summary summary) { var errors = report.ExecuteResults.SelectMany(r => r.Data) .Union(report.ExecuteResults.SelectMany(r => r.ExtraOutput)) diff --git a/src/BenchmarkDotNet/Attributes/ArgumentsAttribute.cs b/src/BenchmarkDotNet/Attributes/ArgumentsAttribute.cs index d2a421dadc..99836c4b93 100644 --- a/src/BenchmarkDotNet/Attributes/ArgumentsAttribute.cs +++ b/src/BenchmarkDotNet/Attributes/ArgumentsAttribute.cs @@ -5,7 +5,7 @@ namespace BenchmarkDotNet.Attributes [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class ArgumentsAttribute : Attribute { - public object[] Values { get; private set; } + public object[] Values { get; } // CLS-Compliant Code requires a constructor without an array in the argument list public ArgumentsAttribute() diff --git a/src/BenchmarkDotNet/Attributes/ArtifactsPathAttribute.cs b/src/BenchmarkDotNet/Attributes/ArtifactsPathAttribute.cs index d3f79ca606..5b28276de4 100644 --- a/src/BenchmarkDotNet/Attributes/ArtifactsPathAttribute.cs +++ b/src/BenchmarkDotNet/Attributes/ArtifactsPathAttribute.cs @@ -1,8 +1,10 @@ using System; using BenchmarkDotNet.Configs; +using JetBrains.Annotations; namespace BenchmarkDotNet.Attributes { + [PublicAPI] public class ArtifactsPathAttribute : Attribute, IConfigSource { public string Value { get; } diff --git a/src/BenchmarkDotNet/Attributes/Exporters/JsonExporterAttribute.cs b/src/BenchmarkDotNet/Attributes/Exporters/JsonExporterAttribute.cs index f0fc8f9b7e..dee4da2dd5 100644 --- a/src/BenchmarkDotNet/Attributes/Exporters/JsonExporterAttribute.cs +++ b/src/BenchmarkDotNet/Attributes/Exporters/JsonExporterAttribute.cs @@ -7,7 +7,7 @@ namespace BenchmarkDotNet.Attributes [AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true)] public class JsonExporterAttribute : ExporterConfigBaseAttribute { - protected JsonExporterAttribute(IExporter exporter) : base(exporter) + private JsonExporterAttribute(IExporter exporter) : base(exporter) { } diff --git a/src/BenchmarkDotNet/Attributes/Exporters/XmlExporterAttribute.cs b/src/BenchmarkDotNet/Attributes/Exporters/XmlExporterAttribute.cs index 8c4a0ccc41..7c098bf434 100644 --- a/src/BenchmarkDotNet/Attributes/Exporters/XmlExporterAttribute.cs +++ b/src/BenchmarkDotNet/Attributes/Exporters/XmlExporterAttribute.cs @@ -7,7 +7,7 @@ namespace BenchmarkDotNet.Attributes [AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true)] public class XmlExporterAttribute : ExporterConfigBaseAttribute { - public XmlExporterAttribute(IExporter exporter) : base(exporter) + private XmlExporterAttribute(IExporter exporter) : base(exporter) { } diff --git a/src/BenchmarkDotNet/Attributes/Jobs/JobConfigbaseAttribute.cs b/src/BenchmarkDotNet/Attributes/Jobs/JobConfigbaseAttribute.cs index 3840404d5e..fb394813fa 100644 --- a/src/BenchmarkDotNet/Attributes/Jobs/JobConfigbaseAttribute.cs +++ b/src/BenchmarkDotNet/Attributes/Jobs/JobConfigbaseAttribute.cs @@ -9,8 +9,8 @@ public class JobConfigBaseAttribute : Attribute, IConfigSource { // CLS-Compliant Code requires a constructor which use only CLS-compliant types public JobConfigBaseAttribute() => Config = ManualConfig.CreateEmpty(); - - public JobConfigBaseAttribute(Job job) => Config = ManualConfig.CreateEmpty().With(job); + + protected JobConfigBaseAttribute(Job job) => Config = ManualConfig.CreateEmpty().With(job); public IConfig Config { get; } } diff --git a/src/BenchmarkDotNet/Attributes/KeepBenchmarkFilesAttribute.cs b/src/BenchmarkDotNet/Attributes/KeepBenchmarkFilesAttribute.cs index 8ef24024ab..4616ef62ed 100644 --- a/src/BenchmarkDotNet/Attributes/KeepBenchmarkFilesAttribute.cs +++ b/src/BenchmarkDotNet/Attributes/KeepBenchmarkFilesAttribute.cs @@ -5,12 +5,10 @@ namespace BenchmarkDotNet.Attributes { public class KeepBenchmarkFilesAttribute : Attribute, IConfigSource { - public bool Value { get; } public IConfig Config { get; } public KeepBenchmarkFilesAttribute(bool value = true) { - Value = value; Config = ManualConfig.CreateEmpty().KeepBenchmarkFiles(value); } } diff --git a/src/BenchmarkDotNet/Attributes/ParamsAttribute.cs b/src/BenchmarkDotNet/Attributes/ParamsAttribute.cs index 29bdf2a1e5..f8974e1248 100644 --- a/src/BenchmarkDotNet/Attributes/ParamsAttribute.cs +++ b/src/BenchmarkDotNet/Attributes/ParamsAttribute.cs @@ -5,7 +5,7 @@ namespace BenchmarkDotNet.Attributes [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class ParamsAttribute : Attribute { - public object[] Values { get; private set; } + public object[] Values { get; } // CLS-Compliant Code requires a constructor without an array in the argument list public ParamsAttribute() diff --git a/src/BenchmarkDotNet/Characteristics/Characteristic.cs b/src/BenchmarkDotNet/Characteristics/Characteristic.cs index bc21a0421a..b83aad315a 100644 --- a/src/BenchmarkDotNet/Characteristics/Characteristic.cs +++ b/src/BenchmarkDotNet/Characteristics/Characteristic.cs @@ -82,7 +82,7 @@ protected Characteristic( public Type DeclaringType { get; } - public object FallbackValue { get; } + private object FallbackValue { get; } public object this[CharacteristicObject obj] { diff --git a/src/BenchmarkDotNet/Characteristics/CharacteristicHelper.cs b/src/BenchmarkDotNet/Characteristics/CharacteristicHelper.cs index e6e947d13c..3dcce84b79 100644 --- a/src/BenchmarkDotNet/Characteristics/CharacteristicHelper.cs +++ b/src/BenchmarkDotNet/Characteristics/CharacteristicHelper.cs @@ -12,12 +12,11 @@ public static class CharacteristicHelper internal static bool IsCharacteristicObjectSubclass(Type type) => type.GetTypeInfo().IsSubclassOf(typeof(CharacteristicObject)); - internal static bool IsCharacteristicSubclass(Type type) => + private static bool IsCharacteristicSubclass(Type type) => type.GetTypeInfo().IsSubclassOf(typeof(Characteristic)); private static Characteristic AssertHasValue(MemberInfo member, Characteristic value) { - // ReSharper disable once PossibleNullReferenceException if (value == null) throw new ArgumentException( $"The value of {member.DeclaringType.Name}.{member.Name} is null"); diff --git a/src/BenchmarkDotNet/Characteristics/CharacteristicObject.cs b/src/BenchmarkDotNet/Characteristics/CharacteristicObject.cs index f6299814c7..521e56ec08 100644 --- a/src/BenchmarkDotNet/Characteristics/CharacteristicObject.cs +++ b/src/BenchmarkDotNet/Characteristics/CharacteristicObject.cs @@ -49,7 +49,8 @@ protected CharacteristicObject(string id) : this() #endregion #region Assertions - protected void AssertNotFrozen() + + private void AssertNotFrozen() { if (Frozen) { @@ -57,7 +58,7 @@ protected void AssertNotFrozen() } } - protected void AssertIsRoot() + private void AssertIsRoot() { if (Owner != null) { @@ -67,13 +68,13 @@ protected void AssertIsRoot() } } - protected void AssertIsNonFrozenRoot() + private void AssertIsNonFrozenRoot() { AssertNotFrozen(); AssertIsRoot(); } - protected void AssertIsAssignable(Characteristic characteristic, object value) + private static void AssertIsAssignable(Characteristic characteristic, object value) { if (ReferenceEquals(value, Characteristic.EmptyValue) || ReferenceEquals(value, null)) { @@ -91,7 +92,8 @@ protected void AssertIsAssignable(Characteristic characteristic, object value) #endregion #region Properties - protected CharacteristicObject Owner => owner; + + private CharacteristicObject Owner => owner; protected CharacteristicObject OwnerOrSelf => owner ?? this; diff --git a/src/BenchmarkDotNet/Characteristics/CharacteristicObject`1.cs b/src/BenchmarkDotNet/Characteristics/CharacteristicObject`1.cs index cda74afdb9..9723255b46 100644 --- a/src/BenchmarkDotNet/Characteristics/CharacteristicObject`1.cs +++ b/src/BenchmarkDotNet/Characteristics/CharacteristicObject`1.cs @@ -1,4 +1,6 @@ -namespace BenchmarkDotNet.Characteristics +using JetBrains.Annotations; + +namespace BenchmarkDotNet.Characteristics { public abstract class CharacteristicObject : CharacteristicObject where T : CharacteristicObject, new() @@ -9,6 +11,7 @@ protected CharacteristicObject(string id) : base(id) { } public new T Apply(CharacteristicObject other) => (T)ApplyCore(other); + [PublicAPI] public T Apply(params CharacteristicObject[] others) { var result = this; diff --git a/src/BenchmarkDotNet/Characteristics/Characteristic`1.cs b/src/BenchmarkDotNet/Characteristics/Characteristic`1.cs index 52fb34ac53..bd4fb78946 100644 --- a/src/BenchmarkDotNet/Characteristics/Characteristic`1.cs +++ b/src/BenchmarkDotNet/Characteristics/Characteristic`1.cs @@ -17,9 +17,9 @@ internal Characteristic( FallbackValue = fallbackValue; } - public Func Resolver { get; } + private Func Resolver { get; } - public new T FallbackValue { get; } + public T FallbackValue { get; } public new T this[CharacteristicObject obj] { diff --git a/src/BenchmarkDotNet/Columns/BaselineScaledColumn.cs b/src/BenchmarkDotNet/Columns/BaselineScaledColumn.cs index d8671bc541..7ba1b79677 100644 --- a/src/BenchmarkDotNet/Columns/BaselineScaledColumn.cs +++ b/src/BenchmarkDotNet/Columns/BaselineScaledColumn.cs @@ -87,7 +87,7 @@ public string GetValue(Summary summary, BenchmarkCase benchmarkCase) } } - public bool IsNonBaselinesPrecise(Summary summary, Statistics baselineStat, BenchmarkCase benchmarkCase) + private static bool IsNonBaselinesPrecise(Summary summary, Statistics baselineStat, BenchmarkCase benchmarkCase) { string logicalGroupKey = summary.GetLogicalGroupKey(benchmarkCase); var nonBaselines = summary.BenchmarksCases diff --git a/src/BenchmarkDotNet/Columns/DefaultColumnProvider.cs b/src/BenchmarkDotNet/Columns/DefaultColumnProvider.cs index bada6bd6a6..a7d0133705 100644 --- a/src/BenchmarkDotNet/Columns/DefaultColumnProvider.cs +++ b/src/BenchmarkDotNet/Columns/DefaultColumnProvider.cs @@ -4,16 +4,17 @@ using BenchmarkDotNet.Extensions; using BenchmarkDotNet.Mathematics; using BenchmarkDotNet.Reports; +using JetBrains.Annotations; namespace BenchmarkDotNet.Columns { public static class DefaultColumnProviders { - public static readonly IColumnProvider Descriptor = new DescriptorColumnProvider(); - public static readonly IColumnProvider Job = new JobColumnProvider(); - public static readonly IColumnProvider Statistics = new StatisticsColumnProvider(); - public static readonly IColumnProvider Params = new ParamsColumnProvider(); - public static readonly IColumnProvider Diagnosers = new DiagnosersColumnProvider(); + [PublicAPI] public static readonly IColumnProvider Descriptor = new DescriptorColumnProvider(); + [PublicAPI] public static readonly IColumnProvider Job = new JobColumnProvider(); + [PublicAPI] public static readonly IColumnProvider Statistics = new StatisticsColumnProvider(); + [PublicAPI] public static readonly IColumnProvider Params = new ParamsColumnProvider(); + [PublicAPI] public static readonly IColumnProvider Diagnosers = new DiagnosersColumnProvider(); public static readonly IColumnProvider[] Instance = { Descriptor, Job, Statistics, Params, Diagnosers }; diff --git a/src/BenchmarkDotNet/Columns/JobCharacteristicColumn.cs b/src/BenchmarkDotNet/Columns/JobCharacteristicColumn.cs index 2512c7ef0d..5c14a0a978 100644 --- a/src/BenchmarkDotNet/Columns/JobCharacteristicColumn.cs +++ b/src/BenchmarkDotNet/Columns/JobCharacteristicColumn.cs @@ -14,7 +14,7 @@ public class JobCharacteristicColumn : IColumn private readonly Characteristic characteristic; - public JobCharacteristicColumn(Characteristic characteristic) + private JobCharacteristicColumn(Characteristic characteristic) { this.characteristic = characteristic; Id = "Job." + characteristic.Id; diff --git a/src/BenchmarkDotNet/Columns/SizeUnit.cs b/src/BenchmarkDotNet/Columns/SizeUnit.cs index faec4c2840..de029bae52 100644 --- a/src/BenchmarkDotNet/Columns/SizeUnit.cs +++ b/src/BenchmarkDotNet/Columns/SizeUnit.cs @@ -1,12 +1,15 @@ -using System.Linq; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using JetBrains.Annotations; namespace BenchmarkDotNet.Columns { + [SuppressMessage("ReSharper", "InconsistentNaming")] // We want to use "KB", "MB", "GB", "TB" public class SizeUnit { - public string Name { get; } - public string Description { get; } - public long ByteAmount { get; } + [PublicAPI] public string Name { get; } + [PublicAPI] public string Description { get; } + [PublicAPI] public long ByteAmount { get; } public SizeUnit(string name, string description, long byteAmount) { @@ -15,13 +18,14 @@ public SizeUnit(string name, string description, long byteAmount) ByteAmount = byteAmount; } - public const long BytesInKiloByte = 1024L; // this value MUST NOT be changed - public static readonly SizeUnit B = new SizeUnit("B", "Byte", 1L); - public static readonly SizeUnit KB = new SizeUnit("KB", "Kilobyte", BytesInKiloByte); - public static readonly SizeUnit MB = new SizeUnit("MB", "Megabyte", BytesInKiloByte * BytesInKiloByte); - public static readonly SizeUnit GB = new SizeUnit("GB", "Gigabyte", BytesInKiloByte * BytesInKiloByte * BytesInKiloByte); - public static readonly SizeUnit TB = new SizeUnit("TB", "Terabyte", BytesInKiloByte * BytesInKiloByte * BytesInKiloByte * BytesInKiloByte); - public static readonly SizeUnit[] All = { B, KB, MB, GB, TB }; + private const long BytesInKiloByte = 1024L; // this value MUST NOT be changed + + [PublicAPI] public static readonly SizeUnit B = new SizeUnit("B", "Byte", 1L); + [PublicAPI] public static readonly SizeUnit KB = new SizeUnit("KB", "Kilobyte", BytesInKiloByte); + [PublicAPI] public static readonly SizeUnit MB = new SizeUnit("MB", "Megabyte", BytesInKiloByte * BytesInKiloByte); + [PublicAPI] public static readonly SizeUnit GB = new SizeUnit("GB", "Gigabyte", BytesInKiloByte * BytesInKiloByte * BytesInKiloByte); + [PublicAPI] public static readonly SizeUnit TB = new SizeUnit("TB", "Terabyte", BytesInKiloByte * BytesInKiloByte * BytesInKiloByte * BytesInKiloByte); + [PublicAPI] public static readonly SizeUnit[] All = { B, KB, MB, GB, TB }; public static SizeUnit GetBestSizeUnit(params long[] values) { diff --git a/src/BenchmarkDotNet/Columns/StatisticColumn.cs b/src/BenchmarkDotNet/Columns/StatisticColumn.cs index 5afc11c868..a85f9bb0b7 100644 --- a/src/BenchmarkDotNet/Columns/StatisticColumn.cs +++ b/src/BenchmarkDotNet/Columns/StatisticColumn.cs @@ -9,7 +9,7 @@ namespace BenchmarkDotNet.Columns { public class StatisticColumn : IColumn { - public enum Priority + private enum Priority { Main, Quartile, diff --git a/src/BenchmarkDotNet/Configs/ManualConfig.cs b/src/BenchmarkDotNet/Configs/ManualConfig.cs index 36d7c7b935..05a87aff6f 100644 --- a/src/BenchmarkDotNet/Configs/ManualConfig.cs +++ b/src/BenchmarkDotNet/Configs/ManualConfig.cs @@ -13,6 +13,7 @@ using BenchmarkDotNet.Order; using BenchmarkDotNet.Reports; using BenchmarkDotNet.Validators; +using JetBrains.Annotations; namespace BenchmarkDotNet.Configs { @@ -43,15 +44,11 @@ public class ManualConfig : IConfig public IEnumerable GetLogicalGroupRules() => logicalGroupRules; - public ConfigUnionRule UnionRule { get; set; } = ConfigUnionRule.Union; - - public bool KeepBenchmarkFiles { get; set; } - - public bool SummaryPerType { get; set; } = true; - - public string ArtifactsPath { get; set; } - - public Encoding Encoding { get; set; } + [PublicAPI] public ConfigUnionRule UnionRule { get; set; } = ConfigUnionRule.Union; + [PublicAPI] public bool KeepBenchmarkFiles { get; set; } + [PublicAPI] public bool SummaryPerType { get; set; } = true; + [PublicAPI] public string ArtifactsPath { get; set; } + [PublicAPI] public Encoding Encoding { get; set; } public void Add(params IColumn[] newColumns) => columnProviders.AddRange(newColumns.Select(c => c.ToProvider())); public void Add(params IColumnProvider[] newColumnProviders) => columnProviders.AddRange(newColumnProviders); @@ -68,6 +65,7 @@ public class ManualConfig : IConfig public void Set(Encoding encoding) => Encoding = encoding; public void Add(params BenchmarkLogicalGroupRule[] rules) => logicalGroupRules.AddRange(rules); + [PublicAPI] public void Add(IConfig config) { columnProviders.AddRange(config.GetColumnProviders()); diff --git a/src/BenchmarkDotNet/ConsoleArguments/CommandLineOptions.cs b/src/BenchmarkDotNet/ConsoleArguments/CommandLineOptions.cs index 560604d8d7..cae9101a03 100644 --- a/src/BenchmarkDotNet/ConsoleArguments/CommandLineOptions.cs +++ b/src/BenchmarkDotNet/ConsoleArguments/CommandLineOptions.cs @@ -1,11 +1,15 @@ using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.IO; using BenchmarkDotNet.Mathematics; using CommandLine; using CommandLine.Text; +using JetBrains.Annotations; namespace BenchmarkDotNet.ConsoleArguments { + [SuppressMessage("ReSharper", "MemberCanBePrivate.Global")] + [SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Global")] public class CommandLineOptions { [Option('j', "job", Required = false, Default = "Default", HelpText = "Dry/Short/Medium/Long or Default")] @@ -54,6 +58,7 @@ public class CommandLineOptions public bool Join { get; set; } [Usage(ApplicationAlias = "")] + [PublicAPI] public static IEnumerable Examples { get diff --git a/src/BenchmarkDotNet/ConsoleArguments/LoggerWrapper.cs b/src/BenchmarkDotNet/ConsoleArguments/LoggerWrapper.cs index 6f5f672775..a7e4cd50a0 100644 --- a/src/BenchmarkDotNet/ConsoleArguments/LoggerWrapper.cs +++ b/src/BenchmarkDotNet/ConsoleArguments/LoggerWrapper.cs @@ -10,7 +10,7 @@ internal class LoggerWrapper : TextWriter public LoggerWrapper(ILogger logger) => this.logger = logger; - public override Encoding Encoding { get; } + public override Encoding Encoding { get; } = Encoding.ASCII; public override void Write(string value) => logger.WriteInfo(value); } diff --git a/src/BenchmarkDotNet/Diagnosers/DiagnosersLoader.cs b/src/BenchmarkDotNet/Diagnosers/DiagnosersLoader.cs index 3ebe51b36a..0442513848 100644 --- a/src/BenchmarkDotNet/Diagnosers/DiagnosersLoader.cs +++ b/src/BenchmarkDotNet/Diagnosers/DiagnosersLoader.cs @@ -15,7 +15,7 @@ internal static class DiagnosersLoader private const string DiagnosticAssemblyName = "BenchmarkDotNet.Diagnostics.Windows"; // Make the Diagnosers lazy-loaded, so they are only instantiated if needed - internal static readonly Lazy LazyLoadedDiagnosers + private static readonly Lazy LazyLoadedDiagnosers = new Lazy(LoadDiagnosers, LazyThreadSafetyMode.ExecutionAndPublication); internal static IDiagnoser GetImplementation() where TDiagnoser : IDiagnoser diff --git a/src/BenchmarkDotNet/Diagnosers/DisassemblyDiagnoser.cs b/src/BenchmarkDotNet/Diagnosers/DisassemblyDiagnoser.cs index 6bd8e7255d..67a2ec68f0 100644 --- a/src/BenchmarkDotNet/Diagnosers/DisassemblyDiagnoser.cs +++ b/src/BenchmarkDotNet/Diagnosers/DisassemblyDiagnoser.cs @@ -20,7 +20,7 @@ public class DisassemblyDiagnoser : IDisassemblyDiagnoser private readonly MonoDisassembler monoDisassembler; private readonly Dictionary results; - internal DisassemblyDiagnoser(WindowsDisassembler windowsDisassembler, MonoDisassembler monoDisassembler) + private DisassemblyDiagnoser(WindowsDisassembler windowsDisassembler, MonoDisassembler monoDisassembler) { this.windowsDisassembler = windowsDisassembler; this.monoDisassembler = monoDisassembler; @@ -67,7 +67,7 @@ public void Handle(HostSignal signal, DiagnoserActionParameters parameters) if (signal == HostSignal.AfterAll && ShouldUseWindowsDisassembler(benchmark)) results.Add(benchmark, windowsDisassembler.Disassemble(parameters)); else if (signal == HostSignal.SeparateLogic && ShouldUseMonoDisassembler(benchmark)) - results.Add(benchmark, monoDisassembler.Disassemble(benchmark, benchmark.Job.Environment.Runtime as MonoRuntime)); + results.Add(benchmark, MonoDisassembler.Disassemble(benchmark, benchmark.Job.Environment.Runtime as MonoRuntime)); } public void DisplayResults(ILogger logger) @@ -91,10 +91,10 @@ public IEnumerable Validate(ValidationParameters validationPara } } - private bool ShouldUseMonoDisassembler(BenchmarkCase benchmarkCase) + private static bool ShouldUseMonoDisassembler(BenchmarkCase benchmarkCase) => benchmarkCase.Job.Environment.Runtime is MonoRuntime || RuntimeInformation.IsMono; - private bool ShouldUseWindowsDisassembler(BenchmarkCase benchmarkCase) + private static bool ShouldUseWindowsDisassembler(BenchmarkCase benchmarkCase) => !(benchmarkCase.Job.Environment.Runtime is MonoRuntime) && RuntimeInformation.IsWindows(); } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Diagnosers/DisassemblyPrettifier.cs b/src/BenchmarkDotNet/Diagnosers/DisassemblyPrettifier.cs index ef34e284dc..728284b64d 100644 --- a/src/BenchmarkDotNet/Diagnosers/DisassemblyPrettifier.cs +++ b/src/BenchmarkDotNet/Diagnosers/DisassemblyPrettifier.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Linq; using System.Text; @@ -141,7 +142,7 @@ private static string PadRight(string instruction) private static string WithoutAddress(string extraArguments) { - int startOfTheAddress = extraArguments.IndexOf("("); + int startOfTheAddress = extraArguments.IndexOf("(", StringComparison.Ordinal); if (startOfTheAddress < 0) return extraArguments; diff --git a/src/BenchmarkDotNet/Diagnosers/IDiagnoser.cs b/src/BenchmarkDotNet/Diagnosers/IDiagnoser.cs index a0b9ebd85e..018147924a 100644 --- a/src/BenchmarkDotNet/Diagnosers/IDiagnoser.cs +++ b/src/BenchmarkDotNet/Diagnosers/IDiagnoser.cs @@ -30,7 +30,7 @@ public interface IDiagnoser IEnumerable Validate(ValidationParameters validationParameters); } - public interface IConfigurableDiagnoser : IDiagnoser + public interface IConfigurableDiagnoser : IDiagnoser { IConfigurableDiagnoser Configure(TConfig config); } diff --git a/src/BenchmarkDotNet/Diagnosers/MemoryDiagnoser.cs b/src/BenchmarkDotNet/Diagnosers/MemoryDiagnoser.cs index ba8f0b6149..2a78a17a74 100644 --- a/src/BenchmarkDotNet/Diagnosers/MemoryDiagnoser.cs +++ b/src/BenchmarkDotNet/Diagnosers/MemoryDiagnoser.cs @@ -12,6 +12,7 @@ using BenchmarkDotNet.Reports; using BenchmarkDotNet.Running; using BenchmarkDotNet.Validators; +using JetBrains.Annotations; namespace BenchmarkDotNet.Diagnosers { @@ -20,7 +21,7 @@ public class MemoryDiagnoser : IDiagnoser private const int Gen0 = 0, Gen1 = 1, Gen2 = 2; public static readonly MemoryDiagnoser Default = new MemoryDiagnoser(); - public const string DiagnoserId = nameof(MemoryDiagnoser); + private const string DiagnoserId = nameof(MemoryDiagnoser); private readonly Dictionary results = new Dictionary(); @@ -50,6 +51,7 @@ public void ProcessResults(DiagnoserResults results) public IEnumerable Validate(ValidationParameters validationParameters) => Array.Empty(); + [PublicAPI] public class AllocationColumn : IColumn { private readonly Dictionary results; @@ -81,6 +83,7 @@ public string GetValue(Summary summary, BenchmarkCase benchmarkCase, ISummarySty } } + [PublicAPI] public class GCCollectionColumn : IColumn { private readonly Dictionary results; diff --git a/src/BenchmarkDotNet/Diagnosers/MonoDisassembler.cs b/src/BenchmarkDotNet/Diagnosers/MonoDisassembler.cs index 963542a49c..3a54914505 100644 --- a/src/BenchmarkDotNet/Diagnosers/MonoDisassembler.cs +++ b/src/BenchmarkDotNet/Diagnosers/MonoDisassembler.cs @@ -27,7 +27,7 @@ internal MonoDisassembler(DisassemblyDiagnoserConfig config) recursiveDepth = config.RecursiveDepth; } - internal DisassemblyResult Disassemble(BenchmarkCase benchmarkCase, MonoRuntime mono) + internal static DisassemblyResult Disassemble(BenchmarkCase benchmarkCase, MonoRuntime mono) { Debug.Assert(mono == null || !RuntimeInformation.IsMono, "Must never be called for Non-Mono benchmarks"); @@ -136,9 +136,9 @@ private static DisassemblyResult CreateErrorResult([ItemCanBeNull] IReadOnlyList //line example 1: 0: 48 83 ec 28 sub $0x28,%rsp //line example 2: 0000000000000000 subq $0x28, %rsp - private static Regex instructionRegex = new Regex(@"\s*(?
[0-9a-f]+)(\:\s+([0-9a-f]{2}\s+)+)?\s+(?.*)\s*"); + private static readonly Regex instructionRegex = new Regex(@"\s*(?
[0-9a-f]+)(\:\s+([0-9a-f]{2}\s+)+)?\s+(?.*)\s*"); - public static bool TryParseInstruction(string line, out Code instruction) + private static bool TryParseInstruction(string line, out Code instruction) { instruction = null; var match = instructionRegex.Match(line); diff --git a/src/BenchmarkDotNet/Diagnosers/PreciseMachineCounter.cs b/src/BenchmarkDotNet/Diagnosers/PreciseMachineCounter.cs index 079df01085..1719898dc4 100644 --- a/src/BenchmarkDotNet/Diagnosers/PreciseMachineCounter.cs +++ b/src/BenchmarkDotNet/Diagnosers/PreciseMachineCounter.cs @@ -1,15 +1,16 @@ using System.Collections.Generic; +using JetBrains.Annotations; namespace BenchmarkDotNet.Diagnosers { #pragma warning disable CS3001, CS3003 // ulong is non CLS-compilant public class PreciseMachineCounter { - public int ProfileSourceId { get; } - public string Name { get; } - public HardwareCounter Counter { get; } - public int Interval { get; } - public Dictionary PerInstructionPointer { get; } + [PublicAPI] public int ProfileSourceId { get; } + [PublicAPI] public string Name { get; } + [PublicAPI] public HardwareCounter Counter { get; } + [PublicAPI] public int Interval { get; } + [PublicAPI] public Dictionary PerInstructionPointer { get; } public ulong Count { get; private set; } diff --git a/src/BenchmarkDotNet/Diagnosers/WindowsDisassembler.cs b/src/BenchmarkDotNet/Diagnosers/WindowsDisassembler.cs index 6b99c32b98..663689dbe9 100644 --- a/src/BenchmarkDotNet/Diagnosers/WindowsDisassembler.cs +++ b/src/BenchmarkDotNet/Diagnosers/WindowsDisassembler.cs @@ -57,7 +57,7 @@ internal DisassemblyResult Disassemble(DiagnoserActionParameters parameters) } } - private string GetDisassemblerPath(Process process, Platform platform) + private static string GetDisassemblerPath(Process process, Platform platform) { switch (platform) { @@ -75,7 +75,7 @@ private string GetDisassemblerPath(Process process, Platform platform) } } - private string GetDisassemblerPath(string architectureName) + private static string GetDisassemblerPath(string architectureName) { // one can only attach to a process of same target architecture, this is why we need exe for x64 and for x86 string exeName = $"BenchmarkDotNet.Disassembler.{architectureName}.exe"; @@ -102,7 +102,7 @@ private string GetDisassemblerPath(string architectureName) return disassemblerPath; } - private void CopyAllRequiredDependencies(Assembly assemblyWithDisassemblersInResources, string destinationFolder) + private static void CopyAllRequiredDependencies(Assembly assemblyWithDisassemblersInResources, string destinationFolder) { // ClrMD and Cecil are also embedded in the resources, we need to copy them as well foreach (string dependency in assemblyWithDisassemblersInResources.GetManifestResourceNames().Where(name => name.EndsWith(".dll"))) @@ -119,7 +119,7 @@ private void CopyAllRequiredDependencies(Assembly assemblyWithDisassemblersInRes } } - private void CopyFromResources(Assembly assembly, string resourceName, string destinationPath) + private static void CopyFromResources(Assembly assembly, string resourceName, string destinationPath) { using (var resourceStream = assembly.GetManifestResourceStream(resourceName)) using (var exeStream = File.Create(destinationPath)) @@ -143,7 +143,7 @@ private string BuildArguments(DiagnoserActionParameters parameters, string resul .ToString(); // code copied from https://stackoverflow.com/a/33206186/5852046 - internal static class NativeMethods + private static class NativeMethods { // see https://msdn.microsoft.com/en-us/library/windows/desktop/ms684139%28v=vs.85%29.aspx public static bool Is64Bit(Process process) diff --git a/src/BenchmarkDotNet/Engines/Engine.cs b/src/BenchmarkDotNet/Engines/Engine.cs index edf248333c..865044ad60 100644 --- a/src/BenchmarkDotNet/Engines/Engine.cs +++ b/src/BenchmarkDotNet/Engines/Engine.cs @@ -16,20 +16,20 @@ public class Engine : IEngine { public const int MinInvokeCount = 4; - public IHost Host { get; } - public Action WorkloadAction { get; } - public Action Dummy1Action { get; } - public Action Dummy2Action { get; } - public Action Dummy3Action { get; } - public Action OverheadAction { get; } - public Job TargetJob { get; } - public long OperationsPerInvoke { get; } - public Action GlobalSetupAction { get; } - public Action GlobalCleanupAction { get; } - public Action IterationSetupAction { get; } - public Action IterationCleanupAction { get; } - public IResolver Resolver { get; } - public Encoding Encoding { get; } + [PublicAPI] public IHost Host { get; } + [PublicAPI] public Action WorkloadAction { get; } + [PublicAPI] public Action Dummy1Action { get; } + [PublicAPI] public Action Dummy2Action { get; } + [PublicAPI] public Action Dummy3Action { get; } + [PublicAPI] public Action OverheadAction { get; } + [PublicAPI] public Job TargetJob { get; } + [PublicAPI] public long OperationsPerInvoke { get; } + [PublicAPI] public Action GlobalSetupAction { get; } + [PublicAPI] public Action GlobalCleanupAction { get; } + [PublicAPI] public Action IterationSetupAction { get; } + [PublicAPI] public Action IterationCleanupAction { get; } + [PublicAPI] public IResolver Resolver { get; } + [PublicAPI] public Encoding Encoding { get; } private IClock Clock { get; } private bool ForceAllocations { get; } @@ -177,7 +177,7 @@ private void GcCollect() ForceGcCollect(); } - private void ForceGcCollect() + private static void ForceGcCollect() { GC.Collect(); GC.WaitForPendingFinalizers(); @@ -188,7 +188,7 @@ private void ForceGcCollect() public void WriteLine() => Host.WriteLine(); - private void EnableMonitoring() + private static void EnableMonitoring() { if (RuntimeInformation.IsMono) // Monitoring is not available in Mono, see http://stackoverflow.com/questions/40234948/how-to-get-the-number-of-allocated-bytes-in-mono return; diff --git a/src/BenchmarkDotNet/Engines/EngineGeneralStage.cs b/src/BenchmarkDotNet/Engines/EngineGeneralStage.cs index 1c30d312d6..15cd3bddd4 100644 --- a/src/BenchmarkDotNet/Engines/EngineGeneralStage.cs +++ b/src/BenchmarkDotNet/Engines/EngineGeneralStage.cs @@ -10,8 +10,8 @@ namespace BenchmarkDotNet.Engines public class EngineActualStage : EngineStage { internal const int MaxOverheadIterationCount = 20; - internal const double MaxOverheadRelativeError = 0.05; - internal const int DefaultWorkloadCount = 10; + private const double MaxOverheadRelativeError = 0.05; + private const int DefaultWorkloadCount = 10; private readonly int? targetCount; private readonly double maxRelativeError; diff --git a/src/BenchmarkDotNet/Engines/RunResults.cs b/src/BenchmarkDotNet/Engines/RunResults.cs index 16e97753be..9553854fb4 100644 --- a/src/BenchmarkDotNet/Engines/RunResults.cs +++ b/src/BenchmarkDotNet/Engines/RunResults.cs @@ -13,10 +13,11 @@ public struct RunResults { private readonly OutlierMode outlierMode; private readonly Encoding encoding; - [CanBeNull] + + [CanBeNull, PublicAPI] public IReadOnlyList Overhead { get; } - [NotNull] + [NotNull, PublicAPI] public IReadOnlyList Workload { get; } public GcStats GCStats { get; } diff --git a/src/BenchmarkDotNet/Environments/BenchmarkEnvironmentInfo.cs b/src/BenchmarkDotNet/Environments/BenchmarkEnvironmentInfo.cs index 4946979e89..63dc9825bf 100644 --- a/src/BenchmarkDotNet/Environments/BenchmarkEnvironmentInfo.cs +++ b/src/BenchmarkDotNet/Environments/BenchmarkEnvironmentInfo.cs @@ -6,6 +6,7 @@ using BenchmarkDotNet.Jobs; using BenchmarkDotNet.Portability; using BenchmarkDotNet.Validators; +using JetBrains.Annotations; namespace BenchmarkDotNet.Environments { @@ -14,23 +15,15 @@ public class BenchmarkEnvironmentInfo internal const string RuntimeInfoPrefix = "Runtime="; internal const string GcInfoPrefix = "GC="; - public string Architecture { get; protected set; } - - public string Configuration { get; protected set; } - - public string RuntimeVersion { get; protected set; } - - public bool HasAttachedDebugger { get; protected set; } - - public bool HasRyuJit { get; protected set; } - - public string JitInfo { get; protected set; } - - public bool IsServerGC { get; protected set; } - - public bool IsConcurrentGC { get; protected set; } - - public long GCAllocationQuantum { get; protected set; } + [PublicAPI] public string Architecture { get; protected set; } + [PublicAPI] public string Configuration { get; protected set; } + [PublicAPI] public string RuntimeVersion { get; protected set; } + [PublicAPI] public bool HasAttachedDebugger { get; protected set; } + [PublicAPI] public bool HasRyuJit { get; protected set; } + [PublicAPI] public string JitInfo { get; protected set; } + [PublicAPI] public bool IsServerGC { get; protected set; } + [PublicAPI] public bool IsConcurrentGC { get; protected set; } + [PublicAPI] public long GCAllocationQuantum { get; protected set; } protected BenchmarkEnvironmentInfo() { @@ -55,15 +48,13 @@ public virtual IEnumerable ToFormattedString() yield return $"{GcInfoPrefix}{GetGcConcurrentFlag()} {GetGcServerFlag()}"; } - protected string GetConfigurationFlag() => Configuration == RuntimeInformation.Unknown || Configuration == RuntimeInformation.ReleaseConfigurationName + [PublicAPI] protected string GetConfigurationFlag() => Configuration == RuntimeInformation.Unknown || Configuration == RuntimeInformation.ReleaseConfigurationName ? "" : Configuration; - protected string GetDebuggerFlag() => HasAttachedDebugger ? " [AttachedDebugger]" : ""; - - protected string GetGcServerFlag() => IsServerGC ? "Server" : "Workstation"; - - protected string GetGcConcurrentFlag() => IsConcurrentGC ? "Concurrent" : "Non-concurrent"; + [PublicAPI] protected string GetDebuggerFlag() => HasAttachedDebugger ? " [AttachedDebugger]" : ""; + [PublicAPI] protected string GetGcServerFlag() => IsServerGC ? "Server" : "Workstation"; + [PublicAPI] protected string GetGcConcurrentFlag() => IsConcurrentGC ? "Concurrent" : "Non-concurrent"; internal string GetRuntimeInfo() { diff --git a/src/BenchmarkDotNet/Environments/HostEnvironmentInfo.cs b/src/BenchmarkDotNet/Environments/HostEnvironmentInfo.cs index defb903401..a24475e205 100644 --- a/src/BenchmarkDotNet/Environments/HostEnvironmentInfo.cs +++ b/src/BenchmarkDotNet/Environments/HostEnvironmentInfo.cs @@ -53,17 +53,17 @@ public class HostEnvironmentInfo : BenchmarkEnvironmentInfo /// checks if Mono is installed /// It's expensive to call (creates new process by calling `mono --version`) /// - public Lazy IsMonoInstalled { get; protected set; } + public Lazy IsMonoInstalled { get; } /// /// The frequency of the timer as the number of ticks per second. /// - public Frequency ChronometerFrequency { get; protected set; } - public TimeInterval ChronometerResolution => ChronometerFrequency.ToResolution(); + [PublicAPI] public Frequency ChronometerFrequency { get; protected set; } + [PublicAPI] public TimeInterval ChronometerResolution => ChronometerFrequency.ToResolution(); public HardwareTimerKind HardwareTimerKind { get; protected set; } - public Lazy> AntivirusProducts { get; protected set; } + public Lazy> AntivirusProducts { get; } public Lazy VirtualMachineHypervisor { get; protected set; } diff --git a/src/BenchmarkDotNet/Environments/Runtime.cs b/src/BenchmarkDotNet/Environments/Runtime.cs index 4d309815e6..d23fc3ca35 100644 --- a/src/BenchmarkDotNet/Environments/Runtime.cs +++ b/src/BenchmarkDotNet/Environments/Runtime.cs @@ -1,4 +1,5 @@ using System; +using JetBrains.Annotations; namespace BenchmarkDotNet.Environments { @@ -27,7 +28,7 @@ public abstract class Runtime : IEquatable /// public static readonly Runtime CoreRT = new CoreRtRuntime(); - public string Name { get; } + [PublicAPI] public string Name { get; } protected Runtime(string name) => Name = name; diff --git a/src/BenchmarkDotNet/Exporters/CombinedDisassemblyExporter.cs b/src/BenchmarkDotNet/Exporters/CombinedDisassemblyExporter.cs index 4696ae09bb..e368468ba9 100644 --- a/src/BenchmarkDotNet/Exporters/CombinedDisassemblyExporter.cs +++ b/src/BenchmarkDotNet/Exporters/CombinedDisassemblyExporter.cs @@ -107,6 +107,6 @@ private void PrintTable(BenchmarkCase[] benchmarksCase, ILogger logger, string t logger.WriteLine(""); } - private string GetImportantInfo(BenchmarkReport benchmarkReport) => benchmarkReport.GetRuntimeInfo(); + private static string GetImportantInfo(BenchmarkReport benchmarkReport) => benchmarkReport.GetRuntimeInfo(); } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Exporters/Csv/CsvExporter.cs b/src/BenchmarkDotNet/Exporters/Csv/CsvExporter.cs index ecbaecd938..6a7f38e1eb 100644 --- a/src/BenchmarkDotNet/Exporters/Csv/CsvExporter.cs +++ b/src/BenchmarkDotNet/Exporters/Csv/CsvExporter.cs @@ -1,5 +1,6 @@ using BenchmarkDotNet.Loggers; using BenchmarkDotNet.Reports; +using JetBrains.Annotations; namespace BenchmarkDotNet.Exporters.Csv { @@ -15,7 +16,7 @@ public CsvExporter(CsvSeparator separator) : this (separator, SummaryStyle.Defau { } - public CsvExporter(CsvSeparator separator, ISummaryStyle style) + [PublicAPI] public CsvExporter(CsvSeparator separator, ISummaryStyle style) { this.style = style; this.separator = separator; diff --git a/src/BenchmarkDotNet/Exporters/Csv/CsvMeasurementsExporter.cs b/src/BenchmarkDotNet/Exporters/Csv/CsvMeasurementsExporter.cs index dbb488259e..2c99a3e5fe 100644 --- a/src/BenchmarkDotNet/Exporters/Csv/CsvMeasurementsExporter.cs +++ b/src/BenchmarkDotNet/Exporters/Csv/CsvMeasurementsExporter.cs @@ -7,6 +7,7 @@ using BenchmarkDotNet.Jobs; using BenchmarkDotNet.Loggers; using BenchmarkDotNet.Reports; +using JetBrains.Annotations; namespace BenchmarkDotNet.Exporters.Csv { @@ -32,7 +33,7 @@ public CsvMeasurementsExporter(CsvSeparator separator, ISummaryStyle style = nul protected override string FileCaption => "measurements"; - public ISummaryStyle Style { get; private set; } + [PublicAPI] public ISummaryStyle Style { get; } public static Job[] GetJobs(Summary summary) => summary.BenchmarksCases.Select(b => b.Job).ToArray(); diff --git a/src/BenchmarkDotNet/Exporters/DefaultExporters.cs b/src/BenchmarkDotNet/Exporters/DefaultExporters.cs index db562db3f6..50fbb8714c 100644 --- a/src/BenchmarkDotNet/Exporters/DefaultExporters.cs +++ b/src/BenchmarkDotNet/Exporters/DefaultExporters.cs @@ -1,29 +1,30 @@ using BenchmarkDotNet.Exporters.Csv; using BenchmarkDotNet.Exporters.Json; using BenchmarkDotNet.Exporters.Xml; +using JetBrains.Annotations; namespace BenchmarkDotNet.Exporters { public static class DefaultExporters { - public static IExporter AsciiDoc = AsciiDocExporter.Default; - public static IExporter Csv = CsvExporter.Default; - public static IExporter CsvMeasurements = CsvMeasurementsExporter.Default; - public static IExporter Html = HtmlExporter.Default; - public static IExporter Markdown = MarkdownExporter.Default; - public static IExporter Plain = PlainExporter.Default; - public static IExporter RPlot = RPlotExporter.Default; + [PublicAPI] public static readonly IExporter AsciiDoc = AsciiDocExporter.Default; + [PublicAPI] public static readonly IExporter Csv = CsvExporter.Default; + [PublicAPI] public static readonly IExporter CsvMeasurements = CsvMeasurementsExporter.Default; + [PublicAPI] public static readonly IExporter Html = HtmlExporter.Default; + [PublicAPI] public static readonly IExporter Markdown = MarkdownExporter.Default; + [PublicAPI] public static readonly IExporter Plain = PlainExporter.Default; + [PublicAPI] public static readonly IExporter RPlot = RPlotExporter.Default; - public static IExporter Json = JsonExporter.Default; - public static IExporter JsonBrief = JsonExporter.Brief; - public static IExporter JsonBriefCompressed = JsonExporter.BriefCompressed; - public static IExporter JsonFull = JsonExporter.Full; - public static IExporter JsonFullCompressed = JsonExporter.FullCompressed; + [PublicAPI] public static readonly IExporter Json = JsonExporter.Default; + [PublicAPI] public static readonly IExporter JsonBrief = JsonExporter.Brief; + [PublicAPI] public static readonly IExporter JsonBriefCompressed = JsonExporter.BriefCompressed; + [PublicAPI] public static readonly IExporter JsonFull = JsonExporter.Full; + [PublicAPI] public static readonly IExporter JsonFullCompressed = JsonExporter.FullCompressed; - public static IExporter Xml = XmlExporter.Default; - public static IExporter XmlBrief = XmlExporter.Brief; - public static IExporter XmlBriefCompressed = XmlExporter.BriefCompressed; - public static IExporter XmlFull = XmlExporter.Full; - public static IExporter XmlFullCompressed = XmlExporter.FullCompressed; + [PublicAPI] public static readonly IExporter Xml = XmlExporter.Default; + [PublicAPI] public static readonly IExporter XmlBrief = XmlExporter.Brief; + [PublicAPI] public static readonly IExporter XmlBriefCompressed = XmlExporter.BriefCompressed; + [PublicAPI] public static readonly IExporter XmlFull = XmlExporter.Full; + [PublicAPI] public static readonly IExporter XmlFullCompressed = XmlExporter.FullCompressed; } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Exporters/ExporterBase.cs b/src/BenchmarkDotNet/Exporters/ExporterBase.cs index 89774b00dc..f7efe932aa 100644 --- a/src/BenchmarkDotNet/Exporters/ExporterBase.cs +++ b/src/BenchmarkDotNet/Exporters/ExporterBase.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using System.Text; using BenchmarkDotNet.Helpers; using BenchmarkDotNet.Loggers; using BenchmarkDotNet.Reports; @@ -13,7 +12,6 @@ namespace BenchmarkDotNet.Exporters public abstract class ExporterBase : IExporter { public string Name => $"{GetType().Name}{FileNameSuffix}"; - public Encoding Encoding { get; } protected virtual string FileExtension => "txt"; protected virtual string FileNameSuffix => string.Empty; diff --git a/src/BenchmarkDotNet/Exporters/HtmlExporter.cs b/src/BenchmarkDotNet/Exporters/HtmlExporter.cs index cc6b890a95..b8c2bbdab5 100644 --- a/src/BenchmarkDotNet/Exporters/HtmlExporter.cs +++ b/src/BenchmarkDotNet/Exporters/HtmlExporter.cs @@ -45,7 +45,7 @@ public override void ExportToLog(Summary summary, ILogger logger) logger.WriteLine(""); } - private void PrintTable(SummaryTable table, ILogger logger) + private static void PrintTable(SummaryTable table, ILogger logger) { if (table.FullContent.Length == 0) { @@ -78,7 +78,7 @@ private void PrintTable(SummaryTable table, ILogger logger) logger.WriteLine(""); } - private void PrintLine(SummaryTable table, string[] line, ILogger logger, string leftDel, string rightDel) + private static void PrintLine(SummaryTable table, string[] line, ILogger logger, string leftDel, string rightDel) { for (int columnIndex = 0; columnIndex < table.ColumnCount; columnIndex++) { diff --git a/src/BenchmarkDotNet/Exporters/InstructionPointerExporter.cs b/src/BenchmarkDotNet/Exporters/InstructionPointerExporter.cs index 9b046d0439..b85b099017 100644 --- a/src/BenchmarkDotNet/Exporters/InstructionPointerExporter.cs +++ b/src/BenchmarkDotNet/Exporters/InstructionPointerExporter.cs @@ -44,7 +44,7 @@ public IEnumerable ExportToFiles(Summary summary, ILogger consoleLogger) } } - private string Export(Summary summary, BenchmarkCase benchmarkCase, DisassemblyResult disassemblyResult, PmcStats pmcStats) + private static string Export(Summary summary, BenchmarkCase benchmarkCase, DisassemblyResult disassemblyResult, PmcStats pmcStats) { string filePath = $"{Path.Combine(summary.ResultsDirectoryPath, benchmarkCase.Descriptor.WorkloadMethod.Name)}-{benchmarkCase.Job.Environment.Jit}-{benchmarkCase.Job.Environment.Platform}-instructionPointer.html"; if (File.Exists(filePath)) @@ -160,7 +160,7 @@ private static IReadOnlyList SumHardwareCountersPerMethod(Di return model; } - private void Export(ILogger logger, BenchmarkCase benchmarkCase, Dictionary totals, IReadOnlyList model, HardwareCounter[] hardwareCounters) + private static void Export(ILogger logger, BenchmarkCase benchmarkCase, Dictionary totals, IReadOnlyList model, HardwareCounter[] hardwareCounters) { int columnsCount = hardwareCounters.Length + 2; diff --git a/src/BenchmarkDotNet/Exporters/Json/JsonExporterBase.cs b/src/BenchmarkDotNet/Exporters/Json/JsonExporterBase.cs index d2aa344c19..dcdc35a693 100644 --- a/src/BenchmarkDotNet/Exporters/Json/JsonExporterBase.cs +++ b/src/BenchmarkDotNet/Exporters/Json/JsonExporterBase.cs @@ -12,10 +12,10 @@ public abstract class JsonExporterBase : ExporterBase { protected override string FileExtension => "json"; - private bool IndentJson { get; set; } - private bool ExcludeMeasurements { get; set; } + private bool IndentJson { get; } + private bool ExcludeMeasurements { get; } - public JsonExporterBase(bool indentJson = false, bool excludeMeasurements = false) + protected JsonExporterBase(bool indentJson = false, bool excludeMeasurements = false) { IndentJson = indentJson; ExcludeMeasurements = excludeMeasurements; diff --git a/src/BenchmarkDotNet/Exporters/MarkdownExporter.cs b/src/BenchmarkDotNet/Exporters/MarkdownExporter.cs index 39e4c739f4..33b033c67c 100644 --- a/src/BenchmarkDotNet/Exporters/MarkdownExporter.cs +++ b/src/BenchmarkDotNet/Exporters/MarkdownExporter.cs @@ -1,6 +1,7 @@ using System.Linq; using BenchmarkDotNet.Loggers; using BenchmarkDotNet.Reports; +using JetBrains.Annotations; namespace BenchmarkDotNet.Exporters { @@ -26,71 +27,71 @@ public enum MarkdownHighlightStrategy public static readonly IExporter Default = new MarkdownExporter { Dialect = nameof(Default), - startOfGroupHighlightStrategy = MarkdownHighlightStrategy.Bold + StartOfGroupHighlightStrategy = MarkdownHighlightStrategy.Bold }; public static readonly IExporter Console = new MarkdownExporter { Dialect = nameof(Console), - startOfGroupHighlightStrategy = MarkdownHighlightStrategy.None + StartOfGroupHighlightStrategy = MarkdownHighlightStrategy.None }; public static readonly IExporter StackOverflow = new MarkdownExporter { Dialect = nameof(StackOverflow), - prefix = " ", - startOfGroupHighlightStrategy = MarkdownHighlightStrategy.Bold + Prefix = " ", + StartOfGroupHighlightStrategy = MarkdownHighlightStrategy.Bold }; public static readonly IExporter GitHub = new MarkdownExporter { Dialect = nameof(GitHub), - useCodeBlocks = true, - codeBlockStart = "``` ini", - startOfGroupHighlightStrategy = MarkdownHighlightStrategy.Bold, - columnsStartWithSeparator = true, - escapeHtml = true + UseCodeBlocks = true, + CodeBlockStart = "``` ini", + StartOfGroupHighlightStrategy = MarkdownHighlightStrategy.Bold, + ColumnsStartWithSeparator = true, + EscapeHtml = true }; public static readonly IExporter Atlassian = new MarkdownExporter { Dialect = nameof(Atlassian), - startOfGroupHighlightStrategy = MarkdownHighlightStrategy.Bold, - tableHeaderSeparator = " ||", - useHeaderSeparatingRow = false, - columnsStartWithSeparator = true, - useCodeBlocks = true, - codeBlockStart = "{noformat}", - codeBlockEnd = "{noformat}", - boldMarkupFormat = "*{0}*" + StartOfGroupHighlightStrategy = MarkdownHighlightStrategy.Bold, + TableHeaderSeparator = " ||", + UseHeaderSeparatingRow = false, + ColumnsStartWithSeparator = true, + UseCodeBlocks = true, + CodeBlockStart = "{noformat}", + CodeBlockEnd = "{noformat}", + BoldMarkupFormat = "*{0}*" }; // Only for unit tests internal static readonly IExporter Mock = new MarkdownExporter { Dialect = nameof(Mock), - startOfGroupHighlightStrategy = MarkdownHighlightStrategy.Marker + StartOfGroupHighlightStrategy = MarkdownHighlightStrategy.Marker }; - private string prefix = string.Empty; - private bool useCodeBlocks; - private string codeBlockStart = "```"; - private string codeBlockEnd = "```"; - private MarkdownHighlightStrategy startOfGroupHighlightStrategy = MarkdownHighlightStrategy.None; - private string tableHeaderSeparator = " |"; - private string tableColumnSeparator = " |"; - private bool useHeaderSeparatingRow = true; - private bool columnsStartWithSeparator; - private string boldMarkupFormat = "**{0}**"; - private bool escapeHtml; + [PublicAPI] protected string Prefix = string.Empty; + [PublicAPI] protected bool UseCodeBlocks; + [PublicAPI] protected string CodeBlockStart = "```"; + [PublicAPI] protected string CodeBlockEnd = "```"; + [PublicAPI] protected MarkdownHighlightStrategy StartOfGroupHighlightStrategy = MarkdownHighlightStrategy.None; + [PublicAPI] protected string TableHeaderSeparator = " |"; + [PublicAPI] protected string TableColumnSeparator = " |"; + [PublicAPI] protected bool UseHeaderSeparatingRow = true; + [PublicAPI] protected bool ColumnsStartWithSeparator; + [PublicAPI] protected string BoldMarkupFormat = "**{0}**"; + [PublicAPI] protected bool EscapeHtml; private MarkdownExporter() { } public override void ExportToLog(Summary summary, ILogger logger) { - if (useCodeBlocks) + if (UseCodeBlocks) { - logger.WriteLine(codeBlockStart); + logger.WriteLine(CodeBlockStart); } logger = GetRightLogger(logger); @@ -120,12 +121,12 @@ public override void ExportToLog(Summary summary, ILogger logger) private ILogger GetRightLogger(ILogger logger) { - if (string.IsNullOrEmpty(prefix)) // most common scenario!! we don't need expensive LoggerWithPrefix + if (string.IsNullOrEmpty(Prefix)) // most common scenario!! we don't need expensive LoggerWithPrefix { return logger; } - return new LoggerWithPrefix(logger, prefix); + return new LoggerWithPrefix(logger, Prefix); } private void PrintTable(SummaryTable table, ILogger logger) @@ -140,23 +141,23 @@ private void PrintTable(SummaryTable table, ILogger logger) table.PrintCommonColumns(logger); logger.WriteLine(); - if (useCodeBlocks) + if (UseCodeBlocks) { - logger.Write(codeBlockEnd); + logger.Write(CodeBlockEnd); logger.WriteLine(); } - if (columnsStartWithSeparator) + if (ColumnsStartWithSeparator) { - logger.Write(tableHeaderSeparator.TrimStart()); + logger.Write(TableHeaderSeparator.TrimStart()); } - table.PrintLine(table.FullHeader, logger, string.Empty, tableHeaderSeparator); - if (useHeaderSeparatingRow) + table.PrintLine(table.FullHeader, logger, string.Empty, TableHeaderSeparator); + if (UseHeaderSeparatingRow) { - if (columnsStartWithSeparator) + if (ColumnsStartWithSeparator) { - logger.Write(tableHeaderSeparator.TrimStart()); + logger.Write(TableHeaderSeparator.TrimStart()); } logger.WriteLineStatistic(string.Join("", @@ -171,10 +172,10 @@ private void PrintTable(SummaryTable table, ILogger logger) if (rowCounter > 0 && table.FullContentStartOfLogicalGroup[rowCounter] && table.SeparateLogicalGroups) { // Print logical separator - if (columnsStartWithSeparator) - logger.Write(tableColumnSeparator.TrimStart()); - table.PrintLine(separatorLine, logger, string.Empty, tableColumnSeparator, highlightRow, false, startOfGroupHighlightStrategy, - boldMarkupFormat, false); + if (ColumnsStartWithSeparator) + logger.Write(TableColumnSeparator.TrimStart()); + table.PrintLine(separatorLine, logger, string.Empty, TableColumnSeparator, highlightRow, false, StartOfGroupHighlightStrategy, + BoldMarkupFormat, false); } // Each time we hit the start of a new group, alternative the colour (in the console) or display bold in Markdown @@ -183,11 +184,11 @@ private void PrintTable(SummaryTable table, ILogger logger) highlightRow = !highlightRow; } - if (columnsStartWithSeparator) - logger.Write(tableColumnSeparator.TrimStart()); + if (ColumnsStartWithSeparator) + logger.Write(TableColumnSeparator.TrimStart()); - table.PrintLine(line, logger, string.Empty, tableColumnSeparator, highlightRow, table.FullContentStartOfHighlightGroup[rowCounter], - startOfGroupHighlightStrategy, boldMarkupFormat, escapeHtml); + table.PrintLine(line, logger, string.Empty, TableColumnSeparator, highlightRow, table.FullContentStartOfHighlightGroup[rowCounter], + StartOfGroupHighlightStrategy, BoldMarkupFormat, EscapeHtml); rowCounter++; } } diff --git a/src/BenchmarkDotNet/Exporters/PrettyDisassemblyExporter.cs b/src/BenchmarkDotNet/Exporters/PrettyDisassemblyExporter.cs index 9f2dd168cc..e8d5c5fae7 100644 --- a/src/BenchmarkDotNet/Exporters/PrettyDisassemblyExporter.cs +++ b/src/BenchmarkDotNet/Exporters/PrettyDisassemblyExporter.cs @@ -42,7 +42,7 @@ private string Export(Summary summary, BenchmarkCase benchmarkCase) return filePath; } - private void Export(ILogger logger, DisassemblyResult disassemblyResult, BenchmarkCase benchmarkCase) + private static void Export(ILogger logger, DisassemblyResult disassemblyResult, BenchmarkCase benchmarkCase) { logger.WriteLine(""); logger.WriteLine($"Pretty Output of DisassemblyDiagnoser for {benchmarkCase.DisplayInfo}"); diff --git a/src/BenchmarkDotNet/Exporters/RPlotExporter.cs b/src/BenchmarkDotNet/Exporters/RPlotExporter.cs index f982c9219f..fae0e90b68 100644 --- a/src/BenchmarkDotNet/Exporters/RPlotExporter.cs +++ b/src/BenchmarkDotNet/Exporters/RPlotExporter.cs @@ -16,7 +16,7 @@ public class RPlotExporter : IExporter, IExporterDependencies public static readonly IExporter Default = new RPlotExporter(); public string Name => nameof(RPlotExporter); - private static object buildScriptLock = new object(); + private static readonly object buildScriptLock = new object(); public IEnumerable Dependencies { @@ -91,7 +91,7 @@ public void ExportToLog(Summary summary, ILogger logger) throw new NotSupportedException(); } - public static string FindInPath(string fileName) + private static string FindInPath(string fileName) { var dirs = Environment.GetEnvironmentVariable("PATH").Split(Path.PathSeparator); foreach (string dir in dirs) diff --git a/src/BenchmarkDotNet/Exporters/RawDisassemblyExporter.cs b/src/BenchmarkDotNet/Exporters/RawDisassemblyExporter.cs index be4d36a83f..c1e036690a 100644 --- a/src/BenchmarkDotNet/Exporters/RawDisassemblyExporter.cs +++ b/src/BenchmarkDotNet/Exporters/RawDisassemblyExporter.cs @@ -39,7 +39,7 @@ private string Export(Summary summary, BenchmarkCase benchmarkCase) return filePath; } - private void Export(ILogger logger, DisassemblyResult disassemblyResult, BenchmarkCase benchmarkCase) + private static void Export(ILogger logger, DisassemblyResult disassemblyResult, BenchmarkCase benchmarkCase) { logger.WriteLine(""); logger.WriteLine($"Output of DisassemblyDiagnoser for {benchmarkCase.DisplayInfo}"); @@ -109,7 +109,7 @@ private void Export(ILogger logger, DisassemblyResult disassemblyResult, Benchma - private string GetShortName(string fullMethodSignature) + private static string GetShortName(string fullMethodSignature) { int bracketIndex = fullMethodSignature.IndexOf('('); string withoutArguments = fullMethodSignature.Remove(bracketIndex); diff --git a/src/BenchmarkDotNet/Exporters/Xml/SimpleXmlWriter.cs b/src/BenchmarkDotNet/Exporters/Xml/SimpleXmlWriter.cs index 5814ccc46c..7c784ddb7f 100644 --- a/src/BenchmarkDotNet/Exporters/Xml/SimpleXmlWriter.cs +++ b/src/BenchmarkDotNet/Exporters/Xml/SimpleXmlWriter.cs @@ -6,7 +6,7 @@ namespace BenchmarkDotNet.Exporters.Xml { internal class SimpleXmlWriter : IXmlWriter, IDisposable { - private XmlWriter writer; + private readonly XmlWriter writer; public SimpleXmlWriter(TextWriter writer, bool indent) { diff --git a/src/BenchmarkDotNet/Exporters/Xml/SummaryDto.cs b/src/BenchmarkDotNet/Exporters/Xml/SummaryDto.cs index 92dbaf4a95..eabfb469e9 100644 --- a/src/BenchmarkDotNet/Exporters/Xml/SummaryDto.cs +++ b/src/BenchmarkDotNet/Exporters/Xml/SummaryDto.cs @@ -58,7 +58,7 @@ internal class ChronometerDto { public double Hertz => frequency.Hertz; - private Frequency frequency; + private readonly Frequency frequency; public ChronometerDto(Frequency frequency) { diff --git a/src/BenchmarkDotNet/Exporters/Xml/XmlExporterBase.cs b/src/BenchmarkDotNet/Exporters/Xml/XmlExporterBase.cs index 796370fa03..021c25b040 100644 --- a/src/BenchmarkDotNet/Exporters/Xml/XmlExporterBase.cs +++ b/src/BenchmarkDotNet/Exporters/Xml/XmlExporterBase.cs @@ -14,7 +14,7 @@ public abstract class XmlExporterBase : ExporterBase private readonly bool indentXml; private readonly bool excludeMeasurements; - public XmlExporterBase(bool indentXml = false, bool excludeMeasurements = false) + protected XmlExporterBase(bool indentXml = false, bool excludeMeasurements = false) { this.indentXml = indentXml; this.excludeMeasurements = excludeMeasurements; diff --git a/src/BenchmarkDotNet/Exporters/Xml/XmlSerializer.cs b/src/BenchmarkDotNet/Exporters/Xml/XmlSerializer.cs index da549bcf70..4edcc55826 100644 --- a/src/BenchmarkDotNet/Exporters/Xml/XmlSerializer.cs +++ b/src/BenchmarkDotNet/Exporters/Xml/XmlSerializer.cs @@ -16,7 +16,7 @@ internal class XmlSerializer : IXmlSerializer private IXmlWriter writer; - public static string DefaultItemName { get; } = "Item"; + public const string DefaultItemName = "Item"; private XmlSerializer(XmlSerializerBuilder builder) { @@ -156,20 +156,20 @@ private static bool IsSimple(TypeInfo type) { return type.IsPrimitive || type.IsEnum - || type.Equals(typeof(string)) - || type.Equals(typeof(decimal)); + || type == typeof(string) + || type == typeof(decimal); } private static bool IsCollection(PropertyInfo property) => typeof(IEnumerable).IsAssignableFrom(property.PropertyType); - private bool IsCollectionWritable(IEnumerable collection) + private static bool IsCollectionWritable(IEnumerable collection) => collection?.Cast().FirstOrDefault() != null; internal class XmlSerializerBuilder { - private Dictionary collectionItemNameMap = new Dictionary(); - private HashSet excludedPropertyNames = new HashSet(); + private readonly Dictionary collectionItemNameMap = new Dictionary(); + private readonly HashSet excludedPropertyNames = new HashSet(); public Type Type { get; } public string RootName { get; private set; } diff --git a/src/BenchmarkDotNet/Extensions/ReflectionExtensions.cs b/src/BenchmarkDotNet/Extensions/ReflectionExtensions.cs index 401c6c3844..12a7e562a8 100644 --- a/src/BenchmarkDotNet/Extensions/ReflectionExtensions.cs +++ b/src/BenchmarkDotNet/Extensions/ReflectionExtensions.cs @@ -3,23 +3,29 @@ using System.Linq; using System.Reflection; using BenchmarkDotNet.Attributes; +using JetBrains.Annotations; namespace BenchmarkDotNet.Extensions { internal static class ReflectionExtensions { + [PublicAPI] internal static T ResolveAttribute(this Type type) where T : Attribute => type?.GetTypeInfo().GetCustomAttributes(typeof(T), false).OfType().FirstOrDefault(); + [PublicAPI] internal static T ResolveAttribute(this MethodInfo methodInfo) where T : Attribute => methodInfo?.GetCustomAttributes(typeof(T), false).FirstOrDefault() as T; + [PublicAPI] internal static T ResolveAttribute(this PropertyInfo propertyInfo) where T : Attribute => propertyInfo?.GetCustomAttributes(typeof(T), false).FirstOrDefault() as T; + [PublicAPI] internal static T ResolveAttribute(this FieldInfo fieldInfo) where T : Attribute => fieldInfo?.GetCustomAttributes(typeof(T), false).FirstOrDefault() as T; + [PublicAPI] internal static bool HasAttribute(this MethodInfo methodInfo) where T : Attribute => methodInfo.ResolveAttribute() != null; @@ -79,7 +85,7 @@ internal static string GetCorrectCSharpTypeName(this Type type, bool includeName /// /// returns simple, human friendly display name /// - internal static string GetDisplayName(this TypeInfo typeInfo) + private static string GetDisplayName(this TypeInfo typeInfo) { if (!typeInfo.IsGenericType) return typeInfo.Name; @@ -143,7 +149,7 @@ internal static bool ContainsRunnableBenchmarks(this Type type) return typeInfo.GetBenchmarks().Any(); } - internal static MethodInfo[] GetBenchmarks(this TypeInfo typeInfo) + private static MethodInfo[] GetBenchmarks(this TypeInfo typeInfo) => typeInfo .GetMethods(BindingFlags.Instance | BindingFlags.Public) .Where(method => method.GetCustomAttributes(true).OfType().Any()) diff --git a/src/BenchmarkDotNet/Extensions/StatisticsExtensions.cs b/src/BenchmarkDotNet/Extensions/StatisticsExtensions.cs index cfc0ab14c0..3761ab13e3 100644 --- a/src/BenchmarkDotNet/Extensions/StatisticsExtensions.cs +++ b/src/BenchmarkDotNet/Extensions/StatisticsExtensions.cs @@ -7,7 +7,7 @@ namespace BenchmarkDotNet.Extensions { public static class StatisticsExtensions { - private static string NullSummaryMessage = ""; + private const string NullSummaryMessage = ""; public static string ToStr(this Statistics s) { diff --git a/src/BenchmarkDotNet/Filters/SimpleFilter.cs b/src/BenchmarkDotNet/Filters/SimpleFilter.cs index b1f75a431d..d760d36640 100644 --- a/src/BenchmarkDotNet/Filters/SimpleFilter.cs +++ b/src/BenchmarkDotNet/Filters/SimpleFilter.cs @@ -1,5 +1,6 @@ using System; using BenchmarkDotNet.Running; +using JetBrains.Annotations; namespace BenchmarkDotNet.Filters { @@ -7,11 +8,10 @@ public class SimpleFilter : IFilter { private readonly Func predicate; - public SimpleFilter(Func predicate) - { - this.predicate = predicate; - } + [PublicAPI] + public SimpleFilter(Func predicate) => this.predicate = predicate; + [PublicAPI] public bool Predicate(BenchmarkCase benchmarkCase) => predicate(benchmarkCase); } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Helpers/CodeAnnotations.cs b/src/BenchmarkDotNet/Helpers/CodeAnnotations.cs index 3674c8ac60..1bbe20945d 100644 --- a/src/BenchmarkDotNet/Helpers/CodeAnnotations.cs +++ b/src/BenchmarkDotNet/Helpers/CodeAnnotations.cs @@ -21,6 +21,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; +// ReSharper disable All #pragma warning disable 1591 // ReSharper disable UnusedMember.Global diff --git a/src/BenchmarkDotNet/Helpers/MultiEncodingString.cs b/src/BenchmarkDotNet/Helpers/MultiEncodingString.cs index 56714f91f5..c51dd68c44 100644 --- a/src/BenchmarkDotNet/Helpers/MultiEncodingString.cs +++ b/src/BenchmarkDotNet/Helpers/MultiEncodingString.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; +using JetBrains.Annotations; namespace BenchmarkDotNet.Helpers { @@ -11,7 +12,7 @@ public class MultiEncodingString private readonly Dictionary encodedStrings; /// Ctor for ascii-only presentation - public MultiEncodingString(string asciiPresentation) + [PublicAPI] public MultiEncodingString(string asciiPresentation) { var pairs = new[] { @@ -23,7 +24,7 @@ public MultiEncodingString(string asciiPresentation) } /// Ctor for specified unicode and ascii presentations - public MultiEncodingString(string asciiPresentation, string unicodePresentation) + [PublicAPI] public MultiEncodingString(string asciiPresentation, string unicodePresentation) { var pairs = new[] { @@ -49,7 +50,7 @@ public MultiEncodingString(IEnumerable> encodedSt public string ToString(Encoding encoding) => GetStringByEncoding(encoding); - public string GetString(Encoding encoding) => GetStringByEncoding(encoding); + [PublicAPI] public string GetString(Encoding encoding) => GetStringByEncoding(encoding); public static implicit operator MultiEncodingString(string s) => new MultiEncodingString(s); @@ -86,6 +87,6 @@ private string GetStringByEncoding(Encoding encoding) : null; } - private Encoding GetFallback() => Encoding.ASCII; + private static Encoding GetFallback() => Encoding.ASCII; } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Horology/Frequency.cs b/src/BenchmarkDotNet/Horology/Frequency.cs index 20ddba59b2..4176cbf851 100644 --- a/src/BenchmarkDotNet/Horology/Frequency.cs +++ b/src/BenchmarkDotNet/Horology/Frequency.cs @@ -4,55 +4,56 @@ namespace BenchmarkDotNet.Horology { + [PublicAPI] public struct Frequency { - public double Hertz { get; } + [PublicAPI] public double Hertz { get; } - public Frequency(double hertz) => Hertz = hertz; + [PublicAPI] public Frequency(double hertz) => Hertz = hertz; - public Frequency(double value, FrequencyUnit unit) : this(value * unit.HertzAmount) { } + [PublicAPI] public Frequency(double value, FrequencyUnit unit) : this(value * unit.HertzAmount) { } - public static readonly Frequency Zero = new Frequency(0); - public static readonly Frequency Hz = FrequencyUnit.Hz.ToFrequency(); - public static readonly Frequency KHz = FrequencyUnit.KHz.ToFrequency(); - public static readonly Frequency MHz = FrequencyUnit.MHz.ToFrequency(); - public static readonly Frequency GHz = FrequencyUnit.GHz.ToFrequency(); + [PublicAPI] public static readonly Frequency Zero = new Frequency(0); + [PublicAPI] public static readonly Frequency Hz = FrequencyUnit.Hz.ToFrequency(); + [PublicAPI] public static readonly Frequency KHz = FrequencyUnit.KHz.ToFrequency(); + [PublicAPI] public static readonly Frequency MHz = FrequencyUnit.MHz.ToFrequency(); + [PublicAPI] public static readonly Frequency GHz = FrequencyUnit.GHz.ToFrequency(); - [Pure] public TimeInterval ToResolution() => TimeInterval.Second / Hertz; + [PublicAPI, Pure] public TimeInterval ToResolution() => TimeInterval.Second / Hertz; - [Pure] public double ToHz() => this / Hz; - [Pure] public double ToKHz() => this / KHz; - [Pure] public double ToMHz() => this / MHz; - [Pure] public double ToGHz() => this / GHz; + [PublicAPI, Pure] public double ToHz() => this / Hz; + [PublicAPI, Pure] public double ToKHz() => this / KHz; + [PublicAPI, Pure] public double ToMHz() => this / MHz; + [PublicAPI, Pure] public double ToGHz() => this / GHz; - [Pure] public static Frequency FromHz(double value) => Hz * value; - [Pure] public static Frequency FromKHz(double value) => KHz * value; - [Pure] public static Frequency FromMHz(double value) => MHz * value; - [Pure] public static Frequency FromGHz(double value) => GHz * value; + [PublicAPI, Pure] public static Frequency FromHz(double value) => Hz * value; + [PublicAPI, Pure] public static Frequency FromKHz(double value) => KHz * value; + [PublicAPI, Pure] public static Frequency FromMHz(double value) => MHz * value; + [PublicAPI, Pure] public static Frequency FromGHz(double value) => GHz * value; - [Pure] public static implicit operator Frequency(double value) => new Frequency(value); - [Pure] public static implicit operator double(Frequency property) => property.Hertz; + [PublicAPI, Pure] public static implicit operator Frequency(double value) => new Frequency(value); + [PublicAPI, Pure] public static implicit operator double(Frequency property) => property.Hertz; - [Pure] public static double operator /(Frequency a, Frequency b) => 1.0 * a.Hertz / b.Hertz; - [Pure] public static Frequency operator /(Frequency a, double k) => new Frequency(a.Hertz / k); - [Pure] public static Frequency operator /(Frequency a, int k) => new Frequency(a.Hertz / k); - [Pure] public static Frequency operator *(Frequency a, double k) => new Frequency(a.Hertz * k); - [Pure] public static Frequency operator *(Frequency a, int k) => new Frequency(a.Hertz * k); - [Pure] public static Frequency operator *(double k, Frequency a) => new Frequency(a.Hertz * k); - [Pure] public static Frequency operator *(int k, Frequency a) => new Frequency(a.Hertz * k); + [PublicAPI, Pure] public static double operator /(Frequency a, Frequency b) => 1.0 * a.Hertz / b.Hertz; + [PublicAPI, Pure] public static Frequency operator /(Frequency a, double k) => new Frequency(a.Hertz / k); + [PublicAPI, Pure] public static Frequency operator /(Frequency a, int k) => new Frequency(a.Hertz / k); + [PublicAPI, Pure] public static Frequency operator *(Frequency a, double k) => new Frequency(a.Hertz * k); + [PublicAPI, Pure] public static Frequency operator *(Frequency a, int k) => new Frequency(a.Hertz * k); + [PublicAPI, Pure] public static Frequency operator *(double k, Frequency a) => new Frequency(a.Hertz * k); + [PublicAPI, Pure] public static Frequency operator *(int k, Frequency a) => new Frequency(a.Hertz * k); - public static bool TryParse(string s, FrequencyUnit unit, out Frequency freq) + [PublicAPI, Pure] public static bool TryParse(string s, FrequencyUnit unit, out Frequency freq) { bool success = double.TryParse(s, NumberStyles.Any, HostEnvironmentInfo.MainCultureInfo, out double result); freq = new Frequency(result, unit); return success; } - public static bool TryParseHz(string s, out Frequency freq) => TryParse(s, FrequencyUnit.Hz, out freq); - public static bool TryParseKHz(string s, out Frequency freq) => TryParse(s, FrequencyUnit.KHz, out freq); - public static bool TryParseMHz(string s, out Frequency freq) => TryParse(s, FrequencyUnit.MHz, out freq); - public static bool TryParseGHz(string s, out Frequency freq) => TryParse(s, FrequencyUnit.GHz, out freq); + [PublicAPI, Pure] public static bool TryParseHz(string s, out Frequency freq) => TryParse(s, FrequencyUnit.Hz, out freq); + [PublicAPI, Pure] public static bool TryParseKHz(string s, out Frequency freq) => TryParse(s, FrequencyUnit.KHz, out freq); + [PublicAPI, Pure] public static bool TryParseMHz(string s, out Frequency freq) => TryParse(s, FrequencyUnit.MHz, out freq); + [PublicAPI, Pure] public static bool TryParseGHz(string s, out Frequency freq) => TryParse(s, FrequencyUnit.GHz, out freq); - [Pure] public override string ToString() => Hertz + " " + FrequencyUnit.Hz.Name; + [PublicAPI, Pure] public override string ToString() => Hertz + " " + FrequencyUnit.Hz.Name; } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Horology/TimeUnit.cs b/src/BenchmarkDotNet/Horology/TimeUnit.cs index 9ea685a194..ca58088e7f 100644 --- a/src/BenchmarkDotNet/Horology/TimeUnit.cs +++ b/src/BenchmarkDotNet/Horology/TimeUnit.cs @@ -1,5 +1,6 @@ using System.Linq; using BenchmarkDotNet.Helpers; +using JetBrains.Annotations; namespace BenchmarkDotNet.Horology { @@ -20,14 +21,14 @@ private TimeUnit(MultiEncodingString name, string description, long nanosecondAm public TimeInterval ToInterval(long value = 1) => new TimeInterval(value, this); - public static readonly TimeUnit Nanosecond = new TimeUnit("ns", "Nanosecond", 1); - public static readonly TimeUnit Microsecond = new TimeUnit(new MultiEncodingString("us", "\u03BCs"), "Microsecond", 1000); - public static readonly TimeUnit Millisecond = new TimeUnit("ms", "Millisecond", 1000 * 1000); - public static readonly TimeUnit Second = new TimeUnit("s", "Second", 1000 * 1000 * 1000); - public static readonly TimeUnit Minute = new TimeUnit("m", "Minute", Second.NanosecondAmount * 60); - public static readonly TimeUnit Hour = new TimeUnit("h", "Hour", Minute.NanosecondAmount * 60); - public static readonly TimeUnit Day = new TimeUnit("d", "Day", Hour.NanosecondAmount * 24); - public static readonly TimeUnit[] All = { Nanosecond, Microsecond, Millisecond, Second, Minute, Hour, Day }; + [PublicAPI] public static readonly TimeUnit Nanosecond = new TimeUnit("ns", "Nanosecond", 1); + [PublicAPI] public static readonly TimeUnit Microsecond = new TimeUnit(new MultiEncodingString("us", "\u03BCs"), "Microsecond", 1000); + [PublicAPI] public static readonly TimeUnit Millisecond = new TimeUnit("ms", "Millisecond", 1000 * 1000); + [PublicAPI] public static readonly TimeUnit Second = new TimeUnit("s", "Second", 1000 * 1000 * 1000); + [PublicAPI] public static readonly TimeUnit Minute = new TimeUnit("m", "Minute", Second.NanosecondAmount * 60); + [PublicAPI] public static readonly TimeUnit Hour = new TimeUnit("h", "Hour", Minute.NanosecondAmount * 60); + [PublicAPI] public static readonly TimeUnit Day = new TimeUnit("d", "Day", Hour.NanosecondAmount * 24); + [PublicAPI] public static readonly TimeUnit[] All = { Nanosecond, Microsecond, Millisecond, Second, Minute, Hour, Day }; /// /// This method chooses the best time unit for representing a set of time measurements. diff --git a/src/BenchmarkDotNet/Jobs/EnvironmentMode.cs b/src/BenchmarkDotNet/Jobs/EnvironmentMode.cs index 1fddd252e1..bf19ed285b 100644 --- a/src/BenchmarkDotNet/Jobs/EnvironmentMode.cs +++ b/src/BenchmarkDotNet/Jobs/EnvironmentMode.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using BenchmarkDotNet.Characteristics; using BenchmarkDotNet.Environments; +using JetBrains.Annotations; namespace BenchmarkDotNet.Jobs { @@ -23,14 +24,14 @@ public sealed class EnvironmentMode : JobMode public static readonly EnvironmentMode RyuJitX64 = new EnvironmentMode(nameof(RyuJitX64), Jit.RyuJit, Platform.X64).Freeze(); public static readonly EnvironmentMode RyuJitX86 = new EnvironmentMode(nameof(RyuJitX86), Jit.RyuJit, Platform.X86).Freeze(); - public EnvironmentMode() : this(id: null) { } + [PublicAPI] public EnvironmentMode() : this(id: null) { } - public EnvironmentMode(Runtime runtime) : this(runtime.ToString()) + [PublicAPI] public EnvironmentMode(Runtime runtime) : this(runtime.ToString()) { Runtime = runtime; } - public EnvironmentMode(string id, Jit jit, Platform platform) : this(id) + [PublicAPI] public EnvironmentMode(string id, Jit jit, Platform platform) : this(id) { Jit = jit; Platform = platform; @@ -38,7 +39,7 @@ public EnvironmentMode(string id, Jit jit, Platform platform) : this(id) Runtime = Runtime.Clr; } - public EnvironmentMode(string id) : base(id) + [PublicAPI] public EnvironmentMode(string id) : base(id) { GcCharacteristic[this] = new GcMode(); } diff --git a/src/BenchmarkDotNet/Jobs/GcMode.cs b/src/BenchmarkDotNet/Jobs/GcMode.cs index 95f6ea4dbf..4efa15c1c5 100644 --- a/src/BenchmarkDotNet/Jobs/GcMode.cs +++ b/src/BenchmarkDotNet/Jobs/GcMode.cs @@ -1,9 +1,10 @@ using System; +using System.Diagnostics.CodeAnalysis; using BenchmarkDotNet.Characteristics; -// ReSharper disable once CheckNamespace namespace BenchmarkDotNet.Jobs { + [SuppressMessage("ReSharper", "MemberCanBePrivate.Global")] public sealed class GcMode : JobMode, IEquatable { public static readonly Characteristic ServerCharacteristic = CreateCharacteristic(nameof(Server)); diff --git a/src/BenchmarkDotNet/Jobs/Job.cs b/src/BenchmarkDotNet/Jobs/Job.cs index 8a8e62d68c..e84b392e60 100644 --- a/src/BenchmarkDotNet/Jobs/Job.cs +++ b/src/BenchmarkDotNet/Jobs/Job.cs @@ -1,15 +1,16 @@ using BenchmarkDotNet.Characteristics; using BenchmarkDotNet.Environments; +using JetBrains.Annotations; namespace BenchmarkDotNet.Jobs { public sealed class Job : JobMode { - public static readonly Characteristic EnvironmentCharacteristic = CreateCharacteristic(nameof(Environment)); - public static readonly Characteristic RunCharacteristic = CreateCharacteristic(nameof(Run)); - public static readonly Characteristic InfrastructureCharacteristic = CreateCharacteristic(nameof(Infrastructure)); - public static readonly Characteristic AccuracyCharacteristic = CreateCharacteristic(nameof(Accuracy)); - public static readonly Characteristic MetaCharacteristic = CreateCharacteristic(nameof(Meta)); + [PublicAPI] public static readonly Characteristic EnvironmentCharacteristic = CreateCharacteristic(nameof(Environment)); + [PublicAPI] public static readonly Characteristic RunCharacteristic = CreateCharacteristic(nameof(Run)); + [PublicAPI] public static readonly Characteristic InfrastructureCharacteristic = CreateCharacteristic(nameof(Infrastructure)); + [PublicAPI] public static readonly Characteristic AccuracyCharacteristic = CreateCharacteristic(nameof(Accuracy)); + [PublicAPI] public static readonly Characteristic MetaCharacteristic = CreateCharacteristic(nameof(Meta)); // Env public static readonly Job Clr = new Job(nameof(Clr), EnvironmentMode.Clr).Freeze(); diff --git a/src/BenchmarkDotNet/Jobs/MetaMode.cs b/src/BenchmarkDotNet/Jobs/MetaMode.cs index 5935b43a4f..588273af74 100644 --- a/src/BenchmarkDotNet/Jobs/MetaMode.cs +++ b/src/BenchmarkDotNet/Jobs/MetaMode.cs @@ -1,11 +1,12 @@ using BenchmarkDotNet.Characteristics; +using JetBrains.Annotations; namespace BenchmarkDotNet.Jobs { public class MetaMode : JobMode { - public static readonly Characteristic BaselineCharacteristic = CreateHiddenCharacteristic(nameof(Baseline)); - public static readonly Characteristic IsMutatorCharacteristic = CreateIgnoreOnApplyCharacteristic(nameof(IsMutator)); + [PublicAPI] public static readonly Characteristic BaselineCharacteristic = CreateHiddenCharacteristic(nameof(Baseline)); + [PublicAPI] public static readonly Characteristic IsMutatorCharacteristic = CreateIgnoreOnApplyCharacteristic(nameof(IsMutator)); public bool Baseline { diff --git a/src/BenchmarkDotNet/Jobs/RunMode.cs b/src/BenchmarkDotNet/Jobs/RunMode.cs index feb6da3a21..0ec0f6e33f 100644 --- a/src/BenchmarkDotNet/Jobs/RunMode.cs +++ b/src/BenchmarkDotNet/Jobs/RunMode.cs @@ -3,8 +3,6 @@ using BenchmarkDotNet.Engines; using BenchmarkDotNet.Horology; -// ReSharper disable once CheckNamespace - namespace BenchmarkDotNet.Jobs { public sealed class RunMode : JobMode @@ -64,7 +62,7 @@ public RunMode() : this(null) { } - public RunMode(string id) : base(id) + private RunMode(string id) : base(id) { } diff --git a/src/BenchmarkDotNet/Loggers/LoggerWithPrefix.cs b/src/BenchmarkDotNet/Loggers/LoggerWithPrefix.cs index f2f2369b5b..d0cf9a5fcb 100644 --- a/src/BenchmarkDotNet/Loggers/LoggerWithPrefix.cs +++ b/src/BenchmarkDotNet/Loggers/LoggerWithPrefix.cs @@ -5,8 +5,8 @@ /// public class LoggerWithPrefix : ILogger { - public ILogger Logger { get; } - public string Prefix { get; } + private ILogger Logger { get; } + private string Prefix { get; } private bool isNewLine = true; public LoggerWithPrefix(ILogger logger, string prefix) diff --git a/src/BenchmarkDotNet/Loggers/SynchronousProcessOutputLoggerWithDiagnoser.cs b/src/BenchmarkDotNet/Loggers/SynchronousProcessOutputLoggerWithDiagnoser.cs index 4f58d5ff25..ca962bdaf7 100644 --- a/src/BenchmarkDotNet/Loggers/SynchronousProcessOutputLoggerWithDiagnoser.cs +++ b/src/BenchmarkDotNet/Loggers/SynchronousProcessOutputLoggerWithDiagnoser.cs @@ -37,13 +37,11 @@ public SynchronousProcessOutputLoggerWithDiagnoser(ILogger logger, Process proce internal void ProcessInput() { - string line; - // Peek -1 or 0 can indicate internal error. while (!process.StandardOutput.EndOfStream && process.StandardOutput.Peek() > 0) { // ReadLine() can actually return string.Empty and null as valid values. - line = process.StandardOutput.ReadLine(); + string line = process.StandardOutput.ReadLine(); if (!string.IsNullOrEmpty(line)) // Skip bad data. { diff --git a/src/BenchmarkDotNet/Mathematics/ConfidenceInterval.cs b/src/BenchmarkDotNet/Mathematics/ConfidenceInterval.cs index 17aced2d25..3aaeaef6ce 100644 --- a/src/BenchmarkDotNet/Mathematics/ConfidenceInterval.cs +++ b/src/BenchmarkDotNet/Mathematics/ConfidenceInterval.cs @@ -4,6 +4,7 @@ using System.Text; using BenchmarkDotNet.Extensions; using BenchmarkDotNet.Horology; +using JetBrains.Annotations; namespace BenchmarkDotNet.Mathematics { @@ -99,7 +100,7 @@ public static string ToPercentStr(this ConfidenceLevel level) return s + "%"; } - public static double ToPercent(this ConfidenceLevel level) + [PublicAPI] public static double ToPercent(this ConfidenceLevel level) { (int value, int digits) = ConfidenceLevelDetails[level]; @@ -121,15 +122,15 @@ public static double ToPercent(this ConfidenceLevel level) public struct ConfidenceInterval { - public int N { get; } - public double Mean { get; } - public double StandardError { get; } + [PublicAPI] public int N { get; } + [PublicAPI] public double Mean { get; } + [PublicAPI] public double StandardError { get; } - public ConfidenceLevel Level { get; } - public double Margin { get; } + [PublicAPI] public ConfidenceLevel Level { get; } + [PublicAPI] public double Margin { get; } - public double Lower { get; } - public double Upper { get; } + [PublicAPI] public double Lower { get; } + [PublicAPI] public double Upper { get; } public ConfidenceInterval(double mean, double standardError, int n, ConfidenceLevel level = ConfidenceLevel.L999) { diff --git a/src/BenchmarkDotNet/Mathematics/Histograms/HistogramBin.cs b/src/BenchmarkDotNet/Mathematics/Histograms/HistogramBin.cs index 66793b9853..7500e16e03 100644 --- a/src/BenchmarkDotNet/Mathematics/Histograms/HistogramBin.cs +++ b/src/BenchmarkDotNet/Mathematics/Histograms/HistogramBin.cs @@ -3,6 +3,7 @@ using System.Text; using BenchmarkDotNet.Extensions; using BenchmarkDotNet.Horology; +using JetBrains.Annotations; namespace BenchmarkDotNet.Mathematics.Histograms { @@ -31,7 +32,7 @@ public HistogramBin(double lower, double upper, double[] values) public override string ToString() => ToString(Encoding.ASCII); - public string ToString(Encoding encoding) + [PublicAPI] public string ToString(Encoding encoding) { var unit = TimeUnit.GetBestTimeUnit(Values); return $"[{Lower.ToTimeStr(unit, encoding)};{Upper.ToTimeStr(unit, encoding)}) {{{string.Join("; ", Values.Select(v => v.ToTimeStr(unit, encoding)))}}}"; diff --git a/src/BenchmarkDotNet/Mathematics/MathHelper.cs b/src/BenchmarkDotNet/Mathematics/MathHelper.cs index b86f271f5e..5bd8681a3a 100644 --- a/src/BenchmarkDotNet/Mathematics/MathHelper.cs +++ b/src/BenchmarkDotNet/Mathematics/MathHelper.cs @@ -20,6 +20,7 @@ public static class MathHelper /// /// -infinity..+infinity /// Area under the Standard Normal Curve from -infinity to x + [PublicAPI] public static double Gauss(double x) { double z; diff --git a/src/BenchmarkDotNet/Mathematics/MeasurementsStatistics.cs b/src/BenchmarkDotNet/Mathematics/MeasurementsStatistics.cs index bf9fd0c8b9..e4b0086cb2 100644 --- a/src/BenchmarkDotNet/Mathematics/MeasurementsStatistics.cs +++ b/src/BenchmarkDotNet/Mathematics/MeasurementsStatistics.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using BenchmarkDotNet.Reports; +using JetBrains.Annotations; namespace BenchmarkDotNet.Mathematics { @@ -12,6 +13,7 @@ internal struct MeasurementsStatistics /// /// Standard error in nanoseconds. /// + [PublicAPI] public double StandardError { get; } /// diff --git a/src/BenchmarkDotNet/Mathematics/PercentileValues.cs b/src/BenchmarkDotNet/Mathematics/PercentileValues.cs index 4e2adadffe..e1f744f06f 100644 --- a/src/BenchmarkDotNet/Mathematics/PercentileValues.cs +++ b/src/BenchmarkDotNet/Mathematics/PercentileValues.cs @@ -3,6 +3,7 @@ using System.Text; using BenchmarkDotNet.Extensions; using BenchmarkDotNet.Horology; +using JetBrains.Annotations; namespace BenchmarkDotNet.Mathematics { @@ -45,7 +46,7 @@ private static double Percentile(List sortedValues, int percentile) return sortedValues[index]; } - public double Percentile(int percentile) => Percentile(SortedValues, percentile); + [PublicAPI] public double Percentile(int percentile) => Percentile(SortedValues, percentile); private List SortedValues { get; } diff --git a/src/BenchmarkDotNet/Mathematics/Statistics.cs b/src/BenchmarkDotNet/Mathematics/Statistics.cs index bcc8eb2c46..4a73d01525 100644 --- a/src/BenchmarkDotNet/Mathematics/Statistics.cs +++ b/src/BenchmarkDotNet/Mathematics/Statistics.cs @@ -82,14 +82,14 @@ public Statistics(IEnumerable values) Percentiles = new PercentileValues(list); } - public ConfidenceInterval GetConfidenceInterval(ConfidenceLevel level, int n) => new ConfidenceInterval(Mean, StandardError, n, level); - public bool IsLowerOutlier(double value) => value < LowerFence; - public bool IsUpperOutlier(double value) => value > UpperFence; - public bool IsOutlier(double value) => value < LowerFence || value > UpperFence; - public double[] WithoutOutliers() => list.Where(value => !IsOutlier(value)).ToArray(); - public IEnumerable GetValues() => list; + [PublicAPI] public ConfidenceInterval GetConfidenceInterval(ConfidenceLevel level, int n) => new ConfidenceInterval(Mean, StandardError, n, level); + [PublicAPI] public bool IsLowerOutlier(double value) => value < LowerFence; + [PublicAPI] public bool IsUpperOutlier(double value) => value > UpperFence; + [PublicAPI] public bool IsOutlier(double value) => value < LowerFence || value > UpperFence; + [PublicAPI] public double[] WithoutOutliers() => list.Where(value => !IsOutlier(value)).ToArray(); + [PublicAPI] public IEnumerable GetValues() => list; - public double CalcCentralMoment(int k) => list.Average(x => (x - Mean).Pow(k)); + [PublicAPI] public double CalcCentralMoment(int k) => list.Average(x => (x - Mean).Pow(k)); public bool IsActualOutlier(double value, OutlierMode outlierMode) { @@ -147,22 +147,22 @@ public override string ToString() /// /// Statistics for [1/X]. If Min is less then or equal to 0, returns null. /// - public Statistics Invert() => CanBeInverted() ? new Statistics(list.Select(x => 1 / x)) : null; + [PublicAPI] public Statistics Invert() => CanBeInverted() ? new Statistics(list.Select(x => 1 / x)) : null; /// /// Statistics for [X^2]. /// - public Statistics Sqr() => new Statistics(list.Select(x => x * x)); + [PublicAPI] public Statistics Sqr() => new Statistics(list.Select(x => x * x)); /// /// Mean for [X*Y]. /// - public static double MulMean(Statistics x, Statistics y) => x.Mean * y.Mean; + [PublicAPI] public static double MulMean(Statistics x, Statistics y) => x.Mean * y.Mean; /// /// Mean for [X/Y]. /// - public static double DivMean([CanBeNull] Statistics x, [CanBeNull] Statistics y) + [PublicAPI] public static double DivMean([CanBeNull] Statistics x, [CanBeNull] Statistics y) { if (x == null || y == null) return double.NaN; @@ -175,7 +175,7 @@ public static double DivMean([CanBeNull] Statistics x, [CanBeNull] Statistics y) /// /// Variance for [X*Y]. /// - public static double MulVariance(Statistics x, Statistics y) + [PublicAPI] public static double MulVariance(Statistics x, Statistics y) { return x.Sqr().Mean * y.Sqr().Mean - x.Mean.Sqr() * y.Mean.Sqr(); } @@ -183,7 +183,7 @@ public static double MulVariance(Statistics x, Statistics y) /// /// Variance for [X/Y]. /// - public static double DivVariance([CanBeNull] Statistics x, [CanBeNull] Statistics y) + [PublicAPI] public static double DivVariance([CanBeNull] Statistics x, [CanBeNull] Statistics y) { if (x == null || y == null) return double.NaN; diff --git a/src/BenchmarkDotNet/Mathematics/WelchTTest.cs b/src/BenchmarkDotNet/Mathematics/WelchTTest.cs index ed733e82b2..c89fcc0d6c 100644 --- a/src/BenchmarkDotNet/Mathematics/WelchTTest.cs +++ b/src/BenchmarkDotNet/Mathematics/WelchTTest.cs @@ -1,5 +1,6 @@ using System; using BenchmarkDotNet.Extensions; +using JetBrains.Annotations; using static System.Math; namespace BenchmarkDotNet.Mathematics @@ -11,7 +12,7 @@ public class WelchTTest public double PValue { get; } public bool NullHypothesisIsRejected => PValue < 0.05; - public WelchTTest(double x, double df, double pValue) + [PublicAPI] public WelchTTest(double x, double df, double pValue) { T = x; Df = df; diff --git a/src/BenchmarkDotNet/Order/DefaultOrderer.cs b/src/BenchmarkDotNet/Order/DefaultOrderer.cs index 8cbb00fe74..f21234ecf4 100644 --- a/src/BenchmarkDotNet/Order/DefaultOrderer.cs +++ b/src/BenchmarkDotNet/Order/DefaultOrderer.cs @@ -135,7 +135,7 @@ public int Compare(BenchmarkCase x, BenchmarkCase y) => new[] private class LogicalGroupComparer : IComparer> { - private IComparer benchmarkComparer; + private readonly IComparer benchmarkComparer; public LogicalGroupComparer(IComparer benchmarkComparer) => this.benchmarkComparer = benchmarkComparer; diff --git a/src/BenchmarkDotNet/Parameters/ParameterDefinitions.cs b/src/BenchmarkDotNet/Parameters/ParameterDefinitions.cs index 0213b8c810..c9774afe5d 100644 --- a/src/BenchmarkDotNet/Parameters/ParameterDefinitions.cs +++ b/src/BenchmarkDotNet/Parameters/ParameterDefinitions.cs @@ -1,12 +1,13 @@ using System.Collections.Generic; using System.Linq; using BenchmarkDotNet.Extensions; +using JetBrains.Annotations; namespace BenchmarkDotNet.Parameters { public class ParameterDefinitions { - public IReadOnlyList Items { get; } + [PublicAPI] public IReadOnlyList Items { get; } public ParameterDefinitions(IReadOnlyList items) { diff --git a/src/BenchmarkDotNet/Parameters/ParameterInstance.cs b/src/BenchmarkDotNet/Parameters/ParameterInstance.cs index e5b3aa0c07..c73da69680 100644 --- a/src/BenchmarkDotNet/Parameters/ParameterInstance.cs +++ b/src/BenchmarkDotNet/Parameters/ParameterInstance.cs @@ -2,6 +2,7 @@ using BenchmarkDotNet.Code; using BenchmarkDotNet.Extensions; using BenchmarkDotNet.Helpers; +using JetBrains.Annotations; namespace BenchmarkDotNet.Parameters { @@ -10,7 +11,7 @@ public class ParameterInstance public const string NullParameterTextRepresentation = "?"; private const int MaxDisplayTextInnerLength = 15 + 5; // 5 is for postfix " [15]" - public ParameterDefinition Definition { get; } + [PublicAPI] public ParameterDefinition Definition { get; } private readonly object value; @@ -47,7 +48,7 @@ public string ToDisplayText() public override string ToString() => ToDisplayText(); - private string Trim(string value) + private static string Trim(string value) => value.Length <= MaxDisplayTextInnerLength ? value : value.Substring(0, 5) + "(...)" + value.Substring(value.Length - 5, 5) + $" [{value.Length}]"; diff --git a/src/BenchmarkDotNet/Portability/Antivirus.cs b/src/BenchmarkDotNet/Portability/Antivirus.cs index 55722fe185..b7c662ed64 100644 --- a/src/BenchmarkDotNet/Portability/Antivirus.cs +++ b/src/BenchmarkDotNet/Portability/Antivirus.cs @@ -1,4 +1,6 @@ -namespace BenchmarkDotNet.Portability +using JetBrains.Annotations; + +namespace BenchmarkDotNet.Portability { public class Antivirus { @@ -8,8 +10,8 @@ public Antivirus(string name, string path) Path = path; } - public string Name { get; } - public string Path { get; } + [PublicAPI] public string Name { get; } + [PublicAPI] public string Path { get; } public override string ToString() => $"{Name} ({Path})"; } diff --git a/src/BenchmarkDotNet/Portability/Cpu/MosCpuInfoProvider.cs b/src/BenchmarkDotNet/Portability/Cpu/MosCpuInfoProvider.cs index bf70d306c6..c1d35d3078 100644 --- a/src/BenchmarkDotNet/Portability/Cpu/MosCpuInfoProvider.cs +++ b/src/BenchmarkDotNet/Portability/Cpu/MosCpuInfoProvider.cs @@ -9,7 +9,7 @@ namespace BenchmarkDotNet.Portability.Cpu { internal static class MosCpuInfoProvider { - internal static Lazy MosCpuInfo = new Lazy(Load); + internal static readonly Lazy MosCpuInfo = new Lazy(Load); [NotNull] private static CpuInfo Load() diff --git a/src/BenchmarkDotNet/Portability/Cpu/ProcCpuInfoParser.cs b/src/BenchmarkDotNet/Portability/Cpu/ProcCpuInfoParser.cs index d204e21216..0bd7c31695 100644 --- a/src/BenchmarkDotNet/Portability/Cpu/ProcCpuInfoParser.cs +++ b/src/BenchmarkDotNet/Portability/Cpu/ProcCpuInfoParser.cs @@ -61,7 +61,7 @@ internal static CpuInfo ParseOutput([CanBeNull] string content) internal static Frequency ParseFrequencyFromBrandString(string brandString) { - string pattern = "(\\d.\\d+)GHz"; + const string pattern = "(\\d.\\d+)GHz"; var matches = Regex.Matches(brandString, pattern, RegexOptions.IgnoreCase); if (matches.Count > 0 && matches[0].Groups.Count > 1) { diff --git a/src/BenchmarkDotNet/Portability/RuntimeInformation.cs b/src/BenchmarkDotNet/Portability/RuntimeInformation.cs index 438dd85ff6..6b8d76d136 100644 --- a/src/BenchmarkDotNet/Portability/RuntimeInformation.cs +++ b/src/BenchmarkDotNet/Portability/RuntimeInformation.cs @@ -155,7 +155,7 @@ internal static CpuInfo GetCpuInfo() return null; } - public static string GetNetCoreVersion() + private static string GetNetCoreVersion() { var assembly = typeof(GCSettings).GetTypeInfo().Assembly; var assemblyPath = assembly.CodeBase.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries); @@ -231,7 +231,7 @@ internal static Runtime GetCurrentRuntime() public static Platform GetCurrentPlatform() => IntPtr.Size == 4 ? Platform.X86 : Platform.X64; - internal static IEnumerable GetJitModules() + private static IEnumerable GetJitModules() { return Process.GetCurrentProcess().Modules @@ -308,7 +308,7 @@ public bool IsMsX64(int step = 1) } } - public class JitModule + private class JitModule { public string Name { get; } public string Version { get; } diff --git a/src/BenchmarkDotNet/Portability/VirtualMachineHypervisor.cs b/src/BenchmarkDotNet/Portability/VirtualMachineHypervisor.cs index 23bea9a3d1..0950aba850 100644 --- a/src/BenchmarkDotNet/Portability/VirtualMachineHypervisor.cs +++ b/src/BenchmarkDotNet/Portability/VirtualMachineHypervisor.cs @@ -6,7 +6,7 @@ public abstract class VirtualMachineHypervisor public abstract bool IsVirtualMachine(string manufacturer, string model); - protected bool ContainsVmIdentifier(string systemInformation, string vmIdentifier) + protected static bool ContainsVmIdentifier(string systemInformation, string vmIdentifier) { return systemInformation != null && systemInformation.ContainsWithIgnoreCase(vmIdentifier); } diff --git a/src/BenchmarkDotNet/Properties/BenchmarkDotNetInfo.cs b/src/BenchmarkDotNet/Properties/BenchmarkDotNetInfo.cs index c1e5058c6d..ee0322a33a 100644 --- a/src/BenchmarkDotNet/Properties/BenchmarkDotNetInfo.cs +++ b/src/BenchmarkDotNet/Properties/BenchmarkDotNetInfo.cs @@ -4,6 +4,7 @@ namespace BenchmarkDotNet.Properties { + [SuppressMessage("ReSharper", "MemberCanBePrivate.Global")] public static class BenchmarkDotNetInfo { #if PRERELEASE_NIGHTLY diff --git a/src/BenchmarkDotNet/Reports/BenchmarkReport.cs b/src/BenchmarkDotNet/Reports/BenchmarkReport.cs index 66b21e76f5..b100c69a11 100644 --- a/src/BenchmarkDotNet/Reports/BenchmarkReport.cs +++ b/src/BenchmarkDotNet/Reports/BenchmarkReport.cs @@ -15,8 +15,8 @@ public sealed class BenchmarkReport public IReadOnlyList AllMeasurements { get; } public GcStats GcStats { get; } - public GenerateResult GenerateResult { get; } - public BuildResult BuildResult { get; } + [PublicAPI] public GenerateResult GenerateResult { get; } + [PublicAPI] public BuildResult BuildResult { get; } [NotNull] public IReadOnlyList ExecuteResults { get; } diff --git a/src/BenchmarkDotNet/Reports/Measurement.cs b/src/BenchmarkDotNet/Reports/Measurement.cs index 391c73e274..005d895e11 100644 --- a/src/BenchmarkDotNet/Reports/Measurement.cs +++ b/src/BenchmarkDotNet/Reports/Measurement.cs @@ -25,8 +25,8 @@ private static readonly int IterationInfoNameMaxWidth public int LaunchIndex { get; } public int IterationIndex { get; } - - public Encoding Encoding { get; } + + private Encoding Encoding { get; } /// /// Gets the number of operations performed. diff --git a/src/BenchmarkDotNet/Reports/Summary.cs b/src/BenchmarkDotNet/Reports/Summary.cs index a25f28bff9..34c79c5ed8 100644 --- a/src/BenchmarkDotNet/Reports/Summary.cs +++ b/src/BenchmarkDotNet/Reports/Summary.cs @@ -19,19 +19,19 @@ public class Summary public string Title { get; } public BenchmarkCase[] BenchmarksCases { get; } public BenchmarkReport[] Reports { get; } - public ISummaryStyle Style { get; } + [PublicAPI] public ISummaryStyle Style { get; } public HostEnvironmentInfo HostEnvironmentInfo { get; } public IConfig Config { get; } public string ResultsDirectoryPath { get; } public SummaryTable Table { get; } - public TimeSpan TotalTime { get; } - public ValidationError[] ValidationErrors { get; } + [PublicAPI] public TimeSpan TotalTime { get; } + [PublicAPI] public ValidationError[] ValidationErrors { get; } public string AllRuntimes { get; } private readonly Dictionary reportMap = new Dictionary(); private readonly IOrderer orderer; - public bool HasReport(BenchmarkCase benchmarkCase) => reportMap.ContainsKey(benchmarkCase); + [PublicAPI] public bool HasReport(BenchmarkCase benchmarkCase) => reportMap.ContainsKey(benchmarkCase); /// /// Returns a report for the given benchmark or null if there is no a corresponded report. diff --git a/src/BenchmarkDotNet/Reports/SummaryStyle.cs b/src/BenchmarkDotNet/Reports/SummaryStyle.cs index 3c5cc44d34..352e4abe94 100644 --- a/src/BenchmarkDotNet/Reports/SummaryStyle.cs +++ b/src/BenchmarkDotNet/Reports/SummaryStyle.cs @@ -5,10 +5,10 @@ namespace BenchmarkDotNet.Reports { public class SummaryStyle : ISummaryStyle { - public bool PrintUnitsInHeader { get; set; } - public bool PrintUnitsInContent { get; set; } = true; - public SizeUnit SizeUnit { get; set; } - public TimeUnit TimeUnit { get; set; } + public bool PrintUnitsInHeader { get; private set; } + public bool PrintUnitsInContent { get; private set; } = true; + public SizeUnit SizeUnit { get; private set; } + public TimeUnit TimeUnit { get; private set; } public static SummaryStyle Default => new SummaryStyle { diff --git a/src/BenchmarkDotNet/Reports/SummaryTable.cs b/src/BenchmarkDotNet/Reports/SummaryTable.cs index f888f5be5b..ae9c51b6bd 100644 --- a/src/BenchmarkDotNet/Reports/SummaryTable.cs +++ b/src/BenchmarkDotNet/Reports/SummaryTable.cs @@ -5,12 +5,13 @@ using BenchmarkDotNet.Extensions; using BenchmarkDotNet.Horology; using BenchmarkDotNet.Order; +using JetBrains.Annotations; namespace BenchmarkDotNet.Reports { public class SummaryTable { - public Summary Summary { get; } + [PublicAPI] public Summary Summary { get; } public SummaryTableColumn[] Columns { get; } public int ColumnCount { get; } @@ -20,7 +21,7 @@ public class SummaryTable public bool[] FullContentStartOfHighlightGroup { get; } public bool[] FullContentStartOfLogicalGroup { get; } public string[][] FullContentWithHeader { get; } - public bool[] IsDefault { get; } + [PublicAPI] public bool[] IsDefault { get; } public ISummaryStyle EffectiveSummaryStyle { get; } public bool SeparateLogicalGroups { get; } @@ -93,7 +94,7 @@ internal SummaryTable(Summary summary, ISummaryStyle style = null) public class SummaryTableColumn { - public int Index { get; } + [PublicAPI] public int Index { get; } public string Header { get; } public string[] Content { get; } public bool NeedToShow { get; } diff --git a/src/BenchmarkDotNet/Running/BenchmarkPartitioner.cs b/src/BenchmarkDotNet/Running/BenchmarkPartitioner.cs index e8bdae2267..9007261d19 100644 --- a/src/BenchmarkDotNet/Running/BenchmarkPartitioner.cs +++ b/src/BenchmarkDotNet/Running/BenchmarkPartitioner.cs @@ -82,12 +82,12 @@ public int GetHashCode(BenchmarkCase obj) return hashCode; } - private Runtime GetRuntime(Job job) + private static Runtime GetRuntime(Job job) => job.Environment.HasValue(EnvironmentMode.RuntimeCharacteristic) ? job.Environment.Runtime : Current; - private bool AreDifferent(object x, object y) + private static bool AreDifferent(object x, object y) { if (x == null && y == null) return false; @@ -97,7 +97,7 @@ private bool AreDifferent(object x, object y) return !x.Equals(y); } - private bool AreDifferent(IReadOnlyList x, IReadOnlyList y) + private static bool AreDifferent(IReadOnlyList x, IReadOnlyList y) { if (x == null && y == null) return false; diff --git a/src/BenchmarkDotNet/Running/BenchmarkSwitcher.cs b/src/BenchmarkDotNet/Running/BenchmarkSwitcher.cs index 1d92095cf5..c1e391675e 100644 --- a/src/BenchmarkDotNet/Running/BenchmarkSwitcher.cs +++ b/src/BenchmarkDotNet/Running/BenchmarkSwitcher.cs @@ -8,6 +8,7 @@ using BenchmarkDotNet.Horology; using BenchmarkDotNet.Loggers; using BenchmarkDotNet.Reports; +using JetBrains.Annotations; namespace BenchmarkDotNet.Running { @@ -16,7 +17,7 @@ public class BenchmarkSwitcher private readonly ConsoleLogger logger = new ConsoleLogger(); private readonly TypeParser typeParser; - public BenchmarkSwitcher(Type[] types) + [PublicAPI] public BenchmarkSwitcher(Type[] types) { foreach (var type in types.Where(type => !type.ContainsRunnableBenchmarks()).ToArray()) { @@ -26,37 +27,37 @@ public BenchmarkSwitcher(Type[] types) typeParser = new TypeParser(types.Where(type => type.ContainsRunnableBenchmarks()).ToArray(), logger); } - public BenchmarkSwitcher(Assembly assembly) + [PublicAPI] public BenchmarkSwitcher(Assembly assembly) { typeParser = new TypeParser(assembly.GetRunnableBenchmarks(), logger); } - public BenchmarkSwitcher(Assembly[] assemblies) + [PublicAPI] public BenchmarkSwitcher(Assembly[] assemblies) { var runnableBenchmarkTypes = assemblies.SelectMany(a => a.GetRunnableBenchmarks()).ToArray(); typeParser = new TypeParser(runnableBenchmarkTypes, logger); } - public static BenchmarkSwitcher FromTypes(Type[] types) => new BenchmarkSwitcher(types); + [PublicAPI] public static BenchmarkSwitcher FromTypes(Type[] types) => new BenchmarkSwitcher(types); - public static BenchmarkSwitcher FromAssembly(Assembly assembly) => new BenchmarkSwitcher(assembly); + [PublicAPI] public static BenchmarkSwitcher FromAssembly(Assembly assembly) => new BenchmarkSwitcher(assembly); - public static BenchmarkSwitcher FromAssemblies(Assembly[] assemblies) => new BenchmarkSwitcher(assemblies); + [PublicAPI] public static BenchmarkSwitcher FromAssemblies(Assembly[] assemblies) => new BenchmarkSwitcher(assemblies); - public static BenchmarkSwitcher FromAssemblyAndTypes(Assembly assembly, Type[] types) + [PublicAPI] public static BenchmarkSwitcher FromAssemblyAndTypes(Assembly assembly, Type[] types) => new BenchmarkSwitcher(assembly.GetRunnableBenchmarks().Concat(types).ToArray()); /// /// Run all available benchmarks. /// - public IEnumerable RunAll() => Run(new[] { "--filter", "*" }); + [PublicAPI] public IEnumerable RunAll() => Run(new[] { "--filter", "*" }); /// /// Run all available benchmarks and join them to a single summary /// - public Summary RunAllJoined() => Run(new[] { "--filter", "*", "--join" }).Single(); + [PublicAPI] public Summary RunAllJoined() => Run(new[] { "--filter", "*", "--join" }).Single(); - public IEnumerable Run(string[] args = null, IConfig config = null) + [PublicAPI] public IEnumerable Run(string[] args = null, IConfig config = null) { args = args ?? Array.Empty(); @@ -79,7 +80,5 @@ public IEnumerable Run(string[] args = null, IConfig config = null) BenchmarkRunner.LogTotalTime(logger, globalChronometer.GetElapsed().GetTimeSpan(), totalNumberOfExecutedBenchmarks, "Global total time"); return summaries; } - - } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Toolchains/ArtifactsPaths.cs b/src/BenchmarkDotNet/Toolchains/ArtifactsPaths.cs index 61a1291e78..95d59abd8a 100644 --- a/src/BenchmarkDotNet/Toolchains/ArtifactsPaths.cs +++ b/src/BenchmarkDotNet/Toolchains/ArtifactsPaths.cs @@ -1,30 +1,22 @@ +using JetBrains.Annotations; + namespace BenchmarkDotNet.Toolchains { public class ArtifactsPaths { - public static ArtifactsPaths Empty = new ArtifactsPaths("", "", "", "", "", "", "", "", "", "", ""); - - public string RootArtifactsFolderPath { get; } - - public string BuildArtifactsDirectoryPath { get; } - - public string BinariesDirectoryPath { get; } - - public string ProgramCodePath { get; } - - public string AppConfigPath { get; } - - public string NuGetConfigPath { get; } - - public string ProjectFilePath { get; } - - public string BuildScriptFilePath { get; } - - public string ExecutablePath { get; } - - public string ProgramName { get; } - - public string PackagesDirectoryName { get; } + public static readonly ArtifactsPaths Empty = new ArtifactsPaths("", "", "", "", "", "", "", "", "", "", ""); + + [PublicAPI] public string RootArtifactsFolderPath { get; } + [PublicAPI] public string BuildArtifactsDirectoryPath { get; } + [PublicAPI] public string BinariesDirectoryPath { get; } + [PublicAPI] public string ProgramCodePath { get; } + [PublicAPI] public string AppConfigPath { get; } + [PublicAPI] public string NuGetConfigPath { get; } + [PublicAPI] public string ProjectFilePath { get; } + [PublicAPI] public string BuildScriptFilePath { get; } + [PublicAPI] public string ExecutablePath { get; } + [PublicAPI] public string ProgramName { get; } + [PublicAPI] public string PackagesDirectoryName { get; } public ArtifactsPaths( string rootArtifactsFolderPath, diff --git a/src/BenchmarkDotNet/Toolchains/ConsoleHandler.cs b/src/BenchmarkDotNet/Toolchains/ConsoleHandler.cs index 11847e5654..cfa11d4e78 100644 --- a/src/BenchmarkDotNet/Toolchains/ConsoleHandler.cs +++ b/src/BenchmarkDotNet/Toolchains/ConsoleHandler.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Threading; using BenchmarkDotNet.Loggers; +using JetBrains.Annotations; namespace BenchmarkDotNet.Toolchains { @@ -11,13 +12,13 @@ internal class ConsoleHandler // This needs to be static, so that we can share a single handler amongst all instances of Executor's internal static ConsoleHandler Instance; - public ConsoleCancelEventHandler EventHandler { get; private set; } + [PublicAPI] public ConsoleCancelEventHandler EventHandler { get; } private Process process; - private ILogger logger; + private readonly ILogger logger; private ConsoleColor? colorBefore; - public ConsoleHandler(ILogger logger) + [PublicAPI] public ConsoleHandler(ILogger logger) { this.logger = logger; EventHandler = HandlerCallback; @@ -99,7 +100,7 @@ public override string ToString() return $"Process: {processId}, Handler: {EventHandler?.GetHashCode()}"; } - private bool HasProcessDied(Process process) + private static bool HasProcessDied(Process process) { if (process == null) return true; diff --git a/src/BenchmarkDotNet/Toolchains/CoreRt/CoreRtToolchainBuilder.cs b/src/BenchmarkDotNet/Toolchains/CoreRt/CoreRtToolchainBuilder.cs index 047f4d72c0..8064a69d42 100644 --- a/src/BenchmarkDotNet/Toolchains/CoreRt/CoreRtToolchainBuilder.cs +++ b/src/BenchmarkDotNet/Toolchains/CoreRt/CoreRtToolchainBuilder.cs @@ -27,7 +27,7 @@ public CoreRtToolchainBuilder UseCoreRtNuGet(string microsoftDotNetILCompilerVer coreRtVersion = microsoftDotNetILCompilerVersion; - feeds[Generator.CoreRtNuGetFeed] = nugetFeedUrl; + Feeds[Generator.CoreRtNuGetFeed] = nugetFeedUrl; isCoreRtConfigured = true; @@ -79,7 +79,7 @@ public override IToolchain ToToolchain() targetFrameworkMoniker: targetFrameworkMoniker, runtimeIdentifier: runtimeIdentifier ?? GetPortableRuntimeIdentifier(), customDotNetCliPath: customDotNetCliPath, - feeds: feeds, + feeds: Feeds, useNuGetClearTag: useNuGetClearTag, useTempFolderForRestore: useTempFolderForRestore); } diff --git a/src/BenchmarkDotNet/Toolchains/CustomCoreClr/CustomCoreClrToolchainBuilder.cs b/src/BenchmarkDotNet/Toolchains/CustomCoreClr/CustomCoreClrToolchainBuilder.cs index 7a03ba3eb1..0d676d0ff7 100644 --- a/src/BenchmarkDotNet/Toolchains/CustomCoreClr/CustomCoreClrToolchainBuilder.cs +++ b/src/BenchmarkDotNet/Toolchains/CustomCoreClr/CustomCoreClrToolchainBuilder.cs @@ -28,8 +28,8 @@ public CustomCoreClrToolchainBuilder UseCoreClrLocalBuild(string coreClrVersion, this.coreClrVersion = coreClrVersion; - feeds[Generator.LocalCoreClrPackagesBin] = binPackagesPath; - feeds[Generator.LocalCoreClrPackages] = packagesPath; + Feeds[Generator.LocalCoreClrPackagesBin] = binPackagesPath; + Feeds[Generator.LocalCoreClrPackages] = packagesPath; isCoreClrConfigured = true; useTempFolderForRestore = true; @@ -49,7 +49,7 @@ public CustomCoreClrToolchainBuilder UseCoreClrNuGet(string coreClrVersion, stri this.coreClrVersion = coreClrVersion; - feeds[Generator.CoreClrNuGetFeed] = nugetFeedUrl; + Feeds[Generator.CoreClrNuGetFeed] = nugetFeedUrl; isCoreClrConfigured = true; @@ -79,7 +79,7 @@ public CustomCoreClrToolchainBuilder UseCoreFxLocalBuild(string privateCoreFxNet if (!Directory.Exists(binPackagesPath)) throw new DirectoryNotFoundException($"{binPackagesPath} does not exist"); coreFxVersion = privateCoreFxNetCoreAppVersion; - feeds[Generator.LocalCoreFxPackagesBin] = binPackagesPath; + Feeds[Generator.LocalCoreFxPackagesBin] = binPackagesPath; isCoreFxConfigured = true; useTempFolderForRestore = true; @@ -97,7 +97,7 @@ public CustomCoreClrToolchainBuilder UseCoreFxNuGet(string privateCoreFxNetCoreA if (nugetFeedUrl == null) throw new ArgumentNullException(nameof(nugetFeedUrl)); coreFxVersion = privateCoreFxNetCoreAppVersion; - feeds[Generator.CoreFxNuGetFeed] = nugetFeedUrl; + Feeds[Generator.CoreFxNuGetFeed] = nugetFeedUrl; isCoreFxConfigured = true; return this; @@ -129,7 +129,7 @@ public override IToolchain ToToolchain() targetFrameworkMoniker: targetFrameworkMoniker, runtimeIdentifier: runtimeIdentifier ?? GetPortableRuntimeIdentifier(), customDotNetCliPath: customDotNetCliPath, - feeds: feeds, + feeds: Feeds, useNuGetClearTag: useNuGetClearTag, useTempFolderForRestore: useTempFolderForRestore); } diff --git a/src/BenchmarkDotNet/Toolchains/DotNetCli/CustomDotNetCliToolchainBuilder.cs b/src/BenchmarkDotNet/Toolchains/DotNetCli/CustomDotNetCliToolchainBuilder.cs index c5ea2c9663..4d9f997f4f 100644 --- a/src/BenchmarkDotNet/Toolchains/DotNetCli/CustomDotNetCliToolchainBuilder.cs +++ b/src/BenchmarkDotNet/Toolchains/DotNetCli/CustomDotNetCliToolchainBuilder.cs @@ -1,10 +1,12 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.IO; using Microsoft.DotNet.PlatformAbstractions; namespace BenchmarkDotNet.Toolchains.DotNetCli { + [SuppressMessage("ReSharper", "InconsistentNaming")] public abstract class CustomDotNetCliToolchainBuilder { protected string runtimeIdentifier, customDotNetCliPath; @@ -12,7 +14,7 @@ public abstract class CustomDotNetCliToolchainBuilder protected string runtimeFrameworkVersion; protected bool useNuGetClearTag, useTempFolderForRestore; - protected Dictionary feeds = new Dictionary(); + protected readonly Dictionary Feeds = new Dictionary(); public abstract IToolchain ToToolchain(); @@ -24,7 +26,7 @@ public CustomDotNetCliToolchainBuilder AdditionalNuGetFeed(string feedName, stri if (string.IsNullOrEmpty(feedName)) throw new ArgumentException("Value cannot be null or empty.", nameof(feedName)); if (string.IsNullOrEmpty(feedAddress)) throw new ArgumentException("Value cannot be null or empty.", nameof(feedAddress)); - feeds[feedName] = feedAddress; + Feeds[feedName] = feedAddress; return this; } diff --git a/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliCommandExecutor.cs b/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliCommandExecutor.cs index b8ec1aaf05..a7c2c4b179 100644 --- a/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliCommandExecutor.cs +++ b/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliCommandExecutor.cs @@ -6,6 +6,7 @@ using System.Text.RegularExpressions; using BenchmarkDotNet.Jobs; using BenchmarkDotNet.Loggers; +using JetBrains.Annotations; namespace BenchmarkDotNet.Toolchains.DotNetCli { @@ -15,11 +16,11 @@ internal struct CommandResult { public bool IsSuccess { get; } - public TimeSpan ExecutionTime { get; } + [PublicAPI] public TimeSpan ExecutionTime { get; } - public string StandardOutput { get; } + [PublicAPI] public string StandardOutput { get; } - public string StandardError { get; } + [PublicAPI] public string StandardError { get; } /// /// in theory, all errors should be reported to standard error, @@ -28,7 +29,7 @@ internal struct CommandResult /// public string ProblemDescription => HasNonEmptyErrorMessage ? StandardError : StandardOutput; - public bool HasNonEmptyErrorMessage => !string.IsNullOrEmpty(StandardError); + [PublicAPI] public bool HasNonEmptyErrorMessage => !string.IsNullOrEmpty(StandardError); private CommandResult(bool isSuccess, TimeSpan executionTime, string standardOutput, string standardError) { @@ -114,7 +115,7 @@ internal static ProcessStartInfo BuildStartInfo(string customDotNetCliPath, stri foreach (var environmentVariable in environmentVariables) startInfo.EnvironmentVariables[environmentVariable.Key] = environmentVariable.Value; - if (!string.IsNullOrEmpty(customDotNetCliPath) && (environmentVariables == null || !environmentVariables.Any(envVar => envVar.Key == dotnetMultiLevelLookupEnvVarName))) + if (!string.IsNullOrEmpty(customDotNetCliPath) && (environmentVariables == null || environmentVariables.All(envVar => envVar.Key != dotnetMultiLevelLookupEnvVarName))) startInfo.EnvironmentVariables[dotnetMultiLevelLookupEnvVarName] = "0"; return startInfo; diff --git a/src/BenchmarkDotNet/Toolchains/InProcess/InProcessHost.cs b/src/BenchmarkDotNet/Toolchains/InProcess/InProcessHost.cs index de7d89c4d1..d7b9965221 100644 --- a/src/BenchmarkDotNet/Toolchains/InProcess/InProcessHost.cs +++ b/src/BenchmarkDotNet/Toolchains/InProcess/InProcessHost.cs @@ -52,14 +52,14 @@ public InProcessHost(BenchmarkCase benchmarkCase, ILogger logger, IDiagnoser dia /// True if there are diagnosers attached. /// True if there are diagnosers attached. - public bool IsDiagnoserAttached { get; } + [PublicAPI] public bool IsDiagnoserAttached { get; } /// Results of the run. /// Results of the run. public RunResults RunResults { get; private set; } /// Current config - public IConfig Config { get; set; } + [PublicAPI] public IConfig Config { get; set; } /// Passes text to the host. /// Text to write. diff --git a/src/BenchmarkDotNet/Validators/CompilationValidator.cs b/src/BenchmarkDotNet/Validators/CompilationValidator.cs index 15b2fe85e6..4177b2f030 100644 --- a/src/BenchmarkDotNet/Validators/CompilationValidator.cs +++ b/src/BenchmarkDotNet/Validators/CompilationValidator.cs @@ -21,7 +21,7 @@ public IEnumerable Validate(ValidationParameters validationPara .Union(ValidateNamingConflicts(validationParameters.Benchmarks)) .Union(ValidateAccessModifiers(validationParameters.Benchmarks)); - private IEnumerable ValidateCSharpNaming(IEnumerable benchmarks) + private static IEnumerable ValidateCSharpNaming(IEnumerable benchmarks) => benchmarks .Where(benchmark => !IsValidCSharpIdentifier(benchmark.Descriptor.WorkloadMethod.Name)) .Distinct(BenchmarkMethodEqualityComparer.Instance) // we might have multiple jobs targeting same method. Single error should be enough ;) @@ -32,7 +32,7 @@ private IEnumerable ValidateCSharpNaming(IEnumerable ValidateNamingConflicts(IEnumerable benchmarks) + private static IEnumerable ValidateNamingConflicts(IEnumerable benchmarks) => benchmarks .Select(benchmark => benchmark.Descriptor.Type) .Distinct() @@ -42,22 +42,22 @@ private IEnumerable ValidateNamingConflicts(IEnumerable ValidateAccessModifiers(IEnumerable benchmarks) + private static IEnumerable ValidateAccessModifiers(IEnumerable benchmarks) => benchmarks.Where(x => x.Descriptor.Type.IsGenericType && HasPrivateGenericArguments(x.Descriptor.Type)) .Select(benchmark => new ValidationError(true, $"Generic class {benchmark.Descriptor.Type.GetDisplayName()} has non public generic argument(s)")); - private bool IsValidCSharpIdentifier(string identifier) // F# allows to use whitespaces as names #479 + private static bool IsValidCSharpIdentifier(string identifier) // F# allows to use whitespaces as names #479 => !string.IsNullOrEmpty(identifier) && (char.IsLetter(identifier[0]) || identifier[0] == Underscore) // An identifier must start with a letter or an underscore && identifier .Skip(1) .All(character => char.IsLetterOrDigit(character) || character == Underscore); - private bool IsUsingNameUsedInternallyByOurTemplate(string identifier) + private static bool IsUsingNameUsedInternallyByOurTemplate(string identifier) => identifier == "__Overhead"; - private bool HasPrivateGenericArguments(Type type) => type.GetGenericArguments().Any(a => !(a.IsPublic + private static bool HasPrivateGenericArguments(Type type) => type.GetGenericArguments().Any(a => !(a.IsPublic || a.IsNestedPublic)); private class BenchmarkMethodEqualityComparer : IEqualityComparer diff --git a/src/BenchmarkDotNet/Validators/ValidationError.cs b/src/BenchmarkDotNet/Validators/ValidationError.cs index 549267c37b..9cd57fa67c 100644 --- a/src/BenchmarkDotNet/Validators/ValidationError.cs +++ b/src/BenchmarkDotNet/Validators/ValidationError.cs @@ -1,4 +1,5 @@ using BenchmarkDotNet.Running; +using JetBrains.Annotations; namespace BenchmarkDotNet.Validators { @@ -11,12 +12,10 @@ public ValidationError(bool isCritical, string message, BenchmarkCase benchmarkC BenchmarkCase = benchmarkCase; } - public bool IsCritical { get; } - - public string Message { get; } - - public BenchmarkCase BenchmarkCase { get; } - + [PublicAPI] public bool IsCritical { get; } + [PublicAPI] public string Message { get; } + [PublicAPI] public BenchmarkCase BenchmarkCase { get; } + public override string ToString() => Message; } } \ No newline at end of file