jsffi.nim 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2017 Nim Authors
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This Module implements types and macros to facilitate the wrapping of, and
  10. ## interaction with JavaScript libraries. Using the provided types ``JsObject``
  11. ## and ``JsAssoc`` together with the provided macros allows for smoother
  12. ## interfacing with JavaScript, allowing for example quick and easy imports of
  13. ## JavaScript variables:
  14. ##
  15. ## .. code-block:: nim
  16. ##
  17. ## # Here, we are using jQuery for just a few calls and do not want to wrap the
  18. ## # whole library:
  19. ##
  20. ## # import the document object and the console
  21. ## var document {.importc, nodecl.}: JsObject
  22. ## var console {.importc, nodecl.}: JsObject
  23. ## # import the "$" function
  24. ## proc jq(selector: JsObject): JsObject {.importcpp: "$$(#)".}
  25. ##
  26. ## # Use jQuery to make the following code run, after the document is ready.
  27. ## # This uses an experimental ``.()`` operator for ``JsObject``, to emit
  28. ## # JavaScript calls, when no corresponding proc exists for ``JsObject``.
  29. ## proc main =
  30. ## jq(document).ready(proc() =
  31. ## console.log("Hello JavaScript!")
  32. ## )
  33. ##
  34. when not defined(js) and not defined(nimdoc) and not defined(nimsuggest):
  35. {.fatal: "Module jsFFI is designed to be used with the JavaScript backend.".}
  36. import macros, tables
  37. const
  38. setImpl = "#[#] = #"
  39. getImpl = "#[#]"
  40. var
  41. mangledNames {.compileTime.} = initTable[string, string]()
  42. nameCounter {.compileTime.} = 0
  43. proc validJsName(name: string): bool =
  44. result = true
  45. const reservedWords = ["break", "case", "catch", "class", "const", "continue",
  46. "debugger", "default", "delete", "do", "else", "export", "extends",
  47. "finally", "for", "function", "if", "import", "in", "instanceof", "new",
  48. "return", "super", "switch", "this", "throw", "try", "typeof", "var",
  49. "void", "while", "with", "yield", "enum", "implements", "interface",
  50. "let", "package", "private", "protected", "public", "static", "await",
  51. "abstract", "boolean", "byte", "char", "double", "final", "float", "goto",
  52. "int", "long", "native", "short", "synchronized", "throws", "transient",
  53. "volatile", "null", "true", "false"]
  54. case name
  55. of reservedWords: return false
  56. else: discard
  57. if name[0] notin {'A'..'Z','a'..'z','_','$'}: return false
  58. for chr in name:
  59. if chr notin {'A'..'Z','a'..'z','_','$','0'..'9'}:
  60. return false
  61. template mangleJsName(name: cstring): cstring =
  62. inc nameCounter
  63. "mangledName" & $nameCounter
  64. # only values that can be mapped 1 to 1 with cstring should be keys: they have an injective function with cstring
  65. proc toJsKey*[T: SomeInteger](text: cstring, t: type T): T {.importcpp: "parseInt(#)".}
  66. proc toJsKey*[T: enum](text: cstring, t: type T): T =
  67. T(text.toJsKey(int))
  68. proc toJsKey*(text: cstring, t: type cstring): cstring =
  69. text
  70. proc toJsKey*[T: SomeFloat](text: cstring, t: type T): T {.importcpp: "parseFloat(#)".}
  71. type
  72. JsKey* = concept a, type T
  73. cstring.toJsKey(T) is T
  74. JsObject* = ref object of JsRoot
  75. ## Dynamically typed wrapper around a JavaScript object.
  76. JsAssoc*[K: JsKey, V] = ref object of JsRoot
  77. ## Statically typed wrapper around a JavaScript object.
  78. js* = JsObject
  79. var
  80. jsArguments* {.importc: "arguments", nodecl}: JsObject
  81. ## JavaScript's arguments pseudo-variable
  82. jsNull* {.importc: "null", nodecl.}: JsObject
  83. ## JavaScript's null literal
  84. jsUndefined* {.importc: "undefined", nodecl.}: JsObject
  85. ## JavaScript's undefined literal
  86. jsDirname* {.importc: "__dirname", nodecl.}: cstring
  87. ## JavaScript's __dirname pseudo-variable
  88. jsFilename* {.importc: "__filename", nodecl.}: cstring
  89. ## JavaScript's __filename pseudo-variable
  90. proc isNull*[T](x: T): bool {.noSideEffect, importcpp: "(# === null)".}
  91. ## check if a value is exactly null
  92. proc isUndefined*[T](x: T): bool {.noSideEffect, importcpp: "(# === undefined)".}
  93. ## check if a value is exactly undefined
  94. # Exceptions
  95. type
  96. JsError* {.importc: "Error".} = object of JsRoot
  97. message*: cstring
  98. JsEvalError* {.importc: "EvalError".} = object of JsError
  99. JsRangeError* {.importc: "RangeError".} = object of JsError
  100. JsReferenceError* {.importc: "ReferenceError".} = object of JsError
  101. JsSyntaxError* {.importc: "SyntaxError".} = object of JsError
  102. JsTypeError* {.importc: "TypeError".} = object of JsError
  103. JsURIError* {.importc: "URIError".} = object of JsError
  104. # New
  105. proc newJsObject*: JsObject {.importcpp: "{@}".}
  106. ## Creates a new empty JsObject
  107. proc newJsAssoc*[K: JsKey, V]: JsAssoc[K, V] {.importcpp: "{@}".}
  108. ## Creates a new empty JsAssoc with key type `K` and value type `V`.
  109. # Checks
  110. proc hasOwnProperty*(x: JsObject, prop: cstring): bool
  111. {.importcpp: "#.hasOwnProperty(#)".}
  112. ## Checks, whether `x` has a property of name `prop`.
  113. proc jsTypeOf*(x: JsObject): cstring {.importcpp: "typeof(#)".}
  114. ## Returns the name of the JsObject's JavaScript type as a cstring.
  115. proc jsNew*(x: auto): JsObject {.importcpp: "(new #)".}
  116. ## Turns a regular function call into an invocation of the
  117. ## JavaScript's `new` operator
  118. proc jsDelete*(x: auto): JsObject {.importcpp: "(delete #)".}
  119. ## JavaScript's `delete` operator
  120. proc require*(module: cstring): JsObject {.importc.}
  121. ## JavaScript's `require` function
  122. # Conversion to and from JsObject
  123. proc to*(x: JsObject, T: typedesc): T {.importcpp: "(#)".}
  124. ## Converts a JsObject `x` to type `T`.
  125. proc toJs*[T](val: T): JsObject {.importcpp: "(#)".}
  126. ## Converts a value of any type to type JsObject
  127. template toJs*(s: string): JsObject = cstring(s).toJs
  128. macro jsFromAst*(n: untyped): untyped =
  129. result = n
  130. if n.kind == nnkStmtList:
  131. result = newProc(procType = nnkDo, body = result)
  132. return quote: toJs(`result`)
  133. proc `&`*(a, b: cstring): cstring {.importcpp: "(# + #)".}
  134. ## Concatenation operator for JavaScript strings
  135. proc `+` *(x, y: JsObject): JsObject {.importcpp: "(# + #)".}
  136. proc `-` *(x, y: JsObject): JsObject {.importcpp: "(# - #)".}
  137. proc `*` *(x, y: JsObject): JsObject {.importcpp: "(# * #)".}
  138. proc `/` *(x, y: JsObject): JsObject {.importcpp: "(# / #)".}
  139. proc `%` *(x, y: JsObject): JsObject {.importcpp: "(# % #)".}
  140. proc `+=` *(x, y: JsObject): JsObject {.importcpp: "(# += #)", discardable.}
  141. proc `-=` *(x, y: JsObject): JsObject {.importcpp: "(# -= #)", discardable.}
  142. proc `*=` *(x, y: JsObject): JsObject {.importcpp: "(# *= #)", discardable.}
  143. proc `/=` *(x, y: JsObject): JsObject {.importcpp: "(# /= #)", discardable.}
  144. proc `%=` *(x, y: JsObject): JsObject {.importcpp: "(# %= #)", discardable.}
  145. proc `++` *(x: JsObject): JsObject {.importcpp: "(++#)".}
  146. proc `--` *(x: JsObject): JsObject {.importcpp: "(--#)".}
  147. proc `>` *(x, y: JsObject): JsObject {.importcpp: "(# > #)".}
  148. proc `<` *(x, y: JsObject): JsObject {.importcpp: "(# < #)".}
  149. proc `>=` *(x, y: JsObject): JsObject {.importcpp: "(# >= #)".}
  150. proc `<=` *(x, y: JsObject): JsObject {.importcpp: "(# <= #)".}
  151. proc `and`*(x, y: JsObject): JsObject {.importcpp: "(# && #)".}
  152. proc `or` *(x, y: JsObject): JsObject {.importcpp: "(# || #)".}
  153. proc `not`*(x: JsObject): JsObject {.importcpp: "(!#)".}
  154. proc `in` *(x, y: JsObject): JsObject {.importcpp: "(# in #)".}
  155. proc `[]`*(obj: JsObject, field: cstring): JsObject {.importcpp: getImpl.}
  156. ## Return the value of a property of name `field` from a JsObject `obj`.
  157. proc `[]`*(obj: JsObject, field: int): JsObject {.importcpp: getImpl.}
  158. ## Return the value of a property of name `field` from a JsObject `obj`.
  159. proc `[]=`*[T](obj: JsObject, field: cstring, val: T) {.importcpp: setImpl.}
  160. ## Set the value of a property of name `field` in a JsObject `obj` to `v`.
  161. proc `[]=`*[T](obj: JsObject, field: int, val: T) {.importcpp: setImpl.}
  162. ## Set the value of a property of name `field` in a JsObject `obj` to `v`.
  163. proc `[]`*[K: JsKey, V](obj: JsAssoc[K, V], field: K): V
  164. {.importcpp: getImpl.}
  165. ## Return the value of a property of name `field` from a JsAssoc `obj`.
  166. proc `[]=`*[K: JsKey, V](obj: JsAssoc[K, V], field: K, val: V)
  167. {.importcpp: setImpl.}
  168. ## Set the value of a property of name `field` in a JsAssoc `obj` to `v`.
  169. proc `[]`*[V](obj: JsAssoc[cstring, V], field: string): V =
  170. obj[cstring(field)]
  171. proc `[]=`*[V](obj: JsAssoc[cstring, V], field: string, val: V) =
  172. obj[cstring(field)] = val
  173. proc `==`*(x, y: JsRoot): bool {.importcpp: "(# === #)".}
  174. ## Compare two JsObjects or JsAssocs. Be careful though, as this is comparison
  175. ## like in JavaScript, so if your JsObjects are in fact JavaScript Objects,
  176. ## and not strings or numbers, this is a *comparison of references*.
  177. {.experimental.}
  178. macro `.`*(obj: JsObject, field: untyped): JsObject =
  179. ## Experimental dot accessor (get) for type JsObject.
  180. ## Returns the value of a property of name `field` from a JsObject `x`.
  181. ##
  182. ## Example:
  183. ##
  184. ## .. code-block:: nim
  185. ##
  186. ## let obj = newJsObject()
  187. ## obj.a = 20
  188. ## console.log(obj.a) # puts 20 onto the console.
  189. if validJsName($field):
  190. let importString = "#." & $field
  191. result = quote do:
  192. proc helper(o: JsObject): JsObject
  193. {.importcpp: `importString`, gensym.}
  194. helper(`obj`)
  195. else:
  196. if not mangledNames.hasKey($field):
  197. mangledNames[$field] = $mangleJsName($field)
  198. let importString = "#." & mangledNames[$field]
  199. result = quote do:
  200. proc helper(o: JsObject): JsObject
  201. {.importcpp: `importString`, gensym.}
  202. helper(`obj`)
  203. macro `.=`*(obj: JsObject, field, value: untyped): untyped =
  204. ## Experimental dot accessor (set) for type JsObject.
  205. ## Sets the value of a property of name `field` in a JsObject `x` to `value`.
  206. if validJsName($field):
  207. let importString = "#." & $field & " = #"
  208. result = quote do:
  209. proc helper(o: JsObject, v: auto)
  210. {.importcpp: `importString`, gensym.}
  211. helper(`obj`, `value`)
  212. else:
  213. if not mangledNames.hasKey($field):
  214. mangledNames[$field] = $mangleJsName($field)
  215. let importString = "#." & mangledNames[$field] & " = #"
  216. result = quote do:
  217. proc helper(o: JsObject, v: auto)
  218. {.importcpp: `importString`, gensym.}
  219. helper(`obj`, `value`)
  220. macro `.()`*(obj: JsObject,
  221. field: untyped,
  222. args: varargs[JsObject, jsFromAst]): JsObject =
  223. ## Experimental "method call" operator for type JsObject.
  224. ## Takes the name of a method of the JavaScript object (`field`) and calls
  225. ## it with `args` as arguments, returning a JsObject (which may be discarded,
  226. ## and may be `undefined`, if the method does not return anything,
  227. ## so be careful when using this.)
  228. ##
  229. ## Example:
  230. ##
  231. ## .. code-block:: nim
  232. ##
  233. ## # Let's get back to the console example:
  234. ## var console {.importc, nodecl.}: JsObject
  235. ## let res = console.log("I return undefined!")
  236. ## console.log(res) # This prints undefined, as console.log always returns
  237. ## # undefined. Thus one has to be careful, when using
  238. ## # JsObject calls.
  239. var importString: string
  240. if validJsName($field):
  241. importString = "#." & $field & "(@)"
  242. else:
  243. if not mangledNames.hasKey($field):
  244. mangledNames[$field] = $mangleJsName($field)
  245. importString = "#." & mangledNames[$field] & "(@)"
  246. result = quote:
  247. proc helper(o: JsObject): JsObject
  248. {.importcpp: `importString`, gensym, discardable.}
  249. helper(`obj`)
  250. for idx in 0 ..< args.len:
  251. let paramName = newIdentNode("param" & $idx)
  252. result[0][3].add newIdentDefs(paramName, newIdentNode("JsObject"))
  253. result[1].add args[idx].copyNimTree
  254. macro `.`*[K: cstring, V](obj: JsAssoc[K, V],
  255. field: untyped): V =
  256. ## Experimental dot accessor (get) for type JsAssoc.
  257. ## Returns the value of a property of name `field` from a JsObject `x`.
  258. var importString: string
  259. if validJsName($field):
  260. importString = "#." & $field
  261. else:
  262. if not mangledNames.hasKey($field):
  263. mangledNames[$field] = $mangleJsName($field)
  264. importString = "#." & mangledNames[$field]
  265. result = quote do:
  266. proc helper(o: type(`obj`)): `obj`.V
  267. {.importcpp: `importString`, gensym.}
  268. helper(`obj`)
  269. macro `.=`*[K: cstring, V](obj: JsAssoc[K, V],
  270. field: untyped,
  271. value: V): untyped =
  272. ## Experimental dot accessor (set) for type JsAssoc.
  273. ## Sets the value of a property of name `field` in a JsObject `x` to `value`.
  274. var importString: string
  275. if validJsName($field):
  276. importString = "#." & $field & " = #"
  277. else:
  278. if not mangledNames.hasKey($field):
  279. mangledNames[$field] = $mangleJsName($field)
  280. importString = "#." & mangledNames[$field] & " = #"
  281. result = quote do:
  282. proc helper(o: type(`obj`), v: `obj`.V)
  283. {.importcpp: `importString`, gensym.}
  284. helper(`obj`, `value`)
  285. macro `.()`*[K: cstring, V: proc](obj: JsAssoc[K, V],
  286. field: untyped,
  287. args: varargs[untyped]): auto =
  288. ## Experimental "method call" operator for type JsAssoc.
  289. ## Takes the name of a method of the JavaScript object (`field`) and calls
  290. ## it with `args` as arguments. Here, everything is typechecked, so you do not
  291. ## have to worry about `undefined` return values.
  292. let dotOp = bindSym"."
  293. result = quote do:
  294. (`dotOp`(`obj`, `field`))()
  295. for elem in args:
  296. result.add elem
  297. # Iterators:
  298. iterator pairs*(obj: JsObject): (cstring, JsObject) =
  299. ## Yields tuples of type ``(cstring, JsObject)``, with the first entry
  300. ## being the `name` of a fields in the JsObject and the second being its
  301. ## value wrapped into a JsObject.
  302. var k: cstring
  303. var v: JsObject
  304. {.emit: "for (var `k` in `obj`) {".}
  305. {.emit: " if (!`obj`.hasOwnProperty(`k`)) continue;".}
  306. {.emit: " `v`=`obj`[`k`];".}
  307. yield (k, v)
  308. {.emit: "}".}
  309. iterator items*(obj: JsObject): JsObject =
  310. ## Yields the `values` of each field in a JsObject, wrapped into a JsObject.
  311. var v: JsObject
  312. {.emit: "for (var k in `obj`) {".}
  313. {.emit: " if (!`obj`.hasOwnProperty(k)) continue;".}
  314. {.emit: " `v`=`obj`[k];".}
  315. yield v
  316. {.emit: "}".}
  317. iterator keys*(obj: JsObject): cstring =
  318. ## Yields the `names` of each field in a JsObject.
  319. var k: cstring
  320. {.emit: "for (var `k` in `obj`) {".}
  321. {.emit: " if (!`obj`.hasOwnProperty(`k`)) continue;".}
  322. yield k
  323. {.emit: "}".}
  324. iterator pairs*[K: JsKey, V](assoc: JsAssoc[K, V]): (K,V) =
  325. ## Yields tuples of type ``(K, V)``, with the first entry
  326. ## being a `key` in the JsAssoc and the second being its corresponding value.
  327. var k: cstring
  328. var v: V
  329. {.emit: "for (var `k` in `assoc`) {".}
  330. {.emit: " if (!`assoc`.hasOwnProperty(`k`)) continue;".}
  331. {.emit: " `v`=`assoc`[`k`];".}
  332. yield (k.toJsKey(K), v)
  333. {.emit: "}".}
  334. iterator items*[K, V](assoc: JSAssoc[K, V]): V =
  335. ## Yields the `values` in a JsAssoc.
  336. var v: V
  337. {.emit: "for (var k in `assoc`) {".}
  338. {.emit: " if (!`assoc`.hasOwnProperty(k)) continue;".}
  339. {.emit: " `v`=`assoc`[k];".}
  340. yield v
  341. {.emit: "}".}
  342. iterator keys*[K: JsKey, V](assoc: JSAssoc[K, V]): K =
  343. ## Yields the `keys` in a JsAssoc.
  344. var k: cstring
  345. {.emit: "for (var `k` in `assoc`) {".}
  346. {.emit: " if (!`assoc`.hasOwnProperty(`k`)) continue;".}
  347. yield k.toJsKey(K)
  348. {.emit: "}".}
  349. # Literal generation
  350. macro `{}`*(typ: typedesc, xs: varargs[untyped]): auto =
  351. ## Takes a ``typedesc`` as its first argument, and a series of expressions of
  352. ## type ``key: value``, and returns a value of the specified type with each
  353. ## field ``key`` set to ``value``, as specified in the arguments of ``{}``.
  354. ##
  355. ## Example:
  356. ##
  357. ## .. code-block:: nim
  358. ##
  359. ## # Let's say we have a type with a ton of fields, where some fields do not
  360. ## # need to be set, and we do not want those fields to be set to ``nil``:
  361. ## type
  362. ## ExtremelyHugeType = ref object
  363. ## a, b, c, d, e, f, g: int
  364. ## h, i, j, k, l: cstring
  365. ## # And even more fields ...
  366. ##
  367. ## let obj = ExtremelyHugeType{ a: 1, k: "foo".cstring, d: 42 }
  368. ##
  369. ## # This generates roughly the same JavaScript as:
  370. ## {.emit: "var obj = {a: 1, k: "foo", d: 42};".}
  371. ##
  372. let a = ident"a"
  373. var body = quote do:
  374. var `a` {.noinit.}: `typ`
  375. {.emit: "`a` = {};".}
  376. for x in xs.children:
  377. if x.kind == nnkExprColonExpr:
  378. let
  379. k = x[0]
  380. kString = quote do:
  381. when compiles($`k`): $`k` else: "invalid"
  382. v = x[1]
  383. body.add quote do:
  384. when compiles(`a`.`k`):
  385. `a`.`k` = `v`
  386. elif compiles(`a`[`k`]):
  387. `a`[`k`] = `v`
  388. else:
  389. `a`[`kString`] = `v`
  390. else:
  391. error("Expression `" & $x.toStrLit & "` not allowed in `{}` macro")
  392. body.add quote do:
  393. return `a`
  394. result = quote do:
  395. proc inner(): `typ` {.gensym.} =
  396. `body`
  397. inner()
  398. # Macro to build a lambda using JavaScript's `this`
  399. # from a proc, `this` being the first argument.
  400. proc replaceSyms(n: NimNode): NimNode =
  401. if n.kind == nnkSym:
  402. result = newIdentNode($n)
  403. else:
  404. result = n
  405. for i in 0..<n.len:
  406. result[i] = replaceSyms(n[i])
  407. macro bindMethod*(procedure: typed): auto =
  408. ## Takes the name of a procedure and wraps it into a lambda missing the first
  409. ## argument, which passes the JavaScript builtin ``this`` as the first
  410. ## argument to the procedure. Returns the resulting lambda.
  411. ##
  412. ## Example:
  413. ##
  414. ## We want to generate roughly this JavaScript:
  415. ##
  416. ## .. code-block:: js
  417. ## var obj = {a: 10};
  418. ## obj.someMethod = function() {
  419. ## return this.a + 42;
  420. ## };
  421. ##
  422. ## We can achieve this using the ``bindMethod`` macro:
  423. ##
  424. ## .. code-block:: nim
  425. ## let obj = JsObject{ a: 10 }
  426. ## proc someMethodImpl(that: JsObject): int =
  427. ## that.a.to(int) + 42
  428. ## obj.someMethod = bindMethod someMethodImpl
  429. ##
  430. ## # Alternatively:
  431. ## obj.someMethod = bindMethod
  432. ## proc(that: JsObject): int = that.a.to(int) + 42
  433. if not (procedure.kind == nnkSym or procedure.kind == nnkLambda):
  434. error("Argument has to be a proc or a symbol corresponding to a proc.")
  435. var
  436. rawProc = if procedure.kind == nnkSym:
  437. getImpl(procedure)
  438. else:
  439. procedure
  440. args = rawProc[3].copyNimTree.replaceSyms
  441. thisType = args[1][1]
  442. params = newNimNode(nnkFormalParams).add(args[0])
  443. body = newNimNode(nnkLambda)
  444. this = newIdentNode("this")
  445. # construct the `this` parameter:
  446. thisQuote = quote do:
  447. var `this` {.nodecl, importc: "this".}: `thisType`
  448. call = newNimNode(nnkCall).add(rawProc[0], thisQuote[0][0][0])
  449. # construct the procedure call inside the method
  450. if args.len > 2:
  451. for idx in 2..args.len-1:
  452. params.add(args[idx])
  453. call.add(args[idx][0])
  454. body.add(newNimNode(nnkEmpty),
  455. rawProc[1],
  456. rawProc[2],
  457. params,
  458. rawProc[4],
  459. rawProc[5],
  460. newTree(nnkStmtList, thisQuote, call)
  461. )
  462. result = body