1NICKLE(1) General Commands Manual NICKLE(1)
2
3
4
6 nickle - a desk calculator language
7
9 nickle [--help|--usage] [-f file] [-l library] [-e expr] [ script ]
10 [--] [arg ...]
11
13 Nickle is a desk calculator language with powerful programming and
14 scripting capabilities. Nickle supports a variety of datatypes, espe‐
15 cially arbitrary precision integers, rationals, and imprecise reals.
16 The input language vaguely resembles C. Some things in C which do not
17 translate easily are different, some design choices have been made dif‐
18 ferently, and a very few features are simply missing.
19
21 An un-flagged argument is treated as a Nickle script, and replaces
22 standard input. Any remaining arguments following the script are
23 placed in the Nickle string array argv for programmatic inspection.
24 When invoked without an expression or script argument, Nickle reads
25 from standard input, and writes to standard output.
26
27 Options are as follows:
28
29 --help,--usage
30 Print a help/usage message and exit. This is a built-in feature
31 of Nickle's ParseArgs module, and thus will also be true of
32 Nickle scripts that use this library.
33
34 -f,--file file
35 Load file into Nickle before beginning execution.
36
37 -l,--library library
38 Load library into Nickle before beginning execution. See below
39 for a description of the library facility.
40
41 -e,--expr expr
42 Evaluate expr before beginning execution.
43
44 -- Quit parsing arguments and pass the remainder, unevaluated, to
45 argv.
46
48 To make the input language more useful in an interactive setting, new‐
49 line only terminates statements at ``reasonable'' times. Newline ter‐
50 minates either expressions or single statements typed by the user (with
51 the exception of a few statements which require lookahead: notably if()
52 and twixt(), which have an optional else part). Inside compound state‐
53 ments or function definitions, only a ; terminates statements. This
54 approach is convenient and does not appear to cause problems in normal
55 use.
56
57 The syntax of Nickle programs is as follows. In this description, name
58 denotes any sequence of letters, digits and _ characters not starting
59 with a digit; E denotes any expression; S denotes any statement; and T
60 denotes any type. The syntax X,X,...,X denotes one or more comma-sepa‐
61 rated Xs, unless otherwise indicated.
62
63 Comments:
64
65 C-style comments are enclosed in /* and */, and shell-style comments
66 are denoted by a leading # at the start of a line.
67
68 Operands:
69
70 real number
71 Can include exponent, need not include decimal point or sign.
72 Will be treated as exact rationals. If a trailing decimal part
73 contains an opening curly brace, the brace is silently ignored;
74 if it contains a curly-bracketed trailing portion, it is treated
75 as a repeating decimal. `Floating point'' constants are cur‐
76 rently represented internally as rationals: for floating con‐
77 stants with a given precision (and an infinite-precision expo‐
78 nent), use the imprecise() builtin function described below.
79
80 octal number
81 Start with a 0 (e.g., 014 is the same as 12).
82
83 hexidecimal number
84 Start with "0x" (e.g., 0x1a is the same as 26).
85
86 string As in C. String constants are surrounded by double-quotes.
87 Backslashed characters (including double-quotes) stand for them‐
88 selves, except "\n" stands for newline, "\r" for carriage
89 return, "\b" for backspace, "\t" for tab and "\f" for formfeed.
90
91 name A variable reference.
92
93 name() name(E,E,...,E)
94 A function call with zero or more arguments. Functions are
95 fully call-by-value: arrays and structures are copied rather
96 than being referenced as in C.
97
98 desc name T name = value
99 Definition expressions: a new name is made available, with the
100 value of the definition being the value of the initializer in
101 the second form, and uninitialized in the first form. The
102 descriptor desc is not optional: it consists of any combination
103 of visibility, storage class or type (in that order). See QUAL‐
104 IFIERS immediately below for a description of these qualifiers.
105 A structured value expression is also possible: see VALUES
106 below.
107
108 In addition to being able to initialize a definition with a
109 Nickle value, C-style array, structure, and union definitions
110 are also allowed: For example, the following
111 int[*,*] name = {{0,1},{2,3}}
112 int[2,2] name = {{0...}...}
113 are permitted with the obvious semantics. This is the context
114 in which the dimensions in a type may be expressions: see the
115 discussion of array types above. See the discussion of array
116 and structure values for array and structure initializer syntax.
117
119 A declaration or definition may be qualified, as in C, to indicate
120 details of programmatic behavior. Unlike in C, these qualifiers, while
121 optional, must appear in the given order.
122
123 Visibility:
124
125 public Any definition expression (function definition, variable defini‐
126 tion, type definition) can be qualified with public to indicate
127 that the name being defined should be visible outside the cur‐
128 rent namespace, and should be automatically imported. See
129 Namespaces below for further info.
130
131 protected
132 Any definition expression (function definition, variable defini‐
133 tion, type definition) can be qualified with protected to indi‐
134 cate that the name being defined should be visible outside the
135 current namespace, but should not be made available by import
136 declarations. See Namespaces below for further info.
137
138 Lifetime:
139
140 auto An auto object is local to a particular block: its lifetime is
141 at least the lifetime of that block. An auto object with an
142 initializer will be re-initialized each time it is evaluated.
143 This is the default lifetime for local objects.
144
145 static A static object is local to a particular function definition:
146 its lifetime is at least the lifetime of that definition. A new
147 static object will be created each time its enclosing function
148 definition is evaluated.
149
150 In Nickle, the keyword static has to do only with lifetime (like
151 the use of static inside C functions), not with visibility
152 (which is handled by separate qualifiers as described above, not
153 like the use of static in global scope in C).
154
155 global A global object is global to the entire program: its lifetime is
156 the lifetime of the program. A global object will be created
157 and initialized when its definition is first seen. This is the
158 default lifetime for global objects.
159
160 The distinction between static and global lifetime in Nickle is
161 not possible in C, because C functions are not first class
162 objects with nested scope. When deciding which to use in a
163 Nickle program, think about what should happen if a definition
164 is re-evaluated.
165
167 Here are the basic Nickle operators, grouped in order of decreasing
168 precedence:
169
170 A[E,E,...,E]
171 Refers to the E'th element of the array expression A, or the
172 E1'th/E2'th/etc element of a multi-dimensional array. Both
173 arrays of arrays ala C and multidimensional arrays ala NAWK are
174 possible.
175
176 struct.tag
177 Structure dereference.
178
179 struct->tag
180 Structure pointer dereference ala C.
181
182 =============
183
184 ++ -- Unary increment/decrement. May be either postfix or prefix.
185
186 - Unary negate
187
188 ! E Logical negation.
189
190 E ! Factorial. Requires a non-negative integer argument.
191
192 * E Pointer dereference.
193
194 & E Reference construction.
195
196 =============
197
198 (U) E Construct a value of union type with tag U and value E.
199
200 =============
201
202 ** Exponentiation. Both operands may be fractional. The left oper‐
203 and must be non-negative unless the right operand is integer.
204 The result type is the type of the left operand if the right op‐
205 erand is integer, and real otherwise.
206
207 This is the only known type-unsound feature of Nickle: an
208 expression like 2 ** -3 will statically be of type integer, but
209 dynamically will generate a rational result. This may cause a
210 runtime type error later on: consider
211 int x = 2 ** -3;
212
213 =============
214
215 * / // %
216 Times, divide, integer divide, and remainder. The right operand
217 of the last three operators must be nonzero. The result type of
218 the division operator will always be at least rational: the
219 result type of the integer division operator will always be int.
220 This is a notable departure from C, where integer division is
221 implied by integer operands. Integer division is defined by
222 x // y == y > 0 ? floor (x / y) : ceil(x / y)
223 The remainder is always non-negative and is defined by: by
224 x % y = x - (x // y) * y
225
226 =============
227
228 + - Addition and subtraction.
229
230 =============
231
232 << >> Bitwise left and right shift with integer operands. Negative
233 right operands work as expected. These operators are defined by
234 x << y = x * 2 ** y
235 x >> y = x // 2 ** y
236 Another way to look at this is that negative left operands are
237 considered to be in an infinite twos-complement representation
238 (i.e., sign-extended to infinity), with right shift sign-extend‐
239 ing its left operand.
240
241 =============
242
243 <= >= < >
244 Relational operators.
245
246 =============
247
248 == != Equality operators.
249
250 =============
251 Finally, in order of decreasing precedence:
252
253 & Bitwise AND. Negative operands are considered to be in an infi‐
254 nite twos-complement representation (i.e., sign-extended to
255 infinity).
256
257 ^ Bitwise XOR. Negative operands as in bitwise AND.
258
259 | Bitwise OR. Negative operands as in bitwise AND.
260
261 && Short-circuit logical AND.
262
263 || Short-circuit logical OR.
264
265 E ? E : E
266 Conditional expression: if first expression is logical true,
267 value is second expression, else third.
268
269 fork E Create (and return) a thread. See Thread below for details.
270
271 = += -= *= /= //= %= **= <<= >>= ^= &= |=
272 Assignment operators. Left-hand-side must be assignable. x
273 <op>= y is equivalent to x = x <op> y
274
275 E , E Returns right-hand expression.
276
278 The type declaration syntax of Nickle more strongly resembles the
279 ``left'' variant of the Java syntax than the C syntax. Essentially, a
280 type consists of:
281
282 poly integer rational real string continuation void
283 A base type of the language. Type void is actually only usable
284 in certain contexts, notably function returns. It is currently
285 implemented as a ``unit'' type ala ML, and thus has slightly
286 different behavior than in C. Type poly is the supertype of all
287 other types (i.e., it can be used to inhibit static type check‐
288 ing), and is the default type in most situations where a type
289 need not appear.
290
291 file semaphore thread
292 Also builtin base types, but integral to the File and Thread
293 ADTs: see below.
294
295 More About Types:
296
297 Nickle supports polymorphic data: As an expression is evaluated, a data
298 type is chosen to fit the result. Any Nickle object may be statically
299 typed, in which case bounds violations will be flagged as errors at
300 compile time. Polymorphic variables and functions do not place
301 restrictions on the assigned data type; this is the default type for
302 all objects.
303
304 poly This describes the union of all datatypes. A variable with this
305 type can contain any data value.
306
307 int Arbitrary precision integers.
308
309 rational
310 Arbitrary precision rational numbers.
311
312 real Arbitrary exponent precision floating point numbers. As many
313 computations cannot be carried out exactly as rational numbers,
314 Nickle implements non-precise arithmetic using its own machine-
315 independent representation for floating point numbers. The
316 builtin function imprecise(n) generates a real number with 256
317 bits of precision from the number n, while imprecise(n,p) gener‐
318 ates a real number with p bits of precision.
319
320 T[] An array of type T, of one or more dimensions. There are no
321 zero-dimensional arrays in Nickle.
322
323 T[*] A one-dimensional array of type T. Unlike in C, the dimension
324 of an array is never part of its type in Nickle. Further,
325 arrays and pointers are unrelated types in Nickle.
326
327 T[*,*,...,*]
328 A two or more dimensional array of type T. The stars ``*'' are
329 not optional. As the previous paragraphs make clear, ``T[]'' is
330 not a zero-dimensional array.
331
332 T[E,E,...,E]
333 In definition contexts, integer values may be given for each
334 dimension of an array context. These are strictly for value-
335 creation purposes, and are not part of the type. An array type
336 is determined only by the base type and number of dimensions of
337 the array.
338
339 T0() T0(T,T,...,T)
340 A function returning type T0. A function accepts 0 or more
341 arguments.
342
343 T0() T0(T,T,...,T ...)
344 A function accepting zero or more required arguments, plus an
345 arbitrary number of optional arguments. The second sequence of
346 three dots (ellipsis) is syntax, not metasyntax: see the
347 description of varargs functions for details.
348
349 *T A pointer to a location of type T. Pointer arithmetic in Nickle
350 operates only upon pointers to arrays: the pointer must be of
351 the correct type, and may never stray out of bounds. A pointer
352 may either point to some location or be null (0). As in C, the
353 precedence of ``*'' is lower than the precedence of ``[]'' or
354 ``()'': use parenthesis as needed.
355
356 struct {T name; T name; ...}
357 A structure with fields of the given name and type. The types T
358 are optional: in their absence, the type of the field is poly.
359
360 union {T name; T name; ...}
361 A ``disjoint union'' of the given types. This is more like the
362 variant record type of Pascal or the datatype of ML than the C
363 union type: the names are tags of the given type, exactly one of
364 which applies to a given value at a given time.
365
366 (T) Parentheses for grouping.
367
368 Typedef:
369
370 As in C, new type names may be created with the typedef statement. The
371 syntax is
372 typedef T typename;
373 where T is a Nickle type. The resulting typename may be used anywhere
374 a type is expected.
375
377 Values of the base types of Nickle are as expected. See the syntax for
378 constants above. Values of type file, semaphore, and continuation may
379 currently be created only by calls to builtin functions: no Nickle con‐
380 stants of these types exist.
381
382 As noted in TYPES above, Nickle has several kinds of ``structured
383 value'': arrays, functions, pointers, structures and disjoint unions.
384 All of these have some common properties. When created, all of the
385 component values are uninitialized (unless otherwise specified).
386 Attempts to use an uninitialized value will result in either a compile-
387 time error or a runtime exception.
388
389 Arrays:
390
391 [E] creates a (zero-based) array with E elements. E must be non-
392 negative.
393
394 [E]{V,V,...,V}
395 Creates an array with E elements, initialized to the Vs. If
396 there are too few initializers, remaining elements will remain
397 uninitialized.
398
399 [E]{V,V,...,V...}
400 The second ellipsis (three dots) is syntax, not metasyntax.
401 Create an array with E elements. The first elements in the
402 array will be initialized according to the Vs, with any remain‐
403 ing elements receiving the same value as the last V. This syn‐
404 tax may be used in the obvious fashion with any of the array
405 initializers below.
406
407 [*]{V,V,...,V}
408 Creates an initialized array with exactly as many elements as
409 initializers. There must be at least one initializer.
410
411 [E,E,...,E] [*,*,...,*]
412 Creates multidimensional arrays. Integer expressions and "*"
413 cannot be mixed: an array's dimensions are entirely either spec‐
414 ified or unspecified by the definition. These arrays may also
415 be created initialized: see next paragraph for initializer syn‐
416 tax.
417
418 (T[E]) (T[E,E,...,E]) (T[E]){E,E,...,E}
419
420 (T[E,E,...,E]){{E,...},...,{E,...}}
421 Alternate syntax for creating arrays of type T. The initializ‐
422 ers, in curly braces, are optional. The number of initializers
423 must be less than or equal to the given number of elements in
424 each dimension. For multidimensional arrays, the extra curly
425 braces per dimension in the initializer are required; this is
426 unlike C, where they are optional.
427
428 (T[*]){E,E,...,E} (T[*,*,...,*]){{E,...},...,{E,...}}
429 Creates arrays of type T, with each dimension's size given by
430 the maximum number of initializers in any subarray in that
431 dimension.
432
433 Pointers:
434
435 0 The null pointer, in contexts where a pointer is required.
436
437 &V &A[E,E,...,E] &S.N
438 Creates a pointer to the given variable, array element, or
439 structure member. The type of the pointer will be *T, where T
440 is the type of the object pointed to.
441
442 *P The value pointed to by pointer P. This can be viewed or modi‐
443 fied as in C.
444
445 Functions:
446
447 (T func(){S;S;...S;}) (T func(T name,T name,...T name){S;S;...S;})
448 Function expression: denotes a function of zero or more formal
449 parameters with the given types and names, returning the given
450 result type. The function body is given by the curly-brace-
451 enclosed statement list. All types are optional, and default to
452 poly. As noted above, functions are strictly call-by-value: in
453 particular, arrays and structures are copied rather than refer‐
454 enced.
455
456 T function name(T name,T name,...,T name){S;S;...S;}
457 Defines a function of zero or more arguments. Syntactic sugar
458 for
459 T(T,T,...T) name = (T func(T name,T name,...T
460 name){S;S;...S;});
461
462 T function name(T name, T name ...)
463 The ellipsis here is syntax, not metasyntax: if the last formal
464 argument to a function is followed by three dots, the function
465 may be called with more actuals than formals. All ``extra''
466 actuals are packaged into the array formal of the given name,
467 and typechecked against the optional type T of the last argument
468 (default poly).
469
470 Structures:
471
472 (struct { T name; T name; ...T name; }){name = E; name = E; ...name=E;}
473 Create a value of a structured type. The named fields are ini‐
474 tialized to the given values, with the remainder uninitialized.
475 As indicated, initialization is by label rather than positional
476 as in C.
477
478 Unions:
479
480 (union { T name; T name; ...T name; }.name) E
481 Create a value of the given union type, the variant given by
482 .name, and the value given by E. E must be type-compatible with
483 name.
484
486 The statement syntax very closely resembles that of C. Some additional
487 syntax has been added to support Nickle's additional functionality.
488
489 E; Evaluates the expression.
490
491 {S ... S}
492 Executes the enclosed statements in order.
493
494 if (E) S
495 Basic conditional.
496
497 if (E) S
498 Conditional execution.
499
500 else S Else is allowed, with the usual syntax and semantics. In par‐
501 ticular, an else binds to the most recent applicable if() or
502 twixt().
503
504 while (E) S
505 C-style while loop.
506
507 do S while (E);
508 C-style do loop.
509
510 for (opt-E; opt-E; opt-E) S
511 C-style for loop.
512
513 switch (E) { case E: S-list case E: S-list ... default: S-list }
514 C-style case statement. The case expressions are not required
515 to be constant expressions, but may be arbitrary. The first
516 case evaluating to the switch argument is taken, else the
517 default if present, else the switch body is skipped.
518
519 twixt(opt-E; opt-E) S
520
521 twixt(opt-E; opt-E) S else S
522 If first argument expression evaluates to true, the body of the
523 twixt() and then the second argument expression will be evalu‐
524 ated. If the first argument expression evaluates to false, the
525 else statement will be executed if present. Otherwise, the
526 entire twixt() statement will be skipped.
527
528 The twixt() statement guarantees that all of these events will happen
529 in the specified order regardless of the manner in which the twixt() is
530 entered (from outside) or exited, including exceptions, continuations,
531 and break. (Compare with Java's ``finally'' clause.)
532
533 try S;
534
535 try S catch name (T name, ...) { S; ... };
536
537 try S catch name (T name, ...) { S; ... } ... ;
538 Execute the first statement S. If an exception is raised during
539 execution, and the name matches the name in a catch block, bind
540 the formal parameters in the catch block to the actual parame‐
541 ters of the exception, and execute the body of the catch block.
542 There may be multiple catch blocks per try. Zero catches, while
543 legal, is relatively useless. After completion of a catch
544 block, execution continues after the try clause. As with else,
545 a catch binds to the most recent applicable try-catch block.
546
547 raise name(name, name, ..., name)
548 Raise the named exception with zero or more arguments.
549
550 ; The null statement
551
552 break; Discontinue execution of the nearest enclosing
553 for/do/while/switch/twixt statement. The leave expression will
554 be executed as the twixt statement is exited.
555
556 continue;
557 Branch directly to the conditional test of the nearest enclosing
558 for/do/while statement.
559
560 return E;
561 Return value E from the nearest enclosing function.
562
563 Namespaces:
564
565 Like Java and C++ Nickle has a notion of namespace, a collection of
566 names with partially restricted visibility. In Nickle, namespaces are
567 created with the namespace command.
568
569 opt-P namespace N { S ... }
570 Places all names defined in the statements S into a namespace
571 named N. The optional qualifier P may be the keyword public,
572 but beware: this merely indicates that the name N itself is vis‐
573 ible elsewhere in the current scope, and has nothing to do with
574 the visibility of items inside the namespace.
575
576 extend namespace N { S ... }
577 Reopen the given namespace N, and extend it with the names
578 defined as public in the given statements S.
579
580 Names defined inside the namespace are invisible outside the
581 namespace unless they are qualified with the keyword public.
582 Public names may be referred to using a path notation:
583 namespace::namespace::...::namespace::name
584 refers to the given name as defined inside the given set of
585 namespaces. The double-colon syntax is unfortunate, as it is
586 slightly different in meaning than in C++, but all the good sym‐
587 bols were taken, and it is believed to be a feature that the
588 namespace separator is syntactically different than the struc‐
589 ture operator. In Java, for example, the phrase
590 name.name.name
591 is syntactically ambiguous: the middle name may be either a
592 structure or a namespace.
593
594 import N;
595 The name N must refer to a namespace: all public names in this
596 namespace are brought into the current scope (scoping out con‐
597 flicting names).
598
600 Nickle has a collection of standard functions built in. Some of these
601 are written in C, but many are written in Nickle. Several collections
602 of functions have associated builtin datatypes: their namespaces,
603 together with their types, should be viewed as ADTs.
604
605 Top-Level Builtins:
606
607 int printf(string fmt, poly args...)
608 Calls File::fprintf(stdout, fmt, args ...) and returns its
609 result.
610
611 string function gets ()
612 Calls File::fgets(stdin) and returns its result.
613
614 string function scanf (string fmt, *poly args...)
615 Calls File::vfscanf(stdin, fmt, args) and returns its result.
616
617 string function vscanf (string fmt, (*poly)[*] args)
618 Calls File::vfscanf(stdin, fmt, args) and returns its result.
619
620 real imprecise(rational value)
621 See the discussion of type real above.
622
623 real imprecise(rational value, int prec)
624 See the discussion of type real above.
625
626 int string_to_integer(string s)
627
628 int atoi(string s)
629 The argument s is a signed digit string, and the result is the
630 integer it represents. If the string s is syntactically a hexa‐
631 decimal, octal, binary, or explicit base-10 constant, treat it
632 as such.
633
634 int string_to_integer(string s, int base)
635
636 int atoi(string s, int base)
637 Treat s as a string of digits in the given base. A base of 0
638 acts as with no base argument. Otherwise, base specification
639 syntax in the string is ignored.
640
641 int putchar(int c)
642 Place the given character on the standard output using
643 File::putc(c, stdout), and return its result.
644
645 int sleep(int msecs)
646 Try to suspend the current thread for at least msecs millisec‐
647 onds. Return 1 on early return, and 0 otherwise.
648
649 int exit(int status)
650 Exit Nickle with the given status code. Do not return anything.
651
652 int dim(poly[*] a)
653 Given a one-dimensional array a, dim() returns the number of
654 elements of a.
655
656 int[] dims(poly[] a)
657 Given an arbitrary array a, dims() returns an array of integers
658 giving the size of each dimension of a. Thus, dim(dims(a)) is
659 the number of dimensions of a.
660
661 *poly reference(poly v)
662 Given an arbitrary value v, ``box'' that value into storage and
663 return a pointer to the box.
664
665 rational string_to_real(string s)
666
667 rational atof(string s)
668 Convert the real constant string s into its associated real num‐
669 ber.
670
671 number abs(real v)
672 Return the absolute value of v. The result type chosen will
673 match the given context.
674
675 int floor(real v)
676 Return the largest integer less than or equal to v. This will
677 fail if v is a real and the precision is too low.
678
679 int ceil(real v)
680 Return the smallest integer greater than or equal to v. This
681 will fail if v is a real and the precision is too low.
682
683 int exponent(real v)
684 Return the exponent of the imprecise real v.
685
686 rational mantissa(real v)
687 Return the mantissa of the imprecise real v, as a rational m
688 with 0 <= m <= 0.5 .
689
690 int numerator(rational v)
691 Return the numerator of the rational number v: i.e., if v = n/d
692 in reduced form, return n.
693
694 int denominator(rational v)
695 Return the denominator of the rational number v: i.e., if v =
696 n/d in reduced form, return d.
697
698 int precision(real v)
699 Return the number of bits of precision of the mantissa of the
700 imprecise real number v.
701
702 int sign(real v)
703 Return -1 or 1 as v is negative or nonnegative.
704
705 int bit_width(int v)
706 Return the number of bits required to represent abs(v) inter‐
707 nally.
708
709 int is_int(poly v)
710 Type predicate.
711
712 int is_rational(poly v)
713 Numeric type predicates are inclusive: e.g., is_rational(1)
714 returns 1.
715
716 int is_number(poly v)
717 Type predicate.
718
719 int is_string(poly v)
720 Type predicate.
721
722 int is_file(poly v)
723 Type predicate.
724
725 int is_thread(poly v)
726 Type predicate.
727
728 int is_semaphore(poly v)
729 Type predicate.
730
731 int is_continuation(poly v)
732 Type predicate.
733
734 int is_array(poly v)
735 Type predicate.
736
737 int is_ref(poly v)
738 Type predicate: checks for pointer type. This is arguably a
739 misfeature, and may change.
740
741 int is_struct(poly v)
742 Type predicate.
743
744 int is_func(poly v)
745 Type predicate.
746
747 int is_void(poly v)
748 Type predicate.
749
750 int gcd(int p, int q)
751 Return the GCD of p and q. The result is always positive.
752
753 int xor(int a, int b)
754 Return a ^ b . This is mostly a holdover from before Nickle had
755 an xor operator.
756
757 poly setjmp(continuation *c, poly retval)
758 The setjmp() and longjmp() primitives together with the continu‐
759 ation type form an ADT useful for nearly arbitrary transfers of
760 flow-of-control. The setjmp() and longjmp() builtins are like
761 those of C, except that the restriction that longjmp() always
762 jump upwards is removed(!): a continuation saved via setjmp()
763 never becomes invalid during the program lifetime.
764
765 The setjmp() builtin saves the current location and context into
766 its continuation pointer argument, and then returns its second
767 argument.
768
769 void longjmp(continuation c, poly retval)
770 The longjmp() builtin never returns to the call site, but
771 instead returns from the setjmp() that created the continuation,
772 with return value equal to the second argument of longjmp().
773
774 string prompt
775 The prompt printed during interactive use when at top-level.
776 Default "> ". when waiting for the rest of a statement or
777 expression, and when debugging, respectively. Default values
778 are "> ", "+ ", and "- ".
779
780 string prompt2
781 The prompt printed during interactive use when waiting for the
782 rest of a statement or expression. Default "+ ".
783
784 string prompt3
785 The prompt printed during interactive use when debugging.
786 Default "- ".
787
788 string format
789 The printf() format for printing top-level values. Default
790 "%g".
791
792 string version
793 The version number of the Nickle implementation currently being
794 executed.
795
796 string build
797 The build date of the Nickle implementation currently being exe‐
798 cuted, in the form "yyyy/mm/dd", or "?" if the build date is
799 unknown for some reason.
800
801 file stdin
802 Bound to the standard input stream.
803
804 file stdout
805 Bound to the standard output stream.
806
807 file stderr
808 Bound to the standard error stream.
809
810 Exceptions:
811
812 A few standard exceptions are predeclared and used internally by
813 Nickle.
814
815 exception uninitialized_value(string msg)
816 Attempt to use an uninitialized value.
817
818 exception invalid_argument(string msg, int arg, poly val)
819 The arg-th argument to a builtin function had invalid value val.
820
821 exception readonly_box(string msg, poly val)
822 Attempt to change the value of a read-only quantity to val.
823
824 exception invalid_array_bounds(string msg, poly a, poly i)
825 Attempt to access array a at index i is out of bounds.
826
827 exception divide_by_zero(string msg, real num, real den)
828 Attempt to divide num by den with den == 0.
829
830 exception invalid_struct_member(string msg, poly struct, string name)
831 Attempt to refer to member name of the object struct, which does
832 not exist.
833
834 exception invalid_binop_values(string msg, poly arg1, poly arg2)
835 Attempt to evaluate a binary operator with args arg1 and arg2,
836 where at least one of these values is invalid.
837
838 exception invalid_unop_values(string msg, poly arg)
839 Attempt to evaluate a unary operator with invalid argument arg.
840
841 Builtin Namespaces:
842
843 Math The math functions available in the Math namespace are imple‐
844 mented in a fashion intended to be compatible with the C
845 library. Please consult the appropriate manuals for further
846 details.
847
848 real pi
849 Imprecise constant giving the value of the circumference/diame‐
850 ter ratio of the circle to the default precision of 256 bits.
851
852 protected real e
853 Imprecise constant giving the value of the base of natural loga‐
854 rithms to the default precision of 256 bits. Since e is pro‐
855 tected, it must be referenced via Math::e, in order to avoid
856 problems with using the fifth letter of the alphabet at top
857 level.
858
859 real function sqrt(real v)
860 Returns the square root of v.
861
862 real function cbrt(real v)
863 Returns the cube root of v.
864
865 real function exp(real v)
866 Returns e**v.
867
868 real function log(real a)
869 Returns v such that e**v == a. Throws an invalid_argument
870 exception if a is non-positive.
871
872 real function log10(real a)
873 Returns v such that 10**v == a. Throws an invalid_argument
874 exception if a is non-positive.
875
876 real function log2(real a)
877 Returns v such that 2**v == a. Throws an invalid_argument
878 exception if a is non-positive.
879
880 real function pi_value(int prec)
881 Returns the ratio of the circumference of a circle to the diame‐
882 ter, with prec bits of precision.
883
884 real function sin(real a)
885 Returns the ratio of the opposite side to the hypotenuse of
886 angle a of a right triangle, given in radians.
887
888 real function cos(real a)
889 Returns the ratio of the adjacent side to the hypotenuse of
890 angle a of a right triangle, given in radians.
891
892 void function sin_cos(real a, *real sinp, *real cosp)
893 Returns with sin(a) and cos(a) stored in the locations pointed
894 to by sinp and cosp respectively. If either pointer is 0, do
895 not store into that location. May be slightly faster than call‐
896 ing both trig functions independently.
897
898 real function tan(real a)
899 Returns the ratio of the opposite side to the adjacent side of
900 angle a of a right triangle, given in radians. Note that
901 tan(pi/2) is not currently an error: it will return a very large
902 number dependent on the precision of its input.
903
904 real function asin(real v)
905 Returns a such that sin(a) == v.
906
907 real function acos(real v)
908 Returns a such that cos(a) == v.
909
910 real function atan(real v)
911 Returns a such that tan(a) == v.
912
913 real function atan2(real x, y)
914 Returns a such that tan(a) == x / y. Deals correctly with y ==
915 0.
916
917 real function pow(real a, real b)
918 The implementation of the ** operator.
919
920 File The namespace File provides operations on file values.
921
922 int function fprintf(file f, string s, ....)
923 Print formatted values to a file, as with UNIX stdio library
924 fprintf(). fprintf() and printf() accept a reasonable sub-set
925 of the stdio library version: %c, %d, %e, %x, %o, %f, %s, %g
926 work as expected, as does %v to smart-print a value. Format
927 modifiers may be placed between the percent-sign and the format
928 letter to modify formatting. There are a lot of known bugs with
929 input and output formatting.
930
931 Format Letters:
932
933 %c Requires a small integer argument (0..255), and formats
934 as an ASCII character.
935
936 %d Requires an integer argument, and formats as an integer.
937
938 %x Requires an integer argument, and formats as a base-16
939 (hexadecimal) integer.
940
941 %o Requires an integer argument, and formats as a base-8
942 (octal) integer.
943
944 %e Requires a number argument, and formats in scientific
945 notation.
946
947 %f Requires a number argument, and formats in fixed-point
948 notation.
949
950 %s Requires a string argument, and emits the string liter‐
951 ally.
952
953 %g Requires a number, and tries to pick a precise and read‐
954 able representation to format it.
955
956 Format Modifiers:
957
958 digits All format characters will take an integer format modi‐
959 fier indicating the number of blanks in the format field
960 for the data to be formatted. The value will be printed
961 right-justified in this space.
962
963 digits.digits
964 The real formats will take a pair of integer format modi‐
965 fiers indicating the field width and precision (number of
966 chars after decimal point) of the formatted value.
967 Either integer may be omitted.
968
969 - A precision value indicating infinite precision.
970
971 * The next argument to fprintf() is an integer indicating
972 the field width or precision of the formatted value.
973
974 file function string_write()
975 Return a file which collects written values into a string.
976
977 int function close(file f)
978 Close file f and return an indication of success.
979
980 int function flush(file f)
981 Flush the buffers of file f and return an indication of success.
982
983 int function getc(file f)
984 Get the next character from file f and return it.
985
986 int function end(file f)
987 Returns true if file f is at EOF, else false.
988
989 int function error(file f)
990 Returns true if an error is pending on file f, else false.
991
992 int function clear_error(file f)
993 Clears pending errors on file f, and returns an indication of
994 success.
995
996 file function string_read(string s)
997 Returns a virtual file whose contents are the string s.
998
999 string function string_string(file f)
1000 Return the string previously written into the file f, which
1001 should have been created by string_read() or string_write().
1002 Behavior on other files is currently undefined.
1003
1004 file function open(string path, string mode)
1005 Open the file at the given path with the given mode string, ala
1006 UNIX stdio fopen(). Permissible modes are as in stdio: "r",
1007 "w", "x", "r+", "w+" and "x+".
1008
1009 integer function fputc(integer c, file f)
1010 Output the character c to the output file f, and return an indi‐
1011 cation of success.
1012
1013 integer function ungetc(integer c, file f)
1014 Push the character c back onto the input file f, and return an
1015 indication of success.
1016
1017 integer function setbuf(file f, integer n)
1018 Set the size of the buffer associated with file f to n, and
1019 return n.
1020
1021 string function fgets (file f)
1022 Get a line of input from file f, and return the resulting
1023 string.
1024
1025 file function pipe(string path, string[*] argv, string mode)
1026 Start up the program at the given path, returning a file which
1027 is one end of a "pipe" to the given process. The mode argument
1028 can be "r" to read from the pipe or "w" to write to the pipe.
1029 The argv argument is an array of strings giving the arguments to
1030 be passed to the program, with argv[0] conventionally being the
1031 program name.
1032
1033 int function print (file f, poly v, string fmt, int base, int width,
1034 int prec, string fill)
1035 Print value v to file f in format fmt with the given base,
1036 width, prec, and fill. Used internally by File::fprintf();
1037
1038 int function fscanf(file f, string fmt, *poly args...)
1039 Fill the locations pointed to by the array args with values
1040 taken from file f according to string fmt. The format speci‐
1041 fiers are much as in UNIX stdio scanf(): the "%d", "%e", "%f",
1042 "%c" and "%s" specifiers are supported with the expected modi‐
1043 fiers.
1044
1045 int function vfscanf (file f, string fmt, (*poly)[*] args)
1046 Given the file f, the format fmt, and the array of arguments
1047 args, fscanf() appropriately.
1048
1049 Thread The namespace Thread supports various operations useful for pro‐
1050 gramming with threads, which provide concurrent flow of control
1051 in the shared address space. There is one piece of special syn‐
1052 tax associated with threads.
1053
1054 fork(E)
1055 Accepts an arbitrary expression, and evaluates it in a
1056 new child thread. The parent thread receives the thread
1057 as the value of the fork expression.
1058
1059 The remainder of the Thread functions are fairly standard.
1060
1061 int function kill(thread list...)
1062 Kills every running thread in the array list. With no argu‐
1063 ments, kills the currently running thread. Returns the number
1064 of threads killed.
1065
1066 int function trace(poly list...)
1067 Shows the state of every running thread in the array list. With
1068 no arguments, traces the default continuation. Returns the num‐
1069 ber of threads traced.
1070
1071 int function cont()
1072 Continues execution of any interrupted threads, and returns the
1073 number of continued threads.
1074
1075 thread function current()
1076 Return the current thread.
1077
1078 int function list()
1079 Reports the currently running thread to stdout.
1080
1081 int function get_priority(thread t)
1082 Reports the priority of the given thread.
1083
1084 thread function id_to_thread(int id)
1085 Returns the thread with the given id, if found, and 0 otherwise.
1086
1087 poly function join(thread t)
1088 Waits for thread t to terminate, and returns whatever it
1089 returns.
1090
1091 int function set_priority(thread t, int i)
1092 Attempts to set the priority of thread t to level i, and returns
1093 the new priority. Larger priorities mean more runtime: a task
1094 with higher priority will always run instead of a lower priority
1095 task. Threads of equal highest priority will be pre-emptively
1096 multitasked.
1097
1098 Semaphore
1099 The Semaphore namespace encapsulates operations on the semaphore
1100 built-in ADT. A semaphore is used for thread synchronization.
1101 Each signal() operation on the semaphore awakens the least-
1102 recent thread to wait() on that semaphore. The ``count'' of
1103 waiting processes may be set at semaphore creation time.
1104
1105 semaphore function new(int c)
1106 Create a new semaphore with an initial count c of waiting pro‐
1107 cesses. If c is positive, it means that c threads may wait on
1108 the semaphore before one blocks. If c is negative, it sets a
1109 count of threads which must be waiting on the semaphore before
1110 further waits will not block.
1111
1112 semaphore function new()
1113 Call semaphore(0) and return its result.
1114
1115 int signal(semaphore s)
1116 Increment semaphore s. If s is non-positive, and some thread is
1117 blocked on s, release the least-recently-blocked thread. Return
1118 1 on success.
1119
1120 int wait(semaphore s)
1121 Decrement semaphore s. If s is negative, block until released.
1122 Return 1 on success.
1123
1124 int test(semaphore s)
1125 Test whether wait() on semaphore s would cause the current
1126 thread to block. If so, return 0. Otherwise, attempt to decre‐
1127 ment s, and return 1 if successful.
1128
1129 String The String namespace contains a few basic operations on the
1130 string ADT.
1131
1132 int function length(string s)
1133 Returns the number of characters in s.
1134
1135 string function new(int c)
1136 Returns as a string the single character c.
1137
1138 string function new(int cv[*])
1139 Returns a string comprised of the characters of cv.
1140
1141 int function index(string t, string p)
1142 Returns the integer index of the pattern string p in the target
1143 string t, or -1 if p is not a substring of t.
1144
1145 string function substr(string s, int i, int l)
1146 Returns the substring of string s starting with the character at
1147 offset i (zero-based) and continuing for a total of l charac‐
1148 ters. If l is negative, the substring will consist of charac‐
1149 ters preceding rather than succeeding i.
1150
1151 PRNG The PRNG namespace provides pseudo-random number generation and
1152 manipulation. The core generator is the RC4 stream cipher gen‐
1153 erator, properly bootstrapped. This provide a stream of crypto‐
1154 graphically-secure pseudo-random bits at reasonable amortized
1155 cost. (But beware, initialization is somewhat expensive.)
1156
1157 void function srandom(int s)
1158 Initialize the generator, using the (arbitrarily-large) integer
1159 as a seed.
1160
1161 void function dev_srandom(int nbits)
1162 Initialize the generator, using nbits bits of entropy obtained
1163 from some reasonable entropy source. On UNIX systems, this
1164 source is /dev/urandom. Asking for more initial entropy than
1165 the system has may lead either to bootstrapping (as on UNIX) or
1166 to hanging, so use cautiously.
1167
1168 int function randbits(int n)
1169 Returns an n-bit pseudo-random number, in the range 0..(2**n)-1.
1170 Useful for things like RSA.
1171
1172 int function randint(int n)
1173 Returns a pseudo-random number in the range 0..n-1.
1174
1175 void function shuffle(*(poly[*]) a)
1176 Performs an efficient in-place true shuffle (c.f. Knuth) of the
1177 array a.
1178
1179 Command
1180 The Command namespace is used by the top-level commands as
1181 described below. It is also occasionally useful in its own
1182 right.
1183
1184 string library_path
1185 Contains the current library search path, a colon-separated list
1186 of directories to be searched for library files.
1187
1188 int function undefine(string name)
1189 Implements the top-level undefine command. Remove the name
1190 denoted by string name from the namespace. This removes all
1191 visible definitions of the name.
1192
1193 int function undefine(string[*] names)
1194 Remove each of the names in the array names from the namespace.
1195 This removes all visible definitions of each name.
1196
1197 int function delete(string name)
1198 Attempt to remove the command with the given string name from
1199 the top-level command list, and return 1 if successful.
1200
1201 int function lex_file(string path)
1202 Attempt to make the file at the given path the current source of
1203 Nickle code, and return 1 if successful. Note that this effec‐
1204 tively ``includes'' the file by pushing it onto a stack of files
1205 to be processed.
1206
1207 int function lex_library(string filename)
1208 Like lex_file(), but searches the directories given by the
1209 library_path variable for the first file with the given file‐
1210 name.
1211
1212 int function lex_string(string code)
1213 Attempt to make the Nickle code contained in the string code be
1214 the next input.
1215
1216 int function edit(string[*] names)
1217 Implements the top-level edit command. The names in the array
1218 are a path of namespace names leading to the symbol name, which
1219 is last.
1220
1221 int function new(string name, poly func)
1222 Binds function func to the top-level command string name: i.e.,
1223 makes it part of the top-level command vocabulary.
1224
1225 int function new_names(string name, poly func)
1226 Binds function func to the top-level command string name: i.e.,
1227 makes it part of the top-level command vocabulary. Unlike
1228 new(), the string names given to func at the top level are
1229 passed unevaluated as an array of string names or as a single
1230 string name.
1231
1232 int function pretty_print(file f, string[*] names)
1233 Implements the top-level print command. Each of the passed name
1234 strings is looked up and the corresponding code printed to file
1235 f.
1236
1237 int function display(string fmt, poly val)
1238 Uses printf() to display the value val in format fmt.
1239
1240 History
1241 Nickle maintains a top-level value history, useful as an adjunct
1242 to command-line editing when calculating. The History namespace
1243 contains functions to access this history.
1244
1245 int function show(string fmt)
1246 Implements the history top-level command with no arguments.
1247 Show the most recent history values with format fmt.
1248
1249 int function show(string fmt, int count)
1250 Implements the history top-level command with one argument.
1251 Show the last count history values with format fmt.
1252
1253 int function show(string fmt, int first, int last)
1254 Implements the history top-level command with two arguments.
1255
1256 poly function insert(poly val)
1257 Insert val in the history list, and return it.
1258
1259 Environ
1260 Many operating systems have some notion of ``environment vari‐
1261 ables.'' The Environ namespace contains functions to manipulate
1262 these.
1263
1264 int function check(string name)
1265 Returns 1 if the variable with the given name is in the environ‐
1266 ment, and 0 otherwise.
1267
1268 string function get(string name)
1269 Attempts to retrieve and return the value of the environment
1270 variable with the given name. Throws an invalid_argument excep‐
1271 tion if the variable is not available.
1272
1273 int function unset(string name)
1274 Attempts to unset the environment variable with the given name,
1275 and returns an indication of success.
1276
1277 string function set(string name, string value)
1278 Attempts to set the environment variable with the given name to
1279 the given value, and returns an indication of success.
1280
1282 Nickle has a set of commands which may be given at the top level.
1283
1284 quit Exit Nickle.
1285
1286 quit E Exit Nickle with integer status code E.
1287
1288 undefine NAME {,NAME}
1289 Remove these names from the system.
1290
1291 load E Load a file given by the string name E.
1292
1293 library E
1294 Load a library given by the string name E. See the discussion
1295 of the NICKLEPATH environment variable in ENVIRONMENT below, and
1296 the discussion of Command::library_path above.
1297
1298 E # E Print expr1 in base expr2 .
1299
1300 print NAME
1301 Display a formatted version of the object denoted by NAME. Com‐
1302 ments and original formatting are lost. If NAME is a variable,
1303 print the type as well as the value.
1304
1305 edit NAME
1306 Invoke $EDITOR on the named object, and re-incorporate the
1307 results of the edit. This is most useful with functions.
1308
1309 history
1310 Display the 10 most recently printed values. They can be
1311 accessed with $n where n is the number displayed to the right of
1312 the value in this list.
1313
1314 history E
1315 Display the E most recent history values.
1316
1317 history E,E
1318 Display history values from the first integer E through the sec‐
1319 ond.
1320
1322 When an unhandled exception reaches top level during execution, the
1323 user receives a dash prompt, indicating that debug mode is active. In
1324 this mode, the command-line environment is that in which the unhandled
1325 exception was raised. In addition a number of debugging commands are
1326 available to the user:
1327
1328 trace Get a stack backtrace showing the current state, as with the GDB
1329 where command.
1330
1331 up Move up the stack (i.e., toward the top-level expression) ala
1332 GDB.
1333
1334 down Move down the stack (i.e., toward the current context) ala GDB.
1335
1336 done Leave debugging mode, abandoning execution.
1337
1338 In addition, the Debug namespace is scoped in in debugging mode.
1339 This is primarily of use in debugging Nickle itself.
1340
1341 collect()
1342 Run the garbage collector.
1343
1344 dump(function)
1345 Print the compiled byte code for function.
1346
1348 EDITOR The editor used by the edit command, described in COMMANDS
1349 above.
1350
1351 NICKLERC
1352 The location of the user's .nicklerc file, which will be loaded
1353 at the beginning of nickle execution if possible.
1354
1355 HOME Used to find the user's .nicklerc if NICKLERC is not set.
1356
1357 NICKLEPATH
1358 A colon-separated path whose elements are directories containing
1359 Nickle code. The library command and the -l flag, described
1360 above, search this path for a filename matching the given file.
1361 The default library path in the absence of this variable is
1362 /usr/share/nickle.
1363
1364 NICKLESTART
1365 The filename of the file that should be loaded as a bootstrap on
1366 Nickle startup. The default in the absence of this variable is
1367 to load /usr/share/nickle/builtin.5c.
1368
1370 An example (taken from the bc manual:
1371
1372 real function exponent(real x) {
1373 real a = 1;
1374 int b = 1;
1375 real s = 1;
1376 int i = 1;
1377 while (1) {
1378 a = a * x;
1379 b = b * i;
1380 real c = a / b;
1381 if (abs(c) < 1e-6)
1382 return s;
1383 s = s + c;
1384 i++;
1385 }
1386 }
1387
1388 defines a function to compute an approximate value of the exponential
1389 function e ** x and
1390
1391 for (i = 1; i < 10; i++)
1392 printf ("%g\n", exponent (i));
1393
1394 prints approximate values of the exponential function of the first ten
1395 integers.
1396
1398 This document describes version 1.99.2 of nickle, as well as some newer
1399 features. It was distributed with version 2.90 of nickle.
1400
1402 See the discussion of the type of the exponentiation operator ** above.
1403
1404 Due to a difficult-to-remove grammar ambiguity, it is not possible to
1405 use a bare assignment expression in an array initializer: it is con‐
1406 fused with a structure initializer. For example:
1407 > int x = 0;
1408 > (int[*]){x = 1}
1409 -> (int[*]) { x = 1 }
1410 Non array initializer
1411 The workaround is to parenthesize the assignment expression:
1412 > (int[*]){(x = 1)}
1413 [1]{1}
1414 Because this is so rare, so hard to fix, and so easy to work around,
1415 this bug is unlikely to be fixed anytime soon.
1416
1417 There are a lot of known bugs with input and output formatting. The
1418 obvious stuff works, other stuff does not.
1419
1420 The semantics of division are unfortunately different from those of C.
1421 This is arguably because C is broken in this area: we cannot currently
1422 see any obvious fix. C allows automatic implicit coercion of floating
1423 to integral types, but we consider this a misfeature.
1424
1425 The implementation has not been thoroughly tested.
1426
1428 Nickle is the work of Keith Packard <keithp@keithp.com> and Bart Massey
1429 <bart_massey@iname.com>.
1430
1431 Nickle is
1432 Copyright 1988-2006 Keith Packard and Bart Massey. All Rights
1433 Reserved.
1434
1435 Permission is hereby granted, free of charge, to any person obtaining a
1436 copy of this software and associated documentation files (the "Soft‐
1437 ware"), to deal in the Software without restriction, including without
1438 limitation the rights to use, copy, modify, merge, publish, distribute,
1439 sublicense, and/or sell copies of the Software, and to permit persons
1440 to whom the Software is furnished to do so, subject to the following
1441 conditions:
1442
1443 The above copyright notice and this permission notice shall be included
1444 in all copies or substantial portions of the Software.
1445
1446 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1447 OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MER‐
1448 CHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
1449 NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1450 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
1451 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
1452 DEALINGS IN THE SOFTWARE.
1453
1454 Except as contained in this notice, the names of the authors or their
1455 institutions shall not be used in advertising or otherwise to promote
1456 the sale, use or other dealings in this Software without prior written
1457 authorization from the authors.
1458
1459
1460
1461 @RELEASE_DATE@ NICKLE(1)