got rid of 'accept' dir in the tests

This commit is contained in:
Araq 2011-11-19 15:45:51 +01:00
commit a274f3bf5b
264 changed files with 5 additions and 7 deletions

1
tests/compile/mrecmod.nim Executable file
View file

@ -0,0 +1 @@
import trecmod

9
tests/compile/mrecmod2.nim Executable file
View file

@ -0,0 +1,9 @@
# Module B
import trecmod2
proc p*(x: trecmod2.T1): trecmod2.T1 =
# this works because the compiler has already
# added T1 to trecmod2's interface symbol table
return x + 1

10
tests/compile/mtempl5.nim Normal file
View file

@ -0,0 +1,10 @@
var
gx = 88
gy = 44
template templ*(): int =
bind gx, gy
gx + gy

6
tests/compile/mvarious.nim Executable file
View file

@ -0,0 +1,6 @@
# Test a submodule
#type
# TStringArr = array [0.. *] of string
proc exportme* = nil

68
tests/compile/sunset.tmpl Executable file
View file

@ -0,0 +1,68 @@
#! stdtmpl
#proc sunsetTemplate*(current, ticker, content: string,
# tabs: openarray[array[0..1, string]]): string =
# result = ""
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Nimrod Programming System</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" type="text/css" href="style/style.css" />
</head>
<body>
<div id="main">
<div id="links">
<!-- **** INSERT LINKS HERE **** -->
</div>
<div id="logo"><h1>Nimrod Programming System</h1></div>
<div id="content">
<div id="menu">
<ul>
#for item in items(tabs):
#var name = item[0]
#var t = item[1]
#if t == current:
<li><a id="selected" href="${t}.html" title = "Nimrod - $name">$name</a></li>
#else:
<li><a href="${t}.html" title = "Nimrod - $name">$name</a></li>
#end if
#end for
</ul>
</div>
<div id="column1">
<div class="sidebaritem">
<div class="sbihead">
<h1>latest news</h1>
</div>
<div class="sbicontent">
$ticker
</div>
</div>
<div class="sidebaritem">
<div class="sbihead">
<h1>additional links</h1>
</div>
<div class="sbilinks">
<!-- **** INSERT ADDITIONAL LINKS HERE **** -->
<ul>
<li><a class="reference" href="http://llvm.org">LLVM</a></li>
<li><a class="reference" href="http://gcc.gnu.org">GCC</a></li>
</ul>
</div>
</div>
</div>
<div id="column2">
$content
</div>
</div>
<div id="footer">
copyright &copy; 2008 Andreas Rumpf | Last update: ${getDateStr()}
| <a class="reference" href="http://validator.w3.org/check?uri=referer">XHTML 1.1</a>
| <a class="reference" href="http://jigsaw.w3.org/css-validator/check/referer">CSS</a>
| <a class="reference" href="http://www.dcarter.co.uk">design by dcarter</a>
</div>
</div>
</body>
</html>

8
tests/compile/tambsym2.nim Executable file
View file

@ -0,0 +1,8 @@
from sdl import PSurface
discard SDL.CreateRGBSurface(SDL.SWSURFACE, 23, 34,
32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xff000000'i32)

13
tests/compile/tarrindx.nim Executable file
View file

@ -0,0 +1,13 @@
# test another strange bug ... (I hate this compiler; it is much too buggy!)
proc putEnv(key, val: string) =
# XXX: we have to leak memory here, as we cannot
# free it before the program ends (says Borland's
# documentation)
var
env: ptr array[0..500000, char]
env = cast[ptr array[0..500000, char]](alloc(len(key) + len(val) + 2))
for i in 0..len(key)-1: env[i] = key[i]
env[len(key)] = '='
for i in 0..len(val)-1:
env[len(key)+1+i] = val[i]

31
tests/compile/tassign.nim Executable file
View file

@ -0,0 +1,31 @@
# Test the assignment operator for complex types which need RTTI
type
TRec = object
x, y: int
s: string
seq: seq[string]
arr: seq[seq[array[0..3, string]]]
TRecSeq = seq[TRec]
proc test() =
var
a, b: TRec
a.x = 1
a.y = 2
a.s = "Hallo!"
a.seq = @["abc", "def", "ghi", "jkl"]
a.arr = @[]
setLen(a.arr, 4)
a.arr[0] = @[]
a.arr[1] = @[]
b = a # perform a deep copy here!
b.seq = @["xyz", "huch", "was", "soll"]
writeln(stdout, len(a.seq))
writeln(stdout, a.seq[3])
writeln(stdout, len(b.seq))
writeln(stdout, b.seq[3])
writeln(stdout, b.y)
test()

View file

@ -0,0 +1,11 @@
##
## can_alias_generic Nimrod Module
##
## Created by Eric Doughty-Papassideris on 2011-02-16.
## Copyright (c) 2011 FWA. All rights reserved.
type
TGen[T] = object
TGen2[T] = TGen[T]

View file

@ -0,0 +1,15 @@
discard """
disabled: true
"""
##
## can_alias_specialised_generic Nimrod Module
##
## Created by Eric Doughty-Papassideris on 2011-02-16.
## Copyright (c) 2011 FWA. All rights reserved.
type
TGen[T] = object
TSpef = TGen[string]

View file

@ -0,0 +1,17 @@
##
## can_inherit_generic Nimrod Module
##
## Created by Eric Doughty-Papassideris on 2011-02-16.
## Copyright (c) 2011 FWA. All rights reserved.
type
TGen[T] = object
x, y: T
TSpef[T] = object of TGen[T]
var s: TSpef[float]
s.x = 0.4
s.y = 0.6

View file

@ -0,0 +1,11 @@
##
## can_specialise_generic Nimrod Module
##
## Created by Eric Doughty-Papassideris on 2011-02-16.
## Copyright (c) 2011 FWA. All rights reserved.
type
TGen[T] = object
TSpef = object of TGen[string]

67
tests/compile/tccgen1.nim Executable file
View file

@ -0,0 +1,67 @@
type
Feature = tuple[name: string, version: string]
PDOMImplementation* = ref DOMImplementation
DOMImplementation = object
Features: seq[Feature] # Read-Only
PNode* = ref Node
Node = object
attributes*: seq[PAttr]
childNodes*: seq[PNode]
FLocalName: string # Read-only
FNamespaceURI: string # Read-only
FNodeName: string # Read-only
nodeValue*: string
FNodeType: int # Read-only
FOwnerDocument: PDocument # Read-Only
FParentNode: PNode # Read-Only
prefix*: string # Setting this should change some values... TODO!
PElement* = ref Element
Element = object of Node
FTagName: string # Read-only
PCharacterData = ref CharacterData
CharacterData = object of Node
data*: string
PDocument* = ref Document
Document = object of Node
FImplementation: PDOMImplementation # Read-only
FDocumentElement: PElement # Read-only
PAttr* = ref Attr
Attr = object of Node
FName: string # Read-only
FSpecified: bool # Read-only
value*: string
FOwnerElement: PElement # Read-only
PDocumentFragment* = ref DocumentFragment
DocumentFragment = object of Node
PText* = ref Text
Text = object of CharacterData
PComment* = ref comment
Comment = object of CharacterData
PCDataSection* = ref CDataSection
CDataSection = object of Text
PProcessingInstruction* = ref ProcessingInstruction
ProcessingInstruction = object of Node
data*: string
FTarget: string # Read-only
proc `namespaceURI=`*(n: var PNode, value: string) =
n.FNamespaceURI = value
proc main =
var n: PNode
new(n)
n.namespaceURI = "test"
main()

14
tests/compile/tcmdline.nim Executable file
View file

@ -0,0 +1,14 @@
# Test the command line
import
os, strutils
var
i: int
params = paramCount()
i = 0
writeln(stdout, "This exe: " & getAppFilename())
writeln(stdout, "Number of parameters: " & $params)
while i <= params:
writeln(stdout, paramStr(i))
i = i + 1

55
tests/compile/tcodegenbug1.nim Executable file
View file

@ -0,0 +1,55 @@
import os
type
TStatusEnum* = enum
sUnknown = -1, sBuildFailure, sBuildInProgress, sBuildSuccess,
sTestFailure, sTestInProgress, sTestSuccess, # ORDER MATTERS!
sDocGenFailure, sDocGenInProgress, sDocGenSuccess,
sCSrcGenFailure, sCSrcGenInProgress, sCSrcGenSuccess
TStatus* = object
status*: TStatusEnum
desc*: string
hash*: string
proc initStatus*(): TStatus =
result.status = sUnknown
result.desc = ""
result.hash = ""
proc isInProgress*(status: TStatusEnum): bool =
return status in {sBuildInProgress, sTestInProgress, sDocGenInProgress,
sCSrcGenInProgress}
proc `$`*(status: TStatusEnum): string =
case status
of sBuildFailure:
return "build failure"
of sBuildInProgress:
return "build in progress"
of sBuildSuccess:
return "build finished"
of sTestFailure:
return "testing failure"
of sTestInProgress:
return "testing in progress"
of sTestSuccess:
return "testing finished"
of sDocGenFailure:
return "documentation generation failed"
of sDocGenInProgress:
return "generating documentation"
of sDocGenSuccess:
return "documentation generation succeeded"
of sCSrcGenFailure:
return "csource generation failed"
of sCSrcGenInProgress:
return "csource generation in progress"
of sCSrcGenSuccess:
return "csource generation succeeded"
of sUnknown:
return "unknown"
proc makeCommitPath*(platform, hash: string): string =
return platform / "nimrod_" & hash.substr(0, 11) # 11 Chars.

39
tests/compile/tcolors.nim Executable file
View file

@ -0,0 +1,39 @@
import strutils
type
TColor = distinct int32
proc rgb(r, g, b: range[0..255]): TColor =
result = TColor(r or g shl 8 or b shl 16)
proc `$`(c: TColor): string =
result = "#" & toHex(int32(c), 6)
echo rgb(34, 55, 255)
when false:
type
TColor = distinct int32
TColorComponent = distinct int8
proc red(a: TColor): TColorComponent =
result = TColorComponent(int32(a) and 0xff'i32)
proc green(a: TColor): TColorComponent =
result = TColorComponent(int32(a) shr 8'i32 and 0xff'i32)
proc blue(a: TColor): TColorComponent =
result = TColorComponent(int32(a) shr 16'i32 and 0xff'i32)
proc rgb(r, g, b: range[0..255]): TColor =
result = TColor(r or g shl 8 or b shl 8)
proc `+!` (a, b: TColorComponent): TColorComponent =
## saturated arithmetic:
result = TColorComponent(min(ze(int8(a)) + ze(int8(b)), 255))
proc `+` (a, b: TColor): TColor =
## saturated arithmetic for colors makes sense, I think:
return rgb(red(a) +! red(b), green(a) +! green(b), blue(a) +! blue(b))
rgb(34, 55, 255)

31
tests/compile/tconsteval.nim Executable file
View file

@ -0,0 +1,31 @@
discard """
"""
import strutils
const
HelpText = """
+-----------------------------------------------------------------+
| Maintenance program for Nimrod |
| Version $1|
| (c) 2009 Andreas Rumpf |
+-----------------------------------------------------------------+
Compiled at: $2, $3
Usage:
koch [options] command [options for command]
Options:
--force, -f, -B, -b forces rebuild
--help, -h shows this help and quits
Possible Commands:
boot [options] bootstraps with given command line options
clean cleans Nimrod project; removes generated files
web generates the website
csource [options] builds the C sources for installation
zip builds the installation ZIP package
inno builds the Inno Setup installer
""" % [NimrodVersion & repeatChar(44-len(NimrodVersion)),
CompileDate, CompileTime]
echo helpText

15
tests/compile/tconstraints.nim Executable file
View file

@ -0,0 +1,15 @@
proc myGenericProc[T: object|tuple|int|ptr|ref|distinct](x: T): string =
result = $x
type
TMyObj = tuple[x, y: int]
var
x: TMyObj
assert myGenericProc(232) == "232"
assert myGenericProc(x) == "(x: 0, y: 0)"

5
tests/compile/tconvcolors.nim Executable file
View file

@ -0,0 +1,5 @@
import colors
echo int32(colWhite), 'A'

38
tests/compile/tconvert.nim Executable file
View file

@ -0,0 +1,38 @@
import
Cairo
converter FloatConversion64(x: int): float64 = return toFloat(x)
converter FloatConversion32(x: int): float32 = return toFloat(x)
converter FloatConversionPlain(x: int): float = return toFloat(x)
const width = 500
const height = 500
const outFile = "CairoTest.png"
var surface = Cairo.ImageSurfaceCreate(CAIRO.FORMAT_RGB24, width, height)
var ç = Cairo.Create(surface)
ç.SetSourceRGB(1, 1, 1)
ç.Paint()
ç.SetLineWidth(10)
ç.SetLineCap(CAIRO.LINE_CAP_ROUND)
const count = 12
var winc = width / count
var hinc = width / count
for i in 1 .. count-1:
var amount = i / count
ç.SetSourceRGB(0, 1 - amount, amount)
ç.MoveTo(i * winc, hinc)
ç.LineTo(width - i * winc, height - hinc)
ç.Stroke()
ç.SetSourceRGB(1 - amount, 0, amount)
ç.MoveTo(winc, i * hinc)
ç.LineTo(width - winc, height - i * hinc)
ç.Stroke()
echo(surface.WriteToPNG(outFile))
surface.Destroy()

13
tests/compile/tcputime.nim Executable file
View file

@ -0,0 +1,13 @@
import times, os
var e = epochTime()
var c = cpuTime()
os.sleep(1500)
e = epochTime() - e
c = cpuTime() - c
echo "epochTime: ", e, " cpuTime: ", c

17
tests/compile/tdialogs.nim Executable file
View file

@ -0,0 +1,17 @@
# Test the dialogs module
import dialogs, gtk2
gtk2.nimrod_init()
var x = ChooseFilesToOpen(nil)
for a in items(x):
writeln(stdout, a)
info(nil, "start with an info box")
warning(nil, "now a warning ...")
error(nil, "... and an error!")
writeln(stdout, ChooseFileToOpen(nil))
writeln(stdout, ChooseFileToSave(nil))
writeln(stdout, ChooseDir(nil))

20
tests/compile/tdictdestruct.nim Executable file
View file

@ -0,0 +1,20 @@
type
TDict[TK, TV] = object
k: TK
v: TV
PDict[TK, TV] = ref TDict[TK, TV]
proc fakeNew[T](x: var ref T, destroy: proc (a: ref T)) =
nil
proc destroyDict[TK, TV](a: PDict[TK, TV]) =
return
proc newDict[TK, TV](a: TK, b: TV): PDict[TK, TV] =
Fakenew(result, destroyDict[TK, TV])
# Problem: destroyDict is not instantiated when newDict is instantiated!
discard newDict("a", "b")

View file

@ -0,0 +1,13 @@
# Test the discardable pragma
proc p(x, y: int): int {.discardable.} =
return x + y
# test that it is inherited from generic procs too:
proc q[T](x, y: T): T {.discardable.} =
return x + y
p(8, 2)
q[float](0.8, 0.2)

16
tests/compile/tdllvar.nim Executable file
View file

@ -0,0 +1,16 @@
import os
proc getDllName: string =
result = "mylib.dll"
if ExistsFile(result): return
result = "mylib2.dll"
if ExistsFile(result): return
quit("could not load dynamic library")
proc myImport(s: cstring) {.cdecl, importc, dynlib: getDllName().}
proc myImport2(s: int) {.cdecl, importc, dynlib: getDllName().}
myImport("test2")
myImport2(12)

32
tests/compile/tdumpast.nim Executable file
View file

@ -0,0 +1,32 @@
# Dump the contents of a PNimrodNode
import macros
template plus(a, b: expr): expr =
a + b
macro call(e: expr): expr =
return newCall("foo", newStrLitNode("bar"))
macro dumpAST(n: stmt): stmt =
# dump AST as a side-effect and return the inner node
echo n.lispRepr
echo n.treeRepr
var plusAst = getAst(plus(1, 2))
echo plusAst.lispRepr
var callAst = getAst(call())
echo callAst.lispRepr
var e = parseExpr("foo(bar + baz)")
echo e.lispRepr
result = n[1]
dumpAST:
proc add(x, y: int): int =
return x + y
proc sub(x, y: int): int = return x - y

View file

@ -0,0 +1,35 @@
# Dump the contents of a PNimrodNode
import macros
proc dumpit(n: PNimrodNode): string {.compileTime.} =
if n == nil: return "nil"
result = $n.kind
add(result, "(")
case n.kind
of nnkEmpty: nil # same as nil node in this representation
of nnkNilLit: add(result, "nil")
of nnkCharLit..nnkInt64Lit: add(result, $n.intVal)
of nnkFloatLit..nnkFloat64Lit: add(result, $n.floatVal)
of nnkStrLit..nnkTripleStrLit: add(result, $n.strVal)
of nnkIdent: add(result, $n.ident)
of nnkSym, nnkNone: assert false
else:
add(result, dumpit(n[0]))
for j in 1..n.len-1:
add(result, ", ")
add(result, dumpit(n[j]))
add(result, ")")
macro dumpAST(n: stmt): stmt =
# dump AST as a side-effect and return the inner node
echo dumpit(n)
result = n[1]
dumpAST:
proc add(x, y: int): int =
return x + y
proc sub(x, y: int): int = return x - y

3
tests/compile/techo.nim Executable file
View file

@ -0,0 +1,3 @@
# Simplest Nimrod program
echo "Hello, World!"

2
tests/compile/temptyecho.nim Executable file
View file

@ -0,0 +1,2 @@
echo()

3
tests/compile/tendian.nim Executable file
View file

@ -0,0 +1,3 @@
# test the new endian magic
writeln(stdout, repr(system.cpuEndian))

8
tests/compile/tenum.nim Executable file
View file

@ -0,0 +1,8 @@
# Test enums
type
E = enum a, b, c, x, y, z
var
en: E
en = a

16
tests/compile/tenum2.nim Executable file
View file

@ -0,0 +1,16 @@
# Test that enum with holes is handled correctly by case statement
type
TEnumHole = enum
eA = 0,
eB = 4,
eC = 5
var
e: TEnumHole = eB
case e
of eA: echo "A"
of eB: echo "B"
of eC: echo "C"

16
tests/compile/tenum3.nim Executable file
View file

@ -0,0 +1,16 @@
# Test enum with explicit size
type
TEnumHole {.size: sizeof(int).} = enum
eA = 0,
eB = 4,
eC = 5
var
e: TEnumHole = eB
case e
of eA: echo "A"
of eB: echo "B"
of eC: echo "C"

19
tests/compile/teval1.nim Executable file
View file

@ -0,0 +1,19 @@
import macros
proc testProc: string {.compileTime.} =
result = ""
result = result & ""
when true:
macro test(n: stmt): stmt =
result = newNimNode(nnkStmtList)
echo "#", testProc(), "#"
test:
"hi"
const
x = testProc()
echo "##", x, "##"

11
tests/compile/tfib.nim Executable file
View file

@ -0,0 +1,11 @@
iterator fibonacci(): int =
var a = 0
var b = 1
while true:
yield a
var c = b
b = a
a = a + c

View file

@ -0,0 +1,11 @@
discard """
output: "1.0000000000000000e+00 10"
"""
proc p[T](a, b: T): T
echo p(0.9, 0.1), " ", p(9, 1)
proc p[T](a, b: T): T =
result = a + b

9
tests/compile/tforwty.nim Executable file
View file

@ -0,0 +1,9 @@
# Test 13: forward types
type
PSym = ref TSym
TSym = object
next: PSym
var s: PSym

22
tests/compile/tforwty2.nim Executable file
View file

@ -0,0 +1,22 @@
# Test for a hard to fix internal error
# occured in the SDL library
{.push dynlib: "SDL.dll", callconv: cdecl.}
type
PSDL_semaphore = ptr TSDL_semaphore
TSDL_semaphore {.final.} = object
sem: Pointer #PSem_t;
when not defined(USE_NAMED_SEMAPHORES):
sem_data: int
when defined(BROKEN_SEMGETVALUE):
# This is a little hack for MacOS X -
# It's not thread-safe, but it's better than nothing
sem_value: cint
type
PSDL_Sem = ptr TSDL_Sem
TSDL_Sem = TSDL_Semaphore
proc SDL_CreateSemaphore(initial_value: Int32): PSDL_Sem {.
importc: "SDL_CreateSemaphore".}

View file

@ -0,0 +1,22 @@
discard """
disabled: true
"""
type
TMatcherKind = enum
mkTerminal, mkSequence, mkAlternation, mkRepeat
TMatcher[T] = object
case kind: TMatcherKind
of mkTerminal:
value: T
of mkSequence, mkAlternation:
matchers: seq[TMatcher[T]]
of mkRepeat:
matcher: PMatcher[T]
min, max: int
PMatcher[T] = ref TMatcher[T]
var
m: PMatcher[int]

View file

@ -0,0 +1,18 @@
type
TMatcherKind = enum
mkTerminal, mkSequence, mkAlternation, mkRepeat
TMatcher[T] = object
case kind: TMatcherKind
of mkTerminal:
value: T
of mkSequence, mkAlternation:
matchers: seq[TMatcher[T]]
of mkRepeat:
matcher: ref TMatcher[T]
min, max: int
var
m: ref TMatcher[int]

View file

@ -0,0 +1,5 @@
proc foo[T](thing: T) =
discard thing
var a: proc (thing: int) = foo[int]

28
tests/compile/tgenericrefs.nim Executable file
View file

@ -0,0 +1,28 @@
discard """
disabled: true
"""
# Compiles:
type
TA[T] = object
PA[T] = ref TA[T]
var a: PA[string]
# Compiles unless you use var a: PA[string]
type
PA = ref TA
TA[T] = object
# Cannot instantiate:
type
TA[T] = object
a: PA[T]
PA[T] = ref TA[T]
type
PA[T] = ref TA[T]
TA[T] = object

View file

@ -0,0 +1,23 @@
type
TMaybe[T] = object
case empty: Bool
of False: value: T
else: nil
proc Just*[T](val: T): TMaybe[T] =
result.empty = False
result.value = val
proc Nothing[T](): TMaybe[T] =
result.empty = True
proc safeReadLine(): TMaybe[string] =
var r = stdin.readLine()
if r == "": return Nothing[string]()
else: return Just(r)
when isMainModule:
var Test = Just("Test")
echo(Test.value)
var mSomething = safeReadLine()
echo(mSomething.value)

View file

@ -0,0 +1,7 @@
#
import times, os
var start = epochTime()
os.sleep(1000)
echo epochTime() - start #OUT 1000

51
tests/compile/tgtk.nim Executable file
View file

@ -0,0 +1,51 @@
import
gtk2, glib2, atk, gdk2, gdk2pixbuf, libglade2, pango,
pangoutils
proc hello(widget: PWidget, data: pointer) {.cdecl.} =
write(stdout, "Hello World\n")
proc delete_event(widget: PWidget, event: PEvent,
data: pointer): bool {.cdecl.} =
# If you return FALSE in the "delete_event" signal handler,
# GTK will emit the "destroy" signal. Returning TRUE means
# you don't want the window to be destroyed.
# This is useful for popping up 'are you sure you want to quit?'
# type dialogs.
write(stdout, "delete event occurred\n")
# Change TRUE to FALSE and the main window will be destroyed with
# a "delete_event".
return false
# Another callback
proc mydestroy(widget: PWidget, data: pointer) {.cdecl.} =
gtk2.main_quit()
proc mymain() =
# GtkWidget is the storage type for widgets
gtk2.nimrod_init()
var window = window_new(gtk2.WINDOW_TOPLEVEL)
discard g_signal_connect(window, "delete_event",
Gcallback(delete_event), nil)
discard g_signal_connect(window, "destroy", Gcallback(mydestroy), nil)
# Sets the border width of the window.
set_border_width(window, 10)
# Creates a new button with the label "Hello World".
var button = button_new("Hello World")
discard g_signal_connect(button, "clicked", Gcallback(hello), nil)
# This packs the button into the window (a gtk container).
add(window, button)
# The final step is to display this newly created widget.
show(button)
# and the window
show(window)
gtk2.main()
mymain()

83
tests/compile/thallo.nim Executable file
View file

@ -0,0 +1,83 @@
# Hallo
import
os, strutils, macros
type
TMyEnum = enum
meA, meB, meC, meD
when isMainModule:
{.hint: "this is the main file".}
proc fac[T](x: T): T =
# test recursive generic procs
if x <= 1: return 1
else: return x.`*`(fac(x-1))
macro macrotest(n: expr): stmt =
expectKind(n, nnkCall)
expectMinLen(n, 2)
result = newNimNode(nnkStmtList, n)
for i in 2..n.len-1:
result.add(newCall("write", n[1], n[i]))
result.add(newCall("writeln", n[1], newStrLitNode("")))
macro debug(n: expr): stmt =
result = newNimNode(nnkStmtList, n)
for i in 1..n.len-1:
result.add(newCall("write", newIdentNode("stdout"), toStrLit(n[i])))
result.add(newCall("write", newIdentNode("stdout"), newStrLitNode(": ")))
result.add(newCall("writeln", newIdentNode("stdout"), n[i]))
macrotest(stdout, "finally", 4, 5, "variable", "argument lists")
macrotest(stdout)
#GC_disable()
echo("This was compiled by Nimrod version " & system.nimrodVersion)
writeln(stdout, "Hello", " World", "!")
echo(["a", "b", "c", "d"].len)
for x in items(["What's", "your", "name", "?", ]):
echo(x)
var `name` = readLine(stdin)
{.breakpoint.}
echo("Hi " & thallo.name & "!\n")
debug(name)
var testseq: seq[string] = @[
"a", "b", "c", "d", "e"
]
echo(repr(testseq))
var dummy = "hello"
echo(substr(dummy, 2, 3))
echo($meC)
# test tuples:
for x, y in items([(1, 2), (3, 4), (6, 1), (5, 2)]):
echo x
echo y
proc simpleConst(): int = return 34
# test constant evaluation:
const
constEval3 = simpleConst()
constEval = "abc".contains('b')
constEval2 = fac(7)
echo(constEval3)
echo(constEval)
echo(constEval2)
echo(1.`+`(2))
for i in 2..6:
for j in countdown(i+4, 2):
echo(fac(i * j))
when isMainModule:
{.hint: "this is the main file".}

8
tests/compile/thexrange.nim Executable file
View file

@ -0,0 +1,8 @@
type
TArray = array[0x0012..0x0013, int]
var a: TArray
echo a[0] #OUT 0

22
tests/compile/tident.nim Executable file
View file

@ -0,0 +1,22 @@
type
TIdObj* = object of TObject
id*: int # unique id; use this for comparisons and not the pointers
PIdObj* = ref TIdObj
PIdent* = ref TIdent
TIdent*{.acyclic.} = object
s*: string
proc myNewString(L: int): string {.inline.} =
result = newString(L)
if result.len == L: echo("Length correct")
else: echo("bug")
for i in 0..L-1:
if result[i] == '\0':
echo("Correct")
else:
echo("Wrong")
var s = myNewString(8)

24
tests/compile/tindent1.nim Executable file
View file

@ -0,0 +1,24 @@
const romanNumbers1 =
[
("M", 1000), ("D", 500), ("C", 100),
("L", 50), ("X", 10), ("V", 5), ("I", 1) ]
const romanNumbers2 =
[
("M", 1000), ("D", 500), ("C", 100),
("L", 50), ("X", 10), ("V", 5), ("I", 1)
]
const romanNumbers3 =
[
("M", 1000), ("D", 500), ("C", 100),
("L", 50), ("X", 10), ("V", 5), ("I", 1)
]
const romanNumbers4 = [
("M", 1000), ("D", 500), ("C", 100),
("L", 50), ("X", 10), ("V", 5), ("I", 1)
]

7
tests/compile/tio.nim Executable file
View file

@ -0,0 +1,7 @@
# test the file-IO
proc main() =
for line in lines("thello.nim"):
writeln(stdout, line)
main()

44
tests/compile/titer.nim Executable file
View file

@ -0,0 +1,44 @@
# Test the new iterators
iterator xrange(fromm, to: int, step = 1): int =
var a = fromm
while a <= to:
yield a
inc(a, step)
iterator interval[T](a, b: T): T =
var x = a
while x <= b:
yield x
inc(x)
#
#iterator lines(filename: string): (line: string) =
# var
# f: tTextfile
# shouldClose = open(f, filename)
# if shouldClose:
# setSpace(line, 256)
# while readTextLine(f, line):
# yield line
# finally:
# if shouldClose: close(f)
#
for i in xrange(0, 5):
for k in xrange(1, 7):
write(stdout, "test")
for j in interval(45, 45):
write(stdout, "test2!")
write(stdout, "test3?")
for x in items(["hi", "what's", "your", "name"]):
echo(x)
const
stringArray = ["hi", "what's", "your", "name"]
for i in 0..len(stringArray)-1:
echo(stringArray[i])

51
tests/compile/titer2.nim Executable file
View file

@ -0,0 +1,51 @@
discard """
output: '''true'''
cmd: "nimrod cc --gc:none --hints:on $# $#"
"""
import hashes
type
TSlotEnum = enum seEmpty, seFilled, seDeleted
TKeyValuePair[A, B] = tuple[slot: TSlotEnum, key: A, val: B]
TKeyValuePairSeq[A, B] = seq[TKeyValuePair[A, B]]
TTable* {.final.}[A, B] = object
data: TKeyValuePairSeq[A, B]
counter: int
iterator mycountup(a, b: int): int =
var res = a
while res <= b:
yield res
inc(res)
when true:
iterator pairs*[A, B](t: TTable[A, B]): tuple[key: A, val: B] =
## iterates over any (key, value) pair in the table `t`.
for h in mycountup(0, high(t.data)):
var k = t.data[h].key
if t.data[h].slot == seFilled: yield (k, t.data[h].val)
else:
iterator pairs*(t: TTable[int, string]): tuple[key: int, val: string] =
## iterates over any (key, value) pair in the table `t`.
for h in mycountup(0, high(t.data)):
var k = t.data[h].key
if t.data[h].slot == seFilled: yield (k, t.data[h].val)
proc initTable*[A, B](initialSize=64): TTable[A, B] =
## creates a new hash table that is empty. `initialSize` needs to be
## a power of two.
result.counter = 0
newSeq(result.data, initialSize)
block Test1:
# generic cache does not instantiate the same iterator[types] twice. This
# means we have only one instantiation of 'h'. However, this is the same for
# a non-generic iterator!
var t = initTable[int, string]()
for k, v in t.pairs: nil
for k, v in t.pairs: nil
echo "true"

View file

@ -0,0 +1,13 @@
iterator xrange(fromm, to: int, step = 1): tuple[x, y: int] =
var a = fromm
while a <= to:
yield (a, a+1)
inc(a, step)
for a, b in xrange(3, 7):
echo a, " ", b
for tup in xrange(3, 7):
echo tup

18
tests/compile/tlastmod.nim Executable file
View file

@ -0,0 +1,18 @@
# test the new LastModificationTime() proc
import
os, times, strutils
proc main() =
var
a, b: TTime
a = getLastModificationTime(ParamStr(1))
b = getLastModificationTime(ParamStr(2))
writeln(stdout, $a)
writeln(stdout, $b)
if a < b:
Write(stdout, "$2 is newer than $1\n" % [ParamStr(1), ParamStr(2)])
else:
Write(stdout, "$1 is newer than $2\n" % [ParamStr(1), ParamStr(2)])
main()

60
tests/compile/tlexer.nim Executable file
View file

@ -0,0 +1,60 @@
discard """
disabled: true
"""
# We start with a comment
# This is the same comment
# This is a new one!
import
lexbase, os, strutils
type
TMyRec {.final.} = object
x, y: int # coordinates
c: char # a character
a: int32 # an integer
PMyRec = ref TMyRec # a reference to `TMyRec`
proc splitText(txt: string): seq[string] # splits a text into several lines
# the comment continues here
# this is not easy to parse!
proc anotherSplit(txt: string): seq[string] =
# the comment should belong to `anotherSplit`!
# another problem: comments are statements!
const
x = 0B0_10001110100_0000101001000111101011101111111011000101001101001001'f64 # x ~~ 1.72826e35
myNan = 0B01111111100000101100000000001000'f32 # NAN
y = """
a rather long text.
Over many
lines.
"""
s = "\xff"
a = {0..234}
b = {0..high(int)}
v = 0'i32
z = 6767566'f32
# small test program for lexbase
proc main*(infile: string, a, b: int, someverylongnamewithtype = 0,
anotherlongthingie = 3) =
var
myInt: int = 0
s: seq[string]
# this should be an error!
if initBaseLexer(L, infile, 30): nil
else:
writeln(stdout, "could not open: " & infile)
writeln(stdout, "Success!")
call(3, # we use 3
12, # we use 12
43) # we use 43
main(ParamStr(1), 9, 0)

24
tests/compile/tlibs.nim Executable file
View file

@ -0,0 +1,24 @@
# Test wether the bindings at least compile...
import
unicode, cgi, terminal, libcurl,
parsexml, parseopt, parsecfg,
osproc, complex,
sdl, smpeg, sdl_gfx, sdl_net, sdl_mixer, sdl_ttf,
sdl_image, sdl_mixer_nosmpeg,
cursorfont, xatom, xf86vmode, xkb, xrandr, xshm, xvlib, keysym, xcms, xi,
xkblib, xrender, xutil, x, xf86dga, xinerama, xlib, xresource, xv,
gtk2, glib2, pango, gdk2,
cairowin32, cairoxlib,
odbcsql,
gl, glut, glu, glx, glext, wingl,
lua, lualib, lauxlib, mysql, sqlite3, python, tcl,
db_postgres, db_mysql, db_sqlite, ropes, sockets, browsers, httpserver,
httpclient, parseutils, unidecode, xmldom, xmldomparser, xmltree, xmlparser,
htmlparser, re, graphics, colors, pegs
when defined(linux):
import
zlib, zipfiles
writeln(stdout, "test compilation of binding modules")

View file

@ -0,0 +1,24 @@
import strutils
var x = 343
case stdin.readline.parseInt
of 0:
echo "most common case"
of 1:
{.linearScanEnd.}
echo "second most common case"
of 2: echo "unlikely: use branch table"
else:
echo "unlikely too: use branch table"
case x
of 23: echo "23"
of 343: echo "343"
of 21: echo "21"
else:
{.linearScanEnd.}
echo "default"

64
tests/compile/tloops.nim Executable file
View file

@ -0,0 +1,64 @@
# Test nested loops and some other things
proc andTest() =
var a = 0 == 5 and 6 == 6
proc incx(x: var int) = # is built-in proc
x = x + 1
proc decx(x: var int) =
x = x - 1
proc First(y: var int) =
var x: int
i_ncx(x)
if x == 10:
y = 0
else:
if x == 0:
incx(x)
else:
x=11
proc TestLoops() =
var i, j: int
while i >= 0:
if i mod 3 == 0:
break
i = i + 1
while j == 13:
j = 13
break
break
while True:
break
proc Foo(n: int): int =
var
a, old: int
b, c: bool
F_irst(a)
if a == 10:
a = 30
elif a == 11:
a = 22
elif a == 12:
a = 23
elif b:
old = 12
else:
a = 40
#
b = false or 2 == 0 and 3 == 9
a = 0 + 3 * 5 + 6 + 7 + +8 # 36
while b:
a = a + 3
a = a + 5
write(stdout, "Hello!")
# We should come till here :-)
discard Foo(345)

21
tests/compile/tmacro1.nim Executable file
View file

@ -0,0 +1,21 @@
import macros
macro test*(a: stmt): stmt =
var nodes: tuple[a, b: int]
nodes.a = 4
nodes[1] = 45
type
TTypeEx = object
x, y: int
case b: bool
of false: nil
of true: z: float
var t: TTypeEx
t.b = true
t.z = 4.5
test:
"hi"

17
tests/compile/tmacrostmt.nim Executable file
View file

@ -0,0 +1,17 @@
import macros
macro case_token(n: stmt): stmt =
# creates a lexical analyzer from regular expressions
# ... (implementation is an exercise for the reader :-)
nil
case_token: # this colon tells the parser it is a macro statement
of r"[A-Za-z_]+[A-Za-z_0-9]*":
return tkIdentifier
of r"0-9+":
return tkInteger
of r"[\+\-\*\?]+":
return tkOperator
else:
return tkUnknown
case_token: inc i

View file

@ -0,0 +1,53 @@
# -*- nimrod -*-
import math
import os
import strutils
type TComplex = tuple[re, im: float]
proc `+` (a, b: TComplex): TComplex =
return (a.re + b.re, a.im + b.im)
proc `*` (a, b: TComplex): TComplex =
result.re = a.re * b.re - a.im * b.im
result.im = a.re * b.im + a.im * b.re
proc abs2 (a: TComplex): float =
return a.re * a.re + a.im * a.im
var size = parseInt (paramStr (1))
var bit = 128
var byteAcc = 0
stdout.writeln ("P4")
stdout.write ($size)
stdout.write (" ")
stdout.writeln ($size)
var fsize = float (size)
for y in 0 .. size-1:
var fy = 2.0 * float (y) / fsize - 1.0
for x in 0 .. size-1:
var z = (0.0, 0.0)
var c = (float (2*x) / fsize - 1.5, fy)
block iter:
for i in 0 .. 49:
z = z*z + c
if abs2 (z) >= 4.0:
break iter
byteAcc = byteAcc + bit
if bit > 1:
bit = bit div 2
else:
stdout.write (chr (byteAcc))
bit = 128
byteAcc = 0
if bit != 128:
stdout.write (chr (byteAcc))
bit = 128
byteAcc = 0

65
tests/compile/tmarshal.nim Executable file
View file

@ -0,0 +1,65 @@
discard """
output: ""
"""
import marshal
template testit(x: expr) = echo($$to[type(x)]($$x))
var x: array[0..4, array[0..4, string]] = [
["test", "1", "2", "3", "4"], ["test", "1", "2", "3", "4"],
["test", "1", "2", "3", "4"], ["test", "1", "2", "3", "4"],
["test", "1", "2", "3", "4"]]
testit(x)
var test2: tuple[name: string, s: int] = ("tuple test", 56)
testit(test2)
type
TE = enum
blah, blah2
TestObj = object
test, asd: int
case test2: TE
of blah:
help: string
else:
nil
PNode = ref TNode
TNode = object
next, prev: PNode
data: string
proc buildList(): PNode =
new(result)
new(result.next)
new(result.prev)
result.data = "middle"
result.next.data = "next"
result.prev.data = "prev"
result.next.next = result.prev
result.next.prev = result
result.prev.next = result
result.prev.prev = result.next
var test3: TestObj
test3.test = 42
test3.test2 = blah
testit(test3)
var test4: ref tuple[a, b: string]
new(test4)
test4.a = "ref string test: A"
test4.b = "ref string test: B"
testit(test4)
var test5 = @[(0,1),(2,3),(4,5)]
testit(test5)
var test7 = buildList()
testit(test7)
var test6: set[char] = {'A'..'Z', '_'}
testit(test6)

85
tests/compile/tmath.nim Executable file
View file

@ -0,0 +1,85 @@
# tests for the interpreter
proc loops(a: var int) =
nil
#var
# b: int
#b = glob
#while b != 0:
# b = b + 1
#a = b
proc mymax(a, b: int): int =
#loops(result)
result = a
if b > a: result = b
proc test(a, b: int) =
var
x, y: int
x = 0
y = 7
if x == a + b * 3 - 7 or
x == 8 or
x == y and y > -56 and y < 699:
y = 0
elif y == 78 and x == 0:
y = 1
elif y == 0 and x == 0:
y = 2
else:
y = 3
type
TTokType = enum
tkNil, tkType, tkConst, tkVar, tkSymbol, tkIf,
tkWhile, tkFor, tkLoop, tkCase, tkLabel, tkGoto
proc testCase(t: TTokType): int =
case t
of tkNil, tkType, tkConst: result = 0
of tkVar: result = 1
of tkSymbol: result = 2
of tkIf..tkFor: result = 3
of tkLoop: result = 56
else: result = -1
test(0, 9) # test the call
proc TestLoops() =
var
i, j: int
while i >= 0:
if i mod 3 == 0:
break
i = i + 1
while j == 13:
j = 13
break
break
while True:
break
var
glob: int
a: array [0..5, int]
proc main() =
#glob = 0
#loops( glob )
var
res: int
s: string
#write(stdout, mymax(23, 45))
write(stdout, "Hallo! Wie heißt du? ")
s = readLine(stdin)
# test the case statement
case s
of "Andreas": write(stdout, "Du bist mein Meister!\n")
of "Rumpf": write(stdout, "Du bist in der Familie meines Meisters!\n")
else: write(stdout, "ich kenne dich nicht!\n")
write(stdout, "Du heisst " & s & "\n")
main()

19
tests/compile/tmodulealias.nim Executable file
View file

@ -0,0 +1,19 @@
discard """
disabled: true
"""
when defined(windows):
import winlean
else:
import posix
when defined(Windows):
template orig: expr =
winlean
else:
template orig: expr =
posix
proc socket(domain, typ, protocol: int): int =
result = orig.socket(ord(domain), ord(typ), ord(protocol)))

8
tests/compile/tnamedparams.nim Executable file
View file

@ -0,0 +1,8 @@
import pegs
discard parsePeg(
pattern = "input",
filename = "filename",
line = 1,
col = 23)

View file

@ -0,0 +1,12 @@
discard """
output: "11"
"""
proc p(x, y: int): int =
result = x + y
echo p((proc (): int =
var x = 7
return x)(),
(proc (): int = return 4)())

49
tests/compile/tnew.nim Executable file
View file

@ -0,0 +1,49 @@
# Test the implementation of the new operator
# and the code generation for gc walkers
# (and the garbage collector):
type
PNode = ref TNode
TNode = object
data: int
str: string
le, ri: PNode
TStressTest = ref array [0..45, array [1..45, TNode]]
proc finalizer(n: PNode) =
write(stdout, n.data)
write(stdout, " is now freed\n")
proc newNode(data: int, le, ri: PNode): PNode =
new(result, finalizer)
result.le = le
result.ri = ri
result.data = data
# now loop and build a tree
proc main() =
var
i = 0
p: TStressTest
while i < 1000:
var n: PNode
n = newNode(i, nil, newNode(i + 10000, nil, nil))
inc(i)
new(p)
write(stdout, "Simple tree node allocation worked!\n")
i = 0
while i < 1000:
var m = newNode(i + 20000, nil, nil)
var k = newNode(i + 30000, nil, nil)
m.le = m
m.ri = k
k.le = m
k.ri = k
inc(i)
write(stdout, "Simple cycle allocation worked!\n")
main()

16
tests/compile/tnewlibs.nim Executable file
View file

@ -0,0 +1,16 @@
# Test wether the bindings at least compile...
import
tcl,
sdl, smpeg, sdl_gfx, sdl_net, sdl_mixer, sdl_ttf,
sdl_image, sdl_mixer_nosmpeg,
gtk2, glib2, pango, gdk2,
unicode, cgi, terminal, libcurl,
parsexml, parseopt, parsecfg,
osproc,
cairowin32, cairoxlib,
gl, glut, glu, glx, glext, wingl,
lua, lualib, lauxlib, mysql, sqlite3,
writeln(stdout, "test compilation of binding modules")

6
tests/compile/tnewsets.nim Executable file
View file

@ -0,0 +1,6 @@
# new test for sets:
const elem = ' '
var s: set[char] = {elem}
assert(elem in s and 'a' not_in s and 'c' not_in s )

12
tests/compile/tnewuns.nim Executable file
View file

@ -0,0 +1,12 @@
# test the new unsigned operations:
import
strutils
var
x, y: int
x = 1
y = high(int)
writeln(stdout, $ ( x +% y ) )

View file

@ -0,0 +1,13 @@
discard """
output: "bla"
disabled: true
"""
import macros
proc makeMacro: PNimrodNode =
result = nil
var p = makeMacro()
echo "bla"

View file

@ -0,0 +1,7 @@
import db_sqlite
var db: TDbConn
Exec(db, sql"create table blabla()")

17
tests/compile/tobjcov.nim Executable file
View file

@ -0,0 +1,17 @@
# Covariance is not type safe:
type
TA = object
a: int
TB = object of TA
b: array[0..5000_000, int]
proc ap(x: var TA) = x.a = -1
proc bp(x: var TB) = x.b[high(x.b)] = -1
# in Nimrod proc (x: TB) is compatible to proc (x: TA),
# but this is not type safe:
var f = cast[proc (x: var TA)](bp)
var a: TA
f(a) # bp expects a TB, but gets a TA

21
tests/compile/tobject2.nim Executable file
View file

@ -0,0 +1,21 @@
# Tests the object implementation
type
TPoint2d = object
x, y: int
TPoint3d = object of TPoint2d
z: int # added a field
proc getPoint( p: var TPoint2d) =
{.breakpoint.}
writeln(stdout, p.x)
var
p: TPoint3d
TPoint2d(p).x = 34
p.y = 98
p.z = 343
getPoint(p)

42
tests/compile/tobjects.nim Executable file
View file

@ -0,0 +1,42 @@
type
TBase = object
x, y: int
TSubclassKind = enum ka, kb, kc, kd, ke, kf
TSubclass = object of TBase
case c: TSubclassKind
of ka, kb, kc, kd:
a, b: int
of ke:
d, e, f: char
else: nil
n: bool
var
global: int
var
s: string
r: float = 0.0
i: int = 500 + 400
case i
of 500..999: write(stdout, "ha!\n")
of 1000..3000, 12: write(stdout, "ganz schön groß\n")
of 1, 2, 3: write(stdout, "1 2 oder 3\n")
else: write(stdout, "sollte nicht passieren\n")
case readLine(stdin)
of "Rumpf": write(stdout, "Hallo Meister!\n")
of "Andreas": write(stdout, "Hallo Meister!\n")
else: write(stdout, "Nicht mein Meister!\n")
global = global + 1
write(stdout, "Hallo wie heißt du? \n")
s = readLine(stdin)
i = 0
while i < len(s):
if s[i] == 'c': write(stdout, "'c' in deinem Namen gefunden\n")
i = i + 1
write(stdout, "Du heißt " & s)

21
tests/compile/toop.nim Executable file
View file

@ -0,0 +1,21 @@
discard """
disabled: true
"""
type
TA = object
x, y: int
TB = object of TA
z: int
TC = object of TB
whatever: string
proc p(a: var TA) = nil
proc p(b: var TB) = nil
var c: TC
p(c)

22
tests/compile/toptions.nim Executable file
View file

@ -0,0 +1,22 @@
# Converted by Pas2mor v1.54
# Used command line arguments:
# -m -q -o bootstrap\options.mor options.pas
#
type
# please make sure we have under 32 options (improves code efficiency!)
TOption = enum
optNone, optForceFullMake, optBoehmGC, optRefcGC, optRangeCheck,
optBoundsCheck, optOverflowCheck, optNilCheck, optAssert, optLineDir,
optWarns, optHints, optDeadCodeElim, optListCmd, optCompileOnly,
optSafeCode, # only allow safe code
optStyleCheck, optOptimizeSpeed, optOptimizeSize, optGenDynLib,
optGenGuiApp, optStackTrace
TOptionset = set[TOption]
var
gOptions: TOptionset = {optRefcGC, optRangeCheck, optBoundsCheck,
optOverflowCheck, optAssert, optWarns, optHints, optLineDir, optStackTrace}
compilerArgs: int
gExitcode: int8

12
tests/compile/tos.nim Executable file
View file

@ -0,0 +1,12 @@
# test some things of the os module
import os
proc walkDirTree(root: string) =
for k, f in walkDir(root):
case k
of pcFile, pcLinkToFile: echo(f)
of pcDir: walkDirTree(f)
of pcLinkToDir: nil
walkDirTree(".")

27
tests/compile/toverprc.nim Executable file
View file

@ -0,0 +1,27 @@
# Test overloading of procs when used as function pointers
import strutils
proc parseInt(x: float): int {.noSideEffect.} = nil
proc parseInt(x: bool): int {.noSideEffect.} = nil
proc parseInt(x: float32): int {.noSideEffect.} = nil
proc parseInt(x: int8): int {.noSideEffect.} = nil
proc parseInt(x: TFile): int {.noSideEffect.} = nil
proc parseInt(x: char): int {.noSideEffect.} = nil
proc parseInt(x: int16): int {.noSideEffect.} = nil
type
TParseInt = proc (x: string): int {.noSideEffect.}
var
q = TParseInt(parseInt)
p: TParseInt = parseInt
proc takeParseInt(x: proc (y: string): int {.noSideEffect.}): int =
result = x("123")
echo "Give a list of numbers (separated by spaces): "
var x = stdin.readline.split.each(parseInt).max
echo x, " is the maximum!"
echo "another number: ", takeParseInt(parseInt)

4
tests/compile/tparedef.nim Executable file
View file

@ -0,0 +1,4 @@
# This test is now superfluous:
proc a(a: int) =
return

25
tests/compile/tparscfg.nim Executable file
View file

@ -0,0 +1,25 @@
import
os, parsecfg, strutils, streams
var f = newFileStream(paramStr(1), fmRead)
if f != nil:
var p: TCfgParser
open(p, f, paramStr(1))
while true:
var e = next(p)
case e.kind
of cfgEof:
echo("EOF!")
break
of cfgSectionStart: ## a ``[section]`` has been parsed
echo("new section: " & e.section)
of cfgKeyValuePair:
echo("key-value-pair: " & e.key & ": " & e.value)
of cfgOption:
echo("command: " & e.key & ": " & e.value)
of cfgError:
echo(e.msg)
close(p)
else:
echo("cannot open: " & paramStr(1))

3
tests/compile/tparsefloat.nim Executable file
View file

@ -0,0 +1,3 @@
import strutils
echo ParseFloat("5000") / ParseFloat("10")

27
tests/compile/tparsopt.nim Executable file
View file

@ -0,0 +1,27 @@
# Test the new parseopt module
import
parseopt
proc writeHelp() =
writeln(stdout, "Usage: tparsopt [options] filename [options]")
proc writeVersion() =
writeln(stdout, "Version: 1.0.0")
var
filename = ""
for kind, key, val in getopt():
case kind
of cmdArgument:
filename = key
of cmdLongOption, cmdShortOption:
case key
of "help", "h": writeHelp()
of "version", "v": writeVersion()
else:
writeln(stdout, "Unknown command line option: ", key, ": ", val)
of cmdEnd: assert(false) # cannot happen
if filename == "":
# no filename has been given, so we show the help:
writeHelp()

16
tests/compile/tposix.nim Executable file
View file

@ -0,0 +1,16 @@
# Test Posix interface
when not defined(windows):
import posix
var
u: Tutsname
discard uname(u)
writeln(stdout, u.sysname)
writeln(stdout, u.nodename)
writeln(stdout, u.release)
writeln(stdout, u.machine)

30
tests/compile/tprep.nim Executable file
View file

@ -0,0 +1,30 @@
# Test the features that used to belong to the preprocessor
import
times
#{.warning: "This is only a test warning!".}
const
case2 = true
case3 = true
when defined(case1):
{.hint: "Case 1".}
when case3:
{.hint: "Case 1.3".}
elif case2:
{.hint: "Case 2".}
when case3:
{.hint: "Case 2.3".}
elif case3:
{.hint: "Case 3".}
else:
{.hint: "unknown case".}
var
s: string
write(stdout, "compiled at " & system.compileDate &
" " & compileTime & "\n")
echo getDateStr()
echo getClockStr()

15
tests/compile/tpush.nim Executable file
View file

@ -0,0 +1,15 @@
# test the new pragmas
{.push warnings: off, hints: off.}
proc noWarning() =
var
x: int
echo(x)
{.pop.}
proc WarnMe() =
var
x: int
echo(x)

26
tests/compile/tquicksort.nim Executable file
View file

@ -0,0 +1,26 @@
proc QuickSort(list: seq[int]): seq[int] =
if len(list) == 0:
return @[]
var pivot = list[0]
var left: seq[int] = @[]
var right: seq[int] = @[]
for i in low(list)..high(list):
if list[i] < pivot:
left.add(list[i])
elif list[i] > pivot:
right.add(list[i])
result = QuickSort(left) &
pivot &
QuickSort(right)
proc echoSeq(a: seq[int]) =
for i in low(a)..high(a):
echo(a[i])
var
list: seq[int]
list = QuickSort(@[89,23,15,23,56,123,356,12,7,1,6,2,9,4,3])
echoSeq(list)

6
tests/compile/tquit.nim Executable file
View file

@ -0,0 +1,6 @@
# Test the new beforeQuit variable:
proc myExit() {.noconv.} =
write(stdout, "just exiting...\n")
addQuitProc(myExit)

319
tests/compile/tradix.nim Executable file
View file

@ -0,0 +1,319 @@
# implements and tests an efficient radix tree
## another method to store an efficient array of pointers:
## We use a radix tree with node compression.
## There are two node kinds:
const bitsPerUnit = 8*sizeof(int)
type
TRadixNodeKind = enum rnLinear, rnFull, rnLeafBits, rnLeafLinear
PRadixNode = ptr TRadixNode
TRadixNode {.pure.} = object
kind: TRadixNodeKind
TRadixNodeLinear = object of TRadixNode
len: byte
keys: array [0..31, byte]
vals: array [0..31, PRadixNode]
TRadixNodeFull = object of TRadixNode
b: array [0..255, PRadixNode]
TRadixNodeLeafBits = object of TRadixNode
b: array [0..7, int]
TRadixNodeLeafLinear = object of TRadixNode
len: byte
keys: array [0..31, byte]
var
root: PRadixNode
proc searchInner(r: PRadixNode, a: int): PRadixNode =
case r.kind
of rnLinear:
var x = cast[ptr TRadixNodeLinear](r)
for i in 0..ze(x.len)-1:
if ze(x.keys[i]) == a: return x.vals[i]
of rnFull:
var x = cast[ptr TRadixNodeFull](r)
return x.b[a]
else: assert(false)
proc testBit(w, i: int): bool {.inline.} =
result = (w and (1 shl (i %% BitsPerUnit))) != 0
proc setBit(w: var int, i: int) {.inline.} =
w = w or (1 shl (i %% bitsPerUnit))
proc resetBit(w: var int, i: int) {.inline.} =
w = w and not (1 shl (i %% bitsPerUnit))
proc testOrSetBit(w: var int, i: int): bool {.inline.} =
var x = (1 shl (i %% bitsPerUnit))
if (w and x) != 0: return true
w = w or x
proc searchLeaf(r: PRadixNode, a: int): bool =
case r.kind
of rnLeafBits:
var x = cast[ptr TRadixNodeLeafBits](r)
return testBit(x.b[a /% BitsPerUnit], a)
of rnLeafLinear:
var x = cast[ptr TRadixNodeLeafLinear](r)
for i in 0..ze(x.len)-1:
if ze(x.keys[i]) == a: return true
else: assert(false)
proc exclLeaf(r: PRadixNode, a: int) =
case r.kind
of rnLeafBits:
var x = cast[ptr TRadixNodeLeafBits](r)
resetBit(x.b[a /% BitsPerUnit], a)
of rnLeafLinear:
var x = cast[ptr TRadixNodeLeafLinear](r)
var L = ze(x.len)
for i in 0..L-1:
if ze(x.keys[i]) == a:
x.keys[i] = x.keys[L-1]
dec(x.len)
return
else: assert(false)
proc in_Operator*(r: PRadixNode, a: TAddress): bool =
if r == nil: return false
var x = searchInner(r, a shr 24 and 0xff)
if x == nil: return false
x = searchInner(x, a shr 16 and 0xff)
if x == nil: return false
x = searchInner(x, a shr 8 and 0xff)
if x == nil: return false
return searchLeaf(x, a and 0xff)
proc excl*(r: PRadixNode, a: TAddress): bool =
if r == nil: return false
var x = searchInner(r, a shr 24 and 0xff)
if x == nil: return false
x = searchInner(x, a shr 16 and 0xff)
if x == nil: return false
x = searchInner(x, a shr 8 and 0xff)
if x == nil: return false
exclLeaf(x, a and 0xff)
proc addLeaf(r: var PRadixNode, a: int): bool =
if r == nil:
# a linear node:
var x = cast[ptr TRadixNodeLinear](alloc(sizeof(TRadixNodeLinear)))
x.kind = rnLeafLinear
x.len = 1'i8
x.keys[0] = toU8(a)
r = x
return false # not already in set
case r.kind
of rnLeafBits:
var x = cast[ptr TRadixNodeLeafBits](r)
return testOrSetBit(x.b[a /% BitsPerUnit], a)
of rnLeafLinear:
var x = cast[ptr TRadixNodeLeafLinear](r)
var L = ze(x.len)
for i in 0..L-1:
if ze(x.keys[i]) == a: return true
if L <= high(x.keys):
x.keys[L] = toU8(a)
inc(x.len)
else:
# transform into a full node:
var y = cast[ptr TRadixNodeLeafBits](alloc0(sizeof(TRadixNodeLeafBits)))
y.kind = rnLeafBits
for i in 0..ze(x.len)-1:
var u = ze(x.keys[i])
setBit(y.b[u /% BitsPerUnit], u)
setBit(y.b[a /% BitsPerUnit], a)
dealloc(r)
r = y
else: assert(false)
proc addInner(r: var PRadixNode, a: int, d: int): bool =
if d == 0:
return addLeaf(r, a and 0xff)
var k = a shr d and 0xff
if r == nil:
# a linear node:
var x = cast[ptr TRadixNodeLinear](alloc(sizeof(TRadixNodeLinear)))
x.kind = rnLinear
x.len = 1'i8
x.keys[0] = toU8(k)
r = x
return addInner(x.vals[0], a, d-8)
case r.kind
of rnLinear:
var x = cast[ptr TRadixNodeLinear](r)
var L = ze(x.len)
for i in 0..L-1:
if ze(x.keys[i]) == k: # already exists
return addInner(x.vals[i], a, d-8)
if L <= high(x.keys):
x.keys[L] = toU8(k)
inc(x.len)
return addInner(x.vals[L], a, d-8)
else:
# transform into a full node:
var y = cast[ptr TRadixNodeFull](alloc0(sizeof(TRadixNodeFull)))
y.kind = rnFull
for i in 0..L-1: y.b[ze(x.keys[i])] = x.vals[i]
dealloc(r)
r = y
return addInner(y.b[k], a, d-8)
of rnFull:
var x = cast[ptr TRadixNodeFull](r)
return addInner(x.b[k], a, d-8)
else: assert(false)
proc incl*(r: var PRadixNode, a: TAddress) {.inline.} =
discard addInner(r, a, 24)
proc testOrIncl*(r: var PRadixNode, a: TAddress): bool {.inline.} =
return addInner(r, a, 24)
iterator innerElements(r: PRadixNode): tuple[prefix: int, n: PRadixNode] =
if r != nil:
case r.kind
of rnFull:
var r = cast[ptr TRadixNodeFull](r)
for i in 0..high(r.b):
if r.b[i] != nil:
yield (i, r.b[i])
of rnLinear:
var r = cast[ptr TRadixNodeLinear](r)
for i in 0..ze(r.len)-1:
yield (ze(r.keys[i]), r.vals[i])
else: assert(false)
iterator leafElements(r: PRadixNode): int =
if r != nil:
case r.kind
of rnLeafBits:
var r = cast[ptr TRadixNodeLeafBits](r)
# iterate over any bit:
for i in 0..high(r.b):
if r.b[i] != 0: # test all bits for zero
for j in 0..BitsPerUnit-1:
if testBit(r.b[i], j):
yield i*BitsPerUnit+j
of rnLeafLinear:
var r = cast[ptr TRadixNodeLeafLinear](r)
for i in 0..ze(r.len)-1:
yield ze(r.keys[i])
else: assert(false)
iterator elements*(r: PRadixNode): TAddress {.inline.} =
for p1, n1 in innerElements(r):
for p2, n2 in innerElements(n1):
for p3, n3 in innerElements(n2):
for p4 in leafElements(n3):
yield p1 shl 24 or p2 shl 16 or p3 shl 8 or p4
proc main() =
const
numbers = [128, 1, 2, 3, 4, 255, 17, -8, 45, 19_000]
var
r: PRadixNode = nil
for x in items(numbers):
echo testOrIncl(r, x)
for x in elements(r): echo(x)
main()
when false:
proc traverse(r: PRadixNode, prefix: int, d: int) =
if r == nil: return
case r.kind
of rnLeafBits:
assert(d == 0)
var x = cast[ptr TRadixNodeLeafBits](r)
# iterate over any bit:
for i in 0..high(x.b):
if x.b[i] != 0: # test all bits for zero
for j in 0..BitsPerUnit-1:
if testBit(x.b[i], j):
visit(prefix or i*BitsPerUnit+j)
of rnLeafLinear:
assert(d == 0)
var x = cast[ptr TRadixNodeLeafLinear](r)
for i in 0..ze(x.len)-1:
visit(prefix or ze(x.keys[i]))
of rnFull:
var x = cast[ptr TRadixNodeFull](r)
for i in 0..high(r.b):
if r.b[i] != nil:
traverse(r.b[i], prefix or (i shl d), d-8)
of rnLinear:
var x = cast[ptr TRadixNodeLinear](r)
for i in 0..ze(x.len)-1:
traverse(x.vals[i], prefix or (ze(x.keys[i]) shl d), d-8)
type
TRadixIter {.final.} = object
r: PRadixNode
p: int
x: int
proc init(i: var TRadixIter, r: PRadixNode) =
i.r = r
i.x = 0
i.p = 0
proc nextr(i: var TRadixIter): PRadixNode =
if i.r == nil: return nil
case i.r.kind
of rnFull:
var r = cast[ptr TRadixNodeFull](i.r)
while i.x <= high(r.b):
if r.b[i.x] != nil:
i.p = i.x
return r.b[i.x]
inc(i.x)
of rnLinear:
var r = cast[ptr TRadixNodeLinear](i.r)
if i.x < ze(r.len):
i.p = ze(r.keys[i.x])
result = r.vals[i.x]
inc(i.x)
else: assert(false)
proc nexti(i: var TRadixIter): int =
result = -1
case i.r.kind
of rnLeafBits:
var r = cast[ptr TRadixNodeLeafBits](i.r)
# iterate over any bit:
for i in 0..high(r.b):
if x.b[i] != 0: # test all bits for zero
for j in 0..BitsPerUnit-1:
if testBit(x.b[i], j):
visit(prefix or i*BitsPerUnit+j)
of rnLeafLinear:
var r = cast[ptr TRadixNodeLeafLinear](i.r)
if i.x < ze(r.len):
result = ze(r.keys[i.x])
inc(i.x)
iterator elements(r: PRadixNode): TAddress {.inline.} =
var
a, b, c, d: TRadixIter
init(a, r)
while true:
var x = nextr(a)
if x != nil:
init(b, x)
while true:
var y = nextr(b)
if y != nil:
init(c, y)
while true:
var z = nextr(c)
if z != nil:
init(d, z)
while true:
var q = nexti(d)
if q != -1:
yield a.p shl 24 or b.p shl 16 or c.p shl 8 or q

12
tests/compile/treadln.nim Executable file
View file

@ -0,0 +1,12 @@
# test the improved readline handling that does not care whether its
# Macintosh, Unix or Windows text format.
var
inp: TFile
line: string
if open(inp, "readme.txt"):
while not EndOfFile(inp):
line = readLine(inp)
echo("#" & line & "#")
close(inp)

12
tests/compile/treadx.nim Executable file
View file

@ -0,0 +1,12 @@
import posix
var inp = ""
var buf: array[0..10, char]
while true:
var r = read(0, addr(buf), sizeof(buf)-1)
add inp, $buf
if r != sizeof(buf)-1: break
echo inp
#dafkladskölklödsaf ölksdakölfölksfklwe4iojr389wr 89uweokf sdlkf jweklr jweflksdj fioewjfsdlfsd

2
tests/compile/trecmod.nim Executable file
View file

@ -0,0 +1,2 @@
# recursive module
import mrecmod

10
tests/compile/trecmod2.nim Executable file
View file

@ -0,0 +1,10 @@
type
T1* = int # Module A exports the type ``T1``
import mrecmod2 # the compiler starts parsing B
proc main() =
var i = p(3) # works because B has been parsed completely here
main()

9
tests/compile/trectuple.nim Executable file
View file

@ -0,0 +1,9 @@
type
PNode = ref TNode
TNode = tuple[self: PNode]
var node: PNode
new(node)
node.self = node

View file

@ -0,0 +1,10 @@
type Node = tuple[left: ref Node]
proc traverse(root: ref Node) =
if root.left != nil: traverse(root.left)
type A = tuple[B: ptr A]
proc C(D: ptr A) = C(D.B)

32
tests/compile/trepr.nim Executable file
View file

@ -0,0 +1,32 @@
# test the new "repr" built-in proc
type
TEnum = enum
en1, en2, en3, en4, en5, en6
TPoint {.final.} = object
x, y, z: int
s: array [0..1, string]
e: TEnum
var
p: TPoint
q: ref TPoint
s: seq[ref TPoint]
p.x = 0
p.y = 13
p.z = 45
p.s[0] = "abc"
p.s[1] = "xyz"
p.e = en6
new(q)
q[] = p
s = @[q, q, q, q]
writeln(stdout, repr(p))
writeln(stdout, repr(q))
writeln(stdout, repr(s))
writeln(stdout, repr(en4))

13
tests/compile/tseq2.nim Executable file
View file

@ -0,0 +1,13 @@
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])

9
tests/compile/tseqcon2.nim Executable file
View file

@ -0,0 +1,9 @@
import os
proc rec_dir(dir: string): seq[string] =
result = @[]
for kind, path in walk_dir(dir):
if kind == pcDir:
add(result, rec_dir(path))
else:
add(result, path)

View file

@ -0,0 +1,24 @@
type
TListItemType* = enum
RedisNil, RedisString
TListItem* = object
case kind*: TListItemType
of RedisString:
str*: string
else: nil
TRedisList* = seq[TListItem]
# Caused by this.
proc seq*() =
nil
proc lrange*(key: string): TRedisList =
var foo: TListItem
foo.kind = RedisNil
result = @[foo]
when isMainModule:
var p = lrange("mylist")
for i in items(p):
echo(i.str)

10
tests/compile/tsizeof.nim Executable file
View file

@ -0,0 +1,10 @@
# Test the sizeof proc
type
TMyRecord {.final.} = object
x, y: int
b: bool
r: float
s: string
write(stdout, sizeof(TMyRecord))

Some files were not shown because too many files have changed in this diff Show more