Skip to content

Commit 6c727b1

Browse files
authored
Merge pull request #16857 from tamasvajk/feature/stringformat
C#: Change `string.Format` calls to interpolated strings
2 parents c5678ad + 0c34b45 commit 6c727b1

File tree

17 files changed

+58
-58
lines changed

17 files changed

+58
-58
lines changed

csharp/autobuilder/Semmle.Autobuild.CSharp/DotNetRule.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ public BuildScript Analyse(IAutobuilder<CSharpAutobuildOptions> builder, bool au
3939

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

csharp/autobuilder/Semmle.Autobuild.CSharp/Program.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,12 @@ public static int Main()
2222
}
2323
catch (InvalidEnvironmentException ex)
2424
{
25-
Console.WriteLine("The environment is invalid: {0}", ex.Message);
25+
Console.WriteLine($"The environment is invalid: {ex.Message}");
2626
}
2727
}
2828
catch (ArgumentOutOfRangeException ex)
2929
{
30-
Console.WriteLine("The value \"{0}\" for parameter \"{1}\" is invalid", ex.ActualValue, ex.ParamName);
30+
Console.WriteLine($"The value \"{ex.ActualValue}\" for parameter \"{ex.ParamName}\" is invalid");
3131
}
3232
return 1;
3333
}

csharp/autobuilder/Semmle.Autobuild.Cpp/Program.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,12 @@ static int Main()
2222
}
2323
catch (InvalidEnvironmentException ex)
2424
{
25-
Console.WriteLine("The environment is invalid: {0}", ex.Message);
25+
Console.WriteLine($"The environment is invalid: {ex.Message}");
2626
}
2727
}
2828
catch (ArgumentOutOfRangeException ex)
2929
{
30-
Console.WriteLine("The value \"{0}\" for parameter \"{1}\" is invalid", ex.ActualValue, ex.ParamName);
30+
Console.WriteLine($"The value \"{ex.ActualValue}\" for parameter \"{ex.ParamName}\" is invalid");
3131
}
3232
return 1;
3333
}

csharp/autobuilder/Semmle.Autobuild.Shared/MsBuildRule.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -128,9 +128,9 @@ BuildScript GetNugetRestoreScript() =>
128128

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

135135
// append the build script which invokes msbuild to the overall build script `ret`;
136136
// we insert a check that building the current project or solution was successful:

csharp/autobuilder/Semmle.Autobuild.Shared/Project.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ public Project(Autobuilder<TAutobuildOptions> builder, string path) : base(build
6666
catch // lgtm[cs/catch-of-all-exceptions]
6767
// Generic catch clause - Version constructor throws about 5 different exceptions.
6868
{
69-
builder.Logger.Log(Severity.Warning, "Project {0} has invalid tools version {1}", path, toolsVersion);
69+
builder.Logger.LogWarning($"Project {path} has invalid tools version {toolsVersion}");
7070
}
7171
}
7272

csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/AssemblyInfo.cs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -60,11 +60,11 @@ public string Id
6060
{
6161
var result = Name;
6262
if (Version is not null)
63-
result = string.Format("{0}, Version={1}", result, Version);
63+
result = $"{result}, Version={Version}";
6464
if (Culture is not null)
65-
result = string.Format("{0}, Culture={1}", result, Culture);
65+
result = $"{result}, Culture={Culture}";
6666
if (PublicKeyToken is not null)
67-
result = string.Format("{0}, PublicKeyToken={1}", result, PublicKeyToken);
67+
result = $"{result}, PublicKeyToken={PublicKeyToken}";
6868
return result;
6969
}
7070
}
@@ -82,8 +82,8 @@ public IEnumerable<string> IndexStrings
8282
if (Version is not null)
8383
{
8484
if (Culture is not null)
85-
yield return string.Format("{0}, Version={1}, Culture={2}", Name, Version, Culture);
86-
yield return string.Format("{0}, Version={1}", Name, Version);
85+
yield return $"{Name}, Version={Version}, Culture={Culture}";
86+
yield return $"{Name}, Version={Version}";
8787
}
8888
yield return Name;
8989
yield return Name.ToLowerInvariant();

csharp/extractor/Semmle.Extraction.CSharp.Standalone/Extractor.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ public static ExitCode Run(Options options)
151151
}
152152
catch (Exception ex) // lgtm[cs/catch-of-all-exceptions]
153153
{
154-
fileLogger.Log(Severity.Error, " Unhandled exception: {0}", ex);
154+
fileLogger.LogError($" Unhandled exception: {ex}");
155155
}
156156

157157
logger.Log(Severity.Info, $"Extraction completed in {overallStopwatch.Elapsed}");

csharp/extractor/Semmle.Extraction.CSharp/Entities/Destructor.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ public override void Populate(TextWriter trapFile)
1414
PopulateModifiers(trapFile);
1515
ContainingType!.PopulateGenerics();
1616

17-
trapFile.destructors(this, string.Format("~{0}", Symbol.ContainingType.Name), ContainingType, OriginalDefinition(Context, this, Symbol));
17+
trapFile.destructors(this, $"~{Symbol.ContainingType.Name}", ContainingType, OriginalDefinition(Context, this, Symbol));
1818
trapFile.destructor_location(this, Location);
1919
}
2020

csharp/extractor/Semmle.Extraction.CSharp/Entities/OrdinaryMethod.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ Symbol.ContainingType is INamedTypeSymbol nt &&
6363
{
6464
if (method.MethodKind == MethodKind.ReducedExtension)
6565
{
66-
cx.ExtractionContext.Logger.Log(Semmle.Util.Logging.Severity.Warning, "Reduced extension method symbols should not be directly extracted.");
66+
cx.ExtractionContext.Logger.LogWarning("Reduced extension method symbols should not be directly extracted.");
6767
}
6868

6969
return OrdinaryMethodFactory.Instance.CreateEntityFromSymbol(cx, method);

csharp/extractor/Semmle.Extraction.CSharp/Extractor/Analyser.cs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ protected Analyser(
5454
this.addAssemblyTrapPrefix = addAssemblyTrapPrefix;
5555
this.progressMonitor = pm;
5656

57-
Logger.Log(Severity.Info, "EXTRACTION STARTING at {0}", DateTime.Now);
57+
Logger.LogInfo($"EXTRACTION STARTING at {DateTime.Now}");
5858
stopWatch.Start();
5959
}
6060

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

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

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

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

325325
compilationTrapFile?.Dispose();
326326
}
@@ -345,9 +345,9 @@ public virtual void Dispose()
345345
/// </summary>
346346
public void LogExtractorInfo()
347347
{
348-
Logger.Log(Severity.Info, " Extractor: {0}", Environment.GetCommandLineArgs().First());
349-
Logger.Log(Severity.Info, " Extractor version: {0}", Version);
350-
Logger.Log(Severity.Info, " Current working directory: {0}", Directory.GetCurrentDirectory());
348+
Logger.LogInfo($" Extractor: {Environment.GetCommandLineArgs().First()}");
349+
Logger.LogInfo($" Extractor version: {Version}");
350+
Logger.LogInfo($" Current working directory: {Directory.GetCurrentDirectory()}");
351351
}
352352

353353
private static string Version

csharp/extractor/Semmle.Extraction.CSharp/Extractor/Extractor.cs

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -38,12 +38,12 @@ public void Analysed(int item, int total, string source, string output, TimeSpan
3838
{
3939
if (action != AnalysisAction.UpToDate)
4040
{
41-
logger.Log(Severity.Info, " {0} ({1})", source,
42-
action == AnalysisAction.Extracted
43-
? time.ToString()
44-
: action == AnalysisAction.Excluded
45-
? "excluded"
46-
: "up to date");
41+
var state = action == AnalysisAction.Extracted
42+
? time.ToString()
43+
: action == AnalysisAction.Excluded
44+
? "excluded"
45+
: "up to date";
46+
logger.LogInfo($" {source} ({state})");
4747
}
4848
}
4949

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

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

141141
if (!analyser.BeginInitialize(compilerVersion.ArgsWithResponse))
142142
{
143-
logger.Log(Severity.Info, "Skipping extraction since files have already been extracted");
143+
logger.LogInfo("Skipping extraction since files have already been extracted");
144144
return ExitCode.Ok;
145145
}
146146

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

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

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

173173
var csProj = new CsProjFile(fi);
174174

@@ -242,7 +242,7 @@ private static IEnumerable<Action> ResolveReferences(Microsoft.CodeAnalysis.Comm
242242
{
243243
lock (analyser)
244244
{
245-
analyser.Logger.Log(Severity.Error, " Reference '{0}' does not exist", clref.Reference);
245+
analyser.Logger.LogError($" Reference '{clref.Reference}' does not exist");
246246
++analyser.CompilationErrors;
247247
}
248248
}
@@ -264,7 +264,7 @@ private static IEnumerable<Action> ResolveReferences(Microsoft.CodeAnalysis.Comm
264264
{
265265
lock (analyser)
266266
{
267-
analyser.Logger.Log(Severity.Error, " Unable to resolve reference '{0}'", clref.Reference);
267+
analyser.Logger.LogError($" Unable to resolve reference '{clref.Reference}'");
268268
++analyser.CompilationErrors;
269269
}
270270
}
@@ -285,9 +285,9 @@ public static IEnumerable<Action> ReadSyntaxTrees(IEnumerable<string> sources, A
285285
try
286286
{
287287
using var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
288-
analyser.Logger.Log(Severity.Trace, $"Parsing source file: '{path}'");
288+
analyser.Logger.LogTrace($"Parsing source file: '{path}'");
289289
var tree = CSharpSyntaxTree.ParseText(SourceText.From(file, encoding), parseOptions, path);
290-
analyser.Logger.Log(Severity.Trace, $"Source file parsed: '{path}'");
290+
analyser.Logger.LogTrace($"Source file parsed: '{path}'");
291291

292292
lock (ret)
293293
{
@@ -298,7 +298,7 @@ public static IEnumerable<Action> ReadSyntaxTrees(IEnumerable<string> sources, A
298298
{
299299
lock (analyser)
300300
{
301-
analyser.Logger.Log(Severity.Error, " Unable to open source file {0}: {1}", path, ex.Message);
301+
analyser.Logger.LogError($" Unable to open source file {path}: {ex.Message}");
302302
++analyser.CompilationErrors;
303303
}
304304
}
@@ -327,7 +327,7 @@ public static ExitCode Analyse(Stopwatch stopwatch, Analyser analyser, CommonOpt
327327

328328
if (syntaxTrees.Count == 0)
329329
{
330-
analyser.Logger.Log(Severity.Error, " No source files");
330+
analyser.Logger.LogError(" No source files");
331331
++analyser.CompilationErrors;
332332
if (analyser is TracingAnalyser)
333333
{
@@ -347,7 +347,7 @@ public static ExitCode Analyse(Stopwatch stopwatch, Analyser analyser, CommonOpt
347347
}
348348

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

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

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

374374
postProcess();
375375

csharp/extractor/Semmle.Extraction.CSharp/Extractor/TracingAnalyser.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ public void EndInitialize(
6262
/// <returns>A Boolean indicating whether the same arguments have been logged previously.</returns>
6363
private bool LogRoslynArgs(IEnumerable<string> roslynArgs)
6464
{
65-
Logger.Log(Severity.Info, $" Arguments to Roslyn: {string.Join(' ', roslynArgs)}");
65+
Logger.LogInfo($" Arguments to Roslyn: {string.Join(' ', roslynArgs)}");
6666

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

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

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

8282
if (File.Exists(argsFile))
8383
{
@@ -87,7 +87,7 @@ private bool LogRoslynArgs(IEnumerable<string> roslynArgs)
8787
}
8888
catch (IOException e)
8989
{
90-
Logger.Log(Severity.Warning, $" Failed to remove {tempFile}: {e.Message}");
90+
Logger.LogWarning($" Failed to remove {tempFile}: {e.Message}");
9191
}
9292
return false;
9393
}
@@ -98,7 +98,7 @@ private bool LogRoslynArgs(IEnumerable<string> roslynArgs)
9898
}
9999
catch (IOException e)
100100
{
101-
Logger.Log(Severity.Warning, $" Failed to move {tempFile} to {argsFile}: {e.Message}");
101+
Logger.LogWarning($" Failed to move {tempFile} to {argsFile}: {e.Message}");
102102
}
103103

104104
return true;
@@ -146,14 +146,14 @@ private int LogDiagnostics()
146146

147147
foreach (var error in filteredDiagnostics)
148148
{
149-
Logger.Log(Severity.Error, " Compilation error: {0}", error);
149+
Logger.LogError($" Compilation error: {error}");
150150
}
151151

152152
if (filteredDiagnostics.Count != 0)
153153
{
154154
foreach (var reference in compilation.References)
155155
{
156-
Logger.Log(Severity.Info, " Resolved reference {0}", reference.Display);
156+
Logger.LogInfo($" Resolved reference {reference.Display}");
157157
}
158158
}
159159

csharp/extractor/Semmle.Extraction/Context.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,7 @@ protected Context(ExtractionContext extractionContext, TrapWriter trapWriter, bo
203203
private void EnterScope()
204204
{
205205
if (currentRecursiveDepth >= maxRecursiveDepth)
206-
throw new StackOverflowException(string.Format("Maximum nesting depth of {0} exceeded", maxRecursiveDepth));
206+
throw new StackOverflowException($"Maximum nesting depth of {maxRecursiveDepth} exceeded");
207207
++currentRecursiveDepth;
208208
}
209209

csharp/extractor/Semmle.Extraction/Extractor/ExtractionContext.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ public void Message(Message msg)
5050
++Errors;
5151
if (Errors == maxErrors)
5252
{
53-
Logger.LogInfo(" Stopping logging after {0} errors", Errors);
53+
Logger.LogInfo($" Stopping logging after {Errors} errors");
5454
}
5555
}
5656

csharp/extractor/Semmle.Extraction/TrapWriter.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -183,13 +183,13 @@ public void Dispose()
183183
if (TryMove(tmpFile, $"{root}-{hash}.trap{TrapExtension(trapCompression)}"))
184184
return;
185185
}
186-
logger.Log(Severity.Info, "Identical trap file for {0} already exists", TrapFile);
186+
logger.LogInfo($"Identical trap file for {TrapFile} already exists");
187187
FileUtils.TryDelete(tmpFile);
188188
}
189189
}
190190
catch (Exception ex) // lgtm[cs/catch-of-all-exceptions]
191191
{
192-
logger.Log(Severity.Error, "Failed to move the trap file from {0} to {1} because {2}", tmpFile, TrapFile, ex);
192+
logger.LogError($"Failed to move the trap file from {tmpFile} to {TrapFile} because {ex}");
193193
}
194194
}
195195

0 commit comments

Comments
 (0)