File size: 12,365 Bytes
fc8f83a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 | import express, { Request, Response } from 'express';
import cors from 'cors';
import { exec } from 'child_process';
import { promises as fs } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { promisify } from 'util';
const execAsync = promisify(exec);
const app = express();
const PORT = process.env.PORT || 3456;
const EMSDK_PATH = process.env.EMSDK_PATH || `${process.env.HOME}/wasm-toolchains/emsdk`;
const SWIFTWASM_PATH = process.env.SWIFTWASM_PATH || `${process.env.HOME}/wasm-toolchains/swiftwasm`;
app.use(cors());
app.use(express.json({ limit: '5mb' }));
app.use(express.static('public'));
interface CompileRequest {
code: string;
flags?: string;
}
interface Diagnostic {
line?: number;
column?: number;
message: string;
severity: 'error' | 'warning' | 'note';
file?: string;
}
function getEmsdkEnvCommand(): string {
return `source "${EMSDK_PATH}/emsdk_env.sh"`;
}
function getSwiftPath(): string {
return `${SWIFTWASM_PATH}/usr/bin`;
}
async function findCompiler(compilerName: string, extraPaths: string[] = []): Promise<string | null> {
const paths = [...extraPaths, ...(process.env.PATH?.split(':') || [])];
for (const p of paths) {
try {
await fs.access(join(p, compilerName));
return join(p, compilerName);
} catch { /* ignore */ }
}
return null;
}
async function findInPathsOnly(compilerName: string, searchPaths: string[]): Promise<string | null> {
for (const p of searchPaths) {
try {
await fs.access(join(p, compilerName));
return join(p, compilerName);
} catch { /* ignore */ }
}
return null;
}
async function canTargetWasm32(swiftcPath: string): Promise<boolean> {
try {
const testDir = await fs.mkdtemp(join(tmpdir(), 'swift-wasm-test-'));
const testFile = join(testDir, 'test.swift');
await fs.writeFile(testFile, 'print("hello")\n');
await execAsync(`"${swiftcPath}" -target wasm32-unknown-wasi -o "${join(testDir, 'test.wasm')}" "${testFile}"`, { timeout: 15000 });
await fs.rm(testDir, { recursive: true, force: true }).catch(() => { });
return true;
} catch {
return false;
}
}
function parseDiagnostics(stderr: string, lang: 'cpp' | 'swift'): Diagnostic[] {
const diagnostics: Diagnostic[] = [];
if (!stderr) return diagnostics;
const lines = stderr.split('\n');
if (lang === 'cpp') {
// emcc/clang: file.cpp:12:34: error: message
const re = /^(.+?):(\d+):(\d+):\s*(error|warning|note):\s*(.+)$/;
for (const line of lines) {
const m = line.match(re);
if (m) {
diagnostics.push({
file: m[1],
line: parseInt(m[2], 10),
column: parseInt(m[3], 10),
severity: m[4] as Diagnostic['severity'],
message: m[5],
});
}
}
} else {
// swiftc: file.swift:12:34: error: message
const re = /^(.+?):(\d+):(\d+):\s*(error|warning|note):\s*(.+)$/;
for (const line of lines) {
const m = line.match(re);
if (m) {
diagnostics.push({
file: m[1],
line: parseInt(m[2], 10),
column: parseInt(m[3], 10),
severity: m[4] as Diagnostic['severity'],
message: m[5],
});
}
}
}
return diagnostics;
}
function parseWasmExportsImports(wasmBytes: Buffer): { exports: any[]; imports: any[]; memories: any[] } {
const result = { exports: [] as any[], imports: [] as any[], memories: [] as any[] };
let pos = 8; // skip magic + version
while (pos < wasmBytes.length) {
const id = wasmBytes[pos++];
if (id > 11) break;
let len = 0;
let shift = 0;
while (true) {
const b = wasmBytes[pos++];
len |= (b & 0x7f) << shift;
shift += 7;
if ((b & 0x80) === 0) break;
}
const end = pos + len;
if (id === 1) { // Type section - skip
} else if (id === 2) { // Import section
let count = readLeb(wasmBytes, pos);
for (let i = 0; i < count.value; i++) {
const mod = readString(wasmBytes, pos + count.bytes);
const name = readString(wasmBytes, pos + count.bytes + mod.bytes);
const kind = wasmBytes[pos + count.bytes + mod.bytes + name.bytes];
result.imports.push({ module: mod.str, name: name.str, kind });
}
} else if (id === 7) { // Export section
let count = readLeb(wasmBytes, pos);
for (let i = 0; i < count.value; i++) {
const name = readString(wasmBytes, pos + count.bytes);
const kind = wasmBytes[pos + count.bytes + name.bytes];
const idx = readLeb(wasmBytes, pos + count.bytes + name.bytes + 1);
result.exports.push({ name: name.str, kind, index: idx.value });
}
} else if (id === 5) { // Memory section
let count = readLeb(wasmBytes, pos);
for (let i = 0; i < count.value; i++) {
const flags = wasmBytes[pos + count.bytes];
const min = readLeb(wasmBytes, pos + count.bytes + 1);
result.memories.push({ flags, min: min.value });
}
}
pos = end;
}
return result;
}
function readLeb(buf: Buffer, offset: number): { value: number; bytes: number } {
let value = 0, shift = 0, bytes = 0;
while (true) {
const b = buf[offset + bytes++];
value |= (b & 0x7f) << shift;
shift += 7;
if ((b & 0x80) === 0) break;
}
return { value, bytes };
}
function readString(buf: Buffer, offset: number): { str: string; bytes: number } {
const len = readLeb(buf, offset);
const str = buf.slice(offset + len.bytes, offset + len.bytes + len.value).toString('utf8');
return { str, bytes: len.bytes + len.value };
}
// --- EXAMPLES ---
const examples = {
cpp: [
{
name: 'Hello WASM',
code: `#include <emscripten.h>
#include <stdio.h>
int main() {
printf("Hello from C++ WASM!\\n");
return 0;
}
`
},
{
name: 'Exported Functions',
code: `#include <emscripten.h>
extern "C" {
EMSCRIPTEN_KEEPALIVE
int add(int a, int b) {
return a + b;
}
EMSCRIPTEN_KEEPALIVE
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
}
int main() {
return 0;
}
`
},
{
name: 'Memory & Pointer',
code: `#include <emscripten.h>
#include <string.h>
extern "C" {
EMSCRIPTEN_KEEPALIVE
int sumArray(int* arr, int len) {
int sum = 0;
for (int i = 0; i < len; i++) sum += arr[i];
return sum;
}
EMSCRIPTEN_KEEPALIVE
void reverseInPlace(int* arr, int len) {
for (int i = 0; i < len / 2; i++) {
int tmp = arr[i];
arr[i] = arr[len - 1 - i];
arr[len - 1 - i] = tmp;
}
}
}
int main() { return 0; }
`
},
{
name: 'Fibonacci Benchmark',
code: `#include <emscripten.h>
#include <stdio.h>
extern "C" {
EMSCRIPTEN_KEEPALIVE
int fib(int n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
}
int main() {
for (int i = 0; i <= 20; i++) {
printf("fib(%d) = %d\\n", i, fib(i));
}
return 0;
}
`
}
],
swift: [
{
name: 'Hello WASM',
code: `print("Hello from Swift WASM!")
`
},
{
name: 'Exported Functions',
code: `@_cdecl("add")
public func add(a: Int32, b: Int32) -> Int32 {
return a + b
}
@_cdecl("multiply")
public func multiply(a: Int32, b: Int32) -> Int32 {
return a * b
}
`
},
{
name: 'Recursive Factorial',
code: `@_cdecl("factorial")
public func factorial(n: Int32) -> Int32 {
if n <= 1 { return 1 }
return n * factorial(n: n - 1)
}
`
},
{
name: 'Array Sum',
code: `@_cdecl("sumArray")
public func sumArray(ptr: UnsafePointer<Int32>, count: Int32) -> Int32 {
var sum: Int32 = 0
for i in 0..<count {
sum += ptr[Int(i)]
}
return sum
}
`
}
]
};
app.get('/api/examples', (_req: Request, res: Response) => {
res.json(examples);
});
app.get('/api/status', async (_req: Request, res: Response) => {
const emcc = await findCompiler('emcc', [`${EMSDK_PATH}/upstream/emscripten`]);
const swiftc = await findCompiler('swiftc', [getSwiftPath()]);
const swiftWasmCapable = swiftc ? await canTargetWasm32(swiftc) : false;
res.json({
emccAvailable: !!emcc,
emccPath: emcc || null,
swiftcAvailable: swiftWasmCapable,
swiftcPath: swiftWasmCapable ? swiftc : null,
emsdkPath: EMSDK_PATH,
swiftwasmPath: SWIFTWASM_PATH
});
});
app.post('/api/compile/cpp', async (req: Request, res: Response) => {
const { code, flags } = req.body as CompileRequest;
if (!code || typeof code !== 'string') {
res.status(400).json({ success: false, error: 'Missing code field' });
return;
}
const workDir = await fs.mkdtemp(join(tmpdir(), 'cpp-wasm-'));
try {
const emcc = await findInPathsOnly('emcc', [`${EMSDK_PATH}/upstream/emscripten`]);
if (!emcc) {
res.status(503).json({ success: false, error: 'emcc not found. Run: ./scripts/install-toolchains.sh' });
return;
}
await fs.writeFile(join(workDir, 'main.cpp'), code);
const extraFlags = flags ? ` ${flags}` : '';
const cmd = `bash -c '${getEmsdkEnvCommand()} && emcc "${workDir}/main.cpp" -o "${workDir}/main.js" -s EXPORTED_FUNCTIONS="['_main']" -s EXPORTED_RUNTIME_METHODS="['ccall','cwrap','UTF8ToString']" -s ALLOW_MEMORY_GROWTH=1 -s INITIAL_MEMORY=16MB -s STACK_SIZE=1MB -s SINGLE_FILE=1 -O2${extraFlags}'`;
const { stdout, stderr } = await execAsync(cmd, {
timeout: 60000,
env: { ...process.env, HOME: process.env.HOME || '' }
});
const jsFile = await fs.readFile(join(workDir, 'main.js'), 'utf-8');
const diagnostics = parseDiagnostics(stderr, 'cpp');
res.json({
success: true,
js: jsFile,
stdout,
stderr,
diagnostics
});
} catch (err: any) {
const diagnostics = parseDiagnostics(err.stderr || '', 'cpp');
res.json({
success: false,
error: err.stderr || err.message,
stdout: err.stdout || '',
diagnostics
});
} finally {
await fs.rm(workDir, { recursive: true, force: true }).catch(() => { });
}
});
app.post('/api/compile/swift', async (req: Request, res: Response) => {
const { code, flags } = req.body as CompileRequest;
if (!code || typeof code !== 'string') {
res.status(400).json({ success: false, error: 'Missing code field' });
return;
}
const workDir = await fs.mkdtemp(join(tmpdir(), 'swift-wasm-'));
try {
const swiftc = await findInPathsOnly('swiftc', [getSwiftPath()]);
if (!swiftc) {
res.status(503).json({ success: false, error: 'swiftc (SwiftWasm) not found. Run: ./scripts/install-toolchains.sh' });
return;
}
await fs.writeFile(join(workDir, 'main.swift'), code);
const extraFlags = flags ? ` ${flags}` : '';
const cmd = `PATH="${getSwiftPath()}:$PATH" swiftc -target wasm32-unknown-wasi -o "${workDir}/main.wasm" "${workDir}/main.swift"${extraFlags}`;
const { stdout, stderr } = await execAsync(cmd, {
timeout: 60000,
env: { ...process.env, HOME: process.env.HOME || '' }
});
const wasmBytes = await fs.readFile(join(workDir, 'main.wasm'));
const wasmInfo = parseWasmExportsImports(wasmBytes);
const diagnostics = parseDiagnostics(stderr, 'swift');
res.json({
success: true,
wasm: wasmBytes.toString('base64'),
stdout,
stderr,
diagnostics,
wasmInfo
});
} catch (err: any) {
const diagnostics = parseDiagnostics(err.stderr || '', 'swift');
res.json({
success: false,
error: err.stderr || err.message,
stdout: err.stdout || '',
diagnostics
});
} finally {
await fs.rm(workDir, { recursive: true, force: true }).catch(() => { });
}
});
app.post('/api/inspect', async (req: Request, res: Response) => {
const { wasmBase64 } = req.body;
if (!wasmBase64 || typeof wasmBase64 !== 'string') {
res.status(400).json({ success: false, error: 'Missing wasmBase64 field' });
return;
}
try {
const wasmBytes = Buffer.from(wasmBase64, 'base64');
const info = parseWasmExportsImports(wasmBytes);
res.json({ success: true, info });
} catch (err: any) {
res.status(500).json({ success: false, error: err.message });
}
});
app.listen(PORT, () => {
console.log(`WASM Compiler Bridge running at http://localhost:${PORT}`);
console.log(`EMSDK_PATH: ${EMSDK_PATH}`);
console.log(`SWIFTWASM_PATH: ${SWIFTWASM_PATH}`);
});
|