Engine-Contract Analyzers for Managed C# Projects
FOnline.Analyzers checks Managed C# script sources against contracts the Engine owns: how attributed entry points are reached, how Invariant helpers are written, and which static fields the shutdown sweep can clear. This page lists those rules, shows how an embedding project enables and configures them, and how it keeps its own style and naming rules in a separate analyzer beside them. The entity-cover rules (FOSYNC*) live in the same assembly and are described in Managed C# Scripting.
Source paths inspected
Source/Scripting/Managed/Analyzers/EntryPointAnalyzer.csSource/Scripting/Managed/Analyzers/InvariantAnalyzer.csSource/Scripting/Managed/Analyzers/ScriptStaticAnalyzer.csSource/Scripting/Managed/Analyzers/CoverVocabulary.csSource/Scripting/Managed/Analyzers/FOnline.Analyzers.csprojSource/Scripting/Managed/Analyzers/AnalyzerReleases.Unshipped.mdSource/Scripting/Managed/Analyzers/Acceptance/EngineContractProbe.csSource/Scripting/Managed/Analyzers/Tests/EngineContractTests.csSource/Scripting/Managed/Analyzers/Tests/FOnline.Analyzers.Tests.csprojSource/Scripting/Managed/CoreScripts/Attributes.csSource/Scripting/Managed/CoreScripts/DatabaseDocument.csSource/Scripting/Managed/CoreScripts/Invariant.csSource/Scripting/Managed/CoreScripts/ScriptStaticCleanup.csSource/Scripting/Managed/ManagedScriptBackend.cppSource/Scripting/AngelScript/AngelScriptAttributes.cppSource/Common/Settings.incSource/Tools/ManagedScriptBaker.cpp
Rules
Every rule is enabled by default at Warning. The generated script project sets TreatWarningsAsErrors=true, so an unconfigured rule already fails CompileManagedScripts and the Managed bake.
| ID | Enforces | Default | Engine owner of the contract |
|---|---|---|---|
FOENTRY001 |
A method carrying a dispatch attribute is not invoked from ordinary code | Warning | Dispatchers in ManagedScriptBackend.cpp; the AngelScript backend applies the same gate in AngelScriptAttributes.cpp |
FOENTRY002 |
A method the engine dispatches or looks up through an attribute is declared internal |
Warning | Reflective lookup in CoreScripts and the backend |
FOENTRY003 |
Every name in an fonline_entry.* option resolves to a type |
Warning | Configuration of the two rules above |
FOVERIFY001 |
An Invariant.Verify message describes the invariant instead of repeating the condition |
Warning | CoreScripts/Invariant.cs |
FOVERIFY002 |
A proved violation uses Invariant.Failed, not Invariant.Verify(false, ...) |
Warning | CoreScripts/Invariant.cs |
FOVERIFY003 |
The condition of Invariant.Verify and the value of Invariant.VerifyNotNull do no work |
Warning | CoreScripts/Invariant.cs |
FOSTATIC001 |
No script static is out of reach of the shutdown sweep | Warning | CoreScripts/ScriptStaticCleanup.cs |
Rule categories are Dispatch (FOENTRY), Verification (FOVERIFY) and Lifetime (FOSTATIC); FOSYNC rules use Synchronization.
Entry points: FOENTRY001 and FOENTRY002
Dispatched attributes are [ModuleInit], [PropertyGetter], [PropertySetter], [AnimCallback], [ScriptFuncRegistrar] and every attribute whose class carries [EntryPointMarker]: [Event], [TimeEvent], the three remote-call markers, [ItemInit], [ItemTrigger], [ItemStatic], [CritterInit], [MapInit] and [LocationInit]. A direct call skips the context the dispatcher prepares and voids the entry point’s [RequiresCover] declaration, which FOSYNC003 relies on. Subscribing the method group remains the registration route and is not reported.
Registered attributes are [CallableByName], [CallableFromNative], [CallableByEngine], [PropertyMigrator] and [ProtoMigrator]. An ordinary C# call of such a method is legal; only its access is checked.
FOENTRY002 applies to both groups. Overrides and interface implementations keep the access of their base and are not judged. Code generated by ManagedScriptBaker in the FOnline namespace keeps its private lookup members deliberately and is not judged; generated code of a project generator is.
// Violation: FOENTRY002 (public entry point) and FOENTRY001 (direct call)
public static class Combat
{
[Event]
public static void OnDamaged(Critter cr) { ApplyDamage(cr); }
public static void Heal(Critter cr) { OnDamaged(cr); }
private static void ApplyDamage(Critter cr) { }
}
// Fix: the entry point is internal, and ordinary code calls the shared helper
public static class Combat
{
[Event]
internal static void OnDamaged(Critter cr) { ApplyDamage(cr); }
public static void Heal(Critter cr) { ApplyDamage(cr); }
private static void ApplyDamage(Critter cr) { }
}
Invariants: FOVERIFY001 to FOVERIFY003
Only calls that bind to FOnline.Invariant are judged. FOVERIFY001 judges literal messages only: a message equal to the condition (whitespace ignored), or a message without spaces that is a fragment of the condition, such as "cr.HasKit". A sentence that quotes a bound, such as "Group size must be >= 1", is accepted. FOVERIFY003 reports await, assignments, increments and decrements, and out or ref arguments inside the condition; context arguments are not judged.
// Violations: FOVERIFY001, FOVERIFY002 and FOVERIFY003, in that order
public static class Building
{
public static void Check(Critter cr, string text)
{
Invariant.Verify(cr.HasKit, "cr.HasKit");
if (!cr.HasKit) {
Invariant.Verify(false, "Builder must carry a construction kit");
}
Invariant.Verify(int.TryParse(text, out int count), "Count must be an integer");
}
}
// Fixes: a sentence plus context, Failed for a proved branch, the work before the check
public static class Building
{
public static void Check(Critter cr, string text)
{
Invariant.Verify(cr.HasKit, "Builder must carry a construction kit", cr.Id);
if (!cr.HasKit) {
Invariant.Failed("Builder must carry a construction kit");
}
bool parsed = int.TryParse(text, out int count);
Invariant.Verify(parsed, "Count must be an integer", text);
}
}
Script statics: FOSTATIC001
The script load context is not collectible, so a script static roots its object graph for the life of the process. At shutdown ScriptStaticCleanup clears every static reference field of the script and dynamic assemblies outside the FOnline namespace. It cannot reach three shapes, and the rule reports them: a static of a generic type (including types nested in one), a [ThreadStatic] field or field-like event, and a static value type that can hold a reference. Constants, unmanaged value types and computed properties have no reachable storage and are not reported. Types in FOnline and its child namespaces are outside both the sweep and the rule.
// Violation: FOSTATIC001
public static class Cache<T>
{
public static T? Last { get; set; }
}
// Fix: the state lives behind an ordinary static reference field the sweep clears
public static class Cache
{
private static readonly System.Collections.Generic.Dictionary<System.Type, object> Last =
new System.Collections.Generic.Dictionary<System.Type, object>();
}
Enable the analyzers
List the analyzer project in the main configuration. Paths are relative to the configuration directory and the list is space-separated:
ManagedScript.Analyzers = Engine/Source/Scripting/Managed/Analyzers/FOnline.Analyzers.csproj
ManagedScriptBaker adds each entry to the generated project as an analyzer reference. Editing an analyzer project, an additional file or an .editorconfig recompiles the scripts, so a changed rule cannot stay silent behind an up-to-date result. Run CompileManagedScripts for every role after enabling the analyzers; each role is a separate compilation and may report different results under #if SERVER, #if CLIENT or #if MAPPER.
Configure severities and options
Roslyn reads severities from the .editorconfig files above each script source. A key applies to the files its section matches:
[*.cs]
dotnet_diagnostic.FOENTRY001.severity = error
dotnet_diagnostic.FOENTRY002.severity = error
dotnet_analyzer_diagnostic.category-Verification.severity = error
dotnet_diagnostic.FOSTATIC001.severity = error
# Tests call entry points directly to exercise the dispatch path itself
[Scripts/Tests/**.cs]
dotnet_diagnostic.FOENTRY001.severity = none
Accepted severities are error, warning, suggestion, silent and none. Prefer explicit error for every enforced rule so the gate does not depend on TreatWarningsAsErrors. Lower a rule only for a path that has a written reason, as above; the analyzers have no caller-name exemption.
Two options extend the entry-point vocabulary with project attributes. Values are comma-separated metadata names (Namespace.TypeName, Outer+Nested for a nested type). An option applies to methods declared in the files its section covers, so set it in a section that covers every script source:
| Option | Effect |
|---|---|
fonline_entry.dispatched_attributes |
Methods with the attribute are entry points: FOENTRY001 and FOENTRY002 |
fonline_entry.registered_attributes |
Methods with the attribute are looked up by name: FOENTRY002 only |
[*.cs]
fonline_entry.dispatched_attributes = MyGame.QuestHookAttribute
fonline_entry.registered_attributes = MyGame.DialogScriptAttribute, MyGame.ConsoleCommandAttribute
A project dispatch marker whose dispatcher synchronizes the subject should instead carry [EntryPointMarker] on its attribute class. That one declaration makes it an entry point for FOENTRY001, FOENTRY002 and FOSYNC003 without any option. A name that does not resolve is reported as FOENTRY003 without a source location, so a misspelt option cannot silently remove an attribute from the rules.
Keep project rules in a project analyzer
Style, naming, accessibility and other game policies belong to the project, not to FOnline.Analyzers. Keep them in a project analyzer and load it next to the Engine one:
ManagedScript.Analyzers = Engine/Source/Scripting/Managed/Analyzers/FOnline.Analyzers.csproj Tools/Analyzers/MyGame.Analyzers.csproj
ManagedScript.AnalyzerPackages = Microsoft.CodeAnalysis.BannedApiAnalyzers,4.14.0
ManagedScript.AdditionalFiles = Scripts/BannedSymbols.txt
ManagedScript.AnalyzerPackages takes NuGet packages as exact name,version pairs; a floating version is rejected. ManagedScript.AdditionalFiles passes configuration files such as a banned-symbols list.
A project analyzer project follows the shape of FOnline.Analyzers.csproj:
- target
netstandard2.0, the framework the compiler loads analyzers in; - reference
Microsoft.CodeAnalysis.CSharpat a version not newer than the Roslyn of the SDK that builds the scripts, withPrivateAssets="all"; - set
EnableDefaultItemsandEnableDefaultCompileItemstofalseand list sources explicitly, because the script build invokes the project with its ownConfiguration(Server,Client,Mapper) and a glob would compile the secondobj/<Config>tree; - enable
EnforceExtendedAnalyzerRulesand track every ID inAnalyzerReleases.Shipped.mdandAnalyzerReleases.Unshipped.md(ruleRS2008); - use a project prefix for its IDs and category; never reuse an
FOprefix.
A project rule that needs to know engine entry points should read the same [EntryPointMarker] declaration or fonline_entry.* options rather than keep its own list of Engine attribute names.
Prove that rules fire
A rule that is enabled but never reaches the compilation reads exactly like a rule that found nothing. The Engine keeps one deliberate defect per rule in Analyzers/Acceptance/EngineContractProbe.cs. Each // ACCEPT: <ID> marker expects that ID inside the declaration that follows it; // ACCEPT-NA: <ID> - <reason> records a rule that cannot fire on source. The self-tests compile the probe with the real CoreScripts/Attributes.cs and CoreScripts/Invariant.cs, require every marker to fire, reject unexpected diagnostics, and require a marker or a reason for every rule of these analyzers. A second pass compiles all CoreScripts for the SERVER, CLIENT and MAPPER symbols and requires them to be free of these diagnostics, because every project compiles CoreScripts with the analyzers enabled.
A project applies the same pattern to the severities it configured: keep a probe file outside ManagedScript.Dirs, compile it in a dedicated acceptance run with the project’s real generated project and .editorconfig, and fail when a marked ID is missing. Add a probe case whenever a rule is raised to error.
Run the self-tests
Run from the Engine root on Windows or Linux with a .NET 10 SDK on PATH:
dotnet run --project Source/Scripting/Managed/Analyzers/Tests/FOnline.Analyzers.Tests.csproj --configuration Release
dotnet run --project Source/Scripting/Managed/Analyzers/Tests/FOnline.Analyzers.Tests.csproj --configuration Release
From an embedding project, prefix the path with Engine/. The first run restores Microsoft.CodeAnalysis.CSharp from NuGet. A pass prints:
OK: analyzer self-tests passed
| Exit code | Meaning |
|---|---|
0 |
Every case passed |
1 |
One or more cases failed; each is printed as FAIL: <case>: <expected and actual> |
| other non-zero | The harness stopped: a snippet does not compile or Source/Scripting/Managed cannot be located |
The command is verified on Windows in PowerShell and Git Bash; the Linux form is identical and has not been observed on a Linux host. In CI, run it in a job that installs a .NET 10 SDK, for example with actions/setup-dotnet, and treat a non-zero exit as a failure.
Migrate from project-prefixed copies
A project that kept its own copies of these rules under project-prefixed IDs removes those copies and switches its configuration to the Engine IDs:
| Earlier project rule | Engine rule | Behavior change |
|---|---|---|
| Direct call of a dispatcher-bound entry point | FOENTRY001 |
No caller-name exemption; lower the rule per path for tests. Project markers join through [EntryPointMarker] or fonline_entry.dispatched_attributes |
Engine-called method not internal |
FOENTRY002 |
Judges project-generated code; skips only baker-generated code in FOnline. Name-registered project attributes join through fonline_entry.registered_attributes |
Invariant.Verify message restates its condition |
FOVERIFY001 |
None |
Invariant.Verify(false, ...) |
FOVERIFY002 |
None |
Acting code in a Verify condition |
FOVERIFY003 |
None |
| Static out of reach of the shutdown sweep | FOSTATIC001 |
Scope is the FOnline namespace, not a source path |
- Delete the project analyzer sources, test cases and release-tracking rows of the replaced rules. Keep project rules that encode game policy.
- In every
.editorconfig, replace eachdotnet_diagnostic.<old-id>.severitykey with the Engine ID from the table, keeping its severity. - Replace a caller-name test exemption with a per-path section that sets
dotnet_diagnostic.FOENTRY001.severity = none. - Mark project dispatch attributes with
[EntryPointMarker]or list them infonline_entry.dispatched_attributes; list name-registered ones infonline_entry.registered_attributes. - Replace old IDs in acceptance probes, suppressions (
#pragma warning disable,SuppressMessage) and gate scripts. Search for them withgit grep -n "<old-id>". - Run
CompileManagedScriptsfor every role and the acceptance run. While both copies are loaded, each defect is reported under both IDs; after step 1 only the Engine ID remains.
The Engine rules are active as soon as the Engine update reaches the project, so land these steps in the same change as the update.
Validation checklist
ManagedScript.AnalyzerslistsFOnline.Analyzers.csproj, and every role compiles warning-free.- Every enforced Engine rule has an explicit
.editorconfigseverity, and every lowered rule has a path section with a reason. - Project dispatch attributes carry
[EntryPointMarker]or appear in anfonline_entry.*option, and noFOENTRY003is reported. - Project style and naming rules live in a project analyzer with project-prefixed IDs.
- A probe proves every rule the project raised to
errorstill fires. - The Engine self-tests pass with exit code
0after any change toSource/Scripting/Managed/Analyzersor CoreScripts.