* Use assert in runnableExamples and improve boundary check * Add more tests for ceilDiv * Fix comment in ceilDiv * Calling ceilDiv with int type T such like sizeof(T) > 8 is error
22 KiB
v1.6.x - yyyy-mm-dd
Changes affecting backward compatibility
-
Deprecated
std/mersenne. -
system.deletehad a most surprising behavior when the index passed to it was out of bounds (it would delete the last entry then). Compile with-d:nimStrictDeleteso that an index error is produced instead. But be aware 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:nimAuditDeleteswitch, it pretends thatsystem.deleteis deprecated so that it is easier to see where it was used in your code.-d:nimStrictDeletewill become the default in upcoming versions. -
cucharis now deprecated as it aliasedcharwhere arguably it should have aliaseduint8. Please usecharoruint8instead. -
reprnow doesn't insert trailing newline; previous behavior was very inconsistent, see #16034. Use-d:nimLegacyReprWithNewlinefor previous behavior. -
A type conversion from one enum type to another now produces an
[EnumConv]warning. You should useord(orcast, but the compiler won't help, if you misuse it) instead.type A = enum a1, a2 type B = enum b1, b2 echo a1.B # produces a warning echo a1.ord.B # produces no warning -
A dangerous implicit conversion to
cstringnow triggers a[CStringConv]warning. This warning will become an error in future versions! Use an explicit conversion likecstring(x)in order to silence the warning. -
There is a new warning for any type conversion to enum that can be enabled via
.warning[AnyEnumConv]:onor--warning:AnyEnumConv:on. -
Type mismatch errors now show more context, use
-d:nimLegacyTypeMismatchfor previous behavior. -
math.roundnow is rounded "away from zero" in JS backend which is consistent with other backends. See #9125. Use-d:nimLegacyJsRoundfor previous behavior. -
Changed the behavior of
uri.decodeQuerywhen there are unencoded=characters in the decoded values. Prior versions would raise an error. This is no longer the case to comply with the HTML spec and other languages implementations. Old behavior can be obtained with-d:nimLegacyParseQueryStrict.cgi.decodeDatawhich uses the same underlying code is also updated the same way. -
On POSIX systems, the default signal handlers used for Nim programs (it's used for printing the stacktrace on fatal signals) will now re-raise the signal for the OS default handlers to handle.
This lets the OS perform its default actions, which might include core dumping (on select signals) and notifying the parent process about the cause of termination.
-
On POSIX systems, we now ignore
SIGPIPEsignals, use-d:nimLegacySigpipeHandlerfor previous behavior. -
hashes.hashcan now supportobjectandref(can be overloaded in user code), if-d:nimEnableHashRefis used. -
hashes.hash(proc|ptr|ref|pointer)now callshash(int)and honors-d:nimIntHash1,hashes.hash(closure)has also been improved. -
The unary slice
..bwas deprecated, use0..binstead. -
Removed
.travis.yml,appveyor.yml.disabled,.github/workflows/ci.yml.disabled. -
random.initRand(seed)now produces non-skewed values for the 1st call torand()after initialization with a small (< 30000) seed. Use-d:nimLegacyRandomInitRandto restore previous behavior for a transition time, see PR #17467. -
jsonutilsnow serializes/deserializes holey enums as regular enums (viaord) instead of as strings. Use-d:nimLegacyJsonutilsHoleyEnumfor a transition period.toJsonnow serializesJsonNodeas is via reference (without a deep copy) instead of treatingJsonNodeas a regular ref object, this can be customized viajsonNodeMode. -
jsonandjsonutilsnow serialize NaN, Inf, -Inf as strings, so that%[NaN, -Inf]is the string["nan","-inf"]instead of[nan,-inf]which was invalid json. -
strformatis now part ofinclude std/prelude. -
Deprecated
proc reversed*[T](a: openArray[T], first: Natural, last: int): seq[T]instd/algorithm. -
In
std/macros,treeRepr,lispRepr,astGenReprnow represent SymChoice nodes in a collapsed way, use-d:nimLegacyMacrosCollapseSymChoiceto get previous behavior. -
The configuration subsystem now allows for
-d:releaseand-d:dangerto work as expected. The downside is that these defines now have custom logic that doesn't apply for other defines. -
std/os:putEnvnow raises if the 1st argument contains a= -
Renamed
-d:nimCompilerStackraceHintsto-d:nimCompilerStacktraceHints. -
In
std/dom,Intervalis now aref object, same asTimeout. Definitions ofsetTimeout,clearTimeout,setInterval,clearIntervalwere updated. -
The allocator for Nintendo Switch, which was nonfunctional because of breaking changes in libnx, was removed, in favour of the new
-d:nimAllocPagesViaMallocoption.
Standard library additions and changes
-
strformat: added support for parenthesized expressions. added support for const string's instead of just string literals -
system.addFloatandsystem.$now can produce string representations of floating point numbers that are minimal in size and that "roundtrip" (via the "Dragonbox" algorithm). This currently has to be enabled via-d:nimPreviewFloatRoundtrip. It is expected that this behavior becomes the new default in upcoming versions, as with othernimPreviewXdefine flags. -
Fixed buffer overflow bugs in
net -
Exported
sslHandlefromnetandasyncnet. -
Added
sectionsiterator inparsecfg. -
Make custom op in macros.quote work for all statements.
-
On Windows the SSL library now checks for valid certificates. It uses the
cacert.pemfile for this purpose which was extracted fromhttps://curl.se/ca/cacert.pem. Besides the OpenSSL DLLs (e.g. libssl-1_1-x64.dll, libcrypto-1_1-x64.dll) you now also need to shipcacert.pemwith your.exefile. -
typetraits:distinctBasenow is identity instead of error for non distinct types. AddedenumLento return the number of elements in an enum. AddedHoleyEnumfor enums with holes,OrdinalEnumfor enums without holes. AddedhasClosure. AddedpointerBaseto returnTforref T | ptr T. -
preludenow works with the JavaScript target. Addedsequtilsimport toprelude.preludecan now be used viainclude std/prelude, butinclude preludestill works. -
Added
almostEqualinmathfor comparing two float values using a machine epsilon. -
Added
clampinmathwhich allows using aSliceto clamp to a value. -
Added
ceilDivinmathfor round up integer division. -
The JSON module can now handle integer literals and floating point literals of arbitrary length and precision. Numbers that do not fit the underlying
BiggestIntorBiggestFloatfields are kept as string literals and one can use external BigNum libraries to handle these. TheparseFloatfamily of functions also has now optionalrawIntegersandrawFloatsparameters that can be used to enforce that all integer or float literals remain in the "raw" string form so that client code can easily treat small and large numbers uniformly. -
Added
BackwardsIndexoverload forJsonNode. -
json.%,json.to,jsonutils.formJson,jsonutils.toJsonnow work withuint|uint64instead of raising (as in 1.4) or giving wrong results (as in 1.2). -
jsonutilsnow handlescstring(including as Table key), andset. -
added
jsonutils.jsonTooverload withopt = Joptions()param. -
jsonutils.toJsonnow supports customization viaToJsonOptions. -
Added an overload for the
collectmacro that inferes the container type based on the syntax of the last expression. Works with std seqs, tables and sets. -
Added
randStatetemplate that exposes the default random number generator. Useful for library authors. -
Added
random.initRand()overload with no argument which uses the current time as a seed. -
random.initRand(seed)now allowsseed == 0. -
Added
std/sysrandmodule to get random numbers from a secure source provided by the operating system. -
Added
std/enumutilsmodule. AddedgenEnumCaseStmtmacro that generates case statement to parse string to enum. Addeditemsfor enums with holes. AddedsymbolNameto return the enum symbol name ignoring the human readable name. AddedsymbolRankto return the index in which an enum member is listed in an enum. -
Removed deprecated
iupmodule from stdlib, it has already moved to nimble. -
various functions in
httpclientnow accepturlof typeUri. Moreoverrequestfunction'shttpMethodargument of typestringwas deprecated in favor ofHttpMethodenum type. -
nodejsbackend now supports osenv:getEnv,putEnv,envPairs,delEnv,existsEnv. -
Added
cmpMemtosystem. -
doAssertRaisesnow correctly handles foreign exceptions. -
Added
asyncdispatch.activeDescriptorsthat returns the number of currently active async event handles/file descriptors. -
Added
getPorttoasynchttpserver. -
--gc:orcis now 10% faster than previously for common workloads. If you have trouble with its changed behavior, compile with-d:nimOldOrc. -
os.FileInfo(returned bygetFileInfo) now containsblockSize, determining preferred I/O block size for this file object. -
Added
os.getCacheDir()to return platform specific cache directory. -
Added a simpler to use
io.readCharsoverload. -
Added
**to jsffi. -
writeStackTraceis available in JS backend now. -
Added
decodeQuerytostd/uri. -
strscans.scanfnow supports parsing single characters. -
strscans.scanTupleadded which usesstrscans.scanfinternally, returning a tuple which can be unpacked for easier usage ofscanf. -
Added
setutils.toSetthat can take any iterable and convert it to a built-inset, if the iterable yields a built-in settable type. -
Added
setutils.fullSetwhich returns a full built-insetfor a valid type. -
Added
setutils.complementwhich returns the complement of a built-inset. -
Added
setutils.[]=. -
Added
math.isNaN. -
Added
jsbigintsmodule, arbitrary precision integers for JavaScript target. -
Added
math.copySign. -
Added new operations for singly- and doubly linked lists:
lists.toSinglyLinkedListandlists.toDoublyLinkedListconvert fromopenArrays;lists.copyimplements shallow copying;lists.addconcatenates two lists - an O(1) variation that consumes its argument,addMoved, is also supplied. -
Added
euclDivandeuclModtomath. -
Added
httpcore.is1xxand missing HTTP codes. -
Added
jsconsole.jsAssertfor JavaScript target. -
Added
posix_utils.osReleaseFileto get system identification fromos-releasefile on Linux and the BSDs. https://www.freedesktop.org/software/systemd/man/os-release.html -
Added
socketstreammodule that wraps sockets in the stream interface -
Added
sugar.dumpToStringwhich improves onsugar.dump. -
Added
math.signbit. -
Removed the optional
longestMatchparameter of thecritbits._WithPrefixiterators (it never worked reliably) -
In
lists: renamedappendtoaddand retainedappendas an alias; addedprependandprependMovedanalogously toaddandaddMoved; addedremoveforSinglyLinkedLists. -
Deprecated
any. See https://github.com/nim-lang/RFCs/issues/281 -
Added optional
optionsargument tocopyFile,copyFileToDir, andcopyFileWithPermissions. By default, on non-Windows OSes, symlinks are followed (copy files symlinks point to); on Windows,optionsargument is ignored and symlinks are skipped. -
On non-Windows OSes,
copyDirandcopyDirWithPermissionscopy symlinks as symlinks (instead of skipping them as it was before); on Windows symlinks are skipped. -
On non-Windows OSes,
moveFileandmoveDirmove symlinks as symlinks (instead of skipping them sometimes as it was before). -
Added optional
followSymlinksargument tosetFilePermissions. -
Added
os.isAdminto tell whether the caller's process is a member of the Administrators local group (on Windows) or a root (on POSIX). -
Added experimental
linenoise.readLineStatusto get line and status (e.g. ctrl-D or ctrl-C). -
Added
compilesettings.SingleValueSetting.libPath. -
std/wrapnilsdoesn't useexperimental:dotOperatorsanymore, avoiding issues like https://github.com/nim-lang/Nim/issues/13063 (which affected error messages) for modules importingstd/wrapnils. Added??.macro which returns anOption.std/wrapnilscan now be used to protect againstFieldDefecterrors in case objects, generates optimal code (no overhead compared to manual if-else branches), and preserves lvalue semantics which allows modifying an expression. -
Added
math.frexpoverload procs. Deprecatedc_frexp, usefrexpinstead. -
parseopt.initOptParserhas been made available andparseopthas been added back topreludefor all backends. PreviouslyinitOptParserwas unavailable if theosmodule did not haveparamCountorparamStr, but the use of these ininitOptParserwere conditionally to the runtime arguments passed to it, soinitOptParserhas been changed to raiseValueErrorwhen the real command line is not available.parseoptwas previously excluded frompreludefor JS, as it could not be imported. -
Added
system.prepareStrMutationfor better support of low levelmoveMem,copyMemoperations for Orc's copy-on-write string implementation. -
Added
std/strbasicsfor high performance string operations. Addedstrip,setSlice,add(a: var string, b: openArray[char]). -
std/optionschanged$some(3)to"some(3)"instead of"Some(3)"and$none(int)to"none(int)"instead of"None[int]". -
Added
algorithm.merge. -
Added
std/jsfetchmodule Fetch wrapper for JavaScript target. -
Added
std/jsheadersmodule Headers wrapper for JavaScript target. -
Added
std/jsformdatamodule FormData wrapper for JavaScript target. -
system.addEscapedCharnow renders\ras\rinstead of\c, to be compatible with most other languages. -
Removed support for named procs in
sugar.=>. -
Added
jscore.debuggerto call any available debugging functionality, such as breakpoints.. -
Added
std/channels. -
Added
htmlgen.portalfor making "SPA style" pages using HTML only. -
std/times: AddedZZZandZZZZpatterns totimes.nimDateTimeparsing, to match time zone offsets without colons, e.g.UTC+7 -> +0700.Added
dateTimeand deprecatedinitDateTime. -
Added
jsconsole.dir,jsconsole.dirxml,jsconsole.timeStamp. -
Added dollar
$andlenforjsre.RegExp. -
Added
std/tasks. -
Added
hasDataBufferedtoasyncnet. -
Added
std/tempfiles. -
Added
genasts.genAstthat avoids the problems inherent withquote doand can be used as a replacement. -
Added
copyWithinforseqandarrayfor JavaScript targets. -
Fixed premature garbage collection in asyncdispatch, when a stack trace override is in place.
-
Added setCurrentException for JS backend.
-
Added
dom.scrollIntoViewproc with options -
Added
dom.setInterval,dom.clearIntervaloverloads. -
Allow reading parameters when compiling for Nintendo Switch.
-
Deprecated
sequtils.deleteand added an overload taking aSlicethat raises a defect if the slice is out of bounds, likewise withstrutils.delete.
Language changes
-
nimscriptnow handlesexcept Exception as e. -
The
cstringdoesn't support[]=operator in JS backend. -
nil dereference is not allowed at compile time.
cast[ptr int](nil)[]is rejected at compile time. -
os.copyFileis now 2.5x faster on OSX, by usingcopyfilefromcopyfile.h; use-d:nimLegacyCopyFilefor OSX < 10.5. -
The required name of case statement macros for the experimental
caseStmtMacrosfeature has changed frommatchto`case`. -
typedesc[Foo]now renders as such instead oftype Fooin compiler messages. -
The unary minus in
-1is now part of the integer literal, it is now parsed as a single token. This implies that edge cases like-128'i8finally work correctly. -
Custom numeric literals (e.g.
-128'bignum) are now supported. -
Tuple expressions are now parsed consistently as
nnkTupleConstrnode. Will affect macros expecting nodes to be ofnnkPar. -
nim enow accepts arbitrary file extensions for the nimscript file, although.nimsis still the preferred extension in general. -
Added
iterable[T]type class to match called iterators, which enables writing:template fn(a: iterable)instead oftemplate fn(a: untyped) -
A new import syntax
import foo {.all.}now allows to import all symbols (public or private) fromfoo. It works in combination with all pre-existing import features. This reduces or eliminates the need for workarounds such as usinginclude(which has known issues) when you need a private symbol for testing or making some internal APIs public just because another internal module needs those. It also helps mitigate the lack of cyclic imports in some cases. -
Added a new module
std/importutils, and an APIprivateAccess, which allows access to private fields for an object type in the current scope. -
typeof(voidStmt)now works and returnsvoid. -
The
gc:orcalgorithm was refined so that custom container types can participate in the cycle collection process. -
On embedded devices
malloccan now be used instead ofmmapvia-d:nimAllocPagesViaMalloc. This is only supported for--gc:orcor--gc:arc.
Compiler changes
-
Added
--declaredLocsto show symbol declaration location in messages. -
You can now enable/disable VM tracing in user code via
vmutils.vmTrace. -
Deprecated
TaintedStringand--taintmode. -
Deprecated
--nilseqswhich is now a noop. -
Added
--spellSuggestto show spelling suggestions on typos. -
Added
--filenames:abs|canonical|legacyRelProjwhich replaces --listFullPaths:on|off -
Added
--processing:dots|filenames|offwhich customizeshintProcessing -
Added
--unitsep:on|offto control whether to add ASCII unit separator\31before a newline for every generated message (potentially multiline), so tooling can tell when messages start and end. -
Source+Edit links now appear on top of every docgen'd page when
nim doc --git.url:url ...is given. -
Added
nim --eval:cmdto evaluate a command directly, seenim --help. -
VM now supports
addr(mystring[ind])(index + index assignment) -
Added
--hintAsErrorwith similar semantics as--warningAsError. -
TLS: OSX now uses native TLS (
--tlsEmulation:off), TLS now works with importcpp non-POD types, such types must use.cppNonPodand--tlsEmulation:offshould be used. -
Now array literals(JS backend) uses JS typed arrays when the corresponding js typed array exists, for example
[byte(1), 2, 3]generatesnew Uint8Array([1, 2, 3]). -
docgen: rst files can now use single backticks instead of double backticks and correctly render in both rst2html (as before) as well as common tools rendering rst directly (e.g. github), by adding:
default-role:: codedirective inside the rst file, which is now handled by rst2html. -
Added
-d:nimStrictModein CI in several places to ensure code doesn't have certain hints/warnings -
Added
then,catchtoasyncjs, for now hidden behind-d:nimExperimentalAsyncjsThen. -
--newruntimeand--refchecksare deprecated. -
Added
unsafeIsolateandextracttostd/isolation. -
--hint:CCnow goes to stderr (like all other hints) instead of stdout. -
--hint:all:on|offis now supported to select or deselect all hints; it differs from--hints:on|offwhich acts as a (reversible) gate. Likewise with--warning:all:on|off. -
json build instructions are now generated in
$nimcache/outFileBasename.jsoninstead of$nimcache/projectName.json. This allows avoiding recompiling a given project compiled with different options if the output file differs. -
--usenimcache(implied bynim r main) now generates an output file that includes a hash of some of the compilation options, which allows caching generated binaries: nim r main # recompiles nim r -d:foo main # recompiles nim r main # uses cached binary nim r main arg1 arg2 # ditto (runtime arguments are irrelevant) -
nim rnow supports cross compilation from unix to windows when specifying-d:mingwby using wine, e.g.:nim r --eval:'import os; echo "a" / "b"'printsa\b -
nimcan compile version 1.4.0 as follows:nim c --lib:lib --stylecheck:off -d:nimVersion140 compiler/nim.-d:nimVersion140is not needed for bootstrapping, only for building 1.4.0 from devel. -
The style checking of the compiler now supports a
--styleCheck:usagesswitch. This switch enforces that every symbol is written as it was declared, not enforcing the official Nim style guide. To be enabled, this has to be combined either with--styleCheck:erroror--styleCheck:hint.
Tool changes
-
Latex doc generation is revised: output
.texfiles should be compiled byxelatex(not bypdflatexas before). Now default Latex settings provide support for Unicode and do better job for avoiding margin overflows. -
Implemented
doc2texcompiler command which converts documentation in.nimfiles to Latex. -
The rst parser now supports markdown table syntax. Known limitations:
- cell alignment is not supported, i.e. alignment annotations in a delimiter
row (
:---,:--:,---:) are ignored, - every table row must start with
|, e.g.| cell 1 | cell 2 |.
- cell alignment is not supported, i.e. alignment annotations in a delimiter
row (
-
fusionis now un-bundled from nim,./koch fusionwill install it via nimble at a fixed hash. -
testament: added
nimoutFull: boolspec to compare full output of compiler instead of a subset.