Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Macros] Add support for wasm macros #73031

Open
wants to merge 111 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
111 commits
Select commit Hold shift + click to select a range
e5c191d
wip
kabiroberai Apr 15, 2024
e5342e7
wip
kabiroberai Apr 15, 2024
d5d1cb7
wip
kabiroberai Apr 15, 2024
f776c28
revert swift-plugin-server
kabiroberai Apr 15, 2024
43fc233
use jsc in-proc
kabiroberai Apr 15, 2024
961fd54
Allow wasm in sandbox, don’t disable it
kabiroberai Apr 15, 2024
a771631
fix warning, prune version check
kabiroberai Apr 15, 2024
3f8ef81
Factor out JSCWasmPlugin
kabiroberai Apr 15, 2024
23426e0
the continuation just... works now?
kabiroberai Apr 15, 2024
9fe505f
more tweaks to JSCWasmPlugin
kabiroberai Apr 15, 2024
89158e2
Create SwiftPluginServerSupport
kabiroberai Apr 15, 2024
f084e25
JSCWasmPlugin: memoize, improve errors
kabiroberai Apr 15, 2024
5ef86da
steps towards x-plat
kabiroberai Apr 15, 2024
02f4324
more modularity
kabiroberai Apr 15, 2024
bddde66
Add wasm-plugin-server-path frontend opt
kabiroberai Apr 16, 2024
ca22e2d
Start adding WasmKit support
kabiroberai Apr 16, 2024
6a9bbe7
Update WasmKitPlugin
kabiroberai Apr 16, 2024
e598064
safety, tweaks
kabiroberai Apr 16, 2024
7d1510e
tweaks to JSC
kabiroberai Apr 16, 2024
37b8a61
Merge remote-tracking branch 'upstream/main' into kabir/wasm-plugins
kabiroberai Apr 17, 2024
da74f38
Proper WasmKit integration
kabiroberai Apr 22, 2024
7a18da2
tweaks
kabiroberai Apr 22, 2024
1076b16
Check ABI version
kabiroberai Apr 22, 2024
805c659
Merge remote-tracking branch 'upstream/main' into kabir/wasm-plugins
kabiroberai Apr 22, 2024
4527842
move ABI check into WasmEnginePlugin
kabiroberai Apr 22, 2024
f9dbbb1
build fixes
kabiroberai Apr 22, 2024
6511672
Elide copies of wasm blob
kabiroberai Apr 22, 2024
dd481fe
fix duplicate libraries warning
kabiroberai Apr 23, 2024
4ce4749
Merge remote-tracking branch 'upstream/main' into kabir/wasm-plugins
kabiroberai Apr 23, 2024
482871c
add SWIFT_WASM_USE_JSC
kabiroberai Apr 23, 2024
771acb0
Merge remote-tracking branch 'upstream/main' into kabir/wasm-plugins
kabiroberai Apr 23, 2024
2460e98
Skip wasmkit CLI for now
kabiroberai Apr 24, 2024
150f3d2
Or actually build wasmkit-cli
kabiroberai Apr 24, 2024
34ed5b0
use stdio for ipc
kabiroberai Apr 24, 2024
94d525e
No need for memory witness
kabiroberai Apr 24, 2024
a99f6b3
Byte-swap length if needed
kabiroberai Apr 24, 2024
c5dc6bd
Improve error handling
kabiroberai Apr 24, 2024
6375faf
Merge branch 'main' into kabir/wasm-plugins
kabiroberai Apr 30, 2024
826a80f
Fix linkage
kabiroberai Apr 30, 2024
f053859
No C dep needed for wasm
kabiroberai Apr 30, 2024
6c0b40c
Drop foundation (mostly); lower min os
kabiroberai Apr 30, 2024
d72e165
More foundation pruning
kabiroberai Apr 30, 2024
564f844
interop mode cxx -> c
kabiroberai Apr 30, 2024
a670f32
Target
kabiroberai Apr 30, 2024
aaaaae3
tweaks
kabiroberai Apr 30, 2024
7b16cbd
We don’t need WasmKitPluginError
kabiroberai Apr 30, 2024
7d9d015
Change wasm versioning approach
kabiroberai May 5, 2024
ea81405
Merge branch 'main' into kabir/wasm-plugins
kabiroberai May 5, 2024
b472f4f
Merge branch 'main' into kabir/wasm-plugins
kabiroberai May 11, 2024
3baf627
Merge branch 'main' into kabir/wasm-plugins
kabiroberai May 25, 2024
eee48e0
swift-wasm-plugin-server => swift-plugin-server
kabiroberai May 25, 2024
4fca102
swift-plugin-server doesn’t need a product
kabiroberai May 25, 2024
d465d36
We don’t need Dispatch here
kabiroberai May 25, 2024
c4efcee
Improve diagnostics
kabiroberai May 25, 2024
b3f53c2
Remove JSC for now
kabiroberai May 25, 2024
b629484
Explicitly depend on System
kabiroberai May 26, 2024
af2b87e
Nevermind SwiftPM didn’t like that
kabiroberai May 26, 2024
bbb916c
Lower swift-tools-version
kabiroberai May 26, 2024
77c273f
Fix WASI dep
kabiroberai May 26, 2024
b56e28a
Add missing header
kabiroberai May 26, 2024
94f0ad7
Merge branch 'main' into kabir/wasm-plugins
kabiroberai May 26, 2024
14b5b79
Include position in diagnostics if possible
kabiroberai May 26, 2024
af68825
Merge branch 'main' into kabir/wasm-plugins
kabiroberai May 26, 2024
92aef4e
this comment is now stale
kabiroberai May 26, 2024
9b1e4ee
No wasm_plugin_server_path
kabiroberai May 26, 2024
f93df4d
Remove debug code
kabiroberai May 26, 2024
95f254c
error_load_plugin diagnostic
kabiroberai May 26, 2024
ca27b45
Merge branch 'main' into kabir/wasm-plugins
kabiroberai May 26, 2024
caa1a8c
Elide copy
kabiroberai May 26, 2024
2ee417f
Merge branch 'main' into kabir/wasm-plugins
kabiroberai Jun 12, 2024
fa52ecd
Feedback
kabiroberai Jun 12, 2024
f2f2ea2
nit
kabiroberai Jun 12, 2024
c0a75e1
record ServerPath
kabiroberai Jun 12, 2024
011a0a5
Basic test
kabiroberai Jun 12, 2024
d2d3b94
Parameterize
kabiroberai Jun 12, 2024
e2a455a
Merge branch 'main' into kabir/wasm-plugins
kabiroberai Jun 29, 2024
b307eb4
Fix deprecation warning
kabiroberai Jun 29, 2024
782956a
working test
kabiroberai Jun 30, 2024
8a88dc5
simplify
kabiroberai Jun 30, 2024
fcb838d
remove wasm_sdk_root
kabiroberai Jun 30, 2024
469d84a
error tests
kabiroberai Jun 30, 2024
cc41cf1
Update WasmKit to 0.0.5
kateinoigakukun Jul 1, 2024
7499295
Merge branch 'main' into kabir/wasm-plugins
kabiroberai Jul 14, 2024
e89fd6a
post-merge fixup
kabiroberai Jul 14, 2024
2b47724
no opaque types
kabiroberai Jul 14, 2024
4285cf1
tentative fix for lldb build
kabiroberai Jul 14, 2024
56b6cae
don’t depend on ArgumentParser
kabiroberai Jul 14, 2024
96363e1
temporarily update wasmkit checkout
kabiroberai Jul 14, 2024
913041b
Revert "temporarily update wasmkit checkout"
kateinoigakukun Jul 15, 2024
6cd389e
Update WasmKit to 0.0.6
kateinoigakukun Jul 15, 2024
c3f4276
[test] Annotate macro tests that require the WebAssembly code generator
kateinoigakukun Jul 15, 2024
4341058
Update WasmKit to 0.0.7
kateinoigakukun Jul 21, 2024
393933a
Add temporary workaround for Windows pipe support of swift-system
kateinoigakukun Jul 22, 2024
9c5e7fc
[test] Remove usage of unused lit variables for building wasm plugins
kateinoigakukun Jul 22, 2024
5890c3e
Change the first `-load-plugin` path separator from `:` to `#`
kateinoigakukun Jul 23, 2024
0f39ec8
[test] Fix path segment separator of plugin path for Windows
kateinoigakukun Jul 23, 2024
48dd97f
Merge branch 'main' into kabir/wasm-plugins
MaxDesiatov Aug 20, 2024
c3f41c7
Merge branch 'main' into kabir/wasm-plugins
MaxDesiatov Aug 21, 2024
ee82b85
Merge branch 'main' of github.com:apple/swift into kabir/wasm-plugins
MaxDesiatov Aug 23, 2024
1dcdd7b
Merge branch 'main' of github.com:apple/swift into kabir/wasm-plugins
MaxDesiatov Aug 27, 2024
6e56934
Attempt to use `main` branch of WasmKit
MaxDesiatov Aug 27, 2024
dd13597
Merge branch 'main' into kabir/wasm-plugins
kabiroberai Sep 21, 2024
5770553
Revert wasmkit bump
kabiroberai Sep 21, 2024
94f870c
Merge branch 'main' into kabir/wasm-plugins
MaxDesiatov Oct 10, 2024
ed54400
Bump WasmKit to 0.1.0 in `update-checkout-config.json`
MaxDesiatov Oct 10, 2024
d568d67
Update for WasmKit 0.1.0 API
MaxDesiatov Oct 10, 2024
75bd7ca
Fix missing imports in `WasmKitEngine.swift`
MaxDesiatov Oct 11, 2024
c1e928d
Bump wasmkit to 0.1.1 to enable WMO
kateinoigakukun Oct 13, 2024
0d2c140
Merge remote-tracking branch 'origin/main' into kabir/wasm-plugins
kateinoigakukun Oct 13, 2024
7683e83
Bump WasmKit to 0.1.2 in `update-checkout-config.json`
MaxDesiatov Oct 21, 2024
e0427b2
Bump stack size in `WasmKitEngine.swift` to avoid OOB
MaxDesiatov Oct 21, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions include/swift/AST/DiagnosticsFrontend.def
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,9 @@ ERROR(error_no_source_location_scope_map,none,
ERROR(error_load_plugin_executable,none,
"invalid value '%0' in '-load-plugin-executable'; "
"make sure to use format '<plugin path>#<module names>'", (StringRef))
ERROR(error_load_plugin,none,
"invalid value '%0' in '-load-plugin'; "
"make sure to use format '<library path>#<server path>#<module names>'", (StringRef))

NOTE(note_valid_swift_versions, none,
"valid arguments to '-swift-version' are %0", (StringRef))
Expand Down
13 changes: 12 additions & 1 deletion include/swift/AST/SearchPathOptions.h
Original file line number Diff line number Diff line change
Expand Up @@ -214,17 +214,23 @@ class PluginSearchOption {
std::string SearchPath;
std::string ServerPath;
};
struct LoadPlugin {
std::string LibraryPath;
std::string ServerPath;
std::vector<std::string> ModuleNames;
};

enum class Kind : uint8_t {
LoadPluginLibrary,
LoadPluginExecutable,
PluginPath,
ExternalPluginPath,
LoadPlugin,
};

private:
using Members = ExternalUnionMembers<LoadPluginLibrary, LoadPluginExecutable,
PluginPath, ExternalPluginPath>;
PluginPath, ExternalPluginPath, LoadPlugin>;
static Members::Index getIndexForKind(Kind kind) {
switch (kind) {
case Kind::LoadPluginLibrary:
Expand All @@ -235,6 +241,8 @@ class PluginSearchOption {
return Members::indexOf<PluginPath>();
case Kind::ExternalPluginPath:
return Members::indexOf<ExternalPluginPath>();
case Kind::LoadPlugin:
return Members::indexOf<LoadPlugin>();
}
};
using Storage = ExternalUnion<Kind, Members, getIndexForKind>;
Expand All @@ -258,6 +266,9 @@ class PluginSearchOption {
: kind(Kind::ExternalPluginPath) {
storage.emplace<ExternalPluginPath>(kind, v);
}
PluginSearchOption(const LoadPlugin &v) : kind(Kind::LoadPlugin) {
storage.emplace<LoadPlugin>(kind, v);
}
PluginSearchOption(const PluginSearchOption &o) : kind(o.kind) {
storage.copyConstruct(o.kind, o.storage);
}
Expand Down
7 changes: 7 additions & 0 deletions include/swift/Option/Options.td
Original file line number Diff line number Diff line change
Expand Up @@ -2071,6 +2071,13 @@ def in_process_plugin_server_path : Separate<["-"], "in-process-plugin-server-pa
Flags<[FrontendOption, ArgumentIsPath]>,
HelpText<"Path to dynamic library plugin server">;

def load_plugin:
Separate<["-"], "load-plugin">, Group<plugin_search_Group>,
Flags<[FrontendOption, DoesNotAffectIncrementalBuild]>,
HelpText<"Path to a plugin library, a server to load it in, and a comma-separated "
"list of module names where the macro types are declared">,
MetaVarName<"<library-path>#<server-path>#<module-names>">;

def disable_sandbox:
Flag<["-"], "disable-sandbox">,
Flags<[FrontendOption, DoesNotAffectIncrementalBuild]>,
Expand Down
8 changes: 8 additions & 0 deletions lib/AST/PluginLoader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,14 @@ PluginLoader::getPluginMap() {
continue;
}

case PluginSearchOption::Kind::LoadPlugin: {
auto &val = entry.get<PluginSearchOption::LoadPlugin>();
for (auto &moduleName : val.ModuleNames) {
try_emplace(moduleName, val.LibraryPath, val.ServerPath);
}
continue;
}

// '-plugin-path <library search path>'.
case PluginSearchOption::Kind::PluginPath: {
auto &val = entry.get<PluginSearchOption::PluginPath>();
Expand Down
4 changes: 2 additions & 2 deletions lib/Basic/Sandbox.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ static StringRef sandboxProfile(llvm::BumpPtrAllocator &Alloc) {
// Allow reading file metadata of any files.
contents += "(allow file-read-metadata)\n";

// Allow reading dylibs.
contents += "(allow file-read* (regex #\"\\.dylib$\"))\n";
// Allow reading dylibs and WebAssembly macros.
contents += "(allow file-read* (regex #\"\\.(dylib|wasm)$\"))\n";

// This is required to launch any processes (execve(2)).
contents += "(allow process-exec*)\n";
Expand Down
24 changes: 24 additions & 0 deletions lib/Frontend/CompilerInvocation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2154,6 +2154,30 @@ static bool ParseSearchPathArgs(SearchPathOptions &Opts, ArgList &Args,
}
break;
}
case OPT_load_plugin: {
// '<path to library>#<path to server>#<module names>' where the module names are
// comma separated.
StringRef pathAndServer;
StringRef modulesStr;
std::tie(pathAndServer, modulesStr) = StringRef(A->getValue()).rsplit('#');
StringRef path;
StringRef server;
std::tie(path, server) = pathAndServer.rsplit('#');
std::vector<std::string> moduleNames;
for (auto name : llvm::split(modulesStr, ',')) {
moduleNames.emplace_back(name);
}
if (path.empty() || server.empty() || moduleNames.empty()) {
Diags.diagnose(SourceLoc(), diag::error_load_plugin,
A->getValue());
} else {
Opts.PluginSearchOpts.emplace_back(
PluginSearchOption::LoadPlugin{resolveSearchPath(path),
resolveSearchPath(server),
std::move(moduleNames)});
}
break;
}
case OPT_plugin_path: {
Opts.PluginSearchOpts.emplace_back(
PluginSearchOption::PluginPath{resolveSearchPath(A->getValue())});
Expand Down
9 changes: 9 additions & 0 deletions lib/Frontend/ModuleInterfaceLoader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1728,6 +1728,15 @@ void InterfaceSubContextDelegateImpl::inheritOptionsForBuildingInterface(
}
break;
}
case PluginSearchOption::Kind::LoadPlugin: {
auto &val = entry.get<PluginSearchOption::LoadPlugin>();
for (auto &moduleName : val.ModuleNames) {
GenericArgs.push_back("-load-plugin");
GenericArgs.push_back(
ArgSaver.save(val.LibraryPath + "#" + val.ServerPath + "#" + moduleName));
}
break;
}
case PluginSearchOption::Kind::PluginPath: {
auto &val = entry.get<PluginSearchOption::PluginPath>();
GenericArgs.push_back("-plugin-path");
Expand Down
3 changes: 3 additions & 0 deletions lib/Serialization/ModuleFileSharedCore.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,9 @@ static bool readOptionsBlock(llvm::BitstreamCursor &cursor,
case PluginSearchOptionKind::LoadPluginExecutable:
optKind = PluginSearchOption::Kind::LoadPluginExecutable;
break;
case PluginSearchOptionKind::LoadPlugin:
optKind = PluginSearchOption::Kind::LoadPlugin;
break;
}
extendedInfo.addPluginSearchOption({optKind, blobData});
break;
Expand Down
3 changes: 2 additions & 1 deletion lib/Serialization/ModuleFormat.h
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ const uint16_t SWIFTMODULE_VERSION_MAJOR = 0;
/// describe what change you made. The content of this comment isn't important;
/// it just ensures a conflict if two people change the module format.
/// Don't worry about adhering to the 80-column limit for this line.
const uint16_t SWIFTMODULE_VERSION_MINOR = 896; // @yield_once_2 produces address
const uint16_t SWIFTMODULE_VERSION_MINOR = 897; // Add PluginSearchOptionKind::LoadPlugin

/// A standard hash seed used for all string hashes in a serialized module.
///
Expand Down Expand Up @@ -694,6 +694,7 @@ enum class PluginSearchOptionKind : uint8_t {
ExternalPluginPath,
LoadPluginLibrary,
LoadPluginExecutable,
LoadPlugin,
};
using PluginSearchOptionKindField = BCFixed<3>;

Expand Down
11 changes: 11 additions & 0 deletions lib/Serialization/Serialization.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1237,6 +1237,17 @@ void Serializer::writeHeader() {
uint8_t(PluginSearchOptionKind::LoadPluginExecutable), optStr);
continue;
}
case PluginSearchOption::Kind::LoadPlugin: {
auto &opt = elem.get<PluginSearchOption::LoadPlugin>();
std::string optStr = opt.LibraryPath + "#" + opt.ServerPath + "#";
llvm::interleave(
opt.ModuleNames, [&](auto &name) { optStr += name; },
[&]() { optStr += ","; });
PluginSearchOpt.emit(
ScratchRecord,
uint8_t(PluginSearchOptionKind::LoadPlugin), optStr);
continue;
}
}
}
}
Expand Down
55 changes: 55 additions & 0 deletions test/Macros/Inputs/wasi_shim.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// definitions from
// https://github.com/WebAssembly/wasi-libc/blob/320bbbcced68ce8e564b0dc4c8f80a5a5ad21a9c/libc-bottom-half/headers/public/wasi/api.h

typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
typedef unsigned long long uint64_t;

typedef uint8_t wasi_signal_t;
typedef uint16_t wasi_errno_t;
typedef uint32_t wasi_exitcode_t;
typedef int wasi_fd_t;
typedef __SIZE_TYPE__ wasi_size_t;

typedef struct wasi_ciovec_t {
const uint8_t *buf;
wasi_size_t buf_len;
} wasi_ciovec_t;

wasi_errno_t wasi_fd_write(
wasi_fd_t fd,
const wasi_ciovec_t *iovs,
wasi_size_t iovs_len,
wasi_size_t *nwritten
) __attribute__((
__import_module__("wasi_snapshot_preview1"),
__import_name__("fd_write"),
__warn_unused_result__
));

_Noreturn void wasi_proc_exit(
wasi_exitcode_t code
) __attribute__((
__import_module__("wasi_snapshot_preview1"),
__import_name__("proc_exit")
));

// libc shims

static inline wasi_size_t swift_strlen(const char *buf) {
wasi_size_t len = 0;
while (buf[len]) len++;
return len;
}

static inline wasi_errno_t swift_write(int fd, const void *buf, wasi_size_t len) {
struct wasi_ciovec_t vec = { .buf = (const uint8_t *)buf, .buf_len = len };
wasi_size_t nwritten = 0;
return wasi_fd_write(fd, &vec, 1, &nwritten);
}

_Noreturn static inline void swift_abort(const char *message) {
swift_write(2, message, swift_strlen(message));
wasi_proc_exit(1);
}
8 changes: 8 additions & 0 deletions test/Macros/lit.local.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,11 @@ else:
)
config.substitutions.append(('%c-flags', config.c_flags))
config.substitutions.append(('%exe-linker-flags', config.exe_linker_flags))

config.substitutions.insert(
0,
(
'%swift-build-wasm-c-plugin',
f'{config.clang} -target wasm32 -nostdlib -iquote %S'
)
)
60 changes: 60 additions & 0 deletions test/Macros/macro_plugin_wasm.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// REQUIRES: swift_swift_parser
// REQUIRES: CODEGENERATOR=WebAssembly

// RUN: %empty-directory(%t)

// RUN: split-file %s %t

//#-- Prepare the Wasm macro plugin.
// RUN: %swift-build-wasm-c-plugin %t/MacroDefinition.c -o %t/Plugin.wasm

// RUN: env SWIFT_DUMP_PLUGIN_MESSAGING=1 %target-swift-frontend \
// RUN: -typecheck \
// RUN: -swift-version 5 \
// RUN: -load-plugin %t/Plugin.wasm#%swift-plugin-server#MacroDefinition \
// RUN: -Rmacro-loading \
// RUN: -module-name MyApp \
// RUN: %t/test.swift \
// RUN: > %t/macro-loading.txt 2>&1

// RUN: %FileCheck %s < %t/macro-loading.txt

// CHECK: ->(plugin:[[#PID:]]) {"getCapability":{"capability":{"protocolVersion":[[#PROTOCOL_VERSION:]]}}}
// CHECK: <-(plugin:[[#PID]]) {"getCapabilityResult":{"capability":{"features":["load-plugin-library"],"protocolVersion":7}}}
// CHECK: ->(plugin:[[#PID]]) {"loadPluginLibrary":{"libraryPath":"{{.*[\\/]}}Plugin.wasm","moduleName":"MacroDefinition"}}
// CHECK: <-(plugin:[[#PID]]) {"loadPluginLibraryResult":{"diagnostics":[],"loaded":true}}
// CHECK: ->(plugin:[[#PID]]) {"expandFreestandingMacro":{"discriminator":"$s{{.+}}","lexicalContext":[{{.*}}],"macro":{"moduleName":"MacroDefinition","name":"constInt","typeName":"ConstMacro"},"macroRole":"expression","syntax":{"kind":"expression","location":{"column":16,"fileID":"MyApp/test.swift","fileName":"{{.+}}test.swift","line":4,"offset":143},"source":"#constInt"}}}
// CHECK: <-(plugin:[[#PID]]) {"expandMacroResult":{"diagnostics":[],"expandedSource":"1"}}

//--- test.swift
@freestanding(expression) macro constInt() -> Int = #externalMacro(module: "MacroDefinition", type: "ConstMacro")

func foo() {
let _: Int = #constInt
}

//--- MacroDefinition.c
#include "Inputs/wasi_shim.h"

static void write_json(const char *json) {
wasi_size_t len = swift_strlen(json);
uint64_t len64 = (uint64_t)len;
swift_write(1, &len64, sizeof(len64));
swift_write(1, json, len);
}

int was_start_called = 0;
int pump_calls = 0;

__attribute__((export_name("_start")))
void _start(void) {
if (was_start_called) swift_abort("_start called twice!");
was_start_called = 1;
}

__attribute__((export_name("swift_wasm_macro_v1_pump")))
void pump(void) {
if (!was_start_called) swift_abort("_start not called!");
if (pump_calls++ != 0) swift_abort("expected pump to be called once");
write_json("{\"expandMacroResult\": {\"expandedSource\": \"1\", \"diagnostics\": []}}");
}
33 changes: 33 additions & 0 deletions test/Macros/macro_plugin_wasm_badversion.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// REQUIRES: swift_swift_parser
// REQUIRES: CODEGENERATOR=WebAssembly

// RUN: %empty-directory(%t)

// RUN: split-file %s %t

//#-- Prepare the Wasm macro plugin.
// RUN: %swift-build-wasm-c-plugin %t/MacroDefinition.c -o %t/Plugin.wasm

// RUN: %target-swift-frontend \
// RUN: -typecheck -verify \
// RUN: -swift-version 5 \
// RUN: -load-plugin %t/Plugin.wasm#%swift-plugin-server#MacroDefinition \
// RUN: -module-name MyApp \
// RUN: %t/test.swift

//--- test.swift
// expected-warning @+2 {{Wasm plugin has an unknown ABI (could not find 'swift_wasm_macro_v1_pump')}}
// expected-note @+1 {{declared here}}
@freestanding(expression) macro constInt() -> Int = #externalMacro(module: "MacroDefinition", type: "ConstMacro")

func foo() {
// expected-error @+1 {{Wasm plugin has an unknown ABI (could not find 'swift_wasm_macro_v1_pump')}}
let _: Int = #constInt
}

//--- MacroDefinition.c
__attribute__((export_name("_start")))
void _start(void) {}

__attribute__((export_name("swift_wasm_macro_v100_pump")))
void pump(void) {}
40 changes: 40 additions & 0 deletions test/Macros/macro_plugin_wasm_guest_error.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// REQUIRES: swift_swift_parser
// REQUIRES: CODEGENERATOR=WebAssembly

// RUN: %empty-directory(%t)

// RUN: split-file %s %t

//#-- Prepare the Wasm macro plugin.
// RUN: %swift-build-wasm-c-plugin %t/MacroDefinition.c -o %t/Plugin.wasm

// RUN: %target-swift-frontend \
// RUN: -typecheck -verify \
// RUN: -swift-version 5 \
// RUN: -load-plugin %t/Plugin.wasm#%swift-plugin-server#MacroDefinition \
// RUN: -module-name MyApp \
// RUN: %t/test.swift \
// RUN: 2>%t/macro-loading.txt

// RUN: %FileCheck %s < %t/macro-loading.txt

// CHECK: guest error!

//--- test.swift
@freestanding(expression) macro constInt() -> Int = #externalMacro(module: "MacroDefinition", type: "ConstMacro")

func foo() {
// expected-error @+1 {{failed to communicate with external macro}}
let _: Int = #constInt
}

//--- MacroDefinition.c
#include "Inputs/wasi_shim.h"

__attribute__((export_name("_start")))
void _start(void) {}

__attribute__((export_name("swift_wasm_macro_v1_pump")))
void pump(void) {
swift_abort("guest error!\n");
}
Loading