Skip to content

Latest commit

 

History

History
1842 lines (1243 loc) · 33.4 KB

nimcon.rst

File metadata and controls

1842 lines (1243 loc) · 33.4 KB

Workshop

Outline

  1. Goals, history, philosophy
  2. Basics
  3. Meta programming
  4. c2nim

Goals

"The reasonable man adapts himself to the world: the unreasonable one persists in trying to adapt the world to himself. Therefore all progress depends on the unreasonable man." -- George Bernard Shaw

  • as fast as C
  • as expressive as Python
  • as extensible as Lisp

The history of Nim

  • Development started in 2006.
  • First bootstrapping succeeded in 2008. - Compiler written in Pascal. - Translated by a tool (pas2nim) to Nim - used pas2nim to produce the first wrappers

The history of Nim

  • Development started in 2006.
  • First bootstrapping succeeded in 2008. - Compiler written in Pascal. - Translated by a tool (pas2nim) to Nim - used pas2nim to produce the first wrappers
  • Goals: - leverage meta programming to keep the language small - compile to C - implementation size: 20_000 lines of code - learn from C's, C++'s, Ada's mistakes

The history of Nim (2)

"Good Software Takes Ten Years. Get Used To it." -- Joel Spolsky
  • current implementation size: about 90_000 lines of code
  • language is actually pretty big: generics, concepts, exceptions, procs, templates, macros, methods, inheritance, pointers, effect system, ...

Language influences

The language borrows heavily from:

  • Modula 3: * traced vs untraced pointers
  • Delphi * type safe bit sets (set of char) * the parts of the syntax people don't like
  • Ada * subrange types * distinct type * safe variants / case objects
  • C++ * Excessive overloading * Generic programming

Language influences

  • Python * indentation based syntax * programming should be fun * the parts of the syntax people do like

  • Lisp * we really want a macro system * embrace the AST * homoiconicity; everything is a function application

    (well, in Nim's case ... not really)

  • Oberon * the export marker

  • C# * async / await * lambda macros

Why Nim?

  • One language to rule them all.

Why Nim?

  • One language to rule them all.
  • "Nim is good at everything".
    • web development
    • games
    • compilers
    • operating system development
    • scientific computing
    • scripting
    • command line applications
    • UI applications
    • And lots more!

Why Nim?

  • One language to rule them all.
  • "Nim is good at everything".
    • web development
    • games
    • compilers
    • operating system development
    • scientific computing
    • scripting
    • command line applications
    • UI applications
    • And lots more!
  • Convince programmers with code

Function application

Function application is f(), f(a), f(a, b).

And here is the sugar:

Sugar Meaning Example
f a f(a) spawn log("some message")
a.f() f(a) db.fetchRow()
a.f f(a) mystring.len
f a, b f(a, b) echo "hello ", "world"
a.f(b) f(a, b) myarray.map(f)
a.f b f(a, b) db.fetchRow 1

BUT: f does not mean f(); myarray.map(f) passes f to map

if statement

indentation based syntax

if thisIsaLongCondition() and
    thisIsAnotherLongCondition(1,
       2, 3, 4):
  x = true
  • Rule of thumb: optional indentation after operators, ( and ,
  • if, case etc also available as expressions

if expression

If vs when

case statement

Var vs let vs const

Var vs let vs const

loops

Builtin types: numbers

Type system

  • strict and statically typed
  • type system weakened for the meta-programming
  • value based datatypes (like in C++)
  • subtyping via single inheritance (object of RootObj)
  • subtyping via range: type Natural = range[0..high(int)]
  • generics (HashSet[string])
  • "concepts": constraints for generic types
  • no interfaces, use (tuple of) closures instead
  • no Hindley-Milner type inference, Nim embraces overloading
  • limited amount of flow typing

Flow typing

Effect system

  • model effects as tuples (T, E) rather than E[T]
  • every effect is inferred

Effect system

  • tracks side effects
  • tracks exceptions
  • tracks "tags": ReadIOEffect, WriteIoEffect, TimeEffect, ReadDirEffect, ExecIOEffect
  • tracks locking levels; deadlock prevention at compile-time
  • tracks "GC safety"

Effect system

Builtin types: arrays

  • array[FixedSize, T] * fixed size in Nim * value based datatypes * layout is compatible to C * create via [1, 2, 3] construction
  • seq[T] * dynamically resizable at runtime * grow with add, resize with setLen * create via @ or newSeq: @[1, 2, 3] * allocated on the heap and GC'ed
  • openArray[T] * allows to pass seq or array to a routine * internally a (pointer, length) pair

Builtin types: strings

Builtin types: pointers

Builtin types

tuple

  • value based datatypes
  • structural typing
  • optional field names
  • construct with ()

Builtin types

object

  • value based datatypes
  • ref object an idiom to get reference semantics out of objects

Builtin types: functions

  • type Callback = proc (a, b: string) {.closure.} * functions are first class in Nim * "calling convention" affects type compatibility * closure is a special calling convention (closures are GC'ed)

Builtin types: functions

Regular expressions

Equality

Accessors

Accessors

Accessors

Distinct

Distinct

::
nim c -r --taintMode:on taintmode_ex

Distinct

::
nim c -r --taintMode:on taintmode_ex

Module system

Module system

Module system

Routines

  • proc
  • iterator
  • template
  • macro
  • method
  • converter
  • (func)

Iterators

Iterators

Iterators

Rewritten to:

Iterators

Iterators

Iterators

Iterators

Concepts

Concepts (2)

Templates (1)

Templates (2)

Templates (3)

Templates (3)

Templates (3)

Templates (3)

Templates (4)

Macros

test "tactors"
test "tactors2"
test "threadex"

-->

test "tactors", "tactors2", "threadex"

Macros

Macros

Quoting

Currying

Currying

Currying

Slides

::
git clone https://github.com/Araq/NimCon2015 nim c -r build.nim

CPU emulation

CPU emulation

CPU emulation

CPU emulation

CPU emulation

CPU emulation

Interfacing with C

2 options

  • via dynlib
  • via header

Dynlib import

Header import

type
  GtkWidget {.importc: "GtkWidget_t", header: "<gtk.h>".} = object
    data {.importc: "Data".}: cint
    binary {.importc: "Binary".}: cfloat
    compatible: char

proc gtk_image_new(): ptr GtkWidget
  {.cdecl, header: "<gtk.h>", importc.}

{.passC: staticExec("pkg-config --cflags gtk").}
{.passL: staticExec("pkg-config --libs gtk").}

Header import

proc printf(formatstr: cstring)
  {.header: "<stdio.h>", importc: "printf", varargs.}

printf("%s%s", "Nim strings ", "converted to cstring for you")

Data exchange with C

C type Nim type
int cint
unsigned long culong
float cfloat
int x[4] array[4, cint]
int* ptr int
char* cstring
char** cstringArray = ptr array [0..ArrayDummySize, cstring]

Data exchange with C

Data exchange with C

Data exchange with C (2)

Data exchange with C (2)

CodegenDecl pragma

Wrapping C++

Wrapping C++

Constructors

Constructors

Constructors

Constructors

Constructors

Generics

For example:

Produces:

Emit pragma

Parallelism

Parallelism

Parallelism

Parallelism

Happy hacking!

Website http://nim-lang.org
Mailing list http://www.freelists.org/list/nim-dev
Forum http://forum.nim-lang.org
Github https://github.com/nim-lang/Nim
IRC irc.freenode.net/nim