Skip to content

Commit

Permalink
Code cleanup (#416)
Browse files Browse the repository at this point in the history
I just upgraded to VS 17.13, and it has more code-style opinions than
17.12 did.

VS wants to fix IDE0306 by generating invalid code, but I went ahead and
applied most of the rest.
  • Loading branch information
shpaass authored Feb 14, 2025
2 parents f3b0e97 + 9851f25 commit 9b57fdb
Show file tree
Hide file tree
Showing 33 changed files with 91 additions and 84 deletions.
3 changes: 3 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -166,3 +166,6 @@ dotnet_diagnostic.IDE0052.severity = none
dotnet_style_namespace_match_folder = false

spelling_exclusion_path = exclusion.dic

# Suppress IDE0306 because it (only?) triggers on Queue<T>, which does not have an Add method.
dotnet_diagnostic.IDE0306.severity = none
1 change: 1 addition & 0 deletions FactorioCalc.sln
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Yafc.Model.Tests", "Yafc.Mo
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{D6A715CB-5C17-4DD7-9ADA-5D7F44FADFCF}"
ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig
changelog.txt = changelog.txt
Directory.Build.props = Directory.Build.props
exclusion.dic = exclusion.dic
Expand Down
1 change: 0 additions & 1 deletion Yafc.Model.Tests/Analysis/Milestones.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System.Reflection;
using Xunit;

#pragma warning disable CA1861 // "CA1861: Avoid constant arrays as arguments." Disabled because it tried to fix constant arrays in InlineData.
namespace Yafc.Model.Tests;

public class MilestonesTests {
Expand Down
2 changes: 0 additions & 2 deletions Yafc.Model.Tests/Math/Bits.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
using System.Reflection;
using Xunit;

#pragma warning disable CA1861 // "CA1861: Avoid constant arrays as arguments." Disabled because it tried to fix constant arrays in InlineData.

namespace Yafc.Model.Tests;

public class BitsTests {
Expand Down
2 changes: 1 addition & 1 deletion Yafc.Model.Tests/Model/ProductionTableContentTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public void ChangeProductionTableModuleConfig_ShouldPreserveFixedAmount() {
table.AddRecipe(Database.recipes.all.Single(r => r.name == "recipe"), DataUtils.DeterministicComparer);
RecipeRow row = table.GetAllRecipes().Single();

List<Module> modules = Database.allModules.Where(m => !m.name.Contains("productivity")).ToList();
List<Module> modules = [.. Database.allModules.Where(m => !m.name.Contains("productivity"))];
EntityBeacon beacon = Database.allBeacons.Single();

RunTest(row, testCombinations, (3 * 3 + 3 * 1) * 6 * 13 * 32 * 6); // Crafter&fuel * modules * beacon count * payback values * available fixed values
Expand Down
4 changes: 2 additions & 2 deletions Yafc.Model/Analysis/DependencyNode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ internal static DependencyNode Create(IEnumerable<DependencyNode> dependencies)
realDependencies.Add(item);
}
}
realDependencies = realDependencies.Distinct().ToList();
realDependencies = [.. realDependencies.Distinct()];

if (realDependencies.Count == 0) {
throw new ArgumentException($"Must not join zero nodes with an 'and'. Instead, create an empty DependencyList to explain what expected dependencies are missing.");
Expand Down Expand Up @@ -196,7 +196,7 @@ internal static DependencyNode Create(IEnumerable<DependencyNode> dependencies)
realDependencies.Add(item);
}
}
realDependencies = realDependencies.Distinct().ToList();
realDependencies = [.. realDependencies.Distinct()];

if (realDependencies.Count == 0) {
throw new ArgumentException($"Must not join zero nodes with an 'or'. Instead, create an empty DependencyList to explain what expected dependencies are missing.");
Expand Down
6 changes: 3 additions & 3 deletions Yafc.Model/Analysis/Milestones.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,8 @@ private enum ProcessingFlags : byte {

public override void Compute(Project project, ErrorCollector warnings) {
if (project.settings.milestones.Count == 0) {
FactorioObject[] milestones = new List<FactorioObject>([.. Database.allSciencePacks, .. Database.locations.all])
.Where(m => m is not Location { name: "nauvis" or "space-location-unknown" }).ToArray();
FactorioObject[] milestones = [.. new List<FactorioObject>([.. Database.allSciencePacks, .. Database.locations.all])
.Where(m => m is not Location { name: "nauvis" or "space-location-unknown" })];
ComputeWithParameters(project, warnings, milestones, true);
}
else {
Expand Down Expand Up @@ -131,7 +131,7 @@ public void ComputeWithParameters(Project project, ErrorCollector warnings, Fact
// Do these in parallel; the only write operation for these is setting the dictionary value at the end.
Parallel.ForEach(milestones, milestone => {
logger.Information("Processing milestone {Milestone}", milestone.locName);
HashSet<FactorioObject> pruneAt = new(markedInaccessible.Append(milestone));
HashSet<FactorioObject> pruneAt = [.. markedInaccessible.Append(milestone)];
accessibility[milestone.id] = WalkAccessibilityGraph(project, pruneAt, [], null);
});

Expand Down
2 changes: 1 addition & 1 deletion Yafc.Model/Data/DataClasses.cs
Original file line number Diff line number Diff line change
Expand Up @@ -576,7 +576,7 @@ public sealed override DependencyNode GetDependencies() {
foreach (Ammo ammo in captureAmmo) {
List<EntitySpawner> spawners;
if (ammo.targetFilter == null) {
spawners = Database.objects.all.OfType<EntitySpawner>().Where(s => s.capturedEntityName == name).ToList();
spawners = [.. Database.objects.all.OfType<EntitySpawner>().Where(s => s.capturedEntityName == name)];
}
else {
spawners = ammo.targetFilter.Select(t => Database.objectsByTypeName["Entity." + t] as EntitySpawner)
Expand Down
6 changes: 3 additions & 3 deletions Yafc.Model/Model/AutoPlanner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ public override async Task<string> Solve(ProjectPage page) {
}
}

HashSet<(Recipe, Recipe[])> remainingNodes = new HashSet<(Recipe, Recipe[])>(subgraph.Select(x => x.userData));
HashSet<(Recipe, Recipe[])> remainingNodes = [.. subgraph.Select(x => x.userData)];
List<(Recipe, Recipe[])> nodesToClear = [];
List<AutoPlannerRecipe[]> tiers = [];
List<Recipe> currentTier = [];
Expand Down Expand Up @@ -246,13 +246,13 @@ public override async Task<string> Solve(ProjectPage page) {
remainingNodes.Clear();
logger.Information("Tier creation failure");
}
tiers.Add(currentTier.Select(x => new AutoPlannerRecipe {
tiers.Add([.. currentTier.Select(x => new AutoPlannerRecipe {
recipe = x,
tier = tiers.Count,
recipesPerSecond = (float)processedRecipes[x].SolutionValue(),
downstream = downstream.TryGetValue(x, out var res) ? res : null,
upstream = upstream.TryGetValue(x, out var res2) ? res2 : null
}).ToArray());
})]);
}
bestFlowSolver.Dispose();
await Ui.EnterMainThread();
Expand Down
6 changes: 3 additions & 3 deletions Yafc.Model/Model/ProductionTableContent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ internal void GetModulesInfo(RecipeRow row, EntityCrafter entity, ref ModuleEffe
}

if (beacon != null) {
int beaconCount = CalcBeaconCount();
int beaconCount = CalculateBeaconCount();
if (beaconCount > 0) {
float beaconEfficiency = beacon.GetBeaconEfficiency() * beacon.target.GetProfile(beaconCount);
foreach (var module in beaconList) {
Expand All @@ -159,9 +159,9 @@ internal void GetModulesInfo(RecipeRow row, EntityCrafter entity, ref ModuleEffe
used.modules = [.. buffer];
}

public int CalcBeaconCount() {
public int CalculateBeaconCount() {
if (beacon is null) {
throw new InvalidOperationException($"Must not call {nameof(CalcBeaconCount)} when {nameof(beacon)} is null.");
throw new InvalidOperationException($"Must not call {nameof(CalculateBeaconCount)} when {nameof(beacon)} is null.");
}

int moduleCount = 0;
Expand Down
3 changes: 0 additions & 3 deletions Yafc.Model/Model/RecipeParameters.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,6 @@ public static RecipeParameters CalculateParameters(RecipeRow row) {
if (entity == null) {
warningFlags |= WarningFlags.EntityNotSpecified;
recipeTime = recipe.time;
productivity = 0f;
speed = 0;
consumption = 0f;
}
else {
recipeTime = recipe.time / entity.GetCraftingSpeed();
Expand Down
5 changes: 3 additions & 2 deletions Yafc.Model/Serialization/ErrorCollector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@ public void Error(string message, ErrorSeverity severity) {
logger.Information(message);
}

public (string error, ErrorSeverity severity)[] GetArrErrors() => allErrors.OrderByDescending(x => x.Key.severity).ThenByDescending(x => x.Value)
.Select(x => (x.Value == 1 ? x.Key.message : x.Key.message + " (x" + x.Value + ")", x.Key.severity)).ToArray();
public (string error, ErrorSeverity severity)[] GetArrErrors()
=> [.. allErrors.OrderByDescending(x => x.Key.severity).ThenByDescending(x => x.Value)
.Select(x => (x.Value == 1 ? x.Key.message : x.Key.message + " (x" + x.Value + ")", x.Key.severity))];

public void Exception(Exception exception, string message, ErrorSeverity errorSeverity) {
while (exception.InnerException != null) {
Expand Down
16 changes: 8 additions & 8 deletions Yafc.Parser/Data/FactorioDataDeserializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ private static void AddTemperatureToFluidIcon(Fluid fluid) {
string iconStr = fluid.temperature + "d";
fluid.iconSpec =
[
.. fluid.iconSpec,
.. fluid.iconSpec ?? [],
.. iconStr.Take(4).Select((x, n) => new FactorioIconPart("__.__/" + x) { y = -16, x = (n * 7) - 12, scale = 0.28f }),
];
}
Expand Down Expand Up @@ -399,7 +399,7 @@ private void DeserializeItem(LuaTable table, ErrorCollector _1) {
ammo_type.ReadObjectOrArray(readAmmoType);

if (ammo_type["target_filter"] is LuaTable targets) {
ammo.targetFilter = new(targets.ArrayElements.OfType<string>());
ammo.targetFilter = [.. targets.ArrayElements.OfType<string>()];
}

void readAmmoType(LuaTable table) {
Expand Down Expand Up @@ -437,7 +437,7 @@ void readTrigger(LuaTable table) {
if (table.Get("send_to_orbit_mode", "not-sendable") != "not-sendable" || item.factorioType == "space-platform-starter-pack") {
Product[] launchProducts;
if (table.Get("rocket_launch_products", out LuaTable? products)) {
launchProducts = products.ArrayElements<LuaTable>().Select(LoadProduct(item.typeDotName, item.stackSize)).ToArray();
launchProducts = [.. products.ArrayElements<LuaTable>().Select(LoadProduct(item.typeDotName, item.stackSize))];
}
else {
launchProducts = [];
Expand Down Expand Up @@ -557,7 +557,7 @@ private void CalculateItemWeights() {
nextWeightCalculation:;
}

List<EntityCrafter> rocketSilos = registeredObjects.Values.OfType<EntityCrafter>().Where(e => e.factorioType == "rocket-silo").ToList();
List<EntityCrafter> rocketSilos = [.. registeredObjects.Values.OfType<EntityCrafter>().Where(e => e.factorioType == "rocket-silo")];
int maxStacks = 1;// if we have no rocket silos, default to one stack.
if (rocketSilos.Count > 0) {
maxStacks = rocketSilos.Max(r => r.rocketInventorySize);
Expand Down Expand Up @@ -678,10 +678,10 @@ private void DeserializeLocation(LuaTable table, ErrorCollector collector) {
Location location = DeserializeCommon<Location>(table, "space-location");
if (table.Get("map_gen_settings", out LuaTable? mapGen)) {
if (mapGen.Get("autoplace_controls", out LuaTable? controls)) {
location.placementControls = controls.ObjectElements.Keys.OfType<string>().ToList();
location.placementControls = [.. controls.ObjectElements.Keys.OfType<string>()];
}
if (mapGen.Get<LuaTable>("autoplace_settings").Get<LuaTable>("entity").Get<LuaTable>("settings") is LuaTable entities) {
location.entitySpawns = entities.ObjectElements.Keys.OfType<string>().ToList();
location.entitySpawns = [.. entities.ObjectElements.Keys.OfType<string>()];
}
if (mapGen.Get<LuaTable>("autoplace_settings").Get<LuaTable>("tile").Get<LuaTable>("settings") is LuaTable tiles) {
foreach (string tile in tiles.ObjectElements.Keys.Cast<string>()) {
Expand Down Expand Up @@ -727,7 +727,7 @@ private void DeserializeLocation(LuaTable table, ErrorCollector collector) {
target.iconSpec = [new FactorioIconPart(s) { size = defaultIconSize }];
}
else if (table.Get("icons", out LuaTable? iconList)) {
target.iconSpec = iconList.ArrayElements<LuaTable>().Select(x => {
target.iconSpec = [.. iconList.ArrayElements<LuaTable>().Select(x => {
if (!x.Get("icon", out string? path)) {
throw new NotSupportedException($"One of the icon layers for {name} does not have a path.");
}
Expand All @@ -749,7 +749,7 @@ private void DeserializeLocation(LuaTable table, ErrorCollector collector) {
}

return part;
}).ToArray();
})];
}

return target;
Expand Down
30 changes: 15 additions & 15 deletions Yafc.Parser/Data/FactorioDataDeserializer_Context.cs
Original file line number Diff line number Diff line change
Expand Up @@ -226,12 +226,12 @@ private void ExportBuiltData() {
Database.fluidVariants = fluidVariants;

Database.allModules = [.. allModules];
Database.allBeacons = Database.entities.all.OfType<EntityBeacon>().ToArray();
Database.allCrafters = Database.entities.all.OfType<EntityCrafter>().ToArray();
Database.allBelts = Database.entities.all.OfType<EntityBelt>().ToArray();
Database.allInserters = Database.entities.all.OfType<EntityInserter>().ToArray();
Database.allAccumulators = Database.entities.all.OfType<EntityAccumulator>().ToArray();
Database.allContainers = Database.entities.all.OfType<EntityContainer>().ToArray();
Database.allBeacons = [.. Database.entities.all.OfType<EntityBeacon>()];
Database.allCrafters = [.. Database.entities.all.OfType<EntityCrafter>()];
Database.allBelts = [.. Database.entities.all.OfType<EntityBelt>()];
Database.allInserters = [.. Database.entities.all.OfType<EntityInserter>()];
Database.allAccumulators = [.. Database.entities.all.OfType<EntityAccumulator>()];
Database.allContainers = [.. Database.entities.all.OfType<EntityContainer>()];

Database.rocketCapacity = rocketCapacity;
}
Expand Down Expand Up @@ -419,8 +419,8 @@ private void CalculateMaps(bool netProduction) {
}

if (entity is EntityCrafter crafter) {
crafter.recipes = recipeCrafters.GetRaw(crafter)
.SelectMany(x => recipeCategories.GetRaw(x).Where(y => y.CanFit(crafter.itemInputs, crafter.fluidInputs, crafter.inputs))).ToArray();
crafter.recipes = [.. recipeCrafters.GetRaw(crafter)
.SelectMany(x => recipeCategories.GetRaw(x).Where(y => y.CanFit(crafter.itemInputs, crafter.fluidInputs, crafter.inputs)))];
foreach (var recipe in crafter.recipes) {
actualRecipeCrafters.Add(recipe, crafter, true);
}
Expand Down Expand Up @@ -478,7 +478,7 @@ private void CalculateMaps(bool netProduction) {
break;
case Goods goods:
goods.usages = itemUsages.GetArray(goods);
goods.production = itemProduction.GetArray(goods).Distinct().ToArray();
goods.production = [.. itemProduction.GetArray(goods).Distinct()];
goods.miscSources = miscSources.GetArray(goods);

if (o is Item item) {
Expand Down Expand Up @@ -510,7 +510,7 @@ private void CalculateMaps(bool netProduction) {
entity.mapGenerated = true;
}

entity.sourceEntities = asteroids.GetArray(entity.name).ToList();
entity.sourceEntities = [.. asteroids.GetArray(entity.name)];
break;
case Location location:
location.technologyUnlock = locationUnlockers.GetArray(location);
Expand Down Expand Up @@ -675,9 +675,9 @@ private Recipe CreateSpecialRecipe(FactorioObject production, string category, s
}

private void ParseCaptureEffects() {
HashSet<string> captureRobots = new(allObjects.Where(e => e.factorioType == "capture-robot").Select(e => e.name));
HashSet<string> captureRobots = [.. allObjects.Where(e => e.factorioType == "capture-robot").Select(e => e.name)];
// Projectiles that create capture robots.
HashSet<string> captureProjectiles = new(allObjects.OfType<EntityProjectile>().Where(p => p.placeEntities.Intersect(captureRobots).Any()).Select(p => p.name));
HashSet<string> captureProjectiles = [.. allObjects.OfType<EntityProjectile>().Where(p => p.placeEntities.Intersect(captureRobots).Any()).Select(p => p.name)];
// Ammo that creates projectiles that create capture robots.
List<Ammo> captureAmmo = [.. allObjects.OfType<Ammo>().Where(a => captureProjectiles.Intersect(a.projectileNames).Any())];

Expand Down Expand Up @@ -725,7 +725,7 @@ public void Seal(Func<TKey, IEnumerable<TValue>>? addExtraItems = null) {

// Add the extra values to the list when provided before storing the complete array.
IEnumerable<TValue> completeList = addExtraItems != null ? list.Concat(addExtraItems(key)) : list;
TValue[] completeArray = completeList.ToArray();
TValue[] completeArray = [.. completeList];

storage[key] = completeArray;
}
Expand All @@ -752,15 +752,15 @@ public void Add(TKey key, TValue value, bool checkUnique = false) {

public TValue[] GetArray(TKey key) {
if (!storage.TryGetValue(key, out var list)) {
return defaultList(key).ToArray();
return [.. defaultList(key)];
}

return list is TValue[] value ? value : [.. list];
}

public IList<TValue> GetRaw(TKey key) {
if (!storage.TryGetValue(key, out var list)) {
list = defaultList(key).ToList();
list = [.. defaultList(key)];

if (isSealed) {
list = [.. list];
Expand Down
Loading

0 comments on commit 9b57fdb

Please sign in to comment.