===================== Nim Tutorial (Part I) ===================== :Author: Andreas Rumpf :Version: |nimversion| .. contents:: Introduction ============ .. raw:: html

"Der Mensch ist doch ein Augentier -- schöne Dinge wünsch ich mir."

This document is a tutorial for the programming language *Nim*. This tutorial assumes that you are familiar with basic programming concepts like variables, types or statements but is kept very basic. The `manual `_ contains many more examples of the advanced language features. All code examples in this tutorial, as well as the ones found in the rest of Nim's documentation, follow the `Nim style guide `. The first program ================= We start the tour with a modified "hello world" program: .. code-block:: Nim # This is a comment echo "What's your name? " var name: string = readLine(stdin) echo "Hi, ", name, "!" Save this code to the file "greetings.nim". Now compile and run it:: nim compile --run greetings.nim With the ``--run`` `switch `_ Nim executes the file automatically after compilation. You can give your program command line arguments by appending them after the filename:: nim compile --run greetings.nim arg1 arg2 Commonly used commands and switches have abbreviations, so you can also use:: nim c -r greetings.nim To compile a release version use:: nim c -d:release greetings.nim By default the Nim compiler generates a large amount of runtime checks aiming for your debugging pleasure. With ``-d:release`` these checks are `turned off and optimizations are turned on `_. Though it should be pretty obvious what the program does, I will explain the syntax: statements which are not indented are executed when the program starts. Indentation is Nim's way of grouping statements. Indentation is done with spaces only, tabulators are not allowed. String literals are enclosed in double quotes. The ``var`` statement declares a new variable named ``name`` of type ``string`` with the value that is returned by the `readLine `_ procedure. Since the compiler knows that `readLine `_ returns a string, you can leave out the type in the declaration (this is called `local type inference`:idx:). So this will work too: .. code-block:: Nim var name = readLine(stdin) Note that this is basically the only form of type inference that exists in Nim: it is a good compromise between brevity and readability. The "hello world" program contains several identifiers that are already known to the compiler: ``echo``, `readLine `_, etc. These built-ins are declared in the system_ module which is implicitly imported by any other module. Lexical elements ================ Let us look at Nim's lexical elements in more detail: like other programming languages Nim consists of (string) literals, identifiers, keywords, comments, operators, and other punctuation marks. String and character literals ----------------------------- String literals are enclosed in double quotes; character literals in single quotes. Special characters are escaped with ``\``: ``\n`` means newline, ``\t`` means tabulator, etc. There are also *raw* string literals: .. code-block:: Nim r"C:\program files\nim" In raw literals the backslash is not an escape character. The third and last way to write string literals are *long string literals*. They are written with three quotes: ``""" ... """``; they can span over multiple lines and the ``\`` is not an escape character either. They are very useful for embedding HTML code templates for example. Comments -------- Comments start anywhere outside a string or character literal with the hash character ``#``. Documentation comments start with ``##``: .. code-block:: nim # A comment. var myVariable: int ## a documentation comment Documentation comments are tokens; they are only allowed at certain places in the input file as they belong to the syntax tree! This feature enables simpler documentation generators. You can also use the `discard statement`_ together with *long string literals* to create block comments: .. code-block:: nim discard """ You can have any Nim code text commented out inside this with no indentation restrictions. yes("May I ask a pointless question?") """ Numbers ------- Numerical literals are written as in most other languages. As a special twist, underscores are allowed for better readability: ``1_000_000`` (one million). A number that contains a dot (or 'e' or 'E') is a floating point literal: ``1.0e9`` (one billion). Hexadecimal literals are prefixed with ``0x``, binary literals with ``0b`` and octal literals with ``0o``. A leading zero alone does not produce an octal. The var statement ================= The var statement declares a new local or global variable: .. code-block:: var x, y: int # declares x and y to have the type ``int`` Indentation can be used after the ``var`` keyword to list a whole section of variables: .. code-block:: var x, y: int # a comment can occur here too a, b, c: string The assignment statement ======================== The assignment statement assigns a new value to a variable or more generally to a storage location: .. code-block:: var x = "abc" # introduces a new variable `x` and assigns a value to it x = "xyz" # assigns a new value to `x` ``=`` is the *assignment operator*. The assignment operator cannot be overloaded, overwritten or forbidden, but this might change in a future version of Nim. You can declare multiple variables with a single assignment statement and all the variables will have the same value: .. code-block:: var x, y = 3 # assigns 3 to the variables `x` and `y` echo "x ", x # outputs "x 3" echo "y ", y # outputs "y 3" x = 42 # changes `x` to 42 without changing `y` echo "x ", x # outputs "x 42" echo "y ", y # outputs "y 3" Note that declaring multiple variables with a single assignment which calls a procedure can have unexpected results: the compiler will *unroll* the assignments and end up calling the procedure several times. If the result of the procedure depends on side effects, your variables may end up having different values! For safety use only constant values. Constants ========= Constants are symbols which are bound to a value. The constant's value cannot change. The compiler must be able to evaluate the expression in a constant declaration at compile time: .. code-block:: nim const x = "abc" # the constant x contains the string "abc" Indentation can be used after the ``const`` keyword to list a whole section of constants: .. code-block:: const x = 1 # a comment can occur here too y = 2 z = y + 5 # computations are possible The let statement ================= The ``let`` statement works like the ``var`` statement but the declared symbols are *single assignment* variables: After the initialization their value cannot change: .. code-block:: let x = "abc" # introduces a new variable `x` and binds a value to it x = "xyz" # Illegal: assignment to `x` The difference between ``let`` and ``const`` is: ``let`` introduces a variable that can not be re-assigned, ``const`` means "enforce compile time evaluation and put it into a data section": .. code-block:: const input = readLine(stdin) # Error: constant expression expected .. code-block:: let input = readLine(stdin) # works Control flow statements ======================= The greetings program consists of 3 statements that are executed sequentially. Only the most primitive programs can get away with that: branching and looping are needed too. If statement ------------ The if statement is one way to branch the control flow: .. code-block:: nim let name = readLine(stdin) if name == "": echo "Poor soul, you lost your name?" elif name == "name": echo "Very funny, your name is name." else: echo "Hi, ", name, "!" There can be zero or more ``elif`` parts, and the ``else`` part is optional. The keyword ``elif`` is short for ``else if``, and is useful to avoid excessive indentation. (The ``""`` is the empty string. It contains no characters.) Case statement -------------- Another way to branch is provided by the case statement. A case statement is a multi-branch: .. code-block:: nim let name = readLine(stdin) case name of "": echo "Poor soul, you lost your name?" of "name": echo "Very funny, your name is name." of "Dave", "Frank": echo "Cool name!" else: echo "Hi, ", name, "!" As it can be seen, for an ``of`` branch a comma separated list of values is also allowed. The case statement can deal with integers, other ordinal types and strings. (What an ordinal type is will be explained soon.) For integers or other ordinal types value ranges are also possible: .. code-block:: nim # this statement will be explained later: from strutils import parseInt echo "A number please: " let n = parseInt(readLine(stdin)) case n of 0..2, 4..7: echo "The number is in the set: {0, 1, 2, 4, 5, 6, 7}" of 3, 8: echo "The number is 3 or 8" However, the above code does not compile: the reason is that you have to cover every value that ``n`` may contain, but the code only handles the values ``0..8``. Since it is not very practical to list every other possible integer (though it is possible thanks to the range notation), we fix this by telling the compiler that for every other value nothing should be done: .. code-block:: nim ... case n of 0..2, 4..7: echo "The number is in the set: {0, 1, 2, 4, 5, 6, 7}" of 3, 8: echo "The number is 3 or 8" else: discard The empty `discard statement`_ is a *do nothing* statement. The compiler knows that a case statement with an else part cannot fail and thus the error disappears. Note that it is impossible to cover all possible string values: that is why string cases always need an ``else`` branch. In general the case statement is used for subrange types or enumerations where it is of great help that the compiler checks that you covered any possible value. While statement --------------- The while statement is a simple looping construct: .. code-block:: nim echo "What's your name? " var name = readLine(stdin) while name == "": echo "Please tell me your name: " name = readLine(stdin) # no ``var``, because we do not declare a new variable here The example uses a while loop to keep asking the users for their name, as long as the user types in nothing (only presses RETURN). For statement ------------- The ``for`` statement is a construct to loop over any element an *iterator* provides. The example uses the built-in `countup `_ iterator: .. code-block:: nim echo "Counting to ten: " for i in countup(1, 10): echo $i # --> Outputs 1 2 3 4 5 6 7 8 9 10 on different lines The built-in `$ `_ operator turns an integer (``int``) and many other types into a string. The variable ``i`` is implicitly declared by the ``for`` loop and has the type ``int``, because that is what `countup `_ returns. ``i`` runs through the values 1, 2, .., 10. Each value is ``echo``-ed. This code does the same: .. code-block:: nim echo "Counting to 10: " var i = 1 while i <= 10: echo $i inc(i) # increment i by 1 # --> Outputs 1 2 3 4 5 6 7 8 9 10 on different lines Counting down can be achieved as easily (but is less often needed): .. code-block:: nim echo "Counting down from 10 to 1: " for i in countdown(10, 1): echo $i # --> Outputs 10 9 8 7 6 5 4 3 2 1 on different lines Since counting up occurs so often in programs, Nim also has a `.. `_ iterator that does the same: .. code-block:: nim for i in 1..10: ... Scopes and the block statement ------------------------------ Control flow statements have a feature not covered yet: they open a new scope. This means that in the following example, ``x`` is not accessible outside the loop: .. code-block:: nim while false: var x = "hi" echo x # does not work A while (for) statement introduces an implicit block. Identifiers are only visible within the block they have been declared. The ``block`` statement can be used to open a new block explicitly: .. code-block:: nim block myblock: var x = "hi" echo x # does not work either The block's *label* (``myblock`` in the example) is optional. Break statement --------------- A block can be left prematurely with a ``break`` statement. The break statement can leave a ``while``, ``for``, or a ``block`` statement. It leaves the innermost construct, unless a label of a block is given: .. code-block:: nim block myblock: echo "entering block" while true: echo "looping" break # leaves the loop, but not the block echo "still in block" block myblock2: echo "entering block" while true: echo "looping" break myblock2 # leaves the block (and the loop) echo "still in block" Continue statement ------------------ Like in many other programming languages, a ``continue`` statement starts the next iteration immediately: .. code-block:: nim while true: let x = readLine(stdin) if x == "": continue echo x When statement -------------- Example: .. code-block:: nim when system.hostOS == "windows": echo "running on Windows!" elif system.hostOS == "linux": echo "running on Linux!" elif system.hostOS == "macosx": echo "running on Mac OS X!" else: echo "unknown operating system" The ``when`` statement is almost identical to the ``if`` statement with some differences: * Each condition has to be a constant expression since it is evaluated by the compiler. * The statements within a branch do not open a new scope. * The compiler checks the semantics and produces code *only* for the statements that belong to the first condition that evaluates to ``true``. The ``when`` statement is useful for writing platform specific code, similar to the ``#ifdef`` construct in the C programming language. **Note**: To comment out a large piece of code, it is often better to use a ``when false:`` statement than to use real comments. This way nesting is possible. Statements and indentation ========================== Now that we covered the basic control flow statements, let's return to Nim indentation rules. In Nim there is a distinction between *simple statements* and *complex statements*. *Simple statements* cannot contain other statements: Assignment, procedure calls or the ``return`` statement belong to the simple statements. *Complex statements* like ``if``, ``when``, ``for``, ``while`` can contain other statements. To avoid ambiguities, complex statements always have to be indented, but single simple statements do not: .. code-block:: nim # no indentation needed for single assignment statement: if x: x = false # indentation needed for nested if statement: if x: if y: y = false else: y = true # indentation needed, because two statements follow the condition: if x: x = false y = false *Expressions* are parts of a statement which usually result in a value. The condition in an if statement is an example for an expression. Expressions can contain indentation at certain places for better readability: .. code-block:: nim if thisIsaLongCondition() and thisIsAnotherLongCondition(1, 2, 3, 4): x = true As a rule of thumb, indentation within expressions is allowed after operators, an open parenthesis and after commas. With parenthesis and semicolons ``(;)`` you can use statements where only an expression is allowed: .. code-block:: nim # computes fac(4) at compile time: const fac4 = (var x = 1; for i in 1..4: x *= i; x) Procedures ========== To define new commands like `echo `_ and `readLine `_ in the examples, the concept of a `procedure` is needed. (Some languages call them *methods* or *functions*.) In Nim new procedures are defined with the ``proc`` keyword: .. code-block:: nim proc yes(question: string): bool = echo question, " (y/n)" while true: case readLine(stdin) of "y", "Y", "yes", "Yes": return true of "n", "N", "no", "No": return false else: echo "Please be clear: yes or no" if yes("Should I delete all your important files?"): echo "I'm sorry Dave, I'm afraid I can't do that." else: echo "I think you know what the problem is just as well as I do." This example shows a procedure named ``yes`` that asks the user a ``question`` and returns true if they answered "yes" (or something similar) and returns false if they answered "no" (or something similar). A ``return`` statement leaves the procedure (and therefore the while loop) immediately. The ``(question: string): bool`` syntax describes that the procedure expects a parameter named ``question`` of type ``string`` and returns a value of type ``bool``. ``Bool`` is a built-in type: the only valid values for ``bool`` are ``true`` and ``false``. The conditions in if or while statements should be of the type ``bool``. Some terminology: in the example ``question`` is called a (formal) *parameter*, ``"Should I..."`` is called an *argument* that is passed to this parameter. Result variable --------------- A procedure that returns a value has an implicit ``result`` variable declared that represents the return value. A ``return`` statement with no expression is a shorthand for ``return result``. The ``result`` value is always returned automatically at the end a procedure if there is no ``return`` statement at the exit. .. code-block:: nim proc sumTillNegative(x: varargs[int]): int = for i in x: if i < 0: return result = result + i echo sumTillNegative() # echos 0 echo sumTillNegative(3, 4, 5) # echos 12 echo sumTillNegative(3, 4 , -1 , 6) # echos 7 The ``result`` variable is already implicitly declared at the start of the function, so declaring it again with 'var result', for example, would shadow it with a normal variable of the same name. The result variable is also already initialised with the type's default value. Note that referential data types will be ``nil`` at the start of the procedure, and thus may require manual initialisation. Parameters ---------- Parameters are constant in the procedure body. By default, their value cannot be changed because this allows the compiler to implement parameter passing in the most efficient way. If a mutable variable is needed inside the procedure, it has to be declared with ``var`` in the procedure body. Shadowing the parameter name is possible, and actually an idiom: .. code-block:: nim proc printSeq(s: seq, nprinted: int = -1) = var nprinted = if nprinted == -1: s.len else: min(nprinted, s.len) for i in 0 .. pre { line-height: 125%; } td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; } span.linenos { color: inherit; background-color: 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 */
#
#
#            Nim's Runtime Library
#        (c) Copyright 2018 Nim contributors
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

## This module implements a json parser. It is used
## and exported by the ``json`` standard library
## module, but can also be used in its own right.

import strutils, lexbase, streams, unicode
import std/private/decode_helpers

type
  JsonEventKind* = enum ## enumeration of all events that may occur when parsing
    jsonError,          ## an error occurred during parsing
    jsonEof,            ## end of file reached
    jsonString,         ## a string literal
    jsonInt,            ## an integer literal
    jsonFloat,          ## a float literal
    jsonTrue,           ## the value ``true``
    jsonFalse,          ## the value ``false``
    jsonNull,           ## the value ``null``
    jsonObjectStart,    ## start of an object: the ``{`` token
    jsonObjectEnd,      ## end of an object: the ``}`` token
    jsonArrayStart,     ## start of an array: the ``[`` token
    jsonArrayEnd        ## end of an array: the ``]`` token

  TokKind* = enum # must be synchronized with TJsonEventKind!
    tkError,
    tkEof,
    tkString,
    tkInt,
    tkFloat,
    tkTrue,
    tkFalse,
    tkNull,
    tkCurlyLe,
    tkCurlyRi,
    tkBracketLe,
    tkBracketRi,
    tkColon,
    tkComma

  JsonError* = enum       ## enumeration that lists all errors that can occur
    errNone,              ## no error
    errInvalidToken,      ## invalid token
    errStringExpected,    ## string expected
    errColonExpected,     ## ``:`` expected
    errCommaExpected,     ## ``,`` expected
    errBracketRiExpected, ## ``]`` expected
    errCurlyRiExpected,   ## ``}`` expected
    errQuoteExpected,     ## ``"`` or ``'`` expected
    errEOC_Expected,      ## ``*/`` expected
    errEofExpected,       ## EOF expected
    errExprExpected       ## expr expected

  ParserState = enum
    stateEof, stateStart, stateObject, stateArray, stateExpectArrayComma,
    stateExpectObjectComma, stateExpectColon, stateExpectValue

  JsonParser* = object of BaseLexer ## the parser object.
    a*: string
    tok*: TokKind
    kind: JsonEventKind
    err: JsonError
    state: seq[ParserState]
    filename: string
    rawStringLiterals: bool

  JsonKindError* = object of ValueError ## raised by the ``to`` macro if the
                                        ## JSON kind is incorrect.
  JsonParsingError* = object of ValueError ## is raised for a JSON error

const
  errorMessages*: array[JsonError, string] = [
    "no error",
    "invalid token",
    "string expected",
    "':' expected",
    "',' expected",
    "']' expected",
    "'}' expected",
    "'\"' or \"'\" expected",
    "'*/' expected",
    "EOF expected",
    "expression expected"
  ]
  tokToStr: array[TokKind, string] = [
    "invalid token",
    "EOF",
    "string literal",
    "int literal",
    "float literal",
    "true",
    "false",
    "null",
    "{", "}", "[", "]", ":", ","
  ]

proc open*(my: var JsonParser, input: Stream, filename: string;
           rawStringLiterals = false) =
  ## initializes the parser with an input stream. `Filename` is only used
  ## for nice error messages. If `rawStringLiterals` is true, string literals
  ## are kept with their surrounding quotes and escape sequences in them are
  ## left untouched too.
  lexbase.open(my, input)
  my.filename = filename
  my.state = @[stateStart]
  my.kind = jsonError
  my.a = ""
  my.rawStringLiterals = rawStringLiterals

proc close*(my: var JsonParser) {.inline.} =
  ## closes the parser `my` and its associated input stream.
  lexbase.close(my)

proc str*(my: JsonParser): string {.inline.} =
  ## returns the character data for the events: ``jsonInt``, ``jsonFloat``,
  ## ``jsonString``
  assert(my.kind in {jsonInt, jsonFloat, jsonString})
  return my.a

proc getInt*(my: JsonParser): BiggestInt {.inline.} =
  ## returns the number for the event: ``jsonInt``
  assert(my.kind == jsonInt)
  return parseBiggestInt(my.a)

proc getFloat*(my: JsonParser): float {.inline.} =
  ## returns the number for the event: ``jsonFloat``
  assert(my.kind == jsonFloat)
  return parseFloat(my.a)

proc kind*(my: JsonParser): JsonEventKind {.inline.} =
  ## returns the current event type for the JSON parser
  return my.kind

proc getColumn*(my: JsonParser): int {.inline.} =
  ## get the current column the parser has arrived at.
  result = getColNumber(my, my.bufpos)

proc getLine*(my: JsonParser): int {.inline.} =
  ## get the current line the parser has arrived at.
  result = my.lineNumber

proc getFilename*(my: JsonParser): string {.inline.} =
  ## get the filename of the file that the parser processes.
  result = my.filename

proc errorMsg*(my: JsonParser): string =
  ## returns a helpful error message for the event ``jsonError``
  assert(my.kind == jsonError)
  result = "$1($2, $3) Error: $4" % [
    my.filename, $getLine(my), $getColumn(my), errorMessages[my.err]]

proc errorMsgExpected*(my: JsonParser, e: string): string =
  ## returns an error message "`e` expected" in the same format as the
  ## other error messages
  result = "$1($2, $3) Error: $4" % [
    my.filename, $getLine(my), $getColumn(my), e & " expected"]

proc parseEscapedUTF16*(buf: cstring, pos: var int): int =
  result = 0
  #UTF-16 escape is always 4 bytes.
  for _ in 0..3:
    # if char in '0' .. '9', 'a' .. 'f', 'A' .. 'F'
    if handleHexChar(buf[pos], result):
      inc(pos)
    else:
      return -1

proc parseString(my: var JsonParser): TokKind =
  result = tkString
  var pos = my.bufpos + 1
  if my.rawStringLiterals:
    add(my.a, '"')
  while true