jssys.nim 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  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. framePtr = nil
  116. {.emit: """
  117. if (typeof(Error) !== "undefined") {
  118. throw new Error(`cbuf`);
  119. }
  120. else {
  121. throw `cbuf`;
  122. }
  123. """.}
  124. proc raiseException(e: ref Exception, ename: cstring) {.
  125. compilerproc, asmNoStackFrame.} =
  126. e.name = ename
  127. if excHandler == 0:
  128. unhandledException(e)
  129. when NimStackTrace:
  130. e.trace = rawWriteStackTrace()
  131. asm "throw `e`;"
  132. proc reraiseException() {.compilerproc, asmNoStackFrame.} =
  133. if lastJSError == nil:
  134. raise newException(ReraiseDefect, "no exception to reraise")
  135. else:
  136. if excHandler == 0:
  137. if isNimException():
  138. unhandledException(cast[ref Exception](lastJSError))
  139. asm "throw lastJSError;"
  140. proc raiseOverflow {.exportc: "raiseOverflow", noreturn, compilerproc.} =
  141. raise newException(OverflowDefect, "over- or underflow")
  142. proc raiseDivByZero {.exportc: "raiseDivByZero", noreturn, compilerproc.} =
  143. raise newException(DivByZeroDefect, "division by zero")
  144. proc raiseRangeError() {.compilerproc, noreturn.} =
  145. raise newException(RangeDefect, "value out of range")
  146. proc raiseIndexError(i, a, b: int) {.compilerproc, noreturn.} =
  147. raise newException(IndexDefect, formatErrorIndexBound(int(i), int(a), int(b)))
  148. proc raiseFieldError2(f: string, discVal: string) {.compilerproc, noreturn.} =
  149. raise newException(FieldDefect, formatFieldDefect(f, discVal))
  150. proc setConstr() {.varargs, asmNoStackFrame, compilerproc.} =
  151. asm """
  152. var result = {};
  153. for (var i = 0; i < arguments.length; ++i) {
  154. var x = arguments[i];
  155. if (typeof(x) == "object") {
  156. for (var j = x[0]; j <= x[1]; ++j) {
  157. result[j] = true;
  158. }
  159. } else {
  160. result[x] = true;
  161. }
  162. }
  163. return result;
  164. """
  165. proc makeNimstrLit(c: cstring): string {.asmNoStackFrame, compilerproc.} =
  166. {.emit: """
  167. var result = [];
  168. for (var i = 0; i < `c`.length; ++i) {
  169. result[i] = `c`.charCodeAt(i);
  170. }
  171. return result;
  172. """.}
  173. proc cstrToNimstr(c: cstring): string {.asmNoStackFrame, compilerproc.} =
  174. {.emit: """
  175. var ln = `c`.length;
  176. var result = new Array(ln);
  177. var r = 0;
  178. for (var i = 0; i < ln; ++i) {
  179. var ch = `c`.charCodeAt(i);
  180. if (ch < 128) {
  181. result[r] = ch;
  182. }
  183. else {
  184. if (ch < 2048) {
  185. result[r] = (ch >> 6) | 192;
  186. }
  187. else {
  188. if (ch < 55296 || ch >= 57344) {
  189. result[r] = (ch >> 12) | 224;
  190. }
  191. else {
  192. ++i;
  193. ch = 65536 + (((ch & 1023) << 10) | (`c`.charCodeAt(i) & 1023));
  194. result[r] = (ch >> 18) | 240;
  195. ++r;
  196. result[r] = ((ch >> 12) & 63) | 128;
  197. }
  198. ++r;
  199. result[r] = ((ch >> 6) & 63) | 128;
  200. }
  201. ++r;
  202. result[r] = (ch & 63) | 128;
  203. }
  204. ++r;
  205. }
  206. return result;
  207. """.}
  208. proc toJSStr(s: string): cstring {.compilerproc.} =
  209. proc fromCharCode(c: char): cstring {.importc: "String.fromCharCode".}
  210. proc join(x: openArray[cstring]; d = cstring""): cstring {.
  211. importcpp: "#.join(@)".}
  212. proc decodeURIComponent(x: cstring): cstring {.
  213. importc: "decodeURIComponent".}
  214. proc toHexString(c: char; d = 16): cstring {.importcpp: "#.toString(@)".}
  215. proc log(x: cstring) {.importc: "console.log".}
  216. var res = newSeq[cstring](s.len)
  217. var i = 0
  218. var j = 0
  219. while i < s.len:
  220. var c = s[i]
  221. if c < '\128':
  222. res[j] = fromCharCode(c)
  223. inc i
  224. else:
  225. var helper = newSeq[cstring]()
  226. while true:
  227. let code = toHexString(c)
  228. if code.len == 1:
  229. helper.add cstring"%0"
  230. else:
  231. helper.add cstring"%"
  232. helper.add code
  233. inc i
  234. if i >= s.len or s[i] < '\128': break
  235. c = s[i]
  236. try:
  237. res[j] = decodeURIComponent join(helper)
  238. except:
  239. res[j] = join(helper)
  240. inc j
  241. setLen(res, j)
  242. result = join(res)
  243. proc mnewString(len: int): string {.asmNoStackFrame, compilerproc.} =
  244. asm """
  245. return new Array(`len`);
  246. """
  247. proc SetCard(a: int): int {.compilerproc, asmNoStackFrame.} =
  248. # argument type is a fake
  249. asm """
  250. var result = 0;
  251. for (var elem in `a`) { ++result; }
  252. return result;
  253. """
  254. proc SetEq(a, b: int): bool {.compilerproc, asmNoStackFrame.} =
  255. asm """
  256. for (var elem in `a`) { if (!`b`[elem]) return false; }
  257. for (var elem in `b`) { if (!`a`[elem]) return false; }
  258. return true;
  259. """
  260. proc SetLe(a, b: int): bool {.compilerproc, asmNoStackFrame.} =
  261. asm """
  262. for (var elem in `a`) { if (!`b`[elem]) return false; }
  263. return true;
  264. """
  265. proc SetLt(a, b: int): bool {.compilerproc.} =
  266. result = SetLe(a, b) and not SetEq(a, b)
  267. proc SetMul(a, b: int): int {.compilerproc, asmNoStackFrame.} =
  268. asm """
  269. var result = {};
  270. for (var elem in `a`) {
  271. if (`b`[elem]) { result[elem] = true; }
  272. }
  273. return result;
  274. """
  275. proc SetPlus(a, b: int): int {.compilerproc, asmNoStackFrame.} =
  276. asm """
  277. var result = {};
  278. for (var elem in `a`) { result[elem] = true; }
  279. for (var elem in `b`) { result[elem] = true; }
  280. return result;
  281. """
  282. proc SetMinus(a, b: int): int {.compilerproc, asmNoStackFrame.} =
  283. asm """
  284. var result = {};
  285. for (var elem in `a`) {
  286. if (!`b`[elem]) { result[elem] = true; }
  287. }
  288. return result;
  289. """
  290. proc cmpStrings(a, b: string): int {.asmNoStackFrame, compilerproc.} =
  291. asm """
  292. if (`a` == `b`) return 0;
  293. if (!`a`) return -1;
  294. if (!`b`) return 1;
  295. for (var i = 0; i < `a`.length && i < `b`.length; i++) {
  296. var result = `a`[i] - `b`[i];
  297. if (result != 0) return result;
  298. }
  299. return `a`.length - `b`.length;
  300. """
  301. proc cmp(x, y: string): int =
  302. when nimvm:
  303. if x == y: result = 0
  304. elif x < y: result = -1
  305. else: result = 1
  306. else:
  307. result = cmpStrings(x, y)
  308. proc eqStrings(a, b: string): bool {.asmNoStackFrame, compilerproc.} =
  309. asm """
  310. if (`a` == `b`) return true;
  311. if (`a` === null && `b`.length == 0) return true;
  312. if (`b` === null && `a`.length == 0) return true;
  313. if ((!`a`) || (!`b`)) return false;
  314. var alen = `a`.length;
  315. if (alen != `b`.length) return false;
  316. for (var i = 0; i < alen; ++i)
  317. if (`a`[i] != `b`[i]) return false;
  318. return true;
  319. """
  320. when defined(kwin):
  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. print(buf);
  328. """
  329. elif not defined(nimOldEcho):
  330. proc ewriteln(x: cstring) = log(x)
  331. proc rawEcho {.compilerproc, asmNoStackFrame.} =
  332. asm """
  333. var buf = "";
  334. for (var i = 0; i < arguments.length; ++i) {
  335. buf += `toJSStr`(arguments[i]);
  336. }
  337. console.log(buf);
  338. """
  339. else:
  340. proc ewriteln(x: cstring) =
  341. var node : JSRef
  342. {.emit: "`node` = document.getElementsByTagName('body')[0];".}
  343. if node.isNil:
  344. raise newException(ValueError, "<body> element does not exist yet!")
  345. {.emit: """
  346. `node`.appendChild(document.createTextNode(`x`));
  347. `node`.appendChild(document.createElement("br"));
  348. """.}
  349. proc rawEcho {.compilerproc.} =
  350. var node : JSRef
  351. {.emit: "`node` = document.getElementsByTagName('body')[0];".}
  352. if node.isNil:
  353. raise newException(IOError, "<body> element does not exist yet!")
  354. {.emit: """
  355. for (var i = 0; i < arguments.length; ++i) {
  356. var x = `toJSStr`(arguments[i]);
  357. `node`.appendChild(document.createTextNode(x));
  358. }
  359. `node`.appendChild(document.createElement("br"));
  360. """.}
  361. # Arithmetic:
  362. proc checkOverflowInt(a: int) {.asmNoStackFrame, compilerproc.} =
  363. asm """
  364. if (`a` > 2147483647 || `a` < -2147483648) `raiseOverflow`();
  365. """
  366. proc addInt(a, b: int): int {.asmNoStackFrame, compilerproc.} =
  367. asm """
  368. var result = `a` + `b`;
  369. `checkOverflowInt`(result);
  370. return result;
  371. """
  372. proc subInt(a, b: int): int {.asmNoStackFrame, compilerproc.} =
  373. asm """
  374. var result = `a` - `b`;
  375. `checkOverflowInt`(result);
  376. return result;
  377. """
  378. proc mulInt(a, b: int): int {.asmNoStackFrame, compilerproc.} =
  379. asm """
  380. var result = `a` * `b`;
  381. `checkOverflowInt`(result);
  382. return result;
  383. """
  384. proc divInt(a, b: int): int {.asmNoStackFrame, compilerproc.} =
  385. asm """
  386. if (`b` == 0) `raiseDivByZero`();
  387. if (`b` == -1 && `a` == 2147483647) `raiseOverflow`();
  388. return Math.trunc(`a` / `b`);
  389. """
  390. proc modInt(a, b: int): int {.asmNoStackFrame, compilerproc.} =
  391. asm """
  392. if (`b` == 0) `raiseDivByZero`();
  393. if (`b` == -1 && `a` == 2147483647) `raiseOverflow`();
  394. return Math.trunc(`a` % `b`);
  395. """
  396. proc checkOverflowInt64(a: int) {.asmNoStackFrame, compilerproc.} =
  397. asm """
  398. if (`a` > 9223372036854775807 || `a` < -9223372036854775808) `raiseOverflow`();
  399. """
  400. proc addInt64(a, b: int): int {.asmNoStackFrame, compilerproc.} =
  401. asm """
  402. var result = `a` + `b`;
  403. `checkOverflowInt64`(result);
  404. return result;
  405. """
  406. proc subInt64(a, b: int): int {.asmNoStackFrame, compilerproc.} =
  407. asm """
  408. var result = `a` - `b`;
  409. `checkOverflowInt64`(result);
  410. return result;
  411. """
  412. proc mulInt64(a, b: int): int {.asmNoStackFrame, compilerproc.} =
  413. asm """
  414. var result = `a` * `b`;
  415. `checkOverflowInt64`(result);
  416. return result;
  417. """
  418. proc divInt64(a, b: int): int {.asmNoStackFrame, compilerproc.} =
  419. asm """
  420. if (`b` == 0) `raiseDivByZero`();
  421. if (`b` == -1 && `a` == 9223372036854775807) `raiseOverflow`();
  422. return Math.trunc(`a` / `b`);
  423. """
  424. proc modInt64(a, b: int): int {.asmNoStackFrame, compilerproc.} =
  425. asm """
  426. if (`b` == 0) `raiseDivByZero`();
  427. if (`b` == -1 && `a` == 9223372036854775807) `raiseOverflow`();
  428. return Math.trunc(`a` % `b`);
  429. """
  430. proc negInt(a: int): int {.compilerproc.} =
  431. result = a*(-1)
  432. proc negInt64(a: int64): int64 {.compilerproc.} =
  433. result = a*(-1)
  434. proc absInt(a: int): int {.compilerproc.} =
  435. result = if a < 0: a*(-1) else: a
  436. proc absInt64(a: int64): int64 {.compilerproc.} =
  437. result = if a < 0: a*(-1) else: a
  438. when not defined(nimNoZeroExtendMagic):
  439. proc ze*(a: int): int {.compilerproc.} =
  440. result = a
  441. proc ze64*(a: int64): int64 {.compilerproc.} =
  442. result = a
  443. proc toU8*(a: int): int8 {.asmNoStackFrame, compilerproc.} =
  444. asm """
  445. return `a`;
  446. """
  447. proc toU16*(a: int): int16 {.asmNoStackFrame, compilerproc.} =
  448. asm """
  449. return `a`;
  450. """
  451. proc toU32*(a: int64): int32 {.asmNoStackFrame, compilerproc.} =
  452. asm """
  453. return `a`;
  454. """
  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: pointer) {.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. asm """
  472. `dest`[`n`.offset] = nimCopy(`dest`[`n`.offset], `src`[`n`.offset], `n`.typ);
  473. """
  474. of nkList:
  475. asm """
  476. for (var i = 0; i < `n`.sons.length; i++) {
  477. nimCopyAux(`dest`, `src`, `n`.sons[i]);
  478. }
  479. """
  480. of nkCase:
  481. asm """
  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. asm "`result` = [`src`[0], `src`[1]];"
  494. of tySet:
  495. asm """
  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. asm "`result` = (`dest` === null || `dest` === undefined) ? {m_type: `ti`} : `dest`;"
  509. else:
  510. asm "`result` = (`dest` === null || `dest` === undefined) ? {} : `dest`;"
  511. nimCopyAux(result, src, ti.node)
  512. of tySequence, tyArrayConstr, tyOpenArray, tyArray:
  513. asm """
  514. if (`src` === null) {
  515. `result` = null;
  516. }
  517. else {
  518. if (`dest` === null || `dest` === undefined || `dest`.length != `src`.length) {
  519. `dest` = new Array(`src`.length);
  520. }
  521. `result` = `dest`;
  522. for (var i = 0; i < `src`.length; ++i) {
  523. `result`[i] = nimCopy(`result`[i], `src`[i], `ti`.base);
  524. }
  525. }
  526. """
  527. of tyString:
  528. asm """
  529. if (`src` !== null) {
  530. `result` = `src`.slice(0);
  531. }
  532. """
  533. else:
  534. result = src
  535. proc genericReset(x: JSRef, ti: PNimType): JSRef {.compilerproc.} =
  536. asm "`result` = null;"
  537. case ti.kind
  538. of tyPtr, tyRef, tyVar, tyNil:
  539. if isFatPointer(ti):
  540. asm """
  541. `result` = [null, 0];
  542. """
  543. of tySet:
  544. asm """
  545. `result` = {};
  546. """
  547. of tyTuple, tyObject:
  548. if ti.kind == tyObject:
  549. asm "`result` = {m_type: `ti`};"
  550. else:
  551. asm "`result` = {};"
  552. of tySequence, tyOpenArray, tyString:
  553. asm """
  554. `result` = [];
  555. """
  556. of tyArrayConstr, tyArray:
  557. asm """
  558. `result` = new Array(`x`.length);
  559. for (var i = 0; i < `x`.length; ++i) {
  560. `result`[i] = genericReset(`x`[i], `ti`.base);
  561. }
  562. """
  563. else:
  564. discard
  565. proc arrayConstr(len: int, value: JSRef, typ: PNimType): JSRef {.
  566. asmNoStackFrame, compilerproc.} =
  567. # types are fake
  568. asm """
  569. var result = new Array(`len`);
  570. for (var i = 0; i < `len`; ++i) result[i] = nimCopy(null, `value`, `typ`);
  571. return result;
  572. """
  573. proc chckIndx(i, a, b: int): int {.compilerproc.} =
  574. if i >= a and i <= b: return i
  575. else: raiseIndexError(i, a, b)
  576. proc chckRange(i, a, b: int): int {.compilerproc.} =
  577. if i >= a and i <= b: return i
  578. else: raiseRangeError()
  579. proc chckObj(obj, subclass: PNimType) {.compilerproc.} =
  580. # checks if obj is of type subclass:
  581. var x = obj
  582. if x == subclass: return # optimized fast path
  583. while x != subclass:
  584. if x == nil:
  585. raise newException(ObjectConversionDefect, "invalid object conversion")
  586. x = x.base
  587. proc isObj(obj, subclass: PNimType): bool {.compilerproc.} =
  588. # checks if obj is of type subclass:
  589. var x = obj
  590. if x == subclass: return true # optimized fast path
  591. while x != subclass:
  592. if x == nil: return false
  593. x = x.base
  594. return true
  595. proc addChar(x: string, c: char) {.compilerproc, asmNoStackFrame.} =
  596. asm "`x`.push(`c`);"
  597. {.pop.}
  598. proc tenToThePowerOf(b: int): BiggestFloat =
  599. # xxx deadcode
  600. var b = b
  601. var a = 10.0
  602. result = 1.0
  603. while true:
  604. if (b and 1) == 1:
  605. result = result * a
  606. b = b shr 1
  607. if b == 0: break
  608. a = a * a
  609. const
  610. IdentChars = {'a'..'z', 'A'..'Z', '0'..'9', '_'}
  611. proc parseFloatNative(a: string): float =
  612. let a2 = a.cstring
  613. asm """
  614. `result` = Number(`a2`);
  615. """
  616. #[
  617. xxx how come code like this doesn't give IndexDefect ?
  618. let z = s[10000] == 'a'
  619. ]#
  620. proc nimParseBiggestFloat(s: string, number: var BiggestFloat, start: int): int {.compilerproc.} =
  621. var sign: bool
  622. var i = start
  623. if s[i] == '+': inc(i)
  624. elif s[i] == '-':
  625. sign = true
  626. inc(i)
  627. if s[i] == 'N' or s[i] == 'n':
  628. if s[i+1] == 'A' or s[i+1] == 'a':
  629. if s[i+2] == 'N' or s[i+2] == 'n':
  630. if s[i+3] notin IdentChars:
  631. number = NaN
  632. return i+3 - start
  633. return 0
  634. if s[i] == 'I' or s[i] == 'i':
  635. if s[i+1] == 'N' or s[i+1] == 'n':
  636. if s[i+2] == 'F' or s[i+2] == 'f':
  637. if s[i+3] notin IdentChars:
  638. number = if sign: -Inf else: Inf
  639. return i+3 - start
  640. return 0
  641. var buf: string
  642. # we could also use an `array[char, N]` buffer to avoid reallocs, or
  643. # use a 2-pass algorithm that first computes the length.
  644. if sign: buf.add '-'
  645. template addInc =
  646. buf.add s[i]
  647. inc(i)
  648. template eatUnderscores =
  649. while s[i] == '_': inc(i)
  650. while s[i] in {'0'..'9'}: # Read integer part
  651. buf.add s[i]
  652. inc(i)
  653. eatUnderscores()
  654. if s[i] == '.': # Decimal?
  655. addInc()
  656. while s[i] in {'0'..'9'}: # Read fractional part
  657. addInc()
  658. eatUnderscores()
  659. # Again, read integer and fractional part
  660. if buf.len == ord(sign): return 0
  661. if s[i] in {'e', 'E'}: # Exponent?
  662. addInc()
  663. if s[i] == '+': inc(i)
  664. elif s[i] == '-': addInc()
  665. if s[i] notin {'0'..'9'}: return 0
  666. while s[i] in {'0'..'9'}:
  667. addInc()
  668. eatUnderscores()
  669. number = parseFloatNative(buf)
  670. result = i - start
  671. # Workaround for IE, IE up to version 11 lacks 'Math.trunc'. We produce
  672. # 'Math.trunc' for Nim's ``div`` and ``mod`` operators:
  673. const jsMathTrunc = """
  674. if (!Math.trunc) {
  675. Math.trunc = function(v) {
  676. v = +v;
  677. if (!isFinite(v)) return v;
  678. return (v - v % 1) || (v < 0 ? -0 : v === 0 ? v : 0);
  679. };
  680. }
  681. """
  682. when not defined(nodejs): {.emit: jsMathTrunc .}