Merge branch 'devel' into pr-remove-encode-overload

This commit is contained in:
AmjadHD
2022-09-22 21:41:52 +01:00
12 changed files with 453 additions and 287 deletions

View File

@@ -65,6 +65,8 @@
- `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.
- `std/oids` now uses `int64` to store time internally (before it was int32), the length of
the string form of `Oid` changes from 24 to 32.
[//]: # "Additions:"
- Added ISO 8601 week date utilities in `times`:

View File

@@ -232,7 +232,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
@@ -304,6 +304,12 @@ type
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]

View File

@@ -398,8 +398,12 @@ proc semObjConstr(c: PContext, n: PNode, flags: TExprFlags; expectedType: PType
# multiple times as long as they don't have closures.
result.typ.flags.incl tfHasOwned
if t.kind != tyObject:
return localErrorNode(c, result,
"object constructor needs an object type".dup(addDeclaredLoc(c.config, t)))
return localErrorNode(c, result, if t.kind != tyGenericBody:
"object constructor needs an object type".dup(addDeclaredLoc(c.config, t))
else: "cannot instantiate: '" &
typeToString(t, preferDesc) &
"'; the object's generic parameters cannot be inferred and must be explicitly given"
)
# Check if the object is fully initialized by recursively testing each
# field (if this is a case object, initialized fields in two different

View File

@@ -1425,6 +1425,7 @@ proc typeSectionRightSidePass(c: PContext, n: PNode) =
excl(objTy.flags, tfFinal)
let obj = newSym(skType, getIdent(c.cache, s.name.s & ":ObjectType"),
nextSymId c.idgen, getCurrOwner(c), s.info)
obj.flags.incl sfGeneratedType
let symNode = newSymNode(obj)
obj.ast = a.shallowCopy
case a[0].kind

View File

@@ -499,17 +499,20 @@ proc propagateFieldFlags(t: PType, n: PNode) =
proc replaceTypeVarsTAux(cl: var TReplTypeVars, t: PType): PType =
template bailout =
if cl.recursionLimit > 100:
# bail out, see bug #2509. But note this caching is in general wrong,
# look at this example where TwoVectors should not share the generic
# instantiations (bug #3112):
# type
# Vector[N: static[int]] = array[N, float64]
# TwoVectors[Na, Nb: static[int]] = (Vector[Na], Vector[Nb])
result = PType(idTableGet(cl.localCache, t))
if result != nil: return result
inc cl.recursionLimit
if t.sym != nil and sfGeneratedType in t.sym.flags:
# Only consider the recursion limit if the symbol is a type with generic
# parameters that have not been explicitly supplied, typechecking should
# terminate when generic parameters are explicitly supplied.
if cl.recursionLimit > 100:
# bail out, see bug #2509. But note this caching is in general wrong,
# look at this example where TwoVectors should not share the generic
# instantiations (bug #3112):
# type
# Vector[N: static[int]] = array[N, float64]
# TwoVectors[Na, Nb: static[int]] = (Vector[Na], Vector[Nb])
result = PType(idTableGet(cl.localCache, t))
if result != nil: return result
inc cl.recursionLimit
result = t
if t == nil: return

View File

@@ -20,16 +20,6 @@ from input ``.nim`` files and projects, as well as HTML and LaTeX from input RST
dependencies (`import`), any top-level documentation comments (`##`), and
exported symbols (`*`), including procedures, types, and variables.
=================== ====================== ============ ==============
command runs on... input format output format
=================== ====================== ============ ==============
`nim doc`:cmd: documentation comments ``.nim`` ``.html`` HTML
`nim doc2tex`:cmd: ″ ″ ``.tex`` LaTeX
`nim jsondoc`:cmd: ″ ″ ``.json`` JSON
`nim rst2html`:cmd: standalone rst files ``.rst`` ``.html`` HTML
`nim rst2tex`:cmd: ″ ″ ``.tex`` LaTeX
=================== ====================== ============ ==============
Quick start
-----------
@@ -490,18 +480,8 @@ highlighting with the ``.. code-block:: nim`` prefix. ``code-block`` also
supports highlighting of a few other languages supported by the
[packages/docutils/highlite module](highlite.html).
Usage:
```cmd
nim rst2html docgen.rst
```
Output::
You're reading it!
The `rst2tex`:option: command is invoked identically to `rst2html`:option:,
but outputs a ``.tex`` file instead of ``.html``.
See [Markdown and RST markup languages](markdown_rst.html) for
usage of those commands.
HTML anchor generation
======================
@@ -628,10 +608,9 @@ Additional resources
* [Nim Compiler User Guide](nimc.html#compiler-usage-commandminusline-switches)
* Documentation for [rst module](rst.html) -- Nim RST/Markdown parser.
* [RST Quick Reference](
http://docutils.sourceforge.net/docs/user/rst/quickref.html)
* already mentioned documentation for
[Markdown and RST markup languages](markdown_rst.html), which also
contains the list of implemented features of these markup languages.
The output for HTML and LaTeX comes from the ``config/nimdoc.cfg`` and
``config/nimdoc.tex.cfg`` configuration files. You can add and modify these

258
doc/markdown_rst.md Normal file
View File

@@ -0,0 +1,258 @@
==========================================
Nim-flavored Markdown and reStructuredText
==========================================
:Author: Andrey Makarov
:Version: |nimversion|
.. default-role:: code
.. include:: rstcommon.rst
.. contents::
Both `Markdown`:idx: (md) and `reStructuredText`:idx: (RST) are markup
languages whose goal is to typeset texts with complex structure,
formatting and references using simple plaintext representation.
Command line usage
==================
Usage (to convert Markdown into HTML):
```cmd
nim md2html markdown_rst.md
```
Output::
You're reading it!
The `md2tex`:option: command is invoked identically to `md2html`:option:,
but outputs a ``.tex`` file instead of ``.html``.
These tools embedded into Nim compiler; the compiler can output
the result to HTML \[#html] or Latex \[#latex].
\[#html] commands `nim doc`:cmd: for ``*.nim`` files and
`nim rst2html`:cmd: for ``*.rst`` files
\[#latex] commands `nim doc2tex`:cmd: for ``*.nim`` and
`nim rst2tex`:cmd: for ``*.rst``.
Full list of supported commands:
=================== ====================== ============ ==============
command runs on... input format output format
=================== ====================== ============ ==============
`nim md2html`:cmd: standalone md files ``.md`` ``.html`` HTML
`nim md2tex`:cmd: same same ``.tex`` LaTeX
`nim rst2html`:cmd: standalone rst files ``.rst`` ``.html`` HTML
`nim rst2tex`:cmd: same same ``.tex`` LaTeX
`nim doc`:cmd: documentation comments ``.nim`` ``.html`` HTML
`nim doc2tex`:cmd: same same ``.tex`` LaTeX
`nim jsondoc`:cmd: same same ``.json`` JSON
=================== ====================== ============ ==============
Basic markup
============
If you are new to Markdown/RST please consider reading the following:
1) [Markdown Basic Syntax]
2) a long specification of Markdown: [CommonMark Spec]
3) a short [quick introduction] to RST
4) an [RST reference]: a comprehensive cheatsheet for RST
5) a more formal 50-page [RST specification].
Features
--------
A large subset is implemented with some [limitations] and
[additional Nim-specific features].
Supported standard RST features:
* body elements
+ sections
+ transitions
+ paragraphs
+ bullet lists using \+, \*, \-
+ enumerated lists using arabic numerals or alphabet
characters: 1. ... 2. ... *or* a. ... b. ... *or* A. ... B. ...
+ footnotes (including manually numbered, auto-numbered, auto-numbered
with label, and auto-symbol footnotes) and citations
+ definition lists
+ field lists
+ option lists
+ indented literal blocks
+ quoted literal blocks
+ line blocks
+ simple tables
+ directives (see official documentation in [RST directives list]):
- ``image``, ``figure`` for including images and videos
- ``code``
- ``contents`` (table of contents), ``container``, ``raw``
- ``include``
- admonitions: "attention", "caution", "danger", "error", "hint",
"important", "note", "tip", "warning", "admonition"
- substitution definitions: `replace` and `image`
+ comments
* inline markup
+ *emphasis*, **strong emphasis**,
``inline literals``, hyperlink references (including embedded URI),
substitution references, standalone hyperlinks,
internal links (inline and outline)
+ \`interpreted text\` with roles ``:literal:``, ``:strong:``,
``emphasis``, ``:sub:``/``:subscript:``, ``:sup:``/``:superscript:``
(see [RST roles list] for description).
+ inline internal targets
Additional Nim-specific features
--------------------------------
* directives: ``code-block`` \[cmp:Sphinx], ``title``,
``index`` \[cmp:Sphinx]
* predefined roles
- ``:nim:`` (default), ``:c:`` (C programming language),
``:python:``, ``:yaml:``, ``:java:``, ``:cpp:`` (C++), ``:csharp`` (C#).
That is every language that [highlite](highlite.html) supports.
They turn on appropriate syntax highlighting in inline code.
.. Note:: default role for Nim files is ``:nim:``,
for ``*.rst`` it's currently ``:literal:``.
- generic command line highlighting roles:
- ``:cmd:`` for commands and common shells syntax
- ``:console:`` the same for interactive sessions
(commands should be prepended by ``$``)
- ``:program:`` for executable names \[cmp:Sphinx]
(one can just use ``:cmd:`` on single word)
- ``:option:`` for command line options \[cmp:Sphinx]
- ``:tok:``, a role for highlighting of programming language tokens
* ***triple emphasis*** (bold and italic) using \*\*\*
* ``:idx:`` role for \`interpreted text\` to include the link to this
text into an index (example: [Nim index]).
* double slash `//` in option lists serves as a prefix for any option that
starts from a word (without any leading symbols like `-`, `--`, `/`)::
//compile compile the project
//doc generate documentation
Here the dummy `//` will disappear, while options `compile`:option:
and `doc`:option: will be left in the final document.
\[cmp:Sphinx] similar but different from the directives of
Python [Sphinx directives] and [Sphinx roles] extensions
Extra features
--------------
Optional additional features, by default turned on:
* emoji / smiley symbols
* Markdown tables
* Markdown code blocks. For them the same additional arguments as for RST
code blocks can be provided (e.g. `test` or `number-lines`) but with
a one-line syntax like this::
```nim test number-lines=10
echo "ok"
```
* Markdown links
* Markdown headlines
* Markdown block quotes
* using ``1`` as auto-enumerator in enumerated lists like RST ``#``
(auto-enumerator ``1`` can not be used with ``#`` in the same list)
.. Note:: By default Nim has ``roSupportMarkdown`` and
``roSupportRawDirective`` turned **on**.
.. warning:: Using Nim-specific features can cause other RST implementations
to fail on your document.
Idiosyncrasies
--------------
Currently we do **not** aim at 100% Markdown or RST compatibility in inline
markup recognition rules because that would provide very little user value.
This parser has 2 modes for inline markup:
1) Markdown-like mode which is enabled by `roPreferMarkdown` option
(turned **on** by default).
.. Note:: RST features like directives are still turned **on**
2) Compatibility mode which is RST rules.
.. Note:: in both modes the parser interpretes text between single
backticks (code) identically:
backslash does not escape; the only exception: ``\`` folowed by `
does escape so that we can always input a single backtick ` in
inline code. However that makes impossible to input code with
``\`` at the end in *single* backticks, one must use *double*
backticks::
`\` -- WRONG
``\`` -- GOOD
So single backticks can always be input: `\`` will turn to ` code
.. Attention::
We don't support some obviously poor design choices of Markdown (or RST).
- no support for the rule of 2 spaces causing a line break in Markdown
(use RST "line blocks" syntax for making line breaks)
- interpretation of Markdown block quotes is also slightly different,
e.g. case
::
>>> foo
> bar
>>baz
is a single 3rd-level quote `foo bar baz` in original Markdown, while
in Nim we naturally see it as 3rd-level quote `foo` + 1st level `bar` +
2nd level `baz`:
>>> foo
> bar
>>baz
Limitations
-----------
* no Unicode support in character width calculations
* body elements
- no roman numerals in enumerated lists
- no doctest blocks
- no grid tables
- some directives are missing (check official [RST directives list]):
``parsed-literal``, ``sidebar``, ``topic``, ``math``, ``rubric``,
``epigraph``, ``highlights``, ``pull-quote``, ``compound``,
``table``, ``csv-table``, ``list-table``, ``section-numbering``,
``header``, ``footer``, ``meta``, ``class``
- no ``role`` directives and no custom interpreted text roles
- some standard roles are not supported (check [RST roles list])
- no generic admonition support
* inline markup
- no simple-inline-markup
- no embedded aliases
Additional resources
--------------------
* See [Nim DocGen Tools Guide](docgen.html) for the details about
`nim doc`:cmd: command and idiosyncrasies of documentation markup in
``.nim`` files and Nim programming language projects.
* See also documentation for [rst module](rst.html) -- Nim RST/Markdown parser.
.. _Markdown Basic Syntax: https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax
.. _CommonMark Spec: https://spec.commonmark.org/0.30
.. _quick introduction: https://docutils.sourceforge.io/docs/user/rst/quickstart.html
.. _RST reference: https://docutils.sourceforge.io/docs/user/rst/quickref.html
.. _RST specification: https://docutils.sourceforge.io/docs/ref/rst/restructuredtext.html
.. _RST directives list: https://docutils.sourceforge.io/docs/ref/rst/directives.html
.. _RST roles list: https://docutils.sourceforge.io/docs/ref/rst/roles.html
.. _Nim index: https://nim-lang.org/docs/theindex.html
.. _Sphinx directives: https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html
.. _Sphinx roles: https://www.sphinx-doc.org/en/master/usage/restructuredtext/roles.html

View File

@@ -7,231 +7,18 @@
# distribution, for details about the copyright.
#
## ==================================
## packages/docutils/rst
## ==================================
##
## ------------------------------------------
## Nim-flavored reStructuredText and Markdown
## ------------------------------------------
##
## This module implements a `reStructuredText`:idx: (RST) and
## `Markdown`:idx: parser.
## A large subset is implemented with some limitations_ and
## `Nim-specific features`_.
## Both Markdown and RST are mark-up languages whose goal is to
## typeset texts with complex structure, formatting and references
## using simple plaintext representation.
## User's manual on supported markup syntax and command line usage can be
## found in [Nim-flavored Markdown and reStructuredText](markdown_rst.html).
##
## This module is also embedded into Nim compiler; the compiler can output
## the result to HTML \[#html] or Latex \[#latex].
## * See also [Nim DocGen Tools Guide](docgen.html) for handling of
## ``.nim`` files.
## * See also [packages/docutils/rstgen module](rstgen.html) to know how to
## generate HTML or Latex strings (for embedding them into custom documents).
##
## \[#html] commands `nim doc`:cmd: for ``*.nim`` files and
## `nim rst2html`:cmd: for ``*.rst`` files
##
## \[#latex] commands `nim doc2tex`:cmd: for ``*.nim`` and
## `nim rst2tex`:cmd: for ``*.rst``.
##
## If you are new to Markdown/RST please consider reading the following:
##
## 1) `Markdown Basic Syntax`_
## 2) a long specification of Markdown: `CommonMark Spec`_
## 3) a short `quick introduction`_ to RST
## 4) an `RST reference`_: a comprehensive cheatsheet for RST
## 5) a more formal 50-page `RST specification`_.
##
## Features
## --------
##
## Supported standard RST features:
##
## * body elements
## + sections
## + transitions
## + paragraphs
## + bullet lists using \+, \*, \-
## + enumerated lists using arabic numerals or alphabet
## characters: 1. ... 2. ... *or* a. ... b. ... *or* A. ... B. ...
## + footnotes (including manually numbered, auto-numbered, auto-numbered
## with label, and auto-symbol footnotes) and citations
## + definition lists
## + field lists
## + option lists
## + indented literal blocks
## + quoted literal blocks
## + line blocks
## + simple tables
## + directives (see official documentation in `RST directives list`_):
## - ``image``, ``figure`` for including images and videos
## - ``code``
## - ``contents`` (table of contents), ``container``, ``raw``
## - ``include``
## - admonitions: "attention", "caution", "danger", "error", "hint",
## "important", "note", "tip", "warning", "admonition"
## - substitution definitions: `replace` and `image`
## + comments
## * inline markup
## + *emphasis*, **strong emphasis**,
## ``inline literals``, hyperlink references (including embedded URI),
## substitution references, standalone hyperlinks,
## internal links (inline and outline)
## + \`interpreted text\` with roles ``:literal:``, ``:strong:``,
## ``emphasis``, ``:sub:``/``:subscript:``, ``:sup:``/``:superscript:``
## (see `RST roles list`_ for description).
## + inline internal targets
##
## .. _`Nim-specific features`:
##
## Additional Nim-specific features:
##
## * directives: ``code-block`` \[cmp:Sphinx], ``title``,
## ``index`` \[cmp:Sphinx]
## * predefined roles
## - ``:nim:`` (default), ``:c:`` (C programming language),
## ``:python:``, ``:yaml:``, ``:java:``, ``:cpp:`` (C++), ``:csharp`` (C#).
## That is every language that `highlite <highlite.html>`_ supports.
## They turn on appropriate syntax highlighting in inline code.
##
## .. Note:: default role for Nim files is ``:nim:``,
## for ``*.rst`` it's currently ``:literal:``.
##
## - generic command line highlighting roles:
## - ``:cmd:`` for commands and common shells syntax
## - ``:console:`` the same for interactive sessions
## (commands should be prepended by ``$``)
## - ``:program:`` for executable names \[cmp:Sphinx]
## (one can just use ``:cmd:`` on single word)
## - ``:option:`` for command line options \[cmp:Sphinx]
## - ``:tok:``, a role for highlighting of programming language tokens
## * ***triple emphasis*** (bold and italic) using \*\*\*
## * ``:idx:`` role for \`interpreted text\` to include the link to this
## text into an index (example: `Nim index`_).
## * double slash `//` in option lists serves as a prefix for any option that
## starts from a word (without any leading symbols like `-`, `--`, `/`)::
##
## //compile compile the project
## //doc generate documentation
##
## Here the dummy `//` will disappear, while options `compile`:option:
## and `doc`:option: will be left in the final document.
##
## \[cmp:Sphinx] similar but different from the directives of
## Python `Sphinx directives`_ and `Sphinx roles`_ extensions
##
## .. _`extra features`:
##
## Optional additional features, turned on by ``options: RstParseOption`` in
## `proc rstParse`_:
##
## * emoji / smiley symbols
## * Markdown tables
## * Markdown code blocks. For them the same additional arguments as for RST
## code blocks can be provided (e.g. `test` or `number-lines`) but with
## a one-line syntax like this::
##
## ```nim test number-lines=10
## echo "ok"
## ```
## * Markdown links
## * Markdown headlines
## * Markdown block quotes
## * using ``1`` as auto-enumerator in enumerated lists like RST ``#``
## (auto-enumerator ``1`` can not be used with ``#`` in the same list)
##
## .. Note:: By default Nim has ``roSupportMarkdown`` and
## ``roSupportRawDirective`` turned **on**.
##
## .. warning:: Using Nim-specific features can cause other RST implementations
## to fail on your document.
##
## Idiosyncrasies
## --------------
##
## Currently we do **not** aim at 100% Markdown or RST compatibility in inline
## markup recognition rules because that would provide very little user value.
## This parser has 2 modes for inline markup:
##
## 1) Markdown-like mode which is enabled by `roPreferMarkdown` option
## (turned **on** by default).
##
## .. Note:: RST features like directives are still turned **on**
##
## 2) Compatibility mode which is RST rules.
##
## .. Note:: in both modes the parser interpretes text between single
## backticks (code) identically:
## backslash does not escape; the only exception: ``\`` folowed by `
## does escape so that we can always input a single backtick ` in
## inline code. However that makes impossible to input code with
## ``\`` at the end in *single* backticks, one must use *double*
## backticks::
##
## `\` -- WRONG
## ``\`` -- GOOD
## So single backticks can always be input: `\`` will turn to ` code
##
## .. Attention::
## We don't support some obviously poor design choices of Markdown (or RST).
##
## - no support for the rule of 2 spaces causing a line break in Markdown
## (use RST "line blocks" syntax for making line breaks)
##
## - interpretation of Markdown block quotes is also slightly different,
## e.g. case
##
## ::
##
## >>> foo
## > bar
## >>baz
##
## is a single 3rd-level quote `foo bar baz` in original Markdown, while
## in Nim we naturally see it as 3rd-level quote `foo` + 1st level `bar` +
## 2nd level `baz`:
##
## >>> foo
## > bar
## >>baz
##
## Limitations
## -----------
##
## * no Unicode support in character width calculations
## * body elements
## - no roman numerals in enumerated lists
## - no doctest blocks
## - no grid tables
## - some directives are missing (check official `RST directives list`_):
## ``parsed-literal``, ``sidebar``, ``topic``, ``math``, ``rubric``,
## ``epigraph``, ``highlights``, ``pull-quote``, ``compound``,
## ``table``, ``csv-table``, ``list-table``, ``section-numbering``,
## ``header``, ``footer``, ``meta``, ``class``
## - no ``role`` directives and no custom interpreted text roles
## - some standard roles are not supported (check `RST roles list`_)
## - no generic admonition support
## * inline markup
## - no simple-inline-markup
## - no embedded aliases
##
## Usage
## -----
##
## See `Nim DocGen Tools Guide <docgen.html>`_ for the details about
## `nim doc`:cmd:, `nim rst2html`:cmd: and `nim rst2tex`:cmd: commands.
##
## See `packages/docutils/rstgen module <rstgen.html>`_ to know how to
## generate HTML or Latex strings to embed them into your documents.
##
## .. _Markdown Basic Syntax: https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax
## .. _CommonMark Spec: https://spec.commonmark.org/0.30
## .. _quick introduction: https://docutils.sourceforge.io/docs/user/rst/quickstart.html
## .. _RST reference: https://docutils.sourceforge.io/docs/user/rst/quickref.html
## .. _RST specification: https://docutils.sourceforge.io/docs/ref/rst/restructuredtext.html
## .. _RST directives list: https://docutils.sourceforge.io/docs/ref/rst/directives.html
## .. _RST roles list: https://docutils.sourceforge.io/docs/ref/rst/roles.html
## .. _Nim index: https://nim-lang.org/docs/theindex.html
## .. _Sphinx directives: https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html
## .. _Sphinx roles: https://www.sphinx-doc.org/en/master/usage/restructuredtext/roles.html
## Choice between Markdown and RST as well as optional additional features are
## turned on by passing ``options:`` [RstParseOptions] to [proc rstParse].
import
os, strutils, rstast, dochelpers, std/enumutils, algorithm, lists, sequtils,

View File

@@ -9,8 +9,7 @@
## Nim OID support. 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 is thus binary compatible with a MongoDB OID.
## produce a globally distributed unique ID.
##
## This implementation calls `initRand()` for the first call of
## `genOid`.
@@ -20,7 +19,7 @@ from std/private/decode_helpers import handleHexChar
type
Oid* = object ## An OID.
time: int32
time: int64
fuzz: int32
count: int32
@@ -44,37 +43,27 @@ proc parseOid*(str: cstring): Oid =
## Parses an OID.
var bytes = cast[cstring](addr(result.time))
var i = 0
while i < 12:
while i < 16:
bytes[i] = chr((hexbyte(str[2 * i]) shl 4) or hexbyte(str[2 * i + 1]))
inc(i)
template toStringImpl[T: string | cstring](result: var T, oid: Oid) =
## Stringifies `oid`.
proc `$`*(oid: Oid): string =
## Converts an OID to a string.
const hex = "0123456789abcdef"
const N = 24
when T is string:
result.setLen N
result.setLen 32
var o = oid
var bytes = cast[cstring](addr(o))
var i = 0
while i < 12:
while i < 16:
let b = bytes[i].ord
result[2 * i] = hex[(b and 0xF0) shr 4]
result[2 * i + 1] = hex[b and 0xF]
inc(i)
when T is cstring:
result[N] = '\0'
proc `$`*(oid: Oid): string =
## Converts an OID to a string.
toStringImpl(result, oid)
let
t = getTime().toUnix.int32
t = getTime().toUnix
var
seed = initRand(t)
@@ -84,24 +73,24 @@ let fuzz = cast[int32](seed.rand(high(int)))
template genOid(result: var Oid, incr: var int, fuzz: int32) =
var time = getTime().toUnix.int32
var time = getTime().toUnix
var i = cast[int32](atomicInc(incr))
bigEndian32(addr result.time, addr(time))
bigEndian64(addr result.time, addr(time))
result.fuzz = fuzz
bigEndian32(addr result.count, addr(i))
proc genOid*(): Oid =
## Generates a new OID.
runnableExamples:
doAssert ($genOid()).len == 24
doAssert ($genOid()).len == 32
runnableExamples("-r:off"):
echo $genOid() # for example, "5fc7f546ddbbc84800006aaf"
echo $genOid() # for example, "00000000632c452db08c3d19ee9073e5"
genOid(result, incr, fuzz)
proc generatedTime*(oid: Oid): Time =
## Returns the generated timestamp of the OID.
var tmp: int32
var tmp: int64
var dummy = oid.time
bigEndian32(addr(tmp), addr(dummy))
bigEndian64(addr(tmp), addr(dummy))
result = fromUnix(tmp)

View File

@@ -0,0 +1,5 @@
discard """
errormsg: "cannot instantiate: 'A[T]'; the object's generic parameters cannot be inferred and must be explicitly given"
"""
type A[T] = object
var a = A()

View File

@@ -0,0 +1,123 @@
discard """
action: "compile"
"""
# https://github.com/nim-lang/Nim/issues/20348
type
Payload[T] = object
payload: T
Carrier[T] = object
val: T
type
Payload0*[T] = object
payload: Payload[T]
Payload1*[T] = object
payload: Payload[T]
Payload2*[T] = object
payload: Payload[T]
Payload3*[T] = object
payload: Payload[T]
Payload4*[T] = object
payload: Payload[T]
Payload5*[T] = object
payload: Payload[T]
Payload6*[T] = object
payload: Payload[T]
Payload7*[T] = object
payload: Payload[T]
Payload8*[T] = object
payload: Payload[T]
Payload9*[T] = object
payload: Payload[T]
Payload10*[T] = object
payload: Payload[T]
Payload11*[T] = object
payload: Payload[T]
Payload12*[T] = object
payload: Payload[T]
Payload13*[T] = object
payload: Payload[T]
Payload14*[T] = object
payload: Payload[T]
Payload15*[T] = object
payload: Payload[T]
Payload16*[T] = object
payload: Payload[T]
Payload17*[T] = object
payload: Payload[T]
Payload18*[T] = object
payload: Payload[T]
Payload19*[T] = object
payload: Payload[T]
Payload20*[T] = object
payload: Payload[T]
Payload21*[T] = object
payload: Payload[T]
Payload22*[T] = object
payload: Payload[T]
Payload23*[T] = object
payload: Payload[T]
Payload24*[T] = object
payload: Payload[T]
Payload25*[T] = object
payload: Payload[T]
Payload26*[T] = object
payload: Payload[T]
Payload27*[T] = object
payload: Payload[T]
Payload28*[T] = object
payload: Payload[T]
Payload29*[T] = object
payload: Payload[T]
Payload30*[T] = object
payload: Payload[T]
Payload31*[T] = object
payload: Payload[T]
Payload32*[T] = object
payload: Payload[T]
Payload33*[T] = object
payload: Payload[T]
type
Carriers*[T] = object
c0*: Carrier[Payload0[T]]
c1*: Carrier[Payload1[T]]
c2*: Carrier[Payload2[T]]
c3*: Carrier[Payload3[T]]
c4*: Carrier[Payload4[T]]
c5*: Carrier[Payload5[T]]
c6*: Carrier[Payload6[T]]
c7*: Carrier[Payload7[T]]
c8*: Carrier[Payload8[T]]
c9*: Carrier[Payload9[T]]
c10*: Carrier[Payload10[T]]
c11*: Carrier[Payload11[T]]
c12*: Carrier[Payload12[T]]
c13*: Carrier[Payload13[T]]
c14*: Carrier[Payload14[T]]
c15*: Carrier[Payload15[T]]
c16*: Carrier[Payload16[T]]
c17*: Carrier[Payload17[T]]
c18*: Carrier[Payload18[T]]
c19*: Carrier[Payload19[T]]
c20*: Carrier[Payload20[T]]
c21*: Carrier[Payload21[T]]
c22*: Carrier[Payload22[T]]
c23*: Carrier[Payload23[T]]
c24*: Carrier[Payload24[T]]
c25*: Carrier[Payload25[T]]
c26*: Carrier[Payload26[T]]
c27*: Carrier[Payload27[T]]
c28*: Carrier[Payload28[T]]
c29*: Carrier[Payload29[T]]
c30*: Carrier[Payload30[T]]
c31*: Carrier[Payload31[T]]
c32*: Carrier[Payload32[T]]
c33*: Carrier[Payload33[T]]
var carriers : Carriers[int]
static:
assert $(typeof(carriers.c33.val)) == "Payload33[system.int]"

View File

@@ -1,6 +1,15 @@
discard """
matrix: "--mm:refc; --mm:orc"
"""
import std/oids
block: # genOid
let x = genOid()
doAssert ($x).len == 24
doAssert ($x).len == 32
block:
let x = genOid()
let y = parseOid(cstring($x))
doAssert x == y