Compare commits

..

1212 Commits

Author SHA1 Message Date
ringabout
1204f4a38e more test cases 2023-03-31 16:38:19 +08:00
ringabout
a891b0d948 adds documentation 2023-03-30 23:02:05 +08:00
ringabout
a8c9e9c4e9 deduplicate 2023-03-29 21:12:01 +08:00
ringabout
d997bd4cb5 message 2023-03-26 23:45:37 +08:00
ringabout
e51f27c806 add one more message 2023-03-26 23:44:04 +08:00
ringabout
c1c53bebf1 fixes private fields 2023-03-25 15:47:38 +08:00
ringabout
bde9abb2f7 fixes tests 2023-03-25 09:45:01 +08:00
ringabout
3c36fc17dc Merge remote-tracking branch 'upstream/devel' into pr_object 2023-03-24 23:29:14 +08:00
ringabout
6f8b9b7cc4 better error messages 2023-03-24 23:24:37 +08:00
ringabout
a56697b513 add a filter for unnamed fields 2023-03-24 14:59:44 +08:00
ringabout
55636a2913 fixes #14255; Crash in compiler when using system.any by accident. (#21562)
fixes #14255; Crash in compiler when using system.any by accident.
2023-03-23 16:10:14 +01:00
ringabout
24857a0162 fixes a test 2023-03-23 23:06:31 +08:00
ringabout
91dee1bcff typo 2023-03-23 21:49:46 +08:00
ringabout
251fec94ce add some tests 2023-03-23 21:47:17 +08:00
ringabout
0175be50a9 fixes existing tests 2023-03-23 21:08:35 +08:00
tersec
e8a70ff179 don't access void* out of alignment in refc GC to avoid UB (#21560) 2023-03-22 22:05:20 +01:00
Andreas Rumpf
d84b02f0e0 atlas tool: 'update' command (#21557) 2023-03-21 15:24:57 +01:00
ringabout
c814c4d993 fixes #3770; templates with untyped parameters resolve private fields wrongly in generics (#21554)
* fixes #3770; templates with untyped parameters resolve private fields wrongly

* add a test case for #3770

* rename to `nfSkipFieldChecking`
2023-03-21 15:22:07 +01:00
Andreas Rumpf
f7e3af0c2d mitigates #21272; but it's not the final fix because the first round … (#21462)
mitigates #21272; but it's not the final fix because the first round of overload resolution should already match
2023-03-20 22:53:13 +01:00
Peter Munch-Ellingsen
c155e20796 Fix infinite recursion introduced in 7031ea6 [backport 1.6] (#21555)
Fix infinite recursion introduced in 7031ea6
2023-03-20 22:43:42 +01:00
ringabout
274d61865f closes #21536; fixes manual (#21552)
fixes manual
2023-03-20 22:42:57 +01:00
Federico Ceratto
9df8ca0d81 Add URI parsing warning (#21547)
Related to CVE-2021-41259
https://github.com/nim-lang/security/security/advisories/GHSA-3gg2-rw3q-qwgc
https://github.com/nim-lang/Nim/pull/19128#issuecomment-1181944367
2023-03-20 18:51:58 +01:00
Eric N. Vander Weele
da7833c68b fixes #21538; expand len template parameter once in newSeqWith (#21543)
`len` could contain side effects and may result in different values when
substituted twice in the template expansion. Instead, capture the result
of substituting `len` once.

closes: #21538
2023-03-20 18:51:31 +01:00
Mark Leyva
285ea3c48e Fix: #21541. Add support for xnVerbatimText (#21542)
to text and text= procs. Remove unnecessary LF for xnVerbatimText
in $ proc.
2023-03-20 18:50:58 +01:00
Ivan Yonchovski
fb00b482eb Avoid calling build_all* when nim binary is present (#21522)
- `nimble` will build `nim` using `bin/nim` and if it is already present we can
reuse it.
2023-03-20 18:49:59 +01:00
Regis Caillaud
ba22826e9b Add check for nimMaxJeap on occupied memory + allocation size (#21521)
* fix nimMAxHeap checks

* move check to alloc pages

* remove debug trace

* Fix bad indentation

How the hell did that pass through CI ?
2023-03-20 18:49:18 +01:00
Jake Leahy
741fed716e Use analyseIfAddressTaken logic for checking if address is taken in converter (#21533)
* Add a test case

There are way more test cases (See all branches of analyseIfAddressTaken but this covers at least a second branch

* Port analyseIfAddressTaken from semexprs to sigmatch

This was done since we cannot import sem or semexprs (circular import) but we need the rest of the logic. In needs to be done here since the converter isn't semmed afterwards and so we can't just leave the process til later use the version from semexprs

* Less hacky solution which has the checking be done in analyseIfAddressTakenInCall

This was done instead of the recommendation on removing it since sfAddrTaken is used in places other than the backend

* Remove weird whitespace

* Still check nkHiddenAddr if we are checking a converter
2023-03-20 18:48:13 +01:00
Hiroki Noda
ae06c6623d NuttX: use posix_spawn for osproc (#21539)
NuttX has standard posix_spawn interface, and can be used with it.

* https://nuttx.apache.org/docs/12.0.0/reference/user/01_task_control.html#c.posix_spawn
2023-03-20 18:43:10 +01:00
Hiroki Noda
0c1d595fae NuttX: use accept4 (#21544)
NuttX supports accept4 since 48c9d10336
2023-03-20 18:41:25 +01:00
Joey
cae539996a Update LLDB debug script + Add Custom Nim formatters (#21517)
* Fix custom objects, fix handling of nil variables

* Rename because lldb complains about dashes in filename

* Add example of how to use custom type formatting from Nim

* Add synthetic objects with dynamic fields and add an example
2023-03-19 06:28:00 +01:00
Jason Beetham
a9d0124b5d Made generic type classes work with types using static parameters (#21528) 2023-03-17 10:17:08 +01:00
ringabout
fd4e3ae3e4 add a prepass for codeReordering (#21513)
* add a prepass for codeReordering

* simplify

* fixes
2023-03-17 08:02:48 +01:00
ringabout
b5ee81fd23 fix #18977; disallow change branch of an object variant in ORC (#21526)
* fix #18977 disallow change branch of an object variant in ORC

* check errors for goto exception

* fixes conditions

* fixes tests

* add a test case for #18977
2023-03-16 16:06:26 +01:00
ringabout
6552a27ec1 fixes #19857; Exception raised in closure may be "skipped" in ORC (#21530)
fixes #19857; Exception raised in closure may be "skipped"
2023-03-16 21:07:54 +08:00
Hiroki Noda
c43ac90390 Add NuttX for thread stack size doc (#21529) 2023-03-16 18:03:43 +08:00
Amjad Ben Hedhili
26b7a74a45 Optimize cgen.addIndent (#21508)
* Optimize `cgen.addIndent`

* Avoid temporaries
2023-03-13 17:32:20 +01:00
Amjad Ben Hedhili
c52e44d845 Add cursor annotations to lists iterator variables (#21507)
Add `cursor` annotations to iterator variables

* See https://nim-lang.github.io/Nim/destructors.html#the-cursor-pragma
2023-03-13 08:43:45 +01:00
ringabout
b2c1dcbbc9 fixes explicit globals in macros (#21502) 2023-03-12 20:03:46 +01:00
ringabout
ffadc75afe fixes #21496; Ambiguous calls compiles when module name are equal (#21500)
* fixes #21496; Ambiguous calls compiles when module name are equal

* add a test case
2023-03-12 20:03:14 +01:00
ringabout
af086b68f2 fixes sinkinference documentation, which has been disabled (#21470)
since https://github.com/nim-lang/Nim/pull/15105
2023-03-12 13:01:12 +08:00
Andreas Rumpf
46d2161c23 minor refactoring (#21499) 2023-03-10 14:20:30 +01:00
ringabout
f2dad94902 fixes #21306; fixes #20485; don't transform yields in the var section when introducing new local vars [backport: 1.6] (#21489)
* fixes #21306;  don't transform yields in the var section when introducing new local vars

* adds `inVarSection` so the var section in the var section is freshed

* use `isIntroducingNewLocalVars` to avoid yield transformations in var sections

* fixes comments
2023-03-10 14:19:31 +01:00
ringabout
0319824322 fixes #21023; Segfault when mixing seqs, orc, variants and futures (#21497)
* fixes #21023; Segfault when mixing seqs, orc, variants and futures

* fixes none of the branches were explicitly selected

* add one more test

* one more test
2023-03-10 09:28:51 +01:00
ringabout
72e262666b fixes quoted variables with typedesc types (#21493) 2023-03-09 08:09:08 +01:00
ghost
8e9fc5e639 a better message if graphviz's dot/nodejs is not found in PATH (#21488)
* finish issue #21474: a better message if dot is not found locally when using gendepend

* fix a typo in compiler

* trim empty path reported in `findNodeJs`

* compiler/main.nim: switch raise to simply quit
2023-03-08 22:34:59 +01:00
ringabout
2f89f1eb78 closes #8295; add a test case (#21486) 2023-03-07 20:17:05 +08:00
ringabout
6ef9430153 closes #6231; add a test case (#21485) 2023-03-07 17:34:02 +08:00
Jake Leahy
25eef64fe1 Remove Defect from raises list in std/times (#21473)
* Remove Defect from raises list

Since defects aren't tracked anymore this causes a hint to pop up mentioning it

* Still track Defect when getting ran with an older Nim version

The raises followed a pattern so moving them into a pragma didn't seem to cause any extra problems
2023-03-06 15:31:53 +01:00
ringabout
64a0355f3f fixes #21377; fixes @[] and {} type inference as returns in generics (#21475)
* fixes `@[]` type inference in generics

* add issue links

* fixes macros and iterators

* refactor

* add one more test
2023-03-06 15:30:22 +01:00
ringabout
2d9af2bd55 closes #20704; add a test case (#21480) 2023-03-06 17:34:41 +08:00
ringabout
4d76725299 closes #16654; add a test case (#21478) 2023-03-06 14:12:47 +08:00
Joey
05e8a60bb4 Add line directives for C code variables (#21466)
* Add line directives for C code variables

* Refactor genCLineDir to only use toFullPath if necessary
2023-03-05 20:14:59 +01:00
SirOlaf
7bde421e4d Fix #21272: Rewrite parts of pickBestCandidate (#21465)
* Make pickBestCandidate store syms

* Remove useless cursor

* Try making pickBestCandidate more readable

* Fix advance order

* Revert back to seq with lots of comments

---------

Co-authored-by: SirOlaf <>
2023-03-05 11:56:51 +01:00
Sultan Al Isaiee
04a494f8cf Add warning to specify timeout value in milliseconds, Fix #21449 (#21471)
a warning message been added to the documentation to remind users that the timeout parameter is expressed in milliseconds, not seconds. to help prevent confusion and unexpected behaviours.
2023-03-04 15:53:57 +01:00
ringabout
d950e5f3a8 remove nosinks hacks from compiler (#21469) 2023-03-04 20:07:33 +08:00
quantimnot
6994e1b1d7 --embedsrc for JavaScript (#21467)
Co-authored-by: quantimnot <quantimnot@users.noreply.github.com>
2023-03-04 07:57:30 +01:00
Arnaud Moura
b2c5f8a05f fixes #21461 (#21463)
* fixes #21461; Move nim-gdb.py and add nim-lldb.py

* fixes bad path for nim-gdb.py
2023-03-03 23:37:12 +01:00
ringabout
2e2affb13c test DLL generation with ORC (#21445)
* test DLL generation with ORC

* fixes

* fixes refc

* Update testament/categories.nim
2023-03-03 23:13:27 +08:00
ringabout
d51a392149 replaces implicit passes array registed at runtime with explicit function calls; simplify compilation pipeline (#21444)
* abolish using passes in the compiler; simplify compilation pipeline

* duplicate code

* Really cool to have the same signature...

* haul

* unify other backends

* refactor process

* introduce PipelinePhase

* refactor compiler

* fixes passes

* fixes nimsuggest

* add a sentinel

* enable docs checkj

* activate doc testing

* clean up

* complete cleanups
2023-03-03 07:36:38 +01:00
Jake Leahy
d4d28f2ffe Allow futureLogging in release builds (#21448)
* Add test case

* Fixes 21447: Keeps stackTrace around when using futureLogging

* Remove extra whitespace
2023-03-02 14:27:10 -05:00
ringabout
38d299dfc0 fixes #20139; hash types based on its path relative to its package path (#21274) [backport:1.6]
* fixes #20139; hash types based on its path relative its project

* add a test case

* fixes procs

* better implementation and test case

---------

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2023-03-02 09:16:28 +01:00
Andreas Rumpf
50baf21eac fixes #20422; emit nimPrepareStrMutationV2 for toOpenArray to keep th… (#21459)
fixes #20422; emit nimPrepareStrMutationV2 for toOpenArray to keep the abstraction of mutable strings which have immutable string literals
2023-03-02 08:36:02 +01:00
tersec
612abda4f4 remove decades-deprecated Win32 API *A function support (#21315) 2023-03-02 05:51:54 +01:00
Ivan Yonchovski
9b5ae2b2eb Define the version of nim package without using system module (#21415)
This is follow up from https://github.com/nim-lang/Nim/pull/21313
2023-03-02 05:30:55 +01:00
ringabout
a137e50150 fixes #19291; implements wasMoved hook (#21303)
* fixes #19291; implements `wasMoved` hook

* basics

* checkpoint

* finish `wasMoved`

* add a test for #19291

* add documentation and changelog

* work `attachedWasMoved` with generics

* fixes optimizer

* register `=wasMoved`

* handle wasMoved magcis

* check another round

* some patches

* try `op == nil`

* nicer

* generate `wasMoved` before `destroy`

* try again

* fixes tests

* default wasMoved

* Update tests/destructor/tv2_cast.nim

* Update tests/destructor/tv2_cast.nim

* Update tests/arc/topt_refcursors.nim
2023-03-02 05:29:40 +01:00
ringabout
9948fed919 fixes #21326; fixes #7375; fixes #11986; fixes #9607; rework quote do; getAst uses type info to annotate the type of quoted variables; no more type erasures for quoted variables (#21433)
* fixes #21326; getAst uses type info to annotateType quoted variables

* simplify logics; sem types first

* fixes important packages

* add testcases

* tiny
2023-03-02 05:25:55 +01:00
Anna
070938720a tests/errmsgs/tcall_with_default_arg.nim: sync (#21237) 2023-03-01 21:29:23 +01:00
Anna
cf083af262 tests: explicitly enable stack traces where needed (#21236)
* tests/assert/tassert_c.nim: explicitly enable stack traces

* tests/errmsgs: explicitly enable stack traces
2023-03-01 18:01:58 +01:00
Anna
89d8c0b246 tests/stylecheck: make sure necessary hints are enabled (#21240) 2023-03-01 18:00:58 +01:00
ringabout
1b1412f3d1 fixes #10938; fixes #13312; fixes #13918; fixes #20985; always initializes global variables with null values in VM (#21351)
* fixes #10938; always initialize global variable in VM

* fixes importc vars

* there is a pre-existing issue regarding closure types in the VM

* add tests
2023-03-01 17:18:09 +01:00
heterodoxic
c4dd0c4301 suggestion for a simple fix for #21279 (#21378) 2023-03-01 17:17:05 +01:00
Constantine Molchanov
39d0a93d0e Fix #21452; enable Norm in important packages. (#21455)
* fix #21452; enable Norm in important packages.

* Run test that doesn't require SQLite.
2023-03-01 10:30:38 +08:00
Century Systems
dd629c8f45 asyncdispatch: for NuttX, add destructor to clear global dispatcher. (#21432)
* asyncdispatch: for NuttX, add destructor to clear global dispatcher using atexit().

Signed-off-by: Takeyoshi Kikuchi <kikuchi@centurysys.co.jp>

* std: exitprocs: remove "when defined(nuttx)" block.

Signed-off-by: Takeyoshi Kikuchi <kikuchi@centurysys.co.jp>

---------

Signed-off-by: Takeyoshi Kikuchi <kikuchi@centurysys.co.jp>
2023-02-28 14:38:50 +01:00
Antonis Geralis
83e3320725 Use a cast to suppress KeyError raises (#21451) 2023-02-28 14:17:21 +01:00
ringabout
6fea221d65 Overrides =copy for PackedSets (#21417) 2023-02-27 00:57:36 +01:00
Ikko Eltociear Ashimine
89a60939f8 Fix typo in sourcemap.nim (#21438)
seperated -> separated
2023-02-27 00:57:02 +01:00
Constantine Molchanov
4ae598762e fixes #21439; Add tyOpenArray to genTypeInfo. (#21440)
* fixes #21439; Add tyOpenArray to genTypeInfo.

* Add test.
2023-02-27 00:56:43 +01:00
PhilippMDoerner
425225119a Add mention of breaking change about [_] in generics to changelog (#21437)
Add mention of breaking change to changelog

As described by #21435 , generic proc declarations making use of `_` as generic
parameter are no longer possible. This is a change that was introduced by 
#21192 . During the debate over if this should be part of the intended spec in
#21435 we concluded that it is and thus should be mentioned as a breaking
change in the changelogs.
2023-02-26 16:57:51 +08:00
Dmitry Arkhipenko
b2edfe7a02 Fix: nintendoswitch compilation (#21368)
* Fix: make nintendoswitch someGcc, remove symlink support for nintendoswitch, add getAppFilename for nintendoswitch

* Fix: use getApplHeuristic on nintendoswitch
2023-02-25 11:47:19 +01:00
ringabout
d4782c9e42 closes #17864; add a test case (#21434) 2023-02-25 00:53:04 +08:00
Francis Thérien
7837e57e93 Disable threads for os:any (#21425) 2023-02-24 09:07:35 +01:00
ringabout
bbb6d2c69d fixes #20695; fixes object with distinct defaults and tables (#21428) 2023-02-24 09:02:44 +01:00
Andreas Rumpf
8a19ac2070 fixes #21393 and misc style changes (#21419)
* fixes #21393 and misc style changes

* progress

---------

Co-authored-by: ringabout <43030857+ringabout@users.noreply.github.com>
2023-02-24 09:02:15 +01:00
Francis Thérien
7dc80a7fef Mitigate issues related to compiler options when cross-compiling (#21330)
* Document C compiler options config when cross-compiling

* Allow empty string to override default
2023-02-22 21:10:02 +01:00
ringabout
38f876dd48 fixes #19795; fixes #11852; fixes #19974; remove parsing pipeline, Nim now parses the whole module at one time (#21379)
* fixes #19795; remove parse pipeline

* isScript

* fixes nimscriptapi

* don't touch reorder

* check script

* fixes tests

* it seems implicit imports of system cause troubles

* access the first child of `nkStmtList`

* ignore comments

* minor messages

* perhaps increases hloLoopDetector

* the module is a stmtList, which changes the errors

* fixes nimdoc

* fixes tlinter

* fixes nim  secret tests

* fixes arc_misc

* fixes nim secret tests again

* safe; fixes one more test

* GlobalError is the root cause too

* fixes parsing errors

* put emit types to the cfsForwardTypes section

* fixes #11852; `{.push checks:off}` now works in procs

* disable navigator

* fixes nimdoc

* add tests for JS

* fixes nimsuggest
2023-02-22 20:34:20 +01:00
c-blake
fdd7520257 Fix the TODO portion of recently added posix_fallocate on OS X. (#21387) 2023-02-22 13:54:04 -05:00
Century Systems
ab1d4a5d58 ioselectors_epoll: for NuttX, limit initial numFD to configured value. (#21421)
ioselectors: ioselectors_epoll: for NuttX, limit initial numFD to configured value.

In the NuttX build config, there is a setting called "FS_NEPOLL_DESCRIPTORS".

--------
config FS_NEPOLL_DESCRIPTORS
	int "Maximum number of default epoll descriptors for epoll_create1(2)"
	default 8
	---help---
		The maximum number of default epoll descriptors for epoll_create1(2)
--------

For NuttX, change the number of fd arrays allocated by newSelector() to that value.

Signed-off-by: Takeyoshi Kikuchi <kikuchi@centurysys.co.jp>
2023-02-22 13:53:04 -05:00
Benji York
64a788cafb Fix a couple of small keyword issues. (#21416)
In this section of the manual, "if" should be enclosed in backticks and "elif" should be lower case.
2023-02-22 12:12:10 +01:00
ringabout
a3603c8a6e saves one unnecessary compare which is also a small regression (#21413)
saves one unnecessary compare which is also a sall regression

follow up d30c6419a0
2023-02-21 23:42:28 +01:00
Jake Leahy
0a45543cc1 Specify that address is taken when converter takes a var parameter (#21391)
* Add test case

* closes #21247 Add the sfAddrTaken flag to var parameters in converters

This allows the JS backend to properly pass the parameter as a fat pointer
2023-02-21 12:27:12 +01:00
Ecorous
de65b380ed Add getDataDir proc (#21408)
* Add getDataDir()

* Update lib/std/private/osappdirs.nim

---------

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2023-02-21 12:14:41 +01:00
Jake Leahy
6d423f1856 Make Time work with std/strformat (#21409)
* Add test case

* Remove formatValue template for `Time`

It didn't handle empty specifier correctly which caused it to be blank with strformat
2023-02-21 12:04:27 +01:00
Jake Leahy
e54d3cc418 Support tuples in nim-gdb (#21410)
* Support for printing tuple types

* Add test of printing a tuple

* Add support for printing tuples in GDB

* Forgot to [skip ci]
2023-02-21 12:02:42 +01:00
ringabout
bdc850916f improve invalid module names errors (#21412)
I have seen these questions: "Why I got an invalid module name errors?". To eliminate this kind of questions, We might improve th error messages. Though, the question might evolve into "What is a valid Nim identifier", which should be more searchable on the Internet.
2023-02-21 11:46:50 +01:00
ringabout
ffd6bc8749 csources_v2 can build the ORC-booted compiler; building now uses strict mode (#21411)
* csources_v2 can build the ORC-booted compiler; building now uses strict mode

* test booting in refc
2023-02-21 08:58:45 +01:00
ringabout
f7bd2088aa corrects the linkerexe of riscv64 in config (#21292) 2023-02-21 11:27:42 +08:00
Century Systems
c73c76fdc6 NuttX added supports getrlimit(RLIMIT_NOFILE), so remove NuttX specific codes. (#21385)
async: NuttX added supports getrlimit(RLIMIT_NOFILE), so remove NuttX-specific codes.

Signed-off-by: Takeyoshi Kikuchi <kikuchi@centurysys.co.jp>
2023-02-21 10:38:25 +08:00
Jake Leahy
c66dc913ce Support new runtime with nim-gdb (#21400)
* Add support for orc strings

* Cleaned up testing script

Enums now printing properly

Merged both old and new strings into the one printer

Moving onto sets which seem kinda difficult

* Sets working

Instead of trying to imitate how Nim represents enums, I just call the dollar proc for each enum value

While this runs into problems if the user doesn't call the dollar proc anywhere, I believe its a decent tradeoff

I've cleaned up the error message for when it cannot find dollar proc (Might add in proper message on how to fix)

* Support sequences

V2 runtime seems to have sequences that don't have a len (Guessing its some kind of short seq optimisation?) but I've rolled
the implementation into normal sequences since the implementation is practically the same

* Clean up test program so it isn't using diff

Also don't redirect the first nim compile to /dev/null so that we can check for any compilation errors

I found the diff to be annoying to read (Seeing as the test script already performs diffing)

* Tables are now supported

* Add colours to test output

It was getting difficult to tell apart test output from GDB output so I added colour to better tell them apart

* Both old and new runtime are working

Set exit code in python test script so that this could possibly be added to the CI. Only issue is that it can be flaky (GDB crashes randomly for some reason)

* Remove old code that was commented out

If I need it later I'll just use git

* Remove branch that never runs

* Remove the old test output [skip ci]
2023-02-20 21:19:46 +01:00
ringabout
e896977bd1 closes #1072; add a test case (#21396) 2023-02-19 14:49:19 +08:00
Matt Haggard
6b93db7070 Fix long link commands on macOS (v2) (#21382)
Handle long link commands on macOS with a script, since ar does not support response files
2023-02-17 11:25:15 +01:00
Jake Leahy
13711b101d std/xmltree Add the type of the node when the assertion fails (#21383)
Print the type of the node when the assertion fails

This way the user actually knows what the type was instead of just knowing it failed
2023-02-17 11:24:25 +01:00
Qinsi (James) ZHU
03dd853815 add .replace() with callback to jsre (#21371) 2023-02-16 18:12:48 +01:00
Century Systems
3b9e9fd7b2 Add support for NuttX RTOS. (#21372)
* Add support for NuttX RTOS.

Signed-off-by: Takeyoshi Kikuchi <kikuchi@centurysys.co.jp>

* lib: pure: asyncdispatch: assign to result.

Signed-off-by: Takeyoshi Kikuchi <kikuchi@centurysys.co.jp>

* lib: std: typedthreads: add support for parameters to adjust Thread Stack Size.

Like FreeRTOS/Zephyr, add support for following configurations.

  -d:nimThreadStackSize=xxxxx
  -d:nimThreadStackGuard=yyyy

Signed-off-by: Takeyoshi Kikuchi <kikuchi@centurysys.co.jp>

---------

Signed-off-by: Takeyoshi Kikuchi <kikuchi@centurysys.co.jp>
2023-02-16 13:47:52 +01:00
ringabout
93e4f278a1 add deprecated warnings for {.deadcodeelim: on.} (#21277) 2023-02-16 13:34:32 +08:00
ringabout
fc7385bfda fixes #21360; discarding empty seqs/arrays now raises errors (#21374)
* discarding empty seqs now raises errors

* the same goes for sets
2023-02-16 10:23:35 +08:00
c-blake
c91ef1a09f Fix closeHandle bug, add setFileSize, make resize work on Windows (#21375)
* Add general purpose `setFileSize` (unexported for now).  Use to simplify
`memfiles.open` as well as make robust (via hard allocation, not merely
`ftruncate` address space allocation) on systems with `posix_fallocate`.

As part of this, fix a bad `closeHandle` return check bug on Windows and
add `MemFile.resize` for Windows now that setFileSize makes that easier.

* Adapt existing test to exercise newly portable `MemFile.resize`.

* Since Apple has never provided `posix_fallocate`, provide a fallback.
This is presently written in terms of `ftruncate`, but it can be
improved to use `F_PREALLOCATE` instead, as mentioned in a comment.
2023-02-15 17:41:28 +01:00
ringabout
e24d0e5faf remove legacy code; the first iteration now can build Nim with cpp backend (#21373) 2023-02-15 13:03:11 +01:00
ringabout
56a4d246a4 Refines raises list in osproc (#21323)
* Remove Exception from raises in closeImpl

* Update osproc.nim

* refine errors

* add ValueError

* cast raises

* refactor raises lists

* Update lib/pure/osproc.nim

* Update lib/pure/osproc.nim

---------

Co-authored-by: Antonis Geralis <43617260+planetis-m@users.noreply.github.com>
Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2023-02-14 13:11:14 +01:00
Jake Leahy
cac49694c0 std/asyncjs allow transforming proc types (#21356)
* Add test case

* Implement JS async transform for nnkProcTy
2023-02-14 08:14:19 +01:00
c-blake
1d06c2b6cf This adds parseutils.parseSize, an inverse to strutils.formatSize (#21349)
* This adds `parseutils.parseSize`, an inverse to `strutils.formatSize`
which has existed since 2017.

It is useful for parsing the compiler's own output logs (like SuccessX)
or many other scenarios where "human readable" units have been chosen.
The doc comment and tests explain accepted syntax in detail.

Big units lead to small numbers, often with a fractional part, but we
parse into an `int64` since that is what `formatSize` stringifies and
this is an inverse over partial function slots.  Although metric
prefixes z & y for zettabyte & yottabyte are accepted, these will
saturate the result at `int64.high` unless the qualified number is a
small fraction.  This should not be much of a problem until such sizes
are common (at which point another overload with the parse result
either `float64` or `int128` could be added).

Tests avoids `test()` because of a weakly related static: test() failure
as mentioned in https://github.com/nim-lang/Nim/pull/21325. This is a
more elemental VM failure.  As such, it needs its own failure exhibition
issue that is a smaller test case.  (I am working on that, but unless
there is a burning need to `parseSize` at compile-time before run-time
it need not hold up this PR.)

* This worked with `int` but fails with `int64`.  Try for green tests.

* Lift 2-result matching into a `checkParseSize` template and format as a
table of input & 2 expected outputs which seems nicer and to address
https://github.com/nim-lang/Nim/pull/21349#pullrequestreview-1294407679

* Fix (probably) the i386 trouble by using `int64` consistently.

* Improve documentation by mentioning saturation.

* Improve documentation with `runnableExamples` and a little more detail in
the main doc comment based on excellent code review by @juancarlospaco:
https://github.com/nim-lang/Nim/pull/21349#pullrequestreview-1294564155

* Address some more @juancarlospaco code review concerns.

* Remove a stray space.

* Mention milli-bytes in docs to maybe help clarify why wild conventions
are so prone to going case-insensitive-metric.

* Add some parens.
2023-02-14 08:00:30 +01:00
ringabout
406d302131 allow omitting stmts using finally as post expr blocks; make it consistent with else, except etc. (#21361)
allow omitting stmts using `finally` as post expr blocks
2023-02-14 07:29:30 +01:00
ringabout
684c3b3aeb fixes comments about type bound operations (#21365) 2023-02-14 07:00:29 +01:00
Gabriel Huber
6c15958a83 Change the default stdlib location for Linux packaging (#21328)
* Correctly evaluate the Nim prefix on Posix

* Document new packaging layout
2023-02-12 16:41:27 +01:00
Juan M Gómez
642136ec4f Adds an extra optional argument to vcc: vctoolset Fixes #21335 (#21336) 2023-02-09 16:19:05 -05:00
ringabout
51f410e1d5 megatest now checks refc too (#21341)
* megatest now checks refc too

* fixes refc
2023-02-09 16:14:39 -05:00
ringabout
be4912681f add nimib to important packages (#20697)
r

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2023-02-09 20:00:56 +08:00
Andreas Rumpf
9fb4c2b3c7 fixes #21333; bad codegen for the at operator; [backport:1.6] (#21344) 2023-02-08 20:55:01 +01:00
ringabout
cbb6001d1e fixes backticks in the documentation (#21340) 2023-02-08 18:27:44 +08:00
Ikko Eltociear Ashimine
9f651f05d5 nimgrep: fix typo (#21337)
occurences -> occurrences
2023-02-07 16:15:44 +08:00
ringabout
8e53fba083 replaces pairs with keys and items; saves 8 bytes (#21319)
replace `pairs` with `keys` and `items`
2023-02-02 13:11:20 -05:00
ringabout
17115cbc73 fixes SSL version check logic [backport] (#21324)
* fixed version check logic [backport]

* add ciphersuites

* debug nimble

* fixes returns omission

* finally

* remove debug message

* add ciphersuites

---------

Co-authored-by: Araq <rumpf_a@web.de>
2023-02-02 16:44:14 +01:00
Ivan Yonchovski
43b1b9d077 Fix the nimble build on Windows (#21314)
Fix the build on Windows

- `nimble install` fails on Windows, the `./` is not needed.
2023-02-01 10:38:22 +01:00
Jake Leahy
900fe8f501 Add contains to std/macrocache (#21304)
* Add test cases

* Implement contains for CacheSeq

* Implement contains for CacheTable

* Fix implementation of hasKey

* Remove contains for CacheSeq

Fix runnable examples

I was accidently using --doccmd:skip so I didn't spot the failure locally

* Implement hasKey as a VM callback instead of magic

* Implement suggestions from PR

Co-Authored-By: ringabout <ringabout@users.noreply.github.com>

* Update lib/core/macrocache.nim

---------

Co-authored-by: ringabout <ringabout@users.noreply.github.com>
Co-authored-by: ringabout <43030857+ringabout@users.noreply.github.com>
2023-02-01 10:00:10 +01:00
ringabout
ff8ab06720 fixes #19396; Nimdoc hide nonexported fields (#21305)
* suppresses non-exported fields of types and adds command-line option to re-enable this if desired

* corrected the doctest that produced a CI error

* an embarrassingly bad error in reasoning

* modified a nimdoc test to reflect updated behavior

* needed another change to bring utils.html doctest in sync with update

* add info

* fix nimdoc

* lint

* render postfix

* fixes a problem

* fixes nimdoc

* fix nimdoc

---------

Co-authored-by: johnperry-math <john.perry@usm.edu>
Co-authored-by: johnperry-math <devotus@yahoo.com>
2023-02-01 08:13:40 +01:00
ringabout
cbf3ed9d92 fixes #21317; 1.6.4 regression; etyBaseIndex should return fat pointers [backport 1.6] (#21320)
fixes #21317; regression; etyBaseIndex should return fat pointers
2023-02-01 07:58:12 +01:00
ringabout
b5f64f55d0 fixes #16790; fixes #19075; put big arrays on the constant seqs; don't inline them in the VM; big performance boost (#21318)
* don't inline arrays in VM

* add a test for #19075
2023-01-31 19:22:10 +01:00
ringabout
ebaa07b955 remove md5_old (#21312) 2023-01-31 16:11:44 +01:00
ringabout
4459c272ec remove enumUtilsExist defines (#21309) 2023-01-29 15:11:24 +01:00
ringabout
1431f90d8c Revert "Fix #13093 C++ Atomics: operator= is implicitly deleted because the default definition would be ill-formed " (#21307)
Revert "Fix #13093 C++ Atomics: operator= is implicitly deleted because the default definition would be ill-formed  (#21169)"

This reverts commit a7bae919ad.
2023-01-27 21:41:59 +01:00
Bung
a7bae919ad Fix #13093 C++ Atomics: operator= is implicitly deleted because the default definition would be ill-formed (#21169)
* add test

* fix #17982 Invalid C++ code generation when returning discardable var T

* fix #13093

* cpp atomic good example

* clearify the condition
2023-01-27 09:50:44 +01:00
Ivan Yonchovski
7031ea65cd Implemented basic macro expand functionality (#20579)
* Implemented level based macro expand functionality

- it can handle single macro call or expand whole function/proc/etc and it

- In addition, I have altered the parser to provide the endInfo for the node.
The usefulness of the `endInfo` is not limited to the `expandMacro`
functionality but also it is useful for `ideOutline` functionality and I have
altered the ideOutline functionality to use `endInfo`. Note `endInfo` most of
the time is lost during the AST transformation thus in `nimsuggest.nim` I am
using freshly parsed tree to get the location information.

* Make sure we stop expanding correctly

* Test CI

* Fix tv3_outline.nim
2023-01-27 07:11:30 +01:00
ringabout
4647c7b596 fixes #14409; fixes #10674 VM callbacks switch to table-index seqs (#21297)
* fixes #14409; fixes#10674 VM callbacks switch to table-index seqs

* fixes package name

* reduce runtime cost
2023-01-26 23:49:04 +01:00
ringabout
fc068ee06d fixes #18134; registers formatBiggestFloat in VM (#21299)
fixes #18134; registers formatBiggestFloat in vmops

strformat supports float format in VM
2023-01-26 23:03:59 +01:00
Heechul Ryu
23bd812b0c Update nims.md to use nim e instead of nim in advanced shebang (#21301)
Update nims.md

- suggest a better shebang that works with any filename
- related to https://github.com/nim-lang/Nim/issues/17190
2023-01-26 12:43:55 +01:00
ringabout
af0f3639ec remove dead code in VM (#21296)
remove deadcode in VM
2023-01-25 14:58:52 -05:00
ringabout
c4d3d650ba fixes #21273; fixes an io.readLine off by one bug [backport 1.0] (#21276)
fixes #21273; io.readLine off by one
2023-01-25 14:56:19 -05:00
ringabout
d54a7f078d fixes #21261; always checking nimTestErrorFlag in the main module (#21288)
* fixes #21261; always checking nimTestErrorFlag in the main module

* add a test
2023-01-24 15:37:22 +01:00
ringabout
5e7f7109e1 fixes #21290; deindent if the last same level is a text node (#21293)
* fixes #21290; deindent if the last same level is a text node

* add one more test
2023-01-24 13:35:19 +01:00
ringabout
36e489e69b add md2html, md2tex to cmd helpers (#21295) 2023-01-24 13:33:13 +01:00
ghais
f5ec4fbde3 Update the reference to parseSpec (#21289)
The current reference pointed to the wrong location
2023-01-21 18:07:40 +08:00
ringabout
b82b5d44af fixes #21278; deques.shrink off by one bug (#21284)
fixes #21278; deques.shrink off ny one bug
2023-01-20 11:43:45 +01:00
ringabout
4c74b9b54c switch to official chronos URL (#21283)
ref https://github.com/status-im/nim-chronos/pull/348
2023-01-20 12:48:12 +08:00
Yuriy Glukhov
9afb466d73 Force lambda lifting for getImplTransformed. Hacky. Fixes #19818 (#21031) 2023-01-19 11:46:41 +01:00
metagn
ac982d8a96 close #21257 (#21275)
* close #21257

* fix generics
2023-01-18 21:40:00 +01:00
Ivan Yonchovski
7c6dcfd968 Implicitly set noNimblePath when nimble.lock is present (#21266)
Fixes https://github.com/nim-lang/nimble/issues/1004
2023-01-18 21:38:48 +01:00
Andreas Rumpf
00ef27f4d1 minor parseopt.nim improvements (#21256)
* minor parseopt.nim improvements

* attempt to make CI happy

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2023-01-18 21:37:26 +01:00
Phil Krylov
f04f3e8bf7 std/parsesql: Add OFFSET keyword support. (#21255)
Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2023-01-18 13:11:15 -05:00
ringabout
fc5b7a01ec fixes #21243; ships build_all.sh on Unix [backport] (#21264)
fixes #21243; ships `build_all.sh` on Unix
2023-01-18 13:10:34 -05:00
PhilippMDoerner
fd207827c5 Add docs informing about gotcha of clients (#21262)
* Add docs informing about gotcha of clients

It is a hidden problem that AsyncHttpClient-instances *can not* deal with multiple requests at once.
Similar to normal HttpClients they can only deal with sending one request at a time.
This is not told anywhere in the documentation, but critical information that should be available to the user.

* Update lib/pure/httpclient.nim

fixes typo

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

Co-authored-by: ringabout <43030857+ringabout@users.noreply.github.com>
2023-01-18 13:10:05 -05:00
ringabout
fc35f83eee fixes #21260; add check for illegal recursion for defaults (#21270)
* fixes #21260; add check for illegal recursion for defaults

* fixes differently
2023-01-18 11:52:18 +01:00
ringabout
c4035d7f7c fixes unittest warnings (#21271) 2023-01-18 09:03:03 +01:00
ringabout
cc08a9015e fixes #21263; consider all candidates for concept matches (#21265) 2023-01-17 23:15:23 +01:00
ringabout
30da566d9d switch to official DelaunayNim URL (#21269)
follow up https://github.com/Nycto/DelaunayNim/pull/4#event-8240077930
2023-01-17 12:09:26 +08:00
ringabout
71c60bf6f7 bump nimble (#21259) 2023-01-14 12:30:02 +01:00
Bung
5f41be3b45 fix #20253 (#21174)
* fix #20253

* change NimbleStableCommit

* Update koch.nim

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2023-01-13 15:36:13 +01:00
Jake Leahy
1e52423774 Fix getting custom pragma from generic object (#20481)
* Merge devel

Add another test case

* Fix test

Use getCustomPragmaVal instead of hasCustomPragma

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2023-01-11 20:44:33 -05:00
Anna
e4e947232b testament: make valgrind optional (#21238)
Add a simple switch to enable/disable valgrind support. On by default
2023-01-11 12:23:43 -05:00
Russell Brinson
8be46f3d16 parseopt.nim documentation clarity - default values & cmdEnd in getopt (#21047)
parseopt.nim documentation clarity

Added example for default values to cmd line parameters.
Additionally, added lines in getopt documentation about case switching still requiring the `cmdEnd` kind. Hopefully this clears up any vagueness for those following along in the example but omitting the `cmdEnd` in the case because the documentation said it wasn't needed.
2023-01-11 12:20:39 -05:00
Bung
b68b28fd24 fix typeRel of typeDesc (#21227) 2023-01-09 07:34:51 +01:00
ringabout
a55604a3d8 fixes #21232; highlite.getNextToken() returns gtOperator for '/' in C (#21234) 2023-01-08 15:40:27 +01:00
ringabout
76e4f8afb1 fixes #21209; exclude threads options for JS (#21233) 2023-01-08 15:39:25 +01:00
ringabout
24d297b437 disable bump (#21241) 2023-01-08 16:37:40 +08:00
metagn
05c6db6500 underscores for routine parameters (#21192)
* underscores for routine parameters

fixes #13443, fixes #13804, refs #21121

* add changelog + more tests

* support generics and ensure inferred lambdas work
2023-01-08 06:49:49 +01:00
ringabout
b34412ff0f adds changelog for more architectures support and fixes a link (#21229) 2023-01-06 06:24:58 +01:00
Andrey Makarov
2620da9bf9 docgen: implement cross-document links (#20990)
* docgen: implement cross-document links

Fully implements https://github.com/nim-lang/RFCs/issues/125
Follow-up of: https://github.com/nim-lang/Nim/pull/18642 (for internal links)
and https://github.com/nim-lang/Nim/issues/20127.

Overview
--------

Explicit import-like directive is required, called `.. importdoc::`.
(the syntax is % RST, Markdown will use it for a while).

Then one can reference any symbols/headings/anchors, as if they
were in the local file (but they will be prefixed with a module name
or markup document in link text).
It's possible to reference anything from anywhere (any direction
in `.nim`/`.md`/`.rst` files).

See `doc/docgen.md` for full description.

Working is based on `.idx` files, hence one needs to generate
all `.idx` beforehand. A dedicated option `--index:only` is introduced
(and a separate stage for `--index:only` is added to `kochdocs.nim`).

Performance note
----------------

Full run for `./koch docs` now takes 185% of the time before this PR.
(After: 315 s, before: 170 s on my PC).
All the time seems to be spent on `--index:only` run, which takes
almost as much (85%) of normal doc run -- it seems that most time
is spent on file parsing, turning off HTML generation phase has not
helped much.
(One could avoid it by specifying list of files that can be referenced
and pre-processing only them. But it can become error-prone and I assume
that these linke will be **everywhere** in the repository anyway,
especially considering https://github.com/nim-lang/RFCs/issues/478.
So every `.nim`/`.md` file is processed for `.idx` first).

But that's all without significant part of repository converted to
cross-module auto links. To estimate impact I checked the time for
`doc`ing a few files (after all indexes have been generated), and
everywhere difference was **negligible**.
E.g. for `lib/std/private/osfiles.nim` that `importdoc`s large
`os.idx` and hence should have been a case with relatively large
performance impact, but:

* After: 0.59 s.
* Before: 0.59 s.

So Nim compiler works so slow that doc part basically does not matter :-)

Testing
-------

1) added `extlinks` test to `nimdoc/`
2) checked that `theindex.html` is still correct
2) fixed broken auto-links for modules that were derived from `os.nim`
   by adding appropriate ``importdoc``

Implementation note
-------------------

Parsing and formating of `.idx` entries is moved into a dedicated
`rstidx.nim` module from `rstgen.nim`.

`.idx` file format changed:

* fields are not escaped in most cases because we need original
  strings for referencing, not HTML ones
  (the exception is linkTitle for titles and headings).
  Escaping happens later -- on the stage of `rstgen` buildIndex, etc.
* all lines have fixed number of columns 6
* added discriminator tag as a first column,
  it always allows distinguish Nim/markup entries, titles/headings, etc.
  `rstgen` does not rely any more (in most cases) on ad-hoc logic
  to determine what type each entry is.
* there is now always a title entry added at the first line.
* add a line number as 6th column
* linkTitle (4th) column has a different format: before it was like
  `module: funcName()`, now it's `proc funcName()`.
  (This format is also propagated to `theindex.html` and search results,
  I kept it that way since I like it more though it's discussible.)
  This column is what used for Nim symbols resolution.
* also changed details on column format for headings and titles:
  "keyword" is original, "linkTitle" is HTML one

* fix paths on Windows + more clear code

* Update compiler/docgen.nim

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

* Handle .md and .nim paths uniformly in findRefFile

* handle titles better + more comments

* don't allow markup overwrite index title for .nim files

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2023-01-04 15:19:01 -05:00
Bung
b2328b44ba make it printer friendly (#21218) 2023-01-04 15:10:44 -05:00
ringabout
81b7f9108f fixes #21207; reports redefinition error in the definition of enums (#21217)
* fixes #21207;  reports redefinition in the enums

* add a test
2023-01-03 08:15:10 +01:00
ringabout
3b965f463b bump csource_v2 to include fix for linking parameter maximum length (#21216)
> If accepted, I believe it should be used in csources_v2 and also backport 2.0

ref https://github.com/nim-lang/Nim/pull/21186
2023-01-02 22:10:26 +08:00
Andreas Rumpf
cf1b16ef8b minor code cleanups (#21215) 2023-01-02 10:39:17 +01:00
Chavdar Ivanov
e9ed090c33 Update nim.cfg (#21204)
tlsEmulation:on under NetBSD-10Beta and NetBSD-current produces an executable which crashes immediately as follows:

Core was generated by `koch'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0  0x000000000047b4c2 in nimZeroMem ()
(gdb) bt
#0  0x000000000047b4c2 in nimZeroMem ()
#1  0x00000000004897b2 in threadVarAlloc__system_2162 ()
#2  0x000000000048980e in initThreadVarsEmulation ()
#3  0x0000000000489848 in PreMain ()
#4  0x000000000048986a in NimMain ()
#5  0x00000000004898a9 in main ()

I can't speak about the other BSDs.
2023-01-02 09:16:18 +01:00
ringabout
5b20f0685c fixes pragmas reorder (#21205) 2023-01-01 10:25:04 +01:00
ringabout
4032eb4baa fixes #20906; update copyright year [backport 1.6] (#21210) 2023-01-01 16:51:58 +08:00
rockcavera
e5639408d5 avoiding unnecessary allocation for dollar IpAddress (#21199)
* avoiding allocating an unnecessary byte for IPv4

The inet.h file uses 16 as the string in C needs the last null byte
1b929c02af/include/linux/inet.h (L49)

However, strings in Nim do not need this. So one byte is being allocated unnecessary and will never be used.

* avoid unnecessary allocation in IPv6 dollar

It is currently allocating 48 bytes. However, the Nim implementation for IPv6 will print a maximum of 39 characters. Nim does not implement IPv6 "0000:0000:0000:0000:0000:ffff:255.255.255.255" (45 characters) nor "0000:0000:0000:0000:0000:ffff:255.255.255.255%3" (47 characters). 

The indication in inet.h for 48 is due to the maximum use of 47 characters of a C string that needs a null byte at the end. So 48.
1b929c02af/include/linux/inet.h (L50)
2022-12-30 09:20:32 +01:00
Bung
c598d0b6ec fix #15117 zero size array cause incorrect codegen for VCC compiler (#21197)
fix #15117
2022-12-30 00:50:12 +01:00
ringabout
ebd1c678be fixes #21195; std/assertions continue to use sysFatal when nimPreviewSlimSystem is not defined (#21196)
* fixes #21195; `std/assertions` continue to use `sysFatal`

* try includes

* make `std/assertions` self-contained

* fixes tests

* fixes tests
2022-12-29 14:15:08 -05:00
ringabout
705da9d452 fixes #14444; add genLineDir before assignment (#21201)
* fixes #14444; add `genLineDir` before raises

* add a test case

* fixes differently
2022-12-29 17:06:57 +01:00
ringabout
e602ebeb66 fixes #19997; ships changelogs directory for a release (#21200)
fixes #19997; ship changelogs directory for a release
2022-12-29 08:29:40 +01:00
ringabout
761c5a0830 less verbose type mismatch messages (#21191)
* less verbose type mismatch messages

* Update compiler/types.nim

* fixes i386

* fixes i386
2022-12-28 20:54:15 +01:00
ringabout
646932b3f3 fixes warnings when building csources (#21194)
* replace `symbolfiles` with `incremental`; fixes warnings when build csources

* fixes self conversion warnings
2022-12-28 20:41:27 +01:00
ringabout
4b63ac4b87 fixes #21171; dynamic acyclic refs need to use dyn decRef (#21184)
* fixes #21171; dyn destructors for acyclic inherited  refs

* add a test

* Update compiler/liftdestructors.nim
2022-12-28 16:23:37 +01:00
Bung
7a74c2dc3a fix #14667 (#21190) 2022-12-28 08:28:48 +01:00
Jake Leahy
3d5dbf8f96 Fix nimsuggest not suggesting fields in when theres static parameters (#21189)
Don't check against empty arguments

Add test case
2022-12-28 07:35:11 +01:00
rockcavera
9efa56a8bb [backport: 2.0] prevents the jsonscript command from exceeding the maximum length of a command line during linking (#21186) 2022-12-28 10:40:17 +08:00
Phil Krylov
9e35631191 std/encodings: Fix open() documentation in regard to exception raised (#21187) 2022-12-28 10:26:52 +08:00
metagn
5684093135 fix for bad error message with const in case statement (#21182)
* preliminary fix for bad error message with const

* add test case

* fix tmatrixconcept and tmatrixlib
2022-12-27 21:24:00 +01:00
Andreas Rumpf
82d80e6e2c atlas: minor doc improvements (#21183)
* closes #20808

* atlas: better docs
2022-12-27 14:30:26 +01:00
Bung
f232329bb1 add test case for #20289 (#21180) 2022-12-27 12:07:15 +01:00
rockcavera
9b4516fbcb fix in msg doAssert() to update grammar.txt (#21179) 2022-12-27 12:13:05 +08:00
ringabout
f7c203fb6c remove legacy code (#21134)
* remove legacy code

* fixes
2022-12-26 13:20:05 +01:00
ringabout
b08c50bb55 sync some changes from release notes (#21173) 2022-12-26 06:52:40 +01:00
ringabout
9323cb7b2a enforce void for nkWhileStmt [backport: 2.0] (#21170)
enforce void for nkWhileStmt
2022-12-24 10:37:32 +01:00
Jake Leahy
86a6c90c9e Make search results be relative to documentation root (#21145)
Use Nim instead of JS for searching
2022-12-23 13:20:51 -05:00
ringabout
ac5a36c0a4 re and nre now link to regex and tinyre (#21161) 2022-12-23 10:50:07 -05:00
ringabout
0ffc322cf6 add the cpp target (#21164)
The issue is related to cpp codegen, the previous test doesn't test cpp backend, which will join into the megatest.
2022-12-23 22:31:53 +08:00
Bung
0b319fee3d fix #20997 calling system.card[T](x: set[T]) with T of int8 or uint8 … (#21010)
* fix #20997 calling system.card[T](x: set[T]) with T of int8 or uint8 uses mismatched C array sizes
* fullfil set variant
2022-12-23 12:20:25 +01:00
Bung
ca9c74391a fix #11634 (#21146) 2022-12-23 11:32:03 +01:00
Bung
13251c2ac9 fix #12946 Bad C++ codegen on distinct generics C++ types (#21157) 2022-12-23 09:47:01 +01:00
Jaremy Creechley
3bba2b34fd fix socket send for string types (#21155)
* fix socket send for string types

* include windows version

Co-authored-by: ringabout <43030857+ringabout@users.noreply.github.com>
2022-12-22 21:43:27 +01:00
Jake Leahy
18c115c8d0 Don't repeat suggestions for same symbol (#21140)
* Track seen module graphs so symbols from the same module aren't repeated
Add test case

* Track symbols instead of modules

* Don't show duplicate symbols in spell checker

Removes the declared location from the message. Since we don't show duplicates anymore it would be a bit misleading if we only show the location for the first declaration of the symbol
2022-12-22 14:44:10 +01:00
metagn
37daed3897 remove misleading slimsystem deprecated warnings (#21156)
refs #20967
2022-12-22 09:54:41 +01:00
Peder Bergebakken Sundt
314a24472e add link to setutils in system module docs (#21130) 2022-12-22 09:54:17 +01:00
Michael Voronin
7931bdac95 Feature/xmltree additions (#20988)
* [change] add/insert/delete family of xmltree expanded with several variations. Added replace methods family

* [change] Lifted child limitations on insert methods (consulted with @araq)

* [tests] add/insert/replace/delete of xmltree XmlNodes tests added
2022-12-22 08:32:12 +01:00
ringabout
93b59da490 fixes #20244; fixes castSizes warnings (#21102)
* fixes #20244; fixes castSizes warnings

* fixes js

* fixes js

* fixes js

* fixes

* typo

* extend using uint64

* Update lib/std/syncio.nim
2022-12-22 08:27:11 +01:00
Jake Leahy
70fe360456 Use ErrorColor when a warning that is turned into an error is raised (#21131)
Use ErrorColor when a warning that is turned into an error is raised
2022-12-22 08:25:24 +01:00
Bung
c5a72ebddd fix #16541 (#21148) 2022-12-22 06:16:25 +01:00
Peter Munch-Ellingsen
613829f7a4 Implement setLineInfo (#21153)
* Implement setLineInfo

* Add tests
2022-12-22 04:34:36 +01:00
ringabout
d0721eadf8 fixes #21144; try expression will not match the less indentation except (#21152)
fixes #21144; try expression will not match the less indent except
2022-12-21 21:46:14 +01:00
ringabout
81d8ea95af bump csource_v2 to include fixes for macos m1 (#21147) 2022-12-21 17:18:47 +08:00
Luca Guzzon
8a77798dac ucpu fix-up for arm64 value on macos m1 (#21142) 2022-12-20 20:29:42 +01:00
ringabout
0aec095b26 fixes #19292; fixes #21122; fixes putEnv and setEnv with vcc (#21143)
* fixes #19292; fixes 21122; fixes putEnv and setEnv with vcc

* add a test
2022-12-20 20:26:32 +01:00
Bung
40b5c4c4c3 fix #20248;fix #6215;turns into simple CT error (#21141) 2022-12-20 20:23:48 +01:00
ringabout
886572a516 disable "Warning: gc is deprecated" in compiler (#21137)
* disable "Warning: gc is deprecated" in compiler

* Apply @tersec 's suggestion
2022-12-20 15:04:13 +08:00
Bung
e278a781fc fix #21109 (#21127) 2022-12-19 12:35:15 +01:00
ringabout
70c575095e add changelog for the new strict function checking algorithm (#21129)
add changelog for the new strict function checking
2022-12-19 17:56:49 +08:00
ringabout
53eed2be45 close #11705; add a testcase (#21128) 2022-12-18 22:31:13 +08:00
ringabout
100b304ac2 fixes misplaced changelog entries; pre-existing issue (#21125)
* move misplaced changelog entries to the right place

* fixes misplaced changelog
2022-12-17 21:42:29 +08:00
ringabout
b8d200683a remove unused imports (#21126) 2022-12-17 20:44:30 +08:00
ringabout
ae4645e8df add 2.0 changelog (#21107)
[backport: 2.0] add v2.0 changelog
2022-12-17 09:28:59 +01:00
ringabout
d83f66a24d fixes #21116; always mangles the param (#21121)
* fixes #21116; always mangles the param

* idOrSig

* fixes tests

* Apply suggestions from code review
2022-12-17 09:10:56 +01:00
ringabout
7fa983f5e6 Nim now ships nimble with 0.14.1 version (#21120)
* Nimble now uses latest patch

* Update koch.nim
2022-12-17 00:21:07 +08:00
ringabout
296e7f598e Bump the devel version to 1.9.1 (#21117) 2022-12-16 19:49:26 +08:00
ringabout
84200f28a1 bump csource_v2 hash (#21118) 2022-12-16 16:42:31 +08:00
Bung
a9bd78d579 fix #12122 (#21096) 2022-12-16 08:01:15 +01:00
ringabout
8a3b76b287 csource building prefers bin/nim (#21115) 2022-12-16 07:59:18 +01:00
ringabout
644318ad9c the devel branch now uses csources_v2 (#21108)
* the devel branch now uses csources_v2

* fixes hash

* bump csources_v2
2022-12-16 07:58:40 +01:00
ringabout
78b68421da fixes chronicles (#21114) 2022-12-16 11:36:52 +08:00
Jake Leahy
d00477dffb Check file exists in {.compile.} pragma (#21105)
* Add test

* Check file exists before adding it into compilation

* Make error message look like other error messages

i.e. following the format `error msg: file`
2022-12-15 19:22:45 +01:00
Bung
8054be6e52 fix #20588 (#21104) 2022-12-15 16:12:17 +01:00
Jake Leahy
d88f46df38 Make async stacktraces less verbose (#21091)
* Name iterators something human readable

Remove intermediate async procs from stacktraces

Clean async traceback message from reraises message

* Remove unused import/variable

* Fix failing tests

Don't add {.stackTrace: off.} to anonymous procs (They already don't appear in stacktrace)

* Fix failing tests in pragma category

Now check that the nim is a routine type first so we don't run into any assertion defects

* Hide stack trace pragma in docs and update doc tests

User doesn't need to know if something won't appear so this more becomes verbose noise

If this is a bad idea we can always add a `when defined(nimdoc)` switch so we don't add {.stackTrace: off.} to the Future[T] returning proc for docs
2022-12-15 16:05:34 +01:00
ringabout
91ce8c385d fix #19580; add warning for bare except: clause (#21099)
* fix #19580; add warning for bare except: clause

* fixes some easy ones

* Update doc/manual.md

* fixes docs

* Update changelog.md

* addition

* Apply suggestions from code review

Co-authored-by: Jacek Sieka <arnetheduck@gmail.com>

* Update doc/tut2.md

Co-authored-by: Jacek Sieka <arnetheduck@gmail.com>
2022-12-15 06:45:36 +01:00
metagn
9a50033d5b generic define pragma + string alias (#20979)
* generic `define` pragma + string alias

* clean

* add tests and document

* remove char/float, minimize changelog
2022-12-13 21:20:55 +01:00
Aditya Siram
2564b5c938 Fix #20416. Enable the recursion limit for ref/ptr types. (#21092) 2022-12-13 22:57:07 +08:00
Xavier Noria
e4aadcf1c1 Document that system:pop() may raise IndexDefect (#21070)
* Document system:pop() may raise IndexDefect

* Add backticks to KeyError
2022-12-13 08:47:01 +01:00
Jake Leahy
7ae7832f76 JS backend properly extends string with setLen (#21087)
* Add test case

* Extend string with '0' when setting length to be longer
2022-12-13 08:43:37 +01:00
Jake Leahy
1fefb8e92a Refactor JS sourcemap generator (#21053)
* Parse the new line format

* Fix pattern

Didn't have space after the path

* Remove duplicate sources

Sources would sometimes double up with a new line at the end

* Remove unused variable

* Refactor sourcemap.nim

Removes the multiple translations needed, now goes from single high level type to the final SourceMap

Adds documentation for procs

* Line numbers line up properly now

Files aren't linking correctly though

* Files now link up correctly

Lines are sometimes off but overall seems pretty good

Just need to implement parser

* Add column info to output

Add sourceMappingURL to rope directly to prevent copy

* Properly handle columns

* Remove debug lines

* Add testcase

* Finish testcase

* Use the outdir folder instead of the folder the test is in to find the sourcemap

Co-authored-by: ringabout <43030857+ringabout@users.noreply.github.com>
2022-12-13 12:21:51 +08:00
ringabout
d84f64d2e7 add CI for version-2-0 branch (#21084) 2022-12-13 09:52:35 +08:00
Jake Leahy
b0a850adbf Nimsuggest now defines the backends symbol (#21083)
* Add testcase

* Define the backend symbol

* Remove unneeded whitespace
2022-12-12 22:19:02 +01:00
ringabout
4388636010 fixes #21043; fixes a named exception in the infixAs expression which generate an implicit uninitialized let statement (#21081)
* fixes #21043; fixes a named exception in the infixAs expression which generate an implicit uninitialized let statement

* Update compiler/sempass2.nim

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

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2022-12-12 23:14:44 +08:00
ringabout
584cfa6af8 remove implicitDeref feature enum (#21075)
remove implicitDeref feature
2022-12-12 15:59:09 +01:00
ringabout
fd7da7da62 add a changelog for nimble (#21078) 2022-12-12 14:57:27 +01:00
ringabout
19923aa8b7 work around chronos (#21079)
* work around chronos

chronos has tests against the devel branch, it will be eventually fine.

* Apply suggestions from code review

* Update testament/important_packages.nim
2022-12-12 21:14:24 +08:00
Andreas Rumpf
28bed059aa closes #20808 (#21077) 2022-12-12 11:46:51 +01:00
Jake Leahy
cbeefc877c Docs expand using parameters (#21076)
* Trying to fix by changing renderer

* add renderExpandUsing flag

This flag makes the renderer expand parameters that use using statement to have their full type

* Update docs

* Make comment better explain why checking for nkSym

* Fix nil access when macro/template has parameter with no type

* Fix nil access when node is not semmed yet
2022-12-12 07:44:17 +01:00
ringabout
b981f3eeb7 ship a modern nimble with lock files support (#21061)
* change `include genode/env` to an import 

ref 0b262e9496 (diff-8718bd20d8f61d6638d3d64b19efc31bcd40a6d5be8215b2a1f0b75ed93e8d56)

* fixes comments

* ship a modern nimble with lock files support

* not sure whether the latest nimble has a regression

now I'm trying  0.14.0

* change `pkgs` to `pkgs2` (#21073)

* overwrite problematic packages

* Apply suggestions from code review

* Apply suggestions from code review

* Apply suggestions from code review
2022-12-12 07:25:39 +01:00
Bung
5917c2d5b7 fix #15836 proc arg return type auto unexpectly match proc with concr… (#21065)
* fix #15836 proc arg return type auto unexpectly match proc with concrete type

* fix #16244

* add test case for #12869
2022-12-12 06:26:18 +01:00
Andreas Rumpf
3812d91390 alternative, much simpler algorithm for strict func checking (#21066)
* alternative, much simpler algorithm for strict func checking

* forgot to git add new compiler module

* new spec is incredibly simple to describe

* fixes bigints regression

* typos

* closes #16305; closes #17387; closes #20863
2022-12-11 16:58:50 +01:00
Jake Leahy
c7493bbdd0 multisync now allows tuples in return type (#21074)
* Add test case

* Use .toStrLit() on param node first

This means that more complex types are fully rendered
2022-12-11 14:44:41 +01:00
Bung
1585bfec3b fix #16758 Nim crashes in fixAbstractType (#20855)
* fix #16758 Nim crashes in fixAbstractType

* Update compiler/semexprs.nim

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

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2022-12-11 06:58:29 +01:00
ringabout
07be1791ba fix #21045; getTime with vmopsDanger is broken; alternative to #21054 (#21056)
* fix #21045 getTime with vmopsDanger is broken; alternative to #21054

* typo
2022-12-10 18:57:19 +01:00
ringabout
7a18c1ef44 clean up the documentation of threads (#21067)
* clean up the documentation of threads

* cleanup
2022-12-10 23:23:31 +08:00
Andreas Rumpf
b59c657be3 fixes #21062 (#21068) 2022-12-10 16:21:43 +01:00
Andreas Rumpf
2ebd71bfd4 tiny refactoring related to sink parameter inference logic (#21064)
* tiny refactoring related to sink parameter inference logic

* Update compiler/sempass2.nim
2022-12-10 15:42:22 +01:00
Jake Leahy
f330b33e2b Use a unique name for template in async macro return (#21058)
Use unique template name
2022-12-10 09:15:45 +08:00
ringabout
db56fc3bcb Revert "fix #15836 proc arg return type auto unexpectly match proc with concr…" (#21057)
Revert "fix #15836 proc arg return type auto unexpectly match proc with concr… (#21044)"

This reverts commit 0cd9bdcf9f.
2022-12-09 21:38:55 +01:00
Jake Leahy
da3274d1b3 Implicit return working for async proc (#20933)
* Implicit return working for asyncdispatch proc

Closes #11558

* Test case

* Test that return value is actually used

* Update tests/async/t11558.nim

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2022-12-09 18:10:33 +01:00
Bung
0cd9bdcf9f fix #15836 proc arg return type auto unexpectly match proc with concr… (#21044)
fix #15836 proc arg return type auto unexpectly match proc with concrete type
2022-12-09 18:01:13 +01:00
ringabout
ef190f349d remove duplicate assignment (#21050)
`newNodeIT` has already assigned `n.typ` to x.
2022-12-09 08:50:35 +08:00
Juan Carlos
f8e64d879c Remove deprecated rightSize (#21011)
* Remove deprecated rightSize nop

* Remove deprecated rightSize nop
2022-12-08 15:26:58 +01:00
Vindaar
0a1d4ba842 fix issue #20922 by handling missing expr in exprList for tkOf (#20930)
* fix issue #20922 by handling missing expr in `exprList` for `tkOf`

* fix line numbers in test case

* rewrite exprList requiring expr, add optionalExprList for except

As suggested by @metagn.

* update test case to reflect new code

* update grammar.txt

* update line numbers in test case taking into account nimout

Given the number of errors that are produced it seems easier to do it
this way instead of using `tt.Error`.
2022-12-08 10:59:13 +01:00
Xavier Noria
e669835665 Mention toSet in the docs of the set type (#21037) 2022-12-08 10:58:00 +01:00
Emery Hemingway
696def2bf7 macros.customPragmaNode: walk brackets on brackets (#21040) 2022-12-08 10:57:26 +01:00
ringabout
c5eb3fd4f0 fixes #9839; fixes noReturn pragma doesn't work for non-simple templates (#21048) 2022-12-08 10:37:02 +01:00
ringabout
4480fd3e93 fixes #16656; add nre to lib.md (#21042) 2022-12-08 08:51:31 +01:00
ringabout
4da3ead294 fixes strictnotnil documentation; comment unfinished sections (#21041)
fixes documentation; comment unfinished sections
2022-12-08 10:06:48 +08:00
ringabout
53fbb497e9 add a changelog for std/cmdline (#21039)
for a changelog for `std/cmdline`
2022-12-08 10:06:25 +08:00
ringabout
d6b485493d switch to the official URL of nimquery (#21038)
ref 3f728fb480
2022-12-07 11:33:31 +08:00
ringabout
9ba07edb2e build the documentation of official packages (#20986)
* remove db stuffs

* remove punycode

* remove

* fixes script

* add cloner

* patches

* disable

* patch

* fixes external packages

* disable two packages

* preview documentation build

* try again

* fixes URL

* fixes a bug

* simplify

* fixes documentaion

* fixes

* Apply suggestions from code review
2022-12-06 22:37:16 +08:00
metagn
4ca2dcb404 Named arguments in commands + many grammar fixes (#20994)
* Breaking parser changes, implement https://github.com/nim-lang/RFCs/issues/442

Types are separated from expressions and better reflected in the grammar.

* add test

* more accurate grammar

* fix keyword typedescs

* accept expressions in proc argument lists

* CI "fixes"

* fixes

* allow full ref expressions again, adapt old tests

* cleanup, fix some tests

* improve grammar, try and revert semtypes change

* restrict sigil binding to identOrLiteral

* fix, should have caught this immediately

* add changelog entry, fix double not nil bug

* correct grammar

* change section

* fix

* real fix hopefully

* fix test

* support LL(1) for tuples

* make grammar.txt too
2022-12-06 13:11:56 +01:00
ringabout
1564ae650f fixes #21027; cast expressions need a type (#21029)
* fixes #21027; cast expressions need a type

* Apply suggestions from code review

Thanks to @beef331
2022-12-06 13:09:50 +01:00
ringabout
b2c7019006 definite assignment analysis for let (#21024)
* draft for let daa

* patch

* fixes bugs

* errors for global let variable reassignments

* checkpoint

* out param accepts let

* add more tests

* add documentation

* merge tests
2022-12-06 10:19:12 +01:00
metagn
6d8cf25bd7 deprecate do: meaning do (): + misc cleanup (#20927)
* test disable do: block lambda lifting

* fix last test [skip ci]

* deprecate `do:` meaning `do ():` + misc cleanup

closes https://github.com/nim-lang/RFCs/issues/486

* oops

* fix

* no idea what could be causing nimsuggest failure other than this

* ensure ci works
2022-12-06 09:44:26 +01:00
metagn
739e1badb6 stdlib organization & documentation improvements (#20971)
* stdlib organization & documentation improvements

* fix CI

* Update doc/lib.md

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

* fix ci, remove jshttpcore, export in jsfetch instead

* fix alphabetical order violations

* add cmdline, db_odbc

Co-authored-by: Juan Carlos <juancarlospaco@gmail.com>
2022-12-06 09:37:03 +01:00
Bung
5d469686b0 fix #20829 Regression in int64 type matching since (#21019)
fix #20829 Regression in int64 type matching
2022-12-06 07:44:54 +01:00
ringabout
feb0481ba3 Revert "fixes #20883; Unspecified generic on default value segfaults the compiler" (#21028)
Revert "fixes #20883; Unspecified generic on default value segfaults the compiler (#20917)"

This reverts commit 10b6e4f5b4.
2022-12-06 12:50:16 +08:00
metagn
e98efdcc5e fix #16639 (#21017) 2022-12-05 22:52:49 +01:00
Yuriy Glukhov
c47d5196be Dont produce initing moves for sfNoInit variables in closure env (#21026) 2022-12-05 22:49:31 +01:00
ringabout
b83bd282dc fixes #20954; bounchecks for len(toOpenArray()) [backport] (#20956)
* bounchecks for len(toOpenArray())

* add a testcase
2022-12-05 22:27:18 +01:00
ringabout
a8090f7d65 fixes isLocalVarSym; an implicit global is a global nonetheless (#21025)
fixes isLocalVarSym; an implicit global is a global nonetheless
2022-12-05 22:24:36 +01:00
Dmitry Arkhipenko
794bcc8029 Add: missing nintendo-switch define (#21009) 2022-12-05 07:24:24 +01:00
ringabout
6f96c4bc96 ref #20846; give a deprecation message for overriding = hook (#21020)
give a deprecation message for overriding `=` hook
2022-12-05 07:13:51 +01:00
Juan Carlos
1b5e03f975 Remove deprecated posix.CLONE_STOPPED (#21012)
* Remove deprecated CLONE_STOPPED

* Remove deprecated CLONE_STOPPED
2022-12-05 06:53:40 +01:00
ringabout
78b387d948 fixes deprecation message by update action versions (#21021) 2022-12-05 12:37:23 +08:00
metagn
5536f74992 fix #20996 (#21016)
* fix #20996

* hopefully fix
2022-12-04 20:37:23 +01:00
ringabout
55373e65b4 unpublic arrayWith and rename it to nimArrayWith (#21006)
* unpublic arrayWith

* unindent
2022-12-04 15:39:14 +08:00
Michal Maršálek
83493e4294 Update prelude example (#21005)
comment to match what's actually being imported.
2022-12-03 21:25:49 +08:00
ringabout
ece41d2605 minor cleanup; correct the module name (#21001)
* minor cleanup 

follow up https://github.com/nim-lang/Nim/pull/20946

* Update lib/std/cmdline.nim

* Update lib/std/cmdline.nim

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2022-12-02 15:10:08 -05:00
metagn
79ec6d677c Add back error message to tprevent_forloopvar_mutations (#20992) 2022-12-02 16:19:26 +08:00
ringabout
10b6e4f5b4 fixes #20883; Unspecified generic on default value segfaults the compiler (#20917)
test CI
2022-12-01 22:04:11 +01:00
ringabout
8266750497 [unittest] remove unnecessay export for testing (#20868) 2022-12-01 14:31:48 -05:00
Ikko Ashimine
a104aa4714 IC: fix typo in rodfiles.nim (#20989)
preceeded -> preceded
2022-12-01 14:26:59 -05:00
Bung
658b28dc57 tyInt tyUint fit target int bit width (#20829) 2022-12-01 13:34:00 +01:00
ringabout
a70d3abd37 replace data init function with consts for typeinfov2 (#20977)
* replace data initial function with consts for typeinfov2

* fixes

* fixes

* workaround C++

* C++ keeps the previous implementaion

* fixes
2022-12-01 13:29:58 +01:00
ringabout
54f5ab12b7 add smtp to important packages (#20984) 2022-12-01 08:14:42 +01:00
metagn
2449c37137 better procvar ambiguity errors, clean up after #20457 (#20932)
* better procvar ambiguity errors, clean up after #20457

fixes #6359, fixes #13849

* only trigger on closedsymchoice again

* new approach

* add manual entry for ambiguous enums too

* add indent [skip ci]

* move to proc
2022-12-01 08:01:13 +01:00
Federico Ceratto
b36f5119ae Add HPPA and sparc64 architectures (#20934)
* Add comments on CPU arch detection

* Support HPPA/hppa/parisc64 CPU architecture

* Support sparc64 CPU architecture

* Update tools/niminst/makefile.nimf

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2022-12-01 12:48:47 +08:00
ringabout
17ac8c31bf move smtp to nimble packages (#20953)
* move `smtp` to nimble packages

* fixes

* install smtp

* yes
2022-11-30 21:52:36 +01:00
ringabout
a7133e0594 removed unused sections in codegen (#20976) 2022-11-30 21:51:13 +01:00
IgorDeepakM
84ea62ea0d Move command line parameter code (#20946)
Command line paramater code moved from os.nim to cmdparam.nim

Co-authored-by: IgorDeepakM <IgorDeepak@noreply.com>
2022-11-30 11:00:26 +01:00
Chavdar Ivanov
8f728ace35 Update tssl.nim (#20973)
This test hangs also under NetBSD and prevents the rest of the tests to carry over to the end.
2022-11-30 07:21:47 +08:00
metagn
ce971400c0 dom: remove X* = ref XObj [backport] (#20910)
dom: remove X* = ref XObj
2022-11-29 14:24:51 -05:00
rockcavera
9c5061eab7 fix #20969 - making vcc work again with cpp backend (#20970)
Update sysatomics.nim
2022-11-29 14:07:17 -05:00
ringabout
09b8f989b4 add pkg/asyncftpclient to important packages (#20964) 2022-11-29 23:49:38 +08:00
Jaremy Creechley
5658e8e5c5 Add --genCDeps for better integration with CMake (#20950)
* add gencdeps option

* add case statement

* Update compiler/main.nim

* Update compiler/main.nim

* Apply suggestions from code review

Fixes

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

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2022-11-29 15:27:48 +01:00
ringabout
77a337a39a fixes documentation regression (#20960)
follow up https://github.com/nim-lang/Nim/pull/20371
2022-11-29 14:49:40 +08:00
ringabout
3d5edb41be fixes #20958; fixes the return type of slice function [backport] (#20959)
* fixes #20958; fixes the return type of slice function

* add a testcase
2022-11-29 07:21:44 +01:00
ringabout
d4afa53fd5 fixes #13583; enforce void for nkWhileStmt (#20947)
* fixes #13583; enfore void for nkWhileStmt

* one more case
2022-11-29 06:41:38 +01:00
Anna
b5a008bac8 Allow some tests to run without network (#20955)
* thttpclient.nim: respect NIM_TESTAMENT_REMOTE_NETWORKING

* tnetconnect.nim: respect NIM_TESTAMENT_REMOTE_NETWORKING
2022-11-29 06:40:28 +01:00
metagn
15d00ca0e1 allow proc expressions in place of statements (#20935)
properly fixes #18714
2022-11-29 06:37:00 +01:00
metagn
555c5ed1a7 fix bugs with dot & call operators [backport] (#20931)
* better error messages for dot operators [backport]

fixes #13063

* also fixes #7777

* fix #6981 and #9831 too

* fix

* minor improvement

* sus test fixes

* make test multiplatform lol

* fix nimsuggest test, extra improvements
2022-11-28 21:33:02 +01:00
ringabout
f31dc63169 move asyncftpclient to nimble packages (#20952) 2022-11-28 21:17:50 +01:00
Juan Carlos
dd57410afe Improve jsformdata (#20929)
* jsformdata now accepts Blob data type similar to JS

* jsformdata now accepts Blob data type similar to JS
2022-11-28 15:15:44 -05:00
Federico Ceratto
8a68ed65d0 Support IBM Z architecture (#20943) 2022-11-28 13:33:09 -05:00
Jake Leahy
d26b1232ee Add nkFastAsgn into semExpr (#20939)
* Add nkFastAsgn into case statement

* Add test case
2022-11-27 20:09:25 +01:00
jfilby
5a848a0707 Fix several memory leaks in the Postgres wrapper. (#20940) 2022-11-27 19:28:38 +01:00
Federico Ceratto
f644f04654 Handle ppc CPU architecture (#20920)
* Remove confusing "ppc" block

The PowerPC arch is called "powerpc" in platforms.nim

The makefile shipped in release 1.6.10 populates the oFiles variable when myos=linux and mycpu=powerpc
mycpu=ppc instead leads to  ``no C code generated for: [linux: ppc].  Stop``

* Handle ucpu=ppc
2022-11-26 21:59:52 +01:00
metagn
c0daea7b31 issue form: don't syntax highlight output logs (#20924)
* issue form: don't syntax highlight output logs

* example output logs make no sense

* dummy to skip ci [skip ci]
2022-11-26 11:32:13 -05:00
ringabout
dc21ae9ea5 Correct descriptions for oids (#20926) 2022-11-26 11:29:45 -05:00
ringabout
2d6c200284 fixes documentation regression (#20925)
follow up https://github.com/nim-lang/Nim/pull/17004
2022-11-26 16:35:30 +01:00
ringabout
37fe9c0f38 Add a link for testament (#20923) 2022-11-26 21:48:37 +08:00
ringabout
b57a9637e8 fixes #20914; fixes the alignment of big sets (#20918)
* fixes #20914; fixes the align of bug sets

* add a test for alignof
2022-11-26 07:48:11 +01:00
Juan Carlos
2709898a5e koch remove dead code (#20912)
* koch remove dead code for Travis CI

* Restart CI

* Restart CI
2022-11-25 13:51:11 +01:00
ringabout
cbc2fa7156 add a testcase for vcc (#20915)
test vcc
2022-11-25 17:39:50 +08:00
ringabout
521720f30f fixes #20873; rework vcc with arc/orc (#20913)
* fixes #20873; arc/orc is broken for vcc

* fixes signature
2022-11-25 08:49:46 +01:00
ringabout
b7d96cd3f5 fixes broken importc for vcc [backport] (#20909)
fixes broken imports for vcc
2022-11-24 20:16:51 +01:00
ringabout
27a38a9fce fix #13790; ptr char (+friends) should not implicitly convert to cstring (#20761)
* fix =#13790 ptr char (+friends) should not implicitly convert to cstring

* Apply suggestions from code review

* first round; compiles on windows

* nimPreviewSlimSystem

* conversion is unsafe, cast needed

* fixes more tests

* fixes asyncnet

* another try another error

* last one

* true

* one more

* why bugs didn't show at once

* add `nimPreviewCstringConversion` switch

* typo

Co-authored-by: xflywind <43030857+xflywind@users.noreply.github.com>
2022-11-24 07:49:23 +01:00
ringabout
ef29987781 An unnamed break in a block now gives an UnnamedBreak warning (#20901)
* unnamed break in the block now gives an error

* bootstrap

* fixes

* more fixes

* break with label

* label again

* one moee

* Delete test5.txt

* it now gives a UnnamedBreak warning

* change the URL of bump back to the original one
2022-11-24 07:31:47 +01:00
ringabout
d149727f34 remove enabled defines in config (#20904) 2022-11-24 13:45:25 +08:00
ringabout
d3eb1383d1 alloc uses atomic operations only when necessary (#20899) 2022-11-23 07:20:35 +01:00
metagn
5adfaa2a92 render post expr blocks better (#20871)
* render post expr blocks

* remove pointless diff

* fix PR split mistake
2022-11-22 20:40:05 +01:00
ringabout
09b7f90475 move system/atomics out of system; std/atomics should be preferred (#20875)
* move `system/atomics` out of system; `std/atomics` should be preferred

* add deprecation message

* fixes

* fixes

* fixes

* fixes more tests
2022-11-22 20:39:30 +01:00
Bung
8cfce70738 fix #18964 Small string case with else statement first in AST evaluat… (#20862)
fix #18964 Small string case with else statement first in AST evaluates wrongly
2022-11-22 20:08:17 +01:00
ringabout
0448f30fd9 fixes #20026; marks system procs which can raise defects (#20864)
* marks system procs which can raise defects

* add tests

* add more systemRaisesDefect

* add comment
2022-11-22 20:07:00 +01:00
Bung
354eb2a86c fix #20866 [ORC] Bad codegen for global pointer to iterator (#20876) 2022-11-22 20:05:16 +01:00
Yuriy Glukhov
fc37554795 NimMain/NimPreMain calls are now only volatile when it makes sense. (#20882) 2022-11-22 15:55:31 +01:00
metagn
27d9c67352 correct Ptr field name for RTL_CONDITION_VARIABLE? (#20896)
correct field name for RTL_CONDITION_VARIABLE?

ref #20895
2022-11-22 15:54:15 +01:00
Kyle Coffey
f4553af343 Fix compiler build with -d:nimDebugReorder (#20888)
* add missing import for -d:debugReorder

* rename compile-time symbol to match best practices

Fix #20887.
2022-11-22 15:51:17 +01:00
ringabout
d5151c1afe switch to the official taskpools URL (#20893)
ref https://github.com/status-im/nim-taskpools/pull/24
2022-11-22 09:15:36 +01:00
Matt Moseley
75493cfb78 Small cleanup to cgen output (#20874) 2022-11-21 15:00:46 -05:00
Jake Leahy
753868f16c Fix #14476 (#20878)
* Use link from webpage. Closes #14476

* Update doc generation tests

* Update RST test
2022-11-21 14:59:06 -05:00
Tanguy
19cc494b80 echo: only lock when threading is enabled (#20890) 2022-11-21 14:56:54 -05:00
ringabout
bce1f35f87 fixes strict effects (#20885)
* fixes strict effects

* remove nosideeffect

* Update lib/system/comparisons.nim
2022-11-21 14:55:13 -05:00
Ico Doornekamp
79b25a911b channel send() condition variable lock ordering (#20879) 2022-11-21 13:11:28 +01:00
rockcavera
fe43f751eb fix #20835 (#20872)
Update syncio.nim
2022-11-18 07:41:46 +01:00
ringabout
68f6926348 remove useless defines (#20867) 2022-11-17 23:04:43 +08:00
ringabout
1707bc4a99 fixes #20856; store defaults directly (#20859)
* fixes #20856; store defaults directly

* fixes

* fixes

* check

* fixes
2022-11-17 09:38:50 +08:00
ringabout
cdbf5b4699 fixes a severe bug of testament (#20832)
* test azure

* use exit 1

* try again

* use useSysAssert

* disable i386

* use refc for tlsEmulation on i386

* use refc

* disable i386

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2022-11-17 09:38:07 +08:00
ringabout
e03a178bff rename std/threads to std/typedthreads (#20850)
* rename `std/threads` to `std/oldthreads`

* fixes tests

* rename to `typedthreads`

* changelog
2022-11-16 16:35:20 +01:00
ringabout
06cd15663d fixes ptr to cstring warnings[backport] (#20848)
* fix =#13790 ptr char (+friends) should not implicitly convert to cstring

* Apply suggestions from code review

* first round; compiles on windows

* nimPreviewSlimSystem

* conversion is unsafe, cast needed

* fixes more tests

* fixes asyncnet

* another try another error

* last one

* true

* one more

* why bugs didn't show at once

* add `nimPreviewCstringConversion` switch

* typo

* fixes ptr to cstring warnings[backport]

* add fixes

Co-authored-by: xflywind <43030857+xflywind@users.noreply.github.com>
2022-11-16 10:22:51 +01:00
ringabout
3d692d08f7 fixes a long-standing ARC bug (#20849)
* fixes an ARC bug

* add a testcase
2022-11-16 07:36:14 +01:00
ringabout
4a3be7e29e add documentation and changelog for default object fields (#20845) 2022-11-15 08:42:01 +01:00
Don-Duong Quach
32b145460f createDir is now callable at compile time (#20824) 2022-11-14 20:13:04 +01:00
Derek 呆
de89f6ce32 add more test for #20836 (#20842) 2022-11-14 13:49:11 -05:00
ringabout
7f2ff909d9 fixes object default fields bugs and add tests (#20839)
* fixes object default fields bugs and add tests

* Update compiler/semmagic.nim

* Update compiler/sem.nim

* Update compiler/sem.nim

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2022-11-15 00:31:06 +08:00
Matt Haggard
1daf43fb14 Allow users to set log flushing rules (#20817)
* Add flushThreshold to std/logging loggers

* Remove duplicate field

* Add -d:nimFlushAllLogs for changing default flush behavior globally

* Add changelog entry for log flushing change

* Flush all log levels by default in Nim v2
2022-11-14 16:00:45 +01:00
ringabout
d901d3b8c5 fixes #20836; fixes #20833; fixes unsafeNew (#20841)
* fixes #20836; fixes `unsafeNew`

* fixes #20833
2022-11-14 15:59:37 +01:00
Andrey Makarov
3eef0491a8 fix a few "broken link" warnings (#20837) 2022-11-14 15:43:29 +08:00
ringabout
7db0d2bb58 fixes a CI error (#20834) 2022-11-14 14:05:13 +08:00
ringabout
d73fff1ecc fixes flaky CI with channels and ORC (#20831)
fixes flasky CI with channels

channels doesn't seem to work well with arc/orc
2022-11-13 15:29:47 +08:00
ringabout
cfab08d985 fixes tests and add notes (#20830) 2022-11-13 05:52:21 +01:00
Bung
1410243d3b fix #3505 wrong var {.global.} initialization, asign variable to it (#20812)
* fix #3505 wrong var {.global.} initialization, asign variable to it

* fix #5132 as well

* follow suggestions

* handle all call kinds

* Update tests/global/t3505.nim

* Update compiler/semstmts.nim

* Update compiler/semstmts.nim

* Update compiler/semstmts.nim

* follow suggestion

* Update compiler/semstmts.nim

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2022-11-12 22:57:07 +01:00
Andreas Rumpf
165d523edf Revert "fixes #20699; generate an empty struct for void type" (#20806)
* Revert "fixes #20699; generate an empty struct for void type (#20790)"

This reverts commit 8fcb9380f0.

* better fix [backport]
2022-11-12 22:56:40 +01:00
ringabout
73680cef95 [minor] documentation improvement (#20825)
[minor] documentation improvament
2022-11-12 21:05:57 +01:00
scarf
bf0c17c9bc chore: wider nim cache name detection (#20826)
ignores directories such as nimcache19994
2022-11-12 18:15:08 +01:00
Andreas Rumpf
852cf596ed fixes a strange issue most likely caused by a git merge (#20822) 2022-11-12 13:12:28 +01:00
ringabout
c75e6f3583 [testament] parsetoml switches to official URL (#20819) 2022-11-12 05:28:20 +01:00
metagn
77e58bf573 fixes #20807, refs #20450, regression with seq inference (#20818) 2022-11-12 05:27:51 +01:00
ringabout
8e1181bde5 issue a warning for ptr to cstring conversion[backport] (#20814)
* issue a warning for ptr to cstring conversion[backport]

* add a changelog
2022-11-11 19:32:33 +01:00
Derek 呆
6007a40eac support UncheckedArray[T] in repr_v2.nim (#20816) 2022-11-11 19:31:59 +01:00
ringabout
993630e40f switch to official docopt URL (#20815) 2022-11-11 23:05:27 +08:00
ringabout
15bffc20ed fixes tests for quit (#20813)
Co-authored-by: xflywind <43030857+xflywind@users.noreply.github.com>
2022-11-11 12:01:35 +01:00
ringabout
d17b1d475c revert #19891; nimRawSetjmp causes problems for mingw 32 bits too [backport] (#20758)
revert https://github.com/nim-lang/Nim/pull/19891
2022-11-11 08:42:31 +01:00
ringabout
645e632f21 enable yaml tests (#20810)
follow up 7dd8e88639
2022-11-11 00:53:25 -05:00
Vindaar
cc2b0f0172 [sugar] handle HiddenDeref in capture, error at CT if unsupported nnk (#20680)
* [sugar] handle HiddenDeref in capture, error at CT if unsupported nnk

Instead of running into trouble of the `.strVal` access failing, it's
better to error at CT.

* [tests] remove unnecessary import in test case

* improve ident extraction & extend test cases

* [tests] improve tests for `capture` of different types & act. check
2022-11-10 15:42:53 -05:00
ringabout
a15872ba9e refactor strongSpaceB with an enum (#20809)
refactor strongSpaceB
2022-11-10 16:21:52 +01:00
ringabout
31be01d78f add taskpools to important packages (#20803)
* add `taskpools` to important packages

* Update testament/important_packages.nim
2022-11-10 18:12:04 +08:00
ringabout
0264cded2b fixes #20798; add stew to important_packages (#20799)
ref https://github.com/status-im/nim-stew/pull/148
2022-11-10 17:57:37 +08:00
ringabout
2848cdb18a fixes #13781; fixes #14901; add acyclic pragmas to FlowVar (#20804)
* add acyclic pragmas to FlowVar

* add testcases
2022-11-10 16:54:39 +08:00
ringabout
dac5a56d70 use tlsEmulation:off for freebsd (#20802) 2022-11-10 05:48:30 +01:00
Bung
82e99f2332 fix topt_no_cursor.nim (#20791) 2022-11-09 15:52:44 -05:00
Aditya Siram
8fcb9380f0 fixes #20699; generate an empty struct for void type (#20790)
* fixes #20699; generate an empty struct for void type

* Add docs and test case.
2022-11-09 20:15:06 +01:00
tersec
6894a00409 reduce openArray-related C undefined behavior (#20795) 2022-11-09 18:08:44 +01:00
ringabout
25cb19a8fe fixes documentation regression and a bit clean up (#20793)
* fixes documentation regression and a bit clean up

follow up https://github.com/nim-lang/Nim/pull/20371

* Apply suggestions from code review

* Apply suggestions from code review
2022-11-09 16:50:14 +01:00
ringabout
f11b7debf7 remove name field for ARC (#20797)
* remove name field for ARC

* mistake

* improvement

* better

* typo

* fixes a pre-existing bug
2022-11-09 16:22:55 +01:00
ringabout
0ead94c4eb add more {.cursor.} to vm (#20796) 2022-11-09 12:53:32 +01:00
Jake Leahy
1826ff7d84 Use same defaults as JS for fetch options (#20783)
* Use same defaults as JS for fetch options

* Add changelog entry
2022-11-09 12:22:18 +01:00
ringabout
d8d08324d3 clean up system/arc (#20792) 2022-11-09 06:13:52 +01:00
ringabout
cdb136f585 arc/orc no longer needs type names by default; with nimTypeNames it gets nicer names (#20789)
Co-authored-by: Araq <rumpf_a@web.de>
2022-11-08 20:39:42 +01:00
ringabout
7d15fdd375 implements display based subtype checking (6.4x faster without threads; 2.8x faster with threads) (#20781)
* WIP: fast 'of' operator based on the literature
* implement  display based subtype checking

Co-authored-by: Araq <rumpf_a@web.de>
2022-11-08 13:08:01 +01:00
ringabout
ca3b6cba5d fixes nightlies regression; patches for freebsd (#20786) 2022-11-08 10:13:29 +01:00
Lee Matos
53643c9bc4 Update testament usage to clarify testament all (#20757) 2022-11-07 18:23:44 -05:00
ringabout
600b3a91ab fixes regression #20746; remove string copies for ORC booted compiler (#20776)
* fixes #20746; remove string copies for ORC booted compiler

* add a test case

* use `cursor` thanks to @beef331

* for old compilers

* change file extension

* change test cases
2022-11-07 14:36:43 +01:00
ringabout
66b0c843c3 fixes #20694; the exit function now takes cint type (#20775) 2022-11-07 12:17:52 +01:00
Ico Doornekamp
0b4f502393 Export trace member of exception type to allow custom stack trace entries (#20772)
Added insertStackTraceEntry() proc to allow custom stack trace entries
2022-11-07 12:17:00 +01:00
ringabout
a228e331f3 fixes regression #17121; adding doc comment in importc proc makes it silently noop at CT (#20766)
* fixes regression #17121; adding doc comment in importc proc makes it silently noop at CT

* Update compiler/vmgen.nim

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2022-11-06 22:25:55 +08:00
ringabout
fc8bfd781a fixes pre-existing quit documentation regression [backport] (#20763)
fixes pre-existing `quit` documentation regression
2022-11-06 11:50:10 +01:00
Bung
bae0fb720a fix #19149 Invalid codegen when returning var tuple from a template (#20762)
* fix #19149 Invalid codegen when returning var tuple from a template

* fix type
2022-11-06 11:49:34 +01:00
Bung
fdc8dd4128 Arc global (#20768)
* temp

* unsure

* fix condition

* port macro arc runable examples to one file

* trigger doc ci

* fix

Co-authored-by: ringabout <43030857+ringabout@users.noreply.github.com>
2022-11-06 11:47:35 +01:00
ringabout
93b085a57a closes #12589; add testcase (#20769)
* fixes #12589; add testcase

* fixes i386

* i386
2022-11-06 11:46:51 +01:00
Andreas Rumpf
3c2c728eb6 codegen: optimized generation of proc headers (#20770) 2022-11-06 11:46:19 +01:00
Ikko Ashimine
f0400eef68 Fix typo in nimsuggest.nim (#20767)
becase -> because
2022-11-05 20:32:28 +01:00
ringabout
afd4e22f76 Revert "fix arc global variable issues" (#20764)
* Revert "fix arc global variable issues (#20759)"

This reverts commit a3d32a4176.

* trigger documentation builds
2022-11-05 22:47:12 +08:00
Bung
10e7f18d01 remove compiler/strutils2.nim (#20748)
* use std strutils toLowerAscii char

* avoid additional call and assign

* remove compiler/strutils2.nim

* canonical
2022-11-05 12:22:45 +01:00
Bung
a3d32a4176 fix arc global variable issues (#20759)
* temp

* unsure
2022-11-05 12:22:16 +01:00
ringabout
92e525d2a6 add effectsOf to map in the std/sets module (#20760) 2022-11-05 12:05:02 +01:00
Lee Matos
4b24d85907 Update testament docs demo, command output, and gotchas (#20756) 2022-11-05 11:10:19 +01:00
ringabout
d5cc2085ea ref #20694; quit value gets saturated to ranges (#20753)
* quit value gets saturated to ranges

* add documentation

* minimal changes

* refactor

* small fix

* add documentation

* fixes

* Update lib/system.nim

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

Co-authored-by: Juan Carlos <juancarlospaco@gmail.com>
2022-11-05 10:58:57 +01:00
n5m
51bef9b4a8 fix posix.mq_receive compilation with cpp backend (#20710)
* fix posix.mq_receive compilation with cpp backend

* only enable runnableExample on posix

* linux, not posix

* simplify example

* add test

* mqueue.h does not exist on MacOS

* place test case in own block

* drop runnableExamples
2022-11-05 06:31:19 +01:00
konsumlamm
4491da4c4d Support doc comments in new-styled concepts (#20752)
Support comments in new-styled concepts
2022-11-04 20:32:41 +08:00
Bung
ecc8f61fe4 Fix #18079 Illegal storage access compiling call with nested ref/deref (#20738)
* add test case
* refactoring transformAddrDeref and fix #18079
* fix jsgen
2022-11-04 09:54:45 +01:00
ringabout
12a20b9fb6 revert #20719; relieve std/assertions of the sysFatal dep (#20743)
* Revert "make `system/fatal` importable (#20718)"

This reverts commit d735c447d3.

* relieve `std/assertions` of the sysFatal dep
2022-11-04 09:53:19 +01:00
ringabout
8fb172c7a6 add effectsOf to std/tables (#20751) 2022-11-04 16:25:40 +08:00
ringabout
090661d46c add a testcase for laxeffects (#20750) 2022-11-04 12:43:32 +08:00
Juan Carlos
4503fa5422 Uri.isIpv6 exported (#20736)
* Export Uri.isIpv6

* Export Uri.isIpv6
2022-11-03 09:48:51 +01:00
Juan Carlos
f562a5c55c Improve dollar IpAddress (#20729)
* Improve dollar

* Improve dollar

* Simplify, remove 1 if in for loop

* ci

* Update lib/pure/net.nim

* Update lib/pure/net.nim

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2022-11-03 09:48:25 +01:00
Juan Carlos
46eac22172 Improve dollar int (#20737)
Improve dollar
2022-11-03 09:44:11 +01:00
ringabout
0b1d1b7886 fixes #15688; handle strongSpace overflow issues (#20724)
* fixes #15688; handle `strongSpace` overflow issues

* stop at 1

* change the type of strongSpaceA to bool
2022-11-03 09:18:09 +01:00
ringabout
c4e5dab419 fixes #20740; fixes pre-existing field visibility issues and removes efSkipFieldVisibilityCheck (#20741)
fixes #20740 pre-existing field visibility and refactoring
2022-11-03 15:46:16 +08:00
Xiao-Yong
6b1e353aa1 nim-gdb: remove unnecessary quotes and fix uname (#20739) 2022-11-03 05:51:21 +01:00
ringabout
117a19d032 closes #13618; add testcase (#20734) 2022-11-02 19:25:51 +08:00
Antonis Geralis
606aa45ec6 Export FileMode (#20726) 2022-11-02 10:52:15 +01:00
ringabout
87f7f50553 closes #14216; add testcase (#20733) 2022-11-02 15:29:46 +08:00
ringabout
841d9d5975 closes #16331; add testcase (#20730) 2022-11-02 12:01:36 +08:00
Jacek Sieka
58f79e7c3e fix sighashes for generic ref (#20723)
the `hashType` issue in #12229 was never really fixed - it just stopped
being called in that context
2022-11-01 19:01:06 +01:00
ringabout
59083e2e48 fixes ssl static link regression (#20722) 2022-11-01 13:34:58 +01:00
ringabout
75ece74bdd fixes #20526; use nimPreviewSlimSystem for documentation build (#20714)
* fixes #20526; use `nimPreviewSlimSystem` for `koch docs`

* fixes documentation errors

* fixes remaning issues
2022-11-01 12:53:14 +01:00
ringabout
07cf4486bc change include genode/env to an import (#20721)
* change `include genode/env` to an import 

ref 0b262e9496 (diff-8718bd20d8f61d6638d3d64b19efc31bcd40a6d5be8215b2a1f0b75ed93e8d56)

* fixes comments
2022-11-01 18:18:06 +08:00
Bung
eec1543baf fix semcase on tySequence and tyObject #20283 #19682 (#20339)
* fix semcase on tySequence and tyObject #20283 #19682

* use better arg name

* avoiding returns nil use errorNode instead, clean code

* use efNoDiagnostics flag

* remove tests/errmsgs/t19682.nim

* combine 2 test cases to one file
2022-11-01 10:19:37 +01:00
ringabout
6166b796ba refactor os imports into corresponding small modules (#20720) 2022-11-01 10:18:04 +01:00
ringabout
d735c447d3 make system/fatal importable (#20719) 2022-11-01 07:56:32 +01:00
Bung
49e793e8c4 fix #20272 range of uint64 shows signed upper bound (#20702) 2022-11-01 05:58:32 +01:00
Juan Carlos
2f6e06d224 Improve dollar (#20672)
* Improve dollar for uri

* Refactor

* .

* .

* verde

* optimize

* https://github.com/nim-lang/Nim/pull/20672#issuecomment-1295440246 [skip ci]

* https://github.com/nim-lang/Nim/pull/20670#issuecomment-1295937393

* ci

* Update lib/pure/uri.nim

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2022-10-31 15:37:09 -04:00
Juan Carlos
229f146280 Improve getDataUri (#20670)
* Improve getDataUri

* Restart ci

* https://github.com/nim-lang/Nim/pull/20670#issuecomment-1295937393
2022-10-31 15:34:17 -04:00
ehmry
0b262e9496 Genode: add scheduleCallbacks to asyncdispatch (#20708)
* Genode: add native signal handler

* Genode: add scheduleCallbacks to asyncdispatch

This resolves some awkwardness where an RPC server may or may not
use callSoon while dispatching RPC but without scheduling timers
or I/O.
2022-10-31 19:24:57 +01:00
ringabout
39f925b95d fixes #20715; range[a..b] inside object variant fails (#20716)
* fixes #20715; range[a..b] inside object variant fails

* step one fix

* better fix

* fixes private fields

* mistake
2022-10-31 18:42:45 +01:00
Jacek Sieka
a0653ae71a fix closure iter state table init type [backport] (#20717)
fix closure iter state table init type

It is a well-known fact that using closed intervals for ranges is
logically, objectively and eternally wrong, as evidenced by this
off-by-one.
2022-10-31 18:41:48 +01:00
n5m
52166e3546 allow deferred close of nil stream (#20706)
* allow deferred close of nil stream

* improve example
2022-10-31 11:20:06 +01:00
ringabout
0a1f204f0f removes channels_builtin when enabling nimPreviewSlimSystem (#20713) 2022-10-31 16:56:05 +08:00
ringabout
e1ddd2d524 put std/threads under the umbrella of nimPreviewSlimSystem (#20711)
* put `std/threads` under the umbrella of `nimPreviewSlimSystem`

* add changelog

* fixes tests

* fixes tests again

* fixes tests
2022-10-31 06:36:50 +01:00
ringabout
fb2ec8d192 follow up #20668; fixes nightlies (#20701) 2022-10-31 06:33:07 +01:00
Jacek Sieka
f8b5464f31 fix dispatcher call type [backport] (#20696)
fix dispatcher call type

The call node should have the type of the dispatcher, not the static
call
2022-10-29 18:12:19 +02:00
ringabout
1dab8ba334 move threads out of system (#20674)
* move syslocks first

* progress

* clean up

* go on

* clean up

* clean up

* add imports syslocks

* remove documentation

* public deallocOsPages

* fixes genode

* fixes more

* fixes boehmGC

* cover more cases

* fixes cyclic deps

* fixes genode

* cleanup

* unpublic fields

* cleanup

* clean up
2022-10-29 18:11:40 +02:00
Bung
a51ed90c5d fix #20148 implicit compile time conversion int to ranged float cause… (#20698)
fix #20148 implicit compile time conversion int to ranged float causes compiler fatal error
2022-10-29 18:04:05 +02:00
Bung
534c97edc5 fix #16264 low(Time) OverflowDefect (#20552)
fix #16264 regression(0.18.0 => devel): import times; echo low(Time) gives OverflowDefect
2022-10-29 08:59:51 +02:00
ringabout
66f958b313 enable weave (#20692) 2022-10-29 13:49:28 +08:00
metagn
cb3af8ad39 alternate fix + test for #12094, refs #13804 (#20686) 2022-10-29 07:20:04 +02:00
Pietro Peterlongo
9c3faa449b add back discard as a way to do multiline comments, see #12352 (#20688) 2022-10-28 16:24:51 -04:00
ringabout
141abb7b75 fixes #20681; add efSkipFieldVisibilityCheck to skip check (#20639)
* don't sem const objectConstr defaults

* fixes

* add `efSkipFieldVisibilityCheck`; fixes nkBracket types

* fixes #20681

* fixes tests

* suggestion from @metagn

* fixes tests

Co-authored-by: xflywind <43030857+xflywind@users.noreply.github.com>
2022-10-28 16:19:40 -04:00
Andrey Makarov
779b1cc5be Fix #20628 for Windows (#20667)
* Fix #20628 for Windows

* Move isRegular - !isSpecial and onlyRegular - skipSpecial

* Forgot to change it in 1 more place
2022-10-28 10:01:28 +02:00
metagn
e68a6ea759 openssl 3 support no longer opt in + some 1.0 support (#20668)
* Revert "Add OpenSSL 3 support (#19814)"

This reverts commit 2dcfd73260.

* openssl 3 support no longer opt in + some 1.0 support

* hopefully fix

* maybe fix

* final attempt

* actual fix hopefully
2022-10-27 17:24:26 +02:00
ringabout
27896ed469 fixes type check of ranges for default fields (#20660) 2022-10-27 17:23:33 +02:00
Juan Carlos
82b7423cea int128.nim fix warnings (#20666)
* Silence warning false positive for int128.nim: Warning: target type is larger than source type

* Silence warning false positive for int128.nim: Warning: target type is larger than source type

* https://github.com/nim-lang/Nim/pull/20666#discussion_r1006162835
2022-10-27 14:19:55 +02:00
Jason Beetham
0b1989d736 Added openarray[char] overloads to std/unicode (#20648)
* Added openarray[char] overloads to std/unicode

Call substr instead of index slice inside unicode

Added substr overload for openarray for parity with string functionality

Made style checker happies and fixed overloads for substr

* Added update to changelog [skip ci]

* Inline unicode string operations

* Moved substr overload to unicode

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2022-10-27 14:16:41 +02:00
Bung
aa6f9d490f fix #6637 array index type depends generic (#20673) 2022-10-27 12:22:04 +02:00
ringabout
c341f20476 cleanup os related documentation links (#20663)
cleanup documentation links
2022-10-27 12:16:27 +02:00
ringabout
5a14b9ea1f add changelog for new modules (#20675) 2022-10-27 12:11:53 +02:00
Juan Carlos
3e7f6562b5 Documentation only, koch (#20665)
* Fix doc about Travis CI

* Rerun ci
2022-10-27 11:58:35 +02:00
Bung
3469f37a56 add test case for #500 (#20661) 2022-10-26 19:45:51 +08:00
ringabout
4b377b07fc fixes #19201; fixes sink causes crash in VM (#20658) 2022-10-25 20:08:36 +02:00
Juan M Gómez
3b973f3fc8 fixes #20654 FAMs should not be used in the C++ backend (#20655)
* fixes #20654 FAMs should not be used in the C++ backend

* updates the test so it only affects clang
2022-10-25 17:39:51 +02:00
ringabout
2d3e3ab527 closes #6213 #11777; add testcase (#20656) 2022-10-25 22:39:36 +08:00
ringabout
69eaa4f14c clean up std/os related modules (#20651)
* clean up `std/os` related modules

* use `cmpPaths`

* reset

* cleanup
2022-10-25 17:56:11 +08:00
Saint
daf35c6d1b Change both code snippets to use the same test URL (#20647) 2022-10-25 09:40:57 +02:00
Bung
4728c52c78 fix #12094 Use of _ (as var placeholder) inside a template causes XDe… (#20635)
fix #12094 Use of _ (as var placeholder) inside a template causes XDeclaredButNotUsed
2022-10-25 08:43:14 +02:00
Andrey Makarov
8ed2431db0 Implement Unix file regularity check (#20448) (#20628)
* Implement Unix file regularity check

* update std/dirs also
2022-10-25 07:42:47 +02:00
ringabout
c1343739e1 add type check for default fields (#20652) 2022-10-25 07:39:57 +02:00
ringabout
064b72a59c fixes #1027; disallow templates to use ambiguous identifiers (#20631)
* test qualifiedLookUp in templates

* check later

* add testcase

* add 4errormsg

* Update tests/template/m1027a.nim

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>

* Update tests/template/m1027b.nim

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2022-10-24 21:44:09 +02:00
Andreas Rumpf
48d41ab375 fixes #20645 (#20646)
* fixes #20645

* better bugfix
2022-10-24 21:41:29 +02:00
Jason Beetham
ea0e45e62f Added 'openArray[char]' overloads to 'std/parseutils' (#20527)
* Added 'openarray[char]' overloads to 'std/parseutils'

* Removed redundant `start` and `last` params from slice using procs

* Fixed type for parseIdent overload

* fixed one by off with 'substr'

* removed missed start parameters for procedures

* Added 'openarray[char]' overloads to 'std/parseutils'

* Removed redundant `start` and `last` params from slice using procs

* Fixed type for parseIdent overload

* fixed one by off with 'substr'

* removed missed start parameters for procedures

* Fixed VM op to work with new 'opcSlice'

* Corrected captureBetween's logic to work with openarray

* js sys's parsefloat logic now uses openarray

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2022-10-24 14:50:54 -04:00
Jake Leahy
eed1b6df20 Add better error messages to std/jsonutils (#20629)
* Add better error messages

* Add fmt on tuple msg
2022-10-24 12:57:48 -04:00
Jacek Sieka
e2f412145f fix fwrite prototype (#20644)
* fix fwrite prototype

* Update lib/std/syncio.nim

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

Co-authored-by: ringabout <43030857+ringabout@users.noreply.github.com>
2022-10-24 17:25:34 +02:00
ringabout
7c2aa53e44 fixes #19278; make privateAccess work with generic ref object (#20640)
* fixes #19278; make `privateAccess` work with generic ref object

* fixes
2022-10-24 15:24:51 +02:00
ringabout
878919a4df fixes the typical (not a == b) bug in the documentation (#20643)
* fixes the typical (not a == b) bug; uses runnableExamples

* cannot add runnableExamples
2022-10-24 15:20:57 +02:00
Jake Leahy
d261135c5c Fix tuple size check in std/jsonutils (#20637)
* Add test for tuple being invalid size

* Test tuple size before accessing fields

* Fix formatting for import

* Fix not being able to build from csources_v1

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2022-10-24 17:17:14 +08:00
ringabout
98b2838a30 borrowed procs can have a body now for documentation generation (#20617)
* borrowed procs can have a body now

* fixes examples
2022-10-24 10:08:39 +02:00
Tanguy
008c3ec76a Fix double defer with break in closureiterators [backport] (#20630)
Fix double defer with break in closureiterators

Signed-off-by: Tanguy <tanguy@status.im>

Signed-off-by: Tanguy <tanguy@status.im>
2022-10-24 08:50:48 +02:00
Jake Leahy
69cb671d8d Pass json options to hooks (#20638)
* Added tests

* Fix expected string

* Allow hooks to take an optional parameter that is the current options

* Add options to hooks for other generic types

* Fix doc links
2022-10-24 08:14:17 +02:00
Tanguy
4578e773ce Remove side-effects from sysFatal with panics on (#20632) 2022-10-24 07:57:49 +02:00
ringabout
6d8178a93e closes #4678; add testcase (#20634) 2022-10-24 09:26:07 +08:00
ringabout
684a862526 closes #4466; add testcase (#20625) 2022-10-23 16:47:52 +08:00
ringabout
c75cfb363f improve error message when using toTask with a call with a return value (#20622) 2022-10-23 08:27:34 +02:00
ringabout
fa1606c6d6 enable static tests for topenarray (#20620) 2022-10-23 00:36:11 +08:00
ringabout
9361938ccd add std/appdirs (#20618) 2022-10-22 13:42:46 +02:00
Jason Beetham
da0a2fdca2 Unpack mSlice tupleconstr for static openarrays (#20615) 2022-10-22 06:37:23 +02:00
Andreas Rumpf
0faae4d5e2 fixes a strict case object problem that has been reported on the forum (#20614) 2022-10-21 22:46:32 +02:00
ringabout
3c12b72168 add typesafe std/paths, std/files, std/dirs, std/symlinks (#20582)
* split std/os; add typesafe std/paths
* add more files, dirs, paths
* add documentation
* add testcase
* remove tryRemoveFile
* clean up
* Delete test.nim
* apply changes
* add `add` and fixes
2022-10-21 21:53:44 +02:00
Bung
66cbcaab84 fix #20152 Illegal capture of closure iterator, when should be legal (#20607) 2022-10-21 09:59:05 +02:00
Bung
84fab7f39b fix #19349 incompatible type when mixing float32 and cfloat in generics (#20551) 2022-10-21 09:28:18 +02:00
Bung
04c48e3c5b fix #19426 compile error using when/elif/else and typedesc in template (#20550) 2022-10-21 09:26:46 +02:00
Amjad Ben Hedhili
5b195ab0f0 Add safe parameter to base64.encodeMime (#20559)
* Improve `encodeMime` signature

* `string` to `openArray[char or byte]`
* `safe` parameter

* Fix

* Revert "Fix"

This reverts commit a394c505c2.

* Remove encodeMime's openArray overload

* Document the `safe` parameter

* Add changelog entry
2022-10-21 09:25:25 +02:00
ringabout
1db25ffcd3 closes #19969; add testcase for #19969 #15952 #16306 (#20610)
closes #19969; add testcase
2022-10-21 13:38:40 +08:00
Andreas Rumpf
76763f51aa implemented strictCaseObjects (#20608)
* implemented strictCaseObjects

* changelog update
2022-10-21 06:55:52 +02:00
Jason Beetham
4aa67ad7fd Implemented mSlice on the VM allowing toOpenArray to work at compile time. (#20586)
* Implemented opcSlice to make 'toOpenArray' work on the VM

* Added nkOpenArray for VM to reduce bodgeness

* Fixed range issues and erraneous comments

* Range check correctly for openArrays in opcLdArr

* Inverted logic for ldArr checking

* vm now supports slicing strings

* Added string tests

* Removed usage of 'nkOpenArray' and redundant operations

* Refactored vmSlice implementation, removing redundant and incorrect code

* Made tuples go throw opcWrObj for field assignment

* All strkinds should be considered for openarrays
2022-10-20 23:59:57 +02:00
ringabout
ff2cb113ad move procs in os to appdirs (#20605)
* move procs in os to `appdirs`

* Update lib/std/private/osappdirs.nim
2022-10-20 23:14:50 +02:00
ringabout
14a2fb71b9 change vm imports after bootstrapping (#20602) 2022-10-20 21:47:59 +08:00
ringabout
2ffa230b49 enable ggplotnim (#20600)
ref https://github.com/Vindaar/ggplotnim/pull/151
ref b1a653b198
2022-10-20 17:11:51 +08:00
ringabout
f6a002c8a5 [std/os] split and re-export (#20593)
* [std/os] split and export
* move to private modules
* fixes docs and tests

Co-authored-by: xflywind <43030857+xflywind@users.noreply.github.com>
2022-10-20 07:58:29 +02:00
ringabout
ea5dcdbe8f add measuremancer to important packages (#20599)
* add measuremancer to important packages

wait for https://github.com/nim-lang/packages/pull/2392

* Update testament/important_packages.nim

* Update testament/important_packages.nim

* Update testament/important_packages.nim
2022-10-20 01:22:53 +08:00
SirOlaf
2f441ac675 [backport] Handle nkOpenSymChoice for nkAccQuoted in considerQuotedIdent (#20578)
* Handle nkOpenSymChoice for nkAccQuoted in considerQuotedIdent

* Add test

* Update compiler/lookups.nim

Co-authored-by: SirOlaf <a>
Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2022-10-18 14:56:38 -04:00
ringabout
b07526b2c7 refactor envvars, oserrors; register vmops (#20592)
* refactor envvars, oserrors; register vmops

* remove type definitions
2022-10-18 19:44:26 +02:00
ringabout
b13ef07f58 enable telebot (#20589)
ref https://github.com/ba0f3/telebot.nim/pull/79
ref https://github.com/ba0f3/telebot.nim/releases/tag/2022.10.18
2022-10-18 18:25:26 +08:00
ringabout
15dff4daff fixes niminst with stricteffects; add testcase for niminst (#20587)
fixes niminst with stricteffects; add testcase
2022-10-18 08:59:02 +02:00
Andreas Rumpf
81087c949f fixes #20572 (#20585)
* fixes #20572

* added a test case
2022-10-17 23:48:51 +02:00
ringabout
c0824b9b80 [std/os clean up] import and export osseps (#20580)
import and export osseps
2022-10-17 20:29:00 +02:00
Juan Carlos
b7f1757952 Documentation only, dom (#20584)
Add docs to dom
2022-10-17 20:01:08 +02:00
Can Lehmann
2102e3b02f Fix #12517 Allow single branch when nimvm statements (#20577)
Allow single branch when statements
2022-10-17 08:01:53 +02:00
Andrey Makarov
081dfea746 Fix "imported but not used" warnings (#20575) 2022-10-16 20:24:16 +02:00
ringabout
0bacdf5fdf fixes #20515; base method requires explicit {.gcsafe.} to be GC-safe (#20574)
* fixes #20515; base requires explicit `{.gcsafe.}` to be GC-safe

* add tests
2022-10-16 13:20:05 +02:00
ringabout
619d6c318c enable glob (#20573)
ref 5cc3310437
2022-10-16 09:52:19 +08:00
Antonis Geralis
ed26156c99 atomicInc global alloc counters (#20571) 2022-10-16 01:07:22 +02:00
ringabout
1e15f975b8 fixes #19162; enable strictEffects for v2 (#19380)
* enable stricteffects
* add gcsafe
* fix tests
* use func
* fixes pegs tests
* explicitly mark repr related procs with noSideEffect
* add nimLegacyEffects
* change URL
* fixes docopt
* add `raises: []` to repr
* fixes weave
* fixes nimyaml
* fixes glob
* fixes parsetoml
* Apply suggestions from code review
* Update testament/important_packages.nim
* add legacy:laxEffects
2022-10-15 14:07:40 +02:00
Bung
0510a2be0d fix #19700 Crash when passing a template to a generic functio… (#20567)
fix nim-lang#19700 Crash when passing a template to a generic function expecting a procedure
2022-10-15 07:15:58 +02:00
ringabout
57574eaf31 fixes changelog for oids (#20565) 2022-10-14 20:58:36 +08:00
Bung
b286448a99 fix #8821 JS codegen can produce extreme switch statements with case … (#20548)
* fix #8821 JS codegen can produce extreme switch statements with case a of range

* remove totalRange
2022-10-14 12:21:02 +02:00
Andreas Rumpf
07b645342a fixes #3748 (#20563)
* fixes #3748

* fix the regression

* don't use the new allocator for the SSL wrapper

* fixes regression
2022-10-14 12:00:38 +02:00
Andrey Makarov
b793ca7394 Validate nimgrep filter options not empty (#20562) 2022-10-14 00:44:34 -04:00
ringabout
be18f4e513 follow up #19714; add memmem optimizations for find on Linux, Macos and BSDs (#20556)
* fixes tests

* add memmem optimization for find

* fixes

* ty[o

* fixes `"abc".find("") == 0 doesn't work on macOS

Co-authored-by: xflywind <43030857+xflywind@users.noreply.github.com>
2022-10-13 23:58:59 +02:00
ringabout
6082b9ea5d fixes #20553; don't format code for stropping identifier (#20561) [backport]
* fixes #20553; don't format code for stropping identifier

* add tests

* Update nimpretty/tests/expected/simple.nim
2022-10-13 23:37:41 +02:00
Bung
169d3fda00 fix #18136 tests/proc/t17157.nim now gives SIGSEGV instead of error (#20555) 2022-10-13 06:39:43 +02:00
ringabout
a1a9d63d22 add nimPNG to important packages (#20557)
* try to enable nico since nimPNG works with ORC now

ref 2dccf3e19c

* Update important_packages.nim
2022-10-13 11:51:09 +08:00
Bung
ea2f2775a7 fix #18990 Regression in proc symbol resolution; Error: attempting to… (#20554)
fix #18990 Regression in proc symbol resolution; Error: attempting to call routine
2022-10-12 20:44:45 -04:00
Dominik Picheta
fa60378a7f Return error message in output of gorge/staticExec. (#18942)
* Return error message in output of gorge/staticExec.

* Document nimLegacyGorgeErrors in changelog.
2022-10-12 18:52:22 +02:00
Andrey Makarov
19ff746916 Markdown code blocks migration part 7 (#20547) 2022-10-12 16:13:43 +02:00
ringabout
13b3ea71da oids sticks to 24 length strings; fixes breaking changes (#20546)
oids sticks 24 length strings
2022-10-12 15:15:21 +02:00
ringabout
7394587217 move google fonts to the last part (#20541)
* move google fonts to the last part

* fixes tests

* fix rst2html
2022-10-11 19:42:02 +02:00
Bung
083ea8f10c fix #7446 Generics: type mismatch 'SomeunsignedInt or Natural' (#20522)
* fix #7446 Generics: type mismatch 'SomeunsignedInt or Natural'

* try fix
2022-10-11 11:42:49 +02:00
ringabout
5602183234 'lock levels' are deprecated, now a noop (#20539)
* 'lock levels' are deprecated, now a noop

* fixes tests
2022-10-11 09:17:09 +02:00
Andreas Rumpf
7587371554 time to make IC work with ORC (here we go again...) (#20538)
works for me
2022-10-11 09:00:07 +02:00
ringabout
666a0e34cd remove unused userVersion:1.6 which is succeeded by nimPreviewSlimSystem in this case (#20535)
removed unused userVersion:1.6
2022-10-10 23:38:18 +02:00
ringabout
0774c3aaaa update the maintained repo of ast-pattern-matching (#20537) 2022-10-10 15:48:51 -04:00
Andreas Rumpf
08ae3467b9 refactorings (#20536)
* refactoring

* refactoring: removed unused macroUsagesSection

* enum instead of bool for better readability
2022-10-10 21:40:07 +02:00
ringabout
e290b028ab Make rstgen work with gcsafe (#20534)
* Make rstgen work with gcsafe

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

* add tests and fixes

* if nimHasWarningAsError

Co-authored-by: Danil Yarantsev <tiberiumk12@gmail.com>
2022-10-10 18:56:01 +02:00
ringabout
1f2075042b enable nimlsp and ast_pattern_matching (#20533) 2022-10-10 22:35:39 +08:00
ringabout
d954e698b3 Automatic dereferencing is removed (#20531) 2022-10-10 15:02:23 +02:00
Andreas Rumpf
b8def03575 Atlas: added an explicit --workspace option (#20532) 2022-10-10 15:01:39 +02:00
Bung
db3d2971cf fix #18886 crash on ambiguous proc cast (#20472)
* fix #18886 crash on ambiguous proc cast

* follow suggestion
2022-10-10 11:09:54 +02:00
Andreas Rumpf
0f2775aacf implemented 'atlas install' command (#20530) 2022-10-10 11:05:44 +02:00
Amjad Ben Hedhili
944e4cf585 Remove unused base64.encode overload (#20369)
* Remove unused `base64.encode` overload

* [skip ci] Remove commented code

* [skip ci] var -> let

* [skip ci] Remove mentions of the string overload

* Remove `SomeInteger` overload

* Fix CI

* Fix CI

* Deprecate `SomeInteger` overload

* [skip ci] Add changelog entry

* Revert "Remove `SomeInteger` overload"

This reverts commit 79a2963a21.

* Revert "[skip ci] Add changelog entry"

This reverts commit 186f17eb39.

* Revert "Revert "Remove `SomeInteger` overload""

This reverts commit 8005318ee4.

* Update lib/pure/base64.nim

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2022-10-09 15:54:21 -04:00
ringabout
0c0b086d58 fixes #20524; add forbids pragmas to hideable lists (#20525)
* fixes #20524; add forbids pragmas to hideable lists

* fixes nimdoc
2022-10-09 12:13:45 -04:00
ee7
5661edd75a parseutils: skipWhile: fix parameter name in doc comment (#20523) 2022-10-09 19:32:04 +08:00
Andreas Rumpf
fbc6975922 threaded alloc (#20492)
* allocator: catch up with multi-threading techniques
* removed the global thread lock
* more atomics for fun and profit
* added important sysAssert
* stats remain thread local and don't have to be atomic
* undo split chunk optimizations in the hope it makes the CI happy
2022-10-09 11:44:02 +02:00
Huy Doan
b47d5486db FTP client is now able to connect to server over TLS by set `useTls =… (#17219)
* FTP client is now able to connect to server over TLS by set `useTls = true` in newAsyncFtpClient proc

* Update asyncftpclient.nim

* fix CI

* shouldn't use {.error.}

* Update lib/pure/asyncftpclient.nim

Co-authored-by: flywind <xzsflywind@gmail.com>
Co-authored-by: ringabout <43030857+ringabout@users.noreply.github.com>
Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2022-10-09 14:29:22 +08:00
ringabout
5e4dd571d4 fixes #20516; system.create doesn't work with bitfield objects (#20518)
* Revert "fixes #19000 (#19032)"

This reverts commit 2bda4a30a6.

* fixes #20516; add testcase
2022-10-08 17:38:22 +02:00
Andreas Rumpf
e83f27e6a0 out parameters: enforce that 'out' is only used as a parameter (#20510)
* out parameters: enforce that 'out' is only used as a parameter

* make tables.nim use 'out' parameters

* better backwards compat
2022-10-07 22:26:53 +02:00
ringabout
a132f5502a closes #12994; add testcase (#20511) 2022-10-08 00:27:17 +08:00
ringabout
c651817ffd fixes devel CI (#20512) 2022-10-07 15:00:15 +02:00
ringabout
079363bfc3 remove implicit let/var default initialization (#20508) 2022-10-07 07:49:27 +02:00
Andreas Rumpf
0d23419e68 DAA and 'out' parameters (#20506)
* DAA and 'out' parameters

* progress

* documented strictDefs and out parameters

* docs, tests and a bugfix

* fixes silly regression
2022-10-06 17:08:41 +02:00
ringabout
e323b91a32 correct grammar (ref #20199) and add check for grammar.txt (#20494)
* correct grammar; ref #20199

* add check for keeping grammar.txt up-to-date

* add nimTestGrammar
2022-10-06 16:36:32 +02:00
ringabout
114acff98d closes #9401; add testcase (#20507) 2022-10-06 13:51:42 +08:00
Juan Carlos
c273496d18 Add no-math-errno for GCC when build for Release (#20503)
* gcc matherrno
* changelog
2022-10-06 07:19:41 +02:00
Ivan Yonchovski
7caa037936 Fix/improve handling of forward declarations in nimsuggest (#20493)
* Fix/improve handling of forward declarations in nimsuggest

- ideUse now works fine when invoked on the implementation
- implemented ideDeclaration to make cover lsp feature textDocument/declaration
- fixed performance issue related to deduplicating symbols. Now the
deduplication happens after the symbols are filtered. As a alternative we might
change the way cached symbols are stored(e. g. use set).
- I also fixed the way globalSymbols work. Now it will sort the responses based
on the match location to make sure that the results are sorted in user friendly way.

* Update nimsuggest/nimsuggest.nim

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

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2022-10-06 07:18:46 +02:00
ringabout
723a71bd22 follow up #20109; remove shallow seqs/strings for ORC (#20502)
* remove `shallow` seqs/strings for ORC

* add a changelog item

* change url of DelaunayNim
2022-10-06 07:16:50 +02:00
Matt Haggard
964afd3050 Make output assertion deterministic for test for #7172 (#20495)
Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2022-10-05 20:14:22 -04:00
ringabout
a600dfa5b7 closes #11267; closes #11259; closes #11085; add testcases (#20505)
* closes #11267; add testcase

* closes #11259

* closes #11085
2022-10-06 02:30:10 +08:00
Andrey Makarov
6505bd347d Markdown indented code blocks (#20473)
* Implement Markdown indented code blocks

Additional indentation of 4 spaces makes a block an "indented code block"
(monospaced text without syntax highlighting).
Also `::` RST syntax for code blocks is disabled.

So instead of
```rst
see::

  Some code
```

the code block should be written as
```markdown
see:

    Some code
```

* Migrate RST literal blocks :: to Markdown's ones
2022-10-05 14:03:10 -04:00
Matt Haggard
594e93a66b macOS use SecRandomCopyBytes instead of getentropy (#20466)
* On macOS use SecRandomCopyBytes instead of getentropy (which is only available on macOS 10.12+)

* Change passL to passl
2022-10-05 13:59:10 -04:00
ee7
10355cb48a strutils, rstgen: avoid deprecated strutils.delete (#20488)
The strutils `delete` func with signature

    func delete*(s: var string, first, last: int)

was deprecated in adba5eb45e, in favor of one with signature

    func delete*(s: var string, slice: Slice[int])

However, a few procedures still used the deprecated form. This commit
updates them, resolving these deprecation warnings:

    rstgen.nim(766, 12) Warning: use `delete(s, first..last)`; delete is deprecated [Deprecated]
    strutils.nim(1651, 19) Warning: use `delete(s, first..last)`; delete is deprecated [Deprecated]
    strutils.nim(1679, 7) Warning: use `delete(s, first..last)`; delete is deprecated [Deprecated]
    strutils.nim(2472, 7) Warning: use `delete(s, first..last)`; delete is deprecated [Deprecated]

Before this commit:

- `trimZeros` called `s.delete(i+1, i)` for an input that lacks a
  trailing zero (like "1.23").

- `removePrefix*(s: var string, prefix: string)` called
  `s.delete(0, -1)` when the prefix was the empty string.

which did not modify `s`, nor raise an error. But the newer slice
`delete` raises an `IndexDefect` when the start of the slice is greater
than the end, so we avoid calling the new `delete` for such a case.

Recall that exceptions inheriting from `system.Defect` are not tracked
with the `.raises: []` exception tracking mechanism [1], so this commit
does not break existing code like:

    proc foo {.raises: [].} =
      var s = "abc1.20"
      s.removePrefix("abc")
      s.trimZeros()
      doAssert s == "1.2"

The `strutils.delete` deprecation was motivated by a problem with
`system.delete` [2][3]:

    `system.delete` had surprising behavior when the index passed to it
    was out of bounds (it would delete the last entry then). Compile
    with `-d:nimStrictDelete` so that an index error is produced
    instead.

    Be aware however that your code might depend on this quirky behavior
    so a review process is required on your part before you can use
    `-d:nimStrictDelete`. To make this review easier, use the
    `-d:nimAuditDelete` switch, which pretends that `system.delete` is
    deprecated so that it is easier to see where it was used in your
    code.

    `-d:nimStrictDelete` will become the default in upcoming versions.

A similar deprecation happened with `sequtils.delete` [4], but that
deprecated form is already not used in this repo.

[1] https://github.com/nim-lang/Nim/blob/2dec69fe5aa6/doc/manual.md#exception-tracking
[2] https://github.com/nim-lang/Nim/blob/2dec69fe5aa6/changelogs/changelog_1_6_0.md#system
[3] https://github.com/nim-lang/Nim/commit/92cb76571432
[4] https://github.com/nim-lang/Nim/commit/1d6863a7899f
2022-10-05 13:57:17 -04:00
TerrorTrace
28c879c8bb Add proxy basic auth documentation (#20498) 2022-10-05 13:50:27 -04:00
ringabout
de3b438db4 enable important packages which pass tests (#20501) 2022-10-05 23:27:33 +08:00
Andreas Rumpf
9d858a29fc cleanup nfFirstWrite flags (#20500) 2022-10-05 11:50:16 +02:00
ringabout
3e2b30879c fixes #19231; newFinalize doesn't work with ORC (#20291)
* fixes #19231; newFinalize doesn't work with ORC

first make it pass tests

* remove the tables dep

creates a binding for finalized procs in order to handle the same symbols. It used to wrongly generat a new symbol id for the same symbol as the encountered one before

* refactor and revert #14257

* de indentation

* fixes tests; uses instantiated types
2022-10-05 10:35:40 +02:00
ringabout
2dec69fe5a enable ORC tests for nimsl (#20497) 2022-10-04 23:31:32 +08:00
ringabout
827971dab2 remove deprecation messages for unsafeAddr; add warnings to docs (#20496) 2022-10-04 17:05:11 +02:00
ringabout
f89ba2c951 add default field support for object in ARC/ORC (#20480)
* fresh start

* add cpp target

* add result support

* add nimPreviewRangeDefault

* reduce

* use orc

* refactor common parts

* add tuple support

* add testcase for tuple

* cleanup; fixes nimsuggest tests

* there is something wrong with cpp

* remove

* add support for seqs

* fixes style

* addd initial distinct support

* remove links

* typo

* fixes tuple defaults

* add rangedefault

* add cpp support

* fixes one more bugs

* add more hasDefaults

* fixes ordinal types

* add testcase for #16744

* add testcase for #3608

* fixes docgen

* small fix

* recursive

* fixes

* cleanup and remove tuple support

* fixes nimsuggest

* fixes generics procs

* refactor

* increases timeout

* refactor hasDefault

* zero default; disable i386

* add tuples back

* fixes bugs

* fixes tuple

* add more tests

* fix one more bug regarding tuples

* more tests and cleanup

* remove messy distinct types which must be initialized by original types

* add tests

* fixes zero default

* fixes grammar

* fixes tests

* fixes tests

* fixes tests

* fixes comments

* fixes and add testcase

* undo default values for results

Co-authored-by: flywind <43030857+xflywind@users.noreply.github.com>
2022-10-04 12:45:10 +02:00
Bung
6cf0727192 decrease iteration count of btree test (#20491)
disable btree test
2022-10-04 12:32:07 +02:00
Andreas Rumpf
7aaeb75ebd allocator: disable unnecessary stuff for ORC [backport] (#20489) 2022-10-03 18:33:45 +02:00
ringabout
0f5ad49971 [ARC] fixes #18645; C Compiler error when initializing {.global.} with a block (#19953)
* fixes #18645; C Compiler error when initializing {.global.} with a block:

* arguably cleaner solution

Co-authored-by: xflywind <43030857+xflywind@users.noreply.github.com>
Co-authored-by: Araq <rumpf_a@web.de>
2022-10-03 16:12:23 +02:00
ringabout
852a7c4919 close #11415; add testcase (#20486) 2022-10-03 10:37:27 +02:00
metagn
2cca38d33c pragma for sfCallsite instead of name check + better semantics, test (#20464)
* pragma for sfCallsite instead of name check at every template definition

Not documented because it seems to be for internal use?

Should also make it possible to make comparisons and setops imports, but this doesn't have to be done.

I can reuse a name like `cursor` for the pragma as well, added a new name just to be safe.

* make sfCallsite recursive, add tests
2022-10-03 06:07:55 +02:00
ringabout
81e7811e01 fixes nim check with orc (#20456)
* fixes nim check with orc

* fixes tests

* add tests

* fixes tests

* Update tests/arc/t20456.nim
2022-10-02 06:44:10 +02:00
Bung
0769b160c5 less test time costs (#20479) 2022-10-02 06:42:41 +02:00
ringabout
1737bb9f9e disable threads when booting the compiler (#20478) 2022-10-02 06:42:09 +02:00
Bung
567c3f055d Fix #19224 For loops over a hardcoded empty array crash the compiler (#20476)
* Fix #11684 For loops over a hardcoded empty array crash the compiler

* Update t19224.nim
2022-10-01 23:19:07 +02:00
metagn
0b1650576c move widestrs out of system (#20462)
* move widestrs out of system

* fix osproc
2022-10-01 22:35:09 +02:00
Bung
cbd9fee22a fix #19678 Broken behavior with string ranges in case labels (#20475)
* fix #19678 Broken behavior with string ranges in case labels

* Update compiler/semtypes.nim

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

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2022-10-01 18:17:07 +02:00
Andreas Rumpf
8d47bf1822 new move analyser2 (#20471)
* produce better code for closure environment creation
* new 'first write' analysis; 
* scope based move analyser
* code cleanup

Co-authored-by: ringabout <43030857+ringabout@users.noreply.github.com>
2022-10-01 16:46:51 +02:00
metagn
cfff454cf9 closed ambiguous enum defaults to first overload (#20457)
* closed ambiguous enum defaults to first overload

* add warning

* turn to hint

* work around config
2022-10-01 13:30:23 +02:00
metagn
24b81e9df6 remove hack for deprecated csize in compiler (#20463)
* remove hack for deprecated csize in compiler

* remove test
2022-10-01 09:07:52 +02:00
ringabout
96c5586d03 add plausibleAnalytics support for koch docs[backport:1.6] (#20454)
add plausibleAnalytics to koch docs[backport:1.6]
2022-09-30 12:39:28 +02:00
ringabout
ae050b05e9 koch boot compiler with orc (#20467)
* koch boot compiler with orc

* use orc

* workaround bugs

* move it

* move the data
2022-09-30 12:38:25 +02:00
ringabout
3e43ea3384 make koch and tools work with nimPreviewSlimSystem (#20459) 2022-09-30 08:09:40 +08:00
ringabout
716d68cb24 fixes postgres with nimPreviewSlimSystem (#20455) 2022-09-29 23:54:45 +08:00
Juan Carlos
1e635bb539 Undeprecate isvalidfilename (#19643)
* Remove deprecated isvalidfilename
* https://github.com/nim-lang/Nim/pull/19643#issuecomment-1235102314
* https://github.com/nim-lang/Nim/pull/19643#issuecomment-1235102314
* https://github.com/nim-lang/Nim/pull/19643#issuecomment-1235102314
* Add unittests
* Add more

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2022-09-29 12:22:29 +02:00
ringabout
f56085f21e refactor dbFormat (#19746)
* refactor dbFormat

* add simple tests
2022-09-29 12:16:42 +02:00
Andreas Rumpf
77a65d3c33 fixed tstrimpl (#20452) 2022-09-29 09:41:00 +02:00
ringabout
a8cc5d1379 Unicode Operators are no longer experimental (#20444)
* Unicode Operators are no longer experimental

* fixes tests

* Update doc/manual.md

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2022-09-28 22:37:26 +02:00
ringabout
65c2518d5c fix #19500; remove find optimization [backport: 1.6] (#19714)
* remove find optimization

close #19500

* save find to std

* add simple tests

* Apply suggestions from code review

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

Co-authored-by: sandytypical <43030857+xflywind@users.noreply.github.com>
Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>
2022-09-28 16:05:41 -04:00
metagn
919a889ba8 moderate system cleanup & refactor (#20355)
* system refactor, move out 600 lines

* compilation, slice, backwardsindex, misc_num moved out of system
* some procs/types moved into arithmetics, basic_types
* system no longer depends on syncio
* some procs moved around to fit with their surroundings

* make exceptions an import, old ops to misc_num

* move instantiationInfo back

* move back nim version, fix windows echo

* include compilation

* better docs for imported modules, fix unsigned ops

also remove ze, ze64, toU8, toU16, toU32 with nimPreviewSlimSystem

* fix terminal

* workaround IC test & weird csize bug, changelog

* move NimMajor etc back to compilation, rebase for CI

* try ic fix

* form single `indices`, slim out TaintedString, try fix IC

* fix CI, update changelog, addQuitProc

* fix CI

* try fix CI

* actually fix CI finally hopefully

* Update lib/system/compilation.nim

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

* update kochdocs

* hopefully fix csize uses for slimsystem

* fix tquit

Co-authored-by: ringabout <43030857+ringabout@users.noreply.github.com>
2022-09-28 15:28:45 -04:00
ringabout
b463c8aedf fixes changelog links (#20446) 2022-09-28 19:40:14 +02:00
Tomohiro
92a0f191bf Use vccexe when generating static lib with vcc (#19843) 2022-09-28 15:07:41 +02:00
metagn
de4b0346bd store full definition AST for consts, fix noRewrite (#20115)
* continue #9582 for consts, close #9331, fix #20114

also move extractPragma to ast to pave the way for things like {.strdefine: "abc".} etc

* changelog correctly

* fix jsgen

* update tgetimpl

* fix sighashes

* fix #19766, add comment about postfix

* fix noRewrite LOL

refs #16620

* fix changelog

* fix destructors
2022-09-28 15:05:01 +02:00
ringabout
fdc6b0fb6e fixes #19986; mutable view from immutable location (#20134)
* fixes #19986; mutable view from immutable location

* fixes the tests
2022-09-28 14:02:07 +02:00
konsumlamm
18cea8e9bd Update message for checking cast (#20145)
* Update message for checking `cast`

* Update error messages in tests
2022-09-28 13:59:27 +02:00
ringabout
e33e9e4a32 fixes #20141; dereferencing pointer to incomplete type error with cast (#20147)
Co-authored-by: xflywind <43030857+xflywind@users.noreply.github.com>
2022-09-28 13:57:47 +02:00
ringabout
fe8feb46c6 fixes #19457 seqs are not properly updated in loop with ARC/ORC (#19922)
* test CI

* fixes #19457

* add comments

Co-authored-by: sandytypical <43030857+xflywind@users.noreply.github.com>
2022-09-28 13:12:08 +02:00
ringabout
95614089ac remove deprecated and broken nimweb tools (#20442)
* remove deprecated and broken nimweb tools

* readme
2022-09-28 12:14:35 +02:00
ringabout
89f76bb448 follow up #19408; bump devel version and deprecated unsafeAddr (#20432)
bump devel version and deprecated unsafeAddr
2022-09-28 11:09:01 +02:00
Nan Xiao
fd257a9a0f Refactor initOptParser (#19656)
Co-authored-by: flywind <xzsflywind@gmail.com>
2022-09-27 15:00:57 -04:00
ringabout
80e739f2bf fixes #19401; fixes #19402; rework Forward declaration and finalizer for ORC (#20295)
* fixes #19401; fixes #19402; rework Forward declaration and finalizer for ORC

* add more tests

* give it a name

* make more tests

* fixes tests

* hidden addr for cpp

* move code to a function
2022-09-27 20:07:26 +02:00
ringabout
3d2f0e2c7c make more standard libraries work with nimPreviewSlimSystem (#20343)
* make more standard libraries work with `nimPreviewSlimSystem`

* typo

* part two

* Delete specutils.nim

* fixes more tests

* more fixes

* fixes tests

* fixes three more tests

* add formatfloat import

* fix

* last
2022-09-27 20:06:23 +02:00
Amjad Ben Hedhili
98a717dda9 allow more simple expressions in js (#20270)
* make it match ccgexprs.nim `isSimpleExpr`
* x in {1, 2}
* r[].x and r.x when r is ref type
* float(x)

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2022-09-27 12:47:45 +02:00
Amjad Ben Hedhili
d755c02b02 Compute small nim string lit at CT (#20439)
* Reduces runtime overhead for small strings.
* Avoids including `makeNimstrLit` in the output when all strings are
  small enough.
2022-09-27 11:11:09 +02:00
Andreas Rumpf
ca1f3f36b9 no ropes WIP (#20433)
* refactorings in preparation for ropes elimination of the C code generator; mostly the usual ': Rope' -> 'result: var Rope' rewrite
* rewrote ccgcalls.nim
* refactored ccgexprs.nim
* ccgliterals: refactoring
* refactoring: code dealing with name mangling
* refactoring: getRecordFieldsAux
* ropes are strings (insert obscene joke here)
* optimize JS code gen
* optimizations and code improvements
* more optimizations
* final cleanups
2022-09-27 10:57:47 +02:00
Peter Munch-Ellingsen
805186809c Fix issue with fields trying to use wrong name (#12655)
* Fix issue with fields trying to use wrong name

* Fix similar issue in winlean

* Revert accidental csize change

Co-authored-by: Clyybber <darkmine956@gmail.com>
Co-authored-by: ringabout <43030857+ringabout@users.noreply.github.com>
2022-09-26 15:44:02 -04:00
n5m
6b4ea88734 use almostEqual in tstats.nim (#20431)
prefer math.almostEqual
2022-09-26 15:42:26 -04:00
ringabout
cb24eea86b fixes #20426; remove maincommand and m options since they are a no op since 2014 (#20429)
* bump macOS image on Azure CI to macos-11

##[warning]The macOS-10.15 environment is deprecated, consider switching to macos-11(macos-latest), macos-12 instead. For more details see https://github.com/actions/virtual-environments/issues/5583

* fix CI error

* fixes #20426; remove `maincommand` and `m` options since they are a noop since 2014 and causes confusion

fixes #20426

7f7b13a45f (diff-d949f8c356fd2dc9ceedc6f3dbbd01e2c806269dd0a8ad6516facf589fa2c99a) makes it a no op, but it causes a regression because it should add `expectArg(switch, arg, pass, info)` before the discard statement. It causes https://github.com/nim-lang/Nim/issues/20426 to happen. Without `expectArg(switch, arg, pass, info)`, `-mm:orc` is wrongly interpreted as `-m` and compiler, which doesn't make sense. It should either abort compilation or prints `argument for command line option expected: '-m'` message. Since they are a no op since 2014, let's remove it to clear the confusion. Let's wait and see whether it breaks something.

* add a changelog
2022-09-26 15:40:20 -04:00
n5m
9ca88a1889 fix #18128 rfind on empty needle returns rightmost index (#20430)
rfind on empty needle returns haystack len
2022-09-26 15:39:22 -04:00
ringabout
b213913dcb add a changelog and update the document for ORC (#20415)
* add a changelog and update the document for ORC

* hone

* back

* Apply suggestions from code review

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>

* Update doc/mm.md

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>

* Update doc/mm.md

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2022-09-26 19:32:08 +02:00
Amjad Ben Hedhili
40dae8c731 Represent more types as JS TypedArrays (#20411)
* Represent `array[N, char]` as JS `UInt8Array(N)`

* Add support distinct and range types

* Add support for bools and enums
2022-09-26 12:26:28 +02:00
Bung
e13cd40e21 fix #2614 improve error message when array of proc calling convention… (#20379)
fix #2614 improve error message when array of proc calling convention mismatch
2022-09-26 11:58:13 +02:00
Amjad Ben Hedhili
f7f375f59d Optimize base64.encodeMime (#20409)
* Optimize `base64.encodeMime`

* 5x faster for common scenarios, 13x faster if `lineLen` <= encoded
string's length or `newLine` is empty.
* Changed `lineLen`'s type to `Positive` to disallow `0`.

* Fix
2022-09-25 15:23:23 -04:00
ringabout
30bd75e459 continue booting the compiler with refc (#20421)
* continue boot the compiler with refc

* koch

* use `gc:refc`
2022-09-24 20:14:01 +08:00
ringabout
37ca97dd76 close #15955; add a test case (#20414) 2022-09-24 01:37:21 +08:00
ringabout
7739e23420 defaults to ORC (#19972)
* defaults to Orc

* bootstrap using refc

* use gc

* init orc defines

* unregister orc

* fix gc

* fix commands

* add prepareMutation for orc

* enable deepcopy for orc

* prepareMutation

* more fixes

* some cases

* bug #20081

* partial fixes

* partial fixes

* fixes command line

* more fixes

* build Nim with refc

* use gc

* more fixes

* rstore

* orc doesn't support threadpool

* more shallowCopy

* more fixes

* fixes unsafeNew

* workarounds

* small

* more fixes

* fixes some megatest

* tcodegenbugs1 refc

* fxies megatest

* build nimble with refc

* workaround tensordsl tests

* replace shallowCopy with move

* fixes action

* workaround

* add todo

* fixes important packages

* unpublic unregisterArcOrc

* fixes cpp

* enable windows

Co-authored-by: xflywind <43030857+xflywind@users.noreply.github.com>
2022-09-23 13:05:05 +02:00
ringabout
47b59e4d33 fix #17351; switch to c++17 and remove hacks (#20407)
* fix #17351; switch to c++17

* remove workaround
2022-09-23 11:16:43 +02:00
Aditya Siram
be4bd8a0ed Fixes #20348; only respect the recursion limit if the symbol's generic type has been generated by the compiler (#20377)
Fixes #20348
2022-09-22 14:19:36 -04:00
ringabout
db8a62d480 fixes #20285; prevent oid time overflow at year 2038 (#20338)
* Revert "fixes  #20285; prevent oid time overflow at year 2038"

This reverts commit dfcdb6ec2a.

* increase time to 64 bits and clean up

* add testcase

* inline consts

* add a changelog

* fixes  #20285; prevent oid time overflow at year 2038
2022-09-22 21:15:27 +08:00
Andrey Makarov
ae3dd759c4 Extract markdown/rst doc into separate file (#20404)
* Extract Markdown & Rst doc into separate file

This documentation should be extracted into separate file
as it's user's documentation, which can be used as a separate
utility for compiling `.md/.rst` files.

* Restructure: move markup info into markdown_rst.md

+Markdown link migration
2022-09-22 12:05:53 +02:00
Bung
2afce84616 Improve error message when instantiating generics with object constructor (#20358)
* Improve error message when instantiating generics with object constructor

* follow suggestion

* Update compiler/semobjconstr.nim

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>

* Update tests/errmsgs/t19882_2.nim

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2022-09-21 21:11:39 -04:00
Bung
de089d7fdb contentLength default to -1 if not present (#19835)
* contentLength default to -1 if not present

* `httpclient.contentLength` changelog
2022-09-21 18:01:22 -04:00
ringabout
70c25c45d6 fixes #20397; fixes stylecheck regression (#20398)
* fixes  #20397; fixes stylecheck

* add testcase
2022-09-21 15:04:33 -04:00
Judd
4133698f2d Update manual.md (#20394)
* Update manual.md

update outdated information on `ObservableStores`.

* Update manual.md

add `base` pragma to fix the warning.

* Update doc/manual.md

accept.

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>

* Update manual.md

update example code.

* Update manual.md

1. more updates to help keeping readers on track.
1. fix typos.

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2022-09-21 15:00:55 -04:00
Juan Carlos
ebb1b7af23 RFC-460 implemented (#19771)
* RFC-460 implemented

* RFC-460 implemented

* RFC-460 implemented

* Fix dumb GitHub autoupdate on changelog
2022-09-21 10:37:13 +02:00
ringabout
e0c1159fb3 fixes #20391; make of operator work with generics for ORC (#20395) 2022-09-21 10:29:39 +02:00
ringabout
de70128fcc follow up #19968; add more tests (#20396) 2022-09-20 16:14:01 -04:00
ringabout
4a1bda667c turn nimIncrSeqV3 into deadcode (#20388) 2022-09-20 14:59:50 +02:00
metagn
3dc302662e clarify distinct pointer type nil change (#20376)
* clarify distinct pointer type `nil` change

* Update changelog.md [skip ci]

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>

* remove extra quote [skip ci]

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2022-09-20 14:58:22 +02:00
Bung
08c02f0236 report expression has no type other than has to be used (or discarded… (#20392)
report expression has no type other than has to be used (or discarded) when typ is tyNone in discardCheck
2022-09-20 14:50:48 +02:00
Bung
a302b26e0e fix #19882 Improve error message when instantiating generics that lac… (#20356)
* fix #19882 Improve error message when instantiating generics that lack a type

* Update tests/errmsgs/t19882.nim

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2022-09-19 18:31:40 -04:00
Andrey Makarov
c4ba4f06f8 Markdown link migration part 2 (#20371) 2022-09-19 18:24:40 -04:00
Juan Carlos
2147b116a1 Add missing proc to dom (#20378)
* Add missing proc from dom

* Add missing proc from dom

* Add missing proc from dom

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2022-09-19 17:51:47 -04:00
Juan Carlos
c8000b1025 Add missing symbols to regex (#20383)
* Add missing attribute to jsre

* Add missing attribute to jsre
2022-09-19 17:47:39 -04:00
Amjad Ben Hedhili
7023176dcb Recommend mapIt in some cases (#20347)
* Recommend `mapIt` in some cases

* Remove runnableExample
2022-09-19 17:43:46 -04:00
Amjad Ben Hedhili
7a756bfaef Shorten JS block code (#20370) 2022-09-19 15:09:41 +02:00
ringabout
97259a5ab3 fixes #19713; Revert "Remove tlsEmulation enabled from Windows + GCC config" (#19119) (#20327)
* Revert "Remove tlsEmulation enabled from Windows + GCC config (#19119) [backport:1.6]"

This reverts commit 77b696c2c9.

* increase nimTlsSize to 48000

* enable for windows

* fixes tests

* fixes tlsEmulation:on
2022-09-19 09:16:54 +02:00
ringabout
f6dc30e52d fixes Thread initializer for ARC/ORC on Macos (#20368)
* fixes Thread initializer for ARC/ORC

* another try

* fix

* use int
2022-09-16 16:35:53 -04:00
Tanguy
3a5e38ab9d Allow custom pragma on iterators [backport] (#20344)
Allow custom pragma on iterators
2022-09-17 02:10:47 +08:00
ringabout
d44b547144 add docs to copyNimNode and copyNimTree (#20357)
* add docs to copyNimNode and copyNimTree

* Apply suggestions from code review

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2022-09-16 00:35:44 -04:00
metagn
c7ee4ab509 don't run azure on other branches either (#20365)
* don't run azure on other branches either

refs #20184

Azure is more prone to clogging & it's especially bad with the timeouts (some PRs haven't rebased).

* allow all version- branches

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>

* add closing quote

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2022-09-16 10:48:47 +08:00
Judd
758598dd3e more minor updates to manual.md (#20360)
* fix typos in manual.md

1. remove redundant `(`
1. 'System module' -> 'system module'.

* Update manual.md

"However" is not easy to understand. Suggest changing to the word into "In this version" to make the comparison explicite.
2022-09-15 22:38:06 +02:00
ringabout
cd9290818a add testcase for #19020 (#20363) 2022-09-15 23:18:14 +08:00
metagn
3e83c4a168 only run github CI on latest commit of branch/PR (#20361)
based on [this](https://stackoverflow.com/a/72408109/10633874)
2022-09-15 23:17:35 +08:00
ringabout
2b80ff2374 fixes #19104; peg Incorrect captures [backport:1.6] (#20352)
* fixes #19104; peg Incorrect captures [backport:1.6]

* add tests

Co-authored-by: khchen <khchen@gmail.com>
2022-09-15 07:54:53 +02:00
metagn
79afee868d partial revert and redesign of #19814, changelog (#20341)
* conservative partial revert of #19814

* fix

* revert tssl

* revert azure CI change

* keep azure, revert version range

* fully revert CI, add changelog

* useOpenssl3 as separate define, .3 is a version
2022-09-14 14:14:58 -04:00
metagn
a73ae3e066 minor improvements to follow up recent PRs (#20342)
put mOpenArrayToSeq in compile-time evaluation whitelist
(it was mNone before which was whitelisted), homogenize
"ordinal type expected" errors, put overloadable enums
in non-experimental manual
2022-09-14 18:30:15 +02:00
Andrey Makarov
2140d05f34 nimgrep: add --inContext and --notinContext options (#19528)
* nimgrep: add `--matchContext` and `--noMatchContext` options

* Rename options for uniformity

* Revise option names, add `--parentPath` options

* Revert --bin deprecation

* Copy-paste an original test from quantimnot

The origin was:
96544656d5/tnimgrep.nim

* Change ! to n

* Attempt to fix test

* Fix test on Windows

* Change --contentsFile -> --inFile, add more tests

* Bump

* Change --parentPath to --dirpath
2022-09-14 18:28:01 +02:00
Bung
08faa04d78 fix #20233 Float ranges in case statement in JS crash compiler (#20349) 2022-09-14 17:16:34 +02:00
ringabout
2e8c016799 disable tlsEmulation for ic tests (#20345) 2022-09-14 12:06:05 +08:00
Antonis Geralis
7c85b500df Add testcase for bug #20305 (#20323)
* add testcase for bug #20305

* Update tcaseobj.nim

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2022-09-13 19:10:08 +08:00
ringabout
c9a92117f9 Revert "add fromChar" (#20336)
Revert "add `fromChar` (#20332)"

This reverts commit 846cc746a2.
2022-09-12 13:33:47 -04:00
Andreas Rumpf
6bf21e7b3d fixes #19724; don't be aggressive when you infer sink parameters (#20314)
* fixes #19724; don't be aggressive when you infer sink parameters

* better logic and updated tests

* wip

* fixes tests (#20330)

* restore tests

* try splitPath

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

* Apply suggestions from code review

* Apply suggestions from code review

Co-authored-by: ringabout <43030857+ringabout@users.noreply.github.com>
Co-authored-by: xflywind <43030857+xflywind@users.noreply.github.com>
2022-09-12 00:58:29 +02:00
Clay Sweetser
8850644cb7 Revert "fixes #20155; repr range with distinct types is broken with ORC" (#20334)
Revert "fixes #20155; repr range with distinct types is broken with ORC (#20158)"

This reverts commit 37b3f62eef.
2022-09-11 16:56:11 -04:00
ringabout
37b3f62eef fixes #20155; repr range with distinct types is broken with ORC (#20158)
* fixes #20155; repr range with distinct types is broken with ORC

* skipRanges
2022-09-11 16:55:22 -04:00
random-bites
9b9f24f01b Replace word 'param(s)' with 'parameter(s)'. (#20331)
Replace word 'params(s)' with 'parameter(s)'.
2022-09-11 16:52:56 -04:00
havardjohn
68f92af17c Fix cannot create Windows directory in root (#20311)
* Fix cannot create Windows directory in root

Fixes #20306, a regression bug with `createDir` caused by
`23e0160af283bb0bb573a86145e6c1c792780d49`.

The issue is that, if the path consists only of a drive and a single
directory (e.g. "Y:\nimcache2" in the original issue), then no
directories will be created. This works fine if there are multiple
directories (e.g. "Y:\nimcache2\test").

In the case of "Y:\nimcache2", `omitNext` in `createDir` is `false` on
the last condition in `createDir`. This means that the "nimcache2"
directory will not be created, and no exception will be raised.

Fixed by refactoring to use `parentDirs` iterator instead of iterating
over the string characters. Motivation is reduced code complexity.

Will not test the specific "C:\test" `createDir` case, since there is no
standard Windows drive with write permissions in the root. Creating a
custom drive-mapping to Windows Temp is a non-option. That could mess
up some users running the test.

Added `parentDirs` tests since they are lacking on for POSIX paths.

* Fix `createDir("")` causing error

The change to `createDir` caused `createDir("")` to raise an error,
where it previously didn't. Fixed so `createDir("")` does not fail, and
added test case.
2022-09-11 16:51:39 -04:00
Andrey Makarov
088487f652 Implement Markdown definition lists (+ migration) (#20333)
Implements definition lists Markdown extension adopted in a few
implementations including:
* [Pandoc](
  https://pandoc.org/MANUAL.html#definition-lists)
* [kramdown](
  https://kramdown.gettalong.org/quickref.html#definition-lists)
* [PHP extra Markdown](
  https://michelf.ca/projects/php-markdown/extra/#def-list)

Also affected files have been migrated.
RST definition lists are turned off for Markdown: this solves the
problem of broken formatting mentioned in
https://github.com/nim-lang/Nim/pull/20292.
2022-09-11 13:52:43 -04:00
Hamid Bluri
846cc746a2 add fromChar (#20332)
`fromChar` converts `char` to `SomeInteger`, related to `isDigit`
2022-09-11 13:50:06 -04:00
metagn
58e6d439d8 fix #13515 [backport] (#20315)
* fix #13515

* only compile test

* no idea why this PR is unlocking this

* don't rope in symchoices

* even more restrictive
2022-09-11 08:33:24 +02:00
Andreas Rumpf
884f1f6b11 SSL: Allow the same range of versions for OSX (#20324) 2022-09-10 09:58:40 +02:00
Andrey Makarov
f6ee066ee2 Markdown links migration part 1 (#20319)
Markdown link migration part 1

Also the warning is improved a bit.

Local links (targeting inside its document) which had had a full anchor
were turned into concise form.
The very fact that they existed may be due to the bug in
reference to subsections fixed https://github.com/nim-lang/Nim/pull/20279,
now they are working well (both in RST syntax and
new Pandoc Markdown syntax implemented in
https://github.com/nim-lang/Nim/pull/20304)
2022-09-09 10:45:54 -04:00
Judd
89e6540fd3 update manual (#20325)
1. remove two redundant `.`;
1. add information on format string for `importc` just as `exportc`
2022-09-09 15:02:15 +02:00
ringabout
1699ba1c93 fixes nightlies build regression (#20322)
fixes nightlies build
2022-09-08 22:30:03 +02:00
Judd
918ae16919 Update manual.md (#20321)
* Update manual.md

add explanation for $#.

* Update manual.md

add explanation.
2022-09-08 17:33:29 +02:00
ringabout
3ea8219d73 Revert "clarify that char may not be unsigned" (#20320)
Revert "clarify that `char` may not be unsigned (#20308)"

This reverts commit f433d9cccf.
2022-09-08 15:52:30 +08:00
ringabout
bbbfde7341 fixes #20303; wasMoved expressions with side effects for ORC (#20307) [backport]
fixes #20303; wasMoved expressions with side effects
2022-09-08 08:07:28 +02:00
ringabout
f433d9cccf clarify that char may not be unsigned (#20308) 2022-09-06 23:06:32 +02:00
ringabout
b2c5f6f3c8 give a deprecate warning when using newPar to construct tuple expressions (#20312)
* error/deprecate when using `newPar` to construct tuple expressions

* Update lib/core/macros.nim

* fixes
2022-09-06 21:38:08 +02:00
Amjad Ben Hedhili
5d947bb791 Replace if by case in JS isSimpleExpr (#20267)
use case stmt
2022-09-06 21:33:40 +02:00
metagn
801eb3cb56 use arrow precedence in spec (#20166)
* test using arrow precedence in spec

refs #8759

* add test for #8759
2022-09-06 21:24:32 +02:00
ringabout
557d79e7a2 fixes #9462; jsondoc --index can generate a theindex.json (#20205) 2022-09-06 21:23:33 +02:00
metagn
5ebd1248df overloadable enums no longer experimental (#20298)
depends on #20126
2022-09-05 23:38:38 +02:00
Antonis Geralis
8dcf367e52 Prevent use-after-free bugs in object variants. Fixes bug #20305 (#20300) [backport]
prevent use-after-free bugs in cased objects

the bug happens specifically when deleting
an item in a seq. The item taking it's place
might not have the same case fields. Then =sink(x[i], move x[xl])
might leave the deleted fields still in memory!
If the new item switches branches again, you get a use-after-free bug.
2022-09-05 08:26:02 +02:00
Andrey Makarov
cde6b2aab8 Implement Pandoc Markdown concise link extension (#20304)
* Implement Pandoc Markdown concise link extension

This implements https://github.com/nim-lang/Nim/issues/20127.
Besides reference to headings we also support doing references
to Nim symbols inside Nim modules.

Markdown:
```
Some heading
------------

Ref. [Some heading].
```

Nim:
```
proc someFunction*() ...

... ## Ref. [someFunction]
```

This is substitution for RST syntax like `` `target`_ ``.
All 3 syntax variants of extension from Pandoc Markdown are supported:
`[target]`, `[target][]`, `[description][target]`.

This PR also fixes clashes in existing files, particularly
conflicts with RST footnote feature, which does not work with
this PR (but there is a plan to adopt a popular [Markdown footnote
extension](https://pandoc.org/MANUAL.html#footnotes) to make footnotes work).

Also the PR fixes a bug that Markdown links did not work when `[...]`
section had a line break.

The implementation is straightforward since link resolution did not
change w.r.t. RST implementation, it's almost only about new syntax
addition. The only essential difference is a possibility to add a custom
link description: form `[description][target]` which does not have an
RST equivalent.

* fix nim 1.0 gotcha
2022-09-04 14:52:21 -04:00
Amjad Ben Hedhili
b931e74a59 Cleanup dochack (#20299)
* Cleanup dochack

* xxx

* More cleanups
2022-09-04 01:38:38 -04:00
havardjohn
23e0160af2 Add improved Windows UNC path support in std/os (#20281)
* Add improved Windows UNC path support in std/os

Original issue: `std/os.createDir` tries to create every component of
the given path as a directory. The problem is that `createDir`
interprets every backslash/slash as a path separator. For a UNC path
this is incorrect. E.g. one UNC form is `\\Server\Volume\Path`. It's an
error to create the `\\Server` directory, as well as creating
`\\Server\Volume`.

Add `ntpath.nim` module with `splitDrive` proc. This implements UNC path
parsing as implemented in the Python `ntpath.py` module. The following
UNC forms are supported:

* `\\Server\Volume\Path`
* `\\?\Volume\Path`
* `\\?\UNC\Server\Volume\Path`

Improves support for UNC paths in various procs in `std/os`:
---

* pathnorm.addNormalizePath
  * Issue: This had incomplete support for UNC paths
    * The UNC prefix (first 2 characters of a UNC path) was assumed to
      be exactly `\\`, but it can be `//` and `\/`, etc. as well
    * Also, the UNC prefix must be normalized to the `dirSep` argument
      of `addNormalizePath`
  * Resolution: Changed to account for different UNC prefixes, and
    normalizing the prefixes according to `dirSep`
    * Affected procs that get tests: `relativePath`, `joinPath`
  * Issue: The server/volume part of UNC paths can be stripped when
    normalizing `..` path components
    * This error should be negligable, so ignoring this
* splitPath
  * Now make sure the UNC drive is not split; return the UNC drive as
    `head` if the UNC drive is the only component of the path
  * Consequently fixes `extractFilename`, `lastPathPart`
* parentDir / `/../`
  * Strip away drive before working on the path, prepending the drive
    after all work is done - prevents stripping UNC components
  * Return empty string if drive component is the only component; this
    is the behavior for POSIX paths as well
  * Alternative implementation: Just call something like
    `pathnorm.normalizePath(path & "/..")` for the whole proc - maybe
    too big of a change
* tailDir
  * If drive is present in path, just split that from path and return
    path
* parentDirs iterator
  * Uses `parentDir` for going backwards
  * When going forwards, first `splitDrive`, yield the drive field, and
    then iterate over path field as normal
* splitFile
  * Make sure path parsing stops at end of drive component
* createDir
  * Fixed by skipping drive part before creating directories
  * Alternative implementation: use `parentDirs` iterator instead of
    iterating over characters
    * Consequence is that it will try to create the root directory
* isRootDir
  * Changed to treat UNC drive alone as root (e.g. "//?/c:" is root)
  * This change prevents the empty string being yielded by the
    `parentDirs` iterator with `fromRoot = false`
* Internal `sameRoot`
  * The "root" refers to the drive, so `splitDrive` can be used here

This adds UNC path support to all procs that could use it in std/os. I
don't think any more work has to be done to support UNC paths. For the
future, I believe the path handling code can be refactored due to
duplicate code. There are multiple ways of manipulating paths, such as
manually searching string for path separator and also having a path
normalizer (pathnorm.nim). If all path manipulation used `pathnorm.nim`,
and path component splitting used `parentDirs` iterator, then a lot of
code could be removed.

Tests
---

Added test file for `pathnorm.nim` and `ntpath.nim`.
`pathnorm.normalizePath` has no tests, so I'm adding a few unit tests.
`ntpath.nim` contains tests copied from Python's test suite.

Added integration tests to `tos.nim` that tests UNC paths.

Removed incorrect `relativePath` runnableExamples from being tested on Windows:
---

`relativePath("/Users///me/bar//z.nim", "//Users/", '/') == "me/bar/z.nim"`

This is incorrect on Windows because the `/` and `//` are not the same
root. `/` (or `\`) is expanded to the drive in the current working
directory (e.g. `C:\`). `//` (or `\\`), however, are the first two
characters of a UNC path. The following holds true for normal Windows
installations:

* `dirExists("/Users") != dirExists("//Users")`
* `dirExists("\\Users") != dirExists("\\\\Users")`

Fixes #19103

Questions:
---

* Should the `splitDrive` proc be in `os.nim` instead with copyright
  notice above the proc?
* Is it fine to put most of the new tests into the `runnableExamples`
  section of the procs in std/os?

* [skipci] Apply suggestions from code review

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>

* [skip ci] Update lib/pure/os.nim

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>

* Move runnableExamples tests in os.nim to tos.nim

* tests/topt_no_cursor: Change from using splitFile to splitDrive

`splitFile` can no longer be used in the test, because it generates
different ARC code on Windows and Linux. This replaces `splitFile` with
`splitDrive`, because it generates same ARC code on Windows and Linux,
and returns a tuple. I assume the test wants a proc that returns a
tuple.

* Drop copyright attribute to Python

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2022-09-03 20:47:09 -04:00
metagn
a6189fbb98 only allow enums to overload enums + extra test (#20126)
mirror behavior without overloadableEnums
2022-09-03 09:53:31 +02:00
metagn
86f7f4ffa5 remove deprecated type pragma syntax, fix bugs that required it (#20199)
* remove deprecated pragma syntax from 0.20.0

closes #4651, closes #16653 with a cheap fix for now due to
how early `tfFinal` is set

* remove type pragma between name and generics

* undo removal, try removing bind expression (0.8.14)

* fix test, unremove bind expr

* remove again

* Update changelog.md

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

* dependencies @ HEAD & weave test dependencies

* try fix package ci

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>
2022-09-03 09:52:13 +02:00
ringabout
f540fd5cde Partially Revert "Change nim's nimble files to make it installable" (#20296)
add nimsuggest.nimble back
2022-09-02 19:05:23 +02:00
ringabout
5ff06fd3c2 Revert "fix #19600 No error checking on fclose (#19836)" (#20297)
This reverts commit 04e4a5ec0e.
2022-09-02 19:04:58 +02:00
Tomohiro
2a34d143ac Fix #16937; --clib option pass library name to backend C compiler correctly (#19754)
* Fix 16937: Make --clib option works

* Make tests/compiler/tcmdlineclib.nim works from any current dir

* Try to fix link error on macosx

* Add a comment to tests/compiler/tcmdlineclib.nims

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2022-09-01 13:57:17 -04:00
metagn
a95b6391fd support cstring in case (#20130)
* implement case for cstring

for now just converts to string on C backend

* custom implementation for cstring

* remove leftover

* revert even more

* add nil + fix packages weird variant literal bug

* update docs
2022-09-01 18:10:00 +02:00
ringabout
1f838d9af1 remove the old nimv019 define in the config (#20133)
remove the olf nimv019 define in the config
2022-09-01 18:07:49 +02:00
quantimnot
6289b002b6 [Testament] Extend and document message testing aids (#19996)
* [Testament] Extend and document message testing aids

* Enable inline msgs when not reject action.
Eliminates the pain of changing the line and column numbers in `nimout`
or `output` while making changes to the test.
* Enable using inline msgs and nimout together.
Allows ease of inline msgs for the test as well as testing msgs from
other modules.
* Add path separator and test filename variable interpolation in
msgs.
Eases handling path separators in the msgs.
* Add some documentation.

* Fixed lots of broken tests

* Fixed more broken tests

* Support multiple inline messages per a line

* Fix a broken test

* Revert variable substitution in `output`

* Remove uneeded params

* Update doc/testament.md

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>

* Update testament/specs.nim

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>

* Update testament/specs.nim

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>

* Fix indentation

Co-authored-by: quantimnot <quantimnot@users.noreply.github.com>
Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2022-09-01 17:52:13 +02:00
Dan Rose
c2cdc752c8 Simpler complex division implementation (#20088) 2022-09-01 17:44:07 +02:00
Andrey Makarov
0f555110e6 Markdown code blocks part 6 (#20292) 2022-08-31 19:39:02 -04:00
Ivan Yonchovski
fb2773411e Change nim's nimble files to make it installable (#20179)
- needs #20168 to make the stuff working

I went for this minimal solution because it seems like `compiler.nimble` and
`nimsuggest.nimble` are not in use

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2022-08-31 15:06:27 -04:00
metagn
538b8d4032 update changelog for #20242, #20091, #20087 (#20288) 2022-08-31 14:46:17 -04:00
Andreas Rumpf
5211a471c8 fixes the regressions caused by the fix for #20107 [backport] (#20287)
* fixes the regressions caused by the fix for #20107 [backport]
2022-08-31 13:19:26 +02:00
Ivan Yonchovski
d4c0d35b32 [nimsuggest] fix def call on identifier 2 times on the line (#20228)
- apparently TLineInfo's implementation of `==` ignores the column. After I fixed
the code to use exact TLineInfo comparison I fixed several other issues hidden
by that issue.

- Replaced `tuple[sym, info]` with `SymInfoPair`
2022-08-30 21:02:15 +02:00
Bung
04e4a5ec0e fix #19600 No error checking on fclose (#19836)
* fix #19600 No error checking on fclose

* add IOError to open
2022-08-29 18:09:14 +02:00
Dan Rose
cc81866da1 Implement complex sgn (#20087)
Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2022-08-28 22:17:18 -04:00
ringabout
04642335c1 fixes #17658; add cert dir for ssl ctx (#19920)
add cert dir for ssl ctx

Co-authored-by: Paul Roberts <pmr@stelo.org.uk>
Co-authored-by: sandytypical <43030857+xflywind@users.noreply.github.com>
Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2022-08-28 22:16:19 -04:00
Andrey Makarov
ee11302c24 fix nim md2tex and koch pdf commands (#20280)
* fix `nim md2tex` and `koch pdf` commands

* change rst2tex -> md2tex also
2022-08-28 18:04:13 -04:00
Judd
2b56b38235 minor updates on manual (#20258)
* minor updates on manual

1. statement -> keyword:

1. re-phase on the explanation of `import except`: maybe the newer version does not export some of the identifiers;

1. "The original module name is then not accessible" is moved up to the previous paragraph, since it is coupled with 
   the previous paragraph, but not the current one.

1. re-phase on the explanation of _Disabling certain messages_.

* Apply suggestions from code review

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

* Apply suggestions from code review

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>

* Update manual.md

do not use "()".

* Update doc/manual.md

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>
Co-authored-by: ringabout <43030857+ringabout@users.noreply.github.com>
Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2022-08-27 17:29:41 -04:00
Andrey Makarov
de9cbf6af1 Fix auto links to subheader when TOC is present (#20279)
Fix links to subheader when TOC is present

It was observed (in https://github.com/nim-lang/Nim/pull/20112)
that links to 2nd- (and subsequent) -level headings
fail if TOC is present, e.g.:
```nim
.. contents::

Type relations
==============

Convertible relation
--------------------

Ref. `Convertible relation`_
```

The problem here is that links are resolved in `rst.nim` but later
`rstgen.nim` fixes ("fixes") anchors to make them unique so that
TOC always works (if e.g. there was another sub-section like
"Convertible relation").
The solution implemented in this PR is to move that fix-up of anchors
into `rst.nim`, so that link resolution could know final anchors.

The bug seems to be added in https://github.com/nim-lang/Nim/pull/2332
in 2015, that is it is present in Nim 1.0.
2022-08-27 17:28:26 -04:00
Clay Sweetser
9ca6345122 Update manual.md (#20277) 2022-08-26 16:30:14 -04:00
Antonis Geralis
a52918a994 Add missing rand(var Rand, Ordinal) overload (#20124)
* Add missing rand(var Rand, Ordinal) overload

* Corrected mistake, thanks @metagn

Co-authored-by: metagn <metagngn@gmail.com>

* Update random.nim

Co-authored-by: metagn <metagngn@gmail.com>
2022-08-26 15:39:12 -04:00
ringabout
ea44c5cfed remove var for ref parameters in std/tables (#20175)
remove `var` from ref parameters; make it consistent
2022-08-25 23:48:43 +02:00
ringabout
16f6dc05fd std/options enables stricteffects (#19441) 2022-08-25 03:21:46 -04:00
ringabout
404e91ce48 provide better error messages for large set (#20207)
Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2022-08-25 00:49:52 +02:00
metagn
d143924ab2 remove unused sfProcvar, "procvar" mentions (#20204)
refs #12975. doesn't close it because wProcvar isn't removed
2022-08-24 21:38:37 +02:00
ringabout
b6bfe38ff5 move formatfloat out of system (#20195)
* move formatfloat out of system

* fixes doc

* Update changelog.md

* careless

* fixes

* deprecate system/formatfloat

* better handling
2022-08-24 13:38:30 +02:00
ringabout
12f23d5ae8 fixes nimPreviewSlimSystem; register echoBinSafe for nimPreviewSlimSystem (#20194)
* register echoBinSafe

* add output
2022-08-24 13:32:11 +02:00
ringabout
e832fea160 fixes #20227; skip distinct types for genObjConstr [JS backend] (#20229)
fixes #20227; skip distinct types for genObjConstr
2022-08-24 13:31:44 +02:00
metagn
b8dc58d884 test removing dollar for objects out of system (#20242)
* test removing dollar for objects out of system

* test & fixes

* fix bootstrap

* use nimPreviewSlimSystem, test stdlib category

* fix test
2022-08-24 09:44:16 +02:00
ringabout
9d9ecc3c1d fixes #20219; ignore comment/empty node in stmtListExpr (#20249) 2022-08-24 09:28:46 +02:00
metagn
0014b9c48e top-down type inference, implements rfc 149 (#20091)
* micro implementation of rfc 149

refs https://github.com/nim-lang/RFCs/issues/149

* number/array/seq literals, more statements

* try fix number literal alias issue

* renew expectedType with if/case/try branch types

* fix (nerf) index type handling and float typed int

* use typeAllowed

* tweaks + const test (tested locally) [skip ci]

* fill out more of the checklist

* more literals, change @ order, type conversions

Not copying the full call tree before the typedesc call check
in `semIndirectOp` is also a small performance improvement.

* disable self-conversion warning

* revert type conversions (maybe separate op later)

* deal with CI for now (seems unrelated), try enums

* workaround CI different way

* proper fix

* again

* see sizes

* lol

* overload selection, simplify int literal -> float

* range, new @ solution, try use fitNode for nil

* use new magic

* try fix ranges, new magic, deal with #20193

* add documentation, support templates

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2022-08-24 07:11:41 +02:00
Federico Ceratto
2dcfd73260 Add OpenSSL 3 support (#19814)
* Minor refactor

* Add OpenSSL 3 support

Remove symbols noOpenSSLHacksq and openssl10

* Drop loading of older openssl versions

* Add library path

* Use only versioned libssl soname os OSX

* Update .github/workflows/ci_packages.yml

Co-authored-by: Hein Thant <official.heinthanth@gmail.com>

* On Mac OS X CI, link OpenSSL in /usr/local/lib/

* Install OpenSSL on Mac OS X on azure pipeline

* Remove DYLD_LIBRARY_PATH

Co-authored-by: Hein Thant <official.heinthanth@gmail.com>

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
Co-authored-by: Hein Thant <official.heinthanth@gmail.com>
2022-08-23 21:44:50 +02:00
metagn
d1d141b135 new .redefine pragma for templates, warn on redefinition without it (#20211)
* test CI for template redefinitions

* adapt asyncmacro

* fix quote

* fix again

* try something else

* revert

* fix ioselectors_select, disable packages CI

* adapt more tests & simplify

* more

* more

* more

* rename to redefine, warn on implicit redefinition

* basic documentation [skip ci]

* Update compiler/lineinfos.nim

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>
2022-08-23 21:41:30 +02:00
Andrey Makarov
14656154ef Add doctype: RST|Markdown|RstMarkdown pragma (#20252)
* Add `doctype: RST|Markdown|RstMarkdown` pragma

Implements https://github.com/nim-lang/RFCs/issues/68 ,
see also discussion in https://github.com/nim-lang/Nim/issues/17987

The permitted values:
* `markdown`, which is default. It still contains nearly all of
  the RST supported but it is assumed that in time we will give up
  most or all RST features in this mode
* `rst`, without any extensions
* `RstMarkdown` — compatibility with Nim 1.x. It's basically RST
  with those Markdown features enabled that don't conflict with RST.

* Apply suggestions from code review

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>

* Additional fix in spirit of review

* Fix test after #20188

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2022-08-23 14:49:53 -04:00
metagn
f4af9e955b remove some deprecated pre-1.0 stdlib modules (#20202)
* remove pre-1.0 stdlib deprecations

notable exceptions:
* ze, toU8 etc in system/arithmetics
* potentially callsite

* undo macros, ospaths, securehash, oswalkdir

* add sets back

* add back future, document deprecated versions

* add to changelog [skip ci]
2022-08-23 20:18:40 +02:00
ringabout
a895bbf714 fixes #18983 #5282 #13008; recursive types casue infinite type (#20172)
* fixes #18983 #5282 #13008; recursive types casue infinite type

* re

* add testcases
2022-08-23 19:58:50 +02:00
metagn
f6eb1d4d7d remove {.this.} pragma, deprecated since 0.19 (#20201)
Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2022-08-23 19:44:37 +02:00
ringabout
3dbf2ac946 remove echo statements in tests (part 1) (#20178)
* remove echo statements

* Update tests/vm/triangle_array.nim

* Update tests/vm/tyaytypedesc.nim

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>
2022-08-23 19:28:51 +02:00
ringabout
1182216381 remove a special case in sigmatch; distinct pointer types no longer match nil type (#20251)
* remove a special case in sigmatch; distinct pointer types no longer match `nil` type

* add tests

* fixes tests

* Update changelog.md

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>
2022-08-23 19:27:20 +02:00
ringabout
7d7886b729 remove unused nimfind defines (#20250)
remove unused nimfind
2022-08-23 19:08:56 +02:00
ringabout
2b8f0a7971 fixes #19973; switch to poll on posix (#20212)
* fixes #19973; switch to poll on posix

* it is fd

* exclude lwip

* fixes lwip

* rename select to timeoutRead

* refactor into timeoutRead/timeoutWrite

* refactor common parts

Co-authored-by: xflywind <43030857+xflywind@users.noreply.github.com>
2022-08-23 18:58:08 +02:00
ringabout
9753dd0a1b remove shallow usages for ORC (#20109) 2022-08-23 18:50:59 +02:00
ringabout
e8556b45f5 fixes #19967; reset does not work on set [backport: 1.2] (#19968)
* fixes #19967

* use case

* add testcase

* fix typos

* explictly specify other branches

Co-authored-by: xflywind <43030857+xflywind@users.noreply.github.com>
2022-08-23 18:38:12 +02:00
ringabout
32e4b33632 fixes doc building regression; trigger builds on markdown files (#20260)
fix doc building regression; trigger builds on markdown files
2022-08-23 22:14:37 +08:00
ringabout
d8e5c5c5a6 fixes manual regression (#20259)
ref https://github.com/nim-lang/Nim/pull/20080
2022-08-23 19:17:00 +08:00
ringabout
25c6491b65 fixes #20162; locals doesn't work with ORC [backport] (#20163)
fixes #20162; locals doesn't work with ORC
2022-08-23 09:00:23 +02:00
ringabout
8fc19b9e12 document compiler procs regarding & (#20257) 2022-08-22 04:11:43 -04:00
ringabout
fdb781c713 add comments back (#20256)
My bad, I shouldn't have removed it in the precedent PR.
2022-08-21 22:45:30 -04:00
ringabout
2494470459 remove the merge pragma and obsolete comments (#20254)
remove the merge pragma which has been deprecated for seven years
2022-08-21 16:56:35 -04:00
Amjad Ben Hedhili
70a8e0d65c Docs auto dark mode (#20188)
* Implement auto dark mode

* Rename class

* Fix borders cutout

* Apply suggestions from code review

* Apply suggestions from code review

Co-authored-by: ringabout <43030857+ringabout@users.noreply.github.com>
2022-08-21 16:56:12 -04:00
ringabout
d8d86e07c3 fixes #11953; jsondoc creates no files unless the htmldocs dir is created (#20198)
* fixes #11953; jsondoc creates no files unless the htmldocs dir is created

* target

* fixes runner
2022-08-20 20:09:48 -04:00
metagn
1b61e71bb8 Remove string == nil/nil == string error (#20222)
* Remove string == nil/nil == string error

This was to help migration for `nil` strings being removed, but `nil` strings have been gone for a while now.

* remove isNil too
2022-08-20 20:07:33 -04:00
havardjohn
f4bbf3bf0b Add use of Windows Wide CRT API for env. vars (#20084)
* Add use of Windows Wide CRT API for env. vars

Replaces use of CRT API `getenv` and `putenv` with respectively
`_wgetenv` and `_wputenv`. Motivation is to reliably convert environment
variables to UTF-8, and the wide API is best there, because it's
reliably UTF-16.

Changed the hack in `lib/std/private/win_setenv.nim` by switching the
order of the Unicode and MBCS environment update; Unicode first, MBCS
second. Because `_wgetenv`/`_wputenv` is now used, the Unicode
environment will be initialized, so it should always be updated.

Stop updating MBCS environment with the name of `getEnv`. It's not
necessarily true that MBCS encoding and the `string` encoding is the
same. Instead convert UTF-16 to current Windows code page with
`wcstombs`, and use that string to update MBCS.

Fixes regression in `6b3c77e` that caused `std/envvars.getEnv` or
`std/os.getEnv` on Windows to return non-UTF-8 encoded strings.

Add tests that test environment variables with Unicode characters in
their name or value.

* Fix test issues

Fixes

* `nim cpp` didn't compile the tests
* Nimscript import of `tosenv.nim` from `test_nimscript.nims` failed
  with "cannot importc"

* Fix missing error check on `wcstombs`

* Fix ANSI testing errors

* Separate ANSI-related testing to their own tests, and only executing
  them if running process has a specific code page
  * Setting locale with `setlocale` was not reliable and didn't work on
    certain machines
* Add handling of a "no character representation" error in second
  `wcstombs` call

* tests/newruntime_misc: Increment allocCount

Increments overall allocations in `tnewruntime_misc` test. This is
because `getEnv` now does an additional allocation: allocation of the
UTF-16 string used as parameter to `c_wgetenv`.

* Revert "tests/newruntime_misc: Increment allocCount"

This reverts commit 4d4fe8bd3e.

* tests/newruntime_misc: Increment allocCount on Windows

Increments overall allocations in `tnewruntime_misc` test for Windows.
This is because `getEnv` on Windows now does an additional allocation:
allocation of the UTF-16 string used as parameter to `c_wgetenv`.

* Refactor, adding suggestions from code review

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>

* Document, adding suggestions

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>

Co-authored-by: ringabout <43030857+ringabout@users.noreply.github.com>
Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2022-08-20 04:30:11 -04:00
ringabout
641381e3d4 fixes #20149; fixes #16762; hintAsError and warningAsError now ignore foreign packages (#20151)
* fixes #20149;  hintAsError/warningAsError ignores foreign packages

* add changelog

* fixes the test

* remove

* fixes tests again

* fix

* I'm careless

Co-authored-by: xflywind <43030857+xflywind@users.noreply.github.com>
2022-08-19 16:24:09 -04:00
ringabout
c9c1c97f1e make sure tools/heapdumprepl.nim continues to compile (#20146) 2022-08-19 15:42:51 -04:00
ee7
e8657c7107 make implicit cstring conversions explicit (#19488)
The Nim manual says that an implicit conversion to cstring will
eventually not be allowed [1]:

    A Nim `string` is implicitly convertible to `cstring` for convenience.

    [...]

    Even though the conversion is implicit, it is not *safe*: The garbage collector
    does not consider a `cstring` to be a root and may collect the underlying
    memory. For this reason, the implicit conversion will be removed in future
    releases of the Nim compiler. Certain idioms like conversion of a `const` string
    to `cstring` are safe and will remain to be allowed.

And from Nim 1.6.0, such a conversion triggers a warning [2]:

    A dangerous implicit conversion to `cstring` now triggers a `[CStringConv]` warning.
    This warning will become an error in future versions! Use an explicit conversion
    like `cstring(x)` in order to silence the warning.

However, some files in this repo produced such a warning. For example,
before this commit, compiling `parsejson.nim` would produce:

    /foo/Nim/lib/pure/parsejson.nim(221, 37) Warning: implicit conversion to 'cstring' from a non-const location: my.buf; this will become a compile time error in the future [CStringConv]
    /foo/Nim/lib/pure/parsejson.nim(231, 39) Warning: implicit conversion to 'cstring' from a non-const location: my.buf; this will become a compile time error in the future [CStringConv]

This commit resolves the most visible `CStringConv` warnings, making the
cstring conversions explicit.

[1] https://github.com/nim-lang/Nim/blob/d2318d9ccfe6/doc/manual.md#cstring-type
[2] https://github.com/nim-lang/Nim/blob/d2318d9ccfe6/changelogs/changelog_1_6_0.md#type-system
2022-08-19 15:40:53 -04:00
jgirvin-venturi
7fe6dedb62 Adds missing SEEK_ POSIX constants for FreeRTOS (#20241) 2022-08-19 15:40:17 -04:00
Andreas Rumpf
b1fe1690c4 fixes #20107 (#20246) [backport] 2022-08-19 13:42:08 +02:00
Andrey Makarov
1c31de361d Markdown code blocks part 5 (#20236)
No logic was added, just a few more `*.md` files have been migrated.
2022-08-17 15:20:22 -04:00
Judd
60f6724b70 fix comment in the Nim manual (#20234)
fix comment

there is no `y` in the example.
2022-08-17 09:48:52 +08:00
Andrey Makarov
9f408ea943 Don't require blank line before Markdown code (#20215)
Fixes bug reported in https://github.com/nim-lang/Nim/pull/20189
affecting nimforum.
2022-08-15 18:37:45 -04:00
Dan Rose
c579243e0c Pass check condition directly to if (#20217)
When checking conditions, pass `check` untyped argument directly to if. This results in better error messages when the condition is malformed.

Previously `check 1` would fail at compile time with `Error: type mismatch: got 'int literal(-2)' for '-2' but expected 'bool'`
Now it fails with `Error: type mismatch: got 'int literal(1)' for '1' but expected 'bool'`.

Similarly `check "foo"` would fail with
```
Error: type mismatch: got <string>
but expected one of:
proc `not`(a: typedesc): typedesc
  first type mismatch at position: 1
  required type for a: typedesc
  but expression '"somestring"' is of type: string
...
```
Now it fails with `Error: type mismatch: got 'string' for '"somestring"' but expected 'bool'`
2022-08-15 18:37:10 -04:00
metagn
691026f507 changelog fixes again (#20206)
changelog fixes again [skip ci]
2022-08-15 18:33:43 -04:00
ringabout
a4d63ca8ba closes #12955; add testcase (#20223) 2022-08-15 18:50:12 +08:00
ringabout
c0b25f33c7 add version-1-6 and version-1-2 to triggered branches (#20214)
* add version-1-6 and version-1-2 to triggered branches

* Update .github/workflows/ci_packages.yml

* use quote
2022-08-14 18:42:52 +08:00
ringabout
d2318d9ccf closes #15316; add testcase (#20213) 2022-08-13 22:23:11 +08:00
Andrey Makarov
713f39083e Markdown code blocks part 4 (#20189)
No logic was added, just 8 more files have been migrated.
2022-08-12 14:33:43 -04:00
ringabout
8155837cde CI upgrade to ubuntu-20.04 (#20182)
* CI upgrade to ubuntu-20.04 

The ubuntu-18.04 environment is deprecated, consider switching to ubuntu-20.04(ubuntu-latest), or ubuntu-22.04 instead. For more details see https://github.com/actions/virtual-environments/issues/6002

* Update azure-pipelines.yml
2022-08-12 21:57:00 +08:00
ringabout
1a7b33942b closes #6559; add testcase (#20200) 2022-08-12 09:03:10 +08:00
ringabout
ff25103c9a Show beatutiful html instead of ugly markdown preview (#20196) 2022-08-11 21:30:06 +08:00
ringabout
e559cd0c3a improve deprecation error messages (#20197) 2022-08-11 14:04:12 +08:00
metagn
31b7a25e1e fix broken runnableExamples for getWeeksInIsoYear (#20193)
Based on what I understand from [Wikipedia](https://en.wikipedia.org/wiki/ISO_week_date#Weeks_per_year), 2001 does not have 53 weeks, but 2004, 2009, 2015, 2020 do. The years 2000 and 2001 seem to be copy pasted from the `getDaysInYear` example above. The result of `getWeeksInIsoYear` also seem to match up with Wikipedia.

That means these runnableExamples were never tested. Why is this the case? I only discovered this in #20091.
2022-08-11 09:39:18 +08:00
ringabout
5a502d7884 help our poor CI; don't run CI on other branches for push (#20184) 2022-08-09 15:47:19 -04:00
Ivan Yonchovski
ec2bc2a50e Build compiler with --noNimblePath (#20168)
- Fixes https://github.com/nim-lang/Nim/issues/18840
2022-08-09 14:04:52 -04:00
ee7
b4157f6772 docs: fix some spelling errors (#19816)
* docs: fix some spelling errors

* contributing: fix spelling error

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

* Update contributing.md

* Update intern.md

* Update manual.md

* Update manual_experimental_strictnotnil.md

* Update nimgrep_cmdline.txt

* Update pegdocs.txt

* Update testament.md

* Update tut1.md

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>
Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2022-08-09 14:01:46 -04:00
ringabout
e8ae2dc90b bootstrap the compiler with nimPreviewSlimSystem (#20176)
* bootstrap the compiler with nimPreviewSlimSystem

* threads
2022-08-09 16:32:29 +08:00
ringabout
cddd4de658 fixes broken ssl tests (#20181) 2022-08-09 11:48:17 +08:00
ringabout
80a0dc295b update the docs of arc following up #19749 (#19752)
Co-authored-by: flywind <43030857+xflywind@users.noreply.github.com>
2022-08-08 16:56:37 +08:00
ringabout
4f4501abbc fixes links in the readme (#20167) 2022-08-07 23:50:55 +08:00
ringabout
fd6640fcda [minor] don't find "Hint: gc" for action (#20170) 2022-08-07 23:50:26 +08:00
ringabout
3bd935f331 fixes #20153; do not escape _ for mysql [backport] (#20164)
* fixes #20153; do not escape `_` for mysql

* add a test

* Update db_mysql.nim

* Update tdb_mysql.nim

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2022-08-05 17:15:58 -04:00
konsumlamm
3fef2fd52c Improve error message for strutils.addf (#20157)
Co-authored-by: ringabout <43030857+ringabout@users.noreply.github.com>
2022-08-05 13:44:21 -04:00
ringabout
714eb65866 remove annoying dropdowns from the bug form (#20154)
* Update bug_report.yml

* Update bug_report.yml

* Update bug_report.yml
2022-08-05 02:56:08 +08:00
Sojin
0641df33aa Two broken links found (#20121)
Updated the two broken internal links: rebuilding the compiler, reproducible builds
2022-08-04 12:53:42 -04:00
Juan Carlos
2f3980f491 Add bug form (#19913)
* Add Bug Form

* Add Bug Form

* Add Bug Form

* Add Bug Form

* https://github.com/nim-lang/Nim/pull/19913#issuecomment-1160663243

* https://github.com/nim-lang/Nim/pull/19913#issuecomment-1160663243

* Update .github/ISSUE_TEMPLATE/bug_report.yml

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

* Update .github/ISSUE_TEMPLATE/bug_report.yml

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

* Update .github/ISSUE_TEMPLATE/bug_report.yml

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

* Update .github/ISSUE_TEMPLATE/bug_report.yml

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

* Update .github/ISSUE_TEMPLATE/feature_request.yml

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

* Update .github/ISSUE_TEMPLATE/feature_request.yml

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

* Do not Star Nim on Github

* No backwards compat problems

* Typo

Co-authored-by: Yardanico <tiberiumk12@gmail.com>
Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>
2022-08-04 11:15:22 +02:00
Andrey Makarov
a34dd3d77a Markdown code blocks part 3 (#20117)
No logic was added, just 4 more files migrated.
2022-08-04 09:32:23 +02:00
ringabout
2aeb0d516b fixes #20132; fixes the broken jsondoc comand [backport] (#20135)
* fixes #20132; fixes the broken jsondoc comand

* add testcase
2022-08-04 08:49:51 +02:00
gecko
7af484da94 Add client.close() in httpclient examples. (#20118)
Without this, the httpclient examples are essentially setting you up for failure. I was bitten by this when my app became unable to open any more sockets.

I'm not entirely sure how long this will relevant, as I hope destructors will be added to an upcoming version of the stdlib. But figured it was worth submitting anyways!
2022-08-04 06:46:08 +02:00
ringabout
09840c09e4 closes #20123; remove builds.sr.ht (#20131) 2022-08-03 16:05:57 -04:00
ringabout
c08c455016 Revert "enable nimPreviewDotLikeOps" (#19919)
* Revert "enable nimPreviewDotLikeOps (#19598)"

This reverts commit 6773ffa63d.

* add deprecated message

Co-authored-by: flywind <43030857+xflywind@users.noreply.github.com>
2022-08-03 22:39:14 +08:00
Yuriy Glukhov
0d734d7966 Fixed compilation of void closureiters with try stmt (#20138) [backport] 2022-08-03 08:46:36 +02:00
random-bites
02cbd7dc53 Edits to sections 'Open arrays' and 'varargs'. (#20140) 2022-08-03 08:44:14 +02:00
Sultan Al Isaiee
da267911ec [Changelog] Add Wider Ascii Chars sets string formatting in strutils.nim (#20137)
* Add Wider Ascii Chars sets string formatting in strutils.nim

Add Wider Ascii Chars sets for string formatting (#19994) (#20120):
- Added `UppercaseLetters`, `LowercaseLetters` The set of UppercaseLetters and lowercase ASCII letters.
- Added `PunctuationChars` The set of all ASCII punctuation characters.
- Added `PrintableChars` The set of all printable ASCII characters (letters, digits, whitespace, and punctuation characters).

* Update changelog.md

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

* Update changelog.md

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>
Co-authored-by: ringabout <43030857+ringabout@users.noreply.github.com>
2022-08-02 19:50:42 +08:00
ringabout
59befed8ee prevent cache thrashing (#20129)
* prevent cache thrash

Co-authored-by: Charles Blake <cb@cblake.net>

* Update lib/pure/random.nim

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

Co-authored-by: Charles Blake <cb@cblake.net>
Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>
2022-08-02 00:06:27 +08:00
Clay Sweetser
77891cedae Fix "Add Wider Ascii Chars sets and func for string formatting" (#20120) 2022-07-31 23:24:14 -04:00
Sultan Al Isaiee
3987a3bf97 Add Wider Ascii Chars sets and func for string formatting (#19994)
* Add more Ascii Chars sets

- add UpperCaseLetters set
- add LowerCaseLetters set
- add Punctuations set
- add PrintablesNoWhiteSpace set
- add Printables set
- add isPunctuationAscii func
- add isPrintableAscii func

* Omit isPunctuationAscii and isPrintableAscii procs

* Apply suggestions for adding Wider Ascii Chars sets

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>

* Update strutils.nim

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2022-07-31 20:20:25 -04:00
quantimnot
313ce91533 [Doc] Fix some minor markup errors in manual (#20112)
* Fix header level for noalias pragma section.
* Fix code snippet outside of code block that raised an error with `rst2html`.
* Fix broken 'Convertible relation' links that were raising warnings.

Co-authored-by: quantimnot <quantimnot@users.noreply.github.com>
2022-07-31 20:08:01 -04:00
ringabout
a8590d6707 [ORC] replace threadpool with createThread in the runnableExamples (#20106)
replace threadpool with createThreads in the runnableExamples
2022-07-31 20:02:23 -04:00
ringabout
86fc78a9c0 replace the broken link for ORC implementation with a working one (#20105) 2022-07-31 20:01:36 -04:00
Andrey Makarov
40e0048a50 Highlight Nim default in Markdown code in .nim (#20110)
Highlight Nim by default in Markdown code in .nim
2022-07-31 15:38:00 +02:00
Sojin
99dd588d6b The internal link to koch.rst docs was broken (#20113)
Broken Link found for koch.rst docs

The Current internal link was broken. Updated with a new link to the same path
2022-07-31 11:07:06 +02:00
konsumlamm
528b6d1c3f Warn when casting to a larger type (#20103)
* Warn when casting to a larger type

* Revert change to error message to fix CI
2022-07-28 15:09:58 +02:00
Yuriy Glukhov
424e87fd09 Fixed noinit pragma for closure variables (#20101) 2022-07-28 18:43:41 +08:00
ringabout
8ef509b85b fixes broken CI; bump macOS version to macos-11 (#20098)
* bump macOS image on Azure CI to macos-11

##[warning]The macOS-10.15 environment is deprecated, consider switching to macos-11(macos-latest), macos-12 instead. For more details see https://github.com/actions/virtual-environments/issues/5583

* fix CI error
2022-07-27 21:06:34 +08:00
ringabout
5bbc5edf43 fixes #20031; uint64 is an ordinal type since 1.0 (#20094)
* fixes #20031; uint64 is an ordinal type since 1.0

* Update compiler/semstmts.nim
2022-07-27 11:15:51 +02:00
ringabout
4c46358db1 remove shallowCopy for ARC/ORC (#20070)
* remove shallowCopy for ARC/ORC

* use move

* fix

* more fixes

* typo

* Update lib/system.nim

* follow

* add nodestroy

* move

* copy string

* add a changelog entry

Co-authored-by: xflywind <43030857+xflywind@users.noreply.github.com>
Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2022-07-26 16:51:01 +02:00
ringabout
1c39af3389 fixes #20089; remove setPointer since strings/seqs are not pointers with ORC (#20090)
fixes #20089; remove setPointer since strings/seqs are not pointers anymore
2022-07-26 16:48:01 +02:00
metagn
3d5f10f0d0 clean up and clarify changelog [skip ci] (#20093) 2022-07-26 16:44:13 +02:00
Lancer11211
efd5c571bf .forbids pragma: defining forbidden tags (#20050)
* .forbids pragma: defining illegal effects for proc types

This patch intends to define the opposite of the .tags pragma: a way to define effects which are not allowed in a proc.

* updated documentation and changelogs for the forbids pragma

* renamed notTagEffects to forbiddenEffects

* corrected issues of forbids pragma

the forbids pragma didn't handle simple restrictions properly and it also had issues with subtyping

* removed incorrect character from changelog

* added test to cover the interaction of methods and the forbids pragma

* covering the interaction of the tags and forbids pragmas

* updated manual about the forbids pragma

* removed useless statement

* corrected the subtyping of proc types using the forbids pragma

* updated manual for the forbids pragma

* updated documentations for forbids pragma

* updated nim docs

* updated docs with rsttester.nim

* regenerated documentation

* updated rst docs

* Update changelog.md

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

* updated changelog

* corrected typo

Co-authored-by: ringabout <43030857+ringabout@users.noreply.github.com>
2022-07-26 07:40:49 +02:00
Andrey Makarov
62b81d7f10 Markdown code blocks part 2; migrate Nim Manual (#20080)
* Change headings underscored by `~~~` to `###`

* Markdown code blocks part 2; migrate Nim Manual
2022-07-25 18:29:52 +02:00
metagn
685bf944aa fix #20067, fix #18976 [backport] (#20069) 2022-07-22 15:04:07 +08:00
tersec
1a9123eb90 Use passc and passl consistently with compiler checking (#20068) 2022-07-21 09:41:33 +02:00
kraptor
efcb89fa70 Correctly detect major version of GCC (#20059)
We were doing a very poor job detecting the major version of GCC by
parsing the output of --version.

This patches uses -dumpversion to make this parsing straightforward and
it also fixes a bunch of compiling issues on different platforms with
custom output for --version switches. For example, openSUSE first line
of the output includes the revision number and the parsing that was
being done did mix that number with the major version and breaks
building the nim compiler (as it doesn't find the 3 dots for an X.Y.Z semver
format, hence returning "false").

In this patch, we simply use -dumpversion (which has been at least from
1993, so we are safe :)
2022-07-18 21:24:39 +02:00
flywind
d934ba9326 replace shallowcopy with move in ARC/ORC (#20061) 2022-07-18 21:23:39 +02:00
Anna
2549d398a9 niminst: support DESTDIR and quote variables (#20051)
* niminst: support DESTDIR (fix #9788)

* niminst: quote variables
2022-07-18 21:22:53 +02:00
Antonis Geralis
f34734ffb4 Improve rand(bool) (#20045)
* Improve rand(bool)

* Use sign test instead of mod 2

* Use mod 2 again, as it works for js

* Use right shift as suggested by the authors of xoroshiro

* Update random.nim

* General case doesn't need any right shift it was correct to begin with

* Update random.nim

* add comment

Co-authored-by: flywind <43030857+xflywind@users.noreply.github.com>
2022-07-18 21:18:12 +02:00
Jacek Sieka
f2e4407306 epoll: correct mapping [backport] (#20058)
* epoll: correct mapping

`epoll_data` is a union and `epoll_event` is packed on `amd64`

* names
2022-07-18 21:03:25 +02:00
LetThereBeLemons
f443bece06 Fixed typo in std/os doc (#20054)
Fixed typo
2022-07-18 14:20:30 +08:00
Jacek Sieka
c6264ed847 fix pthread_mutex_t size (#20055) 2022-07-18 06:44:47 +02:00
Don-Duong Quach
efdcc00169 Fixed errors in Nim Backend integration docs. (#20046)
Fixed errors in Nim Backend integration.
Section "Nim invocation example from C"
NimMain needs a declaration and function declarations have external
linkage by default.
Also with the order of arguments to gcc with a static lib,
maths.c needs to come before the static lib.
2022-07-17 09:32:33 +02:00
flywind
01ad0cdc52 defines the gcRefc symbol which allows writing specific code for refc (#20009)
* define gcRefc symbols

* add comments

* add a changelog item

* Update changelog.md

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

* Update changelog.md

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

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>
Co-authored-by: Yardanico <tiberiumk12@gmail.com>
2022-07-17 09:24:40 +02:00
Peter Guld Leth
0d8bec6956 Fix typo in line 456 (#20047) 2022-07-17 00:00:28 +02:00
kraptor
8679464e49 Display protocol name in exceptions raised by getProtoByName() (#19808) 2022-07-16 17:44:14 -04:00
Jake Leahy
c43a377057 Make imports/exports not be a dropdown in sidebar (#19907)
* Don't make a section be a dropdown if it has no child links

* - Cleaned up code

- Updated tests

* Document what the 'if' is checking
2022-07-16 17:41:18 -04:00
Jacek Sieka
094d86f997 testament: use full test name in skips [backport] (#19937)
testament: use full test name in skips
2022-07-16 16:56:54 -04:00
Amjad Ben Hedhili
cf78c02b70 Make random.rand work with Ordinal (#20043)
* Make `random.rand` work with `Ordinal`

* Add changelog entry

* It's fine to cast to char
2022-07-16 16:51:27 -04:00
David Krause
60dd38c502 make AsyncSocket.getPeerAddr work ; fix #15022 (#20038)
Signed-off-by: David Krause <enthus1ast@users.noreply.github.com>
2022-07-16 10:59:58 +01:00
Ivan Yonchovski
b0b9a3e5fa Use module actual file instead of PSym.info (#19956)
After this you can do goto module from module import
2022-07-15 19:56:33 +02:00
Ivan Yonchovski
e636c211b0 Implement type command (#19944)
* Implement type command

- this will be mapped to textDocument/typeDefinition in LSP protocol. It will be
very useful for `nim` in particular because typically most of the time the type
is inferred.

* Update nimsuggest/nimsuggest.nim

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2022-07-15 19:56:05 +02:00
Andrey Makarov
417b90a7e5 Improve Markdown code blocks & start moving docs to Markdown style (#19954)
- add additional parameters parsing (other implementations will just
  ignore them). E.g. if in RST we have:

  .. code:: nim
     :test: "nim c $1"

     ...

  then in Markdown that will be:

  ```nim test="nim c $1"
  ...
  ```

- implement Markdown interpretation of additional indentation which is
  less than 4 spaces (>=4 spaces is a code block but it's not
implemented yet). RST interpretes it as quoted block, for Markdown it's
just normal paragraphs.
- add separate `md2html` and `md2tex` commands. This is to separate
  Markdown behavior in cases when it diverges w.r.t. RST significantly —
most conspicously like in the case of additional indentation above, and
also currently the contradicting inline rule of Markdown is also turned
on only in `md2html` and `md2tex`. **Rationale:** mixing Markdown and
RST arbitrarily is a way to nowhere, we need to provide a way to fix the
particular behavior. Note that still all commands have **both** Markdown
and RST features **enabled**. In this PR `*.nim` files can be processed
only in Markdown mode, while `md2html` is for `*.md` files and
`rst2html` for `*.rst` files.
- rename `*.rst` files to `.*md` as our current default behavior is
  already Markdown-ish
- convert code blocks in `docgen.rst` to Markdown style as an example.
  Other code blocks will be converted in the follow-up PRs
- fix indentation inside Markdown code blocks — additional indentation
  is preserved there
- allow more than 3 backticks open/close blocks (tildas \~ are still not
  allowed to avoid conflict with RST adornment headings) see also
https://github.com/nim-lang/RFCs/issues/355
- better error messages
- (other) fix a bug that admonitions cannot be used in sandbox mode; fix
  annoying warning on line 2711
2022-07-15 19:27:54 +02:00
metagn
f35c9cf73d fix #20002 (#20004)
While this fix seems innocent,
this unlocks the hidden behavior of
method calls not being able to call
gensym'ed routines inside templates.
2022-07-15 12:37:08 +02:00
flywind
286fcef68e [Orc] fixes "streams.readDataStr segafaults" when accepting a string literal (#20019) [backport]
fixes streams.readDataStr accept a string literal
2022-07-15 09:42:54 +02:00
quantimnot
800cb006e7 Change styleCheck to ignore foreign packages (#19822)
* Change `styleCheck` to ignore foreign packages

* Symbols from foreign packages are now ignored.
* Fixed `styleCheck` violations in `compiler` package.
* Added symbol ownership to custom annotation pragmas.
* Minor refactors to cleanup style check callsites.
* Minor internal documentation of reasons why a symbol isn't checked.

Style violations were fixed in the compiler after thet were exposed by
the changes. The compiler wouldn't compile otherwise.

Symbol ownership for custom pragma annotations is needed for checking
the annotation's style. A NPE was raised otherwise.

Fixes #10201
See also nim-lang/RFCs#456

* Fix a misunderstanding about excluding field style checks

I had refactored the callsites of `styleCheckUse` to apply the DRY
principle, but I misunderstood the field access handling in a template
as a general case. This corrects it.

* Fix some `styleCheck` violations in `compiler/evalffi`

The violations were exposed in CI when the compiler was built with
libffi.

* Removed some uneeded transitionary code

* Add changelog entry

Co-authored-by: quantimnot <quantimnot@users.noreply.github.com>
2022-07-14 14:20:40 +02:00
flywind
10c8e2037d fixes #20015; document shallowCopy does a deep copy with ARC/ORC (#20025) 2022-07-14 18:42:56 +08:00
silent-observer
93211a2bdd Add sink and lent annotations to the critbits module (#20021)
* Add sink and lent to critbits

* Remove lent for pairs
I guess lent doesn't work well inside tuples

* Remove lent from template in critbits
Apparently this also doesn't work, because some checks failed
2022-07-14 12:03:16 +02:00
flywind
73ee34f56f use pull_request_target (#20020) 2022-07-13 22:37:31 +08:00
Daniel Clarke
489f6ddfef fix #20012 (#20013)
* replace gcc asm with __asm__ and add a test

* update test case to specify gcc or clang and not cpp

Co-authored-by: daniel <danielclarke@wearepopgun.com>
2022-07-13 20:55:33 +08:00
metagn
af140966ea Add #19406 changes to changelog (#20011) 2022-07-12 23:24:17 +02:00
flywind
0180c6179a fix #18735; genDepend broken for duplicate module names in separate folders (#19988) 2022-07-12 19:35:08 +02:00
metagn
5c510a9ab9 allow dots in defined() (#20010)
* allow dots in defined()

refs https://github.com/nim-lang/RFCs/issues/181

* mention accents in older versions
2022-07-12 18:03:58 +02:00
flywind
a97b00ad8d try to optimize hot spots for orc-booting compiler (#20001)
* optimize hot spots fro orc-booting compiler

* remove GC_ref

* minor

* remove comments

* Revert "minor"

This reverts commit 4965a190a2.

* emulate cursor
2022-07-12 13:07:18 +02:00
flywind
d0bae989d6 fix github script failure (#20006)
* yaml

* pub

* redo

* let's comment

* now action

* newly

* code name

* build

* ready

* remove submodule

* build

* modify name

* fix

* rephrase

* trigger when PR is merged

* fix CI failure
2022-07-12 09:05:50 +08:00
flywind
cf1c149366 tracking the memory usage of orc-booting compiler for each commit (#19941)
* yaml

* pub

* redo

* let's comment

* now action

* newly

* code name

* build

* ready

* remove submodule

* build

* modify name

* fix

* rephrase

* trigger when PR is merged
2022-07-11 23:27:01 +08:00
Tanguy
fb5fbf1e08 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>
2022-07-11 11:28:52 +02:00
Juan M Gómez
a90763ebd7 Fixes Compilation error with --app:lib (#19965)
Fixes Compilation error with --app:lib  when a module tries to pull os.paramStr on posix by throwing a runtime exception instead. 
More details here: #19964
2022-07-10 15:40:26 +02:00
flywind
ed2bf02a51 remove when declared(cache); cache is always there (#19991) 2022-07-10 09:37:15 +02:00
flywind
e8ee2f9c2a update section regarding std/assertions in changelog (#19992)
Update changelog.md
2022-07-09 17:28:14 +08:00
Andreas Rumpf
7a29a782f8 removed caching logic; saves 400MB for an ORC booting compiler (#19989) 2022-07-09 06:46:05 +02:00
Jacek Sieka
ad0aee5354 sysrand: fix syscall signature [backport] (#19982)
sysrand: fix syscall signature

`syscall` is a `C` varags function
2022-07-07 21:26:58 +08:00
flywind
dcb28fd061 cache rope when threads are enabled (#19981)
* cache rope

* add threadvar
2022-07-07 14:14:05 +02:00
flywind
430a179307 default threads on (#19368)
* default threads on

* make rst gcsafe

* ignore threads option for nimscript

* threads off

* use createShared for threads

* test without threads

* avr threds off

* avr threads off

* async threads off

* threads off

* fix ci

* restore option

* make CI pleased

* fix ic tests

* Update config.nims

* add changelog

* Update changelog.md

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>
2022-07-06 13:06:41 +02:00
Daniel Clarke
01b40dc1d7 Fixes return values of execCmd on macos (#19963)
* Fixes return values of execCmd on macos

* update tests to use existing structure

Co-authored-by: daniel <danielclarke@wearepopgun.com>
2022-07-05 22:29:05 +02:00
flywind
7d0285853f rename gc to mm (#19971) 2022-07-05 10:11:34 +02:00
rockcavera
d2d8f1342b Fixing nimRawSetJmp for vcc and clangcl on Windows (#19959)
* fix vcc rawsetjmp

* changing `_longjmp()` to `longjmp()` and

`_setjmp()` to `setjmp()`

* fix

* fix setjmp to clangcl on Windows

* fix genTrySetjmp() to clangcl on Windows
2022-07-04 13:52:44 +02:00
flywind
4897c47c80 closes #15897; add testcase (#19961) 2022-07-02 16:51:21 +08:00
Tanguy
ce4078acd4 Allow recursive closure iterators (#19939) 2022-06-30 23:19:04 +02:00
Juan Carlos
2c0aaac304 jsffi add missing braces (#19948)
js codegen add missing whitespaces and braces
2022-06-30 23:18:11 +02:00
Sam Zaydel
306810a748 Enable nim-lang to build correctly on illumos-based systems (#19952) 2022-06-30 23:16:50 +02:00
Jacek Sieka
ad430c0daa once C++, always C++ [backport] (#19938)
* once C++, always C++

When using `{.compile: "file.cc".}` in a nim module, even when compiling
with `nim c` the C++ compiler should be used - once any C++ file has
been compiled, the C++ linker also needs to be used.

* more strict C++ check

* simplify code
2022-06-30 10:20:19 +02:00
flywind
bcff13debc dec inLoop after exiting the while scope in computeLiveRanges [backport] (#19918)
* dec inLoop after exiting the while scope in computeLiveRanges

* add testcase
2022-06-29 22:37:24 +08:00
flywind
8a344cb25b closes #11042; add testcase (#19935)
close #11042; add testcase
2022-06-28 16:49:31 +08:00
Juan Carlos
7c31b6a47b Fix jsre (#19917)
* Fixes for jsre to make it more safe at runtime on some edge cases

* https://github.com/nim-lang/Nim/pull/19917#issuecomment-1162692893
2022-06-28 08:13:17 +02:00
flywind
0189122d4f ref #19830; multiple definition of in Nim generated static libraries (#19934)
* ref #19830; multiple definition of in Nim generated static libraries

* fix compile errors
2022-06-27 17:57:07 +02:00
Khaled Hammouda
caf6aff06b Fix distinct requiresInit test and manual (#19901)
fix distinct test and manual
2022-06-22 12:36:30 +02:00
flywind
3cb2d7af05 [vm]fixes #15974 #12551 #19464 #16020 #16780 #16613 #14553 #19909 #18641 (#19902) [backport]
* revert #12217 since the root problem seems to have been fixed; fix #15974;fix #12551; fix #19464

* fix #16020; fix #16780

* fix tests and #16613

* fix #14553

* fix #19909; skip skipRegisterAddr

* fix #18641
2022-06-22 08:43:58 +02:00
flywind
a65db5e2e9 [Tiny] correct comment opcDeref => opcLdDeref (#19908)
correct comment opcDeref => opcLdDeref
2022-06-21 09:37:23 +02:00
flintforge
0ae44e562f fix typo in nre.nim (#19915)
Update nre.nim

typo in proc replace description
2022-06-21 09:53:46 +08:00
Tanguy
40464fa762 Fix nimRawSetjmp for VCC [backport: 1.2] (#19899) 2022-06-20 08:21:20 +02:00
tersec
5e32fc7855 Recommend gcc 5.x or newer (#19910) 2022-06-20 08:01:41 +02:00
Jake Leahy
dd4cc266cd Fixes #19900 (#19906)
Fixed tocRoot placement
2022-06-19 07:36:33 +02:00
flywind
332aa0af75 [vm] refactor stdlib.marshal.load (#19905)
refactor stdlib.marshal.load
2022-06-19 07:35:25 +02:00
flywind
ef2dd2e473 document nimTestsNimdocFixup for rsttester (#19894) 2022-06-16 08:46:59 +02:00
Tanguy
d33e112766 Better range error messages (#19867)
* Better range error messages

* Revert to old behavior for arrays

* Small corrections
2022-06-15 16:38:12 +02:00
JJ
e7e8f437c4 Keep the doc sidebar on the screen while scrolling (#19851)
* [docgen] Group sidebar sections into <details> (open by default)

* [docgen] Consistent indentation in generated HTML

(this is a boon for working on docgen's html/css output)

* [docgen] Move Source/Edit buttons inside main div

This makes styling the documentation significantly easier.

* [docgen] Somewhat consistent CSS formatting

* [docgen] Keep the sidebar onscreen while scrolling

* [docgen] Tweak CSS for the sticky sidebar

* [docgen] search type=text ==> type=search

* [docgen] Update expected doc output

* [docgen] Fix Group by Type sidebar placement bug

* [docgen] Curse you, whitespace (fix tests)

* [docgen] Fix rst2html tests

Co-authored-by: sandytypical <43030857+xflywind@users.noreply.github.com>
2022-06-15 15:40:56 +02:00
Don-Duong Quach
789b1bcbb6 Fixes #19883 so genscript works with vcc (#19893) 2022-06-15 08:20:34 +02:00
Tanguy
251bdc1d5a Windows: enable nimRawSetjmp by default [backport] (#19891)
* Windows: enable nimRawSetjmp by default

See #19197. The default setjmp can randomly segfault on windows

* Attempt to disable the flag for bootstraping

* Disable styleCheck for c_setjmp
2022-06-14 12:37:31 +02:00
Ivan Yonchovski
b41226001c Initial implementation of nimsuggest v3 (#19826)
* Initial implementation of nimsuggest v3

Rework `nimsuggest` to use caching to make usage of ide commands more efficient.
Previously, all commands no matter what the state of the process is were causing
clean build. In the context of Language Server Protocol(LSP) and lsp clients
this was causing perf issues and overall instability. Overall, the goal of v3 is
to fit to LSP Server needs

- added two new commands:
  - `recompile` to do clean compilation
  - `changed` which can be used by the IDEs to notify that a particular file has been changed.
The later can be utilized when using LSP file watches.
  - `globalSymbols` - searching global references

- added `segfaults` dependency to allow fallback to clean build when incremental
fails. I wish the error to be propagated to the client so we can work on fixing
the incremental build failures (typically hitting pointer)

- more efficient rebuild flow. ATM incremental rebuild is triggered when the
command needs that(i. e. it is global) while the commands that work on the
current source rebuild only it

Things missing in this PR:

- Documentation
- Extensive unit testing.

Although functional I still see this more as a POC that this approach can work.

Next steps:
- Implement `sug` request.
- Rework/extend the protocol to allow better client/server communication.
Ideally we will need push events, diagnostics should be restructored to allow
per file notifications, etc.
- implement v3 test suite.
- better logging

* Add tests for v3 and implement ideSug

* Remove typeInstCache/procInstCache cleanup

* Add ideChkFile command

* Avoid contains call when adding symbol info

* Remove log

* Remove segfaults
2022-06-13 11:33:44 +02:00
Ardek Romak
a4fdaa88cc Correctly import libcrypto functions using dynlib (#19881) 2022-06-13 09:22:20 +02:00
flywind
ab47707586 [semfold] fix #19199; properly fold uint to float conversion (#19890) [backport]
fix #19199; properly fold float conversion
2022-06-13 09:01:40 +02:00
flywind
2f4900615a [cleanup] remove unnecessary procs in vm (#19888)
remove unused procs
2022-06-13 08:10:40 +02:00
Jake Leahy
8fa2c0b532 Pass headers and body correctly to FetchOptions (#19884) [backport]
* Pass headers to FetchOptions

Don't pass body if method is HttpGet or HttpHead

* Syntax fixes

* Restart CI
2022-06-13 08:03:40 +02:00
Carlo Capocasa
e2e663a143 Friendlier error message with solution (#19880)
* Add helpful suggestion, should always apply

* mention var param limitation in async docs

* Update compiler/lambdalifting.nim

whoops thanks

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

Co-authored-by: flywind <43030857+xflywind@users.noreply.github.com>
2022-06-11 18:23:31 +02:00
Bung
ac89eead8a test for #19046 (#19839)
* test for #19046

* add threads flag
2022-06-10 20:40:34 +02:00
quantimnot
6f4bacff67 Extend and document compiler debugging utilities (#19841)
* Add two debugutils procs that native debuggers can break on use to
  execute commands when code of interest is being compiled.
* Add GDB and LLDB programs to disable and enable breakpoints and
  watchpoints when code of interest is being compiled.
* Extend the `intern.rst` docs regarding debugging the compiler.

Co-authored-by: quantimnot <quantimnot@users.noreply.github.com>
2022-06-10 20:40:08 +02:00
flywind
1e5dd9022b [js] add testcase for array indexDefect and remove todo (#19838)
* remove unused opcSubstr

* [js] add testcase for array indexDefect

* Revert "remove unused opcSubstr"

This reverts commit cb461f2545.
2022-06-10 20:33:44 +02:00
flywind
8cde6ba6bc remove noop option gc:v2 (#19810)
* remove noop option gc:v2

* changelog
2022-06-10 20:32:27 +02:00
flywind
eefca1b81f not generate initStackBottomWith in arc/orc [backport] (#19875)
not generate initStackBottomWith in arc/orc
2022-06-10 21:24:28 +08:00
flywind
1972005439 fix #19862; make widestrs consistent between refc and orc (#19874) [backport]
fix #19862; make widestrs consistent in refc and orc
2022-06-09 16:51:17 +02:00
Andreas Rumpf
25d89269eb give a better error message for some template expansions (#19871) 2022-06-09 14:21:18 +02:00
Antonis Geralis
836b95c896 Deprecate std/sums (#18439)
* Deprecate sums

* Update changelog.md

* Update lib/std/sums.nim

* log

* format

* remove

* Update changelog.md

Co-authored-by: sandytypical <43030857+xflywind@users.noreply.github.com>
2022-06-09 08:27:31 +02:00
flywind
415689323c clarify how to restart CI (#19845) 2022-06-08 18:17:25 +02:00
Zoom
e1702ae1e6 changelog.md: Add strutils.find changes (#19868)
Added `strutils.find` changes

Standard library section restructured to group by `changed/added/deprecated/removed` with paragraphs marked by markdown comments.
2022-06-08 16:11:22 +02:00
Juan Carlos
f2b16c490d Add Microtasks docs (#19870)
* Add Microtasks

* Add Microtasks

* Workaround to build js docs in older NodeJS versions
2022-06-08 16:10:52 +02:00
Zoom
b024a45163 Fix find routines' api to default to last=-1 (#19761)
This changes the default for the `last` parameter of various `find`
routines from `0` to `-1`. Previous default prevents limiting the search
to the first character. This is a logic error, as full text search was
performed for 2 *valid* values of `last`: `0` and `last.high()`.

Adds an overload for `initSkipTable` which returns a newly initialized
table. This encapsulates every single usage of a `var`-acting original
func in this module.

Co-authored-by: flywind <xzsflywind@gmail.com>
2022-06-07 10:35:06 +02:00
Juan Carlos
d0232f0e5b Add Microtasks (#19860)
* Add Microtasks

* Add Microtasks
2022-06-04 07:03:25 +02:00
Andrey Makarov
4341b06f65 RST: improve simple tables (#19859)
* RST: improve simple tables

* nim 1.0 gotchas

* Still allow legacy boundaries like `----`
2022-06-04 07:03:03 +02:00
quantimnot
f7a13f62d6 Stop type aliases from inheriting sfUsed (#19861)
Fixes #18201

Co-authored-by: quantimnot <quantimnot@users.noreply.github.com>
2022-06-04 06:25:21 +02:00
flywind
68aeb4c1a6 change the type of mangleJsName; fixes CStringConv warnings (#19852)
change the type of mangleJsName

since mangleJsName is used in macros, there is no need to use cstring. Using cstring may increase conversions and cause warnings.
2022-06-01 15:01:17 +02:00
flywind
4e3eb7414c [Minor] remove unused and unnecessary local variable (#19853) 2022-06-01 14:44:26 +02:00
quantimnot
d30c6419a0 Refactor and doc package handling, module name mangling (#19821)
* Refactor and doc package handling, module name mangling

* Consolidate, de-duplicate and extend package handling
* Alter how duplicate module names of a package are handled
* Alter how module names are mangled
* Fix crash when another package is named 'stdlib' (test case added)
* Doc what defines a package in the manual

Modules with duplicate names within a package used to be given 'fake'
packages to resolve conflicts. That prevented the ability to discern if
a module belonged to the current project package or a foreign package.
They now have the proper package owner and the names are mangled in a
consistent manner to prevent codegen clashes.

All module names are now mangled the same. Stdlib was treated special
before, but now it is same as any other package. This fixes a crash
when a foreign package is named 'stdlib'.

Module mangling is altered for both file paths and symbols used by the
backends.

Removed an unused module name to package mapping that may have been
intended for IC. The mapping was removed because it wasn't being used
and was complicating the issue of package modules with duplicate names
not having the proper package owner assigned.

* Fix some tests

* Refactor `packagehandling`

* Remove `packagehandling.withPackageName` and its uses
* Move module path mangling from `packagehandling` to `modulepaths`
* Move `options.toRodFile` to `ic` to break import cycle

* Changed import style to match preferred style

Co-authored-by: quantimnot <quantimnot@users.noreply.github.com>
2022-05-30 18:52:19 +02:00
Alfred Morgan
15f0b48676 Zectbumo fixes 19824 (#19825)
* borrowed `$` to make Time string friendly

* added sep character parameter

* Revert "added sep character parameter"

This reverts commit 45f4b019a4.

* added sep character parameter

* Revert "borrowed `$` to make Time string friendly"

This reverts commit 10e2e44c9a.

* added uri tests and made changelong entry

* Update lib/pure/uri.nim

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

* Update lib/pure/uri.nim

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

* Update tests/stdlib/turi.nim

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

* Update tests/stdlib/turi.nim

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>
2022-05-30 12:09:18 +02:00
quantimnot
497af2c0d9 Doc preferred import style in compiler (#19832)
Doc prefered import style in compiler

Co-authored-by: quantimnot <quantimnot@users.noreply.github.com>
2022-05-30 11:07:47 +02:00
flywind
004fc23a3f [vm] remove unused opcSubstr opcode (#19834)
remove unused opcSubstr
2022-05-30 10:41:24 +02:00
Michael New
14960fa754 Fix typo and incorrect pragma name (#19847) 2022-05-30 10:40:15 +08:00
flywind
d81edcacc6 Add link to std/tempfiles in the docs; fix #19155 (#19807) 2022-05-24 17:53:01 +02:00
tandy1000
ec0cec3170 Add document.hidden and document.visibilityState properties (#19817) 2022-05-24 17:37:39 +02:00
Juan Carlos
b1b5e3ab10 Add Array.shift (#19811)
* Add Array.shift for JavaScript targets

* Add Array.shift for JavaScript targets
2022-05-24 17:37:19 +02:00
quantimnot
05c0419658 Fix global destructor injection for JS backend (#19797)
* Fix global destructor injection for JS backend

* Moved global destructors injection before the final call to transform and
  generate JS code. It had previously been after and thus not no JS was
  generated for them.
* Added some internal documentation of `jsgen`.
* Enable a current destructor test to cover the JS backend as well.
* Fixes the JS aspect of #17237.

* Fixed global destructor injection order for JS backend

Co-authored-by: quantimnot <quantimnot@users.noreply.github.com>
2022-05-23 06:17:32 +02:00
quantimnot
a8426fc789 Fix default testament target in docs and cli help (#19796)
Co-authored-by: quantimnot <quantimnot@users.noreply.github.com>
2022-05-23 06:12:34 +02:00
Jacek Sieka
63cca93ea9 testament: include extra options in test name (#19801)
there's currently no (simple) way to disambiguate which option failed
2022-05-19 17:11:53 +02:00
Yardanico
06f02bb771 Always use httpclient in nimgrab (#19767) 2022-05-17 09:56:39 +02:00
flywind
33888a7384 [manual] TLock => Lock (#19785)
* [manual] TLock => Lock

* minor
2022-05-17 07:37:26 +02:00
Anthony Dario
19001c070b Fix typo in sequtils documentation (#19789)
Found another small typo.
2022-05-13 11:19:42 +08:00
flywind
c61eb5df32 disable polypbren (#19787)
* disable polypbren

* Update important_packages.nim
2022-05-13 01:03:30 +08:00
Alfred Morgan
b9f243eb2a string is missing formatting when calling fmt (#19780)
it appears the documentation intends to compare & with .fmt but there is no formatting in the string. even though the assert is true it doesn't quite prove that .fmt is an equivalent formatter.
2022-05-10 17:45:57 +02:00
Alfred Morgan
85bc8326ac varargs example erroneously transformed "abc" to "def" (#19781) 2022-05-10 20:21:35 +08:00
Juan Carlos
b2b878f4d6 Remove deprecated posix proc (#19774)
* Remove deprecated posix proc that takes wrong argument types

* Remove deprecated posix proc that takes wrong argument types
2022-05-08 11:56:46 +02:00
huantian
61c1142667 Update nimscript withDir doc example (#19776) 2022-05-08 11:54:25 +02:00
kraptor
8c100a37b9 Add new self-signed 4096 bit certificate to testdata (#19758)
The test tasyncssl may fail on modern linux versions
as they require at least 2048 bit certificates.

A new certificate and private key with default values
has been added to meet this new requirement.
2022-05-08 11:54:04 +02:00
kraptor
2c73e84436 "ip" protocol as id 0 is long gone (#19760)
IANA is using id 0 for "HOPOPT" instead of "ip"
for some time now and those systems that still
support the old mapping will stop doing so at
some point in the future.

Some BSDs and openSUSE are already following this
change as per IANA list here:
https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml

As new unixes (and maybe Windows, who knows) start
to adopt the updated IANA list, this will keep
failing from time to time, so it's better to
remove the "ip" check altogether.
2022-05-07 20:46:45 +02:00
Zoom
0455d24d55 Fix questionable suggestion in strutils docs (#19765)
* Fix questionable suggestion in `stutils` docs

- Removes the recommendation to pass a string slice for getting a relative
index for `find` and `rfind` functions, as this currently makes a string
copy, while a simple subtraction is enough.

- Docstring for `SkipTable` type.

* Doc layout fixup
2022-05-06 11:19:27 +02:00
Anthony Dario
a4401054cc Fix broken link in sets documentation. (#19769) 2022-05-06 17:16:00 +08:00
Zoom
278ecad973 Add 'usages' option to the --stylechecks error msg (#19759) 2022-05-04 15:24:52 +01:00
flywind
2ecae20c43 switch to mainline bigints (#19756) 2022-05-03 18:35:16 +08:00
Jake Leahy
832b8c5034 Fix link to experimental manual in macro pragmas section [skip ci] (#19753) 2022-05-03 10:08:39 +08:00
huantian
927978345b Rework discarding futures documentation in asyncdispatch (#19738)
* Rework discarding futures docs in asyncdispatch

* Fix typos

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

* Use rst note::

Co-authored-by: flywind <xzsflywind@gmail.com>

* Split discarding and handling futures.

* Update lib/pure/asyncdispatch.nim

* Update lib/pure/asyncdispatch.nim

* Update lib/pure/asyncdispatch.nim

* Update lib/pure/asyncdispatch.nim

Co-authored-by: Danil Yarantsev <tiberiumk12@gmail.com>
Co-authored-by: flywind <xzsflywind@gmail.com>
Co-authored-by: Dominik Picheta <dominikpicheta@googlemail.com>
2022-05-02 17:06:57 +01:00
nc-x
4680ab61c0 Fix fixAbstractType for user defined typeclasses, fixes #19730 & #18409 (#19732) 2022-04-30 15:58:58 +02:00
Ivan Yonchovski
e4a2c2d474 Make sure that field usage preserves the original line info (#19751)
Currently `struct.field` will generate a node with `info` that points to the
symbol definition instead of having the actual node location.
2022-04-29 11:16:07 +02:00
flywind
8bfc396a4d fixes #18612; apply cache and memcmp for methods in arc/orc (#19749)
* try using endsWith

* use memcmp

* add cache

* cleanup

* better

* minor

* fix

* improve test coverage for methods with ARC
2022-04-26 20:14:39 +02:00
Andreas Rumpf
ef4ac5a0d2 use signed comparisons for the index checking in the hope it improves the code generation (#19712) 2022-04-26 08:58:15 +02:00
ehmry
82680a12a7 macros: make hasCustomPragma more permissive (#19747)
Make hasCustomPragma return false rather than fail for invalid
parameters.
2022-04-25 22:16:11 +02:00
flywind
42ac50e988 fixes #19662; Indent level errored for first line (#19718) 2022-04-25 12:00:23 +02:00
Andreas Rumpf
ee0a470294 Revert "fix db_sqlite.tryInsertID does raise exceptions in 1.6.0 #19743 (#19744)" (#19745)
This reverts commit b10f0e7bca.
2022-04-25 11:59:37 +02:00
flywind
15ae9323e8 fix NimNode comment repr() regression [backport: 1.2] (#19726) 2022-04-25 11:19:21 +02:00
flywind
465fd06d50 add warnings for gc:option (#19722) 2022-04-25 11:18:26 +02:00
Danil Yarantsev
2f32b450d3 Really fix StringStream with ARC at compile-time, improve streams test (#19739)
* Fix compile-time StringStream with ARC

* make readDataStr work with ARC, improve test
2022-04-25 11:15:03 +02:00
flywind
efaa6777a4 fix #19435; don't create TypeBoundOps for tyOpenArray, tyVarargs [backport: 1.6] (#19723)
* fix #19435; openArray wronyly registers typebounds

* add testcase

* don't create TypeBoundOps for tyOpenArray, tyVarargs
2022-04-25 11:07:55 +02:00
tersec
8e6136dd59 document localPassC consistently with compiler; fix ANSI capitalization (#19721) 2022-04-25 11:06:53 +02:00
flywind
b10f0e7bca fix db_sqlite.tryInsertID does raise exceptions in 1.6.0 #19743 (#19744) 2022-04-24 14:20:18 -04:00
huantian
02e8aa9660 Fix doc: list of async backends (#19741) 2022-04-24 10:47:39 +01:00
Andrey Makarov
bb839029d5 Move common Latex code into class nimdoc.cls (#19734) 2022-04-21 15:06:09 -04:00
Jason Beetham
dc4cc2dca5 Fix string stream crashing when created on nimscript due to last fix (#19717) 2022-04-14 11:30:59 +02:00
huantian
ef7d7f2459 Better error message and tests for bad await (#19622)
* Better error message and tests for bad await

* Use compiles to check if await is valid

* temp: disable windows noasync test

* Better error report, simplify test

Co-authored-by: flywind <xzsflywind@gmail.com>
2022-04-13 23:03:46 +02:00
flywind
98cebad7de enable style:usages for stdlib tests [backport: 1.6] (#19715)
* enable style:usages for stdlib tests

* freeAddrInfo

* more tests

* importc

* bufSize

* fix more

* => parseSql and renderSql
2022-04-13 11:53:02 +02:00
flywind
26bcf18f91 fix #19680; check if stderr is static (#19709) 2022-04-12 09:48:48 +02:00
Jason Beetham
26acc97864 StringStreams no longer errors when intialized with literals on arc/orc (#19708) 2022-04-11 14:27:12 +02:00
flywind
a77ffdb7ea fix #17286 nim check -b:js works (#19704)
* fix #17286 nim check -b:js works

* fix
2022-04-09 17:52:11 +02:00
Leon
152dab0983 fix: Fix introductory macro examples (#19706)
Co-authored-by: adigitoleo <adigitoleo@dissimulo.com>
2022-04-09 17:51:44 +02:00
flywind
ded8b0e541 rewrite docs JS in Nim (#19701)
* rewrite docs JS in Nim

* fixup

* fix nimdoc/rsttester
2022-04-09 17:50:57 +02:00
flywind
00775f6880 fix stylecheck bug with nre (#19356)
* stylecheck usages part two: stdlib cleanup

typeinfo.nim: importCompilerProc => importcompilerproc

nre.nim: newLineFlags => newlineFlags

system.nim: JSRoot => JsRoot

ref #19319

* prefer importCompilerProc

* fix stylecheck error with asyncdispatch

it is a partial regression since #12842

* add tests

* don't use echo in tests

* fix stylecheck bug with nre

* Update compiler/linter.nim

* no need to check dotexpr again

* neither did let/var/const
2022-04-08 08:04:46 +02:00
Timothee Cour
e78ef57c93 typetraits: add toSigned, toUnsigned (#18445)
* typetraits: add toSigned, toUnsigned

* improve and add tests

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
Co-authored-by: flywind <xzsflywind@gmail.com>
2022-04-07 17:38:01 -04:00
flywind
1807de38e5 add testcase for #16462 (#19692) 2022-04-07 20:57:50 +02:00
flywind
c8aeea9d62 improve the error messages for std/tasks [backport: 1.6] (#19695) 2022-04-07 20:56:34 +02:00
Ivan Yonchovski
810d5e91e4 [nimsuggest] return the type when on symbol in let/var (#19639)
- make sure `suggestSym` is called after `PSym.typ` is set.
2022-04-07 13:39:27 +02:00
flywind
0978276ed9 use two spaces indentation (#19696) 2022-04-07 13:07:39 +08:00
flywind
e1929deac7 remove useless compilation condition (#19690)
ref https://github.com/nim-lang/Nim/pull/18546
2022-04-07 07:11:25 +08:00
Nan Xiao
065f568470 No need to export pos from OptParser (#19688)
Co-authored-by: flywind <xzsflywind@gmail.com>
2022-04-06 20:28:58 +02:00
Jacek Sieka
cb6ce80cb8 std/tasks: fix spelling (#19691) [backport]
why aren't these not being caught by style check options?
--styleCheck:usages finds it.

Co-authored-by: flywind <xzsflywind@gmail.com>
2022-04-06 20:28:37 +02:00
flywind
e649ddd09b Revert "Load Google Fonts last (#19683)" (#19693)
This reverts commit abe3b0eb64.
2022-04-06 20:27:51 +02:00
locriacyber
abe3b0eb64 Load Google Fonts last (#19683) 2022-04-06 18:08:27 +02:00
Miran
c322faaf38 [backport] fix broken SSL tests (#19684)
* [backport] fix broken SSL tests

* remove a flaky one
2022-04-06 16:18:10 +02:00
flywind
5a995ffc53 fix #18986; Import/except doesn't work on devel [backport: 1.6] (#19687)
* fix #18986; Import/except doesn't work on devel [backport: 1.6]

* add testcase
2022-04-06 16:17:09 +02:00
flywind
83dabb69ae Fix bug in freshVarForClosureIter. Fixes #18474 (#19675) [backport]
* Fix bug in freshVarForClosureIter. Fixes #18474.

freshVarForClosureIter was returning non-fresh symbols sometimes.
Fixed by making addField return the generated PSym.

* remove discardable

Co-authored-by: Nick Smallbone <nick@smallbone.se>
2022-04-04 12:05:23 +02:00
flywind
c3f03cfa5d add somes links to docs (#19668) 2022-04-01 13:30:02 -04:00
Nan Xiao
a7024f49af fix 19655 - fixing more url fragments (#19669) 2022-04-01 13:29:15 -04:00
rockcavera
1275763284 fix 19655 - fixing url fragment (#19667) 2022-04-01 08:01:51 +02:00
Juan Carlos
49844415ce Deprecate selfExe (#19660)
* Deprecate selfExe Nimscript

* Deprecate selfExe Nimscript
2022-03-31 21:06:13 +02:00
Jaremy Creechley
eae29e8eaf Embedded Network patches - eventfd & socket getters (#19632) 2022-03-28 12:37:59 +02:00
Andreas Rumpf
7d32425a57 fixes #14318 (#14335) 2022-03-26 13:29:04 +01:00
flywind
82319ef00d fix #8219; nim check/dump shouldn't run single nimscript project [backport: 1.6] (#19641)
* fix #8219; nim check/dump shouldn't run single nimscript project [backport: 1.6]
2022-03-26 11:50:15 +01:00
John Titor
8cdd8867c0 Fix dial ignoring buffered parameter (#19650) [backport] 2022-03-26 11:43:26 +01:00
Omar Flores
86e93eb293 Fixed description as option in advopt.txt (#19635)
* Fixed formatting error in warningAsError.

There was only a single space character between the warning and its description, so it shows up as part of the name (in bold) and with no description.
Copied the way hotCodeReloading was formatted, with the description in a new line.

Also changed descriptions from 'ditto' to what the description it references says.

* Fixed typo in advopt.txt

Corrected 'hints' to 'warnings' in updated advopt.txt.
2022-03-26 09:56:10 +01:00
flywind
84ac003519 remove tmpFramePtr when optStackTrace is absent (#19649) 2022-03-26 08:57:29 +01:00
tandy1000
4dfe420c2f Add support for Window.matchMedia (#19648) 2022-03-26 06:57:39 +01:00
Andreas Rumpf
51df9ff1c7 fixes #19603; some pragmas were really only supported as top level statements. Now this is enforced properly. (#19646) 2022-03-26 06:47:04 +01:00
Andreas Rumpf
12a0f88a52 mitigates #19364 [backport]; we make this bug more unlikely to appear by producing better code to begin with; real fix will come later (#19647) 2022-03-26 06:37:04 +01:00
flywind
afbcba909b remove unnecessary framePtr code (#19645) 2022-03-25 10:46:42 +01:00
treeform
400e0260b8 Add more info for {.bycopy.} (#18815)
* Add more info for {.bycopy.} 

See confusion here: https://github.com/nim-lang/Nim/issues/18807

I hope this will help people googling to find this.

* Update doc/manual.rst

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2022-03-24 07:35:29 +01:00
flywind
7c3c61f2f1 fix nim check nimscript [backport: 1.6] (#19444)
fix #19440; fix #3858
2022-03-23 21:09:44 +01:00
flywind
a262a87bbe [add testcase] arc problems with recursive types (#19456)
* [add testcase] arc problems with recursive types

close #9650

* do test

* expand

* Update tests/arc/t9650.nim
2022-03-23 21:07:05 +01:00
flywind
2c01c9c4c8 output byref types into --header file [backport: 1.6] (#19505)
* output byref types into --header file

fix #19445

* fix comments

* set targets
2022-03-23 20:57:13 +01:00
Juan Carlos
b0bd4320a0 Remove deprecated typo poDemon (#19631)
* Remove Deprecated poDemon

* Remove Deprecated poDemon
2022-03-23 20:43:58 +01:00
Juan Carlos
d7a966c4eb Remove Deprecated domextension (#19630)
* Remove Deprecated domextension

* Remove Deprecated domextension
2022-03-23 20:43:28 +01:00
Juan Carlos
d14e8e8dcc Remove Deprecated Nimscript proc (#19629) 2022-03-23 20:42:54 +01:00
flywind
e93eaac223 build external deps with userversion:1.6 (#19612) 2022-03-23 20:42:08 +01:00
flywind
7f6e800caf move assertions out of system (#19599) 2022-03-23 20:34:53 +01:00
Dominic Ward
a8b5ad845c Fix process lines iterator (#19605)
* Ensure lines when process done

* eliminate post-EOF exit test

* Recommend fixes for execCmdEx/execProcess
2022-03-23 07:50:36 +01:00
Jaremy Creechley
4c8934305c system: thread: stack dealloction on Zephyr (#19633) [backport:1.6]
Try to free the stack allocation when a thread exits. Possibly works for FreeRTOS as well.
2022-03-22 20:08:31 +01:00
Andreas Rumpf
c4a0d4c5e3 fixes #19615; emit better code for integer divisions when the divisor… (#19626)
* fixes #19615; emit better code for integer divisions when the divisor is known at compile-time

* proper bugfix: unsigned numbers cannot be -1
2022-03-22 15:36:49 +01:00
Andreas Rumpf
731eabc930 fixes #19631 (#19618)
Aliasing is hard and we have to watch out not to compile 'x = f(x.a)' into 'f(x.a, addr x)'
2022-03-20 14:02:44 +01:00
Clyybber
3e83d73f27 compiler: Handle nkCheckedFieldExpr better in dfa (#19616)
Simply recurse into their first child, which is always
a nkDotExpr instead of treating them seperately.
This fixes the rhs sym of a nkCheckedFieldExpr being
checked twice in aliases. This double checking didn't
cause any issues, but was unintentional and redundant.
2022-03-18 16:41:45 +01:00
Araq
7b811deeff db_sqlite: added a space 2022-03-18 14:18:05 +01:00
Juan Carlos
7a50d66346 Removed deprecated httpcore func (#19550)
* Remove Deprecated httpcore func

* Remove Deprecated httpcore func

* Fix a test with Deprecated func

* Restart CI, Apple can code shit anymore I tell you
2022-03-18 07:54:20 +01:00
flywind
4c76f9f152 support useVersion:1.6 (#19601) 2022-03-10 17:01:27 +01:00
flywind
6773ffa63d enable nimPreviewDotLikeOps (#19598) 2022-03-09 12:55:20 +01:00
Andreas Rumpf
2beefb9aa0 fixes #19575 (#19596) [backport]
* fixes #19575

* better bugfix
2022-03-09 11:42:09 +01:00
Andreas Rumpf
0d6795a771 fixes #19569 (#19595) [backport]
* minor code refactorings

* fixes #19569
2022-03-09 07:22:10 +01:00
flywind
8f9dd5b349 register callback for marshal in VM (#19578)
* register callback for marshal in VM

* remove unrelated code

* polish

* more tests

* more tests

* add loadVM and toVM
2022-03-08 18:12:31 +01:00
Hamid Bluri
6454472938 fix not flushing stdout in MSYS (#19590)
I did this pull request according to what xflywind said: https://github.com/nim-lang/Nim/pull/19584#issuecomment-1060085141
2022-03-07 17:21:42 +08:00
VlkrS
488e18f90d Fix CPU detection for i386 (#19577)
* Fix CPU detection for i386

Commit 787def271b breaks CPU detection for i386 on OpenBSD and probably on other platforms.
[ isOpenIndiana -eq "yes" ] always returns 0, so mycpu is always set to "amd64".

* Update buildsh.nimf

Fix accidental bashism
2022-03-03 14:41:35 +01:00
huantian
590d397852 Fix typo in Nim Tutorial pt3 (#19579) 2022-03-02 13:53:59 +08:00
flywind
d6d36093b1 apply changes from #18017 and some fixes (#19571)
* implements https://github.com/nim-lang/RFCs/issues/369

* deprecate unsafeAddr; extend addr

addr is now available for all addressable locations, unsafeAddr is deprecated and become an alias for addr

* follow @Vindaar's advice

* change the signature of addr

* unsafeAddr => addr (stdlib)

* Update changelog.md

* unsafeAddr => addr (tests)

* Revert "unsafeAddr => addr (stdlib)"

This reverts commit ab83c99c50.

* doc changes; thanks to @konsumlamm

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

* merge

* remove

* fix bug

Co-authored-by: Araq <rumpf_a@web.de>
Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>
2022-03-01 07:46:08 +01:00
Evan Typanski
207237cec2 Fix #18662 (#19534) 2022-02-28 13:18:41 +01:00
Tomohiro
c870ff5946 Add error message to pointer size check assert in lib/nimbase.h (#19549) 2022-02-27 15:36:16 +01:00
solarizedalias
c2c9fbd745 make compileOption("panics") work (#19568) 2022-02-27 08:22:52 +01:00
Juan Carlos
f0bfc0bd3f Remove define for jsfetch (#19530)
* Remove define nimExperimentalAsyncjsThen for std/asyncjs.then and std/jsfetch

* Remove define nimExperimentalAsyncjsThen for std/asyncjs.then and std/jsfetch

* Remove define nimExperimentalAsyncjsThen for std/asyncjs.then and std/jsfetch

* Remove define nimExperimentalAsyncjsThen for std/asyncjs.then and std/jsfetch
2022-02-25 20:34:16 +01:00
flywind
9c17a32e0e fix #19266; allow reassign discriminant field (#19567)
* add inUncheckedAssignSection

* add one more test
2022-02-25 20:33:28 +01:00
Tanguy
ef3f343ec2 Allow std/macros.params to work with nnkProcTy (#19563)
* Allow std/macros.params to work with nnkProcTy

* Add tests for proc params & pragma
2022-02-25 12:57:58 +01:00
Juan Carlos
fe791c67b4 Remove Deprecated jsre func (#19551)
* Remove Deprecated jsre func

* Remove Deprecated jsre func

* ReStart CI, because OSX is dumb and I have no permission to restart
2022-02-25 10:43:35 +01:00
PMunch
9a49451124 Remove volatiles when compiling with ARC/ORC (#19545)
This removes volatiles on ARC/ORC targets in NimMain and PreMainInner.
This avoids an issue where they couldn't be optimised out on
microcontrollers leading to larger code. Since the stack bottom doesn't
have to be initialised this way when using ARC or ORC (or None, which is
also covered by this PR) these can be safely removed.
2022-02-25 10:43:03 +01:00
Jake Leahy
340b5a1676 Document links repect --out in .idx file (#19543)
* Link in .idx file now respects --out:file switch

* Use clearer chained calls

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2022-02-24 15:16:46 -05:00
Ștefan Talpalaru
0c915b5e47 compile pragma: cache the result sooner (#19554)
extccomp.addExternalFileToCompile() relies on hashes to decide whether
an external C file needs recompilation or not.

Due to short-circuit evaluation of boolean expressions, the procedure
that generates a corresponding hash file is not called the first time an
external file is compiled, so an avoidable recompilation is triggered
the next build.

This patch fixes that by moving the proc call with a desired side
effect from its boolean expression, so it's executed unconditionally.
2022-02-24 08:31:40 +01:00
locriacyber
516db3bac3 Remove trailing space in nim r command; Amend one error message (#19487) 2022-02-18 17:24:42 -05:00
tersec
f019e999d4 keep casing of noinit and noreturn pragmas consistently documented (#19535) 2022-02-18 16:06:11 +01:00
rockcavera
30e9f23ec0 Update chcks.nim (#19540) 2022-02-17 12:48:57 +01:00
Sizhe Zhao
b2c5d7b4ff Documentation: Fix word usage (#19529) 2022-02-14 22:15:59 +00:00
flywind
2ef71c0a46 [testcase] genSym fails to make unique identifier for ref object types (#19506)
close #15118
2022-02-14 14:36:01 +01:00
Juan Carlos
8e8231f9d6 Remove deprecated math.c_frexp (#19518)
* Remove Deprecated math proc

* Remove Deprecated math proc

* Remove Deprecated math proc
2022-02-14 14:35:33 +01:00
Juan Carlos
42eeab5fd1 Remove Deprecated oids.oidsToString (#19519)
* Remove deprecated oids.oidToString

* Remove deprecated oids.oidToString
2022-02-14 09:09:21 +01:00
David Krause
cda77c1520 use OrderedTable instead of OrderedTableRef for mimedb (#19522)
* use OrderedTable instead of OrderedTableRef for mimedb

Signed-off-by: David Krause <enthus1ast@users.noreply.github.com>

* added changelog entry for mimedb change

Signed-off-by: David Krause <enthus1ast@users.noreply.github.com>
2022-02-14 08:56:35 +01:00
konsumlamm
551225d888 Remove backslash in glob pattern (#19524) 2022-02-14 08:50:38 +01:00
Andreas Rumpf
ed0dce7292 fixes #19404 by protecting the memory we borrow from. this replaces crashes with minor memory leaks which seems to be acceptable. In the longer run we need a better VM that didn't grow hacks over a decade. (#19515)
Co-authored-by: flywind <xzsflywind@gmail.com>
2022-02-12 15:10:45 +01:00
flywind
b936bfd01a fix #16458; make useNimRtl compile for --gc:orc (#19512)
* fix #16458; make useNimRtl compile for --gc:orc/arc

* fix tests
2022-02-11 11:16:27 +01:00
flywind
27e548140b don't use a temp for addr [backport: 1.6] (#19503)
* don't use a temp for addr

fix #19497

* Update compiler/ccgcalls.nim

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

* add a test

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>
2022-02-08 08:34:44 +01:00
Andrey Makarov
801c0f0369 Fix bug 27 of #17340 (#19433)
Fixes silent disappearance of Markdown (pseudo-)link when it's detected as
unsafe protocol. Now it will be converted to plain text in spirit of
[the specification](https://spec.commonmark.org/0.30/#links).
For that sake the check for protocol is added to rst.nim also.
2022-02-07 18:11:53 -05:00
Federico Ceratto
4b0636fba0 Add compilers and hints to default nim.cfg (#18424) 2022-02-07 18:05:41 -05:00
flywind
28180e47a9 disable nimlsp (#19499) 2022-02-07 14:04:04 +08:00
Roj
6b302bb71b Improve consistency (#19490) 2022-02-07 10:28:54 +08:00
flywind
d0287748fe setjump => setjmp [backport: 1.2] (#19496) 2022-02-06 08:51:03 +01:00
flywind
7b09fd70ab undefine C symbols in JS backend [backport:1.6] (#19437)
fix #19330; fix #19059
2022-02-04 17:10:24 -05:00
flywind
33bfe5b12c fix parseEnum cannot parse enum with const fields (#19466)
fix #19463
2022-02-04 13:47:03 +01:00
flywind
772ed5eff2 correct typos (#19485) 2022-02-03 11:15:46 +08:00
flywind
891329cd4b move io out of system (#19442)
* move io out of system

* fix tests

* fix tests

* next step

* rename to syncio

* rename

* fix nimscript

* comma

* fix

* fix parts of errors

* good for now

* fix test
2022-02-02 17:10:11 +01:00
Regis Caillaud
486cb09ec2 Clonkk fix2 11923 (#19451)
* fix nnkBracketExpr not compiling for getImpl on customPragmaNode

* fix test import

* fix alias not working with hasCustomPragmas
2022-02-02 09:44:51 +01:00
Jason Beetham
1830a3b505 No longer segfault when using a typeclass with a self referencing type (#19467) 2022-02-02 09:38:21 +01:00
tandy1000
22ae0bef63 Update jsfetch with latest API and fix missing bindings (#19473)
* Update with latest API and fix missing bindings

remove deprecated `Body`
remove implicit `cstring` convs
add `Headers` to `FetchOptions`
add `Request` init proc which takes `FetchOptions`

* Update lib/std/jsfetch.nim

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

* Update lib/std/jsfetch.nim

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

* remove experimental flag

Co-authored-by: Juan Carlos <juancarlospaco@gmail.com>
2022-02-01 12:12:55 +01:00
flywind
56a901f9e1 fix broken CI (#19472)
* fix broken CI

* fix

* fix tests
2022-01-31 13:49:20 +01:00
flywind
33cd883e27 [add testcase] NRVO does not occur with init procedures (#19462)
* [add testcase] NRVO does not occur with init procedures

close #19094

* Update tests/ccgbugs2/tcodegen.nim
2022-01-29 14:06:54 +01:00
Dominik Picheta
cb894c7094 Merge pull request from GHSA-ggrq-h43f-3w7m
This fixes a CVE (currently
https://github.com/nim-lang/Nim/security/advisories/GHSA-ggrq-h43f-3w7m)
2022-01-29 14:03:01 +01:00
flywind
520881af9a update outdated link (#19465)
Ref https://github.com/nim-lang/Nim/issues/19463
2022-01-28 21:08:38 -05:00
flywind
0c3892c3c7 nvro don't touch cdecl types [backport: 1.6] (#19461)
* nvro don't touch cdecl types; fix #19342 again
2022-01-28 09:53:42 +01:00
flywind
6319b00ef7 support set other GCs after mm = orc or mm = arc is set in the global config (#19455)
* support set other GCs after arc/orc in global config

fix #15535

* set before
2022-01-27 15:23:34 +01:00
Hugo Granström
4b723c0f53 change run command for numericalnim (#19448)
Now it makes runs the custom `nimCI` task that installs the external dependencies
2022-01-25 17:31:24 +08:00
Andreas Rumpf
6ea6225523 bugfix: varargs count as open arrays (#19447) 2022-01-25 08:08:22 +01:00
ehmry
f7c4fb0014 os: faster getFileSize (#19438)
Use "stat" rather than "open", "seek", and "close" system calls.
The Windows implementation remains the same.
2022-01-24 20:57:37 +01:00
Andreas Rumpf
15f54de5c4 RST: allow empty number-lines directives just like it was done for a decade; all my documents rely on this feature [backport (#19431) 2022-01-22 20:33:55 +01:00
metagn
2bd1aa186e New/better macro pragmas, mark some as experimental (#19406)
* New/better macro pragmas, make some experimental

fix #15920, close #18212, close #14781, close #6696,
close https://github.com/nim-lang/RFCs/issues/220

Variable macro pragmas have been changed to
only take a unary section node.
They can now also be applied in sections with multiple variables,
as well as `const` sections. They also accept arguments.

Templates now support macro pragmas, mirroring other routine types.

Type and variable macro pragmas have been made experimental.
Symbols without parentheses instatiating nullary macros or templates
has also been documented in the experimental manual.

A check for a redefinition error based on the left hand side of variable
definitions when using variable macro pragmas was disabled.
This nerfs `byaddr` specifically, however this has been documented as
a consequence of the experimental features `byaddr` uses.

Given how simple these changes are I'm worried if I'm missing something.

* accomodate compiler boot

* allow weird pragmas

* add test for #10994

* remove some control flow, try remove some logic
2022-01-20 20:57:50 +01:00
Regis Caillaud
1563cb2f6e Fix #11923 (#19427)
* Apply commit 5da931fe81 that was never merged (was part of a bigger PR). Should fix issue #11932

* add a generic object for custom pragma
2022-01-20 20:50:36 +01:00
flywind
927fa890ec enable weave (#19363) [backport:1.6]
* enable weave
* workaround CI
2022-01-20 13:59:36 +01:00
James
851e515bba Resolve cross file resolution errors in atomics (#19422) [backport:1.6]
* Resolve call undeclared routine testAndSet

* Fix undeclared field atomicType
2022-01-20 13:58:59 +01:00
flywind
4a38092ac1 Added std/envvars for env vars handling (#19421) 2022-01-20 13:55:19 +01:00
Tom
ce44cf03cc Add noQuit option (#19419) [backport:1.6]
* Add noQuit option

* Add nim prefix in case of conflicts

Co-authored-by: flywind <xzsflywind@gmail.com>

Co-authored-by: flywind <xzsflywind@gmail.com>
2022-01-19 17:41:11 +01:00
metagn
08261cb9e3 Don't reject types directly on AST (#19407)
Instead of rejecting type expressions based on node kind,
evaluate the expression as a type.
This is already the behavior for call results, and it has its own error
for non-types, which is the same error you would normally get
with 2 words swapped.
2022-01-19 12:38:14 +01:00
flywind
5d34e81f23 fix term rewriting with sideeffect (#19410)
* fix term rewriting with sideeffect

fix #6217

* add tests

* Update tests/template/template_various.nim
2022-01-19 12:37:30 +01:00
nblaxall
23c4bbedcb add an example to setControlCHook (#19416)
* add an example to setControlCHook

* [skip CI] format example for setControlCHook

Co-authored-by: Nathan Blaxall <nathan.blaxall@actionstep.com>
2022-01-19 12:25:21 +01:00
flywind
b3c178c202 suppress deprecated warnings (#19408)
* suppress deprecated warnings

once bump version to 1.7.3 enable deprecated messages

* deprecate later
2022-01-19 08:39:22 +01:00
flywind
aac54b9c7f fix stricteffects (nimsuggest/sexp) (#19405)
* fix stricteffects (nimsuggest/sexp)

* Update tstrict_effects3.nim

* Update tests/effects/tstrict_effects3.nim
2022-01-18 16:02:35 -05:00
Andrey Makarov
d7869a8009 Improve Zshell completion (#19354) 2022-01-18 15:58:18 -05:00
Hamid Bluri
5d303762f1 update deprecated example (#19415)
`toNimIdent` proc is deprecated, so I replaced it with `ident` proc
2022-01-18 15:55:39 -05:00
flywind
bc3bee5469 Added std/oserrors for OS error reporting (#19390)
* Added 'std/oserrors' for OS error reporting

* add a simple test

* New code should not support -d:useWinAnsi anymore

thanks to @Araq
2022-01-17 13:06:31 +01:00
hlaaftana
07c7a8a526 Optimize lent in JS [backport:1.6] (#19393)
* Optimize lent in JS [backport:1.6]

* addr on lent doesn't work anymore, don't use it

* use unsafeAddr  in test again for older versions
2022-01-17 13:03:40 +01:00
Jaremy Creechley
dc8ac66873 fix no net compilation on zephyr (#19399)
Co-authored-by: Jaremy J. Creechley <jaremy.creechley@panthalassa.com>
2022-01-17 13:02:31 +01:00
flywind
4f6b59de96 mangle names in nimbase.h using cppDefine (#19395) [backport]
mangle names in nimbase.h
fix comments
2022-01-17 11:14:13 +01:00
flywind
2c5b367001 improve changelog a bit (#19400) 2022-01-17 11:54:27 +08:00
flywind
15e3813d96 add mm to compilesettings; deprecate gc (#19394) 2022-01-16 21:10:35 +01:00
flywind
d102b2f54c deprecate unsafeAddr; extend addr (#19373)
* deprecate unsafeAddr; extend addr

addr is now available for all addressable locations, unsafeAddr is deprecated and become an alias for addr

* follow @Vindaar's advice

* change the signature of addr

* unsafeAddr => addr (stdlib)

* Update changelog.md

* unsafeAddr => addr (tests)

* Revert "unsafeAddr => addr (stdlib)"

This reverts commit ab83c99c50.

* doc changes; thanks to @konsumlamm

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>
2022-01-16 11:08:38 +01:00
hlaaftana
a95399143f Use openarray of bytes in md5 (#19307)
* Use openarray of bytes in md5
* fix CI
* cleanup
* use noSideEffect for bootstrapping
* fix CI again
* actually fix CI by checking if it works
* this is getting ridiculous
* put old md5 version in compiler, remove vmop
2022-01-15 13:19:05 +01:00
flywind
342b74ef70 move type operation section and remove deepcopy document (#19389)
ref #19173; because deepcopy is not fit for ORC/ARC which was used for spawn and spawn will be removed from compiler
2022-01-15 11:25:09 +01:00
Jason Beetham
7bdfeb7819 Fixed concept constraints for static types (#19391) 2022-01-15 09:24:23 +01:00
Jason Beetham
a93f6e7acc Generic parameters now can constrain statics in type definitions (#19362)
* Parameters now can constrain static in type definitions

resolved regression with generic procedures

* Update compiler/sigmatch.nim

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2022-01-14 00:39:55 +08:00
flywind
9b9ae8a487 nrvo shouldn't touch bycopy object[backport:1.2] (#19385)
fix nim-lang#19342
2022-01-14 00:39:17 +08:00
Leon
5853303be0 docs: Fix broken cross references to rfind in strutils (#19382) [backport]
Fixes three broken cross references to `rfind` in strutils.
Breakage due to signature changes of the `rfind` methods.

Co-authored-by: adigitoleo <adigitoleo@dissimulo.com>
2022-01-13 14:45:47 +01:00
flywind
40a9c33eff update copyright year (#19381) 2022-01-13 14:43:35 +01:00
Leon
a9135095f0 docs: Mention import foo {.all.} syntax (#19377)
Mention the `import foo {.all.}` syntax in the manual,
with a caveat about private imports.
Also link to the experimental importutils module.

Co-authored-by: adigitoleo <adigitoleo@dissimulo.com>
2022-01-13 14:40:27 +01:00
flywind
ada815e459 make rst thread safe (#19369)
split for the convenience of review
2022-01-13 08:03:14 +01:00
flywind
9a32905d89 nimscript ignore the threads option (#19370)
because nimscript doesn't support threads and causes troubles when the threads option is on
2022-01-13 08:02:41 +01:00
Andreas Rumpf
9888a29c3d bitsets.nim: cleanup (#19361) 2022-01-11 10:16:51 +01:00
flywind
bcbeff3632 remove spaces between an identifier and a star (#19355)
It makes search easier by searching `+`* instead of `+` which filter lots of unexported versions.

Follow https://github.com/nim-lang/Nim/pull/18681
2022-01-10 11:59:44 +01:00
flywind
92e5573b20 fix stylecheck error with asyncdispatch (#19350)
* stylecheck usages part two: stdlib cleanup

typeinfo.nim: importCompilerProc => importcompilerproc

nre.nim: newLineFlags => newlineFlags

system.nim: JSRoot => JsRoot

ref #19319

* prefer importCompilerProc

* fix stylecheck error with asyncdispatch

it is a partial regression since #12842

* add tests

* don't use echo in tests
2022-01-10 10:29:04 +01:00
gecko
955040f0f1 Fix remove on last node of singly-linked list [backport:1.6] (#19353) 2022-01-10 10:27:59 +01:00
Smarcy
b098546da0 added filemode docs (#19346) 2022-01-09 14:02:08 +01:00
flywind
ae92eac060 stylecheck usages part two: stdlib cleanup (#19338)
* stylecheck usages part two: stdlib cleanup

typeinfo.nim: importCompilerProc => importcompilerproc

nre.nim: newLineFlags => newlineFlags

system.nim: JSRoot => JsRoot

ref #19319

* prefer importCompilerProc
2022-01-08 21:34:22 +01:00
Zachary Marquez
58656aa5bb fix nim-lang#19343 (#19344) [backport]
Ensure HttpClient onProgress is called once per second
Ensure that reported speed is accurate
2022-01-08 10:22:56 +01:00
flywind
4306d8fb36 disable fragments (#19341)
The original repo has moved to Rust, while the package path stay unchanged. And it causes troubles to https://github.com/nim-lang/Nim/pull/19338
2022-01-08 12:06:28 +08:00
rockcavera
c7d5b8c83d Fix #19038 - making the Nim compiler work again on Windows XP (#19331)
* Update osenv.nim

* Update win_setenv.nim

* Update lib/pure/includes/osenv.nim

* Update lib/pure/includes/osenv.nim

* fixing cstring

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2022-01-07 08:26:55 +01:00
rockcavera
5ec8b60942 Update net.nim (#19327) [backport] 2022-01-06 12:19:32 +01:00
flywind
9df195ef58 style usages part one (openarray => openArray) (#19321)
* style usages (openArray)

* revert doc changes
2022-01-04 13:29:50 +01:00
flywind
1869826668 add std/private/win_getsysteminfo; refactor the usage of GetSystemInfo (#19310)
* add std/private/win_getsysteminfo

* import at the top level

* wrappers follow nep1 too

* follow review comment
2022-01-04 11:49:54 +01:00
flywind
0bcd7062c6 correct the comments (#19322)
--expandArc

```
var
  a
  b
a = matrix(5, 5, 1.0)
b = matrix(5, 5, 2.0)
`=sink`(b, -
  let blitTmp = b
  wasMoved(b)
  blitTmp +
    a)
`=destroy`(b)
`=destroy`(a)
```
2022-01-04 11:10:46 +01:00
Nan Xiao
39a27783fc docs: Fix typo in tut1.rst (#19324) 2022-01-04 10:42:21 +01:00
Ștefan Talpalaru
35cae73aa5 devel: style fix (#19318)
this allows "--styleCheck:usages --styleCheck:error"
2022-01-04 07:56:10 +01:00
Smarcy
fcf1df6e56 fixed typos (#19316) 2022-01-03 15:04:15 -05:00
rockcavera
526a32e169 Fix #19314 - fixing broken DoublyLinkedList after adding empty DoublyLinkedList (#19315) [backport]
* Update lists.nim

* Update tlists.nim
2022-01-03 20:14:08 +01:00
flywind
19bcb43a0e enable multiple packages (arraymancer, fidget ...) (#19311)
The cause of arraymancer failure has been tracked here: https://github.com/mratsim/Arraymancer/issues/505
And it was fixed by https://github.com/mratsim/Arraymancer/pull/542
2022-01-03 20:40:43 +08:00
Nan Xiao
bd4f76a2e3 docs: Fix typo in tut1.rst (#19309) 2022-01-03 10:30:26 +01:00
Carlo Capocasa
e49d52eb61 Add Week-Of-Year Implementation to Times Module (#17223)
* initial

* more tests

* Apply suggestions from code review

idiomatize

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

* test iron age dates

* add examples

* fix typo

* consistent param mention

* add since pragrams

* add changelog

* Update lib/pure/times.nim

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

* fix examples

* fix negative years

* add getWeeksInYear tests

* add back fix dropped by rebase

* week-year tuple api

* add changelog

* fix doc tags

* add docstrings

* fix typos

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

Co-authored-by: Timothee Cour <timothee.cour2@gmail.com>
Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>
2022-01-03 09:11:23 +01:00
flywind
bbd5086bc3 [docs] clarify the raised exception (#19308)
* [docs] clarify the raised exception

Lest developers wanna know what the exception is.

* Apply suggestions from @konsumlamm

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>
2022-01-03 09:02:58 +01:00
BarrOff
53e1d57419 add compile time option for POSIX sigwait on Illumos/Solaris (#19296)
* add compile time option for POSIX sigwait on Illumos/Solaris

* fix link to documentation of `sigwait` on Illumos/Solaris
2022-01-02 07:37:13 +01:00
hlaaftana
61d682e733 Allow full commands and blocks in type sections (#19181)
* allow full commands and blocks in type sections
* update grammar
* fix changelog [skip ci]
* more tests
* even more tests
2022-01-02 07:29:55 +01:00
rockcavera
ef634cc251 Update manual.rst (#19301) 2022-01-01 13:33:29 +01:00
hlaaftana
faaf271928 Update JS and nimscript import tests (#19306)
* add new modules, except experimental ones
* remove deprecated modules mersenne and sharedlist
* better describe why some modules fail and some modules don't
2022-01-01 13:33:16 +01:00
Andreas Rumpf
ac37eed5a2 fixes #16617 [backport] (#19300) 2021-12-31 09:21:30 +01:00
rockcavera
dc5c88ca79 Fix #19297 - fixing broken list after adding empty list (#19299)
* Update lists.nim

* Update tlists.nim

* removed check `if b.tail != nil`

The tail of the list being null it is still possible to retrieve its end by going through all nodes from the head. So checking for null from `b.tail` is unnecessary. However, setting `a.tail = b.tail` only if `a.head != nil`, so you don't break a good list with an already broken one.
2021-12-30 21:52:48 +01:00
BarrOff
23d64be860 enable maxDescriptors on Illumos/Solaris (#19295) 2021-12-30 21:10:36 +01:00
Andreas Rumpf
a9223d4cdd nep1: make header reflect reality (#19294) 2021-12-29 12:18:32 +01:00
rockcavera
77ad8b81e4 fix 19292 (#19293) 2021-12-29 07:26:54 +01:00
Andreas Rumpf
a61bbf7d8d fixes grammar typos [backport] (#19289) 2021-12-27 17:28:19 +01:00
Tomohiro
fdbec969d8 Fix #19107 (#19286) [backport] 2021-12-25 10:31:35 +01:00
Jason Beetham
fa96e56ad0 Fixed object field access of static objects in generics (#19283) [backport] 2021-12-23 07:12:56 +01:00
Andreas Rumpf
81d32cf7e5 Revert "Update uri.nim (#19148) [backport:1.0]" (#19280)
This reverts commit a3ef5df680.
2021-12-23 07:03:40 +01:00
pkubaj
7a5314c571 Fix build on FreeBSD/powerpc (#19282)
It's currently misdetected as powerpc64.
2021-12-22 20:52:33 -05:00
Andrey Makarov
19898e1225 Fix group reference (with capital letters (#19196)
in group name)
2021-12-20 15:10:15 -05:00
Jake Leahy
4da7dbffc5 Extract runnables that specify doccmd (#19275) [backport:1.6] 2021-12-20 17:29:03 +01:00
MichalMarsalek
ea475a4e98 Update colors.nim (#19274)
* Update colors.nim

Added `lightgray` alias to `lightgrey` and `...grey`aliases for the rest of the gray colors.
Added color `rebeccapurple`.
Fixed the incorrect values for the `PaleVioletRed` and `MediumPurple` colors.
This module should now be matching the CSS colors.
I used the seq[tuple] syntax for defining the names.

* Document colors changes.
2021-12-20 10:40:32 +01:00
xioren
b812431f83 use uppercase "type" for Proxy-Authorization header (#19273)
Some servers will reject authorization requests with a lowercase "basic" type. Changing to "Basic" seems to solve these issues.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Proxy-Authorization
2021-12-19 13:01:17 +00:00
Don-Duong Quach
610516e027 Fixed typo in manual.rst unsafeAssign->uncheckedAssign. Fixes part 1 of #19266 (#19267) 2021-12-17 20:58:31 +01:00
flywind
3d9b6cfebc [formatter] async.nim uses two spaces (#19264)
according to https://nim-lang.org/docs/nep1.html#introduction-spacing-and-whitespace-conventions, two spaces should be preferred in stdlib.
2021-12-17 10:16:59 +00:00
rockcavera
5ddaf3e1fb fix #19244 - solves the problem of the InAddr object constructor in Windows. (#19259)
* Update winlean.nim

* Update tnet_ll.nim
2021-12-17 09:01:33 +01:00
snxx
609388e33f Add icon for Nim (#19258)
* Add Nim's file icon

* Add installer icon

* Add uninstaller icon
2021-12-17 08:58:05 +01:00
Sven Keller
5d2bab7558 suggestion to respect typedarray type (#19257)
* suggestion to respect typedarray

* Update jssys.nim

Co-authored-by: Sven Keller <s.keller@cortona.de>
2021-12-16 08:58:32 +01:00
Miran
c17baaefbc [backport:1.0] json: limit recursion depth (#19252)
* json: limit recursion depth

* do not run this check for JS backend
2021-12-14 18:16:49 +01:00
PMunch
3e31f55aed Fix #19253 (#19254)
This fixes 19253 by marking the bodyStream as completed when no content
was sent.
2021-12-14 13:28:42 +00:00
Nick Wilburn
c55930f2e6 fix: fixes bug in CVerifyPeerUseEnvVars (#19247)
Previously CVerifyPeerUseEnvVars was not being passed into
scanSslCertificates, which meant that we weren't scanning
additional certificate locations given via the SSL_CERT_FILE and
SSL_CERT_DIR environment variables
2021-12-14 12:22:10 +00:00
Nan Xiao
78b86b7942 basicopt.txt: Unify the format (#19251) 2021-12-14 09:54:01 +01:00
Carlo Capocasa
0ff4b2ba7e fix bug #14468 zero-width split (#19248) 2021-12-13 07:29:22 +01:00
Jaremy Creechley
4b5cecd902 Various std net improvements (#19132)
* Variant of  that works with raw IpAddresses.

- Add doc tests for new net proc's.
- Aadd recvFrom impl
- Add recvFrom impl -- tweak handling data var

- Update lib/pure/net.nim
	Co-authored-by: Dominik Picheta <dominikpicheta@googlemail.com>

- cleaning up sendTo args
- remove extra connect test
- cleaning up sendTo args
- fix inet_ntop test
- fix test failing - byte len

* fix test failing - byte len

* debugging odd windows build failure

* debugging odd windows build failure

* more experiments to figure out the windows failure

* try manual assigment on InAddr

Co-authored-by: Jaremy Creechley <jaremy.creechley@panthalassa.com>
2021-12-12 21:39:56 +00:00
Dominik Picheta
a3ef5df680 Update uri.nim (#19148) [backport:1.0] 2021-12-11 09:24:23 +01:00
Ștefan Talpalaru
1a92edeb89 nimc.rst: fix table markup (#19239) 2021-12-11 05:15:44 +01:00
Andreas Rumpf
908fc2a22e let Nim support Nimble 0.14 with lock-file support [backport:1.6] (#19236) 2021-12-10 17:13:48 +01:00
Andreas Rumpf
7ff43d07b2 added --nimMainPrefix switch; fixes #15955; refs #16945 [backport:1.6] (#19235) 2021-12-10 14:28:59 +01:00
Andreas Rumpf
9338aa2497 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>
2021-12-10 09:24:20 +01:00
MichalMarsalek
c989542339 move toDeque to after addLast (#19233) [backport:1.0]
Changes the order of procs definitions in order to avoid calling an undefined proc.
2021-12-10 07:39:12 +01:00
Jaremy Creechley
d39147219a Revert "swap port to correct port order (#19177)" (#19234)
This reverts commit 0d0c249074.
2021-12-10 07:38:39 +01:00
Ștefan Talpalaru
69aabdab80 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++
2021-12-10 06:31:29 +01:00
Andreas Rumpf
32d4bf3525 fixes an old ARC bug: the produced copy/sink operations don't copy the hidden type field for objects with enabled inheritance; fixes #19205 [backport:1.6] (#19232) 2021-12-09 22:23:16 +01:00
flywind
4f64c9fae5 add comments to spawn and pinnedSpawn (#19230)
`spawn` uses `nimSpawn3` internally and `pinnedSpawn` uses `nimSpawn4` internally. I comment it in order to help contributors get the gist of its functionality.
2021-12-09 18:49:31 +01:00
flywind
99f8793502 remove std/sharedstrings (#19228)
* remove std/sharedstrings

it has been broken since 0.18.0

* rephrase the changelog entry
2021-12-09 22:37:59 +08:00
wenghongquan
742e9d65ad Add support for LoongArch (#19223)
* Add support for LoongArch

* Update compiler/installer.ini

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2021-12-09 14:00:33 +01:00
Andreas Rumpf
502ac4ed5e fixes a converter handling regression that caused private converters to leak into client modules; fixes #19213; [backport:1.6] (#19229) 2021-12-09 13:56:51 +01:00
flywind
0992854941 Atomic inc/dec should use ATOMIC_SEQ_CST (#19212) 2021-12-08 08:40:35 +01:00
rockcavera
7806ec525e Making TCC work again on Windows --cpu:amd64 - fix #16326 (#19221)
* fix #16326

* removing comments
2021-12-08 06:48:34 +01:00
Tanguy
cd592ed85b fix #19193 (#19195) [backport:1.2] 2021-12-07 18:01:22 +01:00
Andreas Rumpf
93c8427fca re-enable chronos testing once again [backport:1.2] (#19222) 2021-12-07 17:59:43 +01:00
flywind
ebd88725f9 remove sysspawn which is dead code (#19218) 2021-12-06 22:41:42 +01:00
Etan Kissling
0213c7313b 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.
2021-12-06 20:38:23 +01:00
flywind
7e3da693f5 [format minor] remove unnecessary spaces (#19216) 2021-12-06 18:58:01 +01:00
flywind
faacd63bf6 the title of PR should contain a brief description (#19211)
In addition to an issue number, the title of a PR should contain a brief description; then users can follow the progress more easily from the title.
2021-12-06 10:04:54 +01:00
flywind
e5475768ba feature_request should be labelled automatically (#19215) 2021-12-05 07:17:52 +01:00
hlaaftana
1ef945668d treat do with pragmas but no parens as proc (#19191)
fixes #19188
2021-12-05 06:44:22 +01:00
PMunch
c658de24b0 Improve documentation around func and method (#19207)
* Improve documentation around func and method

* Update doc/tut1.rst

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

* Update doc/tut1.rst

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

* Update doc/tut1.rst

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

* Update doc/tut1.rst

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

* Update doc/tut1.rst

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

* Update doc/tut1.rst

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

* Update doc/tut1.rst

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

* Update doc/tut1.rst

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

* Update doc/tut1.rst

Co-authored-by: Zoom <ZoomRmc@users.noreply.github.com>

* Update doc/tut1.rst

Co-authored-by: Zoom <ZoomRmc@users.noreply.github.com>

* Update doc/tut1.rst

Co-authored-by: Zoom <ZoomRmc@users.noreply.github.com>

* Update doc/tut1.rst

Co-authored-by: Zoom <ZoomRmc@users.noreply.github.com>

* Rewrite of Zooms suggestion

* Update doc/tut1.rst

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

Co-authored-by: Danil Yarantsev <tiberiumk12@gmail.com>
Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>
Co-authored-by: Zoom <ZoomRmc@users.noreply.github.com>
2021-12-04 07:54:11 +01:00
Andreas Rumpf
1cbdc1573a fixes #19159 [backport:1.6] (#19210) 2021-12-04 07:44:26 +01:00
Andreas Rumpf
f90620fb32 fixes #19198 [backport:1.6] (#19209)
* fixes #19198 [backport:1.6]

* added a test case
2021-12-04 07:43:20 +01:00
Andreas Rumpf
d584dd5b99 fixes #19015 [backport:1.6] (#19204) 2021-12-04 07:42:58 +01:00
Andreas Rumpf
23c117a950 misc bugfixes [backport:1.2] (#19203) 2021-12-04 07:42:34 +01:00
Iced Quinn
373c909300 feat: TLS-ALPN wrappers for OpenSSL (#19202)
Co-authored-by: Iced Quinn <icedquinn@iceworks.cc>
2021-12-04 07:42:03 +01:00
Jaremy Creechley
0d0c249074 swap port to correct port order (#19177)
Co-authored-by: Jaremy Creechley <jaremy.creechley@panthalassa.com>
2021-11-24 17:37:14 +01:00
hlaaftana
f91867aa31 accept object type node from macros (#19179) 2021-11-24 16:34:42 +01:00
Andrey Makarov
a59ad20062 fix inline syntax highlighting in system.nim (#19184) 2021-11-24 16:16:20 +01:00
Andreas Rumpf
a0073d2d4c renamed 'gc' switch to 'mm'; [backport:1.6] (#19187)
* renamed 'gc' switch to 'mm'; [backport:1.6]
* better docs
2021-11-24 15:49:32 +01:00
hlaaftana
c7c6b13a32 parseExpr/parseStmt accept filename, fixes #13540 (#19182) 2021-11-24 12:22:40 +01:00
hlaaftana
ff39f6e260 make JS trunc polyfill opt-in, closes #16144 (#19183) 2021-11-24 08:20:15 +01:00
hlaaftana
2859069dbe fix #12274 (#19180) 2021-11-24 07:08:07 +01:00
hlaaftana
5933aece9b caseStmtMacros no longer experimental, experimental manual refactor (#19173)
* `caseStmtMacros` no longer experimental, experimental manual refactor

* Update doc/manual.rst

* apply review suggestions

* apply review

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2021-11-23 16:30:17 +01:00
Andrey Makarov
040d23e799 implement RST & Markdown quote blocks (#19147)
* implement RST & Markdown quote blocks

* compile with nim 1.0

* Fix indentation
2021-11-23 13:02:03 +01:00
Jaremy Creechley
7772ca303c Implement threads on Zephyr (#19156)
* pthreads setup for zephyr

- enable tweak stack size
- update lib/system/threads.nim
- Fix int/uint in casting pointer.

* add documentation and tweak flag names

* add documentation and tweak flag names

* fix configuration flag names

* fix configuration flag names

* cleanup

Co-authored-by: Jaremy Creechley <jaremy.creechley@panthalassa.com>
2021-11-23 09:13:03 +01:00
hlaaftana
1b143f5e79 Accept nnkTypeSection from typedef macro pragmas (#19168) 2021-11-22 10:41:35 +01:00
quantimnot
eb5358dcdb Testament now checks OS, CPU, endianess, bitsizes 8-64 in discard statements (#19137)
* Testament checks host/cpu in compiler/platform for discard spec statement

* Remove duplicated value checks, add comments, add all cpu bit sizes and endianesses

Co-authored-by: quantimnot <quantimnot@users.noreply.github.com>
2021-11-19 08:19:01 +01:00
OxFred
a8611c665f Update dependency (#19151) 2021-11-17 13:16:12 +01:00
flywind
fe46c8b5f1 fix marshal bugs in VM (#19161) [backport:1.6] 2021-11-17 10:15:54 +01:00
Jaremy Creechley
92d6fb86c6 Enable customizing PageShift to set PageSize for embedded targets (#19129)
* Enable customizing PageSize (via PageShift).

This enables adjusting PageSize for embedded targets without abusing
cpu16.

* copy nimPageXYZ settings for mmpaptest

* add docs for Nim manual

* add docs for Nim manual

* docs tweaks

Co-authored-by: Jaremy Creechley <jaremy.creechley@panthalassa.com>
2021-11-16 20:30:07 +01:00
Andreas Rumpf
309ec7167e fixes .raises inference for newSeq builtin under --gc:orc [backport] (#19158) 2021-11-16 15:49:04 +01:00
Jaremy Creechley
6976d18519 Implement zephyr urandom and monotime (#19142)
* implement urandom for Zephyr

* add monotime on zephyr

Co-authored-by: Jaremy Creechley <jaremy.creechley@panthalassa.com>
2021-11-14 12:49:30 +01:00
flywind
bec4900165 wrong spaces (3 => 2) (#19145) 2021-11-14 12:46:21 +01:00
Anuken
270a5a372d Fix undeclared 'SYS_getrandom' on emscripten (#19144) 2021-11-13 19:09:15 -05:00
Christoph Krybus
ade85ee91f Fix punycode.decode function (#19136)
* Refactor: rename proc to func

* Fix punycode.decode function

This function could only properly decode punycodes containing a single
encoded unicode character. As soon as there was more than one punycode
character group to decode it produced invalid output - the number of
characters was correct, but their position was not.

* Update tpunycode.nim

Co-authored-by: Clay Sweetser <Varriount@users.noreply.github.com>
2021-11-12 22:51:58 -05:00
Clay Sweetser
0a1049881e Merge file size fields correctly on Windows (#19141)
* Merge file size fields correctly on Windows

Merge file size fields correctly on Windows

- Merge the two 32-bit file size fields from `BY_HANDLE_FILE_INFORMATION` correctly in `rawToFormalFileInfo`.
- Fixes #19135

* Update os.nim
2021-11-12 22:51:43 -05:00
Andreas Rumpf
c6fc3b2eae fixes #19051 [backport:1.6] (#19133) 2021-11-12 11:19:24 +01:00
Jake Leahy
f8b71f7075 Fix type mismatch with future logging (#19131) 2021-11-12 08:00:19 +01:00
flywind
3aaa12dbe5 update manual (#19130) [backport] 2021-11-12 07:59:48 +01:00
orthoplex
528ef6c218 fixed colorNames sorting mistake (#19125) [backport] 2021-11-11 20:01:51 +01:00
Andreas Rumpf
cde83d90aa refactoring: orc can use getThreadId() (#19123)
* refactoring: orc can use getThreadId()

* progress
2021-11-11 19:07:08 +01:00
flywind
7313b70a6a correct cookie docs (#19122) 2021-11-11 08:53:27 +01:00
Federico Ceratto
036d894e6a Add security tip for setCookie (#19117)
* Add security tip for setCookie

* Update lib/pure/cookies.nim

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

* Update lib/pure/cookies.nim

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
Co-authored-by: Dominik Picheta <dominikpicheta@googlemail.com>
Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>
2021-11-11 08:41:21 +01:00
Ryan Oldenburg
77b696c2c9 Remove tlsEmulation enabled from Windows + GCC config (#19119) [backport:1.6]
This flag has a very significant performance impact on programs compiled with --threads:on. It is also apparently not needed anymore for standard circumstances. Can we remove the config? See https://github.com/nim-lang/Nim/issues/18146#issuecomment-876802676 for discussion and perf impact. [backport:1.6]
2021-11-11 06:48:22 +01:00
treeform
a78ee8ae84 Call {.cursor.} a pragma. (#19116)
* Call {.cursor.} a pragma.

Its hard to find .curser annotation while googling because all other things like it are called pragmas. See https://nim-lang.org/docs/manual.html#pragmas
Also the . in front of the name makes it hard to find and search for.

Can we just call it cursor pragma?

* Small fix for comment.
2021-11-10 08:52:34 +01:00
Andreas Rumpf
15157d06c3 fixes #14470 [backport:1.2] (#19115) 2021-11-09 22:48:04 +01:00
Andrey Makarov
997ccc5889 fix nimindexterm in rst2tex/doc2tex [backport] (#19106)
* fix nimindexterm (rst2tex/doc2tex) [backport]

* Add support for indexing in rst
2021-11-09 19:01:47 +01:00
konsumlamm
46fb855425 Deprecate std/sharedlist and std/sharedtables (#19112) 2021-11-09 19:00:43 +01:00
konsumlamm
b0f4a9b845 Add deprecation pragmas in lib/deprecated/pure (#19113) 2021-11-09 19:00:33 +01:00
Andreas Rumpf
6ff61766da fixes #19011 [backport:1.6] (#19114) 2021-11-09 18:59:59 +01:00
Andreas Rumpf
b7c66ce860 fixes #19013 [backport:1.6] (#19111)
* fixes #19013 [backport:1.6]

* added test case
2021-11-09 12:43:16 +01:00
Zoom
83a9c3ba31 Update readme.md: matrix links (#19109)
Added links to the main #nim-lang room on Matrix and to the Nim matrix space.
Added Matrix badge.
2021-11-08 18:47:20 +00:00
Andrey Makarov
b21eb1ed36 change os.nim doc links to new style (#19102) 2021-11-08 13:10:01 +01:00
Dominik Picheta
b423ab138f Remove invalid statements about try in async docs. (#19108) 2021-11-08 08:21:15 +01:00
Andreas Rumpf
fce89cb60a fixes another effect inference bug [backport:1.6] (#19100)
* fixes another effect inference bug [backport:1.6]
2021-11-07 16:38:02 +01:00
Don-Duong Quach
f2f15e9726 fix for #19020, credit to @ElegantBeef (#19021) 2021-11-03 16:47:31 +01:00
Constantine Molchanov
b2edc3468c Use testament to check Norm test pass (#19018)
* Use testament to check Norm test pass

This is what I actually use to test Norm, so it's better to use it.

This should not currently pass. This is expected because this is exactly the problem I want to highlight with this PR. My tests do indeed not pass at the moment.

* Remove clearNimblePath from testament command.

Co-authored-by: flywind <xzsflywind@gmail.com>
2021-11-03 09:16:24 +01:00
David Krause
f7cfc46ae1 Added support for sending "ehlo" and receiving multiline "ehlo" response. (#19077)
* Added support for sending "ehlo"
and receiving multiline "ehlo" response.

Signed-off-by: David Krause <enthus1ast@users.noreply.github.com>

* fix typo

Signed-off-by: David Krause <enthus1ast@users.noreply.github.com>

* send "EHLO" first, if not supported, send "HELO" to smtp server.

Signed-off-by: David Krause <enthus1ast@users.noreply.github.com>

* fix english

Signed-off-by: David Krause <enthus1ast@users.noreply.github.com>

* add changelog entry for smtp `ehlo`

Signed-off-by: David Krause <enthus1ast@users.noreply.github.com>

* recvEhlo must not be exported

Signed-off-by: David Krause <enthus1ast@users.noreply.github.com>
2021-11-03 09:14:59 +01:00
Kaushal Modi
dbbafd320c manual: Document that comma propagates the default values of parameters (#19080)
* manual: Document that comma propagates the default values of parameters

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

* Use the "bug #NNNN" comment syntax for consistency

Ref:
https://nim-lang.github.io/Nim/contributing.html#writing-tests-stdlib

> Always refer to a GitHub issue using the following exact syntax: bug
for tooling.
2021-11-03 08:08:50 +01:00
Kaushal Modi
5fed1c05ce manual: Document the use of static as a proc call (#19084)
* manual: Document the use of `static` as a proc call

Also adds tests.

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

* Update doc/manual.rst

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

* Use the "bug #NNNN" comment syntax for consistency

Ref:
https://nim-lang.github.io/Nim/contributing.html#writing-tests-stdlib

> Always refer to a GitHub issue using the following exact syntax: bug
for tooling.

* manual: Undocument usage of foo.static

foo.static and foo.static() are not expected to work.

Ref: https://github.com/nim-lang/Nim/pull/19084/files#r741203578

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>
2021-11-03 06:48:30 +01:00
Kaushal Modi
539bced70d Add test for issue 15435 (#19079)
* Add test for issue 15435

Closes https://github.com/nim-lang/Nim/issues/15435.

* Specify bug # in comment

Addresses https://github.com/nim-lang/Nim/pull/19079#discussion_r740279547
2021-11-03 06:46:34 +01:00
flywind
b155864967 build testament in package CI (#19092)
* build testament in package CI

* Update testament/important_packages.nim
2021-11-02 16:31:30 +01:00
Andreas Rumpf
9d51197aa4 fixes #19078 [backport] (#19090) 2021-11-02 16:30:59 +01:00
flywind
a55b90827e remove the mention of travis from readme (#19093) 2021-11-02 16:22:11 +01:00
Kaushal Modi
efaaa38eef docstyle.rst: Do not export it to HTML as a standalone doc (#19083)
.. This doc is included in contributing.rst.

Fixes https://github.com/nim-lang/Nim/issues/14593.
2021-11-02 10:34:11 +01:00
Kaushal Modi
12d2901e89 libs/impore/re: Add note about the requirement of matches to be pre-allocated (#19081)
Add few runnableExamples for `findBounds` for clarity.

Fixes https://github.com/nim-lang/Nim/issues/18775
2021-11-02 09:12:54 +01:00
flywind
e01e543fce bootstrapping Nim compiler with cpp --gc:orc (#19087) 2021-11-02 09:10:25 +01:00
Kaushal Modi
2e0db988e7 tests: Fix warnings in tstrscans (#19082) 2021-11-02 09:06:46 +01:00
Jason Beetham
cc984217a9 Fix VM's sametype impl to work for generics/typedescs (#19073)
* Fix vm's sametype implementation to properly handle generics and typedescs

* actually fixed sametype + have test

* added comments and removed unsafe code
2021-11-02 09:02:53 +01:00
Derek 呆
24a7584299 update numbers of lifetime-tracking hooks in doc/destructors.rst (#19088) 2021-11-02 08:55:50 +01:00
haxscramper
4c510d5577 [FIX] Do not break formatted string line (#19085) [backport]
Otherwise, compiler produces broken error message - `$1` is not interpolated

`Error: The $1 type doesn't have a default value. The following fields must be initialized: importGraph.`
2021-11-02 08:54:04 +01:00
flywind
2f730afe9e fix #18410 (Errors initializing an object of RootObj with the C++ backend) [backport] (#18836)
* fix #18410

* one line comment

* typo

* typo

* cover cpp
2021-10-31 06:22:00 +01:00
Andreas Rumpf
2bda4a30a6 fixes #19000 (#19032)
* fixes #19000

* progress
2021-10-30 10:14:23 +02:00
Derek 呆
f755e452d2 fix #18971 (#19070) [backport:1.6]
since the example code return value from global variable, instead
of first argument, the `n.len` is 1 which causes compiler crashes.
2021-10-29 19:55:48 +02:00
Tail Wag Games
cfdac6666f Freeing critical sections via atexit in system/alloc and system/io (#19062)
* adding new system module sysexitprocs and including system exit procedures when registering exit handlers defined in userland

* fixing failing tests and adding initialization guard to handle cases where the module's global init logic isn't invoked first as is the case with some gc implementaions

* js backend shouldn't try to invoke actual system exit procs

* fixing formatting in sysexitprocs.nim

* 256 was too much - my max number of plugins in my engine is 64 and I require two hooks per runtime it looks like with tls emulation turned off, so for my purposes 128 should be sufficient

* so atExit should be enough here, can get rid of all the extra cruft I had added on top since I didn't realize atExit already provided a stack

* done being cute - since newruntime prevents correct cpp codegen for object variants apparently and breaks tests if I try to use std/exitprocs, ddSysExitProc is just going into both modules. Since system doesn't include system/io, polluting system with it doesn't make sense either... at least it is only importc'd when it is required in either module and we don't have to have any weird when defined(nimOwnedEnabled) with a comment explaining why
2021-10-29 13:42:44 +02:00
Tomasz Kramkowski
ee703c5db4 Fix nimIdentNormalize, fixes #19067 (#19068)
* Make nimIdentNormalize return "" when passed ""; fixes #19067

Fixes #19067

* Add tests for nimIdentNormalize
2021-10-29 11:39:41 +02:00
Andrey Makarov
7ba2659f73 docgen: implement doc link resolution in current module (#18642) 2021-10-28 19:20:52 +02:00
ynfle
c80e2c1736 Docs: change clipboard cursor type to pointer (#19064) 2021-10-28 10:02:18 +02:00
Derek 呆
cd2b093d07 fix a tiny code snippet formatting issue in doc/constructors.rst, again (#19065) 2021-10-28 09:35:57 +02:00
Derek 呆
ee65767d44 fix a tiny formating issue in doc/destructors.rst (#19058) 2021-10-27 11:45:05 +02:00
Netsu
f50bcf82c3 Minor update to terminal docs (#19056)
* Update terminal.nim

- Added some extra docs to cursorUp/Down/Forward/Backward
- I was able to use hideCursor and showCursor without adding stdout, removed the parameter
- Added docs to terminalHeight()* and terminalWidth()*

* Update lib/pure/terminal.nim

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

* Update lib/pure/terminal.nim

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

* Added back f: file to cursor movement

* Removed unnecessary comments

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>
2021-10-26 21:42:22 +02:00
Timothy Alexander
dde556665a Fix #19052; [backport:1.6.0] (#19053)
* Fix #19052; [backport:1.6.0]

Adds a compile flag to avoid a getrandom syscall, fixing #19052.

This is neccesary when the getrandom syscall is missing, as noted in #19052, particularly in kernel versions < 3.17 when getrandom was introduced. Specifically relevant is this is missing from kernel 3.10, which is the supported kernel throughout RHEL 7 and CentOS 7, which is widely used at many organizations. Without this, versions of nim that include sysrand (i.e. versions >= 1.6.0) will not compile without modification, however with this change a compile flag may be used to fall back using /dev/urandom as done with any unknown Posix OS (preferred here as a fallback since it already supplies a cryptographically secure PRNG and existing code deals with entropy pool init, etc).

The change is placed behind a compile flag, as discussed in github ticket #19052 (summed up here):
* First, I can't seem to catch that a importc such as SYS_getrandom is declared without using it (the declared proc returns true, but compiler throws an undeclared identifier flag when referencing it).
* Second, it seemed preferable to be behaviorally explicit vs implicit when considering this is intended to be a cryptographically secure PRNG.
* Third, if I intend to compile on a kernel >= 3.17 while running the binary on at least one system < 3.17, I'll want to be able to target this without relying on a compile time determination if the getrandom syscall is available.

* Documenting compile flag for -d:nimNoGetRandom and adding changelog entry
Related to #19052 and comments in PR #19053. Also created a new changelog file since none currently exists.

Co-authored-by: Timothy Alexander <talexander@midwestlabs.com>
2021-10-26 20:32:52 +02:00
Jason Beetham
8d5a275189 Fixed distinct composite type class proc borrowing (#18904)
* Fixed composite type class proc borrowing

* Moved borrow search into transf

* added borrow check to symbol flag
2021-10-26 11:29:07 +02:00
Jason Beetham
83a2515af7 Fixed generic distinct conversions for 'var' (#18837)
* SameTypeAux now properly traverses generic distincts

* Smarter traversal of distincts

* Removed redundant check

* Fixed nkConv for jsgen

* Added test for non distinct nkConv

* using skiptypes for distinct now

* Fixed genaddr for nkconv
2021-10-26 11:27:11 +02:00
quantimnot
3ecb369ca1 Document file changes that may be needed for add a new platform (#19055)
Co-authored-by: quantimnot <quantimnot@users.noreply.github.com>
2021-10-26 08:33:26 +02:00
Tail Wag Games
582468da1c deinitializing locks at program exit (#19043)
* deinitializing locks at program exit

* deinitLock shouldn't be called for js backend I guess...

* I suppose this is the best way to detect the
ewruntime option

* I guess I need these guards here too...

* fixing merge conflict
2021-10-25 10:13:30 +02:00
Jaremy Creechley
141b76e365 Add Zephyr Support (#19003)
* Porting Nim to run on Zephyr.

Includes changes to `std/net`.

Squashed commit of the following:
    tweaking more memory / malloc things
    revert back bitmasks
    tweaking nim to use kernel heap as C malloc doesn't work
    fixing socket polling on zephyr
    cleanup getting maximum sockets for process or for rtos'es
    reorganizing and fixing net for async / system
    merge netlite changes back into nativesockets
    merge netlite changes back into nativesockets
    reverting native sockets back
    tweaking nim / zephyr network
    adding option to run 'net-lite' from linux
    bridging zephyr's max connections
    fixing net errors
    fixing compilation with getAddrString
    fixing compilation with getAddrString
    experimenting with a nativesockets_lite ... getAddrString
    experimenting with a nativesockets_lite ... getAddrString
    experimenting with a nativesockets_lite ... getLocalAddr
    experimenting with a nativesockets_lite ... getLocalAddr
    experimenting with a nativesockets_lite ...
    add note regarding incorrect FreeRTOS Sockadd_in fields
    changing to NIM_STATIC_ASSERT
    cleaning up the static_assert error messages
    cleaning up the static_assert error messages
    setting up static assert ftw!
    testing compile time asserts
    reworking Sockaddr objects to more closely match various platforms
    reworking Sockaddr objects to more closely match various platforms
    reworking Sockaddr objects to more closely match various platforms
    finding missing items (issue  #18684)
    fixup posix constants (issue  #18684)
    adding plumbing for zephyr os (issue  #18684)
    adding plumbing for zephyr os (issue  #18684)

* fixing constant capitalizations

* remove extra debug prints and fix TSa_Family/cint issue

* remove extra debug prints and fix TSa_Family/cint issue

* Porting Nim to run on Zephyr.

Includes changes to `std/net`.

Squashed commit of the following:
    tweaking more memory / malloc things
    revert back bitmasks
    tweaking nim to use kernel heap as C malloc doesn't work
    fixing socket polling on zephyr
    cleanup getting maximum sockets for process or for rtos'es
    reorganizing and fixing net for async / system
    merge netlite changes back into nativesockets
    merge netlite changes back into nativesockets
    reverting native sockets back
    tweaking nim / zephyr network
    adding option to run 'net-lite' from linux
    bridging zephyr's max connections
    fixing net errors
    fixing compilation with getAddrString
    fixing compilation with getAddrString
    experimenting with a nativesockets_lite ... getAddrString
    experimenting with a nativesockets_lite ... getAddrString
    experimenting with a nativesockets_lite ... getLocalAddr
    experimenting with a nativesockets_lite ... getLocalAddr
    experimenting with a nativesockets_lite ...
    add note regarding incorrect FreeRTOS Sockadd_in fields
    changing to NIM_STATIC_ASSERT
    cleaning up the static_assert error messages
    cleaning up the static_assert error messages
    setting up static assert ftw!
    testing compile time asserts
    reworking Sockaddr objects to more closely match various platforms
    reworking Sockaddr objects to more closely match various platforms
    reworking Sockaddr objects to more closely match various platforms
    finding missing items (issue  #18684)
    fixup posix constants (issue  #18684)
    adding plumbing for zephyr os (issue  #18684)
    adding plumbing for zephyr os (issue  #18684)

* fixing constant capitalizations

* remove extra debug prints and fix TSa_Family/cint issue

* remove extra debug prints and fix TSa_Family/cint issue

* fixing PR issues

* Porting Nim to run on Zephyr.

Includes changes to `std/net`.

Squashed commit of the following:
    tweaking more memory / malloc things
    revert back bitmasks
    tweaking nim to use kernel heap as C malloc doesn't work
    fixing socket polling on zephyr
    cleanup getting maximum sockets for process or for rtos'es
    reorganizing and fixing net for async / system
    merge netlite changes back into nativesockets
    merge netlite changes back into nativesockets
    reverting native sockets back
    tweaking nim / zephyr network
    adding option to run 'net-lite' from linux
    bridging zephyr's max connections
    fixing net errors
    fixing compilation with getAddrString
    fixing compilation with getAddrString
    experimenting with a nativesockets_lite ... getAddrString
    experimenting with a nativesockets_lite ... getAddrString
    experimenting with a nativesockets_lite ... getLocalAddr
    experimenting with a nativesockets_lite ... getLocalAddr
    experimenting with a nativesockets_lite ...
    add note regarding incorrect FreeRTOS Sockadd_in fields
    changing to NIM_STATIC_ASSERT
    cleaning up the static_assert error messages
    cleaning up the static_assert error messages
    setting up static assert ftw!
    testing compile time asserts
    reworking Sockaddr objects to more closely match various platforms
    reworking Sockaddr objects to more closely match various platforms
    reworking Sockaddr objects to more closely match various platforms
    finding missing items (issue  #18684)
    fixup posix constants (issue  #18684)
    adding plumbing for zephyr os (issue  #18684)
    adding plumbing for zephyr os (issue  #18684)

* fixing constant capitalizations

* remove extra debug prints and fix TSa_Family/cint issue

* remove extra debug prints and fix TSa_Family/cint issue

* Remerge

* fixing constant capitalizations

* remove extra debug prints and fix TSa_Family/cint issue

* remove extra debug prints and fix TSa_Family/cint issue

* fixing PR issues

* fix maxDescriptors on zephyr/freertos

* move maxDescriptors to selector.nim -- fixes compile issue

* change realloc impl on zephyr to match ansi c behavior

* change realloc impl on zephyr to match ansi c behavior

* force compileOnly mode for tlwip

Co-authored-by: Jaremy J. Creechley <jaremy.creechley@wavebaselabs.com>
Co-authored-by: Jaremy Creechley <jaremy.creechley@panthalassa.com>
2021-10-24 11:51:57 +02:00
BarrOff
41d9918591 use gmake in the buildscript on Solaris systems (#19036) 2021-10-24 01:24:31 -04:00
BarrOff
6621e1a3ea use the correct header for TIOCGWINSZ on Solaris (#19037) 2021-10-22 19:42:54 -04:00
Etan Kissling
490c4226a5 allow converting static vars to openArray (#19035)
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.
2021-10-22 17:32:02 +02:00
flywind
4d8108046b remove exception (#18906) 2021-10-22 12:15:08 +02:00
Abishek PY
d634587423 feat: copy to clipboard (#18963)
* feat: copy to clipboard

* fix: CI failure related issue

* fix: CI failure issue

* fix: copy to clipboard button bug

* feat: copy pragmadots value to clipboard
2021-10-22 12:10:32 +02:00
Danil Yarantsev
5e2b9341f3 Add Elbrus 2000 architecture (#19024)
* Add Elbrus 2000 architecture

* Add e2k to niminst

* Update compiler/installer.ini

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
2021-10-21 17:01:48 +02:00
Andreas Rumpf
1a45da9150 use two underscores for easy demangling [backport:1.6] (#19028) 2021-10-21 16:53:15 +02:00
John Novak
62701cd3b9 Fix isInvalidFilename & always operate on the full passed in string (#19004)
* Fix isInvalidFilename segfault & deprecate the method

* Update lib/pure/os.nim

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

* Update lib/pure/os.nim

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>

Co-authored-by: konsumlamm <44230978+konsumlamm@users.noreply.github.com>
2021-10-20 17:06:00 +02:00
narimiran
c239db4817 bump NimVersion to 1.7.1 2021-10-19 17:01:56 +02:00
1443 changed files with 52510 additions and 35335 deletions

View File

@@ -1,33 +0,0 @@
## DO NO EDIT DIRECTLY! auto-generated by `nim r tools/ci_generate.nim`
# 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:
NIM_TESTAMENT_BATCH: "0_1"
CC: /usr/bin/clang
tasks:
- setup: |
set -e
cd Nim
. ci/funs.sh && nimBuildCsourcesIfNeeded
echo 'export PATH=$HOME/Nim/bin:$PATH' >> $HOME/.buildenv
- test: |
set -e
cd Nim
. ci/funs.sh && nimInternalBuildKochAndRunCI
triggers:
- action: email
condition: failure
to: Andreas Rumpf <rumpf_a@web.de>

View File

@@ -1,33 +0,0 @@
## DO NO 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_2"
CC: /usr/bin/clang
tasks:
- setup: |
set -e
cd Nim
. ci/funs.sh && nimBuildCsourcesIfNeeded
echo 'export PATH=$HOME/Nim/bin:$PATH' >> $HOME/.buildenv
- test: |
set -e
cd Nim
. ci/funs.sh && nimInternalBuildKochAndRunCI
triggers:
- action: email
condition: failure
to: Andreas Rumpf <rumpf_a@web.de>

View File

@@ -1,33 +0,0 @@
## DO NO 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_2"
CC: /usr/bin/clang
tasks:
- setup: |
set -e
cd Nim
. ci/funs.sh && nimBuildCsourcesIfNeeded
echo 'export PATH=$HOME/Nim/bin:$PATH' >> $HOME/.buildenv
- test: |
set -e
cd Nim
. ci/funs.sh && nimInternalBuildKochAndRunCI
triggers:
- action: email
condition: failure
to: Andreas Rumpf <rumpf_a@web.de>

View File

@@ -1,53 +0,0 @@
---
name: Bug report
about: Have you found an unexpected behavior? Use this template.
title: Think about the title, twice
labels: ''
assignees: ''
---
(Consider writing a PR targetting devel branch after filing this, see [contributing.html](https://nim-lang.github.io/Nim/contributing.html)).
Function `echo` outputs the wrong string.
### Example
```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
```
Hello World!
```
### Possible Solution
* In file xyz there is a call that might be the cause of it.
### Additional Information
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
```

75
.github/ISSUE_TEMPLATE/bug_report.yml vendored Normal file
View File

@@ -0,0 +1,75 @@
name: "Bug Report"
description: "Create a new bug report. Have you found an unexpected behavior? Use this form."
title: "Think about the title, twice."
labels: ["unconfirmed"]
body:
- type: markdown
attributes:
value: |
- **Please provide a minimal code example that reproduces the Bug!** :bug:
Reports with a reproducible example and descriptive detailed information will likely receive fixes faster.
- type: textarea
id: description
attributes:
label: Description
description: |
Use DETAILED DESCRIPTIVE information about the problem.
Here, you go into more details about your Bug report. This section can be a few paragraphs long.
placeholder: Bug reports with reproducible code and detailed information will be fixed faster.
validations:
required: true
- type: textarea
id: nim-version
attributes:
label: Nim Version
description: Copy and paste the output of `nim -v` on the command line. For development versions, make sure to include the commit hash.
validations:
required: true
- type: textarea
id: current-logs
attributes:
label: Current Output
description: Please copy and paste any relevant log output. This will be automatically formatted into code, so no need for backticks.
placeholder: Bug reports with reproducible code and detailed information will be fixed faster.
render: text
- type: textarea
id: expected-logs
attributes:
label: Expected Output
description: Please copy and paste any relevant log output. This will be automatically formatted into code, so no need for backticks.
placeholder: Bug reports with reproducible code and detailed information will be fixed faster.
render: text
- type: textarea
id: possible-solution
attributes:
label: Possible Solution
description: Propose a possible solution.
validations:
required: false
- type: textarea
id: extra-info
attributes:
label: Additional Information
description: Any additional relevant information.
validations:
required: false
- type: markdown
attributes:
value: |
- Thanks for your contributions!, your Bug report will receive feedback from the community soon...
- Please check whether the problem still exists in the devel branch, see [rebuilding the compiler](https://nim-lang.github.io/Nim/intern.html#rebuilding-the-compiler).
- Consider writing a PR targetting devel branch after filing this, see [contributing](https://nim-lang.github.io/Nim/contributing.html).
- 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.
- 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`).
- [Please, consider a Donation for the Nim project.](https://nim-lang.org/donate.html)

View File

@@ -1,35 +0,0 @@
---
name: Feature request
about: Do you want to suggest a new feature? Use this template.
title: ''
labels: ''
assignees: ''
---
<!---
Notice there is now a separate repository for the detailed RFCs and proposals:
https://github.com/nim-lang/RFCs
If you have a simple feature request, you can post it here using this template,
but bear in mind that adding new features to the language is currently a low priority.
-->
### Summary
<!--- Short summary of your proposed feature -->
### Description
<!--- Describe your solution, what problem does it fix? -->
### Alternatives
<!--- Are there any alternatives you've considered? -->
### Additional Information
<!--- For Example:
* A link to a project where the issue is relevant.
* A link to a related issue or discussion.
-->

View File

@@ -0,0 +1,72 @@
name: "Feature request"
description: "Create a new Feature Request. Do you want to suggest a new feature? Use this form."
title: "Think about the title, twice."
labels: ["unconfirmed"]
body:
- type: markdown
attributes:
value: |
- Please provide a minimal code example that illustrates the basic idea behind your feature request.
Reports with full repro code and descriptive detailed information will likely receive feedback faster.
- There is a separate repository for the detailed RFCs and proposals: https://github.com/nim-lang/RFCs.
If you have a simple feature request, you can post it here using this form,
but bear in mind that adding new features to the language is currently a low priority.
- type: textarea
id: summary
attributes:
label: Summary
description: |
Use DETAILED DESCRIPTIVE information about the feature request.
Here, you go into more details about your ideas. This section can be a few paragraphs long.
placeholder: Short summary of your proposed feature.
validations:
required: true
- type: textarea
id: description
attributes:
label: Description
description: Describe your solution, what problem does it fix?
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives
description: Are there any alternatives you've considered?
validations:
required: false
- type: textarea
id: Examples
attributes:
label: Examples
description: Provide examples for your feature request here.
placeholder: Example code here.
- type: textarea
id: incompatibility
attributes:
label: Backwards Compatibility
description: If your Feature Request introduces backward-incompatible changes, describe them and propose how to deal with them.
validations:
required: false
- type: textarea
id: links
attributes:
label: Links
description: Please copy and paste any relevant links to projects, issues, discussions, technical documentations, code samples, etc.
validations:
required: false
- type: markdown
attributes:
value: |
- Thanks for your contributions!, your ideas will receive feedback from the community soon...
- **Remember to :star: Star the Nim project on GitHub!.**
- Consider writing a PR targetting devel branch after filing this, see [contributing](https://nim-lang.github.io/Nim/contributing.html).
- [Please, consider a Donation for the Nim project.](https://nim-lang.org/donate.html)

View File

@@ -6,6 +6,7 @@ on:
- 'compiler/renderverbatim.nim'
- 'config/nimdoc.cfg'
- 'doc/**.rst'
- 'doc/**.md'
- 'doc/nimdoc.css'
- 'lib/**.nim'
- 'nimdoc/testproject/expected/testproject.html'
@@ -13,6 +14,7 @@ on:
- 'tools/kochdocs.nim'
- '.github/workflows/ci_docs.yml'
- 'koch.nim'
pull_request:
# Run only on changes on these files.
paths:
@@ -20,6 +22,7 @@ on:
- 'compiler/renderverbatim.nim'
- 'config/nimdoc.cfg'
- 'doc/**.rst'
- 'doc/**.md'
- 'doc/nimdoc.css'
- 'lib/**.nim'
- 'nimdoc/testproject/expected/testproject.html'
@@ -28,6 +31,10 @@ on:
- '.github/workflows/ci_docs.yml'
- 'koch.nim'
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
build:
strategy:
@@ -40,7 +47,7 @@ jobs:
- target: windows
os: windows-2019
- target: osx
os: macos-10.15
os: macos-11
name: ${{ matrix.target }}
runs-on: ${{ matrix.os }}
@@ -48,7 +55,7 @@ jobs:
steps:
- name: 'Checkout'
uses: actions/checkout@v2
uses: actions/checkout@v3
with:
fetch-depth: 2
@@ -104,7 +111,7 @@ jobs:
if: |
github.event_name == 'push' && github.ref == 'refs/heads/devel' &&
matrix.target == 'linux'
uses: crazy-max/ghaction-github-pages@v1
uses: crazy-max/ghaction-github-pages@v3
with:
build_dir: doc/html
env:

View File

@@ -1,12 +1,23 @@
name: Packages CI
on: [push, pull_request]
on:
pull_request:
push:
branches:
- 'devel'
- 'version-2-0'
- 'version-1-6'
- 'version-1-2'
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
build:
strategy:
fail-fast: false
matrix:
os: [ubuntu-20.04, macos-10.15]
os: [ubuntu-20.04, macos-11]
cpu: [amd64]
batch: ["allowed_failures", "0_3", "1_3", "2_3"] # list of `index_num`
name: '${{ matrix.os }} (batch: ${{ matrix.batch }})'
@@ -17,12 +28,12 @@ jobs:
NIM_TESTAMENT_BATCH: ${{ matrix.batch }}
steps:
- name: 'Checkout'
uses: actions/checkout@v2
uses: actions/checkout@v3
with:
fetch-depth: 2
- name: 'Install node.js 16.x'
uses: actions/setup-node@v2
uses: actions/setup-node@v3
with:
node-version: '16.x'

90
.github/workflows/ci_publish.yml vendored Normal file
View File

@@ -0,0 +1,90 @@
name: Tracking orc-booting compiler memory usage
on:
pull_request_target:
types: [closed]
jobs:
build:
if: github.event.pull_request.merged == true
strategy:
fail-fast: false
matrix:
os: [ubuntu-20.04]
cpu: [amd64]
name: '${{ matrix.os }}'
runs-on: ${{ matrix.os }}
steps:
- name: 'Checkout'
uses: actions/checkout@v3
with:
fetch-depth: 2
- name: 'Install node.js 16.x'
uses: actions/setup-node@v3
with:
node-version: '16.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: |
set -e
. ci/funs.sh
nimInternalInstallDepsWindows
echo_run echo "${{ github.workspace }}/dist/mingw64/bin" >> "${GITHUB_PATH}"
- name: 'Add build binaries to PATH'
shell: bash
run: echo "${{ github.workspace }}/bin" >> "${GITHUB_PATH}"
- name: 'System information'
shell: bash
run: . ci/funs.sh && nimCiSystemInfo
- name: 'Build csourcesAny'
shell: bash
run: . ci/funs.sh && nimBuildCsourcesIfNeeded CC=gcc ucpu='${{ matrix.cpu }}'
- name: 'Build koch'
shell: bash
run: nim c koch
- name: 'Build Nim'
shell: bash
run: ./koch boot -d:release -d:nimStrictMode --lib:lib
- name: 'Action'
shell: bash
run: nim c -r -d:release ci/action.nim
- name: 'Comment'
uses: actions/github-script@v6
with:
script: |
const fs = require('fs');
try {
const data = fs.readFileSync('ci/nimcache/results.txt', 'utf8');
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: data
})
} catch (err) {
console.error(err);
}

7
.gitignore vendored
View File

@@ -3,9 +3,9 @@
!*.*
# Cache
nimcache/
rnimcache/
dnimcache/
nimcache*/
rnimcache*/
dnimcache*/
*.o
!/icons/*.o
@@ -67,6 +67,7 @@ testament.db
/csources
/csources_v1
/csources_v2
/dist/
# /lib/fusion # fusion is now unbundled; `git status` should reveal if it's there so users can act on it

View File

@@ -1,7 +1,8 @@
trigger:
branches:
include:
- '*'
- 'devel'
- 'version-*'
pr:
branches:
include:
@@ -19,7 +20,7 @@ jobs:
strategy:
matrix:
Linux_amd64:
vmImage: 'ubuntu-18.04'
vmImage: 'ubuntu-20.04'
CPU: amd64
# regularly breaks, refs bug #17325
Linux_i386:
@@ -28,10 +29,10 @@ jobs:
vmImage: 'ubuntu-18.04'
CPU: i386
OSX_amd64:
vmImage: 'macOS-10.15'
vmImage: 'macOS-11'
CPU: amd64
OSX_amd64_cpp:
vmImage: 'macOS-10.15'
vmImage: 'macOS-11'
CPU: amd64
NIM_COMPILE_TO_CPP: true
Windows_amd64_batch0_3:

View File

@@ -7,14 +7,14 @@ 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
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
GDB_PYTHON_MODULE_PATH="$NIM_SYSROOT/tools/nim-gdb.py"
GDB_PYTHON_MODULE_PATH="$NIM_SYSROOT/tools/debug/nim-gdb.py"
# Run GDB with the additional arguments that load the pretty printers
# Set the environment variable `NIM_GDB` to overwrite the call to a

View File

@@ -3,7 +3,7 @@ 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 @GDB_PYTHON_MODULE_PATH=%NIM_ROOT%\tools\debug\nim-gdb.py
set @NIM_GDB=gdb.exe
@echo source %@GDB_PYTHON_MODULE_PATH%> wingdbcommand.txt

View File

@@ -24,6 +24,6 @@ if not exist %nim_csources% (
cd ..
copy /y bin\nim.exe %nim_csources%
)
bin\nim.exe c --skipUserCfg --skipParentCfg --hints:off koch
bin\nim.exe c --noNimblePath --skipUserCfg --skipParentCfg --hints:off koch
koch boot -d:release --skipUserCfg --skipParentCfg --hints:off
koch tools --skipUserCfg --skipParentCfg --hints:off

View File

@@ -11,7 +11,7 @@ set -e # exit on first error
. ci/funs.sh
nimBuildCsourcesIfNeeded "$@"
echo_run bin/nim c --skipUserCfg --skipParentCfg --hints:off koch
echo_run bin/nim c --noNimblePath --skipUserCfg --skipParentCfg --hints:off koch
echo_run ./koch boot -d:release --skipUserCfg --skipParentCfg --hints:off
echo_run ./koch tools --skipUserCfg --skipParentCfg --hints:off

View File

@@ -1,12 +1,21 @@
# v1.8.x - yyyy-mm-dd
# v2.2.0 - yyyy-mm-dd
## Changes affecting backward compatibility
## Standard library additions and changes
[//]: # "Changes:"
[//]: # "Additions:"
- Added `parseutils.parseSize` - inverse to `strutils.formatSize` - to parse human readable sizes.
[//]: # "Deprecations:"
[//]: # "Removals:"
## Language changes
@@ -15,11 +24,8 @@
## Compiler changes
- `nim` can now compile version 1.4.0 as follows: `nim c --lib:lib --stylecheck:off compiler/nim`,
without requiring `-d:nimVersion140` which is now a noop.
## Tool changes

View File

@@ -282,7 +282,7 @@
- Removed the deprecated `asyncdispatch.newAsyncNativeSocket`.
- Removed the deprecated `dom.releaseEvents` and `dom.captureEvents`.
- Removed `sharedlists.initSharedList`, was deprecated and produces undefined behaviour.
- Removed `sharedlist.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)

View File

@@ -0,0 +1,367 @@
# v2.0.0 - yyyy-mm-dd
## Changes affecting backward compatibility
- `httpclient.contentLength` default to `-1` if the Content-Length header is not set in the response. It follows Apache HttpClient(Java), http(go) and .Net HttpWebResponse(C#) behavior. Previously it raised `ValueError`.
- `addr` is now available for all addressable locations,
`unsafeAddr` is now deprecated and an alias for `addr`.
- Certain definitions from the default `system` module have been moved to
the following new modules:
- `std/syncio`
- `std/assertions`
- `std/formatfloat`
- `std/objectdollar`
- `std/widestrs`
- `std/typedthreads`
- `std/sysatomics`
In the future, these definitions will be removed from the `system` module,
and their respective modules will have to be imported to use them.
Currently, to make these imports required, the `-d:nimPreviewSlimSystem` option
may be used.
- Enabling `-d:nimPreviewSlimSystem` also removes the following deprecated
symbols in the `system` module:
- Aliases with `Error` suffix to exception types that have a `Defect` suffix
(see [exceptions](https://nim-lang.github.io/Nim/exceptions.html)):
`ArithmeticError`, `DivByZeroError`, `OverflowError`,
`AccessViolationError`, `AssertionError`, `OutOfMemError`, `IndexError`,
`FieldError`, `RangeError`, `StackOverflowError`, `ReraiseError`,
`ObjectAssignmentError`, `ObjectConversionError`, `FloatingPointError`,
`FloatOverflowError`, `FloatUnderflowError`, `FloatInexactError`,
`DeadThreadError`, `NilAccessError`
- `addQuitProc`, replaced by `exitprocs.addExitProc`
- Legacy unsigned conversion operations: `ze`, `ze64`, `toU8`, `toU16`, `toU32`
- `TaintedString`, formerly a distinct alias to `string`
- `PInt32`, `PInt64`, `PFloat32`, `PFloat64`, aliases to
`ptr int32`, `ptr int64`, `ptr float32`, `ptr float64`
- Enabling `-d:nimPreviewSlimSystem` removes the import of `channels_builtin` in
in the `system` module.
- Enabling `-d:nimPreviewCstringConversion`, `ptr char`, `ptr array[N, char]` and `ptr UncheckedArray[N, char]` don't support conversion to cstring anymore.
- The `gc:v2` option is removed.
- The `mainmodule` and `m` options are removed.
- The `threads:on` option is now the default.
- Optional parameters in combination with `: body` syntax (RFC #405) are now opt-in via
`experimental:flexibleOptionalParams`.
- Automatic dereferencing (experimental feature) is removed.
- The `Math.trunc` polyfill for targeting Internet Explorer was
previously included in most JavaScript output files.
Now, it is only included with `-d:nimJsMathTruncPolyfill`.
If you are targeting Internet Explorer, you may choose to enable this option
or define your own `Math.trunc` polyfill using the [`emit` pragma](https://nim-lang.org/docs/manual.html#implementation-specific-pragmas-emit-pragma).
Nim uses `Math.trunc` for the division and modulo operators for integers.
- `shallowCopy` and `shallow` are removed for ARC/ORC. Use `move` when possible or combine assignment and
`sink` for optimization purposes.
- The experimental `nimPreviewDotLikeOps` switch is going to be removed or deprecated because it didn't fullfill its promises.
- The `{.this.}` pragma, deprecated since 0.19, has been removed.
- `nil` literals can no longer be directly assigned to variables or fields of `distinct` pointer types. They must be converted instead.
```nim
type Foo = distinct ptr int
# Before:
var x: Foo = nil
# After:
var x: Foo = Foo(nil)
```
- Removed two type pragma syntaxes deprecated since 0.20, namely
`type Foo = object {.final.}`, and `type Foo {.final.} [T] = object`.
- `foo a = b` now means `foo(a = b)` rather than `foo(a) = b`. This is consistent
with the existing behavior of `foo a, b = c` meaning `foo(a, b = c)`.
This decision was made with the assumption that the old syntax was used rarely;
if your code used the old syntax, please be aware of this change.
- [Overloadable enums](https://nim-lang.github.io/Nim/manual.html#overloadable-enum-value-names) and Unicode Operators
are no longer experimental.
- Removed the `nimIncrSeqV3` define.
- `macros.getImpl` for `const` symbols now returns the full definition node
(as `nnkConstDef`) rather than the AST of the constant value.
- Lock levels are deprecated, now a noop.
- ORC is now the default memory management strategy. Use
`--mm:refc` for a transition period.
- `strictEffects` are no longer experimental.
Use `legacy:laxEffects` to keep backward compatibility.
- The `gorge`/`staticExec` calls will now return a descriptive message in the output
if the execution fails for whatever reason. To get back legacy behaviour use `-d:nimLegacyGorgeErrors`.
- Pointer to `cstring` conversion now triggers a `[PtrToCstringConv]` warning.
This warning will become an error in future versions! Use a `cast` operation
like `cast[cstring](x)` instead.
- `logging` will default to flushing all log level messages. To get the legacy behaviour of only flushing Error and Fatal messages, use `-d:nimV1LogFlushBehavior`.
- Redefining templates with the same signature was previously
allowed to support certain macro code. To do this explicitly, the
`{.redefine.}` pragma has been added. Note that this is only for templates.
Implicit redefinition of templates is now deprecated and will give an error in the future.
- Using an unnamed break in a block is deprecated. This warning will become an error in future versions! Use a named block with a named break instead.
- Several Standard libraries are moved to nimble packages, use `nimble` to install them:
- `std/punycode` => `punycode`
- `std/asyncftpclient` => `asyncftpclient`
- `std/smtp` => `smtp`
- `std/db_common` => `db_connector/db_common`
- `std/db_sqlite` => `db_connector/db_sqlite`
- `std/db_mysql` => `db_connector/db_mysql`
- `std/db_postgres` => `db_connector/db_postgres`
- `std/db_odbc` => `db_connector/db_odbc`
- Previously, calls like `foo(a, b): ...` or `foo(a, b) do: ...` where the final argument of
`foo` had type `proc ()` were assumed by the compiler to mean `foo(a, b, proc () = ...)`.
This behavior is now deprecated. Use `foo(a, b) do (): ...` or `foo(a, b, proc () = ...)` instead.
- If no exception or any exception deriving from Exception but not Defect or CatchableError given in except, a `warnBareExcept` warning will be triggered.
- The experimental strictFuncs feature now disallows a store to the heap via a `ref` or `ptr` indirection.
- Underscores (`_`) as routine parameters are now ignored and cannot be used in the routine body.
The following code now does not compile:
```nim
proc foo(_: int): int = _ + 1
echo foo(1)
```
Instead, the following code now compiles:
```nim
proc foo(_, _: int): int = 123
echo foo(1, 2)
```
- Underscores (`_`) as generic parameters are not supported and cannot be used.
Generics that use `_` as parameters will no longer compile requires you to replace `_` with something else:
```nim
proc foo[_](t: typedesc[_]): string = "BAR" # Can not compile
proc foo[T](t: typedesc[T]): string = "BAR" # Can compile
```
- - Added the `--legacy:verboseTypeMismatch` switch to get legacy type mismatch error messages.
## Standard library additions and changes
[//]: # "Changes:"
- OpenSSL 3 is now supported.
- `macros.parseExpr` and `macros.parseStmt` now accept an optional
filename argument for more informative errors.
- Module `colors` expanded with missing colors from the CSS color standard.
`colPaleVioletRed` and `colMediumPurple` have also been changed to match the CSS color standard.
- Fixed `lists.SinglyLinkedList` being broken after removing the last node ([#19353](https://github.com/nim-lang/Nim/pull/19353)).
- The `md5` module now works at compile time and in JavaScript.
- Changed `mimedb` to use an `OrderedTable` instead of `OrderedTableRef` to support `const` tables.
- `strutils.find` now uses and defaults to `last = -1` for whole string searches,
making limiting it to just the first char (`last = 0`) valid.
- `random.rand` now works with `Ordinal`s.
- Undeprecated `os.isvalidfilename`.
- `std/oids` now uses `int64` to store time internally (before it was int32).
- `std/uri.Uri` dollar `$` improved, precalculates the `string` result length from the `Uri`.
- `std/uri.Uri.isIpv6` is now exported.
- `std/logging.ConsoleLogger` and `FileLogger` now have a `flushThreshold` attribute to set what log message levels are automatically flushed. For Nim v1 use `-d:nimFlushAllLogs` to automatically flush all message levels. Flushing all logs is the default behavior for Nim v2.
- `std/net.IpAddress` dollar `$` improved, uses a fixed capacity for the `string` result based from the `IpAddressFamily`.
- `std/jsfetch.newFetchOptions` now has default values for all parameters
- `std/jsformdata` now accepts `Blob` data type.
- `std/sharedlist` and `std/sharedtables` are now deprecated, see RFC [#433](https://github.com/nim-lang/RFCs/issues/433).
- New compile flag (`-d:nimNoGetRandom`) when building `std/sysrand` to remove dependency on linux `getrandom` syscall.
This compile flag only affects linux builds and is necessary if either compiling on a linux kernel version < 3.17, or if code built will be executing on kernel < 3.17.
On linux kernels < 3.17 (such as kernel 3.10 in RHEL7 and CentOS7), the `getrandom` syscall was not yet introduced. Without this, the `std/sysrand` module will not build properly, and if code is built on a kernel >= 3.17 without the flag, any usage of the `std/sysrand` module will fail to execute on a kernel < 3.17 (since it attempts to perform a syscall to `getrandom`, which isn't present in the current kernel). A compile flag has been added to force the `std/sysrand` module to use /dev/urandom (available since linux kernel 1.3.30), rather than the `getrandom` syscall. This allows for use of a cryptographically secure PRNG, regardless of kernel support for the `getrandom` syscall.
When building for RHEL7/CentOS7 for example, the entire build process for nim from a source package would then be:
```sh
$ yum install devtoolset-8 # Install GCC version 8 vs the standard 4.8.5 on RHEL7/CentOS7. Alternatively use -d:nimEmulateOverflowChecks. See issue #13692 for details
$ scl enable devtoolset-8 bash # Run bash shell with default toolchain of gcc 8
$ sh build.sh # per unix install instructions
$ bin/nim c koch # per unix install instructions
$ ./koch boot -d:release # per unix install instructions
$ ./koch tools -d:nimNoGetRandom # pass the nimNoGetRandom flag to compile std/sysrand without support for getrandom syscall
```
This is necessary to pass when building nim on kernel versions < 3.17 in particular to avoid an error of "SYS_getrandom undeclared" during the build process for stdlib (sysrand in particular).
[//]: # "Additions:"
- Added ISO 8601 week date utilities in `times`:
- Added `IsoWeekRange`, a range type for weeks in a week-based year.
- Added `IsoYear`, a distinct type for a week-based year in contrast to a regular year.
- Added a `initDateTime` overload to create a datetime from an ISO week date.
- Added `getIsoWeekAndYear` to get an ISO week number and week-based year from a datetime.
- Added `getIsoWeeksInYear` to return the number of weeks in a week-based year.
- Added new modules which were part of `std/os`:
- Added `std/oserrors` for OS error reporting. Added `std/envvars` for environment variables handling.
- Added `std/paths`, `std/dirs`, `std/files`, `std/symlinks` and `std/appdirs`.
- Added `std/cmdline` for reading command line parameters.
- Added `sep` parameter in `std/uri` to specify the query separator.
- Added bindings to [`Array.shift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift)
and [`queueMicrotask`](https://developer.mozilla.org/en-US/docs/Web/API/queueMicrotask)
in `jscore` for JavaScript targets.
- Added `UppercaseLetters`, `LowercaseLetters`, `PunctuationChars`, `PrintableChars` sets to `std/strutils`.
- Added `complex.sgn` for obtaining the phase of complex numbers.
- Added `insertAdjacentText`, `insertAdjacentElement`, `insertAdjacentHTML`,
`after`, `before`, `closest`, `append`, `hasAttributeNS`, `removeAttributeNS`,
`hasPointerCapture`, `releasePointerCapture`, `requestPointerLock`,
`replaceChildren`, `replaceWith`, `scrollIntoViewIfNeeded`, `setHTML`,
`toggleAttribute`, and `matches` to `std/dom`.
- Added [`jsre.hasIndices`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/hasIndices)
- Added `capacity` for `string` and `seq` to return the current capacity, see https://github.com/nim-lang/RFCs/issues/460
- Added `openArray[char]` overloads for `std/parseutils` allowing more code reuse.
- Added `openArray[char]` overloads for `std/unicode` allowing more code reuse.
- Added `safe` parameter to `base64.encodeMime`.
[//]: # "Deprecations:"
- Deprecated `selfExe` for Nimscript.
- Deprecated `std/sums`.
- Deprecated `std/base64.encode` for collections of arbitrary integer element type.
Now only `byte` and `char` are supported.
[//]: # "Removals:"
- Removed deprecated module `parseopt2`.
- Removed deprecated module `sharedstrings`.
- Removed deprecated module `dom_extensions`.
- Removed deprecated module `LockFreeHash`.
- Removed deprecated module `events`.
- Removed deprecated `oids.oidToString`.
- Removed define `nimExperimentalAsyncjsThen` for `std/asyncjs.then` and `std/jsfetch`.
- Removed deprecated `jsre.test` and `jsre.toString`.
- Removed deprecated `math.c_frexp`.
- Removed deprecated `` httpcore.`==` ``.
- Removed deprecated `std/posix.CMSG_SPACE` and `std/posix.CMSG_LEN` that takes wrong argument types.
- Removed deprecated `osproc.poDemon`, symbol with typo.
- Removed deprecated `tables.rightSize`.
- Removed deprecated `posix.CLONE_STOPPED`.
## Language changes
- [Tag tracking](https://nim-lang.github.io/Nim/manual.html#effect-system-tag-tracking) supports the definition of forbidden tags by the `.forbids` pragma
which can be used to disable certain effects in proc types.
- [Case statement macros](https://nim-lang.github.io/Nim/manual.html#macros-case-statement-macros) are no longer experimental,
meaning you no longer need to enable the experimental switch `caseStmtMacros` to use them.
- Full command syntax and block arguments i.e. `foo a, b: c` are now allowed
for the right-hand side of type definitions in type sections. Previously
they would error with "invalid indentation".
- Compile-time define changes:
- `defined` now accepts identifiers separated by dots, i.e. `defined(a.b.c)`.
In the command line, this is defined as `-d:a.b.c`. Older versions can
use accents as in ``defined(`a.b.c`)`` to access such defines.
- [Define pragmas for constants](https://nim-lang.github.io/Nim/manual.html#implementation-specific-pragmas-compileminustime-define-pragmas)
now support a string argument for qualified define names.
```nim
# -d:package.FooBar=42
const FooBar {.intdefine: "package.FooBar".}: int = 5
echo FooBar # 42
```
This was added to help disambiguate similar define names for different packages.
In older versions, this could only be achieved with something like the following:
```nim
const FooBar = block:
const `package.FooBar` {.intdefine.}: int = 5
`package.FooBar`
```
- A generic `define` pragma for constants has been added that interprets
the value of the define based on the type of the constant value.
See the [experimental manual](https://nim-lang.github.io/Nim/manual_experimental.html#generic-define-pragma)
for a list of supported types.
- [Macro pragmas](https://nim-lang.github.io/Nim/manual.html#userminusdefined-pragmas-macro-pragmas) changes:
- Templates now accept macro pragmas.
- Macro pragmas for var/let/const sections have been redesigned in a way that works
similarly to routine macro pragmas. The new behavior is documented in the
[experimental manual](https://nim-lang.github.io/Nim/manual_experimental.html#extended-macro-pragmas).
- Pragma macros on type definitions can now return `nnkTypeSection` nodes as well as `nnkTypeDef`,
allowing multiple type definitions to be injected in place of the original type definition.
```nim
import macros
macro multiply(amount: static int, s: untyped): untyped =
let name = $s[0].basename
result = newNimNode(nnkTypeSection)
for i in 1 .. amount:
result.add(newTree(nnkTypeDef, ident(name & $i), s[1], s[2]))
type
Foo = object
Bar {.multiply: 3.} = object
x, y, z: int
Baz = object
# becomes
type
Foo = object
Bar1 = object
x, y, z: int
Bar2 = object
x, y, z: int
Bar3 = object
x, y, z: int
Baz = object
```
- A new form of type inference called [top-down inference](https://nim-lang.github.io/Nim/manual_experimental.html#topminusdown-type-inference)
has been implemented for a variety of basic cases. For example, code like the following now compiles:
```nim
let foo: seq[(float, byte, cstring)] = @[(1, 2, "abc")]
```
- `cstring` is now accepted as a selector in `case` statements, removing the
need to convert to `string`. On the JS backend, this is translated directly
to a `switch` statement.
- Nim now supports `out` parameters and ["strict definitions"](https://nim-lang.github.io/Nim/manual_experimental.html#strict-definitions-and-nimout-parameters).
- Nim now offers a [strict mode](https://nim-lang.github.io/Nim/manual_experimental.html#strict-case-objects) for `case objects`.
- IBM Z architecture and macOS m1 arm64 architecture are supported.
- `=wasMoved` can be overridden by users.
## Compiler changes
- The `gc` switch has been renamed to `mm` ("memory management") in order to reflect the
reality better. (Nim moved away from all techniques based on "tracing".)
- Defines the `gcRefc` symbol which allows writing specific code for the refc GC.
- `nim` can now compile version 1.4.0 as follows: `nim c --lib:lib --stylecheck:off compiler/nim`,
without requiring `-d:nimVersion140` which is now a noop.
- `--styleCheck`, `--hintAsError` and `--warningAsError` now only apply to the current package.
- The switch `--nimMainPrefix:prefix` has been added to add a prefix to the names of `NimMain` and
related functions produced on the backend. This prevents conflicts with other Nim
static libraries.
- When compiling for Release the flag `-fno-math-errno` is used for GCC.
## Tool changes
- Nim now ships Nimble version 0.14 which added support for lock-files. Libraries are stored in `$nimbleDir/pkgs2` (it was `$nimbleDir/pkgs`).

26
ci/action.nim Normal file
View File

@@ -0,0 +1,26 @@
import std/[strutils, os, osproc, parseutils, strformat]
proc main() =
var msg = ""
const cmd = "./koch boot --gc:orc -d:release"
let (output, exitCode) = execCmdEx(cmd)
doAssert exitCode == 0, output
let start = rfind(output, "Hint: mm")
doAssert parseUntil(output, msg, "; proj", start) > 0, output
let (commitHash, _) = execCmdEx("""git log --format="%H" -n 1""")
let welcomeMessage = fmt"""Thanks for your hard work on this PR!
The lines below are statistics of the Nim compiler built from {commitHash}
{msg}
"""
createDir "ci/nimcache"
writeFile "ci/nimcache/results.txt", welcomeMessage
when isMainModule:
main()

View File

@@ -76,6 +76,8 @@ _nimBuildCsourcesIfNeeded(){
makeX=gmake
elif [ "$unamestr" = 'CROSSOS' ]; then
makeX=gmake
elif [ "$unamestr" = 'SunOS' ]; then
makeX=gmake
else
makeX=make
fi

View File

@@ -1,9 +0,0 @@
version = system.NimVersion
author = "Andreas Rumpf"
description = "Compiler package providing the compiler sources as a library."
license = "MIT"
installDirs = @["compiler", "nimsuggest"]
requires "nim >= 0.14.0"

128
compiler/aliasanalysis.nim Normal file
View File

@@ -0,0 +1,128 @@
import ast
import std / assertions
const
PathKinds0* = {nkDotExpr, nkCheckedFieldExpr,
nkBracketExpr, nkDerefExpr, nkHiddenDeref,
nkAddr, nkHiddenAddr,
nkObjDownConv, nkObjUpConv}
PathKinds1* = {nkHiddenStdConv, nkHiddenSubConv}
proc skipConvDfa*(n: PNode): PNode =
result = n
while true:
case result.kind
of nkObjDownConv, nkObjUpConv:
result = result[0]
of PathKinds1:
result = result[1]
else: break
proc isAnalysableFieldAccess*(orig: PNode; owner: PSym): bool =
var n = orig
while true:
case n.kind
of PathKinds0 - {nkHiddenDeref, nkDerefExpr}:
n = n[0]
of PathKinds1:
n = n[1]
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
(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
{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
#
# let splited = split(move self.root, x)
# self.root = merge(splited.lower, splited.greater)
#
# could be written without the ``move self.root``. However, this would be
# wrong! Then the write barrier for the ``self.root`` assignment would
# free the old data and all is lost! Lesson: Don't be too smart, trust the
# lower level C++ optimizer to specialize this code.
type AliasKind* = enum
yes, no, maybe
proc aliases*(obj, field: PNode): AliasKind =
# obj -> field:
# x -> x: true
# x -> x.f: true
# x.f -> x: false
# x.f -> x.f: true
# x.f -> x.v: false
# x -> x[]: true
# x[] -> x: false
# x -> x[0]: true
# x[0] -> x: false
# x[0] -> x[0]: true
# x[0] -> x[1]: false
# x -> x[i]: true
# x[i] -> x: false
# x[i] -> x[i]: maybe; Further analysis could make this return true when i is a runtime-constant
# x[i] -> x[j]: maybe; also returns maybe if only one of i or j is a compiletime-constant
template collectImportantNodes(result, n) =
var result: seq[PNode]
var n = n
while true:
case n.kind
of PathKinds0 - {nkDotExpr, nkBracketExpr, nkDerefExpr, nkHiddenDeref}:
n = n[0]
of PathKinds1:
n = n[1]
of nkDotExpr, nkBracketExpr, nkDerefExpr, nkHiddenDeref:
result.add n
n = n[0]
of nkSym:
result.add n
break
else: return no
collectImportantNodes(objImportantNodes, obj)
collectImportantNodes(fieldImportantNodes, field)
# If field is less nested than obj, then it cannot be part of/aliased by obj
if fieldImportantNodes.len < objImportantNodes.len: return no
result = yes
for i in 1..objImportantNodes.len:
# We compare the nodes leading to the location of obj and field
# with each other.
# We continue until they diverge, in which case we return no, or
# until we reach the location of obj, in which case we do not need
# to look further, since field must be part of/aliased by obj now.
# If we encounter an element access using an index which is a runtime value,
# we simply return maybe instead of yes; should further nodes not diverge.
let currFieldPath = fieldImportantNodes[^i]
let currObjPath = objImportantNodes[^i]
if currFieldPath.kind != currObjPath.kind:
return no
case currFieldPath.kind
of nkSym:
if currFieldPath.sym != currObjPath.sym: return no
of nkDotExpr:
if currFieldPath[1].sym != currObjPath[1].sym: return no
of nkDerefExpr, nkHiddenDeref:
discard
of nkBracketExpr:
if currFieldPath[1].kind in nkLiterals and currObjPath[1].kind in nkLiterals:
if currFieldPath[1].intVal != currObjPath[1].intVal:
return no
else:
result = maybe
else: assert false # unreachable

View File

@@ -12,6 +12,9 @@
import
ast, astalgo, types, trees, intsets
when defined(nimPreviewSlimSystem):
import std/assertions
type
TAnalysisResult* = enum
arNo, arMaybe, arYes
@@ -74,24 +77,29 @@ proc isPartOf*(a, b: PNode): TAnalysisResult =
## cases:
##
## YES-cases:
## ```
## x <| x # for general trees
## x[] <| x
## x[i] <| x
## x.f <| x
## ```
##
## NO-cases:
## ```
## x !<| y # depending on type and symbol kind
## x[constA] !<| x[constB]
## x.f !<| x.g
## x.f !<| y.f iff x !<= y
## ```
##
## MAYBE-cases:
##
## ```
## x[] ?<| y[] iff compatible type
##
##
## x[] ?<| y depending on type
##
## ```
if a.kind == b.kind:
case a.kind
of nkSym:

View File

@@ -13,6 +13,9 @@ import
lineinfos, hashes, options, ropes, idents, int128, tables
from strutils import toLowerAscii
when defined(nimPreviewSlimSystem):
import std/assertions
export int128
type
@@ -204,12 +207,11 @@ type
nkPtrTy, # ``ptr T``
nkVarTy, # ``var T``
nkConstTy, # ``const T``
nkMutableTy, # ``mutable T``
nkOutTy, # ``out T``
nkDistinctTy, # distinct type
nkProcTy, # proc type
nkIteratorTy, # iterator type
nkSharedTy, # 'shared T'
# we use 'nkPostFix' for the 'not nil' addition
nkSinkAsgn, # '=sink(x, y)'
nkEnumTy, # enum body
nkEnumFieldDef, # `ident = expr` in an enumeration
nkArgList, # argument list
@@ -229,7 +231,7 @@ type
TNodeKinds* = set[TNodeKind]
type
TSymFlag* = enum # 48 flags!
TSymFlag* = enum # 49 flags!
sfUsed, # read access of sym (for warnings) or simply used
sfExported, # symbol is exported from module
sfFromGeneric, # symbol is instantiation of a generic; this is needed
@@ -257,7 +259,8 @@ type
# *OR*: a proc is indirectly called (used as first class)
sfCompilerProc, # proc is a compiler proc, that is a C proc that is
# needed for the code generator
sfProcvar, # proc can be passed to a proc var
sfEscapes # param escapes
# currently unimplemented
sfDiscriminant, # field is a discriminant in a record/object
sfRequiresInit, # field must be initialized during construction
sfDeprecated, # symbol is deprecated
@@ -296,10 +299,17 @@ type
sfInjectDestructors # whether the proc needs the 'injectdestructors' transformation
sfNeverRaises # proc can never raise an exception, not even OverflowDefect
# or out-of-memory
sfSystemRaisesDefect # proc in the system can raise defects
sfUsedInFinallyOrExcept # symbol is used inside an 'except' or 'finally'
sfSingleUsedTemp # For temporaries that we know will only be used once
sfNoalias # 'noalias' annotation, means C's 'restrict'
sfEffectsDelayed # an 'effectsDelayed' parameter
sfGeneratedType # A anonymous generic type that is generated by the compiler for
# objects that do not have generic parameters in case one of the
# object fields has one.
#
# This is disallowed but can cause the typechecking to go into
# an infinite loop, this flag is used as a sentinel to stop it.
TSymFlags* = set[TSymFlag]
@@ -328,10 +338,10 @@ const
sfExperimental* = sfOverriden # module uses the .experimental switch
sfGoto* = sfOverriden # var is used for 'goto' code generation
sfWrittenTo* = sfBorrow # param is assigned to
sfEscapes* = sfProcvar # param escapes
# currently unimplemented
sfBase* = sfDiscriminant
sfIsSelf* = sfOverriden # param is 'self'
sfCustomPragma* = sfRegister # symbol is custom pragma template
sfTemplateRedefinition* = sfExportc # symbol is a redefinition of an earlier template
const
# getting ready for the future expr/stmt merge
@@ -344,7 +354,8 @@ const
ensuresEffects* = 2 # 'ensures' annotation
tagEffects* = 3 # user defined tag ('gc', 'time' etc.)
pragmasEffects* = 4 # not an effect, but a slot for pragmas in proc type
effectListLen* = 5 # list of effects list
forbiddenEffects* = 5 # list of illegal effects
effectListLen* = 6 # list of effects list
nkLastBlockStmts* = {nkRaiseStmt, nkReturnStmt, nkBreakStmt, nkContinueStmt}
# these must be last statements in a block
@@ -497,11 +508,12 @@ type
# the flag is applied to proc default values and to calls
nfExecuteOnReload # A top-level statement that will be executed during reloads
nfLastRead # this node is a last read
nfFirstWrite# this node is a first write
nfFirstWrite # this node is a first write
nfHasComment # node has a comment
nfSkipFieldChecking # node skips field visable checking
TNodeFlags* = set[TNodeFlag]
TTypeFlag* = enum # keep below 32 for efficiency reasons (now: 43)
TTypeFlag* = enum # keep below 32 for efficiency reasons (now: 46)
tfVarargs, # procedure has C styled varargs
# tyArray type represeting a varargs list
tfNoSideEffect, # procedure type does not allow side effects
@@ -570,6 +582,7 @@ type
tfExplicitCallConv
tfIsConstructor
tfEffectSystemWorkaround
tfIsOutParam
TTypeFlags* = set[TTypeFlag]
@@ -620,7 +633,7 @@ const
skError* = skUnknown
var
eqTypeFlags* = {tfIterator, tfNotNil, tfVarIsPtr, tfGcSafe, tfNoSideEffect}
eqTypeFlags* = {tfIterator, tfNotNil, tfVarIsPtr, tfGcSafe, tfNoSideEffect, tfIsOutParam}
## type flags that are essential for type equality.
## This is now a variable because for emulation of version:1.0 we
## might exclude {tfGcSafe, tfNoSideEffect}.
@@ -670,10 +683,10 @@ type
mInSet, mRepr, mExit,
mSetLengthStr, mSetLengthSeq,
mIsPartOf, mAstToStr, mParallel,
mSwap, mIsNil, mArrToSeq,
mSwap, mIsNil, mArrToSeq, mOpenArrayToSeq,
mNewString, mNewStringOfCap, mParseBiggestFloat,
mMove, mWasMoved, mDestroy, mTrace,
mDefault, mUnown, mFinished, mIsolate, mAccessEnv, mReset,
mDefault, mUnown, mFinished, mIsolate, mAccessEnv, mAccessTypeField, mReset,
mArray, mOpenArray, mRange, mSet, mSeq, mVarargs,
mRef, mPtr, mVar, mDistinct, mVoid, mTuple,
mOrdinal, mIterableType,
@@ -693,19 +706,19 @@ type
mNctPut, mNctLen, mNctGet, mNctHasNext, mNctNext,
mNIntVal, mNFloatVal, mNSymbol, mNIdent, mNGetType, mNStrVal, mNSetIntVal,
mNSetFloatVal, mNSetSymbol, mNSetIdent, mNSetType, mNSetStrVal, mNLineInfo,
mNSetFloatVal, mNSetSymbol, mNSetIdent, mNSetStrVal, mNLineInfo,
mNNewNimNode, mNCopyNimNode, mNCopyNimTree, mStrToIdent, mNSigHash, mNSizeOf,
mNBindSym, mNCallSite,
mEqIdent, mEqNimrodNode, mSameNodeType, mGetImpl, mNGenSym,
mNHint, mNWarning, mNError,
mInstantiationInfo, mGetTypeInfo, mGetTypeInfoV2,
mNimvm, mIntDefine, mStrDefine, mBoolDefine, mRunnableExamples,
mNimvm, mIntDefine, mStrDefine, mBoolDefine, mGenericDefine, mRunnableExamples,
mException, mBuiltinType, mSymOwner, mUncheckedArray, mGetImplTransf,
mSymIsInstantiationOf, mNodeId, mPrivateAccess
mSymIsInstantiationOf, mNodeId, mPrivateAccess, mZeroDefault
# things that we can evaluate safely at compile time, even if not asked for it:
const
# things that we can evaluate safely at compile time, even if not asked for it:
ctfeWhitelist* = {mNone, mSucc,
mPred, mInc, mDec, mOrd, mLengthOpenArray,
mLengthStr, mLengthArray, mLengthSeq,
@@ -733,13 +746,19 @@ const
mEqStr, mLeStr, mLtStr,
mEqSet, mLeSet, mLtSet, mMulSet, mPlusSet, mMinusSet,
mConStrStr, mAppendStrCh, mAppendStrStr, mAppendSeqElem,
mInSet, mRepr}
mInSet, mRepr, mOpenArrayToSeq}
generatedMagics* = {mNone, mIsolate, mFinished, mOpenArrayToSeq}
## magics that are generated as normal procs in the backend
type
ItemId* = object
module*: int32
item*: int32
proc `$`*(x: ItemId): string =
"(module: " & $x.module & ", item: " & $x.item & ")"
proc `==`*(a, b: ItemId): bool {.inline.} =
a.item == b.item and a.module == b.module
@@ -777,6 +796,8 @@ type
ident*: PIdent
else:
sons*: TNodeSeq
when defined(nimsuggest):
endInfo*: TLineInfo
TStrTable* = object # a table[PIdent] of PSym
counter*: int
@@ -873,6 +894,8 @@ type
typ*: PType
name*: PIdent
info*: TLineInfo
when defined(nimsuggest):
endInfo*: TLineInfo
owner*: PSym
flags*: TSymFlags
ast*: PNode # syntax tree of proc, iterator, etc.:
@@ -910,9 +933,9 @@ type
allUsages*: seq[TLineInfo]
TTypeSeq* = seq[PType]
TLockLevel* = distinct int16
TTypeAttachedOp* = enum ## as usual, order is important here
attachedWasMoved,
attachedDestructor,
attachedAsgn,
attachedSink,
@@ -944,7 +967,6 @@ type
# -1 means that the size is unkwown
align*: int16 # the type's alignment requirements
paddingAtEnd*: int16 #
lockLevel*: TLockLevel # lock level as required for deadlock checking
loc*: TLoc
typeInst*: PType # for generic instantiations the tyGenericInst that led to this
# type.
@@ -1058,7 +1080,8 @@ const
nfDotSetter, nfDotField,
nfIsRef, nfIsPtr, nfPreventCg, nfLL,
nfFromTemplate, nfDefaultRefsParam,
nfExecuteOnReload, nfLastRead, nfFirstWrite}
nfExecuteOnReload, nfLastRead,
nfFirstWrite, nfSkipFieldChecking}
namePos* = 0
patternPos* = 1 # empty except for term rewriting macros
genericParamsPos* = 2
@@ -1105,21 +1128,6 @@ proc getPIdent*(a: PNode): PIdent {.inline.} =
of nkIdent: a.ident
else: nil
proc getnimblePkg*(a: PSym): PSym =
result = a
while result != nil:
case result.kind
of skModule:
result = result.owner
assert result.kind == skPackage
of skPackage:
if result.owner == nil:
break
else:
result = result.owner
else:
assert false, $result.kind
const
moduleShift = when defined(cpu32): 20 else: 24
@@ -1164,13 +1172,7 @@ when false:
assert dest.ItemId.item <= src.ItemId.item
dest = src
proc getnimblePkgId*(a: PSym): int =
let b = a.getnimblePkg
result = if b == nil: -1 else: b.id
var ggDebug* {.deprecated.}: bool ## convenience switch for trying out things
#var
# gMainPackageId*: int
proc isCallExpr*(n: PNode): bool =
result = n.kind in nkCallKinds
@@ -1237,6 +1239,31 @@ proc getDeclPragma*(n: PNode): PNode =
if result != nil:
assert result.kind == nkPragma, $(result.kind, n.kind)
proc extractPragma*(s: PSym): PNode =
## gets the pragma node of routine/type/var/let/const symbol `s`
if s.kind in routineKinds:
result = s.ast[pragmasPos]
elif s.kind in {skType, skVar, skLet, skConst}:
if s.ast != nil and s.ast.len > 0:
if s.ast[0].kind == nkPragmaExpr and s.ast[0].len > 1:
# s.ast = nkTypedef / nkPragmaExpr / [nkSym, nkPragma]
result = s.ast[0][1]
assert result == nil or result.kind == nkPragma
proc skipPragmaExpr*(n: PNode): PNode =
## if pragma expr, give the node the pragmas are applied to,
## otherwise give node itself
if n.kind == nkPragmaExpr:
result = n[0]
else:
result = n
proc setInfoRecursive*(n: PNode, info: TLineInfo) =
## set line info recursively
if n != nil:
for i in 0..<n.safeLen: setInfoRecursive(n[i], info)
n.info = info
when defined(useNodeIds):
const nodeIdToDebug* = -1 # 2322968
var gNodeId: int
@@ -1325,7 +1352,7 @@ proc newSym*(symKind: TSymKind, name: PIdent, id: ItemId, owner: PSym,
proc astdef*(s: PSym): PNode =
# get only the definition (initializer) portion of the ast
if s.ast != nil and s.ast.kind == nkIdentDefs:
if s.ast != nil and s.ast.kind in {nkIdentDefs, nkConstDef}:
s.ast[2]
else:
s.ast
@@ -1475,16 +1502,8 @@ proc newProcNode*(kind: TNodeKind, info: TLineInfo, body: PNode,
pragmas, exceptions, body]
const
UnspecifiedLockLevel* = TLockLevel(-1'i16)
MaxLockLevel* = 1000'i16
UnknownLockLevel* = TLockLevel(1001'i16)
AttachedOpToStr*: array[TTypeAttachedOp, string] = [
"=destroy", "=copy", "=sink", "=trace", "=deepcopy"]
proc `$`*(x: TLockLevel): string =
if x.ord == UnspecifiedLockLevel.ord: result = "<unspecified>"
elif x.ord == UnknownLockLevel.ord: result = "<unknown>"
else: result = $int16(x)
"=wasMoved", "=destroy", "=copy", "=sink", "=trace", "=deepcopy"]
proc `$`*(s: PSym): string =
if s != nil:
@@ -1495,7 +1514,6 @@ proc `$`*(s: PSym): string =
proc newType*(kind: TTypeKind, id: ItemId; owner: PSym): PType =
result = PType(kind: kind, owner: owner, size: defaultSize,
align: defaultAlignment, itemId: id,
lockLevel: UnspecifiedLockLevel,
uniqueId: id)
when false:
if result.itemId.module == 55 and result.itemId.item == 2:
@@ -1508,7 +1526,7 @@ proc mergeLoc(a: var TLoc, b: TLoc) =
if a.storage == low(typeof(a.storage)): a.storage = b.storage
a.flags.incl b.flags
if a.lode == nil: a.lode = b.lode
if a.r == nil: a.r = b.r
if a.r == "": a.r = b.r
proc newSons*(father: Indexable, length: int) =
setLen(father.sons, length)
@@ -1520,11 +1538,10 @@ proc assignType*(dest, src: PType) =
dest.n = src.n
dest.size = src.size
dest.align = src.align
dest.lockLevel = src.lockLevel
# this fixes 'type TLock = TSysLock':
if src.sym != nil:
if dest.sym != nil:
dest.sym.flags.incl src.sym.flags-{sfExported}
dest.sym.flags.incl src.sym.flags-{sfUsed, sfExported}
if dest.sym.annex == nil: dest.sym.annex = src.sym.annex
mergeLoc(dest.sym.loc, src.sym.loc)
else:
@@ -1678,6 +1695,8 @@ proc copyNode*(src: PNode): PNode =
of nkIdent: result.ident = src.ident
of nkStrLit..nkTripleStrLit: result.strVal = src.strVal
else: discard
when defined(nimsuggest):
result.endInfo = src.endInfo
template transitionNodeKindCommon(k: TNodeKind) =
let obj {.inject.} = n[]
@@ -1694,6 +1713,10 @@ proc transitionIntKind*(n: PNode, kind: range[nkCharLit..nkUInt64Lit]) =
transitionNodeKindCommon(kind)
n.intVal = obj.intVal
proc transitionIntToFloatKind*(n: PNode, kind: range[nkFloatLit..nkFloat128Lit]) =
transitionNodeKindCommon(kind)
n.floatVal = BiggestFloat(obj.intVal)
proc transitionNoneToSym*(n: PNode) =
transitionNodeKindCommon(nkSym)
@@ -1726,6 +1749,8 @@ template copyNodeImpl(dst, src, processSonsStmt) =
if src == nil: return
dst = newNode(src.kind)
dst.info = src.info
when defined(nimsuggest):
result.endInfo = src.endInfo
dst.typ = src.typ
dst.flags = src.flags * PersistentNodeFlags
dst.comment = src.comment
@@ -2031,6 +2056,9 @@ template detailedInfo*(sym: PSym): string =
proc isInlineIterator*(typ: PType): bool {.inline.} =
typ.kind == tyProc and tfIterator in typ.flags and typ.callConv != ccClosure
proc isIterator*(typ: PType): bool {.inline.} =
typ.kind == tyProc and tfIterator in typ.flags
proc isClosureIterator*(typ: PType): bool {.inline.} =
typ.kind == tyProc and tfIterator in typ.flags and typ.callConv == ccClosure
@@ -2101,3 +2129,13 @@ proc skipAddr*(n: PNode): PNode {.inline.} =
proc isNewStyleConcept*(n: PNode): bool {.inline.} =
assert n.kind == nkTypeClassTy
result = n[0].kind == nkEmpty
proc isOutParam*(t: PType): bool {.inline.} = tfIsOutParam in t.flags
const
nodesToIgnoreSet* = {nkNone..pred(nkSym), succ(nkSym)..nkNilLit,
nkTypeSection, nkProcDef, nkConverterDef,
nkMethodDef, nkIteratorDef, nkMacroDef, nkTemplateDef, nkLambda, nkDo,
nkFuncDef, nkConstSection, nkConstDef, nkIncludeStmt, nkImportStmt,
nkExportStmt, nkPragma, nkCommentStmt, nkBreakState,
nkTypeOfExpr, nkMixinStmt, nkBindStmt}

View File

@@ -12,9 +12,14 @@
# the data structures here are used in various places of the compiler.
import
ast, hashes, intsets, strutils, options, lineinfos, ropes, idents, rodutils,
ast, hashes, intsets, options, lineinfos, ropes, idents, rodutils,
msgs
import strutils except addf
when defined(nimPreviewSlimSystem):
import std/assertions
proc hashNode*(p: RootRef): Hash
proc treeToYaml*(conf: ConfigRef; n: PNode, indent: int = 0, maxRecDepth: int = - 1): Rope
# Convert a tree into its YAML representation; this is used by the
@@ -221,11 +226,10 @@ 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
## ignore, see compiler / evaltempl.nim, snippet:
##
## .. code-block:: nim
##
## ```
## result.add newIdentNode(getIdent(c.ic, x.name.s & "\`gensym" & $x.id),
## if c.instLines: actual.info else: templ.info)
## ```
for i in 1..<list.len:
let it = list[i].sym
if it.name.id == ident.id or
@@ -253,7 +257,7 @@ proc makeYamlString*(s: string): Rope =
# this could trigger InternalError(111). See the ropes module for
# further information.
const MaxLineLength = 64
result = nil
result = ""
var res = "\""
for i in 0..<s.len:
if (i + 1) mod MaxLineLength == 0:
@@ -269,9 +273,9 @@ proc flagsToStr[T](flags: set[T]): Rope =
if flags == {}:
result = rope("[]")
else:
result = nil
result = ""
for x in items(flags):
if result != nil: result.add(", ")
if result != "": result.add(", ")
result.add(makeYamlString($x))
result = "[" & result & "]"
@@ -326,7 +330,7 @@ proc typeToYamlAux(conf: ConfigRef; n: PType, marker: var IntSet, indent: int,
sonsRope = rope("null")
elif containsOrIncl(marker, n.id):
sonsRope = "\"$1 @$2\"" % [rope($n.kind), rope(
strutils.toHex(cast[ByteAddress](n), sizeof(n) * 2))]
strutils.toHex(cast[int](n), sizeof(n) * 2))]
else:
if n.len > 0:
sonsRope = rope("[")
@@ -812,16 +816,21 @@ type
name*: PIdent
proc nextIdentIter*(ti: var TIdentIter, tab: TStrTable): PSym =
# hot spots
var h = ti.h and high(tab.data)
var start = h
result = tab.data[h]
while result != nil:
if result.name.id == ti.name.id: break
var p {.cursor.} = tab.data[h]
while p != nil:
if p.name.id == ti.name.id: break
h = nextTry(h, high(tab.data))
if h == start:
result = nil
p = nil
break
result = tab.data[h]
p = tab.data[h]
if p != nil:
result = p # increase the count
else:
result = nil
ti.h = nextTry(h, high(tab.data))
proc initIdentIter*(ti: var TIdentIter, tab: TStrTable, s: PIdent): PSym =

View File

@@ -0,0 +1,25 @@
import pragmas, options, ast, trees
proc pushBackendOption(optionsStack: var seq[TOptions], options: var TOptions) =
optionsStack.add options
proc popBackendOption(optionsStack: var seq[TOptions], options: var TOptions) =
options = optionsStack[^1]
optionsStack.setLen(optionsStack.len-1)
proc processPushBackendOption*(optionsStack: var seq[TOptions], options: var TOptions,
n: PNode, start: int) =
pushBackendOption(optionsStack, options)
for i in start..<n.len:
let it = n[i]
if it.kind in nkPragmaCallKinds and it.len == 2 and it[1].kind == nkIntLit:
let sw = whichPragma(it[0])
let opts = pragmaToOptions(sw)
if opts != {}:
if it[1].intVal != 0:
options.incl opts
else:
options.excl opts
template processPopBackendOption*(optionsStack: var seq[TOptions], options: var TOptions) =
popBackendOption(optionsStack, options)

View File

@@ -10,6 +10,9 @@
# this unit handles Nim sets; it implements bit sets
# the code here should be reused in the Nim standard library
when defined(nimPreviewSlimSystem):
import std/assertions
type
ElemType = byte
TBitSet* = seq[ElemType] # we use byte here to avoid issues with
@@ -23,53 +26,40 @@ const
template modElemSize(arg: untyped): untyped = arg and 7
template divElemSize(arg: untyped): untyped = arg shr 3
proc bitSetInit*(b: var TBitSet, length: int)
proc bitSetUnion*(x: var TBitSet, y: TBitSet)
proc bitSetDiff*(x: var TBitSet, y: TBitSet)
proc bitSetSymDiff*(x: var TBitSet, y: TBitSet)
proc bitSetIntersect*(x: var TBitSet, y: TBitSet)
proc bitSetIncl*(x: var TBitSet, elem: BiggestInt)
proc bitSetExcl*(x: var TBitSet, elem: BiggestInt)
proc bitSetIn*(x: TBitSet, e: BiggestInt): bool
proc bitSetEquals*(x, y: TBitSet): bool
proc bitSetContains*(x, y: TBitSet): bool
proc bitSetCard*(x: TBitSet): BiggestInt
# implementation
proc bitSetIn(x: TBitSet, e: BiggestInt): bool =
proc bitSetIn*(x: TBitSet, e: BiggestInt): bool =
result = (x[int(e.divElemSize)] and (One shl e.modElemSize)) != Zero
proc bitSetIncl(x: var TBitSet, elem: BiggestInt) =
proc bitSetIncl*(x: var TBitSet, elem: BiggestInt) =
assert(elem >= 0)
x[int(elem.divElemSize)] = x[int(elem.divElemSize)] or
(One shl elem.modElemSize)
proc bitSetExcl(x: var TBitSet, elem: BiggestInt) =
proc bitSetExcl*(x: var TBitSet, elem: BiggestInt) =
x[int(elem.divElemSize)] = x[int(elem.divElemSize)] and
not(One shl elem.modElemSize)
proc bitSetInit(b: var TBitSet, length: int) =
proc bitSetInit*(b: var TBitSet, length: int) =
newSeq(b, length)
proc bitSetUnion(x: var TBitSet, y: TBitSet) =
proc bitSetUnion*(x: var TBitSet, y: TBitSet) =
for i in 0..high(x): x[i] = x[i] or y[i]
proc bitSetDiff(x: var TBitSet, y: TBitSet) =
proc bitSetDiff*(x: var TBitSet, y: TBitSet) =
for i in 0..high(x): x[i] = x[i] and not y[i]
proc bitSetSymDiff(x: var TBitSet, y: TBitSet) =
proc bitSetSymDiff*(x: var TBitSet, y: TBitSet) =
for i in 0..high(x): x[i] = x[i] xor y[i]
proc bitSetIntersect(x: var TBitSet, y: TBitSet) =
proc bitSetIntersect*(x: var TBitSet, y: TBitSet) =
for i in 0..high(x): x[i] = x[i] and y[i]
proc bitSetEquals(x, y: TBitSet): bool =
proc bitSetEquals*(x, y: TBitSet): bool =
for i in 0..high(x):
if x[i] != y[i]:
return false
result = true
proc bitSetContains(x, y: TBitSet): bool =
proc bitSetContains*(x, y: TBitSet): bool =
for i in 0..high(x):
if (x[i] and not y[i]) != Zero:
return false
@@ -96,6 +86,6 @@ const populationCount: array[uint8, uint8] = block:
arr
proc bitSetCard(x: TBitSet): BiggestInt =
proc bitSetCard*(x: TBitSet): BiggestInt =
for it in x:
result.inc int(populationCount[it])

View File

@@ -10,6 +10,9 @@
## BTree implementation with few features, but good enough for the
## Nim compiler's needs.
when defined(nimPreviewSlimSystem):
import std/assertions
const
M = 512 # max children per B-tree node = M-1
# (must be even and greater than 2)
@@ -65,7 +68,10 @@ proc copyHalf[Key, Val](h, result: Node[Key, Val]) =
result.links[j] = h.links[Mhalf + j]
else:
for j in 0..<Mhalf:
shallowCopy(result.vals[j], h.vals[Mhalf + j])
when defined(gcArc) or defined(gcOrc):
result.vals[j] = move h.vals[Mhalf + j]
else:
shallowCopy(result.vals[j], h.vals[Mhalf + j])
proc split[Key, Val](h: Node[Key, Val]): Node[Key, Val] =
## split node in half
@@ -85,7 +91,10 @@ proc insert[Key, Val](h: Node[Key, Val], key: Key, val: Val): Node[Key, Val] =
if less(key, h.keys[j]): break
inc j
for i in countdown(h.entries, j+1):
shallowCopy(h.vals[i], h.vals[i-1])
when defined(gcArc) or defined(gcOrc):
h.vals[i] = move h.vals[i-1]
else:
shallowCopy(h.vals[i], h.vals[i-1])
h.vals[j] = val
else:
var newLink: Node[Key, Val] = nil

View File

@@ -14,14 +14,15 @@ proc canRaiseDisp(p: BProc; n: PNode): bool =
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):
(n.kind == nkSym and sfSystemModule in getModule(n.sym).flags and
sfSystemRaisesDefect notin 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 preventNrvo(p: BProc; dest, le, ri: PNode): bool =
proc locationEscapes(p: BProc; le: PNode; inTryStmt: bool): bool =
var n = le
while true:
@@ -54,6 +55,11 @@ proc preventNrvo(p: BProc; le, ri: PNode): bool =
if canRaise(ri[0]) and
locationEscapes(p, le, p.nestedTryStmts.len > 0):
message(p.config, le.info, warnObservableStores, $le)
# bug #19613 prevent dangerous aliasing too:
if dest != nil and dest != le:
for i in 1..<ri.len:
let r = ri[i]
if isPartOf(dest, r) != arNo: return true
proc hasNoInit(call: PNode): bool {.inline.} =
result = call[0].kind == nkSym and sfNoInit in call[0].sym.flags
@@ -72,32 +78,32 @@ 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
var pl = callee & "(" & params
# getUniqueType() is too expensive here:
var typ = skipTypes(ri[0].typ, abstractInst)
if typ[0] != nil:
if isInvalidReturnType(p.config, typ[0]):
if params != nil: pl.add(~", ")
if isInvalidReturnType(p.config, typ):
if params.len != 0: pl.add(", ")
# beware of 'result = p(result)'. We may need to allocate a temporary:
if d.k in {locTemp, locNone} or not preventNrvo(p, le, ri):
if d.k in {locTemp, locNone} or not preventNrvo(p, d.lode, le, ri):
# Great, we can use 'd':
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)"
pl.add(addrLoc(p.config, d))
pl.add(~");$n")
pl.add(");\n")
line(p, cpsStmts, pl)
else:
var tmp: TLoc
getTemp(p, typ[0], tmp, needsInit=true)
pl.add(addrLoc(p.config, tmp))
pl.add(~");$n")
pl.add(");\n")
line(p, cpsStmts, pl)
genAssignment(p, d, tmp, {}) # no need for deep copying
if canRaise: raiseExit(p)
else:
pl.add(~")")
pl.add(")")
if p.module.compileToCpp:
if lfSingleUse in d.flags:
# do not generate spurious temporaries for C++! For C we're better off
@@ -135,7 +141,7 @@ proc fixupCall(p: BProc, le, ri: PNode, d: var TLoc,
if canRaise: raiseExit(p)
genAssignment(p, d, tmp, {})
else:
pl.add(~");$n")
pl.add(");\n")
line(p, cpsStmts, pl)
if canRaise: raiseExit(p)
@@ -150,7 +156,7 @@ proc reifiedOpenArray(n: PNode): bool {.inline.} =
else:
result = true
proc genOpenArraySlice(p: BProc; q: PNode; formalType, destType: PType): (Rope, Rope) =
proc genOpenArraySlice(p: BProc; q: PNode; formalType, destType: PType; prepareForMutation = false): (Rope, Rope) =
var a, b, c: TLoc
initLocExpr(p, q[1], a)
initLocExpr(p, q[2], b)
@@ -158,6 +164,8 @@ proc genOpenArraySlice(p: BProc; q: PNode; formalType, destType: PType): (Rope,
# but first produce the required index checks:
if optBoundsCheck in p.options:
genBoundsCheck(p, a, b, c)
if prepareForMutation:
linefmt(p, cpsStmts, "#nimPrepareStrMutationV2($1);$n", [byRefLoc(p, a)])
let ty = skipTypes(a.t, abstractVar+{tyPtr})
let dest = getTypeDesc(p.module, destType)
let lengthExpr = "($1)-($2)+1" % [rdLoc(c), rdLoc(b)]
@@ -168,8 +176,10 @@ proc genOpenArraySlice(p: BProc; q: PNode; formalType, destType: PType): (Rope,
result = ("($3*)(($1)+($2))" % [rdLoc(a), rdLoc(b), dest],
lengthExpr)
else:
var lit = newRopeAppender()
intLiteral(first, lit)
result = ("($4*)($1)+(($2)-($3))" %
[rdLoc(a), rdLoc(b), intLiteral(first), dest],
[rdLoc(a), rdLoc(b), lit, dest],
lengthExpr)
of tyOpenArray, tyVarargs:
if reifiedOpenArray(q[1]):
@@ -187,15 +197,17 @@ proc genOpenArraySlice(p: BProc; q: PNode; formalType, destType: PType): (Rope,
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],
result = ("(($5) ? (($4*)(*$1)$3+($2)) : NIM_NIL)" %
[rdLoc(a), rdLoc(b), dataField(p), dest, dataFieldAccessor(p, "*" & rdLoc(a))],
lengthExpr)
else:
result = ("($4*)$1$3+($2)" % [rdLoc(a), rdLoc(b), dataField(p), dest],
result = ("(($5) ? (($4*)$1$3+($2)) : NIM_NIL)" %
[rdLoc(a), rdLoc(b), dataField(p), dest, dataFieldAccessor(p, rdLoc(a))],
lengthExpr)
else:
internalError(p.config, "openArrayLoc: " & typeToString(a.t))
proc openArrayLoc(p: BProc, formalType: PType, n: PNode): Rope =
proc openArrayLoc(p: BProc, formalType: PType, n: PNode; result: var Rope) =
var q = skipConv(n)
var skipped = false
while q.kind == nkStmtListExpr and q.len > 0:
@@ -210,19 +222,19 @@ proc openArrayLoc(p: BProc, formalType: PType, n: PNode): Rope =
genStmts(p, q[i])
q = q.lastSon
let (x, y) = genOpenArraySlice(p, q, formalType, n.typ[0])
result = x & ", " & y
result.add x & ", " & y
else:
var a: TLoc
initLocExpr(p, if n.kind == nkHiddenStdConv: n[1] else: n, a)
case skipTypes(a.t, abstractVar).kind
case skipTypes(a.t, abstractVar+{tyStatic}).kind
of tyOpenArray, tyVarargs:
if reifiedOpenArray(n):
if a.t.kind in {tyVar, tyLent}:
result = "$1->Field0, $1->Field1" % [rdLoc(a)]
result.add "$1->Field0, $1->Field1" % [rdLoc(a)]
else:
result = "$1.Field0, $1.Field1" % [rdLoc(a)]
result.add "$1.Field0, $1.Field1" % [rdLoc(a)]
else:
result = "$1, $1Len_0" % [rdLoc(a)]
result.add "$1, $1Len_0" % [rdLoc(a)]
of tyString, tySequence:
let ntyp = skipTypes(n.typ, abstractInst)
if formalType.skipTypes(abstractInst).kind in {tyVar} and ntyp.kind == tyString and
@@ -231,19 +243,24 @@ proc openArrayLoc(p: BProc, formalType: PType, n: PNode): Rope =
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)]
result.add "($4) ? ((*$1)$3) : NIM_NIL, $2" %
[a.rdLoc, lenExpr(p, t), dataField(p),
dataFieldAccessor(p, "*" & a.rdLoc)]
else:
result = "$1$3, $2" % [a.rdLoc, lenExpr(p, a), dataField(p)]
result.add "($4) ? ($1$3) : NIM_NIL, $2" %
[a.rdLoc, lenExpr(p, a), dataField(p), dataFieldAccessor(p, a.rdLoc)]
of tyArray:
result = "$1, $2" % [rdLoc(a), rope(lengthOrd(p.config, a.t))]
result.add "$1, $2" % [rdLoc(a), rope(lengthOrd(p.config, a.t))]
of tyPtr, tyRef:
case lastSon(a.t).kind
of tyString, tySequence:
var t: TLoc
t.r = "(*$1)" % [a.rdLoc]
result = "(*$1)$3, $2" % [a.rdLoc, lenExpr(p, t), dataField(p)]
result.add "($4) ? ((*$1)$3) : NIM_NIL, $2" %
[a.rdLoc, lenExpr(p, t), dataField(p),
dataFieldAccessor(p, "*" & a.rdLoc)]
of tyArray:
result = "$1, $2" % [rdLoc(a), rope(lengthOrd(p.config, lastSon(a.t)))]
result.add "$1, $2" % [rdLoc(a), rope(lengthOrd(p.config, lastSon(a.t)))]
else:
internalError(p.config, "openArrayLoc: " & typeToString(a.t))
else: internalError(p.config, "openArrayLoc: " & typeToString(a.t))
@@ -263,24 +280,24 @@ proc literalsNeedsTmp(p: BProc, a: TLoc): TLoc =
getTemp(p, a.lode.typ, result, needsInit=false)
genAssignment(p, result, a, {})
proc genArgStringToCString(p: BProc, n: PNode, needsTmp: bool): Rope {.inline.} =
proc genArgStringToCString(p: BProc, n: PNode; result: var Rope; needsTmp: bool) {.inline.} =
var a: TLoc
initLocExpr(p, n[0], a)
ropecg(p.module, "#nimToCStringConv($1)", [withTmpIfNeeded(p, a, needsTmp).rdLoc])
appcg(p.module, result, "#nimToCStringConv($1)", [withTmpIfNeeded(p, a, needsTmp).rdLoc])
proc genArg(p: BProc, n: PNode, param: PSym; call: PNode, needsTmp = false): Rope =
proc genArg(p: BProc, n: PNode, param: PSym; call: PNode; result: var Rope; needsTmp = false) =
var a: TLoc
if n.kind == nkStringToCString:
result = genArgStringToCString(p, n, needsTmp)
genArgStringToCString(p, n, result, needsTmp)
elif skipTypes(param.typ, abstractVar).kind in {tyOpenArray, tyVarargs}:
var n = if n.kind != nkHiddenAddr: n else: n[0]
result = openArrayLoc(p, param.typ, n)
openArrayLoc(p, param.typ, n, result)
elif ccgIntroducedPtr(p.config, param, call[0].typ[0]):
initLocExpr(p, n, a)
if n.kind in {nkCharLit..nkNilLit}:
result = addrLoc(p.config, literalsNeedsTmp(p, a))
addAddrLoc(p.config, literalsNeedsTmp(p, a), result)
else:
result = addrLoc(p.config, withTmpIfNeeded(p, a, needsTmp))
addAddrLoc(p.config, withTmpIfNeeded(p, a, needsTmp), result)
elif p.module.compileToCpp and param.typ.kind in {tyVar} and
n.kind == nkHiddenAddr:
initLocExprSingleUse(p, n[0], a)
@@ -290,23 +307,23 @@ proc genArg(p: BProc, n: PNode, param: PSym; call: PNode, needsTmp = false): Rop
if callee.kind == nkSym and
{sfImportc, sfInfixCall, sfCompilerProc} * callee.sym.flags == {sfImportc} and
{lfHeader, lfNoDecl} * callee.sym.loc.flags != {}:
result = addrLoc(p.config, a)
addAddrLoc(p.config, a, result)
else:
result = rdLoc(a)
addRdLoc(a, result)
else:
initLocExprSingleUse(p, n, a)
result = rdLoc(withTmpIfNeeded(p, a, needsTmp))
addRdLoc(withTmpIfNeeded(p, a, needsTmp), result)
#assert result != nil
proc genArgNoParam(p: BProc, n: PNode, needsTmp = false): Rope =
proc genArgNoParam(p: BProc, n: PNode; result: var Rope; needsTmp = false) =
var a: TLoc
if n.kind == nkStringToCString:
result = genArgStringToCString(p, n, needsTmp)
genArgStringToCString(p, n, result, needsTmp)
else:
initLocExprSingleUse(p, n, a)
result = rdLoc(withTmpIfNeeded(p, a, needsTmp))
addRdLoc(withTmpIfNeeded(p, a, needsTmp), result)
from dfa import aliases, AliasKind
import aliasanalysis
proc potentialAlias(n: PNode, potentialWrites: seq[PNode]): bool =
for p in potentialWrites:
@@ -328,7 +345,7 @@ proc getPotentialWrites(n: PNode; mutate: bool; result: var seq[PNode]) =
of nkLiterals, nkIdent, nkFormalParams: discard
of nkSym:
if mutate: result.add n
of nkAsgn, nkFastAsgn:
of nkAsgn, nkFastAsgn, nkSinkAsgn:
getPotentialWrites(n[0], true, result)
getPotentialWrites(n[1], mutate, result)
of nkAddr, nkHiddenAddr:
@@ -360,7 +377,7 @@ proc getPotentialReads(n: PNode; result: var seq[PNode]) =
for s in n:
getPotentialReads(s, result)
proc genParams(p: BProc, ri: PNode, typ: PType): Rope =
proc genParams(p: BProc, ri: PNode, typ: PType; result: var Rope) =
# We must generate temporaries in cases like #14396
# to keep the strict Left-To-Right evaluation
var needTmp = newSeq[bool](ri.len - 1)
@@ -376,20 +393,25 @@ proc genParams(p: BProc, ri: PNode, typ: PType): Rope =
if not needTmp[i - 1]:
needTmp[i - 1] = potentialAlias(n, potentialWrites)
getPotentialWrites(ri[i], false, potentialWrites)
if ri[i].kind == nkHiddenAddr:
# Optimization: don't use a temp, if we would only take the adress anyway
if ri[i].kind in {nkHiddenAddr, nkAddr}:
# Optimization: don't use a temp, if we would only take the address anyway
needTmp[i - 1] = false
var oldLen = result.len
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]))
if oldLen != result.len:
result.add(", ")
oldLen = result.len
genArg(p, ri[i], paramType.sym, ri, result, needTmp[i-1])
else:
if result != nil: result.add(~", ")
result.add(genArgNoParam(p, ri[i], needTmp[i-1]))
if oldLen != result.len:
result.add(", ")
oldLen = result.len
genArgNoParam(p, ri[i], result, needTmp[i-1])
proc addActualSuffixForHCR(res: var Rope, module: PSym, sym: PSym) =
if sym.flags * {sfImportc, sfNonReloadable} == {} and sym.loc.k == locProc and
@@ -405,7 +427,8 @@ proc genPrefixCall(p: BProc, le, ri: PNode, d: var TLoc) =
assert(typ.kind == tyProc)
assert(typ.len == typ.n.len)
var params = genParams(p, ri, typ)
var params = newRopeAppender()
genParams(p, ri, typ, params)
var callee = rdLoc(op)
if p.hcrOn and ri[0].kind == nkSym:
@@ -415,7 +438,7 @@ proc genPrefixCall(p: BProc, le, ri: PNode, d: var TLoc) =
proc genClosureCall(p: BProc, le, ri: PNode, d: var TLoc) =
proc addComma(r: Rope): Rope =
if r == nil: r else: r & ~", "
if r.len == 0: 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
@@ -428,7 +451,8 @@ proc genClosureCall(p: BProc, le, ri: PNode, d: var TLoc) =
assert(typ.kind == tyProc)
assert(typ.len == typ.n.len)
var pl = genParams(p, ri, typ)
var pl = newRopeAppender()
genParams(p, ri, typ, pl)
template genCallPattern {.dirty.} =
if tfIterator in typ.flags:
@@ -439,10 +463,10 @@ proc genClosureCall(p: BProc, le, ri: PNode, d: var TLoc) =
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(~", ")
if isInvalidReturnType(p.config, typ):
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 preventNrvo(p, le, ri):
if d.k in {locTemp, locNone} or not preventNrvo(p, d.lode, le, ri):
# Great, we can use 'd':
if d.k == locNone:
getTemp(p, typ[0], d, needsInit=true)
@@ -451,6 +475,7 @@ proc genClosureCall(p: BProc, le, ri: PNode, d: var TLoc) =
discard "resetLoc(p, d)"
pl.add(addrLoc(p.config, d))
genCallPattern()
if canRaise: raiseExit(p)
else:
var tmp: TLoc
getTemp(p, typ[0], tmp, needsInit=true)
@@ -486,24 +511,30 @@ proc genClosureCall(p: BProc, le, ri: PNode, d: var TLoc) =
genCallPattern()
if canRaise: raiseExit(p)
proc genOtherArg(p: BProc; ri: PNode; i: int; typ: PType): Rope =
proc genOtherArg(p: BProc; ri: PNode; i: int; typ: PType; result: var Rope;
argsCounter: var int) =
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[i]
assert(paramType.kind == nkSym)
if paramType.typ.isCompileTimeOnly:
result = nil
discard
elif typ[i].kind in {tyVar} and ri[i].kind == nkHiddenAddr:
result = genArgNoParam(p, ri[i][0])
if argsCounter > 0: result.add ", "
genArgNoParam(p, ri[i][0], result)
inc argsCounter
else:
result = genArgNoParam(p, ri[i]) #, typ.n[i].sym)
if argsCounter > 0: result.add ", "
genArgNoParam(p, ri[i], result) #, typ.n[i].sym)
inc argsCounter
else:
if tfVarargs notin typ.flags:
localError(p.config, ri.info, "wrong argument count")
result = nil
else:
result = genArgNoParam(p, ri[i])
if argsCounter > 0: result.add ", "
genArgNoParam(p, ri[i], result)
inc argsCounter
discard """
Dot call syntax in C++
@@ -560,7 +591,7 @@ proc skipAddrDeref(node: PNode): PNode =
else:
result = node
proc genThisArg(p: BProc; ri: PNode; i: int; typ: PType): Rope =
proc genThisArg(p: BProc; ri: PNode; i: int; typ: PType; result: var 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.
@@ -574,75 +605,72 @@ proc genThisArg(p: BProc; ri: PNode; i: int; typ: PType): Rope =
if t.kind in {tyVar}:
let x = if ri.kind == nkHiddenAddr: ri[0] else: ri
if x.typ.kind == tyPtr:
result = genArgNoParam(p, x)
genArgNoParam(p, x, result)
result.add("->")
elif x.kind in {nkHiddenDeref, nkDerefExpr} and x[0].typ.kind == tyPtr:
result = genArgNoParam(p, x[0])
genArgNoParam(p, x[0], result)
result.add("->")
else:
result = genArgNoParam(p, x)
genArgNoParam(p, x, result)
result.add(".")
elif t.kind == tyPtr:
if ri.kind in {nkAddr, nkHiddenAddr}:
result = genArgNoParam(p, ri[0])
genArgNoParam(p, ri[0], result)
result.add(".")
else:
result = genArgNoParam(p, ri)
genArgNoParam(p, ri, result)
result.add("->")
else:
ri = skipAddrDeref(ri)
if ri.kind in {nkAddr, nkHiddenAddr}: ri = ri[0]
result = genArgNoParam(p, ri) #, typ.n[i].sym)
genArgNoParam(p, ri, result) #, typ.n[i].sym)
result.add(".")
proc genPatternCall(p: BProc; ri: PNode; pat: string; typ: PType): Rope =
proc genPatternCall(p: BProc; ri: PNode; pat: string; typ: PType; result: var Rope) =
var i = 0
var j = 1
while i < pat.len:
case pat[i]
of '@':
var first = true
var argsCounter = 0
for k in j..<ri.len:
let arg = genOtherArg(p, ri, k, typ)
if arg.len > 0:
if not first:
result.add(~", ")
first = false
result.add arg
genOtherArg(p, ri, k, typ, result, argsCounter)
inc i
of '#':
if i+1 < pat.len and pat[i+1] in {'+', '@'}:
let ri = ri[j]
if ri.kind in nkCallKinds:
let typ = skipTypes(ri[0].typ, abstractInst)
if pat[i+1] == '+': result.add genArgNoParam(p, ri[0])
result.add(~"(")
if pat[i+1] == '+': genArgNoParam(p, ri[0], result)
result.add("(")
if 1 < ri.len:
result.add genOtherArg(p, ri, 1, typ)
var argsCounterB = 0
genOtherArg(p, ri, 1, typ, result, argsCounterB)
for k in j+1..<ri.len:
result.add(~", ")
result.add genOtherArg(p, ri, k, typ)
result.add(~")")
var argsCounterB = 0
genOtherArg(p, ri, k, typ, result, argsCounterB)
result.add(")")
else:
localError(p.config, ri.info, "call expression expected for C++ pattern")
inc i
elif i+1 < pat.len and pat[i+1] == '.':
result.add genThisArg(p, ri, j, typ)
genThisArg(p, ri, j, typ, result)
inc i
elif i+1 < pat.len and pat[i+1] == '[':
var arg = ri[j].skipAddrDeref
while arg.kind in {nkAddr, nkHiddenAddr, nkObjDownConv}: arg = arg[0]
result.add genArgNoParam(p, arg)
genArgNoParam(p, arg, result)
#result.add debugTree(arg, 0, 10)
else:
result.add genOtherArg(p, ri, j, typ)
var argsCounter = 0
genOtherArg(p, ri, j, typ, result, argsCounter)
inc j
inc i
of '\'':
var idx, stars: int
if scanCppGenericSlot(pat, i, idx, stars):
var t = resolveStarsInCppType(typ, idx, stars)
if t == nil: result.add(~"void")
if t == nil: result.add("void")
else: result.add(getTypeDesc(p.module, t))
else:
let start = i
@@ -660,10 +688,11 @@ proc genInfixCall(p: BProc, le, ri: PNode, d: var TLoc) =
assert(typ.kind == tyProc)
assert(typ.len == typ.n.len)
# don't call '$' here for efficiency:
let pat = ri[0].sym.loc.r.data
let pat = $ri[0].sym.loc.r
internalAssert p.config, pat.len > 0
if pat.contains({'#', '(', '@', '\''}):
var pl = genPatternCall(p, ri, pat, typ)
var pl = newRopeAppender()
genPatternCall(p, ri, pat, typ, pl)
# simpler version of 'fixupCall' that works with the pl+params combination:
var typ = skipTypes(ri[0].typ, abstractInst)
if typ[0] != nil:
@@ -682,80 +711,79 @@ proc genInfixCall(p: BProc, le, ri: PNode, d: var TLoc) =
list.r = pl
genAssignment(p, d, list, {}) # no need for deep copying
else:
pl.add(~";$n")
pl.add(";\n")
line(p, cpsStmts, pl)
else:
var pl: Rope = nil
#var param = typ.n[1].sym
var pl = newRopeAppender()
var argsCounter = 0
if 1 < ri.len:
pl.add(genThisArg(p, ri, 1, typ))
genThisArg(p, ri, 1, typ, pl)
pl.add(op.r)
var params: Rope
var params = newRopeAppender()
for i in 2..<ri.len:
if params != nil: params.add(~", ")
assert(typ.len == typ.n.len)
params.add(genOtherArg(p, ri, i, typ))
genOtherArg(p, ri, i, typ, params, argsCounter)
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[0], op)
var pl = ~"["
var pl = "["
# getUniqueType() is too expensive here:
var typ = skipTypes(ri[0].typ, abstractInst)
assert(typ.kind == tyProc)
assert(typ.len == typ.n.len)
# don't call '$' here for efficiency:
let pat = ri[0].sym.loc.r.data
let pat = $ri[0].sym.loc.r
internalAssert p.config, pat.len > 0
var start = 3
if ' ' in pat:
start = 1
pl.add(op.r)
if ri.len > 1:
pl.add(~": ")
pl.add(genArg(p, ri[1], typ.n[1].sym, ri))
pl.add(": ")
genArg(p, ri[1], typ.n[1].sym, ri, pl)
start = 2
else:
if ri.len > 1:
pl.add(genArg(p, ri[1], typ.n[1].sym, ri))
pl.add(~" ")
genArg(p, ri[1], typ.n[1].sym, ri, pl)
pl.add(" ")
pl.add(op.r)
if ri.len > 2:
pl.add(~": ")
pl.add(genArg(p, ri[2], typ.n[2].sym, ri))
pl.add(": ")
genArg(p, ri[2], typ.n[2].sym, ri, pl)
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[i].kind == nkSym)
var param = typ.n[i].sym
pl.add(~" ")
pl.add(" ")
pl.add(param.name.s)
pl.add(~": ")
pl.add(genArg(p, ri[i], param, ri))
pl.add(": ")
genArg(p, ri[i], param, ri, pl)
if typ[0] != nil:
if isInvalidReturnType(p.config, typ[0]):
if ri.len > 1: pl.add(~" ")
if isInvalidReturnType(p.config, typ):
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[0], d, needsInit=true)
pl.add(~"Result: ")
pl.add("Result: ")
pl.add(addrLoc(p.config, d))
pl.add(~"];$n")
pl.add("];\n")
line(p, cpsStmts, pl)
else:
var tmp: TLoc
getTemp(p, typ[0], tmp, needsInit=true)
pl.add(addrLoc(p.config, tmp))
pl.add(~"];$n")
pl.add("];\n")
line(p, cpsStmts, pl)
genAssignment(p, d, tmp, {}) # no need for deep copying
else:
pl.add(~"]")
pl.add("]")
if d.k == locNone: getTemp(p, typ[0], d)
assert(d.t != nil) # generate an assignment to d:
var list: TLoc
@@ -763,7 +791,7 @@ proc genNamedParamCall(p: BProc, ri: PNode, d: var TLoc) =
list.r = pl
genAssignment(p, d, list, {}) # no need for deep copying
else:
pl.add(~"];$n")
pl.add("];\n")
line(p, cpsStmts, pl)
proc notYetAlive(n: PNode): bool {.inline.} =

File diff suppressed because it is too large Load Diff

View File

@@ -21,7 +21,7 @@ template detectVersion(field, corename) =
if core == nil or core.kind != skConst:
m.g.field = 1
else:
m.g.field = toInt(ast.getInt(core.ast))
m.g.field = toInt(ast.getInt(core.astdef))
result = m.g.field
proc detectStrVersion(m: BModule): int =
@@ -32,82 +32,87 @@ proc detectSeqVersion(m: BModule): int =
# ----- Version 1: GC'ed strings and seqs --------------------------------
proc genStringLiteralDataOnlyV1(m: BModule, s: string): Rope =
discard cgsym(m, "TGenericSeq")
result = getTempName(m)
m.s[cfsData].addf("STRING_LITERAL($1, $2, $3);$n",
[result, makeCString(s), rope(s.len)])
proc genStringLiteralDataOnlyV1(m: BModule, s: string; result: var Rope) =
cgsym(m, "TGenericSeq")
let tmp = getTempName(m)
result.add tmp
m.s[cfsStrData].addf("STRING_LITERAL($1, $2, $3);$n",
[tmp, makeCString(s), rope(s.len)])
proc genStringLiteralV1(m: BModule; n: PNode): Rope =
proc genStringLiteralV1(m: BModule; n: PNode; result: var Rope) =
if s.isNil:
result = ropecg(m, "((#NimStringDesc*) NIM_NIL)", [])
appcg(m, result, "((#NimStringDesc*) NIM_NIL)", [])
else:
let id = nodeTableTestOrSet(m.dataCache, n, m.labels)
if id == m.labels:
# string literal not found in the cache:
result = ropecg(m, "((#NimStringDesc*) &$1)",
[genStringLiteralDataOnlyV1(m, n.strVal)])
appcg(m, result, "((#NimStringDesc*) &", [])
genStringLiteralDataOnlyV1(m, n.strVal, result)
result.add ")"
else:
result = ropecg(m, "((#NimStringDesc*) &$1$2)",
appcg(m, result, "((#NimStringDesc*) &$1$2)",
[m.tmpBase, id])
# ------ Version 2: destructor based strings and seqs -----------------------
proc genStringLiteralDataOnlyV2(m: BModule, s: string; result: Rope; isConst: bool) =
m.s[cfsData].addf("static $4 struct {$n" &
m.s[cfsStrData].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; isConst: bool): Rope =
proc genStringLiteralV2(m: BModule; n: PNode; isConst: bool; result: var Rope) =
let id = nodeTableTestOrSet(m.dataCache, n, m.labels)
if id == m.labels:
let pureLit = getTempName(m)
genStringLiteralDataOnlyV2(m, n.strVal, pureLit, isConst)
result = getTempName(m)
discard cgsym(m, "NimStrPayload")
discard cgsym(m, "NimStringV2")
let tmp = getTempName(m)
result.add tmp
cgsym(m, "NimStrPayload")
cgsym(m, "NimStringV2")
# string literal not found in the cache:
m.s[cfsData].addf("static $4 NimStringV2 $1 = {$2, (NimStrPayload*)&$3};$n",
[result, rope(n.strVal.len), pureLit, rope(if isConst: "const" else: "")])
m.s[cfsStrData].addf("static $4 NimStringV2 $1 = {$2, (NimStrPayload*)&$3};$n",
[tmp, rope(n.strVal.len), pureLit, rope(if isConst: "const" else: "")])
else:
result = getTempName(m)
m.s[cfsData].addf("static $4 NimStringV2 $1 = {$2, (NimStrPayload*)&$3};$n",
[result, rope(n.strVal.len), m.tmpBase & rope(id),
let tmp = getTempName(m)
result.add tmp
m.s[cfsStrData].addf("static $4 NimStringV2 $1 = {$2, (NimStrPayload*)&$3};$n",
[tmp, rope(n.strVal.len), m.tmpBase & rope(id),
rope(if isConst: "const" else: "")])
proc genStringLiteralV2Const(m: BModule; n: PNode; isConst: bool): Rope =
proc genStringLiteralV2Const(m: BModule; n: PNode; isConst: bool; result: var Rope) =
let id = nodeTableTestOrSet(m.dataCache, n, m.labels)
var pureLit: Rope
if id == m.labels:
pureLit = getTempName(m)
discard cgsym(m, "NimStrPayload")
discard cgsym(m, "NimStringV2")
cgsym(m, "NimStrPayload")
cgsym(m, "NimStringV2")
# string literal not found in the cache:
genStringLiteralDataOnlyV2(m, n.strVal, pureLit, isConst)
else:
pureLit = m.tmpBase & rope(id)
result = "{$1, (NimStrPayload*)&$2}" % [rope(n.strVal.len), pureLit]
result.addf "{$1, (NimStrPayload*)&$2}", [rope(n.strVal.len), pureLit]
# ------ Version selector ---------------------------------------------------
proc genStringLiteralDataOnly(m: BModule; s: string; info: TLineInfo;
isConst: bool): Rope =
isConst: bool; result: var Rope) =
case detectStrVersion(m)
of 0, 1: result = genStringLiteralDataOnlyV1(m, s)
of 0, 1: genStringLiteralDataOnlyV1(m, s, result)
of 2:
result = getTempName(m)
genStringLiteralDataOnlyV2(m, s, result, isConst)
let tmp = getTempName(m)
genStringLiteralDataOnlyV2(m, s, tmp, isConst)
result.add tmp
else:
localError(m.config, info, "cannot determine how to produce code for string literal")
proc genNilStringLiteral(m: BModule; info: TLineInfo): Rope =
result = ropecg(m, "((#NimStringDesc*) NIM_NIL)", [])
proc genNilStringLiteral(m: BModule; info: TLineInfo; result: var Rope) =
appcg(m, result, "((#NimStringDesc*) NIM_NIL)", [])
proc genStringLiteral(m: BModule; n: PNode): Rope =
proc genStringLiteral(m: BModule; n: PNode; result: var Rope) =
case detectStrVersion(m)
of 0, 1: result = genStringLiteralV1(m, n)
of 2: result = genStringLiteralV2(m, n, isConst = true)
of 0, 1: genStringLiteralV1(m, n, result)
of 2: genStringLiteralV2(m, n, isConst = true, result)
else:
localError(m.config, n.info, "cannot determine how to produce code for string literal")

View File

@@ -19,13 +19,11 @@ import
const
CFileSectionNames: array[TCFileSection, string] = [
cfsMergeInfo: "",
cfsHeaders: "NIM_merge_HEADERS",
cfsFrameDefines: "NIM_merge_FRAME_DEFINES",
cfsForwardTypes: "NIM_merge_FORWARD_TYPES",
cfsTypes: "NIM_merge_TYPES",
cfsSeqTypes: "NIM_merge_SEQ_TYPES",
cfsFieldInfo: "NIM_merge_FIELD_INFO",
cfsTypeInfo: "NIM_merge_TYPE_INFO",
cfsProcHeaders: "NIM_merge_PROC_HEADERS",
cfsData: "NIM_merge_DATA",
@@ -34,11 +32,8 @@ const
cfsInitProc: "NIM_merge_INIT_PROC",
cfsDatInitProc: "NIM_merge_DATINIT_PROC",
cfsTypeInit1: "NIM_merge_TYPE_INIT1",
cfsTypeInit2: "NIM_merge_TYPE_INIT2",
cfsTypeInit3: "NIM_merge_TYPE_INIT3",
cfsDebugInit: "NIM_merge_DEBUG_INIT",
cfsDynLibInit: "NIM_merge_DYNLIB_INIT",
cfsDynLibDeinit: "NIM_merge_DYNLIB_DEINIT",
cfsDynLibInit: "NIM_merge_DYNLIB_INIT"
]
CProcSectionNames: array[TCProcSection, string] = [
cpsLocals: "NIM_merge_PROC_LOCALS",

View File

@@ -24,7 +24,7 @@ proc specializeResetN(p: BProc, accessor: Rope, n: PNode;
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.r == "": 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])
@@ -42,7 +42,7 @@ proc specializeResetN(p: BProc, accessor: Rope, n: PNode;
of nkSym:
let field = n.sym
if field.typ.kind == tyVoid: return
if field.loc.r == nil: fillObjectFields(p.module, typ)
if field.loc.r == "": 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)
@@ -87,7 +87,20 @@ proc specializeResetT(p: BProc, accessor: Rope, typ: PType) =
lineCg(p, cpsStmts, "$1 = 0;$n", [accessor])
of tyCstring, tyPointer, tyPtr, tyVar, tyLent:
lineCg(p, cpsStmts, "$1 = NIM_NIL;$n", [accessor])
else:
of tySet:
case mapSetType(p.config, typ)
of ctArray:
lineCg(p, cpsStmts, "#nimZeroMem($1, sizeof($2));$n",
[accessor, getTypeDesc(p.module, typ)])
of ctInt8, ctInt16, ctInt32, ctInt64:
lineCg(p, cpsStmts, "$1 = 0;$n", [accessor])
else:
doAssert false, "unexpected set type kind"
of {tyNone, tyEmpty, tyNil, tyUntyped, tyTyped, tyGenericInvocation,
tyGenericParam, tyOrdinal, tyRange, tyOpenArray, tyForward, tyVarargs,
tyUncheckedArray, tyProxy, tyBuiltInTypeClass, tyUserTypeClass,
tyUserTypeClassInst, tyCompositeTypeClass, tyAnd, tyOr, tyNot,
tyAnything, tyStatic, tyFromExpr, tyConcept, tyVoid, tyIterable}:
discard
proc specializeReset(p: BProc, a: TLoc) =

View File

@@ -8,37 +8,44 @@
#
# included from cgen.nim
const
RangeExpandLimit = 256 # do not generate ranges
# over 'RangeExpandLimit' elements
stringCaseThreshold = 8
# above X strings a hash-switch for strings is generated
proc getTraverseProc(p: BProc, v: PSym): Rope =
if p.config.selectedGC in {gcMarkAndSweep, gcHooks, gcV2, gcRefc} and
proc registerTraverseProc(p: BProc, v: PSym) =
var traverseProc = ""
if p.config.selectedGC in {gcMarkAndSweep, gcHooks, gcRefc} and
optOwnedRefs notin p.config.globalOptions and
containsGarbageCollectedRef(v.loc.t):
# we register a specialized marked proc here; this has the advantage
# that it works out of the box for thread local storage then :-)
result = genTraverseProcForGlobal(p.module, v, v.info)
traverseProc = genTraverseProcForGlobal(p.module, v, v.info)
proc registerTraverseProc(p: BProc, v: PSym, traverseProc: Rope) =
if sfThread in v.flags:
appcg(p.module, p.module.preInitProc.procSec(cpsInit),
"$n\t#nimRegisterThreadLocalMarker($1);$n$n", [traverseProc])
else:
appcg(p.module, p.module.preInitProc.procSec(cpsInit),
"$n\t#nimRegisterGlobalMarker($1);$n$n", [traverseProc])
if traverseProc.len != 0 and not p.hcrOn:
if sfThread in v.flags:
appcg(p.module, p.module.preInitProc.procSec(cpsInit),
"$n\t#nimRegisterThreadLocalMarker($1);$n$n", [traverseProc])
else:
appcg(p.module, p.module.preInitProc.procSec(cpsInit),
"$n\t#nimRegisterGlobalMarker($1);$n$n", [traverseProc])
proc isAssignedImmediately(conf: ConfigRef; n: PNode): bool {.inline.} =
if n.kind == nkEmpty: return false
if isInvalidReturnType(conf, n.typ):
# var v = f()
# is transformed into: var v; f(addr v)
# where 'f' **does not** initialize the result!
return false
result = true
if n.kind == nkEmpty:
result = false
elif n.kind in nkCallKinds and n[0] != nil and n[0].typ != nil and n[0].typ.skipTypes(abstractInst).kind == tyProc:
if isInvalidReturnType(conf, n[0].typ, true):
# var v = f()
# is transformed into: var v; f(addr v)
# where 'f' **does not** initialize the result!
result = false
else:
result = true
elif isInvalidReturnType(conf, n.typ, false):
result = false
else:
result = true
proc inExceptBlockLen(p: BProc): int =
for x in p.nestedTryStmts:
@@ -47,7 +54,9 @@ proc inExceptBlockLen(p: BProc): int =
proc startBlockInternal(p: BProc): int {.discardable.} =
inc(p.labels)
result = p.blocks.len
setLen(p.blocks, result + 1)
p.blocks.add initBlock()
p.blocks[result].id = p.labels
p.blocks[result].nestedTryStmts = p.nestedTryStmts.len.int16
p.blocks[result].nestedExceptStmts = p.inExceptBlockLen.int16
@@ -71,7 +80,7 @@ proc genVarTuple(p: BProc, n: PNode) =
# check only the first son
var forHcr = treatGlobalDifferentlyForHCR(p.module, n[0].sym)
let hcrCond = if forHcr: getTempName(p.module) else: nil
let hcrCond = if forHcr: getTempName(p.module) else: ""
var hcrGlobals: seq[tuple[loc: TLoc, tp: Rope]]
# determine if the tuple is constructed at top-level scope or inside of a block (if/while/block)
let isGlobalInBlock = forHcr and p.blocks.len > 2
@@ -90,13 +99,10 @@ proc genVarTuple(p: BProc, n: PNode) =
let vn = n[i]
let v = vn.sym
if sfCompileTime in v.flags: continue
var traverseProc: Rope
if sfGlobal in v.flags:
assignGlobalVar(p, vn, nil)
assignGlobalVar(p, vn, "")
genObjectInit(p, cpsInit, v.typ, v.loc, constructObj)
traverseProc = getTraverseProc(p, v)
if traverseProc != nil and not p.hcrOn:
registerTraverseProc(p, v, traverseProc)
registerTraverseProc(p, v)
else:
assignLocalVar(p, vn)
initLocalVar(p, v, immediateAsgn=isAssignedImmediately(p.config, n[^1]))
@@ -108,7 +114,7 @@ proc genVarTuple(p: BProc, n: PNode) =
field.r = "$1.$2" % [rdLoc(tup), mangleRecFieldName(p.module, t.n[i].sym)]
putLocIntoDest(p, v.loc, field)
if forHcr or isGlobalInBlock:
hcrGlobals.add((loc: v.loc, tp: if traverseProc == nil: ~"NULL" else: traverseProc))
hcrGlobals.add((loc: v.loc, tp: "NULL"))
if forHcr:
# end the block where the tuple gets initialized
@@ -138,12 +144,12 @@ proc loadInto(p: BProc, le, ri: PNode, a: var TLoc) {.inline.} =
a.flags.incl(lfEnforceDeref)
expr(p, ri, a)
proc assignLabel(b: var TBlock): Rope {.inline.} =
proc assignLabel(b: var TBlock; result: var Rope) {.inline.} =
b.label = "LA" & b.id.rope
result = b.label
result.add b.label
proc blockBody(b: var TBlock): Rope =
result = b.sections[cpsLocals]
proc blockBody(b: var TBlock; result: var Rope) =
result.add b.sections[cpsLocals]
if b.frameLen > 0:
result.addf("FR_.len+=$1;$n", [b.frameLen.rope])
result.add(b.sections[cpsInit])
@@ -152,7 +158,7 @@ proc blockBody(b: var TBlock): Rope =
proc endBlock(p: BProc, blockEnd: Rope) =
let topBlock = p.blocks.len-1
# the block is merged into the parent block
p.blocks[topBlock-1].sections[cpsStmts].add(p.blocks[topBlock].blockBody)
p.blocks[topBlock].blockBody(p.blocks[topBlock-1].sections[cpsStmts])
setLen(p.blocks, topBlock)
# this is done after the block is popped so $n is
# properly indented when pretty printing is enabled
@@ -164,7 +170,7 @@ proc endBlock(p: BProc) =
var blockEnd: Rope
if frameLen > 0:
blockEnd.addf("FR_.len-=$1;$n", [frameLen.rope])
if p.blocks[topBlock].label != nil:
if p.blocks[topBlock].label.len != 0:
blockEnd.addf("} $1: ;$n", [p.blocks[topBlock].label])
else:
blockEnd.addf("}$n", [])
@@ -272,17 +278,15 @@ proc genGotoVar(p: BProc; value: PNode) =
else:
lineF(p, cpsStmts, "goto NIMSTATE_$#;$n", [value.intVal.rope])
proc genBracedInit(p: BProc, n: PNode; isConst: bool; optionalType: PType): Rope
proc genBracedInit(p: BProc, n: PNode; isConst: bool; optionalType: PType; result: var Rope)
proc potentialValueInit(p: BProc; v: PSym; value: PNode): Rope =
proc potentialValueInit(p: BProc; v: PSym; value: PNode; result: var Rope) =
if lfDynamicLib in v.loc.flags or sfThread in v.flags or p.hcrOn:
result = nil
discard "nothing to do"
elif sfGlobal in v.flags and value != nil and isDeepConstExpr(value, p.module.compileToCpp) and
p.withinLoop == 0 and not containsGarbageCollectedRef(v.typ):
#echo "New code produced for ", v.name.s, " ", p.config $ value.info
result = genBracedInit(p, value, isConst = false, v.typ)
else:
result = nil
genBracedInit(p, value, isConst = false, v.typ, result)
proc genSingleVar(p: BProc, v: PSym; vn, value: PNode) =
if sfGoto in v.flags:
@@ -290,8 +294,8 @@ proc genSingleVar(p: BProc, v: PSym; vn, value: PNode) =
genGotoVar(p, value)
return
var targetProc = p
var traverseProc: Rope
let valueAsRope = potentialValueInit(p, v, value)
var valueAsRope = ""
potentialValueInit(p, v, value, valueAsRope)
if sfGlobal in v.flags:
if v.flags * {sfImportc, sfExportc} == {sfImportc} and
value.kind == nkEmpty and
@@ -307,7 +311,7 @@ proc genSingleVar(p: BProc, v: PSym; vn, value: PNode) =
# That's why we are doing the construction inside the preInitProc.
# genObjectInit relies on the C runtime's guarantees that
# global variables will be initialized to zero.
if valueAsRope == nil:
if valueAsRope.len == 0:
var loc = v.loc
# When the native TLS is unavailable, a global thread-local variable needs
@@ -321,9 +325,7 @@ proc genSingleVar(p: BProc, v: PSym; vn, value: PNode) =
# if sfImportc notin v.flags: constructLoc(p.module.preInitProc, v.loc)
if sfExportc in v.flags and p.module.g.generatedHeader != nil:
genVarPrototype(p.module.g.generatedHeader, vn)
traverseProc = getTraverseProc(p, v)
if traverseProc != nil and not p.hcrOn:
registerTraverseProc(p, v, traverseProc)
registerTraverseProc(p, v)
else:
let imm = isAssignedImmediately(p.config, value)
if imm and p.module.compileToCpp and p.splitDecls == 0 and
@@ -336,14 +338,14 @@ proc genSingleVar(p: BProc, v: PSym; vn, value: PNode) =
var tmp: TLoc
if value.kind in nkCallKinds and value[0].kind == nkSym and
sfConstructor in value[0].sym.flags:
var params: Rope
var params = newRopeAppender()
var argsCounter = 0
let typ = skipTypes(value[0].typ, abstractInst)
assert(typ.kind == tyProc)
for i in 1..<value.len:
if params != nil: params.add(~", ")
assert(typ.len == typ.n.len)
params.add(genOtherArg(p, value, i, typ))
if params == nil:
genOtherArg(p, value, i, typ, params, argsCounter)
if params.len == 0:
lineF(p, cpsStmts, "$#;$n", [decl])
else:
lineF(p, cpsStmts, "$#($#);$n", [decl, params])
@@ -354,7 +356,7 @@ proc genSingleVar(p: BProc, v: PSym; vn, value: PNode) =
assignLocalVar(p, vn)
initLocalVar(p, v, imm)
if traverseProc == nil: traverseProc = ~"NULL"
let traverseProc = "NULL"
# If the var is in a block (control flow like if/while or a block) in global scope just
# register the so called "global" so it can be used later on. There is no need to close
# and reopen of if (nim_hcr_do_init_) blocks because we are in one already anyway.
@@ -374,7 +376,7 @@ proc genSingleVar(p: BProc, v: PSym; vn, value: PNode) =
lineCg(targetProc, cpsStmts, "if (hcrRegisterGlobal($3, \"$1\", sizeof($2), $4, (void**)&$1))$N",
[v.loc.r, rdLoc(v.loc), getModuleDllPath(p.module, v), traverseProc])
startBlock(targetProc)
if value.kind != nkEmpty and valueAsRope == nil:
if value.kind != nkEmpty and valueAsRope.len == 0:
genLineDir(targetProc, vn)
loadInto(targetProc, vn, value, v.loc)
if forHcr:
@@ -398,7 +400,7 @@ proc genClosureVar(p: BProc, a: PNode) =
genLineDir(p, a)
if immediateAsgn:
loadInto(p, a[0], a[2], v)
else:
elif sfNoInit notin a[0][1].sym.flags:
constructLoc(p, v)
proc genVarStmt(p: BProc, n: PNode) =
@@ -553,7 +555,9 @@ proc genComputedGoto(p: BProc; n: PNode) =
return
let val = getOrdValue(it[j])
lineF(p, cpsStmts, "TMP$#_:$n", [intLiteral(toInt64(val)+id+1)])
var lit = newRopeAppender()
intLiteral(toInt64(val)+id+1, lit)
lineF(p, cpsStmts, "TMP$#_:$n", [lit])
genStmts(p, it.lastSon)
@@ -607,8 +611,9 @@ proc genWhileStmt(p: BProc, t: PNode) =
p.blocks[p.breakIdx].isLoop = true
initLocExpr(p, t[0], a)
if (t[0].kind != nkIntLit) or (t[0].intVal == 0):
let label = assignLabel(p.blocks[p.breakIdx])
lineF(p, cpsStmts, "if (!$1) goto $2;$n", [rdLoc(a), label])
lineF(p, cpsStmts, "if (!$1) goto ", [rdLoc(a)])
assignLabel(p.blocks[p.breakIdx], p.s(cpsStmts))
lineF(p, cpsStmts, ";$n", [])
genStmts(p, loopBody)
if optProfiler in p.options:
@@ -695,12 +700,12 @@ proc genBreakStmt(p: BProc, t: PNode) =
while idx >= 0 and not p.blocks[idx].isLoop: dec idx
if idx < 0 or not p.blocks[idx].isLoop:
internalError(p.config, t.info, "no loop to break")
let label = assignLabel(p.blocks[idx])
p.blocks[idx].label = "LA" & p.blocks[idx].id.rope
blockLeaveActions(p,
p.nestedTryStmts.len - p.blocks[idx].nestedTryStmts,
p.inExceptBlockLen - p.blocks[idx].nestedExceptStmts)
genLineDir(p, t)
lineF(p, cpsStmts, "goto $1;$n", [label])
lineF(p, cpsStmts, "goto $1;$n", [p.blocks[idx].label])
proc raiseExit(p: BProc) =
assert p.config.exc == excGoto
@@ -722,21 +727,19 @@ proc finallyActions(p: BProc) =
if finallyBlock != nil:
genSimpleBlock(p, finallyBlock[0])
proc raiseInstr(p: BProc): Rope =
proc raiseInstr(p: BProc; result: var Rope) =
if p.config.exc == excGoto:
let L = p.nestedTryStmts.len
if L == 0:
p.flags.incl beforeRetNeeded
# easy case, simply goto 'ret':
result = ropecg(p.module, "goto BeforeRet_;$n", [])
result.add ropecg(p.module, "goto BeforeRet_;$n", [])
else:
# raise inside an 'except' must go to the finally block,
# raise outside an 'except' block must go to the 'except' list.
result = ropecg(p.module, "goto LA$1_;$n",
result.add ropecg(p.module, "goto LA$1_;$n",
[p.nestedTryStmts[L-1].label])
# + ord(p.nestedTryStmts[L-1].inExcept)])
else:
result = nil
proc genRaiseStmt(p: BProc, t: PNode) =
if t[0].kind != nkEmpty:
@@ -765,12 +768,10 @@ proc genRaiseStmt(p: BProc, t: PNode) =
genLineDir(p, t)
# reraise the last exception:
if p.config.exc == excCpp:
line(p, cpsStmts, ~"throw;$n")
line(p, cpsStmts, "throw;\n")
else:
linefmt(p, cpsStmts, "#reraiseException();$n", [])
let gotoInstr = raiseInstr(p)
if gotoInstr != nil:
line(p, cpsStmts, gotoInstr)
raiseInstr(p, p.s(cpsStmts))
template genCaseGenericBranch(p: BProc, b: PNode, e: TLoc,
rangeFormat, eqFormat: FormatStr, labl: TLabel) =
@@ -830,17 +831,27 @@ template genCaseGeneric(p: BProc, t: PNode, d: var TLoc,
fixLabel(p, lend)
proc genCaseStringBranch(p: BProc, b: PNode, e: TLoc, labl: TLabel,
stringKind: TTypeKind,
branches: var openArray[Rope]) =
var x: TLoc
for i in 0..<b.len - 1:
assert(b[i].kind != nkRange)
initLocExpr(p, b[i], x)
assert(b[i].kind in {nkStrLit..nkTripleStrLit})
var j = int(hashString(p.config, b[i].strVal) and high(branches))
appcg(p.module, branches[j], "if (#eqStrings($1, $2)) goto $3;$n",
var j: int
case b[i].kind
of nkStrLit..nkTripleStrLit:
j = int(hashString(p.config, b[i].strVal) and high(branches))
of nkNilLit: j = 0
else:
assert false, "invalid string case branch node kind"
if stringKind == tyCstring:
appcg(p.module, branches[j], "if (#eqCstrings($1, $2)) goto $3;$n",
[rdLoc(e), rdLoc(x), labl])
else:
appcg(p.module, branches[j], "if (#eqStrings($1, $2)) goto $3;$n",
[rdLoc(e), rdLoc(x), labl])
proc genStringCase(p: BProc, t: PNode, d: var TLoc) =
proc genStringCase(p: BProc, t: PNode, stringKind: TTypeKind, d: var TLoc) =
# count how many constant strings there are in the case:
var strings = 0
for i in 1..<t.len:
@@ -856,17 +867,23 @@ proc genStringCase(p: BProc, t: PNode, d: var TLoc) =
inc(p.labels)
if t[i].kind == nkOfBranch:
genCaseStringBranch(p, t[i], a, "LA" & rope(p.labels) & "_",
branches)
stringKind, branches)
else:
# else statement: nothing to do yet
# but we reserved a label, which we use later
discard
linefmt(p, cpsStmts, "switch (#hashString($1) & $2) {$n",
[rdLoc(a), bitMask])
if stringKind == tyCstring:
linefmt(p, cpsStmts, "switch (#hashCstring($1) & $2) {$n",
[rdLoc(a), bitMask])
else:
linefmt(p, cpsStmts, "switch (#hashString($1) & $2) {$n",
[rdLoc(a), bitMask])
for j in 0..high(branches):
if branches[j] != nil:
if branches[j] != "":
var lit = newRopeAppender()
intLiteral(j, lit)
lineF(p, cpsStmts, "case $1: $n$2break;$n",
[intLiteral(j), branches[j]])
[lit, branches[j]])
lineF(p, cpsStmts, "}$n", []) # else statement:
if t[^1].kind != nkOfBranch:
lineF(p, cpsStmts, "goto LA$1_;$n", [rope(p.labels)])
@@ -874,7 +891,10 @@ proc genStringCase(p: BProc, t: PNode, d: var TLoc) =
var lend = genCaseSecondPass(p, t, d, labId, t.len-1)
fixLabel(p, lend)
else:
genCaseGeneric(p, t, d, "", "if (#eqStrings($1, $2)) goto $3;$n")
if stringKind == tyCstring:
genCaseGeneric(p, t, d, "", "if (#eqCstrings($1, $2)) goto $3;$n")
else:
genCaseGeneric(p, t, d, "", "if (#eqStrings($1, $2)) goto $3;$n")
proc branchHasTooBigRange(b: PNode): bool =
for it in b:
@@ -897,16 +917,22 @@ proc genCaseRange(p: BProc, branch: PNode) =
for j in 0..<branch.len-1:
if branch[j].kind == nkRange:
if hasSwitchRange in CC[p.config.cCompiler].props:
lineF(p, cpsStmts, "case $1 ... $2:$n", [
genLiteral(p, branch[j][0]),
genLiteral(p, branch[j][1])])
var litA = newRopeAppender()
var litB = newRopeAppender()
genLiteral(p, branch[j][0], litA)
genLiteral(p, branch[j][1], litB)
lineF(p, cpsStmts, "case $1 ... $2:$n", [litA, litB])
else:
var v = copyNode(branch[j][0])
while v.intVal <= branch[j][1].intVal:
lineF(p, cpsStmts, "case $1:$n", [genLiteral(p, v)])
var litA = newRopeAppender()
genLiteral(p, v, litA)
lineF(p, cpsStmts, "case $1:$n", [litA])
inc(v.intVal)
else:
lineF(p, cpsStmts, "case $1:$n", [genLiteral(p, branch[j])])
var litA = newRopeAppender()
genLiteral(p, branch[j], litA)
lineF(p, cpsStmts, "case $1:$n", [litA])
proc genOrdinalCase(p: BProc, n: PNode, d: var TLoc) =
# analyse 'case' statement:
@@ -918,7 +944,7 @@ proc genOrdinalCase(p: BProc, n: PNode, d: var TLoc) =
var lend = if splitPoint > 0: genIfForCaseUntil(p, n, d,
rangeFormat = "if ($1 >= $2 && $1 <= $3) goto $4;$n",
eqFormat = "if ($1 == $2) goto $3;$n",
splitPoint, a) else: nil
splitPoint, a) else: ""
# generate switch part (might be empty):
if splitPoint+1 < n.len:
@@ -939,7 +965,7 @@ proc genOrdinalCase(p: BProc, n: PNode, d: var TLoc) =
if (hasAssume in CC[p.config.cCompiler].props) and not hasDefault:
lineF(p, cpsStmts, "default: __assume(0);$n", [])
lineF(p, cpsStmts, "}$n", [])
if lend != nil: fixLabel(p, lend)
if lend != "": fixLabel(p, lend)
proc genCase(p: BProc, t: PNode, d: var TLoc) =
genLineDir(p, t)
@@ -947,7 +973,9 @@ proc genCase(p: BProc, t: PNode, d: var TLoc) =
getTemp(p, t.typ, d)
case skipTypes(t[0].typ, abstractVarRange).kind
of tyString:
genStringCase(p, t, d)
genStringCase(p, t, tyString, d)
of tyCstring:
genStringCase(p, t, tyCstring, d)
of tyFloat..tyFloat128:
genCaseGeneric(p, t, d, "if ($1 >= $2 && $1 <= $3) goto $4;$n",
"if ($1 == $2) goto $3;$n")
@@ -1038,7 +1066,7 @@ proc genTryCpp(p: BProc, t: PNode, d: var TLoc) =
linefmt(p, cpsStmts, "#popCurrentException();$n", [])
endBlock(p)
else:
var orExpr = Rope(nil)
var orExpr = newRopeAppender()
var exvar = PNode(nil)
for j in 0..<t[i].len - 1:
var typeNode = t[i][j]
@@ -1049,22 +1077,24 @@ proc genTryCpp(p: BProc, t: PNode, d: var TLoc) =
if isImportedException(typeNode.typ, p.config):
hasImportedCppExceptions = true
else:
if orExpr != nil: orExpr.add("||")
let checkFor = if optTinyRtti in p.config.globalOptions:
genTypeInfo2Name(p.module, typeNode.typ)
else:
genTypeInfoV1(p.module, typeNode.typ, typeNode.info)
if orExpr.len != 0: orExpr.add("||")
let memberName = if p.module.compileToCpp: "m_type" else: "Sup.m_type"
appcg(p.module, orExpr, "#isObj(#nimBorrowCurrentException()->$1, $2)", [memberName, checkFor])
if optTinyRtti in p.config.globalOptions:
let checkFor = $getObjDepth(typeNode.typ)
appcg(p.module, orExpr, "#isObjDisplayCheck(#nimBorrowCurrentException()->$1, $2, $3)", [memberName, checkFor, $genDisplayElem(MD5Digest(hashType(typeNode.typ, p.config)))])
else:
let checkFor = genTypeInfoV1(p.module, typeNode.typ, typeNode.info)
appcg(p.module, orExpr, "#isObj(#nimBorrowCurrentException()->$1, $2)", [memberName, checkFor])
if orExpr != nil:
if orExpr.len != 0:
if hasIf:
startBlock(p, "else if ($1) {$n", [orExpr])
else:
startBlock(p, "if ($1) {$n", [orExpr])
hasIf = true
if exvar != nil:
fillLoc(exvar.sym.loc, locTemp, exvar, mangleLocalName(p, exvar.sym), OnStack)
fillLocalName(p, exvar.sym)
fillLoc(exvar.sym.loc, locTemp, exvar, OnStack)
linefmt(p, cpsStmts, "$1 $2 = T$3_;$n", [getTypeDesc(p.module, exvar.sym.typ),
rdLoc(exvar.sym.loc), rope(etmp+1)])
# we handled the error:
@@ -1105,7 +1135,8 @@ proc genTryCpp(p: BProc, t: PNode, d: var TLoc) =
typeNode = t[i][j][1]
if isImportedException(typeNode.typ, p.config):
let exvar = t[i][j][2] # ex1 in `except ExceptType as ex1:`
fillLoc(exvar.sym.loc, locTemp, exvar, mangleLocalName(p, exvar.sym), OnStack)
fillLocalName(p, exvar.sym)
fillLoc(exvar.sym.loc, locTemp, exvar, OnStack)
startBlock(p, "catch ($1& $2) {$n", getTypeDesc(p.module, typeNode.typ), rdLoc(exvar.sym.loc))
genExceptBranchBody(t[i][^1]) # exception handler body will duplicated for every type
endBlock(p)
@@ -1158,7 +1189,7 @@ proc genTryCppOld(p: BProc, t: PNode, d: var TLoc) =
if not isEmptyType(t.typ) and d.k == locNone:
getTemp(p, t.typ, d)
genLineDir(p, t)
discard cgsym(p.module, "popCurrentExceptionEx")
cgsym(p.module, "popCurrentExceptionEx")
let fin = if t[^1].kind == nkFinally: t[^1] else: nil
p.nestedTryStmts.add((fin, false, 0.Natural))
startBlock(p, "try {$n")
@@ -1184,7 +1215,8 @@ proc genTryCppOld(p: BProc, t: PNode, d: var TLoc) =
for j in 0..<t[i].len-1:
if t[i][j].isInfixAs():
let exvar = t[i][j][2] # ex1 in `except ExceptType as ex1:`
fillLoc(exvar.sym.loc, locTemp, exvar, mangleLocalName(p, exvar.sym), OnUnknown)
fillLocalName(p, exvar.sym)
fillLoc(exvar.sym.loc, locTemp, exvar, OnUnknown)
startBlock(p, "catch ($1& $2) {$n", getTypeDesc(p.module, t[i][j][1].typ), rdLoc(exvar.sym.loc))
else:
startBlock(p, "catch ($1&) {$n", getTypeDesc(p.module, t[i][j].typ))
@@ -1199,7 +1231,7 @@ proc genTryCppOld(p: BProc, t: PNode, d: var TLoc) =
# finally requires catch all presence
startBlock(p, "catch (...) {$n")
genStmts(p, t[^1][0])
line(p, cpsStmts, ~"throw;$n")
line(p, cpsStmts, "throw;\n")
endBlock(p)
genSimpleBlock(p, t[^1][0])
@@ -1261,16 +1293,17 @@ proc genTryGoto(p: BProc; t: PNode; d: var TLoc) =
linefmt(p, cpsStmts, "*nimErr_ = NIM_FALSE;$n", [])
expr(p, t[i][0], d)
else:
var orExpr: Rope = nil
var orExpr = newRopeAppender()
for j in 0..<t[i].len - 1:
assert(t[i][j].kind == nkType)
if orExpr != nil: orExpr.add("||")
let checkFor = if optTinyRtti in p.config.globalOptions:
genTypeInfo2Name(p.module, t[i][j].typ)
else:
genTypeInfoV1(p.module, t[i][j].typ, t[i][j].info)
if orExpr.len != 0: orExpr.add("||")
let memberName = if p.module.compileToCpp: "m_type" else: "Sup.m_type"
appcg(p.module, orExpr, "#isObj(#nimBorrowCurrentException()->$1, $2)", [memberName, checkFor])
if optTinyRtti in p.config.globalOptions:
let checkFor = $getObjDepth(t[i][j].typ)
appcg(p.module, orExpr, "#isObjDisplayCheck(#nimBorrowCurrentException()->$1, $2, $3)", [memberName, checkFor, $genDisplayElem(MD5Digest(hashType(t[i][j].typ, p.config)))])
else:
let checkFor = genTypeInfoV1(p.module, t[i][j].typ, t[i][j].info)
appcg(p.module, orExpr, "#isObj(#nimBorrowCurrentException()->$1, $2)", [memberName, checkFor])
if i > 1: line(p, cpsStmts, "else ")
startBlock(p, "if ($1) {$n", [orExpr])
@@ -1346,7 +1379,7 @@ proc genTrySetjmp(p: BProc, t: PNode, d: var TLoc) =
else:
p.flags.incl noSafePoints
genLineDir(p, t)
discard cgsym(p.module, "Exception")
cgsym(p.module, "Exception")
var safePoint: Rope
if not quirkyExceptions:
safePoint = getTempName(p.module)
@@ -1356,8 +1389,24 @@ proc genTrySetjmp(p: BProc, t: PNode, d: var TLoc) =
linefmt(p, cpsStmts, "$1.status = setjmp($1.context);$n", [safePoint])
elif isDefined(p.config, "nimSigSetjmp"):
linefmt(p, cpsStmts, "$1.status = sigsetjmp($1.context, 0);$n", [safePoint])
elif isDefined(p.config, "nimBuiltinSetjmp"):
linefmt(p, cpsStmts, "$1.status = __builtin_setjmp($1.context);$n", [safePoint])
elif isDefined(p.config, "nimRawSetjmp"):
linefmt(p, cpsStmts, "$1.status = _setjmp($1.context);$n", [safePoint])
if isDefined(p.config, "mswindows"):
if isDefined(p.config, "vcc") or isDefined(p.config, "clangcl"):
# For the vcc compiler, use `setjmp()` with one argument.
# See https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/setjmp?view=msvc-170
linefmt(p, cpsStmts, "$1.status = setjmp($1.context);$n", [safePoint])
else:
# The Windows `_setjmp()` takes two arguments, with the second being an
# undocumented buffer used by the SEH mechanism for stack unwinding.
# Mingw-w64 has been trying to get it right for years, but it's still
# prone to stack corruption during unwinding, so we disable that by setting
# it to NULL.
# More details: https://github.com/status-im/nimbus-eth2/issues/3121
linefmt(p, cpsStmts, "$1.status = _setjmp($1.context, 0);$n", [safePoint])
else:
linefmt(p, cpsStmts, "$1.status = _setjmp($1.context);$n", [safePoint])
else:
linefmt(p, cpsStmts, "$1.status = setjmp($1.context);$n", [safePoint])
lineCg(p, cpsStmts, "if ($1.status == 0) {$n", [safePoint])
@@ -1389,16 +1438,17 @@ proc genTrySetjmp(p: BProc, t: PNode, d: var TLoc) =
linefmt(p, cpsStmts, "#popCurrentException();$n", [])
endBlock(p)
else:
var orExpr: Rope = nil
var orExpr = newRopeAppender()
for j in 0..<t[i].len - 1:
assert(t[i][j].kind == nkType)
if orExpr != nil: orExpr.add("||")
let checkFor = if optTinyRtti in p.config.globalOptions:
genTypeInfo2Name(p.module, t[i][j].typ)
else:
genTypeInfoV1(p.module, t[i][j].typ, t[i][j].info)
if orExpr.len != 0: orExpr.add("||")
let memberName = if p.module.compileToCpp: "m_type" else: "Sup.m_type"
appcg(p.module, orExpr, "#isObj(#nimBorrowCurrentException()->$1, $2)", [memberName, checkFor])
if optTinyRtti in p.config.globalOptions:
let checkFor = $getObjDepth(t[i][j].typ)
appcg(p.module, orExpr, "#isObjDisplayCheck(#nimBorrowCurrentException()->$1, $2, $3)", [memberName, checkFor, $genDisplayElem(MD5Digest(hashType(t[i][j].typ, p.config)))])
else:
let checkFor = genTypeInfoV1(p.module, t[i][j].typ, t[i][j].info)
appcg(p.module, orExpr, "#isObj(#nimBorrowCurrentException()->$1, $2)", [memberName, checkFor])
if i > 1: line(p, cpsStmts, "else ")
startBlock(p, "if ($1) {$n", [orExpr])
@@ -1424,7 +1474,7 @@ proc genTrySetjmp(p: BProc, t: PNode, d: var TLoc) =
if not quirkyExceptions:
linefmt(p, cpsStmts, "if ($1.status != 0) #reraiseException();$n", [safePoint])
proc genAsmOrEmitStmt(p: BProc, t: PNode, isAsmStmt=false): Rope =
proc genAsmOrEmitStmt(p: BProc, t: PNode, isAsmStmt=false; result: var Rope) =
var res = ""
for it in t.sons:
case it.kind
@@ -1440,13 +1490,8 @@ proc genAsmOrEmitStmt(p: BProc, t: PNode, isAsmStmt=false): Rope =
res.add($getTypeDesc(p.module, sym.typ))
else:
discard getTypeDesc(p.module, skipTypes(sym.typ, abstractPtrs))
var r = sym.loc.r
if r == nil:
# if no name has already been given,
# it doesn't matter much:
r = mangleName(p.module, sym)
sym.loc.r = r # but be consequent!
res.add($r)
fillBackendName(p.module, sym)
res.add($sym.loc.r)
of nkTypeOfExpr:
res.add($getTypeDesc(p.module, it.typ))
else:
@@ -1471,12 +1516,13 @@ proc genAsmOrEmitStmt(p: BProc, t: PNode, isAsmStmt=false): Rope =
result.add("\\n\"\n")
else:
res.add("\L")
result = res.rope
result.add res.rope
proc genAsmStmt(p: BProc, t: PNode) =
assert(t.kind == nkAsmStmt)
genLineDir(p, t)
var s = genAsmOrEmitStmt(p, t, isAsmStmt=true)
var s = newRopeAppender()
genAsmOrEmitStmt(p, t, isAsmStmt=true, s)
# see bug #2362, "top level asm statements" seem to be a mis-feature
# but even if we don't do this, the example in #2362 cannot possibly
# work:
@@ -1484,18 +1530,20 @@ proc genAsmStmt(p: BProc, t: PNode) =
# top level asm statement?
p.module.s[cfsProcHeaders].add runtimeFormat(CC[p.config.cCompiler].asmStmtFrmt, [s])
else:
p.s(cpsStmts).add indentLine(p, runtimeFormat(CC[p.config.cCompiler].asmStmtFrmt, [s]))
addIndent p, p.s(cpsStmts)
p.s(cpsStmts).add runtimeFormat(CC[p.config.cCompiler].asmStmtFrmt, [s])
proc determineSection(n: PNode): TCFileSection =
result = cfsProcHeaders
if n.len >= 1 and n[0].kind in {nkStrLit..nkTripleStrLit}:
let sec = n[0].strVal
if sec.startsWith("/*TYPESECTION*/"): result = cfsTypes
if sec.startsWith("/*TYPESECTION*/"): result = cfsForwardTypes # TODO WORKAROUND
elif sec.startsWith("/*VARSECTION*/"): result = cfsVars
elif sec.startsWith("/*INCLUDESECTION*/"): result = cfsHeaders
proc genEmit(p: BProc, t: PNode) =
var s = genAsmOrEmitStmt(p, t[1])
var s = newRopeAppender()
genAsmOrEmitStmt(p, t[1], false, s)
if p.prc == nil:
# top level emit pragma?
let section = determineSection(t[1])
@@ -1506,9 +1554,14 @@ proc genEmit(p: BProc, t: PNode) =
line(p, cpsStmts, s)
proc genPragma(p: BProc, n: PNode) =
for it in n.sons:
for i in 0..<n.len:
let it = n[i]
case whichPragma(it)
of wEmit: genEmit(p, it)
of wPush:
processPushBackendOption(p.optionsStack, p.options, n, i+1)
of wPop:
processPopBackendOption(p.optionsStack, p.options)
else: discard
@@ -1520,10 +1573,14 @@ proc genDiscriminantCheck(p: BProc, a, tmp: TLoc, objtype: PType,
if not containsOrIncl(p.module.declaredThings, field.id):
appcg(p.module, cfsVars, "extern $1",
[discriminatorTableDecl(p.module, t, field)])
var lit = newRopeAppender()
intLiteral(toInt64(lengthOrd(p.config, field.typ))+1, lit)
lineCg(p, cpsStmts,
"#FieldDiscriminantCheck((NI)(NU)($1), (NI)(NU)($2), $3, $4);$n",
[rdLoc(a), rdLoc(tmp), discriminatorTableName(p.module, t, field),
intLiteral(toInt64(lengthOrd(p.config, field.typ))+1)])
lit])
if p.config.exc == excGoto:
raiseExit(p)
when false:
proc genCaseObjDiscMapping(p: BProc, e: PNode, t: PType, field: PSym; d: var TLoc) =
@@ -1548,7 +1605,7 @@ proc asgnFieldDiscriminant(p: BProc, e: PNode) =
initLocExpr(p, e[0], a)
getTemp(p, a.t, tmp)
expr(p, e[1], tmp)
if optTinyRtti notin p.config.globalOptions:
if p.inUncheckedAssignSection == 0:
let field = dotExpr[1].sym
genDiscriminantCheck(p, a, tmp, dotExpr[0].typ, field)
message(p.config, e.info, warnCaseTransition)
@@ -1569,6 +1626,7 @@ proc genAsgn(p: BProc, e: PNode, fastAsgn: bool) =
initLoc(a, locNone, le, OnUnknown)
a.flags.incl(lfEnforceDeref)
a.flags.incl(lfPrepareForMutation)
genLineDir(p, le) # it can be a nkBracketExpr, which may raise
expr(p, le, a)
a.flags.excl(lfPrepareForMutation)
if fastAsgn: incl(a.flags, lfNoDeepCopy)

View File

@@ -44,13 +44,13 @@ proc declareThreadVar(m: BModule, s: PSym, isExtern: bool) =
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):
if m.g.nimtv != "" and (usesThreadVars in m.flags or sfMainModule in m.module.flags):
for t in items(m.g.nimtvDeps): discard getTypeDesc(m, t)
finishTypeDescriptions(m)
m.s[cfsSeqTypes].addf("typedef struct {$1} NimThreadVars;$n", [m.g.nimtv])
proc generateThreadVarsSize(m: BModule) =
if m.g.nimtv != nil:
if m.g.nimtv != "":
let externc = if m.config.backend == backendCpp or
sfCompileToCpp in m.module.flags: "extern \"C\" "
else: ""

View File

@@ -34,7 +34,7 @@ proc genTraverseProc(c: TTraversalClosure, accessor: Rope, n: PNode;
if (n[0].kind != nkSym): internalError(c.p.config, n.info, "genTraverseProc")
var p = c.p
let disc = n[0].sym
if disc.loc.r == nil: fillObjectFields(c.p.module, typ)
if disc.loc.r == "": 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])
@@ -51,7 +51,7 @@ proc genTraverseProc(c: TTraversalClosure, accessor: Rope, n: PNode;
of nkSym:
let field = n.sym
if field.typ.kind == tyVoid: return
if field.loc.r == nil: fillObjectFields(c.p.module, typ)
if field.loc.r == "": fillObjectFields(c.p.module, typ)
if field.loc.t == nil:
internalError(c.p.config, n.info, "genTraverseProc()")
genTraverseProc(c, "$1.$2" % [accessor, field.loc.r], field.loc.t)
@@ -76,7 +76,8 @@ proc genTraverseProc(c: TTraversalClosure, accessor: Rope, typ: PType) =
let arraySize = lengthOrd(c.p.config, typ[0])
var i: TLoc
getTemp(p, getSysType(c.p.module.g.graph, unknownLineInfo, tyInt), i)
let oldCode = p.s(cpsStmts)
var oldCode = p.s(cpsStmts)
freeze oldCode
linefmt(p, cpsStmts, "for ($1 = 0; $1 < $2; $1++) {$n",
[i.r, arraySize])
let oldLen = p.s(cpsStmts).len
@@ -120,7 +121,8 @@ proc genTraverseProcSeq(c: TTraversalClosure, accessor: Rope, typ: PType) =
assert typ.kind == tySequence
var i: TLoc
getTemp(p, getSysType(c.p.module.g.graph, unknownLineInfo, tyInt), i)
let oldCode = p.s(cpsStmts)
var oldCode = p.s(cpsStmts)
freeze oldCode
var a: TLoc
a.r = accessor

View File

@@ -12,8 +12,7 @@
# ------------------------- Name Mangling --------------------------------
import sighashes, modulegraphs
proc genProcHeader(m: BModule, prc: PSym, asPtr: bool = false): Rope
import std/md5
proc isKeyword(w: PIdent): bool =
# Nim and C++ share some keywords
@@ -35,27 +34,23 @@ proc mangleField(m: BModule; name: PIdent): string =
if isKeyword(name):
result.add "_0"
proc mangleName(m: BModule; s: PSym): Rope =
result = s.loc.r
if result == nil:
result = s.name.s.mangle.rope
result.add "_"
proc fillBackendName(m: BModule; s: PSym) =
if s.loc.r == "":
var result = s.name.s.mangle.rope
result.add "__"
result.add m.g.graph.ifaces[s.itemId.module].uniqueName
result.add "_"
result.add rope s.itemId.item
if m.hcrOn:
result.add "_"
result.add(idOrSig(s, m.module.name.s.mangle, m.sigConflicts))
result.add(idOrSig(s, m.module.name.s.mangle, m.sigConflicts, m.config))
s.loc.r = result
writeMangledName(m.ndi, s, m.config)
proc mangleParamName(m: BModule; s: PSym): Rope =
## we cannot use 'sigConflicts' here since we have a BModule, not a BProc.
## Fortunately C's scoping rules are sane enough so that that doesn't
## cause any trouble.
result = s.loc.r
if result == nil:
proc fillParamName(m: BModule; s: PSym) =
if s.loc.r == "":
var res = s.name.s.mangle
res.add idOrSig(s, res, m.sigConflicts, m.config)
# Take into account if HCR is on because of the following scenario:
# if a module gets imported and it has some more importc symbols in it,
# some param names might receive the "_0" suffix to distinguish from what
@@ -72,21 +67,16 @@ proc mangleParamName(m: BModule; s: PSym): Rope =
# and a function called in main or proxy uses `socket` as a parameter name.
# That would lead to either needing to reload `proxy` or to overwrite the
# executable file for the main module, which is running (or both!) -> error.
if m.hcrOn or isKeyword(s.name) or m.g.config.cppDefines.contains(res):
res.add "_0"
result = res.rope
s.loc.r = result
s.loc.r = res.rope
writeMangledName(m.ndi, s, m.config)
proc mangleLocalName(p: BProc; s: PSym): Rope =
proc fillLocalName(p: BProc; s: PSym) =
assert s.kind in skLocalVars+{skTemp}
#assert sfGlobal notin s.flags
result = s.loc.r
if result == nil:
if s.loc.r == "":
var key = s.name.s.mangle
shallow(key)
let counter = p.sigConflicts.getOrDefault(key)
result = key.rope
var result = key.rope
if s.kind == skTemp:
# speed up conflict search for temps (these are quite common):
if counter != 0: result.add "_" & rope(counter+1)
@@ -102,7 +92,6 @@ proc scopeMangledParam(p: BProc; param: PSym) =
## generate unique identifiers reliably (consider that ``var a = a`` is
## even an idiom in Nim).
var key = param.name.s.mangle
shallow(key)
p.sigConflicts.inc(key)
const
@@ -110,13 +99,12 @@ const
tyDistinct, tyRange, tyStatic, tyAlias, tySink,
tyInferred, tyOwned}
proc typeName(typ: PType): Rope =
proc typeName(typ: PType; result: var Rope) =
let typ = typ.skipTypes(irrelevantForBackend)
result =
if typ.sym != nil and typ.kind in {tyObject, tyEnum}:
rope($typ.kind & '_' & typ.sym.name.s.mangle)
else:
rope($typ.kind)
result.add $typ.kind
if typ.sym != nil and typ.kind in {tyObject, tyEnum}:
result.add "_"
result.add typ.sym.name.s.mangle
proc getTypeName(m: BModule; typ: PType; sig: SigHash): Rope =
var t = typ
@@ -129,14 +117,17 @@ proc getTypeName(m: BModule; typ: PType; sig: SigHash): Rope =
else:
break
let typ = if typ.kind in {tyAlias, tySink, tyOwned}: typ.lastSon else: typ
if typ.loc.r == nil:
typ.loc.r = typ.typeName & $sig
if typ.loc.r == "":
typ.typeName(typ.loc.r)
typ.loc.r.add $sig
else:
when defined(debugSigHashes):
# check consistency:
assert($typ.loc.r == $(typ.typeName & $sig))
var tn = newRopeAppender()
typ.typeName(tn)
assert($typ.loc.r == $(tn & $sig))
result = typ.loc.r
if result == nil: internalError(m.config, "getTypeName: " & $typ.kind)
if result == "": internalError(m.config, "getTypeName: " & $typ.kind)
proc mapSetType(conf: ConfigRef; typ: PType): TCTypeKind =
case int(getSize(conf, typ))
@@ -215,12 +206,19 @@ proc isObjLackingTypeField(typ: PType): bool {.inline.} =
result = (typ.kind == tyObject) and ((tfFinal in typ.flags) and
(typ[0] == nil) or isPureObject(typ))
proc isInvalidReturnType(conf: ConfigRef; rettype: PType): bool =
proc isInvalidReturnType(conf: ConfigRef; typ: PType, isProc = true): bool =
# Arrays and sets cannot be returned by a C procedure, because C is
# such a poor programming language.
# We exclude records with refs too. This enhances efficiency and
# is necessary for proper code generation of assignments.
if rettype == nil: result = true
var rettype = typ
var isAllowedCall = true
if isProc:
rettype = rettype[0]
isAllowedCall = typ.callConv in {ccClosure, ccInline, ccNimCall}
if rettype == nil or (isAllowedCall and
getSize(conf, rettype) > conf.target.floatSize*3):
result = true
else:
case mapType(conf, rettype, skResult)
of ctArray:
@@ -256,11 +254,11 @@ proc addAbiCheck(m: BModule, t: PType, name: Rope) =
# see `testCodegenABICheck` for example error message it generates
proc fillResult(conf: ConfigRef; param: PNode) =
fillLoc(param.sym.loc, locParam, param, ~"Result",
proc fillResult(conf: ConfigRef; param: PNode, proctype: PType) =
fillLoc(param.sym.loc, locParam, param, "Result",
OnStack)
let t = param.sym.typ
if mapReturnType(conf, t) != ctArray and isInvalidReturnType(conf, t):
if mapReturnType(conf, t) != ctArray and isInvalidReturnType(conf, proctype):
incl(param.sym.loc.flags, lfIndirect)
param.sym.loc.storage = OnUnknown
@@ -283,11 +281,11 @@ proc getSimpleTypeDesc(m: BModule, typ: PType): Rope =
of tyString:
case detectStrVersion(m)
of 2:
discard cgsym(m, "NimStrPayload")
discard cgsym(m, "NimStringV2")
cgsym(m, "NimStrPayload")
cgsym(m, "NimStringV2")
result = typeNameOrLiteral(m, typ, "NimStringV2")
else:
discard cgsym(m, "NimStringDesc")
cgsym(m, "NimStringDesc")
result = typeNameOrLiteral(m, typ, "NimStringDesc*")
of tyCstring: result = typeNameOrLiteral(m, typ, "NCSTRING")
of tyBool: result = typeNameOrLiteral(m, typ, "NIM_BOOL")
@@ -301,11 +299,11 @@ proc getSimpleTypeDesc(m: BModule, typ: PType): Rope =
else: internalError(m.config, "tyStatic for getSimpleTypeDesc")
of tyGenericInst, tyAlias, tySink, tyOwned:
result = getSimpleTypeDesc(m, lastSon typ)
else: result = nil
else: result = ""
if result != nil and typ.isImportedType():
let sig = hashType typ
if cacheGetType(m.typeCache, sig) == nil:
if result != "" and typ.isImportedType():
let sig = hashType(typ, m.config)
if cacheGetType(m.typeCache, sig) == "":
m.typeCache[sig] = result
proc pushType(m: BModule, typ: PType) =
@@ -318,7 +316,7 @@ proc getTypePre(m: BModule, typ: PType; sig: SigHash): Rope =
if typ == nil: result = rope("void")
else:
result = getSimpleTypeDesc(m, typ)
if result == nil: result = cacheGetType(m.typeCache, sig)
if result == "": result = cacheGetType(m.typeCache, sig)
proc structOrUnion(t: PType): Rope =
let cachedUnion = rope("union")
@@ -339,9 +337,9 @@ proc seqStar(m: BModule): string =
proc getTypeForward(m: BModule, typ: PType; sig: SigHash): Rope =
result = cacheGetType(m.forwTypeCache, sig)
if result != nil: return
if result != "": return
result = getTypePre(m, typ, sig)
if result != nil: return
if result != "": return
let concrete = typ.skipTypes(abstractInst)
case concrete.kind
of tySequence, tyTuple, tyObject:
@@ -364,16 +362,16 @@ proc getTypeDescWeak(m: BModule; t: PType; check: var IntSet; kind: TSymKind): R
if isImportedCppType(etB) and t.kind == tyGenericInst:
result = getTypeDescAux(m, t, check, kind)
else:
result = getTypeForward(m, t, hashType(t))
result = getTypeForward(m, t, hashType(t, m.config))
pushType(m, t)
of tySequence:
let sig = hashType(t)
let sig = hashType(t, m.config)
if optSeqDestructors in m.config.globalOptions:
if skipTypes(etB[0], typedescInst).kind == tyEmpty:
internalError(m.config, "cannot map the empty seq type to a C type")
result = cacheGetType(m.forwTypeCache, sig)
if result == nil:
if result == "":
result = getTypeName(m, t, sig)
if not isImportedType(t):
m.forwTypeCache[sig] = result
@@ -381,7 +379,7 @@ proc getTypeDescWeak(m: BModule; t: PType; check: var IntSet; kind: TSymKind): R
let payload = result & "_Content"
addForwardStructFormat(m, rope"struct", payload)
if cacheGetType(m.typeCache, sig) == nil:
if cacheGetType(m.typeCache, sig) == "":
m.typeCache[sig] = result
#echo "adding ", sig, " ", typeToString(t), " ", m.module.name.s
appcg(m, m.s[cfsTypes],
@@ -400,9 +398,9 @@ proc getSeqPayloadType(m: BModule; t: PType): Rope =
#result = getTypeForward(m, t, hashType(t)) & "_Content"
proc seqV2ContentType(m: BModule; t: PType; check: var IntSet) =
let sig = hashType(t)
let sig = hashType(t, m.config)
let result = cacheGetType(m.typeCache, sig)
if result == nil:
if result == "":
discard getTypeDescAux(m, t, check, skVar)
else:
# little hack for now to prevent multiple definitions of the same
@@ -424,30 +422,31 @@ proc paramStorageLoc(param: PSym): TStorageLoc =
proc genProcParams(m: BModule, t: PType, rettype, params: var Rope,
check: var IntSet, declareEnvironment=true;
weakDep=false) =
params = nil
if t[0] == nil or isInvalidReturnType(m.config, t[0]):
rettype = ~"void"
params = "("
if t[0] == nil or isInvalidReturnType(m.config, t):
rettype = "void"
else:
rettype = getTypeDescAux(m, t[0], check, skResult)
for i in 1..<t.n.len:
if t.n[i].kind != nkSym: internalError(m.config, t.n.info, "genProcParams")
var param = t.n[i].sym
if isCompileTimeOnly(param.typ): continue
if params != nil: params.add(~", ")
fillLoc(param.loc, locParam, t.n[i], mangleParamName(m, param),
if params != "(": params.add(", ")
fillParamName(m, param)
fillLoc(param.loc, locParam, t.n[i],
param.paramStorageLoc)
if ccgIntroducedPtr(m.config, param, t[0]):
params.add(getTypeDescWeak(m, param.typ, check, skParam))
params.add(~"*")
params.add("*")
incl(param.loc.flags, lfIndirect)
param.loc.storage = OnUnknown
elif weakDep:
params.add(getTypeDescWeak(m, param.typ, check, skParam))
else:
params.add(getTypeDescAux(m, param.typ, check, skParam))
params.add(~" ")
params.add(" ")
if sfNoalias in param.flags:
params.add(~"NIM_NOALIAS ")
params.add("NIM_NOALIAS ")
params.add(param.loc.r)
# declare the len field for open arrays:
var arr = param.typ.skipTypes({tyGenericInst})
@@ -460,54 +459,58 @@ proc genProcParams(m: BModule, t: PType, rettype, params: var Rope,
params.addf(", NI $1Len_$2", [param.loc.r, j.rope])
inc(j)
arr = arr[0].skipTypes({tySink})
if t[0] != nil and isInvalidReturnType(m.config, t[0]):
if t[0] != nil and isInvalidReturnType(m.config, t):
var arr = t[0]
if params != nil: params.add(", ")
if params != "(": params.add(", ")
if mapReturnType(m.config, t[0]) != ctArray:
params.add(getTypeDescWeak(m, arr, check, skResult))
params.add("*")
if isHeaderFile in m.flags:
# still generates types for `--header`
params.add(getTypeDescAux(m, arr, check, skResult))
params.add("*")
else:
params.add(getTypeDescWeak(m, arr, check, skResult))
params.add("*")
else:
params.add(getTypeDescAux(m, arr, check, skResult))
params.addf(" Result", [])
if t.callConv == ccClosure and declareEnvironment:
if params != nil: params.add(", ")
if params != "(": params.add(", ")
params.add("void* ClE_0")
if tfVarargs in t.flags:
if params != nil: params.add(", ")
if params != "(": params.add(", ")
params.add("...")
if params == nil: params.add("void)")
if params == "(": params.add("void)")
else: params.add(")")
params = "(" & params
proc mangleRecFieldName(m: BModule; field: PSym): Rope =
if {sfImportc, sfExportc} * field.flags != {}:
result = field.loc.r
else:
result = rope(mangleField(m, field.name))
if result == nil: internalError(m.config, field.info, "mangleRecFieldName")
if result == "": internalError(m.config, field.info, "mangleRecFieldName")
proc genRecordFieldsAux(m: BModule, n: PNode,
rectype: PType,
check: var IntSet, unionPrefix = ""): Rope =
result = nil
check: var IntSet; result: var Rope; unionPrefix = "") =
case n.kind
of nkRecList:
for i in 0..<n.len:
result.add(genRecordFieldsAux(m, n[i], rectype, check, unionPrefix))
genRecordFieldsAux(m, n[i], rectype, check, result, unionPrefix)
of nkRecCase:
if n[0].kind != nkSym: internalError(m.config, n.info, "genRecordFieldsAux")
result.add(genRecordFieldsAux(m, n[0], rectype, check, unionPrefix))
genRecordFieldsAux(m, n[0], rectype, check, result, unionPrefix)
# prefix mangled name with "_U" to avoid clashes with other field names,
# since identifiers are not allowed to start with '_'
var unionBody: Rope = nil
var unionBody: Rope = ""
for i in 1..<n.len:
case n[i].kind
of nkOfBranch, nkElse:
let k = lastSon(n[i])
if k.kind != nkSym:
let structName = "_" & mangleRecFieldName(m, n[0].sym) & "_" & $i
let a = genRecordFieldsAux(m, k, rectype, check, unionPrefix & $structName & ".")
if a != nil:
var a = newRopeAppender()
genRecordFieldsAux(m, k, rectype, check, a, unionPrefix & $structName & ".")
if a != "":
if tfPacked notin rectype.flags:
unionBody.add("struct {")
else:
@@ -520,9 +523,9 @@ proc genRecordFieldsAux(m: BModule, n: PNode,
if tfPacked in rectype.flags and hasAttribute notin CC[m.config.cCompiler].props:
unionBody.addf("#pragma pack(pop)$n", [])
else:
unionBody.add(genRecordFieldsAux(m, k, rectype, check, unionPrefix))
genRecordFieldsAux(m, k, rectype, check, unionBody, unionPrefix)
else: internalError(m.config, "genRecordFieldsAux(record case branch)")
if unionBody != nil:
if unionBody != "":
result.addf("union{$n$1};$n", [unionBody])
of nkSym:
let field = n.sym
@@ -536,7 +539,7 @@ proc genRecordFieldsAux(m: BModule, n: PNode,
# have to recurse via 'getTypeDescAux'. And not doing so prevents problems
# with heavily templatized C++ code:
if not isImportedCppType(rectype):
let noAlias = if sfNoalias in field.flags: ~" NIM_NOALIAS" else: nil
let noAlias = if sfNoalias in field.flags: " NIM_NOALIAS" else: ""
let fieldType = field.loc.lode.typ.skipTypes(abstractInst)
if fieldType.kind == tyUncheckedArray:
@@ -554,7 +557,8 @@ proc genRecordFieldsAux(m: BModule, n: PNode,
else: internalError(m.config, n.info, "genRecordFieldsAux()")
proc getRecordFields(m: BModule, typ: PType, check: var IntSet): Rope =
result = genRecordFieldsAux(m, typ.n, typ, check)
result = newRopeAppender()
genRecordFieldsAux(m, typ.n, typ, check, result)
proc fillObjectFields*(m: BModule; typ: PType) =
# sometimes generic objects are not consistently merged. We patch over
@@ -582,7 +586,7 @@ proc getRecordDesc(m: BModule, typ: PType, name: Rope,
if typ.kind == tyObject:
if typ[0] == nil:
if (typ.sym != nil and sfPure in typ.sym.flags) or tfFinal in typ.flags:
if lacksMTypeField(typ):
appcg(m, result, " {$n", [])
else:
if optTinyRtti in m.config.globalOptions:
@@ -611,7 +615,7 @@ proc getRecordDesc(m: BModule, typ: PType, name: Rope,
result.addf(" {$n", [name])
let desc = getRecordFields(m, typ, check)
if desc == nil and not hasField:
if desc == "" and not hasField:
result.addf("char dummy;$n", [])
else:
result.add(desc)
@@ -622,11 +626,11 @@ proc getRecordDesc(m: BModule, typ: PType, name: Rope,
proc getTupleDesc(m: BModule, typ: PType, name: Rope,
check: var IntSet): Rope =
result = "$1 $2 {$n" % [structOrUnion(typ), name]
var desc: Rope = nil
var desc: Rope = ""
for i in 0..<typ.len:
desc.addf("$1 Field$2;$n",
[getTypeDescAux(m, typ[i], check, skField), rope(i)])
if desc == nil: result.add("char dummy;\L")
if desc == "": result.add("char dummy;\L")
else: result.add(desc)
result.add("};\L")
@@ -660,12 +664,12 @@ proc resolveStarsInCppType(typ: PType, idx, stars: int): PType =
else: result.elemType
proc getOpenArrayDesc(m: BModule, t: PType, check: var IntSet; kind: TSymKind): Rope =
let sig = hashType(t)
let sig = hashType(t, m.config)
if kind == skParam:
result = getTypeDescWeak(m, t[0], check, kind) & "*"
else:
result = cacheGetType(m.typeCache, sig)
if result == nil:
if result == "":
result = getTypeName(m, t, sig)
m.typeCache[sig] = result
let elemType = getTypeDescWeak(m, t[0], check, kind)
@@ -684,14 +688,14 @@ proc getTypeDescAux(m: BModule, origTyp: PType, check: var IntSet; kind: TSymKin
# C type generation into an analysis and a code generation phase somehow.
if t.sym != nil: useHeader(m, t.sym)
if t != origTyp and origTyp.sym != nil: useHeader(m, origTyp.sym)
let sig = hashType(origTyp)
let sig = hashType(origTyp, m.config)
defer: # defer is the simplest in this case
if isImportedType(t) and not m.typeABICache.containsOrIncl(sig):
addAbiCheck(m, t, result)
result = getTypePre(m, t, sig)
if result != nil and t.kind != tyOpenArray:
if result != "" and t.kind != tyOpenArray:
excl(check, t.id)
return
case t.kind
@@ -713,7 +717,7 @@ proc getTypeDescAux(m: BModule, origTyp: PType, check: var IntSet; kind: TSymKin
result = getTypeDescAux(m, et, check, kind) & star
else:
# no restriction! We have a forward declaration for structs
let name = getTypeForward(m, et, hashType et)
let name = getTypeForward(m, et, hashType(et, m.config))
result = name & star
m.typeCache[sig] = result
of tySequence:
@@ -722,7 +726,7 @@ proc getTypeDescAux(m: BModule, origTyp: PType, check: var IntSet; kind: TSymKin
m.typeCache[sig] = result
else:
# no restriction! We have a forward declaration for structs
let name = getTypeForward(m, et, hashType et)
let name = getTypeForward(m, et, hashType(et, m.config))
result = name & seqStar(m) & star
m.typeCache[sig] = result
pushType(m, et)
@@ -734,7 +738,7 @@ proc getTypeDescAux(m: BModule, origTyp: PType, check: var IntSet; kind: TSymKin
result = getOpenArrayDesc(m, t, check, kind)
of tyEnum:
result = cacheGetType(m.typeCache, sig)
if result == nil:
if result == "":
result = getTypeName(m, origTyp, sig)
if not (isImportedCppType(t) or
(sfImportc in t.sym.flags and t.sym.magic == mNone)):
@@ -782,12 +786,12 @@ proc getTypeDescAux(m: BModule, origTyp: PType, check: var IntSet; kind: TSymKin
# we cannot use getTypeForward here because then t would be associated
# with the name of the struct, not with the pointer to the struct:
result = cacheGetType(m.forwTypeCache, sig)
if result == nil:
if result == "":
result = getTypeName(m, origTyp, sig)
if not isImportedType(t):
addForwardStructFormat(m, structOrUnion(t), result)
m.forwTypeCache[sig] = result
assert(cacheGetType(m.typeCache, sig) == nil)
assert(cacheGetType(m.typeCache, sig) == "")
m.typeCache[sig] = result & seqStar(m)
if not isImportedType(t):
if skipTypes(t[0], typedescInst).kind != tyEmpty:
@@ -822,40 +826,42 @@ proc getTypeDescAux(m: BModule, origTyp: PType, check: var IntSet; kind: TSymKin
m.s[cfsTypes].addf("typedef $1 $2[$3];$n",
[foo, result, rope(n)])
of tyObject, tyTuple:
if isImportedCppType(t) and origTyp.kind == tyGenericInst:
let cppName = getTypeName(m, t, sig)
let tt = origTyp.skipTypes({tyDistinct})
if isImportedCppType(t) and tt.kind == tyGenericInst:
let cppNameAsRope = getTypeName(m, t, sig)
let cppName = $cppNameAsRope
var i = 0
var chunkStart = 0
template addResultType(ty: untyped) =
if ty == nil or ty.kind == tyVoid:
result.add(~"void")
result.add("void")
elif ty.kind == tyStatic:
internalAssert m.config, ty.n != nil
result.add ty.n.renderTree
else:
result.add getTypeDescAux(m, ty, check, kind)
while i < cppName.data.len:
if cppName.data[i] == '\'':
while i < cppName.len:
if cppName[i] == '\'':
var chunkEnd = i-1
var idx, stars: int
if scanCppGenericSlot(cppName.data, i, idx, stars):
result.add cppName.data.substr(chunkStart, chunkEnd)
if scanCppGenericSlot(cppName, i, idx, stars):
result.add cppName.substr(chunkStart, chunkEnd)
chunkStart = i
let typeInSlot = resolveStarsInCppType(origTyp, idx + 1, stars)
let typeInSlot = resolveStarsInCppType(tt, idx + 1, stars)
addResultType(typeInSlot)
else:
inc i
if chunkStart != 0:
result.add cppName.data.substr(chunkStart)
result.add cppName.substr(chunkStart)
else:
result = cppName & "<"
for i in 1..<origTyp.len-1:
result = cppNameAsRope & "<"
for i in 1..<tt.len-1:
if i > 1: result.add(" COMMA ")
addResultType(origTyp[i])
addResultType(tt[i])
result.add("> ")
# always call for sideeffects:
assert t.kind != tyTuple
@@ -863,13 +869,13 @@ proc getTypeDescAux(m: BModule, origTyp: PType, check: var IntSet; kind: TSymKin
# The resulting type will include commas and these won't play well
# with the C macros for defining procs such as N_NIMCALL. We must
# create a typedef for the type and use it in the proc signature:
let typedefName = ~"TY" & $sig
let typedefName = "TY" & $sig
m.s[cfsTypes].addf("typedef $1 $2;$n", [result, typedefName])
m.typeCache[sig] = typedefName
result = typedefName
else:
result = cacheGetType(m.forwTypeCache, sig)
if result == nil:
if result == "":
result = getTypeName(m, origTyp, sig)
m.forwTypeCache[sig] = result
if not isImportedType(t):
@@ -885,7 +891,9 @@ proc getTypeDescAux(m: BModule, origTyp: PType, check: var IntSet; kind: TSymKin
discard # addAbiCheck(m, t, result) # already handled elsewhere
of tySet:
# Don't use the imported name as it may be scoped: 'Foo::SomeKind'
result = $t.kind & '_' & t.lastSon.typeName & $t.lastSon.hashType
result = rope("tySet_")
t.lastSon.typeName(result)
result.add $t.lastSon.hashType(m.config)
m.typeCache[sig] = result
if not isImportedType(t):
let s = int(getSize(m.config, t))
@@ -898,7 +906,7 @@ proc getTypeDescAux(m: BModule, origTyp: PType, check: var IntSet; kind: TSymKin
result = getTypeDescAux(m, lastSon(t), check, kind)
else:
internalError(m.config, "getTypeDescAux(" & $t.kind & ')')
result = nil
result = ""
# fixes bug #145:
excl(check, t.id)
@@ -949,21 +957,12 @@ proc isReloadable(m: BModule, prc: PSym): bool =
proc isNonReloadable(m: BModule, prc: PSym): bool =
return m.hcrOn and sfNonReloadable in prc.flags
proc genProcHeader(m: BModule, prc: PSym, asPtr: bool = false): Rope =
var
rettype, params: Rope
proc genProcHeader(m: BModule, prc: PSym; result: var Rope; asPtr: bool = false) =
# using static is needed for inline procs
if lfExportLib in prc.loc.flags:
if isHeaderFile in m.flags:
result.add "N_LIB_IMPORT "
else:
result.add "N_LIB_EXPORT "
elif prc.typ.callConv == ccInline or asPtr or isNonReloadable(m, prc):
result.add "static "
elif sfImportc notin prc.flags:
result.add "N_LIB_PRIVATE "
var check = initIntSet()
fillLoc(prc.loc, locProc, prc.ast[namePos], mangleName(m, prc), OnUnknown)
fillBackendName(m, prc)
fillLoc(prc.loc, locProc, prc.ast[namePos], OnUnknown)
var rettype, params: Rope
genProcParams(m, prc.typ, rettype, params, check)
# handle the 2 options for hotcodereloading codegen - function pointer
# (instead of forward declaration) or header for function body with "_actual" postfix
@@ -974,12 +973,21 @@ proc genProcHeader(m: BModule, prc: PSym, asPtr: bool = false): Rope =
# careful here! don't access ``prc.ast`` as that could reload large parts of
# the object graph!
if prc.constraint.isNil:
if lfExportLib in prc.loc.flags:
if isHeaderFile in m.flags:
result.add "N_LIB_IMPORT "
else:
result.add "N_LIB_EXPORT "
elif prc.typ.callConv == ccInline or asPtr or isNonReloadable(m, prc):
result.add "static "
elif sfImportc notin prc.flags:
result.add "N_LIB_PRIVATE "
result.addf("$1$2($3, $4)$5",
[rope(CallingConvToStr[prc.typ.callConv]), asPtrStr, rettype, name,
params])
else:
let asPtrStr = if asPtr: (rope("(*") & name & ")") else: name
result = runtimeFormat(prc.cgDeclFrmt, [rettype, asPtrStr, params])
result.add runtimeFormat(prc.cgDeclFrmt, [rettype, asPtrStr, params])
# ------------------ type info generation -------------------------------------
@@ -1018,7 +1026,7 @@ proc genTypeInfoAuxBase(m: BModule; typ, origType: PType;
#else echo("can contain a cycle: " & typeToString(typ))
if flags != 0:
m.s[cfsTypeInit3].addf("$1.flags = $2;$n", [nameHcr, rope(flags)])
discard cgsym(m, "TNimType")
cgsym(m, "TNimType")
if isDefined(m.config, "nimTypeNames"):
var typename = typeToString(if origType.typeInst != nil: origType.typeInst
else: origType, preferName)
@@ -1026,16 +1034,16 @@ proc genTypeInfoAuxBase(m: BModule; typ, origType: PType;
typename = "anon ref object from " & m.config$origType.skipTypes(skipPtrs).sym.info
m.s[cfsTypeInit3].addf("$1.name = $2;$n",
[nameHcr, makeCString typename])
discard cgsym(m, "nimTypeRoot")
cgsym(m, "nimTypeRoot")
m.s[cfsTypeInit3].addf("$1.nextType = nimTypeRoot; nimTypeRoot=&$1;$n",
[nameHcr])
if m.hcrOn:
m.s[cfsData].addf("static TNimType* $1;$n", [name])
m.s[cfsStrData].addf("static TNimType* $1;$n", [name])
m.hcrCreateTypeInfosProc.addf("\thcrRegisterGlobal($2, \"$1\", sizeof(TNimType), NULL, (void**)&$1);$n",
[name, getModuleDllPath(m, m.module)])
else:
m.s[cfsData].addf("N_LIB_PRIVATE TNimType $1;$n", [name])
m.s[cfsStrData].addf("N_LIB_PRIVATE TNimType $1;$n", [name])
proc genTypeInfoAux(m: BModule, typ, origType: PType, name: Rope;
info: TLineInfo) =
@@ -1058,12 +1066,12 @@ proc discriminatorTableName(m: BModule, objtype: PType, d: PSym): Rope =
objtype = objtype[0].skipTypes(abstractPtrs)
if objtype.sym == nil:
internalError(m.config, d.info, "anonymous obj with discriminator")
result = "NimDT_$1_$2" % [rope($hashType(objtype)), rope(d.name.s.mangle)]
result = "NimDT_$1_$2" % [rope($hashType(objtype, m.config)), rope(d.name.s.mangle)]
proc rope(arg: Int128): Rope = rope($arg)
proc discriminatorTableDecl(m: BModule, objtype: PType, d: PSym): Rope =
discard cgsym(m, "TNimNode")
cgsym(m, "TNimNode")
var tmp = discriminatorTableName(m, objtype, d)
result = "TNimNode* $1[$2];$n" % [tmp, rope(lengthOrd(m.config, d.typ)+1)]
@@ -1098,7 +1106,7 @@ proc genObjectFields(m: BModule, typ, origType: PType, n: PNode, expr: Rope;
var tmp = discriminatorTableName(m, typ, field)
var L = lengthOrd(m.config, field.typ)
assert L > 0
if field.loc.r == nil: fillObjectFields(m, typ)
if field.loc.r == "": fillObjectFields(m, typ)
if field.loc.t == nil:
internalError(m.config, n.info, "genObjectFields")
m.s[cfsTypeInit3].addf("$1.kind = 3;$n" &
@@ -1136,7 +1144,7 @@ proc genObjectFields(m: BModule, typ, origType: PType, n: PNode, expr: Rope;
# Do not produce code for void types
if isEmptyType(field.typ): return
if field.bitsize == 0:
if field.loc.r == nil: fillObjectFields(m, typ)
if field.loc.r == "": fillObjectFields(m, typ)
if field.loc.t == nil:
internalError(m.config, n.info, "genObjectFields")
m.s[cfsTypeInit3].addf("$1.kind = 1;$n" &
@@ -1230,7 +1238,7 @@ proc genSetInfo(m: BModule, typ: PType, name: Rope; info: TLineInfo) =
assert(typ[0] != nil)
genTypeInfoAux(m, typ, typ, name, info)
var tmp = getNimNode(m)
m.s[cfsTypeInit3].addf("$1.len = $2; $1.kind = 0;$n" & "$3.node = &$1;$n",
m.s[cfsTypeInit3].addf("$1.len = $2; $1.kind = 0;$n$3.node = &$1;$n",
[tmp, rope(firstOrd(m.config, typ)), tiNameForHcr(m, name)])
proc genArrayInfo(m: BModule, typ: PType, name: Rope; info: TLineInfo) =
@@ -1255,38 +1263,34 @@ proc genDeepCopyProc(m: BModule; s: PSym; result: Rope) =
proc declareNimType(m: BModule, name: string; str: Rope, module: int) =
let nr = rope(name)
if m.hcrOn:
m.s[cfsData].addf("static $2* $1;$n", [str, nr])
m.s[cfsStrData].addf("static $2* $1;$n", [str, nr])
m.s[cfsTypeInit1].addf("\t$1 = ($3*)hcrGetGlobal($2, \"$1\");$n",
[str, getModuleDllPath(m, module), nr])
else:
m.s[cfsData].addf("extern $2 $1;$n", [str, nr])
m.s[cfsStrData].addf("extern $2 $1;$n", [str, nr])
proc genTypeInfo2Name(m: BModule; t: PType): Rope =
var res = "|"
var it = t
while it != nil:
it = it.skipTypes(skipPtrs)
if it.sym != nil:
var m = it.sym.owner
while m != nil and m.kind != skModule: m = m.owner
if m == nil or sfSystemModule in m.flags:
# produce short names for system types:
res.add it.sym.name.s
else:
var p = m.owner
if p != nil and p.kind == skPackage:
res.add p.name.s & "."
res.add m.name.s & "."
res.add it.sym.name.s
it = it.skipTypes(skipPtrs)
if it.sym != nil and tfFromGeneric notin it.flags:
var m = it.sym.owner
while m != nil and m.kind != skModule: m = m.owner
if m == nil or sfSystemModule in m.flags:
# produce short names for system types:
result = it.sym.name.s
else:
res.add $hashType(it)
res.add "|"
it = it[0]
result = makeCString(res)
var p = m.owner
if p != nil and p.kind == skPackage:
result.add p.name.s & "."
result.add m.name.s & "."
result.add it.sym.name.s
else:
result = $hashType(it, m.config)
result = makeCString(result)
proc isTrivialProc(g: ModuleGraph; s: PSym): bool {.inline.} = getBody(g, s).len == 0
proc genHook(m: BModule; t: PType; info: TLineInfo; op: TTypeAttachedOp): Rope =
proc genHook(m: BModule; t: PType; info: TLineInfo; op: TTypeAttachedOp; result: var Rope) =
let theProc = getAttachedOp(m.g.graph, t, op)
if theProc != nil and not isTrivialProc(m.g.graph, theProc):
# the prototype of a destructor is ``=destroy(x: var T)`` and that of a
@@ -1297,7 +1301,7 @@ proc genHook(m: BModule; t: PType; info: TLineInfo; op: TTypeAttachedOp): Rope =
theProc.name.s & " needs to have the 'nimcall' calling convention")
genProc(m, theProc)
result = theProc.loc.r
result.add theProc.loc.r
when false:
if not canFormAcycle(t) and op == attachedTrace:
@@ -1309,29 +1313,117 @@ proc genHook(m: BModule; t: PType; info: TLineInfo; op: TTypeAttachedOp): Rope =
# unfortunately this check is wrong for an object type that only contains
# .cursor fields like 'Node' inside 'cycleleak'.
internalError(m.config, info, "no attached trace proc found")
result = rope("NIM_NIL")
result.add rope("NIM_NIL")
proc genTypeInfoV2Impl(m: BModule, t, origType: PType, name: Rope; info: TLineInfo) =
var typeName: Rope
if t.kind in {tyObject, tyDistinct}:
if incompleteType(t):
localError(m.config, info, "request for RTTI generation for incomplete object: " &
typeToString(t))
typeName = genTypeInfo2Name(m, t)
else:
typeName = rope("NIM_NIL")
proc getObjDepth(t: PType): int16 =
var x = t
result = -1
while x != nil:
x = skipTypes(x, skipPtrs)
x = x[0]
inc(result)
discard cgsym(m, "TNimTypeV2")
m.s[cfsData].addf("N_LIB_PRIVATE TNimTypeV2 $1;$n", [name])
let destroyImpl = genHook(m, t, info, attachedDestructor)
let traceImpl = genHook(m, t, info, attachedTrace)
proc genDisplayElem(d: MD5Digest): uint32 =
result = 0
for i in 0..3:
result += uint32(d[i])
result = result shl 8
proc genDisplay(m: BModule, t: PType, depth: int): Rope =
result = Rope"{"
var x = t
var seqs = newSeq[string](depth+1)
var i = 0
while x != nil:
x = skipTypes(x, skipPtrs)
seqs[i] = $genDisplayElem(MD5Digest(hashType(x, m.config)))
x = x[0]
inc i
for i in countdown(depth, 1):
result.add seqs[i] & ", "
result.add seqs[0]
result.add "}"
proc genTypeInfoV2OldImpl(m: BModule; t, origType: PType, name: Rope; info: TLineInfo) =
cgsym(m, "TNimTypeV2")
m.s[cfsStrData].addf("N_LIB_PRIVATE TNimTypeV2 $1;$n", [name])
var flags = 0
if not canFormAcycle(t): flags = flags or 1
addf(m.s[cfsTypeInit3], "$1.destructor = (void*)$2; $1.size = sizeof($3); $1.align = NIM_ALIGNOF($3); $1.name = $4;$n; $1.traceImpl = (void*)$5; $1.flags = $6;", [
name, destroyImpl, getTypeDesc(m, t), typeName,
traceImpl, rope(flags)])
var typeEntry = newRopeAppender()
addf(typeEntry, "$1.destructor = (void*)", [name])
genHook(m, t, info, attachedDestructor, typeEntry)
addf(typeEntry, "; $1.traceImpl = (void*)", [name])
genHook(m, t, info, attachedTrace, typeEntry)
let objDepth = if t.kind == tyObject: getObjDepth(t) else: -1
if t.kind in {tyObject, tyDistinct} and incompleteType(t):
localError(m.config, info, "request for RTTI generation for incomplete object: " &
typeToString(t))
if isDefined(m.config, "nimTypeNames"):
var typeName: Rope
if t.kind in {tyObject, tyDistinct}:
typeName = genTypeInfo2Name(m, t)
else:
typeName = rope("NIM_NIL")
addf(typeEntry, "; $1.name = $2", [name, typeName])
addf(typeEntry, "; $1.size = sizeof($2); $1.align = (NI16) NIM_ALIGNOF($2); $1.depth = $3; $1.flags = $4;",
[name, getTypeDesc(m, t), rope(objDepth), rope(flags)])
if objDepth >= 0:
let objDisplay = genDisplay(m, t, objDepth)
let objDisplayStore = getTempName(m)
m.s[cfsVars].addf("static $1 $2[$3] = $4;$n", [getTypeDesc(m, getSysType(m.g.graph, unknownLineInfo, tyUInt32), skVar), objDisplayStore, rope(objDepth+1), objDisplay])
addf(typeEntry, "$1.display = $2;$n", [name, rope(objDisplayStore)])
m.s[cfsTypeInit3].add typeEntry
if t.kind == tyObject and t.len > 0 and t[0] != nil and optEnableDeepCopy in m.config.globalOptions:
discard genTypeInfoV1(m, t, info)
proc genTypeInfoV2Impl(m: BModule; t, origType: PType, name: Rope; info: TLineInfo) =
cgsym(m, "TNimTypeV2")
m.s[cfsStrData].addf("N_LIB_PRIVATE TNimTypeV2 $1;$n", [name])
var flags = 0
if not canFormAcycle(t): flags = flags or 1
var typeEntry = newRopeAppender()
addf(typeEntry, "N_LIB_PRIVATE TNimTypeV2 $1 = {", [name])
add(typeEntry, ".destructor = (void*)")
genHook(m, t, info, attachedDestructor, typeEntry)
let objDepth = if t.kind == tyObject: getObjDepth(t) else: -1
if t.kind in {tyObject, tyDistinct} and incompleteType(t):
localError(m.config, info, "request for RTTI generation for incomplete object: " &
typeToString(t))
addf(typeEntry, ", .size = sizeof($1), .align = (NI16) NIM_ALIGNOF($1), .depth = $2",
[getTypeDesc(m, t), rope(objDepth)])
if objDepth >= 0:
let objDisplay = genDisplay(m, t, objDepth)
let objDisplayStore = getTempName(m)
m.s[cfsVars].addf("static NIM_CONST $1 $2[$3] = $4;$n", [getTypeDesc(m, getSysType(m.g.graph, unknownLineInfo, tyUInt32), skVar), objDisplayStore, rope(objDepth+1), objDisplay])
addf(typeEntry, ", .display = $1", [rope(objDisplayStore)])
if isDefined(m.config, "nimTypeNames"):
var typeName: Rope
if t.kind in {tyObject, tyDistinct}:
typeName = genTypeInfo2Name(m, t)
else:
typeName = rope("NIM_NIL")
addf(typeEntry, ", .name = $1", [typeName])
add(typeEntry, ", .traceImpl = (void*)")
genHook(m, t, info, attachedTrace, typeEntry)
addf(typeEntry, ", .flags = $1};$n", [rope(flags)])
m.s[cfsVars].add typeEntry
if t.kind == tyObject and t.len > 0 and t[0] != nil and optEnableDeepCopy in m.config.globalOptions:
discard genTypeInfoV1(m, t, info)
@@ -1343,14 +1435,14 @@ proc genTypeInfoV2(m: BModule, t: PType; info: TLineInfo): Rope =
let prefixTI = if m.hcrOn: "(" else: "(&"
let sig = hashType(origType)
let sig = hashType(origType, m.config)
result = m.typeInfoMarkerV2.getOrDefault(sig)
if result != nil:
if result != "":
return prefixTI.rope & result & ")".rope
let marker = m.g.typeInfoMarkerV2.getOrDefault(sig)
if marker.str != nil:
discard cgsym(m, "TNimTypeV2")
if marker.str != "":
cgsym(m, "TNimTypeV2")
declareNimType(m, "TNimTypeV2", marker.str, marker.owner)
# also store in local type section:
m.typeInfoMarkerV2[sig] = marker.str
@@ -1364,12 +1456,15 @@ proc genTypeInfoV2(m: BModule, t: PType; info: TLineInfo): Rope =
# make sure the type info is created in the owner module
discard genTypeInfoV2(m.g.modules[owner], origType, info)
# reference the type info as extern here
discard cgsym(m, "TNimTypeV2")
cgsym(m, "TNimTypeV2")
declareNimType(m, "TNimTypeV2", result, owner)
return prefixTI.rope & result & ")".rope
m.g.typeInfoMarkerV2[sig] = (str: result, owner: owner)
genTypeInfoV2Impl(m, t, origType, result, info)
if m.compileToCpp:
genTypeInfoV2OldImpl(m, t, origType, result, info)
else:
genTypeInfoV2Impl(m, t, origType, result, info)
result = prefixTI.rope & result & ")".rope
proc openArrayToTuple(m: BModule; t: PType): PType =
@@ -1414,15 +1509,15 @@ proc genTypeInfoV1(m: BModule, t: PType; info: TLineInfo): Rope =
let prefixTI = if m.hcrOn: "(" else: "(&"
let sig = hashType(origType)
let sig = hashType(origType, m.config)
result = m.typeInfoMarker.getOrDefault(sig)
if result != nil:
if result != "":
return prefixTI.rope & result & ")".rope
let marker = m.g.typeInfoMarker.getOrDefault(sig)
if marker.str != nil:
discard cgsym(m, "TNimType")
discard cgsym(m, "TNimNode")
if marker.str != "":
cgsym(m, "TNimType")
cgsym(m, "TNimNode")
declareNimType(m, "TNimType", marker.str, marker.owner)
# also store in local type section:
m.typeInfoMarker[sig] = marker.str
@@ -1433,8 +1528,8 @@ proc genTypeInfoV1(m: BModule, t: PType; info: TLineInfo): Rope =
let old = m.g.graph.emittedTypeInfo.getOrDefault($result)
if old != FileIndex(0):
discard cgsym(m, "TNimType")
discard cgsym(m, "TNimNode")
cgsym(m, "TNimType")
cgsym(m, "TNimNode")
declareNimType(m, "TNimType", result, old.int)
return prefixTI.rope & result & ")".rope
@@ -1443,8 +1538,8 @@ proc genTypeInfoV1(m: BModule, t: PType; info: TLineInfo): Rope =
# make sure the type info is created in the owner module
discard genTypeInfoV1(m.g.modules[owner], origType, info)
# reference the type info as extern here
discard cgsym(m, "TNimType")
discard cgsym(m, "TNimNode")
cgsym(m, "TNimType")
cgsym(m, "TNimNode")
declareNimType(m, "TNimType", result, owner)
return prefixTI.rope & result & ")".rope
else:
@@ -1471,12 +1566,12 @@ proc genTypeInfoV1(m: BModule, t: PType; info: TLineInfo): Rope =
genTupleInfo(m, x, x, result, info)
of tySequence:
genTypeInfoAux(m, t, t, result, info)
if m.config.selectedGC in {gcMarkAndSweep, gcRefc, gcV2, gcGo}:
if m.config.selectedGC in {gcMarkAndSweep, gcRefc, gcGo}:
let markerProc = genTraverseProc(m, origType, sig)
m.s[cfsTypeInit3].addf("$1.marker = $2;$n", [tiNameForHcr(m, result), markerProc])
of tyRef:
genTypeInfoAux(m, t, t, result, info)
if m.config.selectedGC in {gcMarkAndSweep, gcRefc, gcV2, gcGo}:
if m.config.selectedGC in {gcMarkAndSweep, gcRefc, gcGo}:
let markerProc = genTraverseProc(m, origType, sig)
m.s[cfsTypeInit3].addf("$1.marker = $2;$n", [tiNameForHcr(m, result), markerProc])
of tyPtr, tyRange, tyUncheckedArray: genTypeInfoAux(m, t, t, result, info)

View File

@@ -13,6 +13,9 @@ import
ast, types, hashes, strutils, msgs, wordrecg,
platform, trees, options, cgendata
when defined(nimPreviewSlimSystem):
import std/assertions
proc getPragmaStmt*(n: PNode, w: TSpecialWord): PNode =
case n.kind
of nkStmtList:
@@ -50,7 +53,7 @@ proc hashString*(conf: ConfigRef; s: string): BiggestInt =
a = a + (a shl 3)
a = a xor (a shr 11)
a = a + (a shl 15)
result = cast[Hash](a)
result = cast[Hash](uint(a))
template getUniqueType*(key: PType): PType = key

File diff suppressed because it is too large Load Diff

View File

@@ -16,7 +16,6 @@ import
type
TLabel* = Rope # for the C generator a label is just a rope
TCFileSection* = enum # the sections a generated C file consists of
cfsMergeInfo, # section containing merge information
cfsHeaders, # section for C include file headers
cfsFrameDefines # section for nim frame macros
cfsForwardTypes, # section for C forward typedefs
@@ -24,21 +23,17 @@ type
cfsSeqTypes, # section for sequence types only
# this is needed for strange type generation
# reasons
cfsFieldInfo, # section for field information
cfsTypeInfo, # section for type information (ag ABI checks)
cfsProcHeaders, # section for C procs prototypes
cfsStrData, # section for constant string literals
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
cfsTypeInit1, # section 1 for declarations of type information
cfsTypeInit2, # section 2 for init of type information
cfsTypeInit3, # section 3 for init of type information
cfsDebugInit, # section for init of debug information
cfsDynLibInit, # section for init of dynamic library binding
cfsDynLibDeinit # section for deinitialization of dynamic
# libraries
TCTypeKind* = enum # describes the type kind of a C type
ctVoid, ctChar, ctBool,
ctInt, ctInt8, ctInt16, ctInt32, ctInt64,
@@ -91,6 +86,7 @@ type
options*: TOptions # options that should be used for code
# generation; this is the same as prc.options
# unless prc == nil
optionsStack*: seq[TOptions]
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
@@ -99,6 +95,7 @@ type
withinTryWithExcept*: int # required for goto based exception handling
withinBlockLeaveActions*: int # complex to explain
sigConflicts*: CountTable[string]
inUncheckedAssignSection*: int
TTypeSeq* = seq[PType]
TypeCache* = Table[SigHash, Rope]
@@ -176,6 +173,7 @@ type
template config*(m: BModule): ConfigRef = m.g.config
template config*(p: BProc): ConfigRef = p.module.g.config
template vccAndC*(p: BProc): bool = p.module.config.cCompiler == ccVcc and p.module.config.backend == backendC
proc includeHeader*(this: BModule; header: string) =
if not this.headerFiles.contains header:
@@ -189,13 +187,18 @@ proc procSec*(p: BProc, s: TCProcSection): var Rope {.inline.} =
# top level proc sections
result = p.blocks[0].sections[s]
proc initBlock*(): TBlock =
result = TBlock()
for i in low(result.sections)..high(result.sections):
result.sections[i] = newRopeAppender()
proc newProc*(prc: PSym, module: BModule): BProc =
new(result)
result.prc = prc
result.module = module
result.options = if prc != nil: prc.options
else: module.config.options
newSeq(result.blocks, 1)
result.blocks = @[initBlock()]
result.nestedTryStmts = @[]
result.finallySafePoints = @[]
result.sigConflicts = initCountTable[string]()

View File

@@ -11,7 +11,11 @@
import
intsets, options, ast, msgs, idents, renderer, types, magicsys,
sempass2, strutils, modulegraphs, lineinfos
sempass2, modulegraphs, lineinfos
when defined(nimPreviewSlimSystem):
import std/assertions
proc genConv(n: PNode, d: PType, downcast: bool; conf: ConfigRef): PNode =
var dest = skipTypes(d, abstractPtrs)
@@ -46,6 +50,7 @@ proc methodCall*(n: PNode; conf: ConfigRef): PNode =
# replace ordinary method by dispatcher method:
let disp = getDispatcher(result[0].sym)
if disp != nil:
result[0].typ = disp.typ
result[0].sym = disp
# change the arguments to up/downcasts to fit the dispatcher's parameters:
for i in 1..<result.len:
@@ -119,7 +124,7 @@ proc createDispatcher(s: PSym; g: ModuleGraph; idgen: IdGenerator): PSym =
if disp.typ.callConv == ccInline: disp.typ.callConv = ccNimCall
disp.ast = copyTree(s.ast)
disp.ast[bodyPos] = newNodeI(nkEmpty, s.info)
disp.loc.r = nil
disp.loc.r = ""
if s.typ[0] != nil:
if disp.ast.len > resultPos:
disp.ast[resultPos].sym = copySym(s.ast[resultPos].sym, nextSymId(idgen))
@@ -143,23 +148,6 @@ proc fixupDispatcher(meth, disp: PSym; conf: ConfigRef) =
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.
when declared(TLockLevel):
proc `<`(a, b: TLockLevel): bool {.borrow.}
proc `==`(a, b: TLockLevel): bool {.borrow.}
if disp.typ.lockLevel == UnspecifiedLockLevel:
disp.typ.lockLevel = meth.typ.lockLevel
elif meth.typ.lockLevel != UnspecifiedLockLevel and
meth.typ.lockLevel != disp.typ.lockLevel:
message(conf, meth.info, warnLockLevel,
"method has lock level $1, but another method has $2" %
[$meth.typ.lockLevel, $disp.typ.lockLevel])
# XXX The following code silences a duplicate warning in
# checkMethodeffects() in sempass2.nim for now.
if disp.typ.lockLevel < meth.typ.lockLevel:
disp.typ.lockLevel = meth.typ.lockLevel
proc methodDef*(g: ModuleGraph; idgen: IdGenerator; s: PSym) =
var witness: PSym
for i in 0..<g.methods.len:

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
@@ -133,6 +136,9 @@ import
renderer, magicsys, lowerings, lambdalifting, modulegraphs, lineinfos,
tables, options
when defined(nimPreviewSlimSystem):
import std/assertions
type
Ctx = object
g: ModuleGraph
@@ -712,7 +718,7 @@ proc lowerStmtListExprs(ctx: var Ctx, n: PNode, needsSplit: var bool): PNode =
n[^1] = ex
result.add(n)
of nkAsgn, nkFastAsgn:
of nkAsgn, nkFastAsgn, nkSinkAsgn:
var ns = false
for i in 0..<n.len:
n[i] = ctx.lowerStmtListExprs(n[i], ns)
@@ -804,7 +810,10 @@ 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()
@@ -813,11 +822,20 @@ 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, ctx.idgen), info),
ctx.newTmpResultAccess())
let retStmt =
if ctx.nearestFinally == 0:
# last finally, we can return
let retValue = if ctx.fn.typ[0].isNil:
ctx.g.emptyNode
else:
newTree(nkFastAsgn,
newSymNode(getClosureIterResult(ctx.g, ctx.fn, ctx.idgen), info),
ctx.newTmpResultAccess())
newTree(nkReturnStmt, retValue)
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)
@@ -850,7 +868,7 @@ proc transformReturnsInTry(ctx: var Ctx, n: PNode): PNode =
if n[0].kind != nkEmpty:
let asgnTmpResult = newNodeI(nkAsgn, n.info)
asgnTmpResult.add(ctx.newTmpResultAccess())
let x = if n[0].kind in {nkAsgn, nkFastAsgn}: n[0][1] else: n[0]
let x = if n[0].kind in {nkAsgn, nkFastAsgn, nkSinkAsgn}: n[0][1] else: n[0]
asgnTmpResult.add(x)
result.add(asgnTmpResult)
@@ -861,6 +879,13 @@ 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:
n[i] = ctx.transformReturnsInTry(n[i])
@@ -1130,7 +1155,7 @@ proc newArrayType(g: ModuleGraph; n: int, t: PType; idgen: IdGenerator; owner: P
result = newType(tyArray, nextTypeId(idgen), owner)
let rng = newType(tyRange, nextTypeId(idgen), owner)
rng.n = newTree(nkRange, g.newIntLit(owner.info, 0), g.newIntLit(owner.info, n))
rng.n = newTree(nkRange, g.newIntLit(owner.info, 0), g.newIntLit(owner.info, n - 1))
rng.rawAddSon(t)
result.rawAddSon(rng)
@@ -1347,20 +1372,24 @@ proc preprocess(c: var PreprocessContext; n: PNode): PNode =
# 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
var didAddSomething = false
if f.kind == nkFinally:
c.finallys.add f.lastSon
didAddSomething = true
for i in 0 ..< n.len:
result[i] = preprocess(c, n[i])
if f.kind == nkFinally:
if didAddSomething:
discard c.finallys.pop()
of nkWhileStmt, nkBlockStmt:
if n.hasYields == false: return n
c.blocks.add((n, c.finallys.len))
for i in 0 ..< n.len:
result[i] = preprocess(c, n[i])
@@ -1384,7 +1413,7 @@ proc preprocess(c: var PreprocessContext; n: PNode): PNode =
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, idgen: c.idgen)
result.add freshVars(preprocess(c, c.finallys[i]), vars)
result.add freshVars(copyTree(c.finallys[i]), vars)
c.idgen = vars.idgen
result.add n
of nkSkip: discard

View File

@@ -64,7 +64,8 @@ proc loadConfigsAndProcessCmdLine*(self: NimProg, cache: IdentCache; conf: Confi
if conf.cmd == cmdNimscript: return false
# now process command line arguments again, because some options in the
# command line can overwrite the config file's settings
extccomp.initVars(conf)
if conf.backend != backendJs: # bug #19059
extccomp.initVars(conf)
self.processCmdLine(passCmd2, "", conf)
if conf.cmd == cmdNone:
rawMessage(conf, errGenerated, "command missing")

View File

@@ -31,6 +31,9 @@ import
from ast import setUseIc, eqTypeFlags, tfGcSafe, tfNoSideEffect
when defined(nimPreviewSlimSystem):
import std/assertions
# but some have deps to imported modules. Yay.
bootSwitch(usedTinyC, hasTinyCBackend, "-d:tinyc")
bootSwitch(usedFFI, hasFFI, "-d:nimHasLibFFI")
@@ -113,7 +116,7 @@ const
errInvalidCmdLineOption = "invalid command line option: '$1'"
errOnOrOffExpectedButXFound = "'on' or 'off' expected, but '$1' found"
errOnOffOrListExpectedButXFound = "'on', 'off' or 'list' expected, but '$1' found"
errOffHintsError = "'off', 'hint' or 'error' expected, but '$1' found"
errOffHintsError = "'off', 'hint', 'error' or 'usages' expected, but '$1' found"
proc invalidCmdLineOption(conf: ConfigRef; pass: TCmdLinePass, switch: string, info: TLineInfo) =
if switch == " ": localError(conf, info, errInvalidCmdLineOption % "-")
@@ -238,7 +241,7 @@ const
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"
errInvalidExceptionSystem = "'goto', 'setjmp', 'cpp' or 'quirky' expected, but '$1' found"
template warningOptionNoop(switch: string) =
warningDeprecated(conf, info, "'$#' is deprecated, now a noop" % switch)
@@ -248,7 +251,7 @@ template deprecatedAlias(oldName, newName: string) =
proc testCompileOptionArg*(conf: ConfigRef; switch, arg: string, info: TLineInfo): bool =
case switch.normalize
of "gc":
of "gc", "mm":
case arg.normalize
of "boehm": result = conf.selectedGC == gcBoehm
of "refc": result = conf.selectedGC == gcRefc
@@ -259,7 +262,6 @@ proc testCompileOptionArg*(conf: ConfigRef; switch, arg: string, info: TLineInfo
of "go": result = conf.selectedGC == gcGo
of "none": result = conf.selectedGC == gcNone
of "stack", "regions": result = conf.selectedGC == gcRegions
of "v2", "generational": warningOptionNoop(arg)
else: localError(conf, info, errNoneBoehmRefcExpectedButXFound % arg)
of "opt":
case arg.normalize
@@ -324,6 +326,7 @@ proc testCompileOption*(conf: ConfigRef; switch: string, info: TLineInfo): bool
of "run", "r": result = contains(conf.globalOptions, optRun)
of "symbolfiles": result = conf.symbolFiles != disabledSf
of "genscript": result = contains(conf.globalOptions, optGenScript)
of "gencdeps": result = contains(conf.globalOptions, optGenCDeps)
of "threads": result = contains(conf.globalOptions, optThreads)
of "tlsemulation": result = contains(conf.globalOptions, optTlsEmulation)
of "implicitstatic": result = contains(conf.options, optImplicitStatic)
@@ -332,6 +335,7 @@ proc testCompileOption*(conf: ConfigRef; switch: string, info: TLineInfo): bool
result = contains(conf.options, optTrMacros)
of "excessivestacktrace": result = contains(conf.globalOptions, optExcessiveStackTrace)
of "nilseqs", "nilchecks", "taintmode": warningOptionNoop(switch)
of "panics": result = contains(conf.globalOptions, optPanics)
else: invalidCmdLineOption(conf, passCmd1, switch, info)
proc processPath(conf: ConfigRef; path: string, info: TLineInfo,
@@ -446,6 +450,8 @@ proc parseCommand*(command: string): Command =
of "doc2", "doc": cmdDoc
of "doc2tex": cmdDoc2tex
of "rst2html": cmdRst2html
of "md2tex": cmdMd2tex
of "md2html": cmdMd2html
of "rst2tex": cmdRst2tex
of "jsondoc0": cmdJsondoc0
of "jsondoc2", "jsondoc": cmdJsondoc
@@ -477,7 +483,8 @@ proc setCommandEarly*(conf: ConfigRef, command: string) =
# command early customizations
# must be handled here to honor subsequent `--hint:x:on|off`
case conf.cmd
of cmdRst2html, cmdRst2tex: # xxx see whether to add others: cmdGendepend, etc.
of cmdRst2html, cmdRst2tex, cmdMd2html, cmdMd2tex:
# xxx see whether to add others: cmdGendepend, etc.
conf.foreignPackageNotes = {hintSuccessX}
else:
conf.foreignPackageNotes = foreignPackageNotesDefault
@@ -497,6 +504,87 @@ proc specialDefine(conf: ConfigRef, key: string; pass: TCmdLinePass) =
optOverflowCheck, optAssert, optStackTrace, optLineTrace, optLineDir}
conf.globalOptions.excl {optCDebug}
proc initOrcDefines*(conf: ConfigRef) =
conf.selectedGC = gcOrc
defineSymbol(conf.symbols, "gcorc")
defineSymbol(conf.symbols, "gcdestructors")
incl conf.globalOptions, optSeqDestructors
incl conf.globalOptions, optTinyRtti
defineSymbol(conf.symbols, "nimSeqsV2")
defineSymbol(conf.symbols, "nimV2")
if conf.exc == excNone and conf.backend != backendCpp:
conf.exc = excGoto
proc registerArcOrc(pass: TCmdLinePass, conf: ConfigRef, isOrc: bool) =
if isOrc:
conf.selectedGC = gcOrc
defineSymbol(conf.symbols, "gcorc")
else:
conf.selectedGC = gcArc
defineSymbol(conf.symbols, "gcarc")
defineSymbol(conf.symbols, "gcdestructors")
incl conf.globalOptions, optSeqDestructors
incl conf.globalOptions, optTinyRtti
if pass in {passCmd2, passPP}:
defineSymbol(conf.symbols, "nimSeqsV2")
defineSymbol(conf.symbols, "nimV2")
if conf.exc == excNone and conf.backend != backendCpp:
conf.exc = excGoto
proc unregisterArcOrc(conf: ConfigRef) =
undefSymbol(conf.symbols, "gcdestructors")
undefSymbol(conf.symbols, "gcarc")
undefSymbol(conf.symbols, "gcorc")
undefSymbol(conf.symbols, "nimSeqsV2")
undefSymbol(conf.symbols, "nimV2")
excl conf.globalOptions, optSeqDestructors
excl conf.globalOptions, optTinyRtti
proc processMemoryManagementOption(switch, arg: string, pass: TCmdLinePass,
info: TLineInfo; conf: ConfigRef) =
if conf.backend == backendJs: return # for: bug #16033
expectArg(conf, switch, arg, pass, info)
if pass in {passCmd2, passPP}:
case arg.normalize
of "boehm":
unregisterArcOrc(conf)
conf.selectedGC = gcBoehm
defineSymbol(conf.symbols, "boehmgc")
incl conf.globalOptions, optTlsEmulation # Boehm GC doesn't scan the real TLS
of "refc":
unregisterArcOrc(conf)
defineSymbol(conf.symbols, "gcrefc")
conf.selectedGC = gcRefc
of "markandsweep":
unregisterArcOrc(conf)
conf.selectedGC = gcMarkAndSweep
defineSymbol(conf.symbols, "gcmarkandsweep")
of "destructors", "arc":
registerArcOrc(pass, conf, false)
of "orc":
registerArcOrc(pass, conf, true)
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":
unregisterArcOrc(conf)
conf.selectedGC = gcGo
defineSymbol(conf.symbols, "gogc")
of "none":
unregisterArcOrc(conf)
conf.selectedGC = gcNone
defineSymbol(conf.symbols, "nogc")
of "stack", "regions":
unregisterArcOrc(conf)
conf.selectedGC = gcRegions
defineSymbol(conf.symbols, "gcregions")
else: localError(conf, info, errNoneBoehmRefcExpectedButXFound % arg)
proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
conf: ConfigRef) =
var
@@ -561,6 +649,8 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
of "backend", "b":
let backend = parseEnum(arg.normalize, TBackend.default)
if backend == TBackend.default: localError(conf, info, "invalid backend: '$1'" % arg)
if backend == backendJs: # bug #21209
conf.globalOptions.excl {optThreadAnalysis, optThreads}
conf.backend = backend
of "doccmd": conf.docCmd = arg
of "define", "d":
@@ -597,59 +687,10 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
of "project":
processOnOffSwitchG(conf, {optWholeProject, optGenIndex}, arg, pass, info)
of "gc":
if conf.backend == backendJs: return # for: bug #16033
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 "markandsweep":
conf.selectedGC = gcMarkAndSweep
defineSymbol(conf.symbols, "gcmarkandsweep")
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")
if conf.exc == excNone and conf.backend != backendCpp:
conf.exc = excGoto
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")
if conf.exc == excNone and conf.backend != backendCpp:
conf.exc = excGoto
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")
of "none":
conf.selectedGC = gcNone
defineSymbol(conf.symbols, "nogc")
of "stack", "regions":
conf.selectedGC = gcRegions
defineSymbol(conf.symbols, "gcregions")
of "v2": warningOptionNoop(arg)
else: localError(conf, info, errNoneBoehmRefcExpectedButXFound % arg)
warningDeprecated(conf, info, "`gc:option` is deprecated; use `mm:option` instead")
processMemoryManagementOption(switch, arg, pass, info, conf)
of "mm":
processMemoryManagementOption(switch, arg, pass, info, conf)
of "warnings", "w":
if processOnOffSwitchOrList(conf, {optWarns}, arg, pass, info): listWarnings(conf)
of "warning": processSpecificNote(arg, wWarning, pass, info, switch, conf)
@@ -717,7 +758,7 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
of "linedir": processOnOffSwitch(conf, {optLineDir}, arg, pass, info)
of "assertions", "a": processOnOffSwitch(conf, {optAssert}, arg, pass, info)
of "threads":
if conf.backend == backendJs: discard
if conf.backend == backendJs or conf.cmd == cmdNimscript: discard
else: processOnOffSwitchG(conf, {optThreads}, arg, pass, info)
#if optThreads in conf.globalOptions: conf.setNote(warnGcUnsafe)
of "tlsemulation": processOnOffSwitchG(conf, {optTlsEmulation}, arg, pass, info)
@@ -776,12 +817,18 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
of "clib":
expectArg(conf, switch, arg, pass, info)
if pass in {passCmd2, passPP}:
conf.cLinkedLibs.add processPath(conf, arg, info).string
conf.cLinkedLibs.add arg
of "header":
if conf != nil: conf.headerFile = arg
incl(conf.globalOptions, optGenIndex)
of "index":
processOnOffSwitchG(conf, {optGenIndex}, arg, pass, info)
case arg.normalize
of "", "on": conf.globalOptions.incl {optGenIndex}
of "only": conf.globalOptions.incl {optGenIndexOnly, optGenIndex}
of "off": conf.globalOptions.excl {optGenIndex, optGenIndexOnly}
else: localError(conf, info, errOnOrOffExpectedButXFound % arg)
of "noimportdoc":
processOnOffSwitchG(conf, {optNoImportdoc}, arg, pass, info)
of "import":
expectArg(conf, switch, arg, pass, info)
if pass in {passCmd2, passPP}:
@@ -876,6 +923,8 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
if switch.normalize == "gendeps": deprecatedAlias(switch, "genscript")
processOnOffSwitchG(conf, {optGenScript}, arg, pass, info)
processOnOffSwitchG(conf, {optCompileOnly}, arg, pass, info)
of "gencdeps":
processOnOffSwitchG(conf, {optGenCDeps}, arg, pass, info)
of "colors": processOnOffSwitchG(conf, {optUseColors}, arg, pass, info)
of "lib":
expectArg(conf, switch, arg, pass, info)
@@ -885,8 +934,9 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
splitSwitch(conf, arg, key, val, pass, info)
os.putEnv(key, val)
of "cc":
expectArg(conf, switch, arg, pass, info)
setCC(conf, arg, info)
if conf.backend != backendJs: # bug #19330
expectArg(conf, switch, arg, pass, info)
setCC(conf, arg, info)
of "track":
expectArg(conf, switch, arg, pass, info)
track(conf, arg, info)
@@ -958,6 +1008,9 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
expectNoArg(conf, switch, arg, pass, info)
conf.exc = low(ExceptionSystem)
defineSymbol(conf.symbols, "noCppExceptions")
of "shownonexports":
expectNoArg(conf, switch, arg, pass, info)
showNonExportedFields(conf)
of "exceptions":
case arg.normalize
of "cpp": conf.exc = excCpp
@@ -1027,6 +1080,10 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
defineSymbol(conf.symbols, "NimMajor", "1")
defineSymbol(conf.symbols, "NimMinor", "2")
conf.globalOptions.incl optNimV12Emulation
of "1.6":
defineSymbol(conf.symbols, "NimMajor", "1")
defineSymbol(conf.symbols, "NimMinor", "6")
conf.globalOptions.incl optNimV16Emulation
else:
localError(conf, info, "unknown Nim version; currently supported values are: `1.0`, `1.2`")
# always be compatible with 1.x.100:
@@ -1051,7 +1108,8 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
processOnOffSwitchG(conf, {optEnableDeepCopy}, arg, pass, info)
of "": # comes from "-" in for example: `nim c -r -` (gets stripped from -)
handleStdinInput(conf)
of "nilseqs", "nilchecks", "mainmodule", "m", "symbol", "taintmode", "cs", "deadcodeelim": warningOptionNoop(switch)
of "nilseqs", "nilchecks", "symbol", "taintmode", "cs", "deadcodeelim": warningOptionNoop(switch)
of "nimmainprefix": conf.nimMainPrefix = arg
else:
if strutils.find(switch, '.') >= 0: options.setConfigVar(conf, switch, arg)
else: invalidCmdLineOption(conf, pass, switch, info)
@@ -1088,6 +1146,8 @@ proc processArgument*(pass: TCmdLinePass; p: OptParser;
else:
if pass == passCmd1: config.commandArgs.add p.key
if argsCount == 1:
if p.key.endsWith(".nims"):
incl(config.globalOptions, optWasNimscript)
# support UNIX style filenames everywhere for portable build scripts:
if config.projectName.len == 0:
config.projectName = unixToNativePath(p.key)

View File

@@ -15,6 +15,9 @@ import ast, astalgo, semdata, lookups, lineinfos, idents, msgs, renderer, types,
from magicsys import addSonSkipIntLit
when defined(nimPreviewSlimSystem):
import std/assertions
const
logBindings = false
@@ -58,6 +61,8 @@ proc semConceptDecl(c: PContext; n: PNode): PNode =
for i in 0..<n.len-1:
result[i] = n[i]
result[^1] = semConceptDecl(c, n[^1])
of nkCommentStmt:
discard
else:
localError(c.config, n.info, "unexpected construct in the new-styled concept: " & renderTree(n))
result = n
@@ -269,7 +274,7 @@ proc matchSym(c: PContext; candidate: PSym, n: PNode; m: var MatchCon): bool =
proc matchSyms(c: PContext, n: PNode; kinds: set[TSymKind]; m: var MatchCon): bool =
## Walk the current scope, extract candidates which the same name as 'n[namePos]',
## 'n' is the nkProcDef or similar from the concept that we try to match.
let candidates = searchInScopesFilterBy(c, n[namePos].sym.name, kinds)
let candidates = searchInScopesAllCandidatesFilterBy(c, n[namePos].sym.name, kinds)
for candidate in candidates:
#echo "considering ", typeToString(candidate.typ), " ", candidate.magic
m.magic = candidate.magic
@@ -311,7 +316,7 @@ proc conceptMatch*(c: PContext; concpt, arg: PType; bindings: var TIdTable; invo
## concept's requirements. If so, we return true and fill the 'bindings' with pairs of
## (typeVar, instance) pairs. ('typeVar' is usually simply written as a generic 'T'.)
## 'invocation' can be nil for atomic concepts. For non-atomic concepts, it contains the
## 'C[S, T]' parent type that we look for. We need this because we need to store bindings
## `C[S, T]` parent type that we look for. We need this because we need to store bindings
## for 'S' and 'T' inside 'bindings' on a successful match. It is very important that
## we do not add any bindings at all on an unsuccessful match!
var m = MatchCon(inferred: @[], potentialImplementation: arg)

View File

@@ -25,7 +25,7 @@ proc undefSymbol*(symbols: StringTableRef; symbol: string) =
# result = if isDefined(symbol): gSymbols[symbol] else: nil
iterator definedSymbolNames*(symbols: StringTableRef): string =
for key, val in pairs(symbols):
for key in keys(symbols):
yield key
proc countDefinedSymbols*(symbols: StringTableRef): int =
@@ -70,7 +70,7 @@ proc initDefines*(symbols: StringTableRef) =
defineSymbol("nimVmExportFixed") # deadcode
defineSymbol("nimHasSymOwnerInMacro") # deadcode
defineSymbol("nimNewRuntime") # deadcode
defineSymbol("nimIncrSeqV3") # xxx: turn this into deadcode
defineSymbol("nimIncrSeqV3") # deadcode
defineSymbol("nimAshr") # deadcode
defineSymbol("nimNoNilSeqs") # deadcode
defineSymbol("nimNoNilSeqs2") # deadcode
@@ -84,10 +84,24 @@ proc initDefines*(symbols: StringTableRef) =
defineSymbol("nimHasSignatureHashInMacro") # deadcode
defineSymbol("nimHasDefault") # deadcode
defineSymbol("nimMacrosSizealignof") # deadcode
defineSymbol("nimNoZeroExtendMagic") # deadcode
defineSymbol("nimMacrosGetNodeId") # deadcode
defineSymbol("nimFixedForwardGeneric") # deadcode
defineSymbol("nimToOpenArrayCString") # deadcode
defineSymbol("nimHasUsed") # deadcode
defineSymbol("nimnomagic64") # deadcode
defineSymbol("nimNewShiftOps") # deadcode
defineSymbol("nimHasCursor") # deadcode
defineSymbol("nimAlignPragma") # deadcode
defineSymbol("nimHasExceptionsQuery") # deadcode
defineSymbol("nimHasIsNamedTuple") # deadcode
defineSymbol("nimHashOrdinalFixed") # deadcode
defineSymbol("nimHasSinkInference") # deadcode
defineSymbol("nimNewIntegerOps") # deadcode
defineSymbol("nimHasInvariant") # deadcode
# > 0.20.0
defineSymbol("nimNoZeroExtendMagic")
defineSymbol("nimMacrosGetNodeId")
for f in Feature:
defineSymbol("nimHas" & $f)
@@ -98,31 +112,18 @@ proc initDefines*(symbols: StringTableRef) =
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("nimHasLibFFIEnabled") # deadcode
defineSymbol("nimHasSinkInference")
defineSymbol("nimNewIntegerOps")
defineSymbol("nimHasInvariant")
defineSymbol("nimHasStacktraceMsgs")
defineSymbol("nimHasStacktraceMsgs") # deadcode
defineSymbol("nimDoesntTrackDefects")
defineSymbol("nimHasLentIterators")
defineSymbol("nimHasDeclaredMagic")
defineSymbol("nimHasStacktracesModule")
defineSymbol("nimHasLentIterators") # deadcode
defineSymbol("nimHasDeclaredMagic") # deadcode
defineSymbol("nimHasStacktracesModule") # deadcode
defineSymbol("nimHasEffectTraitsModule")
defineSymbol("nimHasCastPragmaBlocks")
defineSymbol("nimHasDeclaredLocs")
@@ -133,8 +134,23 @@ proc initDefines*(symbols: StringTableRef) =
defineSymbol("nimHasCustomLiterals")
defineSymbol("nimHasUnifiedTuple")
defineSymbol("nimHasIterable")
defineSymbol("nimHasTypeofVoid")
defineSymbol("nimHasDragonBox")
defineSymbol("nimHasTypeofVoid") # deadcode
defineSymbol("nimHasDragonBox") # deadcode
defineSymbol("nimHasHintAll")
defineSymbol("nimHasTrace")
defineSymbol("nimHasEffectsOf")
defineSymbol("nimHasEnforceNoRaises")
defineSymbol("nimHasTopDownInference")
defineSymbol("nimHasTemplateRedefinitionPragma")
defineSymbol("nimHasCstringCase")
defineSymbol("nimHasCallsitePragma")
defineSymbol("nimHasAmbiguousEnumHint")
defineSymbol("nimHasWarnCastSizes")
defineSymbol("nimHasOutParams")
defineSymbol("nimHasSystemRaisesDefect")
defineSymbol("nimHasWarnUnnamedBreak")
defineSymbol("nimHasGenericDefine")
defineSymbol("nimHasDefineAliases")
defineSymbol("nimHasWarnBareExcept")

View File

@@ -54,3 +54,19 @@ proc isCompilerDebug*(): bool =
{.undef(nimCompilerDebug).}
echo 'x'
conf0.isDefined("nimCompilerDebug")
proc enteringDebugSection*() {.exportc, dynlib.} =
## Provides a way for native debuggers to enable breakpoints, watchpoints, etc
## when code of interest is being compiled.
##
## Set your debugger to break on entering `nimCompilerIsEnteringDebugSection`
## and then execute a desired command.
discard
proc exitingDebugSection*() {.exportc, dynlib.} =
## Provides a way for native debuggers to disable breakpoints, watchpoints, etc
## when code of interest is no longer being compiled.
##
## Set your debugger to break on entering `exitingDebugSection`
## and then execute a desired command.
discard

View File

@@ -9,10 +9,17 @@
# This module implements a dependency file generator.
import
options, ast, ropes, idents, passes, modulepaths, pathutils
import options, ast, ropes, pathutils, msgs, lineinfos
import modulegraphs
import std/[os, parseutils]
import strutils except addf
import std/private/globs
when defined(nimPreviewSlimSystem):
import std/assertions
from modulegraphs import ModuleGraph, PPassContext
type
TGen = object of PPassContext
@@ -28,18 +35,60 @@ proc addDependencyAux(b: Backend; importing, imported: string) =
b.dotGraph.addf("\"$1\" -> \"$2\";$n", [rope(importing), rope(imported)])
# s1 -> s2_4[label="[0-9]"];
proc addDotDependency(c: PPassContext, n: PNode): PNode =
proc toNimblePath(s: string, isStdlib: bool): string =
const stdPrefix = "std/"
const pkgPrefix = "pkg/"
if isStdlib:
let sub = "lib/"
var start = s.find(sub)
if start < 0:
doAssert false
else:
start += sub.len
let base = s[start..^1]
if base.startsWith("system") or base.startsWith("std"):
result = base
else:
for dir in stdlibDirs:
if base.startsWith(dir):
return stdPrefix & base.splitFile.name
result = stdPrefix & base
else:
var sub = getEnv("NIMBLE_DIR")
if sub.len == 0:
sub = ".nimble/pkgs/"
else:
sub.add "/pkgs/"
var start = s.find(sub)
if start < 0:
result = s
else:
start += sub.len
start += skipUntil(s, '/', start)
start += 1
result = pkgPrefix & s[start..^1]
proc addDependency(c: PPassContext, g: PGen, b: Backend, n: PNode) =
doAssert n.kind == nkSym, $n.kind
let path = splitFile(toProjPath(g.config, n.sym.position.FileIndex))
let modulePath = splitFile(toProjPath(g.config, g.module.position.FileIndex))
let parent = nativeToUnixPath(modulePath.dir / modulePath.name).toNimblePath(belongsToStdlib(g.graph, g.module))
let child = nativeToUnixPath(path.dir / path.name).toNimblePath(belongsToStdlib(g.graph, n.sym))
addDependencyAux(b, parent, child)
proc addDotDependency*(c: PPassContext, n: PNode): PNode =
result = n
let g = PGen(c)
let b = Backend(g.graph.backend)
case n.kind
of nkImportStmt:
for i in 0..<n.len:
var imported = getModuleName(g.config, n[i])
addDependencyAux(b, g.module.name.s, imported)
addDependency(c, g, b, n[i])
of nkFromStmt, nkImportExceptStmt:
var imported = getModuleName(g.config, n[0])
addDependencyAux(b, g.module.name.s, imported)
addDependency(c, g, b, n[0])
of nkStmtList, nkBlockStmt, nkStmtListExpr, nkBlockExpr:
for i in 0..<n.len: discard addDotDependency(c, n[i])
else:
@@ -51,18 +100,12 @@ proc generateDot*(graph: ModuleGraph; project: AbsoluteFile) =
rope(project.splitFile.name), b.dotGraph],
changeFileExt(project, "dot"))
when not defined(nimHasSinkInference):
{.pragma: nosinks.}
proc myOpen(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext {.nosinks.} =
proc setupDependPass*(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext =
var g: PGen
new(g)
g.module = module
g.config = graph.config
g.graph = graph
if graph.backend == nil:
graph.backend = Backend(dotGraph: nil)
graph.backend = Backend(dotGraph: "")
result = g
const gendependPass* = makePass(open = myOpen, process = addDotDependency)

View File

@@ -9,37 +9,33 @@
## Data flow analysis for Nim.
## We transform the AST into a linear list of instructions first to
## make this easier to handle: There are only 2 different branching
## make this easier to handle: There are only 3 different branching
## instructions: 'goto X' is an unconditional goto, 'fork X'
## is a conditional goto (either the next instruction or 'X' can be
## taken). Exhaustive case statements are translated
## taken), 'loop X' is the only jump that jumps back.
##
## Exhaustive case statements are translated
## so that the last branch is transformed into an 'else' branch.
## ``return`` and ``break`` are all covered by 'goto'.
##
## Control flow through exception handling:
## Contrary to popular belief, exception handling doesn't cause
## many problems for this DFA representation, ``raise`` is a statement
## that ``goes to`` the outer ``finally`` or ``except`` if there is one,
## otherwise it is the same as ``return``. Every call is treated as
## a call that can potentially ``raise``. However, without a surrounding
## ``try`` we don't emit these ``fork ReturnLabel`` instructions in order
## to speed up the dataflow analysis passes.
##
## The data structures and algorithms used here are inspired by
## "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, intsets, lineinfos, renderer
import ast, intsets, lineinfos, renderer, aliasanalysis
import std/private/asciitables
when defined(nimPreviewSlimSystem):
import std/assertions
type
InstrKind* = enum
goto, fork, def, use
goto, loop, fork, def, use
Instr* = object
n*: PNode # contains the def/use location.
case kind*: InstrKind
of goto, fork: dest*: int
else: discard
of goto, fork, loop: dest*: int
of def, use:
n*: PNode # contains the def/use location.
ControlFlowGraph* = seq[Instr]
@@ -56,9 +52,10 @@ type
Con = object
code: ControlFlowGraph
inTryStmt: int
inTryStmt, interestingInstructions: int
blocks: seq[TBlock]
owner: PSym
root: PSym
proc codeListing(c: ControlFlowGraph, start = 0; last = -1): string =
# for debugging purposes
@@ -66,7 +63,7 @@ proc codeListing(c: ControlFlowGraph, start = 0; last = -1): string =
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}:
if c[i].kind in {goto, fork, loop}:
jumpTargets.incl(i+c[i].dest)
var i = start
while i <= last:
@@ -77,12 +74,12 @@ proc codeListing(c: ControlFlowGraph, start = 0; last = -1): string =
case c[i].kind
of def, use:
result.add renderTree(c[i].n)
of goto, fork:
result.add("\t#")
result.add($c[i].n.info.line)
result.add("\n")
of goto, fork, loop:
result.add "L"
result.addInt c[i].dest+i
result.add("\t#")
result.add($c[i].n.info.line)
result.add("\n")
inc i
if i in jumpTargets: result.add("L" & $i & ": End\n")
@@ -90,181 +87,13 @@ proc echoCfg*(c: ControlFlowGraph; start = 0; last = -1) {.deprecated.} =
## echos the ControlFlowGraph for debugging purposes.
echo codeListing(c, start, last).alignTable
proc forkI(c: var Con; n: PNode): TPosition =
proc forkI(c: var Con): TPosition =
result = TPosition(c.code.len)
c.code.add Instr(n: n, kind: fork, dest: 0)
c.code.add Instr(kind: fork, dest: 0)
proc gotoI(c: var Con; n: PNode): TPosition =
proc gotoI(c: var Con): TPosition =
result = TPosition(c.code.len)
c.code.add Instr(n: n, kind: goto, dest: 0)
#[
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
==============
block:
if cond: break
def(x)
use(x)
Generates:
L0: fork lab1
join L0 # patched.
goto Louter
lab1:
def x
join L0
Louter:
use x
block outer:
while a:
while b:
if foo:
if bar:
break outer # --> we need to 'join' every pushed 'fork' here
This works and then our abstract interpretation needs to deal with 'fork'
differently. It really causes a split in execution. Two threads are
"spawned" and both need to reach the 'join L' instruction. Afterwards
the abstract interpretations are joined and execution resumes single
threaded.
Abstract Interpretation
-----------------------
proc interpret(pc, state, comesFrom): state =
result = state
# we need an explicit 'create' instruction (an explicit heap), in order
# to deal with 'var x = create(); var y = x; var z = y; destroy(z)'
while true:
case pc
of fork:
let a = interpret(pc+1, result, pc)
let b = interpret(forkTarget, result, pc)
result = a ++ b # ++ is a union operation
inc pc
of join:
if joinTarget == comesFrom: return result
else: inc pc
of use X:
if not result.contains(x):
error "variable not initialized " & x
inc pc
of def X:
if not result.contains(x):
result.incl X
else:
error "overwrite of variable causes memory leak " & x
inc pc
of destroy X:
result.excl X
This is correct but still can lead to false positives:
proc p(cond: bool) =
if cond:
new(x)
otherThings()
if cond:
destroy x
Is not a leak. We should find a way to model *data* flow, not just
control flow. One solution is to rewrite the 'if' without a fork
instruction. The unstructured aspect can now be easily dealt with
the 'goto' and 'join' instructions.
proc p(cond: bool) =
L0: fork Lend
new(x)
# do not 'join' here!
Lend:
otherThings()
join L0 # SKIP THIS FOR new(x) SOMEHOW
destroy x
join L0 # but here.
But if we follow 'goto Louter' we will never come to the join point.
We restore the bindings after popping pc from the stack then there
"no" problem?!
while cond:
prelude()
if not condB: break
postlude()
--->
var setFlag = true
while cond and not setFlag:
prelude()
if not condB:
setFlag = true # BUT: Dependency
if not setFlag: # HERE
postlude()
--->
var setFlag = true
while cond and not setFlag:
prelude()
if not condB:
postlude()
setFlag = true
-------------------------------------------------
while cond:
prelude()
if more:
if not condB: break
stuffHere()
postlude()
-->
var setFlag = true
while cond and not setFlag:
prelude()
if more:
if not condB:
setFlag = false
else:
stuffHere()
postlude()
else:
postlude()
This is getting complicated. Instead we keep the whole 'join' idea but
duplicate the 'join' instructions on breaks and return exits!
]#
c.code.add Instr(kind: goto, dest: 0)
proc genLabel(c: Con): TPosition = TPosition(c.code.len)
@@ -272,8 +101,8 @@ 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)) =
c.code.add Instr(n: n, kind: goto, dest: checkedDistance(p.int - c.code.len))
proc jmpBack(c: var Con, p = TPosition(0)) =
c.code.add Instr(kind: loop, dest: checkedDistance(p.int - c.code.len))
proc patch(c: var Con, p: TPosition) =
# patch with current index
@@ -283,12 +112,12 @@ proc gen(c: var Con; n: PNode)
proc popBlock(c: var Con; oldLen: int) =
var exits: seq[TPosition]
exits.add c.gotoI(newNode(nkEmpty))
exits.add c.gotoI()
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))
exits.add c.gotoI()
for e in exits:
c.patch e
c.blocks.setLen(oldLen)
@@ -303,91 +132,29 @@ 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
when true:
proc genWhile(c: var Con; n: PNode) =
# We unroll every loop 3 times. We emulate 0, 1, 2 iterations
# through the loop. We need to prove this is correct for our
# purposes. But Herb Sutter claims it is. (Proof by authority.)
#
# EDIT: Actually, we only need to unroll 2 times
# because Nim doesn't have a way of breaking/goto-ing into
# a loop iteration. Unrolling 2 times is much better for compile
# times of nested loops than 3 times, so we do that here.
#[
while cond:
body
Becomes:
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.
So the code to generate is:
cond
fork L4 # F1
body
cond
fork L5 # F2
body
cond
fork L6 # F3
body
L6:
join F3
L5:
join F2
L4:
join F1
]#
if isTrue(n[0]):
# 'while true' is an idiom in Nim and so we produce
# better code for it:
withBlock(nil):
for i in 0..1:
c.gen(n[1])
else:
withBlock(nil):
var endings: array[2, TPosition]
for i in 0..1:
c.gen(n[0])
endings[i] = c.forkI(n)
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
# fork tmp, lab2
# body
# jmp lab1
# lab2:
let lab1 = c.genLabel
withBlock(nil):
if isTrue(n[0]):
c.gen(n[1])
c.jmpBack(n, lab1)
else:
c.gen(n[0])
forkT(n):
c.gen(n[1])
c.jmpBack(n, lab1)
template forkT(n, body) =
let lab1 = c.forkI(n)
template forkT(body) =
let lab1 = c.forkI()
body
c.patch(lab1)
proc genWhile(c: var Con; n: PNode) =
# lab1:
# cond, tmp
# fork tmp, lab2
# body
# jmp lab1
# lab2:
let lab1 = c.genLabel
withBlock(nil):
if isTrue(n[0]):
c.gen(n[1])
c.jmpBack(lab1)
else:
c.gen(n[0])
forkT:
c.gen(n[1])
c.jmpBack(lab1)
proc genIf(c: var Con, n: PNode) =
#[
@@ -426,15 +193,22 @@ proc genIf(c: var Con, n: PNode) =
]#
var endings: seq[TPosition] = @[]
let oldInteresting = c.interestingInstructions
let oldLen = c.code.len
for i in 0..<n.len:
let it = n[i]
c.gen(it[0])
if it.len == 2:
forkT(it[1]):
c.gen(it[1])
endings.add c.gotoI(it[1])
for i in countdown(endings.high, 0):
c.patch(endings[i])
forkT:
c.gen(it.lastSon)
endings.add c.gotoI()
if oldInteresting == c.interestingInstructions:
setLen c.code, oldLen
else:
for i in countdown(endings.high, 0):
c.patch(endings[i])
proc genAndOr(c: var Con; n: PNode) =
# asgn dest, a
@@ -443,7 +217,7 @@ proc genAndOr(c: var Con; n: PNode) =
# lab1:
# join F1
c.gen(n[1])
forkT(n):
forkT:
c.gen(n[2])
proc genCase(c: var Con; n: PNode) =
@@ -458,34 +232,34 @@ proc genCase(c: var Con; n: PNode) =
# elsePart
# Lend:
let isExhaustive = skipTypes(n[0].typ,
abstractVarRange-{tyTypeDesc}).kind notin {tyFloat..tyFloat128, tyString}
abstractVarRange-{tyTypeDesc}).kind notin {tyFloat..tyFloat128, tyString, tyCstring}
# we generate endings as a set of chained gotos, this is a bit awkward but it
# ensures when recursively traversing the CFG for various analysis, we don't
# artificially extended the life of each branch (for the purposes of DFA)
# beyond the minimum amount.
var endings: seq[TPosition] = @[]
c.gen(n[0])
let oldInteresting = c.interestingInstructions
let oldLen = c.code.len
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)
if endings.len != 0:
c.patch(endings[^1])
else:
forkT(it.lastSon):
forkT:
c.gen(it.lastSon)
if endings.len != 0:
c.patch(endings[^1])
endings.add c.gotoI(it.lastSon)
endings.add c.gotoI()
if oldInteresting == c.interestingInstructions:
setLen c.code, oldLen
else:
for i in countdown(endings.high, 0):
c.patch(endings[i])
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)
let lab1 = c.gotoI()
if c.blocks[i].isTryBlock:
c.blocks[i].raiseFixups.add lab1
else:
@@ -498,6 +272,7 @@ proc genBreakOrRaiseAux(c: var Con, i: int, n: PNode) =
c.blocks[i].breakFixups.add (lab1, trailingFinales)
proc genBreak(c: var Con; n: PNode) =
inc c.interestingInstructions
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:
@@ -528,9 +303,9 @@ proc genTry(c: var Con; n: PNode) =
for i in 1..<n.len:
let it = n[i]
if it.kind != nkFinally:
forkT(it):
forkT:
c.gen(it.lastSon)
endings.add c.gotoI(it)
endings.add c.gotoI()
for i in countdown(endings.high, 0):
c.patch(endings[i])
@@ -538,11 +313,12 @@ proc genTry(c: var Con; n: PNode) =
if fin.kind == nkFinally:
c.gen(fin[0])
template genNoReturn(c: var Con; n: PNode) =
template genNoReturn(c: var Con) =
# leave the graph
c.code.add Instr(n: n, kind: goto, dest: high(int) - c.code.len)
c.code.add Instr(kind: goto, dest: high(int) - c.code.len)
proc genRaise(c: var Con; n: PNode) =
inc c.interestingInstructions
gen(c, n[0])
if c.inTryStmt > 0:
for i in countdown(c.blocks.high, 0):
@@ -551,13 +327,14 @@ proc genRaise(c: var Con; n: PNode) =
return
assert false #Unreachable
else:
genNoReturn(c, n)
genNoReturn(c)
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[resultPos])
proc genReturn(c: var Con; n: PNode) =
inc c.interestingInstructions
if n[0].kind != nkEmpty:
gen(c, n[0])
else:
@@ -566,124 +343,6 @@ proc genReturn(c: var Con; n: PNode) =
const
InterestingSyms = {skVar, skResult, skLet, skParam, skForVar, skTemp}
PathKinds0 = {nkDotExpr, nkCheckedFieldExpr,
nkBracketExpr, nkDerefExpr, nkHiddenDeref,
nkAddr, nkHiddenAddr,
nkObjDownConv, nkObjUpConv}
PathKinds1 = {nkHiddenStdConv, nkHiddenSubConv}
proc skipConvDfa*(n: PNode): PNode =
result = n
while true:
case result.kind
of nkObjDownConv, nkObjUpConv:
result = result[0]
of PathKinds1:
result = result[1]
else: break
type AliasKind* = enum
yes, no, maybe
proc aliases*(obj, field: PNode): AliasKind =
# obj -> field:
# x -> x: true
# x -> x.f: true
# x.f -> x: false
# x.f -> x.f: true
# x.f -> x.v: false
# x -> x[0]: true
# x[0] -> x: false
# x[0] -> x[0]: true
# x[0] -> x[1]: false
# x -> x[i]: true
# x[i] -> x: false
# x[i] -> x[i]: maybe; Further analysis could make this return true when i is a runtime-constant
# x[i] -> x[j]: maybe; also returns maybe if only one of i or j is a compiletime-constant
template collectImportantNodes(result, n) =
var result: seq[PNode]
var n = n
while true:
case n.kind
of PathKinds0 - {nkDotExpr, nkCheckedFieldExpr, nkBracketExpr}:
n = n[0]
of PathKinds1:
n = n[1]
of nkDotExpr, nkCheckedFieldExpr, nkBracketExpr:
result.add n
n = n[0]
of nkSym:
result.add n; break
else: return no
collectImportantNodes(objImportantNodes, obj)
collectImportantNodes(fieldImportantNodes, field)
# If field is less nested than obj, then it cannot be part of/aliased by obj
if fieldImportantNodes.len < objImportantNodes.len: return no
result = yes
for i in 1..objImportantNodes.len:
# We compare the nodes leading to the location of obj and field
# with each other.
# We continue until they diverge, in which case we return no, or
# until we reach the location of obj, in which case we do not need
# to look further, since field must be part of/aliased by obj now.
# If we encounter an element access using an index which is a runtime value,
# we simply return maybe instead of yes; should further nodes not diverge.
let currFieldPath = fieldImportantNodes[^i]
let currObjPath = objImportantNodes[^i]
if currFieldPath.kind != currObjPath.kind:
return no
case currFieldPath.kind
of nkSym:
if currFieldPath.sym != currObjPath.sym: return no
of nkDotExpr:
if currFieldPath[1].sym != currObjPath[1].sym: return no
of nkCheckedFieldExpr:
if currFieldPath[0][1].sym != currObjPath[0][1].sym: return no
of nkBracketExpr:
if currFieldPath[1].kind in nkLiterals and currObjPath[1].kind in nkLiterals:
if currFieldPath[1].intVal != currObjPath[1].intVal:
return no
else:
result = maybe
else: assert false # unreachable
proc isAnalysableFieldAccess*(orig: PNode; owner: PSym): bool =
var n = orig
while true:
case n.kind
of PathKinds0 - {nkHiddenDeref, nkDerefExpr}:
n = n[0]
of PathKinds1:
n = n[1]
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
(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
{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
#
# let splited = split(move self.root, x)
# self.root = merge(splited.lower, splited.greater)
#
# could be written without the ``move self.root``. However, this would be
# wrong! Then the write barrier for the ``self.root`` assignment would
# 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 skipTrivials(c: var Con, n: PNode): PNode =
result = n
@@ -702,8 +361,9 @@ proc genUse(c: var Con; orig: PNode) =
let n = c.skipTrivials(orig)
if n.kind == nkSym:
if n.sym.kind in InterestingSyms:
c.code.add Instr(n: orig, kind: use)
if n.sym.kind in InterestingSyms and n.sym == c.root:
c.code.add Instr(kind: use, n: orig)
inc c.interestingInstructions
else:
gen(c, n)
@@ -711,7 +371,9 @@ 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)
if n.sym == c.root:
c.code.add Instr(kind: def, n: orig)
inc c.interestingInstructions
proc genCall(c: var Con; n: PNode) =
gen(c, n[0])
@@ -719,18 +381,17 @@ proc genCall(c: var Con; n: PNode) =
if t != nil: t = t.skipTypes(abstractInst)
for i in 1..<n.len:
gen(c, n[i])
when false:
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])
if t != nil and i < t.len and isOutParam(t[i]):
# 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 canRaiseConservative(n[0]):
if false: # c.inTryStmt > 0 and canRaiseConservative(n[0]):
# we generate the instruction sequence:
# fork lab1
# goto exceptionHandler (except or finally)
# lab1:
# join F1
forkT(n):
forkT:
for i in countdown(c.blocks.high, 0):
if c.blocks[i].isTryBlock:
genBreakOrRaiseAux(c, i, n)
@@ -768,11 +429,11 @@ proc gen(c: var Con; n: PNode) =
else:
genCall(c, n)
if sfNoReturn in n[0].sym.flags:
genNoReturn(c, n)
genNoReturn(c)
else:
genCall(c, n)
of nkCharLit..nkNilLit: discard
of nkAsgn, nkFastAsgn:
of nkAsgn, nkFastAsgn, nkSinkAsgn:
gen(c, n[1])
if n[0].kind in PathKinds0:
@@ -809,13 +470,32 @@ proc gen(c: var Con; n: PNode) =
of nkDefer: doAssert false, "dfa construction pass requires the elimination of 'defer'"
else: discard
proc constructCfg*(s: PSym; body: PNode): ControlFlowGraph =
when false:
proc optimizeJumps(c: var ControlFlowGraph) =
for i in 0..<c.len:
case c[i].kind
of goto, fork:
var pc = i + c[i].dest
if pc < c.len and c[pc].kind == goto:
while pc < c.len and c[pc].kind == goto:
let newPc = pc + c[pc].dest
if newPc > pc:
pc = newPc
else:
break
c[i].dest = pc - i
of loop, def, use: discard
proc constructCfg*(s: PSym; body: PNode; root: PSym): ControlFlowGraph =
## constructs a control flow graph for ``body``.
var c = Con(code: @[], blocks: @[], owner: s)
var c = Con(code: @[], blocks: @[], owner: s, root: root)
withBlock(s):
gen(c, body)
genImplicitReturn(c)
if root.kind == skResult:
genImplicitReturn(c)
when defined(gcArc) or defined(gcOrc):
result = c.code # will move
else:
shallowCopy(result, c.code)
when false:
optimizeJumps result

View File

@@ -7,22 +7,29 @@
# distribution, for details about the copyright.
#
# This is the documentation generator. Cross-references are generated
# by knowing how the anchors are going to be named.
## This is the Nim documentation generator. Cross-references are generated
## by knowing how the anchors are going to be named.
##
## .. importdoc:: ../docgen.md
##
## For corresponding users' documentation see [Nim DocGen Tools Guide].
import
ast, strutils, strtabs, algorithm, sequtils, options, msgs, os, idents,
wordrecg, syntaxes, renderer, lexer,
packages/docutils/rst, packages/docutils/rstgen,
packages/docutils/[rst, rstidx, rstgen, dochelpers],
json, xmltree, trees, types,
typesrenderer, astalgo, lineinfos, intsets,
pathutils, tables, nimpaths, renderverbatim, osproc
pathutils, tables, nimpaths, renderverbatim, osproc, packages
import packages/docutils/rstast except FileIndex, TLineInfo
from uri import encodeUrl
from std/private/globs import nativeToUnixPath
from nodejs import findNodeJs
when defined(nimPreviewSlimSystem):
import std/[assertions, syncio]
const
exportSection = skField
docCmdSkip = "skip"
@@ -44,8 +51,14 @@ type
## runnableExamples).
substitutions: seq[string] ## Variable names in `doc.item`...
sortName: string ## The string used for sorting in output
info: rstast.TLineInfo ## place where symbol was defined (for messages)
anchor: string ## e.g. HTML anchor
name: string ## short name of the symbol, not unique
## (includes backticks ` if present)
detailedName: string ## longer name like `proc search(x: int): int`
ModSection = object ## Section like Procs, Types, etc.
secItems: seq[Item] ## Pre-processed items.
secItems: Table[string, seq[Item]]
## Map basic name -> pre-processed items.
finalMarkup: string ## The items, after RST pass 2 and rendering.
ModSections = array[TSymKind, ModSection]
TocItem = object ## HTML TOC item
@@ -82,7 +95,7 @@ type
jEntriesFinal: JsonNode # final JSON after RST pass 2 and rendering
types: TStrTable
sharedState: PRstSharedState
isPureRst: bool
standaloneDoc: bool # is markup (.rst/.md) document?
conf*: ConfigRef
cache*: IdentCache
exampleCounter: int
@@ -91,12 +104,22 @@ type
thisDir*: AbsoluteDir
exampleGroups: OrderedTable[string, ExampleGroup]
wroteSupportFiles*: bool
nimToRstFid: Table[lineinfos.FileIndex, rstast.FileIndex]
## map Nim FileIndex -> RST one, it's needed because we keep them separate
PDoc* = ref TDocumentor ## Alias to type less.
proc add(dest: var ItemPre, rst: PRstNode) = dest.add ItemFragment(isRst: true, rst: rst)
proc add(dest: var ItemPre, str: string) = dest.add ItemFragment(isRst: false, str: str)
proc addRstFileIndex(d: PDoc, info: lineinfos.TLineInfo): rstast.FileIndex =
let invalid = rstast.FileIndex(-1)
result = d.nimToRstFid.getOrDefault(info.fileIndex, default = invalid)
if result == invalid:
let fname = toFullPath(d.conf, info)
result = addFilename(d.sharedState, fname)
d.nimToRstFid[info.fileIndex] = result
proc cmpDecimalsIgnoreCase(a, b: string): int =
## For sorting with correct handling of cases like 'uint8' and 'uint16'.
## Also handles leading zeros well (however note that leading zeros are
@@ -206,7 +229,7 @@ proc attachToType(d: PDoc; p: PSym): PSym =
if params.len > 0: check(0)
for i in 2..<params.len: check(i)
template declareClosures =
template declareClosures(currentFilename: AbsoluteFile, destFile: string) =
proc compilerMsgHandler(filename: string, line, col: int,
msgKind: rst.MsgKind, arg: string) {.gcsafe.} =
# translate msg kind:
@@ -214,18 +237,23 @@ template declareClosures =
case msgKind
of meCannotOpenFile: k = errCannotOpenFile
of meExpected: k = errXExpected
of meMissingClosing: k = errRstMissingClosing
of meGridTableNotImplemented: k = errRstGridTableNotImplemented
of meMarkdownIllformedTable: k = errRstMarkdownIllformedTable
of meIllformedTable: k = errRstIllformedTable
of meNewSectionExpected: k = errRstNewSectionExpected
of meGeneralParseError: k = errRstGeneralParseError
of meInvalidDirective: k = errRstInvalidDirectiveX
of meInvalidField: k = errRstInvalidField
of meFootnoteMismatch: k = errRstFootnoteMismatch
of meSandboxedDirective: k = errRstSandboxedDirective
of mwRedefinitionOfLabel: k = warnRstRedefinitionOfLabel
of mwUnknownSubstitution: k = warnRstUnknownSubstitutionX
of mwAmbiguousLink: k = warnRstAmbiguousLink
of mwBrokenLink: k = warnRstBrokenLink
of mwUnsupportedLanguage: k = warnRstLanguageXNotSupported
of mwUnsupportedField: k = warnRstFieldXNotSupported
of mwUnusedImportdoc: k = warnRstUnusedImportdoc
of mwRstStyle: k = warnRstStyle
{.gcsafe.}:
globalError(conf, newLineInfo(conf, AbsoluteFile filename, line, col), k, arg)
@@ -236,10 +264,29 @@ template declareClosures =
result = getCurrentDir() / s
if not fileExists(result): result = ""
proc parseRst(text, filename: string,
proc docgenFindRefFile(targetRelPath: string):
tuple[targetPath: string, linkRelPath: string] {.gcsafe.} =
let fromDir = splitFile(destFile).dir # dir where we reference from
let basedir = os.splitFile(currentFilename.string).dir
let outDirPath: RelativeFile =
presentationPath(conf, AbsoluteFile(basedir / targetRelPath))
# use presentationPath because `..` path can be be mangled to `_._`
result.targetPath = string(conf.outDir / outDirPath)
if not fileExists(result.targetPath):
# this can happen if targetRelPath goes to parent directory `OUTDIR/..`.
# Trying it, this may cause ambiguities, but allows us to insert
# "packages" into each other, which is actually used in Nim repo itself.
let destPath = fromDir / targetRelPath
if destPath != result.targetPath and fileExists(destPath):
result.targetPath = destPath
result.linkRelPath = relativePath(result.targetPath.splitFile.dir,
fromDir).replace('\\', '/')
proc parseRst(text: string,
line, column: int,
conf: ConfigRef, sharedState: PRstSharedState): PRstNode =
declareClosures()
result = rstParsePass1(text, line, column, sharedState)
proc getOutFile2(conf: ConfigRef; filename: RelativeFile,
@@ -253,27 +300,38 @@ proc getOutFile2(conf: ConfigRef; filename: RelativeFile,
else:
result = getOutFile(conf, filename, ext)
proc isLatexCmd(conf: ConfigRef): bool = conf.cmd in {cmdRst2tex, cmdDoc2tex}
proc isLatexCmd(conf: ConfigRef): bool =
conf.cmd in {cmdRst2tex, cmdMd2tex, cmdDoc2tex}
proc newDocumentor*(filename: AbsoluteFile; cache: IdentCache; conf: ConfigRef,
outExt: string = HtmlExt, module: PSym = nil,
isPureRst = false): PDoc =
declareClosures()
standaloneDoc = false, preferMarkdown = true,
hasToc = true): PDoc =
let destFile = getOutFile2(conf, presentationPath(conf, filename), outExt, false).string
declareClosures(currentFilename = filename, destFile = destFile)
new(result)
result.module = module
result.conf = conf
result.cache = cache
result.outDir = conf.outDir.string
result.isPureRst = isPureRst
var options= {roSupportRawDirective, roSupportMarkdown, roPreferMarkdown}
if not isPureRst: options.incl roNimFile
result.standaloneDoc = standaloneDoc
var options= {roSupportRawDirective, roSupportMarkdown, roSandboxDisabled}
if preferMarkdown:
options.incl roPreferMarkdown
if not standaloneDoc: options.incl roNimFile
# (options can be changed dynamically in `setDoctype` by `{.doctype.}`)
result.hasToc = hasToc
result.sharedState = newRstSharedState(
options, filename.string,
docgenFindFile, compilerMsgHandler)
docgenFindFile, docgenFindRefFile, compilerMsgHandler, hasToc)
initRstGenerator(result[], (if conf.isLatexCmd: outLatex else: outHtml),
conf.configVars, filename.string,
docgenFindFile, compilerMsgHandler)
if conf.configVars.hasKey("doc.googleAnalytics") and
conf.configVars.hasKey("doc.plausibleAnalytics"):
doAssert false, "Either use googleAnalytics or plausibleAnalytics"
if conf.configVars.hasKey("doc.googleAnalytics"):
result.analytics = """
<script>
@@ -287,6 +345,10 @@ proc newDocumentor*(filename: AbsoluteFile; cache: IdentCache; conf: ConfigRef,
</script>
""" % [conf.configVars.getOrDefault"doc.googleAnalytics"]
elif conf.configVars.hasKey("doc.plausibleAnalytics"):
result.analytics = """
<script defer data-domain="$1" src="https://plausible.io/js/plausible.js"></script>
""" % [conf.configVars.getOrDefault"doc.plausibleAnalytics"]
else:
result.analytics = ""
@@ -295,7 +357,7 @@ proc newDocumentor*(filename: AbsoluteFile; cache: IdentCache; conf: ConfigRef,
result.jEntriesFinal = newJArray()
initStrTable result.types
result.onTestSnippet =
proc (gen: var RstGenerator; filename, cmd: string; status: int; content: string) =
proc (gen: var RstGenerator; filename, cmd: string; status: int; content: string) {.gcsafe.} =
if conf.docCmd == docCmdSkip: return
inc(gen.id)
var d = (ptr TDocumentor)(addr gen)
@@ -314,7 +376,7 @@ proc newDocumentor*(filename: AbsoluteFile; cache: IdentCache; conf: ConfigRef,
# Make sure the destination directory exists
createDir(outp.splitFile.dir)
# Include the current file if we're parsing a nim file
let importStmt = if d.isPureRst: "" else: "import \"$1\"\n" % [d.filename.replace("\\", "/")]
let importStmt = if d.standaloneDoc: "" else: "import \"$1\"\n" % [d.filename.replace("\\", "/")]
writeFile(outp, importStmt & content)
proc interpSnippetCmd(cmd: string): string =
@@ -336,7 +398,7 @@ proc newDocumentor*(filename: AbsoluteFile; cache: IdentCache; conf: ConfigRef,
if gotten != status:
rawMessage(conf, errGenerated, "snippet failed: cmd: '$1' status: $2 expected: $3 output: $4" % [cmd, $gotten, $status, output])
result.emitted = initIntSet()
result.destFile = getOutFile2(conf, presentationPath(conf, filename), outExt, false).string
result.destFile = destFile
result.thisDir = result.destFile.AbsoluteFile.splitFile.dir
template dispA(conf: ConfigRef; dest: var string, xml, tex: string,
@@ -352,7 +414,8 @@ proc getVarIdx(varnames: openArray[string], id: string): int =
proc genComment(d: PDoc, n: PNode): PRstNode =
if n.comment.len > 0:
result = parseRst(n.comment, toFullPath(d.conf, n.info),
d.sharedState.currFileIdx = addRstFileIndex(d, n.info)
result = parseRst(n.comment,
toLinenumber(n.info),
toColumn(n.info) + DocColOffset,
d.conf, d.sharedState)
@@ -362,7 +425,7 @@ proc genRecCommentAux(d: PDoc, n: PNode): PRstNode =
result = genComment(d, n)
if result == nil:
if n.kind in {nkStmtList, nkStmtListExpr, nkTypeDef, nkConstDef,
nkObjectTy, nkRefTy, nkPtrTy, nkAsgn, nkFastAsgn, nkHiddenStdConv}:
nkObjectTy, nkRefTy, nkPtrTy, nkAsgn, nkFastAsgn, nkSinkAsgn, nkHiddenStdConv}:
# notin {nkEmpty..nkNilLit, nkEnumTy, nkTupleTy}:
for i in 0..<n.len:
result = genRecCommentAux(d, n[i])
@@ -394,9 +457,6 @@ proc getPlainDocstring(n: PNode): string =
result = getPlainDocstring(n[i])
if result.len > 0: return
proc belongsToPackage(conf: ConfigRef; module: PSym): bool =
result = module.kind == skModule and module.getnimblePkgId == conf.mainPackageId
proc externalDep(d: PDoc; module: PSym): string =
if optWholeProject in d.conf.globalOptions or d.conf.docRoot.len > 0:
let full = AbsoluteFile toFullPath(d.conf, FileIndex module.position)
@@ -452,7 +512,7 @@ proc nodeToHighlightedHtml(d: PDoc; n: PNode; result: var string;
"\\spanIdentifier{$1}", [escLit, procLink])
elif s != nil and s.kind in {skType, skVar, skLet, skConst} and
sfExported in s.flags and s.owner != nil and
belongsToPackage(d.conf, s.owner) and d.target == outHtml:
belongsToProjectPackage(d.conf, s.owner) and d.target == outHtml:
let external = externalDep(d, s.owner)
result.addf "<a href=\"$1#$2\"><span class=\"Identifier\">$3</span></a>",
[changeFileExt(external, "html"), literal,
@@ -523,7 +583,7 @@ proc runAllExamples(d: PDoc) =
proc quoted(a: string): string = result.addQuoted(a)
proc toInstantiationInfo(conf: ConfigRef, info: TLineInfo): auto =
proc toInstantiationInfo(conf: ConfigRef, info: TLineInfo): (string, int, int) =
# xxx expose in compiler/lineinfos.nim
(conf.toMsgFilename(info), info.line.int, info.col.int + ColOffset)
@@ -730,21 +790,24 @@ proc isVisible(d: PDoc; n: PNode): bool =
elif n.kind == nkPragmaExpr:
result = isVisible(d, n[0])
proc getName(d: PDoc, n: PNode, splitAfter = -1): string =
proc getName(n: PNode): string =
case n.kind
of nkPostfix: result = getName(d, n[1], splitAfter)
of nkPragmaExpr: result = getName(d, n[0], splitAfter)
of nkSym: result = esc(d.target, n.sym.renderDefinitionName, splitAfter)
of nkIdent: result = esc(d.target, n.ident.s, splitAfter)
of nkPostfix: result = getName(n[1])
of nkPragmaExpr: result = getName(n[0])
of nkSym: result = n.sym.renderDefinitionName
of nkIdent: result = n.ident.s
of nkAccQuoted:
result = esc(d.target, "`")
for i in 0..<n.len: result.add(getName(d, n[i], splitAfter))
result.add esc(d.target, "`")
result = "`"
for i in 0..<n.len: result.add(getName(n[i]))
result = "`"
of nkOpenSymChoice, nkClosedSymChoice:
result = getName(d, n[0], splitAfter)
result = getName(n[0])
else:
result = ""
proc getNameEsc(d: PDoc, n: PNode): string =
esc(d.target, getName(n))
proc getNameIdent(cache: IdentCache; n: PNode): PIdent =
case n.kind
of nkPostfix: result = getNameIdent(cache, n[1])
@@ -885,10 +948,71 @@ proc genSeeSrc(d: PDoc, path: string, line: int): string =
"path", path.string, "line", $line, "url", gitUrl,
"commit", commit, "devel", develBranch]])
proc genItem(d: PDoc, n, nameNode: PNode, k: TSymKind, docFlags: DocFlags) =
proc symbolPriority(k: TSymKind): int =
result = case k
of skMacro: -3
of skTemplate: -2
of skIterator: -1
else: 0 # including skProc which have higher priority
# documentation itself has even higher priority 1
proc getTypeKind(n: PNode): string =
case n[2].kind
of nkEnumTy: "enum"
of nkObjectTy: "object"
of nkTupleTy: "tuple"
else: ""
proc toLangSymbol(k: TSymKind, n: PNode, baseName: string): LangSymbol =
## Converts symbol info (names/types/parameters) in `n` into format
## `LangSymbol` convenient for ``rst.nim``/``dochelpers.nim``.
result.name = baseName.nimIdentNormalize
result.symKind = k.toHumanStr
if k in routineKinds:
var
paramTypes: seq[string]
renderParamTypes(paramTypes, n[paramsPos], toNormalize=true)
let paramNames = renderParamNames(n[paramsPos], toNormalize=true)
# In some rare cases (system.typeof) parameter type is not set for default:
doAssert paramTypes.len <= paramNames.len
for i in 0 ..< paramNames.len:
if i < paramTypes.len:
result.parameters.add (paramNames[i], paramTypes[i])
else:
result.parameters.add (paramNames[i], "")
result.parametersProvided = true
result.outType = renderOutType(n[paramsPos], toNormalize=true)
if k in {skProc, skFunc, skType, skIterator}:
# Obtain `result.generics`
# Use `n[miscPos]` since n[genericParamsPos] does not contain constraints
var genNode: PNode = nil
if k == skType:
genNode = n[1] # FIXME: what is index 1?
else:
if n[miscPos].kind != nkEmpty:
genNode = n[miscPos][1] # FIXME: what is index 1?
if genNode != nil:
var literal = ""
var r: TSrcGen
initTokRender(r, genNode, {renderNoBody, renderNoComments,
renderNoPragmas, renderNoProcDefs, renderExpandUsing})
var kind = tkEof
while true:
getNextTok(r, kind, literal)
if kind == tkEof:
break
if kind != tkSpaces:
result.generics.add(literal.nimIdentNormalize)
if k == skType: result.symTypeKind = getTypeKind(n)
proc genItem(d: PDoc, n, nameNode: PNode, k: TSymKind, docFlags: DocFlags, nonExports: bool = false) =
if (docFlags != kForceExport) and not isVisible(d, nameNode): return
let
name = getName(d, nameNode)
name = getName(nameNode)
nameEsc = esc(d.target, name)
var plainDocstring = getPlainDocstring(n) # call here before genRecComment!
var result = ""
var literal, plainName = ""
@@ -902,7 +1026,7 @@ proc genItem(d: PDoc, n, nameNode: PNode, k: TSymKind, docFlags: DocFlags) =
var r: TSrcGen
# Obtain the plain rendered string for hyperlink titles.
initTokRender(r, n, {renderNoBody, renderNoComments, renderDocComments,
renderNoPragmas, renderNoProcDefs})
renderNoPragmas, renderNoProcDefs, renderExpandUsing})
while true:
getNextTok(r, kind, literal)
if kind == tkEof:
@@ -915,7 +1039,12 @@ proc genItem(d: PDoc, n, nameNode: PNode, k: TSymKind, docFlags: DocFlags) =
inc(d.id)
let
plainNameEsc = esc(d.target, plainName.strip)
uniqueName = if k in routineKinds: plainNameEsc else: name
typeDescr =
if k == skType and getTypeKind(n) != "": getTypeKind(n)
else: k.toHumanStr
detailedName = typeDescr & " " & (
if k in routineKinds: plainName else: name)
uniqueName = if k in routineKinds: plainNameEsc else: nameEsc
sortName = if k in routineKinds: plainName.strip else: name
cleanPlainSymbol = renderPlainSymbolName(nameNode)
complexSymbol = complexName(k, n, cleanPlainSymbol)
@@ -923,20 +1052,36 @@ proc genItem(d: PDoc, n, nameNode: PNode, k: TSymKind, docFlags: DocFlags) =
symbolOrId = d.newUniquePlainSymbol(complexSymbol)
symbolOrIdEnc = encodeUrl(symbolOrId, usePlus = false)
deprecationMsg = genDeprecationMsg(d, pragmaNode)
rstLangSymbol = toLangSymbol(k, n, cleanPlainSymbol)
nodeToHighlightedHtml(d, n, result, {renderNoBody, renderNoComments,
renderDocComments, renderSyms}, symbolOrIdEnc)
# we generate anchors automatically for subsequent use in doc comments
let lineinfo = rstast.TLineInfo(
line: nameNode.info.line, col: nameNode.info.col,
fileIndex: addRstFileIndex(d, nameNode.info))
addAnchorNim(d.sharedState, external = false, refn = symbolOrId,
tooltip = detailedName, langSym = rstLangSymbol,
priority = symbolPriority(k), info = lineinfo)
let renderFlags =
if nonExports: {renderNoBody, renderNoComments, renderDocComments, renderSyms,
renderExpandUsing, renderNonExportedFields}
else: {renderNoBody, renderNoComments, renderDocComments, renderSyms, renderExpandUsing}
nodeToHighlightedHtml(d, n, result, renderFlags, symbolOrIdEnc)
let seeSrc = genSeeSrc(d, toFullPath(d.conf, n.info), n.info.line.int)
d.section[k].secItems.add Item(
d.section[k].secItems.mgetOrPut(cleanPlainSymbol, newSeq[Item]()).add Item(
descRst: comm,
sortName: sortName,
info: lineinfo,
anchor: symbolOrId,
detailedName: detailedName,
name: name,
substitutions: @[
"name", name, "uniqueName", uniqueName,
"uniqueName", uniqueName,
"header", result, "itemID", $d.id,
"header_plain", plainNameEsc, "itemSym", cleanPlainSymbol,
"itemSymOrID", symbolOrId, "itemSymEnc", plainSymbolEnc,
"itemSymEnc", plainSymbolEnc,
"itemSymOrIDEnc", symbolOrIdEnc, "seeSrc", seeSrc,
"deprecationMsg", deprecationMsg])
@@ -953,8 +1098,10 @@ proc genItem(d: PDoc, n, nameNode: PNode, k: TSymKind, docFlags: DocFlags) =
if e.sym.kind != skEnumField: continue
let plain = renderPlainSymbolName(e)
let symbolOrId = d.newUniquePlainSymbol(plain)
setIndexTerm(d[], external, symbolOrId, plain, nameNode.sym.name.s & '.' & plain,
xmltree.escape(getPlainDocstring(e).docstringSummary))
setIndexTerm(d[], ieNim, htmlFile = external, id = symbolOrId,
term = plain, linkTitle = nameNode.sym.name.s & '.' & plain,
linkDesc = xmltree.escape(getPlainDocstring(e).docstringSummary),
line = n.info.line.int)
d.tocSimple[k].add TocItem(
sortName: sortName,
@@ -969,25 +1116,20 @@ proc genItem(d: PDoc, n, nameNode: PNode, k: TSymKind, docFlags: DocFlags) =
"itemSymOrID", symbolOrId.replace(",", ",<wbr>"),
"itemSymOrIDEnc", symbolOrIdEnc])
# Ironically for types the complexSymbol is *cleaner* than the plainName
# because it doesn't include object fields or documentation comments. So we
# use the plain one for callable elements, and the complex for the rest.
var linkTitle = changeFileExt(extractFilename(d.filename), "") & ": "
if n.kind in routineDefs: linkTitle.add(xmltree.escape(plainName.strip))
else: linkTitle.add(xmltree.escape(complexSymbol.strip))
setIndexTerm(d[], external, symbolOrId, name, linkTitle,
xmltree.escape(plainDocstring.docstringSummary))
setIndexTerm(d[], ieNim, htmlFile = external, id = symbolOrId, term = name,
linkTitle = detailedName,
linkDesc = xmltree.escape(plainDocstring.docstringSummary),
line = n.info.line.int)
if k == skType and nameNode.kind == nkSym:
d.types.strTableAdd nameNode.sym
proc genJsonItem(d: PDoc, n, nameNode: PNode, k: TSymKind): JsonItem =
if not isVisible(d, nameNode): return
var
name = getName(d, nameNode)
name = getNameEsc(d, nameNode)
comm = genRecComment(d, n)
r: TSrcGen
initTokRender(r, n, {renderNoBody, renderNoComments, renderDocComments})
initTokRender(r, n, {renderNoBody, renderNoComments, renderDocComments, renderExpandUsing})
result.json = %{ "name": %name, "type": %($k), "line": %n.info.line.int,
"col": %n.info.col}
if comm != nil:
@@ -1024,6 +1166,46 @@ proc genJsonItem(d: PDoc, n, nameNode: PNode, k: TSymKind): JsonItem =
for kind in genericParam.sym.typ.sons:
param["types"].add %($kind)
result.json["signature"]["genericParams"].add param
if optGenIndex in d.conf.globalOptions:
genItem(d, n, nameNode, k, kForceExport)
proc setDoctype(d: PDoc, n: PNode) =
## Processes `{.doctype.}` pragma changing Markdown/RST parsing options.
if n == nil:
return
if n.len != 2:
localError(d.conf, n.info, errUser,
"doctype pragma takes exactly 1 argument"
)
return
var dt = ""
case n[1].kind
of nkStrLit:
dt = toLowerAscii(n[1].strVal)
of nkIdent:
dt = toLowerAscii(n[1].ident.s)
else:
localError(d.conf, n.info, errUser,
"unknown argument type $1 provided to doctype" % [$n[1].kind]
)
return
case dt
of "markdown":
d.sharedState.options.incl roSupportMarkdown
d.sharedState.options.incl roPreferMarkdown
of "rstmarkdown":
d.sharedState.options.incl roSupportMarkdown
d.sharedState.options.excl roPreferMarkdown
of "rst":
d.sharedState.options.excl roSupportMarkdown
d.sharedState.options.excl roPreferMarkdown
else:
localError(d.conf, n.info, errUser,
(
"unknown doctype value \"$1\", should be from " &
"\"RST\", \"Markdown\", \"RstMarkdown\""
) % [dt]
)
proc checkForFalse(n: PNode): bool =
result = n.kind == nkIdent and cmpIgnoreStyle(n.ident.s, "false") == 0
@@ -1040,7 +1222,7 @@ proc traceDeps(d: PDoc, it: PNode) =
for x in it[2]:
a[2] = x
traceDeps(d, a)
elif it.kind == nkSym and belongsToPackage(d.conf, it.sym):
elif it.kind == nkSym and belongsToProjectPackage(d.conf, it.sym):
let external = externalDep(d, it.sym)
if d.section[k].finalMarkup != "": d.section[k].finalMarkup.add(", ")
dispA(d.conf, d.section[k].finalMarkup,
@@ -1050,7 +1232,7 @@ proc traceDeps(d: PDoc, it: PNode) =
proc exportSym(d: PDoc; s: PSym) =
const k = exportSection
if s.kind == skModule and belongsToPackage(d.conf, s):
if s.kind == skModule and belongsToProjectPackage(d.conf, s):
let external = externalDep(d, s)
if d.section[k].finalMarkup != "": d.section[k].finalMarkup.add(", ")
dispA(d.conf, d.section[k].finalMarkup,
@@ -1059,7 +1241,7 @@ proc exportSym(d: PDoc; s: PSym) =
changeFileExt(external, "html")])
elif s.kind != skModule and s.owner != nil:
let module = originatingModule(s)
if belongsToPackage(d.conf, module):
if belongsToProjectPackage(d.conf, module):
let
complexSymbol = complexName(s.kind, s.ast, s.name.s)
symbolOrId = d.newUniquePlainSymbol(complexSymbol)
@@ -1120,8 +1302,9 @@ proc documentRaises*(cache: IdentCache; n: PNode) =
let p3 = documentWriteEffect(cache, n, sfWrittenTo, "writes")
let p4 = documentNewEffect(cache, n)
let p5 = documentWriteEffect(cache, n, sfEscapes, "escapes")
let p6 = documentEffect(cache, n, pragmas, wForbids, forbiddenEffects)
if p1 != nil or p2 != nil or p3 != nil or p4 != nil or p5 != nil:
if p1 != nil or p2 != nil or p3 != nil or p4 != nil or p5 != nil or p6 != nil:
if pragmas.kind == nkEmpty:
n[pragmasPos] = newNodeI(nkPragma, n.info)
if p1 != nil: n[pragmasPos].add p1
@@ -1129,17 +1312,21 @@ proc documentRaises*(cache: IdentCache; n: PNode) =
if p3 != nil: n[pragmasPos].add p3
if p4 != nil: n[pragmasPos].add p4
if p5 != nil: n[pragmasPos].add p5
if p6 != nil: n[pragmasPos].add p6
proc generateDoc*(d: PDoc, n, orig: PNode, docFlags: DocFlags = kDefault) =
proc generateDoc*(d: PDoc, n, orig: PNode, config: ConfigRef, docFlags: DocFlags = kDefault) =
## Goes through nim nodes recursively and collects doc comments.
## Main function for `doc`:option: command,
## which is implemented in ``docgen2.nim``.
template genItemAux(skind) =
genItem(d, n, n[namePos], skind, docFlags)
let showNonExports = optShowNonExportedFields in config.globalOptions
case n.kind
of nkPragma:
let pragmaNode = findPragma(n, wDeprecated)
d.modDeprecationMsg.add(genDeprecationMsg(d, pragmaNode))
let doctypeNode = findPragma(n, wDoctype)
setDoctype(d, doctypeNode)
of nkCommentStmt: d.modDescPre.add(genComment(d, n))
of nkProcDef, nkFuncDef:
when useEffectSystem: documentRaises(d.cache, n)
@@ -1160,20 +1347,20 @@ proc generateDoc*(d: PDoc, n, orig: PNode, docFlags: DocFlags = kDefault) =
if n[i].kind != nkCommentStmt:
# order is always 'type var let const':
genItem(d, n[i], n[i][0],
succ(skType, ord(n.kind)-ord(nkTypeSection)), docFlags)
succ(skType, ord(n.kind)-ord(nkTypeSection)), docFlags, showNonExports)
of nkStmtList:
for i in 0..<n.len: generateDoc(d, n[i], orig)
for i in 0..<n.len: generateDoc(d, n[i], orig, config)
of nkWhenStmt:
# generate documentation for the first branch only:
if not checkForFalse(n[0][0]):
generateDoc(d, lastSon(n[0]), orig)
generateDoc(d, lastSon(n[0]), orig, config)
of nkImportStmt:
for it in n: traceDeps(d, it)
of nkExportStmt:
for it in n:
if it.kind == nkSym:
if d.module != nil and d.module == it.sym.owner:
generateDoc(d, it.sym.ast, orig, kForceExport)
generateDoc(d, it.sym.ast, orig, config, kForceExport)
elif it.sym.ast != nil:
exportSym(d, it.sym)
of nkExportExceptStmt: discard "transformed into nkExportStmt by semExportExcept"
@@ -1184,6 +1371,33 @@ proc generateDoc*(d: PDoc, n, orig: PNode, docFlags: DocFlags = kDefault) =
if comm.len != 0: d.modDescPre.add(comm)
else: discard
proc overloadGroupName(s: string, k: TSymKind): string =
## Turns a name like `f` into anchor `f-procs-all`
s & "-" & k.toHumanStr & "s-all"
proc setIndexTitle(d: PDoc, useMetaTitle: bool) =
let titleKind = if d.standaloneDoc: ieMarkupTitle else: ieNimTitle
let external = AbsoluteFile(d.destFile)
.relativeTo(d.conf.outDir, '/')
.changeFileExt(HtmlExt)
.string
var term, linkTitle: string
if useMetaTitle and d.meta[metaTitle].len != 0:
term = d.meta[metaTitleRaw]
linkTitle = d.meta[metaTitleRaw]
else:
let filename = extractFilename(d.filename)
term =
if d.standaloneDoc: filename # keep .rst/.md extension
else: changeFileExt(filename, "") # rm .nim extension
linkTitle =
if d.standaloneDoc: term # keep .rst/.md extension
else: canonicalImport(d.conf, AbsoluteFile d.filename)
if not d.standaloneDoc:
linkTitle = "module " & linkTitle
setIndexTerm(d[], titleKind, htmlFile = external, id = "",
term = term, linkTitle = linkTitle)
proc finishGenerateDoc*(d: var PDoc) =
## Perform 2nd RST pass for resolution of links/footnotes/headings...
# copy file map `filenames` to ``rstgen.nim`` for its warnings
@@ -1195,7 +1409,52 @@ proc finishGenerateDoc*(d: var PDoc) =
if fragment.isRst:
firstRst = fragment.rst
break
preparePass2(d.sharedState, firstRst)
d.hasToc = d.hasToc or d.sharedState.hasToc
# in --index:only mode we do NOT want to load other .idx, only write ours:
let importdoc = optGenIndexOnly notin d.conf.globalOptions and
optNoImportdoc notin d.conf.globalOptions
preparePass2(d.sharedState, firstRst, importdoc)
if optGenIndexOnly in d.conf.globalOptions:
# Top-level doc.comments may contain titles and :idx: statements:
for fragment in d.modDescPre:
if fragment.isRst:
traverseForIndex(d[], fragment.rst)
setIndexTitle(d, useMetaTitle = d.standaloneDoc)
# Symbol-associated doc.comments may contain :idx: statements:
for k in TSymKind:
for _, overloadChoices in d.section[k].secItems:
for item in overloadChoices:
for fragment in item.descRst:
if fragment.isRst:
traverseForIndex(d[], fragment.rst)
# add anchors to overload groups before RST resolution
for k in TSymKind:
if k in routineKinds:
for plainName, overloadChoices in d.section[k].secItems:
if overloadChoices.len > 1:
let refn = overloadGroupName(plainName, k)
let tooltip = "$1 ($2 overloads)" % [
k.toHumanStr & " " & plainName, $overloadChoices.len]
let name = nimIdentBackticksNormalize(plainName)
# save overload group to ``.idx``
let external = d.destFile.AbsoluteFile.relativeTo(d.conf.outDir, '/').
changeFileExt(HtmlExt).string
setIndexTerm(d[], ieNimGroup, htmlFile = external, id = refn,
term = name, linkTitle = k.toHumanStr,
linkDesc = "", line = overloadChoices[0].info.line.int)
if optGenIndexOnly in d.conf.globalOptions: continue
addAnchorNim(d.sharedState, external=false, refn, tooltip,
LangSymbol(symKind: k.toHumanStr,
name: name,
isGroup: true),
priority = symbolPriority(k),
# select index `0` just to have any meaningful warning:
info = overloadChoices[0].info)
if optGenIndexOnly in d.conf.globalOptions:
return
# Finalize fragments of ``.nim`` or ``.rst`` file
proc renderItemPre(d: PDoc, fragments: ItemPre, result: var string) =
@@ -1207,17 +1466,35 @@ proc finishGenerateDoc*(d: var PDoc) =
of false: result &= f.str
proc cmp(x, y: Item): int = cmpDecimalsIgnoreCase(x.sortName, y.sortName)
for k in TSymKind:
for item in d.section[k].secItems.sorted(cmp):
var itemDesc: string
renderItemPre(d, item.descRst, itemDesc)
d.section[k].finalMarkup.add(
getConfigVar(d.conf, "doc.item") % (
item.substitutions & @["desc", itemDesc]))
itemDesc = ""
d.section[k].secItems.setLen 0
# add symbols to section for each `k`, while optionally wrapping
# overloadable items with the same basic name by ``doc.item2``
let overloadableNames = toSeq(keys(d.section[k].secItems))
for plainName in overloadableNames.sorted(cmpDecimalsIgnoreCase):
var overloadChoices = d.section[k].secItems[plainName]
overloadChoices.sort(cmp)
var nameContent = ""
for item in overloadChoices:
var itemDesc: string
renderItemPre(d, item.descRst, itemDesc)
nameContent.add(
getConfigVar(d.conf, "doc.item") % (
item.substitutions & @[
"desc", itemDesc,
"name", item.name,
"itemSymOrID", item.anchor]))
if k in routineKinds:
let plainNameEsc1 = esc(d.target, plainName.strip)
let plainNameEsc2 = esc(d.target, plainName.strip, escMode=emUrl)
d.section[k].finalMarkup.add(
getConfigVar(d.conf, "doc.item2") % (
@["header_plain", plainNameEsc1,
"overloadGroupName", overloadGroupName(plainNameEsc2, k),
"content", nameContent]))
else:
d.section[k].finalMarkup.add(nameContent)
d.section[k].secItems.clear
renderItemPre(d, d.modDescPre, d.modDescFinal)
d.modDescPre.setLen 0
d.hasToc = d.hasToc or d.sharedState.hasToc
# Finalize fragments of ``.json`` file
for i, entry in d.jEntriesPre:
@@ -1226,14 +1503,21 @@ proc finishGenerateDoc*(d: var PDoc) =
var str: string
renderRstToOut(d[], resolved, str)
entry.json[entry.rstField] = %str
d.jEntriesFinal.add entry.json
d.jEntriesPre[i].rst = nil
d.jEntriesFinal.add entry.json # generates docs
setIndexTitle(d, useMetaTitle = d.standaloneDoc)
completePass2(d.sharedState)
proc add(d: PDoc; j: JsonItem) =
if j.json != nil or j.rst != nil: d.jEntriesPre.add j
proc generateJson*(d: PDoc, n: PNode, includeComments: bool = true) =
case n.kind
of nkPragma:
let doctypeNode = findPragma(n, wDoctype)
setDoctype(d, doctypeNode)
of nkCommentStmt:
if includeComments:
d.add JsonItem(rst: genComment(d, n), rstField: "comment",
@@ -1272,7 +1556,7 @@ proc generateJson*(d: PDoc, n: PNode, includeComments: bool = true) =
else: discard
proc genTagsItem(d: PDoc, n, nameNode: PNode, k: TSymKind): string =
result = getName(d, nameNode) & "\n"
result = getNameEsc(d, nameNode) & "\n"
proc generateTags*(d: PDoc, n: PNode, r: var string) =
case n.kind
@@ -1342,9 +1626,20 @@ proc genSection(d: PDoc, kind: TSymKind, groupedToc = false) =
for item in d.tocSimple[kind].sorted(cmp):
d.toc2[kind].add item.content
d.toc[kind] = getConfigVar(d.conf, "doc.section.toc") % [
"sectionid", $ord(kind), "sectionTitle", title,
"sectionTitleID", $(ord(kind) + 50), "content", d.toc2[kind]]
let sectionValues = @[
"sectionID", $ord(kind), "sectionTitleID", $(ord(kind) + 50),
"sectionTitle", title
]
# Check if the toc has any children
if d.toc2[kind] != "":
# Use the dropdown version instead and store the children in the dropdown
d.toc[kind] = getConfigVar(d.conf, "doc.section.toc") % (sectionValues & @[
"content", d.toc2[kind]
])
else:
# Just have the link
d.toc[kind] = getConfigVar(d.conf, "doc.section.toc_item") % sectionValues
proc relLink(outDir: AbsoluteDir, destFile: AbsoluteFile, linkto: RelativeFile): string =
$relativeTo(outDir / linkto, destFile.splitFile().dir, '/')
@@ -1368,10 +1663,7 @@ proc genOutFile(d: PDoc, groupedToc = false): string =
# Extract the title. Non API modules generate an entry in the index table.
if d.meta[metaTitle].len != 0:
title = d.meta[metaTitle]
let external = presentationPath(d.conf, AbsoluteFile d.filename).changeFileExt(HtmlExt).string.nativeToUnixPath
setIndexTerm(d[], external, "", title)
else:
# Modules get an automatic title for the HTML, but no entry in the index.
title = canonicalImport(d.conf, AbsoluteFile d.filename)
title = esc(d.target, title)
var subtitle = ""
@@ -1380,7 +1672,7 @@ proc genOutFile(d: PDoc, groupedToc = false): string =
"\\\\\\vspace{0.5em}\\large $1", [esc(d.target, d.meta[metaSubtitle])])
var groupsection = getConfigVar(d.conf, "doc.body_toc_groupsection")
let bodyname = if d.hasToc and not d.isPureRst and not d.conf.isLatexCmd:
let bodyname = if d.hasToc and not d.standaloneDoc and not d.conf.isLatexCmd:
groupsection.setLen 0
"doc.body_toc_group"
elif d.hasToc: "doc.body_toc"
@@ -1410,11 +1702,17 @@ proc genOutFile(d: PDoc, groupedToc = false): string =
code = content
result = code
proc indexFile(d: PDoc): AbsoluteFile =
let dir = d.conf.outDir
result = dir / changeFileExt(presentationPath(d.conf,
AbsoluteFile d.filename),
IndexExt)
let (finalDir, _, _) = result.string.splitFile
createDir(finalDir)
proc generateIndex*(d: PDoc) =
if optGenIndex in d.conf.globalOptions:
let dir = d.conf.outDir
createDir(dir)
let dest = dir / changeFileExt(presentationPath(d.conf, AbsoluteFile d.filename), IndexExt)
let dest = indexFile(d)
writeIndexFile(d[], dest.string)
proc updateOutfile(d: PDoc, outfile: AbsoluteFile) =
@@ -1425,6 +1723,9 @@ proc updateOutfile(d: PDoc, outfile: AbsoluteFile) =
d.conf.outFile = splitPath(d.conf.outFile.string)[1].RelativeFile
proc writeOutput*(d: PDoc, useWarning = false, groupedToc = false) =
if optGenIndexOnly in d.conf.globalOptions:
d.conf.outFile = indexFile(d).relativeTo(d.conf.outDir) # just for display
return
runAllExamples(d)
var content = genOutFile(d, groupedToc)
if optStdout in d.conf.globalOptions:
@@ -1442,7 +1743,11 @@ proc writeOutput*(d: PDoc, useWarning = false, groupedToc = false) =
outfile.string)
if not d.wroteSupportFiles: # nimdoc.css + dochack.js
let nimr = $d.conf.getPrefixDir()
copyFile(docCss.interp(nimr = nimr), $d.conf.outDir / nimdocOutCss)
case d.target
of outHtml:
copyFile(docCss.interp(nimr = nimr), $d.conf.outDir / nimdocOutCss)
of outLatex:
copyFile(docCls.interp(nimr = nimr), $d.conf.outDir / nimdocOutCls)
if optGenIndex in d.conf.globalOptions:
let docHackJs2 = getDocHacksJs(nimr, nim = getAppFilename())
copyFile(docHackJs2, $d.conf.outDir / docHackJs2.lastPathPart)
@@ -1460,6 +1765,8 @@ proc writeOutputJson*(d: PDoc, useWarning = false) =
if optStdout in d.conf.globalOptions:
write(stdout, $content)
else:
let dir = d.destFile.splitFile.dir
createDir(dir)
var f: File
if open(f, d.destFile, fmWrite):
write(f, $content)
@@ -1482,18 +1789,19 @@ proc commandDoc*(cache: IdentCache, conf: ConfigRef) =
handleDocOutputOptions conf
var ast = parseFile(conf.projectMainIdx, cache, conf)
if ast == nil: return
var d = newDocumentor(conf.projectFull, cache, conf)
d.hasToc = true
generateDoc(d, ast, ast)
var d = newDocumentor(conf.projectFull, cache, conf, hasToc = true)
generateDoc(d, ast, ast, conf)
finishGenerateDoc(d)
writeOutput(d)
generateIndex(d)
proc commandRstAux(cache: IdentCache, conf: ConfigRef;
filename: AbsoluteFile, outExt: string) =
filename: AbsoluteFile, outExt: string,
preferMarkdown: bool) =
var filen = addFileExt(filename, "txt")
var d = newDocumentor(filen, cache, conf, outExt, isPureRst = true)
let rst = parseRst(readFile(filen.string), filen.string,
var d = newDocumentor(filen, cache, conf, outExt, standaloneDoc = true,
preferMarkdown = preferMarkdown, hasToc = false)
let rst = parseRst(readFile(filen.string),
line=LineRstInit, column=ColRstInit,
conf, d.sharedState)
d.modDescPre = @[ItemFragment(isRst: true, rst: rst)]
@@ -1501,22 +1809,23 @@ proc commandRstAux(cache: IdentCache, conf: ConfigRef;
writeOutput(d)
generateIndex(d)
proc commandRst2Html*(cache: IdentCache, conf: ConfigRef) =
commandRstAux(cache, conf, conf.projectFull, HtmlExt)
proc commandRst2Html*(cache: IdentCache, conf: ConfigRef,
preferMarkdown=false) =
commandRstAux(cache, conf, conf.projectFull, HtmlExt, preferMarkdown)
proc commandRst2TeX*(cache: IdentCache, conf: ConfigRef) =
commandRstAux(cache, conf, conf.projectFull, TexExt)
proc commandRst2TeX*(cache: IdentCache, conf: ConfigRef,
preferMarkdown=false) =
commandRstAux(cache, conf, conf.projectFull, TexExt, preferMarkdown)
proc commandJson*(cache: IdentCache, conf: ConfigRef) =
## implementation of a deprecated jsondoc0 command
var ast = parseFile(conf.projectMainIdx, cache, conf)
if ast == nil: return
var d = newDocumentor(conf.projectFull, cache, conf)
var d = newDocumentor(conf.projectFull, cache, conf, hasToc = true)
d.onTestSnippet = proc (d: var RstGenerator; filename, cmd: string;
status: int; content: string) =
status: int; content: string) {.gcsafe.} =
localError(conf, newLineInfo(conf, AbsoluteFile d.filename, -1, -1),
warnUser, "the ':test:' attribute is not supported by this backend")
d.hasToc = true
generateJson(d, ast)
finishGenerateDoc(d)
let json = d.jEntriesFinal
@@ -1529,18 +1838,17 @@ proc commandJson*(cache: IdentCache, conf: ConfigRef) =
let filename = getOutFile(conf, RelativeFile conf.projectName, JsonExt)
try:
writeFile(filename, content)
except:
except IOError:
rawMessage(conf, errCannotOpenFile, filename.string)
proc commandTags*(cache: IdentCache, conf: ConfigRef) =
var ast = parseFile(conf.projectMainIdx, cache, conf)
if ast == nil: return
var d = newDocumentor(conf.projectFull, cache, conf)
var d = newDocumentor(conf.projectFull, cache, conf, hasToc = true)
d.onTestSnippet = proc (d: var RstGenerator; filename, cmd: string;
status: int; content: string) =
status: int; content: string) {.gcsafe.} =
localError(conf, newLineInfo(conf, AbsoluteFile d.filename, -1, -1),
warnUser, "the ':test:' attribute is not supported by this backend")
d.hasToc = true
var
content = ""
generateTags(d, ast, content)
@@ -1552,10 +1860,12 @@ proc commandTags*(cache: IdentCache, conf: ConfigRef) =
let filename = getOutFile(conf, RelativeFile conf.projectName, TagsExt)
try:
writeFile(filename, content)
except:
except IOError:
rawMessage(conf, errCannotOpenFile, filename.string)
proc commandBuildIndex*(conf: ConfigRef, dir: string, outFile = RelativeFile"") =
if optGenIndexOnly in conf.globalOptions:
return
var content = mergeIndexes(dir)
var outFile = outFile
@@ -1573,5 +1883,19 @@ proc commandBuildIndex*(conf: ConfigRef, dir: string, outFile = RelativeFile"")
try:
writeFile(filename, code)
except:
except IOError:
rawMessage(conf, errCannotOpenFile, filename.string)
proc commandBuildIndexJson*(conf: ConfigRef, dir: string, outFile = RelativeFile"") =
var (modules, symbols, docs) = readIndexDir(dir)
let documents = toSeq(keys(Table[IndexEntry, seq[IndexEntry]](docs)))
let body = %*({"documents": documents, "modules": modules, "symbols": symbols})
var outFile = outFile
if outFile.isEmpty: outFile = theindexFname.RelativeFile.changeFileExt("")
let filename = getOutFile(conf, outFile, JsonExt)
try:
writeFile(filename, $body)
except IOError:
rawMessage(conf, errCannotOpenFile, filename.string)

View File

@@ -11,7 +11,7 @@
# semantic checking.
import
options, ast, msgs, passes, docgen, lineinfos, pathutils
options, ast, msgs, docgen, lineinfos, pathutils, packages
from modulegraphs import ModuleGraph, PPassContext
@@ -23,7 +23,7 @@ type
PGen = ref TGen
proc shouldProcess(g: PGen): bool =
(optWholeProject in g.doc.conf.globalOptions and g.module.getnimblePkgId == g.doc.conf.mainPackageId) or
(optWholeProject in g.doc.conf.globalOptions and g.doc.conf.belongsToProjectPackage(g.module)) or
sfMainModule in g.module.flags or g.config.projectMainIdx == g.module.info.fileIndex
template closeImpl(body: untyped) {.dirty.} =
@@ -38,21 +38,21 @@ template closeImpl(body: untyped) {.dirty.} =
except IOError:
discard
proc close(graph: ModuleGraph; p: PPassContext, n: PNode): PNode =
proc closeDoc*(graph: ModuleGraph; p: PPassContext, n: PNode): PNode =
closeImpl:
writeOutput(g.doc, useWarning, groupedToc)
proc closeJson(graph: ModuleGraph; p: PPassContext, n: PNode): PNode =
proc closeJson*(graph: ModuleGraph; p: PPassContext, n: PNode): PNode =
closeImpl:
writeOutputJson(g.doc, useWarning)
proc processNode(c: PPassContext, n: PNode): PNode =
proc processNode*(c: PPassContext, n: PNode): PNode =
result = n
var g = PGen(c)
if shouldProcess(g):
generateDoc(g.doc, n, n)
generateDoc(g.doc, n, n, g.config)
proc processNodeJson(c: PPassContext, n: PNode): PNode =
proc processNodeJson*(c: PPassContext, n: PNode): PNode =
result = n
var g = PGen(c)
if shouldProcess(g):
@@ -64,25 +64,15 @@ template myOpenImpl(ext: untyped) {.dirty.} =
g.module = module
g.config = graph.config
var d = newDocumentor(AbsoluteFile toFullPath(graph.config, FileIndex module.position),
graph.cache, graph.config, ext, module)
d.hasToc = true
graph.cache, graph.config, ext, module, hasToc = true)
g.doc = d
result = g
proc myOpen(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext =
proc openHtml*(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext =
myOpenImpl(HtmlExt)
proc myOpenTex(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext =
proc openTex*(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext =
myOpenImpl(TexExt)
proc myOpenJson(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext =
proc openJson*(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext =
myOpenImpl(JsonExt)
const docgen2Pass* = makePass(open = myOpen, process = processNode, close = close)
const docgen2TexPass* = makePass(open = myOpenTex, process = processNode,
close = close)
const docgen2JsonPass* = makePass(open = myOpenJson, process = processNodeJson,
close = closeJson)
proc finishDoc2Pass*(project: string) =
discard

View File

@@ -1,6 +1,10 @@
import ast, idents, lineinfos, modulegraphs, magicsys
when defined(nimPreviewSlimSystem):
import std/assertions
proc genEnumToStrProc*(t: PType; info: TLineInfo; g: ModuleGraph; idgen: IdGenerator): PSym =
result = newSym(skProc, getIdent(g.cache, "$"), nextSymId idgen, t.owner, info)
@@ -26,7 +30,7 @@ proc genEnumToStrProc*(t: PType; info: TLineInfo; g: ModuleGraph; idgen: IdGener
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
caseStmt.add newTree(nkOfBranch, newSymNode(field),
caseStmt.add newTree(nkOfBranch, newIntTypeNode(field.position, t),
newTree(nkStmtList, newTree(nkFastAsgn, newSymNode(res), newStrNode(val, info))))
#newIntTypeNode(nkIntLit, field.position, t)

View File

@@ -12,6 +12,9 @@
import ast, renderer, options, strutils, types
when defined(nimPreviewSlimSystem):
import std/assertions
type
ErrorKind* = enum ## expand as you need.
RawTypeMismatchError

View File

@@ -65,19 +65,19 @@ proc importcSymbol*(conf: ConfigRef, sym: PSym): PNode =
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)
theAddr = gExeHandle.symAddr(name.cstring)
# then try libc:
if theAddr.isNil:
let dllhandle = getDll(conf, gDllCache, libcDll, sym.info)
theAddr = dllhandle.symAddr(name)
theAddr = dllhandle.symAddr(name.cstring)
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)
theAddr = dllhandle.symAddr(name.cstring)
if theAddr.isNil: globalError(conf, sym.info,
"cannot import symbol: " & name & " from " & libPathMsg)
result.intVal = cast[ByteAddress](theAddr)
result.intVal = cast[int](theAddr)
proc mapType(conf: ConfigRef, t: ast.PType): ptr libffi.Type =
if t == nil: return addr libffi.type_void
@@ -110,10 +110,10 @@ proc mapCallConv(conf: ConfigRef, cc: TCallingConvention, info: TLineInfo): TABI
else:
globalError(conf, info, "cannot map calling convention to FFI")
template rd(T, p: untyped): untyped = (cast[ptr T](p))[]
template wr(T, p, v: untyped): untyped = (cast[ptr T](p))[] = v
template rd(typ, p: untyped): untyped = (cast[ptr typ](p))[]
template wr(typ, p, v: untyped): untyped = (cast[ptr typ](p))[] = v
template `+!`(x, y: untyped): untyped =
cast[pointer](cast[ByteAddress](x) + y)
cast[pointer](cast[int](x) + y)
proc packSize(conf: ConfigRef, v: PNode, typ: PType): int =
## computes the size of the blob
@@ -177,8 +177,8 @@ const maxPackDepth = 20
var packRecCheck = 0
proc pack(conf: ConfigRef, v: PNode, typ: PType, res: pointer) =
template awr(T, v: untyped): untyped =
wr(T, res, v)
template awr(typ, v: untyped): untyped =
wr(typ, res, v)
case typ.kind
of tyBool: awr(bool, v.intVal != 0)
@@ -369,13 +369,13 @@ proc unpack(conf: ConfigRef, x: pointer, typ: PType, n: PNode): PNode =
# in their unboxed representation so nothing it to be unpacked:
result = n
else:
awi(nkPtrLit, cast[ByteAddress](p))
awi(nkPtrLit, cast[int](p))
of tyPtr, tyRef, tyVar, tyLent:
let p = rd(pointer, x)
if p.isNil:
setNil()
elif n == nil or n.kind == nkPtrLit:
awi(nkPtrLit, cast[ByteAddress](p))
awi(nkPtrLit, cast[int](p))
elif n != nil and n.len == 1:
internalAssert(conf, n.kind == nkRefTy)
n[0] = unpack(conf, p, typ.lastSon, n[0])

View File

@@ -26,7 +26,7 @@ type
proc copyNode(ctx: TemplCtx, a, b: PNode): PNode =
result = copyNode(a)
if ctx.instLines: result.info = b.info
if ctx.instLines: setInfoRecursive(result, b.info)
proc evalTemplateAux(templ, actual: PNode, c: var TemplCtx, result: PNode) =
template handleParam(param) =
@@ -204,7 +204,7 @@ proc evalTemplate*(n: PNode, tmpl, genSymOwner: PSym;
result = copyNode(body)
ctx.instLines = sfCallsite in tmpl.flags
if ctx.instLines:
result.info = n.info
setInfoRecursive(result, n.info)
for i in 0..<body.safeLen:
evalTemplateAux(body[i], args, ctx, result)
result.flags.incl nfFromTemplate

View File

@@ -12,9 +12,14 @@
# from a lineinfos file, to provide generalized procedures to compile
# nim files.
import ropes, platform, condsyms, options, msgs, lineinfos, pathutils
import ropes, platform, condsyms, options, msgs, lineinfos, pathutils, modulepaths
import std/[os, strutils, osproc, sha1, streams, sequtils, times, strtabs, json, jsonutils, sugar]
import std/[os, osproc, sha1, streams, sequtils, times, strtabs, json, jsonutils, sugar, parseutils]
import std / strutils except addf
when defined(nimPreviewSlimSystem):
import std/syncio
type
TInfoCCProp* = enum # properties of the C compiler:
@@ -83,10 +88,10 @@ compiler gcc:
linkLibCmd: " -l$1",
debug: "",
pic: "-fPIC",
asmStmtFrmt: "asm($1);$n",
asmStmtFrmt: "__asm__($1);$n",
structStmtFmt: "$1 $3 $2 ", # struct|union [packed] $name
produceAsm: gnuAsmListing,
cppXsupport: "-std=gnu++14 -funsigned-char",
cppXsupport: "-std=gnu++17 -funsigned-char",
props: {hasSwitchRange, hasComputedGoto, hasCpp, hasGcGuard, hasGnuAsm,
hasAttribute})
@@ -113,7 +118,7 @@ compiler nintendoSwitchGCC:
asmStmtFrmt: "asm($1);$n",
structStmtFmt: "$1 $3 $2 ", # struct|union [packed] $name
produceAsm: gnuAsmListing,
cppXsupport: "-std=gnu++14 -funsigned-char",
cppXsupport: "-std=gnu++17 -funsigned-char",
props: {hasSwitchRange, hasComputedGoto, hasCpp, hasGcGuard, hasGnuAsm,
hasAttribute})
@@ -150,7 +155,7 @@ compiler vcc:
compileTmpl: "/c$vccplatform $options $include /nologo /Fo$objfile $file",
buildGui: " /SUBSYSTEM:WINDOWS user32.lib ",
buildDll: " /LD",
buildLib: "lib /OUT:$libfile $objfiles",
buildLib: "vccexe --command:lib$vccplatform /nologo /OUT:$libfile $objfiles",
linkerExe: "cl",
linkTmpl: "$builddll$vccplatform /Fe$exefile $objfiles $buildgui /nologo $options",
includeCmd: " /I",
@@ -323,7 +328,9 @@ proc getConfigVar(conf: ConfigRef; c: TSystemCC, suffix: string): string =
platform.OS[conf.target.targetOS].name & '.' &
CC[c].name & fullSuffix
result = getConfigVar(conf, fullCCname)
if result.len == 0:
if existsConfigVar(conf, fullCCname):
result = getConfigVar(conf, fullCCname)
else:
# not overridden for this cross compilation setting?
result = getConfigVar(conf, CC[c].name & fullSuffix)
else:
@@ -367,6 +374,7 @@ proc initVars*(conf: ConfigRef) =
proc completeCfilePath*(conf: ConfigRef; cfile: AbsoluteFile,
createSubDir: bool = true): AbsoluteFile =
## Generate the absolute file path to the generated modules.
result = completeGeneratedFilePath(conf, cfile, createSubDir)
proc toObjFile*(conf: ConfigRef; filename: AbsoluteFile): AbsoluteFile =
@@ -377,7 +385,7 @@ 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
let key = completeCfilePath(conf, mangleModuleName(conf, nimfile).AbsoluteFile).string
var value = conf.cfileSpecificOptions.getOrDefault(key)
if strutils.find(value, option, 0) < 0:
addOpt(value, option)
@@ -430,7 +438,13 @@ proc noAbsolutePaths(conf: ConfigRef): bool {.inline.} =
# really: Cross compilation from Linux to Linux for example is entirely
# reasonable.
# `optGenMapping` is included here for niminst.
result = conf.globalOptions * {optGenScript, optGenMapping} != {}
# We use absolute paths for vcc / cl, see issue #19883.
let options =
if conf.cCompiler == ccVcc:
{optGenMapping}
else:
{optGenScript, optGenMapping}
result = conf.globalOptions * options != {}
proc cFileSpecificOptions(conf: ConfigRef; nimname, fullNimFile: string): string =
result = conf.compileOptions
@@ -483,7 +497,10 @@ proc needsExeExt(conf: ConfigRef): bool {.inline.} =
(conf.target.hostOS == osWindows)
proc useCpp(conf: ConfigRef; cfile: AbsoluteFile): bool =
conf.backend == backendCpp and not cfile.string.endsWith(".c")
# List of possible file extensions taken from gcc
for ext in [".C", ".cc", ".cpp", ".CPP", ".c++", ".cp", ".cxx"]:
if cfile.string.endsWith(ext): return true
false
proc envFlags(conf: ConfigRef): string =
result = if conf.backend == backendCpp:
@@ -491,14 +508,14 @@ proc envFlags(conf: ConfigRef): string =
else:
getEnv("CFLAGS")
proc getCompilerExe(conf: ConfigRef; compiler: TSystemCC; cfile: AbsoluteFile): string =
proc getCompilerExe(conf: ConfigRef; compiler: TSystemCC; isCpp: bool): string =
if compiler == ccEnv:
result = if useCpp(conf, cfile):
result = if isCpp:
getEnv("CXX")
else:
getEnv("CC")
else:
result = if useCpp(conf, cfile):
result = if isCpp:
CC[compiler].cppCompiler
else:
CC[compiler].compilerExe
@@ -512,47 +529,36 @@ proc ccHasSaneOverflow*(conf: ConfigRef): bool =
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)
# NOTE: should we need the full version, use -dumpfullversion
let (s, exitCode) = try: execCmdEx(exe & " -dumpversion") except IOError, OSError, ValueError: ("", 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
var major: int
discard parseInt(s, major)
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.backend != backendCpp: CC[compiler].cppCompiler
else: getCompilerExe(conf, compiler, AbsoluteFile"")
else: getCompilerExe(conf, compiler, optMixedMode in conf.globalOptions or conf.backend == backendCpp)
proc getCompileCFileCmd*(conf: ConfigRef; cfile: Cfile,
isMainFile = false; produceOutput = false): string =
let c = conf.cCompiler
let
c = conf.cCompiler
isCpp = useCpp(conf, cfile.cname)
# 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):
if isCpp:
# 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
# If any C++ file was compiled, we need to use C++ driver for linking as well
incl conf.globalOptions, optMixedMode
var exe = getConfigVar(conf, c, ".exe")
if exe.len == 0: exe = getCompilerExe(conf, c, cfile.cname)
if exe.len == 0: exe = getCompilerExe(conf, c, isCpp)
if needsExeExt(conf): exe = addFileExt(exe, "exe")
if (optGenDynLib in conf.globalOptions or (conf.hcrOn and not isMainFile)) and
@@ -572,7 +578,7 @@ proc getCompileCFileCmd*(conf: ConfigRef; cfile: Cfile,
compilePattern = joinPath(conf.cCompilerPath, exe)
else:
compilePattern = getCompilerExe(conf, c, cfile.cname)
compilePattern = getCompilerExe(conf, c, isCpp)
includeCmd.add(join([CC[c].includeCmd, quoteShell(conf.projectPath.string)]))
@@ -614,7 +620,7 @@ proc getCompileCFileCmd*(conf: ConfigRef; cfile: Cfile,
"for the selected C compiler: " & CC[conf.cCompiler].name)
result.add(' ')
result.addf(CC[c].compileTmpl, [
strutils.addf(result, CC[c].compileTmpl, [
"dfile", dfile,
"file", cfsh, "objfile", quoteShell(objfile),
"options", options, "include", includeCmd,
@@ -634,7 +640,7 @@ proc footprint(conf: ConfigRef; cfile: Cfile): SecureHash =
proc externalFileChanged(conf: ConfigRef; cfile: Cfile): bool =
if conf.backend == backendJs: return false # pre-existing behavior, but not sure it's good
let hashFile = toGeneratedFile(conf, conf.withPackageName(cfile.cname), "sha1")
let hashFile = toGeneratedFile(conf, conf.mangleModuleName(cfile.cname).AbsoluteFile, "sha1")
let currentHash = footprint(conf, cfile)
var f: File
if open(f, hashFile.string, fmRead):
@@ -649,8 +655,10 @@ proc externalFileChanged(conf: ConfigRef; cfile: Cfile): bool =
close(f)
proc addExternalFileToCompile*(conf: ConfigRef; c: var Cfile) =
# we want to generate the hash file unconditionally
let extFileChanged = externalFileChanged(conf, c)
if optForceFullMake notin conf.globalOptions and fileExists(c.obj) and
not externalFileChanged(conf, c):
not extFileChanged:
c.flags.incl CfileFlag.Cached
else:
# make sure Nim keeps recompiling the external file on reruns
@@ -670,7 +678,8 @@ proc getLinkCmd(conf: ConfigRef; output: AbsoluteFile,
if removeStaticFile:
removeFile output # fixes: bug #16947
result = CC[conf.cCompiler].buildLib % ["libfile", quoteShell(output),
"objfiles", objfiles]
"objfiles", objfiles,
"vccplatform", vccplatform(conf)]
else:
var linkerExe = getConfigVar(conf, conf.cCompiler, ".linkerexe")
if linkerExe.len == 0: linkerExe = getLinkerExe(conf, conf.cCompiler)
@@ -703,7 +712,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 ' '
result.addf(linkTmpl, ["builddll", builddll,
strutils.addf(result, linkTmpl, ["builddll", builddll,
"mapfile", mapfile,
"buildgui", buildgui, "options", linkOptions,
"objfiles", objfiles, "exefile", exefile,
@@ -827,6 +836,15 @@ proc linkViaResponseFile(conf: ConfigRef; cmd: string) =
finally:
removeFile(linkerArgs)
proc linkViaShellScript(conf: ConfigRef; cmd: string) =
let linkerScript = conf.projectName & "_" & "linkerScript.sh"
writeFile(linkerScript, cmd)
let shell = getEnv("SHELL")
try:
execLinkCmd(conf, shell & " " & linkerScript)
finally:
removeFile(linkerScript)
proc getObjFilePath(conf: ConfigRef, f: Cfile): string =
if noAbsolutePaths(conf): f.obj.extractFilename
else: f.obj.string
@@ -840,9 +858,23 @@ proc hcrLinkTargetName(conf: ConfigRef, objFile: string, isMain = false): Absolu
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)
result = MsgKindToStr[hintCC] % (demangleModuleName(path.splitFile.name) & ": " & compileCmd)
else:
result = MsgKindToStr[hintCC] % demanglePackageName(path.splitFile.name)
result = MsgKindToStr[hintCC] % demangleModuleName(path.splitFile.name)
proc preventLinkCmdMaxCmdLen(conf: ConfigRef, linkCmd: string) =
# Prevent linkcmd from exceeding the maximum command line length.
# Windows's command line limit is about 8K (8191 characters) so C compilers on
# Windows support a feature where the command line can be passed via ``@linkcmd``
# to them.
const MaxCmdLen = when defined(windows): 8_000 elif defined(macosx): 260_000 else: 32_000
if linkCmd.len > MaxCmdLen:
when defined(macosx):
linkViaShellScript(conf, linkCmd)
else:
linkViaResponseFile(conf, linkCmd)
else:
execLinkCmd(conf, linkCmd)
proc callCCompiler*(conf: ConfigRef) =
var
@@ -852,7 +884,7 @@ proc callCCompiler*(conf: ConfigRef) =
return # speed up that call if only compiling and no script shall be
# generated
#var c = cCompiler
var script: Rope = nil
var script: Rope = ""
var cmds: TStringSeq
var prettyCmds: TStringSeq
let prettyCb = proc (idx: int) = writePrettyCmdsStderr(prettyCmds[idx])
@@ -915,19 +947,12 @@ proc callCCompiler*(conf: ConfigRef) =
objfiles.add(' ')
objfiles.add(quoteShell(objFile))
let mainOutput = if optGenScript notin conf.globalOptions: conf.prepareToWriteOutput
else: AbsoluteFile(conf.projectName)
else: AbsoluteFile(conf.outFile)
linkCmd = getLinkCmd(conf, mainOutput, objfiles, removeStaticFile = true)
extraCmds = getExtraCmds(conf, mainOutput)
if optCompileOnly notin conf.globalOptions:
const MaxCmdLen = when defined(windows): 8_000 else: 32_000
if linkCmd.len > MaxCmdLen:
# Windows's command line limit is about 8K (don't laugh...) so C compilers on
# Windows support a feature where the command line can be passed via ``@linkcmd``
# to them.
linkViaResponseFile(conf, linkCmd)
else:
execLinkCmd(conf, linkCmd)
preventLinkCmdMaxCmdLen(conf, linkCmd)
for cmd in extraCmds:
execExternalProgram(conf, cmd, hintExecuting)
else:
@@ -1011,7 +1036,7 @@ proc changeDetectedViaJsonBuildInstructions*(conf: ConfigRef; jsonFile: Absolute
proc runJsonBuildInstructions*(conf: ConfigRef; jsonFile: AbsoluteFile) =
var bcache: BuildCache
try: bcache.fromJson(jsonFile.string.parseFile)
except:
except ValueError, KeyError, JsonKindError:
let e = getCurrentException()
conf.quitOrRaise "\ncaught exception:\n$#\nstacktrace:\n$#error evaluating JSON file: $#" %
[e.msg, e.getStackTrace(), jsonFile.string]
@@ -1028,7 +1053,7 @@ proc runJsonBuildInstructions*(conf: ConfigRef; jsonFile: AbsoluteFile) =
cmds.add cmd
prettyCmds.add displayProgressCC(conf, name, cmd)
execCmdsInParallel(conf, cmds, prettyCb)
execLinkCmd(conf, bcache.linkcmd)
preventLinkCmdMaxCmdLen(conf, bcache.linkcmd)
for cmd in bcache.extraCmds: execExternalProgram(conf, cmd, hintExecuting)
proc genMappingFiles(conf: ConfigRef; list: CfileList): Rope =

View File

@@ -12,6 +12,9 @@
import msgs, std / sha1, os, osproc, streams, options,
lineinfos, pathutils
when defined(nimPreviewSlimSystem):
import std/syncio
proc readOutput(p: Process): (string, int) =
result[0] = ""
var output = p.outputStream
@@ -46,7 +49,11 @@ proc opGorge*(cmd, input, cache: string, info: TLineInfo; conf: ConfigRef): (str
if result[1] == 0:
writeFile(filename, result[0])
except IOError, OSError:
if not readSuccessful: result = ("", -1)
if not readSuccessful:
when defined(nimLegacyGorgeErrors):
result = ("", -1)
else:
result = ("Error running startProcess: " & getCurrentExceptionMsg(), -1)
else:
try:
var p = startProcess(cmd, workingDir,
@@ -57,4 +64,7 @@ proc opGorge*(cmd, input, cache: string, info: TLineInfo; conf: ConfigRef): (str
result = p.readOutput
p.close()
except IOError, OSError:
result = ("", -1)
when defined(nimLegacyGorgeErrors):
result = ("", -1)
else:
result = ("Error running startProcess: " & getCurrentExceptionMsg(), -1)

View File

@@ -12,6 +12,9 @@
import ast, astalgo, msgs, magicsys, nimsets, trees, types, renderer, idents,
saturate, modulegraphs, options, lineinfos, int128
when defined(nimPreviewSlimSystem):
import std/assertions
const
someEq = {mEqI, mEqF64, mEqEnum, mEqCh, mEqB, mEqRef, mEqProc,
mEqStr, mEqSet, mEqCString}
@@ -65,9 +68,12 @@ proc isLetLocation(m: PNode, isApprox: bool): bool =
case n.kind
of nkDotExpr, nkCheckedFieldExpr, nkObjUpConv, nkObjDownConv:
n = n[0]
of nkDerefExpr, nkHiddenDeref:
of nkDerefExpr:
n = n[0]
inc derefs
of nkHiddenDeref:
n = n[0]
if not isApprox: inc derefs
of nkBracketExpr:
if isConstExpr(n[1]) or isLet(n[1]) or isConstExpr(n[1].skipConv):
n = n[0]
@@ -197,7 +203,7 @@ proc highBound*(conf: ConfigRef; x: PNode; o: Operators): PNode =
nkIntLit.newIntNode(lastOrd(conf, typ))
elif typ.kind == tySequence and x.kind == nkSym and
x.sym.kind == skConst:
nkIntLit.newIntNode(x.sym.ast.len-1)
nkIntLit.newIntNode(x.sym.astdef.len-1)
else:
o.opAdd.buildCall(o.opLen.buildCall(x), minusOne())
result.info = x.info
@@ -1051,8 +1057,12 @@ proc buildProperFieldCheck(access, check: PNode; o: Operators): PNode =
assert check.getMagic == mNot
result = buildProperFieldCheck(access, check[1], o).neg(o)
proc checkFieldAccess*(m: TModel, n: PNode; conf: ConfigRef) =
proc checkFieldAccess*(m: TModel, n: PNode; conf: ConfigRef; produceError: bool) =
for i in 1..<n.len:
let check = buildProperFieldCheck(n[0], n[i], m.g.operators)
if check != nil and m.doesImply(check) != impYes:
message(conf, n.info, warnProveField, renderTree(n[0])); break
if produceError:
localError(conf, n.info, "field access outside of valid case branch: " & renderTree(n[0]))
else:
message(conf, n.info, warnProveField, renderTree(n[0]))
break

View File

@@ -8,6 +8,10 @@
#
# This include implements the high level optimization pass.
# included from sem.nim
when defined(nimPreviewSlimSystem):
import std/assertions
proc hlo(c: PContext, n: PNode): PNode
@@ -67,7 +71,7 @@ proc hlo(c: PContext, n: PNode): PNode =
# already processed (special cases in semstmts.nim)
result = n
else:
if n.kind in {nkFastAsgn, nkAsgn, nkIdentDefs, nkVarTuple} and
if n.kind in {nkFastAsgn, nkAsgn, nkSinkAsgn, nkIdentDefs, nkVarTuple} and
n[0].kind == nkSym and
{sfGlobal, sfPure} * n[0].sym.flags == {sfGlobal, sfPure}:
# do not optimize 'var g {.global} = re(...)' again!

View File

@@ -1,8 +1,11 @@
## A BiTable is a table that can be seen as an optimized pair
## of (Table[LitId, Val], Table[Val, LitId]).
## of `(Table[LitId, Val], Table[Val, LitId])`.
import hashes, rodfiles
when defined(nimPreviewSlimSystem):
import std/assertions
type
LitId* = distinct uint32
@@ -90,13 +93,13 @@ proc getOrIncl*[T](t: var BiTable[T]; v: T): LitId =
t.vals.add v
proc `[]`*[T](t: var BiTable[T]; LitId: LitId): var T {.inline.} =
let idx = idToIdx LitId
proc `[]`*[T](t: var BiTable[T]; litId: LitId): var T {.inline.} =
let idx = idToIdx litId
assert idx < t.vals.len
result = t.vals[idx]
proc `[]`*[T](t: BiTable[T]; LitId: LitId): lent T {.inline.} =
let idx = idToIdx LitId
proc `[]`*[T](t: BiTable[T]; litId: LitId): lent T {.inline.} =
let idx = idToIdx litId
assert idx < t.vals.len
result = t.vals[idx]

View File

@@ -20,8 +20,11 @@
import std/packedsets, algorithm, tables
when defined(nimPreviewSlimSystem):
import std/assertions
import ".."/[ast, options, lineinfos, modulegraphs, cgendata, cgen,
pathutils, extccomp, msgs]
pathutils, extccomp, msgs, modulepaths]
import packed_ast, ic, dce, rodfiles
@@ -61,7 +64,8 @@ proc addFileToLink(config: ConfigRef; m: PSym) =
if config.backend == backendCpp: ".nim.cpp"
elif config.backend == backendObjc: ".nim.m"
else: ".nim.c"
let cfile = changeFileExt(completeCfilePath(config, withPackageName(config, filename)), ext)
let cfile = changeFileExt(completeCfilePath(config,
mangleModuleName(config, filename).AbsoluteFile), ext)
let objFile = completeCfilePath(config, toObjFile(config, cfile))
if fileExists(objFile):
var cf = Cfile(nimname: m.name.s, cname: cfile,

View File

@@ -10,6 +10,10 @@
## Dead code elimination (=DCE) for IC.
import std/[intsets, tables]
when defined(nimPreviewSlimSystem):
import std/assertions
import ".." / [ast, options, lineinfos, types]
import packed_ast, ic, bitabs

View File

@@ -10,10 +10,13 @@
import hashes, tables, intsets, std/sha1
import packed_ast, bitabs, rodfiles
import ".." / [ast, idents, lineinfos, msgs, ropes, options,
pathutils, condsyms]
pathutils, condsyms, packages, modulepaths]
#import ".." / [renderer, astalgo]
from os import removeFile, isAbsolute
when defined(nimPreviewSlimSystem):
import std/[syncio, assertions, formatfloat]
type
PackedConfig* = object
backend: TBackend
@@ -40,11 +43,10 @@ type
reexports*: seq[(LitId, PackedItemId)]
compilerProcs*: seq[(LitId, int32)]
converters*, methods*, trmacros*, pureEnums*: seq[int32]
macroUsages*: seq[(PackedItemId, PackedLineInfo)]
typeInstCache*: seq[(PackedItemId, PackedItemId)]
procInstCache*: seq[PackedInstantiation]
attachedOps*: seq[(TTypeAttachedOp, PackedItemId, PackedItemId)]
attachedOps*: seq[(PackedItemId, TTypeAttachedOp, PackedItemId)]
methodsPerType*: seq[(PackedItemId, int, PackedItemId)]
enumToStringProcs*: seq[(PackedItemId, PackedItemId)]
@@ -352,7 +354,7 @@ proc storeType(t: PType; c: var PackedEncoder; m: var PackedModule): PackedItemI
var p = PackedType(kind: t.kind, flags: t.flags, callConv: t.callConv,
size: t.size, align: t.align, nonUniqueId: t.itemId.item,
paddingAtEnd: t.paddingAtEnd, lockLevel: t.lockLevel)
paddingAtEnd: t.paddingAtEnd)
storeNode(p, t, n)
p.typeInst = t.typeInst.storeType(c, m)
for kid in items t.sons:
@@ -400,7 +402,7 @@ proc storeSym*(s: PSym; c: var PackedEncoder; m: var PackedModule): PackedItemId
p.bitsize = s.bitsize
p.alignment = s.alignment
p.externalName = toLitId(if s.loc.r.isNil: "" else: $s.loc.r, m)
p.externalName = toLitId(s.loc.r, m)
p.locFlags = s.loc.flags
c.addMissing s.typ
p.typ = s.typ.storeType(c, m)
@@ -526,6 +528,15 @@ proc toPackedGeneratedProcDef*(s: PSym, encoder: var PackedEncoder; m: var Packe
toPackedProcDef(s.ast, m.topLevel, encoder, m)
#flush encoder, m
proc storeAttachedProcDef*(t: PType; op: TTypeAttachedOp; s: PSym,
encoder: var PackedEncoder; m: var PackedModule) =
assert s.kind in routineKinds
assert isActive(encoder)
let tid = storeTypeLater(t, encoder, m)
let sid = storeSymLater(s, encoder, m)
m.attachedOps.add (tid, op, sid)
toPackedGeneratedProcDef(s, encoder, m)
proc storeInstantiation*(c: var PackedEncoder; m: var PackedModule; s: PSym; i: PInstantiation) =
var t = newSeq[PackedItemId](i.concreteTypes.len)
for j in 0..high(i.concreteTypes):
@@ -548,6 +559,10 @@ proc loadError(err: RodFileError; filename: AbsoluteFile; config: ConfigRef;) =
rawMessage(config, warnCannotOpenFile, filename.string & " reason: " & $err)
#echo "Error: ", $err, " loading file: ", filename.string
proc toRodFile*(conf: ConfigRef; f: AbsoluteFile; ext = RodExt): AbsoluteFile =
result = changeFileExt(completeGeneratedFilePath(conf,
mangleModuleName(conf, f).AbsoluteFile), ext)
proc loadRodFile*(filename: AbsoluteFile; m: var PackedModule; config: ConfigRef;
ignoreConfig = false): RodFileError =
var f = rodfiles.open(filename.string)
@@ -590,7 +605,6 @@ proc loadRodFile*(filename: AbsoluteFile; m: var PackedModule; config: ConfigRef
loadSeqSection convertersSection, m.converters
loadSeqSection methodsSection, m.methods
loadSeqSection pureEnumsSection, m.pureEnums
loadSeqSection macroUsagesSection, m.macroUsages
loadSeqSection toReplaySection, m.toReplay.nodes
loadSeqSection topLevelSection, m.topLevel.nodes
@@ -654,7 +668,6 @@ proc saveRodFile*(filename: AbsoluteFile; encoder: var PackedEncoder; m: var Pac
storeSeqSection convertersSection, m.converters
storeSeqSection methodsSection, m.methods
storeSeqSection pureEnumsSection, m.pureEnums
storeSeqSection macroUsagesSection, m.macroUsages
storeSeqSection toReplaySection, m.toReplay.nodes
storeSeqSection topLevelSection, m.topLevel.nodes
@@ -887,7 +900,7 @@ proc typeHeaderFromPacked(c: var PackedDecoder; g: var PackedModuleGraph;
t: PackedType; si, item: int32): PType =
result = PType(itemId: ItemId(module: si, item: t.nonUniqueId), kind: t.kind,
flags: t.flags, size: t.size, align: t.align,
paddingAtEnd: t.paddingAtEnd, lockLevel: t.lockLevel,
paddingAtEnd: t.paddingAtEnd,
uniqueId: ItemId(module: si, item: item),
callConv: t.callConv)
@@ -927,17 +940,6 @@ proc loadType(c: var PackedDecoder; g: var PackedModuleGraph; thisModule: int; t
result = g[si].types[t.item]
assert result.itemId.item > 0
proc newPackage(config: ConfigRef; cache: IdentCache; fileIdx: FileIndex): PSym =
let filename = AbsoluteFile toFullPath(config, fileIdx)
let name = getIdent(cache, splitFile(filename).name)
let info = newLineInfo(fileIdx, 1, 1)
let
pck = getPackageName(config, filename.string)
pck2 = if pck.len > 0: pck else: "unknown"
pack = getIdent(cache, pck2)
result = newSym(skPackage, getIdent(cache, pck2),
ItemId(module: PackageModuleId, item: int32(fileIdx)), nil, info)
proc setupLookupTables(g: var PackedModuleGraph; conf: ConfigRef; cache: IdentCache;
fileIdx: FileIndex; m: var LoadedModule) =
m.iface = initTable[PIdent, seq[PackedItemId]]()
@@ -965,7 +967,7 @@ proc setupLookupTables(g: var PackedModuleGraph; conf: ConfigRef; cache: IdentCa
name: getIdent(cache, splitFile(filename).name),
info: newLineInfo(fileIdx, 1, 1),
position: int(fileIdx))
m.module.owner = newPackage(conf, cache, fileIdx)
m.module.owner = getPackage(conf, cache, fileIdx)
m.module.flags = m.fromDisk.moduleFlags
proc loadToReplayNodes(g: var PackedModuleGraph; conf: ConfigRef; cache: IdentCache;

View File

@@ -11,6 +11,10 @@
## The set must cover a complete Nim project.
import sets
when defined(nimPreviewSlimSystem):
import std/assertions
import ".." / [ast, modulegraphs]
import packed_ast, bitabs, ic

View File

@@ -16,6 +16,9 @@ import sets
from os import nil
from std/private/miscdollars import toLocation
when defined(nimPreviewSlimSystem):
import std/assertions
import ".." / [ast, modulegraphs, msgs, options]
import packed_ast, bitabs, ic

View File

@@ -16,6 +16,9 @@ import hashes, tables, strtabs
import bitabs
import ".." / [ast, options]
when defined(nimPreviewSlimSystem):
import std/assertions
type
SymId* = distinct int32
ModuleId* = distinct int32
@@ -81,7 +84,6 @@ type
size*: BiggestInt
align*: int16
paddingAtEnd*: int16
lockLevel*: TLockLevel # lock level as required for deadlock checking
# not serialized: loc*: TLoc because it is backend-specific
typeInst*: PackedItemId
nonUniqueId*: int32

View File

@@ -16,6 +16,9 @@ import ".." / [ast, modulegraphs, trees, extccomp, btrees,
import tables
when defined(nimPreviewSlimSystem):
import std/assertions
import packed_ast, ic, bitabs
proc replayStateChanges*(module: PSym; g: ModuleGraph) =
@@ -86,6 +89,20 @@ proc replayStateChanges*(module: PSym; g: ModuleGraph) =
else:
internalAssert g.config, false
proc replayBackendProcs*(g: ModuleGraph; module: int) =
for it in mitems(g.packed[module].fromDisk.attachedOps):
let key = translateId(it[0], g.packed, module, g.config)
let op = it[1]
let tmp = translateId(it[2], g.packed, module, g.config)
let symId = FullId(module: tmp.module, packed: it[2])
g.attachedOps[op][key] = LazySym(id: symId, sym: nil)
for it in mitems(g.packed[module].fromDisk.enumToStringProcs):
let key = translateId(it[0], g.packed, module, g.config)
let tmp = translateId(it[1], g.packed, module, g.config)
let symId = FullId(module: tmp.module, packed: it[1])
g.enumToStringProcs[key] = LazySym(id: symId, sym: nil)
proc replayGenericCacheInformation*(g: ModuleGraph; module: int) =
## We remember the generic instantiations a module performed
## in order to to avoid the code bloat that generic code tends
@@ -117,11 +134,7 @@ proc replayGenericCacheInformation*(g: ModuleGraph; module: int) =
let symId = FullId(module: tmp.module, packed: it[2])
g.methodsPerType.mgetOrPut(key, @[]).add (col, LazySym(id: symId, sym: nil))
for it in mitems(g.packed[module].fromDisk.enumToStringProcs):
let key = translateId(it[0], g.packed, module, g.config)
let tmp = translateId(it[1], g.packed, module, g.config)
let symId = FullId(module: tmp.module, packed: it[1])
g.enumToStringProcs[key] = LazySym(id: symId, sym: nil)
replayBackendProcs(g, module)
for it in mitems(g.packed[module].fromDisk.methods):
let sym = loadSymFromId(g.config, g.cache, g.packed, module,

View File

@@ -16,12 +16,15 @@
from typetraits import supportsCopyMem
when defined(nimPreviewSlimSystem):
import std/[syncio, assertions]
## Overview
## ========
## `RodFile` represents a Rod File (versioned binary format), and the
## associated data for common interactions such as IO and error tracking
## (`RodFileError`). The file format broken up into sections (`RodSection`)
## and preceeded by a header (see: `cookie`). The precise layout, section
## and preceded by a header (see: `cookie`). The precise layout, section
## ordering and data following the section are determined by the user. See
## `ic.loadRodFile`.
##
@@ -34,8 +37,7 @@ from typetraits import supportsCopyMem
##
## Now read the bits below to understand what's missing.
##
## Issues with the Example
## ```````````````````````
## ### Issues with the Example
## Missing Sections:
## This is a low level API, so headers and sections need to be stored and
## loaded by the user, see `storeHeader` & `loadHeader` and `storeSection` &
@@ -82,7 +84,6 @@ type
convertersSection
methodsSection
pureEnumsSection
macroUsagesSection
toReplaySection
topLevelSection
bodiesSection

View File

@@ -14,6 +14,9 @@
import
hashes, wordrecg
when defined(nimPreviewSlimSystem):
import std/assertions
type
PIdent* = ref TIdent
TIdent*{.acyclic.} = object

View File

@@ -15,6 +15,9 @@ import
modulegraphs, wordrecg, tables
from strutils import `%`
when defined(nimPreviewSlimSystem):
import std/assertions
proc readExceptSet*(c: PContext, n: PNode): IntSet =
assert n.kind in {nkImportExceptStmt, nkExportExceptStmt}
result = initIntSet()
@@ -185,11 +188,13 @@ template addUnnamedIt(c: PContext, fromMod: PSym; filter: untyped) {.dirty.} =
for it in mitems c.graph.ifaces[fromMod.position].converters:
if filter:
loadPackedSym(c.graph, it)
addConverter(c, it)
if sfExported in it.sym.flags:
addConverter(c, it)
for it in mitems c.graph.ifaces[fromMod.position].patterns:
if filter:
loadPackedSym(c.graph, it)
addPattern(c, it)
if sfExported in it.sym.flags:
addPattern(c, it)
for it in mitems c.graph.ifaces[fromMod.position].pureEnums:
if filter:
loadPackedSym(c.graph, it)
@@ -197,7 +202,7 @@ template addUnnamedIt(c: PContext, fromMod: PSym; filter: untyped) {.dirty.} =
proc importAllSymbolsExcept(c: PContext, fromMod: PSym, exceptSet: IntSet) =
c.addImport ImportedModule(m: fromMod, mode: importExcept, exceptSet: exceptSet)
addUnnamedIt(c, fromMod, it.sym.id notin exceptSet)
addUnnamedIt(c, fromMod, it.sym.name.id notin exceptSet)
proc importAllSymbols*(c: PContext, fromMod: PSym) =
c.addImport ImportedModule(m: fromMod, mode: importAll)

View File

@@ -15,21 +15,27 @@
import
intsets, strtabs, ast, astalgo, msgs, renderer, magicsys, types, idents,
strutils, options, dfa, lowerings, tables, modulegraphs,
strutils, options, lowerings, tables, modulegraphs,
lineinfos, parampatterns, sighashes, liftdestructors, optimizer,
varpartitions
varpartitions, aliasanalysis, dfa, wordrecg
from trees import exprStructuralEquivalent, getRoot
when defined(nimPreviewSlimSystem):
import std/assertions
from trees import exprStructuralEquivalent, getRoot, whichPragma
type
Con = object
owner: PSym
g: ControlFlowGraph
when true:
g: ControlFlowGraph
graph: ModuleGraph
inLoop, inSpawn, inLoopCond: int
uninit: IntSet # set of uninit'ed vars
uninitComputed: bool
idgen: IdGenerator
body: PNode
otherUsage: TLineInfo
inUncheckedAssignSection: int
Scope = object # we do scope-based memory management.
# a scope is comparable to an nkStmtListExpr like
@@ -37,6 +43,8 @@ type
vars: seq[PSym]
wasMoved: seq[PNode]
final: seq[PNode] # finally section
locals: seq[PSym]
body: PNode
needsTry: bool
parent: ptr Scope
@@ -67,167 +75,100 @@ proc getTemp(c: var Con; s: var Scope; typ: PType; info: TLineInfo): PNode =
s.vars.add(sym)
result = newSymNode(sym)
proc nestedScope(parent: var Scope): Scope =
Scope(vars: @[], wasMoved: @[], final: @[], needsTry: false, parent: addr(parent))
proc nestedScope(parent: var Scope; body: PNode): Scope =
Scope(vars: @[], locals: @[], wasMoved: @[], final: @[], body: body, needsTry: false, parent: addr(parent))
proc p(n: PNode; c: var Con; s: var Scope; mode: ProcessMode): PNode
proc moveOrCopy(dest, ri: PNode; c: var Con; s: var Scope; isDecl = false): PNode
import sets, hashes
proc hash(n: PNode): Hash = hash(cast[pointer](n))
proc aliasesCached(cache: var Table[(PNode, PNode), AliasKind], obj, field: PNode): AliasKind =
let key = (obj, field)
if not cache.hasKey(key):
cache[key] = aliases(obj, field)
cache[key]
proc p(n: PNode; c: var Con; s: var Scope; mode: ProcessMode; tmpFlags = {sfSingleUsedTemp}): PNode
type
State = ref object
lastReads: IntSet
potentialLastReads: IntSet
notLastReads: IntSet
alreadySeen: HashSet[PNode]
MoveOrCopyFlag = enum
IsDecl, IsExplicitSink
proc preprocessCfg(cfg: var ControlFlowGraph) =
for i in 0..<cfg.len:
if cfg[i].kind in {goto, fork} and i + cfg[i].dest > cfg.len:
cfg[i].dest = cfg.len - i
proc moveOrCopy(dest, ri: PNode; c: var Con; s: var Scope; flags: set[MoveOrCopyFlag] = {}): PNode
proc mergeStates(a: var State, b: sink State) =
# Inplace for performance:
# lastReads = a.lastReads + b.lastReads
# potentialLastReads = (a.potentialLastReads + b.potentialLastReads) - (a.notLastReads + b.notLastReads)
# notLastReads = a.notLastReads + b.notLastReads
# alreadySeen = a.alreadySeen + b.alreadySeen
# b is never nil
if a == nil:
a = b
when false:
var
perfCounters: array[InstrKind, int]
proc showCounters*() =
for i in low(InstrKind)..high(InstrKind):
echo "INSTR ", i, " ", perfCounters[i]
proc isLastReadImpl(n: PNode; c: var Con; scope: var Scope): bool =
let root = parampatterns.exprRoot(n, allowCalls=false)
if root == nil: return false
var s = addr(scope)
while s != nil:
if s.locals.contains(root): break
s = s.parent
c.g = constructCfg(c.owner, if s != nil: s.body else: c.body, root)
dbg:
echo "\n### ", c.owner.name.s, ":\nCFG:"
echoCfg(c.g)
#echo c.body
var j = 0
while j < c.g.len:
if c.g[j].kind == use and c.g[j].n == n: break
inc j
c.otherUsage = unknownLineInfo
if j < c.g.len:
var pcs = @[j+1]
var marked = initIntSet()
result = true
while pcs.len > 0:
var pc = pcs.pop()
if not marked.contains(pc):
let oldPc = pc
while pc < c.g.len:
dbg:
echo "EXEC ", c.g[pc].kind, " ", pc, " ", n
when false:
inc perfCounters[c.g[pc].kind]
case c.g[pc].kind
of loop:
let back = pc + c.g[pc].dest
if not marked.containsOrIncl(back):
pc = back
else:
break
of goto:
pc = pc + c.g[pc].dest
of fork:
if not marked.contains(pc+1):
pcs.add pc + 1
pc = pc + c.g[pc].dest
of use:
if c.g[pc].n.aliases(n) != no or n.aliases(c.g[pc].n) != no:
c.otherUsage = c.g[pc].n.info
return false
inc pc
of def:
if c.g[pc].n.aliases(n) == yes:
# the path leads to a redefinition of 's' --> sink 's'.
break
elif n.aliases(c.g[pc].n) != no:
# only partially writes to 's' --> can't sink 's', so this def reads 's'
# or maybe writes to 's' --> can't sink 's'
c.otherUsage = c.g[pc].n.info
return false
inc pc
marked.incl oldPc
else:
a.lastReads.incl b.lastReads
a.potentialLastReads.incl b.potentialLastReads
a.potentialLastReads.excl a.notLastReads
a.potentialLastReads.excl b.notLastReads
a.notLastReads.incl b.notLastReads
a.alreadySeen.incl b.alreadySeen
result = false
proc computeLastReadsAndFirstWrites(cfg: ControlFlowGraph) =
var cache = initTable[(PNode, PNode), AliasKind]()
template aliasesCached(obj, field: PNode): AliasKind =
aliasesCached(cache, obj, field)
proc isLastRead(n: PNode; c: var Con; s: var Scope): bool =
if not hasDestructor(c, n.typ): return true
var cfg = cfg
preprocessCfg(cfg)
var states = newSeq[State](cfg.len + 1)
states[0] = State()
for pc in 0..<cfg.len:
template state: State = states[pc]
if state != nil:
case cfg[pc].kind
of def:
var potentialLastReadsCopy = state.potentialLastReads
for r in potentialLastReadsCopy:
if cfg[pc].n.aliasesCached(cfg[r].n) == yes:
# the path leads to a redefinition of 's' --> sink 's'.
state.lastReads.incl r
state.potentialLastReads.excl r
elif cfg[r].n.aliasesCached(cfg[pc].n) != no:
# only partially writes to 's' --> can't sink 's', so this def reads 's'
# or maybe writes to 's' --> can't sink 's'
cfg[r].n.comment = '\n' & $pc
state.potentialLastReads.excl r
state.notLastReads.incl r
var alreadySeenThisNode = false
for s in state.alreadySeen:
if cfg[pc].n.aliasesCached(s) != no or s.aliasesCached(cfg[pc].n) != no:
alreadySeenThisNode = true; break
if alreadySeenThisNode: cfg[pc].n.flags.excl nfFirstWrite
else: cfg[pc].n.flags.incl nfFirstWrite
state.alreadySeen.incl cfg[pc].n
mergeStates(states[pc + 1], move(states[pc]))
of use:
var potentialLastReadsCopy = state.potentialLastReads
for r in potentialLastReadsCopy:
if cfg[pc].n.aliasesCached(cfg[r].n) != no or cfg[r].n.aliasesCached(cfg[pc].n) != no:
cfg[r].n.comment = '\n' & $pc
state.potentialLastReads.excl r
state.notLastReads.incl r
state.potentialLastReads.incl pc
state.alreadySeen.incl cfg[pc].n
mergeStates(states[pc + 1], move(states[pc]))
of goto:
mergeStates(states[pc + cfg[pc].dest], move(states[pc]))
of fork:
var copy = State()
copy[] = states[pc][]
mergeStates(states[pc + cfg[pc].dest], copy)
mergeStates(states[pc + 1], move(states[pc]))
let lastReads = (states[^1].lastReads + states[^1].potentialLastReads) - states[^1].notLastReads
var lastReadTable: Table[PNode, seq[int]]
for position, node in cfg:
if node.kind == use:
lastReadTable.mgetOrPut(node.n, @[]).add position
for node, positions in lastReadTable:
block checkIfAllPosLastRead:
for p in positions:
if p notin lastReads: break checkIfAllPosLastRead
node.flags.incl nfLastRead
proc isLastRead(n: PNode; c: var Con): bool =
let m = dfa.skipConvDfa(n)
(m.kind == nkSym and sfSingleUsedTemp in m.sym.flags) or nfLastRead in m.flags
let m = skipConvDfa(n)
result = (m.kind == nkSym and sfSingleUsedTemp in m.sym.flags) or
isLastReadImpl(n, c, s)
proc isFirstWrite(n: PNode; c: var Con): bool =
let m = dfa.skipConvDfa(n)
nfFirstWrite in m.flags
proc initialized(code: ControlFlowGraph; pc: int,
init, uninit: var IntSet; until: int): int =
## Computes the set of definitely initialized variables across all code paths
## as an IntSet of IDs.
var pc = pc
while pc < code.len:
case code[pc].kind
of goto:
pc += code[pc].dest
of fork:
var initA = initIntSet()
var initB = initIntSet()
var variantA = pc + 1
var variantB = pc + code[pc].dest
while variantA != variantB:
if max(variantA, variantB) > until:
break
if variantA < variantB:
variantA = initialized(code, variantA, initA, uninit, min(variantB, until))
else:
variantB = initialized(code, variantB, initB, uninit, min(variantA, until))
pc = min(variantA, variantB)
# we add vars if they are in both branches:
for v in initA:
if v in initB:
init.incl v
of use:
let v = code[pc].n.sym
if v.kind != skParam and v.id notin init:
# attempt to read an uninit'ed variable
uninit.incl v.id
inc pc
of def:
let v = code[pc].n.sym
init.incl v.id
inc pc
return pc
let m = skipConvDfa(n)
result = nfFirstWrite in m.flags
proc isCursor(n: PNode): bool =
case n.kind
@@ -251,9 +192,11 @@ proc checkForErrorPragma(c: Con; t: PType; ri: PNode; opname: string) =
m.add "; requires a copy because it's not the last read of '"
m.add renderTree(ri)
m.add '\''
if ri.comment.startsWith('\n'):
if c.otherUsage != unknownLineInfo:
# ri.comment.startsWith('\n'):
m.add "; another read is done here: "
m.add c.graph.config $ c.g[parseInt(ri.comment[1..^1])].n.info
m.add c.graph.config $ c.otherUsage
#m.add c.graph.config $ c.g[parseInt(ri.comment[1..^1])].n.info
elif ri.kind == nkSym and ri.sym.kind == skParam and not isSinkType(ri.sym.typ):
m.add "; try to make "
m.add renderTree(ri)
@@ -275,7 +218,7 @@ proc genOp(c: var Con; t: PType; kind: TTypeAttachedOp; dest, ri: PNode): PNode
var op = getAttachedOp(c.graph, t, kind)
if op == nil or op.ast.isGenericRoutine:
# give up and find the canonical type instead:
let h = sighashes.hashType(t, {CoType, CoConsiderOwned, CoDistinct})
let h = sighashes.hashType(t, c.graph.config, {CoType, CoConsiderOwned, CoDistinct})
let canon = c.graph.canonTypes.getOrDefault(h)
if canon != nil:
op = getAttachedOp(c.graph, canon, kind)
@@ -306,8 +249,8 @@ proc canBeMoved(c: Con; t: PType): bool {.inline.} =
proc isNoInit(dest: PNode): bool {.inline.} =
result = dest.kind == nkSym and sfNoInit in dest.sym.flags
proc genSink(c: var Con; dest, ri: PNode, isDecl = false): PNode =
if (c.inLoopCond == 0 and (isUnpackedTuple(dest) or isDecl or
proc genSink(c: var Con; dest, ri: PNode; flags: set[MoveOrCopyFlag] = {}): PNode =
if (c.inLoopCond == 0 and (isUnpackedTuple(dest) or IsDecl in flags or
(isAnalysableFieldAccess(dest, c.owner) and isFirstWrite(dest, c)))) or
isNoInit(dest):
# optimize sink call into a bitwise memcopy
@@ -359,17 +302,21 @@ proc genMarkCyclic(c: var Con; result, dest: PNode) =
xenv.typ = getSysType(c.graph, dest.info, tyPointer)
result.add callCodegenProc(c.graph, "nimMarkCyclic", dest.info, xenv)
proc genCopyNoCheck(c: var Con; dest, ri: PNode): PNode =
proc genCopyNoCheck(c: var Con; dest, ri: PNode; a: TTypeAttachedOp): PNode =
let t = dest.typ.skipTypes({tyGenericInst, tyAlias, tySink})
result = c.genOp(t, attachedAsgn, dest, ri)
result = c.genOp(t, a, dest, ri)
assert ri.typ != nil
proc genCopy(c: var Con; dest, ri: PNode): PNode =
proc genCopy(c: var Con; dest, ri: PNode; flags: set[MoveOrCopyFlag]): PNode =
let t = dest.typ
if tfHasOwned in t.flags and ri.kind != nkNilLit:
# try to improve the error message here:
c.checkForErrorPragma(t, ri, "=copy")
result = c.genCopyNoCheck(dest, ri)
if IsExplicitSink in flags:
c.checkForErrorPragma(t, ri, "=sink")
else:
c.checkForErrorPragma(t, ri, "=copy")
let a = if IsExplicitSink in flags: attachedSink else: attachedAsgn
result = c.genCopyNoCheck(dest, ri, a)
assert ri.typ != nil
proc genDiscriminantAsgn(c: var Con; s: var Scope; n: PNode): PNode =
@@ -396,23 +343,31 @@ It is best to factor out piece of object that needs custom destructor into separ
return
# generate: if le != tmp: `=destroy`(le)
let branchDestructor = produceDestructorForDiscriminator(c.graph, objType, leDotExpr[1].sym, n.info, c.idgen)
let cond = newNodeIT(nkInfix, n.info, getSysType(c.graph, unknownLineInfo, tyBool))
cond.add newSymNode(getMagicEqSymForType(c.graph, le.typ, n.info))
cond.add le
cond.add tmp
let notExpr = newNodeIT(nkPrefix, n.info, getSysType(c.graph, unknownLineInfo, tyBool))
notExpr.add newSymNode(createMagic(c.graph, c.idgen, "not", mNot))
notExpr.add cond
result.add newTree(nkIfStmt, newTree(nkElifBranch, notExpr, c.genOp(branchDestructor, le)))
if c.inUncheckedAssignSection != 0:
let branchDestructor = produceDestructorForDiscriminator(c.graph, objType, leDotExpr[1].sym, n.info, c.idgen)
let cond = newNodeIT(nkInfix, n.info, getSysType(c.graph, unknownLineInfo, tyBool))
cond.add newSymNode(getMagicEqSymForType(c.graph, le.typ, n.info))
cond.add le
cond.add tmp
let notExpr = newNodeIT(nkPrefix, n.info, getSysType(c.graph, unknownLineInfo, tyBool))
notExpr.add newSymNode(createMagic(c.graph, c.idgen, "not", mNot))
notExpr.add cond
result.add newTree(nkIfStmt, newTree(nkElifBranch, notExpr, c.genOp(branchDestructor, le)))
result.add newTree(nkFastAsgn, le, tmp)
proc genWasMoved(c: var Con, n: PNode): PNode =
result = newNodeI(nkCall, n.info)
result.add(newSymNode(createMagic(c.graph, c.idgen, "wasMoved", mWasMoved)))
result.add copyTree(n) #mWasMoved does not take the address
#if n.kind != nkSym:
# message(c.graph.config, n.info, warnUser, "wasMoved(" & $n & ")")
let typ = n.typ.skipTypes({tyGenericInst, tyAlias, tySink})
let op = getAttachedOp(c.graph, n.typ, attachedWasMoved)
if op != nil:
if sfError in op.flags:
c.checkForErrorPragma(n.typ, n, "=wasMoved")
result = genOp(c, op, n)
else:
result = newNodeI(nkCall, n.info)
result.add(newSymNode(createMagic(c.graph, c.idgen, "wasMoved", mWasMoved)))
result.add copyTree(n) #mWasMoved does not take the address
#if n.kind != nkSym:
# message(c.graph.config, n.info, warnUser, "wasMoved(" & $n & ")")
proc genDefaultCall(t: PType; c: Con; info: TLineInfo): PNode =
result = newNodeI(nkCall, info)
@@ -454,7 +409,7 @@ proc passCopyToSink(n: PNode; c: var Con; s: var Scope): PNode =
let tmp = c.getTemp(s, n.typ, n.info)
if hasDestructor(c, n.typ):
result.add c.genWasMoved(tmp)
var m = c.genCopy(tmp, n)
var m = c.genCopy(tmp, n, {})
m.add p(n, c, s, normal)
c.finishCopy(m, n, isFromSink = true)
result.add m
@@ -499,7 +454,7 @@ proc ensureDestruction(arg, orig: PNode; c: var Con; s: var Scope): PNode =
# This was already done in the sink parameter handling logic.
result = newNodeIT(nkStmtListExpr, arg.info, arg.typ)
let tmp = c.getTemp(s, arg.typ, arg.info)
result.add c.genSink(tmp, arg, isDecl = true)
result.add c.genSink(tmp, arg, {IsDecl})
result.add tmp
s.final.add c.genDestroy(tmp)
else:
@@ -544,7 +499,7 @@ proc pVarTopLevel(v: PNode; c: var Con; s: var Scope; res: PNode) =
res.add newTree(nkFastAsgn, v, genDefaultCall(v.typ, c, v.info))
elif sfThread notin v.sym.flags and sfCursor notin v.sym.flags:
# do not destroy thread vars for now at all for consistency.
if sfGlobal in v.sym.flags and s.parent == nil: #XXX: Rethink this logic (see tarcmisc.test2)
if {sfGlobal, sfPure} <= v.sym.flags or sfGlobal in v.sym.flags and s.parent == nil:
c.graph.globalDestructors.add c.genDestroy(v)
else:
s.final.add c.genDestroy(v)
@@ -571,17 +526,17 @@ proc processScope(c: var Con; s: var Scope; ret: PNode): PNode =
if s.parent != nil: s.parent[].needsTry = s.parent[].needsTry or s.needsTry
template processScopeExpr(c: var Con; s: var Scope; ret: PNode, processCall: untyped): PNode =
template processScopeExpr(c: var Con; s: var Scope; ret: PNode, processCall: untyped, tmpFlags: TSymFlags): PNode =
assert not ret.typ.isEmptyType
var result = newNodeI(nkStmtListExpr, ret.info)
var result = newNodeIT(nkStmtListExpr, ret.info, ret.typ)
# There is a possibility to do this check: s.wasMoved.len > 0 or s.final.len > 0
# later and use it to eliminate the temporary when theres no need for it, but its
# tricky because you would have to intercept moveOrCopy at a certain point
let tmp = c.getTemp(s.parent[], ret.typ, ret.info)
tmp.sym.flags.incl sfSingleUsedTemp
tmp.sym.flags = tmpFlags
let cpy = if hasDestructor(c, ret.typ):
s.parent[].final.add c.genDestroy(tmp)
moveOrCopy(tmp, ret, c, s, isDecl = true)
moveOrCopy(tmp, ret, c, s, {IsDecl})
else:
newTree(nkFastAsgn, tmp, p(ret, c, s, normal))
@@ -605,7 +560,8 @@ template processScopeExpr(c: var Con; s: var Scope; ret: PNode, processCall: unt
result
template handleNestedTempl(n, processCall: untyped, willProduceStmt = false) =
template handleNestedTempl(n, processCall: untyped, willProduceStmt = false,
tmpFlags = {sfSingleUsedTemp}) =
template maybeVoid(child, s): untyped =
if isEmptyType(child.typ): p(child, c, s, normal)
else: processCall(child, s)
@@ -629,11 +585,11 @@ template handleNestedTempl(n, processCall: untyped, willProduceStmt = false) =
var branch = shallowCopy(it)
for j in 0 ..< it.len-1:
branch[j] = copyTree(it[j])
var ofScope = nestedScope(s)
var ofScope = nestedScope(s, it.lastSon)
branch[^1] = if it[^1].typ.isEmptyType or willProduceStmt:
processScope(c, ofScope, maybeVoid(it[^1], ofScope))
else:
processScopeExpr(c, ofScope, it[^1], processCall)
processScopeExpr(c, ofScope, it[^1], processCall, tmpFlags)
result.add branch
of nkWhileStmt:
@@ -642,7 +598,7 @@ template handleNestedTempl(n, processCall: untyped, willProduceStmt = false) =
result = copyNode(n)
result.add p(n[0], c, s, normal)
dec c.inLoopCond
var bodyScope = nestedScope(s)
var bodyScope = nestedScope(s, n[1])
let bodyResult = p(n[1], c, bodyScope, normal)
result.add processScope(c, bodyScope, bodyResult)
dec c.inLoop
@@ -654,7 +610,7 @@ template handleNestedTempl(n, processCall: untyped, willProduceStmt = false) =
for i in 0..<last-1:
result[i] = n[i]
result[last-1] = p(n[last-1], c, s, normal)
var bodyScope = nestedScope(s)
var bodyScope = nestedScope(s, n[1])
let bodyResult = p(n[last], c, bodyScope, normal)
result[last] = processScope(c, bodyScope, bodyResult)
dec c.inLoop
@@ -662,18 +618,18 @@ template handleNestedTempl(n, processCall: untyped, willProduceStmt = false) =
of nkBlockStmt, nkBlockExpr:
result = copyNode(n)
result.add n[0]
var bodyScope = nestedScope(s)
var bodyScope = nestedScope(s, n[1])
result.add if n[1].typ.isEmptyType or willProduceStmt:
processScope(c, bodyScope, processCall(n[1], bodyScope))
else:
processScopeExpr(c, bodyScope, n[1], processCall)
processScopeExpr(c, bodyScope, n[1], processCall, tmpFlags)
of nkIfStmt, nkIfExpr:
result = copyNode(n)
for i in 0..<n.len:
let it = n[i]
var branch = shallowCopy(it)
var branchScope = nestedScope(s)
var branchScope = nestedScope(s, it.lastSon)
if it.kind in {nkElifBranch, nkElifExpr}:
#Condition needs to be destroyed outside of the condition/branch scope
branch[0] = p(it[0], c, s, normal)
@@ -681,26 +637,26 @@ template handleNestedTempl(n, processCall: untyped, willProduceStmt = false) =
branch[^1] = if it[^1].typ.isEmptyType or willProduceStmt:
processScope(c, branchScope, maybeVoid(it[^1], branchScope))
else:
processScopeExpr(c, branchScope, it[^1], processCall)
processScopeExpr(c, branchScope, it[^1], processCall, tmpFlags)
result.add branch
of nkTryStmt:
result = copyNode(n)
var tryScope = nestedScope(s)
var tryScope = nestedScope(s, n[0])
result.add if n[0].typ.isEmptyType or willProduceStmt:
processScope(c, tryScope, maybeVoid(n[0], tryScope))
else:
processScopeExpr(c, tryScope, n[0], maybeVoid)
processScopeExpr(c, tryScope, n[0], maybeVoid, tmpFlags)
for i in 1..<n.len:
let it = n[i]
var branch = copyTree(it)
var branchScope = nestedScope(s)
var branchScope = nestedScope(s, it[^1])
branch[^1] = if it[^1].typ.isEmptyType or willProduceStmt or it.kind == nkFinally:
processScope(c, branchScope, if it.kind == nkFinally: p(it[^1], c, branchScope, normal)
else: maybeVoid(it[^1], branchScope))
else:
processScopeExpr(c, branchScope, it[^1], processCall)
processScopeExpr(c, branchScope, it[^1], processCall, tmpFlags)
result.add branch
of nkWhen: # This should be a "when nimvm" node.
@@ -716,7 +672,7 @@ proc pRaiseStmt(n: PNode, c: var Con; s: var Scope): PNode =
result.add call
else:
let tmp = c.getTemp(s, n[0].typ, n.info)
var m = c.genCopyNoCheck(tmp, n[0])
var m = c.genCopyNoCheck(tmp, n[0], attachedAsgn)
m.add p(n[0], c, s, normal)
c.finishCopy(m, n[0], isFromSink = false)
result = newTree(nkStmtList, c.genWasMoved(tmp), m)
@@ -733,11 +689,11 @@ proc pRaiseStmt(n: PNode, c: var Con; s: var Scope): PNode =
result.add copyNode(n[0])
s.needsTry = true
proc p(n: PNode; c: var Con; s: var Scope; mode: ProcessMode): PNode =
proc p(n: PNode; c: var Con; s: var Scope; mode: ProcessMode; tmpFlags = {sfSingleUsedTemp}): PNode =
if n.kind in {nkStmtList, nkStmtListExpr, nkBlockStmt, nkBlockExpr, nkIfStmt,
nkIfExpr, nkCaseStmt, nkWhen, nkWhileStmt, nkParForStmt, nkTryStmt}:
template process(child, s): untyped = p(child, c, s, mode)
handleNestedTempl(n, process)
handleNestedTempl(n, process, tmpFlags = tmpFlags)
elif mode == sinkArg:
if n.containsConstSeq:
# const sequences are not mutable and so we need to pass a copy to the
@@ -748,7 +704,7 @@ proc p(n: PNode; c: var Con; s: var Scope; mode: ProcessMode): PNode =
nkCallKinds + nkLiterals:
result = p(n, c, s, consumed)
elif ((n.kind == nkSym and isSinkParam(n.sym)) or isAnalysableFieldAccess(n, c.owner)) and
isLastRead(n, c) and not (n.kind == nkSym and isCursor(n)):
isLastRead(n, c, s) and not (n.kind == nkSym and isCursor(n)):
# Sinked params can be consumed only once. We need to reset the memory
# to disable the destructor which we have not elided
result = destructiveMoveVar(n, c, s)
@@ -868,32 +824,43 @@ proc p(n: PNode; c: var Con; s: var Scope; mode: ProcessMode): PNode =
for it in n:
var ri = it[^1]
if it.kind == nkVarTuple and hasDestructor(c, ri.typ):
for i in 0..<it.len-2:
if it[i].kind == nkSym: s.locals.add it[i].sym
let x = lowerTupleUnpacking(c.graph, it, c.idgen, c.owner)
result.add p(x, c, s, consumed)
elif it.kind == nkIdentDefs and hasDestructor(c, it[0].typ):
elif it.kind == nkIdentDefs and hasDestructor(c, skipPragmaExpr(it[0]).typ):
for j in 0..<it.len-2:
let v = it[j]
let v = skipPragmaExpr(it[j])
if v.kind == nkSym:
if sfCompileTime in v.sym.flags: continue
s.locals.add v.sym
pVarTopLevel(v, c, s, result)
if ri.kind != nkEmpty:
result.add moveOrCopy(v, ri, c, s, isDecl = v.kind == nkSym)
result.add moveOrCopy(v, ri, c, s, if v.kind == nkSym: {IsDecl} else: {})
elif ri.kind == nkEmpty and c.inLoop > 0:
result.add moveOrCopy(v, genDefaultCall(v.typ, c, v.info), c, s, isDecl = v.kind == nkSym)
let skipInit = v.kind == nkDotExpr and # Closure var
sfNoInit in v[1].sym.flags
if not skipInit:
result.add moveOrCopy(v, genDefaultCall(v.typ, c, v.info), c, s, if v.kind == nkSym: {IsDecl} else: {})
else: # keep the var but transform 'ri':
var v = copyNode(n)
var itCopy = copyNode(it)
for j in 0..<it.len-1:
itCopy.add it[j]
itCopy.add p(it[^1], c, s, normal)
var flags = {sfSingleUsedTemp}
if it.kind == nkIdentDefs and it.len == 3 and it[0].kind == nkSym and
sfGlobal in it[0].sym.flags:
flags.incl sfGlobal
itCopy.add p(it[^1], c, s, normal, tmpFlags = flags)
v.add itCopy
result.add v
of nkAsgn, nkFastAsgn:
of nkAsgn, nkFastAsgn, nkSinkAsgn:
if hasDestructor(c, n[0].typ) and n[1].kind notin {nkProcDef, nkDo, nkLambda}:
if n[0].kind in {nkDotExpr, nkCheckedFieldExpr}:
cycleCheck(n, c)
assert n[1].kind notin {nkAsgn, nkFastAsgn}
result = moveOrCopy(p(n[0], c, s, mode), n[1], c, s)
assert n[1].kind notin {nkAsgn, nkFastAsgn, nkSinkAsgn}
let flags = if n.kind == nkSinkAsgn: {IsExplicitSink} else: {}
result = moveOrCopy(p(n[0], c, s, mode), n[1], c, s, flags)
elif isDiscriminantField(n[0]):
result = c.genDiscriminantAsgn(s, n)
else:
@@ -912,7 +879,7 @@ proc p(n: PNode; c: var Con; s: var Scope; mode: ProcessMode): PNode =
nkTypeOfExpr, nkMixinStmt, nkBindStmt:
result = n
of nkStringToCString, nkCStringToString, nkChckRangeF, nkChckRange64, nkChckRange, nkPragmaBlock:
of nkStringToCString, nkCStringToString, nkChckRangeF, nkChckRange64, nkChckRange:
result = shallowCopy(n)
for i in 0 ..< n.len:
result[i] = p(n[i], c, s, normal)
@@ -920,6 +887,25 @@ proc p(n: PNode; c: var Con; s: var Scope; mode: ProcessMode): PNode =
if mode == normal:
result = ensureDestruction(result, n, c, s)
of nkPragmaBlock:
var inUncheckedAssignSection = 0
let pragmaList = n[0]
for pi in pragmaList:
if whichPragma(pi) == wCast:
case whichPragma(pi[1])
of wUncheckedAssign:
inUncheckedAssignSection = 1
else:
discard
result = shallowCopy(n)
inc c.inUncheckedAssignSection, inUncheckedAssignSection
for i in 0 ..< n.len:
result[i] = p(n[i], c, s, normal)
dec c.inUncheckedAssignSection, inUncheckedAssignSection
if n.typ != nil and hasDestructor(c, n.typ):
if mode == normal:
result = ensureDestruction(result, n, c, s)
of nkHiddenSubConv, nkHiddenStdConv, nkConv:
# we have an "ownership invariance" for all constructors C(x).
# See the comment for nkBracket construction. If the caller wants
@@ -947,7 +933,7 @@ proc p(n: PNode; c: var Con; s: var Scope; mode: ProcessMode): PNode =
for i in 1 ..< n.len:
result[i] = n[i]
if mode == sinkArg and hasDestructor(c, n.typ):
if isAnalysableFieldAccess(n, c.owner) and isLastRead(n, c):
if isAnalysableFieldAccess(n, c.owner) and isLastRead(n, c, s):
s.wasMoved.add c.genWasMoved(n)
else:
result = passCopyToSink(result, c, s)
@@ -957,7 +943,7 @@ proc p(n: PNode; c: var Con; s: var Scope; mode: ProcessMode): PNode =
for i in 0 ..< n.len:
result[i] = p(n[i], c, s, normal)
if mode == sinkArg and hasDestructor(c, n.typ):
if isAnalysableFieldAccess(n, c.owner) and isLastRead(n, c):
if isAnalysableFieldAccess(n, c.owner) and isLastRead(n, c, s):
# consider 'a[(g; destroy(g); 3)]', we want to say 'wasMoved(a[3])'
# without the junk, hence 'c.genWasMoved(n)'
# and not 'c.genWasMoved(result)':
@@ -1018,14 +1004,34 @@ proc sameLocation*(a, b: PNode): bool =
of nkHiddenStdConv, nkHiddenSubConv: sameLocation(a[1], b)
else: false
proc moveOrCopy(dest, ri: PNode; c: var Con; s: var Scope, isDecl = false): PNode =
proc genFieldAccessSideEffects(c: var Con; dest, ri: PNode; flags: set[MoveOrCopyFlag] = {}): PNode =
# with side effects
var temp = newSym(skLet, getIdent(c.graph.cache, "bracketTmp"), nextSymId c.idgen, c.owner, ri[1].info)
temp.typ = ri[1].typ
var v = newNodeI(nkLetSection, ri[1].info)
let tempAsNode = newSymNode(temp)
var vpart = newNodeI(nkIdentDefs, tempAsNode.info, 3)
vpart[0] = tempAsNode
vpart[1] = newNodeI(nkEmpty, tempAsNode.info)
vpart[2] = ri[1]
v.add(vpart)
var newAccess = copyNode(ri)
newAccess.add ri[0]
newAccess.add tempAsNode
var snk = c.genSink(dest, newAccess, flags)
result = newTree(nkStmtList, v, snk, c.genWasMoved(newAccess))
proc moveOrCopy(dest, ri: PNode; c: var Con; s: var Scope, flags: set[MoveOrCopyFlag] = {}): PNode =
if sameLocation(dest, ri):
# rule (self-assignment-removal):
result = newNodeI(nkEmpty, dest.info)
elif isCursor(dest):
case ri.kind:
of nkStmtListExpr, nkBlockExpr, nkIfExpr, nkCaseStmt, nkTryStmt:
template process(child, s): untyped = moveOrCopy(dest, child, c, s, isDecl)
template process(child, s): untyped = moveOrCopy(dest, child, c, s, flags)
# We know the result will be a stmt so we use that fact to optimize
handleNestedTempl(ri, process, willProduceStmt = true)
else:
@@ -1033,108 +1039,106 @@ proc moveOrCopy(dest, ri: PNode; c: var Con; s: var Scope, isDecl = false): PNod
else:
case ri.kind
of nkCallKinds:
result = c.genSink(dest, p(ri, c, s, consumed), isDecl)
result = c.genSink(dest, p(ri, c, s, consumed), flags)
of nkBracketExpr:
if isUnpackedTuple(ri[0]):
# unpacking of tuple: take over the elements
result = c.genSink(dest, p(ri, c, s, consumed), isDecl)
elif isAnalysableFieldAccess(ri, c.owner) and isLastRead(ri, c):
result = c.genSink(dest, p(ri, c, s, consumed), flags)
elif isAnalysableFieldAccess(ri, c.owner) and isLastRead(ri, c, s):
if aliases(dest, ri) == no:
# Rule 3: `=sink`(x, z); wasMoved(z)
var snk = c.genSink(dest, ri, isDecl)
result = newTree(nkStmtList, snk, c.genWasMoved(ri))
if isAtom(ri[1]):
var snk = c.genSink(dest, ri, flags)
result = newTree(nkStmtList, snk, c.genWasMoved(ri))
else:
result = genFieldAccessSideEffects(c, dest, ri, flags)
else:
result = c.genSink(dest, destructiveMoveVar(ri, c, s), isDecl)
result = c.genSink(dest, destructiveMoveVar(ri, c, s), flags)
else:
result = c.genCopy(dest, ri)
result = c.genCopy(dest, ri, flags)
result.add p(ri, c, s, consumed)
c.finishCopy(result, dest, isFromSink = false)
of nkBracket:
# array constructor
if ri.len > 0 and isDangerousSeq(ri.typ):
result = c.genCopy(dest, ri)
result = c.genCopy(dest, ri, flags)
result.add p(ri, c, s, consumed)
c.finishCopy(result, dest, isFromSink = false)
else:
result = c.genSink(dest, p(ri, c, s, consumed), isDecl)
result = c.genSink(dest, p(ri, c, s, consumed), flags)
of nkObjConstr, nkTupleConstr, nkClosure, nkCharLit..nkNilLit:
result = c.genSink(dest, p(ri, c, s, consumed), isDecl)
result = c.genSink(dest, p(ri, c, s, consumed), flags)
of nkSym:
if isSinkParam(ri.sym) and isLastRead(ri, c):
if isSinkParam(ri.sym) and isLastRead(ri, c, s):
# Rule 3: `=sink`(x, z); wasMoved(z)
let snk = c.genSink(dest, ri, isDecl)
let snk = c.genSink(dest, ri, flags)
result = newTree(nkStmtList, snk, c.genWasMoved(ri))
elif ri.sym.kind != skParam and ri.sym.owner == c.owner and
isLastRead(ri, c) and canBeMoved(c, dest.typ) and not isCursor(ri):
isLastRead(ri, c, s) and canBeMoved(c, dest.typ) and not isCursor(ri):
# Rule 3: `=sink`(x, z); wasMoved(z)
let snk = c.genSink(dest, ri, isDecl)
let snk = c.genSink(dest, ri, flags)
result = newTree(nkStmtList, snk, c.genWasMoved(ri))
else:
result = c.genCopy(dest, ri)
result = c.genCopy(dest, ri, flags)
result.add p(ri, c, s, consumed)
c.finishCopy(result, dest, isFromSink = false)
of nkHiddenSubConv, nkHiddenStdConv, nkConv, nkObjDownConv, nkObjUpConv, nkCast:
result = c.genSink(dest, p(ri, c, s, sinkArg), isDecl)
result = c.genSink(dest, p(ri, c, s, sinkArg), flags)
of nkStmtListExpr, nkBlockExpr, nkIfExpr, nkCaseStmt, nkTryStmt:
template process(child, s): untyped = moveOrCopy(dest, child, c, s, isDecl)
template process(child, s): untyped = moveOrCopy(dest, child, c, s, flags)
# We know the result will be a stmt so we use that fact to optimize
handleNestedTempl(ri, process, willProduceStmt = true)
of nkRaiseStmt:
result = pRaiseStmt(ri, c, s)
else:
if isAnalysableFieldAccess(ri, c.owner) and isLastRead(ri, c) and
if isAnalysableFieldAccess(ri, c.owner) and isLastRead(ri, c, s) and
canBeMoved(c, dest.typ):
# Rule 3: `=sink`(x, z); wasMoved(z)
let snk = c.genSink(dest, ri, isDecl)
let snk = c.genSink(dest, ri, flags)
result = newTree(nkStmtList, snk, c.genWasMoved(ri))
else:
result = c.genCopy(dest, ri)
result = c.genCopy(dest, ri, flags)
result.add p(ri, c, s, consumed)
c.finishCopy(result, dest, isFromSink = false)
proc computeUninit(c: var Con) =
if not c.uninitComputed:
c.uninitComputed = true
c.uninit = initIntSet()
var init = initIntSet()
discard initialized(c.g, pc = 0, init, c.uninit, int.high)
when false:
proc computeUninit(c: var Con) =
if not c.uninitComputed:
c.uninitComputed = true
c.uninit = initIntSet()
var init = initIntSet()
discard initialized(c.g, pc = 0, init, c.uninit, int.high)
proc injectDefaultCalls(n: PNode, c: var Con) =
case n.kind
of nkVarSection, nkLetSection:
for it in n:
if it.kind == nkIdentDefs and it[^1].kind == nkEmpty:
computeUninit(c)
for j in 0..<it.len-2:
let v = it[j]
doAssert v.kind == nkSym
if c.uninit.contains(v.sym.id):
it[^1] = genDefaultCall(v.sym.typ, c, v.info)
break
of nkNone..nkNilLit, nkTypeSection, nkProcDef, nkConverterDef, nkMethodDef,
nkIteratorDef, nkMacroDef, nkTemplateDef, nkLambda, nkDo, nkFuncDef:
discard
else:
for i in 0..<n.safeLen:
injectDefaultCalls(n[i], c)
proc injectDefaultCalls(n: PNode, c: var Con) =
case n.kind
of nkVarSection, nkLetSection:
for it in n:
if it.kind == nkIdentDefs and it[^1].kind == nkEmpty:
computeUninit(c)
for j in 0..<it.len-2:
let v = skipPragmaExpr(it[j])
doAssert v.kind == nkSym
if c.uninit.contains(v.sym.id):
it[^1] = genDefaultCall(v.sym.typ, c, v.info)
break
of nkNone..nkNilLit, nkTypeSection, nkProcDef, nkConverterDef, nkMethodDef,
nkIteratorDef, nkMacroDef, nkTemplateDef, nkLambda, nkDo, nkFuncDef:
discard
else:
for i in 0..<n.safeLen:
injectDefaultCalls(n[i], c)
proc injectDestructorCalls*(g: ModuleGraph; idgen: IdGenerator; owner: PSym; n: PNode): PNode =
when toDebug.len > 0:
shouldDebug = toDebug == owner.name.s or toDebug == "always"
if sfGeneratedOp in owner.flags or (owner.kind == skIterator and isInlineIterator(owner.typ)):
return n
var c = Con(owner: owner, graph: g, g: constructCfg(owner, n), idgen: idgen)
dbg:
echo "\n### ", owner.name.s, ":\nCFG:"
echoCfg(c.g)
echo n
var c = Con(owner: owner, graph: g, idgen: idgen, body: n, otherUsage: unknownLineInfo)
if optCursorInference in g.config.options:
computeCursors(owner, n, g)
computeLastReadsAndFirstWrites(c.g)
var scope: Scope
var scope = Scope(body: n)
let body = p(n, c, scope, normal)
if owner.kind in {skProc, skFunc, skMethod, skIterator, skConverter}:

View File

@@ -65,11 +65,12 @@ Files: "compiler"
Files: "doc"
Files: "doc/html"
Files: "tools"
Files: "tools/nim-gdb.py"
Files: "tools/debug/nim-gdb.py"
Files: "nimpretty"
Files: "testament"
Files: "nimsuggest"
Files: "nimsuggest/tests/*.nim"
Files: "changelogs/*.md"
[Lib]
Files: "lib"
@@ -120,6 +121,7 @@ Files: "bin/nim"
InstallScript: "yes"
UninstallScript: "yes"
Files: "bin/nim-gdb"
Files: "build_all.sh"
[InnoSetup]
@@ -141,5 +143,5 @@ shortDesc: "The Nim Compiler"
licenses: "bin/nim,MIT;lib/*,MIT;"
[nimble]
pkgName: "compiler"
pkgName: "nim"
pkgFiles: "compiler/*;doc/basicopt.txt;doc/advopt.txt;doc/nimdoc.css"

View File

@@ -5,6 +5,9 @@
from math import trunc
when defined(nimPreviewSlimSystem):
import std/assertions
type
Int128* = object
udata: array[4, uint32]
@@ -30,39 +33,34 @@ template high*(t: typedesc[Int128]): Int128 = Max
proc `$`*(a: Int128): string
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)
{.noSideEffect.}:
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:
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:
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
template isNegative(arg: int32): bool =
arg < 0
proc bitconcat(a, b: uint32): uint64 =
(uint64(a) shl 32) or uint64(b)
proc bitsplit(a: uint64): (uint32, uint32) =
(cast[uint32](a shr 32), cast[uint32](a))
proc toInt64*(arg: Int128): int64 =
if isNegative(arg):
assert(arg.sdata(3) == -1, "out of range")
@@ -208,12 +206,6 @@ proc `==`*(a, b: Int128): bool =
if a.udata[3] != b.udata[3]: return false
return true
proc inplaceBitnot(a: var Int128) =
a.udata[0] = not a.udata[0]
a.udata[1] = not a.udata[1]
a.udata[2] = not a.udata[2]
a.udata[3] = not a.udata[3]
proc bitnot*(a: Int128): Int128 =
result.udata[0] = not a.udata[0]
result.udata[1] = not a.udata[1]
@@ -354,23 +346,10 @@ proc low64(a: Int128): uint64 =
bitconcat(a.udata[1], a.udata[0])
proc `*`*(lhs, rhs: Int128): Int128 =
let
a = cast[uint64](lhs.udata[0])
b = cast[uint64](lhs.udata[1])
c = cast[uint64](lhs.udata[2])
d = cast[uint64](lhs.udata[3])
e = cast[uint64](rhs.udata[0])
f = cast[uint64](rhs.udata[1])
g = cast[uint64](rhs.udata[2])
h = cast[uint64](rhs.udata[3])
let a32 = cast[uint64](lhs.udata[1])
let a00 = cast[uint64](lhs.udata[0])
let b32 = cast[uint64](rhs.udata[1])
let b00 = cast[uint64](rhs.udata[0])
let a32 = uint64(lhs.udata[1])
let a00 = uint64(lhs.udata[0])
let b32 = uint64(rhs.udata[1])
let b00 = uint64(rhs.udata[0])
result = makeInt128(high64(lhs) * low64(rhs) + low64(lhs) * high64(rhs) + a32 * b32, a00 * b00)
result += toInt128(a32 * b00) shl 32
result += toInt128(a00 * b32) shl 32
@@ -441,17 +420,17 @@ proc divMod*(dividend, divisor: Int128): tuple[quotient, remainder: Int128] =
result.remainder = dividend
proc `div`*(a, b: Int128): Int128 =
let (a, b) = divMod(a, b)
let (a, _) = divMod(a, b)
return a
proc `mod`*(a, b: Int128): Int128 =
let (a, b) = divMod(a, b)
let (_, b) = divMod(a, b)
return b
proc addInt128*(result: var string; value: Int128) =
let initialSize = result.len
if value == Zero:
result.add "0"
result.add '0'
elif value == low(Int128):
result.add "-170141183460469231731687303715884105728"
else:
@@ -472,6 +451,8 @@ proc addInt128*(result: var string; value: Int128) =
j -= 1
proc `$`*(a: Int128): string =
# "-170141183460469231731687303715884105728".len == 41
result = newStringOfCap(41)
result.addInt128(a)
proc parseDecimalInt128*(arg: string, pos: int = 0): Int128 =

View File

@@ -13,6 +13,9 @@
import
ast, types, renderer, intsets
when defined(nimPreviewSlimSystem):
import std/assertions
proc canAlias(arg, ret: PType; marker: var IntSet): bool
proc canAliasN(arg: PType; n: PNode; marker: var IntSet): bool =
@@ -71,12 +74,23 @@ proc isValueOnlyType(t: PType): bool =
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
# can alias only with addr(arg.x) and we don't care if it is not safe
result = false
else:
var marker = initIntSet()
result = canAlias(arg, ret, marker)
proc containsVariable(n: PNode): bool =
case n.kind
of nodesToIgnoreSet:
result = false
of nkSym:
result = n.sym.kind in {skForVar, skParam, skVar, skLet, skConst, skResult, skTemp}
else:
for ch in n:
if containsVariable(ch): return true
result = false
proc checkIsolate*(n: PNode): bool =
if types.containsTyRef(n.typ):
# XXX Maybe require that 'n.typ' is acyclic. This is not much
@@ -96,7 +110,11 @@ proc checkIsolate*(n: PNode): bool =
else:
let argType = n[i].typ
if argType != nil and not isCompileTimeOnly(argType) and containsTyRef(argType):
if argType.canAlias(n.typ):
if argType.canAlias(n.typ) or containsVariable(n[i]):
# bug #19013: Alias information is not enough, we need to check for potential
# "overlaps". I claim the problem can only happen by reading again from a location
# that materialized which is only possible if a variable that contains a `ref`
# is involved.
return false
result = true
of nkIfStmt, nkIfExpr:

File diff suppressed because it is too large Load Diff

View File

@@ -19,13 +19,13 @@ proc genObjectFields(p: PProc, typ: PType, n: PNode): Rope =
s, u: Rope
field: PSym
b: PNode
result = nil
result = ""
case n.kind
of nkRecList:
if n.len == 1:
result = genObjectFields(p, typ, n[0])
else:
s = nil
s = ""
for i in 0..<n.len:
if i > 0: s.add(", \L")
s.add(genObjectFields(p, typ, n[i]))
@@ -44,13 +44,13 @@ proc genObjectFields(p: PProc, typ: PType, n: PNode): Rope =
s = genTypeInfo(p, field.typ)
for i in 1..<n.len:
b = n[i] # branch
u = nil
u = ""
case b.kind
of nkOfBranch:
if b.len < 2:
internalError(p.config, b.info, "genObjectFields; nkOfBranch broken")
for j in 0..<b.len - 1:
if u != nil: u.add(", ")
if u != "": u.add(", ")
if b[j].kind == nkRange:
u.addf("[$1, $2]", [rope(getOrdValue(b[j][0])),
rope(getOrdValue(b[j][1]))])
@@ -59,7 +59,7 @@ proc genObjectFields(p: PProc, typ: PType, n: PNode): Rope =
of nkElse:
u = rope(lengthOrd(p.config, field.typ))
else: internalError(p.config, n.info, "genObjectFields(nkRecCase)")
if result != nil: result.add(", \L")
if result != "": result.add(", \L")
result.addf("[setConstr($1), $2]",
[u, genObjectFields(p, typ, lastSon(b))])
result = ("{kind: 3, offset: \"$1\", len: $3, " &
@@ -84,7 +84,7 @@ proc genObjectInfo(p: PProc, typ: PType, name: Rope) =
[name, genTypeInfo(p, typ[0].skipTypes(skipPtrs))])
proc genTupleFields(p: PProc, typ: PType): Rope =
var s: Rope = nil
var s: Rope = ""
for i in 0..<typ.len:
if i > 0: s.add(", \L")
s.addf("{kind: 1, offset: \"Field$1\", len: 0, " &
@@ -102,7 +102,7 @@ proc genTupleInfo(p: PProc, typ: PType, name: Rope) =
p.g.typeInfo.addf("$1.node = NNI$2;$n", [name, rope(typ.id)])
proc genEnumInfo(p: PProc, typ: PType, name: Rope) =
var s: Rope = nil
var s: Rope = ""
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
@@ -133,7 +133,7 @@ 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)
of tyVar, tyLent, tyRef, tyPtr, tySequence, tyRange, tySet:
of tyVar, tyLent, tyRef, tyPtr, tySequence, tyRange, tySet, tyOpenArray:
var s =
"var $1 = {size: 0, kind: $2, base: null, node: null, finalizer: null};$n" %
[result, rope(ord(t.kind))]

View File

@@ -14,6 +14,9 @@ import
idents, renderer, types, magicsys, lowerings, tables, modulegraphs, lineinfos,
transf, liftdestructors, typeallowed
when defined(nimPreviewSlimSystem):
import std/assertions
discard """
The basic approach is that captured vars need to be put on the heap and
that the calling chain needs to be explicitly modelled. Things to consider:
@@ -242,6 +245,13 @@ proc createTypeBoundOpsLL(g: ModuleGraph; refType: PType; info: TLineInfo; idgen
if tfHasAsgn in refType.flags or optSeqDestructors in g.config.globalOptions:
owner.flags.incl sfInjectDestructors
proc genCreateEnv(env: PNode): PNode =
var c = newNodeIT(nkObjConstr, env.info, env.typ)
c.add newNodeIT(nkType, env.info, env.typ)
let e = copyTree(env)
e.flags.incl nfFirstWrite
result = newAsgnStmt(e, c)
proc liftIterSym*(g: ModuleGraph; n: PNode; idgen: IdGenerator; owner: PSym): PNode =
# transforms (iter) to (let env = newClosure[iter](); (iter, env))
if liftingHarmful(g.config, owner): return n
@@ -265,23 +275,19 @@ proc liftIterSym*(g: ModuleGraph; n: PNode; idgen: IdGenerator; owner: PSym): PN
addVar(v, env)
result.add(v)
# add 'new' statement:
result.add newCall(getSysSym(g, n.info, "internalNew"), env)
#result.add newCall(getSysSym(g, n.info, "internalNew"), env)
result.add genCreateEnv(env)
createTypeBoundOpsLL(g, env.typ, n.info, idgen, owner)
result.add makeClosure(g, idgen, iter, env, n.info)
proc freshVarForClosureIter*(g: ModuleGraph; s: PSym; idgen: IdGenerator; owner: PSym): PNode =
let envParam = getHiddenParam(g, owner)
let obj = envParam.typ.skipTypes({tyOwned, tyRef, tyPtr})
addField(obj, s, g.cache, idgen)
let field = addField(obj, s, g.cache, idgen)
var access = newSymNode(envParam)
assert obj.kind == tyObject
let field = getFieldFromObj(obj, s)
if field != nil:
result = rawIndirectAccess(access, field, s.info)
else:
localError(g.config, s.info, "internal error: cannot generate fresh variable")
result = access
result = rawIndirectAccess(access, field, s.info)
# ------------------ new stuff -------------------------------------------
@@ -290,7 +296,8 @@ 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; using '-d:nimNoLentIterators' helps in some cases") %
" safety, declared here: $3; using '-d:nimNoLentIterators' helps in some cases." &
" Consider using a <ref $2> which can be captured.") %
[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>" %
@@ -434,7 +441,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, c.idgen, s, cache = true)
let body = transformBody(c.graph, c.idgen, s, useCache)
detectCapturedVars(body, s, c)
let ow = s.skipGenericOwner
if ow == owner:
@@ -449,9 +456,9 @@ proc detectCapturedVars(n: PNode; owner: PSym; c: var DetectionPass) =
if s.name.id == getIdent(c.graph.cache, ":state").id:
obj.n[0].sym.itemId = ItemId(module: s.itemId.module, item: -s.itemId.item)
else:
addField(obj, s, c.graph.cache, c.idgen)
discard addField(obj, s, c.graph.cache, c.idgen)
# direct or indirect dependency:
elif (innerProc and s.typ.callConv == ccClosure) or interestingVar(s):
elif (innerProc and not s.isIterator and s.typ.callConv == ccClosure) or interestingVar(s):
discard """
proc outer() =
var x: int
@@ -471,7 +478,7 @@ proc detectCapturedVars(n: PNode; owner: PSym; c: var DetectionPass) =
if interestingVar(s) and not c.capturedVars.containsOrIncl(s.id):
let obj = c.getEnvTypeForOwner(ow, n.info).skipTypes({tyOwned, tyRef, tyPtr})
#getHiddenParam(owner).typ.skipTypes({tyOwned, tyRef, tyPtr})
addField(obj, s, c.graph.cache, c.idgen)
discard addField(obj, s, c.graph.cache, c.idgen)
# create required upFields:
var w = owner.skipGenericOwner
if isInnerProc(w) or owner.isIterator:
@@ -597,7 +604,7 @@ proc rawClosureCreation(owner: PSym;
addVar(v, unowned)
# add 'new' statement:
result.add(newCall(getSysSym(d.graph, env.info, "internalNew"), env))
result.add genCreateEnv(env)
if optOwnedRefs in d.graph.config.globalOptions:
let unowned = c.unownedEnvVars[owner.id]
assert unowned != nil
@@ -659,7 +666,7 @@ proc closureCreationForIter(iter: PNode;
var vs = newNodeI(nkVarSection, iter.info)
addVar(vs, vnode)
result.add(vs)
result.add(newCall(getSysSym(d.graph, iter.info, "internalNew"), vnode))
result.add genCreateEnv(vnode)
createTypeBoundOpsLL(d.graph, vnode.typ, iter.info, d.idgen, owner)
let upField = lookupInRecord(v.typ.skipTypes({tyOwned, tyRef, tyPtr}).n, getIdent(d.graph.cache, upName))
@@ -730,7 +737,7 @@ proc liftCapturedVars(n: PNode; owner: PSym; d: var DetectionPass;
# echo renderTree(s.getBody, {renderIds})
let oldInContainer = c.inContainer
c.inContainer = 0
var body = transformBody(d.graph, d.idgen, s, cache = false)
var body = transformBody(d.graph, d.idgen, s, dontUseCache)
body = liftCapturedVars(body, s, d, c)
if c.envVars.getOrDefault(s.id).isNil:
s.transformedBody = body
@@ -775,7 +782,7 @@ proc liftCapturedVars(n: PNode; owner: PSym; d: var DetectionPass;
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}:
if n[0].kind in {nkAsgn, nkFastAsgn, nkSinkAsgn}:
# 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
@@ -852,7 +859,7 @@ proc liftIterToProc*(g: ModuleGraph; fn: PSym; body: PNode; ptrType: PType;
fn.typ.callConv = oldCC
proc liftLambdas*(g: ModuleGraph; fn: PSym, body: PNode; tooEarly: var bool;
idgen: IdGenerator): PNode =
idgen: IdGenerator, force: bool): PNode =
# XXX backend == backendJs does not suffice! The compiletime stuff needs
# the transformation even when compiling to JS ...
@@ -861,7 +868,7 @@ proc liftLambdas*(g: ModuleGraph; fn: PSym, body: PNode; tooEarly: var bool;
if body.kind == nkEmpty or (
g.config.backend == backendJs and not isCompileTime) or
fn.skipGenericOwner.kind != skModule:
(fn.skipGenericOwner.kind != skModule and not force):
# ignore forward declaration:
result = body
@@ -944,7 +951,7 @@ proc liftForLoop*(g: ModuleGraph; body: PNode; idgen: IdGenerator; owner: PSym):
addVar(v, newSymNode(env))
result.add(v)
# add 'new' statement:
result.add(newCall(getSysSym(g, env.info, "internalNew"), env.newSymNode))
result.add genCreateEnv(env.newSymNode)
createTypeBoundOpsLL(g, env.typ, body.info, idgen, owner)
elif op.kind == nkStmtListExpr:

View File

@@ -510,7 +510,7 @@ proc emitTok*(em: var Emitter; L: Lexer; tok: Token) =
rememberSplit(splitComma)
wrSpace em
of openPars:
if tok.strongSpaceA > 0 and not em.endsInWhite and
if tok.strongSpaceA and not em.endsInWhite and
(not em.wasExportMarker or tok.tokType == tkCurlyDotLe):
wrSpace em
wr(em, $tok.tokType, ltSomeParLe)
@@ -528,7 +528,7 @@ proc emitTok*(em: var Emitter; L: Lexer; tok: Token) =
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
if em.inquote or (((not tok.strongSpaceA) and tok.strongSpaceB == tsNone) and
tok.ident.s notin ["<", ">", "<=", ">=", "==", "!="]):
# bug #9504: remember to not spacify a keyword:
lastTokWasTerse = true
@@ -538,7 +538,7 @@ proc emitTok*(em: var Emitter; L: Lexer; tok: Token) =
if not em.endsInWhite: wrSpace(em)
wr(em, tok.ident.s, ltOpr)
template isUnary(tok): bool =
tok.strongSpaceB == 0 and tok.strongSpaceA > 0
tok.strongSpaceB == tsNone and tok.strongSpaceA
if not isUnary(tok):
rememberSplit(splitBinary)
@@ -551,11 +551,15 @@ proc emitTok*(em: var Emitter; L: Lexer; tok: Token) =
if not preventComment:
emitComment(em, tok, dontIndent = false)
of tkIntLit..tkStrLit, tkRStrLit, tkTripleStrLit, tkGStrLit, tkGTripleStrLit, tkCharLit:
let lit = fileSection(em.config, em.fid, tok.offsetA, tok.offsetB)
if endsInAlpha(em) and tok.tokType notin {tkGStrLit, tkGTripleStrLit}: wrSpace(em)
em.lineSpan = countNewlines(lit)
if em.lineSpan > 0: calcCol(em, lit)
wr em, lit, ltLit
if not em.inquote:
let lit = fileSection(em.config, em.fid, tok.offsetA, tok.offsetB)
if endsInAlpha(em) and tok.tokType notin {tkGStrLit, tkGTripleStrLit}: wrSpace(em)
em.lineSpan = countNewlines(lit)
if em.lineSpan > 0: calcCol(em, lit)
wr em, lit, ltLit
else:
if endsInAlpha(em): wrSpace(em)
wr em, tok.literal, ltLit
of tkEof: discard
else:
let lit = if tok.ident != nil: tok.ident.s else: tok.literal

View File

@@ -19,6 +19,9 @@ import
hashes, options, msgs, strutils, platform, idents, nimlexbase, llstream,
wordrecg, lineinfos, pathutils, parseutils
when defined(nimPreviewSlimSystem):
import std/[assertions, formatfloat]
const
MaxLineLength* = 80 # lines longer than this lead to a warning
numChars*: set[char] = {'0'..'9', 'a'..'z', 'A'..'Z'}
@@ -90,19 +93,22 @@ type
# so that it is the correct default value
base2, base8, base16
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*: 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
literal*: string # the parsed (string) literal; and
# documentation comments are here too
TokenSpacing* = enum
tsNone, tsTrailing, tsEof
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*: NumericalBase # the numerical base; only valid for int
# or float literals
strongSpaceA*: bool # leading spaces of an operator
strongSpaceB*: TokenSpacing # trailing spaces of an operator
literal*: string # the parsed (string) literal; and
# documentation comments are here too
line*, col*: int
when defined(nimpretty):
offsetA*, offsetB*: int # used for pretty printing so that literals
@@ -121,6 +127,8 @@ type
cache*: IdentCache
when defined(nimsuggest):
previousToken: TLineInfo
tokenEnd*: TLineInfo
previousTokenEnd*: TLineInfo
config*: ConfigRef
proc getLineInfo*(L: Lexer, tok: Token): TLineInfo {.inline.} =
@@ -170,7 +178,7 @@ proc initToken*(L: var Token) =
L.tokType = tkInvalid
L.iNumber = 0
L.indent = 0
L.strongSpaceA = 0
L.strongSpaceA = false
L.literal = ""
L.fNumber = 0.0
L.base = base10
@@ -183,7 +191,7 @@ proc fillToken(L: var Token) =
L.tokType = tkInvalid
L.iNumber = 0
L.indent = 0
L.strongSpaceA = 0
L.strongSpaceA = false
setLen(L.literal, 0)
L.fNumber = 0.0
L.base = base10
@@ -502,11 +510,11 @@ proc getNumber(L: var Lexer, result: var Token) =
of tkUInt16Lit: setNumber result.iNumber, xi and 0xffff
of tkUInt32Lit: setNumber result.iNumber, xi and 0xffffffff
of tkFloat32Lit:
setNumber result.fNumber, (cast[PFloat32](addr(xi)))[]
setNumber result.fNumber, (cast[ptr float32](addr(xi)))[]
# note: this code is endian neutral!
# XXX: Test this on big endian machine!
of tkFloat64Lit, tkFloatLit:
setNumber result.fNumber, (cast[PFloat64](addr(xi)))[]
setNumber result.fNumber, (cast[ptr float64](addr(xi)))[]
else: internalError(L.config, getLineInfo(L), "getNumber")
# Bounds checks. Non decimal literals are allowed to overflow the range of
@@ -904,7 +912,7 @@ proc getSymbol(L: var Lexer, tok: var Token) =
inc(pos)
suspicious = true
of '\x80'..'\xFF':
if c in UnicodeOperatorStartChars and unicodeOperators in L.config.features and unicodeOprLen(L.buf, pos)[0] != 0:
if c in UnicodeOperatorStartChars and unicodeOprLen(L.buf, pos)[0] != 0:
break
else:
h = h !& ord(c)
@@ -912,7 +920,7 @@ proc getSymbol(L: var Lexer, tok: var Token) =
else: break
tokenEnd(tok, pos-1)
h = !$h
tok.ident = L.cache.getIdent(addr(L.buf[L.bufpos]), pos - L.bufpos, h)
tok.ident = L.cache.getIdent(cast[cstring](addr(L.buf[L.bufpos])), pos - L.bufpos, h)
if (tok.ident.id < ord(tokKeywordLow) - ord(tkSymbol)) or
(tok.ident.id > ord(tokKeywordHigh) - ord(tkSymbol)):
tok.tokType = tkSymbol
@@ -926,7 +934,7 @@ proc getSymbol(L: var Lexer, tok: var Token) =
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)
tok.ident = L.cache.getIdent(cast[cstring](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 = TokType(tok.ident.id - oprLow + ord(tkColon))
L.bufpos = pos
@@ -940,7 +948,7 @@ proc getOperator(L: var Lexer, tok: var Token) =
if c in OpChars:
h = h !& ord(c)
inc(pos)
elif c in UnicodeOperatorStartChars and unicodeOperators in L.config.features:
elif c in UnicodeOperatorStartChars:
let oprLen = unicodeOprLen(L.buf, pos)[0]
if oprLen == 0: break
for i in 0..<oprLen:
@@ -952,12 +960,13 @@ proc getOperator(L: var Lexer, tok: var Token) =
tokenEnd(tok, pos-1)
# advance pos but don't store it in L.bufpos so the next token (which might
# be an operator too) gets the preceding spaces:
tok.strongSpaceB = 0
tok.strongSpaceB = tsNone
while L.buf[pos] == ' ':
inc pos
inc tok.strongSpaceB
if tok.strongSpaceB != tsTrailing:
tok.strongSpaceB = tsTrailing
if L.buf[pos] in {CR, LF, nimlexbase.EndOfFile}:
tok.strongSpaceB = -1
tok.strongSpaceB = tsEof
proc getPrecedence*(tok: Token): int =
## Calculates the precedence of the given token.
@@ -970,7 +979,7 @@ proc getPrecedence*(tok: Token): int =
# arrow like?
if tok.ident.s.len > 1 and tok.ident.s[^1] == '>' and
tok.ident.s[^2] in {'-', '~', '='}: return 1
tok.ident.s[^2] in {'-', '~', '='}: return 0
template considerAsgn(value: untyped) =
result = if tok.ident.s[^1] == '=': 1 else: value
@@ -1144,7 +1153,7 @@ proc scanComment(L: var Lexer, tok: var Token) =
proc skip(L: var Lexer, tok: var Token) =
var pos = L.bufpos
tokenBegin(tok, pos)
tok.strongSpaceA = 0
tok.strongSpaceA = false
when defined(nimpretty):
var hasComment = false
var commentIndent = L.currLineIndent
@@ -1155,7 +1164,8 @@ proc skip(L: var Lexer, tok: var Token) =
case L.buf[pos]
of ' ':
inc(pos)
inc(tok.strongSpaceA)
if not tok.strongSpaceA:
tok.strongSpaceA = true
of '\t':
if not L.allowTabs: lexMessagePos(L, errGenerated, pos, "tabs are not allowed, use spaces instead")
inc(pos)
@@ -1177,7 +1187,7 @@ proc skip(L: var Lexer, tok: var Token) =
pos = L.bufpos
else:
break
tok.strongSpaceA = 0
tok.strongSpaceA = false
when defined(nimpretty):
if L.buf[pos] == '#' and tok.line < 0: commentIndent = indent
if L.buf[pos] > ' ' and (L.buf[pos] != '#' or L.buf[pos+1] == '#'):
@@ -1216,6 +1226,10 @@ proc skip(L: var Lexer, tok: var Token) =
proc rawGetTok*(L: var Lexer, tok: var Token) =
template atTokenEnd() {.dirty.} =
when defined(nimsuggest):
L.previousTokenEnd.line = L.tokenEnd.line
L.previousTokenEnd.col = L.tokenEnd.col
L.tokenEnd.line = tok.line.uint16
L.tokenEnd.col = getColNumber(L, L.bufpos).int16
# we attach the cursor to the last *strong* token
if tok.tokType notin weakTokens:
L.previousToken.line = tok.line.uint16
@@ -1241,7 +1255,7 @@ proc rawGetTok*(L: var Lexer, tok: var Token) =
else:
case c
of UnicodeOperatorStartChars:
if unicodeOperators in L.config.features and unicodeOprLen(L.buf, L.bufpos)[0] != 0:
if unicodeOprLen(L.buf, L.bufpos)[0] != 0:
getOperator(L, tok)
else:
getSymbol(L, tok)
@@ -1352,7 +1366,7 @@ proc rawGetTok*(L: var Lexer, tok: var Token) =
getNumber(L, tok)
let c = L.buf[L.bufpos]
if c in SymChars+{'_'}:
if c in UnicodeOperatorStartChars and unicodeOperators in L.config.features and
if c in UnicodeOperatorStartChars and
unicodeOprLen(L.buf, L.bufpos)[0] != 0:
discard
else:
@@ -1367,7 +1381,7 @@ proc rawGetTok*(L: var Lexer, tok: var Token) =
getNumber(L, tok)
let c = L.buf[L.bufpos]
if c in SymChars+{'_'}:
if c in UnicodeOperatorStartChars and unicodeOperators in L.config.features and
if c in UnicodeOperatorStartChars and
unicodeOprLen(L.buf, L.bufpos)[0] != 0:
discard
else:

View File

@@ -8,13 +8,16 @@
#
## This module implements lifting for type-bound operations
## (``=sink``, ``=``, ``=destroy``, ``=deepCopy``).
## (``=sink``, ``=copy``, ``=destroy``, ``=deepCopy``).
import modulegraphs, lineinfos, idents, ast, renderer, semdata,
sighashes, lowerings, options, types, msgs, magicsys, tables, ccgutils
from trees import isCaseObj
when defined(nimPreviewSlimSystem):
import std/assertions
type
TLiftCtx = object
g: ModuleGraph
@@ -85,6 +88,8 @@ proc defaultOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
let call = genBuiltin(c, mDefault, "default", x)
call.typ = t
body.add newAsgnStmt(x, call)
elif c.kind == attachedWasMoved:
body.add genBuiltin(c, mWasMoved, "wasMoved", x)
proc genAddr(c: var TLiftCtx; x: PNode): PNode =
if x.kind == nkHiddenDeref:
@@ -142,6 +147,11 @@ proc destructorCall(c: var TLiftCtx; op: PSym; x: PNode): PNode =
else:
result = destroy
proc genWasMovedCall(c: var TLiftCtx; op: PSym; x: PNode): PNode =
result = newNodeIT(nkCall, x.info, op.typ[0])
result.add(newSymNode(op))
result.add genAddr(c, x)
proc fillBodyObj(c: var TLiftCtx; n, body, x, y: PNode; enforceDefaultOp: bool) =
case n.kind
of nkSym:
@@ -162,9 +172,12 @@ proc fillBodyObj(c: var TLiftCtx; n, body, x, y: PNode; enforceDefaultOp: bool)
# the value needs to be destroyed before we assign the selector
# or the value is lost
let prevKind = c.kind
let prevAddMemReset = c.addMemReset
c.kind = attachedDestructor
c.addMemReset = true
fillBodyObj(c, n, body, x, y, enforceDefaultOp = false)
c.kind = prevKind
c.addMemReset = prevAddMemReset
localEnforceDefaultOp = true
if c.kind != attachedDestructor:
@@ -436,6 +449,20 @@ proc considerUserDefinedOp(c: var TLiftCtx; t: PType; body, x, y: PNode): bool =
body.add newDeepCopyCall(c, op, x, y)
result = true
of attachedWasMoved:
var op = getAttachedOp(c.g, t, attachedWasMoved)
if op != nil and sfOverriden in op.flags:
if op.ast.isGenericRoutine:
# patch generic destructor:
op = instantiateGeneric(c, op, t, t.typeInst)
setAttachedOp(c.g, c.idgen.module, t, attachedWasMoved, op)
#markUsed(c.g.config, c.info, op, c.g.usageSym)
onUse(c.info, op)
body.add genWasMovedCall(c, op, x)
result = true
proc declareCounter(c: var TLiftCtx; body: PNode; first: BiggestInt): PNode =
var temp = newSym(skTemp, getIdent(c.g.cache, lowerings.genPrefix), nextSymId(c.idgen), c.fn, c.info)
temp.typ = getSysType(c.g, body.info, tyInt)
@@ -518,6 +545,7 @@ proc fillSeqOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
if canFormAcycle(t.elemType):
# follow all elements:
forallElements(c, t, body, x, y)
of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "wasMoved", x)
proc useSeqOrStrOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
createTypeBoundOps(c.g, c.c, t, body.info, c.idgen)
@@ -525,7 +553,7 @@ proc useSeqOrStrOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
# operation here:
var t = t
if t.assignment == nil or t.destructor == nil:
let h = sighashes.hashType(t, {CoType, CoConsiderOwned, CoDistinct})
let h = sighashes.hashType(t,c.g.config, {CoType, CoConsiderOwned, CoDistinct})
let canon = c.g.canonTypes.getOrDefault(h)
if canon != nil: t = canon
@@ -555,6 +583,7 @@ proc useSeqOrStrOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
if op == nil:
return # protect from recursion
body.add newHookCall(c, op, x, y)
of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "wasMoved", x)
proc fillStrOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
case c.kind
@@ -570,6 +599,7 @@ proc fillStrOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
body.add genBuiltin(c, mDestroy, "destroy", x)
of attachedTrace:
discard "strings are atomic and have no inner elements that are to trace"
of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "wasMoved", x)
proc cyclicType*(t: PType): bool =
case t.kind
@@ -603,6 +633,11 @@ proc atomicRefOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
createTypeBoundOps(c.g, c.c, elemType, c.info, c.idgen)
let isCyclic = c.g.config.selectedGC == gcOrc and types.canFormAcycle(elemType)
let isInheritableAcyclicRef = c.g.config.selectedGC == gcOrc and
(not isPureObject(elemType)) and
tfAcyclic in skipTypes(elemType, abstractInst+{tyOwned}-{tyTypeDesc}).flags
# dynamic Acyclic refs need to use dyn decRef
let tmp =
if isCyclic and c.kind in {attachedAsgn, attachedSink}:
declareTempOf(c, body, x)
@@ -626,6 +661,8 @@ proc atomicRefOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
cond = callCodegenProc(c.g, "nimDecRefIsLastCyclicStatic", c.info, tmp, typInfo)
else:
cond = callCodegenProc(c.g, "nimDecRefIsLastCyclicDyn", c.info, tmp)
elif isInheritableAcyclicRef:
cond = callCodegenProc(c.g, "nimDecRefIsLastDyn", c.info, x)
else:
cond = callCodegenProc(c.g, "nimDecRefIsLast", c.info, x)
cond.typ = getSysType(c.g, x.info, tyBool)
@@ -661,6 +698,8 @@ proc atomicRefOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
# If the ref is polymorphic we have to account for this
body.add callCodegenProc(c.g, "nimTraceRefDyn", c.info, genAddrOf(x, c.idgen), y)
#echo "can follow ", elemType, " static ", isFinal(elemType)
of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "wasMoved", x)
proc atomicClosureOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
## Closures are really like refs except they always use a virtual destructor
@@ -709,6 +748,7 @@ proc atomicClosureOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
of attachedDeepCopy: assert(false, "cannot happen")
of attachedTrace:
body.add callCodegenProc(c.g, "nimTraceRefDyn", c.info, genAddrOf(xenv, c.idgen), y)
of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "wasMoved", x)
proc weakrefOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
case c.kind
@@ -733,6 +773,7 @@ proc weakrefOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
body.sons.insert(des, 0)
of attachedDeepCopy: assert(false, "cannot happen")
of attachedTrace: discard
of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "wasMoved", x)
proc ownedRefOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
var actions = newNodeI(nkStmtList, c.info)
@@ -758,6 +799,7 @@ proc ownedRefOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
body.add genIf(c, x, actions)
of attachedDeepCopy: assert(false, "cannot happen")
of attachedTrace: discard
of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "wasMoved", x)
proc closureOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
if c.kind == attachedDeepCopy:
@@ -792,6 +834,7 @@ proc closureOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
body.sons.insert(des, 0)
of attachedDeepCopy: assert(false, "cannot happen")
of attachedTrace: discard
of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "wasMoved", x)
proc ownedClosureOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
let xx = genBuiltin(c, mAccessEnv, "accessEnv", x)
@@ -807,6 +850,7 @@ proc ownedClosureOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
body.add genIf(c, xx, actions)
of attachedDeepCopy: assert(false, "cannot happen")
of attachedTrace: discard
of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "wasMoved", x)
proc fillBody(c: var TLiftCtx; t: PType; body, x, y: PNode) =
case t.kind
@@ -922,7 +966,7 @@ proc symPrototype(g: ModuleGraph; typ: PType; owner: PSym; kind: TTypeAttachedOp
result.typ = newProcType(info, nextTypeId(idgen), owner)
result.typ.addParam dest
if kind != attachedDestructor:
if kind notin {attachedDestructor, attachedWasMoved}:
result.typ.addParam src
if kind == attachedAsgn and g.config.selectedGC == gcOrc and
@@ -941,6 +985,12 @@ proc symPrototype(g: ModuleGraph; typ: PType; owner: PSym; kind: TTypeAttachedOp
incl result.flags, sfFromGeneric
incl result.flags, sfGeneratedOp
proc genTypeFieldCopy(c: var TLiftCtx; t: PType; body, x, y: PNode) =
let xx = genBuiltin(c, mAccessTypeField, "accessTypeField", x)
let yy = genBuiltin(c, mAccessTypeField, "accessTypeField", y)
xx.typ = getSysType(c.g, c.info, tyPointer)
yy.typ = xx.typ
body.add newAsgnStmt(xx, yy)
proc produceSym(g: ModuleGraph; c: PContext; typ: PType; kind: TTypeAttachedOp;
info: TLineInfo; idgen: IdGenerator): PSym =
@@ -956,7 +1006,7 @@ proc produceSym(g: ModuleGraph; c: PContext; typ: PType; kind: TTypeAttachedOp;
let dest = result.typ.n[1].sym
let d = newDeref(newSymNode(dest))
let src = if kind == attachedDestructor: newNodeIT(nkSym, info, getSysType(g, info, tyPointer))
let src = if kind in {attachedDestructor, attachedWasMoved}: newNodeIT(nkSym, info, getSysType(g, info, tyPointer))
else: newSymNode(result.typ.n[2].sym)
# register this operation already:
@@ -980,6 +1030,10 @@ proc produceSym(g: ModuleGraph; c: PContext; typ: PType; kind: TTypeAttachedOp;
fillStrOp(a, typ, result.ast[bodyPos], d, src)
else:
fillBody(a, typ, result.ast[bodyPos], d, src)
if tk == tyObject and a.kind in {attachedAsgn, attachedSink, attachedDeepCopy} and not lacksMTypeField(typ):
# bug #19205: Do not forget to also copy the hidden type field:
genTypeFieldCopy(a, typ, result.ast[bodyPos], d, src)
if not a.canRaise: incl result.flags, sfNeverRaises
completePartialOp(g, idgen.module, typ, kind, result)
@@ -1031,13 +1085,7 @@ proc inst(g: ModuleGraph; c: PContext; t: PType; kind: TTypeAttachedOp; idgen: I
let op = getAttachedOp(g, t, kind)
if op != nil and op.ast != nil and op.ast.isGenericRoutine:
if t.typeInst != nil:
var a: TLiftCtx
a.info = info
a.g = g
a.kind = kind
a.c = c
a.idgen = idgen
var a = TLiftCtx(info: info, g: g, kind: kind, c: c, idgen: idgen)
let opInst = instantiateGeneric(a, op, t, t.typeInst)
if opInst.ast != nil:
patchBody(g, c, opInst.ast, info, a.idgen)
@@ -1059,7 +1107,7 @@ proc createTypeBoundOps(g: ModuleGraph; c: PContext; orig: PType; info: TLineInf
let skipped = orig.skipTypes({tyGenericInst, tyAlias, tySink})
if isEmptyContainer(skipped) or skipped.kind == tyStatic: return
let h = sighashes.hashType(skipped, {CoType, CoConsiderOwned, CoDistinct})
let h = sighashes.hashType(skipped, g.config, {CoType, CoConsiderOwned, CoDistinct})
var canon = g.canonTypes.getOrDefault(h)
if canon == nil:
g.canonTypes[h] = skipped
@@ -1080,15 +1128,15 @@ proc createTypeBoundOps(g: ModuleGraph; c: PContext; orig: PType; info: TLineInf
# bug #15122: We need to produce all prototypes before entering the
# mind boggling recursion. Hacks like these imply we should rewrite
# this module.
var generics: array[attachedDestructor..attachedTrace, bool]
for k in attachedDestructor..lastAttached:
var generics: array[attachedWasMoved..attachedTrace, bool]
for k in attachedWasMoved..lastAttached:
generics[k] = getAttachedOp(g, canon, k) != nil
if not generics[k]:
setAttachedOp(g, idgen.module, canon, k,
symPrototype(g, canon, canon.owner, k, info, idgen))
# we generate the destructor first so that other operators can depend on it:
for k in attachedDestructor..lastAttached:
for k in attachedWasMoved..lastAttached:
if not generics[k]:
discard produceSym(g, c, canon, k, info, idgen)
else:

View File

@@ -32,13 +32,16 @@ type
# non-fatal errors
errIllFormedAstX, errCannotOpenFile,
errXExpected,
errRstMissingClosing,
errRstGridTableNotImplemented,
errRstMarkdownIllformedTable,
errRstIllformedTable,
errRstNewSectionExpected,
errRstGeneralParseError,
errRstInvalidDirectiveX,
errRstInvalidField,
errRstFootnoteMismatch,
errRstSandboxedDirective,
errProveInit, # deadcode
errGenerated,
errUser,
@@ -50,9 +53,11 @@ type
warnSmallLshouldNotBeUsed = "SmallLshouldNotBeUsed", warnUnknownMagic = "UnknownMagic",
warnRstRedefinitionOfLabel = "RedefinitionOfLabel",
warnRstUnknownSubstitutionX = "UnknownSubstitutionX",
warnRstAmbiguousLink = "AmbiguousLink",
warnRstBrokenLink = "BrokenLink",
warnRstLanguageXNotSupported = "LanguageXNotSupported",
warnRstFieldXNotSupported = "FieldXNotSupported",
warnRstUnusedImportdoc = "UnusedImportdoc",
warnRstStyle = "warnRstStyle",
warnCommentXIgnored = "CommentXIgnored",
warnTypelessParam = "TypelessParam",
@@ -64,7 +69,8 @@ type
warnUnreachableElse = "UnreachableElse", warnUnreachableCode = "UnreachableCode",
warnStaticIndexCheck = "IndexCheck", warnGcUnsafe = "GcUnsafe", warnGcUnsafe2 = "GcUnsafe2",
warnUninit = "Uninit", warnGcMem = "GcMem", warnDestructor = "Destructor",
warnLockLevel = "LockLevel", warnResultShadowed = "ResultShadowed",
warnLockLevel = "LockLevel", # deadcode
warnResultShadowed = "ResultShadowed",
warnInconsistentSpacing = "Spacing", warnCaseTransition = "CaseTransition",
warnCycleCreated = "CycleCreated", warnObservableStores = "ObservableStores",
warnStrictNotNil = "StrictNotNil",
@@ -75,7 +81,13 @@ type
warnAnyEnumConv = "AnyEnumConv",
warnHoleEnumConv = "HoleEnumConv",
warnCstringConv = "CStringConv",
warnPtrToCstringConv = "PtrToCstringConv",
warnEffect = "Effect",
warnCastSizes = "CastSizes"
warnImplicitTemplateRedefinition = "ImplicitTemplateRedefinition",
warnUnnamedBreak = "UnnamedBreak",
warnStmtListLambda = "StmtListLambda",
warnBareExcept = "BareExcept",
warnUser = "User",
# hints
hintSuccess = "Success", hintSuccessX = "SuccessX",
@@ -90,6 +102,7 @@ type
hintPattern = "Pattern", hintExecuting = "Exec", hintLinking = "Link", hintDependency = "Dependency",
hintSource = "Source", hintPerformance = "Performance", hintStackTrace = "StackTrace",
hintGCStats = "GCStats", hintGlobalVar = "GlobalVar", hintExpandMacro = "ExpandMacro",
hintAmbiguousEnum = "AmbiguousEnum",
hintUser = "User", hintUserRaw = "UserRaw", hintExtendedContext = "ExtendedContext",
hintMsgOrigin = "MsgOrigin", # since 1.3.5
hintDeclaredLoc = "DeclaredLoc", # since 1.5.1
@@ -102,13 +115,16 @@ const
errIllFormedAstX: "illformed AST: $1",
errCannotOpenFile: "cannot open '$1'",
errXExpected: "'$1' expected",
errRstMissingClosing: "$1",
errRstGridTableNotImplemented: "grid table is not implemented",
errRstMarkdownIllformedTable: "illformed delimiter row of a markdown table",
errRstIllformedTable: "Illformed table: $1",
errRstNewSectionExpected: "new section expected $1",
errRstGeneralParseError: "general parse error",
errRstInvalidDirectiveX: "invalid directive: '$1'",
errRstInvalidField: "invalid field: $1",
errRstFootnoteMismatch: "number of footnotes and their references don't match: $1",
errRstSandboxedDirective: "disabled directive: '$1'",
errProveInit: "Cannot prove that '$1' is initialized.", # deadcode
errGenerated: "$1",
errUser: "$1",
@@ -123,9 +139,11 @@ const
warnUnknownMagic: "unknown magic '$1' might crash the compiler",
warnRstRedefinitionOfLabel: "redefinition of label '$1'",
warnRstUnknownSubstitutionX: "unknown substitution '$1'",
warnRstAmbiguousLink: "ambiguous doc link $1",
warnRstBrokenLink: "broken link '$1'",
warnRstLanguageXNotSupported: "language '$1' not supported",
warnRstFieldXNotSupported: "field '$1' not supported",
warnRstUnusedImportdoc: "importdoc for '$1' is not used",
warnRstStyle: "RST style: $1",
warnCommentXIgnored: "comment '$1' ignored",
warnTypelessParam: "", # deadcode
@@ -150,7 +168,7 @@ const
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",
warnLockLevel: "$1", # deadcode
warnResultShadowed: "Special variable 'result' is shadowed.",
warnInconsistentSpacing: "Number of spaces around '$#' is not consistent",
warnCaseTransition: "Potential object case transition, instantiate new object instead",
@@ -164,7 +182,13 @@ const
warnAnyEnumConv: "$1",
warnHoleEnumConv: "$1",
warnCstringConv: "$1",
warnPtrToCstringConv: "unsafe conversion to 'cstring' from '$1'; this will become a compile time error in the future",
warnEffect: "$1",
warnCastSizes: "$1",
warnImplicitTemplateRedefinition: "template '$1' is implicitly redefined; this is deprecated, add an explicit .redefine pragma",
warnUnnamedBreak: "Using an unnamed break in a block is deprecated; Use a named block with a named break instead",
warnStmtListLambda: "statement list expression assumed to be anonymous proc; this is deprecated, use `do (): ...` or `proc () = ...` instead",
warnBareExcept: "$1",
warnUser: "$1",
hintSuccess: "operation successful: $#",
# keep in sync with `testament.isSuccess`
@@ -197,6 +221,7 @@ const
hintGCStats: "$1",
hintGlobalVar: "global variable declared here",
hintExpandMacro: "expanded macro: $1",
hintAmbiguousEnum: "$1",
hintUser: "$1",
hintUserRaw: "$1",
hintExtendedContext: "$1",
@@ -220,7 +245,7 @@ type
proc computeNotesVerbosity(): array[0..3, TNoteKinds] =
result[3] = {low(TNoteKind)..high(TNoteKind)} - {warnObservableStores, warnResultUsed, warnAnyEnumConv}
result[2] = result[3] - {hintStackTrace, warnUninit, hintExtendedContext, hintDeclaredLoc, hintProcessingStmt}
result[2] = result[3] - {hintStackTrace, hintExtendedContext, hintDeclaredLoc, hintProcessingStmt}
result[1] = result[2] - {warnProveField, warnProveIndex,
warnGcUnsafe, hintPath, hintDependency, hintCodeBegin, hintCodeEnd,
hintSource, hintGlobalVar, hintGCStats, hintMsgOrigin, hintPerformance}

View File

@@ -12,7 +12,8 @@
import std/strutils
from std/sugar import dup
import options, ast, msgs, idents, lineinfos, wordrecg, astmsgs
import options, ast, msgs, idents, lineinfos, wordrecg, astmsgs, semdata, packages
export packages
const
Letters* = {'a'..'z', 'A'..'Z', '0'..'9', '\x80'..'\xFF', '_'}
@@ -85,24 +86,33 @@ proc differ*(line: string, a, b: int, x: string): string =
result = y
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
if k in {skType, skGenericParam} and sfAnon in s.flags: return
if s.typ != nil and s.typ.kind == tyTypeDesc: return
if {sfImportc, sfExportc} * s.flags != {}: return
if optStyleCheck notin s.options: return
let beau = beautifyName(s.name.s, k)
if s.name.s != beau:
lintReport(conf, info, beau, s.name.s)
template styleCheckDef*(conf: ConfigRef; info: TLineInfo; s: PSym; k: TSymKind) =
if {optStyleHint, optStyleError} * conf.globalOptions != {} and optStyleUsages notin conf.globalOptions:
nep1CheckDefImpl(conf, info, s, k)
template styleCheckDef*(ctx: PContext; info: TLineInfo; sym: PSym; k: TSymKind) =
## Check symbol definitions adhere to NEP1 style rules.
if optStyleCheck in ctx.config.options and # ignore if styleChecks are off
{optStyleHint, optStyleError} * ctx.config.globalOptions != {} and # check only if hint/error is enabled
hintName in ctx.config.notes and # ignore if name checks are not requested
ctx.config.belongsToProjectPackage(ctx.module) and # ignore foreign packages
optStyleUsages notin ctx.config.globalOptions and # ignore if requested to only check name usage
sym.kind != skResult and # ignore `result`
sym.kind != skTemp and # ignore temporary variables created by the compiler
sym.name.s[0] in Letters and # ignore operators TODO: what about unicode symbols???
k notin {skType, skGenericParam} and # ignore types and generic params
(sym.typ == nil or sym.typ.kind != tyTypeDesc) and # ignore `typedesc`
{sfImportc, sfExportc} * sym.flags == {} and # ignore FFI
sfAnon notin sym.flags: # ignore if created by compiler
nep1CheckDefImpl(ctx.config, info, sym, k)
template styleCheckDef*(conf: ConfigRef; info: TLineInfo; s: PSym) =
styleCheckDef(conf, info, s, s.kind)
template styleCheckDef*(conf: ConfigRef; s: PSym) =
styleCheckDef(conf, s.info, s, s.kind)
template styleCheckDef*(ctx: PContext; info: TLineInfo; s: PSym) =
## Check symbol definitions adhere to NEP1 style rules.
styleCheckDef(ctx, info, s, s.kind)
template styleCheckDef*(ctx: PContext; s: PSym) =
## Check symbol definitions adhere to NEP1 style rules.
styleCheckDef(ctx, s.info, s, s.kind)
proc differs(conf: ConfigRef; info: TLineInfo; newName: string): string =
let line = sourceLine(conf, info)
@@ -116,23 +126,27 @@ proc differs(conf: ConfigRef; info: TLineInfo; newName: string): string =
let last = first+identLen(line, first)-1
result = differ(line, first, last, newName)
proc styleCheckUse*(conf: ConfigRef; info: TLineInfo; s: PSym) =
if info.fileIndex.int < 0: return
# we simply convert it to what it looks like in the definition
# for consistency
# operators stay as they are:
if s.kind == skTemp or s.name.s[0] notin Letters or sfAnon in s.flags:
return
proc styleCheckUseImpl(conf: ConfigRef; info: TLineInfo; s: PSym) =
let newName = s.name.s
let badName = differs(conf, info, newName)
if badName.len > 0:
# special rules for historical reasons
let forceHint = badName == "nnkArgList" and newName == "nnkArglist" or badName == "nnkArglist" and newName == "nnkArgList"
lintReport(conf, info, newName, badName, forceHint = forceHint, extraMsg = "".dup(addDeclaredLoc(conf, s)))
lintReport(conf, info, newName, badName, "".dup(addDeclaredLoc(conf, s)))
proc checkPragmaUse*(conf: ConfigRef; info: TLineInfo; w: TSpecialWord; pragmaName: string) =
template styleCheckUse*(ctx: PContext; info: TLineInfo; sym: PSym) =
## Check symbol uses match their definition's style.
if {optStyleHint, optStyleError} * ctx.config.globalOptions != {} and # ignore if styleChecks are off
hintName in ctx.config.notes and # ignore if name checks are not requested
ctx.config.belongsToProjectPackage(ctx.module) and # ignore foreign packages
sym.kind != skTemp and # ignore temporary variables created by the compiler
sym.name.s[0] in Letters and # ignore operators TODO: what about unicode symbols???
sfAnon notin sym.flags: # ignore temporary variables created by the compiler
styleCheckUseImpl(ctx.config, info, sym)
proc checkPragmaUseImpl(conf: ConfigRef; info: TLineInfo; w: TSpecialWord; pragmaName: string) =
let wanted = $w
if pragmaName != wanted:
lintReport(conf, info, wanted, pragmaName)
template checkPragmaUse*(conf: ConfigRef; info: TLineInfo; w: TSpecialWord; pragmaName: string) =
if {optStyleHint, optStyleError} * conf.globalOptions != {}:
checkPragmaUseImpl(conf, info, w, pragmaName)

View File

@@ -12,6 +12,9 @@
import
pathutils
when defined(nimPreviewSlimSystem):
import std/syncio
# support `useGnuReadline`, `useLinenoise` for backwards compatibility
const hasRstdin = (defined(nimUseLinenoise) or defined(useLinenoise) or defined(useGnuReadline)) and
not defined(windows)

View File

@@ -9,9 +9,13 @@
# This module implements lookup helpers.
import std/[algorithm, strutils]
when defined(nimPreviewSlimSystem):
import std/assertions
import
intsets, ast, astalgo, idents, semdata, types, msgs, options,
renderer, nimfix/prettybase, lineinfos, modulegraphs, astmsgs
renderer, nimfix/prettybase, lineinfos, modulegraphs, astmsgs, sets
proc ensureNoMissingOrUnusedSymbols(c: PContext; scope: PScope)
@@ -44,6 +48,11 @@ proc considerQuotedIdent*(c: PContext; n: PNode, origin: PNode = nil): PIdent =
case x.kind
of nkIdent: id.add(x.ident.s)
of nkSym: id.add(x.sym.name.s)
of nkSymChoices:
if x[0].kind == nkSym:
id.add(x[0].sym.name.s)
else:
handleError(n, origin)
of nkLiterals - nkFloatLiterals: id.add(x.renderTree)
else: handleError(n, origin)
result = getIdent(c.cache, id)
@@ -161,6 +170,7 @@ iterator allSyms*(c: PContext): (PSym, int, bool) =
# really iterate over all symbols in all the scopes. This is expensive
# and only used by suggest.nim.
var isLocal = true
var scopeN = 0
for scope in allScopes(c.currentScope):
if scope == c.topLevelScope: isLocal = false
@@ -175,11 +185,20 @@ iterator allSyms*(c: PContext): (PSym, int, bool) =
assert s != nil
yield (s, scopeN, isLocal)
iterator uniqueSyms*(c: PContext): (PSym, int, bool) =
## Like [allSyms] except only returns unique symbols (Uniqueness determined by line + name)
# Track seen symbols so we don't duplicate them.
# The int is for the symbols name, and line info is
# to be able to tell apart symbols with same name but on different lines
var seen = initHashSet[(TLineInfo, int)]()
for res in allSyms(c):
if not seen.containsOrIncl((res[0].info, res[0].name.id)):
yield res
proc someSymFromImportTable*(c: PContext; name: PIdent; ambiguous: var bool): PSym =
var marked = initIntSet()
var symSet = OverloadableSyms
if overloadableEnums notin c.features:
symSet.excl skEnumField
result = nil
block outer:
for im in c.imports.mitems:
@@ -209,6 +228,23 @@ proc debugScopes*(c: PContext; limit=0, max = int.high) {.deprecated.} =
if i == limit: return
inc i
proc searchInScopesAllCandidatesFilterBy*(c: PContext, s: PIdent, filter: TSymKinds): seq[PSym] =
result = @[]
for scope in allScopes(c.currentScope):
var ti: TIdentIter
var candidate = initIdentIter(ti, scope.symbols, s)
while candidate != nil:
if candidate.kind in filter:
result.add candidate
candidate = nextIdentIter(ti, scope.symbols)
if result.len == 0:
var marked = initIntSet()
for im in c.imports.mitems:
for s in symbols(im, marked, s, c.graph):
if s.kind in filter:
result.add s
proc searchInScopesFilterBy*(c: PContext, s: PIdent, filter: TSymKinds): seq[PSym] =
result = @[]
block outer:
@@ -304,9 +340,11 @@ proc wrongRedefinition*(c: PContext; info: TLineInfo, s: string;
# xxx pending bootstrap >= 1.4, replace all those overloads with a single one:
# proc addDecl*(c: PContext, sym: PSym, info = sym.info, scope = c.currentScope) {.inline.} =
proc addDeclAt*(c: PContext; scope: PScope, sym: PSym, info: TLineInfo) =
if sym.name.s == "_": return
let conflict = scope.addUniqueSym(sym)
if conflict != nil:
if sym.kind == skModule and conflict.kind == skModule and sym.owner == conflict.owner:
if sym.kind == skModule and conflict.kind == skModule and
sym.position == conflict.position:
# e.g.: import foo; import foo
# xxx we could refine this by issuing a different hint for the case
# where a duplicate import happens inside an include.
@@ -415,7 +453,7 @@ type SpellCandidate = object
msg: string
sym: PSym
template toOrderTup(a: SpellCandidate): auto =
template toOrderTup(a: SpellCandidate): (int, int, string) =
# `dist` is first, to favor nearby matches
# `depth` is next, to favor nearby enclosing scopes among ties
# `sym.name.s` is last, to make the list ordered and deterministic among ties
@@ -438,12 +476,13 @@ proc fixSpelling(c: PContext, n: PNode, ident: PIdent, result: var string) =
let dist = editDistance(name0, sym.name.s.nimIdentNormalize)
var msg: string
msg.add "\n ($1, $2): '$3'" % [$dist, $depth, sym.name.s]
addDeclaredLoc(msg, c.config, sym) # `msg` needed for deterministic ordering.
list.push SpellCandidate(dist: dist, depth: depth, msg: msg, sym: sym)
if list.len == 0: return
let e0 = list[0]
var count = 0
var
count = 0
last: PIdent = nil
while true:
# pending https://github.com/timotheecour/Nim/issues/373 use more efficient `itemsSorted`.
if list.len == 0: break
@@ -459,8 +498,10 @@ proc fixSpelling(c: PContext, n: PNode, ident: PIdent, result: var string) =
elif count >= c.config.spellSuggestMax: break
if count == 0:
result.add "\ncandidates (edit distance, scope distance); see '--spellSuggest': "
result.add e.msg
count.inc
if e.sym.name != last:
result.add e.msg
count.inc
last = e.sym.name
proc errorUseQualifier(c: PContext; info: TLineInfo; s: PSym; amb: var bool): PSym =
var err = "ambiguous identifier: '" & s.name.s & "'"
@@ -486,17 +527,24 @@ proc errorUseQualifier*(c: PContext; info: TLineInfo; s: PSym) =
var amb: bool
discard errorUseQualifier(c, info, s, amb)
proc errorUseQualifier(c: PContext; info: TLineInfo; candidates: seq[PSym]) =
proc errorUseQualifier(c: PContext; info: TLineInfo; candidates: seq[PSym]; prefix = "use one of") =
var err = "ambiguous identifier: '" & candidates[0].name.s & "'"
var i = 0
for candidate in candidates:
if i == 0: err.add " -- use one of the following:\n"
if i == 0: err.add " -- $1 the following:\n" % prefix
else: err.add "\n"
err.add " " & candidate.owner.name.s & "." & candidate.name.s
err.add ": " & typeToString(candidate.typ)
inc i
localError(c.config, info, errGenerated, err)
proc errorUseQualifier*(c: PContext; info:TLineInfo; choices: PNode) =
var candidates = newSeq[PSym](choices.len)
let prefix = if choices[0].typ.kind != tyProc: "use one of" else: "you need a helper proc to disambiguate"
for i, n in choices:
candidates[i] = n.sym
errorUseQualifier(c, info, candidates, prefix)
proc errorUndeclaredIdentifier*(c: PContext; info: TLineInfo; name: string, extra = "") =
var err = "undeclared identifier: '" & name & "'" & extra
if c.recursiveDep.len > 0:

View File

@@ -15,6 +15,9 @@ const
import ast, astalgo, types, idents, magicsys, msgs, options, modulegraphs,
lineinfos
when defined(nimPreviewSlimSystem):
import std/assertions
proc newDeref*(n: PNode): PNode {.inline.} =
result = newNodeIT(nkHiddenDeref, n.info, n.typ[0])
result.add n
@@ -71,14 +74,20 @@ proc lowerTupleUnpacking*(g: ModuleGraph; n: PNode; idgen: IdGenerator; owner: P
let value = n.lastSon
result = newNodeI(nkStmtList, n.info)
var temp = newSym(skTemp, getIdent(g.cache, genPrefix), nextSymId(idgen),
owner, value.info, g.config.options)
temp.typ = skipTypes(value.typ, abstractInst)
incl(temp.flags, sfFromGeneric)
var tempAsNode: PNode
let avoidTemp = value.kind == nkSym
if avoidTemp:
tempAsNode = value
else:
var temp = newSym(skTemp, getIdent(g.cache, genPrefix), nextSymId(idgen),
owner, value.info, g.config.options)
temp.typ = skipTypes(value.typ, abstractInst)
incl(temp.flags, sfFromGeneric)
tempAsNode = newSymNode(temp)
var v = newNodeI(nkVarSection, value.info)
let tempAsNode = newSymNode(temp)
v.addVar(tempAsNode, value)
if not avoidTemp:
v.addVar(tempAsNode, value)
result.add(v)
for i in 0..<n.len-2:
@@ -221,7 +230,7 @@ proc lookupInRecord(n: PNode, id: ItemId): PSym =
if n.sym.itemId.module == id.module and n.sym.itemId.item == -abs(id.item): result = n.sym
else: discard
proc addField*(obj: PType; s: PSym; cache: IdentCache; idgen: IdGenerator) =
proc addField*(obj: PType; s: PSym; cache: IdentCache; idgen: IdGenerator): PSym =
# because of 'gensym' support, we have to mangle the name with its ID.
# This is hacky but the clean solution is much more complex than it looks.
var field = newSym(skField, getIdent(cache, s.name.s & $obj.n.len),
@@ -232,9 +241,11 @@ proc addField*(obj: PType; s: PSym; cache: IdentCache; idgen: IdGenerator) =
assert t.kind != tyTyped
propagateToOwner(obj, t)
field.position = obj.n.len
field.flags = s.flags * {sfCursor}
# sfNoInit flag for skField is used in closureiterator codegen
field.flags = s.flags * {sfCursor, sfNoInit}
obj.n.add newSymNode(field)
fieldCheck()
result = field
proc addUniqueField*(obj: PType; s: PSym; cache: IdentCache; idgen: IdGenerator): PSym {.discardable.} =
result = lookupInRecord(obj.n, s.itemId)

View File

@@ -16,21 +16,23 @@ import
std/[strutils, os, times, tables, sha1, with, json],
llstream, ast, lexer, syntaxes, options, msgs,
condsyms,
sem, idents, passes, extccomp,
idents, extccomp,
cgen, nversion,
platform, nimconf, passaux, depends, vm,
platform, nimconf, depends,
modules,
modulegraphs, lineinfos, pathutils, vmprofiler
when defined(nimPreviewSlimSystem):
import std/[syncio, assertions]
import ic / [cbackend, integrity, navigator]
from ic / ic import rodViewer
when not defined(leanCompiler):
import jsgen, docgen, docgen2
import pipelines
proc semanticPasses(g: ModuleGraph) =
registerPass g, verbosePass
registerPass g, semPass
when not defined(leanCompiler):
import docgen
proc writeDepsFile(g: ModuleGraph) =
let fname = g.config.nimcacheDir / RelativeFile(g.config.projectName & ".deps")
@@ -43,13 +45,39 @@ proc writeDepsFile(g: ModuleGraph) =
f.writeLine(toFullPath(g.config, k))
f.close()
proc writeCMakeDepsFile(conf: ConfigRef) =
## write a list of C files for build systems like CMake.
## only updated when the C file list changes.
let fname = getNimcacheDir(conf) / conf.outFile.changeFileExt("cdeps")
# generate output files list
var cfiles: seq[string] = @[]
for it in conf.toCompile: cfiles.add(it.cname.string)
let fileset = cfiles.toCountTable()
# read old cfiles list
var fl: File
var prevset = initCountTable[string]()
if open(fl, fname.string, fmRead):
for line in fl.lines: prevset.inc(line)
fl.close()
# write cfiles out
if fileset != prevset:
fl = open(fname.string, fmWrite)
for line in cfiles: fl.writeLine(line)
fl.close()
proc commandGenDepend(graph: ModuleGraph) =
semanticPasses(graph)
registerPass(graph, gendependPass)
compileProject(graph)
setPipeLinePass(graph, GenDependPass)
compilePipelineProject(graph)
let project = graph.config.projectFull
writeDepsFile(graph)
generateDot(graph, project)
# dot in graphivz tool kit is required
let graphvizDotPath = findExe("dot")
if graphvizDotPath.len == 0:
quit("gendepend: Graphviz's tool dot is required," &
"see https://graphviz.org/download for downloading")
execExternalProgram(graph.config, "dot -Tpng -o" &
changeFileExt(project, "png").string &
' ' & changeFileExt(project, "dot").string)
@@ -58,8 +86,13 @@ proc commandCheck(graph: ModuleGraph) =
let conf = graph.config
conf.setErrorMaxHighMaybe
defineSymbol(conf.symbols, "nimcheck")
semanticPasses(graph) # use an empty backend for semantic checking only
compileProject(graph)
if optWasNimscript in conf.globalOptions:
defineSymbol(conf.symbols, "nimscript")
defineSymbol(conf.symbols, "nimconfig")
elif conf.backend == backendJs:
setTarget(conf.target, osJS, cpuJS)
setPipeLinePass(graph, SemPass)
compilePipelineProject(graph)
if conf.symbolFiles != disabledSf:
case conf.ideCmd
@@ -73,22 +106,20 @@ when not defined(leanCompiler):
proc commandDoc2(graph: ModuleGraph; ext: string) =
handleDocOutputOptions graph.config
graph.config.setErrorMaxHighMaybe
semanticPasses(graph)
case ext:
of TexExt: registerPass(graph, docgen2TexPass)
of JsonExt: registerPass(graph, docgen2JsonPass)
of HtmlExt: registerPass(graph, docgen2Pass)
of TexExt:
setPipeLinePass(graph, Docgen2TexPass)
of JsonExt:
setPipeLinePass(graph, Docgen2JsonPass)
of HtmlExt:
setPipeLinePass(graph, Docgen2Pass)
else: doAssert false, $ext
compileProject(graph)
finishDoc2Pass(graph.config.projectName)
compilePipelineProject(graph)
proc commandCompileToC(graph: ModuleGraph) =
let conf = graph.config
extccomp.initVars(conf)
semanticPasses(graph)
if conf.symbolFiles == disabledSf:
registerPass(graph, cgenPass)
if {optRun, optForceFullMake} * conf.globalOptions == {optRun} or isDefined(conf, "nimBetterRun"):
if not changeDetectedViaJsonBuildInstructions(conf, conf.jsonBuildInstructionsFile):
# nothing changed
@@ -98,7 +129,11 @@ proc commandCompileToC(graph: ModuleGraph) =
if not extccomp.ccHasSaneOverflow(conf):
conf.symbols.defineSymbol("nimEmulateOverflowChecks")
compileProject(graph)
if conf.symbolFiles == disabledSf:
setPipeLinePass(graph, CgenPass)
else:
setPipeLinePass(graph, SemPass)
compilePipelineProject(graph)
if graph.config.errorCounter > 0:
return # issue #9933
if conf.symbolFiles == disabledSf:
@@ -117,6 +152,8 @@ proc commandCompileToC(graph: ModuleGraph) =
extccomp.writeJsonBuildInstructions(conf)
if optGenScript in graph.config.globalOptions:
writeDepsFile(graph)
if optGenCDeps in graph.config.globalOptions:
writeCMakeDepsFile(conf)
proc commandJsonScript(graph: ModuleGraph) =
extccomp.runJsonBuildInstructions(graph.config, graph.config.jsonBuildInstructionsFile)
@@ -129,33 +166,27 @@ proc commandCompileToJS(graph: ModuleGraph) =
conf.exc = excCpp
setTarget(conf.target, osJS, cpuJS)
defineSymbol(conf.symbols, "ecmascript") # For backward compatibility
semanticPasses(graph)
registerPass(graph, JSgenPass)
compileProject(graph)
setPipeLinePass(graph, JSgenPass)
compilePipelineProject(graph)
if optGenScript in conf.globalOptions:
writeDepsFile(graph)
proc interactivePasses(graph: ModuleGraph) =
proc commandInteractive(graph: ModuleGraph) =
graph.config.setErrorMaxHighMaybe
initDefines(graph.config.symbols)
defineSymbol(graph.config.symbols, "nimscript")
# note: seems redundant with -d:nimHasLibFFI
when hasFFI: defineSymbol(graph.config.symbols, "nimffi")
registerPass(graph, verbosePass)
registerPass(graph, semPass)
registerPass(graph, evalPass)
proc commandInteractive(graph: ModuleGraph) =
graph.config.setErrorMaxHighMaybe
interactivePasses(graph)
compileSystemModule(graph)
setPipeLinePass(graph, InterpreterPass)
compilePipelineSystemModule(graph)
if graph.config.commandArgs.len > 0:
discard graph.compileModule(fileInfoIdx(graph.config, graph.config.projectFull), {})
discard graph.compilePipelineModule(fileInfoIdx(graph.config, graph.config.projectFull), {})
else:
var m = graph.makeStdinModule()
incl(m.flags, sfMainModule)
var idgen = IdGenerator(module: m.itemId.module, symId: m.itemId.item, typeId: 0)
let s = llStreamOpenStdIn(onPrompt = proc() = flushDot(graph.config))
processModule(graph, m, idgen, s)
discard processPipelineModule(graph, m, idgen, s)
proc commandScan(cache: IdentCache, config: ConfigRef) =
var f = addFileExt(AbsoluteFile mainCommandArg(config), NimExt)
@@ -210,8 +241,6 @@ proc mainCommand*(graph: ModuleGraph) =
let conf = graph.config
let cache = graph.cache
# In "nim serve" scenario, each command must reset the registered passes
clearPasses(graph)
conf.lastCmdTime = epochTime()
conf.searchPaths.add(conf.libpath)
@@ -267,7 +296,8 @@ proc mainCommand*(graph: ModuleGraph) =
var ret = if optUseNimcache in conf.globalOptions: getNimcacheDir(conf)
else: conf.projectPath
doAssert ret.string.isAbsolute # `AbsoluteDir` is not a real guarantee
if conf.cmd in cmdDocLike + {cmdRst2html, cmdRst2tex}: ret = ret / htmldocsDir
if conf.cmd in cmdDocLike + {cmdRst2html, cmdRst2tex, cmdMd2html, cmdMd2tex}:
ret = ret / htmldocsDir
conf.outDir = ret
## process all commands
@@ -284,7 +314,6 @@ proc mainCommand*(graph: ModuleGraph) =
of cmdDoc0: docLikeCmd commandDoc(cache, conf)
of cmdDoc:
docLikeCmd():
conf.setNoteDefaults(warnLockLevel, false) # issue #13218
conf.setNoteDefaults(warnRstRedefinitionOfLabel, false) # issue #13218
# because currently generates lots of false positives due to conflation
# of labels links in doc comments, e.g. for random.rand:
@@ -293,7 +322,7 @@ proc mainCommand*(graph: ModuleGraph) =
commandDoc2(graph, HtmlExt)
if optGenIndex in conf.globalOptions and optWholeProject in conf.globalOptions:
commandBuildIndex(conf, $conf.outDir)
of cmdRst2html:
of cmdRst2html, cmdMd2html:
# XXX: why are warnings disabled by default for rst2html and rst2tex?
for warn in rstWarnings:
conf.setNoteDefaults(warn, true)
@@ -302,20 +331,24 @@ proc mainCommand*(graph: ModuleGraph) =
conf.quitOrRaise "compiler wasn't built with documentation generator"
else:
loadConfigs(DocConfig, cache, conf, graph.idgen)
commandRst2Html(cache, conf)
of cmdRst2tex, cmdDoc2tex:
commandRst2Html(cache, conf, preferMarkdown = (conf.cmd == cmdMd2html))
of cmdRst2tex, cmdMd2tex, cmdDoc2tex:
for warn in rstWarnings:
conf.setNoteDefaults(warn, true)
when defined(leanCompiler):
conf.quitOrRaise "compiler wasn't built with documentation generator"
else:
if conf.cmd == cmdRst2tex:
if conf.cmd in {cmdRst2tex, cmdMd2tex}:
loadConfigs(DocTexConfig, cache, conf, graph.idgen)
commandRst2TeX(cache, conf)
commandRst2TeX(cache, conf, preferMarkdown = (conf.cmd == cmdMd2tex))
else:
docLikeCmd commandDoc2(graph, TexExt)
of cmdJsondoc0: docLikeCmd commandJson(cache, conf)
of cmdJsondoc: docLikeCmd commandDoc2(graph, JsonExt)
of cmdJsondoc:
docLikeCmd():
commandDoc2(graph, JsonExt)
if optGenIndex in conf.globalOptions and optWholeProject in conf.globalOptions:
commandBuildIndexJson(conf, $conf.outDir)
of cmdCtags: docLikeCmd commandTags(cache, conf)
of cmdBuildindex: docLikeCmd commandBuildIndex(conf, $conf.projectFull, conf.outFile)
of cmdGendepend: commandGenDepend(graph)
@@ -363,7 +396,8 @@ proc mainCommand*(graph: ModuleGraph) =
msgWriteln(conf, "-- end of list --", {msgStdout, msgSkipHook})
for it in conf.searchPaths: msgWriteln(conf, it.string)
of cmdCheck: commandCheck(graph)
of cmdCheck:
commandCheck(graph)
of cmdParse:
wantMainModule(conf)
discard parseFile(conf.projectMainIdx, cache, conf)

View File

@@ -12,9 +12,12 @@
## or stored in a rod-file.
import intsets, tables, hashes, md5
import ast, astalgo, options, lineinfos,idents, btrees, ropes, msgs, pathutils
import ast, astalgo, options, lineinfos,idents, btrees, ropes, msgs, pathutils, packages
import ic / [packed_ast, ic]
when defined(nimPreviewSlimSystem):
import std/assertions
type
SigHash* = distinct MD5Digest
@@ -50,6 +53,22 @@ type
concreteTypes*: seq[FullId]
inst*: PInstantiation
SymInfoPair* = object
sym*: PSym
info*: TLineInfo
PipelinePass* = enum
NonePass
SemPass
JSgenPass
CgenPass
EvalPass
InterpreterPass
GenDependPass
Docgen2TexPass
Docgen2JsonPass
Docgen2Pass
ModuleGraph* {.acyclic.} = ref object
ifaces*: seq[Iface] ## indexed by int32 fileIdx
packed*: PackedModuleGraph
@@ -57,14 +76,13 @@ type
typeInstCache*: Table[ItemId, seq[LazyType]] # A symbol's ItemId.
procInstCache*: Table[ItemId, seq[LazyInstantiation]] # A symbol's ItemId.
attachedOps*: array[TTypeAttachedOp, Table[ItemId, PSym]] # Type ID, destructors, etc.
attachedOps*: array[TTypeAttachedOp, Table[ItemId, LazySym]] # Type ID, destructors, etc.
methodsPerType*: Table[ItemId, seq[(int, LazySym)]] # Type ID, attached methods
enumToStringProcs*: Table[ItemId, LazySym]
emittedTypeInfo*: Table[string, FileIndex]
startupPackedConfig*: PackedConfig
packageSyms*: TStrTable
modulesPerPackage*: Table[ItemId, TStrTable]
deps*: IntSet # the dependency graph or potentially its transitive closure.
importDeps*: Table[FileIndex, seq[FileIndex]] # explicit import module dependencies
suggestMode*: bool # whether we are in nimsuggest mode or not.
@@ -81,6 +99,8 @@ type
doStopCompile*: proc(): bool {.closure.}
usageSym*: PSym # for nimsuggest
owners*: seq[PSym]
suggestSymbols*: Table[FileIndex, seq[SymInfoPair]]
suggestErrors*: Table[FileIndex, seq[Suggest]]
methods*: seq[tuple[methods: seq[PSym], dispatcher: PSym]] # needs serialization!
systemModule*: PSym
sysTypes*: array[TTypeKind, PType]
@@ -96,6 +116,7 @@ type
cacheCounters*: Table[string, BiggestInt] # IC: implemented
cacheTables*: Table[string, BTree[string, PNode]] # IC: implemented
passes*: seq[TPass]
pipelinePass*: PipelinePass
onDefinition*: proc (graph: ModuleGraph; s: PSym; info: TLineInfo) {.nimcall.}
onDefinitionResolveForward*: proc (graph: ModuleGraph; s: PSym; info: TLineInfo) {.nimcall.}
onUsage*: proc (graph: ModuleGraph; s: PSym; info: TLineInfo) {.nimcall.}
@@ -277,6 +298,13 @@ proc resolveInst(g: ModuleGraph; t: var LazyInstantiation): PInstantiation =
t.inst = result
assert result != nil
proc resolveAttachedOp(g: ModuleGraph; t: var LazySym): PSym =
result = t.sym
if result == nil:
result = loadSymFromId(g.config, g.cache, g.packed, t.id.module, t.id.packed)
t.sym = result
assert result != nil
iterator typeInstCacheItems*(g: ModuleGraph; s: PSym): PType =
if g.typeInstCache.contains(s.itemId):
let x = addr(g.typeInstCache[s.itemId])
@@ -292,22 +320,25 @@ iterator procInstCacheItems*(g: ModuleGraph; s: PSym): PInstantiation =
proc getAttachedOp*(g: ModuleGraph; t: PType; op: TTypeAttachedOp): PSym =
## returns the requested attached operation for type `t`. Can return nil
## if no such operation exists.
result = g.attachedOps[op].getOrDefault(t.itemId)
if g.attachedOps[op].contains(t.itemId):
result = resolveAttachedOp(g, g.attachedOps[op][t.itemId])
else:
result = nil
proc setAttachedOp*(g: ModuleGraph; module: int; t: PType; op: TTypeAttachedOp; value: PSym) =
## we also need to record this to the packed module.
g.attachedOps[op][t.itemId] = value
g.attachedOps[op][t.itemId] = LazySym(sym: value)
proc setAttachedOpPartial*(g: ModuleGraph; module: int; t: PType; op: TTypeAttachedOp; value: PSym) =
## we also need to record this to the packed module.
g.attachedOps[op][t.itemId] = value
# XXX Also add to the packed module!
g.attachedOps[op][t.itemId] = LazySym(sym: value)
proc completePartialOp*(g: ModuleGraph; module: int; t: PType; op: TTypeAttachedOp; value: PSym) =
if g.config.symbolFiles != disabledSf:
assert module < g.encoders.len
assert isActive(g.encoders[module])
toPackedGeneratedProcDef(value, g.encoders[module], g.packed[module].fromDisk)
#storeAttachedProcDef(t, op, value, g.encoders[module], g.packed[module].fromDisk)
proc getToStringProc*(g: ModuleGraph; t: PType): PSym =
result = resolveSym(g, g.enumToStringProcs[t.itemId])
@@ -368,20 +399,9 @@ template getPContext(): untyped =
when c is PContext: c
else: c.c
when defined(nimfind):
template onUse*(info: TLineInfo; s: PSym) =
let c = getPContext()
if c.graph.onUsage != nil: c.graph.onUsage(c.graph, s, info)
template onDef*(info: TLineInfo; s: PSym) =
let c = getPContext()
if c.graph.onDefinition != nil: c.graph.onDefinition(c.graph, s, info)
template onDefResolveForward*(info: TLineInfo; s: PSym) =
let c = getPContext()
if c.graph.onDefinitionResolveForward != nil:
c.graph.onDefinitionResolveForward(c.graph, s, info)
when defined(nimsuggest):
template onUse*(info: TLineInfo; s: PSym) = discard
template onDefResolveForward*(info: TLineInfo; s: PSym) = discard
else:
template onUse*(info: TLineInfo; s: PSym) = discard
template onDef*(info: TLineInfo; s: PSym) = discard
@@ -432,8 +452,7 @@ proc initOperators*(g: ModuleGraph): Operators =
result.opNot = createMagic(g, "not", mNot)
result.opContains = createMagic(g, "contains", mInSet)
proc newModuleGraph*(cache: IdentCache; config: ConfigRef): ModuleGraph =
result = ModuleGraph()
proc initModuleGraphFields(result: ModuleGraph) =
# A module ID of -1 means that the symbol is not attached to a module at all,
# but to the module graph:
result.idgen = IdGenerator(module: -1'i32, symId: 0'i32, typeId: 0'i32)
@@ -443,9 +462,9 @@ proc newModuleGraph*(cache: IdentCache; config: ConfigRef): ModuleGraph =
result.ifaces = @[]
result.importStack = @[]
result.inclToMod = initTable[FileIndex, FileIndex]()
result.config = config
result.cache = cache
result.owners = @[]
result.suggestSymbols = initTable[FileIndex, seq[SymInfoPair]]()
result.suggestErrors = initTable[FileIndex, seq[Suggest]]()
result.methods = @[]
initStrTable(result.compilerprocs)
initStrTable(result.exposed)
@@ -459,6 +478,12 @@ proc newModuleGraph*(cache: IdentCache; config: ConfigRef): ModuleGraph =
result.operators = initOperators(result)
result.emittedTypeInfo = initTable[string, FileIndex]()
proc newModuleGraph*(cache: IdentCache; config: ConfigRef): ModuleGraph =
result = ModuleGraph()
result.config = config
result.cache = cache
initModuleGraphFields(result)
proc resetAllModules*(g: ModuleGraph) =
initStrTable(g.packageSyms)
g.deps = initIntSet()
@@ -470,6 +495,7 @@ proc resetAllModules*(g: ModuleGraph) =
g.methods = @[]
initStrTable(g.compilerprocs)
initStrTable(g.exposed)
initModuleGraphFields(g)
proc getModule*(g: ModuleGraph; fileIdx: FileIndex): PSym =
if fileIdx.int32 >= 0:
@@ -548,7 +574,19 @@ proc transitiveClosure(g: var IntSet; n: int) =
proc markDirty*(g: ModuleGraph; fileIdx: FileIndex) =
let m = g.getModule fileIdx
if m != nil: incl m.flags, sfDirty
if m != nil:
g.suggestSymbols.del(fileIdx)
g.suggestErrors.del(fileIdx)
incl m.flags, sfDirty
proc unmarkAllDirty*(g: ModuleGraph) =
for i in 0i32..<g.ifaces.len.int32:
let m = g.ifaces[i].module
if m != nil:
m.flags.excl sfDirty
proc isDirty*(g: ModuleGraph; m: PSym): bool =
result = g.suggestMode and sfDirty in m.flags
proc markClientsDirty*(g: ModuleGraph; fileIdx: FileIndex) =
# we need to mark its dependent modules D as dirty right away because after
@@ -560,12 +598,26 @@ proc markClientsDirty*(g: ModuleGraph; fileIdx: FileIndex) =
# every module that *depends* on this file is also dirty:
for i in 0i32..<g.ifaces.len.int32:
let m = g.ifaces[i].module
if m != nil and g.deps.contains(i.dependsOn(fileIdx.int)):
incl m.flags, sfDirty
if g.deps.contains(i.dependsOn(fileIdx.int)):
g.markDirty(FileIndex(i))
proc isDirty*(g: ModuleGraph; m: PSym): bool =
result = g.suggestMode and sfDirty in m.flags
proc needsCompilation*(g: ModuleGraph): bool =
# every module that *depends* on this file is also dirty:
for i in 0i32..<g.ifaces.len.int32:
let m = g.ifaces[i].module
if m != nil:
if sfDirty in m.flags:
return true
proc needsCompilation*(g: ModuleGraph, fileIdx: FileIndex): bool =
let module = g.getModule(fileIdx)
if module != nil and g.isDirty(module):
return true
for i in 0i32..<g.ifaces.len.int32:
let m = g.ifaces[i].module
if m != nil and g.isDirty(m) and g.deps.contains(fileIdx.int32.dependsOn(i)):
return true
proc getBody*(g: ModuleGraph; s: PSym): PNode {.inline.} =
result = s.ast[bodyPos]
@@ -594,3 +646,34 @@ proc onProcessing*(graph: ModuleGraph, fileIdx: FileIndex, moduleStatus: string,
let fromModule2 = if fromModule != nil: $fromModule.name.s else: "(toplevel)"
let mode = if isNimscript: "(nims) " else: ""
rawMessage(conf, hintProcessing, "$#$# $#: $#: $#" % [mode, indent, fromModule2, moduleStatus, path])
proc getPackage*(graph: ModuleGraph; fileIdx: FileIndex): PSym =
## Returns a package symbol for yet to be defined module for fileIdx.
## The package symbol is added to the graph if it doesn't exist.
let pkgSym = getPackage(graph.config, graph.cache, fileIdx)
# check if the package is already in the graph
result = graph.packageSyms.strTableGet(pkgSym.name)
if result == nil:
# the package isn't in the graph, so create and add it
result = pkgSym
graph.packageSyms.strTableAdd(pkgSym)
func belongsToStdlib*(graph: ModuleGraph, sym: PSym): bool =
## Check if symbol belongs to the 'stdlib' package.
sym.getPackageSymbol.getPackageId == graph.systemModule.getPackageId
proc `==`*(a, b: SymInfoPair): bool =
result = a.sym == b.sym and a.info.exactEquals(b.info)
proc fileSymbols*(graph: ModuleGraph, fileIdx: FileIndex): seq[SymInfoPair] =
result = graph.suggestSymbols.getOrDefault(fileIdx, @[])
iterator suggestSymbolsIter*(g: ModuleGraph): SymInfoPair =
for xs in g.suggestSymbols.values:
for x in xs:
yield x
iterator suggestErrorsIter*(g: ModuleGraph): Suggest =
for xs in g.suggestErrors.values:
for x in xs:
yield x

View File

@@ -10,100 +10,6 @@
import ast, renderer, strutils, msgs, options, idents, os, lineinfos,
pathutils
when false:
const
considerParentDirs = not defined(noParentProjects)
considerNimbleDirs = not defined(noNimbleDirs)
proc findInNimbleDir(pkg, subdir, dir: string): string =
var best = ""
var bestv = ""
for k, p in os.walkDir(dir, relative=true):
if k == pcDir and p.len > pkg.len+1 and
p[pkg.len] == '-' and p.startsWith(pkg):
let (_, a, _) = getPathVersionChecksum(p)
if bestv.len == 0 or bestv < a:
bestv = a
best = dir / p
if best.len > 0:
var f: File
if open(f, best / changeFileExt(pkg, ".nimble-link")):
# the second line contains what we're interested in, see:
# https://github.com/nim-lang/nimble#nimble-link
var override = ""
discard readLine(f, override)
discard readLine(f, override)
close(f)
if not override.isAbsolute():
best = best / override
else:
best = override
let f = if subdir.len == 0: pkg else: subdir
let res = addFileExt(best / f, "nim")
if best.len > 0 and fileExists(res):
result = res
when false:
proc resolveDollar(project, source, pkg, subdir: string; info: TLineInfo): string =
template attempt(a) =
let x = addFileExt(a, "nim")
if fileExists(x): return x
case pkg
of "stdlib":
if subdir.len == 0:
return options.libpath
else:
for candidate in stdlibDirs:
attempt(options.libpath / candidate / subdir)
of "root":
let root = project.splitFile.dir
if subdir.len == 0:
return root
else:
attempt(root / subdir)
else:
when considerParentDirs:
var p = parentDir(source.splitFile.dir)
# support 'import $karax':
let f = if subdir.len == 0: pkg else: subdir
while p.len > 0:
let dir = p / pkg
if dirExists(dir):
attempt(dir / f)
# 2nd attempt: try to use 'karax/karax'
attempt(dir / pkg / f)
# 3rd attempt: try to use 'karax/src/karax'
attempt(dir / "src" / f)
attempt(dir / "src" / pkg / f)
p = parentDir(p)
when considerNimbleDirs:
if not options.gNoNimblePath:
var nimbleDir = getEnv("NIMBLE_DIR")
if nimbleDir.len == 0: nimbleDir = getHomeDir() / ".nimble"
result = findInNimbleDir(pkg, subdir, nimbleDir / "pkgs")
if result.len > 0: return result
when not defined(windows):
result = findInNimbleDir(pkg, subdir, "/opt/nimble/pkgs")
if result.len > 0: return result
proc scriptableImport(pkg, sub: string; info: TLineInfo): string =
resolveDollar(gProjectFull, info.toFullPath(), pkg, sub, info)
proc lookupPackage(pkg, subdir: PNode): string =
let sub = if subdir != nil: renderTree(subdir, {renderNoComments}).replace(" ") else: ""
case pkg.kind
of nkStrLit, nkRStrLit, nkTripleStrLit:
result = scriptableImport(pkg.strVal, sub, pkg.info)
of nkIdent:
result = scriptableImport(pkg.ident.s, sub, pkg.info)
else:
localError(pkg.info, "package name must be an identifier or string literal")
result = ""
proc getModuleName*(conf: ConfigRef; n: PNode): string =
# This returns a short relative module name without the nim extension
# e.g. like "system", "importer" or "somepath/module"
@@ -163,3 +69,18 @@ proc checkModuleName*(conf: ConfigRef; n: PNode; doLocalError=true): FileIndex =
result = InvalidFileIdx
else:
result = fileInfoIdx(conf, fullPath)
proc mangleModuleName*(conf: ConfigRef; path: AbsoluteFile): string =
## Mangle a relative module path to avoid path and symbol collisions.
##
## Used by backends that need to generate intermediary files from Nim modules.
## This is needed because the compiler uses a flat cache file hierarchy.
##
## Example:
## `foo-#head/../bar` becomes `@foo-@hhead@s..@sbar`
"@m" & relativeTo(path, conf.projectPath).string.multiReplace(
{$os.DirSep: "@s", $os.AltSep: "@s", "#": "@h", "@": "@@", ":": "@c"})
proc demangleModuleName*(path: string): string =
## Demangle a relative module path.
result = path.multiReplace({"@@": "@", "@h": "#", "@s": "/", "@m": "", "@c": ":"})

View File

@@ -10,11 +10,9 @@
## Implements the module handling, including the caching of modules.
import
ast, astalgo, magicsys, msgs, options,
idents, lexer, passes, syntaxes, llstream, modulegraphs,
lineinfos, pathutils, tables
import ic / replayer
ast, magicsys, msgs, options,
idents, lexer, syntaxes, modulegraphs,
lineinfos, pathutils
proc resetSystemArtifacts*(g: ModuleGraph) =
magicsys.resetSysTypes(g)
@@ -22,57 +20,12 @@ proc resetSystemArtifacts*(g: ModuleGraph) =
template getModuleIdent(graph: ModuleGraph, filename: AbsoluteFile): PIdent =
getIdent(graph.cache, splitFile(filename).name)
template packageId(): untyped {.dirty.} = ItemId(module: PackageModuleId, item: int32(fileIdx))
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)
result = graph.packageSyms.strTableGet(pack)
if result == nil:
result = newSym(skPackage, getIdent(graph.cache, pck2), packageId(), nil, info)
#initStrTable(packSym.tab)
graph.packageSyms.strTableAdd(result)
else:
let modules = graph.modulesPerPackage.getOrDefault(result.itemId)
let existing = if modules.data.len > 0: strTableGet(modules, name) else: nil
if existing != nil and existing.info.fileIndex != info.fileIndex:
when false:
# we used to produce an error:
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)
# this makes the new `result`'s owner be the original `result`
result = newSym(skPackage, getIdent(graph.cache, pck3), packageId(), result, info)
#initStrTable(packSym.tab)
graph.packageSyms.strTableAdd(result)
proc partialInitModule(result: PSym; graph: ModuleGraph; fileIdx: FileIndex; filename: AbsoluteFile) =
proc partialInitModule*(result: PSym; graph: ModuleGraph; fileIdx: FileIndex; filename: AbsoluteFile) =
let packSym = getPackage(graph, fileIdx)
result.owner = packSym
result.position = int fileIdx
#initStrTable(result.tab(graph))
when false:
strTableAdd(result.tab, result) # a module knows itself
# This is now implemented via
# c.moduleScope.addSym(module) # a module knows itself
# in sem.nim, around line 527
if graph.modulesPerPackage.getOrDefault(packSym.itemId).data.len == 0:
graph.modulesPerPackage[packSym.itemId] = newStrTable()
graph.modulesPerPackage[packSym.itemId].strTableAdd(result)
proc newModule(graph: ModuleGraph; fileIdx: FileIndex): PSym =
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.
@@ -80,103 +33,21 @@ proc newModule(graph: ModuleGraph; fileIdx: FileIndex): PSym =
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)
rawMessage(graph.config, errGenerated, "invalid module name: '" & result.name.s &
"'; a module name must be a valid Nim identifier.")
partialInitModule(result, graph, fileIdx, filename)
graph.registerModule(result)
proc compileModule*(graph: ModuleGraph; fileIdx: FileIndex; flags: TSymFlags, fromModule: PSym = nil): PSym =
var flags = flags
if fileIdx == graph.config.projectMainIdx2: flags.incl sfMainModule
result = graph.getModule(fileIdx)
template processModuleAux(moduleStatus) =
onProcessing(graph, fileIdx, moduleStatus, fromModule = fromModule)
var s: PLLStream
if sfMainModule in flags:
if graph.config.projectIsStdin: s = stdin.llStreamOpen
elif graph.config.projectIsCmd: s = llStreamOpen(graph.config.cmdInput)
discard processModule(graph, result, idGeneratorFromModule(result), s)
if result == nil:
var cachedModules: seq[FileIndex]
result = moduleFromRodFile(graph, fileIdx, cachedModules)
let filename = AbsoluteFile toFullPath(graph.config, fileIdx)
if result == nil:
result = newModule(graph, fileIdx)
result.flags.incl flags
registerModule(graph, result)
processModuleAux("import")
else:
if sfSystemModule in flags:
graph.systemModule = result
partialInitModule(result, graph, fileIdx, filename)
for m in cachedModules:
registerModuleById(graph, m)
replayStateChanges(graph.packed[m.int].module, graph)
replayGenericCacheInformation(graph, m.int)
elif graph.isDirty(result):
result.flags.excl sfDirty
# reset module fields:
initStrTables(graph, result)
result.ast = nil
processModuleAux("import(dirty)")
graph.markClientsDirty(fileIdx)
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, {}, s)
graph.addDep(s, fileIdx)
# keep track of import relationships
if graph.config.hcrOn:
graph.importDeps.mgetOrPut(FileIndex(s.position), @[]).add(fileIdx)
#if sfSystemModule in result.flags:
# localError(result.info, errAttemptToRedefine, result.name.s)
# restore the notes for outer module:
graph.config.notes =
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 =
result = syntaxes.parseFile(fileIdx, graph.cache, graph.config)
graph.addDep(s, fileIdx)
graph.addIncludeDep(s.position.FileIndex, fileIdx)
proc connectCallbacks*(graph: ModuleGraph) =
graph.includeFileCallback = includeModule
graph.importModuleCallback = importModule
proc compileSystemModule*(graph: ModuleGraph) =
if graph.systemModule == nil:
connectCallbacks(graph)
graph.config.m.systemFileIdx = fileInfoIdx(graph.config,
graph.config.libpath / RelativeFile"system.nim")
discard graph.compileModule(graph.config.m.systemFileIdx, {sfSystemModule})
proc wantMainModule*(conf: ConfigRef) =
if conf.projectFull.isEmpty:
fatal(conf, gCmdLineInfo, "command expects a filename")
conf.projectMainIdx = fileInfoIdx(conf, addFileExt(conf.projectFull, NimExt))
proc compileProject*(graph: ModuleGraph; projectFileIdx = InvalidFileIdx) =
connectCallbacks(graph)
let conf = graph.config
wantMainModule(conf)
configComplete(graph)
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:
graph.compileSystemModule()
discard graph.compileModule(projectFile, {sfMainModule})
proc makeModule*(graph: ModuleGraph; filename: AbsoluteFile): PSym =
result = graph.newModule(fileInfoIdx(graph.config, filename))
registerModule(graph, result)

View File

@@ -10,7 +10,13 @@
import
std/[strutils, os, tables, terminal, macros, times],
std/private/miscdollars,
options, ropes, lineinfos, pathutils, strutils2
options, lineinfos, pathutils
import ropes except `%`
when defined(nimPreviewSlimSystem):
import std/[syncio, assertions]
type InstantiationInfo* = typeof(instantiationInfo())
template instLoc*(): InstantiationInfo = instantiationInfo(-2, fullPaths = true)
@@ -18,6 +24,10 @@ template instLoc*(): InstantiationInfo = instantiationInfo(-2, fullPaths = true)
template toStdOrrKind(stdOrr): untyped =
if stdOrr == stdout: stdOrrStdout else: stdOrrStderr
proc toLowerAscii(a: var string) {.inline.} =
for c in mitems(a):
if isUpperAscii(c): c = char(uint8(c) xor 0b0010_0000'u8)
proc flushDot*(conf: ConfigRef) =
## safe to call multiple times
# xxx one edge case not yet handled is when `printf` is called at CT with `compiletimeFFI`.
@@ -39,18 +49,16 @@ proc toCChar*(c: char; result: var string) {.inline.} =
result.add c
proc makeCString*(s: string): Rope =
result = nil
var res = newStringOfCap(int(s.len.toFloat * 1.1) + 1)
res.add("\"")
result = newStringOfCap(int(s.len.toFloat * 1.1) + 1)
result.add("\"")
for i in 0..<s.len:
# line wrapping of string litterals in cgen'd code was a bad idea, e.g. causes: bug #16265
# It also makes reading c sources or grepping harder, for zero benefit.
# const MaxLineLength = 64
# if (i + 1) mod MaxLineLength == 0:
# res.add("\"\L\"")
toCChar(s[i], res)
res.add('\"')
result.add(rope(res))
toCChar(s[i], result)
result.add('\"')
proc newFileInfo(fullPath: AbsoluteFile, projPath: RelativeFile): TFileInfo =
result.fullPath = fullPath
@@ -74,7 +82,7 @@ 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) =
proc canonicalCase(path: var string) {.inline.} =
## 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
@@ -97,15 +105,13 @@ proc fileInfoIdx*(conf: ConfigRef; filename: AbsoluteFile; isKnownFile: var bool
try:
canon = canonicalizePath(conf, filename)
shallow(canon.string)
except OSError:
canon = filename
# The compiler uses "filenames" such as `command line` or `stdin`
# This flag indicates that we are working with such a path here
pseudoPath = true
var canon2: string
forceCopy(canon2, canon.string) # because `canon` may be shallow
var canon2 = canon.string
canon2.canonicalCase
if conf.m.filenameToIndexTbl.hasKey(canon2):
@@ -114,7 +120,6 @@ proc fileInfoIdx*(conf: ConfigRef; filename: AbsoluteFile; isKnownFile: var bool
else:
isKnownFile = false
result = conf.m.fileInfos.len.FileIndex
#echo "ID ", result.int, " ", canon2
conf.m.fileInfos.add(newFileInfo(canon, if pseudoPath: RelativeFile filename
else: relativeTo(canon, conf.projectPath)))
conf.m.filenameToIndexTbl[canon2] = result
@@ -123,6 +128,13 @@ proc fileInfoIdx*(conf: ConfigRef; filename: AbsoluteFile): FileIndex =
var dummy: bool
result = fileInfoIdx(conf, filename, dummy)
proc fileInfoIdx*(conf: ConfigRef; filename: RelativeFile; isKnownFile: var bool): FileIndex =
fileInfoIdx(conf, AbsoluteFile expandFilename(filename.string), isKnownFile)
proc fileInfoIdx*(conf: ConfigRef; filename: RelativeFile): FileIndex =
var dummy: bool
fileInfoIdx(conf, AbsoluteFile expandFilename(filename.string), dummy)
proc newLineInfo*(fileInfoIdx: FileIndex, line, col: int): TLineInfo =
result.fileIndex = fileInfoIdx
if line < int high(uint16):
@@ -214,11 +226,18 @@ proc setDirtyFile*(conf: ConfigRef; fileIdx: FileIndex; filename: AbsoluteFile)
proc setHash*(conf: ConfigRef; fileIdx: FileIndex; hash: string) =
assert fileIdx.int32 >= 0
shallowCopy(conf.m.fileInfos[fileIdx.int32].hash, hash)
when defined(gcArc) or defined(gcOrc):
conf.m.fileInfos[fileIdx.int32].hash = hash
else:
shallowCopy(conf.m.fileInfos[fileIdx.int32].hash, hash)
proc getHash*(conf: ConfigRef; fileIdx: FileIndex): string =
assert fileIdx.int32 >= 0
shallowCopy(result, conf.m.fileInfos[fileIdx.int32].hash)
when defined(gcArc) or defined(gcOrc):
result = conf.m.fileInfos[fileIdx.int32].hash
else:
shallowCopy(result, conf.m.fileInfos[fileIdx.int32].hash)
proc toFullPathConsiderDirty*(conf: ConfigRef; fileIdx: FileIndex): AbsoluteFile =
if fileIdx.int32 < 0:
@@ -407,12 +426,12 @@ To create a stacktrace, rerun compilation with './koch temp $1 <file>', see $2 f
[conf.command, "intern.html#debugging-the-compiler".createDocLink], conf.unitSep)
quit 1
proc handleError(conf: ConfigRef; msg: TMsgKind, eh: TErrorHandling, s: string) =
proc handleError(conf: ConfigRef; msg: TMsgKind, eh: TErrorHandling, s: string, ignoreMsg: bool) =
if msg in fatalMsgs:
if conf.cmd == cmdIdeTools: log(s)
quit(conf, msg)
if msg >= errMin and msg <= errMax or
(msg in warnMin..hintMax and msg in conf.warningAsErrors):
(msg in warnMin..hintMax and msg in conf.warningAsErrors and not ignoreMsg):
inc(conf.errorCounter)
conf.exitcode = 1'i8
if conf.errorCounter >= conf.errorMax:
@@ -492,7 +511,7 @@ proc formatMsg*(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg: string): s
conf.toFileLineCol(info) & " " & title & getMessageStr(msg, arg)
proc liMessage*(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg: string,
eh: TErrorHandling, info2: InstantiationInfo, isRaw = false) {.noinline.} =
eh: TErrorHandling, info2: InstantiationInfo, isRaw = false) {.gcsafe, noinline.} =
var
title: string
color: ForegroundColor
@@ -520,19 +539,18 @@ proc liMessage*(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg: string,
of warnMin..warnMax:
sev = Severity.Warning
ignoreMsg = not conf.hasWarn(msg)
if msg in conf.warningAsErrors:
ignoreMsg = false
if not ignoreMsg and msg in conf.warningAsErrors:
title = ErrorTitle
color = ErrorColor
else:
title = WarningTitle
color = WarningColor
if not ignoreMsg: writeContext(conf, info)
color = WarningColor
inc(conf.warnCounter)
of hintMin..hintMax:
sev = Severity.Hint
ignoreMsg = not conf.hasHint(msg)
if msg in conf.warningAsErrors:
ignoreMsg = false
if not ignoreMsg and msg in conf.warningAsErrors:
title = ErrorTitle
else:
title = HintTitle
@@ -558,7 +576,7 @@ proc liMessage*(conf: ConfigRef; info: TLineInfo, msg: TMsgKind, arg: string,
" compiler msg initiated here", KindColor,
KindFormat % $hintMsgOrigin,
resetStyle, conf.unitSep)
handleError(conf, msg, eh, s)
handleError(conf, msg, eh, s, ignoreMsg)
if msg in fatalMsgs:
# most likely would have died here but just in case, we restore state
conf.m.errorOutputs = errorOutputsOld
@@ -618,9 +636,9 @@ template internalAssert*(conf: ConfigRef, e: bool) =
let arg = info2.toFileLineCol
internalErrorImpl(conf, unknownLineInfo, arg, info2)
template lintReport*(conf: ConfigRef; info: TLineInfo, beau, got: string, forceHint = false, extraMsg = "") =
template lintReport*(conf: ConfigRef; info: TLineInfo, beau, got: string, extraMsg = "") =
let m = "'$1' should be: '$2'$3" % [got, beau, extraMsg]
let msg = if optStyleError in conf.globalOptions and not forceHint: errGenerated else: hintName
let msg = if optStyleError in conf.globalOptions: errGenerated else: hintName
liMessage(conf, info, msg, m, doNothing, instLoc())
proc quotedFilename*(conf: ConfigRef; i: TLineInfo): Rope =
@@ -673,7 +691,7 @@ proc genSuccessX*(conf: ConfigRef) =
const debugModeHints = "none (DEBUG BUILD, `-d:release` generates faster code)"
if conf.cmd in cmdBackends:
if conf.backend != backendJs:
build.add "gc: $#; " % $conf.selectedGC
build.add "mm: $#; " % $conf.selectedGC
if optThreads in conf.globalOptions: build.add "threads: on; "
build.add "opt: "
if optOptimizeSpeed in conf.options: build.add "speed"

View File

@@ -12,6 +12,9 @@
import ast, msgs, ropes, options, pathutils
when defined(nimPreviewSlimSystem):
import std/[syncio, assertions]
type
NdiFile* = object
enabled: bool

View File

@@ -10,6 +10,9 @@
import ast, renderer, intsets, tables, msgs, options, lineinfos, strformat, idents, treetab, hashes
import sequtils, strutils, sets
when defined(nimPreviewSlimSystem):
import std/assertions
# IMPORTANT: notes not up to date, i'll update this comment again
#
# notes:
@@ -1239,7 +1242,7 @@ proc check(n: PNode, ctx: NilCheckerContext, map: NilMap): Check =
result = check(n.sons[0], ctx, map)
of nkIfStmt, nkIfExpr:
result = checkIf(n, ctx, map)
of nkAsgn:
of nkAsgn, nkFastAsgn, nkSinkAsgn:
result = checkAsgn(n[0], n[1], ctx, map)
of nkVarSection:
result.map = map

View File

@@ -5,11 +5,16 @@ hint[XDeclaredButNotUsed]:off
define:booting
define:nimcore
define:nimPreviewFloatRoundtrip
define:nimPreviewSlimSystem
define:nimPreviewCstringConversion
define:nimPreviewRangeDefault
threads:off
#import:"$projectpath/testability"
@if windows:
cincludes: "$lib/wrappers/libffi/common"
tlsEmulation:off
@end
define:useStdoutAsStdmsg
@@ -23,10 +28,21 @@ define:useStdoutAsStdmsg
#gc:markAndSweep
@if nimHasWarningObservableStores:
warning[ObservableStores]: off
warning[ObservableStores]:off
@end
@if nimHasEffectsOf:
experimental:strictEffects
warningAsError:Effect:on
@if nimHasWarnCastSizes:
warning[CastSizes]:on
@end
@if nimHasWarningAsError:
warningAsError[GcUnsafe2]:on
@end
@if nimHasWarnUnnamedBreak:
warningAserror[UnnamedBreak]:on
@end
@if nimHasWarnBareExcept:
warningAserror[BareExcept]:on
@end

View File

@@ -8,6 +8,10 @@
#
import std/[os, strutils, parseopt]
when defined(nimPreviewSlimSystem):
import std/assertions
when defined(windows) and not defined(nimKochBootstrap):
# remove workaround pending bootstrap >= 1.5.1
# refs https://github.com/nim-lang/Nim/issues/18334#issuecomment-867114536
@@ -37,6 +41,15 @@ when defined(profiler) or defined(memProfiler):
{.hint: "Profiling support is turned on!".}
import nimprof
proc nimbleLockExists(config: ConfigRef): bool =
const nimbleLock = "nimble.lock"
let pd = if not config.projectPath.isEmpty: config.projectPath else: AbsoluteDir(getCurrentDir())
if optSkipParentConfigFiles notin config.globalOptions:
for dir in parentDirs(pd.string, fromRoot=true, inclusive=false):
if fileExists(dir / nimbleLock):
return true
return fileExists(pd.string / nimbleLock)
proc processCmdLine(pass: TCmdLinePass, cmd: string; config: ConfigRef) =
var p = parseopt.initOptParser(cmd)
var argsCount = 0
@@ -70,6 +83,11 @@ proc processCmdLine(pass: TCmdLinePass, cmd: string; config: ConfigRef) =
config.arguments.len > 0 and config.cmd notin {cmdTcc, cmdNimscript, cmdCrun}:
rawMessage(config, errGenerated, errArgsNeedRunOption)
if config.nimbleLockExists:
# disable nimble path if nimble.lock is present.
# see https://github.com/nim-lang/nimble/issues/1004
disableNimblePath(config)
proc getNimRunExe(conf: ConfigRef): string =
# xxx consider defining `conf.getConfigVar("nimrun.exe")` to allow users to
# customize the binary to run the command with, e.g. for custom `nodejs` or `wine`.
@@ -88,9 +106,19 @@ proc handleCmdLine(cache: IdentCache; conf: ConfigRef) =
return
self.processCmdLineAndProjectPath(conf)
var graph = newModuleGraph(cache, conf)
if not self.loadConfigsAndProcessCmdLine(cache, conf, graph):
return
if conf.cmd == cmdCheck and optWasNimscript notin conf.globalOptions and
conf.backend == backendInvalid:
conf.backend = backendC
if conf.selectedGC == gcUnselected:
if conf.backend in {backendC, backendCpp, backendObjc}:
initOrcDefines(conf)
mainCommand(graph)
if conf.hasHint(hintGCStats): echo(GC_getStatistics())
#echo(GC_getStatistics())
@@ -103,7 +131,7 @@ proc handleCmdLine(cache: IdentCache; conf: ConfigRef) =
case conf.cmd
of cmdBackends, cmdTcc:
let nimRunExe = getNimRunExe(conf)
var cmdPrefix: string
var cmdPrefix = ""
if nimRunExe.len > 0: cmdPrefix.add nimRunExe.quoteShell
case conf.backend
of backendC, backendCpp, backendObjc: discard
@@ -116,8 +144,9 @@ proc handleCmdLine(cache: IdentCache; conf: ConfigRef) =
if cmdPrefix.len > 0: cmdPrefix.add " "
# without the `cmdPrefix.len > 0` check, on windows you'd get a cryptic:
# `The parameter is incorrect`
execExternalProgram(conf, cmdPrefix & output.quoteShell & ' ' & conf.arguments)
of cmdDocLike, cmdRst2html, cmdRst2tex: # bugfix(cmdRst2tex was missing)
let cmd = cmdPrefix & output.quoteShell & ' ' & conf.arguments
execExternalProgram(conf, cmd.strip(leading=false,trailing=true))
of cmdDocLike, cmdRst2html, cmdRst2tex, cmdMd2html, cmdMd2tex: # bugfix(cmdRst2tex was missing)
if conf.arguments.len > 0:
# reserved for future use
rawMessage(conf, errGenerated, "'$1 cannot handle arguments" % [$conf.cmd])

View File

@@ -12,6 +12,9 @@
import parseutils, strutils, os, options, msgs, sequtils, lineinfos, pathutils,
std/sha1, tables
when defined(nimPreviewSlimSystem):
import std/[syncio, assertions]
proc addPath*(conf: ConfigRef; path: AbsoluteDir, info: TLineInfo) =
if not conf.searchPaths.contains(path):
conf.searchPaths.insert(path, 0)

View File

@@ -13,6 +13,9 @@ import
llstream, commands, os, strutils, msgs, lexer, ast,
options, idents, wordrecg, strtabs, lineinfos, pathutils, scriptconfig
when defined(nimPreviewSlimSystem):
import std/syncio
# ---------------- configuration file parser -----------------------------
# we use Nim's lexer here to save space and work
@@ -298,7 +301,7 @@ proc loadConfigs*(cfg: RelativeFile; cache: IdentCache; conf: ConfigRef; idgen:
if conf.cmd == cmdNimscript:
showHintConf()
conf.configFiles.setLen 0
if conf.cmd != cmdIdeTools:
if conf.cmd notin {cmdIdeTools, cmdCheck, cmdDump}:
if conf.cmd == cmdNimscript:
runNimScriptIfExists(conf.projectFull, isMain = true)
else:
@@ -308,5 +311,6 @@ proc loadConfigs*(cfg: RelativeFile; cache: IdentCache; conf: ConfigRef; idgen:
runNimScriptIfExists(scriptFile, isMain = true)
else:
# 'nimsuggest foo.nims' means to just auto-complete the NimScript file
# `nim check foo.nims' means to check the syntax of the NimScript file
discard
showHintConf()

View File

@@ -9,10 +9,16 @@
## exposes the Nim VM to clients.
import
ast, astalgo, modules, passes, condsyms,
options, sem, llstream, lineinfos, vm,
ast, modules, condsyms,
options, llstream, lineinfos, vm,
vmdef, modulegraphs, idents, os, pathutils,
passaux, scriptconfig, std/compilesettings
scriptconfig, std/compilesettings
import pipelines
when defined(nimPreviewSlimSystem):
import std/[assertions, syncio]
type
Interpreter* = ref object ## Use Nim as an interpreter with this object
@@ -76,7 +82,7 @@ proc evalScript*(i: Interpreter; scriptStream: PLLStream = nil) =
let s = if scriptStream != nil: scriptStream
else: llStreamOpen(findFile(i.graph.config, i.scriptName), fmRead)
processModule(i.graph, i.mainModule, i.idgen, s)
discard processPipelineModule(i.graph, i.mainModule, i.idgen, s)
proc findNimStdLib*(): string =
## Tries to find a path to a valid "system.nim" file.
@@ -109,12 +115,10 @@ proc createInterpreter*(scriptName: string;
var conf = newConfigRef()
var cache = newIdentCache()
var graph = newModuleGraph(cache, conf)
connectCallbacks(graph)
connectPipelineCallbacks(graph)
initDefines(conf.symbols)
for define in defines:
defineSymbol(conf.symbols, define[0], define[1])
registerPass(graph, semPass)
registerPass(graph, evalPass)
for p in searchPaths:
conf.searchPaths.add(AbsoluteDir p)
@@ -129,7 +133,8 @@ proc createInterpreter*(scriptName: string;
if registerOps:
vm.registerAdditionalOps() # Required to register parts of stdlib modules
graph.vm = vm
graph.compileSystemModule()
setPipeLinePass(graph, EvalPass)
graph.compilePipelineSystemModule()
result = Interpreter(mainModule: m, graph: graph, scriptName: scriptName, idgen: idgen)
proc destroyInterpreter*(i: Interpreter) =
@@ -159,13 +164,11 @@ proc runRepl*(r: TLLRepl;
defineSymbol(conf.symbols, "nimscript")
if supportNimscript: defineSymbol(conf.symbols, "nimconfig")
when hasFFI: defineSymbol(graph.config.symbols, "nimffi")
registerPass(graph, verbosePass)
registerPass(graph, semPass)
registerPass(graph, evalPass)
var m = graph.makeStdinModule()
incl(m.flags, sfMainModule)
var idgen = idGeneratorFromModule(m)
if supportNimscript: graph.vm = setupVM(m, cache, "stdin", graph, idgen)
graph.compileSystemModule()
processModule(graph, m, idgen, llStreamOpenStdIn(r))
setPipeLinePass(graph, InterpreterPass)
graph.compilePipelineSystemModule()
discard processPipelineModule(graph, m, idgen, llStreamOpenStdIn(r))

View File

@@ -22,7 +22,10 @@ proc replaceDeprecated*(conf: ConfigRef; info: TLineInfo; oldSym, newSym: PIdent
let last = first+identLen(line, first)-1
if cmpIgnoreStyle(line[first..last], oldSym.s) == 0:
var x = line.substr(0, first-1) & newSym.s & line.substr(last+1)
system.shallowCopy(conf.m.fileInfos[info.fileIndex.int32].lines[info.line.int-1], x)
when defined(gcArc) or defined(gcOrc):
conf.m.fileInfos[info.fileIndex.int32].lines[info.line.int-1] = move x
else:
system.shallowCopy(conf.m.fileInfos[info.fileIndex.int32].lines[info.line.int-1], x)
conf.m.fileInfos[info.fileIndex.int32].dirty = true
#if newSym.s == "File": writeStackTrace()
@@ -35,5 +38,8 @@ proc replaceComment*(conf: ConfigRef; info: TLineInfo) =
if line[first] != '#': inc first
var x = line.substr(0, first-1) & "discard " & line.substr(first+1).escape
system.shallowCopy(conf.m.fileInfos[info.fileIndex.int32].lines[info.line.int-1], x)
when defined(gcArc) or defined(gcOrc):
conf.m.fileInfos[info.fileIndex.int32].lines[info.line.int-1] = move x
else:
system.shallowCopy(conf.m.fileInfos[info.fileIndex.int32].lines[info.line.int-1], x)
conf.m.fileInfos[info.fileIndex.int32].dirty = true

View File

@@ -15,6 +15,9 @@
import
llstream, strutils
when defined(nimPreviewSlimSystem):
import std/assertions
const
Lrz* = ' '
Apo* = '\''

Some files were not shown because too many files have changed in this diff Show More