about summary refs log tree commit diff stats
path: root/client.c
blob: 679e2be46b1a4783284aed7b5df7358745f47326 (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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
/*
 * (C)opyright MMVI Anselm R. Garbe <garbeam at gmail dot com>
 * See LICENSE file for license details.
 */

#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <X11/Xatom.h>
#include <X11/Xutil.h>

#include "wm.h"

static void floating(void);
static void tiling(void);
static void (*arrange)(void) = tiling;

void
max(void *aux)
{
	if(!stack)
		return;
	stack->x = sx;
	stack->y = sy;
	stack->w = sw - 2 * stack->border;
	stack->h = sh - 2 * stack->border;
	resize(stack);
	discard_events(EnterWindowMask);
}

static void
floating(void)
{
	Client *c;

	for(c = stack; c; c = c->snext)
		resize(c);
	discard_events(EnterWindowMask);
}

static void
tiling(void)
{
	Client *c;
	int n, cols, rows, gw, gh, i, j;
    float rt, fd;

	if(!clients)
		return;
	for(n = 0, c = clients; c; c = c->next, n++);
	rt = sqrt(n);
	if(modff(rt, &fd) < 0.5)
		rows = floor(rt);
	else
		rows = ceil(rt);
	if(rows * rows < n)
		cols = rows + 1;
	else
		cols = rows;

	gw = (sw - 2)  / cols;
	gh = (sh - 2) / rows;

	for(i = j = 0, c = clients; c; c = c->next) {
		c->x = i * gw;
		c->y = j * gh;
		c->w = gw;
		c->h = gh;
		resize(c);
		if(++i == cols) {
			j++;
			i = 0;
		}
	}
	discard_events(EnterWindowMask);
}

void
toggle(void *aux)
{
	if(arrange == floating)
		arrange = tiling;
	else
		arrange = floating;
	arrange();
}


void
sel(void *aux)
{
	const char *arg = aux;
	Client *c = NULL;

	if(!arg || !stack)
		return;
	if(!strncmp(arg, "next", 5))
		c = stack->snext ? stack->snext : stack;
	else if(!strncmp(arg, "prev", 5))
		for(c = stack; c && c->snext; c = c->snext);
	if(!c)
		c = stack;
	craise(c);
	focus(c);
}

void
ckill(void *aux)
{
	Client *c = stack;

	if(!c)
		return;
	if(c->proto & WM_PROTOCOL_DELWIN)
		send_message(c->win, wm_atom[WMProtocols], wm_atom[WMDelete]);
	else
		XKillClient(dpy, c->win);
}

static void
resize_title(Client *c)
{
	int i;

	c->tw = 0;
	for(i = 0; i < TLast; i++)
		if(c->tags[i])
			c->tw += textw(&dc.font, c->tags[i]) + dc.font.height;
	c->tw += textw(&dc.font, c->name) + dc.font.height;
	if(c->tw > c->w)
		c->tw = c->w + 2;
	c->tx = c->x + c->w - c->tw + 2;
	c->ty = c->y;
	XMoveResizeWindow(dpy, c->title, c->tx, c->ty, c->tw, c->th);
}

void
update_name(Client *c)
{
	XTextProperty name;
	int n;
	char **list = NULL;

	name.nitems = 0;
	c->name[0] = 0;
	XGetTextProperty(dpy, c->win, &name, net_atom[NetWMName]);
	if(!name.nitems)
		XGetWMName(dpy, c->win, &name);
	if(!name.nitems)
		return;
	if(name.encoding == XA_STRING)
		strncpy(c->name, (char *)name.value, sizeof(c->name));
	else {
		if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
				&& n > 0 && *list)
		{
			strncpy(c->name, *list, sizeof(c->name));
			XFreeStringList(list);
		}
	}
	XFree(name.value);
	resize_title(c);
}

void
update_size(Client *c)
{
	XSizeHints size;
	long msize;
	if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
		size.flags = PSize;
	c->flags = size.flags;
	if(c->flags & PBaseSize) {
		c->basew = size.base_width;
		c->baseh = size.base_height;
	}
	else
		c->basew = c->baseh = 0;
	if(c->flags & PResizeInc) {
		c->incw = size.width_inc;
		c->inch = size.height_inc;
	}
	else
		c->incw = c->inch = 0;
	if(c->flags & PMaxSize) {
		c->maxw = size.max_width;
		c->maxh = size.max_height;
	}
	else
		c->maxw = c->maxh = 0;
	if(c->flags & PMinSize) {
		c->minw = size.min_width;
		c->minh = size.min_height;
	}
	else
		c->minw = c->minh = 0;
	if(c->flags & PWinGravity)
		c->grav = size.win_gravity;
	else
		c->grav = NorthWestGravity;
}

void
craise(Client *c)
{
	XRaiseWindow(dpy, c->win);
	XRaiseWindow(dpy, c->title);
}

void
lower(Client *c)
{
	XLowerWindow(dpy, c->title);
	XLowerWindow(dpy, c->win);
}

void
focus(Client *c)
{
	Client **l, *old;

	old = stack;
	for(l = &stack; *l && *l != c; l = &(*l)->snext);
	if(*l)
		*l = c->snext;
	c->snext = stack;
	stack = c;
	if(old && old != c) {
		XMapWindow(dpy, old->title);
		draw_client(old);
	}
	XUnmapWindow(dpy, c->title);
	draw_client(c);
	XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
	XFlush(dpy);
}

void
manage(Window w, XWindowAttributes *wa)
{
	Client *c, **l;
	XSetWindowAttributes twa;

	c = emallocz(sizeof(Client));
	c->win = w;
	c->tx = c->x = wa->x;
	c->ty = c->y = wa->y;
	c->tw = c->w = wa->width;
	c->h = wa->height;
	c->th = th;
	c->border = 1;
	update_size(c);
	XSetWindowBorderWidth(dpy, c->win, 1);
	XSetWindowBorder(dpy, c->win, dc.border);
	XSelectInput(dpy, c->win,
			StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
	XGetTransientForHint(dpy, c->win, &c->trans);
	twa.override_redirect = 1;
	twa.background_pixmap = ParentRelative;
	twa.event_mask = ExposureMask;

	c->tags[tsel] = tags[tsel];
	c->title = XCreateWindow(dpy, root, c->tx, c->ty, c->tw, c->th,
			0, DefaultDepth(dpy, screen), CopyFromParent,
			DefaultVisual(dpy, screen),
			CWOverrideRedirect | CWBackPixmap | CWEventMask, &twa);

	update_name(c);
	for(l=&clients; *l; l=&(*l)->next);
	c->next = *l; /* *l == nil */
	*l = c;
	XMapRaised(dpy, c->win);
	XMapRaised(dpy, c->title);
	XGrabButton(dpy, Button1, Mod1Mask, c->win, False, ButtonPressMask,
			GrabModeAsync, GrabModeSync, None, None);
	XGrabButton(dpy, Button2, Mod1Mask, c->win, False, ButtonPressMask,
			GrabModeAsync, GrabModeSync, None, None);
	XGrabButton(dpy, Button3, Mod1Mask, c->win, False, ButtonPressMask,
			GrabModeAsync, GrabModeSync, None, None);
	arrange();
	focus(c);
}

void
gravitate(Client *c, Bool invert)
{
	int dx = 0, dy = 0;

	switch(c->grav) {
	case StaticGravity:
	case NorthWestGravity:
	case NorthGravity:
	case NorthEastGravity:
		dy = c->border;
		break;
	case EastGravity:
	case CenterGravity:
	case WestGravity:
		dy = -(c->h / 2) + c->border;
		break;
	case SouthEastGravity:
	case SouthGravity:
	case SouthWestGravity:
		dy = -c->h;
		break;
	default:
		break;
	}

	switch (c->grav) {
	case StaticGravity:
	case NorthWestGravity:
	case WestGravity:
	case SouthWestGravity:
		dx = c->border;
		break;
	case NorthGravity:
	case CenterGravity:
	case SouthGravity:
		dx = -(c->w / 2) + c->border;
		break;
	case NorthEastGravity:
	case EastGravity:
	case SouthEastGravity:
		dx = -(c->w + c->border);
		break;
	default:
		break;
	}

	if(invert) {
		dx = -dx;
		dy = -dy;
	}
	c->x += dx;
	c->y += dy;
}


void
resize(Client *c)
{
	XConfigureEvent e;

	if(c->incw)
		c->w -= (c->w - c->basew) % c->incw;
	if(c->inch)
		c->h -= (c->h - c->baseh) % c->inch;
	if(c->minw && c->w < c->minw)
		c->w = c->minw;
	if(c->minh && c->h < c->minh)
		c->h = c->minh;
	if(c->maxw && c->w > c->maxw)
		c->w = c->maxw;
	if(c->maxh && c->h > c->maxh)
		c->h = c->maxh;
	resize_title(c);
	XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
	e.type = ConfigureNotify;
	e.event = c->win;
	e.window = c->win;
	e.x = c->x;
	e.y = c->y;
	e.width = c->w;
	e.height = c->h;
	e.border_width = c->border;
	e.above = None;
	e.override_redirect = False;
	XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&e);
	XFlush(dpy);
}

static int
dummy_error_handler(Display *dsply, XErrorEvent *err)
{
	return 0;
}

void
unmanage(Client *c)
{
	Client **l;

	XGrabServer(dpy);
	XSetErrorHandler(dummy_error_handler);

	XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
	XDestroyWindow(dpy, c->title);

	for(l=&clients; *l && *l != c; l=&(*l)->next);
	*l = c->next;
	for(l=&stack; *l && *l != c; l=&(*l)->snext);
	*l = c->snext;
	free(c);

	XFlush(dpy);
	XSetErrorHandler(error_handler);
	XUngrabServer(dpy);
	arrange();
	if(stack)
		focus(stack);
}

Client *
gettitle(Window w)
{
	Client *c;
	for(c = clients; c; c = c->next)
		if(c->title == w)
			return c;
	return NULL;
}

Client *
getclient(Window w)
{
	Client *c;
	for(c = clients; c; c = c->next)
		if(c->win == w)
			return c;
	return NULL;
}

void
draw_client(Client *c)
{
	int i;
	if(c == stack)
		return;

	dc.x = dc.y = 0;
	dc.h = c->th;

	dc.w = 0;
	for(i = 0; i < TLast; i++) {
		if(c->tags[i]) {
			dc.x += dc.w;
			dc.w = textw(&dc.font, c->tags[i]) + dc.font.height;
			draw(True, c->tags[i]);
		}
	}
	dc.x += dc.w;
	dc.w = textw(&dc.font, c->name) + dc.font.height;
	draw(True, c->name);
	XCopyArea(dpy, dc.drawable, c->title, dc.gc,
			0, 0, c->tw, c->th, 0, 0);
	XFlush(dpy);
}
f the caller does not specify them: .. code-block:: nimrod proc createWindow(x = 0, y = 0, width = 500, height = 700, title = "unknown", show = true): Window = ... var w = createWindow(title = "My Application", height = 600, width = 800) Now the call to ``createWindow`` only needs to set the values that differ from the defaults. Note that type inference works for parameters with default values, there is no need to specify ``title: string = "unknown"``, for example. Overloaded procedures --------------------- Nimrod provides the ability to overload procedures similar to C++: .. code-block:: nimrod proc toString(x: int): string = ... proc toString(x: bool): string = if x: return "true" else: return "false" Echo(toString(13)) # calls the toString(x: int) proc Echo(toString(true)) # calls the toString(x: bool) proc (Note that ``toString`` is usually the ``$`` operator in Nimrod.) The compiler chooses the most appropriate proc for the ``toString`` calls. How this overloading resolution algorithm works exactly is not discussed here (it will be specified in the manual soon). However, it does not lead to nasty suprises and is based on a quite simple unification algorithm. Ambiguous calls are reported as errors. Operators --------- The Nimrod library makes heavy use of overloading - one reason for this is that each operator like ``+`` is a just an overloaded proc. The parser lets you use operators in `infix notation` (``a + b``) or `prefix notation` (``+ a``). An infix operator always receives two arguments, a prefix operator always one. Postfix operators are not possible, because this would be ambiguous: Does ``a @ @ b`` mean ``(a) @ (@b)`` or ``(a@) @ (b)``? It always means ``(a) @ (@b)``, because there are no postfix operators in Nimrod. Apart from a few built-in keyword operators such as ``and``, ``or``, ``not``, operators always consist of these characters: ``+ - * \ / < > = @ $ ~ & % ! ? ^ . |`` User defined operators are allowed. Nothing stops you from defining your own ``@!?+~`` operator, but readability can suffer. The operator's precedence is determined by its first character. The details can be found in the manual. To define a new operator enclose the operator in "``": .. code-block:: nimrod proc `$` (x: myDataType): string = ... # now the $ operator also works with myDataType, overloading resolution # ensures that $ works for built-in types just like before The "``" notation can also be used to call an operator just like a procedure with a real name: .. code-block:: nimrod if `==`( `+`(3, 4), 7): Echo("True") Forward declarations -------------------- Every variable, procedure, etc. needs to be declared before it can be used. (The reason for this is compilation efficiency.) However, this cannot be done for mutually recursive procedures: .. code-block:: nimrod # forward declaration: proc even(n: int): bool proc odd(n: int): bool = if n == 1: return true else: return even(n-1) proc even(n: int): bool = if n == 0: return true else: return odd(n-1) Here ``odd`` depends on ``even`` and vice versa. Thus ``even`` needs to be introduced to the compiler before it is completely defined. The syntax for such a `forward declaration` is simple: Just omit the ``=`` and the procedure's body. Iterators ========= Let's return to the boring counting example: .. code-block:: nimrod Echo("Counting to ten: ") for i in countup(1, 10): Echo($i) Can a ``countup`` proc be written that supports this loop? Lets try: .. code-block:: nimrod proc countup(a, b: int): int = var res = a while res <= b: return res inc(res) However, this does not work. The problem is that the procedure should not only ``return``, but return and **continue** after an iteration has finished. This *return and continue* is called a `yield` statement. Now the only thing left to do is to replace the ``proc`` keyword by ``iterator`` and there it is - our first iterator: .. code-block:: nimrod iterator countup(a, b: int): int = var res = a while res <= b: yield res inc(res) Iterators look very similar to procedures, but there are several important differences: * Iterators can only be called from for loops. * Iterators cannot contain a ``return`` statement and procs cannot contain a ``yield`` statement. * Iterators have no implicit ``result`` variable. * Iterators do not support recursion. (This restriction will be gone in a future version of the compiler.) * Iterators cannot be forward declared, because the compiler must be able to inline an iterator. (This restriction will be gone in a future version of the compiler.) Basic types =========== This section deals with the basic built-in types and the operations that are available for them in detail. Booleans -------- The `boolean`:idx: type is named ``bool`` in Nimrod and consists of the two pre-defined values ``true`` and ``false``. Conditions in while, if, elif, when statements need to be of type bool. The operators ``not, and, or, xor, <, <=, >, >=, !=, ==`` are defined for the bool type. The ``and`` and ``or`` operators perform short-cut evaluation. Example: .. code-block:: nimrod while p != nil and p.name != "xyz": # p.name is not evaluated if p == nil p = p.next Characters ---------- The `character type` is named ``char`` in Nimrod. Its size is one byte. Thus it cannot represent an UTF-8 character, but a part of it. The reason for this is efficiency: For the overwhelming majority of use-cases, the resulting programs will still handle UTF-8 properly as UTF-8 was specially designed for this. Character literals are enclosed in single quotes. Chars can be compared with the ``==``, ``<``, ``<=``, ``>``, ``>=`` operators. The ``$`` operator converts a ``char`` to a ``string``. Chars cannot be mixed with integers; to get the ordinal value of a ``char`` use the ``ord`` proc. Converting from an integer to a ``char`` is done with the ``chr`` proc. Strings ------- String variables in Nimrod are **mutable**, so appending to a string is quite efficient. Strings in Nimrod are both zero-terminated and have a length field. One can retrieve a string's length with the builtin ``len`` procedure; the length never counts the terminating zero. Accessing the terminating zero is no error and often leads to simpler code: .. code-block:: nimrod if s[i] == 'a' and s[i+1] == 'b' and s[i+2] == '\0': # no need to check whether ``i < len(s)``! ... The assignment operator for strings copies the string. Strings are compared by their lexicographical order. All comparison operators are available. Per convention, all strings are UTF-8 strings, but this is not enforced. For example, when reading strings from binary files, they are merely a sequence of bytes. The index operation ``s[i]`` means the i-th *char* of ``s``, not the i-th *unichar*. String variables are initialized with a special value, called ``nil``. However, most string operations cannot deal with ``nil`` (leading to an exception being raised) for performance reasons. Thus one should use empty strings ``""`` rather than ``nil`` as the *empty* value. But ``""`` often creates a string object on the heap, so there is a trade-off to be made here. Integers -------- Nimrod has these integer types built-in: ``int int8 int16 int32 int64``. These are all signed integer types, there are no `unsigned integer`:idx: types, only `unsigned operations`:idx: that treat their arguments as unsigned. The default integer type is ``int``. Integer literals can have a *type suffix* to mark them to be of another integer type: .. code-block:: nimrod var x = 0 # x is of type ``int`` y = 0'i8 # y is of type ``int8`` z = 0'i64 # z is of type ``int64`` Most often integers are used for couting objects that reside in memory, so ``int`` has the same size as a pointer. The common operators ``+ - * div mod < <= == != > >=`` are defined for integers. The ``and or xor not`` operators are defined for integers too and provide *bitwise* operations. Left bit shifting is done with the ``shl``, right shifting with the ``shr`` operator. Bit shifting operators always treat their arguments as *unsigned*. For `arithmetic bit shifts`:idx: ordinary multiplication or division can be used. Unsigned operations all wrap around; they cannot lead to over- or underflow errors. Unsigned operations use the ``%`` suffix as convention: ====================== ====================================================== operation meaning ====================== ====================================================== ``a +% b`` unsigned integer addition ``a -% b`` unsigned integer substraction ``a *% b`` unsigned integer multiplication ``a /% b`` unsigned integer division ``a %% b`` unsigned integer modulo operation ``a <% b`` treat ``a`` and ``b`` as unsigned and compare ``a <=% b`` treat ``a`` and ``b`` as unsigned and compare ====================== ====================================================== `Automatic type conversion`:idx: is performed in expressions where different kinds of integer types are used. However, if the type conversion loses information, the `EOutOfRange`:idx: exception is raised (if the error cannot be detected at compile time). Floats ------ Nimrod has these floating point types built-in: ``float float32 float64``. The default float type is ``float``. In the current implementation, ``float`` is always 64 bit wide. Float literals can have a *type suffix* to mark them to be of another float type: .. code-block:: nimrod var x = 0.0 # x is of type ``float`` y = 0.0'f32 # y is of type ``float32`` z = 0.0'f64 # z is of type ``int64`` The common operators ``+ - * / < <= == != > >=`` are defined for floats and follow the IEEE standard. Automatic type conversion in expressions with different kinds of floating point types is performed: The smaller type is converted to the larger. Integer types are **not** converted to floating point types automatically and vice versa. The ``toInt`` and ``toFloat`` procs can be used for these conversions. Advanced types ============== In Nimrod new types can be defined within a ``type`` statement: .. code-block:: nimrod type biggestInt = int64 # biggest integer type that is available biggestFloat = float64 # biggest float type that is available Enumeration and object types cannot be defined on the fly, but only within a ``type`` statement. Enumerations ------------ A variable of an `enumeration`:idx: type can only be assigned a value of a limited set. This set consists of ordered symbols. Each symbol is mapped to an integer value internally. The first symbol is represented at runtime by 0, the second by 1 and so on. Example: .. code-block:: nimrod type TDirection = enum north, east, south, west var x = south # `x` is of type `TDirection`; its value is `south` echo($x) # writes "south" to `stdout` (To prefix a new type with the letter ``T`` is a convention in Nimrod.) All comparison operators can be used with enumeration types. An enumeration's symbol can be qualified to avoid ambiguities: ``TDirection.south``. The ``$`` operator can convert any enumeration value to its name, the ``ord`` proc to its underlying integer value. For better interfacing to other programming languages, the symbols of enum types can be assigned an explicit ordinal value. However, the ordinal values have to be in ascending order. A symbol whose ordinal value is not explicitly given is assigned the value of the previous symbol + 1. An explicit ordered enum can have *wholes*: .. code-block:: nimrod type TMyEnum = enum a = 2, b = 4, c = 89 Ordinal types ------------- Enumerations without wholes, integer types, ``char`` and ``bool`` (and subranges) are called `ordinal`:idx: types. Ordinal types have quite a few special operations: ----------------- -------------------------------------------------------- Operation Comment ----------------- -------------------------------------------------------- ``ord(x)`` returns the integer value that is used to represent `x`'s value ``inc(x)`` increments `x` by one ``inc(x, n)`` increments `x` by `n`; `n` is an integer ``dec(x)`` decrements `x` by one ``dec(x, n)`` decrements `x` by `n`; `n` is an integer ``succ(x)`` returns the successor of `x` ``succ(x, n)`` returns the `n`'th successor of `x` ``prec(x)`` returns the predecessor of `x` ``pred(x, n)`` returns the `n`'th predecessor of `x` ----------------- -------------------------------------------------------- The ``inc dec succ pred`` operations can fail by raising an `EOutOfRange` or `EOverflow` exception. (If the code has been compiled with the proper runtime checks turned on.) Subranges --------- A `subrange`:idx: type is a range of values from an integer or enumeration type (the base type). Example: .. code-block:: nimrod type TSubrange = range[0..5] ``TSubrange`` is a subrange of ``int`` which can only hold the values 0 to 5. Assigning any other value to a variable of type ``TSubrange`` is a compile-time or runtime error. Assignments from the base type to one of its subrange types (and vice versa) are allowed. The ``system`` module defines the important ``natural`` type as ``range[0..high(int)]`` (``high`` returns the maximal value). Other programming languages mandate the usage of unsigned integers for natural numbers. This is often **wrong**: You don't want unsigned arithmetic (which wraps around) just because the numbers cannot be negative. Nimrod's ``natural`` type helps to avoid this common programming error. Sets ---- The `set type`:idx: models the mathematical notion of a set. The set's basetype can only be an ordinal type. The reason is that sets are implemented as high performance bit vectors. Sets can be constructed via the set constructor: ``{}`` is the empty set. The empty set is type compatible with any concrete set type. The constructor can also be used to include elements (and ranges of elements): .. code-block:: nimrod type TCharSet = set[char] var x: TCharSet x = {'a'..'z', '0'..'9'} # This constructs a set that conains the # letters from 'a' to 'z' and the digits # from '0' to '9' These operations are supported by sets: ================== ======================================================== operation meaning ================== ======================================================== ``A + B`` union of two sets ``A * B`` intersection of two sets ``A - B`` difference of two sets (A without B's elements) ``A == B`` set equality ``A <= B`` subset relation (A is subset of B or equal to B) ``A < B`` strong subset relation (A is a real subset of B) ``e in A`` set membership (A contains element e) ``e notin A`` A does not contain element e ``contains(A, e)`` A contains element e ``A -+- B`` symmetric set difference (= (A - B) + (B - A)) ``card(A)`` the cardinality of A (number of elements in A) ``incl(A, elem)`` same as ``A = A + {elem}`` ``excl(A, elem)`` same as ``A = A - {elem}`` ================== ======================================================== Sets are often used to define a type for the *flags* of a procedure. This is much cleaner (and type safe) solution than just defining integer constants that should be ``or``'ed together. Arrays ------ An `array`:idx: is a simple fixed length container. Each element in the array has the same type. The array's index type can be any ordinal type. Arrays can be constructed via the array constructor: ``[]`` is the empty array. The constructor can also be used to include elements. .. code-block:: nimrod type TIntArray = array[0..5, int] # an array that is indexed with 0..5 var x: TIntArray x = [1, 2, 3, 4, 5, 6] for i in low(x)..high(x): echo(x[i]) The notation ``x[i]`` is used to access the i-th element of ``x``. Array access is always bounds checked (at compile-time or at runtime). These checks can be disabled via pragmas or invoking the compiler with the ``--bound_checks:off`` command line switch. Arrays are value types, like any other Nimrod type. The assignment operator copies the whole array contents. The built-in ``len`` proc returns the array's length. ``low(a)`` returns the lowest valid index for the array `a` and ``high(a)`` the highest valid index. Sequences --------- `Sequences`:idx: are similar to arrays but of dynamic length which may change during runtime (like strings). Since sequences are resizeable they are always allocated on the heap and garbage collected. Sequences are always indexed with an ``int`` starting at position 0. The ``len``, ``low`` and ``high`` operations are available for sequences too. The notation ``x[i]`` can be used to access the i-th element of ``x``. Sequences can be constructed by the array constructor ``[]`` in conjunction with the array to sequence operator ``@``. Another way to allocate space for a sequence is to call the built-in ``newSeq`` procedure. A sequence may be passed to an openarray parameter. Example: .. code-block:: nimrod var x: seq[int] # a sequence of integers x = @[1, 2, 3, 4, 5, 6] # the @ turns the array into a sequence Sequence variables are initialized with ``nil``. However, most sequence operations cannot deal with ``nil`` (leading to an exception being raised) for performance reasons. Thus one should use empty sequences ``@[]`` rather than ``nil`` as the *empty* value. But ``@[]`` creates a sequence object on the heap, so there is a trade-off to be made here. Open arrays ----------- **Note**: Openarrays can only be used for parameters. Often fixed size arrays turn out to be too inflexible; procedures should be able to deal with arrays of different sizes. The `openarray`:idx: type allows this. Openarrays are always indexed with an ``int`` starting at position 0. The ``len``, ``low`` and ``high`` operations are available for open arrays too. Any array with a compatible base type can be passed to an openarray parameter, the index type does not matter. The openarray type cannot be nested: Multidimensional openarrays are not supported because this is seldom needed and cannot be done efficiently. An openarray is also a means to implement passing a variable number of arguments to a procedure. The compiler converts the list of arguments to an array automatically: .. code-block:: nimrod proc myWriteln(f: TFile, a: openarray[string]) = for s in items(a): write(f, s) write(f, "\n") myWriteln(stdout, "abc", "def", "xyz") # is transformed by the compiler to: myWriteln(stdout, ["abc", "def", "xyz"]) This transformation is only done if the openarray parameter is the last parameter in the procedure header. Tuples ------ A tuple type defines various named *fields* and an *order* of the fields. The constructor ``()`` can be used to construct tuples. The order of the fields in the constructor must match the order in the tuple's definition. Different tuple-types are *equivalent* if they specify the same fields of the same type in the same order. The assignment operator for tuples copies each component. The notation ``t.field`` is used to access a tuple's field. Another notation is ``t[i]`` to access the ``i``'th field. Here ``i`` needs to be a constant integer. .. code-block:: nimrod type TPerson = tuple[name: string, age: int] # type representing a person: # a person consists of a name # and an age var person: TPerson person = (name: "Peter", age: 30) # the same, but less readable: person = ("Peter", 30) echo(person.name) # "Peter" echo(person.age) # 30 echo(person[0]) # "Peter" echo(person[1]) # 30 Reference and pointer types --------------------------- References (similiar to `pointers`:idx: in other programming languages) are a way to introduce many-to-one relationships. This means different references can point to and modify the same location in memory. Nimrod distinguishes between `traced`:idx: and `untraced`:idx: references. Untraced references are also called *pointers*. Traced references point to objects of a garbage collected heap, untraced references point to manually allocated objects or to objects somewhere else in memory. Thus untraced references are *unsafe*. However for certain low-level operations (accessing the hardware) untraced references are unavoidable. Traced references are declared with the **ref** keyword, untraced references are declared with the **ptr** keyword. The ``^`` operator can be used to *derefer* a reference, meaning to retrieve the item the reference points to. The ``addr`` procedure returns the address of an item. An address is always an untraced reference: ``addr`` is an *unsafe* feature. The ``.`` (access a tuple/object field operator) and ``[]`` (array/string/sequence index operator) operators perform implicit dereferencing operations for reference types: .. code-block:: nimrod type PNode = ref TNode TNode = tuple[le, ri: PNode, data: int] var n: PNode new(n) n.data = 9 # no need to write n^ .data (As a convention, reference types use a 'P' prefix.) To allocate a new traced object, the built-in procedure ``new`` has to be used. To deal with untraced memory, the procedures ``alloc``, ``dealloc`` and ``realloc`` can be used. The documentation of the system module contains further information. If a reference points to *nothing*, it has the value ``nil``. Special care has to be taken if an untraced object contains traced objects like traced references, strings or sequences: In order to free everything properly, the built-in procedure ``GCunref`` has to be called before freeing the untraced memory manually: .. code-block:: nimrod type TData = tuple[x, y: int, s: string] # allocate memory for TData on the heap: var d = cast[ptr TData](alloc0(sizeof(TData))) # create a new string on the garbage collected heap: d.s = "abc" # tell the GC that the string is not needed anymore: GCunref(d.s) # free the memory: dealloc(d) Without the ``GCunref`` call the memory allocated for the ``d.s`` string would never be freed. The example also demonstrates two important features for low level programming: The ``sizeof`` proc returns the size of a type or value in bytes. The ``cast`` operator can circumvent the type system: The compiler is forced to treat the result of the ``alloc0`` call (which returns an untyped pointer) as if it would have the type ``ptr TData``. Casting should only be done if it is unavoidable: It breaks type safety and bugs can lead to mysterious crashes. **Note**: The example only works because the memory is initialized with zero (``alloc0`` instead of ``alloc`` does this): ``d.s`` is thus initialized to ``nil`` which the string assignment can handle. You need to know low level details like this when mixing garbage collected data with unmanaged memory! Procedural type --------------- A `procedural type`:idx: is a (somewhat abstract) pointer to a procedure. ``nil`` is an allowed value for a variable of a procedural type. Nimrod uses procedural types to achieve `functional`:idx: programming techniques. Dynamic dispatch for OOP constructs can also be implemented with procedural types (details follow in the OOP section). Example: .. code-block:: nimrod type TCallback = proc (x: int) proc echoItem(x: Int) = echo(x) proc forEach(callback: TCallback) = const data = [2, 3, 5, 7, 11] for d in items(data): callback(d) forEach(echoItem) A subtle issue with procedural types is that the calling convention of the procedure influences the type compability: Procedural types are only compatible if they have the same calling convention. The different calling conventions are listed in the `user guide <nimrodc.html>`_. Modules ======= Nimrod supports splitting a program into pieces with a `module`:idx: concept. Each module is in its own file. Modules enable `information hiding`:idx: and `separate compilation`:idx:. A module may gain access to symbols of another module by the `import`:idx: statement. Only top-level symbols that are marked with an asterisk (``*``) are exported: .. code-block:: nimrod # Module A var x*, y: int proc `*` *(a, b: seq[int]): seq[int] = # allocate a new sequence: newSeq(result, len(a)) # multiply two int sequences: for i in 0..len(a)-1: result[i] = a[i] * b[i] when isMainModule: # test the new ``*`` operator for sequences: assert(@[1, 2, 3] * @[1, 2, 3] == @[1, 4, 9]) The above module exports ``x`` and ``*``, but not ``y``. The top-level statements of a module are executed at the start of the program. This can be used to initalize complex data structures for example. Each module has a special magic constant ``isMainModule`` that is true if the module is compiled as the main file. This is very useful to embed tests within the module as shown by the above example. Modules that depend on each other are possible, but strongly discouraged, because then one module cannot be reused without the other. The algorithm for compiling modules is: - Compile the whole module as usual, following import statements recursively - if there is a cycle only import the already parsed symbols (that are exported); if an unknown identifier occurs then abort This is best illustrated by an example: .. code-block:: nimrod # Module A type T1* = int # Module A exports the type ``T1`` import B # the compiler starts parsing B proc main() = var i = p(3) # works because B has been parsed completely here main() # Module B import A # A is not parsed here! Only the already known symbols # of A are imported. proc p*(x: A.T1): A.T1 = # this works because the compiler has already # added T1 to A's interface symbol table return x + 1 A symbol of a module *can* be *qualified* with the ``module.symbol`` syntax. If the symbol is ambiguous, it even *has* to be qualified. A symbol is ambiguous if it is defined in two (or more) different modules and both modules are imported by a third one: .. code-block:: nimrod # Module A var x*: string # Module B var x*: int # Module C import A, B write(stdout, x) # error: x is ambiguous write(stdout, A.x) # no error: qualifier used var x = 4 write(stdout, x) # not ambiguous: uses the module C's x But this rule does not apply to procedures or iterators. Here the overloading rules apply: .. code-block:: nimrod # Module A proc x*(a: int): string = return $a # Module B proc x*(a: string): string = return $a # Module C import A, B write(stdout, x(3)) # no error: A.x is called write(stdout, x("")) # no error: B.x is called proc x*(a: int): string = nil write(stdout, x(3)) # ambiguous: which `x` is to call? From statement -------------- We have already seen the simple ``import`` statement that just imports all exported symbols. An alternative that only imports listed symbols is the ``from import`` statement: .. code-block:: nimrod from mymodule import x, y, z Include statement ----------------- The `include`:idx: statement does something fundametally different than importing a module: It merely includes the contents of a file. The ``include`` statement is useful to split up a large module into several files: .. code-block:: nimrod include fileA, fileB, fileC **Note**: The documentation generator currently does not follow ``include`` statements, so exported symbols in an include file will not show up in the generated documentation. Part 2 ====== So, now that we are done with the basics, let's see what Nimrod offers apart from a nice syntax for procedural programming: `Part II <tut2.html>`_ .. _strutils: strutils.html .. _system: system.html