jssys.nim 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. include system/indexerrors
  10. import std/private/miscdollars
  11. proc log*(s: cstring) {.importc: "console.log", varargs, nodecl.}
  12. type
  13. PSafePoint = ptr SafePoint
  14. SafePoint {.compilerproc, final.} = object
  15. prev: PSafePoint # points to next safe point
  16. exc: ref Exception
  17. PCallFrame = ptr CallFrame
  18. CallFrame {.importc, nodecl, final.} = object
  19. prev: PCallFrame
  20. procname: cstring
  21. line: int # current line number
  22. filename: cstring
  23. PJSError = ref object
  24. columnNumber {.importc.}: int
  25. fileName {.importc.}: cstring
  26. lineNumber {.importc.}: int
  27. message {.importc.}: cstring
  28. stack {.importc.}: cstring
  29. JSRef = ref RootObj # Fake type.
  30. var
  31. framePtr {.importc, nodecl, volatile.}: PCallFrame
  32. excHandler {.importc, nodecl, volatile.}: int = 0
  33. lastJSError {.importc, nodecl, volatile.}: PJSError = nil
  34. {.push stacktrace: off, profiler:off.}
  35. proc nimBoolToStr(x: bool): string {.compilerproc.} =
  36. if x: result = "true"
  37. else: result = "false"
  38. proc nimCharToStr(x: char): string {.compilerproc.} =
  39. result = newString(1)
  40. result[0] = x
  41. proc isNimException(): bool {.asmNoStackFrame.} =
  42. {.emit: "return `lastJSError` && `lastJSError`.m_type;".}
  43. proc getCurrentException*(): ref Exception {.compilerRtl, benign.} =
  44. if isNimException(): result = cast[ref Exception](lastJSError)
  45. proc getCurrentExceptionMsg*(): string =
  46. if lastJSError != nil:
  47. if isNimException():
  48. return cast[Exception](lastJSError).msg
  49. else:
  50. var msg: cstring
  51. {.emit: """
  52. if (`lastJSError`.message !== undefined) {
  53. `msg` = `lastJSError`.message;
  54. }
  55. """.}
  56. if not msg.isNil:
  57. return $msg
  58. return ""
  59. proc setCurrentException*(exc: ref Exception) =
  60. lastJSError = cast[PJSError](exc)
  61. proc closureIterSetupExc(e: ref Exception) {.compilerproc, inline.} =
  62. ## Used to set up exception handling for closure iterators
  63. setCurrentException(e)
  64. proc auxWriteStackTrace(f: PCallFrame): string =
  65. type
  66. TempFrame = tuple[procname: cstring, line: int, filename: cstring]
  67. var
  68. it = f
  69. i = 0
  70. total = 0
  71. tempFrames: array[0..63, TempFrame]
  72. while it != nil and i <= high(tempFrames):
  73. tempFrames[i].procname = it.procname
  74. tempFrames[i].line = it.line
  75. tempFrames[i].filename = it.filename
  76. inc(i)
  77. inc(total)
  78. it = it.prev
  79. while it != nil:
  80. inc(total)
  81. it = it.prev
  82. result = ""
  83. # if the buffer overflowed print '...':
  84. if total != i:
  85. add(result, "(")
  86. add(result, $(total-i))
  87. add(result, " calls omitted) ...\n")
  88. for j in countdown(i-1, 0):
  89. result.toLocation($tempFrames[j].filename, tempFrames[j].line, 0)
  90. add(result, " at ")
  91. add(result, tempFrames[j].procname)
  92. add(result, "\n")
  93. proc rawWriteStackTrace(): string =
  94. if framePtr != nil:
  95. result = "Traceback (most recent call last)\n" & auxWriteStackTrace(framePtr)
  96. else:
  97. result = "No stack traceback available\n"
  98. proc writeStackTrace() =
  99. var trace = rawWriteStackTrace()
  100. trace.setLen(trace.len - 1)
  101. echo trace
  102. proc getStackTrace*(): string = rawWriteStackTrace()
  103. proc getStackTrace*(e: ref Exception): string = e.trace
  104. proc unhandledException(e: ref Exception) {.
  105. compilerproc, asmNoStackFrame.} =
  106. var buf = ""
  107. if e.msg.len != 0:
  108. add(buf, "Error: unhandled exception: ")
  109. add(buf, e.msg)
  110. else:
  111. add(buf, "Error: unhandled exception")
  112. add(buf, " [")
  113. add(buf, e.name)
  114. add(buf, "]\n")
  115. when NimStackTrace:
  116. add(buf, rawWriteStackTrace())
  117. let cbuf = cstring(buf)
  118. when NimStackTrace:
  119. framePtr = nil
  120. {.emit: """
  121. if (typeof(Error) !== "undefined") {
  122. throw new Error(`cbuf`);
  123. }
  124. else {
  125. throw `cbuf`;
  126. }
  127. """.}
  128. proc raiseException(e: ref Exception, ename: cstring) {.
  129. compilerproc, asmNoStackFrame.} =
  130. e.name = ename
  131. if excHandler == 0:
  132. unhandledException(e)
  133. when NimStackTrace:
  134. e.trace = rawWriteStackTrace()
  135. {.emit: "throw `e`;".}
  136. proc reraiseException() {.compilerproc, asmNoStackFrame.} =
  137. if lastJSError == nil:
  138. raise newException(ReraiseDefect, "no exception to reraise")
  139. else:
  140. if excHandler == 0:
  141. if isNimException():
  142. unhandledException(cast[ref Exception](lastJSError))
  143. {.emit: "throw lastJSError;".}
  144. proc raiseOverflow {.exportc: "raiseOverflow", noreturn, compilerproc.} =
  145. raise newException(OverflowDefect, "over- or underflow")
  146. proc raiseDivByZero {.exportc: "raiseDivByZero", noreturn, compilerproc.} =
  147. raise newException(DivByZeroDefect, "division by zero")
  148. proc raiseRangeError() {.compilerproc, noreturn.} =
  149. raise newException(RangeDefect, "value out of range")
  150. proc raiseIndexError(i, a, b: int) {.compilerproc, noreturn.} =
  151. raise newException(IndexDefect, formatErrorIndexBound(int(i), int(a), int(b)))
  152. proc raiseFieldError2(f: string, discVal: string) {.compilerproc, noreturn.} =
  153. raise newException(FieldDefect, formatFieldDefect(f, discVal))
  154. proc setConstr() {.varargs, asmNoStackFrame, compilerproc.} =
  155. {.emit: """
  156. var result = {};
  157. for (var i = 0; i < arguments.length; ++i) {
  158. var x = arguments[i];
  159. if (typeof(x) == "object") {
  160. for (var j = x[0]; j <= x[1]; ++j) {
  161. result[j] = true;
  162. }
  163. } else {
  164. result[x] = true;
  165. }
  166. }
  167. return result;
  168. """.}
  169. proc makeNimstrLit(c: cstring): string {.asmNoStackFrame, compilerproc.} =
  170. {.emit: """
  171. var result = [];
  172. for (var i = 0; i < `c`.length; ++i) {
  173. result[i] = `c`.charCodeAt(i);
  174. }
  175. return result;
  176. """.}
  177. proc cstrToNimstr(c: cstring): string {.asmNoStackFrame, compilerproc.} =
  178. {.emit: """
  179. var ln = `c`.length;
  180. var result = new Array(ln);
  181. var r = 0;
  182. for (var i = 0; i < ln; ++i) {
  183. var ch = `c`.charCodeAt(i);
  184. if (ch < 128) {
  185. result[r] = ch;
  186. }
  187. else {
  188. if (ch < 2048) {
  189. result[r] = (ch >> 6) | 192;
  190. }
  191. else {
  192. if (ch < 55296 || ch >= 57344) {
  193. result[r] = (ch >> 12) | 224;
  194. }
  195. else {
  196. ++i;
  197. ch = 65536 + (((ch & 1023) << 10) | (`c`.charCodeAt(i) & 1023));
  198. result[r] = (ch >> 18) | 240;
  199. ++r;
  200. result[r] = ((ch >> 12) & 63) | 128;
  201. }
  202. ++r;
  203. result[r] = ((ch >> 6) & 63) | 128;
  204. }
  205. ++r;
  206. result[r] = (ch & 63) | 128;
  207. }
  208. ++r;
  209. }
  210. return result;
  211. """.}
  212. proc toJSStr(s: string): cstring {.compilerproc.} =
  213. proc fromCharCode(c: char): cstring {.importc: "String.fromCharCode".}
  214. proc join(x: openArray[cstring]; d = cstring""): cstring {.
  215. importcpp: "#.join(@)".}
  216. proc decodeURIComponent(x: cstring): cstring {.
  217. importc: "decodeURIComponent".}
  218. proc toHexString(c: char; d = 16): cstring {.importcpp: "#.toString(@)".}
  219. proc log(x: cstring) {.importc: "console.log".}
  220. var res = newSeq[cstring](s.len)
  221. var i = 0
  222. var j = 0
  223. while i < s.len:
  224. var c = s[i]
  225. if c < '\128':
  226. res[j] = fromCharCode(c)
  227. inc i
  228. else:
  229. var helper = newSeq[cstring]()
  230. while true:
  231. let code = toHexString(c)
  232. if code.len == 1:
  233. helper.add cstring"%0"
  234. else:
  235. helper.add cstring"%"
  236. helper.add code
  237. inc i
  238. if i >= s.len or s[i] < '\128': break
  239. c = s[i]
  240. try:
  241. res[j] = decodeURIComponent join(helper)
  242. except:
  243. res[j] = join(helper)
  244. inc j
  245. setLen(res, j)
  246. result = join(res)
  247. proc mnewString(len: int): string {.asmNoStackFrame, compilerproc.} =
  248. {.emit: """
  249. var result = new Array(`len`);
  250. for (var i = 0; i < `len`; i++) {result[i] = 0;}
  251. return result;
  252. """.}
  253. proc SetCard(a: int): int {.compilerproc, asmNoStackFrame.} =
  254. # argument type is a fake
  255. {.emit: """
  256. var result = 0;
  257. for (var elem in `a`) { ++result; }
  258. return result;
  259. """.}
  260. proc SetEq(a, b: int): bool {.compilerproc, asmNoStackFrame.} =
  261. {.emit: """
  262. for (var elem in `a`) { if (!`b`[elem]) return false; }
  263. for (var elem in `b`) { if (!`a`[elem]) return false; }
  264. return true;
  265. """.}
  266. proc SetLe(a, b: int): bool {.compilerproc, asmNoStackFrame.} =
  267. {.emit: """
  268. for (var elem in `a`) { if (!`b`[elem]) return false; }
  269. return true;
  270. """.}
  271. proc SetLt(a, b: int): bool {.compilerproc.} =
  272. result = SetLe(a, b) and not SetEq(a, b)
  273. proc SetMul(a, b: int): int {.compilerproc, asmNoStackFrame.} =
  274. {.emit: """
  275. var result = {};
  276. for (var elem in `a`) {
  277. if (`b`[elem]) { result[elem] = true; }
  278. }
  279. return result;
  280. """.}
  281. proc SetPlus(a, b: int): int {.compilerproc, asmNoStackFrame.} =
  282. {.emit: """
  283. var result = {};
  284. for (var elem in `a`) { result[elem] = true; }
  285. for (var elem in `b`) { result[elem] = true; }
  286. return result;
  287. """.}
  288. proc SetMinus(a, b: int): int {.compilerproc, asmNoStackFrame.} =
  289. {.emit: """
  290. var result = {};
  291. for (var elem in `a`) {
  292. if (!`b`[elem]) { result[elem] = true; }
  293. }
  294. return result;
  295. """.}
  296. proc SetXor(a, b: int): int {.compilerproc, asmNoStackFrame.} =
  297. {.emit: """
  298. var result = {};
  299. for (var elem in `a`) {
  300. if (!`b`[elem]) { result[elem] = true; }
  301. }
  302. for (var elem in `b`) {
  303. if (!`a`[elem]) { result[elem] = true; }
  304. }
  305. return result;
  306. """.}
  307. proc cmpStrings(a, b: string): int {.asmNoStackFrame, compilerproc.} =
  308. {.emit: """
  309. if (`a` == `b`) return 0;
  310. if (!`a`) return -1;
  311. if (!`b`) return 1;
  312. for (var i = 0; i < `a`.length && i < `b`.length; i++) {
  313. var result = `a`[i] - `b`[i];
  314. if (result != 0) return result;
  315. }
  316. return `a`.length - `b`.length;
  317. """.}
  318. proc cmp(x, y: string): int =
  319. when nimvm:
  320. if x == y: result = 0
  321. elif x < y: result = -1
  322. else: result = 1
  323. else:
  324. result = cmpStrings(x, y)
  325. proc eqStrings(a, b: string): bool {.asmNoStackFrame, compilerproc.} =
  326. {.emit: """
  327. if (`a` == `b`) return true;
  328. if (`a` === null && `b`.length == 0) return true;
  329. if (`b` === null && `a`.length == 0) return true;
  330. if ((!`a`) || (!`b`)) return false;
  331. var alen = `a`.length;
  332. if (alen != `b`.length) return false;
  333. for (var i = 0; i < alen; ++i)
  334. if (`a`[i] != `b`[i]) return false;
  335. return true;
  336. """.}
  337. when defined(kwin):
  338. proc rawEcho {.compilerproc, asmNoStackFrame.} =
  339. {.emit: """
  340. var buf = "";
  341. for (var i = 0; i < arguments.length; ++i) {
  342. buf += `toJSStr`(arguments[i]);
  343. }
  344. print(buf);
  345. """.}
  346. elif not defined(nimOldEcho):
  347. proc ewriteln(x: cstring) = log(x)
  348. proc rawEcho {.compilerproc, asmNoStackFrame.} =
  349. {.emit: """
  350. var buf = "";
  351. for (var i = 0; i < arguments.length; ++i) {
  352. buf += `toJSStr`(arguments[i]);
  353. }
  354. console.log(buf);
  355. """.}
  356. else:
  357. proc ewriteln(x: cstring) =
  358. var node : JSRef
  359. {.emit: "`node` = document.getElementsByTagName('body')[0];".}
  360. if node.isNil:
  361. raise newException(ValueError, "<body> element does not exist yet!")
  362. {.emit: """
  363. `node`.appendChild(document.createTextNode(`x`));
  364. `node`.appendChild(document.createElement("br"));
  365. """.}
  366. proc rawEcho {.compilerproc.} =
  367. var node : JSRef
  368. {.emit: "`node` = document.getElementsByTagName('body')[0];".}
  369. if node.isNil:
  370. raise newException(IOError, "<body> element does not exist yet!")
  371. {.emit: """
  372. for (var i = 0; i < arguments.length; ++i) {
  373. var x = `toJSStr`(arguments[i]);
  374. `node`.appendChild(document.createTextNode(x));
  375. }
  376. `node`.appendChild(document.createElement("br"));
  377. """.}
  378. # Arithmetic:
  379. proc checkOverflowInt(a: int) {.asmNoStackFrame, compilerproc.} =
  380. {.emit: """
  381. if (`a` > 2147483647 || `a` < -2147483648) `raiseOverflow`();
  382. """.}
  383. proc addInt(a, b: int): int {.asmNoStackFrame, compilerproc.} =
  384. {.emit: """
  385. var result = `a` + `b`;
  386. `checkOverflowInt`(result);
  387. return result;
  388. """.}
  389. proc subInt(a, b: int): int {.asmNoStackFrame, compilerproc.} =
  390. {.emit: """
  391. var result = `a` - `b`;
  392. `checkOverflowInt`(result);
  393. return result;
  394. """.}
  395. proc mulInt(a, b: int): int {.asmNoStackFrame, compilerproc.} =
  396. {.emit: """
  397. var result = `a` * `b`;
  398. `checkOverflowInt`(result);
  399. return result;
  400. """.}
  401. proc divInt(a, b: int): int {.asmNoStackFrame, compilerproc.} =
  402. {.emit: """
  403. if (`b` == 0) `raiseDivByZero`();
  404. if (`b` == -1 && `a` == 2147483647) `raiseOverflow`();
  405. return Math.trunc(`a` / `b`);
  406. """.}
  407. proc modInt(a, b: int): int {.asmNoStackFrame, compilerproc.} =
  408. {.emit: """
  409. if (`b` == 0) `raiseDivByZero`();
  410. if (`b` == -1 && `a` == 2147483647) `raiseOverflow`();
  411. return Math.trunc(`a` % `b`);
  412. """.}
  413. proc checkOverflowInt64(a: int64) {.asmNoStackFrame, compilerproc.} =
  414. {.emit: """
  415. if (`a` > 9223372036854775807n || `a` < -9223372036854775808n) `raiseOverflow`();
  416. """.}
  417. proc addInt64(a, b: int64): int64 {.asmNoStackFrame, compilerproc.} =
  418. {.emit: """
  419. var result = `a` + `b`;
  420. `checkOverflowInt64`(result);
  421. return result;
  422. """.}
  423. proc subInt64(a, b: int64): int64 {.asmNoStackFrame, compilerproc.} =
  424. {.emit: """
  425. var result = `a` - `b`;
  426. `checkOverflowInt64`(result);
  427. return result;
  428. """.}
  429. proc mulInt64(a, b: int64): int64 {.asmNoStackFrame, compilerproc.} =
  430. {.emit: """
  431. var result = `a` * `b`;
  432. `checkOverflowInt64`(result);
  433. return result;
  434. """.}
  435. proc divInt64(a, b: int64): int64 {.asmNoStackFrame, compilerproc.} =
  436. {.emit: """
  437. if (`b` == 0n) `raiseDivByZero`();
  438. if (`b` == -1n && `a` == 9223372036854775807n) `raiseOverflow`();
  439. return `a` / `b`;
  440. """.}
  441. proc modInt64(a, b: int64): int64 {.asmNoStackFrame, compilerproc.} =
  442. {.emit: """
  443. if (`b` == 0n) `raiseDivByZero`();
  444. if (`b` == -1n && `a` == 9223372036854775807n) `raiseOverflow`();
  445. return `a` % `b`;
  446. """.}
  447. proc negInt(a: int): int {.compilerproc.} =
  448. result = a*(-1)
  449. proc negInt64(a: int64): int64 {.compilerproc.} =
  450. result = a*(-1)
  451. proc absInt(a: int): int {.compilerproc.} =
  452. result = if a < 0: a*(-1) else: a
  453. proc absInt64(a: int64): int64 {.compilerproc.} =
  454. result = if a < 0: a*(-1) else: a
  455. proc nimMin(a, b: int): int {.compilerproc.} = return if a <= b: a else: b
  456. proc nimMax(a, b: int): int {.compilerproc.} = return if a >= b: a else: b
  457. proc chckNilDisp(p: JSRef) {.compilerproc.} =
  458. if p == nil:
  459. sysFatal(NilAccessDefect, "cannot dispatch; dispatcher is nil")
  460. include "system/hti"
  461. proc isFatPointer(ti: PNimType): bool =
  462. # This has to be consistent with the code generator!
  463. return ti.base.kind notin {tyObject,
  464. tyArray, tyArrayConstr, tyTuple,
  465. tyOpenArray, tySet, tyVar, tyRef, tyPtr}
  466. proc nimCopy(dest, src: JSRef, ti: PNimType): JSRef {.compilerproc.}
  467. proc nimCopyAux(dest, src: JSRef, n: ptr TNimNode) {.compilerproc.} =
  468. case n.kind
  469. of nkNone: sysAssert(false, "nimCopyAux")
  470. of nkSlot:
  471. {.emit: """
  472. `dest`[`n`.offset] = nimCopy(`dest`[`n`.offset], `src`[`n`.offset], `n`.typ);
  473. """.}
  474. of nkList:
  475. {.emit: """
  476. for (var i = 0; i < `n`.sons.length; i++) {
  477. nimCopyAux(`dest`, `src`, `n`.sons[i]);
  478. }
  479. """.}
  480. of nkCase:
  481. {.emit: """
  482. `dest`[`n`.offset] = nimCopy(`dest`[`n`.offset], `src`[`n`.offset], `n`.typ);
  483. for (var i = 0; i < `n`.sons.length; ++i) {
  484. nimCopyAux(`dest`, `src`, `n`.sons[i][1]);
  485. }
  486. """.}
  487. proc nimCopy(dest, src: JSRef, ti: PNimType): JSRef =
  488. case ti.kind
  489. of tyPtr, tyRef, tyVar, tyNil:
  490. if not isFatPointer(ti):
  491. result = src
  492. else:
  493. {.emit: "`result` = [`src`[0], `src`[1]];".}
  494. of tySet:
  495. {.emit: """
  496. if (`dest` === null || `dest` === undefined) {
  497. `dest` = {};
  498. }
  499. else {
  500. for (var key in `dest`) { delete `dest`[key]; }
  501. }
  502. for (var key in `src`) { `dest`[key] = `src`[key]; }
  503. `result` = `dest`;
  504. """.}
  505. of tyTuple, tyObject:
  506. if ti.base != nil: result = nimCopy(dest, src, ti.base)
  507. elif ti.kind == tyObject:
  508. {.emit: "`result` = (`dest` === null || `dest` === undefined) ? {m_type: `ti`} : `dest`;".}
  509. else:
  510. {.emit: "`result` = (`dest` === null || `dest` === undefined) ? {} : `dest`;".}
  511. nimCopyAux(result, src, ti.node)
  512. of tyArrayConstr, tyArray:
  513. # In order to prevent a type change (TypedArray -> Array) and to have better copying performance,
  514. # arrays constructors are considered separately
  515. {.emit: """
  516. if(ArrayBuffer.isView(`src`)) {
  517. if(`dest` === null || `dest` === undefined || `dest`.length != `src`.length) {
  518. `dest` = new `src`.constructor(`src`);
  519. } else {
  520. `dest`.set(`src`, 0);
  521. }
  522. `result` = `dest`;
  523. } else {
  524. if (`src` === null) {
  525. `result` = null;
  526. }
  527. else {
  528. if (`dest` === null || `dest` === undefined || `dest`.length != `src`.length) {
  529. `dest` = new Array(`src`.length);
  530. }
  531. `result` = `dest`;
  532. for (var i = 0; i < `src`.length; ++i) {
  533. `result`[i] = nimCopy(`result`[i], `src`[i], `ti`.base);
  534. }
  535. }
  536. }
  537. """.}
  538. of tySequence, tyOpenArray:
  539. {.emit: """
  540. if (`src` === null) {
  541. `result` = null;
  542. }
  543. else {
  544. if (`dest` === null || `dest` === undefined || `dest`.length != `src`.length) {
  545. `dest` = new Array(`src`.length);
  546. }
  547. `result` = `dest`;
  548. for (var i = 0; i < `src`.length; ++i) {
  549. `result`[i] = nimCopy(`result`[i], `src`[i], `ti`.base);
  550. }
  551. }
  552. """.}
  553. of tyString:
  554. {.emit: """
  555. if (`src` !== null) {
  556. `result` = `src`.slice(0);
  557. }
  558. """.}
  559. else:
  560. result = src
  561. proc arrayConstr(len: int, value: JSRef, typ: PNimType): JSRef {.
  562. asmNoStackFrame, compilerproc.} =
  563. # types are fake
  564. {.emit: """
  565. var result = new Array(`len`);
  566. for (var i = 0; i < `len`; ++i) result[i] = nimCopy(null, `value`, `typ`);
  567. return result;
  568. """.}
  569. proc chckIndx(i, a, b: int): int {.compilerproc.} =
  570. if i >= a and i <= b: return i
  571. else: raiseIndexError(i, a, b)
  572. proc chckRange(i, a, b: int): int {.compilerproc.} =
  573. if i >= a and i <= b: return i
  574. else: raiseRangeError()
  575. proc chckObj(obj, subclass: PNimType) {.compilerproc.} =
  576. # checks if obj is of type subclass:
  577. var x = obj
  578. if x == subclass: return # optimized fast path
  579. while x != subclass:
  580. if x == nil:
  581. raise newException(ObjectConversionDefect, "invalid object conversion")
  582. x = x.base
  583. proc isObj(obj, subclass: PNimType): bool {.compilerproc.} =
  584. # checks if obj is of type subclass:
  585. var x = obj
  586. if x == subclass: return true # optimized fast path
  587. while x != subclass:
  588. if x == nil: return false
  589. x = x.base
  590. return true
  591. proc addChar(x: string, c: char) {.compilerproc, asmNoStackFrame.} =
  592. {.emit: "`x`.push(`c`);".}
  593. {.pop.}
  594. proc tenToThePowerOf(b: int): BiggestFloat =
  595. # xxx deadcode
  596. var b = b
  597. var a = 10.0
  598. result = 1.0
  599. while true:
  600. if (b and 1) == 1:
  601. result = result * a
  602. b = b shr 1
  603. if b == 0: break
  604. a = a * a
  605. const
  606. IdentChars = {'a'..'z', 'A'..'Z', '0'..'9', '_'}
  607. proc parseFloatNative(a: openarray[char]): float =
  608. var str = ""
  609. for x in a:
  610. str.add x
  611. let cstr = cstring str
  612. {.emit: """
  613. `result` = Number(`cstr`);
  614. """.}
  615. proc nimParseBiggestFloat(s: openarray[char], number: var BiggestFloat): int {.compilerproc.} =
  616. var sign: bool
  617. var i = 0
  618. if s[i] == '+': inc(i)
  619. elif s[i] == '-':
  620. sign = true
  621. inc(i)
  622. if s[i] == 'N' or s[i] == 'n':
  623. if s[i+1] == 'A' or s[i+1] == 'a':
  624. if s[i+2] == 'N' or s[i+2] == 'n':
  625. if s[i+3] notin IdentChars:
  626. number = NaN
  627. return i+3
  628. return 0
  629. if s[i] == 'I' or s[i] == 'i':
  630. if s[i+1] == 'N' or s[i+1] == 'n':
  631. if s[i+2] == 'F' or s[i+2] == 'f':
  632. if s[i+3] notin IdentChars:
  633. number = if sign: -Inf else: Inf
  634. return i+3
  635. return 0
  636. var buf: string
  637. # we could also use an `array[char, N]` buffer to avoid reallocs, or
  638. # use a 2-pass algorithm that first computes the length.
  639. if sign: buf.add '-'
  640. template addInc =
  641. buf.add s[i]
  642. inc(i)
  643. template eatUnderscores =
  644. while s[i] == '_': inc(i)
  645. while s[i] in {'0'..'9'}: # Read integer part
  646. buf.add s[i]
  647. inc(i)
  648. eatUnderscores()
  649. if s[i] == '.': # Decimal?
  650. addInc()
  651. while s[i] in {'0'..'9'}: # Read fractional part
  652. addInc()
  653. eatUnderscores()
  654. # Again, read integer and fractional part
  655. if buf.len == ord(sign): return 0
  656. if s[i] in {'e', 'E'}: # Exponent?
  657. addInc()
  658. if s[i] == '+': inc(i)
  659. elif s[i] == '-': addInc()
  660. if s[i] notin {'0'..'9'}: return 0
  661. while s[i] in {'0'..'9'}:
  662. addInc()
  663. eatUnderscores()
  664. number = parseFloatNative(buf)
  665. result = i
  666. # Workaround for IE, IE up to version 11 lacks 'Math.trunc'. We produce
  667. # 'Math.trunc' for Nim's ``div`` and ``mod`` operators:
  668. when defined(nimJsMathTruncPolyfill):
  669. {.emit: """
  670. if (!Math.trunc) {
  671. Math.trunc = function(v) {
  672. v = +v;
  673. if (!isFinite(v)) return v;
  674. return (v - v % 1) || (v < 0 ? -0 : v === 0 ? v : 0);
  675. };
  676. }
  677. """.}
  678. proc cmpClosures(a, b: JSRef): bool {.compilerproc, asmNoStackFrame.} =
  679. # Both `a` and `b` need to be a closure
  680. {.emit: """
  681. if (`a` !== null && `a`.ClP_0 !== undefined &&
  682. `b` !== null && `b`.ClP_0 !== undefined) {
  683. return `a`.ClP_0 == `b`.ClP_0 && `a`.ClE_0 == `b`.ClE_0;
  684. } else {
  685. return `a` == `b`;
  686. }
  687. """
  688. .}