@@ -16,13 +16,15 @@ import BridgeJSSkeleton
1616/// JavaScript glue code and TypeScript definitions.
1717public class ExportSwift {
1818 let progress : ProgressReporting
19+ let moduleName : String
1920
2021 private var exportedFunctions : [ ExportedFunction ] = [ ]
2122 private var exportedClasses : [ ExportedClass ] = [ ]
2223 private var typeDeclResolver : TypeDeclResolver = TypeDeclResolver ( )
2324
24- public init ( progress: ProgressReporting ) {
25+ public init ( progress: ProgressReporting , moduleName : String ) {
2526 self . progress = progress
27+ self . moduleName = moduleName
2628 }
2729
2830 /// Processes a Swift source file to find declarations marked with @JS
@@ -53,7 +55,11 @@ public class ExportSwift {
5355 }
5456 return (
5557 outputSwift: outputSwift,
56- outputSkeleton: ExportedSkeleton ( functions: exportedFunctions, classes: exportedClasses)
58+ outputSkeleton: ExportedSkeleton (
59+ moduleName: moduleName,
60+ functions: exportedFunctions,
61+ classes: exportedClasses
62+ )
5763 )
5864 }
5965
@@ -676,8 +682,41 @@ public class ExportSwift {
676682 )
677683 }
678684
685+ // Generate ConvertibleToJSValue extension
686+ decls. append ( renderConvertibleToJSValueExtension ( klass: klass) )
687+
679688 return decls
680689 }
690+
691+ /// Generates a ConvertibleToJSValue extension for the exported class
692+ ///
693+ /// # Example
694+ ///
695+ /// For a class named `Greeter`, this generates:
696+ ///
697+ /// ```swift
698+ /// extension Greeter: ConvertibleToJSValue {
699+ /// var jsValue: JSValue {
700+ /// @_extern(wasm, module: "MyModule", name: "bjs_Greeter_wrap")
701+ /// func _bjs_Greeter_wrap(_: UnsafeMutableRawPointer) -> Int32
702+ /// return JSObject(id: UInt32(bitPattern: _bjs_Greeter_wrap(Unmanaged.passRetained(self).toOpaque())))
703+ /// }
704+ /// }
705+ /// ```
706+ func renderConvertibleToJSValueExtension( klass: ExportedClass ) -> DeclSyntax {
707+ let wrapFunctionName = " _bjs_ \( klass. name) _wrap "
708+ let externFunctionName = " bjs_ \( klass. name) _wrap "
709+
710+ return """
711+ extension \( raw: klass. name) : ConvertibleToJSValue {
712+ var jsValue: JSValue {
713+ @_extern(wasm, module: " \( raw: moduleName) " , name: " \( raw: externFunctionName) " )
714+ func \( raw: wrapFunctionName) (_: UnsafeMutableRawPointer) -> Int32
715+ return .object(JSObject(id: UInt32(bitPattern: \( raw: wrapFunctionName) (Unmanaged.passRetained(self).toOpaque()))))
716+ }
717+ }
718+ """
719+ }
681720}
682721
683722extension AttributeListSyntax {
0 commit comments