Skip to content

Compiler

James Courtney edited this page Sep 15, 2021 · 13 revisions

FlatSharp can be run at build-time with the FlatSharp.Compiler NuGet package. The compiler accepts fbs files and produces C# at build time. The FlatSharp compiler targets netcoreapp3.1 and net5.0, which are just the runtimes necessary to execute the compiler, and has no bearing on the code the compiler generates. The FlatSharp compiler generates code that can run inside .NET Framework, .NET Standard 2.0+, or .NET Core 2.1+.

Adding FBS files

FBS files must be opted into the compiler:

<Project Sdk="Microsoft.NET.Sdk">
  <ItemGroup>
    <FlatSharpSchema Include="YourSchema.fbs" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="FlatSharp.Compiler" Version="5.0.0">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="FlatSharp.Runtime" Version="5.0.0" />
  </ItemGroup>
</Project>

Unity

Unity does not allow modification of the .csproj file, which makes the above difficult. For Unity users, the best current option is to invoke the compiler manually in a prebuild step. The syntax is:

net5.0/netcoreapp3.1: dotnet FlatSharp.Compiler.dll -i <input_file> -o <output directory>

Nullable Annotations

By default, the FlatSharp compiler inherits the project setting for nullable annotations. If <Nullable> is set to enabled in the project, then FlatSharp will generate code with full nullable attributes and annotations. If <Nullable> is set to anything besides enabled in the project, FlatSharp will generate code with nullable annotations only.

Full nullable annotations may only work correctly with C# 9 and above.

This behavior can be overridden with the <FlatSharpNullable> property.

  <!-- Flatsharp inherits the project setting and generates full nullable code -->
  <PropertyGroup>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <!-- FlatSharp only generates nullable annotations (no attributes/warnings) -->
  <PropertyGroup>
    <Nullable>enable</Nullable>
    <FlatSharpNullable>false</FlatSharpNullable>
  </PropertyGroup>

  <!-- FlatSharp only generates nullable annotations (no attributes/warnings) -->
  <PropertyGroup>
    <Nullable>disable</Nullable>
  </PropertyGroup>

  <!-- Flatsharp overrides the project setting and generates full nullable code -->
  <PropertyGroup>
    <Nullable>disable</Nullable>
    <FlatSharpNullable>true</FlatSharpNullable>
  </PropertyGroup>
Clone this wiki locally