Skip to content

Customizing generated code with annotations

c80k edited this page Apr 25, 2020 · 3 revisions

Annotations are the Cap'n Proto way of controlling generator behavior if one has particular requirements. The reference implementation defines some C++-related attributes in c++.capnp. capnproto-dotnetcore understands the namespace attribute and generates C#-style namespaces if this attribute is given. Starting from version 1.3, capnproto-dotnetcore brings its own set of annotations, which are defined in csharp.capnp. The following sections assume that you included this file into your schema like this:

using CSharp = import "/csharp.capnp";

Namespace

namespace is a file-level attribute for specifying the desired output namespace. Usage:

$CSharp.namespace("My.CSharp.Namespace");

Changing member names

The name attribute is applicable to any type and member. It lets you override the generated C# identifier. Example:

struct SomeStruct $CSharp.name("CsStruct") {
  someField @0 : Int32 $CSharp.name("CsField");

  someUnion : union $CSharp.name("CsUnion") {
    u0 @1 : Int32;
	u1 @2 : Int32;
  }

  someGroup : group $CSharp.name("CsGroup") {
    g0 @3 : Int32;
	g1 @4 : Int32;
  }
}

enum SomeEnum $CSharp.name("CsEnum") {
  someEnumerant @0 $CSharp.name("CsEnumerant");
}

interface SomeInterface $CSharp.name("CsInterface") {
  someMethod @0 () -> (someResult :Bool $CSharp.name("CsResult") ) $CSharp.name("CsMethod");
}

Nullable reference types

The generation of nullable reference types can be controlled by two switches:

  • nullableEnable specifies whether the generator should emit nullable reference types. Default is false.
  • emitNullableDirective specifies whether to wrap the generated code in a #nullable directive. If nullableEnable is true, this will be a #nullable enable directive. If false, it will be a #nullable disable directive. Default is false.

Example:

$CSharp.nullableEnable(true);
$CSharp.emitNullableDirective(false);

Domain class and interface generation

The generation of domain classes and interfaces can be suppressed:

$CSharp.emitDomainClassesAndInterfaces(false);

Type visibility

The visibility of all generated types can be controlled like this:

$CSharp.typeVisibility(internal);

You may choose between public and internal. Default is public.

Embedding preambles

This feature allows you to prepend custom text before the actual generated output. It is particularly useful for embedding file documentation or disabling warnings. It works by inserting the "magic token" $$embed into the comment block which relates to the file ID.

Example:

@0xb312981b2552a250;
# This does not yet appear in generated code.
# $$embed
# // But this will appear in generated code.
# #pragma warning disable CS1591

Clone this wiki locally