jssys.nim 21 KB

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