jsffi.nim 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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. type
  65. JsObject* = ref object of JsRoot
  66. ## Dynamically typed wrapper around a JavaScript object.
  67. JsAssoc*[K, V] = ref object of JsRoot
  68. ## Statically typed wrapper around a JavaScript object.
  69. js* = JsObject
  70. var
  71. jsArguments* {.importc: "arguments", nodecl}: JsObject
  72. ## JavaScript's arguments pseudo-variable
  73. jsNull* {.importc: "null", nodecl.}: JsObject
  74. ## JavaScript's null literal
  75. jsUndefined* {.importc: "undefined", nodecl.}: JsObject
  76. ## JavaScript's undefined literal
  77. jsDirname* {.importc: "__dirname", nodecl.}: cstring
  78. ## JavaScript's __dirname pseudo-variable
  79. jsFilename* {.importc: "__filename", nodecl.}: cstring
  80. ## JavaScript's __filename pseudo-variable
  81. # New
  82. proc newJsObject*: JsObject {. importcpp: "{@}" .}
  83. ## Creates a new empty JsObject
  84. proc newJsAssoc*[K, V]: JsAssoc[K, V] {. importcpp: "{@}" .}
  85. ## Creates a new empty JsAssoc with key type `K` and value type `V`.
  86. # Checks
  87. proc hasOwnProperty*(x: JsObject, prop: cstring): bool
  88. {. importcpp: "#.hasOwnProperty(#)" .}
  89. ## Checks, whether `x` has a property of name `prop`.
  90. proc jsTypeOf*(x: JsObject): cstring {. importcpp: "typeof(#)" .}
  91. ## Returns the name of the JsObject's JavaScript type as a cstring.
  92. proc jsNew*(x: auto): JsObject {.importcpp: "(new #)".}
  93. ## Turns a regular function call into an invocation of the
  94. ## JavaScript's `new` operator
  95. proc jsDelete*(x: auto): JsObject {.importcpp: "(delete #)".}
  96. ## JavaScript's `delete` operator
  97. proc require*(module: cstring): JsObject {.importc.}
  98. ## JavaScript's `require` function
  99. # Conversion to and from JsObject
  100. proc to*(x: JsObject, T: typedesc): T {. importcpp: "(#)" .}
  101. ## Converts a JsObject `x` to type `T`.
  102. proc toJs*[T](val: T): JsObject {. importcpp: "(#)" .}
  103. ## Converts a value of any type to type JsObject
  104. template toJs*(s: string): JsObject = cstring(s).toJs
  105. macro jsFromAst*(n: untyped): untyped =
  106. result = n
  107. if n.kind == nnkStmtList:
  108. result = newProc(procType = nnkDo, body = result)
  109. return quote: toJs(`result`)
  110. proc `&`*(a, b: cstring): cstring {.importcpp: "(# + #)".}
  111. ## Concatenation operator for JavaScript strings
  112. proc `+` *(x, y: JsObject): JsObject {. importcpp: "(# + #)" .}
  113. proc `-` *(x, y: JsObject): JsObject {. importcpp: "(# - #)" .}
  114. proc `*` *(x, y: JsObject): JsObject {. importcpp: "(# * #)" .}
  115. proc `/` *(x, y: JsObject): JsObject {. importcpp: "(# / #)" .}
  116. proc `%` *(x, y: JsObject): JsObject {. importcpp: "(# % #)" .}
  117. proc `+=` *(x, y: JsObject): JsObject {. importcpp: "(# += #)", discardable .}
  118. proc `-=` *(x, y: JsObject): JsObject {. importcpp: "(# -= #)", discardable .}
  119. proc `*=` *(x, y: JsObject): JsObject {. importcpp: "(# *= #)", discardable .}
  120. proc `/=` *(x, y: JsObject): JsObject {. importcpp: "(# /= #)", discardable .}
  121. proc `%=` *(x, y: JsObject): JsObject {. importcpp: "(# %= #)", discardable .}
  122. proc `++` *(x: JsObject): JsObject {. importcpp: "(++#)" .}
  123. proc `--` *(x: JsObject): JsObject {. importcpp: "(--#)" .}
  124. proc `>` *(x, y: JsObject): JsObject {. importcpp: "(# > #)" .}
  125. proc `<` *(x, y: JsObject): JsObject {. importcpp: "(# < #)" .}
  126. proc `>=` *(x, y: JsObject): JsObject {. importcpp: "(# >= #)" .}
  127. proc `<=` *(x, y: JsObject): JsObject {. importcpp: "(# <= #)" .}
  128. proc `and`*(x, y: JsObject): JsObject {. importcpp: "(# && #)" .}
  129. proc `or` *(x, y: JsObject): JsObject {. importcpp: "(# || #)" .}
  130. proc `not`*(x: JsObject): JsObject {. importcpp: "(!#)" .}
  131. proc `in` *(x, y: JsObject): JsObject {. importcpp: "(# in #)" .}
  132. proc `[]`*(obj: JsObject, field: cstring): JsObject {. importcpp: getImpl .}
  133. ## Return the value of a property of name `field` from a JsObject `obj`.
  134. proc `[]`*(obj: JsObject, field: int): JsObject {. importcpp: getImpl .}
  135. ## Return the value of a property of name `field` from a JsObject `obj`.
  136. proc `[]=`*[T](obj: JsObject, field: cstring, val: T) {. importcpp: setImpl .}
  137. ## Set the value of a property of name `field` in a JsObject `obj` to `v`.
  138. proc `[]=`*[T](obj: JsObject, field: int, val: T) {. importcpp: setImpl .}
  139. ## Set the value of a property of name `field` in a JsObject `obj` to `v`.
  140. proc `[]`*[K: not string, V](obj: JsAssoc[K, V], field: K): V
  141. {. importcpp: getImpl .}
  142. ## Return the value of a property of name `field` from a JsAssoc `obj`.
  143. proc `[]`*[V](obj: JsAssoc[string, V], field: cstring): V
  144. {. importcpp: getImpl .}
  145. ## Return the value of a property of name `field` from a JsAssoc `obj`.
  146. proc `[]=`*[K: not string, V](obj: JsAssoc[K, V], field: K, val: V)
  147. {. importcpp: setImpl .}
  148. ## Set the value of a property of name `field` in a JsAssoc `obj` to `v`.
  149. proc `[]=`*[V](obj: JsAssoc[string, V], field: cstring, val: V)
  150. {. importcpp: setImpl .}
  151. ## Set the value of a property of name `field` in a JsAssoc `obj` to `v`.
  152. proc `==`*(x, y: JsRoot): bool {. importcpp: "(# === #)" .}
  153. ## Compare two JsObjects or JsAssocs. Be careful though, as this is comparison
  154. ## like in JavaScript, so if your JsObjects are in fact JavaScript Objects,
  155. ## and not strings or numbers, this is a *comparison of references*.
  156. {. experimental .}
  157. macro `.`*(obj: JsObject, field: untyped): JsObject =
  158. ## Experimental dot accessor (get) for type JsObject.
  159. ## Returns the value of a property of name `field` from a JsObject `x`.
  160. ##
  161. ## Example:
  162. ##
  163. ## .. code-block:: nim
  164. ##
  165. ## let obj = newJsObject()
  166. ## obj.a = 20
  167. ## console.log(obj.a) # puts 20 onto the console.
  168. if validJsName($field):
  169. let importString = "#." & $field
  170. result = quote do:
  171. proc helper(o: JsObject): JsObject
  172. {. importcpp: `importString`, gensym .}
  173. helper(`obj`)
  174. else:
  175. if not mangledNames.hasKey($field):
  176. mangledNames[$field] = $mangleJsName($field)
  177. let importString = "#." & mangledNames[$field]
  178. result = quote do:
  179. proc helper(o: JsObject): JsObject
  180. {. importcpp: `importString`, gensym .}
  181. helper(`obj`)
  182. macro `.=`*(obj: JsObject, field, value: untyped): untyped =
  183. ## Experimental dot accessor (set) for type JsObject.
  184. ## Sets the value of a property of name `field` in a JsObject `x` to `value`.
  185. if validJsName($field):
  186. let importString = "#." & $field & " = #"
  187. result = quote do:
  188. proc helper(o: JsObject, v: auto)
  189. {. importcpp: `importString`, gensym .}
  190. helper(`obj`, `value`)
  191. else:
  192. if not mangledNames.hasKey($field):
  193. mangledNames[$field] = $mangleJsName($field)
  194. let importString = "#." & mangledNames[$field] & " = #"
  195. result = quote do:
  196. proc helper(o: JsObject, v: auto)
  197. {. importcpp: `importString`, gensym .}
  198. helper(`obj`, `value`)
  199. macro `.()`*(obj: JsObject,
  200. field: untyped,
  201. args: varargs[JsObject, jsFromAst]): JsObject =
  202. ## Experimental "method call" operator for type JsObject.
  203. ## Takes the name of a method of the JavaScript object (`field`) and calls
  204. ## it with `args` as arguments, returning a JsObject (which may be discarded,
  205. ## and may be `undefined`, if the method does not return anything,
  206. ## so be careful when using this.)
  207. ##
  208. ## Example:
  209. ##
  210. ## .. code-block:: nim
  211. ##
  212. ## # Let's get back to the console example:
  213. ## var console {. importc, nodecl .}: JsObject
  214. ## let res = console.log("I return undefined!")
  215. ## console.log(res) # This prints undefined, as console.log always returns
  216. ## # undefined. Thus one has to be careful, when using
  217. ## # JsObject calls.
  218. var importString: string
  219. if validJsName($field):
  220. importString = "#." & $field & "(@)"
  221. else:
  222. if not mangledNames.hasKey($field):
  223. mangledNames[$field] = $mangleJsName($field)
  224. importString = "#." & mangledNames[$field] & "(@)"
  225. result = quote:
  226. proc helper(o: JsObject): JsObject
  227. {. importcpp: `importString`, gensym, discardable .}
  228. helper(`obj`)
  229. for idx in 0 ..< args.len:
  230. let paramName = newIdentNode(!("param" & $idx))
  231. result[0][3].add newIdentDefs(paramName, newIdentNode(!"JsObject"))
  232. result[1].add args[idx].copyNimTree
  233. macro `.`*[K: string | cstring, V](obj: JsAssoc[K, V],
  234. field: untyped): V =
  235. ## Experimental dot accessor (get) for type JsAssoc.
  236. ## Returns the value of a property of name `field` from a JsObject `x`.
  237. var importString: string
  238. if validJsName($field):
  239. importString = "#." & $field
  240. else:
  241. if not mangledNames.hasKey($field):
  242. mangledNames[$field] = $mangleJsName($field)
  243. importString = "#." & mangledNames[$field]
  244. result = quote do:
  245. proc helper(o: type(`obj`)): `obj`.V
  246. {. importcpp: `importString`, gensym .}
  247. helper(`obj`)
  248. macro `.=`*[K: string | cstring, V](obj: JsAssoc[K, V],
  249. field: untyped,
  250. value: V): untyped =
  251. ## Experimental dot accessor (set) for type JsAssoc.
  252. ## Sets the value of a property of name `field` in a JsObject `x` to `value`.
  253. var importString: string
  254. if validJsName($field):
  255. importString = "#." & $field & " = #"
  256. else:
  257. if not mangledNames.hasKey($field):
  258. mangledNames[$field] = $mangleJsName($field)
  259. importString = "#." & mangledNames[$field] & " = #"
  260. result = quote do:
  261. proc helper(o: type(`obj`), v: `obj`.V)
  262. {. importcpp: `importString`, gensym .}
  263. helper(`obj`, `value`)
  264. macro `.()`*[K: string | cstring, V: proc](obj: JsAssoc[K, V],
  265. field: untyped,
  266. args: varargs[untyped]): auto =
  267. ## Experimental "method call" operator for type JsAssoc.
  268. ## Takes the name of a method of the JavaScript object (`field`) and calls
  269. ## it with `args` as arguments. Here, everything is typechecked, so you do not
  270. ## have to worry about `undefined` return values.
  271. let dotOp = bindSym"."
  272. result = quote do:
  273. (`dotOp`(`obj`, `field`))()
  274. for elem in args:
  275. result.add elem
  276. # Iterators:
  277. iterator pairs*(obj: JsObject): (cstring, JsObject) =
  278. ## Yields tuples of type ``(cstring, JsObject)``, with the first entry
  279. ## being the `name` of a fields in the JsObject and the second being its
  280. ## value wrapped into a JsObject.
  281. var k: cstring
  282. var v: JsObject
  283. {.emit: "for (var `k` in `obj`) {".}
  284. {.emit: " if (!`obj`.hasOwnProperty(`k`)) continue;".}
  285. {.emit: " `v`=`obj`[`k`];".}
  286. yield (k, v)
  287. {.emit: "}".}
  288. iterator items*(obj: JsObject): JsObject =
  289. ## Yields the `values` of each field in a JsObject, wrapped into a JsObject.
  290. var v: JsObject
  291. {.emit: "for (var k in `obj`) {".}
  292. {.emit: " if (!`obj`.hasOwnProperty(k)) continue;".}
  293. {.emit: " `v`=`obj`[k];".}
  294. yield v
  295. {.emit: "}".}
  296. iterator keys*(obj: JsObject): cstring =
  297. ## Yields the `names` of each field in a JsObject.
  298. var k: cstring
  299. {.emit: "for (var `k` in `obj`) {".}
  300. {.emit: " if (!`obj`.hasOwnProperty(`k`)) continue;".}
  301. yield k
  302. {.emit: "}".}
  303. iterator pairs*[K, V](assoc: JsAssoc[K, V]): (K,V) =
  304. ## Yields tuples of type ``(K, V)``, with the first entry
  305. ## being a `key` in the JsAssoc and the second being its corresponding value.
  306. when K is string:
  307. var k: cstring
  308. else:
  309. var k: K
  310. var v: V
  311. {.emit: "for (var `k` in `assoc`) {".}
  312. {.emit: " if (!`assoc`.hasOwnProperty(`k`)) continue;".}
  313. {.emit: " `v`=`assoc`[`k`];".}
  314. when K is string:
  315. yield ($k, v)
  316. else:
  317. yield (k, v)
  318. {.emit: "}".}
  319. iterator items*[K,V](assoc: JSAssoc[K,V]): V =
  320. ## Yields the `values` in a JsAssoc.
  321. var v: V
  322. {.emit: "for (var k in `assoc`) {".}
  323. {.emit: " if (!`assoc`.hasOwnProperty(k)) continue;".}
  324. {.emit: " `v`=`assoc`[k];".}
  325. yield v
  326. {.emit: "}".}
  327. iterator keys*[K,V](assoc: JSAssoc[K,V]): K =
  328. ## Yields the `keys` in a JsAssoc.
  329. when K is string:
  330. var k: cstring
  331. else:
  332. var k: K
  333. {.emit: "for (var `k` in `assoc`) {".}
  334. {.emit: " if (!`assoc`.hasOwnProperty(`k`)) continue;".}
  335. when K is string:
  336. yield $k
  337. else:
  338. yield k
  339. {.emit: "}".}
  340. # Literal generation
  341. macro `{}`*(typ: typedesc, xs: varargs[untyped]): auto =
  342. ## Takes a ``typedesc`` as its first argument, and a series of expressions of
  343. ## type ``key: value``, and returns a value of the specified type with each
  344. ## field ``key`` set to ``value``, as specified in the arguments of ``{}``.
  345. ##
  346. ## Example:
  347. ##
  348. ## .. code-block:: nim
  349. ##
  350. ## # Let's say we have a type with a ton of fields, where some fields do not
  351. ## # need to be set, and we do not want those fields to be set to ``nil``:
  352. ## type
  353. ## ExtremelyHugeType = ref object
  354. ## a, b, c, d, e, f, g: int
  355. ## h, i, j, k, l: cstring
  356. ## # And even more fields ...
  357. ##
  358. ## let obj = ExtremelyHugeType{ a: 1, k: "foo".cstring, d: 42 }
  359. ##
  360. ## # This generates roughly the same JavaScript as:
  361. ## {. emit: "var obj = {a: 1, k: "foo", d: 42};" .}
  362. ##
  363. let a = !"a"
  364. var body = quote do:
  365. var `a` {.noinit.}: `typ`
  366. {.emit: "`a` = {};".}
  367. for x in xs.children:
  368. if x.kind == nnkExprColonExpr:
  369. let
  370. k = x[0]
  371. kString = quote do:
  372. when compiles($`k`): $`k` else: "invalid"
  373. v = x[1]
  374. body.add quote do:
  375. when compiles(`a`.`k`):
  376. `a`.`k` = `v`
  377. elif compiles(`a`[`k`]):
  378. `a`[`k`] = `v`
  379. else:
  380. `a`[`kString`] = `v`
  381. else:
  382. error("Expression `" & $x.toStrLit & "` not allowed in `{}` macro")
  383. body.add quote do:
  384. return `a`
  385. result = quote do:
  386. proc inner(): `typ` {.gensym.} =
  387. `body`
  388. inner()
  389. # Macro to build a lambda using JavaScript's `this`
  390. # from a proc, `this` being the first argument.
  391. macro bindMethod*(procedure: typed): auto =
  392. ## Takes the name of a procedure and wraps it into a lambda missing the first
  393. ## argument, which passes the JavaScript builtin ``this`` as the first
  394. ## argument to the procedure. Returns the resulting lambda.
  395. ##
  396. ## Example:
  397. ##
  398. ## We want to generate roughly this JavaScript:
  399. ##
  400. ## .. code-block:: js
  401. ## var obj = {a: 10};
  402. ## obj.someMethod = function() {
  403. ## return this.a + 42;
  404. ## };
  405. ##
  406. ## We can achieve this using the ``bindMethod`` macro:
  407. ##
  408. ## .. code-block:: nim
  409. ## let obj = JsObject{ a: 10 }
  410. ## proc someMethodImpl(that: JsObject): int =
  411. ## that.a.to(int) + 42
  412. ## obj.someMethod = bindMethod someMethodImpl
  413. ##
  414. ## # Alternatively:
  415. ## obj.someMethod = bindMethod
  416. ## proc(that: JsObject): int = that.a.to(int) + 42
  417. if not (procedure.kind == nnkSym or procedure.kind == nnkLambda):
  418. error("Argument has to be a proc or a symbol corresponding to a proc.")
  419. var
  420. rawProc = if procedure.kind == nnkSym:
  421. getImpl(procedure.symbol)
  422. else:
  423. procedure
  424. args = rawProc[3]
  425. thisType = args[1][1]
  426. params = newNimNode(nnkFormalParams).add(args[0])
  427. body = newNimNode(nnkLambda)
  428. this = newIdentNode("this")
  429. # construct the `this` parameter:
  430. thisQuote = quote do:
  431. var `this` {. nodecl, importc .} : `thisType`
  432. call = newNimNode(nnkCall).add(rawProc[0], thisQuote[0][0][0])
  433. # construct the procedure call inside the method
  434. if args.len > 2:
  435. for idx in 2..args.len-1:
  436. params.add(args[idx])
  437. call.add(args[idx][0])
  438. body.add(newNimNode(nnkEmpty),
  439. rawProc[1],
  440. rawProc[2],
  441. params,
  442. rawProc[4],
  443. rawProc[5],
  444. newTree(nnkStmtList, thisQuote, call)
  445. )
  446. result = body