jsffi.nim 18 KB

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