Overview
Porffor provides thePorffor.wasm template tag, which allows you to write inline WebAssembly bytecode directly in your TypeScript/JavaScript code. This is similar to C’s asm macro and enables fine-grained performance optimization and low-level memory operations.
The syntax is similar to WebAssembly Text Format (WAT), making it familiar if you’ve worked with WebAssembly before.
Basic Syntax
ThePorffor.wasm template tag accepts WAT-like instructions:
${...} syntax to reference their indices in the WebAssembly local space.
Declaring Locals
Declare typed local variables at the beginning of your inline Wasm block:i32- 32-bit integer (use for pointers)i64- 64-bit integerf64- 64-bit float (standard number type)
Setting Return Types
By default, Porffor functions return(f64, i32) - a valtype and type tag. You can override this:
Getting Pointers
To get the memory pointer of a variable:i32 instead of the object itself.
Accessing Variable Types
Porffor stores type information alongside values. To access the type of a variable:variable at index n and variable#type at index n+1.
Custom Instructions
Porffor provides custom instructions for converting between valtypes and specific types:Type Conversions
i32.from- convert valtype to i32i32.to- convert i32 to valtypef64.from- convert valtype to f64f64.to- convert f64 to valtype
Complete Example
Here’s a real example from Porffor’s built-ins - adding two i32 values:Control Flow
Use standard WebAssembly control flow instructions:Comments
Use;; for single-line comments (WebAssembly’s equivalent of //):
Use Cases
Use inline WebAssembly when:- Performance critical code - You need to squeeze out every bit of performance
- Type-specific optimizations - Different code paths for different types
- Memory operations - Direct memory access for strings, arrays, objects
- SIMD operations - Vector operations not expressible in JavaScript
- Low-level bit manipulation - Operations the compiler might not optimize well
Always benchmark! Inline Wasm adds complexity. The compiler is often smart enough without it.
Best Practices
- Keep it minimal - Use inline Wasm sparingly for hot paths only
- Document heavily - Wasm code is harder to read than JavaScript
- Test thoroughly - Type mismatches and stack errors can be subtle
- Check types carefully - Always validate types when working with
any - Preserve return types - Match Porffor’s
(f64, i32)convention unless absolutely necessary
Common Pitfalls
Related APIs
For memory operations, see:- Porffor API Reference - Memory intrinsics
- Custom Built-ins - Writing full custom functions
Further Reading
- WebAssembly Opcodes Reference
- Understanding WebAssembly Text Format
- Porffor source:
compiler/codegen.js- Full list of custom instructions