FIDL 编译器错误目录

本文档列出了 FIDL 编译器 fidlc 发出的所有错误。此网域中的错误标识符始终以前缀 fi- 后跟一个四位数代码(如 fi-0123)呈现。

fi-0001:字符无效

词法分析器未能将字符转换为指定位置的词元。

library test.bad.fi0001;

type ßar = struct {
    value uint64;
};

无效字符应通过替换或删除来修复。

library test.good.fi0001;

type Foo = struct {
    value uint64;
};

无效字符视位置而定。请参阅 FIDL 语言规范,以确定 FIDL 语法的各个部分允许使用哪些字符。

fi-0002:意外的换行符

字符串字面量不能拆分为多行:

library test.bad.fi0002;

const BAD_STRING string:1 = "Hello
World";

请改用转义序列 \n 来表示换行符:

library test.good.fi0002;

const GOOD_STRING string:11 = "Hello\nWorld";

fi-0003:转义序列无效

词法分析器在转义序列的开头遇到了无效字符。

library test.bad.fi0003;

const UNESCAPED_BACKSLASH string:2 = "\ ";
const BACKSLASH_TYPO string:1 = "\i";
const CODE_POINT_TYPO string:1 = "\Y1F604";

您可以替换成有效字符以开始转义序列,或者移除意外的反斜杠字符。

library test.good.fi0003;

const ESCAPED_BACKSLASH string:2 = "\\ ";
const REMOVED_BACKSLASH string:1 = "i";
const SMALL_CODE_POINT string:3 = "\u{2604}";
const BIG_CODE_POINT string:4 = "\u{01F604}";

如需了解有效的转义序列,请参阅 FIDL 语法规范

fi-0004:十六进制数字无效

字符串字面量中的 Unicode 转义字符不得包含无效的十六进制数字:

library test.bad.fi0004;

const SMILE string = "\u{1G600}";

您必须以十六进制形式指定有效的 Unicode 代码点,范围为 0 到 10FFFF。 每个十六进制数字都必须是 0 到 9 之间的数字、从 af 的小写字母或 AF 的大写字母。在本例中,GF 的拼写错误:

library test.good.fi0004;

const SMILE string = "\u{1F600}";

fi-0005

fi-0006:预期声明

当 FIDL 需要声明时,如果发现了其他内容,就会出现此错误。 这通常是由拼写错误导致的。有效的声明为:typealiasconstusingprotocolservice

library test.bad.fi0006;

cosnt SPELLED_CONST_WRONG string:2 = ":("; // Expected a declaraction (such as const).

如需修正此错误,请检查顶级声明中是否存在拼写错误,并确保您使用的是 FIDL 支持的功能。

library test.good.fi0006;

const SPELLED_CONST_RIGHT string:2 = ":)";

fi-0007:意外令牌

解析期间遇到意外令牌时,会发生此错误。一般来说,这是由拼写错误导致的:

library test.bad.fi0007;

alias MyType = vector<uint8>:<,256,optional>; // Extra leading comma

此问题的解决方法通常是移除意外的令牌,或者在某些情况下,提供缺少的其余语法:

library test.good.fi0007;

alias MyType = vector<uint8>:<256, optional>;

fi-0008:意外令牌

每当 FIDL 解析器遇到语法无效的令牌时,就会发生此错误。发生这种情况的方式有很多,例如枚举成员缺少 =library = what.is.that.equals.doing.there 等额外令牌等。

library test.bad.unexpectedtokenofkind;

type Numbers = flexible enum {
    ONE; // FIDL enums don't have a default value.
};

通常,此问题的解决方法是添加缺失的令牌或移除额外的令牌。

library test.good.fi0008;

type Numbers = flexible enum {
    ONE = 1;
};

为避免此错误,请对 *.fidl 文件执行一次操作,确保它们的语法正确无误。

fi-0009:意外标识符

如果在错误的位置使用标识符,通常会出现此错误:

using test.bad.fi0009;

改用正确的标识符:

library test.good.fi0009;

fi-0010:标识符无效

找到了不符合有效标识符要求的标识符。FIDL 标识符可以包含字母数字和下划线(具体来说是 A-Za-z0-9_),此外,每个标识符必须以字母开头,以字母或数字结尾。

library test.bad.fi0010a;

// Foo_ is not a valid identifier because it ends with '_'.
type Foo_ = struct {
    value uint64;
};

如需解决此问题,请更改标识符,以确保它仅包含有效字符,以字母开头,以字母或数字结尾。

library test.good.fi0010a;

type Foo = struct {
    value uint64;
};

如果将多部分(虚线)标识符传递给属性,也可能会发生此错误。

library test.bad.fi0010b;

@foo(bar.baz="Bar", zork="Zoom")
type Empty = struct{};

若要解决此问题,请更改为在属性中仅使用单部分标识符。

library test.good.fi0010b;

@foo(bar="Bar", zork="Zoom")
type Empty = struct {};

fi-0011:库名称组件无效

库名称只能包含字母和数字(A-Za-z0-9),并且必须以字母开头。

library test.bad.fi0011.name_with_underscores;

如需解决此问题,请确保所有库名称组件都符合要求。

library test.good.fi0011.namewithoutunderscores;

fi-0012:类型布局类无效

类型声明必须指定 FIDL 已知的布局:

library test.bad.fi00012;

type Foo = invalid {};

有效的布局为 bitsenumstructtableunion

library test.good.fi0012;

type Empty = struct {};

布局是 FIDL 类型的可参数化描述。它指的是一系列可能的类型,这些类型可以接收更多参数来指定其形状。例如,struct 是一种布局,在定义了特定成员后会变为具体类型;而 array 则是一种在给定类型(要按顺序重复指定的次数)时变为具体的布局。

所有布局都内置于 FIDL 语言中,用户无法通过任何方式指定自己的布局或创建自己的通用类型模板。

fi-0013:封装类型无效

当传递给枚举或位声明的值不是某个类型的标识符(例如,您提供的字符串值作为“后备类型”)时,就会出现此错误:

library test.bad.fi0013;

type TypeDecl = enum : "int32" {
    FOO = 1;
    BAR = 2;
};

如需修正此错误,请确保枚举或位的后备类型是类型标识符。

library test.good.fi0013;

type TypeDecl = enum : int32 {
    FOO = 1;
    BAR = 2;
};

fi-0014:带有空括号的属性

如果某个属性有圆括号,但没有实参,就会出现此错误。

library test.bad.fi0014;

@discoverable()
protocol MyProtocol {};

如需解决此问题,请从不含实参的属性中移除括号,或者原本应该提供实参。

library test.good.fi0014;

@discoverable
protocol MyProtocol {};

FIDL 不允许将属性中的空参数列表作为一种样式选择。

fi-0015:必须全部为属性参数命名

为清楚起见,特此说明:如果某个属性包含多个参数,则该属性的所有参数都必须明确指定。

当属性具有多个参数但未明确提供参数名称时,就会出现此错误。

library test.bad.fi0015;

@foo("abc", "def")
type MyStruct = struct {};

如需解决此问题,请使用 name=value 语法提供所有参数的名称。

library test.good.fi0015;

@foo(bar="abc", baz="def")
type MyStruct = struct {};

fi-0016:成员前缺少序数

当联合或表中的字段缺少序数时,就会出现此错误。

library test.bad.fi0016a;

type Foo = table {
    x int64;
};
library test.bad.fi0016b;

type Bar = union {
    foo int64;
    bar vector<uint32>:10;
};

要修复此错误,请明确指定表或联合的序数:

library test.good.fi0016;

type Foo = table {
    1: x int64;
};

type Bar = union {
    1: foo int64;
    2: bar vector<uint32>:10;
};

与结构体不同,表和联合旨在允许对其内容进行向后兼容的更改。为了实现这一点,需要使用一致的值(序数)来标识表字段或并集变体。为避免混淆并在更改表或联合时更难以意外更改序数,必须始终明确指定序数。

fi-0017:序数超出范围

表和联合的序数必须是有效的无符号 32 位整数。如果负序数或序数大于 4,294,967,295,将会导致此错误。

library test.bad.fi0017a;

type Foo = table {
  -1: foo string;
};
library test.bad.fi0017b;

type Bar = union {
  -1: foo string;
};

要修正此错误,请确保所有序数都在允许的范围内。

library test.good.fi0017;

type Foo = table {
    1: foo string;
};

type Bar = union {
    1: foo string;
};

fi-0018:序数必须从 1 开始

tableunion 成员序数值都不能为 0:

library test.bad.fi0018;

type Foo = strict union {
    0: foo uint32;
    1: bar uint64;
};

相反,编号应从 1 开始:

library test.good.fi0018;

type Foo = strict union {
    1: foo uint32;
    2: bar uint64;
};

fi-0019:严格位、枚举或联合不得为空

严格位、枚举或联合不得有零个成员:

library test.bad.fi0019;

type Numbers = strict enum {};

而必须至少包含一个成员:

library test.good.fi0019a;

type Numbers = flexible enum {};

或者,您也可以将声明 flexible 而不是 strict 标记为:

library test.good.fi0019b;

type Numbers = strict enum {
    ONE = 1;
};

空位、枚举或联合没有任何信息,因此通常不应在 API 中使用。不过,灵活的数据类型是专为进化而设计的,因此可以定义一开始为空的灵活位或枚举,以便稍后添加成员。定义新的数据类型时,您应该始终仔细考虑是使用 strict 还是 flexible

fi-0020:协议成员无效

如果协议中的某个项未被识别为有效的协议成员(例如协议中的某些项不是协议构成、单向方法、双向方法或事件),就会出现此错误。

library test.bad.fi0020;

protocol Example {
    NotAMethodOrCompose;
};

如需修正此错误,请移除无效项,或将其转换为与原本的协议项类型对应的正确语法。

library test.good.fi0020;

protocol Example {
    AMethod();
};

fi-0021

fi-0022:无法将属性附加到标识符

如果某个声明的类型是标识符类型,而将某个属性放在声明的类型上,就会出现此错误。例如,在结构体声明中将某个属性放置在字段名称之后、字段类型之前,会将该属性与字段类型而非字段本身相关联。如果字段的类型是名称引用的现有类型,则无法将其他属性应用于该字段。

library test.bad.fi0022;

type Foo = struct {
    // uint32 is an existing type, extra attributes cannot be added to it just
    // for this field.
    data @foo uint32;
};

如果意图是将某个属性应用于该字段,则该属性应移到字段名称之前。

属性可以应用于声明它们的类型。这意味着,如果结构体字段或其他类似声明的类型是匿名类型而不是标识符类型,则可以将属性应用于该类型。

library test.good.fi0022;

type Foo = struct {
    // The foo attribute is associated with the data1 field, not the uint32
    // type.
    @foo
    data1 uint32;
    // The type of data2 is a newly declared anonymous structure, so that new
    // type can have an attribute applied to it.
    data2 @foo struct {};
};

fi-0023:冗余属性放置

应用于命名类型的声明的属性也应用于生成的类型,与直接应用于类型布局的属性相同。

发生此错误的属性同时位于类型声明和该声明的布局中。

library test.bad.fi0023;

@foo
type Foo = @bar struct {};

如需修正此错误,请将所有属性移至类型声明,或将所有属性移至布局中。

library test.good.fi0023;

@foo
@bar
type Foo = struct {};
type Bar = @foo @bar struct {};

FIDL 包含此错误是为了避免混淆,这可能是由于在单一类型的声明和布局中都设置了属性所致。

fi-0024:方法参数列表的文档注释

方法参数列表不能包含文档注释:

library test.bad.fi0024;

protocol Example {
    Method(/// This is a one-way method.
            struct {
        b bool;
    });
};

对于目前,请为方法本身添加文档注释:

library test.good.fi0024;

protocol Example {
    /// This is a one-way method.
    Method(struct {
        b bool;
    });
};

解决此错误后,此错误将不再存在。从迁移保留的错误,使用 FIDL 类型(而不是参数列表)来描述方法载荷。

fi-0025:导入组必须位于文件顶部

除了文件顶部的 library 声明之外,在文件导入 using 之前不得有任何其他声明(如果存在):

library test.bad.fi0025;

alias i16 = int16;
using dependent;

type UsesDependent = struct {
    field dependent.Something;
};

如需解决此错误,请将所有 using 导入项放在 library 声明之后的块中:

library test.good.fi0025;

using dependent;

alias i16 = int16;
type UsesDependent = struct {
    field dependent.Something;
};

这条规则主要反映了 FIDL 团队做出的一个审美决定,即依赖项分类得当且易于定位时更易于阅读。

fi-0026:在文档注释块内添加注释

评论不应放置在文档评论区块内:

library test.bad.fi0026;

/// start
// middle
/// end
type Empty = struct {};

而应放置在文档注释块的前面或后面:

library test.good.fi0026;

// some comments above,
// maybe about the doc comment
/// A
/// multiline
/// comment!
// another comment, maybe about the struct
type Empty = struct {};

通常,紧接在文档注释块前面的注释是提供有关文档注释本身的注释的最佳位置。

fi-0027:文档注释块中出现空白行

文档注释区块中不应有空白行:

library test.bad.fi0027;

/// start

/// end
type Empty = struct {};

只能在文档注释块之前或之后放置空白行:

library test.good.fi0027a;

/// A doc comment
type Empty = struct {};

或者,您也可以考虑完全省略空白行:

library test.good.fi0027b;

/// A doc comment
type Empty = struct {};

fi-0028:文档注释后面必须跟声明

文档评论不得像常规评论一样自由浮动:

library test.bad.fi0028;

type Empty = struct {};
/// bad

在任何情况下,文档注释都必须直接在 FIDL 声明之前添加:

library test.good.fi0028a;

/// A doc comment
type Empty = struct {};

在编译期间,FIDL 会将文档注释“降低”为 @doc 属性。事实上,如果需要,可以直接这样写出任何注释:

library test.good.fi0028b;

@doc("An attribute doc comment")
type Empty = struct {};

从技术角度来看,独立文档注释不可编译,但在语义上也会造成混淆:什么也不“记录”任何内容?与常规注释不同,文档注释会处理为结构化文档,因此必须明确说明它们附加到哪个 FIDL 结构。

fi-0029:资源定义必须至少包含一个属性

禁止指定未指定属性的资源定义:

library test.bad.resourcedefinitionnoproperties;

resource_definition SomeResource : uint32 {
  properties {};
};

请至少指定一个属性:

library test.good.fi0029;

resource_definition SomeResource : uint32 {
    properties {
        subtype strict enum : uint32 {
            NONE = 0;
        };
    };
};

这是一个与 FIDL 的内部实现相关的错误,因此只应向处理 FIDL 核心库的开发者公开。最终用户绝不会看到此错误。

它所引用的 resource_definition 声明是 FIDL 用于定义句柄等资源的内部方法,将来可能会作为处理程序泛化工作的一部分而发生变化。

fi-0030:修饰符无效

每个 FIDL 修饰符都有一组特定的声明可用于该修饰符。不允许在禁止的声明中使用该修饰符:

library test.bad.fi0030;

type MyStruct = strict struct {
    i int32;
};

最佳做法是移除违规修饰符:

library test.good.fi0030;

type MyStruct = struct {
    i int32;
};

fi-0031:只有位和枚举可以有子类型

并非所有 FIDL 布局都可以带有子类型:

library test.bad.fi0031;

type Foo = flexible union : uint32 {};

只有 bitsenum 布局是基于底层类型定义的。

library test.good.fi0031;

type Foo = flexible enum : uint32 {};

bitsenum 布局有些独特,因为它们只是受限于完整的 FIDL 基元的子类型。因此,他们最好指定充当此子类型的基础类型。相反,structtableunion 布局可以任意大,并且可以包含许多成员,因此全局布局范围的子类型没有意义。

fi-0032:不允许出现重复的修饰符

禁止在单个声明中指定相同的修饰符:

library test.bad.fi0032;

type MyUnion = strict resource strict union {
    1: foo bool;
};

移除重复的修饰符:

library test.good.fi0032;

type MyUnion = resource strict union {
    1: foo bool;
};

fi-0033:冲突修饰符

某些修饰符是互斥的,不能同时修改同一个声明:

library test.bad.conflictingmodifiers;

type StrictFlexibleFoo = strict flexible union {
    1: b bool;
};

type FlexibleStrictBar = flexible strict union {
    1: b bool;
};

一次只能在一个声明中使用其中一个 strictflexible 修饰符:

library test.good.fi0033;

type FlexibleFoo = flexible union {
    1: i int32;
};

type StrictBar = strict union {
    1: i int32;
};

目前,只有 strictflexible 修饰符以此方式是互斥的。resource 修饰符没有倒数修饰符,因此不对其应用此类限制。

fi-0034:名称冲突

两个声明不得同名:

library test.bad.fi0034;

const COLOR string = "red";
const COLOR string = "blue";

相反,请为每个声明指定一个唯一的名称:

library test.good.fi0034b;

const COLOR string = "red";
const OTHER_COLOR string = "blue";

或者,如果您误添加了以下声明,请将其移除:

library test.good.fi0034a;

const COLOR string = "red";

如需详细了解如何选择名称,请参阅 FIDL 样式指南

fi-0035:规范名称冲突

两项声明不得具有相同的规范名称:

library test.bad.fi0035;

const COLOR string = "red";

protocol Color {};

虽然 COLORColor 看起来不同,但它们都由规范名称 color 表示。通过将原始名称转换为 snake_case,可获得规范名称。

如需修正该错误,请为每个声明指定一个在规范化后唯一的名称:

library test.good.fi0035;

const COLOR string = "red";

protocol ColorMixer {};

遵循 FIDL 样式指南的命名准则可最大限度地降低遇到此错误的几率。采用相同大小写样式的声明之间不会发生规范名称冲突,由于其他要求,使用不同样式的声明之间也很少会发生规范名称冲突(例如,协议名称通常应该是以 -er 结尾的名词短语)。

FIDL 强制执行此规则,因为绑定生成器会将名称转换为目标语言的惯用命名样式。通过确保唯一的规范名称,我们可以保证绑定能够做到这一点,而不会产生名称冲突。如需了解详情,请参阅 RFC-0040:标识符唯一性

fi-0036:名称重叠

同名的声明不得有重叠的可用性:

@available(added=1)
library test.bad.fi0036;

type Color = strict enum {
    RED = 1;
};

@available(added=2)
type Color = flexible enum {
    RED = 1;
};

请改为使用 @available 属性,确保任何给定版本中都只存在其中一个声明:

@available(added=1)
library test.good.fi0036;

@available(replaced=2)
type Color = strict enum {
    RED = 1;
};

@available(added=2)
type Color = flexible enum {
    RED = 1;
};

或者,重命名或移除其中一个声明,如 fi-0034 中所示。

如需详细了解版本控制,请参阅 FIDL 版本控制

fi-0037:规范名称重叠

具有相同规范名称的声明不得有重叠的可用性:

@available(added=1)
library test.bad.fi0037;

const COLOR string = "red";

@available(added=2)
protocol Color {};

虽然 COLORColor 看起来不同,但它们都由规范名称 color 表示。通过将原始名称转换为 snake_case,可获得规范名称。

如需修正该错误,请为每个声明指定一个在规范化后唯一的名称。

@available(added=1)
library test.good.fi0037;

const COLOR string = "red";

@available(added=2)
protocol ColorMixer {};

或者,您也可以更改其中一个声明可用性(如 fi-0036 中所示),或移除该声明。

如需详细了解 FIDL 为何要求声明具有唯一的规范名称,请参阅 fi-0035

fi-0038:名称与导入冲突

声明不能与使用 using 导入的库同名:

library dependency;

const VALUE uint32 = 1;
library test.bad.fi0038b;

using dependency;

type dependency = struct {};

// Without this, we'd get fi-0178 instead.
const USE_VALUE uint32 = dependency.VALUE;

请改为使用 using ... as 语法以其他名称导入库:

library test.good.fi0038b;

using dependency as dep;

type dependency = struct {};

const USE_VALUE uint32 = dep.VALUE;

或者,重命名声明以避免冲突:

library test.good.fi0038c;

using dependency;

type OtherName = struct {};

const USE_VALUE uint32 = dependency.VALUE;

您可以在库名称中使用多个组件来避免此问题。例如,Fuchsia SDK 中的 FIDL 库以 fuchsia. 开头,因此它们至少有两个组件,不能与声明名称冲突。

此错误是为了防止歧义。例如,如果 dependency 是一个具有名为 VALUE 的成员的枚举,那么 dependency.VALUE 是引用该枚举成员还是引用导入库中声明的常量,就会产生歧义。

fi-0039:规范名称与导入冲突

声明不能与使用 using 的库导入具有相同的规范名称:

library dependency;

const VALUE uint32 = 1;
library test.bad.fi0039b;

using dependency;

type Dependency = struct {};

// Without this, we'd get fi-0178 instead.
const USE_VALUE uint32 = dependency.VALUE;

虽然 dependencyDependency 看起来不同,但它们都由规范名称 dependency 表示。通过将原始名称转换为 snake_case,可获得规范名称。

如需修正该错误,请使用 using ... as 语法以其他名称导入库:

library test.good.fi0039b;

using dependency as dep;

type Dependency = struct {};

const USE_VALUE uint32 = dep.VALUE;

或者,重命名声明以避免冲突:

library test.good.fi0039c;

using dependency;

type OtherName = struct {};

const USE_VALUE uint32 = dependency.VALUE;

请参阅 fi-0038,了解出现此错误的原因以及如何避免此错误。

如需详细了解 FIDL 为何要求声明具有唯一的规范名称,请参阅 fi-0035

fi-0040:文件对库名称不认可

库可以由多个文件组成,但每个文件必须具有相同的名称:

library test.bad.fi0040a;
library test.bad.fi0040b;

确保库使用的所有文件均同名:

library test.good.fi0040;
library test.good.fi0040;

对于多文件库,建议创建一个空的 overview.fidl 文件,作为库的主“入口点”。overview.fidl 文件也是放置库级 @available 平台规范的适当位置。

fi-0041:多个同名的库

传递给 fidlc 的每个库都必须具有唯一的名称:

library test.bad.fi0041;
library test.bad.fi0041;

确保所有库的名称都是唯一的:

library test.good.fi0041a;
library test.good.fi0041b;

此错误通常是由于以不正确的方式向 fidlc 提供的参数导致的。构成编译所需的每个库的组成文件(即正在编译的库及其所有传递依赖项)必须以单个以空格分隔的文件列表的形式提供,其中包含通过 --files 参数传递的文件(每个库包含一个此类标志)。一个常见的错误是尝试在单个 --files 列表中传递所有库的文件。

fi-0042:重复库导入

依赖项无法导入多次:

library test.bad.fi0042a;

type Bar = struct {};
library test.bad.fi0042b;

using test.bad.fi0042a;
using test.bad.fi0042a; // duplicated
type Foo = struct {
    bar test.bad.fi0042a.Bar;
};

确保每个依赖项仅导入一次:

library test.good.fi0042a;

type Bar = struct {};
library test.good.fi0042b;

using test.good.fi0042a;
type Foo = struct {
    bar test.good.fi0042a.Bar;
};

值得注意的是,FIDL 不支持导入同一库的不同版本。@available 版本通过 --available 标志针对整个 fidlc 编译进行解析,这意味着对于任何给定的编译运行,正在编译的库及其所有依赖项都必须共用同一版本。

fi-0043:冲突的库导入

禁止为导入的库指定别名,以免与其他导入库的非别名名称相冲突:

library test.bad.fi0043a;

type Bar = struct {};

// This library has a one component name to demonstrate the error.
library fi0043b;

type Baz = struct {};
library test.bad.fi0043c;

using test.bad.fi0043a as fi0043b; // conflict
using fi0043b;

type Foo = struct {
    a fi0043b.Bar;
    b fi0043b.Baz;
};

请选择其他别名以解决名称冲突:

library test.good.fi0043a;

type Bar = struct {};
library fi0043b;

type Baz = struct {};
library test.good.fi0043c;

using test.good.fi0043a as dep;
using fi0043b;

type Foo = struct {
    a dep.Bar;
    b fi0043b.Baz;
};

fi-0044:有冲突的库导入别名

禁止为导入的库指定别名,以免与分配给其他导入库的别名冲突:

library test.bad.fi0044a;

type Bar = struct {};
library test.bad.fi0044b;

type Baz = struct {};
library test.bad.fi0044c;

using test.bad.fi0044a as dep;
using test.bad.fi0044b as dep; // conflict
type Foo = struct {
    a dep.Bar;
    b dep.Baz;
};

选择无冲突的别名可解决名称冲突:

library test.good.fi0044a;

type Bar = struct {};
library test.good.fi0044b;

type Baz = struct {};
library test.good.fi0044c;

using test.good.fi0044a as dep1;
using test.good.fi0044b as dep2;
type Foo = struct {
    a dep1.Bar;
    b dep2.Baz;
};

fi-0045:使用声明时不允许使用的属性

属性无法附加到 using 声明:

library test.bad.fi0045a;

type Bar = struct {};
library test.bad.fi0045b;

/// not allowed
@also_not_allowed
using test.bad.fi0045a;

type Foo = struct {
    bar test.bad.fi0045a.Bar;
};

请移除此属性以解决错误:

library test.good.fi0045a;

type Bar = struct {};
library test.good.fi0045b;

using test.good.fi0045a;

type Foo = struct {
    bar test.good.fi0045a.Bar;
};

此限制也适用于 /// ... 文档注释,因为这些注释只是 @doc("...") 属性的语法糖。

fi-0046:未知库

在大多数情况下,此问题是因为依赖项拼写有误或构建系统未提供。如果相关依赖项是有意不使用的,则必须移除相关的 using 行:

library test.bad.fi0046;

using dependent; // unknown using.

type Foo = struct {
    dep dependent.Bar;
};

确保使用构建系统将所有导入项作为依赖项添加到库。

library test.good.fi0046;

type Foo = struct {
    dep int64;
};

fi-0047:协议由多次组成

一个协议最多只能构成另一个协议:

library test.bad.fi0047;

protocol Parent {
    Method();
};

protocol Child {
    compose Parent;
    compose Parent;
};

移除多余的 compose 子句:

library test.good.fi0047;

protocol Parent {
    Method();
};

protocol Child {
    compose Parent;
};

fi-0048:可选的表成员

表成员类型不能为 optional

library test.bad.fi0048;

type Foo = table {
    // Strings can be optional in general, but not in table member position.
    1: t string:optional;
};

从所有成员中移除 optional 限制条件:

library test.good.fi0048;

type Foo = table {
    1: t string;
};

表成员始终是可选的,因此在成员的基础类型上指定这一事实是多余的。

表成员始终是可选的,因为在线上,每个表成员都表示为矢量中的条目。该向量始终表示表上的所有已知字段,因此每个省略的表成员都表示为一个空信封 - 与省略的可选类型的表示形式完全相同。

fi-0049:可选联盟成员

联合成员不得为可选:

library test.bad.fi0049;

type Foo = strict union {
    // Strings can be optional in general, but not in unions.
    1: bar string:optional;
};

移除 optional 约束条件:

library test.good.fi0049;

type Foo = strict union {
    1: bar string;
};

FIDL 不允许联合成员是可选的,因为这可能会导致以多种方式表示同一值。例如,如果有三个可选成员的工会有 6 个州(每个成员 2 个),相反,应使用类型为 struct {} 的第四个成员进行建模,或者使用 Foo:optional 将整个联合设为可选。

fi-0050:禁止使用已废弃的结构体默认语法

以前,FIDL 允许在 struct 成员上设置默认值:

library test.bad.fi0050;

type MyStruct = struct {
    field int64 = 20;
};

RFC-0160:移除对 FIDL 结构默认值的支持起,不允许此行为:

library test.good.fi0050;

type MyStruct = struct {
    field int64;
};

系统不再允许 struct 成员使用默认值。用户应改为在应用逻辑中设置此类默认值。

少数使用此语法的旧版用户可以在编译器内置的许可名单内继续使用该语法,但目前没有新的例外情况添加到该名单。一旦这些用户迁离,此功能就会从 FIDL 中永久移除。

fi-0051:未知的依赖库

如果您使用来自未知库的符号,就会出现此错误。

library test.bad.fi0051;

type Company = table {
    1: employees vector<unknown.dependent.library.Person>;
    2: name string;
};

要解决此问题,请使用 using 声明导入缺少的依赖库。

library known.dependent.library;

type Person = table {
    1: age uint8;
    2: name string;
};
library test.good.fi0051;
using known.dependent.library;

type Company = table {
    1: employees vector<known.dependent.library.Person>;
    2: name string;
};

如果 fidlc 命令行调用的格式不正确,通常会发生此错误。如果您确信未知库存在且应该可解析,请务必通过传递给 --files 标志的空格分隔列表正确传递依赖库的文件。

fi-0052:未找到名称

如果您使用 FIDL 编译器无法找到的名称,就会出现此错误。

library test.bad.fi0052;

protocol Parser {
    Tokenize() -> (struct {
        tokens vector<string>;
    }) error ParsingError; // ParsingError doesn't exist.
};

如需解决此问题,请移除未找到的名称:

library test.good.fi0052a;

protocol Parser {
    Tokenize() -> (struct {
        tokens vector<string>;
    });
};

或定义找不到的名称:

library test.good.fi0052b;

type ParsingError = flexible enum {
    UNEXPECTED_EOF = 0;
};

protocol Parser {
    Tokenize() -> (struct {
        tokens vector<string>;
    }) error ParsingError;
};

fi-0053:无法指代成员

如果您引用的成员不是 bitsenum 条目,则会出现此错误。

library test.bad.fi0053a;

type Person = struct {
    name string;
    birthday struct {
        year uint16;
        month uint8;
        day uint8;
    };
};

const JOHNS_NAME Person.name = "John Johnson"; // Cannot refer to member of struct 'Person'.
library test.bad.fi0053b;

type Person = struct {
    name string;
    birthday struct {
        year uint16;
        month uint8;
        day uint8;
    };
};

type Cat = struct {
    name string;
    age Person.birthday; // Cannot refer to member of struct 'Person'.
};

如需修复此错误,您可以将其更改为已命名的类型:

library test.good.fi0053a;

type Person = struct {
    name string;
    birthday struct {
        year uint16;
        month uint8;
        day uint8;
    };
};

const JOHNS_NAME string = "John Johnson";

或提取成员的类型:

library test.good.fi0053b;

type Date = struct {
    year uint16;
    month uint8;
    day uint8;
};

type Person = struct {
    name string;
    birthday Date;
};

type Cat = struct {
    name string;
    age Date;
};

fi-0054:位/枚举成员无效

如果在没有预先定义的情况下引用 enumbits 成员,就会出现此错误。

library test.bad.fi0054;

type Enum = enum {
    foo_bar = 1;
};

const EXAMPLE Enum = Enum.FOO_BAR;

为避免此错误,请确认您先前已经为引用的成员值声明了值。这些值区分大小写。

library test.good.fi0054;

type Enum = enum {
    foo_bar = 1;
};

const EXAMPLE Enum = Enum.foo_bar;

fi-0055:对已弃用项的引用无效

如果您使用对 typeconst 的引用具有不兼容的 @available 属性,就会出现此错误。使用更高版本中已废弃的 typesconsts 时,通常就会发生这种情况。

@available(added=1)
library test.bad.fi0055;

@available(added=1, deprecated=2, note="use Color instead")
alias RGB = array<uint8, 3>;

@available(added=2)
type Color = struct {
    r uint8;
    g uint8;
    b uint8;
    a uint8;
};

@available(added=3)
type Config = table {
    // RGB is deprecated in version 2.
    1: color RGB;
};

如需修复此错误,请使用未废弃的 typeconst

@available(added=1)
library test.good.fi0055;

@available(added=1, deprecated=2, note="use Color instead")
alias RGB = array<uint8, 3>;

@available(added=2)
type Color = struct {
    r uint8;
    g uint8;
    b uint8;
    a uint8;
};

@available(added=3)
type Config = table {
    // Using a non-deprecated type.
    1: color Color;
};

fi-0056:对已弃用的其他平台的引用无效

如果您使用对其他平台的 typeconst 的引用,该引用具有不兼容的 @available 属性,就会出现此错误。使用更高版本中已废弃的 typesconsts 时,通常会出现这种情况。

@available(platform="foo", added=1)
library test.bad.fi0056a;

@available(added=1, deprecated=2, note="use Color instead")
alias RGB = array<uint8, 3>;

@available(added=2)
type Color = struct {
    r uint8;
    g uint8;
    b uint8;
    a uint8;
};
@available(platform="bar", added=2)
library test.bad.fi0056b;

using test.bad.fi0056a;

@available(added=3)
type Config = table {
    // RGB is deprecated in version 2.
    1: color test.bad.fi0056a.RGB;
};

如需修复此错误,请使用未废弃的 typeconst

@available(platform="foo", added=1)
library test.good.fi0056a;

@available(added=1, deprecated=2, note="use Color instead")
alias RGB = array<uint8, 3>;

@available(added=2)
type Color = struct {
    r uint8;
    g uint8;
    b uint8;
    a uint8;
};
@available(platform="bar", added=2)
library test.good.fi0056b;

using test.good.fi0056a;

@available(added=2)
type Config = table {
    // Change to use a non-deprecated type.
    1: color test.good.fi0056a.Color;
};

fi-0057:包含循环

有多种情况可能会导致出现此问题,但所有这些情况基本上可以归结为一个 FIDL 声明,以无法解析的方式引用自身。此错误的最简单形式是某个类型或协议在其自己的定义中直接引用自身:

library test.bad.fi0057c;

type MySelf = struct {
    me MySelf;
};

当某个类型或协议至少通过一个级别的间接方式指代自身时,可能会出现更复杂的故障情况:

library test.bad.fi0057a;

type Yin = struct {
    yang Yang;
};

type Yang = struct {
    yin Yin;
};
library test.bad.fi0057b;

protocol Yin {
    compose Yang;
};

protocol Yang {
    compose Yin;
};

此错误可以通过在包含周期中的某个位置添加信封(也称为可选性)来解决,因为这可以让周期在编码/解码时被“破坏”:

library test.good.fi0057;

type MySelf = struct {
    me box<MySelf>;
};
library test.bad.fi0057d;

type MySelf = table {
    1: me MySelf;
};

不允许使用未被信封连结的递归类型,因为它们无法编码。在上面的第一个示例中,对 MySelf 进行编码需要首先对 MySelf 的实例进行编码,而这又需要对 MySelf 的实例进行编码。如需解决此问题,可通过可选性在此链中添加“换行符”,可以选择对 MySelf 的另一个嵌套实例进行编码,或者编码一个 null 信封而不发送其他数据。

fi-0058:对编译器生成的载荷名称的引用

匿名方法载荷的名称将由 FIDL 编译器自动生成,因此生成的后端代码的用户可根据需要引用它们所代表的类型。但是,禁止在 *.fidl 文件中本身引用这些类型:

library test.bad.fi0058;

protocol MyProtocol {
    strict MyInfallible(struct {
        in uint8;
    }) -> (struct {
        out int8;
    });
    strict MyFallible(struct {
        in uint8;
    }) -> (struct {
        out int8;
    }) error flexible enum {};
    strict -> MyEvent(struct {
        out int8;
    });
};

type MyAnonymousReferences = struct {
    a MyProtocolMyInfallibleRequest;
    b MyProtocolMyInfallibleResponse;
    c MyProtocolMyFallibleRequest;
    d MyProtocol_MyFallible_Result;
    e MyProtocol_MyFallible_Response;
    f MyProtocol_MyFallible_Error;
    g MyProtocolMyEventRequest;
};

如果您希望直接引用载荷类型,则应将载荷类型提取到其自己的命名类型声明中:

library test.good.fi0058;

type MyRequest = struct {
    in uint8;
};
type MyResponse = struct {
    out int8;
};
type MyError = flexible enum {};

protocol MyProtocol {
    strict MyInfallible(MyRequest) -> (MyResponse);
    strict MyFallible(MyRequest) -> (MyResponse) error MyError;
    strict -> MyEvent(MyResponse);
};

type MyAnonymousReferences = struct {
    a MyRequest;
    b MyResponse;
    c MyRequest;
    // There is no way to explicitly name the error result union.
    // d MyProtocol_MyFallible_Result;
    e MyResponse;
    f MyError;
    g MyResponse;
};

所有 FIDL 方法和事件都会为其匿名请求载荷保留 [PROTOCOL_NAME][METHOD_NAME]Request 名称。严格且不会出错的双向方法还会预留 [PROTOCOL_NAME][METHOD_NAME]Response。灵活或容易出错的双向方法应为预留方法:

  • [PROTOCOL_NAME]_[METHOD_NAME]_Result
  • [PROTOCOL_NAME]_[METHOD_NAME]_Response
  • [PROTOCOL_NAME]_[METHOD_NAME]_Error

由于历史原因,这些名称使用的下划线与其他名称不同。

fi-0059:常量类型无效

并非所有类型都可以在 const 声明中使用:

library test.bad.fi0059;

const MY_CONST string:optional = "foo";

如果可能,转换为允许的类型:

library test.good.fi0059;

const MY_CONST string = "foo";

只有 FIDL 基元(boolint8int16int32int64uint8uint16uint32uint64float32float64)和非可选的 string 类型可以在 const 声明的左侧使用。

fi-0060:无法解析常量值

常量值必须可解析为已知值:

library test.bad.fi0060;

const MY_CONST bool = optional;

请确保使用的常量是有效值:

library test.good.fi0060;

const MY_CONST bool = true;

此错误通常伴随着其他错误,它们可让您详细了解不可解析的预期常量的性质。

fi-0061:非原始值上的 Or 运算符

“二元或”运算符只能用于基元:

library test.bad.fi0061;

const HI string = "hi";
const THERE string = "there";
const OR_OP string = HI | THERE;

请尝试将要操作的数据表示为 bits 枚举:

library test.good.fi0061;

type MyBits = flexible bits {
    HI = 0x1;
    THERE = 0x10;
};
const OR_OP MyBits = MyBits.HI | MyBits.THERE;

fi-0062:不允许使用 newtype

RFC-0052:类型别名和新类型中的新类型尚未完全实现,尚无法使用:

library test.bad.fi0062;

type Matrix = array<float64, 9>;

与此同时,您可以使用单个元素定义结构体,从而实现类似的效果:

library test.good.fi0062a;

type Matrix = struct {
    elements array<float64, 9>;
};

或者,您也可以定义别名,但请注意,与 newtype 不同,它不提供类型安全性(即它可以与其底层类型互换使用):

library test.good.fi0062b;

alias Matrix = array<float64, 9>;

fi-0063:应为值,但实际为类型

const 声明的右侧必须解析为常量值,而不是类型:

library test.bad.fi0063;

type MyType = struct {};
const MY_CONST uint32 = MyType;

确保右侧是一个值:

library test.good.fi0063;

const MY_VALUE uint32 = 8;
const MY_CONST uint32 = MY_VALUE;

fi-0064:位或枚举值类型不正确

使用 bitsenum 变体作为 const 声明中的值时,bits/enum 值的类型必须与 const 声明的左侧相同:

library test.bad.fi0064;

type MyEnum = enum : int32 {
    VALUE = 1;
};
type OtherEnum = enum : int32 {
    VALUE = 5;
};
const MY_CONST MyEnum = OtherEnum.VALUE;

一种解决方案是更改 const 声明的类型,使其与存储的值的类型一致:

library test.good.fi0064;

type MyEnum = enum : int32 {
    VALUE = 1;
};
type OtherEnum = enum : int32 {
    VALUE = 5;
};
const MY_CONST OtherEnum = OtherEnum.VALUE;

或者,您也可以选择其他值来匹配 const 声明的类型:

library test.good.fi0064;

type MyEnum = enum : int32 {
    VALUE = 1;
};
type OtherEnum = enum : int32 {
    VALUE = 5;
};
const MY_CONST MyEnum = MyEnum.VALUE;

fi-0065:无法将值转换为预期的类型

常量值的类型必须与其使用的位置相符。

导致此错误的最常见原因是 const 声明的值与其声明的类型不匹配:

library test.bad.fi0065a;

const MY_CONST bool = "foo";

如果在基础类型无效的位置使用正确定义的 const 值,就仍然可能出现问题:

library test.bad.fi0065b;

const ONE uint8 = 0x0001;
const TWO_FIFTY_SIX uint16 = 0x0100;
const TWO_FIFTY_SEVEN uint8 = ONE | TWO_FIFTY_SIX;

此外,FIDL 的官方工具会根据架构检查其参数。由于这些参数本身就是常量值,因此可能会发生同类的类型不匹配问题:

library test.bad.fi0065c;

protocol MyProtocol {
    @selector(3840912312901827381273)
    MyMethod();
};

在所有这些情况下,解决方案都是在接受 const 值的位置仅使用预期类型的值。上述情况将分别变为:

library test.good.fi0065a;

const MY_CONST string = "foo";
library test.good.fi0065b;

const ONE uint8 = 0x0001;
const TWO_FIFTY_SIX uint16 = 0x0100;
const TWO_FIFTY_SEVEN uint16 = ONE | TWO_FIFTY_SIX;
library test.good.fi0065c;

protocol MyProtocol {
    @selector("MyOldMethod")
    MyMethod();
};

fi-0066:常量溢出类型

常量值不能超出其基础类型固有的范围:

library test.bad.fi0066;

const NUM uint64 = -42;

您可以通过更改值使其适应类型的范围,从而解决此问题:

library test.good.fi0066a;

const NUM uint64 = 42;

或者,通过更改为类型以适应当前溢出的值:

library test.good.fi0066b;

const NUM int64 = -42;

此错误只涉及 FIDL 的数字类型,所有数字类型都可以溢出。这些范围来自 C++ std::numeric_limits 接口,如下所示:

类型 最小值 最大时长
int8 -128 127
int16 32768 32767
int32 2147483648 2147483647
int64 9223372036854775808 9223372036854775807
uint8 0 255
uint16 0 65536
uint32 0 4294967295
uint64 0 18446744073709551615
float32 -3.40282e+38 3.40282e+38
float64 -1.79769e+308 1.79769e+308

fi-0067:位成员必须是 2 的幂

bits 声明中所有成员的值都不得为任何不是 2 的幂的任何数字:

library test.bad.fi0067;

type NonPowerOfTwo = bits : uint64 {
    THREE = 3;
};

相反,成员值应始终为 2 的幂:

library test.good.fi0067a;

type Fruit = bits : uint64 {
    ORANGE = 1;
    APPLE = 2;
    BANANA = 4;
};

为避免受到此限制的困扰,一种简单方法就是只对位成员值使用位掩码,而不是十进制数:

library test.good.fi0067b;

type Life = bits {
    A = 0b000010;
    B = 0b001000;
    C = 0b100000;
};

bits 结构表示位数组。这是表示一系列布尔标志的最内存效率方式。由于 bits 声明的每个成员都会映射到其底层内存的特定位,因此用于该映射的值必须明确标识要分配到的无符号整数中的特定位。

fi-0068:灵活枚举具有保留的未知值

当您定义的枚举成员的值与预留的未知值冲突时,会发生此错误。

灵活的枚举可能包含 FIDL 架构不知道的值。此外,灵活的枚举始终保留一些被视为未知的值。默认情况下,该值是相应枚举的底层整数类型可表示的最大数值(例如,uint8255)。

library test.bad.fi0068;

type Foo = flexible enum : uint8 {
    ZERO = 0;
    ONE = 1;
    MAX = 255;
};

如需修正该错误,您可以移除成员或更改其值:

library test.good.fi0068a;

type Foo = flexible enum : uint8 {
    ZERO = 0;
    ONE = 1;
};
library test.good.fi0068b;

type Foo = flexible enum : uint8 {
    ZERO = 0;
    ONE = 1;
    MAX = 254;
};

最后,如果在将 strict 枚举转换为 flexible 枚举时遇到此错误,可以使用 @unknown 属性将特定成员的数值指定为未知值。请参阅 @unknown

fi-0069:位必须使用无符号整数子类型

禁止使用带符号数字作为 bits 声明的基础类型:

library test.bad.fi0069;

type Fruit = bits : int64 {
    ORANGE = 1;
    APPLE = 2;
    BANANA = 4;
};

请改用以下任何一项:uint8uint16uint32uint64

library test.good.fi0069;

type Fruit = bits : uint64 {
    ORANGE = 1;
    APPLE = 2;
    BANANA = 4;
};

与同时允许有符号和无符号整数的 enum 声明(请参阅 fi-0070)不同,bits 声明仅允许后者。这是因为,每个 bits 成员都必须表示某个位数组中的一个特定底层位(这就是 fi-0067 存在的原因)。它最简洁地表示为一个无符号整数。无符号整数的二进制表示法直接映射到单个位(2 为其索引次幂),而有符号整数中的负数几乎总是根据二进制补码表示法的机制选择多个位。

fi-0070:枚举必须使用整数子类型

禁止使用非整数 float32float64 作为 enum 声明的基础类型:

library test.bad.fi0070;

type MyEnum = enum : float64 {
    ONE_POINT_FIVE = 1.5;
};

请改用以下任何一项:int8int16int32int64uint8uint16uint32uint64

library test.good.fi0070;

type MyEnum = enum : uint64 {
    ONE = 1;
};

fi-0071:不允许严格枚举成员使用未知属性

strict enum 不得包含任何带有 @unknown 属性注解的成员:

library test.bad.fi0071;

type MyEnum = strict enum : int8 {
    @unknown
    UNKNOWN = 0;
    FOO = 1;
    MAX = 127;
};

如需继续使用 @unknown 属性,请更改为 flexible enum

library test.good.fi0071a;

type MyEnum = flexible enum : int8 {
    @unknown
    UNKNOWN = 0;
    FOO = 1;
    MAX = 127;
};

否则,只需彻底移除该属性即可保留 strict enum

library test.good.fi0071;

type MyEnum = strict enum : int8 {
    UNKNOWN = 0;
    FOO = 1;
    MAX = 127;
};

@unknown 属性的用途是平滑从具有用户定义的未知值的 strict enum 到具有未知值的 FIDL 处理的 flexible enum 的转换。在上面的示例中,它用于从第二个正确用法转换到第一个正确用法。

fi-0072:只有枚举成员可以带有未知属性

禁止使用 @unknown 属性为多个 enum 成员添加装饰:

library test.bad.fi0072;

type MyEnum = flexible enum : uint8 {
    @unknown
    UNKNOWN = 0;
    @unknown
    OTHER = 1;
};

仅选择用作网域特定“未知”值的成员并添加注释:

library test.good.fi0071a;

type MyEnum = flexible enum : int8 {
    @unknown
    UNKNOWN = 0;
    OTHER = 1;
};

@unknown 属性的用途是平滑从具有用户定义的未知值的 strict enum 到具有未知值的 FIDL 处理的 flexible enum 的转换:

library test.good.fi0072;

type MyEnum = strict enum : int8 {
    UNKNOWN = 0;
    OTHER = 1;
};
library test.good.fi0071a;

type MyEnum = flexible enum : int8 {
    @unknown
    UNKNOWN = 0;
    OTHER = 1;
};

fi-0073:编写非协议

compose 语句中只能使用协议:

library test.bad.fi0073;

type MyStruct = struct {};

protocol MyProtocol {
    compose MyStruct;
};

请确保您所指的名称指向协议:

library test.good.fi0073;

protocol MyOtherProtocol {};

protocol MyProtocol {
    compose MyOtherProtocol;
};

fi-0074:方法载荷使用的布局无效

只能使用 structtableunion 布局描述方法载荷:

library test.bad.fi0074;

protocol MyProtocol {
    MyMethod(enum {
        FOO = 1;
    });
};

请改用下列其中一种布局:

library test.good.fi0074;

protocol MyProtocol {
    MyMethod(struct {
        foo bool;
    });
};

fi-0075:用于方法负载的基元无效

基元不能用作方法方法载荷:

library test.bad.fi0075;

protocol MyProtocol {
    MyMethod(uint32);
};

请改用 structtableunion 布局类型:

library test.good.fi0075;

protocol MyProtocol {
    MyMethod(struct {
        wrapped_in_struct uint32;
    });
};

如果所需的载荷实际上只是一个基元值,并且未来的演变并不在意,则将该值封装在 struct 布局中会导致载荷本身的大小与所需值的大小相同。

fi-0076

fi-0077:互动载荷不能为空结构体

方法或事件中的载荷不能是空结构体:

library test.bad.fi0077a;

protocol Test {
    MyMethod(struct {}) -> (struct {});
};
library test.bad.fi0077b;

protocol Test {
    -> MyEvent(struct {});
};

如果您希望表示特定请求/响应不保存任何信息,请删除空结构体,并将 () 保留在该位置:

library test.good.fi0077a;

protocol Test {
    MyMethod() -> ();
};
library test.good.fi0077b;

protocol Test {
    -> MyEvent();
};

空结构体无法扩展,会占用 1 个字节。由于 FIDL 支持没有载荷的交互,因此以这种方式使用空结构体会多余且效率较低。因此不允许使用。

fi-0078

fi-0079

fi-0080:生成的零值序数

此错误绝不应发生。如果您成功做到了,那么恭喜您,您可能破坏了 SHA-256!

开玩笑的是,如果 fidlc 编译器生成的序数值为 0,就会出现此错误。这种情况绝不该发生,因此如果出现这种情况,可能是因为您在 FIDL 编译器中发现了一个 bug。如果发生这种情况,请向我们的问题跟踪器报告该问题。

fi-0081:重复方法序数

当您使用 @selector 属性使两个方法名称生成相同的序数时,通常会发生此错误。

library test.bad.fi0081;

protocol Parser {
    ParseLine();

    // Multiple methods with the same ordinal...
    @selector("ParseLine")
    ParseOneLine();
};

要解决此问题,请更新方法名称或选择器,以避免冲突。

library test.good.fi0081;

protocol Parser {
    ParseLine();

    @selector("Parse1Line")
    ParseOneLine();
};

如果存在 SHA-256 冲突,也会发生此错误,但这种冲突的概率基本上为零。如果您确定选择器没有故障,但仍然遇到此错误,则可能是因为您在 FIDL 编译器中发现了 bug。如果发生这种情况,请向我们的问题跟踪器报告该问题。

fi-0082:选择器值无效

当您为 @selector 使用无效值时,就会出现此错误。这通常是由拼写错误导致的。选择器必须是独立的方法名称,或完全限定的方法名称。

library test.bad.fi0082;

protocol Parser {
    @selector("test.old.fi0082.Parser.Parse")
    Parse();
};

如需修复此问题,请将选择器更新为有效的独立方法名称或完全限定的方法名称:

library test.good.fi0082;

protocol Parser {
    @selector("test.old.fi0082/Parser.Parse")
    Parse();
};

fi-0083:fuchsia.io 必须使用显式序数

FIDL 编译器用于将 fuchsia.io 序数自动重命名为 fuchsia.io1。此魔法命令旨在让方法的 io2 版本具有“常规”序数,从而更轻松地迁移到 fuchsia.io2。不过,这个系统最终有点太神奇了,因此现在需要手动为 fuchsia.io 提供序数。

library fuchsia.io;

protocol SomeProtocol {
    SomeMethod();
};

若要解决此问题,请手动提供一个使用 fuchsia.io1 作为库名称的选择器,以允许将 fuchsia.io 名称用于 io2。

library fuchsia.io;

protocol SomeProtocol {
    @selector("fuchsia.io1/SomeProtocol.SomeMethod")
    SomeMethod();
};

fi-0084:方法载荷结构体不允许默认成员

用作方法 Paylod 的结构体不能指定默认成员:

library test.bad.fi0084;

type MyStruct = struct {
    @allow_deprecated_struct_defaults
    a bool = false;
};

protocol MyProtocol {
    MyMethod(MyStruct) -> (MyStruct);
};

从相关的 struct 声明中移除默认成员:

library test.good.fi0084;

type MyStruct = struct {
    a bool;
};

protocol MyProtocol {
    MyMethod(MyStruct) -> (MyStruct);
};

fi-0085

fi-0086

fi-0087

fi-0088:服务成员不能是可选成员

当您将服务成员标记为 optional 时,就会出现此错误。不允许将服务成员标记为 optional,因为服务成员始终是可选的。

library test.bad.fi0088;

protocol Sorter {
    Sort(struct {
        input vector<int32>;
    }) -> (struct {
        output vector<int32>;
    });
};

service SortService {
    quicksort client_end:<Sorter, optional>;
    mergesort client_end:<Sorter, optional>;
};

要解决此问题,请移除可选子句:

library test.good.fi0088;

protocol Sorter {
    Sort(struct {
        input vector<int32>;
    }) -> (struct {
        output vector<int32>;
    });
};

service SortService {
    quicksort client_end:Sorter;
    mergesort client_end:Sorter;
};

fi-0089

fi-0090

fi-0091:结构体成员类型无效

当您尝试为不受支持的类型设置默认结构体值时,就会出现此错误。只允许数字和布尔值类型设置默认结构体值。

library test.bad.fi0091;

type Person = struct {
    @allow_deprecated_struct_defaults
    name string:optional = "";
};

如需修复此问题,请移除默认值:

library test.good.fi0091;

type Person = struct {
    @allow_deprecated_struct_defaults
    name string:optional;
};

fi-0092:表序号太大

FIDL 表序数不能超过 64:

library test.bad.fi0092;

type Table64thField = table {
    1: x int64;
};

type Example = table {
    1: v1 int64;
    2: v2 int64;
    3: v3 int64;
    4: v4 int64;
    5: v5 int64;
    6: v6 int64;
    7: v7 int64;
    8: v8 int64;
    9: v9 int64;
   10: v10 int64;
   11: v11 int64;
   12: v12 int64;
   13: v13 int64;
   14: v14 int64;
   15: v15 int64;
   16: v16 int64;
   17: v17 int64;
   18: v18 int64;
   19: v19 int64;
   20: v20 int64;
   21: v21 int64;
   22: v22 int64;
   23: v23 int64;
   24: v24 int64;
   25: v25 int64;
   26: v26 int64;
   27: v27 int64;
   28: v28 int64;
   29: v29 int64;
   30: v30 int64;
   31: v31 int64;
   32: v32 int64;
   33: v33 int64;
   34: v34 int64;
   35: v35 int64;
   36: v36 int64;
   37: v37 int64;
   38: v38 int64;
   39: v39 int64;
   40: v40 int64;
   41: v41 int64;
   42: v42 int64;
   43: v43 int64;
   44: v44 int64;
   45: v45 int64;
   46: v46 int64;
   47: v47 int64;
   48: v48 int64;
   49: v49 int64;
   50: v50 int64;
   51: v51 int64;
   52: v52 int64;
   53: v53 int64;
   54: v54 int64;
   55: v55 int64;
   56: v56 int64;
   57: v57 int64;
   58: v58 int64;
   59: v59 int64;
   60: v60 int64;
   61: v61 int64;
   62: v62 int64;
   63: v63 int64;
    // The 64th field of a table must be another table, otherwise it will cause
    // fi-0093: Max Ordinal In Table Must Be Table.
   64: v64 Table64thField;
   65: v65 int64;
};

为支持超过 64 个序数的增长,FIDL 要求一个表的最后一个字段是另一个表。超过 64 的任何表字段都必须放在嵌套表中。

library test.good.fi0092;

type Table64thField = table {
    1: x int64;
    // Any fields beyond 64 of table Example must be move to the nested table in
    // ordinal 64 of Example.
    2: v65 int64;
};

type Example = table {
    1: v1 int64;
    2: v2 int64;
    3: v3 int64;
    4: v4 int64;
    5: v5 int64;
    6: v6 int64;
    7: v7 int64;
    8: v8 int64;
    9: v9 int64;
   10: v10 int64;
   11: v11 int64;
   12: v12 int64;
   13: v13 int64;
   14: v14 int64;
   15: v15 int64;
   16: v16 int64;
   17: v17 int64;
   18: v18 int64;
   19: v19 int64;
   20: v20 int64;
   21: v21 int64;
   22: v22 int64;
   23: v23 int64;
   24: v24 int64;
   25: v25 int64;
   26: v26 int64;
   27: v27 int64;
   28: v28 int64;
   29: v29 int64;
   30: v30 int64;
   31: v31 int64;
   32: v32 int64;
   33: v33 int64;
   34: v34 int64;
   35: v35 int64;
   36: v36 int64;
   37: v37 int64;
   38: v38 int64;
   39: v39 int64;
   40: v40 int64;
   41: v41 int64;
   42: v42 int64;
   43: v43 int64;
   44: v44 int64;
   45: v45 int64;
   46: v46 int64;
   47: v47 int64;
   48: v48 int64;
   49: v49 int64;
   50: v50 int64;
   51: v51 int64;
   52: v52 int64;
   53: v53 int64;
   54: v54 int64;
   55: v55 int64;
   56: v56 int64;
   57: v57 int64;
   58: v58 int64;
   59: v59 int64;
   60: v60 int64;
   61: v61 int64;
   62: v62 int64;
   63: v63 int64;
   64: v64 Table64thField;
};

为了将字段设为可选字段,表中的每个字段都会产生 FIDL 信封的开销。这样,表的每个字段均存在或不存在,并可通过添加或移除字段来演变表,但代价是比结构体大得多的内存开销。

通常,您可以通过避免在表中使用较小的精细字段来避免此错误并减少开销。相反,您可以将需要同时添加或移除的元素组合到结构体中,并将其用作表的字段。这样可以减少开销,并避免用序数用完,但代价是有一定程度的演进性。

这在 RFC-0132: FIDL table size limit 中成为了错误,旨在防止用户意外产生非常大的表的开销。这种额外费用在架构中并不明显,尤其是在只有几个字段(具有大型序数)或者字段有很多但每次仅使用几个字段时。

fi-0093:表中的最大序数必须为表

FIDL 表中第 64 个成员的类型本身必须是表:

library test.bad.fi0093;

type Example = table {
    1: v1 int64;
    2: v2 int64;
    3: v3 int64;
    4: v4 int64;
    5: v5 int64;
    6: v6 int64;
    7: v7 int64;
    8: v8 int64;
    9: v9 int64;
   10: v10 int64;
   11: v11 int64;
   12: v12 int64;
   13: v13 int64;
   14: v14 int64;
   15: v15 int64;
   16: v16 int64;
   17: v17 int64;
   18: v18 int64;
   19: v19 int64;
   20: v20 int64;
   21: v21 int64;
   22: v22 int64;
   23: v23 int64;
   24: v24 int64;
   25: v25 int64;
   26: v26 int64;
   27: v27 int64;
   28: v28 int64;
   29: v29 int64;
   30: v30 int64;
   31: v31 int64;
   32: v32 int64;
   33: v33 int64;
   34: v34 int64;
   35: v35 int64;
   36: v36 int64;
   37: v37 int64;
   38: v38 int64;
   39: v39 int64;
   40: v40 int64;
   41: v41 int64;
   42: v42 int64;
   43: v43 int64;
   44: v44 int64;
   45: v45 int64;
   46: v46 int64;
   47: v47 int64;
   48: v48 int64;
   49: v49 int64;
   50: v50 int64;
   51: v51 int64;
   52: v52 int64;
   53: v53 int64;
   54: v54 int64;
   55: v55 int64;
   56: v56 int64;
   57: v57 int64;
   58: v58 int64;
   59: v59 int64;
   60: v60 int64;
   61: v61 int64;
   62: v62 int64;
   63: v63 int64;
   64: v64 int64;
};

如果用户发现自己需要添加第 64 个成员,则应创建一个单独的表来存放 64 岁及以上的成员,并将该成员放入表中:

library test.good.fi0093;

type Table64thField = table {
    1: x int64;
};

type Example = table {
    1: v1 int64;
    2: v2 int64;
    3: v3 int64;
    4: v4 int64;
    5: v5 int64;
    6: v6 int64;
    7: v7 int64;
    8: v8 int64;
    9: v9 int64;
   10: v10 int64;
   11: v11 int64;
   12: v12 int64;
   13: v13 int64;
   14: v14 int64;
   15: v15 int64;
   16: v16 int64;
   17: v17 int64;
   18: v18 int64;
   19: v19 int64;
   20: v20 int64;
   21: v21 int64;
   22: v22 int64;
   23: v23 int64;
   24: v24 int64;
   25: v25 int64;
   26: v26 int64;
   27: v27 int64;
   28: v28 int64;
   29: v29 int64;
   30: v30 int64;
   31: v31 int64;
   32: v32 int64;
   33: v33 int64;
   34: v34 int64;
   35: v35 int64;
   36: v36 int64;
   37: v37 int64;
   38: v38 int64;
   39: v39 int64;
   40: v40 int64;
   41: v41 int64;
   42: v42 int64;
   43: v43 int64;
   44: v44 int64;
   45: v45 int64;
   46: v46 int64;
   47: v47 int64;
   48: v48 int64;
   49: v49 int64;
   50: v50 int64;
   51: v51 int64;
   52: v52 int64;
   53: v53 int64;
   54: v54 int64;
   55: v55 int64;
   56: v56 int64;
   57: v57 int64;
   58: v58 int64;
   59: v59 int64;
   60: v60 int64;
   61: v61 int64;
   62: v62 int64;
   63: v63 int64;
   64: v64 Table64thField;
};

RFC-0132:FIDL 表大小限制详细说明了制定此要求的原因和相关动机。简而言之,FIDL 表需要对允许的字段数量设置相对限制,否则,一次仅使用几个字段的表编码形式将会产生令人无法接受的大量死空间(每个省略的成员为 16 个字节)。

为了给需要表中超过 64 个字段的用户提供一种临时解决方法,FIDL 会强制为包含额外字段的“接续表”预留最后一个序数。在此位置使用任何其他类型都会呈现表格今后将变为后续内容。

fi-0094:重复的表成员序数

table 声明中成员使用的序数不能重复:

library test.bad.fi0094;

type MyTable = table {
    1: my_field string;
    1: my_other_field uint32;
};

根据需要递增序数,以确保声明的所有成员的序数都是唯一的:

library test.good.fi0094a;

type MyTable = table {
    1: my_field string;
    2: my_other_field uint32;
};

或者,可以移除其中一个具有重复名称的成员:

library test.good.fi0094b;

type MyTable = table {
    1: my_field string;
};

序数用于标识电线上的字段。如果两个成员共用一个序数,则在解码 FIDL 消息时,没有可靠的方法来辨别所引用的字段。

fi-0095

fi-0096

fi-0097:重复工会成员序号

union 声明中成员使用的序数不能重复:

library test.bad.fi0097;

type MyUnion = strict union {
    1: my_variant string;
    1: my_other_variant int32;
};

根据需要递增序数,以确保声明的所有成员的序数都是唯一的:

library test.good.fi0097a;

type MyUnion = strict union {
    1: my_variant string;
    2: my_other_variant int32;
};

或者,可以移除其中一个具有重复名称的成员:

library test.good.fi0097b;

type MyUnion = strict union {
    1: my_variant string;
};

序数用于标识电线上的款式。如果两个成员共用一个序数,在解码 FIDL 消息时,没有可靠的方法可以辨别所引用的变体。

fi-0098

fi-0099

fi-0100

fi-0101:尺寸限制无法解析

vectorstring 类型定义应用的大小限制条件必须是有效的 uint32 类型值:

library test.bad.fi0101a;

alias MyBoundedOptionalVector = vector<uint32>:<"255", optional>;
library test.bad.fi0101b;

alias MyBoundedOptionalVector = vector<uint32>:<uint8, optional>;

确保情况符合上述情况:

library test.good.fi0101;

alias MyBoundedOptionalVector = vector<uint32>:<255, optional>;

fi-0102:成员值无法解析

bitsenum 声明的成员必须是指定子类型的可解析值:

library test.bad.fi0102;

type Fruit = bits : uint64 {
    ORANGE = 1;
    APPLE = 2;
    BANANA = -4;
};

确保所有值都与声明的基础类型匹配:

library test.good.fi0102;

type Fruit = bits : uint64 {
    ORANGE = 1;
    APPLE = 2;
    BANANA = 4;
};

fi-0103:无法解析结构体默认值

struct 声明的成员的默认值必须与各自成员声明的类型相匹配:

library test.bad.fi0103;

type MyEnum = enum : int32 {
    A = 1;
};

type MyStruct = struct {
    @allow_deprecated_struct_defaults
    field MyEnum = 1;
};

确保该值与声明的类型匹配:

library test.good.fi0103;

type MyEnum = enum : int32 {
    A = 1;
};

type MyStruct = struct {
    @allow_deprecated_struct_defaults
    field MyEnum = MyEnum.A;
};

fi-0104:属性参数无法解析

根据属性架构对该参数的预期,官方 FIDL 属性的参数值不得无效:

library test.bad.fi0104;

type MyStruct = struct {
    my_field @generated_name(true) struct {};
};

确保用作属性参数的值的类型正确无误:

library test.good.fi0104;

type MyStruct = struct {
    my_field @generated_name("my_inner_type") struct {};
};

fi-0105

fi-0106

fi-0107:成员值重复

bitsenum 声明都不能包含具有相同值的成员:

library test.bad.fi0107;

type Fruit = flexible enum {
    ORANGE = 1;
    APPLE = 1;
};

将成员值更改为所有值都是唯一的:

library test.good.fi0107a;

type Fruit = flexible enum {
    ORANGE = 1;
    APPLE = 2;
};

或者,您也可以移除某个重复的成员:

library test.good.fi0107b;

type Fruit = flexible enum {
    ORANGE = 1;
};

fi-0108

fi-0109

fi-0110:包含类型的资源必须标记为资源

如果类型包含句柄(无论是直接包含还是通过传递包含另一个包含句柄的类型),则无法声明该类型,除非将该类型指定为 resource

library test.bad.fi0110;

using zx;

type Foo = struct {
    handle zx.Handle;
};

有两种可能的解决方案。第一种方法是使用资源修饰符为违规声明添加注解:

library test.good.fi0110a;

using zx;

type Foo = resource struct {
    handle zx.Handle;
};

或者,也可以选择完全移除包含 resource 的类型,这样就无需对所属声明使用修饰符:

library test.good.fi0110b;

type Foo = struct {
    value uint32;
};

如需了解添加 resource 修饰符的原因和动机,以及由此错误强制执行的使用模式的“传染性”特性,请参阅 RFC-0057: Default nohandle(默认无句柄)。

fi-0111:内嵌大小超出限制

不允许使用内嵌大小为 64 KiB 或更大的 FIDL 类型:

library test.bad.fi0111;

type MyStruct = struct {
    numbers array<uint8, 65536>;
};

请改为确保该类型的内嵌大小小于 64 KiB。在这种情况下,我们可以调整数组边界:

library test.good.fi0111;

type MyStruct = struct {
    numbers array<uint8, 65535>;
};

此限制是出于性能方面的考虑。这意味着编码器和解码器可以假定大小和偏移量适合无符号 16 位整数。

除非您使用大型数组或深度嵌套的结构体,否则在实践中不太可能遇到此问题。大多数 FIDL 结构(例如字符串、向量、表和联合)都使用行外存储,这类存储不会计入其各自的内嵌大小。

fi-0112:服务成员不是 client_end

服务成员只能作为客户端端,而不能是任何其他类型:

library test.bad.fi0112;

protocol Calculator {};

service Service {
    calculator server_end:Calculator;
};

如需修正该错误,请确保该成员使用某些协议 Pclient_end:P 格式:

library test.good.fi0112;

protocol Calculator {};

service Service {
    calculator client_end:Calculator;
};

服务是协议实例的集合,而不是通用的数据结构,因此允许任意类型是毫无意义的。

fi-0113:服务中的传输不匹配

FIDL 服务不得包含采用不同传输的协议:

library test.bad.fi0113;

protocol ChannelProtocol {};

@transport("Driver")
protocol DriverProtocol {};

service SomeService {
    a client_end:ChannelProtocol;
    b client_end:DriverProtocol;
};

相反,对每种传输使用单独的服务:

library test.good.fi0113;

protocol ChannelProtocol {};

@transport("Driver")
protocol DriverProtocol {};

service ChannelService {
    protocol client_end:ChannelProtocol;
};

service DriverService {
    protocol client_end:DriverProtocol;
};

请注意,服务是 FIDL 中尚未完成的功能。它们最初是在 RFC-0041:支持统一服务和设备中设计的。如需了解截至 2022 年 10 月的状态,请参阅 https://fxbug.dev/42160684

fi-0114:Compose 协议太开放

一个协议无法编写比其开放性更高的其他协议:

library test.bad.fi0114;

open protocol Composed {};

ajar protocol Composing {
    compose Composed;
};

您可以通过提高组合协议的开放性(即将其从 closed 更改为 ajar 或从 ajar 更改为 open)来解决此问题:

library test.good.fi0114a;

open protocol Composed {};

open protocol Composing {
    compose Composed;
};

或者,您也可以降低组合协议的开放性,即将其从 open 更改为 ajar,或从 ajar 更改为 closed

library test.good.fi0114b;

ajar protocol Composed {};

ajar protocol Composing {
    compose Composed;
};

之所以存在此规则,是因为协议的开放性限制了允许包含的方法类型。例如,ajar 协议不能包含灵活的双向方法,但 Open 协议可以包含,因此 ajar 协议构成开放协议并不安全。

如需详细了解协议修饰符,请参阅 RFC-0138:处理未知互动

fi-0115:灵活的双向方法需要开放式协议

封闭式协议和 ajar 协议不得包含灵活的双向方法:

library test.bad.fi0115;

ajar protocol Protocol {
    flexible Method() -> ();
};

请改为将双向方法标记为 strict,而不是 flexible

library test.good.fi0115a;

ajar protocol Protocol {
    strict Method() -> ();
};

或者,将协议标记为 open,而不是 closedajar

library test.good.fi0115b;

open protocol Protocol {
    flexible Method() -> ();
};

出现此错误的原因是,closed(或 ajar)修饰符的用途是确保方法不包含任何灵活的(双向)方法。首次创建协议时,您应该根据从协议中所需的演化性属性来仔细考虑该协议是应该关闭、ajar 还是开放。

如需详细了解协议修饰符,请参阅 RFC-0138:处理未知互动

fi-0116:灵活的单向方法需要 ajar 文件或开放式协议

封闭式协议不得包含灵活的单向方法:

library test.bad.fi0116;

closed protocol Protocol {
    flexible Method();
};

请改为将单向方法标记为 strict,而不是 flexible

library test.good.fi0116;

closed protocol Protocol {
    strict Method();
};

或者,将协议标记为 ajaropen,而不是 closed

library test.good.fi0116;

ajar protocol Protocol {
    flexible Method();
};

之所以出现此错误,是因为 closed 修饰符的用途是确保方法不包含任何灵活方法。首次创建协议时,您应该根据协议所需的演化性属性,仔细考虑该协议是应该关闭、ajar 还是开放。

如需详细了解协议修饰符,请参阅 RFC-0138:处理未知互动

fi-0117:在不兼容的传输中所使用的句柄

协议只能引用与其传输兼容的句柄。例如,基于 Zircon 通道传输的协议不能引用 Fuchsia 驱动程序框架句柄:

library test.bad.fi0117;

using fdf;

protocol Protocol {
    Method(resource struct {
        h fdf.handle;
    });
};

请改为使用与协议传输兼容的句柄:

library test.good.fi0117a;

using zx;

protocol Protocol {
    Method(resource struct {
        h zx.Handle;
    });
};

或者,更改协议的传输以匹配句柄:

library test.good.fi0117b;

using fdf;

@transport("Driver")
protocol Protocol {
    Method(resource struct {
        h fdf.handle;
    });
};

fi-0118:在不兼容的传输中使用传输端

协议只能指代在同一传输中的协议的传输结束(client_endserver_end)。例如,使用 Syscall 传输的协议不能引用使用驱动程序传输的协议的客户端:

library test.bad.fi0118;

@transport("Driver")
protocol DriverProtocol {};

@transport("Syscall")
protocol P {
    M(resource struct {
        s client_end:DriverProtocol;
    });
};

如需修复此错误,请移除传输端成员:

library test.good.fi0118;

@transport("Driver")
protocol DriverProtocol {};

@transport("Syscall")
protocol Protocol {
    M();
};

fi-0119:事件中的错误语法已弃用

该事件用于允许错误语法,但现在已被弃用:

library example;

protocol MyProtocol {
    -> OnMyEvent() error int32;
};

而应指定没有错误的事件:

library test.good.fi0119a;

protocol MyProtocol {
    -> OnMyEvent();
};

或者,改为将错误建模为联合体:

library test.good.fi0119b;

protocol MyProtocol {
    -> OnMyEvent(flexible union {
        1: success struct {};
        2: error uint32;
    });
};

在错误语法弃用之前,将错误语法用于事件已经是不寻常的做法。事件是由服务器发起的,服务器无请求地向客户端发送故障似乎很奇怪。最好针对这些罕见的用例使用联合,而不是在所有绑定中都支持某种语言功能。

fi-0120:属性放置无效

某些官方属性仅可在特定位置使用。例如,@selector 属性只能用于方法:

library test.bad.fi0120a;

@selector("Nonsense")
type MyUnion = union {
    1: hello uint8;
};

如需修正该错误,请移除此属性:

library test.good.fi0120a;

type MyUnion = union {
    1: hello uint8;
};

如果您打算以受支持的方式使用某个属性,但将其放在错误的位置,也可能会遇到此错误。例如,@generated_name 属性不能直接作用于成员:

library test.bad.fi0120a;

@selector("Nonsense")
type MyUnion = union {
    1: hello uint8;
};

相反,它应该位于成员的匿名布局之前:

library test.good.fi0120a;

type MyUnion = union {
    1: hello uint8;
};

fi-0121:属性已弃用

某些官方属性已弃用,不应再使用:

library test.bad.fi0121;

@example_deprecated_attribute
type MyStruct = struct {};

修复方法取决于该属性已弃用的原因。例如,错误消息可能会提示改用其他属性。在本例中,我们只需移除该属性:

library test.good.fi0121;

type MyStruct = struct {};

fi-0122:属性名称重复

一个元素不能有多个同名属性:

library test.bad.fi0122;

@custom_attribute("first")
@custom_attribute("second")
type Foo = struct {};

而应仅指定每个属性一次:

library test.good.fi0122;

@custom_attribute("first")
type Foo = struct {};

fi-0123:规范属性名称重复

一个元素不能有多个具有相同规范名称的属性:

library test.bad.fi0123;

@custom_attribute("first")
@CustomAttribute("second")
type Foo = struct {};

虽然 custom_attributeCustomAttribute 看起来有所不同,但它们都由规范名称 custom_attribute 表示。通过将原始名称转换为 snake_case,即可得到规范名称。

如需修正该错误,请为每个属性指定一个在规范化后唯一的名称。

library test.good.fi0123;

@custom_attribute("first")
@AnotherCustomAttribute("first")
type Foo = struct {};

如需详细了解 FIDL 为何要求声明具有唯一的规范名称,请参阅 fi-0035

fi-0124:自定义属性参数必须为字符串或布尔值

用户定义的 FIDL 属性中的参数仅限于字符串或布尔值类型:

library test.bad.fi0124;

@my_custom_attr(foo=1, bar=2.3)
type MyStruct = struct {};
library test.good.fi0124;

@my_custom_attr(foo=true, bar="baz")
type MyStruct = struct {};

官方属性不同,编译器不了解用户定义的属性的架构。因此,编译器无法推断出任何给定数字参数的类型 - 2int8uint64 还是 float32?编译器无法知晓。

此问题的可能解决方法是在 JSON IR 中针对此类不明确的情况实现一级 numeric 类型。但是,由于自定义属性参数是此功能目前唯一已知的用例,因此我们没有优先考虑此功能。

fi-0125:属性参数不得命名

使用采用单个参数的官方属性时,您无法为该参数命名:

library test.bad.fi0125;

@discoverable(value="example.Bar")
protocol Foo {};

相反,您应传递参数而不为其指定名称:

library test.good.fi0125;

@discoverable("example.Bar")
protocol Foo {};

FIDL 强制执行此限制条件,以使属性更简洁和一致。从本质上讲,参数名称会推断为 value(并且会显示在 JSON IR 中),因为这是属性接受的唯一参数。

fi-0126:属性参数必须命名

使用采用多个参数的官方属性时,不能传递未命名的参数:

@available(1)
library test.bad.fi0126;

而应指定参数的名称:

@available(added=1)
library test.good.fi0126;

出现此错误的原因是,如果属性接受多个参数,则无法知道您打算设置哪个参数。

fi-0127:缺少必需的属性参数

使用具有必需参数的官方属性时,不能将其省略:

library test.bad.fi0127;

@has_required_arg
type Foo = struct {};

而应提供必需的参数:

library test.good.fi0127;

@has_required_arg(required="something")
type Foo = struct {};

fi-0128:缺少单个属性参数

使用需要单个参数的官方属性时,不能将其省略:

library test.bad.fi0128;

@transport
protocol Protocol {};

而应改为提供实参:

library test.good.fi0128;

@transport("Driver")
protocol Protocol {};

fi-0129:未知属性参数

使用官方属性时,您不能提供未包含在架构中的参数:

@available(added=1, discontinued=2)
library test.bad.fi0129;

如果您想传递其他参数但名称有误,请将其更改为使用正确的名称:

@available(added=1, deprecated=2)
library test.good.fi0129a;

或者,移除该参数:

@available(added=1)
library test.good.fi0129b;

出现此错误是因为官方属性是针对架构进行验证的。如果 FIDL 允许任意参数,这些参数将不会产生任何影响,并且可能会通过遮盖拼写错误而导致 bug。

fi-0130:属性参数重复

一个属性不能包含两个同名参数:

library test.bad.fi0130;

@custom_attribute(custom_arg=true, custom_arg=true)
type Foo = struct {};

而应仅提供一个具有该名称的参数:

library test.good.fi0130;

@custom_attribute(custom_arg=true)
type Foo = struct {};

fi-0131:规范属性参数重复

一个属性不能包含两个具有相同规范名称的参数:

library test.bad.fi0131;

@custom_attribute(custom_arg=true, CustomArg=true)
type Foo = struct {};

虽然 custom_argCustomArg 看起来不同,但它们都由规范名称 custom_arg 表示。通过将原始名称转换为 snake_case,可获得规范名称。

如需修复该错误,请为每个参数指定一个在规范化后唯一的名称:

library test.good.fi0131a;

@custom_attribute(custom_arg=true, AnotherCustomArg=true)
type Foo = struct {};

或者,移除以下参数之一:

library test.good.fi0131b;

@custom_attribute(custom_arg=true)
type Foo = struct {};

如需详细了解 FIDL 为何要求声明具有唯一的规范名称,请参阅 fi-0035

fi-0132:非预期属性参数

使用不带参数的官方属性时,您不能提供参数:

library test.bad.fi0132;

type Foo = flexible enum : uint8 {
    @unknown("hello")
    BAR = 1;
};

而应移除该参数:

library test.good.fi0132;

type Foo = flexible enum : uint8 {
    @unknown
    BAR = 1;
};

fi-0133:属性参数必须为字面量

某些官方属性不允许引用常量的参数:

library test.bad.fi0133;

const NAME string = "MyTable";

type Foo = struct {
    bar @generated_name(NAME) table {};
};

请改为传递字面量值作为参数:

library test.good.fi0133;

type Foo = struct {
    bar @generated_name("MyTable") table {};
};

这些属性需要字面量参数,因为它们的值会影响编译。支持非字面上的参数很难实现,在某些情况下,甚至根本做不到,因为它会导致冲突。

fi-0134

fi-0135:可检测到的名称无效

如果您为 @discoverable 属性使用了错误的名称,就会出现此错误。@discoverable 属性应为库名称,后跟 . 和协议名称。

library test.bad.fi0135;

@discoverable("test.bad.fi0135/Parser")
protocol Parser {
    Tokenize() -> (struct {
        tokens vector<string>;
    });
};

如需修正此错误,请使用有效的可检测名称:

library test.good.fi0135;

@discoverable("test.good.fi0135.Parser")
protocol Parser {
    Tokenize() -> (struct {
        tokens vector<string>;
    });
};

fi-0136

fi-0137

fi-0138

fi-0139

fi-0140

fi-0141:错误类型无效

方法响应载荷的 error 类型必须是 int32uint32enum

library test.bad.fi0141;

protocol MyProtocol {
    MyMethod() -> () error float32;
};

请将 error 类型更改为以下某个有效选项来修复此错误:

library test.good.fi0141;

protocol MyProtocol {
    MyMethod() -> () error int32;
};

如需了解详情,请参阅 RFC-0060:错误处理

fi-0142:协议传输类型无效

protocol 声明中的 @transport(...) 属性不得指定无效传输:

library test.bad.fi0142;

@transport("Invalid")
protocol MyProtocol {
    MyMethod();
};

请改用其中一种受支持的传输:

library test.good.fi0142;

@transport("Syscall")
protocol MyProtocol {
    MyMethod();
};

构成受支持的传输的内容仍在最终确定。如需了解最新信息,请参阅 FIDL 属性

fi-0143

fi-0144

fi-0145:属性拼写错误

如果属性名称的拼写与 FIDL 的某个官方属性过于相似,则会导致编译器警告:

library test.bad.fi0145;

@duc("should be doc")
protocol Example {
    Method();
};

在上面的示例中,属性 @duc 在拼写上与官方 FIDL 属性 @doc 过于相似。在这种情况下,属性命名是有意为之,而不是对官方 FIDL 属性的意外拼写错误,应予以修改,使其具有足够的唯一性:

library test.good.fi0145;

@duck("quack")
protocol Example {
    Method();
};

除了拼写检查之外,此警告的目的是不要使用与官方 FIDL 属性过于相似的名称。

拼写错误检测算法的工作原理是从每个官方 FIDL 属性计算属性名称的修改距离。如果名称过于相似(例如修改距离太小),就会触发拼写错误检测器。

fi-0146:生成的名称无效

如果您使用的 @generated_name 属性具有无效的名称,就会出现此错误。生成的名称必须遵循与所有 FIDL 标识符相同的规则。

library test.bad.fi0146;

type Device = table {
    1: kind flexible enum {
        DESKTOP = 1;
        PHONE = 2;
    };
};

type Input = table {
    1: kind @generated_name("_kind") flexible enum {
        KEYBOARD = 1;
        MOUSE = 2;
    };
};

如需解决此问题,请将 @generated_name 值更改为有效的标识符。

library test.good.fi0146;

type Device = table {
    1: kind flexible enum {
        DESKTOP = 1;
        PHONE = 2;
    };
};

type Input = table {
    1: kind @generated_name("input_kind") flexible enum {
        KEYBOARD = 1;
        MOUSE = 2;
    };
};

fi-0147:@available 缺少参数

如果您使用 @available 属性但未提供必要的参数,就会出现此错误。@available 至少需要 addeddeprecatedremoved 中的一个。

@available(added=1)
library test.bad.fi0147;

@available
type Foo = struct {};

如需解决此问题,请添加以下某个必需参数:

@available(added=1)
library test.good.fi0147;

@available(added=2)
type Foo = struct {};

如需了解详情,请参阅 FIDL 版本控制

fi-0148:备注但不弃用

如果您将 note 参数用于没有 deprecated 参数的 @available 属性,就会出现此错误。只有弃用了 note

@available(added=1, note="My note")
library test.bad.fi0148;

如需修正此错误,请移除备注:

@available(added=1)
library test.good.fi0148a;

或添加必要的 deprecated 通知:

@available(added=1, deprecated=2, note="Removed in 2; use X instead.")
library test.good.fi0148b;

如需了解详情,请参阅 FIDL 版本控制

fi-0149:平台不在库中

当您尝试在库声明上方以外的任何位置使用 @available 属性的 platform 参数时,就会出现此错误。platform 参数仅在 library 级别有效。

@available(added=1)
library test.bad.fi0149;

@available(platform="foo")
type Person = struct {
    name string;
};

如需解决此问题,请将 platform 参数移至库 @available 属性:

@available(added=1, platform="foo")
library test.good.fi0149a;

type Person = struct {
    name string;
};

或完全移除 platform 参数:

@available(added=1)
library test.good.fi0149b;

type Person = struct {
    name string;
};

fi-0150:添加了库可用性缺失信息

如果您在未提供 added 参数的情况下向库添加 @available 属性,就会出现此错误。library @available 属性需要 added 参数。

@available(removed=2)
library test.bad.fi0150a;
@available(platform="foo")
library test.bad.fi0150b;

如需解决此问题,请向库的 @available 属性添加 added 参数:

@available(added=1, removed=2)
library test.good.fi0150a;
@available(added=1, platform="foo")
library test.good.fi0150b;

fi-0151:缺少书库可用性

如果您在非 library 声明中添加了 @available 属性,但 library 声明中没有 @available 属性,就会出现此错误。

library test.bad.fi0151;

@available(added=1)
type Person = struct {
    name string;
};

如需修复此错误,请将 @available 属性添加到 library 声明中:

@available(added=1)
library test.good.fi0151a;

@available(added=1)
type Person = struct {
    name string;
};

或从非 library 声明中移除 @available 属性:

library test.good.fi0151b;

type Person = struct {
    name string;
};

fi-0152:平台无效

当您对 @available 属性的 platform 参数使用无效字符时,就会出现此错误。platform 参数必须是有效的 FIDL 库标识符

@available(added=1, platform="Spaces are not allowed")
library test.bad.fi0152;

如需修正此错误,请移除不允许使用的字符:

@available(added=1, platform="foo")
library test.good.fi0152;

fi-0153:版本无效

当您对 @available 属性中的 addedremoved 参数使用无效版本时,就会出现此错误。addedremoved 参数必须是 1 到 2^63-1 之间的正整数,或者是特殊常量 HEAD

@available(added=0)
library test.bad.fi0153;

如需解决此问题,请将版本更改为有效值:

@available(added=1)
library test.good.fi0153;

fi-0154:存货订单无效

当您为 @available 属性使用 addeddeprecatedremove 参数的错误组合时,就会出现此错误。必须遵循以下约束条件:

  • added必须小于或等于 deprecated
  • deprecated”必须小于 removed
  • added”必须小于 removed
@available(added=2, removed=2)
library test.bad.fi0154a;
@available(added=2, deprecated=3, removed=3)
library test.bad.fi0154b;

如需解决此问题,请将 addeddeprecatedremoved 参数更新为所需的顺序:

@available(added=1, removed=2)
library test.good.fi0154a;
@available(added=2, deprecated=2, removed=3)
library test.good.fi0154b;

fi-0155:可用性与父级冲突

在非 library 声明中添加 @availability 属性与 library 的声明冲突时,就会出现此错误。

@available(added=2, deprecated=3, removed=4)
library test.bad.fi0155a;

@available(added=1)
type Person = struct {
    name string;
};
@available(added=2, deprecated=3, removed=4)
library test.bad.fi0155b;

@available(added=4)
type Person = struct {
    name string;
};

如需修复此错误,请将 @availability 属性更新为必需的限制条件:

@available(added=2, deprecated=3, removed=4)
library test.good.fi0155;

@available(added=2)
type Person = struct {
    name string;
};

fi-0156:不能是可选项

当您尝试将某个类型标记为不可选时,就会出现此错误。

library test.bad.fi0156;

type Person = struct {
    name string;
    age int16:optional;
};

如需修正此错误,请移除可选的约束条件:

library test.good.fi0156;

type Person = struct {
    name string;
    age int16;
};

只有可设置为可选且不改变导线形状的 FIDL 类型才能使用 optional 约束条件。如需了解详情,请参阅可选指南或下面的可展开部分。

FIDL 配方:可选

某些 FIDL 类型可以设置为可选,添加 :optional 限制后,不更改其包含消息的线形。此外,table 布局始终是可选的,而 struct 布局从不。如需使 struct 成为可选,它必须封装在 box<T> 中,从而更改其包含消息的线形。

基本类型 可选版本 可选性是否会改变线路布局?
struct {...} box<struct {...}>
table {...} table {...} 不兼容
union {...} union {...}:optional 不兼容
vector<T> vector<T>:optional 不兼容
string string:optional 不兼容
zx.Handle zx.Handle:optional 不兼容
client_end:P client_end:<P, optional> 不兼容
server_end:P server_end:<P, optional> 不兼容

所有其他类型(bitsenumarray<T, N> 和基元类型)都不能设为可选类型。

在此变体中,我们允许键值对存储区将其他键值对存储区作为成员。简而言之,我们将其变成一棵树。为此,我们将 value 的原始定义替换为使用双成员 union 的定义:一个变体使用与之前相同的 vector<byte> 类型存储叶节点,而另一个变体以其他嵌套存储的形式存储分支节点。

推理

在这里,我们看到可选性的几种用途,我们可以借此声明一个可能存在或可能不存在的类型。FIDL 中有三种可选类型:

  • 始终在线在线存储的类型,因此有一种内置方式,通过 null 信封来描述“缺失”。为这些类型启用可选性不会影响包含它们的消息的传输形状,而只是更改该特定类型有效的值。通过添加 :optional 约束条件,unionvector<T>client_endserver_endzx.Handle 类型均可设为可选类型。通过将 value union 设为可选,我们能够采用不存在的 value 的形式引入规范的“null”条目。这意味着空 bytes 和缺失/空 store 属性都是无效值。
  • 与上述类型不同,struct 布局没有额外的空间可存储 null 标头。因此,需要将其封装在信封中,从而更改包含它的消息的线上形状。为了确保这种导线修改效果易于辨认,必须将 Item struct 类型封装在 box<T> 类型模板中。
  • 最后,table 布局始终是可选的。如果 table 不存在,则只是未设置任何成员的标识符。

树是一种天生的自引用数据结构:树中的任何节点都可能包含具有纯数据的叶(在本例中为字符串)或具有更多节点的子树。这需要递归:Item 的定义现在以传递方式依赖于其本身!在 FIDL 中表示递归类型可能有点复杂,尤其是因为目前对支持的内容有些有限。只要自引用创建的周期中至少有一个可选类型,我们就可以支持此类类型。例如,在这里,我们将 items struct 成员定义为 box<Item>,从而打破包含循环。

这些更改还大量使用了匿名类型(即声明内嵌在其单一使用点的类型),而不是被命名的顶级 type 声明。默认情况下,生成的语言绑定中的匿名类型名称取自其本地上下文。例如,新引入的 flexible union 将采用其自有成员的名称 Value,新引入的 struct 将变为 Store,依此类推。由于这种启发式方法有时可能会导致冲突,因此 FIDL 提供了应急方法,允许作者手动替换匿名类型的生成名称。这是通过 @generated_name 属性实现的,该属性可用于更改后端生成的名称。我们可以在这里使用一个示例,将原本的 Store 类型重命名为 NestedStore,以防止名称与使用相同名称的 protocol 声明发生名称冲突。

实现

FIDL、CML 和 Realm 接口定义修改如下:

FIDL

// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
library examples.keyvaluestore.supporttrees;

/// An item in the store. The key must match the regex `^[A-z][A-z0-9_\.\/]{2,62}[A-z0-9]$`. That
/// is, it must start with a letter, end with a letter or number, contain only letters, numbers,
/// periods, and slashes, and be between 4 and 64 characters long.
type Item = struct {
    key string:128;
    value strict union {
        // Keep the original `bytes` as one of the options in the new union. All leaf nodes in the
        // tree must be `bytes`, or absent unions (representing empty). Empty byte arrays are
        // disallowed.
        1: bytes vector<byte>:64000;

        // Allows a store within a store, thereby turning our flat key-value store into a tree
        // thereof. Note the use of `@generated_name` to prevent a type-name collision with the
        // `Store` protocol below, and the use of `box<T>` to ensure that there is a break in the
        // chain of recursion, thereby allowing `Item` to include itself in its own definition.
        //
        // This is a table so that added fields, like for example a `hash`, can be easily added in
        // the future.
        2: store @generated_name("nested_store") table {
            1: items vector<box<Item>>;
        };
    }:optional;
};

/// An enumeration of things that may go wrong when trying to write a value to our store.
type WriteError = flexible enum {
    UNKNOWN = 0;
    INVALID_KEY = 1;
    INVALID_VALUE = 2;
    ALREADY_EXISTS = 3;
};

/// A very basic key-value store.
@discoverable
open protocol Store {
    /// Writes an item to the store.
    flexible WriteItem(struct {
        attempt Item;
    }) -> () error WriteError;
};

全渠道营销 (CML)

客户端

// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
{
    include: [ "syslog/client.shard.cml" ],
    program: {
        runner: "elf",
        binary: "bin/client_bin",
    },
    use: [
        { protocol: "examples.keyvaluestore.supporttrees.Store" },
    ],
    config: {
        write_items: {
            type: "vector",
            max_count: 16,
            element: {
                type: "string",
                max_size: 64,
            },
        },

        // A newline separated list nested entries. The first line should be the key
        // for the nested store, and each subsequent entry should be a pointer to a text file
        // containing the string value. The name of that text file (without the `.txt` suffix) will
        // serve as the entries key.
        write_nested: {
            type: "vector",
            max_count: 16,
            element: {
                type: "string",
                max_size: 64,
            },
        },

        // A list of keys, all of which will be populated as null entries.
        write_null: {
            type: "vector",
            max_count: 16,
            element: {
                type: "string",
                max_size: 64,
            },
        },

    },
}

服务器

// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
{
    include: [ "syslog/client.shard.cml" ],
    program: {
        runner: "elf",
        binary: "bin/server_bin",
    },
    capabilities: [
        { protocol: "examples.keyvaluestore.supporttrees.Store" },
    ],
    expose: [
        {
            protocol: "examples.keyvaluestore.supporttrees.Store",
            from: "self",
        },
    ],
}

领域

// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
{
    children: [
        {
            name: "client",
            url: "#meta/client.cm",
        },
        {
            name: "server",
            url: "#meta/server.cm",
        },
    ],
    offer: [
        // Route the protocol under test from the server to the client.
        {
            protocol: "examples.keyvaluestore.supporttrees.Store",
            from: "#server",
            to: "#client",
        },

        // Route diagnostics support to all children.
        {
            protocol: [
                "fuchsia.inspect.InspectSink",
                "fuchsia.logger.LogSink",
            ],
            from: "parent",
            to: [
                "#client",
                "#server",
            ],
        },
    ],
}

然后,可以使用任何支持的语言编写客户端和服务器实现:

Rust

客户端

// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use {
    anyhow::{Context as _, Error},
    config::Config,
    fidl_examples_keyvaluestore_supporttrees::{Item, NestedStore, StoreMarker, Value},
    fuchsia_component::client::connect_to_protocol,
    std::{thread, time},
};

#[fuchsia::main]
async fn main() -> Result<(), Error> {
    println!("Started");

    // Load the structured config values passed to this component at startup.
    let config = Config::take_from_startup_handle();

    // Use the Component Framework runtime to connect to the newly spun up server component. We wrap
    // our retained client end in a proxy object that lets us asynchronously send `Store` requests
    // across the channel.
    let store = connect_to_protocol::<StoreMarker>()?;
    println!("Outgoing connection enabled");

    // This client's structured config has one parameter, a vector of strings. Each string is the
    // path to a resource file whose filename is a key and whose contents are a value. We iterate
    // over them and try to write each key-value pair to the remote store.
    for key in config.write_items.into_iter() {
        let path = format!("/pkg/data/{}.txt", key);
        let value = std::fs::read_to_string(path.clone())
            .with_context(|| format!("Failed to load {path}"))?;
        let res = store
            .write_item(&Item {
                key: key.clone(),
                value: Some(Box::new(Value::Bytes(value.into_bytes()))),
            })
            .await;
        match res? {
            Ok(_) => println!("WriteItem Success at key: {}", key),
            Err(err) => println!("WriteItem Error: {}", err.into_primitive()),
        }
    }

    // Add nested entries to the key-value store as well. The entries are strings, where the first
    // line is the key of the entry, and each subsequent entry should be a pointer to a text file
    // containing the string value. The name of that text file (without the `.txt` suffix) will
    // serve as the entries key.
    for spec in config.write_nested.into_iter() {
        let mut items = vec![];
        let mut nested_store = NestedStore::default();
        let mut lines = spec.split("\n");
        let key = lines.next().unwrap();

        // For each entry, make a new entry in the `NestedStore` being built.
        for entry in lines {
            let path = format!("/pkg/data/{}.txt", entry);
            let contents = std::fs::read_to_string(path.clone())
                .with_context(|| format!("Failed to load {path}"))?;
            items.push(Some(Box::new(Item {
                key: entry.to_string(),
                value: Some(Box::new(Value::Bytes(contents.into()))),
            })));
        }
        nested_store.items = Some(items);

        // Send the `NestedStore`, represented as a vector of values.
        let res = store
            .write_item(&Item {
                key: key.to_string(),
                value: Some(Box::new(Value::Store(nested_store))),
            })
            .await;
        match res? {
            Ok(_) => println!("WriteItem Success at key: {}", key),
            Err(err) => println!("WriteItem Error: {}", err.into_primitive()),
        }
    }

    // Each entry in this list is a null value in the store.
    for key in config.write_null.into_iter() {
        match store.write_item(&Item { key: key.to_string(), value: None }).await? {
            Ok(_) => println!("WriteItem Success at key: {}", key),
            Err(err) => println!("WriteItem Error: {}", err.into_primitive()),
        }
    }

    // TODO(https://fxbug.dev/42156498): We need to sleep here to make sure all logs get drained. Once the
    // referenced bug has been resolved, we can remove the sleep.
    thread::sleep(time::Duration::from_secs(2));
    Ok(())
}

服务器

// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use {
    anyhow::{Context as _, Error},
    fidl_examples_keyvaluestore_supporttrees::{
        Item, StoreRequest, StoreRequestStream, Value, WriteError,
    },
    fuchsia_component::server::ServiceFs,
    futures::prelude::*,
    lazy_static::lazy_static,
    regex::Regex,
    std::cell::RefCell,
    std::collections::hash_map::Entry,
    std::collections::HashMap,
    std::str::from_utf8,
};

lazy_static! {
    static ref KEY_VALIDATION_REGEX: Regex =
        Regex::new(r"^[A-Za-z]\w+[A-Za-z0-9]$").expect("Key validation regex failed to compile");
}

// A representation of a key-value store that can contain an arbitrarily deep nesting of other
// key-value stores.
#[allow(dead_code)] // TODO(https://fxbug.dev/318827209)
enum StoreNode {
    Leaf(Option<Vec<u8>>),
    Branch(Box<HashMap<String, StoreNode>>),
}

/// Recursive item writer, which takes a `StoreNode` that may not necessarily be the root node, and
/// writes an entry to it.
fn write_item(
    store: &mut HashMap<String, StoreNode>,
    attempt: Item,
    path: &str,
) -> Result<(), WriteError> {
    // Validate the key.
    if !KEY_VALIDATION_REGEX.is_match(attempt.key.as_str()) {
        println!("Write error: INVALID_KEY, For key: {}", attempt.key);
        return Err(WriteError::InvalidKey);
    }

    // Write to the store, validating that the key did not already exist.
    match store.entry(attempt.key) {
        Entry::Occupied(entry) => {
            println!("Write error: ALREADY_EXISTS, For key: {}", entry.key());
            Err(WriteError::AlreadyExists)
        }
        Entry::Vacant(entry) => {
            let key = format!("{}{}", &path, entry.key());
            match attempt.value {
                // Null entries are allowed.
                None => {
                    println!("Wrote value: NONE at key: {}", key);
                    entry.insert(StoreNode::Leaf(None));
                }
                Some(value) => match *value {
                    // If this is a nested store, recursively make a new store to insert at this
                    // position.
                    Value::Store(entry_list) => {
                        // Validate the value - absent stores, items lists with no children, or any
                        // of the elements within that list being empty boxes, are all not allowed.
                        if entry_list.items.is_some() {
                            let items = entry_list.items.unwrap();
                            if !items.is_empty() && items.iter().all(|i| i.is_some()) {
                                let nested_path = format!("{}/", key);
                                let mut nested_store = HashMap::<String, StoreNode>::new();
                                for item in items.into_iter() {
                                    write_item(&mut nested_store, *item.unwrap(), &nested_path)?;
                                }

                                println!("Created branch at key: {}", key);
                                entry.insert(StoreNode::Branch(Box::new(nested_store)));
                                return Ok(());
                            }
                        }

                        println!("Write error: INVALID_VALUE, For key: {}", key);
                        return Err(WriteError::InvalidValue);
                    }

                    // This is a simple leaf node on this branch.
                    Value::Bytes(value) => {
                        // Validate the value.
                        if value.is_empty() {
                            println!("Write error: INVALID_VALUE, For key: {}", key);
                            return Err(WriteError::InvalidValue);
                        }

                        println!("Wrote key: {}, value: {:?}", key, from_utf8(&value).unwrap());
                        entry.insert(StoreNode::Leaf(Some(value)));
                    }
                },
            }
            Ok(())
        }
    }
}

/// Creates a new instance of the server. Each server has its own bespoke, per-connection instance
/// of the key-value store.
async fn run_server(stream: StoreRequestStream) -> Result<(), Error> {
    // Create a new in-memory key-value store. The store will live for the lifetime of the
    // connection between the server and this particular client.
    let store = RefCell::new(HashMap::<String, StoreNode>::new());

    // Serve all requests on the protocol sequentially - a new request is not handled until its
    // predecessor has been processed.
    stream
        .map(|result| result.context("failed request"))
        .try_for_each(|request| async {
            // Match based on the method being invoked.
            match request {
                StoreRequest::WriteItem { attempt, responder } => {
                    println!("WriteItem request received");

                    // The `responder` parameter is a special struct that manages the outgoing reply
                    // to this method call. Calling `send` on the responder exactly once will send
                    // the reply.
                    responder
                        .send(write_item(&mut store.borrow_mut(), attempt, ""))
                        .context("error sending reply")?;
                    println!("WriteItem response sent");
                }
                StoreRequest::_UnknownMethod { ordinal, .. } => {
                    println!("Received an unknown method with ordinal {ordinal}");
                }
            }
            Ok(())
        })
        .await
}

// A helper enum that allows us to treat a `Store` service instance as a value.
enum IncomingService {
    Store(StoreRequestStream),
}

#[fuchsia::main]
async fn main() -> Result<(), Error> {
    println!("Started");

    // Add a discoverable instance of our `Store` protocol - this will allow the client to see the
    // server and connect to it.
    let mut fs = ServiceFs::new_local();
    fs.dir("svc").add_fidl_service(IncomingService::Store);
    fs.take_and_serve_directory_handle()?;
    println!("Listening for incoming connections");

    // The maximum number of concurrent clients that may be served by this process.
    const MAX_CONCURRENT: usize = 10;

    // Serve each connection simultaneously, up to the `MAX_CONCURRENT` limit.
    fs.for_each_concurrent(MAX_CONCURRENT, |IncomingService::Store(stream)| {
        run_server(stream).unwrap_or_else(|e| println!("{:?}", e))
    })
    .await;

    Ok(())
}

C++(自然)

客户端

// TODO(https://fxbug.dev/42060656): C++ (Natural) implementation.

服务器

// TODO(https://fxbug.dev/42060656): C++ (Natural) implementation.

C++(有线)

客户端

// TODO(https://fxbug.dev/42060656): C++ (Wire) implementation.

服务器

// TODO(https://fxbug.dev/42060656): C++ (Wire) implementation.

HLCPP

客户端

// TODO(https://fxbug.dev/42060656): HLCPP implementation.

服务器

// TODO(https://fxbug.dev/42060656): HLCPP implementation.

fi-0157:客户端/服务器端约束条件必须是协议

应用于 client_endserver_end 的第一个限制条件必须指向 protocol 定义:

library test.bad.fi0157;

type MyStruct = struct {};
alias ServerEnd = server_end:MyStruct;

将限制条件更改为指向协议:

library test.good.fi0157;

protocol MyProtocol {};
alias ServerEnd = server_end:MyProtocol;

fi-0158:不能绑定两次

alias 声明无法更改其别名类型上已设置的约束条件的值:

library test.bad.fi0158;

alias ByteVec256 = vector<uint8>:256;
alias ByteVec512 = ByteVec256:512;

相反,无界限定义应接收自己的 alias 声明,每个进一步受限的别名应继而从其继承:

library test.good.fi0158;

alias AliasOfVectorOfString = vector<string>;
alias AliasOfVectorOfStringSmall = AliasOfVectorOfString:8;
alias AliasOfVectorOfStringLarge = AliasOfVectorOfString:16;

这种做法是不允许的,以避免混淆,并避免编译器实现复杂性。

fi-0159:结构体不能是可选结构

结构体不能包含 optional 限制条件:

library test.bad.fi0159;

type Date = struct {
    year uint16;
    month uint8;
    day uint8;
};

type Person = struct {
    name string;
    birthday Date:optional;
};

T:optional 更改为 box<T> 以解决此问题:

library test.good.fi0159;

type Date = struct {
    year uint16;
    month uint8;
    day uint8;
};

type Person = struct {
    name string;
    birthday box<Date>;
};

只有可设置为可选且不改变导线形状的 FIDL 类型才能使用 optional 约束条件。如需了解详情,请参阅可选指南。

fi-0160:类型不能两次标记为可选项

当某个类型被设为可选项两次时,就会出现此错误。通常,如果类型在其使用和声明网站上均被标记为“可选项”,就会发生这种情况。

library test.bad.fi0160;

alias MyAlias = vector<string>:optional;

type MyStruct = struct {
    my_member MyAlias:optional;
};

要修复此错误,请仅将类型设为可选属性一次。

例如,您可以从使用网站中移除 :optional

library test.good.fi0160a;

alias MyAlias = vector<string>:optional;

type MyStruct = struct {
    my_member MyAlias;
};

您还可以从别名声明中移除 :optional

library test.good.fi0160b;

alias MyAlias = vector<string>;

type MyStruct = struct {
    my_member MyAlias:optional;
};

fi-0161:大小不得为零

当您尝试将数组大小限制设置为 0 时,就会出现此错误。数组的大小不能为零。

library test.bad.fi0161;

type Person = struct {
    name string;
    nicknames array<string, 0>;
};

如需修正此错误,请将大小限制更改为正整数。

library test.good.fi0161;

type Person = struct {
    name string;
    nicknames array<string, 5>;
};

fi-0162:布局参数数错误

某些 FIDL 布局(如 vectorarray)接受参数。此错误表示突出显示的类型指定的参数数量不正确:

library test.bad.fi0162a;

type Foo = struct {
    bar array<8>;
};

如果不可参数类型错误地附加了参数,也会出现此错误:

library test.bad.fi0162b;

type Foo = struct {
    bar uint8<8>;
};

解决方法始终是为相关布局指定正确数量的参数:

library test.good.fi0162;

type Foo = struct {
    bar array<uint8, 8>;
};

FIDL 中唯一的参数化类型是 array<T, N>box<T>vector<T>client_endserver_end 类型过去在旧版 FIDL 语法中会被参数化,但现在不同了,尽管这种情况经常发生,导致出现此错误。这两种类型现在将其协议规范作为(必需)约束条件。

参数始终列在尖括号 <...> 内,与约束条件(位于类型末尾的 :... 字符后面)有一些类似。例如,乍一看,array<T, N> 以参数形式指定其大小,而 vector<T>:N 以约束条件指定其大小,这似乎很奇怪。不同之处在于参数始终会影响相关类型的线路布局形状,而约束条件只是改变该类型的编码/解码时被视为可接受的值集,而对线路布局没有影响。

如需更全面地讨论这两个概念之间的区别,请参阅 RFC-0050:FIDL 语法修订

fi-0163:多个约束条件定义

当您尝试使用多个英文冒号 (:) 定义多个限制条件定义时,就会出现此错误。多个限制条件定义必须使用尖括号语法 type:<constraint1, constraint2, etc>

library test.bad.fi0163;

type Person = struct {
  name string;
  favorite_color string:30:optional;
};

如需修复此错误,请为约束条件使用尖括号语法:

library test.good.fi0163;

type Person = struct {
    name string;
    favorite_color string:<30, optional>;
};

fi-0164:约束条件过多

当您尝试向某个类型添加超出支持的限制条件数量时,就会出现此错误。例如,string 最多支持两个约束条件。

library test.bad.fi0164;

type Person = struct {
    name string:<0, optional, 20>;
};

如需解决此问题,请移除额外的约束条件:

library test.good.fi0164;

type Person = struct {
    name string:<20, optional>;
};

fi-0165:预期类型

如果您在 FIDL 需要类型时使用常量或协议标识符,就会出现此错误。

library test.bad.fi0165;

type Person = struct {
    name string;
    nicknames vector<5>;
};

如需修复此错误,请更新您的代码以使用有效的类型:

library test.good.fi0165;

type Person = struct {
    name string;
    nicknames vector<string>:5;
};

协议不属于 FIDL 类型,也无法在需要类型时使用。

fi-0166:意外约束条件

当您试图使用不符合预期的限制条件时,就会出现此错误。这通常是因为已命名的 const 位置有误。

library test.bad.fi0166;

const MIN_SIZE uint8 = 1;
const MAX_SIZE uint8 = 5;

type Person = struct {
    name string;
    nicknames vector<string>:<MIN_SIZE, MAX_SIZE>;
};

如需修复此错误,请移除此约束条件:

library test.good.fi0166;

const MAX_SIZE uint8 = 5;

type Person = struct {
    name string;
    nicknames vector<string>:<MAX_SIZE>;
};

fi-0167:不能限制两次

对于已通过 alias 声明定义了传输边界的 client_endserver_end,禁止为其重新分配传输边界:

library test.bad.fi0167;

protocol MyOtherProtocol {};

alias ClientEnd = client_end:MyProtocol;
alias ServerEnd = server_end:MyProtocol;

protocol MyProtocol {
    MyMethod(resource struct {
        my_client ClientEnd:MyOtherProtocol;
    }) -> (resource struct {
        my_server ServerEnd:MyOtherProtocol;
    });
};

应完全避免 client_endserver_end 类型的别名:

library test.good.fi0167;

protocol MyProtocol {
    MyMethod(resource struct {
        my_client client_end:MyProtocol;
    }) -> (resource struct {
        my_server server_end:MyProtocol;
    });
};

这种做法是不允许的,以避免混淆,并避免编译器实现复杂性。

fi-0168:客户端/服务器端必须具有协议约束条件

应用于 client_endserver_end 的第一个限制条件必须指向 protocol 定义:

library test.bad.fi0168;

protocol MyProtocol {
    MyMethod(resource struct {
        server server_end;
    });
};

添加指向所需协议的限制条件:

library test.good.fi0168;

protocol MyProtocol {
    MyMethod(resource struct {
        server server_end:MyProtocol;
    });
};

fi-0169:盒装类型不能可选

无法对 box<T> 形式的类型应用 optional 约束条件:

library test.bad.fi0169;

type Color = struct {
    red byte;
    green byte;
    blue byte;
};

type MyStruct = struct {
    maybe_color box<Color>:optional;
};

根据定义,盒装类型是可选的,因此添加额外的限制条件没有必要而且是多余的:

library test.good.fi0169;

type Color = struct {
    red byte;
    green byte;
    blue byte;
};

type MyStruct = struct {
    maybe_color box<Color>;
};

fi-0170

fi-0171:盒装类型应使用可选的约束条件

只有使用 struct 布局的类型才能进行封装;unionvectorstringclient_endserver_endzx.Handle 必须改用 optional 约束条件:

library test.bad.fi0171;

using zx;

type MyStruct = resource struct {
    my_resource_member box<zx.Handle>;
};

box<T> 转换为 T:optional 以解决此问题:

library test.good.fi0171;

using zx;

type MyStruct = resource struct {
    my_resource_member zx.Handle:optional;
};

只有可设置为可选且不改变导线形状的 FIDL 类型才能使用 optional 约束条件。如需了解详情,请参阅可选指南或下面的可展开部分。

FIDL 配方:可选

某些 FIDL 类型可以设置为可选,添加 :optional 限制后,不更改其包含消息的线形。此外,table 布局始终是可选的,而 struct 布局从不。如需使 struct 成为可选,它必须封装在 box<T> 中,从而更改其包含消息的线形。

基本类型 可选版本 可选性是否会改变线路布局?
struct {...} box<struct {...}>
table {...} table {...} 不兼容
union {...} union {...}:optional 不兼容
vector<T> vector<T>:optional 不兼容
string string:optional 不兼容
zx.Handle zx.Handle:optional 不兼容
client_end:P client_end:<P, optional> 不兼容
server_end:P server_end:<P, optional> 不兼容

所有其他类型(bitsenumarray<T, N> 和基元类型)都不能设为可选类型。

在此变体中,我们允许键值对存储区将其他键值对存储区作为成员。简而言之,我们将其变成一棵树。为此,我们将 value 的原始定义替换为使用双成员 union 的定义:一个变体使用与之前相同的 vector<byte> 类型存储叶节点,而另一个变体以其他嵌套存储的形式存储分支节点。

推理

在这里,我们看到可选性的几种用途,我们可以借此声明一个可能存在或可能不存在的类型。FIDL 中有三种可选类型:

  • 始终在线在线存储的类型,因此有一种内置方式,通过 null 信封来描述“缺失”。为这些类型启用可选性不会影响包含它们的消息的传输形状,而只是更改该特定类型有效的值。通过添加 :optional 约束条件,unionvector<T>client_endserver_endzx.Handle 类型均可设为可选类型。通过将 value union 设为可选,我们能够采用不存在的 value 的形式引入规范的“null”条目。这意味着空 bytes 和缺失/空 store 属性都是无效值。
  • 与上述类型不同,struct 布局没有额外的空间可存储 null 标头。因此,需要将其封装在信封中,从而更改包含它的消息的线上形状。为了确保这种导线修改效果易于辨认,必须将 Item struct 类型封装在 box<T> 类型模板中。
  • 最后,table 布局始终是可选的。如果 table 不存在,则只是未设置任何成员的标识符。

树是一种天生的自引用数据结构:树中的任何节点都可能包含具有纯数据的叶(在本例中为字符串)或具有更多节点的子树。这需要递归:Item 的定义现在以传递方式依赖于其本身!在 FIDL 中表示递归类型可能有点复杂,尤其是因为目前对支持的内容有些有限。只要自引用创建的周期中至少有一个可选类型,我们就可以支持此类类型。例如,在这里,我们将 items struct 成员定义为 box<Item>,从而打破包含循环。

这些更改还大量使用了匿名类型(即声明内嵌在其单一使用点的类型),而不是被命名的顶级 type 声明。默认情况下,生成的语言绑定中的匿名类型名称取自其本地上下文。例如,新引入的 flexible union 将采用其自有成员的名称 Value,新引入的 struct 将变为 Store,依此类推。由于这种启发式方法有时可能会导致冲突,因此 FIDL 提供了应急方法,允许作者手动替换匿名类型的生成名称。这是通过 @generated_name 属性实现的,该属性可用于更改后端生成的名称。我们可以在这里使用一个示例,将原本的 Store 类型重命名为 NestedStore,以防止名称与使用相同名称的 protocol 声明发生名称冲突。

实现

FIDL、CML 和 Realm 接口定义修改如下:

FIDL

// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
library examples.keyvaluestore.supporttrees;

/// An item in the store. The key must match the regex `^[A-z][A-z0-9_\.\/]{2,62}[A-z0-9]$`. That
/// is, it must start with a letter, end with a letter or number, contain only letters, numbers,
/// periods, and slashes, and be between 4 and 64 characters long.
type Item = struct {
    key string:128;
    value strict union {
        // Keep the original `bytes` as one of the options in the new union. All leaf nodes in the
        // tree must be `bytes`, or absent unions (representing empty). Empty byte arrays are
        // disallowed.
        1: bytes vector<byte>:64000;

        // Allows a store within a store, thereby turning our flat key-value store into a tree
        // thereof. Note the use of `@generated_name` to prevent a type-name collision with the
        // `Store` protocol below, and the use of `box<T>` to ensure that there is a break in the
        // chain of recursion, thereby allowing `Item` to include itself in its own definition.
        //
        // This is a table so that added fields, like for example a `hash`, can be easily added in
        // the future.
        2: store @generated_name("nested_store") table {
            1: items vector<box<Item>>;
        };
    }:optional;
};

/// An enumeration of things that may go wrong when trying to write a value to our store.
type WriteError = flexible enum {
    UNKNOWN = 0;
    INVALID_KEY = 1;
    INVALID_VALUE = 2;
    ALREADY_EXISTS = 3;
};

/// A very basic key-value store.
@discoverable
open protocol Store {
    /// Writes an item to the store.
    flexible WriteItem(struct {
        attempt Item;
    }) -> () error WriteError;
};

全渠道营销 (CML)

客户端

// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
{
    include: [ "syslog/client.shard.cml" ],
    program: {
        runner: "elf",
        binary: "bin/client_bin",
    },
    use: [
        { protocol: "examples.keyvaluestore.supporttrees.Store" },
    ],
    config: {
        write_items: {
            type: "vector",
            max_count: 16,
            element: {
                type: "string",
                max_size: 64,
            },
        },

        // A newline separated list nested entries. The first line should be the key
        // for the nested store, and each subsequent entry should be a pointer to a text file
        // containing the string value. The name of that text file (without the `.txt` suffix) will
        // serve as the entries key.
        write_nested: {
            type: "vector",
            max_count: 16,
            element: {
                type: "string",
                max_size: 64,
            },
        },

        // A list of keys, all of which will be populated as null entries.
        write_null: {
            type: "vector",
            max_count: 16,
            element: {
                type: "string",
                max_size: 64,
            },
        },

    },
}

服务器

// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
{
    include: [ "syslog/client.shard.cml" ],
    program: {
        runner: "elf",
        binary: "bin/server_bin",
    },
    capabilities: [
        { protocol: "examples.keyvaluestore.supporttrees.Store" },
    ],
    expose: [
        {
            protocol: "examples.keyvaluestore.supporttrees.Store",
            from: "self",
        },
    ],
}

领域

// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
{
    children: [
        {
            name: "client",
            url: "#meta/client.cm",
        },
        {
            name: "server",
            url: "#meta/server.cm",
        },
    ],
    offer: [
        // Route the protocol under test from the server to the client.
        {
            protocol: "examples.keyvaluestore.supporttrees.Store",
            from: "#server",
            to: "#client",
        },

        // Route diagnostics support to all children.
        {
            protocol: [
                "fuchsia.inspect.InspectSink",
                "fuchsia.logger.LogSink",
            ],
            from: "parent",
            to: [
                "#client",
                "#server",
            ],
        },
    ],
}

然后,可以使用任何支持的语言编写客户端和服务器实现:

Rust

客户端

// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use {
    anyhow::{Context as _, Error},
    config::Config,
    fidl_examples_keyvaluestore_supporttrees::{Item, NestedStore, StoreMarker, Value},
    fuchsia_component::client::connect_to_protocol,
    std::{thread, time},
};

#[fuchsia::main]
async fn main() -> Result<(), Error> {
    println!("Started");

    // Load the structured config values passed to this component at startup.
    let config = Config::take_from_startup_handle();

    // Use the Component Framework runtime to connect to the newly spun up server component. We wrap
    // our retained client end in a proxy object that lets us asynchronously send `Store` requests
    // across the channel.
    let store = connect_to_protocol::<StoreMarker>()?;
    println!("Outgoing connection enabled");

    // This client's structured config has one parameter, a vector of strings. Each string is the
    // path to a resource file whose filename is a key and whose contents are a value. We iterate
    // over them and try to write each key-value pair to the remote store.
    for key in config.write_items.into_iter() {
        let path = format!("/pkg/data/{}.txt", key);
        let value = std::fs::read_to_string(path.clone())
            .with_context(|| format!("Failed to load {path}"))?;
        let res = store
            .write_item(&Item {
                key: key.clone(),
                value: Some(Box::new(Value::Bytes(value.into_bytes()))),
            })
            .await;
        match res? {
            Ok(_) => println!("WriteItem Success at key: {}", key),
            Err(err) => println!("WriteItem Error: {}", err.into_primitive()),
        }
    }

    // Add nested entries to the key-value store as well. The entries are strings, where the first
    // line is the key of the entry, and each subsequent entry should be a pointer to a text file
    // containing the string value. The name of that text file (without the `.txt` suffix) will
    // serve as the entries key.
    for spec in config.write_nested.into_iter() {
        let mut items = vec![];
        let mut nested_store = NestedStore::default();
        let mut lines = spec.split("\n");
        let key = lines.next().unwrap();

        // For each entry, make a new entry in the `NestedStore` being built.
        for entry in lines {
            let path = format!("/pkg/data/{}.txt", entry);
            let contents = std::fs::read_to_string(path.clone())
                .with_context(|| format!("Failed to load {path}"))?;
            items.push(Some(Box::new(Item {
                key: entry.to_string(),
                value: Some(Box::new(Value::Bytes(contents.into()))),
            })));
        }
        nested_store.items = Some(items);

        // Send the `NestedStore`, represented as a vector of values.
        let res = store
            .write_item(&Item {
                key: key.to_string(),
                value: Some(Box::new(Value::Store(nested_store))),
            })
            .await;
        match res? {
            Ok(_) => println!("WriteItem Success at key: {}", key),
            Err(err) => println!("WriteItem Error: {}", err.into_primitive()),
        }
    }

    // Each entry in this list is a null value in the store.
    for key in config.write_null.into_iter() {
        match store.write_item(&Item { key: key.to_string(), value: None }).await? {
            Ok(_) => println!("WriteItem Success at key: {}", key),
            Err(err) => println!("WriteItem Error: {}", err.into_primitive()),
        }
    }

    // TODO(https://fxbug.dev/42156498): We need to sleep here to make sure all logs get drained. Once the
    // referenced bug has been resolved, we can remove the sleep.
    thread::sleep(time::Duration::from_secs(2));
    Ok(())
}

服务器

// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use {
    anyhow::{Context as _, Error},
    fidl_examples_keyvaluestore_supporttrees::{
        Item, StoreRequest, StoreRequestStream, Value, WriteError,
    },
    fuchsia_component::server::ServiceFs,
    futures::prelude::*,
    lazy_static::lazy_static,
    regex::Regex,
    std::cell::RefCell,
    std::collections::hash_map::Entry,
    std::collections::HashMap,
    std::str::from_utf8,
};

lazy_static! {
    static ref KEY_VALIDATION_REGEX: Regex =
        Regex::new(r"^[A-Za-z]\w+[A-Za-z0-9]$").expect("Key validation regex failed to compile");
}

// A representation of a key-value store that can contain an arbitrarily deep nesting of other
// key-value stores.
#[allow(dead_code)] // TODO(https://fxbug.dev/318827209)
enum StoreNode {
    Leaf(Option<Vec<u8>>),
    Branch(Box<HashMap<String, StoreNode>>),
}

/// Recursive item writer, which takes a `StoreNode` that may not necessarily be the root node, and
/// writes an entry to it.
fn write_item(
    store: &mut HashMap<String, StoreNode>,
    attempt: Item,
    path: &str,
) -> Result<(), WriteError> {
    // Validate the key.
    if !KEY_VALIDATION_REGEX.is_match(attempt.key.as_str()) {
        println!("Write error: INVALID_KEY, For key: {}", attempt.key);
        return Err(WriteError::InvalidKey);
    }

    // Write to the store, validating that the key did not already exist.
    match store.entry(attempt.key) {
        Entry::Occupied(entry) => {
            println!("Write error: ALREADY_EXISTS, For key: {}", entry.key());
            Err(WriteError::AlreadyExists)
        }
        Entry::Vacant(entry) => {
            let key = format!("{}{}", &path, entry.key());
            match attempt.value {
                // Null entries are allowed.
                None => {
                    println!("Wrote value: NONE at key: {}", key);
                    entry.insert(StoreNode::Leaf(None));
                }
                Some(value) => match *value {
                    // If this is a nested store, recursively make a new store to insert at this
                    // position.
                    Value::Store(entry_list) => {
                        // Validate the value - absent stores, items lists with no children, or any
                        // of the elements within that list being empty boxes, are all not allowed.
                        if entry_list.items.is_some() {
                            let items = entry_list.items.unwrap();
                            if !items.is_empty() && items.iter().all(|i| i.is_some()) {
                                let nested_path = format!("{}/", key);
                                let mut nested_store = HashMap::<String, StoreNode>::new();
                                for item in items.into_iter() {
                                    write_item(&mut nested_store, *item.unwrap(), &nested_path)?;
                                }

                                println!("Created branch at key: {}", key);
                                entry.insert(StoreNode::Branch(Box::new(nested_store)));
                                return Ok(());
                            }
                        }

                        println!("Write error: INVALID_VALUE, For key: {}", key);
                        return Err(WriteError::InvalidValue);
                    }

                    // This is a simple leaf node on this branch.
                    Value::Bytes(value) => {
                        // Validate the value.
                        if value.is_empty() {
                            println!("Write error: INVALID_VALUE, For key: {}", key);
                            return Err(WriteError::InvalidValue);
                        }

                        println!("Wrote key: {}, value: {:?}", key, from_utf8(&value).unwrap());
                        entry.insert(StoreNode::Leaf(Some(value)));
                    }
                },
            }
            Ok(())
        }
    }
}

/// Creates a new instance of the server. Each server has its own bespoke, per-connection instance
/// of the key-value store.
async fn run_server(stream: StoreRequestStream) -> Result<(), Error> {
    // Create a new in-memory key-value store. The store will live for the lifetime of the
    // connection between the server and this particular client.
    let store = RefCell::new(HashMap::<String, StoreNode>::new());

    // Serve all requests on the protocol sequentially - a new request is not handled until its
    // predecessor has been processed.
    stream
        .map(|result| result.context("failed request"))
        .try_for_each(|request| async {
            // Match based on the method being invoked.
            match request {
                StoreRequest::WriteItem { attempt, responder } => {
                    println!("WriteItem request received");

                    // The `responder` parameter is a special struct that manages the outgoing reply
                    // to this method call. Calling `send` on the responder exactly once will send
                    // the reply.
                    responder
                        .send(write_item(&mut store.borrow_mut(), attempt, ""))
                        .context("error sending reply")?;
                    println!("WriteItem response sent");
                }
                StoreRequest::_UnknownMethod { ordinal, .. } => {
                    println!("Received an unknown method with ordinal {ordinal}");
                }
            }
            Ok(())
        })
        .await
}

// A helper enum that allows us to treat a `Store` service instance as a value.
enum IncomingService {
    Store(StoreRequestStream),
}

#[fuchsia::main]
async fn main() -> Result<(), Error> {
    println!("Started");

    // Add a discoverable instance of our `Store` protocol - this will allow the client to see the
    // server and connect to it.
    let mut fs = ServiceFs::new_local();
    fs.dir("svc").add_fidl_service(IncomingService::Store);
    fs.take_and_serve_directory_handle()?;
    println!("Listening for incoming connections");

    // The maximum number of concurrent clients that may be served by this process.
    const MAX_CONCURRENT: usize = 10;

    // Serve each connection simultaneously, up to the `MAX_CONCURRENT` limit.
    fs.for_each_concurrent(MAX_CONCURRENT, |IncomingService::Store(stream)| {
        run_server(stream).unwrap_or_else(|e| println!("{:?}", e))
    })
    .await;

    Ok(())
}

C++(自然)

客户端

// TODO(https://fxbug.dev/42060656): C++ (Natural) implementation.

服务器

// TODO(https://fxbug.dev/42060656): C++ (Natural) implementation.

C++(有线)

客户端

// TODO(https://fxbug.dev/42060656): C++ (Wire) implementation.

服务器

// TODO(https://fxbug.dev/42060656): C++ (Wire) implementation.

HLCPP

客户端

// TODO(https://fxbug.dev/42060656): HLCPP implementation.

服务器

// TODO(https://fxbug.dev/42060656): HLCPP implementation.

fi-0172:资源定义必须使用 uint32 子类型

resource_definition 声明的子类型必须是 uint32

library test.bad.fi0172;

type MySubtype = strict enum : uint32 {
    NONE = 0;
};

resource_definition MyResource : uint8 {
    properties {
        subtype MySubtype;
    };
};

将子类型更改为 uint32 以修复此错误:

library test.good.fi0172;

type MySubtype = strict enum : uint32 {
    NONE = 0;
};

resource_definition MyResource : uint32 {
    properties {
        subtype MySubtype;
    };
};

这是一个与 FIDL 的内部实现相关的错误,因此只应向处理 FIDL 核心库的开发者公开。最终用户绝不会看到此错误。

它所引用的 resource_definition 声明是 FIDL 用于定义句柄等资源的内部方法,将来可能会作为处理程序泛化工作的一部分而发生变化。

fi-0173:资源定义必须指定子类型

resource_definition 声明不能省略 subtype 成员:

library test.bad.fi0173;

resource_definition MyResource : uint32 {
    properties {
        rights uint32;
    };
};

将此成员指向有效的 enum : uint32 声明:

library test.good.fi0173;

resource_definition MyResource : uint32 {
    properties {
        subtype flexible enum : uint32 {};
        rights uint32;
    };
};

这是一个与 FIDL 的内部实现相关的错误,因此只应向处理 FIDL 核心库的开发者公开。最终用户绝不会看到此错误。

它所引用的 resource_definition 声明是 FIDL 用于定义句柄等资源的内部方法,将来可能会作为处理程序泛化工作的一部分而发生变化。

fi-0174

fi-0175:资源定义子类型属性必须引用枚举

resource_definition 声明不能将非 enum 用作 subtype 成员:

library test.bad.fi0175;

resource_definition MyResource : uint32 {
    properties {
        subtype struct {};
    };
};

将此成员指向有效的 enum : uint32 声明:

library test.good.fi0175;

resource_definition MyResource : uint32 {
    properties {
        subtype flexible enum : uint32 {};
    };
};

这是一个与 FIDL 的内部实现相关的错误,因此只应向处理 FIDL 核心库的开发者公开。最终用户绝不会看到此错误。

它所引用的 resource_definition 声明是 FIDL 用于定义句柄等资源的内部方法,将来可能会作为处理程序泛化工作的一部分而发生变化。

fi-0176

fi-0177:资源定义权利属性必须引用位

resource_definition 声明不能将非 bits 用作 rights 成员:

library test.bad.fi0177;

type MySubtype = enum : uint32 {
    NONE = 0;
    VMO = 3;
};

resource_definition MyResource : uint32 {
    properties {
        subtype MySubtype;
        rights string;
    };
};

将此成员指向有效的 bits : uint32 声明:

library test.good.fi0177;

type MySubtype = enum : uint32 {
    NONE = 0;
    VMO = 3;
};

resource_definition MyResource : uint32 {
    properties {
        subtype MySubtype;
        rights uint32;
    };
};

这是一个与 FIDL 的内部实现相关的错误,因此只应向处理 FIDL 核心库的开发者公开。最终用户绝不会看到此错误。

它所引用的 resource_definition 声明是 FIDL 用于定义句柄等资源的内部方法,将来可能会作为处理程序泛化工作的一部分而发生变化。

fi-0178:未使用的导入

如果不引用通过 using 声明导入的依赖项,则会出错:

library test.bad.fi0178;

using dependent;

type Foo = struct {
    does_not int64;
    use_dependent int32;
};

确保通过实际引用导入或移除未使用的依赖项在库导入中使用所有此类导入:

library test.good.fi0178;

using dependent;

type Foo = struct {
    dep dependent.Bar;
};

fi-0179:不能对 newtype 进行限制

不允许限制 RFC-0052:类型别名和新类型中的新类型。例如,您不能使用 :optionalstring 的新类型进行约束:

library test.bad.fi0179;

type Name = string;

type Info = struct {
    name Name:optional;
};

在这种情况下,我们可以将 name 字段放在表(而不是结构体)中,使其成为可选字段:

library test.good.fi0179;

type Name = string;

type Info = table {
    1: name Name;
};

此限制简化了 newtype 的设计。不清楚对于受限的新类型,API 和 ABI 应该是什么样子(例如,限制条件是应该应用于 newtype 本身,还是延伸到底层类型?)。

fi-0180:Zircon C 类型处于实验阶段

我们正在为 Zither 项目开发内置类型 usizeuintptrucharexperimental_pointer。它们不适用于普通 FIDL 库:

library test.bad.fi0180;

type Data = struct {
    size usize64;
};

请改用其他类型,例如 uint64 而不是 usize

library test.good.fi0180;

type Data = struct {
    size uint64;
};

fi-0181:库属性参数引用常量

库声明中的属性参数不能引用常量:

@custom_attribute(VALUE)
library test.bad.fi0181a;

const VALUE string = "hello";

请改为提供字面量参数:

@custom_attribute("hello")
library test.good.fi0181a;

存在此限制是因为它很少需要,支持它会增加编译器的复杂性。

fi-0182:旧版仅适用于已移除的元素

不允许(直接或通过继承)移除的元素向 @available 属性提供 legacy 参数:

@available(added=1)
library test.bad.fi0182;

protocol Foo {
    @available(added=2, legacy=true)
    Bar() -> ();
};

请改为移除 legacy 参数:

@available(added=1)
library test.good.fi0182a;

protocol Foo {
    @available(added=2)
    Bar() -> ();
};

或者,保留 legacy 实参,但添加 removed 实参:

@available(added=1)
library test.good.fi0182b;

protocol Foo {
    @available(added=2, removed=3, legacy=true)
    Bar() -> ();
};

legacy 参数用于指明移除某个元素后是否应在 LEGACY 版本中重新添加该元素,因此将其用于从未移除的元素毫无意义。如需了解详情,请参阅有关 legacy 的文档

fi-0183:旧版与父级冲突

如果在没有旧版支持的情况下移除子元素的父元素,则无法将其标记为 legacy=true

@available(added=1)
library test.bad.fi0183;

@available(removed=3)
protocol Foo {
    @available(added=2, legacy=true)
    Bar() -> ();
};

请改为移除 legacy=true 参数:

@available(added=1)
library test.good.fi0183a;

@available(removed=3)
protocol Foo {
    @available(added=2)
    Bar() -> ();
};

或者,将 legacy=true 也添加到父级。子级将会继承它,因此无需在此处再次指定。请注意,这也会影响父级拥有的任何其他子级。

@available(added=1)
library test.good.fi0183b;

@available(removed=3, legacy=true)
protocol Foo {
    @available(added=2)
    Bar() -> ();
};

legacy=true 参数表示元素在移除后应重新添加到 LEGACY 版本中,并且子元素不能独立于其父元素存在。如需了解详情,请参阅有关 legacy 的文档

fi-0184:非预期的控制字符

字符串字面量不得包含原始控制字符(从 0x000x1f 的 ASCII 字符):

library test.bad.fi0184;

const TAB string = "	"; // literal tab character

请改用转义序列。在本例中,正确的是 \t

library test.good.fi0184a;

const TAB string = "\t";

您也可以使用 Unicode 转义序列。这适用于任何 Unicode 代码点:

library test.good.fi0184b;

const TAB string = "\u{9}";

字符串字面量中不允许使用原始控制字符,因为它们要么是空格,要么是不可打印字符,因此如果直接嵌入 FIDL 源文件中,它们会令人困惑且难以注意。

fi-0185:Unicode 转义序列缺少大括号

字符串字面量中的 Unicode 转义序列必须用大括号指定一个代码点:

library test.bad.fi0185;

const SMILE string = "\u";

若要修正该错误,请用大括号指定一个代码点:

library test.good.fi0185;

const SMILE string = "\u{1F600}";

fi-0186:Unicode 转义序列未结束

字符串字面量中的 Unicode 转义序列必须终止:

library test.bad.fi0186;

const SMILE string = "\u{1F600";

如需终止转义序列,请添加右大括号 }

library test.good.fi0186;

const SMILE string = "\u{1F600}";

fi-0187:Unicode 转义序列为空

字符串字面量中的 Unicode 转义序列必须至少包含一个十六进制数字:

library test.bad.fi0187;

const SMILE string = "\u{}";

要修正该错误,请添加十六进制数字以指定 Unicode 代码点:

library test.good.fi0187;

const SMILE string = "\u{1F600}";

fi-0188:Unicode 转义序列中的位数过多

字符串字面量中的 Unicode 转义序列不能超过 6 个十六进制数字:

library test.bad.fi0188;

const SMILE string = "\u{001F600}";

如需修正该错误,请最多指定 6 个十六进制数字。在本示例中,我们可以移除前导零:

library test.good.fi0188;

const SMILE string = "\u{1F600}";

存在此限制,因为所有有效的 Unicode 代码点都可容纳 6 位十六进制数字,因此没有理由允许超过该值的位数。

fi-0189:Unicode 代码点过大

字符串字面量中的 Unicode 转义序列不能指定大于 0x10ffff 最大值的 Unicode 代码点:

library test.bad.fi0189;

const TOO_LARGE string = "\u{110000}";

请改为确保代码点有效:

library test.good.fi0189;

const MAX_CODEPOINT string = "\u{10ffff}";

fi-0190

fi-0191:方法必须指定严格程度

此错误表示 FIDL 方法没有 strictflexible 修饰符。

library test.bad.fi0191;

open protocol Example {
    OneWay();
};

如需解决此问题,请向该方法添加 strictflexible。如果这是一个现有方法,您必须使用 strict,并且应参阅兼容性指南,了解如何将其更改为 flexible。如果这是一种新方法,您应查看 API 评分准则,了解选择方法。

library test.good.fi0191;

open protocol Example {
    flexible OneWay();
};

FIDL 目前正在进行迁移,以便支持处理 RFC-0138 中定义的未知互动。这项新功能允许修饰符 strictflexible 应用于 FIDL 方法和事件。过去,所有方法的行为都像是 strict 一样,但在此迁移结束时,默认值将为 flexible。为了避免混淆和可能因将方法默认修饰符从 strict 更改为 flexible 而导致的问题,在此过渡期间必须使用方法修饰符。迁移完成后,此值将从错误更改为 Linter 建议。

如需详细了解未知互动,请参阅 FIDL 语言参考文档

fi-0192:协议必须指定开放性

此错误表示 FIDL 协议没有 openajarclosed 修饰符。

library test.bad.fi0192;

protocol ImplicitOpenness {};

如需修复此问题,请向协议中添加 openajarclosed。如果这是一个现有协议,您必须使用 closed,并且应参阅兼容性指南,了解如何将其更改为 openajar。如果这是一种新方法,您应该查看 API 评分准则来寻找选择方法。

library test.good.fi0192;

open protocol ImplicitOpenness {};

FIDL 目前正在进行迁移,以便支持处理 RFC-0138 中定义的未知互动。这项新功能添加了三个新的修饰符:openajarclosed,它们适用于 FIDL 协议。过去,所有协议的行为都就像是 closed 一样,但在此迁移结束时,默认值将为 open。为避免因将协议默认修饰符从 closed 更改为 open 而引发混淆和可能的问题,您需要在此过渡期内使用协议修饰符。迁移完成后,此值将从错误更改为 Linter 建议。

如需详细了解未知互动,请参阅 FIDL 语言参考文档

fi-0193:无法框类型

结构体以外的类型不能装箱。例如,基元类型不能封装:

library test.bad.fi0193;

type MyStruct = struct {
    my_member box<bool>;
};

如需为基元装箱,请改为将其放入单个成员 struct 中:

library test.good.fi0193;

type MyStruct = struct {
    my_member box<struct {
        my_bool bool;
    }>;
};

请注意,某些类型可通过使用 optional 约束设置为可选。如需了解详情,请参阅可选指南或下面的展开式广告。

FIDL 配方:可选

某些 FIDL 类型可以设置为可选,添加 :optional 限制后,不更改其包含消息的线形。此外,table 布局始终是可选的,而 struct 布局从不。如需使 struct 成为可选,它必须封装在 box<T> 中,从而更改其包含消息的线形。

基本类型 可选版本 可选性是否会改变线路布局?
struct {...} box<struct {...}>
table {...} table {...} 不兼容
union {...} union {...}:optional 不兼容
vector<T> vector<T>:optional 不兼容
string string:optional 不兼容
zx.Handle zx.Handle:optional 不兼容
client_end:P client_end:<P, optional> 不兼容
server_end:P server_end:<P, optional> 不兼容

所有其他类型(bitsenumarray<T, N> 和基元类型)都不能设为可选类型。

在此变体中,我们允许键值对存储区将其他键值对存储区作为成员。简而言之,我们将其变成一棵树。为此,我们将 value 的原始定义替换为使用双成员 union 的定义:一个变体使用与之前相同的 vector<byte> 类型存储叶节点,而另一个变体以其他嵌套存储的形式存储分支节点。

推理

在这里,我们看到可选性的几种用途,我们可以借此声明一个可能存在或可能不存在的类型。FIDL 中有三种可选类型:

  • 始终在线在线存储的类型,因此有一种内置方式,通过 null 信封来描述“缺失”。为这些类型启用可选性不会影响包含它们的消息的传输形状,而只是更改该特定类型有效的值。通过添加 :optional 约束条件,unionvector<T>client_endserver_endzx.Handle 类型均可设为可选类型。通过将 value union 设为可选,我们能够采用不存在的 value 的形式引入规范的“null”条目。这意味着空 bytes 和缺失/空 store 属性都是无效值。
  • 与上述类型不同,struct 布局没有额外的空间可存储 null 标头。因此,需要将其封装在信封中,从而更改包含它的消息的线上形状。为了确保这种导线修改效果易于辨认,必须将 Item struct 类型封装在 box<T> 类型模板中。
  • 最后,table 布局始终是可选的。如果 table 不存在,则只是未设置任何成员的标识符。

树是一种天生的自引用数据结构:树中的任何节点都可能包含具有纯数据的叶(在本例中为字符串)或具有更多节点的子树。这需要递归:Item 的定义现在以传递方式依赖于其本身!在 FIDL 中表示递归类型可能有点复杂,尤其是因为目前对支持的内容有些有限。只要自引用创建的周期中至少有一个可选类型,我们就可以支持此类类型。例如,在这里,我们将 items struct 成员定义为 box<Item>,从而打破包含循环。

这些更改还大量使用了匿名类型(即声明内嵌在其单一使用点的类型),而不是被命名的顶级 type 声明。默认情况下,生成的语言绑定中的匿名类型名称取自其本地上下文。例如,新引入的 flexible union 将采用其自有成员的名称 Value,新引入的 struct 将变为 Store,依此类推。由于这种启发式方法有时可能会导致冲突,因此 FIDL 提供了应急方法,允许作者手动替换匿名类型的生成名称。这是通过 @generated_name 属性实现的,该属性可用于更改后端生成的名称。我们可以在这里使用一个示例,将原本的 Store 类型重命名为 NestedStore,以防止名称与使用相同名称的 protocol 声明发生名称冲突。

实现

FIDL、CML 和 Realm 接口定义修改如下:

FIDL

// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
library examples.keyvaluestore.supporttrees;

/// An item in the store. The key must match the regex `^[A-z][A-z0-9_\.\/]{2,62}[A-z0-9]$`. That
/// is, it must start with a letter, end with a letter or number, contain only letters, numbers,
/// periods, and slashes, and be between 4 and 64 characters long.
type Item = struct {
    key string:128;
    value strict union {
        // Keep the original `bytes` as one of the options in the new union. All leaf nodes in the
        // tree must be `bytes`, or absent unions (representing empty). Empty byte arrays are
        // disallowed.
        1: bytes vector<byte>:64000;

        // Allows a store within a store, thereby turning our flat key-value store into a tree
        // thereof. Note the use of `@generated_name` to prevent a type-name collision with the
        // `Store` protocol below, and the use of `box<T>` to ensure that there is a break in the
        // chain of recursion, thereby allowing `Item` to include itself in its own definition.
        //
        // This is a table so that added fields, like for example a `hash`, can be easily added in
        // the future.
        2: store @generated_name("nested_store") table {
            1: items vector<box<Item>>;
        };
    }:optional;
};

/// An enumeration of things that may go wrong when trying to write a value to our store.
type WriteError = flexible enum {
    UNKNOWN = 0;
    INVALID_KEY = 1;
    INVALID_VALUE = 2;
    ALREADY_EXISTS = 3;
};

/// A very basic key-value store.
@discoverable
open protocol Store {
    /// Writes an item to the store.
    flexible WriteItem(struct {
        attempt Item;
    }) -> () error WriteError;
};

全渠道营销 (CML)

客户端

// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
{
    include: [ "syslog/client.shard.cml" ],
    program: {
        runner: "elf",
        binary: "bin/client_bin",
    },
    use: [
        { protocol: "examples.keyvaluestore.supporttrees.Store" },
    ],
    config: {
        write_items: {
            type: "vector",
            max_count: 16,
            element: {
                type: "string",
                max_size: 64,
            },
        },

        // A newline separated list nested entries. The first line should be the key
        // for the nested store, and each subsequent entry should be a pointer to a text file
        // containing the string value. The name of that text file (without the `.txt` suffix) will
        // serve as the entries key.
        write_nested: {
            type: "vector",
            max_count: 16,
            element: {
                type: "string",
                max_size: 64,
            },
        },

        // A list of keys, all of which will be populated as null entries.
        write_null: {
            type: "vector",
            max_count: 16,
            element: {
                type: "string",
                max_size: 64,
            },
        },

    },
}

服务器

// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
{
    include: [ "syslog/client.shard.cml" ],
    program: {
        runner: "elf",
        binary: "bin/server_bin",
    },
    capabilities: [
        { protocol: "examples.keyvaluestore.supporttrees.Store" },
    ],
    expose: [
        {
            protocol: "examples.keyvaluestore.supporttrees.Store",
            from: "self",
        },
    ],
}

领域

// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
{
    children: [
        {
            name: "client",
            url: "#meta/client.cm",
        },
        {
            name: "server",
            url: "#meta/server.cm",
        },
    ],
    offer: [
        // Route the protocol under test from the server to the client.
        {
            protocol: "examples.keyvaluestore.supporttrees.Store",
            from: "#server",
            to: "#client",
        },

        // Route diagnostics support to all children.
        {
            protocol: [
                "fuchsia.inspect.InspectSink",
                "fuchsia.logger.LogSink",
            ],
            from: "parent",
            to: [
                "#client",
                "#server",
            ],
        },
    ],
}

然后,可以使用任何支持的语言编写客户端和服务器实现:

Rust

客户端

// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use {
    anyhow::{Context as _, Error},
    config::Config,
    fidl_examples_keyvaluestore_supporttrees::{Item, NestedStore, StoreMarker, Value},
    fuchsia_component::client::connect_to_protocol,
    std::{thread, time},
};

#[fuchsia::main]
async fn main() -> Result<(), Error> {
    println!("Started");

    // Load the structured config values passed to this component at startup.
    let config = Config::take_from_startup_handle();

    // Use the Component Framework runtime to connect to the newly spun up server component. We wrap
    // our retained client end in a proxy object that lets us asynchronously send `Store` requests
    // across the channel.
    let store = connect_to_protocol::<StoreMarker>()?;
    println!("Outgoing connection enabled");

    // This client's structured config has one parameter, a vector of strings. Each string is the
    // path to a resource file whose filename is a key and whose contents are a value. We iterate
    // over them and try to write each key-value pair to the remote store.
    for key in config.write_items.into_iter() {
        let path = format!("/pkg/data/{}.txt", key);
        let value = std::fs::read_to_string(path.clone())
            .with_context(|| format!("Failed to load {path}"))?;
        let res = store
            .write_item(&Item {
                key: key.clone(),
                value: Some(Box::new(Value::Bytes(value.into_bytes()))),
            })
            .await;
        match res? {
            Ok(_) => println!("WriteItem Success at key: {}", key),
            Err(err) => println!("WriteItem Error: {}", err.into_primitive()),
        }
    }

    // Add nested entries to the key-value store as well. The entries are strings, where the first
    // line is the key of the entry, and each subsequent entry should be a pointer to a text file
    // containing the string value. The name of that text file (without the `.txt` suffix) will
    // serve as the entries key.
    for spec in config.write_nested.into_iter() {
        let mut items = vec![];
        let mut nested_store = NestedStore::default();
        let mut lines = spec.split("\n");
        let key = lines.next().unwrap();

        // For each entry, make a new entry in the `NestedStore` being built.
        for entry in lines {
            let path = format!("/pkg/data/{}.txt", entry);
            let contents = std::fs::read_to_string(path.clone())
                .with_context(|| format!("Failed to load {path}"))?;
            items.push(Some(Box::new(Item {
                key: entry.to_string(),
                value: Some(Box::new(Value::Bytes(contents.into()))),
            })));
        }
        nested_store.items = Some(items);

        // Send the `NestedStore`, represented as a vector of values.
        let res = store
            .write_item(&Item {
                key: key.to_string(),
                value: Some(Box::new(Value::Store(nested_store))),
            })
            .await;
        match res? {
            Ok(_) => println!("WriteItem Success at key: {}", key),
            Err(err) => println!("WriteItem Error: {}", err.into_primitive()),
        }
    }

    // Each entry in this list is a null value in the store.
    for key in config.write_null.into_iter() {
        match store.write_item(&Item { key: key.to_string(), value: None }).await? {
            Ok(_) => println!("WriteItem Success at key: {}", key),
            Err(err) => println!("WriteItem Error: {}", err.into_primitive()),
        }
    }

    // TODO(https://fxbug.dev/42156498): We need to sleep here to make sure all logs get drained. Once the
    // referenced bug has been resolved, we can remove the sleep.
    thread::sleep(time::Duration::from_secs(2));
    Ok(())
}

服务器

// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use {
    anyhow::{Context as _, Error},
    fidl_examples_keyvaluestore_supporttrees::{
        Item, StoreRequest, StoreRequestStream, Value, WriteError,
    },
    fuchsia_component::server::ServiceFs,
    futures::prelude::*,
    lazy_static::lazy_static,
    regex::Regex,
    std::cell::RefCell,
    std::collections::hash_map::Entry,
    std::collections::HashMap,
    std::str::from_utf8,
};

lazy_static! {
    static ref KEY_VALIDATION_REGEX: Regex =
        Regex::new(r"^[A-Za-z]\w+[A-Za-z0-9]$").expect("Key validation regex failed to compile");
}

// A representation of a key-value store that can contain an arbitrarily deep nesting of other
// key-value stores.
#[allow(dead_code)] // TODO(https://fxbug.dev/318827209)
enum StoreNode {
    Leaf(Option<Vec<u8>>),
    Branch(Box<HashMap<String, StoreNode>>),
}

/// Recursive item writer, which takes a `StoreNode` that may not necessarily be the root node, and
/// writes an entry to it.
fn write_item(
    store: &mut HashMap<String, StoreNode>,
    attempt: Item,
    path: &str,
) -> Result<(), WriteError> {
    // Validate the key.
    if !KEY_VALIDATION_REGEX.is_match(attempt.key.as_str()) {
        println!("Write error: INVALID_KEY, For key: {}", attempt.key);
        return Err(WriteError::InvalidKey);
    }

    // Write to the store, validating that the key did not already exist.
    match store.entry(attempt.key) {
        Entry::Occupied(entry) => {
            println!("Write error: ALREADY_EXISTS, For key: {}", entry.key());
            Err(WriteError::AlreadyExists)
        }
        Entry::Vacant(entry) => {
            let key = format!("{}{}", &path, entry.key());
            match attempt.value {
                // Null entries are allowed.
                None => {
                    println!("Wrote value: NONE at key: {}", key);
                    entry.insert(StoreNode::Leaf(None));
                }
                Some(value) => match *value {
                    // If this is a nested store, recursively make a new store to insert at this
                    // position.
                    Value::Store(entry_list) => {
                        // Validate the value - absent stores, items lists with no children, or any
                        // of the elements within that list being empty boxes, are all not allowed.
                        if entry_list.items.is_some() {
                            let items = entry_list.items.unwrap();
                            if !items.is_empty() && items.iter().all(|i| i.is_some()) {
                                let nested_path = format!("{}/", key);
                                let mut nested_store = HashMap::<String, StoreNode>::new();
                                for item in items.into_iter() {
                                    write_item(&mut nested_store, *item.unwrap(), &nested_path)?;
                                }

                                println!("Created branch at key: {}", key);
                                entry.insert(StoreNode::Branch(Box::new(nested_store)));
                                return Ok(());
                            }
                        }

                        println!("Write error: INVALID_VALUE, For key: {}", key);
                        return Err(WriteError::InvalidValue);
                    }

                    // This is a simple leaf node on this branch.
                    Value::Bytes(value) => {
                        // Validate the value.
                        if value.is_empty() {
                            println!("Write error: INVALID_VALUE, For key: {}", key);
                            return Err(WriteError::InvalidValue);
                        }

                        println!("Wrote key: {}, value: {:?}", key, from_utf8(&value).unwrap());
                        entry.insert(StoreNode::Leaf(Some(value)));
                    }
                },
            }
            Ok(())
        }
    }
}

/// Creates a new instance of the server. Each server has its own bespoke, per-connection instance
/// of the key-value store.
async fn run_server(stream: StoreRequestStream) -> Result<(), Error> {
    // Create a new in-memory key-value store. The store will live for the lifetime of the
    // connection between the server and this particular client.
    let store = RefCell::new(HashMap::<String, StoreNode>::new());

    // Serve all requests on the protocol sequentially - a new request is not handled until its
    // predecessor has been processed.
    stream
        .map(|result| result.context("failed request"))
        .try_for_each(|request| async {
            // Match based on the method being invoked.
            match request {
                StoreRequest::WriteItem { attempt, responder } => {
                    println!("WriteItem request received");

                    // The `responder` parameter is a special struct that manages the outgoing reply
                    // to this method call. Calling `send` on the responder exactly once will send
                    // the reply.
                    responder
                        .send(write_item(&mut store.borrow_mut(), attempt, ""))
                        .context("error sending reply")?;
                    println!("WriteItem response sent");
                }
                StoreRequest::_UnknownMethod { ordinal, .. } => {
                    println!("Received an unknown method with ordinal {ordinal}");
                }
            }
            Ok(())
        })
        .await
}

// A helper enum that allows us to treat a `Store` service instance as a value.
enum IncomingService {
    Store(StoreRequestStream),
}

#[fuchsia::main]
async fn main() -> Result<(), Error> {
    println!("Started");

    // Add a discoverable instance of our `Store` protocol - this will allow the client to see the
    // server and connect to it.
    let mut fs = ServiceFs::new_local();
    fs.dir("svc").add_fidl_service(IncomingService::Store);
    fs.take_and_serve_directory_handle()?;
    println!("Listening for incoming connections");

    // The maximum number of concurrent clients that may be served by this process.
    const MAX_CONCURRENT: usize = 10;

    // Serve each connection simultaneously, up to the `MAX_CONCURRENT` limit.
    fs.for_each_concurrent(MAX_CONCURRENT, |IncomingService::Store(stream)| {
        run_server(stream).unwrap_or_else(|e| println!("{:?}", e))
    })
    .await;

    Ok(())
}

C++(自然)

客户端

// TODO(https://fxbug.dev/42060656): C++ (Natural) implementation.

服务器

// TODO(https://fxbug.dev/42060656): C++ (Natural) implementation.

C++(有线)

客户端

// TODO(https://fxbug.dev/42060656): C++ (Wire) implementation.

服务器

// TODO(https://fxbug.dev/42060656): C++ (Wire) implementation.

HLCPP

客户端

// TODO(https://fxbug.dev/42060656): HLCPP implementation.

服务器

// TODO(https://fxbug.dev/42060656): HLCPP implementation.

fi-0194

fi-0195

fi-0196

fi-0201:未选择平台版本

如果您在未选择版本的情况下编译带版本号的 FIDL 库,就会出现此错误:

// fidlc --files test.fidl --out test.json
@available(platform="foo", added=1)
library test.bad.fi0201;

如需解决此问题,请选择带有 --available 命令行标志的版本:

// fidlc --files test.fidl --out test.json --available foo:1
@available(platform="foo", added=1)
library test.good.fi0201;

版本必须是大于或等于 1 的数字,或者是特殊版本 HEADLEGACY 之一。如需了解详情,请参阅 FIDL 版本控制文档。

fi-0202

fi-0203:删除和替换的内容相互排斥

@available 属性支持参数 removedreplaced,但它们不能一起使用:

@available(added=1)
library test.bad.fi0203;

protocol Foo {
    @available(removed=2, replaced=2)
    Foo();
};

如需修正该错误,请删除其中一个参数。如果您打算在不替换元素的情况下移除元素,请保留 removed 并删除 replaced

@available(added=1)
library test.good.fi0203a;

open protocol Foo {
    @available(removed=2)
    strict Foo();
};

或者,如果您要将元素替换为新定义,请保留 replaced 并删除 removed

@available(added=1)
library test.good.fi0203b;

open protocol Foo {
    @available(replaced=2)
    strict Foo();

    @available(added=2)
    flexible Foo();
};

removedreplaced 结合使用没有意义,因为它们的含义相反。如果某个元素被标记为 removed,fidlc 会验证相应版本是否没有添加的替换元素。如果某个元素被标记为 replaced,fidlc 会验证是否存在在同一版本中添加的替换元素。IS

如需详细了解版本控制,请参阅 FIDL 版本控制

fi-0204:库无法替换

@available 属性的 replaced 参数不能用于库声明:

@available(added=1, replaced=2)
library test.bad.fi0204;

请改用 removed 参数:

@available(added=1, removed=2)
library test.good.fi0204;

replaced 参数表示某个元素被新的定义替换。整个库不支持此功能,因为我们假设每个库只有一组定义该实例的文件。

如需详细了解版本控制,请参阅 FIDL 版本控制

fi-0205:已移除的元素不能有替换元素

如果某个元素被标记为 @available(removed=N),则表示该元素在版本 N 中已无法再使用。它不应只是替换为标记为 @available(added=N) 的新定义:

@available(added=1)
library test.bad.fi0204;

open protocol Foo {
    @available(removed=2)
    strict Bar();
    @available(added=2)
    flexible Bar();
};

如果替换是有意为之,请使用 replaced 参数(而不是 removed 参数)明确替换:

@available(added=1)
library test.good.fi0204a;

open protocol Foo {
    @available(replaced=2)
    strict Bar();
    @available(added=2)
    flexible Bar();
};

如果替换是无意的,请移除或重命名其他元素:

@available(added=1)
library test.good.fi0204b;

open protocol Foo {
    @available(removed=2)
    strict Bar();
    @available(added=2)
    flexible NewBar();
};

removedreplaced 参数对生成的绑定具有相同的效果,但它们代表 API 生命周期中的不同时间点。removed 参数表示 API 结束,而 replaced 参数表示过渡到新定义。

如需详细了解版本控制,请参阅 FIDL 版本控制

fi-0206:被替换的元素没有替换项

如果某个元素被标记为 @available(replaced=N),则表示该元素被替换为标记为 @available(added=N) 的新定义。如果 FIDL 编译器找不到这样的定义,则会报告错误:

@available(added=1)
library test.bad.fi0205;

open protocol Foo {
    @available(replaced=2)
    strict Bar();
};

如果您不打算替换该元素,请使用 removed 参数,而不是 replaced 参数:

@available(added=1)
library test.good.fi0205a;

open protocol Foo {
    @available(removed=2)
    strict Bar();
};

如果您想要替换该元素,请添加替换定义:

@available(added=1)
library test.good.fi0205b;

open protocol Foo {
    @available(replaced=2)
    strict Bar();
    @available(added=2)
    flexible Bar();
};

removedreplaced 参数对生成的绑定具有相同的效果,但它们代表 API 生命周期中的不同时间点。removed 参数表示 API 结束,而 replaced 参数表示过渡到新定义。

如需详细了解版本控制,请参阅 FIDL 版本控制

fi-0207:类型形状整数溢出

FIDL 类型不得过大,使其大小超出 uint32

library test.bad.fi0207;

type Foo = struct {
    bytes array<uint64, 536870912>;
};

如需修复该错误,请使用较小的数组大小:

library test.good.fi0207;

type Foo = struct {
    bytes array<uint64, 100>;
};

在实践中,FIDL 类型应远小于 232 字节,因为它们通常是通过 Zircon 通道发送的,而每条消息的上限为 64 KiB。

fi-0208:预留平台

某些平台名称由 FIDL 保留。例如,“未版本化”的平台已预留以表示不使用版本控制的库:

@available(platform="unversioned", added=1)
library test.bad.fi0208;

请改为选择其他平台名称:

@available(platform="foo", added=1)
library test.good.fi0208;

如需详细了解版本控制,请参阅 FIDL 版本控制