Nim

home https://nim-lang.org/
source https://github.com/nim-lang/Nim
doc https://nim-lang.org/docs/manual.html
doc https://nim-lang.github.io/Nim/
wiki https://en.wikipedia.org/wiki/Nim_(programming_language)
exercises https://github.com/sergiotapia/nimlings

Language

Types

name instance type
tuple (a: 1, b: 2) tuple[a: T, b: T]
set {1,2,3} set[T]
array ["foo","bar"] array[N,T]
bitset {'a'..'b'} bitset[T]
seq(uence) @[], newSeq[char](10) seq[T]
hashset toSet([]) HashSet[T]
orderedset   OrderedSet[]
channel   Channel[T]
enum Colors.Red type Colors = enum Red = 0xFF000
object Name(a: "foo")  
ref object Name(a: "foo")  
thread createThread(thread, fn, arg) Thread[T]
table initTable[T,T]() toTable[T,T]({})  
  initCountTable[T] toCountTable({})  
  toOrderedTable({})  

Operators

<c> description
$a returns string version of a
& sequtils: seq/string concatenation
.. iterator?
`/` returns a floating-point result
div returns a integer division result
%* json: used to create JSON objects
"" % [] strutils: format string
fmt"" strformat: interpolate raw string with {variable}
&"" strformat: interpolate non-raw string with {variable}
!$ hashes: finalizes a hash, ensuring is not repeated
@ sequtils: array/string -> sequences
in sequtils: check item in container
notin sequtils: check item NOT in container

pragmas

{. noSideEffect .} proc ensures that there are no side effects
{. async .} proc makes the proc async
{. borrow .} proc bring proc from original type
{. thread .} proc marks it to be used for threads
{. base .} method  
{. pure .} enum requires all ambiguos references to be qualified

stdlib modules

Pure Libraries

  • do NOT depend on any external *.dll or *.so binary
Algorithms
algorithm some common generic algorithms like sort or binary search.
enumutils adds functionality for the built-in enum type.
sequtils operations for the built-in seq type which were inspired by functional programming languages.
setutils adds functionality for the built-in set type.
Automatic imports
  description
system Basic procs and operators that every program needs.
  It also provides IO facilities for reading and writing text and binary files.
  It is imported implicitly by the compiler.
  Do not import it directly. It relies on compiler magic to work.
threads Basic Nim thread support. Note: This is part of the system module.
  Do not import it explicitly. Enabled with –threads:on.
channels_builtin Nim message passing support for threads.
  Note: This is part of the system module.
  Do not import it explicitly. Enabled with –threads:on.
Core
atomics Types and operations for atomic operations and lockless algorithms.
bitops Provides a series of low-level methods for bit manipulation.
cpuinfo procs to determine the number of CPUs / cores.
endians contains helpers that deal with different byte orders.
lenientops Provides binary operators for mixed integer/float expressions for convenience.
locks Locks and condition variables for Nim.
macrocache Provides an API for macros to collect compile-time information across modules.
macros Contains the AST API and documentation of Nim for writing macros.
rlocks Reentrant locks for Nim.
typeinfo Provides (unsafe) access to Nim's run-time type information.
typetraits defines compile-time reflection procs for working with types.
volatile contains code for generating volatile loads and stores, which are useful in embedded and systems programming.
Collections
critbits a crit bit tree which is an efficient container for a sorted set of strings, or a sorted mapping of strings.
deques Implementation of a double-ended queue. The underlying implementation uses a seq.
heapqueue Implementation of a binary heap data structure that can be used as a priority queue.
intsets Efficient implementation of a set of ints as a sparse bit set.
lists Nim linked list support. Contains singly and doubly linked lists and circular lists ("rings").
options The option type encapsulates an optional value.
packedsets Efficient implementation of a set of ordinals as a sparse bit set.
sets Nim hash set support.
sharedlist Nim shared linked list support. Contains a shared singly-linked list.
sharedtables Nim shared hash table support. Contains shared tables.
tables Nim hash table support. Contains tables, ordered tables, and count tables.
Docutils
packages/docutils/highlite Source highlighter for programming or markup languages. Currently, only a few languages are supported, other languages may be added. The interface supports one language nested in another.
packages/docutils/rst a reStructuredText parser. A large subset is implemented. Some features of the markdown wiki syntax are also supported.
packages/docutils/rstast an AST for the reStructuredText parser.
packages/docutils/rstgen a generator of HTML/Latex from reStructuredText.
Generic Operating System Services
  description
distros the basics for OS distribution ("distro") detection and the OS's native package manager.
  Its primary purpose is to produce output for Nimble packages,
  but it also contains the widely used Distribution enum that is useful for writing platform-specific code.
  See packaging for hints on distributing Nim using OS packages.
dynlib the ability to access symbols from shared libraries.
marshal Contains procs for serialization and deserialization of arbitrary Nim data structures.
memfiles provides support for memory-mapped files (Posix's mmap) on the different operating systems.
os Basic OS facilities like retrieving environment variables,
  reading command line arguments, working with directories, running shell commands, etc.
osproc Module for process communication beyond os.execShellCmd.
streams provides a stream interface and two implementations thereof:
  the FileStream and the StringStream which implement the stream interface for Nim file objects (File) and strings.
  Other modules may provide other implementations for this standard stream interface.
terminal contains a few procedures to control the terminal (also called console).
  The implementation simply uses ANSI escape sequences and does not depend on any other module.
Generators
htmlgen a simple XML and HTML code generator. Each commonly used HTML tag has a corresponding macro that generates a string with its HTML representation.
Hashing
base64 a Base64 encoder and decoder.
hashes efficient computations of hash values for diverse Nim types.
md5 the MD5 checksum algorithm.
oids An OID is a global ID that consists of a timestamp, a unique counter, and a random value. This combination should suffice to produce a globally distributed unique ID. This implementation was extracted from the MongoDB interface and it thus binary compatible with a MongoDB OID.
sha1 a sha1 encoder and decoder.
Internet Protocols and Support
asyncdispatch an asynchronous dispatcher for IO operations.
asyncfile asynchronous file reading and writing using asyncdispatch.
asyncftpclient an asynchronous FTP client using the asyncnet module.
asynchttpserver an asynchronous HTTP server using the asyncnet module.
asyncnet asynchronous sockets based on the asyncdispatch module.
asyncstreams provides FutureStream - a future that acts as a queue.
cgi helpers for CGI applications.
cookies contains helper procs for parsing and generating cookies.
httpclient a simple HTTP client which supports both synchronous and asynchronous retrieval of web pages.
mimetypes a mimetypes database.
nativesockets a low-level sockets API.
net a high-level sockets API. It replaces the sockets module.
selectors a selector API with backends specific to each OS. Currently, epoll on Linux and select on other operating systems.
smtp a simple SMTP client.
uri provides functions for working with URIs.
Math libraries
complex complex numbers and relevant mathematical operations.
fenv Floating-point environment. Handling of floating-point rounding and exceptions (overflow, zero-divide, etc.).
math Mathematical operations like cosine, square root.
random Fast and tiny random number generator.
rationals rational numbers and relevant mathematical operations.
stats Statistical analysis.
sums Accurate summation functions.
sysrand Cryptographically secure pseudorandom number generator.
Miscellaneous
browsers procs for opening URLs with the user's default browser.
colors color handling for Nim.
coro experimental coroutines in Nim.
enumerate enumerate syntactic sugar based on Nim's macro system.
logging a simple logger.
segfaults Turns access violations or segfaults into a NilAccessDefect exception.
sugar nice syntactic sugar based on Nim's macro system.
unittest a Unit testing DSL.
varints Decode variable-length integers that are compatible with SQLite.
with the with macro for easy function chaining.
Modules for the JS backend
asyncjs Types and macros for writing asynchronous procedures in JavaScript.
dom Declaration of the Document Object Model for the JS backend.
jsbigints Arbitrary precision integers.
jsconsole Wrapper for the console object.
jscore The wrapper of core JavaScript functions. For most purposes, you should be using the math, json, and times stdlib modules instead of this module.
jsffi Types and macros for easier interaction with JavaScript.
Parsers
htmlparser parses an HTML document and creates its XML tree representation.
json High-performance JSON parser.
jsonutils a hookable (de)serialization for arbitrary types.
lexbase This is a low-level module that implements an extremely efficient buffering scheme for lexers and parsers. This is used by the diverse parsing modules.
parsecfg The parsecfg module implements a high-performance configuration file parser. The configuration file's syntax is similar to the Windows .ini format, but much more powerful, as it is not a line based parser. String literals, raw string literals, and triple quote string literals are supported as in the Nim programming language.
parsecsv The parsecsv module implements a simple high-performance CSV parser.
parsejson a JSON parser. It is used and exported by the json module, but can also be used in its own right.
parseopt The parseopt module implements a command line option parser.
parsesql The parsesql module implements a simple high-performance SQL parser.
parsexml The parsexml module implements a simple high performance XML/HTML parser. The only encoding that is supported is UTF-8. The parser has been designed to be somewhat error-correcting, so that even some "wild HTML" found on the web can be parsed with it.
String handling
cstrutils Utilities for cstring handling.
editdistance contains an algorithm to compute the edit distance between two Unicode strings.
encodings Converts between different character encodings. On UNIX, this uses the iconv library, on Windows the Windows API.
parseutils contains helpers for parsing tokens, numbers, identifiers, etc.
pegs contains procedures and operators for handling PEGs.
punycode a representation of Unicode with the limited ASCII character subset.
ropes contains support for a rope data type. Ropes can represent very long strings efficiently;
  in particular, concatenation is done in O(1) instead of O(n).
strbasics provides some high performance string operations.
strformat Macro based standard string interpolation/formatting. Inspired by Python's f-strings.
strmisc contains uncommon string handling operations that do not fit with the commonly used operations in strutils.
strscans contains a scanf macro for convenient parsing of mini languages.
strtabs implements an efficient hash table that is a mapping from strings to strings.
  Supports a case-sensitive, case-insensitive and style-insensitive modes.
strutils contains common string handling operations like changing case, splitting, searching, replacing.
unicode provides support to handle the Unicode UTF-8 encoding.
unidecode It provides a single proc that does Unicode to ASCII transliterations. Based on Python's Unidecode module.
wordwrap contains an algorithm to wordwrap a Unicode string.
Time handling
monotimes implements monotonic timestamps.
times contains support for working with time.
Threading
threadpool Nim's spawn.
XML Processing
xmltree A simple XML tree. More efficient and simpler than the DOM. It also contains a macro for XML/HTML code generation.
xmlparser parses an XML document and creates its XML tree representation.

Impure Libraries

  • depend on .so or .dll.
Regular expressions
re This module contains procedures and operators for handling regular expressions. The current implementation uses PCRE.
Database support
db_postgres A higher level PostgreSQL database wrapper. The same interface is implemented for other databases too.
db_mysql A higher level MySQL database wrapper. The same interface is implemented for other databases too.
db_sqlite A higher level SQLite database wrapper. The same interface is implemented for other databases too.
Generic Operating System Services
rdstdin This module contains code for reading from stdin.

Wrappers

  • a very low-level interface to a C library
Database support
postgres Contains a wrapper for the PostgreSQL API.
mysql Contains a wrapper for the mySQL API.
sqlite3 Contains a wrapper for the SQLite 3 API.
odbcsql interface to the ODBC driver.
Regular expressions
pcre Wrapper for the PCRE library.
UNIX specific
posix Contains a wrapper for the POSIX standard.
posix_utils Contains helpers for the POSIX standard or specialized for Linux and BSDs.
Windows-specific
winlean Contains a wrapper for a small subset of the Win32 API.
registry Windows registry support.

Codebases

Libraries


Created: 2022-12-23

Updated: 2024-11-16

Back