jssys.nim 21 KB

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