Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C#: Change string.Format calls to interpolated strings #16857

Merged
merged 1 commit into from
Jun 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion csharp/autobuilder/Semmle.Autobuild.CSharp/DotNetRule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public BuildScript Analyse(IAutobuilder<CSharpAutobuildOptions> builder, bool au

if (notDotNetProject is not null)
{
builder.Logger.Log(Severity.Info, "Not using .NET Core because of incompatible project {0}", notDotNetProject);
builder.Logger.LogInfo($"Not using .NET Core because of incompatible project {notDotNetProject}");
return BuildScript.Failure;
}

Expand Down
4 changes: 2 additions & 2 deletions csharp/autobuilder/Semmle.Autobuild.CSharp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,12 @@ public static int Main()
}
catch (InvalidEnvironmentException ex)
{
Console.WriteLine("The environment is invalid: {0}", ex.Message);
Console.WriteLine($"The environment is invalid: {ex.Message}");
}
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine("The value \"{0}\" for parameter \"{1}\" is invalid", ex.ActualValue, ex.ParamName);
Console.WriteLine($"The value \"{ex.ActualValue}\" for parameter \"{ex.ParamName}\" is invalid");
}
return 1;
}
Expand Down
4 changes: 2 additions & 2 deletions csharp/autobuilder/Semmle.Autobuild.Cpp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,12 @@ static int Main()
}
catch (InvalidEnvironmentException ex)
{
Console.WriteLine("The environment is invalid: {0}", ex.Message);
Console.WriteLine($"The environment is invalid: {ex.Message}");
}
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine("The value \"{0}\" for parameter \"{1}\" is invalid", ex.ActualValue, ex.ParamName);
Console.WriteLine($"The value \"{ex.ActualValue}\" for parameter \"{ex.ParamName}\" is invalid");
}
return 1;
}
Expand Down
4 changes: 2 additions & 2 deletions csharp/autobuilder/Semmle.Autobuild.Shared/MsBuildRule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -128,9 +128,9 @@ BuildScript GetNugetRestoreScript() =>

command.Argument("/t:" + target);
if (platform is not null)
command.Argument(string.Format("/p:Platform=\"{0}\"", platform));
command.Argument($"/p:Platform=\"{platform}\"");
if (configuration is not null)
command.Argument(string.Format("/p:Configuration=\"{0}\"", configuration));
command.Argument($"/p:Configuration=\"{configuration}\"");

// append the build script which invokes msbuild to the overall build script `ret`;
// we insert a check that building the current project or solution was successful:
Expand Down
2 changes: 1 addition & 1 deletion csharp/autobuilder/Semmle.Autobuild.Shared/Project.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public Project(Autobuilder<TAutobuildOptions> builder, string path) : base(build
catch // lgtm[cs/catch-of-all-exceptions]
// Generic catch clause - Version constructor throws about 5 different exceptions.
{
builder.Logger.Log(Severity.Warning, "Project {0} has invalid tools version {1}", path, toolsVersion);
builder.Logger.LogWarning($"Project {path} has invalid tools version {toolsVersion}");
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,11 @@ public string Id
{
var result = Name;
if (Version is not null)
result = string.Format("{0}, Version={1}", result, Version);
result = $"{result}, Version={Version}";
if (Culture is not null)
result = string.Format("{0}, Culture={1}", result, Culture);
result = $"{result}, Culture={Culture}";
if (PublicKeyToken is not null)
result = string.Format("{0}, PublicKeyToken={1}", result, PublicKeyToken);
result = $"{result}, PublicKeyToken={PublicKeyToken}";
return result;
}
}
Expand All @@ -82,8 +82,8 @@ public IEnumerable<string> IndexStrings
if (Version is not null)
{
if (Culture is not null)
yield return string.Format("{0}, Version={1}, Culture={2}", Name, Version, Culture);
yield return string.Format("{0}, Version={1}", Name, Version);
yield return $"{Name}, Version={Version}, Culture={Culture}";
yield return $"{Name}, Version={Version}";
}
yield return Name;
yield return Name.ToLowerInvariant();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ public static ExitCode Run(Options options)
}
catch (Exception ex) // lgtm[cs/catch-of-all-exceptions]
{
fileLogger.Log(Severity.Error, " Unhandled exception: {0}", ex);
fileLogger.LogError($" Unhandled exception: {ex}");
}

logger.Log(Severity.Info, $"Extraction completed in {overallStopwatch.Elapsed}");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public override void Populate(TextWriter trapFile)
PopulateModifiers(trapFile);
ContainingType!.PopulateGenerics();

trapFile.destructors(this, string.Format("~{0}", Symbol.ContainingType.Name), ContainingType, OriginalDefinition(Context, this, Symbol));
trapFile.destructors(this, $"~{Symbol.ContainingType.Name}", ContainingType, OriginalDefinition(Context, this, Symbol));
trapFile.destructor_location(this, Location);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ Symbol.ContainingType is INamedTypeSymbol nt &&
{
if (method.MethodKind == MethodKind.ReducedExtension)
{
cx.ExtractionContext.Logger.Log(Semmle.Util.Logging.Severity.Warning, "Reduced extension method symbols should not be directly extracted.");
cx.ExtractionContext.Logger.LogWarning("Reduced extension method symbols should not be directly extracted.");
}

return OrdinaryMethodFactory.Instance.CreateEntityFromSymbol(cx, method);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ protected Analyser(
this.addAssemblyTrapPrefix = addAssemblyTrapPrefix;
this.progressMonitor = pm;

Logger.Log(Severity.Info, "EXTRACTION STARTING at {0}", DateTime.Now);
Logger.LogInfo($"EXTRACTION STARTING at {DateTime.Now}");
stopWatch.Start();
}

Expand Down Expand Up @@ -175,7 +175,7 @@ private void DoAnalyseReferenceAssembly(PortableExecutableReference r)
}
catch (Exception ex) // lgtm[cs/catch-of-all-exceptions]
{
Logger.Log(Severity.Error, " Unhandled exception analyzing {0}: {1}", r.FilePath, ex);
Logger.LogError($" Unhandled exception analyzing {r.FilePath}: {ex}");
}
}

Expand Down Expand Up @@ -251,7 +251,7 @@ private void DoAnalyseCompilation()
}
catch (Exception ex) // lgtm[cs/catch-of-all-exceptions]
{
Logger.Log(Severity.Error, " Unhandled exception analyzing {0}: {1}", "compilation", ex);
Logger.LogError($" Unhandled exception analyzing compilation: {ex}");
}
}

Expand Down Expand Up @@ -315,12 +315,12 @@ public void PerformExtraction(int numberOfThreads)
public virtual void Dispose()
{
stopWatch.Stop();
Logger.Log(Severity.Info, " Peak working set = {0} MB", Process.GetCurrentProcess().PeakWorkingSet64 / (1024 * 1024));
Logger.LogInfo($" Peak working set = {Process.GetCurrentProcess().PeakWorkingSet64 / (1024 * 1024)} MB");

if (TotalErrors > 0)
Logger.Log(Severity.Info, "EXTRACTION FAILED with {0} error{1} in {2}", TotalErrors, TotalErrors == 1 ? "" : "s", stopWatch.Elapsed);
Logger.LogInfo($"EXTRACTION FAILED with {TotalErrors} error{(TotalErrors == 1 ? "" : "s")} in {stopWatch.Elapsed}");
else
Logger.Log(Severity.Info, "EXTRACTION SUCCEEDED in {0}", stopWatch.Elapsed);
Logger.LogInfo($"EXTRACTION SUCCEEDED in {stopWatch.Elapsed}");

compilationTrapFile?.Dispose();
}
Expand All @@ -345,9 +345,9 @@ public virtual void Dispose()
/// </summary>
public void LogExtractorInfo()
{
Logger.Log(Severity.Info, " Extractor: {0}", Environment.GetCommandLineArgs().First());
Logger.Log(Severity.Info, " Extractor version: {0}", Version);
Logger.Log(Severity.Info, " Current working directory: {0}", Directory.GetCurrentDirectory());
Logger.LogInfo($" Extractor: {Environment.GetCommandLineArgs().First()}");
Logger.LogInfo($" Extractor version: {Version}");
Logger.LogInfo($" Current working directory: {Directory.GetCurrentDirectory()}");
}

private static string Version
Expand Down
40 changes: 20 additions & 20 deletions csharp/extractor/Semmle.Extraction.CSharp/Extractor/Extractor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,12 @@ public void Analysed(int item, int total, string source, string output, TimeSpan
{
if (action != AnalysisAction.UpToDate)
{
logger.Log(Severity.Info, " {0} ({1})", source,
action == AnalysisAction.Extracted
? time.ToString()
: action == AnalysisAction.Excluded
? "excluded"
: "up to date");
var state = action == AnalysisAction.Extracted
? time.ToString()
: action == AnalysisAction.Excluded
? "excluded"
: "up to date";
logger.LogInfo($" {source} ({state})");
}
}

Expand Down Expand Up @@ -110,7 +110,7 @@ public static ExitCode Run(string[] args)
var compilerVersion = new CompilerVersion(options);
if (compilerVersion.SkipExtraction)
{
logger.Log(Severity.Warning, " Unrecognized compiler '{0}' because {1}", compilerVersion.SpecifiedCompiler, compilerVersion.SkipReason);
logger.LogWarning($" Unrecognized compiler '{compilerVersion.SpecifiedCompiler}' because {compilerVersion.SkipReason}");
return ExitCode.Ok;
}

Expand All @@ -133,29 +133,29 @@ public static ExitCode Run(string[] args)
{
var sb = new StringBuilder();
sb.Append(" Failed to parse command line: ").AppendList(" ", compilerArgs);
logger.Log(Severity.Error, sb.ToString());
logger.LogError(sb.ToString());
++analyser.CompilationErrors;
return ExitCode.Failed;
}

if (!analyser.BeginInitialize(compilerVersion.ArgsWithResponse))
{
logger.Log(Severity.Info, "Skipping extraction since files have already been extracted");
logger.LogInfo("Skipping extraction since files have already been extracted");
return ExitCode.Ok;
}

return AnalyseTracing(workingDirectory, compilerArgs, analyser, compilerArguments, options, analyzerStopwatch);
}
catch (Exception ex) // lgtm[cs/catch-of-all-exceptions]
{
logger.Log(Severity.Error, " Unhandled exception: {0}", ex);
logger.LogError($" Unhandled exception: {ex}");
return ExitCode.Errors;
}
}

private static void AddSourceFilesFromProjects(IEnumerable<string> projectsToLoad, IList<string> compilerArguments, ILogger logger)
{
logger.Log(Severity.Info, " Loading referenced projects.");
logger.LogInfo(" Loading referenced projects.");
var projects = new Queue<string>(projectsToLoad);
var processed = new HashSet<string>();
while (projects.Count > 0)
Expand All @@ -168,7 +168,7 @@ private static void AddSourceFilesFromProjects(IEnumerable<string> projectsToLoa
}

processed.Add(fi.FullName);
logger.Log(Severity.Info, " Processing referenced project: " + fi.FullName);
logger.LogInfo($" Processing referenced project: {fi.FullName}");

var csProj = new CsProjFile(fi);

Expand Down Expand Up @@ -242,7 +242,7 @@ private static IEnumerable<Action> ResolveReferences(Microsoft.CodeAnalysis.Comm
{
lock (analyser)
{
analyser.Logger.Log(Severity.Error, " Reference '{0}' does not exist", clref.Reference);
analyser.Logger.LogError($" Reference '{clref.Reference}' does not exist");
++analyser.CompilationErrors;
}
}
Expand All @@ -264,7 +264,7 @@ private static IEnumerable<Action> ResolveReferences(Microsoft.CodeAnalysis.Comm
{
lock (analyser)
{
analyser.Logger.Log(Severity.Error, " Unable to resolve reference '{0}'", clref.Reference);
analyser.Logger.LogError($" Unable to resolve reference '{clref.Reference}'");
++analyser.CompilationErrors;
}
}
Expand All @@ -285,9 +285,9 @@ public static IEnumerable<Action> ReadSyntaxTrees(IEnumerable<string> sources, A
try
{
using var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
analyser.Logger.Log(Severity.Trace, $"Parsing source file: '{path}'");
analyser.Logger.LogTrace($"Parsing source file: '{path}'");
var tree = CSharpSyntaxTree.ParseText(SourceText.From(file, encoding), parseOptions, path);
analyser.Logger.Log(Severity.Trace, $"Source file parsed: '{path}'");
analyser.Logger.LogTrace($"Source file parsed: '{path}'");

lock (ret)
{
Expand All @@ -298,7 +298,7 @@ public static IEnumerable<Action> ReadSyntaxTrees(IEnumerable<string> sources, A
{
lock (analyser)
{
analyser.Logger.Log(Severity.Error, " Unable to open source file {0}: {1}", path, ex.Message);
analyser.Logger.LogError($" Unable to open source file {path}: {ex.Message}");
++analyser.CompilationErrors;
}
}
Expand Down Expand Up @@ -327,7 +327,7 @@ public static ExitCode Analyse(Stopwatch stopwatch, Analyser analyser, CommonOpt

if (syntaxTrees.Count == 0)
{
analyser.Logger.Log(Severity.Error, " No source files");
analyser.Logger.LogError(" No source files");
++analyser.CompilationErrors;
if (analyser is TracingAnalyser)
{
Expand All @@ -347,7 +347,7 @@ public static ExitCode Analyse(Stopwatch stopwatch, Analyser analyser, CommonOpt
}

sw.Stop();
analyser.Logger.Log(Severity.Info, " Models constructed in {0}", sw.Elapsed);
analyser.Logger.LogInfo($" Models constructed in {sw.Elapsed}");
var elapsed = sw.Elapsed;

var currentProcess = Process.GetCurrentProcess();
Expand All @@ -369,7 +369,7 @@ public static ExitCode Analyse(Stopwatch stopwatch, Analyser analyser, CommonOpt
};

analyser.LogPerformance(performance);
analyser.Logger.Log(Severity.Info, " Extraction took {0}", sw.Elapsed);
analyser.Logger.LogInfo($" Extraction took {sw.Elapsed}");

postProcess();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public void EndInitialize(
/// <returns>A Boolean indicating whether the same arguments have been logged previously.</returns>
private bool LogRoslynArgs(IEnumerable<string> roslynArgs)
{
Logger.Log(Severity.Info, $" Arguments to Roslyn: {string.Join(' ', roslynArgs)}");
Logger.LogInfo($" Arguments to Roslyn: {string.Join(' ', roslynArgs)}");

var tempFile = Extractor.GetCSharpArgsLogPath(Path.GetRandomFileName());

Expand All @@ -77,7 +77,7 @@ private bool LogRoslynArgs(IEnumerable<string> roslynArgs)
var argsFile = Extractor.GetCSharpArgsLogPath(hash);

if (argsWritten)
Logger.Log(Severity.Info, $" Arguments have been written to {argsFile}");
Logger.LogInfo($" Arguments have been written to {argsFile}");

if (File.Exists(argsFile))
{
Expand All @@ -87,7 +87,7 @@ private bool LogRoslynArgs(IEnumerable<string> roslynArgs)
}
catch (IOException e)
{
Logger.Log(Severity.Warning, $" Failed to remove {tempFile}: {e.Message}");
Logger.LogWarning($" Failed to remove {tempFile}: {e.Message}");
}
return false;
}
Expand All @@ -98,7 +98,7 @@ private bool LogRoslynArgs(IEnumerable<string> roslynArgs)
}
catch (IOException e)
{
Logger.Log(Severity.Warning, $" Failed to move {tempFile} to {argsFile}: {e.Message}");
Logger.LogWarning($" Failed to move {tempFile} to {argsFile}: {e.Message}");
}

return true;
Expand Down Expand Up @@ -146,14 +146,14 @@ private int LogDiagnostics()

foreach (var error in filteredDiagnostics)
{
Logger.Log(Severity.Error, " Compilation error: {0}", error);
Logger.LogError($" Compilation error: {error}");
}

if (filteredDiagnostics.Count != 0)
{
foreach (var reference in compilation.References)
{
Logger.Log(Severity.Info, " Resolved reference {0}", reference.Display);
Logger.LogInfo($" Resolved reference {reference.Display}");
}
}

Expand Down
2 changes: 1 addition & 1 deletion csharp/extractor/Semmle.Extraction/Context.cs
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ protected Context(ExtractionContext extractionContext, TrapWriter trapWriter, bo
private void EnterScope()
{
if (currentRecursiveDepth >= maxRecursiveDepth)
throw new StackOverflowException(string.Format("Maximum nesting depth of {0} exceeded", maxRecursiveDepth));
throw new StackOverflowException($"Maximum nesting depth of {maxRecursiveDepth} exceeded");
++currentRecursiveDepth;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public void Message(Message msg)
++Errors;
if (Errors == maxErrors)
{
Logger.LogInfo(" Stopping logging after {0} errors", Errors);
Logger.LogInfo($" Stopping logging after {Errors} errors");
}
}

Expand Down
4 changes: 2 additions & 2 deletions csharp/extractor/Semmle.Extraction/TrapWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -183,13 +183,13 @@ public void Dispose()
if (TryMove(tmpFile, $"{root}-{hash}.trap{TrapExtension(trapCompression)}"))
return;
}
logger.Log(Severity.Info, "Identical trap file for {0} already exists", TrapFile);
logger.LogInfo($"Identical trap file for {TrapFile} already exists");
FileUtils.TryDelete(tmpFile);
}
}
catch (Exception ex) // lgtm[cs/catch-of-all-exceptions]
{
logger.Log(Severity.Error, "Failed to move the trap file from {0} to {1} because {2}", tmpFile, TrapFile, ex);
logger.LogError($"Failed to move the trap file from {tmpFile} to {TrapFile} because {ex}");
}
}

Expand Down
Loading
Loading