Skip to content

Commit

Permalink
Fix CA1851, assume_method_enumerates_parameters = true
Browse files Browse the repository at this point in the history
  • Loading branch information
RoosterDragon committed Aug 11, 2023
1 parent e3d0dd8 commit 5bf18d4
Show file tree
Hide file tree
Showing 37 changed files with 108 additions and 96 deletions.
4 changes: 2 additions & 2 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -836,8 +836,8 @@ dotnet_diagnostic.CA1850.severity = none

# Possible multiple enumerations of IEnumerable collection.
#dotnet_code_quality.CA1851.enumeration_methods =
#dotnet_code_quality.CA1851.linq_chain_methods =
#dotnet_code_quality.CA1851.assume_method_enumerates_parameters = false
dotnet_code_quality.CA1851.linq_chain_methods = M:OpenRA.Traits.IRenderModifier.Modify*
dotnet_code_quality.CA1851.assume_method_enumerates_parameters = true
dotnet_diagnostic.CA1851.severity = warning

# Seal internal types.
Expand Down
2 changes: 1 addition & 1 deletion OpenRA.Game/Exts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ public static T RandomOrDefault<T>(this IEnumerable<T> ts, MersenneTwister r)

static T Random<T>(IEnumerable<T> ts, MersenneTwister r, bool throws)
{
var xs = ts as ICollection<T>;
var xs = ts as IReadOnlyCollection<T>;
xs ??= ts.ToList();
if (xs.Count == 0)
{
Expand Down
5 changes: 3 additions & 2 deletions OpenRA.Game/Game.cs
Original file line number Diff line number Diff line change
Expand Up @@ -523,10 +523,11 @@ static string ChooseShellmap()
.Where(m => m.Status == MapStatus.Available && m.Visibility.HasFlag(MapVisibility.Shellmap))
.Select(m => m.Uid);

if (!shellmaps.Any())
var shellmap = shellmaps.RandomOrDefault(CosmeticRandom);
if (shellmap == null)
throw new InvalidDataException("No valid shellmaps available");

return shellmaps.Random(CosmeticRandom);
return shellmap;
}

public static void SwitchToExternalMod(ExternalMod mod, string[] launchArguments = null, Action onFailed = null)
Expand Down
2 changes: 2 additions & 0 deletions OpenRA.Game/GameRules/ActorInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ public IEnumerable<TraitInfo> TraitsInConstructOrder()

// Continue resolving traits as long as possible.
// Each time we resolve some traits, this means dependencies for other traits may then be possible to satisfy in the next pass.
#pragma warning disable CA1851 // Possible multiple enumerations of 'IEnumerable' collection
var readyToResolve = more.ToList();
while (readyToResolve.Count != 0)
{
Expand All @@ -138,6 +139,7 @@ public IEnumerable<TraitInfo> TraitsInConstructOrder()
readyToResolve.Clear();
readyToResolve.AddRange(more);
}
#pragma warning restore CA1851

if (unresolved.Count != 0)
{
Expand Down
7 changes: 5 additions & 2 deletions OpenRA.Game/Graphics/Viewport.cs
Original file line number Diff line number Diff line change
Expand Up @@ -299,10 +299,13 @@ IEnumerable<MPos> CandidateMouseoverCells(int2 world)

public void Center(IEnumerable<Actor> actors)
{
if (!actors.Any())
var actorsCollection = actors as IReadOnlyCollection<Actor>;
actorsCollection ??= actors.ToList();

if (actorsCollection.Count == 0)
return;

Center(actors.Select(a => a.CenterPosition).Average());
Center(actorsCollection.Select(a => a.CenterPosition).Average());
}

public void Center(WPos pos)
Expand Down
5 changes: 1 addition & 4 deletions OpenRA.Game/SelectableExts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,7 @@ static int BaseSelectionPriority(ISelectableInfo info, Modifiers modifiers)

public static Actor WithHighestSelectionPriority(this IEnumerable<ActorBoundsPair> actors, int2 selectionPixel, Modifiers modifiers)
{
if (!actors.Any())
return null;

return actors.MaxBy(a => CalculateActorSelectionPriority(a.Actor.Info, a.Bounds, selectionPixel, modifiers)).Actor;
return actors.MaxByOrDefault(a => CalculateActorSelectionPriority(a.Actor.Info, a.Bounds, selectionPixel, modifiers)).Actor;
}

public static FrozenActor WithHighestSelectionPriority(this IEnumerable<FrozenActor> actors, int2 selectionPixel, Modifiers modifiers)
Expand Down
2 changes: 1 addition & 1 deletion OpenRA.Game/Support/AssemblyLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ static IEnumerable<string> GetRids(RuntimeFallbacks runtimeGraph)
return Enumerable.Concat(new[] { runtimeGraph.Runtime }, runtimeGraph?.Fallbacks ?? Enumerable.Empty<string>());
}

static IEnumerable<string> SelectAssets(IEnumerable<string> rids, IEnumerable<RuntimeAssetGroup> groups)
static IEnumerable<string> SelectAssets(IEnumerable<string> rids, IReadOnlyCollection<RuntimeAssetGroup> groups)
{
foreach (var rid in rids)
{
Expand Down
2 changes: 1 addition & 1 deletion OpenRA.Game/Traits/TraitsInterfaces.cs
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,7 @@ public interface ISelectableInfo : ITraitInfoInterface
public interface ISelection
{
int Hash { get; }
IEnumerable<Actor> Actors { get; }
IReadOnlyCollection<Actor> Actors { get; }

void Add(Actor a);
void Remove(Actor a);
Expand Down
3 changes: 2 additions & 1 deletion OpenRA.Mods.Common/Activities/Air/Land.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

using System;
using System.Collections.Generic;
using System.Linq;
using OpenRA.Activities;
using OpenRA.Mods.Common.Traits;
using OpenRA.Primitives;
Expand Down Expand Up @@ -211,7 +212,7 @@ public override bool Tick(Actor self)

if (!landingInitiated)
{
var blockingCells = clearCells.Append(landingCell);
var blockingCells = clearCells.Append(landingCell).ToList();

if (!aircraft.CanLand(blockingCells, target.Actor))
{
Expand Down
8 changes: 4 additions & 4 deletions OpenRA.Mods.Common/Lint/CheckConditions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,12 @@ static void Run(Action<string> emitError, Action<string> emitWarning, Ruleset ru
granted.Add(g);
}

var unconsumed = granted.Except(consumed);
if (unconsumed.Any())
var unconsumed = granted.Except(consumed).ToList();
if (unconsumed.Count != 0)
emitWarning($"Actor type `{actorInfo.Key}` grants conditions that are not consumed: {unconsumed.JoinWith(", ")}.");

var ungranted = consumed.Except(granted);
if (ungranted.Any())
var ungranted = consumed.Except(granted).ToList();
if (ungranted.Count != 0)
emitError($"Actor type `{actorInfo.Key}` consumes conditions that are not granted: {ungranted.JoinWith(", ")}.");
}
}
Expand Down
19 changes: 9 additions & 10 deletions OpenRA.Mods.Common/Lint/CheckSyncAnnotations.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@ sealed class CheckSyncAnnotations : ILintPass
public void Run(Action<string> emitError, Action<string> emitWarning, ModData modData)
{
var modTypes = modData.ObjectCreator.GetTypes();
CheckTypesWithSyncableMembersImplementSyncInterface(modTypes, emitWarning);
CheckTypesImplementingSyncInterfaceHaveSyncableMembers(modTypes, emitWarning);
CheckTypes(modTypes, emitWarning);
}

static readonly Type SyncInterface = typeof(ISync);
Expand All @@ -45,18 +44,18 @@ static bool AnyTypeMemberIsSynced(Type type)
return false;
}

static void CheckTypesWithSyncableMembersImplementSyncInterface(IEnumerable<Type> types, Action<string> emitWarning)
static void CheckTypes(IEnumerable<Type> types, Action<string> emitWarning)
{
foreach (var type in types)
if (!TypeImplementsSync(type) && AnyTypeMemberIsSynced(type))
emitWarning($"{type.FullName} has members with the Sync attribute but does not implement ISync.");
}
{
var typeImplementsSync = TypeImplementsSync(type);
var anyTypeMemberIsSynced = AnyTypeMemberIsSynced(type);

static void CheckTypesImplementingSyncInterfaceHaveSyncableMembers(IEnumerable<Type> types, Action<string> emitWarning)
{
foreach (var type in types)
if (TypeImplementsSync(type) && !AnyTypeMemberIsSynced(type))
if (!typeImplementsSync && anyTypeMemberIsSynced)
emitWarning($"{type.FullName} has members with the Sync attribute but does not implement ISync.");
else if (typeImplementsSync && !anyTypeMemberIsSynced)
emitWarning($"{type.FullName} implements ISync but does not use the Sync attribute on any members.");
}
}
}
}
2 changes: 1 addition & 1 deletion OpenRA.Mods.Common/Orders/UnitOrderGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public virtual string GetCursor(World world, CPos cell, int2 worldPixel, MouseIn
return cursorOrder.Cursor;

useSelect = target.Type == TargetType.Actor && target.Actor.Info.HasTraitInfo<ISelectableInfo>() &&
(mi.Modifiers.HasModifier(Modifiers.Shift) || !world.Selection.Actors.Any());
(mi.Modifiers.HasModifier(Modifiers.Shift) || world.Selection.Actors.Count == 0);
}

return useSelect ? worldSelectCursor : worldDefaultCursor;
Expand Down
3 changes: 2 additions & 1 deletion OpenRA.Mods.Common/Scripting/Global/ActorGlobal.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ static ActorInit CreateInit(string initName, LuaValue value)
}

var initializers = initType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(m => m.Name == "Initialize" && m.GetParameters().Length == 1);
.Where(m => m.Name == "Initialize" && m.GetParameters().Length == 1)
.ToList();

foreach (var initializer in initializers)
{
Expand Down
9 changes: 5 additions & 4 deletions OpenRA.Mods.Common/ServerTraits/LobbyCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -530,9 +530,9 @@ static bool SlotBot(S server, Connection conn, Session.Client client, string s)

// Pick a random color for the bot
var colorManager = server.ModData.DefaultRules.Actors[SystemActors.World].TraitInfo<IColorPickerManagerInfo>();
var terrainColors = server.ModData.DefaultTerrainInfo[server.Map.TileSet].RestrictedPlayerColors;
var terrainColors = server.ModData.DefaultTerrainInfo[server.Map.TileSet].RestrictedPlayerColors.ToList();
var playerColors = server.LobbyInfo.Clients.Select(c => c.Color)
.Concat(server.Map.Players.Players.Values.Select(p => p.Color));
.Concat(server.Map.Players.Players.Values.Select(p => p.Color)).ToList();

bot.Color = bot.PreferredColor = colorManager.RandomPresetColor(server.Random, terrainColors, playerColors);

Expand Down Expand Up @@ -935,7 +935,8 @@ static bool Faction(S server, Connection conn, Session.Client client, string s)
return true;

var factions = server.Map.WorldActorInfo.TraitInfos<FactionInfo>()
.Where(f => f.Selectable).Select(f => f.InternalName);
.Where(f => f.Selectable).Select(f => f.InternalName)
.ToList();

var faction = parts[1];
if (!factions.Contains(faction))
Expand Down Expand Up @@ -1250,7 +1251,7 @@ void OnError(string message)
server.SendLocalizedMessageTo(connectionToEcho, message);
}

var terrainColors = server.ModData.DefaultTerrainInfo[server.Map.TileSet].RestrictedPlayerColors;
var terrainColors = server.ModData.DefaultTerrainInfo[server.Map.TileSet].RestrictedPlayerColors.ToList();
var playerColors = server.LobbyInfo.Clients.Where(c => c.Index != playerIndex).Select(c => c.Color)
.Concat(server.Map.Players.Players.Values.Select(p => p.Color)).ToList();

Expand Down
5 changes: 3 additions & 2 deletions OpenRA.Mods.Common/Traits/BotModules/BaseBuilderBotModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -239,9 +239,10 @@ void SetRallyPointsForNewProductionBuildings(IBot bot)
CPos ChooseRallyLocationNear(Actor producer)
{
var possibleRallyPoints = world.Map.FindTilesInCircle(producer.Location, Info.RallyPointScanRadius)
.Where(c => IsRallyPointValid(c, producer.Info.TraitInfoOrDefault<BuildingInfo>()));
.Where(c => IsRallyPointValid(c, producer.Info.TraitInfoOrDefault<BuildingInfo>()))
.ToList();

if (!possibleRallyPoints.Any())
if (possibleRallyPoints.Count == 0)
{
AIUtils.BotDebug("{0} has no possible rallypoint near {1}", producer.Owner, producer.Location);
return producer.Location;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ bool HasSufficientPowerForActor(ActorInfo actorInfo)

ActorInfo ChooseBuildingToBuild(ProductionQueue queue)
{
var buildableThings = queue.BuildableItems();
var buildableThings = queue.BuildableItems().ToList();

// This gets used quite a bit, so let's cache it here
var power = GetProducibleBuilding(baseBuilder.Info.PowerTypes, buildableThings,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,12 +154,13 @@ void QueueCaptureOrders(IBot bot)
if (Info.CapturableActorTypes.Count > 0)
capturableTargetOptions = capturableTargetOptions.Where(target => Info.CapturableActorTypes.Contains(target.Info.Name.ToLowerInvariant()));

if (!capturableTargetOptions.Any())
var capturableTargetOptionsList = capturableTargetOptions.ToList();
if (capturableTargetOptionsList.Count == 0)
return;

foreach (var capturer in capturers)
{
var targetActor = capturableTargetOptions.MinByOrDefault(target => (target.CenterPosition - capturer.Actor.CenterPosition).LengthSquared);
var targetActor = capturableTargetOptionsList.MinByOrDefault(target => (target.CenterPosition - capturer.Actor.CenterPosition).LengthSquared);
if (targetActor == null)
continue;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ void IBotTick.BotTick(IBot bot)

internal Actor FindClosestEnemy(WPos pos)
{
var units = World.Actors.Where(IsPreferredEnemyUnit);
var units = World.Actors.Where(IsPreferredEnemyUnit).ToList();
return units.Where(IsNotHiddenUnit).ClosestTo(pos) ?? units.ClosestTo(pos);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,9 @@ protected static Actor FindClosestEnemy(Squad owner)
&& mobile.PathFinder.PathExistsForLocomotor(mobile.Locomotor, first.Location, a.Location)
&& a.AppearsHostileTo(first));

if (navalProductions.Any())
var nearest = navalProductions.ClosestTo(first);
if (nearest != null)
{
var nearest = navalProductions.ClosestTo(first);

// Return nearest when it is FAR enough.
// If the naval production is within MaxBaseRadius, it implies that
// this squad is close to enemy territory and they should expect a naval combat;
Expand Down
7 changes: 2 additions & 5 deletions OpenRA.Mods.Common/Traits/BotModules/UnitBuilderBotModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -163,11 +163,8 @@ void BuildUnit(IBot bot, string name)
ActorInfo ChooseRandomUnitToBuild(ProductionQueue queue)
{
var buildableThings = queue.BuildableItems();
if (!buildableThings.Any())
return null;

var unit = buildableThings.Random(world.LocalRandom);
return HasAdequateAirUnitReloadBuildings(unit) ? unit : null;
var unit = buildableThings.RandomOrDefault(world.LocalRandom);
return unit != null && HasAdequateAirUnitReloadBuildings(unit) ? unit : null;
}

ActorInfo ChooseUnitToBuild(ProductionQueue queue)
Expand Down
2 changes: 1 addition & 1 deletion OpenRA.Mods.Common/Traits/Buildings/RepairableBuilding.cs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ public void RepairBuilding(Actor self, Player player)
if (Repairers.Remove(player))
{
UpdateCondition(self);
if (!Repairers.Any())
if (Repairers.Count == 0)
{
Game.Sound.PlayNotification(self.World.Map.Rules, player, "Speech", Info.RepairingStoppedNotification, player.Faction.InternalName);
TextNotificationsManager.AddTransientLine(Info.RepairingStoppedTextNotification, self.Owner);
Expand Down
8 changes: 3 additions & 5 deletions OpenRA.Mods.Common/Traits/Crates/GiveUnitCrateAction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,11 +111,9 @@ IEnumerable<CPos> GetSuitableCells(CPos near, string unitName)

CPos? ChooseEmptyCellNear(Actor a, string unit)
{
var possibleCells = GetSuitableCells(a.Location, unit);
if (!possibleCells.Any())
return null;

return possibleCells.Random(self.World.SharedRandom);
return GetSuitableCells(a.Location, unit)
.Cast<CPos?>()
.RandomOrDefault(self.World.SharedRandom);
}
}
}
8 changes: 4 additions & 4 deletions OpenRA.Mods.Common/Traits/World/ColorPickerManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ public bool IsInvalidColor(Color color, IEnumerable<Color> candidateBlockers)
return false;
}

Color MakeValid(float hue, float sat, float val, MersenneTwister random, IEnumerable<Color> terrainColors, IEnumerable<Color> playerColors, Action<string> onError)
Color MakeValid(float hue, float sat, float val, MersenneTwister random, IReadOnlyCollection<Color> terrainColors, IReadOnlyCollection<Color> playerColors, Action<string> onError)
{
// Clamp saturation without triggering a warning
// This can only happen due to rounding errors (common) or modified clients (rare)
Expand Down Expand Up @@ -132,7 +132,7 @@ Color MakeValid(float hue, float sat, float val, MersenneTwister random, IEnumer

Color[] IColorPickerManagerInfo.PresetColors => PresetColors;

Color IColorPickerManagerInfo.RandomPresetColor(MersenneTwister random, IEnumerable<Color> terrainColors, IEnumerable<Color> playerColors)
Color IColorPickerManagerInfo.RandomPresetColor(MersenneTwister random, IReadOnlyCollection<Color> terrainColors, IReadOnlyCollection<Color> playerColors)
{
foreach (var color in PresetColors.Shuffle(random))
{
Expand All @@ -148,13 +148,13 @@ Color IColorPickerManagerInfo.RandomPresetColor(MersenneTwister random, IEnumera
return MakeValid(randomHue, randomSat, randomVal, random, terrainColors, playerColors, null);
}

Color IColorPickerManagerInfo.MakeValid(Color color, MersenneTwister random, IEnumerable<Color> terrainColors, IEnumerable<Color> playerColors, Action<string> onError)
Color IColorPickerManagerInfo.MakeValid(Color color, MersenneTwister random, IReadOnlyCollection<Color> terrainColors, IReadOnlyCollection<Color> playerColors, Action<string> onError)
{
var (_, h, s, v) = color.ToAhsv();
return MakeValid(h, s, v, random, terrainColors, playerColors, onError);
}

Color IColorPickerManagerInfo.RandomValidColor(MersenneTwister random, IEnumerable<Color> terrainColors, IEnumerable<Color> playerColors)
Color IColorPickerManagerInfo.RandomValidColor(MersenneTwister random, IReadOnlyCollection<Color> terrainColors, IReadOnlyCollection<Color> playerColors)
{
var h = random.NextFloat();
var s = float2.Lerp(HsvSaturationRange[0], HsvSaturationRange[1], random.NextFloat());
Expand Down
4 changes: 2 additions & 2 deletions OpenRA.Mods.Common/Traits/World/ControlGroups.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public void SelectControlGroup(int group)

public void CreateControlGroup(int group)
{
if (!world.Selection.Actors.Any())
if (world.Selection.Actors.Count == 0)
return;

controlGroups[group].Clear();
Expand All @@ -59,7 +59,7 @@ public void CreateControlGroup(int group)

public void AddSelectionToControlGroup(int group)
{
if (!world.Selection.Actors.Any())
if (world.Selection.Actors.Count == 0)
return;

RemoveActorsFromAllControlGroups(world.Selection.Actors);
Expand Down

0 comments on commit 5bf18d4

Please sign in to comment.