@@ -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,7 @@ public class ExportSwift {
5355 }
5456 return (
5557 outputSwift: outputSwift,
56- outputSkeleton: ExportedSkeleton ( functions: exportedFunctions, classes: exportedClasses)
58+ outputSkeleton: ExportedSkeleton ( moduleName : moduleName , functions: exportedFunctions, classes: exportedClasses)
5759 )
5860 }
5961
@@ -676,8 +678,41 @@ public class ExportSwift {
676678 )
677679 }
678680
681+ // Generate ConvertibleToJSValue extension
682+ decls. append ( renderConvertibleToJSValueExtension ( klass: klass) )
683+
679684 return decls
680685 }
686+
687+ /// Generates a ConvertibleToJSValue extension for the exported class
688+ ///
689+ /// # Example
690+ ///
691+ /// For a class named `Greeter`, this generates:
692+ ///
693+ /// ```swift
694+ /// extension Greeter: ConvertibleToJSValue {
695+ /// var jsValue: JSValue {
696+ /// @_extern(wasm, module: "MyModule", name: "bjs_Greeter_wrap")
697+ /// func _bjs_Greeter_wrap(_: UnsafeMutableRawPointer) -> Int32
698+ /// return JSObject(id: UInt32(bitPattern: _bjs_Greeter_wrap(Unmanaged.passRetained(self).toOpaque())))
699+ /// }
700+ /// }
701+ /// ```
702+ func renderConvertibleToJSValueExtension( klass: ExportedClass ) -> DeclSyntax {
703+ let wrapFunctionName = " _bjs_ \( klass. name) _wrap "
704+ let externFunctionName = " bjs_ \( klass. name) _wrap "
705+
706+ return """
707+ extension \( raw: klass. name) : ConvertibleToJSValue {
708+ var jsValue: JSValue {
709+ @_extern(wasm, module: " \( raw: moduleName) " , name: " \( raw: externFunctionName) " )
710+ func \( raw: wrapFunctionName) (_: UnsafeMutableRawPointer) -> Int32
711+ return .object(JSObject(id: UInt32(bitPattern: \( raw: wrapFunctionName) (Unmanaged.passRetained(self).toOpaque()))))
712+ }
713+ }
714+ """
715+ }
681716}
682717
683718extension AttributeListSyntax {
0 commit comments