Compare commits

..

2213 Commits

Author SHA1 Message Date
ringabout
ce295d7243 fixes broken CI; bump macOS version to macos-11 (#20098)
* bump macOS image on Azure CI to macos-11
* fix CI error

(cherry picked from commit 8ef509b85b)
2022-07-28 07:47:52 +02:00
narimiran
c6e0983b47 fix typo 2022-07-20 11:20:33 +02:00
narimiran
c5cd23a776 fix important_packages 2022-07-20 11:19:41 +02:00
Tanguy
30ba13d22a Fix nested finally handling in closureiters [backport] (#19933)
* Fix nested finally handling in closureiters

* Fix CI

* review comment

* third time the charm

* Update compiler/closureiters.nim

Co-authored-by: Dominik Picheta <dominikpicheta@googlemail.com>

Co-authored-by: Dominik Picheta <dominikpicheta@googlemail.com>
(cherry picked from commit fb5fbf1e08)
2022-07-18 17:27:29 +02:00
narimiran
315f4ecff1 disable testing of 'fragments' package 2022-01-17 11:25:51 +01:00
flywind
49379e85ec mangle names in nimbase.h using cppDefine (#19395) [backport]
mangle names in nimbase.h
fix comments

(cherry picked from commit 4f6b59de96)
2022-01-17 11:18:03 +01:00
flywind
6ab3c1b365 nrvo shouldn't touch bycopy object[backport:1.2] (#19385)
fix nim-lang#19342

(cherry picked from commit 9b9ae8a487)
2022-01-17 07:40:43 +01:00
Ștefan Talpalaru
0dae9115c8 Nim-1.4: style fix (#19317)
this allows "--styleCheck:usages --styleCheck:error"
2022-01-05 01:31:09 +08:00
flywind
32882fa024 disable packages which doesn't support 1.4 (#19320)
ref https://github.com/nim-lang/Nim/pull/19317
2022-01-04 11:11:07 +01:00
Andreas Rumpf
dc1e948f15 Revert "Update uri.nim (#19148) [backport:1.0]" (#19280)
This reverts commit a3ef5df680.

(cherry picked from commit 81d32cf7e5)
2021-12-31 05:14:52 +01:00
Miran
65db3013a8 [backport:1.0] json: limit recursion depth (#19252)
* json: limit recursion depth

* do not run this check for JS backend

(cherry picked from commit c17baaefbc)
2021-12-14 18:21:19 +01:00
flywind
7f0e662032 oids: switch from PRNG to random module (#16203)
* switch from PRNG to random module
* fix the regression
* comments + tests
* runnableExamples
* make oids better

(cherry picked from commit 89a21e4ec7)
2021-12-13 15:03:56 +01:00
Dominik Picheta
547973c3e9 Update uri.nim (#19148) [backport:1.0]
(cherry picked from commit a3ef5df680)
2021-12-11 09:25:34 +01:00
Ștefan Talpalaru
4d5c5893ae nimc.rst: fix table markup (#19239)
(cherry picked from commit 1a92edeb89)
2021-12-11 05:48:23 +01:00
Ștefan Talpalaru
8c356fd971 nimRawSetjmp: support Windows (#19197)
* nimRawSetjmp: support Windows

Using `_setjmp()` directly is required to avoid some rare (but very
annoying) exception-related stack corruption leading to segfaults on
Windows, with Mingw-w64 and SEH.
More details: https://github.com/status-im/nimbus-eth2/issues/3121

Also add "nimBuiltinSetjmp" - mostly for benchmarking.

* fix for Apple's Clang++

(cherry picked from commit 69aabdab80)
2021-12-11 05:48:19 +01:00
Andreas Rumpf
17522d6ae1 fixes a possible 'javascript:' protocol exploit [backport:1.0] (#19134)
* fixes a possible 'javascript:' protocol exploit [backport:1.0]

* add tests

* Update tests/stdlib/trstgen.nim

* add the same logic for hyperlinks

* move the logic into a proc

Co-authored-by: narimiran <narimiran@disroot.org>
(cherry picked from commit 9338aa2497)
2021-12-10 11:56:52 +01:00
Tanguy
f8047c3e3c fix #19193 (#19195) [backport:1.2]
(cherry picked from commit cd592ed85b)
2021-12-10 11:50:13 +01:00
Etan Kissling
cfb6ebc07a allow HSlice bounded by constants of distinct types (#19219) [backport:1.2]
When creating heterogenous slices of distinct types, the compiler does
not initialize the internal type's `size` before accessing it.
This then leads to this crash message:
```
compiler/int128.nim(594, 11) `false` masking only implemented for 1, 2, 4 and 8 bytes [AssertionError]
```
This patch initializes the `size` properly, fixing the problem.

(cherry picked from commit 0213c7313b)
2021-12-10 11:49:39 +01:00
narimiran
8f20400466 we must use Ubuntu 18.04 2021-12-07 20:34:33 +01:00
Andreas Rumpf
6d3b706f6e misc bugfixes [backport:1.2] (#19203)
(cherry picked from commit 23c117a950)
2021-12-06 12:48:37 +01:00
Andreas Rumpf
0df0510722 fixes #14470 [backport:1.2] (#19115)
(cherry picked from commit 15157d06c3)
2021-12-06 12:41:49 +01:00
Andreas Rumpf
68df3c9afd fixes a 'mixin' statement handling regression [backport:1.2] (#18968)
(cherry picked from commit 8eef557157)
2021-12-06 12:41:33 +01:00
Etan Kissling
a8aaf5a27d allow converting static vars to openArray (#19048)
When assigning constant output to a seq, and then passing that static
seq to other functions that take `openArray`, the compiler may end up
producing errors, as it does not know how to convert `static[seq[T]]`
to `openArray[T]`. By ignoring the `static` wrapper on the type for
the purpose of determining data memory location and length, this gets
resolved cleanly. Unfortunately, it is relatively tricky to come up
with a minimal example, as there are followup problems from the failing
conversion, e.g., this may lead to `internal error: inconsistent
environment type`, instead of the relevant `openArrayLoc` error message.

(cherry picked from commit 490c4226a5)
2021-10-27 11:04:04 +02:00
flywind
80c8107c56 [tools] use the right parameter [backport:1.0] (#18957)
(cherry picked from commit b2873f0f63)
2021-10-06 13:41:18 +02:00
Andreas Rumpf
5bed375b52 fixes #16325 [backport:1.4] (#18784)
(cherry picked from commit a7cae2bda2)
2021-09-02 20:25:46 +02:00
Dankr4d
1228c5b3fc fixes #14511 [backport:1.4] (#18732)
* fixes #14511 [backport:1.4]

Signed-off-by: Dankr4d <dude569@freenet.de>

* Replaced fix with code from alaviss, for better readability, with small
changes.

Signed-off-by: Dankr4d <dude569@freenet.de>

* - Specified output in test.

Signed-off-by: Dankr4d <dude569@freenet.de>

* Replaced case in nnkRecCase with a simpler version, which just adds the
last son.

Signed-off-by: Dankr4d <dude569@freenet.de>

* Update tests/macros/t14511.nim

* Update tests/macros/t14511.nim

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
(cherry picked from commit c70e4040bd)
2021-09-02 20:25:39 +02:00
narimiran
0a8e9318d3 fix broken test 2021-08-24 07:28:19 +02:00
narimiran
22650a61e7 bump NimVersion to 1.4.9 2021-08-24 07:21:56 +02:00
flywind
8b80039cac fix #18702(fix parseutils.parseFloat) (#18703) [backport:1.0]
* fix #18702
* Apply suggestions from code review

(cherry picked from commit 901c5ded52)
2021-08-24 07:10:48 +02:00
Andreas Rumpf
b18c6fd09b fixes #18643 [backport:1.0] (#18678)
(cherry picked from commit 018465a234)
2021-08-24 07:10:26 +02:00
Andreas Rumpf
88340aab6d fixes #18411 (#18432) [backport:1.4]
(cherry picked from commit 1bed777314)
2021-08-24 07:09:10 +02:00
flywind
8a3e64f00e fixes #17768 [backport:1.4] (#18317)
* fixes #17768 [backport:1.4]

* tiny

(cherry picked from commit 2deb7011f5)
2021-08-24 07:09:00 +02:00
Timothee Cour
6c5585fc0b link stable and devel docs in nim docs (#18272) [backport:1.2]
(cherry picked from commit d3b27eb63e)
2021-08-24 07:08:47 +02:00
Yuriy Glukhov
ca1b7feb0f Fixes #17849 (#18055) [backport:1.2]
* Fixes #17849
* Update compiler/closureiters.nim

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
(cherry picked from commit a6bd6c7ed8)
2021-08-24 07:08:34 +02:00
narimiran
44e653a931 bump NimVersion to 1.4.8 2021-05-24 16:47:31 +02:00
narimiran
0250c4710d fix ccgexprs 2021-05-20 21:07:43 +02:00
Andreas Rumpf
8001c7be98 config system: special case -d:release and -d:danger [backport:1.4] (#18051)
(cherry picked from commit df429fa287)
2021-05-20 13:21:56 +02:00
Ștefan Talpalaru
94f80f5bcb asyncdispatch+stackTraceOverride: fix premature collection (#18039) [backport:1.2]
Copying StackTraceEntry instances when nimStackTraceOverride is defined
breaks the link between a cstring field that's supposed to point at
another string field in the same object.

Sometimes, the original object is garbage collected, that memory region
reused for storing other strings, so when the StackTraceEntry copy tries
to use its cstring pointer to construct a traceback message, it accesses
unrelated strings.

This only happens for async tracebacks and this patch prevents that by
making sure we only use the string fields when nimStackTraceOverride is
defined.

Async tracebacks also beautified slightly by getting rid of an extra line
that was supposed to be commented out, along with the corresponding debugging output.

There's also a micro-optimisation to avoid concatenating two strings just
to get their combined length.

(cherry picked from commit a1c82c39af)
2021-05-19 19:53:08 +02:00
Andreas Rumpf
1281d8dfb8 ARC: fixes memory leaks with newSeq used in a loop [backport:1.4] (#18040)
* ARC: fixes memory leaks with newSeq used in a loop [backport:1.4]
* Update tests/arc/tnewseq_legacy.nim

(cherry picked from commit 53935b8b27)
2021-05-19 18:20:21 +02:00
Thomas T. Jarløv
7a8817e87f Escape %00 / \0 in dbQuote (#18015) [backport:1.4]
Fix https://github.com/nim-lang/Nim/issues/17925

(cherry picked from commit 99788ee504)
2021-05-19 18:20:13 +02:00
Timothee Cour
a63d434180 refs #18011 disable some newly failing tests on cpp windows; refs #17946 increase timeout for tchannels (#18012)
(cherry picked from commit 2ce592a209)
2021-05-17 16:03:42 +02:00
Andreas Rumpf
9fc0955587 ORC: progress (#18000)
* ORC: progress

* ORC: bugfix; don't follow acyclic data even if only at runtime the subtype is marked as acyclic

* progress

* minor style changes

(cherry picked from commit 3bc625aff1)
2021-05-14 13:31:00 +02:00
Andreas Rumpf
cb22a99584 ORC: improvements (#17993)
* ORC: improvements
* ORC: fix .acyclic annotation for ref objects

(cherry picked from commit 39ad9a69a9)
2021-05-14 13:23:36 +02:00
Andreas Rumpf
ad5c784d22 ORC: critical bugfix for mixing acyclic refs with cyclic refs [backport:1.4] (#17991)
(cherry picked from commit 2c2ec48bc4)
2021-05-14 13:18:09 +02:00
Andreas Rumpf
a6d84179fc feature: the compiler can warn when you use the implicit 'result' variable (#17988) [backport:1.2]
* implements #17855

(cherry picked from commit 378ee7f888)
2021-05-14 13:14:52 +02:00
Andreas Rumpf
e4d5139de0 fixes #15848 [backport:1.2] (#17959)
(cherry picked from commit 51f3ef6cb8)
2021-05-14 13:12:45 +02:00
narimiran
9d23c14dd2 some other files need the same change too 2021-04-30 11:00:19 +02:00
narimiran
daad1cd9d9 do the same for build_all.bat too 2021-04-30 10:57:17 +02:00
narimiran
61ac87a2b8 use csources_v1 in build_all.sh 2021-04-30 10:55:06 +02:00
Dankr4d
f825c8f691 Fix #17755 (#17766)
Signed-off-by: Dankr4d <dude569@freenet.de>
(cherry picked from commit 6916faf83c)
2021-04-28 13:51:29 +02:00
Yuriy Glukhov
4b4ef2b4b3 Check for errors after sendPendingSslData (#16696)
* Check for errors after sendPendingSslData

* Leftover comment removed

(cherry picked from commit 165d39738d)
2021-04-28 13:50:51 +02:00
Yuriy Glukhov
431eb05708 Fixes #16436 (#16695)
* Fixes #16436

* Comments addressed

(cherry picked from commit 4ae520711d)
2021-04-28 13:50:30 +02:00
Andreas Rumpf
3e154e7740 CIs: attempt to use csources_v1 (#16282)
* CIs: attempt to use csources_v1
* also updated the BSDs
* also updated azure pipelines
* std modules should not itself use the 'std/' import dir...
* compiler has to be careful with std/ for v1 booting

(cherry picked from commit a9b62de895)
2021-04-28 08:35:00 +02:00
shirleyquirk
e70044fb28 Fix buffer-overrun bug in net (#17728) [backport:1.0]
(cherry picked from commit fdd4391534)
2021-04-21 15:09:35 +02:00
Joey
5618a34d61 Fix Httpclient headers from being modified accidentally (#17808)
(cherry picked from commit f1ce173283)
2021-04-21 15:08:48 +02:00
Miran
f48daa29f6 fix #16506 by changing the example (#16580)
Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
(cherry picked from commit d2f4f25b56)
2021-04-21 15:08:01 +02:00
narimiran
2640dc2637 bump NimVersion to 1.4.7 2021-04-21 15:07:19 +02:00
zah
2b6b080323 Remove the use of usrToCell in gcMark [backport:1.2] (#17709)
* Remove the use of usrToCell in gcMark [backport:1.2]

Recently, we've discovered a GC crash resulting from inlining of
the memory allocation procs that allowed the compiler to avoid
maintaining any references to the "user pointer" on the stack.
Instead, a "cell pointer" appeared there and all field accesses
were performed with adjusted offsets. This interfered with the
ability of the GC to mark the correct cell in the conservative
stack scans which lead to premature collection of objects.

More details here:
af69b3ceae

This commit closes another theoretical loophole that may lead to
the same problem. If a short proc is accessing both the object and
its reference count in a short sequence of instructions, the compiler
may be enticed to reduce the number of registers being used by storing
only a single pointer to the object and using offsets when reading
and writing fields. A perfectly good strategy would be to store only
the cell pointer, so the reference count updates can be performed
without applying offsets. Accessing the fields of the object requires
offsets anyway, but these can be adjusted at compile-time without any
loss. Following this strategy will lead to the same problem of marking
a wrong cell during the conservative stack scan, leading to premature
collection.

The problem is avoided by not using `usrToCell` in `gcMark`. Since
the cell discovery logic can already handle interior pointers, the
user pointers don't need to be adjusted for the GC to function correctly.

(cherry picked from commit 3b47a689cf)
2021-04-14 12:10:29 +02:00
narimiran
ab1ae92587 bump NimVersion to 1.4.6 2021-04-13 21:51:50 +02:00
narimiran
5dd88ca1a4 [ci skip] minor: fix indentation in manual.rst
(cherry picked from commit d3529d0d5a)
2021-03-31 13:42:11 +02:00
Miran
598d9f8402 [backport:1.2] Avoid inlining of newObj and newObjRC1 calls (#17582)
This is taken from:
af69b3ceae

Full original comment:

This is to avoid heavy inlining happening when two allocation calls
would occur shortly after each other.

This inlining would sometimes be accompanied with an optimisation
as the compiler is able to see that cellToUsr ending the first
allocation call is shortly followed by an usrToCell call. The
pointer arithmetic is redundant and the compiler can eliminate it,
leaving only the cell address in a register (and later the stack)
instead of the actual pointer to the user data, as one would expect.

This combined with a GC collect cycle will cause the stack scan to
only notice the cell address, which is of no good due to a usrToCell
in the gcMark call which shifts that address to an adjacent cell.
This means that the actual cell of importance will not get marked
and thus cause a premature collection of that cell. BOOM.

(cherry picked from commit 40093b4a93)
2021-03-30 11:47:28 +02:00
Danil Yarantsev
f7f7a02915 Free the certificate after checking in checkCertName (#17558) [backport:1.2]
* Fix small leak in checkCertName
* Size is not needed either
* Free the certificate after checking

(cherry picked from commit b36182b0a4)
2021-03-29 15:31:30 +02:00
Timothee Cour
28b301cbaa fix #17454 (#17461)
(cherry picked from commit d78ebe4a0e)
2021-03-29 15:27:09 +02:00
narimiran
69c2c05463 bump NimVersion to 1.4.5 2021-03-26 09:02:30 +01:00
Andreas Rumpf
cc6bc8960d closes #17085; boehm has problems with large allocations, that is expected and we don't care (#17487)
(cherry picked from commit 8ccde68f13)
2021-03-24 18:20:19 +01:00
narimiran
05991805fb change back part of the test 2021-03-24 18:19:42 +01:00
narimiran
82561f31eb backport json-related part of #17469 2021-03-24 17:48:39 +01:00
Timothee Cour
e5027dc3da fix #17383: json.%,to and jsonutils.formJson,toJson now works with uint|uint64 (#17389) [backport:1.2]
* fix #17383: json.%,to and jsonutils.formJson,toJson now works with uint|uint64
* fixup
* fix for js

(cherry picked from commit 895a40d1ac)
2021-03-19 15:49:56 +01:00
Igor Ribeiro de Assis
f97d840f96 Fix FutureStream memory usage (#17395) [backport:1.2]
(cherry picked from commit 9bb0e55749)
2021-03-18 17:23:06 +01:00
xioren
560800246e Relocate 4xx/5xx exception in downloadFile (#17332) [backport:1.2]
Move 4xx/5xx exception to before disk i/o. As it stands an empty file is created on http error 4xx/5xx.

(cherry picked from commit 3d198fdcc2)
2021-03-18 14:08:54 +01:00
Andreas Rumpf
cf1ecee794 fixes #11225; generic sandwich problems; [backport:1.2] (#17255)
* fixes #11225; generic sandwich problems; [backport:1.2]
* progress
* delegating these symbols must be done via 'bind'

(cherry picked from commit 2f213db7ee)
2021-03-18 14:08:54 +01:00
flywind
6b00463074 Add unsafeIsolate and extract to std/isolation [backport:1.4] (#17263)
(cherry picked from commit 19be5eb1eb)
2021-03-18 14:08:54 +01:00
flywind
e996d98a8a fix #16384 and #17144 (#17126) [backport]
(cherry picked from commit 6391f6e861)
2021-03-18 14:08:54 +01:00
flywind
5c88067953 fix #17264 [backport:1.4] (#17266)
* fix #17264
* fix vm
* fix js and add tests

(cherry picked from commit 171b03c386)
2021-03-18 13:13:51 +01:00
alaviss
061d106671 compiler/installer.ini: package cacert.pem on Windows [backport:1.2] (#17172)
Follow up of 5dc544e1f5

After updating windeps.zip, it appears that Windows' build was
unchanged. As it turns out, cacert.pem is not set for packaging by the
compiler package manifest.

This commit add cacert.pem to the Windows package.

(cherry picked from commit d35f366d6f)
2021-03-18 08:33:16 +01:00
Andreas Rumpf
c2e2f50d35 fixes yet another SSL problem on Windows [backport:1.2] (#17167)
(cherry picked from commit b48a32053f)
2021-03-18 08:32:40 +01:00
narimiran
2ff517462b remove tests for stuff not available in 1.4 2021-02-22 13:51:56 +01:00
narimiran
29a064e275 bump NimVersion to 1.4.4 2021-02-22 10:26:35 +01:00
flywind
bfc0d64825 fix #17118 (#17119) [backport:1.2]
* fix js unsigned integer
* Use `std` prefix for standard library modules
* fix #17118

(cherry picked from commit 32bf10126c)
2021-02-22 10:26:14 +01:00
Miran
540d16540b [backport:1.2] update nimble commit hash (#17109)
(cherry picked from commit da52e81327)
2021-02-19 20:34:36 +01:00
Andreas Rumpf
7705948d52 fixes #17085 [backport:1.2] (#17101)
(cherry picked from commit 4395a26764)
2021-02-19 20:33:41 +01:00
Timothee Cour
a154acda85 followup #17001: improve coverage for tests/openarray/topenarray.nim (#17006)
* followup #17001: improve coverage for tests/openarray/topenarray.nim

(cherry picked from commit 21e60b9a97)
2021-02-18 19:13:10 +01:00
flywind
8f9ea358b6 [JS] Ref #15952 make toOpenArray works better (#17001)
* ref 15952 toOpenArray works in JS

* fix

(cherry picked from commit 9bd4f503f4)
2021-02-18 19:13:01 +01:00
narimiran
8d7e1c4649 remove tests for not backported stuff 2021-02-17 22:04:03 +01:00
Andreas Rumpf
87dc838370 fixes #17033 [backport:1.4] (#17061)
* fixes #17033 [backport:1.4]

* make test robust against stdlib gensym things

* cleanup assertions.nim to make topt_no_cursor easier to get right

(cherry picked from commit f32ffb6ed8)
2021-02-17 18:38:53 +01:00
Andreas Rumpf
c04214f8cb don't introduce 'dispose', use '=dispose', fixes #17003 [backport:1.4] (#17062)
(cherry picked from commit e463a67c74)
2021-02-17 18:36:39 +01:00
Benoit Favre
132a694c6e Fix bug in removeDotSegments when path ends with dot (#17038) [backport:1.2]
(cherry picked from commit 8f54d3b792)
2021-02-17 18:36:27 +01:00
hlaaftana
c55506006f [backport:1.4] JS cstring null fixes (#16979)
* [backport:1.4] JS cstring null fixes
* fix JS move string
* make it look cleaner

(cherry picked from commit 81533a0014)
2021-02-17 18:36:05 +01:00
Miran
a263e9aae0 [backport:1.2] update the nimble commit hash to the latest one (#16971)
(cherry picked from commit 0d34345f29)
2021-02-09 19:08:22 +01:00
narimiran
94560a9faa remove 'tsugar' 2021-02-09 17:32:38 +01:00
hlaaftana
5f46474555 fix #16967 [backport:1.2] (#16976)
* fix #16967 [backport:1.2]

* move test to tsugar

(cherry picked from commit 49ee2f7f3b)
2021-02-09 15:39:39 +01:00
konsumlamm
21e1fa6217 Improve documentation for std/sha1 (#16970)
(cherry picked from commit cee58ccf7f)
2021-02-09 15:37:27 +01:00
hlaaftana
bf06fb7053 Remove declPragmas from lambdas [backport:1.0] (#16966)
* Remove declPragmas from lambdas [backport:1.0]

* add test for exportc

* fix test

* fix align, nodecl -> noinit

(cherry picked from commit 49b64e8dc7)
2021-02-09 15:37:12 +01:00
Andreas Rumpf
ccbdb95539 final SSL changes [backport:1.2] (#16983)
(cherry picked from commit 74d6a4d7f4)
2021-02-09 15:33:57 +01:00
Héctor M. Monacci
de98648caa Correct typo (#16972)
From `fliter proc` to `filter proc`

(cherry picked from commit a9f44b7257)
2021-02-08 22:00:15 +01:00
narimiran
3f1f26a7e2 disable 'fidget' package 2021-02-08 18:51:29 +01:00
narimiran
8f38f3e34d disable package 'bump' 2021-02-08 17:10:05 +01:00
Andreas Rumpf
c7d090c418 basic cleanups regarding SSL handling (#16940) [backport:1.0]
* basic cleanups regarding SSL handling
* enabled certificate checking on Windows
* updated the SSL test
* quoting helps

(cherry picked from commit abac35e743)
2021-02-08 17:08:10 +01:00
narimiran
9b31b12ca5 disable 'criterion' package 2021-02-02 14:34:25 +01:00
hlaaftana
3c74ec0a0f add finally as post expr block [backport:1.4] (#16896)
(cherry picked from commit def1f99289)
2021-02-02 10:10:18 +01:00
Andreas Rumpf
4da6577c97 fixes #16897 [backport:1.2] (#16900)
(cherry picked from commit 91ace2188a)
2021-02-02 10:10:10 +01:00
narimiran
93ee832d3c [ci skip] CountTable, remove link to unexisting proc
(cherry picked from commit 1d1c831efa)
2021-02-02 09:53:55 +01:00
narimiran
5e49d3b68a Revert "make --gc:arc --exceptions:quirky work again [backport:1.4] (#16583)"
This reverts commit 822c7acd3c.
2021-02-02 09:45:54 +01:00
Timothee Cour
5e5803f28f typetraits: make genericHead docs reflect reality; use runnableExamples (#16776) [backport:1.4]
(cherry picked from commit 8f1f0bd1da)
2021-02-01 15:19:07 +01:00
flywind
d9e14414a4 fix #16706 (#16717) [backport:1.4]
(cherry picked from commit ef9027c290)
2021-02-01 15:18:48 +01:00
Timothee Cour
c346c0b91b [backport 1.0] add backend support for js bigint (#16606)
* add backend support for js bigint

* cleanup

* add tests

* add -d:nimHasJsBigIntBackend

* cleanup

* more tests

(cherry picked from commit 025ca660f7)
2021-02-01 15:18:27 +01:00
Andreas Rumpf
822c7acd3c make --gc:arc --exceptions:quirky work again [backport:1.4] (#16583)
* make --gc:arc --exceptions:quirky work again [backport:1.4]

* fixes #16404 [backport:1.4]

(cherry picked from commit 6317e4004d)
2021-02-01 15:16:50 +01:00
cooldome
71bbbdbf96 fix #15043 (#16441) [backport:1.4]
* fix #15043

* Trigger build

(cherry picked from commit fbc8a40c7a)
2021-02-01 15:11:37 +01:00
Timothee Cour
1d8b7aa07c [backport => 1.0] fix #16428 vmops now works for generic procs (#16429)
* fix #16428 vmops now works for generic procs

* remove duplication

(cherry picked from commit bc84d9c8cb)
2020-12-27 14:45:54 +01:00
Andreas Rumpf
db5ce7ed48 asynchttpserver cleanups [backport:1.0] (#15966)
* asynchttpserver cleanups [backport:1.0]

(cherry picked from commit 122f22d163)
2020-12-27 14:19:08 +01:00
Code Hz
939702a001 removing out T from docs since it no longer working (#16378) [backport]
* remove `out T` from docs

see https://github.com/nim-lang/Nim/issues/16131

* remove `out T` in title
* remove entire paragraph

(cherry picked from commit 90dbb6f3fb)
2020-12-19 14:11:12 +01:00
Tomohiro
753aed9d63 Fix osproc so that it doesn't close pipe/process/thread handles twice (#16385) [backport]
* Add error check to closeHandle and fix closing handle twice in osproc

* Fix compile error on Linux

(cherry picked from commit dcdbae798c)
2020-12-19 14:11:04 +01:00
Andreas Rumpf
c9d7c67acb fixes #16365 [backport] (#16381)
(cherry picked from commit 868c31e88a)
2020-12-19 14:10:54 +01:00
flywind
265499ee57 fix #16364 (#16379) [backport]
* fix #16364

* add comments

* Update tools/dochack/dochack.nim

Co-authored-by: Clyybber <darkmine956@gmail.com>

Co-authored-by: Clyybber <darkmine956@gmail.com>
(cherry picked from commit 5d8f862bc6)
2020-12-19 14:10:40 +01:00
Andreas Rumpf
2f13f5bb56 fixes #16359 [backport] (#16377)
(cherry picked from commit b87bcb6d92)
2020-12-19 14:10:22 +01:00
lqdev
9a86afc8fd disabled sink openArray[T] for adding to seqs (#16352) [backport:1.4]
(cherry picked from commit 233c6a2fba)
2020-12-19 14:10:15 +01:00
rockcavera
553c2e5cff Fix #14259 #15621 (#16322) [backport:1.4]
* IPv6 text representation according to RFC 5952

* Revert IPv6 text representation according to RFC 5952

* fix #14259 #15621

fix #14259 #15621

* Update lib/system/io.nim

* reverted IoHandle removal

* adaptation of types for WinAPI

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
(cherry picked from commit d15f63a0f2)
2020-12-19 14:10:06 +01:00
Andreas Rumpf
bf0ad3acab OSX: support for M1 [backport:1.0] (#16279)
(cherry picked from commit 94bb816de3)
2020-12-11 05:42:02 +01:00
Andreas Rumpf
4c918515fd fixes #16249 [backport:1.4] (#16251)
(cherry picked from commit 8178388a78)
2020-12-11 05:39:54 +01:00
Andreas Rumpf
6e45429ab1 fixes #16214 [backport] (#16252)
(cherry picked from commit edce5897a5)
2020-12-11 05:39:46 +01:00
narimiran
8a528979e8 bump NimVersion to 1.4.3 2020-12-11 05:39:02 +01:00
narimiran
3fb5157ab1 bump NimVersion to 1.4.2 2020-11-30 07:07:40 +01:00
Andreas Rumpf
74c687e395 fixes #16154; underlying system.add for seq is the real cause; will be addressed in a follow-up PR (#16161)
(cherry picked from commit c9a10bb9e4)
2020-11-27 17:51:35 +01:00
flywind
204369845a add testcase (#16156)
(cherry picked from commit 3510216c8a)
2020-11-27 17:51:27 +01:00
Andreas Rumpf
150fc44bb3 fixes #16119 [backport:1.4] (#16149)
(cherry picked from commit 9f1c5f64c5)
2020-11-27 17:50:29 +01:00
Timothee Cour
1a92a4b0bd remove all mentions of doc2, jsondoc2 (except 1 mentioning the alias) (#15683)
(cherry picked from commit 13b1b19a83)
2020-11-27 17:47:27 +01:00
Andreas Rumpf
498ac30f9a updated repr tests (#16147)
(cherry picked from commit 4fdaded227)
2020-11-27 17:47:17 +01:00
Andreas Rumpf
2d63592619 fixes https://github.com/status-im/nimbus-eth2/issues/1549 (#16146)
* fixes https://github.com/status-im/nimbus-eth2/issues/1549 [backport:1.4]

* test fixup

(cherry picked from commit cf516713d0)
2020-11-27 17:46:30 +01:00
cooldome
160436c8b3 fix #16120 (#16145)
(cherry picked from commit 8c12d3e29d)
2020-11-26 17:14:43 +01:00
flywind
c576c1cb76 ref #16054 undefine some stuff in JS backend (#16070)
(cherry picked from commit e7e9007c4c)
2020-11-26 14:17:47 +01:00
flywind
32e0542ca0 improve docs for prelude (#16135)
* improve docs for prelude

* better

(cherry picked from commit 0b3a45692c)
2020-11-26 14:17:38 +01:00
Andreas Rumpf
72f4a0d3e9 fixes #15076 (#16143)
* fixes #15076

* heapqueue: optimized for ARC

* added another test case [backport:1.4]

* code cleanup

(cherry picked from commit da753c6a2e)
2020-11-26 14:17:30 +01:00
flywind
cf30401f02 move tests under the compiler directory to testament (#16096)
(cherry picked from commit 57bd64582c)
2020-11-25 12:46:02 +01:00
flywind
4f89307180 improve the documentation of ropes (#16111)
(cherry picked from commit b7809cc992)
2020-11-25 12:44:41 +01:00
flywind
6494b95f3c ref #16054 remove typed array (#16077)
(cherry picked from commit 3fed85437b)
2020-11-25 12:43:59 +01:00
flywind
ef0776380c add simple runnableExamples for atomics (#16116)
(cherry picked from commit d2c6ac4750)
2020-11-25 12:43:25 +01:00
flywind
cfb38c2383 move tests to testament (#16101)
* move tests to testament

* minor

* fix random

* disable test random

(cherry picked from commit cbc793b30b)
2020-11-25 12:42:51 +01:00
Andreas Rumpf
99032ca07b fixes #16069; [backport:1.2] [backport:1.4] (#16115)
* fixes #16069; refs https://github.com/nim-lang/RFCs/issues/257 [backport:1.2] [backport:1.4]

* make tests green again

(cherry picked from commit d306a04466)
2020-11-24 16:18:18 +01:00
cooldome
e2f1fab458 fix #16110 (#16117)
(cherry picked from commit 1d14b2c9e6)
2020-11-24 16:12:27 +01:00
flywind
03f07f8b5e improve document for heapqueue (#16107)
(cherry picked from commit afb8b69c0a)
2020-11-24 16:10:18 +01:00
Miran
3597824c00 fix export links in the documentation (#16114) [backport:1.4]
* fix export links in the documentation

* fix `len` problem

(cherry picked from commit 9a86198ed5)
2020-11-24 16:10:02 +01:00
flywind
c55c49052f fix #16103 (#16109) [backport:1.0]
* fix #16103

* docs

(cherry picked from commit 823a71380d)
2020-11-24 16:08:37 +01:00
flywind
47ebaa4200 typeinfo minor improvement (#16083)
* typeinfo minor improvement

* minor

* Update lib/core/typeinfo.nim

* rename typeinfo

(cherry picked from commit e4d0f9f3de)
2020-11-24 16:08:24 +01:00
kemifl
4b27458cfc fix #14056 (#16071)
fix #14056, incorporate review comments

(cherry picked from commit a764a5b9bc)
2020-11-24 16:08:08 +01:00
flywind
1eda325177 fix ropes format errors (#16106) [backport:1.0]
* fix rope index

* add testcase

* fix ropes format

(cherry picked from commit 0c6c4be0e7)
2020-11-24 16:06:57 +01:00
flywind
62d497237a ref #5617 add lineinfo to complete (#16102)
(cherry picked from commit 7fc0c3dfbf)
2020-11-24 16:06:47 +01:00
RokkuCode
29f9cc0e3d fixes #16080 (#16091) [backport:1.2]
* fixes #16080

db_sqlite: Error: undeclared field: 'untypedLen'

* redacting fix

(cherry picked from commit ffccdf3c1a)
2020-11-23 15:24:47 +01:00
flywind
976b5bf7c5 correct errors in xmltree docs (#16104)
(cherry picked from commit 79ec1bdcbb)
2020-11-23 15:24:43 +01:00
flywind
74fa24ce45 fix rope index (#16100)
* fix rope index

* add testcase

(cherry picked from commit ab2c082cb3)
2020-11-23 15:23:53 +01:00
flywind
fbb58343d9 ast minor (#16079)
(cherry picked from commit 6a37c0682a)
2020-11-23 15:23:21 +01:00
flywind
e6ea779b06 fix #9695 asyncmacro: tfuturevar fails when activated [backport: 1.0] (#16090)
* fix asyncmacro

* Apply suggestions from code review

* Update lib/pure/asyncmacro.nim

(cherry picked from commit 6f1a72069a)
2020-11-23 15:22:35 +01:00
flywind
cb138fc304 sets minor improvement (#16087)
(cherry picked from commit f1764aaa9e)
2020-11-23 15:22:22 +01:00
flywind
c6f7337c77 deques minor improvement (#16084)
(cherry picked from commit c9371ef59d)
2020-11-23 15:22:14 +01:00
flywind
6c070452e4 xmltree minor improvement (#16085)
(cherry picked from commit 3040f05505)
2020-11-23 15:22:00 +01:00
flywind
475b7e1444 complex minor improvement (#16086)
(cherry picked from commit dd57d46f2f)
2020-11-23 15:21:53 +01:00
flywind
64692b185f heapqueue minor improvement (#16088)
(cherry picked from commit f3887dea2c)
2020-11-23 15:21:46 +01:00
Andreas Rumpf
da3948ae32 fixes #15671 [backport:1.4] (#15690)
* fixes #15671 [backport:1.4]

* progress

(cherry picked from commit d9038ed792)
2020-11-20 18:15:16 +01:00
cooldome
f052e251be fix #15958 (#15970) [backport:1.4]
* fix #15958

* also cover openArray and VarArgs

* more tests

* cover even more types

* cover even more types

* Trigger build

* Trigger build

* cover sets passed as arrays

(cherry picked from commit fcb2ec4ed6)
2020-11-20 15:01:12 +01:00
Miran
577b4f795c fix #16047 (#16066)
(cherry picked from commit 1ad7e4f30b)
2020-11-20 13:53:35 +01:00
satoru
e99c248106 colors: Reuse the HexDigits constant in strutils (#16065)
Co-authored-by: Xuecong Liao <xliao@flexport.com>
(cherry picked from commit 81a03238ed)
2020-11-20 13:39:59 +01:00
flywind
9c6444c192 alternative way to fix #16022 (#16064) [backport:1.4]
* alternative way to fix #16022
* add testcase for #16022

[backport:1.4]

(cherry picked from commit 6cf5ca1dc2)
2020-11-20 13:39:04 +01:00
Antonis Geralis
e94f9cdb4f Improve enumerate (#16053)
* Improve enumerate

* updates

* add tests

(cherry picked from commit 59332ec235)
2020-11-20 13:38:49 +01:00
Andreas Rumpf
4ddb8feb93 fixes #15942 [backport:1.2] [backport:1.4] (#16051)
(cherry picked from commit 1efd11e266)
2020-11-19 13:51:16 +01:00
flywind
ff8fbb3001 close #14847(add testcase for #14847) (#16045)
(cherry picked from commit 1bcc352137)
2020-11-19 13:51:04 +01:00
Andreas Rumpf
63296fb983 makes parsesql .gcsafe [backport:1.0] (#16039)
(cherry picked from commit 743f2f5faa)
2020-11-19 13:50:49 +01:00
Timothee Cour
80068f7dfc fix #16033 nim js --gc:arc works and ignores --gc:arc (#16036)
(cherry picked from commit 557dcfd87d)
2020-11-19 13:49:56 +01:00
Andreas Rumpf
8e181cbd3f fixes db_mysql broken quoting; refs c16ee37a71 (r44209990) [backport:1.4] (#16035)
(cherry picked from commit 2773efa034)
2020-11-19 13:48:40 +01:00
Igor Ribeiro de Assis
80c33b187d Do not read the whole file to compute SHA1 hash (fixes 15997) (#16006)
* Do not read the whole file to compute SHA1 hash (fixes 15997)

* Update lib/std/sha1.nim

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>

* Update lib/std/sha1.nim

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>

* Directly break from loop

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>

 [backport:1.2] [backport:1.4]

(cherry picked from commit baaa19b927)
2020-11-19 13:48:06 +01:00
cooldome
817a16c027 Semfold for nil cast (#16030)
* bring back the semfold of nil

* remove space

* fix test

* proc type can't be dereferenced

(cherry picked from commit 87d3e5331a)
2020-11-19 13:46:59 +01:00
Juan Carlos
63ae6308c2 htmlgen: Add lazy loading (#15986)
(cherry picked from commit a8858eb93e)
2020-11-19 13:45:45 +01:00
Bung
f0b19e8ef2 add parent property to window in dom.nim (#15922)
(cherry picked from commit bc007a3cd3)
2020-11-19 13:45:28 +01:00
narimiran
41569f9693 fix wrong backport containing idgen 2020-11-18 11:53:22 +01:00
flywind
5977f553fc fix #6497 (#16027)
* fix #6497

* add testcase for #16027

(cherry picked from commit 581bcfe290)
2020-11-18 11:31:30 +01:00
flywind
462209f4b0 combine PR#16009 and PR#16012 (#16024)
* fix #15623
* add testcase for #15623
* add testcase
* combine #16009
* support casting nil to NilableTypes in VM

(cherry picked from commit e6e1e9574d)
2020-11-18 11:31:04 +01:00
flywind
55abacc514 fix #15972 (#15994)
* fix #15972

* add testcase

* more

(cherry picked from commit 0869d2a477)
2020-11-18 11:30:56 +01:00
Timothee Cour
ce1570a6fb defer: improve manual, clarify difference wrt try/finally (#16010)
(cherry picked from commit 50d035b789)
2020-11-18 11:04:29 +01:00
Timothee Cour
cc6497406f remove unused and misleading FilenameOption.foShort (#15982)
(cherry picked from commit 61352d5a20)
2020-11-18 11:03:26 +01:00
narimiran
00c9dafd5f telling us once about a change is enough [ci skip]
(cherry picked from commit 3e5e029ef8)
2020-11-18 11:01:23 +01:00
flywind
9560efafc2 rename: stmt -> typed and expr -> untyped (#15989)
* stmt -> typed

* expr -> untyped

* minor

(cherry picked from commit 4213f7a6c9)
2020-11-18 11:01:15 +01:00
cooldome
b92666745e fix #15910 (#15984)
* fix #15910

* produce op of op is nil

* Trigger build

(cherry picked from commit a4d02f591c)
2020-11-18 11:01:05 +01:00
Timothee Cour
d08c2f195c workaround #15713 disable freebsd tssl.nim (#15718)
(cherry picked from commit b56a037183)
2020-11-16 14:12:06 +01:00
Luca Guzzon
c225d0182a Console apps in Windows can raise OSError (#15874)
Console apps in Windows implementation can raise OSError so I've fixed it, see below some examples for reference:
- c07807bedf/lib/pure/terminal.nim (L170)
- c07807bedf/lib/pure/terminal.nim (L178)
- c07807bedf/lib/pure/terminal.nim (L191-L192)
- c07807bedf/lib/pure/terminal.nim (L196-L197)
- ...

(cherry picked from commit 49f68122e6)
2020-11-16 11:24:44 +01:00
narimiran
e0e8762e6b fix wrongly backported change containing nextId 2020-11-16 09:52:59 +01:00
Andreas Rumpf
fffb0dbea5 fixes #15753 [backport:1.4] (#15971)
(cherry picked from commit 7eb34d170a)
2020-11-16 07:30:53 +01:00
Clyybber
f02b359968 Fix nimsuggest/#117 (#15602)
(cherry picked from commit 92da06e64e)
2020-11-16 07:29:30 +01:00
Juan Carlos
7c4fbde78e https://github.com/nim-lang/Nim/pull/15968/files#r523468677
(cherry picked from commit 1b9f37c6dc)
2020-11-16 07:28:59 +01:00
Juan Carlos
2f08a1e390 Fix #15806
(cherry picked from commit c56a6133bb)
2020-11-16 07:28:43 +01:00
Juan Carlos
6cc39b5a57 Fix #15806
(cherry picked from commit 9ab1a86b5b)
2020-11-16 07:28:32 +01:00
Juan Carlos
2bfabfde49 Fix #15806
(cherry picked from commit 3cebae492e)
2020-11-16 07:28:26 +01:00
Juan Carlos
d4ce6acfed Fix #15806
(cherry picked from commit d0dda9efab)
2020-11-16 07:27:32 +01:00
flywind
11f6fd88ea minor
(cherry picked from commit bfa387d384)
2020-11-16 07:27:25 +01:00
flywind
452203a28e [docs minor]add some tips yo intern.rst
(cherry picked from commit 5af798c21b)
2020-11-16 07:27:20 +01:00
Timothee Cour
b47a98f7f2 targets: use cpp instead of c++ everywhere (was by far the most common) (#15961)
(cherry picked from commit 96930b9cae)
2020-11-16 07:25:54 +01:00
Timothee Cour
95efe6d3ca strengthen taddr.nim: add test case for #14578; reference other issues; test cpp (#15960)
(cherry picked from commit 1a47fc2291)
2020-11-16 07:25:40 +01:00
Araq
a2c51867f2 fixes the doc rendering
(cherry picked from commit 02f8b11a71)
2020-11-16 07:19:56 +01:00
Araq
0848a816b2 ported to FreeRTOS
(cherry picked from commit 9f566881f1)
2020-11-16 07:19:49 +01:00
Araq
1be3caf7c3 makes test green again
(cherry picked from commit fa7b12bcf9)
2020-11-16 07:19:40 +01:00
Araq
4095cae94c fixes 'nim doc'
(cherry picked from commit 19d52033f8)
2020-11-16 07:19:31 +01:00
Araq
3e9df7da45 better documentation
(cherry picked from commit cb19dc53ca)
2020-11-16 07:19:23 +01:00
Araq
abe178b602 attempt to make asynchttpserver better; fixes #15925; [backport:1.0]
(cherry picked from commit 8778d4a6f3)
2020-11-16 07:19:17 +01:00
Bung
42a3e31826 Fix #8404 JS backend doesn't handle float->int type conversion (#15950) [backport]
* Fix #8404 JS backend doesn't handle float->int type conversion
* handle conv to uint as cast, discard other cases
* limit to int32, times use int64
* toInt including tyInt64 break times timezones lib, ignore for now
* also affect to vm
* move to tests/misc/t8404.nim

(cherry picked from commit 797cb2e67b)
2020-11-16 07:18:16 +01:00
flywind
b9260514fe minor
(cherry picked from commit a86aa31081)
2020-11-16 07:12:23 +01:00
flywind
5d88e6c5f5 add testcase for #9754
(cherry picked from commit a968e7dd9b)
2020-11-16 07:12:16 +01:00
flywind
36429cabda nil
(cherry picked from commit 0f53b129b7)
2020-11-16 07:12:08 +01:00
flywind
a983c6a843 close #13062(add testcase for #13062) (#15956)
(cherry picked from commit d802a4a669)
2020-11-16 07:09:55 +01:00
flywind
561902ca2b close #2771(add testcase for #2771) (#15932)
(cherry picked from commit 7d51ad96e9)
2020-11-16 07:09:39 +01:00
lenoil98
b3b7a1e73f Update buildsh.nimf (#15945)
fix powerpc64le detection

(cherry picked from commit 778914c3ca)
2020-11-16 07:07:58 +01:00
wilypomegranate
efaa55d429 Don't use os for Standalone (#15944)
(cherry picked from commit 1fdfa234d7)
2020-11-16 07:07:25 +01:00
treeform
afedd5ee24 Add documentElement to Document. (#15943)
(cherry picked from commit 83432aecfc)
2020-11-16 07:07:05 +01:00
flywind
9b51f9b7e1 fix #15941 (#15948)
* fix #15941

* add testcase

* update

(cherry picked from commit 492e9afa4c)
2020-11-16 07:06:15 +01:00
flywind
71583cd2e9 add testcase
(cherry picked from commit 8ec3c141ae)
2020-11-16 07:05:58 +01:00
flywind
53421be985 make workaround for #15934 and #15620
(cherry picked from commit 077eba7b38)
2020-11-16 07:05:51 +01:00
flywind
37229707ed change some code-blocks to runnableExamples and correct some errors in docs (#15900)
* original docs are wrong
* fix pathnorm
* Update lib/pure/pathnorm.nim

Co-authored-by: Juan Carlos <juancarlospaco@gmail.com>
(cherry picked from commit ef2677f5f3)
2020-11-16 07:00:48 +01:00
lenoil98
30362cde20 Add support for FreeBSD/PowerPC64 Little Endian (#15927)
* Update installer.ini

Add support for powerpc64 little endian

* Update buildsh.nimf

Add support for powerpc64 little endian

* Update makefile.nimf

Add support for freebsd/powerpc64 little endian

(cherry picked from commit 63c559e781)
2020-11-16 07:00:24 +01:00
Christopher Dunn
9fb713cf23 Fix a problem for long symlinks in conda (#15908) [backport]
* d8c80ea69d (diff-e1d8e552330911f9f779f85b6f2c00a15e790dcc3fbb3b28f5da1d660a30c5b8)

(cherry picked from commit c6ceefea6d)
2020-11-16 06:58:21 +01:00
flywind
23ea176cb2 fix #15916 (#15917) [backport]
* fix #15916

* add testcase for #15916

* add comments

(cherry picked from commit 402df0b061)
2020-11-16 06:58:07 +01:00
Fanael Linithien
48e5520894 Fix #15909 (#15914)
(cherry picked from commit 7d4f70280e)
2020-11-16 06:57:46 +01:00
flywind
23b0b10886 fix #14157 (#15877)
* fix #14157

* Update compiler/jsgen.nim

* add changelog

* Update compiler/jsgen.nim

* Update tests/js/tmodify_cstring.nim

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
(cherry picked from commit 1f9bf43100)
2020-11-16 06:56:43 +01:00
Bung
04254fe9d6 fix #12726 Cannot take the compile-time sizeof Atomic types (#15928)
* fix #12726 Cannot take the compile-time sizeof Atomic types

* fix for arch 32

(cherry picked from commit 826e62953f)
2020-11-16 06:56:33 +01:00
Bung
272bc81f51 Fix 14127 js from int to int casting (#15918)
* fix #14127 from int to int casting

* add test for #14127

* use template for test, also test uint2int

* move to tests/types/t14127_cast_number.nim targets:c cpp js

(cherry picked from commit a81434a890)
2020-11-16 06:56:24 +01:00
narimiran
d10f841b60 nimdoc: items of ordered lists now have numbers instead of circles
(cherry picked from commit f02c7542fc)
2020-11-16 06:55:32 +01:00
narimiran
1781848122 remove codeowners [ci skip]
(cherry picked from commit b831033db6)
2020-11-16 06:55:25 +01:00
ee7
916c4bb484 Docs(strutils): Fix broken links (#15912)
The `dedent` and `unindent` links were introduced by commit d67c5cb751
(#15264).

(cherry picked from commit 42c434fa3d)
2020-11-16 06:55:00 +01:00
flywind
2e6cfe3a0d close #4318(add testcase for #4318) (#15904)
* close #4318(add testcase for #4318)

* Update tests/objects/t4318.nim

Co-authored-by: Juan Carlos <juancarlospaco@gmail.com>

Co-authored-by: Juan Carlos <juancarlospaco@gmail.com>
(cherry picked from commit 35f8803250)
2020-11-16 06:54:53 +01:00
Miran
04f810c2ec Correct all eggs (#15906)
* "eg" is a misspelled "egg", "e.g." is "exempli gratia"
* Also, "ie" is "i.e.".

(cherry picked from commit bbe49a14ae)
2020-11-16 06:54:45 +01:00
narimiran
192cb9ff90 fix norm package testing command
(cherry picked from commit c44ae647a9)
2020-11-16 06:54:34 +01:00
flywind
127d63b343 fix #12471 (#15901)
* fix #12471

* add testcase

* fix

* test nimdoc is tricky

* Delete t12471.nim

(cherry picked from commit b38f0403fd)
2020-11-16 06:54:25 +01:00
flywind
a27ed88688 follow #15874(add testcase for #15874) (#15893)
(cherry picked from commit d8e7caf5dd)
2020-11-16 06:54:10 +01:00
cooldome
7724cd534f fix #15825 (#15894)
* fix #15825

* better fix

(cherry picked from commit 338602a402)
2020-11-16 06:53:59 +01:00
Clyybber
4e89dffc15 Add testcase for #14601 (#15677)
(cherry picked from commit 7435d912ad)
2020-11-16 06:53:52 +01:00
narimiran
19a11bc8a6 fix the incorrect merge conflict of an earlier backport 2020-11-10 12:31:06 +01:00
Aethylia
244f3f62ce Added [:T] syntax explanation to generics tutorial. (#15890)
* Added [:T] syntax explanation to generics tutorial.

* Update doc/tut2.rst

Co-authored-by: flywind <43030857+xflywind@users.noreply.github.com>

* Update doc/tut2.rst

Co-authored-by: flywind <43030857+xflywind@users.noreply.github.com>

* Made second generics example runnable and added test line.

* Update doc/tut2.rst

* Update doc/tut2.rst

* Update doc/tut2.rst

Co-authored-by: flywind <43030857+xflywind@users.noreply.github.com>
Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
(cherry picked from commit 53eca459f1)
2020-11-09 16:26:00 +01:00
ee7
b6f8ed7193 CI(actions): Replace deprecated add-path commands (#15892)
This commit resolves the following warning in the CI logs:

> Error: The `add-path` command is deprecated and will be disabled soon.
> Please upgrade to using Environment Files. For more information see:
> https://github.blog/changelog/2020-10-01-github-actions-deprecating-set-env-and-add-path-commands/

The deprecation is due to an injection vulnerability (CVE-2020-15228).

See:
- https://bugs.chromium.org/p/project-zero/issues/detail?id=2070
- https://github.com/nim-lang/Nim/runs/1373146963#step:8:1

(cherry picked from commit 3948b40bcd)
2020-11-09 16:25:54 +01:00
cooldome
18289607eb Fix 15629 (#15888)
* fix #15858

* fix space

* fix #15629

* Revert "fix space"

* Revert "fix #15858"

(cherry picked from commit 69fe707025)
2020-11-09 16:25:22 +01:00
cooldome
d57418ab9e Fix #15858 (#15887)
* fix #15858
* fix space
* fix #15629
* Revert "fix #15629"

(cherry picked from commit d5a0a5dfff)
2020-11-09 16:25:14 +01:00
n5m
e7e33b14b5 improve Testament docs (#15881)
* fix mentions of recursive test discovery

* document that {.fatal.} pragmas cannot be caught

(cherry picked from commit 3bff12b966)
2020-11-09 16:25:07 +01:00
Bung
cd97e3ef98 export PrettyOptions,prettyPrint from nimpretty (#15865)
(cherry picked from commit 204435ad97)
2020-11-09 16:25:00 +01:00
cooldome
283698b1ec fix #15707 (#15870)
(cherry picked from commit 7b19217798)
2020-11-09 16:24:20 +01:00
flywind
8f35bca839 fix #12558 (#15864)
* fix #12558
* Update compiler/pragmas.nim

(cherry picked from commit 673c5990c6)
2020-11-09 16:24:00 +01:00
n5m
12145adecd include example of error-marked copy proc (#15886)
* include example of error-marked copy proc

* Update destructors.rst

(cherry picked from commit 3be404af04)
2020-11-09 16:23:45 +01:00
Clyybber
5ea4dea4ea Closes #12897 (#15867)
(cherry picked from commit 60c364fb22)
2020-11-09 16:22:13 +01:00
flywind
e7d14ce6f2 close #8829(add testcase for #8829) (#15866)
(cherry picked from commit fb60e35a54)
2020-11-09 16:22:05 +01:00
flywind
839ec1395d follow #11707(add pragmas examples for =>) (#15863)
(cherry picked from commit 9fd67958b9)
2020-11-09 16:21:57 +01:00
flywind
ac32cf129b fix #15851 (#15852)
* fix #15851

* {.cast(noSideEffect).}

(cherry picked from commit 218ff27b70)
2020-11-09 16:21:16 +01:00
cooldome
992912e21d static[T] related fixes (#15853)
* close #9679

* close #7546

* close #9520

* close #6177

(cherry picked from commit cdd459dd60)
2020-11-09 16:21:11 +01:00
cooldome
ca53629c42 fix #15609 (#15856)
* fix #15609

* fix test

(cherry picked from commit fa5f225efc)
2020-11-09 16:21:03 +01:00
Clyybber
554a9ad156 Tiny unittest doc fix
(cherry picked from commit d1bea1f71f)
2020-11-09 16:20:51 +01:00
cooldome
1c027d591c Fix #12636 (#15850)
* close #11142

* fix #12636

* undo unwanted changes

* fix illegal recursion case

(cherry picked from commit 3af7818af4)
2020-11-09 16:20:43 +01:00
cooldome
0ed4c2bc4f close #11142 (#15847)
(cherry picked from commit 9455a0c3e3)
2020-11-09 16:19:28 +01:00
flywind
ac25f63f82 document #15618 (#15810)
* document #15618

* Update lib/pure/unittest.nim

* Update lib/pure/unittest.nim

Co-authored-by: Juan Carlos <juancarlospaco@gmail.com>

* Update lib/pure/unittest.nim

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
Co-authored-by: Juan Carlos <juancarlospaco@gmail.com>
(cherry picked from commit adde5ba6b0)
2020-11-09 16:19:14 +01:00
flywind
e5a04f8914 fix adding empty sequence to HTTP headers (#15783)
* fix adding empty sequence to HTTP headers

* add tests

(cherry picked from commit c4cc907433)
2020-11-09 16:19:05 +01:00
flywind
8c31c210ee fix #15663 (#15839) [backport:1.4]
(cherry picked from commit 8e1fa84b0d)
2020-11-09 16:18:20 +01:00
flywind
64ded4a51f fix #15463 (#15831)
(cherry picked from commit a8af664e8b)
2020-11-09 16:18:03 +01:00
flywind
5da17acfce change non-working example to runnableExamples (#15841)
(cherry picked from commit cae92f670a)
2020-11-09 16:15:49 +01:00
flywind
5bc573cf1e close #10307(add testcase for #10307) (#15840)
(cherry picked from commit dfa2f011d7)
2020-11-09 16:15:42 +01:00
flywind
b100c67515 close #8457 (#15844)
(cherry picked from commit fdd25ed19c)
2020-11-09 16:15:35 +01:00
cooldome
c2263c685f Use modern enums in compiler (#15775)
(cherry picked from commit 00b495de95)
2020-11-09 16:14:22 +01:00
cooldome
01403f8cfa fix static[Slice[T]] as argument issue (#15842)
(cherry picked from commit 4c19c5dfae)
2020-11-05 09:19:51 +01:00
c-blake
2443b40623 Clarify the sense in which Nim supports recursive iterators in the (#15834)
manual, the tutorial, and the `tbintree` test.

(cherry picked from commit f17555770e)
2020-11-05 09:19:35 +01:00
flywind
3565d14cc4 fix #15835 (#15838)
* fix #15835

* add tests

(cherry picked from commit 7d640e0943)
2020-11-05 09:19:27 +01:00
flywind
6d9961c898 fix deprecated messages regarding high (#15832)
(cherry picked from commit 75dc69417a)
2020-11-05 09:18:45 +01:00
flywind
740112c1e0 fix #12640 (#15829)
(cherry picked from commit b8bcf236dd)
2020-11-05 09:17:52 +01:00
flywind
bf446e8cec follow #15818 and close #7109 (#15823)
* follow #15818 and close #7109

* Update compiler/jsgen.nim

Co-authored-by: Juan Carlos <juancarlospaco@gmail.com>

Co-authored-by: Juan Carlos <juancarlospaco@gmail.com>
(cherry picked from commit fde17b159f)
2020-11-05 09:17:42 +01:00
Andreas Rumpf
bb3cdcad99 fixes #15804 (#15820)
* fixes #15804

* fix the existing test

* add the testcase for #15804

Co-authored-by: narimiran <narimiran@disroot.org>
(cherry picked from commit dfd8a83f35)
2020-11-05 09:17:29 +01:00
flywind
9954b7f046 fixes #15594 (#15819)
(cherry picked from commit eb429988cd)
2020-11-05 09:17:12 +01:00
flywind
dd36bfffa1 more clear (#15812)
(cherry picked from commit 4fe56b56ce)
2020-11-05 09:16:24 +01:00
flywind
9d9bf12e1c Closure iterators are not supported by VM (#15818)
(cherry picked from commit 5b4c17b5e7)
2020-11-05 09:16:10 +01:00
flywind
45e87ade15 fix #8821 (#15809)
(cherry picked from commit 544cb107c7)
2020-11-05 09:16:00 +01:00
Thomas Tay
b238c077a1 Update tables documentation (#15807)
Added a case where a user might use mgetOrPut and create an accidental
copy of a seq.

(cherry picked from commit 5298366f86)
2020-11-05 09:13:52 +01:00
flywind
29cd083e12 fixes #15717
(cherry picked from commit 558115fa29)
2020-11-05 09:13:09 +01:00
flywind
2e35621af0 fix #15815 (#15817)
(cherry picked from commit 919593395c)
2020-11-05 09:13:05 +01:00
flywind
e0aa7cf09b fix #15145 (#15816)
(cherry picked from commit 27eb19cc48)
2020-11-05 09:13:00 +01:00
flywind
98bd81b4a3 closes #3670 [add testcase for #3670] (#15808)
* add testcase

* Update tests/template/twhenintemplates.nim

Co-authored-by: Clyybber <darkmine956@gmail.com>
(cherry picked from commit 98cec6b692)
2020-11-05 09:12:45 +01:00
Clyybber
5e7c6b7f7e Typos
(cherry picked from commit 1eb4a38a50)
2020-11-05 09:12:33 +01:00
n5m
0699b57402 improve public Testament docs (#15710)
* improve glob docs

* punctuation

* move spec descriptions above example

notably, change the description of timeout to reference seconds, not microseconds

* document nimout

* document sortoutput

* explain the action options

(cherry picked from commit bcb30566fc)
2020-11-05 09:12:26 +01:00
flywind
f235eb48a0 fix #15651 (#15800)
* fix

* minor

(cherry picked from commit 80b0748d75)
2020-11-05 09:12:17 +01:00
flywind
975a5b64ad support par expression as checkpoint (#15802)
(cherry picked from commit 8115b655e7)
2020-11-05 09:12:04 +01:00
flywind
5d2b1a8943 [closes #12682]add testcase for #12682 (#15796)
* add testcase for #12682

* fix

(cherry picked from commit bc9a521270)
2020-11-05 09:11:34 +01:00
Miran
b14958caa0 fix #15702, show enum fields documentation (#15792)
(cherry picked from commit 28bbcd9d45)
2020-11-05 09:11:28 +01:00
Clyybber
208ed6e816 Grammar fixes
(cherry picked from commit 7364794fed)
2020-11-05 09:11:23 +01:00
flywind
e085010e59 add testcase for #14227 (#15794)
(cherry picked from commit ae86df12af)
2020-11-05 09:11:08 +01:00
flywind
f6f1594cef [closes #11625 and closes #2488]add global and threadvar(with --threads:off mode ) pragmas supports for JS backend (#15772)
* add global pragma support for js backend

* globalThis

* add support for threadvar

* more tests

* Update compiler/jsgen.nim

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
(cherry picked from commit 2cfe5e0745)
2020-11-05 09:11:02 +01:00
cooldome
c657af440a canAlias improvement (#15773)
* canAlias improvement

* fix comment

(cherry picked from commit 6fe2e8977d)
2020-11-05 09:10:20 +01:00
Miran
df069c8ddb promote collect macro as a map+filter replacement (#15788)
* promote `collect` macro as a map+filter replacement

* Update lib/pure/collections/sequtils.nim

(cherry picked from commit ec059240b0)
2020-11-05 09:10:05 +01:00
Timothee Cour
e524df8746 simplify toHex (#15821)
(cherry picked from commit 235e4930ab)
2020-11-05 09:09:55 +01:00
Miran
81a302b197 fix toHex - make it work with int literals (#15770)
(cherry picked from commit c0fdc8b215)
2020-11-05 09:09:46 +01:00
flywind
e301285d4c closes #6036 (#15779)
* add testcase for #6036

* try

* try again

* make it work

(cherry picked from commit 4374c638cd)
2020-11-05 09:09:30 +01:00
flywind
daba6d935f closes #7374 (#15781)
* add testcase for #7374

* minor

* fix test

(cherry picked from commit 1725db9295)
2020-11-05 09:09:09 +01:00
flywind
1d06c70c18 add testcase for #7416 (#15782)
(cherry picked from commit 3028c1be82)
2020-11-05 09:08:56 +01:00
flywind
a480cbddcc closes #7658 (#15784)
* fix #7658

* more

(cherry picked from commit 17f08b2939)
2020-11-05 09:08:49 +01:00
flywind
eb2ed782c6 add testcase for #8012 (#15785)
(cherry picked from commit 2de90a14cb)
2020-11-05 09:08:42 +01:00
flywind
dc6073b0b8 add testcase for #9165 (#15787)
(cherry picked from commit 1655c04aa3)
2020-11-05 09:08:38 +01:00
flywind
3d939dd863 add testcase for #9091 (#15791)
* add testcase for #9091

* more tests

(cherry picked from commit b5df823191)
2020-11-05 09:08:19 +01:00
flywind
d426f75593 fix #15638 (#15789)
(cherry picked from commit f79ded3cb6)
2020-11-05 09:08:14 +01:00
flywind
051c201068 add testcase for #7127 (#15780)
(cherry picked from commit d8fb2379c9)
2020-11-05 09:08:01 +01:00
flywind
b0291b88fc add tests for #7686 (#15771)
(cherry picked from commit 33e258c72f)
2020-11-05 09:07:51 +01:00
Antonis Geralis
1b5b98c943 Fix doc comment for sumKbn (#15769)
Co-authored-by: b3liever <b3liever@yandex.com>
(cherry picked from commit 912d8f80ad)
2020-11-05 09:07:43 +01:00
Andreas Rumpf
645200aa3d fixes #15413 (#15768)
* fixes #15413

* better hide it properly

* see if this makes our list of important packages happy

(cherry picked from commit 87a60c1b28)
2020-11-05 09:07:36 +01:00
Yanis Zafirópulos
a7bd58ed07 Massive documentation fixes + copy editing (#15747)
(cherry picked from commit 0cae8ef2ca)
2020-11-05 09:07:07 +01:00
Tim Smith
4a95d45b28 Spelling and Grammer fixes (#15719)
Co-authored-by: Tim Smith <tim.smith.hdg@gmail.com>
Co-authored-by: Miran <narimiran@disroot.org>
(cherry picked from commit 485d4ff802)
2020-11-05 09:07:01 +01:00
Antonis Geralis
60403c9e6b Make newObjUninit proc to adhere to its name (#15764)
Co-authored-by: b3liever <b3liever@yandex.com>
(cherry picked from commit 94e2b9e837)
2020-11-05 09:06:53 +01:00
cooldome
e39b01e126 fix #15756 (#15761)
* fix #15756

* simplify test

(cherry picked from commit 610e9b2fe9)
2020-11-05 09:06:45 +01:00
cooldome
a4f9bc55c7 ARC now capable of custom extra alignment. Ref, closure and seq support. (#15697)
(cherry picked from commit 0956a99537)
2020-11-05 09:06:39 +01:00
narimiran
e27f595aee change/remove deprecated stuff
(cherry picked from commit 732ddc02da)
2020-11-05 09:06:07 +01:00
narimiran
96bd6426c2 fix #15750
(cherry picked from commit b13fb9ddb8)
2020-11-05 09:05:46 +01:00
cooldome
afb5212fe0 fix #15752 (#15754)
(cherry picked from commit f8cac6bbbc)
2020-11-05 09:05:39 +01:00
shirleyquirk
5c48058c86 fixes #10456,#12928 issues when chaining templates to sortedByIt (#15734)
* update c_malloc's to csize_t

fix for broken --os:ios

* I'm an idiot sorry

* Create talgorithm.nim

* workaround for #10456

I don't understand the intricacies of how lambdalifting and template expansions interact with lent, so i don't know how to fix the real problem, but this sidesteps whatever issue that is.

* working test, use typeof rather than auto

(cherry picked from commit 218acfe367)
2020-11-05 09:05:21 +01:00
n5m
33375aff15 add tests for Testament "reject" action (#15709)
* add test for reject action

* highlight that a compilation failure is expected

* add the converse test for action=reject

* add trailing newline

* fix wording

(cherry picked from commit 066f3ebc2a)
2020-11-05 09:04:57 +01:00
Xavier Noria
1fbfd77580 Document implicit return values from procedures (#15738)
(cherry picked from commit 25955440df)
2020-11-05 09:03:57 +01:00
Timothee Cour
3326f1df1d [backport] fix #15595 procvar == works in VM (#15724)
(cherry picked from commit 3bdc000521)
2020-11-05 09:03:47 +01:00
Andreas Rumpf
a156484553 ensure the Nim compiler works with --experimental:strictFuncs --experimental:views [backport:1.4] (#15737)
(cherry picked from commit cf01945f54)
2020-10-27 09:06:45 +01:00
Juan Carlos
c8f6eb6c14 Documentation only iup (#15732)
* ReSync with Devel

* ReSync

* Add Examples for IUP, based from official doc

(cherry picked from commit 3a69f14621)
2020-10-27 09:06:20 +01:00
Yanis Zafirópulos
513ced8966 Copy editing (#15733)
(cherry picked from commit ae8eb1ec3d)
2020-10-27 09:05:46 +01:00
Andy Davidoff
75d76c28c8 add criterion to important packages (#15604)
* add criterion to important packages

* use a special nimscript for criterion tests

* fix criterion speed differently

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
(cherry picked from commit ea6c28249a)
2020-10-27 09:02:46 +01:00
Jason Beetham
2351b66e08 Fixed iteration limit hit from execproc (#15723) [backport:1.2] [backport:1.4]
When calling procs from Nim in Nimscript you could hit the VM iteration limit even though the code is functioning properly. This resolves that by making the iteration limit reset eachtime you call a proc.

(cherry picked from commit a87617956f)
2020-10-27 09:02:11 +01:00
Danil Yarantsev
a2367d4bd2 Add support to the latest LibreSSL version (#15715) [backport:1.2] [backport:1.4]
(cherry picked from commit b2740f5c63)
2020-10-27 09:01:51 +01:00
Timothee Cour
4e91c11eff fix #15704 #15597 wrong VM register was freed (#15705)
* fix #15704 #15597 wrong VM register was freed

* same treatment for nkCheckedFieldExpr

* note concerning HighRegisterPressure

* bump NimPatch

* Update lib/system.nim

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
(cherry picked from commit d4c2e2c53f)
2020-10-27 09:00:51 +01:00
Timothee Cour
9d81415603 close #8007 (#15695)
(cherry picked from commit bf894ad3eb)
2020-10-27 09:00:48 +01:00
Danil Yarantsev
60ddbf1e45 Add tests to #15363 (#15633)
(cherry picked from commit d22ab0fb96)
2020-10-27 08:59:52 +01:00
Juan Carlos
a48c16b155 Fix Prelude (#15714)
* ReSync with Devel

* Fix prelude for JS target

* ReSync devel

* Fix prelude for JS target

(cherry picked from commit e284445e51)
2020-10-27 08:57:50 +01:00
rockcavera
796785abf6 fix #15698 (#15699)
* fix in the net.`$` to print zeros that are not in the compressed group

* Update lib/pure/net.nim

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>

* Update net.nim

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
(cherry picked from commit 7252a50fef)
2020-10-27 08:57:18 +01:00
Timothee Cour
e89592787b [minor] nimVMDebug: fix codeListing formatting for jump-to-file to work (#15711)
(cherry picked from commit 64eb62889a)
2020-10-27 08:57:18 +01:00
Clyybber
9b37fc98a2 Try to fix CI failures (#15701)
* Use cligens release version

* Rework important_packages main loop

* Fix

* Fix

* Create pkgs dir

* Don't use nimble develop
since it doesn't work for binary only packages, and always install head

* Use git to get the latest release/tag instead

* Tackle the root cause

* Reduce diff

* Cleanup

(cherry picked from commit e18fc698ed)
2020-10-27 08:57:18 +01:00
Clyybber
9e8ad86d6a Revert "fixes #15280 [backport:1.2] (#15281)" (#15700)
This reverts commit 3f00a738db.

(cherry picked from commit d4022ebe53)
2020-10-24 17:16:02 +02:00
cooldome
d1924f2852 fix #15662 (#15678)
* fix #15662

* alternative fix

* fix spacing

(cherry picked from commit ae320b4e7d)
2020-10-24 17:15:08 +02:00
Clyybber
7a9db0e5c5 Fix #12410 (#15685)
* Fix #12410, big thanks to @pmetras for this fix

* Add testcase

(cherry picked from commit 01a62320f0)
2020-10-24 17:14:49 +02:00
Andreas Rumpf
e7b7356bd1 fixes view types for sizeof() and --gc:orc (#15680)
(cherry picked from commit 64016ddedc)
2020-10-22 20:21:49 +02:00
Andreas Rumpf
ce94ce40c7 fixes #15652 [backport:1.4] (#15679)
(cherry picked from commit 8358974b73)
2020-10-22 20:21:42 +02:00
Miran
6d99de7c2c [backport: 1.4] Better linebreaks (#15658)
(cherry picked from commit d8a6b0b04e)
2020-10-22 20:20:49 +02:00
n5m
06846d23ad expect valgrind test failure on memory leak (#15669)
* expect valgrind test failure on memory leak

* alloc 1 instead of 0

(cherry picked from commit 8da0e01769)
2020-10-22 20:20:15 +02:00
Gampol T
bc5c6c812b Fix #13609 (#15567)
* add documentation that discardable pragma cannot use on template

* Update doc/manual.rst

Co-authored-by: Euan <euantorano@users.noreply.github.com>

* Update doc/manual.rst

Co-authored-by: Euan <euantorano@users.noreply.github.com>

Co-authored-by: Euan <euantorano@users.noreply.github.com>
(cherry picked from commit b2f51e2950)
2020-10-22 20:19:23 +02:00
Andreas Rumpf
eb04535b53 fixes bootstrapping for any machine that has a Nim already installed [backport:1.4] (#15660)
(cherry picked from commit 9a059657ca)
2020-10-21 11:09:13 +02:00
Timothee Cour
11ef97d57f $(uint|uint64) now works with nimscript (#15644)
* $(uint|uint64) now works with nimscript

* fixup

(cherry picked from commit 3cbe8d2c53)
2020-10-21 11:08:43 +02:00
RecruitMain707
5874bce91c Fix compilation error for regions and memory profiling (#15641) (#15656)
Co-authored-by: Recruit_main707 <Recruit_main707@users.noreply.github.com>
(cherry picked from commit ed0f8a4973)
2020-10-21 11:08:14 +02:00
narimiran
38ebd767db even more "eg" fixes [ci skip]
(cherry picked from commit b418c54ec4)
2020-10-21 11:07:40 +02:00
Tomáš Hübelbauer
293ef09b49 Remove bit about opening files not raising (#15654)
Resolved #473

I am removing this bit because this advice to not throw on recoverable-from cases like a file failing to open is actually not respected by Nim standard library. `readFile` and `readLines` both throw and exceptions must be used as a method of control flow for the recovery from that. There are alternatives, like opening a file handle instead of using these helpers, but that's less convenient than these helper methods for cases where you really want to just slurp up a file to memory and use a fallback value if it doesn't exist or is for whatever reason not readable.

(cherry picked from commit 725c7caa02)
2020-10-21 11:07:33 +02:00
narimiran
8fb501b52c more "eg" fixes
(cherry picked from commit 5e9dd81baa)
2020-10-21 11:06:50 +02:00
narimiran
c087e2d8de it is not "eg", it is "e.g."
(cherry picked from commit 0a686659d2)
2020-10-21 11:06:28 +02:00
Clyybber
45977c2d70 Fix commentOffsetA for doc comments (#15643)
(cherry picked from commit f20e485827)
2020-10-21 11:03:47 +02:00
n5m
1d63995896 fix #15631 (#15632)
* trigger valgrind failure on memory leak

* remove non-malloc tests

* remove ORC test

is redundant because we already have an ARC test

* only run valgrind tests on 64-bit Linux

* disable freebsd and openbsd

* Remove tleak_refc

As to not test implementation details (or bug)

* Fix test failures by removing redundant test

Since this tests/shoulfail/tvalgrind.nim was specified here to fail this test
itself fails since it will be skipped on non-linux CI

* Remove test, reason detailed in the previous commit

* Remove redundant disables

* Revert removing disables

* Add and use valgrind: leaks

* Fix

Co-authored-by: Clyybber <darkmine956@gmail.com>
Co-authored-by: n5m
(cherry picked from commit 436e1fa5b1)
2020-10-21 11:03:17 +02:00
Clyybber
893dab429e Fix #15639 (#15640)
(cherry picked from commit 0f4b1ed270)
2020-10-21 11:02:27 +02:00
cooldome
1e9746aade arc allocation method aligned (#15588)
* progress

* fix typo

(cherry picked from commit 833035bacd)
2020-10-21 11:02:10 +02:00
cooldome
35f5a3e48f Tables, use sink val arguments more actively (#15625)
(cherry picked from commit 04f8fcfbd0)
2020-10-21 11:01:50 +02:00
n5m
642807de18 add tests for #15584 (#15619)
* add test for #15584

* Rename userlocks.nim to trlocks.nim

* add bug comment

* improve cmd

* reference bugfix, not bug

* add test that runs rlocks

* disallow joining

joining with other test cases (e.g., a test case that invokes `RLock.initRLock()`) may cause this test to compile, when the goal is to test if these lines can be compiled in isolation

(cherry picked from commit 78cbb52fa0)
2020-10-21 11:00:33 +02:00
Euan
8a9da2fa0d Fix FreeBSD build failures (#15613)
The FreeBSD is/was failing, due to a conflict with installing Git.

Git is guaranteed to be in the base image, so this removes that package from the package list. It also reverts back to the built-in `packages` tag since it's officially supported.

Should the build fail in the future, the best place to go is the #sr.ht channel on freenode.

(cherry picked from commit ba2a477e64)
2020-10-21 11:00:21 +02:00
n5m
a222aa14e1 document that Nim executable must be included (#15611)
(cherry picked from commit b16b2eb06f)
2020-10-21 10:59:20 +02:00
Clyybber
d86d7c9fe1 Fix #15599 (#15601)
* Fix #15599

* Add test

(cherry picked from commit 66cd9c2e57)
2020-10-21 10:58:57 +02:00
Andreas Rumpf
b3c77bb982 fixes #15560 (#15587)
(cherry picked from commit a43202ea57)
2020-10-21 10:58:01 +02:00
narimiran
1dffa67b6e bump NimVersion to 1.4.1 2020-10-21 10:57:51 +02:00
narimiran
bdcd87afca cosmetic fixes for the 1.4 changelog [ci skip]
(cherry picked from commit 6b8baab536)
2020-10-16 13:19:32 +02:00
narimiran
018ae963ba add bufixes for 1.4 in its changelog
(cherry picked from commit 091ec916fd)
2020-10-16 08:14:05 +02:00
narimiran
cffbf5e778 create a changelog for 1.4.0
(cherry picked from commit 6349001879)
2020-10-16 07:17:09 +02:00
narimiran
cac0e01725 bump NimVersion to 1.4.0 2020-10-15 16:10:08 +02:00
shirleyquirk
4ef255b69d fix rlock compilation failure (#15584)
* change SysLockType_Reentrant

fix edge case where using SysLockType_Reentrant doesn't trigger an #include pthread.h

* syslocktype_reentrant now a var
* remove nodecl to remove empty system_syslocks.c
* let is better than var.

in reality SysLockType = enum, maybe that would be a better fix
2020-10-15 12:54:01 +02:00
Andreas Rumpf
da4aa2e1fb renamed '=' to '=copy' [backport:1.2] (#15585)
* Assign hook name changed to `=copy`
* Adapt destructors.rst
* [nobackport] Duplicate tests for =copy hook
* Fix tests
* added a changelog entry

Co-authored-by: Clyybber <darkmine956@gmail.com>
2020-10-15 12:52:30 +02:00
Igor Ribeiro de Assis
42c180c665 Fix crash in parsexml (#15582) (#15583)
Co-authored-by: Igor Ribeiro de Assis <igor.ribeiro_de_assis@zeiss.com>
2020-10-15 12:45:55 +02:00
Andreas Rumpf
fd9ab2ce6d ORC: API extensions for 1.4 (#15581) 2020-10-15 11:51:40 +02:00
Andreas Rumpf
1bbc20010e harden the ORC asyncleak3 test case (#15580)
* harden the ORC asyncleak3 test case

* add another ORC stress test
2020-10-15 09:42:43 +02:00
genotrance
a4c28394be Bump nimble (#15573) 2020-10-14 22:26:44 +02:00
Andreas Rumpf
644eb4dd54 ORC: critical bugfix for the cycle analyser, introduce -d:nimStressOrc for easier stress testing (#15572) 2020-10-14 22:26:21 +02:00
alaviss
c2ba4ef979 suggest: try to find the implementation of a symbol when def is used (#15555)
* suggest: try to find the implementation of a symbol when def is used

* suggest: return all declarations of the symbol on `def`
2020-10-14 17:08:56 +02:00
Clyybber
977bccdbff Make useVersion:1.0 disable the proc arg sym change (#15570)
* Make useVersion:1.0 disable the proc arg sym change

* Also do this for useVersion:1.2
2020-10-14 16:07:25 +02:00
Andreas Rumpf
8978112457 fixes a C code generator regression, no need to backport, only the 1.4 line is affected (#15569) 2020-10-14 13:58:36 +02:00
Timothee Cour
09cad44be9 ci docs: add config/nimdoc.cfg to paths (#15566) 2020-10-14 12:04:14 +02:00
Benjamin Lee
12c8ef5949 Update the list of GC options when raising an error (closes #15547) (#15553) 2020-10-14 11:20:59 +02:00
Andreas Rumpf
c664fb2843 sigmatch: hotfix [backport] (#15565) 2020-10-14 09:55:47 +02:00
narimiran
fc90eb9f27 change case in nimdoc [ci skip] 2020-10-14 09:26:44 +02:00
Timothee Cour
0c0f86b2c5 reference fusion docs (#15562) 2020-10-14 09:25:28 +02:00
alaviss
d1af9587b8 terminal: fix fgColor/bgColor commands [backport] (#15554)
Since #8296, fgSetColor is no longer a global. These commands were
probably left out from the change as an oversight, so some tests have
been added to make sure this won't happen again.
2020-10-13 17:39:32 +01:00
Timothee Cour
0134e34e03 dup docs: add an example with addQuoted (#15548)
* dup docs: add addQuoted example

* fixup
2020-10-13 08:24:30 +02:00
Christopher Dunn
f1d81dc6e6 Fix doc for CountTable (#15561) [backport] 2020-10-13 06:33:53 +02:00
Christian Ulrich
1f51a33998 close socket in getPrimaryIPAddr even if exception occurs (#15558) 2020-10-12 22:02:17 +02:00
Timothee Cour
30b966bdf7 unbreak CI: fix logic for skipping ci (#15556) 2020-10-12 21:04:40 +02:00
cooldome
9668a1106d Fix 15543 (#15544)
* fix #15543

* fix spacing

* fix test

* simplify test for freebsd platform
2020-10-12 10:12:32 +01:00
Andreas Rumpf
d66e274e1a refactoring: moved setOutFile to where it belongs 2020-10-11 20:44:04 +02:00
Andreas Rumpf
3492178494 refactoring: removed cmdlinehelper.mainCommand callback 2020-10-11 20:44:04 +02:00
flywind
c2c7f60259 docs minor (#15550) 2020-10-11 20:43:44 +02:00
Timothee Cour
3eac9b2344 os: add overload copyFile*(source, dest: string, isDir = false) (#15537)
* os: add overload copyFile*(source, dest: string, isDir = false)
* renamed to copyFileToDir
2020-10-11 20:43:01 +02:00
Andreas Rumpf
992952d868 nimpretty: do not produce 'line too long' messages (#15541) 2020-10-10 17:46:22 +02:00
Christian Ulrich
c7ccbfac39 close socket in getPrimaryIPAddr (#15538) [backport] 2020-10-10 07:06:13 +02:00
Timothee Cour
8a5f550491 followup after #15529 and #15534 (#15536) 2020-10-10 07:05:27 +02:00
genotrance
442841037a Fix #12027 (#15519) 2020-10-10 07:04:57 +02:00
genotrance
0a560144ce Bump nimble (#15539) 2020-10-10 07:04:03 +02:00
Andreas Rumpf
d430216288 fixes #15532 (#15534) 2020-10-09 16:18:36 +02:00
Timothee Cour
16e8005031 fix gitignore for testament cruft (#15530)
* fix gitignore for testament cruft

* fix rendertree => renderTree
2020-10-09 11:28:21 +02:00
Timothee Cour
8fb57d7451 close #13081 (#15529)
* close #13081

* fixup
2020-10-09 08:56:09 +02:00
cooldome
91ce4515c8 fix gc:arc in nimscript (#15525) 2020-10-09 08:52:26 +02:00
lihaifeng
3eaacac230 Update parsecfg.nim (#15513)
* Update parsecfg.nim

Returns the specified default value if the specified key value does not exist.

* Update lib/pure/parsecfg.nim

Co-authored-by: flywind <43030857+xflywind@users.noreply.github.com>

* Update lib/pure/parsecfg.nim

Co-authored-by: flywind <43030857+xflywind@users.noreply.github.com>

* Update lib/pure/parsecfg.nim

Co-authored-by: flywind <43030857+xflywind@users.noreply.github.com>

Co-authored-by: flywind <43030857+xflywind@users.noreply.github.com>
2020-10-08 17:17:00 +02:00
Andreas Rumpf
538a57a522 fixes #15511 (#15524) 2020-10-08 17:09:28 +02:00
Andreas Rumpf
cfba237d14 fixes #15510 (#15523) 2020-10-08 15:28:23 +02:00
ee7
aa0b73575c changelog.md: Group the new to procs (#15522)
* changelog.md: Group the new `to` procs [ci skip]

This also moves the `critbits.toCritBitTree` entry from the "Language
Changes" section to the "Standard library additions and changes"
section.

* changelog.md: Remove extra space
2020-10-08 14:21:20 +02:00
Andreas Rumpf
1e9d83efb0 fixes #15512 (#15521) 2020-10-08 14:17:27 +02:00
Araq
4d91cc7950 changelog improvements 2020-10-08 11:43:18 +02:00
Araq
0ac74ddd74 fixes a regression 2020-10-08 11:43:18 +02:00
cooldome
fe187719ab fix #15516 (#15518) 2020-10-08 09:12:03 +02:00
Andreas Rumpf
3b901d1e36 docgen: improve alignment of comments (still not perfect) (#15506)
* docgen: improve alignment of comments (still not perfect)

* fix error message text in `tunknown_named_parameter`

Co-authored-by: narimiran <narimiran@disroot.org>
2020-10-07 14:39:13 +02:00
Andreas Rumpf
0426a4d85a fixes #15508 (#15509) 2020-10-07 14:38:25 +02:00
Andreas Rumpf
acbe27b082 disable 'observable stores' warning message for 1.4 (#15507) 2020-10-07 13:05:19 +02:00
Andreas Rumpf
51e3e0c7c4 implements https://github.com/nim-lang/RFCs/issues/260 (#15505)
* implements https://github.com/nim-lang/RFCs/issues/260

* added a test case
2020-10-07 00:09:28 +02:00
Serban Constantin
dd86228548 update unittest docs with correct exit code info (#15502) 2020-10-06 18:05:57 +02:00
Paul Tan
fa84121421 effects: exclude swap() from "indirect calls" assumption (#15504)
swap() will never call any procs passed to it, and so it can be safely
excluded from the "assume indirect calls are taken" effects tracking
rule.
2020-10-06 18:05:31 +02:00
Juan Carlos
695f955f70 inline tiny proc (#15498) 2020-10-06 16:52:12 +02:00
IDF
9560e49e8f New hint for unused exceptions in .raises (#15492)
* New hint for unused exceptions in .raises

* Fix effects test

* Further adapt teffects1.nim
2020-10-06 16:49:30 +02:00
Andreas Rumpf
92163fa330 implements https://github.com/nim-lang/RFCs/issues/258 (#15503)
* implements https://github.com/nim-lang/RFCs/issues/258

* don't be too strict with custom pragma blocks

* cast pragmas: documentation

* added most missing inference query procs to effecttraits.nim
2020-10-06 16:47:15 +02:00
Benjamin Lee
acd71dd6bb Iterate over smaller set when computing intersection (#15497)
Closes #15496
2020-10-06 10:29:45 +02:00
Juan Carlos
aca1fae55a GitHub Actions Skip CI (#15289) 2020-10-06 04:52:49 +00:00
Araq
37758826ff typo 2020-10-06 06:33:43 +02:00
Araq
e9d7e21dbe minor reformating 2020-10-06 06:10:47 +02:00
Andreas Rumpf
4e438f9096 const view types; fixes some cases from https://github.com/nim-lang/Nim/issues/15428 (#15488) 2020-10-05 18:31:46 +02:00
Juan Carlos
1e28cea0d1 inline tiny func on httpcore (#15480) 2020-10-05 17:08:50 +02:00
David Krause
f25ca0d304 added testament documentation link to tools.rst (#15481) 2020-10-05 17:04:47 +02:00
flywind
af9cc2882f use func in uri module (#15486) 2020-10-05 17:04:08 +02:00
Miran
112b11c154 group procs of the same name in TOC (#15487)
* group procs of the same name in TOC

* correctly show `sink` parameters in TOC

* no need to reinvent the wheel - `mgetorPut` exists

* better setting of text color [ci skip]

* fix CSS for better alignment
2020-10-05 17:03:14 +02:00
Luis Felipe Manfroni
5967b6f60f doc(sugar): added description and examples to dup (#15455) 2020-10-05 12:02:08 +02:00
Euan
cc4c546f8f Fix #15493 - disable TLS emulation for NetBSD (#15494)
TLS emulation was already disabled for FreeBSD due to the same issue.
2020-10-05 12:00:06 +02:00
flywind
b760fdc9ca make testing for prologue more stable (#15491) 2020-10-05 09:57:23 +02:00
supakeen
bbe2eb20df Provide a configurable progressInterval. (#15477) 2020-10-04 11:32:07 +01:00
Abhishek Dubey
ccd1f58183 Installation Instruction (#15485)
The instruction command was missing `install` for Ubuntu.
2020-10-04 10:58:19 +02:00
alaviss
fc973b2c0c renderer: use the biggest integer type for masking literals (#15482)
On 32-bit system the mask would have a size of 32-bit, which is smaller
than the BiggestInt (usually 64-bit) it was masked against.

For some reason this only affect 32-bit Windows but not 32-bit Linux.
Might just be a difference in how gcc handle out of bound shifts for
Windows and Linux.
2020-10-04 00:39:56 +02:00
Andreas Rumpf
2288188fe9 fixes https://github.com/nim-lang/RFCs/issues/257 [backport:1.2] (#15479) 2020-10-03 17:34:42 +02:00
supakeen
662c508075 Return type of asyncftpclient to fix example. (#15476)
Related to: #13641
2020-10-03 13:43:43 +02:00
alaviss
dcd0ce1775 niminst: restore ZIP building functionality (#15472)
This is necessary for building Windows releases, was erroneously removed
by #15451.
2020-10-02 22:48:35 +02:00
ee7
0a05176057 heapqueue.nim: Add toHeapQueue proc (#15459)
Similar to:
- `critbits.toCritBitTree`
- `deques.toDeque`
- `sets.toHashSet`
- `tables.toTable`

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2020-10-02 16:01:03 -04:00
ee7
d48b356e49 intsets.nim: Add toIntSet proc (#15460)
Similar to:
- `critbits.toCritBitTree`
- `deques.toDeque`
- `sets.toHashSet`
- `tables.toTable`
2020-10-02 21:10:24 +02:00
alaviss
7ef22bf912 koch: remove c2nim from windows release builds (#15471)
We don't ship this tool with any other OS, and the c2nim bundle is
non-deterministic due to the lack of a pinned commit.
2020-10-02 19:18:44 +02:00
Andreas Rumpf
9828392df3 implements https://github.com/nim-lang/RFCs/issues/257 (#15466) 2020-10-02 18:53:22 +02:00
alaviss
e3eae3f7c7 tools/deps: fix git dir check (#15470)
On Windows, a successful call will have a trailing newline appended, so
strip that away before doing any checks.
2020-10-02 18:52:20 +02:00
Andreas Rumpf
ff70ff529d remove nim.cfg file change lefover [backport:1.2] (#15469) 2020-10-02 18:51:49 +02:00
Andreas Rumpf
7d8c1be8fb parser hotfix: don't run into endless loops; regression (#15468) 2020-10-02 18:26:52 +02:00
Andreas Rumpf
1f4b9cebd4 Added std/effecttraits.nim (#15462) 2020-10-02 17:22:31 +02:00
Andreas Rumpf
aa1d7fe1e9 closureiters: fixes #15243 (#15454) [backport:1.2]
* fixes #15243 [backport:1.2]
2020-10-02 12:38:16 +02:00
Euan
f785174c60 Ref #14094 - disable hot code reloading tests on NetBSD (#15458) 2020-10-02 11:17:31 +02:00
flywind
6e32a9e88c use func in httpcore (#15457) 2020-10-02 08:47:24 +02:00
Juan Carlos
d1eb76184b Clean out niminst (#15451) 2020-10-01 22:19:06 +02:00
Euan
b4fe0c8862 Fix #15452 - ip protocol not defined on NetBSD (#15453) 2020-10-01 22:15:34 +02:00
Clyybber
37e0d6f32d Fix typo 2020-10-01 19:58:53 +02:00
Clyybber
800d6204cd Fix "arraq" typo :) 2020-10-01 19:58:08 +02:00
shirleyquirk
84d9b1227d fixes #15430, pop pragma takes invalid input (#15449)
* fix #15430, pop pragma

{.pop, experimental.} should be allowed, but not {.pop experimental.}
2020-10-01 18:07:55 +02:00
c-blake
26d656e73e Add first draft of new osproc.readLines (#15429)
* Add first draft of new osproc.readLines

* Add test for new osproc.readLines

* Rename test to start w/t to run; Also add newline to output

* Suppress hint messages.

* Output should match this time.

* Shoulda picked a program with simpler syntax than ..lol

* Address https://github.com/nim-lang/Nim/pull/15429#issuecomment-701890898
and https://github.com/nim-lang/Nim/pull/15429#issuecomment-701985976 by
factoring `readLines` into `iterator lines` and a wrapper `proc`.

* Address https://github.com/nim-lang/Nim/pull/15429#issuecomment-702127289
and also add a `ReadIOEffect` tag to the iterator (called by the wrapper..
so it should need no separate tag, if I understand correctly).
2020-10-01 18:06:38 +02:00
cooldome
531ed2dc36 fix #15405. deepcopy arc (#15410)
* fix #15405
* fix tests
* deepcopy for ARC has to be enabled via --deepcopy:on

Co-authored-by: Araq <rumpf_a@web.de>
2020-10-01 17:39:48 +02:00
alaviss
3919f0aa54 koch: unify nimble building scripts [backport:1.4] (#15443)
This commit gets rid of buildNimble in favor of the simpler
bundleNimbleExe, which does pretty much the same thing.
2020-10-01 17:20:38 +02:00
flywind
0bfa0fcaea [docs minor] unify generates and Generates (#15434)
* [docs] unify generates and Generates

* fix typo
2020-10-01 15:17:16 +02:00
Juan Carlos
5e160bff1b Add critbits.toCritBitTree (#15444)
* Add critbits.toCritBitTree

* https://github.com/nim-lang/Nim/pull/15444#discussion_r498035342
2020-10-01 15:11:10 +02:00
Juan Carlos
8f90ac6af1 Clean out (#15448) 2020-10-01 15:07:57 +02:00
Andreas Rumpf
ab405c936e views: yet another bugfix (#15447)
* views: yet another bugfix

* views: extended the spec

* views: take into account potential hidden mutations via proc calls
2020-10-01 15:04:36 +02:00
Juan Carlos
79a92da8ef Clean out (#15440) 2020-10-01 12:39:50 +02:00
Juan Carlos
4e7d383f29 Clean out jssys (#15442) 2020-10-01 11:21:27 +02:00
Andreas Rumpf
2b91845f1d refactoring, fixes yet another strictFuncs regression (#15446) 2020-10-01 11:16:04 +02:00
Andreas Rumpf
b703f02ad2 added missing .noalias support for object fields (#15445) 2020-10-01 09:46:50 +02:00
Juan Carlos
6b3654c48d Add 1 overload to apply (#15439) 2020-10-01 09:22:22 +02:00
Andreas Rumpf
86d7b63e2a better support for view types (#15436)
* you can put borrows into tables

* enforces mutating views only mutate mutable data
2020-09-30 20:44:18 +02:00
flywind
9c86f4867e fix doc search(escape HTML code) (#15433)
* use release version

* fix doc search
2020-09-30 10:52:49 +02:00
Miran
eb2a4961c7 various documentation fixes [backport] (#15422) 2020-09-29 23:43:12 +02:00
Andreas Rumpf
4058801607 spec for view types (#15424)
* spec for view types
* spec additions
* refactoring; there are two different kinds of views
* refactorings and spec additions
* enforce that view types are initialized
* enforce borrowing from the first formal parameter
* enforce lifetimes for borrowing of locals
* typo in the manual
* clarify in the implementation what a borrow operation really is
2020-09-29 23:42:38 +02:00
shirleyquirk
f8866598e7 odbc regression from #14357 (#15417)
#14357 changed from sending 'val', an int, to a pointer to int, which is understandable, but not how SQLSetEnvAttr works.
"Depending on the value of Attribute, ValuePtr will be a 32-bit integer value or point to a null-terminated character string"
2020-09-29 17:08:24 +02:00
Yuriy Glukhov
22d0a39932 Dont assert on setstacksize result in iOS (#15427) [backport:1.2] 2020-09-29 16:55:53 +02:00
Timothee Cour
5f9b366180 document that items no longer works with enum with holes (#15426) 2020-09-29 07:54:17 +02:00
Andreas Rumpf
50b6f6996a .noalias annotation; frontend support (#15419)
* .noalias annotation; frontend support

* added .noalias support to Nim; implements https://github.com/nim-lang/RFCs/issues/204
2020-09-28 13:51:39 +02:00
Andreas Rumpf
453167a41e cleanup lib/system/stacktraces.nim; refs #15416 (#15418) 2020-09-28 10:51:13 +02:00
Andreas Rumpf
f1ac01459c produce runtime type information for reified openArrays (#15415)
* produce runtime type information for reified openArrays

* added a test case
2020-09-27 20:44:22 +02:00
hlaaftana
0ea559611d Fix proc generic params ident defs, missing empty (#15412) 2020-09-27 19:47:58 +02:00
Andreas Rumpf
57b7841c18 better support for slices as views (#15414)
* moved view tests to tests/views
* refactoring
* more refactorings
* better support for system.toOpenArray for first class view types
2020-09-27 09:20:10 +02:00
Andreas Rumpf
e6616115e6 cursor inference: makes combparser work; refactorings (#15411)
* cursor inference: makes combparser work; refactorings
2020-09-26 13:11:35 +02:00
alaviss
d4892e9388 koch, compiler: bundle fusion as part of the source archive (#15409)
This allows distributions to build Nim from the downloaded source
archive without an Internet connection.
2020-09-26 09:31:55 +02:00
Miran
2de6e18774 fix #11537, correct parse inline code without surrounding spaces (#15399) 2020-09-25 09:25:47 +02:00
Andreas Rumpf
e9fa486493 fixes #14983 (#15320)
* fixes #14983

* allow bootstrapping with 0.20

* added a test case for the new system.add with a sink parameter

* make npeg green again
2020-09-25 08:49:21 +02:00
cooldome
68ec7a018b Revert "fix #15035 (#15236)" (#15408)
This reverts commit f8c48fc186.
2020-09-24 22:21:14 +02:00
Andreas Rumpf
e3b5f80a89 more precise borrow checking of 'result' (#15406) 2020-09-24 22:07:23 +02:00
Andreas Rumpf
ce72d7ffc5 fixes #15403 (#15404) 2020-09-24 19:34:59 +02:00
Miran
496e9f74e1 fix #14474, crash inside of a sole code-block (#15402) 2020-09-24 16:41:08 +02:00
Andreas Rumpf
4ec5cbac0d fixes #15361 (#15401)
* fixes #15361; better cursor inference
2020-09-24 15:41:45 +02:00
flywind
8a6c5edc43 use release version (#15400) 2020-09-24 14:14:23 +02:00
flywind
e85c5ad379 fix #15333 (#15336) 2020-09-24 08:54:13 +02:00
genotrance
7a6f4eca19 Bump nimble (#15398) 2020-09-24 08:07:32 +02:00
cooldome
f21a49b2c4 Fix #15389 (#15390)
* allow result symbol reuse

* try different approach

* Revert "try different approach"

This reverts commit abcfb6b759.
2020-09-24 00:07:30 +01:00
Miran
fe3211fbcf fix the indentation in --help and --fullhelp (#15387)
* fix the indentation in `--help` and `--fullhelp`

* a better way to fix it
2020-09-23 12:44:41 +02:00
Araq
94c8d53a03 'koch temp' bugfix 2020-09-23 10:41:33 +02:00
Andreas Rumpf
e2d80b15a6 finish the stacktraces.nim implementation [backport:1.2] (#15393) 2020-09-23 10:01:52 +02:00
Clyybber
4b9eea2fcc Fix forward declarations in shadow scope contexts (#15386)
* Fix forward declarations in shadow scope contexts

* Add testcase for #15385

* Less empty lines

* Fix tests

* Inline isShadowScope

* Add original testcase (with reduced amount of iterations)

* Add testcase without forward decl
2020-09-22 18:24:13 +02:00
Miran
11c377c114 add enumerate macro (#15297)
* add `enumerate` macro

* address the comments

* put `enumerate` in its own module
2020-09-22 13:08:36 +02:00
flywind
ab05e141c0 deinitLock (#15383)
* deinitLock

* minor
2020-09-22 13:07:31 +02:00
Andreas Rumpf
1fae66e4df better nativestacktrace support; refs #15284; backport [1.2] (#15384)
* nimStackTraceOverride: enable stack traces in exceptions

This is a two-step stack trace collection scheme, because re-raised
exceptions will collect multiple stack traces but use them rarely, when
printing info about an uncaught exception, so it makes sense to only do
the cheap stack unwinding all the time and the relatively expensive
debugging information collection on-demand.

`asyncfutures` implements its own `$` proc for printing
`seq[StackTraceEntry]`, so we have to add the debugging info there, just
like we do for the private `$` proc in `system/excpt`.

* cleaned up PR #15284

Co-authored-by: Ștefan Talpalaru <stefantalpalaru@yahoo.com>
2020-09-22 13:03:24 +02:00
Clyybber
d67c5cb751 Add strutils.indentation and make unindent use it (#15264)
* Add strutils.indentation and make unindent use it

* Code style

* Fix bootstrapping

* Improve wording

* Fix test

* Introduce without breaking change

* Fix

* Reduce diff

* Fix docs link

* Add since annotation

* Update changelog
2020-09-22 10:43:12 +02:00
alaviss
aca9c5fb30 os: make getApplFreebsd available for NetBSD (#15381)
NetBSD was switched to getApplFreebsd() in #15359, however the proc was
not made available for the said target.

This commit exposes `getApplFreebsd()` to NetBSD.
2020-09-21 19:52:44 +02:00
genotrance
8f511fd0e6 Bump nimble (#15380) 2020-09-21 11:48:00 -05:00
Miran
4645183272 fix #6430, support :target: for images (#15379) 2020-09-21 17:01:12 +02:00
flywind
40a868bccc add testcase for #6060 (#15366)
* add testcase for #6060

* Remove overspecific testament spec

Co-authored-by: Clyybber <darkmine956@gmail.com>
2020-09-21 13:37:14 +02:00
flywind
6c83eb48c2 add testcase for #7165 (#15368)
* add testcase for #7165

* Remove overspecific testament spec

Co-authored-by: Clyybber <darkmine956@gmail.com>
2020-09-21 13:32:05 +02:00
Juan Carlos
db9ab2a4c0 Documentation prelude (#15377) 2020-09-21 12:37:14 +02:00
Andreas Rumpf
c2434d939e fixes #15360 [backport:1.2] (#15378) 2020-09-21 12:35:23 +02:00
flywind
0a1e4cad7f add testcase for #9710 (#15365)
* string is not nil anymore

* tatus
2020-09-21 12:21:05 +02:00
Andreas Rumpf
4d75059e8b added a basic ORC test I still had lying around (#15376) 2020-09-20 22:47:48 +02:00
Andreas Rumpf
04cecdf9c2 async: removed the 'unown' references, async never worked with --newruntime anyway and --newruntime is dead (#15374) 2020-09-20 18:01:07 +02:00
Araq
cdac67376c arc: added tmarshal.nim test case 2020-09-20 10:43:57 +02:00
Araq
33be7c6f5e arc: =deepcopy fixes 2020-09-20 10:43:57 +02:00
Andreas Rumpf
ebb632ccba fixes #15369 (#15371) 2020-09-20 01:07:13 +02:00
Andreas Rumpf
a15d77df7e ORC/ARC async progress (#15370)
* ARC/ORC: fixes memory leak for empty seqs that have a non-zero capacity

* async: minor refactorings

* it helps to finish a refactoring
2020-09-20 00:27:32 +02:00
Andreas Rumpf
cbdda631db base64: fixes the error message for an invalid base64 input character [backport:1.2] 2020-09-20 00:05:41 +02:00
Andreas Rumpf
9a34009f00 ORC and stdlib optimizations (#15362) 2020-09-19 00:27:43 +02:00
Timothee Cour
8ae4a774b7 doc fix typo in lib/pure/httpclient.nim (#15364) 2020-09-19 00:20:41 +02:00
Euan
ae1f5c1559 Use sysctl on NetBSD to get exe name (#15359) 2020-09-18 22:26:53 +02:00
yatsen1
341cd844b2 fix coro proc crash for stack problem when run long enough than a GC cycle (#7612) (#11410)
Co-authored-by: drswinghead <drswinghead@gmail.com>
Co-authored-by: Clyybber <darkmine956@gmail.com>
2020-09-18 17:17:09 +02:00
Andreas Rumpf
d19316bbb9 more ORC bugfixes (#15355)
* introduced --define:nimArcIds

* ORC: bugfixes
2020-09-18 11:55:58 +02:00
narimiran
59b7857167 bump NimVersion to 1.3.7 2020-09-18 11:50:15 +02:00
Andreas Rumpf
2671efab78 async: minor refactorings (#15354) 2020-09-18 11:22:34 +02:00
jcosborn
e56d50d747 fix infinite recursion in typeRel (#15241)
* fix generic constraints

Co-authored-by: James Osborn <osborn@Jamess-MacBook-Pro.local>
2020-09-18 11:21:37 +02:00
flywind
c57023f324 string is not nil anymore (#15352) 2020-09-18 10:02:31 +02:00
Miran
cbd78ec1f6 close #6071, remove the mentions of deprecated docSeeSrcUrl (#15350) 2020-09-17 19:55:18 +02:00
Andreas Rumpf
bc9967f05a Revert "Introduce explicit copy (#15330)" (#15346)
This reverts commit a3e9cc5234.
2020-09-16 23:24:17 +02:00
cooldome
d938c6411e fix #15326 (#15341) 2020-09-16 21:37:23 +02:00
Juan Carlos
913ffbb92d Add documentation for Testament (#15344) 2020-09-16 21:31:35 +02:00
Yuriy Glukhov
28a64869f0 Fixed undeclared nimIdentNormalize compilation error in parseEnum (#15343) 2020-09-16 19:41:57 +02:00
Andreas Rumpf
8b66412a8b fixes #9754 [backport] (#15342) 2020-09-16 19:41:14 +02:00
cooldome
341be0b61c proc params as syms (#15332)
* proc params are now syms

* Fix typesrenderer

* Add testcase for disrupteks issue

* fix test

* Trigger build

* Trigger build

* Trigger build

Co-authored-by: Clyybber <darkmine956@gmail.com>
2020-09-16 17:25:24 +01:00
cooldome
a3e9cc5234 Introduce explicit copy (#15330) 2020-09-16 17:26:45 +02:00
Andreas Rumpf
ae4ede6b00 fixes #15325 (#15340) 2020-09-16 17:26:13 +02:00
flywind
de7f2372be docs minor and #15335 (#15337) 2020-09-16 14:58:50 +02:00
Andreas Rumpf
fd31e8ff6f allow old styled RTTI for arc/orc (#15331) 2020-09-16 14:57:01 +02:00
flywind
0aaf4e2dfa Methods docs improvement (#15338)
* docs improvement

* minor
2020-09-16 14:51:01 +02:00
Andreas Rumpf
bc179ccc3f fixes #15076 (#15329) 2020-09-15 12:40:23 +02:00
Juan Carlos
073bea6606 Remove Deprecated {.this:self.} from Documentation so people dont use it anymore (#15328) 2020-09-15 11:59:33 +02:00
Andreas Rumpf
c38487aa22 fixes a critical ORC bug, refs #15076 (#15323) 2020-09-14 12:50:23 +02:00
flywind
e111b610ca test cookies with comma for #15319 (#15322)
* test cookies with comma for #15319

* space
2020-09-14 12:20:42 +02:00
flywind
366216da64 fix cookie with comma (#15319) 2020-09-14 09:00:29 +02:00
Juan Carlos
a667475aaf dom.Navigator add missing attributes (#15310)
* Add missing attributes and methods to dom.Navigator

* Add missing attributes and methods to dom.Navigator

* Add missing attributes and methods to dom.Navigator
2020-09-14 08:58:21 +02:00
Jaremy Creechley
6c49767a6c Fixing issue #15302 -- lwip doesn't support signals (#15303)
* Fixing issue #15302 -- lwip doesn't support signals

* Adding test to catch issue #15302 -- lwip/freertos net library
don't try to build / run on windows, it'll compile only but not run

Fixing issue #15302 -- reworking test to compile on other platforms
2020-09-14 08:57:49 +02:00
Andreas Rumpf
1df5cfba52 fixes #15147 (#15315) 2020-09-12 23:11:38 +02:00
Clyybber
60ad95f799 Add testcase for invalid if statement (#15313) 2020-09-12 14:28:19 +02:00
Clyybber
1881fc5812 Fix #15305 (#15311)
* Fix #15305

* Fix test
2020-09-12 12:39:46 +01:00
flywind
a41b243fea remove annoying messages when creating orderedTables (#15309)
* nativesockets docs minor [backport: 1.2]

* remove annoying messages
2020-09-12 10:34:11 +02:00
narimiran
5f08d39398 fix broken links in the documentation 2020-09-12 09:22:14 +02:00
genotrance
f1f694dccb Bump nimble (#15304) 2020-09-11 11:57:54 -05:00
Araq
9e4920c068 fixes #15021 2020-09-11 14:21:09 +02:00
Juan Carlos
c4e03b540e Fix #15183 (#15300) 2020-09-11 08:57:57 +02:00
Andreas Rumpf
0c41ac792b fixes #15122 (#15301) 2020-09-11 01:50:42 +02:00
Miran
6a621b35e7 fix warnings for deprecated low and high (#15291) 2020-09-11 01:04:07 +02:00
hlaaftana
625edf6a98 Add /lib/fusion to gitignore (#15295) 2020-09-11 00:43:10 +02:00
Juan Carlos
b03d221d0b Improve prelude so it does not hijacks documentation when used (#15299) 2020-09-11 00:25:09 +02:00
Andreas Rumpf
9a110047cb testament improvement: allow inline error messages inside test cases (#15294)
* testament support for inline error messages
* adapt teffects1.nim test to show the potential
2020-09-10 16:30:20 +02:00
cooldome
61c85e034d Fix #15286 (#15292)
* fix #15286

* fix spacing
2020-09-10 12:40:39 +02:00
Andreas Rumpf
3f00a738db fixes #15280 [backport:1.2] (#15281)
* fixes #15280 [backport:1.2]

* make tests green again

* adapt tests
2020-09-09 14:20:10 +02:00
Andreas Rumpf
217675cf84 borrow checking refinements (#15290)
* added basic borrowing test
2020-09-09 14:19:22 +02:00
Ivan Bobev
ccd77b42af Add some enhancements to jsonutils.nim (#15133)
* Add some enhancements to `jsonutils.nim`

* Use `jsonutils.nim` hookable API to add a possibility to deserialize
  JSON arrays directly to `HashSet` and `OrderedSet` types and
  respectively to serialize those types to JSON arrays.

* Also add a possibility to deserialize JSON `null` objects to Nim
  option objects and respectively to serialize Nim option object to JSON
  object if some or to JSON `null` object if none.

* Move serialization/deserialization functionality for `Table` and
  `OrderedTable` types from `jsonutils.nim` to `tables.nim` via the
  hookable API.

* Add object `jsonutils.Joptions` and parameter from its type to
  `jsonutils.fromJson` procedure to control whether to allow
  deserializing JSON objects to Nim objects when the JSON has some
  extra or missing keys.

* Add unit tests for the added functionalities to `tjsonutils.nim`.

* improve fromJsonFields

* Add changelog entry for the jsonutils enhancements

* Add TODO in `jsonutils.nim`

* Added an entry to "Future directions" section in `jsonutils.nim` as
  suggestion for future support of serialization and de-serialization of
  nested variant objects.

* Added currently disabled test case in `tjsonutils.nim` for testing
  serialization and de-serialization of nested variant objects.

* Move JSON hooks to `jsonutils.nim`

Move `fromJsonHook` and `toJsonHook` procedures for different types to
`jsonutils.nim` module to avoid a dependency of collections modules to
the `json.nim` module.

The hooks are removed from the following modules:

  * `tables.nim`

  * `sets.nim`

  * `options.nim`

  * `strtabs.nim`

* Add some tests about `StringTableRef`

Add tests for `StringTableRef`'s `fromJsonHook` and `toJsonHook` to
`tjsonutils.nim`.

* Disable a warning in `jsonutils.nim`

Mark `fun` template in `jsonutils` module with `{.used.}` pragma in
order to disable `[XDeclaredButNotUsed]` hint. The template is actually
used by the `initCaseObject` macro in the same module.

Co-authored-by: Timothee Cour <timothee.cour2@gmail.com>
2020-09-09 14:18:59 +02:00
narimiran
8a2cd7b24b [ci skip] fix typo in the manual 2020-09-09 12:59:14 +02:00
flywind
8c82144ba5 add getprotobyname (#15273)
* add getprotobyname

* tests, docs, changelog

* add since
2020-09-09 12:47:22 +02:00
Miran
7d4f0df107 deprecate high(value) and low(value) (#15283) 2020-09-09 12:43:04 +02:00
Clyybber
f3552b86c1 Better semiStmtList parsing (#15123)
* Better semiStmtList parsing
* Add examples from forums and wiki
* Move parseIfExpr near parseIfOrWhen
* Update grammar
2020-09-09 07:36:31 +02:00
Andreas Rumpf
10988d4840 borrow checking (#15282)
* refactoring: move procs to typeallowed.nim
* frontend preparations for first class openArray support
* prepare the code generator for first class openArray
* code generation for first class openArray; WIP
* code generation for open arrays, progress
* added isViewType proc
* preparations for borrow checking
* added borrow checking to the front end
2020-09-09 07:32:03 +02:00
Miran
c49b88163c "for-loop macros" are no longer an experimental feature (#15288) 2020-09-08 14:25:25 +02:00
flywind
a81610230d nativesockets docs minor [backport: 1.2] (#15285) 2020-09-08 11:27:43 +02:00
Scott Wadden
098a8a7c52 nimeval errorHook support (#15255) 2020-09-07 20:05:07 +02:00
Andy Davidoff
0b74d26d0c don't raise index defects on malformed ast (#15278)
* don't raise index defects on malformed ast

* style
2020-09-07 20:04:07 +02:00
flywind
e08b802d79 more Protocol supports in windows (#15274) [backport:1.2] 2020-09-07 12:10:20 +02:00
Andreas Rumpf
2f6d04fd5d strict funcs: use control flow information for a more precise analysis (#15271)
* strict funcs: use control flow information for a more precise analysis

* cursor inference uses control flow information
2020-09-06 22:01:39 +02:00
genotrance
072c655653 Bump nimble (#15272) 2020-09-06 07:05:35 +02:00
shirleyquirk
57f98dae9a Fix c_malloc inside syslocks.nim to take size_t (#15268) [backport]
* update c_malloc's to csize_t
2020-09-05 23:00:59 +02:00
Clyybber
35ff17410f Expand hoisted default params in sem (#15270)
* Expand hoisted default params in sem
Introduce ast.newTree{I,IT}
Add test for default params in procs

* Cleanup

* Simplify hoist transformation and expand test
2020-09-05 22:01:47 +02:00
IDF
70d6238756 Add SSL_CTX_set_session_id_context (#15233)
* Added SSL_CTX_set_session_id_context()

* Added basic nimdoc

* Raise an error if sessionIdContext is longer than the maximum length

* Update nimdocs
2020-09-04 22:27:51 +01:00
Bung
c16ee37a71 Fix #15219 SQL escape in db_mysql is not enough (#15234) 2020-09-04 11:04:27 +02:00
cooldome
77df02313d fix #15238 (#15262)
* fix_15238

* fix test
2020-09-04 10:26:14 +02:00
Miran
4fb17bc03b fix #15257, toHex couldn't handle large uint64 (#15261) [backport:1.2] 2020-09-04 09:23:27 +02:00
Andreas Rumpf
48f2997221 fixes system.add for strict funcs (#15259)
* fixes system.add for strict funcs

* fixes #15248
2020-09-03 12:59:34 +02:00
Silvio
3172ca5475 replace / with _ in trId (#15256)
Fixes jquery error when clicking to collapse/expand a panel
2020-09-02 20:53:02 +02:00
PMunch
244760197c Fix sets for architectures with default integers smaller than 32 bits (#15258) [backport] 2020-09-02 10:07:08 +02:00
Andreas Rumpf
ff13f8cc3c fixes #15210 [backport:1.2] (#15237)
* fixes #15210 [backport:1.2]

* use patched version of bigints library
2020-08-31 14:46:23 +02:00
Jaremy Creechley
a76ae8f795 Changes for FreeRTOS/LwIP Port for the ESP32 (ESP-IDF) (#15250)
* Changes for FreeRTOS/LwIP Port for the ESP32 (ESP-IDF)

Adding FreeRTOS/LwIP to compiler:

* adding freertos option
* dyncalls for freertos
* add freertos to posix os list
* adding lwip option

Setting up networking FreeRTOS/LwIP Port:

* setting up lwip network for freertos
* fixing posix / networking for freertos
* disable setInheritable for freerots
* using lwip for net control items

* Fix builds by ignoring lib/posix/posix_freertos_consts.nim similar to lib/posix/posix_other_consts.nim
2020-08-31 11:48:54 +02:00
Andy Davidoff
b5424b826e template hygiene (#15240) 2020-08-29 08:06:11 -04:00
Clyybber
13e659cfec Big compiler Cleanup (#14777) 2020-08-28 22:18:09 +02:00
cooldome
f8c48fc186 fix #15035 (#15236) 2020-08-28 17:57:52 +02:00
Clyybber
fb58066b61 Fix #5691 (#15158)
* Fix #5691
* Cleanup and thoughts
* Use scope approach
* Seperate defined/declared/declaredInScope magics
* Fix declaredInScope
* Update spec accordingly
2020-08-27 15:50:59 +02:00
jcosborn
d11933ad99 fix some issues overloading with generics and inheritance (#15211)
* fix some issues overloading with generics and inheritance

* fix passing procs with subtype matches
2020-08-27 12:56:38 +02:00
Andreas Rumpf
ccccd30cf6 fixes #15221 (#15230) 2020-08-27 11:25:20 +02:00
Scott Wadden
a9a9860b0b Raise KeyError if passed an invalid row entry (#15227) 2020-08-26 20:00:54 +02:00
Juan Carlos
d85015e922 Remove unroll pragma from stdlib (#14706) 2020-08-26 16:51:41 +02:00
Araq
40969296e9 fixes #15207 [backport:1.2] 2020-08-26 15:27:15 +02:00
Araq
71025b8a8f deleted dead code, writetracking.nim was replaced by varpartitions.nim 2020-08-26 15:27:15 +02:00
Miran
5163fe7d87 remove deprecation from math.round (#15224) 2020-08-25 15:59:42 +02:00
Bung
7cee63bba3 avoid #8231, bitwise move to mul,div (#15070)
* avoid #8231, bitwise move to mul,div

* add test for #8231

* fix bitwise move when div result is float

* bitwise move depends on typ.size
2020-08-25 09:58:32 +02:00
Miran
15ff89cec1 [backport] fix #15064, strscans.scanf edge case for '$+' (#15223) 2020-08-25 09:57:15 +02:00
narimiran
5651a2f711 PRs with no activity in last year are marked as stale 2020-08-24 13:44:19 +02:00
Jon
8321617a78 fix in doc: incomplete output (#15222) [ci skip] 2020-08-24 08:33:51 +02:00
Mamy Ratsimbazafy
07d82b5cc4 Use more lent in options (#15208) 2020-08-24 08:05:17 +02:00
alaviss
575697e1f4 doc/nimdoc.css: align field names to the right (#15217) 2020-08-23 09:48:37 +02:00
wltsmrz
9bae1ed205 Unsigned iovlen (#15216) 2020-08-22 23:14:50 +02:00
John Dupuy
66eba3388a Added more SSL documentation to net module. (#15206)
* Added more SSL documentation to `net` module.

* Changed two of the net.nim doc refs to links.

* Update lib/pure/net.nim doc wording.

Co-authored-by: Dominik Picheta <dominikpicheta@googlemail.com>

* Update lib/pure/net.nim - added space to doc URI

Co-authored-by: alaviss <leorize+oss@disroot.org>

* Fixed another doc URI in net module.

* For net module doc added warning to connect procedure.

* Update net.nim

Co-authored-by: Dominik Picheta <dominikpicheta@googlemail.com>
Co-authored-by: alaviss <leorize+oss@disroot.org>
2020-08-22 11:00:38 +01:00
Elijah Shaw-Rutschman
8a004e2fc0 Add test coverage for atomics (#15193)
* Add test coverage for atomics

Signed-off-by: Elijah Shaw-Rutschman <elijahr@gmail.com>

* Fix compareExchange bugs for non-trivial objects

Bugs fixed:

1. compareExchange would not set the desired value in the success case.
2. compareExchange would not set var expected to the found value in the failure case.
3. withLock would spin forever running the unit tests. try..body..finally prevents this. Not sure why this makes a difference, since an exception wasn’t being raised, but clearing the guard in a finally block seems correct anyways.

Signed-off-by: Elijah Shaw-Rutschman <elijahr@gmail.com>
2020-08-18 18:02:10 +02:00
Andreas Rumpf
ddff13f01b better strict funcs, WIP (#15199)
* better strict funcs, WIP

* progress
2020-08-18 12:45:22 +02:00
jcosborn
e194cb41a4 fix overloading issue with generic invocation (#15135)
* fix overloading issue with generic alias

* add test for inheritance depth
2020-08-18 08:23:19 +02:00
alaviss
e9df8ebcfd gc_regions: cleanup & fixes for deallocation (#11920)
* gc_regions: withRegion nows return the modified MemRegion

* gc_regions: make withScratchRegion dealloc correctly

* tests/gc: add tregionleak test

This test checks if memory within regions are freed properly.
2020-08-17 20:20:48 +02:00
Andreas Rumpf
6feb3900b1 fixes #15177, the error message is now what it should have been (#15195) 2020-08-17 14:32:52 +02:00
Bung
cd28fe2ef7 add openssl missing procs (#15180) 2020-08-17 10:54:34 +02:00
narimiran
39906c52c4 stale bot is now active only for pull requests 2020-08-17 09:11:33 +02:00
Juan Carlos
c9fdad2c21 db_postgres document how to use it with unix socket (#15187) 2020-08-17 08:39:58 +02:00
slangmgh
ba042af9cc std/with support field assign (#14484)
* std/with support filed assign

* add changelog

* add support x.dup.with

* add example

* revert support x.dup.with; add example

* update changelog; fix assignment in parameter

* Update changelog.md

* add example for assignment in parameter

* Remove colon style assign

Co-authored-by: Clyybber <darkmine956@gmail.com>
2020-08-15 01:33:21 +02:00
alaviss
957bf15a08 asyncnet: don't try to close the socket again [backport] (#15174)
The closed flag isn't a good design by any means, but let's have this
working first before I get rid of the flag and potentially create a
non-backportable commit.
2020-08-12 08:04:54 +02:00
Cléber Zavadniak
ce2da87eca Fix typo on CoroutineRef* doc (#15179)
Just a small fix for a typo ("for for").
2020-08-12 04:46:16 +02:00
Clyybber
2cea52ee7e Allow pragmas on parameters (#15178) 2020-08-11 22:28:49 +02:00
Andreas Rumpf
813f16a2a3 Fix #8473 (#15169)
* Make explicit {.nimcall.} a seperate calling convention

* Add testcase for #5688

* Fix bootstrapping

* Remove little lies :)

* Use typeflag instead
2020-08-11 14:50:46 +02:00
Silvio
963db9e7da docs: dlimport -> dynlib (#15175) 2020-08-11 14:49:57 +02:00
Ico Doornekamp
2260ede247 Added array type definition to manual (#15173)
Co-authored-by: Ico Doornekamp <git@zevv.nl>
2020-08-10 14:01:47 +02:00
Clyybber
b022576ce9 Use typeflag instead 2020-08-10 12:57:32 +02:00
haxscramper
e5dbdc1d37 [FIX] strtabs interpolation in nimscript (#15172)
* [FIX] strtabs interpolation in nimscript

* [TEST] Use `static` in strtabs test
2020-08-09 14:12:53 +02:00
Andreas Rumpf
2a8bf470af fixes #15101 [backport] (#15171) 2020-08-08 23:08:34 +02:00
Clyybber
26a867c83c Remove little lies :) 2020-08-08 13:22:53 +02:00
Clyybber
2a8d010742 Fix bootstrapping 2020-08-08 12:50:06 +02:00
Clyybber
78b2012a92 Add testcase for #5688 2020-08-08 12:45:07 +02:00
Clyybber
38068f9778 Make explicit {.nimcall.} a seperate calling convention 2020-08-08 12:36:20 +02:00
c-blake
0bc8dd0b00 Add iterator inotify_events which is *almost always* needed logic for (#15152)
client code since Linux `inotify` is much like Linux `getdents64`.

Expanding on "almost always"..The only time that this `iterator` logic
is ***not*** needed on the output of a `read` from inotify fd's is when
one passes a length to `read` *guaranteed* to only pass one event struct
in the buffer.  That unusual circumstance requires (at least!) knowing
the length of the delivered filename before an event occurs, and the
filename itself is optional for some event types.

It is *far* more common to not know lengths in advance which means one
passes a buffer big enough for at least one maximum length directory
entry (256 bytes) which is then also big enough for *many* "typical"
length entries and therefore many events.  In such more common scenarios
this iterator logic is definitely needed.

Further, not using this logic, yet treating the return from read as "the
whole answer" can test ok on "thin" event streams (e.g. 1 event per ms),
hiding a latent bug of processing only the first event.
2020-08-08 07:26:20 +02:00
flywind
eee3b189ff fix #15148 (#15149)
* fix #15148

Co-authored-by: alaviss <leorize+oss@disroot.org>
2020-08-08 07:24:54 +02:00
ee7
6f482ab934 deques.nim: Refactor the toDeque functionality (#15166)
This commit polishes the new proc introduced by d9ed816b10.

Changes:
- Rename to `toDeque` for more consistency with well-known procs like
  `toHashSet` and `toTable`.
- Rename the `openArray` parameter. The name `arr` was potentially less
  clear given that the proc can be used with a seq (or string).
- Add a `since` annotation.
- Reword the doc comment, and clarify that ordering is preserved.
- Add runnableExamples.
- Add "see also" cross linking between `initDeque` and `toDeque`.
- Remove duplicate `nextPowerOfTwo`. The `initImpl` template already
  includes it.
- Implement the proc using the `items` iterator, rather than indexing.
  This matches the implementation of `sets.toHashSet` and
  `tables.toTable`.
- Add a test within `when isMainModule`.
- Add a changelog entry.
2020-08-07 22:54:34 +02:00
cooldome
a528382e05 fix sqlgetdata regression in odbc (#15161)
* fix sqlgetdata import

* fix db_odbc

* more fixes

* fix style
2020-08-07 22:37:54 +02:00
archnim
d9ed816b10 Added the ability to initialize a deque with an openArray (#15138)
* Add ability to initialize a deque with a sequence

Example:
var dq = initDeque[char](@['a', 'b', 'c'])

* Update deques.nim

* Optimized deque initialization

* Sequence replaced by open array in deque initialization
2020-08-05 12:41:42 -04:00
cooldome
ef6358f0b0 implement (#15153) 2020-08-04 19:22:35 +02:00
narimiran
eb3ba0ae5f limit stalebot a bit more 2020-08-04 13:00:09 +02:00
Andreas Rumpf
64aec6eb85 fixes a collect() bug reported on the forum (#15156) [backport:1.2] 2020-08-04 12:45:15 +02:00
flywind
2d494f42f3 minor improvement (#15155) 2020-08-04 11:29:57 +02:00
narimiran
836660a297 put stale limit at 3 years
It needs to be slowly brought down to limit the notifications
and prevent excessive spamming.
2020-08-04 11:00:04 +02:00
narimiran
e4710f893e stalebot: don't send messages to keep spam down 2020-08-04 10:47:16 +02:00
narimiran
9b08c7b375 add stale bot 2020-08-04 09:03:20 +02:00
Andreas Rumpf
d6161e7e9e fixes #15129 [backport:1.2] (#15144) 2020-08-01 22:03:15 +02:00
sschwarzer
98eb8410f2 Remove noSideEffect pragmas (#15143)
These don't seem to make sense for the purpose of the procs and lead
to errors when the `--experimental:strictFuncs` feature is enabled.

See also https://github.com/nim-lang/Nim/issues/15142
2020-08-01 22:00:25 +02:00
alaviss
c619cedd7c net: allow close() to ignore SSL failures due to disconnections (#15120)
* net: allow close() to ignore SSL failures due to disconnections

Comes with this PR is also a SIGPIPE handling contraption.

* net: don't do selectSigpipe() on macOS

macOS sockets have SO_NOSIGPIPE set, so an EPIPE doesn't necessary mean
that a SIGPIPE happened.

* net: fix alreadyBlocked logic

* net: WSAESHUTDOWN is also a disconnection error
2020-08-01 21:27:55 +02:00
flywind
3ce32a7e40 export asyncdispatch handles (#15140)
* improve epoll docs

* export handles

* add comments and changelog
2020-08-01 21:27:21 +02:00
Andreas Rumpf
8e3f51f06c fixes #15130 (#15141)
* fixes #15130

* you really have to copy from cursors
2020-08-01 18:04:04 +02:00
Andreas Rumpf
9ff2c50155 fixes #15122 [backport:1.2] (#15139) 2020-08-01 13:16:50 +02:00
alaviss
e192e07bf0 ci_docs: build fusion docs (#15127) 2020-08-01 11:33:19 +02:00
flywind
a7736b6b43 improve epoll docs (#15137) 2020-08-01 11:30:51 +02:00
Andreas Rumpf
4ab6887a67 fixes #15111 (#15136) 2020-08-01 07:39:00 +02:00
Andreas Rumpf
6b88cd0d42 Revert "Small typo (#15132)" (#15134)
This reverts commit 4bf8d38248.
2020-07-31 20:27:58 +02:00
Oliver Daniel
4bf8d38248 Small typo (#15132)
The expected output necessarily cannot match the formatted string.
2020-07-31 16:35:50 +02:00
Andreas Rumpf
d23ae49535 fixes #15071 [backport] (#15131) 2020-07-31 12:13:33 +02:00
genotrance
f1971243d3 Bump nimble (#15126) 2020-07-30 13:13:34 -05:00
Andreas Rumpf
355b275175 fixes #15112 (#15124) 2020-07-30 19:19:59 +02:00
Andreas Rumpf
d130175342 cursor and mutation tracking fixes (#15113)
* fixes #15110
* fixes #15096

* prepare varpartitions for cursor inference
* new cursor inference begins to work
* make tests green
2020-07-30 17:32:48 +02:00
jcosborn
32c6146200 fix overloading case with generic alias (#15116)
* fix overloading case with generic alias

* revert reorganization of tests
2020-07-30 15:34:11 +02:00
treeform
604f7461d7 Fix tables.CountTable largest and smallest (#15115)
It needs to have len defined first because of the assert .len > 0.  I just moved it up a bit to make them work.
2020-07-29 23:49:51 -04:00
alaviss
20315637aa asyncnet, net: don't attempt SSL_shutdown if a fatal error occurred (#15066)
* asyncnet, net: don't attempt SSL_shutdown if a fatal error occurred

Per TLS standard and SSL_shutdown(3ssl). This should prevent errors
coming from a close() after a bad event (ie. the other end of the pipe
is closed before shutdown can be negotiated).

Ref #9867

* tssl: try sending until an error occur

* tssl: cleanup

* tssl: actually run the test

I forgot to make the test run :P

* tssl: run the test on ARC, maybe then it'll be happy

* tssl: turns off ARC, switch tlsEmulation on for freebsd

* tssl: document why tlsEmulation is employed

* net: move SafeDisconn handling logic to socketError
2020-07-30 00:35:02 +02:00
genotrance
0788a7f970 Bump nimble (#15114) 2020-07-29 15:42:08 -05:00
flywind
c645dba038 fixes #14139 (#15107)
* fix #14139
* Update lib/pure/collections/heapqueue.nim

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
Co-authored-by: Clyybber <darkmine956@gmail.com>
2020-07-29 16:18:27 +02:00
Clyybber
2629d619a1 Fix forward declaration issues in template/macro context (#15091)
* Fix forward declaration issues in template/macro context

* Correct forward declaration resolving for overloads

* Remove old dead code

* WIP consistent gensym ids

* Minimize diff

* Remove obsoleted hack

* Add templInstCounter to give unique IDs to template instantiations

* Remove obsoleted code

* Eh, init in myOpen, not myProcess...

* Remove optNimV019

* Add testcase for #13484
2020-07-29 16:17:20 +02:00
c-blake
196e747df1 Attempt to explain better why delImplIdx is the way it is. Maybe this can (#15108)
avoid future implementation mischief.  (Maybe not.  Sometimes, general
distrust of theory leads people to distrust simple reasoning over times
from CPUs trying as hard as possible to mask DRAM latency via pre-fetch.)
2020-07-29 11:19:02 +02:00
Andreas Rumpf
a3a87cdb29 fixes #14616 [backport:1.2] (#15109) 2020-07-29 11:11:58 +02:00
c-blake
b2a1944587 Fulfill https://github.com/nim-lang/Nim/pull/14995#issuecomment-664914391 (#15104)
request.  This can be conceived as an alternate, more capable resolution of
  https://github.com/nim-lang/Nim/issues/12200
than
  https://github.com/nim-lang/Nim/pull/12208

The code re-org idea here is to upgrade tablimpl.nim:`delImpl`/`delImplIdx`
to abstract client code conventions for cell emptiness & cell hashing via
three new template arguments - `makeEmpty`, `cellEmpty`, `cellHash` which
all take a single integer argument and clear a cell, test if clear or
produce the hash of the key stored at that index in `.data[]`.

Then we update the 3 call sites (`Table`, `CountTable`, `SharedTable`) of
`delImpl`/`delImplIdx` by defining define those arguments just before the
first invocation as non-exported templates.

Because `CountTable` does not save hash() outputs as `.hcode`, it needs a
new tableimpl.nim:`delImplNoHCode` which simply in-lines the hash search
when no `.hcode` field is available for "prefix compare" acceleration.
It is conceivable this new template could be used by future variants, such
as one optimized for integer keys where `hash()` and `==` are fast and
`.hcode` is both wasted space & time (though a small change to interfaces
there for a sentinel key meaning "empty" is needed for maximum efficiency).

We also eliminate the old O(n) `proc remove(CountTable...)` in favor of
simply invoking the new `delImpl*` templates and take care to correctly
handle the case where `val` is either zero for non-existent keys in `inc`
or evolves to zero over time in `[]=` or `inc`.

The only user-visible changes from the +-42 delta here are speed, iteration
order post deletes, and relaxing the `Positive` constraint on `val` in
`proc inc` again, as indicated in the `changelog.md` entry.
2020-07-28 23:48:50 +02:00
Andreas Rumpf
86c9b78339 disable sink inference, only enable it for the stdlib. Reason: better source code compatibility (#15105) 2020-07-28 19:18:46 +02:00
Euan
e4e4931432 Change clibdir and cincludes for NetBSD (#15102) 2020-07-28 12:01:25 -04:00
Bung
e2b1491905 Fix #11352 strutil.insertSep() fails on negative numbers (#15087)
* fix #11352 strutil.insertSep handle negtive number

* test for #11352

* optimize

* not parts string var

* Update lib/pure/strutils.nim

Thanks!

Co-authored-by: alaviss <leorize+oss@disroot.org>

* need to be countdown

Co-authored-by: alaviss <leorize+oss@disroot.org>
2020-07-28 11:47:22 +02:00
Miran
39487f9728 deprecate tables.allValues; continuation of #15047 (#15092) 2020-07-28 11:40:56 +02:00
Andreas Rumpf
be78b35bb8 cleanup ARC documentation (#15100) 2020-07-28 11:34:44 +02:00
narimiran
a2f330569c yet another fusion fix 2020-07-28 10:57:24 +02:00
narimiran
75083979f9 another bump 2020-07-28 09:27:00 +02:00
narimiran
d6a0c35330 bump FusionStableCommit to the latest commit 2020-07-28 08:51:10 +02:00
Ray Imber
d60fae576f Improvements to Windows install instructions (#15099) 2020-07-28 02:04:04 -04:00
Andreas Rumpf
e6f0d4a5a5 fixes #15076 (#15095) 2020-07-27 23:27:20 +02:00
Timothee Cour
377f716766 fix #14698 nkRecWhen caused internalAssert in semConstructFields when generic type not mentioned in fields (#14709)
* fix #14698 nkRecWhen caused internalAssert in semConstructFields when generic type not mentioned in fields

* address comment

* Update compiler/semtypinst.nim

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2020-07-27 22:32:21 +02:00
Bung
cac09a43ae fix #11354 jsgen not carefully handle genAddr with nkHiddenAddr,nkStm… (#15078)
* fix #11354 jsgen not carefully handle genAddr with nkHiddenAddr,nkStmtListExpr; genAsgn with lvalue tyVar and rvalue tyPtr

* correct logic

* add test for #11354

* handle nkHiddenAddr when n.len == 1

* Update compiler/jsgen.nim

* Update compiler/jsgen.nim

* Apply suggestions from code review

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2020-07-27 21:13:49 +02:00
Bung
191c388792 fixes #14189 (#15080) [backport] 2020-07-27 14:06:54 +02:00
Araq
947ecd1257 more renamings 2020-07-27 13:07:09 +02:00
Araq
46bd6787b8 code cleanup 2020-07-27 13:07:09 +02:00
Araq
318f0992ea fixes a closure iterator memory leaks, progress on #15076 2020-07-27 13:07:09 +02:00
Danil Yarantsev
4c43915b59 Add test-cases for #12576 and #12523 (#15085)
* Add a test-case for #12576

* Add a test-case for #12523
2020-07-27 13:01:50 +02:00
alaviss
c292c57e48 Small optimization for the CI pipeline. (#15088)
* azure-pipelines: cache csources to speed up build

Building csources takes about 2-4 mins, and since it hasn't changed for
a long time, employ some caching to cut the time spent.

* azure-pipelines: remove ppa avoidance configs

Testing shows that there aren't any difference between having this and
not having it, so removing this to simplify the code.
2020-07-27 10:38:20 +02:00
Jjp137
a62bc55955 parsecsv: fix '\0' being displayed as '0' in docs (#15086) [backport] 2020-07-27 08:17:23 +02:00
Araq
a0049d1fb0 compiler: minor code cleanups 2020-07-27 08:05:52 +02:00
genotrance
c229df95a4 Bump nimble (#15077) 2020-07-26 08:44:14 +02:00
Andreas Rumpf
aae998feff fixes #15038 [backport:1.2] 2020-07-26 01:16:06 +02:00
Andreas Rumpf
624762cfb7 fixes #15052 2020-07-26 01:16:06 +02:00
Miran
5c4e2bf68e fix nightlies: smaller log files (#15074)
Hopefully this will fix
"The job exceeded the maximum log length, and has been terminated."
2020-07-25 22:56:37 +02:00
alaviss
33c2d7bfc4 koch: bundle nim-lang/fusion with Nim (#15061)
Initial work on bundling nim-lang/fusion as part of the Nim distribution.
2020-07-25 22:52:18 +02:00
Danil Yarantsev
080bed8b6b Add a test-case for #12990 (#15072)
* closes #12990
* Add a test-case for #12990
2020-07-25 20:35:20 +02:00
Andreas Rumpf
2aca748ddd strict func: much better error messages (#15068)
* strict func: much better error messages
* documented the 'strict funcs' mode
2020-07-25 19:36:53 +02:00
Andreas Rumpf
7ca32c86bb writing to a location counts as "side effect"; implements https://github.com/nim-lang/RFCs/issues/234 (#15030) 2020-07-25 15:14:28 +02:00
Miran
1330597f6d deprecate tables.add (#15047) 2020-07-25 09:53:47 +02:00
Bung
2dddf32726 fix #14684 (#15059) 2020-07-25 09:52:29 +02:00
Bung
9746868832 fix #14534 (#15060) [backport] 2020-07-25 09:51:59 +02:00
genotrance
8211d38569 Bump nimble commit (#15053) 2020-07-25 01:16:25 -05:00
jcosborn
add003a074 fix assignment to converted concept type (#15051)
* fix assignment to converted concept type

* check for resolved concepts

* add extra test
2020-07-24 21:19:11 +02:00
Miran
4b93c61f0d jsre: try to fix nightlies (#15057) 2020-07-24 21:15:20 +02:00
Araq
12a9fe017e fixes #15056 [backport] 2020-07-24 17:49:25 +02:00
Andreas Rumpf
18a70a7563 fixes #15036 2020-07-23 20:27:17 +02:00
Andreas Rumpf
c90c53e8bb fixes #15044 [backport:1.2] 2020-07-23 20:27:17 +02:00
Miran
14d16c2174 json.nim: smaller init size (#15048)
There was a recent `rightSize` change in tables.nim, so the existing
value (4) was creating too large tables.
2020-07-23 15:42:12 +02:00
Andreas Rumpf
925dd92e07 enforce browsers.nim only handles URLs [backport] (#15045) 2020-07-23 11:03:39 +02:00
Miran
ec65bfae3a Change testing commands for some packages (#15041) 2020-07-22 14:57:40 +02:00
Andreas Rumpf
d84894de2e fixes #15026 [backport] (#15040)
no test case since only a special case was affected and the special case got removed
2020-07-22 13:02:03 +02:00
Hugo Granström
32ac1b7c9d fix #15033 (#15034) 2020-07-22 10:30:46 +02:00
Danil Yarantsev
f25454d5c6 Add a testcase for #14480. Fixes #14480 (#15037) 2020-07-22 09:52:38 +02:00
Mildred Ki'Lya
503c5e0520 smtp: Fix STARTTLS, request HELO once TLS is established (#15032) 2020-07-22 00:30:33 -04:00
Andreas Rumpf
911e39351e ARC: optimize the code better when --panics:off (#15031) 2020-07-21 23:23:33 +02:00
Miran
5fafa2fd5c fix several newline problems (#15028) [backend]
* prevent newlines where they shouldn't be
* 'contentLength' shouldn't be negative
2020-07-21 22:49:08 +02:00
genotrance
450a3e3179 Fix #2408 - add -d:globalSymbols (#14904) 2020-07-21 19:14:36 +02:00
Bung
64d629c617 Shadow Dom apis (#14979)
* shadow dom api

* fix typos

* host to Element type

* fix code style

* move elementsFromPoint to dom_extensions.nim
2020-07-21 19:11:12 +02:00
Andreas Rumpf
c8a72e0748 Merge pull request #15027 from nim-lang/araq-cursor-fix
cursor inference bugfix
2020-07-21 07:33:37 +02:00
Andreas Rumpf
3a4e4cec4d cursor inference bugfix 2020-07-20 18:37:14 +02:00
Andreas Rumpf
80d3ef9952 hotfix: firstOrd/lastOrd for 'tyLent' as it shows up in strange places, as usual 2020-07-20 17:44:35 +02:00
Andreas Rumpf
70acba7f0d readLine: Unicode support for Windows console (#14782)
* readLine: Unicode support for Windows console

When input is read from the Windows console, input encoding is UTF16. This is translated internally to UTF8.

* readLine: Remove recursive imports

* readLine: Fix issues with --gc:arc

**--gc:arc** defines **nimv2**. This changes the definition of **WideCStringObj**.
Also an empty string should be returned in case of EOF.
2020-07-20 14:39:27 +02:00
Andreas Rumpf
49d4b50fe5 fixes #14194 (#15023) 2020-07-20 14:28:00 +02:00
alaviss
9a76398ec6 koch: use in-tree Nim to run test if possible (#15018)
Fixes #15013
2020-07-20 08:02:48 +02:00
Andreas Rumpf
71dd5f85b9 'isolate' builtin; refs https://github.com/nim-lang/RFCs/issues/244 (#15011) 2020-07-20 07:50:19 +02:00
alaviss
bb1adf6a70 io: fix SetHandleInformation signature to match Windows' (#15017)
* io: fix SetHandleInformation signature to match Windows'

Fixes #14980

* rename Handle -> IoHandle because system.nim is a mess
2020-07-20 00:17:33 -04:00
narimiran
b16284633e enable 'nimterop' test 2020-07-20 05:44:06 +02:00
Dominik Picheta
1e3a0ef1e1 [Backport] Fixes callbacks being dropped on Linux/macOS/BSD. (#15012)
Fixes #15003.

This is a serious bug which occurs when data cannot be read/sent
immediately and there are a bunch of other read/write events
pending. What happens is that the new events are dropped which
results in the case of the reported bug resulted in some data not
being sent (!).
2020-07-19 08:41:36 +02:00
Araq
ffe7b3a9bf threadpool.nim: minor code style changes 2020-07-18 21:40:57 +02:00
Andy Davidoff
ae358a0c7a fix docs for nativesocket read/write selects (#15010)
The sockets which *cannot* be _[read from or written to]_ will also be removed from ``readfds``.
2020-07-18 16:39:41 +02:00
Timothee Cour
169ca37d26 enable,document,test getImplTransformed, very useful for understanding how nim transforms code (#14924)
* enable,document,test getImplTransformed, very useful for understanding how nim transforms code
2020-07-18 10:49:36 +02:00
Tomohiro
c983466c15 Fix #14906 (#14949)
* Fix #14906 by wrapping outputStream with PipeOutStream

* Fix compile error when ./build_all.sh

* Use PipeOutStream on posix

* Fix compile error when build_all.sh

* Use ptr UncheckedArray

* Replace copyRefObj

* Remove tmp buffer from posPeekData

* Add more tests for outputStream

* Add comments about PipeOutStream.buffer

* Fix bug in posReadLine

* Move implementation of newPipeOutStream to streamwrapper module
2020-07-18 10:41:33 +02:00
cooldome
edbbbdf1a8 fix odbc regressions (#15009) [backport]
* fix odbc regressions

* make only necessary changes
2020-07-18 10:21:09 +02:00
Andreas Rumpf
d4984e069a arc: cursors for simple for loop variables (#15008)
* arc: cursors for simple for loop variables

* merged devel
2020-07-17 15:24:36 +02:00
Bung
c2f80de1c7 fix #14822 copy test into var in matrix process, so can reset startTime before actully run (#15000)
* TTest pass by ref , so can reset startTime before actully run

* change TTest to ref type

* clone test in matrix process
2020-07-17 11:01:47 +02:00
Miran
c62513049c fix #14082, don't crash on incorrectly formatted input (#14977) [backport]
* fix #14082, don't crash on incorrectly formatted input

* address code review

* remove duplication
2020-07-17 10:59:53 +02:00
Clyybber
1355b461aa Show that a variable is cursor in --expandArc (#15002) 2020-07-17 10:56:17 +02:00
flywind
9fb7467fda fix #15006 (#15007) 2020-07-17 10:53:26 +02:00
Andreas Rumpf
6b607413e9 cursor inference: hotfix (#14999) 2020-07-16 12:07:06 +02:00
Bung
ba5604b96d fix #13621, the nim-livereload is mentioned as proposal in #8927 (#14998) 2020-07-16 11:18:59 +02:00
Clyybber
282128ab66 Fix #14994 (#14996)
* Fix #14994

* Revert misplaced "optimization"

* Typo
2020-07-15 23:33:58 +02:00
Andreas Rumpf
617c1f16d7 disable debug output 2020-07-15 23:04:18 +02:00
Andreas Rumpf
c5358b0d4b An optimizer for ARC (#14962)
* WIP: an optimizer for ARC
* do not optimize away destructors in 'finally' if unstructured control flow is involved
* optimized the optimizer
* minor code cleanup
* first steps to .cursor inference
* cursor inference: big steps to a working solution
* baby steps
* better .cursor inference
* new feature: expandArc for easy inspection of the AST after ARC transformations
* added topt_cursor test
* adapt tests
* cleanups, make tests green
* optimize common traversal patterns
* moved test case
* fixes .cursor inference so that npeg compiles once again
* cursor inference: more bugfixes

Co-authored-by: Clyybber <darkmine956@gmail.com>
2020-07-15 23:00:06 +02:00
Clyybber
813dd1b670 repr_v2 improvements (#14992)
* Support proc in arc repr

* Typo

* Improve repr for strings and chars
2020-07-15 22:04:15 +02:00
Clyybber
e057b1d839 Fix #14990 (#14991)
* Fix #14990

* Add testcase
2020-07-15 19:00:52 +02:00
Clyybber
08159733cd Fix #14985 (#14988) 2020-07-15 11:34:10 +02:00
flywind
c5f64f101b fix #13086 (#14987)
* fix #6608

* minor

* fix

* clean tests

* make testamnet happy

* again

* minor

* fix #13086
2020-07-15 03:46:17 -04:00
Clyybber
f2b041f168 Reenable a few tests 2020-07-14 19:50:42 +02:00
Clyybber
ddfb7d9877 Closes #10396 2020-07-14 19:50:42 +02:00
Clyybber
695a537c05 Closes #13253 2020-07-14 19:50:42 +02:00
Clyybber
03b0374e5c Closes #8426 2020-07-14 19:50:42 +02:00
Juan Carlos
9465b5db44 Clean up macros (#14959) 2020-07-14 16:44:56 +02:00
Clyybber
2b0e336c97 injectdestructors fixes and refactor (#14964)
* injectdestructors fixes and refactor

* Tiny cleanup

* Refactor and expand testcase

* Closes #14902 by adding testcase

* Better naming

* Fix test failures

* Misc cleanup

* Add testcase for #14968

* Better approach; expand testcases

* Optimizations and fixes

* Add testcase

* typo

* Tiny cleanup
2020-07-14 14:15:39 +02:00
Bung
f999f916f3 add missing props,procs (#14978) 2020-07-14 13:53:41 +02:00
Hendrik
9ed0dbfa6e fix index error (#14974)
Co-authored-by: Hendrik Albers <mail@hendrik.dev>
2020-07-14 13:15:22 +02:00
Timothee Cour
e07d661d16 fix #14475; unittest.require now works with nim c; require and check now works with -d:nodejs (#14676)
* fix #14475; make unittest work with -d:nodejs

* fixup

* fixup

* disable inim, delaunay which failed after unittest.require got fixed

* re-enable tests that have been fixed
2020-07-14 13:14:32 +02:00
jcosborn
ffaf4797be add full tests from #9463 (#14975) 2020-07-14 11:24:17 +02:00
flywind
086efac49b fix #6608 (#14963)
* fix #6608
2020-07-14 09:22:48 +02:00
Miran
f4f21c89e5 asyncftpclient.nim - don't assume a sufficiend line length (#14973) 2020-07-14 02:18:02 -04:00
Andreas Rumpf
6cc0061a72 optimize the new nimPrepareStrMutationV2 with inlining (#14969) 2020-07-12 16:50:56 +02:00
Alexander Wolfe
124feb2af8 nimpretty support for multiple files (#14890) 2020-07-12 16:07:31 +02:00
flywind
9ec9a31f46 Fix #12759 (#14967)
* add testcase for #5926

* fix #12759
2020-07-12 03:31:03 -04:00
Clyybber
d409694b02 :D 2020-07-11 19:17:40 +02:00
flywind
21772b6419 add testcase for #5926 (#14965) 2020-07-11 17:09:41 +02:00
Juan Carlos
6d10baa339 https://github.com/nim-lang/Nim/pull/14948#issuecomment-656498426 (#14958) 2020-07-11 06:21:59 -04:00
Clyybber
425972c4e8 Add testcase for some old fixed issues (#14960)
* Add testcase for #2703

* Add testcase for #2586

* Small fix
2020-07-10 19:21:50 +02:00
Clyybber
1850efbb6c Add testcase for #14383 (#14957) 2020-07-10 18:10:32 +02:00
Clyybber
db6ffeba8e Add testcase for #13815 (#14956) 2020-07-10 17:31:15 +02:00
Clyybber
0db32e9885 Add testcase for #12571 (#14955) 2020-07-10 17:13:37 +02:00
Clyybber
b21782a667 Add testcase for #4722 (#14954) 2020-07-10 17:02:49 +02:00
kwgchi
229a623849 Update readme.md (#14953) 2020-07-10 16:45:26 +02:00
Miran
371b416ac8 fix #14912, make --useVersion:1.0 work again (#14945)
* fix #14912, make `--useVersion:1.0` work again
* a better fix
* add test
2020-07-10 16:44:12 +02:00
Manuel Bojato
04232d92cd Fix theme switch load from local storage (#14897)
* fix theme switch load from local storage

* Fix tests

Co-authored-by: Clyybber <darkmine956@gmail.com>
2020-07-10 15:06:07 +02:00
Araq
4603197fe8 fixes a minor regression 2020-07-10 13:36:02 +02:00
Araq
112511084d fixes the tcontrolflow regression, clen idea of an escaping expression 2020-07-10 13:36:02 +02:00
Araq
b59385f22b no wasMoved() calls after destructors necessary 2020-07-10 13:36:02 +02:00
Araq
37a98c77f3 optimize sinks even when in a loop 2020-07-10 13:36:02 +02:00
Araq
78513a9204 renderer.nim: more obvious debug output 2020-07-10 13:36:02 +02:00
Clyybber
bf51cee431 Update docs and changelog 2020-07-10 13:36:02 +02:00
Clyybber
4a1128d16c Move wasMoved out of =destroy 2020-07-10 13:36:02 +02:00
Clyybber
3e52136f26 Cosmetics 2020-07-10 13:36:02 +02:00
Araq
f92d2eaa35 cleanup of PR #14833 (VM profiler) 2020-07-09 19:21:20 +02:00
Ico Doornekamp
d7ccd82eac VM profiler (#14833)
* Crude VM profiler

* Added --profileVM flag, refactoring

* fixed FileLine hash

* Use TLineInfo instead of own FileLine, updated formatting

* Refactoring, moved PStackFrame to vmdefs for cleaner data structure

* Moved vmprofiler to separate file

* Simplified TLineInfo hash, use toFileLineCol for output

* Hash

* Moved profile data into Config, dump only once at end of run

* Changed profile output header to show '#instr' instead of 'count'

* Do not accumulate instrcount for non-top frames

Co-authored-by: Ico Doornekamp <git@zevv.nl>
2020-07-09 19:18:35 +02:00
Andreas Rumpf
c38a459582 fixes #14925 (#14947) 2020-07-09 17:24:23 +02:00
flywind
64815f59b2 add testcase for #4668 (#14946)
closes #4668
closes #9463
2020-07-09 12:53:12 +02:00
flywind
40b58a0a18 fix #11009 (#14935) 2020-07-09 09:57:35 +02:00
treeform
399b2e3134 Add missing dom.nim things (#14944) 2020-07-09 09:18:27 +02:00
flywind
00528cbc3c Add testcase for #10465 (#14943)
* add debug format string

* remove try except

* add changelog

* add docs and more tests

* Update lib/pure/strformat.nim

Co-authored-by: Juan Carlos <juancarlospaco@gmail.com>

* minor

* add testcase

Co-authored-by: Juan Carlos <juancarlospaco@gmail.com>
2020-07-09 01:51:18 +02:00
flywind
3db6d9ea0c add docs and more tests for debug format strings (#14861)
* add debug format string

* remove try except

* add changelog

* add docs and more tests

* Update lib/pure/strformat.nim

Co-authored-by: Juan Carlos <juancarlospaco@gmail.com>

* minor

Co-authored-by: Juan Carlos <juancarlospaco@gmail.com>
2020-07-08 22:21:30 +02:00
Clyybber
9016dd96ee Add testcase for #12129 (#14940)
* Add testcase for #12129

* Fix test
2020-07-08 22:04:21 +02:00
Andreas Rumpf
bc712c28fc fixes #14865 (#14937) 2020-07-08 18:59:34 +02:00
Clyybber
27579cfd3a Make arc compile laser again 2020-07-08 16:20:16 +02:00
Miran
3de5296337 remove a condition that table size must be passed as power of 2 (#14926)
* remove a condition that table size must be passed as power of 2
* remove power-of-2 condition from sets and sharedtables
* remove power-of-2 condition from deques
* use 'correctSize' for both branches
* prettify changelog.md and fix typos
* add a changelog entry
* fix double-call of 'right-size'
* fix the same thing in sets.nim
* introduce a new internal proc `slotsNeeded`

Deprecate the public proc `rightSize`, which is not needed anymore.
Now it is an identity function, allowing the old code to work
correctly and without extra allocations.
2020-07-08 15:01:47 +02:00
Andreas Rumpf
06d776a582 fixes #14900, this time for real, maybe (#14934) 2020-07-08 14:47:14 +02:00
Araq
cb1ecbf956 closes #14878 2020-07-08 12:22:55 +02:00
Araq
e42ce877a6 fixes #14805 2020-07-08 12:22:55 +02:00
Araq
ecf8cbbbe0 fixes #14900 2020-07-08 10:48:12 +02:00
Araq
cdce245a23 fixes #14899 2020-07-08 10:48:12 +02:00
Araq
b17e1efc67 progress 2020-07-08 10:48:12 +02:00
Andreas Rumpf
87f6a9592c fixes #14402 (#14908)
* fixes #14402

* added a test case
2020-07-08 08:21:55 +02:00
narimiran
e82a14b273 fix mistake in times.nim docs 2020-07-07 22:57:06 +02:00
Clyybber
8480bef1c4 Add testcase for #14864 (#14928)
* Add testcase for #14864

* :D
2020-07-07 22:43:36 +02:00
Dominik Picheta
25ceacbe4f Revert commit 3e843ab335. Closes #14930. 2020-07-07 19:18:02 +01:00
Andreas Rumpf
a61a7889b8 injectdestructors: refactoring, added more cases explicitly (#14929) 2020-07-07 17:47:57 +02:00
Araq
95808c2806 speed up Nim's lexer by using cstring instead of string. C optimizers are fragile. 2020-07-07 15:17:58 +02:00
Araq
49cea86d8b weaken tosproc test for my Windows machine which doesn't have 'ls' 2020-07-07 15:17:58 +02:00
awr1
37253d660f Minor improvements to typecast section of manual (#14896)
* Minor improvements to typecast section of manual

* Clarification to casting w/ concrete types

* Added less ambiguous language
2020-07-07 10:22:55 +02:00
Tomohiro
61a6098f2d Limit number of error messages from gcc/clang backend (#14852)
* Limit number of error messages from backend

* Avoid duplication of -fmax-errors

* make tests/misc/trunner.nim success
2020-07-07 10:22:10 +02:00
Clyybber
5bd2da3f64 Fix #14911 (#14922) [backport]
* Fix #14911

* Add testcase

* Fix test
2020-07-07 10:21:18 +02:00
Clyybber
ebd97884a0 Add testcase for #14472 (#14921) 2020-07-06 20:53:38 +02:00
ee7
a754160d65 tables.nim: Add named fields in smallest and largest (#14919)
The `smallest` and `largest` procs for `CountTable` returned a tuple
with named fields, but the same procs for `CountTableRef` returned an
anonymous tuple.

This commit makes those `CountTableRef` procs more consistent, and adds
a test.

Fixes: #14918
2020-07-06 14:02:03 +02:00
Araq
65af99a203 added security.md; refs #14882 2020-07-06 14:01:25 +02:00
Araq
6f962a4b36 fixes #14830 2020-07-06 13:41:56 +02:00
narimiran
46aacf917f Fix style inconsistencies due to the previous commit 2020-07-06 11:24:43 +02:00
narimiran
ebaf603c84 revert 0944b0f4 2020-07-06 10:55:51 +02:00
Dean Eigenmann
842efab8ae Update btrees.nim (#14916) 2020-07-06 10:23:42 +02:00
Juan Carlos
21b3ca636f Fix logging tiny bug (#14910)
* Fix logging tiny bug

* Update changelog.md

Co-authored-by: Danil Yarantsev <tiberiumk12@gmail.com>

* Update changelog.md

Co-authored-by: Danil Yarantsev <tiberiumk12@gmail.com>

* Update changelog.md

Co-authored-by: Danil Yarantsev <tiberiumk12@gmail.com>

* https://github.com/nim-lang/Nim/pull/14910#discussion_r450012032

Co-authored-by: Danil Yarantsev <tiberiumk12@gmail.com>
2020-07-06 04:00:25 -04:00
Clyybber
af27e6bdea Fix #14396 (#14793)
* Correct Left-To-Right evaluation of proc args
* Fix CPP backend
* Add testcase
* closes #14396
* closes #14345
* Improve test and optimize
* Improve testcase and optimize literals
* Fix bug
* Expand testcase and use DFA to optimize
* Turn genParams into proc
* Turn withTmpIfNeeded into a proc
* Cleanup
* Fix crash
* Better analysis
* Cleanup
* Trailing newline..
* Fix build
* Tiny cleanup

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2020-07-04 17:45:07 +02:00
Andreas Rumpf
1854d29781 scoped memory management (#14790)
* fixes the regressions
* closes #13936
* scope based memory management implemented
* enabled tcontrolflow.nim test case
* final cleanups
2020-07-04 07:37:24 +02:00
Timothee Cour
695154970d deprecate existsDir; use dirExists instead (#14884) 2020-07-03 23:04:23 +02:00
Juan Carlos
4f6acf24ff Add jsre (#14870) 2020-07-03 20:13:10 +02:00
Timothee Cour
a6cbe58e8c typetraits.$: $((int, float), int) is now "((int, float), int)" instead of "(tuple of (int, float), int)" (#14812)
Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2020-07-02 16:19:43 +02:00
Timothee Cour
dc5a40f3f3 {.deprecated: [existsFile: fileExists].} (#14735)
* {.deprecated: [existsFile: fileExists].}

* s/existsFile/fileExists/ except under deps

* workaround pending #14819

* fix test
2020-07-02 16:19:13 +02:00
Tomohiro
366b9a7e4a Fix #12745 (#14879) 2020-07-02 13:20:34 +02:00
Juan Carlos
d590611fc5 Clean out sharedlists (#14857) 2020-07-02 08:40:58 +02:00
Juan Carlos
cbcaf2bbc4 Clean out strutils (#14859)
Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2020-07-01 23:16:50 +02:00
Timothee Cour
930a0c999b cleanup comment now that #14434 was fixed (#14874) 2020-07-01 14:16:22 -07:00
Clyybber
1440e70c62 allow packed union (#14868)
Co-authored-by: Arne Döring <arne.doering@gmx.net>
2020-07-01 11:41:03 +02:00
Miran
1edb9a6178 fix #14401, trailing comma confuses nimpretty (#14867) 2020-07-01 11:40:13 +02:00
Timothee Cour
2867a33ebc fix #14846; add macros.extractDocCommentsAndRunnables (#14849)
* fix #14846; add macros.extractDocCommentsAndRunnables

* fixup

* update tests

* address comment
2020-07-01 09:26:23 +02:00
Juan Carlos
05384efec5 Clean out sharedtables (#14858)
Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2020-06-30 19:09:13 +02:00
Juan Carlos
a519f3b038 Removed asyncdispatch.newAsyncNativeSocket, was deprecated since 0.18 (#14854)
Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2020-06-30 16:29:53 +02:00
alaviss
56b3d422b0 typetraits: features and fixes (#14791)
* typetraits: add support for nnkTypeOfExpr

* typetraits: don't wrap typedesc symbols in StaticParam

* typetraits: add nested generics support to genericParams

* typetraits: make genericParams understand array[I, T] whackiness

Also moved tests to ttypetraits

* typetraits: clarify comment on genericParams
2020-06-30 15:25:53 +02:00
Ray Imber
36fa79a524 Fix asyncdispatch drain behavior (#14820) (#14838)
* Fix asyncdispatch drain behavior (#14820)

* Changed test to use asyncCheck instead of discard after code review (#14820)

* Added some debug statements to help understand what is happening in Azure.

* Removed debug statements and increased timeouts by 1 order of magnitude to account for slow Azure VMs

Co-authored-by: Ray Imber <ray@crankuptheamps.com>
2020-06-30 15:23:53 +02:00
flywind
8be54b8fa7 add debug fmt string like python's (#14808)
* add debug format string

* remove try except

* add changelog
2020-06-30 15:21:37 +02:00
Timothee Cour
89a15e417d CI openbsd: 3x batching via NIM_TESTAMENT_BATCH ; overall CI finishes in 21m instead of 34m (#14851)
* CI openbsd: 2x batching via NIM_TESTAMENT_BATCH

* auto-generate .builds/openbsd_x.yml to avoid code duplication

* 3x batching
2020-06-30 14:21:30 +02:00
Juan Carlos
04deb6c942 Clean out dom (#14855)
* Clean out dom

* Clean out dom
2020-06-30 10:08:16 +02:00
Juan Carlos
74d1f25010 Clean out oldast (#14837)
* Clean out old Deprecated CLI switch
* Update to remove --oldast CLI option
2020-06-30 10:01:25 +02:00
lbartoletti
5c1fa142d6 New freebsd platforms (#14801)
* add riscv as riscv64

* add all platforms supported by FreeBSD
2020-06-29 10:31:25 +02:00
Timothee Cour
1b41c3122b fix #13432 typetraits.$: $(int,) is now (int,); $tuple[] is now tuple[] (#14799)
* typetraits.$: $(int,) is now (int,); $tuple[] is now tuple[]

* changelog
2020-06-29 09:34:05 +02:00
Juan Carlos
5d5df4a394 Clean out Deprecated proc (#14797)
* Remove and/or clean out Deprecated 'add' proc for floats
* Update a test
2020-06-29 09:33:07 +02:00
aguspiza
d968163cd1 SSL_CTX_load_verify_locations parameters are reversed (#14815) [backport] 2020-06-29 08:50:37 +02:00
Clyybber
299ddda5f6 Make unreachable code a warning instead of an error (#14816)
* Make unreachable code a warning

* Adapt test

* Trigger CI
2020-06-29 08:49:53 +02:00
Timothee Cour
3732556468 fix ./koch tests following #14823 (#14845) 2020-06-28 14:34:34 -07:00
Clyybber
62394616e8 DFA and injectdestructors cleanup (#14824)
* DFA and injectdestructors cleanup

* More precise write analysis

* Cleanup obsoleted path

* Unify defInstrTargets and useInstrTargets

* Misc cleanups

* Nicer CFG printing

* Misc cleanups 2
2020-06-28 19:36:30 +02:00
Danil Yarantsev
7936768560 Fix some typos (#14843) 2020-06-28 19:17:18 +02:00
Clyybber
4f70180a58 Fix typo 2020-06-28 18:03:39 +02:00
Danil Yarantsev
c285739d55 Remove double entry for thiscall (#14842) 2020-06-28 18:00:43 +02:00
Andrey Makarov
d9c1501757 get rid of $READLINK variable (#14841) 2020-06-28 17:59:57 +02:00
Clyybber
394a56650a Fix #14647 (#14776)
* Fix #14647

* Correct fix

* Typo and add test

* For real now :p
2020-06-28 17:47:47 +02:00
Clyybber
037990bc78 Changelog: Tiny style improvement 2020-06-28 15:38:24 +02:00
lqdev
5d5271b789 fixed #14839 (#14840) 2020-06-28 13:38:57 +02:00
Clyybber
54a52e7d08 Update link to parseSpec proc 2020-06-28 00:13:54 +02:00
rockcavera
252f668829 add a second asyncnet.recvFrom (#14237)
* add a second asyncnet.recvFrom

* fixes

* pre-allocating address

* add a new nativesockets.getAddrString()
2020-06-27 22:59:08 +01:00
Manuel Bojato
bc66788b3f docs: Make ..<, .. ^ more discoverable (#14835) 2020-06-27 23:42:58 +02:00
Manuel Bojato
22f1b5120e Fix nimdoc invalid css on theme switch class (#14834) 2020-06-27 23:36:31 +02:00
Sizhe Zhao
ad00d616e8 Warn about calling wrappers at compile time until #14049 is fixed. (#14828) 2020-06-27 16:51:48 +02:00
Timothee Cour
90808877c5 testament: generic N-fold batching: windows CI 37mn=>16m (#14823)
* testament: run CI faster thanks to batching
* move ta_in, tstdin into existing tosproc
* move ta_out,tafalse,texitcode,tstderr into existing tosproc
* joinable osproc
* move tstdout into existing tosproc
* spec: batchable; fix tests
* fixup
2020-06-27 16:51:17 +02:00
Clyybber
fdb37400cb Testament: Reenable arraymancer (#14831) 2020-06-27 15:58:19 +02:00
Sizhe Zhao
70b07edf42 Fix missing comma (#14829) 2020-06-27 12:11:29 +02:00
treeform
f926dc53f1 Add all missing css properties to dom.nim. (#14825)
* Add all missing css properties

* remove extra space
2020-06-26 19:15:21 +01:00
Timothee Cour
4dfb062f4d update contributing.rst and docstyle.rst: refer to a bug via bug #1234 + other guidelines (#14796)
* add a testing convention in nep1
* misc updates to contributing.rst and docstyle.rst
* address comments
2020-06-26 10:40:34 +02:00
Timothee Cour
49fcda3330 followup after https://github.com/Vindaar/ggplotnim/pull/74 wrt #14447 lent iterators (#14817)
* followup after https://github.com/Vindaar/ggplotnim/pull/74 wrt #14447 lent iterators

* ggplotnim: remove -d:nimHasWorkaround14720
2020-06-26 04:10:22 +02:00
treeform
baa80ca9d4 Add hasAttribute method to dom.nim. (#14814)
See: https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttribute
2020-06-25 14:45:37 -07:00
ktamp
41c97e4b70 readLine: Fix issues with --gc:arc
**--gc:arc** defines **nimv2**. This changes the definition of **WideCStringObj**.
Also an empty string should be returned in case of EOF.
2020-06-26 00:31:06 +03:00
narimiran
13193b2964 turn 'runnableExample' into 'code-block' to make nightlies green
This example doesn't work on our nightlies CI.
Other procs in this module already use 'code-block'.
2020-06-25 16:55:11 +02:00
Clyybber
0a9a639230 Add testcase for #4796 (#14784)
* Add testcase for #4796

* Fix test
2020-06-25 15:12:30 +02:00
alaviss
1a0725f022 koch: add --localdocs to allow building only local docs (#14783)
* koch: add --localdocs to allow building only local docs

This flag also make koch doc use the passed arguments when building
the offline docs.

This is useful when generating nightlies as we would want to use
--doccmd:skip and also skipping a pass of docgen speed things up
drastically (for non-native targets).

This flag superseded the undocumented --docslocal.

* kochdocs: filter google analytics code from the arg list instead

This commit introduce a small PEG expression to filter out the google
analytics code before building local docs when --localdocs is not
specified. This lets us keep any arguments unrelated to google analytics
when building local docs, useful for use with --doccmd:skip
2020-06-25 10:28:57 +02:00
Timothee Cour
0c56eeda0e expr => untyped; stmt => typed (#14804)
* expr => untyped; stmt => typed

* changelog + comment
2020-06-25 10:22:08 +02:00
Timothee Cour
32f335f594 fix #14802 (#14803) 2020-06-25 08:00:19 +02:00
Danil Yarantsev
0327159344 Add test-cases to some fixed issues to close them (#14795) 2020-06-24 20:38:08 -07:00
ktamp
c6e09e335a readLine: Remove recursive imports 2020-06-25 00:22:24 +03:00
Danil Yarantsev
80952cadaa Reject casts to builtin typeclasses (#14788)
* Closes #14231, closes #14452

* Merge test to tcast.nim
2020-06-24 22:32:01 +02:00
Timothee Cour
3e5743d6f7 add typetraits.elementType (#14780)
* add typetraits.elementType

* add a test for 0-sized seq
2020-06-24 22:31:07 +02:00
Euan
0434aef4cd Patch #14716 - add missing when (#14792) 2020-06-24 18:44:10 +02:00
Timothee Cour
37081e2945 fromJson: support object variants (#14694) 2020-06-24 18:03:01 +02:00
Euan
a3ae52de1a Fix #14715 - detect tool fails on FreeBSD (#14716) 2020-06-24 18:02:18 +02:00
Timothee Cour
b49ac11a77 fix #10343 (#14789) 2020-06-24 18:00:35 +02:00
Clyybber
302e3b7f44 CI: Install the pkg we cloned (#14770) 2020-06-24 17:27:46 +02:00
narimiran
2220ff70be cleanup [ci skip] 2020-06-24 13:16:40 +02:00
Constantine Molchanov
1b196d85aa Fix Norm test path. (#14779) 2020-06-24 00:36:41 +02:00
ktamp
a3b9516249 readLine: Unicode support for Windows console
When input is read from the Windows console, input encoding is UTF16. This is translated internally to UTF8.
2020-06-23 23:31:41 +03:00
treeform
9ebbe000a8 Enable fidget in important_packages. (#14742)
* Enable fidget in important_packages.

Fidget now works with `nimble test` and there is a CI: https://github.com/treeform/fidget/commits/master

* Add libx11-dev to make fidget compile.

* try libxcursor-dev

* try xorg-dev
2020-06-23 20:37:29 +02:00
Miran
6bf2990f66 [backport] fix #14748, move gdb files to other section of installer.ini (#14772) 2020-06-23 20:36:59 +02:00
Miran
881d1ee57b fix #14750, don't allocate too much in newWideCString (#14773) 2020-06-23 16:15:37 +02:00
Clyybber
685d03e2e0 Correct changelog (#14775)
These switches were removed, not deprecated :)
2020-06-23 15:20:31 +02:00
Andreas Rumpf
16bdc547b7 fixes #14760 (#14769) 2020-06-23 15:17:17 +02:00
Clyybber
4cb41f53f0 Add testcase for #14440 (#14771) 2020-06-23 14:17:12 +02:00
Juan Carlos
28510a9da9 Deprecated laxStrings for mutating the internal zero terminator on strings and its Deprecated code cleaned out (#14766)
Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2020-06-23 13:20:53 +02:00
Juan Carlos
c3459c7b14 Deprecate oldNewlines, clean out deprecated code from oldNewlines (#14763) 2020-06-23 11:22:07 +02:00
Juan Carlos
79ed8e79ef Documentation GC (#14739) 2020-06-23 11:21:33 +02:00
Araq
ebd1cc0265 minor bugfixes for 'func' and .borrow 2020-06-23 10:58:55 +02:00
Andreas Rumpf
da29222f86 init checks and 'out' parameters (#14521)
* I don't care about observable stores
* enforce explicit initializations
* cleaner code for the stdlib
* stdlib: use explicit initializations
* make tests green
* algorithm.nim: set result explicitly
* remove out parameters and bring the PR into a mergable state
* updated the changelog
2020-06-23 10:53:57 +02:00
Timothee Cour
a9eee6db65 misc testament cleanups (#14764)
* misc testament cleanups extracted cleanups from #14530

* make sure all CI failures can be searched with `FAIL: ` including megatest failures
2020-06-23 10:53:03 +02:00
Juan Carlos
8e54bc5b0c Deprecate and/or remove ospaths (#14767) 2020-06-23 10:51:33 +02:00
Timothee Cour
511bd947d3 fix bug in semgnrc: runnableExamples should not semcheck, even with > 1 arg (#14768) 2020-06-23 10:06:36 +02:00
Timothee Cour
235d8ba069 unbreak CI, refs https://github.com/timotheecour/Nim/issues/167 (#14765) 2020-06-22 18:38:23 -07:00
Clyybber
03c8bbcc6e Remove outdated comment and copy of length (#14759) 2020-06-22 22:05:18 +02:00
b3liever
59ba4d8c03 added normal variate function (#14725)
* added normal variate function
* change method only slightly faster
* changelog + since

Co-authored-by: b3liever <b3liever@yandex.com>
2020-06-22 20:48:33 +02:00
Andreas Rumpf
451129de42 fixes #14240 [backport:1.2] (#14757) 2020-06-22 14:11:13 +02:00
Andreas Rumpf
8df20276c9 fixes #14458 [backport:1.2] (#14756) 2020-06-22 13:06:22 +02:00
alaviss
c8554ebc0c posix_other: add define to force time_t to 64 bit [backport] (#14753)
This is a temporary remedy for time_t transition to 64 bit on newer
Linux libc (musl >= 1.2.0, glibc >= 2.32).

In the future we might want to move away from libc, or figure out a way
to reliably detect the real size of C types at compile time, both of
which are difficult.
2020-06-22 09:23:24 +02:00
ee7
1e484ed62b [backport] Docs: Fix broken code-block (#14749)
This commit indents the contents of a `code-block` in `httpclient.nim`
so that it displays correctly. The bug was introduced by 42a64245f8.

I did a quick search for other `code-block`s that are broken in the same
way, but the only other one I found (in `pegs.nim`) is not included in
the generated documentation.
2020-06-22 08:12:50 +02:00
treeform
1ffe113450 Export fields from the Selection object. (#14752)
See: https://developer.mozilla.org/en-US/docs/Web/API/Selection
2020-06-21 20:41:24 +02:00
Andreas Rumpf
3ba0c30758 sizeof for empty objects/tuples should be 1; fixes #14690 (#14751) 2020-06-21 19:58:37 +02:00
alaviss
c7dee55b87 encodings: use only one iconv definition [backport:1.2] (#14741)
Fix an issue reported on IRC: using encodings with --dynlibOverrideAll
result in duplicated iconv definitions, causing compile errors.

This commit remove the `var` wrapper of iconv and go all out on
pointers, as it should due to how the API accepts nil. Also corrected
the API to resemble iconv(3p).
2020-06-21 19:28:03 +02:00
treeform
ca71a60ff6 Add css white-space property to dom.nim. (#14743)
https://developer.mozilla.org/en-US/docs/Web/CSS/white-space
2020-06-21 19:25:29 +02:00
Timothee Cour
79c90b30ee nep1: use subjectVerb, not verbSuject (#14732) 2020-06-19 23:38:43 +02:00
Kaushal Modi
ac8ab4c549 Clarify the use of the backwards index operator (^N) in tut1 (#14681)
* Clarify the use of the backwards index operator (^N) in tut1

For consistency:
- Do `[a .. ^b]` (notice spaces on both sides of `..`)
- Do `[c ..< d]` (notice spaces on both sides of `..<`)

Fixes https://github.com/nim-lang/Nim/issues/14671.

* tut1: Add a note that ^ template calls can be saved to consts
2020-06-19 10:22:48 -04:00
Juan Carlos
99c198625c Deprecate unroll pragma, remove from documentation (#14705) 2020-06-19 15:08:45 +02:00
Timothee Cour
2039e3e883 fix #13899 defer now works with async (#14723) 2020-06-19 15:08:00 +02:00
Araq
65c7884a3c fixes #14718 [backport] 2020-06-19 15:02:38 +02:00
Clyybber
45d1e55e72 Add testcases for #11811 and #14315 (#14726)
* Add testcase for #11811

* Add testcase for #14315
2020-06-19 14:56:38 +02:00
Araq
45bc6954c5 improve the parser's error message 2020-06-19 10:50:39 +02:00
Araq
522bc8dda1 added a space 2020-06-19 10:32:16 +02:00
Timothee Cour
5ad8b9e8eb fix #14685 tests/async/t7758.nim flaky (#14721)
* fix #14685 tests/async/t7758.nim flaky

* address comment

* address comment
2020-06-19 09:53:45 +02:00
Timothee Cour
9c42ae91b7 add legacy workaround; improve test so that it actually tests for the bugfix 2020-06-19 09:53:06 +02:00
solo989
408518c9fe Update tuple newLit 2020-06-19 09:53:06 +02:00
BarrOff
99ad65fdd6 make nim-gdb compatible with BSD systems (#14700) 2020-06-18 20:48:55 +02:00
Timothee Cour
bb62feff72 fix #14691 docgen works again for methods (#14701)
* fix #14691 docgen methods

* fixup
2020-06-18 08:47:16 +02:00
Timothee Cour
7df27b5035 [cleanups] doassert => doAssert; mark deadcode (#14711) 2020-06-17 20:25:25 -07:00
Miran
e7f280bd26 Remove deprecated stuff from stdlib (#14699)
* update to the latest Jester

* remove deprecated procs from some stdlib modules

* 'criterion' is not maintained anymore and relies on obsolete stuff
2020-06-17 15:25:02 +02:00
Timothee Cour
8619534293 remove compilerproc from newIdentNode (#14692) 2020-06-17 08:10:34 +02:00
Juan Carlos
15a45e8e73 Documentation update nims.rst (#14683)
* Update nims.rst to add modules that work on NimScript as mentioned in the changelog.md

* https://github.com/nim-lang/Nim/pull/14683#issuecomment-644976921
2020-06-17 07:58:03 +02:00
solo989
bdd2c25e9f Update macros.nim (#14697) 2020-06-17 07:57:04 +02:00
Timothee Cour
ff93302f69 use check to investigate #14685 flaky tests/async/t7758.nim (#14689) 2020-06-16 15:57:57 -07:00
Timothee Cour
7ded490ec0 cleanup tests/test_nimscript.nims (#14686) 2020-06-16 14:38:30 -07:00
Dylan Modesitt
e35b21e553 Close#5586 (#14682)
* re-enable macos and bsd on some coro tests

* re-enable macos and bsd on some coro tests
2020-06-16 16:24:26 +02:00
Euan
1bc2e19498 Set cincludes and clibdir for FreeBSD, OpenBSD and NetBSD. (#14680) 2020-06-16 11:44:28 +02:00
Timothee Cour
dfe51d10a1 addQuitProc now works with closures, and c, js(node/browser) backend; fix some bugs in testament (#14342)
* make addQuitProc great again

* fix bugs in testament

* fix test

* change 2016 => 2020

* addQuitProc => addExitProc + locks

* move to std/exitprocs
2020-06-16 11:43:48 +02:00
Timothee Cour
45cac4afda fix #14179, fix #14142, make CI 1.4x faster (2x faster locally) (#14658)
* fix #14142: no more clash with: import os + use of existsDir/dirExists/existsFile/fileExists/findExe in config.nims

* remove a comment

* Revert "fixes the regression #12860 caused; hotfix"

This reverts commit 3d2459bdc0.

* Revert "Undefine `paramCount` & `paramStr` in nimscript.nim for *.nims (#12860)"

This reverts commit d38853c504.

* noNimScript => noWeirdTarget + noNimJs
2020-06-16 08:56:12 +02:00
Euan
7b12f13946 Use cc on OpenBSD and link to libm when building result (#14672) 2020-06-16 08:50:57 +02:00
Timothee Cour
de5cde473a hintMsgOrigin now works in VM code (#14678)
* `hintMsgOrigin` now works in VM code

* remove a simplification for now
2020-06-16 08:49:57 +02:00
Timothee Cour
faedb14a16 misc cleanups in compiler msgs: use toHumanStr, etc (#14677) 2020-06-15 21:17:24 -07:00
Timothee Cour
49033eb531 make tests/stdlib tests joinable (#14626)
* make tests/stdlib tests joinable

* fixup
2020-06-15 13:27:33 +02:00
Timothee Cour
d51beb7b20 make fromJson/toJson work with array[range, typ], + 1 bugfix (#14669)
* make toJson more robust

* properly handle array
2020-06-15 13:22:43 +02:00
Timothee Cour
bf604c6829 normalizeExe (#14668) 2020-06-15 10:57:34 +02:00
solo989
3cbf59336d Update newLit set[T] to work when set is empty. (#14662)
* Update macros.nim

* Update lib/core/macros.nim

Co-authored-by: Clyybber <darkmine956@gmail.com>

Co-authored-by: Clyybber <darkmine956@gmail.com>
2020-06-15 09:15:17 +02:00
Ico Doornekamp
571bc011ea Added --benchmarkVM to times.cpuTime() documentation (#14663) 2020-06-15 08:58:11 +02:00
Juan Carlos
a056b4c3f1 Change 'Future Directions' to link memory management documentation (#14664) 2020-06-15 08:55:24 +02:00
jcosborn
5a22d6b57b fix codegen bug due to changing existing symbol declaration in template (#14666) 2020-06-15 08:40:12 +02:00
alaviss
d749c8cd87 compiler/commands: make gitHash settable at compile-time. (#14654)
This is useful for building nightlies, since we will be building from a
generated source archive and git metadata is lost there.
2020-06-14 11:22:55 +02:00
Andy Davidoff
4e3edf5836 add arc and orc to gc list (#14653) 2020-06-14 11:12:08 +02:00
Timothee Cour
0fc5d3f13b fix #14655 setLen(seq) now zeros memory (#14656)
* simplify sysstr.nim

* fix #14655
2020-06-14 11:11:26 +02:00
Dominik Picheta
d3b25a2948 Clarify imported exceptions note in manual 2020-06-13 11:44:01 +01:00
Timothee Cour
d149823019 fix #13166 tioselectors flaky test on freebsd+OSX (#14634) 2020-06-12 21:19:23 -07:00
Araq
5a26c3799b reorder.nim: fixed typos 2020-06-12 11:57:29 +02:00
Timothee Cour
e30a08103d remove tyOpt, mOpt (#14636)
* remove tyOpt, mOpt

* fixup
2020-06-12 11:03:52 +02:00
Juan Carlos
82e424189e Add rstgen.rstToLatex convenience proc for renderRstToOut and initRstGenerator with outLatex output, see https://github.com/nim-lang/fusion/pull/11#issuecomment-641804899 (#14629) 2020-06-12 10:51:55 +02:00
djazz
1168c75381 httpcore: Add http code 308 Permanent Redirect (#14639)
* httpcore: Add http code 308
* httpclient: Add 308 to redirection proc
* fix typo
2020-06-12 10:16:38 +02:00
alaviss
67d34366dc tools/kochdocs: add log folding supports for more CI services (#14643)
Added log folding for:
- Github Actions
- Azure Pipelines
2020-06-12 10:06:29 +02:00
Timothee Cour
c83a22b76e Disable tfdleak_multiple on platforms other than Windows (#14624) 2020-06-11 12:54:32 -07:00
c-blake
6aa971d39f Add proc find to heapqueue (#14628)
* Unwind just the "pseudorandom probing" (whole hash-code-keyed variable
stride double hashing) part of recent sets & tables changes (which has
still been causing bugs over a month later (e.g., two days ago
https://github.com/nim-lang/Nim/issues/13794) as well as still having
several "figure this out" implementation question comments in them (see
just diffs of this PR).

This topic has been discussed in many places:
  https://github.com/nim-lang/Nim/issues/13393
  https://github.com/nim-lang/Nim/pull/13418
  https://github.com/nim-lang/Nim/pull/13440
  https://github.com/nim-lang/Nim/issues/13794

Alternative/non-mandatory stronger integer hashes (or vice-versa opt-in
identity hashes) are a better solution that is more general (no illusion
of one hard-coded sequence solving all problems) while retaining the
virtues of linear probing such as cache obliviousness and age-less tables
under delete-heavy workloads (still untested after a month of this change).

The only real solution for truly adversarial keys is a hash keyed off of
data unobservable to attackers.  That all fits better with a few families
of user-pluggable/define-switchable hashes which can be provided in a
separate PR more about `hashes.nim`.

This PR carefully preserves the better (but still hard coded!) probing
of the  `intsets` and other recent fixes like `move` annotations, hash
order invariant tests, `intsets.missingOrExcl` fixing, and the move of
`rightSize` into `hashcommon.nim`.

* Fix `data.len` -> `dataLen` problem.

* Add neglected API call `find` to heapqueue.

* Add a changelog.md entry, `since` annotation and rename parameter to be
`heap` like all the other procs for consistency.

* Add missing import.
2020-06-10 19:53:18 +01:00
Timothee Cour
8bbdb8f43f fix #14545 windows CI docs (#14590)
* fix #14545 windows paths
* add lib/std/private/strutils2.nim
* remove dependency strutils2 => strutils
* address comment: lib/std/private/strutils2.nim => compiler/strutils2.nim
2020-06-10 14:10:57 +02:00
ee7
5131af1a44 exceptions.nim: Fix a bad Error -> Defect renaming (#14621)
This commit fixes a mistake from 7d6cbf290a.
2020-06-10 09:34:20 +02:00
Timothee Cour
b7b84fa165 parseutils: integerOutOfRangeDefect => integerOutOfRangeError (#14627) 2020-06-09 23:57:27 -07:00
Timothee Cour
d81bc69587 enable tioselectors on osx; more diagnostic for #13166 (#14625) 2020-06-09 19:15:18 -07:00
Juan Carlos
387e337a2a Documentation update a description (#14619)
* Documentation update a description in a page listing links

* Update doc/docs.rst

Co-authored-by: Danil Yarantsev <tiberiumk12@gmail.com>

Co-authored-by: Danil Yarantsev <tiberiumk12@gmail.com>
2020-06-09 22:17:32 +01:00
Andreas Rumpf
6085ad95ff fixes #14279 (#14618) 2020-06-09 20:39:26 +02:00
Andreas Rumpf
b3029ba213 fixes #14578 (#14615) 2020-06-09 17:05:01 +02:00
Juan Carlos
881fa94b57 Documentation Fix Typo, Add Table (#14609) 2020-06-09 15:43:42 +02:00
ynfle
aa70cfdea2 Fix(astspec.txt): type of repeated word (#14612) 2020-06-08 20:14:26 -07:00
Max Grender-Jones
cc3409e264 Make the example better describe the desired outcome (#14611) 2020-06-08 18:49:07 -07:00
lbartoletti
30c09e4607 [OpenBSD] Add arm support (#14608)
* add arm support to openbsd

* use clang on openbsd
2020-06-08 20:06:04 +02:00
Andreas Rumpf
c308c2e60b optimized wrapWords; fixes #14579 (#14606) [backport:1.2] 2020-06-08 14:34:26 +02:00
Andreas Rumpf
e3f80e434a fixes #14557 (#14607) 2020-06-08 14:32:45 +02:00
Timothee Cour
c7a1a7b8bf toJson, jsonTo, json (de)serialization for custom types; remove dependency on strtabs thanks to a hooking mechanism (#14563)
* json custom serialization; application for strtabs
* serialize using nesting
* make toJson more feature complete
* add since
* Revert "Improve JSON serialisation of strtabs (#14549)"

This reverts commit 7cb4ef26ad.

* better approach via mixin
* toJson, jsonTo
* fix test
* address comments
* move to jsonutils
* doc
* cleanups
* also test for js
* also test for vm
2020-06-08 10:35:23 +02:00
Tomohiro
733bd76f6b Fix sugar.dump: It doesn't work correctly with compile time expression (#14580) 2020-06-08 10:28:42 +02:00
Timothee Cour
0d814f2d44 hotfix disable nitter refs https://github.com/timotheecour/Nim/issues/167 (#14603) 2020-06-08 08:15:34 +02:00
alaviss
8edac9cf1d openssl: use explicit result for SSL_in_init (#14597)
Sometimes the analysis might get funky and decide that the if-expression
below is not an if-expression. Details of how this can happen is largely
unknown, but it's easy to prevent so we will just go forward with that.

Fix #14591
2020-06-08 08:15:10 +02:00
Clyybber
52841dba09 Fix #14568 (#14583)
* Fix #14568
* Add testcase
* Fix bogus test
* Adapt other failing tests
* Declarations are always first writes
2020-06-07 23:32:41 +02:00
Andreas Rumpf
754a196d47 fixes #14315 (#14594) 2020-06-07 23:29:26 +02:00
Andreas Rumpf
419dbd573d fixes #14118 (#14595) 2020-06-07 20:11:42 +02:00
Andreas Rumpf
66c50c2ffc implement the 'bind' statement for generics, it was an oversight that this was never implemented (#14584) 2020-06-07 09:55:56 +02:00
lbartoletti
51b71e35f2 Fix link to "rebuilding the compiler" (#14567) 2020-06-06 21:53:18 +02:00
Andreas Rumpf
32083c7ff8 more precise analysis about 'observable stores' [backport:1.2] (#14582) 2020-06-06 21:28:46 +02:00
Leorize
4fdf9cb808 wrappers/openssl: defer loading SSL_CTX_set_ciphersuites 2020-06-06 21:11:53 +02:00
Leorize
6b2d8bfc8b net: also set TLSv1.3 cipher suites 2020-06-06 21:11:53 +02:00
Leorize
3cd74c6408 wrappers/openssl: mark casts as gcsafe
Nim will pretend that these proc are not gcsafe if they are not marked.
2020-06-06 21:11:53 +02:00
Leorize
b323bccd81 wrappers/openssl: enable SSL_CTX_set_ecdh_auto for LibreSSL
This procedure is not no-op for older LibreSSL, and the ABI is kept for
newer versions, so there's no harm in enabling it unconditionally for
all LibreSSL versions.
2020-06-06 21:11:53 +02:00
Leorize
e80a23f4d2 net: revert compatibility changes for Windows
This reverts commit d53a6355f3 and
688b1f250e.
2020-06-06 21:11:53 +02:00
Leorize
d406f588d8 wrappers/openssl: the version number comes from the utility library
Previously we loaded the SSL library for this, but that's not where the
symbol resides.
2020-06-06 21:11:53 +02:00
Leorize
0ca069b4f8 net: use CiphersOld list for Windows
The default DLLs shipped are too old, switch to CiphersOld list to
ensure compatibility.

This commit should be reverted before any future release.
2020-06-06 21:11:53 +02:00
Leorize
279438f1df net: don't call set_ecdh_auto for super old OpenSSL
And the fun thing is that currently we use a super old OpenSSL on
Windows.
2020-06-06 21:11:53 +02:00
Leorize
b5b191af4b wrappers/openssl: fix SSL_CTX_set_mode
Follow up of 794042080b
2020-06-06 21:11:53 +02:00
Leorize
61d4fbce4f wrappers/openssl: getOpenSSLVersion is gcsafe
Yet another weird {.gcsafe.} triggering when it shouldn't.
2020-06-06 21:11:53 +02:00
Leorize
6c0f86c486 net: enable automatic EC curve selection for OpenSSL 1.0.2
This setting is required for servers running OpenSSL < 1.1.0 to support
EC-based secure ciphers that is now part of the default cipher list.
2020-06-06 21:11:53 +02:00
Leorize
9278e785bd wrappers/openssl: fix SSL_CTX_ctrl signature 2020-06-06 21:11:53 +02:00
Leorize
e4e3d99ee2 asyncnet: clear SSL error queue before performing I/O
Follow up of 476be6cc27
2020-06-06 21:11:53 +02:00
Leorize
256841cf2c changelog.md: clarify that only the default has changed [ci-skip] 2020-06-06 21:11:53 +02:00
Leorize
1715935846 ssl_config_parser: refactor for sanity reasons 2020-06-06 21:11:53 +02:00
Leorize
3d4d3f4ac2 untestable/thttpclient_ssl: some tests are no longer broken
With the changes to the default cipher suites, certain tests are no
longer broken and are acting as they should.
2020-06-06 21:11:53 +02:00
Leorize
23cc4091d9 untestable/thttpclient_ssl: move incomplete-chain to dubious_broken
It's unsure why this test fail for macOS, but it doesn't hurt if it's
not passing.
2020-06-06 21:11:53 +02:00
Leorize
1fb2a58674 net: use a secure cipher list by default
Previously, the `net` module use the blanket "ALL" as the default cipher
list. This list may contain security ciphers that are weak and/or outdated
according to the current standard.

This commit introduces a new module `ssl_config` that contains the
latest OpenSSL configurations as recommended by Mozilla OpSec, and
make the `net` module use the cipher list targeting `intermediate`
compatibility level as the default.
2020-06-06 21:11:53 +02:00
Leorize
6cb94b5da6 asyncnet, net: clear openssl error queue before performing I/O
Per SSL_get_error(3):

  The current thread's error queue must be empty before the TLS/SSL I/O
  operation is attempted, or SSL_get_error() will not work reliably.

There has been records of not clearing the error queue causing weird SSL
errors when there shouldn't be any, see:

https://github.com/openssl/openssl/issues/11889
2020-06-06 21:11:53 +02:00
Leorize
f243f9aeb5 openssl: fix erroneous function signatures
Now matches the declaration in openssl/err.h
2020-06-06 21:11:53 +02:00
Leorize
78982b52f0 net: don't clear error queue unless shutdown() will be performed 2020-06-06 21:11:53 +02:00
Leorize
19ccce2617 Revert "net: don't clear all errors on close"
You're supposed to clear the error queue before any I/O operations. Per
SSL_get_error(3) man page.

This reverts commit ee3ed37300.
2020-06-06 21:11:53 +02:00
Leorize
44d0b4bdfd thttpclient_ssl: be less specific
The error we're looking for is "certificate verify failed". The routine
that reports this will be different between openssl versions, so it
makes no sense to track the routine name as well.
2020-06-06 21:11:53 +02:00
Leorize
d06e6eec79 net: don't clear all errors on close
Closing a socket clears the error queue of the entire thread, which
seems to be a bit too invasive.

Also I don't find any reason in the PR that added this.
2020-06-06 21:11:53 +02:00
Leorize
65b350f112 untestable/thttpclient_ssl: fix macos 2020-06-06 21:11:53 +02:00
Leorize
df91f61e20 untestable/thttpclient_ssl: fix 10000-sans test 2020-06-06 21:11:53 +02:00
Leorize
19ccc5fd8d untestable/thttpclient_ssl: catch errors caused by the bad catergory
Previously the errors caused by `SSL_shutdown()` masked these, so now we
catch them.
2020-06-06 21:11:53 +02:00
Leorize
82092b3bb7 asyncnet, net: call SSL_shutdown only when connection established
This commit prevents "SSL_shutdown while in init" errors from happening.

See https://github.com/openssl/openssl/issues/710#issuecomment-253897666
2020-06-06 21:11:53 +02:00
Timothee Cour
61f2f1f5c5 fix #14576 addr of param (including for lent) now works with nim js (#14577)
* fix #14576 addr(param) now works in nim js

* workaround https://github.com/nim-lang/Nim/issues/14578
2020-06-06 20:15:24 +02:00
Araq
336f1e63d0 reorder.nim: fixes the indentation 2020-06-06 20:08:57 +02:00
Zed
ea761419ad Fix asynchttpserver newline breaking content-length (#14565) [backport] 2020-06-06 12:20:11 +02:00
Timothee Cour
d573581eb7 remove isMainModule from json,os,sequtils (#14572)
* move json.isMainModule => tjson

* move isMainModule => tos,tsequtils
2020-06-06 11:50:46 +02:00
Danil Yarantsev
b19ad22b90 Fix #14570 (#14571)
* Fix #14570
2020-06-06 09:31:19 +02:00
Timothee Cour
7cdf470269 refs #14545 fix snippet errors: avoid showing confusing errors when they are expected (#14569) 2020-06-05 19:04:39 -07:00
Araq
0824fdd061 fixes #14562 2020-06-05 16:15:13 +02:00
PMunch
7cb4ef26ad Improve JSON serialisation of strtabs (#14549)
This creates a more compact serialisation of strtabs that is more in
line with the normal tables.
2020-06-05 10:54:38 +02:00
alaviss
c1ca06b452 tfdleak: fix flakyness on Windows (#14550)
* tfdleak_multiple: introduce stress tester for tfdleak

Imported from #14548 and tweaked for consumption by testament.

This test seems to be really good at bringing out the flakyness of
tfdleadk.

Co-authored-by: Timothee Cour <timothee.cour2@gmail.com>

* tfdleak: increase accuracy of the test on Windows

This commit implements a new testing strategy for Windows:
1. We duplicate the handle that will be tested and enable inheritance.
   This duplicate will serve as a reference handle.
2. In addition to checking whether the handle is valid, we also verify
   whether the handle is the same as the reference. This gives us
   complete certainty on whether the handle in question is inherited
   from the parent.
   A side effect is that this uses Windows 10+ APIs. But since
   this is just for the test, we don't have to be picky about it.

Ideally we would want to do something like this for other POSIX-based
system, but most of them lack a facility to do this, and as of writing
there isn't any false positive for them, so we won't need the additional
checks.

MemFile.fHandle will also no longer be tested, as this handle defaults
to being invalid.

Co-authored-by: Timothee Cour <timothee.cour2@gmail.com>
2020-06-04 13:25:38 +02:00
Timothee Cour
01f6e505c8 bug fixes with sfMainModule, hints, mainPackageNotes, mainPackageId, hintSuccessX (#14555)
* SuccessX `out` now works with --compileOnly and jsonscript; fix bugs in jsonscript
* several bug fixes; eg: `nim doc lib/system/io` now is sane
* dummy edit to force docs CI
2020-06-04 10:40:17 +02:00
Timothee Cour
4ba34522f6 [cleanup] docgen: remove docOutdir now that outDir is always set (#14554) 2020-06-03 19:20:41 -07:00
alaviss
55f0df164b io: correct signature for some win32 apis (#14551)
See https://github.com/nim-lang/Nim/pull/14550#issuecomment-637937649
2020-06-03 18:17:06 +02:00
Timothee Cour
4301a3da9d * honor --errorMax even for tools (eg drnim, nim doc) (#14546)
* fix a bug that prevented nim doc compiler/nim on windows
2020-06-02 18:54:33 +02:00
Timothee Cour
621384b8ef fix https://github.com/timotheecour/Nim/issues/266 retry on failure to avoid common 503 github errors (#14547) 2020-06-02 10:47:19 +02:00
cooldome
e5b64af831 Implement rendering of []=, {}, {}= braces (#14539)
* render curly braces
* fix typo
* fix test

Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-06-01 19:56:17 +02:00
Timothee Cour
3cf88c2b49 walkDirRecFilter, update doc CI filter, compiler/index.nim for docs + various other fixes (#14501)
* update doc CI filter to include the files mostly likely to require doc rebuild
* remove code duplication in ./config/nimdoc.cfg; show link to compiler docs, various fixes
* walkDirRecFilter, factor nativeToUnixPath workaround
* glob for getRst2html
* docslocal: 40s to build all docs
* revert code dedup in github actions which did not work alas...
* fixups
2020-06-01 19:21:41 +02:00
Andreas Rumpf
75e579ff8e parser.nim: minor refactorings (#14540) 2020-06-01 19:04:28 +02:00
Danil Yarantsev
3698f197f1 Change severity of template instantiation message [backport] (#14526)
* Change severity of template instatiation msg

* Add a test

* Trailing newline argh
2020-06-01 17:07:01 +02:00
Frank Paulo Filho
4bb301dbe2 Make build_all.sh file executable (#14518) 2020-06-01 15:57:16 +02:00
Timothee Cour
0a27cca4b5 runnableExamples: correctly handle multiline string litterals (#14492)
* runnableExamples: correctly handle multiline string litterals

* address comments: improve doc comments + variable namings
2020-06-01 15:56:29 +02:00
Andreas Rumpf
0db148163b fixes --warningAsError implementation (#14538) 2020-06-01 15:41:14 +02:00
Danil Yarantsev
00ec43305e Fix compiles for nimsuggest [backport] (#14527)
* Handle nimsuggest in tryExpr
* Added test
2020-06-01 15:06:45 +02:00
Khronos
5900d8442c Fix a problem with extra build commands. (#14528)
When --compileOnly is on, extraCmds are not added to JsonBuildInstructions.

```
$ echo 'echo 123'>test.nim
$ nim c --debuginfo --nimcache:cache test
$ ls
cache test test.dSYM test.nim
$ tail -n3 cache/test.json
"extraCmds": ["dsymutil /Users/khronos31/src/tmp/test"],
"stdinInput": false
}
```

```
$ echo 'echo 123'>test.nim
$ nim c --debuginfo --nimcache:cache --compileOnly test
$ nim jsonscript --nimcache:cache test
$ ls
cache test test.nim
$ tail -n3 cache/test.json
"extraCmds": [],
"stdinInput": false
}
```
2020-06-01 14:06:25 +02:00
Ico Doornekamp
0489e76da7 manual: removed subjective phrase from 'macros' section (#14536)
Removed phrase "However, this is no real restriction because
Nim's syntax is flexible enough anyway." from the manual - I find it
very subjective, and I sometimes *do* find myself restricted by Nim's
syntax when writing DSLs
2020-06-01 14:02:17 +02:00
Andreas Rumpf
8710395a0f fixes #14514 [backport:1.2] (#14533) 2020-06-01 12:33:13 +02:00
Danil Yarantsev
5d0cf883c1 Disable unused warnings for error await template too (#14531) 2020-06-01 11:56:07 +02:00
Timothee Cour
004b0759c5 fix CI doc windows: style error in lib/std/time_t.nim (#14523) 2020-05-31 14:57:16 -07:00
Danil Yarantsev
5150186c68 Disable unused warnings for await in async macro (#14517)
* Disable unused warnings for await in async macro

* Remove used for the error template
2020-05-31 12:43:27 +02:00
Araq
177c7f96e9 spec: be explicit that NRVO will evolve further 2020-05-30 19:55:01 +02:00
Araq
984af3d64e document NVRO and exception handling 2020-05-30 19:50:11 +02:00
Andreas Rumpf
52c3633223 warn about observerable stores but don't prevent them for 1.2.2 [backport:1.2]; refs https://github.com/nim-lang/RFCs/issues/230 (#14510) 2020-05-30 19:38:51 +02:00
Andreas Rumpf
7ccc7d7e93 fixes #14498 [backport:1.2] (#14503) 2020-05-30 15:32:31 +02:00
Andreas Rumpf
3105909f88 fixes #14495 [backport:1.2] (#14496) 2020-05-29 23:35:57 +02:00
Timothee Cour
cb6eb5268f enable compiler docs with their own index+search (#14493)
* enable compiler docs (with its own index)
2020-05-29 22:11:41 +02:00
Timothee Cour
63d1a0289e fix #14421 items uses lent T (#14447)
* fix #14421 items uses lent T for seq + openArray
* add -d:nimWorkaround14447
* fix test
2020-05-29 17:10:59 +02:00
Timothee Cour
e646c16e06 hotfix doc comments for procs without body (#14494) 2020-05-29 05:30:36 -07:00
Andreas Rumpf
e31ac81899 more checking for --gc:arc, no need for valgrind (#14467)
* sigmatch: removed dead code
2020-05-29 12:08:17 +02:00
Neelesh Chandola
4c08e64e98 disallow typedesc in arrays & move existing checks to types.typeAllowedAux (#13261)
* disallow typedesc in arrays and move previous checks to types.typeAllowedAux
2020-05-29 11:48:15 +02:00
Timothee Cour
579456d520 fix #14485 (#14487) 2020-05-28 19:00:36 -07:00
Timothee Cour
e013ebc91a fix #8871 runnableExamples now preserves source code comments, litterals, and all formatting; other bug fix (#14439)
* fix #8871 runnableExamples now preserves source code comments, litterals, and all formatting
* remove orig deadcode from getAllRunnableExamplesImpl
* fix expected examples
* add test to close https://github.com/nim-lang/Nim/issues/14473
* correctly handle regular comments before 1st token inside runnableExamples
* add test to answer https://github.com/nim-lang/Nim/pull/14439#discussion_r431829199
* update tests
2020-05-28 20:46:06 +02:00
Timothee Cour
17d08ff71c close #14284 document semantics for start for re,nre; improve examples (#14483) 2020-05-28 20:43:36 +02:00
Timothee Cour
fe7a2d60f9 make it easier to figure out how to debug issues (#14477) 2020-05-28 01:19:12 -07:00
Kaushal Modi
e62ccaa4dc Propagate the outDir to rstgen to fix hrefs for modules in subdirs (#14479) 2020-05-28 00:13:24 -07:00
Andreas Rumpf
1fc40db984 drnim improvements (#14471) 2020-05-27 18:14:24 +02:00
Huy Doan
00fa7a5747 Add thiscall calling convention, mostly for hooking purpose (#14466)
* Add thiscall calling convention, mostly for hooking purpose
* add changelog and documentation
2020-05-27 16:24:47 +02:00
Ivan Bobev
cc65ae6011 Change UnpackError with UnpackDefect (#14457)
* Change `UnpackError` with `UnpackDefect`

The deprecation warning for `UnpackError` exception raised by some
`inline` procedures in the Nim standard library propagates to the user
code. If the user code has a requirement for building without warnings
this is a problem for the successful execution of the tests. In order
to resolve this, all occurrences of `UnpackError` in the Nim code base
are changed to `UnpackDefect`. Only the type alias is retained to not
break other people's user code since `UnpackError` is exported type.

* Remove the catching of `UnpackDefect`

Defect exceptions should not be cached, because they indicate problem in
the API usage. The code in `nimblesocket.nim` is rewritten to first
check whether there is a value set into the `knownDomain` variable from
the `Option` type before usage.
2020-05-27 08:34:13 +02:00
alaviss
0533c43547 Revert "niminst: use threaded compression when supported (#14455)" (#14462)
This reverts commit b749d58ea1.
2020-05-27 08:33:24 +02:00
Andreas Rumpf
dadc97d91e typo 2020-05-26 14:49:44 +02:00
alaviss
b749d58ea1 niminst: use threaded compression when supported (#14455) 2020-05-26 14:05:51 +02:00
Timothee Cour
38cb277653 docgen: mangling using _. instead of @@ to avoid issue (#14454) 2020-05-26 10:08:35 +02:00
Bung
2a4a43b05f add bindParams to db_sqlite (#14408)
* add bindParams to db_sqlite
* no need typeinfo
* remove extro spaces
* reduce bindParams to two branches,raise DbError
* Update lib/impure/db_sqlite.nim
* change bindParams to macro,accept varargs[untyped] as params
* change bind blob val to openArray[byte]
* remove unused err type
* explicitly using i32 param
* using import std/private/since
* SQLITE_OK to right hand

* bindParam val int using bindParam overload
* copy data by default
* change exec to template
* remove SqlPrepared procs unused varargs
* fix setupquery for prepared,reset first for exec prepared,add bindNull for literal nil

Co-authored-by: alaviss <leorize+oss@disroot.org>
2020-05-26 07:44:47 +02:00
Timothee Cour
55758920f4 docgen: fix #14448 show @@ as .. in href text (#14451) 2020-05-25 18:16:00 -07:00
Timothee Cour
acadda8da2 tnimblepathdollarfail.nim -> tests/nimble/tnimblepathdollar_fault to reduce false positives when searching for fail in CI logs (#14450) 2020-05-25 13:54:30 -07:00
Timothee Cour
f96555bd10 fix #9227 procs can now have multiple interleaved doc comments + runnableExamples and be docgen'd correctly (#14441)
* fix #9227 proc doc comments after 1st runnableExamples are not ignored anymore
2020-05-25 15:44:23 +02:00
cooldome
6635874a85 make get for options use lent T (#14442)
Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-05-25 15:31:02 +02:00
Timothee Cour
58282547f6 fix #6583, fix #14376, index+search now generated for all projects, many bug fixes with nim doc (#14324)
* refs #6583 fix nim doc output
* changelog
* change default for outDir when unspecified
* cleanups
* --project implies --index
2020-05-25 13:25:40 +02:00
Max Grender-Jones
cbfe9325c5 Add support for mktemps (#14347) 2020-05-25 12:18:35 +02:00
Andreas Rumpf
79e85cb0b5 manual.rst: updates [backport] (#14445) 2020-05-25 12:16:32 +02:00
Timothee Cour
a008f591e2 add test for define, undef (#14443) 2020-05-25 11:17:25 +02:00
treeform
acae3b02c7 Add clipPath to dom.nim. (#14435)
Just adds a single new css atribute, see: https://developer.mozilla.org/en-US/docs/Web/CSS/clip-path .
2020-05-24 07:32:24 +02:00
hlaaftana
f70d01a7d5 fix repr(char) example assert (#14437) 2020-05-23 21:26:49 -07:00
genotrance
b012205b2e Fix #14057 - moveFile should overwrite on Windows (#14433) 2020-05-23 17:06:04 +01:00
Andreas Rumpf
c61f746629 avoid unsafe Nim features in preparation for --gc:arc (#14431) 2020-05-22 20:24:37 +02:00
Bung
6668b43409 add insert,tryInsert unify for postgres that need pk name (#14416)
* add insert,tryInsert unify for postgres that need pk name
* add ReadDbEffect to new procs
* add .since and changelog
* change since to 1.3
* Update lib/impure/db_postgres.nim

Co-authored-by: bung87 <crc32@qq.com>
Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
Co-authored-by: alaviss <leorize+oss@disroot.org>
2020-05-22 19:24:52 +02:00
Mildred Ki'Lya
7b3dcfde20 Add missing attributes and methods to JavaScript DOM (#14428)
- content attribute to access HTML template element:
  https://developer.mozilla.org/en-US/docs/Web/API/HTMLTemplateElement/content

- ownerDocument to access the owning document from a DOM Node:
  https://developer.mozilla.org/en-US/docs/Web/API/Node/ownerDocument

- outerHTML to get/set the outer HTML representation of a Node:
  https://developer.mozilla.org/en-US/docs/Web/API/Node/ownerDocument

- createComment() to create comment Nodes:
  https://developer.mozilla.org/en-US/docs/Web/API/Document/createComment

- querySelector() and querySelectorAll() on Nodes:
  https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelector
  https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll
2020-05-22 14:34:20 +02:00
Timothee Cour
0d0ea3a11e no more code duplication bw liMessage and rawMessage + several bug fixes (#14415)
* no more code duplication bw rawMessage and liMessage; fixes some bugs in rawMessage
* all compiler messages work with hint:msgorigin
2020-05-22 12:02:10 +02:00
Andreas Rumpf
f7b73e6bfd make malloc.nim consistent in style (#14427) 2020-05-22 09:55:10 +02:00
Timothee Cour
149251cab9 [cleanup] fix UnusedImport sempass2 compiler/semparallel.nim (#14426) 2020-05-21 23:28:47 -07:00
Andreas Rumpf
3eaa870c0a ARC/ORC: optimize s.setLen(0) to match the old runtime's behaviour (#14423) 2020-05-21 22:38:13 +02:00
Andreas Rumpf
ddee8a362a change the [Processing] messages into dots (#14418)
* change the [Processing] messages into dots

* better implementation

* maybe I should work on something else...
2020-05-21 22:36:34 +02:00
Andreas Rumpf
063229a301 fixes a bug reported in https://forum.nim-lang.org/t/6361 (#14422) 2020-05-21 22:18:58 +02:00
Mamy Ratsimbazafy
f71f8b0239 The whole options module should be inline (#14417) [backport:1.2]
* The whole options module should be inline

* Use inline per proc and tag `lent` where appropriate

* Remove lent annotation (failing at compiletime)
2020-05-21 17:52:40 +02:00
Timothee Cour
5caaa4bf6f fix #14404 foldr had the classic multiple evaluation bug (#14413) 2020-05-21 11:01:43 +02:00
Timothee Cour
e600ddc555 fix comment from e909486e5c (r39287564) (#14412) 2020-05-20 18:34:14 -07:00
Clyybber
6969a468ce Remove #PRTEMP leftover comment 2020-05-20 13:04:52 +02:00
Clyybber
7fe4c66f35 Small improvements for string and char repr with gc:arc (#14400)
* Small improvements for string and char repr with gc:arc

* Fix test
2020-05-20 12:54:04 +02:00
Timothee Cour
3d20f14193 fix #10731 ; runnableExamples "-b:cpp --run:off": code works (#14384)
* runnableExamples "-b:cpp -r:off": code
2020-05-20 09:45:34 +02:00
alaviss
4ae341353d asyncdispatch, asyncnet: add inheritance control (#14362)
* asyncdispatch, asyncnet: add inheritance control

* asyncnet, asyncdispatch: cleanup
2020-05-20 09:42:55 +02:00
Danil Yarantsev
1450924b1e Fix some typos in the manual [backport] (#14399) 2020-05-20 09:28:47 +02:00
Andreas Rumpf
16003bffe1 fixes #14126 [backport:1.2] (#14390)
* fixes #14126 [backport:1.2]

* used more logic to optimize it further; updated Nimble version
2020-05-20 00:41:57 +02:00
Andreas Rumpf
b35d370d88 specialize genericReset (#14398)
* progress
* make tests green
* maybe we also want to reset pointers, dunno
* progress
* cleanup; fixes #13879 [backport:1.2]
2020-05-19 21:42:53 +02:00
Timothee Cour
e909486e5c trunner was not actually being tested in non-CTFFI mode; minor testament cleanups (#14377)
* use check
* trunner now works with cpp
* cleanup: move compiler/unittest_light => stdtest/unittest_light
* fix tests/readme.md
* remove deadcode references to rodfiles
* fix for windows
2020-05-19 09:41:31 +02:00
Ștefan Talpalaru
27741d6a5c fix #14364 (#14372) [backport:1.2]
Turn on the TLS emulation when using Boehm, since it doesn't scan the
real TLS.
2020-05-18 23:44:04 +02:00
Clyybber
ac65986aae Fix #14394 (#14395) 2020-05-18 17:43:06 +01:00
Timothee Cour
2627e1e945 refs #14369 improve docs for importcpp exceptions (#14391)
* refs #14369 improve docs for importcpp exceptions

* address comments
2020-05-18 17:10:30 +01:00
cooldome
810039ec0b docs:getCurrentException() and getCurrentExceptionMsg() are not available for imported exceptions (#14392) 2020-05-18 08:15:10 -07:00
Timothee Cour
5beed56d0a fix #14174 do not collapse pragma inside runnableExamples (#14385) 2020-05-18 11:03:34 +02:00
cooldome
bc42e9aa98 fix #14369 (#14386)
* fix #14369

* empty commit
2020-05-18 09:38:36 +02:00
Timothee Cour
b11ff518fa fix #12293 findNimStdLibCompileTime should not break with nimble install compiler (#14334)
* fix #12293 findNimStdLibCompileTime should not break with nimble install compiler

* address comment to unblock PR
2020-05-18 09:38:12 +02:00
Miran
69cc1ddc4d install gtk3 on osx for package testing (#14388) 2020-05-18 09:03:01 +02:00
Timothee Cour
51578be296 close #12746; minor cleanup (#14379) 2020-05-17 13:28:18 +02:00
Frank Schmitt
42e80829c7 docs: fix syntax error in hotCodeReloading example (fixes #14380) (#14381)
Co-authored-by: Frank Schmitt <frankschmitt@gmx.de>
2020-05-17 12:44:36 +02:00
John
40ac19572a add OpenBSD MAP_STACK for coroutines (#14353) 2020-05-16 21:56:52 +02:00
Andreas Rumpf
7f377da1d2 fixes #14370 (#14371) 2020-05-16 17:03:25 +02:00
Dominik Picheta
7361e2627b Emscripten: disable epoll (#14361)
Epoll is not supported by epoll.
2020-05-16 15:50:41 +02:00
Bung
390ff428f0 add SqlPrepared api fix #13559 (#14365)
Co-authored-by: bung87 <crc32@qq.com>
2020-05-16 15:50:04 +02:00
Timothee Cour
c777f2fb60 fix some issues with --backend (#14363)
* fix some issues with --backend
* fix https://github.com/timotheecour/Nim/issues/175; improve upon #14306
2020-05-16 13:09:18 +02:00
Bung
c32e1378eb docfix: fix wrong link in doc/manual.rst (#14367) 2020-05-16 03:04:39 -07:00
Kaushal Modi
bf0e1c696f Remove the uses of {.procvar.} pragma (#14359)
This pragma did nothing.

Ref:
- https://github.com/nim-lang/Nim/issues/2172#issuecomment-383276469
- https://github.com/nim-lang/Nim/issues/12975
2020-05-15 23:37:24 +02:00
Bung
ce0552c100 fix #9771 (#14357)
* fix #9771
* map SQLLEN SQLULEN
* fix proc params take TSqlLen

Co-authored-by: bung87 <crc32@qq.com>
2020-05-15 21:00:06 +02:00
Clyybber
9f78f116b2 New "ping-pong" DFA (#14322)
* New ping-pong analysis

* Add testcase for #13456

* Remove debugging leftover

* Unquote "unstructured controlflow"

* Fix typo

* Fix exponential complexity in edge cases

* Add sanity testcase

* Fix
2020-05-15 19:24:43 +01:00
PMunch
13cfaf5fd5 Improve nimeval, changes some defaults (#14351)
* Improve nimeval, changes some defaults

This improves nimeval to make it easier to use NimScript as an embedded
scripting languages. It does change some of the defaults, so in case
anything used the old version and depended on the old behaviour these
would have to be changed.

* Remove dependency on nimhcr for nimscript
2020-05-15 19:32:52 +02:00
Danil Yarantsev
105079e88a Speed up testing of some packages (#14358) 2020-05-15 16:26:03 +02:00
hlaaftana
80c360fceb fix #14350, cstrings in JS init as null (#14355)
* fix #14350, cstrings in JS init as null
2020-05-15 10:07:30 +02:00
Araq
278b4582f5 fixes #14340 2020-05-14 08:51:47 +02:00
Kaushal Modi
a2a3fa1039 Fail quickly if re or nre module is attempted to be compiled with js [backport] (#14341)
Fixes https://github.com/nim-lang/Nim/issues/14338 .
2020-05-14 07:27:57 +02:00
cooldome
5fb40af57e fix #14333 (#14336)
Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-05-13 23:57:05 +02:00
Andreas Rumpf
82870e0737 fixes #13998 [backport:1.2] 2020-05-13 23:56:40 +02:00
Araq
8a339d1178 fixes #13862 2020-05-13 23:56:40 +02:00
Andreas Rumpf
f3e17e7c77 fixes #13104 [backport] 2020-05-13 22:29:02 +02:00
Andreas Rumpf
79fe87500f fixes #13935 2020-05-13 22:17:38 +02:00
Timothee Cour
3573a4f9c1 no more guessing where compiler msgs came from (#14317) 2020-05-13 17:19:44 +02:00
Araq
a3719df8b3 fixes #14331 2020-05-13 14:29:53 +02:00
Timothee Cour
041ee92bba osproc.execCmdEx now takes an optional input for stdin, env, workingDir (#14211)
* `osproc.execCmdEx` now takes an optional `input` for stdin

* execCmdEx now also takes an optional ``workingDir` and `env`
2020-05-13 13:45:36 +02:00
Timothee Cour
1648f1dd99 fix #14320 (tasyncawait.nim is recently very flaky) + avoid hardcoding service ports everywhere + flakyAssert (#14327)
* hotfix #14320 tasyncawait.nim is recently very flaky
* fix #14327
* add flakyAssert
2020-05-13 11:05:47 +02:00
PMunch
9acbf99efb Allow let to not have value when using importc (#14258)
* Allow let to not have value when using importc

This allows a let statement with the `{.importc.}` pragma to not be
initialised with a value. This allows us to declare C constants as Nim
lets without putting the value in the Nim code (which can lead to
errors, and requires us to go looking for the value). Fixes #14253

* Proper fix and documentation + changelog entry

* Improve testcase with one from timotheecour

* Add test to verify it working with macros
2020-05-12 20:28:18 +02:00
Araq
82f008158c cycle collector: make it threadsafe 2020-05-12 20:13:06 +02:00
b3liever
09ea8f9cf8 fix detecting closure env for nested asts (#14326)
Co-authored-by: b3liever <b3liever@yandex.com>
2020-05-12 20:09:56 +02:00
Timothee Cour
dddfbcf211 close #13071 by adding test: nim cpp -r --gc:arc` segfaults on caught AssertionError (#14323) 2020-05-12 19:19:31 +02:00
Timothee Cour
de74362213 fix #14314 do not analyze importc procs for effects (#14319) 2020-05-12 16:19:03 +02:00
Andreas Rumpf
06dfd31612 fixes #13881
* fixes #13881
* documented changed requirements for system.onThreadDestruction
* destructors.rst: update the documentation
2020-05-12 15:46:24 +02:00
cooldome
4277ab470a fix one motr dicriminator bug 2020-05-12 12:45:34 +01:00
cooldome
dfae796ac3 fix test 2020-05-12 11:45:14 +01:00
cooldome
2d7ccf0928 fix #14312 2020-05-12 10:23:05 +01:00
Avahe Kellenberger
55446c05a4 Added a reference to ternary operators. (#14309)
`if expressions` are similar to ternary operators in other languages.
In order to make this easier to find in the manual, I've added a
sentence about it.
2020-05-12 08:28:10 +02:00
Timothee Cour
b8ec07f19e properly fixes #13758 so that import std/macros stays legal (#14291)
* properly fix https://github.com/nim-lang/Nim/issues/12389
* use --lib:lib in koch.nim.cfg instead
* third time is the charm
2020-05-12 08:27:47 +02:00
cooldome
a39123c93c fix #14219 (#14225)
Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-05-11 23:11:20 +02:00
Kaushal Modi
86669ef5b4 Make --backend:cpp|js work for :test: code-blocks as well (#14306)
Continues 9502e39b63

Ref:
- 9502e39b63 (commitcomment-39087584)
- https://github.com/nim-lang/Nim/pull/14278

Fixes https://github.com/nim-lang/Nim/issues/13129 .
2020-05-11 20:45:35 +02:00
slangmgh
76f7e95814 Fix #14289 (#14304) [backport] 2020-05-11 19:17:37 +02:00
Andreas Rumpf
0f344a70c9 fixes #13946 (#14302) 2020-05-11 19:12:40 +02:00
b3liever
a081b10b54 small refactoring (#14303)
Co-authored-by: Antonis <b3liever@yandex.com>
2020-05-11 19:12:25 +02:00
cooldome
fee71d466c fix #14294 (#14301)
* fix #14294

* fix orc as well

Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-05-11 19:10:54 +02:00
Andreas Rumpf
03c146cd93 do not track 'raise Defect' in the .raises: [] clause anymore (#14298)
* do not track 'raise Defect' in the .raises: [] clause anymore

* --panics:on maps 'raise Defect' to an unrecoverable fatal error

* make tests green again

* update the documentation too
2020-05-11 16:25:56 +02:00
Antonis
517dd800f8 better error message 2020-05-11 15:39:44 +02:00
Antonis
3616b0698b fix closure env check 2020-05-11 15:39:44 +02:00
Antonis
73c9d2c9d7 Fix for --styleCheck:error 2020-05-11 15:39:44 +02:00
Jovial Joe Jayarson
14f76f721d refactor: renamed readme to readme.md (#14283) 2020-05-11 13:50:40 +02:00
Timothee Cour
9502e39b63 nim doc --backend:js, nim doc --doccmd:-d:foo, nim r --backend:js, --doccmd:skip + other improvements (#14278)
* `nim doc --backend:js|cpp...`
`nim doc --doccmd:'-d:foo --threads:on'`
`nim r --backend:cpp...` (implies --run --usenimcache)
* --usenimcache works with all targets
* --docCmd:skip now skips compiling snippets; 50X speedup for doc/manual.rst
2020-05-11 12:01:18 +02:00
Timothee Cour
d11cb9d495 fix a critical bug in windows.osproc leading to resource leaks and blocking IO [backport] (#14296) 2020-05-11 11:14:21 +02:00
Andy Davidoff
8018449319 simple typo in locks.nim (#14297) 2020-05-11 02:59:31 -04:00
Timothee Cour
7c24250a57 diable nimx (CI failure) refs https://github.com/timotheecour/Nim/issues/167 (#14293) 2020-05-10 18:56:00 -04:00
Timothee Cour
dda6f3f6d4 nim doc -r main and nim rst2html -r main now call openDefaultBrowser (#14285) 2020-05-10 09:23:01 +02:00
Clyybber
8e93105606 Fix #14269 (#14286) 2020-05-09 18:22:25 +02:00
Timothee Cour
411be506a3 --hint:processing (+friends) is now supported and means --hint:processing:on, like all other bool flags (#14271) 2020-05-08 18:54:16 +02:00
Andreas Rumpf
ce16115e79 Merge pull request #14265 from alaviss/quickfix
nativesockets: add missing inheritable pass-through
2020-05-08 17:33:38 +02:00
Andreas Rumpf
bae8e95b73 fix root cause of https://github.com/dom96/choosenim/issues/193; config/config.nims should get installed (#14267) 2020-05-08 16:14:10 +02:00
Clyybber
4bd77cf045 Fix typo 2020-05-08 16:13:53 +02:00
Timothee Cour
363b7ff3b8 fix https://github.com/nim-lang/Nim/issues/14275 querySetting(nimcacheDir) works even if implicitly set (#14277) 2020-05-08 16:13:07 +02:00
Clyybber
120ea906fb Fix #14270 and add testcases (#14276) 2020-05-08 15:54:34 +02:00
hlaaftana
de27910ab7 make from an operator (#14241) 2020-05-08 07:54:46 +02:00
Timothee Cour
ee15437aed fix root cause of https://github.com/dom96/choosenim/issues/193; config/config.nims should get installed 2020-05-07 15:01:46 -07:00
cooldome
5fa7d374c4 fix #14243 (#14257)
* fix #14243

Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-05-07 22:15:25 +02:00
alaviss
83435fe696 tslow_tables: wait for an additional 2 seconds (#14266)
This test runtime tends to hover around the 5s mark depending on how
loaded the system currently is. This causes the test to fail a lot
during CI, per analytics:
https://dev.azure.com/nim-lang/Nim/_test/analytics?definitionId=1&contextType=build

Give the test an extra 2 seconds to account for unrelated overhead.
2020-05-07 22:07:08 +02:00
Leorize
73a42ce941 nativesockets: add missing inheritable pass-through 2020-05-07 14:43:53 -05:00
Clyybber
42db75c970 Fix the DFA for "unstructured controlflow" (#14263)
* Fix the DFA for "unstructured controlflow"

* Add testcase from #14233
2020-05-07 21:41:55 +02:00
alaviss
1a1e9986a3 net: remove more erroneous set constructions (#14252) [backport]
Refs #13764
2020-05-07 13:37:54 +02:00
Miran
5a9b3c27c1 Split testing important packages into two jobs (#14256)
* split testing packages in two separate jobs
* speed-up the slowest tests
* special treatment for two packages
2020-05-07 10:08:05 +02:00
cooldome
0d8507cd3d fix #14236 (#14250)
Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-05-07 00:13:59 +02:00
cooldome
6dba06f9e6 fixes #14244 (#14248)
Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-05-06 20:43:18 +02:00
awr1
b70b8a7cdd Fix runnable examples for bitops (#14247) 2020-05-06 19:29:36 +02:00
Andreas Rumpf
c64db68f0b added a new feature: --cc:env so that you can use any C compiler as long as it works like GCC 2020-05-06 18:41:24 +02:00
Andreas Rumpf
1b2b32169a cleanup the CC setting, only leave in there what is at least semi-officially supported 2020-05-06 18:41:24 +02:00
Timothee Cour
330b3c4453 fix regression: -d:nimHasLibFFI was not being tested anymore (#14234)
* * fix regression: -d:nimHasLibFFI was not being tested anymore,
in part because testament was silently treating some errors as easy to overlook messages
* turned that message into an error
* -d:nimHasLibFFI is now being tested with nim cpp
* use correct signatures for importc procs
* workaround for openbsd to unblock ctffi testing
2020-05-06 17:16:54 +02:00
awr1
b8e6ea7547 Added bitslice operations for bitops (#14016)
* added bit operations based on bit slices, clarified documentation, made non-mutating versions of mask ops
* Added since annotations, some runnable examples
* Added mask()/masked() functions, changed internal workings of mask ops to use new bit* funcs
* Changelog updated for new bitops improvements
* Reorganization, added runnable examples
* Documentation adjustments
* Add incltrl for since annotation
* Fix masked() impl
* Fix mask() return type
* Don't call toUnsigned on already unsigned types
* Remove improper `var T` for flipMasked()
* Fix return types for flipMasked()
* Slight syntactic cleanup for *masked ops
* Added tests for bitslice operations, new mask() operation, non-mutating mask ops
* Fix setmasked() var T issue
* More comprehensive tests
* Fix runnable example for bitsliced()
* Fix runnable example for mask()
2020-05-06 12:21:49 +02:00
Oscar Nihlgård
48e7775ad1 Make the fields of times.DateTime private (#14197)
* Make the fields of `times.DateTime` private

* PR fixes
2020-05-06 12:20:34 +02:00
Timothee Cour
c28a057a6b fix js stacktraces, unify all file,line,col formatting into a single function (#14230)
* fix https://github.com/timotheecour/Nim/issues/135 ; unify all file,line,col formatting into a single function
2020-05-05 14:56:15 +02:00
hlaaftana
6b7b5fb4fa Clarify JS cstring len (#14184) 2020-05-05 10:34:37 +02:00
cooldome
eefada8a88 fix #14217 (#14218)
* fix #14217

Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-05-05 07:26:32 +02:00
Andreas Rumpf
64e839d5fd fixes #14209 [backport:1.2] (#14213)
* fixes #14209 [backport:1.2]
* improve stability
2020-05-05 00:48:13 +02:00
cooldome
e86a6d24d5 vcc fix (#14222)
Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-05-04 19:42:29 +02:00
wltsmrz
c817e85f4c Linux updates (#14170)
* Add posix_memalign()

* Add linux-specific open() flags

O_TMPFILE: since Linux 3.11
O_PATH: since Linux 2.6.39
O_NOATIME: since Linux 2.6.8
O_DIRECT: since Linux 2.4.10

* Fix Stat type

* Fix POSIX AF_INET* const generation
2020-05-04 19:23:49 +02:00
PMunch
44f377ff5e Add procedures to read RSA keys from BIO format (#14223) 2020-05-04 19:23:11 +02:00
Timothee Cour
a23302ef56 fix https://github.com/timotheecour/Nim/issues/152: avoid writing spurious ^[[0m to stderr when callStyledWriteLineStderr not called (#14214)
* fix https://github.com/timotheecour/Nim/issues/152 `^[[0m` is inserted in stderr for `echo code | nim c -`

* resetAttributes not even needed, already handled in styledWriteLine

* simplify tests in tests/trunner.nim thanks to this fix
2020-05-04 15:07:32 +02:00
Tristram Oaten
927737975c Re-enabling INim (#14215) 2020-05-04 15:07:04 +02:00
rockcavera
603010f8c9 Fixes net.recvFrom to work correctly with IPv6 (#14131)
* added high level sendTo and recvFrom to std/asyncnet; tests were also added.
* add .since annotation, a changelog entry and fixed to standard library style guide.
* fixes net.recvFrom to work correctly with IPv6
* raise if domain is not AF_INET or AF_INET6
* renamed template to adaptRecvFromToDomain()
2020-05-04 11:54:08 +02:00
Timothee Cour
f115e40e6a echo cmd | nim r - -arg1 -arg2 now works (#14210) 2020-05-04 11:27:59 +02:00
Andreas Rumpf
a73d403901 sequtils refactoring: prefer typeof over type (#14212) 2020-05-04 11:18:29 +02:00
Andreas Rumpf
b6fb609e0d destructors: don't produce stupid code for 'cast' (#14208) [backport:1.2]
* destructors: don't produce stupid code for 'cast'

* fixes #14207
2020-05-04 07:43:22 +02:00
hlaaftana
3e060cfb0a => supports pragmas & names (+ changed behavior) (#14200)
* => supports pragmas & names (+ changed behavior)

(x, y: int) is now parsed as (x: int, y: int) instead of
(x: auto, y: int) inside => and ->.

* fix pragma check

* fixes, use since & LHS of -> supports pragmas
2020-05-03 10:22:49 +02:00
slangmgh
b56432bd8a fix #14203 (#14204) 2020-05-03 09:50:08 +02:00
slangmgh
d5c014e59b Fix #14151 (#14205) [backport] 2020-05-03 09:47:21 +02:00
slangmgh
b447ff7860 Fix #14201 (#14202) 2020-05-03 09:46:42 +02:00
Andreas Rumpf
49b28f1997 fixes #14136 (#14198) 2020-05-03 00:12:52 +02:00
hlaaftana
fbc97e712a move since from inclrtl to std/private/since (#14188)
* move since from inclrtl to std/private/since
* move since import in system below for HCR
2020-05-02 23:51:59 +02:00
Dien Tran
3be669be32 Move generated tex file to doc to correct location (#14191) 2020-05-02 23:49:08 +02:00
Araq
ff1c0bae4c update tests that tested for the 'discard' error messages 2020-05-02 22:31:19 +02:00
Araq
7f1d2489ad improve the 'has to be discarded' error message 2020-05-02 22:31:19 +02:00
Araq
87ac28d19a fixes #14159 [backport:1.2] 2020-05-02 22:31:19 +02:00
Araq
4301a7bdf0 fixes #14177 2020-05-02 22:31:19 +02:00
Araq
7bac6f5f9a don't close #14142 2020-05-02 22:31:19 +02:00
Araq
8e04ef3c0f closes #14142 2020-05-02 22:31:19 +02:00
Araq
15f54728ef fixes a bug encountered when running 'nim check posix_haiku.nim' 2020-05-02 22:31:19 +02:00
hlaaftana
f50377986a exp. features now in correct manual, closes #11932 (#14195) 2020-05-02 22:30:08 +02:00
Kaushal Modi
0880f118d3 Document that proc named fooTask is created for every foo task [backport] (#14187)
Ref: https://irclogs.nim-lang.org/01-05-2020.html#15:18:03
2020-05-02 17:50:27 +02:00
Clyybber
83547ec769 Make unreachable else in case statements a warning instead of an error (#14190)
* Fix #14019 by making trailing else a warning

* Rename to UnreachableElse
2020-05-02 16:09:02 +02:00
Clyybber
1f1e4de3bc Make ./koch temp --gc:arc work (#14186) 2020-05-01 20:25:18 +02:00
Miran
9c33bcac5c change 'iff' to 'if' to stop "corrections" once and for all (#14182) 2020-05-01 15:54:03 +02:00
hlaaftana
9b01c6cf48 discardable async procs are now an error (#14176)
* add discard warning in manual
2020-05-01 09:49:13 +02:00
Andreas Rumpf
d5fc35c968 arc: do not unload globals when building a library [backport:1.2] (#14180) 2020-05-01 09:15:46 +02:00
rockcavera
33e9ac7cd3 fix sendTo and recvFrom in asyncnet (#14154)
* added high level sendTo and recvFrom to std/asyncnet; tests were also added.

* add .since annotation, a changelog entry and fixed to standard library style guide.

* Improved asserts msgs and added notes for use with UDP sockets

* pointers removed in parameters and fixes

* added .since annotation

* minor fixes
2020-04-30 22:50:37 +02:00
Araq
6b39b47abc hotfix: make tcompilerapi green again 2020-04-30 22:48:10 +02:00
Andreas Rumpf
89be5be03e fixes #13698 [backport:1.2] (#14175) 2020-04-30 22:45:02 +02:00
Araq
3d2459bdc0 fixes the regression #12860 caused; hotfix 2020-04-30 20:23:53 +02:00
Andreas Rumpf
cf3e0008b9 fixes #13986 [backport:1.2] (#14173) 2020-04-30 19:32:03 +02:00
hlaaftana
0aefebb728 JS unittest stacktrace fix, cleanup js repr and inclrtl includes (#14168) 2020-04-30 17:04:53 +01:00
narimiran
4d799f8820 test even more packages 2020-04-30 13:03:48 +02:00
narimiran
d844d10e8e [ci skip] clean-up CI badges 2020-04-30 10:19:18 +02:00
narimiran
f1068c01a8 [ci skip] prevent fail-fast on packages CI 2020-04-30 10:11:18 +02:00
Andreas Rumpf
cc60caedb3 fixes #14054 [backport:1.2] (#14061)
* fixes #14054

* make tests green again

* more tests are green

* maybe now
2020-04-30 06:48:57 +02:00
Clyybber
d6e1b5c070 Fix #14160 (#14161)
* Fix #14160

* Add testcase
2020-04-30 02:01:07 +02:00
Araq
bd57f0cd32 fixes another silly arc/orc bug [backport:1.2] 2020-04-29 22:14:01 +02:00
Andreas Rumpf
d9e907c0e2 fixes #14079 [backport:1.2] (#14163) 2020-04-29 21:58:59 +02:00
hlaaftana
707367e1ca many bugfixes for js (#14158)
* many bugfixes for js

fixes #12672, fixes #14153, closes #14123, closes #11331, fixes #11783, fixes #13966, fixes #14087, fixes #14117, closes #12256.

mostly fixes the fact that it was allowed to assign to newly created temp variables. additionally attempts to get rid of null initialized seqs/strings (though they might pop up here and there); this simplifies a lot of things and makes code size smaller. even if null seqs/strings pop up here and there it's still better than all those bugs existing.

* formatting fixes

* CI fixes

* more CI fixes
2020-04-29 20:55:09 +02:00
Tristram Oaten
a297c016fa Remove travis ci badge (#14062) 2020-04-29 17:06:14 +02:00
hlaaftana
800ce5b950 Fix negative indexed arrays for JS, refs #13966 (#14152)
* Fix negative arrays for JS, refs #13966

* small extra fix: no need to .slice() cstring in JS
2020-04-29 08:59:08 +02:00
cooldome
3b5a504692 parseEnum_regression (#14150)
Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-04-28 19:56:50 +02:00
Jacek Sieka
7d6cbf290a Error -> Defect for defects (#13908)
* Error -> Defect for defects

The distinction between Error and Defect is subjective,
context-dependent and somewhat arbitrary, so when looking at an
exception, it's hard to guess what it is - this happens often when
looking at a `raises` list _without_ opening the corresponding
definition and digging through layers of inheritance.

With the help of a little consistency in naming, it's at least possible
to start disentangling the two error types and the standard lib can set
a good example here.
2020-04-28 19:56:01 +02:00
hlaaftana
cd9af6b804 StringStream & more stdlib modules support for JS/NimScript (#14095)
* StringStream & more stdlib modules support for JS/NimScript

* change back pegs test in line with #14134
2020-04-28 19:44:52 +02:00
narimiran
d5ed4fba3e test packages with Github workflows 2020-04-28 18:14:34 +02:00
cooldome
289d48e5fe bug fix (#14149) [backport:1.2]
Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-04-28 18:02:14 +02:00
narimiran
e63fc95bd4 fix tdistros test which was failing on Nightlies 2020-04-28 15:59:32 +02:00
hlaaftana
82fc66b607 Update grammar.txt with func and as (#14147) [backport] 2020-04-28 10:57:35 +02:00
Miran
e1dab59d46 add 14 more packages to 'important_packages' (#14141) 2020-04-28 07:28:48 +02:00
Andreas Rumpf
065a6af2de fixes a critical =trace generation bug (see test case) (#14140) 2020-04-27 22:20:14 +02:00
PMunch
2f1aad0264 Add RSA key reading and encrypt/decrypt to openssl (#14137)
This adds the procedures to read RSA keys and encrypt/decrypt messages
with both public and private keys.
2020-04-27 21:01:56 +02:00
Neelesh Chandola
d38853c504 Undefine paramCount & paramStr in nimscript.nim for *.nims (#12860)
* Remove `paramStr` and `paramCount` from implicitly imported nimscript.nim
* Update changelog.md
* Update stable nimble commit hash

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2020-04-27 19:16:40 +02:00
Timothee Cour
a3a317b76d $ now works for unsigned intergers with nim js (#14122)
* $(unsigned) now works for js
* move NimMajor+friends closer to NimVersion according as per reviewer feedback
2020-04-27 19:15:17 +02:00
PMunch
0e6eb96a5f Fix #14066 issue with stringifying incomplete types (#14135) 2020-04-27 18:43:02 +02:00
Timothee Cour
bb982c644b $(a: float) now works consistently in nim js, avoiding printing floats as ints (#14134)
* fix https://github.com/timotheecour/Nim/issues/133; $(a: float) works in nim js like in other backends

* fix tests

* fix test for windows that prints 1.1e17 differently than other OS
2020-04-27 17:33:03 +02:00
Oscar Nihlgård
664cb2c0be Remove some deprecated procs from std/times (#14129) 2020-04-27 14:42:29 +02:00
Timothee Cour
b8d7a98265 fix #14132 dsymutil should not be called on static libraries (#14133) [backport:1.2] 2020-04-27 12:39:27 +02:00
Andreas Rumpf
dedb04fa9e new implementations for --gc:orc (#14121)
* cycle collector: new implementation
* cycle collector: make self-adaptive based on its previous effectiveness
* cycle collector: added Lins's jump stack to improve traversal from 3*N to 2*N
* cycle collector: make tests green
* API extensions and bugfixes
* code cleanup and use --gc:orc for tasyncawait
2020-04-27 11:57:26 +02:00
cooldome
eaedd0cb94 add FileReader Web API to js dom (#14105)
* add FileReader to js dom
* minor improvement
Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-04-27 00:08:11 +02:00
Timothee Cour
9384f7ad35 since now takes an optional patch, eg: since: (1, 3, 1) (#14124)
add tests for tinclrtl
2020-04-26 14:55:25 +02:00
rockcavera
d23446c6ba added high level sendTo and recvFrom to std/asyncnet (UDP functionality) (#14109)
* added high level sendTo and recvFrom to std/asyncnet; tests were also added.

* add .since annotation, a changelog entry and fixed to standard library style guide.

* Improved asserts msgs and added notes for use with UDP sockets
2020-04-26 10:16:10 +02:00
hlaaftana
76ffa4fa25 fixes #14112, tests for #12892, #12671, #11697 (#14125) 2020-04-26 10:12:16 +02:00
hlaaftana
31ba27590c small docs fix in typetraits (#14108) 2020-04-25 20:35:20 +02:00
Alexander Ivanov
56584414f3 Make await a template (#12085)
* Make await a template
* Generate await inside async/multisync
2020-04-25 20:27:03 +02:00
Christopher Dunn
caf30e7cb5 Faster readStr() (#14099)
* Faster readStr()

* https://github.com/nim-lang/Nim/issues/13857

* Add .since annotation and add to changelog

* Private, un-sinced proc for csource bootstrapping
2020-04-25 20:19:11 +02:00
Viktor Kirilov
018e297d66 HCR: properly handling complex const objects in the codegen - fixes #13915 (#14115) 2020-04-25 20:17:33 +02:00
Jae Yang
362c8964bf Fixes #14110 (#14111)
Fixes jsffi usage example in doc
2020-04-25 20:00:24 +02:00
cooldome
13fa338ada implement (#14114)
Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-04-25 19:59:56 +02:00
Euan
f3eeb3f921 Fix #14088 and #14089 on NetBSD (#14104)
* Set path to libSDL for NetBSD.

* Disable SFML test on NetBSD
2020-04-24 14:30:41 +02:00
Timothee Cour
706de1a566 add CI badges for CI github actions ssl+docs 2020-04-24 11:10:14 +01:00
Timothee Cour
d5b7e9902c fix nim CI; fix local testament (#14102) 2020-04-24 10:24:30 +02:00
Phil Krylov
d5d3594457 Add critbits.commonPrefixLen (#14072)
* Add critbits.commonPrefixLen

* add inline and since annotations, as well as a changelog entry

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2020-04-24 09:31:30 +02:00
hlaaftana
b2141fc2a1 changed type() to typeof() in docs and error messages (#14084) 2020-04-24 09:22:12 +02:00
alaviss
dd5ccc3e5a testament: don't try to test nimgrep if it's not there [backport:1.2] (#14085)
One more compiler source-specific tackled
2020-04-24 09:20:33 +02:00
hlaaftana
dff007f66d Make JS not mangle to snake_case (#14086) 2020-04-24 09:19:54 +02:00
Euan
123f9fb77a Fix #14091 and #14093 - test failures on NetBSD (#14096) 2020-04-24 09:18:44 +02:00
Timothee Cour
f07f07eef9 [ci skip] changelog conflicts are a thing of the past (#14098) 2020-04-24 09:16:20 +02:00
Timothee Cour
b18b1b0302 add CI badges for azure-pipelines for devel, 1.0, 1.2 branches (#14101) 2020-04-24 09:08:27 +02:00
Clyybber
eca8f1d79f Add tests for #8481, #6490 and #4061 (#14083) 2020-04-23 19:52:33 +02:00
Timothee Cour
66db9de714 CT sizeof(+friends) for {.importc, completeStruct.} types, enable ABI static checks (#13926)
* -d:checkabi obsolete (ABI check now enforced); add `addTypeHeader` helper
* cleanups
* import sizeof at CT for {.completeType.}
* address comments; revert default enabling of -d:checkAbi for now
* mimportc_size_check.nim => msizeof5.nim; merge mabi_check.nim into msizeof5.nim; refactor
* all pragmas in errmsgs should be written: '.importc' (un-ambiguous and less verbose than {.importc.})
2020-04-23 11:24:09 +02:00
Timothee Cour
5c534b2943 new cmd: nim r main [args...] to compile & run, saving binary under $nimcache/main (#13382)
* implement `nim r main` to compile and run, saving binary to $nimcache
* remove outFileAbs for now
2020-04-23 10:02:18 +02:00
alaviss
4b43d42b98 testament: don't rely on Nim source structure [backport:1.2] (#14077)
It's also just faster to get the current file name instead of scanning
the PATH.
2020-04-23 09:26:06 +02:00
Euan
0b4a475f2e Ref #14075 - enable two tests which seem to now be passing locally on FreeBSD. (#14076) 2020-04-22 23:35:22 +01:00
Keithcat1
d27bc03b21 Add LTO support for most compilers and do some VCC fixes (#14013)
* Added LTO in nim.cfg, added /link in extccomp.nim and other fixes

* Fix line endings

* Fix line endings, for real this time. Almost certainly. Like, 95% certain.

* Removed /MD from extccom.nim VCC comiler
2020-04-22 23:56:43 +02:00
Hiroki Noda
6cfe2e0c3d Set O_NONBLOCK flag atomically (#13934)
These flags were added in Linux 2.6.27, I'm not sure Nim's minimal
support Linux version.
2020-04-22 20:24:45 +02:00
Bung
e1cc0219de fix #14064 xmltree should allow create text node with raw text(non-es… (#14070)
* fix #14064 xmltree should allow create text node with raw text(non-escaped) eg. html style element's text

* change xnRawText to VerbatimText,newRawText to newVerbatimText ,add since anotation

* change changelog_1_2_0.md latest date

* move change log

Co-authored-by: bung87 <crc32@qq.com>
2020-04-22 19:46:55 +02:00
Chris Heller
6c0c882509 Make debugSend/debugRecv procs public. Fixes #12189 (#12190)
* Make debugSend/debugRecv procs public. Fixes #12189

* Make checkReply proc public. Part of #12189

* Add doc comments for debugSend,debugRecv and checkReply
2020-04-22 17:45:31 +02:00
wonderix
5571d48c32 Add the ability to pass title case headers to an HTTP server (#13968)
* Add the ability to pass title case headers to an HTTP server

* Remove unnecessary type spec of titleCase

* Replace convert member proc by isTitleCase

Co-authored-by: wonderix <wonderix@googlemail.com>
2020-04-22 17:43:39 +02:00
Andreas Rumpf
269a458d74 cycle collector (#14071)
* figured out the wrong cycle trace proc problem
* cycle collector/break refactorings and minor improvements
2020-04-22 17:34:35 +02:00
hlaaftana
01523b2b58 change some Exceptions to CatchableError or Defect, fixes #10288 (#14069) 2020-04-22 16:49:41 +02:00
Miran
5c26a83a4a use newer nodejs on Azure Pipelines (#14065) 2020-04-22 11:38:33 +02:00
Vindaar
d42c5a575d base parseEnum on a case statement, fixes #14030 (#14046)
* base `parseEnum` on a case statement, fixes #14030

* apply simplifactions / clean up, remove `norm` node, use strVal

* export `normalize` in json.nim

* cmp using nimIdentNormalize, error at CT if ambiguous enum found

`nimIdentNormalize` provided by @cooldome.

We track all names of the branches we have created so far and error if
a duplicate is found.

Dummy change to make github react...

* fix docstring of `nimIdentNormalize`

* make `typ` arg `typedesc`, add lineinfo, call norm. only once
2020-04-22 09:41:56 +01:00
Hessam Mehr
c3f4b93060 Treat zig like clang/gcc wrt integer arithmetic. (#13957) 2020-04-22 08:31:24 +02:00
alaviss
22418ce8fb tools/finish: don't quote path with space (#14058) [backport]
Path with spaces should be added as is, quoting them makes utilities
treat the quotes as part of the path. This makes `nim` unable to be used
from the command line even if it appears to be added to user's Path
environment variable.

Even more confusing, Windows 10's PATH editor shows the path without any
quotes, you only see them when you use "Edit text". Took me a good 15
minutes to figure out why couldn't I run `nim` despite it being in Path.
2020-04-22 07:51:18 +02:00
Timothee Cour
eb6f523733 fix globalOptions (#14059) 2020-04-22 07:50:38 +02:00
Arnaud Moura
dc40fb805f Fix OS detection in a docker container (#13172)
* Support detection in docker container.
* Get only ID information in os-release.
* Add test to distros module.
* Fix Linux OS detection in Windows.
* Fix OS detection for FreeBSD and OpenBSD.
2020-04-22 07:49:42 +02:00
Andy Davidoff
9604a5a97a fix typo (#14063) 2020-04-21 23:23:15 -04:00
Timothee Cour
7ce0358351 fix #13222: make relativePath more robust and flexible (#13451)
* * relativePath(foo) now works
* relativePath(rel, abs) and relativePath(abs, rel) now work (fixes #13222)
* relativePath, absolutePath, getCurrentDir now available in more targets (eg: vm, nodejs etc)
* fix bug: isAbsolutePath now works with -d:js; add tests
* workaround https://github.com/nim-lang/Nim/issues/13469
* remove `relativePath(path)` overload for now
* add back changelog after rebase
2020-04-21 23:53:55 +02:00
Araq
dd24004fab cleanup PR #14048 2020-04-21 23:27:19 +02:00
Andreas Rumpf
1b6c4ed2ba fixes #14052 [backport:1.2] (#14055) 2020-04-21 23:19:34 +02:00
hlaaftana
5608a4e57b Add deques.peekFirst/Last(var Deque[T]) -> var T (#13542)
* Add deques.peekFirst/Last(var Deque[T]) -> var T
* Add changelog entry for deques.peekFirst/Last var T overloads
* Add since annotation to peekFirst/peekLast

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2020-04-21 22:09:19 +02:00
Arnaud Moura
cb2b9bd797 Add package install command for FreeBSD and OpenBSD. (#14051) 2020-04-21 22:07:19 +02:00
cooldome
5db0bb744c Replace enum fields idents with syms (#14048)
* replace enum fields idents with syms
* Trigger build

Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-04-21 20:12:32 +02:00
Oscar Nihlgård
218cbf0e09 Times refactorings (#13949) 2020-04-21 17:07:37 +02:00
Euan
7828199827 #12103 - CI for OpenBSD (#12105)
* Working on OpenBSD CI
* Condense steps into 2 steps to make output easier to follow.
* Move up one directory after csources build.
* Remove FreeBSD build manifest and add OpenBSD test ignores for coroutines and hot code reloading.
* If runCI fails, run the test results script.
* Add email trigger for build failure
* Remove .git from repository URL
* Disable SFML test on OpenBSD
* Disable tgetaddrinfo on OpenBSD as only UDP and TCP protocols are supported.
* Remove getFilePermissions as it causes CI test failures with NimScript.
* Set clang as cc in nim.cfg and use gmake to build csources.
* Add getCurrentDir to nimscript.
* Remove duplicate getCurrentDir and check for not weirdTarget.
* Add CI badge for OpenBSD.
* Disable tests which allocate lots of memory for OpenBSD.
* Use `CORO_BACKEND_SETJMP` on OpenBSD rather than ucontext.
* Simplify building of koch
* Disable t8657 on OpenBSD. See issue #13760.
* Fix #12142 - tarray_of_channels fails on OpenBSD
* Disable thhtpclient_ssl and tosprocterminate on OpenBSD. These tests can be enabled at a later date after fixing them.
* Install libffi.
* Set path to libc for openbsd.
* Disable tevalffi for now.
* Remove tevalffi.nim.
* Use ncpuonline sysctl rather than ncpu.
* Disable tacceptcloserace and tasynchttpserver on OpenBSD.
* Enable tacceptcloserace and tasynchttpserver.
* Fix #13775 as suggested by @alaviss - use /bin/cat on OpenBSD rather than /bin/sh.
* Enable test on OpenBSD.
* Disable tflowvar on OpenBSD.
2020-04-21 15:05:21 +02:00
treeform
89e6a7ab48 Fix the getSelection method. (#13632) 2020-04-21 14:57:19 +02:00
Rory O’Kane
b8b0e9b21d docs: move not nil to the experimental page (#14027)
When I heard that this feature existed, and found the 2018 changelog entry that said `not nil` was made experimental (https://github.com/nim-lang/Nim/blob/devel/changelogs/changelog_0_19_0.md#changes-affecting-backwards-compatibility), I looked for `not nil` documentation in https://nim-lang.org/docs/manual_experimental.html. When I didn’t find it there, I initially assumed the feature had no documentation. This change moves the documentation to where readers will expect it.

As well as moving the text to another file, I added instructions for enabling the experimental feature and tweaked some wording.
2020-04-21 14:54:43 +02:00
Judd
04c326569b fix mapIt issues #12625 & #12639 (#14041)
* fix mapIt issues #12625 & #12639:

1. fallback to call `map` when the result of `op` is a closure;
2. use `items(s)` in the for loop.

* fix test errors.

* add comments and InType is moved.

* fix ident.
2020-04-21 14:50:16 +02:00
Tristram Oaten
1a44b7e3ce New runnableExample for newAsyncHttpClient() (#14045) 2020-04-21 14:47:06 +02:00
alaviss
7beed44fc9 asyncdispatch: export Callback (#14042) [backport]
This let us see the definition of `Callback` in docs, which is required
to even make use of asyncdispatch.

Ref #13539.
2020-04-21 11:21:36 +02:00
hlaaftana
3fe3db3c0d clarify tuples and objects in manual, fixes #12486 (#14044) 2020-04-21 11:21:12 +02:00
Tristram Oaten
42a64245f8 Fix broken async httpclient example
As the async httpclient is almost certainly the first async example beginners will want to try, we OWE it to them to give them a real example.

Example repeated here for clarity:

```nim
import asyncdispatch, httpclient

proc asyncProc(): Future[string] {.async.} =
  var client = newAsyncHttpClient()
  return await client.getContent("http://example.com")

echo waitFor asyncProc()
```

This is my first Nim contribution, please let me know if the code is right. (it runs on my machine, but may not be the best example)
2020-04-21 00:00:30 +01:00
Andreas Rumpf
67d71bb76d fixes #14038 2020-04-20 23:44:29 +02:00
alaviss
1bdc30bdb1 Make file descriptors from stdlib non-inheritable by default (#13201)
* io: make file descriptors non-inheritable by default

This prevents file descriptors/handles leakage to child processes
that might cause issues like running out of file descriptors, or potential
security issues like leaking a file descriptor to a restricted file.

While this breaks backward compatibility, I'm rather certain that not
many programs (if any) actually make use of this implementation detail.
A new API `setInheritable` is provided for the few that actually want to
use this functionality.

* io: disable inheritance at file creation time for supported platforms

Some platforms provide extension to fopen-family of functions to allow
for disabling descriptor inheritance atomically during File creation.
This guards against possible leaks when a child process is spawned
before we managed to disable the file descriptor inheritance
(ie. in a multi-threaded program).

* net, nativesockets: make sockets non inheritable by default

With this commit, sockets will no longer leak to child processes when
you don't want it to. Should solves a lot of "address in use" that might
occur when your server has just restarted.

All APIs that create sockets in these modules now expose a `inheritable`
flag that allow users to toggle inheritance for the resulting sockets.
An implementation of `setInheritance()` is also provided for SocketHandle.

While atomically disabling inheritance at creation time is supported on
Windows, it's only implemented by native winsock2, which is too much for
now. This support can be implemented in a future patch.

* posix: add F_DUPFD_CLOEXEC

This command duplicates file descriptor with close-on-exec flag set.

Defined in POSIX.1-2008.

* ioselectors_kqueue: don't leak file descriptors

File descriptors internally used by ioselectors on BSD/OSX are now
shielded from leakage.

* posix: add O_CLOEXEC

This flag allows file descriptors to be open() with close-on-exec flag
set atomically.

This flag is specified in POSIX.1-2008

* tfdleak: test for selectors leakage

Also simplified the test by using handle-type agnostic APIs to test for
validity.

* ioselectors_epoll: mark all fd created close-on-exec

File descriptors from ioselectors should no longer leaks on Linux.

* tfdleak: don't check for selector leakage on Windows

The getFd proc for ioselectors_select returns a hardcoded -1

* io: add NoInheritFlag at compile time

* io: add support for ioctl-based close-on-exec

This allows for the flag to be set/unset in one syscall. While the
performance gains might be negliable, we have one less failure point
to deal with.

* tfdleak: add a test for setInheritable

* stdlib: add nimInheritHandles to restore old behaviors

* memfiles: make file handle not inheritable by default for posix

* io: setInheritable now operates on OS file handle

On Windows, the native handle is the only thing that's inheritable, thus
we can assume that users of this function will already have the handle
available to them. This also allows users to pass down file descriptors
from memfiles on Windows with ease, should that be desired.

With this, nativesockets.setInheritable can be made much simpler.

* changelog: clarify

* nativesockets: document setInheritable return value

* posix_utils: atomically disable fd inheritance for mkstemp
2020-04-20 17:09:59 +02:00
Clyybber
6bd279c978 Fix #13972 (#14034) 2020-04-20 17:06:44 +02:00
cooldome
65c5367dc1 Fixes #14014 (#14029)
* add test

* improve test

* progress

* fix #14014

* fix bug

Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-04-20 15:57:36 +02:00
Jasper Jenkins
ba0af0f827 allow generic typedesc field access (#12220)
Co-authored-by: Clyybber <darkmine956@gmail.com>
2020-04-20 15:36:57 +02:00
Lưu Danh, Hiếu
4476d8a2e0 Update code example to match new sdl2.nim syntax (#13924)
* Update code example to match new sdl2.nim syntax

Signed-off-by: Hieu Luu Danh <hieu@vivu.asia>

* Modify on recommendation of @alaviss

- Removed trailing whitespaces
- Detailed how to compile libnimhcr and libnimrtl
- Fixed some logic in example code

* Modify following recommendations of @alaviss

- Rewording so that it conforms to Windows/Linux/MacOS

Signed-off-by: Hieu Luu Danh <hieu@vivu.asia>
2020-04-20 14:49:05 +02:00
awr1
59aeaa1c98 Make bitand, bitor, bitxor varargs-friendly (#13985)
* made bitand, bitor, bitxor varargs friendly
* changed new bitops to macros
* changed macro signature for consistency (this technically doesn't matter)
* added tests
* removed redundant assert
* fix literal
2020-04-20 14:48:37 +02:00
Araq
59f1462b95 remove the nilChecks switch; refs #11570 2020-04-20 14:44:54 +02:00
Araq
4d1149cffd fix for asm statement; refs #12650 2020-04-20 14:44:54 +02:00
Araq
17f222613a refactor system.$ for objects a little; refs #13398 2020-04-20 14:44:54 +02:00
Timothee Cour
b2720317fa add --experimental:vmopsDanger; add generic conversion for vmops (#13813)
* add --experimental:vmopsDanger; vmops cleanups
2020-04-20 12:00:00 +02:00
alaviss
77834f0fda compiler/suggest: highlight squashed operators (#11796)
The operator fetching proc is greedy, so operators such as `%*` in
expression `%*{}` can't be highlighted.

This commit fixes that.
2020-04-20 11:54:53 +02:00
Araq
e6cf11351d unicode: minor documention improvement 2020-04-20 08:42:08 +02:00
Andreas Rumpf
242d39d27f fixes #12834 (#14017) 2020-04-19 14:42:45 +02:00
Andreas Rumpf
73eff1f457 fixes #12741 (#14005)
* fixes #12741
* updated tests
2020-04-19 11:59:01 +02:00
Andreas Rumpf
9874981e75 fixes #14001 (#14004) 2020-04-19 10:01:04 +02:00
Arne Döring
4005f0d0e4 forward type alignment information to seqs (#12430) 2020-04-19 07:52:01 +02:00
Andreas Rumpf
a8f030fea2 drnim: phi nodes for 'if' statements (#13990) 2020-04-19 02:41:16 +02:00
jiro
f1ee817627 Add runnableExamples to critbits module (#13994)
* doc: critbit: add runnableExamples

* doc: critbit: change to upper
2020-04-18 20:06:20 +02:00
hlaaftana
f46803b225 Fix unused warning for $ for empty tuple/objects (#13991) 2020-04-18 17:41:03 +02:00
Timothee Cour
e3919b658f fix https://github.com/nim-lang/RFCs/issues/211: var a: DateTime compiles and is usable (#14002) [backport:1.2]
* fix https://github.com/nim-lang/RFCs/issues/211: `var a: DateTime` works
* assertValidDate checks for sentinel month
2020-04-18 16:22:03 +02:00
cooldome
d839eb9352 fix #14007 (#14012) [backport]
Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-04-18 16:15:17 +02:00
cooldome
f10689d3d4 fixes #14003 (#14006) [backport:1.2]
Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-04-17 13:23:04 +02:00
cooldome
d3b0132061 Step2: fixes #13781, fixes #13805 (#13897)
* Fix sym owner in wrapper proc
* threadpool changes
* revert lowerings
* add newFastMoveStmt
* try fixing test by switching to cpp

Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-04-16 23:27:08 +02:00
cooldome
9295251e68 Implements RFCs #209 (#13995)
* add test
* add changelod entry
Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-04-16 21:04:05 +02:00
awr1
b6f99409a9 added extended msg for failed library loads w/ incorrect DLL formats (#13950)
* added extended msg for failed library loads w/ incorrect DLL formats

* missing colon

* fix GetLastError()

* make GetLastError() available for windows console apps

* remove premature nullchar if outputting extra message

* if-protect nullchar detection

* better fix for message box code
2020-04-16 20:23:54 +02:00
Miran
06e0c75ba9 make fuzzy search a bit less fuzzy (#13996) [backport:1.2] 2020-04-16 20:22:32 +02:00
Timothee Cour
6914de0d8d fix newDomParser (#13981) 2020-04-16 08:59:54 +02:00
Adam Weber
d72808520b Grammar correction in backends.rst (#13989)
I hate to be the guy that submits a couple grammatical/spelling corrections.
2020-04-16 00:39:44 -04:00
Andreas Rumpf
60ec5c89c5 added a .since annotation to hashIdentity 2020-04-15 23:35:10 +02:00
c-blake
a0b33f9408 Add hashWangYi1 (#13823)
* Unwind just the "pseudorandom probing" (whole hash-code-keyed variable
stride double hashing) part of recent sets & tables changes (which has
still been causing bugs over a month later (e.g., two days ago
https://github.com/nim-lang/Nim/issues/13794) as well as still having
several "figure this out" implementation question comments in them (see
just diffs of this PR).

This topic has been discussed in many places:
  https://github.com/nim-lang/Nim/issues/13393
  https://github.com/nim-lang/Nim/pull/13418
  https://github.com/nim-lang/Nim/pull/13440
  https://github.com/nim-lang/Nim/issues/13794

Alternative/non-mandatory stronger integer hashes (or vice-versa opt-in
identity hashes) are a better solution that is more general (no illusion
of one hard-coded sequence solving all problems) while retaining the
virtues of linear probing such as cache obliviousness and age-less tables
under delete-heavy workloads (still untested after a month of this change).

The only real solution for truly adversarial keys is a hash keyed off of
data unobservable to attackers.  That all fits better with a few families
of user-pluggable/define-switchable hashes which can be provided in a
separate PR more about `hashes.nim`.

This PR carefully preserves the better (but still hard coded!) probing
of the  `intsets` and other recent fixes like `move` annotations, hash
order invariant tests, `intsets.missingOrExcl` fixing, and the move of
`rightSize` into `hashcommon.nim`.

* Fix `data.len` -> `dataLen` problem.

* This is an alternate resolution to https://github.com/nim-lang/Nim/issues/13393
(which arguably could be resolved outside the stdlib).

Add version1 of Wang Yi's hash specialized to 8 byte integers.  This gives
simple help to users having trouble with overly colliding hash(key)s.  I.e.,
  A) `import hashes; proc hash(x: myInt): Hash = hashWangYi1(int(x))`
      in the instantiation context of a `HashSet` or `Table`
or
  B) more globally, compile with `nim c -d:hashWangYi1`.

No hash can be all things to all use cases, but this one is A) vetted to
scramble well by the SMHasher test suite (a necessarily limited but far
more thorough test than prior proposals here), B) only a few ALU ops on
many common CPUs, and C) possesses an easy via "grade school multi-digit
multiplication" fall back for weaker deployment contexts.

Some people might want to stampede ahead unbridled, but my view is that a
good plan is to
  A) include this in the stdlib for a release or three to let people try it
     on various key sets nim-core could realistically never access/test
     (maybe mentioning it in the changelog so people actually try it out),
  B) have them report problems (if any),
  C) if all seems good, make the stdlib more novice friendly by adding
     `hashIdentity(x)=x` and changing the default `hash() = hashWangYi1`
     with some `when defined` rearranging so users can `-d:hashIdentity`
     if they want the old behavior back.
This plan is compatible with any number of competing integer hashes if
people want to add them.  I would strongly recommend they all *at least*
pass the SMHasher suite since the idea here is to become more friendly to
novices who do not generally understand hashing failure modes.

* Re-organize to work around `when nimvm` limitations; Add some tests; Add
a changelog.md entry.

* Add less than 64-bit CPU when fork.

* Fix decl instead of call typo.

* First attempt at fixing range error on 32-bit platforms; Still do the
arithmetic in doubled up 64-bit, but truncate the hash to the lower
32-bits, but then still return `uint64` to be the same.  So, type
correct but truncated hash value.  Update `thashes.nim` as well.

* A second try at making 32-bit mode CI work.

* Use a more systematic identifier convention than Wang Yi's code.

* Fix test that was wrong for as long as `toHashSet` used `rightSize` (a
very long time, I think).  `$a`/`$b` depend on iteration order which
varies with table range reduced hash order which varies with range for
some `hash()`.  With 3 elements, 3!=6 is small and we've just gotten
lucky with past experimental `hash()` changes.  An alternate fix here
would be to not stringify but use the HashSet operators, but it is not
clear that doesn't alter the "spirit" of the test.

* Fix another stringified test depending upon hash order.

* Oops - revert the string-keyed test.

* Fix another stringify test depending on hash order.

* Add a better than always zero `defined(js)` branch.

* It turns out to be easy to just work all in `BigInt` inside JS and thus
guarantee the same low order bits of output hashes (for `isSafeInteger`
input numbers).  Since `hashWangYi1` output bits are equally random in
all their bits, this means that tables will be safely scrambled for table
sizes up to 2**32 or 4 gigaentries which is probably fine, as long as the
integer keys are all < 2**53 (also likely fine).  (I'm unsure why the
infidelity with C/C++ back ends cut off is 32, not 53 bits.)

Since HashSet & Table only use the low order bits, a quick corollary of
this is that `$` on most int-keyed sets/tables will be the same in all
the various back ends which seems a nice-to-have trait.

* These string hash tests fail for me locally.  Maybe this is what causes
the CI hang for testament pcat collections?

* Oops. That failure was from me manually patching string hash in hashes.  Revert.

* Import more test improvements from https://github.com/nim-lang/Nim/pull/13410

* Fix bug where I swapped order when reverting the test.  Ack.

* Oh, just accept either order like more and more hash tests.

* Iterate in the same order.

* `return` inside `emit` made us skip `popFrame` causing weird troubles.

* Oops - do Windows branch also.

* `nimV1hash` -> multiply-mnemonic, type-scoped `nimIntHash1` (mnemonic
resolutions are "1 == identity", 1 for Nim Version 1, 1 for
first/simplest/fastest in a series of possibilities.  Should be very
easy to remember.)

* Re-organize `when nimvm` logic to be a strict `when`-`else`.

* Merge other changes.

* Lift constants to a common area.

* Fall back to identity hash when `BigInt` is unavailable.

* Increase timeout slightly (probably just real-time perturbation of CI
system performance).
2020-04-15 20:11:18 +02:00
Andreas Rumpf
3a2697dd73 drnim: tiny progress (#13882)
* drnim: tiny progress
* refactoring complete
* drnim: prove .ensures annotations
* Moved code around to avoid code duplication
* drnim: first implementation of the 'old' property
* drnim: be precise about the assignment statement
* first implementation of --assumeUnique
* progress on forall/exists handling
2020-04-15 20:03:25 +02:00
Miran
04b6e9cf3e add timezones package to important_packages (#13987) 2020-04-15 17:33:16 +02:00
Timothee Cour
4764220cfb Fix https://github.com/inim-repl/INim/issues/66 (#13984) 2020-04-15 13:07:18 +02:00
Timothee Cour
2c93d1684e enable important_pkg on OSX (#13954)
* enable important_pkg on OSX

* disable some important_packages on OSX

* fixup

* enable nigui by installing dependency
2020-04-14 15:00:35 +02:00
Timothee Cour
10eabec6d4 fix #12864 static params were mutating arg types during sigmatch; fix #12713 ; refs #13529 (#13976)
* fix #12864 static params were mutating arg types during sigmatch

* fix test

* fix StaticParam

* also fixes #12713; added test case
2020-04-14 15:00:02 +02:00
Juan Carlos
c269964860 Add Data URI Base64, implements RFC-2397 (#13759)
* Add Data URI Base64, implements RFC-2397

* Add Data URI Base64, implements RFC-2397

* Add Data URI Base64, implements RFC-2397

* https://github.com/nim-lang/Nim/pull/13759#issuecomment-611498420

* https://github.com/nim-lang/Nim/pull/13759#issuecomment-611498420

* ReSync changelog

* https://github.com/nim-lang/Nim/pull/13759#issuecomment-611498420

Co-authored-by: Dominik Picheta <dominikpicheta@googlemail.com>
2020-04-13 14:15:45 +01:00
Juan Carlos
0a84219b3e Add jsdomparser (#13920)
* Add jsdomparser

* Add jsdomparser

* Add jsdomparser

* https://github.com/nim-lang/Nim/pull/13920#issuecomment-610727142

* https://github.com/nim-lang/Nim/pull/13920#issuecomment-610727142

* https://github.com/nim-lang/Nim/pull/13920#issuecomment-610727142

* https://github.com/nim-lang/Nim/pull/13920#discussion_r405932909

* https://github.com/nim-lang/Nim/pull/13920#discussion_r406502592
2020-04-13 14:07:52 +01:00
Oscar Nihlgård
255698deee Fix semfold handling of {.str/int/bool-define.} (#13964) 2020-04-13 14:22:33 +02:00
jiro
40b64ccd7b Add runnableExamples to bitops module (#13951)
* doc: bitops: add runnableExamples

* doc: bitops: add notes to documentation comments of macros

* doc: bitops: add periods to documentation comments

* doc: bitops: add static

* Revert "doc: bitops: add static"

This reverts commit 595ee134ab.

* doc: bitops: add `var` to arguments of macros

* doc: bitops: remove examples of testBit
2020-04-13 14:21:45 +02:00
cooldome
8ba915e449 error msg for #13864 (#13962)
Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-04-13 14:17:22 +02:00
Timothee Cour
814f150184 fix #13848: make var result work with nim cpp (#13959)
* fix #13848

* add exhaustive tests for var result
2020-04-13 14:16:06 +02:00
narimiran
2ef39081e1 minor fixes in 1.2 changelog [ci skip] 2020-04-13 08:12:27 +02:00
genotrance
35b046373a Improve #12920 fix (#13958) 2020-04-12 21:08:16 +02:00
Juan Carlos
7238b968f3 Make unused code into actual test, replace echo with doassert (#13952) 2020-04-11 22:16:26 +02:00
alaviss
5f6962337d osproc: added a better version of waitForExit for Haiku (#13938)
Also modified tosprocterminate to verify waitForExit implementations.
2020-04-10 09:34:52 +02:00
alaviss
cc3f5d21b2 posix: add full Haiku support (#13931)
* posix: add full Haiku support

This commit provides a posix_haiku derived from posix_other, with types
following Haiku's definition. This fixes cases where the compiler
generates type check for the wrong types (ie. checks where generated for
an int-derived type but it's actually implemented as an uint instead).

* tools/kochdocs: welcome posix_haiku to the blacklist
2020-04-09 15:56:08 +02:00
cooldome
7b582fd6a6 fixes #13863 (#13929)
Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-04-08 19:51:23 +02:00
Hessam Mehr
bff742cd8b Add support for zig cc as C compiler. (#13757) 2020-04-08 15:24:14 +02:00
Dominik Picheta
350ee0308a Fixes issues with dynamic loading OpenSSL. Fixes #13903. (#13919) [backport]
This fixes at least a couple of issues:

* Procs loaded from the DLL being used even when the pointer is nil.
* The actual issue (#13903) which appeared to cause stack corruption on
  Android 7.1.1 with OpenSSL 1.1.1f. The change that fixed this was the
  move to loading the procs in `sslSym`.
2020-04-08 14:37:00 +02:00
Miran
3dc8068075 Test packages on Linux (#13921)
* test important packages on Linux

* enable chronos
2020-04-08 14:34:08 +02:00
cooldome
b4e9f8e814 fix ICE in isUnresolvedSym (#13925)
Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-04-08 13:16:25 +01:00
cooldome
f86fc5316a fix #13909 (#13914) [backport:1.2]
Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-04-08 11:28:09 +02:00
Timothee Cour
95fd8ae93c fix #13902 distinct uint64 type corruption on 32-bit with borrow (#13907) [backport:1.2]
* fix #13902 distinct uint64 type corruption on 32-bit with borrow

Co-authored-by: Timothee Cour <timothee.cour2+lightsail@gmail.com>
2020-04-08 09:56:16 +02:00
narimiran
3036ec9c44 fix #13894, httpclient hang on Http204 2020-04-07 22:21:39 +01:00
cooldome
c835c8c4e7 fix #13910 (#13917)
Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-04-07 19:40:14 +02:00
Timothee Cour
ab5e26c53c fix some codegen bugs: NIM_BOOL, NIM_STATIC_ASSERT, --passc:-std=... (etc) (#13798)
* fix cgen bool D20200328T203812
* --passc:std=c++17 (etc) now works instead of silently ignored
* document caveats for NIM_NIL
2020-04-07 15:17:30 +02:00
Nicolai Søborg
b41931bf67 json doc: Note about Option and reserved keywords (#13895) 2020-04-07 15:14:25 +02:00
Arne Döring
37692baf49 fix #13739 (#13742) 2020-04-07 14:42:59 +02:00
Clyybber
92c4aad205 Fix #13889 with testcase (#13896) [backport]
* Fix https://github.com/nim-lang/Nim/issues/13889

* Add testcase

* Reduce test time

Co-authored-by: Elie Zedeck RANDRIAMIANDRIRAY <elie.zedeck@gmail.com>
2020-04-06 16:25:24 +02:00
Clyybber
1e25e16c88 Fix #13872 (#13898) 2020-04-06 14:35:27 +01:00
Timothee Cour
e6d870896b openDefaultBrowser now works on OSX (#13892) [backport] 2020-04-06 08:26:12 +02:00
Timothee Cour
f1fd3ef7f4 fix https://github.com/timotheecour/Nim/issues/88 (#13865) [backport:1.2] 2020-04-06 00:24:35 +02:00
supakeen
87847150bf Add barebones asynchttpserver tests (#13883)
* Add isNil check to custom Content-Length.

Related to #13866.

* Setup barebones asynchttpserver tests.
2020-04-05 21:16:13 +02:00
Hiroki Noda
b6814be653 doc: fix comment for repr*(x: char): string (#13873)
replace `$` with `repr`.
2020-04-05 16:44:55 +02:00
Timothee Cour
29734b73ff add nimPath to nim dump (#13876)
* add nimPath to nim dump

* rename
2020-04-05 16:44:34 +02:00
cooldome
6d4f07f2ea Fix sym owner in wrapper proc (#13878)
Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-04-05 16:44:15 +02:00
supakeen
09ca19208f Add isNil check to custom Content-Length. (#13867) [backport:1.2]
Related to #13866.
2020-04-05 09:02:30 +02:00
alaviss
813ed358bf asyncdispatch: get rid of erroneous set constructions (#13877)
Ref #13764
2020-04-05 08:39:43 +02:00
Andreas Rumpf
a890aa75aa finally de-deprecate the .define and .undef pragmas 2020-04-04 23:12:24 +02:00
Andreas Rumpf
9c46927fad new feature: ability to turn specific warnings to errors 2020-04-04 22:56:03 +02:00
narimiran
ed44e524b0 bump devel version to 1.3.1 2020-04-03 21:28:11 +02:00
Alexander Ivanov
cec320b569 Remove my wrongly written mangled-related code, not needed anymore (#13858) 2020-04-03 20:22:03 +02:00
Alexander Ivanov
920add5880 sourcemaps for the JS codegen (#7508) 2020-04-03 12:06:23 +02:00
Andreas Rumpf
2b3b24a804 make bootstrapping more robust for people who have Nim inside /usr/bin (#13855) 2020-04-03 10:25:15 +02:00
itsumura-h
87e6b88f3b fix #7241 (#13779)
finalize() should run in insert()
2020-04-03 09:38:05 +02:00
Timothee Cour
93cd98dd14 move tinyc to a separate repo and allow installing external dependencency (eg tinyc) from koch / library code (#13850)
* remove tinyc
* installDeps
* update tinyc paths
2020-04-03 09:10:45 +02:00
flywind
6b9ffc7fad fix asynchttpserver content-length header (#13846) 2020-04-03 09:05:43 +02:00
Timothee Cour
d23371fdd7 std/byaddr => std/decls (#13847) 2020-04-03 09:03:13 +02:00
narimiran
7d17cd34b8 create a changelog for v1.2.0 2020-04-02 16:28:01 +02:00
Araq
8ee0771b5a return types must not be Natural for reasons I won't outline here 2020-04-02 15:01:14 +02:00
Araq
d01fca974d added an .assert pragma and mentioned the pragmas in the changelog 2020-04-02 12:57:32 +02:00
Dean Eigenmann
df8e0e7f0c feature/count (#13837) 2020-04-02 12:09:29 +02:00
Andreas Rumpf
d01245e501 renamed new std/pragmas.nim to std/byaddr.nim (#13844)
* renamed new std/pragmas.nim to std/byaddr.nim

* minor code cleanup
2020-04-02 11:52:31 +02:00
Timothee Cour
68539a2926 fix last remaining warning when building nim (intVal should be Int128) + minor cleanups (#13841) 2020-04-02 08:53:52 +02:00
Juan Carlos
c167261735 Deprecate PHP (#13838) 2020-04-02 08:48:09 +02:00
Juan Carlos
160d5fe589 Jsconsole update (#12448)
* Improve jsconsole adding the rest of the stable api as documented on the standard at https://developer.mozilla.org/docs/Web/API/Console

* Improve jsconsole, add runnableexamples
* Simplify jsconsole
2020-04-02 08:47:45 +02:00
Juan Carlos
46ca19ff18 Deprecate DCE:on (#13839) 2020-04-02 02:58:43 +02:00
Juan Carlos
afd0afe0a3 Deprecate when declared(echo):echo (#13840) 2020-04-02 02:56:18 +02:00
Juan Carlos
9102ac8c7d Documentation and Code Style inotify (#13836) 2020-04-02 01:05:55 +02:00
Juan Carlos
9599757068 Add browsers.openDefaultBrowser without URL, implements IETF RFC-6694 Section-3 (#13835) 2020-04-01 15:46:47 -04:00
Andreas Rumpf
bc37668c5a fixes #13782 (#13834) 2020-04-01 20:30:28 +02:00
Juan Carlos
4816984726 Documentation, add more examples (#13825) 2020-04-01 19:39:58 +02:00
Andreas Rumpf
484548c784 revert stdlib changes which are not required anymore 2020-04-01 19:38:44 +02:00
Zahary Karadjov
66f18037b3 Fix tests/types/tparameterizedparent0 2020-04-01 19:38:44 +02:00
Zahary Karadjov
08afa03075 The raises list can now use expressions referencing the generic params 2020-04-01 19:38:44 +02:00
Zahary Karadjov
be95f8fdfa Turn some of the errors back into warnings 2020-04-01 19:38:44 +02:00
Zahary Karadjov
ce9a4ed124 Replace tfHasRequiresInit with a more accurate mechanism
The new mechanism can deal with more complex scenarios such as
not nil field appearing in a non-default case object branch or
a field within a generic object that may depend on a when branch.

The commit also plugs another hole: the user is no longer able
to create illegal default values through seq.setLen(N).
2020-04-01 19:38:44 +02:00
Zahary Karadjov
d374c6373b Fix tests/parallel/tguard2.nim 2020-04-01 19:38:44 +02:00
Zahary Karadjov
2b66d66567 Fix a CI failure during koch doc 2020-04-01 19:38:44 +02:00
Zahary Karadjov
e63b673ce2 Fix https://github.com/nim-lang/Nim/issues/4907 2020-04-01 19:38:44 +02:00
Zahary Karadjov
06438ed143 Close https://github.com/nim-lang/Nim/issues/11428 2020-04-01 19:38:44 +02:00
Zahary Karadjov
4f3d309fb0 Perform nil checks during object construction and within compiles()
Close https://github.com/nim-lang/Nim/issues/6494
2020-04-01 19:38:44 +02:00
Zahary Karadjov
7b7e42be54 More precise error messages for uninitialized fields in the presence of inheritance 2020-04-01 19:38:44 +02:00
Zahary Karadjov
0521f98486 Hrm, the new errors highlighted some code that seems to be broken
New issue: since `Table[A, B]` allocates its backing storage with
`newSeq[KeyValuePair[A, B]]`, it's no longer legal to create a table
with `not nil` types used as either keys or values.
2020-04-01 19:38:44 +02:00
Zahary Karadjov
f3be5a716f not nil types are illegal to construct through default(T) 2020-04-01 19:38:44 +02:00
Zahary Karadjov
1b570f2b18 Turn the warning for uninitialized (result) variables into errors 2020-04-01 19:38:44 +02:00
Zahary Karadjov
e0bb78553a Fix tests/notnil/tnotnil_in_objconstr.nim 2020-04-01 19:38:44 +02:00
Zahary Karadjov
54f06427c8 Enable the requiresInit checks only for objects 2020-04-01 19:38:44 +02:00
Zahary Karadjov
8ae48292ff Plug another hole: default(T) forbidden for objects requiring initialization 2020-04-01 19:38:44 +02:00
Zahary Karadjov
05a0ec4adb Don't allow 'var x: T' for objects that require initialization 2020-04-01 19:38:44 +02:00
Zahary Karadjov
7652aede41 More sophistication; Allow requiresInit to be specified per-field 2020-04-01 19:38:44 +02:00
Zahary Karadjov
a8b6222c86 First steps, the compiler can boot with enforced requiresInit 2020-04-01 19:38:44 +02:00
Timothee Cour
216fd59c44 make usage of foo is a user-defined error more informative (#13833) 2020-04-01 17:49:29 +02:00
Timothee Cour
d3020af44d fix open file leak when running --debugger:native (#13832) 2020-04-01 17:48:17 +02:00
Araq
c2d29eb3e0 updated the changelog 2020-04-01 14:10:47 +02:00
Araq
48213c7428 encodeMIME should be encodeMime by our coding guidelines 2020-04-01 14:10:27 +02:00
Timothee Cour
fd202136b4 fix #13829 (#13831) 2020-04-01 12:46:59 +01:00
Clyybber
515b6d661e Small typo (#13824) 2020-03-31 22:59:43 +02:00
lbartoletti
567af54baf Add arm/arm64 for FreeBSD (#13822)
* Add arm and arm64 for FreeBSD

* Add arm64 with aarch64 and reorder to avoid conflict with arm
2020-03-31 22:55:25 +02:00
Andreas Rumpf
9ffec79300 DrNim (Nim compiler with Z3 integration) (#13743)
* code cleanups and feature additions
* added basic test and koch/CI integration
* make it build on Unix
* DrNim: now buildable on Unix, only takes 10 minutes, enjoy
* added basic documentation for DrNim which can also be seen as the RFC we're following
* drnim: change the build setup so that drnim.exe ends up in bin/
* makes simple floating point ranges work
* added basic float range check
* drnim: teach Z3 about Nim's range types plus code refactoring
* drnim: make unsigned numbers work
* added and fixed index checking under setLen
* first implementation of .ensures, .invariant and .assume (.requires still missing and so is proc type compatibility checking
* drnim: .requires checking implemented
* drnim: implemented .ensures properly
* more impressive test involving min()
* drnim: check for proc type compatibility and base method compatibility wrt .requires and .ensures
* testament: support for 'pattern <directory>
* koch: uses new <directory> feature of testament
* drnim: added tiny musings about 'old'
* Make testament work with old SSL versions
* koch: add support for 'koch drnim -d:release'
* drnim: preparations for the param.old notation
2020-03-31 22:54:48 +02:00
Juan Carlos
dd44701728 Tiny fix on browsers.openDefaultBrowser (#13818) 2020-03-31 21:22:24 +02:00
Juan Carlos
c6586322ba Fix a 'See XXX' on documentation, clean out (#13820) 2020-03-31 21:21:49 +02:00
cooldome
c70b3952ff fixes #13810 (#13821)
Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-03-31 21:15:06 +02:00
Andreas Rumpf
9134bb9cfb macros for proc types, macros for types (#13778)
* new minor feature: macros for proc types, to be documented

* Finished the implementation and added tests

* [skip ci] Describe the new custom pragmas in the manual and the changelog

Co-authored-by: Zahary Karadjov <zahary@gmail.com>
2020-03-31 21:14:05 +02:00
alaviss
40898871a9 workflows/ci_docs: fix documentation deployment (#13819)
* workflows/ci_docs: fix docs publishing

It turns out that github.ref is the full ref name, so we have to be a
bit more specific.

See https://developer.github.com/v3/activity/events/types/#pushevent

Also fixed a silly typo :)

* workflows/ci_docs: run CI when there are changes to the workflow
2020-03-31 19:36:37 +02:00
c-blake
b1aa3b1eea Unwind just the "pseudorandom probing" part of recent sets,tables changes (#13816)
* Unwind just the "pseudorandom probing" (whole hash-code-keyed variable
stride double hashing) part of recent sets & tables changes (which has
still been causing bugs over a month later (e.g., two days ago
https://github.com/nim-lang/Nim/issues/13794) as well as still having
several "figure this out" implementation question comments in them (see
just diffs of this PR).

This topic has been discussed in many places:
  https://github.com/nim-lang/Nim/issues/13393
  https://github.com/nim-lang/Nim/pull/13418
  https://github.com/nim-lang/Nim/pull/13440
  https://github.com/nim-lang/Nim/issues/13794

Alternative/non-mandatory stronger integer hashes (or vice-versa opt-in
identity hashes) are a better solution that is more general (no illusion
of one hard-coded sequence solving all problems) while retaining the
virtues of linear probing such as cache obliviousness and age-less tables
under delete-heavy workloads (still untested after a month of this change).

The only real solution for truly adversarial keys is a hash keyed off of
data unobservable to attackers.  That all fits better with a few families
of user-pluggable/define-switchable hashes which can be provided in a
separate PR more about `hashes.nim`.

This PR carefully preserves the better (but still hard coded!) probing
of the  `intsets` and other recent fixes like `move` annotations, hash
order invariant tests, `intsets.missingOrExcl` fixing, and the move of
`rightSize` into `hashcommon.nim`.

* Fix `data.len` -> `dataLen` problem.
2020-03-31 19:18:45 +02:00
Euan
7abeba6aeb #13806 - getApplFreebsd might lose data (#13807)
* #13806 - first call sysctl with a null buffer to get the length, then alloc buffer and call again

* Use csize_t rather than csize

* Suggestions from @Clyybber

Co-authored-by: Euan Torano <euan.torano@bluesky-wireless.co.uk>
2020-03-31 15:50:24 +02:00
alaviss
5621ff6d09 workflows/ci_docs: lots of goodies (#13809)
* workflows/ci_docs: publish documentation to Github Pages

This should be a complete replacement for our current Travis CI setup.

* workflows/ci_docs: run docgen upon modification to the css on push

So that any changes regarding the stylesheets would be reflected on the
published docs.

* workflows/ci_docs: build the compiler in release mode

* workflows/ci_docs: set branch name for the generated docs

This makes the "Source" links work correctly.

* workflows/ci_docs: run docgen on windows and osx too

Only deploy the Linux-generated version.

* workflows/ci_docs: cache csources compiler

This should cut the time spent building csources, which is about 1-2mins
depending on OS.
2020-03-31 15:48:56 +02:00
Juan Carlos
42d2c3088e Add Documentation (#13811)
* Add more Docs and runnableExamples
2020-03-31 15:47:57 +02:00
Timothee Cour
1e4093d949 refs #13797 (#13812) 2020-03-31 15:43:35 +02:00
Huy Doan
119b0ce66f Fix telebot test failed, closes ba0f3/telebot.nim#49 [ref #13812] (#13814)
I was update telebot to version 1.0.0, update folder structure follow `nimble` guideline
2020-03-31 11:25:12 +02:00
Timothee Cour
19cab9fa51 stacktraces can now show custom runtime msgs per frame (#13351)
* stacktraces can now show custom runtime msgs
* improve tests/stdlib/tstackframes.nim
* fix test for --gc:arc
* test --stacktraceMsgs:on and --stacktraceMsgs:off
* --stacktracemsgs:off by default
2020-03-30 13:45:32 +02:00
Miran
8088633250 faster CIs (#13803)
* ttables: smaller table, 5x speedup

* thavlak: less iterations, less loops; 30% speedup

* tasyncclosestall: shorter timeout; 35% speedup

* gcleak4: less iterations, 2x speedup

* ttimes: remove deprecated stuff

* tdangerisrelease: remove cpp backend, 3x speedup

* tfrexp1: smaller range, 2x speedup

* trtree: fix warnings, less iterations, 6x speedup

* tasyncawait_cyclebreaker: smaller swarm size; 2x speedup

* trealloc: smaller number of iterations; 10x speedup

* towned_binary_tree: less iterations, 4x speedup

* tclosure: remove unused code, less iterations; 2x speedup

* twaitany: less durations; 1.4x speedup

* tasync_misc: less iterations, 2x speedup

* t8535: smaller sleep, 1.5x speedup

* tmanyjoin: smaller sleep, 2x speedup

* t12221: shorter sleeps, removed two slower tests; 1.6x speedup

* tfuturestream: smaller sleep; 1.5x speedup

* growobjcrash: less iterations; 2x speedup

* ttryrecv: smaller sleep; 1.5x speedup

* treusetvar: less threads; 2x speedup

* delete tthreadanalysis2, basically a duplicate of tthreadanalysis

* t7758: less iterations, 1.5x speedup

* tasyncawait: smaller swarm, less messages; 1.5x speedup

* tjsandnativeasync: smaller sleep, 1.5x speedup

* tpendingcheck: smaller sleep, 1.5x speedup

* remove rodfiles test category

* move tseq from its own category to 'collections' category

* remove unneeded tests and helpers from 'assert' category

* stdlib: merge tbitops2 into tbitops

* remove 'trepr2' from 'stdlib' cat

* merge 'tstreams' into one file

* remove 'tinefficient_const_table' from 'ccbugs' cat

* merge 'tcollections_to_string' into 'tcollections'

* tblocking_channel: smaller sleep, small speedup

* tconvexhull: less iterartions; 1.2x speedup

* merge 'tdeepcopy2' into 'tdeepcopy'

* merge 'tdisjoint_slice2' into 'tdisjoint_slice1'

* tmissing_deepcopy: smaller sequence

* tsendtwice: smaller arrays; 5x speedup

* remove 'tindexerrorformatbounds'

* disable multimethod tests

* remove 'gc:none' and 'refc' without 'd:useRealtimeGC' from gc tests

* koch.nim: bootstrap just with '-d:release', no need for 'csource'

* add github workflow for documentation

* testament: no need for 8 sub-second decimals
2020-03-30 13:18:12 +02:00
Andreas Rumpf
2a278f6eba '.push raises: []' now also affects proc types (#13776)
* '.push raises: []' now also affects proc types

* fixes the regression

* less disruptive bugfix

* another attempt
2020-03-29 22:00:18 +02:00
Timothee Cour
06f8c5cb6f fix #13794 HashSet leak (#13800) 2020-03-29 18:08:50 +02:00
Juan Carlos
8c719fce54 Fix #13631 (#13789) 2020-03-29 14:39:58 +02:00
Timothee Cour
cfa1a827dc fix #13730 (#13787) 2020-03-28 08:51:16 +01:00
Timothee Cour
95ab9ab75d [CI] fix recent freebsd systematic failure (#13788) 2020-03-28 01:45:22 -04:00
Andreas Rumpf
0a49fe5fad fixes #13763 (#13777) 2020-03-27 12:14:57 +01:00
alaviss
0eaacbc2c4 More fixes for Haiku (#13774)
* osproc: move fork-based code path under the when conditional

* osproc: avoid using the environ global on Haiku

* osenv: import environ from stdlib.h on Haiku

Haiku's environ is declared in `<stdlib.h>` by default, differing from
POSIX and/or Linux. Import it from there to avoid collision with anyone
importing `<stdlib.h>` from Nim.
2020-03-27 09:08:13 +01:00
Arne Döring
142c59fc37 fix typos and deprecation warnings for tconvariancerules.nim (#13772) 2020-03-27 08:36:21 +01:00
cooldome
289b31ee75 make nim_temp compile with --gc:arc --sinkInference:off (#13769)
* make nim_temp compiler with --gc:arc

* trigger build

Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-03-26 20:15:38 +01:00
Clyybber
2925a47ae6 Fix vm.nim for --gc:arc (#13741)
* koch boot --gc:arc now passes the nim stage

... but generates invalid C code

* Move it closer to where its used

* Try something else

* Poor mans var

* Use UncheckedArray instead
2020-03-26 15:18:45 +00:00
alaviss
6162da812a ssl_certs: add Haiku support (#13761) 2020-03-26 14:47:15 +01:00
alaviss
2da438c33b asyncdispatch: fix erroneous set construction (#13765)
These constants were defined as `cint`. They can be huge on certain
systems, such as Haiku, and trigger out-of-bounds errors in
asyncdispatch.

Ref #13764.
2020-03-26 09:26:56 +01:00
zah
e50441ab33 Fix typeSym.getImpl for ref types (#13752)
* Fix typeSym.getImpl for ref types

* Fix a codegen issue affecting the test suite of nim-beacon-chain

* Fix tests/stdlib/tjsonmacro

To understand the fix better it may help to take a look
at the history of the replaced code.

The nil check that is removed in this commit was introduced
in another fix that failed to identify the root cause of the
issue - namely that we allow an object type to exist for which
no ast is present:

https://github.com/nim-lang/Nim/pull/9601/files

The original intention of the code is more obvious here:

https://github.com/nim-lang/Nim/pull/9538/files
2020-03-26 09:26:19 +01:00
Euan
1b31e08917 import macros rather than import std/macros. (#13762) 2020-03-26 09:11:32 +01:00
Timothee Cour
98753da331 distinctBase overload for values (#13746) 2020-03-25 21:47:03 +01:00
cooldome
764a81ca25 Continue bool conversion fixing (#13751)
* continue fixing #13744

* improve style

* improve test

Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-03-25 21:36:22 +01:00
Miran
e1e062197e bump copyright year to 2020 (#13753) 2020-03-25 21:28:16 +01:00
Rory O’Kane
a8a464810e [ci skip] docs: make the syntax for generics easy to look up (#13754) 2020-03-25 21:09:23 +01:00
Rory O’Kane
febd48f343 [skip ci] docs: reword Part 3 link to communicate that it exists (#13755) 2020-03-25 21:08:24 +01:00
Rory O’Kane
84b378b94f docs: say that nil can be used as a value (#13756)
and improve wording in other ways

Showing that `nil` can be assigned helps to warn readers that variables can be `nil` even after being assigned a value.
2020-03-25 19:42:34 +01:00
Miran
5b55aa52d0 fix deprecations and other warnings (#13748) 2020-03-25 19:15:34 +01:00
cooldome
182d3c16e3 fixes #13744 (#13749)
* fixes #13744

* improve style

Co-authored-by: cooldome <ariabushenko@gmail.ru>
2020-03-25 13:44:52 +00:00
Timothee Cour
46c827be6a fix #13737 (#13738) 2020-03-24 10:14:49 +01:00
Araq
5300baae06 use nimEmulateOverflowChecks for ARM/ARM64 2020-03-24 09:46:54 +01:00
Euan
c0dbcffca6 __stderrp and friends are only on FreeBSD & DragonFlyBSD. (#13735) 2020-03-23 21:39:40 +01:00
Miran
4fb7f076d8 fix #13731, ambiguous repr of pointers (#13732) 2020-03-23 20:03:07 +01:00
Andreas Rumpf
fc5dd11b3d fixes #13722 (#13729)
* fixes #13722

* better fix
2020-03-23 15:47:10 +01:00
Araq
e05fd1d00f hotfix: make 'nim doc nimhcr' work on all platforms 2020-03-23 13:05:29 +01:00
Araq
bcccb74429 trees.nim: compare floating points by their bitpatterns because NaN comparisions are always false (WORST design in the history of computing!) 2020-03-23 12:06:33 +01:00
Araq
ee440df02d disable even more of scope based destruction handling; fixes #13709 2020-03-23 12:05:59 +01:00
Araq
28a755dc80 trees.nim: compare floating points by their bitpatterns because NaN comparisions are always false (WORST design in the history of computing!) 2020-03-23 12:05:59 +01:00
Timothee Cour
913bc95964 new syntax for lvalue references: var b {.byaddr.} = expr (#13508)
* new syntax for lvalue references: `var b {.byaddr.} = expr`
* on type mismatch, `???(0, 0)` not shown anymore
* * compiler now lowers `var a: {.foo.}: MyType = expr` to foo(a, MyType, expr)
* new pragmas.byaddr defined in pure library code exploiting this lowering
* skip `template foo() {.pragma.}`
2020-03-23 11:15:45 +01:00
Andy Davidoff
fa06203e90 add error for missing commandLineParams (#13719)
* add error for missing commandLineParams

* fixup

* rewrite
2020-03-23 11:08:37 +01:00
Andreas Rumpf
7ee08b8cf6 Revert "fix #13417 (#13712)" (#13728)
This reverts commit a5f02cac85.
2020-03-23 09:57:17 +01:00
Christian Ulrich
0ac9c7bb64 introduce getPeerCertificates, fixes #13299 (#13650)
* make i2d_X509 and d2i_X509 always available

i2d_X509 and d2i_X509 have been available in all versions of OpenSSL, so
make them available even if nimDisableCertificateValidation is set.

* introduce getPeerCertificates, fixes #13299

getPeerCertificates retrieves the verified certificate chain of the peer
we are connected to through an SSL-wrapped Socket/AsyncSocket. This
introduces the new type Certificate which stores a DER-encoded X509 certificate.
2020-03-22 21:00:37 +01:00
Araq
ef2566218e better error messages for Nim's effect system 2020-03-22 20:45:03 +01:00
Araq
4c1fdc2e8f Windows API callbacks cannot raise exceptions 2020-03-22 20:45:03 +01:00
Arne Döring
a5f02cac85 fix #13417 (#13712)
* fix #13417

* add test
2020-03-22 20:03:51 +01:00
Arne Döring
64ffa17f0f fixes #13715 (#13716)
* fixes #13715

* fix test
2020-03-22 20:01:01 +01:00
Araq
474dd98125 typo 2020-03-22 19:45:02 +01:00
Arne Döring
047d3af6da fix #13720 (#13721) 2020-03-22 19:35:55 +01:00
Hiroki Noda
86b9435138 Add EPOLLEXCLUSIVE (#13718) 2020-03-21 22:52:44 +01:00
cooldome
586ebb090b fixes #13708 (#13711)
* fixes #13708
* differentiate between arc and rest of GC

Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-03-21 07:12:10 +01:00
narimiran
b6e04eafce [ci skip] add back unintentionally removed line 2020-03-20 17:15:48 +01:00
Federico Ceratto
5b85444244 SSL certificate verify GitHub action (#13697)
* Implement SSL/TLS certificate checking #782

* SSL: Add nimDisableCertificateValidation

Remove NIM_SSL_CERT_VALIDATION env var
tests/untestable/thttpclient_ssl.nim ran successfully on Linux with libssl 1.1.1d

* SSL: update integ test to skip flapping tests

* Revert .travis.yml change

* nimDisableCertificateValidation disable imports

Prevent loading symbols that are not defined on older SSL libs

* SSL: disable verification in net.nim

..when nimDisableCertificateValidation is set

* Update changelog

* Fix peername type

* Add define check for windows

* Disable test on windows

* Add exprimental GitHub action CI for SSL

* Test nimDisableCertificateValidation
2020-03-20 17:11:39 +01:00
Timothee Cour
1d665adecd [RFC] 'walkDir' now has a new 'checkDir' flag, to mimic behaviour of other languages (#13642)
Co-authored-by: narimiran
2020-03-20 16:39:55 +01:00
Araq
8215c57666 threadpool.nim: allow control over MaxThreadPoolSize and MaxDistinguishedThread; refs #10584 2020-03-20 15:07:11 +01:00
Joey
0f2377ebef Revert –#13658 for nim-gdb.bat. Fixes #13705 (#13707) 2020-03-20 14:38:33 +01:00
Andreas Rumpf
253e1b9e96 fixes #13698 (#13706) 2020-03-20 14:35:45 +01:00
Hayden
f4dbdd311f Detect Ubuntu by checking release() and uname() (#13704)
This will improve detection of Ubuntu when running on Ubuntu on WSL. #13703
2020-03-20 10:59:05 +01:00
Araq
dae9865b14 fight the code bloat in base64.nim 2020-03-20 10:46:58 +01:00
Araq
12ab5059a0 make 'nim check' more robust for illdefined constants 2020-03-20 10:46:40 +01:00
Juan Carlos
70d93636cb Add Base64 safe (#13672)
* Implement RFC-4648 Section-7
* https://github.com/nim-lang/Nim/pull/13672#issuecomment-600993466
2020-03-20 10:21:42 +01:00
Timothee Cour
dd362ab4c0 fix #13538 sigmatch errors are now sorted (#13701)
* fix #13538 sigmatch now sorted and has reliable order

* re-enable tests that were disabled because of that bug

* fix remaining tests and un-disable 2 other tests that were affected by this bug
2020-03-20 09:28:03 +01:00
Juan Carlos
55d3780b7b Remove 2 old deprecated files (#13702) 2020-03-20 09:24:35 +01:00
Jasper Jenkins
1037318e68 fix nimsuggest warning (#13699) 2020-03-20 09:24:04 +01:00
Jasper Jenkins
28b6b1c3fb fix nimpretty warning (#13700) 2020-03-20 09:22:40 +01:00
Andreas Rumpf
35fb38629f cycle breaker (#13593)
* cycle breaking as an alternative to cycle detection
2020-03-19 22:58:16 +01:00
Juan Carlos
705e283fef Clean 1 old deprecated empty file (#13696) 2020-03-19 20:40:52 +01:00
cooldome
b3176b8817 Attempt to finish off araq cpp exceptions (#13695)
* config update
* disable a questionable test
* remove c++ exception handling IDs, new impl doesn't require it anymore
* C++ based exceptions finally work
* fixes bootstrapping problem in C++ mode
* teach GCC it's 2020 now
* more bugfixes for C++ based exception handling
* apply cooldome's patch
* another attempt to enable C++11
* bug fix

Co-authored-by: Araq <rumpf_a@web.de>
Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-03-19 20:38:25 +01:00
Andreas Rumpf
034dad8e32 fixes #13691 (#13694) 2020-03-19 12:57:45 +01:00
Timothee Cour
1f2042411a fix #13412 nim now recompiles for stdin input; SuccessX now configurable; can show whether it recompiled (#13506)
* fix #13412 nim now recompiles for stdin input; SuccessX now indicates whether it recompiled
2020-03-19 10:39:18 +01:00
Timothee Cour
a17e87b516 fix #11458 oswalkdir (#13689)
* fix #11458 oswalkdir

* changelog
2020-03-19 10:23:05 +01:00
Andreas Rumpf
ba6e7c6365 added a switch -d:nimEmulateOverflowChecks for broken or old GCC versions (#13692) 2020-03-19 09:56:30 +01:00
Miran
b5c9881a30 add move to tables to prevent warnings when compiled with --gc:arc (#13684) 2020-03-19 09:09:01 +01:00
alaviss
b33335d7fd httpcore: deprecate ==(string, HttpCode) (#13682)
According to [RFC7230], the reason phrase attached to the status line is
optional and clients should not rely on it. This in turn causes the proc
to be practically useless, as clients should only inspect the return
code.

Ref #13680.

[RFC7230]: https://tools.ietf.org/html/rfc7230#section-3.1.2
2020-03-19 09:07:44 +01:00
Andreas Rumpf
c74cee4e6a gc.rst that doesn't lie (#13686) 2020-03-19 06:41:54 +01:00
Andreas Rumpf
15ba765ebd enable --tlsEmulation:on for --gc:arc (#13685)
* enable --tlsEmulation:on for --gc:arc
* make -d:useMalloc work with --gc:arc --threads:on
2020-03-18 23:52:49 +01:00
Juan Carlos
a0ccfd16a7 Documentation GC (#13109)
* Update Documentation about GC, add ARC based on code observations and https://forum.nim-lang.org/t/5734#35562

* Rephrase 'Garbage Collector' on documentation, see #13331

* Peer Review Feedbacks

* When the body of a documentation section is all for garbage collector details then add 'for garbage collectors' to the title to identify they may not apply for ARC

* Change 'GC' for 'garbage collector'.

* Move 'Memory Management Strategies' at the top, without changes

* Move the info for RefC GC from 'Introduction' to 'RefC' section without changes, make 'Introduction' about Nims 'Multi-paradigm Memory Management Strategies'.
2020-03-18 22:55:39 +01:00
Arne Döring
88566cc651 allow category nimble-packages to test a single package (#13576) 2020-03-18 21:36:48 +01:00
Andreas Rumpf
fb641483f0 arc optimizations (#13325)
* scope based destructors
* handle 'or' and 'and' expressions properly, see the new test arc/tcontrolflow.nim
* make this branch mergable, logic is disabled for now
2020-03-18 16:57:34 +01:00
Araq
a96842aaeb removed .gitattributes as it only causes trouble for me 2020-03-18 14:43:39 +01:00
Andreas Rumpf
3f29911a94 new feature: --staticBoundChecks:on to enforce static array index checking (#10965) 2020-03-18 14:25:10 +01:00
Timothee Cour
ed263e174e fix #13524 astToStr now works inside generics (#13681) 2020-03-18 13:43:32 +01:00
Andreas Rumpf
a87062393a fixes #13622 (#13679) 2020-03-18 13:42:33 +01:00
Araq
3f1a85b7f0 fixes hash(HashSet) which was wrong as it didn't respect tombstones; refs #13649 2020-03-18 10:47:58 +01:00
Andreas Rumpf
5f6997794e fixes #13671 [backport] (#13678) 2020-03-18 10:37:36 +01:00
Jasper Jenkins
51bd442b88 fix when statements in inheritable generic objects (#13667) [backport] 2020-03-17 23:44:32 +01:00
Jasper Jenkins
122751aa52 add nnkMacroDef to RoutineNodes (#13676) 2020-03-17 23:41:07 +01:00
Andreas Rumpf
fe7b1dfb2a rewritten goto based exception handling; much cleaner implementation;… (#13677)
* rewritten goto based exception handling; much cleaner implementation; fixes #13668
2020-03-17 23:18:43 +01:00
Araq
b737bb4be0 fixes a bug for 'dup' and 'with'; they can now handle nested statement lists that can result from macros 2020-03-17 18:00:11 +01:00
cooldome
35d14095ed Fixes #13659 (#13674)
* fixes #13659

Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-03-17 16:36:38 +01:00
Timothee Cour
af9c852701 fix nim doc subdir/foo which was generating broken css; + other fixes (#13647)
* docgen: minor refactoring via docOutDir
* fix css for `nim doc subdir/foo` without --outdir nor -o
* tcompilesetting.nim: keep `git status` clean
* re-enable pkg nimgame2 that got fixed upstream
2020-03-17 13:44:37 +01:00
Jasper Jenkins
6a23452bf4 fix sets of scoped imported enums (#13666) 2020-03-17 10:47:27 +01:00
Andreas Rumpf
bec0522fca updated builds.sr.ht script according to their email (#13669) 2020-03-17 08:49:26 +01:00
Leorize
e5adaeed20 workflows/ci: disable
Since we got Azure Pipelines running, this will be a fallback pipeline.

Activate by removing the `.disabled` suffix
2020-03-17 08:48:42 +01:00
Leorize
5017320e7b gitattributes: fix tests for windows
Nim-generated files used in tests all end in LF, so we tell git to not
touch them. Should allow a Windows user to clone and run tests without
having to tweak their git settings
2020-03-17 08:48:42 +01:00
alaviss
6e4cd3e5bf .github/workflows: new CI pipeline (#13656)
* .github/workflows: new CI pipeline

As Azure Pipelines went offline, this will be our (temporary?)
replacement. This pipeline covers everything that Azure Pipelines does.

* workflows/ci: disable pipeline

* workflows/ci: properly disable the pipeline

* gitattributes: .txt used in tests should be LF-terminated

This avoids test failures when the compiler was cloned on an OS where
git attempts to convert LF->CRLF.

We target only .txt in tests/ as the minimum required to keep tests
running correctly.

* workflows/ci: re-enable for testing
2020-03-16 23:02:50 +01:00
Andreas Rumpf
955b31a7d9 fixes #13654 2020-03-16 23:00:43 +01:00
Araq
d375120c42 rename sfAlwaysReturn to sfNeverRaises 2020-03-16 19:05:33 +01:00
Andreas Rumpf
5ba5b5202a fixes #13661 (#13664) [backport] 2020-03-16 18:40:17 +01:00
Araq
b9b53b6ca1 fixes #13645 2020-03-16 16:24:50 +01:00
Andy Davidoff
0f672378ab fix .deprecated. object typedef crash (#13643)
* fix .deprecated. object typedef crash
* fixup a test that i don't understand
* disable the test rather than debug ci
2020-03-16 15:08:38 +01:00
Araq
a102eb5ef6 fixes #13646 2020-03-16 14:55:58 +01:00
Araq
3a6b470412 minor code style change 2020-03-16 14:55:58 +01:00
Araq
7205c3ebe2 minor code style changes 2020-03-16 14:55:58 +01:00
cooldome
613ea6e85e fixes #12747 [backport] (#13651)
* fixes #12747
* fix tests
* improve code style

Co-authored-by: cooldome <ariabushenko@bk.ru>
2020-03-16 13:40:40 +01:00
Kartik Saranathan
fe53f6ef4f fix typo (#13660) [ci skip] 2020-03-16 09:07:10 +01:00
Joey
fd3583803e Fix gdb scripts (#13658)
* Fix nim-gdb and rename to nim-gdb.bash
* Add symlink to nim-gdb.bash
* Fix windows debug script
* Add PR suggestions
* Make readlink check easier to maintain/understand
* Swap symlinks
2020-03-16 08:59:16 +01:00
alaviss
ae5094e143 azure-pipelines: walkaround issues with triggers (#13657)
See https://status.dev.azure.com/_event/179641421
2020-03-15 23:44:07 +01:00
Timothee Cour
6e0c06f50e fix #13218: avoid some irrelevant warnings for nim doc,rst2html,--app:lib, + other fixes (#13550)
* fix #13218: avoid some irrelevant warnings for nim doc,rst2html
* suppress warnRedefinitionOfLabel for nim doc
* lots of fixes for UnusedImport warnings
2020-03-13 20:42:41 +01:00
Timothee Cour
380a505507 azure-pipelines: use OSX 10.15 (was just enabled upstream) (#13546) 2020-03-13 14:02:47 +01:00
Araq
9eeb514dda disable nimgame2 for now 2020-03-13 11:50:39 +01:00
Andreas Rumpf
a6682de004 catchable defects (#13626)
* allow defects to be caught even for --exceptions:goto (WIP)
* implemented the new --panics:on|off switch; refs https://github.com/nim-lang/RFCs/issues/180
* new implementation for integer overflow checking
* produce a warning if a user-defined exception type inherits from Exception directly
* applied Timothee's suggestions; improved the documentation and replace the term 'checked runtime check' by 'panic'
* fixes #13627
* don't inherit from Exception directly
2020-03-12 23:44:33 +01:00
Miran
14b2354b7d rename lenTuple and lenVarargs (#13639)
* rename 'lenTuple' to 'tupleLen'

Rationale:
`lenTuple` is a tuple consisting of lengths (e.g. `(1, 5, 0)`),
`tupleLen` is a length of a tuple (e.g. `tupleLen((1, 5, 0) == 3`)

* rename 'lenVarargs' to 'varargsLen'

The same rationale as a previous commit. Consistency.
2020-03-12 20:07:02 +01:00
Clyybber
f0cd50f9c4 Change order of forwarded koch boot command line options, so as to be able to overwrite the nimcache location (#13637) 2020-03-12 16:15:46 +01:00
Timothee Cour
60a3e036f6 fix #13633 fix koch boot crashing regression (#13635) 2020-03-12 11:39:10 +01:00
Clyybber
2bb0ada797 Amend fix for #13633 (#13636) 2020-03-12 11:20:08 +01:00
Clyybber
d84c4bba9b Fix #13633 2020-03-12 11:01:03 +01:00
genotrance
bbc231f8e0 Fix #12676 (#13634) 2020-03-12 08:53:11 +01:00
Kaushal Modi
64995db4fd unicode.split: Fix the splitting when a Rune separator is used [backport] (#13629)
* unicode.split: Fix the splitting when a Rune separator is used [backport]

- Fixes https://github.com/nim-lang/Nim/issues/13628
- Ref https://irclogs.nim-lang.org/11-03-2020.html#20:01:34

* unicode.split: Remove the sepLen based logic.. resulted in wrong jumps
2020-03-12 00:41:45 +01:00
treeform
f2c7152770 Add more JS stuff to dom.nim (#13483)
* Add more JS stuff to dom.nim

* Make all links to docs doc comments.

* Fix minor textContent * space.

* Remove Selection object.

* More work on docs.

* Fixing links.

* Made the links be "see <docs>".
2020-03-11 23:24:56 +00:00
Clyybber
6b3098c378 Make listCmd honor hint:cc:off (#13606)
* Make listCmd honor hint:cc:off

* Tiny cleanup

* Tiny tiny cleanup

* VERY IMPORTANT: --hint:cc:on will overwrite --verbosity:0 :p

* Tiny cleanup

* Stupid

* Move displayProgressCC to where its required

* Tiny cleanup
2020-03-11 23:04:33 +01:00
Miran
70bd41dae0 fix #13310, Deque misbehaves on VM (#13625)
* fix #13310, Deque misbehaves on VM
* use 'when nimVM'
2020-03-11 17:30:36 +01:00
Timothee Cour
281e02fc79 fixes #13558: toDateTime buggy on 29th, 30th and 31th of each month; breaking change: do not use now to compute result, was undocumented and non-sensical (#13565) 2020-03-11 09:47:34 +01:00
Araq
f5f9243cc0 disable chronos testing for now 2020-03-11 09:28:10 +01:00
Araq
3aed8ff432 fixes async regression 2020-03-11 09:26:57 +01:00
Araq
60f8fdcdab fixes #13240 2020-03-11 09:26:57 +01:00
Araq
861a5340fe fixes #13519 2020-03-11 09:26:57 +01:00
Araq
b0684ec425 fixes #12757 2020-03-11 09:26:57 +01:00
Arne Döring
f95eef99a9 add expectIdent to macros (#12778)
* add expectIdent to macros

* apply feedback

* Update lib/core/macros.nim

Co-Authored-By: Clyybber <darkmine956@gmail.com>

* Update texpectIdent2.nim

* Update texpectIdent1.nim

Co-authored-by: Clyybber <darkmine956@gmail.com>
Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2020-03-11 08:27:31 +01:00
めぐみ発動機 (isVowel / GreenWing)
8e3a349561 fixed to jsonArrayEnd comment. (#13624)
typo: start → end
2020-03-11 08:26:10 +01:00
Arne Döring
2f557652d4 fix operators containing percent for VM usage (#13536)
* fixes #13513
* merge tarithmetics in tarithm
2020-03-11 01:01:25 +01:00
Timothee Cour
e64f1c7ee4 koch --nim:pathto/nim boot and koch boot --hint:cc:off now work (#13516)
* `koch boot --hint:cc:off` now works

* `koch --nim:pathto/nim boot` now works; code cleanup
2020-03-11 00:31:34 +01:00
Araq
3b7b017798 fixes #13607 2020-03-10 16:01:13 +01:00
Araq
9e2bce2a8c hotfix: make --useVersion:1.0 work 2020-03-10 16:01:13 +01:00
genotrance
ab5d962b50 Revert "Support cross compiling from host to host (#12859)" (#13591)
This reverts commit e4f7656772.
2020-03-10 15:58:27 +01:00
Andreas Rumpf
090ba1e3a3 fixes #13436 (#13615) 2020-03-10 00:52:46 +01:00
narimiran
7d07897a99 travis now only builds devel docs 2020-03-09 21:16:56 +01:00
Andreas Rumpf
ec5cef13cf fixes #13599 (#13614) 2020-03-09 18:12:52 +01:00
Andreas Rumpf
63af8ae53c fixes #13596 (#13612) 2020-03-09 15:32:38 +01:00
Miran
4aecc6b346 fix #12508, unaligned access on sparc64 (#13594) 2020-03-09 14:08:50 +01:00
Andreas Rumpf
dc94c81cb0 fixes #13605 (#13611) 2020-03-09 13:13:54 +01:00
Andy Davidoff
a693ce7765 surgical fix for #13319 (#13604) 2020-03-08 10:55:19 +01:00
Clyybber
eae31a7f8d Only print the link command when listCmd is active; fix docs (#13603) 2020-03-07 23:53:43 +01:00
Juan Carlos
6a5b3811e7 Add isValidFilename (#13561)
* Add os.isValidFilename

* Add os.isValidFilename

* Peer Review Feedbacks https://github.com/nim-lang/Nim/pull/13561#discussion_r388013139

* Peer Review Feedbacks https://github.com/nim-lang/Nim/pull/13561#issuecomment-595259568

* Add since to const

* Update the documentation comment

* Update the changelog

* Update lib/pure/os.nim

Co-Authored-By: Dominik Picheta <dominikpicheta@googlemail.com>

* Update lib/pure/os.nim

Co-Authored-By: Dominik Picheta <dominikpicheta@googlemail.com>

* Peer Review Feedbacks, Add more Tests

Co-authored-by: Dominik Picheta <dominikpicheta@googlemail.com>
2020-03-07 14:10:22 +00:00
Zed
e056298ceb Implement file streaming for httpclient's MultipartData (#12982)
* Add `uploadFile` to POST files by streaming them

* Use constant for \c\L

* Formatting

* Remove uploadFile

* Implement MultipartData file streaming

* Remove unnecessary var annotations

* Call string on TaintedStrings

Fixes #12789

* Move cl constant to httpcore

* Fix `request` inconsistencies

* Update documentaion

* Clean up

* Skip multipart formatting when there's 0 entries

* Remove extraneous `cl` from multipart formatting

* Update MultipartData `$` to match old behaviour

* Update comment

* Address comments
2020-03-06 18:55:45 +00:00
Andrea Ferretti
7ae0811818 Fix #13573 and #13574 (#13575)
* Fix https://github.com/nim-lang/Nim/issues/13573 and https://github.com/nim-lang/Nim/issues/13574

* Restored asynchttpserver
2020-03-06 18:38:56 +00:00
alaviss
4bd388ad58 Revert "nimsuggest: don't add CRLF to replies (#13545)" (#13597)
This reverts commit a974684b14.

The CRLF was to separate between each response, and removing them causes
the responses to not be splitted correctly.

I didn't notice that it was in a loop when I made the #13545.
2020-03-06 19:29:28 +01:00
Dominik Picheta
ec8a17cc86 Revert broken asynchttpserver FutureStream additions.
As discussed in #13394, these changes cannot work. Reverted via

```
git revert --no-commit 5bf571f061
git revert --no-commit abd660c407
git revert --no-commit 955465e5f4
git commit
```
2020-03-06 11:52:30 +01:00
Timothee Cour
b80d293a3f close #12704 by adding a test (tuple codegen error) (#13592)
* close #12704 by adding a test

* move test to tests/metatype/ttypedesc2.nim
2020-03-06 08:55:53 +01:00
Andreas Rumpf
cb0f7c5d9e Removed simpleGetOrDefault (#13590) 2020-03-05 21:03:39 +01:00
Andreas Rumpf
83e715c5b6 fixes #5170 (#13589)
* fixes #5170

* make tests green
2020-03-05 16:02:34 +01:00
Andreas Rumpf
62c113ebc7 fix #13579 joinPath("/foo/", "../a") is now /a (#13586) 2020-03-05 15:31:22 +01:00
Varriount
357edd86b4 fix nightlies builds on Windows (#13587)
Before the files that should have been ignored weren't ignored
because of different dir separator ('\' vs '/') on Windows.
2020-03-04 14:44:42 -05:00
alaviss
a974684b14 nimsuggest: don't add CRLF to replies (#13545)
This is already sent by replTcp after the message is sent.
2020-03-04 15:56:40 +01:00
Andreas Rumpf
a0eca75182 sink parameter inference for types that have destructors (#13544)
* ensure capitalize doesn't take an inferred sink parameter

* sink parameter inference: first version, for now disabled. Changed that sink parameters can be consumed multiple times in order to adhere to our spec.

* sink inference can now be disabled with .nosinks; sometimes for proc type interop this is required

* fixes yet another critical DFA bug

* better implementation that also understands if expressions etc

* document sink parameter inference and allow for global disabling
2020-03-04 14:28:53 +01:00
Andreas Rumpf
614fb7567c std/compilesettings implementation (#13584)
* Implement compileSetting() and compileSettingSeq()
* Change from magic to vmop
* better design for querySetting

Co-authored-by: genotrance <dev@genotrance.com>
2020-03-04 13:46:42 +01:00
Juan Carlos
0809098971 Nimpretty Fix negative indent breaks code (#13580) 2020-03-04 10:27:52 +01:00
Timothee Cour
9fa070b1dc fix hintSuccess: out was wrong for nim doc without -o flag (#13569) 2020-03-04 10:26:56 +01:00
Miran
9961d1f67d fix #13531 by adding a test (#13581) 2020-03-04 10:25:59 +01:00
hlaaftana
34c16f5eca fix #13409: Document as infix operator (#13570) 2020-03-04 07:50:36 +01:00
narimiran
3ca8f0bde6 [ci skip] important_packages: change the order in commented out packages too 2020-03-04 07:15:34 +01:00
Araq
8705ee7015 ARC hotfix; proper destruction of seqs and strings after a move 2020-03-03 23:03:33 +01:00
genotrance
f8175688a3 Fix docgen snippet numbering (#13507) 2020-03-03 20:52:16 +01:00
Miran
e8c057fb27 important_packages: change the order of arguments in the template (#13577)
Leads to a cleaner and less confusing code - an empty command
doesn't mean 'nimble test' anymore.
2020-03-03 16:25:59 +01:00
Arne Döring
eb42f38088 Remove dead magics (#13551) 2020-03-03 12:42:43 +01:00
Timothee Cour
31332bca45 workaround refs #13563 freebsd CI (#13564) 2020-03-02 22:30:41 -05:00
Timothee Cour
451b724c40 make genericParams support static[T] generic params (#13433)
* make genericParams support static[T] generic params

* WrapStatic => StaticParam
2020-03-02 18:05:14 +01:00
Timothee Cour
27241fda23 fix #13528 nimgrep --word now works better with operators (#13537) 2020-03-02 17:55:17 +01:00
PMunch
05e9473f80 Add signatures object to jsondoc for routine types (#13530)
jsondoc is meant to be read by computers, but yet the signatures of
procedures where simply a string of the whole thing. This adds a
signature object that unpacks this information into an object so it's
easier to analyse the documented signatures.
2020-03-02 17:52:42 +01:00
Timothee Cour
653de5f27a fix broken nim CI, disable blscurve (#13555) 2020-03-02 10:26:10 +01:00
Timothee Cour
22d1ba4be7 fixes #13543 and added times.isLeapDay (#13547) 2020-03-01 21:56:20 +01:00
hlaaftana
525ab5a497 Document import/include outside of top level semantics (#13548) 2020-03-01 21:52:29 +01:00
cooldome
0f1a4ac96c make it possible to pass linker options for vcc (#13535) [backport] 2020-02-29 18:57:00 +01:00
cooldome
c79df2fb6a EndsInNoReturn in expressions extension, fixes #13490 (#13520)
* fix #13490
2020-02-28 09:55:06 +00:00
cooldome
25dc5f76e0 fixes #12627 (#13521)
* fixes #12627
2020-02-28 09:54:17 +00:00
Timothee Cour
1056f9ecff properly handle note override logic/verbosity/config/cmdline using modifiedyNotes, cmdlineNotes 2020-02-27 13:22:18 +01:00
Timothee Cour
c1cbf94e2d remove isCmdLine; use passCmd1 2020-02-27 13:22:18 +01:00
Timothee Cour
ce36fdc897 correctly honor cmdline --hint:conf:on/off ; correctly show Conf hints in order 2020-02-27 13:22:18 +01:00
Ganesh Viswanathan
96bffadf60 Fix #9405 - cfg and nims run in sync 2020-02-27 13:22:18 +01:00
Timothee Cour
73f5f1e80c save another 33s of CI for tests/gc/gcleak.nim 2020-02-27 13:19:31 +01:00
Timothee Cour
fdc5925cbd CI tests run faster: save 120s in azure machines, 335s on local OSX 2020-02-27 13:19:31 +01:00
Timothee Cour
9b8c9abead revert changes to tests/gc/gcleak2.nim 2020-02-27 13:19:31 +01:00
Timothee Cour
81b0718a8f make CI tests faster + more precise 2020-02-27 13:19:31 +01:00
solo989
e84e01cb8c Update pegs.nim to work at compiletime. No range errors. (#13459) 2020-02-27 11:08:57 +01:00
Timothee Cour
6a0e87eb38 cleanup Ordinal (#13501) 2020-02-27 10:43:13 +01:00
Timothee Cour
42dad3a836 tables/sharedtables/intsets/etc: fix #13496, #13504, #13505; add lots of tests (#13498) [backport]
* fix #13496 handle tombstones
* add test
* more tests
* fix #13504; add SharedTable tests
* fix #https://github.com/nim-lang/Nim/issues/13505 intsets.missingOrExcl silently gave wrong results sometimes
* add test for tintsets
2020-02-26 22:07:09 +01:00
Miran
9a93f73983 docgen: don't create compiler's docs + cleanup (#13509) 2020-02-26 20:37:27 +01:00
Andreas Rumpf
d55bbefdcc added operateOn to sugar.nim to give Nim the chaining mechanism it de… (#13092)
* implemented the with stdlib module as specified in https://github.com/nim-lang/RFCs/issues/193
* change sugar.outplace to sugar.dup according to https://github.com/nim-lang/RFCs/issues/193
* changelog update
2020-02-26 20:36:06 +01:00
Kaushal Modi
f091b5a0ee xmltree: Make indentation consistent with any num of children nodes (#13482)
Ref: https://forum.nim-lang.org/t/5972
2020-02-26 11:41:44 +01:00
Timothee Cour
0c312ad898 fix #13455 ; joinPath(a,b) now honors trailing slashes in b (or a if b = "") (#13467)
* fix #13455 ; joinPath(a,b) now honors trailing slashes in b (or a if b = "")
* fix test windows
2020-02-26 11:25:27 +01:00
Timothee Cour
11db28bc61 runCI: logs now show CPU/OS/etc info to be self contained (#13486) 2020-02-26 10:44:23 +01:00
Timothee Cour
bd90199a2f fix #8312 --hints:off and --warnings:off now honored everywhere (#13489) 2020-02-26 10:26:47 +01:00
Juan Carlos
94b0d6bb63 Documentation staticRead maximum file size limits (#13485) 2020-02-26 10:01:23 +01:00
Arne Döring
5d2483fb64 fix #13479 (#13503) 2020-02-26 09:51:07 +01:00
Kaushal Modi
e4ed19c12f [backport] tut1: Update the proc overloading examples (#13497) [skip ci] 2020-02-25 21:19:51 +01:00
Timothee Cour
db540a0223 fix #13449 texitcode flaky on windows (#13487) 2020-02-25 17:49:16 +01:00
narimiran
c444ab9a54 make devel green again: tnetdial still doesn't work on Travis 2020-02-25 08:46:08 +01:00
Timothee Cour
1cf5c280e3 only enable linenoise for -d:nimUseLinenoise (#13478)
* only enable linenoise for -d:nimUseLinenoise

* fixup
2020-02-24 11:06:39 +01:00
hlaaftana
84e78b4ffc Minor doc change in macros, future -> sugar (#13475) [ci skip] 2020-02-24 09:57:15 +01:00
Miran
3e8858d694 add more files to the ignore list, hopefully fixes nightlies on windows (#13474) 2020-02-24 09:41:28 +01:00
Andrey Makarov
3dad130034 fix 3 minor bugs in joinPath (see #13455) (#13462) [backport] 2020-02-23 20:22:46 +01:00
hlaaftana
13d292786e Remove genToArray in jsgen, a PHP remnant (#13466) 2020-02-22 20:04:46 +01:00
Lee Matos
c11b91d52d Update advopt.txt to include link to nim cache docs (#13464) 2020-02-22 09:09:04 +01:00
Timothee Cour
a43583f9c8 relativePath("foo", "foo") is now ".", not "" (#13452) 2020-02-22 09:07:53 +01:00
hlaaftana
1276e386fe Consider proc as a pointer type in options (#13460)
* Consider proc as a pointer type in options

* Add version annotation for SomePointer having proc in options

* Log procs as pointers for options in changelog
2020-02-21 23:14:55 +01:00
Andreas Rumpf
0d219d2c67 fixes #13457 (#13458) 2020-02-21 21:06:41 +01:00
Timothee Cour
e05aca8734 make unzip faster: seq[i]=val can be 7X faster than seq.add(elem) (#13448) 2020-02-21 17:26:52 +01:00
Araq
1d90d9816b fixes #13444 2020-02-21 16:58:30 +01:00
Joey
3667fd9f42 Make gdb script work on mac and linux; add windows gdb script (#13453) 2020-02-21 08:53:05 +01:00
genotrance
7a2b623d2a Fix #8648 - use parent streams to avoid hang (#13445) 2020-02-20 23:04:48 +01:00
Kaushal Modi
bb777fef76 Add sequtils.unzip to complement sequtils.zip (#13429) 2020-02-20 19:15:34 +01:00
Manav
479f4ca6a3 Fixed non-working examples in Manual: Exception Handling (#13424) 2020-02-20 15:16:19 +01:00
Clyybber
87dd19453b Remove testutils (#13435) [backport] 2020-02-19 23:02:08 +01:00
Timothee Cour
8c22518d67 [backport] pseudorandom probing for hash collision (#13418) 2020-02-19 17:19:55 +01:00
Timothee Cour
273a93581f fix incorrect lenTuple implementation (#13423) 2020-02-19 11:07:17 +01:00
alaviss
d1f9f11245 manual: documents changes regarding dynlib (#13425)
* manual: documents changes regarding dynlib

Closes #13416

* manual: clean up sentence phrasing
2020-02-18 19:44:54 +01:00
cooldome
046bb0b881 stdlib/system: add sink and move (#13283) 2020-02-18 19:43:26 +01:00
Nな人(N na hito)
8f73753a2d Update LICENSE (#13421) 2020-02-17 18:40:39 +01:00
Ico Doornekamp
73553621a1 Improved assertion error messages on usage of JsonNode iterators on wrong kinds (#13389) 2020-02-17 09:00:25 +01:00
Khronos
006fe4cfc4 Fix vertical tab in JSON. (#13399)
'\v' is not injected in JSON anymore
2020-02-17 00:39:19 +01:00
Juan Carlos
ba25f849a6 Add browsers.osOpen (#12901)
* Add osOpen alias for the operating system specific open command

* Add `--git.devel` option to the documentation
remove unused import (#12900)

fix json regression D20191212T144944 (#12902) [backport]

Peer Review Feedback https://github.com/nim-lang/Nim/pull/12901#issuecomment-565851680

Merge branch 'devel' of https://github.com/nim-lang/Nim into osopen

Peer Review Feedback https://github.com/nim-lang/Nim/pull/12901#issuecomment-565851680

Update lib/pure/browsers.nim

Co-Authored-By: Dominik Picheta <dominikpicheta@googlemail.com>
Peer Review Feedback https://github.com/nim-lang/Nim/pull/12901#discussion_r358492316

allow typed/untyped in magic procs (#12911)

NaN floatFormat with clang_cl  (#12910)

* clang_cl nan floatFormat

* format

add $nimeq for gdb (#12909)

ARC: cycle detector (#12823)

* first implementation of the =trace and =dispose hooks for the cycle collector
* a cycle collector for ARC: progress
* manual: the .acyclic pragma is a thing once again
* gcbench: adaptations for --gc:arc
* enable valgrind tests for the strutils tests
* testament: better valgrind support
* ARC refactoring: growable jumpstacks
* ARC cycle detector: non-recursive algorithm
* moved and renamed core/ files back to system/
* refactoring: --gc:arc vs --gc:orc since 'orc' is even more experimental and we want to ship --gc:arc soonish

Cleanup leftovers of #12911(#12916)

Fix single match output (#12920)

fixes #12899 (#12921)

* fixes #12899

* fixes regression: destroy global variables in reverse declaration order, closureleak test relies on it

Implement NixOS distro check (#12914)

Better case coverage error message for alias and range enum (#12913)

fix error in assertions document (#12925) [backport]

fix cmdline bugs affecting nimBetterRun correctness (#12933) [backport]

fix #12919 tasyncclosestall flaky: Address already in use (#12934)

system.reset is no longer magic (#12937)

It has now means setting x to default for new and old runtime alike
Fix #12785 (#12943)

* Fix #12785 and add test

* better variable name

update documentation for `closureScope` and `capture` (#12886)

fixes #12735 on osx, call dsymutil for debug builds (#12931)

* fix #12735 osx: dsymutil needs to be called for debug builds
* also write dsymutil command to extraCmds in json build file

Auto-initialize deques (#12879)

case coverage error message for `char` (#12948)

lenVarargs: number of varargs elements (#12907)

docs: tiny style improvements

added guidelines for evolving Nim's stdlib

fixes a bug that kept sugar.collect from working with for loop macros [backport]

fixes #12826

fixes a regression

a better bugfix

fixes a test case

fixes a silly regression

fixes the distros.nim regression

ported channels to ARC

ported osproc.nim to ARC

ported re.nim to ARC

ARC: default to a shared heap with --threads:on

osproc: fixes regression

fixes another regression

fixes #12945 (#12959)

minor refactorings

Fixes stackoverflow links in readme (#12963) [backport]

Allow customize Host header
[ci skip] docfix .. < => ..< (#12981) [backport]

parsecfg: retain CRLF line breaks, fixes #12970 (#12971)

generic stack trace overriding mechanism (#12922)

* libbacktrace support

* switch to a generic stack trace overriding mechanism

When "nimStackTraceOverride" is defined, once of the imported modules
can register its own procedure to replace the default stack trace
generation by calling `registerStackTraceOverride(myOwnProc)`.

Tested with `./koch boot -d:release --debugger:native -d:nimStackTraceOverride --import:libbacktrace`
for the compiler itself and `./bin/nim c -r -f --stacktrace:off --debugger:native -d:nimStackTraceOverride --import:libbacktrace foo.nim`
for an external program.

* make the StackTraceOverrideProc {.noinline.}

Added fix for handling TaintedStrings in streams and httpclient (#12969)

* Added fix for taint mode in streams and httpclient

* Removed taintMode export from system.nim

Check pqntuples > 0 in getValue. Fixes #12973 (#12974)

c_fflush() the rawWrite() buffer (#12987)

Stack traces on an unbuffered stderr get out of sync with line-buffered
stdout - usually on Windows terminals or CI logs. This fixes it by
calling C's fflush() on the output buffer in the procedure used for
printing stack traces.
fixes #12989

Revert "fixes #12989"

This reverts commit 928c2fee06.

fixes #12965 (#12991)

fixes #12989 (#12992)

* fixes #12989
* Revert "remove unwanted changes"

This reverts commit 501829732a.

fixes disruptek/nimph#102 multi-level nim.cfg use (#13001) [backport]

--exception:goto switch for deterministic exception handling (#12977)

This implements "deterministic" exception handling for Nim based on goto instead of setjmp. This means raising an exception is much cheaper than in C++'s table based implementations. Supports hard realtime systems. Default for --gc:arc and the C target because it's generally a good idea and arc is all about deterministic behavior.

Note: This implies that fatal runtime traps are not catchable anymore! This needs to be documented.
fix #12985 {.push.} now does not apply to generic instantiations (#12986)

Sink to MemMove optimization in injectdestructors (#13002)

remove default argument for readLines (#12807) [backport]

fixes #12978 (#13012)

Fix typo (#13015) [backport]

fixes #12961 (#13019)

fixes #12956 (#13020)

fix #12988 (#13022)

fix #12988
Fixes #13026 (#13028)

fixes #12964 (#13027)

fixes #13032

VM: support importc var, ptr/pointer types, cast int <=> ptr/pointer (#12877)

* VM: allow certain hardcoded special var variables at CT
* VM: allow all importc var, cast[int](ptr)
* fix tests tests/vm/tstaticprintseq.nim, tests/cpp/t8241.nim
* VM: == works for ptr/pointer nodes
* bugfix: ==, cast now also works for pointer, not just ptr
* VM supports cast PtrLikeKinds <=> PtrLikeKinds / int
* improve cname handling
* fixup + bug fix
* VM: support cast from ref to int
* address comment: opcLdGlobalDeref => opcLdGlobalDerefFFI
* defensive check against typ == nil

fix enumtostr crash for enum-range (#13035)

fixes #13013, reverts previous changes to readLines() (#13036) [backport]

* Revert "remove default argument for readLines (#12807) [backport]"

This reverts commit c949b81efd.

reprjs: style changes

fixes #12996

Rst parser respect `:start-after:` and `:end-before:` in `include` directive (#12972)

* [FEATURE] rst parser respect :start-after: in include

Rst parser now respects `:start-after:` and `:end-before:` attributes
for `include` directive.

* [DOC] include directive parsing proc update

* [TEST] Added unit tests for include rst directive in `rst` module

Allow `-o` option for `buildIndex` (#13037) [backport]

Addressing #12771

This is also included in the docgen documentation [here](https://nim-lang.org/docs/docgen.html) but its not respected as reported in the issue.
[cleanup] remove disabled (and obsolete) ttypetraits; rename ttypetraits2 => ttypetraits (#13041)

* remove disabled (and obsolete) ttypetraits; rename ttypetraits2 => ttypetraits

* D20200105T085828 fix super strange bug that causes CI to fail: builds.sr.ht with: `Error: Settle timed out after 120 attempts`

Continue #13002 (#13021)

testament/important_packages dont run hts (#13052)

Modify the test command for nimly (nimble-package) (#13053)

clean up deprecated stuff and unused imports in tests (#13059)

--styleCheck:hint now works (#13055)

[easy] --hint🔗on now shows link cmd instead of nothing (#13056)

* --hint🔗on now shows link cmd instead of nothing

* update doc for --listCmd

add pqserverVersion,pqconnectionNeedsPassword,pqconnectionUsedPassword (#13060)

basename supports pragmaexpr (#13045)

* basename supports pragmaexpr

* update changelog

distinctBase type trait for distinct types (#13031)

make SuccessX show project file + output file (#13043)

* make SuccessX show project file + output file
* address comments
* fix test and add `result.err = reNimcCrash` otherwise hard to see where reNimcCrash used
* address comments

move entries from the wrong changelog file [ci skip]

fix crash due to errant symbols in nim.cfg (#13073) [backport]

Deleted misplaced separator (#13085) [backport]

Misplaced separator, which was constantly breaking compilation on Haiku OS, was deleted.
take the one good idea from --os:standalone and enable it via -d:StandaloneHeapSize (#13077)

remove all remaining warnings when build nim (with -d:nimHasLibFFI) (#13084)

* cleanup deprecations in evalffi + elsewhere

* remove dead code getOrdValue64

Use '__noinline' instead of 'noinline' for N_NOINLINE gcc attribute, this prevents clashes with systems where 'noinline' might be already defined (#13089)

Fix error check code in osproc (#13090) [backport]

fixes #13072; no test case because it will be added later with more exception handling related bugfixes

fixes #13070

typetraits: fixes #6454; genericParams; added lenTuple; added tuple type get (#13064)

[backport] system/io.nim fix wrong documentation comment [ci skip]

fixes an asyncftpclient bug; refs #13096 [backport]

System cleanup, part 1 (#13069)

* system.nim: mark what every .pop does

* system.nim: un-nest when statements

[backport] fix #12813, fix #13079 (#13099)

Correctly remove a key from CountTable when it is set to zero.
more arc features (#13098)

* config update
* ARC now supports 'repr' and 'new' with finalizers is supported

Remove some unused/disabled OpenSSL functions (#13106)

Add link to posix_utils.html in posix.nim (#13111)

VM FFI: write(stderr, msg) and fprintf(cstderr, msg) now work at CT (#13083)

fix the ftp store function read the local file bug (#13108) [backport]

* Update asyncftpclient.nim

When use newStringOfCap function not have assign memory for the string data,so if use this address the fault is rasise.

* complelete the bugfix

fix rtti sizeof for varargs in global scope (#13125) [backport]

fixes #13122 (#13126)

* fixes #13122

* moved tests to where they belong

fixes #13112 (#13127)

* improve line error information

* fixes #13112

Expose more openSSL methods. (#13131)

fixes #13100 nim doc now treats `export localSymbol` correctly (#13123) [backport]

* fix #13100 nim doc now treats `export localSymbol` correctly
* use owner instead

fixes #13119 (#13128)

* fixes #13119
* fixes a regression

fixes #13105 (#13138)

fixes #10665 (#13141) [backport]

pass platform argument only if vccexe is used (#13078)

* pass platform only if vccexe is used
* fixes #12297

fixes #13104 [backport] (#13142)

fixes #9674 [backport] (#13143)

Fix typo in doc/destructors.rst (#13148)

Added 'ansic' os support for minimal (embedded) targets (#13088)

* os:any implementation
* os:asny: omit flock/funlock calls in echoBinSafe
* Disabled default "unhandled expection" reporting for `--os:any` to reduce
code size. Added unhandledExceptionHook instead which can be used to get
a notification from Nim and handle it from the application.

System cleanup, part 2 (#13155)

* create basic_types, arithmetics, exceptions, comparisons
* create setops.nim
* create memalloc.nim
* create gc_interface.nim
* create iterators_1.nim

export normalizePathEnd (#13152)

successX now correctly shows html output for `nim doc`, `nim jsondoc`; fix #13121 (#13116)

* successX now correctly shows html output for nim doc
* fixes #13121
* fixup hintSuccessX to be less weird

ARC: misc bugfixes (#13156)

* fixes #13102
* closes #13149
* ARC: fixes a move optimizer bug (there are more left regarding array and tuple indexing)
* proper fix; fixes #12957
* fixes yet another case object '=' code generation problem

CI fix timeout error (#13134)

Remove obsolete code from osalloc (#13158)

style fix: change 'JS' to 'js' to make it consistent (#13168)

Working towards arc codegen (#13153)

fixes #13029
fixes #12998 nim doc regression (#13117)

fix tsizeof3 for aarch64 (#13169)

Cleanup DFA (#13173)

Fix docs (#13176)

fixes #13095 (#13181)

* fixes #13095

* fix typo

make case-object transitions explicit, make unknownLineInfo a const, replace a few magic numbers with consts (#13170)

ARC works for async on Windows (#13179)

make sink operator optional (#13068)

* make sink operator optional

* bug fix, add changelog entry

* Trigger build

* fix one regression

* fix test

* Trigger build

* fix typos

Fix docs for subdirs too (#13180)

* Fix doc subdirs
* Extract to helper proc, and fix on windows

followup on #10435 : should be diff, not show (#13162)

fixes #13157

refs #13054 correctly handle {.exportc,dynlib.} and {.exportcpp,dynlib.}  (#13136)

* refs #13054 correctly handle {.exportc,dynlib.} and {.exportcpp,dynlib.}
* put back NIM_EXTERNC for N_LIB_EXPORT; causes issues with compilerproc

fixes #13144 (#13145)

* fixup: genscript now does not copy nimbase.h but uses -I$nim/lib

times: toUnixFloat, fromUnixFloat (#13044)

maybe: allows optional chaining of field access and indexing when LHS i snil (#13023)

* maybe: allows optional chaining
* fix tools/kochdocs.nim
* improve semantics to distinguish valid from invalid values
* for now, wrapnil, isValid, unwrap are not exported

fix docs + API for fieldPairs, fields (#13189)

more on arc codegen (#13178)

* arc codegen for union type

* add more tests

* fix offsetof

* fix tsizeof test

* fix style

Add link to packaging.html (#13194)

Fixes #13186 (#13188)

fixes #13195

revert last commit

Merge branch 'devel' of https://github.com/nim-lang/Nim into devel

Revert "fixes #13195"

This reverts commit cd7904f2b2.

fixes #13110 (#13197)

fixes #13195 (#13198)

* fixes #13195

* extra fix

* fix typo

compiler/ccgtypes: hide exportc proc unless it has dynlib (#13199)

This hides most of stdlib's internal functions from resulting
binaries/libraries, where they aren't needed on *nix. Static libraries
are not affected by this change (visibility doesn't apply to them).
fix range[enum] type conversion (#13204) [backport]

Idxmin & idxmax, continuation (#13208)

* Add idxmin() which returns the index of the minimum value

* Add idxmax() which returns the index of the maximum value

* Add tests for idxmin()

* Add tests for idxmax()

* Remove initialization of result = 0

* Adds overloading for arrays (no enums indexed arrays yet)

* Add support for enum index arrays

* Fix tests with enum

* Fix tests for idxmax

* Change names of the procedures to minIndex and maxIndex

* address Araq's comments:

- remove 'array' versions
- add .since pragma
- return 'int' instead of 'Natural'
- add changelog entry

Co-authored-by: Federico A. Corazza <20555025+Imperator26@users.noreply.github.com>

fix #13211 relativePath("foo", ".") (#13213)

fixes a critical times.nim bug reported on IRC [backport] (#13216)

httpclient, maxredirects to Natural, newHttpClient/newAsyncHttpClient add headers argument instead of hardcoded empty (#13207)

added note to re constructor regarding performance (#13224)

Since I was new to regex I did not know that there is a compilation going on with ``re"[abc]"`` constructor and so I followed the other examples in the docs blindly, that is I just put the constructor directly in the arguments of match, find, etc., which was inside a loop and then wondered why my performance was so bad. Of course putting it outside the loop made it vastly more performant. People like me would benefit from the small note I added I would think :)
[backport] Documentation Fix #12251 (#13226) [ci skip]

[backport] times/getClockStr(): fix mistake in doc (#13229) [ci skip]

new os.isRelativeTo (#13212)

[backport] Fix typo and improve in code-block of 'lib/pure/parseutils.nim' (#13231) [ci skip]

[backport] fix #11440, add docs to isNil for seq types needing nilseq (#13234) [ci skip]

VM: allow overriding MaxLoopIterations without rebuilding nim (#13233)

kochdocs: use a glob instead of hardcoded list; generate docs for compiler/; bugfixes (#13221)

* kochdocs: use a glob instead of hardcoded list; generate docs for compiler/; bugfixes
* fixup after #13212 isRelativeTo got merged

fix lots of bugs with parentDir, refs #8734 (#13236)

Unexport even more symbols (#13214)

* system/gc: don't export markStackAndRegisters

* compiler/cgen: unexport internal symbols

As these functions are Nim-specific walkaround against C's optimization
schemes, they don't serve any purpose being exported.

* compiler/cgen: don't export global var unless marked

* compiler/ccgthreadvars: don't export threadvar unless marked

* tests/dll/visibility: also check for exports

This ensure that these changes don't break manual exports.

* compiler/cgen: hide all variables created for constants

* compiler/ccgtypes: don't export RTTI variables

* compiler/ccgexprs: make all complex const static

* nimbase.h: fix export for windows

* compiler/cgen, ccgthreadvars: export variables correctly

For C/C++ variables, `extern` means that the variable is defined in an
another unit. Added a new N_LIB_EXPORT_VAR to correctly export
variables.

Removed lib/system/allocators.nim. seqs_v2 and strs_v2 now uses allocShared0. (#13190)

* Cleanup, remove lib/system/allocators.nim. seqs_v2 and strs_v2 now use
allocShared0 by default.

* Fixed -d:useMalloc allocShared / reallocShared / deallocShared. These now use the alloc/dealloc/realloc implementation that also takes care of zeroing memory at realloc.

* Removed debug printfs

* Removed unpairedEnvAllocs() from tests/destructor/tnewruntime_misc

* More mmdisp cleanups. The shared allocators do not need to zero memory or throw since the regular ones already do that

* Introduced realloc0 and reallocShared0, these procs are now used by
strs_v2 and seqs_v2. This also allowed the -d:useMalloc allocator to
drop the extra header with allocation length.

* Moved strs_v2/seqs_v2 'allocated' flag into 'cap' field

* Added 'getAllocStats()' to get low level alloc/dealloc counters. Enable with -d:allocStats

* *allocShared implementations for boehm and go allocators now depend on the proper *allocImpl procs

[backport] documentation: Add channels examples (#13202) [ci skip]

[backport] Make all parseutils examples auto-checking (#13238)

- Also fix one example's output (ikString -> ikStr, ikVar instead of ikExpr)
Updated 'nim for embedded systems' section to use --os:any and --gc:arc (#13237)

* Updated 'nim for embedded systems' section to use --os:any and --gc:arc

* Added section about size optimization to embedded systems

Remove name attribute from docutils.nimble (#13239)

Fixes asyncftpclient multiline reading, fixes #4684 (#13242)

Previously, the 4th character of `result` was checked for `'-'` every time, instead of each new line.

Also made it work for taint mode.
Fix typo for literal `[` (#13243)

The literal value for the `tkBracketLe` token was incorrectly set to `]` rather than `[`. I've had a quick glance at the code and it doesn't look like this change will affect anything at all, but I haven't tested yet - let's see if the CI explodes...
Add "origin" to window.location (#13251)

Add "origin" to window location: https://www.w3schools.com/jsref/prop_loc_origin.asp
nim dump: add libpath (#13249)

contributing docs: symbols need package prefix; changed allocStats to nimAllocStats (#13247)

testament/azure: major rewrite (#13246)

This commit features a major rewrite of Azure Pipelines integration,
turning the spaghetti it originally was into something maintainable.

Key changes:
- No longer requires a ton of hooks into testament.
- Results are now cached then bulk-uploaded to prevent throttling from
  Azure Pipelines, avoiding costly timeouts.
- A low timeout is also employed to avoid inflated test time.
- The integration is now documented.
Cleaned up mmdisp.nim, moved implementations into lib/system/mm/ (#13254)

make goto based exceptions available for 'nim cpp' (#13244)

* make goto based exceptions available for 'nim cpp'
* optimize seq.add to be comparable to C++'s emplace_back

ARC: remove unnecessary code

ARC: optimize complete object constructors to use nimNewObjUninit

make nre compile with --gc:arc

Rename isNilOrWhitespace to isEmptyOrWhitespace and make it use allCharsInSet (#13258)

* Rename isNilOrWhitespace to isEmptyOrWhitespace

* Make isEmptyOrWhitespace use allCharsInSet(Whitespace)

Clearer final objects error; fixes #13256 (#13257)

scrollTop must be settable (#13263)

* scrollTop must be assignable

Make scrollTop settable

* add missing export

fixes #13219 (#13272)

fixes #13281 (#13282)

* fixes ##13281

* add comment to test

unittest add resetOutputFormatters proc (#13267)

* add resetOutputFormatters

* remove space

* resolve comments

TlSF Alloctor: use less memory for --gc:arc (#13280)

Tiny since cleanup (#13286)

nimv2 widestring indexing (#13279)

Repr v2 progress (#13268)

* progress on repr_v2

* repr progress

* add ref objects with distrinct

* fix failing tests

refactor htmldocs; gitignore it

removed unused import

fix stdout(etc) for emscripten

csize => csize_t for sysctl

Thread attributes should be destroyed using the pthread_attr_destroy() (#13293)

On some OSes (such as FreeBSD or Solaris), pthread_attr_init allocate
memory. So it is necessary to deallocate that memory by using
pthread_attr_destroy.
fix critical bug discovered by #11591 (#13290) [backport]

miscellaneous bug fixes (#13291)

* fix for emscripten etc

* add testcase for #13290

* replace deprecated isNilOrWhitespace

CT FFI: fix for windows; fix case transition; error msg shows more useful context (#13292)

* evalffi: fix case transition
* evalffi: fix for windows
* evallffi: `cannot import` errmsg now also shows which library it tried to import symbol from

refs #8391 std/os now shows runtime context for raiseOSError exceptions (#13294)

* refs #8391: fix errmsg for setCurrentDir

* raiseOSError calls for copyFile

* refs #8391 std/os now shows runtime context for raiseOSError exceptions

build_all.sh: building csources 5X faster thanks to make -j (#13300)

* build_all.sh: building csources 5X faster thanks to make -j
* fix for freebsd
* use OS-dependent formula to get number of logical cores
* make is an optional dependency

Fix capture for object types (#13315)

* Fix capture for object|tuple|... types

* Add test case

Quote nim executable before executing. (#13316) [backport]

In case nim executable is located in PATH containing spaces.

fixes #13311
ReSync with devel

Make build_all.sh more portable and a bit simpler (#13308)

koch: enable checks in the compiler when running CI (#13323)

fix #13132 tnetdial (#13318)

enable testing -d:nimHasLibFFI mode (#13091)

Fix #10717, fix #13284 (#13307)

Fixed codegen for constant cstring with --gc:arc (#13326)

* Fixed codegen for constant cstring with --gc:arc, fixes  #13321

* Added test for #13321

Option to allow the request body to be processed outside the asynchttpserver library. (#13147)

Allow the request body to be processed outside the asynchttpserver library to break big files into chunks of data. This change does not break anything.

build_all.sh update (#13320)

* Don't overload the system, don't crash when you can't determine the CPU count and don't rely on bash

* Extract to variable

* Limit number of spawned jobs for systems with weak IO

* Use proper arithmetic braces

contributing.rst: Add a special rule for 'outplace'-like features

[backport] -d:danger should imply -d:release (#13336)

nim secret: support linenoise when available (#13328)

fix #13150 `nim doc --project` now works reliably (#13223)

* fix #13150 `nim doc --project` works with duplicate names and with imports below main project file

* add to help; fixup after #13212 isRelativeTo got merged
* fix test tests/compilerapi/tcompilerapi.nim
* remove nimblePkg field; compute on the fly instead
* kochdocs: compiler docs now under compiler/
* --docRoot now has smart default: best among @pkg, @path

make monotimes have zero overhead if you don't use it (#13338) [backport]

fix #13349 regression: isNamedTuple now works with generic tuples (#13350)

fixes #13269 (#13344)

adding sqlite3 backup functions (#13346)

* adding sqlite3 backup functions

* changing sleep to sqlite3_sleep to prevent clashes

Added a basic example how to handle a Post request. (#13339)

* Added a basic example how to handle a Post request.

They were also made minor cosmetic changes.

* Minor fixes suggested by Yardanico

* Fixed a wrong value in chunkSize constant.

* Re-added the request.body for compatibility!

replace old problematic isNamedTuple implementation by TypeTrait isNamedTuple in dollars.nim (#13347)

* replace old problematic isNamedTuple implementation by TypeTrait isNamedTuple

* fix for bootstrap

fix #13182: `proc fun(a: varargs[Foo, conv])` now can be overloaded (#13345) [backport]

miscellaneous bug fixes (part 3) (#13304)

* fix deprecation; fix indentation

* git clone: use -q

* fix Warning: pragma before generic parameter list is deprecated; fix typo

* bugfix: sysTypeFromName("float64") was never cached

testament: introduce 'matrix' for testing multiple options (#13343)

printing float values will have one more digit. (#13276) [backport]

* printing float values will have one more digit. Fixes #13196

[backport] fix #13352

[backport] remove 'CountTable.mget' (#13355)

It didn't work, and it was an oversight to be included in v1.0.
fix #6736: templates in unittest now show actual value (#13354)

Revert "printing float values will have one more digit. (#13276) [backport]" (#13363)

This reverts commit b2c6db97f9.
Add sideEffect pragma to importC procs in posix, winlean and time module (#13370)

* Add sideEffect pragma to procs in winlean
* Add sideEffect pragma to procs in posix
* Add test for #13306
* Add sideEffect pragma to procs in times
* Fixes #13306
fixes #3339 by documenting the limitations of case-statement (#13366)

fixes #13314 (#13372)

testament: this now works: "testament r /abspath/to/test.nim" (#13358)

fix `is` with generic types; fix `genericHead(Foo[T])` (#13303)

* fix #9855, fix #9855, fix genericHead
* render TTypeKind via toHumanStr

fix #13255 (#13275) [backport]

remove outplace version of 'merge' for CountTables (#13377)

* remove outplace version of 'merge' for CountTables

* remove 'merge' tests

fix #13374 `nim c -r -` now generates $nimcache/stdinfile (#13380) [backport]

fix #9634 don't crash on execCmdEx/readLine when inside gdb/lldb (#13232)

* fix #9634 debugging a program using execCmdEx now works

* only apply EINTR to c_gets for now

This reverts commit c0f5305b5a0b46983dfd27e3d77ecbf4f8744dcc.

lib.rst: add a link for jsconsole [backport] (#13383)

Make vccexe parse response files (#13329)

expectLen now shows the length that we got (#13387)

fix several bugs with `repr`  (#13386)

fixes #13378 [backport] (#13392)

remove dead code test_nimhcr_integration.(bat,sh) (#13388)

* enable test for osx: import tests/dll/nimhcr_integration

* re-disable osx test

fix linenoise regression (#13395)

* fix nightlies linenoise regression

* fix other installers

Revert "remove dead code test_nimhcr_integration.(bat,sh) (#13388)" (#13396)

This reverts commit 90491ea0a9.
fixes #13368 (#13397)

fix bug in int128 (#13403)

isolate the build process from external config files (#13411)

add ggplotnim to important_packages (#13206)

Fix to asynchttpserver form data/body broken with #13147 (#13394)

* Fix to asynchttpserver form data/body broken with #13147
* New implementation that use a interator instance of future streams
* asynchttpserver now can handle chunks of data.

Merge branch 'devel' of https://github.com/nim-lang/Nim into osopen

Squash Commits; Peer review feedbacks https://github.com/nim-lang/Nim/pull/12901#discussion_r379694384
2020-02-15 22:31:00 +00:00
Clyybber
f3eb0a5970 capture macro now accepts variables of different types (#13356)
* Capture macro can now accept variables of different types

* Add test

* Update examples

* Use let instead of var
2020-02-15 19:53:40 +01:00
Henrique Dias
5bf571f061 Fix to asynchttpserver form data/body broken with #13147 (#13394)
* Fix to asynchttpserver form data/body broken with #13147
* New implementation that use a interator instance of future streams
* asynchttpserver now can handle chunks of data.
2020-02-14 21:59:37 +01:00
Miran
3300e317a4 add ggplotnim to important_packages (#13206) 2020-02-14 21:28:50 +01:00
Ștefan Talpalaru
3d7d06571c isolate the build process from external config files (#13411) 2020-02-14 21:15:52 +01:00
Arne Döring
ccd2e044cb fix bug in int128 (#13403) 2020-02-14 12:33:36 +01:00
cooldome
7dd787b8a3 fixes #13368 (#13397) 2020-02-14 10:13:55 +01:00
Andreas Rumpf
1e303100f8 Revert "remove dead code test_nimhcr_integration.(bat,sh) (#13388)" (#13396)
This reverts commit 90491ea0a9.
2020-02-12 13:22:26 +01:00
Timothee Cour
2b368bcdd7 fix linenoise regression (#13395)
* fix nightlies linenoise regression

* fix other installers
2020-02-12 10:35:00 +01:00
Timothee Cour
90491ea0a9 remove dead code test_nimhcr_integration.(bat,sh) (#13388)
* enable test for osx: import tests/dll/nimhcr_integration

* re-disable osx test
2020-02-12 10:21:32 +01:00
Andreas Rumpf
c446c0f57a fixes #13378 [backport] (#13392) 2020-02-11 23:48:41 +01:00
Timothee Cour
eec07b4e84 fix several bugs with repr (#13386) 2020-02-11 21:33:06 +01:00
Clyybber
f6d45b40a5 expectLen now shows the length that we got (#13387) 2020-02-11 12:31:52 +01:00
Fredrik Høisæther Rasch
8100e2e9cd Make vccexe parse response files (#13329) 2020-02-11 12:05:47 +01:00
Jjp137
84a71dad87 lib.rst: add a link for jsconsole [backport] (#13383) 2020-02-11 10:22:49 +01:00
Timothee Cour
39ba502f87 fix #9634 don't crash on execCmdEx/readLine when inside gdb/lldb (#13232)
* fix #9634 debugging a program using execCmdEx now works

* only apply EINTR to c_gets for now

This reverts commit c0f5305b5a0b46983dfd27e3d77ecbf4f8744dcc.
2020-02-11 10:16:30 +01:00
Timothee Cour
1f7c907e7d fix #13374 nim c -r - now generates $nimcache/stdinfile (#13380) [backport] 2020-02-11 00:37:40 +01:00
Miran
ceb3d5ad68 remove outplace version of 'merge' for CountTables (#13377)
* remove outplace version of 'merge' for CountTables

* remove 'merge' tests
2020-02-10 20:50:55 +01:00
Arne Döring
2fee89f7db fix #13255 (#13275) [backport] 2020-02-09 13:51:36 +01:00
Timothee Cour
7939319379 fix is with generic types; fix genericHead(Foo[T]) (#13303)
* fix #9855, fix #9855, fix genericHead
* render TTypeKind via toHumanStr
2020-02-09 13:48:55 +01:00
Timothee Cour
debe7fffd8 testament: this now works: "testament r /abspath/to/test.nim" (#13358) 2020-02-09 13:44:16 +01:00
Andreas Rumpf
240174dd81 fixes #13314 (#13372) 2020-02-09 00:22:34 +01:00
Miran
038f47e7b9 fixes #3339 by documenting the limitations of case-statement (#13366) 2020-02-08 20:11:20 +01:00
Tomohiro
2a4aa24620 Add sideEffect pragma to importC procs in posix, winlean and time module (#13370)
* Add sideEffect pragma to procs in winlean
* Add sideEffect pragma to procs in posix
* Add test for #13306
* Add sideEffect pragma to procs in times
* Fixes #13306
2020-02-08 20:09:49 +01:00
Timothee Cour
e4415422fe Revert "printing float values will have one more digit. (#13276) [backport]" (#13363)
This reverts commit b2c6db97f9.
2020-02-08 09:30:24 +01:00
Miran
f3117d350e fix #6736: templates in unittest now show actual value (#13354) 2020-02-07 22:04:08 +01:00
Miran
78b15de304 [backport] remove 'CountTable.mget' (#13355)
It didn't work, and it was an oversight to be included in v1.0.
2020-02-07 20:50:44 +01:00
narimiran
36d1ad39d0 [backport] fix #13352 2020-02-07 18:26:08 +01:00
Arne Döring
b2c6db97f9 printing float values will have one more digit. (#13276) [backport]
* printing float values will have one more digit. Fixes #13196
2020-02-07 17:10:25 +01:00
Miran
cdedb86348 testament: introduce 'matrix' for testing multiple options (#13343) 2020-02-07 16:45:49 +01:00
Timothee Cour
1f725f1d7e miscellaneous bug fixes (part 3) (#13304)
* fix deprecation; fix indentation

* git clone: use -q

* fix Warning: pragma before generic parameter list is deprecated; fix typo

* bugfix: sysTypeFromName("float64") was never cached
2020-02-07 16:37:40 +01:00
Timothee Cour
79ec8c2571 fix #13182: proc fun(a: varargs[Foo, conv]) now can be overloaded (#13345) [backport] 2020-02-07 13:29:18 +01:00
Timothee Cour
c0a2e2ed92 replace old problematic isNamedTuple implementation by TypeTrait isNamedTuple in dollars.nim (#13347)
* replace old problematic isNamedTuple implementation by TypeTrait isNamedTuple

* fix for bootstrap
2020-02-07 13:27:28 +01:00
Henrique Dias
abd660c407 Added a basic example how to handle a Post request. (#13339)
* Added a basic example how to handle a Post request.

They were also made minor cosmetic changes.

* Minor fixes suggested by Yardanico

* Fixed a wrong value in chunkSize constant.

* Re-added the request.body for compatibility!
2020-02-07 03:59:28 -05:00
pyloor
bf3f1c3762 adding sqlite3 backup functions (#13346)
* adding sqlite3 backup functions

* changing sleep to sqlite3_sleep to prevent clashes
2020-02-07 01:11:05 -05:00
Andreas Rumpf
c87796180e fixes #13269 (#13344) 2020-02-07 06:58:57 +01:00
Timothee Cour
7481f43753 fix #13349 regression: isNamedTuple now works with generic tuples (#13350) 2020-02-07 06:58:04 +01:00
Andreas Rumpf
e24443f1bc make monotimes have zero overhead if you don't use it (#13338) [backport] 2020-02-06 16:12:54 +01:00
Timothee Cour
7ec7731f82 fix #13150 nim doc --project now works reliably (#13223)
* fix #13150 `nim doc --project` works with duplicate names and with imports below main project file

* add to help; fixup after #13212 isRelativeTo got merged
* fix test tests/compilerapi/tcompilerapi.nim
* remove nimblePkg field; compute on the fly instead
* kochdocs: compiler docs now under compiler/
* --docRoot now has smart default: best among @pkg, @path
2020-02-06 11:17:00 +01:00
Timothee Cour
574f61315d nim secret: support linenoise when available (#13328) 2020-02-05 16:44:19 +01:00
Miran
c6d5f0df8d [backport] -d:danger should imply -d:release (#13336) 2020-02-05 13:41:16 +01:00
Araq
8279da5219 contributing.rst: Add a special rule for 'outplace'-like features 2020-02-05 13:39:08 +01:00
Clyybber
ab525cc48a build_all.sh update (#13320)
* Don't overload the system, don't crash when you can't determine the CPU count and don't rely on bash

* Extract to variable

* Limit number of spawned jobs for systems with weak IO

* Use proper arithmetic braces
2020-02-04 21:26:38 +01:00
Henrique Dias
955465e5f4 Option to allow the request body to be processed outside the asynchttpserver library. (#13147)
Allow the request body to be processed outside the asynchttpserver library to break big files into chunks of data. This change does not break anything.
2020-02-04 21:13:25 +01:00
Ico Doornekamp
bfe96e069b Fixed codegen for constant cstring with --gc:arc (#13326)
* Fixed codegen for constant cstring with --gc:arc, fixes  #13321

* Added test for #13321
2020-02-04 17:39:27 +01:00
genotrance
7cc03b43f8 Fix #10717, fix #13284 (#13307) 2020-02-04 17:38:24 +01:00
Timothee Cour
e70294dff2 enable testing -d:nimHasLibFFI mode (#13091) 2020-02-04 14:08:56 +01:00
Timothee Cour
b20d7e2110 fix #13132 tnetdial (#13318) 2020-02-04 10:31:44 +01:00
alaviss
7e5c070244 koch: enable checks in the compiler when running CI (#13323) 2020-02-04 09:27:54 +01:00
Clyybber
1ab37ccfc6 Make build_all.sh more portable and a bit simpler (#13308) 2020-02-03 02:02:44 +01:00
Fredrik Høisæther Rasch
dfecc3489b Quote nim executable before executing. (#13316) [backport]
In case nim executable is located in PATH containing spaces.

fixes #13311
2020-02-02 13:54:48 +01:00
Clyybber
d43e5bef39 Fix capture for object types (#13315)
* Fix capture for object|tuple|... types

* Add test case
2020-02-02 13:52:21 +01:00
Timothee Cour
45a5c64c9a build_all.sh: building csources 5X faster thanks to make -j (#13300)
* build_all.sh: building csources 5X faster thanks to make -j
* fix for freebsd
* use OS-dependent formula to get number of logical cores
* make is an optional dependency
2020-01-31 20:00:05 +01:00
Timothee Cour
adc52b0039 refs #8391 std/os now shows runtime context for raiseOSError exceptions (#13294)
* refs #8391: fix errmsg for setCurrentDir

* raiseOSError calls for copyFile

* refs #8391 std/os now shows runtime context for raiseOSError exceptions
2020-01-30 11:06:04 +01:00
Timothee Cour
4a747f0250 CT FFI: fix for windows; fix case transition; error msg shows more useful context (#13292)
* evalffi: fix case transition
* evalffi: fix for windows
* evallffi: `cannot import` errmsg now also shows which library it tried to import symbol from
2020-01-30 11:04:06 +01:00
Timothee Cour
bf22b44b1f miscellaneous bug fixes (#13291)
* fix for emscripten etc

* add testcase for #13290

* replace deprecated isNilOrWhitespace
2020-01-30 10:54:50 +01:00
Timothee Cour
81a43791f9 fix critical bug discovered by #11591 (#13290) [backport] 2020-01-29 17:40:03 +01:00
Hiroki Noda
3ab1274231 Thread attributes should be destroyed using the pthread_attr_destroy() (#13293)
On some OSes (such as FreeBSD or Solaris), pthread_attr_init allocate
memory. So it is necessary to deallocate that memory by using
pthread_attr_destroy.
2020-01-29 17:33:21 +01:00
Timothee Cour
2ecef8f779 csize => csize_t for sysctl 2020-01-28 23:36:24 +00:00
Timothee Cour
2e20f5648b fix stdout(etc) for emscripten 2020-01-28 23:36:24 +00:00
Timothee Cour
9657a83698 removed unused import 2020-01-28 23:36:24 +00:00
Timothee Cour
5676912209 refactor htmldocs; gitignore it 2020-01-28 23:36:24 +00:00
cooldome
76ede7c198 Repr v2 progress (#13268)
* progress on repr_v2

* repr progress

* add ref objects with distrinct

* fix failing tests
2020-01-28 20:05:57 +01:00
cooldome
92010becbe nimv2 widestring indexing (#13279) 2020-01-28 20:02:39 +01:00
Clyybber
fb94836bc7 Tiny since cleanup (#13286) 2020-01-28 20:02:07 +01:00
Andreas Rumpf
be795bbf1a TlSF Alloctor: use less memory for --gc:arc (#13280) 2020-01-28 17:09:48 +01:00
cooldome
84e8477b90 unittest add resetOutputFormatters proc (#13267)
* add resetOutputFormatters

* remove space

* resolve comments
2020-01-28 14:16:03 +00:00
cooldome
46bfb590c8 fixes #13281 (#13282)
* fixes ##13281

* add comment to test
2020-01-28 14:55:54 +01:00
Andreas Rumpf
c8418651b1 fixes #13219 (#13272) 2020-01-27 22:50:10 +01:00
Jairo
32f0910f11 scrollTop must be settable (#13263)
* scrollTop must be assignable

Make scrollTop settable

* add missing export
2020-01-27 09:14:56 +01:00
hlaaftana
a71654323d Clearer final objects error; fixes #13256 (#13257) 2020-01-26 18:56:04 +01:00
hlaaftana
e7744b0909 Rename isNilOrWhitespace to isEmptyOrWhitespace and make it use allCharsInSet (#13258)
* Rename isNilOrWhitespace to isEmptyOrWhitespace

* Make isEmptyOrWhitespace use allCharsInSet(Whitespace)
2020-01-26 14:02:07 +01:00
Araq
6900da314c make nre compile with --gc:arc 2020-01-26 13:43:02 +01:00
Araq
a10cc18247 ARC: optimize complete object constructors to use nimNewObjUninit 2020-01-26 13:43:02 +01:00
Araq
ab35f07e77 ARC: remove unnecessary code 2020-01-26 13:43:02 +01:00
Andreas Rumpf
6efac70181 make goto based exceptions available for 'nim cpp' (#13244)
* make goto based exceptions available for 'nim cpp'
* optimize seq.add to be comparable to C++'s emplace_back
2020-01-25 20:00:13 +01:00
Ico Doornekamp
4f3dd33509 Cleaned up mmdisp.nim, moved implementations into lib/system/mm/ (#13254) 2020-01-25 17:14:31 +01:00
alaviss
5124b2e575 testament/azure: major rewrite (#13246)
This commit features a major rewrite of Azure Pipelines integration,
turning the spaghetti it originally was into something maintainable.

Key changes:
- No longer requires a ton of hooks into testament.
- Results are now cached then bulk-uploaded to prevent throttling from
  Azure Pipelines, avoiding costly timeouts.
- A low timeout is also employed to avoid inflated test time.
- The integration is now documented.
2020-01-25 09:32:27 +01:00
Timothee Cour
981ffc912e contributing docs: symbols need package prefix; changed allocStats to nimAllocStats (#13247) 2020-01-25 09:27:29 +01:00
Timothee Cour
4cbeddddcc nim dump: add libpath (#13249) 2020-01-24 20:06:54 +01:00
Jairo
fb74497c99 Add "origin" to window.location (#13251)
Add "origin" to window location: https://www.w3schools.com/jsref/prop_loc_origin.asp
2020-01-24 20:06:17 +01:00
Euan
ccb728a7b0 Fix typo for literal [ (#13243)
The literal value for the `tkBracketLe` token was incorrectly set to `]` rather than `[`. I've had a quick glance at the code and it doesn't look like this change will affect anything at all, but I haven't tested yet - let's see if the CI explodes...
2020-01-24 08:42:03 +00:00
hlaaftana
4656580b54 Fixes asyncftpclient multiline reading, fixes #4684 (#13242)
Previously, the 4th character of `result` was checked for `'-'` every time, instead of each new line.

Also made it work for taint mode.
2020-01-24 00:18:16 +01:00
hlaaftana
caaa8f285f Remove name attribute from docutils.nimble (#13239) 2020-01-23 18:51:25 +01:00
Ico Doornekamp
5dd2fa3e0c Updated 'nim for embedded systems' section to use --os:any and --gc:arc (#13237)
* Updated 'nim for embedded systems' section to use --os:any and --gc:arc

* Added section about size optimization to embedded systems
2020-01-23 17:17:48 +01:00
Kaushal Modi
c4ff4e553e [backport] Make all parseutils examples auto-checking (#13238)
- Also fix one example's output (ikString -> ikStr, ikVar instead of ikExpr)
2020-01-23 17:14:22 +01:00
chr v1.x
aebcbfe5ea [backport] documentation: Add channels examples (#13202) [ci skip] 2020-01-23 14:47:00 +01:00
Ico Doornekamp
b68eb1cad0 Removed lib/system/allocators.nim. seqs_v2 and strs_v2 now uses allocShared0. (#13190)
* Cleanup, remove lib/system/allocators.nim. seqs_v2 and strs_v2 now use
allocShared0 by default.

* Fixed -d:useMalloc allocShared / reallocShared / deallocShared. These now use the alloc/dealloc/realloc implementation that also takes care of zeroing memory at realloc.

* Removed debug printfs

* Removed unpairedEnvAllocs() from tests/destructor/tnewruntime_misc

* More mmdisp cleanups. The shared allocators do not need to zero memory or throw since the regular ones already do that

* Introduced realloc0 and reallocShared0, these procs are now used by
strs_v2 and seqs_v2. This also allowed the -d:useMalloc allocator to
drop the extra header with allocation length.

* Moved strs_v2/seqs_v2 'allocated' flag into 'cap' field

* Added 'getAllocStats()' to get low level alloc/dealloc counters. Enable with -d:allocStats

* *allocShared implementations for boehm and go allocators now depend on the proper *allocImpl procs
2020-01-23 14:25:22 +01:00
alaviss
f500895efe Unexport even more symbols (#13214)
* system/gc: don't export markStackAndRegisters

* compiler/cgen: unexport internal symbols

As these functions are Nim-specific walkaround against C's optimization
schemes, they don't serve any purpose being exported.

* compiler/cgen: don't export global var unless marked

* compiler/ccgthreadvars: don't export threadvar unless marked

* tests/dll/visibility: also check for exports

This ensure that these changes don't break manual exports.

* compiler/cgen: hide all variables created for constants

* compiler/ccgtypes: don't export RTTI variables

* compiler/ccgexprs: make all complex const static

* nimbase.h: fix export for windows

* compiler/cgen, ccgthreadvars: export variables correctly

For C/C++ variables, `extern` means that the variable is defined in an
another unit. Added a new N_LIB_EXPORT_VAR to correctly export
variables.
2020-01-23 13:45:31 +01:00
Timothee Cour
3a5056dc70 fix lots of bugs with parentDir, refs #8734 (#13236) 2020-01-23 13:39:41 +01:00
Timothee Cour
b8a436af93 kochdocs: use a glob instead of hardcoded list; generate docs for compiler/; bugfixes (#13221)
* kochdocs: use a glob instead of hardcoded list; generate docs for compiler/; bugfixes
* fixup after #13212 isRelativeTo got merged
2020-01-23 11:06:28 +01:00
Timothee Cour
b462baed65 VM: allow overriding MaxLoopIterations without rebuilding nim (#13233) 2020-01-23 10:53:30 +01:00
D-Nice
f12bea16ad [backport] fix #11440, add docs to isNil for seq types needing nilseq (#13234) [ci skip] 2020-01-23 07:51:53 +01:00
Mera
4a754ff392 [backport] Fix typo and improve in code-block of 'lib/pure/parseutils.nim' (#13231) [ci skip] 2020-01-23 06:49:27 +01:00
Timothee Cour
7356bc29b7 new os.isRelativeTo (#13212) 2020-01-23 00:45:16 +01:00
Milan
3e843ab335 [backport] times/getClockStr(): fix mistake in doc (#13229) [ci skip] 2020-01-22 18:22:14 +01:00
Juan Carlos
fbd7fe118c [backport] Documentation Fix #12251 (#13226) [ci skip] 2020-01-22 17:56:44 +01:00
whiterock
ef9fb39cdf added note to re constructor regarding performance (#13224)
Since I was new to regex I did not know that there is a compilation going on with ``re"[abc]"`` constructor and so I followed the other examples in the docs blindly, that is I just put the constructor directly in the arguments of match, find, etc., which was inside a loop and then wondered why my performance was so bad. Of course putting it outside the loop made it vastly more performant. People like me would benefit from the small note I added I would think :)
2020-01-22 16:02:16 +01:00
Juan Carlos
2fad7f134f httpclient, maxredirects to Natural, newHttpClient/newAsyncHttpClient add headers argument instead of hardcoded empty (#13207) 2020-01-21 19:34:47 +01:00
Andreas Rumpf
bdb7c82c6a fixes a critical times.nim bug reported on IRC [backport] (#13216) 2020-01-21 16:49:59 +01:00
Timothee Cour
b355ef2a72 fix #13211 relativePath("foo", ".") (#13213) 2020-01-21 15:48:19 +01:00
Miran
bf96d6d316 Idxmin & idxmax, continuation (#13208)
* Add idxmin() which returns the index of the minimum value

* Add idxmax() which returns the index of the maximum value

* Add tests for idxmin()

* Add tests for idxmax()

* Remove initialization of result = 0

* Adds overloading for arrays (no enums indexed arrays yet)

* Add support for enum index arrays

* Fix tests with enum

* Fix tests for idxmax

* Change names of the procedures to minIndex and maxIndex

* address Araq's comments:

- remove 'array' versions
- add .since pragma
- return 'int' instead of 'Natural'
- add changelog entry

Co-authored-by: Federico A. Corazza <20555025+Imperator26@users.noreply.github.com>
2020-01-20 16:57:34 +01:00
Jasper Jenkins
0606b6a44e fix range[enum] type conversion (#13204) [backport] 2020-01-20 16:56:59 +01:00
alaviss
470faa97c6 compiler/ccgtypes: hide exportc proc unless it has dynlib (#13199)
This hides most of stdlib's internal functions from resulting
binaries/libraries, where they aren't needed on *nix. Static libraries
are not affected by this change (visibility doesn't apply to them).
2020-01-20 10:51:21 +01:00
cooldome
da1bddb084 fixes #13195 (#13198)
* fixes #13195

* extra fix

* fix typo
2020-01-20 10:41:12 +01:00
Andreas Rumpf
41555ca86f fixes #13110 (#13197) 2020-01-19 23:30:45 +01:00
Andrii Riabushenko
6f3476d39c Revert "fixes #13195"
This reverts commit cd7904f2b2.
2020-01-19 20:33:23 +00:00
Andrii Riabushenko
e349f7ad21 Merge branch 'devel' of https://github.com/nim-lang/Nim into devel 2020-01-19 20:22:06 +00:00
Andrii Riabushenko
7576387dfe revert last commit 2020-01-19 20:21:26 +00:00
Andrii Riabushenko
cd7904f2b2 fixes #13195 2020-01-19 20:18:04 +00:00
slangmgh
13ddbc46fc Fixes #13186 (#13188) 2020-01-19 14:16:50 +01:00
Federico Ceratto
8d64550b1e Add link to packaging.html (#13194) 2020-01-19 14:15:59 +01:00
cooldome
416b4c3612 more on arc codegen (#13178)
* arc codegen for union type

* add more tests

* fix offsetof

* fix tsizeof test

* fix style
2020-01-19 14:14:26 +01:00
Timothee Cour
bc14453f69 fix docs + API for fieldPairs, fields (#13189) 2020-01-18 13:33:30 +01:00
Timothee Cour
f6ba4e81b0 maybe: allows optional chaining of field access and indexing when LHS i snil (#13023)
* maybe: allows optional chaining
* fix tools/kochdocs.nim
* improve semantics to distinguish valid from invalid values
* for now, wrapnil, isValid, unwrap are not exported
2020-01-18 12:24:56 +01:00
Timothee Cour
e11ecc8266 times: toUnixFloat, fromUnixFloat (#13044) 2020-01-18 01:24:44 +01:00
Timothee Cour
5010bc1af5 fixes #13144 (#13145)
* fixup: genscript now does not copy nimbase.h but uses -I$nim/lib
2020-01-18 01:21:13 +01:00
Timothee Cour
c56612ff96 refs #13054 correctly handle {.exportc,dynlib.} and {.exportcpp,dynlib.} (#13136)
* refs #13054 correctly handle {.exportc,dynlib.} and {.exportcpp,dynlib.}
* put back NIM_EXTERNC for N_LIB_EXPORT; causes issues with compilerproc
2020-01-18 01:19:20 +01:00
Araq
107352f9d7 fixes #13157 2020-01-17 17:52:06 +01:00
Timothee Cour
6c2214b7de followup on #10435 : should be diff, not show (#13162) 2020-01-17 16:56:21 +01:00
Clyybber
451c47634c Fix docs for subdirs too (#13180)
* Fix doc subdirs
* Extract to helper proc, and fix on windows
2020-01-17 16:49:37 +01:00
cooldome
f51613e262 make sink operator optional (#13068)
* make sink operator optional

* bug fix, add changelog entry

* Trigger build

* fix one regression

* fix test

* Trigger build

* fix typos
2020-01-17 11:44:06 +00:00
Andreas Rumpf
7626907401 ARC works for async on Windows (#13179) 2020-01-17 11:14:17 +01:00
Jasper Jenkins
796aafe7e0 make case-object transitions explicit, make unknownLineInfo a const, replace a few magic numbers with consts (#13170) 2020-01-17 10:34:31 +01:00
cooldome
2bf337abae fixes #13095 (#13181)
* fixes #13095

* fix typo
2020-01-17 09:17:18 +01:00
Clyybber
41cf609fc7 Fix docs (#13176) 2020-01-16 22:22:17 +01:00
Clyybber
e3acb2d12c Cleanup DFA (#13173) 2020-01-16 20:15:50 +01:00
Jasper Jenkins
d245d4cf09 fix tsizeof3 for aarch64 (#13169) 2020-01-16 14:21:12 +01:00
Timothee Cour
1b54be7779 fixes #12998 nim doc regression (#13117) 2020-01-16 14:19:58 +01:00
cooldome
5ef0494677 Working towards arc codegen (#13153)
fixes #13029
2020-01-16 14:16:17 +01:00
Miran
352232e62d style fix: change 'JS' to 'js' to make it consistent (#13168) 2020-01-16 14:14:03 +01:00
Ico Doornekamp
54bfd69a27 Remove obsolete code from osalloc (#13158) 2020-01-16 09:11:05 +01:00
Timothee Cour
d5f011d9e6 CI fix timeout error (#13134) 2020-01-15 22:54:04 +01:00
Andreas Rumpf
a5e67071d2 ARC: misc bugfixes (#13156)
* fixes #13102
* closes #13149
* ARC: fixes a move optimizer bug (there are more left regarding array and tuple indexing)
* proper fix; fixes #12957
* fixes yet another case object '=' code generation problem
2020-01-15 22:13:31 +01:00
Timothee Cour
d88b52c0bc successX now correctly shows html output for nim doc, nim jsondoc; fix #13121 (#13116)
* successX now correctly shows html output for nim doc
* fixes #13121
* fixup hintSuccessX to be less weird
2020-01-15 15:18:37 +01:00
Timothee Cour
51c072bd37 export normalizePathEnd (#13152) 2020-01-15 15:03:06 +01:00
Miran
e708d5de75 System cleanup, part 2 (#13155)
* create basic_types, arithmetics, exceptions, comparisons
* create setops.nim
* create memalloc.nim
* create gc_interface.nim
* create iterators_1.nim
2020-01-15 14:42:49 +01:00
Ico Doornekamp
79a326759a Added 'ansic' os support for minimal (embedded) targets (#13088)
* os:any implementation
* os:asny: omit flock/funlock calls in echoBinSafe
* Disabled default "unhandled expection" reporting for `--os:any` to reduce
code size. Added unhandledExceptionHook instead which can be used to get
a notification from Nim and handle it from the application.
2020-01-15 11:06:41 +01:00
Tomohiro
d31e32743f Fix typo in doc/destructors.rst (#13148) 2020-01-14 19:51:58 +01:00
Andreas Rumpf
675ca997fb fixes #9674 [backport] (#13143) 2020-01-14 16:20:48 +01:00
Andreas Rumpf
8b00586488 fixes #13104 [backport] (#13142) 2020-01-14 15:16:36 +01:00
cooldome
b4545f03de pass platform argument only if vccexe is used (#13078)
* pass platform only if vccexe is used
* fixes #12297
2020-01-14 15:02:10 +01:00
Andreas Rumpf
fadbd8f70d fixes #10665 (#13141) [backport] 2020-01-14 13:51:28 +01:00
Andreas Rumpf
9fc04a555c fixes #13105 (#13138) 2020-01-14 12:57:20 +01:00
Andreas Rumpf
d56848878c fixes #13119 (#13128)
* fixes #13119
* fixes a regression
2020-01-14 09:56:08 +01:00
Timothee Cour
49d1822c8f fixes #13100 nim doc now treats export localSymbol correctly (#13123) [backport]
* fix #13100 nim doc now treats `export localSymbol` correctly
* use owner instead
2020-01-13 22:05:38 +01:00
treeform
d9640ed075 Expose more openSSL methods. (#13131) 2020-01-13 22:04:43 +01:00
Andreas Rumpf
eadd1ba9ed fixes #13112 (#13127)
* improve line error information

* fixes #13112
2020-01-13 15:47:17 +01:00
Andreas Rumpf
abea80376a fixes #13122 (#13126)
* fixes #13122

* moved tests to where they belong
2020-01-13 14:11:51 +01:00
Jasper Jenkins
bf2e052e6d fix rtti sizeof for varargs in global scope (#13125) [backport] 2020-01-13 10:17:21 +01:00
perter lee
1f27a2f8ab fix the ftp store function read the local file bug (#13108) [backport]
* Update asyncftpclient.nim

When use newStringOfCap function not have assign memory for the string data,so if use this address the fault is rasise.

* complelete the bugfix
2020-01-13 10:16:19 +01:00
Timothee Cour
ee1563ef33 VM FFI: write(stderr, msg) and fprintf(cstderr, msg) now work at CT (#13083) 2020-01-12 13:44:43 +01:00
Federico Ceratto
1c001fe583 Add link to posix_utils.html in posix.nim (#13111) 2020-01-12 13:36:37 +01:00
treeform
01a89cc473 Remove some unused/disabled OpenSSL functions (#13106) 2020-01-11 10:58:38 +01:00
Andreas Rumpf
767592a3c3 more arc features (#13098)
* config update
* ARC now supports 'repr' and 'new' with finalizers is supported
2020-01-10 23:17:33 +01:00
Miran
c0973d1b47 [backport] fix #12813, fix #13079 (#13099)
Correctly remove a key from CountTable when it is set to zero.
2020-01-10 15:24:33 +01:00
Miran
f7ce4e8705 System cleanup, part 1 (#13069)
* system.nim: mark what every .pop does

* system.nim: un-nest when statements
2020-01-10 10:14:02 +01:00
Andreas Rumpf
3a39ab83ac fixes an asyncftpclient bug; refs #13096 [backport] 2020-01-10 09:42:21 +01:00
narimiran
e9e114058c [backport] system/io.nim fix wrong documentation comment [ci skip] 2020-01-10 08:53:44 +01:00
Timothee Cour
4cd86c0842 typetraits: fixes #6454; genericParams; added lenTuple; added tuple type get (#13064) 2020-01-10 08:51:37 +01:00
Araq
fcd2f305ad fixes #13070 2020-01-10 08:32:30 +01:00
Araq
033da35de1 fixes #13072; no test case because it will be added later with more exception handling related bugfixes 2020-01-10 08:32:30 +01:00
Tomohiro
a33b72af49 Fix error check code in osproc (#13090) [backport] 2020-01-09 18:00:41 +01:00
Ico Doornekamp
bb7273bc47 Use '__noinline' instead of 'noinline' for N_NOINLINE gcc attribute, this prevents clashes with systems where 'noinline' might be already defined (#13089) 2020-01-09 17:27:42 +01:00
Timothee Cour
3f78873898 remove all remaining warnings when build nim (with -d:nimHasLibFFI) (#13084)
* cleanup deprecations in evalffi + elsewhere

* remove dead code getOrdValue64
2020-01-09 13:19:18 +01:00
Andreas Rumpf
852170cc78 take the one good idea from --os:standalone and enable it via -d:StandaloneHeapSize (#13077) 2020-01-09 11:48:37 +01:00
Teashrock
27fee4d8b4 Deleted misplaced separator (#13085) [backport]
Misplaced separator, which was constantly breaking compilation on Haiku OS, was deleted.
2020-01-09 11:48:13 +01:00
Andy Davidoff
56fb909676 fix crash due to errant symbols in nim.cfg (#13073) [backport] 2020-01-08 22:25:25 +01:00
narimiran
5e9ebe9ec1 move entries from the wrong changelog file [ci skip] 2020-01-08 15:20:30 +01:00
Timothee Cour
15043d35b8 make SuccessX show project file + output file (#13043)
* make SuccessX show project file + output file
* address comments
* fix test and add `result.err = reNimcCrash` otherwise hard to see where reNimcCrash used
* address comments
2020-01-08 00:39:07 +01:00
cooldome
871d5e79b1 distinctBase type trait for distinct types (#13031) 2020-01-08 00:36:57 +01:00
b3liever
8bcc7e8b9e basename supports pragmaexpr (#13045)
* basename supports pragmaexpr

* update changelog
2020-01-07 11:25:51 +01:00
Bung
291608045c add pqserverVersion,pqconnectionNeedsPassword,pqconnectionUsedPassword (#13060) 2020-01-07 10:52:02 +01:00
Timothee Cour
e5ae7ceaa3 [easy] --hint🔗on now shows link cmd instead of nothing (#13056)
* --hint🔗on now shows link cmd instead of nothing

* update doc for --listCmd
2020-01-07 10:38:59 +01:00
Timothee Cour
569d4d18f8 --styleCheck:hint now works (#13055) 2020-01-07 09:53:11 +01:00
Miran
1551fff853 clean up deprecated stuff and unused imports in tests (#13059) 2020-01-07 09:49:08 +01:00
loloiccl
6a7a19eb15 Modify the test command for nimly (nimble-package) (#13053) 2020-01-07 06:47:40 +01:00
Brent Pedersen
a019cc52f6 testament/important_packages dont run hts (#13052) 2020-01-07 06:47:18 +01:00
Clyybber
ba4fbb6328 Continue #13002 (#13021) 2020-01-06 11:40:42 +00:00
Timothee Cour
72499a8d7c [cleanup] remove disabled (and obsolete) ttypetraits; rename ttypetraits2 => ttypetraits (#13041)
* remove disabled (and obsolete) ttypetraits; rename ttypetraits2 => ttypetraits

* D20200105T085828 fix super strange bug that causes CI to fail: builds.sr.ht with: `Error: Settle timed out after 120 attempts`
2020-01-05 19:33:33 +01:00
BinHong Lee
2cfa8d8385 Allow -o option for buildIndex (#13037) [backport]
Addressing #12771 

This is also included in the docgen documentation [here](https://nim-lang.org/docs/docgen.html) but its not respected as reported in the issue.
2020-01-05 19:24:29 +01:00
Kamanji
9a5aaadda8 Rst parser respect :start-after: and :end-before: in include directive (#12972)
* [FEATURE] rst parser respect :start-after: in include

Rst parser now respects `:start-after:` and `:end-before:` attributes
for `include` directive.

* [DOC] include directive parsing proc update

* [TEST] Added unit tests for include rst directive in `rst` module
2020-01-05 10:01:21 +01:00
Araq
ae68ff959b fixes #12996 2020-01-05 09:42:44 +01:00
Araq
fdcea66fd9 reprjs: style changes 2020-01-05 09:42:44 +01:00
cooldome
a3df1b55f3 fixes #13013, reverts previous changes to readLines() (#13036) [backport]
* Revert "remove default argument for readLines (#12807) [backport]"

This reverts commit c949b81efd.
2020-01-05 09:22:41 +01:00
Jasper Jenkins
9474a818af fix enumtostr crash for enum-range (#13035) 2020-01-05 09:18:14 +01:00
Timothee Cour
13c08f3ab4 VM: support importc var, ptr/pointer types, cast int <=> ptr/pointer (#12877)
* VM: allow certain hardcoded special var variables at CT
* VM: allow all importc var, cast[int](ptr)
* fix tests tests/vm/tstaticprintseq.nim, tests/cpp/t8241.nim
* VM: == works for ptr/pointer nodes
* bugfix: ==, cast now also works for pointer, not just ptr
* VM supports cast PtrLikeKinds <=> PtrLikeKinds / int
* improve cname handling
* fixup + bug fix
* VM: support cast from ref to int
* address comment: opcLdGlobalDeref => opcLdGlobalDerefFFI
* defensive check against typ == nil
2020-01-05 09:11:29 +01:00
Araq
a1beeb313f fixes #13032 2020-01-04 19:33:49 +01:00
Andreas Rumpf
0f6987a86e fixes #12964 (#13027) 2020-01-04 07:40:02 +01:00
cooldome
47e7b8771c Fixes #13026 (#13028) 2020-01-04 02:33:13 +01:00
rockcavera
89570aa44b fix #12988 (#13022)
fix #12988
2020-01-03 22:41:58 +01:00
Andreas Rumpf
fb1b51f1e3 fixes #12956 (#13020) 2020-01-03 17:36:09 +01:00
Andreas Rumpf
8aadba1a2a fixes #12961 (#13019) 2020-01-03 14:30:54 +01:00
Siegfried Ehret
a577a88c36 Fix typo (#13015) [backport] 2020-01-03 10:23:28 +01:00
Andreas Rumpf
0ecb709cbe fixes #12978 (#13012) 2020-01-03 01:21:45 +01:00
cooldome
c949b81efd remove default argument for readLines (#12807) [backport] 2020-01-02 23:27:37 +01:00
cooldome
002d50f1f0 Sink to MemMove optimization in injectdestructors (#13002) 2020-01-02 22:58:01 +01:00
Timothee Cour
0ff23e696c fix #12985 {.push.} now does not apply to generic instantiations (#12986) 2020-01-02 16:49:57 +01:00
Andreas Rumpf
c3344862b0 --exception:goto switch for deterministic exception handling (#12977)
This implements "deterministic" exception handling for Nim based on goto instead of setjmp. This means raising an exception is much cheaper than in C++'s table based implementations. Supports hard realtime systems. Default for --gc:arc and the C target because it's generally a good idea and arc is all about deterministic behavior.

Note: This implies that fatal runtime traps are not catchable anymore! This needs to be documented.
2020-01-01 10:01:49 +01:00
Andy Davidoff
8a63caca07 fixes disruptek/nimph#102 multi-level nim.cfg use (#13001) [backport] 2019-12-31 22:29:19 +01:00
cooldome
584e8c8283 fixes #12989 (#12992)
* fixes #12989
* Revert "remove unwanted changes"

This reverts commit 501829732a.
2019-12-31 21:13:26 +01:00
Andreas Rumpf
ce40ed18bb fixes #12965 (#12991) 2019-12-31 09:42:18 +01:00
Andrii Riabushenko
9eeff690d5 Revert "fixes #12989"
This reverts commit 928c2fee06.
2019-12-31 00:10:02 +00:00
Andrii Riabushenko
928c2fee06 fixes #12989 2019-12-31 00:07:49 +00:00
Ștefan Talpalaru
defaf3b5a5 c_fflush() the rawWrite() buffer (#12987)
Stack traces on an unbuffered stderr get out of sync with line-buffered
stdout - usually on Windows terminals or CI logs. This fixes it by
calling C's fflush() on the output buffer in the procedure used for
printing stack traces.
2019-12-30 02:13:41 +01:00
Chris Heller
8d1a7db6ea Check pqntuples > 0 in getValue. Fixes #12973 (#12974) 2019-12-29 17:41:18 +01:00
Sam Wang
441cacf70f Added fix for handling TaintedStrings in streams and httpclient (#12969)
* Added fix for taint mode in streams and httpclient

* Removed taintMode export from system.nim
2019-12-29 17:37:22 +01:00
Ștefan Talpalaru
ee9ee297d8 generic stack trace overriding mechanism (#12922)
* libbacktrace support

* switch to a generic stack trace overriding mechanism

When "nimStackTraceOverride" is defined, once of the imported modules
can register its own procedure to replace the default stack trace
generation by calling `registerStackTraceOverride(myOwnProc)`.

Tested with `./koch boot -d:release --debugger:native -d:nimStackTraceOverride --import:libbacktrace`
for the compiler itself and `./bin/nim c -r -f --stacktrace:off --debugger:native -d:nimStackTraceOverride --import:libbacktrace foo.nim`
for an external program.

* make the StackTraceOverrideProc {.noinline.}
2019-12-29 15:46:01 +01:00
Simon Krauter
37e93eab66 parsecfg: retain CRLF line breaks, fixes #12970 (#12971) 2019-12-29 15:39:48 +01:00
Timothee Cour
8c19372690 [ci skip] docfix .. < => ..< (#12981) [backport] 2019-12-29 15:34:36 +01:00
Jack Tang
21ea1094ef Allow customize Host header 2019-12-28 17:26:02 +00:00
King Eca
b67dea7a33 Fixes stackoverflow links in readme (#12963) [backport] 2019-12-27 08:31:01 +00:00
Andreas Rumpf
1917ebf082 minor refactorings 2019-12-27 08:29:40 +01:00
cooldome
649bf326bf fixes #12945 (#12959) 2019-12-24 20:34:14 +01:00
Araq
30162908b0 fixes another regression 2019-12-24 17:33:27 +01:00
Araq
3516947642 osproc: fixes regression 2019-12-24 17:33:27 +01:00
Araq
5aa7b1a44b ARC: default to a shared heap with --threads:on 2019-12-24 17:33:27 +01:00
Araq
bafb4f119c ported re.nim to ARC 2019-12-24 17:33:27 +01:00
Araq
8f17a70fe1 ported osproc.nim to ARC 2019-12-24 17:33:27 +01:00
Araq
9faf00598f ported channels to ARC 2019-12-24 17:33:27 +01:00
Araq
fbb8052e3a fixes the distros.nim regression 2019-12-24 17:33:27 +01:00
Araq
7bcf7696f0 fixes a silly regression 2019-12-24 17:33:27 +01:00
Araq
942db8c5f3 fixes a test case 2019-12-24 17:33:27 +01:00
Araq
6152eb3be3 a better bugfix 2019-12-24 17:33:27 +01:00
Araq
767bd57289 fixes a regression 2019-12-24 17:33:27 +01:00
Araq
d1d017ae85 fixes #12826 2019-12-24 17:33:27 +01:00
Araq
a7b4b2ed54 fixes a bug that kept sugar.collect from working with for loop macros [backport] 2019-12-24 17:33:27 +01:00
Araq
fd5aa89304 added guidelines for evolving Nim's stdlib 2019-12-24 17:33:27 +01:00
Araq
2616a86d4b docs: tiny style improvements 2019-12-24 17:33:27 +01:00
Timothee Cour
a0980c88c9 lenVarargs: number of varargs elements (#12907) 2019-12-23 09:42:32 +01:00
Jasper Jenkins
2e7c9eb6a8 case coverage error message for char (#12948) 2019-12-22 10:10:46 +01:00
Ico Doornekamp
28466ce6fc Auto-initialize deques (#12879) 2019-12-21 21:01:34 +01:00
Timothee Cour
b081166685 fixes #12735 on osx, call dsymutil for debug builds (#12931)
* fix #12735 osx: dsymutil needs to be called for debug builds
* also write dsymutil command to extraCmds in json build file
2019-12-21 20:59:08 +01:00
Judd
e1d79d40f2 update documentation for closureScope and capture (#12886) 2019-12-21 08:06:32 +01:00
RSDuck
9b8afd1dbb Fix #12785 (#12943)
* Fix #12785 and add test

* better variable name
2019-12-21 07:51:19 +01:00
Clyybber
10bd7d8fa0 system.reset is no longer magic (#12937)
It has now means setting x to default for new and old runtime alike
2019-12-19 20:36:59 +01:00
Timothee Cour
e041c184d2 fix #12919 tasyncclosestall flaky: Address already in use (#12934) 2019-12-19 18:50:39 +01:00
Timothee Cour
206a4cee77 fix cmdline bugs affecting nimBetterRun correctness (#12933) [backport] 2019-12-19 14:53:01 +01:00
flywind
cb0a20b9b4 fix error in assertions document (#12925) [backport] 2019-12-18 14:29:45 +01:00
Jasper Jenkins
3c38edf563 Better case coverage error message for alias and range enum (#12913) 2019-12-18 10:29:01 +01:00
Emery Hemingway
148f6d9820 Implement NixOS distro check (#12914) 2019-12-18 08:01:58 +01:00
Andreas Rumpf
3f6df5cc34 fixes #12899 (#12921)
* fixes #12899

* fixes regression: destroy global variables in reverse declaration order, closureleak test relies on it
2019-12-18 07:54:20 +01:00
genotrance
f9f55a23bb Fix single match output (#12920) 2019-12-17 20:26:11 +01:00
Clyybber
18e2ea787e Cleanup leftovers of #12911(#12916) 2019-12-17 17:58:04 +01:00
Andreas Rumpf
83a736a34a ARC: cycle detector (#12823)
* first implementation of the =trace and =dispose hooks for the cycle collector
* a cycle collector for ARC: progress
* manual: the .acyclic pragma is a thing once again
* gcbench: adaptations for --gc:arc
* enable valgrind tests for the strutils tests
* testament: better valgrind support
* ARC refactoring: growable jumpstacks
* ARC cycle detector: non-recursive algorithm
* moved and renamed core/ files back to system/
* refactoring: --gc:arc vs --gc:orc since 'orc' is even more experimental and we want to ship --gc:arc soonish
2019-12-17 17:37:50 +01:00
Arne Döring
5848f0042c add $nimeq for gdb (#12909) 2019-12-17 11:30:01 +01:00
cooldome
7650617448 NaN floatFormat with clang_cl (#12910)
* clang_cl nan floatFormat

* format
2019-12-17 11:25:46 +01:00
Timothee Cour
e8f4586c68 allow typed/untyped in magic procs (#12911) 2019-12-17 11:07:32 +01:00
Timothee Cour
e5ed4c1b7d fix json regression D20191212T144944 (#12902) [backport] 2019-12-15 23:04:06 +01:00
Krzysztof Majk
e4e74a5565 remove unused import (#12900) 2019-12-15 22:59:08 +01:00
BinHong Lee
20a59da401 Add --git.devel option to the documentation 2019-12-15 12:45:57 +00:00
Andreas Rumpf
347a04606b fixes #12885 [backport] (#12895) 2019-12-13 19:20:29 +01:00
Andreas Rumpf
a0aa8fa857 fixes #12874 (#12890)
* fixes #12874

* fixes introduced regressions
2019-12-13 15:36:39 +01:00
cooldome
12d2b980e8 Fixes #12883 (#12894)
* fixes #12883

* fix comment

* add normalize

* fix
2019-12-13 13:30:27 +00:00
cooldome
777c9ad0ef Better clang_cl support (#12896) 2019-12-13 12:12:04 +00:00
cooldome
1e1fd73530 fixes #12882 (#12889)
* fixes #12882
2019-12-13 11:24:05 +00:00
Andreas Rumpf
22b2684608 fixes #12148 [backport] (#12888) 2019-12-12 11:05:18 +01:00
cooldome
94289161f9 invoke createTypeBoundOps for constructors (#12878) 2019-12-11 10:46:20 +00:00
Andreas Rumpf
3524944e21 ARC: fixes cycle detection and move the .cursor attribute into closures (#12872) 2019-12-11 06:57:00 +01:00
Ico Doornekamp
e61d702206 Increased TInstr field sizes: allow long jumps and 65535 VM registers (#12777)
* Increased regBx size from 16 to 24 bits to increase jump range in the VM
from 32K to 8M instructions. Fixes #12727

* Increased VM TInst register field sizes to 16 bits to allow up to 65535 VM registers per proc

* Added test case for >255 VM registers
2019-12-10 19:04:02 +01:00
Andreas Rumpf
b8152b29e8 ARC: yet another bugfix (#12871) 2019-12-10 16:44:54 +01:00
Judd
56cf3403b4 introduce capture macro (#12712)
capture works for more cases than `closureScope`.
2019-12-10 13:16:37 +01:00
PMunch
65fd95bf85 Fix AVR target to define ints properly (#12817)
* Fix AVR target to define ints properly

* Fix more than AVR target

* Test to see how robust not using stdint is

* Fix for namespaces using cstdint

* Fix for pre C++11 compilers when using namespaces
2019-12-10 12:10:33 +01:00
Andreas Rumpf
61d89aae11 completes #12799, fixes #12216 (#12870) 2019-12-10 12:09:48 +01:00
cooldome
13d232ec56 fixes #12827 (#12829) [backport] 2019-12-10 07:08:46 +01:00
Andreas Rumpf
c282cee4db feature dracula themed doc (#12816)
* Implement gorgeous Dracula themed Nim documentation

* Add color for escape sequences

* fixes the test cases

* the big CSS cleanup
2019-12-10 06:48:11 +01:00
cooldome
5929c3da21 fixes #12820 (#12828) 2019-12-09 20:03:23 +01:00
Neelesh Chandola
e4f7656772 Support cross compiling from host to host (#12859) 2019-12-09 13:39:25 +01:00
Neelesh Chandola
7ebb2baa6c Assigning template to var/let/const gives a proper error (#12851)
* Assigning template to var/let/const gives a proper error

* Fix style
2019-12-09 08:19:40 +00:00
Andy Davidoff
a3d45d0c1b add a StringTable.clear that requires no mode specification (#12853)
* add clear overload, test, changelog

* add since annotation
2019-12-09 06:58:36 +01:00
Kevin
a02d043b58 added cstrutils (#12858) [backport]
fixed for 'csuCmpIgnoreStyle' error on hotcodereloading
2019-12-09 06:58:06 +01:00
Neelesh Chandola
ff5ef95414 Fixes #12832 (#12842) [backport]
* Fix #12832
* nimVm -> nimvm in json.nim
* Use suggestSym() instead of markUsed(); Also use styleCheckUse() for finding style violations
2019-12-08 23:27:25 +01:00
Mark
73dd348ddd Manual update: custom exceptions (#12847) [backport]
Said that you can have custom exceptions and showed how to create and raise them.
2019-12-08 21:39:44 +00:00
Elliot Waite
50c1e50184 Add a 32x32 favicon (#12856) 2019-12-08 22:19:35 +01:00
KeepCoolWithCoolidge
ae7b53ec51 Fixes classify function to detect subnormal floating points (#12836)
* Fix classify to test for subnormality.
* Minor fix.
* Modified to maintain existing API.
* Minor change.
* Removed 32-bit case since float is always 64-bit.
2019-12-08 20:17:11 +01:00
Elliot Waite
5da27a891c Removing the mention of using discard for block comments (#12837) [backport]
* Remove mention of using `discard` for block comments

* Add a 32x32 alternate favicon
2019-12-08 20:16:17 +01:00
Mark
0ebc709037 deviated -> derived (#12846) [backport] 2019-12-08 20:15:19 +01:00
Mark
46144a31ab deviated -> derived (#12845) [backport] 2019-12-08 20:14:54 +01:00
Timothee Cour
23fc93fc2d VM: allow ptr setting ptr fields (#12825) 2019-12-06 22:38:53 +01:00
cooldome
7213969901 fixes #12821 (#12822) 2019-12-06 09:56:54 +01:00
Neelesh Chandola
1db21721ec Fixed objects being erroneously zeroed out before object construction (#12814) [backport] 2019-12-05 17:31:51 +01:00
Andreas Rumpf
3fbb3bfd3f ARC related bugfixes and refactorings (#12781) 2019-12-05 16:59:06 +01:00
cooldome
9b0e874687 fixes #12783 [backport] (#12810)
* fixes #12783

* Trigger build
2019-12-05 15:17:45 +01:00
Andrey Makarov
26074f594d nimgrep improvements (#12779)
* fix sticky colors in styledWrite

* nimgrep: context printing, colorthemes and other

* add context printing (lines after and before a match)
* nimgrep: add exclude/include options
* nimgrep: improve error printing & symlink handling
* nimgrep: rename dangerous `-r` argument
* add a `--newLine` style option for starting matching/context
  lines from a new line
* add color themes: 3 new themes besides default `simple`
* enable printing of multi-line matches with line numbers
* proper display of replace when there was another match replaced at
  the same line / context block
* improve cmdline arguments error reporting
2019-12-05 14:42:20 +01:00
Andreas Rumpf
0e7338d65c better support for PROGMEM like annotations for lets/vars; fixes #12216 (#12799) 2019-12-05 13:45:16 +01:00
Clyybber
267fed53ee Fix #12812 2019-12-05 13:22:40 +01:00
itsumura-h
208b018f6b fix db_mysql getRow() when column is null error raised (#12806) [backport]
* fix db_mysql getRow()
* added if y == nil [backport]
2019-12-05 10:28:47 +01:00
cooldome
0987872675 fixes #12804 (#12809) 2019-12-05 07:38:12 +01:00
Araq
de1a283383 fixes #12798 [backport] 2019-12-04 20:38:20 +01:00
Arne Döring
b0c06aa711 fix #12740 (#12774)
* fix #12740

* A different kind of a hack

* proper fix

* fix typo
2019-12-04 07:33:01 +00:00
Timothee Cour
3383985c44 osx: support nanosecond resolution for file stat (eg getLastModificationTime) (#12794) 2019-12-04 08:12:55 +01:00
cooldome
01c7409924 Fix external file recompilation (#12802) 2019-12-03 16:54:42 +01:00
Alex Mitchell
7b562dd43d Update events.nim (#12803)
Removing old username.
2019-12-03 16:54:23 +01:00
genotrance
eed328856f Path substitution for --out and --outdir (#12796)
* Enable pathSubs for --out and --outDir
* Cleanup
2019-12-03 09:26:18 +01:00
Timothee Cour
9e1fd9e46b [minor] fix doc for $(Time) (#12795) [backport] 2019-12-03 09:12:08 +01:00
Tomohiro
378289c6a8 Fixes #12734 (#12784) 2019-12-01 23:21:36 +01:00
Ico Doornekamp
6aade97fe8 Refactored VM registerlayout. The size and location of the registers in (#12775)
the instructions are now all derived from a single definition, allowing
the register layout to be changed.
2019-11-30 13:38:36 +01:00
Jasper Jenkins
0d022622e3 fix nimsuggest deprecation warnings (#12772) 2019-11-30 06:54:15 +01:00
Jasper Jenkins
b6b8d540e3 [backport] always set fileInfoIdx.isKnownFile (#12773) 2019-11-29 22:36:01 +01:00
Euan
c5c6bae2a4 #12103 - CI for FreeBSD (#12179)
* Ref #12103 - adds FreeBSD CI
* Fix getApplFreebsd - length of the string includes the null terminator byte, so minus 1 for result length
* Show last commit in setup task.
* Remove .git from repository URL
* Don't include noisy details showing last commit.
* Add FreeBSD build status badge
* Fix #12182 - disable tconsole on FreeBSD
* Disable tgetaddrinfo on FreebSD as getaddrinfo doesn't support the ICMP protocol.
* Install boehm-gc-threaded
* Use libgc-threaded.so on FreeBSD rather than libgc.so.
* Simplify build failure handling. Update alt text for CI badge.
* Disable test on FreeBSD
* Simplify build config

- use GNU make to build csources
- set PATH variable using the environment key
- remove modification of config to set CC as this is already set

* Install git which seems to be missing from current freebsd images
* Revert change to how path is set
* Add a comment explaining why the length is truncated
* Fix tconsole.
2019-11-29 21:00:54 +01:00
Araq
7e6e399d10 fixes #12669 2019-11-29 19:46:21 +01:00
Araq
b688250202 fixes #12766 2019-11-29 19:46:21 +01:00
Pierre-Jean Grenier
a114a40b57 fix httpclient.lastModified bad pattern in parsing (#12698) 2019-11-29 11:17:10 +01:00
Oscar Nihlgård
5456da3ca9 Fix sequtils.delete bug with out of bounds indexes (#12506) 2019-11-29 11:15:20 +01:00
genotrance
49db2a08ba Fixes #12767 (#12768) 2019-11-29 10:18:44 +01:00
Jasper Jenkins
9ea55eccbb make addQuoted work on nimscript (#12717) [backport] 2019-11-28 23:01:17 +01:00
Araq
0996eb174f fixes #11727 [backport] 2019-11-28 23:00:34 +01:00
Araq
87f0d534d6 fixes #12488 [backport] 2019-11-28 23:00:34 +01:00
Araq
2dea920379 ARC: implemented a simple cycle detector 2019-11-28 23:00:34 +01:00
Clyybber
7e747d11c6 Cosmetic compiler cleanup (#12718)
* Cleanup compiler code base

* Unify add calls

* Unify len invocations

* Unify range operators

* Fix oversight

* Remove {.procvar.} pragma

* initCandidate -> newCandidate where reasonable

* Unify safeLen calls
2019-11-28 17:13:04 +01:00
PMunch
b662842bd0 Fix for 16 bit platforms (#12760) [backend]
This fixes some tiny issues with using Nim on 16-bit platforms. Not
entirely sure why the AVR chip I was compiling for with "cpu = avr" was
detected as 16-bit, but that's probably another issue..
2019-11-28 17:11:56 +01:00
genotrance
010067f3cc Substitute $nimbleDir in --path flags (#12750) 2019-11-28 13:58:38 +01:00
Andreas Rumpf
abe07eb75d VM: improvements for var T/addr (#12667); fixes #12489 2019-11-28 09:56:02 +01:00
Araq
d4cae118dc fixes a flaky test for the realtime GC 2019-11-28 09:33:01 +01:00
3n-k1
0944b0f441 [backport] Fix style issues in lib/, tools/, and testament/. Fixes #12687. (#12754) 2019-11-28 08:32:11 +01:00
Brian Wignall
a7aeabb9d2 [backport] Fix spelling typos (#12755) 2019-11-28 08:30:55 +01:00
Andreas Rumpf
fd85a5ae05 more fixes for --cpu:avr [backport] (#12748) 2019-11-27 16:24:21 +01:00
Araq
80b508d337 test suite: rename tests containing 'fail' for easier search in logs 2019-11-26 16:04:28 +01:00
Araq
72237e2bcf ARC: ported the GC tests over to --gc:arc 2019-11-26 16:04:28 +01:00
Miran
879801c639 increase the timeout for 'tasyncclosestall' (#12744)
This test is very flaky, this change might help reducing the
number of failings (usually solved by restarting the test suite).

Refs https://github.com/nim-lang/Nim/pull/12694#issuecomment-557583790
2019-11-26 14:12:15 +01:00
Timothee Cour
dfe5d115fb fixes #12663 staticRead now creates a dependency for rebuilds (#12731) [backport]
* fix #12663 staticRead
* address comments
2019-11-25 14:44:13 +01:00
Arne Döring
04614a30bd fix in tests/js/tconsole (#12709) 2019-11-25 10:30:22 +01:00
Andy Davidoff
bd8f49cbd3 replace some runtime repr in stdlib for gc:arc (#12716) 2019-11-25 10:13:30 +01:00
tauplus
8debf79837 fix typo in the manual (#12723) 2019-11-25 10:08:22 +01:00
tauplus
bfad0056ab Fix wrong section hierarchy in the manual (#12724) [backport] 2019-11-25 10:06:54 +01:00
Mamy Ratsimbazafy
1f7871ea1c csize_t changes: pinToCpu didn't compile (#12725) 2019-11-25 08:42:19 +01:00
narimiran
015bec6254 Revert "ARC: another critical bugfix; temporary tuples we introduce for tuple unpackaging are not owning the data"
This reverts commit 8b2f8f5430.
2019-11-24 09:50:52 +01:00
Araq
8b2f8f5430 ARC: another critical bugfix; temporary tuples we introduce for tuple unpackaging are not owning the data 2019-11-22 21:41:45 +01:00
Arne Döring
2acf74d458 delete list comprehension (#12392)
The `lc` macro is now part of `graveyard` repository.
2019-11-22 19:57:43 +01:00
Araq
c85e266d1d ARC: yet another silly bugfix 2019-11-22 17:18:11 +01:00
Jack Tang
f0c5d99924 index out of bounds exception when data is empty (#12428) 2019-11-22 15:37:59 +01:00
b3liever
5bb6c67a45 add collect macro (#12708)
* add collect macro

* Add to changelog
2019-11-22 14:40:50 +01:00
Andreas Rumpf
e5478b32a8 fixes #11863 multipart data need $ (#12707)
* fixes #11863
* improved the code; refs #12412
2019-11-22 14:21:03 +01:00
Andreas Rumpf
64e8f050e1 implemented a new localPassc pragma (#12706) 2019-11-22 14:20:15 +01:00
Juan Carlos
c0eeea4f3c Improve head comment on JS (#12548)
* Improve comment on JSGen, replace 12+ concatenations by 1 multiline string

* Peer review feedbacks https://github.com/nim-lang/Nim/pull/12548#discussion_r340051147
2019-11-22 11:37:30 +01:00
Andreas Rumpf
f7ba7c711a added the --asm command line option for inspection of the produced assember code (#12699) 2019-11-21 22:53:51 +01:00
Araq
135774d92b thavlak.nim: more idiomatic code 2019-11-21 20:01:43 +01:00
Araq
d45a736cc8 more thavlak.nim improvements 2019-11-21 16:06:04 +01:00
Araq
f07774d064 more thavlak.nim improvements 2019-11-21 16:03:44 +01:00
Araq
48eed1f522 thavlak.nim test: improved the code style 2019-11-21 15:34:45 +01:00
Jjp137
1b2c1bc64a Remove a stray file (#12697) 2019-11-21 11:19:54 +01:00
Andreas Rumpf
78e02d174d fixes #12670 [backport] (#12693) 2019-11-20 19:08:16 +01:00
Andreas Rumpf
c98e0e22ad conversions to unsigned numbers are not checked anymore; implements /… (#12688) [backport]
* conversions to unsigned numbers are not checked anymore; implements / fixes https://github.com/nim-lang/RFCs/issues/175

* change the spec yet again to be less consistent but to make more sense; updated the changelog
2019-11-20 17:08:43 +01:00
Andreas Rumpf
85ffcd80c0 more arc improvements (#12690)
* ARC: bugfix for =destroy for inherited objects
* added code useful for debugging
2019-11-20 14:34:05 +01:00
c-blake
a88004114d Discussion both in (#12678)
https://github.com/nim-lang/Nim/pull/12600
and in
    https://forum.nim-lang.org/t/5499
indicates that everyone is happy/happier with ``pop``.

This just renames the brand new ``take``s to ``pop`` and installs inline
aliases/wrappers to preserve ``Table.take`` and ``TableRef.take``.

Update apis.rst to try to maintain consistency of remove-and-return procs.
2019-11-20 08:39:45 +01:00
Andreas Rumpf
56a00da34a fixes #12612 [backport] (#12681) 2019-11-19 12:09:36 +01:00
Arne Döring
03fa9a9041 fix regression in align (#12680)
* fix regression in align

* add test typesym without type
2019-11-19 09:58:47 +01:00
Andreas Rumpf
5278cf80eb ARC: closure bugfixes (#12677)
* ARC: closure bugfixes
* progress
* ARC closures: create =hooks for captured parameters
* ARC: always destroy constructions like tuples, arrays properly, even in edge cases
* fixes a regression
2019-11-18 12:33:44 +01:00
Dominik Picheta
bab5351d43 Fixes ambiguity errors when evaluating Nimble files. (#12674) [backport]
When trying to evaluate a Nimble file which imports a Nim module
I was getting the following errors for some reason:

```
/Users/dom/projects/nim/lib/pure/parseopt.nim(229, 46) Error: ambiguous call; both system.paramCount() [declared in /Users/dom/projects/nim/lib/system/nimscript.nim(65, 6)] and os.paramCount() [declared in /Users/dom/projects/nim/lib/pure/os.nim(2613, 8)] match for: ()
```
2019-11-18 09:26:06 +01:00
Andreas Rumpf
223e65e529 attempt to add valgrind support to the CIs and testament (#12646)
* attempt to add valgrind support to the CIs and testament

* valgrind (currently) works only on 64-bit Linux
2019-11-18 09:10:48 +01:00
Andreas Rumpf
58f3e07b1a fixes and changes the recently introduced 'alignas' to be 'align' (#12666)
* fixes and changes the recently introduced 'alignas' to be 'align'

* more improvements
2019-11-15 20:24:14 +01:00
Juan Carlos
9c46526cfa Fix htmlgen html lang (#12668) [backport]
* Fix HTMLGen enable lang on html tag
2019-11-15 20:23:03 +01:00
Gampol T
83b7656c0e fixes #12319 - change exception handling for finish.exe (#12413)
* documented behaviour of recv on bufferd socket

* fixes #12319- check exception using errorCode
2019-11-15 13:28:55 +01:00
Andreas Rumpf
76179cbec2 ARC: fixes leaking new() statement (#12665) 2019-11-15 12:38:11 +01:00
Miran
107b40f097 remove two asserts in int128.nim (#12648) [backport]
Before this PR, `tests/misc/tconv.nim` fails when the compiler
is compiled without `-d:danger` flag.
Bear in mind that even without the asserts, the values outside of
a given range are still checked and a meaningful error message
(from `compiler/semexprs.nim`) is printed.
2019-11-15 12:37:43 +01:00
David Krause
ffca3eefb5 fix documentation of $*(dt: DateTime) (#12660)
(cherry picked from commit 39122ecd93)
2019-11-15 08:06:26 +01:00
Andreas Rumpf
a14abc5708 ARC: solves phase ordering problems (#12654) 2019-11-14 23:19:18 +01:00
Araq
f22d3c75aa ARC: closure inside object constructor now works 2019-11-13 23:29:21 +01:00
Araq
bcab3ed06c ARC: handle closures like tuples consistently 2019-11-13 23:29:21 +01:00
Araq
3020e49b75 ARC: use the new .cursor annotation for 'up' pointers 2019-11-13 23:29:21 +01:00
Andreas Rumpf
6ad0238fd7 make tests green again 2019-11-13 23:29:21 +01:00
Araq
25c724d38b gc:arc: support GC_ref/unref for ref T 2019-11-13 23:29:21 +01:00
Araq
eea0cb07cf async: cleaner solution that avoids GC_ref on strings which doesn't exist for --gc:arc 2019-11-13 23:29:21 +01:00
narimiran
a1e7bf81b3 a better way to test Arraymancer 2019-11-13 16:25:43 +01:00
narimiran
8394c00300 remove long-deprecated 'mapIt' 2019-11-13 14:24:25 +01:00
Arne Döring
0496a666e2 implemented alignas pragma (#12643)
* implemented alignas pragma

* fix bootstrap

* generate c++ compatible syntax for alignas

* Make it work.

* Multiple alignof expressions. Implement top level alignof.
2019-11-13 08:22:41 +00:00
Andreas Rumpf
84861eb48a fixes #12644 2019-11-12 23:56:19 +01:00
Andreas Rumpf
dfb020b174 .cursor implementation (#12637)
* cursors: first implementation
* added currently failing test
* .cursor works for doubly linked lists
* make -d:useMalloc work again
* added code to nil out refs in a destructor
* it's now called --gc:arc
* renderer.nim: render nkBreakState properly
* make simple closure iterators work without leaking
2019-11-12 15:05:36 +01:00
Euan
7e689873e2 Fix #12135 and #12109 (#12137)
* Fix #12135 and fix #12109 - fix OpenBSD type defs

* Fix Mode definition as in #12132
2019-11-11 16:18:08 +01:00
b3liever
0c4d81241a Version of trimZeros without temp strings (#12633) 2019-11-11 12:54:17 +01:00
Araq
a4d43d7d0c --gc:destructors: bugfixes 2019-11-09 20:34:51 +01:00
Araq
e835377d3f inhibit silly warning about moving closure environments for performance 2019-11-09 20:33:23 +01:00
Andreas Rumpf
82e0765fc9 --gc:destructors improvements (#12626)
* do not cache the noDestructors transformation
* liftdestructor: improvements
* undo bugfix
2019-11-09 13:21:55 +01:00
Clyybber
144ad36974 Implemented outplace differently (#12599)
* implemented sugar.outplace; refs #12550
* Different approach, allows for chaining
2019-11-09 12:52:31 +01:00
Miran
6958248efe fix #12519: introduce OrderedTable.take, CountTable.del, CountTable.take (#12600)
* add OrderedTable.take

* add CountTable.del and CountTable.take

* add .since pragma to the introduced public procs

* add changelog entry [ci skip]
2019-11-08 16:35:27 +01:00
cooldome
1e71c13697 fix compilation warning (#12618)
* fix compilation warning

* comments incorporated
2019-11-08 09:16:44 +01:00
Volodymyr Lashko
4e841ab156 Fix crash in terminate handler (#12572) [backport]
* fix undefined behavior in terminate handler

* fix failing unit test

* Revert "fix failing unit test"

This reverts commit 0e5e385fbf.

* Revert "fix undefined behavior in terminate handler"

This reverts commit 2b582871f1.

* do not throw inside terminate handler with msvc < 1923
2019-11-07 22:00:34 +00:00
Andreas Rumpf
135e945ff0 make parsexml compatible with --gc:destructors/newruntime 2019-11-07 18:18:51 +01:00
Yanis Zafirópulos
76085e8a45 added support for openArray's for gcd and lcm (#12621) 2019-11-07 18:06:48 +01:00
Arne Döring
a2d6691af2 fix #12597 (#12604) 2019-11-07 17:16:34 +01:00
Judd
8b1ef8e07e allow random module to be used in standalone: (#12617)
proc randomized*() uses time releated function which is not available on
standalone, so disable this function for standalone.
2019-11-07 14:48:33 +01:00
cooldome
e1b1759439 fixes #5050; fixes #11826 (#12606) [backport] 2019-11-07 14:47:26 +01:00
Arne Döring
94675c2378 backtick and export marker handling in eqIdent (#12574) 2019-11-07 14:40:44 +01:00
Andreas Rumpf
372b01711e added 'since' template for further stdlib additions 2019-11-07 14:20:39 +01:00
Andreas Rumpf
f69ee294c8 bugfix that enables the 'since' template [backport] 2019-11-07 14:20:39 +01:00
Andreas Rumpf
14a0182ca6 pragmas.nim: tiny code formatting 2019-11-07 14:20:39 +01:00
narimiran
0d00bde4ea fix failing test 2019-11-07 11:04:41 +01:00
Andreas Rumpf
166048da5d osproc needs 'import linux' for -d:useClone 2019-11-07 09:51:15 +01:00
Andreas Rumpf
230c618eb9 error message: Nim calls it 'proc' 2019-11-07 09:41:04 +01:00
Dominik Picheta
675189c77f Merge pull request #12613 from nim-lang/miran-unused-imports
Remove unused imports
2019-11-06 22:08:43 +00:00
Andy Davidoff
5544a13236 restore --define🔑val in nim.cfg and fix #12367 (#12611) 2019-11-06 21:26:03 +01:00
Andy Davidoff
738c957e94 add --clearNimblePath; fixes #12601 (#12609) 2019-11-06 20:40:22 +01:00
narimiran
717da9f158 [backport] print more information for the previous commit 2019-11-06 16:14:28 +01:00
narimiran
5381c810a8 [backport] rewrite flaky runnable example 2019-11-06 15:54:21 +01:00
narimiran
c6a451c584 remove unused imports from tests 2019-11-06 14:35:45 +01:00
Tor Arvid Lund
5ccbf7e3cf [backport] doc/tut3.rst: Fix typo in Introduction (#12607) [ci skip]
Derivative of `b*pow(x, 2)` is `2*b*x`, while old version had `2*a*x`
2019-11-06 13:42:39 +01:00
narimiran
cc3e9ca164 remove unused imports 2019-11-06 12:01:00 +01:00
Andy Davidoff
61889c604a export nim.cfg parser (#12602) 2019-11-06 09:59:23 +01:00
Federico Ceratto
59c212607e [backport] Add links to packaging and distro pages (#12603) [ci skip] 2019-11-06 09:03:28 +01:00
Araq
d19206755b async: use $ and not repr in debug mode 2019-11-05 17:10:02 +01:00
Araq
1794cd477d expr -> untyped 2019-11-05 16:55:08 +01:00
jiro
0694bd47b9 Add or detectOs(Manjaro) (#12587) [backport]
Using `pacman` command in Manjaro Linux

(cherry picked from commit 1ff3494dab)
2019-11-05 16:21:28 +01:00
Andreas Rumpf
3ba3307d61 remove deprecated procs (#12535) 2019-11-05 11:05:46 +01:00
Miran
ffa9a7405f fix #8242, fix #12586: fix 'formatFloat' with 'precision = 0' (#12592)
* fix #8242, fix #12586: fix 'formatFloat' with 'precision = 0'

'formatFloat' with 'precision = 0' now gives the same result
(a number without a decimal point) in all backends.
This is compatible with Python's formatters, too.

* fix failing tests

* add changelog entry

* add version switch
2019-11-05 10:31:23 +01:00
Andreas Rumpf
46af8164c0 implement the --useVersion emulation feature 2019-11-04 21:58:26 +01:00
Kaushal Modi
b24560a140 Make sequtils.zip return seq of anonymous tuples (#12575)
* Make sequtils.zip return seq of anonymous tuples

Earlier the tuples had named fields "a" and "b" and that made it
difficult to assign the zip returned seqs to other vars which expected
seqs of tuples with field names other than "a" and "b".

* Make sequtils.zip backwards compatible with Nim 1.0.x
2019-11-04 21:11:43 +01:00
Clyybber
cf5c3f2400 Fixes #12379 (#12591) [backport] 2019-11-04 20:57:14 +01:00
alaviss
558ecd1ca6 compiler/suggest: add variable support to con (#12569)
This allows for the type of a variable to be retrieved.
2019-11-04 18:29:26 +01:00
Miran
ae32d637f7 [backport] fix #12395 (#12590)
'countBits32' is now fixed in the same way that
'countBits64' was already patched earlier (by adding 'u32
where needed).
2019-11-04 15:02:36 +01:00
Arne Döring
992f0a7756 fix conversions to uint in varints.nim (#12564) 2019-11-04 13:06:08 +01:00
Andreas Rumpf
62fc3db9d7 --os:ios needs to imply defined(macosx) [backport] (#12585) 2019-11-04 13:05:03 +01:00
narimiran
bdc2bcc36c NimPatch of devel version should be an odd number because of the earlier hacks 2019-11-03 16:04:21 +01:00
Andreas Rumpf
3f4b9971fc newruntime: only check for dangling refs when 'owned ref T' support is enabled 2019-11-03 09:46:49 +01:00
Juan Carlos
4c9a7e6f00 JS improve indent (#12581)
* JSgen make indent be all spaces, instead of mixed spaces and tabs, for generated JS
2019-11-03 08:03:03 +01:00
Andreas Rumpf
ceda586d88 fixes #12577 [backport] (#12584) 2019-11-03 07:55:55 +01:00
Tomohiro
4e0f12092e Fixes #12536 (#12568) [backport] 2019-11-02 08:21:49 +01:00
Andreas Rumpf
44a27ccfe1 --gc:destructors: simple closures work 2019-11-02 00:39:04 +01:00
Andreas Rumpf
7a4d066102 make renderIds work again 2019-11-01 21:02:44 +01:00
Andreas Rumpf
3761e62fde improve codegen quality for --gc:destructors 2019-11-01 09:59:18 +01:00
Kaushal Modi
d914e9a65f [backport] Add docs to better distinguish among getProjectPath, getCurrentDir and currentSourcePath (#12565)
Fixes https://github.com/nim-lang/Nim/issues/10477.
2019-10-31 21:00:18 +01:00
Arne Döring
99078d80d7 introduce csize_t instead of fixing csize (#12497) 2019-10-31 19:18:12 +01:00
genotrance
0c7b6c9c15 Switch mingw links (#12561) 2019-10-31 11:13:32 +01:00
Andreas Rumpf
79a262d6e9 better testing for nimcrypto; re-enable chronos testing (#12560) 2019-10-31 07:18:45 +01:00
Andreas Rumpf
1746da2d9e --gc:destructors now means Nim uses pure refcounting (#12557) 2019-10-30 16:15:17 +01:00
Juan Carlos
b5bb581642 Improve Math.Trunc code emit on JS, had weird whitespaces and indents (#12549) 2019-10-30 14:12:17 +01:00
Nindaleth
34dbc5699e fix several typos in documentation and comments (#12553) 2019-10-30 09:08:45 +01:00
Araq
1214960a1b fixes #12547 [backport] 2019-10-29 15:07:04 +01:00
zah
de5f6a07c2 Fix newLit for objects having string fields (#12542) [backport] 2019-10-28 22:45:55 +01:00
Araq
44b1ecc287 destructors.rst: added a missing 'var' to the motivating example 2019-10-28 18:15:17 +01:00
Andreas Rumpf
e58c2d261c [backport] fix #12528, fix #12525: incorrect generic type resolution for default values (#12538) 2019-10-28 16:56:38 +01:00
Andreas Rumpf
c52a2c3ab0 proof that refcounting can handle Nim's async (#12533) 2019-10-28 16:13:38 +01:00
Solitude
160c07be00 Fix code style errors (#12545) 2019-10-28 15:21:10 +01:00
Anthon van der Neut
c58aa7705d [backport] fix broken link to non-existing c2nim manual html, fixes #12537 [ci skip] (#12544) 2019-10-28 13:51:43 +01:00
Tomohiro
90376940bb Add a changelog entry related to PR #11748 [ci skip] (#12541) 2019-10-28 13:29:13 +01:00
Jjp137
ee119f7984 colors: fix 'mix' template and make most examples runnable (#12532) [backport]
* colors: fix the 'mix' template
* colors: make most examples runnable
2019-10-28 13:11:11 +01:00
Artem V L
580462c886 splitPath() behavior synchronized with splitFile() (#12481)
* splitPath() behavior synchronized with splitFile() having the expected behavior in all languages

splitPath() docstrings update, tests added for both splitPath() and splitFile()

* Path splitting refined and described
2019-10-28 12:58:02 +01:00
Tomohiro
a9d7796e1c [feature]strformat: add 2 'fmt' macros that use specified characters instead of '{}' (#11748)
* [feature]strformat: add 2 'fmt' macros that use specified chars instead of '{}'

* strformat: revert documentation comments of `&` and 'fmt'

* strformat: removed single open/close char variant of fmt
2019-10-28 12:33:44 +01:00
Arne Döring
5ed99f8d3f Extent json.to testing to VM, add workrounds for VM bugs. (#12493)
fixes #12479
2019-10-28 10:06:16 +01:00
Miran
a2ad7d4883 fix deprecation warnings related to Int128 (#12474)
* semfold: fix deprecation warnings related to Int128

* semmagic: fix deprecation warnings related to Int128

* system/io: remove unneeded conversion of TaintedString to itself
2019-10-28 09:58:39 +01:00
Arne Döring
91af075244 integer literal documentation [ci skip] (#12513)
* integer literal documentation [ci skip]

* apply feedback [ci skip]
2019-10-28 09:52:59 +01:00
Andreas Rumpf
7192b13609 some progress on bug #12443 2019-10-27 17:50:30 +01:00
Andreas Rumpf
cbbc2cc237 fixes #12502 2019-10-27 17:50:30 +01:00
Andreas Rumpf
120829155a development version should be 1.1.0 so that version checking can work properly 2019-10-27 17:50:30 +01:00
Andreas Rumpf
0631d2dccc minor improvements 2019-10-27 17:50:30 +01:00
Tomohiro
f3b56e7ac0 Add /nologo option when nim call cl.exe (#12524) 2019-10-27 11:36:38 +01:00
Arne Döring
3c567bcf20 fixes #12514 (#12520) [backport] 2019-10-27 11:34:33 +01:00
Jjp137
3a62cf29d8 Remove sentences referring to the graphics module (#12522) 2019-10-26 04:28:01 -04:00
Artem V L
60ff41a8da '#' value parcing is explained (disambiguated) (#12476) 2019-10-25 15:22:26 +02:00
Jjp137
1d42108fda sequtils: replace deprecated 'random' call within example (#12515) [backport] 2019-10-25 09:47:34 +02:00
alaviss
5b3571c9a4 compiler/semtypes: improve lineinfo for exported object fields (#12495)
The line info should now points to the `a`, not the `*`, like this:
    a*: string
    ^
Additionally this fixes nimsuggest's highlighting of exported object
fields.
2019-10-25 01:06:53 +02:00
Andreas Rumpf
e0d13abaff VM: fixes register leaks [backport] (#12510) 2019-10-25 00:45:06 +02:00
Tomohiro
8040c84615 Fix Nim specify wrong option to vccexe when vcc.options.always is set (#12490) [backport] 2019-10-24 23:43:59 +02:00
Andreas Rumpf
8a599fb571 fixes #12491 [backport] 2019-10-24 22:51:13 +02:00
alaviss
f827d75804 compiler/semcall: return the correct lineinfo for nkCallStrLit (#12484) 2019-10-24 18:21:37 +02:00
Andreas Rumpf
801a794039 VM: fixes most ran-out-registers problems [backport] (#12485) 2019-10-24 17:29:32 +02:00
Federico Ceratto
9ac062b746 [backport] Add link to posix_utils.html - related to #10723 (#12509) 2019-10-24 14:08:59 +02:00
UNIcodeX
d731646106 [backport] Clarifies experimental / parallel example on manual.rst (#12472)
* Clarifies experimental / parallel on manual.rst

Details:
Calling `useParallel()` in example fails with compiler error
  Error: 'parallel' section without 'spawn'

Adding `spawn` causes error:
  Error: internal error: (filename: "ccgexprs.nim", line: 1032, column: 17)
  No stack traceback available
  To create a stacktrace, rerun compilation with ./koch temp c <file>

Therefore a separate proc, `threadedEcho`, is added for the echo'ing
of the string, which allows the example to build, however, `sync()`
must be added so that the "echo in parallel" strings will actually
be shown on the terminal. Otherwise, the program will spawn of the
threads and exit before they can return to the main thread.

* Fixes and clarifies example for threading in manual.rst

Issue:
Calling useParallel() in example failed with compiler error
`Error: 'parallel' section without 'spawn'`

Adding spawn yielded compiler error:
```bash
Error: internal error: (filename: "ccgexprs.nim", line: 1032, column: 17)
No stack traceback available
To create a stacktrace, rerun compilation with ./koch temp c
```

Proposed Solution:
- Separate proc, threadedEcho, is added for the echo'ing
  of the string, which allows the example to build
- Added the thread number so that it can demonstrate that sometimes
  threads which were started sooner, come back after threads which
  were started later.
2019-10-24 14:08:27 +02:00
Miran
b03de8a4d9 Fix many broken links and prefer relative links within docs (#12463)
* Fix many broken links

Note that contrary to what docgen.rst currently says, the ids have
to match exactly or else most web browsers will not jump to the
intended symbol.

* Prefer relative links for Nim documentation

This is more friendly to those browsing the documentation without
a network connection. The nim-doc package in Debian allows this,
for example.

Also, the domain name being used was not consistent. It could have
been either nim-lang.org or nim-lang.github.io, and those reading
the stable docs could have found themselves suddenly reading the
devel docs instead.

* koch.rst: remove link to nonexistent section

* manual.rst: remove unintended link

cast[T](0) is interpreted as a link to id 0 with text T, so escape
the opening parentheses to display the intended output.

* asyncstreams: replace unintended link with emphasis

* Fix word wrapping
2019-10-24 14:07:43 +02:00
Juan Carlos
8f8916413f [backport] Documentation Math module (#12460) 2019-10-24 14:07:21 +02:00
narimiran
2baa21d461 disable package 'chronos' for now 2019-10-24 13:46:59 +02:00
Araq
a03a8e80ea fixes a regression that caused that Nim devel cannot compile 1.0 anymore 2019-10-24 12:27:34 +02:00
Araq
e506c1e0ea fixes a regression that caused that Nim devel cannot compile 1.0 anymore 2019-10-24 12:27:34 +02:00
Araq
619b997c31 ast.nim: slightly better documentation 2019-10-24 12:27:34 +02:00
Oscar Nihlgård
3d0c756a3c Fix JS bug in std/monotimes (#12499) [backport] 2019-10-24 11:24:26 +02:00
Oscar Nihlgård
4ac100c912 Fix jsgen bug with uninitialized seq (#12500) [backport] 2019-10-24 11:17:01 +02:00
Oscar Nihlgård
9ccfcf5dd2 Fix compiler crash caused by top level return (#12501) 2019-10-24 11:04:04 +02:00
narimiran
822078ed12 add changelog for v1.0.2 2019-10-23 14:35:31 +02:00
Arne Döring
8d3d97aa9b no html comments in issue template [skip ci] (#12496) 2019-10-23 12:08:17 +02:00
narimiran
d5cd5b00b9 disable flaky test on OSX 2019-10-23 11:24:43 +02:00
narimiran
2120fb2777 [backport] package chronos now has dependencies 2019-10-23 11:20:12 +02:00
Arne Döring
fe4a59f12b fixes #12453 (#12475) 2019-10-23 10:29:12 +02:00
narimiran
c90b4ecddc Revert "[ci skip] disable two packages until #11764 is merged"
This reverts commit 48975bb3e7.
2019-10-23 07:09:08 +02:00
Jjp137
3ad48069d3 Fix word wrapping 2019-10-22 17:59:12 -07:00
Jjp137
e6d5379b3b asyncstreams: replace unintended link with emphasis 2019-10-22 17:59:12 -07:00
Jjp137
59c1f7c87f manual.rst: remove unintended link
cast[T](0) is interpreted as a link to id 0 with text T, so escape
the opening parentheses to display the intended output.
2019-10-22 17:59:12 -07:00
Jjp137
79aa58979c koch.rst: remove link to nonexistent section 2019-10-22 17:59:12 -07:00
Jjp137
72147c9ba4 Prefer relative links for Nim documentation
This is more friendly to those browsing the documentation without
a network connection. The nim-doc package in Debian allows this,
for example.

Also, the domain name being used was not consistent. It could have
been either nim-lang.org or nim-lang.github.io, and those reading
the stable docs could have found themselves suddenly reading the
devel docs instead.
2019-10-22 17:59:12 -07:00
Jjp137
93461aee34 Fix many broken links
Note that contrary to what docgen.rst currently says, the ids have
to match exactly or else most web browsers will not jump to the
intended symbol.
2019-10-22 17:59:12 -07:00
Dominik Picheta
6bfa4eb6c5 Merge pull request #12371 from rayman22201/IOSelector_unregister_fix
Test + fix for epoll and kqueue selector modules to properly unregister event handles that have the key type "User"
2019-10-22 11:32:22 -07:00
Dominik Picheta
92fa7e0579 Merge branch 'devel' into IOSelector_unregister_fix 2019-10-22 11:31:38 -07:00
Artem V L
049032432c Docstring refined for the getSectionValue() (#12478) [backport] 2019-10-22 18:20:25 +02:00
Paul Tan
ad3c10022a guards.nim:sameTree(): handle uint literals correctly (#12483) [backport] 2019-10-22 18:18:33 +02:00
Andy Davidoff
2ccd1c3428 tweaked for clarity after editing to fix a typo (#12473) 2019-10-22 13:54:48 +02:00
Andreas Rumpf
38b3590e40 fixes #12310 [backport] (#12470) 2019-10-20 22:37:31 +02:00
Arne Döring
ec20fd3544 fix #12426 (#12462) 2019-10-20 11:52:50 +02:00
ducdetronquito
df4c339cfc Namespace unittest enums to avoid name conflicts (#12468) [backport]
* [backport] Fixes: #12465 - Unittest - Namespace the usage of TestStatus enum to avoid name conflicts.
2019-10-20 08:12:02 +02:00
Araq
0eae2217b6 first implementation of the new --seqsv2 switch 2019-10-20 08:11:07 +02:00
Araq
ed2fb36bc6 refactoring: use the new strings and seqs when optSeqDestructors is active 2019-10-20 08:11:07 +02:00
Araq
61ea85687c refactoring: --newruntime consists of 3 different switches 2019-10-20 08:11:07 +02:00
Ray Imber
91661c16a1 Update changelog.md based on feedback from Dom96 2019-10-19 14:30:10 -07:00
Andreas Rumpf
832b0a0232 fixes #12420 [backport] (#12456) 2019-10-18 22:13:24 +02:00
Tomohiro
6b157e5f73 Fix vcc linker option name (#12422) 2019-10-18 16:20:18 +02:00
Andreas Rumpf
889b745b2b Revert "Fixes #12187 (#12321)" (#12447)
This reverts commit 00c31e8766.
2019-10-18 15:59:22 +02:00
Juan Carlos
f5b4d9a2e5 Fixes #8802 (#12439)
* Fix #8802

* Peer review feedbacks https://github.com/nim-lang/Nim/pull/12439#discussion_r335905397
2019-10-18 14:27:23 +02:00
Juan Carlos
4a0debfe87 Add no-ident for GCC when -d:release (#12454) 2019-10-18 14:13:55 +02:00
Juan Carlos
0a6e0a3f38 Improve htmlgen (#12452) 2019-10-18 12:16:01 +02:00
Miran
a5ab502f08 [backport] fix type's case in random.nim (#12445) 2019-10-17 22:13:00 +02:00
Andreas Rumpf
81125e2029 [backport] add back a check that got accidentically removed; fixes #12379 (#12444) 2019-10-17 20:02:59 +02:00
Juan Carlos
4d1f69c7d2 Fixes #10824 (#12437) 2019-10-17 11:39:01 +02:00
Juan Carlos
2cfd58de48 Fix #10804 (#12438) 2019-10-17 11:37:55 +02:00
Juan Carlos
1ccf1b89c2 Improve jsconsole adding the rest of the stable api as documented on the standard at https://developer.mozilla.org/docs/Web/API/Console (#12440) 2019-10-17 11:37:08 +02:00
Arne Döring
21cbfd72ec Refactor json macro (#12391)
* closes #12316
* make tjsonmacro work at js target
* closes #12289
* closes #11988
* also fixed gdb related stuff
2019-10-17 09:55:41 +02:00
treeform
5ba932e43c About 50% faster base64 implemention. (#12436) 2019-10-17 09:50:00 +02:00
Ray Imber
bec8225448 Updated the changelog 2019-10-16 19:14:18 -07:00
Ray Imber
bef1c4437d fixes based on code review by @dom96
- For clarity: Changed the unregister if statement to use the in operator instead of
the set intersection operator in ioselectors_epoll.nim and
ioselectors_select.nim.

- Fixed unregister of Event.User case on the Android branch.
2019-10-16 14:13:09 -07:00
alaviss
37dfb7ecc6 compiler/options: only check the last folder for a candidate (#12421)
This prevents a nimble file from causing a different project to be
targeted instead of the desired one.
2019-10-16 13:03:11 +02:00
Miran
734da9e1df fixes #11764, faster hashing of (u)int (#12407) 2019-10-15 16:31:07 +02:00
Miran
5f5ac8ce16 [backport] fix #12418, fix random.randomize on JS backend (#12432) 2019-10-15 16:29:32 +02:00
Yuriy Glukhov
1aed455e7c Fixed yield in nkCheckedFieldExpr (#12429) [backport] 2019-10-15 09:16:06 +02:00
narimiran
48975bb3e7 [ci skip] disable two packages until #11764 is merged 2019-10-14 11:51:41 +02:00
Ray Imber
233455a685 Remove unnecessary change to ioselectors_kqueue.nim found by @cheatfate. 2019-10-11 12:24:29 -07:00
Alexander Ivanov
990aadc43c Fixes semCustomPragma when nkSym (#12414) [backport] 2019-10-11 18:05:23 +02:00
alaviss
94c1695be6 compiler/options: improve project file detection (#12404)
The compiler can now correctly find the project file of a nimble package.
The algorithm is based on what used by nim.nvim, which has yielded good
results.
2019-10-11 18:04:52 +02:00
alaviss
f957266574 nimsuggest: add a command that returns the project file (#12411)
This can be used to let nimsuggest users know which project is
nimsuggest being in charge of, so they can know when should a new
nimsuggest instance be spawned.

An additional feature is to debug the project file finding feature.
2019-10-11 18:00:38 +02:00
alaviss
eeffa0163f nimsuggest: add option to force finding the project file (#12409) 2019-10-11 09:55:15 +02:00
Arne Döring
7cf3395d85 refactor illegal iterator assignment detection (#12212)
* refactor illegal iterator assignment detection

* delete crappy test
2019-10-11 08:43:58 +02:00
Jasper Jenkins
245a954b25 ungeneric unsigned ops (#12230)
* ungenericise unsigned ops, remove nimNewShiftOps
* fix/remove tests
* update t6448
* fix line info
* disable on 32bit
* fix different line info
* add changelog entry
2019-10-11 08:38:08 +02:00
genotrance
9e62876647 Fixes #12286 - require explicit disabling of boehm interior pointer checking (#12406) [backport] 2019-10-11 07:39:18 +02:00
Ray Imber
4e6f2b5313 Fix drain to correctly take into account hasPendingOperations and the timeout value 2019-10-10 17:53:44 -07:00
Ray Imber
aa84d35d86 Fix io slector unregister for windows as well. 2019-10-10 16:50:36 -07:00
Euan
45030972b9 #12389: Check working directory for getAppFilename() (#12390)
* Check working directory for exe
* Expand symlinks
* Use expandFilename() to expand symlinks
* Move OpenBSD code to getApplOpenBsd()
2019-10-10 17:28:47 +02:00
Arne Döring
0a29c05a1b fix #12332 (#12402) [backport] 2019-10-10 14:35:26 +02:00
Andreas Rumpf
00e06bba28 minor improvements for htmlgen.nim 2019-10-10 13:47:55 +02:00
Andreas Rumpf
d783c0f7ff fixes a koch regression that made 'koch boot --listcmd' not work anymore [backport] (#12400) 2019-10-10 11:56:01 +02:00
Araq
7f904e2c66 fixes #12244 [backport] 2019-10-10 10:00:57 +02:00
awr1
3b1760df72 [backport] Mention "lambdas" and => in the manual (#12397) [ci skip]
(so that "lambda" can be CTRL+F'd)
2019-10-10 09:28:54 +02:00
Andreas Rumpf
f728614ef8 fixes #12366 [backport] (#12393) 2019-10-09 14:48:42 +02:00
Gampol T
82fe19769a documented behaviour of recv on bufferd socket (#12374) 2019-10-09 10:48:15 +02:00
Nindaleth
84c956d9da fix a few dead links and a missing sentence in documentation (#12387) 2019-10-08 15:24:34 -04:00
Andreas Rumpf
f30da2f266 fixes #12315 [backport]; refs #12314 (#12385) 2019-10-08 20:49:45 +02:00
Clyybber
00c31e8766 Fixes #12187 (#12321)
* Fixes #12187
* Point to fork of compactdict
Since the original repo is now archived / read-only
2019-10-08 14:15:47 +02:00
alaviss
edb24b7ce0 nimsuggest: fix tcp socket leak for epc backend (#12384) [backport]
Same as e9fa4c9b9c, but for the epc
backend which is used by emacs and vscode plugin.

Since the EPC backend only deal with one connection per nimsuggest
instance, only one socket is leaked, thus not as servere as with the tcp
backend.
2019-10-08 14:14:18 +02:00
Ray Imber
7c23522b29 Documentation improvements around the db interface (#12362)
Added more details about the limits and reasoning behind the API.
Came about from this discussion on IRC: https://irclogs.nim-lang.org/04-10-2019.html#16:58:04
2019-10-08 11:24:06 +02:00
Ridho Pratama
7ef4bffa79 renderer letAux fix only for octal literal (#12343)
* renderer letAux fix only for octal literal

* Handle when it's octal -1 for i64

* Added testcases
2019-10-08 11:12:24 +02:00
treeform
dbcffcfccb Easier build instructions for windows - just run build_all.bat. (#12276)
* Easier build instructions for windows.

* title letter

* Update build_all.bat to be like build_all.sh
2019-10-08 11:00:37 +02:00
pietroppeter
89c37fada7 [doc/tut1] removed discard discussion in comments (#12352) 2019-10-08 09:08:38 +02:00
alaviss
e9fa4c9b9c nimsuggest: fix tcp socket leak (#12377) [backport]
A new socket is created for each iteration and leak immediately thanks
to the accept() call replacing the created socket with the client socket.

This commit fixes that.
2019-10-08 08:11:18 +02:00
cooldome
0355c64b92 External file compilation improvement (#12380) 2019-10-08 08:10:55 +02:00
Tomohiro
509f53b782 On windows, os.relativePath returns path as is when roots are different (#12329)
* On windows, os.relativePath returns path as is when roots are different
* Implement os.sameRoot without windows API
* Fix compile error when compiling lib/nimhcr.nim
* Fix compile error when compiling lib/nimhcr.nim on Windows
2019-10-07 19:57:16 +02:00
Ray Imber
b347490f91 lowered the number of events in the test because some CI's have an extremely low FD limit 2019-10-07 10:07:05 -07:00
Federico Ceratto
f9d95fd6a7 Refactor closeEmitter to make it more modular (#12365) 2019-10-07 17:26:27 +02:00
Andreas Rumpf
a60f18d025 fixes #12323 [backport] 2019-10-07 06:47:30 +02:00
Andreas Rumpf
9d000c519a render typeof as typeof 2019-10-07 06:47:30 +02:00
Ray Imber
0338516e70 Additional fix for User key unregister in the KQueue backend 2019-10-06 17:33:58 -07:00
Ray Imber
adc1419499 Test + fix for epoll and kqueue selector modules to properly unregister
event handles that have the key type "User"
2019-10-06 16:02:12 -07:00
Andreas Rumpf
5be8e0b088 VM: no special casing for big endian machines; refs #9690 [backport] (#12364) 2019-10-06 19:28:53 +02:00
Federico Ceratto
a03d8ed4c2 Expose some layouter elements, improve readme (#12361)
Useful for writing linters and static code analysis
2019-10-04 22:43:47 +02:00
Ico Doornekamp
26676066cc added cpuTime to VM (#12346)
* added cpuTime to VM

* Hide VM-time cpuTime() behind --benchmarkVM flag
2019-10-04 19:32:16 +02:00
kraptor
412011eb96 Fix reference to parseSpec proc in readme (#12359) 2019-10-04 19:30:58 +02:00
Hideki Okamoto
294d5fb560 Fixes #12010; Add the description for "cc" option into --fullhelp (#12350) 2019-10-04 19:30:20 +02:00
Miran
2909e41370 [backport] bundle nimpretty on Windows (#12358) 2019-10-04 17:13:04 +02:00
Andreas Rumpf
60d64d1aef use system.move instead of system.shallowCopy if the GC mode requires it 2019-10-04 09:48:45 +02:00
Andreas Rumpf
68ce808db1 minor optimization for asynchttpserver.nim 2019-10-04 09:48:45 +02:00
Andrew Owen
64acc9dbfb [backport] Fix typo in docs (#12356) [ci skip] 2019-10-04 08:40:15 +02:00
Dominik Picheta
4ab9b6146b Change future version number in changelog 2019-10-03 21:26:20 +01:00
Ridho Pratama
678775601a Fixed sizeOf to sizeof (#12347) 2019-10-03 19:38:37 +02:00
Leorize
73c8391fd3 azure: disable failing tests 2019-10-03 18:36:18 +02:00
Leorize
acebcd7899 testament: add azure integration 2019-10-03 18:36:07 +02:00
Leorize
880df4de62 azure-pipelines: add pipelines for linux, mac and win
This is the equivalent to the current AppVeyor + Travis setup.
2019-10-03 18:35:54 +02:00
Andreas Rumpf
c51857f434 fixes #12291 [backport] (#12338) 2019-10-03 07:50:32 +02:00
Ico Doornekamp
982086dbe9 Fixed #12337, leaking pipe after gorge (#12339) 2019-10-03 00:48:31 -04:00
hlaaftana
ba43156363 Sets need copying in JS (#11392)
* Sets need copying in JS
* Fixes #11353
* Add test for #11353
2019-10-02 21:01:59 +02:00
zah
ad13e18c7c system.writeFile has been overloaded to also support openarray[byte] (#12313) 2019-10-02 20:34:03 +02:00
Timothee Cour
2446570350 fixes #12330 (#12331) 2019-10-02 17:57:24 +02:00
Andreas Rumpf
98e76a1058 fixes #12336 [backport] 2019-10-02 17:01:27 +02:00
narimiran
032c3b77db test more packages 2019-10-02 12:35:18 +02:00
Andrew Smith
0d94ee15c0 Updated the code example in the os module to use better grammar. (#12328) 2019-10-02 00:43:38 -04:00
Jasper Jenkins
c20778d2d3 Macro docs additions (#12270)
* small macros doc additions

* more changes

* fixes [ci skip]

* capitalization, couple additions

* nkNodeKind to nnkNodeKind
2019-10-01 08:55:26 -04:00
Clyybber
5f5879dc4c Refactor injectdestructors (#12295)
One improvement over #devel is visible in the transformation of getEnv. With this approach we move to result whenever possible.
2019-10-01 14:09:24 +02:00
Tomohiro
64d5e25821 Fix how relativePath handle case sensitiviy (#12312) [backport] 2019-10-01 09:09:59 +02:00
Andreas Rumpf
6dd4cbc3af fixes #12240 [backport] (#12308) 2019-10-01 05:52:51 +02:00
zah
a4ade43536 macros.newLit now works for ref object types (#12307) 2019-09-30 22:24:57 +02:00
Andreas Rumpf
dd082b6ec8 fixes #12264 [backport] (#12302) 2019-09-30 21:44:24 +02:00
Andreas Rumpf
72acf5de94 fixes #12281 [backport] 2019-09-30 20:42:16 +02:00
Andreas Rumpf
1964589a29 fixes #12294 [backport] 2019-09-30 20:01:25 +02:00
narimiran
5732bb41ef [backport] run nimpretty on the remaining files 2019-09-30 13:58:17 +02:00
narimiran
34d0be2ec1 [backport] run nimpretty on os-related stuff 2019-09-30 13:58:15 +02:00
narimiran
dcf3181bd1 [backport] run nimpretty on string stuff 2019-09-30 13:58:13 +02:00
narimiran
0ca9cc7419 [backport] run nimpretty on web stuff 2019-09-30 13:58:11 +02:00
narimiran
15895ebc3f [backport] run nimpretty on hashes 2019-09-30 13:58:10 +02:00
narimiran
b17ed2ca9c [backport] run nimpretty on parsers 2019-09-30 13:58:08 +02:00
narimiran
6c994b2498 [backport] run nimpretty on numbers stuff 2019-09-30 13:58:05 +02:00
narimiran
aa513d78e7 [backport] run nimpretty on async 2019-09-30 13:57:58 +02:00
Araq
63bcbea700 JS: gensym is stricter for 'this'; refs #12246 [backport] 2019-09-30 13:21:46 +02:00
Araq
c5a1149e00 different fix for #12279 [backport] 2019-09-30 13:11:24 +02:00
Araq
0ecf3806c4 fixes #12298 2019-09-30 12:06:41 +02:00
Araq
86de2cddf6 fixes #12279 [backport] 2019-09-30 10:40:00 +02:00
Clyybber
16c39f9b2e More of StringStream now works at compile time (#12284)
* readLine of StringStream now works at compile time
* Work for js backend only at compile time
* readAll now works at CT
* readAll works in js ct now
* Add test
2019-09-29 22:20:00 +02:00
Clyybber
85db42ad8c Fixes #10514 (#12268)
* Fixes #10514

(cherry picked from commit f6f789bb4d)

* Add comment

* Add changelog entry
2019-09-28 19:50:20 +02:00
Andrey Makarov
5a65243e14 fix nimgrep color on posix #7591 (#12288) 2019-09-28 00:19:57 +02:00
narimiran
f804245087 [backport] fix nimpretty removing space before pragma 2019-09-27 10:36:22 +02:00
narimiran
e0cd52365c [backport] fix #12278, don't expose internal PCRE documentation 2019-09-27 10:13:04 +02:00
narimiran
ce4eb4ac91 Nim now has Patreon account [ci skip] 2019-09-27 08:22:46 +02:00
Federico Ceratto
39290cf88c Fix spellings (#12277) [backport] 2019-09-27 07:02:54 +02:00
Ray Imber
9dd297f613 Locks modules should give a compile error when threads are not enabled. (#12231)
* Locks modules should give a compile error when threads are not enabled.

* fix the compile flags to make the tests pass, or ignore files where necessary.

* Fixed when statement to account for doc builds.
2019-09-26 15:45:50 +02:00
John Paul Adrian Glaubitz
944fcc0e62 Add build support for Linux/hppa (#12271)
* build.sh: Enable CPU detection for hppa
* compiler: Add hppa as target architecture on Linux
* lib/system: Add platform support for hppa
2019-09-26 15:45:05 +02:00
Endeg
657e09e79d Fix #12242, replacing ":" with "@c" in packages [backport] (#12265) 2019-09-25 20:32:36 +02:00
Mathias Stearn
920f9be9aa Explicitly state that trailing underscores are banned (#12257)
It was explicit in the BNF, but the English text implied it was allowed.
2019-09-25 19:12:54 +02:00
Andreas Rumpf
5f44651769 updated the contributing.rst guidelines 2019-09-25 15:01:35 +02:00
narimiran
6b4b329f45 devel version is 1.0.99 [ci skip] 2019-09-25 09:14:38 +02:00
Jjp137
e065e51245 threadpool: fix link in docs [ci skip] (#12258) [backport]
[backport]
2019-09-25 07:12:08 +02:00
treeform
cbefb266bb Fix -d:logGC compile cerror: 'stdout not defined' (#12237) 2019-09-24 12:02:53 +02:00
Jasper Jenkins
b49fb2d90f remove nimnomagic64 (#12243) 2019-09-24 12:02:25 +02:00
Andreas Rumpf
13960066cb fixes the --verbosity:2 regression [backport] 2019-09-24 01:31:03 +02:00
1730 changed files with 77918 additions and 137780 deletions

31
.builds/freebsd.yml Normal file
View File

@@ -0,0 +1,31 @@
# see https://man.sr.ht/builds.sr.ht/compatibility.md#freebsd
image: freebsd/latest
packages:
- databases/sqlite3
- devel/boehm-gc-threaded
- devel/pcre
- devel/sdl20
- devel/sfml
- www/node
- devel/gmake
sources:
- https://github.com/nim-lang/Nim
environment:
CC: /usr/bin/clang
tasks:
- setup: |
cd Nim
git clone --depth 1 -q https://github.com/nim-lang/csources_v1.git csources
gmake -C csources -j $(sysctl -n hw.ncpu)
bin/nim c --skipUserCfg --skipParentCfg koch
echo 'export PATH=$HOME/Nim/bin:$PATH' >> $HOME/.buildenv
- test: |
cd Nim
if ! ./koch runCI; then
nim c -r tools/ci_testresults.nim
exit 1
fi
triggers:
- action: email
condition: failure
to: Andreas Rumpf <rumpf_a@web.de>

34
.builds/openbsd_0.yml Normal file
View File

@@ -0,0 +1,34 @@
## do not edit directly; auto-generated by `nim r tools/ci_generate.nim`
image: openbsd/latest
packages:
- gmake
- sqlite3
- node
- boehm-gc
- pcre
- sfml
- sdl2
- libffi
sources:
- https://github.com/nim-lang/Nim
environment:
NIM_TESTAMENT_BATCH: "0_3"
CC: /usr/bin/clang
tasks:
- setup: |
cd Nim
git clone --depth 1 -q https://github.com/nim-lang/csources_v1.git csources
gmake -C csources -j $(sysctl -n hw.ncpuonline)
bin/nim c koch
echo 'export PATH=$HOME/Nim/bin:$PATH' >> $HOME/.buildenv
- test: |
cd Nim
if ! ./koch runCI; then
nim c -r tools/ci_testresults.nim
exit 1
fi
triggers:
- action: email
condition: failure
to: Andreas Rumpf <rumpf_a@web.de>

34
.builds/openbsd_1.yml Normal file
View File

@@ -0,0 +1,34 @@
## do not edit directly; auto-generated by `nim r tools/ci_generate.nim`
image: openbsd/latest
packages:
- gmake
- sqlite3
- node
- boehm-gc
- pcre
- sfml
- sdl2
- libffi
sources:
- https://github.com/nim-lang/Nim
environment:
NIM_TESTAMENT_BATCH: "1_3"
CC: /usr/bin/clang
tasks:
- setup: |
cd Nim
git clone --depth 1 -q https://github.com/nim-lang/csources_v1.git csources
gmake -C csources -j $(sysctl -n hw.ncpuonline)
bin/nim c koch
echo 'export PATH=$HOME/Nim/bin:$PATH' >> $HOME/.buildenv
- test: |
cd Nim
if ! ./koch runCI; then
nim c -r tools/ci_testresults.nim
exit 1
fi
triggers:
- action: email
condition: failure
to: Andreas Rumpf <rumpf_a@web.de>

34
.builds/openbsd_2.yml Normal file
View File

@@ -0,0 +1,34 @@
## do not edit directly; auto-generated by `nim r tools/ci_generate.nim`
image: openbsd/latest
packages:
- gmake
- sqlite3
- node
- boehm-gc
- pcre
- sfml
- sdl2
- libffi
sources:
- https://github.com/nim-lang/Nim
environment:
NIM_TESTAMENT_BATCH: "2_3"
CC: /usr/bin/clang
tasks:
- setup: |
cd Nim
git clone --depth 1 -q https://github.com/nim-lang/csources_v1.git csources
gmake -C csources -j $(sysctl -n hw.ncpuonline)
bin/nim c koch
echo 'export PATH=$HOME/Nim/bin:$PATH' >> $HOME/.buildenv
- test: |
cd Nim
if ! ./koch runCI; then
nim c -r tools/ci_testresults.nim
exit 1
fi
triggers:
- action: email
condition: failure
to: Andreas Rumpf <rumpf_a@web.de>

6
.gitattributes vendored Normal file
View File

@@ -0,0 +1,6 @@
# Avoids changelog conflicts by assuming additions-only, which is by far the common case.
# In the rare case where branch b1 rebases against branch b2 and both branches
# modified the same changelog entry, you'll end up with that changelog entry
# duplicated, which is easily identifiable and fixable.
/changelog.md merge=union

2
.github/FUNDING.yml vendored
View File

@@ -1,7 +1,7 @@
# These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
patreon: 'araq' # Replace with a single Patreon username
open_collective: 'nim' # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel

View File

@@ -1,46 +1,51 @@
---
name: Bug report
about: Have you found an unexpected behavior? Use this template.
title: Think about the title, twice
labels: ''
assignees: ''
---
<!-- Think about the title, twice. -->
<!-- Summarize the problem here, keep it short and simple. -->
Function `echo` outputs the wrong string.
### Example
<!-- Paste your example in the code-block below. -->
```nim
echo "Hello World!"
# This code should be a minimum reproducible example:
# try to simplify and minimize as much as possible. If it's a compiler
# issue, try to minimize further by removing any imports if possible.
```
### Current Output
please check whether the problem still exists in git head before posting,
see [rebuilding the compiler](https://nim-lang.github.io/Nim/intern.html#rebuilding-the-compiler).
```
Hola mundo!
```
### Expected Output
<!-- What should be the correct output? -->
```
Hello World!
```
### Possible Solution
<!--- Have you found a possible solution? Post it here. -->
* In file xyz there is a call that might be the cause of it.
### Additional Information
<!--- For Example:
* Your Nim version (output of `nim -v`).
* Was it working in the previous Nim releases?
* A link to a related issue or discussion.
* A project reference where (and how) the issue causes problems.
-->
If it's a regression, you can help us by identifying which version introduced
the bug, see [Bisecting for regressions](https://nim-lang.github.io/Nim/intern.html#bisecting-for-regressions),
or at least try known past releases (eg `choosenim 1.2.0`).
If it's a pre-existing compiler bug, see [Debugging the compiler](https://nim-lang.github.io/Nim/intern.html#debugging-the-compiler)
which should give more context on a compiler crash.
* Issue #abc is related, but different because of ...
* This issue is blocking my project xyz
```
$ nim -v
Nim Compiler Version 0.1.2
# make sure to include the git hash if not using a tagged release
```

View File

@@ -1,6 +1,9 @@
---
name: Feature request
about: Do you want to suggest a new feature? Use this template.
title: ''
labels: ''
assignees: ''
---

69
.github/stale.yml vendored Normal file
View File

@@ -0,0 +1,69 @@
# Configuration for probot-stale - https://github.com/probot/stale
# Number of days of inactivity before an Issue or Pull Request becomes stale
daysUntilStale: 365
# Number of days of inactivity before an Issue or Pull Request with the stale label is closed.
# Set to false to disable. If disabled, issues still need to be closed manually, but will remain marked as stale.
daysUntilClose: 30
# Only issues or pull requests with all of these labels are check if stale. Defaults to `[]` (disabled)
onlyLabels: []
# Issues or Pull Requests with these labels will never be considered stale. Set to `[]` to disable
exemptLabels:
- ARC
- bounty
- Codegen
- Crash
- Generics
- High Priority
- Macros
- Next release
- Showstopper
- Static[T]
# Set to true to ignore issues in a project (defaults to false)
exemptProjects: false
# Set to true to ignore issues in a milestone (defaults to false)
exemptMilestones: false
# Set to true to ignore issues with an assignee (defaults to false)
exemptAssignees: false
# Label to use when marking as stale
staleLabel: stale
# Comment to post when marking as stale. Set to `false` to disable
markComment: >
This pull request has been automatically marked as stale because it has not had
recent activity.
If you think it is still a valid PR, please rebase it on the latest devel;
otherwise it will be closed. Thank you for your contributions.
# Comment to post when removing the stale label.
# unmarkComment: >
# Your comment here.
# Comment to post when closing a stale Issue or Pull Request.
# closeComment: >
# Your comment here.
# Limit the number of actions per hour, from 1-30. Default is 30
limitPerRun: 20
# Limit to only `issues` or `pulls`
only: pulls
# Optionally, specify configuration settings that are specific to just 'issues' or 'pulls':
# pulls:
# daysUntilStale: 30
# markComment: >
# This pull request has been automatically marked as stale because it has not had
# recent activity. It will be closed if no further activity occurs. Thank you
# for your contributions.
# issues:
# exemptLabels:
# - confirmed

122
.github/workflows/ci.yml.disabled vendored Normal file
View File

@@ -0,0 +1,122 @@
name: Continous Integration
on: [push, pull_request]
jobs:
build:
strategy:
matrix:
os: [ubuntu-18.04, macos-10.15, windows-2019]
cpu: [amd64, i386]
cpp: ['false', 'true']
pkg: ['false', 'true']
exclude:
- os: ubuntu-18.04
cpp: 'true'
- os: ubuntu-18.04
pkg: 'true'
- os: macos-10.15
cpu: i386
- os: macos-10.15
pkg: 'true'
- os: windows-2019
cpu: i386
- os: windows-2019
cpp: 'true'
name: '${{ matrix.os }} (${{ matrix.cpu }}, cpp: ${{ matrix.cpp }}, pkg: ${{ matrix.pkg }})'
runs-on: ${{ matrix.os }}
env:
NIM_COMPILE_TO_CPP: ${{ matrix.cpp }}
NIM_TEST_PACKAGES: ${{ matrix.pkg }}
steps:
- name: 'Checkout'
uses: actions/checkout@v2
- name: 'Checkout csources'
uses: actions/checkout@v2
with:
repository: nim-lang/csources
path: csources
- name: 'Install node.js 8.x'
uses: actions/setup-node@v1
with:
node-version: '8.x'
- name: 'Install dependencies (Linux amd64)'
if: runner.os == 'Linux' && matrix.cpu == 'amd64'
run: |
sudo apt-fast update -qq
DEBIAN_FRONTEND='noninteractive' \
sudo apt-fast install --no-install-recommends -yq \
libcurl4-openssl-dev libgc-dev libsdl1.2-dev libsfml-dev \
valgrind libc6-dbg
- name: 'Install dependencies (Linux i386)'
if: runner.os == 'Linux' && matrix.cpu == 'i386'
run: |
sudo dpkg --add-architecture i386
sudo apt-fast update -qq
DEBIAN_FRONTEND='noninteractive' \
sudo apt-fast install --no-install-recommends --allow-downgrades -yq \
g++-multilib gcc-multilib libcurl4-openssl-dev:i386 libgc-dev:i386 \
libsdl1.2-dev:i386 libsfml-dev:i386 libglib2.0-dev:i386 \
libffi-dev:i386
cat << EOF > bin/gcc
#!/bin/bash
exec $(which gcc) -m32 "\$@"
EOF
cat << EOF > bin/g++
#!/bin/bash
exec $(which g++) -m32 "\$@"
EOF
chmod 755 bin/gcc
chmod 755 bin/g++
- name: 'Install dependencies (macOS)'
if: runner.os == 'macOS'
run: brew install boehmgc make sfml
- name: 'Install dependencies (Windows)'
if: runner.os == 'Windows'
shell: bash
run: |
mkdir dist
curl -L https://nim-lang.org/download/mingw64.7z -o dist/mingw64.7z
curl -L https://nim-lang.org/download/dlls.zip -o dist/dlls.zip
7z x dist/mingw64.7z -odist
7z x dist/dlls.zip -obin
echo "${{ github.workspace }}/dist/mingw64/bin" >> "${GITHUB_PATH}"
- name: 'Add build binaries to PATH'
shell: bash
run: echo "${{ github.workspace }}/bin" >> "${GITHUB_PATH}"
- name: 'Build csources'
shell: bash
run: |
ncpu=
case '${{ runner.os }}' in
'Linux')
ncpu=$(nproc)
;;
'macOS')
ncpu=$(sysctl -n hw.ncpu)
;;
'Windows')
ncpu=$NUMBER_OF_PROCESSORS
;;
esac
[[ -z "$ncpu" || $ncpu -le 0 ]] && ncpu=1
make -C csources -j $ncpu CC=gcc ucpu='${{ matrix.cpu }}'
- name: 'Build koch'
shell: bash
run: nim c koch
- name: 'Run CI'
shell: bash
run: ./koch runCI
- name: 'Show failed tests'
if: failure()
shell: bash
run: nim c -r tools/ci_testresults.nim

145
.github/workflows/ci_docs.yml vendored Normal file
View File

@@ -0,0 +1,145 @@
name: Nim Docs CI
on:
push:
paths:
- 'compiler/docgen.nim'
- 'compiler/renderverbatim.nim'
- 'config/nimdoc.cfg'
- 'doc/**.rst'
- 'doc/nimdoc.css'
- 'lib/**.nim'
- 'nimdoc/testproject/expected/testproject.html'
- 'tools/dochack/dochack.nim'
- 'tools/kochdocs.nim'
- '.github/workflows/ci_docs.yml'
- 'koch.nim'
pull_request:
# Run only on changes on these files.
paths:
- 'compiler/docgen.nim'
- 'compiler/renderverbatim.nim'
- 'config/nimdoc.cfg'
- 'doc/**.rst'
- 'doc/nimdoc.css'
- 'lib/**.nim'
- 'nimdoc/testproject/expected/testproject.html'
- 'tools/dochack/dochack.nim'
- 'tools/kochdocs.nim'
- '.github/workflows/ci_docs.yml'
jobs:
build:
if: |
!contains(format('{0} {1}', github.event.head_commit.message, github.event.pull_request.title), '[skip ci]')
strategy:
fail-fast: false
matrix:
target: [linux, windows, osx]
include:
- target: linux
os: ubuntu-18.04
- target: windows
os: windows-2019
- target: osx
os: macos-11
name: ${{ matrix.target }}
runs-on: ${{ matrix.os }}
steps:
- name: 'Checkout'
uses: actions/checkout@v2
- name: 'Install build dependencies (macOS)'
if: runner.os == 'macOS'
run: brew install make
- name: 'Install build dependencies (Windows)'
if: runner.os == 'Windows'
shell: bash
run: |
mkdir dist
curl -L https://nim-lang.org/download/mingw64.7z -o dist/mingw64.7z
curl -L https://nim-lang.org/download/dlls.zip -o dist/dlls.zip
7z x dist/mingw64.7z -odist
7z x dist/dlls.zip -obin
echo "${{ github.workspace }}/dist/mingw64/bin" >> "${GITHUB_PATH}"
- name: 'Add build binaries to PATH'
shell: bash
run: echo "${{ github.workspace }}/bin" >> "${GITHUB_PATH}"
- name: 'Get current csources version'
id: csources-version
shell: bash
run: |
sha=$(git ls-remote https://github.com/nim-lang/csources_v1 master | cut -f 1)
echo "::set-output name=sha::$sha"
- name: 'Get prebuilt csources from cache'
id: csources-cache
uses: actions/cache@v1
with:
path: bin
key: '${{ matrix.os }}-${{ steps.csources-version.outputs.sha }}'
- name: 'Checkout csources'
if: steps.csources-cache.outputs.cache-hit != 'true'
uses: actions/checkout@v2
with:
repository: nim-lang/csources_v1
path: csources
- name: 'Build 1-stage compiler from csources'
shell: bash
run: |
ext=
[[ '${{ runner.os }}' == 'Windows' ]] && ext=.exe
if [[ ! -x bin/nim-csources$ext ]]; then
ncpu=
case '${{ runner.os }}' in
'Linux')
ncpu=$(nproc)
;;
'macOS')
ncpu=$(sysctl -n hw.ncpu)
;;
'Windows')
ncpu=$NUMBER_OF_PROCESSORS
;;
esac
[[ -z "$ncpu" || $ncpu -le 0 ]] && ncpu=1
make -C csources -j $ncpu CC=gcc
cp bin/nim{,-csources}$ext
else
echo 'Cache hit, using prebuilt csources'
cp bin/nim{-csources,}$ext
fi
- name: 'Build koch'
shell: bash
run: nim c koch
- name: 'Build the real compiler'
shell: bash
run: ./koch boot -d:release
- name: 'Clone fusion'
shell: bash
run: ./koch fusion
- name: 'Build documentation'
shell: bash
run: ./koch doc --git.commit:devel
- name: 'Publish documentation to Github Pages'
if: |
github.event_name == 'push' && github.ref == 'refs/heads/devel' &&
matrix.target == 'linux'
uses: crazy-max/ghaction-github-pages@v1
with:
build_dir: doc/html
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

85
.github/workflows/ci_packages.yml vendored Normal file
View File

@@ -0,0 +1,85 @@
name: Packages CI
on: [push, pull_request]
jobs:
build:
if: |
!contains(format('{0} {1}', github.event.head_commit.message, github.event.pull_request.title), '[skip ci]')
strategy:
fail-fast: false
matrix:
os: [ubuntu-20.04, macos-11]
cpu: [amd64]
pkg: [1, 2]
name: '${{ matrix.os }} (pkg: ${{ matrix.pkg }})'
runs-on: ${{ matrix.os }}
env:
NIM_TEST_PACKAGES: ${{ matrix.pkg }}
steps:
- name: 'Checkout'
uses: actions/checkout@v2
- name: 'Checkout csources'
uses: actions/checkout@v2
with:
repository: nim-lang/csources
path: csources
- name: 'Install node.js 12.x'
uses: actions/setup-node@v1
with:
node-version: '12.x'
- name: 'Install dependencies (Linux amd64)'
if: runner.os == 'Linux' && matrix.cpu == 'amd64'
run: |
sudo apt-fast update -qq
DEBIAN_FRONTEND='noninteractive' \
sudo apt-fast install --no-install-recommends -yq \
libcurl4-openssl-dev libgc-dev libsdl1.2-dev libsfml-dev \
valgrind libc6-dbg libblas-dev xorg-dev
- name: 'Install dependencies (macOS)'
if: runner.os == 'macOS'
run: brew install boehmgc make sfml gtk+3
- name: 'Install dependencies (Windows)'
if: runner.os == 'Windows'
shell: bash
run: |
mkdir dist
curl -L https://nim-lang.org/download/mingw64.7z -o dist/mingw64.7z
curl -L https://nim-lang.org/download/dlls.zip -o dist/dlls.zip
7z x dist/mingw64.7z -odist
7z x dist/dlls.zip -obin
echo "${{ github.workspace }}/dist/mingw64/bin" >> "${GITHUB_PATH}"
- name: 'Add build binaries to PATH'
shell: bash
run: echo "${{ github.workspace }}/bin" >> "${GITHUB_PATH}"
- name: 'Build csources'
shell: bash
run: |
ncpu=
case '${{ runner.os }}' in
'Linux')
ncpu=$(nproc)
;;
'macOS')
ncpu=$(sysctl -n hw.ncpu)
;;
'Windows')
ncpu=$NUMBER_OF_PROCESSORS
;;
esac
[[ -z "$ncpu" || $ncpu -le 0 ]] && ncpu=1
make -C csources -j $ncpu CC=gcc ucpu='${{ matrix.cpu }}'
- name: 'Build koch'
shell: bash
run: nim c koch
- name: 'Run CI'
shell: bash
run: ./koch runCI
- name: 'Show failed tests'
if: failure()
shell: bash
run: nim c -r tools/ci_testresults.nim

93
.github/workflows/ci_ssl.yml vendored Normal file
View File

@@ -0,0 +1,93 @@
name: Nim SSL CI
on:
pull_request:
# Run only on changes on related files
paths:
- 'lib/pure/httpclient.nim'
- 'lib/pure/net.nim'
- 'lib/pure/ssl_certs.nim'
- 'lib/wrappers/openssl.nim'
- 'tests/stdlib/thttpclient_ssl*'
- 'tests/untestable/thttpclient_ssl*'
jobs:
build:
if: |
!contains(format('{0} {1}', github.event.head_commit.message, github.event.pull_request.title), '[skip ci]')
strategy:
fail-fast: false
matrix:
os: [ubuntu-18.04, macos-10.15, windows-2019]
cpu: [amd64]
name: '${{ matrix.os }} (${{ matrix.cpu }})'
runs-on: ${{ matrix.os }}
steps:
- name: 'Checkout'
uses: actions/checkout@v2
- name: 'Checkout csources'
uses: actions/checkout@v2
with:
repository: nim-lang/csources
path: csources
- name: 'Install dependencies (Linux amd64)'
if: runner.os == 'Linux' && matrix.cpu == 'amd64'
run: |
sudo apt-fast update -qq
DEBIAN_FRONTEND='noninteractive' \
sudo apt-fast install --no-install-recommends -y libssl1.1
- name: 'Install dependencies (macOS)'
if: runner.os == 'macOS'
run: brew install make
- name: 'Install dependencies (Windows)'
if: runner.os == 'Windows'
shell: bash
run: |
mkdir dist
curl -L https://nim-lang.org/download/mingw64.7z -o dist/mingw64.7z
curl -L https://nim-lang.org/download/dlls.zip -o dist/dlls.zip
7z x dist/mingw64.7z -odist
7z x dist/dlls.zip -obin
echo "${{ github.workspace }}/dist/mingw64/bin" >> "${GITHUB_PATH}"
- name: 'Add build binaries to PATH'
shell: bash
run: echo "${{ github.workspace }}/bin" >> "${GITHUB_PATH}"
- name: 'Build 1-stage compiler from csources'
shell: bash
run: |
ncpu=
case '${{ runner.os }}' in
'Linux')
ncpu=$(nproc)
;;
'macOS')
ncpu=$(sysctl -n hw.ncpu)
;;
'Windows')
ncpu=$NUMBER_OF_PROCESSORS
;;
esac
[[ -z "$ncpu" || $ncpu -le 0 ]] && ncpu=1
make -C csources -j $ncpu CC=gcc ucpu='${{ matrix.cpu }}'
- name: 'Build koch'
shell: bash
run: nim c koch
- name: 'Build the real compiler'
shell: bash
run: ./koch boot
- name: 'Run SSL nimDisableCertificateValidation integration tests'
shell: bash
run: nim c -d:nimDisableCertificateValidation -d:ssl -r -p:. tests/untestable/thttpclient_ssl_disabled.nim
- name: 'Run SSL certificate check integration tests'
# Not supported on Windows due to old openssl version
if: runner.os != 'Windows'
shell: bash
run: nim c -d:ssl -p:. --threads:on -r tests/untestable/thttpclient_ssl.nim

18
.gitignore vendored
View File

@@ -65,7 +65,8 @@ testament.db
/tests/**/*.json
/tests/**/*.js
/csources
dist/
/dist/
/lib/fusion
# Private directories and files (IDEs)
.*/
@@ -82,5 +83,20 @@ megatest.nim
/outputExpected.txt
/outputGotten.txt
/t15148.txt
/tests/vm/tfile_rw.txt
/lib/pure/*.js
!/.builds/
!/.github
# ignore debug dirs generated by dsymutil on OSX
*.dSYM
# for `nim c -r nimdoc/tester` etc; this can be in multiple places
htmldocs
## these are not needed anymore unless checkout old older versions
nimdoc.out.css

View File

@@ -4,45 +4,12 @@ language: c
dist: xenial
matrix:
fast_finish: true
include:
- os: linux
env:
- NIM_COMPILE_TO_CPP=false
- CPU=amd64
- os: linux
env:
- NIM_COMPILE_TO_CPP=false
- CPU=i386
addons:
apt:
packages:
- gcc-multilib
- g++-multilib
- libcurl4-openssl-dev:i386
- libgc-dev:i386
- libglib2.0-dev:i386
- libpulse-dev:i386
- libsdl1.2-dev:i386
- libsfml-dev:i386
- os: osx
env:
- NIM_COMPILE_TO_CPP=false
- CPU=amd64
- os: osx
env:
- NIM_COMPILE_TO_CPP=true
- CPU=amd64
# To allow failures for a failing configuration, use something like:
# allow_failures:
# - env: NIM_COMPILE_TO_CPP=true
# - os: osx
addons:
apt:
# update the list above if more deps are introduced
@@ -53,21 +20,9 @@ addons:
- libsfml-dev
- libc6-dbg
- valgrind
homebrew:
packages:
- boehmgc
- make
- sfml
update: true
install:
- if [[ $CPU = i386 ]]; then echo -e "#!/bin/bash\n$(which gcc) -m32 \"\$@\"" > bin/gcc; fi
- if [[ $CPU = i386 ]]; then chmod 755 bin/gcc; fi
- if [[ $CPU = i386 ]]; then echo -e "#!/bin/bash\n$(which g++) -m32 \"\$@\"" > bin/g++; fi
- if [[ $CPU = i386 ]]; then chmod 755 bin/g++; fi
before_script:
- git clone --depth 1 https://github.com/nim-lang/csources.git
- git clone --depth 1 https://github.com/nim-lang/csources_v1.git csources
- export PATH="$PWD/bin${PATH:+:$PATH}"
- make -C csources -j 2 LD=$CC ucpu=$CPU
@@ -75,11 +30,17 @@ script:
- echo "travis_fold:start:nim_c_koch"
- nim c koch
- echo "travis_fold:end:nim_c_koch"
- ./koch runCI
- echo "travis_fold:start:koch_boot"
- ./koch boot
- echo "travis_fold:end:koch_boot"
- echo "travis_fold:start:koch_doc"
- ./koch doc
- echo "travis_fold:end:koch_doc"
before_deploy:
# Make https://nim-lang.github.io/Nim work the same as https://nim-lang.github.io/Nim/overview.html
- cp -f ./doc/html/overview.html ./doc/html/index.html
deploy: # https://nim-lang.github.io/Nim
provider: pages
# local-dir *has* to be a relative path from the repo root.
@@ -89,6 +50,3 @@ deploy: # https://nim-lang.github.io/Nim
keep-history: false
on:
branch: devel
# Extract failed tests
after_failure: nim c -r tools/ci_testresults.nim

View File

@@ -4,8 +4,8 @@ environment:
DLLS_URL: https://nim-lang.org/download/dlls.zip
DLLS_ARCHIVE: dlls.zip
MINGW_DIR: mingw64
MINGW_URL: https://nim-lang.org/download/mingw64-6.3.0.7z
MINGW_ARCHIVE: mingw64-6.3.0.7z
MINGW_URL: https://nim-lang.org/download/mingw64.7z
MINGW_ARCHIVE: mingw64.7z
matrix:
- NIM_TEST_PACKAGES: false
@@ -29,6 +29,8 @@ install:
- cd ..
build_script:
- openssl version
- openssl version -d
- bin\nim c koch
- koch runCI

View File

@@ -1,148 +1,180 @@
strategy:
matrix:
Linux_amd64:
vmImage: 'ubuntu-16.04'
CPU: amd64
Linux_i386:
vmImage: 'ubuntu-16.04'
CPU: i386
OSX_amd64:
vmImage: 'macOS-10.14'
CPU: amd64
OSX_amd64_cpp:
vmImage: 'macOS-10.14'
CPU: amd64
NIM_COMPILE_TO_CPP: true
Windows_amd64:
vmImage: 'windows-2019'
CPU: amd64
Windows_amd64_pkg:
vmImage: 'windows-2019'
CPU: amd64
NIM_TEST_PACKAGES: true
trigger:
branches:
include:
- '*'
pr:
branches:
include:
- '*'
pool:
vmImage: $(vmImage)
jobs:
- job: packages
workspace:
clean: all
timeoutInMinutes: 90 # default `60` led to lots of cancelled jobs; use 0 for unlimited (may be undesirable)
steps:
- bash: git config --global core.autocrlf false
displayName: 'Disable auto conversion to CRLF by git (Windows-only)'
condition: eq(variables['Agent.OS'], 'Windows_NT')
strategy:
matrix:
Linux_amd64:
vmImage: 'ubuntu-18.04'
CPU: amd64
Linux_i386:
vmImage: 'ubuntu-18.04'
CPU: i386
OSX_amd64:
vmImage: 'macOS-11'
CPU: amd64
OSX_amd64_cpp:
vmImage: 'macOS-11'
CPU: amd64
NIM_COMPILE_TO_CPP: true
Windows_amd64_batch0_3:
vmImage: 'windows-2019'
CPU: amd64
# see also: `NIM_TEST_PACKAGES`
NIM_TESTAMENT_BATCH: "0_3"
Windows_amd64_batch1_3:
vmImage: 'windows-2019'
CPU: amd64
NIM_TESTAMENT_BATCH: "1_3"
Windows_amd64_batch2_3:
vmImage: 'windows-2019'
CPU: amd64
NIM_TESTAMENT_BATCH: "2_3"
- checkout: self
pool:
vmImage: $(vmImage)
- bash: git clone --depth 1 https://github.com/nim-lang/csources.git
displayName: 'Checkout csources'
workspace:
clean: all
- task: NodeTool@0
inputs:
versionSpec: '8.x'
displayName: 'Install node.js 8.x'
steps:
- bash: git config --global core.autocrlf false
displayName: 'Disable auto conversion to CRLF by git (Windows-only)'
condition: eq(variables['Agent.OS'], 'Windows_NT')
- bash: |
sudo apt-fast update -qq
DEBIAN_FRONTEND='noninteractive' \
sudo apt-fast install --no-install-recommends -yq \
libcurl4-openssl-dev libgc-dev libsdl1.2-dev libsfml-dev valgrind libc6-dbg
displayName: 'Install dependencies (amd64 Linux)'
condition: and(eq(variables['Agent.OS'], 'Linux'), eq(variables['CPU'], 'amd64'))
- checkout: self
fetchDepth: 1
- bash: |
sudo dpkg --add-architecture i386
- bash: git clone --depth 1 https://github.com/nim-lang/csources_v1 csources
displayName: 'Checkout Nim csources'
# Downgrade llvm, libgcc and libstdc++:
# - llvm has to be downgraded to have 32bit version installed for sfml.
# - libgcc and libstdc++ have to be downgraded as an optimization to
# prevent the use of the toolchain ppa, which has a terrible download
# speed.
cat << EOF | sudo tee /etc/apt/preferences.d/pin-to-rel
Package: libllvm6.0 libgcc1 libstdc++6
Pin: origin "azure.archive.ubuntu.com"
Pin-Priority: 1001
- task: NodeTool@0
inputs:
versionSpec: '12.x'
displayName: 'Install node.js 12.x'
Package: *
Pin: release o=LP-PPA-ubuntu-toolchain-r-test
Pin-Priority: 100
EOF
- bash: |
sudo apt-fast update -qq
DEBIAN_FRONTEND='noninteractive' \
sudo apt-fast install --no-install-recommends -yq \
libcurl4-openssl-dev libgc-dev libsdl1.2-dev libsfml-dev valgrind libc6-dbg
displayName: 'Install dependencies (amd64 Linux)'
condition: and(eq(variables['Agent.OS'], 'Linux'), eq(variables['CPU'], 'amd64'))
sudo apt-fast update -qq
DEBIAN_FRONTEND='noninteractive' \
sudo apt-fast install --no-install-recommends --allow-downgrades -yq \
g++-multilib gcc-multilib libcurl4-openssl-dev:i386 libgc-dev:i386 \
libsdl1.2-dev:i386 libsfml-dev:i386 libglib2.0-dev:i386
- bash: |
sudo dpkg --add-architecture i386
cat << EOF > bin/gcc
#!/bin/bash
# Downgrade llvm:
# - llvm has to be downgraded to have 32bit version installed for sfml.
cat << EOF | sudo tee /etc/apt/preferences.d/pin-to-rel
Package: libllvm6.0
Pin: origin "azure.archive.ubuntu.com"
Pin-Priority: 1001
EOF
exec $(which gcc) -m32 "\$@"
EOF
cat << EOF > bin/g++
#!/bin/bash
sudo apt-fast update -qq
# `:i386` (e.g. in `libffi-dev:i386`) is needed otherwise you may get:
# `could not load: libffi.so` during dynamic loading.
DEBIAN_FRONTEND='noninteractive' \
sudo apt-fast install --no-install-recommends --allow-downgrades -yq \
g++-multilib gcc-multilib libcurl4-openssl-dev:i386 libgc-dev:i386 \
libsdl1.2-dev:i386 libsfml-dev:i386 libglib2.0-dev:i386 libffi-dev:i386
exec $(which g++) -m32 "\$@"
EOF
cat << EOF > bin/gcc
#!/bin/bash
chmod 755 bin/gcc
chmod 755 bin/g++
exec $(which gcc) -m32 "\$@"
EOF
cat << EOF > bin/g++
#!/bin/bash
displayName: 'Install dependencies (i386 Linux)'
condition: and(eq(variables['Agent.OS'], 'Linux'), eq(variables['CPU'], 'i386'))
exec $(which g++) -m32 "\$@"
EOF
- bash: brew install boehmgc make sfml
displayName: 'Install dependencies (OSX)'
condition: eq(variables['Agent.OS'], 'Darwin')
chmod 755 bin/gcc
chmod 755 bin/g++
- bash: |
mkdir dist
curl -L https://nim-lang.org/download/mingw64-6.3.0.7z -o dist/mingw64.7z
curl -L https://nim-lang.org/download/dlls.zip -o dist/dlls.zip
7z x dist/mingw64.7z -odist
7z x dist/dlls.zip -obin
echo '##vso[task.prependpath]$(System.DefaultWorkingDirectory)/dist/mingw64/bin'
displayName: 'Install dependencies (i386 Linux)'
condition: and(eq(variables['Agent.OS'], 'Linux'), eq(variables['CPU'], 'i386'))
displayName: 'Install dependencies (Windows)'
condition: eq(variables['Agent.OS'], 'Windows_NT')
- bash: brew install boehmgc make sfml
displayName: 'Install dependencies (OSX)'
condition: eq(variables['Agent.OS'], 'Darwin')
- bash: echo '##vso[task.prependpath]$(System.DefaultWorkingDirectory)/bin'
displayName: 'Add build binaries to PATH'
- bash: |
mkdir dist
curl -L https://nim-lang.org/download/mingw64.7z -o dist/mingw64.7z
curl -L https://nim-lang.org/download/dlls.zip -o dist/dlls.zip
7z x dist/mingw64.7z -odist
7z x dist/dlls.zip -obin
echo '##vso[task.prependpath]$(System.DefaultWorkingDirectory)/dist/mingw64/bin'
- bash: |
echo 'PATH:' "$PATH"
echo '##[section]gcc version'
gcc -v
echo '##[section]nodejs version'
node -v
echo '##[section]make version'
make -v
displayName: 'System information'
displayName: 'Install dependencies (Windows)'
condition: eq(variables['Agent.OS'], 'Windows_NT')
- bash: |
ncpu=
case '$(Agent.OS)' in
'Linux')
ncpu=$(nproc)
;;
'Darwin')
ncpu=$(sysctl -n hw.ncpu)
;;
'Windows_NT')
ncpu=$NUMBER_OF_PROCESSORS
;;
esac
[[ -z "$ncpu" || $ncpu -le 0 ]] && ncpu=1
- bash: echo '##vso[task.prependpath]$(System.DefaultWorkingDirectory)/bin'
displayName: 'Add build binaries to PATH'
make -C csources -j $ncpu CC=gcc ucpu=$(CPU)
displayName: 'Build csources'
- bash: |
echo 'PATH:' "$PATH"
echo '##[section]gcc version'
gcc -v
echo '##[section]nodejs version'
node -v
echo '##[section]make version'
make -v
displayName: 'System information'
- bash: nim c koch
displayName: 'Build koch'
- bash: echo '##vso[task.setvariable variable=csources_version]'"$(git -C csources rev-parse HEAD)"
displayName: 'Get csources version'
# set result to omit the "bash exited with error code '1'" message
- bash: |
./koch runCI || echo '##vso[task.complete result=Failed]'
displayName: 'Run CI'
env:
SYSTEM_ACCESSTOKEN: $(System.AccessToken)
- task: Cache@2
inputs:
key: 'csources | "$(Agent.OS)" | $(CPU) | $(csources_version)'
path: csources/bin
displayName: 'Restore built csources'
- bash: |
ncpu=
ext=
case '$(Agent.OS)' in
'Linux')
ncpu=$(nproc)
;;
'Darwin')
ncpu=$(sysctl -n hw.ncpu)
;;
'Windows_NT')
ncpu=$NUMBER_OF_PROCESSORS
ext=.exe
;;
esac
[[ -z "$ncpu" || $ncpu -le 0 ]] && ncpu=1
if [[ -x csources/bin/nim$ext ]]; then
echo "Found cached compiler, skipping build"
else
make -C csources -j $ncpu CC=gcc ucpu=$(CPU) koch=no
fi
cp csources/bin/nim$ext bin
displayName: 'Build 1-stage compiler from csources'
- bash: nim c koch
displayName: 'Build koch'
# set result to omit the "bash exited with error code '1'" message
- bash: ./koch runCI || echo '##vso[task.complete result=Failed]'
displayName: 'Run CI'
env:
SYSTEM_ACCESSTOKEN: $(System.AccessToken)

View File

@@ -5,9 +5,15 @@ set -e
which nim > /dev/null || (echo "nim not in PATH"; exit 1)
which gdb > /dev/null || (echo "gdb not in PATH"; exit 1)
which readlink > /dev/null || (echo "readlink not in PATH."; exit 1)
if [[ "$(uname -s)" == "Darwin" || "(uname -s)" == *"BSD" ]]; then
NIM_SYSROOT=$(dirname $(dirname $(readlink -f $(which nim))))
else
NIM_SYSROOT=$(dirname $(dirname $(readlink -e $(which nim))))
fi
# Find out where the pretty printer Python module is
NIM_SYSROOT=$(dirname $(dirname $(readlink -e $(which nim))))
GDB_PYTHON_MODULE_PATH="$NIM_SYSROOT/tools/nim-gdb.py"
# Run GDB with the additional arguments that load the pretty printers
@@ -16,6 +22,4 @@ GDB_PYTHON_MODULE_PATH="$NIM_SYSROOT/tools/nim-gdb.py"
NIM_GDB="${NIM_GDB:-gdb}"
# exec replaces the new process of bash with gdb. It is always good to
# have fewer processes.
exec ${NIM_GDB} \
-eval-command "source $GDB_PYTHON_MODULE_PATH" \
"$@"
exec "${NIM_GDB}" -eval-command="source $GDB_PYTHON_MODULE_PATH" "$@"

1
bin/nim-gdb.bash Symbolic link
View File

@@ -0,0 +1 @@
nim-gdb

14
bin/nim-gdb.bat Normal file
View File

@@ -0,0 +1,14 @@
@echo off
for %%i in (nim.exe) do (set NIM_BIN=%%~dp$PATH:i)
for %%i in ("%NIM_BIN%\..\") do (set NIM_ROOT=%%~fi)
set @GDB_PYTHON_MODULE_PATH=%NIM_ROOT%\tools\nim-gdb.py
set @NIM_GDB=gdb.exe
@echo source %@GDB_PYTHON_MODULE_PATH%> wingdbcommand.txt
%@NIM_GDB% --command="wingdbcommand.txt" %*
del wingdbcommand.txt /f /q
EXIT /B %ERRORLEVEL%
@echo on

View File

@@ -1,7 +1,7 @@
@echo off
rem build development version of the compiler; can be rerun safely
if not exist csources (
git clone --depth 1 https://github.com/nim-lang/csources.git
git clone --depth 1 https://github.com/nim-lang/csources_v1.git csources
)
if not exist bin\nim.exe (
cd csources
@@ -12,5 +12,6 @@ if not exist bin\nim.exe (
cd ..
)
bin\nim.exe c --skipUserCfg --skipParentCfg koch
koch.exe boot -d:release
koch.exe tools
koch.exe boot -d:release --skipUserCfg --skipParentCfg
koch.exe tools --skipUserCfg --skipParentCfg

35
build_all.sh Normal file → Executable file
View File

@@ -1,23 +1,41 @@
#! /bin/sh
# build development version of the compiler; can be rerun safely
# build development version of the compiler; can be rerun safely.
# arguments can be passed, e.g. `--os freebsd`
set -u # error on undefined variables
set -e # exit on first error
echo_run(){
printf "\n$*\n"
echo "$*"
"$@"
}
[ -d csources ] || echo_run git clone --depth 1 https://github.com/nim-lang/csources.git
[ -d csources ] || echo_run git clone -q --depth 1 https://github.com/nim-lang/csources_v1.git csources
nim_csources=bin/nim_csources
build_nim_csources_via_script(){
echo_run cd csources
echo_run sh build.sh "$@"
}
build_nim_csources(){
## avoid changing dir in case of failure
# avoid changing dir in case of failure
(
echo_run cd csources
echo_run sh build.sh $@
if [ $# -ne 0 ]; then
# some args were passed (e.g.: `--cpu i386`), need to call build.sh
build_nim_csources_via_script "$@"
else
# no args, use multiple Make jobs (5X faster on 16 cores: 10s instead of 50s)
makeX=make
unamestr=$(uname)
if [ "$unamestr" = 'FreeBSD' ]; then
makeX=gmake
fi
nCPU=$(nproc 2>/dev/null || sysctl -n hw.logicalcpu 2>/dev/null || getconf _NPROCESSORS_ONLN 2>/dev/null || 1)
which $makeX && echo_run $makeX -C csources -j $((nCPU + 2)) -l $nCPU || build_nim_csources_via_script
fi
)
# keep $nim_csources in case needed to investigate bootstrap issues
# without having to rebuild from csources
@@ -29,5 +47,6 @@ build_nim_csources(){
# Note: if fails, may need to `cd csources && git pull`
echo_run bin/nim c --skipUserCfg --skipParentCfg koch
echo_run ./koch boot -d:release
echo_run ./koch tools # Compile Nimble and other tools.
echo_run ./koch boot -d:release --skipUserCfg --skipParentCfg
echo_run ./koch tools --skipUserCfg --skipParentCfg # Compile Nimble and other tools.

View File

@@ -1,41 +1,83 @@
# v1.1 - xxxx-xx-xx
## Changes affecting backwards compatibility
# v1.6.x - yyyy-mm-dd
### Breaking changes in the standard library
## Changes affecting backward compatibility
- The configuration subsystem now allows for `-d:release` and `-d:danger` to work as expected.
The downside is that these defines now have custom logic that doesn't apply for
other defines.
## Standard library additions and changes
- Added support for parenthesized expressions in `strformat`
### Breaking changes in the compiler
- Fixed buffer overflow bugs in `net`
- Added `sections` iterator in `parsecfg`.
- Make custom op in macros.quote work for all statements.
- On Windows the SSL library now checks for valid certificates.
It uses the `cacert.pem` file for this purpose which was extracted
from `https://curl.se/ca/cacert.pem`. Besides
the OpenSSL DLLs (e.g. libssl-1_1-x64.dll, libcrypto-1_1-x64.dll) you
now also need to ship `cacert.pem` with your `.exe` file.
- Make `{.requiresInit.}` pragma to work for `distinct` types.
## Library additions
- Added a macros `enumLen` for returning the number of items in an enum to the
`typetraits.nim` module.
- `prelude` now works with the JavaScript target.
- Added `ioutils` module containing `duplicate` and `duplicateTo` to duplicate `FileHandle` using C function `dup` and `dup2`.
## Library changes
- The JSON module can now handle integer literals and floating point literals of arbitrary length and precision.
Numbers that do not fit the underlying `BiggestInt` or `BiggestFloat` fields are kept as string literals and
one can use external BigNum libraries to handle these. The `parseFloat` family of functions also has now optional
`rawIntegers` and `rawFloats` parameters that can be used to enforce that all integer or float literals remain
in the "raw" string form so that client code can easily treat small and large numbers uniformly.
- Added `randState` template that exposes the default random number generator. Useful for library authors.
- Added `asyncdispatch.activeDescriptors` that returns the number of currently
active async event handles/file descriptors
## Language additions
- Fixed premature garbage collection in asyncdispatch, when a stack trace override is in place.
## Language changes
- `nimscript` now handles `except Exception as e`
### Tool changes
- The `cstring` doesn't support `[]=` operator in JS backend.
### Compiler changes
## Compiler changes
- Added `unsafeIsolate` and `extract` to `std/isolation`.
- `--hint:CC` now goes to stderr (like all other hints) instead of stdout.
- json build instructions are now generated in `$nimcache/outFileBasename.json`
instead of `$nimcache/projectName.json`. This allows avoiding recompiling a given project
compiled with different options if the output file differs.
- `--usenimcache` (implied by `nim r main`) now generates an output file that includes a hash of
some of the compilation options, which allows caching generated binaries:
nim r main # recompiles
nim r -d:foo main # recompiles
nim r main # uses cached binary
nim r main arg1 arg2 # ditto (runtime arguments are irrelevant)
- The style checking of the compiler now supports a `--styleCheck:usages` switch. This switch
enforces that every symbol is written as it was declared, not enforcing
the official Nim style guide. To be enabled, this has to be combined either
with `--styleCheck:error` or `--styleCheck:hint`.
## Tool changes
## Bugfixes

View File

@@ -43,7 +43,7 @@
* threadpool: fix link in docs (#12258)
* Fix spellings (#12277)
* fix #12278, don't expose internal PCRE documentation
* Fixed "Documentation of quitprocs is wrong" [#12279](https://github.com/nim-lang/Nim/issues/12279)
* Fixed "Documentation of quitprocs is wrong" [#12279(https://github.com/nim-lang/Nim/issues/12279)
* Fix typo in docs
* Fix reference to parseSpec proc in readme
* [doc/tut1] removed discard discussion in comments

View File

@@ -1,75 +0,0 @@
# v1.0.4 - 2019-11-26
## Language changes
- Conversions to unsigned integers are unchecked at runtime, imitating earlier Nim
versions. The documentation was improved to acknowledge this special case.
See https://github.com/nim-lang/RFCs/issues/175 for more details. (#12688)
- Add `or detectOs(Manjaro)` (#12587)
- --os:ios needs to imply defined(macosx) (#12585)
- export nim.cfg parser (#12602)
## Bugfixes
- Fixed "gorge(Ex) fails after a few calls on OSX"
([#12337](https://github.com/nim-lang/Nim/issues/12337))
- Fixed "Improve posix module"
([#10723](https://github.com/nim-lang/Nim/issues/10723))
- Fixed "nim check allows gorgeEx but doesn't allow writeFile"
([#12491](https://github.com/nim-lang/Nim/issues/12491))
- Fixed "Low level arithmetics bug: -3 mod 7 == 3"
([#12514](https://github.com/nim-lang/Nim/issues/12514))
- Fixed "Broken link to c2nim in backends.rst/.html"
([#12537](https://github.com/nim-lang/Nim/issues/12537))
- Fixed "generic argument with default value causes incorrect generic type resolution"
([#12528](https://github.com/nim-lang/Nim/issues/12528))
- Fixed "regression: compiler/vmgen.nim(354, 20) `false` leaking temporary 10 slotTempInt [AssertionError]
([#12547](https://github.com/nim-lang/Nim/issues/12547))
- Fixed "Compile/link broken for nim (64-bit only) on Windows"
([#12536](https://github.com/nim-lang/Nim/issues/12536))
- Fixed "No `=destroy` for elements of closure environments other than for latest devel --gc:destructors"
([#12577](https://github.com/nim-lang/Nim/issues/12577))
- Fixed "[1.0.0] Cannot compile anything with --cpu:avr"
([#12395](https://github.com/nim-lang/Nim/issues/12395))
- Fixed "Compiler crash with invalid object variant"
([#12379](https://github.com/nim-lang/Nim/issues/12379))
- Fixed "push pragma is silently ignored if position is in front of import statement"
([#5050](https://github.com/nim-lang/Nim/issues/5050))
- Fixed "Error with strformat + asyncdispatch + const"
([#12612](https://github.com/nim-lang/Nim/issues/12612))
- Fixed "The --nimblePath is additive; need a pain-free workaround"
([#12601](https://github.com/nim-lang/Nim/issues/12601))
- Fixed "nim.cfg syntax for --define:FOO:VAL undocumented or absent"
([#12367](https://github.com/nim-lang/Nim/issues/12367))
- Fixed "vm string literals do not work when generated by a macro"
([#12670](https://github.com/nim-lang/Nim/issues/12670))
- Fixed "StaticRead does force a recompile if static file changes."
([#12663](https://github.com/nim-lang/Nim/issues/12663))
- Fixed crash in terminate handler
([#12572](https://github.com/nim-lang/Nim/pull/12572))
- Fixed newLit for objects having string fields
([#12542](https://github.com/nim-lang/Nim/pull/12542))
## Documentation improvements
- Documentation Math module (#12460)
- Fix many broken links and prefer relative links within docs (#12463)
- sequtils: replace deprecated 'random' call within example (#12515)
- integer literal documentation (#12513)
- Fix code style errors (#12545)
- fix several typos in documentation and comments (#12553)
- Add docs to better distinguish among getProjectPath, getCurrentDir and currentSourcePath (#12565)
- doc/tut3.rst: Fix typo in Introduction (#12607)
- Add links to packaging and distro pages (#12603)
- fix documentation of `$`\*(dt: DateTime) (#12660)
- Clarifies experimental / parallel example on manual.rst (#12472)
- Fix wrong section hierarchy in the manual (#12724)

View File

@@ -1,68 +0,0 @@
# v1.0.6 - 2020-01-24
## Bugfixes
### Fixed issues
- Fixed "Nim stdlib style issues with --styleCheck:error"
([#12687](https://github.com/nim-lang/Nim/issues/12687))
- Fixed "new(ref MyObject) doesn't work at compile time"
([#12488](https://github.com/nim-lang/Nim/issues/12488))
- Fixed "Accessing the wrong variant field in the VM does not trigger the appropriate error message"
([#11727](https://github.com/nim-lang/Nim/issues/11727))
- Fixed "orderedTable.del() crashes with unitialized table"
([#12798](https://github.com/nim-lang/Nim/issues/12798))
- Fixed "semfold bug with negative value * 0"
([#12783](https://github.com/nim-lang/Nim/issues/12783))
- Fixed "nimsuggest `use` command does not return all instances of symbol"
([#12832](https://github.com/nim-lang/Nim/issues/12832))
- Fixed "Codegen ICE in allPathsAsgnResult"
([#12827](https://github.com/nim-lang/Nim/issues/12827))
- Fixed "Static[T] + syntactic error in the for loop = compiler crash"
([#12148](https://github.com/nim-lang/Nim/issues/12148))
- Fixed "Incorrect unused import warning involving templates and tables"
([#12885](https://github.com/nim-lang/Nim/issues/12885))
- Fixed "regression(1.0.4): undeclared identifier: 'readLines'; plus another regression and bug"
([#13013](https://github.com/nim-lang/Nim/issues/13013))
- Fixed "`nim doc` treats `export localSymbol` incorrectly"
([#13100](https://github.com/nim-lang/Nim/issues/13100))
- Fixed "symbols not defined in the grammar"
([#10665](https://github.com/nim-lang/Nim/issues/10665))
- Fixed "nim-gdb is missing from all released packages"
([#13104](https://github.com/nim-lang/Nim/issues/13104))
- Fixed "[JS] Move is not defined"
([#9674](https://github.com/nim-lang/Nim/issues/9674))
- Fixed "Error: usage of 'isNil' is a user-defined error"
([#11440](https://github.com/nim-lang/Nim/issues/11440))
### Other bugfixes
- make addQuoted work on nimscript (#12717)
- fix db_mysql getRow() when column is null error raised (#12806)
- Fixed objects being erroneously zeroed out before object construction (#12814)
- added cstrutils (#12858): fixed for 'csuCmpIgnoreStyle' error on hotcodereloading
- Better clang_cl support (#12896)
- fix cmdline bugs affecting nimBetterRun correctness (#12933)
- fixes a bug that kept sugar.collect from working with for loop macros
- Path substitution for --out and --outdir (#12796)
- fix crash due to errant symbols in nim.cfg (#13073)
- Allow `-o` option for `buildIndex` (#13037)
- Deleted misplaced separator (#13085): Misplaced separator, which was constantly breaking compilation on Haiku OS, was deleted.
- fixes an asyncftpclient bug; refs #13096
- fix the ftp store function read the local file bug (#13108)
- fix rtti sizeof for varargs in global scope (#13125)
- Correctly remove a key from CountTable when it is set to zero.
- fixes the distros.nim regression
- fixes a critical times.nim bug reported on IRC
- c_fflush() the rawWrite() buffer
## Documentation improvements
- Fixed "Documentation, Testament missing from "Tools available with Nim""
([#12251](https://github.com/nim-lang/Nim/issues/12251))
- Manual update: custom exceptions (#12847)
- times/getClockStr(): fix mistake in doc
- Fix typo and improve in code-block of 'lib/pure/parseutils.nim'

View File

@@ -0,0 +1,535 @@
# v1.2.0 - 2020-04-02
## Standard library additions and changes
- Added overloaded `strformat.fmt` macro that use specified characters as
delimiter instead of '{' and '}'.
- Added new procs in `tables.nim`: `OrderedTable.pop`, `CountTable.del`,
`CountTable.pop`, `Table.pop`.
- Added `strtabs.clear` overload that reuses the existing mode.
- Added `browsers.osOpen` const alias for the operating system specific *"open"* command.
- Added `sugar.dup` for turning in-place algorithms like `sort` and `shuffle`
into operations that work on a copy of the data and return the mutated copy,
like the existing `sorted` does.
- Added `sugar.collect` that does comprehension for seq/set/table collections.
- Added `sugar.capture` for capturing some local loop variables when creating a
closure. This is an enhanced version of `closureScope`.
- Added `typetraits.tupleLen` to get number of elements of a tuple/type tuple,
and `typetraits.get` to get the ith element of a type tuple.
- Added `typetraits.genericParams` to return a tuple of generic params from a
generic instantiation.
- `options` now treats `proc` like other pointer types, meaning `nil` proc variables
are converted to `None`.
- Added `os.normalizePathEnd` for additional path sanitization.
- Added `times.fromUnixFloat,toUnixFloat`, sub-second resolution versions of
`fromUnix`,`toUnixFloat`.
- Added `wrapnils` module for chains of field-access and indexing where the LHS
can be nil. This simplifies code by reducing need for if-else branches around
intermediate maybe nil values. E.g. `echo ?.n.typ.kind`.
- Added `minIndex`, `maxIndex` and `unzip` to the `sequtils` module.
- Added `os.isRelativeTo` to tell whether a path is relative to another.
- Added `resetOutputFormatters` to `unittest`.
- Added `expectIdent` to the `macros` module.
- Added `os.isValidFilename` that returns `true` if `filename` argument is valid
for cross-platform use.
- Added `times.isLeapDay`.
- `base64` adds URL-Safe Base64, implements RFC-4648 Section-7.
- Added a new module, `std / compilesettings` for querying the compiler about
diverse configuration settings.
- Added `net.getPeerCertificates` and `asyncnet.getPeerCertificates` for
retrieving the verified certificate chain of the peer we are connected to
through an SSL-wrapped `Socket`/`AsyncSocket`.
- Added `browsers.openDefaultBrowser` without URL, implements IETF RFC-6694 Section-3.
- Added `jsconsole.trace`, `jsconsole.table`, `jsconsole.exception` for JavaScript target.
- Added `distinctBase` overload for values: `assert 12.MyInt.distinctBase == 12`
- Added new module `std/stackframes`, in particular `setFrameMsg`, which enables
custom runtime annotation of stackframes, see #13351 for examples.
Turn on/off via `--stackTraceMsgs:on/off`.
- Added `sequtils.countIt`, allowing for counting items using a predicate.
- Added a `with` macro for easy function chaining that's available everywhere,
there is no need to concern your APIs with returning the first argument
to enable "chaining", instead use the dedicated macro `with` that
was designed for it. For example:
```nim
import std/with
type
Foo = object
col, pos: string
proc setColor(f: var Foo; r, g, b: int) = f.col = $(r, g, b)
proc setPosition(f: var Foo; x, y: float) = f.pos = $(x, y)
var f: Foo
with(f, setColor(2, 3, 4), setPosition(0.0, 1.0))
echo f
```
- `macros.newLit` now works for ref object types.
- `macro pragmas` can now be used in type sections.
- 5 new pragmas were added to Nim in order to make the upcoming tooling more
convenient to use. Nim compiler checks these pragmas for syntax but otherwise
ignores them. The pragmas are `requires`, `ensures`, `assume`, `assert`, `invariant`.
- `system.writeFile` has been overloaded to also support `openarray[byte]`.
- `asyncdispatch.drain` now properly takes into account `selector.hasPendingOperations`
and only returns once all pending async operations are guaranteed to have completed.
- `sequtils.zip` now returns a sequence of anonymous tuples i.e. those tuples
now do not have fields named "a" and "b".
- `distinctBase` has been moved from `sugar` to `typetraits` and now it is
implemented as compiler type trait instead of macro. `distinctBase` in sugar
module is now deprecated.
- `CountTable.mget` has been removed from `tables.nim`. It didn't work, and it
was an oversight to be included in v1.0.
- `tables.merge(CountTable, CountTable): CountTable` has been removed.
It didn't work well together with the existing inplace version of the same proc
(`tables.merge(var CountTable, CountTable)`).
It was an oversight to be included in v1.0.
- `asyncdispatch.drain` now consistently uses the passed timeout value for all
iterations of the event loop, and not just the first iteration.
This is more consistent with the other asyncdispatch APIs, and allows
`asyncdispatch.drain` to be more efficient.
- `base64.encode` and `base64.decode` were made faster by about 50%.
- `htmlgen` adds [MathML](https://wikipedia.org/wiki/MathML) support
(ISO 40314).
- `macros.eqIdent` is now invariant to export markers and backtick quotes.
- `htmlgen.html` allows `lang` in the `<html>` tag and common valid attributes.
- `macros.basename` and `basename=` got support for `PragmaExpr`,
so that an expression like `MyEnum {.pure.}` is handled correctly.
- `httpclient.maxredirects` changed from `int` to `Natural`, because negative values
serve no purpose whatsoever.
- `httpclient.newHttpClient` and `httpclient.newAsyncHttpClient` added `headers`
argument to set initial HTTP Headers, instead of a hardcoded empty `newHttpHeader()`.
- `parseutils.parseUntil` has now a different behaviour if the `until` parameter is
empty. This was required for intuitive behaviour of the strscans module
(see bug #13605).
- `strutils.formatFloat` with `precision = 0` has the same behavior in all
backends, and it is compatible with Python's behavior,
e.g. `formatFloat(3.14159, precision = 0)` is now `3`, not `3.`.
- `times.parse` now only uses input to compute its result, and not `now`:
`parse("2020", "YYYY", utc())` is now `2020-01-01T00:00:00Z` instead of
`2020-03-02T00:00:00Z` if run on 03-02; it also doesn't crash anymore when
used on 29th, 30th, 31st of each month.
- `httpcore.==(string, HttpCode)` is now deprecated due to lack of practical
usage. The `$` operator can be used to obtain the string form of `HttpCode`
for comparison if desired.
- `std/oswalkdir` was buggy, it's now deprecated and reuses `std/os` procs.
- `os.walkDir` and `os.walkDirRec` now have new flag, `checkDir` (default: false).
If it is set to true, it will throw if input dir is invalid instead of a noop
(which is the default behaviour, as it was before this change),
`os.walkDirRec` only throws if top-level dir is invalid, but ignores errors for
subdirs, otherwise it would be impossible to resume iteration.
- The `FD` variant of `selector.unregister` for `ioselector_epoll` and
`ioselector_select` now properly handle the `Event.User` select event type.
- `joinPath` path normalization when `/` is the first argument works correctly:
`assert "/" / "/a" == "/a"`. Fixed the edge case: `assert "" / "" == ""`.
- `xmltree` now adds indentation consistently to child nodes for any number
of children nodes.
- `os.splitPath()` behavior synchronized with `os.splitFile()` to return "/"
as the dir component of `/root_sub_dir` instead of the empty string.
- The deprecated `lc` macro has been removed from `sugar`. It is now replaced
with the more powerful `collect` macro.
- `os.relativePath("foo", "foo")` is now `"."`, not `""`, as `""` means invalid
path and shouldn't be conflated with `"."`; use `-d:nimOldRelativePathBehavior`
to restore the old behavior.
- `os.joinPath(a, b)` now honors trailing slashes in `b` (or `a` if `b` = "").
- `base64.encode` no longer supports `lineLen` and `newLine`.
Use `base64.encodeMime` instead.
### Breaking changes
- `net.newContext` now performs SSL Certificate checking on Linux and OSX.
Define `nimDisableCertificateValidation` to disable it globally.
## Language changes
- An `align` pragma can now be used for variables and object fields, similar
to the `alignas` declaration modifier in C/C++.
- The `=sink` type bound operator is now optional. The compiler can now use a
combination of `=destroy` and `copyMem` to move objects efficiently.
- Unsigned integer operators have been fixed to allow promotion of the first operand.
- Conversions to unsigned integers are unchecked at runtime, imitating earlier Nim
versions. The documentation was improved to acknowledge this special case.
See https://github.com/nim-lang/RFCs/issues/175 for more details.
- There is a new syntax for lvalue references: `var b {.byaddr.} = expr` enabled by
`import std/decls`.
- `var a {.foo.}: MyType = expr` now lowers to `foo(a, MyType, expr)` for
non-builtin pragmas, enabling things like lvalue references (see `decls.byaddr`).
## Compiler changes
- The generated JS code uses spaces, instead of mixing spaces and tabs.
- The Nim compiler now supports the ``--asm`` command option for easier
inspection of the produced assembler code.
- The Nim compiler now supports a new pragma called ``.localPassc`` to
pass specific compiler options to the C(++) backend for the C(++) file
that was produced from the current Nim module.
- The compiler now inferes "sink parameters". To disable this for a specific routine,
annotate it with `.nosinks`. To disable it for a section of code, use
`{.push sinkInference: off.}`...`{.pop.}`.
- The compiler now supports a new switch `--panics:on` that turns runtime
errors like `IndexError` or `OverflowError` into fatal errors that **cannot**
be caught via Nim's `try` statement. `--panics:on` can improve the
runtime efficiency and code size of your program significantly.
- The compiler now warns about inheriting directly from `system.Exception` as
this is **very bad** style. You should inherit from `ValueError`, `IOError`,
`OSError` or from a different specific exception type that inherits from
`CatchableError` and cannot be confused with a `Defect`.
- The error reporting for Nim's effect system has been improved.
- Implicit conversions for `const` behave correctly now, meaning that code like
`const SOMECONST = 0.int; procThatTakesInt32(SOMECONST)` will be illegal now.
Simply write `const SOMECONST = 0` instead.
- The `{.dynlib.}` pragma is now required for exporting symbols when making
shared objects on POSIX and macOS, which make it consistent with the behavior
on Windows.
- The compiler is now more strict about type conversions concerning proc
types: Type conversions cannot be used to hide `.raise` effects or side
effects, instead a `cast` must be used. With the flag `--useVersion:1.0` the
old behaviour is emulated.
- The Nim compiler now implements a faster way to detect overflows based
on GCC's `__builtin_sadd_overflow` family of functions. (Clang also
supports these). Some versions of GCC lack this feature and unfortunately
we cannot detect this case reliably. So if you get compilation errors like
"undefined reference to `__builtin_saddll_overflow`" compile your programs
with `-d:nimEmulateOverflowChecks`.
## Bugfixes
- Fixed "`nimgrep --nocolor` is ignored on posix; should be instead: `--nimgrep --color=[auto]|true|false`"
([#7591](https://github.com/nim-lang/Nim/issues/7591))
- Fixed "Runtime index on const array (of converted obj) causes C-compiler error"
([#10514](https://github.com/nim-lang/Nim/issues/10514))
- Fixed "windows x86 with vcc compile error with "asmNoStackFrame""
([#12298](https://github.com/nim-lang/Nim/issues/12298))
- Fixed "[TODO] regression: Error: Locks requires --threads:on option"
([#12330](https://github.com/nim-lang/Nim/issues/12330))
- Fixed "Add --cc option to --help or --fullhelp output"
([#12010](https://github.com/nim-lang/Nim/issues/12010))
- Fixed "questionable `csize` definition in `system.nim`"
([#12187](https://github.com/nim-lang/Nim/issues/12187))
- Fixed "os.getAppFilename() returns incorrect results on OpenBSD"
([#12389](https://github.com/nim-lang/Nim/issues/12389))
- Fixed "HashSet[uint64] slow insertion depending on values"
([#11764](https://github.com/nim-lang/Nim/issues/11764))
- Fixed "Differences between compiling 'classic call syntax' vs 'method call syntax' ."
([#12453](https://github.com/nim-lang/Nim/issues/12453))
- Fixed "c -d:nodejs --> SIGSEGV: Illegal storage access"
([#12502](https://github.com/nim-lang/Nim/issues/12502))
- Fixed "Closure iterator crashes on --newruntime due to "dangling references""
([#12443](https://github.com/nim-lang/Nim/issues/12443))
- Fixed "No `=destroy` for elements of closure environments other than for latest devel --gc:destructors"
([#12577](https://github.com/nim-lang/Nim/issues/12577))
- Fixed "strutils:formatBiggestFloat() gives different results in JS mode"
([#8242](https://github.com/nim-lang/Nim/issues/8242))
- Fixed "Regression (devel): the new `csize_t` definition isn't consistently used, nor tested thoroughly..."
([#12597](https://github.com/nim-lang/Nim/issues/12597))
- Fixed "tables.take() is defined only for `Table` and missed for other table containers"
([#12519](https://github.com/nim-lang/Nim/issues/12519))
- Fixed "`pthread_key_t` errors on OpenBSD"
([#12135](https://github.com/nim-lang/Nim/issues/12135))
- Fixed "newruntime: simple seq pop at ct results in compile error"
([#12644](https://github.com/nim-lang/Nim/issues/12644))
- Fixed "[Windows] finish.exe C:\Users\<USERNAME>\.nimble\bin is not in your PATH environment variable."
([#12319](https://github.com/nim-lang/Nim/issues/12319))
- Fixed "Error with strformat + asyncdispatch + const"
([#12612](https://github.com/nim-lang/Nim/issues/12612))
- Fixed "MultipartData needs $"
([#11863](https://github.com/nim-lang/Nim/issues/11863))
- Fixed "Nim stdlib style issues with --styleCheck:error"
([#12687](https://github.com/nim-lang/Nim/issues/12687))
- Fixed "new $nimbleDir path substitution yields unexpected search paths"
([#12767](https://github.com/nim-lang/Nim/issues/12767))
- Fixed "Regression: inlined procs now get multiple rounds of destructor injection"
([#12766](https://github.com/nim-lang/Nim/issues/12766))
- Fixed "newruntime: compiler generates defective code"
([#12669](https://github.com/nim-lang/Nim/issues/12669))
- Fixed "broken windows modules path handling because of 'os.relativePath' breaking changes"
([#12734](https://github.com/nim-lang/Nim/issues/12734))
- Fixed "for loop tuple syntax not rendered correctly"
([#12740](https://github.com/nim-lang/Nim/issues/12740))
- Fixed "Crash when trying to use `type.name[0]`"
([#12804](https://github.com/nim-lang/Nim/issues/12804))
- Fixed "Enums should be considered Trivial types in Atomics"
([#12812](https://github.com/nim-lang/Nim/issues/12812))
- Fixed "Produce static/const initializations for variables when possible"
([#12216](https://github.com/nim-lang/Nim/issues/12216))
- Fixed "Assigning descriminator field leads to internal assert with --gc:destructors"
([#12821](https://github.com/nim-lang/Nim/issues/12821))
- Fixed "nimsuggest `use` command does not return all instances of symbol"
([#12832](https://github.com/nim-lang/Nim/issues/12832))
- Fixed "@[] is a problem for --gc:destructors"
([#12820](https://github.com/nim-lang/Nim/issues/12820))
- Fixed "Codegen ICE in allPathsAsgnResult"
([#12827](https://github.com/nim-lang/Nim/issues/12827))
- Fixed "seq[Object with ref and destructor type] doesn't work in old runtime"
([#12882](https://github.com/nim-lang/Nim/issues/12882))
- Fixed "Destructor not invoked because it is instantiated too late, old runtime"
([#12883](https://github.com/nim-lang/Nim/issues/12883))
- Fixed "The collect macro does not handle if/case correctly"
([#12874](https://github.com/nim-lang/Nim/issues/12874))
- Fixed "allow typed/untyped params in magic procs (even if not in stdlib)"
([#12911](https://github.com/nim-lang/Nim/issues/12911))
- Fixed "ARC/newruntime memory corruption"
([#12899](https://github.com/nim-lang/Nim/issues/12899))
- Fixed "tasyncclosestall.nim still flaky test: Address already in use"
([#12919](https://github.com/nim-lang/Nim/issues/12919))
- Fixed "newruntime and computed goto: variables inside the loop are in generated code uninitialised"
([#12785](https://github.com/nim-lang/Nim/issues/12785))
- Fixed "osx: dsymutil needs to be called for debug builds to keep debug info"
([#12735](https://github.com/nim-lang/Nim/issues/12735))
- Fixed "codegen ICE with ref objects, gc:destructors"
([#12826](https://github.com/nim-lang/Nim/issues/12826))
- Fixed "mutable iterator cannot yield named tuples"
([#12945](https://github.com/nim-lang/Nim/issues/12945))
- Fixed "parsecfg stores "\r\n" line breaks just as "\n""
([#12970](https://github.com/nim-lang/Nim/issues/12970))
- Fixed "db_postgres.getValue issues warning when no rows found"
([#12973](https://github.com/nim-lang/Nim/issues/12973))
- Fixed "ARC: Unpacking tuple with seq causes segfault"
([#12989](https://github.com/nim-lang/Nim/issues/12989))
- Fixed "ARC/newruntime: strutils.join on seq with only empty strings causes segfault"
([#12965](https://github.com/nim-lang/Nim/issues/12965))
- Fixed "regression (1.0.4): `{.push exportc.}` wrongly affects generic instantiations, causing codegen errors"
([#12985](https://github.com/nim-lang/Nim/issues/12985))
- Fixed "cdt, crash with --gc:arc, works fine with default gc"
([#12978](https://github.com/nim-lang/Nim/issues/12978))
- Fixed "ARC: No indexError thrown on out-of-bound seq access, SIGSEGV instead"
([#12961](https://github.com/nim-lang/Nim/issues/12961))
- Fixed "ARC/async: Returning in a try-block results in wrong codegen"
([#12956](https://github.com/nim-lang/Nim/issues/12956))
- Fixed "asm keyword is generating wrong output C code when --cc:tcc"
([#12988](https://github.com/nim-lang/Nim/issues/12988))
- Fixed "Destructor not invoked"
([#13026](https://github.com/nim-lang/Nim/issues/13026))
- Fixed "ARC/newruntime: Adding inherited var ref object to seq with base type causes segfault"
([#12964](https://github.com/nim-lang/Nim/issues/12964))
- Fixed "Style check error with JS compiler target"
([#13032](https://github.com/nim-lang/Nim/issues/13032))
- Fixed "regression(1.0.4): undeclared identifier: 'readLines'; plus another regression and bug"
([#13013](https://github.com/nim-lang/Nim/issues/13013))
- Fixed "regression(1.04) `invalid pragma: since` with nim js"
([#12996](https://github.com/nim-lang/Nim/issues/12996))
- Fixed "Sink to MemMove optimization in injectdestructors"
([#13002](https://github.com/nim-lang/Nim/issues/13002))
- Fixed "--gc:arc: `catch` doesn't work with exception subclassing"
([#13072](https://github.com/nim-lang/Nim/issues/13072))
- Fixed "nim c --gc:arc --exceptions:{setjmp,goto} incorrectly handles raise; `nim cpp --gc:arc` is ok"
([#13070](https://github.com/nim-lang/Nim/issues/13070))
- Fixed "typetraits feature request - get subtype of a generic type"
([#6454](https://github.com/nim-lang/Nim/issues/6454))
- Fixed "CountTable inconsistencies between keys() and len() after setting value to 0"
([#12813](https://github.com/nim-lang/Nim/issues/12813))
- Fixed "{.align.} pragma is not applied if there is a generic field"
([#13122](https://github.com/nim-lang/Nim/issues/13122))
- Fixed "ARC, finalizer, allow rebinding the same function multiple times"
([#13112](https://github.com/nim-lang/Nim/issues/13112))
- Fixed "`nim doc` treats `export localSymbol` incorrectly"
([#13100](https://github.com/nim-lang/Nim/issues/13100))
- Fixed "--gc:arc SIGSEGV (double free?)"
([#13119](https://github.com/nim-lang/Nim/issues/13119))
- Fixed "codegen bug with arc"
([#13105](https://github.com/nim-lang/Nim/issues/13105))
- Fixed "symbols not defined in the grammar"
([#10665](https://github.com/nim-lang/Nim/issues/10665))
- Fixed "[JS] Move is not defined"
([#9674](https://github.com/nim-lang/Nim/issues/9674))
- Fixed "[TODO] pathutils.`/` can return invalid AbsoluteFile"
([#13121](https://github.com/nim-lang/Nim/issues/13121))
- Fixed "regression(1.04) `nim doc main.nim` generates broken html (no css)"
([#12998](https://github.com/nim-lang/Nim/issues/12998))
- Fixed "Wrong supportsCopyMem on string in type section"
([#13095](https://github.com/nim-lang/Nim/issues/13095))
- Fixed "Arc, finalizer, out of memory"
([#13157](https://github.com/nim-lang/Nim/issues/13157))
- Fixed "`--genscript` messes up nimcache and future nim invocations"
([#13144](https://github.com/nim-lang/Nim/issues/13144))
- Fixed "--gc:arc with --exceptions:goto for "nim c" generate invalid c code"
([#13186](https://github.com/nim-lang/Nim/issues/13186))
- Fixed "[regression] duplicate member `_i1` codegen bug"
([#13195](https://github.com/nim-lang/Nim/issues/13195))
- Fixed "RTree investigations with valgrind for --gc:arc"
([#13110](https://github.com/nim-lang/Nim/issues/13110))
- Fixed "relativePath("foo", ".") returns wrong path"
([#13211](https://github.com/nim-lang/Nim/issues/13211))
- Fixed "asyncftpclient - problem with welcome.msg"
([#4684](https://github.com/nim-lang/Nim/issues/4684))
- Fixed "Unclear error message, lowest priority"
([#13256](https://github.com/nim-lang/Nim/issues/13256))
- Fixed "Channel messages are corrupted"
([#13219](https://github.com/nim-lang/Nim/issues/13219))
- Fixed "Codegen bug with exportc and case objects"
([#13281](https://github.com/nim-lang/Nim/issues/13281))
- Fixed "[bugfix] fix #11590: c compiler warnings silently ignored, giving undefined behavior"
([#11591](https://github.com/nim-lang/Nim/issues/11591))
- Fixed "[CI] tnetdial flaky test"
([#13132](https://github.com/nim-lang/Nim/issues/13132))
- Fixed "Cross-Compiling with -d:mingw fails to locate compiler under OSX"
([#10717](https://github.com/nim-lang/Nim/issues/10717))
- Fixed "`nim doc --project` broken with imports below main project file or duplicate names"
([#13150](https://github.com/nim-lang/Nim/issues/13150))
- Fixed "regression: isNamedTuple(MyGenericTuple[int]) is false, should be true"
([#13349](https://github.com/nim-lang/Nim/issues/13349))
- Fixed "--gc:arc codegen bug copying objects bound to C structs with missing C struct fields"
([#13269](https://github.com/nim-lang/Nim/issues/13269))
- Fixed "write requires conversion to string"
([#13182](https://github.com/nim-lang/Nim/issues/13182))
- Fixed "Some remarks to stdlib documentation"
([#13352](https://github.com/nim-lang/Nim/issues/13352))
- Fixed "a `check` in unittest generated by template doesn't show actual value"
([#6736](https://github.com/nim-lang/Nim/issues/6736))
- Fixed "Implicit return with case expression fails with 'var' return."
([#3339](https://github.com/nim-lang/Nim/issues/3339))
- Fixed "Segfault with closure on arc"
([#13314](https://github.com/nim-lang/Nim/issues/13314))
- Fixed "[Macro] Crash on malformed case statement with multiple else"
([#13255](https://github.com/nim-lang/Nim/issues/13255))
- Fixed "regression: `echo 'discard' | nim c -r -` generates a file '-' ; `-` should be treated specially"
([#13374](https://github.com/nim-lang/Nim/issues/13374))
- Fixed "on OSX, debugging (w gdb or lldb) a nim program crashes at the 1st call to `execCmdEx`"
([#9634](https://github.com/nim-lang/Nim/issues/9634))
- Fixed "Internal error in getTypeDescAux"
([#13378](https://github.com/nim-lang/Nim/issues/13378))
- Fixed "gc:arc mode breaks tuple let"
([#13368](https://github.com/nim-lang/Nim/issues/13368))
- Fixed "Nim compiler hangs for certain C/C++ compiler errors"
([#8648](https://github.com/nim-lang/Nim/issues/8648))
- Fixed "htmlgen does not support `data-*` attributes"
([#13444](https://github.com/nim-lang/Nim/issues/13444))
- Fixed "[gc:arc] setLen will cause string not to be null-terminated."
([#13457](https://github.com/nim-lang/Nim/issues/13457))
- Fixed "joinPath("", "") is "/" ; should be """
([#13455](https://github.com/nim-lang/Nim/issues/13455))
- Fixed "[CI] flaky test on windows: tests/osproc/texitcode.nim"
([#13449](https://github.com/nim-lang/Nim/issues/13449))
- Fixed "Casting to float32 on NimVM is broken"
([#13479](https://github.com/nim-lang/Nim/issues/13479))
- Fixed "`--hints:off` doesn't work (doesn't override ~/.config/nim.cfg)"
([#8312](https://github.com/nim-lang/Nim/issues/8312))
- Fixed "joinPath("", "") is "/" ; should be """
([#13455](https://github.com/nim-lang/Nim/issues/13455))
- Fixed "tables.values is broken"
([#13496](https://github.com/nim-lang/Nim/issues/13496))
- Fixed "global user config can override project specific config"
([#9405](https://github.com/nim-lang/Nim/issues/9405))
- Fixed "Non deterministic macros and id consistency problem"
([#12627](https://github.com/nim-lang/Nim/issues/12627))
- Fixed "try expression doesn't work with return on expect branch"
([#13490](https://github.com/nim-lang/Nim/issues/13490))
- Fixed "CI will break every 4 years on feb 28: times doesn't handle leap years properly"
([#13543](https://github.com/nim-lang/Nim/issues/13543))
- Fixed "[minor] `nimgrep --word` doesn't work with operators (eg misses `1 +% 2`)"
([#13528](https://github.com/nim-lang/Nim/issues/13528))
- Fixed "`as` is usable as infix operator but its existence and precedence are not documented"
([#13409](https://github.com/nim-lang/Nim/issues/13409))
- Fixed "JSON unmarshalling drops seq's items"
([#13531](https://github.com/nim-lang/Nim/issues/13531))
- Fixed "os.joinPath returns wrong path when head ends '\' or '/' and tail starts '..'."
([#13579](https://github.com/nim-lang/Nim/issues/13579))
- Fixed "Block-local types with the same name lead to bad codegen (sighashes regression)"
([#5170](https://github.com/nim-lang/Nim/issues/5170))
- Fixed "tuple codegen error"
([#12704](https://github.com/nim-lang/Nim/issues/12704))
- Fixed "newHttpHeaders does not accept repeated headers"
([#13573](https://github.com/nim-lang/Nim/issues/13573))
- Fixed "regression: --incremental:on fails on simplest example"
([#13319](https://github.com/nim-lang/Nim/issues/13319))
- Fixed "strscan can't get value of last element in format"
([#13605](https://github.com/nim-lang/Nim/issues/13605))
- Fixed "hashes_examples crashes with "Bus Error" (unaligned access) on sparc64"
([#12508](https://github.com/nim-lang/Nim/issues/12508))
- Fixed "gc:arc bug with re-used `seq[T]`"
([#13596](https://github.com/nim-lang/Nim/issues/13596))
- Fixed "`raise CatchableError` is broken with --gc:arc when throwing inside a proc"
([#13599](https://github.com/nim-lang/Nim/issues/13599))
- Fixed "cpp --gc:arc --exceptions:goto fails to raise with discard"
([#13436](https://github.com/nim-lang/Nim/issues/13436))
- Fixed "terminal doesn't compile with -d:useWinAnsi"
([#13607](https://github.com/nim-lang/Nim/issues/13607))
- Fixed "Parsing "sink ptr T" - region needs to be an object type"
([#12757](https://github.com/nim-lang/Nim/issues/12757))
- Fixed "gc:arc + threads:on + closures compilation error"
([#13519](https://github.com/nim-lang/Nim/issues/13519))
- Fixed "[ARC] segmentation fault"
([#13240](https://github.com/nim-lang/Nim/issues/13240))
- Fixed "times.toDateTime buggy on 29th, 30th and 31th of each month"
([#13558](https://github.com/nim-lang/Nim/issues/13558))
- Fixed "Deque misbehaves on VM"
([#13310](https://github.com/nim-lang/Nim/issues/13310))
- Fixed "Nimscript listFiles should throw exception when path is not found"
([#12676](https://github.com/nim-lang/Nim/issues/12676))
- Fixed "koch boot fails if even an empty config.nims is present in ~/.config/nims/ [devel regression]"
([#13633](https://github.com/nim-lang/Nim/issues/13633))
- Fixed "nim doc generates lots of false positive LockLevel warnings"
([#13218](https://github.com/nim-lang/Nim/issues/13218))
- Fixed "Arrays are passed by copy to iterators, causing crashes, unnecessary allocations and slowdowns"
([#12747](https://github.com/nim-lang/Nim/issues/12747))
- Fixed "Range types always uses signed integer as a base type"
([#13646](https://github.com/nim-lang/Nim/issues/13646))
- Fixed "Generate c code cannot compile with recent devel version"
([#13645](https://github.com/nim-lang/Nim/issues/13645))
- Fixed "[regression] VM: Error: cannot convert -1 to uint64"
([#13661](https://github.com/nim-lang/Nim/issues/13661))
- Fixed "Spurious raiseException(Exception) detected"
([#13654](https://github.com/nim-lang/Nim/issues/13654))
- Fixed "gc:arc memory leak"
([#13659](https://github.com/nim-lang/Nim/issues/13659))
- Fixed "Error: cannot convert -1 to uint (inside tuples)"
([#13671](https://github.com/nim-lang/Nim/issues/13671))
- Fixed "strformat issue with --gc:arc"
([#13622](https://github.com/nim-lang/Nim/issues/13622))
- Fixed "astToStr doesn't work inside generics"
([#13524](https://github.com/nim-lang/Nim/issues/13524))
- Fixed "oswalkdir.walkDirRec wont return folders"
([#11458](https://github.com/nim-lang/Nim/issues/11458))
- Fixed "`echo 'echo 1' | nim c -r -` silently gives wrong results (nimBetterRun not updated for stdin)"
([#13412](https://github.com/nim-lang/Nim/issues/13412))
- Fixed "gc:arc destroys the global variable accidentally."
([#13691](https://github.com/nim-lang/Nim/issues/13691))
- Fixed "[minor] sigmatch errors should be sorted, for reproducible errors"
([#13538](https://github.com/nim-lang/Nim/issues/13538))
- Fixed "Exception when converting csize to clong"
([#13698](https://github.com/nim-lang/Nim/issues/13698))
- Fixed "ARC: variables are no copied on the thread spawn causing crashes"
([#13708](https://github.com/nim-lang/Nim/issues/13708))
- Fixed "Illegal distinct seq causes compiler crash"
([#13720](https://github.com/nim-lang/Nim/issues/13720))
- Fixed "cyclic seq definition crashes the compiler"
([#13715](https://github.com/nim-lang/Nim/issues/13715))
- Fixed "Iterator with openArray parameter make the argument evaluated many times"
([#13417](https://github.com/nim-lang/Nim/issues/13417))
- Fixed "net/asyncnet: Unable to access peer's certificate chain"
([#13299](https://github.com/nim-lang/Nim/issues/13299))
- Fixed "Accidentally "SIGSEGV: Illegal storage access" error after arc optimizations (#13325)"
([#13709](https://github.com/nim-lang/Nim/issues/13709))
- Fixed "Base64 Regression"
([#13722](https://github.com/nim-lang/Nim/issues/13722))
- Fixed "A regression (?) with --gc:arc and repr"
([#13731](https://github.com/nim-lang/Nim/issues/13731))
- Fixed "Internal compiler error when using the new variable pragmas"
([#13737](https://github.com/nim-lang/Nim/issues/13737))
- Fixed "bool conversion produces vcc 2019 warning at cpp compilation stage"
([#13744](https://github.com/nim-lang/Nim/issues/13744))
- Fixed "Compiler "does not detect" a type recursion error in the wrong code, remaining frozen"
([#13763](https://github.com/nim-lang/Nim/issues/13763))
- Fixed "[minor] regression: `Foo[0.0] is Foo[-0.0]` is now false"
([#13730](https://github.com/nim-lang/Nim/issues/13730))
- Fixed "`nim doc` - only whitespace on first line causes segfault"
([#13631](https://github.com/nim-lang/Nim/issues/13631))
- Fixed "hashset regression"
([#13794](https://github.com/nim-lang/Nim/issues/13794))
- Fixed "`os.getApplFreebsd` could return incorrect paths in the case of a long path"
([#13806](https://github.com/nim-lang/Nim/issues/13806))
- Fixed "Destructors are not inherited"
([#13810](https://github.com/nim-lang/Nim/issues/13810))
- Fixed "io.readLines AssertionError on devel"
([#13829](https://github.com/nim-lang/Nim/issues/13829))
- Fixed "exceptions:goto accidentally reset the variable during exception handling"
([#13782](https://github.com/nim-lang/Nim/issues/13782))

View File

@@ -0,0 +1,874 @@
# v1.4.0 - 2020-10-16
## Standard library additions and changes
- Added some enhancements to `std/jsonutils` module.
* Added a possibility to deserialize JSON arrays directly to `HashSet` and
`OrderedSet` types and respectively to serialize those types to JSON arrays
via `jsonutils.fromJson` and `jsonutils.toJson` procedures.
* Added a possibility to deserialize JSON `null` objects to Nim option objects
and respectively to serialize Nim option object to JSON object if `isSome`
or to JSON null object if `isNone` via `jsonutils.fromJson` and
`jsonutils.toJson` procedures.
* Added a `Joptions` parameter to `jsonutils.fromJson` currently
containing two boolean options `allowExtraKeys` and `allowMissingKeys`.
- If `allowExtraKeys` is `true` Nim's object to which the JSON is parsed is
not required to have a field for every JSON key.
- If `allowMissingKeys` is `true` Nim's object to which JSON is parsed is
allowed to have fields without corresponding JSON keys.
- Added `bindParams`, `bindParam` to `db_sqlite` for binding parameters into a `SqlPrepared` statement.
- Added `tryInsert`,`insert` procs to `db_*` libs which accept primary key column name.
- Added `xmltree.newVerbatimText` support create `style`'s,`script`'s text.
- `uri` module now implements RFC-2397.
- Added [DOM Parser](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser)
to the `dom` module for the JavaScript target.
- The default hash for `Ordinal` has changed to something more bit-scrambling.
`import hashes; proc hash(x: myInt): Hash = hashIdentity(x)` recovers the old
one in an instantiation context while `-d:nimIntHash1` recovers it globally.
- `deques.peekFirst` and `deques.peekLast` now have `var Deque[T] -> var T` overloads.
- File handles created from high-level abstractions in the stdlib will no longer
be inherited by child processes. In particular, these modules are affected:
`asyncdispatch`, `asyncnet`, `system`, `nativesockets`, `net` and `selectors`.
For `asyncdispatch`, `asyncnet`, `net` and `nativesockets`, an `inheritable`
flag has been added to all `proc`s that create sockets, allowing the user to
control whether the resulting socket is inheritable. This flag is provided to
ease the writing of multi-process servers, where sockets inheritance is
desired.
For a transition period, define `nimInheritHandles` to enable file handle
inheritance by default. This flag does **not** affect the `selectors` module
due to the differing semantics between operating systems.
`asyncdispatch.setInheritable`, `system.setInheritable` and
`nativesockets.setInheritable` are also introduced for setting file handle or
socket inheritance. Not all platforms have these `proc`s defined.
- The file descriptors created for internal bookkeeping by `ioselector_kqueue`
and `ioselector_epoll` will no longer be leaked to child processes.
- `strutils.formatFloat` with `precision = 0` has been restored to the version
1 behaviour that produces a trailing dot, e.g. `formatFloat(3.14159, precision = 0)`
is now `3.`, not `3`.
- Added `commonPrefixLen` to `critbits`.
- `relativePath(rel, abs)` and `relativePath(abs, rel)` used to silently give wrong results
(see #13222); instead they now use `getCurrentDir` to resolve those cases,
and this can now throw in edge cases where `getCurrentDir` throws.
`relativePath` also now works for js with `-d:nodejs`.
- JavaScript and NimScript standard library changes: `streams.StringStream` is
now supported in JavaScript, with the limitation that any buffer `pointer`s
used must be castable to `ptr string`, any incompatible pointer type will not
work. The `lexbase` and `streams` modules used to fail to compile on
NimScript due to a bug, but this has been fixed.
The following modules now compile on both JS and NimScript: `parsecsv`,
`parsecfg`, `parsesql`, `xmlparser`, `htmlparser` and `ropes`. Additionally
supported for JS is `cstrutils.startsWith` and `cstrutils.endsWith`, for
NimScript: `json`, `parsejson`, `strtabs` and `unidecode`.
- Added `streams.readStr` and `streams.peekStr` overloads to
accept an existing string to modify, which avoids memory
allocations, similar to `streams.readLine` (#13857).
- Added high-level `asyncnet.sendTo` and `asyncnet.recvFrom` UDP functionality.
- `dollars.$` now works for unsigned ints with `nim js`.
- Improvements to the `bitops` module, including bitslices, non-mutating versions
of the original masking functions, `mask`/`masked`, and varargs support for
`bitand`, `bitor`, and `bitxor`.
- `sugar.=>` and `sugar.->` changes: Previously `(x, y: int)` was transformed
into `(x: auto, y: int)`, it now becomes `(x: int, y: int)` for consistency
with regular proc definitions (although you cannot use semicolons).
Pragmas and using a name are now allowed on the lefthand side of `=>`. Here
is an example of these changes:
```nim
import sugar
foo(x, y: int) {.noSideEffect.} => x + y
# is transformed into
proc foo(x: int, y: int): auto {.noSideEffect.} = x + y
```
- The fields of `times.DateTime` are now private, and are accessed with getters and deprecated setters.
- The `times` module now handles the default value for `DateTime` more consistently.
Most procs raise an assertion error when given
an uninitialized `DateTime`, the exceptions are `==` and `$` (which returns `"Uninitialized DateTime"`).
The proc `times.isInitialized` has been added which can be used to check if
a `DateTime` has been initialized.
- Fix a bug where calling `close` on io streams in `osproc.startProcess` was a noop and led to
hangs if a process had both reads from stdin and writes (e.g. to stdout).
- The callback that is passed to `system.onThreadDestruction` must now be `.raises: []`.
- The callback that is assigned to `system.onUnhandledException` must now be `.gcsafe`.
- `osproc.execCmdEx` now takes an optional `input` for stdin, `workingDir` and `env`
parameters.
- Added a `ssl_config` module containing lists of secure ciphers as recommended by
[Mozilla OpSec](https://wiki.mozilla.org/Security/Server_Side_TLS)
- `net.newContext` now defaults to the list of ciphers targeting
["Intermediate compatibility"](https://wiki.mozilla.org/Security/Server_Side_TLS#Intermediate_compatibility_.28recommended.29)
per Mozilla's recommendation instead of `ALL`. This change should protect
users from the use of weak and insecure ciphers while still provides
adequate compatibility with the majority of the Internet.
- A new module `std/jsonutils` with hookable `jsonTo,toJson,fromJson` operations for json
serialization/deserialization of custom types was added.
- A new proc `heapqueue.find[T](heap: HeapQueue[T], x: T): int` to get index of element ``x``
was added.
- Added `rstgen.rstToLatex` a convenience proc for `renderRstToOut` and `initRstGenerator`.
- Added `os.normalizeExe`.
- `macros.newLit` now preserves named vs unnamed tuples.
- Added `random.gauss`, that uses the ratio of uniforms method of sampling from a Gaussian distribution.
- Added `typetraits.elementType` to get the element type of an iterable.
- `typetraits.$` changes: `$(int,)` is now `"(int,)"` instead of `"(int)"`;
`$tuple[]` is now `"tuple[]"` instead of `"tuple"`;
`$((int, float), int)` is now `"((int, float), int)"` instead of `"(tuple of (int, float), int)"`
- Added `macros.extractDocCommentsAndRunnables` helper.
- `strformat.fmt` and `strformat.&` support `specifier =`. `fmt"{expr=}"` now
expands to `fmt"expr={expr}"`.
- Deprecations: instead of `os.existsDir` use `dirExists`, instead of `os.existsFile` use `fileExists`.
- Added the `jsre` module, [Regular Expressions for the JavaScript target.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions).
- Made `maxLines` argument `Positive` in `logging.newRollingFileLogger`,
because negative values will result in a new file being created for each logged
line which doesn't make sense.
- Changed `log` in `logging` to use proper log level for JavaScript,
e.g. `debug` uses `console.debug`, `info` uses `console.info`, `warn` uses `console.warn`, etc.
- Tables, HashSets, SharedTables and deques don't require anymore that the passed
initial size must be a power of two - this is done internally.
Proc `rightSize` for Tables and HashSets is deprecated, as it is not needed anymore.
`CountTable.inc` takes `val: int` again not `val: Positive`; i.e. it can "count down" again.
- Removed deprecated symbols from `macros` module, some of which were deprecated already in `0.15`.
- Removed `sugar.distinctBase`, deprecated since `0.19`. Use `typetraits.distinctBase`.
- `asyncdispatch.PDispatcher.handles` is exported so that an external low-level libraries can access it.
- `std/with`, `sugar.dup` now support object field assignment expressions:
```nim
import std/with
type Foo = object
x, y: int
var foo = Foo()
with foo:
x = 10
y = 20
echo foo
```
- Proc `math.round` is no longer deprecated. The advice to use `strformat` instead
cannot be applied to every use case. The limitations and the (lack of) reliability
of `round` are well documented.
- Added `getprotobyname` to `winlean`. Added `getProtoByname` to `nativesockets` which returns a protocol code
from the database that matches the protocol `name`.
- Added missing attributes and methods to `dom.Navigator` like `deviceMemory`, `onLine`, `vibrate()`, etc.
- Added `strutils.indentation` and `strutils.dedent` which enable indented string literals:
```nim
import strutils
echo dedent """
This
is
cool!
"""
```
- Added `initUri(isIpv6: bool)` to `uri` module, now `uri` supports parsing ipv6 hostname.
- Added `readLines(p: Process)` to `osproc`.
- Added the below `toX` procs for collections. The usage is similar to procs such as
`sets.toHashSet` and `tables.toTable`. Previously, it was necessary to create the
respective empty collection and add items manually.
* `critbits.toCritBitTree`, which creates a `CritBitTree` from an `openArray` of
items or an `openArray` of pairs.
* `deques.toDeque`, which creates a `Deque` from an `openArray`.
* `heapqueue.toHeapQueue`, which creates a `HeapQueue` from an `openArray`.
* `intsets.toIntSet`, which creates an `IntSet` from an `openArray`.
- Added `progressInterval` argument to `asyncftpclient.newAsyncFtpClient` to control the interval
at which progress callbacks are called.
- Added `os.copyFileToDir`.
## Language changes
- The `=destroy` hook no longer has to reset its target, as the compiler now automatically inserts
`wasMoved` calls where needed.
- The `=` hook is now called `=copy` for clarity. The old name `=` is still available so there
is no need to update your code. This change was backported to 1.2 too so you can use the
more readable `=copy` without loss of compatibility.
- In the newruntime it is now allowed to assign to the discriminator field
without restrictions as long as the case object doesn't have a custom destructor.
The discriminator value doesn't have to be a constant either. If you have a
custom destructor for a case object and you do want to freely assign discriminator
fields, it is recommended to refactor the object into 2 objects like this:
```nim
type
MyObj = object
case kind: bool
of true: y: ptr UncheckedArray[float]
of false: z: seq[int]
proc `=destroy`(x: MyObj) =
if x.kind and x.y != nil:
deallocShared(x.y)
```
Refactor into:
```nim
type
MySubObj = object
val: ptr UncheckedArray[float]
MyObj = object
case kind: bool
of true: y: MySubObj
of false: z: seq[int]
proc `=destroy`(x: MySubObj) =
if x.val != nil:
deallocShared(x.val)
```
- `getImpl` on enum type symbols now returns field syms instead of idents. This helps
with writing typed macros. The old behavior for backwards compatibility can be restored
with `--useVersion:1.0`.
- The typed AST for proc headers will now have the arguments be syms instead of idents.
This helps with writing typed macros. The old behaviour for backwards compatibility can
be restored with `--useVersion:1.0`.
- ``let`` statements can now be used without a value if declared with
``importc``/``importcpp``/``importjs``/``importobjc``.
- The keyword `from` is now usable as an operator.
- Exceptions inheriting from `system.Defect` are no longer tracked with
the `.raises: []` exception tracking mechanism. This is more consistent with the
built-in operations. The following always used to compile (and still does):
```nim
proc mydiv(a, b): int {.raises: [].} =
a div b # can raise an DivByZeroDefect
```
Now also this compiles:
```nim
proc mydiv(a, b): int {.raises: [].} =
if b == 0: raise newException(DivByZeroDefect, "division by zero")
else: result = a div b
```
The reason for this is that `DivByZeroDefect` inherits from `Defect` and
with `--panics:on` `Defects` become unrecoverable errors.
- Added the `thiscall` calling convention as specified by Microsoft, mostly for hooking purposes.
- Deprecated the `{.unroll.}` pragma, because it was always ignored by the compiler anyway.
- Removed the deprecated `strutils.isNilOrWhitespace`.
- Removed the deprecated `sharedtables.initSharedTable`.
- Removed the deprecated `asyncdispatch.newAsyncNativeSocket`.
- Removed the deprecated `dom.releaseEvents` and `dom.captureEvents`.
- Removed `sharedlists.initSharedList`, was deprecated and produces undefined behaviour.
- There is a new experimental feature called "strictFuncs" which makes the definition of
`.noSideEffect` stricter. [See here](manual_experimental.html#stricts-funcs)
for more information.
- "for-loop macros" (see [the manual](manual.html#macros-for-loop-macros)) are no longer
an experimental feature. In other words, you don't have to write pragma
`{.experimental: "forLoopMacros".}` if you want to use them.
- Added the ``.noalias`` pragma. It is mapped to C's ``restrict`` keyword for the increased
performance this keyword can enable.
- `items` no longer compiles with enums with holes as its behavior was error prone, see #14004.
- `system.deepcopy` has to be enabled explicitly for `--gc:arc` and `--gc:orc` via
`--deepcopy:on`.
- Added the `std/effecttraits` module for introspection of the inferred effects.
We hope this enables `async` macros that are precise about the possible exceptions that
can be raised.
- The pragma blocks `{.gcsafe.}: ...` and `{.noSideEffect.}: ...` can now also be
written as `{.cast(gcsafe).}: ...` and `{.cast(noSideEffect).}: ...`. This is the new
preferred way of writing these, emphasizing their unsafe nature.
## Compiler changes
- Specific warnings can now be turned into errors via `--warningAsError[X]:on|off`.
- The `define` and `undef` pragmas have been de-deprecated.
- New command: `nim r main.nim [args...]` which compiles and runs main.nim, and implies `--usenimcache`
so that the output is saved to $nimcache/main$exeExt, using the same logic as `nim c -r` to
avoid recompilations when sources don't change.
Example:
```bash
nim r compiler/nim.nim --help # only compiled the first time
echo 'import os; echo getCurrentCompilerExe()' | nim r - # this works too
nim r compiler/nim.nim --fullhelp # no recompilation
nim r --nimcache:/tmp main # binary saved to /tmp/main
```
- `--hint:processing` is now supported and means `--hint:processing:on`
(likewise with other hints and warnings), which is consistent with all other bool flags.
(since 1.3.3).
- `nim doc -r main` and `nim rst2html -r main` now call `openDefaultBrowser`.
- Added the new hint `--hint:msgOrigin` will show where a compiler msg (hint|warning|error)
was generated; this helps in particular when it's non obvious where it came from
either because multiple locations generate the same message, or because the
message involves runtime formatting.
- Added the new flag `--backend:js|c|cpp|objc` (or -b:js etc), to change the backend; can be
used with any command (e.g. nim r, doc, check etc); safe to re-assign.
- Added the new flag `--doccmd:cmd` to pass additional flags for runnableExamples,
e.g.: `--doccmd:-d:foo --threads`
use `--doccmd:skip` to skip runnableExamples and rst test snippets.
- Added the new flag `--usenimcache` to output binary files to nimcache.
- `runnableExamples "-b:cpp -r:off": code` is now supported, allowing to override
how an example is compiled and run, for example to change the backend.
- `nim doc` now outputs under `$projectPath/htmldocs` when `--outdir` is unspecified
(with or without `--project`); passing `--project` now automatically generates
an index and enables search.
See [docgen](docgen.html#introduction-quick-start) for details.
- Removed the `--oldNewlines` switch.
- Removed the `--laxStrings` switch for mutating the internal zero terminator on strings.
- Removed the `--oldast` switch.
- Removed the `--oldgensym` switch.
- `$getType(untyped)` is now "untyped" instead of "expr", `$getType(typed)` is
now "typed" instead of "stmt".
- Sink inference is now disabled per default and has to enabled explicitly via
`--sinkInference:on`. *Note*: For the standard library sink inference remains
enabled. This change is most relevant for the `--gc:arc`, `--gc:orc` memory
management modes.
## Tool changes
- `nimsuggest` now returns both the forward declaration and the
implementation location upon a `def` query. Previously the behavior was
to return the forward declaration only.
## Bugfixes
- Fixed "repr() not available for uint{,8,16,32,64} under --gc:arc"
([#13872](https://github.com/nim-lang/Nim/issues/13872))
- Fixed "Critical: 1 completed Future, multiple await: Only 1 await will be awakened (the last one)"
([#13889](https://github.com/nim-lang/Nim/issues/13889))
- Fixed "crash on openarray interator with argument in stmtListExpr"
([#13739](https://github.com/nim-lang/Nim/issues/13739))
- Fixed "Some compilers on Windows don't work"
([#13910](https://github.com/nim-lang/Nim/issues/13910))
- Fixed "httpclient hangs if it recieves an HTTP 204 (No Content)"
([#13894](https://github.com/nim-lang/Nim/issues/13894))
- Fixed ""distinct uint64" type corruption on 32-bit, when using {.borrow.} operators"
([#13902](https://github.com/nim-lang/Nim/issues/13902))
- Fixed "Regression: impossible to use typed pragmas with proc types"
([#13909](https://github.com/nim-lang/Nim/issues/13909))
- Fixed "openssl wrapper corrupts stack on OpenSSL 1.1.1f + Android"
([#13903](https://github.com/nim-lang/Nim/issues/13903))
- Fixed "C compile error with --gc:arc on version 1.2.0 "unknown type name 'TGenericSeq'"
([#13863](https://github.com/nim-lang/Nim/issues/13863))
- Fixed "var return type for proc doesn't work at c++ backend"
([#13848](https://github.com/nim-lang/Nim/issues/13848))
- Fixed "TimeFormat() should raise an error but craches at compilation time"
([#12864](https://github.com/nim-lang/Nim/issues/12864))
- Fixed "gc:arc cannot fully support threadpool with FlowVar"
([#13781](https://github.com/nim-lang/Nim/issues/13781))
- Fixed "simple 'var openarray[char]' assignment crash when the openarray source is a local string and using gc:arc"
([#14003](https://github.com/nim-lang/Nim/issues/14003))
- Fixed "Cant use expressions with `when` in `type` sections."
([#14007](https://github.com/nim-lang/Nim/issues/14007))
- Fixed "`for a in MyEnum` gives incorrect results with enum with holes"
([#14001](https://github.com/nim-lang/Nim/issues/14001))
- Fixed "Trivial crash"
([#12741](https://github.com/nim-lang/Nim/issues/12741))
- Fixed "Enum with holes cannot be used as Table index"
([#12834](https://github.com/nim-lang/Nim/issues/12834))
- Fixed "spawn proc that uses typedesc crashes the compiler"
([#14014](https://github.com/nim-lang/Nim/issues/14014))
- Fixed "Docs Search `Results` box styling is not Dark Mode Friendly"
([#13972](https://github.com/nim-lang/Nim/issues/13972))
- Fixed "--gc:arc -d:useSysAssert undeclared identifier `cstderr` with newSeq"
([#14038](https://github.com/nim-lang/Nim/issues/14038))
- Fixed "issues in the manual"
([#12486](https://github.com/nim-lang/Nim/issues/12486))
- Fixed "Annoying warning: inherit from a more precise exception type like ValueError, IOError or OSError [InheritFromException]"
([#14052](https://github.com/nim-lang/Nim/issues/14052))
- Fixed "relativePath("foo", "/") and relativePath("/", "foo") is wrong"
([#13222](https://github.com/nim-lang/Nim/issues/13222))
- Fixed "[regression] `parseEnum` does not work anymore for enums with holes"
([#14030](https://github.com/nim-lang/Nim/issues/14030))
- Fixed "Exception types in the stdlib should inherit from `CatchableError` or `Defect`, not `Exception`"
([#10288](https://github.com/nim-lang/Nim/issues/10288))
- Fixed "Make debugSend and debugRecv procs public in smtp.nim"
([#12189](https://github.com/nim-lang/Nim/issues/12189))
- Fixed "xmltree need add raw text, when add style element"
([#14064](https://github.com/nim-lang/Nim/issues/14064))
- Fixed "raises requirement does not propagate to derived methods"
([#8481](https://github.com/nim-lang/Nim/issues/8481))
- Fixed "tests/stdlib/tgetaddrinfo.nim fails on NetBSD"
([#14091](https://github.com/nim-lang/Nim/issues/14091))
- Fixed "tests/niminaction/Chapter8/sdl/sdl_test.nim fails on NetBSD"
([#14088](https://github.com/nim-lang/Nim/issues/14088))
- Fixed "Incorrect escape sequence for example in jsffi library documentation"
([#14110](https://github.com/nim-lang/Nim/issues/14110))
- Fixed "HCR: Can not link exported const, in external library"
([#13915](https://github.com/nim-lang/Nim/issues/13915))
- Fixed "Cannot import std/unidecode"
([#14112](https://github.com/nim-lang/Nim/issues/14112))
- Fixed "macOS: dsymutil should not be called on static libraries"
([#14132](https://github.com/nim-lang/Nim/issues/14132))
- Fixed "nim jsondoc -o:doc.json filename.nim fails when sequences without a type are used"
([#14066](https://github.com/nim-lang/Nim/issues/14066))
- Fixed "algorithm.sortedByIt template corrupts tuple input under --gc:arc"
([#14079](https://github.com/nim-lang/Nim/issues/14079))
- Fixed "Invalid C code with lvalue conversion"
([#14160](https://github.com/nim-lang/Nim/issues/14160))
- Fixed "strformat: doc example fails"
([#14054](https://github.com/nim-lang/Nim/issues/14054))
- Fixed "Nim doc fail to run for nim 1.2.0 (nim 1.0.4 is ok)"
([#13986](https://github.com/nim-lang/Nim/issues/13986))
- Fixed "Exception when converting csize to clong"
([#13698](https://github.com/nim-lang/Nim/issues/13698))
- Fixed "[Documentation] overloading using named arguments works but is not documented"
([#11932](https://github.com/nim-lang/Nim/issues/11932))
- Fixed "import os + use of existsDir/dirExists/existsFile/fileExists/findExe in config.nims causes "ambiguous call' error"
([#14142](https://github.com/nim-lang/Nim/issues/14142))
- Fixed "import os + use of existsDir/dirExists/existsFile/fileExists/findExe in config.nims causes "ambiguous call' error"
([#14142](https://github.com/nim-lang/Nim/issues/14142))
- Fixed "runnableExamples doc gen crashes compiler with `except Exception as e` syntax"
([#14177](https://github.com/nim-lang/Nim/issues/14177))
- Fixed "[ARC] Segfault with cyclic references (?)"
([#14159](https://github.com/nim-lang/Nim/issues/14159))
- Fixed "Semcheck regression when accessing a static parameter in proc"
([#14136](https://github.com/nim-lang/Nim/issues/14136))
- Fixed "iterator walkDir doesn't work with -d:useWinAnsi"
([#14201](https://github.com/nim-lang/Nim/issues/14201))
- Fixed "cas is wrong for tcc"
([#14151](https://github.com/nim-lang/Nim/issues/14151))
- Fixed "proc execCmdEx doesn't work with -d:useWinAnsi"
([#14203](https://github.com/nim-lang/Nim/issues/14203))
- Fixed "Use -d:nimEmulateOverflowChecks by default?"
([#14209](https://github.com/nim-lang/Nim/issues/14209))
- Fixed "Old sequences with destructor objects bug"
([#14217](https://github.com/nim-lang/Nim/issues/14217))
- Fixed "[ARC] ICE when changing the discriminant of a return value"
([#14244](https://github.com/nim-lang/Nim/issues/14244))
- Fixed "[ARC] ICE with static objects"
([#14236](https://github.com/nim-lang/Nim/issues/14236))
- Fixed "[ARC] "internal error: environment misses: a" in a finalizer"
([#14243](https://github.com/nim-lang/Nim/issues/14243))
- Fixed "[ARC] compile failure using repr with object containing `ref seq[string]`"
([#14270](https://github.com/nim-lang/Nim/issues/14270))
- Fixed "[ARC] implicit move on last use happening on non-last use"
([#14269](https://github.com/nim-lang/Nim/issues/14269))
- Fixed "[ARC] Compiler crash with a recursive non-ref object variant"
([#14294](https://github.com/nim-lang/Nim/issues/14294))
- Fixed "htmlparser.parseHtml behaves differently using --gc:arc or --gc:orc"
([#13946](https://github.com/nim-lang/Nim/issues/13946))
- Fixed "Invalid return value of openProcess is NULL rather than INVALID_HANDLE_VALUE(-1) in windows"
([#14289](https://github.com/nim-lang/Nim/issues/14289))
- Fixed "ARC codegen bug with inline iterators"
([#14219](https://github.com/nim-lang/Nim/issues/14219))
- Fixed "Building koch on OpenBSD fails unless the Nim directory is in `$PATH`"
([#13758](https://github.com/nim-lang/Nim/issues/13758))
- Fixed "[gc:arc] case object assignment SIGSEGV: destroy not called for primitive type "
([#14312](https://github.com/nim-lang/Nim/issues/14312))
- Fixed "Crash when using thread and --gc:arc "
([#13881](https://github.com/nim-lang/Nim/issues/13881))
- Fixed "Getting "Warning: Cannot prove that 'result' is initialized" for an importcpp'd proc with `var T` return type"
([#14314](https://github.com/nim-lang/Nim/issues/14314))
- Fixed "`nim cpp -r --gc:arc` segfaults on caught AssertionError"
([#13071](https://github.com/nim-lang/Nim/issues/13071))
- Fixed "tests/async/tasyncawait.nim is recently very flaky"
([#14320](https://github.com/nim-lang/Nim/issues/14320))
- Fixed "Documentation nonexistent quitprocs module"
([#14331](https://github.com/nim-lang/Nim/issues/14331))
- Fixed "SIGSEV encountered when creating threads in a loop w/ --gc:arc"
([#13935](https://github.com/nim-lang/Nim/issues/13935))
- Fixed "nim-gdb is missing from all released packages"
([#13104](https://github.com/nim-lang/Nim/issues/13104))
- Fixed "sysAssert error with gc:arc on 3 line program"
([#13862](https://github.com/nim-lang/Nim/issues/13862))
- Fixed "compiler error with inline async proc and pragma"
([#13998](https://github.com/nim-lang/Nim/issues/13998))
- Fixed "[ARC] Compiler crash when adding to a seq[ref Object]"
([#14333](https://github.com/nim-lang/Nim/issues/14333))
- Fixed "nimvm: sysFatal: unhandled exception: 'sons' is not accessible using discriminant 'kind' of type 'TNode' [FieldError]"
([#14340](https://github.com/nim-lang/Nim/issues/14340))
- Fixed "[Regression] karax events are not firing "
([#14350](https://github.com/nim-lang/Nim/issues/14350))
- Fixed "odbcsql module has some wrong integer types"
([#9771](https://github.com/nim-lang/Nim/issues/9771))
- Fixed "db_sqlite needs sqlPrepared"
([#13559](https://github.com/nim-lang/Nim/issues/13559))
- Fixed "[Regression] `createThread` is not GC-safe"
([#14370](https://github.com/nim-lang/Nim/issues/14370))
- Fixed "Broken example on hot code reloading"
([#14380](https://github.com/nim-lang/Nim/issues/14380))
- Fixed "runnableExamples block with `except` on specified error fails with `nim doc`"
([#12746](https://github.com/nim-lang/Nim/issues/12746))
- Fixed "compiler as a library: findNimStdLibCompileTime fails to find system.nim"
([#12293](https://github.com/nim-lang/Nim/issues/12293))
- Fixed "5 bugs with importcpp exceptions"
([#14369](https://github.com/nim-lang/Nim/issues/14369))
- Fixed "Docs shouldn't collapse pragmas inside runnableExamples/code blocks"
([#14174](https://github.com/nim-lang/Nim/issues/14174))
- Fixed "Bad codegen/emit for hashes.hiXorLo in some contexts."
([#14394](https://github.com/nim-lang/Nim/issues/14394))
- Fixed "Boehm GC does not scan thread-local storage"
([#14364](https://github.com/nim-lang/Nim/issues/14364))
- Fixed "RVO not exception safe"
([#14126](https://github.com/nim-lang/Nim/issues/14126))
- Fixed "runnableExamples that are only compiled"
([#10731](https://github.com/nim-lang/Nim/issues/10731))
- Fixed "`foldr` raises IndexError when called on sequence"
([#14404](https://github.com/nim-lang/Nim/issues/14404))
- Fixed "moveFile does not overwrite destination file"
([#14057](https://github.com/nim-lang/Nim/issues/14057))
- Fixed "doc2 outputs in current work dir"
([#6583](https://github.com/nim-lang/Nim/issues/6583))
- Fixed "[docgen] proc doc comments silently omitted after 1st runnableExamples"
([#9227](https://github.com/nim-lang/Nim/issues/9227))
- Fixed "`nim doc --project` shows '@@/' instead of '../' for relative paths to submodules"
([#14448](https://github.com/nim-lang/Nim/issues/14448))
- Fixed "re, nre have wrong `start` semantics"
([#14284](https://github.com/nim-lang/Nim/issues/14284))
- Fixed "runnableExamples should preserve source code doc comments, strings, and (maybe) formatting"
([#8871](https://github.com/nim-lang/Nim/issues/8871))
- Fixed "`nim doc ..` fails when runnableExamples uses `$` [devel] [regression]"
([#14485](https://github.com/nim-lang/Nim/issues/14485))
- Fixed "`items` is 20%~30% slower than iteration via an index"
([#14421](https://github.com/nim-lang/Nim/issues/14421))
- Fixed "ARC: unreliable setLen "
([#14495](https://github.com/nim-lang/Nim/issues/14495))
- Fixed "lent is unsafe: after #14447 you can modify variables with "items" loop for sequences"
([#14498](https://github.com/nim-lang/Nim/issues/14498))
- Fixed "`var op = fn()` wrongly gives warning `ObservableStores` with `object of RootObj` type"
([#14514](https://github.com/nim-lang/Nim/issues/14514))
- Fixed "Compiler assertion"
([#14562](https://github.com/nim-lang/Nim/issues/14562))
- Fixed "Can't get `ord` of a value of a Range type in the JS backend "
([#14570](https://github.com/nim-lang/Nim/issues/14570))
- Fixed "js: can't take addr of param (including implicitly via `lent`)"
([#14576](https://github.com/nim-lang/Nim/issues/14576))
- Fixed "{.noinit.} ignored in for loop -> bad codegen for non-movable types"
([#14118](https://github.com/nim-lang/Nim/issues/14118))
- Fixed "generic destructor gives: `Error: unresolved generic parameter`"
([#14315](https://github.com/nim-lang/Nim/issues/14315))
- Fixed "Memory leak with arc gc"
([#14568](https://github.com/nim-lang/Nim/issues/14568))
- Fixed "escape analysis broken with `lent`"
([#14557](https://github.com/nim-lang/Nim/issues/14557))
- Fixed "`wrapWords` seems to ignore linebreaks when wrapping, leaving breaks in the wrong place"
([#14579](https://github.com/nim-lang/Nim/issues/14579))
- Fixed "`lent` gives wrong results with -d:release"
([#14578](https://github.com/nim-lang/Nim/issues/14578))
- Fixed "Nested await expressions regression: `await a(await expandValue())` doesnt compile"
([#14279](https://github.com/nim-lang/Nim/issues/14279))
- Fixed "windows CI docs fails with strange errors"
([#14545](https://github.com/nim-lang/Nim/issues/14545))
- Fixed "[CI] tests/async/tioselectors.nim flaky test for freebsd + OSX CI"
([#13166](https://github.com/nim-lang/Nim/issues/13166))
- Fixed "seq.setLen sometimes doesn't zero memory"
([#14655](https://github.com/nim-lang/Nim/issues/14655))
- Fixed "`nim dump` is roughly 100x slower in 1.3 versus 1.2"
([#14179](https://github.com/nim-lang/Nim/issues/14179))
- Fixed "Regression: devel docgen cannot generate document for method"
([#14691](https://github.com/nim-lang/Nim/issues/14691))
- Fixed "recently flaky tests/async/t7758.nim"
([#14685](https://github.com/nim-lang/Nim/issues/14685))
- Fixed "Bind no longer working in generic procs."
([#11811](https://github.com/nim-lang/Nim/issues/11811))
- Fixed "The pegs module doesn't work with generics!"
([#14718](https://github.com/nim-lang/Nim/issues/14718))
- Fixed "Defer is not properly working for asynchronous procedures."
([#13899](https://github.com/nim-lang/Nim/issues/13899))
- Fixed "Add an ARC test with threads in a loop"
([#14690](https://github.com/nim-lang/Nim/issues/14690))
- Fixed "[goto exceptions] {.noReturn.} pragma is not detected in a case expression"
([#14458](https://github.com/nim-lang/Nim/issues/14458))
- Fixed "[exceptions:goto] C compiler error with dynlib pragma calling a proc"
([#14240](https://github.com/nim-lang/Nim/issues/14240))
- Fixed "Cannot borrow var float64 in infix assignment"
([#14440](https://github.com/nim-lang/Nim/issues/14440))
- Fixed "lib/pure/memfiles.nim: compilation error with --taintMode:on"
([#14760](https://github.com/nim-lang/Nim/issues/14760))
- Fixed "newWideCString allocates a multiple of the memory needed"
([#14750](https://github.com/nim-lang/Nim/issues/14750))
- Fixed "Nim source archive install: 'install.sh' fails with error: cp: cannot stat 'bin/nim-gdb': No such file or directory"
([#14748](https://github.com/nim-lang/Nim/issues/14748))
- Fixed "`nim cpp -r tests/exception/t9657` hangs"
([#10343](https://github.com/nim-lang/Nim/issues/10343))
- Fixed "Detect tool fails on FreeBSD"
([#14715](https://github.com/nim-lang/Nim/issues/14715))
- Fixed "compiler crash: `findUnresolvedStatic` "
([#14802](https://github.com/nim-lang/Nim/issues/14802))
- Fixed "seq namespace (?) regression"
([#4796](https://github.com/nim-lang/Nim/issues/4796))
- Fixed "Possible out of bounds string access in std/colors parseColor and isColor"
([#14839](https://github.com/nim-lang/Nim/issues/14839))
- Fixed "compile error on latest devel with orc and ssl"
([#14647](https://github.com/nim-lang/Nim/issues/14647))
- Fixed "[minor] `$` wrong for type tuple"
([#13432](https://github.com/nim-lang/Nim/issues/13432))
- Fixed "Documentation missing on devel asyncftpclient"
([#14846](https://github.com/nim-lang/Nim/issues/14846))
- Fixed "nimpretty is confused with a trailing comma in enum definition"
([#14401](https://github.com/nim-lang/Nim/issues/14401))
- Fixed "Output arguments get ignored when compiling with --app:staticlib"
([#12745](https://github.com/nim-lang/Nim/issues/12745))
- Fixed "[ARC] destructive move destroys the object too early"
([#14396](https://github.com/nim-lang/Nim/issues/14396))
- Fixed "highlite.getNextToken() crashes if the buffer string is "echo "\"""
([#14830](https://github.com/nim-lang/Nim/issues/14830))
- Fixed "Memory corruption with --gc:arc with a seq of objects with an empty body."
([#14472](https://github.com/nim-lang/Nim/issues/14472))
- Fixed "Stropped identifiers don't work as field names in tuple literals"
([#14911](https://github.com/nim-lang/Nim/issues/14911))
- Fixed "Please revert my commit"
([#14930](https://github.com/nim-lang/Nim/issues/14930))
- Fixed "[ARC] C compiler error with inline iterators and imports"
([#14864](https://github.com/nim-lang/Nim/issues/14864))
- Fixed "AsyncHttpClient segfaults with gc:orc, possibly memory corruption"
([#14402](https://github.com/nim-lang/Nim/issues/14402))
- Fixed "[ARC] Template with a block evaluating to a GC'd value results in a compiler crash"
([#14899](https://github.com/nim-lang/Nim/issues/14899))
- Fixed "[ARC] Weird issue with if expressions and templates"
([#14900](https://github.com/nim-lang/Nim/issues/14900))
- Fixed "xmlparser does not compile on devel"
([#14805](https://github.com/nim-lang/Nim/issues/14805))
- Fixed "returning lent T from a var T param gives codegen errors or SIGSEGV"
([#14878](https://github.com/nim-lang/Nim/issues/14878))
- Fixed "[ARC] Weird issue with if expressions and templates"
([#14900](https://github.com/nim-lang/Nim/issues/14900))
- Fixed "threads:on + gc:orc + unittest = C compiler errors"
([#14865](https://github.com/nim-lang/Nim/issues/14865))
- Fixed "mitems, mpairs doesn't work at compile time anymore"
([#12129](https://github.com/nim-lang/Nim/issues/12129))
- Fixed "strange result from executing code in const expression"
([#10465](https://github.com/nim-lang/Nim/issues/10465))
- Fixed "Same warning printed 3 times"
([#11009](https://github.com/nim-lang/Nim/issues/11009))
- Fixed "type alias for generic typeclass doesn't work"
([#4668](https://github.com/nim-lang/Nim/issues/4668))
- Fixed "exceptions:goto Bug devel codegen lvalue NIM_FALSE=NIM_FALSE"
([#14925](https://github.com/nim-lang/Nim/issues/14925))
- Fixed "the --useVersion:1.0 no longer works in devel"
([#14912](https://github.com/nim-lang/Nim/issues/14912))
- Fixed "template declaration of iterator doesn't compile"
([#4722](https://github.com/nim-lang/Nim/issues/4722))
- Fixed "Compiler crash on type inheritance with static generic parameter and equality check"
([#12571](https://github.com/nim-lang/Nim/issues/12571))
- Fixed "Nim crashes while handling a cast in async circumstances."
([#13815](https://github.com/nim-lang/Nim/issues/13815))
- Fixed "[ARC] Internal compiler error when calling an iterator from an inline proc "
([#14383](https://github.com/nim-lang/Nim/issues/14383))
- Fixed ""Cannot instantiate" error when template uses generic type"
([#5926](https://github.com/nim-lang/Nim/issues/5926))
- Fixed "Different raises behaviour for newTerminal between Linux and Windows"
([#12759](https://github.com/nim-lang/Nim/issues/12759))
- Fixed "Expand on a type (that defines a proc type) in error message "
([#6608](https://github.com/nim-lang/Nim/issues/6608))
- Fixed "unittest require quits program with an exit code of 0"
([#14475](https://github.com/nim-lang/Nim/issues/14475))
- Fixed "Range type: Generics vs concrete type, semcheck difference."
([#8426](https://github.com/nim-lang/Nim/issues/8426))
- Fixed "[Macro] Type mismatch when parameter name is the same as a field"
([#13253](https://github.com/nim-lang/Nim/issues/13253))
- Fixed "Generic instantiation failure when converting a sequence of circular generic types to strings"
([#10396](https://github.com/nim-lang/Nim/issues/10396))
- Fixed "initOptParser ignores argument after value option with empty value."
([#13086](https://github.com/nim-lang/Nim/issues/13086))
- Fixed "[ARC] proc with both explicit and implicit return results in a C compiler error"
([#14985](https://github.com/nim-lang/Nim/issues/14985))
- Fixed "Alias type forgets implicit generic params depending on order"
([#14990](https://github.com/nim-lang/Nim/issues/14990))
- Fixed "[ARC] sequtils.insert has different behaviour between ARC/refc"
([#14994](https://github.com/nim-lang/Nim/issues/14994))
- Fixed "The documentation for "hot code reloading" references a non-existent npm package"
([#13621](https://github.com/nim-lang/Nim/issues/13621))
- Fixed "existsDir deprecated but breaking `dir` undeclared"
([#15006](https://github.com/nim-lang/Nim/issues/15006))
- Fixed "uri.decodeUrl crashes on incorrectly formatted input"
([#14082](https://github.com/nim-lang/Nim/issues/14082))
- Fixed "testament incorrectly reports time for tests, leading to wrong conclusions"
([#14822](https://github.com/nim-lang/Nim/issues/14822))
- Fixed "Calling peekChar with Stream returned from osproc.outputStream generate runtime error"
([#14906](https://github.com/nim-lang/Nim/issues/14906))
- Fixed "localPassC pragma should come *after* other flags"
([#14194](https://github.com/nim-lang/Nim/issues/14194))
- Fixed ""Could not load" dynamic library at runtime because of hidden dependency"
([#2408](https://github.com/nim-lang/Nim/issues/2408))
- Fixed "--gc:arc generate invalid code for {.global.} (`«nimErr_» in NIM_UNLIKELY`)"
([#14480](https://github.com/nim-lang/Nim/issues/14480))
- Fixed "Using `^` from stdlib/math along with converters gives a match for types that aren't SomeNumber"
([#15033](https://github.com/nim-lang/Nim/issues/15033))
- Fixed "[ARC] Weird exception behaviour from doAssertRaises"
([#15026](https://github.com/nim-lang/Nim/issues/15026))
- Fixed "[ARC] Compiler crash declaring a finalizer proc directly in 'new'"
([#15044](https://github.com/nim-lang/Nim/issues/15044))
- Fixed "[ARC] C compiler error when creating a var of a const seq"
([#15036](https://github.com/nim-lang/Nim/issues/15036))
- Fixed "code with named arguments in proc of winim/com can not been compiled"
([#15056](https://github.com/nim-lang/Nim/issues/15056))
- Fixed "javascript backend produces javascript code with syntax error in object syntax"
([#14534](https://github.com/nim-lang/Nim/issues/14534))
- Fixed "--gc:arc should be ignored in JS mode."
([#14684](https://github.com/nim-lang/Nim/issues/14684))
- Fixed "arc: C compilation error with imported global code using a closure iterator"
([#12990](https://github.com/nim-lang/Nim/issues/12990))
- Fixed "[ARC] Crash when modifying a string with mitems iterator"
([#15052](https://github.com/nim-lang/Nim/issues/15052))
- Fixed "[ARC] SIGSEGV when calling a closure as a tuple field in a seq"
([#15038](https://github.com/nim-lang/Nim/issues/15038))
- Fixed "pass varargs[seq[T]] to iterator give empty seq "
([#12576](https://github.com/nim-lang/Nim/issues/12576))
- Fixed "Compiler crashes when using string as object variant selector with else branch"
([#14189](https://github.com/nim-lang/Nim/issues/14189))
- Fixed "JS compiler error related to implicit return and return var type"
([#11354](https://github.com/nim-lang/Nim/issues/11354))
- Fixed "`nkRecWhen` causes internalAssert in semConstructFields"
([#14698](https://github.com/nim-lang/Nim/issues/14698))
- Fixed "Memory leaks with async (closure iterators?) under ORC"
([#15076](https://github.com/nim-lang/Nim/issues/15076))
- Fixed "strutil.insertSep() fails on negative numbers"
([#11352](https://github.com/nim-lang/Nim/issues/11352))
- Fixed "Constructing a uint64 range on a 32-bit machine leads to incorrect codegen"
([#14616](https://github.com/nim-lang/Nim/issues/14616))
- Fixed "heapqueue pushpop() proc doesn't compile"
([#14139](https://github.com/nim-lang/Nim/issues/14139))
- Fixed "[ARC] SIGSEGV when trying to swap in a literal/const string"
([#15112](https://github.com/nim-lang/Nim/issues/15112))
- Fixed "Defer and --gc:arc"
([#15071](https://github.com/nim-lang/Nim/issues/15071))
- Fixed "internal error: compiler/semobjconstr.nim(324, 20) example"
([#15111](https://github.com/nim-lang/Nim/issues/15111))
- Fixed "[ARC] Sequence "disappears" with a table inside of a table with an object variant"
([#15122](https://github.com/nim-lang/Nim/issues/15122))
- Fixed "[ARC] SIGSEGV with tuple assignment caused by cursor inference"
([#15130](https://github.com/nim-lang/Nim/issues/15130))
- Fixed "Issue with --gc:arc at compile time"
([#15129](https://github.com/nim-lang/Nim/issues/15129))
- Fixed "Writing an empty string to an AsyncFile raises an IndexDefect"
([#15148](https://github.com/nim-lang/Nim/issues/15148))
- Fixed "Compiler is confused about call convention of function with nested closure"
([#5688](https://github.com/nim-lang/Nim/issues/5688))
- Fixed "Nil check on each field fails in generic function"
([#15101](https://github.com/nim-lang/Nim/issues/15101))
- Fixed "{.nimcall.} convention won't avoid the creation of closures"
([#8473](https://github.com/nim-lang/Nim/issues/8473))
- Fixed "smtp.nim(161, 40) Error: type mismatch: got <typeof(nil)> but expected 'SslContext = void'"
([#15177](https://github.com/nim-lang/Nim/issues/15177))
- Fixed "[strscans] scanf doesn't match a single character with $+ if it's the end of the string"
([#15064](https://github.com/nim-lang/Nim/issues/15064))
- Fixed "Crash and incorrect return values when using readPasswordFromStdin on Windows."
([#15207](https://github.com/nim-lang/Nim/issues/15207))
- Fixed "Possible capture error with fieldPairs and genericParams"
([#15221](https://github.com/nim-lang/Nim/issues/15221))
- Fixed "The StmtList processing of template parameters can lead to unexpected errors"
([#5691](https://github.com/nim-lang/Nim/issues/5691))
- Fixed "[ARC] C compiler error when passing a var openArray to a sink openArray"
([#15035](https://github.com/nim-lang/Nim/issues/15035))
- Fixed "Inconsistent unsigned -> signed RangeDefect usage across integer sizes"
([#15210](https://github.com/nim-lang/Nim/issues/15210))
- Fixed "toHex results in RangeDefect exception when used with large uint64"
([#15257](https://github.com/nim-lang/Nim/issues/15257))
- Fixed "Arc sink arg crash"
([#15238](https://github.com/nim-lang/Nim/issues/15238))
- Fixed "SQL escape in db_mysql is not enough"
([#15219](https://github.com/nim-lang/Nim/issues/15219))
- Fixed "Mixing 'return' with expressions is allowed in 1.2"
([#15280](https://github.com/nim-lang/Nim/issues/15280))
- Fixed "os.getFileInfo() causes ICE with --gc:arc on Windows"
([#15286](https://github.com/nim-lang/Nim/issues/15286))
- Fixed "[ARC] Sequence "disappears" with a table inside of a table with an object variant"
([#15122](https://github.com/nim-lang/Nim/issues/15122))
- Fixed "Documentation regression jsre module missing"
([#15183](https://github.com/nim-lang/Nim/issues/15183))
- Fixed "CountTable.smallest/largest() on empty table either asserts or gives bogus answer"
([#15021](https://github.com/nim-lang/Nim/issues/15021))
- Fixed "[Regression] Parser regression"
([#15305](https://github.com/nim-lang/Nim/issues/15305))
- Fixed "[ARC] SIGSEGV with tuple unpacking caused by cursor inference"
([#15147](https://github.com/nim-lang/Nim/issues/15147))
- Fixed "LwIP/FreeRTOS compile error - missing SIGPIPE and more "
([#15302](https://github.com/nim-lang/Nim/issues/15302))
- Fixed "Memory leaks with async (closure iterators?) under ORC"
([#15076](https://github.com/nim-lang/Nim/issues/15076))
- Fixed "Bug compiling with --gc:arg or --gc:orc"
([#15325](https://github.com/nim-lang/Nim/issues/15325))
- Fixed "memory corruption in tmarshall.nim"
([#9754](https://github.com/nim-lang/Nim/issues/9754))
- Fixed "typed macros break generic proc definitions"
([#15326](https://github.com/nim-lang/Nim/issues/15326))
- Fixed "nim doc2 ignores --docSeeSrcUrl parameter"
([#6071](https://github.com/nim-lang/Nim/issues/6071))
- Fixed "The decodeData Iterator from cgi module crash"
([#15369](https://github.com/nim-lang/Nim/issues/15369))
- Fixed "|| iterator generates invalid code when compiling with --debugger:native"
([#9710](https://github.com/nim-lang/Nim/issues/9710))
- Fixed "Wrong number of variables"
([#15360](https://github.com/nim-lang/Nim/issues/15360))
- Fixed "Coercions with distinct types should traverse pointer modifiers transparently."
([#7165](https://github.com/nim-lang/Nim/issues/7165))
- Fixed "Error with distinct generic TableRef"
([#6060](https://github.com/nim-lang/Nim/issues/6060))
- Fixed "Support images in nim docgen"
([#6430](https://github.com/nim-lang/Nim/issues/6430))
- Fixed "Regression. Double sem check for procs."
([#15389](https://github.com/nim-lang/Nim/issues/15389))
- Fixed "uri.nim url with literal ipv6 address is printed wrong, and cannot parsed again"
([#15333](https://github.com/nim-lang/Nim/issues/15333))
- Fixed "[ARC] Object variant gets corrupted with cursor inference"
([#15361](https://github.com/nim-lang/Nim/issues/15361))
- Fixed "`nim doc ..` compiler crash (regression 0.19.6 => 1.0)"
([#14474](https://github.com/nim-lang/Nim/issues/14474))
- Fixed "cannot borrow result; what it borrows from is potentially mutated"
([#15403](https://github.com/nim-lang/Nim/issues/15403))
- Fixed "memory corruption for seq.add(seq) with gc:arc and d:useMalloc "
([#14983](https://github.com/nim-lang/Nim/issues/14983))
- Fixed "DocGen HTML output appears improperly when encountering text immediately after/before inline monospace; in some cases won't compile"
([#11537](https://github.com/nim-lang/Nim/issues/11537))
- Fixed "Deepcopy in arc crashes"
([#15405](https://github.com/nim-lang/Nim/issues/15405))
- Fixed "pop pragma takes invalid input"
([#15430](https://github.com/nim-lang/Nim/issues/15430))
- Fixed "tests/stdlib/tgetprotobyname fails on NetBSD"
([#15452](https://github.com/nim-lang/Nim/issues/15452))
- Fixed "defer doesnt work with block, break and await"
([#15243](https://github.com/nim-lang/Nim/issues/15243))
- Fixed "tests/stdlib/tssl failing on NetBSD"
([#15493](https://github.com/nim-lang/Nim/issues/15493))
- Fixed "strictFuncs doesn't seem to catch simple ref mutation"
([#15508](https://github.com/nim-lang/Nim/issues/15508))
- Fixed "Sizeof of case object is incorrect. Showstopper"
([#15516](https://github.com/nim-lang/Nim/issues/15516))
- Fixed "[ARC] Internal error when trying to use a parallel for loop"
([#15512](https://github.com/nim-lang/Nim/issues/15512))
- Fixed "[ARC] Type-bound assign op is not being generated"
([#15510](https://github.com/nim-lang/Nim/issues/15510))
- Fixed "[ARC] Crash when adding openArray proc argument to a local seq"
([#15511](https://github.com/nim-lang/Nim/issues/15511))
- Fixed "VM: const case object gets some fields zeroed out at runtime"
([#13081](https://github.com/nim-lang/Nim/issues/13081))
- Fixed "regression(1.2.6 => devel): VM: const case object field access gives: 'sons' is not accessible"
([#15532](https://github.com/nim-lang/Nim/issues/15532))
- Fixed "Csources: huge size increase (x2.3) in 0.20"
([#12027](https://github.com/nim-lang/Nim/issues/12027))
- Fixed "Out of date error message for GC options"
([#15547](https://github.com/nim-lang/Nim/issues/15547))
- Fixed "dbQuote additional escape regression"
([#15560](https://github.com/nim-lang/Nim/issues/15560))

View File

@@ -1,33 +1,20 @@
# vx.xx.x - yyyy-mm-dd
# v1.xx.x - yyyy-mm-dd
This is an example file.
The changes should go to changelog.md!
## Changes affecting backwards compatibility
## Standard library additions and changes
- Example item: `Foo` changed to `Bar`.
### Breaking changes in the standard library
### Breaking changes in the compiler
## Library additions
- `set[T].len` is now an alias for `set[T].card` (cardinality)
## Library changes
## Language additions
- Added `example.exampleProc`.
- Changed `example.foo` to take additional `bar` parameter.
## Language changes
### Tool changes
## Compiler changes
### Compiler changes
## Tool changes
## Bugfixes

View File

@@ -2,7 +2,7 @@ REM Some debug info
echo "Running on %CI_RUNNER_ID% (%CI_RUNNER_DESCRIPTION%) with tags %CI_RUNNER_TAGS%."
gcc -v
git clone --depth 1 https://github.com/nim-lang/csources.git
git clone --depth 1 https://github.com/nim-lang/csources_v1.git csources
cd csources
call build64.bat
cd ..

View File

@@ -1,7 +1,7 @@
sh ci/deps.sh
# Build from C sources.
git clone --depth 1 https://github.com/nim-lang/csources.git
git clone --depth 1 https://github.com/nim-lang/csources_v1.git csources
cd csources
sh build.sh
cd ..

View File

@@ -25,7 +25,7 @@ Rem Build csources
koch csources -d:release || exit /b
rem Grab C sources and nimsuggest
git clone --depth 1 https://github.com/nim-lang/csources.git
git clone --depth 1 https://github.com/nim-lang/csources_v1.git csources
set PATH=%CD%\bin;%PATH%

View File

@@ -22,17 +22,17 @@ proc isPartOfAux(n: PNode, b: PType, marker: var IntSet): TAnalysisResult =
result = arNo
case n.kind
of nkRecList:
for i in 0 ..< len(n):
result = isPartOfAux(n.sons[i], b, marker)
for i in 0..<n.len:
result = isPartOfAux(n[i], b, marker)
if result == arYes: return
of nkRecCase:
assert(n.sons[0].kind == nkSym)
result = isPartOfAux(n.sons[0], b, marker)
assert(n[0].kind == nkSym)
result = isPartOfAux(n[0], b, marker)
if result == arYes: return
for i in 1 ..< len(n):
case n.sons[i].kind
for i in 1..<n.len:
case n[i].kind
of nkOfBranch, nkElse:
result = isPartOfAux(lastSon(n.sons[i]), b, marker)
result = isPartOfAux(lastSon(n[i]), b, marker)
if result == arYes: return
else: discard "isPartOfAux(record case branch)"
of nkSym:
@@ -46,14 +46,14 @@ proc isPartOfAux(a, b: PType, marker: var IntSet): TAnalysisResult =
if compareTypes(a, b, dcEqIgnoreDistinct): return arYes
case a.kind
of tyObject:
if a.sons[0] != nil:
result = isPartOfAux(a.sons[0].skipTypes(skipPtrs), b, marker)
if a[0] != nil:
result = isPartOfAux(a[0].skipTypes(skipPtrs), b, marker)
if result == arNo: result = isPartOfAux(a.n, b, marker)
of tyGenericInst, tyDistinct, tyAlias, tySink:
result = isPartOfAux(lastSon(a), b, marker)
of tyArray, tySet, tyTuple:
for i in 0 ..< len(a):
result = isPartOfAux(a.sons[i], b, marker)
for i in 0..<a.len:
result = isPartOfAux(a[i], b, marker)
if result == arYes: return
else: discard
@@ -108,7 +108,7 @@ proc isPartOf*(a, b: PNode): TAnalysisResult =
result = arMaybe
of nkBracketExpr:
result = isPartOf(a[0], b[0])
if len(a) >= 2 and len(b) >= 2:
if a.len >= 2 and b.len >= 2:
# array accesses:
if result == arYes and isDeepConstExpr(a[1]) and isDeepConstExpr(b[1]):
# we know it's the same array and we have 2 constant indexes;
@@ -181,14 +181,14 @@ proc isPartOf*(a, b: PNode): TAnalysisResult =
else: discard
of nkObjConstr:
result = arNo
for i in 1 ..< b.len:
for i in 1..<b.len:
let res = isPartOf(a, b[i][1])
if res != arNo:
result = res
if res == arYes: break
of nkCallKinds:
result = arNo
for i in 1 ..< b.len:
for i in 1..<b.len:
let res = isPartOf(a, b[i])
if res != arNo:
result = res

File diff suppressed because it is too large Load Diff

View File

@@ -24,55 +24,55 @@ proc typeToYaml*(conf: ConfigRef; n: PType, indent: int = 0, maxRecDepth: int =
proc symToYaml*(conf: ConfigRef; n: PSym, indent: int = 0, maxRecDepth: int = - 1): Rope
proc lineInfoToStr*(conf: ConfigRef; info: TLineInfo): Rope
when declared(echo):
# these are for debugging only: They are not really deprecated, but I want
# the warning so that release versions do not contain debugging statements:
proc debug*(n: PSym; conf: ConfigRef = nil) {.exportc: "debugSym", deprecated.}
proc debug*(n: PType; conf: ConfigRef = nil) {.exportc: "debugType", deprecated.}
proc debug*(n: PNode; conf: ConfigRef = nil) {.exportc: "debugNode", deprecated.}
proc typekinds*(t: PType) {.deprecated.} =
var t = t
var s = ""
while t != nil and t.len > 0:
s.add $t.kind
s.add " "
t = t.lastSon
echo s
# these are for debugging only: They are not really deprecated, but I want
# the warning so that release versions do not contain debugging statements:
proc debug*(n: PSym; conf: ConfigRef = nil) {.exportc: "debugSym", deprecated.}
proc debug*(n: PType; conf: ConfigRef = nil) {.exportc: "debugType", deprecated.}
proc debug*(n: PNode; conf: ConfigRef = nil) {.exportc: "debugNode", deprecated.}
template debug*(x: PSym|PType|PNode) {.deprecated.} =
when compiles(c.config):
debug(c.config, x)
elif compiles(c.graph.config):
debug(c.graph.config, x)
proc typekinds*(t: PType) {.deprecated.} =
var t = t
var s = ""
while t != nil and t.len > 0:
s.add $t.kind
s.add " "
t = t.lastSon
echo s
template debug*(x: PSym|PType|PNode) {.deprecated.} =
when compiles(c.config):
debug(c.config, x)
elif compiles(c.graph.config):
debug(c.graph.config, x)
else:
error()
template debug*(x: auto) {.deprecated.} =
echo x
template mdbg*: bool {.deprecated.} =
when compiles(c.graph):
c.module.fileIdx == c.graph.config.projectMainIdx
elif compiles(c.module):
c.module.fileIdx == c.config.projectMainIdx
elif compiles(c.c.module):
c.c.module.fileIdx == c.c.config.projectMainIdx
elif compiles(m.c.module):
m.c.module.fileIdx == m.c.config.projectMainIdx
elif compiles(cl.c.module):
cl.c.module.fileIdx == cl.c.config.projectMainIdx
elif compiles(p):
when compiles(p.lex):
p.lex.fileIdx == p.lex.config.projectMainIdx
else:
error()
template debug*(x: auto) {.deprecated.} =
echo x
template mdbg*: bool {.deprecated.} =
when compiles(c.graph):
c.module.fileIdx == c.graph.config.projectMainIdx
elif compiles(c.module):
c.module.fileIdx == c.config.projectMainIdx
elif compiles(c.c.module):
c.c.module.fileIdx == c.c.config.projectMainIdx
elif compiles(m.c.module):
m.c.module.fileIdx == m.c.config.projectMainIdx
elif compiles(cl.c.module):
cl.c.module.fileIdx == cl.c.config.projectMainIdx
elif compiles(p):
when compiles(p.lex):
p.lex.fileIdx == p.lex.config.projectMainIdx
else:
p.module.module.fileIdx == p.config.projectMainIdx
elif compiles(m.module.fileIdx):
m.module.fileIdx == m.config.projectMainIdx
elif compiles(L.fileIdx):
L.fileIdx == L.config.projectMainIdx
else:
error()
p.module.module.fileIdx == p.config.projectMainIdx
elif compiles(m.module.fileIdx):
m.module.fileIdx == m.config.projectMainIdx
elif compiles(L.fileIdx):
L.fileIdx == L.config.projectMainIdx
else:
error()
# --------------------------- ident tables ----------------------------------
proc idTableGet*(t: TIdTable, key: PIdObj): RootRef
@@ -110,15 +110,15 @@ proc iiTablePut*(t: var TIITable, key, val: int)
# implementation
proc skipConvAndClosure*(n: PNode): PNode =
proc skipConvCastAndClosure*(n: PNode): PNode =
result = n
while true:
case result.kind
of nkObjUpConv, nkObjDownConv, nkChckRange, nkChckRangeF, nkChckRange64,
nkClosure:
result = result.sons[0]
of nkHiddenStdConv, nkHiddenSubConv, nkConv:
result = result.sons[1]
result = result[0]
of nkHiddenStdConv, nkHiddenSubConv, nkConv, nkCast:
result = result[1]
else: break
proc sameValue*(a, b: PNode): bool =
@@ -160,17 +160,17 @@ proc lookupInRecord(n: PNode, field: PIdent): PSym =
result = nil
case n.kind
of nkRecList:
for i in 0 ..< len(n):
result = lookupInRecord(n.sons[i], field)
for i in 0..<n.len:
result = lookupInRecord(n[i], field)
if result != nil: return
of nkRecCase:
if (n.sons[0].kind != nkSym): return nil
result = lookupInRecord(n.sons[0], field)
if (n[0].kind != nkSym): return nil
result = lookupInRecord(n[0], field)
if result != nil: return
for i in 1 ..< len(n):
case n.sons[i].kind
for i in 1..<n.len:
case n[i].kind
of nkOfBranch, nkElse:
result = lookupInRecord(lastSon(n.sons[i]), field)
result = lookupInRecord(lastSon(n[i]), field)
if result != nil: return
else: return nil
of nkSym:
@@ -182,10 +182,11 @@ proc getModule*(s: PSym): PSym =
assert((result.kind == skModule) or (result.owner != result))
while result != nil and result.kind != skModule: result = result.owner
proc fromSystem*(op: PSym): bool {.inline.} = sfSystemModule in getModule(op).flags
proc getSymFromList*(list: PNode, ident: PIdent, start: int = 0): PSym =
for i in start ..< len(list):
if list.sons[i].kind == nkSym:
result = list.sons[i].sym
for i in start..<list.len:
if list[i].kind == nkSym:
result = list[i].sym
if result.name.id == ident.id: return
else: return nil
result = nil
@@ -218,14 +219,14 @@ proc sameIgnoreBacktickGensymInfo(a, b: string): bool =
proc getNamedParamFromList*(list: PNode, ident: PIdent): PSym =
## Named parameters are special because a named parameter can be
## gensym'ed and then they have '`<number>' suffix that we need to
## gensym'ed and then they have '\`<number>' suffix that we need to
## ignore, see compiler / evaltempl.nim, snippet:
##
## .. code-block:: nim
##..code-block:: nim
##
## result.add newIdentNode(getIdent(c.ic, x.name.s & "`gensym" & $x.id),
## result.add newIdentNode(getIdent(c.ic, x.name.s & "\`gensym" & $x.id),
## if c.instLines: actual.info else: templ.info)
for i in 1 ..< len(list):
for i in 1..<list.len:
let it = list[i].sym
if it.name.id == ident.id or
sameIgnoreBacktickGensymInfo(it.name.s, ident.s): return it
@@ -254,15 +255,15 @@ proc makeYamlString*(s: string): Rope =
const MaxLineLength = 64
result = nil
var res = "\""
for i in 0 ..< s.len:
for i in 0..<s.len:
if (i + 1) mod MaxLineLength == 0:
add(res, '\"')
add(res, "\n")
add(result, rope(res))
res.add('\"')
res.add("\n")
result.add(rope(res))
res = "\"" # reset
add(res, toYamlChar(s[i]))
add(res, '\"')
add(result, rope(res))
res.add(toYamlChar(s[i]))
res.add('\"')
result.add(rope(res))
proc flagsToStr[T](flags: set[T]): Rope =
if flags == {}:
@@ -270,8 +271,8 @@ proc flagsToStr[T](flags: set[T]): Rope =
else:
result = nil
for x in items(flags):
if result != nil: add(result, ", ")
add(result, makeYamlString($x))
if result != nil: result.add(", ")
result.add(makeYamlString($x))
result = "[" & result & "]"
proc lineInfoToStr(conf: ConfigRef; info: TLineInfo): Rope =
@@ -298,25 +299,25 @@ proc symToYamlAux(conf: ConfigRef; n: PSym, marker: var IntSet, indent: int,
# indent + 2, maxRecDepth - 1),
let istr = rspaces(indent + 2)
result = rope("{")
addf(result, "$N$1\"kind\": $2", [istr, makeYamlString($n.kind)])
addf(result, "$N$1\"name\": $2", [istr, makeYamlString(n.name.s)])
addf(result, "$N$1\"typ\": $2", [istr, typeToYamlAux(conf, n.typ, marker, indent + 2, maxRecDepth - 1)])
result.addf("$N$1\"kind\": $2", [istr, makeYamlString($n.kind)])
result.addf("$N$1\"name\": $2", [istr, makeYamlString(n.name.s)])
result.addf("$N$1\"typ\": $2", [istr, typeToYamlAux(conf, n.typ, marker, indent + 2, maxRecDepth - 1)])
if conf != nil:
# if we don't pass the config, we probably don't care about the line info
addf(result, "$N$1\"info\": $2", [istr, lineInfoToStr(conf, n.info)])
result.addf("$N$1\"info\": $2", [istr, lineInfoToStr(conf, n.info)])
if card(n.flags) > 0:
addf(result, "$N$1\"flags\": $2", [istr, flagsToStr(n.flags)])
addf(result, "$N$1\"magic\": $2", [istr, makeYamlString($n.magic)])
addf(result, "$N$1\"ast\": $2", [istr, ast])
addf(result, "$N$1\"options\": $2", [istr, flagsToStr(n.options)])
addf(result, "$N$1\"position\": $2", [istr, rope(n.position)])
addf(result, "$N$1\"k\": $2", [istr, makeYamlString($n.loc.k)])
addf(result, "$N$1\"storage\": $2", [istr, makeYamlString($n.loc.storage)])
result.addf("$N$1\"flags\": $2", [istr, flagsToStr(n.flags)])
result.addf("$N$1\"magic\": $2", [istr, makeYamlString($n.magic)])
result.addf("$N$1\"ast\": $2", [istr, ast])
result.addf("$N$1\"options\": $2", [istr, flagsToStr(n.options)])
result.addf("$N$1\"position\": $2", [istr, rope(n.position)])
result.addf("$N$1\"k\": $2", [istr, makeYamlString($n.loc.k)])
result.addf("$N$1\"storage\": $2", [istr, makeYamlString($n.loc.storage)])
if card(n.loc.flags) > 0:
addf(result, "$N$1\"flags\": $2", [istr, makeYamlString($n.loc.flags)])
addf(result, "$N$1\"r\": $2", [istr, n.loc.r])
addf(result, "$N$1\"lode\": $2", [istr, treeToYamlAux(conf, n.loc.lode, marker, indent + 2, maxRecDepth - 1)])
addf(result, "$N$1}", [rspaces(indent)])
result.addf("$N$1\"flags\": $2", [istr, makeYamlString($n.loc.flags)])
result.addf("$N$1\"r\": $2", [istr, n.loc.r])
result.addf("$N$1\"lode\": $2", [istr, treeToYamlAux(conf, n.loc.lode, marker, indent + 2, maxRecDepth - 1)])
result.addf("$N$1}", [rspaces(indent)])
proc typeToYamlAux(conf: ConfigRef; n: PType, marker: var IntSet, indent: int,
maxRecDepth: int): Rope =
@@ -327,27 +328,27 @@ proc typeToYamlAux(conf: ConfigRef; n: PType, marker: var IntSet, indent: int,
sonsRope = "\"$1 @$2\"" % [rope($n.kind), rope(
strutils.toHex(cast[ByteAddress](n), sizeof(n) * 2))]
else:
if len(n) > 0:
if n.len > 0:
sonsRope = rope("[")
for i in 0 ..< len(n):
if i > 0: add(sonsRope, ",")
addf(sonsRope, "$N$1$2", [rspaces(indent + 4), typeToYamlAux(conf, n.sons[i],
for i in 0..<n.len:
if i > 0: sonsRope.add(",")
sonsRope.addf("$N$1$2", [rspaces(indent + 4), typeToYamlAux(conf, n[i],
marker, indent + 4, maxRecDepth - 1)])
addf(sonsRope, "$N$1]", [rspaces(indent + 2)])
sonsRope.addf("$N$1]", [rspaces(indent + 2)])
else:
sonsRope = rope("null")
let istr = rspaces(indent + 2)
result = rope("{")
addf(result, "$N$1\"kind\": $2", [istr, makeYamlString($n.kind)])
addf(result, "$N$1\"sym\": $2", [istr, symToYamlAux(conf, n.sym, marker, indent + 2, maxRecDepth - 1)])
addf(result, "$N$1\"n\": $2", [istr, treeToYamlAux(conf, n.n, marker, indent + 2, maxRecDepth - 1)])
result.addf("$N$1\"kind\": $2", [istr, makeYamlString($n.kind)])
result.addf("$N$1\"sym\": $2", [istr, symToYamlAux(conf, n.sym, marker, indent + 2, maxRecDepth - 1)])
result.addf("$N$1\"n\": $2", [istr, treeToYamlAux(conf, n.n, marker, indent + 2, maxRecDepth - 1)])
if card(n.flags) > 0:
addf(result, "$N$1\"flags\": $2", [istr, flagsToStr(n.flags)])
addf(result, "$N$1\"callconv\": $2", [istr, makeYamlString(CallingConvToStr[n.callConv])])
addf(result, "$N$1\"size\": $2", [istr, rope(n.size)])
addf(result, "$N$1\"align\": $2", [istr, rope(n.align)])
addf(result, "$N$1\"sons\": $2", [istr, sonsRope])
result.addf("$N$1\"flags\": $2", [istr, flagsToStr(n.flags)])
result.addf("$N$1\"callconv\": $2", [istr, makeYamlString($n.callConv)])
result.addf("$N$1\"size\": $2", [istr, rope(n.size)])
result.addf("$N$1\"align\": $2", [istr, rope(n.align)])
result.addf("$N$1\"sons\": $2", [istr, sonsRope])
proc treeToYamlAux(conf: ConfigRef; n: PNode, marker: var IntSet, indent: int,
maxRecDepth: int): Rope =
@@ -358,34 +359,34 @@ proc treeToYamlAux(conf: ConfigRef; n: PNode, marker: var IntSet, indent: int,
result = "{$N$1\"kind\": $2" % [istr, makeYamlString($n.kind)]
if maxRecDepth != 0:
if conf != nil:
addf(result, ",$N$1\"info\": $2", [istr, lineInfoToStr(conf, n.info)])
result.addf(",$N$1\"info\": $2", [istr, lineInfoToStr(conf, n.info)])
case n.kind
of nkCharLit..nkInt64Lit:
addf(result, ",$N$1\"intVal\": $2", [istr, rope(n.intVal)])
result.addf(",$N$1\"intVal\": $2", [istr, rope(n.intVal)])
of nkFloatLit, nkFloat32Lit, nkFloat64Lit:
addf(result, ",$N$1\"floatVal\": $2",
result.addf(",$N$1\"floatVal\": $2",
[istr, rope(n.floatVal.toStrMaxPrecision)])
of nkStrLit..nkTripleStrLit:
addf(result, ",$N$1\"strVal\": $2", [istr, makeYamlString(n.strVal)])
result.addf(",$N$1\"strVal\": $2", [istr, makeYamlString(n.strVal)])
of nkSym:
addf(result, ",$N$1\"sym\": $2",
result.addf(",$N$1\"sym\": $2",
[istr, symToYamlAux(conf, n.sym, marker, indent + 2, maxRecDepth)])
of nkIdent:
if n.ident != nil:
addf(result, ",$N$1\"ident\": $2", [istr, makeYamlString(n.ident.s)])
result.addf(",$N$1\"ident\": $2", [istr, makeYamlString(n.ident.s)])
else:
addf(result, ",$N$1\"ident\": null", [istr])
result.addf(",$N$1\"ident\": null", [istr])
else:
if len(n) > 0:
addf(result, ",$N$1\"sons\": [", [istr])
for i in 0 ..< len(n):
if i > 0: add(result, ",")
addf(result, "$N$1$2", [rspaces(indent + 4), treeToYamlAux(conf, n.sons[i],
if n.len > 0:
result.addf(",$N$1\"sons\": [", [istr])
for i in 0..<n.len:
if i > 0: result.add(",")
result.addf("$N$1$2", [rspaces(indent + 4), treeToYamlAux(conf, n[i],
marker, indent + 4, maxRecDepth - 1)])
addf(result, "$N$1]", [istr])
addf(result, ",$N$1\"typ\": $2",
result.addf("$N$1]", [istr])
result.addf(",$N$1\"typ\": $2",
[istr, typeToYamlAux(conf, n.typ, marker, indent + 2, maxRecDepth)])
addf(result, "$N$1}", [rspaces(indent)])
result.addf("$N$1}", [rspaces(indent)])
proc treeToYaml(conf: ConfigRef; n: PNode, indent: int = 0, maxRecDepth: int = - 1): Rope =
var marker = initIntSet()
@@ -427,7 +428,7 @@ proc indentLess(this: var DebugPrinter) =
proc newlineAndIndent(this: var DebugPrinter) =
this.res.add "\n"
this.currentLine += 1
for i in 0 ..< this.indent:
for i in 0..<this.indent:
this.res.add ' '
proc openCurly(this: var DebugPrinter) =
@@ -563,12 +564,12 @@ proc value(this: var DebugPrinter; value: PType) =
this.key "n"
this.value value.n
if len(value) > 0:
if value.len > 0:
this.key "sons"
this.openBracket
for i in 0 ..< len(value):
this.value value.sons[i]
if i != len(value) - 1:
for i in 0..<value.len:
this.value value[i]
if i != value.len - 1:
this.comma
this.closeBracket
@@ -590,10 +591,17 @@ proc value(this: var DebugPrinter; value: PNode) =
if this.conf != nil:
this.key "info"
this.value $lineInfoToStr(this.conf, value.info)
if card(value.flags) > 0:
if value.flags != {}:
this.key "flags"
this.value value.flags
if value.typ != nil:
this.key "typ"
this.value value.typ.kind
else:
this.key "typ"
this.value "nil"
case value.kind
of nkCharLit..nkUInt64Lit:
this.key "intVal"
@@ -616,41 +624,41 @@ proc value(this: var DebugPrinter; value: PNode) =
if this.renderSymType and value.typ != nil:
this.key "typ"
this.value value.typ
if len(value) > 0:
if value.len > 0:
this.key "sons"
this.openBracket
for i in 0 ..< len(value):
this.value value.sons[i]
if i != len(value) - 1:
for i in 0..<value.len:
this.value value[i]
if i != value.len - 1:
this.comma
this.closeBracket
this.closeCurly
when declared(echo):
proc debug(n: PSym; conf: ConfigRef) =
var this: DebugPrinter
this.visited = initTable[pointer, int]()
this.renderSymType = true
this.useColor = not defined(windows)
this.value(n)
echo($this.res)
proc debug(n: PType; conf: ConfigRef) =
var this: DebugPrinter
this.visited = initTable[pointer, int]()
this.renderSymType = true
this.useColor = not defined(windows)
this.value(n)
echo($this.res)
proc debug(n: PSym; conf: ConfigRef) =
var this: DebugPrinter
this.visited = initTable[pointer, int]()
this.renderSymType = true
this.useColor = not defined(windows)
this.value(n)
echo($this.res)
proc debug(n: PNode; conf: ConfigRef) =
var this: DebugPrinter
this.visited = initTable[pointer, int]()
#this.renderSymType = true
this.useColor = not defined(windows)
this.value(n)
echo($this.res)
proc debug(n: PType; conf: ConfigRef) =
var this: DebugPrinter
this.visited = initTable[pointer, int]()
this.renderSymType = true
this.useColor = not defined(windows)
this.value(n)
echo($this.res)
proc debug(n: PNode; conf: ConfigRef) =
var this: DebugPrinter
this.visited = initTable[pointer, int]()
#this.renderSymType = true
this.useColor = not defined(windows)
this.value(n)
echo($this.res)
proc nextTry(h, maxHash: Hash): Hash =
result = ((5 * h) + 1) and maxHash
@@ -677,13 +685,13 @@ proc objectSetRawInsert(data: var TObjectSeq, obj: RootRef) =
proc objectSetEnlarge(t: var TObjectSet) =
var n: TObjectSeq
newSeq(n, len(t.data) * GrowthFactor)
for i in 0 .. high(t.data):
newSeq(n, t.data.len * GrowthFactor)
for i in 0..high(t.data):
if t.data[i] != nil: objectSetRawInsert(n, t.data[i])
swap(t.data, n)
proc objectSetIncl*(t: var TObjectSet, obj: RootRef) =
if mustRehash(len(t.data), t.counter): objectSetEnlarge(t)
if mustRehash(t.data.len, t.counter): objectSetEnlarge(t)
objectSetRawInsert(t.data, obj)
inc(t.counter)
@@ -696,7 +704,7 @@ proc objectSetContainsOrIncl*(t: var TObjectSet, obj: RootRef): bool =
if it == obj:
return true # found it
h = nextTry(h, high(t.data))
if mustRehash(len(t.data), t.counter):
if mustRehash(t.data.len, t.counter):
objectSetEnlarge(t)
objectSetRawInsert(t.data, obj)
else:
@@ -739,13 +747,13 @@ proc symTabReplace*(t: var TStrTable, prevSym: PSym, newSym: PSym) =
proc strTableEnlarge(t: var TStrTable) =
var n: seq[PSym]
newSeq(n, len(t.data) * GrowthFactor)
for i in 0 .. high(t.data):
newSeq(n, t.data.len * GrowthFactor)
for i in 0..high(t.data):
if t.data[i] != nil: strTableRawInsert(n, t.data[i])
swap(t.data, n)
proc strTableAdd*(t: var TStrTable, n: PSym) =
if mustRehash(len(t.data), t.counter): strTableEnlarge(t)
if mustRehash(t.data.len, t.counter): strTableEnlarge(t)
strTableRawInsert(t.data, n)
inc(t.counter)
@@ -772,7 +780,7 @@ proc strTableInclReportConflict*(t: var TStrTable, n: PSym;
if not onConflictKeepOld:
t.data[replaceSlot] = n # overwrite it with newer definition!
return t.data[replaceSlot] # found it
elif mustRehash(len(t.data), t.counter):
elif mustRehash(t.data.len, t.counter):
strTableEnlarge(t)
strTableRawInsert(t.data, n)
else:
@@ -876,7 +884,7 @@ iterator items*(tab: TStrTable): PSym =
s = nextIter(it, tab)
proc hasEmptySlot(data: TIdPairSeq): bool =
for h in 0 .. high(data):
for h in 0..high(data):
if data[h].key == nil:
return true
result = false
@@ -929,9 +937,9 @@ proc idTablePut(t: var TIdTable, key: PIdObj, val: RootRef) =
assert(t.data[index].key != nil)
t.data[index].val = val
else:
if mustRehash(len(t.data), t.counter):
newSeq(n, len(t.data) * GrowthFactor)
for i in 0 .. high(t.data):
if mustRehash(t.data.len, t.counter):
newSeq(n, t.data.len * GrowthFactor)
for i in 0..high(t.data):
if t.data[i].key != nil:
idTableRawInsert(n, t.data[i].key, t.data[i].val)
assert(hasEmptySlot(n))
@@ -940,7 +948,7 @@ proc idTablePut(t: var TIdTable, key: PIdObj, val: RootRef) =
inc(t.counter)
iterator idTablePairs*(t: TIdTable): tuple[key: PIdObj, val: RootRef] =
for i in 0 .. high(t.data):
for i in 0..high(t.data):
if not isNil(t.data[i].key): yield (t.data[i].key, t.data[i].val)
proc idNodeTableRawGet(t: TIdNodeTable, key: PIdObj): int =
@@ -974,10 +982,10 @@ proc idNodeTablePut(t: var TIdNodeTable, key: PIdObj, val: PNode) =
assert(t.data[index].key != nil)
t.data[index].val = val
else:
if mustRehash(len(t.data), t.counter):
if mustRehash(t.data.len, t.counter):
var n: TIdNodePairSeq
newSeq(n, len(t.data) * GrowthFactor)
for i in 0 .. high(t.data):
newSeq(n, t.data.len * GrowthFactor)
for i in 0..high(t.data):
if t.data[i].key != nil:
idNodeTableRawInsert(n, t.data[i].key, t.data[i].val)
swap(t.data, n)
@@ -985,13 +993,13 @@ proc idNodeTablePut(t: var TIdNodeTable, key: PIdObj, val: PNode) =
inc(t.counter)
iterator pairs*(t: TIdNodeTable): tuple[key: PIdObj, val: PNode] =
for i in 0 .. high(t.data):
for i in 0..high(t.data):
if not isNil(t.data[i].key): yield (t.data[i].key, t.data[i].val)
proc initIITable(x: var TIITable) =
x.counter = 0
newSeq(x.data, StartSize)
for i in 0 ..< StartSize: x.data[i].key = InvalidKey
for i in 0..<StartSize: x.data[i].key = InvalidKey
proc iiTableRawGet(t: TIITable, key: int): int =
var h: Hash
@@ -1022,11 +1030,11 @@ proc iiTablePut(t: var TIITable, key, val: int) =
assert(t.data[index].key != InvalidKey)
t.data[index].val = val
else:
if mustRehash(len(t.data), t.counter):
if mustRehash(t.data.len, t.counter):
var n: TIIPairSeq
newSeq(n, len(t.data) * GrowthFactor)
for i in 0 .. high(n): n[i].key = InvalidKey
for i in 0 .. high(t.data):
newSeq(n, t.data.len * GrowthFactor)
for i in 0..high(n): n[i].key = InvalidKey
for i in 0..high(t.data):
if t.data[i].key != InvalidKey:
iiTableRawInsert(n, t.data[i].key, t.data[i].val)
swap(t.data, n)
@@ -1040,3 +1048,14 @@ proc isAddrNode*(n: PNode): bool =
if n[0].kind == nkSym and n[0].sym.magic == mAddr: true
else: false
else: false
proc listSymbolNames*(symbols: openArray[PSym]): string =
for sym in symbols:
if result.len > 0:
result.add ", "
result.add sym.name.s
proc isDiscriminantField*(n: PNode): bool =
if n.kind == nkCheckedFieldExpr: sfDiscriminant in n[0][1].sym.flags
elif n.kind == nkDotExpr: sfDiscriminant in n[1].sym.flags
else: false

View File

@@ -52,25 +52,25 @@ proc bitSetInit(b: var TBitSet, length: int) =
newSeq(b, length)
proc bitSetUnion(x: var TBitSet, y: TBitSet) =
for i in 0 .. high(x): x[i] = x[i] or y[i]
for i in 0..high(x): x[i] = x[i] or y[i]
proc bitSetDiff(x: var TBitSet, y: TBitSet) =
for i in 0 .. high(x): x[i] = x[i] and not y[i]
for i in 0..high(x): x[i] = x[i] and not y[i]
proc bitSetSymDiff(x: var TBitSet, y: TBitSet) =
for i in 0 .. high(x): x[i] = x[i] xor y[i]
for i in 0..high(x): x[i] = x[i] xor y[i]
proc bitSetIntersect(x: var TBitSet, y: TBitSet) =
for i in 0 .. high(x): x[i] = x[i] and y[i]
for i in 0..high(x): x[i] = x[i] and y[i]
proc bitSetEquals(x, y: TBitSet): bool =
for i in 0 .. high(x):
for i in 0..high(x):
if x[i] != y[i]:
return false
result = true
proc bitSetContains(x, y: TBitSet): bool =
for i in 0 .. high(x):
for i in 0..high(x):
if (x[i] and not y[i]) != Zero:
return false
result = true

View File

@@ -16,7 +16,7 @@ const
Mhalf = M div 2
type
Node[Key, Val] = ref object
Node[Key, Val] {.acyclic.} = ref object
entries: int
keys: array[M, Key]
case isInternal: bool
@@ -37,34 +37,34 @@ template eq(a, b): bool = cmp(a, b) == 0
proc getOrDefault*[Key, Val](b: BTree[Key, Val], key: Key): Val =
var x = b.root
while x.isInternal:
for j in 0 ..< x.entries:
for j in 0..<x.entries:
if j+1 == x.entries or less(key, x.keys[j+1]):
x = x.links[j]
break
assert(not x.isInternal)
for j in 0 ..< x.entries:
for j in 0..<x.entries:
if eq(key, x.keys[j]): return x.vals[j]
proc contains*[Key, Val](b: BTree[Key, Val], key: Key): bool =
var x = b.root
while x.isInternal:
for j in 0 ..< x.entries:
for j in 0..<x.entries:
if j+1 == x.entries or less(key, x.keys[j+1]):
x = x.links[j]
break
assert(not x.isInternal)
for j in 0 ..< x.entries:
for j in 0..<x.entries:
if eq(key, x.keys[j]): return true
return false
proc copyHalf[Key, Val](h, result: Node[Key, Val]) =
for j in 0 ..< Mhalf:
for j in 0..<Mhalf:
result.keys[j] = h.keys[Mhalf + j]
if h.isInternal:
for j in 0 ..< Mhalf:
for j in 0..<Mhalf:
result.links[j] = h.links[Mhalf + j]
else:
for j in 0 ..< Mhalf:
for j in 0..<Mhalf:
shallowCopy(result.vals[j], h.vals[Mhalf + j])
proc split[Key, Val](h: Node[Key, Val]): Node[Key, Val] =
@@ -79,6 +79,9 @@ proc insert[Key, Val](h: Node[Key, Val], key: Key, val: Val): Node[Key, Val] =
var j = 0
if not h.isInternal:
while j < h.entries:
if eq(key, h.keys[j]):
h.vals[j] = val
return
if less(key, h.keys[j]): break
inc j
for i in countdown(h.entries, j+1):
@@ -132,8 +135,7 @@ proc `$`[Key, Val](b: BTree[Key, Val]): string =
result = ""
toString(b.root, "", result)
proc hasNext*[Key, Val](b: BTree[Key, Val]; index: int): bool =
result = index < b.entries
proc hasNext*[Key, Val](b: BTree[Key, Val]; index: int): bool = index < b.entries
proc countSubTree[Key, Val](it: Node[Key, Val]): int =
if it.isInternal:
@@ -166,68 +168,3 @@ iterator pairs*[Key, Val](b: BTree[Key, Val]): (Key, Val) =
yield (k, v)
proc len*[Key, Val](b: BTree[Key, Val]): int {.inline.} = b.entries
when isMainModule:
import random, tables
proc main =
var st = initBTree[string, string]()
st.add("www.cs.princeton.edu", "abc")
st.add("www.princeton.edu", "128.112.128.15")
st.add("www.yale.edu", "130.132.143.21")
st.add("www.simpsons.com", "209.052.165.60")
st.add("www.apple.com", "17.112.152.32")
st.add("www.amazon.com", "207.171.182.16")
st.add("www.ebay.com", "66.135.192.87")
st.add("www.cnn.com", "64.236.16.20")
st.add("www.google.com", "216.239.41.99")
st.add("www.nytimes.com", "199.239.136.200")
st.add("www.microsoft.com", "207.126.99.140")
st.add("www.dell.com", "143.166.224.230")
st.add("www.slashdot.org", "66.35.250.151")
st.add("www.espn.com", "199.181.135.201")
st.add("www.weather.com", "63.111.66.11")
st.add("www.yahoo.com", "216.109.118.65")
assert st.getOrDefault("www.cs.princeton.edu") == "abc"
assert st.getOrDefault("www.harvardsucks.com") == nil
assert st.getOrDefault("www.simpsons.com") == "209.052.165.60"
assert st.getOrDefault("www.apple.com") == "17.112.152.32"
assert st.getOrDefault("www.ebay.com") == "66.135.192.87"
assert st.getOrDefault("www.dell.com") == "143.166.224.230"
assert(st.entries == 16)
for k, v in st:
echo k, ": ", v
when false:
var b2 = initBTree[string, string]()
const iters = 10_000
for i in 1..iters:
b2.add($i, $(iters - i))
for i in 1..iters:
let x = b2.getOrDefault($i)
if x != $(iters - i):
echo "got ", x, ", but expected ", iters - i
echo b2.entries
when true:
var b2 = initBTree[int, string]()
var t2 = initTable[int, string]()
const iters = 100_000
for i in 1..iters:
let x = rand(high(int))
if not t2.hasKey(x):
doAssert b2.getOrDefault(x).len == 0, " what, tree has this element " & $x
t2[x] = $x
b2.add(x, $x)
doAssert b2.entries == t2.len
echo "unique entries ", b2.entries
for k, v in t2:
doAssert $k == v
doAssert b2.getOrDefault(k) == $k
main()

View File

@@ -102,7 +102,7 @@ proc hashTree(c: var MD5Context, n: PNode) =
of nkStrLit..nkTripleStrLit:
c &= n.strVal
else:
for i in 0..<n.len: hashTree(c, n.sons[i])
for i in 0..<n.len: hashTree(c, n[i])
proc hashType(c: var MD5Context, t: PType) =
# modelled after 'typeToString'
@@ -120,44 +120,44 @@ proc hashType(c: var MD5Context, t: PType) =
case t.kind
of tyGenericBody, tyGenericInst, tyGenericInvocation:
for i in 0 ..< len(t)-ord(t.kind != tyGenericInvocation):
c.hashType t.sons[i]
for i in 0..<t.len-ord(t.kind != tyGenericInvocation):
c.hashType t[i]
of tyUserTypeClass:
internalAssert t.sym != nil and t.sym.owner != nil
c &= t.sym.owner.name.s
of tyUserTypeClassInst:
let body = t.base
c.hashSym body.sym
for i in 1 .. len(t) - 2:
c.hashType t.sons[i]
for i in 1..<t.len-1:
c.hashType t[i]
of tyFromExpr:
c.hashTree(t.n)
of tyArray:
c.hashTree(t.sons[0].n)
c.hashType(t.sons[1])
c.hashTree(t[0].n)
c.hashType(t[1])
of tyTuple:
if t.n != nil:
assert(len(t.n) == len(t))
for i in 0 ..< len(t.n):
assert(t.n.sons[i].kind == nkSym)
c &= t.n.sons[i].sym.name.s
assert(t.n.len == t.len)
for i in 0..<t.n.len:
assert(t.n[i].kind == nkSym)
c &= t.n[i].sym.name.s
c &= ":"
c.hashType(t.sons[i])
c.hashType(t[i])
c &= ","
else:
for i in 0 ..< len(t): c.hashType t.sons[i]
for i in 0..<t.len: c.hashType t[i]
of tyRange:
c.hashTree(t.n)
c.hashType(t.sons[0])
c.hashType(t[0])
of tyProc:
c &= (if tfIterator in t.flags: "iterator " else: "proc ")
for i in 0..<t.len: c.hashType(t.sons[i])
for i in 0..<t.len: c.hashType(t[i])
md5Update(c, cast[cstring](addr(t.callConv)), 1)
if tfNoSideEffect in t.flags: c &= ".noSideEffect"
if tfThread in t.flags: c &= ".thread"
else:
for i in 0..<t.len: c.hashType(t.sons[i])
for i in 0..<t.len: c.hashType(t[i])
if tfNotNil in t.flags: c &= "not nil"
proc canonConst(n: PNode): TUid =
@@ -238,35 +238,35 @@ proc encodeNode(w: PRodWriter, fInfo: TLineInfo, n: PNode,
encodeVInt(n.sym.id, result)
pushSym(w, n.sym)
else:
for i in 0 ..< len(n):
encodeNode(w, n.info, n.sons[i], result)
add(result, ')')
for i in 0..<n.len:
encodeNode(w, n.info, n[i], result)
result.add(')')
proc encodeLoc(w: PRodWriter, loc: TLoc, result: var string) =
var oldLen = result.len
result.add('<')
if loc.k != low(loc.k): encodeVInt(ord(loc.k), result)
if loc.s != low(loc.s):
add(result, '*')
result.add('*')
encodeVInt(ord(loc.s), result)
if loc.flags != {}:
add(result, '$')
result.add('$')
encodeVInt(cast[int32](loc.flags), result)
if loc.t != nil:
add(result, '^')
result.add('^')
encodeVInt(cast[int32](loc.t.id), result)
pushType(w, loc.t)
if loc.r != nil:
add(result, '!')
result.add('!')
encodeStr($loc.r, result)
if loc.a != 0:
add(result, '?')
result.add('?')
encodeVInt(loc.a, result)
if oldLen + 1 == result.len:
# no data was necessary, so remove the '<' again:
setLen(result, oldLen)
else:
add(result, '>')
result.add('>')
proc encodeType(w: PRodWriter, t: PType, result: var string) =
if t == nil:
@@ -277,47 +277,47 @@ proc encodeType(w: PRodWriter, t: PType, result: var string) =
if t.kind == tyForward: internalError("encodeType: tyForward")
# for the new rodfile viewer we use a preceding [ so that the data section
# can easily be disambiguated:
add(result, '[')
result.add('[')
encodeVInt(ord(t.kind), result)
add(result, '+')
result.add('+')
encodeVInt(t.id, result)
if t.n != nil:
encodeNode(w, unknownLineInfo(), t.n, result)
encodeNode(w, unknownLineInfo, t.n, result)
if t.flags != {}:
add(result, '$')
result.add('$')
encodeVInt(cast[int32](t.flags), result)
if t.callConv != low(t.callConv):
add(result, '?')
result.add('?')
encodeVInt(ord(t.callConv), result)
if t.owner != nil:
add(result, '*')
result.add('*')
encodeVInt(t.owner.id, result)
pushSym(w, t.owner)
if t.sym != nil:
add(result, '&')
result.add('&')
encodeVInt(t.sym.id, result)
pushSym(w, t.sym)
if t.size != - 1:
add(result, '/')
result.add('/')
encodeVBiggestInt(t.size, result)
if t.align != - 1:
add(result, '=')
result.add('=')
encodeVInt(t.align, result)
encodeLoc(w, t.loc, result)
for i in 0 ..< len(t):
if t.sons[i] == nil:
add(result, "^()")
for i in 0..<t.len:
if t[i] == nil:
result.add("^()")
else:
add(result, '^')
encodeVInt(t.sons[i].id, result)
pushType(w, t.sons[i])
result.add('^')
encodeVInt(t[i].id, result)
pushType(w, t[i])
proc encodeLib(w: PRodWriter, lib: PLib, info: TLineInfo, result: var string) =
add(result, '|')
result.add('|')
encodeVInt(ord(lib.kind), result)
add(result, '|')
result.add('|')
encodeStr($lib.name, result)
add(result, '|')
result.add('|')
encodeNode(w, info, lib.path, result)
proc encodeSym(w: PRodWriter, s: PSym, result: var string) =
@@ -363,8 +363,8 @@ proc encodeSym(w: PRodWriter, s: PSym, result: var string) =
encodeLoc(w, s.loc, result)
if s.annex != nil: encodeLib(w, s.annex, s.info, result)
if s.constraint != nil:
add(result, '#')
encodeNode(w, unknownLineInfo(), s.constraint, result)
result.add('#')
encodeNode(w, unknownLineInfo, s.constraint, result)
# lazy loading will soon reload the ast lazily, so the ast needs to be
# the last entry of a symbol:
if s.ast != nil:

View File

@@ -9,43 +9,95 @@
#
# included from cgen.nim
proc leftAppearsOnRightSide(le, ri: PNode): bool =
proc canRaiseDisp(p: BProc; n: PNode): bool =
# we assume things like sysFatal cannot raise themselves
if n.kind == nkSym and {sfNeverRaises, sfImportc, sfCompilerProc} * n.sym.flags != {}:
result = false
elif optPanics in p.config.globalOptions or
(n.kind == nkSym and sfSystemModule in getModule(n.sym).flags):
# we know we can be strict:
result = canRaise(n)
else:
# we have to be *very* conservative:
result = canRaiseConservative(n)
proc preventNrvo(p: BProc; le, ri: PNode): bool =
proc locationEscapes(p: BProc; le: PNode; inTryStmt: bool): bool =
var n = le
while true:
# do NOT follow nkHiddenDeref here!
case n.kind
of nkSym:
# we don't own the location so it escapes:
if n.sym.owner != p.prc:
return true
elif inTryStmt and sfUsedInFinallyOrExcept in n.sym.flags:
# it is also an observable store if the location is used
# in 'except' or 'finally'
return true
return false
of nkDotExpr, nkBracketExpr, nkObjUpConv, nkObjDownConv,
nkCheckedFieldExpr:
n = n[0]
of nkHiddenStdConv, nkHiddenSubConv, nkConv:
n = n[1]
else:
# cannot analyse the location; assume the worst
return true
if le != nil:
for i in 1 ..< ri.len:
for i in 1..<ri.len:
let r = ri[i]
if isPartOf(le, r) != arNo: return true
# we use the weaker 'canRaise' here in order to prevent too many
# annoying warnings, see #14514
if canRaise(ri[0]) and
locationEscapes(p, le, p.nestedTryStmts.len > 0):
message(p.config, le.info, warnObservableStores, $le)
proc hasNoInit(call: PNode): bool {.inline.} =
result = call.sons[0].kind == nkSym and sfNoInit in call.sons[0].sym.flags
result = call[0].kind == nkSym and sfNoInit in call[0].sym.flags
proc isHarmlessStore(p: BProc; canRaise: bool; d: TLoc): bool =
if d.k in {locTemp, locNone} or not canRaise:
result = true
elif d.k == locLocalVar and p.withinTryWithExcept == 0:
# we cannot observe a store to a local variable if the current proc
# has no error handler:
result = true
else:
result = false
proc fixupCall(p: BProc, le, ri: PNode, d: var TLoc,
callee, params: Rope) =
let canRaise = p.config.exc == excGoto and canRaiseDisp(p, ri[0])
genLineDir(p, ri)
var pl = callee & ~"(" & params
# getUniqueType() is too expensive here:
var typ = skipTypes(ri.sons[0].typ, abstractInst)
if typ.sons[0] != nil:
if isInvalidReturnType(p.config, typ.sons[0]):
var typ = skipTypes(ri[0].typ, abstractInst)
if typ[0] != nil:
if isInvalidReturnType(p.config, typ[0]):
if params != nil: pl.add(~", ")
# beware of 'result = p(result)'. We may need to allocate a temporary:
if d.k in {locTemp, locNone} or not leftAppearsOnRightSide(le, ri):
if d.k in {locTemp, locNone} or not preventNrvo(p, le, ri):
# Great, we can use 'd':
if d.k == locNone: getTemp(p, typ.sons[0], d, needsInit=true)
if d.k == locNone: getTemp(p, typ[0], d, needsInit=true)
elif d.k notin {locTemp} and not hasNoInit(ri):
# reset before pass as 'result' var:
discard "resetLoc(p, d)"
add(pl, addrLoc(p.config, d))
add(pl, ~");$n")
pl.add(addrLoc(p.config, d))
pl.add(~");$n")
line(p, cpsStmts, pl)
else:
var tmp: TLoc
getTemp(p, typ.sons[0], tmp, needsInit=true)
add(pl, addrLoc(p.config, tmp))
add(pl, ~");$n")
getTemp(p, typ[0], tmp, needsInit=true)
pl.add(addrLoc(p.config, tmp))
pl.add(~");$n")
line(p, cpsStmts, pl)
genAssignment(p, d, tmp, {}) # no need for deep copying
if canRaise: raiseExit(p)
else:
add(pl, ~")")
pl.add(~")")
if p.module.compileToCpp:
if lfSingleUse in d.flags:
# do not generate spurious temporaries for C++! For C we're better off
@@ -56,29 +108,94 @@ proc fixupCall(p: BProc, le, ri: PNode, d: var TLoc,
excl d.flags, lfSingleUse
else:
if d.k == locNone and p.splitDecls == 0:
getTempCpp(p, typ.sons[0], d, pl)
getTempCpp(p, typ[0], d, pl)
else:
if d.k == locNone: getTemp(p, typ.sons[0], d)
if d.k == locNone: getTemp(p, typ[0], d)
var list: TLoc
initLoc(list, locCall, d.lode, OnUnknown)
list.r = pl
genAssignment(p, d, list, {}) # no need for deep copying
else:
if d.k == locNone: getTemp(p, typ.sons[0], d)
if canRaise: raiseExit(p)
elif isHarmlessStore(p, canRaise, d):
if d.k == locNone: getTemp(p, typ[0], d)
assert(d.t != nil) # generate an assignment to d:
var list: TLoc
initLoc(list, locCall, d.lode, OnUnknown)
list.r = pl
genAssignment(p, d, list, {}) # no need for deep copying
if canRaise: raiseExit(p)
else:
var tmp: TLoc
getTemp(p, typ[0], tmp, needsInit=true)
var list: TLoc
initLoc(list, locCall, d.lode, OnUnknown)
list.r = pl
genAssignment(p, tmp, list, {}) # no need for deep copying
if canRaise: raiseExit(p)
genAssignment(p, d, tmp, {})
else:
add(pl, ~");$n")
pl.add(~");$n")
line(p, cpsStmts, pl)
if canRaise: raiseExit(p)
proc genBoundsCheck(p: BProc; arr, a, b: TLoc)
proc openArrayLoc(p: BProc, n: PNode): Rope =
var a: TLoc
proc reifiedOpenArray(n: PNode): bool {.inline.} =
var x = n
while x.kind in {nkAddr, nkHiddenAddr, nkHiddenStdConv, nkHiddenDeref}:
x = x[0]
if x.kind == nkSym and x.sym.kind == skParam:
result = false
else:
result = true
proc genOpenArraySlice(p: BProc; q: PNode; formalType, destType: PType): (Rope, Rope) =
var a, b, c: TLoc
initLocExpr(p, q[1], a)
initLocExpr(p, q[2], b)
initLocExpr(p, q[3], c)
# but first produce the required index checks:
if optBoundsCheck in p.options:
genBoundsCheck(p, a, b, c)
let ty = skipTypes(a.t, abstractVar+{tyPtr})
let dest = getTypeDesc(p.module, destType)
let lengthExpr = "($1)-($2)+1" % [rdLoc(c), rdLoc(b)]
case ty.kind
of tyArray:
let first = toInt64(firstOrd(p.config, ty))
if first == 0:
result = ("($3*)(($1)+($2))" % [rdLoc(a), rdLoc(b), dest],
lengthExpr)
else:
result = ("($4*)($1)+(($2)-($3))" %
[rdLoc(a), rdLoc(b), intLiteral(first), dest],
lengthExpr)
of tyOpenArray, tyVarargs:
if reifiedOpenArray(q[1]):
result = ("($3*)($1.Field0)+($2)" % [rdLoc(a), rdLoc(b), dest],
lengthExpr)
else:
result = ("($3*)($1)+($2)" % [rdLoc(a), rdLoc(b), dest],
lengthExpr)
of tyUncheckedArray, tyCString:
result = ("($3*)($1)+($2)" % [rdLoc(a), rdLoc(b), dest],
lengthExpr)
of tyString, tySequence:
let atyp = skipTypes(a.t, abstractInst)
if formalType.skipTypes(abstractInst).kind in {tyVar} and atyp.kind == tyString and
optSeqDestructors in p.config.globalOptions:
linefmt(p, cpsStmts, "#nimPrepareStrMutationV2($1);$n", [byRefLoc(p, a)])
if atyp.kind in {tyVar} and not compileToCpp(p.module):
result = ("($4*)(*$1)$3+($2)" % [rdLoc(a), rdLoc(b), dataField(p), dest],
lengthExpr)
else:
result = ("($4*)$1$3+($2)" % [rdLoc(a), rdLoc(b), dataField(p), dest],
lengthExpr)
else:
internalError(p.config, "openArrayLoc: " & typeToString(a.t))
proc openArrayLoc(p: BProc, formalType: PType, n: PNode): Rope =
var q = skipConv(n)
var skipped = false
while q.kind == nkStmtListExpr and q.len > 0:
@@ -89,44 +206,29 @@ proc openArrayLoc(p: BProc, n: PNode): Rope =
if skipped:
q = skipConv(n)
while q.kind == nkStmtListExpr and q.len > 0:
for i in 0..q.len-2:
for i in 0..<q.len-1:
genStmts(p, q[i])
q = q.lastSon
var b, c: TLoc
initLocExpr(p, q[1], a)
initLocExpr(p, q[2], b)
initLocExpr(p, q[3], c)
# but first produce the required index checks:
if optBoundsCheck in p.options:
genBoundsCheck(p, a, b, c)
let ty = skipTypes(a.t, abstractVar+{tyPtr})
let dest = getTypeDesc(p.module, n.typ.sons[0])
case ty.kind
of tyArray:
let first = toInt64(firstOrd(p.config, ty))
if first == 0:
result = "($4*)(($1)+($2)), ($3)-($2)+1" % [rdLoc(a), rdLoc(b), rdLoc(c), dest]
else:
result = "($5*)($1)+(($2)-($4)), ($3)-($2)+1" %
[rdLoc(a), rdLoc(b), rdLoc(c), intLiteral(first), dest]
of tyOpenArray, tyVarargs, tyUncheckedArray, tyCString:
result = "($4*)($1)+($2), ($3)-($2)+1" % [rdLoc(a), rdLoc(b), rdLoc(c), dest]
of tyString, tySequence:
if skipTypes(n.typ, abstractInst).kind == tyVar and
not compileToCpp(p.module):
result = "($5*)(*$1)$4+($2), ($3)-($2)+1" % [rdLoc(a), rdLoc(b), rdLoc(c), dataField(p), dest]
else:
result = "($5*)$1$4+($2), ($3)-($2)+1" % [rdLoc(a), rdLoc(b), rdLoc(c), dataField(p), dest]
else:
internalError(p.config, "openArrayLoc: " & typeToString(a.t))
let (x, y) = genOpenArraySlice(p, q, formalType, n.typ[0])
result = x & ", " & y
else:
initLocExpr(p, n, a)
case skipTypes(a.t, abstractVar).kind
var a: TLoc
initLocExpr(p, if n.kind == nkHiddenStdConv: n[1] else: n, a)
case skipTypes(a.t, abstractVar+{tyStatic}).kind
of tyOpenArray, tyVarargs:
result = "$1, $1Len_0" % [rdLoc(a)]
if reifiedOpenArray(n):
if a.t.kind in {tyVar, tyLent}:
result = "$1->Field0, $1->Field1" % [rdLoc(a)]
else:
result = "$1.Field0, $1.Field1" % [rdLoc(a)]
else:
result = "$1, $1Len_0" % [rdLoc(a)]
of tyString, tySequence:
if skipTypes(n.typ, abstractInst).kind == tyVar and
not compileToCpp(p.module):
let ntyp = skipTypes(n.typ, abstractInst)
if formalType.skipTypes(abstractInst).kind in {tyVar} and ntyp.kind == tyString and
optSeqDestructors in p.config.globalOptions:
linefmt(p, cpsStmts, "#nimPrepareStrMutationV2($1);$n", [byRefLoc(p, a)])
if ntyp.kind in {tyVar} and not compileToCpp(p.module):
var t: TLoc
t.r = "(*$1)" % [a.rdLoc]
result = "(*$1)$3, $2" % [a.rdLoc, lenExpr(p, t), dataField(p)]
@@ -146,27 +248,38 @@ proc openArrayLoc(p: BProc, n: PNode): Rope =
internalError(p.config, "openArrayLoc: " & typeToString(a.t))
else: internalError(p.config, "openArrayLoc: " & typeToString(a.t))
proc genArgStringToCString(p: BProc, n: PNode): Rope {.inline.} =
var a: TLoc
initLocExpr(p, n.sons[0], a)
result = ropecg(p.module, "#nimToCStringConv($1)", [a.rdLoc])
proc withTmpIfNeeded(p: BProc, a: TLoc, needsTmp: bool): TLoc =
# Bug https://github.com/status-im/nimbus-eth2/issues/1549
# Aliasing is preferred over stack overflows.
# Also don't regress for non ARC-builds, too risky.
if needsTmp and a.lode.typ != nil and p.config.selectedGC in {gcArc, gcOrc} and
getSize(p.config, a.lode.typ) < 1024:
getTemp(p, a.lode.typ, result, needsInit=false)
genAssignment(p, result, a, {})
else:
result = a
proc genArg(p: BProc, n: PNode, param: PSym; call: PNode): Rope =
proc genArgStringToCString(p: BProc, n: PNode, needsTmp: bool): Rope {.inline.} =
var a: TLoc
initLocExpr(p, n[0], a)
ropecg(p.module, "#nimToCStringConv($1)", [withTmpIfNeeded(p, a, needsTmp).rdLoc])
proc genArg(p: BProc, n: PNode, param: PSym; call: PNode, needsTmp = false): Rope =
var a: TLoc
if n.kind == nkStringToCString:
result = genArgStringToCString(p, n)
result = genArgStringToCString(p, n, needsTmp)
elif skipTypes(param.typ, abstractVar).kind in {tyOpenArray, tyVarargs}:
var n = if n.kind != nkHiddenAddr: n else: n.sons[0]
result = openArrayLoc(p, n)
var n = if n.kind != nkHiddenAddr: n else: n[0]
result = openArrayLoc(p, param.typ, n)
elif ccgIntroducedPtr(p.config, param, call[0].typ[0]):
initLocExpr(p, n, a)
result = addrLoc(p.config, a)
elif p.module.compileToCpp and param.typ.kind == tyVar and
result = addrLoc(p.config, withTmpIfNeeded(p, a, needsTmp))
elif p.module.compileToCpp and param.typ.kind in {tyVar} and
n.kind == nkHiddenAddr:
initLocExprSingleUse(p, n.sons[0], a)
initLocExprSingleUse(p, n[0], a)
# if the proc is 'importc'ed but not 'importcpp'ed then 'var T' still
# means '*T'. See posix.nim for lots of examples that do that in the wild.
let callee = call.sons[0]
let callee = call[0]
if callee.kind == nkSym and
{sfImportc, sfInfixCall, sfCompilerProc} * callee.sym.flags == {sfImportc} and
{lfHeader, lfNoDecl} * callee.sym.loc.flags != {}:
@@ -175,26 +288,85 @@ proc genArg(p: BProc, n: PNode, param: PSym; call: PNode): Rope =
result = rdLoc(a)
else:
initLocExprSingleUse(p, n, a)
result = rdLoc(a)
result = rdLoc(withTmpIfNeeded(p, a, needsTmp))
proc genArgNoParam(p: BProc, n: PNode): Rope =
proc genArgNoParam(p: BProc, n: PNode, needsTmp = false): Rope =
var a: TLoc
if n.kind == nkStringToCString:
result = genArgStringToCString(p, n)
result = genArgStringToCString(p, n, needsTmp)
else:
initLocExprSingleUse(p, n, a)
result = rdLoc(a)
result = rdLoc(withTmpIfNeeded(p, a, needsTmp))
template genParamLoop(params) {.dirty.} =
if i < len(typ):
assert(typ.n.sons[i].kind == nkSym)
let paramType = typ.n.sons[i]
if not paramType.typ.isCompileTimeOnly:
if params != nil: add(params, ~", ")
add(params, genArg(p, ri.sons[i], paramType.sym, ri))
from dfa import instrTargets, InstrTargetKind
proc potentialAlias(n: PNode, potentialWrites: seq[PNode]): bool =
for p in potentialWrites:
if instrTargets(p, n) != None:
return true
proc skipTrivialIndirections(n: PNode): PNode =
result = n
while true:
case result.kind
of {nkDerefExpr, nkHiddenDeref, nkAddr, nkHiddenAddr, nkObjDownConv, nkObjUpConv}:
result = result[0]
of {nkHiddenStdConv, nkHiddenSubConv}:
result = result[1]
else: break
proc getPotentialWrites(n: PNode, mutate = false): seq[PNode] =
case n.kind:
of nkLiterals, nkIdent: discard
of nkSym:
if mutate: result.add n
of nkAsgn, nkFastAsgn:
result.add getPotentialWrites(n[0], true)
result.add getPotentialWrites(n[1], mutate)
of nkAddr, nkHiddenAddr:
result.add getPotentialWrites(n[0], true)
of nkCallKinds: #TODO: Find out why in f += 1, f is a nkSym and not a nkHiddenAddr
for s in n.sons:
result.add getPotentialWrites(s, true)
else:
if params != nil: add(params, ~", ")
add(params, genArgNoParam(p, ri.sons[i]))
for s in n.sons:
result.add getPotentialWrites(s, mutate)
proc getPotentialReads(n: PNode): seq[PNode] =
case n.kind:
of nkLiterals, nkIdent: discard
of nkSym: result.add n
else:
for s in n.sons:
result.add getPotentialReads(s)
proc genParams(p: BProc, ri: PNode, typ: PType): Rope =
# We must generate temporaries in cases like #14396
# to keep the strict Left-To-Right evaluation
var needTmp = newSeq[bool](ri.len - 1)
var potentialWrites: seq[PNode]
for i in countdown(ri.len - 1, 1):
if ri[i].skipTrivialIndirections.kind == nkSym:
needTmp[i - 1] = potentialAlias(ri[i], potentialWrites)
else:
for n in getPotentialReads(ri[i]):
if not needTmp[i - 1]:
needTmp[i - 1] = potentialAlias(n, potentialWrites)
potentialWrites.add getPotentialWrites(ri[i])
if ri[i].kind == nkHiddenAddr:
# Optimization: don't use a temp, if we would only take the adress anyway
needTmp[i - 1] = false
for i in 1..<ri.len:
if i < typ.len:
assert(typ.n[i].kind == nkSym)
let paramType = typ.n[i]
if not paramType.typ.isCompileTimeOnly:
if result != nil: result.add(~", ")
result.add(genArg(p, ri[i], paramType.sym, ri, needTmp[i-1]))
else:
if result != nil: result.add(~", ")
result.add(genArgNoParam(p, ri[i], needTmp[i-1]))
proc addActualSuffixForHCR(res: var Rope, module: PSym, sym: PSym) =
if sym.flags * {sfImportc, sfNonReloadable} == {} and sym.loc.k == locProc and
@@ -204,40 +376,36 @@ proc addActualSuffixForHCR(res: var Rope, module: PSym, sym: PSym) =
proc genPrefixCall(p: BProc, le, ri: PNode, d: var TLoc) =
var op: TLoc
# this is a hotspot in the compiler
initLocExpr(p, ri.sons[0], op)
var params: Rope
initLocExpr(p, ri[0], op)
# getUniqueType() is too expensive here:
var typ = skipTypes(ri.sons[0].typ, abstractInstOwned)
var typ = skipTypes(ri[0].typ, abstractInstOwned)
assert(typ.kind == tyProc)
assert(len(typ) == len(typ.n))
var length = len(ri)
for i in 1 ..< length:
genParamLoop(params)
assert(typ.len == typ.n.len)
var params = genParams(p, ri, typ)
var callee = rdLoc(op)
if p.hcrOn and ri.sons[0].kind == nkSym:
callee.addActualSuffixForHCR(p.module.module, ri.sons[0].sym)
if p.hcrOn and ri[0].kind == nkSym:
callee.addActualSuffixForHCR(p.module.module, ri[0].sym)
fixupCall(p, le, ri, d, callee, params)
proc genClosureCall(p: BProc, le, ri: PNode, d: var TLoc) =
proc getRawProcType(p: BProc, t: PType): Rope =
result = getClosureType(p.module, t, clHalf)
proc addComma(r: Rope): Rope =
result = if r == nil: r else: r & ~", "
if r == nil: r else: r & ~", "
const PatProc = "$1.ClE_0? $1.ClP_0($3$1.ClE_0):(($4)($1.ClP_0))($2)"
const PatIter = "$1.ClP_0($3$1.ClE_0)" # we know the env exists
var op: TLoc
initLocExpr(p, ri.sons[0], op)
var pl: Rope
var typ = skipTypes(ri.sons[0].typ, abstractInst)
var op: TLoc
initLocExpr(p, ri[0], op)
# getUniqueType() is too expensive here:
var typ = skipTypes(ri[0].typ, abstractInstOwned)
assert(typ.kind == tyProc)
var length = len(ri)
for i in 1 ..< length:
assert(len(typ) == len(typ.n))
genParamLoop(pl)
assert(typ.len == typ.n.len)
var pl = genParams(p, ri, typ)
template genCallPattern {.dirty.} =
if tfIterator in typ.flags:
@@ -245,28 +413,30 @@ proc genClosureCall(p: BProc, le, ri: PNode, d: var TLoc) =
else:
lineF(p, cpsStmts, PatProc & ";$n", [rdLoc(op), pl, pl.addComma, rawProc])
let rawProc = getRawProcType(p, typ)
if typ.sons[0] != nil:
if isInvalidReturnType(p.config, typ.sons[0]):
if len(ri) > 1: add(pl, ~", ")
let rawProc = getClosureType(p.module, typ, clHalf)
let canRaise = p.config.exc == excGoto and canRaiseDisp(p, ri[0])
if typ[0] != nil:
if isInvalidReturnType(p.config, typ[0]):
if ri.len > 1: pl.add(~", ")
# beware of 'result = p(result)'. We may need to allocate a temporary:
if d.k in {locTemp, locNone} or not leftAppearsOnRightSide(le, ri):
if d.k in {locTemp, locNone} or not preventNrvo(p, le, ri):
# Great, we can use 'd':
if d.k == locNone:
getTemp(p, typ.sons[0], d, needsInit=true)
getTemp(p, typ[0], d, needsInit=true)
elif d.k notin {locTemp} and not hasNoInit(ri):
# reset before pass as 'result' var:
discard "resetLoc(p, d)"
add(pl, addrLoc(p.config, d))
pl.add(addrLoc(p.config, d))
genCallPattern()
else:
var tmp: TLoc
getTemp(p, typ.sons[0], tmp, needsInit=true)
add(pl, addrLoc(p.config, tmp))
getTemp(p, typ[0], tmp, needsInit=true)
pl.add(addrLoc(p.config, tmp))
genCallPattern()
if canRaise: raiseExit(p)
genAssignment(p, d, tmp, {}) # no need for deep copying
else:
if d.k == locNone: getTemp(p, typ.sons[0], d)
elif isHarmlessStore(p, canRaise, d):
if d.k == locNone: getTemp(p, typ[0], d)
assert(d.t != nil) # generate an assignment to d:
var list: TLoc
initLoc(list, locCall, d.lode, OnUnknown)
@@ -274,29 +444,43 @@ proc genClosureCall(p: BProc, le, ri: PNode, d: var TLoc) =
list.r = PatIter % [rdLoc(op), pl, pl.addComma, rawProc]
else:
list.r = PatProc % [rdLoc(op), pl, pl.addComma, rawProc]
genAssignment(p, d, list, {}) # no need for deep copying
if canRaise: raiseExit(p)
else:
var tmp: TLoc
getTemp(p, typ[0], tmp)
assert(d.t != nil) # generate an assignment to d:
var list: TLoc
initLoc(list, locCall, d.lode, OnUnknown)
if tfIterator in typ.flags:
list.r = PatIter % [rdLoc(op), pl, pl.addComma, rawProc]
else:
list.r = PatProc % [rdLoc(op), pl, pl.addComma, rawProc]
genAssignment(p, tmp, list, {})
if canRaise: raiseExit(p)
genAssignment(p, d, tmp, {})
else:
genCallPattern()
if canRaise: raiseExit(p)
proc genOtherArg(p: BProc; ri: PNode; i: int; typ: PType): Rope =
if i < len(typ):
if i < typ.len:
# 'var T' is 'T&' in C++. This means we ignore the request of
# any nkHiddenAddr when it's a 'var T'.
let paramType = typ.n.sons[i]
let paramType = typ.n[i]
assert(paramType.kind == nkSym)
if paramType.typ.isCompileTimeOnly:
result = nil
elif typ.sons[i].kind == tyVar and ri.sons[i].kind == nkHiddenAddr:
result = genArgNoParam(p, ri.sons[i][0])
elif typ[i].kind in {tyVar} and ri[i].kind == nkHiddenAddr:
result = genArgNoParam(p, ri[i][0])
else:
result = genArgNoParam(p, ri.sons[i]) #, typ.n.sons[i].sym)
result = genArgNoParam(p, ri[i]) #, typ.n[i].sym)
else:
if tfVarargs notin typ.flags:
localError(p.config, ri.info, "wrong argument count")
result = nil
else:
result = genArgNoParam(p, ri.sons[i])
result = genArgNoParam(p, ri[i])
discard """
Dot call syntax in C++
@@ -340,16 +524,16 @@ proc skipAddrDeref(node: PNode): PNode =
var isAddr = false
case n.kind
of nkAddr, nkHiddenAddr:
n = n.sons[0]
n = n[0]
isAddr = true
of nkDerefExpr, nkHiddenDeref:
n = n.sons[0]
n = n[0]
else: return n
if n.kind == nkObjDownConv: n = n.sons[0]
if n.kind == nkObjDownConv: n = n[0]
if isAddr and n.kind in {nkDerefExpr, nkHiddenDeref}:
result = n.sons[0]
result = n[0]
elif n.kind in {nkAddr, nkHiddenAddr}:
result = n.sons[0]
result = n[0]
else:
result = node
@@ -357,14 +541,14 @@ proc genThisArg(p: BProc; ri: PNode; i: int; typ: PType): Rope =
# for better or worse c2nim translates the 'this' argument to a 'var T'.
# However manual wrappers may also use 'ptr T'. In any case we support both
# for convenience.
internalAssert p.config, i < len(typ)
assert(typ.n.sons[i].kind == nkSym)
internalAssert p.config, i < typ.len
assert(typ.n[i].kind == nkSym)
# if the parameter is lying (tyVar) and thus we required an additional deref,
# skip the deref:
var ri = ri[i]
while ri.kind == nkObjDownConv: ri = ri[0]
let t = typ.sons[i].skipTypes({tyGenericInst, tyAlias, tySink})
if t.kind == tyVar:
let t = typ[i].skipTypes({tyGenericInst, tyAlias, tySink})
if t.kind in {tyVar}:
let x = if ri.kind == nkHiddenAddr: ri[0] else: ri
if x.typ.kind == tyPtr:
result = genArgNoParam(p, x)
@@ -385,7 +569,7 @@ proc genThisArg(p: BProc; ri: PNode; i: int; typ: PType): Rope =
else:
ri = skipAddrDeref(ri)
if ri.kind in {nkAddr, nkHiddenAddr}: ri = ri[0]
result = genArgNoParam(p, ri) #, typ.n.sons[i].sym)
result = genArgNoParam(p, ri) #, typ.n[i].sym)
result.add(".")
proc genPatternCall(p: BProc; ri: PNode; pat: string; typ: PType): Rope =
@@ -395,7 +579,7 @@ proc genPatternCall(p: BProc; ri: PNode; pat: string; typ: PType): Rope =
case pat[i]
of '@':
var first = true
for k in j ..< ri.len:
for k in j..<ri.len:
let arg = genOtherArg(p, ri, k, typ)
if arg.len > 0:
if not first:
@@ -407,12 +591,12 @@ proc genPatternCall(p: BProc; ri: PNode; pat: string; typ: PType): Rope =
if i+1 < pat.len and pat[i+1] in {'+', '@'}:
let ri = ri[j]
if ri.kind in nkCallKinds:
let typ = skipTypes(ri.sons[0].typ, abstractInst)
if pat[i+1] == '+': result.add genArgNoParam(p, ri.sons[0])
let typ = skipTypes(ri[0].typ, abstractInst)
if pat[i+1] == '+': result.add genArgNoParam(p, ri[0])
result.add(~"(")
if 1 < ri.len:
result.add genOtherArg(p, ri, 1, typ)
for k in j+1 ..< ri.len:
for k in j+1..<ri.len:
result.add(~", ")
result.add genOtherArg(p, ri, k, typ)
result.add(~")")
@@ -423,7 +607,7 @@ proc genPatternCall(p: BProc; ri: PNode; pat: string; typ: PType): Rope =
result.add genThisArg(p, ri, j, typ)
inc i
elif i+1 < pat.len and pat[i+1] == '[':
var arg = ri.sons[j].skipAddrDeref
var arg = ri[j].skipAddrDeref
while arg.kind in {nkAddr, nkHiddenAddr, nkObjDownConv}: arg = arg[0]
result.add genArgNoParam(p, arg)
#result.add debugTree(arg, 0, 10)
@@ -443,24 +627,23 @@ proc genPatternCall(p: BProc; ri: PNode; pat: string; typ: PType): Rope =
if pat[i] notin {'@', '#', '\''}: inc(i)
else: break
if i - 1 >= start:
add(result, substr(pat, start, i - 1))
result.add(substr(pat, start, i - 1))
proc genInfixCall(p: BProc, le, ri: PNode, d: var TLoc) =
var op: TLoc
initLocExpr(p, ri.sons[0], op)
initLocExpr(p, ri[0], op)
# getUniqueType() is too expensive here:
var typ = skipTypes(ri.sons[0].typ, abstractInst)
var typ = skipTypes(ri[0].typ, abstractInst)
assert(typ.kind == tyProc)
var length = len(ri)
assert(len(typ) == len(typ.n))
assert(typ.len == typ.n.len)
# don't call '$' here for efficiency:
let pat = ri.sons[0].sym.loc.r.data
let pat = ri[0].sym.loc.r.data
internalAssert p.config, pat.len > 0
if pat.contains({'#', '(', '@', '\''}):
var pl = genPatternCall(p, ri, pat, typ)
# simpler version of 'fixupCall' that works with the pl+params combination:
var typ = skipTypes(ri.sons[0].typ, abstractInst)
if typ.sons[0] != nil:
var typ = skipTypes(ri[0].typ, abstractInst)
if typ[0] != nil:
if p.module.compileToCpp and lfSingleUse in d.flags:
# do not generate spurious temporaries for C++! For C we're better off
# with them to prevent undefined behaviour and because the codegen
@@ -469,116 +652,132 @@ proc genInfixCall(p: BProc, le, ri: PNode, d: var TLoc) =
d.r = pl
excl d.flags, lfSingleUse
else:
if d.k == locNone: getTemp(p, typ.sons[0], d)
if d.k == locNone: getTemp(p, typ[0], d)
assert(d.t != nil) # generate an assignment to d:
var list: TLoc
initLoc(list, locCall, d.lode, OnUnknown)
list.r = pl
genAssignment(p, d, list, {}) # no need for deep copying
else:
add(pl, ~";$n")
pl.add(~";$n")
line(p, cpsStmts, pl)
else:
var pl: Rope = nil
#var param = typ.n.sons[1].sym
#var param = typ.n[1].sym
if 1 < ri.len:
add(pl, genThisArg(p, ri, 1, typ))
add(pl, op.r)
pl.add(genThisArg(p, ri, 1, typ))
pl.add(op.r)
var params: Rope
for i in 2 ..< length:
for i in 2..<ri.len:
if params != nil: params.add(~", ")
assert(len(typ) == len(typ.n))
add(params, genOtherArg(p, ri, i, typ))
assert(typ.len == typ.n.len)
params.add(genOtherArg(p, ri, i, typ))
fixupCall(p, le, ri, d, pl, params)
proc genNamedParamCall(p: BProc, ri: PNode, d: var TLoc) =
# generates a crappy ObjC call
var op: TLoc
initLocExpr(p, ri.sons[0], op)
initLocExpr(p, ri[0], op)
var pl = ~"["
# getUniqueType() is too expensive here:
var typ = skipTypes(ri.sons[0].typ, abstractInst)
var typ = skipTypes(ri[0].typ, abstractInst)
assert(typ.kind == tyProc)
var length = len(ri)
assert(len(typ) == len(typ.n))
assert(typ.len == typ.n.len)
# don't call '$' here for efficiency:
let pat = ri.sons[0].sym.loc.r.data
let pat = ri[0].sym.loc.r.data
internalAssert p.config, pat.len > 0
var start = 3
if ' ' in pat:
start = 1
add(pl, op.r)
if length > 1:
add(pl, ~": ")
add(pl, genArg(p, ri.sons[1], typ.n.sons[1].sym, ri))
pl.add(op.r)
if ri.len > 1:
pl.add(~": ")
pl.add(genArg(p, ri[1], typ.n[1].sym, ri))
start = 2
else:
if length > 1:
add(pl, genArg(p, ri.sons[1], typ.n.sons[1].sym, ri))
add(pl, ~" ")
add(pl, op.r)
if length > 2:
add(pl, ~": ")
add(pl, genArg(p, ri.sons[2], typ.n.sons[2].sym, ri))
for i in start ..< length:
assert(len(typ) == len(typ.n))
if i >= len(typ):
if ri.len > 1:
pl.add(genArg(p, ri[1], typ.n[1].sym, ri))
pl.add(~" ")
pl.add(op.r)
if ri.len > 2:
pl.add(~": ")
pl.add(genArg(p, ri[2], typ.n[2].sym, ri))
for i in start..<ri.len:
assert(typ.len == typ.n.len)
if i >= typ.len:
internalError(p.config, ri.info, "varargs for objective C method?")
assert(typ.n.sons[i].kind == nkSym)
var param = typ.n.sons[i].sym
add(pl, ~" ")
add(pl, param.name.s)
add(pl, ~": ")
add(pl, genArg(p, ri.sons[i], param, ri))
if typ.sons[0] != nil:
if isInvalidReturnType(p.config, typ.sons[0]):
if len(ri) > 1: add(pl, ~" ")
assert(typ.n[i].kind == nkSym)
var param = typ.n[i].sym
pl.add(~" ")
pl.add(param.name.s)
pl.add(~": ")
pl.add(genArg(p, ri[i], param, ri))
if typ[0] != nil:
if isInvalidReturnType(p.config, typ[0]):
if ri.len > 1: pl.add(~" ")
# beware of 'result = p(result)'. We always allocate a temporary:
if d.k in {locTemp, locNone}:
# We already got a temp. Great, special case it:
if d.k == locNone: getTemp(p, typ.sons[0], d, needsInit=true)
add(pl, ~"Result: ")
add(pl, addrLoc(p.config, d))
add(pl, ~"];$n")
if d.k == locNone: getTemp(p, typ[0], d, needsInit=true)
pl.add(~"Result: ")
pl.add(addrLoc(p.config, d))
pl.add(~"];$n")
line(p, cpsStmts, pl)
else:
var tmp: TLoc
getTemp(p, typ.sons[0], tmp, needsInit=true)
add(pl, addrLoc(p.config, tmp))
add(pl, ~"];$n")
getTemp(p, typ[0], tmp, needsInit=true)
pl.add(addrLoc(p.config, tmp))
pl.add(~"];$n")
line(p, cpsStmts, pl)
genAssignment(p, d, tmp, {}) # no need for deep copying
else:
add(pl, ~"]")
if d.k == locNone: getTemp(p, typ.sons[0], d)
pl.add(~"]")
if d.k == locNone: getTemp(p, typ[0], d)
assert(d.t != nil) # generate an assignment to d:
var list: TLoc
initLoc(list, locCall, ri, OnUnknown)
list.r = pl
genAssignment(p, d, list, {}) # no need for deep copying
else:
add(pl, ~"];$n")
pl.add(~"];$n")
line(p, cpsStmts, pl)
proc genCall(p: BProc, e: PNode, d: var TLoc) =
if e.sons[0].typ.skipTypes({tyGenericInst, tyAlias, tySink, tyOwned}).callConv == ccClosure:
genClosureCall(p, nil, e, d)
elif e.sons[0].kind == nkSym and sfInfixCall in e.sons[0].sym.flags:
genInfixCall(p, nil, e, d)
elif e.sons[0].kind == nkSym and sfNamedParamCall in e.sons[0].sym.flags:
genNamedParamCall(p, e, d)
else:
genPrefixCall(p, nil, e, d)
postStmtActions(p)
proc notYetAlive(n: PNode): bool {.inline.} =
let r = getRoot(n)
result = r != nil and r.loc.lode == nil
proc isInactiveDestructorCall(p: BProc, e: PNode): bool =
#[ Consider this example.
var :tmpD_3281815
try:
if true:
return
let args_3280013 =
wasMoved_3281816(:tmpD_3281815)
`=_3280036`(:tmpD_3281815, [1])
:tmpD_3281815
finally:
`=destroy_3280027`(args_3280013)
We want to return early but the 'finally' section is traversed before
the 'let args = ...' statement. We exploit this to generate better
code for 'return'. ]#
result = e.len == 2 and e[0].kind == nkSym and
e[0].sym.name.s == "=destroy" and notYetAlive(e[1].skipAddr)
proc genAsgnCall(p: BProc, le, ri: PNode, d: var TLoc) =
if ri.sons[0].typ.skipTypes({tyGenericInst, tyAlias, tySink, tyOwned}).callConv == ccClosure:
if p.withinBlockLeaveActions > 0 and isInactiveDestructorCall(p, ri):
return
if ri[0].typ.skipTypes({tyGenericInst, tyAlias, tySink, tyOwned}).callConv == ccClosure:
genClosureCall(p, le, ri, d)
elif ri.sons[0].kind == nkSym and sfInfixCall in ri.sons[0].sym.flags:
elif ri[0].kind == nkSym and sfInfixCall in ri[0].sym.flags:
genInfixCall(p, le, ri, d)
elif ri.sons[0].kind == nkSym and sfNamedParamCall in ri.sons[0].sym.flags:
elif ri[0].kind == nkSym and sfNamedParamCall in ri[0].sym.flags:
genNamedParamCall(p, ri, d)
else:
genPrefixCall(p, le, ri, d)
postStmtActions(p)
proc genCall(p: BProc, e: PNode, d: var TLoc) = genAsgnCall(p, nil, e, d)

File diff suppressed because it is too large Load Diff

View File

@@ -35,8 +35,8 @@ proc detectSeqVersion(m: BModule): int =
proc genStringLiteralDataOnlyV1(m: BModule, s: string): Rope =
discard cgsym(m, "TGenericSeq")
result = getTempName(m)
addf(m.s[cfsData], "STRING_LITERAL($1, $2, $3);$n",
[result, makeCString(s), rope(len(s))])
m.s[cfsData].addf("STRING_LITERAL($1, $2, $3);$n",
[result, makeCString(s), rope(s.len)])
proc genStringLiteralV1(m: BModule; n: PNode): Rope =
if s.isNil:
@@ -53,29 +53,31 @@ proc genStringLiteralV1(m: BModule; n: PNode): Rope =
# ------ Version 2: destructor based strings and seqs -----------------------
proc genStringLiteralDataOnlyV2(m: BModule, s: string; result: Rope) =
addf(m.s[cfsData], "static const struct {$n" &
" NI cap; void* allocator; NIM_CHAR data[$2+1];$n" &
"} $1 = { $2, NIM_NIL, $3 };$n",
[result, rope(len(s)), makeCString(s)])
proc genStringLiteralDataOnlyV2(m: BModule, s: string; result: Rope; isConst: bool) =
m.s[cfsData].addf("static $4 struct {$n" &
" NI cap; NIM_CHAR data[$2+1];$n" &
"} $1 = { $2 | NIM_STRLIT_FLAG, $3 };$n",
[result, rope(s.len), makeCString(s),
rope(if isConst: "const" else: "")])
proc genStringLiteralV2(m: BModule; n: PNode): Rope =
proc genStringLiteralV2(m: BModule; n: PNode; isConst: bool): Rope =
let id = nodeTableTestOrSet(m.dataCache, n, m.labels)
if id == m.labels:
let pureLit = getTempName(m)
genStringLiteralDataOnlyV2(m, n.strVal, pureLit)
genStringLiteralDataOnlyV2(m, n.strVal, pureLit, isConst)
result = getTempName(m)
discard cgsym(m, "NimStrPayload")
discard cgsym(m, "NimStringV2")
# string literal not found in the cache:
addf(m.s[cfsData], "static const NimStringV2 $1 = {$2, (NimStrPayload*)&$3};$n",
[result, rope(len(n.strVal)), pureLit])
m.s[cfsData].addf("static $4 NimStringV2 $1 = {$2, (NimStrPayload*)&$3};$n",
[result, rope(n.strVal.len), pureLit, rope(if isConst: "const" else: "")])
else:
result = getTempName(m)
addf(m.s[cfsData], "static const NimStringV2 $1 = {$2, (NimStrPayload*)&$3};$n",
[result, rope(len(n.strVal)), m.tmpBase & rope(id)])
m.s[cfsData].addf("static $4 NimStringV2 $1 = {$2, (NimStrPayload*)&$3};$n",
[result, rope(n.strVal.len), m.tmpBase & rope(id),
rope(if isConst: "const" else: "")])
proc genStringLiteralV2Const(m: BModule; n: PNode): Rope =
proc genStringLiteralV2Const(m: BModule; n: PNode; isConst: bool): Rope =
let id = nodeTableTestOrSet(m.dataCache, n, m.labels)
var pureLit: Rope
if id == m.labels:
@@ -83,19 +85,20 @@ proc genStringLiteralV2Const(m: BModule; n: PNode): Rope =
discard cgsym(m, "NimStrPayload")
discard cgsym(m, "NimStringV2")
# string literal not found in the cache:
genStringLiteralDataOnlyV2(m, n.strVal, pureLit)
genStringLiteralDataOnlyV2(m, n.strVal, pureLit, isConst)
else:
pureLit = m.tmpBase & rope(id)
result = "{$1, (NimStrPayload*)&$2}" % [rope(len(n.strVal)), pureLit]
result = "{$1, (NimStrPayload*)&$2}" % [rope(n.strVal.len), pureLit]
# ------ Version selector ---------------------------------------------------
proc genStringLiteralDataOnly(m: BModule; s: string; info: TLineInfo): Rope =
proc genStringLiteralDataOnly(m: BModule; s: string; info: TLineInfo;
isConst: bool): Rope =
case detectStrVersion(m)
of 0, 1: result = genStringLiteralDataOnlyV1(m, s)
of 2:
result = getTempName(m)
genStringLiteralDataOnlyV2(m, s, result)
genStringLiteralDataOnlyV2(m, s, result, isConst)
else:
localError(m.config, info, "cannot determine how to produce code for string literal")
@@ -105,6 +108,6 @@ proc genNilStringLiteral(m: BModule; info: TLineInfo): Rope =
proc genStringLiteral(m: BModule; n: PNode): Rope =
case detectStrVersion(m)
of 0, 1: result = genStringLiteralV1(m, n)
of 2: result = genStringLiteralV2(m, n)
of 2: result = genStringLiteralV2(m, n, isConst = true)
else:
localError(m.config, n.info, "cannot determine how to produce code for string literal")

View File

@@ -28,8 +28,8 @@ const
cfsFieldInfo: "NIM_merge_FIELD_INFO",
cfsTypeInfo: "NIM_merge_TYPE_INFO",
cfsProcHeaders: "NIM_merge_PROC_HEADERS",
cfsVars: "NIM_merge_VARS",
cfsData: "NIM_merge_DATA",
cfsVars: "NIM_merge_VARS",
cfsProcs: "NIM_merge_PROCS",
cfsInitProc: "NIM_merge_INIT_PROC",
cfsDatInitProc: "NIM_merge_DATINIT_PROC",
@@ -48,11 +48,15 @@ const
NimMergeEndMark = "/*\tNIM_merge_END:*/"
proc genSectionStart*(fs: TCFileSection; conf: ConfigRef): Rope =
# useful for debugging and only adds at most a few lines in each file
result.add("\n/* section: ")
result.add(CFileSectionNames[fs])
result.add(" */\n")
if compilationCachePresent(conf):
result = nil
add(result, "\n/*\t")
add(result, CFileSectionNames[fs])
add(result, ":*/\n")
result.add("\n/*\t")
result.add(CFileSectionNames[fs])
result.add(":*/\n")
proc genSectionEnd*(fs: TCFileSection; conf: ConfigRef): Rope =
if compilationCachePresent(conf):
@@ -61,9 +65,9 @@ proc genSectionEnd*(fs: TCFileSection; conf: ConfigRef): Rope =
proc genSectionStart*(ps: TCProcSection; conf: ConfigRef): Rope =
if compilationCachePresent(conf):
result = rope("")
add(result, "\n/*\t")
add(result, CProcSectionNames[ps])
add(result, ":*/\n")
result.add("\n/*\t")
result.add(CProcSectionNames[ps])
result.add(":*/\n")
proc genSectionEnd*(ps: TCProcSection; conf: ConfigRef): Rope =
if compilationCachePresent(conf):
@@ -278,7 +282,7 @@ proc mergeRequired*(m: BModule): bool =
if m.s[i] != nil:
#echo "not empty: ", i, " ", m.s[i]
return true
for i in low(TCProcSection)..high(TCProcSection):
for i in TCProcSection:
if m.initProc.s(i) != nil:
#echo "not empty: ", i, " ", m.initProc.s[i]
return true
@@ -288,7 +292,7 @@ proc mergeFiles*(cfilename: AbsoluteFile, m: BModule) =
var old: TMergeSections
readMergeSections(cfilename, old)
# do the merge; old section before new section:
for i in low(TCFileSection)..high(TCFileSection):
for i in TCFileSection:
m.s[i] = old.f[i] & m.s[i]
for i in low(TCProcSection)..high(TCProcSection):
for i in TCProcSection:
m.initProc.s(i) = old.p[i] & m.initProc.s(i)

94
compiler/ccgreset.nim Normal file
View File

@@ -0,0 +1,94 @@
#
#
# The Nim Compiler
# (c) Copyright 2020 Andreas Rumpf
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
# included from cgen.nim
## Code specialization instead of the old, incredibly slow 'genericReset'
## implementation.
proc specializeResetT(p: BProc, accessor: Rope, typ: PType)
proc specializeResetN(p: BProc, accessor: Rope, n: PNode;
typ: PType) =
if n == nil: return
case n.kind
of nkRecList:
for i in 0..<n.len:
specializeResetN(p, accessor, n[i], typ)
of nkRecCase:
if (n[0].kind != nkSym): internalError(p.config, n.info, "specializeResetN")
let disc = n[0].sym
if disc.loc.r == nil: fillObjectFields(p.module, typ)
if disc.loc.t == nil:
internalError(p.config, n.info, "specializeResetN()")
lineF(p, cpsStmts, "switch ($1.$2) {$n", [accessor, disc.loc.r])
for i in 1..<n.len:
let branch = n[i]
assert branch.kind in {nkOfBranch, nkElse}
if branch.kind == nkOfBranch:
genCaseRange(p, branch)
else:
lineF(p, cpsStmts, "default:$n", [])
specializeResetN(p, accessor, lastSon(branch), typ)
lineF(p, cpsStmts, "break;$n", [])
lineF(p, cpsStmts, "} $n", [])
specializeResetT(p, "$1.$2" % [accessor, disc.loc.r], disc.loc.t)
of nkSym:
let field = n.sym
if field.typ.kind == tyVoid: return
if field.loc.r == nil: fillObjectFields(p.module, typ)
if field.loc.t == nil:
internalError(p.config, n.info, "specializeResetN()")
specializeResetT(p, "$1.$2" % [accessor, field.loc.r], field.loc.t)
else: internalError(p.config, n.info, "specializeResetN()")
proc specializeResetT(p: BProc, accessor: Rope, typ: PType) =
if typ == nil: return
case typ.kind
of tyGenericInst, tyGenericBody, tyTypeDesc, tyAlias, tyDistinct, tyInferred,
tySink, tyOwned:
specializeResetT(p, accessor, lastSon(typ))
of tyArray:
let arraySize = lengthOrd(p.config, typ[0])
var i: TLoc
getTemp(p, getSysType(p.module.g.graph, unknownLineInfo, tyInt), i)
linefmt(p, cpsStmts, "for ($1 = 0; $1 < $2; $1++) {$n",
[i.r, arraySize])
specializeResetT(p, ropecg(p.module, "$1[$2]", [accessor, i.r]), typ[1])
lineF(p, cpsStmts, "}$n", [])
of tyObject:
for i in 0..<typ.len:
var x = typ[i]
if x != nil: x = x.skipTypes(skipPtrs)
specializeResetT(p, accessor.parentObj(p.module), x)
if typ.n != nil: specializeResetN(p, accessor, typ.n, typ)
of tyTuple:
let typ = getUniqueType(typ)
for i in 0..<typ.len:
specializeResetT(p, ropecg(p.module, "$1.Field$2", [accessor, i]), typ[i])
of tyString, tyRef, tySequence:
lineCg(p, cpsStmts, "#unsureAsgnRef((void**)&$1, NIM_NIL);$n", [accessor])
of tyProc:
if typ.callConv == ccClosure:
lineCg(p, cpsStmts, "#unsureAsgnRef((void**)&$1.ClE_0, NIM_NIL);$n", [accessor])
lineCg(p, cpsStmts, "$1.ClP_0 = NIM_NIL;$n", [accessor])
else:
lineCg(p, cpsStmts, "$1 = NIM_NIL;$n", [accessor])
of tyChar, tyBool, tyEnum, tyInt..tyUInt64:
lineCg(p, cpsStmts, "$1 = 0;$n", [accessor])
of tyCString, tyPointer, tyPtr, tyVar, tyLent:
lineCg(p, cpsStmts, "$1 = NIM_NIL;$n", [accessor])
else:
discard
proc specializeReset(p: BProc, a: TLoc) =
specializeResetT(p, rdLoc(a), a.t)

File diff suppressed because it is too large Load Diff

View File

@@ -16,11 +16,11 @@ proc emulatedThreadVars(conf: ConfigRef): bool =
result = {optThreads, optTlsEmulation} <= conf.globalOptions
proc accessThreadLocalVar(p: BProc, s: PSym) =
if emulatedThreadVars(p.config) and not p.threadVarAccessed:
p.threadVarAccessed = true
if emulatedThreadVars(p.config) and threadVarAccessed notin p.flags:
p.flags.incl threadVarAccessed
incl p.module.flags, usesThreadVars
addf(p.procSec(cpsLocals), "\tNimThreadVars* NimTV_;$n", [])
add(p.procSec(cpsInit),
p.procSec(cpsLocals).addf("\tNimThreadVars* NimTV_;$n", [])
p.procSec(cpsInit).add(
ropecg(p.module, "\tNimTV_ = (NimThreadVars*) #GetThreadLocalVars();$n", []))
proc declareThreadVar(m: BModule, s: PSym, isExtern: bool) =
@@ -30,23 +30,26 @@ proc declareThreadVar(m: BModule, s: PSym, isExtern: bool) =
# allocator for it :-(
if not containsOrIncl(m.g.nimtvDeclared, s.id):
m.g.nimtvDeps.add(s.loc.t)
addf(m.g.nimtv, "$1 $2;$n", [getTypeDesc(m, s.loc.t), s.loc.r])
m.g.nimtv.addf("$1 $2;$n", [getTypeDesc(m, s.loc.t), s.loc.r])
else:
if isExtern: add(m.s[cfsVars], "extern ")
if optThreads in m.config.globalOptions: add(m.s[cfsVars], "NIM_THREADVAR ")
add(m.s[cfsVars], getTypeDesc(m, s.loc.t))
addf(m.s[cfsVars], " $1;$n", [s.loc.r])
if isExtern: m.s[cfsVars].add("extern ")
elif lfExportLib in s.loc.flags: m.s[cfsVars].add("N_LIB_EXPORT_VAR ")
else: m.s[cfsVars].add("N_LIB_PRIVATE ")
if optThreads in m.config.globalOptions: m.s[cfsVars].add("NIM_THREADVAR ")
m.s[cfsVars].add(getTypeDesc(m, s.loc.t))
m.s[cfsVars].addf(" $1;$n", [s.loc.r])
proc generateThreadLocalStorage(m: BModule) =
if m.g.nimtv != nil and (usesThreadVars in m.flags or sfMainModule in m.module.flags):
for t in items(m.g.nimtvDeps): discard getTypeDesc(m, t)
addf(m.s[cfsSeqTypes], "typedef struct {$1} NimThreadVars;$n", [m.g.nimtv])
finishTypeDescriptions(m)
m.s[cfsSeqTypes].addf("typedef struct {$1} NimThreadVars;$n", [m.g.nimtv])
proc generateThreadVarsSize(m: BModule) =
if m.g.nimtv != nil:
let externc = if m.config.cmd == cmdCompileToCpp or
let externc = if m.config.backend == backendCpp or
sfCompileToCpp in m.module.flags: "extern \"C\" "
else: ""
addf(m.s[cfsProcs],
m.s[cfsProcs].addf(
"$#NI NimThreadVarsSize(){return (NI)sizeof(NimThreadVars);}$n",
[externc.rope])

View File

@@ -28,18 +28,18 @@ proc genTraverseProc(c: TTraversalClosure, accessor: Rope, n: PNode;
if n == nil: return
case n.kind
of nkRecList:
for i in 0 ..< len(n):
genTraverseProc(c, accessor, n.sons[i], typ)
for i in 0..<n.len:
genTraverseProc(c, accessor, n[i], typ)
of nkRecCase:
if (n.sons[0].kind != nkSym): internalError(c.p.config, n.info, "genTraverseProc")
if (n[0].kind != nkSym): internalError(c.p.config, n.info, "genTraverseProc")
var p = c.p
let disc = n.sons[0].sym
let disc = n[0].sym
if disc.loc.r == nil: fillObjectFields(c.p.module, typ)
if disc.loc.t == nil:
internalError(c.p.config, n.info, "genTraverseProc()")
lineF(p, cpsStmts, "switch ($1.$2) {$n", [accessor, disc.loc.r])
for i in 1 ..< len(n):
let branch = n.sons[i]
for i in 1..<n.len:
let branch = n[i]
assert branch.kind in {nkOfBranch, nkElse}
if branch.kind == nkOfBranch:
genCaseRange(c.p, branch)
@@ -73,33 +73,33 @@ proc genTraverseProc(c: TTraversalClosure, accessor: Rope, typ: PType) =
tySink, tyOwned:
genTraverseProc(c, accessor, lastSon(typ))
of tyArray:
let arraySize = lengthOrd(c.p.config, typ.sons[0])
let arraySize = lengthOrd(c.p.config, typ[0])
var i: TLoc
getTemp(p, getSysType(c.p.module.g.graph, unknownLineInfo(), tyInt), i)
getTemp(p, getSysType(c.p.module.g.graph, unknownLineInfo, tyInt), i)
let oldCode = p.s(cpsStmts)
linefmt(p, cpsStmts, "for ($1 = 0; $1 < $2; $1++) {$n",
[i.r, arraySize])
let oldLen = p.s(cpsStmts).len
genTraverseProc(c, ropecg(c.p.module, "$1[$2]", [accessor, i.r]), typ.sons[1])
genTraverseProc(c, ropecg(c.p.module, "$1[$2]", [accessor, i.r]), typ[1])
if p.s(cpsStmts).len == oldLen:
# do not emit dummy long loops for faster debug builds:
p.s(cpsStmts) = oldCode
else:
lineF(p, cpsStmts, "}$n", [])
of tyObject:
for i in 0 ..< len(typ):
var x = typ.sons[i]
for i in 0..<typ.len:
var x = typ[i]
if x != nil: x = x.skipTypes(skipPtrs)
genTraverseProc(c, accessor.parentObj(c.p.module), x)
if typ.n != nil: genTraverseProc(c, accessor, typ.n, typ)
of tyTuple:
let typ = getUniqueType(typ)
for i in 0 ..< len(typ):
genTraverseProc(c, ropecg(c.p.module, "$1.Field$2", [accessor, i]), typ.sons[i])
for i in 0..<typ.len:
genTraverseProc(c, ropecg(c.p.module, "$1.Field$2", [accessor, i]), typ[i])
of tyRef:
lineCg(p, cpsStmts, visitorFrmt, [accessor, c.visitorFrmt])
of tySequence:
if tfHasAsgn notin typ.flags:
if optSeqDestructors notin c.p.module.config.globalOptions:
lineCg(p, cpsStmts, visitorFrmt, [accessor, c.visitorFrmt])
elif containsGarbageCollectedRef(typ.lastSon):
# destructor based seqs are themselves not traced but their data is, if
@@ -119,7 +119,7 @@ proc genTraverseProcSeq(c: TTraversalClosure, accessor: Rope, typ: PType) =
var p = c.p
assert typ.kind == tySequence
var i: TLoc
getTemp(p, getSysType(c.p.module.g.graph, unknownLineInfo(), tyInt), i)
getTemp(p, getSysType(c.p.module.g.graph, unknownLineInfo, tyInt), i)
let oldCode = p.s(cpsStmts)
var a: TLoc
a.r = accessor
@@ -127,7 +127,7 @@ proc genTraverseProcSeq(c: TTraversalClosure, accessor: Rope, typ: PType) =
lineF(p, cpsStmts, "for ($1 = 0; $1 < $2; $1++) {$n",
[i.r, lenExpr(c.p, a)])
let oldLen = p.s(cpsStmts).len
genTraverseProc(c, "$1$3[$2]" % [accessor, i.r, dataField(c.p)], typ.sons[0])
genTraverseProc(c, "$1$3[$2]" % [accessor, i.r, dataField(c.p)], typ[0])
if p.s(cpsStmts).len == oldLen:
# do not emit dummy long loops for faster debug builds:
p.s(cpsStmts) = oldCode
@@ -155,11 +155,11 @@ proc genTraverseProc(m: BModule, origTyp: PType; sig: SigHash): Rope =
if typ.kind == tySequence:
genTraverseProcSeq(c, "a".rope, typ)
else:
if skipTypes(typ.sons[0], typedescInst+{tyOwned}).kind == tyArray:
if skipTypes(typ[0], typedescInst+{tyOwned}).kind == tyArray:
# C's arrays are broken beyond repair:
genTraverseProc(c, "a".rope, typ.sons[0])
genTraverseProc(c, "a".rope, typ[0])
else:
genTraverseProc(c, "(*a)".rope, typ.sons[0])
genTraverseProc(c, "(*a)".rope, typ[0])
let generatedProc = "$1 {$n$2$3$4}\n" %
[header, p.s(cpsLocals), p.s(cpsInit), p.s(cpsStmts)]
@@ -168,12 +168,12 @@ proc genTraverseProc(m: BModule, origTyp: PType; sig: SigHash): Rope =
m.s[cfsProcs].add(generatedProc)
if hcrOn:
addf(m.s[cfsProcHeaders], "N_NIMCALL_PTR(void, $1)(void*, NI);\n", [result])
addf(m.s[cfsDynLibInit], "\t$1 = (N_NIMCALL_PTR(void, )(void*, NI)) hcrRegisterProc($3, \"$1\", (void*)$2);\n",
m.s[cfsProcHeaders].addf("N_NIMCALL_PTR(void, $1)(void*, NI);\n", [result])
m.s[cfsDynLibInit].addf("\t$1 = (N_NIMCALL_PTR(void, )(void*, NI)) hcrRegisterProc($3, \"$1\", (void*)$2);\n",
[result, markerName, getModuleDllPath(m)])
proc genTraverseProcForGlobal(m: BModule, s: PSym; info: TLineInfo): Rope =
discard genTypeInfo(m, s.loc.t, info)
discard genTypeInfoV1(m, s.loc.t, info)
var c: TTraversalClosure
var p = newProc(nil, m)

File diff suppressed because it is too large Load Diff

View File

@@ -16,11 +16,11 @@ import
proc getPragmaStmt*(n: PNode, w: TSpecialWord): PNode =
case n.kind
of nkStmtList:
for i in 0 ..< n.len:
for i in 0..<n.len:
result = getPragmaStmt(n[i], w)
if result != nil: break
of nkPragma:
for i in 0 ..< n.len:
for i in 0..<n.len:
if whichPragma(n[i]) == w: return n[i]
else: discard
@@ -33,7 +33,7 @@ proc hashString*(conf: ConfigRef; s: string): BiggestInt =
# we have to use the same bitwidth
# as the target CPU
var b = 0'u64
for i in 0 ..< len(s):
for i in 0..<s.len:
b = b + uint(s[i])
b = b + (b shl 10)
b = b xor (b shr 6)
@@ -43,7 +43,7 @@ proc hashString*(conf: ConfigRef; s: string): BiggestInt =
result = cast[Hash](b)
else:
var a = 0'u32
for i in 0 ..< len(s):
for i in 0..<s.len:
a = a + uint32(s[i])
a = a + (a shl 10)
a = a xor (a shr 6)
@@ -70,18 +70,18 @@ proc mangle*(name: string): string =
template special(x) =
result.add x
requiresUnderscore = true
for i in start..(name.len-1):
for i in start..<name.len:
let c = name[i]
case c
of 'a'..'z', '0'..'9', 'A'..'Z':
add(result, c)
result.add(c)
of '_':
# we generate names like 'foo_9' for scope disambiguations and so
# disallow this here:
if i > 0 and i < name.len-1 and name[i+1] in Digits:
discard
else:
add(result, c)
result.add(c)
of '$': special "dollar"
of '%': special "percent"
of '&': special "amp"
@@ -102,7 +102,7 @@ proc mangle*(name: string): string =
of '@': special "at"
of '|': special "bar"
else:
add(result, "X" & toHex(ord(c), 2))
result.add("X" & toHex(ord(c), 2))
requiresUnderscore = true
if requiresUnderscore:
result.add "_"

File diff suppressed because it is too large Load Diff

View File

@@ -11,7 +11,7 @@
import
ast, ropes, options, intsets,
tables, ndi, lineinfos, pathutils, modulegraphs
tables, ndi, lineinfos, pathutils, modulegraphs, sets
type
TLabel* = Rope # for the C generator a label is just a rope
@@ -25,10 +25,10 @@ type
# this is needed for strange type generation
# reasons
cfsFieldInfo, # section for field information
cfsTypeInfo, # section for type information
cfsTypeInfo, # section for type information (ag ABI checks)
cfsProcHeaders, # section for C procs prototypes
cfsVars, # section for C variable declarations
cfsData, # section for C constant data
cfsVars, # section for C variable declarations
cfsProcs, # section for C procs that are not inline
cfsInitProc, # section for the C init proc
cfsDatInitProc, # section for the C datInit proc
@@ -64,16 +64,21 @@ type
nestedExceptStmts*: int16 # how many except statements is it nested into
frameLen*: int16
TCProcFlag* = enum
beforeRetNeeded,
threadVarAccessed,
hasCurFramePointer,
noSafePoints,
nimErrorFlagAccessed,
nimErrorFlagDeclared,
nimErrorFlagDisabled
TCProc = object # represents C proc that is currently generated
prc*: PSym # the Nim proc that this C proc belongs to
beforeRetNeeded*: bool # true iff 'BeforeRet' label for proc is needed
threadVarAccessed*: bool # true if the proc already accessed some threadvar
hasCurFramePointer*: bool # true if _nimCurFrame var needed to recover after
# exception is generated
noSafePoints*: bool # the proc doesn't use safe points in exception handling
flags*: set[TCProcFlag]
lastLineInfo*: TLineInfo # to avoid generating excessive 'nimln' statements
currLineInfo*: TLineInfo # AST codegen will make this superfluous
nestedTryStmts*: seq[tuple[fin: PNode, inExcept: bool]]
nestedTryStmts*: seq[tuple[fin: PNode, inExcept: bool, label: Natural]]
# in how many nested try statements we are
# (the vars must be volatile then)
# bool is true when are in the except part of a try block
@@ -86,14 +91,13 @@ type
options*: TOptions # options that should be used for code
# generation; this is the same as prc.options
# unless prc == nil
maxFrameLen*: int # max length of frame descriptor
module*: BModule # used to prevent excessive parameter passing
withinLoop*: int # > 0 if we are within a loop
splitDecls*: int # > 0 if we are in some context for C++ that
# requires 'T x = T()' to become 'T x; x = T()'
# (yes, C++ is weird like that)
gcFrameId*: Natural # for the GC stack marking
gcFrameType*: Rope # the struct {} we put the GC markers into
withinTryWithExcept*: int # required for goto based exception handling
withinBlockLeaveActions*: int # complex to explain
sigConflicts*: CountTable[string]
TTypeSeq* = seq[PType]
@@ -118,6 +122,7 @@ type
forwardedProcs*: seq[PSym] # proc:s that did not yet have a body
generatedHeader*: BModule
typeInfoMarker*: TypeCacheWithOwner
typeInfoMarkerV2*: TypeCacheWithOwner
config*: ConfigRef
graph*: ModuleGraph
strVersion*, seqVersion*: int # version of the string/seq implementation to use
@@ -142,11 +147,16 @@ type
# without extension)
tmpBase*: Rope # base for temp identifier generation
typeCache*: TypeCache # cache the generated types
typeABICache*: HashSet[SigHash] # cache for ABI checks; reusing typeCache
# would be ideal but for some reason enums
# don't seem to get cached so it'd generate
# 1 ABI check per occurence in code
forwTypeCache*: TypeCache # cache for forward declarations of types
declaredThings*: IntSet # things we have declared in this .c file
declaredProtos*: IntSet # prototypes we have declared in this .c file
headerFiles*: seq[string] # needed headers to include
typeInfoMarker*: TypeCache # needed for generating type information
typeInfoMarkerV2*: TypeCache
initProc*: BProc # code for init procedure
preInitProc*: BProc # code executed before the init proc
hcrCreateTypeInfosProc*: Rope # type info globals are in here when HCR=on
@@ -172,7 +182,7 @@ proc includeHeader*(this: BModule; header: string) =
proc s*(p: BProc, s: TCProcSection): var Rope {.inline.} =
# section in the current block
result = p.blocks[p.blocks.len-1].sections[s]
result = p.blocks[^1].sections[s]
proc procSec*(p: BProc, s: TCProcSection): var Rope {.inline.} =
# top level proc sections
@@ -182,8 +192,8 @@ proc newProc*(prc: PSym, module: BModule): BProc =
new(result)
result.prc = prc
result.module = module
if prc != nil: result.options = prc.options
else: result.options = module.config.options
result.options = if prc != nil: prc.options
else: module.config.options
newSeq(result.blocks, 1)
result.nestedTryStmts = @[]
result.finallySafePoints = @[]

View File

@@ -7,7 +7,7 @@
# distribution, for details about the copyright.
#
## This module implements code generation for multi methods.
## This module implements code generation for methods.
import
intsets, options, ast, msgs, idents, renderer, types, magicsys,
@@ -23,11 +23,11 @@ proc genConv(n: PNode, d: PType, downcast: bool; conf: ConfigRef): PNode =
result = n
elif diff < 0:
result = newNodeIT(nkObjUpConv, n.info, d)
addSon(result, n)
result.add n
if downcast: internalError(conf, n.info, "cgmeth.genConv: no upcast allowed")
elif diff > 0:
result = newNodeIT(nkObjDownConv, n.info, d)
addSon(result, n)
result.add n
if not downcast:
internalError(conf, n.info, "cgmeth.genConv: no downcast allowed")
else:
@@ -44,26 +44,26 @@ proc getDispatcher*(s: PSym): PSym =
proc methodCall*(n: PNode; conf: ConfigRef): PNode =
result = n
# replace ordinary method by dispatcher method:
let disp = getDispatcher(result.sons[0].sym)
let disp = getDispatcher(result[0].sym)
if disp != nil:
result.sons[0].sym = disp
result[0].sym = disp
# change the arguments to up/downcasts to fit the dispatcher's parameters:
for i in 1 ..< len(result):
result.sons[i] = genConv(result.sons[i], disp.typ.sons[i], true, conf)
for i in 1..<result.len:
result[i] = genConv(result[i], disp.typ[i], true, conf)
else:
localError(conf, n.info, "'" & $result.sons[0] & "' lacks a dispatcher")
localError(conf, n.info, "'" & $result[0] & "' lacks a dispatcher")
type
MethodResult = enum No, Invalid, Yes
proc sameMethodBucket(a, b: PSym; multiMethods: bool): MethodResult =
if a.name.id != b.name.id: return
if len(a.typ) != len(b.typ):
if a.typ.len != b.typ.len:
return
for i in 1 ..< len(a.typ):
var aa = a.typ.sons[i]
var bb = b.typ.sons[i]
for i in 1..<a.typ.len:
var aa = a.typ[i]
var bb = b.typ[i]
while true:
aa = skipTypes(aa, {tyGenericInst, tyAlias})
bb = skipTypes(bb, {tyGenericInst, tyAlias})
@@ -72,7 +72,7 @@ proc sameMethodBucket(a, b: PSym; multiMethods: bool): MethodResult =
bb = bb.lastSon
else:
break
if sameType(a.typ.sons[i], b.typ.sons[i]):
if sameType(a.typ[i], b.typ[i]):
if aa.kind == tyObject and result != Invalid:
result = Yes
elif aa.kind == tyObject and bb.kind == tyObject and (i == 1 or multiMethods):
@@ -90,22 +90,22 @@ proc sameMethodBucket(a, b: PSym; multiMethods: bool): MethodResult =
return No
if result == Yes:
# check for return type:
if not sameTypeOrNil(a.typ.sons[0], b.typ.sons[0]):
if b.typ.sons[0] != nil and b.typ.sons[0].kind == tyUntyped:
if not sameTypeOrNil(a.typ[0], b.typ[0]):
if b.typ[0] != nil and b.typ[0].kind == tyUntyped:
# infer 'auto' from the base to make it consistent:
b.typ.sons[0] = a.typ.sons[0]
b.typ[0] = a.typ[0]
else:
return No
proc attachDispatcher(s: PSym, dispatcher: PNode) =
if dispatcherPos < s.ast.len:
# we've added a dispatcher already, so overwrite it
s.ast.sons[dispatcherPos] = dispatcher
s.ast[dispatcherPos] = dispatcher
else:
setLen(s.ast.sons, dispatcherPos+1)
if s.ast[resultPos] == nil:
s.ast[resultPos] = newNodeI(nkEmpty, s.info)
s.ast.sons[dispatcherPos] = dispatcher
s.ast[dispatcherPos] = dispatcher
proc createDispatcher(s: PSym): PSym =
var disp = copySym(s)
@@ -113,18 +113,18 @@ proc createDispatcher(s: PSym): PSym =
excl(disp.flags, sfExported)
disp.typ = copyType(disp.typ, disp.typ.owner, false)
# we can't inline the dispatcher itself (for now):
if disp.typ.callConv == ccInline: disp.typ.callConv = ccDefault
if disp.typ.callConv == ccInline: disp.typ.callConv = ccNimCall
disp.ast = copyTree(s.ast)
disp.ast.sons[bodyPos] = newNodeI(nkEmpty, s.info)
disp.ast[bodyPos] = newNodeI(nkEmpty, s.info)
disp.loc.r = nil
if s.typ.sons[0] != nil:
if s.typ[0] != nil:
if disp.ast.len > resultPos:
disp.ast.sons[resultPos].sym = copySym(s.ast.sons[resultPos].sym)
disp.ast[resultPos].sym = copySym(s.ast[resultPos].sym)
else:
# We've encountered a method prototype without a filled-in
# resultPos slot. We put a placeholder in there that will
# be updated in fixupDispatcher().
disp.ast.addSon(newNodeI(nkEmpty, s.info))
disp.ast.add newNodeI(nkEmpty, s.info)
attachDispatcher(s, newSymNode(disp))
# attach to itself to prevent bugs:
attachDispatcher(disp, newSymNode(disp))
@@ -137,8 +137,8 @@ proc fixupDispatcher(meth, disp: PSym; conf: ConfigRef) =
# the lock level of the dispatcher needs to be updated/checked
# against that of the method.
if disp.ast.len > resultPos and meth.ast.len > resultPos and
disp.ast.sons[resultPos].kind == nkEmpty:
disp.ast.sons[resultPos] = copyTree(meth.ast.sons[resultPos])
disp.ast[resultPos].kind == nkEmpty:
disp.ast[resultPos] = copyTree(meth.ast[resultPos])
# The following code works only with lock levels, so we disable
# it when they're not available.
@@ -158,13 +158,12 @@ proc fixupDispatcher(meth, disp: PSym; conf: ConfigRef) =
disp.typ.lockLevel = meth.typ.lockLevel
proc methodDef*(g: ModuleGraph; s: PSym, fromCache: bool) =
let L = len(g.methods)
var witness: PSym
for i in 0 ..< L:
for i in 0..<g.methods.len:
let disp = g.methods[i].dispatcher
case sameMethodBucket(disp, s, multimethods = optMultiMethods in g.config.globalOptions)
of Yes:
add(g.methods[i].methods, s)
g.methods[i].methods.add(s)
attachDispatcher(s, disp.ast[dispatcherPos])
fixupDispatcher(s, disp, g.config)
#echo "fixup ", disp.name.s, " ", disp.id
@@ -178,7 +177,7 @@ proc methodDef*(g: ModuleGraph; s: PSym, fromCache: bool) =
of Invalid:
if witness.isNil: witness = g.methods[i].methods[0]
# create a new dispatcher:
add(g.methods, (methods: @[s], dispatcher: createDispatcher(s)))
g.methods.add((methods: @[s], dispatcher: createDispatcher(s)))
#echo "adding ", s.info
#if fromCache:
# internalError(s.info, "no method dispatcher found")
@@ -190,32 +189,32 @@ proc methodDef*(g: ModuleGraph; s: PSym, fromCache: bool) =
proc relevantCol(methods: seq[PSym], col: int): bool =
# returns true iff the position is relevant
var t = methods[0].typ.sons[col].skipTypes(skipPtrs)
var t = methods[0].typ[col].skipTypes(skipPtrs)
if t.kind == tyObject:
for i in 1 .. high(methods):
let t2 = skipTypes(methods[i].typ.sons[col], skipPtrs)
for i in 1..high(methods):
let t2 = skipTypes(methods[i].typ[col], skipPtrs)
if not sameType(t2, t):
return true
proc cmpSignatures(a, b: PSym, relevantCols: IntSet): int =
for col in 1 ..< len(a.typ):
for col in 1..<a.typ.len:
if contains(relevantCols, col):
var aa = skipTypes(a.typ.sons[col], skipPtrs)
var bb = skipTypes(b.typ.sons[col], skipPtrs)
var aa = skipTypes(a.typ[col], skipPtrs)
var bb = skipTypes(b.typ[col], skipPtrs)
var d = inheritanceDiff(aa, bb)
if (d != high(int)) and d != 0:
return d
proc sortBucket(a: var seq[PSym], relevantCols: IntSet) =
# we use shellsort here; fast and simple
var n = len(a)
var n = a.len
var h = 1
while true:
h = 3 * h + 1
if h > n: break
while true:
h = h div 3
for i in h ..< n:
for i in h..<n:
var v = a[i]
var j = i
while cmpSignatures(a[j - h], v, relevantCols) >= 0:
@@ -228,71 +227,70 @@ proc sortBucket(a: var seq[PSym], relevantCols: IntSet) =
proc genDispatcher(g: ModuleGraph; methods: seq[PSym], relevantCols: IntSet): PSym =
var base = methods[0].ast[dispatcherPos].sym
result = base
var paramLen = len(base.typ)
var paramLen = base.typ.len
var nilchecks = newNodeI(nkStmtList, base.info)
var disp = newNodeI(nkIfStmt, base.info)
var ands = getSysMagic(g, unknownLineInfo(), "and", mAnd)
var iss = getSysMagic(g, unknownLineInfo(), "of", mOf)
let boolType = getSysType(g, unknownLineInfo(), tyBool)
for col in 1 ..< paramLen:
var ands = getSysMagic(g, unknownLineInfo, "and", mAnd)
var iss = getSysMagic(g, unknownLineInfo, "of", mOf)
let boolType = getSysType(g, unknownLineInfo, tyBool)
for col in 1..<paramLen:
if contains(relevantCols, col):
let param = base.typ.n.sons[col].sym
let param = base.typ.n[col].sym
if param.typ.skipTypes(abstractInst).kind in {tyRef, tyPtr}:
addSon(nilchecks, newTree(nkCall,
newSymNode(getCompilerProc(g, "chckNilDisp")), newSymNode(param)))
for meth in 0 .. high(methods):
nilchecks.add newTree(nkCall,
newSymNode(getCompilerProc(g, "chckNilDisp")), newSymNode(param))
for meth in 0..high(methods):
var curr = methods[meth] # generate condition:
var cond: PNode = nil
for col in 1 ..< paramLen:
for col in 1..<paramLen:
if contains(relevantCols, col):
var isn = newNodeIT(nkCall, base.info, boolType)
addSon(isn, newSymNode(iss))
let param = base.typ.n.sons[col].sym
addSon(isn, newSymNode(param))
addSon(isn, newNodeIT(nkType, base.info, curr.typ.sons[col]))
isn.add newSymNode(iss)
let param = base.typ.n[col].sym
isn.add newSymNode(param)
isn.add newNodeIT(nkType, base.info, curr.typ[col])
if cond != nil:
var a = newNodeIT(nkCall, base.info, boolType)
addSon(a, newSymNode(ands))
addSon(a, cond)
addSon(a, isn)
a.add newSymNode(ands)
a.add cond
a.add isn
cond = a
else:
cond = isn
let retTyp = base.typ.sons[0]
let retTyp = base.typ[0]
let call = newNodeIT(nkCall, base.info, retTyp)
addSon(call, newSymNode(curr))
for col in 1 ..< paramLen:
addSon(call, genConv(newSymNode(base.typ.n.sons[col].sym),
curr.typ.sons[col], false, g.config))
call.add newSymNode(curr)
for col in 1..<paramLen:
call.add genConv(newSymNode(base.typ.n[col].sym),
curr.typ[col], false, g.config)
var ret: PNode
if retTyp != nil:
var a = newNodeI(nkFastAsgn, base.info)
addSon(a, newSymNode(base.ast.sons[resultPos].sym))
addSon(a, call)
a.add newSymNode(base.ast[resultPos].sym)
a.add call
ret = newNodeI(nkReturnStmt, base.info)
addSon(ret, a)
ret.add a
else:
ret = call
if cond != nil:
var a = newNodeI(nkElifBranch, base.info)
addSon(a, cond)
addSon(a, ret)
addSon(disp, a)
a.add cond
a.add ret
disp.add a
else:
disp = ret
nilchecks.add disp
nilchecks.flags.incl nfTransf # should not be further transformed
result.ast.sons[bodyPos] = nilchecks
result.ast[bodyPos] = nilchecks
proc generateMethodDispatchers*(g: ModuleGraph): PNode =
result = newNode(nkStmtList)
for bucket in 0 ..< len(g.methods):
for bucket in 0..<g.methods.len:
var relevantCols = initIntSet()
for col in 1 ..< len(g.methods[bucket].methods[0].typ):
for col in 1..<g.methods[bucket].methods[0].typ.len:
if relevantCol(g.methods[bucket].methods, col): incl(relevantCols, col)
if optMultiMethods notin g.config.globalOptions:
# if multi-methods are not enabled, we are interested only in the first field
break
sortBucket(g.methods[bucket].methods, relevantCols)
addSon(result,
newSymNode(genDispatcher(g, g.methods[bucket].methods, relevantCols)))
result.add newSymNode(genDispatcher(g, g.methods[bucket].methods, relevantCols))

View File

@@ -121,7 +121,10 @@
# yield 2
# if :unrollFinally: # This node is created by `newEndFinallyNode`
# if :curExc.isNil:
# return :tmpResult
# if nearestFinally == 0:
# return :tmpResult
# else:
# :state = nearestFinally # bubble up
# else:
# closureIterSetupExc(nil)
# raise
@@ -130,7 +133,8 @@
import
ast, msgs, idents,
renderer, magicsys, lowerings, lambdalifting, modulegraphs, lineinfos
renderer, magicsys, lowerings, lambdalifting, modulegraphs, lineinfos,
tables, options
type
Ctx = object
@@ -154,8 +158,8 @@ type
# is their finally. For finally it is parent finally. Otherwise -1
const
nkSkip = { nkEmpty..nkNilLit, nkTemplateDef, nkTypeSection, nkStaticStmt,
nkCommentStmt } + procDefs
nkSkip = {nkEmpty..nkNilLit, nkTemplateDef, nkTypeSection, nkStaticStmt,
nkCommentStmt, nkMixinStmt, nkBindStmt} + procDefs
proc newStateAccess(ctx: var Ctx): PNode =
if ctx.stateVarSym.isNil:
@@ -237,7 +241,7 @@ proc toStmtList(n: PNode): PNode =
proc addGotoOut(n: PNode, gotoOut: PNode): PNode =
# Make sure `n` is a stmtlist, and ends with `gotoOut`
result = toStmtList(n)
if result.len == 0 or result.sons[^1].kind != nkGotoState:
if result.len == 0 or result[^1].kind != nkGotoState:
result.add(gotoOut)
proc newTempVar(ctx: var Ctx, typ: PType): PSym =
@@ -273,7 +277,7 @@ proc transformBreaksAndContinuesInWhile(ctx: var Ctx, n: PNode, before, after: P
if ctx.blockLevel == 0:
result = after
else:
for i in 0 ..< n.len:
for i in 0..<n.len:
n[i] = ctx.transformBreaksAndContinuesInWhile(n[i], before, after)
proc transformBreaksInBlock(ctx: var Ctx, n: PNode, label, after: PNode): PNode =
@@ -293,7 +297,7 @@ proc transformBreaksInBlock(ctx: var Ctx, n: PNode, label, after: PNode): PNode
if label.kind == nkSym and n[0].sym == label.sym:
result = after
else:
for i in 0 ..< n.len:
for i in 0..<n.len:
n[i] = ctx.transformBreaksInBlock(n[i], label, after)
proc newNullifyCurExc(ctx: var Ctx, info: TLineInfo): PNode =
@@ -318,7 +322,7 @@ proc collectExceptState(ctx: var Ctx, n: PNode): PNode {.inline.} =
if c.len > 1:
var cond: PNode
for i in 0 .. c.len - 2:
for i in 0..<c.len - 1:
assert(c[i].kind == nkType)
let nextCond = newTree(nkCall,
newSymNode(g.getSysMagic(c.info, "of", mOf)),
@@ -388,6 +392,10 @@ proc hasYieldsInExpressions(n: PNode): bool =
return true
else:
result = n.hasYields
of nkCast:
for i in 1..<n.len:
if n[i].hasYieldsInExpressions:
return true
else:
for c in n:
if c.hasYieldsInExpressions:
@@ -401,7 +409,7 @@ proc exprToStmtList(n: PNode): tuple[s, res: PNode] =
var n = n
while n.kind == nkStmtListExpr:
result.s.sons.add(n.sons)
result.s.sons.setLen(result.s.sons.len - 1) # delete last son
result.s.sons.setLen(result.s.len - 1) # delete last son
n = n[^1]
result.res = n
@@ -435,7 +443,7 @@ proc lowerStmtListExprs(ctx: var Ctx, n: PNode, needsSplit: var bool): PNode =
of nkYieldStmt:
var ns = false
for i in 0 ..< n.len:
for i in 0..<n.len:
n[i] = ctx.lowerStmtListExprs(n[i], ns)
if ns:
@@ -449,7 +457,7 @@ proc lowerStmtListExprs(ctx: var Ctx, n: PNode, needsSplit: var bool): PNode =
of nkPar, nkObjConstr, nkTupleConstr, nkBracket:
var ns = false
for i in 0 ..< n.len:
for i in 0..<n.len:
n[i] = ctx.lowerStmtListExprs(n[i], ns)
if ns:
@@ -459,7 +467,7 @@ proc lowerStmtListExprs(ctx: var Ctx, n: PNode, needsSplit: var bool): PNode =
if n.typ.isNil: internalError(ctx.g.config, "lowerStmtListExprs: constr typ.isNil")
result.typ = n.typ
for i in 0 ..< n.len:
for i in 0..<n.len:
case n[i].kind
of nkExprColonExpr:
if n[i][1].kind == nkStmtListExpr:
@@ -475,13 +483,12 @@ proc lowerStmtListExprs(ctx: var Ctx, n: PNode, needsSplit: var bool): PNode =
of nkIfStmt, nkIfExpr:
var ns = false
for i in 0 ..< n.len:
for i in 0..<n.len:
n[i] = ctx.lowerStmtListExprs(n[i], ns)
if ns:
needsSplit = true
var tmp: PSym
var s: PNode
let isExpr = not isEmptyType(n.typ)
if isExpr:
tmp = ctx.newTempVar(n.typ)
@@ -541,7 +548,7 @@ proc lowerStmtListExprs(ctx: var Ctx, n: PNode, needsSplit: var bool): PNode =
of nkTryStmt, nkHiddenTryStmt:
var ns = false
for i in 0 ..< n.len:
for i in 0..<n.len:
n[i] = ctx.lowerStmtListExprs(n[i], ns)
if ns:
@@ -554,7 +561,7 @@ proc lowerStmtListExprs(ctx: var Ctx, n: PNode, needsSplit: var bool): PNode =
let tmp = ctx.newTempVar(n.typ)
n[0] = ctx.convertExprBodyToAsgn(n[0], tmp)
for i in 1 ..< n.len:
for i in 1..<n.len:
let branch = n[i]
case branch.kind
of nkExceptBranch:
@@ -571,7 +578,7 @@ proc lowerStmtListExprs(ctx: var Ctx, n: PNode, needsSplit: var bool): PNode =
of nkCaseStmt:
var ns = false
for i in 0 ..< n.len:
for i in 0..<n.len:
n[i] = ctx.lowerStmtListExprs(n[i], ns)
if ns:
@@ -589,7 +596,7 @@ proc lowerStmtListExprs(ctx: var Ctx, n: PNode, needsSplit: var bool): PNode =
result.add(st)
n[0] = ex
for i in 1 ..< n.len:
for i in 1..<n.len:
let branch = n[i]
case branch.kind
of nkOfBranch:
@@ -600,10 +607,16 @@ proc lowerStmtListExprs(ctx: var Ctx, n: PNode, needsSplit: var bool): PNode =
internalError(ctx.g.config, "lowerStmtListExpr(nkCaseStmt): " & $branch.kind)
result.add(n)
result.add(ctx.newEnvVarAccess(tmp))
elif n[0].kind == nkStmtListExpr:
result = newNodeI(nkStmtList, n.info)
let (st, ex) = exprToStmtList(n[0])
result.add(st)
n[0] = ex
result.add(n)
of nkCallKinds, nkChckRange, nkChckRangeF, nkChckRange64:
var ns = false
for i in 0 ..< n.len:
for i in 0..<n.len:
n[i] = ctx.lowerStmtListExprs(n[i], ns)
if ns:
@@ -643,7 +656,7 @@ proc lowerStmtListExprs(ctx: var Ctx, n: PNode, needsSplit: var bool): PNode =
result.add(ifNode)
result.add(ctx.newEnvVarAccess(tmp))
else:
for i in 0 ..< n.len:
for i in 0..<n.len:
if n[i].kind == nkStmtListExpr:
let (st, ex) = exprToStmtList(n[i])
result.add(st)
@@ -672,7 +685,7 @@ proc lowerStmtListExprs(ctx: var Ctx, n: PNode, needsSplit: var bool): PNode =
of nkDiscardStmt, nkReturnStmt, nkRaiseStmt:
var ns = false
for i in 0 ..< n.len:
for i in 0..<n.len:
n[i] = ctx.lowerStmtListExprs(n[i], ns)
if ns:
@@ -686,7 +699,7 @@ proc lowerStmtListExprs(ctx: var Ctx, n: PNode, needsSplit: var bool): PNode =
of nkCast, nkHiddenStdConv, nkHiddenSubConv, nkConv, nkObjDownConv,
nkDerefExpr, nkHiddenDeref:
var ns = false
for i in 0 ..< n.len:
for i in ord(n.kind == nkCast)..<n.len:
n[i] = ctx.lowerStmtListExprs(n[i], ns)
if ns:
@@ -700,7 +713,7 @@ proc lowerStmtListExprs(ctx: var Ctx, n: PNode, needsSplit: var bool): PNode =
of nkAsgn, nkFastAsgn:
var ns = false
for i in 0 ..< n.len:
for i in 0..<n.len:
n[i] = ctx.lowerStmtListExprs(n[i], ns)
if ns:
@@ -738,8 +751,6 @@ proc lowerStmtListExprs(ctx: var Ctx, n: PNode, needsSplit: var bool): PNode =
result.add(n)
of nkWhileStmt:
var ns = false
var condNeedsSplit = false
n[0] = ctx.lowerStmtListExprs(n[0], condNeedsSplit)
var bodyNeedsSplit = false
@@ -778,21 +789,24 @@ proc lowerStmtListExprs(ctx: var Ctx, n: PNode, needsSplit: var bool): PNode =
result = newNodeI(nkStmtListExpr, n.info)
result.typ = n.typ
let (st, ex) = exprToStmtList(n[1])
n.kind = nkBlockStmt
n.transitionSonsKind(nkBlockStmt)
n.typ = nil
n[1] = st
result.add(n)
result.add(ex)
else:
for i in 0 ..< n.len:
for i in 0..<n.len:
n[i] = ctx.lowerStmtListExprs(n[i], needsSplit)
proc newEndFinallyNode(ctx: var Ctx, info: TLineInfo): PNode =
# Generate the following code:
# if :unrollFinally:
# if :curExc.isNil:
# return :tmpResult
# if nearestFinally == 0:
# return :tmpResult
# else:
# :state = nearestFinally # bubble up
# else:
# raise
let curExc = ctx.newCurExcAccess()
@@ -801,11 +815,17 @@ proc newEndFinallyNode(ctx: var Ctx, info: TLineInfo): PNode =
let cmp = newTree(nkCall, newSymNode(ctx.g.getSysMagic(info, "==", mEqRef), info), curExc, nilnode)
cmp.typ = ctx.g.getSysType(info, tyBool)
let asgn = newTree(nkFastAsgn,
newSymNode(getClosureIterResult(ctx.g, ctx.fn), info),
ctx.newTmpResultAccess())
let retStmt =
if ctx.nearestFinally == 0:
# last finally, we can return
let asgn = newTree(nkFastAsgn,
newSymNode(getClosureIterResult(ctx.g, ctx.fn), info),
ctx.newTmpResultAccess())
newTree(nkReturnStmt, asgn)
else:
# bubble up to next finally
newTree(nkGotoState, ctx.g.newIntLit(info, ctx.nearestFinally))
let retStmt = newTree(nkReturnStmt, asgn)
let branch = newTree(nkElifBranch, cmp, retStmt)
let nullifyExc = newTree(nkCall, newSymNode(ctx.g.getCompilerProc("closureIterSetupExc")), nilnode)
@@ -838,7 +858,8 @@ proc transformReturnsInTry(ctx: var Ctx, n: PNode): PNode =
if n[0].kind != nkEmpty:
let asgnTmpResult = newNodeI(nkAsgn, n.info)
asgnTmpResult.add(ctx.newTmpResultAccess())
asgnTmpResult.add(n[0])
let x = if n[0].kind in {nkAsgn, nkFastAsgn}: n[0][1] else: n[0]
asgnTmpResult.add(x)
result.add(asgnTmpResult)
result.add(ctx.newNullifyCurExc(n.info))
@@ -848,8 +869,15 @@ proc transformReturnsInTry(ctx: var Ctx, n: PNode): PNode =
of nkSkip:
discard
of nkTryStmt:
if n.hasYields:
# the inner try will handle these transformations
discard
else:
for i in 0..<n.len:
n[i] = ctx.transformReturnsInTry(n[i])
else:
for i in 0 ..< n.len:
for i in 0..<n.len:
n[i] = ctx.transformReturnsInTry(n[i])
proc transformClosureIteratorBody(ctx: var Ctx, n: PNode, gotoOut: PNode): PNode =
@@ -859,14 +887,14 @@ proc transformClosureIteratorBody(ctx: var Ctx, n: PNode, gotoOut: PNode): PNode
of nkStmtList, nkStmtListExpr:
result = addGotoOut(result, gotoOut)
for i in 0 ..< n.len:
for i in 0..<n.len:
if n[i].hasYields:
# Create a new split
let go = newNodeI(nkGotoState, n[i].info)
n[i] = ctx.transformClosureIteratorBody(n[i], go)
let s = newNodeI(nkStmtList, n[i + 1].info)
for j in i + 1 ..< n.len:
for j in i + 1..<n.len:
s.add(n[j])
n.sons.setLen(i + 1)
@@ -889,7 +917,7 @@ proc transformClosureIteratorBody(ctx: var Ctx, n: PNode, gotoOut: PNode): PNode
result[^1] = ctx.transformClosureIteratorBody(result[^1], gotoOut)
of nkIfStmt, nkCaseStmt:
for i in 0 ..< n.len:
for i in 0..<n.len:
n[i] = ctx.transformClosureIteratorBody(n[i], gotoOut)
if n[^1].kind != nkElse:
# We don't have an else branch, but every possible branch has to end with
@@ -1001,7 +1029,7 @@ proc transformClosureIteratorBody(ctx: var Ctx, n: PNode, gotoOut: PNode): PNode
internalError(ctx.g.config, "closure iter " & $n.kind)
else:
for i in 0 ..< n.len:
for i in 0..<n.len:
n[i] = ctx.transformClosureIteratorBody(n[i], gotoOut)
proc stateFromGotoState(n: PNode): int =
@@ -1038,18 +1066,18 @@ proc transformStateAssignments(ctx: var Ctx, n: PNode): PNode =
result.add(ctx.newStateAssgn(stateFromGotoState(n[1])))
var retStmt = newNodeI(nkReturnStmt, n.info)
if n[0].sons[0].kind != nkEmpty:
var a = newNodeI(nkAsgn, n[0].sons[0].info)
var retVal = n[0].sons[0] #liftCapturedVars(n.sons[0], owner, d, c)
addSon(a, newSymNode(getClosureIterResult(ctx.g, ctx.fn)))
addSon(a, retVal)
if n[0][0].kind != nkEmpty:
var a = newNodeI(nkAsgn, n[0][0].info)
var retVal = n[0][0] #liftCapturedVars(n[0], owner, d, c)
a.add newSymNode(getClosureIterResult(ctx.g, ctx.fn))
a.add retVal
retStmt.add(a)
else:
retStmt.add(ctx.g.emptyNode)
result.add(retStmt)
else:
for i in 0 ..< n.len:
for i in 0..<n.len:
n[i] = ctx.transformStateAssignments(n[i])
of nkSkip:
@@ -1069,7 +1097,7 @@ proc transformStateAssignments(ctx: var Ctx, n: PNode): PNode =
result.add(breakState)
else:
for i in 0 ..< n.len:
for i in 0..<n.len:
n[i] = ctx.transformStateAssignments(n[i])
proc skipStmtList(ctx: Ctx; n: PNode): PNode =
@@ -1101,7 +1129,7 @@ proc skipEmptyStates(ctx: Ctx, stateIdx: int): int =
result = ctx.states[stateIdx][0].intVal.int
proc skipThroughEmptyStates(ctx: var Ctx, n: PNode): PNode =
proc skipThroughEmptyStates(ctx: var Ctx, n: PNode): PNode=
result = n
case n.kind
of nkSkip:
@@ -1110,7 +1138,7 @@ proc skipThroughEmptyStates(ctx: var Ctx, n: PNode): PNode =
result = copyTree(n)
result[0].intVal = ctx.skipEmptyStates(result[0].intVal.int)
else:
for i in 0 ..< n.len:
for i in 0..<n.len:
n[i] = ctx.skipThroughEmptyStates(n[i])
proc newArrayType(g: ModuleGraph; n: int, t: PType, owner: PSym): PType =
@@ -1281,6 +1309,101 @@ proc deleteEmptyStates(ctx: var Ctx) =
else:
inc i
type
PreprocessContext = object
finallys: seq[PNode]
config: ConfigRef
blocks: seq[(PNode, int)]
FreshVarsContext = object
tab: Table[int, PSym]
config: ConfigRef
info: TLineInfo
proc freshVars(n: PNode; c: var FreshVarsContext): PNode =
case n.kind
of nkSym:
let x = c.tab.getOrDefault(n.sym.id)
if x == nil:
result = n
else:
result = newSymNode(x, n.info)
of nkSkip - {nkSym}:
result = n
of nkLetSection, nkVarSection:
result = copyNode(n)
for it in n:
if it.kind in {nkIdentDefs, nkVarTuple}:
let idefs = copyNode(it)
for v in 0..it.len-3:
if it[v].kind == nkSym:
let x = copySym(it[v].sym)
c.tab[it[v].sym.id] = x
idefs.add newSymNode(x)
else:
idefs.add it[v]
for rest in it.len-2 ..< it.len: idefs.add it[rest]
result.add idefs
else:
result.add it
of nkRaiseStmt:
localError(c.config, c.info, "unsupported control flow: 'finally: ... raise' duplicated because of 'break'")
else:
result = n
for i in 0..<n.safeLen:
result[i] = freshVars(n[i], c)
proc preprocess(c: var PreprocessContext; n: PNode): PNode =
# in order to fix bug #15243 without risking regressions, we preprocess
# the AST so that 'break' statements inside a 'try finally' also have the
# finally section. We need to duplicate local variables here and also
# detect: 'finally: raises X' which is currently not supported. We produce
# an error for this case for now. All this will be done properly with Yuriy's
# patch.
result = n
case n.kind
of nkTryStmt:
let f = n.lastSon
if f.kind == nkFinally:
c.finallys.add f.lastSon
for i in 0 ..< n.len:
result[i] = preprocess(c, n[i])
if f.kind == nkFinally:
discard c.finallys.pop()
of nkWhileStmt, nkBlockStmt:
c.blocks.add((n, c.finallys.len))
for i in 0 ..< n.len:
result[i] = preprocess(c, n[i])
discard c.blocks.pop()
of nkBreakStmt:
if c.blocks.len == 0:
discard
else:
var fin = -1
if n[0].kind == nkEmpty:
fin = c.blocks[^1][1]
elif n[0].kind == nkSym:
for i in countdown(c.blocks.high, 0):
if c.blocks[i][0].kind == nkBlockStmt and c.blocks[i][0][0].kind == nkSym and
c.blocks[i][0][0].sym == n[0].sym:
fin = c.blocks[i][1]
break
if fin >= 0:
result = newNodeI(nkStmtList, n.info)
for i in countdown(c.finallys.high, fin):
var vars = FreshVarsContext(tab: initTable[int, PSym](), config: c.config, info: n.info)
result.add freshVars(preprocess(c, c.finallys[i]), vars)
result.add n
of nkSkip: discard
else:
for i in 0 ..< n.len:
result[i] = preprocess(c, n[i])
proc transformClosureIterator*(g: ModuleGraph; fn: PSym, n: PNode): PNode =
var ctx: Ctx
ctx.g = g
@@ -1293,7 +1416,10 @@ proc transformClosureIterator*(g: ModuleGraph; fn: PSym, n: PNode): PNode =
ctx.stateVarSym = newSym(skVar, getIdent(ctx.g.cache, ":state"), fn, fn.info)
ctx.stateVarSym.typ = g.createClosureIterStateType(fn)
ctx.stateLoopLabel = newSym(skLabel, getIdent(ctx.g.cache, ":stateLoop"), fn, fn.info)
var n = n.toStmtList
var pc = PreprocessContext(finallys: @[], config: g.config)
var n = preprocess(pc, n.toStmtList)
#echo "transformed into ", n
#var n = n.toStmtList
discard ctx.newState(n, nil)
let gotoOut = newTree(nkGotoState, g.newIntLit(n.info, -1))

View File

@@ -7,20 +7,33 @@
# distribution, for details about the copyright.
#
## Helpers for binaries that use compiler passes, eg: nim, nimsuggest, nimfix
## Helpers for binaries that use compiler passes, e.g.: nim, nimsuggest, nimfix
import
options, idents, nimconf, scriptconfig, extccomp, commands, msgs,
lineinfos, modulegraphs, condsyms, os, pathutils
options, idents, nimconf, extccomp, commands, msgs,
lineinfos, modulegraphs, condsyms, os, pathutils, parseopt
from strutils import normalize
proc prependCurDir*(f: AbsoluteFile): AbsoluteFile =
when defined(unix):
if os.isAbsolute(f.string): result = f
else: result = AbsoluteFile("./" & f.string)
else:
result = f
proc addCmdPrefix*(result: var string, kind: CmdLineKind) =
# consider moving this to std/parseopt
case kind
of cmdLongOption: result.add "--"
of cmdShortOption: result.add "-"
of cmdArgument, cmdEnd: discard
type
NimProg* = ref object
suggestMode*: bool
supportsStdinFile*: bool
processCmdLine*: proc(pass: TCmdLinePass, cmd: string; config: ConfigRef)
mainCommand*: proc(graph: ModuleGraph)
proc initDefinesProg*(self: NimProg, conf: ConfigRef, name: string) =
condsyms.initDefines(conf.symbols)
@@ -29,10 +42,7 @@ proc initDefinesProg*(self: NimProg, conf: ConfigRef, name: string) =
proc processCmdLineAndProjectPath*(self: NimProg, conf: ConfigRef) =
self.processCmdLine(passCmd1, "", conf)
if self.supportsStdinFile and conf.projectName == "-":
conf.projectName = "stdinfile"
conf.projectFull = AbsoluteFile "stdinfile"
conf.projectPath = AbsoluteDir getCurrentDir()
conf.projectIsStdin = true
handleStdinInput(conf)
elif conf.projectName != "":
try:
conf.projectFull = canonicalizePath(conf, AbsoluteFile conf.projectName)
@@ -45,46 +55,21 @@ proc processCmdLineAndProjectPath*(self: NimProg, conf: ConfigRef) =
else:
conf.projectPath = AbsoluteDir canonicalizePath(conf, AbsoluteFile getCurrentDir())
proc loadConfigsAndRunMainCommand*(self: NimProg, cache: IdentCache; conf: ConfigRef): bool =
loadConfigs(DefaultConfig, cache, conf) # load all config files
proc loadConfigsAndRunMainCommand*(self: NimProg, cache: IdentCache; conf: ConfigRef;
graph: ModuleGraph): bool =
if self.suggestMode:
conf.command = "nimsuggest"
loadConfigs(DefaultConfig, cache, conf) # load all config files
template runNimScriptIfExists(path: AbsoluteFile) =
let p = path # eval once
if fileExists(p):
runNimScript(cache, p, freshDefines = false, conf)
# Caution: make sure this stays in sync with `loadConfigs`
if optSkipSystemConfigFile notin conf.globalOptions:
runNimScriptIfExists(getSystemConfigPath(conf, DefaultConfigNims))
if optSkipUserConfigFile notin conf.globalOptions:
runNimScriptIfExists(getUserConfigPath(DefaultConfigNims))
if optSkipParentConfigFiles notin conf.globalOptions:
for dir in parentDirs(conf.projectPath.string, fromRoot = true, inclusive = false):
runNimScriptIfExists(AbsoluteDir(dir) / DefaultConfigNims)
if optSkipProjConfigFile notin conf.globalOptions:
runNimScriptIfExists(conf.projectPath / DefaultConfigNims)
block:
if not self.suggestMode:
let scriptFile = conf.projectFull.changeFileExt("nims")
if not self.suggestMode:
runNimScriptIfExists(scriptFile)
# 'nim foo.nims' means to just run the NimScript file and do nothing more:
if fileExists(scriptFile) and scriptFile == conf.projectFull:
if conf.command == "":
conf.command = "e"
return false
elif conf.command.normalize == "e":
return false
else:
if scriptFile != conf.projectFull:
runNimScriptIfExists(scriptFile)
else:
# 'nimsuggest foo.nims' means to just auto-complete the NimScript file
discard
# 'nim foo.nims' means to just run the NimScript file and do nothing more:
if fileExists(scriptFile) and scriptFile == conf.projectFull:
if conf.command == "":
conf.command = "e"
return false
elif conf.command.normalize == "e":
return false
# now process command line arguments again, because some options in the
# command line can overwrite the config file's settings
@@ -93,7 +78,5 @@ proc loadConfigsAndRunMainCommand*(self: NimProg, cache: IdentCache; conf: Confi
if conf.command == "":
rawMessage(conf, errGenerated, "command missing")
let graph = newModuleGraph(cache, conf)
graph.suggestMode = self.suggestMode
self.mainCommand(graph)
return true

View File

@@ -18,7 +18,8 @@ template bootSwitch(name, expr, userString) =
bootSwitch(usedRelease, defined(release), "-d:release")
bootSwitch(usedDanger, defined(danger), "-d:danger")
bootSwitch(usedGnuReadline, defined(useLinenoise), "-d:useLinenoise")
# `useLinenoise` deprecated in favor of `nimUseLinenoise`, kept for backward compatibility
bootSwitch(useLinenoise, defined(nimUseLinenoise) or defined(useLinenoise), "-d:nimUseLinenoise")
bootSwitch(usedBoehm, defined(boehmgc), "--gc:boehm")
bootSwitch(usedMarkAndSweep, defined(gcmarkandsweep), "--gc:markAndSweep")
bootSwitch(usedGenerational, defined(gcgenerational), "--gc:generational")
@@ -31,6 +32,7 @@ import
pathutils, strtabs
from incremental import nimIncremental
from ast import eqTypeFlags, tfGcSafe, tfNoSideEffect
# but some have deps to imported modules. Yay.
bootSwitch(usedTinyC, hasTinyCBackend, "-d:tinyc")
@@ -51,15 +53,14 @@ const
"Copyright (c) 2006-" & copyrightYear & " by Andreas Rumpf\n"
proc genFeatureDesc[T: enum](t: typedesc[T]): string {.compileTime.} =
var x = ""
for f in low(T)..high(T):
if x.len > 0: x.add "|"
x.add $f
x
result = ""
for f in T:
if result.len > 0: result.add "|"
result.add $f
const
Usage = slurp"../doc/basicopt.txt".replace(" //", " ")
AdvancedUsage = slurp"../doc/advopt.txt".replace(" //", " ") % [genFeatureDesc(Feature), genFeatureDesc(LegacyFeature)]
Usage = slurp"../doc/basicopt.txt".replace(" //", " ")
AdvancedUsage = slurp"../doc/advopt.txt".replace(" //", " ") % [genFeatureDesc(Feature), genFeatureDesc(LegacyFeature)]
proc getCommandLineDesc(conf: ConfigRef): string =
result = (HelpMessage % [VersionAsString, platform.OS[conf.target.hostOS].name,
@@ -96,12 +97,12 @@ proc writeVersionInfo(conf: ConfigRef; pass: TCmdLinePass) =
CPU[conf.target.hostCPU].name, CompileDate]),
{msgStdout})
const gitHash = gorge("git log -n 1 --format=%H").strip
const gitHash {.strdefine.} = gorge("git log -n 1 --format=%H").strip
when gitHash.len == 40:
msgWriteln(conf, "git hash: " & gitHash, {msgStdout})
msgWriteln(conf, "active boot switches:" & usedRelease & usedDanger &
usedTinyC & usedGnuReadline & usedNativeStacktrace &
usedTinyC & useLinenoise & usedNativeStacktrace &
usedFFI & usedBoehm & usedMarkAndSweep & usedGenerational & usedGoGC & usedNoGC,
{msgStdout})
msgQuit(0)
@@ -110,7 +111,7 @@ proc writeCommandLineUsage*(conf: ConfigRef) =
msgWriteln(conf, getCommandLineDesc(conf), {msgStdout})
proc addPrefix(switch: string): string =
if len(switch) <= 1: result = "-" & switch
if switch.len <= 1: result = "-" & switch
else: result = "--" & switch
const
@@ -127,14 +128,14 @@ proc splitSwitch(conf: ConfigRef; switch: string, cmd, arg: var string, pass: TC
info: TLineInfo) =
cmd = ""
var i = 0
if i < len(switch) and switch[i] == '-': inc(i)
if i < len(switch) and switch[i] == '-': inc(i)
while i < len(switch):
if i < switch.len and switch[i] == '-': inc(i)
if i < switch.len and switch[i] == '-': inc(i)
while i < switch.len:
case switch[i]
of 'a'..'z', 'A'..'Z', '0'..'9', '_', '.': add(cmd, switch[i])
of 'a'..'z', 'A'..'Z', '0'..'9', '_', '.': cmd.add(switch[i])
else: break
inc(i)
if i >= len(switch): arg = ""
if i >= switch.len: arg = ""
# cmd:arg => (cmd,arg)
elif switch[i] in {':', '='}: arg = substr(switch, i + 1)
# cmd[sub]:rest => (cmd,[sub]:rest)
@@ -144,24 +145,24 @@ proc splitSwitch(conf: ConfigRef; switch: string, cmd, arg: var string, pass: TC
proc processOnOffSwitch(conf: ConfigRef; op: TOptions, arg: string, pass: TCmdLinePass,
info: TLineInfo) =
case arg.normalize
of "","on": conf.options = conf.options + op
of "off": conf.options = conf.options - op
of "", "on": conf.options.incl op
of "off": conf.options.excl op
else: localError(conf, info, errOnOrOffExpectedButXFound % arg)
proc processOnOffSwitchOrList(conf: ConfigRef; op: TOptions, arg: string, pass: TCmdLinePass,
info: TLineInfo): bool =
result = false
case arg.normalize
of "on": conf.options = conf.options + op
of "off": conf.options = conf.options - op
of "on": conf.options.incl op
of "off": conf.options.excl op
of "list": result = true
else: localError(conf, info, errOnOffOrListExpectedButXFound % arg)
proc processOnOffSwitchG(conf: ConfigRef; op: TGlobalOptions, arg: string, pass: TCmdLinePass,
info: TLineInfo) =
case arg.normalize
of "", "on": conf.globalOptions = conf.globalOptions + op
of "off": conf.globalOptions = conf.globalOptions - op
of "", "on": conf.globalOptions.incl op
of "off": conf.globalOptions.excl op
else: localError(conf, info, errOnOrOffExpectedButXFound % arg)
proc expectArg(conf: ConfigRef; switch, arg: string, pass: TCmdLinePass, info: TLineInfo) =
@@ -174,41 +175,53 @@ proc expectNoArg(conf: ConfigRef; switch, arg: string, pass: TCmdLinePass, info:
proc processSpecificNote*(arg: string, state: TSpecialWord, pass: TCmdLinePass,
info: TLineInfo; orig: string; conf: ConfigRef) =
var id = "" # arg = key:val or [key]:val; with val=on|off
var id = "" # arg = key or [key] or key:val or [key]:val; with val=on|off
var i = 0
var n = hintMin
var isBracket = false
if i < len(arg) and arg[i] == '[':
if i < arg.len and arg[i] == '[':
isBracket = true
inc(i)
while i < len(arg) and (arg[i] notin {':', '=', ']'}):
add(id, arg[i])
while i < arg.len and (arg[i] notin {':', '=', ']'}):
id.add(arg[i])
inc(i)
if isBracket:
if i < len(arg) and arg[i] == ']': inc(i)
if i < arg.len and arg[i] == ']': inc(i)
else: invalidCmdLineOption(conf, pass, orig, info)
if i < len(arg) and (arg[i] in {':', '='}): inc(i)
if i == arg.len: discard
elif i < arg.len and (arg[i] in {':', '='}): inc(i)
else: invalidCmdLineOption(conf, pass, orig, info)
if state == wHint:
let x = findStr(lineinfos.HintsToStr, id)
if x >= 0: n = TNoteKind(x + ord(hintMin))
let x = findStr(hintMin..hintMax, id, errUnknown)
if x != errUnknown: n = TNoteKind(x)
else: localError(conf, info, "unknown hint: " & id)
else:
let x = findStr(lineinfos.WarningsToStr, id)
if x >= 0: n = TNoteKind(x + ord(warnMin))
let x = findStr(warnMin..warnMax, id, errUnknown)
if x != errUnknown: n = TNoteKind(x)
else: localError(conf, info, "unknown warning: " & id)
case substr(arg, i).normalize
of "on":
incl(conf.notes, n)
incl(conf.mainPackageNotes, n)
incl(conf.enableNotes, n)
of "off":
excl(conf.notes, n)
excl(conf.mainPackageNotes, n)
incl(conf.disableNotes, n)
excl(conf.foreignPackageNotes, n)
else: localError(conf, info, errOnOrOffExpectedButXFound % arg)
var val = substr(arg, i).normalize
if val == "": val = "on"
if val notin ["on", "off"]:
localError(conf, info, errOnOrOffExpectedButXFound % arg)
elif n notin conf.cmdlineNotes or pass == passCmd1:
if pass == passCmd1: incl(conf.cmdlineNotes, n)
incl(conf.modifiedyNotes, n)
case val
of "on":
if state == wWarningAsError:
incl(conf.warningAsErrors, n)
else:
incl(conf.notes, n)
incl(conf.mainPackageNotes, n)
of "off":
if state == wWarningAsError:
excl(conf.warningAsErrors, n)
else:
excl(conf.notes, n)
excl(conf.mainPackageNotes, n)
excl(conf.foreignPackageNotes, n)
proc processCompile(conf: ConfigRef; filename: string) =
var found = findFile(conf, filename)
@@ -216,22 +229,25 @@ proc processCompile(conf: ConfigRef; filename: string) =
extccomp.addExternalFileToCompile(conf, found)
const
errNoneBoehmRefcExpectedButXFound = "'none', 'boehm' or 'refc' expected, but '$1' found"
errNoneBoehmRefcExpectedButXFound = "'arc', 'orc', 'markAndSweep', 'boehm', 'go', 'none', 'regions', or 'refc' expected, but '$1' found"
errNoneSpeedOrSizeExpectedButXFound = "'none', 'speed' or 'size' expected, but '$1' found"
errGuiConsoleOrLibExpectedButXFound = "'gui', 'console' or 'lib' expected, but '$1' found"
errInvalidExceptionSystem = "'goto', 'setjump', 'cpp' or 'quirky' expected, but '$1' found"
proc testCompileOptionArg*(conf: ConfigRef; switch, arg: string, info: TLineInfo): bool =
case switch.normalize
of "gc":
case arg.normalize
of "boehm": result = conf.selectedGC == gcBoehm
of "refc": result = conf.selectedGC == gcRefc
of "v2": result = false
of "boehm": result = conf.selectedGC == gcBoehm
of "refc": result = conf.selectedGC == gcRefc
of "v2": result = false
of "markandsweep": result = conf.selectedGC == gcMarkAndSweep
of "generational": result = false
of "destructors": result = conf.selectedGC == gcDestructors
of "go": result = conf.selectedGC == gcGo
of "none": result = conf.selectedGC == gcNone
of "destructors", "arc": result = conf.selectedGC == gcArc
of "orc": result = conf.selectedGC == gcOrc
of "hooks": result = conf.selectedGC == gcHooks
of "go": result = conf.selectedGC == gcGo
of "none": result = conf.selectedGC == gcNone
of "stack", "regions": result = conf.selectedGC == gcRegions
else: localError(conf, info, errNoneBoehmRefcExpectedButXFound % arg)
of "opt":
@@ -243,15 +259,22 @@ proc testCompileOptionArg*(conf: ConfigRef; switch, arg: string, info: TLineInfo
of "verbosity": result = $conf.verbosity == arg
of "app":
case arg.normalize
of "gui": result = contains(conf.globalOptions, optGenGuiApp)
of "console": result = not contains(conf.globalOptions, optGenGuiApp)
of "lib": result = contains(conf.globalOptions, optGenDynLib) and
of "gui": result = contains(conf.globalOptions, optGenGuiApp)
of "console": result = not contains(conf.globalOptions, optGenGuiApp)
of "lib": result = contains(conf.globalOptions, optGenDynLib) and
not contains(conf.globalOptions, optGenGuiApp)
of "staticlib": result = contains(conf.globalOptions, optGenStaticLib) and
not contains(conf.globalOptions, optGenGuiApp)
else: localError(conf, info, errGuiConsoleOrLibExpectedButXFound % arg)
of "dynliboverride":
result = isDynlibOverride(conf, arg)
of "exceptions":
case arg.normalize
of "cpp": result = conf.exc == excCpp
of "setjmp": result = conf.exc == excSetjmp
of "quirky": result = conf.exc == excQuirky
of "goto": result = conf.exc == excGoto
else: localError(conf, info, errInvalidExceptionSystem % arg)
else: invalidCmdLineOption(conf, passCmd1, switch, info)
proc testCompileOption*(conf: ConfigRef; switch: string, info: TLineInfo): bool =
@@ -265,6 +288,7 @@ proc testCompileOption*(conf: ConfigRef; switch: string, info: TLineInfo): bool
of "hints": result = contains(conf.options, optHints)
of "threadanalysis": result = contains(conf.globalOptions, optThreadAnalysis)
of "stacktrace": result = contains(conf.options, optStackTrace)
of "stacktracemsgs": result = contains(conf.options, optStackTraceMsgs)
of "linetrace": result = contains(conf.options, optLineTrace)
of "debugger": result = contains(conf.globalOptions, optCDebug)
of "profiler": result = contains(conf.options, optProfiler)
@@ -274,13 +298,14 @@ proc testCompileOption*(conf: ConfigRef; switch: string, info: TLineInfo): bool
result = conf.options * {optNaNCheck, optInfCheck} == {optNaNCheck, optInfCheck}
of "infchecks": result = contains(conf.options, optInfCheck)
of "nanchecks": result = contains(conf.options, optNaNCheck)
of "nilchecks": result = contains(conf.options, optNilCheck)
of "nilchecks": result = false # not a thing
of "objchecks": result = contains(conf.options, optObjCheck)
of "fieldchecks": result = contains(conf.options, optFieldCheck)
of "rangechecks": result = contains(conf.options, optRangeCheck)
of "boundchecks": result = contains(conf.options, optBoundsCheck)
of "refchecks": result = contains(conf.options, optRefCheck)
of "overflowchecks": result = contains(conf.options, optOverflowCheck)
of "staticboundchecks": result = contains(conf.options, optStaticBoundsCheck)
of "stylechecks": result = contains(conf.options, optStyleCheck)
of "linedir": result = contains(conf.options, optLineDir)
of "assertions", "a": result = contains(conf.options, optAssert)
@@ -294,7 +319,6 @@ proc testCompileOption*(conf: ConfigRef; switch: string, info: TLineInfo): bool
of "patterns", "trmacros": result = contains(conf.options, optTrMacros)
of "excessivestacktrace": result = contains(conf.globalOptions, optExcessiveStackTrace)
of "nilseqs": result = contains(conf.options, optNilSeqs)
of "oldast": result = contains(conf.options, optOldAst)
else: invalidCmdLineOption(conf, passCmd1, switch, info)
proc processPath(conf: ConfigRef; path: string, info: TLineInfo,
@@ -359,6 +383,27 @@ proc dynlibOverride(conf: ConfigRef; switch, arg: string, pass: TCmdLinePass, in
expectArg(conf, switch, arg, pass, info)
options.inclDynlibOverride(conf, arg)
proc handleStdinInput*(conf: ConfigRef) =
conf.projectName = "stdinfile"
conf.projectFull = conf.projectName.AbsoluteFile
conf.projectPath = AbsoluteDir getCurrentDir()
conf.projectIsStdin = true
if conf.outDir.isEmpty:
conf.outDir = getNimcacheDir(conf)
proc specialDefine(conf: ConfigRef, key: string) =
# Keep this syncronized with the default config/nim.cfg!
if cmpIgnoreStyle(key, "nimQuirky") == 0:
conf.exc = excQuirky
elif cmpIgnoreStyle(key, "release") == 0 or cmpIgnoreStyle(key, "danger") == 0:
conf.options.excl {optStackTrace, optLineTrace, optLineDir, optOptimizeSize}
conf.globalOptions.excl {optExcessiveStackTrace, optCDebug}
conf.options.incl optOptimizeSpeed
if cmpIgnoreStyle(key, "danger") == 0 or cmpIgnoreStyle(key, "quick") == 0:
conf.options.excl {optObjCheck, optFieldCheck, optRangeCheck, optBoundsCheck,
optOverflowCheck, optAssert, optStackTrace, optLineTrace, optLineDir}
conf.globalOptions.excl {optCDebug}
proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
conf: ConfigRef) =
var
@@ -366,8 +411,9 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
case switch.normalize
of "path", "p":
expectArg(conf, switch, arg, pass, info)
addPath(conf, if pass == passPP: processCfgPath(conf, arg, info)
else: processPath(conf, arg, info), info)
for path in nimbleSubs(conf, arg):
addPath(conf, if pass == passPP: processCfgPath(conf, path, info)
else: processPath(conf, path, info), info)
of "nimblepath", "babelpath":
# keep the old name for compat
if pass in {passCmd2, passPP} and optNoNimblePath notin conf.globalOptions:
@@ -399,17 +445,28 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
of "outdir":
expectArg(conf, switch, arg, pass, info)
conf.outDir = processPath(conf, arg, info, notRelativeToProj=true)
of "usenimcache":
processOnOffSwitchG(conf, {optUseNimcache}, arg, pass, info)
of "docseesrcurl":
expectArg(conf, switch, arg, pass, info)
conf.docSeeSrcUrl = arg
of "docroot":
conf.docRoot = if arg.len == 0: docRootDefault else: arg
of "backend", "b":
let backend = parseEnum(arg.normalize, TBackend.default)
if backend == TBackend.default: localError(conf, info, "invalid backend: '$1'" % arg)
conf.backend = backend
of "doccmd": conf.docCmd = arg
of "mainmodule", "m":
discard "allow for backwards compatibility, but don't do anything"
of "define", "d":
expectArg(conf, switch, arg, pass, info)
if {':', '='} in arg:
splitSwitch(conf, arg, key, val, pass, info)
specialDefine(conf, key)
defineSymbol(conf.symbols, key, val)
else:
specialDefine(conf, arg)
defineSymbol(conf.symbols, arg)
of "undef", "u":
expectArg(conf, switch, arg, pass, info)
@@ -437,14 +494,20 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
of "forcebuild", "f":
processOnOffSwitchG(conf, {optForceFullMake}, arg, pass, info)
of "project":
processOnOffSwitchG(conf, {optWholeProject}, arg, pass, info)
processOnOffSwitchG(conf, {optWholeProject, optGenIndex}, arg, pass, info)
of "gc":
if conf.backend == backendJs or conf.command == "js":
# for: bug #16033
# This might still be imperfect, in rarse corner cases
# (where command is reset in nimscript, maybe).
return
expectArg(conf, switch, arg, pass, info)
if pass in {passCmd2, passPP}:
case arg.normalize
of "boehm":
conf.selectedGC = gcBoehm
defineSymbol(conf.symbols, "boehmgc")
incl conf.globalOptions, optTlsEmulation # Boehm GC doesn't scan the real TLS
of "refc":
conf.selectedGC = gcRefc
of "v2":
@@ -452,9 +515,31 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
of "markandsweep":
conf.selectedGC = gcMarkAndSweep
defineSymbol(conf.symbols, "gcmarkandsweep")
of "destructors":
conf.selectedGC = gcDestructors
of "destructors", "arc":
conf.selectedGC = gcArc
defineSymbol(conf.symbols, "gcdestructors")
defineSymbol(conf.symbols, "gcarc")
incl conf.globalOptions, optSeqDestructors
incl conf.globalOptions, optTinyRtti
if pass in {passCmd2, passPP}:
defineSymbol(conf.symbols, "nimSeqsV2")
defineSymbol(conf.symbols, "nimV2")
of "orc":
conf.selectedGC = gcOrc
defineSymbol(conf.symbols, "gcdestructors")
defineSymbol(conf.symbols, "gcorc")
incl conf.globalOptions, optSeqDestructors
incl conf.globalOptions, optTinyRtti
if pass in {passCmd2, passPP}:
defineSymbol(conf.symbols, "nimSeqsV2")
defineSymbol(conf.symbols, "nimV2")
of "hooks":
conf.selectedGC = gcHooks
defineSymbol(conf.symbols, "gchooks")
incl conf.globalOptions, optSeqDestructors
processOnOffSwitchG(conf, {optSeqDestructors}, arg, pass, info)
if pass in {passCmd2, passPP}:
defineSymbol(conf.symbols, "nimSeqsV2")
of "go":
conf.selectedGC = gcGo
defineSymbol(conf.symbols, "gogc")
@@ -462,17 +547,19 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
conf.selectedGC = gcNone
defineSymbol(conf.symbols, "nogc")
of "stack", "regions":
conf.selectedGC= gcRegions
conf.selectedGC = gcRegions
defineSymbol(conf.symbols, "gcregions")
else: localError(conf, info, errNoneBoehmRefcExpectedButXFound % arg)
of "warnings", "w":
if processOnOffSwitchOrList(conf, {optWarns}, arg, pass, info): listWarnings(conf)
of "warning": processSpecificNote(arg, wWarning, pass, info, switch, conf)
of "hint": processSpecificNote(arg, wHint, pass, info, switch, conf)
of "warningaserror": processSpecificNote(arg, wWarningAsError, pass, info, switch, conf)
of "hints":
if processOnOffSwitchOrList(conf, {optHints}, arg, pass, info): listHints(conf)
of "threadanalysis": processOnOffSwitchG(conf, {optThreadAnalysis}, arg, pass, info)
of "stacktrace": processOnOffSwitch(conf, {optStackTrace}, arg, pass, info)
of "stacktracemsgs": processOnOffSwitch(conf, {optStackTraceMsgs}, arg, pass, info)
of "excessivestacktrace": processOnOffSwitchG(conf, {optExcessiveStackTrace}, arg, pass, info)
of "linetrace": processOnOffSwitch(conf, {optLineTrace}, arg, pass, info)
of "debugger":
@@ -509,38 +596,27 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
else:
undefSymbol(conf.symbols, "hotcodereloading")
undefSymbol(conf.symbols, "useNimRtl")
of "oldnewlines":
case arg.normalize
of "","on":
conf.oldNewlines = true
defineSymbol(conf.symbols, "nimOldNewlines")
of "off":
conf.oldNewlines = false
undefSymbol(conf.symbols, "nimOldNewlines")
else:
localError(conf, info, errOnOrOffExpectedButXFound % arg)
of "laxstrings": processOnOffSwitch(conf, {optLaxStrings}, arg, pass, info)
of "nilseqs": processOnOffSwitch(conf, {optNilSeqs}, arg, pass, info)
of "oldast": processOnOffSwitch(conf, {optOldAst}, arg, pass, info)
of "checks", "x": processOnOffSwitch(conf, ChecksOptions, arg, pass, info)
of "floatchecks":
processOnOffSwitch(conf, {optNaNCheck, optInfCheck}, arg, pass, info)
of "infchecks": processOnOffSwitch(conf, {optInfCheck}, arg, pass, info)
of "nanchecks": processOnOffSwitch(conf, {optNaNCheck}, arg, pass, info)
of "nilchecks": processOnOffSwitch(conf, {optNilCheck}, arg, pass, info)
of "nilchecks": discard "no such thing anymore"
of "objchecks": processOnOffSwitch(conf, {optObjCheck}, arg, pass, info)
of "fieldchecks": processOnOffSwitch(conf, {optFieldCheck}, arg, pass, info)
of "rangechecks": processOnOffSwitch(conf, {optRangeCheck}, arg, pass, info)
of "boundchecks": processOnOffSwitch(conf, {optBoundsCheck}, arg, pass, info)
of "refchecks": processOnOffSwitch(conf, {optRefCheck}, arg, pass, info)
of "overflowchecks": processOnOffSwitch(conf, {optOverflowCheck}, arg, pass, info)
of "staticboundchecks": processOnOffSwitch(conf, {optStaticBoundsCheck}, arg, pass, info)
of "stylechecks": processOnOffSwitch(conf, {optStyleCheck}, arg, pass, info)
of "linedir": processOnOffSwitch(conf, {optLineDir}, arg, pass, info)
of "assertions", "a": processOnOffSwitch(conf, {optAssert}, arg, pass, info)
of "deadcodeelim": discard # deprecated, dead code elim always on
of "threads":
processOnOffSwitchG(conf, {optThreads}, arg, pass, info)
#if optThreads in conf.globalOptions: incl(conf.notes, warnGcUnsafe)
#if optThreads in conf.globalOptions: conf.setNote(warnGcUnsafe)
of "tlsemulation": processOnOffSwitchG(conf, {optTlsEmulation}, arg, pass, info)
of "taintmode": processOnOffSwitchG(conf, {optTaintMode}, arg, pass, info)
of "implicitstatic":
@@ -613,6 +689,8 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
conf.implicitIncludes.add findModule(conf, arg, toFullPath(conf, info)).string
of "listcmd":
processOnOffSwitchG(conf, {optListCmd}, arg, pass, info)
of "asm":
processOnOffSwitchG(conf, {optProduceAsm}, arg, pass, info)
of "genmapping":
processOnOffSwitchG(conf, {optGenMapping}, arg, pass, info)
of "os":
@@ -633,6 +711,9 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
setTarget(conf.target, conf.target.targetOS, cpu)
of "run", "r":
processOnOffSwitchG(conf, {optRun}, arg, pass, info)
of "maxloopiterationsvm":
expectArg(conf, switch, arg, pass, info)
conf.maxLoopIterationsVM = parseInt(arg)
of "errormax":
expectArg(conf, switch, arg, pass, info)
# Note: `nim check` (etc) can overwrite this.
@@ -647,9 +728,10 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
if verbosity notin {0..3}:
localError(conf, info, "invalid verbosity level: '$1'" % arg)
conf.verbosity = verbosity
conf.notes = NotesVerbosity[conf.verbosity]
incl(conf.notes, conf.enableNotes)
excl(conf.notes, conf.disableNotes)
var verb = NotesVerbosity[conf.verbosity]
## We override the default `verb` by explicitly modified (set/unset) notes.
conf.notes = (conf.modifiedyNotes * conf.notes + verb) -
(conf.modifiedyNotes * verb - conf.notes)
conf.mainPackageNotes = conf.notes
of "parallelbuild":
expectArg(conf, switch, arg, pass, info)
@@ -748,8 +830,15 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
localError(conf, info, "unknown obsolete feature")
of "nocppexceptions":
expectNoArg(conf, switch, arg, pass, info)
incl(conf.globalOptions, optNoCppExceptions)
conf.exc = low(ExceptionSystem)
defineSymbol(conf.symbols, "noCppExceptions")
of "exceptions":
case arg.normalize
of "cpp": conf.exc = excCpp
of "setjmp": conf.exc = excSetjmp
of "quirky": conf.exc = excQuirky
of "goto": conf.exc = excGoto
else: localError(conf, info, errInvalidExceptionSystem % arg)
of "cppdefine":
expectArg(conf, switch, arg, pass, info)
if conf != nil:
@@ -763,13 +852,20 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
incl(conf.globalOptions, optOwnedRefs)
incl(conf.globalOptions, optSeqDestructors)
defineSymbol(conf.symbols, "nimV2")
conf.selectedGC = gcDestructors
defineSymbol(conf.symbols, "gcdestructors")
conf.selectedGC = gcHooks
defineSymbol(conf.symbols, "gchooks")
defineSymbol(conf.symbols, "nimSeqsV2")
defineSymbol(conf.symbols, "nimOwnedEnabled")
of "seqsv2":
processOnOffSwitchG(conf, {optSeqDestructors}, arg, pass, info)
if pass in {passCmd2, passPP}:
defineSymbol(conf.symbols, "nimSeqsV2")
of "stylecheck":
case arg.normalize
of "off": conf.globalOptions = conf.globalOptions - {optStyleHint, optStyleError}
of "hint": conf.globalOptions = conf.globalOptions + {optStyleHint}
of "hint": conf.globalOptions = conf.globalOptions + {optStyleHint} - {optStyleError}
of "error": conf.globalOptions = conf.globalOptions + {optStyleError}
of "usages": conf.globalOptions.incl optStyleUsages
else: localError(conf, info, errOffHintsError % arg)
of "showallmismatches":
processOnOffSwitchG(conf, {optShowAllMismatches}, arg, pass, info)
@@ -786,23 +882,54 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
of "expandmacro":
expectArg(conf, switch, arg, pass, info)
conf.macrosToExpand[arg] = "T"
of "oldgensym":
processOnOffSwitchG(conf, {optNimV019}, arg, pass, info)
of "expandarc":
expectArg(conf, switch, arg, pass, info)
conf.arcToExpand[arg] = "T"
of "useversion":
expectArg(conf, switch, arg, pass, info)
case arg
of "1.0":
discard "the default"
defineSymbol(conf.symbols, "NimMajor", "1")
defineSymbol(conf.symbols, "NimMinor", "0")
# always be compatible with 1.0.100:
defineSymbol(conf.symbols, "NimPatch", "100")
# old behaviors go here:
defineSymbol(conf.symbols, "nimOldRelativePathBehavior")
undefSymbol(conf.symbols, "nimDoesntTrackDefects")
ast.eqTypeFlags.excl {tfGcSafe, tfNoSideEffect}
conf.globalOptions.incl optNimV1Emulation
of "1.2":
defineSymbol(conf.symbols, "NimMajor", "1")
defineSymbol(conf.symbols, "NimMinor", "2")
# always be compatible with 1.2.100:
defineSymbol(conf.symbols, "NimPatch", "100")
conf.globalOptions.incl optNimV12Emulation
else:
localError(conf, info, "unknown Nim version; currently supported values are: {1.0}")
of "":
conf.projectName = "-"
of "benchmarkvm":
processOnOffSwitchG(conf, {optBenchmarkVM}, arg, pass, info)
of "profilevm":
processOnOffSwitchG(conf, {optProfileVM}, arg, pass, info)
of "sinkinference":
processOnOffSwitch(conf, {optSinkInference}, arg, pass, info)
of "cursorinference":
# undocumented, for debugging purposes only:
processOnOffSwitch(conf, {optCursorInference}, arg, pass, info)
of "panics":
processOnOffSwitchG(conf, {optPanics}, arg, pass, info)
if optPanics in conf.globalOptions:
defineSymbol(conf.symbols, "nimPanics")
of "sourcemap":
conf.globalOptions.incl optSourcemap
conf.options.incl optLineDir
of "deepcopy":
processOnOffSwitchG(conf, {optEnableDeepCopy}, arg, pass, info)
of "": # comes from "-" in for example: `nim c -r -` (gets stripped from -)
handleStdinInput(conf)
else:
if strutils.find(switch, '.') >= 0: options.setConfigVar(conf, switch, arg)
else: invalidCmdLineOption(conf, pass, switch, info)
template gCmdLineInfo*(): untyped = newLineInfo(commandLineIdx, 1, 1)
proc processCommand*(switch: string, pass: TCmdLinePass; config: ConfigRef) =
var cmd, arg: string
splitSwitch(config, switch, cmd, arg, pass, gCmdLineInfo)

View File

@@ -13,7 +13,7 @@ import
strtabs
from options import Feature
from lineinfos import HintsToStr, WarningsToStr
from lineinfos import hintMin, hintMax, warnMin, warnMax
proc defineSymbol*(symbols: StringTableRef; symbol: string, value: string = "true") =
symbols[symbol] = value
@@ -48,13 +48,11 @@ proc initDefines*(symbols: StringTableRef) =
defineSymbol("nimalias")
defineSymbol("nimlocks")
defineSymbol("nimnode")
defineSymbol("nimnomagic64")
defineSymbol("nimvarargstyped")
defineSymbol("nimtypedescfixed")
defineSymbol("nimKnowsNimvm")
defineSymbol("nimArrIdx")
defineSymbol("nimHasalignOf")
defineSymbol("nimNewShiftOps")
defineSymbol("nimDistros")
defineSymbol("nimHasCppDefine")
defineSymbol("nimGenericInOutFlags")
@@ -88,15 +86,41 @@ proc initDefines*(symbols: StringTableRef) =
defineSymbol("nimMacrosSizealignof")
defineSymbol("nimNoZeroExtendMagic")
defineSymbol("nimMacrosGetNodeId")
for f in low(Feature)..high(Feature):
for f in Feature:
defineSymbol("nimHas" & $f)
for s in WarningsToStr:
defineSymbol("nimHasWarning" & s)
for s in HintsToStr:
defineSymbol("nimHasHint" & s)
for s in warnMin..warnMax:
defineSymbol("nimHasWarning" & $s)
for s in hintMin..hintMax:
defineSymbol("nimHasHint" & $s)
defineSymbol("nimFixedOwned")
defineSymbol("nimHasStyleChecks")
defineSymbol("nimToOpenArrayCString")
defineSymbol("nimHasUsed")
defineSymbol("nimFixedForwardGeneric")
defineSymbol("nimnomagic64")
defineSymbol("nimNewShiftOps")
defineSymbol("nimHasCursor")
defineSymbol("nimAlignPragma")
defineSymbol("nimHasExceptionsQuery")
defineSymbol("nimHasIsNamedTuple")
defineSymbol("nimHashOrdinalFixed")
when defined(nimHasLibFFI):
# Renaming as we can't conflate input vs output define flags; e.g. this
# will report the right thing regardless of whether user adds
# `-d:nimHasLibFFI` in his user config.
defineSymbol("nimHasLibFFIEnabled")
defineSymbol("nimHasSinkInference")
defineSymbol("nimNewIntegerOps")
defineSymbol("nimHasInvariant")
defineSymbol("nimHasStacktraceMsgs")
defineSymbol("nimDoesntTrackDefects")
defineSymbol("nimHasLentIterators")
defineSymbol("nimHasDeclaredMagic")
defineSymbol("nimHasStacktracesModule")
defineSymbol("nimHasEffectTraitsModule")
defineSymbol("nimHasCastPragmaBlocks")
defineSymbol("nimHasJsBigIntBackend")

View File

@@ -1,6 +0,0 @@
## Use the module 'lineinfos' instead!
{.deprecated.}
import lineinfos
export lineinfos

View File

@@ -25,7 +25,7 @@ type
dotGraph: Rope
proc addDependencyAux(b: Backend; importing, imported: string) =
addf(b.dotGraph, "$1 -> \"$2\";$n", [rope(importing), rope(imported)])
b.dotGraph.addf("$1 -> \"$2\";$n", [rope(importing), rope(imported)])
# s1 -> s2_4[label="[0-9]"];
proc addDotDependency(c: PPassContext, n: PNode): PNode =
@@ -34,14 +34,14 @@ proc addDotDependency(c: PPassContext, n: PNode): PNode =
let b = Backend(g.graph.backend)
case n.kind
of nkImportStmt:
for i in 0 ..< len(n):
var imported = getModuleName(g.config, n.sons[i])
for i in 0..<n.len:
var imported = getModuleName(g.config, n[i])
addDependencyAux(b, g.module.name.s, imported)
of nkFromStmt, nkImportExceptStmt:
var imported = getModuleName(g.config, n.sons[0])
var imported = getModuleName(g.config, n[0])
addDependencyAux(b, g.module.name.s, imported)
of nkStmtList, nkBlockStmt, nkStmtListExpr, nkBlockExpr:
for i in 0 ..< len(n): discard addDotDependency(c, n.sons[i])
for i in 0..<n.len: discard addDotDependency(c, n[i])
else:
discard
@@ -51,7 +51,10 @@ proc generateDot*(graph: ModuleGraph; project: AbsoluteFile) =
rope(project.splitFile.name), b.dotGraph],
changeFileExt(project, "dot"))
proc myOpen(graph: ModuleGraph; module: PSym): PPassContext =
when not defined(nimHasSinkInference):
{.pragma: nosinks.}
proc myOpen(graph: ModuleGraph; module: PSym): PPassContext {.nosinks.} =
var g: PGen
new(g)
g.module = module

View File

@@ -29,47 +29,45 @@
## "A GraphFree Approach to DataFlow Analysis" by Markus Mohnen.
## https://link.springer.com/content/pdf/10.1007/3-540-45937-5_6.pdf
import ast, types, intsets, lineinfos, renderer
import ast, types, intsets, lineinfos, renderer, asciitables
from patterns import sameTrees
type
InstrKind* = enum
goto, fork, join, def, use
goto, fork, def, use
Instr* = object
n*: PNode
n*: PNode # contains the def/use location.
case kind*: InstrKind
of def, use: sym*: PSym # 'sym' can also be 'nil' and
# then 'n' contains the def/use location.
# This is used so that we can track object
# and tuple field accesses precisely.
of goto, fork, join: dest*: int
of goto, fork: dest*: int
else: discard
ControlFlowGraph* = seq[Instr]
TPosition = distinct int
TBlock = object
label: PSym
fixups: seq[TPosition]
case isTryBlock: bool
of false:
label: PSym
breakFixups: seq[(TPosition, seq[PNode])] #Contains the gotos for the breaks along with their pending finales
of true:
finale: PNode
raiseFixups: seq[TPosition] #Contains the gotos for the raises
Con = object
code: ControlFlowGraph
inCall, inTryStmt: int
inTryStmt: int
blocks: seq[TBlock]
tryStmtFixups: seq[TPosition]
forks: seq[TPosition]
owner: PSym
proc debugInfo(info: TLineInfo): string =
result = $info.line #info.toFilename & ":" & $info.line
proc codeListing(c: ControlFlowGraph, result: var string, start=0; last = -1) =
proc codeListing(c: ControlFlowGraph, start = 0; last = -1): string =
# for debugging purposes
# first iteration: compute all necessary labels:
var jumpTargets = initIntSet()
let last = if last < 0: c.len-1 else: min(last, c.len-1)
for i in start..last:
if c[i].kind in {goto, fork, join}:
if c[i].kind in {goto, fork}:
jumpTargets.incl(i+c[i].dest)
var i = start
while i <= last:
@@ -80,27 +78,22 @@ proc codeListing(c: ControlFlowGraph, result: var string, start=0; last = -1) =
case c[i].kind
of def, use:
result.add renderTree(c[i].n)
of goto, fork, join:
of goto, fork:
result.add "L"
result.addInt c[i].dest+i
result.add("\t#")
result.add(debugInfo(c[i].n.info))
result.add($c[i].n.info.line)
result.add("\n")
inc i
if i in jumpTargets: result.add("L" & $i & ": End\n")
# consider calling `asciitables.alignTable`
proc echoCfg*(c: ControlFlowGraph; start=0; last = -1) {.deprecated.} =
proc echoCfg*(c: ControlFlowGraph; start = 0; last = -1) {.deprecated.} =
## echos the ControlFlowGraph for debugging purposes.
var buf = ""
codeListing(c, buf, start, last)
when declared(echo):
echo buf
echo codeListing(c, start, last).alignTable
proc forkI(c: var Con; n: PNode): TPosition =
result = TPosition(c.code.len)
c.code.add Instr(n: n, kind: fork, dest: 0)
c.forks.add result
proc gotoI(c: var Con; n: PNode): TPosition =
result = TPosition(c.code.len)
@@ -108,6 +101,24 @@ proc gotoI(c: var Con; n: PNode): TPosition =
#[
Join is no more
===============
Instead of generating join instructions we adapt our traversal of the CFG.
When encountering a fork we split into two paths, we follow the path
starting at "pc + 1" until it encounters the joinpoint: "pc + forkInstr.dest".
If we encounter gotos that would jump further than the current joinpoint,
as can happen with gotos generated by unstructured controlflow such as break, raise or return,
we simply suspend following the current path, and follow the other path until the new joinpoint
which is simply the instruction pointer returned to us by the now suspended path.
If the path we are following now, also encounters a goto that exceeds the joinpoint
we repeat the process; suspending the current path and evaluating the other one with a new joinpoint.
If we eventually reach a common joinpoint we join the two paths.
This new "ping-pong" approach has the obvious advantage of not requiring join instructions, as such
cutting down on the CFG size but is also mandatory for correctly handling complicated cases
of unstructured controlflow.
Design of join
==============
@@ -256,33 +267,36 @@ duplicate the 'join' instructions on breaks and return exits!
]#
proc joinI(c: var Con; fromFork: TPosition; n: PNode) =
let dist = fromFork.int - c.code.len
c.code.add Instr(n: n, kind: join, dest: dist)
proc genLabel(c: Con): TPosition = TPosition(c.code.len)
proc genLabel(c: Con): TPosition =
result = TPosition(c.code.len)
template checkedDistance(dist): int =
doAssert low(int) div 2 + 1 < dist and dist < high(int) div 2
dist
proc jmpBack(c: var Con, n: PNode, p = TPosition(0)) =
let dist = p.int - c.code.len
doAssert(low(int) div 2 + 1 < dist and dist < high(int) div 2)
c.code.add Instr(n: n, kind: goto, dest: dist)
c.code.add Instr(n: n, kind: goto, dest: checkedDistance(p.int - c.code.len))
proc patch(c: var Con, p: TPosition) =
# patch with current index
let p = p.int
let diff = c.code.len - p
doAssert(low(int) div 2 + 1 < diff and diff < high(int) div 2)
c.code[p].dest = diff
c.code[p.int].dest = checkedDistance(c.code.len - p.int)
proc gen(c: var Con; n: PNode)
proc popBlock(c: var Con; oldLen: int) =
for f in c.blocks[oldLen].fixups:
c.patch(f)
var exits: seq[TPosition]
exits.add c.gotoI(newNode(nkEmpty))
for f in c.blocks[oldLen].breakFixups:
c.patch(f[0])
for finale in f[1]:
c.gen(finale)
exits.add c.gotoI(newNode(nkEmpty))
for e in exits:
c.patch e
c.blocks.setLen(oldLen)
template withBlock(labl: PSym; body: untyped) {.dirty.} =
var oldLen {.gensym.} = c.blocks.len
c.blocks.add TBlock(label: labl, fixups: @[])
template withBlock(labl: PSym; body: untyped) =
let oldLen = c.blocks.len
c.blocks.add TBlock(isTryBlock: false, label: labl)
body
popBlock(c, oldLen)
@@ -290,8 +304,6 @@ proc isTrue(n: PNode): bool =
n.kind == nkSym and n.sym.kind == skEnumField and n.sym.position != 0 or
n.kind == nkIntLit and n.intVal != 0
proc gen(c: var Con; n: PNode) # {.noSideEffect.}
when true:
proc genWhile(c: var Con; n: PNode) =
# We unroll every loop 3 times. We emulate 0, 1, 2 iterations
@@ -303,12 +315,13 @@ when true:
Becomes:
if cond:
body
block:
if cond:
body
if cond:
body
if cond:
body
We still need to ensure 'break' resolves properly, so an AST to AST
translation is impossible.
@@ -331,28 +344,23 @@ when true:
L4:
join F1
]#
if isTrue(n.sons[0]):
if isTrue(n[0]):
# 'while true' is an idiom in Nim and so we produce
# better code for it:
for i in 0..2:
withBlock(nil):
c.gen(n.sons[1])
withBlock(nil):
for i in 0..2:
c.gen(n[1])
else:
let oldForksLen = c.forks.len
var endings: array[3, TPosition]
for i in 0..2:
withBlock(nil):
c.gen(n.sons[0])
withBlock(nil):
var endings: array[3, TPosition]
for i in 0..2:
c.gen(n[0])
endings[i] = c.forkI(n)
c.gen(n.sons[1])
for i in countdown(endings.high, 0):
let endPos = endings[i]
c.patch(endPos)
c.joinI(c.forks.pop(), n)
doAssert(c.forks.len == oldForksLen)
c.gen(n[1])
for i in countdown(endings.high, 0):
c.patch(endings[i])
else:
proc genWhile(c: var Con; n: PNode) =
# lab1:
# cond, tmp
@@ -360,47 +368,21 @@ else:
# body
# jmp lab1
# lab2:
let oldForksLen = c.forks.len
let lab1 = c.genLabel
withBlock(nil):
if isTrue(n.sons[0]):
c.gen(n.sons[1])
if isTrue(n[0]):
c.gen(n[1])
c.jmpBack(n, lab1)
else:
c.gen(n.sons[0])
let lab2 = c.forkI(n)
c.gen(n.sons[1])
c.jmpBack(n, lab1)
c.patch(lab2)
setLen(c.forks, oldForksLen)
proc genBlock(c: var Con; n: PNode) =
withBlock(n.sons[0].sym):
c.gen(n.sons[1])
proc genJoins(c: var Con; n: PNode) =
for i in countdown(c.forks.high, 0): joinI(c, c.forks[i], n)
proc genBreak(c: var Con; n: PNode) =
genJoins(c, n)
let lab1 = c.gotoI(n)
if n.sons[0].kind == nkSym:
#echo cast[int](n.sons[0].sym)
for i in countdown(c.blocks.len-1, 0):
if c.blocks[i].label == n.sons[0].sym:
c.blocks[i].fixups.add lab1
return
#globalError(n.info, "VM problem: cannot find 'break' target")
else:
c.blocks[c.blocks.high].fixups.add lab1
c.gen(n[0])
forkT(n):
c.gen(n[1])
c.jmpBack(n, lab1)
template forkT(n, body) =
let oldLen = c.forks.len
let lab1 = c.forkI(n)
body
c.patch(lab1)
c.joinI(lab1, n)
setLen(c.forks, oldLen)
proc genIf(c: var Con, n: PNode) =
#[
@@ -439,21 +421,16 @@ proc genIf(c: var Con, n: PNode) =
join F1
]#
let oldLen = c.forks.len
var endings: seq[TPosition] = @[]
for i in 0 ..< len(n):
var it = n.sons[i]
c.gen(it.sons[0])
for i in 0..<n.len:
let it = n[i]
c.gen(it[0])
if it.len == 2:
let elsePos = forkI(c, it[1])
c.gen(it.sons[1])
endings.add(c.gotoI(it.sons[1]))
c.patch(elsePos)
forkT(it[1]):
c.gen(it[1])
endings.add c.gotoI(it[1])
for i in countdown(endings.high, 0):
let endPos = endings[i]
c.patch(endPos)
c.joinI(c.forks.pop(), n)
doAssert(c.forks.len == oldLen)
c.patch(endings[i])
proc genAndOr(c: var Con; n: PNode) =
# asgn dest, a
@@ -461,9 +438,9 @@ proc genAndOr(c: var Con; n: PNode) =
# asgn dest, b
# lab1:
# join F1
c.gen(n.sons[1])
c.gen(n[1])
forkT(n):
c.gen(n.sons[2])
c.gen(n[2])
proc genCase(c: var Con; n: PNode) =
# if (!expr1) goto lab1;
@@ -476,94 +453,107 @@ proc genCase(c: var Con; n: PNode) =
# lab2:
# elsePart
# Lend:
let isExhaustive = skipTypes(n.sons[0].typ,
let isExhaustive = skipTypes(n[0].typ,
abstractVarRange-{tyTypeDesc}).kind notin {tyFloat..tyFloat128, tyString}
var endings: seq[TPosition] = @[]
let oldLen = c.forks.len
c.gen(n.sons[0])
for i in 1 ..< n.len:
let it = n.sons[i]
if it.len == 1:
c.gen(it.sons[0])
elif i == n.len-1 and isExhaustive:
c.gen(n[0])
for i in 1..<n.len:
let it = n[i]
if it.len == 1 or (i == n.len-1 and isExhaustive):
# treat the last branch as 'else' if this is an exhaustive case statement.
c.gen(it.lastSon)
else:
let elsePos = c.forkI(it.lastSon)
c.gen(it.lastSon)
endings.add(c.gotoI(it.lastSon))
c.patch(elsePos)
forkT(it.lastSon):
c.gen(it.lastSon)
endings.add c.gotoI(it.lastSon)
for i in countdown(endings.high, 0):
let endPos = endings[i]
c.patch(endPos)
c.joinI(c.forks.pop(), n)
doAssert(c.forks.len == oldLen)
proc genBlock(c: var Con; n: PNode) =
withBlock(n[0].sym):
c.gen(n[1])
proc genBreakOrRaiseAux(c: var Con, i: int, n: PNode) =
let lab1 = c.gotoI(n)
if c.blocks[i].isTryBlock:
c.blocks[i].raiseFixups.add lab1
else:
var trailingFinales: seq[PNode]
if c.inTryStmt > 0: #Ok, we are in a try, lets see which (if any) try's we break out from:
for b in countdown(c.blocks.high, i):
if c.blocks[b].isTryBlock:
trailingFinales.add c.blocks[b].finale
c.blocks[i].breakFixups.add (lab1, trailingFinales)
proc genBreak(c: var Con; n: PNode) =
if n[0].kind == nkSym:
for i in countdown(c.blocks.high, 0):
if not c.blocks[i].isTryBlock and c.blocks[i].label == n[0].sym:
genBreakOrRaiseAux(c, i, n)
return
#globalError(n.info, "VM problem: cannot find 'break' target")
else:
for i in countdown(c.blocks.high, 0):
if not c.blocks[i].isTryBlock:
genBreakOrRaiseAux(c, i, n)
return
proc genTry(c: var Con; n: PNode) =
let oldLen = c.forks.len
var endings: seq[TPosition] = @[]
let oldLen = c.blocks.len
c.blocks.add TBlock(isTryBlock: true, finale: if n[^1].kind == nkFinally: n[^1] else: newNode(nkEmpty))
inc c.inTryStmt
let oldFixups = c.tryStmtFixups.len
#let elsePos = c.forkI(n)
c.gen(n.sons[0])
c.gen(n[0])
dec c.inTryStmt
for i in oldFixups..c.tryStmtFixups.high:
let f = c.tryStmtFixups[i]
for f in c.blocks[oldLen].raiseFixups:
c.patch(f)
# we also need to produce join instructions
# for the 'fork' that might precede the goto instruction
if f.int-1 >= 0 and c.code[f.int-1].kind == fork:
c.joinI(TPosition(f.int-1), n)
setLen(c.tryStmtFixups, oldFixups)
c.blocks.setLen oldLen
#c.patch(elsePos)
for i in 1 ..< n.len:
let it = n.sons[i]
for i in 1..<n.len:
let it = n[i]
if it.kind != nkFinally:
var blen = len(it)
let endExcept = c.forkI(it)
c.gen(it.lastSon)
endings.add(c.gotoI(it))
c.patch(endExcept)
forkT(it):
c.gen(it.lastSon)
endings.add c.gotoI(it)
for i in countdown(endings.high, 0):
let endPos = endings[i]
c.patch(endPos)
c.joinI(c.forks.pop(), n)
# join the 'elsePos' forkI instruction:
#c.joinI(c.forks.pop(), n)
c.patch(endings[i])
let fin = lastSon(n)
if fin.kind == nkFinally:
c.gen(fin.sons[0])
doAssert(c.forks.len == oldLen)
c.gen(fin[0])
template genNoReturn(c: var Con; n: PNode) =
# leave the graph
c.code.add Instr(n: n, kind: goto, dest: high(int) - c.code.len)
proc genRaise(c: var Con; n: PNode) =
genJoins(c, n)
gen(c, n.sons[0])
gen(c, n[0])
if c.inTryStmt > 0:
c.tryStmtFixups.add c.gotoI(n)
for i in countdown(c.blocks.high, 0):
if c.blocks[i].isTryBlock:
genBreakOrRaiseAux(c, i, n)
return
assert false #Unreachable
else:
genNoReturn(c, n)
proc genImplicitReturn(c: var Con) =
if c.owner.kind in {skProc, skFunc, skMethod, skIterator, skConverter} and resultPos < c.owner.ast.len:
gen(c, c.owner.ast.sons[resultPos])
gen(c, c.owner.ast[resultPos])
proc genReturn(c: var Con; n: PNode) =
genJoins(c, n)
if n.sons[0].kind != nkEmpty:
gen(c, n.sons[0])
if n[0].kind != nkEmpty:
gen(c, n[0])
else:
genImplicitReturn(c)
genNoReturn(c, n)
genBreakOrRaiseAux(c, 0, n)
const
InterestingSyms = {skVar, skResult, skLet, skParam, skForVar, skTemp}
@@ -573,16 +563,6 @@ const
nkObjDownConv, nkObjUpConv}
PathKinds1 = {nkHiddenStdConv, nkHiddenSubConv}
proc getRoot(n: PNode): PNode =
result = n
while true:
case result.kind
of PathKinds0:
result = result[0]
of PathKinds1:
result = result[1]
else: break
proc skipConvDfa*(n: PNode): PNode =
result = n
while true:
@@ -593,74 +573,62 @@ proc skipConvDfa*(n: PNode): PNode =
result = result[1]
else: break
proc genUse(c: var Con; orig: PNode) =
let n = dfa.getRoot(orig)
if n.kind == nkSym and n.sym.kind in InterestingSyms:
c.code.add Instr(n: orig, kind: use, sym: if orig != n: nil else: n.sym)
proc aliases(obj, field: PNode): bool =
proc aliases*(obj, field: PNode): bool =
var n = field
var obj = obj
while obj.kind in {nkHiddenSubConv, nkHiddenStdConv, nkObjDownConv, nkObjUpConv}:
obj = obj[0]
while true:
case obj.kind
of {nkObjDownConv, nkObjUpConv, nkAddr, nkHiddenAddr, nkDerefExpr, nkHiddenDeref}:
obj = obj[0]
of PathKinds1:
obj = obj[1]
else: break
while true:
if sameTrees(obj, n): return true
case n.kind
of nkDotExpr, nkCheckedFieldExpr, nkHiddenSubConv, nkHiddenStdConv,
nkObjDownConv, nkObjUpConv, nkHiddenAddr, nkAddr, nkBracketExpr,
nkHiddenDeref, nkDerefExpr:
of PathKinds0:
n = n[0]
else:
break
return false
of PathKinds1:
n = n[1]
else: break
proc useInstrTargets*(ins: Instr; loc: PNode): bool =
assert ins.kind == use
if ins.sym != nil and loc.kind == nkSym:
result = ins.sym == loc.sym
else:
result = ins.n == loc or sameTrees(ins.n, loc)
if not result:
# We can come here if loc is 'x.f' and ins.n is 'x' or the other way round.
# def x.f; question: does it affect the full 'x'? No.
# def x; question: does it affect the 'x.f'? Yes.
# use x.f; question: does it affect the full 'x'? No.
# use x; question does it affect 'x.f'? Yes.
result = aliases(ins.n, loc) or aliases(loc, ins.n)
type InstrTargetKind* = enum
None, Full, Partial
proc defInstrTargets*(ins: Instr; loc: PNode): bool =
assert ins.kind == def
if ins.sym != nil and loc.kind == nkSym:
result = ins.sym == loc.sym
else:
result = ins.n == loc or sameTrees(ins.n, loc)
if not result:
# We can come here if loc is 'x.f' and ins.n is 'x' or the other way round.
# def x.f; question: does it affect the full 'x'? No.
# def x; question: does it affect the 'x.f'? Yes.
# use x.f; question: does it affect the full 'x'? No.
# use x; question does it affect 'x.f'? Yes.
result = aliases(ins.n, loc)
proc instrTargets*(insloc, loc: PNode): InstrTargetKind =
if sameTrees(insloc, loc) or insloc.aliases(loc):
Full # x -> x; x -> x.f
elif loc.aliases(insloc):
Partial # x.f -> x
else: None
proc isAnalysableFieldAccess*(orig: PNode; owner: PSym): bool =
var n = orig
while true:
case n.kind
of nkDotExpr, nkCheckedFieldExpr, nkHiddenSubConv, nkHiddenStdConv,
nkObjDownConv, nkObjUpConv, nkHiddenAddr, nkAddr, nkBracketExpr:
of PathKinds0 - {nkBracketExpr, nkHiddenDeref, nkDerefExpr}:
n = n[0]
of PathKinds1:
n = n[1]
of nkBracketExpr:
# in a[i] the 'i' must be known
if n.len > 1 and n[1].kind in {nkCharLit..nkUInt64Lit}:
n = n[0]
else:
return false
of nkHiddenDeref, nkDerefExpr:
# We "own" sinkparam[].loc but not ourVar[].location as it is a nasty
# pointer indirection.
# bug #14159, we cannot reason about sinkParam[].location as it can
# still be shared for tyRef.
n = n[0]
return n.kind == nkSym and n.sym.owner == owner and (isSinkParam(n.sym) or
n.sym.typ.skipTypes(abstractInst-{tyOwned}).kind in {tyOwned})
else:
break
return n.kind == nkSym and n.sym.owner == owner and
(n.sym.typ.skipTypes(abstractInst-{tyOwned}).kind in {tyOwned})
else: break
# XXX Allow closure deref operations here if we know
# the owner controlled the closure allocation?
result = n.kind == nkSym and n.sym.owner == owner and
owner.kind != skModule and
{sfGlobal, sfThread, sfCursor} * n.sym.flags == {} and
(n.sym.kind != skParam or isSinkParam(n.sym)) # or n.sym.typ.kind == tyVar)
# Note: There is a different move analyzer possible that checks for
# consume(param.key); param.key = newValue for all paths. Then code like
@@ -673,45 +641,55 @@ proc isAnalysableFieldAccess*(orig: PNode; owner: PSym): bool =
# free the old data and all is lost! Lesson: Don't be too smart, trust the
# lower level C++ optimizer to specialize this code.
proc genDef(c: var Con; n: PNode) =
if n.kind == nkSym and n.sym.kind in InterestingSyms:
c.code.add Instr(n: n, kind: def, sym: n.sym)
elif isAnalysableFieldAccess(n, c.owner):
c.code.add Instr(n: n, kind: def, sym: nil)
proc skipTrivials(c: var Con, n: PNode): PNode =
result = n
while true:
case result.kind
of PathKinds0 - {nkBracketExpr}:
result = result[0]
of nkBracketExpr:
gen(c, result[1])
result = result[0]
of PathKinds1:
result = result[1]
else: break
proc canRaise(fn: PNode): bool =
const magicsThatCanRaise = {
mNone, mSlurp, mStaticExec, mParseExprToAst, mParseStmtToAst}
if fn.kind == nkSym and fn.sym.magic notin magicsThatCanRaise:
result = false
else:
result = true
proc genUse(c: var Con; orig: PNode) =
let n = c.skipTrivials(orig)
if n.kind == nkSym and n.sym.kind in InterestingSyms:
c.code.add Instr(n: orig, kind: use)
elif n.kind in nkCallKinds:
gen(c, n)
proc genDef(c: var Con; orig: PNode) =
let n = c.skipTrivials(orig)
if n.kind == nkSym and n.sym.kind in InterestingSyms:
c.code.add Instr(n: orig, kind: def)
proc genCall(c: var Con; n: PNode) =
gen(c, n[0])
var t = n[0].typ
if t != nil: t = t.skipTypes(abstractInst)
inc c.inCall
for i in 1..<n.len:
gen(c, n[i])
when false:
if t != nil and i < t.len and t.sons[i].kind == tyVar:
# This is wrong! Pass by var is a 'might def', not a 'must def'
# like the other defs we emit. This is not good enough for a move
# optimizer.
if t != nil and i < t.len and t[i].kind == tyOut:
# Pass by 'out' is a 'must def'. Good enough for a move optimizer.
genDef(c, n[i])
# every call can potentially raise:
if c.inTryStmt > 0 and canRaise(n[0]):
if c.inTryStmt > 0 and canRaiseConservative(n[0]):
# we generate the instruction sequence:
# fork lab1
# goto exceptionHandler (except or finally)
# lab1:
# join F1
let endGoto = c.forkI(n)
c.tryStmtFixups.add c.gotoI(n)
c.patch(endGoto)
c.joinI(c.forks.pop(), n)
dec c.inCall
forkT(n):
for i in countdown(c.blocks.high, 0):
if c.blocks[i].isTryBlock:
genBreakOrRaiseAux(c, i, n)
break
proc genMagic(c: var Con; n: PNode; m: TMagic) =
case m
@@ -728,23 +706,23 @@ proc genVarSection(c: var Con; n: PNode) =
discard
elif a.kind == nkVarTuple:
gen(c, a.lastSon)
for i in 0 .. a.len-3: genDef(c, a[i])
for i in 0..<a.len-2: genDef(c, a[i])
else:
gen(c, a.lastSon)
if a.lastSon.kind != nkEmpty:
genDef(c, a.sons[0])
genDef(c, a[0])
proc gen(c: var Con; n: PNode) =
case n.kind
of nkSym: genUse(c, n)
of nkCallKinds:
if n.sons[0].kind == nkSym:
let s = n.sons[0].sym
if n[0].kind == nkSym:
let s = n[0].sym
if s.magic != mNone:
genMagic(c, n, s.magic)
else:
genCall(c, n)
if sfNoReturn in n.sons[0].sym.flags:
if sfNoReturn in n[0].sym.flags:
genNoReturn(c, n)
else:
genCall(c, n)
@@ -755,12 +733,12 @@ proc gen(c: var Con; n: PNode) =
# "uses" 'i'. But we are only talking about builtin array indexing so
# it doesn't matter and 'x = 34' is NOT a usage of 'x'.
genDef(c, n[0])
of PathKinds0 - {nkHiddenStdConv, nkHiddenSubConv, nkObjDownConv, nkObjUpConv}:
of PathKinds0 - {nkObjDownConv, nkObjUpConv}:
genUse(c, n)
of nkIfStmt, nkIfExpr: genIf(c, n)
of nkWhenStmt:
# This is "when nimvm" node. Chose the first branch.
gen(c, n.sons[0].sons[1])
gen(c, n[0][1])
of nkCaseStmt: genCase(c, n)
of nkWhileStmt: genWhile(c, n)
of nkBlockExpr, nkBlockStmt: genBlock(c, n)
@@ -772,18 +750,21 @@ proc gen(c: var Con; n: PNode) =
nkBracket, nkCurly, nkPar, nkTupleConstr, nkClosure, nkObjConstr, nkYieldStmt:
for x in n: gen(c, x)
of nkPragmaBlock: gen(c, n.lastSon)
of nkDiscardStmt, nkObjDownConv, nkObjUpConv: gen(c, n.sons[0])
of nkConv, nkExprColonExpr, nkExprEqExpr, nkCast, nkHiddenSubConv, nkHiddenStdConv:
gen(c, n.sons[1])
of nkStringToCString, nkCStringToString: gen(c, n.sons[0])
of nkDiscardStmt, nkObjDownConv, nkObjUpConv, nkStringToCString, nkCStringToString:
gen(c, n[0])
of nkConv, nkExprColonExpr, nkExprEqExpr, nkCast, PathKinds1:
gen(c, n[1])
of nkVarSection, nkLetSection: genVarSection(c, n)
of nkDefer:
doAssert false, "dfa construction pass requires the elimination of 'defer'"
of nkDefer: doAssert false, "dfa construction pass requires the elimination of 'defer'"
else: discard
proc constructCfg*(s: PSym; body: PNode): ControlFlowGraph =
## constructs a control flow graph for ``body``.
var c = Con(code: @[], blocks: @[], owner: s)
gen(c, body)
genImplicitReturn(c)
shallowCopy(result, c.code)
withBlock(s):
gen(c, body)
genImplicitReturn(c)
when defined(gcArc) or defined(gcOrc):
result = c.code # will move
else:
shallowCopy(result, c.code)

File diff suppressed because it is too large Load Diff

View File

@@ -11,7 +11,7 @@
# semantic checking.
import
options, ast, msgs, idents, passes, docgen, lineinfos, pathutils
options, ast, msgs, passes, docgen, lineinfos, pathutils
from modulegraphs import ModuleGraph, PPassContext
@@ -22,13 +22,14 @@ type
config: ConfigRef
PGen = ref TGen
template shouldProcess(g): bool =
(g.module.owner.id == g.doc.conf.mainPackageId and optWholeProject in g.doc.conf.globalOptions) or
proc shouldProcess(g: PGen): bool =
(optWholeProject in g.doc.conf.globalOptions and g.module.getnimblePkgId == g.doc.conf.mainPackageId) or
sfMainModule in g.module.flags or g.config.projectMainIdx == g.module.info.fileIndex
template closeImpl(body: untyped) {.dirty.} =
var g = PGen(p)
let useWarning = sfMainModule notin g.module.flags
let groupedToc = true
if shouldProcess(g):
body
try:
@@ -38,7 +39,7 @@ template closeImpl(body: untyped) {.dirty.} =
proc close(graph: ModuleGraph; p: PPassContext, n: PNode): PNode =
closeImpl:
writeOutput(g.doc, useWarning)
writeOutput(g.doc, useWarning, groupedToc)
proc closeJson(graph: ModuleGraph; p: PPassContext, n: PNode): PNode =
closeImpl:

View File

@@ -13,7 +13,7 @@ proc genEnumToStrProc*(t: PType; info: TLineInfo; g: ModuleGraph): PSym =
result.typ = newType(tyProc, t.owner)
result.typ.n = newNodeI(nkFormalParams, info)
rawAddSon(result.typ, res.typ)
addSon(result.typ.n, newNodeI(nkEffectList, info))
result.typ.n.add newNodeI(nkEffectList, info)
result.typ.addParam dest
@@ -22,7 +22,7 @@ proc genEnumToStrProc*(t: PType; info: TLineInfo; g: ModuleGraph): PSym =
caseStmt.add(newSymNode dest)
# copy the branches over, but replace the fields with the for loop body:
for i in 0 ..< t.n.len:
for i in 0..<t.n.len:
assert(t.n[i].kind == nkSym)
var field = t.n[i].sym
let val = if field.ast == nil: field.name.s else: field.ast.strVal
@@ -33,28 +33,35 @@ proc genEnumToStrProc*(t: PType; info: TLineInfo; g: ModuleGraph): PSym =
body.add(caseStmt)
var n = newNodeI(nkProcDef, info, bodyPos+2)
for i in 0 ..< n.len: n.sons[i] = newNodeI(nkEmpty, info)
n.sons[namePos] = newSymNode(result)
n.sons[paramsPos] = result.typ.n
n.sons[bodyPos] = body
n.sons[resultPos] = newSymNode(res)
for i in 0..<n.len: n[i] = newNodeI(nkEmpty, info)
n[namePos] = newSymNode(result)
n[paramsPos] = result.typ.n
n[bodyPos] = body
n[resultPos] = newSymNode(res)
result.ast = n
incl result.flags, sfFromGeneric
incl result.flags, sfNeverRaises
proc searchObjCase(obj: PNode; field: PSym): PNode =
proc searchObjCaseImpl(obj: PNode; field: PSym): PNode =
case obj.kind
of nkSym:
result = nil
of nkElse, nkOfBranch:
result = searchObjCase(obj.lastSon, field)
result = searchObjCaseImpl(obj.lastSon, field)
else:
if obj.kind == nkRecCase and obj[0].kind == nkSym and obj[0].sym == field:
result = obj
else:
for x in obj:
result = searchObjCase(x, field)
result = searchObjCaseImpl(x, field)
if result != nil: break
proc searchObjCase(t: PType; field: PSym): PNode =
result = searchObjCaseImpl(t.n, field)
if result == nil and t.len > 0:
result = searchObjCase(t[0].skipTypes({tyAlias, tyGenericInst, tyRef, tyPtr}), field)
doAssert result != nil
proc genCaseObjDiscMapping*(t: PType; field: PSym; info: TLineInfo; g: ModuleGraph): PSym =
result = newSym(skProc, getIdent(g.cache, "objDiscMapping"), t.owner, info)
@@ -67,7 +74,7 @@ proc genCaseObjDiscMapping*(t: PType; field: PSym; info: TLineInfo; g: ModuleGra
result.typ = newType(tyProc, t.owner)
result.typ.n = newNodeI(nkFormalParams, info)
rawAddSon(result.typ, res.typ)
addSon(result.typ.n, newNodeI(nkEffectList, info))
result.typ.n.add newNodeI(nkEffectList, info)
result.typ.addParam dest
@@ -75,12 +82,11 @@ proc genCaseObjDiscMapping*(t: PType; field: PSym; info: TLineInfo; g: ModuleGra
var caseStmt = newNodeI(nkCaseStmt, info)
caseStmt.add(newSymNode dest)
let subObj = searchObjCase(t.n, field)
doAssert subObj != nil
for i in 1 ..< subObj.len:
let subObj = searchObjCase(t, field)
for i in 1..<subObj.len:
let ofBranch = subObj[i]
var newBranch = newNodeI(ofBranch.kind, ofBranch.info)
for j in 0..ofBranch.len-2:
for j in 0..<ofBranch.len-1:
newBranch.add ofBranch[j]
newBranch.add newTree(nkStmtList, newTree(nkFastAsgn, newSymNode(res), newIntNode(nkInt8Lit, i)))
@@ -89,10 +95,11 @@ proc genCaseObjDiscMapping*(t: PType; field: PSym; info: TLineInfo; g: ModuleGra
body.add(caseStmt)
var n = newNodeI(nkProcDef, info, bodyPos+2)
for i in 0 ..< n.len: n.sons[i] = newNodeI(nkEmpty, info)
n.sons[namePos] = newSymNode(result)
n.sons[paramsPos] = result.typ.n
n.sons[bodyPos] = body
n.sons[resultPos] = newSymNode(res)
for i in 0..<n.len: n[i] = newNodeI(nkEmpty, info)
n[namePos] = newSymNode(result)
n[paramsPos] = result.typ.n
n[bodyPos] = body
n[resultPos] = newSymNode(res)
result.ast = n
incl result.flags, sfFromGeneric
incl result.flags, sfNeverRaises

View File

@@ -9,13 +9,18 @@
## This file implements the FFI part of the evaluator for Nim code.
import ast, astalgo, ropes, types, options, tables, dynlib, msgs, os, lineinfos
import ast, types, options, tables, dynlib, msgs, lineinfos
from os import getAppFilename
import pkg/libffi
when defined(windows):
const libcDll = "msvcrt.dll"
elif defined(linux):
const libcDll = "libc.so(.6|.5|)"
elif defined(openbsd):
const libcDll = "/usr/lib/libc.so(.95.1|)"
elif defined(bsd):
const libcDll = "/lib/libc.so.7"
elif defined(osx):
const libcDll = "/usr/lib/libSystem.dylib"
else:
@@ -27,7 +32,7 @@ var
gDllCache = initTable[string, LibHandle]()
when defined(windows):
var gExeHandle = loadLib(os.getAppFilename())
var gExeHandle = loadLib(getAppFilename())
else:
var gExeHandle = loadLib()
@@ -46,24 +51,19 @@ proc getDll(conf: ConfigRef, cache: var TDllCache; dll: string; info: TLineInfo)
const
nkPtrLit = nkIntLit # hopefully we can get rid of this hack soon
var myerrno {.importc: "errno", header: "<errno.h>".}: cint ## error variable
proc importcSymbol*(conf: ConfigRef, sym: PSym): PNode =
let name = $sym.loc.r
let name = sym.cname # $sym.loc.r would point to internal name
# the AST does not support untyped pointers directly, so we use an nkIntLit
# that contains the address instead:
result = newNodeIT(nkPtrLit, sym.info, sym.typ)
case name
of "stdin": result.intVal = cast[ByteAddress](system.stdin)
of "stdout": result.intVal = cast[ByteAddress](system.stdout)
of "stderr": result.intVal = cast[ByteAddress](system.stderr)
of "vmErrnoWrapper": result.intVal = cast[ByteAddress](myerrno)
else:
when true:
var libPathMsg = ""
let lib = sym.annex
if lib != nil and lib.path.kind notin {nkStrLit..nkTripleStrLit}:
globalError(conf, sym.info, "dynlib needs to be a string lit")
var theAddr: pointer
if (lib.isNil or lib.kind == libHeader) and not gExeHandle.isNil:
libPathMsg = "current exe: " & getAppFilename() & " nor libc: " & libcDll
# first try this exe itself:
theAddr = gExeHandle.symAddr(name)
# then try libc:
@@ -72,12 +72,14 @@ proc importcSymbol*(conf: ConfigRef, sym: PSym): PNode =
theAddr = dllhandle.symAddr(name)
elif not lib.isNil:
let dll = if lib.kind == libHeader: libcDll else: lib.path.strVal
libPathMsg = dll
let dllhandle = getDll(conf, gDllCache, dll, sym.info)
theAddr = dllhandle.symAddr(name)
if theAddr.isNil: globalError(conf, sym.info, "cannot import: " & sym.name.s)
if theAddr.isNil: globalError(conf, sym.info,
"cannot import symbol: " & name & " from " & libPathMsg)
result.intVal = cast[ByteAddress](theAddr)
proc mapType(conf: ConfigRef, t: ast.PType): ptr libffi.TType =
proc mapType(conf: ConfigRef, t: ast.PType): ptr libffi.Type =
if t == nil: return addr libffi.type_void
case t.kind
@@ -94,7 +96,7 @@ proc mapType(conf: ConfigRef, t: ast.PType): ptr libffi.TType =
tyTyped, tyTypeDesc, tyProc, tyArray, tyStatic, tyNil:
result = addr libffi.type_pointer
of tyDistinct, tyAlias, tySink:
result = mapType(conf, t.sons[0])
result = mapType(conf, t[0])
else:
result = nil
# too risky:
@@ -102,7 +104,7 @@ proc mapType(conf: ConfigRef, t: ast.PType): ptr libffi.TType =
proc mapCallConv(conf: ConfigRef, cc: TCallingConvention, info: TLineInfo): TABI =
case cc
of ccDefault: result = DEFAULT_ABI
of ccNimCall: result = DEFAULT_ABI
of ccStdCall: result = when defined(windows) and defined(x86): STDCALL else: DEFAULT_ABI
of ccCDecl: result = DEFAULT_ABI
else:
@@ -120,16 +122,16 @@ proc packSize(conf: ConfigRef, v: PNode, typ: PType): int =
if v.kind in {nkNilLit, nkPtrLit}:
result = sizeof(pointer)
else:
result = sizeof(pointer) + packSize(conf, v.sons[0], typ.lastSon)
result = sizeof(pointer) + packSize(conf, v[0], typ.lastSon)
of tyDistinct, tyGenericInst, tyAlias, tySink:
result = packSize(conf, v, typ.sons[0])
result = packSize(conf, v, typ[0])
of tyArray:
# consider: ptr array[0..1000_000, int] which is common for interfacing;
# we use the real length here instead
if v.kind in {nkNilLit, nkPtrLit}:
result = sizeof(pointer)
elif v.len != 0:
result = v.len * packSize(conf, v.sons[0], typ.sons[1])
result = v.len * packSize(conf, v[0], typ[1])
else:
result = getSize(conf, typ).int
@@ -138,16 +140,16 @@ proc pack(conf: ConfigRef, v: PNode, typ: PType, res: pointer)
proc getField(conf: ConfigRef, n: PNode; position: int): PSym =
case n.kind
of nkRecList:
for i in 0 ..< len(n):
result = getField(conf, n.sons[i], position)
for i in 0..<n.len:
result = getField(conf, n[i], position)
if result != nil: return
of nkRecCase:
result = getField(conf, n.sons[0], position)
result = getField(conf, n[0], position)
if result != nil: return
for i in 1 ..< len(n):
case n.sons[i].kind
for i in 1..<n.len:
case n[i].kind
of nkOfBranch, nkElse:
result = getField(conf, lastSon(n.sons[i]), position)
result = getField(conf, lastSon(n[i]), position)
if result != nil: return
else: internalError(conf, n.info, "getField(record case branch)")
of nkSym:
@@ -158,12 +160,12 @@ proc packObject(conf: ConfigRef, x: PNode, typ: PType, res: pointer) =
internalAssert conf, x.kind in {nkObjConstr, nkPar, nkTupleConstr}
# compute the field's offsets:
discard getSize(conf, typ)
for i in ord(x.kind == nkObjConstr) ..< len(x):
var it = x.sons[i]
for i in ord(x.kind == nkObjConstr)..<x.len:
var it = x[i]
if it.kind == nkExprColonExpr:
internalAssert conf, it.sons[0].kind == nkSym
let field = it.sons[0].sym
pack(conf, it.sons[1], field.typ, res +! field.offset)
internalAssert conf, it[0].kind == nkSym
let field = it[0].sym
pack(conf, it[1], field.typ, res +! field.offset)
elif typ.n != nil:
let field = getField(conf, typ.n, i)
pack(conf, it, field.typ, res +! field.offset)
@@ -224,19 +226,19 @@ proc pack(conf: ConfigRef, v: PNode, typ: PType, res: pointer) =
packRecCheck = 0
globalError(conf, v.info, "cannot map value to FFI " & typeToString(v.typ))
inc packRecCheck
pack(conf, v.sons[0], typ.lastSon, res +! sizeof(pointer))
pack(conf, v[0], typ.lastSon, res +! sizeof(pointer))
dec packRecCheck
awr(pointer, res +! sizeof(pointer))
of tyArray:
let baseSize = getSize(conf, typ.sons[1])
for i in 0 ..< v.len:
pack(conf, v.sons[i], typ.sons[1], res +! i * baseSize)
let baseSize = getSize(conf, typ[1])
for i in 0..<v.len:
pack(conf, v[i], typ[1], res +! i * baseSize)
of tyObject, tyTuple:
packObject(conf, v, typ, res)
of tyNil:
discard
of tyDistinct, tyGenericInst, tyAlias, tySink:
pack(conf, v, typ.sons[0], res)
pack(conf, v, typ[0], res)
else:
globalError(conf, v.info, "cannot map value to FFI " & typeToString(v.typ))
@@ -245,14 +247,14 @@ proc unpack(conf: ConfigRef, x: pointer, typ: PType, n: PNode): PNode
proc unpackObjectAdd(conf: ConfigRef, x: pointer, n, result: PNode) =
case n.kind
of nkRecList:
for i in 0 ..< len(n):
unpackObjectAdd(conf, x, n.sons[i], result)
for i in 0..<n.len:
unpackObjectAdd(conf, x, n[i], result)
of nkRecCase:
globalError(conf, result.info, "case objects cannot be unpacked")
of nkSym:
var pair = newNodeI(nkExprColonExpr, result.info, 2)
pair.sons[0] = n
pair.sons[1] = unpack(conf, x +! n.sym.offset, n.sym.typ, nil)
pair[0] = n
pair[1] = unpack(conf, x +! n.sym.offset, n.sym.typ, nil)
#echo "offset: ", n.sym.name.s, " ", n.sym.offset
result.add pair
else: discard
@@ -275,15 +277,15 @@ proc unpackObject(conf: ConfigRef, x: pointer, typ: PType, n: PNode): PNode =
globalError(conf, n.info, "cannot map value from FFI")
if typ.n.isNil:
globalError(conf, n.info, "cannot unpack unnamed tuple")
for i in ord(n.kind == nkObjConstr) ..< len(n):
var it = n.sons[i]
for i in ord(n.kind == nkObjConstr)..<n.len:
var it = n[i]
if it.kind == nkExprColonExpr:
internalAssert conf, it.sons[0].kind == nkSym
let field = it.sons[0].sym
it.sons[1] = unpack(conf, x +! field.offset, field.typ, it.sons[1])
internalAssert conf, it[0].kind == nkSym
let field = it[0].sym
it[1] = unpack(conf, x +! field.offset, field.typ, it[1])
else:
let field = getField(conf, typ.n, i)
n.sons[i] = unpack(conf, x +! field.offset, field.typ, it)
n[i] = unpack(conf, x +! field.offset, field.typ, it)
proc unpackArray(conf: ConfigRef, x: pointer, typ: PType, n: PNode): PNode =
if n.isNil:
@@ -294,9 +296,9 @@ proc unpackArray(conf: ConfigRef, x: pointer, typ: PType, n: PNode): PNode =
result = n
if result.kind != nkBracket:
globalError(conf, n.info, "cannot map value from FFI")
let baseSize = getSize(conf, typ.sons[1])
for i in 0 ..< result.len:
result.sons[i] = unpack(conf, x +! i * baseSize, typ.sons[1], result.sons[i])
let baseSize = getSize(conf, typ[1])
for i in 0..<result.len:
result[i] = unpack(conf, x +! i * baseSize, typ[1], result[i])
proc canonNodeKind(k: TNodeKind): TNodeKind =
case k
@@ -327,7 +329,7 @@ proc unpack(conf: ConfigRef, x: pointer, typ: PType, n: PNode): PNode =
else:
reset n[]
result = n
result.kind = nkNilLit
result[] = TNode(kind: nkNilLit)
result.typ = typ
template awi(kind, v: untyped): untyped = aw(kind, v, intVal)
@@ -376,7 +378,7 @@ proc unpack(conf: ConfigRef, x: pointer, typ: PType, n: PNode): PNode =
awi(nkPtrLit, cast[ByteAddress](p))
elif n != nil and n.len == 1:
internalAssert(conf, n.kind == nkRefTy)
n.sons[0] = unpack(conf, p, typ.lastSon, n.sons[0])
n[0] = unpack(conf, p, typ.lastSon, n[0])
result = n
else:
globalError(conf, n.info, "cannot map value from FFI " & typeToString(typ))
@@ -419,41 +421,41 @@ proc fficast*(conf: ConfigRef, x: PNode, destTyp: PType): PNode =
dealloc a
proc callForeignFunction*(conf: ConfigRef, call: PNode): PNode =
internalAssert conf, call.sons[0].kind == nkPtrLit
internalAssert conf, call[0].kind == nkPtrLit
var cif: TCif
var sig: TParamList
var sig: ParamList
# use the arguments' types for varargs support:
for i in 1..call.len-1:
sig[i-1] = mapType(conf, call.sons[i].typ)
for i in 1..<call.len:
sig[i-1] = mapType(conf, call[i].typ)
if sig[i-1].isNil:
globalError(conf, call.info, "cannot map FFI type")
let typ = call.sons[0].typ
let typ = call[0].typ
if prep_cif(cif, mapCallConv(conf, typ.callConv, call.info), cuint(call.len-1),
mapType(conf, typ.sons[0]), sig) != OK:
mapType(conf, typ[0]), sig) != OK:
globalError(conf, call.info, "error in FFI call")
var args: TArgList
let fn = cast[pointer](call.sons[0].intVal)
for i in 1 .. call.len-1:
var t = call.sons[i].typ
args[i-1] = alloc0(packSize(conf, call.sons[i], t))
pack(conf, call.sons[i], t, args[i-1])
let retVal = if isEmptyType(typ.sons[0]): pointer(nil)
else: alloc(getSize(conf, typ.sons[0]).int)
var args: ArgList
let fn = cast[pointer](call[0].intVal)
for i in 1..<call.len:
var t = call[i].typ
args[i-1] = alloc0(packSize(conf, call[i], t))
pack(conf, call[i], t, args[i-1])
let retVal = if isEmptyType(typ[0]): pointer(nil)
else: alloc(getSize(conf, typ[0]).int)
libffi.call(cif, fn, retVal, args)
if retVal.isNil:
result = newNode(nkEmpty)
else:
result = unpack(conf, retVal, typ.sons[0], nil)
result = unpack(conf, retVal, typ[0], nil)
result.info = call.info
if retVal != nil: dealloc retVal
for i in 1 .. call.len-1:
call.sons[i] = unpack(conf, args[i-1], typ.sons[i], call[i])
for i in 1..<call.len:
call[i] = unpack(conf, args[i-1], typ[i], call[i])
dealloc args[i-1]
proc callForeignFunction*(conf: ConfigRef, fn: PNode, fntyp: PType,
@@ -462,39 +464,39 @@ proc callForeignFunction*(conf: ConfigRef, fn: PNode, fntyp: PType,
internalAssert conf, fn.kind == nkPtrLit
var cif: TCif
var sig: TParamList
var sig: ParamList
for i in 0..len-1:
var aTyp = args[i+start].typ
if aTyp.isNil:
internalAssert conf, i+1 < fntyp.len
aTyp = fntyp.sons[i+1]
aTyp = fntyp[i+1]
args[i+start].typ = aTyp
sig[i] = mapType(conf, aTyp)
if sig[i].isNil: globalError(conf, info, "cannot map FFI type")
if prep_cif(cif, mapCallConv(conf, fntyp.callConv, info), cuint(len),
mapType(conf, fntyp.sons[0]), sig) != OK:
mapType(conf, fntyp[0]), sig) != OK:
globalError(conf, info, "error in FFI call")
var cargs: TArgList
var cargs: ArgList
let fn = cast[pointer](fn.intVal)
for i in 0 .. len-1:
for i in 0..len-1:
let t = args[i+start].typ
cargs[i] = alloc0(packSize(conf, args[i+start], t))
pack(conf, args[i+start], t, cargs[i])
let retVal = if isEmptyType(fntyp.sons[0]): pointer(nil)
else: alloc(getSize(conf, fntyp.sons[0]).int)
let retVal = if isEmptyType(fntyp[0]): pointer(nil)
else: alloc(getSize(conf, fntyp[0]).int)
libffi.call(cif, fn, retVal, cargs)
if retVal.isNil:
result = newNode(nkEmpty)
else:
result = unpack(conf, retVal, fntyp.sons[0], nil)
result = unpack(conf, retVal, fntyp[0], nil)
result.info = info
if retVal != nil: dealloc retVal
for i in 0 .. len-1:
for i in 0..len-1:
let t = args[i+start].typ
args[i+start] = unpack(conf, cargs[i], t, args[i+start])
dealloc cargs[i]

View File

@@ -21,6 +21,7 @@ type
# new symbol
config: ConfigRef
ic: IdentCache
instID: int
proc copyNode(ctx: TemplCtx, a, b: PNode): PNode =
result = copyNode(a)
@@ -39,10 +40,10 @@ proc evalTemplateAux(templ, actual: PNode, c: var TemplCtx, result: PNode) =
var s = templ.sym
if (s.owner == nil and s.kind == skParam) or s.owner == c.owner:
if s.kind == skParam and {sfGenSym, sfTemplateParam} * s.flags == {sfTemplateParam}:
handleParam actual.sons[s.position]
handleParam actual[s.position]
elif (s.owner != nil) and (s.kind == skGenericParam or
s.kind == skType and s.typ != nil and s.typ.kind == tyGenericParam):
handleParam actual.sons[s.owner.typ.len + s.position - 1]
handleParam actual[s.owner.typ.len + s.position - 1]
else:
internalAssert c.config, sfGenSym in s.flags or s.kind == skType
var x = PSym(idTableGet(c.mapping, s))
@@ -53,8 +54,8 @@ proc evalTemplateAux(templ, actual: PNode, c: var TemplCtx, result: PNode) =
#if x.kind == skParam and x.owner.kind == skModule:
# internalAssert c.config, false
idTablePut(c.mapping, s, x)
if sfGenSym in s.flags and optNimV019 notin c.config.globalOptions:
result.add newIdentNode(getIdent(c.ic, x.name.s & "`gensym" & $x.id),
if sfGenSym in s.flags:
result.add newIdentNode(getIdent(c.ic, x.name.s & "`gensym" & $c.instID),
if c.instLines: actual.info else: templ.info)
else:
result.add newSymNode(x, if c.instLines: actual.info else: templ.info)
@@ -68,8 +69,8 @@ proc evalTemplateAux(templ, actual: PNode, c: var TemplCtx, result: PNode) =
# "declarative" context (bug #9235).
if c.isDeclarative:
var res = copyNode(c, templ, actual)
for i in 0 ..< len(templ):
evalTemplateAux(templ.sons[i], actual, c, res)
for i in 0..<templ.len:
evalTemplateAux(templ[i], actual, c, res)
result.add res
else:
result.add newNodeI(nkEmpty, templ.info)
@@ -82,8 +83,8 @@ proc evalTemplateAux(templ, actual: PNode, c: var TemplCtx, result: PNode) =
c.isDeclarative = true
isDeclarative = true
var res = copyNode(c, templ, actual)
for i in 0 ..< len(templ):
evalTemplateAux(templ.sons[i], actual, c, res)
for i in 0..<templ.len:
evalTemplateAux(templ[i], actual, c, res)
result.add res
if isDeclarative: c.isDeclarative = false
@@ -122,22 +123,22 @@ proc evalTemplateArgs(n: PNode, s: PSym; conf: ConfigRef; fromHlo: bool): PNode
n.renderTree)
result = newNodeI(nkArgList, n.info)
for i in 1 .. givenRegularParams:
result.addSon n[i]
for i in 1..givenRegularParams:
result.add n[i]
# handle parameters with default values, which were
# not supplied by the user
for i in givenRegularParams+1 .. expectedRegularParams:
let default = s.typ.n.sons[i].sym.ast
for i in givenRegularParams+1..expectedRegularParams:
let default = s.typ.n[i].sym.ast
if default.isNil or default.kind == nkEmpty:
localError(conf, n.info, errWrongNumberOfArguments)
addSon(result, newNodeI(nkEmpty, n.info))
result.add newNodeI(nkEmpty, n.info)
else:
addSon(result, default.copyTree)
result.add default.copyTree
# add any generic parameters
for i in 1 .. genericParams:
result.addSon n.sons[givenRegularParams + i]
for i in 1..genericParams:
result.add n[givenRegularParams + i]
# to prevent endless recursion in template instantiation
const evalTemplateLimit* = 1000
@@ -155,7 +156,7 @@ proc wrapInComesFrom*(info: TLineInfo; sym: PSym; res: PNode): PNode =
if x.kind in nkCallKinds:
for i in 1..<x.len:
if x[i].kind in nkCallKinds:
x.sons[i].info = info
x[i].info = info
else:
result = newNodeI(nkStmtListExpr, info)
var d = newNodeI(nkComesFrom, info)
@@ -166,7 +167,7 @@ proc wrapInComesFrom*(info: TLineInfo; sym: PSym; res: PNode): PNode =
proc evalTemplate*(n: PNode, tmpl, genSymOwner: PSym;
conf: ConfigRef;
ic: IdentCache;
ic: IdentCache; instID: ref int;
fromHlo=false): PNode =
inc(conf.evalTemplateCounter)
if conf.evalTemplateCounter > evalTemplateLimit:
@@ -181,13 +182,14 @@ proc evalTemplate*(n: PNode, tmpl, genSymOwner: PSym;
ctx.config = conf
ctx.ic = ic
initIdTable(ctx.mapping)
ctx.instID = instID[]
let body = tmpl.getBody
#echo "instantion of ", renderTree(body, {renderIds})
if isAtom(body):
result = newNodeI(nkPar, body.info)
evalTemplateAux(body, args, ctx, result)
if result.len == 1: result = result.sons[0]
if result.len == 1: result = result[0]
else:
localError(conf, result.info, "illformed AST: " &
renderTree(result, {renderNoComments}))
@@ -196,10 +198,12 @@ proc evalTemplate*(n: PNode, tmpl, genSymOwner: PSym;
ctx.instLines = sfCallsite in tmpl.flags
if ctx.instLines:
result.info = n.info
for i in 0 ..< safeLen(body):
evalTemplateAux(body.sons[i], args, ctx, result)
for i in 0..<body.safeLen:
evalTemplateAux(body[i], args, ctx, result)
result.flags.incl nfFromTemplate
result = wrapInComesFrom(n.info, tmpl, result)
#if ctx.debugActive:
# echo "instantion of ", renderTree(result, {renderIds})
dec(conf.evalTemplateCounter)
# The instID must be unique for every template instantiation, so we increment it here
inc instID[]

View File

@@ -14,7 +14,7 @@
import
ropes, os, strutils, osproc, platform, condsyms, options, msgs,
lineinfos, std / sha1, streams, pathutils, sequtils, times
lineinfos, std / sha1, streams, pathutils, sequtils, times, strtabs
type
TInfoCCProp* = enum # properties of the C compiler:
@@ -48,6 +48,8 @@ type
# used on some platforms
asmStmtFrmt: string, # format of ASM statement
structStmtFmt: string, # Format for struct statement
produceAsm: string, # Format how to produce assembler listings
cppXsupport: string, # what to do to enable C++X support
props: TInfoCCProps] # properties of the C compiler
@@ -58,13 +60,16 @@ type
template compiler(name, settings: untyped): untyped =
proc name: TInfoCC {.compileTime.} = settings
const
gnuAsmListing = "-Wa,-acdl=$asmfile -g -fverbose-asm -masm=intel"
# GNU C and C++ Compiler
compiler gcc:
result = (
name: "gcc",
objExt: "o",
optSpeed: " -O3 ",
optSize: " -Os ",
optSpeed: " -O3 -fno-ident",
optSize: " -Os -fno-ident",
compilerExe: "gcc",
cppCompiler: "g++",
compileTmpl: "-c $options $include -o $objfile $file",
@@ -80,6 +85,8 @@ compiler gcc:
pic: "-fPIC",
asmStmtFrmt: "asm($1);$n",
structStmtFmt: "$1 $3 $2 ", # struct|union [packed] $name
produceAsm: gnuAsmListing,
cppXsupport: "-std=gnu++14 -funsigned-char",
props: {hasSwitchRange, hasComputedGoto, hasCpp, hasGcGuard, hasGnuAsm,
hasAttribute})
@@ -105,6 +112,8 @@ compiler nintendoSwitchGCC:
pic: "-fPIE",
asmStmtFrmt: "asm($1);$n",
structStmtFmt: "$1 $3 $2 ", # struct|union [packed] $name
produceAsm: gnuAsmListing,
cppXsupport: "-std=gnu++14 -funsigned-char",
props: {hasSwitchRange, hasComputedGoto, hasCpp, hasGcGuard, hasGnuAsm,
hasAttribute})
@@ -134,16 +143,16 @@ compiler vcc:
result = (
name: "vcc",
objExt: "obj",
optSpeed: " /Ogityb2 /G7 ",
optSize: " /O1 /G7 ",
optSpeed: " /Ogityb2 ",
optSize: " /O1 ",
compilerExe: "cl",
cppCompiler: "cl",
compileTmpl: "/c$vccplatform $options $include /Fo$objfile $file",
buildGui: " /link /SUBSYSTEM:WINDOWS ",
compileTmpl: "/c$vccplatform $options $include /nologo /Fo$objfile $file",
buildGui: " /SUBSYSTEM:WINDOWS user32.lib ",
buildDll: " /LD",
buildLib: "lib /OUT:$libfile $objfiles",
linkerExe: "cl",
linkTmpl: "$options $builddll$vccplatform /Fe$exefile $objfiles $buildgui",
linkTmpl: "$builddll$vccplatform /Fe$exefile $objfiles $buildgui /nologo $options",
includeCmd: " /I",
linkDirCmd: " /LIBPATH:",
linkLibCmd: " $1.lib",
@@ -151,6 +160,8 @@ compiler vcc:
pic: "",
asmStmtFrmt: "__asm{$n$1$n}$n",
structStmtFmt: "$3$n$1 $2",
produceAsm: "/Fa$asmfile",
cppXsupport: "",
props: {hasCpp, hasAssume, hasDeclspec})
compiler clangcl:
@@ -159,6 +170,7 @@ compiler clangcl:
result.compilerExe = "clang-cl"
result.cppCompiler = "clang-cl"
result.linkerExe = "clang-cl"
result.linkTmpl = "-fuse-ld=lld " & result.linkTmpl
# Intel C/C++ Compiler
compiler icl:
@@ -174,30 +186,6 @@ compiler icc:
result.compilerExe = "icc"
result.linkerExe = "icc"
# Local C Compiler
compiler lcc:
result = (
name: "lcc",
objExt: "obj",
optSpeed: " -O -p6 ",
optSize: " -O -p6 ",
compilerExe: "lcc",
cppCompiler: "",
compileTmpl: "$options $include -Fo$objfile $file",
buildGui: " -subsystem windows",
buildDll: " -dll",
buildLib: "", # XXX: not supported yet
linkerExe: "lcclnk",
linkTmpl: "$options $buildgui $builddll -O $exefile $objfiles",
includeCmd: " -I",
linkDirCmd: "", # XXX: not supported yet
linkLibCmd: "", # XXX: not supported yet
debug: " -g5 ",
pic: "",
asmStmtFrmt: "_asm{$n$1$n}$n",
structStmtFmt: "$1 $2",
props: {})
# Borland C Compiler
compiler bcc:
result = (
@@ -220,57 +208,11 @@ compiler bcc:
pic: "",
asmStmtFrmt: "__asm{$n$1$n}$n",
structStmtFmt: "$1 $2",
produceAsm: "",
cppXsupport: "",
props: {hasSwitchRange, hasComputedGoto, hasCpp, hasGcGuard,
hasAttribute})
# Digital Mars C Compiler
compiler dmc:
result = (
name: "dmc",
objExt: "obj",
optSpeed: " -ff -o -6 ",
optSize: " -ff -o -6 ",
compilerExe: "dmc",
cppCompiler: "",
compileTmpl: "-c $options $include -o$objfile $file",
buildGui: " -L/exet:nt/su:windows",
buildDll: " -WD",
buildLib: "", # XXX: not supported yet
linkerExe: "dmc",
linkTmpl: "$options $buildgui $builddll -o$exefile $objfiles",
includeCmd: " -I",
linkDirCmd: "", # XXX: not supported yet
linkLibCmd: "", # XXX: not supported yet
debug: " -g ",
pic: "",
asmStmtFrmt: "__asm{$n$1$n}$n",
structStmtFmt: "$3$n$1 $2",
props: {hasCpp})
# Watcom C Compiler
compiler wcc:
result = (
name: "wcc",
objExt: "obj",
optSpeed: " -ox -on -6 -d0 -fp6 -zW ",
optSize: "",
compilerExe: "wcl386",
cppCompiler: "",
compileTmpl: "-c $options $include -fo=$objfile $file",
buildGui: " -bw",
buildDll: " -bd",
buildLib: "", # XXX: not supported yet
linkerExe: "wcl386",
linkTmpl: "$options $buildgui $builddll -fe=$exefile $objfiles ",
includeCmd: " -i=",
linkDirCmd: "", # XXX: not supported yet
linkLibCmd: "", # XXX: not supported yet
debug: " -d2 ",
pic: "",
asmStmtFrmt: "__asm{$n$1$n}$n",
structStmtFmt: "$1 $2",
props: {hasCpp})
# Tiny C Compiler
compiler tcc:
result = (
@@ -291,45 +233,22 @@ compiler tcc:
linkLibCmd: "", # XXX: not supported yet
debug: " -g ",
pic: "",
asmStmtFrmt: "__asm{$n$1$n}$n",
asmStmtFrmt: "asm($1);$n",
structStmtFmt: "$1 $2",
props: {hasSwitchRange, hasComputedGoto})
# Pelles C Compiler
compiler pcc:
# Pelles C
result = (
name: "pcc",
objExt: "obj",
optSpeed: " -Ox ",
optSize: " -Os ",
compilerExe: "cc",
cppCompiler: "",
compileTmpl: "-c $options $include -Fo$objfile $file",
buildGui: " -SUBSYSTEM:WINDOWS",
buildDll: " -DLL",
buildLib: "", # XXX: not supported yet
linkerExe: "cc",
linkTmpl: "$options $buildgui $builddll -OUT:$exefile $objfiles",
includeCmd: " -I",
linkDirCmd: "", # XXX: not supported yet
linkLibCmd: "", # XXX: not supported yet
debug: " -Zi ",
pic: "",
asmStmtFrmt: "__asm{$n$1$n}$n",
structStmtFmt: "$1 $2",
props: {})
produceAsm: gnuAsmListing,
cppXsupport: "",
props: {hasSwitchRange, hasComputedGoto, hasGnuAsm})
# Your C Compiler
compiler ucc:
compiler envcc:
result = (
name: "ucc",
name: "env",
objExt: "o",
optSpeed: " -O3 ",
optSize: " -O1 ",
compilerExe: "cc",
compilerExe: "",
cppCompiler: "",
compileTmpl: "-c $options $include -o $objfile $file",
compileTmpl: "-c $ccenvflags $options $include -o $objfile $file",
buildGui: "",
buildDll: " -shared ",
buildLib: "", # XXX: not supported yet
@@ -342,7 +261,9 @@ compiler ucc:
pic: "",
asmStmtFrmt: "__asm{$n$1$n}$n",
structStmtFmt: "$1 $2",
props: {})
produceAsm: "",
cppXsupport: "",
props: {hasGnuAsm})
const
CC*: array[succ(low(TSystemCC))..high(TSystemCC), TInfoCC] = [
@@ -350,33 +271,28 @@ const
nintendoSwitchGCC(),
llvmGcc(),
clang(),
lcc(),
bcc(),
dmc(),
wcc(),
vcc(),
tcc(),
pcc(),
ucc(),
envcc(),
icl(),
icc(),
clangcl()]
hExt* = ".h"
proc libNameTmpl(conf: ConfigRef): string {.inline.} =
result = if conf.target.targetOS == osWindows: "$1.lib" else: "lib$1.a"
proc nameToCC*(name: string): TSystemCC =
## Returns the kind of compiler referred to by `name`, or ccNone
## if the name doesn't refer to any known compiler.
for i in succ(ccNone) .. high(TSystemCC):
for i in succ(ccNone)..high(TSystemCC):
if cmpIgnoreStyle(name, CC[i].name) == 0:
return i
result = ccNone
proc listCCnames(): seq[string] =
for i in succ(ccNone) .. high(TSystemCC):
proc listCCnames(): string =
result = ""
for i in succ(ccNone)..high(TSystemCC):
if i > succ(ccNone): result.add ", "
result.add CC[i].name
proc isVSCompatible*(conf: ConfigRef): bool =
@@ -387,15 +303,14 @@ proc isVSCompatible*(conf: ConfigRef): bool =
proc getConfigVar(conf: ConfigRef; c: TSystemCC, suffix: string): string =
# use ``cpu.os.cc`` for cross compilation, unless ``--compileOnly`` is given
# for niminst support
let fullSuffix =
if conf.cmd == cmdCompileToCpp:
".cpp" & suffix
elif conf.cmd == cmdCompileToOC:
".objc" & suffix
elif conf.cmd == cmdCompileToJS:
".js" & suffix
else:
suffix
var fullSuffix = suffix
case conf.backend
of backendCpp, backendJs, backendObjc: fullSuffix = "." & $conf.backend & suffix
of backendC: discard
of backendInvalid:
# during parsing of cfg files; we don't know the backend yet, no point in
# guessing wrong thing
return ""
if (conf.target.hostOS != conf.target.targetOS or conf.target.hostCPU != conf.target.targetCPU) and
optCompileOnly notin conf.globalOptions:
@@ -412,17 +327,16 @@ proc getConfigVar(conf: ConfigRef; c: TSystemCC, suffix: string): string =
proc setCC*(conf: ConfigRef; ccname: string; info: TLineInfo) =
conf.cCompiler = nameToCC(ccname)
if conf.cCompiler == ccNone:
let ccList = listCCnames().join(", ")
localError(conf, info, "unknown C compiler: '$1'. Available options are: $2" % [ccname, ccList])
localError(conf, info, "unknown C compiler: '$1'. Available options are: $2" % [ccname, listCCnames()])
conf.compileOptions = getConfigVar(conf, conf.cCompiler, ".options.always")
conf.linkOptions = ""
conf.cCompilerPath = getConfigVar(conf, conf.cCompiler, ".path")
for i in low(CC) .. high(CC): undefSymbol(conf.symbols, CC[i].name)
for c in CC: undefSymbol(conf.symbols, c.name)
defineSymbol(conf.symbols, CC[conf.cCompiler].name)
proc addOpt(dest: var string, src: string) =
if len(dest) == 0 or dest[len(dest)-1] != ' ': add(dest, " ")
add(dest, src)
if dest.len == 0 or dest[^1] != ' ': dest.add(" ")
dest.add(src)
proc addLinkOption*(conf: ConfigRef; option: string) =
addOpt(conf.linkOptions, option)
@@ -439,11 +353,11 @@ proc addCompileOptionCmd*(conf: ConfigRef; option: string) =
proc initVars*(conf: ConfigRef) =
# we need to define the symbol here, because ``CC`` may have never been set!
for i in low(CC) .. high(CC): undefSymbol(conf.symbols, CC[i].name)
for c in CC: undefSymbol(conf.symbols, c.name)
defineSymbol(conf.symbols, CC[conf.cCompiler].name)
addCompileOption(conf, getConfigVar(conf, conf.cCompiler, ".options.always"))
#addLinkOption(getConfigVar(cCompiler, ".options.linker"))
if len(conf.cCompilerPath) == 0:
if conf.cCompilerPath.len == 0:
conf.cCompilerPath = getConfigVar(conf, conf.cCompiler, ".path")
proc completeCfilePath*(conf: ConfigRef; cfile: AbsoluteFile,
@@ -457,6 +371,13 @@ proc toObjFile*(conf: ConfigRef; filename: AbsoluteFile): AbsoluteFile =
proc addFileToCompile*(conf: ConfigRef; cf: Cfile) =
conf.toCompile.add(cf)
proc addLocalCompileOption*(conf: ConfigRef; option: string; nimfile: AbsoluteFile) =
let key = completeCfilePath(conf, withPackageName(conf, nimfile)).string
var value = conf.cfileSpecificOptions.getOrDefault(key)
if strutils.find(value, option, 0) < 0:
addOpt(value, option)
conf.cfileSpecificOptions[key] = value
proc resetCompilationLists*(conf: ConfigRef) =
conf.toCompile.setLen 0
## XXX: we must associate these with their originating module
@@ -469,7 +390,7 @@ proc addExternalFileToLink*(conf: ConfigRef; filename: AbsoluteFile) =
conf.externalToLink.insert(filename.string, 0)
proc execWithEcho(conf: ConfigRef; cmd: string, msg = hintExecuting): int =
rawMessage(conf, msg, cmd)
rawMessage(conf, msg, if msg == hintLinking and not(optListCmd in conf.globalOptions or conf.verbosity > 1): "" else: cmd)
result = execCmd(cmd)
proc execExternalProgram*(conf: ConfigRef; cmd: string, msg = hintExecuting) =
@@ -481,10 +402,7 @@ proc generateScript(conf: ConfigRef; script: Rope) =
let (_, name, _) = splitFile(conf.outFile.string)
let filename = getNimcacheDir(conf) / RelativeFile(addFileExt("compile_" & name,
platform.OS[conf.target.targetOS].scriptExt))
if writeRope(script, filename):
copyFile(conf.libpath / RelativeFile"nimbase.h",
getNimcacheDir(conf) / RelativeFile"nimbase.h")
else:
if not writeRope(script, filename):
rawMessage(conf, errGenerated, "could not write to file: " & filename.string)
proc getOptSpeed(conf: ConfigRef; c: TSystemCC): string =
@@ -509,8 +427,9 @@ proc noAbsolutePaths(conf: ConfigRef): bool {.inline.} =
# `optGenMapping` is included here for niminst.
result = conf.globalOptions * {optGenScript, optGenMapping} != {}
proc cFileSpecificOptions(conf: ConfigRef; nimname: string): string =
proc cFileSpecificOptions(conf: ConfigRef; nimname, fullNimFile: string): string =
result = conf.compileOptions
for option in conf.compileOptionsCmd:
if strutils.find(result, option, 0) < 0:
addOpt(result, option)
@@ -530,21 +449,22 @@ proc cFileSpecificOptions(conf: ConfigRef; nimname: string): string =
let key = nimname & ".always"
if existsConfigVar(conf, key): addOpt(result, getConfigVar(conf, key))
addOpt(result, conf.cfileSpecificOptions.getOrDefault(fullNimFile))
proc getCompileOptions(conf: ConfigRef): string =
result = cFileSpecificOptions(conf, "__dummy__")
result = cFileSpecificOptions(conf, "__dummy__", "__dummy__")
proc vccplatform(conf: ConfigRef): string =
# VCC specific but preferable over the config hacks people
# had to do before, see #11306
case conf.target.targetCPU
of cpuI386:
result = " --platform:x86"
of cpuArm:
result = " --platform:arm"
of cpuAmd64:
result = " --platform:amd64"
else:
result = ""
if conf.cCompiler == ccVcc:
let exe = getConfigVar(conf, conf.cCompiler, ".exe")
if "vccexe.exe" == extractFilename(exe):
result = case conf.target.targetCPU
of cpuI386: " --platform:x86"
of cpuArm: " --platform:arm"
of cpuAmd64: " --platform:amd64"
else: ""
proc getLinkOptions(conf: ConfigRef): string =
result = conf.linkOptions & " " & conf.linkOptionsCmd & " "
@@ -557,43 +477,96 @@ proc needsExeExt(conf: ConfigRef): bool {.inline.} =
result = (optGenScript in conf.globalOptions and conf.target.targetOS == osWindows) or
(conf.target.hostOS == osWindows)
proc useCpp(conf: ConfigRef; cfile: AbsoluteFile): bool =
conf.backend == backendCpp and not cfile.string.endsWith(".c")
proc envFlags(conf: ConfigRef): string =
result = if conf.backend == backendCpp:
getEnv("CXXFLAGS")
else:
getEnv("CFLAGS")
proc getCompilerExe(conf: ConfigRef; compiler: TSystemCC; cfile: AbsoluteFile): string =
result = if conf.cmd == cmdCompileToCpp and not cfile.string.endsWith(".c"):
CC[compiler].cppCompiler
else:
CC[compiler].compilerExe
if compiler == ccEnv:
result = if useCpp(conf, cfile):
getEnv("CXX")
else:
getEnv("CC")
else:
result = if useCpp(conf, cfile):
CC[compiler].cppCompiler
else:
CC[compiler].compilerExe
if result.len == 0:
rawMessage(conf, errGenerated,
"Compiler '$1' doesn't support the requested target" %
CC[compiler].name)
proc ccHasSaneOverflow*(conf: ConfigRef): bool =
if conf.cCompiler == ccGcc:
result = false # assume an old or crappy GCC
var exe = getConfigVar(conf, conf.cCompiler, ".exe")
if exe.len == 0: exe = CC[conf.cCompiler].compilerExe
let (s, exitCode) = try: execCmdEx(exe & " --version") except: ("", 1)
if exitCode == 0:
var i = 0
var j = 0
# the version is the last part of the first line:
while i < s.len and s[i] != '\n':
if s[i] in {' ', '\t'}: j = i+1
inc i
if j > 0:
var major = 0
while j < s.len and s[j] in {'0'..'9'}:
major = major * 10 + (ord(s[j]) - ord('0'))
inc j
if i < s.len and s[j] == '.': inc j
while j < s.len and s[j] in {'0'..'9'}:
inc j
if j+1 < s.len and s[j] == '.' and s[j+1] in {'0'..'9'}:
# we found a third version number, chances are high
# we really parsed the version:
result = major >= 5
else:
result = conf.cCompiler == ccCLang
proc getLinkerExe(conf: ConfigRef; compiler: TSystemCC): string =
result = if CC[compiler].linkerExe.len > 0: CC[compiler].linkerExe
elif optMixedMode in conf.globalOptions and conf.cmd != cmdCompileToCpp: CC[compiler].cppCompiler
elif optMixedMode in conf.globalOptions and conf.backend != backendCpp: CC[compiler].cppCompiler
else: getCompilerExe(conf, compiler, AbsoluteFile"")
proc getCompileCFileCmd*(conf: ConfigRef; cfile: Cfile, isMainFile = false): string =
var c = conf.cCompiler
var options = cFileSpecificOptions(conf, cfile.nimname)
proc getCompileCFileCmd*(conf: ConfigRef; cfile: Cfile,
isMainFile = false; produceOutput = false): string =
let c = conf.cCompiler
# We produce files like module.nim.cpp, so the absolute Nim filename is not
# cfile.name but `cfile.cname.changeFileExt("")`:
var options = cFileSpecificOptions(conf, cfile.nimname, cfile.cname.changeFileExt("").string)
if useCpp(conf, cfile.cname):
# needs to be prepended so that --passc:-std=c++17 can override default.
# we could avoid allocation by making cFileSpecificOptions inplace
options = CC[c].cppXsupport & ' ' & options
var exe = getConfigVar(conf, c, ".exe")
if exe.len == 0: exe = getCompilerExe(conf, c, cfile.cname)
if needsExeExt(conf): exe = addFileExt(exe, "exe")
if (optGenDynLib in conf.globalOptions or (conf.hcrOn and not isMainFile)) and
ospNeedsPIC in platform.OS[conf.target.targetOS].props:
add(options, ' ' & CC[c].pic)
options.add(' ' & CC[c].pic)
var includeCmd, compilePattern: string
if cfile.customArgs != "":
options.add ' '
options.add cfile.customArgs
var compilePattern: string
# compute include paths:
var includeCmd = CC[c].includeCmd & quoteShell(conf.libpath)
if not noAbsolutePaths(conf):
# compute include paths:
includeCmd = CC[c].includeCmd & quoteShell(conf.libpath)
for includeDir in items(conf.cIncludes):
includeCmd.add(join([CC[c].includeCmd, includeDir.quoteShell]))
compilePattern = joinPath(conf.cCompilerPath, exe)
else:
includeCmd = ""
compilePattern = getCompilerExe(conf, c, cfile.cname)
includeCmd.add(join([CC[c].includeCmd, quoteShell(conf.projectPath.string)]))
@@ -603,7 +576,7 @@ proc getCompileCFileCmd*(conf: ConfigRef; cfile: Cfile, isMainFile = false): str
var objfile =
if cfile.obj.isEmpty:
if not cfile.flags.contains(CfileFlag.External) or noAbsolutePaths(conf):
if CfileFlag.External notin cfile.flags or noAbsolutePaths(conf):
toObjFile(conf, cf).string
else:
completeCfilePath(conf, toObjFile(conf, cf)).string
@@ -614,23 +587,36 @@ proc getCompileCFileCmd*(conf: ConfigRef; cfile: Cfile, isMainFile = false): str
# D files are required by nintendo switch libs for
# compilation. They are basically a list of all includes.
let dfile = objfile.changeFileExt(".d").quoteShell()
let dfile = objfile.changeFileExt(".d").quoteShell
objfile = quoteShell(objfile)
let cfsh = quoteShell(cf)
result = quoteShell(compilePattern % [
"dfile", dfile,
"file", cfsh, "objfile", objfile, "options", options,
"file", cfsh, "objfile", quoteShell(objfile), "options", options,
"include", includeCmd, "nim", getPrefixDir(conf).string,
"lib", conf.libpath.string])
add(result, ' ')
addf(result, CC[c].compileTmpl, [
"lib", conf.libpath.string,
"ccenvflags", envFlags(conf)])
if optProduceAsm in conf.globalOptions:
if CC[conf.cCompiler].produceAsm.len > 0:
let asmfile = objfile.changeFileExt(".asm").quoteShell
addOpt(result, CC[conf.cCompiler].produceAsm % ["asmfile", asmfile])
if produceOutput:
rawMessage(conf, hintUserRaw, "Produced assembler here: " & asmfile)
else:
if produceOutput:
rawMessage(conf, hintUserRaw, "Couldn't produce assembler listing " &
"for the selected C compiler: " & CC[conf.cCompiler].name)
result.add(' ')
result.addf(CC[c].compileTmpl, [
"dfile", dfile,
"file", cfsh, "objfile", objfile,
"file", cfsh, "objfile", quoteShell(objfile),
"options", options, "include", includeCmd,
"nim", quoteShell(getPrefixDir(conf)),
"lib", quoteShell(conf.libpath),
"vccplatform", vccplatform(conf)])
"vccplatform", vccplatform(conf),
"ccenvflags", envFlags(conf)])
proc footprint(conf: ConfigRef; cfile: Cfile): SecureHash =
result = secureHash(
@@ -641,8 +627,7 @@ proc footprint(conf: ConfigRef; cfile: Cfile): SecureHash =
getCompileCFileCmd(conf, cfile))
proc externalFileChanged(conf: ConfigRef; cfile: Cfile): bool =
if conf.cmd notin {cmdCompileToC, cmdCompileToCpp, cmdCompileToOC, cmdCompileToLLVM}:
return false
if conf.backend == backendJs: return false # pre-existing behavior, but not sure it's good
var hashFile = toGeneratedFile(conf, conf.withPackageName(cfile.cname), "sha1")
var currentHash = footprint(conf, cfile)
@@ -662,6 +647,10 @@ proc addExternalFileToCompile*(conf: ConfigRef; c: var Cfile) =
if optForceFullMake notin conf.globalOptions and fileExists(c.obj) and
not externalFileChanged(conf, c):
c.flags.incl CfileFlag.Cached
else:
# make sure Nim keeps recompiling the external file on reruns
# if compilation is not successful
discard tryRemoveFile(c.obj.string)
conf.toCompile.add(c)
proc addExternalFileToCompile*(conf: ConfigRef; filename: AbsoluteFile) =
@@ -670,37 +659,14 @@ proc addExternalFileToCompile*(conf: ConfigRef; filename: AbsoluteFile) =
flags: {CfileFlag.External})
addExternalFileToCompile(conf, c)
proc compileCFiles(conf: ConfigRef; list: CfileList, script: var Rope, cmds: var TStringSeq,
prettyCmds: var TStringSeq) =
var currIdx = 0
for it in list:
# call the C compiler for the .c file:
if it.flags.contains(CfileFlag.Cached): continue
var compileCmd = getCompileCFileCmd(conf, it, currIdx == list.len - 1)
inc currIdx
if optCompileOnly notin conf.globalOptions:
add(cmds, compileCmd)
let (_, name, _) = splitFile(it.cname)
add(prettyCmds, if hintCC in conf.notes: "CC: " & demanglePackageName(name) else: "")
if optGenScript in conf.globalOptions:
add(script, compileCmd)
add(script, "\n")
proc getLinkCmd(conf: ConfigRef; output: AbsoluteFile,
objfiles: string, isDllBuild: bool): string =
if optGenStaticLib in conf.globalOptions:
var libname: string
if not conf.outFile.isEmpty:
libname = conf.outFile.string.expandTilde
if not libname.isAbsolute():
libname = getCurrentDir() / libname
else:
libname = (libNameTmpl(conf) % splitFile(conf.projectName).name)
result = CC[conf.cCompiler].buildLib % ["libfile", quoteShell(libname),
result = CC[conf.cCompiler].buildLib % ["libfile", quoteShell(output),
"objfiles", objfiles]
else:
var linkerExe = getConfigVar(conf, conf.cCompiler, ".linkerexe")
if len(linkerExe) == 0: linkerExe = getLinkerExe(conf, conf.cCompiler)
if linkerExe.len == 0: linkerExe = getLinkerExe(conf, conf.cCompiler)
# bug #6452: We must not use ``quoteShell`` here for ``linkerExe``
if needsExeExt(conf): linkerExe = addFileExt(linkerExe, "exe")
if noAbsolutePaths(conf): result = linkerExe
@@ -730,7 +696,7 @@ proc getLinkCmd(conf: ConfigRef; output: AbsoluteFile,
"buildgui", buildgui, "options", linkOptions, "objfiles", objfiles,
"exefile", exefile, "nim", getPrefixDir(conf).string, "lib", conf.libpath.string])
result.add ' '
addf(result, linkTmpl, ["builddll", builddll,
result.addf(linkTmpl, ["builddll", builddll,
"mapfile", mapfile,
"buildgui", buildgui, "options", linkOptions,
"objfiles", objfiles, "exefile", exefile,
@@ -793,22 +759,26 @@ template tryExceptOSErrorMessage(conf: ConfigRef; errorPrefix: string = "", body
(ose.msg & " " & $ose.errorCode))
raise
proc getExtraCmds(conf: ConfigRef; output: AbsoluteFile): seq[string] =
when defined(macosx):
if optCDebug in conf.globalOptions and optGenStaticLib notin conf.globalOptions:
# if needed, add an option to skip or override location
result.add "dsymutil " & $(output).quoteShell
proc execLinkCmd(conf: ConfigRef; linkCmd: string) =
tryExceptOSErrorMessage(conf, "invocation of external linker program failed."):
execExternalProgram(conf, linkCmd,
if optListCmd in conf.globalOptions or conf.verbosity > 1: hintExecuting else: hintLinking)
execExternalProgram(conf, linkCmd, hintLinking)
proc execCmdsInParallel(conf: ConfigRef; cmds: seq[string]; prettyCb: proc (idx: int)) =
let runCb = proc (idx: int, p: Process) =
let exitCode = p.peekExitCode
if exitCode != 0:
rawMessage(conf, errGenerated, "execution of an external compiler program '" &
cmds[idx] & "' failed with exit code: " & $exitCode & "\n\n" &
p.outputStream.readAll.strip)
cmds[idx] & "' failed with exit code: " & $exitCode & "\n\n")
if conf.numberOfProcessors == 0: conf.numberOfProcessors = countProcessors()
var res = 0
if conf.numberOfProcessors <= 1:
for i in 0 .. high(cmds):
for i in 0..high(cmds):
tryExceptOSErrorMessage(conf, "invocation of external compiler program failed."):
res = execWithEcho(conf, cmds[i])
if res != 0:
@@ -816,15 +786,8 @@ proc execCmdsInParallel(conf: ConfigRef; cmds: seq[string]; prettyCb: proc (idx:
cmds[i])
else:
tryExceptOSErrorMessage(conf, "invocation of external compiler program failed."):
if optListCmd in conf.globalOptions or conf.verbosity > 1:
res = execProcesses(cmds, {poEchoCmd, poStdErrToStdOut, poUsePath},
conf.numberOfProcessors, afterRunEvent=runCb)
elif conf.verbosity == 1:
res = execProcesses(cmds, {poStdErrToStdOut, poUsePath},
res = execProcesses(cmds, {poStdErrToStdOut, poUsePath, poParentStreams},
conf.numberOfProcessors, prettyCb, afterRunEvent=runCb)
else:
res = execProcesses(cmds, {poStdErrToStdOut, poUsePath},
conf.numberOfProcessors, afterRunEvent=runCb)
if res != 0:
if conf.numberOfProcessors <= 1:
rawMessage(conf, errGenerated, "execution of an external program failed: '$1'" %
@@ -866,21 +829,38 @@ proc hcrLinkTargetName(conf: ConfigRef, objFile: string, isMain = false): Absolu
else: platform.OS[conf.target.targetOS].dllFrmt % basename
result = conf.getNimcacheDir / RelativeFile(targetName)
proc displayProgressCC(conf: ConfigRef, path, compileCmd: string): string =
if conf.hasHint(hintCC):
if optListCmd in conf.globalOptions or conf.verbosity > 1:
result = MsgKindToStr[hintCC] % (demanglePackageName(path.splitFile.name) & ": " & compileCmd)
else:
result = MsgKindToStr[hintCC] % demanglePackageName(path.splitFile.name)
proc callCCompiler*(conf: ConfigRef) =
var
linkCmd: string
extraCmds: seq[string]
if conf.globalOptions * {optCompileOnly, optGenScript} == {optCompileOnly}:
return # speed up that call if only compiling and no script shall be
# generated
#var c = cCompiler
var script: Rope = nil
var cmds: TStringSeq = @[]
var prettyCmds: TStringSeq = @[]
var cmds: TStringSeq
var prettyCmds: TStringSeq
let prettyCb = proc (idx: int) =
when declared(echo):
let cmd = prettyCmds[idx]
if cmd != "": echo cmd
compileCFiles(conf, conf.toCompile, script, cmds, prettyCmds)
if prettyCmds[idx].len > 0: echo prettyCmds[idx]
for idx, it in conf.toCompile:
# call the C compiler for the .c file:
if CfileFlag.Cached in it.flags: continue
let compileCmd = getCompileCFileCmd(conf, it, idx == conf.toCompile.len - 1, produceOutput=true)
if optCompileOnly notin conf.globalOptions:
cmds.add(compileCmd)
prettyCmds.add displayProgressCC(conf, $it.cname, compileCmd)
if optGenScript in conf.globalOptions:
script.add(compileCmd)
script.add("\n")
if optCompileOnly notin conf.globalOptions:
execCmdsInParallel(conf, cmds, prettyCb)
if optNoLinking notin conf.globalOptions:
@@ -888,8 +868,8 @@ proc callCCompiler*(conf: ConfigRef) =
var objfiles = ""
for it in conf.externalToLink:
let objFile = if noAbsolutePaths(conf): it.extractFilename else: it
add(objfiles, ' ')
add(objfiles, quoteShell(
objfiles.add(' ')
objfiles.add(quoteShell(
addFileExt(objFile, CC[conf.cCompiler].objExt)))
if conf.hcrOn: # lets assume that optCompileOnly isn't on
@@ -899,14 +879,14 @@ proc callCCompiler*(conf: ConfigRef) =
# don't relink each of the many binaries (one for each source file) if the nim code is
# cached because that would take too much time for small changes - the only downside to
# this is that if an external-to-link file changes the final target wouldn't be relinked
if x.flags.contains(CfileFlag.Cached): continue
if CfileFlag.Cached in x.flags: continue
# we pass each object file as if it is the project file - a .dll will be created for each such
# object file in the nimcache directory, and only in the case of the main project file will
# there be probably an executable (if the project is such) which will be copied out of the nimcache
let objFile = conf.getObjFilePath(x)
let buildDll = idx != mainFileIdx
let linkTarget = conf.hcrLinkTargetName(objFile, not buildDll)
add(cmds, getLinkCmd(conf, linkTarget, objfiles & " " & quoteShell(objFile), buildDll))
cmds.add(getLinkCmd(conf, linkTarget, objfiles & " " & quoteShell(objFile), buildDll))
# try to remove all .pdb files for the current binary so they don't accumulate endlessly in the nimcache
# for more info check the comment inside of getLinkCmd() where the /PDB:<filename> MSVC flag is used
if isVSCompatible(conf):
@@ -917,7 +897,7 @@ proc callCCompiler*(conf: ConfigRef) =
prettyCmds = map(prettyCmds, proc (curr: string): string = return curr.replace("CC", "Link"))
execCmdsInParallel(conf, cmds, prettyCb)
# only if not cached - copy the resulting main file from the nimcache folder to its originally intended destination
if not conf.toCompile[mainFileIdx].flags.contains(CfileFlag.Cached):
if CfileFlag.Cached notin conf.toCompile[mainFileIdx].flags:
let mainObjFile = getObjFilePath(conf, conf.toCompile[mainFileIdx])
var src = conf.hcrLinkTargetName(mainObjFile, true)
var dst = conf.prepareToWriteOutput
@@ -925,11 +905,12 @@ proc callCCompiler*(conf: ConfigRef) =
else:
for x in conf.toCompile:
let objFile = if noAbsolutePaths(conf): x.obj.extractFilename else: x.obj.string
add(objfiles, ' ')
add(objfiles, quoteShell(objFile))
objfiles.add(' ')
objfiles.add(quoteShell(objFile))
let mainOutput = if optGenScript notin conf.globalOptions: conf.prepareToWriteOutput
else: AbsoluteFile(conf.projectName)
linkCmd = getLinkCmd(conf, mainOutput, objfiles)
extraCmds = getExtraCmds(conf, mainOutput)
if optCompileOnly notin conf.globalOptions:
const MaxCmdLen = when defined(windows): 8_000 else: 32_000
if linkCmd.len > MaxCmdLen:
@@ -939,11 +920,13 @@ proc callCCompiler*(conf: ConfigRef) =
linkViaResponseFile(conf, linkCmd)
else:
execLinkCmd(conf, linkCmd)
for cmd in extraCmds:
execExternalProgram(conf, cmd, hintExecuting)
else:
linkCmd = ""
if optGenScript in conf.globalOptions:
add(script, linkCmd)
add(script, "\n")
script.add(linkCmd)
script.add("\n")
generateScript(conf, script)
#from json import escapeJson
@@ -962,17 +945,16 @@ proc writeJsonBuildInstructions*(conf: ConfigRef) =
f.write escapeJson(x)
proc cfiles(conf: ConfigRef; f: File; buf: var string; clist: CfileList, isExternal: bool) =
var i = 0
for it in clist:
var comma = false
for i, it in clist:
if CfileFlag.Cached in it.flags: continue
let compileCmd = getCompileCFileCmd(conf, it)
if i > 0: lit ",\L"
if comma: lit ",\L" else: comma = true
lit "["
str it.cname.string
lit ", "
str compileCmd
lit "]"
inc i
proc linkfiles(conf: ConfigRef; f: File; buf, objfiles: var string; clist: CfileList;
llist: seq[string]) =
@@ -981,16 +963,16 @@ proc writeJsonBuildInstructions*(conf: ConfigRef) =
let objfile = if noAbsolutePaths(conf): it.extractFilename
else: it
let objstr = addFileExt(objfile, CC[conf.cCompiler].objExt)
add(objfiles, ' ')
add(objfiles, objstr)
objfiles.add(' ')
objfiles.add(objstr)
if pastStart: lit ",\L"
str objstr
pastStart = true
for it in clist:
let objstr = quoteShell(it.obj)
add(objfiles, ' ')
add(objfiles, objstr)
objfiles.add(' ')
objfiles.add(objstr)
if pastStart: lit ",\L"
str objstr
pastStart = true
@@ -1013,10 +995,16 @@ proc writeJsonBuildInstructions*(conf: ConfigRef) =
var buf = newStringOfCap(50)
let jsonFile = conf.getNimcacheDir / RelativeFile(conf.projectName & ".json")
conf.jsonBuildFile = jsonFile
let output = conf.absOutFile
var f: File
if open(f, jsonFile.string, fmWrite):
lit "{\"compile\":[\L"
lit "{\L"
lit "\"outputFile\": "
str $output
lit ",\L\"compile\":[\L"
cfiles(conf, f, buf, conf.toCompile, false)
lit "],\L\"link\":[\L"
var objfiles = ""
@@ -1024,7 +1012,13 @@ proc writeJsonBuildInstructions*(conf: ConfigRef) =
linkfiles(conf, f, buf, objfiles, conf.toCompile, conf.externalToLink)
lit "],\L\"linkcmd\": "
str getLinkCmd(conf, conf.absOutFile, objfiles)
str getLinkCmd(conf, output, objfiles)
lit ",\L\"extraCmds\": "
lit $(%* getExtraCmds(conf, conf.absOutFile))
lit ",\L\"stdinInput\": "
lit $(%* conf.projectIsStdin)
if optRun in conf.globalOptions or isDefined(conf, "nimBetterRun"):
lit ",\L\"cmdline\": "
@@ -1052,6 +1046,13 @@ proc changeDetectedViaJsonBuildInstructions*(conf: ConfigRef; projectfile: Absol
return true
if hashNimExe() != data["nimexe"].getStr:
return true
if not data.hasKey("stdinInput"): return true
let stdinInput = data["stdinInput"].getBool
if conf.projectIsStdin or stdinInput:
# could optimize by returning false if stdin input was the same,
# but I'm not sure how to get full stding input
return true
let depfilesPairs = data["depfiles"]
doAssert depfilesPairs.kind == JArray
for p in depfilesPairs:
@@ -1071,50 +1072,68 @@ proc runJsonBuildInstructions*(conf: ConfigRef; projectfile: AbsoluteFile) =
let jsonFile = toGeneratedFile(conf, projectfile, "json")
try:
let data = json.parseFile(jsonFile.string)
let output = data["outputFile"].getStr
createDir output.parentDir
let outputCurrent = $conf.absOutFile
if output != outputCurrent:
# previously, any specified output file would be silently ignored;
# simply copying won't work in some cases, for example with `extraCmds`,
# so we just make it an error, user should use same command for jsonscript
# as was used with --compileOnly.
globalError(conf, gCmdLineInfo, "jsonscript command outputFile '$1' must match '$2' which was specified during --compileOnly, see \"outputFile\" entry in '$3' " % [outputCurrent, output, jsonFile.string])
let toCompile = data["compile"]
doAssert toCompile.kind == JArray
var cmds: TStringSeq = @[]
var prettyCmds: TStringSeq = @[]
var cmds: TStringSeq
var prettyCmds: TStringSeq
let prettyCb = proc (idx: int) =
if prettyCmds[idx].len > 0: echo prettyCmds[idx]
for c in toCompile:
doAssert c.kind == JArray
doAssert c.len >= 2
add(cmds, c[1].getStr)
let (_, name, _) = splitFile(c[0].getStr)
add(prettyCmds, "CC: " & demanglePackageName(name))
cmds.add(c[1].getStr)
prettyCmds.add displayProgressCC(conf, c[0].getStr, c[1].getStr)
let prettyCb = proc (idx: int) =
when declared(echo):
echo prettyCmds[idx]
execCmdsInParallel(conf, cmds, prettyCb)
let linkCmd = data["linkcmd"]
doAssert linkCmd.kind == JString
execLinkCmd(conf, linkCmd.getStr)
if data.hasKey("extraCmds"):
let extraCmds = data["extraCmds"]
doAssert extraCmds.kind == JArray
for cmd in extraCmds:
doAssert cmd.kind == JString, $cmd.kind
let cmd2 = cmd.getStr
execExternalProgram(conf, cmd2, hintExecuting)
except:
when declared(echo):
echo getCurrentException().getStackTrace()
quit "error evaluating JSON file: " & jsonFile.string
let e = getCurrentException()
quit "\ncaught exception:\n" & e.msg & "\nstacktrace:\n" & e.getStackTrace() &
"error evaluating JSON file: " & jsonFile.string
proc genMappingFiles(conf: ConfigRef; list: CfileList): Rope =
for it in list:
addf(result, "--file:r\"$1\"$N", [rope(it.cname.string)])
result.addf("--file:r\"$1\"$N", [rope(it.cname.string)])
proc writeMapping*(conf: ConfigRef; symbolMapping: Rope) =
if optGenMapping notin conf.globalOptions: return
var code = rope("[C_Files]\n")
add(code, genMappingFiles(conf, conf.toCompile))
add(code, "\n[C_Compiler]\nFlags=")
add(code, strutils.escape(getCompileOptions(conf)))
code.add(genMappingFiles(conf, conf.toCompile))
code.add("\n[C_Compiler]\nFlags=")
code.add(strutils.escape(getCompileOptions(conf)))
add(code, "\n[Linker]\nFlags=")
add(code, strutils.escape(getLinkOptions(conf) & " " &
code.add("\n[Linker]\nFlags=")
code.add(strutils.escape(getLinkOptions(conf) & " " &
getConfigVar(conf, conf.cCompiler, ".options.linker")))
add(code, "\n[Environment]\nlibpath=")
add(code, strutils.escape(conf.libpath.string))
code.add("\n[Environment]\nlibpath=")
code.add(strutils.escape(conf.libpath.string))
addf(code, "\n[Symbols]$n$1", [symbolMapping])
code.addf("\n[Symbols]$n$1", [symbolMapping])
let filename = conf.projectPath / RelativeFile"mapping.txt"
if not writeRope(code, filename):
rawMessage(conf, errGenerated, "could not write to file: " & filename.string)

View File

@@ -75,7 +75,7 @@ proc parseLine(p: var TTmplParser) =
let d = j
var keyw = ""
while j < len and p.x[j] in PatternChars:
add(keyw, p.x[j])
keyw.add(p.x[j])
inc(j)
scanPar(p, j)
@@ -199,8 +199,8 @@ proc parseLine(p: var TTmplParser) =
inc(j)
llStreamWrite(p.outp, "\\n\"")
proc filterTmpl*(stdin: PLLStream, filename: AbsoluteFile,
call: PNode; conf: ConfigRef): PLLStream =
proc filterTmpl*(conf: ConfigRef, stdin: PLLStream, filename: AbsoluteFile,
call: PNode): PLLStream =
var p: TTmplParser
p.config = conf
p.info = newLineInfo(conf, filename, 0, 0)
@@ -214,9 +214,9 @@ proc filterTmpl*(stdin: PLLStream, filename: AbsoluteFile,
p.x = newStringOfCap(120)
# do not process the first line which contains the directive:
if llStreamReadLine(p.inp, p.x):
p.info.line = p.info.line + 1'u16
inc p.info.line
while llStreamReadLine(p.inp, p.x):
p.info.line = p.info.line + 1'u16
inc p.info.line
parseLine(p)
newLine(p)
result = p.outp

View File

@@ -20,13 +20,13 @@ proc invalidPragma(conf: ConfigRef; n: PNode) =
proc getArg(conf: ConfigRef; n: PNode, name: string, pos: int): PNode =
result = nil
if n.kind in {nkEmpty..nkNilLit}: return
for i in 1 ..< len(n):
if n.sons[i].kind == nkExprEqExpr:
if n.sons[i].sons[0].kind != nkIdent: invalidPragma(conf, n)
if cmpIgnoreStyle(n.sons[i].sons[0].ident.s, name) == 0:
return n.sons[i].sons[1]
for i in 1..<n.len:
if n[i].kind == nkExprEqExpr:
if n[i][0].kind != nkIdent: invalidPragma(conf, n)
if cmpIgnoreStyle(n[i][0].ident.s, name) == 0:
return n[i][1]
elif i == pos:
return n.sons[i]
return n[i]
proc charArg*(conf: ConfigRef; n: PNode, name: string, pos: int, default: char): char =
var x = getArg(conf, n, name, pos)
@@ -55,7 +55,7 @@ proc filterStrip*(conf: ConfigRef; stdin: PLLStream, filename: AbsoluteFile, cal
var line = newStringOfCap(80)
while llStreamReadLine(stdin, line):
var stripped = strip(line, leading, trailing)
if len(pattern) == 0 or startsWith(stripped, pattern):
if pattern.len == 0 or startsWith(stripped, pattern):
llStreamWriteln(result, stripped)
else:
llStreamWriteln(result, line)
@@ -63,7 +63,7 @@ proc filterStrip*(conf: ConfigRef; stdin: PLLStream, filename: AbsoluteFile, cal
proc filterReplace*(conf: ConfigRef; stdin: PLLStream, filename: AbsoluteFile, call: PNode): PLLStream =
var sub = strArg(conf, call, "sub", 1, "")
if len(sub) == 0: invalidPragma(conf, call)
if sub.len == 0: invalidPragma(conf, call)
var by = strArg(conf, call, "by", 2, "")
result = llStreamOpen("")
var line = newStringOfCap(80)

View File

@@ -1,89 +0,0 @@
#
#
# The Nim Compiler
# (c) Copyright 2015 Andreas Rumpf
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
## This module implements for loop detection for better C code generation.
import ast, astalgo
const
someCmp = {mEqI, mEqF64, mEqEnum, mEqCh, mEqB, mEqRef, mEqProc,
mEqUntracedRef, mLeI, mLeF64, mLeU, mLeU64, mLeEnum,
mLeCh, mLeB, mLePtr, mLtI, mLtF64, mLtU, mLtU64, mLtEnum,
mLtCh, mLtB, mLtPtr}
proc isCounter(s: PSym): bool {.inline.} =
s.kind in {skResult, skVar, skLet, skTemp} and
{sfGlobal, sfAddrTaken} * s.flags == {}
proc isCall(n: PNode): bool {.inline.} =
n.kind in nkCallKinds and n[0].kind == nkSym
proc fromSystem(op: PSym): bool = sfSystemModule in getModule(op).flags
proc getCounter(lastStmt: PNode): PSym =
if lastStmt.isCall:
let op = lastStmt.sym
if op.magic in {mDec, mInc} or
((op.name.s == "+=" or op.name.s == "-=") and op.fromSystem):
if op[1].kind == nkSym and isCounter(op[1].sym):
result = op[1].sym
proc counterInTree(n, loop: PNode; counter: PSym): bool =
# prune the search tree: within the loop the counter may be used:
if n == loop: return
case n.kind
of nkSym:
if n.sym == counter: return true
of nkVarSection, nkLetSection:
# definitions are fine!
for it in n:
if counterInTree(it.lastSon): return true
else:
for i in 0 ..< safeLen(n):
if counterInTree(n[i], loop, counter): return true
proc copyExcept(n: PNode, x, dest: PNode) =
if x == n: return
if n.kind in {nkStmtList, nkStmtListExpr}:
for i in 0 ..< n.len: copyExcept(n[i], x, dest)
else:
dest.add n
type
ForLoop* = object
counter*: PSym
init*, cond*, increment*, body*: PNode
proc extractForLoop*(loop, fullTree: PNode): ForLoop =
## returns 'counter == nil' if the while loop 'n' is not a for loop:
assert loop.kind == nkWhileStmt
let cond == loop[0]
if not cond.isCall: return
if cond[0].sym.magic notin someCmp: return
var lastStmt = loop[1]
while lastStmt.kind in {nkStmtList, nkStmtListExpr}:
lastStmt = lastStmt.lastSon
let counter = getCounter(lastStmt)
if counter.isNil or counter.ast.isNil: return
template `=~`(a, b): expr = a.kind == nkSym and a.sym == b
if cond[1] =~ counter or cond[2] =~ counter:
# ok, now check 'counter' is not used *after* the loop
if counterInTree(fullTree, loop, counter): return
# ok, success, fill in the fields:
result.counter = counter
result.init = counter.ast
result.cond = cond
result.increment = lastStmt
result.body = newNodeI(nkStmtList, loop[1].info)
copyExcept(loop[1], lastStmt, result.body)

View File

@@ -14,18 +14,17 @@ import ast, astalgo, msgs, magicsys, nimsets, trees, types, renderer, idents,
const
someEq = {mEqI, mEqF64, mEqEnum, mEqCh, mEqB, mEqRef, mEqProc,
mEqUntracedRef, mEqStr, mEqSet, mEqCString}
mEqStr, mEqSet, mEqCString}
# set excluded here as the semantics are vastly different:
someLe = {mLeI, mLeF64, mLeU, mLeU64, mLeEnum,
someLe = {mLeI, mLeF64, mLeU, mLeEnum,
mLeCh, mLeB, mLePtr, mLeStr}
someLt = {mLtI, mLtF64, mLtU, mLtU64, mLtEnum,
someLt = {mLtI, mLtF64, mLtU, mLtEnum,
mLtCh, mLtB, mLtPtr, mLtStr}
someLen = {mLengthOpenArray, mLengthStr, mLengthArray, mLengthSeq,
mXLenStr, mXLenSeq}
someLen = {mLengthOpenArray, mLengthStr, mLengthArray, mLengthSeq}
someIn = {mInRange, mInSet}
someIn = {mInSet}
someHigh = {mHigh}
# we don't list unsigned here because wrap around semantics suck for
@@ -47,7 +46,7 @@ proc isLet(n: PNode): bool =
if n.sym.kind in {skLet, skTemp, skForVar}:
result = true
elif n.sym.kind == skParam and skipTypes(n.sym.typ,
abstractInst).kind != tyVar:
abstractInst).kind notin {tyVar}:
result = true
proc isVar(n: PNode): bool =
@@ -65,16 +64,16 @@ proc isLetLocation(m: PNode, isApprox: bool): bool =
while true:
case n.kind
of nkDotExpr, nkCheckedFieldExpr, nkObjUpConv, nkObjDownConv:
n = n.sons[0]
n = n[0]
of nkDerefExpr, nkHiddenDeref:
n = n.sons[0]
n = n[0]
inc derefs
of nkBracketExpr:
if isConstExpr(n.sons[1]) or isLet(n.sons[1]) or isConstExpr(n.sons[1].skipConv):
n = n.sons[0]
if isConstExpr(n[1]) or isLet(n[1]) or isConstExpr(n[1].skipConv):
n = n[0]
else: return
of nkHiddenStdConv, nkHiddenSubConv, nkConv:
n = n.sons[1]
n = n[1]
else:
break
result = n.isLet and derefs <= ord(isApprox)
@@ -85,8 +84,8 @@ proc interestingCaseExpr*(m: PNode): bool = isLetLocation(m, true)
type
Operators* = object
opNot, opContains, opLe, opLt, opAnd, opOr, opIsNil, opEq: PSym
opAdd, opSub, opMul, opDiv, opLen: PSym
opNot*, opContains*, opLe*, opLt*, opAnd*, opOr*, opIsNil*, opEq*: PSym
opAdd*, opSub*, opMul*, opDiv*, opLen*: PSym
proc initOperators*(g: ModuleGraph): Operators =
result.opLe = createMagic(g, "<=", mLeI)
@@ -105,34 +104,34 @@ proc initOperators*(g: ModuleGraph): Operators =
proc swapArgs(fact: PNode, newOp: PSym): PNode =
result = newNodeI(nkCall, fact.info, 3)
result.sons[0] = newSymNode(newOp)
result.sons[1] = fact.sons[2]
result.sons[2] = fact.sons[1]
result[0] = newSymNode(newOp)
result[1] = fact[2]
result[2] = fact[1]
proc neg(n: PNode; o: Operators): PNode =
if n == nil: return nil
case n.getMagic
of mNot:
result = n.sons[1]
result = n[1]
of someLt:
# not (a < b) == a >= b == b <= a
result = swapArgs(n, o.opLe)
of someLe:
result = swapArgs(n, o.opLt)
of mInSet:
if n.sons[1].kind != nkCurly: return nil
let t = n.sons[2].typ.skipTypes(abstractInst)
if n[1].kind != nkCurly: return nil
let t = n[2].typ.skipTypes(abstractInst)
result = newNodeI(nkCall, n.info, 3)
result.sons[0] = n.sons[0]
result.sons[2] = n.sons[2]
result[0] = n[0]
result[2] = n[2]
if t.kind == tyEnum:
var s = newNodeIT(nkCurly, n.info, n.sons[1].typ)
var s = newNodeIT(nkCurly, n.info, n[1].typ)
for e in t.n:
let eAsNode = newIntNode(nkIntLit, e.sym.position)
if not inSet(n.sons[1], eAsNode): s.add eAsNode
result.sons[1] = s
if not inSet(n[1], eAsNode): s.add eAsNode
result[1] = s
#elif t.kind notin {tyString, tySequence} and lengthOrd(t) < 1000:
# result.sons[1] = complement(n.sons[1])
# result[1] = complement(n[1])
else:
# not ({2, 3, 4}.contains(x)) x != 2 and x != 3 and x != 4
# XXX todo
@@ -140,13 +139,13 @@ proc neg(n: PNode; o: Operators): PNode =
of mOr:
# not (a or b) --> not a and not b
let
a = n.sons[1].neg(o)
b = n.sons[2].neg(o)
a = n[1].neg(o)
b = n[2].neg(o)
if a != nil and b != nil:
result = newNodeI(nkCall, n.info, 3)
result.sons[0] = newSymNode(o.opAnd)
result.sons[1] = a
result.sons[2] = b
result[0] = newSymNode(o.opAnd)
result[1] = a
result[2] = b
elif a != nil:
result = a
elif b != nil:
@@ -154,19 +153,19 @@ proc neg(n: PNode; o: Operators): PNode =
else:
# leave not (a == 4) as it is
result = newNodeI(nkCall, n.info, 2)
result.sons[0] = newSymNode(o.opNot)
result.sons[1] = n
result[0] = newSymNode(o.opNot)
result[1] = n
proc buildCall(op: PSym; a: PNode): PNode =
proc buildCall*(op: PSym; a: PNode): PNode =
result = newNodeI(nkCall, a.info, 2)
result.sons[0] = newSymNode(op)
result.sons[1] = a
result[0] = newSymNode(op)
result[1] = a
proc buildCall(op: PSym; a, b: PNode): PNode =
proc buildCall*(op: PSym; a, b: PNode): PNode =
result = newNodeI(nkInfix, a.info, 3)
result.sons[0] = newSymNode(op)
result.sons[1] = a
result.sons[2] = b
result[0] = newSymNode(op)
result[1] = a
result[2] = b
proc `|+|`(a, b: PNode): PNode =
result = copyNode(a)
@@ -250,35 +249,35 @@ proc pred(n: PNode): PNode =
else:
result = n
proc buildLe*(o: Operators; a, b: PNode): PNode =
result = o.opLe.buildCall(a, b)
proc canon*(n: PNode; o: Operators): PNode =
# XXX for now only the new code in 'semparallel' uses this
if n.safeLen >= 1:
result = shallowCopy(n)
for i in 0 ..< n.len:
result.sons[i] = canon(n.sons[i], o)
for i in 0..<n.len:
result[i] = canon(n[i], o)
elif n.kind == nkSym and n.sym.kind == skLet and
n.sym.astdef.getMagic in (someEq + someAdd + someMul + someMin +
someMax + someHigh + {mUnaryLt} + someSub + someLen + someDiv):
someMax + someHigh + someSub + someLen + someDiv):
result = n.sym.astdef.copyTree
else:
result = n
case result.getMagic
of someEq, someAdd, someMul, someMin, someMax:
# these are symmetric; put value as last:
if result.sons[1].isValue and not result.sons[2].isValue:
result = swapArgs(result, result.sons[0].sym)
if result[1].isValue and not result[2].isValue:
result = swapArgs(result, result[0].sym)
# (4 + foo) + 2 --> (foo + 4) + 2
of someHigh:
# high == len+(-1)
result = o.opAdd.buildCall(o.opLen.buildCall(result[1]), minusOne())
of mUnaryLt:
result = buildCall(o.opAdd, result[1], minusOne())
of someSub:
# x - 4 --> x + (-4)
result = negate(result[1], result[2], result, o)
of someLen:
result.sons[0] = o.opLen.newSymNode
of someLt:
result[0] = o.opLen.newSymNode
of someLt - {mLtF64}:
# x < y same as x <= y-1:
let y = n[2].canon(o)
let p = pred(y)
@@ -318,16 +317,16 @@ proc canon*(n: PNode; o: Operators): PNode =
if plus != nil and not isLetLocation(x, true):
result = buildCall(result[0].sym, plus, y[1])
else: discard
elif x.isValue and y.getMagic in someAdd and y[2].isValue:
elif x.isValue and y.getMagic in someAdd and y[2].kind == x.kind:
# 0 <= a.len + 3
# -3 <= a.len
result.sons[1] = x |-| y[2]
result.sons[2] = y[1]
elif x.isValue and y.getMagic in someSub and y[2].isValue:
result[1] = x |-| y[2]
result[2] = y[1]
elif x.isValue and y.getMagic in someSub and y[2].kind == x.kind:
# 0 <= a.len - 3
# 3 <= a.len
result.sons[1] = x |+| y[2]
result.sons[2] = y[1]
result[1] = x |+| y[2]
result[2] = y[1]
else: discard
proc buildAdd*(a: PNode; b: BiggestInt; o: Operators): PNode =
@@ -336,41 +335,43 @@ proc buildAdd*(a: PNode; b: BiggestInt; o: Operators): PNode =
proc usefulFact(n: PNode; o: Operators): PNode =
case n.getMagic
of someEq:
if skipConv(n.sons[2]).kind == nkNilLit and (
isLetLocation(n.sons[1], false) or isVar(n.sons[1])):
result = o.opIsNil.buildCall(n.sons[1])
if skipConv(n[2]).kind == nkNilLit and (
isLetLocation(n[1], false) or isVar(n[1])):
result = o.opIsNil.buildCall(n[1])
else:
if isLetLocation(n.sons[1], true) or isLetLocation(n.sons[2], true):
if isLetLocation(n[1], true) or isLetLocation(n[2], true):
# XXX algebraic simplifications! 'i-1 < a.len' --> 'i < a.len+1'
result = n
elif n[1].getMagic in someLen or n[2].getMagic in someLen:
result = n
of someLe+someLt:
if isLetLocation(n.sons[1], true) or isLetLocation(n.sons[2], true):
if isLetLocation(n[1], true) or isLetLocation(n[2], true):
# XXX algebraic simplifications! 'i-1 < a.len' --> 'i < a.len+1'
result = n
elif n[1].getMagic in someLen or n[2].getMagic in someLen:
# XXX Rethink this whole idea of 'usefulFact' for semparallel
result = n
of mIsNil:
if isLetLocation(n.sons[1], false) or isVar(n.sons[1]):
if isLetLocation(n[1], false) or isVar(n[1]):
result = n
of someIn:
if isLetLocation(n.sons[1], true):
if isLetLocation(n[1], true):
result = n
of mAnd:
let
a = usefulFact(n.sons[1], o)
b = usefulFact(n.sons[2], o)
a = usefulFact(n[1], o)
b = usefulFact(n[2], o)
if a != nil and b != nil:
result = newNodeI(nkCall, n.info, 3)
result.sons[0] = newSymNode(o.opAnd)
result.sons[1] = a
result.sons[2] = b
result[0] = newSymNode(o.opAnd)
result[1] = a
result[2] = b
elif a != nil:
result = a
elif b != nil:
result = b
of mNot:
let a = usefulFact(n.sons[1], o)
let a = usefulFact(n[1], o)
if a != nil:
result = a.neg(o)
of mOr:
@@ -381,13 +382,13 @@ proc usefulFact(n: PNode; o: Operators): PNode =
# (x == 3) or (y == 2) ---> not ( not (x==3) and not (y == 2))
# not (x != 3 and y != 2)
let
a = usefulFact(n.sons[1], o).neg(o)
b = usefulFact(n.sons[2], o).neg(o)
a = usefulFact(n[1], o).neg(o)
b = usefulFact(n[2], o).neg(o)
if a != nil and b != nil:
result = newNodeI(nkCall, n.info, 3)
result.sons[0] = newSymNode(o.opAnd)
result.sons[1] = a
result.sons[2] = b
result[0] = newSymNode(o.opAnd)
result[1] = a
result[2] = b
result = result.neg(o)
elif n.kind == nkSym and n.sym.kind == skLet:
# consider:
@@ -404,10 +405,20 @@ type
TModel* = object
s*: seq[PNode] # the "knowledge base"
o*: Operators
beSmart*: bool
proc addFact*(m: var TModel, nn: PNode) =
let n = usefulFact(nn, m.o)
if n != nil: m.s.add n
if n != nil:
if not m.beSmart:
m.s.add n
else:
let c = canon(n, m.o)
if c.getMagic == mAnd:
addFact(m, c[1])
addFact(m, c[2])
else:
m.s.add c
proc addFactNeg*(m: var TModel, n: PNode) =
let n = n.neg(m.o)
@@ -442,18 +453,18 @@ proc sameTree*(a, b: PNode): bool =
of nkType: result = a.typ == b.typ
of nkEmpty, nkNilLit: result = true
else:
if len(a) == len(b):
for i in 0 ..< len(a):
if not sameTree(a.sons[i], b.sons[i]): return
if a.len == b.len:
for i in 0..<a.len:
if not sameTree(a[i], b[i]): return
result = true
proc hasSubTree(n, x: PNode): bool =
if n.sameTree(x): result = true
else:
for i in 0..safeLen(n)-1:
if hasSubTree(n.sons[i], x): return true
for i in 0..n.safeLen-1:
if hasSubTree(n[i], x): return true
proc invalidateFacts*(m: var TModel, n: PNode) =
proc invalidateFacts*(s: var seq[PNode], n: PNode) =
# We are able to guard local vars (as opposed to 'let' variables)!
# 'while p != nil: f(p); p = p.next'
# This is actually quite easy to do:
@@ -471,29 +482,32 @@ proc invalidateFacts*(m: var TModel, n: PNode) =
# The same mechanism could be used for more complex data stored on the heap;
# procs that 'write: []' cannot invalidate 'n.kind' for instance. In fact, we
# could CSE these expressions then and help C's optimizer.
for i in 0..high(m.s):
if m.s[i] != nil and m.s[i].hasSubTree(n): m.s[i] = nil
for i in 0..high(s):
if s[i] != nil and s[i].hasSubTree(n): s[i] = nil
proc invalidateFacts*(m: var TModel, n: PNode) =
invalidateFacts(m.s, n)
proc valuesUnequal(a, b: PNode): bool =
if a.isValue and b.isValue:
result = not sameValue(a, b)
proc impliesEq(fact, eq: PNode): TImplication =
let (loc, val) = if isLocation(eq.sons[1]): (1, 2) else: (2, 1)
let (loc, val) = if isLocation(eq[1]): (1, 2) else: (2, 1)
case fact.sons[0].sym.magic
case fact[0].sym.magic
of someEq:
if sameTree(fact.sons[1], eq.sons[loc]):
if sameTree(fact[1], eq[loc]):
# this is not correct; consider: a == b; a == 1 --> unknown!
if sameTree(fact.sons[2], eq.sons[val]): result = impYes
elif valuesUnequal(fact.sons[2], eq.sons[val]): result = impNo
elif sameTree(fact.sons[2], eq.sons[loc]):
if sameTree(fact.sons[1], eq.sons[val]): result = impYes
elif valuesUnequal(fact.sons[1], eq.sons[val]): result = impNo
if sameTree(fact[2], eq[val]): result = impYes
elif valuesUnequal(fact[2], eq[val]): result = impNo
elif sameTree(fact[2], eq[loc]):
if sameTree(fact[1], eq[val]): result = impYes
elif valuesUnequal(fact[1], eq[val]): result = impNo
of mInSet:
# remember: mInSet is 'contains' so the set comes first!
if sameTree(fact.sons[2], eq.sons[loc]) and isValue(eq.sons[val]):
if inSet(fact.sons[1], eq.sons[val]): result = impYes
if sameTree(fact[2], eq[loc]) and isValue(eq[val]):
if inSet(fact[1], eq[val]): result = impYes
else: result = impNo
of mNot, mOr, mAnd: assert(false, "impliesEq")
else: discard
@@ -536,28 +550,28 @@ proc compareSets(a, b: PNode): TImplication =
elif intersectSets(nil, a, b).len == 0: result = impNo
proc impliesIn(fact, loc, aSet: PNode): TImplication =
case fact.sons[0].sym.magic
case fact[0].sym.magic
of someEq:
if sameTree(fact.sons[1], loc):
if inSet(aSet, fact.sons[2]): result = impYes
if sameTree(fact[1], loc):
if inSet(aSet, fact[2]): result = impYes
else: result = impNo
elif sameTree(fact.sons[2], loc):
if inSet(aSet, fact.sons[1]): result = impYes
elif sameTree(fact[2], loc):
if inSet(aSet, fact[1]): result = impYes
else: result = impNo
of mInSet:
if sameTree(fact.sons[2], loc):
result = compareSets(fact.sons[1], aSet)
if sameTree(fact[2], loc):
result = compareSets(fact[1], aSet)
of someLe:
if sameTree(fact.sons[1], loc):
result = leImpliesIn(fact.sons[1], fact.sons[2], aSet)
elif sameTree(fact.sons[2], loc):
result = geImpliesIn(fact.sons[2], fact.sons[1], aSet)
if sameTree(fact[1], loc):
result = leImpliesIn(fact[1], fact[2], aSet)
elif sameTree(fact[2], loc):
result = geImpliesIn(fact[2], fact[1], aSet)
of someLt:
if sameTree(fact.sons[1], loc):
result = leImpliesIn(fact.sons[1], fact.sons[2].pred, aSet)
elif sameTree(fact.sons[2], loc):
if sameTree(fact[1], loc):
result = leImpliesIn(fact[1], fact[2].pred, aSet)
elif sameTree(fact[2], loc):
# 4 < x --> 3 <= x
result = geImpliesIn(fact.sons[2], fact.sons[1].pred, aSet)
result = geImpliesIn(fact[2], fact[1].pred, aSet)
of mNot, mOr, mAnd: assert(false, "impliesIn")
else: discard
@@ -567,90 +581,93 @@ proc valueIsNil(n: PNode): TImplication =
else: impUnknown
proc impliesIsNil(fact, eq: PNode): TImplication =
case fact.sons[0].sym.magic
case fact[0].sym.magic
of mIsNil:
if sameTree(fact.sons[1], eq.sons[1]):
if sameTree(fact[1], eq[1]):
result = impYes
of someEq:
if sameTree(fact.sons[1], eq.sons[1]):
result = valueIsNil(fact.sons[2].skipConv)
elif sameTree(fact.sons[2], eq.sons[1]):
result = valueIsNil(fact.sons[1].skipConv)
if sameTree(fact[1], eq[1]):
result = valueIsNil(fact[2].skipConv)
elif sameTree(fact[2], eq[1]):
result = valueIsNil(fact[1].skipConv)
of mNot, mOr, mAnd: assert(false, "impliesIsNil")
else: discard
proc impliesGe(fact, x, c: PNode): TImplication =
assert isLocation(x)
case fact.sons[0].sym.magic
case fact[0].sym.magic
of someEq:
if sameTree(fact.sons[1], x):
if isValue(fact.sons[2]) and isValue(c):
if sameTree(fact[1], x):
if isValue(fact[2]) and isValue(c):
# fact: x = 4; question x >= 56? --> true iff 4 >= 56
if leValue(c, fact.sons[2]): result = impYes
if leValue(c, fact[2]): result = impYes
else: result = impNo
elif sameTree(fact.sons[2], x):
if isValue(fact.sons[1]) and isValue(c):
if leValue(c, fact.sons[1]): result = impYes
elif sameTree(fact[2], x):
if isValue(fact[1]) and isValue(c):
if leValue(c, fact[1]): result = impYes
else: result = impNo
of someLt:
if sameTree(fact.sons[1], x):
if isValue(fact.sons[2]) and isValue(c):
if sameTree(fact[1], x):
if isValue(fact[2]) and isValue(c):
# fact: x < 4; question N <= x? --> false iff N <= 4
if leValue(fact.sons[2], c): result = impNo
if leValue(fact[2], c): result = impNo
# fact: x < 4; question 2 <= x? --> we don't know
elif sameTree(fact.sons[2], x):
elif sameTree(fact[2], x):
# fact: 3 < x; question: N-1 < x ? --> true iff N-1 <= 3
if isValue(fact.sons[1]) and isValue(c):
if leValue(c.pred, fact.sons[1]): result = impYes
if isValue(fact[1]) and isValue(c):
if leValue(c.pred, fact[1]): result = impYes
of someLe:
if sameTree(fact.sons[1], x):
if isValue(fact.sons[2]) and isValue(c):
if sameTree(fact[1], x):
if isValue(fact[2]) and isValue(c):
# fact: x <= 4; question x >= 56? --> false iff 4 <= 56
if leValue(fact.sons[2], c): result = impNo
if leValue(fact[2], c): result = impNo
# fact: x <= 4; question x >= 2? --> we don't know
elif sameTree(fact.sons[2], x):
elif sameTree(fact[2], x):
# fact: 3 <= x; question: x >= 2 ? --> true iff 2 <= 3
if isValue(fact.sons[1]) and isValue(c):
if leValue(c, fact.sons[1]): result = impYes
if isValue(fact[1]) and isValue(c):
if leValue(c, fact[1]): result = impYes
of mNot, mOr, mAnd: assert(false, "impliesGe")
else: discard
proc impliesLe(fact, x, c: PNode): TImplication =
if not isLocation(x):
if c.isValue:
if leValue(x, x): return impYes
else: return impNo
return impliesGe(fact, c, x)
case fact.sons[0].sym.magic
case fact[0].sym.magic
of someEq:
if sameTree(fact.sons[1], x):
if isValue(fact.sons[2]) and isValue(c):
if sameTree(fact[1], x):
if isValue(fact[2]) and isValue(c):
# fact: x = 4; question x <= 56? --> true iff 4 <= 56
if leValue(fact.sons[2], c): result = impYes
if leValue(fact[2], c): result = impYes
else: result = impNo
elif sameTree(fact.sons[2], x):
if isValue(fact.sons[1]) and isValue(c):
if leValue(fact.sons[1], c): result = impYes
elif sameTree(fact[2], x):
if isValue(fact[1]) and isValue(c):
if leValue(fact[1], c): result = impYes
else: result = impNo
of someLt:
if sameTree(fact.sons[1], x):
if isValue(fact.sons[2]) and isValue(c):
if sameTree(fact[1], x):
if isValue(fact[2]) and isValue(c):
# fact: x < 4; question x <= N? --> true iff N-1 <= 4
if leValue(fact.sons[2], c.pred): result = impYes
if leValue(fact[2], c.pred): result = impYes
# fact: x < 4; question x <= 2? --> we don't know
elif sameTree(fact.sons[2], x):
elif sameTree(fact[2], x):
# fact: 3 < x; question: x <= 1 ? --> false iff 1 <= 3
if isValue(fact.sons[1]) and isValue(c):
if leValue(c, fact.sons[1]): result = impNo
if isValue(fact[1]) and isValue(c):
if leValue(c, fact[1]): result = impNo
of someLe:
if sameTree(fact.sons[1], x):
if isValue(fact.sons[2]) and isValue(c):
if sameTree(fact[1], x):
if isValue(fact[2]) and isValue(c):
# fact: x <= 4; question x <= 56? --> true iff 4 <= 56
if leValue(fact.sons[2], c): result = impYes
if leValue(fact[2], c): result = impYes
# fact: x <= 4; question x <= 2? --> we don't know
elif sameTree(fact.sons[2], x):
elif sameTree(fact[2], x):
# fact: 3 <= x; question: x <= 2 ? --> false iff 2 < 3
if isValue(fact.sons[1]) and isValue(c):
if leValue(c, fact.sons[1].pred): result = impNo
if isValue(fact[1]) and isValue(c):
if leValue(c, fact[1].pred): result = impNo
of mNot, mOr, mAnd: assert(false, "impliesLe")
else: discard
@@ -686,32 +703,32 @@ proc factImplies(fact, prop: PNode): TImplication =
# (not a) -> b compute as not (a -> b) ???
# == not a or not b == not (a and b)
let arg = fact.sons[1]
let arg = fact[1]
case arg.getMagic
of mIsNil, mEqRef:
return ~factImplies(arg, prop)
of mAnd:
# not (a and b) means not a or not b:
# a or b --> both need to imply 'prop'
let a = factImplies(arg.sons[1], prop)
let b = factImplies(arg.sons[2], prop)
let a = factImplies(arg[1], prop)
let b = factImplies(arg[2], prop)
if a == b: return ~a
return impUnknown
else:
return impUnknown
of mAnd:
result = factImplies(fact.sons[1], prop)
result = factImplies(fact[1], prop)
if result != impUnknown: return result
return factImplies(fact.sons[2], prop)
return factImplies(fact[2], prop)
else: discard
case prop.sons[0].sym.magic
of mNot: result = ~fact.factImplies(prop.sons[1])
case prop[0].sym.magic
of mNot: result = ~fact.factImplies(prop[1])
of mIsNil: result = impliesIsNil(fact, prop)
of someEq: result = impliesEq(fact, prop)
of someLe: result = impliesLe(fact, prop.sons[1], prop.sons[2])
of someLt: result = impliesLt(fact, prop.sons[1], prop.sons[2])
of mInSet: result = impliesIn(fact, prop.sons[2], prop.sons[1])
of someLe: result = impliesLe(fact, prop[1], prop[2])
of someLt: result = impliesLt(fact, prop[1], prop[2])
of mInSet: result = impliesIn(fact, prop[2], prop[1])
else: result = impUnknown
proc doesImply*(facts: TModel, prop: PNode): TImplication =
@@ -802,7 +819,7 @@ proc ple(m: TModel; a, b: PNode): TImplication =
if lastOrd(nil, a.typ) <= b.intVal: return impYes
# 3 <= x iff low(x) <= 3
if a.isValue and b.typ != nil and b.typ.isOrdinalType:
if firstOrd(nil, b.typ) <= a.intVal: return impYes
if a.intVal <= firstOrd(nil, b.typ): return impYes
# x <= x
if sameTree(a, b): return impYes
@@ -813,7 +830,11 @@ proc ple(m: TModel; a, b: PNode): TImplication =
# x <= y+c if 0 <= c and x <= y
# x <= y+(-c) if c <= 0 and y >= x
if b.getMagic in someAdd and zero() <=? b[2] and a <=? b[1]: return impYes
if b.getMagic in someAdd:
if zero() <=? b[2] and a <=? b[1]: return impYes
# x <= y-c if x+c <= y
if b[2] <=? zero() and (canon(m.o.opSub.buildCall(a, b[2]), m.o) <=? b[1]):
return impYes
# x+c <= y if c <= 0 and x <= y
if a.getMagic in someAdd and a[2] <=? zero() and a[1] <=? b: return impYes
@@ -881,8 +902,8 @@ proc replaceSubTree(n, x, by: PNode): PNode =
result = by
elif hasSubTree(n, x):
result = shallowCopy(n)
for i in 0 .. safeLen(n)-1:
result.sons[i] = replaceSubTree(n.sons[i], x, by)
for i in 0..n.safeLen-1:
result[i] = replaceSubTree(n[i], x, by)
else:
result = n
@@ -902,10 +923,13 @@ proc pleViaModelRec(m: var TModel; a, b: PNode): TImplication =
# --> true if (len-100) <= (len-1)
let x = fact[1]
let y = fact[2]
if sameTree(x, a) and y.getMagic in someAdd and b.getMagic in someAdd and
sameTree(y[1], b[1]):
if ple(m, b[2], y[2]) == impYes:
return impYes
# x <= y.
# Question: x <= b? True iff y <= b.
if sameTree(x, a):
if ple(m, y, b) == impYes: return impYes
if y.getMagic in someAdd and b.getMagic in someAdd and sameTree(y[1], b[1]):
if ple(m, b[2], y[2]) == impYes:
return impYes
# x <= y implies a <= b if a <= x and y <= b
if ple(m, a, x) == impYes:
@@ -964,6 +988,10 @@ proc proveLe*(m: TModel; a, b: PNode): TImplication =
proc addFactLe*(m: var TModel; a, b: PNode) =
m.s.add canon(m.o.opLe.buildCall(a, b), m.o)
proc addFactLt*(m: var TModel; a, b: PNode) =
let bb = m.o.opAdd.buildCall(b, minusOne())
addFactLe(m, a, bb)
proc settype(n: PNode): PType =
result = newType(tySet, n.typ.owner)
addSonSkipIntLit(result, n.typ)
@@ -971,37 +999,37 @@ proc settype(n: PNode): PType =
proc buildOf(it, loc: PNode; o: Operators): PNode =
var s = newNodeI(nkCurly, it.info, it.len-1)
s.typ = settype(loc)
for i in 0..it.len-2: s.sons[i] = it.sons[i]
for i in 0..<it.len-1: s[i] = it[i]
result = newNodeI(nkCall, it.info, 3)
result.sons[0] = newSymNode(o.opContains)
result.sons[1] = s
result.sons[2] = loc
result[0] = newSymNode(o.opContains)
result[1] = s
result[2] = loc
proc buildElse(n: PNode; o: Operators): PNode =
var s = newNodeIT(nkCurly, n.info, settype(n.sons[0]))
for i in 1..n.len-2:
let branch = n.sons[i]
var s = newNodeIT(nkCurly, n.info, settype(n[0]))
for i in 1..<n.len-1:
let branch = n[i]
assert branch.kind != nkElse
if branch.kind == nkOfBranch:
for j in 0..branch.len-2:
s.add(branch.sons[j])
for j in 0..<branch.len-1:
s.add(branch[j])
result = newNodeI(nkCall, n.info, 3)
result.sons[0] = newSymNode(o.opContains)
result.sons[1] = s
result.sons[2] = n.sons[0]
result[0] = newSymNode(o.opContains)
result[1] = s
result[2] = n[0]
proc addDiscriminantFact*(m: var TModel, n: PNode) =
var fact = newNodeI(nkCall, n.info, 3)
fact.sons[0] = newSymNode(m.o.opEq)
fact.sons[1] = n.sons[0]
fact.sons[2] = n.sons[1]
fact[0] = newSymNode(m.o.opEq)
fact[1] = n[0]
fact[2] = n[1]
m.s.add fact
proc addAsgnFact*(m: var TModel, key, value: PNode) =
var fact = newNodeI(nkCall, key.info, 3)
fact.sons[0] = newSymNode(m.o.opEq)
fact.sons[1] = key
fact.sons[2] = value
fact[0] = newSymNode(m.o.opEq)
fact[1] = key
fact[2] = value
m.s.add fact
proc sameSubexprs*(m: TModel; a, b: PNode): bool =
@@ -1015,34 +1043,34 @@ proc sameSubexprs*(m: TModel; a, b: PNode): bool =
# However, nil checking requires exactly the same mechanism! But for now
# we simply use sameTree and live with the unsoundness of the analysis.
var check = newNodeI(nkCall, a.info, 3)
check.sons[0] = newSymNode(m.o.opEq)
check.sons[1] = a
check.sons[2] = b
check[0] = newSymNode(m.o.opEq)
check[1] = a
check[2] = b
result = m.doesImply(check) == impYes
proc addCaseBranchFacts*(m: var TModel, n: PNode, i: int) =
let branch = n.sons[i]
let branch = n[i]
if branch.kind == nkOfBranch:
m.s.add buildOf(branch, n.sons[0], m.o)
m.s.add buildOf(branch, n[0], m.o)
else:
m.s.add n.buildElse(m.o).neg(m.o)
proc buildProperFieldCheck(access, check: PNode; o: Operators): PNode =
if check.sons[1].kind == nkCurly:
if check[1].kind == nkCurly:
result = copyTree(check)
if access.kind == nkDotExpr:
var a = copyTree(access)
a.sons[1] = check.sons[2]
result.sons[2] = a
a[1] = check[2]
result[2] = a
# 'access.kind != nkDotExpr' can happen for object constructors
# which we don't check yet
else:
# it is some 'not'
assert check.getMagic == mNot
result = buildProperFieldCheck(access, check.sons[1], o).neg(o)
result = buildProperFieldCheck(access, check[1], o).neg(o)
proc checkFieldAccess*(m: TModel, n: PNode; conf: ConfigRef) =
for i in 1..n.len-1:
let check = buildProperFieldCheck(n.sons[0], n.sons[i], m.o)
for i in 1..<n.len:
let check = buildProperFieldCheck(n[0], n[i], m.o)
if check != nil and m.doesImply(check) != impYes:
message(conf, n.info, warnProveField, renderTree(n.sons[0])); break
message(conf, n.info, warnProveField, renderTree(n[0])); break

View File

@@ -12,14 +12,14 @@
proc hlo(c: PContext, n: PNode): PNode
proc evalPattern(c: PContext, n, orig: PNode): PNode =
internalAssert c.config, n.kind == nkCall and n.sons[0].kind == nkSym
internalAssert c.config, n.kind == nkCall and n[0].kind == nkSym
# we need to ensure that the resulting AST is semchecked. However, it's
# awful to semcheck before macro invocation, so we don't and treat
# templates and macros as immediate in this context.
var rule: string
if optHints in c.config.options and hintPattern in c.config.notes:
if c.config.hasHint(hintPattern):
rule = renderTree(n, {renderNoComments})
let s = n.sons[0].sym
let s = n[0].sym
case s.kind
of skMacro:
result = semMacroExpr(c, n, orig, s)
@@ -27,7 +27,7 @@ proc evalPattern(c: PContext, n, orig: PNode): PNode =
result = semTemplateExpr(c, n, s, {efFromHlo})
else:
result = semDirectOp(c, n, {})
if optHints in c.config.options and hintPattern in c.config.notes:
if c.config.hasHint(hintPattern):
message(c.config, orig.info, hintPattern, rule & " --> '" &
renderTree(result, {renderNoComments}) & "'")
@@ -50,7 +50,7 @@ proc applyPatterns(c: PContext, n: PNode): PNode =
c.patterns[i] = nil
if x.kind == nkStmtList:
assert x.len == 3
x.sons[1] = evalPattern(c, x.sons[1], result)
x[1] = evalPattern(c, x[1], result)
result = flattenStmts(x)
else:
result = evalPattern(c, x, result)
@@ -68,17 +68,17 @@ proc hlo(c: PContext, n: PNode): PNode =
result = n
else:
if n.kind in {nkFastAsgn, nkAsgn, nkIdentDefs, nkVarTuple} and
n.sons[0].kind == nkSym and
{sfGlobal, sfPure} * n.sons[0].sym.flags == {sfGlobal, sfPure}:
n[0].kind == nkSym and
{sfGlobal, sfPure} * n[0].sym.flags == {sfGlobal, sfPure}:
# do not optimize 'var g {.global} = re(...)' again!
return n
result = applyPatterns(c, n)
if result == n:
# no optimization applied, try subtrees:
for i in 0 ..< safeLen(result):
let a = result.sons[i]
for i in 0..<result.safeLen:
let a = result[i]
let h = hlo(c, a)
if h != a: result.sons[i] = h
if h != a: result[i] = h
else:
# perform type checking, so that the replacement still fits:
if isEmptyType(n.typ) and isEmptyType(result.typ):

View File

@@ -87,7 +87,7 @@ proc getIdent*(ic: IdentCache; identifier: cstring, length: int, h: Hash): PIden
new(result)
result.h = h
result.s = newString(length)
for i in 0 ..< length: result.s[i] = identifier[i]
for i in 0..<length: result.s[i] = identifier[i]
result.next = ic.buckets[idx]
ic.buckets[idx] = result
if id == 0:
@@ -97,11 +97,11 @@ proc getIdent*(ic: IdentCache; identifier: cstring, length: int, h: Hash): PIden
result.id = id
proc getIdent*(ic: IdentCache; identifier: string): PIdent =
result = getIdent(ic, cstring(identifier), len(identifier),
result = getIdent(ic, cstring(identifier), identifier.len,
hashIgnoreStyle(identifier))
proc getIdent*(ic: IdentCache; identifier: string, h: Hash): PIdent =
result = getIdent(ic, cstring(identifier), len(identifier), h)
result = getIdent(ic, cstring(identifier), identifier.len, h)
proc newIdentCache*(): IdentCache =
result = IdentCache()
@@ -110,8 +110,8 @@ proc newIdentCache*(): IdentCache =
result.idDelegator = result.getIdent":delegator"
result.emptyIdent = result.getIdent("")
# initialize the keywords:
for s in succ(low(specialWords)) .. high(specialWords):
result.getIdent(specialWords[s], hashIgnoreStyle(specialWords[s])).id = ord(s)
for s in succ(low(TSpecialWord))..high(TSpecialWord):
result.getIdent($s, hashIgnoreStyle($s)).id = ord(s)
proc whichKeyword*(id: PIdent): TSpecialWord =
if id.id < 0: result = wInvalid

View File

@@ -16,7 +16,7 @@ import
proc readExceptSet*(c: PContext, n: PNode): IntSet =
assert n.kind in {nkImportExceptStmt, nkExportExceptStmt}
result = initIntSet()
for i in 1 ..< n.len:
for i in 1..<n.len:
let ident = lookups.considerQuotedIdent(c, n[i])
result.incl(ident.id)
@@ -47,8 +47,8 @@ proc rawImportSymbol(c: PContext, s, origin: PSym) =
if s.kind == skType:
var etyp = s.typ
if etyp.kind in {tyBool, tyEnum}:
for j in 0 ..< len(etyp.n):
var e = etyp.n.sons[j].sym
for j in 0..<etyp.n.len:
var e = etyp.n[j].sym
if e.kind != skEnumField:
internalError(c.config, s.info, "rawImportSymbol")
# BUGFIX: because of aliases for enums the symbol may already
@@ -125,18 +125,18 @@ proc importForwarded(c: PContext, n: PNode, exceptSet: IntSet; fromMod: PSym) =
of nkExportExceptStmt:
localError(c.config, n.info, "'export except' not implemented")
else:
for i in 0..safeLen(n)-1:
importForwarded(c, n.sons[i], exceptSet, fromMod)
for i in 0..n.safeLen-1:
importForwarded(c, n[i], exceptSet, fromMod)
proc importModuleAs(c: PContext; n: PNode, realModule: PSym): PSym =
result = realModule
c.unusedImports.add((realModule, n.info))
if n.kind != nkImportAs: discard
elif n.len != 2 or n.sons[1].kind != nkIdent:
elif n.len != 2 or n[1].kind != nkIdent:
localError(c.config, n.info, "module alias must be an identifier")
elif n.sons[1].ident.id != realModule.name.id:
elif n[1].ident.id != realModule.name.id:
# some misguided guy will write 'import abc.foo as foo' ...
result = createModuleAlias(realModule, n.sons[1].ident, realModule.info,
result = createModuleAlias(realModule, n[1].ident, realModule.info,
c.config.options)
proc myImportModule(c: PContext, n: PNode; importStmtResult: PNode): PSym =
@@ -148,7 +148,7 @@ proc myImportModule(c: PContext, n: PNode; importStmtResult: PNode): PSym =
#echo "adding ", toFullPath(f), " at ", L+1
if recursion >= 0:
var err = ""
for i in recursion ..< L:
for i in recursion..<L:
if i > recursion: err.add "\n"
err.add toFullPath(c.config, c.graph.importStack[i]) & " imports " &
toFullPath(c.config, c.graph.importStack[i+1])
@@ -178,8 +178,8 @@ proc myImportModule(c: PContext, n: PNode; importStmtResult: PNode): PSym =
proc transformImportAs(c: PContext; n: PNode): PNode =
if n.kind == nkInfix and considerQuotedIdent(c, n[0]).s == "as":
result = newNodeI(nkImportAs, n.info)
result.add n.sons[1]
result.add n.sons[2]
result.add n[1]
result.add n[2]
else:
result = n
@@ -187,16 +187,15 @@ proc impMod(c: PContext; it: PNode; importStmtResult: PNode) =
let it = transformImportAs(c, it)
let m = myImportModule(c, it, importStmtResult)
if m != nil:
var emptySet: IntSet
# ``addDecl`` needs to be done before ``importAllSymbols``!
addDecl(c, m, it.info) # add symbol to symbol table of module
importAllSymbolsExcept(c, m, emptySet)
importAllSymbols(c, m)
#importForwarded(c, m.ast, emptySet, m)
proc evalImport*(c: PContext, n: PNode): PNode =
result = newNodeI(nkImportStmt, n.info)
for i in 0 ..< len(n):
let it = n.sons[i]
for i in 0..<n.len:
let it = n[i]
if it.kind == nkInfix and it.len == 3 and it[2].kind == nkBracket:
let sep = it[0]
let dir = it[1]
@@ -206,13 +205,13 @@ proc evalImport*(c: PContext, n: PNode): PNode =
imp.add sep # dummy entry, replaced in the loop
for x in it[2]:
# transform `a/b/[c as d]` to `/a/b/c as d`
if x.kind == nkInfix and x.sons[0].ident.s == "as":
if x.kind == nkInfix and x[0].ident.s == "as":
let impAs = copyTree(x)
imp.sons[2] = x.sons[1]
impAs.sons[1] = imp
imp[2] = x[1]
impAs[1] = imp
impMod(c, imp, result)
else:
imp.sons[2] = x
imp[2] = x
impMod(c, imp, result)
else:
impMod(c, it, result)
@@ -220,22 +219,22 @@ proc evalImport*(c: PContext, n: PNode): PNode =
proc evalFrom*(c: PContext, n: PNode): PNode =
result = newNodeI(nkImportStmt, n.info)
checkMinSonsLen(n, 2, c.config)
n.sons[0] = transformImportAs(c, n.sons[0])
var m = myImportModule(c, n.sons[0], result)
n[0] = transformImportAs(c, n[0])
var m = myImportModule(c, n[0], result)
if m != nil:
n.sons[0] = newSymNode(m)
n[0] = newSymNode(m)
addDecl(c, m, n.info) # add symbol to symbol table of module
for i in 1 ..< len(n):
if n.sons[i].kind != nkNilLit:
importSymbol(c, n.sons[i], m)
for i in 1..<n.len:
if n[i].kind != nkNilLit:
importSymbol(c, n[i], m)
proc evalImportExcept*(c: PContext, n: PNode): PNode =
result = newNodeI(nkImportStmt, n.info)
checkMinSonsLen(n, 2, c.config)
n.sons[0] = transformImportAs(c, n.sons[0])
var m = myImportModule(c, n.sons[0], result)
n[0] = transformImportAs(c, n[0])
var m = myImportModule(c, n[0], result)
if m != nil:
n.sons[0] = newSymNode(m)
n[0] = newSymNode(m)
addDecl(c, m, n.info) # add symbol to symbol table of module
importAllSymbolsExcept(c, m, readExceptSet(c, n))
#importForwarded(c, m.ast, exceptSet, m)

18
compiler/index.nim Normal file
View File

@@ -0,0 +1,18 @@
##[
This module only exists to generate docs for the compiler.
## links
* [main docs](../lib.html)
* [compiler user guide](../nimc.html)
* [Internals of the Nim Compiler](../intern.html)
]##
#[
note: this is named `index` so that navigating to https://nim-lang.github.io/Nim/compiler/
will work.
xxx this should also import other modules, not transitively imported by `compiler/nim.nim`,
eg `evalffi`, otherwise these aren't shown. A glob could be used at CT.
]#
import nim

File diff suppressed because it is too large Load Diff

View File

@@ -6,12 +6,12 @@ Name: "Nim"
Version: "$version"
Platforms: """
windows: i386;amd64
linux: i386;ia64;alpha;amd64;powerpc64;arm;sparc;sparc64;m68k;mips;mipsel;mips64;mips64el;powerpc;powerpc64el;arm64;riscv64
macosx: i386;amd64;powerpc64
linux: i386;hppa;ia64;alpha;amd64;powerpc64;arm;sparc;sparc64;m68k;mips;mipsel;mips64;mips64el;powerpc;powerpc64el;arm64;riscv32;riscv64
macosx: i386;amd64;powerpc64;arm64
solaris: i386;amd64;sparc;sparc64
freebsd: i386;amd64;powerpc64
freebsd: i386;amd64;powerpc64;arm;arm64;riscv64;sparc64;mips;mipsel;mips64;mips64el;powerpc;powerpc64el
netbsd: i386;amd64
openbsd: i386;amd64
openbsd: i386;amd64;arm;arm64
dragonfly: i386;amd64
haiku: i386;amd64
android: i386;arm;arm64
@@ -35,9 +35,8 @@ App: Console
License: "copying.txt"
[Config]
Files: "config/nim.cfg"
Files: "config/nimdoc.cfg"
Files: "config/nimdoc.tex.cfg"
Files: "config/*.cfg"
Files: "config/config.nims"
[Documentation]
; Files: "doc/*.html"
@@ -77,6 +76,7 @@ Files: "lib"
[Other]
Files: "examples"
Files: "dist/nimble"
Files: "dist/fusion"
Files: "tests"
@@ -89,6 +89,7 @@ Files: "bin/vccexe.exe"
Files: "bin/nimgrab.exe"
Files: "bin/nimpretty.exe"
Files: "bin/testament.exe"
Files: "bin/nim-gdb.bat"
Files: "koch.exe"
Files: "finish.exe"
@@ -109,6 +110,7 @@ Download: r"Aporia Text Editor|dist|aporia.zip|97997|https://nim-lang.org/downlo
Files: "bin/makelink.exe"
Files: "bin/7zG.exe"
Files: "bin/*.dll"
Files: "bin/cacert.pem"
[UnixBin]
Files: "bin/nim"
@@ -117,6 +119,8 @@ Files: "bin/nim"
[Unix]
InstallScript: "yes"
UninstallScript: "yes"
Files: "bin/nim-gdb"
Files: "bin/nim-gdb.bash"
[InnoSetup]
@@ -139,4 +143,4 @@ licenses: "bin/nim,MIT;lib/*,MIT;"
[nimble]
pkgName: "compiler"
pkgFiles: "compiler/*;doc/basicopt.txt;doc/advopt.txt"
pkgFiles: "compiler/*;doc/basicopt.txt;doc/advopt.txt;doc/nimdoc.css"

View File

@@ -29,27 +29,27 @@ template high*(t: typedesc[Int128]): Int128 = Max
proc `$`*(a: Int128): string
proc toInt128*[T: SomeInteger](arg: T): Int128 =
when T is SomeUnsignedInt:
proc toInt128*[T: SomeInteger | bool](arg: T): Int128 =
when T is bool: result.sdata(0) = int32(arg)
elif T is SomeUnsignedInt:
when sizeof(arg) <= 4:
result.udata[0] = uint32(arg)
else:
result.udata[0] = uint32(arg and T(0xffffffff))
result.udata[1] = uint32(arg shr 32)
elif sizeof(arg) <= 4:
result.sdata(0) = int32(arg)
if arg < 0: # sign extend
result.sdata(1) = -1
result.sdata(2) = -1
result.sdata(3) = -1
else:
when sizeof(arg) <= 4:
result.sdata(0) = int32(arg)
if arg < 0: # sign extend
result.sdata(1) = -1
result.sdata(2) = -1
result.sdata(3) = -1
else:
let tmp = int64(arg)
result.udata[0] = uint32(tmp and 0xffffffff)
result.sdata(1) = int32(tmp shr 32)
if arg < 0: # sign extend
result.sdata(2) = -1
result.sdata(3) = -1
let tmp = int64(arg)
result.udata[0] = uint32(tmp and 0xffffffff)
result.sdata(1) = int32(tmp shr 32)
if arg < 0: # sign extend
result.sdata(2) = -1
result.sdata(3) = -1
template isNegative(arg: Int128): bool =
arg.sdata(3) < 0
@@ -162,7 +162,7 @@ proc castToUInt64*(arg: Int128): uint64 =
cast[uint64](bitconcat(arg.udata[1], arg.udata[0]))
proc addToHex(result: var string; arg: uint32) =
for i in 0 ..< 8:
for i in 0..<8:
let idx = (arg shr ((7-i) * 4)) and 0xf
result.add "0123456789abcdef"[idx]
@@ -250,14 +250,14 @@ proc `shr`*(a: Int128, b: int): Int128 =
if isNegative(a):
result.sdata(3) = -1
result.sdata(2) = a.sdata(3) shr (b and 31)
result.udata[1] = cast[uint32](bitconcat(a.udata[2], a.udata[1]) shr (b and 31))
result.udata[0] = cast[uint32](bitconcat(a.udata[1], a.udata[0]) shr (b and 31))
result.udata[1] = cast[uint32](bitconcat(a.udata[3], a.udata[2]) shr (b and 31))
result.udata[0] = cast[uint32](bitconcat(a.udata[2], a.udata[1]) shr (b and 31))
elif b < 96:
if isNegative(a):
result.sdata(3) = -1
result.sdata(2) = -1
result.sdata(1) = a.sdata(3) shr (b and 31)
result.udata[0] = cast[uint32](bitconcat(a.udata[1], a.udata[0]) shr (b and 31))
result.udata[0] = cast[uint32](bitconcat(a.udata[3], a.udata[2]) shr (b and 31))
else: # b < 128
if isNegative(a):
result.sdata(3) = -1
@@ -373,8 +373,8 @@ proc `*`*(lhs,rhs: Int128): Int128 =
let b00 = cast[uint64](rhs.udata[0])
result = makeInt128(high64(lhs) * low64(rhs) + low64(lhs) * high64(rhs) + a32 * b32, a00 * b00)
result = result + toInt128(a32 * b00) shl 32
result = result + toInt128(a00 * b32) shl 32
result += toInt128(a32 * b00) shl 32
result += toInt128(a00 * b32) shl 32
proc `*=`*(a: var Int128, b: Int128) =
a = a * b
@@ -424,10 +424,10 @@ proc divMod*(dividend, divisor: Int128): tuple[quotient, remainder: Int128] =
# Uses shift-subtract algorithm to divide dividend by denominator. The
# remainder will be left in dividend.
for i in 0 .. shift:
for i in 0..shift:
quotient = quotient shl 1
if dividend >= denominator:
dividend = dividend - denominator
dividend -= denominator
quotient = bitor(quotient, One)
denominator = denominator shr 1
@@ -486,7 +486,7 @@ proc parseDecimalInt128*(arg: string, pos: int = 0): Int128 =
pos += 1
result = Zero
while pos < arg.len and arg[pos] in '0' .. '9':
while pos < arg.len and arg[pos] in '0'..'9':
result = result * Ten
result.inc(uint32(arg[pos]) - uint32('0'))
pos += 1
@@ -592,107 +592,3 @@ proc maskBytes*(arg: Int128, numbytes: int): Int128 {.noinit.} =
return maskUInt64(arg)
else:
assert(false, "masking only implemented for 1, 2, 4 and 8 bytes")
when isMainModule:
let (a,b) = divMod(Ten,Ten)
doAssert $One == "1"
doAssert $Ten == "10"
doAssert $Zero == "0"
let c = parseDecimalInt128("12345678989876543210123456789")
doAssert $c == "12345678989876543210123456789"
var d : array[39, Int128]
d[0] = parseDecimalInt128("1")
d[1] = parseDecimalInt128("10")
d[2] = parseDecimalInt128("100")
d[3] = parseDecimalInt128("1000")
d[4] = parseDecimalInt128("10000")
d[5] = parseDecimalInt128("100000")
d[6] = parseDecimalInt128("1000000")
d[7] = parseDecimalInt128("10000000")
d[8] = parseDecimalInt128("100000000")
d[9] = parseDecimalInt128("1000000000")
d[10] = parseDecimalInt128("10000000000")
d[11] = parseDecimalInt128("100000000000")
d[12] = parseDecimalInt128("1000000000000")
d[13] = parseDecimalInt128("10000000000000")
d[14] = parseDecimalInt128("100000000000000")
d[15] = parseDecimalInt128("1000000000000000")
d[16] = parseDecimalInt128("10000000000000000")
d[17] = parseDecimalInt128("100000000000000000")
d[18] = parseDecimalInt128("1000000000000000000")
d[19] = parseDecimalInt128("10000000000000000000")
d[20] = parseDecimalInt128("100000000000000000000")
d[21] = parseDecimalInt128("1000000000000000000000")
d[22] = parseDecimalInt128("10000000000000000000000")
d[23] = parseDecimalInt128("100000000000000000000000")
d[24] = parseDecimalInt128("1000000000000000000000000")
d[25] = parseDecimalInt128("10000000000000000000000000")
d[26] = parseDecimalInt128("100000000000000000000000000")
d[27] = parseDecimalInt128("1000000000000000000000000000")
d[28] = parseDecimalInt128("10000000000000000000000000000")
d[29] = parseDecimalInt128("100000000000000000000000000000")
d[30] = parseDecimalInt128("1000000000000000000000000000000")
d[31] = parseDecimalInt128("10000000000000000000000000000000")
d[32] = parseDecimalInt128("100000000000000000000000000000000")
d[33] = parseDecimalInt128("1000000000000000000000000000000000")
d[34] = parseDecimalInt128("10000000000000000000000000000000000")
d[35] = parseDecimalInt128("100000000000000000000000000000000000")
d[36] = parseDecimalInt128("1000000000000000000000000000000000000")
d[37] = parseDecimalInt128("10000000000000000000000000000000000000")
d[38] = parseDecimalInt128("100000000000000000000000000000000000000")
for i in 0 ..< d.len:
for j in 0 ..< d.len:
doAssert(cmp(d[i], d[j]) == cmp(i,j))
if i + j < d.len:
doAssert d[i] * d[j] == d[i+j]
if i - j >= 0:
doAssert d[i] div d[j] == d[i-j]
var sum: Int128
for it in d:
sum += it
doAssert $sum == "111111111111111111111111111111111111111"
for it in d.mitems:
it = -it
for i in 0 ..< d.len:
for j in 0 ..< d.len:
doAssert(cmp(d[i], d[j]) == -cmp(i,j))
if i + j < d.len:
doAssert d[i] * d[j] == -d[i+j]
if i - j >= 0:
doAssert d[i] div d[j] == -d[i-j]
doAssert $high(Int128) == "170141183460469231731687303715884105727"
doAssert $low(Int128) == "-170141183460469231731687303715884105728"
var ma = 100'i64
var mb = 13
doAssert toInt128(ma) * toInt128(0) == toInt128(0)
doAssert toInt128(-ma) * toInt128(0) == toInt128(0)
# sign correctness
doAssert divMod(toInt128( ma),toInt128( mb)) == (toInt128( ma div mb), toInt128( ma mod mb))
doAssert divMod(toInt128(-ma),toInt128( mb)) == (toInt128(-ma div mb), toInt128(-ma mod mb))
doAssert divMod(toInt128( ma),toInt128(-mb)) == (toInt128( ma div -mb), toInt128( ma mod -mb))
doAssert divMod(toInt128(-ma),toInt128(-mb)) == (toInt128(-ma div -mb), toInt128(-ma mod -mb))
doAssert divMod(toInt128( mb),toInt128( mb)) == (toInt128( mb div mb), toInt128( mb mod mb))
doAssert divMod(toInt128(-mb),toInt128( mb)) == (toInt128(-mb div mb), toInt128(-mb mod mb))
doAssert divMod(toInt128( mb),toInt128(-mb)) == (toInt128( mb div -mb), toInt128( mb mod -mb))
doAssert divMod(toInt128(-mb),toInt128(-mb)) == (toInt128(-mb div -mb), toInt128(-mb mod -mb))
doAssert divMod(toInt128( mb),toInt128( ma)) == (toInt128( mb div ma), toInt128( mb mod ma))
doAssert divMod(toInt128(-mb),toInt128( ma)) == (toInt128(-mb div ma), toInt128(-mb mod ma))
doAssert divMod(toInt128( mb),toInt128(-ma)) == (toInt128( mb div -ma), toInt128( mb mod -ma))
doAssert divMod(toInt128(-mb),toInt128(-ma)) == (toInt128(-mb div -ma), toInt128(-mb mod -ma))

View File

@@ -0,0 +1,126 @@
#
#
# The Nim Compiler
# (c) Copyright 2020 Andreas Rumpf
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
## Implementation of the check that `recover` needs, see
## https://github.com/nim-lang/RFCs/issues/244 for more details.
import
ast, types, renderer, idents, intsets
proc canAlias(arg, ret: PType; marker: var IntSet): bool
proc canAliasN(arg: PType; n: PNode; marker: var IntSet): bool =
case n.kind
of nkRecList:
for i in 0..<n.len:
result = canAliasN(arg, n[i], marker)
if result: return
of nkRecCase:
assert(n[0].kind == nkSym)
result = canAliasN(arg, n[0], marker)
if result: return
for i in 1..<n.len:
case n[i].kind
of nkOfBranch, nkElse:
result = canAliasN(arg, lastSon(n[i]), marker)
if result: return
else: discard
of nkSym:
result = canAlias(arg, n.sym.typ, marker)
else: discard
proc canAlias(arg, ret: PType; marker: var IntSet): bool =
if containsOrIncl(marker, ret.id):
return false
if ret.kind in {tyPtr, tyPointer}:
# unsafe so we don't care:
return false
if compareTypes(arg, ret, dcEqIgnoreDistinct):
return true
case ret.kind
of tyObject:
if isFinal(ret):
result = canAliasN(arg, ret.n, marker)
if not result and ret.len > 0 and ret[0] != nil:
result = canAlias(arg, ret[0], marker)
else:
result = true
of tyTuple:
for i in 0..<ret.len:
result = canAlias(arg, ret[i], marker)
if result: break
of tyArray, tySequence, tyDistinct, tyGenericInst,
tyAlias, tyInferred, tySink, tyLent, tyOwned, tyRef:
result = canAlias(arg, ret.lastSon, marker)
of tyProc:
result = ret.callConv == ccClosure
else:
result = false
proc isValueOnlyType(t: PType): bool =
# t doesn't contain pointers and references
proc wrap(t: PType): bool {.nimcall.} = t.kind in {tyRef, tyPtr, tyVar, tyLent}
result = not types.searchTypeFor(t, wrap)
proc canAlias*(arg, ret: PType): bool =
if isValueOnlyType(arg):
# can alias only with unsafeAddr(arg.x) and we don't care if it is not safe
result = false
else:
var marker = initIntSet()
result = canAlias(arg, ret, marker)
proc checkIsolate*(n: PNode): bool =
if types.containsTyRef(n.typ):
# XXX Maybe require that 'n.typ' is acyclic. This is not much
# worse than the already exisiting inheritance and closure restrictions.
case n.kind
of nkCharLit..nkNilLit:
result = true
of nkCallKinds:
if n[0].typ.flags * {tfGcSafe, tfNoSideEffect} == {}:
return false
for i in 1..<n.len:
if checkIsolate(n[i]):
discard "fine, it is isolated already"
else:
let argType = n[i].typ
if argType != nil and not isCompileTimeOnly(argType) and containsTyRef(argType):
if argType.canAlias(n.typ):
return false
result = true
of nkIfStmt, nkIfExpr:
for it in n:
result = checkIsolate(it.lastSon)
if not result: break
of nkCaseStmt, nkObjConstr:
for i in 1..<n.len:
result = checkIsolate(n[i].lastSon)
if not result: break
of nkBracket, nkTupleConstr, nkPar:
for it in n:
result = checkIsolate(it)
if not result: break
of nkHiddenStdConv, nkHiddenSubConv, nkCast, nkConv:
result = checkIsolate(n[1])
of nkObjUpConv, nkObjDownConv, nkDotExpr:
result = checkIsolate(n[0])
of nkStmtList, nkStmtListExpr:
if n.len > 0:
result = checkIsolate(n[^1])
else:
result = false
else:
# unanalysable expression:
result = false
else:
# no ref, no cry:
result = true

File diff suppressed because it is too large Load Diff

View File

@@ -17,22 +17,20 @@ proc genTypeInfo(p: PProc, typ: PType): Rope
proc genObjectFields(p: PProc, typ: PType, n: PNode): Rope =
var
s, u: Rope
length: int
field: PSym
b: PNode
result = nil
case n.kind
of nkRecList:
length = len(n)
if length == 1:
result = genObjectFields(p, typ, n.sons[0])
if n.len == 1:
result = genObjectFields(p, typ, n[0])
else:
s = nil
for i in 0 ..< length:
if i > 0: add(s, ", \L")
add(s, genObjectFields(p, typ, n.sons[i]))
for i in 0..<n.len:
if i > 0: s.add(", \L")
s.add(genObjectFields(p, typ, n[i]))
result = ("{kind: 2, len: $1, offset: 0, " &
"typ: null, name: null, sons: [$2]}") % [rope(length), s]
"typ: null, name: null, sons: [$2]}") % [rope(n.len), s]
of nkSym:
field = n.sym
s = genTypeInfo(p, field.typ)
@@ -41,29 +39,28 @@ proc genObjectFields(p: PProc, typ: PType, n: PNode): Rope =
[mangleName(p.module, field), s,
makeJSString(field.name.s)]
of nkRecCase:
length = len(n)
if (n.sons[0].kind != nkSym): internalError(p.config, n.info, "genObjectFields")
field = n.sons[0].sym
if (n[0].kind != nkSym): internalError(p.config, n.info, "genObjectFields")
field = n[0].sym
s = genTypeInfo(p, field.typ)
for i in 1 ..< length:
b = n.sons[i] # branch
for i in 1..<n.len:
b = n[i] # branch
u = nil
case b.kind
of nkOfBranch:
if len(b) < 2:
if b.len < 2:
internalError(p.config, b.info, "genObjectFields; nkOfBranch broken")
for j in 0 .. len(b) - 2:
if u != nil: add(u, ", ")
if b.sons[j].kind == nkRange:
addf(u, "[$1, $2]", [rope(getOrdValue(b.sons[j].sons[0])),
rope(getOrdValue(b.sons[j].sons[1]))])
for j in 0..<b.len - 1:
if u != nil: u.add(", ")
if b[j].kind == nkRange:
u.addf("[$1, $2]", [rope(getOrdValue(b[j][0])),
rope(getOrdValue(b[j][1]))])
else:
add(u, rope(getOrdValue(b.sons[j])))
u.add(rope(getOrdValue(b[j])))
of nkElse:
u = rope(lengthOrd(p.config, field.typ))
else: internalError(p.config, n.info, "genObjectFields(nkRecCase)")
if result != nil: add(result, ", \L")
addf(result, "[setConstr($1), $2]",
if result != nil: result.add(", \L")
result.addf("[setConstr($1), $2]",
[u, genObjectFields(p, typ, lastSon(b))])
result = ("{kind: 3, offset: \"$1\", len: $3, " &
"typ: $2, name: $4, sons: [$5]}") % [
@@ -72,27 +69,27 @@ proc genObjectFields(p: PProc, typ: PType, n: PNode): Rope =
else: internalError(p.config, n.info, "genObjectFields")
proc objHasTypeField(t: PType): bool {.inline.} =
tfInheritable in t.flags or t.sons[0] != nil
tfInheritable in t.flags or t[0] != nil
proc genObjectInfo(p: PProc, typ: PType, name: Rope) =
let kind = if objHasTypeField(typ): tyObject else: tyTuple
var s = ("var $1 = {size: 0, kind: $2, base: null, node: null, " &
"finalizer: null};$n") % [name, rope(ord(kind))]
prepend(p.g.typeInfo, s)
addf(p.g.typeInfo, "var NNI$1 = $2;$n",
p.g.typeInfo.addf("var NNI$1 = $2;$n",
[rope(typ.id), genObjectFields(p, typ, typ.n)])
addf(p.g.typeInfo, "$1.node = NNI$2;$n", [name, rope(typ.id)])
if (typ.kind == tyObject) and (typ.sons[0] != nil):
addf(p.g.typeInfo, "$1.base = $2;$n",
[name, genTypeInfo(p, typ.sons[0].skipTypes(skipPtrs))])
p.g.typeInfo.addf("$1.node = NNI$2;$n", [name, rope(typ.id)])
if (typ.kind == tyObject) and (typ[0] != nil):
p.g.typeInfo.addf("$1.base = $2;$n",
[name, genTypeInfo(p, typ[0].skipTypes(skipPtrs))])
proc genTupleFields(p: PProc, typ: PType): Rope =
var s: Rope = nil
for i in 0 ..< typ.len:
if i > 0: add(s, ", \L")
for i in 0..<typ.len:
if i > 0: s.add(", \L")
s.addf("{kind: 1, offset: \"Field$1\", len: 0, " &
"typ: $2, name: \"Field$1\", sons: null}",
[i.rope, genTypeInfo(p, typ.sons[i])])
[i.rope, genTypeInfo(p, typ[i])])
result = ("{kind: 2, len: $1, offset: 0, " &
"typ: null, name: null, sons: [$2]}") % [rope(typ.len), s]
@@ -100,30 +97,29 @@ proc genTupleInfo(p: PProc, typ: PType, name: Rope) =
var s = ("var $1 = {size: 0, kind: $2, base: null, node: null, " &
"finalizer: null};$n") % [name, rope(ord(typ.kind))]
prepend(p.g.typeInfo, s)
addf(p.g.typeInfo, "var NNI$1 = $2;$n",
p.g.typeInfo.addf("var NNI$1 = $2;$n",
[rope(typ.id), genTupleFields(p, typ)])
addf(p.g.typeInfo, "$1.node = NNI$2;$n", [name, rope(typ.id)])
p.g.typeInfo.addf("$1.node = NNI$2;$n", [name, rope(typ.id)])
proc genEnumInfo(p: PProc, typ: PType, name: Rope) =
let length = len(typ.n)
var s: Rope = nil
for i in 0 ..< length:
if (typ.n.sons[i].kind != nkSym): internalError(p.config, typ.n.info, "genEnumInfo")
let field = typ.n.sons[i].sym
if i > 0: add(s, ", \L")
for i in 0..<typ.n.len:
if (typ.n[i].kind != nkSym): internalError(p.config, typ.n.info, "genEnumInfo")
let field = typ.n[i].sym
if i > 0: s.add(", \L")
let extName = if field.ast == nil: field.name.s else: field.ast.strVal
addf(s, "\"$1\": {kind: 1, offset: $1, typ: $2, name: $3, len: 0, sons: null}",
s.addf("\"$1\": {kind: 1, offset: $1, typ: $2, name: $3, len: 0, sons: null}",
[rope(field.position), name, makeJSString(extName)])
var n = ("var NNI$1 = {kind: 2, offset: 0, typ: null, " &
"name: null, len: $2, sons: {$3}};$n") % [rope(typ.id), rope(length), s]
"name: null, len: $2, sons: {$3}};$n") % [rope(typ.id), rope(typ.n.len), s]
s = ("var $1 = {size: 0, kind: $2, base: null, node: null, " &
"finalizer: null};$n") % [name, rope(ord(typ.kind))]
prepend(p.g.typeInfo, s)
add(p.g.typeInfo, n)
addf(p.g.typeInfo, "$1.node = NNI$2;$n", [name, rope(typ.id)])
if typ.sons[0] != nil:
addf(p.g.typeInfo, "$1.base = $2;$n",
[name, genTypeInfo(p, typ.sons[0])])
p.g.typeInfo.add(n)
p.g.typeInfo.addf("$1.node = NNI$2;$n", [name, rope(typ.id)])
if typ[0] != nil:
p.g.typeInfo.addf("$1.base = $2;$n",
[name, genTypeInfo(p, typ[0])])
proc genTypeInfo(p: PProc, typ: PType): Rope =
let t = typ.skipTypes({tyGenericInst, tyDistinct, tyAlias, tySink, tyOwned})
@@ -131,7 +127,7 @@ proc genTypeInfo(p: PProc, typ: PType): Rope =
if containsOrIncl(p.g.typeInfoGenerated, t.id): return
case t.kind
of tyDistinct:
result = genTypeInfo(p, t.sons[0])
result = genTypeInfo(p, t[0])
of tyPointer, tyProc, tyBool, tyChar, tyCString, tyString, tyInt..tyUInt64:
var s =
"var $1 = {size: 0,kind: $2,base: null,node: null,finalizer: null};$n" %
@@ -142,15 +138,15 @@ proc genTypeInfo(p: PProc, typ: PType): Rope =
"var $1 = {size: 0,kind: $2,base: null,node: null,finalizer: null};$n" %
[result, rope(ord(t.kind))]
prepend(p.g.typeInfo, s)
addf(p.g.typeInfo, "$1.base = $2;$n",
p.g.typeInfo.addf("$1.base = $2;$n",
[result, genTypeInfo(p, t.lastSon)])
of tyArray:
var s =
"var $1 = {size: 0,kind: $2,base: null,node: null,finalizer: null};$n" %
[result, rope(ord(t.kind))]
prepend(p.g.typeInfo, s)
addf(p.g.typeInfo, "$1.base = $2;$n",
[result, genTypeInfo(p, t.sons[1])])
p.g.typeInfo.addf("$1.base = $2;$n",
[result, genTypeInfo(p, t[1])])
of tyEnum: genEnumInfo(p, t, result)
of tyObject: genObjectInfo(p, t, result)
of tyTuple: genTupleInfo(p, t, result)

View File

@@ -128,8 +128,8 @@ proc newCall(a: PSym, b: PNode): PNode =
proc createClosureIterStateType*(g: ModuleGraph; iter: PSym): PType =
var n = newNodeI(nkRange, iter.info)
addSon(n, newIntNode(nkIntLit, -1))
addSon(n, newIntNode(nkIntLit, 0))
n.add newIntNode(nkIntLit, -1)
n.add newIntNode(nkIntLit, 0)
result = newType(tyRange, iter)
result.n = n
var intType = nilOrSysInt(g)
@@ -148,27 +148,27 @@ proc createEnvObj(g: ModuleGraph; owner: PSym; info: TLineInfo): PType =
proc getClosureIterResult*(g: ModuleGraph; iter: PSym): PSym =
if resultPos < iter.ast.len:
result = iter.ast.sons[resultPos].sym
result = iter.ast[resultPos].sym
else:
# XXX a bit hacky:
result = newSym(skResult, getIdent(g.cache, ":result"), iter, iter.info, {})
result.typ = iter.typ.sons[0]
result.typ = iter.typ[0]
incl(result.flags, sfUsed)
iter.ast.add newSymNode(result)
proc addHiddenParam(routine: PSym, param: PSym) =
assert param.kind == skParam
var params = routine.ast.sons[paramsPos]
var params = routine.ast[paramsPos]
# -1 is correct here as param.position is 0 based but we have at position 0
# some nkEffect node:
param.position = routine.typ.n.len-1
addSon(params, newSymNode(param))
params.add newSymNode(param)
#incl(routine.typ.flags, tfCapturesEnv)
assert sfFromGeneric in param.flags
#echo "produced environment: ", param.id, " for ", routine.id
proc getHiddenParam(g: ModuleGraph; routine: PSym): PSym =
let params = routine.ast.sons[paramsPos]
let params = routine.ast[paramsPos]
let hidden = lastSon(params)
if hidden.kind == nkSym and hidden.sym.kind == skParam and hidden.sym.name.s == paramName:
result = hidden.sym
@@ -179,7 +179,7 @@ proc getHiddenParam(g: ModuleGraph; routine: PSym): PSym =
result = routine
proc getEnvParam*(routine: PSym): PSym =
let params = routine.ast.sons[paramsPos]
let params = routine.ast[paramsPos]
let hidden = lastSon(params)
if hidden.kind == nkSym and hidden.sym.name.s == paramName:
result = hidden.sym
@@ -206,8 +206,8 @@ proc newAsgnStmt(le, ri: PNode, info: TLineInfo): PNode =
# which is however the only case when we generate an assignment in the first
# place.
result = newNodeI(nkAsgn, info, 2)
result.sons[0] = le
result.sons[1] = ri
result[0] = le
result[1] = ri
proc makeClosure*(g: ModuleGraph; prc: PSym; env: PNode; info: TLineInfo): PNode =
result = newNodeIT(nkClosure, info, prc.typ)
@@ -218,6 +218,10 @@ proc makeClosure*(g: ModuleGraph; prc: PSym; env: PNode; info: TLineInfo): PNode
if env.skipConv.kind == nkClosure:
localError(g.config, info, "internal error: taking closure of closure")
result.add(env)
#if isClosureIterator(result.typ):
createTypeBoundOps(g, nil, result.typ, info)
if tfHasAsgn in result.typ.flags or optSeqDestructors in g.config.globalOptions:
prc.flags.incl sfInjectDestructors
proc interestingIterVar(s: PSym): bool {.inline.} =
# XXX optimization: Only lift the variable if it lives across
@@ -231,11 +235,14 @@ template isIterator*(owner: PSym): bool =
proc liftingHarmful(conf: ConfigRef; owner: PSym): bool {.inline.} =
## lambda lifting can be harmful for JS-like code generators.
let isCompileTime = sfCompileTime in owner.flags or owner.kind == skMacro
result = conf.cmd == cmdCompileToJS and not isCompileTime
result = conf.backend == backendJs and not isCompileTime
proc createTypeBoundOpsLL(g: ModuleGraph; refType: PType; info: TLineInfo) =
createTypeBoundOps(g, nil, refType.lastSon, info)
createTypeBoundOps(g, nil, refType, info)
proc createTypeBoundOpsLL(g: ModuleGraph; refType: PType; info: TLineInfo; owner: PSym) =
if owner.kind != skMacro:
createTypeBoundOps(g, nil, refType.lastSon, info)
createTypeBoundOps(g, nil, refType, info)
if tfHasAsgn in refType.flags or optSeqDestructors in g.config.globalOptions:
owner.flags.incl sfInjectDestructors
proc liftIterSym*(g: ModuleGraph; n: PNode; owner: PSym): PNode =
# transforms (iter) to (let env = newClosure[iter](); (iter, env))
@@ -249,7 +256,7 @@ proc liftIterSym*(g: ModuleGraph; n: PNode; owner: PSym): PNode =
var env: PNode
if owner.isIterator:
let it = getHiddenParam(g, owner)
addUniqueField(it.typ.skipTypes({tyOwned}).sons[0], hp, g.cache)
addUniqueField(it.typ.skipTypes({tyOwned})[0], hp, g.cache)
env = indirectAccess(newSymNode(it), hp, hp.info)
else:
let e = newSym(skLet, iter.name, owner, n.info)
@@ -261,8 +268,7 @@ proc liftIterSym*(g: ModuleGraph; n: PNode; owner: PSym): PNode =
result.add(v)
# add 'new' statement:
result.add newCall(getSysSym(g, n.info, "internalNew"), env)
if optOwnedRefs in g.config.globalOptions:
createTypeBoundOps(g, nil, env.typ, n.info)
createTypeBoundOpsLL(g, env.typ, n.info, owner)
result.add makeClosure(g, iter, env, n.info)
proc freshVarForClosureIter*(g: ModuleGraph; s, owner: PSym): PNode =
@@ -286,10 +292,11 @@ proc markAsClosure(g: ModuleGraph; owner: PSym; n: PNode) =
if illegalCapture(s):
localError(g.config, n.info,
("'$1' is of type <$2> which cannot be captured as it would violate memory" &
" safety, declared here: $3") % [s.name.s, typeToString(s.typ), g.config$s.info])
elif owner.typ.callConv notin {ccClosure, ccDefault}:
" safety, declared here: $3; using '-d:nimWorkaround14447' helps in some cases") %
[s.name.s, typeToString(s.typ), g.config$s.info])
elif not (owner.typ.callConv == ccClosure or owner.typ.callConv == ccNimCall and tfExplicitCallConv notin owner.typ.flags):
localError(g.config, n.info, "illegal capture '$1' because '$2' has the calling convention: <$3>" %
[s.name.s, owner.name.s, CallingConvToStr[owner.typ.callConv]])
[s.name.s, owner.name.s, $owner.typ.callConv])
incl(owner.typ.flags, tfCapturesEnv)
owner.typ.callConv = ccClosure
@@ -297,7 +304,7 @@ type
DetectionPass = object
processed, capturedVars: IntSet
ownerToType: Table[int, PType]
somethingToDo, noDestructors: bool
somethingToDo: bool
graph: ModuleGraph
proc initDetectionPass(g: ModuleGraph; fn: PSym): DetectionPass =
@@ -348,8 +355,8 @@ proc createUpField(c: var DetectionPass; dest, dep: PSym; info: TLineInfo) =
# with cycles properly, so it's better to produce a weak ref (=ptr) here.
# This seems to be generally correct but since it's a bit risky it's disabled
# for now.
let fieldType = if isDefined(c.graph.config, "nimCycleBreaker") or
c.graph.config.selectedGC == gcDestructors:
# XXX This is wrong for the 'hamming' test, so remove this logic again.
let fieldType = if isDefined(c.graph.config, "nimCycleBreaker"):
c.getEnvTypeForOwnerUp(dep, info) #getHiddenParam(dep).typ
else:
c.getEnvTypeForOwner(dep, info)
@@ -361,9 +368,16 @@ proc createUpField(c: var DetectionPass; dest, dep: PSym; info: TLineInfo) =
if upField != nil:
if upField.typ.skipTypes({tyOwned, tyRef, tyPtr}) != fieldType.skipTypes({tyOwned, tyRef, tyPtr}):
localError(c.graph.config, dep.info, "internal error: up references do not agree")
when false:
if c.graph.config.selectedGC == gcDestructors and sfCursor notin upField.flags:
localError(c.graph.config, dep.info, "internal error: up reference is not a .cursor")
else:
let result = newSym(skField, upIdent, obj.owner, obj.owner.info)
result.typ = fieldType
when false:
if c.graph.config.selectedGC == gcDestructors:
result.flags.incl sfCursor
rawAddField(obj, result)
discard """
@@ -420,8 +434,7 @@ proc detectCapturedVars(n: PNode; owner: PSym; c: var DetectionPass) =
if innerProc:
if s.isIterator: c.somethingToDo = true
if not c.processed.containsOrIncl(s.id):
let body = transformBody(c.graph, s, cache = true,
noDestructors = c.noDestructors)
let body = transformBody(c.graph, s, cache = true)
detectCapturedVars(body, s, c)
let ow = s.skipGenericOwner
if ow == owner:
@@ -482,7 +495,8 @@ proc detectCapturedVars(n: PNode; owner: PSym; c: var DetectionPass) =
w = up
of nkEmpty..pred(nkSym), succ(nkSym)..nkNilLit,
nkTemplateDef, nkTypeSection, nkProcDef, nkMethodDef,
nkConverterDef, nkMacroDef, nkFuncDef, nkCommentStmt, nkTypeOfExpr:
nkConverterDef, nkMacroDef, nkFuncDef, nkCommentStmt,
nkTypeOfExpr, nkMixinStmt, nkBindStmt:
discard
of nkLambdaKinds, nkIteratorDef:
if n.typ != nil:
@@ -512,7 +526,7 @@ proc accessViaEnvParam(g: ModuleGraph; n: PNode; owner: PSym): PNode =
if not envParam.isNil:
var access = newSymNode(envParam)
while true:
let obj = access.typ.sons[0]
let obj = access.typ[0]
assert obj.kind == tyObject
let field = getFieldFromObj(obj, s)
if field != nil:
@@ -531,7 +545,7 @@ proc newEnvVar(cache: IdentCache; owner: PSym; typ: PType; info: TLineInfo): PNo
when false:
if owner.kind == skIterator and owner.typ.callConv == ccClosure:
let it = getHiddenParam(owner)
addUniqueField(it.typ.sons[0], v)
addUniqueField(it.typ[0], v)
result = indirectAccess(newSymNode(it), v, v.info)
else:
result = newSymNode(v)
@@ -590,7 +604,7 @@ proc rawClosureCreation(owner: PSym;
let env2 = copyTree(env)
env2.typ = unowned.typ
result.add newAsgnStmt(unowned, env2, env.info)
createTypeBoundOpsLL(d.graph, unowned.typ, env.info)
createTypeBoundOpsLL(d.graph, unowned.typ, env.info, owner)
# add assignment statements for captured parameters:
for i in 1..<owner.typ.n.len:
@@ -599,6 +613,10 @@ proc rawClosureCreation(owner: PSym;
let fieldAccess = indirectAccess(env, local, env.info)
# add ``env.param = param``
result.add(newAsgnStmt(fieldAccess, newSymNode(local), env.info))
if owner.kind != skMacro:
createTypeBoundOps(d.graph, nil, fieldAccess.typ, env.info)
if tfHasAsgn in fieldAccess.typ.flags or optSeqDestructors in d.graph.config.globalOptions:
owner.flags.incl sfInjectDestructors
let upField = lookupInRecord(env.typ.skipTypes({tyOwned, tyRef, tyPtr}).n, getIdent(d.graph.cache, upName))
if upField != nil:
@@ -613,8 +631,7 @@ proc rawClosureCreation(owner: PSym;
localError(d.graph.config, env.info, "internal error: cannot create up reference")
# we are not in the sem'check phase anymore! so pass 'nil' for the PContext
# and hope for the best:
if optOwnedRefs in d.graph.config.globalOptions:
createTypeBoundOps(d.graph, nil, env.typ, owner.info)
createTypeBoundOpsLL(d.graph, env.typ, owner.info, owner)
proc finishClosureCreation(owner: PSym; d: DetectionPass; c: LiftingPass;
info: TLineInfo; res: PNode) =
@@ -623,6 +640,7 @@ proc finishClosureCreation(owner: PSym; d: DetectionPass; c: LiftingPass;
assert unowned != nil
let nilLit = newNodeIT(nkNilLit, info, unowned.typ)
res.add newAsgnStmt(unowned, nilLit, info)
createTypeBoundOpsLL(d.graph, unowned.typ, info, owner)
proc closureCreationForIter(iter: PNode;
d: DetectionPass; c: var LiftingPass): PNode =
@@ -642,8 +660,7 @@ proc closureCreationForIter(iter: PNode;
addVar(vs, vnode)
result.add(vs)
result.add(newCall(getSysSym(d.graph, iter.info, "internalNew"), vnode))
if optOwnedRefs in d.graph.config.globalOptions:
createTypeBoundOps(d.graph, nil, vnode.typ, iter.info)
createTypeBoundOpsLL(d.graph, vnode.typ, iter.info, owner)
let upField = lookupInRecord(v.typ.skipTypes({tyOwned, tyRef, tyPtr}).n, getIdent(d.graph.cache, upName))
if upField != nil:
@@ -669,7 +686,7 @@ proc accessViaEnvVar(n: PNode; owner: PSym; d: DetectionPass;
result = n
proc getStateField*(g: ModuleGraph; owner: PSym): PSym =
getHiddenParam(g, owner).typ.skipTypes({tyOwned, tyRef, tyPtr}).n.sons[0].sym
getHiddenParam(g, owner).typ.skipTypes({tyOwned, tyRef, tyPtr}).n[0].sym
proc liftCapturedVars(n: PNode; owner: PSym; d: DetectionPass;
c: var LiftingPass): PNode
@@ -713,7 +730,7 @@ proc liftCapturedVars(n: PNode; owner: PSym; d: DetectionPass;
# echo renderTree(s.getBody, {renderIds})
let oldInContainer = c.inContainer
c.inContainer = 0
var body = transformBody(d.graph, s)
var body = transformBody(d.graph, s, cache = false)
body = liftCapturedVars(body, s, d, c)
if c.envVars.getOrDefault(s.id).isNil:
s.transformedBody = body
@@ -734,17 +751,17 @@ proc liftCapturedVars(n: PNode; owner: PSym; d: DetectionPass;
result = accessViaEnvVar(n, owner, d, c)
of nkEmpty..pred(nkSym), succ(nkSym)..nkNilLit, nkComesFrom,
nkTemplateDef, nkTypeSection, nkProcDef, nkMethodDef, nkConverterDef,
nkMacroDef, nkFuncDef:
nkMacroDef, nkFuncDef, nkMixinStmt, nkBindStmt:
discard
of nkClosure:
if n[1].kind == nkNilLit:
n.sons[0] = liftCapturedVars(n[0], owner, d, c)
let x = n.sons[0].skipConv
n[0] = liftCapturedVars(n[0], owner, d, c)
let x = n[0].skipConv
if x.kind == nkClosure:
#localError(n.info, "internal error: closure to closure created")
# now we know better, so patch it:
n.sons[0] = x.sons[0]
n.sons[1] = x.sons[1]
n[0] = x[0]
n[1] = x[1]
of nkLambdaKinds, nkIteratorDef:
if n.typ != nil and n[namePos].kind == nkSym:
let oldInContainer = c.inContainer
@@ -755,29 +772,29 @@ proc liftCapturedVars(n: PNode; owner: PSym; d: DetectionPass;
c.inContainer = oldInContainer
of nkHiddenStdConv:
if n.len == 2:
n.sons[1] = liftCapturedVars(n[1], owner, d, c)
n[1] = liftCapturedVars(n[1], owner, d, c)
if n[1].kind == nkClosure: result = n[1]
of nkReturnStmt:
if n[0].kind in {nkAsgn, nkFastAsgn}:
# we have a `result = result` expression produced by the closure
# transform, let's not touch the LHS in order to make the lifting pass
# correct when `result` is lifted
n[0].sons[1] = liftCapturedVars(n[0].sons[1], owner, d, c)
n[0][1] = liftCapturedVars(n[0][1], owner, d, c)
else:
n.sons[0] = liftCapturedVars(n[0], owner, d, c)
n[0] = liftCapturedVars(n[0], owner, d, c)
of nkTypeOfExpr:
result = n
else:
if owner.isIterator:
if nfLL in n.flags:
# special case 'when nimVm' due to bug #3636:
n.sons[1] = liftCapturedVars(n[1], owner, d, c)
n[1] = liftCapturedVars(n[1], owner, d, c)
return
let inContainer = n.kind in {nkObjConstr, nkBracket}
if inContainer: inc c.inContainer
for i in 0..<n.len:
n.sons[i] = liftCapturedVars(n[i], owner, d, c)
n[i] = liftCapturedVars(n[i], owner, d, c)
if inContainer: dec c.inContainer
# ------------------ old stuff -------------------------------------------
@@ -808,7 +825,8 @@ proc semCaptureSym*(s, owner: PSym) =
var o = owner.skipGenericOwner
while o != nil and o.kind != skModule:
if s.owner == o:
if owner.typ.callConv in {ccClosure, ccDefault} or owner.kind == skIterator:
if owner.typ.callConv == ccClosure or owner.kind == skIterator or
owner.typ.callConv == ccNimCall and tfExplicitCallConv notin owner.typ.flags:
owner.typ.callConv = ccClosure
propagateClosure(owner.skipGenericOwner, s.owner)
else:
@@ -824,24 +842,23 @@ proc liftIterToProc*(g: ModuleGraph; fn: PSym; body: PNode; ptrType: PType): PNo
# pretend 'fn' is a closure iterator for the analysis:
let oldKind = fn.kind
let oldCC = fn.typ.callConv
fn.kind = skIterator
fn.transitionRoutineSymKind(skIterator)
fn.typ.callConv = ccClosure
d.ownerToType[fn.id] = ptrType
detectCapturedVars(body, fn, d)
result = liftCapturedVars(body, fn, d, c)
fn.kind = oldKind
fn.transitionRoutineSymKind(oldKind)
fn.typ.callConv = oldCC
proc liftLambdas*(g: ModuleGraph; fn: PSym, body: PNode; tooEarly: var bool;
noDestructors: bool): PNode =
# XXX gCmd == cmdCompileToJS does not suffice! The compiletime stuff needs
proc liftLambdas*(g: ModuleGraph; fn: PSym, body: PNode; tooEarly: var bool): PNode =
# XXX backend == backendJs does not suffice! The compiletime stuff needs
# the transformation even when compiling to JS ...
# However we can do lifting for the stuff which is *only* compiletime.
let isCompileTime = sfCompileTime in fn.flags or fn.kind == skMacro
if body.kind == nkEmpty or (
g.config.cmd == cmdCompileToJS and not isCompileTime) or
g.config.backend == backendJs and not isCompileTime) or
fn.skipGenericOwner.kind != skModule:
# ignore forward declaration:
@@ -849,7 +866,6 @@ proc liftLambdas*(g: ModuleGraph; fn: PSym, body: PNode; tooEarly: var bool;
tooEarly = true
else:
var d = initDetectionPass(g, fn)
d.noDestructors = noDestructors
detectCapturedVars(body, fn, d)
if not d.somethingToDo and fn.isIterator:
addClosureParam(d, fn, body.info)
@@ -903,11 +919,10 @@ proc liftForLoop*(g: ModuleGraph; body: PNode; owner: PSym): PNode =
...
"""
if liftingHarmful(g.config, owner): return body
var L = body.len
if not (body.kind == nkForStmt and body[L-2].kind in nkCallKinds):
if not (body.kind == nkForStmt and body[^2].kind in nkCallKinds):
localError(g.config, body.info, "ignored invalid for loop")
return body
var call = body[L-2]
var call = body[^2]
result = newNodeI(nkStmtList, body.info)
@@ -928,40 +943,39 @@ proc liftForLoop*(g: ModuleGraph; body: PNode; owner: PSym): PNode =
result.add(v)
# add 'new' statement:
result.add(newCall(getSysSym(g, env.info, "internalNew"), env.newSymNode))
if optOwnedRefs in g.config.globalOptions:
createTypeBoundOps(g, nil, env.typ, body.info)
createTypeBoundOpsLL(g, env.typ, body.info, owner)
elif op.kind == nkStmtListExpr:
let closure = op.lastSon
if closure.kind == nkClosure:
call.sons[0] = closure
for i in 0 .. op.len-2:
call[0] = closure
for i in 0..<op.len-1:
result.add op[i]
var loopBody = newNodeI(nkStmtList, body.info, 3)
var whileLoop = newNodeI(nkWhileStmt, body.info, 2)
whileLoop.sons[0] = newIntTypeNode(1, getSysType(g, body.info, tyBool))
whileLoop.sons[1] = loopBody
whileLoop[0] = newIntTypeNode(1, getSysType(g, body.info, tyBool))
whileLoop[1] = loopBody
result.add whileLoop
# setup loopBody:
# gather vars in a tuple:
var v2 = newNodeI(nkLetSection, body.info)
var vpart = newNodeI(if L == 3: nkIdentDefs else: nkVarTuple, body.info)
for i in 0 .. L-3:
var vpart = newNodeI(if body.len == 3: nkIdentDefs else: nkVarTuple, body.info)
for i in 0..<body.len-2:
if body[i].kind == nkSym:
body[i].sym.kind = skLet
addSon(vpart, body[i])
body[i].sym.transitionToLet()
vpart.add body[i]
addSon(vpart, newNodeI(nkEmpty, body.info)) # no explicit type
vpart.add newNodeI(nkEmpty, body.info) # no explicit type
if not env.isNil:
call.sons[0] = makeClosure(g, call.sons[0].sym, env.newSymNode, body.info)
addSon(vpart, call)
addSon(v2, vpart)
call[0] = makeClosure(g, call[0].sym, env.newSymNode, body.info)
vpart.add call
v2.add vpart
loopBody.sons[0] = v2
loopBody[0] = v2
var bs = newNodeI(nkBreakState, body.info)
bs.addSon(call.sons[0])
bs.add call[0]
let ibs = newNodeI(nkIfStmt, body.info)
let elifBranch = newNodeI(nkElifBranch, body.info)
@@ -973,5 +987,5 @@ proc liftForLoop*(g: ModuleGraph; body: PNode; owner: PSym): PNode =
elifBranch.add(br)
ibs.add(elifBranch)
loopBody.sons[1] = ibs
loopBody.sons[2] = body[L-1]
loopBody[1] = ibs
loopBody[2] = body[^1]

View File

@@ -21,7 +21,7 @@ type
SemicolonKind = enum
detectSemicolonKind, useSemicolon, dontTouch
LayoutToken = enum
LayoutToken* = enum
ltSpaces,
ltCrucialNewline, ## a semantically crucial newline (indentation!)
ltSplittingNewline, ## newline used for splitting up long
@@ -35,14 +35,14 @@ type
Emitter* = object
config: ConfigRef
fid: FileIndex
lastTok: TTokType
lastTok: TokType
inquote, lastTokWasTerse: bool
semicolons: SemicolonKind
col, lastLineNumber, lineSpan, indentLevel, indWidth*, inSection: int
keepIndents*: int
doIndentMore*: int
kinds: seq[LayoutToken]
tokens: seq[string]
kinds*: seq[LayoutToken]
tokens*: seq[string]
indentStack: seq[int]
fixedUntil: int # marks where we must not go in the content
altSplitPos: array[SplitKind, int] # alternative split positions
@@ -146,7 +146,7 @@ proc optionalIsGood(em: var Emitter; pos, currentLen: int): bool =
proc lenOfNextTokens(em: Emitter; pos: int): int =
result = 0
for i in 1 ..< em.tokens.len-pos:
for i in 1..<em.tokens.len-pos:
if em.kinds[pos+i] in {ltCrucialNewline, ltSplittingNewline, ltOptionalNewline}: break
inc result, em.tokens[pos+i].len
@@ -160,13 +160,11 @@ proc guidingInd(em: Emitter; pos: int): int =
inc i
result = -1
proc closeEmitter*(em: var Emitter) =
proc renderTokens*(em: var Emitter): string =
## Render Emitter tokens to a string of code
template defaultCase() =
content.add em.tokens[i]
inc lineLen, em.tokens[i].len
let outFile = em.config.absOutFile
var content = newStringOfCap(16_000)
var maxLhs = 0
var lineLen = 0
@@ -243,6 +241,11 @@ proc closeEmitter*(em: var Emitter) =
defaultCase()
inc i
return content
proc writeOut*(em: Emitter, content: string) =
## Write to disk
let outFile = em.config.absOutFile
if fileExists(outFile) and readFile(outFile.string) == content:
discard "do nothing, see #9499"
return
@@ -253,6 +256,11 @@ proc closeEmitter*(em: var Emitter) =
f.llStreamWrite content
llStreamClose(f)
proc closeEmitter*(em: var Emitter) =
## Renders emitter tokens and write to a file
let content = renderTokens(em)
em.writeOut(content)
proc wr(em: var Emitter; x: string; lt: LayoutToken) =
em.tokens.add x
em.kinds.add lt
@@ -319,7 +327,7 @@ const
splitters = openPars + {tkComma, tkSemiColon} # do not add 'tkColon' here!
oprSet = {tkOpr, tkDiv, tkMod, tkShl, tkShr, tkIn, tkNotin, tkIs,
tkIsnot, tkNot, tkOf, tkAs, tkDotDot, tkAnd, tkOr, tkXor}
tkIsnot, tkNot, tkOf, tkAs, tkFrom, tkDotDot, tkAnd, tkOr, tkXor}
template goodCol(col): bool = col >= em.maxLineLen div 2
@@ -394,7 +402,7 @@ proc endsInAlpha(em: Emitter): bool =
while i >= 0 and em.kinds[i] in {ltBeginSection, ltEndSection}: dec(i)
result = if i >= 0: em.tokens[i].lastChar in SymChars+{'_'} else: false
proc emitComment(em: var Emitter; tok: TToken; dontIndent: bool) =
proc emitComment(em: var Emitter; tok: Token; dontIndent: bool) =
var col = em.col
let lit = strip fileSection(em.config, em.fid, tok.commentOffsetA, tok.commentOffsetB)
em.lineSpan = countNewlines(lit)
@@ -409,7 +417,7 @@ proc emitComment(em: var Emitter; tok: TToken; dontIndent: bool) =
inc col
emitMultilineComment(em, lit, col, dontIndent)
proc emitTok*(em: var Emitter; L: TLexer; tok: TToken) =
proc emitTok*(em: var Emitter; L: Lexer; tok: Token) =
template wasExportMarker(em): bool =
em.kinds.len > 0 and em.kinds[^1] == ltExportMarker
@@ -444,6 +452,9 @@ proc emitTok*(em: var Emitter; L: TLexer; tok: TToken) =
if tok.tokType in openPars and tok.indent > em.indentStack[^1]:
while em.indentStack[^1] < tok.indent:
em.indentStack.add(em.indentStack[^1] + em.indWidth)
while em.indentStack[^1] > tok.indent:
discard em.indentStack.pop()
# aka: we are in an expression context:
let alignment = max(tok.indent - em.indentStack[^1], 0)
em.indentLevel = alignment + em.indentStack.high * em.indWidth
@@ -483,7 +494,7 @@ proc emitTok*(em: var Emitter; L: TLexer; tok: TToken) =
wrSpace em
if not em.inquote:
wr(em, TokTypeToStr[tok.tokType], ltKeyword)
wr(em, $tok.tokType, ltKeyword)
if tok.tokType in {tkAnd, tkOr, tkIn, tkNotin}:
rememberSplit(splitIn)
wrSpace em
@@ -492,28 +503,28 @@ proc emitTok*(em: var Emitter; L: TLexer; tok: TToken) =
wr(em, tok.ident.s, ltIdent)
of tkColon:
wr(em, TokTypeToStr[tok.tokType], ltOther)
wr(em, $tok.tokType, ltOther)
wrSpace em
of tkSemiColon, tkComma:
wr(em, TokTypeToStr[tok.tokType], ltOther)
wr(em, $tok.tokType, ltOther)
rememberSplit(splitComma)
wrSpace em
of openPars:
if tok.strongSpaceA > 0 and not em.endsInWhite and
(not em.wasExportMarker or tok.tokType == tkCurlyDotLe):
wrSpace em
wr(em, TokTypeToStr[tok.tokType], ltSomeParLe)
wr(em, $tok.tokType, ltSomeParLe)
rememberSplit(splitParLe)
of closedPars:
wr(em, TokTypeToStr[tok.tokType], ltSomeParRi)
wr(em, $tok.tokType, ltSomeParRi)
of tkColonColon:
wr(em, TokTypeToStr[tok.tokType], ltOther)
wr(em, $tok.tokType, ltOther)
of tkDot:
lastTokWasTerse = true
wr(em, TokTypeToStr[tok.tokType], ltOther)
wr(em, $tok.tokType, ltOther)
of tkEquals:
if not em.inquote and not em.endsInWhite: wrSpace(em)
wr(em, TokTypeToStr[tok.tokType], ltOther)
wr(em, $tok.tokType, ltOther)
if not em.inquote: wrSpace(em)
of tkOpr, tkDotDot:
if em.inquote or ((tok.strongSpaceA == 0 and tok.strongSpaceB == 0) and
@@ -533,7 +544,7 @@ proc emitTok*(em: var Emitter; L: TLexer; tok: TToken) =
wrSpace(em)
of tkAccent:
if not em.inquote and endsInAlpha(em): wrSpace(em)
wr(em, TokTypeToStr[tok.tokType], ltOther)
wr(em, $tok.tokType, ltOther)
em.inquote = not em.inquote
of tkComment:
if not preventComment:
@@ -562,7 +573,7 @@ proc endsWith(em: Emitter; k: varargs[string]): bool =
return true
proc rfind(em: Emitter, t: string): int =
for i in 1 .. 5:
for i in 1..5:
if em.tokens[^i] == t:
return i

View File

@@ -30,41 +30,49 @@ const
# don't forget to update the 'highlite' module if these charsets should change
type
TTokType* = enum
tkInvalid, tkEof, # order is important here!
tkSymbol, # keywords:
tkAddr, tkAnd, tkAs, tkAsm,
tkBind, tkBlock, tkBreak, tkCase, tkCast,
tkConcept, tkConst, tkContinue, tkConverter,
tkDefer, tkDiscard, tkDistinct, tkDiv, tkDo,
tkElif, tkElse, tkEnd, tkEnum, tkExcept, tkExport,
tkFinally, tkFor, tkFrom, tkFunc,
tkIf, tkImport, tkIn, tkInclude, tkInterface,
tkIs, tkIsnot, tkIterator,
tkLet,
tkMacro, tkMethod, tkMixin, tkMod, tkNil, tkNot, tkNotin,
tkObject, tkOf, tkOr, tkOut,
tkProc, tkPtr, tkRaise, tkRef, tkReturn,
tkShl, tkShr, tkStatic,
tkTemplate,
tkTry, tkTuple, tkType, tkUsing,
tkVar, tkWhen, tkWhile, tkXor,
tkYield, # end of keywords
tkIntLit, tkInt8Lit, tkInt16Lit, tkInt32Lit, tkInt64Lit,
tkUIntLit, tkUInt8Lit, tkUInt16Lit, tkUInt32Lit, tkUInt64Lit,
tkFloatLit, tkFloat32Lit, tkFloat64Lit, tkFloat128Lit,
tkStrLit, tkRStrLit, tkTripleStrLit,
tkGStrLit, tkGTripleStrLit, tkCharLit, tkParLe, tkParRi, tkBracketLe,
tkBracketRi, tkCurlyLe, tkCurlyRi,
tkBracketDotLe, tkBracketDotRi, # [. and .]
tkCurlyDotLe, tkCurlyDotRi, # {. and .}
tkParDotLe, tkParDotRi, # (. and .)
tkComma, tkSemiColon,
tkColon, tkColonColon, tkEquals, tkDot, tkDotDot, tkBracketLeColon,
tkOpr, tkComment, tkAccent,
TokType* = enum
tkInvalid = "tkInvalid", tkEof = "[EOF]", # order is important here!
tkSymbol = "tkSymbol", # keywords:
tkAddr = "addr", tkAnd = "and", tkAs = "as", tkAsm = "asm",
tkBind = "bind", tkBlock = "block", tkBreak = "break", tkCase = "case", tkCast = "cast",
tkConcept = "concept", tkConst = "const", tkContinue = "continue", tkConverter = "converter",
tkDefer = "defer", tkDiscard = "discard", tkDistinct = "distinct", tkDiv = "div", tkDo = "do",
tkElif = "elif", tkElse = "else", tkEnd = "end", tkEnum = "enum", tkExcept = "except", tkExport = "export",
tkFinally = "finally", tkFor = "for", tkFrom = "from", tkFunc = "func",
tkIf = "if", tkImport = "import", tkIn = "in", tkInclude = "include", tkInterface = "interface",
tkIs = "is", tkIsnot = "isnot", tkIterator = "iterator",
tkLet = "let",
tkMacro = "macro", tkMethod = "method", tkMixin = "mixin", tkMod = "mod", tkNil = "nil", tkNot = "not", tkNotin = "notin",
tkObject = "object", tkOf = "of", tkOr = "or", tkOut = "out",
tkProc = "proc", tkPtr = "ptr", tkRaise = "raise", tkRef = "ref", tkReturn = "return",
tkShl = "shl", tkShr = "shr", tkStatic = "static",
tkTemplate = "template",
tkTry = "try", tkTuple = "tuple", tkType = "type", tkUsing = "using",
tkVar = "var", tkWhen = "when", tkWhile = "while", tkXor = "xor",
tkYield = "yield", # end of keywords
tkIntLit = "tkIntLit", tkInt8Lit = "tkInt8Lit", tkInt16Lit = "tkInt16Lit",
tkInt32Lit = "tkInt32Lit", tkInt64Lit = "tkInt64Lit",
tkUIntLit = "tkUIntLit", tkUInt8Lit = "tkUInt8Lit", tkUInt16Lit = "tkUInt16Lit",
tkUInt32Lit = "tkUInt32Lit", tkUInt64Lit = "tkUInt64Lit",
tkFloatLit = "tkFloatLit", tkFloat32Lit = "tkFloat32Lit",
tkFloat64Lit = "tkFloat64Lit", tkFloat128Lit = "tkFloat128Lit",
tkStrLit = "tkStrLit", tkRStrLit = "tkRStrLit", tkTripleStrLit = "tkTripleStrLit",
tkGStrLit = "tkGStrLit", tkGTripleStrLit = "tkGTripleStrLit", tkCharLit = "tkCharLit",
tkParLe = "(", tkParRi = ")", tkBracketLe = "[",
tkBracketRi = "]", tkCurlyLe = "{", tkCurlyRi = "}",
tkBracketDotLe = "[.", tkBracketDotRi = ".]",
tkCurlyDotLe = "{.", tkCurlyDotRi = ".}",
tkParDotLe = "(.", tkParDotRi = ".)",
tkComma = ",", tkSemiColon = ";",
tkColon = ":", tkColonColon = "::", tkEquals = "=",
tkDot = ".", tkDotDot = "..", tkBracketLeColon = "[:",
tkOpr, tkComment, tkAccent = "`",
# these are fake tokens used by renderer.nim
tkSpaces, tkInfixOpr, tkPrefixOpr, tkPostfixOpr
TTokTypes* = set[TTokType]
TokTypes* = set[TokType]
const
weakTokens = {tkComma, tkSemiColon, tkColon,
@@ -73,53 +81,21 @@ const
# tokens that should not be considered for previousToken
tokKeywordLow* = succ(tkSymbol)
tokKeywordHigh* = pred(tkIntLit)
TokTypeToStr*: array[TTokType, string] = ["tkInvalid", "[EOF]",
"tkSymbol",
"addr", "and", "as", "asm",
"bind", "block", "break", "case", "cast",
"concept", "const", "continue", "converter",
"defer", "discard", "distinct", "div", "do",
"elif", "else", "end", "enum", "except", "export",
"finally", "for", "from", "func", "if",
"import", "in", "include", "interface", "is", "isnot", "iterator",
"let",
"macro", "method", "mixin", "mod",
"nil", "not", "notin", "object", "of", "or",
"out", "proc", "ptr", "raise", "ref", "return",
"shl", "shr", "static",
"template",
"try", "tuple", "type", "using",
"var", "when", "while", "xor",
"yield",
"tkIntLit", "tkInt8Lit", "tkInt16Lit", "tkInt32Lit", "tkInt64Lit",
"tkUIntLit", "tkUInt8Lit", "tkUInt16Lit", "tkUInt32Lit", "tkUInt64Lit",
"tkFloatLit", "tkFloat32Lit", "tkFloat64Lit", "tkFloat128Lit",
"tkStrLit", "tkRStrLit",
"tkTripleStrLit", "tkGStrLit", "tkGTripleStrLit", "tkCharLit", "(",
")", "[", "]", "{", "}", "[.", ".]", "{.", ".}", "(.", ".)",
",", ";",
":", "::", "=", ".", "..", "[:",
"tkOpr", "tkComment", "`",
"tkSpaces", "tkInfixOpr",
"tkPrefixOpr", "tkPostfixOpr"]
type
TNumericalBase* = enum
NumericalBase* = enum
base10, # base10 is listed as the first element,
# so that it is the correct default value
base2, base8, base16
CursorPosition* {.pure.} = enum ## XXX remove this again
None, InToken, BeforeToken, AfterToken
TToken* = object # a Nim token
tokType*: TTokType # the type of the token
Token* = object # a Nim token
tokType*: TokType # the type of the token
indent*: int # the indentation; != -1 if the token has been
# preceded with indentation
ident*: PIdent # the parsed identifier
iNumber*: BiggestInt # the parsed integer literal
fNumber*: BiggestFloat # the parsed floating point literal
base*: TNumericalBase # the numerical base; only valid for int
base*: NumericalBase # the numerical base; only valid for int
# or float literals
strongSpaceA*: int8 # leading spaces of an operator
strongSpaceB*: int8 # trailing spaces of an operator
@@ -127,26 +103,25 @@ type
# documentation comments are here too
line*, col*: int
when defined(nimpretty):
offsetA*, offsetB*: int # used for pretty printing so that literals
# like 0b01 or r"\L" are unaffected
offsetA*, offsetB*: int # used for pretty printing so that literals
# like 0b01 or r"\L" are unaffected
commentOffsetA*, commentOffsetB*: int
TErrorHandler* = proc (conf: ConfigRef; info: TLineInfo; msg: TMsgKind; arg: string)
TLexer* = object of TBaseLexer
ErrorHandler* = proc (conf: ConfigRef; info: TLineInfo; msg: TMsgKind; arg: string)
Lexer* = object of TBaseLexer
fileIdx*: FileIndex
indentAhead*: int # if > 0 an indentation has already been read
# this is needed because scanning comments
# needs so much look-ahead
currLineIndent*: int
strongSpaces*, allowTabs*: bool
cursor*: CursorPosition
errorHandler*: TErrorHandler
errorHandler*: ErrorHandler
cache*: IdentCache
when defined(nimsuggest):
previousToken: TLineInfo
config*: ConfigRef
proc getLineInfo*(L: TLexer, tok: TToken): TLineInfo {.inline.} =
proc getLineInfo*(L: Lexer, tok: Token): TLineInfo {.inline.} =
result = newLineInfo(L.fileIdx, tok.line, tok.col)
when defined(nimpretty):
result.offsetA = tok.offsetA
@@ -154,8 +129,8 @@ proc getLineInfo*(L: TLexer, tok: TToken): TLineInfo {.inline.} =
result.commentOffsetA = tok.commentOffsetA
result.commentOffsetB = tok.commentOffsetB
proc isKeyword*(kind: TTokType): bool =
result = (kind >= tokKeywordLow) and (kind <= tokKeywordHigh)
proc isKeyword*(kind: TokType): bool =
(kind >= tokKeywordLow) and (kind <= tokKeywordHigh)
template ones(n): untyped = ((1 shl n)-1) # for utf-8 conversion
@@ -169,28 +144,26 @@ proc isNimIdentifier*(s: string): bool =
inc(i)
result = true
proc `$`*(tok: TToken): string =
proc `$`*(tok: Token): string =
case tok.tokType
of tkIntLit..tkInt64Lit: result = $tok.iNumber
of tkFloatLit..tkFloat64Lit: result = $tok.fNumber
of tkInvalid, tkStrLit..tkCharLit, tkComment: result = tok.literal
of tkParLe..tkColon, tkEof, tkAccent:
result = TokTypeToStr[tok.tokType]
of tkIntLit..tkInt64Lit: $tok.iNumber
of tkFloatLit..tkFloat64Lit: $tok.fNumber
of tkInvalid, tkStrLit..tkCharLit, tkComment: tok.literal
of tkParLe..tkColon, tkEof, tkAccent: $tok.tokType
else:
if tok.ident != nil:
result = tok.ident.s
tok.ident.s
else:
result = ""
""
proc prettyTok*(tok: TToken): string =
if isKeyword(tok.tokType): result = "keyword " & tok.ident.s
else: result = $tok
proc prettyTok*(tok: Token): string =
if isKeyword(tok.tokType): "keyword " & tok.ident.s
else: $tok
proc printTok*(conf: ConfigRef; tok: TToken) =
msgWriteln(conf, $tok.line & ":" & $tok.col & "\t" &
TokTypeToStr[tok.tokType] & " " & $tok)
proc printTok*(conf: ConfigRef; tok: Token) =
msgWriteln(conf, $tok.line & ":" & $tok.col & "\t" & $tok.tokType & " " & $tok)
proc initToken*(L: var TToken) =
proc initToken*(L: var Token) =
L.tokType = tkInvalid
L.iNumber = 0
L.indent = 0
@@ -203,7 +176,7 @@ proc initToken*(L: var TToken) =
L.commentOffsetA = 0
L.commentOffsetB = 0
proc fillToken(L: var TToken) =
proc fillToken(L: var Token) =
L.tokType = tkInvalid
L.iNumber = 0
L.indent = 0
@@ -216,7 +189,7 @@ proc fillToken(L: var TToken) =
L.commentOffsetA = 0
L.commentOffsetB = 0
proc openLexer*(lex: var TLexer, fileIdx: FileIndex, inputstream: PLLStream;
proc openLexer*(lex: var Lexer, fileIdx: FileIndex, inputstream: PLLStream;
cache: IdentCache; config: ConfigRef) =
openBaseLexer(lex, inputstream)
lex.fileIdx = fileIdx
@@ -228,36 +201,36 @@ proc openLexer*(lex: var TLexer, fileIdx: FileIndex, inputstream: PLLStream;
lex.previousToken.fileIndex = fileIdx
lex.config = config
proc openLexer*(lex: var TLexer, filename: AbsoluteFile, inputstream: PLLStream;
proc openLexer*(lex: var Lexer, filename: AbsoluteFile, inputstream: PLLStream;
cache: IdentCache; config: ConfigRef) =
openLexer(lex, fileInfoIdx(config, filename), inputstream, cache, config)
proc closeLexer*(lex: var TLexer) =
proc closeLexer*(lex: var Lexer) =
if lex.config != nil:
inc(lex.config.linesCompiled, lex.lineNumber)
closeBaseLexer(lex)
proc getLineInfo(L: TLexer): TLineInfo =
proc getLineInfo(L: Lexer): TLineInfo =
result = newLineInfo(L.fileIdx, L.lineNumber, getColNumber(L, L.bufpos))
proc dispMessage(L: TLexer; info: TLineInfo; msg: TMsgKind; arg: string) =
proc dispMessage(L: Lexer; info: TLineInfo; msg: TMsgKind; arg: string) =
if L.errorHandler.isNil:
msgs.message(L.config, info, msg, arg)
else:
L.errorHandler(L.config, info, msg, arg)
proc lexMessage*(L: TLexer, msg: TMsgKind, arg = "") =
proc lexMessage*(L: Lexer, msg: TMsgKind, arg = "") =
L.dispMessage(getLineInfo(L), msg, arg)
proc lexMessageTok*(L: TLexer, msg: TMsgKind, tok: TToken, arg = "") =
proc lexMessageTok*(L: Lexer, msg: TMsgKind, tok: Token, arg = "") =
var info = newLineInfo(L.fileIdx, tok.line, tok.col)
L.dispMessage(info, msg, arg)
proc lexMessagePos(L: var TLexer, msg: TMsgKind, pos: int, arg = "") =
proc lexMessagePos(L: var Lexer, msg: TMsgKind, pos: int, arg = "") =
var info = newLineInfo(L.fileIdx, L.lineNumber, pos - L.lineStart)
L.dispMessage(info, msg, arg)
proc matchTwoChars(L: TLexer, first: char, second: set[char]): bool =
proc matchTwoChars(L: Lexer, first: char, second: set[char]): bool =
result = (L.buf[L.bufpos] == first) and (L.buf[L.bufpos + 1] in second)
template tokenBegin(tok, pos) {.dirty.} =
@@ -271,7 +244,6 @@ template tokenEnd(tok, pos) {.dirty.} =
let colB = getColNumber(L, pos)+1
if L.fileIdx == L.config.m.trackPos.fileIndex and L.config.m.trackPos.col in colA..colB and
L.lineNumber == L.config.m.trackPos.line.int and L.config.ideCmd in {ideSug, ideCon}:
L.cursor = CursorPosition.InToken
L.config.m.trackPos.col = colA.int16
colA = 0
when defined(nimpretty):
@@ -296,28 +268,27 @@ template tokenEndPrevious(tok, pos) =
let colB = getColNumber(L, pos)
if L.fileIdx == L.config.m.trackPos.fileIndex and L.config.m.trackPos.col in colA..colB and
L.lineNumber == L.config.m.trackPos.line.int and L.config.ideCmd in {ideSug, ideCon}:
L.cursor = CursorPosition.BeforeToken
L.config.m.trackPos = L.previousToken
L.config.m.trackPosAttached = true
colA = 0
when defined(nimpretty):
tok.offsetB = L.offsetBase + pos
template eatChar(L: var TLexer, t: var TToken, replacementChar: char) =
add(t.literal, replacementChar)
template eatChar(L: var Lexer, t: var Token, replacementChar: char) =
t.literal.add(replacementChar)
inc(L.bufpos)
template eatChar(L: var TLexer, t: var TToken) =
add(t.literal, L.buf[L.bufpos])
template eatChar(L: var Lexer, t: var Token) =
t.literal.add(L.buf[L.bufpos])
inc(L.bufpos)
proc getNumber(L: var TLexer, result: var TToken) =
proc matchUnderscoreChars(L: var TLexer, tok: var TToken, chars: set[char]): Natural =
proc getNumber(L: var Lexer, result: var Token) =
proc matchUnderscoreChars(L: var Lexer, tok: var Token, chars: set[char]): Natural =
var pos = L.bufpos # use registers for pos, buf
result = 0
while true:
if L.buf[pos] in chars:
add(tok.literal, L.buf[pos])
tok.literal.add(L.buf[pos])
inc(pos)
inc(result)
else:
@@ -328,35 +299,35 @@ proc getNumber(L: var TLexer, result: var TToken) =
"only single underscores may occur in a token and token may not " &
"end with an underscore: e.g. '1__1' and '1_' are invalid")
break
add(tok.literal, '_')
tok.literal.add('_')
inc(pos)
L.bufpos = pos
proc matchChars(L: var TLexer, tok: var TToken, chars: set[char]) =
proc matchChars(L: var Lexer, tok: var Token, chars: set[char]) =
var pos = L.bufpos # use registers for pos, buf
while L.buf[pos] in chars:
add(tok.literal, L.buf[pos])
tok.literal.add(L.buf[pos])
inc(pos)
L.bufpos = pos
proc lexMessageLitNum(L: var TLexer, msg: string, startpos: int, msgKind = errGenerated) =
proc lexMessageLitNum(L: var Lexer, msg: string, startpos: int, msgKind = errGenerated) =
# Used to get slightly human friendlier err messages.
const literalishChars = {'A'..'F', 'a'..'f', '0'..'9', 'X', 'x', 'o', 'O',
'c', 'C', 'b', 'B', '_', '.', '\'', 'd', 'i', 'u'}
var msgPos = L.bufpos
var t: TToken
var t: Token
t.literal = ""
L.bufpos = startpos # Use L.bufpos as pos because of matchChars
matchChars(L, t, literalishChars)
# We must verify +/- specifically so that we're not past the literal
if L.buf[L.bufpos] in {'+', '-'} and
L.buf[L.bufpos - 1] in {'e', 'E'}:
add(t.literal, L.buf[L.bufpos])
t.literal.add(L.buf[L.bufpos])
inc(L.bufpos)
matchChars(L, t, literalishChars)
if L.buf[L.bufpos] in {'\'', 'f', 'F', 'd', 'D', 'i', 'I', 'u', 'U'}:
inc(L.bufpos)
add(t.literal, L.buf[L.bufpos])
t.literal.add(L.buf[L.bufpos])
matchChars(L, t, {'0'..'9'})
L.bufpos = msgPos
lexMessage(L, msgKind, msg % t.literal)
@@ -571,7 +542,7 @@ proc getNumber(L: var TLexer, result: var TToken) =
try:
len = parseBiggestUInt(result.literal, iNumber)
except ValueError:
raise newException(OverflowError, "number out of range: " & $result.literal)
raise newException(OverflowDefect, "number out of range: " & $result.literal)
if len != result.literal.len:
raise newException(ValueError, "invalid integer: " & $result.literal)
result.iNumber = cast[int64](iNumber)
@@ -581,7 +552,7 @@ proc getNumber(L: var TLexer, result: var TToken) =
try:
len = parseBiggestInt(result.literal, iNumber)
except ValueError:
raise newException(OverflowError, "number out of range: " & $result.literal)
raise newException(OverflowDefect, "number out of range: " & $result.literal)
if len != result.literal.len:
raise newException(ValueError, "invalid integer: " & $result.literal)
result.iNumber = iNumber
@@ -607,12 +578,12 @@ proc getNumber(L: var TLexer, result: var TToken) =
except ValueError:
lexMessageLitNum(L, "invalid number: '$1'", startpos)
except OverflowError, RangeError:
except OverflowDefect, RangeDefect:
lexMessageLitNum(L, "number out of range: '$1'", startpos)
tokenEnd(result, postPos-1)
L.bufpos = postPos
proc handleHexChar(L: var TLexer, xi: var int; position: range[0..4]) =
proc handleHexChar(L: var Lexer, xi: var int; position: range[0..4]) =
template invalid() =
lexMessage(L, errGenerated,
"expected a hex digit, but found: " & L.buf[L.bufpos] &
@@ -637,7 +608,7 @@ proc handleHexChar(L: var TLexer, xi: var int; position: range[0..4]) =
# Need to progress for `nim check`
inc(L.bufpos)
proc handleDecChars(L: var TLexer, xi: var int) =
proc handleDecChars(L: var Lexer, xi: var int) =
while L.buf[L.bufpos] in {'0'..'9'}:
xi = (xi * 10) + (ord(L.buf[L.bufpos]) - ord('0'))
inc(L.bufpos)
@@ -680,58 +651,53 @@ proc addUnicodeCodePoint(s: var string, i: int) =
s[pos+4] = chr(i shr 6 and ones(6) or 0b10_0000_00)
s[pos+5] = chr(i and ones(6) or 0b10_0000_00)
proc getEscapedChar(L: var TLexer, tok: var TToken) =
proc getEscapedChar(L: var Lexer, tok: var Token) =
inc(L.bufpos) # skip '\'
case L.buf[L.bufpos]
of 'n', 'N':
if L.config.oldNewlines:
if tok.tokType == tkCharLit:
lexMessage(L, errGenerated, "\\n not allowed in character literal")
add(tok.literal, L.config.target.tnl)
else:
add(tok.literal, '\L')
tok.literal.add('\L')
inc(L.bufpos)
of 'p', 'P':
if tok.tokType == tkCharLit:
lexMessage(L, errGenerated, "\\p not allowed in character literal")
add(tok.literal, L.config.target.tnl)
tok.literal.add(L.config.target.tnl)
inc(L.bufpos)
of 'r', 'R', 'c', 'C':
add(tok.literal, CR)
tok.literal.add(CR)
inc(L.bufpos)
of 'l', 'L':
add(tok.literal, LF)
tok.literal.add(LF)
inc(L.bufpos)
of 'f', 'F':
add(tok.literal, FF)
tok.literal.add(FF)
inc(L.bufpos)
of 'e', 'E':
add(tok.literal, ESC)
tok.literal.add(ESC)
inc(L.bufpos)
of 'a', 'A':
add(tok.literal, BEL)
tok.literal.add(BEL)
inc(L.bufpos)
of 'b', 'B':
add(tok.literal, BACKSPACE)
tok.literal.add(BACKSPACE)
inc(L.bufpos)
of 'v', 'V':
add(tok.literal, VT)
tok.literal.add(VT)
inc(L.bufpos)
of 't', 'T':
add(tok.literal, '\t')
tok.literal.add('\t')
inc(L.bufpos)
of '\'', '\"':
add(tok.literal, L.buf[L.bufpos])
tok.literal.add(L.buf[L.bufpos])
inc(L.bufpos)
of '\\':
add(tok.literal, '\\')
tok.literal.add('\\')
inc(L.bufpos)
of 'x', 'X':
inc(L.bufpos)
var xi = 0
handleHexChar(L, xi, 1)
handleHexChar(L, xi, 2)
add(tok.literal, chr(xi))
tok.literal.add(chr(xi))
of 'u', 'U':
if tok.tokType == tkCharLit:
lexMessage(L, errGenerated, "\\u not allowed in character literal")
@@ -761,22 +727,17 @@ proc getEscapedChar(L: var TLexer, tok: var TToken) =
lexMessage(L, warnOctalEscape)
var xi = 0
handleDecChars(L, xi)
if (xi <= 255): add(tok.literal, chr(xi))
if (xi <= 255): tok.literal.add(chr(xi))
else: lexMessage(L, errGenerated, "invalid character constant")
else: lexMessage(L, errGenerated, "invalid character constant")
proc newString(s: cstring, len: int): string =
## XXX, how come there is no support for this?
result = newString(len)
for i in 0 ..< len:
result[i] = s[i]
proc handleCRLF(L: var TLexer, pos: int): int =
proc handleCRLF(L: var Lexer, pos: int): int =
template registerLine =
let col = L.getColNumber(pos)
if col > MaxLineLength:
lexMessagePos(L, hintLineTooLong, pos)
when not defined(nimpretty):
if col > MaxLineLength:
lexMessagePos(L, hintLineTooLong, pos)
case L.buf[pos]
of CR:
@@ -793,7 +754,7 @@ type
raw,
generalized
proc getString(L: var TLexer, tok: var TToken, mode: StringMode) =
proc getString(L: var Lexer, tok: var Token, mode: StringMode) =
var pos = L.bufpos
var line = L.lineNumber # save linenumber for better error message
tokenBegin(tok, pos - ord(mode == raw))
@@ -815,12 +776,12 @@ proc getString(L: var TLexer, tok: var TToken, mode: StringMode) =
tokenEndIgnore(tok, pos+2)
L.bufpos = pos + 3 # skip the three """
break
add(tok.literal, '\"')
tok.literal.add('\"')
inc(pos)
of CR, LF:
tokenEndIgnore(tok, pos)
pos = handleCRLF(L, pos)
add(tok.literal, "\n")
tok.literal.add("\n")
of nimlexbase.EndOfFile:
tokenEndIgnore(tok, pos)
var line2 = L.lineNumber
@@ -830,7 +791,7 @@ proc getString(L: var TLexer, tok: var TToken, mode: StringMode) =
L.bufpos = pos
break
else:
add(tok.literal, L.buf[pos])
tok.literal.add(L.buf[pos])
inc(pos)
else:
# ordinary string literal
@@ -841,7 +802,7 @@ proc getString(L: var TLexer, tok: var TToken, mode: StringMode) =
if c == '\"':
if mode != normal and L.buf[pos+1] == '\"':
inc(pos, 2)
add(tok.literal, '"')
tok.literal.add('"')
else:
tokenEndIgnore(tok, pos)
inc(pos) # skip '"'
@@ -855,11 +816,11 @@ proc getString(L: var TLexer, tok: var TToken, mode: StringMode) =
getEscapedChar(L, tok)
pos = L.bufpos
else:
add(tok.literal, c)
tok.literal.add(c)
inc(pos)
L.bufpos = pos
proc getCharacter(L: var TLexer, tok: var TToken) =
proc getCharacter(L: var Lexer, tok: var Token) =
tokenBegin(tok, L.bufpos)
inc(L.bufpos) # skip '
var c = L.buf[L.bufpos]
@@ -876,7 +837,7 @@ proc getCharacter(L: var TLexer, tok: var TToken) =
tokenEndIgnore(tok, L.bufpos)
inc(L.bufpos) # skip '
proc getSymbol(L: var TLexer, tok: var TToken) =
proc getSymbol(L: var Lexer, tok: var Token) =
var h: Hash = 0
var pos = L.bufpos
tokenBegin(tok, pos)
@@ -906,21 +867,21 @@ proc getSymbol(L: var TLexer, tok: var TToken) =
(tok.ident.id > ord(tokKeywordHigh) - ord(tkSymbol)):
tok.tokType = tkSymbol
else:
tok.tokType = TTokType(tok.ident.id + ord(tkSymbol))
tok.tokType = TokType(tok.ident.id + ord(tkSymbol))
if suspicious and {optStyleHint, optStyleError} * L.config.globalOptions != {}:
lintReport(L.config, getLineInfo(L), tok.ident.s.normalize, tok.ident.s)
L.bufpos = pos
proc endOperator(L: var TLexer, tok: var TToken, pos: int,
proc endOperator(L: var Lexer, tok: var Token, pos: int,
hash: Hash) {.inline.} =
var h = !$hash
tok.ident = L.cache.getIdent(addr(L.buf[L.bufpos]), pos - L.bufpos, h)
if (tok.ident.id < oprLow) or (tok.ident.id > oprHigh): tok.tokType = tkOpr
else: tok.tokType = TTokType(tok.ident.id - oprLow + ord(tkColon))
else: tok.tokType = TokType(tok.ident.id - oprLow + ord(tkColon))
L.bufpos = pos
proc getOperator(L: var TLexer, tok: var TToken) =
proc getOperator(L: var Lexer, tok: var Token) =
var pos = L.bufpos
tokenBegin(tok, pos)
var h: Hash = 0
@@ -940,22 +901,18 @@ proc getOperator(L: var TLexer, tok: var TToken) =
if L.buf[pos] in {CR, LF, nimlexbase.EndOfFile}:
tok.strongSpaceB = -1
proc getPrecedence*(tok: TToken, strongSpaces: bool): int =
proc getPrecedence*(tok: Token): int =
## Calculates the precedence of the given token.
template considerStrongSpaces(x): untyped =
x + (if strongSpaces: 100 - tok.strongSpaceA.int*10 else: 0)
case tok.tokType
of tkOpr:
let L = tok.ident.s.len
let relevantChar = tok.ident.s[0]
# arrow like?
if L > 1 and tok.ident.s[L-1] == '>' and
tok.ident.s[L-2] in {'-', '~', '='}: return considerStrongSpaces(1)
if tok.ident.s.len > 1 and tok.ident.s[^1] == '>' and
tok.ident.s[^2] in {'-', '~', '='}: return 1
template considerAsgn(value: untyped) =
result = if tok.ident.s[L-1] == '=': 1 else: value
result = if tok.ident.s[^1] == '=': 1 else: value
case relevantChar
of '$', '^': considerAsgn(10)
@@ -968,15 +925,13 @@ proc getPrecedence*(tok: TToken, strongSpaces: bool): int =
of '?': result = 2
else: considerAsgn(2)
of tkDiv, tkMod, tkShl, tkShr: result = 9
of tkIn, tkNotin, tkIs, tkIsnot, tkOf, tkAs: result = 5
of tkDotDot: result = 6
of tkIn, tkNotin, tkIs, tkIsnot, tkOf, tkAs, tkFrom: result = 5
of tkAnd: result = 4
of tkOr, tkXor, tkPtr, tkRef: result = 3
else: return -10
result = considerStrongSpaces(result)
proc newlineFollows*(L: TLexer): bool =
proc newlineFollows*(L: Lexer): bool =
var pos = L.bufpos
while true:
case L.buf[pos]
@@ -992,7 +947,7 @@ proc newlineFollows*(L: TLexer): bool =
else:
break
proc skipMultiLineComment(L: var TLexer; tok: var TToken; start: int;
proc skipMultiLineComment(L: var Lexer; tok: var Token; start: int;
isDoc: bool) =
var pos = start
var toStrip = 0
@@ -1057,14 +1012,14 @@ proc skipMultiLineComment(L: var TLexer; tok: var TToken; start: int;
when defined(nimpretty):
tok.commentOffsetB = L.offsetBase + pos - 1
proc scanComment(L: var TLexer, tok: var TToken) =
proc scanComment(L: var Lexer, tok: var Token) =
var pos = L.bufpos
tok.tokType = tkComment
# iNumber contains the number of '\n' in the token
tok.iNumber = 0
assert L.buf[pos+1] == '#'
when defined(nimpretty):
tok.commentOffsetA = L.offsetBase + pos - 1
tok.commentOffsetA = L.offsetBase + pos
if L.buf[pos+2] == '[':
skipMultiLineComment(L, tok, pos+3, true)
@@ -1081,7 +1036,7 @@ proc scanComment(L: var TLexer, tok: var TToken) =
var lastBackslash = -1
while L.buf[pos] notin {CR, LF, nimlexbase.EndOfFile}:
if L.buf[pos] == '\\': lastBackslash = pos+1
add(tok.literal, L.buf[pos])
tok.literal.add(L.buf[pos])
inc(pos)
tokenEndIgnore(tok, pos)
pos = handleCRLF(L, pos)
@@ -1107,7 +1062,7 @@ proc scanComment(L: var TLexer, tok: var TToken) =
when defined(nimpretty):
tok.commentOffsetB = L.offsetBase + pos - 1
proc skip(L: var TLexer, tok: var TToken) =
proc skip(L: var Lexer, tok: var Token) =
var pos = L.bufpos
tokenBegin(tok, pos)
tok.strongSpaceA = 0
@@ -1179,7 +1134,7 @@ proc skip(L: var TLexer, tok: var TToken) =
tok.tokType = tkComment
tok.indent = commentIndent
proc rawGetTok*(L: var TLexer, tok: var TToken) =
proc rawGetTok*(L: var Lexer, tok: var Token) =
template atTokenEnd() {.dirty.} =
when defined(nimsuggest):
# we attach the cursor to the last *strong* token
@@ -1187,8 +1142,6 @@ proc rawGetTok*(L: var TLexer, tok: var TToken) =
L.previousToken.line = tok.line.uint16
L.previousToken.col = tok.col.int16
when defined(nimsuggest):
L.cursor = CursorPosition.None
fillToken(tok)
if L.indentAhead >= 0:
tok.indent = L.indentAhead
@@ -1259,7 +1212,6 @@ proc rawGetTok*(L: var TLexer, tok: var TToken) =
if L.fileIdx == L.config.m.trackPos.fileIndex and tok.col+1 == L.config.m.trackPos.col and
tok.line == L.config.m.trackPos.line.int and L.config.ideCmd == ideSug:
tok.tokType = tkDot
L.cursor = CursorPosition.InToken
L.config.m.trackPos.col = tok.col.int16
inc(L.bufpos)
atTokenEnd()
@@ -1332,8 +1284,8 @@ proc rawGetTok*(L: var TLexer, tok: var TToken) =
proc getIndentWidth*(fileIdx: FileIndex, inputstream: PLLStream;
cache: IdentCache; config: ConfigRef): int =
var lex: TLexer
var tok: TToken
var lex: Lexer
var tok: Token
initToken(tok)
openLexer(lex, fileIdx, inputstream, cache, config)
var prevToken = tkEof
@@ -1347,11 +1299,11 @@ proc getIndentWidth*(fileIdx: FileIndex, inputstream: PLLStream;
proc getPrecedence*(ident: PIdent): int =
## assumes ident is binary operator already
var tok: TToken
var tok: Token
initToken(tok)
tok.ident = ident
tok.tokType =
if tok.ident.id in ord(tokKeywordLow) - ord(tkSymbol) .. ord(tokKeywordHigh) - ord(tkSymbol):
TTokType(tok.ident.id + ord(tkSymbol))
if tok.ident.id in ord(tokKeywordLow) - ord(tkSymbol)..ord(tokKeywordHigh) - ord(tkSymbol):
TokType(tok.ident.id + ord(tkSymbol))
else: tkOpr
getPrecedence(tok, false)
getPrecedence(tok)

File diff suppressed because it is too large Load Diff

View File

@@ -30,10 +30,10 @@ proc lookupOrAdd(c: var Ctx; s: PSym; info: TLineInfo): PNode =
let field = addUniqueField(c.objType, s, c.cache)
var deref = newNodeI(nkHiddenDeref, info)
deref.typ = c.objType
add(deref, newSymNode(c.partialParam, info))
deref.add(newSymNode(c.partialParam, info))
result = newNodeI(nkDotExpr, info)
add(result, deref)
add(result, newSymNode(field))
result.add(deref)
result.add(newSymNode(field))
result.typ = field.typ
proc liftLocals(n: PNode; i: int; c: var Ctx) =
@@ -42,14 +42,14 @@ proc liftLocals(n: PNode; i: int; c: var Ctx) =
of nkSym:
if interestingVar(it.sym):
n[i] = lookupOrAdd(c, it.sym, it.info)
of procDefs, nkTypeSection: discard
of procDefs, nkTypeSection, nkMixinStmt, nkBindStmt: discard
else:
for i in 0 ..< it.safeLen:
for i in 0..<it.safeLen:
liftLocals(it, i, c)
proc lookupParam(params, dest: PNode): PSym =
if dest.kind != nkIdent: return nil
for i in 1 ..< params.len:
for i in 1..<params.len:
if params[i].kind == nkSym and params[i].sym.name.id == dest.ident.id:
return params[i].sym

View File

@@ -10,10 +10,20 @@
## This module contains the ``TMsgKind`` enum as well as the
## ``TLineInfo`` object.
import ropes, tables, pathutils
import ropes, tables, pathutils, hashes
const
explanationsBaseUrl* = "https://nim-lang.org/docs"
explanationsBaseUrl* = "https://nim-lang.github.io/Nim"
# was: "https://nim-lang.org/docs" but we're now usually showing devel docs
# instead of latest release docs.
proc createDocLink*(urlSuffix: string): string =
# os.`/` is not appropriate for urls.
result = explanationsBaseUrl
if urlSuffix.len > 0 and urlSuffix[0] == '/':
result.add urlSuffix
else:
result.add "/" & urlSuffix
type
TMsgKind* = enum
@@ -23,32 +33,43 @@ type
errGeneralParseError,
errNewSectionExpected,
errInvalidDirectiveX,
errProveInit, # deadcode
errGenerated,
errUser,
warnCannotOpenFile,
warnOctalEscape, warnXIsNeverRead, warnXmightNotBeenInit,
warnDeprecated, warnConfigDeprecated,
warnSmallLshouldNotBeUsed, warnUnknownMagic, warnRedefinitionOfLabel,
warnUnknownSubstitutionX, warnLanguageXNotSupported,
warnFieldXNotSupported, warnCommentXIgnored,
warnTypelessParam,
warnUseBase, warnWriteToForeignHeap, warnUnsafeCode,
warnUnusedImportX,
warnEachIdentIsTuple,
warnProveInit, warnProveField, warnProveIndex, warnGcUnsafe, warnGcUnsafe2,
warnUninit, warnGcMem, warnDestructor, warnLockLevel, warnResultShadowed,
warnInconsistentSpacing, warnCaseTransition, warnUser,
hintSuccess, hintSuccessX, hintCC,
hintLineTooLong, hintXDeclaredButNotUsed,
hintConvToBaseNotNeeded,
hintConvFromXtoItselfNotNeeded, hintExprAlwaysX, hintQuitCalled,
hintProcessing, hintCodeBegin, hintCodeEnd, hintConf, hintPath,
hintConditionAlwaysTrue, hintConditionAlwaysFalse, hintName, hintPattern,
hintExecuting, hintLinking, hintDependency,
hintSource, hintPerformance, hintStackTrace, hintGCStats,
hintGlobalVar, hintExpandMacro,
hintUser, hintUserRaw,
hintExtendedContext
warnCannotOpenFile = "CannotOpenFile", warnOctalEscape = "OctalEscape",
warnXIsNeverRead = "XIsNeverRead", warnXmightNotBeenInit = "XmightNotBeenInit",
warnDeprecated = "Deprecated", warnConfigDeprecated = "ConfigDeprecated",
warnSmallLshouldNotBeUsed = "SmallLshouldNotBeUsed", warnUnknownMagic = "UnknownMagic",
warnRedefinitionOfLabel = "RedefinitionOfLabel", warnUnknownSubstitutionX = "UnknownSubstitutionX",
warnLanguageXNotSupported = "LanguageXNotSupported", warnFieldXNotSupported = "FieldXNotSupported",
warnCommentXIgnored = "CommentXIgnored", warnTypelessParam = "TypelessParam",
warnUseBase = "UseBase", warnWriteToForeignHeap = "WriteToForeignHeap",
warnUnsafeCode = "UnsafeCode", warnUnusedImportX = "UnusedImport",
warnInheritFromException = "InheritFromException", warnEachIdentIsTuple = "EachIdentIsTuple",
warnUnsafeSetLen = "UnsafeSetLen", warnUnsafeDefault = "UnsafeDefault",
warnProveInit = "ProveInit", warnProveField = "ProveField", warnProveIndex = "ProveIndex",
warnUnreachableElse = "UnreachableElse", warnUnreachableCode = "UnreachableCode",
warnStaticIndexCheck = "IndexCheck", warnGcUnsafe = "GcUnsafe", warnGcUnsafe2 = "GcUnsafe2",
warnUninit = "Uninit", warnGcMem = "GcMem", warnDestructor = "Destructor",
warnLockLevel = "LockLevel", warnResultShadowed = "ResultShadowed",
warnInconsistentSpacing = "Spacing", warnCaseTransition = "CaseTransition",
warnCycleCreated = "CycleCreated", warnObservableStores = "ObservableStores",
warnResultUsed = "ResultUsed",
warnUser = "User",
hintSuccess = "Success", hintSuccessX = "SuccessX", hintCC = "CC",
hintLineTooLong = "LineTooLong", hintXDeclaredButNotUsed = "XDeclaredButNotUsed",
hintXCannotRaiseY = "XCannotRaiseY", hintConvToBaseNotNeeded = "ConvToBaseNotNeeded",
hintConvFromXtoItselfNotNeeded = "ConvFromXtoItselfNotNeeded", hintExprAlwaysX = "ExprAlwaysX",
hintQuitCalled = "QuitCalled", hintProcessing = "Processing", hintCodeBegin = "CodeBegin",
hintCodeEnd = "CodeEnd", hintConf = "Conf", hintPath = "Path",
hintConditionAlwaysTrue = "CondTrue", hintConditionAlwaysFalse = "CondFalse", hintName = "Name",
hintPattern = "Pattern", hintExecuting = "Exec", hintLinking = "Link", hintDependency = "Dependency",
hintSource = "Source", hintPerformance = "Performance", hintStackTrace = "StackTrace",
hintGCStats = "GCStats", hintGlobalVar = "GlobalVar", hintExpandMacro = "ExpandMacro",
hintUser = "User", hintUserRaw = "UserRaw", hintExtendedContext = "ExtendedContext",
hintMsgOrigin = "MsgOrigin", # since 1.3.5
const
MsgKindToStr*: array[TMsgKind, string] = [
@@ -61,6 +82,7 @@ const
errGeneralParseError: "general parse error",
errNewSectionExpected: "new section expected",
errInvalidDirectiveX: "invalid directive: '$1'",
errProveInit: "Cannot prove that '$1' is initialized.", # deadcode
errGenerated: "$1",
errUser: "$1",
warnCannotOpenFile: "cannot open '$1'",
@@ -81,25 +103,38 @@ const
warnWriteToForeignHeap: "write to foreign heap",
warnUnsafeCode: "unsafe code: '$1'",
warnUnusedImportX: "imported and not used: '$1'",
warnInheritFromException: "inherit from a more precise exception type like ValueError, " &
"IOError or OSError. If these don't suit, inherit from CatchableError or Defect.",
warnEachIdentIsTuple: "each identifier is a tuple",
warnUnsafeSetLen: "setLen can potentially expand the sequence, " &
"but the element type '$1' doesn't have a valid default value",
warnUnsafeDefault: "The '$1' type doesn't have a valid default value",
warnProveInit: "Cannot prove that '$1' is initialized. This will become a compile time error in the future.",
warnProveField: "cannot prove that field '$1' is accessible",
warnProveIndex: "cannot prove index '$1' is valid",
warnUnreachableElse: "unreachable else, all cases are already covered",
warnUnreachableCode: "unreachable code after 'return' statement or '{.noReturn.}' proc",
warnStaticIndexCheck: "$1",
warnGcUnsafe: "not GC-safe: '$1'",
warnGcUnsafe2: "$1",
warnUninit: "'$1' might not have been initialized",
warnUninit: "use explicit initialization of '$1' for clarity",
warnGcMem: "'$1' uses GC'ed memory",
warnDestructor: "usage of a type with a destructor in a non destructible context. This will become a compile time error in the future.",
warnLockLevel: "$1",
warnResultShadowed: "Special variable 'result' is shadowed.",
warnInconsistentSpacing: "Number of spaces around '$#' is not consistent",
warnCaseTransition: "Potential object case transition, instantiate new object instead",
warnCycleCreated: "$1",
warnObservableStores: "observable stores to '$1'",
warnResultUsed: "used 'result' variable",
warnUser: "$1",
hintSuccess: "operation successful: $#",
hintSuccessX: "operation successful ($# lines compiled; $# sec total; $#; $#)",
hintCC: "CC: \'$1\'", # unused
# keep in sync with `testament.isSuccess`
hintSuccessX: "${loc} lines; ${sec}s; $mem; $build build; proj: $project; out: $output",
hintCC: "CC: $1",
hintLineTooLong: "line too long",
hintXDeclaredButNotUsed: "'$1' is declared but not used",
hintXCannotRaiseY: "$1",
hintConvToBaseNotNeeded: "conversion to base object is not needed",
hintConvFromXtoItselfNotNeeded: "conversion from $1 to itself is pointless",
hintExprAlwaysX: "expression evaluates always to '$1'",
@@ -114,7 +149,7 @@ const
hintName: "$1",
hintPattern: "$1",
hintExecuting: "$1",
hintLinking: "",
hintLinking: "$1",
hintDependency: "$1",
hintSource: "$1",
hintPerformance: "$1",
@@ -125,30 +160,7 @@ const
hintUser: "$1",
hintUserRaw: "$1",
hintExtendedContext: "$1",
]
const
WarningsToStr* = ["CannotOpenFile", "OctalEscape",
"XIsNeverRead", "XmightNotBeenInit",
"Deprecated", "ConfigDeprecated",
"SmallLshouldNotBeUsed", "UnknownMagic",
"RedefinitionOfLabel", "UnknownSubstitutionX",
"LanguageXNotSupported", "FieldXNotSupported",
"CommentXIgnored",
"TypelessParam", "UseBase", "WriteToForeignHeap",
"UnsafeCode", "UnusedImport", "EachIdentIsTuple",
"ProveInit", "ProveField", "ProveIndex", "GcUnsafe", "GcUnsafe2", "Uninit",
"GcMem", "Destructor", "LockLevel", "ResultShadowed",
"Spacing", "CaseTransition", "User"]
HintsToStr* = [
"Success", "SuccessX", "CC", "LineTooLong",
"XDeclaredButNotUsed",
"ConvToBaseNotNeeded", "ConvFromXtoItselfNotNeeded",
"ExprAlwaysX", "QuitCalled", "Processing", "CodeBegin", "CodeEnd", "Conf",
"Path", "CondTrue", "CondFalse", "Name", "Pattern", "Exec", "Link", "Dependency",
"Source", "Performance", "StackTrace", "GCStats", "GlobalVar", "ExpandMacro",
"User", "UserRaw", "ExtendedContext",
hintMsgOrigin: "$1",
]
const
@@ -161,20 +173,16 @@ const
hintMin* = hintSuccess
hintMax* = high(TMsgKind)
static:
doAssert HintsToStr.len == ord(hintMax) - ord(hintMin) + 1
doAssert WarningsToStr.len == ord(warnMax) - ord(warnMin) + 1
type
TNoteKind* = range[warnMin..hintMax] # "notes" are warnings or hints
TNoteKinds* = set[TNoteKind]
proc computeNotesVerbosity(): array[0..3, TNoteKinds] =
result[3] = {low(TNoteKind)..high(TNoteKind)} - {}
result[3] = {low(TNoteKind)..high(TNoteKind)} - {warnObservableStores, warnResultUsed}
result[2] = result[3] - {hintStackTrace, warnUninit, hintExtendedContext}
result[1] = result[2] - {warnProveField, warnProveIndex,
warnGcUnsafe, hintPath, hintDependency, hintCodeBegin, hintCodeEnd,
hintSource, hintGlobalVar, hintGCStats}
hintSource, hintGlobalVar, hintGCStats, hintMsgOrigin}
result[0] = result[1] - {hintSuccessX, hintSuccess, hintConf,
hintProcessing, hintPattern, hintExecuting, hintLinking, hintCC}
@@ -225,20 +233,19 @@ type
TErrorOutputs* = set[TErrorOutput]
ERecoverableError* = object of ValueError
ESuggestDone* = object of Exception
ESuggestDone* = object of ValueError
proc `==`*(a, b: FileIndex): bool {.borrow.}
proc hash*(i: TLineInfo): Hash =
hash (i.line.int, i.col.int, i.fileIndex.int)
proc raiseRecoverableError*(msg: string) {.noinline.} =
raise newException(ERecoverableError, msg)
const
InvalidFileIdx* = FileIndex(-1)
proc unknownLineInfo*(): TLineInfo =
result.line = uint16(0)
result.col = int16(-1)
result.fileIndex = InvalidFileIdx
unknownLineInfo* = TLineInfo(line: 0, col: -1, fileIndex: InvalidFileIdx)
type
Severity* {.pure.} = enum ## VS Code only supports these three
@@ -265,7 +272,7 @@ type
proc initMsgConfig*(): MsgConfig =
result.msgContext = @[]
result.lastError = unknownLineInfo()
result.lastError = unknownLineInfo
result.filenameToIndexTbl = initTable[string, FileIndex]()
result.fileInfos = @[]
result.errorOutputs = {eStdOut, eStdErr}

View File

@@ -37,7 +37,7 @@ proc beautifyName(s: string, k: TSymKind): string =
# Types should start with a capital unless builtins like 'int' etc.:
if s =~ ["int", "uint", "cint", "cuint", "clong", "cstring", "string",
"char", "byte", "bool", "openArray", "seq", "array", "void",
"pointer", "float", "csize", "cdouble", "cchar", "cschar",
"pointer", "float", "csize", "csize_t", "cdouble", "cchar", "cschar",
"cshort", "cu", "nil", "typedesc", "auto", "any",
"range", "openarray", "varargs", "set", "cfloat", "ref", "ptr",
"untyped", "typed", "static", "sink", "lent", "type", "owned"]:
@@ -71,13 +71,9 @@ proc beautifyName(s: string, k: TSymKind): string =
proc differ*(line: string, a, b: int, x: string): string =
proc substrEq(s: string, pos, last: int, substr: string): bool =
var i = 0
var length = substr.len
while i < length and pos+i <= last and s[pos+i] == substr[i]:
inc i
return i == length
let last = min(b, line.len)
result = true
for i in 0..<substr.len:
if pos+i > last or s[pos+i] != substr[i]: return false
result = ""
if not substrEq(line, a, b, x):
@@ -85,11 +81,6 @@ proc differ*(line: string, a, b: int, x: string): string =
if cmpIgnoreStyle(y, x) == 0:
result = y
proc checkStyle(conf: ConfigRef; cache: IdentCache; info: TLineInfo, s: string, k: TSymKind; sym: PSym) =
let beau = beautifyName(s, k)
if s != beau:
lintReport(conf, info, beau, s)
proc nep1CheckDefImpl(conf: ConfigRef; info: TLineInfo; s: PSym; k: TSymKind) =
# operators stay as they are:
if k in {skResult, skTemp} or s.name.s[0] notin Letters: return
@@ -102,7 +93,7 @@ proc nep1CheckDefImpl(conf: ConfigRef; info: TLineInfo; s: PSym; k: TSymKind) =
lintReport(conf, info, beau, s.name.s)
template styleCheckDef*(conf: ConfigRef; info: TLineInfo; s: PSym; k: TSymKind) =
if {optStyleHint, optStyleError} * conf.globalOptions != {}:
if {optStyleHint, optStyleError} * conf.globalOptions != {} and optStyleUsages notin conf.globalOptions:
nep1CheckDefImpl(conf, info, s, k)
template styleCheckDef*(conf: ConfigRef; info: TLineInfo; s: PSym) =
@@ -137,6 +128,6 @@ proc styleCheckUse*(conf: ConfigRef; info: TLineInfo; s: PSym) =
lintReport(conf, info, newName, oldName)
proc checkPragmaUse*(conf: ConfigRef; info: TLineInfo; w: TSpecialWord; pragmaName: string) =
let wanted = canonPragmaSpelling(w)
let wanted = $w
if pragmaName != wanted:
lintReport(conf, info, wanted, pragmaName)

View File

@@ -12,9 +12,11 @@
import
pathutils
# support '-d:useGnuReadline' for backwards compatibility:
when not defined(windows) and (defined(useGnuReadline) or defined(useLinenoise)):
import rdstdin
# support `useGnuReadline`, `useLinenoise` for backwards compatibility
const hasRstdin = (defined(nimUseLinenoise) or defined(useLinenoise) or defined(useGnuReadline)) and
not defined(windows)
when hasRstdin: import rdstdin
type
TLLRepl* = proc (s: PLLStream, buf: pointer, bufLen: int): int
@@ -109,12 +111,12 @@ proc llReadFromStdin(s: PLLStream, buf: pointer, bufLen: int): int =
var line = newStringOfCap(120)
var triples = 0
while readLineFromStdin(if s.s.len == 0: ">>> " else: "... ", line):
add(s.s, line)
add(s.s, "\n")
s.s.add(line)
s.s.add("\n")
inc triples, countTriples(line)
if not continueLine(line, (triples and 1) == 1): break
inc(s.lineOffset)
result = min(bufLen, len(s.s) - s.rd)
result = min(bufLen, s.s.len - s.rd)
if result > 0:
copyMem(buf, addr(s.s[s.rd]), result)
inc(s.rd, result)
@@ -124,7 +126,7 @@ proc llStreamRead*(s: PLLStream, buf: pointer, bufLen: int): int =
of llsNone:
result = 0
of llsString:
result = min(bufLen, len(s.s) - s.rd)
result = min(bufLen, s.s.len - s.rd)
if result > 0:
copyMem(buf, addr(s.s[0 + s.rd]), result)
inc(s.rd, result)
@@ -139,7 +141,7 @@ proc llStreamReadLine*(s: PLLStream, line: var string): bool =
of llsNone:
result = true
of llsString:
while s.rd < len(s.s):
while s.rd < s.s.len:
case s.s[s.rd]
of '\x0D':
inc(s.rd)
@@ -149,9 +151,9 @@ proc llStreamReadLine*(s: PLLStream, line: var string): bool =
inc(s.rd)
break
else:
add(line, s.s[s.rd])
line.add(s.s[s.rd])
inc(s.rd)
result = line.len > 0 or s.rd < len(s.s)
result = line.len > 0 or s.rd < s.s.len
of llsFile:
result = readLine(s.f, line)
of llsStdIn:
@@ -162,8 +164,8 @@ proc llStreamWrite*(s: PLLStream, data: string) =
of llsNone, llsStdIn:
discard
of llsString:
add(s.s, data)
inc(s.wr, len(data))
s.s.add(data)
inc(s.wr, data.len)
of llsFile:
write(s.f, data)
@@ -177,7 +179,7 @@ proc llStreamWrite*(s: PLLStream, data: char) =
of llsNone, llsStdIn:
discard
of llsString:
add(s.s, data)
s.s.add(data)
inc(s.wr)
of llsFile:
c = data
@@ -189,7 +191,7 @@ proc llStreamWrite*(s: PLLStream, buf: pointer, buflen: int) =
discard
of llsString:
if buflen > 0:
setLen(s.s, len(s.s) + buflen)
setLen(s.s, s.s.len + buflen)
copyMem(addr(s.s[0 + s.wr]), buf, buflen)
inc(s.wr, buflen)
of llsFile:
@@ -204,7 +206,7 @@ proc llStreamReadAll*(s: PLLStream): string =
of llsString:
if s.rd == 0: result = s.s
else: result = substr(s.s, s.rd)
s.rd = len(s.s)
s.rd = s.s.len
of llsFile:
result = newString(bufSize)
var bytes = readBuffer(s.f, addr(result[0]), bufSize)

View File

@@ -36,11 +36,11 @@ proc considerQuotedIdent*(c: PContext; n: PNode, origin: PNode = nil): PIdent =
of nkAccQuoted:
case n.len
of 0: handleError(n, origin)
of 1: result = considerQuotedIdent(c, n.sons[0], origin)
of 1: result = considerQuotedIdent(c, n[0], origin)
else:
var id = ""
for i in 0..<n.len:
let x = n.sons[i]
let x = n[i]
case x.kind
of nkIdent: id.add(x.ident.s)
of nkSym: id.add(x.sym.name.s)
@@ -49,7 +49,7 @@ proc considerQuotedIdent*(c: PContext; n: PNode, origin: PNode = nil): PIdent =
result = getIdent(c.cache, id)
of nkOpenSymChoice, nkClosedSymChoice:
if n[0].kind == nkSym:
result = n.sons[0].sym.name
result = n[0].sym.name
else:
handleError(n, origin)
else:
@@ -91,8 +91,15 @@ proc skipAlias*(s: PSym; n: PNode; conf: ConfigRef): PSym =
message(conf, n.info, warnDeprecated, "use " & result.name.s & " instead; " &
s.name.s & " is deprecated")
proc isShadowScope*(s: PScope): bool {.inline.} = s.parent != nil and s.parent.depthLevel == s.depthLevel
proc localSearchInScope*(c: PContext, s: PIdent): PSym =
result = strTableGet(c.currentScope.symbols, s)
var scope = c.currentScope
result = strTableGet(scope.symbols, s)
while result == nil and scope.isShadowScope:
# We are in a shadow scope, check in the parent too
scope = scope.parent
result = strTableGet(scope.symbols, s)
proc searchInScopes*(c: PContext, s: PIdent): PSym =
for scope in walkScopes(c.currentScope):
@@ -100,16 +107,15 @@ proc searchInScopes*(c: PContext, s: PIdent): PSym =
if result != nil: return
result = nil
when declared(echo):
proc debugScopes*(c: PContext; limit=0) {.deprecated.} =
var i = 0
for scope in walkScopes(c.currentScope):
echo "scope ", i
for h in 0 .. high(scope.symbols.data):
if scope.symbols.data[h] != nil:
echo scope.symbols.data[h].name.s
if i == limit: break
inc i
proc debugScopes*(c: PContext; limit=0) {.deprecated.} =
var i = 0
for scope in walkScopes(c.currentScope):
echo "scope ", i
for h in 0..high(scope.symbols.data):
if scope.symbols.data[h] != nil:
echo scope.symbols.data[h].name.s
if i == limit: break
inc i
proc searchInScopes*(c: PContext, s: PIdent, filter: TSymKinds): PSym =
for scope in walkScopes(c.currentScope):
@@ -124,7 +130,7 @@ proc errorSym*(c: PContext, n: PNode): PSym =
## creates an error symbol to avoid cascading errors (for IDE support)
var m = n
# ensure that 'considerQuotedIdent' can't fail:
if m.kind == nkDotExpr: m = m.sons[1]
if m.kind == nkDotExpr: m = m[1]
let ident = if m.kind in {nkIdent, nkSym, nkAccQuoted}:
considerQuotedIdent(c, m)
else:
@@ -232,6 +238,23 @@ proc addInterfaceOverloadableSymAt*(c: PContext, scope: PScope, sym: PSym) =
addOverloadableSymAt(c, scope, sym)
addInterfaceDeclAux(c, sym)
proc openShadowScope*(c: PContext) =
c.currentScope = PScope(parent: c.currentScope,
symbols: newStrTable(),
depthLevel: c.scopeDepth)
proc closeShadowScope*(c: PContext) =
c.closeScope
proc mergeShadowScope*(c: PContext) =
let shadowScope = c.currentScope
c.rawCloseScope
for sym in shadowScope.symbols:
if sym.kind in OverloadableSyms:
c.addInterfaceOverloadableSymAt(c.currentScope, sym)
else:
c.addInterfaceDecl(sym)
when defined(nimfix):
# when we cannot find the identifier, retry with a changed identifier:
proc altSpelling(x: PIdent): PIdent =
@@ -317,8 +340,7 @@ proc qualifiedLookUp*(c: PContext, n: PNode, flags: set[TLookupFlag]): PSym =
fixSpelling(n, ident, searchInScopes)
errorUndeclaredIdentifier(c, n.info, ident.s)
result = errorSym(c, n)
elif checkAmbiguity in flags and result != nil and
contains(c.ambiguousSymbols, result.id):
elif checkAmbiguity in flags and result != nil and result.id in c.ambiguousSymbols:
errorUseQualifier(c, n.info, result)
of nkSym:
result = n.sym
@@ -326,29 +348,29 @@ proc qualifiedLookUp*(c: PContext, n: PNode, flags: set[TLookupFlag]): PSym =
errorUseQualifier(c, n.info, n.sym)
of nkDotExpr:
result = nil
var m = qualifiedLookUp(c, n.sons[0], (flags*{checkUndeclared})+{checkModule})
var m = qualifiedLookUp(c, n[0], (flags*{checkUndeclared})+{checkModule})
if m != nil and m.kind == skModule:
var ident: PIdent = nil
if n.sons[1].kind == nkIdent:
ident = n.sons[1].ident
elif n.sons[1].kind == nkAccQuoted:
ident = considerQuotedIdent(c, n.sons[1])
if n[1].kind == nkIdent:
ident = n[1].ident
elif n[1].kind == nkAccQuoted:
ident = considerQuotedIdent(c, n[1])
if ident != nil:
if m == c.module:
result = strTableGet(c.topLevelScope.symbols, ident).skipAlias(n, c.config)
else:
result = strTableGet(m.tab, ident).skipAlias(n, c.config)
if result == nil and checkUndeclared in flags:
fixSpelling(n.sons[1], ident, searchInScopes)
errorUndeclaredIdentifier(c, n.sons[1].info, ident.s)
result = errorSym(c, n.sons[1])
elif n.sons[1].kind == nkSym:
result = n.sons[1].sym
fixSpelling(n[1], ident, searchInScopes)
errorUndeclaredIdentifier(c, n[1].info, ident.s)
result = errorSym(c, n[1])
elif n[1].kind == nkSym:
result = n[1].sym
elif checkUndeclared in flags and
n.sons[1].kind notin {nkOpenSymChoice, nkClosedSymChoice}:
localError(c.config, n.sons[1].info, "identifier expected, but got: " &
renderTree(n.sons[1]))
result = errorSym(c, n.sons[1])
n[1].kind notin {nkOpenSymChoice, nkClosedSymChoice}:
localError(c.config, n[1].info, "identifier expected, but got: " &
renderTree(n[1]))
result = errorSym(c, n[1])
else:
result = nil
when false:
@@ -372,13 +394,13 @@ proc initOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym =
o.mode = oimDone
of nkDotExpr:
o.mode = oimOtherModule
o.m = qualifiedLookUp(c, n.sons[0], {checkUndeclared, checkModule})
o.m = qualifiedLookUp(c, n[0], {checkUndeclared, checkModule})
if o.m != nil and o.m.kind == skModule:
var ident: PIdent = nil
if n.sons[1].kind == nkIdent:
ident = n.sons[1].ident
elif n.sons[1].kind == nkAccQuoted:
ident = considerQuotedIdent(c, n.sons[1], n)
if n[1].kind == nkIdent:
ident = n[1].ident
elif n[1].kind == nkAccQuoted:
ident = considerQuotedIdent(c, n[1], n)
if ident != nil:
if o.m == c.module:
# a module may access its private members:
@@ -388,12 +410,12 @@ proc initOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym =
else:
result = initIdentIter(o.it, o.m.tab, ident).skipAlias(n, c.config)
else:
noidentError(c.config, n.sons[1], n)
result = errorSym(c, n.sons[1])
noidentError(c.config, n[1], n)
result = errorSym(c, n[1])
of nkClosedSymChoice, nkOpenSymChoice:
o.mode = oimSymChoice
if n[0].kind == nkSym:
result = n.sons[0].sym
result = n[0].sym
else:
o.mode = oimDone
return nil
@@ -430,8 +452,8 @@ proc nextOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym =
of oimOtherModule:
result = nextIdentIter(o.it, o.m.tab).skipAlias(n, c.config)
of oimSymChoice:
if o.symChoiceIndex < len(n):
result = n.sons[o.symChoiceIndex].sym
if o.symChoiceIndex < n.len:
result = n[o.symChoiceIndex].sym
incl(o.inSymChoice, result.id)
inc o.symChoiceIndex
elif n.kind == nkOpenSymChoice:
@@ -439,19 +461,19 @@ proc nextOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym =
o.mode = oimSymChoiceLocalLookup
o.scope = c.currentScope
result = firstIdentExcluding(o.it, o.scope.symbols,
n.sons[0].sym.name, o.inSymChoice).skipAlias(n, c.config)
n[0].sym.name, o.inSymChoice).skipAlias(n, c.config)
while result == nil:
o.scope = o.scope.parent
if o.scope == nil: break
result = firstIdentExcluding(o.it, o.scope.symbols,
n.sons[0].sym.name, o.inSymChoice).skipAlias(n, c.config)
n[0].sym.name, o.inSymChoice).skipAlias(n, c.config)
of oimSymChoiceLocalLookup:
result = nextIdentExcluding(o.it, o.scope.symbols, o.inSymChoice).skipAlias(n, c.config)
while result == nil:
o.scope = o.scope.parent
if o.scope == nil: break
result = firstIdentExcluding(o.it, o.scope.symbols,
n.sons[0].sym.name, o.inSymChoice).skipAlias(n, c.config)
n[0].sym.name, o.inSymChoice).skipAlias(n, c.config)
when false:
if result != nil and result.kind == skStub: loadStub(result)

View File

@@ -16,41 +16,55 @@ import ast, astalgo, types, idents, magicsys, msgs, options, modulegraphs,
lineinfos
proc newDeref*(n: PNode): PNode {.inline.} =
result = newNodeIT(nkHiddenDeref, n.info, n.typ.sons[0])
addSon(result, n)
result = newNodeIT(nkHiddenDeref, n.info, n.typ[0])
result.add n
proc newTupleAccess*(g: ModuleGraph; tup: PNode, i: int): PNode =
if tup.kind == nkHiddenAddr:
result = newNodeIT(nkHiddenAddr, tup.info, tup.typ.skipTypes(abstractInst+{tyPtr, tyVar, tyLent}))
result.addSon(newNodeIT(nkBracketExpr, tup.info, tup.typ.skipTypes(abstractInst+{tyPtr, tyVar, tyLent}).sons[i]))
addSon(result[0], tup[0])
result.add newNodeIT(nkBracketExpr, tup.info, tup.typ.skipTypes(abstractInst+{tyPtr, tyVar, tyLent})[i])
result[0].add tup[0]
var lit = newNodeIT(nkIntLit, tup.info, getSysType(g, tup.info, tyInt))
lit.intVal = i
addSon(result[0], lit)
result[0].add lit
else:
result = newNodeIT(nkBracketExpr, tup.info, tup.typ.skipTypes(
abstractInst).sons[i])
addSon(result, copyTree(tup))
abstractInst)[i])
result.add copyTree(tup)
var lit = newNodeIT(nkIntLit, tup.info, getSysType(g, tup.info, tyInt))
lit.intVal = i
addSon(result, lit)
result.add lit
proc addVar*(father, v: PNode) =
var vpart = newNodeI(nkIdentDefs, v.info, 3)
vpart.sons[0] = v
vpart.sons[1] = newNodeI(nkEmpty, v.info)
vpart.sons[2] = vpart[1]
addSon(father, vpart)
vpart[0] = v
vpart[1] = newNodeI(nkEmpty, v.info)
vpart[2] = vpart[1]
father.add vpart
proc addVar*(father, v, value: PNode) =
var vpart = newNodeI(nkIdentDefs, v.info, 3)
vpart[0] = v
vpart[1] = newNodeI(nkEmpty, v.info)
vpart[2] = value
father.add vpart
proc newAsgnStmt*(le, ri: PNode): PNode =
result = newNodeI(nkAsgn, le.info, 2)
result.sons[0] = le
result.sons[1] = ri
result[0] = le
result[1] = ri
proc newFastAsgnStmt*(le, ri: PNode): PNode =
result = newNodeI(nkFastAsgn, le.info, 2)
result.sons[0] = le
result.sons[1] = ri
result[0] = le
result[1] = ri
proc newFastMoveStmt*(g: ModuleGraph, le, ri: PNode): PNode =
result = newNodeI(nkFastAsgn, le.info, 2)
result[0] = le
result[1] = newNodeIT(nkCall, ri.info, ri.typ)
result[1].add newSymNode(getSysMagic(g, ri.info, "move", mMove))
result[1].add ri
proc lowerTupleUnpacking*(g: ModuleGraph; n: PNode; owner: PSym): PNode =
assert n.kind == nkVarTuple
@@ -63,13 +77,13 @@ proc lowerTupleUnpacking*(g: ModuleGraph; n: PNode; owner: PSym): PNode =
var v = newNodeI(nkVarSection, value.info)
let tempAsNode = newSymNode(temp)
v.addVar(tempAsNode)
v.addVar(tempAsNode, value)
result.add(v)
result.add newAsgnStmt(tempAsNode, value)
for i in 0 .. n.len-3:
if n.sons[i].kind == nkSym: v.addVar(n.sons[i])
result.add newAsgnStmt(n.sons[i], newTupleAccess(g, tempAsNode, i))
for i in 0..<n.len-2:
let val = newTupleAccess(g, tempAsNode, i)
if n[i].kind == nkSym: v.addVar(n[i], val)
else: result.add newAsgnStmt(n[i], val)
proc evalOnce*(g: ModuleGraph; value: PNode; owner: PSym): PNode =
## Turns (value) into (let tmp = value; tmp) so that 'value' can be re-used
@@ -89,10 +103,10 @@ proc evalOnce*(g: ModuleGraph; value: PNode; owner: PSym): PNode =
proc newTupleAccessRaw*(tup: PNode, i: int): PNode =
result = newNodeI(nkBracketExpr, tup.info)
addSon(result, copyTree(tup))
result.add copyTree(tup)
var lit = newNodeI(nkIntLit, tup.info)
lit.intVal = i
addSon(result, lit)
result.add lit
proc newTryFinally*(body, final: PNode): PNode =
result = newTree(nkHiddenTryStmt, body, newTree(nkFinally, final))
@@ -106,31 +120,32 @@ proc lowerTupleUnpackingForAsgn*(g: ModuleGraph; n: PNode; owner: PSym): PNode =
let tempAsNode = newSymNode(temp) #newIdentNode(getIdent(genPrefix & $temp.id), value.info)
var vpart = newNodeI(nkIdentDefs, tempAsNode.info, 3)
vpart.sons[0] = tempAsNode
vpart.sons[1] = newNodeI(nkEmpty, value.info)
vpart.sons[2] = value
addSon(v, vpart)
vpart[0] = tempAsNode
vpart[1] = newNodeI(nkEmpty, value.info)
vpart[2] = value
v.add vpart
result.add(v)
let lhs = n.sons[0]
for i in 0 .. lhs.len-1:
result.add newAsgnStmt(lhs.sons[i], newTupleAccessRaw(tempAsNode, i))
let lhs = n[0]
for i in 0..<lhs.len:
result.add newAsgnStmt(lhs[i], newTupleAccessRaw(tempAsNode, i))
proc lowerSwap*(g: ModuleGraph; n: PNode; owner: PSym): PNode =
result = newNodeI(nkStmtList, n.info)
# note: cannot use 'skTemp' here cause we really need the copy for the VM :-(
var temp = newSym(skVar, getIdent(g.cache, genPrefix), owner, n.info, owner.options)
temp.typ = n.sons[1].typ
temp.typ = n[1].typ
incl(temp.flags, sfFromGeneric)
incl(temp.flags, sfGenSym)
var v = newNodeI(nkVarSection, n.info)
let tempAsNode = newSymNode(temp)
var vpart = newNodeI(nkIdentDefs, v.info, 3)
vpart.sons[0] = tempAsNode
vpart.sons[1] = newNodeI(nkEmpty, v.info)
vpart.sons[2] = n[1]
addSon(v, vpart)
vpart[0] = tempAsNode
vpart[1] = newNodeI(nkEmpty, v.info)
vpart[2] = n[1]
v.add vpart
result.add(v)
result.add newFastAsgnStmt(n[1], n[2])
@@ -144,52 +159,59 @@ proc createObj*(g: ModuleGraph; owner: PSym, info: TLineInfo; final=true): PType
else:
rawAddSon(result, getCompilerProc(g, "RootObj").typ)
result.n = newNodeI(nkRecList, info)
let s = newSym(skType, getIdent(g.cache, "Env_" & toFilename(g.config, info)),
let s = newSym(skType, getIdent(g.cache, "Env_" & toFilename(g.config, info) & "_" & $owner.name.s),
owner, info, owner.options)
incl s.flags, sfAnon
s.typ = result
result.sym = s
template fieldCheck {.dirty.} =
when false:
if tfCheckedForDestructor in obj.flags:
echo "missed field ", field.name.s
writeStackTrace()
proc rawAddField*(obj: PType; field: PSym) =
assert field.kind == skField
field.position = len(obj.n)
addSon(obj.n, newSymNode(field))
field.position = obj.n.len
obj.n.add newSymNode(field)
propagateToOwner(obj, field.typ)
fieldCheck()
proc rawIndirectAccess*(a: PNode; field: PSym; info: TLineInfo): PNode =
# returns a[].field as a node
assert field.kind == skField
var deref = newNodeI(nkHiddenDeref, info)
deref.typ = a.typ.skipTypes(abstractInst).sons[0]
addSon(deref, a)
deref.typ = a.typ.skipTypes(abstractInst)[0]
deref.add a
result = newNodeI(nkDotExpr, info)
addSon(result, deref)
addSon(result, newSymNode(field))
result.add deref
result.add newSymNode(field)
result.typ = field.typ
proc rawDirectAccess*(obj, field: PSym): PNode =
# returns a.field as a node
assert field.kind == skField
result = newNodeI(nkDotExpr, field.info)
addSon(result, newSymNode obj)
addSon(result, newSymNode field)
result.add newSymNode(obj)
result.add newSymNode(field)
result.typ = field.typ
proc lookupInRecord(n: PNode, id: int): PSym =
result = nil
case n.kind
of nkRecList:
for i in 0 ..< len(n):
result = lookupInRecord(n.sons[i], id)
for i in 0..<n.len:
result = lookupInRecord(n[i], id)
if result != nil: return
of nkRecCase:
if n.sons[0].kind != nkSym: return
result = lookupInRecord(n.sons[0], id)
if n[0].kind != nkSym: return
result = lookupInRecord(n[0], id)
if result != nil: return
for i in 1 ..< len(n):
case n.sons[i].kind
for i in 1..<n.len:
case n[i].kind
of nkOfBranch, nkElse:
result = lookupInRecord(lastSon(n.sons[i]), id)
result = lookupInRecord(lastSon(n[i]), id)
if result != nil: return
else: discard
of nkSym:
@@ -206,8 +228,10 @@ proc addField*(obj: PType; s: PSym; cache: IdentCache) =
field.typ = t
assert t.kind != tyTyped
propagateToOwner(obj, t)
field.position = len(obj.n)
addSon(obj.n, newSymNode(field))
field.position = obj.n.len
field.flags = s.flags * {sfCursor}
obj.n.add newSymNode(field)
fieldCheck()
proc addUniqueField*(obj: PType; s: PSym; cache: IdentCache): PSym {.discardable.} =
result = lookupInRecord(obj.n, s.id)
@@ -219,45 +243,45 @@ proc addUniqueField*(obj: PType; s: PSym; cache: IdentCache): PSym {.discardable
field.typ = t
assert t.kind != tyTyped
propagateToOwner(obj, t)
field.position = len(obj.n)
addSon(obj.n, newSymNode(field))
field.position = obj.n.len
obj.n.add newSymNode(field)
result = field
proc newDotExpr*(obj, b: PSym): PNode =
result = newNodeI(nkDotExpr, obj.info)
let field = lookupInRecord(obj.typ.n, b.id)
assert field != nil, b.name.s
addSon(result, newSymNode(obj))
addSon(result, newSymNode(field))
result.add newSymNode(obj)
result.add newSymNode(field)
result.typ = field.typ
proc indirectAccess*(a: PNode, b: int, info: TLineInfo): PNode =
# returns a[].b as a node
var deref = newNodeI(nkHiddenDeref, info)
deref.typ = a.typ.skipTypes(abstractInst).sons[0]
deref.typ = a.typ.skipTypes(abstractInst)[0]
var t = deref.typ.skipTypes(abstractInst)
var field: PSym
while true:
assert t.kind == tyObject
field = lookupInRecord(t.n, b)
if field != nil: break
t = t.sons[0]
t = t[0]
if t == nil: break
t = t.skipTypes(skipPtrs)
#if field == nil:
# echo "FIELD ", b
# debug deref.typ
assert field != nil
addSon(deref, a)
deref.add a
result = newNodeI(nkDotExpr, info)
addSon(result, deref)
addSon(result, newSymNode(field))
result.add deref
result.add newSymNode(field)
result.typ = field.typ
proc indirectAccess*(a: PNode, b: string, info: TLineInfo; cache: IdentCache): PNode =
# returns a[].b as a node
var deref = newNodeI(nkHiddenDeref, info)
deref.typ = a.typ.skipTypes(abstractInst).sons[0]
deref.typ = a.typ.skipTypes(abstractInst)[0]
var t = deref.typ.skipTypes(abstractInst)
var field: PSym
let bb = getIdent(cache, b)
@@ -265,17 +289,17 @@ proc indirectAccess*(a: PNode, b: string, info: TLineInfo; cache: IdentCache): P
assert t.kind == tyObject
field = getSymFromList(t.n, bb)
if field != nil: break
t = t.sons[0]
t = t[0]
if t == nil: break
t = t.skipTypes(skipPtrs)
#if field == nil:
# echo "FIELD ", b
# debug deref.typ
assert field != nil
addSon(deref, a)
deref.add a
result = newNodeI(nkDotExpr, info)
addSon(result, deref)
addSon(result, newSymNode(field))
result.add deref
result.add newSymNode(field)
result.typ = field.typ
proc getFieldFromObj*(t: PType; v: PSym): PSym =
@@ -285,7 +309,7 @@ proc getFieldFromObj*(t: PType; v: PSym): PSym =
assert t.kind == tyObject
result = lookupInRecord(t.n, v.id)
if result != nil: break
t = t.sons[0]
t = t[0]
if t == nil: break
t = t.skipTypes(skipPtrs)
@@ -296,19 +320,19 @@ proc indirectAccess*(a: PNode, b: PSym, info: TLineInfo): PNode =
proc indirectAccess*(a, b: PSym, info: TLineInfo): PNode =
result = indirectAccess(newSymNode(a), b, info)
proc genAddrOf*(n: PNode): PNode =
proc genAddrOf*(n: PNode, typeKind = tyPtr): PNode =
result = newNodeI(nkAddr, n.info, 1)
result.sons[0] = n
result.typ = newType(tyPtr, n.typ.owner)
result[0] = n
result.typ = newType(typeKind, n.typ.owner)
result.typ.rawAddSon(n.typ)
proc genDeref*(n: PNode; k = nkHiddenDeref): PNode =
result = newNodeIT(k, n.info,
n.typ.skipTypes(abstractInst).sons[0])
n.typ.skipTypes(abstractInst)[0])
result.add n
proc callCodegenProc*(g: ModuleGraph; name: string;
info: TLineInfo = unknownLineInfo();
info: TLineInfo = unknownLineInfo;
arg1, arg2, arg3, optionalArgs: PNode = nil): PNode =
result = newNodeI(nkCall, info)
let sym = magicsys.getCompilerProc(g, name)
@@ -320,9 +344,9 @@ proc callCodegenProc*(g: ModuleGraph; name: string;
if arg2 != nil: result.add arg2
if arg3 != nil: result.add arg3
if optionalArgs != nil:
for i in 1..optionalArgs.len-3:
for i in 1..<optionalArgs.len-2:
result.add optionalArgs[i]
result.typ = sym.typ.sons[0]
result.typ = sym.typ[0]
proc newIntLit*(g: ModuleGraph; info: TLineInfo; value: BiggestInt): PNode =
result = nkIntLit.newIntNode(value)
@@ -334,8 +358,8 @@ proc genHigh*(g: ModuleGraph; n: PNode): PNode =
else:
result = newNodeI(nkCall, n.info, 2)
result.typ = getSysType(g, n.info, tyInt)
result.sons[0] = newSymNode(getSysMagic(g, n.info, "high", mHigh))
result.sons[1] = n
result[0] = newSymNode(getSysMagic(g, n.info, "high", mHigh))
result[1] = n
proc genLen*(g: ModuleGraph; n: PNode): PNode =
if skipTypes(n.typ, abstractVar).kind == tyArray:
@@ -343,17 +367,6 @@ proc genLen*(g: ModuleGraph; n: PNode): PNode =
else:
result = newNodeI(nkCall, n.info, 2)
result.typ = getSysType(g, n.info, tyInt)
result.sons[0] = newSymNode(getSysMagic(g, n.info, "len", mLengthSeq))
result.sons[1] = n
result[0] = newSymNode(getSysMagic(g, n.info, "len", mLengthSeq))
result[1] = n
proc hoistExpr*(varSection, expr: PNode, name: PIdent, owner: PSym): PSym =
result = newSym(skLet, name, owner, varSection.info, owner.options)
result.flags.incl sfHoisted
result.typ = expr.typ
var varDef = newNodeI(nkIdentDefs, varSection.info, 3)
varDef.sons[0] = newSymNode(result)
varDef.sons[1] = newNodeI(nkEmpty, varSection.info)
varDef.sons[2] = expr
varSection.add varDef

View File

@@ -40,7 +40,7 @@ proc getSysMagic*(g: ModuleGraph; info: TLineInfo; name: string, m: TMagic): PSy
while r != nil:
if r.magic == m:
# prefer the tyInt variant:
if r.typ.sons[0] != nil and r.typ.sons[0].kind == tyInt: return r
if r.typ[0] != nil and r.typ[0].kind == tyInt: return r
result = r
r = nextIdentIter(ti, g.systemModule.tab)
if result != nil: return result
@@ -68,7 +68,7 @@ proc getSysType*(g: ModuleGraph; info: TLineInfo; kind: TTypeKind): PType =
of tyUInt64: result = sysTypeFromName("uint64")
of tyFloat: result = sysTypeFromName("float")
of tyFloat32: result = sysTypeFromName("float32")
of tyFloat64: return sysTypeFromName("float64")
of tyFloat64: result = sysTypeFromName("float64")
of tyFloat128: result = sysTypeFromName("float128")
of tyBool: result = sysTypeFromName("bool")
of tyChar: result = sysTypeFromName("char")
@@ -79,7 +79,9 @@ proc getSysType*(g: ModuleGraph; info: TLineInfo; kind: TTypeKind): PType =
else: internalError(g.config, "request for typekind: " & $kind)
g.sysTypes[kind] = result
if result.kind != kind:
internalError(g.config, "wanted: " & $kind & " got: " & $result.kind)
if kind == tyFloat64 and result.kind == tyFloat: discard # because of aliasing
else:
internalError(g.config, "wanted: " & $kind & " got: " & $result.kind)
if result == nil: internalError(g.config, "type not found: " & $kind)
proc resetSysTypes*(g: ModuleGraph) =
@@ -123,7 +125,7 @@ proc addSonSkipIntLit*(father, son: PType) =
when not defined(nimNoNilSeqs):
if isNil(father.sons): father.sons = @[]
let s = son.skipIntLit
add(father.sons, s)
father.sons.add(s)
propagateToOwner(father, s)
proc setIntLitType*(g: ModuleGraph; result: PNode) =
@@ -175,3 +177,28 @@ proc getNimScriptSymbol*(g: ModuleGraph; name: string): PSym =
strTableGet(g.exposed, getIdent(g.cache, name))
proc resetNimScriptSymbols*(g: ModuleGraph) = initStrTable(g.exposed)
proc getMagicEqSymForType*(g: ModuleGraph; t: PType; info: TLineInfo): PSym =
case t.kind
of tyInt, tyInt8, tyInt16, tyInt32, tyInt64,
tyUInt, tyUInt8, tyUInt16, tyUInt32, tyUInt64:
result = getSysMagic(g, info, "==", mEqI)
of tyEnum:
result = getSysMagic(g, info, "==", mEqEnum)
of tyBool:
result = getSysMagic(g, info, "==", mEqB)
of tyRef, tyPtr, tyPointer:
result = getSysMagic(g, info, "==", mEqRef)
of tyString:
result = getSysMagic(g, info, "==", mEqStr)
of tyChar:
result = getSysMagic(g, info, "==", mEqCh)
of tySet:
result = getSysMagic(g, info, "==", mEqSet)
of tyProc:
result = getSysMagic(g, info, "==", mEqProc)
else:
globalError(g.config, info,
"can't find magic equals operator for type kind " & $t.kind)

View File

@@ -13,13 +13,13 @@ when not defined(nimcore):
{.error: "nimcore MUST be defined for Nim's core tooling".}
import
llstream, strutils, ast, lexer, syntaxes, options, msgs,
llstream, strutils, os, ast, lexer, syntaxes, options, msgs,
condsyms, times,
sem, idents, passes, extccomp,
cgen, json, nversion,
platform, nimconf, passaux, depends, vm, idgen,
modules,
modulegraphs, tables, rod, lineinfos, pathutils
modulegraphs, tables, rod, lineinfos, pathutils, vmprofiler
when not defined(leanCompiler):
import jsgen, docgen, docgen2
@@ -51,7 +51,7 @@ proc commandGenDepend(graph: ModuleGraph) =
' ' & changeFileExt(project, "dot").string)
proc commandCheck(graph: ModuleGraph) =
graph.config.errorMax = high(int) # do not stop after first error
graph.config.setErrorMaxHighMaybe
defineSymbol(graph.config.symbols, "nimcheck")
semanticPasses(graph) # use an empty backend for semantic checking only
compileProject(graph)
@@ -59,7 +59,7 @@ proc commandCheck(graph: ModuleGraph) =
when not defined(leanCompiler):
proc commandDoc2(graph: ModuleGraph; json: bool) =
handleDocOutputOptions graph.config
graph.config.errorMax = high(int) # do not stop after first error
graph.config.setErrorMaxHighMaybe
semanticPasses(graph)
if json: registerPass(graph, docgen2JsonPass)
else: registerPass(graph, docgen2Pass)
@@ -68,16 +68,7 @@ when not defined(leanCompiler):
proc commandCompileToC(graph: ModuleGraph) =
let conf = graph.config
if conf.outDir.isEmpty:
conf.outDir = conf.projectPath
if conf.outFile.isEmpty:
let targetName = if optGenDynLib in conf.globalOptions:
platform.OS[conf.target.targetOS].dllFrmt % conf.projectName
else:
conf.projectName & platform.OS[conf.target.targetOS].exeExt
conf.outFile = RelativeFile targetName
setOutFile(conf)
extccomp.initVars(conf)
semanticPasses(graph)
registerPass(graph, cgenPass)
@@ -89,6 +80,9 @@ proc commandCompileToC(graph: ModuleGraph) =
graph.config.notes = graph.config.mainPackageNotes
return
if not extccomp.ccHasSaneOverflow(conf):
conf.symbols.defineSymbol("nimEmulateOverflowChecks")
compileProject(graph)
if graph.config.errorCounter > 0:
return # issue #9933
@@ -105,12 +99,13 @@ proc commandJsonScript(graph: ModuleGraph) =
let proj = changeFileExt(graph.config.projectFull, "")
extccomp.runJsonBuildInstructions(graph.config, proj)
when not defined(leanCompiler):
proc commandCompileToJS(graph: ModuleGraph) =
proc commandCompileToJS(graph: ModuleGraph) =
when defined(leanCompiler):
globalError(graph.config, unknownLineInfo, "compiler wasn't built with JS code generator")
else:
let conf = graph.config
conf.exc = excCpp
if conf.outDir.isEmpty:
conf.outDir = conf.projectPath
if conf.outFile.isEmpty:
conf.outFile = RelativeFile(conf.projectName & ".js")
@@ -118,7 +113,6 @@ when not defined(leanCompiler):
setTarget(graph.config.target, osJS, cpuJS)
#initDefines()
defineSymbol(graph.config.symbols, "ecmascript") # For backward compatibility
defineSymbol(graph.config.symbols, "js")
semanticPasses(graph)
registerPass(graph, JSgenPass)
compileProject(graph)
@@ -135,7 +129,7 @@ proc interactivePasses(graph: ModuleGraph) =
registerPass(graph, evalPass)
proc commandInteractive(graph: ModuleGraph) =
graph.config.errorMax = high(int) # do not stop after first error
graph.config.setErrorMaxHighMaybe
interactivePasses(graph)
compileSystemModule(graph)
if graph.config.commandArgs.len > 0:
@@ -155,8 +149,8 @@ proc commandScan(cache: IdentCache, config: ConfigRef) =
var stream = llStreamOpen(f, fmRead)
if stream != nil:
var
L: TLexer
tok: TToken
L: Lexer
tok: Token
initToken(tok)
openLexer(L, f, stream, cache, config)
while true:
@@ -180,56 +174,105 @@ proc mainCommand*(graph: ModuleGraph) =
conf.lastCmdTime = epochTime()
conf.searchPaths.add(conf.libpath)
setId(100)
case conf.command.normalize
of "c", "cc", "compile", "compiletoc":
# compile means compileToC currently
conf.cmd = cmdCompileToC
defineSymbol(graph.config.symbols, "c")
commandCompileToC(graph)
of "cpp", "compiletocpp":
conf.cmd = cmdCompileToCpp
defineSymbol(graph.config.symbols, "cpp")
commandCompileToC(graph)
of "objc", "compiletooc":
conf.cmd = cmdCompileToOC
defineSymbol(graph.config.symbols, "objc")
commandCompileToC(graph)
of "run":
conf.cmd = cmdRun
when hasTinyCBackend:
extccomp.setCC("tcc")
commandCompileToC(graph)
else:
rawMessage(conf, errGenerated, "'run' command not available; rebuild with -d:tinyc")
of "js", "compiletojs":
when defined(leanCompiler):
quit "compiler wasn't built with JS code generator"
else:
conf.cmd = cmdCompileToJS
proc customizeForBackend(backend: TBackend) =
## Sets backend specific options but don't compile to backend yet in
## case command doesn't require it. This must be called by all commands.
if conf.backend == backendInvalid:
# only set if wasn't already set, to allow override via `nim c -b:cpp`
conf.backend = backend
defineSymbol(graph.config.symbols, $conf.backend)
case conf.backend
of backendC:
if conf.exc == excNone: conf.exc = excSetjmp
of backendCpp:
if conf.exc == excNone: conf.exc = excCpp
of backendObjc: discard
of backendJs:
if conf.hcrOn:
# XXX: At the moment, system.nim cannot be compiled in JS mode
# with "-d:useNimRtl". The HCR option has been processed earlier
# and it has added this define implictly, so we must undo that here.
# A better solution might be to fix system.nim
undefSymbol(conf.symbols, "useNimRtl")
commandCompileToJS(graph)
of "doc0":
of backendInvalid: doAssert false
if conf.selectedGC in {gcArc, gcOrc} and conf.backend != backendCpp:
conf.exc = excGoto
var commandAlreadyProcessed = false
proc compileToBackend(backend: TBackend, cmd = cmdCompileToBackend) =
commandAlreadyProcessed = true
conf.cmd = cmd
customizeForBackend(backend)
case conf.backend
of backendC: commandCompileToC(graph)
of backendCpp: commandCompileToC(graph)
of backendObjc: commandCompileToC(graph)
of backendJs: commandCompileToJS(graph)
of backendInvalid: doAssert false
template docLikeCmd(body) =
when defined(leanCompiler):
quit "compiler wasn't built with documentation generator"
else:
wantMainModule(conf)
conf.cmd = cmdDoc
loadConfigs(DocConfig, cache, conf)
commandDoc(cache, conf)
of "doc2", "doc":
when defined(leanCompiler):
quit "compiler wasn't built with documentation generator"
else:
conf.cmd = cmdDoc
loadConfigs(DocConfig, cache, conf)
defineSymbol(conf.symbols, "nimdoc")
body
block: ## command prepass
var docLikeCmd2 = false # includes what calls `docLikeCmd` + some more
case conf.command.normalize
of "r": conf.globalOptions.incl {optRun, optUseNimcache}
of "doc0", "doc2", "doc", "rst2html", "rst2tex", "jsondoc0", "jsondoc2",
"jsondoc", "ctags", "buildindex": docLikeCmd2 = true
else: discard
if conf.outDir.isEmpty:
# doc like commands can generate a lot of files (especially with --project)
# so by default should not end up in $PWD nor in $projectPath.
conf.outDir = block:
var ret = if optUseNimcache in conf.globalOptions: getNimcacheDir(conf)
else: conf.projectPath
doAssert ret.string.isAbsolute # `AbsoluteDir` is not a real guarantee
if docLikeCmd2: ret = ret / htmldocsDir
ret
## process all backend commands
case conf.command.normalize
of "c", "cc", "compile", "compiletoc": compileToBackend(backendC) # compile means compileToC currently
of "cpp", "compiletocpp": compileToBackend(backendCpp)
of "objc", "compiletooc": compileToBackend(backendObjc)
of "js", "compiletojs": compileToBackend(backendJs)
of "r": compileToBackend(backendC) # different from `"run"`!
of "run":
when hasTinyCBackend:
extccomp.setCC(conf, "tcc", unknownLineInfo)
if conf.backend notin {backendC, backendInvalid}:
rawMessage(conf, errGenerated, "'run' requires c backend, got: '$1'" % $conf.backend)
compileToBackend(backendC, cmd = cmdRun)
else:
rawMessage(conf, errGenerated, "'run' command not available; rebuild with -d:tinyc")
else: customizeForBackend(backendC) # fallback for other commands
## process all other commands
case conf.command.normalize # synchronize with `cmdUsingHtmlDocs`
of "doc0": docLikeCmd commandDoc(cache, conf)
of "doc2", "doc":
docLikeCmd():
conf.setNoteDefaults(warnLockLevel, false) # issue #13218
conf.setNoteDefaults(warnRedefinitionOfLabel, false) # issue #13218
# because currently generates lots of false positives due to conflation
# of labels links in doc comments, e.g. for random.rand:
# ## * `rand proc<#rand,Rand,Natural>`_ that returns an integer
# ## * `rand proc<#rand,Rand,range[]>`_ that returns a float
commandDoc2(graph, false)
if optGenIndex in conf.globalOptions and optWholeProject in conf.globalOptions:
commandBuildIndex(conf, $conf.outDir)
of "rst2html":
conf.setNoteDefaults(warnRedefinitionOfLabel, false) # similar to issue #13218
when defined(leanCompiler):
quit "compiler wasn't built with documentation generator"
else:
@@ -243,41 +286,10 @@ proc mainCommand*(graph: ModuleGraph) =
conf.cmd = cmdRst2tex
loadConfigs(DocTexConfig, cache, conf)
commandRst2TeX(cache, conf)
of "jsondoc0":
when defined(leanCompiler):
quit "compiler wasn't built with documentation generator"
else:
wantMainModule(conf)
conf.cmd = cmdDoc
loadConfigs(DocConfig, cache, conf)
wantMainModule(conf)
defineSymbol(conf.symbols, "nimdoc")
commandJson(cache, conf)
of "jsondoc2", "jsondoc":
when defined(leanCompiler):
quit "compiler wasn't built with documentation generator"
else:
conf.cmd = cmdDoc
loadConfigs(DocConfig, cache, conf)
wantMainModule(conf)
defineSymbol(conf.symbols, "nimdoc")
commandDoc2(graph, true)
of "ctags":
when defined(leanCompiler):
quit "compiler wasn't built with documentation generator"
else:
wantMainModule(conf)
conf.cmd = cmdDoc
loadConfigs(DocConfig, cache, conf)
defineSymbol(conf.symbols, "nimdoc")
commandTags(cache, conf)
of "buildindex":
when defined(leanCompiler):
quit "compiler wasn't built with documentation generator"
else:
conf.cmd = cmdDoc
loadConfigs(DocConfig, cache, conf)
commandBuildIndex(cache, conf)
of "jsondoc0": docLikeCmd commandJson(cache, conf)
of "jsondoc2", "jsondoc": docLikeCmd commandDoc2(graph, true)
of "ctags": docLikeCmd commandTags(cache, conf)
of "buildindex": docLikeCmd commandBuildIndex(conf, $conf.projectFull, conf.outFile)
of "gendepend":
conf.cmd = cmdGenDepend
commandGenDepend(graph)
@@ -290,22 +302,26 @@ proc mainCommand*(graph: ModuleGraph) =
for s in definedSymbolNames(conf.symbols): definedSymbols.elems.add(%s)
var libpaths = newJArray()
var lazyPaths = newJArray()
for dir in conf.searchPaths: libpaths.elems.add(%dir.string)
for dir in conf.lazyPaths: lazyPaths.elems.add(%dir.string)
var hints = newJObject() # consider factoring with `listHints`
for a in hintMin..hintMax:
let key = lineinfos.HintsToStr[ord(a) - ord(hintMin)]
hints[key] = %(a in conf.notes)
hints[$a] = %(a in conf.notes)
var warnings = newJObject()
for a in warnMin..warnMax:
let key = lineinfos.WarningsToStr[ord(a) - ord(warnMin)]
warnings[key] = %(a in conf.notes)
warnings[$a] = %(a in conf.notes)
var dumpdata = %[
(key: "version", val: %VersionAsString),
(key: "nimExe", val: %(getAppFilename())),
(key: "prefixdir", val: %conf.getPrefixDir().string),
(key: "libpath", val: %conf.libpath.string),
(key: "project_path", val: %conf.projectFull.string),
(key: "defined_symbols", val: definedSymbols),
(key: "lib_paths", val: %libpaths),
(key: "lazyPaths", val: %lazyPaths),
(key: "outdir", val: %conf.outDir.string),
(key: "out", val: %conf.outFile.string),
(key: "nimcache", val: %getNimcacheDir(conf).string),
@@ -347,22 +363,43 @@ proc mainCommand*(graph: ModuleGraph) =
conf.cmd = cmdDump
of "jsonscript":
conf.cmd = cmdJsonScript
setOutFile(graph.config)
commandJsonScript(graph)
elif commandAlreadyProcessed: discard # already handled
else:
rawMessage(conf, errGenerated, "invalid command: " & conf.command)
if conf.errorCounter == 0 and
conf.cmd notin {cmdInterpret, cmdRun, cmdDump}:
when declared(system.getMaxMem):
let usedMem = formatSize(getMaxMem()) & " peakmem"
let mem =
when declared(system.getMaxMem): formatSize(getMaxMem()) & " peakmem"
else: formatSize(getTotalMem()) & " totmem"
let loc = $conf.linesCompiled
let build = if isDefined(conf, "danger"): "Dangerous Release"
elif isDefined(conf, "release"): "Release"
else: "Debug"
let sec = formatFloat(epochTime() - conf.lastCmdTime, ffDecimal, 3)
let project = if optListFullPaths in conf.globalOptions: $conf.projectFull else: $conf.projectName
var output: string
if optCompileOnly in conf.globalOptions and conf.cmd != cmdJsonScript:
output = $conf.jsonBuildFile
elif conf.outFile.isEmpty and conf.cmd notin {cmdJsonScript, cmdCompileToBackend, cmdDoc}:
# for some cmd we expect a valid absOutFile
output = "unknownOutput"
else:
let usedMem = formatSize(getTotalMem())
rawMessage(conf, hintSuccessX, [$conf.linesCompiled,
formatFloat(epochTime() - conf.lastCmdTime, ffDecimal, 3),
usedMem,
if isDefined(conf, "danger"): "Dangerous Release Build"
elif isDefined(conf, "release"): "Release Build"
else: "Debug Build"])
output = $conf.absOutFile
if optListFullPaths notin conf.globalOptions: output = output.AbsoluteFile.extractFilename
if optProfileVM in conf.globalOptions:
echo conf.dump(conf.vmProfileData)
rawMessage(conf, hintSuccessX, [
"loc", loc,
"sec", sec,
"mem", mem,
"build", build,
"project", project,
"output", output,
])
when PrintRopeCacheStats:
echo "rope cache stats: "
@@ -371,5 +408,3 @@ proc mainCommand*(graph: ModuleGraph) =
echo " int tries: ", gCacheIntTries
echo " efficiency: ", formatFloat(1-(gCacheMisses.float/gCacheTries.float),
ffDecimal, 3)
resetAttributes(conf)

View File

@@ -31,7 +31,7 @@ import ast, intsets, tables, options, lineinfos, hashes, idents,
type
SigHash* = distinct MD5Digest
ModuleGraph* = ref object
ModuleGraph* {.acyclic.} = ref object
modules*: seq[PSym] ## indexed by int32 fileIdx
packageSyms*: TStrTable
deps*: IntSet # the dependency graph or potentially its transitive closure.
@@ -72,6 +72,8 @@ type
onDefinitionResolveForward*: proc (graph: ModuleGraph; s: PSym; info: TLineInfo) {.nimcall.}
onUsage*: proc (graph: ModuleGraph; s: PSym; info: TLineInfo) {.nimcall.}
globalDestructors*: seq[PNode]
strongSemCheck*: proc (graph: ModuleGraph; owner: PSym; body: PNode) {.nimcall.}
compatibleProps*: proc (graph: ModuleGraph; formal, actual: PType): bool {.nimcall.}
TPassContext* = object of RootObj # the pass's context
PPassContext* = ref TPassContext
@@ -163,8 +165,9 @@ proc stopCompile*(g: ModuleGraph): bool {.inline.} =
result = g.doStopCompile != nil and g.doStopCompile()
proc createMagic*(g: ModuleGraph; name: string, m: TMagic): PSym =
result = newSym(skProc, getIdent(g.cache, name), nil, unknownLineInfo(), {})
result = newSym(skProc, getIdent(g.cache, name), nil, unknownLineInfo, {})
result.magic = m
result.flags = {sfNeverRaises}
proc newModuleGraph*(cache: IdentCache; config: ConfigRef): ModuleGraph =
result = ModuleGraph()

View File

@@ -91,8 +91,7 @@ when false:
if result.len > 0: return result
proc scriptableImport(pkg, sub: string; info: TLineInfo): string =
result = resolveDollar(gProjectFull, info.toFullPath(), pkg, sub, info)
if result.isNil: result = ""
resolveDollar(gProjectFull, info.toFullPath(), pkg, sub, info)
proc lookupPackage(pkg, subdir: PNode): string =
let sub = if subdir != nil: renderTree(subdir, {renderNoComments}).replace(" ") else: ""
@@ -112,8 +111,7 @@ proc getModuleName*(conf: ConfigRef; n: PNode): string =
case n.kind
of nkStrLit, nkRStrLit, nkTripleStrLit:
try:
result =
pathSubs(conf, n.strVal, toFullPath(conf, n.info).splitFile().dir)
result = pathSubs(conf, n.strVal, toFullPath(conf, n.info).splitFile().dir)
except ValueError:
localError(conf, n.info, "invalid path: " & n.strVal)
result = n.strVal
@@ -139,7 +137,7 @@ proc getModuleName*(conf: ConfigRef; n: PNode): string =
result.add modname
of nkPrefix:
when false:
if n.sons[0].kind == nkIdent and n.sons[0].ident.s == "$":
if n[0].kind == nkIdent and n[0].ident.s == "$":
result = lookupPackage(n[1], nil)
else:
discard
@@ -149,7 +147,7 @@ proc getModuleName*(conf: ConfigRef; n: PNode): string =
localError(conf, n.info, warnDeprecated, "using '.' instead of '/' in import paths is deprecated")
result = renderTree(n, {renderNoComments}).replace(".", "/")
of nkImportAs:
result = getModuleName(conf, n.sons[0])
result = getModuleName(conf, n[0])
else:
localError(conf, n.info, "invalid module name: '$1'" % n.renderTree)
result = ""

View File

@@ -17,32 +17,43 @@ import
proc resetSystemArtifacts*(g: ModuleGraph) =
magicsys.resetSysTypes(g)
proc partialInitModule(result: PSym; graph: ModuleGraph; fileIdx: FileIndex; filename: AbsoluteFile) =
template getModuleIdent(graph: ModuleGraph, filename: AbsoluteFile): PIdent =
getIdent(graph.cache, splitFile(filename).name)
proc getPackage(graph: ModuleGraph; fileIdx: FileIndex): PSym =
## returns package symbol (skPackage) for yet to be defined module for fileIdx
let filename = AbsoluteFile toFullPath(graph.config, fileIdx)
let name = getModuleIdent(graph, filename)
let info = newLineInfo(fileIdx, 1, 1)
let
pck = getPackageName(graph.config, filename.string)
pck2 = if pck.len > 0: pck else: "unknown"
pack = getIdent(graph.cache, pck2)
var packSym = graph.packageSyms.strTableGet(pack)
if packSym == nil:
packSym = newSym(skPackage, getIdent(graph.cache, pck2), nil, result.info)
packSym = newSym(skPackage, getIdent(graph.cache, pck2), nil, info)
initStrTable(packSym.tab)
graph.packageSyms.strTableAdd(packSym)
else:
let existing = strTableGet(packSym.tab, result.name)
if existing != nil and existing.info.fileIndex != result.info.fileIndex:
let existing = strTableGet(packSym.tab, name)
if existing != nil and existing.info.fileIndex != info.fileIndex:
when false:
# we used to produce an error:
localError(graph.config, result.info,
localError(graph.config, info,
"module names need to be unique per Nimble package; module clashes with " &
toFullPath(graph.config, existing.info.fileIndex))
else:
# but starting with version 0.20 we now produce a fake Nimble package instead
# to resolve the conflicts:
let pck3 = fakePackageName(graph.config, filename)
packSym = newSym(skPackage, getIdent(graph.cache, pck3), nil, result.info)
# this makes the new `packSym`'s owner be the original `packSym`
packSym = newSym(skPackage, getIdent(graph.cache, pck3), packSym, info)
initStrTable(packSym.tab)
graph.packageSyms.strTableAdd(packSym)
result = packSym
proc partialInitModule(result: PSym; graph: ModuleGraph; fileIdx: FileIndex; filename: AbsoluteFile) =
let packSym = getPackage(graph, fileIdx)
result.owner = packSym
result.position = int fileIdx
@@ -55,19 +66,19 @@ proc partialInitModule(result: PSym; graph: ModuleGraph; fileIdx: FileIndex; fil
strTableAdd(packSym.tab, result)
proc newModule(graph: ModuleGraph; fileIdx: FileIndex): PSym =
let filename = AbsoluteFile toFullPath(graph.config, fileIdx)
# We cannot call ``newSym`` here, because we have to circumvent the ID
# mechanism, which we do in order to assign each module a persistent ID.
new(result)
result.id = -1 # for better error checking
result.kind = skModule
let filename = AbsoluteFile toFullPath(graph.config, fileIdx)
result.name = getIdent(graph.cache, splitFile(filename).name)
result = PSym(kind: skModule, id: -1, # for better error checking
name: getModuleIdent(graph, filename),
info: newLineInfo(fileIdx, 1, 1))
if not isNimIdentifier(result.name.s):
rawMessage(graph.config, errGenerated, "invalid module name: " & result.name.s)
result.info = newLineInfo(fileIdx, 1, 1)
partialInitModule(result, graph, fileIdx, filename)
proc compileModule*(graph: ModuleGraph; fileIdx: FileIndex; flags: TSymFlags): PSym =
var flags = flags
if fileIdx == graph.config.projectMainIdx2: flags.incl sfMainModule
result = graph.getModule(fileIdx)
if result == nil:
let filename = AbsoluteFile toFullPath(graph.config, fileIdx)
@@ -75,7 +86,7 @@ proc compileModule*(graph: ModuleGraph; fileIdx: FileIndex; flags: TSymFlags): P
result = r
if result == nil:
result = newModule(graph, fileIdx)
result.flags = result.flags + flags
result.flags.incl flags
result.id = id
registerModule(graph, result)
else:
@@ -93,7 +104,7 @@ proc compileModule*(graph: ModuleGraph; fileIdx: FileIndex; flags: TSymFlags): P
if sfMainModule in flags and graph.config.projectIsStdin: stdin.llStreamOpen else: nil)
graph.markClientsDirty(fileIdx)
proc importModule*(graph: ModuleGraph; s: PSym, fileIdx: FileIndex): PSym {.procvar.} =
proc importModule*(graph: ModuleGraph; s: PSym, fileIdx: FileIndex): PSym =
# this is called by the semantic checking phase
assert graph.config != nil
result = compileModule(graph, fileIdx, {})
@@ -105,10 +116,10 @@ proc importModule*(graph: ModuleGraph; s: PSym, fileIdx: FileIndex): PSym {.proc
# localError(result.info, errAttemptToRedefine, result.name.s)
# restore the notes for outer module:
graph.config.notes =
if s.owner.id == graph.config.mainPackageId or isDefined(graph.config, "booting"): graph.config.mainPackageNotes
if s.getnimblePkgId == graph.config.mainPackageId or isDefined(graph.config, "booting"): graph.config.mainPackageNotes
else: graph.config.foreignPackageNotes
proc includeModule*(graph: ModuleGraph; s: PSym, fileIdx: FileIndex): PNode {.procvar.} =
proc includeModule*(graph: ModuleGraph; s: PSym, fileIdx: FileIndex): PNode =
result = syntaxes.parseFile(fileIdx, graph.cache, graph.config)
graph.addDep(s, fileIdx)
graph.addIncludeDep(s.position.FileIndex, fileIdx)
@@ -126,7 +137,7 @@ proc compileSystemModule*(graph: ModuleGraph) =
proc wantMainModule*(conf: ConfigRef) =
if conf.projectFull.isEmpty:
fatal(conf, newLineInfo(conf, AbsoluteFile"command line", 1, 1), errGenerated,
fatal(conf, newLineInfo(conf, AbsoluteFile(commandLineDesc), 1, 1), errGenerated,
"command expects a filename")
conf.projectMainIdx = fileInfoIdx(conf, addFileExt(conf.projectFull, NimExt))
@@ -136,7 +147,12 @@ proc compileProject*(graph: ModuleGraph; projectFileIdx = InvalidFileIdx) =
wantMainModule(conf)
let systemFileIdx = fileInfoIdx(conf, conf.libpath / RelativeFile"system.nim")
let projectFile = if projectFileIdx == InvalidFileIdx: conf.projectMainIdx else: projectFileIdx
conf.projectMainIdx2 = projectFile
let packSym = getPackage(graph, projectFile)
graph.config.mainPackageId = packSym.getnimblePkgId
graph.importStack.add projectFile
if projectFile == systemFileIdx:
discard graph.compileModule(projectFile, {sfMainModule, sfSystemModule})
else:

View File

@@ -10,6 +10,17 @@
import
options, strutils, os, tables, ropes, terminal, macros,
lineinfos, pathutils
import std/private/miscdollars
import strutils2
type InstantiationInfo* = typeof(instantiationInfo())
template instLoc(): InstantiationInfo = instantiationInfo(-2, fullPaths = true)
template flushDot(conf, stdorr) =
## safe to call multiple times
if conf.lastMsgWasDot:
conf.lastMsgWasDot = false
write(stdorr, "\n")
proc toCChar*(c: char; result: var string) =
case c
@@ -26,14 +37,13 @@ proc makeCString*(s: string): Rope =
const MaxLineLength = 64
result = nil
var res = newStringOfCap(int(s.len.toFloat * 1.1) + 1)
add(res, "\"")
for i in 0 ..< len(s):
res.add("\"")
for i in 0..<s.len:
if (i + 1) mod MaxLineLength == 0:
add(res, "\"\L\"")
res.add("\"\L\"")
toCChar(s[i], res)
add(res, '\"')
add(result, rope(res))
res.add('\"')
result.add(rope(res))
proc newFileInfo(fullPath: AbsoluteFile, projPath: RelativeFile): TFileInfo =
result.fullPath = fullPath
@@ -57,6 +67,12 @@ when defined(nimpretty):
proc fileSection*(conf: ConfigRef; fid: FileIndex; a, b: int): string =
substr(conf.m.fileInfos[fid.int].fullContent, a, b)
proc canonicalCase(path: var string) =
## the idea is to only use this for checking whether a path is already in
## the table but otherwise keep the original case
when FileSystemCaseSensitive: discard
else: toLowerAscii(path)
proc fileInfoKnown*(conf: ConfigRef; filename: AbsoluteFile): bool =
var
canon: AbsoluteFile
@@ -64,6 +80,7 @@ proc fileInfoKnown*(conf: ConfigRef; filename: AbsoluteFile): bool =
canon = canonicalizePath(conf, filename)
except OSError:
canon = filename
canon.string.canonicalCase
result = conf.m.filenameToIndexTbl.hasKey(canon.string)
proc fileInfoIdx*(conf: ConfigRef; filename: AbsoluteFile; isKnownFile: var bool): FileIndex =
@@ -80,15 +97,19 @@ proc fileInfoIdx*(conf: ConfigRef; filename: AbsoluteFile; isKnownFile: var bool
# This flag indicates that we are working with such a path here
pseudoPath = true
if conf.m.filenameToIndexTbl.hasKey(canon.string):
var canon2: string
forceCopy(canon2, canon.string) # because `canon` may be shallow
canon2.canonicalCase
if conf.m.filenameToIndexTbl.hasKey(canon2):
isKnownFile = true
result = conf.m.filenameToIndexTbl[canon.string]
result = conf.m.filenameToIndexTbl[canon2]
else:
isKnownFile = false
result = conf.m.fileInfos.len.FileIndex
conf.m.fileInfos.add(newFileInfo(canon, if pseudoPath: RelativeFile filename
else: relativeTo(canon, conf.projectPath)))
conf.m.filenameToIndexTbl[canon.string] = result
conf.m.filenameToIndexTbl[canon2] = result
proc fileInfoIdx*(conf: ConfigRef; filename: AbsoluteFile): FileIndex =
var dummy: bool
@@ -108,6 +129,7 @@ proc newLineInfo*(fileInfoIdx: FileIndex, line, col: int): TLineInfo =
proc newLineInfo*(conf: ConfigRef; filename: AbsoluteFile, line, col: int): TLineInfo {.inline.} =
result = newLineInfo(fileInfoIdx(conf, filename), line, col)
const gCmdLineInfo* = newLineInfo(commandLineIdx, 1, 1)
proc concat(strings: openArray[string]): string =
var totalLen = 0
@@ -132,7 +154,6 @@ proc suggestQuit*() =
# this format is understood by many text editors: it is the same that
# Borland and Freepascal use
const
PosFormat = "$1($2, $3) "
KindFormat = " [$1]"
KindColor = fgCyan
ErrorTitle = "Error: "
@@ -145,6 +166,7 @@ const
# but column numbers start with 0, however most editors expect
# first column to be 1, so we need to +1 here
ColOffset* = 1
commandLineDesc* = "command line"
proc getInfoContextLen*(conf: ConfigRef): int = return conf.m.msgContext.len
proc setInfoContextLen*(conf: ConfigRef; L: int) = setLen(conf.m.msgContext, L)
@@ -153,17 +175,13 @@ proc pushInfoContext*(conf: ConfigRef; info: TLineInfo; detail: string = "") =
conf.m.msgContext.add((info, detail))
proc popInfoContext*(conf: ConfigRef) =
setLen(conf.m.msgContext, len(conf.m.msgContext) - 1)
setLen(conf.m.msgContext, conf.m.msgContext.len - 1)
proc getInfoContext*(conf: ConfigRef; index: int): TLineInfo =
let L = conf.m.msgContext.len
let i = if index < 0: L + index else: index
if i >=% L: result = unknownLineInfo()
let i = if index < 0: conf.m.msgContext.len + index else: index
if i >=% conf.m.msgContext.len: result = unknownLineInfo
else: result = conf.m.msgContext[i].info
const
commandLineDesc = "command line"
template toFilename*(conf: ConfigRef; fileIdx: FileIndex): string =
if fileIdx.int32 < 0 or conf == nil:
(if fileIdx == commandLineIdx: commandLineDesc else: "???")
@@ -214,16 +232,36 @@ template toFullPath*(conf: ConfigRef; info: TLineInfo): string =
template toFullPathConsiderDirty*(conf: ConfigRef; info: TLineInfo): string =
string toFullPathConsiderDirty(conf, info.fileIndex)
type FilenameOption* = enum
foAbs # absolute path, e.g.: /pathto/bar/foo.nim
foRelProject # relative to project path, e.g.: ../foo.nim
foMagicSauce # magic sauce, shortest of (foAbs, foRelProject)
foName # lastPathPart, e.g.: foo.nim
foStacktrace # if optExcessiveStackTrace: foAbs else: foName
proc toFilenameOption*(conf: ConfigRef, fileIdx: FileIndex, opt: FilenameOption): string =
case opt
of foAbs: result = toFullPath(conf, fileIdx)
of foRelProject: result = toProjPath(conf, fileIdx)
of foMagicSauce:
let
absPath = toFullPath(conf, fileIdx)
relPath = toProjPath(conf, fileIdx)
result = if (optListFullPaths in conf.globalOptions) or
(relPath.len > absPath.len) or
(relPath.count("..") > 2):
absPath
else:
relPath
of foName: result = toProjPath(conf, fileIdx).lastPathPart
of foStacktrace:
if optExcessiveStackTrace in conf.globalOptions:
result = toFilenameOption(conf, fileIdx, foAbs)
else:
result = toFilenameOption(conf, fileIdx, foName)
proc toMsgFilename*(conf: ConfigRef; info: FileIndex): string =
let
absPath = toFullPath(conf, info)
relPath = toProjPath(conf, info)
result = if (optListFullPaths in conf.globalOptions) or
(relPath.len > absPath.len) or
(relPath.count("..") > 2):
absPath
else:
relPath
toFilenameOption(conf, info, foMagicSauce)
template toMsgFilename*(conf: ConfigRef; info: TLineInfo): string =
toMsgFilename(conf, info.fileIndex)
@@ -234,10 +272,11 @@ proc toLinenumber*(info: TLineInfo): int {.inline.} =
proc toColumn*(info: TLineInfo): int {.inline.} =
result = info.col
proc toFileLineCol(info: InstantiationInfo): string {.inline.} =
result.toLocation(info.filename, info.line, info.column + ColOffset)
proc toFileLineCol*(conf: ConfigRef; info: TLineInfo): string {.inline.} =
# consider calling `helpers.lineInfoToString` instead
result = toMsgFilename(conf, info) & "(" & $info.line & ", " &
$(info.col + ColOffset) & ")"
result.toLocation(toMsgFilename(conf, info), info.line.int, info.col.int + ColOffset)
proc `$`*(conf: ConfigRef; info: TLineInfo): string = toFileLineCol(conf, info)
@@ -262,15 +301,16 @@ proc msgWriteln*(conf: ConfigRef; s: string, flags: MsgFlags = {}) =
## This is used for 'nim dump' etc. where we don't have nimsuggest
## support.
#if conf.cmd == cmdIdeTools and optCDebug notin gGlobalOptions: return
if not isNil(conf.writelnHook) and msgSkipHook notin flags:
conf.writelnHook(s)
elif optStdout in conf.globalOptions or msgStdout in flags:
if eStdOut in conf.m.errorOutputs:
flushDot(conf, stdout)
writeLine(stdout, s)
flushFile(stdout)
else:
if eStdErr in conf.m.errorOutputs:
flushDot(conf, stderr)
writeLine(stderr, s)
# On Windows stderr is fully-buffered when piped, regardless of C std.
when defined(windows):
@@ -299,63 +339,73 @@ macro callStyledWriteLineStderr(args: varargs[typed]): untyped =
result.add(bindSym"stderr")
for arg in children(args[0][1]):
result.add(arg)
when false:
# not needed because styledWriteLine already ends with resetAttributes
result = newStmtList(result, newCall(bindSym"resetAttributes", bindSym"stderr"))
template callWritelnHook(args: varargs[string, `$`]) =
conf.writelnHook concat(args)
proc msgWrite(conf: ConfigRef; s: string) =
if conf.m.errorOutputs != {}:
let stdOrr =
if optStdout in conf.globalOptions:
stdout
else:
stderr
write(stdOrr, s)
flushFile(stdOrr)
conf.lastMsgWasDot = true # subsequent writes need `flushDot`
template styledMsgWriteln*(args: varargs[typed]) =
if not isNil(conf.writelnHook):
callIgnoringStyle(callWritelnHook, nil, args)
elif optStdout in conf.globalOptions:
if eStdOut in conf.m.errorOutputs:
flushDot(conf, stdout)
callIgnoringStyle(writeLine, stdout, args)
flushFile(stdout)
else:
if eStdErr in conf.m.errorOutputs:
if optUseColors in conf.globalOptions:
callStyledWriteLineStderr(args)
else:
callIgnoringStyle(writeLine, stderr, args)
# On Windows stderr is fully-buffered when piped, regardless of C std.
when defined(windows):
flushFile(stderr)
elif eStdErr in conf.m.errorOutputs:
flushDot(conf, stderr)
if optUseColors in conf.globalOptions:
callStyledWriteLineStderr(args)
else:
callIgnoringStyle(writeLine, stderr, args)
# On Windows stderr is fully-buffered when piped, regardless of C std.
when defined(windows):
flushFile(stderr)
proc coordToStr(coord: int): string =
if coord == -1: result = "???"
else: result = $coord
proc msgKindToString*(kind: TMsgKind): string =
proc msgKindToString*(kind: TMsgKind): string = MsgKindToStr[kind]
# later versions may provide translated error messages
result = MsgKindToStr[kind]
proc getMessageStr(msg: TMsgKind, arg: string): string =
result = msgKindToString(msg) % [arg]
proc getMessageStr(msg: TMsgKind, arg: string): string = msgKindToString(msg) % [arg]
type
TErrorHandling = enum doNothing, doAbort, doRaise
type TErrorHandling* = enum doNothing, doAbort, doRaise
proc log*(s: string) {.procvar.} =
proc log*(s: string) =
var f: File
if open(f, getHomeDir() / "nimsuggest.log", fmAppend):
f.writeLine(s)
close(f)
proc quit(conf: ConfigRef; msg: TMsgKind) {.gcsafe.} =
if defined(debug) or msg == errInternal or hintStackTrace in conf.notes:
if defined(debug) or msg == errInternal or conf.hasHint(hintStackTrace):
{.gcsafe.}:
if stackTraceAvailable() and isNil(conf.writelnHook):
writeStackTrace()
else:
styledMsgWriteln(fgRed, "No stack traceback available\n" &
"To create a stacktrace, rerun compilation with ./koch temp " &
conf.command & " <file>")
styledMsgWriteln(fgRed, """
No stack traceback available
To create a stacktrace, rerun compilation with './koch temp $1 <file>', see $2 for details""" %
[conf.command, "intern.html#debugging-the-compiler".createDocLink])
quit 1
proc handleError(conf: ConfigRef; msg: TMsgKind, eh: TErrorHandling, s: string) =
if msg >= fatalMin and msg <= fatalMax:
if conf.cmd == cmdIdeTools: log(s)
quit(conf, msg)
if msg >= errMin and msg <= errMax:
if msg >= errMin and msg <= errMax or
(msg in warnMin..warnMax and msg in conf.warningAsErrors):
inc(conf.errorCounter)
conf.exitcode = 1'i8
if conf.errorCounter >= conf.errorMax:
@@ -375,93 +425,45 @@ proc writeContext(conf: ConfigRef; lastinfo: TLineInfo) =
const instantiationFrom = "template/generic instantiation from here"
const instantiationOfFrom = "template/generic instantiation of `$1` from here"
var info = lastinfo
for i in 0 ..< len(conf.m.msgContext):
for i in 0..<conf.m.msgContext.len:
let context = conf.m.msgContext[i]
if context.info != lastinfo and context.info != info:
if conf.structuredErrorHook != nil:
conf.structuredErrorHook(conf, context.info, instantiationFrom,
Severity.Error)
Severity.Hint)
else:
let message = if context.detail == "":
instantiationFrom
else:
instantiationOfFrom.format(context.detail)
styledMsgWriteln(styleBright,
PosFormat % [toMsgFilename(conf, context.info),
coordToStr(context.info.line.int),
coordToStr(context.info.col+ColOffset)],
resetStyle,
message)
styledMsgWriteln(styleBright, conf.toFileLineCol(context.info), " ", resetStyle, message)
info = context.info
proc ignoreMsgBecauseOfIdeTools(conf: ConfigRef; msg: TMsgKind): bool =
msg >= errGenerated and conf.cmd == cmdIdeTools and optIdeDebug notin conf.globalOptions
proc rawMessage*(conf: ConfigRef; msg: TMsgKind, args: openArray[string]) =
var
title: string
color: ForegroundColor
kind: string
sev: Severity
case msg
of errMin..errMax:
sev = Severity.Error
writeContext(conf, unknownLineInfo())
title = ErrorTitle
color = ErrorColor
of warnMin..warnMax:
sev = Severity.Warning
if optWarns notin conf.options: return
if msg notin conf.notes: return
writeContext(conf, unknownLineInfo())
title = WarningTitle
color = WarningColor
kind = WarningsToStr[ord(msg) - ord(warnMin)]
inc(conf.warnCounter)
of hintMin..hintMax:
sev = Severity.Hint
if optHints notin conf.options: return
if msg notin conf.notes: return
title = HintTitle
color = HintColor
if msg != hintUserRaw: kind = HintsToStr[ord(msg) - ord(hintMin)]
inc(conf.hintCounter)
let s = msgKindToString(msg) % args
if conf.structuredErrorHook != nil:
conf.structuredErrorHook(conf, unknownLineInfo(),
s & (if kind.len > 0: KindFormat % kind else: ""), sev)
if not ignoreMsgBecauseOfIdeTools(conf, msg):
if kind.len > 0:
styledMsgWriteln(color, title, resetStyle, s,
KindColor, `%`(KindFormat, kind))
else:
styledMsgWriteln(color, title, resetStyle, s)
handleError(conf, msg, doAbort, s)
proc rawMessage*(conf: ConfigRef; msg: TMsgKind, arg: string) =
rawMessage(conf, msg, [arg])
proc resetAttributes*(conf: ConfigRef) =
if {optUseColors, optStdout} * conf.globalOptions == {optUseColors}:
terminal.resetAttributes(stderr)
proc addSourceLine(conf: ConfigRef; fileIdx: FileIndex, line: string) =
conf.m.fileInfos[fileIdx.int32].lines.add line
proc sourceLine*(conf: ConfigRef; i: TLineInfo): string =
if i.fileIndex.int32 < 0: return ""
if conf.m.fileInfos[i.fileIndex.int32].lines.len == 0:
proc numLines*(conf: ConfigRef, fileIdx: FileIndex): int =
## xxx there's an off by 1 error that should be fixed; if a file ends with "foo" or "foo\n"
## it will return same number of lines (ie, a trailing empty line is discounted)
result = conf.m.fileInfos[fileIdx.int32].lines.len
if result == 0:
try:
for line in lines(toFullPathConsiderDirty(conf, i)):
addSourceLine conf, i.fileIndex, line.string
for line in lines(toFullPathConsiderDirty(conf, fileIdx).string):
addSourceLine conf, fileIdx, line.string
except IOError:
discard
assert i.fileIndex.int32 < conf.m.fileInfos.len
result = conf.m.fileInfos[fileIdx.int32].lines.len
proc sourceLine*(conf: ConfigRef; i: TLineInfo): string =
## 1-based index (matches editor line numbers); 1st line is for i.line = 1
## last valid line is `numLines` inclusive
if i.fileIndex.int32 < 0: return ""
let num = numLines(conf, i.fileIndex)
# can happen if the error points to EOF:
if i.line.int > conf.m.fileInfos[i.fileIndex.int32].lines.len: return ""
if i.line.int > num: return ""
result = conf.m.fileInfos[i.fileIndex.int32].lines[i.line.int-1]
@@ -476,101 +478,127 @@ proc formatMsg*(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg: string): s
of warnMin..warnMax: WarningTitle
of hintMin..hintMax: HintTitle
else: ErrorTitle
result = PosFormat % [toMsgFilename(conf, info), coordToStr(info.line.int),
coordToStr(info.col+ColOffset)] &
title &
getMessageStr(msg, arg)
conf.toFileLineCol(info) & " " & title & getMessageStr(msg, arg)
proc liMessage(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg: string,
eh: TErrorHandling) =
proc liMessage*(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg: string,
eh: TErrorHandling, info2: InstantiationInfo, isRaw = false) {.noinline.} =
var
title: string
color: ForegroundColor
kind: string
ignoreMsg = false
sev: Severity
let kind = if msg in warnMin..hintMax and msg != hintUserRaw: $msg else: "" # xxx not sure why hintUserRaw is special
case msg
of errMin..errMax:
sev = Severity.Error
writeContext(conf, info)
title = ErrorTitle
color = ErrorColor
# we try to filter error messages so that not two error message
# in the same file and line are produced:
#ignoreMsg = lastError == info and eh != doAbort
conf.m.lastError = info
when false:
# we try to filter error messages so that not two error message
# in the same file and line are produced:
# xxx `lastError` is only used in this disabled code; but could be useful to revive
ignoreMsg = conf.m.lastError == info and info != unknownLineInfo and eh != doAbort
if info != unknownLineInfo: conf.m.lastError = info
of warnMin..warnMax:
sev = Severity.Warning
ignoreMsg = optWarns notin conf.options or msg notin conf.notes
ignoreMsg = not conf.hasWarn(msg)
if msg in conf.warningAsErrors:
ignoreMsg = false
title = ErrorTitle
else:
title = WarningTitle
if not ignoreMsg: writeContext(conf, info)
title = WarningTitle
color = WarningColor
kind = WarningsToStr[ord(msg) - ord(warnMin)]
inc(conf.warnCounter)
of hintMin..hintMax:
sev = Severity.Hint
ignoreMsg = optHints notin conf.options or msg notin conf.notes
ignoreMsg = not conf.hasHint(msg)
title = HintTitle
color = HintColor
if msg != hintUserRaw: kind = HintsToStr[ord(msg) - ord(hintMin)]
inc(conf.hintCounter)
let x = PosFormat % [toMsgFilename(conf, info), coordToStr(info.line.int),
coordToStr(info.col+ColOffset)]
let s = getMessageStr(msg, arg)
let s = if isRaw: arg else: getMessageStr(msg, arg)
if not ignoreMsg:
let loc = if info != unknownLineInfo: conf.toFileLineCol(info) & " " else: ""
var kindmsg = if kind.len > 0: KindFormat % kind else: ""
if conf.structuredErrorHook != nil:
conf.structuredErrorHook(conf, info, s & (if kind.len > 0: KindFormat % kind else: ""), sev)
conf.structuredErrorHook(conf, info, s & kindmsg, sev)
if not ignoreMsgBecauseOfIdeTools(conf, msg):
if kind.len > 0:
styledMsgWriteln(styleBright, x, resetStyle, color, title, resetStyle, s,
KindColor, `%`(KindFormat, kind))
if msg == hintProcessing:
msgWrite(conf, ".")
else:
styledMsgWriteln(styleBright, x, resetStyle, color, title, resetStyle, s)
if hintSource in conf.notes:
conf.writeSurroundingSrc(info)
styledMsgWriteln(styleBright, loc, resetStyle, color, title, resetStyle, s, KindColor, kindmsg)
if conf.hasHint(hintSource) and info != unknownLineInfo:
conf.writeSurroundingSrc(info)
if hintMsgOrigin in conf.mainPackageNotes:
styledMsgWriteln(styleBright, toFileLineCol(info2), resetStyle,
" compiler msg initiated here", KindColor,
KindFormat % $hintMsgOrigin,
resetStyle)
handleError(conf, msg, eh, s)
proc fatal*(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg = "") =
# this fixes bug #7080 so that it is at least obvious 'fatal'
# was executed.
template rawMessage*(conf: ConfigRef; msg: TMsgKind, args: openArray[string]) =
let arg = msgKindToString(msg) % args
liMessage(conf, unknownLineInfo, msg, arg, eh = doAbort, instLoc(), isRaw = true)
template rawMessage*(conf: ConfigRef; msg: TMsgKind, arg: string) =
liMessage(conf, unknownLineInfo, msg, arg, eh = doAbort, instLoc())
template fatal*(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg = "") =
# this fixes bug #7080 so that it is at least obvious 'fatal' was executed.
conf.m.errorOutputs = {eStdOut, eStdErr}
liMessage(conf, info, msg, arg, doAbort)
liMessage(conf, info, msg, arg, doAbort, instLoc())
proc globalError*(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg = "") =
liMessage(conf, info, msg, arg, doRaise)
template globalAssert*(conf: ConfigRef; cond: untyped, info: TLineInfo = unknownLineInfo, arg = "") =
## avoids boilerplate
if not cond:
var arg2 = "'$1' failed" % [astToStr(cond)]
if arg.len > 0: arg2.add "; " & astToStr(arg) & ": " & arg
liMessage(conf, info, errGenerated, arg2, doRaise, instLoc())
proc globalError*(conf: ConfigRef; info: TLineInfo, arg: string) =
liMessage(conf, info, errGenerated, arg, doRaise)
template globalError*(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg = "") =
## `local` means compilation keeps going until errorMax is reached (via `doNothing`),
## `global` means it stops.
liMessage(conf, info, msg, arg, doRaise, instLoc())
proc localError*(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg = "") =
liMessage(conf, info, msg, arg, doNothing)
template globalError*(conf: ConfigRef; info: TLineInfo, arg: string) =
liMessage(conf, info, errGenerated, arg, doRaise, instLoc())
proc localError*(conf: ConfigRef; info: TLineInfo, arg: string) =
liMessage(conf, info, errGenerated, arg, doNothing)
template localError*(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg = "") =
liMessage(conf, info, msg, arg, doNothing, instLoc())
proc localError*(conf: ConfigRef; info: TLineInfo, format: string, params: openArray[string]) =
localError(conf, info, format % params)
template localError*(conf: ConfigRef; info: TLineInfo, arg: string) =
liMessage(conf, info, errGenerated, arg, doNothing, instLoc())
proc message*(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg = "") =
liMessage(conf, info, msg, arg, doNothing)
template localError*(conf: ConfigRef; info: TLineInfo, format: string, params: openArray[string]) =
liMessage(conf, info, errGenerated, format % params, doNothing, instLoc())
proc internalError*(conf: ConfigRef; info: TLineInfo, errMsg: string) =
template message*(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg = "") =
liMessage(conf, info, msg, arg, doNothing, instLoc())
proc internalErrorImpl(conf: ConfigRef; info: TLineInfo, errMsg: string, info2: InstantiationInfo) =
if conf.cmd == cmdIdeTools and conf.structuredErrorHook.isNil: return
writeContext(conf, info)
liMessage(conf, info, errInternal, errMsg, doAbort)
liMessage(conf, info, errInternal, errMsg, doAbort, info2)
proc internalError*(conf: ConfigRef; errMsg: string) =
if conf.cmd == cmdIdeTools and conf.structuredErrorHook.isNil: return
writeContext(conf, unknownLineInfo())
rawMessage(conf, errInternal, errMsg)
template internalError*(conf: ConfigRef; info: TLineInfo, errMsg: string) =
internalErrorImpl(conf, info, errMsg, instLoc())
template assertNotNil*(conf: ConfigRef; e): untyped =
if e == nil: internalError(conf, $instantiationInfo())
e
template internalError*(conf: ConfigRef; errMsg: string) =
internalErrorImpl(conf, unknownLineInfo, errMsg, instLoc())
template internalAssert*(conf: ConfigRef, e: bool) =
if not e: internalError(conf, $instantiationInfo())
# xxx merge with `globalAssert`
if not e:
const info2 = instLoc()
let arg = info2.toFileLineCol
internalErrorImpl(conf, unknownLineInfo, arg, info2)
template lintReport*(conf: ConfigRef; info: TLineInfo, beau, got: string) =
let m = "'$2' should be: '$1'" % [beau, got]
let msg = if optStyleError in conf.globalOptions: errGenerated else: hintName
liMessage(conf, info, msg, m, doNothing, instLoc())
proc quotedFilename*(conf: ConfigRef; i: TLineInfo): Rope =
if i.fileIndex.int32 < 0:
@@ -580,25 +608,9 @@ proc quotedFilename*(conf: ConfigRef; i: TLineInfo): Rope =
else:
result = conf.m.fileInfos[i.fileIndex.int32].quotedName
proc listWarnings*(conf: ConfigRef) =
msgWriteln(conf, "Warnings:")
for warn in warnMin..warnMax:
msgWriteln(conf, " [$1] $2" % [
if warn in conf.notes: "x" else: " ",
lineinfos.WarningsToStr[ord(warn) - ord(warnMin)]
])
template listMsg(title, r) =
msgWriteln(conf, title)
for a in r: msgWriteln(conf, " [$1] $2" % [if a in conf.notes: "x" else: " ", $a])
proc listHints*(conf: ConfigRef) =
msgWriteln(conf, "Hints:")
for hint in hintMin..hintMax:
msgWriteln(conf, " [$1] $2" % [
if hint in conf.notes: "x" else: " ",
lineinfos.HintsToStr[ord(hint) - ord(hintMin)]
])
proc lintReport*(conf: ConfigRef; info: TLineInfo, beau, got: string) =
let m = "'$2' should be: '$1'" % [beau, got]
if optStyleError in conf.globalOptions:
localError(conf, info, m)
else:
message(conf, info, hintName, m)
proc listWarnings*(conf: ConfigRef) = listMsg("Warnings:", warnMin..warnMax)
proc listHints*(conf: ConfigRef) = listMsg("Hints:", hintMin..hintMax)

View File

@@ -17,6 +17,8 @@ type
enabled: bool
f: File
buf: string
filename: AbsoluteFile
syms: seq[PSym]
proc doWrite(f: var NdiFile; s: PSym; conf: ConfigRef) =
f.buf.setLen 0
@@ -28,13 +30,20 @@ proc doWrite(f: var NdiFile; s: PSym; conf: ConfigRef) =
f.f.writeLine("\t", toFullPath(conf, s.info), "\t", f.buf)
template writeMangledName*(f: NdiFile; s: PSym; conf: ConfigRef) =
if f.enabled: doWrite(f, s, conf)
if f.enabled: f.syms.add s
proc open*(f: var NdiFile; filename: AbsoluteFile; conf: ConfigRef) =
f.enabled = not filename.isEmpty
if f.enabled:
f.f = open(filename.string, fmWrite, 8000)
f.filename = filename
f.buf = newStringOfCap(20)
proc close*(f: var NdiFile) =
if f.enabled: close(f.f)
proc close*(f: var NdiFile, conf: ConfigRef) =
if f.enabled:
f.f = open(f.filename.string, fmWrite, 8000)
doAssert f.f != nil, f.filename.string
for s in f.syms:
doWrite(f, s, conf)
close(f.f)
f.syms.reset
f.filename.reset

View File

@@ -14,15 +14,15 @@ define:nimcore
@end
define:useStdoutAsStdmsg
define:nimOldCaseObjects
@if nimHasStyleChecks:
styleCheck:error
@end
#define:useNodeIds
#gc:markAndSweep
@if nimHasWarningCaseTransition:
warning[CaseTransition]:off
@if nimHasWarningObservableStores:
warning[ObservableStores]: off
@end

View File

@@ -22,9 +22,10 @@ import
commands, options, msgs,
extccomp, strutils, os, main, parseopt,
idents, lineinfos, cmdlinehelper,
pathutils
pathutils, modulegraphs
include nodejs
from browsers import openDefaultBrowser
from nodejs import findNodeJs
when hasTinyCBackend:
import tccgen
@@ -33,20 +34,6 @@ when defined(profiler) or defined(memProfiler):
{.hint: "Profiling support is turned on!".}
import nimprof
proc prependCurDir(f: AbsoluteFile): AbsoluteFile =
when defined(unix):
if os.isAbsolute(f.string): result = f
else: result = AbsoluteFile("./" & f.string)
else:
result = f
proc addCmdPrefix*(result: var string, kind: CmdLineKind) =
# consider moving this to std/parseopt
case kind
of cmdLongOption: result.add "--"
of cmdShortOption: result.add "-"
of cmdArgument, cmdEnd: discard
proc processCmdLine(pass: TCmdLinePass, cmd: string; config: ConfigRef) =
var p = parseopt.initOptParser(cmd)
var argsCount = 0
@@ -66,7 +53,7 @@ proc processCmdLine(pass: TCmdLinePass, cmd: string; config: ConfigRef) =
config.commandLine.add ':'
config.commandLine.add p.val.quoteShell
if p.key == " ":
if p.key == "": # `-` was passed to indicate main project is stdin
p.key = "-"
if processArgument(pass, p, argsCount, config): break
else:
@@ -77,14 +64,13 @@ proc processCmdLine(pass: TCmdLinePass, cmd: string; config: ConfigRef) =
if processArgument(pass, p, argsCount, config): break
if pass == passCmd2:
if {optRun, optWasNimscript} * config.globalOptions == {} and
config.arguments.len > 0 and config.command.normalize notin ["run", "e"]:
config.arguments.len > 0 and config.command.normalize notin ["run", "e", "r"]:
rawMessage(config, errGenerated, errArgsNeedRunOption)
proc handleCmdLine(cache: IdentCache; conf: ConfigRef) =
let self = NimProg(
supportsStdinFile: true,
processCmdLine: processCmdLine,
mainCommand: mainCommand
processCmdLine: processCmdLine
)
self.initDefinesProg(conf, "nim_compiler")
if paramCount() == 0:
@@ -92,19 +78,33 @@ proc handleCmdLine(cache: IdentCache; conf: ConfigRef) =
return
self.processCmdLineAndProjectPath(conf)
if not self.loadConfigsAndRunMainCommand(cache, conf): return
if optHints in conf.options and hintGCStats in conf.notes: echo(GC_getStatistics())
var graph = newModuleGraph(cache, conf)
if not self.loadConfigsAndRunMainCommand(cache, conf, graph): return
mainCommand(graph)
if conf.hasHint(hintGCStats): echo(GC_getStatistics())
#echo(GC_getStatistics())
if conf.errorCounter != 0: return
when hasTinyCBackend:
if conf.cmd == cmdRun:
tccgen.run(conf.arguments)
tccgen.run(conf, conf.arguments)
if optRun in conf.globalOptions:
var ex = quoteShell conf.absOutFile
if conf.cmd == cmdCompileToJS:
execExternalProgram(conf, findNodeJs() & " " & ex & ' ' & conf.arguments)
let output = conf.absOutFile
case conf.cmd
of cmdCompileToBackend:
var cmdPrefix = ""
case conf.backend
of backendC, backendCpp, backendObjc: discard
of backendJs: cmdPrefix = findNodeJs() & " "
else: doAssert false, $conf.backend
execExternalProgram(conf, cmdPrefix & output.quoteShell & ' ' & conf.arguments)
of cmdDoc, cmdRst2html:
if conf.arguments.len > 0:
# reserved for future use
rawMessage(conf, errGenerated, "'$1 cannot handle arguments" % [$conf.cmd])
openDefaultBrowser($output)
else:
execExternalProgram(conf, ex & ' ' & conf.arguments)
# support as needed
rawMessage(conf, errGenerated, "'$1 cannot handle --run" % [$conf.cmd])
when declared(GC_setMaxPause):
GC_setMaxPause 2_000

View File

@@ -48,7 +48,7 @@ proc `<`*(ver: Version, ver2: Version): bool =
# Handling for normal versions such as "0.1.0" or "1.0".
var sVer = string(ver).split('.')
var sVer2 = string(ver2).split('.')
for i in 0..max(sVer.len, sVer2.len)-1:
for i in 0..<max(sVer.len, sVer2.len):
var sVerI = 0
if i < sVer.len:
discard parseInt(sVer[i], sVerI)
@@ -83,7 +83,7 @@ proc getPathVersion*(p: string): tuple[name, version: string] =
result.name = p
return
result.name = p[0 .. sepIdx - 1]
result.name = p[0..sepIdx - 1]
result.version = p.substr(sepIdx + 1)
proc addPackage(conf: ConfigRef; packages: StringTableRef, p: string; info: TLineInfo) =
@@ -130,30 +130,7 @@ proc addPathRec(conf: ConfigRef; dir: string, info: TLineInfo) =
proc nimblePath*(conf: ConfigRef; path: AbsoluteDir, info: TLineInfo) =
addPathRec(conf, path.string, info)
addNimblePath(conf, path.string, info)
when isMainModule:
proc v(s: string): Version = s.newVersion
# #head is special in the sense that it's assumed to always be newest.
doAssert v"1.0" < v"#head"
doAssert v"1.0" < v"1.1"
doAssert v"1.0.1" < v"1.1"
doAssert v"1" < v"1.1"
doAssert v"#aaaqwe" < v"1.1" # We cannot assume that a branch is newer.
doAssert v"#a111" < v"#head"
let conf = newConfigRef()
var rr = newStringTable()
addPackage conf, rr, "irc-#a111", unknownLineInfo()
addPackage conf, rr, "irc-#head", unknownLineInfo()
addPackage conf, rr, "irc-0.1.0", unknownLineInfo()
#addPackage conf, rr, "irc", unknownLineInfo()
#addPackage conf, rr, "another", unknownLineInfo()
addPackage conf, rr, "another-0.1", unknownLineInfo()
addPackage conf, rr, "ab-0.1.3", unknownLineInfo()
addPackage conf, rr, "ab-0.1", unknownLineInfo()
addPackage conf, rr, "justone-1.0", unknownLineInfo()
doAssert toSeq(rr.chosen) ==
@["irc-#head", "another-0.1", "ab-0.1.3", "justone-1.0"]
let i = conf.nimblePaths.find(path)
if i != -1:
conf.nimblePaths.delete(i)
conf.nimblePaths.insert(path, 0)

View File

@@ -11,18 +11,18 @@
import
llstream, commands, os, strutils, msgs, lexer,
options, idents, wordrecg, strtabs, lineinfos, pathutils
options, idents, wordrecg, strtabs, lineinfos, pathutils, scriptconfig
# ---------------- configuration file parser -----------------------------
# we use Nim's scanner here to save space and work
proc ppGetTok(L: var TLexer, tok: var TToken) =
proc ppGetTok(L: var Lexer, tok: var Token) =
# simple filter
rawGetTok(L, tok)
while tok.tokType in {tkComment}: rawGetTok(L, tok)
proc parseExpr(L: var TLexer, tok: var TToken; config: ConfigRef): bool
proc parseAtom(L: var TLexer, tok: var TToken; config: ConfigRef): bool =
proc parseExpr(L: var Lexer, tok: var Token; config: ConfigRef): bool
proc parseAtom(L: var Lexer, tok: var Token; config: ConfigRef): bool =
if tok.tokType == tkParLe:
ppGetTok(L, tok)
result = parseExpr(L, tok, config)
@@ -35,21 +35,21 @@ proc parseAtom(L: var TLexer, tok: var TToken; config: ConfigRef): bool =
result = isDefined(config, tok.ident.s)
ppGetTok(L, tok)
proc parseAndExpr(L: var TLexer, tok: var TToken; config: ConfigRef): bool =
proc parseAndExpr(L: var Lexer, tok: var Token; config: ConfigRef): bool =
result = parseAtom(L, tok, config)
while tok.tokType == tkAnd:
ppGetTok(L, tok) # skip "and"
var b = parseAtom(L, tok, config)
result = result and b
proc parseExpr(L: var TLexer, tok: var TToken; config: ConfigRef): bool =
proc parseExpr(L: var Lexer, tok: var Token; config: ConfigRef): bool =
result = parseAndExpr(L, tok, config)
while tok.tokType == tkOr:
ppGetTok(L, tok) # skip "or"
var b = parseAndExpr(L, tok, config)
result = result or b
proc evalppIf(L: var TLexer, tok: var TToken; config: ConfigRef): bool =
proc evalppIf(L: var Lexer, tok: var Token; config: ConfigRef): bool =
ppGetTok(L, tok) # skip 'if' or 'elif'
result = parseExpr(L, tok, config)
if tok.tokType == tkColon: ppGetTok(L, tok)
@@ -57,7 +57,7 @@ proc evalppIf(L: var TLexer, tok: var TToken; config: ConfigRef): bool =
#var condStack: seq[bool] = @[]
proc doEnd(L: var TLexer, tok: var TToken; condStack: var seq[bool]) =
proc doEnd(L: var Lexer, tok: var Token; condStack: var seq[bool]) =
if high(condStack) < 0: lexMessage(L, errGenerated, "expected @if")
ppGetTok(L, tok) # skip 'end'
setLen(condStack, high(condStack))
@@ -66,21 +66,21 @@ type
TJumpDest = enum
jdEndif, jdElseEndif
proc jumpToDirective(L: var TLexer, tok: var TToken, dest: TJumpDest; config: ConfigRef;
proc jumpToDirective(L: var Lexer, tok: var Token, dest: TJumpDest; config: ConfigRef;
condStack: var seq[bool])
proc doElse(L: var TLexer, tok: var TToken; config: ConfigRef; condStack: var seq[bool]) =
proc doElse(L: var Lexer, tok: var Token; config: ConfigRef; condStack: var seq[bool]) =
if high(condStack) < 0: lexMessage(L, errGenerated, "expected @if")
ppGetTok(L, tok)
if tok.tokType == tkColon: ppGetTok(L, tok)
if condStack[high(condStack)]: jumpToDirective(L, tok, jdEndif, config, condStack)
proc doElif(L: var TLexer, tok: var TToken; config: ConfigRef; condStack: var seq[bool]) =
proc doElif(L: var Lexer, tok: var Token; config: ConfigRef; condStack: var seq[bool]) =
if high(condStack) < 0: lexMessage(L, errGenerated, "expected @if")
var res = evalppIf(L, tok, config)
if condStack[high(condStack)] or not res: jumpToDirective(L, tok, jdElseEndif, config, condStack)
else: condStack[high(condStack)] = true
proc jumpToDirective(L: var TLexer, tok: var TToken, dest: TJumpDest; config: ConfigRef;
proc jumpToDirective(L: var Lexer, tok: var Token, dest: TJumpDest; config: ConfigRef;
condStack: var seq[bool]) =
var nestedIfs = 0
while true:
@@ -110,11 +110,11 @@ proc jumpToDirective(L: var TLexer, tok: var TToken, dest: TJumpDest; config: Co
else:
ppGetTok(L, tok)
proc parseDirective(L: var TLexer, tok: var TToken; config: ConfigRef; condStack: var seq[bool]) =
proc parseDirective(L: var Lexer, tok: var Token; config: ConfigRef; condStack: var seq[bool]) =
ppGetTok(L, tok) # skip @
case whichKeyword(tok.ident)
of wIf:
setLen(condStack, len(condStack) + 1)
setLen(condStack, condStack.len + 1)
let res = evalppIf(L, tok, config)
condStack[high(condStack)] = res
if not res: jumpToDirective(L, tok, jdElseEndif, config, condStack)
@@ -149,16 +149,16 @@ proc parseDirective(L: var TLexer, tok: var TToken; config: ConfigRef; condStack
else:
lexMessage(L, errGenerated, "invalid directive: '$1'" % $tok)
proc confTok(L: var TLexer, tok: var TToken; config: ConfigRef; condStack: var seq[bool]) =
proc confTok(L: var Lexer, tok: var Token; config: ConfigRef; condStack: var seq[bool]) =
ppGetTok(L, tok)
while tok.ident != nil and tok.ident.s == "@":
parseDirective(L, tok, config, condStack) # else: give the token to the parser
proc checkSymbol(L: TLexer, tok: TToken) =
proc checkSymbol(L: Lexer, tok: Token) =
if tok.tokType notin {tkSymbol..tkInt64Lit, tkStrLit..tkTripleStrLit}:
lexMessage(L, errGenerated, "expected identifier, but got: " & $tok)
proc parseAssignment(L: var TLexer, tok: var TToken;
proc parseAssignment(L: var Lexer, tok: var Token;
config: ConfigRef; condStack: var seq[bool]) =
if tok.ident != nil:
if tok.ident.s == "-" or tok.ident.s == "--":
@@ -169,38 +169,38 @@ proc parseAssignment(L: var TLexer, tok: var TToken;
confTok(L, tok, config, condStack) # skip symbol
var val = ""
while tok.tokType == tkDot:
add(s, '.')
s.add('.')
confTok(L, tok, config, condStack)
checkSymbol(L, tok)
add(s, $tok)
s.add($tok)
confTok(L, tok, config, condStack)
if tok.tokType == tkBracketLe:
# BUGFIX: val, not s!
confTok(L, tok, config, condStack)
checkSymbol(L, tok)
add(val, '[')
add(val, $tok)
val.add('[')
val.add($tok)
confTok(L, tok, config, condStack)
if tok.tokType == tkBracketRi: confTok(L, tok, config, condStack)
else: lexMessage(L, errGenerated, "expected closing ']'")
add(val, ']')
val.add(']')
let percent = tok.ident != nil and tok.ident.s == "%="
if tok.tokType in {tkColon, tkEquals} or percent:
if len(val) > 0: add(val, ':')
if val.len > 0: val.add(':')
confTok(L, tok, config, condStack) # skip ':' or '=' or '%'
checkSymbol(L, tok)
add(val, $tok)
val.add($tok)
confTok(L, tok, config, condStack) # skip symbol
if tok.tokType in {tkColon, tkEquals}:
add(val, $tok) # add the :
val.add($tok) # add the :
confTok(L, tok, config, condStack) # skip symbol
checkSymbol(L, tok)
add(val, $tok) # add the token after it
val.add($tok) # add the token after it
confTok(L, tok, config, condStack) # skip symbol
while tok.ident != nil and tok.ident.s == "&":
confTok(L, tok, config, condStack)
checkSymbol(L, tok)
add(val, $tok)
val.add($tok)
confTok(L, tok, config, condStack)
if percent:
processSwitch(s, strtabs.`%`(val, config.configVars,
@@ -211,8 +211,8 @@ proc parseAssignment(L: var TLexer, tok: var TToken;
proc readConfigFile*(filename: AbsoluteFile; cache: IdentCache;
config: ConfigRef): bool =
var
L: TLexer
tok: TToken
L: Lexer
tok: Token
stream: PLLStream
stream = llStreamOpen(filename, fmRead)
if stream != nil:
@@ -222,7 +222,7 @@ proc readConfigFile*(filename: AbsoluteFile; cache: IdentCache;
var condStack: seq[bool] = @[]
confTok(L, tok, config, condStack) # read in the first token
while tok.tokType != tkEof: parseAssignment(L, tok, config, condStack)
if len(condStack) > 0: lexMessage(L, errGenerated, "expected @end")
if condStack.len > 0: lexMessage(L, errGenerated, "expected @end")
closeLexer(L)
return true
@@ -246,19 +246,34 @@ proc loadConfigs*(cfg: RelativeFile; cache: IdentCache; conf: ConfigRef) =
template readConfigFile(path) =
let configPath = path
if readConfigFile(configPath, cache, conf):
add(configFiles, configPath)
configFiles.add(configPath)
template runNimScriptIfExists(path: AbsoluteFile) =
let p = path # eval once
if fileExists(p):
configFiles.add(p)
runNimScript(cache, p, freshDefines = false, conf)
if optSkipSystemConfigFile notin conf.globalOptions:
readConfigFile(getSystemConfigPath(conf, cfg))
if cfg == DefaultConfig:
runNimScriptIfExists(getSystemConfigPath(conf, DefaultConfigNims))
if optSkipUserConfigFile notin conf.globalOptions:
readConfigFile(getUserConfigPath(cfg))
if cfg == DefaultConfig:
runNimScriptIfExists(getUserConfigPath(DefaultConfigNims))
let pd = if not conf.projectPath.isEmpty: conf.projectPath else: AbsoluteDir(getCurrentDir())
if optSkipParentConfigFiles notin conf.globalOptions:
for dir in parentDirs(pd.string, fromRoot=true, inclusive=false):
readConfigFile(AbsoluteDir(dir) / cfg)
if cfg == DefaultConfig:
runNimScriptIfExists(AbsoluteDir(dir) / DefaultConfigNims)
if optSkipProjConfigFile notin conf.globalOptions:
readConfigFile(pd / cfg)
@@ -269,6 +284,20 @@ proc loadConfigs*(cfg: RelativeFile; cache: IdentCache; conf: ConfigRef) =
projectConfig = changeFileExt(conf.projectFull, "nim.cfg")
readConfigFile(projectConfig)
if cfg == DefaultConfig:
runNimScriptIfExists(pd / DefaultConfigNims)
for filename in configFiles:
# delayed to here so that `hintConf` is honored
rawMessage(conf, hintConf, filename.string)
block:
let scriptFile = conf.projectFull.changeFileExt("nims")
if conf.command != "nimsuggest":
runNimScriptIfExists(scriptFile)
else:
if scriptFile != conf.projectFull:
runNimScriptIfExists(scriptFile)
else:
# 'nimsuggest foo.nims' means to just auto-complete the NimScript file
discard

View File

@@ -10,9 +10,9 @@
## exposes the Nim VM to clients.
import
ast, astalgo, modules, passes, condsyms,
options, sem, semdata, llstream, vm, vmdef,
modulegraphs, idents, os, pathutils, passaux,
scriptconfig
options, sem, semdata, llstream, lineinfos, vm,
vmdef, modulegraphs, idents, os, pathutils,
passaux, scriptconfig
type
Interpreter* = ref object ## Use Nim as an interpreter with this object
@@ -81,6 +81,9 @@ proc findNimStdLib*(): string =
## Returns "" on failure.
try:
let nimexe = os.findExe("nim")
# this can't work with choosenim shims, refs https://github.com/dom96/choosenim/issues/189
# it'd need `nim dump --dump.format:json . | jq -r .libpath`
# which we should simplify as `nim dump --key:libpath`
if nimexe.len == 0: return ""
result = nimexe.splitPath()[0] /../ "lib"
if not fileExists(result / "system.nim"):
@@ -93,20 +96,22 @@ proc findNimStdLib*(): string =
proc findNimStdLibCompileTime*(): string =
## Same as ``findNimStdLib`` but uses source files used at compile time,
## and asserts on error.
const sourcePath = currentSourcePath()
result = sourcePath.parentDir.parentDir / "lib"
const exe = getCurrentCompilerExe()
result = exe.splitFile.dir.parentDir / "lib"
doAssert fileExists(result / "system.nim"), "result:" & result
proc createInterpreter*(scriptName: string;
searchPaths: openArray[string];
flags: TSandboxFlags = {}): Interpreter =
flags: TSandboxFlags = {},
defines = @[("nimscript", "true")],
registerOps = true): Interpreter =
var conf = newConfigRef()
var cache = newIdentCache()
var graph = newModuleGraph(cache, conf)
connectCallbacks(graph)
initDefines(conf.symbols)
defineSymbol(conf.symbols, "nimscript")
defineSymbol(conf.symbols, "nimconfig")
for define in defines:
defineSymbol(conf.symbols, define[0], define[1])
registerPass(graph, semPass)
registerPass(graph, evalPass)
@@ -119,6 +124,8 @@ proc createInterpreter*(scriptName: string;
var vm = newCtx(m, cache, graph)
vm.mode = emRepl
vm.features = flags
if registerOps:
vm.registerAdditionalOps() # Required to register parts of stdlib modules
graph.vm = vm
graph.compileSystemModule()
result = Interpreter(mainModule: m, graph: graph, scriptName: scriptName)
@@ -127,9 +134,15 @@ proc destroyInterpreter*(i: Interpreter) =
## destructor.
discard "currently nothing to do."
proc registerErrorHook*(i: Interpreter, hook:
proc (config: ConfigRef; info: TLineInfo; msg: string;
severity: Severity) {.gcsafe.}) =
i.graph.config.structuredErrorHook = hook
proc runRepl*(r: TLLRepl;
searchPaths: openArray[string];
supportNimscript: bool) =
## deadcode but please don't remove... might be revived
var conf = newConfigRef()
var cache = newIdentCache()
var graph = newModuleGraph(cache, conf)
@@ -139,7 +152,7 @@ proc runRepl*(r: TLLRepl;
if conf.libpath.isEmpty: conf.libpath = AbsoluteDir p
conf.cmd = cmdInteractive
conf.errorMax = high(int)
conf.setErrorMaxHighMaybe
initDefines(conf.symbols)
defineSymbol(conf.symbols, "nimscript")
if supportNimscript: defineSymbol(conf.symbols, "nimconfig")

Some files were not shown because too many files have changed in this diff Show More