From 4dd78cb27e5a218646c24993142a08fc937a2d18 Mon Sep 17 00:00:00 2001 From: alexcrichton Date: Mon, 20 Nov 2023 22:34:44 +0000 Subject: [PATCH] =?UTF-8?q?Deploying=20to=20gh-pages=20from=20@=20bytecode?= =?UTF-8?q?alliance/wasmtime-py@1a916a3262aae0d57c6d691a230a5363a94430b9?= =?UTF-8?q?=20=F0=9F=9A=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bindgen/generated/imports/environment.html | 145 + bindgen/generated/imports/exit.html | 146 + bindgen/generated/imports/index.html | 280 + bindgen/generated/imports/preopens.html | 147 + bindgen/generated/imports/random.html | 145 + bindgen/generated/imports/stderr.html | 147 + bindgen/generated/imports/stdin.html | 147 + bindgen/generated/imports/stdout.html | 147 + bindgen/generated/imports/streams.html | 302 + bindgen/generated/imports/terminal_input.html | 146 + .../generated/imports/terminal_output.html | 146 + .../generated/imports/terminal_stderr.html | 147 + bindgen/generated/imports/terminal_stdin.html | 147 + .../generated/imports/terminal_stdout.html | 147 + bindgen/generated/imports/types.html | 681 ++ bindgen/generated/index.html | 793 +++ bindgen/generated/intrinsics.html | 147 + bindgen/generated/types.html | 143 + bindgen/index.html | 251 + index.html | 5484 +++++++++++++++++ loader.html | 158 + 21 files changed, 9996 insertions(+) create mode 100644 bindgen/generated/imports/environment.html create mode 100644 bindgen/generated/imports/exit.html create mode 100644 bindgen/generated/imports/index.html create mode 100644 bindgen/generated/imports/preopens.html create mode 100644 bindgen/generated/imports/random.html create mode 100644 bindgen/generated/imports/stderr.html create mode 100644 bindgen/generated/imports/stdin.html create mode 100644 bindgen/generated/imports/stdout.html create mode 100644 bindgen/generated/imports/streams.html create mode 100644 bindgen/generated/imports/terminal_input.html create mode 100644 bindgen/generated/imports/terminal_output.html create mode 100644 bindgen/generated/imports/terminal_stderr.html create mode 100644 bindgen/generated/imports/terminal_stdin.html create mode 100644 bindgen/generated/imports/terminal_stdout.html create mode 100644 bindgen/generated/imports/types.html create mode 100644 bindgen/generated/index.html create mode 100644 bindgen/generated/intrinsics.html create mode 100644 bindgen/generated/types.html create mode 100644 bindgen/index.html create mode 100644 index.html create mode 100644 loader.html diff --git a/bindgen/generated/imports/environment.html b/bindgen/generated/imports/environment.html new file mode 100644 index 00000000..89ccd17f --- /dev/null +++ b/bindgen/generated/imports/environment.html @@ -0,0 +1,145 @@ + + + + + + +wasmtime.bindgen.generated.imports.environment API documentation + + + + + + + + + + + +
+
+
+

Module wasmtime.bindgen.generated.imports.environment

+
+
+
+ +Expand source code + +
from abc import abstractmethod
+from typing import List, Protocol, Tuple
+
+class HostEnvironment(Protocol):
+    @abstractmethod
+    def get_environment(self) -> List[Tuple[str, str]]:
+        raise NotImplementedError
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class HostEnvironment +(*args, **kwargs) +
+
+

Base class for protocol classes.

+

Protocol classes are defined as::

+
class Proto(Protocol):
+    def meth(self) -> int:
+        ...
+
+

Such classes are primarily used with static type checkers that recognize +structural subtyping (static duck-typing).

+

For example::

+
class C:
+    def meth(self) -> int:
+        return 0
+
+def func(x: Proto) -> int:
+    return x.meth()
+
+func(C())  # Passes static type check
+
+

See PEP 544 for details. Protocol classes decorated with +@typing.runtime_checkable act as simple-minded runtime protocols that check +only the presence of given attributes, ignoring their type signatures. +Protocol classes can be generic, they are defined as::

+
class GenProto[T](Protocol):
+    def meth(self) -> T:
+        ...
+
+
+ +Expand source code + +
class HostEnvironment(Protocol):
+    @abstractmethod
+    def get_environment(self) -> List[Tuple[str, str]]:
+        raise NotImplementedError
+
+

Ancestors

+
    +
  • typing.Protocol
  • +
  • typing.Generic
  • +
+

Subclasses

+
    +
  • wasmtime.bindgen.WasiEnvironment
  • +
+

Methods

+
+
+def get_environment(self) ‑> List[Tuple[str, str]] +
+
+
+
+ +Expand source code + +
@abstractmethod
+def get_environment(self) -> List[Tuple[str, str]]:
+    raise NotImplementedError
+
+
+
+
+
+
+
+ +
+ + + \ No newline at end of file diff --git a/bindgen/generated/imports/exit.html b/bindgen/generated/imports/exit.html new file mode 100644 index 00000000..b91dfd29 --- /dev/null +++ b/bindgen/generated/imports/exit.html @@ -0,0 +1,146 @@ + + + + + + +wasmtime.bindgen.generated.imports.exit API documentation + + + + + + + + + + + +
+
+
+

Module wasmtime.bindgen.generated.imports.exit

+
+
+
+ +Expand source code + +
from ..types import Result
+from abc import abstractmethod
+from typing import Protocol
+
+class HostExit(Protocol):
+    @abstractmethod
+    def exit(self, status: Result[None, None]) -> None:
+        raise NotImplementedError
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class HostExit +(*args, **kwargs) +
+
+

Base class for protocol classes.

+

Protocol classes are defined as::

+
class Proto(Protocol):
+    def meth(self) -> int:
+        ...
+
+

Such classes are primarily used with static type checkers that recognize +structural subtyping (static duck-typing).

+

For example::

+
class C:
+    def meth(self) -> int:
+        return 0
+
+def func(x: Proto) -> int:
+    return x.meth()
+
+func(C())  # Passes static type check
+
+

See PEP 544 for details. Protocol classes decorated with +@typing.runtime_checkable act as simple-minded runtime protocols that check +only the presence of given attributes, ignoring their type signatures. +Protocol classes can be generic, they are defined as::

+
class GenProto[T](Protocol):
+    def meth(self) -> T:
+        ...
+
+
+ +Expand source code + +
class HostExit(Protocol):
+    @abstractmethod
+    def exit(self, status: Result[None, None]) -> None:
+        raise NotImplementedError
+
+

Ancestors

+
    +
  • typing.Protocol
  • +
  • typing.Generic
  • +
+

Subclasses

+
    +
  • wasmtime.bindgen.WasiExit
  • +
+

Methods

+
+
+def exit(self, status: Union[Ok[None], Err[None]]) ‑> None +
+
+
+
+ +Expand source code + +
@abstractmethod
+def exit(self, status: Result[None, None]) -> None:
+    raise NotImplementedError
+
+
+
+
+
+
+
+ +
+ + + \ No newline at end of file diff --git a/bindgen/generated/imports/index.html b/bindgen/generated/imports/index.html new file mode 100644 index 00000000..1083cf3c --- /dev/null +++ b/bindgen/generated/imports/index.html @@ -0,0 +1,280 @@ + + + + + + +wasmtime.bindgen.generated.imports API documentation + + + + + + + + + + + +
+
+
+

Module wasmtime.bindgen.generated.imports

+
+
+
+ +Expand source code + +
from .environment import HostEnvironment
+from .exit import HostExit
+from .preopens import HostPreopens
+from .random import HostRandom
+from .stderr import HostStderr
+from .stdin import HostStdin
+from .stdout import HostStdout
+from .streams import HostStreams
+from .terminal_input import HostTerminalInput
+from .terminal_output import HostTerminalOutput
+from .terminal_stderr import HostTerminalStderr
+from .terminal_stdin import HostTerminalStdin
+from .terminal_stdout import HostTerminalStdout
+from .types import HostTypes
+from dataclasses import dataclass
+
+@dataclass
+class RootImports:
+    streams: HostStreams
+    types: HostTypes
+    preopens: HostPreopens
+    random: HostRandom
+    environment: HostEnvironment
+    exit: HostExit
+    stdin: HostStdin
+    stdout: HostStdout
+    stderr: HostStderr
+    terminal_input: HostTerminalInput
+    terminal_output: HostTerminalOutput
+    terminal_stdin: HostTerminalStdin
+    terminal_stdout: HostTerminalStdout
+    terminal_stderr: HostTerminalStderr
+
+
+
+

Sub-modules

+
+
wasmtime.bindgen.generated.imports.environment
+
+
+
+
wasmtime.bindgen.generated.imports.exit
+
+
+
+
wasmtime.bindgen.generated.imports.preopens
+
+
+
+
wasmtime.bindgen.generated.imports.random
+
+
+
+
wasmtime.bindgen.generated.imports.stderr
+
+
+
+
wasmtime.bindgen.generated.imports.stdin
+
+
+
+
wasmtime.bindgen.generated.imports.stdout
+
+
+
+
wasmtime.bindgen.generated.imports.streams
+
+
+
+
wasmtime.bindgen.generated.imports.terminal_input
+
+
+
+
wasmtime.bindgen.generated.imports.terminal_output
+
+
+
+
wasmtime.bindgen.generated.imports.terminal_stderr
+
+
+
+
wasmtime.bindgen.generated.imports.terminal_stdin
+
+
+
+
wasmtime.bindgen.generated.imports.terminal_stdout
+
+
+
+
wasmtime.bindgen.generated.imports.types
+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class RootImports +(streams: HostStreams, types: HostTypes, preopens: HostPreopens, random: HostRandom, environment: HostEnvironment, exit: HostExit, stdin: HostStdin, stdout: HostStdout, stderr: HostStderr, terminal_input: HostTerminalInput, terminal_output: HostTerminalOutput, terminal_stdin: HostTerminalStdin, terminal_stdout: HostTerminalStdout, terminal_stderr: HostTerminalStderr) +
+
+

RootImports(streams: wasmtime.bindgen.generated.imports.streams.HostStreams, types: wasmtime.bindgen.generated.imports.types.HostTypes, preopens: wasmtime.bindgen.generated.imports.preopens.HostPreopens, random: wasmtime.bindgen.generated.imports.random.HostRandom, environment: wasmtime.bindgen.generated.imports.environment.HostEnvironment, exit: wasmtime.bindgen.generated.imports.exit.HostExit, stdin: wasmtime.bindgen.generated.imports.stdin.HostStdin, stdout: wasmtime.bindgen.generated.imports.stdout.HostStdout, stderr: wasmtime.bindgen.generated.imports.stderr.HostStderr, terminal_input: wasmtime.bindgen.generated.imports.terminal_input.HostTerminalInput, terminal_output: wasmtime.bindgen.generated.imports.terminal_output.HostTerminalOutput, terminal_stdin: wasmtime.bindgen.generated.imports.terminal_stdin.HostTerminalStdin, terminal_stdout: wasmtime.bindgen.generated.imports.terminal_stdout.HostTerminalStdout, terminal_stderr: wasmtime.bindgen.generated.imports.terminal_stderr.HostTerminalStderr)

+
+ +Expand source code + +
@dataclass
+class RootImports:
+    streams: HostStreams
+    types: HostTypes
+    preopens: HostPreopens
+    random: HostRandom
+    environment: HostEnvironment
+    exit: HostExit
+    stdin: HostStdin
+    stdout: HostStdout
+    stderr: HostStderr
+    terminal_input: HostTerminalInput
+    terminal_output: HostTerminalOutput
+    terminal_stdin: HostTerminalStdin
+    terminal_stdout: HostTerminalStdout
+    terminal_stderr: HostTerminalStderr
+
+

Class variables

+
+
var environmentHostEnvironment
+
+
+
+
var exitHostExit
+
+
+
+
var preopensHostPreopens
+
+
+
+
var randomHostRandom
+
+
+
+
var stderrHostStderr
+
+
+
+
var stdinHostStdin
+
+
+
+
var stdoutHostStdout
+
+
+
+
var streamsHostStreams
+
+
+
+
var terminal_inputHostTerminalInput
+
+
+
+
var terminal_outputHostTerminalOutput
+
+
+
+
var terminal_stderrHostTerminalStderr
+
+
+
+
var terminal_stdinHostTerminalStdin
+
+
+
+
var terminal_stdoutHostTerminalStdout
+
+
+
+
var typesHostTypes
+
+
+
+
+
+
+
+
+ +
+ + + \ No newline at end of file diff --git a/bindgen/generated/imports/preopens.html b/bindgen/generated/imports/preopens.html new file mode 100644 index 00000000..e4cb93bd --- /dev/null +++ b/bindgen/generated/imports/preopens.html @@ -0,0 +1,147 @@ + + + + + + +wasmtime.bindgen.generated.imports.preopens API documentation + + + + + + + + + + + +
+
+
+

Module wasmtime.bindgen.generated.imports.preopens

+
+
+
+ +Expand source code + +
from ..imports import types
+from abc import abstractmethod
+from typing import List, Protocol, Tuple
+
+Descriptor = types.Descriptor
+class HostPreopens(Protocol):
+    @abstractmethod
+    def get_directories(self) -> List[Tuple[Descriptor, str]]:
+        raise NotImplementedError
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class HostPreopens +(*args, **kwargs) +
+
+

Base class for protocol classes.

+

Protocol classes are defined as::

+
class Proto(Protocol):
+    def meth(self) -> int:
+        ...
+
+

Such classes are primarily used with static type checkers that recognize +structural subtyping (static duck-typing).

+

For example::

+
class C:
+    def meth(self) -> int:
+        return 0
+
+def func(x: Proto) -> int:
+    return x.meth()
+
+func(C())  # Passes static type check
+
+

See PEP 544 for details. Protocol classes decorated with +@typing.runtime_checkable act as simple-minded runtime protocols that check +only the presence of given attributes, ignoring their type signatures. +Protocol classes can be generic, they are defined as::

+
class GenProto[T](Protocol):
+    def meth(self) -> T:
+        ...
+
+
+ +Expand source code + +
class HostPreopens(Protocol):
+    @abstractmethod
+    def get_directories(self) -> List[Tuple[Descriptor, str]]:
+        raise NotImplementedError
+
+

Ancestors

+
    +
  • typing.Protocol
  • +
  • typing.Generic
  • +
+

Subclasses

+
    +
  • wasmtime.bindgen.WasiPreopens
  • +
+

Methods

+
+
+def get_directories(self) ‑> List[Tuple[int, str]] +
+
+
+
+ +Expand source code + +
@abstractmethod
+def get_directories(self) -> List[Tuple[Descriptor, str]]:
+    raise NotImplementedError
+
+
+
+
+
+
+
+ +
+ + + \ No newline at end of file diff --git a/bindgen/generated/imports/random.html b/bindgen/generated/imports/random.html new file mode 100644 index 00000000..8e702c38 --- /dev/null +++ b/bindgen/generated/imports/random.html @@ -0,0 +1,145 @@ + + + + + + +wasmtime.bindgen.generated.imports.random API documentation + + + + + + + + + + + +
+
+
+

Module wasmtime.bindgen.generated.imports.random

+
+
+
+ +Expand source code + +
from abc import abstractmethod
+from typing import Protocol
+
+class HostRandom(Protocol):
+    @abstractmethod
+    def get_random_bytes(self, len: int) -> bytes:
+        raise NotImplementedError
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class HostRandom +(*args, **kwargs) +
+
+

Base class for protocol classes.

+

Protocol classes are defined as::

+
class Proto(Protocol):
+    def meth(self) -> int:
+        ...
+
+

Such classes are primarily used with static type checkers that recognize +structural subtyping (static duck-typing).

+

For example::

+
class C:
+    def meth(self) -> int:
+        return 0
+
+def func(x: Proto) -> int:
+    return x.meth()
+
+func(C())  # Passes static type check
+
+

See PEP 544 for details. Protocol classes decorated with +@typing.runtime_checkable act as simple-minded runtime protocols that check +only the presence of given attributes, ignoring their type signatures. +Protocol classes can be generic, they are defined as::

+
class GenProto[T](Protocol):
+    def meth(self) -> T:
+        ...
+
+
+ +Expand source code + +
class HostRandom(Protocol):
+    @abstractmethod
+    def get_random_bytes(self, len: int) -> bytes:
+        raise NotImplementedError
+
+

Ancestors

+
    +
  • typing.Protocol
  • +
  • typing.Generic
  • +
+

Subclasses

+
    +
  • wasmtime.bindgen.WasiRandom
  • +
+

Methods

+
+
+def get_random_bytes(self, len: int) ‑> bytes +
+
+
+
+ +Expand source code + +
@abstractmethod
+def get_random_bytes(self, len: int) -> bytes:
+    raise NotImplementedError
+
+
+
+
+
+
+
+ +
+ + + \ No newline at end of file diff --git a/bindgen/generated/imports/stderr.html b/bindgen/generated/imports/stderr.html new file mode 100644 index 00000000..d051dde2 --- /dev/null +++ b/bindgen/generated/imports/stderr.html @@ -0,0 +1,147 @@ + + + + + + +wasmtime.bindgen.generated.imports.stderr API documentation + + + + + + + + + + + +
+
+
+

Module wasmtime.bindgen.generated.imports.stderr

+
+
+
+ +Expand source code + +
from ..imports import streams
+from abc import abstractmethod
+from typing import Protocol
+
+OutputStream = streams.OutputStream
+class HostStderr(Protocol):
+    @abstractmethod
+    def get_stderr(self) -> OutputStream:
+        raise NotImplementedError
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class HostStderr +(*args, **kwargs) +
+
+

Base class for protocol classes.

+

Protocol classes are defined as::

+
class Proto(Protocol):
+    def meth(self) -> int:
+        ...
+
+

Such classes are primarily used with static type checkers that recognize +structural subtyping (static duck-typing).

+

For example::

+
class C:
+    def meth(self) -> int:
+        return 0
+
+def func(x: Proto) -> int:
+    return x.meth()
+
+func(C())  # Passes static type check
+
+

See PEP 544 for details. Protocol classes decorated with +@typing.runtime_checkable act as simple-minded runtime protocols that check +only the presence of given attributes, ignoring their type signatures. +Protocol classes can be generic, they are defined as::

+
class GenProto[T](Protocol):
+    def meth(self) -> T:
+        ...
+
+
+ +Expand source code + +
class HostStderr(Protocol):
+    @abstractmethod
+    def get_stderr(self) -> OutputStream:
+        raise NotImplementedError
+
+

Ancestors

+
    +
  • typing.Protocol
  • +
  • typing.Generic
  • +
+

Subclasses

+
    +
  • wasmtime.bindgen.WasiStderr
  • +
+

Methods

+
+
+def get_stderr(self) ‑> int +
+
+
+
+ +Expand source code + +
@abstractmethod
+def get_stderr(self) -> OutputStream:
+    raise NotImplementedError
+
+
+
+
+
+
+
+ +
+ + + \ No newline at end of file diff --git a/bindgen/generated/imports/stdin.html b/bindgen/generated/imports/stdin.html new file mode 100644 index 00000000..4071ab6a --- /dev/null +++ b/bindgen/generated/imports/stdin.html @@ -0,0 +1,147 @@ + + + + + + +wasmtime.bindgen.generated.imports.stdin API documentation + + + + + + + + + + + +
+
+
+

Module wasmtime.bindgen.generated.imports.stdin

+
+
+
+ +Expand source code + +
from ..imports import streams
+from abc import abstractmethod
+from typing import Protocol
+
+InputStream = streams.InputStream
+class HostStdin(Protocol):
+    @abstractmethod
+    def get_stdin(self) -> InputStream:
+        raise NotImplementedError
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class HostStdin +(*args, **kwargs) +
+
+

Base class for protocol classes.

+

Protocol classes are defined as::

+
class Proto(Protocol):
+    def meth(self) -> int:
+        ...
+
+

Such classes are primarily used with static type checkers that recognize +structural subtyping (static duck-typing).

+

For example::

+
class C:
+    def meth(self) -> int:
+        return 0
+
+def func(x: Proto) -> int:
+    return x.meth()
+
+func(C())  # Passes static type check
+
+

See PEP 544 for details. Protocol classes decorated with +@typing.runtime_checkable act as simple-minded runtime protocols that check +only the presence of given attributes, ignoring their type signatures. +Protocol classes can be generic, they are defined as::

+
class GenProto[T](Protocol):
+    def meth(self) -> T:
+        ...
+
+
+ +Expand source code + +
class HostStdin(Protocol):
+    @abstractmethod
+    def get_stdin(self) -> InputStream:
+        raise NotImplementedError
+
+

Ancestors

+
    +
  • typing.Protocol
  • +
  • typing.Generic
  • +
+

Subclasses

+
    +
  • wasmtime.bindgen.WasiStdin
  • +
+

Methods

+
+
+def get_stdin(self) ‑> int +
+
+
+
+ +Expand source code + +
@abstractmethod
+def get_stdin(self) -> InputStream:
+    raise NotImplementedError
+
+
+
+
+
+
+
+ +
+ + + \ No newline at end of file diff --git a/bindgen/generated/imports/stdout.html b/bindgen/generated/imports/stdout.html new file mode 100644 index 00000000..5eb4eb8b --- /dev/null +++ b/bindgen/generated/imports/stdout.html @@ -0,0 +1,147 @@ + + + + + + +wasmtime.bindgen.generated.imports.stdout API documentation + + + + + + + + + + + +
+
+
+

Module wasmtime.bindgen.generated.imports.stdout

+
+
+
+ +Expand source code + +
from ..imports import streams
+from abc import abstractmethod
+from typing import Protocol
+
+OutputStream = streams.OutputStream
+class HostStdout(Protocol):
+    @abstractmethod
+    def get_stdout(self) -> OutputStream:
+        raise NotImplementedError
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class HostStdout +(*args, **kwargs) +
+
+

Base class for protocol classes.

+

Protocol classes are defined as::

+
class Proto(Protocol):
+    def meth(self) -> int:
+        ...
+
+

Such classes are primarily used with static type checkers that recognize +structural subtyping (static duck-typing).

+

For example::

+
class C:
+    def meth(self) -> int:
+        return 0
+
+def func(x: Proto) -> int:
+    return x.meth()
+
+func(C())  # Passes static type check
+
+

See PEP 544 for details. Protocol classes decorated with +@typing.runtime_checkable act as simple-minded runtime protocols that check +only the presence of given attributes, ignoring their type signatures. +Protocol classes can be generic, they are defined as::

+
class GenProto[T](Protocol):
+    def meth(self) -> T:
+        ...
+
+
+ +Expand source code + +
class HostStdout(Protocol):
+    @abstractmethod
+    def get_stdout(self) -> OutputStream:
+        raise NotImplementedError
+
+

Ancestors

+
    +
  • typing.Protocol
  • +
  • typing.Generic
  • +
+

Subclasses

+
    +
  • wasmtime.bindgen.WasiStdout
  • +
+

Methods

+
+
+def get_stdout(self) ‑> int +
+
+
+
+ +Expand source code + +
@abstractmethod
+def get_stdout(self) -> OutputStream:
+    raise NotImplementedError
+
+
+
+
+
+
+
+ +
+ + + \ No newline at end of file diff --git a/bindgen/generated/imports/streams.html b/bindgen/generated/imports/streams.html new file mode 100644 index 00000000..3c377fbe --- /dev/null +++ b/bindgen/generated/imports/streams.html @@ -0,0 +1,302 @@ + + + + + + +wasmtime.bindgen.generated.imports.streams API documentation + + + + + + + + + + + +
+
+
+

Module wasmtime.bindgen.generated.imports.streams

+
+
+
+ +Expand source code + +
from ..types import Result
+from abc import abstractmethod
+from enum import Enum
+from typing import Protocol, Tuple
+
+InputStream = int
+OutputStream = int
+class StreamStatus(Enum):
+    OPEN = 0
+    ENDED = 1
+
+class HostStreams(Protocol):
+    @abstractmethod
+    def drop_input_stream(self, this: InputStream) -> None:
+        raise NotImplementedError
+    @abstractmethod
+    def write(self, this: OutputStream, buf: bytes) -> Result[Tuple[int, StreamStatus], None]:
+        raise NotImplementedError
+    @abstractmethod
+    def blocking_write(self, this: OutputStream, buf: bytes) -> Result[Tuple[int, StreamStatus], None]:
+        raise NotImplementedError
+    @abstractmethod
+    def drop_output_stream(self, this: OutputStream) -> None:
+        raise NotImplementedError
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class HostStreams +(*args, **kwargs) +
+
+

Base class for protocol classes.

+

Protocol classes are defined as::

+
class Proto(Protocol):
+    def meth(self) -> int:
+        ...
+
+

Such classes are primarily used with static type checkers that recognize +structural subtyping (static duck-typing).

+

For example::

+
class C:
+    def meth(self) -> int:
+        return 0
+
+def func(x: Proto) -> int:
+    return x.meth()
+
+func(C())  # Passes static type check
+
+

See PEP 544 for details. Protocol classes decorated with +@typing.runtime_checkable act as simple-minded runtime protocols that check +only the presence of given attributes, ignoring their type signatures. +Protocol classes can be generic, they are defined as::

+
class GenProto[T](Protocol):
+    def meth(self) -> T:
+        ...
+
+
+ +Expand source code + +
class HostStreams(Protocol):
+    @abstractmethod
+    def drop_input_stream(self, this: InputStream) -> None:
+        raise NotImplementedError
+    @abstractmethod
+    def write(self, this: OutputStream, buf: bytes) -> Result[Tuple[int, StreamStatus], None]:
+        raise NotImplementedError
+    @abstractmethod
+    def blocking_write(self, this: OutputStream, buf: bytes) -> Result[Tuple[int, StreamStatus], None]:
+        raise NotImplementedError
+    @abstractmethod
+    def drop_output_stream(self, this: OutputStream) -> None:
+        raise NotImplementedError
+
+

Ancestors

+
    +
  • typing.Protocol
  • +
  • typing.Generic
  • +
+

Subclasses

+
    +
  • wasmtime.bindgen.WasiStreams
  • +
+

Methods

+
+
+def blocking_write(self, this: int, buf: bytes) ‑> Union[Ok[Tuple[int, StreamStatus]], Err[None]] +
+
+
+
+ +Expand source code + +
@abstractmethod
+def blocking_write(self, this: OutputStream, buf: bytes) -> Result[Tuple[int, StreamStatus], None]:
+    raise NotImplementedError
+
+
+
+def drop_input_stream(self, this: int) ‑> None +
+
+
+
+ +Expand source code + +
@abstractmethod
+def drop_input_stream(self, this: InputStream) -> None:
+    raise NotImplementedError
+
+
+
+def drop_output_stream(self, this: int) ‑> None +
+
+
+
+ +Expand source code + +
@abstractmethod
+def drop_output_stream(self, this: OutputStream) -> None:
+    raise NotImplementedError
+
+
+
+def write(self, this: int, buf: bytes) ‑> Union[Ok[Tuple[int, StreamStatus]], Err[None]] +
+
+
+
+ +Expand source code + +
@abstractmethod
+def write(self, this: OutputStream, buf: bytes) -> Result[Tuple[int, StreamStatus], None]:
+    raise NotImplementedError
+
+
+
+
+
+class StreamStatus +(*args, **kwds) +
+
+

Create a collection of name/value pairs.

+

Example enumeration:

+
>>> class Color(Enum):
+...     RED = 1
+...     BLUE = 2
+...     GREEN = 3
+
+

Access them by:

+
    +
  • attribute access:
  • +
+
+
+
+

Color.RED +

+
+
+
+
    +
  • value lookup:
  • +
+
+
+
+

Color(1) +

+
+
+
+
    +
  • name lookup:
  • +
+
+
+
+

Color['RED'] +

+
+
+
+

Enumerations can be iterated over, and know how many members they have:

+
>>> len(Color)
+3
+
+
>>> list(Color)
+[<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]
+
+

Methods can be added to enumerations, and members can have their own +attributes – see the documentation for details.

+
+ +Expand source code + +
class StreamStatus(Enum):
+    OPEN = 0
+    ENDED = 1
+
+

Ancestors

+
    +
  • enum.Enum
  • +
+

Class variables

+
+
var ENDED
+
+
+
+
var OPEN
+
+
+
+
+
+
+
+
+ +
+ + + \ No newline at end of file diff --git a/bindgen/generated/imports/terminal_input.html b/bindgen/generated/imports/terminal_input.html new file mode 100644 index 00000000..2f65474e --- /dev/null +++ b/bindgen/generated/imports/terminal_input.html @@ -0,0 +1,146 @@ + + + + + + +wasmtime.bindgen.generated.imports.terminal_input API documentation + + + + + + + + + + + +
+
+
+

Module wasmtime.bindgen.generated.imports.terminal_input

+
+
+
+ +Expand source code + +
from abc import abstractmethod
+from typing import Protocol
+
+TerminalInput = int
+class HostTerminalInput(Protocol):
+    @abstractmethod
+    def drop_terminal_input(self, this: TerminalInput) -> None:
+        raise NotImplementedError
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class HostTerminalInput +(*args, **kwargs) +
+
+

Base class for protocol classes.

+

Protocol classes are defined as::

+
class Proto(Protocol):
+    def meth(self) -> int:
+        ...
+
+

Such classes are primarily used with static type checkers that recognize +structural subtyping (static duck-typing).

+

For example::

+
class C:
+    def meth(self) -> int:
+        return 0
+
+def func(x: Proto) -> int:
+    return x.meth()
+
+func(C())  # Passes static type check
+
+

See PEP 544 for details. Protocol classes decorated with +@typing.runtime_checkable act as simple-minded runtime protocols that check +only the presence of given attributes, ignoring their type signatures. +Protocol classes can be generic, they are defined as::

+
class GenProto[T](Protocol):
+    def meth(self) -> T:
+        ...
+
+
+ +Expand source code + +
class HostTerminalInput(Protocol):
+    @abstractmethod
+    def drop_terminal_input(self, this: TerminalInput) -> None:
+        raise NotImplementedError
+
+

Ancestors

+
    +
  • typing.Protocol
  • +
  • typing.Generic
  • +
+

Subclasses

+
    +
  • wasmtime.bindgen.WasiTerminalInput
  • +
+

Methods

+
+
+def drop_terminal_input(self, this: int) ‑> None +
+
+
+
+ +Expand source code + +
@abstractmethod
+def drop_terminal_input(self, this: TerminalInput) -> None:
+    raise NotImplementedError
+
+
+
+
+
+
+
+ +
+ + + \ No newline at end of file diff --git a/bindgen/generated/imports/terminal_output.html b/bindgen/generated/imports/terminal_output.html new file mode 100644 index 00000000..5f1a156e --- /dev/null +++ b/bindgen/generated/imports/terminal_output.html @@ -0,0 +1,146 @@ + + + + + + +wasmtime.bindgen.generated.imports.terminal_output API documentation + + + + + + + + + + + +
+
+
+

Module wasmtime.bindgen.generated.imports.terminal_output

+
+
+
+ +Expand source code + +
from abc import abstractmethod
+from typing import Protocol
+
+TerminalOutput = int
+class HostTerminalOutput(Protocol):
+    @abstractmethod
+    def drop_terminal_output(self, this: TerminalOutput) -> None:
+        raise NotImplementedError
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class HostTerminalOutput +(*args, **kwargs) +
+
+

Base class for protocol classes.

+

Protocol classes are defined as::

+
class Proto(Protocol):
+    def meth(self) -> int:
+        ...
+
+

Such classes are primarily used with static type checkers that recognize +structural subtyping (static duck-typing).

+

For example::

+
class C:
+    def meth(self) -> int:
+        return 0
+
+def func(x: Proto) -> int:
+    return x.meth()
+
+func(C())  # Passes static type check
+
+

See PEP 544 for details. Protocol classes decorated with +@typing.runtime_checkable act as simple-minded runtime protocols that check +only the presence of given attributes, ignoring their type signatures. +Protocol classes can be generic, they are defined as::

+
class GenProto[T](Protocol):
+    def meth(self) -> T:
+        ...
+
+
+ +Expand source code + +
class HostTerminalOutput(Protocol):
+    @abstractmethod
+    def drop_terminal_output(self, this: TerminalOutput) -> None:
+        raise NotImplementedError
+
+

Ancestors

+
    +
  • typing.Protocol
  • +
  • typing.Generic
  • +
+

Subclasses

+
    +
  • wasmtime.bindgen.WasiTerminalOutput
  • +
+

Methods

+
+
+def drop_terminal_output(self, this: int) ‑> None +
+
+
+
+ +Expand source code + +
@abstractmethod
+def drop_terminal_output(self, this: TerminalOutput) -> None:
+    raise NotImplementedError
+
+
+
+
+
+
+
+ +
+ + + \ No newline at end of file diff --git a/bindgen/generated/imports/terminal_stderr.html b/bindgen/generated/imports/terminal_stderr.html new file mode 100644 index 00000000..81f4732f --- /dev/null +++ b/bindgen/generated/imports/terminal_stderr.html @@ -0,0 +1,147 @@ + + + + + + +wasmtime.bindgen.generated.imports.terminal_stderr API documentation + + + + + + + + + + + +
+
+
+

Module wasmtime.bindgen.generated.imports.terminal_stderr

+
+
+
+ +Expand source code + +
from ..imports import terminal_output
+from abc import abstractmethod
+from typing import Optional, Protocol
+
+TerminalOutput = terminal_output.TerminalOutput
+class HostTerminalStderr(Protocol):
+    @abstractmethod
+    def get_terminal_stderr(self) -> Optional[TerminalOutput]:
+        raise NotImplementedError
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class HostTerminalStderr +(*args, **kwargs) +
+
+

Base class for protocol classes.

+

Protocol classes are defined as::

+
class Proto(Protocol):
+    def meth(self) -> int:
+        ...
+
+

Such classes are primarily used with static type checkers that recognize +structural subtyping (static duck-typing).

+

For example::

+
class C:
+    def meth(self) -> int:
+        return 0
+
+def func(x: Proto) -> int:
+    return x.meth()
+
+func(C())  # Passes static type check
+
+

See PEP 544 for details. Protocol classes decorated with +@typing.runtime_checkable act as simple-minded runtime protocols that check +only the presence of given attributes, ignoring their type signatures. +Protocol classes can be generic, they are defined as::

+
class GenProto[T](Protocol):
+    def meth(self) -> T:
+        ...
+
+
+ +Expand source code + +
class HostTerminalStderr(Protocol):
+    @abstractmethod
+    def get_terminal_stderr(self) -> Optional[TerminalOutput]:
+        raise NotImplementedError
+
+

Ancestors

+
    +
  • typing.Protocol
  • +
  • typing.Generic
  • +
+

Subclasses

+
    +
  • wasmtime.bindgen.WasiTerminalStderr
  • +
+

Methods

+
+
+def get_terminal_stderr(self) ‑> Optional[int] +
+
+
+
+ +Expand source code + +
@abstractmethod
+def get_terminal_stderr(self) -> Optional[TerminalOutput]:
+    raise NotImplementedError
+
+
+
+
+
+
+
+ +
+ + + \ No newline at end of file diff --git a/bindgen/generated/imports/terminal_stdin.html b/bindgen/generated/imports/terminal_stdin.html new file mode 100644 index 00000000..3c8d2824 --- /dev/null +++ b/bindgen/generated/imports/terminal_stdin.html @@ -0,0 +1,147 @@ + + + + + + +wasmtime.bindgen.generated.imports.terminal_stdin API documentation + + + + + + + + + + + +
+
+
+

Module wasmtime.bindgen.generated.imports.terminal_stdin

+
+
+
+ +Expand source code + +
from ..imports import terminal_input
+from abc import abstractmethod
+from typing import Optional, Protocol
+
+TerminalInput = terminal_input.TerminalInput
+class HostTerminalStdin(Protocol):
+    @abstractmethod
+    def get_terminal_stdin(self) -> Optional[TerminalInput]:
+        raise NotImplementedError
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class HostTerminalStdin +(*args, **kwargs) +
+
+

Base class for protocol classes.

+

Protocol classes are defined as::

+
class Proto(Protocol):
+    def meth(self) -> int:
+        ...
+
+

Such classes are primarily used with static type checkers that recognize +structural subtyping (static duck-typing).

+

For example::

+
class C:
+    def meth(self) -> int:
+        return 0
+
+def func(x: Proto) -> int:
+    return x.meth()
+
+func(C())  # Passes static type check
+
+

See PEP 544 for details. Protocol classes decorated with +@typing.runtime_checkable act as simple-minded runtime protocols that check +only the presence of given attributes, ignoring their type signatures. +Protocol classes can be generic, they are defined as::

+
class GenProto[T](Protocol):
+    def meth(self) -> T:
+        ...
+
+
+ +Expand source code + +
class HostTerminalStdin(Protocol):
+    @abstractmethod
+    def get_terminal_stdin(self) -> Optional[TerminalInput]:
+        raise NotImplementedError
+
+

Ancestors

+
    +
  • typing.Protocol
  • +
  • typing.Generic
  • +
+

Subclasses

+
    +
  • wasmtime.bindgen.WasiTerminalStdin
  • +
+

Methods

+
+
+def get_terminal_stdin(self) ‑> Optional[int] +
+
+
+
+ +Expand source code + +
@abstractmethod
+def get_terminal_stdin(self) -> Optional[TerminalInput]:
+    raise NotImplementedError
+
+
+
+
+
+
+
+ +
+ + + \ No newline at end of file diff --git a/bindgen/generated/imports/terminal_stdout.html b/bindgen/generated/imports/terminal_stdout.html new file mode 100644 index 00000000..55a5ad3c --- /dev/null +++ b/bindgen/generated/imports/terminal_stdout.html @@ -0,0 +1,147 @@ + + + + + + +wasmtime.bindgen.generated.imports.terminal_stdout API documentation + + + + + + + + + + + +
+
+
+

Module wasmtime.bindgen.generated.imports.terminal_stdout

+
+
+
+ +Expand source code + +
from ..imports import terminal_output
+from abc import abstractmethod
+from typing import Optional, Protocol
+
+TerminalOutput = terminal_output.TerminalOutput
+class HostTerminalStdout(Protocol):
+    @abstractmethod
+    def get_terminal_stdout(self) -> Optional[TerminalOutput]:
+        raise NotImplementedError
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class HostTerminalStdout +(*args, **kwargs) +
+
+

Base class for protocol classes.

+

Protocol classes are defined as::

+
class Proto(Protocol):
+    def meth(self) -> int:
+        ...
+
+

Such classes are primarily used with static type checkers that recognize +structural subtyping (static duck-typing).

+

For example::

+
class C:
+    def meth(self) -> int:
+        return 0
+
+def func(x: Proto) -> int:
+    return x.meth()
+
+func(C())  # Passes static type check
+
+

See PEP 544 for details. Protocol classes decorated with +@typing.runtime_checkable act as simple-minded runtime protocols that check +only the presence of given attributes, ignoring their type signatures. +Protocol classes can be generic, they are defined as::

+
class GenProto[T](Protocol):
+    def meth(self) -> T:
+        ...
+
+
+ +Expand source code + +
class HostTerminalStdout(Protocol):
+    @abstractmethod
+    def get_terminal_stdout(self) -> Optional[TerminalOutput]:
+        raise NotImplementedError
+
+

Ancestors

+
    +
  • typing.Protocol
  • +
  • typing.Generic
  • +
+

Subclasses

+
    +
  • wasmtime.bindgen.WasiTerminalStdout
  • +
+

Methods

+
+
+def get_terminal_stdout(self) ‑> Optional[int] +
+
+
+
+ +Expand source code + +
@abstractmethod
+def get_terminal_stdout(self) -> Optional[TerminalOutput]:
+    raise NotImplementedError
+
+
+
+
+
+
+
+ +
+ + + \ No newline at end of file diff --git a/bindgen/generated/imports/types.html b/bindgen/generated/imports/types.html new file mode 100644 index 00000000..e292ce15 --- /dev/null +++ b/bindgen/generated/imports/types.html @@ -0,0 +1,681 @@ + + + + + + +wasmtime.bindgen.generated.imports.types API documentation + + + + + + + + + + + +
+
+
+

Module wasmtime.bindgen.generated.imports.types

+
+
+
+ +Expand source code + +
from ..imports import streams
+from ..types import Result
+from abc import abstractmethod
+from enum import Enum
+from typing import Protocol
+
+Descriptor = int
+Filesize = int
+OutputStream = streams.OutputStream
+class ErrorCode(Enum):
+    ACCESS = 0
+    WOULD_BLOCK = 1
+    ALREADY = 2
+    BAD_DESCRIPTOR = 3
+    BUSY = 4
+    DEADLOCK = 5
+    QUOTA = 6
+    EXIST = 7
+    FILE_TOO_LARGE = 8
+    ILLEGAL_BYTE_SEQUENCE = 9
+    IN_PROGRESS = 10
+    INTERRUPTED = 11
+    INVALID = 12
+    IO = 13
+    IS_DIRECTORY = 14
+    LOOP = 15
+    TOO_MANY_LINKS = 16
+    MESSAGE_SIZE = 17
+    NAME_TOO_LONG = 18
+    NO_DEVICE = 19
+    NO_ENTRY = 20
+    NO_LOCK = 21
+    INSUFFICIENT_MEMORY = 22
+    INSUFFICIENT_SPACE = 23
+    NOT_DIRECTORY = 24
+    NOT_EMPTY = 25
+    NOT_RECOVERABLE = 26
+    UNSUPPORTED = 27
+    NO_TTY = 28
+    NO_SUCH_DEVICE = 29
+    OVERFLOW = 30
+    NOT_PERMITTED = 31
+    PIPE = 32
+    READ_ONLY = 33
+    INVALID_SEEK = 34
+    TEXT_FILE_BUSY = 35
+    CROSS_DEVICE = 36
+
+class DescriptorType(Enum):
+    UNKNOWN = 0
+    BLOCK_DEVICE = 1
+    CHARACTER_DEVICE = 2
+    DIRECTORY = 3
+    FIFO = 4
+    SYMBOLIC_LINK = 5
+    REGULAR_FILE = 6
+    SOCKET = 7
+
+class HostTypes(Protocol):
+    @abstractmethod
+    def write_via_stream(self, this: Descriptor, offset: Filesize) -> Result[OutputStream, ErrorCode]:
+        raise NotImplementedError
+    @abstractmethod
+    def append_via_stream(self, this: Descriptor) -> Result[OutputStream, ErrorCode]:
+        raise NotImplementedError
+    @abstractmethod
+    def get_type(self, this: Descriptor) -> Result[DescriptorType, ErrorCode]:
+        raise NotImplementedError
+    @abstractmethod
+    def drop_descriptor(self, this: Descriptor) -> None:
+        raise NotImplementedError
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class DescriptorType +(*args, **kwds) +
+
+

Create a collection of name/value pairs.

+

Example enumeration:

+
>>> class Color(Enum):
+...     RED = 1
+...     BLUE = 2
+...     GREEN = 3
+
+

Access them by:

+
    +
  • attribute access:
  • +
+
+
+
+

Color.RED +

+
+
+
+
    +
  • value lookup:
  • +
+
+
+
+

Color(1) +

+
+
+
+
    +
  • name lookup:
  • +
+
+
+
+

Color['RED'] +

+
+
+
+

Enumerations can be iterated over, and know how many members they have:

+
>>> len(Color)
+3
+
+
>>> list(Color)
+[<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]
+
+

Methods can be added to enumerations, and members can have their own +attributes – see the documentation for details.

+
+ +Expand source code + +
class DescriptorType(Enum):
+    UNKNOWN = 0
+    BLOCK_DEVICE = 1
+    CHARACTER_DEVICE = 2
+    DIRECTORY = 3
+    FIFO = 4
+    SYMBOLIC_LINK = 5
+    REGULAR_FILE = 6
+    SOCKET = 7
+
+

Ancestors

+
    +
  • enum.Enum
  • +
+

Class variables

+
+
var BLOCK_DEVICE
+
+
+
+
var CHARACTER_DEVICE
+
+
+
+
var DIRECTORY
+
+
+
+
var FIFO
+
+
+
+
var REGULAR_FILE
+
+
+
+
var SOCKET
+
+
+
+ +
+
+
+
var UNKNOWN
+
+
+
+
+
+
+class ErrorCode +(*args, **kwds) +
+
+

Create a collection of name/value pairs.

+

Example enumeration:

+
>>> class Color(Enum):
+...     RED = 1
+...     BLUE = 2
+...     GREEN = 3
+
+

Access them by:

+
    +
  • attribute access:
  • +
+
+
+
+

Color.RED +

+
+
+
+
    +
  • value lookup:
  • +
+
+
+
+

Color(1) +

+
+
+
+
    +
  • name lookup:
  • +
+
+
+
+

Color['RED'] +

+
+
+
+

Enumerations can be iterated over, and know how many members they have:

+
>>> len(Color)
+3
+
+
>>> list(Color)
+[<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]
+
+

Methods can be added to enumerations, and members can have their own +attributes – see the documentation for details.

+
+ +Expand source code + +
class ErrorCode(Enum):
+    ACCESS = 0
+    WOULD_BLOCK = 1
+    ALREADY = 2
+    BAD_DESCRIPTOR = 3
+    BUSY = 4
+    DEADLOCK = 5
+    QUOTA = 6
+    EXIST = 7
+    FILE_TOO_LARGE = 8
+    ILLEGAL_BYTE_SEQUENCE = 9
+    IN_PROGRESS = 10
+    INTERRUPTED = 11
+    INVALID = 12
+    IO = 13
+    IS_DIRECTORY = 14
+    LOOP = 15
+    TOO_MANY_LINKS = 16
+    MESSAGE_SIZE = 17
+    NAME_TOO_LONG = 18
+    NO_DEVICE = 19
+    NO_ENTRY = 20
+    NO_LOCK = 21
+    INSUFFICIENT_MEMORY = 22
+    INSUFFICIENT_SPACE = 23
+    NOT_DIRECTORY = 24
+    NOT_EMPTY = 25
+    NOT_RECOVERABLE = 26
+    UNSUPPORTED = 27
+    NO_TTY = 28
+    NO_SUCH_DEVICE = 29
+    OVERFLOW = 30
+    NOT_PERMITTED = 31
+    PIPE = 32
+    READ_ONLY = 33
+    INVALID_SEEK = 34
+    TEXT_FILE_BUSY = 35
+    CROSS_DEVICE = 36
+
+

Ancestors

+
    +
  • enum.Enum
  • +
+

Class variables

+
+
var ACCESS
+
+
+
+
var ALREADY
+
+
+
+
var BAD_DESCRIPTOR
+
+
+
+
var BUSY
+
+
+
+
var CROSS_DEVICE
+
+
+
+
var DEADLOCK
+
+
+
+
var EXIST
+
+
+
+
var FILE_TOO_LARGE
+
+
+
+
var ILLEGAL_BYTE_SEQUENCE
+
+
+
+
var INSUFFICIENT_MEMORY
+
+
+
+
var INSUFFICIENT_SPACE
+
+
+
+
var INTERRUPTED
+
+
+
+
var INVALID
+
+
+
+
var INVALID_SEEK
+
+
+
+
var IN_PROGRESS
+
+
+
+
var IO
+
+
+
+
var IS_DIRECTORY
+
+
+
+
var LOOP
+
+
+
+
var MESSAGE_SIZE
+
+
+
+
var NAME_TOO_LONG
+
+
+
+
var NOT_DIRECTORY
+
+
+
+
var NOT_EMPTY
+
+
+
+
var NOT_PERMITTED
+
+
+
+
var NOT_RECOVERABLE
+
+
+
+
var NO_DEVICE
+
+
+
+
var NO_ENTRY
+
+
+
+
var NO_LOCK
+
+
+
+
var NO_SUCH_DEVICE
+
+
+
+
var NO_TTY
+
+
+
+
var OVERFLOW
+
+
+
+
var PIPE
+
+
+
+
var QUOTA
+
+
+
+
var READ_ONLY
+
+
+
+
var TEXT_FILE_BUSY
+
+
+
+ +
+
+
+
var UNSUPPORTED
+
+
+
+
var WOULD_BLOCK
+
+
+
+
+
+
+class HostTypes +(*args, **kwargs) +
+
+

Base class for protocol classes.

+

Protocol classes are defined as::

+
class Proto(Protocol):
+    def meth(self) -> int:
+        ...
+
+

Such classes are primarily used with static type checkers that recognize +structural subtyping (static duck-typing).

+

For example::

+
class C:
+    def meth(self) -> int:
+        return 0
+
+def func(x: Proto) -> int:
+    return x.meth()
+
+func(C())  # Passes static type check
+
+

See PEP 544 for details. Protocol classes decorated with +@typing.runtime_checkable act as simple-minded runtime protocols that check +only the presence of given attributes, ignoring their type signatures. +Protocol classes can be generic, they are defined as::

+
class GenProto[T](Protocol):
+    def meth(self) -> T:
+        ...
+
+
+ +Expand source code + +
class HostTypes(Protocol):
+    @abstractmethod
+    def write_via_stream(self, this: Descriptor, offset: Filesize) -> Result[OutputStream, ErrorCode]:
+        raise NotImplementedError
+    @abstractmethod
+    def append_via_stream(self, this: Descriptor) -> Result[OutputStream, ErrorCode]:
+        raise NotImplementedError
+    @abstractmethod
+    def get_type(self, this: Descriptor) -> Result[DescriptorType, ErrorCode]:
+        raise NotImplementedError
+    @abstractmethod
+    def drop_descriptor(self, this: Descriptor) -> None:
+        raise NotImplementedError
+
+

Ancestors

+
    +
  • typing.Protocol
  • +
  • typing.Generic
  • +
+

Subclasses

+
    +
  • wasmtime.bindgen.WasiTypes
  • +
+

Methods

+
+
+def append_via_stream(self, this: int) ‑> Union[Ok[int], Err[ErrorCode]] +
+
+
+
+ +Expand source code + +
@abstractmethod
+def append_via_stream(self, this: Descriptor) -> Result[OutputStream, ErrorCode]:
+    raise NotImplementedError
+
+
+
+def drop_descriptor(self, this: int) ‑> None +
+
+
+
+ +Expand source code + +
@abstractmethod
+def drop_descriptor(self, this: Descriptor) -> None:
+    raise NotImplementedError
+
+
+
+def get_type(self, this: int) ‑> Union[Ok[DescriptorType], Err[ErrorCode]] +
+
+
+
+ +Expand source code + +
@abstractmethod
+def get_type(self, this: Descriptor) -> Result[DescriptorType, ErrorCode]:
+    raise NotImplementedError
+
+
+
+def write_via_stream(self, this: int, offset: int) ‑> Union[Ok[int], Err[ErrorCode]] +
+
+
+
+ +Expand source code + +
@abstractmethod
+def write_via_stream(self, this: Descriptor, offset: Filesize) -> Result[OutputStream, ErrorCode]:
+    raise NotImplementedError
+
+
+
+
+
+
+
+ +
+ + + \ No newline at end of file diff --git a/bindgen/generated/index.html b/bindgen/generated/index.html new file mode 100644 index 00000000..4fdd3c34 --- /dev/null +++ b/bindgen/generated/index.html @@ -0,0 +1,793 @@ + + + + + + +wasmtime.bindgen.generated API documentation + + + + + + + + + + + +
+
+
+

Module wasmtime.bindgen.generated

+
+
+
+ +Expand source code + +
from .imports import RootImports
+from .intrinsics import _clamp, _decode_utf8, _encode_utf8, _list_canon_lift, _list_canon_lower, _load, _store
+from .types import Err, Ok, Result
+import ctypes
+import pathlib
+from typing import List, Tuple, cast
+import wasmtime
+
+class Root:
+    
+    def __init__(self, store: wasmtime.Store, import_object: RootImports) -> None:
+        path = pathlib.Path(__file__).parent / ('root.core2.wasm')
+        module = wasmtime.Module.from_file(store.engine, path)
+        instance0 = wasmtime.Instance(store, module, []).exports(store)
+        path = pathlib.Path(__file__).parent / ('root.core0.wasm')
+        module = wasmtime.Module.from_file(store.engine, path)
+        instance1 = wasmtime.Instance(store, module, [
+            instance0["11"],
+            instance0["12"],
+            instance0["13"],
+            instance0["14"],
+            instance0["15"],
+        ]).exports(store)
+        def lowering0_callee(caller: wasmtime.Caller, arg0: int) -> None:
+            import_object.types.drop_descriptor(arg0 & 0xffffffff)
+        lowering0_ty = wasmtime.FuncType([wasmtime.ValType.i32(), ], [])
+        trampoline0 = wasmtime.Func(store, lowering0_ty, lowering0_callee, access_caller = True)
+        def lowering1_callee(caller: wasmtime.Caller) -> int:
+            ret = import_object.stdin.get_stdin()
+            return _clamp(ret, 0, 4294967295)
+        lowering1_ty = wasmtime.FuncType([], [wasmtime.ValType.i32(), ])
+        trampoline1 = wasmtime.Func(store, lowering1_ty, lowering1_callee, access_caller = True)
+        def lowering2_callee(caller: wasmtime.Caller) -> int:
+            ret = import_object.stdout.get_stdout()
+            return _clamp(ret, 0, 4294967295)
+        lowering2_ty = wasmtime.FuncType([], [wasmtime.ValType.i32(), ])
+        trampoline2 = wasmtime.Func(store, lowering2_ty, lowering2_callee, access_caller = True)
+        def lowering3_callee(caller: wasmtime.Caller) -> int:
+            ret = import_object.stderr.get_stderr()
+            return _clamp(ret, 0, 4294967295)
+        lowering3_ty = wasmtime.FuncType([], [wasmtime.ValType.i32(), ])
+        trampoline3 = wasmtime.Func(store, lowering3_ty, lowering3_callee, access_caller = True)
+        def lowering4_callee(caller: wasmtime.Caller, arg0: int) -> None:
+            import_object.terminal_output.drop_terminal_output(arg0 & 0xffffffff)
+        lowering4_ty = wasmtime.FuncType([wasmtime.ValType.i32(), ], [])
+        trampoline4 = wasmtime.Func(store, lowering4_ty, lowering4_callee, access_caller = True)
+        def lowering5_callee(caller: wasmtime.Caller, arg0: int) -> None:
+            import_object.streams.drop_input_stream(arg0 & 0xffffffff)
+        lowering5_ty = wasmtime.FuncType([wasmtime.ValType.i32(), ], [])
+        trampoline5 = wasmtime.Func(store, lowering5_ty, lowering5_callee, access_caller = True)
+        def lowering6_callee(caller: wasmtime.Caller, arg0: int) -> None:
+            import_object.streams.drop_output_stream(arg0 & 0xffffffff)
+        lowering6_ty = wasmtime.FuncType([wasmtime.ValType.i32(), ], [])
+        trampoline6 = wasmtime.Func(store, lowering6_ty, lowering6_callee, access_caller = True)
+        def lowering7_callee(caller: wasmtime.Caller, arg0: int) -> None:
+            import_object.terminal_input.drop_terminal_input(arg0 & 0xffffffff)
+        lowering7_ty = wasmtime.FuncType([wasmtime.ValType.i32(), ], [])
+        trampoline7 = wasmtime.Func(store, lowering7_ty, lowering7_callee, access_caller = True)
+        def lowering8_callee(caller: wasmtime.Caller, arg0: int) -> None:
+            expected: Result[None, None]
+            if arg0 == 0:
+                expected = Ok(None)
+            elif arg0 == 1:
+                expected = Err(None)
+            else:
+                raise TypeError("invalid variant discriminant for expected")
+            import_object.exit.exit(expected)
+        lowering8_ty = wasmtime.FuncType([wasmtime.ValType.i32(), ], [])
+        trampoline8 = wasmtime.Func(store, lowering8_ty, lowering8_callee, access_caller = True)
+        path = pathlib.Path(__file__).parent / ('root.core1.wasm')
+        module = wasmtime.Module.from_file(store.engine, path)
+        instance2 = wasmtime.Instance(store, module, [
+            instance1["memory"],
+            instance0["0"],
+            instance0["3"],
+            instance0["4"],
+            instance1["cabi_realloc"],
+            instance0["5"],
+            instance0["1"],
+            instance0["2"],
+            trampoline0,
+            instance0["6"],
+            instance0["7"],
+            instance0["8"],
+            trampoline1,
+            trampoline2,
+            trampoline3,
+            trampoline4,
+            trampoline5,
+            trampoline6,
+            trampoline7,
+            instance0["9"],
+            instance0["10"],
+            trampoline8,
+        ]).exports(store)
+        def lowering9_callee(caller: wasmtime.Caller, arg0: int) -> None:
+            ret = import_object.preopens.get_directories()
+            vec = ret
+            len3 = len(vec)
+            result = self._realloc0(caller, 0, 0, 4, len3 * 12)
+            assert(isinstance(result, int))
+            for i4 in range(0, len3):
+                e = vec[i4]
+                base0 = result + i4 * 12
+                (tuplei,tuplei1,) = e
+                _store(ctypes.c_uint32, self._core_memory0, caller, base0, 0, _clamp(tuplei, 0, 4294967295))
+                ptr, len2 = _encode_utf8(tuplei1, self._realloc0, self._core_memory0, caller)
+                _store(ctypes.c_uint32, self._core_memory0, caller, base0, 8, len2)
+                _store(ctypes.c_uint32, self._core_memory0, caller, base0, 4, ptr)
+            _store(ctypes.c_uint32, self._core_memory0, caller, arg0, 4, len3)
+            _store(ctypes.c_uint32, self._core_memory0, caller, arg0, 0, result)
+        lowering9_ty = wasmtime.FuncType([wasmtime.ValType.i32(), ], [])
+        trampoline9 = wasmtime.Func(store, lowering9_ty, lowering9_callee, access_caller = True)
+        core_memory0 = instance1["memory"]
+        assert(isinstance(core_memory0, wasmtime.Memory))
+        self._core_memory0 = core_memory0
+        realloc0 = instance2["cabi_import_realloc"]
+        assert(isinstance(realloc0, wasmtime.Func))
+        self._realloc0 = realloc0
+        def lowering10_callee(caller: wasmtime.Caller, arg0: int, arg1: int, arg2: int) -> None:
+            ret = import_object.types.write_via_stream(arg0 & 0xffffffff, arg1 & 0xffffffffffffffff)
+            if isinstance(ret, Ok):
+                payload = ret.value
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg2, 0, 0)
+                _store(ctypes.c_uint32, self._core_memory0, caller, arg2, 4, _clamp(payload, 0, 4294967295))
+            elif isinstance(ret, Err):
+                payload0 = ret.value
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg2, 0, 1)
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg2, 4, (payload0).value)
+            else:
+                raise TypeError("invalid variant specified for expected")
+        lowering10_ty = wasmtime.FuncType([wasmtime.ValType.i32(), wasmtime.ValType.i64(), wasmtime.ValType.i32(), ], [])
+        trampoline10 = wasmtime.Func(store, lowering10_ty, lowering10_callee, access_caller = True)
+        def lowering11_callee(caller: wasmtime.Caller, arg0: int, arg1: int) -> None:
+            ret = import_object.types.append_via_stream(arg0 & 0xffffffff)
+            if isinstance(ret, Ok):
+                payload = ret.value
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg1, 0, 0)
+                _store(ctypes.c_uint32, self._core_memory0, caller, arg1, 4, _clamp(payload, 0, 4294967295))
+            elif isinstance(ret, Err):
+                payload0 = ret.value
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg1, 0, 1)
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg1, 4, (payload0).value)
+            else:
+                raise TypeError("invalid variant specified for expected")
+        lowering11_ty = wasmtime.FuncType([wasmtime.ValType.i32(), wasmtime.ValType.i32(), ], [])
+        trampoline11 = wasmtime.Func(store, lowering11_ty, lowering11_callee, access_caller = True)
+        def lowering12_callee(caller: wasmtime.Caller, arg0: int, arg1: int) -> None:
+            ret = import_object.types.get_type(arg0 & 0xffffffff)
+            if isinstance(ret, Ok):
+                payload = ret.value
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg1, 0, 0)
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg1, 1, (payload).value)
+            elif isinstance(ret, Err):
+                payload0 = ret.value
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg1, 0, 1)
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg1, 1, (payload0).value)
+            else:
+                raise TypeError("invalid variant specified for expected")
+        lowering12_ty = wasmtime.FuncType([wasmtime.ValType.i32(), wasmtime.ValType.i32(), ], [])
+        trampoline12 = wasmtime.Func(store, lowering12_ty, lowering12_callee, access_caller = True)
+        def lowering13_callee(caller: wasmtime.Caller, arg0: int, arg1: int) -> None:
+            ret = import_object.random.get_random_bytes(arg0 & 0xffffffffffffffff)
+            ptr, len0 = _list_canon_lower(ret, ctypes.c_uint8, 1, 1, self._realloc0, self._core_memory0, caller)
+            _store(ctypes.c_uint32, self._core_memory0, caller, arg1, 4, len0)
+            _store(ctypes.c_uint32, self._core_memory0, caller, arg1, 0, ptr)
+        lowering13_ty = wasmtime.FuncType([wasmtime.ValType.i64(), wasmtime.ValType.i32(), ], [])
+        trampoline13 = wasmtime.Func(store, lowering13_ty, lowering13_callee, access_caller = True)
+        def lowering14_callee(caller: wasmtime.Caller, arg0: int) -> None:
+            ret = import_object.environment.get_environment()
+            vec = ret
+            len5 = len(vec)
+            result = self._realloc0(caller, 0, 0, 4, len5 * 16)
+            assert(isinstance(result, int))
+            for i6 in range(0, len5):
+                e = vec[i6]
+                base0 = result + i6 * 16
+                (tuplei,tuplei1,) = e
+                ptr, len2 = _encode_utf8(tuplei, self._realloc0, self._core_memory0, caller)
+                _store(ctypes.c_uint32, self._core_memory0, caller, base0, 4, len2)
+                _store(ctypes.c_uint32, self._core_memory0, caller, base0, 0, ptr)
+                ptr3, len4 = _encode_utf8(tuplei1, self._realloc0, self._core_memory0, caller)
+                _store(ctypes.c_uint32, self._core_memory0, caller, base0, 12, len4)
+                _store(ctypes.c_uint32, self._core_memory0, caller, base0, 8, ptr3)
+            _store(ctypes.c_uint32, self._core_memory0, caller, arg0, 4, len5)
+            _store(ctypes.c_uint32, self._core_memory0, caller, arg0, 0, result)
+        lowering14_ty = wasmtime.FuncType([wasmtime.ValType.i32(), ], [])
+        trampoline14 = wasmtime.Func(store, lowering14_ty, lowering14_callee, access_caller = True)
+        def lowering15_callee(caller: wasmtime.Caller, arg0: int) -> None:
+            ret = import_object.terminal_stderr.get_terminal_stderr()
+            if ret is None:
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg0, 0, 0)
+            else:
+                payload0 = ret
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg0, 0, 1)
+                _store(ctypes.c_uint32, self._core_memory0, caller, arg0, 4, _clamp(payload0, 0, 4294967295))
+        lowering15_ty = wasmtime.FuncType([wasmtime.ValType.i32(), ], [])
+        trampoline15 = wasmtime.Func(store, lowering15_ty, lowering15_callee, access_caller = True)
+        def lowering16_callee(caller: wasmtime.Caller, arg0: int) -> None:
+            ret = import_object.terminal_stdin.get_terminal_stdin()
+            if ret is None:
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg0, 0, 0)
+            else:
+                payload0 = ret
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg0, 0, 1)
+                _store(ctypes.c_uint32, self._core_memory0, caller, arg0, 4, _clamp(payload0, 0, 4294967295))
+        lowering16_ty = wasmtime.FuncType([wasmtime.ValType.i32(), ], [])
+        trampoline16 = wasmtime.Func(store, lowering16_ty, lowering16_callee, access_caller = True)
+        def lowering17_callee(caller: wasmtime.Caller, arg0: int) -> None:
+            ret = import_object.terminal_stdout.get_terminal_stdout()
+            if ret is None:
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg0, 0, 0)
+            else:
+                payload0 = ret
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg0, 0, 1)
+                _store(ctypes.c_uint32, self._core_memory0, caller, arg0, 4, _clamp(payload0, 0, 4294967295))
+        lowering17_ty = wasmtime.FuncType([wasmtime.ValType.i32(), ], [])
+        trampoline17 = wasmtime.Func(store, lowering17_ty, lowering17_callee, access_caller = True)
+        def lowering18_callee(caller: wasmtime.Caller, arg0: int, arg1: int, arg2: int, arg3: int) -> None:
+            ptr = arg1
+            len0 = arg2
+            list = cast(bytes, _list_canon_lift(ptr, len0, 1, ctypes.c_uint8, self._core_memory0, caller))
+            ret = import_object.streams.write(arg0 & 0xffffffff, list)
+            if isinstance(ret, Ok):
+                payload = ret.value
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg3, 0, 0)
+                (tuplei,tuplei1,) = payload
+                _store(ctypes.c_uint64, self._core_memory0, caller, arg3, 8, _clamp(tuplei, 0, 18446744073709551615))
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg3, 16, (tuplei1).value)
+            elif isinstance(ret, Err):
+                payload2 = ret.value
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg3, 0, 1)
+            else:
+                raise TypeError("invalid variant specified for expected")
+        lowering18_ty = wasmtime.FuncType([wasmtime.ValType.i32(), wasmtime.ValType.i32(), wasmtime.ValType.i32(), wasmtime.ValType.i32(), ], [])
+        trampoline18 = wasmtime.Func(store, lowering18_ty, lowering18_callee, access_caller = True)
+        def lowering19_callee(caller: wasmtime.Caller, arg0: int, arg1: int, arg2: int, arg3: int) -> None:
+            ptr = arg1
+            len0 = arg2
+            list = cast(bytes, _list_canon_lift(ptr, len0, 1, ctypes.c_uint8, self._core_memory0, caller))
+            ret = import_object.streams.blocking_write(arg0 & 0xffffffff, list)
+            if isinstance(ret, Ok):
+                payload = ret.value
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg3, 0, 0)
+                (tuplei,tuplei1,) = payload
+                _store(ctypes.c_uint64, self._core_memory0, caller, arg3, 8, _clamp(tuplei, 0, 18446744073709551615))
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg3, 16, (tuplei1).value)
+            elif isinstance(ret, Err):
+                payload2 = ret.value
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg3, 0, 1)
+            else:
+                raise TypeError("invalid variant specified for expected")
+        lowering19_ty = wasmtime.FuncType([wasmtime.ValType.i32(), wasmtime.ValType.i32(), wasmtime.ValType.i32(), wasmtime.ValType.i32(), ], [])
+        trampoline19 = wasmtime.Func(store, lowering19_ty, lowering19_callee, access_caller = True)
+        path = pathlib.Path(__file__).parent / ('root.core3.wasm')
+        module = wasmtime.Module.from_file(store.engine, path)
+        instance3 = wasmtime.Instance(store, module, [
+            trampoline9,
+            trampoline10,
+            trampoline11,
+            trampoline12,
+            trampoline13,
+            trampoline14,
+            trampoline15,
+            trampoline16,
+            trampoline17,
+            trampoline18,
+            trampoline19,
+            instance2["fd_write"],
+            instance2["random_get"],
+            instance2["environ_get"],
+            instance2["environ_sizes_get"],
+            instance2["proc_exit"],
+            instance0["$imports"],
+        ]).exports(store)
+        realloc1 = instance1["cabi_realloc"]
+        assert(isinstance(realloc1, wasmtime.Func))
+        self._realloc1 = realloc1
+        post_return0 = instance1["cabi_post_generate"]
+        assert(isinstance(post_return0, wasmtime.Func))
+        self._post_return0 = post_return0
+        lift_callee0 = instance1["generate"]
+        assert(isinstance(lift_callee0, wasmtime.Func))
+        self.lift_callee0 = lift_callee0
+    def generate(self, caller: wasmtime.Store, name: str, wit: bytes) -> Result[List[Tuple[str, bytes]], str]:
+        ptr, len0 = _encode_utf8(name, self._realloc1, self._core_memory0, caller)
+        ptr1, len2 = _list_canon_lower(wit, ctypes.c_uint8, 1, 1, self._realloc1, self._core_memory0, caller)
+        ret = self.lift_callee0(caller, ptr, len0, ptr1, len2)
+        assert(isinstance(ret, int))
+        load = _load(ctypes.c_uint8, self._core_memory0, caller, ret, 0)
+        expected: Result[List[Tuple[str, bytes]], str]
+        if load == 0:
+            load3 = _load(ctypes.c_int32, self._core_memory0, caller, ret, 4)
+            load4 = _load(ctypes.c_int32, self._core_memory0, caller, ret, 8)
+            ptr15 = load3
+            len16 = load4
+            result: List[Tuple[str, bytes]] = []
+            for i17 in range(0, len16):
+                base5 = ptr15 + i17 * 16
+                load6 = _load(ctypes.c_int32, self._core_memory0, caller, base5, 0)
+                load7 = _load(ctypes.c_int32, self._core_memory0, caller, base5, 4)
+                ptr8 = load6
+                len9 = load7
+                list = _decode_utf8(self._core_memory0, caller, ptr8, len9)
+                load10 = _load(ctypes.c_int32, self._core_memory0, caller, base5, 8)
+                load11 = _load(ctypes.c_int32, self._core_memory0, caller, base5, 12)
+                ptr12 = load10
+                len13 = load11
+                list14 = cast(bytes, _list_canon_lift(ptr12, len13, 1, ctypes.c_uint8, self._core_memory0, caller))
+                result.append((list, list14,))
+            expected = Ok(result)
+        elif load == 1:
+            load18 = _load(ctypes.c_int32, self._core_memory0, caller, ret, 4)
+            load19 = _load(ctypes.c_int32, self._core_memory0, caller, ret, 8)
+            ptr20 = load18
+            len21 = load19
+            list22 = _decode_utf8(self._core_memory0, caller, ptr20, len21)
+            expected = Err(list22)
+        else:
+            raise TypeError("invalid variant discriminant for expected")
+        self._post_return0(caller, ret)
+        return expected
+
+
+
+

Sub-modules

+
+
wasmtime.bindgen.generated.imports
+
+
+
+
wasmtime.bindgen.generated.intrinsics
+
+
+
+
wasmtime.bindgen.generated.types
+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class Root +(store: wasmtime._store.Store, import_object: RootImports) +
+
+
+
+ +Expand source code + +
class Root:
+    
+    def __init__(self, store: wasmtime.Store, import_object: RootImports) -> None:
+        path = pathlib.Path(__file__).parent / ('root.core2.wasm')
+        module = wasmtime.Module.from_file(store.engine, path)
+        instance0 = wasmtime.Instance(store, module, []).exports(store)
+        path = pathlib.Path(__file__).parent / ('root.core0.wasm')
+        module = wasmtime.Module.from_file(store.engine, path)
+        instance1 = wasmtime.Instance(store, module, [
+            instance0["11"],
+            instance0["12"],
+            instance0["13"],
+            instance0["14"],
+            instance0["15"],
+        ]).exports(store)
+        def lowering0_callee(caller: wasmtime.Caller, arg0: int) -> None:
+            import_object.types.drop_descriptor(arg0 & 0xffffffff)
+        lowering0_ty = wasmtime.FuncType([wasmtime.ValType.i32(), ], [])
+        trampoline0 = wasmtime.Func(store, lowering0_ty, lowering0_callee, access_caller = True)
+        def lowering1_callee(caller: wasmtime.Caller) -> int:
+            ret = import_object.stdin.get_stdin()
+            return _clamp(ret, 0, 4294967295)
+        lowering1_ty = wasmtime.FuncType([], [wasmtime.ValType.i32(), ])
+        trampoline1 = wasmtime.Func(store, lowering1_ty, lowering1_callee, access_caller = True)
+        def lowering2_callee(caller: wasmtime.Caller) -> int:
+            ret = import_object.stdout.get_stdout()
+            return _clamp(ret, 0, 4294967295)
+        lowering2_ty = wasmtime.FuncType([], [wasmtime.ValType.i32(), ])
+        trampoline2 = wasmtime.Func(store, lowering2_ty, lowering2_callee, access_caller = True)
+        def lowering3_callee(caller: wasmtime.Caller) -> int:
+            ret = import_object.stderr.get_stderr()
+            return _clamp(ret, 0, 4294967295)
+        lowering3_ty = wasmtime.FuncType([], [wasmtime.ValType.i32(), ])
+        trampoline3 = wasmtime.Func(store, lowering3_ty, lowering3_callee, access_caller = True)
+        def lowering4_callee(caller: wasmtime.Caller, arg0: int) -> None:
+            import_object.terminal_output.drop_terminal_output(arg0 & 0xffffffff)
+        lowering4_ty = wasmtime.FuncType([wasmtime.ValType.i32(), ], [])
+        trampoline4 = wasmtime.Func(store, lowering4_ty, lowering4_callee, access_caller = True)
+        def lowering5_callee(caller: wasmtime.Caller, arg0: int) -> None:
+            import_object.streams.drop_input_stream(arg0 & 0xffffffff)
+        lowering5_ty = wasmtime.FuncType([wasmtime.ValType.i32(), ], [])
+        trampoline5 = wasmtime.Func(store, lowering5_ty, lowering5_callee, access_caller = True)
+        def lowering6_callee(caller: wasmtime.Caller, arg0: int) -> None:
+            import_object.streams.drop_output_stream(arg0 & 0xffffffff)
+        lowering6_ty = wasmtime.FuncType([wasmtime.ValType.i32(), ], [])
+        trampoline6 = wasmtime.Func(store, lowering6_ty, lowering6_callee, access_caller = True)
+        def lowering7_callee(caller: wasmtime.Caller, arg0: int) -> None:
+            import_object.terminal_input.drop_terminal_input(arg0 & 0xffffffff)
+        lowering7_ty = wasmtime.FuncType([wasmtime.ValType.i32(), ], [])
+        trampoline7 = wasmtime.Func(store, lowering7_ty, lowering7_callee, access_caller = True)
+        def lowering8_callee(caller: wasmtime.Caller, arg0: int) -> None:
+            expected: Result[None, None]
+            if arg0 == 0:
+                expected = Ok(None)
+            elif arg0 == 1:
+                expected = Err(None)
+            else:
+                raise TypeError("invalid variant discriminant for expected")
+            import_object.exit.exit(expected)
+        lowering8_ty = wasmtime.FuncType([wasmtime.ValType.i32(), ], [])
+        trampoline8 = wasmtime.Func(store, lowering8_ty, lowering8_callee, access_caller = True)
+        path = pathlib.Path(__file__).parent / ('root.core1.wasm')
+        module = wasmtime.Module.from_file(store.engine, path)
+        instance2 = wasmtime.Instance(store, module, [
+            instance1["memory"],
+            instance0["0"],
+            instance0["3"],
+            instance0["4"],
+            instance1["cabi_realloc"],
+            instance0["5"],
+            instance0["1"],
+            instance0["2"],
+            trampoline0,
+            instance0["6"],
+            instance0["7"],
+            instance0["8"],
+            trampoline1,
+            trampoline2,
+            trampoline3,
+            trampoline4,
+            trampoline5,
+            trampoline6,
+            trampoline7,
+            instance0["9"],
+            instance0["10"],
+            trampoline8,
+        ]).exports(store)
+        def lowering9_callee(caller: wasmtime.Caller, arg0: int) -> None:
+            ret = import_object.preopens.get_directories()
+            vec = ret
+            len3 = len(vec)
+            result = self._realloc0(caller, 0, 0, 4, len3 * 12)
+            assert(isinstance(result, int))
+            for i4 in range(0, len3):
+                e = vec[i4]
+                base0 = result + i4 * 12
+                (tuplei,tuplei1,) = e
+                _store(ctypes.c_uint32, self._core_memory0, caller, base0, 0, _clamp(tuplei, 0, 4294967295))
+                ptr, len2 = _encode_utf8(tuplei1, self._realloc0, self._core_memory0, caller)
+                _store(ctypes.c_uint32, self._core_memory0, caller, base0, 8, len2)
+                _store(ctypes.c_uint32, self._core_memory0, caller, base0, 4, ptr)
+            _store(ctypes.c_uint32, self._core_memory0, caller, arg0, 4, len3)
+            _store(ctypes.c_uint32, self._core_memory0, caller, arg0, 0, result)
+        lowering9_ty = wasmtime.FuncType([wasmtime.ValType.i32(), ], [])
+        trampoline9 = wasmtime.Func(store, lowering9_ty, lowering9_callee, access_caller = True)
+        core_memory0 = instance1["memory"]
+        assert(isinstance(core_memory0, wasmtime.Memory))
+        self._core_memory0 = core_memory0
+        realloc0 = instance2["cabi_import_realloc"]
+        assert(isinstance(realloc0, wasmtime.Func))
+        self._realloc0 = realloc0
+        def lowering10_callee(caller: wasmtime.Caller, arg0: int, arg1: int, arg2: int) -> None:
+            ret = import_object.types.write_via_stream(arg0 & 0xffffffff, arg1 & 0xffffffffffffffff)
+            if isinstance(ret, Ok):
+                payload = ret.value
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg2, 0, 0)
+                _store(ctypes.c_uint32, self._core_memory0, caller, arg2, 4, _clamp(payload, 0, 4294967295))
+            elif isinstance(ret, Err):
+                payload0 = ret.value
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg2, 0, 1)
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg2, 4, (payload0).value)
+            else:
+                raise TypeError("invalid variant specified for expected")
+        lowering10_ty = wasmtime.FuncType([wasmtime.ValType.i32(), wasmtime.ValType.i64(), wasmtime.ValType.i32(), ], [])
+        trampoline10 = wasmtime.Func(store, lowering10_ty, lowering10_callee, access_caller = True)
+        def lowering11_callee(caller: wasmtime.Caller, arg0: int, arg1: int) -> None:
+            ret = import_object.types.append_via_stream(arg0 & 0xffffffff)
+            if isinstance(ret, Ok):
+                payload = ret.value
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg1, 0, 0)
+                _store(ctypes.c_uint32, self._core_memory0, caller, arg1, 4, _clamp(payload, 0, 4294967295))
+            elif isinstance(ret, Err):
+                payload0 = ret.value
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg1, 0, 1)
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg1, 4, (payload0).value)
+            else:
+                raise TypeError("invalid variant specified for expected")
+        lowering11_ty = wasmtime.FuncType([wasmtime.ValType.i32(), wasmtime.ValType.i32(), ], [])
+        trampoline11 = wasmtime.Func(store, lowering11_ty, lowering11_callee, access_caller = True)
+        def lowering12_callee(caller: wasmtime.Caller, arg0: int, arg1: int) -> None:
+            ret = import_object.types.get_type(arg0 & 0xffffffff)
+            if isinstance(ret, Ok):
+                payload = ret.value
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg1, 0, 0)
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg1, 1, (payload).value)
+            elif isinstance(ret, Err):
+                payload0 = ret.value
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg1, 0, 1)
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg1, 1, (payload0).value)
+            else:
+                raise TypeError("invalid variant specified for expected")
+        lowering12_ty = wasmtime.FuncType([wasmtime.ValType.i32(), wasmtime.ValType.i32(), ], [])
+        trampoline12 = wasmtime.Func(store, lowering12_ty, lowering12_callee, access_caller = True)
+        def lowering13_callee(caller: wasmtime.Caller, arg0: int, arg1: int) -> None:
+            ret = import_object.random.get_random_bytes(arg0 & 0xffffffffffffffff)
+            ptr, len0 = _list_canon_lower(ret, ctypes.c_uint8, 1, 1, self._realloc0, self._core_memory0, caller)
+            _store(ctypes.c_uint32, self._core_memory0, caller, arg1, 4, len0)
+            _store(ctypes.c_uint32, self._core_memory0, caller, arg1, 0, ptr)
+        lowering13_ty = wasmtime.FuncType([wasmtime.ValType.i64(), wasmtime.ValType.i32(), ], [])
+        trampoline13 = wasmtime.Func(store, lowering13_ty, lowering13_callee, access_caller = True)
+        def lowering14_callee(caller: wasmtime.Caller, arg0: int) -> None:
+            ret = import_object.environment.get_environment()
+            vec = ret
+            len5 = len(vec)
+            result = self._realloc0(caller, 0, 0, 4, len5 * 16)
+            assert(isinstance(result, int))
+            for i6 in range(0, len5):
+                e = vec[i6]
+                base0 = result + i6 * 16
+                (tuplei,tuplei1,) = e
+                ptr, len2 = _encode_utf8(tuplei, self._realloc0, self._core_memory0, caller)
+                _store(ctypes.c_uint32, self._core_memory0, caller, base0, 4, len2)
+                _store(ctypes.c_uint32, self._core_memory0, caller, base0, 0, ptr)
+                ptr3, len4 = _encode_utf8(tuplei1, self._realloc0, self._core_memory0, caller)
+                _store(ctypes.c_uint32, self._core_memory0, caller, base0, 12, len4)
+                _store(ctypes.c_uint32, self._core_memory0, caller, base0, 8, ptr3)
+            _store(ctypes.c_uint32, self._core_memory0, caller, arg0, 4, len5)
+            _store(ctypes.c_uint32, self._core_memory0, caller, arg0, 0, result)
+        lowering14_ty = wasmtime.FuncType([wasmtime.ValType.i32(), ], [])
+        trampoline14 = wasmtime.Func(store, lowering14_ty, lowering14_callee, access_caller = True)
+        def lowering15_callee(caller: wasmtime.Caller, arg0: int) -> None:
+            ret = import_object.terminal_stderr.get_terminal_stderr()
+            if ret is None:
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg0, 0, 0)
+            else:
+                payload0 = ret
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg0, 0, 1)
+                _store(ctypes.c_uint32, self._core_memory0, caller, arg0, 4, _clamp(payload0, 0, 4294967295))
+        lowering15_ty = wasmtime.FuncType([wasmtime.ValType.i32(), ], [])
+        trampoline15 = wasmtime.Func(store, lowering15_ty, lowering15_callee, access_caller = True)
+        def lowering16_callee(caller: wasmtime.Caller, arg0: int) -> None:
+            ret = import_object.terminal_stdin.get_terminal_stdin()
+            if ret is None:
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg0, 0, 0)
+            else:
+                payload0 = ret
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg0, 0, 1)
+                _store(ctypes.c_uint32, self._core_memory0, caller, arg0, 4, _clamp(payload0, 0, 4294967295))
+        lowering16_ty = wasmtime.FuncType([wasmtime.ValType.i32(), ], [])
+        trampoline16 = wasmtime.Func(store, lowering16_ty, lowering16_callee, access_caller = True)
+        def lowering17_callee(caller: wasmtime.Caller, arg0: int) -> None:
+            ret = import_object.terminal_stdout.get_terminal_stdout()
+            if ret is None:
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg0, 0, 0)
+            else:
+                payload0 = ret
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg0, 0, 1)
+                _store(ctypes.c_uint32, self._core_memory0, caller, arg0, 4, _clamp(payload0, 0, 4294967295))
+        lowering17_ty = wasmtime.FuncType([wasmtime.ValType.i32(), ], [])
+        trampoline17 = wasmtime.Func(store, lowering17_ty, lowering17_callee, access_caller = True)
+        def lowering18_callee(caller: wasmtime.Caller, arg0: int, arg1: int, arg2: int, arg3: int) -> None:
+            ptr = arg1
+            len0 = arg2
+            list = cast(bytes, _list_canon_lift(ptr, len0, 1, ctypes.c_uint8, self._core_memory0, caller))
+            ret = import_object.streams.write(arg0 & 0xffffffff, list)
+            if isinstance(ret, Ok):
+                payload = ret.value
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg3, 0, 0)
+                (tuplei,tuplei1,) = payload
+                _store(ctypes.c_uint64, self._core_memory0, caller, arg3, 8, _clamp(tuplei, 0, 18446744073709551615))
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg3, 16, (tuplei1).value)
+            elif isinstance(ret, Err):
+                payload2 = ret.value
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg3, 0, 1)
+            else:
+                raise TypeError("invalid variant specified for expected")
+        lowering18_ty = wasmtime.FuncType([wasmtime.ValType.i32(), wasmtime.ValType.i32(), wasmtime.ValType.i32(), wasmtime.ValType.i32(), ], [])
+        trampoline18 = wasmtime.Func(store, lowering18_ty, lowering18_callee, access_caller = True)
+        def lowering19_callee(caller: wasmtime.Caller, arg0: int, arg1: int, arg2: int, arg3: int) -> None:
+            ptr = arg1
+            len0 = arg2
+            list = cast(bytes, _list_canon_lift(ptr, len0, 1, ctypes.c_uint8, self._core_memory0, caller))
+            ret = import_object.streams.blocking_write(arg0 & 0xffffffff, list)
+            if isinstance(ret, Ok):
+                payload = ret.value
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg3, 0, 0)
+                (tuplei,tuplei1,) = payload
+                _store(ctypes.c_uint64, self._core_memory0, caller, arg3, 8, _clamp(tuplei, 0, 18446744073709551615))
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg3, 16, (tuplei1).value)
+            elif isinstance(ret, Err):
+                payload2 = ret.value
+                _store(ctypes.c_uint8, self._core_memory0, caller, arg3, 0, 1)
+            else:
+                raise TypeError("invalid variant specified for expected")
+        lowering19_ty = wasmtime.FuncType([wasmtime.ValType.i32(), wasmtime.ValType.i32(), wasmtime.ValType.i32(), wasmtime.ValType.i32(), ], [])
+        trampoline19 = wasmtime.Func(store, lowering19_ty, lowering19_callee, access_caller = True)
+        path = pathlib.Path(__file__).parent / ('root.core3.wasm')
+        module = wasmtime.Module.from_file(store.engine, path)
+        instance3 = wasmtime.Instance(store, module, [
+            trampoline9,
+            trampoline10,
+            trampoline11,
+            trampoline12,
+            trampoline13,
+            trampoline14,
+            trampoline15,
+            trampoline16,
+            trampoline17,
+            trampoline18,
+            trampoline19,
+            instance2["fd_write"],
+            instance2["random_get"],
+            instance2["environ_get"],
+            instance2["environ_sizes_get"],
+            instance2["proc_exit"],
+            instance0["$imports"],
+        ]).exports(store)
+        realloc1 = instance1["cabi_realloc"]
+        assert(isinstance(realloc1, wasmtime.Func))
+        self._realloc1 = realloc1
+        post_return0 = instance1["cabi_post_generate"]
+        assert(isinstance(post_return0, wasmtime.Func))
+        self._post_return0 = post_return0
+        lift_callee0 = instance1["generate"]
+        assert(isinstance(lift_callee0, wasmtime.Func))
+        self.lift_callee0 = lift_callee0
+    def generate(self, caller: wasmtime.Store, name: str, wit: bytes) -> Result[List[Tuple[str, bytes]], str]:
+        ptr, len0 = _encode_utf8(name, self._realloc1, self._core_memory0, caller)
+        ptr1, len2 = _list_canon_lower(wit, ctypes.c_uint8, 1, 1, self._realloc1, self._core_memory0, caller)
+        ret = self.lift_callee0(caller, ptr, len0, ptr1, len2)
+        assert(isinstance(ret, int))
+        load = _load(ctypes.c_uint8, self._core_memory0, caller, ret, 0)
+        expected: Result[List[Tuple[str, bytes]], str]
+        if load == 0:
+            load3 = _load(ctypes.c_int32, self._core_memory0, caller, ret, 4)
+            load4 = _load(ctypes.c_int32, self._core_memory0, caller, ret, 8)
+            ptr15 = load3
+            len16 = load4
+            result: List[Tuple[str, bytes]] = []
+            for i17 in range(0, len16):
+                base5 = ptr15 + i17 * 16
+                load6 = _load(ctypes.c_int32, self._core_memory0, caller, base5, 0)
+                load7 = _load(ctypes.c_int32, self._core_memory0, caller, base5, 4)
+                ptr8 = load6
+                len9 = load7
+                list = _decode_utf8(self._core_memory0, caller, ptr8, len9)
+                load10 = _load(ctypes.c_int32, self._core_memory0, caller, base5, 8)
+                load11 = _load(ctypes.c_int32, self._core_memory0, caller, base5, 12)
+                ptr12 = load10
+                len13 = load11
+                list14 = cast(bytes, _list_canon_lift(ptr12, len13, 1, ctypes.c_uint8, self._core_memory0, caller))
+                result.append((list, list14,))
+            expected = Ok(result)
+        elif load == 1:
+            load18 = _load(ctypes.c_int32, self._core_memory0, caller, ret, 4)
+            load19 = _load(ctypes.c_int32, self._core_memory0, caller, ret, 8)
+            ptr20 = load18
+            len21 = load19
+            list22 = _decode_utf8(self._core_memory0, caller, ptr20, len21)
+            expected = Err(list22)
+        else:
+            raise TypeError("invalid variant discriminant for expected")
+        self._post_return0(caller, ret)
+        return expected
+
+

Methods

+
+
+def generate(self, caller: wasmtime._store.Store, name: str, wit: bytes) ‑> Union[Ok[List[Tuple[str, bytes]]], Err[str]] +
+
+
+
+ +Expand source code + +
def generate(self, caller: wasmtime.Store, name: str, wit: bytes) -> Result[List[Tuple[str, bytes]], str]:
+    ptr, len0 = _encode_utf8(name, self._realloc1, self._core_memory0, caller)
+    ptr1, len2 = _list_canon_lower(wit, ctypes.c_uint8, 1, 1, self._realloc1, self._core_memory0, caller)
+    ret = self.lift_callee0(caller, ptr, len0, ptr1, len2)
+    assert(isinstance(ret, int))
+    load = _load(ctypes.c_uint8, self._core_memory0, caller, ret, 0)
+    expected: Result[List[Tuple[str, bytes]], str]
+    if load == 0:
+        load3 = _load(ctypes.c_int32, self._core_memory0, caller, ret, 4)
+        load4 = _load(ctypes.c_int32, self._core_memory0, caller, ret, 8)
+        ptr15 = load3
+        len16 = load4
+        result: List[Tuple[str, bytes]] = []
+        for i17 in range(0, len16):
+            base5 = ptr15 + i17 * 16
+            load6 = _load(ctypes.c_int32, self._core_memory0, caller, base5, 0)
+            load7 = _load(ctypes.c_int32, self._core_memory0, caller, base5, 4)
+            ptr8 = load6
+            len9 = load7
+            list = _decode_utf8(self._core_memory0, caller, ptr8, len9)
+            load10 = _load(ctypes.c_int32, self._core_memory0, caller, base5, 8)
+            load11 = _load(ctypes.c_int32, self._core_memory0, caller, base5, 12)
+            ptr12 = load10
+            len13 = load11
+            list14 = cast(bytes, _list_canon_lift(ptr12, len13, 1, ctypes.c_uint8, self._core_memory0, caller))
+            result.append((list, list14,))
+        expected = Ok(result)
+    elif load == 1:
+        load18 = _load(ctypes.c_int32, self._core_memory0, caller, ret, 4)
+        load19 = _load(ctypes.c_int32, self._core_memory0, caller, ret, 8)
+        ptr20 = load18
+        len21 = load19
+        list22 = _decode_utf8(self._core_memory0, caller, ptr20, len21)
+        expected = Err(list22)
+    else:
+        raise TypeError("invalid variant discriminant for expected")
+    self._post_return0(caller, ret)
+    return expected
+
+
+
+
+
+
+
+ +
+ + + \ No newline at end of file diff --git a/bindgen/generated/intrinsics.html b/bindgen/generated/intrinsics.html new file mode 100644 index 00000000..e7a20012 --- /dev/null +++ b/bindgen/generated/intrinsics.html @@ -0,0 +1,147 @@ + + + + + + +wasmtime.bindgen.generated.intrinsics API documentation + + + + + + + + + + + +
+
+
+

Module wasmtime.bindgen.generated.intrinsics

+
+
+
+ +Expand source code + +
import ctypes
+from typing import Any, List, Tuple
+import wasmtime
+
+
+def _clamp(i: int, min: int, max: int) -> int:
+                        if i < min or i > max:
+                            raise OverflowError(f'must be between {min} and {max}')
+                        return i
+                
+
+def _store(ty: Any, mem: wasmtime.Memory, store: wasmtime.Storelike, base: int, offset: int, val: Any) -> None:
+                        ptr = (base & 0xffffffff) + offset
+                        if ptr + ctypes.sizeof(ty) > mem.data_len(store):
+                            raise IndexError('out-of-bounds store')
+                        raw_base = mem.data_ptr(store)
+                        c_ptr = ctypes.POINTER(ty)(
+                            ty.from_address(ctypes.addressof(raw_base.contents) + ptr)
+                        )
+                        c_ptr[0] = val
+                
+
+def _encode_utf8(val: str, realloc: wasmtime.Func, mem: wasmtime.Memory, store: wasmtime.Storelike) -> Tuple[int, int]:
+                        bytes = val.encode('utf8')
+                        ptr = realloc(store, 0, 0, 1, len(bytes))
+                        assert(isinstance(ptr, int))
+                        ptr = ptr & 0xffffffff
+                        if ptr + len(bytes) > mem.data_len(store):
+                            raise IndexError('string out of bounds')
+                        base = mem.data_ptr(store)
+                        base = ctypes.POINTER(ctypes.c_ubyte)(
+                            ctypes.c_ubyte.from_address(ctypes.addressof(base.contents) + ptr)
+                        )
+                        ctypes.memmove(base, bytes, len(bytes))
+                        return (ptr, len(bytes))
+                
+
+def _list_canon_lower(list: Any, ty: Any, size: int, align: int, realloc: wasmtime.Func, mem: wasmtime.Memory, store: wasmtime.Storelike) -> Tuple[int, int]:
+                        total_size = size * len(list)
+                        ptr = realloc(store, 0, 0, align, total_size)
+                        assert(isinstance(ptr, int))
+                        ptr = ptr & 0xffffffff
+                        if ptr + total_size > mem.data_len(store):
+                            raise IndexError('list realloc return of bounds')
+                        raw_base = mem.data_ptr(store)
+                        base = ctypes.POINTER(ty)(
+                            ty.from_address(ctypes.addressof(raw_base.contents) + ptr)
+                        )
+                        for i, val in enumerate(list):
+                            base[i] = val
+                        return (ptr, len(list))
+                
+
+def _list_canon_lift(ptr: int, len: int, size: int, ty: Any, mem: wasmtime.Memory ,store: wasmtime.Storelike) -> Any:
+                        ptr = ptr & 0xffffffff
+                        len = len & 0xffffffff
+                        if ptr + len * size > mem.data_len(store):
+                            raise IndexError('list out of bounds')
+                        raw_base = mem.data_ptr(store)
+                        base = ctypes.POINTER(ty)(
+                            ty.from_address(ctypes.addressof(raw_base.contents) + ptr)
+                        )
+                        if ty == ctypes.c_uint8:
+                            return ctypes.string_at(base, len)
+                        return base[:len]
+                
+
+def _load(ty: Any, mem: wasmtime.Memory, store: wasmtime.Storelike, base: int, offset: int) -> Any:
+                        ptr = (base & 0xffffffff) + offset
+                        if ptr + ctypes.sizeof(ty) > mem.data_len(store):
+                            raise IndexError('out-of-bounds store')
+                        raw_base = mem.data_ptr(store)
+                        c_ptr = ctypes.POINTER(ty)(
+                            ty.from_address(ctypes.addressof(raw_base.contents) + ptr)
+                        )
+                        return c_ptr[0]
+                
+
+def _decode_utf8(mem: wasmtime.Memory, store: wasmtime.Storelike, ptr: int, len: int) -> str:
+                        ptr = ptr & 0xffffffff
+                        len = len & 0xffffffff
+                        if ptr + len > mem.data_len(store):
+                            raise IndexError('string out of bounds')
+                        base = mem.data_ptr(store)
+                        base = ctypes.POINTER(ctypes.c_ubyte)(
+                            ctypes.c_ubyte.from_address(ctypes.addressof(base.contents) + ptr)
+                        )
+                        return ctypes.string_at(base, len).decode('utf-8')
+                
+
+
+
+
+
+
+
+
+
+
+
+ +
+ + + \ No newline at end of file diff --git a/bindgen/generated/types.html b/bindgen/generated/types.html new file mode 100644 index 00000000..054ddb3d --- /dev/null +++ b/bindgen/generated/types.html @@ -0,0 +1,143 @@ + + + + + + +wasmtime.bindgen.generated.types API documentation + + + + + + + + + + + +
+
+
+

Module wasmtime.bindgen.generated.types

+
+
+
+ +Expand source code + +
from dataclasses import dataclass
+from typing import Generic, TypeVar, Union
+
+
+T = TypeVar('T')
+@dataclass
+class Ok(Generic[T]):
+    value: T
+E = TypeVar('E')
+@dataclass
+class Err(Generic[E]):
+    value: E
+
+Result = Union[Ok[T], Err[E]]
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class Err +(value: ~E) +
+
+

Err(value: ~E)

+
+ +Expand source code + +
@dataclass
+class Err(Generic[E]):
+    value: E
+
+

Ancestors

+
    +
  • typing.Generic
  • +
+

Class variables

+
+
var value : ~E
+
+
+
+
+
+
+class Ok +(value: ~T) +
+
+

Ok(value: ~T)

+
+ +Expand source code + +
@dataclass
+class Ok(Generic[T]):
+    value: T
+
+

Ancestors

+
    +
  • typing.Generic
  • +
+

Class variables

+
+
var value : ~T
+
+
+
+
+
+
+
+
+ +
+ + + \ No newline at end of file diff --git a/bindgen/index.html b/bindgen/index.html new file mode 100644 index 00000000..5489fd1e --- /dev/null +++ b/bindgen/index.html @@ -0,0 +1,251 @@ + + + + + + +wasmtime.bindgen API documentation + + + + + + + + + + + +
+
+
+

Module wasmtime.bindgen

+
+
+
+ +Expand source code + +
from .generated import Root, RootImports, Err, imports
+from .generated.imports import streams
+from .generated.imports.types import Descriptor, Filesize, ErrorCode, DescriptorType
+from .generated.imports.terminal_input import TerminalInput
+from .generated.imports.terminal_output import TerminalOutput
+from .generated import types as core_types
+from typing import Mapping, Tuple, List
+
+import sys
+import os
+from wasmtime import Store
+
+
+class WasiRandom(imports.HostRandom):
+    def get_random_bytes(self, len: int) -> bytes:
+        return os.urandom(len)
+
+
+class WasiStdin(imports.HostStdin):
+    def get_stdin(self) -> streams.InputStream:
+        return 0
+
+
+class WasiStdout(imports.HostStdout):
+    def get_stdout(self) -> streams.OutputStream:
+        return 1
+
+
+class WasiStderr(imports.HostStderr):
+    def get_stderr(self) -> streams.OutputStream:
+        return 2
+
+
+class WasiPreopens(imports.HostPreopens):
+    def get_directories(self) -> List[Tuple[Descriptor, str]]:
+        return []
+
+
+class WasiStreams(imports.HostStreams):
+    def drop_input_stream(self, this: streams.InputStream) -> None:
+        return None
+
+    def write(self, this: streams.OutputStream, buf: bytes) -> core_types.Result[Tuple[int, streams.StreamStatus], None]:
+        if this == 1:
+            sys.stdout.buffer.write(buf)
+        elif this == 2:
+            sys.stderr.buffer.write(buf)
+        else:
+            raise NotImplementedError
+        return core_types.Ok((len(buf), streams.StreamStatus.OPEN))
+
+    def blocking_write(self, this: streams.OutputStream, buf: bytes) -> core_types.Result[Tuple[int, streams.StreamStatus], None]:
+        return self.write(this, buf)
+
+    def drop_output_stream(self, this: streams.OutputStream) -> None:
+        return None
+
+
+class WasiEnvironment(imports.HostEnvironment):
+    def get_environment(self) -> List[Tuple[str, str]]:
+        return []
+
+
+class WasiTypes(imports.HostTypes):
+    def write_via_stream(self, this: Descriptor, offset: Filesize) -> core_types.Result[streams.OutputStream, ErrorCode]:
+        raise NotImplementedError
+
+    def append_via_stream(self, this: Descriptor) -> core_types.Result[streams.OutputStream, ErrorCode]:
+        raise NotImplementedError
+
+    def get_type(self, this: Descriptor) -> core_types.Result[DescriptorType, ErrorCode]:
+        raise NotImplementedError
+
+    def drop_descriptor(self, this: Descriptor) -> None:
+        raise NotImplementedError
+
+
+class WasiExit(imports.HostExit):
+    def exit(self, status: core_types.Result[None, None]) -> None:
+        raise NotImplementedError
+
+
+class WasiTerminalInput(imports.HostTerminalInput):
+    def drop_terminal_input(self, this: TerminalInput) -> None:
+        raise NotImplementedError
+
+
+class WasiTerminalOutput(imports.HostTerminalOutput):
+    def drop_terminal_output(self, this: TerminalOutput) -> None:
+        raise NotImplementedError
+
+
+class WasiTerminalStdin(imports.HostTerminalStdin):
+    def get_terminal_stdin(self) -> None:
+        raise NotImplementedError
+
+
+class WasiTerminalStdout(imports.HostTerminalStdout):
+    def get_terminal_stdout(self) -> None:
+        raise NotImplementedError
+
+
+class WasiTerminalStderr(imports.HostTerminalStderr):
+    def get_terminal_stderr(self) -> None:
+        raise NotImplementedError
+
+
+root = None
+store = None
+
+
+def init() -> Tuple[Root, Store]:
+    global store
+    global root
+    if root is None:
+        store = Store()
+        root = Root(store, RootImports(WasiStreams(),
+                                       WasiTypes(),
+                                       WasiPreopens(),
+                                       WasiRandom(),
+                                       WasiEnvironment(),
+                                       WasiExit(),
+                                       WasiStdin(),
+                                       WasiStdout(),
+                                       WasiStderr(),
+                                       WasiTerminalInput(),
+                                       WasiTerminalOutput(),
+                                       WasiTerminalStdin(),
+                                       WasiTerminalStdout(),
+                                       WasiTerminalStderr()))
+    return root, store
+
+
+# Generates Python bindings for the given component.
+#
+# The `name` provided is used as the name of the `component` binary provided.
+# The `component` argument is expected to be the binary representation of a
+# component.
+#
+# This function returns a mapping of filename to contents of files that are
+# generated to represent the Python bindings here.
+def generate(name: str, component: bytes) -> Mapping[str, bytes]:
+    root, store = init()
+    result = root.generate(store, name, component)
+    if isinstance(result, Err):
+        raise RuntimeError(result.value)
+    ret = {}
+    for name, contents in result.value:
+        ret[name] = contents
+    return ret
+
+
+__all__ = ['generate']
+
+
+
+

Sub-modules

+
+
wasmtime.bindgen.generated
+
+
+
+
+
+
+
+
+

Functions

+
+
+def generate(name: str, component: bytes) ‑> Mapping[str, bytes] +
+
+
+
+ +Expand source code + +
def generate(name: str, component: bytes) -> Mapping[str, bytes]:
+    root, store = init()
+    result = root.generate(store, name, component)
+    if isinstance(result, Err):
+        raise RuntimeError(result.value)
+    ret = {}
+    for name, contents in result.value:
+        ret[name] = contents
+    return ret
+
+
+
+
+
+
+
+ +
+ + + \ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 00000000..a0d6791c --- /dev/null +++ b/index.html @@ -0,0 +1,5484 @@ + + + + + + +wasmtime API documentation + + + + + + + + + + + +
+
+
+

Package wasmtime

+
+
+

Python bindings for the Wasmtime project

+

This library binds the Wasmtime project's C API to provide an implementation +of a WebAssembly JIT compiler to Python. You can validate, compile, instantiate, +and interact with WebAssembly modules via this library.

+

The API of this library is intended to be very similar to the wasmtime Rust +crate, so if you find the docs are lacking here feel +free to consult that documentation as well. While not exactly the same the two +libraries are intended to be quite similar.

+
+ +Expand source code + +
"""
+Python bindings for the [Wasmtime project]
+
+[Wasmtime project]: https://github.com/bytecodealliance/wasmtime
+
+This library binds the [Wasmtime project]'s C API to provide an implementation
+of a WebAssembly JIT compiler to Python. You can validate, compile, instantiate,
+and interact with WebAssembly modules via this library.
+
+The API of this library is intended to be very similar to the [`wasmtime` Rust
+crate](https://docs.rs/wasmtime), so if you find the docs are lacking here feel
+free to consult that documentation as well. While not exactly the same the two
+libraries are intended to be quite similar.
+"""
+
+from ._error import WasmtimeError, ExitTrap
+from ._config import Config
+from ._engine import Engine
+from ._store import Store, Storelike
+from ._types import FuncType, GlobalType, MemoryType, TableType
+from ._types import ValType, Limits, ImportType, ExportType
+from ._wat2wasm import wat2wasm
+from ._module import Module
+from ._value import Val, IntoVal
+from ._trap import Trap, Frame, TrapCode
+from ._func import Func, Caller
+from ._globals import Global
+from ._table import Table
+from ._memory import Memory
+from ._instance import Instance
+from ._wasi import WasiConfig
+from ._linker import Linker
+
+__all__ = [
+    'wat2wasm',
+    'Config',
+    'Engine',
+    'Store',
+    'FuncType',
+    'GlobalType',
+    'MemoryType',
+    'TableType',
+    'ValType',
+    'Limits',
+    'ImportType',
+    'ExportType',
+    'IntoVal',
+    'Val',
+    'Func',
+    'Caller',
+    'Table',
+    'Memory',
+    'Global',
+    'Trap',
+    'TrapCode',
+    'ExitTrap',
+    'Frame',
+    'Module',
+    'Instance',
+    'WasiConfig',
+    'Linker',
+    'WasmtimeError',
+]
+
+
+
+

Sub-modules

+
+
wasmtime.bindgen
+
+
+
+
wasmtime.loader
+
+

This module is a custom loader for Python which enables importing wasm files +directly into Python programs simply through usage of the import

+
+
+
+
+
+
+

Functions

+
+
+def wat2wasm(wat: Union[str, bytes]) ‑> bytearray +
+
+

Converts the WebAssembly Text format to the binary format.

+

This function is intended to be a convenience function for local +development and you likely don't want to use it extensively in production. +It's much faster to parse and compile the binary format than it is to +process the text format.

+

Takes a str as input, raises an error if it fails to parse, and returns +a bytes if conversion/parsing was successful.

+
>>> wat2wasm('(module)')
+bytearray(b'\x00asm\x01\x00\x00\x00')
+
+
+ +Expand source code + +
def wat2wasm(wat: typing.Union[str, bytes]) -> bytearray:
+    """
+    Converts the [WebAssembly Text format][wat] to the binary format.
+
+    This function is intended to be a convenience function for local
+    development and you likely don't want to use it extensively in production.
+    It's much faster to parse and compile the binary format than it is to
+    process the text format.
+
+    Takes a `str` as input, raises an error if it fails to parse, and returns
+    a `bytes` if conversion/parsing was successful.
+
+    >>> wat2wasm('(module)')
+    bytearray(b'\\x00asm\\x01\\x00\\x00\\x00')
+
+    [wat]: https://webassembly.github.io/spec/core/text/index.html
+    """
+
+    if isinstance(wat, str):
+        wat = wat.encode('utf8')
+    wat_buffer = create_string_buffer(wat)
+    wasm = ffi.wasm_byte_vec_t()
+    error = ffi.wasmtime_wat2wasm(wat_buffer, len(wat), byref(wasm))
+    if error:
+        raise WasmtimeError._from_ptr(error)
+    else:
+        ret = ffi.to_bytes(wasm)
+        ffi.wasm_byte_vec_delete(byref(wasm))
+        return ret
+
+
+
+
+
+

Classes

+
+
+class Caller +(ptr: ctypes._Pointer) +
+
+
+
+ +Expand source code + +
class Caller:
+    _context: "ctypes._Pointer[ffi.wasmtime_context_t]"
+
+    def __init__(self, ptr: "ctypes._Pointer"):
+        self._ptr = ptr
+
+    def __getitem__(self, name: str) -> AsExtern:
+        """
+        Looks up an export with `name` on the calling module.
+
+        If `name` isn't defined on the calling module, or if the caller has gone
+        away for some reason, then this will raise a `KeyError`. For more
+        information about when this could fail see the `get` method which
+        returns `None` on failure.
+        """
+
+        ret = self.get(name)
+        if ret is None:
+            raise KeyError("failed to find export {}".format(name))
+        return ret
+
+    def get(self, name: str) -> Optional[AsExtern]:
+        """
+        Looks up an export with `name` on the calling module.
+
+        May return `None` if the export isn't found, if it's not a memory (for
+        now), or if the caller has gone away and this `Caller` object has
+        persisted too long.
+        """
+
+        # First convert to a raw name so we can typecheck our argument
+        name_bytes = name.encode('utf-8')
+        name_buf = ffi.create_string_buffer(name_bytes)
+
+        # Next see if we've been invalidated
+        if not hasattr(self, '_ptr'):
+            return None
+
+        # And if we're not invalidated we can perform the actual lookup
+        item = ffi.wasmtime_extern_t()
+        ok = ffi.wasmtime_caller_export_get(self._ptr, name_buf, len(name_bytes), byref(item))
+        if ok:
+            return wrap_extern(item)
+        else:
+            return None
+
+

Methods

+
+
+def get(self, name: str) ‑> Union[FuncTableMemoryGlobalInstanceModule, ForwardRef(None)] +
+
+

Looks up an export with name on the calling module.

+

May return None if the export isn't found, if it's not a memory (for +now), or if the caller has gone away and this Caller object has +persisted too long.

+
+ +Expand source code + +
def get(self, name: str) -> Optional[AsExtern]:
+    """
+    Looks up an export with `name` on the calling module.
+
+    May return `None` if the export isn't found, if it's not a memory (for
+    now), or if the caller has gone away and this `Caller` object has
+    persisted too long.
+    """
+
+    # First convert to a raw name so we can typecheck our argument
+    name_bytes = name.encode('utf-8')
+    name_buf = ffi.create_string_buffer(name_bytes)
+
+    # Next see if we've been invalidated
+    if not hasattr(self, '_ptr'):
+        return None
+
+    # And if we're not invalidated we can perform the actual lookup
+    item = ffi.wasmtime_extern_t()
+    ok = ffi.wasmtime_caller_export_get(self._ptr, name_buf, len(name_bytes), byref(item))
+    if ok:
+        return wrap_extern(item)
+    else:
+        return None
+
+
+
+
+
+class Config +
+
+

Global configuration, used to create an Engine.

+

A Config houses a number of configuration options which tweaks how wasm +code is compiled or generated.

+
+ +Expand source code + +
class Config:
+    """
+    Global configuration, used to create an `Engine`.
+
+    A `Config` houses a number of configuration options which tweaks how wasm
+    code is compiled or generated.
+    """
+
+    _ptr: "ctypes._Pointer[ffi.wasm_config_t]"
+
+    def __init__(self) -> None:
+        self._ptr = ffi.wasm_config_new()
+
+    @setter_property
+    def debug_info(self, enable: bool) -> None:
+        """
+        Configures whether DWARF debug information is emitted for the generated
+        code. This can improve profiling and the debugging experience.
+        """
+
+        if not isinstance(enable, bool):
+            raise TypeError('expected a bool')
+        ffi.wasmtime_config_debug_info_set(self._ptr, enable)
+
+    @setter_property
+    def wasm_threads(self, enable: bool) -> None:
+        """
+        Configures whether the wasm [threads proposal] is enabled.
+
+        [threads proposal]: https://github.com/webassembly/threads
+        """
+
+        if not isinstance(enable, bool):
+            raise TypeError('expected a bool')
+        ffi.wasmtime_config_wasm_threads_set(self._ptr, enable)
+
+    @setter_property
+    def wasm_reference_types(self, enable: bool) -> None:
+        """
+        Configures whether the wasm [reference types proposal] is enabled.
+
+        [reference types proposal]: https://github.com/webassembly/reference-types
+        """
+
+        if not isinstance(enable, bool):
+            raise TypeError('expected a bool')
+        ffi.wasmtime_config_wasm_reference_types_set(self._ptr, enable)
+
+    @setter_property
+    def wasm_simd(self, enable: bool) -> None:
+        """
+        Configures whether the wasm [SIMD proposal] is enabled.
+
+        [SIMD proposal]: https://github.com/webassembly/simd
+        """
+
+        if not isinstance(enable, bool):
+            raise TypeError('expected a bool')
+        ffi.wasmtime_config_wasm_simd_set(self._ptr, enable)
+
+    @setter_property
+    def wasm_bulk_memory(self, enable: bool) -> None:
+        """
+        Configures whether the wasm [bulk memory proposal] is enabled.
+
+        [bulk memory proposal]: https://github.com/webassembly/bulk-memory
+        """
+
+        if not isinstance(enable, bool):
+            raise TypeError('expected a bool')
+        ffi.wasmtime_config_wasm_bulk_memory_set(self._ptr, enable)
+
+    @setter_property
+    def wasm_multi_value(self, enable: bool) -> None:
+        """
+        Configures whether the wasm [multi value proposal] is enabled.
+
+        [multi value proposal]: https://github.com/webassembly/multi-value
+        """
+
+        if not isinstance(enable, bool):
+            raise TypeError('expected a bool')
+        ffi.wasmtime_config_wasm_multi_value_set(self._ptr, enable)
+
+    @setter_property
+    def wasm_multi_memory(self, enable: bool) -> None:
+        """
+        Configures whether the wasm [multi memory proposal] is enabled.
+
+        [multi memory proposal]: https://github.com/webassembly/multi-memory
+        """
+
+        if not isinstance(enable, bool):
+            raise TypeError('expected a bool')
+        ffi.wasmtime_config_wasm_multi_memory_set(self._ptr, enable)
+
+    @setter_property
+    def wasm_memory64(self, enable: bool) -> None:
+        """
+        Configures whether the wasm [memory64 proposal] is enabled.
+
+        [memory64 proposal]: https://github.com/webassembly/memory64
+        """
+
+        if not isinstance(enable, bool):
+            raise TypeError('expected a bool')
+        ffi.wasmtime_config_wasm_memory64_set(self._ptr, enable)
+
+    @setter_property
+    def wasm_relaxed_simd(self, enable: bool) -> None:
+        """
+        Configures whether the wasm [relaxed simd proposal] is enabled.
+
+        [relaxed simd proposal]: https://github.com/webassembly/relaxed-simd
+        """
+
+        if not isinstance(enable, bool):
+            raise TypeError('expected a bool')
+        ffi.wasmtime_config_wasm_relaxed_simd_set(self._ptr, enable)
+
+    @setter_property
+    def wasm_relaxed_simd_deterministic(self, enable: bool) -> None:
+        """
+        Configures whether the wasm [relaxed simd proposal] is deterministic
+        in is execution as opposed to having the most optimal implementation for
+        the current platform.
+
+        [relaxed simd proposal]: https://github.com/webassembly/relaxed-simd
+        """
+
+        if not isinstance(enable, bool):
+            raise TypeError('expected a bool')
+        ffi.wasmtime_config_wasm_relaxed_simd_deterministic_set(self._ptr, enable)
+
+    @setter_property
+    def strategy(self, strategy: str) -> None:
+        """
+        Configures the compilation strategy used for wasm code.
+
+        Acceptable values for `strategy` are:
+
+        * `"auto"`
+        * `"cranelift"`
+        """
+
+        if strategy == "auto":
+            ffi.wasmtime_config_strategy_set(self._ptr, 0)
+        elif strategy == "cranelift":
+            ffi.wasmtime_config_strategy_set(self._ptr, 1)
+        else:
+            raise WasmtimeError("unknown strategy: " + str(strategy))
+
+    @setter_property
+    def cranelift_debug_verifier(self, enable: bool) -> None:
+        if not isinstance(enable, bool):
+            raise TypeError('expected a bool')
+        ffi.wasmtime_config_cranelift_debug_verifier_set(self._ptr, enable)
+
+    @setter_property
+    def cranelift_opt_level(self, opt_level: str) -> None:
+        if opt_level == "none":
+            ffi.wasmtime_config_cranelift_opt_level_set(self._ptr, 0)
+        elif opt_level == "speed":
+            ffi.wasmtime_config_cranelift_opt_level_set(self._ptr, 1)
+        elif opt_level == "speed_and_size":
+            ffi.wasmtime_config_cranelift_opt_level_set(self._ptr, 2)
+        else:
+            raise WasmtimeError("unknown opt level: " + str(opt_level))
+
+    @setter_property
+    def profiler(self, profiler: str) -> None:
+        if profiler == "none":
+            ffi.wasmtime_config_profiler_set(self._ptr, 0)
+        elif profiler == "jitdump":
+            ffi.wasmtime_config_profiler_set(self._ptr, 1)
+        else:
+            raise WasmtimeError("unknown profiler: " + str(profiler))
+
+    @setter_property
+    def cache(self, enabled: typing.Union[bool, str]) -> None:
+        """
+        Configures whether code caching is enabled for this `Config`.
+
+        The value `True` can be passed in here to enable the default caching
+        configuration and location, or a path to a file can be passed in which
+        is a path to a TOML configuration file for the cache.
+
+        More information about cache configuration can be found at
+        https://bytecodealliance.github.io/wasmtime/cli-cache.html
+        """
+
+        if isinstance(enabled, bool):
+            if not enabled:
+                raise WasmtimeError("caching cannot be explicitly disabled")
+            error = ffi.wasmtime_config_cache_config_load(self._ptr, None)
+        elif isinstance(enabled, str):
+            error = ffi.wasmtime_config_cache_config_load(self._ptr,
+                                                          c_char_p(enabled.encode('utf-8')))
+        else:
+            raise TypeError("expected string or bool")
+        if error:
+            raise WasmtimeError._from_ptr(error)
+
+    @setter_property
+    def epoch_interruption(self, enabled: bool) -> None:
+        """
+        Configures whether wasm execution can be interrupted via epoch
+        increments.
+        """
+
+        if enabled:
+            val = 1
+        else:
+            val = 0
+        ffi.wasmtime_config_epoch_interruption_set(self._ptr, val)
+
+    @setter_property
+    def consume_fuel(self, instances: bool) -> None:
+        """
+        Configures whether wasm code will consume *fuel* as part of its
+        execution.
+
+        Fuel consumption allows WebAssembly to trap when fuel runs out.
+        Currently stores start with 0 fuel if this is enabled.
+        """
+        if not isinstance(instances, bool):
+            raise TypeError('expected an bool')
+        ffi.wasmtime_config_consume_fuel_set(self._ptr, instances)
+
+    @setter_property
+    def parallel_compilation(self, enable: bool) -> None:
+        """
+        Configures whether parallel compilation is enabled for functions
+        within a module.
+
+        This is enabled by default.
+        """
+        if not isinstance(enable, bool):
+            raise TypeError('expected a bool')
+        ffi.wasmtime_config_parallel_compilation_set(self._ptr, enable)
+
+    def __del__(self) -> None:
+        if hasattr(self, '_ptr'):
+            ffi.wasm_config_delete(self._ptr)
+
+

Instance variables

+
+
var cache
+
+

Configures whether code caching is enabled for this Config.

+

The value True can be passed in here to enable the default caching +configuration and location, or a path to a file can be passed in which +is a path to a TOML configuration file for the cache.

+

More information about cache configuration can be found at +https://bytecodealliance.github.io/wasmtime/cli-cache.html

+

Note that this field can only be set, it cannot be read

+
+
var consume_fuel
+
+

Configures whether wasm code will consume fuel as part of its +execution.

+

Fuel consumption allows WebAssembly to trap when fuel runs out. +Currently stores start with 0 fuel if this is enabled.

+

Note that this field can only be set, it cannot be read

+
+
var cranelift_debug_verifier
+
+
+
+
var cranelift_opt_level
+
+
+
+
var debug_info
+
+

Configures whether DWARF debug information is emitted for the generated +code. This can improve profiling and the debugging experience.

+

Note that this field can only be set, it cannot be read

+
+
var epoch_interruption
+
+

Configures whether wasm execution can be interrupted via epoch +increments.

+

Note that this field can only be set, it cannot be read

+
+
var parallel_compilation
+
+

Configures whether parallel compilation is enabled for functions +within a module.

+

This is enabled by default.

+

Note that this field can only be set, it cannot be read

+
+
var profiler
+
+
+
+
var strategy
+
+

Configures the compilation strategy used for wasm code.

+

Acceptable values for strategy are:

+
    +
  • "auto"
  • +
  • "cranelift"
  • +
+

Note that this field can only be set, it cannot be read

+
+
var wasm_bulk_memory
+
+

Configures whether the wasm bulk memory proposal is enabled.

+

Note that this field can only be set, it cannot be read

+
+
var wasm_memory64
+
+

Configures whether the wasm memory64 proposal is enabled.

+

Note that this field can only be set, it cannot be read

+
+
var wasm_multi_memory
+
+

Configures whether the wasm multi memory proposal is enabled.

+

Note that this field can only be set, it cannot be read

+
+
var wasm_multi_value
+
+

Configures whether the wasm multi value proposal is enabled.

+

Note that this field can only be set, it cannot be read

+
+
var wasm_reference_types
+
+

Configures whether the wasm reference types proposal is enabled.

+

Note that this field can only be set, it cannot be read

+
+
var wasm_relaxed_simd
+
+

Configures whether the wasm relaxed simd proposal is enabled.

+

Note that this field can only be set, it cannot be read

+
+
var wasm_relaxed_simd_deterministic
+
+

Configures whether the wasm relaxed simd proposal is deterministic +in is execution as opposed to having the most optimal implementation for +the current platform.

+

Note that this field can only be set, it cannot be read

+
+
var wasm_simd
+
+

Configures whether the wasm SIMD proposal is enabled.

+

Note that this field can only be set, it cannot be read

+
+
var wasm_threads
+
+

Configures whether the wasm threads proposal is enabled.

+

Note that this field can only be set, it cannot be read

+
+
+
+
+class Engine +(config: Optional[wasmtime._config.Config] = None) +
+
+
+
+ +Expand source code + +
class Engine:
+    _ptr: "ctypes._Pointer[ffi.wasm_engine_t]"
+
+    def __init__(self, config: Optional[Config] = None):
+        if config is None:
+            self._ptr = ffi.wasm_engine_new()
+        elif not isinstance(config, Config):
+            raise TypeError("expected Config")
+        elif not hasattr(config, '_ptr'):
+            raise WasmtimeError("Config already used")
+        else:
+            ptr = config._ptr
+            delattr(config, '_ptr')
+            self._ptr = ffi.wasm_engine_new_with_config(ptr)
+
+    def increment_epoch(self) -> None:
+        ffi.wasmtime_engine_increment_epoch(self._ptr)
+
+    def __del__(self) -> None:
+        if hasattr(self, '_ptr'):
+            ffi.wasm_engine_delete(self._ptr)
+
+

Methods

+
+
+def increment_epoch(self) ‑> None +
+
+
+
+ +Expand source code + +
def increment_epoch(self) -> None:
+    ffi.wasmtime_engine_increment_epoch(self._ptr)
+
+
+
+
+
+class ExitTrap +(message: str) +
+
+

A special type of WasmtimeError which represents the process exiting via +WASI's proc_exit function call.

+

Whenever a WASI program exits via proc_exit a trap is raised, but the +trap will have this type instead of WasmtimeError, so you can catch just +this type instead of all traps (if desired). Exit traps have a code +associated with them which is the exit code provided at exit.

+

Note that ExitTrap is a subclass of WasmtimeError, so if you catch a +trap you'll also catch ExitTrap.

+
+ +Expand source code + +
class ExitTrap(WasmtimeError):
+    """
+    A special type of `WasmtimeError` which represents the process exiting via
+    WASI's `proc_exit` function call.
+
+    Whenever a WASI program exits via `proc_exit` a trap is raised, but the
+    trap will have this type instead of `WasmtimeError`, so you can catch just
+    this type instead of all traps (if desired). Exit traps have a `code`
+    associated with them which is the exit code provided at exit.
+
+    Note that `ExitTrap` is a subclass of `WasmtimeError`, so if you catch a
+    trap you'll also catch `ExitTrap`.
+    """
+    code: int
+    pass
+
+

Ancestors

+
    +
  • wasmtime._error.WasmtimeError
  • +
  • builtins.Exception
  • +
  • builtins.BaseException
  • +
+

Class variables

+
+
var code : int
+
+
+
+
+
+
+class ExportType +
+
+
+
+ +Expand source code + +
class ExportType:
+    _ptr: "ctypes._Pointer[ffi.wasm_exporttype_t]"
+    _owner: Optional[Any]
+
+    @classmethod
+    def _from_ptr(cls, ptr: 'ctypes._Pointer[ffi.wasm_exporttype_t]', owner: Optional[Any]) -> "ExportType":
+        ty: "ExportType" = cls.__new__(cls)
+        if not isinstance(ptr, POINTER(ffi.wasm_exporttype_t)):
+            raise TypeError("wrong pointer type")
+        ty._ptr = ptr
+        ty._owner = owner
+        return ty
+
+    @property
+    def name(self) -> str:
+        """
+        Returns the name in the modulethis export type refers to
+        """
+        return ffi.to_str(ffi.wasm_exporttype_name(self._ptr).contents)
+
+    @property
+    def type(self) -> "AsExternType":
+        """
+        Returns the type that this export refers to
+        """
+        ptr = ffi.wasm_exporttype_type(self._ptr)
+        return wrap_externtype(ptr, self._owner or self)
+
+    def __del__(self) -> None:
+        if self._owner is None:
+            ffi.wasm_exporttype_delete(self._ptr)
+
+

Instance variables

+
+
var name : str
+
+

Returns the name in the modulethis export type refers to

+
+ +Expand source code + +
@property
+def name(self) -> str:
+    """
+    Returns the name in the modulethis export type refers to
+    """
+    return ffi.to_str(ffi.wasm_exporttype_name(self._ptr).contents)
+
+
+
var type : Union[wasmtime._types.FuncType, wasmtime._types.TableType, wasmtime._types.MemoryType, wasmtime._types.GlobalType]
+
+

Returns the type that this export refers to

+
+ +Expand source code + +
@property
+def type(self) -> "AsExternType":
+    """
+    Returns the type that this export refers to
+    """
+    ptr = ffi.wasm_exporttype_type(self._ptr)
+    return wrap_externtype(ptr, self._owner or self)
+
+
+
+
+
+class Frame +
+
+
+
+ +Expand source code + +
class Frame:
+    _ptr: "ctypes._Pointer[ffi.wasm_frame_t]"
+    _owner: Optional[Any]
+
+    @classmethod
+    def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasm_frame_t]", owner: Optional[Any]) -> "Frame":
+        ty: "Frame" = cls.__new__(cls)
+        if not isinstance(ptr, POINTER(ffi.wasm_frame_t)):
+            raise TypeError("wrong pointer type")
+        ty._ptr = ptr
+        ty._owner = owner
+        return ty
+
+    @property
+    def func_index(self) -> int:
+        """
+        Returns the function index this frame corresponds to in its wasm module
+        """
+
+        return ffi.wasm_frame_func_index(self._ptr)
+
+    @property
+    def func_name(self) -> Optional[str]:
+        """
+        Returns the name of the function this frame corresponds to
+
+        May return `None` if no name can be inferred
+        """
+
+        ptr = ffi.wasmtime_frame_func_name(self._ptr)
+        if ptr:
+            return ffi.to_str(ptr.contents)
+        else:
+            return None
+
+    @property
+    def module_name(self) -> Optional[str]:
+        """
+        Returns the name of the module this frame corresponds to
+
+        May return `None` if no name can be inferred
+        """
+
+        ptr = ffi.wasmtime_frame_module_name(self._ptr)
+        if ptr:
+            return ffi.to_str(ptr.contents)
+        else:
+            return None
+
+    @property
+    def module_offset(self) -> int:
+        """
+        Returns the offset of this frame's program counter into the original
+        wasm source module.
+        """
+
+        return ffi.wasm_frame_module_offset(self._ptr)
+
+    @property
+    def func_offset(self) -> int:
+        """
+        Returns the offset of this frame's program counter into the original
+        wasm function.
+        """
+
+        return ffi.wasm_frame_func_offset(self._ptr)
+
+    def __del__(self) -> None:
+        if self._owner is None:
+            ffi.wasm_frame_delete(self._ptr)
+
+

Instance variables

+
+
var func_index : int
+
+

Returns the function index this frame corresponds to in its wasm module

+
+ +Expand source code + +
@property
+def func_index(self) -> int:
+    """
+    Returns the function index this frame corresponds to in its wasm module
+    """
+
+    return ffi.wasm_frame_func_index(self._ptr)
+
+
+
var func_name : Optional[str]
+
+

Returns the name of the function this frame corresponds to

+

May return None if no name can be inferred

+
+ +Expand source code + +
@property
+def func_name(self) -> Optional[str]:
+    """
+    Returns the name of the function this frame corresponds to
+
+    May return `None` if no name can be inferred
+    """
+
+    ptr = ffi.wasmtime_frame_func_name(self._ptr)
+    if ptr:
+        return ffi.to_str(ptr.contents)
+    else:
+        return None
+
+
+
var func_offset : int
+
+

Returns the offset of this frame's program counter into the original +wasm function.

+
+ +Expand source code + +
@property
+def func_offset(self) -> int:
+    """
+    Returns the offset of this frame's program counter into the original
+    wasm function.
+    """
+
+    return ffi.wasm_frame_func_offset(self._ptr)
+
+
+
var module_name : Optional[str]
+
+

Returns the name of the module this frame corresponds to

+

May return None if no name can be inferred

+
+ +Expand source code + +
@property
+def module_name(self) -> Optional[str]:
+    """
+    Returns the name of the module this frame corresponds to
+
+    May return `None` if no name can be inferred
+    """
+
+    ptr = ffi.wasmtime_frame_module_name(self._ptr)
+    if ptr:
+        return ffi.to_str(ptr.contents)
+    else:
+        return None
+
+
+
var module_offset : int
+
+

Returns the offset of this frame's program counter into the original +wasm source module.

+
+ +Expand source code + +
@property
+def module_offset(self) -> int:
+    """
+    Returns the offset of this frame's program counter into the original
+    wasm source module.
+    """
+
+    return ffi.wasm_frame_module_offset(self._ptr)
+
+
+
+
+
+class Func +(store: Union[wasmtime._store.Store, ForwardRef('Caller')], ty: wasmtime._types.FuncType, func: Callable, access_caller: bool = False) +
+
+

Creates a new func in store with the given ty which calls the closure +given

+

The func is called with the parameters natively and they'll have native +Python values rather than being wrapped in Val. If access_caller is +set to True then the first argument given to func is an instance of +type Caller below.

+
+ +Expand source code + +
class Func:
+    _func: ffi.wasmtime_func_t
+
+    def __init__(self, store: Storelike, ty: FuncType, func: Callable, access_caller: bool = False):
+        """
+        Creates a new func in `store` with the given `ty` which calls the closure
+        given
+
+        The `func` is called with the parameters natively and they'll have native
+        Python values rather than being wrapped in `Val`. If `access_caller` is
+        set to `True` then the first argument given to `func` is an instance of
+        type `Caller` below.
+        """
+
+        if not isinstance(store, Store):
+            raise TypeError("expected a Store")
+        if not isinstance(ty, FuncType):
+            raise TypeError("expected a FuncType")
+        idx = FUNCTIONS.allocate((func, ty.results, access_caller))
+        _func = ffi.wasmtime_func_t()
+        ffi.wasmtime_func_new(
+            store._context,
+            ty._ptr,
+            trampoline,
+            idx,
+            finalize,
+            byref(_func))
+        self._func = _func
+
+    @classmethod
+    def _from_raw(cls, func: ffi.wasmtime_func_t) -> "Func":
+        ty: "Func" = cls.__new__(cls)
+        ty._func = func
+        return ty
+
+    def type(self, store: Storelike) -> FuncType:
+        """
+        Gets the type of this func as a `FuncType`
+        """
+        ptr = ffi.wasmtime_func_type(store._context, byref(self._func))
+        return FuncType._from_ptr(ptr, None)
+
+    def __call__(self, store: Storelike, *params: IntoVal) -> Union[IntoVal, Sequence[IntoVal], None]:
+        """
+        Calls this function with the given parameters
+
+        Parameters can either be a `Val` or a native python value which can be
+        converted to a `Val` of the corresponding correct type
+
+        Returns `None` if this func has 0 return types
+        Returns a single value if the func has 1 return type
+        Returns a list if the func has more than 1 return type
+
+        Note that you can also use the `__call__` method and invoke a `Func` as
+        if it were a function directly.
+        """
+
+        ty = self.type(store)
+        param_tys = ty.params
+        if len(params) > len(param_tys):
+            raise WasmtimeError("too many parameters provided: given %s, expected %s" %
+                                (len(params), len(param_tys)))
+        if len(params) < len(param_tys):
+            raise WasmtimeError("too few parameters provided: given %s, expected %s" %
+                                (len(params), len(param_tys)))
+
+        param_vals = [Val._convert(ty, params[i]) for i, ty in enumerate(param_tys)]
+        params_ptr = (ffi.wasmtime_val_t * len(params))()
+        for i, val in enumerate(param_vals):
+            params_ptr[i] = val._unwrap_raw()
+
+        result_tys = ty.results
+        results_ptr = (ffi.wasmtime_val_t * len(result_tys))()
+
+        with enter_wasm(store) as trap:
+            error = ffi.wasmtime_func_call(
+                store._context,
+                byref(self._func),
+                params_ptr,
+                len(params),
+                results_ptr,
+                len(result_tys),
+                trap)
+            if error:
+                raise WasmtimeError._from_ptr(error)
+
+        results = []
+        for i in range(0, len(result_tys)):
+            results.append(Val(results_ptr[i]).value)
+        if len(results) == 0:
+            return None
+        elif len(results) == 1:
+            return results[0]
+        else:
+            return results
+
+    def _as_extern(self) -> ffi.wasmtime_extern_t:
+        union = ffi.wasmtime_extern_union(func=self._func)
+        return ffi.wasmtime_extern_t(ffi.WASMTIME_EXTERN_FUNC, union)
+
+

Methods

+
+
+def type(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')]) ‑> wasmtime._types.FuncType +
+
+

Gets the type of this func as a FuncType

+
+ +Expand source code + +
def type(self, store: Storelike) -> FuncType:
+    """
+    Gets the type of this func as a `FuncType`
+    """
+    ptr = ffi.wasmtime_func_type(store._context, byref(self._func))
+    return FuncType._from_ptr(ptr, None)
+
+
+
+
+
+class FuncType +(params: List[wasmtime._types.ValType], results: List[wasmtime._types.ValType]) +
+
+
+
+ +Expand source code + +
class FuncType:
+    def __init__(self, params: List[ValType], results: List[ValType]):
+        for param in params:
+            if not isinstance(param, ValType):
+                raise TypeError("expected ValType")
+        for result in results:
+            if not isinstance(result, ValType):
+                raise TypeError("expected ValType")
+
+        params_ffi = ffi.wasm_valtype_vec_t()
+        ffi.wasm_valtype_vec_new_uninitialized(byref(params_ffi), len(params))
+
+        results_ffi = ffi.wasm_valtype_vec_t()
+        for i, param in enumerate(params):
+            params_ffi.data[i] = take_owned_valtype(param)
+
+        ffi.wasm_valtype_vec_new_uninitialized(
+            byref(results_ffi), len(results))
+        for i, result in enumerate(results):
+            results_ffi.data[i] = take_owned_valtype(result)
+        ptr = ffi.wasm_functype_new(byref(params_ffi), byref(results_ffi))
+        if not ptr:
+            raise WasmtimeError("failed to allocate FuncType")
+        self._ptr = ptr
+        self._owner = None
+
+    @classmethod
+    def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasm_functype_t]", owner: Optional[Any]) -> "FuncType":
+        ty: "FuncType" = cls.__new__(cls)
+        if not isinstance(ptr, POINTER(ffi.wasm_functype_t)):
+            raise TypeError("wrong pointer type")
+        ty._ptr = ptr
+        ty._owner = owner
+        return ty
+
+    @property
+    def params(self) -> List["ValType"]:
+        """
+        Returns the list of parameter types for this function type
+        """
+
+        ptr = ffi.wasm_functype_params(self._ptr)
+        return ValType._from_list(ptr, self)
+
+    @property
+    def results(self) -> List["ValType"]:
+        """
+        Returns the list of result types for this function type
+        """
+
+        ptr = ffi.wasm_functype_results(self._ptr)
+        return ValType._from_list(ptr, self)
+
+    def _as_extern(self) -> "ctypes._Pointer[ffi.wasm_externtype_t]":
+        return ffi.wasm_functype_as_externtype_const(self._ptr)
+
+    def __del__(self) -> None:
+        if hasattr(self, '_owner') and self._owner is None:
+            ffi.wasm_functype_delete(self._ptr)
+
+

Instance variables

+
+
var params : List[wasmtime._types.ValType]
+
+

Returns the list of parameter types for this function type

+
+ +Expand source code + +
@property
+def params(self) -> List["ValType"]:
+    """
+    Returns the list of parameter types for this function type
+    """
+
+    ptr = ffi.wasm_functype_params(self._ptr)
+    return ValType._from_list(ptr, self)
+
+
+
var results : List[wasmtime._types.ValType]
+
+

Returns the list of result types for this function type

+
+ +Expand source code + +
@property
+def results(self) -> List["ValType"]:
+    """
+    Returns the list of result types for this function type
+    """
+
+    ptr = ffi.wasm_functype_results(self._ptr)
+    return ValType._from_list(ptr, self)
+
+
+
+
+
+class Global +(store: Union[wasmtime._store.Store, ForwardRef('Caller')], ty: wasmtime._types.GlobalType, val: Union[wasmtime._value.Val, int, float, ForwardRef(None), ForwardRef('Func'), Any]) +
+
+
+
+ +Expand source code + +
class Global:
+    _global: ffi.wasmtime_global_t
+
+    def __init__(self, store: Storelike, ty: GlobalType, val: IntoVal):
+        if not isinstance(ty, GlobalType):
+            raise TypeError("expected a GlobalType")
+        val = Val._convert(ty.content, val)
+        global_ = ffi.wasmtime_global_t()
+        error = ffi.wasmtime_global_new(
+            store._context,
+            ty._ptr,
+            byref(val._unwrap_raw()),
+            byref(global_))
+        if error:
+            raise WasmtimeError._from_ptr(error)
+        self._global = global_
+
+    @classmethod
+    def _from_raw(cls, global_: ffi.wasmtime_global_t) -> "Global":
+        ty: "Global" = cls.__new__(cls)
+        ty._global = global_
+        return ty
+
+    def type(self, store: Storelike) -> GlobalType:
+        """
+        Gets the type of this global as a `GlobalType`
+        """
+
+        ptr = ffi.wasmtime_global_type(store._context, byref(self._global))
+        return GlobalType._from_ptr(ptr, None)
+
+    def value(self, store: Storelike) -> IntoVal:
+        """
+        Gets the current value of this global
+
+        Returns a native python type
+        """
+        raw = ffi.wasmtime_val_t()
+        ffi.wasmtime_global_get(store._context, byref(self._global), byref(raw))
+        val = Val(raw)
+        if val.value is not None:
+            return val.value
+        else:
+            return val
+
+    def set_value(self, store: Storelike, val: IntoVal) -> None:
+        """
+        Sets the value of this global to a new value
+        """
+        val = Val._convert(self.type(store).content, val)
+        error = ffi.wasmtime_global_set(store._context, byref(self._global), byref(val._unwrap_raw()))
+        if error:
+            raise WasmtimeError._from_ptr(error)
+
+    def _as_extern(self) -> ffi.wasmtime_extern_t:
+        union = ffi.wasmtime_extern_union(global_=self._global)
+        return ffi.wasmtime_extern_t(ffi.WASMTIME_EXTERN_GLOBAL, union)
+
+

Methods

+
+
+def set_value(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')], val: Union[wasmtime._value.Val, int, float, ForwardRef(None), ForwardRef('Func'), Any]) +
+
+

Sets the value of this global to a new value

+
+ +Expand source code + +
def set_value(self, store: Storelike, val: IntoVal) -> None:
+    """
+    Sets the value of this global to a new value
+    """
+    val = Val._convert(self.type(store).content, val)
+    error = ffi.wasmtime_global_set(store._context, byref(self._global), byref(val._unwrap_raw()))
+    if error:
+        raise WasmtimeError._from_ptr(error)
+
+
+
+def type(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')]) ‑> wasmtime._types.GlobalType +
+
+

Gets the type of this global as a GlobalType

+
+ +Expand source code + +
def type(self, store: Storelike) -> GlobalType:
+    """
+    Gets the type of this global as a `GlobalType`
+    """
+
+    ptr = ffi.wasmtime_global_type(store._context, byref(self._global))
+    return GlobalType._from_ptr(ptr, None)
+
+
+
+def value(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')]) ‑> Union[wasmtime._value.Val, int, float, ForwardRef(None), Func, Any] +
+
+

Gets the current value of this global

+

Returns a native python type

+
+ +Expand source code + +
def value(self, store: Storelike) -> IntoVal:
+    """
+    Gets the current value of this global
+
+    Returns a native python type
+    """
+    raw = ffi.wasmtime_val_t()
+    ffi.wasmtime_global_get(store._context, byref(self._global), byref(raw))
+    val = Val(raw)
+    if val.value is not None:
+        return val.value
+    else:
+        return val
+
+
+
+
+
+class GlobalType +(valtype: wasmtime._types.ValType, mutable: bool) +
+
+
+
+ +Expand source code + +
class GlobalType:
+    def __init__(self, valtype: ValType, mutable: bool):
+        if mutable:
+            mutability = ffi.WASM_VAR
+        else:
+            mutability = ffi.WASM_CONST
+        type_ptr = take_owned_valtype(valtype)
+        ptr = ffi.wasm_globaltype_new(type_ptr, mutability)
+        if ptr == 0:
+            raise WasmtimeError("failed to allocate GlobalType")
+        self._ptr = ptr
+        self._owner = None
+
+    @classmethod
+    def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasm_globaltype_t]", owner: Optional[Any]) -> "GlobalType":
+        ty: "GlobalType" = cls.__new__(cls)
+        if not isinstance(ptr, POINTER(ffi.wasm_globaltype_t)):
+            raise TypeError("wrong pointer type")
+        ty._ptr = ptr
+        ty._owner = owner
+        return ty
+
+    @property
+    def content(self) -> ValType:
+        """
+        Returns the type this global contains
+        """
+
+        ptr = ffi.wasm_globaltype_content(self._ptr)
+        return ValType._from_ptr(ptr, self)
+
+    @property
+    def mutable(self) -> bool:
+        """
+        Returns whether this global is mutable or not
+        """
+        val = ffi.wasm_globaltype_mutability(self._ptr)
+        return val == ffi.WASM_VAR.value
+
+    def _as_extern(self) -> "ctypes._Pointer[ffi.wasm_externtype_t]":
+        return ffi.wasm_globaltype_as_externtype_const(self._ptr)
+
+    def __del__(self) -> None:
+        if hasattr(self, '_owner') and self._owner is None:
+            ffi.wasm_globaltype_delete(self._ptr)
+
+

Instance variables

+
+
var content : wasmtime._types.ValType
+
+

Returns the type this global contains

+
+ +Expand source code + +
@property
+def content(self) -> ValType:
+    """
+    Returns the type this global contains
+    """
+
+    ptr = ffi.wasm_globaltype_content(self._ptr)
+    return ValType._from_ptr(ptr, self)
+
+
+
var mutable : bool
+
+

Returns whether this global is mutable or not

+
+ +Expand source code + +
@property
+def mutable(self) -> bool:
+    """
+    Returns whether this global is mutable or not
+    """
+    val = ffi.wasm_globaltype_mutability(self._ptr)
+    return val == ffi.WASM_VAR.value
+
+
+
+
+
+class ImportType +
+
+
+
+ +Expand source code + +
class ImportType:
+    _ptr: "ctypes._Pointer[ffi.wasm_importtype_t]"
+    _owner: Optional[Any]
+
+    @classmethod
+    def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasm_importtype_t]", owner: Optional[Any]) -> "ImportType":
+        ty: "ImportType" = cls.__new__(cls)
+        if not isinstance(ptr, POINTER(ffi.wasm_importtype_t)):
+            raise TypeError("wrong pointer type")
+        ty._ptr = ptr
+        ty._owner = owner
+        return ty
+
+    @property
+    def module(self) -> str:
+        """
+        Returns the module this import type refers to
+        """
+
+        return ffi.to_str(ffi.wasm_importtype_module(self._ptr).contents)
+
+    @property
+    def name(self) -> Optional[str]:
+        """
+        Returns the name in the modulethis import type refers toa.
+
+        Note that `None` may be returned for the module linking proposal where
+        the field name is optional.
+        """
+        ptr = ffi.wasm_importtype_name(self._ptr)
+        if ptr:
+            return ffi.to_str(ptr.contents)
+        return None
+
+    @property
+    def type(self) -> "AsExternType":
+        """
+        Returns the type that this import refers to
+        """
+        ptr = ffi.wasm_importtype_type(self._ptr)
+        return wrap_externtype(ptr, self._owner or self)
+
+    def __del__(self) -> None:
+        if self._owner is None:
+            ffi.wasm_importtype_delete(self._ptr)
+
+

Instance variables

+
+
var module : str
+
+

Returns the module this import type refers to

+
+ +Expand source code + +
@property
+def module(self) -> str:
+    """
+    Returns the module this import type refers to
+    """
+
+    return ffi.to_str(ffi.wasm_importtype_module(self._ptr).contents)
+
+
+
var name : Optional[str]
+
+

Returns the name in the modulethis import type refers toa.

+

Note that None may be returned for the module linking proposal where +the field name is optional.

+
+ +Expand source code + +
@property
+def name(self) -> Optional[str]:
+    """
+    Returns the name in the modulethis import type refers toa.
+
+    Note that `None` may be returned for the module linking proposal where
+    the field name is optional.
+    """
+    ptr = ffi.wasm_importtype_name(self._ptr)
+    if ptr:
+        return ffi.to_str(ptr.contents)
+    return None
+
+
+
var type : Union[wasmtime._types.FuncType, wasmtime._types.TableType, wasmtime._types.MemoryType, wasmtime._types.GlobalType]
+
+

Returns the type that this import refers to

+
+ +Expand source code + +
@property
+def type(self) -> "AsExternType":
+    """
+    Returns the type that this import refers to
+    """
+    ptr = ffi.wasm_importtype_type(self._ptr)
+    return wrap_externtype(ptr, self._owner or self)
+
+
+
+
+
+class Instance +(store: Union[wasmtime._store.Store, ForwardRef('Caller')], module: wasmtime._module.Module, imports: Sequence[Union[ForwardRef('Func'), ForwardRef('Table'), ForwardRef('Memory'), ForwardRef('Global'), ForwardRef('Instance'), ForwardRef('Module')]]) +
+
+

Creates a new instance by instantiating the module given with the +imports into the store provided.

+

The store must have type Store, the module must have type +Module, and the imports must be an iterable of external values, +either Extern, Func, Table, Memory, or Global.

+

Raises an error if instantiation fails (e.g. linking or trap) and +otherwise initializes the new instance.

+
+ +Expand source code + +
class Instance:
+    _instance: ffi.wasmtime_instance_t
+    _exports: Optional["InstanceExports"]
+
+    def __init__(self, store: Storelike, module: Module, imports: Sequence[AsExtern]):
+        """
+        Creates a new instance by instantiating the `module` given with the
+        `imports` into the `store` provided.
+
+        The `store` must have type `Store`, the `module` must have type
+        `Module`, and the `imports` must be an iterable of external values,
+        either `Extern`, `Func`, `Table`, `Memory`, or `Global`.
+
+        Raises an error if instantiation fails (e.g. linking or trap) and
+        otherwise initializes the new instance.
+        """
+
+        imports_ptr = (ffi.wasmtime_extern_t * len(imports))()
+        for i, val in enumerate(imports):
+            imports_ptr[i] = get_extern_ptr(val)
+
+        instance = ffi.wasmtime_instance_t()
+        trap = POINTER(ffi.wasm_trap_t)()
+        with enter_wasm(store) as trap:
+            error = ffi.wasmtime_instance_new(
+                store._context,
+                module._ptr,
+                imports_ptr,
+                len(imports),
+                byref(instance),
+                trap)
+            if error:
+                raise WasmtimeError._from_ptr(error)
+        self._instance = instance
+        self._exports = None
+
+    @classmethod
+    def _from_raw(cls, instance: ffi.wasmtime_instance_t) -> "Instance":
+        ty: "Instance" = cls.__new__(cls)
+        ty._exports = None
+        ty._instance = instance
+        return ty
+
+    def exports(self, store: Storelike) -> "InstanceExports":
+        """
+        Returns the exports of this module
+
+        The returned type can be indexed both with integers and with strings for
+        names of exports.
+        """
+        if self._exports is None:
+            self._exports = InstanceExports(store, self)
+        return self._exports
+
+    def _as_extern(self) -> ffi.wasmtime_extern_t:
+        union = ffi.wasmtime_extern_union(instance=self._instance)
+        return ffi.wasmtime_extern_t(ffi.WASMTIME_EXTERN_INSTANCE, union)
+
+

Methods

+
+
+def exports(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')]) ‑> wasmtime._instance.InstanceExports +
+
+

Returns the exports of this module

+

The returned type can be indexed both with integers and with strings for +names of exports.

+
+ +Expand source code + +
def exports(self, store: Storelike) -> "InstanceExports":
+    """
+    Returns the exports of this module
+
+    The returned type can be indexed both with integers and with strings for
+    names of exports.
+    """
+    if self._exports is None:
+        self._exports = InstanceExports(store, self)
+    return self._exports
+
+
+
+
+
+class Limits +(min: int, max: Optional[int]) +
+
+
+
+ +Expand source code + +
class Limits:
+    def __init__(self, min: int, max: Optional[int]):
+        self.min = min
+        self.max = max
+
+    def __ffi__(self) -> ffi.wasm_limits_t:
+        max = self.max
+        if max is None:
+            max = 0xffffffff
+        return ffi.wasm_limits_t(self.min, max)
+
+    def __eq__(self, other: object) -> bool:
+        if not isinstance(other, Limits):
+            return False
+        return self.min == other.min and self.max == other.max
+
+    @classmethod
+    def _from_ffi(cls, val: 'ctypes._Pointer[ffi.wasm_limits_t]') -> "Limits":
+        min = val.contents.min
+        max = val.contents.max
+        if max == 0xffffffff:
+            return Limits(min, None)
+        return Limits(min, max)
+
+
+
+class Linker +(engine: wasmtime._engine.Engine) +
+
+

Creates a new linker ready to instantiate modules within the store +provided.

+
+ +Expand source code + +
class Linker:
+    engine: Engine
+
+    def __init__(self, engine: Engine):
+        """
+        Creates a new linker ready to instantiate modules within the store
+        provided.
+        """
+        self._ptr = ffi.wasmtime_linker_new(engine._ptr)
+        self.engine = engine
+
+    @setter_property
+    def allow_shadowing(self, allow: bool) -> None:
+        """
+        Configures whether definitions are allowed to shadow one another within
+        this linker
+        """
+        if not isinstance(allow, bool):
+            raise TypeError("expected a boolean")
+        ffi.wasmtime_linker_allow_shadowing(self._ptr, allow)
+
+    def define(self, store: Storelike, module: str, name: str, item: AsExtern) -> None:
+        """
+        Defines a new item, by name, in this linker.
+
+        This method will add a new definition to this linker. The `module` nad
+        `name` provided are what to name the `item` within the linker.
+
+        This function will raise an error if `item` comes from the wrong store
+        or if shadowing is disallowed and the module/name pair has already been
+        defined.
+        """
+        raw_item = get_extern_ptr(item)
+        module_bytes = module.encode('utf-8')
+        module_buf = create_string_buffer(module_bytes)
+        name_bytes = name.encode('utf-8')
+        name_buf = create_string_buffer(name_bytes)
+        error = ffi.wasmtime_linker_define(
+            self._ptr,
+            store._context,
+            module_buf,
+            len(module_bytes),
+            name_buf,
+            len(name_bytes),
+            byref(raw_item))
+        if error:
+            raise WasmtimeError._from_ptr(error)
+
+    def define_func(self, module: str, name: str, ty: FuncType, func: Callable[..., Any], access_caller: bool = False) -> None:
+        """
+        Defines a new function, by name, in this linker.
+
+        This method is similar to `define` except that you can directly define a
+        function without creating a `Func` itself. This enables
+        `Store`-independent functions to be inserted into this linker, meaning
+        the linker can be used to instantiate modules in multiple stores.
+        """
+        module_bytes = module.encode('utf-8')
+        module_buf = create_string_buffer(module_bytes)
+        name_bytes = name.encode('utf-8')
+        name_buf = create_string_buffer(name_bytes)
+        if not isinstance(ty, FuncType):
+            raise TypeError("expected a FuncType")
+        idx = FUNCTIONS.allocate((func, ty.results, access_caller))
+        error = ffi.wasmtime_linker_define_func(
+            self._ptr,
+            module_buf,
+            len(module_bytes),
+            name_buf,
+            len(name_bytes),
+            ty._ptr,
+            trampoline,
+            idx,
+            finalize)
+        if error:
+            raise WasmtimeError._from_ptr(error)
+
+    def define_instance(self, store: Storelike, name: str, instance: Instance) -> None:
+        """
+        Convenience wrapper to define an entire instance in this linker.
+
+        This function will `define` eaech of the exports on the instance into
+        this linker, using the name provided as the module name and the export's
+        own name as the field name.
+
+        This function will raise an error if `instance` comes from the wrong
+        store or if shadowing is disallowed and a name was previously defined.
+        """
+        if not isinstance(instance, Instance):
+            raise TypeError("expected an `Instance`")
+        name_bytes = name.encode('utf8')
+        name_buf = create_string_buffer(name_bytes)
+        error = ffi.wasmtime_linker_define_instance(self._ptr,
+                                                    store._context,
+                                                    name_buf,
+                                                    len(name_bytes),
+                                                    byref(instance._instance))
+        if error:
+            raise WasmtimeError._from_ptr(error)
+
+    def define_wasi(self) -> None:
+        """
+        Defines a WASI instance in this linker.
+
+        The instance provided has been previously constructed and this method
+        will define all the appropriate imports and their names into this linker
+        to assist with instantiating modules that use WASI.
+
+        This function will raise an error if shadowing is disallowed and a name
+        was previously defined.
+        """
+        error = ffi.wasmtime_linker_define_wasi(self._ptr)
+        if error:
+            raise WasmtimeError._from_ptr(error)
+
+    def define_module(self, store: Storelike, name: str, module: Module) -> None:
+        """
+        Defines automatic instantiations of the provided module in this linker.
+
+        The `module` provided is defined under `name` with automatic
+        instantiations which respect WASI Commands and Reactors.
+
+        For more information see the Rust documentation at
+        https://docs.wasmtime.dev/api/wasmtime/struct.Linker.html#method.module.
+
+        This method will throw an error if shadowing is disallowed and an item
+        has previously been defined.
+        """
+        if not isinstance(module, Module):
+            raise TypeError("expected a `Module`")
+        name_bytes = name.encode('utf-8')
+        name_buf = create_string_buffer(name_bytes)
+        error = ffi.wasmtime_linker_module(self._ptr, store._context, name_buf, len(name_bytes), module._ptr)
+        if error:
+            raise WasmtimeError._from_ptr(error)
+
+    def instantiate(self, store: Storelike, module: Module) -> Instance:
+        """
+        Instantiates a module using this linker's defined set of names.
+
+        This method will attempt to satisfy all the imports of the `module`
+        provided with the names defined within this linker. If all names are
+        defined then the module is instantiated.
+
+        Raises an error if an import of `module` hasn't been defined in this
+        linker or if a trap happens while instantiating the instance.
+        """
+        trap = POINTER(ffi.wasm_trap_t)()
+        instance = ffi.wasmtime_instance_t()
+        with enter_wasm(store) as trap:
+            error = ffi.wasmtime_linker_instantiate(
+                self._ptr, store._context, module._ptr, byref(instance), trap)
+            if error:
+                raise WasmtimeError._from_ptr(error)
+        return Instance._from_raw(instance)
+
+    def get_default(self, store: Storelike, name: str) -> Func:
+        """
+        Gets the default export for the named module in this linker.
+
+        For more information on this see the Rust documentation at
+        https://docs.wasmtime.dev/api/wasmtime/struct.Linker.html#method.get_default.
+
+        Raises an error if the default export wasn't present.
+        """
+        name_bytes = name.encode('utf-8')
+        name_buf = create_string_buffer(name_bytes)
+        func = ffi.wasmtime_func_t()
+        error = ffi.wasmtime_linker_get_default(self._ptr, store._context,
+                                                name_buf, len(name_bytes), byref(func))
+        if error:
+            raise WasmtimeError._from_ptr(error)
+        return Func._from_raw(func)
+
+    def get(self, store: Storelike, module: str, name: str) -> AsExtern:
+        """
+        Gets a singular item defined in this linker.
+
+        Raises an error if this item hasn't been defined or if the item has been
+        defined twice with different types.
+        """
+        module_bytes = module.encode('utf-8')
+        module_buf = create_string_buffer(module_bytes)
+        name_bytes = name.encode('utf-8')
+        name_buf = create_string_buffer(name_bytes)
+        item = ffi.wasmtime_extern_t()
+        ok = ffi.wasmtime_linker_get(self._ptr, store._context,
+                                     module_buf, len(module_bytes),
+                                     name_buf, len(name_bytes),
+                                     byref(item))
+        if ok:
+            return wrap_extern(item)
+        raise WasmtimeError("item not defined in linker")
+
+    def __del__(self) -> None:
+        if hasattr(self, '_ptr'):
+            ffi.wasmtime_linker_delete(self._ptr)
+
+

Class variables

+
+
var engine : wasmtime._engine.Engine
+
+
+
+
+

Instance variables

+
+
var allow_shadowing
+
+

Configures whether definitions are allowed to shadow one another within +this linker

+

Note that this field can only be set, it cannot be read

+
+
+

Methods

+
+
+def define(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')], module: str, name: str, item: Union[ForwardRef('Func'), ForwardRef('Table'), ForwardRef('Memory'), ForwardRef('Global'), ForwardRef('Instance'), ForwardRef('Module')]) +
+
+

Defines a new item, by name, in this linker.

+

This method will add a new definition to this linker. The module nad +name provided are what to name the item within the linker.

+

This function will raise an error if item comes from the wrong store +or if shadowing is disallowed and the module/name pair has already been +defined.

+
+ +Expand source code + +
def define(self, store: Storelike, module: str, name: str, item: AsExtern) -> None:
+    """
+    Defines a new item, by name, in this linker.
+
+    This method will add a new definition to this linker. The `module` nad
+    `name` provided are what to name the `item` within the linker.
+
+    This function will raise an error if `item` comes from the wrong store
+    or if shadowing is disallowed and the module/name pair has already been
+    defined.
+    """
+    raw_item = get_extern_ptr(item)
+    module_bytes = module.encode('utf-8')
+    module_buf = create_string_buffer(module_bytes)
+    name_bytes = name.encode('utf-8')
+    name_buf = create_string_buffer(name_bytes)
+    error = ffi.wasmtime_linker_define(
+        self._ptr,
+        store._context,
+        module_buf,
+        len(module_bytes),
+        name_buf,
+        len(name_bytes),
+        byref(raw_item))
+    if error:
+        raise WasmtimeError._from_ptr(error)
+
+
+
+def define_func(self, module: str, name: str, ty: wasmtime._types.FuncType, func: Callable[..., Any], access_caller: bool = False) ‑> None +
+
+

Defines a new function, by name, in this linker.

+

This method is similar to define except that you can directly define a +function without creating a Func itself. This enables +Store-independent functions to be inserted into this linker, meaning +the linker can be used to instantiate modules in multiple stores.

+
+ +Expand source code + +
def define_func(self, module: str, name: str, ty: FuncType, func: Callable[..., Any], access_caller: bool = False) -> None:
+    """
+    Defines a new function, by name, in this linker.
+
+    This method is similar to `define` except that you can directly define a
+    function without creating a `Func` itself. This enables
+    `Store`-independent functions to be inserted into this linker, meaning
+    the linker can be used to instantiate modules in multiple stores.
+    """
+    module_bytes = module.encode('utf-8')
+    module_buf = create_string_buffer(module_bytes)
+    name_bytes = name.encode('utf-8')
+    name_buf = create_string_buffer(name_bytes)
+    if not isinstance(ty, FuncType):
+        raise TypeError("expected a FuncType")
+    idx = FUNCTIONS.allocate((func, ty.results, access_caller))
+    error = ffi.wasmtime_linker_define_func(
+        self._ptr,
+        module_buf,
+        len(module_bytes),
+        name_buf,
+        len(name_bytes),
+        ty._ptr,
+        trampoline,
+        idx,
+        finalize)
+    if error:
+        raise WasmtimeError._from_ptr(error)
+
+
+
+def define_instance(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')], name: str, instance: wasmtime._instance.Instance) ‑> None +
+
+

Convenience wrapper to define an entire instance in this linker.

+

This function will define eaech of the exports on the instance into +this linker, using the name provided as the module name and the export's +own name as the field name.

+

This function will raise an error if instance comes from the wrong +store or if shadowing is disallowed and a name was previously defined.

+
+ +Expand source code + +
def define_instance(self, store: Storelike, name: str, instance: Instance) -> None:
+    """
+    Convenience wrapper to define an entire instance in this linker.
+
+    This function will `define` eaech of the exports on the instance into
+    this linker, using the name provided as the module name and the export's
+    own name as the field name.
+
+    This function will raise an error if `instance` comes from the wrong
+    store or if shadowing is disallowed and a name was previously defined.
+    """
+    if not isinstance(instance, Instance):
+        raise TypeError("expected an `Instance`")
+    name_bytes = name.encode('utf8')
+    name_buf = create_string_buffer(name_bytes)
+    error = ffi.wasmtime_linker_define_instance(self._ptr,
+                                                store._context,
+                                                name_buf,
+                                                len(name_bytes),
+                                                byref(instance._instance))
+    if error:
+        raise WasmtimeError._from_ptr(error)
+
+
+
+def define_module(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')], name: str, module: wasmtime._module.Module) ‑> None +
+
+

Defines automatic instantiations of the provided module in this linker.

+

The module provided is defined under name with automatic +instantiations which respect WASI Commands and Reactors.

+

For more information see the Rust documentation at +https://docs.wasmtime.dev/api/wasmtime/struct.Linker.html#method.module.

+

This method will throw an error if shadowing is disallowed and an item +has previously been defined.

+
+ +Expand source code + +
def define_module(self, store: Storelike, name: str, module: Module) -> None:
+    """
+    Defines automatic instantiations of the provided module in this linker.
+
+    The `module` provided is defined under `name` with automatic
+    instantiations which respect WASI Commands and Reactors.
+
+    For more information see the Rust documentation at
+    https://docs.wasmtime.dev/api/wasmtime/struct.Linker.html#method.module.
+
+    This method will throw an error if shadowing is disallowed and an item
+    has previously been defined.
+    """
+    if not isinstance(module, Module):
+        raise TypeError("expected a `Module`")
+    name_bytes = name.encode('utf-8')
+    name_buf = create_string_buffer(name_bytes)
+    error = ffi.wasmtime_linker_module(self._ptr, store._context, name_buf, len(name_bytes), module._ptr)
+    if error:
+        raise WasmtimeError._from_ptr(error)
+
+
+
+def define_wasi(self) ‑> None +
+
+

Defines a WASI instance in this linker.

+

The instance provided has been previously constructed and this method +will define all the appropriate imports and their names into this linker +to assist with instantiating modules that use WASI.

+

This function will raise an error if shadowing is disallowed and a name +was previously defined.

+
+ +Expand source code + +
def define_wasi(self) -> None:
+    """
+    Defines a WASI instance in this linker.
+
+    The instance provided has been previously constructed and this method
+    will define all the appropriate imports and their names into this linker
+    to assist with instantiating modules that use WASI.
+
+    This function will raise an error if shadowing is disallowed and a name
+    was previously defined.
+    """
+    error = ffi.wasmtime_linker_define_wasi(self._ptr)
+    if error:
+        raise WasmtimeError._from_ptr(error)
+
+
+
+def get(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')], module: str, name: str) ‑> Union[FuncTableMemoryGlobalInstanceModule] +
+
+

Gets a singular item defined in this linker.

+

Raises an error if this item hasn't been defined or if the item has been +defined twice with different types.

+
+ +Expand source code + +
def get(self, store: Storelike, module: str, name: str) -> AsExtern:
+    """
+    Gets a singular item defined in this linker.
+
+    Raises an error if this item hasn't been defined or if the item has been
+    defined twice with different types.
+    """
+    module_bytes = module.encode('utf-8')
+    module_buf = create_string_buffer(module_bytes)
+    name_bytes = name.encode('utf-8')
+    name_buf = create_string_buffer(name_bytes)
+    item = ffi.wasmtime_extern_t()
+    ok = ffi.wasmtime_linker_get(self._ptr, store._context,
+                                 module_buf, len(module_bytes),
+                                 name_buf, len(name_bytes),
+                                 byref(item))
+    if ok:
+        return wrap_extern(item)
+    raise WasmtimeError("item not defined in linker")
+
+
+
+def get_default(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')], name: str) ‑> wasmtime._func.Func +
+
+

Gets the default export for the named module in this linker.

+

For more information on this see the Rust documentation at +https://docs.wasmtime.dev/api/wasmtime/struct.Linker.html#method.get_default.

+

Raises an error if the default export wasn't present.

+
+ +Expand source code + +
def get_default(self, store: Storelike, name: str) -> Func:
+    """
+    Gets the default export for the named module in this linker.
+
+    For more information on this see the Rust documentation at
+    https://docs.wasmtime.dev/api/wasmtime/struct.Linker.html#method.get_default.
+
+    Raises an error if the default export wasn't present.
+    """
+    name_bytes = name.encode('utf-8')
+    name_buf = create_string_buffer(name_bytes)
+    func = ffi.wasmtime_func_t()
+    error = ffi.wasmtime_linker_get_default(self._ptr, store._context,
+                                            name_buf, len(name_bytes), byref(func))
+    if error:
+        raise WasmtimeError._from_ptr(error)
+    return Func._from_raw(func)
+
+
+
+def instantiate(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')], module: wasmtime._module.Module) ‑> wasmtime._instance.Instance +
+
+

Instantiates a module using this linker's defined set of names.

+

This method will attempt to satisfy all the imports of the module +provided with the names defined within this linker. If all names are +defined then the module is instantiated.

+

Raises an error if an import of module hasn't been defined in this +linker or if a trap happens while instantiating the instance.

+
+ +Expand source code + +
def instantiate(self, store: Storelike, module: Module) -> Instance:
+    """
+    Instantiates a module using this linker's defined set of names.
+
+    This method will attempt to satisfy all the imports of the `module`
+    provided with the names defined within this linker. If all names are
+    defined then the module is instantiated.
+
+    Raises an error if an import of `module` hasn't been defined in this
+    linker or if a trap happens while instantiating the instance.
+    """
+    trap = POINTER(ffi.wasm_trap_t)()
+    instance = ffi.wasmtime_instance_t()
+    with enter_wasm(store) as trap:
+        error = ffi.wasmtime_linker_instantiate(
+            self._ptr, store._context, module._ptr, byref(instance), trap)
+        if error:
+            raise WasmtimeError._from_ptr(error)
+    return Instance._from_raw(instance)
+
+
+
+
+
+class Memory +(store: Union[wasmtime._store.Store, ForwardRef('Caller')], ty: wasmtime._types.MemoryType) +
+
+

Creates a new memory in store with the given ty

+
+ +Expand source code + +
class Memory:
+    _memory: ffi.wasmtime_memory_t
+
+    def __init__(self, store: Storelike, ty: MemoryType):
+        """
+        Creates a new memory in `store` with the given `ty`
+        """
+
+        mem = ffi.wasmtime_memory_t()
+        error = ffi.wasmtime_memory_new(store._context, ty._ptr, byref(mem))
+        if error:
+            raise WasmtimeError._from_ptr(error)
+        self._memory = mem
+
+    @classmethod
+    def _from_raw(cls, mem: ffi.wasmtime_memory_t) -> "Memory":
+        ty: "Memory" = cls.__new__(cls)
+        ty._memory = mem
+        return ty
+
+    def type(self, store: Storelike) -> MemoryType:
+        """
+        Gets the type of this memory as a `MemoryType`
+        """
+
+        ptr = ffi.wasmtime_memory_type(store._context, byref(self._memory))
+        return MemoryType._from_ptr(ptr, None)
+
+    def grow(self, store: Storelike, delta: int) -> int:
+        """
+        Grows this memory by the given number of pages
+        """
+
+        if delta < 0:
+            raise WasmtimeError("cannot grow by negative amount")
+        prev = ffi.c_uint64(0)
+        error = ffi.wasmtime_memory_grow(store._context, byref(self._memory), delta, byref(prev))
+        if error:
+            raise WasmtimeError._from_ptr(error)
+        return prev.value
+
+    def size(self, store: Storelike) -> int:
+        """
+        Returns the size, in WebAssembly pages, of this memory.
+        """
+
+        return ffi.wasmtime_memory_size(store._context, byref(self._memory))
+
+    def data_ptr(self, store: Storelike) -> "ctypes._Pointer[c_ubyte]":
+        """
+        Returns the raw pointer in memory where this wasm memory lives.
+
+        Remember that all accesses to wasm memory should be bounds-checked
+        against the `data_len` method.
+        """
+        return ffi.wasmtime_memory_data(store._context, byref(self._memory))
+
+    def get_buffer_ptr(self, store: Storelike,
+                       size: typing.Optional[int] = None,
+                       offset: int = 0) -> ctypes.Array:
+        """
+        return raw pointer to buffer suitable for creating zero-copy writable NumPy Buffer Protocol
+        this method is also used internally by `read()` and `write()`
+
+        np_mem = np.frombuffer(memory.get_buffer_ptr(store), dtype=np.uint8)
+        np_mem[start:end] = A # write
+        B = np_mem[start:end] # read
+        """
+        if size is None:
+            size = self.data_len(store)
+        ptr_type = ctypes.c_ubyte * size
+        return ptr_type.from_address(ctypes.addressof(self.data_ptr(store).contents) + offset)
+
+    def read(
+            self,
+            store: Storelike,
+            start: typing.Optional[int] = 0,
+            stop: typing.Optional[int] = None) -> bytearray:
+        """
+        Reads this memory starting from `start` and up to `stop`
+        and returns a copy of the contents as a `bytearray`.
+
+        The indexing behavior of this method is similar to `list[start:stop]`
+        where negative starts can be used to read from the end, for example.
+        """
+        size = self.data_len(store)
+        key = slice(start, stop, None)
+        start, stop, _ = key.indices(size)
+        val_size = stop - start
+        if val_size <= 0:
+            # return bytearray of size zero
+            return bytearray(0)
+        src_ptr = self.get_buffer_ptr(store, val_size, start)
+        return bytearray(src_ptr)
+
+    def write(
+            self,
+            store: Storelike,
+            value: typing.Union[bytearray, bytes],
+            start: typing.Optional[int] = None) -> int:
+        """
+        write a bytearray value into a possibly large slice of memory
+        negative start is allowed in a way similat to list slice mylist[-10:]
+        if value is not bytearray it will be used to construct an intermediate bytearray (copyied twice)
+        return number of bytes written
+        raises IndexError when trying to write outside the memory range
+        this happens when start offset is >= size or when end side of value is >= size
+        """
+        size = self.data_len(store)
+        key = slice(start, None)
+        start = key.indices(size)[0]
+        if start >= size:
+            raise IndexError("index out of range")
+        # value must be bytearray ex. cast bytes() to bytearray
+        if not isinstance(value, bytearray):
+            value = bytearray(value)
+        val_size = len(value)
+        if val_size == 0:
+            return val_size
+        # stop is exclusive
+        stop = start + val_size
+        if stop > size:
+            raise IndexError("index out of range")
+        ptr_type = ctypes.c_ubyte * val_size
+        src_ptr = ptr_type.from_buffer(value)
+        dst_ptr = self.get_buffer_ptr(store, val_size, start)
+        ctypes.memmove(dst_ptr, src_ptr, val_size)
+        return val_size
+
+    def data_len(self, store: Storelike) -> int:
+        """
+        Returns the raw byte length of this memory.
+        """
+
+        return ffi.wasmtime_memory_data_size(store._context, byref(self._memory))
+
+    def _as_extern(self) -> ffi.wasmtime_extern_t:
+        union = ffi.wasmtime_extern_union(memory=self._memory)
+        return ffi.wasmtime_extern_t(ffi.WASMTIME_EXTERN_MEMORY, union)
+
+

Methods

+
+
+def data_len(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')]) ‑> int +
+
+

Returns the raw byte length of this memory.

+
+ +Expand source code + +
def data_len(self, store: Storelike) -> int:
+    """
+    Returns the raw byte length of this memory.
+    """
+
+    return ffi.wasmtime_memory_data_size(store._context, byref(self._memory))
+
+
+
+def data_ptr(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')]) ‑> ctypes._Pointer[c_ubyte] +
+
+

Returns the raw pointer in memory where this wasm memory lives.

+

Remember that all accesses to wasm memory should be bounds-checked +against the data_len method.

+
+ +Expand source code + +
def data_ptr(self, store: Storelike) -> "ctypes._Pointer[c_ubyte]":
+    """
+    Returns the raw pointer in memory where this wasm memory lives.
+
+    Remember that all accesses to wasm memory should be bounds-checked
+    against the `data_len` method.
+    """
+    return ffi.wasmtime_memory_data(store._context, byref(self._memory))
+
+
+
+def get_buffer_ptr(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')], size: Optional[int] = None, offset: int = 0) ‑> _ctypes.Array +
+
+

return raw pointer to buffer suitable for creating zero-copy writable NumPy Buffer Protocol +this method is also used internally by read() and write()

+

np_mem = np.frombuffer(memory.get_buffer_ptr(store), dtype=np.uint8) +np_mem[start:end] = A # write +B = np_mem[start:end] # read

+
+ +Expand source code + +
def get_buffer_ptr(self, store: Storelike,
+                   size: typing.Optional[int] = None,
+                   offset: int = 0) -> ctypes.Array:
+    """
+    return raw pointer to buffer suitable for creating zero-copy writable NumPy Buffer Protocol
+    this method is also used internally by `read()` and `write()`
+
+    np_mem = np.frombuffer(memory.get_buffer_ptr(store), dtype=np.uint8)
+    np_mem[start:end] = A # write
+    B = np_mem[start:end] # read
+    """
+    if size is None:
+        size = self.data_len(store)
+    ptr_type = ctypes.c_ubyte * size
+    return ptr_type.from_address(ctypes.addressof(self.data_ptr(store).contents) + offset)
+
+
+
+def grow(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')], delta: int) ‑> int +
+
+

Grows this memory by the given number of pages

+
+ +Expand source code + +
def grow(self, store: Storelike, delta: int) -> int:
+    """
+    Grows this memory by the given number of pages
+    """
+
+    if delta < 0:
+        raise WasmtimeError("cannot grow by negative amount")
+    prev = ffi.c_uint64(0)
+    error = ffi.wasmtime_memory_grow(store._context, byref(self._memory), delta, byref(prev))
+    if error:
+        raise WasmtimeError._from_ptr(error)
+    return prev.value
+
+
+
+def read(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')], start: Optional[int] = 0, stop: Optional[int] = None) ‑> bytearray +
+
+

Reads this memory starting from start and up to stop +and returns a copy of the contents as a bytearray.

+

The indexing behavior of this method is similar to list[start:stop] +where negative starts can be used to read from the end, for example.

+
+ +Expand source code + +
def read(
+        self,
+        store: Storelike,
+        start: typing.Optional[int] = 0,
+        stop: typing.Optional[int] = None) -> bytearray:
+    """
+    Reads this memory starting from `start` and up to `stop`
+    and returns a copy of the contents as a `bytearray`.
+
+    The indexing behavior of this method is similar to `list[start:stop]`
+    where negative starts can be used to read from the end, for example.
+    """
+    size = self.data_len(store)
+    key = slice(start, stop, None)
+    start, stop, _ = key.indices(size)
+    val_size = stop - start
+    if val_size <= 0:
+        # return bytearray of size zero
+        return bytearray(0)
+    src_ptr = self.get_buffer_ptr(store, val_size, start)
+    return bytearray(src_ptr)
+
+
+
+def size(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')]) ‑> int +
+
+

Returns the size, in WebAssembly pages, of this memory.

+
+ +Expand source code + +
def size(self, store: Storelike) -> int:
+    """
+    Returns the size, in WebAssembly pages, of this memory.
+    """
+
+    return ffi.wasmtime_memory_size(store._context, byref(self._memory))
+
+
+
+def type(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')]) ‑> wasmtime._types.MemoryType +
+
+

Gets the type of this memory as a MemoryType

+
+ +Expand source code + +
def type(self, store: Storelike) -> MemoryType:
+    """
+    Gets the type of this memory as a `MemoryType`
+    """
+
+    ptr = ffi.wasmtime_memory_type(store._context, byref(self._memory))
+    return MemoryType._from_ptr(ptr, None)
+
+
+
+def write(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')], value: Union[bytearray, bytes], start: Optional[int] = None) ‑> int +
+
+

write a bytearray value into a possibly large slice of memory +negative start is allowed in a way similat to list slice mylist[-10:] +if value is not bytearray it will be used to construct an intermediate bytearray (copyied twice) +return number of bytes written +raises IndexError when trying to write outside the memory range +this happens when start offset is >= size or when end side of value is >= size

+
+ +Expand source code + +
def write(
+        self,
+        store: Storelike,
+        value: typing.Union[bytearray, bytes],
+        start: typing.Optional[int] = None) -> int:
+    """
+    write a bytearray value into a possibly large slice of memory
+    negative start is allowed in a way similat to list slice mylist[-10:]
+    if value is not bytearray it will be used to construct an intermediate bytearray (copyied twice)
+    return number of bytes written
+    raises IndexError when trying to write outside the memory range
+    this happens when start offset is >= size or when end side of value is >= size
+    """
+    size = self.data_len(store)
+    key = slice(start, None)
+    start = key.indices(size)[0]
+    if start >= size:
+        raise IndexError("index out of range")
+    # value must be bytearray ex. cast bytes() to bytearray
+    if not isinstance(value, bytearray):
+        value = bytearray(value)
+    val_size = len(value)
+    if val_size == 0:
+        return val_size
+    # stop is exclusive
+    stop = start + val_size
+    if stop > size:
+        raise IndexError("index out of range")
+    ptr_type = ctypes.c_ubyte * val_size
+    src_ptr = ptr_type.from_buffer(value)
+    dst_ptr = self.get_buffer_ptr(store, val_size, start)
+    ctypes.memmove(dst_ptr, src_ptr, val_size)
+    return val_size
+
+
+
+
+
+class MemoryType +(limits: wasmtime._types.Limits, is_64: bool = False) +
+
+
+
+ +Expand source code + +
class MemoryType:
+    def __init__(self, limits: Limits, is_64: bool = False):
+        if not isinstance(limits, Limits):
+            raise TypeError("expected Limits")
+        if is_64:
+            maximum = 0x10000000000000000
+        else:
+            maximum = 0x100000000
+        if limits.min >= maximum:
+            raise WasmtimeError("minimum size too large")
+        if limits.max and limits.max >= maximum:
+            raise WasmtimeError("maximum size too large")
+        ptr = ffi.wasmtime_memorytype_new(limits.min,
+                                          limits.max is not None,
+                                          limits.max if limits.max else 0,
+                                          is_64)
+        if not ptr:
+            raise WasmtimeError("failed to allocate MemoryType")
+        self._ptr = ptr
+        self._owner = None
+
+    @classmethod
+    def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasm_memorytype_t]", owner: Optional[Any]) -> "MemoryType":
+        ty: "MemoryType" = cls.__new__(cls)
+        if not isinstance(ptr, POINTER(ffi.wasm_memorytype_t)):
+            raise TypeError("wrong pointer type")
+        ty._ptr = ptr
+        ty._owner = owner
+        return ty
+
+    @property
+    def limits(self) -> Limits:
+        """
+        Returns the limits on the size of this table
+        """
+        minimum = ffi.wasmtime_memorytype_minimum(self._ptr)
+        maximum = ffi.c_uint64(0)
+        has_max = ffi.wasmtime_memorytype_maximum(self._ptr, byref(maximum))
+        return Limits(minimum, maximum.value if has_max else None)
+
+    @property
+    def is_64(self) -> bool:
+        """
+        Returns whether or not this is a 64-bit memory
+        """
+        return ffi.wasmtime_memorytype_is64(self._ptr)
+
+    def _as_extern(self) -> "ctypes._Pointer[ffi.wasm_externtype_t]":
+        return ffi.wasm_memorytype_as_externtype_const(self._ptr)
+
+    def __del__(self) -> None:
+        if hasattr(self, '_owner') and self._owner is None:
+            ffi.wasm_memorytype_delete(self._ptr)
+
+

Instance variables

+
+
var is_64 : bool
+
+

Returns whether or not this is a 64-bit memory

+
+ +Expand source code + +
@property
+def is_64(self) -> bool:
+    """
+    Returns whether or not this is a 64-bit memory
+    """
+    return ffi.wasmtime_memorytype_is64(self._ptr)
+
+
+
var limits : wasmtime._types.Limits
+
+

Returns the limits on the size of this table

+
+ +Expand source code + +
@property
+def limits(self) -> Limits:
+    """
+    Returns the limits on the size of this table
+    """
+    minimum = ffi.wasmtime_memorytype_minimum(self._ptr)
+    maximum = ffi.c_uint64(0)
+    has_max = ffi.wasmtime_memorytype_maximum(self._ptr, byref(maximum))
+    return Limits(minimum, maximum.value if has_max else None)
+
+
+
+
+
+class Module +(engine: wasmtime._engine.Engine, wasm: Union[str, bytes]) +
+
+
+
+ +Expand source code + +
class Module:
+    @classmethod
+    def from_file(cls, engine: Engine, path: typing.Union[str, bytes, PathLike]) -> "Module":
+        """
+        Compiles and creates a new `Module` by reading the file at `path` and
+        then delegating to the `Module` constructor.
+        """
+
+        with open(path, "rb") as f:
+            contents = f.read()
+        return cls(engine, contents)
+
+    def __init__(self, engine: Engine, wasm: typing.Union[str, bytes]):
+        if not isinstance(engine, Engine):
+            raise TypeError("expected an Engine")
+
+        # If this looks like a string, parse it as the text format. Note that
+        # in python 2 strings and bytes are basically the same, so we skip this
+        # if the first byte in the string is 0, meaning this is actually a wasm
+        # module.
+        if isinstance(wasm, str) and len(wasm) > 0 and ord(wasm[0]) != 0:
+            wasm = wat2wasm(wasm)
+        if isinstance(wasm, bytes) and len(wasm) > 0 and wasm[0] != 0:
+            wasm = wat2wasm(wasm)
+
+        if not isinstance(wasm, (bytes, bytearray)):
+            raise TypeError("expected wasm bytes")
+
+        # TODO: can the copy be avoided here? I can't for the life of me
+        # figure this out.
+        binary = (c_uint8 * len(wasm)).from_buffer_copy(wasm)
+        ptr = POINTER(ffi.wasmtime_module_t)()
+        error = ffi.wasmtime_module_new(engine._ptr, binary, len(wasm), byref(ptr))
+        if error:
+            raise WasmtimeError._from_ptr(error)
+        self._ptr = ptr
+
+    @classmethod
+    def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasmtime_module_t]") -> "Module":
+        ty: "Module" = cls.__new__(cls)
+        if not isinstance(ptr, POINTER(ffi.wasmtime_module_t)):
+            raise TypeError("wrong pointer type")
+        ty._ptr = ptr
+        return ty
+
+    @classmethod
+    def deserialize(cls, engine: Engine, encoded: typing.Union[bytes, bytearray]) -> 'Module':
+        """
+        Deserializes bytes previously created by `Module.serialize`.
+
+        This constructor for `Module` will deserialize bytes previously created
+        by a serialized module. This will only succeed if the bytes were
+        previously created by the same version of `wasmtime` as well as the
+        same configuration within `Engine`.
+        """
+
+        if not isinstance(encoded, (bytes, bytearray)):
+            raise TypeError("expected bytes")
+
+        ptr = POINTER(ffi.wasmtime_module_t)()
+
+        # TODO: can the copy be avoided here? I can't for the life of me
+        # figure this out.
+        error = ffi.wasmtime_module_deserialize(
+            engine._ptr,
+            (c_uint8 * len(encoded)).from_buffer_copy(encoded),
+            len(encoded),
+            byref(ptr))
+        if error:
+            raise WasmtimeError._from_ptr(error)
+        ret: "Module" = cls.__new__(cls)
+        ret._ptr = ptr
+        return ret
+
+    @classmethod
+    def deserialize_file(cls, engine: Engine, path: str) -> 'Module':
+        """
+        Deserializes bytes previously created by `Module.serialize` that are
+        stored in a file on the filesystem.
+
+        Otherwise this function is the same as `Module.deserialize`.
+        """
+
+        ptr = POINTER(ffi.wasmtime_module_t)()
+        path_bytes = path.encode('utf-8')
+        error = ffi.wasmtime_module_deserialize_file(
+            engine._ptr,
+            path_bytes,
+            byref(ptr))
+        if error:
+            raise WasmtimeError._from_ptr(error)
+        ret: "Module" = cls.__new__(cls)
+        ret._ptr = ptr
+        return ret
+
+    @classmethod
+    def validate(cls, engine: Engine, wasm: typing.Union[bytes, bytearray]) -> None:
+        """
+        Validates whether the list of bytes `wasm` provided is a valid
+        WebAssembly binary given the configuration in `store`
+
+        Raises a `WasmtimeError` if the wasm isn't valid.
+        """
+
+        if not isinstance(wasm, (bytes, bytearray)):
+            raise TypeError("expected wasm bytes")
+
+        # TODO: can the copy be avoided here? I can't for the life of me
+        # figure this out.
+        buf = (c_uint8 * len(wasm)).from_buffer_copy(wasm)
+        error = ffi.wasmtime_module_validate(engine._ptr, buf, len(wasm))
+
+        if error:
+            raise WasmtimeError._from_ptr(error)
+
+#     @property
+#     def type(self) -> ModuleType:
+#         """
+#         Gets the type of this module as a `ModuleType`
+#         """
+
+#         ptr = ffi.wasmtime_module_type(self._ptr)
+#         return ModuleType._from_ptr(ptr, None)
+
+    @property
+    def imports(self) -> typing.List[ImportType]:
+        """
+        Returns the types of imports that this module has
+        """
+
+        imports = ImportTypeList()
+        ffi.wasmtime_module_imports(self._ptr, byref(imports.vec))
+        ret = []
+        for i in range(0, imports.vec.size):
+            ret.append(ImportType._from_ptr(imports.vec.data[i], imports))
+        return ret
+
+    @property
+    def exports(self) -> typing.List[ExportType]:
+        """
+        Returns the types of the exports that this module has
+        """
+
+        exports = ExportTypeList()
+        ffi.wasmtime_module_exports(self._ptr, byref(exports.vec))
+        ret = []
+        for i in range(0, exports.vec.size):
+            ret.append(ExportType._from_ptr(exports.vec.data[i], exports))
+        return ret
+
+    def serialize(self) -> bytearray:
+        """
+        Serializes this module to a binary representation.
+
+        This method will serialize this module to an in-memory byte array which
+        can be cached and later passed to `Module.deserialize` to recreate this
+        module.
+        """
+        raw = ffi.wasm_byte_vec_t()
+        err = ffi.wasmtime_module_serialize(self._ptr, byref(raw))
+        if err:
+            raise WasmtimeError._from_ptr(err)
+        ret = ffi.to_bytes(raw)
+        ffi.wasm_byte_vec_delete(byref(raw))
+        return ret
+
+    def _as_extern(self) -> ffi.wasmtime_extern_t:
+        union = ffi.wasmtime_extern_union(module=self._ptr)
+        return ffi.wasmtime_extern_t(ffi.WASMTIME_EXTERN_MODULE, union)
+
+    def __del__(self) -> None:
+        if hasattr(self, '_ptr'):
+            ffi.wasmtime_module_delete(self._ptr)
+
+

Static methods

+
+
+def deserialize(engine: wasmtime._engine.Engine, encoded: Union[bytearray, bytes]) ‑> wasmtime._module.Module +
+
+

Deserializes bytes previously created by Module.serialize().

+

This constructor for Module will deserialize bytes previously created +by a serialized module. This will only succeed if the bytes were +previously created by the same version of wasmtime as well as the +same configuration within Engine.

+
+ +Expand source code + +
@classmethod
+def deserialize(cls, engine: Engine, encoded: typing.Union[bytes, bytearray]) -> 'Module':
+    """
+    Deserializes bytes previously created by `Module.serialize`.
+
+    This constructor for `Module` will deserialize bytes previously created
+    by a serialized module. This will only succeed if the bytes were
+    previously created by the same version of `wasmtime` as well as the
+    same configuration within `Engine`.
+    """
+
+    if not isinstance(encoded, (bytes, bytearray)):
+        raise TypeError("expected bytes")
+
+    ptr = POINTER(ffi.wasmtime_module_t)()
+
+    # TODO: can the copy be avoided here? I can't for the life of me
+    # figure this out.
+    error = ffi.wasmtime_module_deserialize(
+        engine._ptr,
+        (c_uint8 * len(encoded)).from_buffer_copy(encoded),
+        len(encoded),
+        byref(ptr))
+    if error:
+        raise WasmtimeError._from_ptr(error)
+    ret: "Module" = cls.__new__(cls)
+    ret._ptr = ptr
+    return ret
+
+
+
+def deserialize_file(engine: wasmtime._engine.Engine, path: str) ‑> wasmtime._module.Module +
+
+

Deserializes bytes previously created by Module.serialize() that are +stored in a file on the filesystem.

+

Otherwise this function is the same as Module.deserialize().

+
+ +Expand source code + +
@classmethod
+def deserialize_file(cls, engine: Engine, path: str) -> 'Module':
+    """
+    Deserializes bytes previously created by `Module.serialize` that are
+    stored in a file on the filesystem.
+
+    Otherwise this function is the same as `Module.deserialize`.
+    """
+
+    ptr = POINTER(ffi.wasmtime_module_t)()
+    path_bytes = path.encode('utf-8')
+    error = ffi.wasmtime_module_deserialize_file(
+        engine._ptr,
+        path_bytes,
+        byref(ptr))
+    if error:
+        raise WasmtimeError._from_ptr(error)
+    ret: "Module" = cls.__new__(cls)
+    ret._ptr = ptr
+    return ret
+
+
+
+def from_file(engine: wasmtime._engine.Engine, path: Union[str, bytes, os.PathLike]) ‑> wasmtime._module.Module +
+
+

Compiles and creates a new Module by reading the file at path and +then delegating to the Module constructor.

+
+ +Expand source code + +
@classmethod
+def from_file(cls, engine: Engine, path: typing.Union[str, bytes, PathLike]) -> "Module":
+    """
+    Compiles and creates a new `Module` by reading the file at `path` and
+    then delegating to the `Module` constructor.
+    """
+
+    with open(path, "rb") as f:
+        contents = f.read()
+    return cls(engine, contents)
+
+
+
+def validate(engine: wasmtime._engine.Engine, wasm: Union[bytearray, bytes]) ‑> None +
+
+

Validates whether the list of bytes wasm provided is a valid +WebAssembly binary given the configuration in store

+

Raises a WasmtimeError if the wasm isn't valid.

+
+ +Expand source code + +
@classmethod
+def validate(cls, engine: Engine, wasm: typing.Union[bytes, bytearray]) -> None:
+    """
+    Validates whether the list of bytes `wasm` provided is a valid
+    WebAssembly binary given the configuration in `store`
+
+    Raises a `WasmtimeError` if the wasm isn't valid.
+    """
+
+    if not isinstance(wasm, (bytes, bytearray)):
+        raise TypeError("expected wasm bytes")
+
+    # TODO: can the copy be avoided here? I can't for the life of me
+    # figure this out.
+    buf = (c_uint8 * len(wasm)).from_buffer_copy(wasm)
+    error = ffi.wasmtime_module_validate(engine._ptr, buf, len(wasm))
+
+    if error:
+        raise WasmtimeError._from_ptr(error)
+
+
+
+

Instance variables

+
+
var exports : List[wasmtime._types.ExportType]
+
+

Returns the types of the exports that this module has

+
+ +Expand source code + +
@property
+def exports(self) -> typing.List[ExportType]:
+    """
+    Returns the types of the exports that this module has
+    """
+
+    exports = ExportTypeList()
+    ffi.wasmtime_module_exports(self._ptr, byref(exports.vec))
+    ret = []
+    for i in range(0, exports.vec.size):
+        ret.append(ExportType._from_ptr(exports.vec.data[i], exports))
+    return ret
+
+
+
var imports : List[wasmtime._types.ImportType]
+
+

Returns the types of imports that this module has

+
+ +Expand source code + +
@property
+def imports(self) -> typing.List[ImportType]:
+    """
+    Returns the types of imports that this module has
+    """
+
+    imports = ImportTypeList()
+    ffi.wasmtime_module_imports(self._ptr, byref(imports.vec))
+    ret = []
+    for i in range(0, imports.vec.size):
+        ret.append(ImportType._from_ptr(imports.vec.data[i], imports))
+    return ret
+
+
+
+

Methods

+
+
+def serialize(self) ‑> bytearray +
+
+

Serializes this module to a binary representation.

+

This method will serialize this module to an in-memory byte array which +can be cached and later passed to Module.deserialize() to recreate this +module.

+
+ +Expand source code + +
def serialize(self) -> bytearray:
+    """
+    Serializes this module to a binary representation.
+
+    This method will serialize this module to an in-memory byte array which
+    can be cached and later passed to `Module.deserialize` to recreate this
+    module.
+    """
+    raw = ffi.wasm_byte_vec_t()
+    err = ffi.wasmtime_module_serialize(self._ptr, byref(raw))
+    if err:
+        raise WasmtimeError._from_ptr(err)
+    ret = ffi.to_bytes(raw)
+    ffi.wasm_byte_vec_delete(byref(raw))
+    return ret
+
+
+
+
+
+class Store +(engine: Optional[wasmtime._engine.Engine] = None, data: Optional[Any] = None) +
+
+
+
+ +Expand source code + +
class Store:
+    _ptr: "ctypes._Pointer[ffi.wasmtime_store_t]"
+    _context: "ctypes._Pointer[ffi.wasmtime_context_t]"
+
+    def __init__(self, engine: typing.Optional[Engine] = None, data: typing.Optional[typing.Any] = None):
+
+        if engine is None:
+            engine = Engine()
+        elif not isinstance(engine, Engine):
+            raise TypeError("expected an Engine")
+        data_id = ffi.c_void_p(0)
+        finalize = cast(0, CFUNCTYPE(None, c_void_p))
+        if data:
+            data_id = value._intern(data)
+            finalize = value._externref_finalizer
+        self._ptr = ffi.wasmtime_store_new(engine._ptr, data_id, finalize)
+        self._context = ffi.wasmtime_store_context(self._ptr)
+        self.engine = engine
+
+    def data(self) -> typing.Optional[typing.Any]:
+        """
+        TODO
+        """
+        data = ffi.wasmtime_context_get_data(self._context)
+        if data:
+            return value._unintern(data)
+        else:
+            return None
+
+    def gc(self) -> None:
+        """
+        Runs a GC over `externref` values that have been passed into this Store,
+        cleaning out anything that is no longer referenced.
+
+        This is not required to be run manually, but can be done so if you'd
+        like more precise control over when unreferenced `externref` values are
+        deallocated.
+        """
+        ffi.wasmtime_context_gc(self._context)
+
+    def set_fuel(self, fuel: int) -> None:
+        """
+        Sets the amount of fuel in this store to `fuel`.
+
+        This is only relevant when `Config.consume_fuel` is configured.
+
+        This is a required call to ensure that the store has fuel to
+        execute WebAssembly since otherwise stores start with zero fuel.
+
+        Raises a `WasmtimeError` if this store's configuration is not configured
+        to consume fuel.
+        """
+        err = ffi.wasmtime_context_set_fuel(self._context, fuel)
+        if err:
+            raise WasmtimeError._from_ptr(err)
+
+    def get_fuel(self) -> int:
+        """
+        Returns the amount of fuel left in the store.
+
+        This is only relevant when `Config.consume_fuel` is configured.
+
+        Raises a `WasmtimeError` if this store's configuration is not configured
+        to consume fuel or if the store doesn't have enough fuel remaining.
+        """
+        remaining = c_uint64(0)
+        err = ffi.wasmtime_context_get_fuel(self._context, byref(remaining))
+        if err:
+            raise WasmtimeError._from_ptr(err)
+        return remaining.value
+
+    def set_wasi(self, wasi: "WasiConfig") -> None:
+        """
+        TODO
+        """
+        error = ffi.wasmtime_context_set_wasi(self._context, wasi._ptr)
+        delattr(wasi, '_ptr')
+        if error:
+            raise WasmtimeError._from_ptr(error)
+
+    def set_epoch_deadline(self, ticks_after_current: int) -> None:
+        """
+        Configures the relative epoch deadline, after the current engine's
+        epoch, after which WebAssembly code will trap.
+        """
+        ffi.wasmtime_context_set_epoch_deadline(self._context, ticks_after_current)
+
+    def set_limits(self,
+                   memory_size: int = -1,
+                   table_elements: int = -1,
+                   instances: int = -1,
+                   tables: int = -1,
+                   memories: int = -1) -> None:
+        """
+        Configures the limits of various items within this store.
+
+        * `memory_size` - the maximum size, in bytes, that linear memory is
+          allowed to consume within this store. Setting this to a lower value
+          will cause instantiation to fail if a module needs more memory.
+          Additionally the `memory.grow` instruction will return -1 once this
+          threshold is reached.
+
+        * `table_elements` - the maximum number of elements that can be stored
+          within tables in this store. Currently each table element takes 8
+          bytes.
+
+        * `instances` - the maximum number of WebAssembly instances that can
+          be created.
+
+        * `tables` - the maximum number of WebAssembly tables that can
+          be created.
+
+        * `memories` - the maximum number of WebAssembly linear memories that
+          can be created.
+
+        If any limit is negative then the limit will not be set as a part of
+        this invocation and it will be ignored.
+        """
+        ffi.wasmtime_store_limiter(self._ptr, memory_size, table_elements, instances, tables, memories)
+
+    def __del__(self) -> None:
+        if hasattr(self, '_ptr'):
+            ffi.wasmtime_store_delete(self._ptr)
+
+

Methods

+
+
+def data(self) ‑> Optional[Any] +
+
+

TODO

+
+ +Expand source code + +
def data(self) -> typing.Optional[typing.Any]:
+    """
+    TODO
+    """
+    data = ffi.wasmtime_context_get_data(self._context)
+    if data:
+        return value._unintern(data)
+    else:
+        return None
+
+
+
+def gc(self) ‑> None +
+
+

Runs a GC over externref values that have been passed into this Store, +cleaning out anything that is no longer referenced.

+

This is not required to be run manually, but can be done so if you'd +like more precise control over when unreferenced externref values are +deallocated.

+
+ +Expand source code + +
def gc(self) -> None:
+    """
+    Runs a GC over `externref` values that have been passed into this Store,
+    cleaning out anything that is no longer referenced.
+
+    This is not required to be run manually, but can be done so if you'd
+    like more precise control over when unreferenced `externref` values are
+    deallocated.
+    """
+    ffi.wasmtime_context_gc(self._context)
+
+
+
+def get_fuel(self) ‑> int +
+
+

Returns the amount of fuel left in the store.

+

This is only relevant when Config.consume_fuel is configured.

+

Raises a WasmtimeError if this store's configuration is not configured +to consume fuel or if the store doesn't have enough fuel remaining.

+
+ +Expand source code + +
def get_fuel(self) -> int:
+    """
+    Returns the amount of fuel left in the store.
+
+    This is only relevant when `Config.consume_fuel` is configured.
+
+    Raises a `WasmtimeError` if this store's configuration is not configured
+    to consume fuel or if the store doesn't have enough fuel remaining.
+    """
+    remaining = c_uint64(0)
+    err = ffi.wasmtime_context_get_fuel(self._context, byref(remaining))
+    if err:
+        raise WasmtimeError._from_ptr(err)
+    return remaining.value
+
+
+
+def set_epoch_deadline(self, ticks_after_current: int) ‑> None +
+
+

Configures the relative epoch deadline, after the current engine's +epoch, after which WebAssembly code will trap.

+
+ +Expand source code + +
def set_epoch_deadline(self, ticks_after_current: int) -> None:
+    """
+    Configures the relative epoch deadline, after the current engine's
+    epoch, after which WebAssembly code will trap.
+    """
+    ffi.wasmtime_context_set_epoch_deadline(self._context, ticks_after_current)
+
+
+
+def set_fuel(self, fuel: int) ‑> None +
+
+

Sets the amount of fuel in this store to fuel.

+

This is only relevant when Config.consume_fuel is configured.

+

This is a required call to ensure that the store has fuel to +execute WebAssembly since otherwise stores start with zero fuel.

+

Raises a WasmtimeError if this store's configuration is not configured +to consume fuel.

+
+ +Expand source code + +
def set_fuel(self, fuel: int) -> None:
+    """
+    Sets the amount of fuel in this store to `fuel`.
+
+    This is only relevant when `Config.consume_fuel` is configured.
+
+    This is a required call to ensure that the store has fuel to
+    execute WebAssembly since otherwise stores start with zero fuel.
+
+    Raises a `WasmtimeError` if this store's configuration is not configured
+    to consume fuel.
+    """
+    err = ffi.wasmtime_context_set_fuel(self._context, fuel)
+    if err:
+        raise WasmtimeError._from_ptr(err)
+
+
+
+def set_limits(self, memory_size: int = -1, table_elements: int = -1, instances: int = -1, tables: int = -1, memories: int = -1) ‑> None +
+
+

Configures the limits of various items within this store.

+
    +
  • +

    memory_size - the maximum size, in bytes, that linear memory is +allowed to consume within this store. Setting this to a lower value +will cause instantiation to fail if a module needs more memory. +Additionally the memory.grow instruction will return -1 once this +threshold is reached.

    +
  • +
  • +

    table_elements - the maximum number of elements that can be stored +within tables in this store. Currently each table element takes 8 +bytes.

    +
  • +
  • +

    instances - the maximum number of WebAssembly instances that can +be created.

    +
  • +
  • +

    tables - the maximum number of WebAssembly tables that can +be created.

    +
  • +
  • +

    memories - the maximum number of WebAssembly linear memories that +can be created.

    +
  • +
+

If any limit is negative then the limit will not be set as a part of +this invocation and it will be ignored.

+
+ +Expand source code + +
def set_limits(self,
+               memory_size: int = -1,
+               table_elements: int = -1,
+               instances: int = -1,
+               tables: int = -1,
+               memories: int = -1) -> None:
+    """
+    Configures the limits of various items within this store.
+
+    * `memory_size` - the maximum size, in bytes, that linear memory is
+      allowed to consume within this store. Setting this to a lower value
+      will cause instantiation to fail if a module needs more memory.
+      Additionally the `memory.grow` instruction will return -1 once this
+      threshold is reached.
+
+    * `table_elements` - the maximum number of elements that can be stored
+      within tables in this store. Currently each table element takes 8
+      bytes.
+
+    * `instances` - the maximum number of WebAssembly instances that can
+      be created.
+
+    * `tables` - the maximum number of WebAssembly tables that can
+      be created.
+
+    * `memories` - the maximum number of WebAssembly linear memories that
+      can be created.
+
+    If any limit is negative then the limit will not be set as a part of
+    this invocation and it will be ignored.
+    """
+    ffi.wasmtime_store_limiter(self._ptr, memory_size, table_elements, instances, tables, memories)
+
+
+
+def set_wasi(self, wasi: WasiConfig) +
+
+

TODO

+
+ +Expand source code + +
def set_wasi(self, wasi: "WasiConfig") -> None:
+    """
+    TODO
+    """
+    error = ffi.wasmtime_context_set_wasi(self._context, wasi._ptr)
+    delattr(wasi, '_ptr')
+    if error:
+        raise WasmtimeError._from_ptr(error)
+
+
+
+
+
+class Table +(store: wasmtime._store.Store, ty: wasmtime._types.TableType, init: Union[wasmtime._value.Val, int, float, ForwardRef(None), ForwardRef('Func'), Any]) +
+
+

Creates a new table within store with the specified ty.

+
+ +Expand source code + +
class Table:
+    _table: ffi.wasmtime_table_t
+
+    def __init__(self, store: Store, ty: TableType, init: IntoVal):
+        """
+        Creates a new table within `store` with the specified `ty`.
+        """
+
+        init_val = Val._convert(ty.element, init)
+
+        table = ffi.wasmtime_table_t()
+        error = ffi.wasmtime_table_new(store._context, ty._ptr, byref(init_val._unwrap_raw()), byref(table))
+        if error:
+            raise WasmtimeError._from_ptr(error)
+        self._table = table
+
+    @classmethod
+    def _from_raw(cls, table: ffi.wasmtime_table_t) -> "Table":
+        ty: "Table" = cls.__new__(cls)
+        ty._table = table
+        return ty
+
+    def type(self, store: Storelike) -> TableType:
+        """
+        Gets the type of this table as a `TableType`
+        """
+
+        ptr = ffi.wasmtime_table_type(store._context, byref(self._table))
+        return TableType._from_ptr(ptr, None)
+
+    def size(self, store: Storelike) -> int:
+        """
+        Gets the size, in elements, of this table
+        """
+        return ffi.wasmtime_table_size(store._context, byref(self._table))
+
+    def grow(self, store: Storelike, amt: int, init: IntoVal) -> int:
+        """
+        Grows this table by the specified number of slots, using the specified
+        initializer for all new table slots.
+
+        Raises a `WasmtimeError` if the table could not be grown.
+        Returns the previous size of the table otherwise.
+        """
+        init_val = Val._convert(self.type(store).element, init)
+        prev = c_uint32(0)
+        error = ffi.wasmtime_table_grow(store._context, byref(self._table), c_uint32(amt), byref(init_val._unwrap_raw()), byref(prev))
+        if error:
+            raise WasmtimeError._from_ptr(error)
+        return prev.value
+
+    def get(self, store: Store, idx: int) -> Optional[Any]:
+        """
+        Gets an individual element within this table.
+
+        Returns `None` for null references in the table (i.e. a null `funcref`
+        or a null `externref).
+
+        Returns a `Func` for non-null `funcref` table elements.
+
+        Returns the wrapped extern data for non-null `externref` table elements.
+
+        Returns `None` if `idx` is out of bounds.
+        """
+        raw = ffi.wasmtime_val_t()
+        ok = ffi.wasmtime_table_get(store._context, byref(self._table), idx, byref(raw))
+        if not ok:
+            return None
+        val = Val(raw)
+        if val.value:
+            return val.value
+        else:
+            return val
+
+    def set(self, store: Store, idx: int, val: IntoVal) -> None:
+        """
+        Sets an individual element within this table.
+
+        `idx` must be an integer index.
+
+        The `val` specified must be convertible into this table's element
+        type. I.e. for a `funcref` table, `val` must either be a `Func` or
+        `None`, and for an `externref` table, `val` may be any arbitrary
+        external data.
+
+        Raises a `WasmtimeError` if `idx` is out of bounds.
+        """
+        value = Val._convert(self.type(store).element, val)
+        error = ffi.wasmtime_table_set(store._context, byref(self._table), idx, byref(value._unwrap_raw()))
+        if error:
+            raise WasmtimeError._from_ptr(error)
+
+    def _as_extern(self) -> ffi.wasmtime_extern_t:
+        union = ffi.wasmtime_extern_union(table=self._table)
+        return ffi.wasmtime_extern_t(ffi.WASMTIME_EXTERN_TABLE, union)
+
+

Methods

+
+
+def get(self, store: wasmtime._store.Store, idx: int) ‑> Optional[Any] +
+
+

Gets an individual element within this table.

+

Returns None for null references in the table (i.e. a null funcref +or a null `externref).

+

Returns a Func for non-null funcref table elements.

+

Returns the wrapped extern data for non-null externref table elements.

+

Returns None if idx is out of bounds.

+
+ +Expand source code + +
def get(self, store: Store, idx: int) -> Optional[Any]:
+    """
+    Gets an individual element within this table.
+
+    Returns `None` for null references in the table (i.e. a null `funcref`
+    or a null `externref).
+
+    Returns a `Func` for non-null `funcref` table elements.
+
+    Returns the wrapped extern data for non-null `externref` table elements.
+
+    Returns `None` if `idx` is out of bounds.
+    """
+    raw = ffi.wasmtime_val_t()
+    ok = ffi.wasmtime_table_get(store._context, byref(self._table), idx, byref(raw))
+    if not ok:
+        return None
+    val = Val(raw)
+    if val.value:
+        return val.value
+    else:
+        return val
+
+
+
+def grow(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')], amt: int, init: Union[wasmtime._value.Val, int, float, ForwardRef(None), ForwardRef('Func'), Any]) ‑> int +
+
+

Grows this table by the specified number of slots, using the specified +initializer for all new table slots.

+

Raises a WasmtimeError if the table could not be grown. +Returns the previous size of the table otherwise.

+
+ +Expand source code + +
def grow(self, store: Storelike, amt: int, init: IntoVal) -> int:
+    """
+    Grows this table by the specified number of slots, using the specified
+    initializer for all new table slots.
+
+    Raises a `WasmtimeError` if the table could not be grown.
+    Returns the previous size of the table otherwise.
+    """
+    init_val = Val._convert(self.type(store).element, init)
+    prev = c_uint32(0)
+    error = ffi.wasmtime_table_grow(store._context, byref(self._table), c_uint32(amt), byref(init_val._unwrap_raw()), byref(prev))
+    if error:
+        raise WasmtimeError._from_ptr(error)
+    return prev.value
+
+
+
+def set(self, store: wasmtime._store.Store, idx: int, val: Union[wasmtime._value.Val, int, float, ForwardRef(None), ForwardRef('Func'), Any]) +
+
+

Sets an individual element within this table.

+

idx must be an integer index.

+

The val specified must be convertible into this table's element +type. I.e. for a funcref table, val must either be a Func or +None, and for an externref table, val may be any arbitrary +external data.

+

Raises a WasmtimeError if idx is out of bounds.

+
+ +Expand source code + +
def set(self, store: Store, idx: int, val: IntoVal) -> None:
+    """
+    Sets an individual element within this table.
+
+    `idx` must be an integer index.
+
+    The `val` specified must be convertible into this table's element
+    type. I.e. for a `funcref` table, `val` must either be a `Func` or
+    `None`, and for an `externref` table, `val` may be any arbitrary
+    external data.
+
+    Raises a `WasmtimeError` if `idx` is out of bounds.
+    """
+    value = Val._convert(self.type(store).element, val)
+    error = ffi.wasmtime_table_set(store._context, byref(self._table), idx, byref(value._unwrap_raw()))
+    if error:
+        raise WasmtimeError._from_ptr(error)
+
+
+
+def size(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')]) ‑> int +
+
+

Gets the size, in elements, of this table

+
+ +Expand source code + +
def size(self, store: Storelike) -> int:
+    """
+    Gets the size, in elements, of this table
+    """
+    return ffi.wasmtime_table_size(store._context, byref(self._table))
+
+
+
+def type(self, store: Union[wasmtime._store.Store, ForwardRef('Caller')]) ‑> wasmtime._types.TableType +
+
+

Gets the type of this table as a TableType

+
+ +Expand source code + +
def type(self, store: Storelike) -> TableType:
+    """
+    Gets the type of this table as a `TableType`
+    """
+
+    ptr = ffi.wasmtime_table_type(store._context, byref(self._table))
+    return TableType._from_ptr(ptr, None)
+
+
+
+
+
+class TableType +(valtype: wasmtime._types.ValType, limits: wasmtime._types.Limits) +
+
+
+
+ +Expand source code + +
class TableType:
+    def __init__(self, valtype: ValType, limits: Limits):
+        if not isinstance(limits, Limits):
+            raise TypeError("expected Limits")
+        type_ptr = take_owned_valtype(valtype)
+        ptr = ffi.wasm_tabletype_new(type_ptr, byref(limits.__ffi__()))
+        if not ptr:
+            raise WasmtimeError("failed to allocate TableType")
+        self._ptr = ptr
+        self._owner = None
+
+    @classmethod
+    def _from_ptr(cls, ptr: 'ctypes._Pointer[ffi.wasm_tabletype_t]', owner: Optional[Any]) -> "TableType":
+        ty: "TableType" = cls.__new__(cls)
+        if not isinstance(ptr, POINTER(ffi.wasm_tabletype_t)):
+            raise TypeError("wrong pointer type")
+        ty._ptr = ptr
+        ty._owner = owner
+        return ty
+
+    @property
+    def element(self) -> ValType:
+        """
+        Returns the type of this table's elements
+        """
+        ptr = ffi.wasm_tabletype_element(self._ptr)
+        return ValType._from_ptr(ptr, self)
+
+    @property
+    def limits(self) -> Limits:
+        """
+        Returns the limits on the size of thi stable
+        """
+        val = ffi.wasm_tabletype_limits(self._ptr)
+        return Limits._from_ffi(val)
+
+    def _as_extern(self) -> "ctypes._Pointer[ffi.wasm_externtype_t]":
+        return ffi.wasm_tabletype_as_externtype_const(self._ptr)
+
+    def __del__(self) -> None:
+        if hasattr(self, '_owner') and self._owner is None:
+            ffi.wasm_tabletype_delete(self._ptr)
+
+

Instance variables

+
+
var element : wasmtime._types.ValType
+
+

Returns the type of this table's elements

+
+ +Expand source code + +
@property
+def element(self) -> ValType:
+    """
+    Returns the type of this table's elements
+    """
+    ptr = ffi.wasm_tabletype_element(self._ptr)
+    return ValType._from_ptr(ptr, self)
+
+
+
var limits : wasmtime._types.Limits
+
+

Returns the limits on the size of thi stable

+
+ +Expand source code + +
@property
+def limits(self) -> Limits:
+    """
+    Returns the limits on the size of thi stable
+    """
+    val = ffi.wasm_tabletype_limits(self._ptr)
+    return Limits._from_ffi(val)
+
+
+
+
+
+class Trap +(message: str) +
+
+

Common base class for all non-exit exceptions.

+

Creates a new trap with the given message

+
+ +Expand source code + +
class Trap(Exception):
+    _ptr: "ctypes._Pointer[ffi.wasm_trap_t]"
+
+    def __init__(self, message: str):
+        """
+        Creates a new trap with the given `message`
+        """
+
+        vec = message.encode('utf-8')
+        self._ptr = ffi.wasmtime_trap_new(ffi.create_string_buffer(vec), len(vec))
+
+    @classmethod
+    def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasm_trap_t]") -> "Trap":
+        if not isinstance(ptr, POINTER(ffi.wasm_trap_t)):
+            raise TypeError("wrong pointer type")
+        trap: Trap = cls.__new__(cls)
+        trap._ptr = ptr
+        return trap
+
+    @property
+    def message(self) -> str:
+        """
+        Returns the message for this trap
+        """
+
+        message = ffi.wasm_byte_vec_t()
+        ffi.wasm_trap_message(self._ptr, byref(message))
+        # subtract one to chop off the trailing nul byte
+        message.size -= 1
+        ret = ffi.to_str(message)
+        message.size += 1
+        ffi.wasm_byte_vec_delete(byref(message))
+        return ret
+
+    @property
+    def frames(self) -> List["Frame"]:
+        frames = FrameList(self)
+        ffi.wasm_trap_trace(self._ptr, byref(frames.vec))
+        ret = []
+        for i in range(0, frames.vec.size):
+            ret.append(Frame._from_ptr(frames.vec.data[i], frames))
+        return ret
+
+    @property
+    def trap_code(self) -> Optional[TrapCode]:
+        """
+        Returns an optional `TrapCode` that corresponds to why this trap
+        happened.
+
+        Note that `None` may be returned for manually created traps which do
+        not have an associated code with them.
+        """
+        code = ffi.wasmtime_trap_code_t()
+        if ffi.wasmtime_trap_code(self._ptr, byref(code)):
+            return TrapCode(code.value)
+        return None
+
+    def __str__(self) -> str:
+        return self.message
+
+    def __del__(self) -> None:
+        if hasattr(self, '_ptr'):
+            ffi.wasm_trap_delete(self._ptr)
+
+

Ancestors

+
    +
  • builtins.Exception
  • +
  • builtins.BaseException
  • +
+

Instance variables

+
+
var frames : List[wasmtime._trap.Frame]
+
+
+
+ +Expand source code + +
@property
+def frames(self) -> List["Frame"]:
+    frames = FrameList(self)
+    ffi.wasm_trap_trace(self._ptr, byref(frames.vec))
+    ret = []
+    for i in range(0, frames.vec.size):
+        ret.append(Frame._from_ptr(frames.vec.data[i], frames))
+    return ret
+
+
+
var message : str
+
+

Returns the message for this trap

+
+ +Expand source code + +
@property
+def message(self) -> str:
+    """
+    Returns the message for this trap
+    """
+
+    message = ffi.wasm_byte_vec_t()
+    ffi.wasm_trap_message(self._ptr, byref(message))
+    # subtract one to chop off the trailing nul byte
+    message.size -= 1
+    ret = ffi.to_str(message)
+    message.size += 1
+    ffi.wasm_byte_vec_delete(byref(message))
+    return ret
+
+
+
var trap_code : Optional[wasmtime._trap.TrapCode]
+
+

Returns an optional TrapCode that corresponds to why this trap +happened.

+

Note that None may be returned for manually created traps which do +not have an associated code with them.

+
+ +Expand source code + +
@property
+def trap_code(self) -> Optional[TrapCode]:
+    """
+    Returns an optional `TrapCode` that corresponds to why this trap
+    happened.
+
+    Note that `None` may be returned for manually created traps which do
+    not have an associated code with them.
+    """
+    code = ffi.wasmtime_trap_code_t()
+    if ffi.wasmtime_trap_code(self._ptr, byref(code)):
+        return TrapCode(code.value)
+    return None
+
+
+
+
+
+class TrapCode +(*args, **kwds) +
+
+

Create a collection of name/value pairs.

+

Example enumeration:

+
>>> class Color(Enum):
+...     RED = 1
+...     BLUE = 2
+...     GREEN = 3
+
+

Access them by:

+
    +
  • attribute access:
  • +
+
+
+
+

Color.RED +

+
+
+
+
    +
  • value lookup:
  • +
+
+
+
+

Color(1) +

+
+
+
+
    +
  • name lookup:
  • +
+
+
+
+

Color['RED'] +

+
+
+
+

Enumerations can be iterated over, and know how many members they have:

+
>>> len(Color)
+3
+
+
>>> list(Color)
+[<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]
+
+

Methods can be added to enumerations, and members can have their own +attributes – see the documentation for details.

+
+ +Expand source code + +
class TrapCode(Enum):
+    # The current stack space was exhausted.
+    STACK_OVERFLOW = 0
+    # An out-of-bounds memory access.
+    MEMORY_OUT_OF_BOUNDS = 1
+    # A wasm atomic operation was presented with a not-naturally-aligned linear-memory address.
+    HEAP_MISALIGNED = 2
+    # An out-of-bounds access to a table.
+    TABLE_OUT_OF_BOUNDS = 3
+    # Indirect call to a null table entry.
+    INDIRECT_CALL_TO_NULL = 4
+    # Signature mismatch on indirect call.
+    BAD_SIGNATURE = 5
+    # An integer arithmetic operation caused an overflow.
+    INTEGER_OVERFLOW = 6
+    # An integer division by zero.
+    INTEGER_DIVISION_BY_ZERO = 7
+    # Failed float-to-int conversion.
+    BAD_CONVERSION_TO_INTEGER = 8
+    # Code that was supposed to have been unreachable was reached.
+    UNREACHABLE = 9
+    # Execution has potentially run too long and may be interrupted.
+    INTERRUPT = 10
+
+

Ancestors

+
    +
  • enum.Enum
  • +
+

Class variables

+
+
var BAD_CONVERSION_TO_INTEGER
+
+
+
+
var BAD_SIGNATURE
+
+
+
+
var HEAP_MISALIGNED
+
+
+
+
var INDIRECT_CALL_TO_NULL
+
+
+
+
var INTEGER_DIVISION_BY_ZERO
+
+
+
+
var INTEGER_OVERFLOW
+
+
+
+
var INTERRUPT
+
+
+
+
var MEMORY_OUT_OF_BOUNDS
+
+
+
+
var STACK_OVERFLOW
+
+
+
+
var TABLE_OUT_OF_BOUNDS
+
+
+
+
var UNREACHABLE
+
+
+
+
+
+
+class Val +(raw: wasmtime._bindings.wasmtime_val) +
+
+
+
+ +Expand source code + +
class Val:
+    # We can't let the extern values we wrap `externref`s around be GC'd, so we
+    # pin them in `_id_to_extern`. Additionally, we might make multiple
+    # `externref`s to the same extern value, so we count how many references
+    # we've created in `_id_to_ref_count`, and only remove a value's entry from
+    # `_id_to_extern` once the ref count is zero.
+    _id_to_extern: typing.Dict[int, typing.Any] = {}
+    _id_to_ref_count: typing.Dict[int, int] = {}
+
+    _raw: typing.Optional[wasmtime_val_t]
+
+    @classmethod
+    def i32(cls, val: int) -> "Val":
+        """
+        Create a new 32-bit integer value
+        """
+        if not isinstance(val, int):
+            raise TypeError("expected an integer")
+        ffi = wasmtime_val_t(WASMTIME_I32, wasmtime_valunion(i32=val))
+        return Val(ffi)
+
+    @classmethod
+    def i64(cls, val: int) -> "Val":
+        """
+        Create a new 64-bit integer value
+        """
+        if not isinstance(val, int):
+            raise TypeError("expected an integer")
+        ffi = wasmtime_val_t(WASMTIME_I64, wasmtime_valunion(i64=val))
+        return Val(ffi)
+
+    @classmethod
+    def f32(cls, val: float) -> "Val":
+        """
+        Create a new 32-bit float value
+        """
+        if not isinstance(val, float):
+            raise TypeError("expected a float")
+        ffi = wasmtime_val_t(WASMTIME_F32, wasmtime_valunion(f32=val))
+        return Val(ffi)
+
+    @classmethod
+    def f64(cls, val: float) -> "Val":
+        """
+        Create a new 64-bit float value
+        """
+        if not isinstance(val, float):
+            raise TypeError("expected a float")
+        ffi = wasmtime_val_t(WASMTIME_F64, wasmtime_valunion(f64=val))
+        return Val(ffi)
+
+    @classmethod
+    def externref(cls, extern: typing.Optional[typing.Any]) -> "Val":
+        ffi = wasmtime_val_t(WASMTIME_EXTERNREF)
+        ffi.of.externref = POINTER(wasmtime_externref_t)()
+        if extern is not None:
+            extern_id = _intern(extern)
+            ptr = wasmtime_externref_new(extern_id, _externref_finalizer)
+            ffi.of.externref = ptr
+        return Val(ffi)
+
+    @classmethod
+    def funcref(cls, f: "typing.Optional[wasmtime.Func]") -> "Val":
+        ffi = wasmtime_val_t(WASMTIME_FUNCREF)
+        if f:
+            ffi.of.funcref = f._func
+        return Val(ffi)
+
+    @classmethod
+    def ref_null(cls, ty: ValType) -> "Val":
+        """
+        Create a null reference value of the given type.
+
+        Raise an exception if `ty` is not a reference type.
+        """
+        if ty == ValType.externref():
+            return Val.externref(None)
+        if ty == ValType.funcref():
+            return Val.funcref(None)
+        raise WasmtimeError("Invalid reference type for `ref_null`: %s" % ty)
+
+    def __init__(self, raw: wasmtime_val_t):
+        self._raw = raw
+
+    def __eq__(self, rhs: typing.Any) -> typing.Any:
+        if isinstance(rhs, Val):
+            return self._unwrap_raw().kind == rhs._unwrap_raw().kind and self.value == rhs.value
+        return self.value == rhs
+
+    def __del__(self) -> None:
+        if hasattr(self, "_raw") and self._raw is not None:
+            wasmtime_val_delete(ctypes.byref(self._raw))
+
+    def _clone(self) -> "Val":
+        raw = self._unwrap_raw()
+        if raw.kind == WASMTIME_EXTERNREF and raw.of.externref:
+            externref = wasmtime_externref_clone(raw.of.externref)
+            raw = wasmtime_val_t(WASMTIME_EXTERNREF)
+            raw.of.externref = externref
+        return Val(raw)
+
+    @classmethod
+    def _convert(cls, ty: ValType, val: "IntoVal") -> "Val":
+        if isinstance(val, Val):
+            if ty != val.type:
+                raise TypeError("wrong type of `Val` provided")
+            return val
+        if ty == ValType.externref():
+            return Val.externref(val)
+        if isinstance(val, int):
+            if ty == ValType.i32():
+                return Val.i32(val)
+            if ty == ValType.i64():
+                return Val.i64(val)
+        elif isinstance(val, float):
+            if ty == ValType.f32():
+                return Val.f32(val)
+            if ty == ValType.f64():
+                return Val.f64(val)
+        elif isinstance(val, wasmtime.Func):
+            return Val.funcref(val)
+        elif val is None:
+            if ty == ValType.externref():
+                return Val.externref(None)
+            if ty == ValType.funcref():
+                return Val.funcref(None)
+        raise TypeError("don't know how to convert %r to %s" % (val, ty))
+
+    def _into_raw(self) -> wasmtime_val_t:
+        raw = self._unwrap_raw()
+        self._raw = None
+        return raw
+
+    def _unwrap_raw(self) -> wasmtime_val_t:
+        if isinstance(self._raw, wasmtime_val_t):
+            return self._raw
+        else:
+            raise WasmtimeError("use of moved `Val`")
+
+    @classmethod
+    def _value(cls, raw: wasmtime_val_t) -> typing.Union[int, float, "wasmtime.Func", typing.Any]:
+        if raw.kind == WASMTIME_I32.value:
+            return raw.of.i32
+        if raw.kind == WASMTIME_I64.value:
+            return raw.of.i64
+        if raw.kind == WASMTIME_F32.value:
+            return raw.of.f32
+        if raw.kind == WASMTIME_F64.value:
+            return raw.of.f64
+        if raw.kind == WASMTIME_EXTERNREF.value:
+            return Val._as_externref(raw)
+        if raw.kind == WASMTIME_FUNCREF.value:
+            return Val._as_funcref(raw)
+        raise WasmtimeError("Unkown `wasmtime_valkind_t`: {}".format(raw.kind))
+
+    @property
+    def value(self) -> typing.Union[int, float, "wasmtime.Func", typing.Any]:
+        """
+        Get the the underlying value as a python value
+
+        Returns `None` if the value can't be represented in Python, or if the
+        value is a null reference type.
+        """
+        return Val._value(self._unwrap_raw())
+
+    def as_i32(self) -> typing.Optional[int]:
+        """
+        Get the 32-bit integer value of this value, or `None` if it's not an i32
+        """
+        raw = self._unwrap_raw()
+        if raw.kind == WASMTIME_I32.value:
+            return int(raw.of.i32)
+        else:
+            return None
+
+    def as_i64(self) -> typing.Optional[int]:
+        """
+        Get the 64-bit integer value of this value, or `None` if it's not an i64
+        """
+        raw = self._unwrap_raw()
+        if raw.kind == WASM_I64.value:
+            return raw.of.i64
+        else:
+            return None
+
+    def as_f32(self) -> typing.Optional[float]:
+        """
+        Get the 32-bit float value of this value, or `None` if it's not an f32
+        """
+        raw = self._unwrap_raw()
+        if raw.kind == WASMTIME_F32.value:
+            return raw.of.f32
+        else:
+            return None
+
+    def as_f64(self) -> typing.Optional[float]:
+        """
+        Get the 64-bit float value of this value, or `None` if it's not an f64
+        """
+        raw = self._unwrap_raw()
+        if raw.kind == WASMTIME_F64.value:
+            return raw.of.f64
+        else:
+            return None
+
+    @classmethod
+    def _as_externref(cls, raw: wasmtime_val_t) -> typing.Optional[typing.Any]:
+        if raw.kind != WASMTIME_EXTERNREF.value:
+            return None
+        if not raw.of.externref:
+            return None
+        extern_id = wasmtime_externref_data(raw.of.externref)
+        return _unintern(extern_id)
+
+    def as_externref(self) -> typing.Optional[typing.Any]:
+        """
+        Get the extern data referenced by this `externref` value, or `None` if
+        it's not an `externref`.
+        """
+        return Val._as_externref(self._unwrap_raw())
+
+    @classmethod
+    def _as_funcref(cls, raw: wasmtime_val_t) -> typing.Optional["wasmtime.Func"]:
+        if raw.kind != WASMTIME_FUNCREF.value:
+            return None
+        if raw.of.funcref.store_id == 0:
+            return None
+        else:
+            return wasmtime.Func._from_raw(raw.of.funcref)
+
+    def as_funcref(self) -> typing.Optional["wasmtime.Func"]:
+        """
+        Get the function that this `funcref` value is referencing, or `None` if
+        this is not a `funcref` value, or is a null reference.
+        """
+        return Val._as_funcref(self._unwrap_raw())
+
+    @property
+    def type(self) -> ValType:
+        """
+        Returns the `ValType` corresponding to this `Val`
+        """
+        kind = self._unwrap_raw().kind
+        if kind == WASMTIME_I32.value:
+            return ValType.i32()
+        elif kind == WASMTIME_I64.value:
+            return ValType.i64()
+        elif kind == WASMTIME_F32.value:
+            return ValType.f32()
+        elif kind == WASMTIME_F64.value:
+            return ValType.f64()
+        elif kind == WASMTIME_V128.value:
+            raise Exception("unimplemented v128 type")
+        elif kind == WASMTIME_EXTERNREF.value:
+            return ValType.externref()
+        elif kind == WASMTIME_FUNCREF.value:
+            return ValType.funcref()
+        else:
+            raise Exception("unknown kind %d" % kind.value)
+
+

Static methods

+
+
+def externref(extern: Optional[Any]) ‑> wasmtime._value.Val +
+
+
+
+ +Expand source code + +
@classmethod
+def externref(cls, extern: typing.Optional[typing.Any]) -> "Val":
+    ffi = wasmtime_val_t(WASMTIME_EXTERNREF)
+    ffi.of.externref = POINTER(wasmtime_externref_t)()
+    if extern is not None:
+        extern_id = _intern(extern)
+        ptr = wasmtime_externref_new(extern_id, _externref_finalizer)
+        ffi.of.externref = ptr
+    return Val(ffi)
+
+
+
+def f32(val: float) ‑> wasmtime._value.Val +
+
+

Create a new 32-bit float value

+
+ +Expand source code + +
@classmethod
+def f32(cls, val: float) -> "Val":
+    """
+    Create a new 32-bit float value
+    """
+    if not isinstance(val, float):
+        raise TypeError("expected a float")
+    ffi = wasmtime_val_t(WASMTIME_F32, wasmtime_valunion(f32=val))
+    return Val(ffi)
+
+
+
+def f64(val: float) ‑> wasmtime._value.Val +
+
+

Create a new 64-bit float value

+
+ +Expand source code + +
@classmethod
+def f64(cls, val: float) -> "Val":
+    """
+    Create a new 64-bit float value
+    """
+    if not isinstance(val, float):
+        raise TypeError("expected a float")
+    ffi = wasmtime_val_t(WASMTIME_F64, wasmtime_valunion(f64=val))
+    return Val(ffi)
+
+
+
+def funcref(f: typing.Optional[Func]) ‑> wasmtime._value.Val +
+
+
+
+ +Expand source code + +
@classmethod
+def funcref(cls, f: "typing.Optional[wasmtime.Func]") -> "Val":
+    ffi = wasmtime_val_t(WASMTIME_FUNCREF)
+    if f:
+        ffi.of.funcref = f._func
+    return Val(ffi)
+
+
+
+def i32(val: int) ‑> wasmtime._value.Val +
+
+

Create a new 32-bit integer value

+
+ +Expand source code + +
@classmethod
+def i32(cls, val: int) -> "Val":
+    """
+    Create a new 32-bit integer value
+    """
+    if not isinstance(val, int):
+        raise TypeError("expected an integer")
+    ffi = wasmtime_val_t(WASMTIME_I32, wasmtime_valunion(i32=val))
+    return Val(ffi)
+
+
+
+def i64(val: int) ‑> wasmtime._value.Val +
+
+

Create a new 64-bit integer value

+
+ +Expand source code + +
@classmethod
+def i64(cls, val: int) -> "Val":
+    """
+    Create a new 64-bit integer value
+    """
+    if not isinstance(val, int):
+        raise TypeError("expected an integer")
+    ffi = wasmtime_val_t(WASMTIME_I64, wasmtime_valunion(i64=val))
+    return Val(ffi)
+
+
+
+def ref_null(ty: wasmtime._types.ValType) ‑> wasmtime._value.Val +
+
+

Create a null reference value of the given type.

+

Raise an exception if ty is not a reference type.

+
+ +Expand source code + +
@classmethod
+def ref_null(cls, ty: ValType) -> "Val":
+    """
+    Create a null reference value of the given type.
+
+    Raise an exception if `ty` is not a reference type.
+    """
+    if ty == ValType.externref():
+        return Val.externref(None)
+    if ty == ValType.funcref():
+        return Val.funcref(None)
+    raise WasmtimeError("Invalid reference type for `ref_null`: %s" % ty)
+
+
+
+

Instance variables

+
+
var type : wasmtime._types.ValType
+
+

Returns the ValType corresponding to this Val

+
+ +Expand source code + +
@property
+def type(self) -> ValType:
+    """
+    Returns the `ValType` corresponding to this `Val`
+    """
+    kind = self._unwrap_raw().kind
+    if kind == WASMTIME_I32.value:
+        return ValType.i32()
+    elif kind == WASMTIME_I64.value:
+        return ValType.i64()
+    elif kind == WASMTIME_F32.value:
+        return ValType.f32()
+    elif kind == WASMTIME_F64.value:
+        return ValType.f64()
+    elif kind == WASMTIME_V128.value:
+        raise Exception("unimplemented v128 type")
+    elif kind == WASMTIME_EXTERNREF.value:
+        return ValType.externref()
+    elif kind == WASMTIME_FUNCREF.value:
+        return ValType.funcref()
+    else:
+        raise Exception("unknown kind %d" % kind.value)
+
+
+
var value : Union[int, float, wasmtime._func.Func, Any]
+
+

Get the the underlying value as a python value

+

Returns None if the value can't be represented in Python, or if the +value is a null reference type.

+
+ +Expand source code + +
@property
+def value(self) -> typing.Union[int, float, "wasmtime.Func", typing.Any]:
+    """
+    Get the the underlying value as a python value
+
+    Returns `None` if the value can't be represented in Python, or if the
+    value is a null reference type.
+    """
+    return Val._value(self._unwrap_raw())
+
+
+
+

Methods

+
+
+def as_externref(self) ‑> Optional[Any] +
+
+

Get the extern data referenced by this externref value, or None if +it's not an externref.

+
+ +Expand source code + +
def as_externref(self) -> typing.Optional[typing.Any]:
+    """
+    Get the extern data referenced by this `externref` value, or `None` if
+    it's not an `externref`.
+    """
+    return Val._as_externref(self._unwrap_raw())
+
+
+
+def as_f32(self) ‑> Optional[float] +
+
+

Get the 32-bit float value of this value, or None if it's not an f32

+
+ +Expand source code + +
def as_f32(self) -> typing.Optional[float]:
+    """
+    Get the 32-bit float value of this value, or `None` if it's not an f32
+    """
+    raw = self._unwrap_raw()
+    if raw.kind == WASMTIME_F32.value:
+        return raw.of.f32
+    else:
+        return None
+
+
+
+def as_f64(self) ‑> Optional[float] +
+
+

Get the 64-bit float value of this value, or None if it's not an f64

+
+ +Expand source code + +
def as_f64(self) -> typing.Optional[float]:
+    """
+    Get the 64-bit float value of this value, or `None` if it's not an f64
+    """
+    raw = self._unwrap_raw()
+    if raw.kind == WASMTIME_F64.value:
+        return raw.of.f64
+    else:
+        return None
+
+
+
+def as_funcref(self) ‑> Optional[wasmtime._func.Func] +
+
+

Get the function that this funcref value is referencing, or None if +this is not a funcref value, or is a null reference.

+
+ +Expand source code + +
def as_funcref(self) -> typing.Optional["wasmtime.Func"]:
+    """
+    Get the function that this `funcref` value is referencing, or `None` if
+    this is not a `funcref` value, or is a null reference.
+    """
+    return Val._as_funcref(self._unwrap_raw())
+
+
+
+def as_i32(self) ‑> Optional[int] +
+
+

Get the 32-bit integer value of this value, or None if it's not an i32

+
+ +Expand source code + +
def as_i32(self) -> typing.Optional[int]:
+    """
+    Get the 32-bit integer value of this value, or `None` if it's not an i32
+    """
+    raw = self._unwrap_raw()
+    if raw.kind == WASMTIME_I32.value:
+        return int(raw.of.i32)
+    else:
+        return None
+
+
+
+def as_i64(self) ‑> Optional[int] +
+
+

Get the 64-bit integer value of this value, or None if it's not an i64

+
+ +Expand source code + +
def as_i64(self) -> typing.Optional[int]:
+    """
+    Get the 64-bit integer value of this value, or `None` if it's not an i64
+    """
+    raw = self._unwrap_raw()
+    if raw.kind == WASM_I64.value:
+        return raw.of.i64
+    else:
+        return None
+
+
+
+
+
+class ValType +
+
+
+
+ +Expand source code + +
class ValType:
+    _ptr: "ctypes._Pointer[ffi.wasm_valtype_t]"
+    _owner: Optional[Any]
+
+    @classmethod
+    def i32(cls) -> "ValType":
+        ptr = ffi.wasm_valtype_new(ffi.WASM_I32)
+        return ValType._from_ptr(ptr, None)
+
+    @classmethod
+    def i64(cls) -> "ValType":
+        ptr = ffi.wasm_valtype_new(ffi.WASM_I64)
+        return ValType._from_ptr(ptr, None)
+
+    @classmethod
+    def f32(cls) -> "ValType":
+        ptr = ffi.wasm_valtype_new(ffi.WASM_F32)
+        return ValType._from_ptr(ptr, None)
+
+    @classmethod
+    def f64(cls) -> "ValType":
+        ptr = ffi.wasm_valtype_new(ffi.WASM_F64)
+        return ValType._from_ptr(ptr, None)
+
+    @classmethod
+    def externref(cls) -> "ValType":
+        ptr = ffi.wasm_valtype_new(ffi.WASM_ANYREF)
+        return ValType._from_ptr(ptr, None)
+
+    @classmethod
+    def funcref(cls) -> "ValType":
+        ptr = ffi.wasm_valtype_new(ffi.WASM_FUNCREF)
+        return ValType._from_ptr(ptr, None)
+
+    def __init__(self) -> None:
+        raise WasmtimeError("cannot construct directly")
+
+    @classmethod
+    def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasm_valtype_t]", owner: Optional[Any]) -> "ValType":
+        ty: "ValType" = cls.__new__(cls)
+        if not isinstance(ptr, POINTER(ffi.wasm_valtype_t)):
+            raise TypeError("wrong pointer type")
+        ty._ptr = ptr
+        ty._owner = owner
+        return ty
+
+    def __eq__(self, other: object) -> bool:
+        if not isinstance(other, ValType):
+            return False
+        assert(self._ptr is not None)
+        assert(other._ptr is not None)
+        kind1 = ffi.wasm_valtype_kind(self._ptr)
+        kind2 = ffi.wasm_valtype_kind(other._ptr)
+        return kind1 == kind2
+
+    def __ne__(self, other: object) -> bool:
+        return not self.__eq__(other)
+
+    def __repr__(self) -> str:
+        return str(self)
+
+    def __str__(self) -> str:
+        assert(self._ptr is not None)
+        kind = ffi.wasm_valtype_kind(self._ptr)
+        if kind == ffi.WASM_I32.value:
+            return 'i32'
+        if kind == ffi.WASM_I64.value:
+            return 'i64'
+        if kind == ffi.WASM_F32.value:
+            return 'f32'
+        if kind == ffi.WASM_F64.value:
+            return 'f64'
+        if kind == ffi.WASM_ANYREF.value:
+            return 'anyref'
+        if kind == ffi.WASM_FUNCREF.value:
+            return 'funcref'
+        return 'ValType(%d)' % kind.value
+
+    def __del__(self) -> None:
+        if not hasattr(self, '_owner') or not hasattr(self, '_ptr'):
+            return
+        # If this is owned by another object we don't free it since that object
+        # is responsible for freeing the backing memory.
+        if self._owner is None:
+            ffi.wasm_valtype_delete(self._ptr)
+
+    @classmethod
+    def _from_list(cls, items: "ctypes._Pointer[ffi.wasm_valtype_vec_t]", owner: Optional[Any]) -> List["ValType"]:
+        types = []
+        for i in range(0, items.contents.size):
+            types.append(ValType._from_ptr(items.contents.data[i], owner))
+        return types
+
+

Static methods

+
+
+def externref() ‑> wasmtime._types.ValType +
+
+
+
+ +Expand source code + +
@classmethod
+def externref(cls) -> "ValType":
+    ptr = ffi.wasm_valtype_new(ffi.WASM_ANYREF)
+    return ValType._from_ptr(ptr, None)
+
+
+
+def f32() ‑> wasmtime._types.ValType +
+
+
+
+ +Expand source code + +
@classmethod
+def f32(cls) -> "ValType":
+    ptr = ffi.wasm_valtype_new(ffi.WASM_F32)
+    return ValType._from_ptr(ptr, None)
+
+
+
+def f64() ‑> wasmtime._types.ValType +
+
+
+
+ +Expand source code + +
@classmethod
+def f64(cls) -> "ValType":
+    ptr = ffi.wasm_valtype_new(ffi.WASM_F64)
+    return ValType._from_ptr(ptr, None)
+
+
+
+def funcref() ‑> wasmtime._types.ValType +
+
+
+
+ +Expand source code + +
@classmethod
+def funcref(cls) -> "ValType":
+    ptr = ffi.wasm_valtype_new(ffi.WASM_FUNCREF)
+    return ValType._from_ptr(ptr, None)
+
+
+
+def i32() ‑> wasmtime._types.ValType +
+
+
+
+ +Expand source code + +
@classmethod
+def i32(cls) -> "ValType":
+    ptr = ffi.wasm_valtype_new(ffi.WASM_I32)
+    return ValType._from_ptr(ptr, None)
+
+
+
+def i64() ‑> wasmtime._types.ValType +
+
+
+
+ +Expand source code + +
@classmethod
+def i64(cls) -> "ValType":
+    ptr = ffi.wasm_valtype_new(ffi.WASM_I64)
+    return ValType._from_ptr(ptr, None)
+
+
+
+
+
+class WasiConfig +
+
+
+
+ +Expand source code + +
class WasiConfig:
+    def __init__(self) -> None:
+        self._ptr = ffi.wasi_config_new()
+
+    @setter_property
+    def argv(self, argv: List[str]) -> None:
+        """
+        Explicitly configure the `argv` for this WASI configuration
+        """
+        ptrs = to_char_array(argv)
+        ffi.wasi_config_set_argv(self._ptr, c_int(len(argv)), ptrs)
+
+    def inherit_argv(self) -> None:
+        ffi.wasi_config_inherit_argv(self._ptr)
+
+    @setter_property
+    def env(self, pairs: Iterable[Iterable]) -> None:
+        """
+        Configure environment variables to be returned for this WASI
+        configuration.
+
+        The `pairs` provided must be an iterable list of key/value pairs of
+        environment variables.
+        """
+        names = []
+        values = []
+        for name, value in pairs:
+            names.append(name)
+            values.append(value)
+        name_ptrs = to_char_array(names)
+        value_ptrs = to_char_array(values)
+        ffi.wasi_config_set_env(self._ptr, c_int(
+            len(names)), name_ptrs, value_ptrs)
+
+    def inherit_env(self) -> None:
+        """
+        Configures the environment variables available within WASI to be those
+        in this own process's environment. All environment variables are
+        inherited.
+        """
+        ffi.wasi_config_inherit_env(self._ptr)
+
+    @setter_property
+    def stdin_file(self, path: Union[str, bytes, PathLike]) -> None:
+        """
+        Configures a file to be used as the stdin stream of this WASI
+        configuration.
+
+        Reads of the stdin stream will read the path specified.
+
+        The file must already exist on the filesystem. If it cannot be
+        opened then `WasmtimeError` is raised.
+        """
+
+        res = ffi.wasi_config_set_stdin_file(
+            self._ptr, c_char_p(_encode_path(path)))
+        if not res:
+            raise WasmtimeError("failed to set stdin file")
+
+    def inherit_stdin(self) -> None:
+        """
+        Configures this own process's stdin to be used as the WASI program's
+        stdin.
+
+        Reads of the stdin stream will read this process's stdin.
+        """
+        ffi.wasi_config_inherit_stdin(self._ptr)
+
+    @setter_property
+    def stdout_file(self, path: str) -> None:
+        """
+        Configures a file to be used as the stdout stream of this WASI
+        configuration.
+
+        Writes to stdout will be written to the file specified.
+
+        The file specified will be created if it doesn't exist, or truncated if
+        it already exists. It must be available to open for writing. If it
+        cannot be opened for writing then `WasmtimeError` is raised.
+        """
+        res = ffi.wasi_config_set_stdout_file(
+            self._ptr, c_char_p(_encode_path(path)))
+        if not res:
+            raise WasmtimeError("failed to set stdout file")
+
+    def inherit_stdout(self) -> None:
+        """
+        Configures this own process's stdout to be used as the WASI program's
+        stdout.
+
+        Writes to stdout stream will write to this process's stdout.
+        """
+        ffi.wasi_config_inherit_stdout(self._ptr)
+
+    @setter_property
+    def stderr_file(self, path: str) -> None:
+        """
+        Configures a file to be used as the stderr stream of this WASI
+        configuration.
+
+        Writes to stderr will be written to the file specified.
+
+        The file specified will be created if it doesn't exist, or truncated if
+        it already exists. It must be available to open for writing. If it
+        cannot be opened for writing then `WasmtimeError` is raised.
+        """
+        res = ffi.wasi_config_set_stderr_file(
+            self._ptr, c_char_p(_encode_path(path)))
+        if not res:
+            raise WasmtimeError("failed to set stderr file")
+
+    def inherit_stderr(self) -> None:
+        """
+        Configures this own process's stderr to be used as the WASI program's
+        stderr.
+
+        Writes to stderr stream will write to this process's stderr.
+        """
+        ffi.wasi_config_inherit_stderr(self._ptr)
+
+    def preopen_dir(self, path: str, guest_path: str) -> None:
+        path_ptr = c_char_p(path.encode('utf-8'))
+        guest_path_ptr = c_char_p(guest_path.encode('utf-8'))
+        ffi.wasi_config_preopen_dir(self._ptr, path_ptr, guest_path_ptr)
+
+    def __del__(self) -> None:
+        if hasattr(self, '_ptr'):
+            ffi.wasi_config_delete(self._ptr)
+
+

Instance variables

+
+
var argv
+
+

Explicitly configure the argv for this WASI configuration

+

Note that this field can only be set, it cannot be read

+
+
var env
+
+

Configure environment variables to be returned for this WASI +configuration.

+

The pairs provided must be an iterable list of key/value pairs of +environment variables.

+

Note that this field can only be set, it cannot be read

+
+
var stderr_file
+
+

Configures a file to be used as the stderr stream of this WASI +configuration.

+

Writes to stderr will be written to the file specified.

+

The file specified will be created if it doesn't exist, or truncated if +it already exists. It must be available to open for writing. If it +cannot be opened for writing then WasmtimeError is raised.

+

Note that this field can only be set, it cannot be read

+
+
var stdin_file
+
+

Configures a file to be used as the stdin stream of this WASI +configuration.

+

Reads of the stdin stream will read the path specified.

+

The file must already exist on the filesystem. If it cannot be +opened then WasmtimeError is raised.

+

Note that this field can only be set, it cannot be read

+
+
var stdout_file
+
+

Configures a file to be used as the stdout stream of this WASI +configuration.

+

Writes to stdout will be written to the file specified.

+

The file specified will be created if it doesn't exist, or truncated if +it already exists. It must be available to open for writing. If it +cannot be opened for writing then WasmtimeError is raised.

+

Note that this field can only be set, it cannot be read

+
+
+

Methods

+
+
+def inherit_argv(self) ‑> None +
+
+
+
+ +Expand source code + +
def inherit_argv(self) -> None:
+    ffi.wasi_config_inherit_argv(self._ptr)
+
+
+
+def inherit_env(self) ‑> None +
+
+

Configures the environment variables available within WASI to be those +in this own process's environment. All environment variables are +inherited.

+
+ +Expand source code + +
def inherit_env(self) -> None:
+    """
+    Configures the environment variables available within WASI to be those
+    in this own process's environment. All environment variables are
+    inherited.
+    """
+    ffi.wasi_config_inherit_env(self._ptr)
+
+
+
+def inherit_stderr(self) ‑> None +
+
+

Configures this own process's stderr to be used as the WASI program's +stderr.

+

Writes to stderr stream will write to this process's stderr.

+
+ +Expand source code + +
def inherit_stderr(self) -> None:
+    """
+    Configures this own process's stderr to be used as the WASI program's
+    stderr.
+
+    Writes to stderr stream will write to this process's stderr.
+    """
+    ffi.wasi_config_inherit_stderr(self._ptr)
+
+
+
+def inherit_stdin(self) ‑> None +
+
+

Configures this own process's stdin to be used as the WASI program's +stdin.

+

Reads of the stdin stream will read this process's stdin.

+
+ +Expand source code + +
def inherit_stdin(self) -> None:
+    """
+    Configures this own process's stdin to be used as the WASI program's
+    stdin.
+
+    Reads of the stdin stream will read this process's stdin.
+    """
+    ffi.wasi_config_inherit_stdin(self._ptr)
+
+
+
+def inherit_stdout(self) ‑> None +
+
+

Configures this own process's stdout to be used as the WASI program's +stdout.

+

Writes to stdout stream will write to this process's stdout.

+
+ +Expand source code + +
def inherit_stdout(self) -> None:
+    """
+    Configures this own process's stdout to be used as the WASI program's
+    stdout.
+
+    Writes to stdout stream will write to this process's stdout.
+    """
+    ffi.wasi_config_inherit_stdout(self._ptr)
+
+
+
+def preopen_dir(self, path: str, guest_path: str) ‑> None +
+
+
+
+ +Expand source code + +
def preopen_dir(self, path: str, guest_path: str) -> None:
+    path_ptr = c_char_p(path.encode('utf-8'))
+    guest_path_ptr = c_char_p(guest_path.encode('utf-8'))
+    ffi.wasi_config_preopen_dir(self._ptr, path_ptr, guest_path_ptr)
+
+
+
+
+
+class WasmtimeError +(message: str) +
+
+

Common base class for all non-exit exceptions.

+
+ +Expand source code + +
class WasmtimeError(Exception):
+    _ptr: "Optional[ctypes._Pointer[ffi.wasmtime_error_t]]"
+    _message: Optional[str]
+
+    def __init__(self, message: str):
+        self._message = message
+        self._ptr = None
+
+    @classmethod
+    def _from_ptr(cls, ptr: "ctypes._Pointer") -> 'WasmtimeError':
+        from . import _ffi as ffi
+        if not isinstance(ptr, POINTER(ffi.wasmtime_error_t)):
+            raise TypeError("wrong pointer type")
+
+        exit_code = c_int(0)
+        if ffi.wasmtime_error_exit_status(ptr, byref(exit_code)):
+            exit_trap: ExitTrap = ExitTrap.__new__(ExitTrap)
+            exit_trap._ptr = ptr
+            exit_trap._message = None
+            exit_trap.code = exit_code.value
+            return exit_trap
+
+        err: WasmtimeError = cls.__new__(cls)
+        err._ptr = ptr
+        err._message = None
+        return err
+
+    def __str__(self) -> str:
+        if self._message:
+            return self._message
+        message_vec = ffi.wasm_byte_vec_t()
+        ffi.wasmtime_error_message(self._ptr, byref(message_vec))
+        message = ffi.to_str(message_vec)
+        ffi.wasm_byte_vec_delete(byref(message_vec))
+        return message
+
+    def __del__(self) -> None:
+        if hasattr(self, '_ptr') and self._ptr:
+            ffi.wasmtime_error_delete(self._ptr)
+
+

Ancestors

+
    +
  • builtins.Exception
  • +
  • builtins.BaseException
  • +
+

Subclasses

+
    +
  • wasmtime._error.ExitTrap
  • +
+
+
+
+
+ +
+ + + \ No newline at end of file diff --git a/loader.html b/loader.html new file mode 100644 index 00000000..a36a3339 --- /dev/null +++ b/loader.html @@ -0,0 +1,158 @@ + + + + + + +wasmtime.loader API documentation + + + + + + + + + + + +
+
+
+

Module wasmtime.loader

+
+
+

This module is a custom loader for Python which enables importing wasm files +directly into Python programs simply through usage of the import statement.

+

You can import this module with import wasmtime.loader and then afterwards you +can import your_wasm_file which will automatically compile and instantiate +your_wasm_file.wasm and hook it up into Python's module system.

+
+ +Expand source code + +
"""
+This module is a custom loader for Python which enables importing wasm files
+directly into Python programs simply through usage of the `import` statement.
+
+You can import this module with `import wasmtime.loader` and then afterwards you
+can `import your_wasm_file` which will automatically compile and instantiate
+`your_wasm_file.wasm` and hook it up into Python's module system.
+"""
+
+from wasmtime import Module, Linker, Store, WasiConfig
+from wasmtime import Func, Table, Global, Memory
+import sys
+from pathlib import Path
+import importlib
+
+from importlib.abc import Loader, MetaPathFinder
+from importlib.util import spec_from_file_location
+
+predefined_modules = []
+store = Store()
+linker = Linker(store.engine)
+# TODO: how to configure wasi?
+store.set_wasi(WasiConfig())
+predefined_modules.append("wasi_snapshot_preview1")
+predefined_modules.append("wasi_unstable")
+linker.define_wasi()
+linker.allow_shadowing = True
+
+# Mostly copied from
+# https://stackoverflow.com/questions/43571737/how-to-implement-an-import-hook-that-can-modify-the-source-code-on-the-fly-using
+
+
+class _WasmtimeMetaFinder(MetaPathFinder):
+    def find_spec(self, fullname, path, target=None):  # type: ignore
+        if path is None or path == "":
+            path = [Path.cwd()]  # top level import --
+            path.extend(sys.path)
+        if "." in fullname:
+            *parents, name = fullname.split(".")
+        else:
+            name = fullname
+        for entry in path:
+            entry = Path(entry)
+            py = entry / (name + ".py")
+            if py.exists():
+                continue
+            wasm = entry / (name + ".wasm")
+            if wasm.exists():
+                return spec_from_file_location(fullname, wasm, loader=_WasmtimeLoader(wasm))
+            wat = entry / (name + ".wat")
+            if wat.exists():
+                return spec_from_file_location(fullname, wat, loader=_WasmtimeLoader(wat))
+
+        return None
+
+
+class _WasmtimeLoader(Loader):
+    def __init__(self, filename: str):
+        self.filename = filename
+
+    def create_module(self, spec):  # type: ignore
+        return None  # use default module creation semantics
+
+    def exec_module(self, module):  # type: ignore
+        wasm_module = Module.from_file(store.engine, self.filename)
+
+        for wasm_import in wasm_module.imports:
+            module_name = wasm_import.module
+            # skip modules predefined in library
+            if module_name in predefined_modules:
+                break
+            field_name = wasm_import.name
+            imported_module = importlib.import_module(module_name)
+            item = imported_module.__dict__[field_name]
+            if not isinstance(item, Func) and \
+                    not isinstance(item, Table) and \
+                    not isinstance(item, Global) and \
+                    not isinstance(item, Memory):
+                item = Func(store, wasm_import.type, item)
+            linker.define(store, module_name, field_name, item)
+
+        res = linker.instantiate(store, wasm_module)
+        exports = res.exports(store)
+        for i, export in enumerate(wasm_module.exports):
+            item = exports.by_index[i]
+            # Calling a function requires a `Store`, so bind the first argument
+            # to our loader's store
+            if isinstance(item, Func):
+                func = item
+                item = lambda *args,func=func: func(store, *args)  # noqa
+            module.__dict__[export.name] = item
+
+
+sys.meta_path.insert(0, _WasmtimeMetaFinder())
+
+
+
+
+
+
+
+
+
+
+
+ +
+ + + \ No newline at end of file