summary refs log tree commit diff stats
path: root/lib/system_overview.rst
blob: d6cbe1a35f8d46e887c1e857f9a774791d7e9235 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
.. default-role:: code

The System module imports several separate modules, and their documentation
is in separate files:

* `iterators <iterators.html>`_
* `assertions <assertions.html>`_
* `dollars <dollars.html>`_
* `io <io.html>`_
* `widestrs <widestrs.html>`_


Here is a short overview of the most commonly used functions from the
`system` module. Function names in the tables below are clickable and
will take you to the full documentation of the function.

There are many more functions available than the ones listed in this overview.
Use the table of contents on the left-hand side and/or `Ctrl+F` to navigate
through this module.


Strings and characters
----------------------

=============================     =======================================
Proc                              Usage
=============================     =======================================
`len(s)<#len,string>`_            Return the length of a string
`chr(i)<#chr,range[]>`_           Convert an `int` in the range `0..255`
                                  to a character
`ord(c)<#ord,T>`_                 Return `int` value of a character
`a & b<#&,string,string>`_        Concatenate two strings
`s.add(c)<#add,string,char>`_     Add character to the string
`$<dollars.html>`_                Convert various types to string
=============================     =======================================

**See also:**
* `strutils module <strutils.html>`_ for common string functions
* `strformat module <strformat.html>`_ for string interpolation and formatting
* `unicode module <unicode.html>`_ for Unicode UTF-8 handling
* `strscans <strscans.html>`_ for `scanf` and `scanp` macros, which offer
  easier substring extraction than regular expressions
* `strtabs module <strtabs.html>`_ for efficient hash tables
  (dictionaries, in some programming languages) mapping from strings to strings



Seqs
----

==============================================     ==========================================
Proc                                               Usage
==============================================     ==========================================
`newSeq<#newSeq>`_                                 Create a new sequence of a given length
`newSeqOfCap<#newSeqOfCap,Natural>`_               Create a new sequence with zero length
                                                   and a given capacity
`setLen<#setLen,seq[T],Natural>`_                  Set the length of a sequence
`len<#len,seq[T]>`_                                Return the length of a sequence
`@<#@,openArray[T]>`_                              Turn an array into a sequence
`add<#add,seq[T],sinkT>`_                          Add an item to the sequence
`insert<#insert,seq[T],sinkT>`_                    Insert an item at a specific position
`delete<#delete,seq[T],Natural>`_                  Delete an item while preserving the
                                                   order of elements (`O(n)` operation)
`del<#del,seq[T],Natural>`_                        `O(1)` removal, doesn't preserve the order
`pop<#pop,seq[T]>`_                                Remove and return last item of a sequence
`x & y<#&,seq[T],seq[T]>`_                         Concatenate two sequences
`x[a .. b]<#[],openArray[T],HSlice[U,V]>`_         Slice of a sequence (both ends included)
`x[a .. ^b]<#[],openArray[T],HSlice[U,V]>`_        Slice of a sequence but `b` is a 
                                                   reversed index (both ends included)
`x[a ..\< b]<#[],openArray[T],HSlice[U,V]>`_       Slice of a sequence (excluded upper bound)
==============================================     ==========================================

**See also:**
* `sequtils module <sequtils.html>`_ for operations on container
  types (including strings)
* `json module <json.html>`_ for a structure which allows heterogeneous members
* `lists module <lists.html>`_ for linked lists



Sets
----

Built-in bit sets.

===============================     ======================================
Proc                                Usage
===============================     ======================================
`incl<#incl,set[T],T>`_             Include element `y` in the set `x`
`excl<#excl,set[T],T>`_             Exclude element `y` from the set `x`
`card<#card,set[T]>`_               Return the cardinality of the set,
                                    i.e. the number of elements
`a * b<#*,set[T],set[T]>`_          Intersection
`a + b<#+,set[T],set[T]>`_          Union
`a - b<#-,set[T],set[T]>`_          Difference
`contains<#contains,set[T],T>`_     Check if an element is in the set
[a < b](#<,set[T],set[T])           Check if `a` is a subset of `b`
===============================     ======================================

**See also:**
* `sets module <sets.html>`_ for hash sets
* `intsets module <intsets.html>`_ for efficient int sets



Numbers
-------

==============================    ==================================     =====================
Proc                              Usage                                  Also known as
                                                                         (in other languages)
==============================    ==================================     =====================
`div<#div,int,int>`_              Integer division                       `//`
`mod<#mod,int,int>`_              Integer modulo (remainder)             `%`
`shl<#shl,int,SomeInteger>`_      Shift left                             `<<`
`shr<#shr,int,SomeInteger>`_      Shift right                            `>>`
`ashr<#ashr,int,SomeInteger>`_    Arithmetic shift right
`and<#and,int,int>`_              Bitwise `and`                          `&`
`or<#or,int,int>`_                Bitwise `or`                           `|`
`xor<#xor,int,int>`_              Bitwise `xor`                          `^`
`not<#not,int>`_                  Bitwise `not` (complement)             `~`
`toInt<#toInt,float>`_            Convert floating-point number
                                  into an `int`
`toFloat<#toFloat,int>`_          Convert an integer into a `float`
==============================    ==================================     =====================

**See also:**
* `math module <math.html>`_ for mathematical operations like trigonometric
  functions, logarithms, square and cubic roots, etc.
* `complex module <complex.html>`_ for operations on complex numbers
* `rationals module <rationals.html>`_ for rational numbers



Ordinals
--------

`Ordinal type <#Ordinal>`_ includes integer, bool, character, and enumeration
types, as well as their subtypes.

=====================     =======================================
Proc                      Usage
=====================     =======================================
`succ<#succ,T,int>`_      Successor of the value
`pred<#pred,T,int>`_      Predecessor of the value
`inc<#inc,T,int>`_        Increment the ordinal
`dec<#dec,T,int>`_        Decrement the ordinal
`high<#high,T>`_          Return the highest possible value
`low<#low,T>`_            Return the lowest possible value
`ord<#ord,T>`_            Return `int` value of an ordinal value
=====================     =======================================



Misc
----

====================================================  ============================================
Proc                                                  Usage
====================================================  ============================================
`is<#is,T,S>`_                                        Check if two arguments are of the same type
`isnot<#isnot.t,untyped,untyped>`_                    Negated version of `is`
`!=<#!%3D.t,untyped,untyped>`_                        Not equals
`addr<#addr,T>`_                                      Take the address of a memory location
`T and F<#and,bool,bool>`_                            Boolean `and`
`T or F<#or,bool,bool>`_                              Boolean `or`
`T xor F<#xor,bool,bool>`_                            Boolean `xor` (exclusive or)
`not T<#not,bool>`_                                   Boolean `not`
`a[^x]<#^.t,int>`_                                    Take the element at the reversed index `x`
`a .. b<#..,sinkT,sinkU>`_                            Binary slice that constructs an interval
                                                      `[a, b]`
`a ..^ b<#..^.t,untyped,untyped>`_                    Interval `[a, b]` but `b` as reversed index
[a ..< b](#..<.t,untyped,untyped)                     Interval `[a, b)` (excluded upper bound)
[runnableExamples](#runnableExamples,string,untyped)  Create testable documentation
====================================================  ============================================
r: transparent; padding-left: 5px; padding-right: 5px; } td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; } span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; } .highlight .hll { background-color: #ffffcc } .highlight .c { color: #888888 } /* Comment */ .highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */ .highlight .k { color: #008800; font-weight: bold } /* Keyword */ .highlight .ch { color: #888888 } /* Comment.Hashbang */ .highlight .cm { color: #888888 } /* Comment.Multiline */ .highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */ .highlight .cpf { color: #888888 } /* Comment.PreprocFile */ .highlight .c1 { color: #888888 } /* Comment.Single */ .highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */ .highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */ .highlight .ge { font-style: italic } /* Generic.Emph */ .highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */ .highlight .gr { color: #aa0000 } /* Generic.Error */ .highlight .gh { color: #333333 } /* Generic.Heading */ .highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */ .highlight .go { color: #888888 } /* Generic.Output */ .highlight .gp { color: #555555 } /* Generic.Prompt */ .highlight .gs { font-weight: bold } /* Generic.Strong */ .highlight .gu { color: #666666 } /* Generic.Subheading */ .highlight .gt { color: #aa0000 } /* Generic.Traceback */ .highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */ .highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */ .highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */ .highlight .kp { color: #008800 } /* Keyword.Pseudo */ .highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */ .highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */ .highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */ .highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */ .highlight .na { color: #336699 } /* Name.Attribute */ .highlight .nb { color: #003388 } /* Name.Builtin */ .highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */ .highlight .no { color: #003366; font-weight: bold } /* Name.Constant */ .highlight .nd { color: #555555 } /* Name.Decorator */ .highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */ .highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */ .highlight .nl { color: #336699; font-style: italic } /* Name.Label */ .highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */ .highlight .py { color: #336699; font-weight: bold } /* Name.Property */ .highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */ .highlight .nv { color: #336699 } /* Name.Variable */ .highlight .ow { color: #008800 } /* Operator.Word */ .highlight .w { color: #bbbbbb } /* Text.Whitespace */ .highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */ .highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */ .highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */ .highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */ .highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */ .highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */ .highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */ .highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */ .highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */ .highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */ .highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */ .highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */ .highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */ .highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */ .highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */ .highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */ .highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */ .highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */ .highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */ .highlight .vc { color: #336699 } /* Name.Variable.Class */ .highlight .vg { color: #dd7700 } /* Name.Variable.Global */ .highlight .vi { color: #3333bb } /* Name.Variable.Instance */ .highlight .vm { color: #336699 } /* Name.Variable.Magic */ .highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
module = stmt ^* (';' / IND{=})
comma = ',' COMMENT?
semicolon = ';' COMMENT?
colon = ':' COMMENT?
colcom = ':' COMMENT?

operator =  OP0 | OP1 | OP2 | OP3 | OP4 | OP5 | OP6 | OP7 | OP8 | OP9
         | 'or' | 'xor' | 'and'
         | 'is' | 'isnot' | 'in' | 'notin' | 'of'
         | 'div' | 'mod' | 'shl' | 'shr' | 'not' | 'addr' | 'static' | '..'

prefixOperator = operator

optInd = COMMENT?
optPar = (IND{>} | IND{=})?

simpleExpr = assignExpr (OP0 optInd assignExpr)*
assignExpr = orExpr (OP1 optInd orExpr)*
orExpr = andExpr (OP2 optInd andExpr)*
andExpr = cmpExpr (OP3 optInd cmpExpr)*
cmpExpr = sliceExpr (OP4 optInd sliceExpr)*
sliceExpr = ampExpr (OP5 optInd ampExpr)*
ampExpr = plusExpr (OP6 optInd plusExpr)*
plusExpr = mulExpr (OP7 optInd mulExpr)*
mulExpr = dollarExpr (OP8 optInd dollarExpr)*
dollarExpr = primary (OP9 optInd primary)*
symbol = '`' (KEYW|IDENT|literal|(operator|'('|')'|'['|']'|'{'|'}'|'=')+)+ '`'
       | IDENT
indexExpr = expr
indexExprList = indexExpr ^+ comma
exprColonEqExpr = expr (':'|'=' expr)?
exprList = expr ^+ comma
dotExpr = expr '.' optInd ('type' | 'addr' | symbol)
qualifiedIdent = symbol ('.' optInd ('type' | 'addr' | symbol))?
exprColonEqExprList = exprColonEqExpr (comma exprColonEqExpr)* (comma)?
setOrTableConstr = '{' ((exprColonEqExpr comma)* | ':' ) '}'
castExpr = 'cast' '[' optInd typeDesc optPar ']' '(' optInd expr optPar ')'
parKeyw = 'discard' | 'include' | 'if' | 'while' | 'case' | 'try'
        | 'finally' | 'except' | 'for' | 'block' | 'const' | 'let'
        | 'when' | 'var' | 'mixin'
par = '(' optInd (&parKeyw complexOrSimpleStmt ^+ ';' 
                 | simpleExpr ('=' expr (';' complexOrSimpleStmt ^+ ';' )? )?
                            | (':' expr)? (',' (exprColonEqExpr comma?)*)?  )?
        optPar ')'
literal = | INT_LIT | INT8_LIT | INT16_LIT | INT32_LIT | INT64_LIT
          | UINT_LIT | UINT8_LIT | UINT16_LIT | UINT32_LIT | UINT64_LIT
          | FLOAT_LIT | FLOAT32_LIT | FLOAT64_LIT
          | STR_LIT | RSTR_LIT | TRIPLESTR_LIT
          | CHAR_LIT
          | NIL
generalizedLit = GENERALIZED_STR_LIT | GENERALIZED_TRIPLESTR_LIT
identOrLiteral = generalizedLit | symbol | literal
               | par | arrayConstr | setOrTableConstr
               | castExpr
tupleConstr = '(' optInd (exprColonEqExpr comma?)* optPar ')'
arrayConstr = '[' optInd (exprColonEqExpr comma?)* optPar ']'
primarySuffix = '(' (exprColonEqExpr comma?)* ')' doBlocks?
              | doBlocks
              | '.' optInd ('type' | 'addr' | symbol) generalizedLit?
              | '[' optInd indexExprList optPar ']'
              | '{' optInd indexExprList optPar '}'
              | &( '`'|IDENT|literal|'cast') expr # command syntax
condExpr = expr colcom expr optInd
        ('elif' expr colcom expr optInd)*
         'else' colcom expr
ifExpr = 'if' condExpr
whenExpr = 'when' condExpr
pragma = '{.' optInd (exprColonExpr comma?)* optPar ('.}' | '}')
identVis = symbol opr?  # postfix position
identWithPragma = identVis pragma?
declColonEquals = identWithPragma (comma identWithPragma)* comma?
                  (':' optInd typeDesc)? ('=' optInd expr)?
identColonEquals = ident (comma ident)* comma?
     (':' optInd typeDesc)? ('=' optInd expr)?)
inlTupleDecl = 'tuple'
    [' optInd  (identColonEquals (comma/semicolon)?)*  optPar ']'
extTupleDecl = 'tuple'
    COMMENT? (IND{>} identColonEquals (IND{=} identColonEquals)*)?
paramList = '(' declColonEquals ^* (comma/semicolon) ')'
paramListArrow = paramList? ('->' optInd typeDesc)?
paramListColon = paramList? (':' optInd typeDesc)?
doBlock = 'do' paramListArrow pragmas? colcom stmt
doBlocks = doBlock ^* IND{=}
procExpr = 'proc' paramListColon pragmas? ('=' COMMENT? stmt)?
distinct = 'distinct' optInd typeDesc
expr = (ifExpr
      | whenExpr
      | caseExpr
      | tryExpr)
      / simpleExpr
typeKeyw = 'var' | 'ref' | 'ptr' | 'shared' | 'type' | 'tuple'
         | 'proc' | 'iterator' | 'distinct' | 'object' | 'enum'
primary = typeKeyw typeDescK
        /  prefixOperator* identOrLiteral primarySuffix*
        / 'addr' primary
        / 'static' primary
        / 'bind' primary
typeDesc = simpleExpr
typeDefAux = simpleExpr
           | 'generic' typeClass
macroColon = ':' stmt? ( IND{=} 'of' exprList ':' stmt 
                       | IND{=} 'elif' expr ':' stmt
                       | IND{=} 'except' exprList ':' stmt
                       | IND{=} 'else' ':' stmt )*
exprStmt = simpleExpr
         (( '=' optInd expr )
         / ( expr ^+ comma
             doBlocks
              / macroColon
           ))?
importStmt = 'import' optInd expr
              ((comma expr)*
              / 'except' optInd (expr ^+ comma))
includeStmt = 'include' optInd expr ^+ comma
fromStmt = 'from' moduleName 'import' optInd expr (comma expr)*
returnStmt = 'return' optInd expr?
raiseStmt = 'raise' optInd expr?
yieldStmt = 'yield' optInd expr?
discardStmt = 'discard' optInd expr?
breakStmt = 'break' optInd expr?
continueStmt = 'break' optInd expr?
condStmt = expr colcom stmt COMMENT?
           (IND{=} 'elif' expr colcom stmt)*
           (IND{=} 'else' colcom stmt)?
ifStmt = 'if' condStmt
whenStmt = 'when' condStmt
whileStmt = 'while' expr colcom stmt
ofBranch = 'of' exprList colcom stmt
ofBranches = ofBranch (IND{=} ofBranch)*
                      (IND{=} 'elif' expr colcom stmt)*
                      (IND{=} 'else' colcom stmt)?
caseStmt = 'case' expr ':'? COMMENT?
            (IND{>} ofBranches DED
            | IND{=} ofBranches)
tryStmt = 'try' colcom stmt &(IND{=}? 'except'|'finally')
           (IND{=}? 'except' exprList colcom stmt)*
           (IND{=}? 'finally' colcom stmt)?
tryExpr = 'try' colcom stmt &(optInd 'except'|'finally')
           (optInd 'except' exprList colcom stmt)*
           (optInd 'finally' colcom stmt)?
exceptBlock = 'except' colcom stmt
forStmt = 'for' (identWithPragma ^+ comma) 'in' expr colcom stmt
blockStmt = 'block' symbol? colcom stmt
staticStmt = 'static' colcom stmt
asmStmt = 'asm' pragma? (STR_LIT | RSTR_LIT | TRIPLE_STR_LIT)
genericParam = symbol (comma symbol)* (colon expr)? ('=' optInd expr)?
genericParamList = '[' optInd
  genericParam ^* (comma/semicolon) optPar ']'
pattern = '{' stmt '}'
indAndComment = (IND{>} COMMENT)? | COMMENT?
routine = optInd identVis pattern? genericParamList?
  paramListColon pragma? ('=' COMMENT? stmt)? indAndComment
commentStmt = COMMENT
section(p) = COMMENT? p / (IND{>} (p / COMMENT)^+IND{=} DED)
constant = identWithPragma (colon typedesc)? '=' optInd expr indAndComment
enum = 'enum' optInd (symbol optInd ('=' optInd expr COMMENT?)? comma?)+
objectWhen = 'when' expr colcom objectPart COMMENT?
            ('elif' expr colcom objectPart COMMENT?)*
            ('else' colcom objectPart COMMENT?)?
objectBranch = 'of' exprList colcom objectPart
objectBranches = objectBranch (IND{=} objectBranch)*
                      (IND{=} 'elif' expr colcom objectPart)*
                      (IND{=} 'else' colcom objectPart)?
objectCase = 'case' identWithPragma ':' typeDesc ':'? COMMENT?
            (IND{>} objectBranches DED
            | IND{=} objectBranches)
objectPart = IND{>} objectPart^+IND{=} DED
           / objectWhen / objectCase / 'nil' / declColonEquals
object = 'object' pragma? ('of' typeDesc)? COMMENT? objectPart
typeClassParam = ('var')? symbol
typeClass = typeClassParam ^* ',' (pragma)? ('of' typeDesc ^* ',')?
              &IND{>} stmt
typeDef = identWithPragma genericParamList? '=' optInd typeDefAux
            indAndComment?
varTuple = '(' optInd identWithPragma ^+ comma optPar ')' '=' optInd expr
variable = (varTuple / identColonEquals) indAndComment
bindStmt = 'bind' optInd qualifiedIdent ^+ comma
mixinStmt = 'mixin' optInd qualifiedIdent ^+ comma
pragmaStmt = pragma (':' COMMENT? stmt)?
simpleStmt = ((returnStmt | raiseStmt | yieldStmt | discardStmt | breakStmt
           | continueStmt | pragmaStmt | importStmt | exportStmt | fromStmt
           | includeStmt | commentStmt) / exprStmt) COMMENT?
complexOrSimpleStmt = (ifStmt | whenStmt | whileStmt
                    | tryStmt | finallyStmt | exceptStmt | forStmt
                    | blockStmt | staticStmt | asmStmt
                    | 'proc' routine
                    | 'method' routine
                    | 'iterator' routine
                    | 'macro' routine
                    | 'template' routine
                    | 'converter' routine
                    | 'type' section(typeDef)
                    | 'const' section(constant)
                    | ('let' | 'var') section(variable)
                    | bindStmt | mixinStmt)
                    / simpleStmt
stmt = (IND{>} complexOrSimpleStmt^+(IND{=} / ';') DED)
     / simpleStmt ^+ ';'