Skip to content

Truly independent web browser

LibIPC+Meta: Generate codecs for declared structs, enums and variants

Andreas Kling275e7cc2cee0
diff --git a/Libraries/LibIPC/Decoder.cpp b/Libraries/LibIPC/Decoder.cpp
index a693632dd3e..99676ce75ae 100644
--- a/Libraries/LibIPC/Decoder.cpp
+++ b/Libraries/LibIPC/Decoder.cpp
@@ -22,7 +22,10 @@ namespace IPC {
ErrorOr<size_t> Decoder::decode_size()
{
+ auto max_size = exchange(m_max_size_of_next_value, NumericLimits<size_t>::max());
auto size = static_cast<size_t>(TRY(decode<u32>()));
+ if (size > max_size)
+ return Error::from_string_literal("IPC decode: Size exceeds the maximum");
// Every element of a string or container takes at least one byte or one attachment of the message.
if (size > m_stream.remaining() + m_attachments.size())
diff --git a/Libraries/LibIPC/Decoder.h b/Libraries/LibIPC/Decoder.h
index 796ed337ff8..28d74273248 100644
--- a/Libraries/LibIPC/Decoder.h
+++ b/Libraries/LibIPC/Decoder.h
@@ -11,7 +11,9 @@
#include <AK/Concepts.h>
#include <AK/Forward.h>
#include <AK/MemoryStream.h>
+#include <AK/NumericLimits.h>
#include <AK/Queue.h>
+#include <AK/ScopeGuard.h>
#include <AK/StdLibExtras.h>
#include <AK/String.h>
#include <AK/Time.h>
@@ -48,6 +50,11 @@ public:
template<typename T>
ErrorOr<T> decode();
+ // Decodes a string, byte buffer or vector, which goes as its size and then its contents, refusing one larger than
+ // max_size before decoding its contents.
+ template<typename T>
+ ErrorOr<T> decode_with_max_size(size_t max_size);
+
template<typename T>
ErrorOr<void> decode_into(T& value)
{
@@ -69,6 +76,7 @@ public:
private:
FixedMemoryStream& m_stream;
Queue<Attachment>& m_attachments;
+ size_t m_max_size_of_next_value { NumericLimits<size_t>::max() };
};
template<Arithmetic T>
@@ -279,4 +287,14 @@ ErrorOr<T> Decoder::decode()
return IPC::decode<T>(*this);
}
+template<typename T>
+ErrorOr<T> Decoder::decode_with_max_size(size_t max_size)
+{
+ // NB: Decoding a string, byte buffer or vector starts with decode_size(), which checks the size against this. The
+ // bound ends with the value, so it never applies to anything decoded after it.
+ m_max_size_of_next_value = max_size;
+ ScopeGuard reset_max_size = [&] { m_max_size_of_next_value = NumericLimits<size_t>::max(); };
+ return decode<T>();
+}
+
}
diff --git a/Libraries/LibIPC/Forward.h b/Libraries/LibIPC/Forward.h
index e3cae82e712..2639ef520d7 100644
--- a/Libraries/LibIPC/Forward.h
+++ b/Libraries/LibIPC/Forward.h
@@ -6,6 +6,7 @@
#pragma once
+#include <AK/Concepts.h>
#include <AK/Error.h>
#include <AK/Platform.h>
@@ -44,6 +45,14 @@ ErrorOr<void> encode(Encoder&, T const&);
template<typename T>
ErrorOr<T> decode(Decoder&);
+// NB: Declared here so that a codec specialized for one enum, wherever it is declared, specializes these and not the
+// templates above.
+template<Enum T>
+ErrorOr<void> encode(Encoder&, T const&);
+
+template<Enum T>
+ErrorOr<T> decode(Decoder&);
+
using MessageDataType = Vector<u8, 1024>;
}
diff --git a/Libraries/LibIPC/Rust/src/wire.rs b/Libraries/LibIPC/Rust/src/wire.rs
index ad9e8d5d8db..6b35ea19a23 100644
--- a/Libraries/LibIPC/Rust/src/wire.rs
+++ b/Libraries/LibIPC/Rust/src/wire.rs
@@ -120,6 +120,7 @@ pub struct Decoder<'a> {
bytes: &'a [u8],
position: usize,
attachments: VecDeque<Attachment>,
+ max_size_of_next_value: usize,
}
impl<'a> Decoder<'a> {
@@ -128,6 +129,7 @@ impl<'a> Decoder<'a> {
bytes,
position: 0,
attachments: attachments.into_iter().collect(),
+ max_size_of_next_value: usize::MAX,
}
}
@@ -143,13 +145,28 @@ impl<'a> Decoder<'a> {
}
pub fn decode_size(&mut self) -> Result<usize, DecodeError> {
+ let max_size = std::mem::replace(&mut self.max_size_of_next_value, usize::MAX);
let size = self.decode::<u32>()? as usize;
+ if size > max_size {
+ return Err(DecodeError::SizeTooLarge(size));
+ }
if size > self.remaining_bytes().saturating_add(self.attachments.len()) {
return Err(DecodeError::UnexpectedEnd);
}
Ok(size)
}
+ /// Decodes a string, byte buffer or vector, which goes as its size and then its contents, refusing one larger than
+ /// `max_size` before decoding its contents.
+ pub fn decode_with_max_size<T: Decode>(&mut self, max_size: usize) -> Result<T, DecodeError> {
+ // NB: Decoding a string, byte buffer or vector starts with decode_size(), which checks the size against this.
+ // The bound ends with the value, so it never applies to anything decoded after it.
+ self.max_size_of_next_value = max_size;
+ let value = self.decode();
+ self.max_size_of_next_value = usize::MAX;
+ value
+ }
+
pub fn take_attachment(&mut self) -> Result<Attachment, DecodeError> {
self.attachments.pop_front().ok_or(DecodeError::MissingAttachment)
}
@@ -622,6 +639,24 @@ mod tests {
(decoded, bytes)
}
+ #[test]
+ fn sizes_are_bounded_before_contents_and_only_within_the_value() {
+ let mut encoder = Encoder::new();
+ encoder.encode("123456789").unwrap();
+ encoder.encode(&None::<String>).unwrap();
+ encoder.encode("123456789").unwrap();
+ let (bytes, _) = encoder.finish();
+ let mut decoder = Decoder::new(&bytes, []);
+ assert_eq!(
+ decoder.decode_with_max_size::<String>(8),
+ Err(DecodeError::SizeTooLarge(9))
+ );
+ let mut decoder = Decoder::new(&bytes, []);
+ assert_eq!(decoder.decode_with_max_size::<String>(9).unwrap(), "123456789");
+ assert_eq!(decoder.decode_with_max_size::<Option<String>>(4).unwrap(), None);
+ assert_eq!(decoder.decode::<String>().unwrap(), "123456789");
+ }
+
#[test]
fn numbers_go_as_their_bytes() {
let (value, bytes) = round_trip(&0x0102_0304u32);
diff --git a/Meta/CMake/code_generators.cmake b/Meta/CMake/code_generators.cmake
index 7e66ab8ab82..c3131c5fe3d 100644
--- a/Meta/CMake/code_generators.cmake
+++ b/Meta/CMake/code_generators.cmake
@@ -35,7 +35,8 @@ function(compile_ipc source output)
cmake_path(RELATIVE_PATH CMAKE_CURRENT_SOURCE_DIR BASE_DIRECTORY ${LADYBIRD_SOURCE_DIR} OUTPUT_VARIABLE current_source_dir_relative)
set(library_arguments)
if (current_source_dir_relative MATCHES "^Libraries/(Lib[^/]+)(/|$)")
- list(APPEND library_arguments --library ${CMAKE_MATCH_1})
+ # NB: The library is defined after its IPC files, so its export macro is only known when the build is generated.
+ list(APPEND library_arguments --library ${CMAKE_MATCH_1} "--export-macro=$<TARGET_PROPERTY:${CMAKE_MATCH_1},LADYBIRD_EXPORT_MACRO>")
set(GENERATED_IPC TRUE PARENT_SCOPE)
endif()
set(rust_arguments)
@@ -70,6 +71,13 @@ function(compile_ipc source output)
set(SOURCES ${SOURCES} PARENT_SCOPE)
if (ENABLE_INSTALL_HEADERS)
- install(FILES ${output} DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${current_source_dir_relative}" OPTIONAL)
+ # NB: A header generated into a subdirectory of the library is installed into the same subdirectory, where
+ # the library's headers include it from.
+ get_filename_component(output_directory ${output} DIRECTORY)
+ file(RELATIVE_PATH output_subdirectory ${CMAKE_CURRENT_BINARY_DIR} ${output_directory})
+ if (output_subdirectory MATCHES "^\\.\\.")
+ set(output_subdirectory "")
+ endif()
+ install(FILES ${output} DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${current_source_dir_relative}/${output_subdirectory}" OPTIONAL)
endif()
endfunction()
diff --git a/Meta/CMake/targets.cmake b/Meta/CMake/targets.cmake
index 7f9d50b13f9..2472f71fe71 100644
--- a/Meta/CMake/targets.cmake
+++ b/Meta/CMake/targets.cmake
@@ -25,6 +25,8 @@ function(ladybird_generate_export_header name fs_name)
set(base_name BASE_NAME ${EXPORT_HEADER_BASE_NAME})
endif()
generate_export_header(${name} ${base_name} EXPORT_MACRO_NAME ${fs_name_upper}_API EXPORT_FILE_NAME "Export.h")
+ # NB: The IPC compiler exports the codecs it generates for the library with this.
+ set_target_properties(${name} PROPERTIES LADYBIRD_EXPORT_MACRO ${fs_name_upper}_API)
endfunction()
# What the objects of every library are compiled and linked with, whether the library is a target of its own or an
diff --git a/Meta/Generators/generate_ipc_definitions.py b/Meta/Generators/generate_ipc_definitions.py
index 270dcc1ebb9..76bb012d96c 100644
--- a/Meta/Generators/generate_ipc_definitions.py
+++ b/Meta/Generators/generate_ipc_definitions.py
@@ -18,12 +18,15 @@ from pathlib import Path
from typing import List
from typing import Optional
from typing import TextIO
+from typing import Tuple
sys.path.append(str(Path(__file__).resolve().parent.parent))
from Utils.lexer import Lexer
from Utils.utils import string_hash
+AK_DIRECTORY = Path(__file__).resolve().parent.parent.parent / "AK"
+
PRIMITIVE_TYPES = {
"i8",
"u8",
@@ -89,7 +92,6 @@ class Message:
@dataclass
class Endpoint:
- includes: List[str] = field(default_factory=list)
name: str = ""
magic: int = 0
messages: List[Message] = field(default_factory=list)
@@ -135,6 +137,159 @@ class Endpoint:
return pascal_case(self.route_scope())
+INTEGER_TYPES = {"u8", "u16", "u32", "u64", "i8", "i16", "i32", "i64"}
+
+# The attributes a struct field may have, and the types each one applies to.
+FIELD_ATTRIBUTE_TYPES = {
+ "MaxBytes": {"String", "ByteString", "ByteBuffer"},
+ "MaxCount": {"Vector"},
+ "NonZero": INTEGER_TYPES,
+ "Finite": {"float", "double"},
+}
+
+IDENTIFIER = r"[A-Za-z_][A-Za-z_0-9]*"
+QUALIFIED_NAME = re.compile(rf"{IDENTIFIER}(::{IDENTIFIER})*")
+FIELD_TYPE = re.compile(rf"(::)?{IDENTIFIER}(::{IDENTIFIER})*(<.+>)?")
+
+# Spellings of the same C++ type, which must not be told apart.
+TYPE_ALIASES = {"int": "i32", "unsigned": "u32", "size_t": "u64"}
+
+
+def canonical_type(type: str) -> str:
+ """The type with one spelling for each C++ type: without leading "::", and with sized integer names."""
+ type = re.sub(r"(?<![\w:])::", "", type)
+ type = re.sub(r"\bunsigned int\b", "u32", type)
+ return re.sub(r"(?<![\w:])\w+(?![\w:])", lambda name: TYPE_ALIASES.get(name[0], name[0]), type)
+
+
+def field_attributes(member: Parameter) -> List[Tuple[str, str]]:
+ """The attributes of a struct field as (name, argument) pairs, e.g. ("MaxBytes", "64")."""
+ attributes: List[Tuple[str, str]] = []
+ for attribute in member.attributes:
+ name, _, argument = attribute.partition("=")
+ attributes.append((name.strip(), argument.strip()))
+ return attributes
+
+
+@dataclass
+class FieldRefusal:
+ """A value of a field that its attributes refuse: how C++ and Rust find it, and what is wrong with it."""
+
+ attribute: str
+ cpp_condition: str
+ rust_condition: str
+ meaning: str
+
+ def is_checked_after_decoding(self) -> bool:
+ # NB: Decoders check sizes before they decode the contents.
+ return self.attribute not in ("MaxBytes", "MaxCount")
+
+
+def field_refusals(member: Parameter, cpp_value: str, rust_value: str) -> List[FieldRefusal]:
+ refusals: List[FieldRefusal] = []
+ for name, argument in field_attributes(member):
+ if name == "NonZero":
+ refusals.append(FieldRefusal(name, f"{cpp_value} == 0", f"{rust_value} == 0", "is zero"))
+ elif name == "Finite":
+ refusals.append(
+ FieldRefusal(name, f"!isfinite({cpp_value})", f"!{rust_value}.is_finite()", "is not finite")
+ )
+ elif name in ("MaxBytes", "MaxCount"):
+ cpp_size = {"String": "bytes().size()", "ByteString": "length()"}.get(member.type, "size()")
+ rust_size = {"String": "as_bytes().len()", "ByteString": "0.len()"}.get(member.type, "len()")
+ refusals.append(
+ FieldRefusal(
+ name,
+ f"{cpp_value}.{cpp_size} > {argument}",
+ f"{rust_value}.{rust_size} > {argument}",
+ "is too large",
+ )
+ )
+ return refusals
+
+
+@dataclass
+class Declaration:
+ """A type declared in an IPC file: a struct, an enum or a variant."""
+
+ kind: str = ""
+ # The C++ name, including its namespace, e.g. "WebView::DictionaryLookup".
+ name: str = ""
+ attributes: List[str] = field(default_factory=list)
+ # The integer type an enum goes as.
+ underlying_type: str = ""
+ # A struct's fields, an enum's values (with names only), or a variant's alternatives (with a name for Rust).
+ members: List[Parameter] = field(default_factory=list)
+
+ def is_existing_cpp(self) -> bool:
+ # The C++ type is defined elsewhere, so only its codec is generated.
+ # NB: Nothing can check that the declaration of an existing struct lists every field of its C++ type, so a
+ # field it leaves out is not sent, and the decoder leaves it to its default. The declaration must list
+ # them all, in their C++ order.
+ return "ExistingCpp" in self.attributes
+
+ def rust_name(self) -> str:
+ return self.name.replace("::", "_")
+
+ def has_accessors(self) -> bool:
+ # The existing C++ type is read through accessor functions and built with a constructor taking every field.
+ return "Accessors" in self.attributes
+
+ def validate(self) -> None:
+ if not re.fullmatch(rf"{IDENTIFIER}(::{IDENTIFIER})+", self.name):
+ raise RuntimeError(f"Expected a type name with a namespace, got '{self.name}'")
+ for attribute in self.attributes:
+ if attribute not in ("ExistingCpp", "Accessors"):
+ raise RuntimeError(f"Unknown attribute '{attribute}' on {self.name}")
+ if self.has_accessors() and (self.kind != "struct" or not self.is_existing_cpp()):
+ raise RuntimeError(f"Only an existing C++ struct can have accessors: {self.name}")
+
+ names = [member.name for member in self.members]
+ for name in names:
+ if not re.fullmatch(IDENTIFIER, name):
+ raise RuntimeError(f"Invalid member name '{name}' in {self.name}")
+ if self.kind != "enum":
+ for member in self.members:
+ if not FIELD_TYPE.fullmatch(member.type):
+ raise RuntimeError(f"Invalid type '{member.type}' of {self.name}::{member.name}")
+ if len(set(names)) != len(names):
+ raise RuntimeError(f"Duplicate member name in {self.name}")
+ if self.kind != "struct" and not names:
+ raise RuntimeError(f"Empty {self.kind}: {self.name}")
+
+ if self.kind == "enum":
+ if self.underlying_type not in INTEGER_TYPES:
+ raise RuntimeError(f"Enum {self.name} needs a sized integer type, got '{self.underlying_type}'")
+ value_bits = int(self.underlying_type[1:]) - (1 if self.underlying_type.startswith("i") else 0)
+ if len(names) > 2**value_bits:
+ raise RuntimeError(f"Enum {self.name} has more values than {self.underlying_type} holds")
+ elif self.kind == "variant":
+ # NB: An AK::Variant of fewer than 255 types goes with a u8 index.
+ if len(names) >= 255:
+ raise RuntimeError(f"Variant {self.name} has too many alternatives")
+ if len({canonical_type(member.type) for member in self.members}) != len(self.members):
+ raise RuntimeError(f"Variant {self.name} needs a distinct type for each alternative")
+ else:
+ for member in self.members:
+ for name, argument in field_attributes(member):
+ if name not in FIELD_ATTRIBUTE_TYPES:
+ raise RuntimeError(f"Unknown attribute '{name}' on {self.name}::{member.name}")
+ if member.type.partition("<")[0] not in FIELD_ATTRIBUTE_TYPES[name]:
+ raise RuntimeError(f"{name} cannot apply to {self.name}::{member.name} of type {member.type}")
+ if name in ("MaxBytes", "MaxCount"):
+ if not argument.isdecimal() or not 0 < int(argument) <= 0xFFFFFFFF:
+ raise RuntimeError(f"{name} on {self.name}::{member.name} needs a size, got '{argument}'")
+ elif argument:
+ raise RuntimeError(f"{name} on {self.name}::{member.name} takes no argument")
+
+
+@dataclass
+class Document:
+ includes: List[str] = field(default_factory=list)
+ declarations: List[Declaration] = field(default_factory=list)
+ endpoints: List[Endpoint] = field(default_factory=list)
+
+
def is_primitive_type(type: str) -> bool:
return type in PRIMITIVE_TYPES
@@ -167,9 +322,10 @@ def make_argument_type(type: str) -> str:
return f"{type} const&"
-def parse(contents: str) -> List[Endpoint]:
+def parse(contents: str) -> Document:
lexer = Lexer(contents)
- endpoints: List[Endpoint] = []
+ document = Document()
+ endpoints = document.endpoints
def assert_specific(ch: str) -> None:
if not lexer.consume_specific(ch):
@@ -177,11 +333,12 @@ def parse(contents: str) -> List[Endpoint]:
def consume_whitespace() -> None:
lexer.ignore_while(lambda c: c.isspace())
- if lexer.peek() == "/" and lexer.peek(1) == "/":
+ while lexer.next_is("//"):
lexer.ignore_until("\n")
+ lexer.ignore_while(lambda c: c.isspace())
- def parse_parameter_type() -> str:
- parameter_type = lexer.consume_until(lambda c: c == "<" or c.isspace())
+ def parse_parameter_type(delimiters: str = "") -> str:
+ parameter_type = lexer.consume_until(lambda c: c == "<" or c.isspace() or c in delimiters)
if lexer.peek() == "<":
lexer.consume()
@@ -212,6 +369,9 @@ def parse(contents: str) -> List[Endpoint]:
return
while True:
+ if lexer.is_eof():
+ raise RuntimeError("Unexpected EOF in attributes")
+
if lexer.consume_specific("]"):
consume_whitespace()
break
@@ -219,7 +379,7 @@ def parse(contents: str) -> List[Endpoint]:
if lexer.consume_specific(","):
consume_whitespace()
- storage.append(lexer.consume_until(lambda c: c in ("]", ",")))
+ storage.append(lexer.consume_until(lambda c: c in ("]", ",")).strip())
consume_whitespace()
def parse_parameter(storage: List[Parameter], message_name: str) -> None:
@@ -315,7 +475,7 @@ def parse(contents: str) -> List[Endpoint]:
include = lexer.consume_while(lambda c: c != "\n")
consume_whitespace()
- endpoints[-1].includes.append(include)
+ document.includes.append(include)
def parse_includes() -> None:
while True:
@@ -328,13 +488,6 @@ def parse(contents: str) -> List[Endpoint]:
def parse_endpoint() -> None:
endpoints.append(Endpoint())
- consume_whitespace()
- parse_includes()
- consume_whitespace()
-
- if not lexer.consume_specific("endpoint"):
- raise RuntimeError(f"Expected 'endpoint' at position {lexer.position}")
-
consume_whitespace()
endpoints[-1].name = lexer.consume_while(lambda c: not c.isspace())
endpoints[-1].magic = string_hash(endpoints[-1].name)
@@ -359,13 +512,75 @@ def parse(contents: str) -> List[Endpoint]:
assert_specific("}")
consume_whitespace()
- while lexer.position < len(contents):
- parse_endpoint()
+ def parse_declaration(kind: str, attributes: List[str]) -> None:
+ declaration = Declaration(kind=kind, attributes=attributes)
+ consume_whitespace()
+ name = QUALIFIED_NAME.match(lexer.text, lexer.position)
+ declaration.name = name[0] if name else ""
+ lexer.ignore(len(declaration.name))
+ consume_whitespace()
+ if kind == "enum":
+ assert_specific(":")
+ consume_whitespace()
+ declaration.underlying_type = lexer.consume_until(lambda c: c.isspace() or c == "{")
+ consume_whitespace()
+ assert_specific("{")
+
+ while True:
+ consume_whitespace()
+ if lexer.consume_specific("}"):
+ break
+ if lexer.is_eof():
+ raise RuntimeError(f"Unexpected EOF in {kind} {declaration.name}")
+
+ # Struct fields are declared as in C++, "Type name;". Enum values are listed by name and variant
+ # alternatives as "Name Type", separated by commas.
+ member = Parameter()
+ if kind == "struct":
+ parse_attributes(member.attributes)
+ member.type = parse_parameter_type()
+ consume_whitespace()
+ member.name = lexer.consume_until(lambda c: c.isspace() or c == ";")
+ consume_whitespace()
+ assert_specific(";")
+ else:
+ member.name = lexer.consume_until(lambda c: c.isspace() or c in ",}")
+ consume_whitespace()
+ if kind == "variant":
+ member.type = parse_parameter_type(",}")
+ consume_whitespace()
+ if not lexer.consume_specific(",") and lexer.peek() != "}":
+ raise RuntimeError(f"Expected ',' or '}}' at position {lexer.position}, got '{lexer.peek()}'")
+ declaration.members.append(member)
+
+ declaration.validate()
+ for existing in document.declarations:
+ if existing.name == declaration.name:
+ raise RuntimeError(f"Duplicate type: {declaration.name}")
+ if existing.rust_name() == declaration.rust_name():
+ raise RuntimeError(f"{existing.name} and {declaration.name} have the same Rust name")
+ document.declarations.append(declaration)
+
+ while True:
+ consume_whitespace()
+ parse_includes()
+ if lexer.is_eof():
+ break
+
+ attributes: List[str] = []
+ parse_attributes(attributes)
+ keyword = lexer.consume_until(lambda c: c.isspace())
+ if keyword in ("struct", "enum", "variant"):
+ parse_declaration(keyword, attributes)
+ elif keyword == "endpoint" and not attributes:
+ parse_endpoint()
+ else:
+ raise RuntimeError(f"Expected 'endpoint', 'struct', 'enum' or 'variant', got '{keyword}'")
for endpoint in endpoints:
endpoint.validate()
- return endpoints
+ return document
def class_declaration(endpoint: Endpoint, name: str) -> str:
@@ -999,39 +1214,230 @@ def write_endpoint(out: TextIO, implementation: TextIO, endpoint: Endpoint) -> N
write_bound_proxy_class(out, implementation, endpoint)
+def cpp_field_value(declaration: Declaration, member: Parameter) -> str:
+ if declaration.has_accessors():
+ return f"value.{member.name}()"
+ return f"value.{member.name}"
+
+
+def max_size(member: Parameter) -> Optional[str]:
+ """The MaxBytes or MaxCount of a field, which bounds the size that its string, byte buffer or vector goes with."""
+ for name, argument in field_attributes(member):
+ if name in ("MaxBytes", "MaxCount"):
+ return argument
+ return None
+
+
+def cpp_field_decode(member: Parameter) -> str:
+ size = max_size(member)
+ if size is not None:
+ return f"TRY((decoder.decode_with_max_size<{member.type}>({size})))"
+ return f"TRY((decoder.decode<{member.type}>()))"
+
+
+def cpp_field_refusals(declaration: Declaration, member: Parameter) -> List[FieldRefusal]:
+ return field_refusals(member, cpp_field_value(declaration, member), "")
+
+
+def write_cpp_definition(out: TextIO, declaration: Declaration) -> None:
+ name = declaration.name.rpartition("::")[2]
+ out.write("\n")
+ if declaration.kind == "enum":
+ out.write(f"enum class {name} : {declaration.underlying_type} {{\n")
+ for member in declaration.members:
+ out.write(f" {member.name},\n")
+ out.write("};\n")
+ elif declaration.kind == "struct" and not declaration.members:
+ out.write(f"struct {name} {{ }};\n")
+ elif declaration.kind == "struct":
+ out.write(f"struct {name} {{\n")
+ for member in declaration.members:
+ out.write(f" {member.type} {member.name} {{}};\n")
+ out.write("};\n")
+ else:
+ alternatives = ", ".join(member.type for member in declaration.members)
+ out.write(f"using {name} = Variant<{alternatives}>;\n")
+
+
+def write_cpp_enum_codec(out: TextIO, declaration: Declaration) -> None:
+ name = declaration.name
+ underlying_type = declaration.underlying_type
+
+ # NB: An enum goes as the position of its value in the declaration, which C++ need not number the same way.
+ out.write(f"""
+template<>
+ErrorOr<void> encode(Encoder& encoder, {name} const& value)
+{{
+ switch (value) {{
+""")
+ for index, member in enumerate(declaration.members):
+ out.write(f" case {name}::{member.name}:\n return encoder.encode<{underlying_type}>({index});\n")
+ out.write(f""" }}
+ return Error::from_string_literal("IPC encode: Invalid {name}");
+}}
+
+template<>
+ErrorOr<{name}> decode(Decoder& decoder)
+{{
+ switch (TRY(decoder.decode<{underlying_type}>())) {{
+""")
+ for index, member in enumerate(declaration.members):
+ out.write(f" case {index}:\n return {name}::{member.name};\n")
+ out.write(f""" default:
+ return Error::from_string_literal("IPC decode: Invalid {name}");
+ }}
+}}
+""")
+
+
+def write_cpp_struct_codec(out: TextIO, declaration: Declaration) -> None:
+ name = declaration.name
+ if not declaration.members:
+ out.write(f"""
+template<>
+ErrorOr<void> encode(Encoder&, {name} const&)
+{{
+ return {{}};
+}}
+
+template<>
+ErrorOr<{name}> decode(Decoder&)
+{{
+ return {name} {{}};
+}}
+""")
+ return
+
+ # NB: Each field must have the type it is declared with, which is the type the decoder reads.
+ out.write(f"\ntemplate<>\nErrorOr<void> encode(Encoder& encoder, {name} const& value)\n{{\n")
+ for member in declaration.members:
+ field_type = f"decltype({cpp_field_value(declaration, member)})"
+ if declaration.has_accessors():
+ field_type = f"RemoveCVReference<{field_type}>"
+ out.write(f" static_assert(IsSame<{field_type}, {member.type}>);\n")
+ for member in declaration.members:
+ for refusal in cpp_field_refusals(declaration, member):
+ out.write(f" if ({refusal.cpp_condition})\n")
+ out.write(
+ f' return Error::from_string_literal("IPC encode: {name}::{member.name} {refusal.meaning}");\n'
+ )
+ for member in declaration.members:
+ out.write(f" TRY(encoder.encode({cpp_field_value(declaration, member)}));\n")
+ out.write(" return {};\n}\n")
+
+ checks = [
+ (member, refusal)
+ for member in declaration.members
+ for refusal in cpp_field_refusals(declaration, member)
+ if refusal.is_checked_after_decoding()
+ ]
+ out.write(f"\ntemplate<>\nErrorOr<{name}> decode(Decoder& decoder)\n{{\n")
+ out.write(f" auto value = {name} {{\n" if checks else f" return {name} {{\n")
+ for member in declaration.members:
+ designator = "" if declaration.has_accessors() else f".{member.name} = "
+ out.write(f" {designator}{cpp_field_decode(member)},\n")
+ out.write(" };\n")
+ for member, refusal in checks:
+ out.write(f" if ({refusal.cpp_condition})\n")
+ out.write(
+ f' return Error::from_string_literal("IPC decode: {name}::{member.name} {refusal.meaning}");\n'
+ )
+ if checks:
+ out.write(" return value;\n")
+ out.write("}\n")
+
+
+def write_cpp_declarations(header: TextIO, implementation: TextIO, document: Document, export_macro: str) -> None:
+ namespace = ""
+ for declaration in document.declarations:
+ if declaration.is_existing_cpp():
+ continue
+ declaration_namespace = declaration.name.rpartition("::")[0]
+ if declaration_namespace != namespace:
+ if namespace:
+ header.write(f"\n}} // namespace {namespace}\n")
+ header.write(f"\nnamespace {declaration_namespace} {{\n")
+ namespace = declaration_namespace
+ write_cpp_definition(header, declaration)
+ if namespace:
+ header.write(f"\n}} // namespace {namespace}\n")
+
+ # NB: A variant goes as the AK::Variant it is, which LibIPC already knows how to encode.
+ codec_declarations = [declaration for declaration in document.declarations if declaration.kind != "variant"]
+ if not codec_declarations:
+ return
+
+ export = f"{export_macro} " if export_macro else ""
+ header.write("\nnamespace IPC {\n")
+ implementation.write("\nnamespace IPC {\n")
+ for declaration in codec_declarations:
+ header.write(f"""
+template<>
+{export}ErrorOr<void> encode(Encoder&, {declaration.name} const&);
+
+template<>
+{export}ErrorOr<{declaration.name}> decode(Decoder&);
+""")
+ if declaration.kind == "enum":
+ write_cpp_enum_codec(implementation, declaration)
+ else:
+ write_cpp_struct_codec(implementation, declaration)
+ header.write("\n} // namespace IPC\n")
+ implementation.write("\n} // namespace IPC\n")
+
+
def build(
out: TextIO,
- endpoints: List[Endpoint],
+ document: Document,
implementation: TextIO,
header_name: str,
library: str = "",
+ export_macro: str = "",
) -> None:
+ """Writes the C++ code of an IPC file. The export macro is that of the library's Export.h, if it has one."""
out.write("#pragma once\n\n")
- export_macro = ""
- if library:
- export_macro = f"{library.removeprefix('Lib').upper()}_API"
+ endpoint_export_macro = ""
+ if document.endpoints and library:
+ endpoint_export_macro = f"{library.removeprefix('Lib').upper()}_API"
out.write(f"""\
#if __has_include(<{library}/Export.h>)
#include <{library}/Export.h>
#else
-#define {export_macro}
+#define {endpoint_export_macro}
#endif
""")
- for endpoint in endpoints:
- for include in endpoint.includes:
- out.write(f"{include}\n")
- # Message members need complete owning types even when an endpoint has no explicit includes.
- parameter_types = " ".join(
- parameter.type
- for endpoint in endpoints
- for message in endpoint.messages
- for parameter in message.inputs + message.outputs
+ elif export_macro:
+ out.write(f"#include <{library}/Export.h>\n")
+ for include in document.includes:
+ out.write(f"{include}\n")
+ # Message and struct members need complete owning types even when the file has no explicit includes.
+ defined_declarations = [declaration for declaration in document.declarations if not declaration.is_existing_cpp()]
+ member_types = " ".join(
+ [
+ parameter.type
+ for endpoint in document.endpoints
+ for message in endpoint.messages
+ for parameter in message.inputs + message.outputs
+ ]
+ + [member.type for declaration in defined_declarations for member in declaration.members]
)
- for name in ["ByteBuffer", "ByteString", "JsonValue", "Optional", "String", "Utf16String", "Vector"]:
- if re.search(rf"\b{name}\b", parameter_types):
- out.write(f"#include <AK/{name}.h>\n")
- out.write("""\
+ names = ["ByteBuffer", "ByteString", "JsonValue", "Optional", "String", "Utf16String", "Vector"]
+ names = [name for name in names if re.search(rf"\b{name}\b", member_types)]
+ # NB: A struct defined here holds any AK type its fields name, such as a HashMap.
+ for declaration in defined_declarations:
+ for member in declaration.members:
+ for name in re.findall(r"(?<![\w:])[A-Z]\w*(?![\w:])", member.type):
+ if name not in names and (AK_DIRECTORY / f"{name}.h").exists():
+ names.append(name)
+ if any(declaration.kind == "variant" for declaration in defined_declarations) and "Variant" not in names:
+ names.append("Variant")
+ for name in sorted(names):
+ out.write(f"#include <AK/{name}.h>\n")
+
+ implementation.write(f'#include "{header_name}"\n\n')
+ if document.endpoints:
+ out.write("""\
#include <AK/Error.h>
#include <AK/OwnPtr.h>
#include <AK/Platform.h>
@@ -1054,8 +1460,7 @@ class ConnectionBase;
#pragma clang diagnostic ignored "-Wdefaulted-function-deleted"
#endif
""")
- implementation.write(f'#include "{header_name}"\n\n')
- implementation.write("""\
+ implementation.write("""\
#include <AK/MemoryStream.h>
#include <AK/Utf8View.h>
#include <LibIPC/Attachment.h>
@@ -1063,10 +1468,23 @@ class ConnectionBase;
#include <LibIPC/Decoder.h>
#include <LibIPC/Encoder.h>
""")
- for endpoint in endpoints:
- endpoint.export_macro = export_macro
+ else:
+ out.write("#include <LibIPC/Forward.h>\n")
+ implementation.write("#include <LibIPC/Decoder.h>\n#include <LibIPC/Encoder.h>\n")
+ if any(
+ name == "Finite"
+ for declaration in document.declarations
+ for member in declaration.members
+ for name, _ in field_attributes(member)
+ ):
+ implementation.write("#include <math.h>\n")
+
+ write_cpp_declarations(out, implementation, document, export_macro)
+ for endpoint in document.endpoints:
+ endpoint.export_macro = endpoint_export_macro
write_endpoint(out, implementation, endpoint)
- out.write("""
+ if document.endpoints:
+ out.write("""
#if defined(AK_COMPILER_CLANG)
#pragma clang diagnostic pop
#endif
@@ -1302,9 +1720,180 @@ pub mod {rust_field_name(snake_case(endpoint.name))} {{
out.write(" }\n}\n")
-def build_rust(out: TextIO, endpoints: List[Endpoint]) -> None:
+def rust_field_refusals(member: Parameter, value: str) -> List[FieldRefusal]:
+ return field_refusals(member, "", f"{value}.{rust_field_name(member.name)}")
+
+
+def write_rust_enum(out: TextIO, declaration: Declaration, name: str) -> None:
+ underlying_type = declaration.underlying_type
+ out.write(f"""
+#[allow(dead_code, non_camel_case_types)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr({underlying_type})]
+pub enum {name} {{
+""")
+ for member in declaration.members:
+ out.write(f" {rust_field_name(member.name)},\n")
+ out.write(f"""}}
+
+impl ::libipc_rust::wire::Encode for {name} {{
+ fn encode(&self, encoder: &mut ::libipc_rust::wire::Encoder) -> ::std::result::Result<(), ::libipc_rust::wire::EncodeError> {{
+ encoder.encode(&(*self as {underlying_type}))
+ }}
+}}
+
+impl ::libipc_rust::wire::Decode for {name} {{
+ fn decode(decoder: &mut ::libipc_rust::wire::Decoder<'_>) -> ::std::result::Result<Self, ::libipc_rust::wire::DecodeError> {{
+ match decoder.decode::<{underlying_type}>()? {{
+""")
+ for index, member in enumerate(declaration.members):
+ out.write(f" {index} => ::std::result::Result::Ok(Self::{rust_field_name(member.name)}),\n")
+ out.write(f""" _ => ::std::result::Result::Err(::libipc_rust::wire::DecodeError::InvalidValue("{declaration.name}")),
+ }}
+ }}
+}}
+""")
+
+
+def write_rust_struct(out: TextIO, declaration: Declaration, name: str) -> None:
+ fields = [(rust_field_name(member.name), rust_type(member.type)) for member in declaration.members]
+ out.write("\n#[allow(dead_code, non_camel_case_types)]\n")
+ if not fields:
+ out.write(f"""pub struct {name};
+
+impl ::libipc_rust::wire::Encode for {name} {{
+ fn encode(&self, _: &mut ::libipc_rust::wire::Encoder) -> ::std::result::Result<(), ::libipc_rust::wire::EncodeError> {{
+ ::std::result::Result::Ok(())
+ }}
+}}
+
+impl ::libipc_rust::wire::Decode for {name} {{
+ fn decode(_: &mut ::libipc_rust::wire::Decoder<'_>) -> ::std::result::Result<Self, ::libipc_rust::wire::DecodeError> {{
+ ::std::result::Result::Ok(Self)
+ }}
+}}
+""")
+ return
+
+ out.write(f"pub struct {name} {{\n")
+ for field_name, field_type in fields:
+ out.write(f" pub {field_name}: {field_type},\n")
+ out.write("}\n")
+
+ refusals = [(member, refusal) for member in declaration.members for refusal in rust_field_refusals(member, "self")]
+ if refusals:
+ out.write(f"""
+impl {name} {{
+ fn validate(&self) -> ::std::result::Result<(), ::libipc_rust::wire::EncodeError> {{
+""")
+ for member, refusal in refusals:
+ out.write(f""" if {refusal.rust_condition} {{
+ return ::std::result::Result::Err(::libipc_rust::wire::EncodeError::InvalidValue("{declaration.name}::{member.name}"));
+ }}
+""")
+ out.write(" ::std::result::Result::Ok(())\n }\n}\n")
+ validate = " self.validate()?;\n" if refusals else ""
+
+ out.write(f"""
+impl ::libipc_rust::wire::Encode for {name} {{
+ fn encode(&self, encoder: &mut ::libipc_rust::wire::Encoder) -> ::std::result::Result<(), ::libipc_rust::wire::EncodeError> {{
+{validate}""")
+ for field_name, _ in fields:
+ out.write(f" encoder.encode(&self.{field_name})?;\n")
+ out.write(f""" ::std::result::Result::Ok(())
+ }}
+
+ fn encode_owned(self, encoder: &mut ::libipc_rust::wire::Encoder) -> ::std::result::Result<(), ::libipc_rust::wire::EncodeError> {{
+{validate}""")
+ for field_name, _ in fields:
+ out.write(f" encoder.encode_owned(self.{field_name})?;\n")
+ checks = [
+ (member, refusal)
+ for member in declaration.members
+ for refusal in rust_field_refusals(member, "value")
+ if refusal.is_checked_after_decoding()
+ ]
+ out.write(f""" ::std::result::Result::Ok(())
+ }}
+}}
+
+impl ::libipc_rust::wire::Decode for {name} {{
+ fn decode(decoder: &mut ::libipc_rust::wire::Decoder<'_>) -> ::std::result::Result<Self, ::libipc_rust::wire::DecodeError> {{
+""")
+ out.write(" let value = Self {\n" if checks else " ::std::result::Result::Ok(Self {\n")
+ for member in declaration.members:
+ size = max_size(member)
+ decode = "decoder.decode()?" if size is None else f"decoder.decode_with_max_size({size})?"
+ out.write(f" {rust_field_name(member.name)}: {decode},\n")
+ if not checks:
+ out.write(" })\n }\n}\n")
+ return
+ out.write(" };\n")
+ for member, refusal in checks:
+ out.write(f""" if {refusal.rust_condition} {{
+ return ::std::result::Result::Err(::libipc_rust::wire::DecodeError::InvalidValue("{declaration.name}::{member.name}"));
+ }}
+""")
+ out.write(""" ::std::result::Result::Ok(value)
+ }
+}
+""")
+
+
+def write_rust_variant(out: TextIO, declaration: Declaration, name: str) -> None:
+ alternatives = [(rust_field_name(member.name), rust_type(member.type)) for member in declaration.members]
+ out.write(f"""
+#[allow(dead_code, non_camel_case_types)]
+pub enum {name} {{
+""")
+ for alternative, alternative_type in alternatives:
+ out.write(f" {alternative}({alternative_type}),\n")
+ out.write(f"""}}
+
+// NB: A variant goes as the index of its alternative, then the alternative, as an AK::Variant does.
+impl ::libipc_rust::wire::Encode for {name} {{
+""")
+ for function, receiver, encode in (("encode", "&self", "encode"), ("encode_owned", "self", "encode_owned")):
+ out.write(f""" fn {function}({receiver}, encoder: &mut ::libipc_rust::wire::Encoder) -> ::std::result::Result<(), ::libipc_rust::wire::EncodeError> {{
+ match self {{
+""")
+ for index, (alternative, _) in enumerate(alternatives):
+ out.write(f""" Self::{alternative}(value) => {{
+ encoder.encode(&{index}u8)?;
+ encoder.{encode}(value)
+ }}
+""")
+ out.write(" }\n }\n")
+ if function == "encode":
+ out.write("\n")
+ out.write(f"""}}
+
+impl ::libipc_rust::wire::Decode for {name} {{
+ fn decode(decoder: &mut ::libipc_rust::wire::Decoder<'_>) -> ::std::result::Result<Self, ::libipc_rust::wire::DecodeError> {{
+ match decoder.decode::<u8>()? {{
+""")
+ for index, (alternative, _) in enumerate(alternatives):
+ out.write(f" {index} => ::std::result::Result::Ok(Self::{alternative}(decoder.decode()?)),\n")
+ out.write(f""" _ => ::std::result::Result::Err(::libipc_rust::wire::DecodeError::InvalidValue("{declaration.name}")),
+ }}
+ }}
+}}
+""")
+
+
+def build_rust(out: TextIO, document: Document) -> None:
out.write("// NB: Generated by the IPC endpoint compiler.\n")
- for endpoint in endpoints:
+ # NB: Declared types refer to each other, and endpoints refer to them, as crate::ipc_types::Namespace_Name, so the
+ # crate includes this file in its ipc_types module.
+ for declaration in document.declarations:
+ name = rust_field_name(declaration.rust_name())
+ if declaration.kind == "enum":
+ write_rust_enum(out, declaration, name)
+ elif declaration.kind == "struct":
+ write_rust_struct(out, declaration, name)
+ else:
+ write_rust_variant(out, declaration, name)
+ for endpoint in document.endpoints:
write_rust_endpoint(out, endpoint)
@@ -1317,6 +1906,9 @@ def main():
parser.add_argument(
"--library", default="", help="Owning library, e.g. LibWebCommon; determines the export header and macro"
)
+ parser.add_argument(
+ "--export-macro", default="", help="Export macro of the owning library, if it exports symbols explicitly"
+ )
parser.add_argument("--rust-output", help="Generated Rust module")
args = parser.parse_args()
if not args.output and not args.rust_output:
@@ -1325,7 +1917,7 @@ def main():
parser.error("--output and --implementation must be used together")
with open(args.input, "r", encoding="utf-8") as input_file:
- endpoints = parse(input_file.read())
+ document = parse(input_file.read())
if args.output:
with (
@@ -1334,15 +1926,16 @@ def main():
):
build(
output_file,
- endpoints,
+ document,
implementation_file,
args.header_name or Path(args.output).name,
args.library,
+ args.export_macro,
)
if args.rust_output:
with open(args.rust_output, "w", encoding="utf-8") as output_file:
- build_rust(output_file, endpoints)
+ build_rust(output_file, document)
if __name__ == "__main__":
diff --git a/Meta/Linters/lint_ipc.py b/Meta/Linters/lint_ipc.py
index 1506c5ad39c..d42f3754506 100755
--- a/Meta/Linters/lint_ipc.py
+++ b/Meta/Linters/lint_ipc.py
@@ -6,6 +6,7 @@
# SPDX-License-Identifier: BSD-2-Clause
import argparse
+import re
import sys
from collections import defaultdict
@@ -18,6 +19,7 @@ sys.path.append(str(Path(__file__).resolve().parent.parent))
from Utils.utils import string_hash
ENDPOINT_PREFIX = "endpoint "
+TYPE_DECLARATION = re.compile(r"(\[[^\]]*\]\s*)?(struct|enum|variant)\s")
def main() -> int:
@@ -35,11 +37,14 @@ def main() -> int:
for path in args.ipc_files:
endpoint_name = ""
+ declares_types = False
try:
with open(path, "r", encoding="utf-8") as ipc_file:
for line in ipc_file:
line = line.strip()
+ if TYPE_DECLARATION.match(line):
+ declares_types = True
if not line.startswith(ENDPOINT_PREFIX):
continue
@@ -53,6 +58,10 @@ def main() -> int:
report_error(f"Cannot open '{path}': {error}")
continue
+ # NB: A file may declare only types, which have no magic number.
+ if not endpoint_name and declares_types:
+ continue
+
if not endpoint_name:
report_error(f"Could not detect endpoint name in file '{path}'")
continue
diff --git a/Tests/LibIPC/RustEchoServer.ipc b/Tests/LibIPC/RustEchoServer.ipc
index 9ecc6663b0e..d5f7bb9d573 100644
--- a/Tests/LibIPC/RustEchoServer.ipc
+++ b/Tests/LibIPC/RustEchoServer.ipc
@@ -4,6 +4,20 @@
#include <AK/Utf16String.h>
#include <LibIPC/File.h>
+enum RustEcho::Shape : u8 { Circle, Square }
+
+struct RustEcho::Record {
+ [NonZero] u64 id;
+ [MaxBytes=8] String label;
+ [MaxBytes=8] ByteString name;
+ [MaxBytes=8] ByteBuffer bytes;
+ [MaxCount=3] Vector<u16> values;
+ [Finite] double scale;
+ RustEcho::Shape shape;
+}
+
+variant RustEcho::Value { Record RustEcho::Record, Number u32, Shape RustEcho::Shape }
+
endpoint RustEchoServer
{
echo(u32 number, String text, Utf16String utf16_text, Vector<Optional<i64>> values, ByteBuffer bytes) => (u32 number, String text, Utf16String utf16_text, Vector<Optional<i64>> values, ByteBuffer bytes)
@@ -11,4 +25,5 @@ endpoint RustEchoServer
echo_files(Vector<IPC::File> files) => (Vector<IPC::File> files)
stop() =|
echo_utf8([UTF8] ByteString text, [UTF8] ByteBuffer bytes) => ([UTF8] ByteString text, [UTF8] ByteBuffer bytes)
+ echo_value(RustEcho::Value value) => (RustEcho::Value value)
}
diff --git a/Tests/LibIPC/RustEchoServer/src/lib.rs b/Tests/LibIPC/RustEchoServer/src/lib.rs
index 9ab02e6fa42..df5adf44961 100644
--- a/Tests/LibIPC/RustEchoServer/src/lib.rs
+++ b/Tests/LibIPC/RustEchoServer/src/lib.rs
@@ -24,11 +24,15 @@ use libipc_rust::{
transport::TransportMachPort as Transport,
};
-include!(env!("RUST_ECHO_SERVER_ENDPOINT"));
+// NB: The generated code names the types RustEchoServer.ipc declares as crate::ipc_types::Namespace_Name.
+mod ipc_types {
+ include!(env!("RUST_ECHO_SERVER_ENDPOINT"));
+}
+use ipc_types::rust_echo_server;
use rust_echo_server::{
Message,
- messages::{EchoFilesResponse, EchoResponse, EchoUtf8Response, WriteToFileResponse},
+ messages::{EchoFilesResponse, EchoResponse, EchoUtf8Response, EchoValueResponse, WriteToFileResponse},
};
#[cfg(test)]
@@ -73,11 +77,13 @@ fn serve(transport: Transport) {
bytes: request.bytes,
},
),
+ Message::EchoValue(request) => reply(&transport, EchoValueResponse { value: request.value }),
Message::Stop(_) => break,
Message::EchoResponse(_)
| Message::WriteToFileResponse(_)
| Message::EchoFilesResponse(_)
- | Message::EchoUtf8Response(_) => {
+ | Message::EchoUtf8Response(_)
+ | Message::EchoValueResponse(_) => {
eprintln!("RustEchoServer: Refusing a response sent to it");
break;
}
diff --git a/Tests/LibIPC/RustEchoServer/src/tests.rs b/Tests/LibIPC/RustEchoServer/src/tests.rs
index dec2dff261a..16fcc7b37a1 100644
--- a/Tests/LibIPC/RustEchoServer/src/tests.rs
+++ b/Tests/LibIPC/RustEchoServer/src/tests.rs
@@ -185,3 +185,42 @@ fn server_flushes_posted_replies_before_returning_on_errors() {
assert!(client.receive().is_none());
}
}
+
+#[test]
+fn generated_encoders_refuse_what_decoders_refuse() {
+ use crate::ipc_types::{RustEcho_Record, RustEcho_Shape};
+ use libipc_rust::wire::{ByteString, Utf8String};
+ use libipc_rust::{EncodeError, Encoder};
+
+ let record = || RustEcho_Record {
+ id: 7,
+ label: Utf8String::from("label"),
+ name: ByteString(b"name".to_vec()),
+ bytes: b"bytes".to_vec(),
+ values: vec![1, 2, 3],
+ scale: 1.5,
+ shape: RustEcho_Shape::Square,
+ };
+ assert!(Encoder::new().encode(&record()).is_ok());
+ let invalidations: [fn(&mut RustEcho_Record); 7] = [
+ |record| record.id = 0,
+ |record| record.label = Utf8String::from("123456789"),
+ |record| record.name = ByteString(b"123456789".to_vec()),
+ |record| record.bytes = b"123456789".to_vec(),
+ |record| record.values.push(4),
+ |record| record.scale = f64::NAN,
+ |record| record.scale = f64::INFINITY,
+ ];
+ for invalidate in invalidations {
+ let mut invalid = record();
+ invalidate(&mut invalid);
+ assert!(matches!(
+ Encoder::new().encode(&invalid),
+ Err(EncodeError::InvalidValue(_))
+ ));
+ assert!(matches!(
+ Encoder::new().encode_owned(invalid),
+ Err(EncodeError::InvalidValue(_))
+ ));
+ }
+}
diff --git a/Tests/LibIPC/TestDecoder.cpp b/Tests/LibIPC/TestDecoder.cpp
index 68f819a4494..fcb4a4ad914 100644
--- a/Tests/LibIPC/TestDecoder.cpp
+++ b/Tests/LibIPC/TestDecoder.cpp
@@ -7,12 +7,15 @@
#include <AK/ByteBuffer.h>
#include <AK/MemoryStream.h>
#include <AK/NumericLimits.h>
+#include <AK/Optional.h>
#include <AK/Queue.h>
+#include <AK/String.h>
#include <AK/Vector.h>
#include <LibCore/AnonymousBuffer.h>
#include <LibCore/System.h>
#include <LibIPC/Attachment.h>
#include <LibIPC/Decoder.h>
+#include <LibIPC/Encoder.h>
#include <LibIPC/File.h>
#include <LibTest/TestCase.h>
@@ -120,3 +123,27 @@ TEST_CASE(decode_anonymous_buffer_refuses_a_size_larger_than_its_backing)
EXPECT(decode_with_claimed_size(1 * MiB).is_error());
}
#endif
+
+TEST_CASE(sizes_are_bounded_before_contents_and_only_within_the_value)
+{
+ IPC::MessageBuffer buffer;
+ IPC::Encoder encoder { buffer };
+ MUST(encoder.encode("123456789"sv));
+ MUST(encoder.encode(Optional<String> {}));
+ MUST(encoder.encode("123456789"sv));
+ auto bytes = buffer.take_data();
+
+ {
+ FixedMemoryStream stream { bytes.span() };
+ Queue<IPC::Attachment> attachments;
+ IPC::Decoder decoder { stream, attachments };
+ EXPECT(decoder.decode_with_max_size<String>(8).is_error());
+ }
+
+ FixedMemoryStream stream { bytes.span() };
+ Queue<IPC::Attachment> attachments;
+ IPC::Decoder decoder { stream, attachments };
+ EXPECT_EQ(MUST(decoder.decode_with_max_size<String>(9)), "123456789"sv);
+ EXPECT(!MUST(decoder.decode_with_max_size<Optional<String>>(4)).has_value());
+ EXPECT_EQ(MUST(decoder.decode<String>()), "123456789"sv);
+}
diff --git a/Tests/LibIPC/TestRustEchoServer.cpp b/Tests/LibIPC/TestRustEchoServer.cpp
index cbda5116ba9..96107db454f 100644
--- a/Tests/LibIPC/TestRustEchoServer.cpp
+++ b/Tests/LibIPC/TestRustEchoServer.cpp
@@ -4,12 +4,19 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+// NB: The generated header comes first, so that it declares its codecs before anything else in LibIPC is seen.
+#include <RustEchoServerEndpoint.h>
+
+#include <AK/Function.h>
+#include <AK/MemoryStream.h>
#include <LibCore/System.h>
+#include <LibIPC/Decoder.h>
+#include <LibIPC/Encoder.h>
#include <LibIPC/Transport.h>
#include <LibTest/TestCase.h>
-#include <RustEchoServerEndpoint.h>
#include <fcntl.h>
#include <limits.h>
+#include <math.h>
#include <sys/resource.h>
// NB: Starts the Rust endpoint, which the IPC compiler generated Rust code for from the same definition as the C++ code
@@ -215,3 +222,118 @@ TEST_CASE(cpp_and_rust_decoders_accept_trailing_bytes)
auto response = receive<Messages::RustEchoServer::EchoUtf8Response>(*transport);
EXPECT_EQ(response->text(), "hello"sv);
}
+
+static RustEcho::Record make_record()
+{
+ return RustEcho::Record {
+ .id = 7,
+ .label = "label"_string,
+ .name = "name"sv,
+ .bytes = MUST(ByteBuffer::copy("bytes"sv.bytes())),
+ .values = { 1, 2, 3 },
+ .scale = 1.5,
+ .shape = RustEcho::Shape::Square,
+ };
+}
+
+static IPC::MessageDataType encode_value(RustEcho::Value const& value)
+{
+ IPC::MessageBuffer buffer;
+ IPC::Encoder encoder { buffer };
+ MUST(encoder.encode(value));
+ return buffer.take_data();
+}
+
+static void expect_refused_by_cpp_and_rust(ReadonlyBytes message)
+{
+ Queue<IPC::Attachment> attachments;
+ EXPECT(RustEchoServerEndpoint::decode_message(message, attachments).is_error());
+
+ auto transport = start_server();
+ Vector<IPC::Attachment> outgoing_attachments;
+ IPC::MessageDataType bytes;
+ bytes.append(message.data(), message.size());
+ MUST(transport->post_message(move(bytes), outgoing_attachments));
+ // NB: A valid message follows, so the Rust end either closes the connection or answers it, and never leaves this
+ // waiting.
+ send(*transport, Messages::RustEchoServer::EchoValue::static_encode(RustEcho::Value { 1u }));
+ auto answered = false;
+ auto should_shutdown = IPC::Transport::ShouldShutdown::No;
+ while (!answered && should_shutdown == IPC::Transport::ShouldShutdown::No) {
+ transport->wait_until_readable();
+ should_shutdown = transport->read_as_many_messages_as_possible_without_blocking([&](auto&&) { answered = true; });
+ }
+ if (answered)
+ FAIL("The Rust endpoint answered a message after one it should have refused");
+}
+
+// NB: Encodes a message with a record field by field, past the generated encoder, which refuses invalid records.
+static IPC::MessageDataType encode_record_message_unchecked(RustEcho::Record const& record)
+{
+ IPC::MessageBuffer buffer;
+ IPC::Encoder encoder { buffer };
+ MUST(encoder.encode(Messages::RustEchoServer::EchoValue::ENDPOINT_MAGIC));
+ MUST(encoder.encode(Messages::RustEchoServer::EchoValue::static_message_id()));
+ MUST(encoder.encode<u8>(0));
+ MUST(encoder.encode(record.id));
+ MUST(encoder.encode(record.label));
+ MUST(encoder.encode(record.name));
+ MUST(encoder.encode(record.bytes));
+ MUST(encoder.encode(record.values));
+ MUST(encoder.encode(record.scale));
+ MUST(encoder.encode(record.shape));
+ return buffer.take_data();
+}
+
+TEST_CASE(declared_types_make_a_round_trip_through_rust)
+{
+ auto transport = start_server();
+ for (RustEcho::Value value : { RustEcho::Value { make_record() }, RustEcho::Value { 42u }, RustEcho::Value { RustEcho::Shape::Circle } }) {
+ send(*transport, Messages::RustEchoServer::EchoValue::static_encode(value));
+ auto response = receive<Messages::RustEchoServer::EchoValueResponse>(*transport);
+ EXPECT_EQ(encode_value(response->value()), encode_value(value));
+ }
+}
+
+TEST_CASE(declared_types_are_checked_by_cpp_and_rust)
+{
+ EXPECT_EQ(encode_record_message_unchecked(make_record()), MUST(Messages::RustEchoServer::EchoValue::static_encode(RustEcho::Value { make_record() })).take_data());
+
+ Vector<Function<void(RustEcho::Record&)>> invalidations;
+ invalidations.append([](auto& record) { record.id = 0; });
+ invalidations.append([](auto& record) { record.label = "123456789"_string; });
+ invalidations.append([](auto& record) { record.name = "123456789"sv; });
+ invalidations.append([](auto& record) { record.bytes = MUST(ByteBuffer::copy("123456789"sv.bytes())); });
+ invalidations.append([](auto& record) { record.values.append(4); });
+ invalidations.append([](auto& record) { record.scale = NAN; });
+ invalidations.append([](auto& record) { record.scale = INFINITY; });
+ for (auto& invalidate : invalidations) {
+ auto record = make_record();
+ invalidate(record);
+ EXPECT(Messages::RustEchoServer::EchoValue::static_encode(RustEcho::Value { record }).is_error());
+ expect_refused_by_cpp_and_rust(encode_record_message_unchecked(record));
+ }
+
+ // NB: The variant's index follows the endpoint magic and message ID, and a shape follows its index.
+ auto message = MUST(Messages::RustEchoServer::EchoValue::static_encode(RustEcho::Value { RustEcho::Shape::Square })).take_data();
+ message[9] = 2;
+ expect_refused_by_cpp_and_rust(message);
+ message[8] = 3;
+ message[9] = 0;
+ expect_refused_by_cpp_and_rust(message);
+}
+
+TEST_CASE(declared_enums_are_checked_wherever_they_are_encoded)
+{
+ // NB: This file encodes and decodes the enum itself, which must use its generated codec and not LibIPC's codec
+ // for any enum, which takes every value.
+ IPC::MessageBuffer buffer;
+ IPC::Encoder encoder { buffer };
+ EXPECT(encoder.encode(static_cast<RustEcho::Shape>(2)).is_error());
+
+ Array<u8, 1> invalid_shape { 2 };
+ FixedMemoryStream stream { invalid_shape.span() };
+ Queue<IPC::Attachment> attachments;
+ IPC::Decoder decoder { stream, attachments };
+ EXPECT(decoder.decode<RustEcho::Shape>().is_error());
+}
diff --git a/Tests/Meta/test-ipc-generator.py b/Tests/Meta/test-ipc-generator.py
index 2a5796ebe1a..a52a9479800 100644
--- a/Tests/Meta/test-ipc-generator.py
+++ b/Tests/Meta/test-ipc-generator.py
@@ -206,6 +206,300 @@ void TestClientPageProxy::async_page_changed(u32 revision) const
self.assertIn("cannot be routed", str(raised.exception))
+DECLARATIONS = """\
+#include <LibIPC/File.h>
+
+enum Test::Shape : u8 { Circle, Square }
+
+struct Test::Record {
+ [NonZero] u64 id;
+ [MaxBytes=8] String label;
+ [MaxCount=3] Vector<u16> values;
+ [Finite] double scale;
+ Test::Shape shape;
+}
+
+variant Test::Value { Record Test::Record, Number u32, File IPC::File }
+
+[ExistingCpp]
+struct Web::Existing {
+ Optional<Test::Shape> shape;
+}
+
+[ExistingCpp, Accessors]
+struct Gfx::IntSize {
+ i32 width;
+ i32 height;
+}
+"""
+
+
+def generate_rust(contents: str) -> str:
+ output = io.StringIO()
+ build_rust(output, parse(contents))
+ return output.getvalue()
+
+
+class TestIPCGeneratorDeclarations(unittest.TestCase):
+ def test_declared_types_are_defined_in_cpp(self) -> None:
+ header, _ = generate_files(DECLARATIONS)
+ self.assertIn(
+ """\
+namespace Test {
+
+enum class Shape : u8 {
+ Circle,
+ Square,
+};
+
+struct Record {
+ u64 id {};
+ String label {};
+ Vector<u16> values {};
+ double scale {};
+ Test::Shape shape {};
+};
+
+using Value = Variant<Test::Record, u32, IPC::File>;
+
+} // namespace Test
+""",
+ header,
+ )
+ self.assertNotIn("struct Existing", header)
+ self.assertNotIn("class IntSize", header)
+ self.assertNotIn("LibIPC/Stub.h", header)
+ self.assertIn("#include <LibIPC/Forward.h>", header)
+
+ def test_codecs_are_declared_for_structs_and_enums_but_not_variants(self) -> None:
+ header = io.StringIO()
+ build(header, parse(DECLARATIONS), io.StringIO(), "TestTypes.h", "LibWebCommon", "WEBCOMMON_API")
+ self.assertIn("#pragma once\n\n#include <LibWebCommon/Export.h>\n", header.getvalue())
+ self.assertNotIn("#define", header.getvalue())
+ for name in ["Test::Shape", "Test::Record", "Web::Existing", "Gfx::IntSize"]:
+ self.assertIn(
+ f"template<>\nWEBCOMMON_API ErrorOr<void> encode(Encoder&, {name} const&);", header.getvalue()
+ )
+ self.assertIn(f"template<>\nWEBCOMMON_API ErrorOr<{name}> decode(Decoder&);", header.getvalue())
+ self.assertNotIn("Test::Value const&", header.getvalue())
+
+ def test_codecs_of_libraries_without_explicit_exports_are_not_exported(self) -> None:
+ header = io.StringIO()
+ build(header, parse(DECLARATIONS), io.StringIO(), "TestTypes.h", "LibGfx")
+ self.assertNotIn("Export.h", header.getvalue())
+ self.assertNotIn("GFX_API", header.getvalue())
+ self.assertIn("template<>\nErrorOr<void> encode(Encoder&, Gfx::IntSize const&);", header.getvalue())
+
+ def test_enums_go_as_the_position_of_their_value(self) -> None:
+ _, implementation = generate_files(DECLARATIONS)
+ self.assertIn(
+ """\
+ switch (value) {
+ case Test::Shape::Circle:
+ return encoder.encode<u8>(0);
+ case Test::Shape::Square:
+ return encoder.encode<u8>(1);
+ }
+""",
+ implementation,
+ )
+ self.assertIn(
+ """\
+ switch (TRY(decoder.decode<u8>())) {
+ case 0:
+ return Test::Shape::Circle;
+ case 1:
+ return Test::Shape::Square;
+ default:
+ return Error::from_string_literal("IPC decode: Invalid Test::Shape");
+ }
+""",
+ implementation,
+ )
+ rust = generate_rust(DECLARATIONS)
+ self.assertIn("#[repr(u8)]\npub enum Test_Shape {\n Circle,\n Square,\n}", rust)
+ self.assertIn("encoder.encode(&(*self as u8))", rust)
+ self.assertIn("1 => ::std::result::Result::Ok(Self::Square),", rust)
+ self.assertIn(
+ '_ => ::std::result::Result::Err(::libipc_rust::wire::DecodeError::InvalidValue("Test::Shape")),', rust
+ )
+
+ def test_sizes_are_bounded_before_contents_and_other_fields_are_checked_after_decoding(self) -> None:
+ _, implementation = generate_files(DECLARATIONS)
+ self.assertIn(
+ """\
+ auto value = Test::Record {
+ .id = TRY((decoder.decode<u64>())),
+ .label = TRY((decoder.decode_with_max_size<String>(8))),
+ .values = TRY((decoder.decode_with_max_size<Vector<u16>>(3))),
+ .scale = TRY((decoder.decode<double>())),
+ .shape = TRY((decoder.decode<Test::Shape>())),
+ };
+ if (value.id == 0)
+ return Error::from_string_literal("IPC decode: Test::Record::id is zero");
+ if (!isfinite(value.scale))
+ return Error::from_string_literal("IPC decode: Test::Record::scale is not finite");
+ return value;
+""",
+ implementation,
+ )
+ rust = generate_rust(DECLARATIONS)
+ self.assertIn(
+ """\
+ let value = Self {
+ id: decoder.decode()?,
+ label: decoder.decode_with_max_size(8)?,
+ values: decoder.decode_with_max_size(3)?,
+ scale: decoder.decode()?,
+ shape: decoder.decode()?,
+ };
+""",
+ rust,
+ )
+ for condition, field in [("value.id == 0", "id"), ("!value.scale.is_finite()", "scale")]:
+ self.assertIn(
+ f' if {condition} {{\n return ::std::result::Result::Err(::libipc_rust::wire::DecodeError::InvalidValue("Test::Record::{field}"));',
+ rust,
+ )
+
+ def test_encoders_refuse_what_decoders_refuse(self) -> None:
+ _, implementation = generate_files(DECLARATIONS)
+ for condition, message in [
+ ("value.id == 0", "id is zero"),
+ ("value.label.bytes().size() > 8", "label is too large"),
+ ("value.values.size() > 3", "values is too large"),
+ ("!isfinite(value.scale)", "scale is not finite"),
+ ]:
+ self.assertIn(
+ f' if ({condition})\n return Error::from_string_literal("IPC encode: Test::Record::{message}");\n',
+ implementation,
+ )
+ rust = generate_rust(DECLARATIONS)
+ for condition, field in [
+ ("self.id == 0", "id"),
+ ("self.label.as_bytes().len() > 8", "label"),
+ ("self.values.len() > 3", "values"),
+ ("!self.scale.is_finite()", "scale"),
+ ]:
+ self.assertIn(
+ f' if {condition} {{\n return ::std::result::Result::Err(::libipc_rust::wire::EncodeError::InvalidValue("Test::Record::{field}"));',
+ rust,
+ )
+ self.assertEqual(rust.count(" self.validate()?;\n"), 2)
+ for cpp_type, cpp_size, rust_size in [
+ ("ByteString", "length()", "0.len()"),
+ ("ByteBuffer", "size()", "len()"),
+ ]:
+ _, implementation = generate_files(f"struct Test::Text {{ [MaxBytes=4] {cpp_type} text; }}")
+ self.assertIn(f"if (value.text.{cpp_size} > 4)", implementation)
+ self.assertIn(
+ f"if self.text.{rust_size} > 4 {{",
+ generate_rust(f"struct Test::Text {{ [MaxBytes=4] {cpp_type} text; }}"),
+ )
+
+ def test_definitions_include_the_ak_types_their_fields_hold(self) -> None:
+ header, _ = generate_files("struct Test::Map { HashMap<u32, Optional<String>> entries; IPC::File file; }")
+ for name in ["HashMap", "Optional", "String"]:
+ self.assertIn(f"#include <AK/{name}.h>\n", header)
+ self.assertNotIn("#include <AK/File.h>", header)
+
+ def test_declared_codecs_use_the_export_macro_beside_endpoints(self) -> None:
+ header = io.StringIO()
+ contents = "struct Test::Value { u32 number; } endpoint Test { send(Test::Value value) =| }"
+ build(header, parse(contents), io.StringIO(), "TestEndpoint.h", "LibWebCommon", "WEBCOMMON_API")
+ self.assertIn(
+ "template<>\nWEBCOMMON_API ErrorOr<void> encode(Encoder&, Test::Value const&);", header.getvalue()
+ )
+ header = io.StringIO()
+ build(header, parse(contents), io.StringIO(), "TestEndpoint.h", "LibGfx")
+ self.assertIn("template<>\nErrorOr<void> encode(Encoder&, Test::Value const&);", header.getvalue())
+ self.assertIn("class GFX_API Test", header.getvalue())
+
+ def test_encoders_check_that_fields_have_their_declared_types(self) -> None:
+ _, implementation = generate_files(DECLARATIONS)
+ self.assertIn(" static_assert(IsSame<decltype(value.label), String>);\n", implementation)
+ self.assertIn(" static_assert(IsSame<RemoveCVReference<decltype(value.width())>, i32>);\n", implementation)
+
+ def test_existing_cpp_types_are_read_as_they_are_built(self) -> None:
+ _, implementation = generate_files(DECLARATIONS)
+ self.assertIn("TRY(encoder.encode(value.shape));", implementation)
+ self.assertIn(
+ "return Web::Existing {\n .shape = TRY((decoder.decode<Optional<Test::Shape>>())),\n };",
+ implementation,
+ )
+ self.assertIn("TRY(encoder.encode(value.width()));", implementation)
+ self.assertIn(
+ "return Gfx::IntSize {\n TRY((decoder.decode<i32>())),\n TRY((decoder.decode<i32>())),\n };",
+ implementation,
+ )
+ _, implementation = generate_files("struct Test::Map { HashMap<u32, u32> entries; }")
+ self.assertIn(".entries = TRY((decoder.decode<HashMap<u32, u32>>())),", implementation)
+
+ def test_variants_go_as_the_index_of_their_alternative(self) -> None:
+ rust = generate_rust(DECLARATIONS)
+ self.assertIn(
+ "pub enum Test_Value {\n Record(crate::ipc_types::Test_Record),\n Number(u32),\n File(::libipc_rust::wire::File),\n}",
+ rust,
+ )
+ self.assertIn(" Self::File(value) => {\n encoder.encode(&2u8)?;\n", rust)
+ self.assertIn(" 2 => ::std::result::Result::Ok(Self::File(decoder.decode()?)),\n", rust)
+ self.assertIn('InvalidValue("Test::Value")', rust)
+
+ def test_endpoints_use_declared_types_through_the_crate(self) -> None:
+ contents = DECLARATIONS + "endpoint Test { echo(Test::Value value) => (Test::Value value) }"
+ header, _ = generate_files(contents)
+ self.assertLess(header.index("using Value ="), header.index("namespace Messages::Test"))
+ self.assertIn("pub value: crate::ipc_types::Test_Value,", generate_rust(contents))
+
+ def test_names_and_attributes_are_read_without_surrounding_spaces(self) -> None:
+ document = parse("[ ExistingCpp , Accessors ] struct Gfx::IntSize { [ NonZero ] i32 width; }")
+ self.assertEqual(document.declarations[0].attributes, ["ExistingCpp", "Accessors"])
+ self.assertEqual(document.declarations[0].members[0].attributes, ["NonZero"])
+ document = parse("enum Test::Kind: u8 { A }")
+ self.assertEqual(document.declarations[0].name, "Test::Kind")
+ self.assertEqual(document.declarations[0].underlying_type, "u8")
+
+ def test_invalid_declarations_are_rejected(self) -> None:
+ for contents, error in [
+ ("struct Record { u32 id; }", "with a namespace"),
+ ("enum Test::Kind { A }", "Expected ':'"),
+ ("enum Test::Kind : int { A }", "sized integer"),
+ ("enum Test::Kind : u8 { }", "Empty enum"),
+ ("enum Test::Kind : i8 { " + ", ".join(f"V{i}" for i in range(129)) + " }", "more values than i8"),
+ ("variant Test::Value { A u32, B u32 }", "distinct type"),
+ ("variant Test::Value { " + ", ".join(f"V{i} Test::T{i}" for i in range(255)) + " }", "too many"),
+ ("struct Test::Record { u32 id; u32 id; }", "Duplicate member"),
+ ("struct Test::Record { u32 id }", "Expected ';'"),
+ ("struct Test::A { } struct Test::A { }", "Duplicate type"),
+ ("[Accessors] struct Test::Record { u32 id; }", "can have accessors"),
+ ("[ExistingCpp, Accessors] enum Test::Kind : u8 { A }", "can have accessors"),
+ ("[Unknown] struct Test::Record { u32 id; }", "Unknown attribute"),
+ ("[ExistingCpp] endpoint Test { ping() =| }", "Expected 'endpoint', 'struct'"),
+ ("struct Test::Record { [Bounded] u32 id; }", "Unknown attribute"),
+ ("struct Test::Record { [MaxBytes=8] Vector<u8> bytes; }", "MaxBytes cannot apply"),
+ ("struct Test::Record { [MaxBytes=0] String text; }", "needs a size"),
+ ("struct Test::Record { [MaxCount=4294967296] Vector<u32> values; }", "needs a size"),
+ ("struct Test::Record { [MaxCount] Vector<u32> values; }", "needs a size"),
+ ("struct Test::Record { [NonZero] double value; }", "NonZero cannot apply"),
+ ("struct Test::Record { [NonZero=1] u32 value; }", "takes no argument"),
+ ("struct Test::Record { [Finite] u32 value; }", "Finite cannot apply"),
+ ("struct Test::Record { unsigned int value; }", "Expected ';'"),
+ ("[ExistingCpp", "Unexpected EOF in attributes"),
+ ("variant Test::Value { A int, B i32 }", "distinct type"),
+ ("variant Test::Value { A unsigned, B u32 }", "distinct type"),
+ ("variant Test::Value { A Test::R, B ::Test::R }", "distinct type"),
+ ("variant Test::Value { A, B u32 }", "Invalid type '' of Test::Value::A"),
+ ("struct Test::Record { ; }", "Expected ';'"),
+ ("struct Test::Record { Vector<> values; }", "Invalid type 'Vector<>' of Test::Record::values"),
+ ("struct Test::Record { 1u32 value; }", "Invalid type '1u32' of Test::Record::value"),
+ ("struct Test::A_B { } struct Test::A::B { }", "same Rust name"),
+ ("struct Test::Record { [NonZero u32 value; }", "Unexpected EOF in attributes"),
+ ]:
+ with self.subTest(contents=contents):
+ with self.assertRaisesRegex(RuntimeError, error):
+ parse(contents)
+
+
class TestIPCRustGenerator(unittest.TestCase):
def generate(self, contents: str) -> str:
output = io.StringIO()
@@ -219,7 +513,7 @@ class TestIPCRustGenerator(unittest.TestCase):
f"impl ::libipc_rust::wire::EndpointMessage for {name} {{\n const ENDPOINT_MAGIC: u32 = super::ENDPOINT_MAGIC;\n const MESSAGE_ID: i32 = {number};",
generated,
)
- self.assertIn(f"pub const ENDPOINT_MAGIC: u32 = {parse(ENDPOINT)[0].magic};", generated)
+ self.assertIn(f"pub const ENDPOINT_MAGIC: u32 = {parse(ENDPOINT).endpoints[0].magic};", generated)
def test_types_compose_and_custom_types_are_supplied_by_the_crate(self) -> None:
self.assertEqual(rust_type("Vector<Optional<i64>>"), "::std::vec::Vec<::std::option::Option<i64>>")