C#: Use var everywhere

This commit is contained in:
Tamas Vajk
2020-10-02 13:45:38 +02:00
parent 7d544e34af
commit aec4481cfb
73 changed files with 196 additions and 195 deletions

View File

@@ -379,7 +379,7 @@ namespace Semmle.Autobuild.CSharp.Tests
string? nugetRestore = null, string? allSolutions = null,
string cwd = @"C:\Project")
{
string codeqlUpperLanguage = Language.CSharp.UpperCaseName;
var codeqlUpperLanguage = Language.CSharp.UpperCaseName;
Actions.GetEnvironmentVariable[$"CODEQL_EXTRACTOR_{codeqlUpperLanguage}_TRAP_DIR"] = "";
Actions.GetEnvironmentVariable[$"CODEQL_EXTRACTOR_{codeqlUpperLanguage}_SOURCE_ARCHIVE_DIR"] = "";
Actions.GetEnvironmentVariable[$"CODEQL_EXTRACTOR_{codeqlUpperLanguage}_ROOT"] = $@"C:\codeql\{codeqlUpperLanguage.ToLowerInvariant()}";
@@ -591,7 +591,7 @@ Microsoft.NETCore.App 2.2.5 [/usr/local/share/dotnet/shared/Microsoft.NETCore.Ap
Assert.Equal(commandsRun, EndCallbackReturn.Count);
var action = Actions.RunProcess.GetEnumerator();
for (int cmd = 0; cmd < commandsRun; ++cmd)
for (var cmd = 0; cmd < commandsRun; ++cmd)
{
Assert.True(action.MoveNext());

View File

@@ -59,7 +59,7 @@ namespace Semmle.Autobuild.CSharp
private static BuildScript WithDotNet(Autobuilder builder, Func<string?, IDictionary<string, string>?, bool, BuildScript> f)
{
string? installDir = builder.Actions.PathCombine(builder.Options.RootDirectory, ".dotnet");
var installDir = builder.Actions.PathCombine(builder.Options.RootDirectory, ".dotnet");
var installScript = DownloadDotNet(builder, installDir);
return BuildScript.Bind(installScript, installed =>
{

View File

@@ -46,7 +46,7 @@ namespace Semmle.Autobuild.Shared
chmod.RunCommand("/bin/chmod", $"u+x {scriptPath}");
var chmodScript = builder.Actions.IsWindows() ? BuildScript.Success : BuildScript.Try(chmod.Script);
string? dir = builder.Actions.GetDirectoryName(scriptPath);
var dir = builder.Actions.GetDirectoryName(scriptPath);
// A specific .NET Core version may be required
return chmodScript & withDotNet(builder, environment =>

View File

@@ -31,12 +31,12 @@ namespace Semmle.Autobuild.Shared
yield break;
// Attempt to use vswhere to find installations of Visual Studio
string vswhere = actions.PathCombine(programFilesx86, "Microsoft Visual Studio", "Installer", "vswhere.exe");
var vswhere = actions.PathCombine(programFilesx86, "Microsoft Visual Studio", "Installer", "vswhere.exe");
if (actions.FileExists(vswhere))
{
int exitCode1 = actions.RunProcess(vswhere, "-prerelease -legacy -property installationPath", null, null, out var installationList);
int exitCode2 = actions.RunProcess(vswhere, "-prerelease -legacy -property installationVersion", null, null, out var versionList);
var exitCode1 = actions.RunProcess(vswhere, "-prerelease -legacy -property installationPath", null, null, out var installationList);
var exitCode2 = actions.RunProcess(vswhere, "-prerelease -legacy -property installationVersion", null, null, out var versionList);
if (exitCode1 == 0 && exitCode2 == 0 && versionList.Count == installationList.Count)
{
@@ -45,7 +45,7 @@ namespace Semmle.Autobuild.Shared
{
var dot = vsInstallation.Version.IndexOf('.');
var majorVersionString = dot == -1 ? vsInstallation.Version : vsInstallation.Version.Substring(0, dot);
if (int.TryParse(majorVersionString, out int majorVersion))
if (int.TryParse(majorVersionString, out var majorVersion))
{
if (majorVersion < 15)
{

View File

@@ -90,7 +90,7 @@ namespace Semmle.Autobuild.Shared
/// </remarks>
private void ArgvQuote(string argument, bool force)
{
bool cmd = escapingMode == EscapeMode.Cmd;
var cmd = escapingMode == EscapeMode.Cmd;
if (!force &&
!string.IsNullOrEmpty(argument) &&
argument.IndexOfAny(specialChars) == -1)
@@ -104,7 +104,7 @@ namespace Semmle.Autobuild.Shared
arguments.Append('\"');
for (int it = 0; ; ++it)
for (var it = 0; ; ++it)
{
var numBackslashes = 0;
while (it != argument.Length && argument[it] == '\\')

View File

@@ -98,9 +98,9 @@ namespace Semmle.Autobuild.Shared
command.Argument("/p:UseSharedCompilation=false");
string target = builder.Options.MsBuildTarget ?? "rebuild";
string? platform = builder.Options.MsBuildPlatform ?? (projectOrSolution is ISolution s1 ? s1.DefaultPlatformName : null);
string? configuration = builder.Options.MsBuildConfiguration ?? (projectOrSolution is ISolution s2 ? s2.DefaultConfigurationName : null);
var target = builder.Options.MsBuildTarget ?? "rebuild";
var platform = builder.Options.MsBuildPlatform ?? (projectOrSolution is ISolution s1 ? s1.DefaultPlatformName : null);
var configuration = builder.Options.MsBuildConfiguration ?? (projectOrSolution is ISolution s2 ? s2.DefaultConfigurationName : null);
command.Argument("/t:" + target);
if (platform != null)

View File

@@ -144,7 +144,7 @@ namespace Semmle.Extraction.CIL.Driver
while (assembliesToReference.Any())
{
var item = assembliesToReference.Pop();
if (assembliesRead.TryGetValue(item, out AssemblyInfo? info))
if (assembliesRead.TryGetValue(item, out var info))
{
if (!info.extract)
{
@@ -213,7 +213,7 @@ namespace Semmle.Extraction.CIL.Driver
if (File.Exists(path))
{
assemblyList.AddFile(path, true);
string? directory = Path.GetDirectoryName(path);
var directory = Path.GetDirectoryName(path);
if (directory is null)
{
throw new InternalError($"Directory of path '{path}' is null");

View File

@@ -34,7 +34,7 @@ namespace Semmle.Extraction.CIL
{
get
{
if (!cache.TryGetValue(src, out TargetType result))
if (!cache.TryGetValue(src, out var result))
{
result = generator(src);
cache[src] = result;

View File

@@ -55,16 +55,16 @@ namespace Semmle.Extraction.CIL.Entities
yield break;
}
for (int index = 0; index < decoded.FixedArguments.Length; ++index)
for (var index = 0; index < decoded.FixedArguments.Length; ++index)
{
object value = decoded.FixedArguments[index].Value;
var value = decoded.FixedArguments[index].Value;
var stringValue = value?.ToString();
yield return Tuples.cil_attribute_positional_argument(this, index, stringValue ?? "null");
}
foreach (var p in decoded.NamedArguments)
{
object value = p.Value;
var value = p.Value;
var stringValue = value?.ToString();
yield return Tuples.cil_attribute_named_argument(this, p.Name, stringValue ?? "null");
}

View File

@@ -31,18 +31,18 @@ namespace Semmle.Extraction.CIL.Entities
get
{
if (!jump_table.TryGetValue(r.TryOffset, out IInstruction? try_start))
if (!jump_table.TryGetValue(r.TryOffset, out var try_start))
throw new InternalError("Failed to retrieve handler");
if (!jump_table.TryGetValue(r.TryOffset + r.TryLength, out IInstruction? try_end))
if (!jump_table.TryGetValue(r.TryOffset + r.TryLength, out var try_end))
throw new InternalError("Failed to retrieve handler");
if (!jump_table.TryGetValue(r.HandlerOffset, out IInstruction? handler_start))
if (!jump_table.TryGetValue(r.HandlerOffset, out var handler_start))
throw new InternalError("Failed to retrieve handler");
yield return Tuples.cil_handler(this, method, index, (int)r.Kind, try_start, try_end, handler_start);
if (r.FilterOffset != -1)
{
if (!jump_table.TryGetValue(r.FilterOffset, out IInstruction? filter_start))
if (!jump_table.TryGetValue(r.FilterOffset, out var filter_start))
throw new InternalError("ExceptionRegion filter clause");
yield return Tuples.cil_handler_filter(this, filter_start);

View File

@@ -279,7 +279,7 @@ namespace Semmle.Extraction.CIL.Entities
{
get
{
if (!opPayload.TryGetValue(OpCode, out Payload result))
if (!opPayload.TryGetValue(OpCode, out var result))
throw new InternalError("Unknown op code " + OpCode);
return result;
}
@@ -361,7 +361,7 @@ namespace Semmle.Extraction.CIL.Entities
{
get
{
int offset = Offset;
var offset = Offset;
if (Method.Implementation is null)
{
@@ -459,11 +459,11 @@ namespace Semmle.Extraction.CIL.Entities
target = Offset + PayloadValue + 5;
break;
case Payload.Switch:
int end = Offset + Width;
var end = Offset + Width;
int offset = Offset + 5;
var offset = Offset + 5;
for (int b = 0; b < PayloadValue; ++b, offset += 4)
for (var b = 0; b < PayloadValue; ++b, offset += 4)
{
target = BitConverter.ToInt32(data, offset) + end;
if (jump_table.TryGetValue(target, out inst))

View File

@@ -64,7 +64,7 @@ namespace Semmle.Extraction.CIL.Entities
trapFile.Write(signature.GenericParameterCount);
}
trapFile.Write('(');
int index = 0;
var index = 0;
foreach (var param in signature.ParameterTypes)
{
trapFile.WriteSeparator(",", ref index);
@@ -88,7 +88,7 @@ namespace Semmle.Extraction.CIL.Entities
protected IEnumerable<Parameter> MakeParameters(IEnumerable<Type> parameterTypes)
{
int i = 0;
var i = 0;
if (!IsStatic)
{
@@ -190,9 +190,9 @@ namespace Semmle.Extraction.CIL.Entities
// We need to perform a 2-phase population because some type parameters can
// depend on other type parameters (as a constraint).
genericParams = new MethodTypeParameter[md.GetGenericParameters().Count];
for (int i = 0; i < genericParams.Length; ++i)
for (var i = 0; i < genericParams.Length; ++i)
genericParams[i] = cx.Populate(new MethodTypeParameter(this, this, i));
for (int i = 0; i < genericParams.Length; ++i)
for (var i = 0; i < genericParams.Length; ++i)
genericParams[i].PopulateHandle(md.GetGenericParameters()[i]);
foreach (var p in genericParams)
yield return p;
@@ -237,7 +237,7 @@ namespace Semmle.Extraction.CIL.Entities
this.locals = new LocalVariable[localVariableTypes.Length];
for (int l = 0; l < this.locals.Length; ++l)
for (var l = 0; l < this.locals.Length; ++l)
{
this.locals[l] = cx.Populate(new LocalVariable(cx, Implementation, l, localVariableTypes[l]));
yield return this.locals[l];
@@ -249,7 +249,7 @@ namespace Semmle.Extraction.CIL.Entities
foreach (var c in Decode(body.GetILBytes(), jump_table))
yield return c;
int filter_index = 0;
var filter_index = 0;
foreach (var region in body.ExceptionRegions)
{
yield return new ExceptionRegion(this, Implementation, filter_index++, region, jump_table);
@@ -326,8 +326,8 @@ namespace Semmle.Extraction.CIL.Entities
}
}
int child = 0;
for (int offset = 0; offset < ilbytes.Length;)
var child = 0;
for (var offset = 0; offset < ilbytes.Length;)
{
var instruction = new Instruction(cx, this, ilbytes, offset, child++);
yield return instruction;
@@ -368,8 +368,8 @@ namespace Semmle.Extraction.CIL.Entities
var ilbytes = body.GetILBytes();
int child = 0;
for (int offset = 0; offset < ilbytes.Length;)
var child = 0;
for (var offset = 0; offset < ilbytes.Length;)
{
Instruction decoded;
try
@@ -452,7 +452,7 @@ namespace Semmle.Extraction.CIL.Entities
get
{
genericParams = new MethodTypeParameter[signature.GenericParameterCount];
for (int p = 0; p < genericParams.Length; ++p)
for (var p = 0; p < genericParams.Length; ++p)
genericParams[p] = cx.Populate(new MethodTypeParameter(this, this, p));
foreach (var p in genericParams)
@@ -495,7 +495,7 @@ namespace Semmle.Extraction.CIL.Entities
{
unboundMethod.WriteId(trapFile);
trapFile.Write('<');
int index = 0;
var index = 0;
foreach (var param in typeParams)
{
trapFile.WriteSeparator(",", ref index);
@@ -555,7 +555,7 @@ namespace Semmle.Extraction.CIL.Entities
if (typeParams.Length != unboundMethod.GenericParameterCount)
throw new InternalError("Method type parameter mismatch");
for (int p = 0; p < typeParams.Length; ++p)
for (var p = 0; p < typeParams.Length; ++p)
{
yield return Tuples.cil_type_argument(this, p, typeParams[p]);
}

View File

@@ -48,7 +48,7 @@ namespace Semmle.Extraction.CIL.Entities
public override int GetHashCode()
{
int h = ParentNamespace is null ? 19 : ParentNamespace.GetHashCode();
var h = ParentNamespace is null ? 19 : ParentNamespace.GetHashCode();
return 13 * h + Name.GetHashCode();
}

View File

@@ -37,7 +37,7 @@ namespace Semmle.Extraction.CIL.Entities
trapFile.Write('.');
trapFile.Write(cx.GetString(pd.Name));
trapFile.Write("(");
int index = 0;
var index = 0;
var signature = pd.DecodeSignature(new SignatureDecoder(), gc);
foreach (var param in signature.ParameterTypes)
{

View File

@@ -427,12 +427,12 @@ namespace Semmle.Extraction.CIL.Entities
var newTypeParams = new TypeTypeParameter[ThisTypeParameters];
var genericParams = td.GetGenericParameters();
int toSkip = genericParams.Count - newTypeParams.Length;
var toSkip = genericParams.Count - newTypeParams.Length;
// Two-phase population because type parameters can be mutually dependent
for (int i = 0; i < newTypeParams.Length; ++i)
for (var i = 0; i < newTypeParams.Length; ++i)
newTypeParams[i] = cx.Populate(new TypeTypeParameter(this, this, i));
for (int i = 0; i < newTypeParams.Length; ++i)
for (var i = 0; i < newTypeParams.Length; ++i)
newTypeParams[i].PopulateHandle(genericParams[i + toSkip]);
return newTypeParams;
}
@@ -578,7 +578,7 @@ namespace Semmle.Extraction.CIL.Entities
private TypeTypeParameter[] MakeTypeParameters()
{
var newTypeParams = new TypeTypeParameter[ThisTypeParameters];
for (int i = 0; i < newTypeParams.Length; ++i)
for (var i = 0; i < newTypeParams.Length; ++i)
{
newTypeParams[i] = new TypeTypeParameter(this, this, i);
}
@@ -726,7 +726,7 @@ namespace Semmle.Extraction.CIL.Entities
foreach (var c in base.Contents)
yield return c;
int i = 0;
var i = 0;
foreach (var type in ThisGenericArguments)
{
yield return type;
@@ -777,7 +777,7 @@ namespace Semmle.Extraction.CIL.Entities
public override int GetHashCode()
{
int h = unboundGenericType.GetHashCode();
var h = unboundGenericType.GetHashCode();
h = 13 * h + (containingType is null ? 0 : containingType.GetHashCode());
if (!(thisTypeArguments is null))
h = h * 13 + thisTypeArguments.SequenceHash();
@@ -822,7 +822,7 @@ namespace Semmle.Extraction.CIL.Entities
if (thisTypeArguments != null && thisTypeArguments.Any())
{
trapFile.Write('<');
int index = 0;
var index = 0;
foreach (var t in thisTypeArguments)
{
trapFile.WriteSeparator(",", ref index);
@@ -914,7 +914,7 @@ namespace Semmle.Extraction.CIL.Entities
{
elementType.GetId(trapFile, inContext);
trapFile.Write('[');
for (int i = 1; i < rank; ++i)
for (var i = 1; i < rank; ++i)
trapFile.Write(',');
trapFile.Write(']');
}
@@ -1209,7 +1209,7 @@ namespace Semmle.Extraction.CIL.Entities
{
elementType.WriteId(trapFile, gc);
trapFile.Write('[');
for (int i = 1; i < shape.Rank; ++i)
for (var i = 1; i < shape.Rank; ++i)
trapFile.Write(',');
trapFile.Write(']');
}
@@ -1279,7 +1279,7 @@ namespace Semmle.Extraction.CIL.Entities
{
genericType.WriteId(trapFile, gc);
trapFile.Write('<');
int index = 0;
var index = 0;
foreach (var arg in typeArguments)
{
trapFile.WriteSeparator(",", ref index);

View File

@@ -40,7 +40,7 @@ namespace Semmle.Extraction.CIL
e.WriteId(writer);
var id = writer.ToString();
if (debugLabels.TryGetValue(id, out IExtractedEntity? previousEntity))
if (debugLabels.TryGetValue(id, out var previousEntity))
{
cx.Extractor.Message(new Message("Duplicate trap ID", id, null, severity: Util.Logging.Severity.Warning));
}
@@ -68,7 +68,7 @@ namespace Semmle.Extraction.CIL
public PrimitiveType Create(PrimitiveTypeCode code)
{
PrimitiveType e = primitiveTypes[(int)code];
var e = primitiveTypes[(int)code];
if (e is null)
{
@@ -194,7 +194,7 @@ namespace Semmle.Extraction.CIL
private Namespace CreateNamespace(NamespaceDefinitionHandle handle)
{
if (handle.IsNil) return GlobalNamespace;
NamespaceDefinition nd = mdReader.GetNamespaceDefinition(handle);
var nd = mdReader.GetNamespaceDefinition(handle);
return Populate(new Namespace(this, GetString(nd.Name), Create(nd.Parent)));
}
#endregion
@@ -236,7 +236,7 @@ namespace Semmle.Extraction.CIL
/// <returns>The short name.</returns>
public string ShortName(StringHandle handle)
{
string str = mdReader.GetString(handle);
var str = mdReader.GetString(handle);
if (str.EndsWith(".ctor")) return ".ctor";
if (str.EndsWith(".cctor")) return ".cctor";
var dot = str.LastIndexOf('.');

View File

@@ -25,7 +25,7 @@ namespace Semmle.Extraction.PDB
document = doc;
contents = new Lazy<string?>(() =>
{
if (document.HasEmbeddedSource(out bool isEmbedded) == 0 && isEmbedded)
if (document.HasEmbeddedSource(out var isEmbedded) == 0 && isEmbedded)
{
var rawContents = document.GetEmbeddedSource().ToArray();
return System.Text.Encoding.Default.GetString(rawContents);
@@ -58,7 +58,7 @@ namespace Semmle.Extraction.PDB
public IMethod? GetMethod(MethodDebugInformationHandle h)
{
int methodToken = MetadataTokens.GetToken(h.ToDefinitionHandle());
var methodToken = MetadataTokens.GetToken(h.ToDefinitionHandle());
var method = reader.GetMethod(methodToken);
if (method != null)
{

View File

@@ -100,7 +100,7 @@ namespace Semmle.BuildAnalyser
(id, assemblyName) = AssemblyInfo.ComputeSanitizedAssemblyInfo(id);
// Look up the id in our references map.
if (assemblyInfoById.TryGetValue(id, out AssemblyInfo? result))
if (assemblyInfoById.TryGetValue(id, out var result))
{
// The string is in the references map.
return result;

View File

@@ -190,7 +190,7 @@ namespace Semmle.BuildAnalyser
sortedReferences = sortedReferences.OrderBy(r => r.Version).ToList();
Dictionary<string, AssemblyInfo> finalAssemblyList = new Dictionary<string, AssemblyInfo>();
var finalAssemblyList = new Dictionary<string, AssemblyInfo>();
// Pick the highest version for each assembly name
foreach (var r in sortedReferences)
@@ -296,7 +296,7 @@ namespace Semmle.BuildAnalyser
{
try
{
AssemblyInfo resolved = assemblyCache.ResolveReference(@ref);
var resolved = assemblyCache.ResolveReference(@ref);
UseReference(resolved.Filename);
}
catch (AssemblyLoadException)
@@ -325,7 +325,7 @@ namespace Semmle.BuildAnalyser
private void Restore(string projectOrSolution)
{
int exit = DotNet.RestoreToDirectory(projectOrSolution, PackageDirectory.DirInfo.FullName);
var exit = DotNet.RestoreToDirectory(projectOrSolution, PackageDirectory.DirInfo.FullName);
switch (exit)
{
case 0:

View File

@@ -90,7 +90,7 @@ namespace Semmle.BuildAnalyser
// Figure out if it's dotnet core
bool netCoreProjectFile = root.GetAttribute("Sdk") == "Microsoft.NET.Sdk";
var netCoreProjectFile = root.GetAttribute("Sdk") == "Microsoft.NET.Sdk";
if (netCoreProjectFile)
{

View File

@@ -25,7 +25,7 @@ namespace Semmle.BuildAnalyser
// Expect nuget.exe to be in a `nuget` directory under the directory containing this exe.
var currentAssembly = System.Reflection.Assembly.GetExecutingAssembly().Location;
string? directory = Path.GetDirectoryName(currentAssembly);
var directory = Path.GetDirectoryName(currentAssembly);
if (directory is null)
throw new FileNotFoundException($"Directory path '{currentAssembly}' of current assembly is null");
@@ -113,8 +113,8 @@ namespace Semmle.BuildAnalyser
{
using var p = Process.Start(pi);
string output = p.StandardOutput.ReadToEnd();
string error = p.StandardError.ReadToEnd();
var output = p.StandardOutput.ReadToEnd();
var error = p.StandardError.ReadToEnd();
p.WaitForExit();
if (p.ExitCode != 0)

View File

@@ -69,7 +69,7 @@ namespace Semmle.Extraction.CSharp.Standalone
output.Log(Severity.Info, "Running C# standalone extractor");
using var a = new Analysis(output, options);
int sourceFileCount = a.Extraction.Sources.Count;
var sourceFileCount = a.Extraction.Sources.Count;
if (sourceFileCount == 0)
{

View File

@@ -312,7 +312,7 @@ namespace Semmle.Extraction.CSharp
{
var stopwatch = new Stopwatch();
stopwatch.Start();
CIL.Entities.Assembly.ExtractCIL(layout, r.FilePath, Logger, !options.Cache, options.PDB, options.TrapCompression, out string trapFile, out bool extracted);
CIL.Entities.Assembly.ExtractCIL(layout, r.FilePath, Logger, !options.Cache, options.PDB, options.TrapCompression, out var trapFile, out var extracted);
stopwatch.Stop();
ReportProgress(r.FilePath, trapFile, stopwatch.Elapsed, extracted ? AnalysisAction.Extracted : AnalysisAction.UpToDate);
}
@@ -360,9 +360,9 @@ namespace Semmle.Extraction.CSharp
var transformedSourcePath = PathTransformer.Transform(sourcePath);
var projectLayout = layout.LookupProjectOrNull(transformedSourcePath);
bool excluded = projectLayout == null;
string trapPath = excluded ? "" : projectLayout.GetTrapPath(Logger, transformedSourcePath, options.TrapCompression);
bool upToDate = false;
var excluded = projectLayout == null;
var trapPath = excluded ? "" : projectLayout.GetTrapPath(Logger, transformedSourcePath, options.TrapCompression);
var upToDate = false;
if (!excluded)
{
@@ -373,7 +373,7 @@ namespace Semmle.Extraction.CSharp
if (!upToDate)
{
Context cx = extractor.CreateContext(compilation.Clone(), trapWriter, new SourceScope(tree), AddAssemblyTrapPrefix);
var cx = extractor.CreateContext(compilation.Clone(), trapWriter, new SourceScope(tree), AddAssemblyTrapPrefix);
Populators.CompilationUnit.Extract(cx, tree.GetRoot());
cx.PopulateAll();
cx.ExtractComments(cx.CommentGenerator);

View File

@@ -56,7 +56,7 @@ namespace Semmle.Extraction.CSharp.Entities
{
cx.PopulateLater(() =>
{
int child = 0;
var child = 0;
foreach (var arg in syntax.ArgumentList.Arguments)
{
var expr = Expression.Create(cx, arg.Expression, this, child++);

View File

@@ -12,7 +12,7 @@ namespace Semmle.Extraction.CSharp.Entities
public override void Populate(TextWriter trapFile)
{
trapFile.commentblock(this);
int child = 0;
var child = 0;
trapFile.commentblock_location(this, Context.Create(symbol.Location));
foreach (var l in symbol.CommentLines)
{

View File

@@ -36,14 +36,14 @@ namespace Semmle.Extraction.CSharp.Entities
var split = text.Split('\n');
var currentLocation = trivia.GetLocation().SourceSpan.Start - 3;
for (int line = 0; line < split.Length - 1; ++line)
for (var line = 0; line < split.Length - 1; ++line)
{
string fullLine = split[line];
var fullLine = split[line];
var nextLineLocation = currentLocation + fullLine.Length + 1;
fullLine = fullLine.TrimEnd('\r');
string trimmedLine = fullLine;
var trimmedLine = fullLine;
int leadingSpaces = trimmedLine.IndexOf('/');
var leadingSpaces = trimmedLine.IndexOf('/');
if (leadingSpaces != -1)
{
fullLine = fullLine.Substring(leadingSpaces);
@@ -66,7 +66,7 @@ namespace Semmle.Extraction.CSharp.Entities
case SyntaxKind.SingleLineCommentTrivia:
{
string contents = trivia.ToString().Substring(2);
var contents = trivia.ToString().Substring(2);
var commentType = CommentLineType.Singleline;
if (contents.Length > 0 && contents[0] == '/')
{
@@ -86,14 +86,15 @@ namespace Semmle.Extraction.CSharp.Entities
split = text.Split('\n');
currentLocation = trivia.GetLocation().SourceSpan.Start;
for (int line = 0; line < split.Length; ++line)
for (var line = 0; line < split.Length; ++line)
{
string fullLine = split[line];
var fullLine = split[line];
var nextLineLocation = currentLocation + fullLine.Length + 1;
fullLine = fullLine.TrimEnd('\r');
string trimmedLine = fullLine;
var trimmedLine = fullLine;
if (line == 0) trimmedLine = trimmedLine.Substring(2);
if (line == split.Length - 1) trimmedLine = trimmedLine.Substring(0, trimmedLine.Length - 2);
trimmedLine = trimmedLine.Trim();
var span = Microsoft.CodeAnalysis.Text.TextSpan.FromBounds(currentLocation, currentLocation + fullLine.Length);

View File

@@ -26,7 +26,7 @@ namespace Semmle.Extraction.CSharp.Entities
trapFile.compilations(this, FileUtils.ConvertToUnix(cwd));
// Arguments
int index = 0;
var index = 0;
foreach (var arg in args)
{
trapFile.compilation_args(this, index++, arg);
@@ -57,8 +57,8 @@ namespace Semmle.Extraction.CSharp.Entities
public void PopulatePerformance(PerformanceMetrics p)
{
var trapFile = cx.TrapWriter.Writer;
int index = 0;
foreach (float metric in p.Metrics)
var index = 0;
foreach (var metric in p.Metrics)
{
trapFile.compilation_time(this, -1, index++, metric);
}

View File

@@ -77,7 +77,7 @@ namespace Semmle.Extraction.CSharp.Entities
trapFile.expr_call(init, target);
int child = 0;
var child = 0;
foreach (var arg in initializer.ArgumentList.Arguments)
{
Expression.Create(Context, arg.Expression, init, child++);

View File

@@ -150,7 +150,7 @@ namespace Semmle.Extraction.CSharp.Entities
var callType = GetCallType(cx, node);
if (callType == CallType.Dynamic)
{
UserOperator.OperatorSymbol(method.Name, out string operatorName);
UserOperator.OperatorSymbol(method.Name, out var operatorName);
trapFile.dynamic_member_name(this, operatorName);
return;
}

View File

@@ -82,7 +82,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
private static ExprKind GetKind(Context cx, AssignmentExpressionSyntax syntax)
{
var leftSymbol = cx.GetSymbolInfo(syntax.Left);
bool assignEvent = leftSymbol.Symbol != null && leftSymbol.Symbol is IEventSymbol;
var assignEvent = leftSymbol.Symbol != null && leftSymbol.Symbol is IEventSymbol;
var kind = GetAssignmentOperation(cx, syntax);
var leftType = cx.GetType(syntax.Left);

View File

@@ -46,11 +46,11 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
if (conversion.MethodSymbol != null)
{
bool convertedToDelegate = Entities.Type.IsDelegate(convertedType.Symbol);
var convertedToDelegate = Entities.Type.IsDelegate(convertedType.Symbol);
if (convertedToDelegate)
{
bool isExplicitConversion =
var isExplicitConversion =
info.Parent is ExplicitObjectCreation objectCreation &&
objectCreation.Kind == ExprKind.EXPLICIT_DELEGATE_CREATION;
@@ -69,7 +69,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
return new ImplicitCast(info, conversion.MethodSymbol);
}
bool implicitUpcast = conversion.IsImplicit &&
var implicitUpcast = conversion.IsImplicit &&
convertedType.Symbol != null &&
!conversion.IsBoxing &&
(

View File

@@ -83,7 +83,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
// If the target is null, then assume that this is an array initializer (of the form `[...] = ...`)
Expression access = target.Symbol is null ?
var access = target.Symbol is null ?
new Expression(new ExpressionNodeInfo(cx, assignment.Left, assignmentEntity, 1).SetKind(ExprKind.ARRAY_ACCESS)) :
Access.Create(new ExpressionNodeInfo(cx, assignment.Left, assignmentEntity, 1), target.Symbol, false, cx.CreateEntity(target.Symbol));
@@ -91,7 +91,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
{
// An array/indexer initializer of the form `[...] = ...`
int indexChild = 0;
var indexChild = 0;
foreach (var arg in iea.ArgumentList.Arguments)
{
Expression.Create(cx, arg.Expression, access, indexChild++);
@@ -136,7 +136,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
var init = (InitializerExpressionSyntax)i;
int addChild = 0;
var addChild = 0;
foreach (var arg in init.Expressions)
{
Create(cx, arg, invocation, addChild++);

View File

@@ -112,7 +112,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
}
var child = 0;
Expression objectInitializer = Syntax.Initializers.Any() ?
var objectInitializer = Syntax.Initializers.Any() ?
new Expression(new ExpressionInfo(cx, Type, Location, ExprKind.OBJECT_INIT, this, -1, false, null)) :
null;

View File

@@ -198,7 +198,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
var info = cx.GetModel(node).GetQueryClauseInfo(node.FromClause);
var method = info.OperationInfo.Symbol as IMethodSymbol;
Clause clauseExpr = new RangeClause(method, node.FromClause, cx.GetModel(node).GetDeclaredSymbol(node.FromClause), node.FromClause.Identifier).AddArgument(node.FromClause.Expression);
var clauseExpr = new RangeClause(method, node.FromClause, cx.GetModel(node).GetDeclaredSymbol(node.FromClause), node.FromClause.Identifier).AddArgument(node.FromClause.Expression);
foreach (var qc in node.Body.Clauses)
{

View File

@@ -15,7 +15,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
protected override void PopulateExpression(TextWriter trapFile)
{
int child = 0;
var child = 0;
foreach (var argument in Syntax.Arguments.Select(a => a.Expression))
{
Expression.Create(cx, argument, this, child++);

View File

@@ -31,7 +31,7 @@ namespace Semmle.Extraction.CSharp.Entities
ContainingType.PopulateGenerics();
PopulateNullability(trapFile, symbol.GetAnnotatedType());
Field unboundFieldKey = Field.Create(Context, symbol.OriginalDefinition);
var unboundFieldKey = Field.Create(Context, symbol.OriginalDefinition);
trapFile.fields(this, (symbol.IsConst ? 2 : 1), symbol.Name, ContainingType, Type.Type.TypeRef, unboundFieldKey);
PopulateModifiers(trapFile);
@@ -57,7 +57,7 @@ namespace Semmle.Extraction.CSharp.Entities
Context.BindComments(this, Location.symbol);
int child = 0;
var child = 0;
foreach (var initializer in symbol.DeclaringSyntaxReferences
.Select(n => n.GetSyntax())
.OfType<VariableDeclaratorSyntax>()

View File

@@ -169,7 +169,7 @@ namespace Semmle.Extraction.CSharp.Entities
protected static void AddParametersToId(Context cx, TextWriter trapFile, IMethodSymbol method)
{
trapFile.Write('(');
int index = 0;
var index = 0;
var @params = method.MethodKind == MethodKind.ReducedExtension
? method.ReducedFrom.Parameters
@@ -293,7 +293,7 @@ namespace Semmle.Extraction.CSharp.Entities
if (IsGeneric)
{
int child = 0;
var child = 0;
if (isFullyConstructed)
{

View File

@@ -72,7 +72,7 @@ namespace Semmle.Extraction.CSharp.Entities
public static void ExtractModifiers(Context cx, TextWriter trapFile, IEntity key, ISymbol symbol)
{
bool interfaceDefinition = symbol.ContainingType != null
var interfaceDefinition = symbol.ContainingType != null
&& symbol.ContainingType.Kind == SymbolKind.NamedType
&& symbol.ContainingType.TypeKind == TypeKind.Interface;
@@ -86,7 +86,7 @@ namespace Semmle.Extraction.CSharp.Entities
if (symbol.IsSealed)
HasModifier(cx, trapFile, key, "sealed");
bool fromSource = symbol.DeclaringSyntaxReferences.Length > 0;
var fromSource = symbol.DeclaringSyntaxReferences.Length > 0;
if (symbol.IsStatic && !(symbol.Kind == SymbolKind.Field && ((IFieldSymbol)symbol).IsConst && !fromSource))
HasModifier(cx, trapFile, key, "static");
@@ -115,7 +115,7 @@ namespace Semmle.Extraction.CSharp.Entities
if (symbol.Kind == SymbolKind.NamedType)
{
INamedTypeSymbol nt = symbol as INamedTypeSymbol;
var nt = symbol as INamedTypeSymbol;
if (nt is null)
throw new InternalError(symbol, "Symbol kind is inconsistent with its type");

View File

@@ -16,7 +16,7 @@ namespace Semmle.Extraction.CSharp.Entities
if (symbol.ContainingNamespace != null)
{
Namespace parent = Create(Context, symbol.ContainingNamespace);
var parent = Create(Context, symbol.ContainingNamespace);
trapFile.parent_namespace(this, parent);
}
}

View File

@@ -34,7 +34,7 @@ namespace Semmle.Extraction.CSharp.Entities
// omit the "this" parameter, so the parameters are
// actually numbered from 1.
// This is to be consistent from the original (unreduced) extension method.
bool isReducedExtension =
var isReducedExtension =
symbol.ContainingSymbol is IMethodSymbol method &&
method.MethodKind == MethodKind.ReducedExtension;
return symbol.Ordinal + (isReducedExtension ? 1 : 0);
@@ -91,7 +91,7 @@ namespace Semmle.Extraction.CSharp.Entities
// Very rarely, two parameters have the same name according to the data model.
// This breaks our database constraints.
// Generate an impossible name to ensure that it doesn't conflict.
int conflictingCount = symbol.ContainingSymbol.GetParameters().Count(p => p.Ordinal < symbol.Ordinal && p.Name == symbol.Name);
var conflictingCount = symbol.ContainingSymbol.GetParameters().Count(p => p.Ordinal < symbol.Ordinal && p.Name == symbol.Name);
return conflictingCount > 0 ? symbol.Name + "`" + conflictingCount : symbol.Name;
}
}

View File

@@ -77,7 +77,7 @@ namespace Semmle.Extraction.CSharp.Entities
Context.PopulateLater(() => Expression.Create(Context, expressionBody, this, 0));
}
int child = 1;
var child = 1;
foreach (var initializer in declSyntaxReferences
.Select(n => n.Initializer)
.Where(i => i != null))
@@ -119,7 +119,7 @@ namespace Semmle.Extraction.CSharp.Entities
public static Property Create(Context cx, IPropertySymbol prop)
{
bool isIndexer = prop.IsIndexer || prop.Parameters.Any();
var isIndexer = prop.IsIndexer || prop.Parameters.Any();
return isIndexer ? Indexer.Create(cx, prop) : PropertyFactory.Instance.CreateEntityFromSymbol(cx, prop);
}

View File

@@ -14,8 +14,8 @@ namespace Semmle.Extraction.CSharp.Entities.Statements
protected override void PopulateStatement(TextWriter trapFile)
{
bool isSpecificCatchClause = Stmt.Declaration != null;
bool hasVariableDeclaration = isSpecificCatchClause && Stmt.Declaration.Identifier.RawKind != 0;
var isSpecificCatchClause = Stmt.Declaration != null;
var hasVariableDeclaration = isSpecificCatchClause && Stmt.Declaration.Identifier.RawKind != 0;
if (hasVariableDeclaration) // A catch clause of the form 'catch(Ex ex) { ... }'
{

View File

@@ -19,7 +19,7 @@ namespace Semmle.Extraction.CSharp.Entities.Statements
protected override void PopulateStatement(TextWriter trapFile)
{
int child = -1;
var child = -1;
if (Stmt.Declaration != null)
VariableDeclarations.Populate(cx, Stmt.Declaration, this, child, childIncrement: -1);

View File

@@ -31,7 +31,7 @@ namespace Semmle.Extraction.CSharp.Entities.Statements
protected override void PopulateStatement(TextWriter trapFile)
{
Expression.Create(cx, Stmt.Expression, this, 0);
int childIndex = 0;
var childIndex = 0;
foreach (var section in Stmt.Sections)
{

View File

@@ -52,7 +52,7 @@ namespace Semmle.Extraction.CSharp.Entities
}
else if (symbol.IsReallyUnbound())
{
for (int i = 0; i < symbol.TypeParameters.Length; ++i)
for (var i = 0; i < symbol.TypeParameters.Length; ++i)
{
TypeParameter.Create(Context, symbol.TypeParameters[i]);
var param = symbol.TypeParameters[i];
@@ -67,7 +67,7 @@ namespace Semmle.Extraction.CSharp.Entities
: Type.Create(Context, symbol.ConstructedFrom);
trapFile.constructed_generic(this, unbound.TypeRef);
for (int i = 0; i < symbol.TypeArguments.Length; ++i)
for (var i = 0; i < symbol.TypeArguments.Length; ++i)
{
trapFile.type_arguments(TypeArguments[i].TypeRef, i, this);
}

View File

@@ -71,7 +71,7 @@ namespace Semmle.Extraction.CSharp.Entities
public override int GetHashCode()
{
int h = Annotation;
var h = Annotation;
foreach (var t in NullableParameters)
h = h * 5 + t.GetHashCode();
@@ -112,7 +112,7 @@ namespace Semmle.Extraction.CSharp.Entities
{
trapFile.nullability(this, symbol.Annotation);
int i = 0;
var i = 0;
foreach (var s in symbol.NullableParameters)
{
trapFile.nullability_parent(Create(Context, s), i, this);

View File

@@ -45,7 +45,7 @@ namespace Semmle.Extraction.CSharp.Entities
trapFile.tuple_underlying_type(this, underlyingType);
int index = 0;
var index = 0;
foreach (var element in TupleElements)
trapFile.tuple_element(this, index++, element);

View File

@@ -105,7 +105,7 @@ namespace Semmle.Extraction.CSharp.Entities
var baseTypes = new List<Type>();
if (symbol.GetNonObjectBaseType(Context) is INamedTypeSymbol @base)
{
Type baseKey = Create(Context, @base);
var baseKey = Create(Context, @base);
trapFile.extend(this, baseKey.TypeRef);
if (symbol.TypeKind != TypeKind.Struct)
baseTypes.Add(baseKey);
@@ -123,7 +123,7 @@ namespace Semmle.Extraction.CSharp.Entities
var containingType = ContainingType;
if (containingType != null && symbol.Kind != SymbolKind.TypeParameter)
{
Type originalDefinition = symbol.TypeKind == TypeKind.Error ? this : Create(Context, symbol.OriginalDefinition);
var originalDefinition = symbol.TypeKind == TypeKind.Error ? this : Create(Context, symbol.OriginalDefinition);
trapFile.nested_types(this, containingType, originalDefinition);
}
else if (symbol.ContainingNamespace != null)
@@ -134,16 +134,16 @@ namespace Semmle.Extraction.CSharp.Entities
if (symbol is IArrayTypeSymbol)
{
// They are in the namespace of the original object
ITypeSymbol elementType = ((IArrayTypeSymbol)symbol).ElementType;
INamespaceSymbol ns = elementType.TypeKind == TypeKind.TypeParameter ? Context.Compilation.GlobalNamespace : elementType.ContainingNamespace;
var elementType = ((IArrayTypeSymbol)symbol).ElementType;
var ns = elementType.TypeKind == TypeKind.TypeParameter ? Context.Compilation.GlobalNamespace : elementType.ContainingNamespace;
if (ns != null)
trapFile.parent_namespace(this, Namespace.Create(Context, ns));
}
if (symbol is IPointerTypeSymbol)
{
ITypeSymbol elementType = ((IPointerTypeSymbol)symbol).PointedAtType;
INamespaceSymbol ns = elementType.TypeKind == TypeKind.TypeParameter ? Context.Compilation.GlobalNamespace : elementType.ContainingNamespace;
var elementType = ((IPointerTypeSymbol)symbol).PointedAtType;
var ns = elementType.TypeKind == TypeKind.TypeParameter ? Context.Compilation.GlobalNamespace : elementType.ContainingNamespace;
if (ns != null)
trapFile.parent_namespace(this, Namespace.Create(Context, ns));

View File

@@ -49,7 +49,7 @@ namespace Semmle.Extraction.CSharp.Entities
trapFile.types(this, Kinds.TypeKind.TYPE_PARAMETER, symbol.Name);
Namespace parentNs = Namespace.Create(Context, symbol.TypeParameterKind == TypeParameterKind.Method ? Context.Compilation.GlobalNamespace : symbol.ContainingNamespace);
var parentNs = Namespace.Create(Context, symbol.TypeParameterKind == TypeParameterKind.Method ? Context.Compilation.GlobalNamespace : symbol.ContainingNamespace);
trapFile.parent_namespace(this, parentNs);
foreach (var l in symbol.Locations)

View File

@@ -178,7 +178,7 @@ namespace Semmle.Extraction.CSharp.Entities
/// <returns>The converted name.</returns>
public static string OperatorSymbol(Context cx, string methodName)
{
if (!OperatorSymbol(methodName, out string result))
if (!OperatorSymbol(methodName, out var result))
cx.ModelError($"Unhandled operator name in OperatorSymbol(): '{methodName}'");
return result;
}

View File

@@ -42,7 +42,7 @@ namespace Semmle.Extraction.CSharp.Entities
else
{
// A "using static"
Type m = Type.Create(cx, (ITypeSymbol)info.Symbol);
var m = Type.Create(cx, (ITypeSymbol)info.Symbol);
trapFile.using_static_directives(this, m.TypeRef);
trapFile.using_directive_location(this, cx.Create(ReportingLocation));
}

View File

@@ -25,7 +25,7 @@ namespace Semmle.Extraction.CSharp.Populators
public override void VisitArgumentList(ArgumentListSyntax node)
{
int c = 0;
var c = 0;
foreach (var m in node.Arguments)
{
cx.Extract(m, parent, c++);

View File

@@ -101,7 +101,7 @@ namespace Semmle.Extraction.CSharp.Populators
}
// Gather comments:
foreach (SyntaxTrivia trivia in compilationUnit.DescendantTrivia(compilationUnit.Span))
foreach (var trivia in compilationUnit.DescendantTrivia(compilationUnit.Span))
{
CommentLine.Extract(cx, trivia);
}

View File

@@ -21,8 +21,8 @@ namespace Semmle.Extraction.CSharp.Populators
}
var l2 = n2.FixedLocation();
int start = System.Math.Min(l1.SourceSpan.Start, l2.SourceSpan.Start);
int end = System.Math.Max(l1.SourceSpan.End, l2.SourceSpan.End);
var start = System.Math.Min(l1.SourceSpan.Start, l2.SourceSpan.Start);
var end = System.Math.Max(l1.SourceSpan.End, l2.SourceSpan.End);
return Location.Create(n2.SyntaxTree, new Microsoft.CodeAnalysis.Text.TextSpan(start, end - start));
}

View File

@@ -12,7 +12,7 @@ namespace Semmle.Extraction.CSharp.Populators
{
public override LineCounts DefaultVisit(SyntaxNode node)
{
string text = node.SyntaxTree.GetText().GetSubText(node.GetLocation().SourceSpan).ToString();
var text = node.SyntaxTree.GetText().GetSubText(node.GetLocation().SourceSpan).ToString();
return Semmle.Util.LineCounter.ComputeLineCounts(text);
}
@@ -23,12 +23,12 @@ namespace Semmle.Extraction.CSharp.Populators
public static LineCounts Visit(SyntaxToken identifier, SyntaxNode body)
{
int start = identifier.GetLocation().SourceSpan.Start;
int end = body.GetLocation().SourceSpan.End - 1;
var start = identifier.GetLocation().SourceSpan.Start;
var end = body.GetLocation().SourceSpan.End - 1;
var textSpan = new Microsoft.CodeAnalysis.Text.TextSpan(start, end - start);
string text = body.SyntaxTree.GetText().GetSubText(textSpan) + "\r\n";
var text = body.SyntaxTree.GetText().GetSubText(textSpan) + "\r\n";
return Semmle.Util.LineCounter.ComputeLineCounts(text);
}

View File

@@ -239,7 +239,7 @@ namespace Semmle.Extraction.CSharp
public static void BuildArraySuffix(this IArrayTypeSymbol array, TextWriter trapFile)
{
trapFile.Write('[');
for (int i = 0; i < array.Rank - 1; i++)
for (var i = 0; i < array.Rank - 1; i++)
trapFile.Write(',');
trapFile.Write(']');
}
@@ -347,8 +347,8 @@ namespace Semmle.Extraction.CSharp
private static void BuildAnonymousName(this INamedTypeSymbol type, Context cx, TextWriter trapFile)
{
int memberCount = type.GetMembers().OfType<IPropertySymbol>().Count();
int hackTypeNumber = memberCount == 1 ? 1 : 0;
var memberCount = type.GetMembers().OfType<IPropertySymbol>().Count();
var hackTypeNumber = memberCount == 1 ? 1 : 0;
trapFile.Write("<>__AnonType");
trapFile.Write(hackTypeNumber);
trapFile.Write('<');

View File

@@ -50,7 +50,7 @@ namespace Semmle.Extraction.CommentProcessing
if (l1 == null) return -1;
if (l2 == null) return 1;
int diff = l1.SourceTree == l2.SourceTree ? 0 : l1.SourceTree.FilePath.CompareTo(l2.SourceTree.FilePath);
var diff = l1.SourceTree == l2.SourceTree ? 0 : l1.SourceTree.FilePath.CompareTo(l2.SourceTree.FilePath);
if (diff != 0) return diff;
diff = l1.SourceSpan.Start - l2.SourceSpan.Start;
if (diff != 0) return diff;
@@ -312,7 +312,7 @@ namespace Semmle.Extraction.CommentProcessing
* (Note that comment processing is O(n.log n) overall due to dictionary of elements and comments.)
*/
ElementStack elementStack = new ElementStack();
var elementStack = new ElementStack();
using IEnumerator<KeyValuePair<Location, Label>> elementEnumerator = elements.GetEnumerator();
using IEnumerator<KeyValuePair<Location, ICommentLine>> commentEnumerator = comments.GetEnumerator();
@@ -361,11 +361,11 @@ namespace Semmle.Extraction.CommentProcessing
{
if (!CommentLines.Any()) return true;
bool sameFile = Location.SourceTree == newLine.Location.SourceTree;
bool sameRow = Location.EndLine() == newLine.Location.StartLine();
bool sameColumn = Location.EndLine() + 1 == newLine.Location.StartLine();
bool nextRow = Location.StartColumn() == newLine.Location.StartColumn();
bool adjacent = sameFile && (sameRow || (sameColumn && nextRow));
var sameFile = Location.SourceTree == newLine.Location.SourceTree;
var sameRow = Location.EndLine() == newLine.Location.StartLine();
var sameColumn = Location.EndLine() + 1 == newLine.Location.StartLine();
var nextRow = Location.StartColumn() == newLine.Location.StartColumn();
var adjacent = sameFile && (sameRow || (sameColumn && nextRow));
return
newLine.Type == CommentLineType.MultilineContinuation ||

View File

@@ -143,12 +143,12 @@ namespace Semmle.Extraction
{
var lines = File.ReadAllLines(layout);
int i = 0;
var i = 0;
while (!lines[i].StartsWith("#"))
i++;
while (i < lines.Length)
{
LayoutBlock block = new LayoutBlock(lines, ref i);
var block = new LayoutBlock(lines, ref i);
blocks.Add(block);
}
@@ -174,7 +174,7 @@ namespace Semmle.Extraction
private static string? ReadVariable(string name, string line)
{
string prefix = name + "=";
var prefix = name + "=";
if (!line.StartsWith(prefix))
return null;
return line.Substring(prefix.Length).Trim();
@@ -184,10 +184,10 @@ namespace Semmle.Extraction
{
// first line: #name
i++;
string? TRAP_FOLDER = ReadVariable("TRAP_FOLDER", lines[i++]);
var TRAP_FOLDER = ReadVariable("TRAP_FOLDER", lines[i++]);
// Don't care about ODASA_DB.
ReadVariable("ODASA_DB", lines[i++]);
string? SOURCE_ARCHIVE = ReadVariable("SOURCE_ARCHIVE", lines[i++]);
var SOURCE_ARCHIVE = ReadVariable("SOURCE_ARCHIVE", lines[i++]);
Directories = new Layout.SubProject(TRAP_FOLDER, SOURCE_ARCHIVE);
// Don't care about ODASA_BUILD_ERROR_DIR.

View File

@@ -18,9 +18,9 @@ namespace Semmle.Extraction
/// <returns>Whether inner is completely container in outer.</returns>
public static bool Contains(this Location outer, Location inner)
{
bool sameFile = outer.SourceTree == inner.SourceTree;
bool startsBefore = outer.SourceSpan.Start <= inner.SourceSpan.Start;
bool endsAfter = outer.SourceSpan.End >= inner.SourceSpan.End;
var sameFile = outer.SourceTree == inner.SourceTree;
var startsBefore = outer.SourceSpan.Start <= inner.SourceSpan.Start;
var endsAfter = outer.SourceSpan.End >= inner.SourceSpan.End;
return sameFile && startsBefore && endsAfter;
}
@@ -32,8 +32,8 @@ namespace Semmle.Extraction
/// <returns>Whether 'before' comes before 'after'.</returns>
public static bool Before(this Location before, Location after)
{
bool sameFile = before.SourceTree == after.SourceTree;
bool endsBefore = before.SourceSpan.End <= after.SourceSpan.Start;
var sameFile = before.SourceTree == after.SourceTree;
var endsBefore = before.SourceSpan.End <= after.SourceSpan.Start;
return sameFile && endsBefore;
}
}

View File

@@ -127,7 +127,7 @@ namespace Semmle.Extraction
var sections = new List<TransformerSection>();
try
{
int i = 0;
var i = 0;
while (i < lines.Length && !lines[i].StartsWith("#"))
i++;
while (i < lines.Length)

View File

@@ -110,7 +110,7 @@ namespace Semmle.Extraction
/// <returns>The truncated string.</returns>
private static string TruncateString(string s, ref int bytesRemaining)
{
int outputLen = encoding.GetByteCount(s);
var outputLen = encoding.GetByteCount(s);
if (outputLen > bytesRemaining)
{
outputLen = 0;
@@ -149,7 +149,7 @@ namespace Semmle.Extraction
if (NeedsTruncation(s))
{
// Slow path
int remaining = maxStringBytes;
var remaining = maxStringBytes;
WriteTruncatedString(trapFile, s, ref remaining);
}
else
@@ -169,7 +169,7 @@ namespace Semmle.Extraction
{
trapFile.Write(name);
trapFile.Write('(');
int index = 0;
var index = 0;
foreach (var p in @params)
{
trapFile.WriteSeparator(",", ref index);
@@ -246,7 +246,7 @@ namespace Semmle.Extraction
/// <returns>The original trap builder (fluent interface).</returns>
public static TextWriter BuildList<T>(this TextWriter trapFile, string separator, IEnumerable<T> items, Action<T, TextWriter> action)
{
bool first = true;
var first = true;
foreach (var item in items)
{
if (first)

View File

@@ -109,7 +109,7 @@ namespace Semmle.Extraction
if (string.IsNullOrEmpty(archive)) return;
// Calling GetFullPath makes this use the canonical capitalisation, if the file exists.
string fullInputPath = Path.GetFullPath(originalPath);
var fullInputPath = Path.GetFullPath(originalPath);
ArchivePath(fullInputPath, transformedPath, inputEncoding);
}
@@ -208,14 +208,14 @@ namespace Semmle.Extraction
/// exceed the system path limit of 260 characters.</exception>
private void ArchivePath(string fullInputPath, PathTransformer.ITransformedPath transformedPath, Encoding inputEncoding)
{
string contents = File.ReadAllText(fullInputPath, inputEncoding);
var contents = File.ReadAllText(fullInputPath, inputEncoding);
ArchiveContents(transformedPath, contents);
}
private void ArchiveContents(PathTransformer.ITransformedPath transformedPath, string contents)
{
string dest = NestPaths(Logger, archive, transformedPath.Value);
string tmpSrcFile = Path.GetTempFileName();
var dest = NestPaths(Logger, archive, transformedPath.Value);
var tmpSrcFile = Path.GetTempFileName();
File.WriteAllText(tmpSrcFile, contents, UTF8);
try
{
@@ -231,7 +231,7 @@ namespace Semmle.Extraction
public static string NestPaths(ILogger logger, string? outerpath, string innerpath)
{
string nested = innerpath;
var nested = innerpath;
if (!string.IsNullOrEmpty(outerpath))
{
// Remove all leading path separators / or \

View File

@@ -30,7 +30,7 @@ namespace Semmle.Util
actions.Add(key, action);
}
if (values.TryGetValue(key, out Value val))
if (values.TryGetValue(key, out var val))
{
action(val);
}

View File

@@ -40,7 +40,7 @@ namespace Semmle.Util
/// <returns>A canonical path.</returns>
protected static string ConstructCanonicalPath(string path, IPathCache cache)
{
DirectoryInfo parent = Directory.GetParent(path);
var parent = Directory.GetParent(path);
return parent != null ?
Path.Combine(cache.GetCanonicalPath(parent.FullName), Path.GetFileName(path)) :
@@ -85,8 +85,8 @@ namespace Semmle.Util
return ConstructCanonicalPath(path, cache);
}
StringBuilder outPath = new StringBuilder(Win32.MAX_PATH);
int length = Win32.GetFinalPathNameByHandle(hFile, outPath, outPath.Capacity, 0); // lgtm[cs/call-to-unmanaged-code]
var outPath = new StringBuilder(Win32.MAX_PATH);
var length = Win32.GetFinalPathNameByHandle(hFile, outPath, outPath.Capacity, 0); // lgtm[cs/call-to-unmanaged-code]
if (length >= outPath.Capacity)
{
@@ -104,7 +104,7 @@ namespace Semmle.Util
return ConstructCanonicalPath(path, cache);
}
string result = outPath.ToString(PREAMBLE, length - PREAMBLE); // Trim off leading \\?\
var result = outPath.ToString(PREAMBLE, length - PREAMBLE); // Trim off leading \\?\
return result.StartsWith("UNC")
? @"\" + result.Substring(3)
@@ -120,7 +120,7 @@ namespace Semmle.Util
{
public override string GetCanonicalPath(string path, IPathCache cache)
{
DirectoryInfo parent = Directory.GetParent(path);
var parent = Directory.GetParent(path);
if (parent == null)
{
@@ -135,7 +135,7 @@ namespace Semmle.Util
var parentPath = cache.GetCanonicalPath(parent.FullName);
try
{
string[] entries = Directory.GetFileSystemEntries(parentPath, name);
var entries = Directory.GetFileSystemEntries(parentPath, name);
return entries.Length == 1
? entries[0]
: Path.Combine(parentPath, name);

View File

@@ -19,7 +19,7 @@ namespace Semmle.Util
foreach (var arg in commandLineArguments.Where(arg => arg.StartsWith('@')).Select(arg => arg.Substring(1)))
{
string? line;
using StreamReader file = new StreamReader(arg);
using var file = new StreamReader(arg);
while ((line = file.ReadLine()) != null)
textWriter.WriteLine(line);
found = true;

View File

@@ -41,9 +41,9 @@ namespace Semmle.Util
{
public static void ParseArguments(this ICommandLineOptions options, IReadOnlyList<string> arguments)
{
for (int i = 0; i < arguments.Count; ++i)
for (var i = 0; i < arguments.Count; ++i)
{
string arg = arguments[i];
var arg = arguments[i];
if (arg.StartsWith("--"))
{
var colon = arg.IndexOf(':');

View File

@@ -51,7 +51,7 @@ namespace Semmle.Util
{
var kv = new KeyValuePair<string, T>(k, v);
string root = StripDigits(k);
var root = StripDigits(k);
index.AddAnother(root, kv);
}
@@ -74,7 +74,7 @@ namespace Semmle.Util
/// <returns>The best match, or null (default).</returns>
public T? FindMatch(string query, out int distance)
{
string root = StripDigits(query);
var root = StripDigits(query);
if (!index.TryGetValue(root, out var list))
{
distance = 0;
@@ -94,13 +94,13 @@ namespace Semmle.Util
/// <returns>The stored value.</returns>
private static T? BestMatch(string query, IEnumerable<KeyValuePair<string, T>> candidates, Func<string, string, int> distance, out int bestDistance)
{
T? bestMatch = default(T);
var bestMatch = default(T);
bestDistance = 0;
bool first = true;
var first = true;
foreach (var candidate in candidates)
{
int d = distance(query, candidate.Key);
var d = distance(query, candidate.Key);
if (d == 0) return candidate.Value;
if (first || d < bestDistance)
@@ -121,8 +121,8 @@ namespace Semmle.Util
/// <returns>String with digits removed.</returns>
private static string StripDigits(string input)
{
StringBuilder result = new StringBuilder();
foreach (char c in input.Where(c => !char.IsDigit(c)))
var result = new StringBuilder();
foreach (var c in input.Where(c => !char.IsDigit(c)))
result.Append(c);
return result.ToString();
}
@@ -134,9 +134,9 @@ namespace Semmle.Util
/// <returns>The sequence of integers.</returns>
public static IEnumerable<int> ExtractIntegers(string input)
{
bool inNumber = false;
int value = 0;
foreach (char c in input)
var inNumber = false;
var value = 0;
foreach (var c in input)
{
if (char.IsDigit(c))
{

View File

@@ -33,8 +33,8 @@ namespace Semmle.Util
/// </summary>
public static IEnumerable<T> Interleave<T>(this IEnumerable<T> first, IEnumerable<T> second)
{
using IEnumerator<T> enumerator1 = first.GetEnumerator();
using IEnumerator<T> enumerator2 = second.GetEnumerator();
using var enumerator1 = first.GetEnumerator();
using var enumerator2 = second.GetEnumerator();
bool moveNext1;
while ((moveNext1 = enumerator1.MoveNext()) && enumerator2.MoveNext())
{
@@ -94,7 +94,7 @@ namespace Semmle.Util
/// <returns>The hash code.</returns>
public static int SequenceHash<T>(this IEnumerable<T> items) where T : notnull
{
int h = 0;
var h = 0;
foreach (var i in items)
h = h * 7 + i.GetHashCode();
return h;

View File

@@ -242,7 +242,7 @@ namespace Semmle.Util
private static void ReadRestOfString(string input, Context context)
{
char? cur = '\0';
int numSlashes = 0;
var numSlashes = 0;
while (cur != null && ((cur = GetNext(input, context)) != '"' || (numSlashes % 2 != 0)))
{
if (cur == '\\') ++numSlashes;

View File

@@ -66,7 +66,7 @@ namespace Semmle.Util.Logging
try
{
string? dir = Path.GetDirectoryName(outputFile);
var dir = Path.GetDirectoryName(outputFile);
if (!string.IsNullOrEmpty(dir) && !System.IO.Directory.Exists(dir))
Directory.CreateDirectory(dir);
writer = new PidStreamWriter(

View File

@@ -30,7 +30,7 @@ namespace Semmle.Util
/// <returns>The original StringBuilder (fluent interface).</returns>
public static StringBuilder BuildList<T>(this StringBuilder builder, string separator, IEnumerable<T> items, Action<T, StringBuilder> action)
{
bool first = true;
var first = true;
foreach (var item in items)
{
if (first) first = false; else builder.Append(separator);

View File

@@ -42,7 +42,7 @@ namespace Semmle.Util
public string GetAll()
{
using var sw = new StringWriter();
foreach (string s in lines)
foreach (var s in lines)
{
sw.WriteLine(s);
}
@@ -71,7 +71,7 @@ namespace Semmle.Util
using var sw = new StringWriter();
string line;
for (int i = startRow; i <= endRow; ++i)
for (var i = startRow; i <= endRow; ++i)
{
if (i == startRow && i == endRow)
{

View File

@@ -48,7 +48,7 @@ namespace Semmle.Util
/// </returns>
public LinkedList<T> GetUnprocessedElements()
{
LinkedList<T> result = internalList;
var result = internalList;
internalList = new LinkedList<T>();
hasNewElements = false;
return result;