jssys.nim 20 KB

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