Skip to content

Commit

Permalink
More .NET 8 code cleanup (#116)
Browse files Browse the repository at this point in the history
It turned out all those inspections that were re-enabled and didn't fix
anything were just dormant for some reason. Perhaps I should've
restarted Visual Studio for them to work.

This PR includes three parts:
* The changes mentioned
#88. Essentially,
now everything is lambdas.
```
csharp_style_expression_bodied_methods = true:suggestion
csharp_style_expression_bodied_constructors = true:suggestion
csharp_style_expression_bodied_operators = true:suggestion
```
The main reason for these changes is that we already enabled arrow
notation for the properties, and the other parts of the code stop
looking weird with arrows if you read them for a bit.
* The improvements from unmuted suggestions.
* A
[bugfix](72de773)
that I found when applying suggestions.

QA: checked the basic functionality on an existing Pyanodons project
file.
  • Loading branch information
shpaass authored May 10, 2024
2 parents 99fb80d + d2434c0 commit 19b1d24
Show file tree
Hide file tree
Showing 89 changed files with 643 additions and 1,166 deletions.
6 changes: 3 additions & 3 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,9 @@ csharp_style_var_when_type_is_apparent = false:suggestion
# For all else, we prefer non-var but don't enforce it
csharp_style_var_elsewhere = false:none
# Expression-bodied members
csharp_style_expression_bodied_methods = false:suggestion
csharp_style_expression_bodied_constructors = false:suggestion
csharp_style_expression_bodied_operators = false:suggestion
csharp_style_expression_bodied_methods = true:suggestion
csharp_style_expression_bodied_constructors = true:suggestion
csharp_style_expression_bodied_operators = true:suggestion
csharp_style_expression_bodied_properties = true:suggestion
csharp_style_expression_bodied_indexers = true:suggestion
csharp_style_expression_bodied_accessors = true:suggestion
Expand Down
8 changes: 4 additions & 4 deletions Yafc.Model.Tests/Analysis/Milestones.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using System.Collections.Generic;
using System.Reflection;
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 {
private static Bits createBits(ulong value) {
Expand All @@ -19,7 +19,7 @@ private static Bits createBits(ulong value) {
private static Milestones setupMilestones(ulong result, ulong mask, out FactorioObject factorioObj) {
factorioObj = new Technology();
Mapping<FactorioObject, Bits> milestoneResult = new Mapping<FactorioObject, Bits>(
new FactorioIdRange<FactorioObject>(0, 1, new List<FactorioObject>() { factorioObj })) {
new FactorioIdRange<FactorioObject>(0, 1, [factorioObj])) {
[factorioObj] = createBits(result)
};

Expand All @@ -29,7 +29,7 @@ private static Milestones setupMilestones(ulong result, ulong mask, out Factorio
var milestoneResultField = milestonesType.GetField("milestoneResult", BindingFlags.NonPublic | BindingFlags.Instance);

Milestones milestones = new Milestones() {
currentMilestones = new FactorioObject[] { factorioObj }
currentMilestones = [factorioObj]
};

milestoneResultField.SetValue(milestones, milestoneResult);
Expand Down
2 changes: 1 addition & 1 deletion Yafc.Model/Analysis/Analysis.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace Yafc.Model {
public abstract class Analysis {
public abstract void Compute(Project project, ErrorCollector warnings);

private static readonly List<Analysis> analyses = new List<Analysis>();
private static readonly List<Analysis> analyses = [];
public static void RegisterAnalysis(Analysis analysis, params Analysis[] dependencies) // TODO don't ignore dependencies
{
analyses.Add(analysis);
Expand Down
32 changes: 14 additions & 18 deletions Yafc.Model/Analysis/CostAnalysis.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
using Google.OrTools.LinearSolver;

namespace Yafc.Model {
public class CostAnalysis : Analysis {
public class CostAnalysis(bool onlyCurrentMilestones) : Analysis {
public static readonly CostAnalysis Instance = new CostAnalysis(false);
public static readonly CostAnalysis InstanceAtMilestones = new CostAnalysis(true);
public static CostAnalysis Get(bool atCurrentMilestones) {
Expand All @@ -32,27 +32,23 @@ public static CostAnalysis Get(bool atCurrentMilestones) {
public Mapping<FactorioObject, float> flow;
public Mapping<Recipe, float> recipeWastePercentage;
public Goods[] importantItems;
private readonly bool onlyCurrentMilestones;
private readonly bool onlyCurrentMilestones = onlyCurrentMilestones;
private string itemAmountPrefix;

public CostAnalysis(bool onlyCurrentMilestones) {
this.onlyCurrentMilestones = onlyCurrentMilestones;
}

private bool ShouldInclude(FactorioObject obj) {
return onlyCurrentMilestones ? obj.IsAutomatableWithCurrentMilestones() : obj.IsAutomatable();
}

public override void Compute(Project project, ErrorCollector warnings) {
var solver = DataUtils.CreateSolver("WorkspaceSolver");
var objective = solver.Objective();
var workspaceSolver = DataUtils.CreateSolver();
var objective = workspaceSolver.Objective();
objective.SetMaximization();
Stopwatch time = Stopwatch.StartNew();

var variables = Database.goods.CreateMapping<Variable>();
var constraints = Database.recipes.CreateMapping<Constraint>();

Dictionary<Goods, float> sciencePackUsage = new Dictionary<Goods, float>();
Dictionary<Goods, float> sciencePackUsage = [];
if (!onlyCurrentMilestones && project.preferences.targetTechnology != null) {
itemAmountPrefix = "Estimated amount for " + project.preferences.targetTechnology.locName + ": ";
foreach (var spUsage in TechnologyScienceAnalysis.Instance.allSciencePacks[project.preferences.targetTechnology]) {
Expand Down Expand Up @@ -93,7 +89,7 @@ public override void Compute(Project project, ErrorCollector warnings) {
}
}
}
var variable = solver.MakeVar(CostLowerLimit, CostLimitWhenGeneratesOnMap / mapGeneratedAmount, false, goods.name);
var variable = workspaceSolver.MakeVar(CostLowerLimit, CostLimitWhenGeneratesOnMap / mapGeneratedAmount, false, goods.name);
objective.SetCoefficient(variable, 1e-3); // adding small amount to each object cost, so even objects that aren't required for science will get cost calculated
variables[goods] = variable;
}
Expand Down Expand Up @@ -176,7 +172,7 @@ public override void Compute(Project project, ErrorCollector warnings) {
singleUsedFuel = null;
}

var constraint = solver.MakeConstraint(double.NegativeInfinity, 0, recipe.name);
var constraint = workspaceSolver.MakeConstraint(double.NegativeInfinity, 0, recipe.name);
constraints[recipe] = constraint;

foreach (var product in recipe.products) {
Expand Down Expand Up @@ -237,7 +233,7 @@ public override void Compute(Project project, ErrorCollector warnings) {
if (ShouldInclude(item)) {
foreach (var source in item.miscSources) {
if (source is Goods g && ShouldInclude(g)) {
var constraint = solver.MakeConstraint(double.NegativeInfinity, 0, "source-" + item.locName);
var constraint = workspaceSolver.MakeConstraint(double.NegativeInfinity, 0, "source-" + item.locName);
constraint.SetCoefficient(variables[g], -1);
constraint.SetCoefficient(variables[item], 1);
}
Expand All @@ -250,14 +246,14 @@ public override void Compute(Project project, ErrorCollector warnings) {
var prev = fluids[0];
for (int i = 1; i < fluids.Count; i++) {
var cur = fluids[i];
var constraint = solver.MakeConstraint(double.NegativeInfinity, 0, "fluid-" + name + "-" + prev.temperature);
var constraint = workspaceSolver.MakeConstraint(double.NegativeInfinity, 0, "fluid-" + name + "-" + prev.temperature);
constraint.SetCoefficient(variables[prev], 1);
constraint.SetCoefficient(variables[cur], -1);
prev = cur;
}
}

var result = solver.TrySolveWithDifferentSeeds();
var result = workspaceSolver.TrySolveWithDifferentSeeds();
Console.WriteLine("Cost analysis completed in " + time.ElapsedMilliseconds + " ms. with result " + result);
float sumImportance = 1f;
int totalRecipes = 0;
Expand Down Expand Up @@ -339,9 +335,9 @@ public override void Compute(Project project, ErrorCollector warnings) {
}
}

importantItems = Database.goods.all.Where(x => x.usages.Length > 1).OrderByDescending(x => flow[x] * cost[x] * x.usages.Count(y => ShouldInclude(y) && recipeWastePercentage[y] == 0f)).ToArray();
importantItems = [.. Database.goods.all.Where(x => x.usages.Length > 1).OrderByDescending(x => flow[x] * cost[x] * x.usages.Count(y => ShouldInclude(y) && recipeWastePercentage[y] == 0f))];

solver.Dispose();
workspaceSolver.Dispose();
}

public override string description => "Cost analysis computes a hypothetical late-game base. This simulation has two very important results: How much does stuff (items, recipes, etc) cost and how much of stuff do you need. " +
Expand Down Expand Up @@ -380,13 +376,13 @@ public static string GetDisplayCost(FactorioObject goods) {

_ = sb.Append(costPrefix).Append(" ¥").Append(DataUtils.FormatAmount(compareCost, UnitOfMeasure.None));
if (compareCostNow > compareCost && !float.IsPositiveInfinity(compareCostNow)) {
_ = sb.Append(" (Currently ¥").Append(DataUtils.FormatAmount(compareCostNow, UnitOfMeasure.None)).Append(")");
_ = sb.Append(" (Currently ¥").Append(DataUtils.FormatAmount(compareCostNow, UnitOfMeasure.None)).Append(')');
}

return sb.ToString();
}

public float GetBuildingHours(Recipe recipe, float flow) {
public static float GetBuildingHours(Recipe recipe, float flow) {
return recipe.time * flow * (1000f / 3600f);
}

Expand Down
6 changes: 3 additions & 3 deletions Yafc.Model/Analysis/Dependencies.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,11 @@ public static void Calculate() {
dependencyList = Database.objects.CreateMapping<DependencyList[]>();
reverseDependencies = Database.objects.CreateMapping<List<FactorioId>>();
foreach (var obj in Database.objects.all) {
reverseDependencies[obj] = new List<FactorioId>();
reverseDependencies[obj] = [];
}

DependencyCollector collector = new DependencyCollector();
List<FactorioObject> temp = new List<FactorioObject>();
List<FactorioObject> temp = [];
foreach (var obj in Database.objects.all) {
obj.GetDependencies(collector, temp);
var packed = collector.Pack();
Expand All @@ -58,7 +58,7 @@ public static void Calculate() {
}

private class DependencyCollector : IDependencyCollector {
private readonly List<DependencyList> list = new List<DependencyList>();
private readonly List<DependencyList> list = [];

public void Add(FactorioId[] raw, DependencyList.Flags flags) {
list.Add(new DependencyList { elements = raw, flags = flags });
Expand Down
2 changes: 1 addition & 1 deletion Yafc.Model/Analysis/Milestones.cs
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ public void ComputeWithParameters(Project project, ErrorCollector warnings, Fact
if (i > 0) {
var milestone = currentMilestones[i - 1];
if (milestone == null) {
milestonesNotReachable = new List<FactorioObject>();
milestonesNotReachable = [];
foreach (var pack in Database.allSciencePacks) {
if (Array.IndexOf(currentMilestones, pack) == -1) {
currentMilestones[nextMilestoneIndex++] = pack;
Expand Down
12 changes: 6 additions & 6 deletions Yafc.Model/Blueprints/Blueprint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ public class Blueprint {

public string item { get; set; } = "blueprint";
public string label { get; set; }
public List<BlueprintEntity> entities { get; } = new List<BlueprintEntity>();
public List<BlueprintIcon> icons { get; } = new List<BlueprintIcon>();
public List<BlueprintEntity> entities { get; } = [];
public List<BlueprintIcon> icons { get; } = [];
public int version { get; set; } = VERSION;
}

Expand Down Expand Up @@ -96,7 +96,7 @@ public class BlueprintEntity {
public string recipe { get; set; }
[JsonPropertyName("control_behavior")] public BlueprintControlBehavior controlBehavior { get; set; }
public BlueprintConnection connections { get; set; }
[JsonPropertyName("request_filters")] public List<BlueprintRequestFilter> requestFilters { get; } = new List<BlueprintRequestFilter>();
[JsonPropertyName("request_filters")] public List<BlueprintRequestFilter> requestFilters { get; } = [];
public Dictionary<string, int> items { get; set; }

public void Connect(BlueprintEntity other, bool red = true, bool secondPort = false, bool targetSecond = false) {
Expand Down Expand Up @@ -134,8 +134,8 @@ public class BlueprintConnection {

[Serializable]
public class BlueprintConnectionPoint {
public List<BlueprintConnectionData> red { get; } = new List<BlueprintConnectionData>();
public List<BlueprintConnectionData> green { get; } = new List<BlueprintConnectionData>();
public List<BlueprintConnectionData> red { get; } = [];
public List<BlueprintConnectionData> green { get; } = [];
}

[Serializable]
Expand All @@ -152,7 +152,7 @@ public class BlueprintPosition {

[Serializable]
public class BlueprintControlBehavior {
public List<BlueprintControlFilter> filters { get; } = new List<BlueprintControlFilter>();
public List<BlueprintControlFilter> filters { get; } = [];
}

[Serializable]
Expand Down
27 changes: 11 additions & 16 deletions Yafc.Model/Data/DataClasses.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ public abstract class RecipeOrTechnology : FactorioObject {
public EntityCrafter[] crafters { get; internal set; }
public Ingredient[] ingredients { get; internal set; }
public Product[] products { get; internal set; }
public Item[] modules { get; internal set; } = Array.Empty<Item>();
public Item[] modules { get; internal set; } = [];
public Entity sourceEntity { get; internal set; }
public Goods mainProduct { get; internal set; }
public float time { get; internal set; }
Expand Down Expand Up @@ -378,7 +378,7 @@ public enum AllowedEffects {
}

public class Entity : FactorioObject {
public Product[] loot { get; internal set; } = Array.Empty<Product>();
public Product[] loot { get; internal set; } = [];
public bool mapGenerated { get; internal set; }
public float mapGenDensity { get; internal set; }
public float power { get; internal set; }
Expand Down Expand Up @@ -482,8 +482,8 @@ public class EntityContainer : Entity {
public class Technology : RecipeOrTechnology // Technology is very similar to recipe
{
public float count { get; internal set; } // TODO support formula count
public Technology[] prerequisites { get; internal set; } = Array.Empty<Technology>();
public Recipe[] unlockRecipes { get; internal set; } = Array.Empty<Recipe>();
public Technology[] prerequisites { get; internal set; } = [];
public Recipe[] unlockRecipes { get; internal set; } = [];
internal override FactorioObjectSortOrder sortingOrder => FactorioObjectSortOrder.Technologies;
public override string type => "Technology";

Expand Down Expand Up @@ -529,35 +529,30 @@ public class ModuleSpecification {
public Recipe[] limitation_blacklist { get; internal set; }
}

public struct TemperatureRange {
public int min;
public int max;
public struct TemperatureRange(int min, int max) {
public int min = min;
public int max = max;

public static readonly TemperatureRange Any = new TemperatureRange(int.MinValue, int.MaxValue);
public bool IsAny() {
public readonly bool IsAny() {
return min == int.MinValue && max == int.MaxValue;
}

public bool IsSingle() {
public readonly bool IsSingle() {
return min == max;
}

public TemperatureRange(int min, int max) {
this.min = min;
this.max = max;
}

public TemperatureRange(int single) : this(single, single) { }

public override string ToString() {
public override readonly string ToString() {
if (min == max) {
return min + "°";
}

return min + "°-" + max + "°";
}

public bool Contains(int value) {
public readonly bool Contains(int value) {
return min <= value && max >= value;
}
}
Expand Down
Loading

0 comments on commit 19b1d24

Please sign in to comment.