Wiki

Clone wiki

racket-webkit / Marshalling

Marshalling between Racket and JavaScript

Web pages displayed by a web-frame% can run JavaScript code. The Racket WebKit binding can marshall code and data between the JavaScriptCore engine and the Racket runtime. This allows both Racket code to access elements in the document object model of a web page and JavaScript code to access Racket as some kind of backend.

From Racket to JavaScript

Conversion of values from Racket to JavaScript proceeds as follows:

  • The Racket void value is converted to the JavaScript undefined value
  • The character #\null is converted to null
  • Racket booleans are converted to JavaScript booleans
  • Racket numbers are converted to JavaScript numbers
  • Racket strings are converted to JavaScript strings
  • Racket proxies for JavaScript objects are unwrapped
  • Any other Racket value is wrapped in a JavaScript proxy

From JavaScript to Racket

Conversion of values from JavaScript to Racket proceeds as follows:

  • The JavaScript undefined value is converted to the Racket void value
  • The value null is converted to the character #\null
  • JavaScript booleans are converted to Racket booleans
  • JavaScript numbers are converted to Racket numbers
  • JavaScript strings are converted to Racket strings
  • JavaScript proxies for Racket values are unwrapped
  • Any other JavaScript object is wrapped in a Racket proxy

Racket Proxies

A JavaScript object can be wrapped in a Racket proxy. Proxies are opaque structures and can be identified using the type predicate jsproxy?.

Racket proxies exhibit the following special behaviour via structure properties:

  • When written to an output port, the proxy stringifies the underlying JavaScript object and displays the resulting string, enclosed in #<jsproxy:...> in case of a write operation.
  • The proxy acts as a mutable dictionary exposing the properties of the underlying JavaScript object via string, symbol or number keys. Values extracted or stored through dictionary operations are automatically marshalled.
  • The proxy acts as a procedure invoking the underlying JavaScript object as a function. Arguments, return values and exceptions are automatically marshalled.

JavaScript Proxies

A Racket value can be wrapped in a JavaScript proxy. The proxy is an object with no corresponding public constructor.

JavaScript proxies exhibit the following special behaviour:

  • When stringified, the underlying Racket value is written to a string port and the result is returned.
  • Property access on the proxy is redirected to the Racket operations on mutable dictionaries. Every key is tried as a string, a symbol or a number, if necessary. Values extracted from or stored into properties are automatically marshalled.
  • The proxy acts as a function applying the underlying Racket procedure. Arguments, return values and exceptions are automatically marshalled.

Updated