From dbf9117c562601d6b571d964a6cb152e95fe8c4e Mon Sep 17 00:00:00 2001 From: Araq Date: Fri, 22 Aug 2014 23:54:26 +0200 Subject: [PATCH] the big renamefest: first steps --- compiler/ast.nim | 5 +- compiler/ccgstmts.nim | 12 +- compiler/condsyms.nim | 1 + compiler/lookups.nim | 91 +++++++------ compiler/magicsys.nim | 12 +- compiler/msgs.nim | 2 +- compiler/pragmas.nim | 39 ++++-- compiler/pretty.nim | 114 ++-------------- compiler/prettybase.nim | 59 ++++++++ compiler/semgnrc.nim | 4 +- compiler/sempass2.nim | 15 ++- compiler/transf.nim | 4 +- doc/exception_hierarchy_fragment.txt | 59 ++++---- doc/lib.txt | 60 ++++----- doc/manual.txt | 184 ++++++++++++------------- doc/nimrodc.txt | 192 +++++++++++++-------------- lib/packages/docutils/highlite.nim | 18 +-- lib/packages/docutils/rstgen.nim | 12 +- lib/system.nim | 2 +- lib/system/alloc.nim | 4 +- lib/system/ansi_c.nim | 4 +- lib/system/arithm.nim | 2 +- lib/system/assign.nim | 2 +- lib/system/atomics.nim | 5 +- lib/system/avltree.nim | 2 +- lib/system/cellsets.nim | 2 +- lib/system/cgprocs.nim | 2 +- lib/system/channels.nim | 2 +- lib/system/chcks.nim | 2 +- lib/system/debugger.nim | 4 +- lib/system/deepcopy.nim | 2 +- lib/system/dyncalls.nim | 2 +- lib/system/embedded.nim | 2 +- lib/system/endb.nim | 4 +- lib/system/excpt.nim | 10 +- lib/system/gc.nim | 2 +- lib/system/gc2.nim | 2 +- lib/system/gc_ms.nim | 4 +- lib/system/hti.nim | 2 +- lib/system/inclrtl.nim | 2 +- lib/system/jssys.nim | 4 +- lib/system/mmdisp.nim | 8 +- lib/system/profiler.nim | 4 +- lib/system/repr.nim | 2 +- lib/system/reprjs.nim | 2 +- lib/system/sets.nim | 2 +- lib/system/syslocks.nim | 2 +- lib/system/sysspawn.nim | 4 +- lib/system/sysstr.nim | 8 +- lib/system/threads.nim | 14 +- lib/system/timers.nim | 2 +- lib/system/widestrs.nim | 4 +- tests/parallel/tflowvar.nim | 22 ++- todo.txt | 5 + web/news.txt | 2 + web/question.txt | 4 +- 56 files changed, 529 insertions(+), 508 deletions(-) create mode 100644 compiler/prettybase.nim diff --git a/compiler/ast.nim b/compiler/ast.nim index 7ad2946957..63cab59980 100644 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -501,7 +501,8 @@ type skStub, # symbol is a stub and not yet loaded from the ROD # file (it is loaded on demand, which may # mean: never) - skPackage # symbol is a package (used for canonicalization) + skPackage, # symbol is a package (used for canonicalization) + skAlias # an alias (needs to be resolved immediately) TSymKinds* = set[TSymKind] const @@ -872,7 +873,7 @@ const tyProc, tyString, tyError} ExportableSymKinds* = {skVar, skConst, skProc, skMethod, skType, skIterator, skClosureIterator, - skMacro, skTemplate, skConverter, skEnumField, skLet, skStub} + skMacro, skTemplate, skConverter, skEnumField, skLet, skStub, skAlias} PersistentNodeFlags*: TNodeFlags = {nfBase2, nfBase8, nfBase16, nfDotSetter, nfDotField, nfIsRef} diff --git a/compiler/ccgstmts.nim b/compiler/ccgstmts.nim index eca026e127..0c3d35f7ba 100644 --- a/compiler/ccgstmts.nim +++ b/compiler/ccgstmts.nim @@ -489,6 +489,8 @@ proc genBreakStmt(p: BProc, t: PNode) = proc getRaiseFrmt(p: BProc): string = if gCmd == cmdCompileToCpp: result = "throw NimException($1, $2);$n" + elif getCompilerProc("Exception") != nil: + result = "#raiseException((#Exception*)$1, $2);$n" else: result = "#raiseException((#E_Base*)$1, $2);$n" @@ -733,7 +735,10 @@ proc genTryCpp(p: BProc, t: PNode, d: var TLoc) = i, length, blen: int genLineDir(p, t) exc = getTempName() - discard cgsym(p.module, "E_Base") + if getCompilerProc("Exception") != nil: + discard cgsym(p.module, "Exception") + else: + discard cgsym(p.module, "E_Base") add(p.nestedTryStmts, t) startBlock(p, "try {$n") expr(p, t.sons[0], d) @@ -815,7 +820,10 @@ proc genTry(p: BProc, t: PNode, d: var TLoc) = discard lists.includeStr(p.module.headerFiles, "") genLineDir(p, t) var safePoint = getTempName() - discard cgsym(p.module, "E_Base") + if getCompilerProc("Exception") != nil: + discard cgsym(p.module, "Exception") + else: + discard cgsym(p.module, "E_Base") linefmt(p, cpsLocals, "#TSafePoint $1;$n", safePoint) linefmt(p, cpsStmts, "#pushSafePoint(&$1);$n", safePoint) linefmt(p, cpsStmts, "$1.status = setjmp($1.context);$n", safePoint) diff --git a/compiler/condsyms.nim b/compiler/condsyms.nim index dc61d2f894..6b93b1c12d 100644 --- a/compiler/condsyms.nim +++ b/compiler/condsyms.nim @@ -85,6 +85,7 @@ proc initDefines*() = defineSymbol("nimnewshared") defineSymbol("nimrequiresnimframe") defineSymbol("nimparsebiggestfloatmagic") + defineSymbol("nimalias") # add platform specific symbols: for c in low(CPU)..high(CPU): diff --git a/compiler/lookups.nim b/compiler/lookups.nim index aee64f52f1..9fecdba6bd 100644 --- a/compiler/lookups.nim +++ b/compiler/lookups.nim @@ -1,6 +1,6 @@ # # -# The Nimrod Compiler +# The Nim Compiler # (c) Copyright 2012 Andreas Rumpf # # See the file "copying.txt", included in this @@ -11,7 +11,7 @@ import intsets, ast, astalgo, idents, semdata, types, msgs, options, rodread, - renderer, wordrecg, idgen + renderer, wordrecg, idgen, prettybase proc ensureNoMissingOrUnusedSymbols(scope: PScope) @@ -65,6 +65,17 @@ iterator walkScopes*(scope: PScope): PScope = yield current current = current.parent +proc skipAlias*(s: PSym; n: PNode): PSym = + if s == nil or s.kind != skAlias: + result = s + else: + result = s.owner + if gCmd == cmdPretty: + prettybase.replaceDeprecated(n.info, s, result) + else: + message(n.info, warnDeprecated, "use " & result.name.s & " instead; " & + s.name.s) + proc localSearchInScope*(c: PContext, s: PIdent): PSym = result = strTableGet(c.currentScope.symbols, s) @@ -183,15 +194,15 @@ proc lookUp*(c: PContext, n: PNode): PSym = # Looks up a symbol. Generates an error in case of nil. case n.kind of nkIdent: - result = searchInScopes(c, n.ident) - if result == nil: + result = searchInScopes(c, n.ident).skipAlias(n) + if result == nil: localError(n.info, errUndeclaredIdentifier, n.ident.s) result = errorSym(c, n) of nkSym: result = n.sym of nkAccQuoted: var ident = considerQuotedIdent(n) - result = searchInScopes(c, ident) + result = searchInScopes(c, ident).skipAlias(n) if result == nil: localError(n.info, errUndeclaredIdentifier, ident.s) result = errorSym(c, n) @@ -210,32 +221,32 @@ proc qualifiedLookUp*(c: PContext, n: PNode, flags = {checkUndeclared}): PSym = case n.kind of nkIdent, nkAccQuoted: var ident = considerQuotedIdent(n) - result = searchInScopes(c, ident) - if result == nil and checkUndeclared in flags: + result = searchInScopes(c, ident).skipAlias(n) + if result == nil and checkUndeclared in flags: localError(n.info, errUndeclaredIdentifier, ident.s) result = errorSym(c, n) - elif checkAmbiguity in flags and result != nil and - contains(c.ambiguousSymbols, result.id): + elif checkAmbiguity in flags and result != nil and + contains(c.ambiguousSymbols, result.id): localError(n.info, errUseQualifier, ident.s) of nkSym: result = n.sym - if checkAmbiguity in flags and contains(c.ambiguousSymbols, result.id): + if checkAmbiguity in flags and contains(c.ambiguousSymbols, result.id): localError(n.info, errUseQualifier, n.sym.name.s) - of nkDotExpr: + of nkDotExpr: result = nil var m = qualifiedLookUp(c, n.sons[0], flags*{checkUndeclared}) - if (m != nil) and (m.kind == skModule): + if m != nil and m.kind == skModule: var ident: PIdent = nil - if n.sons[1].kind == nkIdent: + if n.sons[1].kind == nkIdent: ident = n.sons[1].ident - elif n.sons[1].kind == nkAccQuoted: + elif n.sons[1].kind == nkAccQuoted: ident = considerQuotedIdent(n.sons[1]) - if ident != nil: - if m == c.module: - result = strTableGet(c.topLevelScope.symbols, ident) - else: - result = strTableGet(m.tab, ident) - if result == nil and checkUndeclared in flags: + if ident != nil: + if m == c.module: + result = strTableGet(c.topLevelScope.symbols, ident).skipAlias(n) + else: + result = strTableGet(m.tab, ident).skipAlias(n) + if result == nil and checkUndeclared in flags: localError(n.sons[1].info, errUndeclaredIdentifier, ident.s) result = errorSym(c, n.sons[1]) elif n.sons[1].kind == nkSym: @@ -256,7 +267,7 @@ proc initOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym = o.scope = c.currentScope o.mode = oimNoQualifier while true: - result = initIdentIter(o.it, o.scope.symbols, ident) + result = initIdentIter(o.it, o.scope.symbols, ident).skipAlias(n) if result != nil: break else: @@ -277,11 +288,12 @@ proc initOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym = if ident != nil: if o.m == c.module: # a module may access its private members: - result = initIdentIter(o.it, c.topLevelScope.symbols, ident) + result = initIdentIter(o.it, c.topLevelScope.symbols, + ident).skipAlias(n) o.mode = oimSelfModule - else: - result = initIdentIter(o.it, o.m.tab, ident) - else: + else: + result = initIdentIter(o.it, o.m.tab, ident).skipAlias(n) + else: localError(n.sons[1].info, errIdentifierExpected, renderTree(n.sons[1])) result = errorSym(c, n.sons[1]) @@ -307,18 +319,18 @@ proc nextOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym = result = nil of oimNoQualifier: if o.scope != nil: - result = nextIdentIter(o.it, o.scope.symbols) + result = nextIdentIter(o.it, o.scope.symbols).skipAlias(n) while result == nil: o.scope = o.scope.parent if o.scope == nil: break - result = initIdentIter(o.it, o.scope.symbols, o.it.name) + result = initIdentIter(o.it, o.scope.symbols, o.it.name).skipAlias(n) # BUGFIX: o.it.name <-> n.ident else: result = nil of oimSelfModule: - result = nextIdentIter(o.it, c.topLevelScope.symbols) + result = nextIdentIter(o.it, c.topLevelScope.symbols).skipAlias(n) of oimOtherModule: - result = nextIdentIter(o.it, o.m.tab) + result = nextIdentIter(o.it, o.m.tab).skipAlias(n) of oimSymChoice: if o.symChoiceIndex < sonsLen(n): result = n.sons[o.symChoiceIndex].sym @@ -329,31 +341,18 @@ proc nextOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym = o.mode = oimSymChoiceLocalLookup o.scope = c.currentScope result = firstIdentExcluding(o.it, o.scope.symbols, - n.sons[0].sym.name, o.inSymChoice) + n.sons[0].sym.name, o.inSymChoice).skipAlias(n) while result == nil: o.scope = o.scope.parent if o.scope == nil: break result = firstIdentExcluding(o.it, o.scope.symbols, - n.sons[0].sym.name, o.inSymChoice) + n.sons[0].sym.name, o.inSymChoice).skipAlias(n) of oimSymChoiceLocalLookup: - result = nextIdentExcluding(o.it, o.scope.symbols, o.inSymChoice) + result = nextIdentExcluding(o.it, o.scope.symbols, o.inSymChoice).skipAlias(n) while result == nil: o.scope = o.scope.parent if o.scope == nil: break result = firstIdentExcluding(o.it, o.scope.symbols, - n.sons[0].sym.name, o.inSymChoice) + n.sons[0].sym.name, o.inSymChoice).skipAlias(n) if result != nil and result.kind == skStub: loadStub(result) - -when false: - proc qualifiedLookUpPreferImmediate*(c: PContext, n: PNode, - flags = {checkUndeclared}): PSym = - var o: TOverloadIter - result = initOverloadIter(o, c, n) - var a = result - while a != nil: - if sfImmediate in a.flags: return a - a = nextOverloadIter(o, c, n) - if result == nil and checkUndeclared in flags: - localError(n.info, errUndeclaredIdentifier, n.considerQuotedIdent.s) - result = errorSym(c, n) diff --git a/compiler/magicsys.nim b/compiler/magicsys.nim index 4753261614..a794253df2 100644 --- a/compiler/magicsys.nim +++ b/compiler/magicsys.nim @@ -1,6 +1,6 @@ # # -# The Nimrod Compiler +# The Nim Compiler # (c) Copyright 2012 Andreas Rumpf # # See the file "copying.txt", included in this @@ -44,6 +44,7 @@ proc getSysSym(name: string): PSym = result = newSym(skError, getIdent(name), systemModule, systemModule.info) result.typ = newType(tyError, systemModule) if result.kind == skStub: loadStub(result) + if result.kind == skAlias: result = result.owner proc getSysMagic*(name: string, m: TMagic): PSym = var ti: TIdentIter @@ -165,13 +166,14 @@ proc setIntLitType*(result: PNode) = proc getCompilerProc(name: string): PSym = var ident = getIdent(name, hashIgnoreStyle(name)) result = strTableGet(compilerprocs, ident) - if result == nil: + if result == nil: result = strTableGet(rodCompilerprocs, ident) - if result != nil: + if result != nil: strTableAdd(compilerprocs, result) if result.kind == skStub: loadStub(result) - -proc registerCompilerProc(s: PSym) = + if result.kind == skAlias: result = result.owner + +proc registerCompilerProc(s: PSym) = strTableAdd(compilerprocs, s) proc finishSystem(tab: TStrTable) = discard diff --git a/compiler/msgs.nim b/compiler/msgs.nim index 730cb96055..cd5b34194e 100644 --- a/compiler/msgs.nim +++ b/compiler/msgs.nim @@ -368,7 +368,7 @@ const warnOctalEscape: "octal escape sequences do not exist; leading zero is ignored [OctalEscape]", warnXIsNeverRead: "\'$1\' is never read [XIsNeverRead]", warnXmightNotBeenInit: "\'$1\' might not have been initialized [XmightNotBeenInit]", - warnDeprecated: "\'$1\' is deprecated [Deprecated]", + warnDeprecated: "$1 is deprecated [Deprecated]", warnConfigDeprecated: "config file '$1' is deprecated [ConfigDeprecated]", warnSmallLshouldNotBeUsed: "\'l\' should not be used as an identifier; may look like \'1\' (one) [SmallLshouldNotBeUsed]", warnUnknownMagic: "unknown magic \'$1\' might crash the compiler [UnknownMagic]", diff --git a/compiler/pragmas.nim b/compiler/pragmas.nim index 024401b863..24b2f67508 100644 --- a/compiler/pragmas.nim +++ b/compiler/pragmas.nim @@ -1,6 +1,6 @@ # # -# The Nimrod Compiler +# The Nim Compiler # (c) Copyright 2014 Andreas Rumpf # # See the file "copying.txt", included in this @@ -45,7 +45,7 @@ const wBreakpoint, wWatchPoint, wPassl, wPassc, wDeadCodeElim, wDeprecated, wFloatchecks, wInfChecks, wNanChecks, wPragma, wEmit, wUnroll, wLinearScanEnd, wPatterns, wEffects, wNoForward, wComputedGoto, - wInjectStmt} + wInjectStmt, wDeprecated} lambdaPragmas* = {FirstCallConv..LastCallConv, wImportc, wExportc, wNodecl, wNosideeffect, wSideeffect, wNoreturn, wDynlib, wHeader, wDeprecated, wExtern, wThread, wImportCpp, wImportObjC, wAsmNoStackFrame, @@ -542,6 +542,27 @@ proc typeBorrow(sym: PSym, n: PNode) = localError(n.info, "a type can only borrow `.` for now") incl(sym.typ.flags, tfBorrowDot) +proc markCompilerProc(s: PSym) = + makeExternExport(s, "$1", s.info) + incl(s.flags, sfCompilerProc) + incl(s.flags, sfUsed) + registerCompilerProc(s) + +proc deprecatedStmt(c: PContext; pragma: PNode) = + let pragma = pragma[1] + if pragma.kind != nkBracket: + localError(pragma.info, "list of key:value pairs expected"); return + for n in pragma: + if n.kind in {nkExprColonExpr, nkExprEqExpr}: + let dest = qualifiedLookUp(c, n[1]) + let src = considerQuotedIdent(n[0]) + let alias = newSym(skAlias, src, dest, n[0].info) + incl(alias.flags, sfExported) + if sfCompilerProc in dest.flags: markCompilerProc(alias) + addInterfaceDecl(c, alias) + else: + localError(n.info, "key:value pair expected") + proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int, validPragmas: TSpecialWords): bool = var it = n.sons[i] @@ -648,17 +669,13 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int, processDynLib(c, it, sym) of wCompilerproc: noVal(it) # compilerproc may not get a string! - if sfFromGeneric notin sym.flags: - makeExternExport(sym, "$1", it.info) - incl(sym.flags, sfCompilerProc) - incl(sym.flags, sfUsed) # suppress all those stupid warnings - registerCompilerProc(sym) - of wProcVar: + if sfFromGeneric notin sym.flags: markCompilerProc(sym) + of wProcVar: noVal(it) incl(sym.flags, sfProcvar) - of wDeprecated: - noVal(it) - if sym != nil: incl(sym.flags, sfDeprecated) + of wDeprecated: + if it.kind == nkExprColonExpr: deprecatedStmt(c, it) + elif sym != nil: incl(sym.flags, sfDeprecated) else: incl(c.module.flags, sfDeprecated) of wVarargs: noVal(it) diff --git a/compiler/pretty.nim b/compiler/pretty.nim index 17311f9e62..8d20d205b9 100644 --- a/compiler/pretty.nim +++ b/compiler/pretty.nim @@ -1,6 +1,6 @@ # # -# The Nimrod Compiler +# The Nim Compiler # (c) Copyright 2014 Andreas Rumpf # # See the file "copying.txt", included in this @@ -8,41 +8,19 @@ # ## This module implements the code "prettifier". This is part of the toolchain -## to convert Nimrod code into a consistent style. +## to convert Nim code into a consistent style. import strutils, os, options, ast, astalgo, msgs, ropes, idents, passes, - intsets, strtabs, semdata - -const - removeTP = false # when true, "nimrod pretty" converts TTyp to Typ. + intsets, strtabs, semdata, prettybase type TGen = object of TPassContext module*: PSym PGen = ref TGen - - TSourceFile = object - lines: seq[string] - dirty: bool - fullpath: string var - gSourceFiles: seq[TSourceFile] = @[] gCheckExtern: bool - rules: PStringTable - -proc loadFile(info: TLineInfo) = - let i = info.fileIndex - if i >= gSourceFiles.len: - gSourceFiles.setLen(i+1) - if gSourceFiles[i].lines.isNil: - gSourceFiles[i].lines = @[] - let path = info.toFullPath - gSourceFiles[i].fullpath = path - # we want to die here for EIO: - for line in lines(path): - gSourceFiles[i].lines.add(line) proc overwriteFiles*() = let overWrite = options.getConfigVar("pretty.overwrite").normalize == "on" @@ -78,9 +56,6 @@ proc beautifyName(s: string, k: TSymKind): string = case k of skType, skGenericParam: # Types should start with a capital unless builtins like 'int' etc.: - when removeTP: - if s[0] == 'T' and s[1] in {'A'..'Z'}: - i = 1 if s =~ ["int", "uint", "cint", "cuint", "clong", "cstring", "string", "char", "byte", "bool", "openArray", "seq", "array", "void", "pointer", "float", "csize", "cdouble", "cchar", "cschar", @@ -120,26 +95,10 @@ proc checkStyle*(info: TLineInfo, s: string, k: TSymKind) = if s != beau: message(info, errGenerated, "name should be: " & beau) -const - Letters = {'a'..'z', 'A'..'Z', '0'..'9', '\x80'..'\xFF', '_'} - -proc identLen(line: string, start: int): int = - while start+result < line.len and line[start+result] in Letters: - inc result - -proc differ(line: string, a, b: int, x: string): bool = - let y = line[a..b] - result = cmpIgnoreStyle(y, x) == 0 and y != x - when false: - var j = 0 - for i in a..b: - if line[i] != x[j]: return true - inc j - return false - proc checkDef*(n: PNode; s: PSym) = # operators stay as they are: - if s.kind in {skResult, skTemp} or s.name.s[0] notin Letters: return + if s.kind in {skResult, skTemp} or s.name.s[0] notin prettybase.Letters: + return if s.kind in {skType, skGenericParam} and sfAnon in s.flags: return if {sfImportc, sfExportc} * s.flags == {} or gCheckExtern: @@ -155,7 +114,8 @@ proc checkUse*(info: TLineInfo; s: PSym) = # for consistency # operators stay as they are: - if s.kind in {skResult, skTemp} or s.name.s[0] notin Letters: return + if s.kind in {skResult, skTemp} or s.name.s[0] notin prettybase.Letters: + return if s.kind in {skType, skGenericParam} and sfAnon in s.flags: return let newName = s.name.s @@ -165,61 +125,17 @@ proc checkUse*(info: TLineInfo; s: PSym) = var first = min(info.col.int, line.len) if first < 0: return #inc first, skipIgnoreCase(line, "proc ", first) - while first > 0 and line[first-1] in Letters: dec first + while first > 0 and line[first-1] in prettybase.Letters: dec first if first < 0: return if line[first] == '`': inc first let last = first+identLen(line, first)-1 if differ(line, first, last, newName): # last-first+1 != newName.len or - var x = line.substr(0, first-1) & newName & line.substr(last+1) - when removeTP: - # the WinAPI module is full of 'TX = X' which after the substitution - # becomes 'X = X'. We remove those lines: - if x.match(peg"\s* {\ident} \s* '=' \s* y$1 ('#' .*)?"): - x = "" - + var x = line.substr(0, first-1) & newName & line.substr(last+1) system.shallowCopy(gSourceFiles[info.fileIndex].lines[info.line-1], x) gSourceFiles[info.fileIndex].dirty = true -when false: - var cannotRename = initIntSet() - - proc beautifyName(s: string, k: TSymKind): string = - let allUpper = allCharsInSet(s, {'A'..'Z', '0'..'9', '_'}) - result = newStringOfCap(s.len) - var i = 0 - case k - of skType, skGenericParam: - # skip leading 'T' - when removeTP: - if s[0] == 'T' and s[1] in {'A'..'Z'}: - i = 1 - if s =~ ["int", "uint", "cint", "cuint", "clong", "cstring", "string", - "char", "byte", "bool", "openArray", "seq", "array", "void", - "pointer", "float", "csize", "cdouble", "cchar", "cschar", - "cshort", "cu"]: - result.add s[i] - else: - result.add toUpper(s[i]) - of skConst, skEnumField: - # for 'const' we keep how it's spelt; either upper case or lower case: - result.add s[0] - else: - # as a special rule, don't transform 'L' to 'l' - if s.len == 1 and s[0] == 'L': result.add 'L' - else: result.add toLower(s[0]) - inc i - while i < s.len: - if s[i] == '_': - inc i - result.add toUpper(s[i]) - elif allUpper: - result.add toLower(s[i]) - else: - result.add s[i] - inc i - proc check(c: PGen, n: PNode) = case n.kind of nkSym: checkUse(n.info, n.sym) @@ -264,18 +180,6 @@ proc myOpen(module: PSym): PPassContext = g.module = module gCheckExtern = options.getConfigVar("pretty.checkextern").normalize == "on" result = g - if rules.isNil: - rules = newStringTable(modeStyleInsensitive) - when removeTP: - # XXX activate when the T/P stuff is deprecated - let path = joinPath([getPrefixDir(), "config", "rename.rules.cfg"]) - for line in lines(path): - if line.len > 0: - let colon = line.find(':') - if colon > 0: - rules[line.substr(0, colon-1)] = line.substr(colon+1) - else: - rules[line] = line const prettyPass* = makePass(open = myOpen, process = processSym) diff --git a/compiler/prettybase.nim b/compiler/prettybase.nim new file mode 100644 index 0000000000..581114441a --- /dev/null +++ b/compiler/prettybase.nim @@ -0,0 +1,59 @@ +# +# +# The Nim Compiler +# (c) Copyright 2014 Andreas Rumpf +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + +import ast, msgs, strutils + +type + TSourceFile* = object + lines*: seq[string] + dirty*: bool + fullpath*: string + +var + gSourceFiles*: seq[TSourceFile] = @[] + +proc loadFile*(info: TLineInfo) = + let i = info.fileIndex + if i >= gSourceFiles.len: + gSourceFiles.setLen(i+1) + if gSourceFiles[i].lines.isNil: + gSourceFiles[i].lines = @[] + let path = info.toFullPath + gSourceFiles[i].fullpath = path + # we want to die here for EIO: + for line in lines(path): + gSourceFiles[i].lines.add(line) + +const + Letters* = {'a'..'z', 'A'..'Z', '0'..'9', '\x80'..'\xFF', '_'} + +proc identLen*(line: string, start: int): int = + while start+result < line.len and line[start+result] in Letters: + inc result + +proc differ*(line: string, a, b: int, x: string): bool = + let y = line[a..b] + result = cmpIgnoreStyle(y, x) == 0 and y != x + +proc replaceDeprecated*(info: TlineInfo; oldSym, newSym: PSym) = + loadFile(info) + + let line = gSourceFiles[info.fileIndex].lines[info.line-1] + var first = min(info.col.int, line.len) + if first < 0: return + #inc first, skipIgnoreCase(line, "proc ", first) + while first > 0 and line[first-1] in Letters: dec first + if first < 0: return + if line[first] == '`': inc first + + let last = first+identLen(line, first)-1 + if cmpIgnoreStyle(line[first..last], oldSym.name.s) == 0: + var x = line.substr(0, first-1) & newSym.name.s & line.substr(last+1) + system.shallowCopy(gSourceFiles[info.fileIndex].lines[info.line-1], x) + gSourceFiles[info.fileIndex].dirty = true diff --git a/compiler/semgnrc.nim b/compiler/semgnrc.nim index 934434951c..224168528d 100644 --- a/compiler/semgnrc.nim +++ b/compiler/semgnrc.nim @@ -70,7 +70,7 @@ proc lookup(c: PContext, n: PNode, flags: TSemGenericFlags, ctx: var TIntSet): PNode = result = n let ident = considerQuotedIdent(n) - var s = searchInScopes(c, ident) + var s = searchInScopes(c, ident).skipAlias(n) if s == nil: if ident.id notin ctx and withinMixin notin flags: localError(n.info, errUndeclaredIdentifier, ident.s) @@ -100,7 +100,7 @@ proc fuzzyLookup(c: PContext, n: PNode, flags: TSemGenericFlags, result = n let n = n[1] let ident = considerQuotedIdent(n) - var s = searchInScopes(c, ident) + var s = searchInScopes(c, ident).skipAlias(n) if s != nil and s.kind in routineKinds: if withinBind in flags: result = newDot(result, symChoice(c, n, s, scClosed)) diff --git a/compiler/sempass2.nim b/compiler/sempass2.nim index acc2425f14..332b741555 100644 --- a/compiler/sempass2.nim +++ b/compiler/sempass2.nim @@ -130,20 +130,27 @@ proc addToIntersection(inter: var TIntersection, s: int) = proc throws(tracked, n: PNode) = if n.typ == nil or n.typ.kind != tyError: tracked.add n - + +proc getEbase(): PType = + result = if getCompilerProc("Exception") != nil: sysTypeFromName"Exception" + else: sysTypeFromName"E_Base" + proc excType(n: PNode): PType = # reraise is like raising E_Base: - let t = if n.kind == nkEmpty: sysTypeFromName"E_Base" else: n.typ + let t = if n.kind == nkEmpty: getEbase() else: n.typ result = skipTypes(t, skipPtrs) proc createRaise(n: PNode): PNode = result = newNode(nkType) - result.typ = sysTypeFromName"E_Base" + result.typ = getEbase() if not n.isNil: result.info = n.info proc createTag(n: PNode): PNode = result = newNode(nkType) - result.typ = sysTypeFromName"TEffect" + if getCompilerProc("RootEffect") != nil: + result.typ = sysTypeFromName"RootEffect" + else: + result.typ = sysTypeFromName"TEffect" if not n.isNil: result.info = n.info proc createAnyGlobal(n: PNode): PNode = diff --git a/compiler/transf.nim b/compiler/transf.nim index b9b06675ed..00fe03ab61 100644 --- a/compiler/transf.nim +++ b/compiler/transf.nim @@ -782,8 +782,8 @@ proc transformBody*(module: PSym, n: PNode, prc: PSym): PNode = # result = lambdalifting.liftIterator(prc, result) incl(result.flags, nfTransf) when useEffectSystem: trackProc(prc, result) - if prc.name.s == "testbody": - echo renderTree(result) + #if prc.name.s == "testbody": + # echo renderTree(result) proc transformStmt*(module: PSym, n: PNode): PNode = if nfTransf in n.flags: diff --git a/doc/exception_hierarchy_fragment.txt b/doc/exception_hierarchy_fragment.txt index 6ca68921f1..f4a419fc49 100644 --- a/doc/exception_hierarchy_fragment.txt +++ b/doc/exception_hierarchy_fragment.txt @@ -1,31 +1,28 @@ -* `E_Base `_ - * `EAccessViolation `_ - * `EArithmetic `_ - * `EDivByZero `_ - * `EOverflow `_ - * `EAssertionFailed `_ - * `EAsynch `_ - * `EControlC `_ - * `EDeadThread `_ - * `EFloatingPoint `_ - * `EFloatDivByZero `_ - * `EFloatInexact `_ - * `EFloatInvalidOp `_ - * `EFloatOverflow `_ - * `EFloatUnderflow `_ - * `EInvalidField `_ - * `EInvalidIndex `_ - * `EInvalidObjectAssignment `_ - * `EInvalidObjectConversion `_ - * `EInvalidValue `_ - * `EInvalidKey `_ - * `ENoExceptionToReraise `_ - * `EOutOfRange `_ - * `ESynch `_ - * `EOutOfMemory `_ - * `EResourceExhausted `_ - * `EStackOverflow `_ - * `ESystem `_ - * `EIO `_ - * `EOS `_ - * `EInvalidLibrary `_ +* `Exception `_ + * `AccessViolationError `_ + * `ArithmeticError `_ + * `DivByZeroError `_ + * `OverflowError `_ + * `AssertionError `_ + * `DeadThreadError `_ + * `FloatingPointError `_ + * `FloatDivByZeroError `_ + * `FloatInexactError `_ + * `FloatInvalidOpError `_ + * `FloatOverflowError `_ + * `FloatUnderflowError `_ + * `FieldError `_ + * `IndexError `_ + * `ObjectAssignmentError `_ + * `ObjectConversionError `_ + * `ValueError `_ + * `KeyError `_ + * `ReraiseError `_ + * `RangeError `_ + * `OutOfMemoryError `_ + * `ResourceExhaustedError `_ + * `StackOverflowError `_ + * `SystemError `_ + * `IOError `_ + * `OSError `_ + * `LibraryError `_ diff --git a/doc/lib.txt b/doc/lib.txt index 26ea1b7350..a29e32429e 100644 --- a/doc/lib.txt +++ b/doc/lib.txt @@ -1,15 +1,15 @@ -======================= -Nimrod Standard Library -======================= +==================== +Nim Standard Library +==================== :Author: Andreas Rumpf -:Version: |nimrodversion| +:Version: |nimversion| .. contents:: "The good thing about reinventing the wheel is that you can get a round one." -Though the Nimrod Standard Library is still evolving, it is already quite +Though the Nim Standard Library is still evolving, it is already quite usable. It is divided into *pure libraries*, *impure libraries* and *wrappers*. Pure libraries do not depend on any external ``*.dll`` or ``lib*.so`` binary @@ -19,7 +19,7 @@ low-level interface to a C library. Read this `document `_ for a quick overview of the API design. The `bottom <#babel>`_ of this page includes a list of 3rd party packages -created by the Nimrod community. These packages are a useful addition to the +created by the Nim community. These packages are a useful addition to the modules in the standard library. @@ -41,27 +41,27 @@ Core of ``system``, but an extra import. * `threads `_ - Nimrod thread support. **Note**: This is part of the system module. Do not + Nim thread support. **Note**: This is part of the system module. Do not import it explicitly. * `channels `_ - Nimrod message passing support for threads. **Note**: This is part of the + Nim message passing support for threads. **Note**: This is part of the system module. Do not import it explicitly. * `locks `_ - Locks and condition variables for Nimrod. + Locks and condition variables for Nim. * `macros `_ - Contains the AST API and documentation of Nimrod for writing macros. + Contains the AST API and documentation of Nim for writing macros. * `typeinfo `_ - Provides (unsafe) access to Nimrod's run time type information. + Provides (unsafe) access to Nim's run time type information. * `typetraits `_ This module defines compile-time reflection procs for working with types. * `actors `_ - Actor support for Nimrod; implemented as a layer on top of the threads and + Actor support for Nim; implemented as a layer on top of the threads and channels modules. @@ -71,11 +71,11 @@ Collections and algorithms * `algorithm `_ Implements some common generic algorithms like sort or binary search. * `tables `_ - Nimrod hash table support. Contains tables, ordered tables and count tables. + Nim hash table support. Contains tables, ordered tables and count tables. * `sets `_ - Nimrod hash and bit set support. + Nim hash and bit set support. * `lists `_ - Nimrod linked list support. Contains singly and doubly linked lists and + Nim linked list support. Contains singly and doubly linked lists and circular lists ("rings"). * `queues `_ Implementation of a queue. The underlying implementation uses a ``seq``. @@ -153,11 +153,11 @@ Generic Operating System Services * `streams `_ This module provides a stream interface and two implementations thereof: the `PFileStream` and the `PStringStream` which implement the stream - interface for Nimrod file objects (`TFile`) and strings. Other modules + interface for Nim file objects (`TFile`) and strings. Other modules may provide other implementations for this standard stream interface. * `marshal `_ - Contains procs for serialization and deseralization of arbitrary Nimrod + Contains procs for serialization and deseralization of arbitrary Nim data structures. * `terminal `_ @@ -273,7 +273,7 @@ Parsers parser. The configuration file's syntax is similar to the Windows ``.ini`` format, but much more powerful, as it is not a line based parser. String literals, raw string literals and triple quote string literals are supported - as in the Nimrod programming language. + as in the Nim programming language. * `parsexml `_ The ``parsexml`` module implements a simple high performance XML/HTML parser. @@ -340,7 +340,7 @@ Cryptography and Hashing * `hashes `_ This module implements efficient computations of hash values for diverse - Nimrod types. + Nim types. * `md5 `_ This module implements the MD5 checksum algorithm. @@ -353,7 +353,7 @@ Multimedia support ------------------ * `colors `_ - This module implements color handling for Nimrod. It is used by + This module implements color handling for Nim. It is used by the ``graphics`` module. @@ -426,12 +426,12 @@ Other ----- * `graphics `_ - This module implements graphical output for Nimrod; the current + This module implements graphical output for Nim; the current implementation uses SDL but the interface is meant to support multiple backends some day. * `dialogs `_ - This module implements portable dialogs for Nimrod; the implementation + This module implements portable dialogs for Nim; the implementation builds on the GTK interface. On Windows, native dialogs are shown if appropriate. @@ -444,7 +444,7 @@ Other * `ssl `_ This module provides an easy to use sockets-style - Nimrod interface to the OpenSSL library. + Nim interface to the OpenSSL library. * `rdstdin `_ This module contains code for reading from `stdin`:idx:. On UNIX the GNU @@ -532,7 +532,7 @@ Database support * `odbcsql `_ interface to the ODBC driver. * `sphinx `_ - Nimrod wrapper for ``sphinx``. + Nim wrapper for ``sphinx``. XML Processing @@ -578,15 +578,15 @@ Scientific computing Babel ==================== -Babel is a package manager for the Nimrod programming language. +Babel is a package manager for the Nim programming language. For instructions on how to install Babel packages see -`its README `_. +`its README `_. Official packages ----------------- These packages are officially supported and will therefore be continually -maintained to ensure that they work with the latest versions of the Nimrod +maintained to ensure that they work with the latest versions of the Nim compiler. .. raw:: html @@ -597,9 +597,9 @@ compiler. Unofficial packages ------------------- -These packages have been developed by independent Nimrod developers and as +These packages have been developed by independent Nim developers and as such may not always be up to date with the latest developments in the -Nimrod programming language. +Nim programming language. .. raw:: html @@ -607,4 +607,4 @@ Nimrod programming language. babelpkglist.js or have javascript disabled in your browser. - + diff --git a/doc/manual.txt b/doc/manual.txt index 89a417fb22..d18ede409f 100644 --- a/doc/manual.txt +++ b/doc/manual.txt @@ -1,9 +1,9 @@ -============= -Nimrod Manual -============= +========== +Nim Manual +========== :Authors: Andreas Rumpf, Zahary Karadjov -:Version: |nimrodversion| +:Version: |nimversion| .. contents:: @@ -17,11 +17,11 @@ Nimrod Manual About this document =================== -**Note**: This document is a draft! Several of Nimrod's features need more +**Note**: This document is a draft! Several of Nim's features need more precise wording. This manual will evolve into a proper specification some day. -This document describes the lexis, the syntax, and the semantics of Nimrod. +This document describes the lexis, the syntax, and the semantics of Nim. The language constructs are explained using an extended BNF, in which ``(a)*`` means 0 or more ``a``'s, ``a+`` means 1 or more ``a``'s, and @@ -48,14 +48,14 @@ and ``a ^* b`` is short for ``(a (b a)*)?``. Example:: arrayConstructor = '[' expr ^* ',' ']' -Other parts of Nimrod - like scoping rules or runtime semantics are only +Other parts of Nim - like scoping rules or runtime semantics are only described in an informal manner for now. Definitions =========== -A Nimrod program specifies a computation that acts on a memory consisting of +A Nim program specifies a computation that acts on a memory consisting of components called `locations`:idx:. A variable is basically a name for a location. Each variable and location is of a certain `type`:idx:. The variable's type is called `static type`:idx:, the location's type is called @@ -107,7 +107,7 @@ Lexical Analysis Encoding -------- -All Nimrod source files are in the UTF-8 encoding (or its ASCII subset). Other +All Nim source files are in the UTF-8 encoding (or its ASCII subset). Other encodings are not supported. Any of the standard platform line termination sequences can be used - the Unix form using ASCII LF (linefeed), the Windows form using the ASCII sequence CR LF (return followed by linefeed), or the old @@ -118,13 +118,13 @@ used equally, regardless of platform. Indentation ----------- -Nimrod's standard grammar describes an `indentation sensitive`:idx: language. +Nim's standard grammar describes an `indentation sensitive`:idx: language. This means that all the control structures are recognized by indentation. Indentation consists only of spaces; tabulators are not allowed. The indentation handling is implemented as follows: The lexer annotates the following token with the preceding number of spaces; indentation is not -a separate token. This trick allows parsing of Nimrod with only 1 token of +a separate token. This trick allows parsing of Nim with only 1 token of lookahead. The parser uses a stack of indentation levels: the stack consists of integers @@ -188,7 +188,7 @@ which code snippet the comment refers to. Identifiers & Keywords ---------------------- -Identifiers in Nimrod can be any string of letters, digits +Identifiers in Nim can be any string of letters, digits and underscores, beginning with a letter. Two immediate following underscores ``__`` are not allowed:: @@ -209,12 +209,12 @@ The following keywords are reserved and cannot be used as identifiers: Some keywords are unused; they are reserved for future developments of the language. -Nimrod is a `style-insensitive`:idx: language. This means that it is not +Nim is a `style-insensitive`:idx: language. This means that it is not case-sensitive and even underscores are ignored: **type** is a reserved word, and so is **TYPE** or **T_Y_P_E**. The idea behind this is that this allows programmers to use their own preferred spelling style and libraries written by different programmers cannot use incompatible -conventions. A Nimrod-aware editor or IDE can show the identifiers as +conventions. A Nim-aware editor or IDE can show the identifiers as preferred. Another advantage is that it frees the programmer from remembering the exact spelling of an identifier. @@ -250,7 +250,7 @@ contain the following `escape sequences`:idx:\ : ================== =================================================== -Strings in Nimrod may contain any 8-bit value, even embedded zeros. However +Strings in Nim may contain any 8-bit value, even embedded zeros. However some operations may interpret the first binary zero as a terminator. @@ -317,7 +317,7 @@ identifier and the opening quotation mark) is a generalized raw string literal. It is a shortcut for the construct ``identifier(r"string literal")``, so it denotes a procedure call with a raw string literal as its only argument. Generalized raw string literals -are especially convenient for embedding mini languages directly into Nimrod +are especially convenient for embedding mini languages directly into Nim (for example regular expressions). The construct ``identifier"""string literal"""`` exists too. It is a shortcut @@ -357,7 +357,7 @@ literals: A character is not an Unicode character but a single byte. The reason for this is efficiency: for the overwhelming majority of use-cases, the resulting programs will still handle UTF-8 properly as UTF-8 was specially designed for -this. Another reason is that Nimrod can thus support ``array[char, int]`` or +this. Another reason is that Nim can thus support ``array[char, int]`` or ``set[char]`` efficiently as many algorithms rely on this feature. The `TRune` type is used for Unicode characters, it can represent any Unicode character. ``TRune`` is declared in the `unicode module `_. @@ -441,7 +441,7 @@ is approximately 1.72826e35 according to the IEEE floating point standard. Operators --------- -In Nimrod one can define his own operators. An operator is any +In Nim one can define his own operators. An operator is any combination of the following characters:: = + - * / < > @@ -474,10 +474,10 @@ and not the two tokens `{.`:tok:, `.}`:tok:. Syntax ====== -This section lists Nimrod's standard syntax. How the parser handles +This section lists Nim's standard syntax. How the parser handles the indentation is already described in the `Lexical Analysis`_ section. -Nimrod allows user-definable operators. +Nim allows user-definable operators. Binary operators have 10 different levels of precedence. Relevant character @@ -588,7 +588,7 @@ The grammar's start symbol is ``module``. Types ===== -All expressions have a type which is known at compile time. Nimrod +All expressions have a type which is known at compile time. Nim is statically typed. One can declare new types, which is in essence defining an identifier that can be used to denote this custom type. @@ -686,7 +686,7 @@ kinds of integer types are used: the smaller type is converted to the larger. A `narrowing type conversion`:idx: converts a larger to a smaller type (for example ``int32 -> int16``. A `widening type conversion`:idx: converts a -smaller type to a larger type (for example ``int16 -> int32``). In Nimrod only +smaller type to a larger type (for example ``int16 -> int32``). In Nim only widening type conversions are *implicit*: .. code-block:: nimrod @@ -723,7 +723,7 @@ determined). Assignments from the base type to one of its subrange types A subrange type has the same size as its base type (``int`` in the example). -Nimrod requires `interval arithmetic`:idx: for subrange types over a set +Nim requires `interval arithmetic`:idx: for subrange types over a set of built-in operators that involve constants: ``x %% 3`` is of type ``range[0..2]``. The following built-in operators for integers are affected by this rule: ``-``, ``+``, ``*``, ``min``, ``max``, ``succ``, @@ -781,12 +781,12 @@ The IEEE standard defines five types of floating-point exceptions: precision, for example, 2.0 / 3.0, log(1.1) and 0.1 in input. The IEEE exceptions are either ignored at runtime or mapped to the -Nimrod exceptions: `EFloatInvalidOp`:idx:, `EFloatDivByZero`:idx:, +Nim exceptions: `EFloatInvalidOp`:idx:, `EFloatDivByZero`:idx:, `EFloatOverflow`:idx:, `EFloatUnderflow`:idx:, and `EFloatInexact`:idx:. These exceptions inherit from the `EFloatingPoint`:idx: base class. -Nimrod provides the pragmas `NaNChecks`:idx: and `InfChecks`:idx: to control -whether the IEEE exceptions are ignored or trap a Nimrod exception: +Nim provides the pragmas `NaNChecks`:idx: and `InfChecks`:idx: to control +whether the IEEE exceptions are ignored or trap a Nim exception: .. code-block:: nimrod {.NanChecks: on, InfChecks: on.} @@ -807,7 +807,7 @@ the ``+``, ``-``, ``*``, ``/`` operators for floating point types. Boolean type ------------ -The boolean type is named `bool`:idx: in Nimrod and can be one of the two +The boolean type is named `bool`:idx: in Nim and can be one of the two pre-defined values ``true`` and ``false``. Conditions in while, if, elif, when statements need to be of type bool. @@ -831,12 +831,12 @@ The size of the bool type is one byte. Character type -------------- -The character type is named ``char`` in Nimrod. Its size is one byte. +The character type is named ``char`` in Nim. Its size is one byte. Thus it cannot represent an UTF-8 character, but a part of it. The reason for this is efficiency: for the overwhelming majority of use-cases, the resulting programs will still handle UTF-8 properly as UTF-8 was specially designed for this. -Another reason is that Nimrod can support ``array[char, int]`` or +Another reason is that Nim can support ``array[char, int]`` or ``set[char]`` efficiently as many algorithms rely on this feature. The `TRune` type is used for Unicode characters, it can represent any Unicode character. ``TRune`` is declared in the `unicode module `_. @@ -916,8 +916,8 @@ via ``TMyEnum.value``: String type ----------- -All string literals are of the type ``string``. A string in Nimrod is very -similar to a sequence of characters. However, strings in Nimrod are both +All string literals are of the type ``string``. A string in Nim is very +similar to a sequence of characters. However, strings in Nim are both zero-terminated and have a length field. One can retrieve the length with the builtin ``len`` procedure; the length never counts the terminating zero. The assignment operator for strings always copies the string. @@ -949,8 +949,8 @@ interfacing with C. The index operation ``s[i]`` means the i-th *char* of ``s``; however no bounds checking for ``cstring`` is performed making the index operation unsafe. -A Nimrod ``string`` is implicitly convertible -to ``cstring`` for convenience. If a Nimrod string is passed to a C-style +A Nim ``string`` is implicitly convertible +to ``cstring`` for convenience. If a Nim string is passed to a C-style variadic proc, it is implicitly converted to ``cstring`` too: .. code-block:: nimrod @@ -1169,7 +1169,7 @@ An example: .. code-block:: nimrod - # This is an example how an abstract syntax tree could be modelled in Nimrod + # This is an example how an abstract syntax tree could be modelled in Nim type TNodeKind = enum # the different node types nkInt, # a leaf with an integer value @@ -1230,7 +1230,7 @@ References (similar to pointers in other programming languages) are a way to introduce many-to-one relationships. This means different references can point to and modify the same location in memory (also called `aliasing`:idx:). -Nimrod distinguishes between `traced`:idx: and `untraced`:idx: references. +Nim distinguishes between `traced`:idx: and `untraced`:idx: references. Untraced references are also called *pointers*. Traced references point to objects of a garbage collected heap, untraced references point to manually allocated objects or to objects somewhere else in memory. Thus @@ -1409,7 +1409,7 @@ Future directions: Procedural type --------------- A procedural type is internally a pointer to a procedure. ``nil`` is -an allowed value for variables of a procedural type. Nimrod uses procedural +an allowed value for variables of a procedural type. Nim uses procedural types to achieve `functional`:idx: programming techniques. Examples: @@ -1446,10 +1446,10 @@ compatible if they have the same calling convention. As a special extension, a procedure of the calling convention ``nimcall`` can be passed to a parameter that expects a proc of the calling convention ``closure``. -Nimrod supports these `calling conventions`:idx:\: +Nim supports these `calling conventions`:idx:\: `nimcall`:idx: - is the default convention used for a Nimrod **proc**. It is the + is the default convention used for a Nim **proc**. It is the same as ``fastcall``, but only for C compilers that support ``fastcall``. `closure`:idx: @@ -1476,7 +1476,7 @@ Nimrod supports these `calling conventions`:idx:\: `inline`:idx: The inline convention means the the caller should not call the procedure, - but inline its code directly. Note that Nimrod does not inline, but leaves + but inline its code directly. Note that Nim does not inline, but leaves this to the C compiler; it generates ``__inline`` procedures. This is only a hint for the compiler: it may completely ignore it and it may inline procedures that are not marked as ``inline``. @@ -1492,7 +1492,7 @@ Nimrod supports these `calling conventions`:idx:\: `noconv`:idx: The generated C code will not have any explicit calling convention and thus use the C compiler's default calling convention. This is needed because - Nimrod's default calling convention for procedures is ``fastcall`` to + Nim's default calling convention for procedures is ``fastcall`` to improve speed. Most calling conventions exist only for the Windows 32-bit platform. @@ -1636,7 +1636,7 @@ Currently only the dot accessor can be borrowed in this way. Avoiding SQL injection attacks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -An SQL statement that is passed from Nimrod to an SQL database might be +An SQL statement that is passed from Nim to an SQL database might be modelled as a string. However, using string templates and filling in the values is vulnerable to the famous `SQL injection attack`:idx:\: @@ -1745,7 +1745,7 @@ describe the type checking done by the compiler. Type equality ------------- -Nimrod uses structural type equivalence for most types. Only for objects, +Nim uses structural type equivalence for most types. Only for objects, enumerations and distinct types name equivalence is used. The following algorithm (in pseudo-code) determines type equality: @@ -1932,7 +1932,7 @@ To be written. Statements and expressions ========================== -Nimrod uses the common statement/expression paradigm: Statements do not +Nim uses the common statement/expression paradigm: Statements do not produce a value in contrast to expressions. However, some expressions are statements. @@ -2079,7 +2079,7 @@ Const section cannot change. The compiler must be able to evaluate the expression in a constant declaration at compile time. -Nimrod contains a sophisticated compile-time evaluator, so procedures which +Nim contains a sophisticated compile-time evaluator, so procedures which have no side-effect can be used in constant expressions too: .. code-block:: nimrod @@ -2119,7 +2119,7 @@ time. The current implementation poses some restrictions for compile time evaluation: Code which contains ``cast`` or makes use of the foreign function -interface cannot be evaluated at compile time. Later versions of Nimrod will +interface cannot be evaluated at compile time. Later versions of Nim will support the FFI at compile time. @@ -2374,9 +2374,9 @@ Is equivalent to: Assembler statement ------------------- -The direct embedding of assembler code into Nimrod code is supported +The direct embedding of assembler code into Nim code is supported by the unsafe ``asm`` statement. Identifiers in the assembler code that refer to -Nimrod identifiers shall be enclosed in a special character which can be +Nim identifiers shall be enclosed in a special character which can be specified in the statement's pragmas. The default special character is ``'`'``: .. code-block:: nimrod @@ -2425,7 +2425,7 @@ Using statement The using statement provides syntactic convenience for procs that heavily use a single contextual parameter. When applied to a variable or a -constant, it will instruct Nimrod to automatically consider the used symbol as +constant, it will instruct Nim to automatically consider the used symbol as a hidden leading parameter for any procedure calls, following the using statement in the current scope. Thus, it behaves much like the hidden `this` parameter available in some object-oriented programming languages. @@ -2502,7 +2502,7 @@ The `case expression` is again very similar to the case statement: "ice cream" As seen in the above example, the case expression can also introduce side -effects. When multiple statements are given for a branch, Nimrod will use +effects. When multiple statements are given for a branch, Nim will use the last expression as the result value, much like in an `expr` template. Table constructor @@ -2582,7 +2582,7 @@ Procedures ========== What most programming languages call `methods`:idx: or `functions`:idx: are -called `procedures`:idx: in Nimrod (which is the correct terminology). A +called `procedures`:idx: in Nim (which is the correct terminology). A procedure declaration defines an identifier and associates it with a block of code. A procedure may call itself recursively. A parameter may be given a default @@ -2672,7 +2672,7 @@ postfix notation. Properties ---------- -Nimrod has no need for *get-properties*: Ordinary get-procedures that are called +Nim has no need for *get-properties*: Ordinary get-procedures that are called with the *method call syntax* achieve the same. But setting a value is different; for this a special setter syntax is needed: @@ -2961,7 +2961,7 @@ Invocation of a multi-method cannot be ambiguous: collide 2 is preferred over collide 1 because the resolution works from left to right. In the example ``TUnit, TThing`` is preferred over ``TThing, TUnit``. -**Performance note**: Nimrod does not produce a virtual method table, but +**Performance note**: Nim does not produce a virtual method table, but generates dispatch trees. This avoids the expensive indirect branch for method calls and enables inlining. However, other optimizations like compile time evaluation or dead code elimination do not work with methods. @@ -3033,7 +3033,7 @@ into account. First class iterators --------------------- -There are 2 kinds of iterators in Nimrod: *inline* and *closure* iterators. +There are 2 kinds of iterators in Nim: *inline* and *closure* iterators. An `inline iterator`:idx: is an iterator that's always inlined by the compiler leading to zero overhead for the abstraction, but may result in a heavy increase in code size. Inline iterators are second class citizens; @@ -3290,7 +3290,7 @@ Effect system Exception tracking ------------------ -Nimrod supports exception tracking. The `raises`:idx: pragma can be used +Nim supports exception tracking. The `raises`:idx: pragma can be used to explicitly define which exceptions a proc/iterator/method/converter is allowed to raise. The compiler verifies this: @@ -3367,7 +3367,7 @@ conservative in its effect analysis. Tag tracking ------------ -The exception tracking is part of Nimrod's `effect system`:idx:. Raising an +The exception tracking is part of Nim's `effect system`:idx:. Raising an exception is an *effect*. Other effects can also be defined. A user defined effect is a means to *tag* a routine and to perform checks against this tag: @@ -3467,7 +3467,7 @@ Example: for str in inorder(root): writeln(stdout, str) -Generics are Nimrod's means to parametrize procs, iterators or types with +Generics are Nim's means to parametrize procs, iterators or types with `type parameters`:idx:. Depending on context, the brackets are used either to introduce type parameters or to instantiate a generic proc, iterator or type. @@ -3515,7 +3515,7 @@ Type Classes A type class is a special pseudo-type that can be used to match against types in the context of overload resolution or the ``is`` operator. -Nimrod supports the following built-in type classes: +Nim supports the following built-in type classes: ================== =================================================== type class matches @@ -3553,7 +3553,7 @@ Procedures utilizing type classes in such manner are considered to be `implicitly generic`:idx:. They will be instantiated once for each unique combination of param types used within the program. -Nimrod also allows for type classes and regular types to be specified +Nim also allows for type classes and regular types to be specified as `type constraints`:idx: of the generic type parameter: .. code-block:: nimrod @@ -3579,7 +3579,7 @@ module to illustrate this: Alternatively, the ``distinct`` type modifier can be applied to the type class to allow each param matching the type class to bind to a different type. -If a proc param doesn't have a type specified, Nimrod will use the +If a proc param doesn't have a type specified, Nim will use the ``distinct auto`` type class (also known as ``any``): .. code-block:: nimrod @@ -3675,7 +3675,7 @@ Return Type Inference --------------------- If a type class is used as the return type of a proc and it won't be bound to -a concrete type by some of the proc params, Nimrod will infer the return type +a concrete type by some of the proc params, Nim will infer the return type from the proc body. This is usually used with the ``auto`` type class: .. code-block:: nimrod @@ -3684,7 +3684,7 @@ from the proc body. This is usually used with the ``auto`` type class: The return type will be treated as additional generic param and can be explicitly specified at call sites as any other generic param. -Future versions of Nimrod may also support overloading based on the return type +Future versions of Nim may also support overloading based on the return type of the overloads. In such settings, the expected result type at call sites may also influence the inferred return type. @@ -3760,7 +3760,7 @@ Templates ========= A template is a simple form of a macro: It is a simple substitution -mechanism that operates on Nimrod's abstract syntax trees. It is processed in +mechanism that operates on Nim's abstract syntax trees. It is processed in the semantic pass of the compiler. The syntax to *invoke* a template is the same as calling a procedure. @@ -3991,10 +3991,10 @@ to implement `domain specific languages`:idx:. Like templates, macros come in the 2 flavors *immediate* and *ordinary*. While macros enable advanced compile-time code transformations, they -cannot change Nimrod's syntax. However, this is no real restriction because -Nimrod's syntax is flexible enough anyway. +cannot change Nim's syntax. However, this is no real restriction because +Nim's syntax is flexible enough anyway. -To write macros, one needs to know how the Nimrod concrete syntax is converted +To write macros, one needs to know how the Nim concrete syntax is converted to an abstract syntax tree. There are two ways to invoke a macro: @@ -4009,12 +4009,12 @@ The following example implements a powerful ``debug`` command that accepts a variable number of arguments: .. code-block:: nimrod - # to work with Nimrod syntax trees, we need an API that is defined in the + # to work with Nim syntax trees, we need an API that is defined in the # ``macros`` module: import macros macro debug(n: varargs[expr]): stmt = - # `n` is a Nimrod AST that contains the whole macro invocation + # `n` is a Nim AST that contains the whole macro invocation # this macro returns a list of statements: result = newNimNode(nnkStmtList, n) # iterate over any argument that is passed to this macro: @@ -4313,14 +4313,14 @@ Special Operators dot operators ------------- -Nimrod offers a special family of dot operators that can be used to +Nim offers a special family of dot operators that can be used to intercept and rewrite proc call and field access attempts, referring to previously undeclared symbol names. They can be used to provide a fluent interface to objects lying outside the static confines of the type system such as values from dynamic scripting languages or dynamic file formats such as JSON or XML. -When Nimrod encounters an expression that cannot be resolved by the +When Nim encounters an expression that cannot be resolved by the standard overload resolution rules, the current scope will be searched for a dot operator that can be matched against a re-written form of the expression, where the unknown field or proc name is converted to @@ -4504,7 +4504,7 @@ is **wrong**: echo f() * 2 We cannot duplicate 'a' if it denotes an expression that has a side effect! -Fortunately Nimrod supports side effect analysis: +Fortunately Nim supports side effect analysis: .. code-block:: nimrod template optMul{`*`(a, 2)}(a: int{noSideEffect}): int = a+a @@ -4835,7 +4835,7 @@ optimization for types that have copying semantics: Modules ======= -Nimrod supports splitting a program into pieces by a module concept. +Nim supports splitting a program into pieces by a module concept. Each module needs to be in its own file and has its own `namespace`:idx:. Modules enable `information hiding`:idx: and `separate compilation`:idx:. A module may gain access to symbols of another module by the `import`:idx: @@ -5023,7 +5023,7 @@ iterator in which case the overloading resolution takes place: Compiler Messages ================= -The Nimrod compiler emits different kinds of messages: `hint`:idx:, +The Nim compiler emits different kinds of messages: `hint`:idx:, `warning`:idx:, and `error`:idx: messages. An *error* message is emitted if the compiler encounters any static error. @@ -5031,7 +5031,7 @@ the compiler encounters any static error. Pragmas ======= -Pragmas are Nimrod's method to give the compiler additional information / +Pragmas are Nim's method to give the compiler additional information / commands without introducing a massive number of new keywords. Pragmas are processed on the fly during semantic checking. Pragmas are enclosed in the special ``{.`` and ``.}`` curly brackets. Pragmas are also often used as a @@ -5133,7 +5133,7 @@ shallow pragma The ``shallow`` pragma affects the semantics of a type: The compiler is allowed to make a shallow copy. This can cause serious semantic issues and break memory safety! However, it can speed up assignments considerably, -because the semantics of Nimrod require deep copying of sequences and strings. +because the semantics of Nim require deep copying of sequences and strings. This can be expensive, especially if sequences are used to build a tree structure: @@ -5223,7 +5223,7 @@ If the ``line`` pragma is used with a parameter, the parameter needs be a linearScanEnd pragma -------------------- The ``linearScanEnd`` pragma can be used to tell the compiler how to -compile a Nimrod `case`:idx: statement. Syntactically it has to be used as a +compile a Nim `case`:idx: statement. Syntactically it has to be used as a statement: .. code-block:: nimrod @@ -5251,7 +5251,7 @@ whole ``case`` statement, the whole ``case`` statement uses linear scanning. computedGoto pragma ------------------- The ``computedGoto`` pragma can be used to tell the compiler how to -compile a Nimrod `case`:idx: in a ``while true`` statement. +compile a Nim `case`:idx: in a ``while true`` statement. Syntactically it has to be used as a statement inside the loop: .. code-block:: nimrod @@ -5469,7 +5469,7 @@ Pragma pragma ------------- The ``pragma`` pragma can be used to declare user defined pragmas. This is -useful because Nimrod's templates and macros do not affect pragmas. User +useful because Nim's templates and macros do not affect pragmas. User defined pragmas are in a different module-wide scope than all other symbols. They cannot be imported from a module. @@ -5491,12 +5491,12 @@ generation. Disabling certain messages -------------------------- -Nimrod generates some warnings and hints ("line too long") that may annoy the +Nim generates some warnings and hints ("line too long") that may annoy the user. A mechanism for disabling certain messages is provided: Each hint and warning message contains a symbol in brackets. This is the message's identifier that can be used to enable or disable it: -.. code-block:: Nimrod +.. code-block:: Nim {.hint[LineTooLong]: off.} # turn off the hint about too long lines This is often better than disabling all warnings at once. @@ -5505,7 +5505,7 @@ This is often better than disabling all warnings at once. Foreign function interface ========================== -Nimrod's `FFI`:idx: (foreign function interface) is extensive and only the +Nim's `FFI`:idx: (foreign function interface) is extensive and only the parts that scale to other future backends (like the LLVM/JavaScript backends) are documented here. @@ -5514,7 +5514,7 @@ Importc pragma -------------- The ``importc`` pragma provides a means to import a proc or a variable from C. The optional argument is a string containing the C identifier. If -the argument is missing, the C name is the Nimrod identifier *exactly as +the argument is missing, the C name is the Nim identifier *exactly as spelled*: .. code-block:: @@ -5532,9 +5532,9 @@ Exportc pragma The ``exportc`` pragma provides a means to export a type, a variable, or a procedure to C. Enums and constants can't be exported. The optional argument is a string containing the C identifier. If the argument is missing, the C -name is the Nimrod identifier *exactly as spelled*: +name is the Nim identifier *exactly as spelled*: -.. code-block:: Nimrod +.. code-block:: Nim proc callme(formatstr: cstring) {.exportc: "callMe", varargs.} Note that this pragma is somewhat of a misnomer: Other backends will provide @@ -5546,7 +5546,7 @@ Extern pragma Like ``exportc`` or ``importc``, the ``extern`` pragma affects name mangling. The string literal passed to ``extern`` can be a format string: -.. code-block:: Nimrod +.. code-block:: Nim proc p(s: string) {.extern: "prefix$1".} = echo s @@ -5575,11 +5575,11 @@ the compiler to pass the type by reference (hidden pointer) to procs. Varargs pragma -------------- The ``varargs`` pragma can be applied to procedures only (and procedure -types). It tells Nimrod that the proc can take a variable number of parameters -after the last specified parameter. Nimrod string values will be converted to C +types). It tells Nim that the proc can take a variable number of parameters +after the last specified parameter. Nim string values will be converted to C strings automatically: -.. code-block:: Nimrod +.. code-block:: Nim proc printf(formatstr: cstring) {.nodecl, varargs.} printf("hallo %s", "world") # "world" will be passed as C string @@ -5648,7 +5648,7 @@ With the ``dynlib`` pragma a procedure or a variable can be imported from a dynamic library (``.dll`` files for Windows, ``lib*.so`` files for UNIX). The non-optional argument has to be the name of the dynamic library: -.. code-block:: Nimrod +.. code-block:: Nim proc gtk_image_new(): PGtkWidget {.cdecl, dynlib: "libgtk-x11-2.0.so", importc.} @@ -5706,7 +5706,7 @@ With the ``dynlib`` pragma a procedure can also be exported to a dynamic library. The pragma then has no argument and has to be used in conjunction with the ``exportc`` pragma: -.. code-block:: Nimrod +.. code-block:: Nim proc exportme(): int {.cdecl, exportc, dynlib.} This is only useful if the program is compiled as a dynamic library via the @@ -5721,7 +5721,7 @@ be used. The ``system`` module then contains several threading primitives. See the `threads `_ and `channels `_ modules for the thread API. -Nimrod's memory model for threads is quite different than that of other common +Nim's memory model for threads is quite different than that of other common programming languages (C, Pascal, Java): Each thread has its own (garbage collected) heap and sharing of memory is restricted to global variables. This helps to prevent race conditions. GC efficiency is improved quite a lot, @@ -5797,7 +5797,7 @@ exception in one thread terminates the whole *process*! Spawn ----- -Nimrod has a builtin thread pool that can be used for CPU intensive tasks. For +Nim has a builtin thread pool that can be used for CPU intensive tasks. For IO intensive tasks the upcoming ``async`` and ``await`` features should be used instead. `spawn`:idx: is used to pass a task to the thread pool: @@ -5828,7 +5828,7 @@ Currently the expression that ``spawn`` takes is however quite restricted: Taint mode ========== -The Nimrod compiler and most parts of the standard library support +The Nim compiler and most parts of the standard library support a taint mode. Input strings are declared with the `TaintedString`:idx: string type declared in the ``system`` module. diff --git a/doc/nimrodc.txt b/doc/nimrodc.txt index 016f0ed50c..8af045e2e6 100644 --- a/doc/nimrodc.txt +++ b/doc/nimrodc.txt @@ -1,9 +1,9 @@ =================================== - Nimrod Compiler User Guide + Nim Compiler User Guide =================================== :Author: Andreas Rumpf -:Version: |nimrodversion| +:Version: |nimversion| .. contents:: @@ -15,11 +15,11 @@ Introduction ============ -This document describes the usage of the *Nimrod compiler* -on the different supported platforms. It is not a definition of the Nimrod +This document describes the usage of the *Nim compiler* +on the different supported platforms. It is not a definition of the Nim programming language (therefore is the `manual `_). -Nimrod is free software; it is licensed under the +Nim is free software; it is licensed under the `MIT License `_. @@ -107,14 +107,14 @@ Configuration files passed as a command line argument to the compiler. -The ``nimrod`` executable processes configuration files in the following +The ``nim`` executable processes configuration files in the following directories (in this order; later files overwrite previous settings): -1) ``$nimrod/config/nimrod.cfg``, ``/etc/nimrod.cfg`` (UNIX) or ``%NIMROD%/config/nimrod.cfg`` (Windows). This file can be skipped with the ``--skipCfg`` command line option. -2) ``/home/$user/.config/nimrod.cfg`` (UNIX) or ``%APPDATA%/nimrod.cfg`` (Windows). This file can be skipped with the ``--skipUserCfg`` command line option. -3) ``$parentDir/nimrod.cfg`` where ``$parentDir`` stands for any parent directory of the project file's path. These files can be skipped with the ``--skipParentCfg`` command line option. -4) ``$projectDir/nimrod.cfg`` where ``$projectDir`` stands for the project file's path. This file can be skipped with the ``--skipProjCfg`` command line option. -5) A project can also have a project specific configuration file named ``$project.nimrod.cfg`` that resides in the same directory as ``$project.nim``. This file can be skipped with the ``--skipProjCfg`` command line option. +1) ``$nim/config/nim.cfg``, ``/etc/nim.cfg`` (UNIX) or ``%NIMROD%/config/nim.cfg`` (Windows). This file can be skipped with the ``--skipCfg`` command line option. +2) ``/home/$user/.config/nim.cfg`` (UNIX) or ``%APPDATA%/nim.cfg`` (Windows). This file can be skipped with the ``--skipUserCfg`` command line option. +3) ``$parentDir/nim.cfg`` where ``$parentDir`` stands for any parent directory of the project file's path. These files can be skipped with the ``--skipParentCfg`` command line option. +4) ``$projectDir/nim.cfg`` where ``$projectDir`` stands for the project file's path. This file can be skipped with the ``--skipProjCfg`` command line option. +5) A project can also have a project specific configuration file named ``$project.nim.cfg`` that resides in the same directory as ``$project.nim``. This file can be skipped with the ``--skipProjCfg`` command line option. Command line settings have priority over configuration file settings. @@ -122,17 +122,17 @@ Command line settings have priority over configuration file settings. The default build of a project is a `debug build`:idx:. To compile a `release build`:idx: define the ``release`` symbol:: - nimrod c -d:release myproject.nim + nim c -d:release myproject.nim Search path handling -------------------- -Nimrod has the concept of a global search path (PATH) that is queried to +Nim has the concept of a global search path (PATH) that is queried to determine where to find imported modules or include files. If multiple files are found an ambiguity error is produced. -``nimrod dump`` shows the contents of the PATH. +``nim dump`` shows the contents of the PATH. However before the PATH is used the current directory is checked for the file's existance. So if PATH contains ``$lib`` and ``$lib/bar`` and the @@ -152,10 +152,10 @@ the first matching file is used. Generated C code directory -------------------------- -The generated files that Nimrod produces all go into a subdirectory called +The generated files that Nim produces all go into a subdirectory called ``nimcache`` in your project directory. This makes it easy to delete all generated files. Files generated in this directory follow a naming logic which -you can read about in the `Nimrod Backend Integration document +you can read about in the `Nim Backend Integration document `_. However, the generated C code is not platform independent. C code generated for @@ -190,14 +190,14 @@ Cross compilation To cross compile, use for example:: - nimrod c --cpu:i386 --os:linux --compile_only --gen_script myproject.nim + nim c --cpu:i386 --os:linux --compile_only --gen_script myproject.nim Then move the C code and the compile script ``compile_myproject.sh`` to your Linux i386 machine and run the script. -Another way is to make Nimrod invoke a cross compiler toolchain:: +Another way is to make Nim invoke a cross compiler toolchain:: - nimrod c --cpu:arm --os:linux myproject.nim + nim c --cpu:arm --os:linux myproject.nim For cross compilation, the compiler invokes a C compiler named like ``$cpu.$os.$cc`` (for example arm.linux.gcc) and the configuration @@ -212,16 +212,16 @@ configuration file should contain something like:: DLL generation ============== -Nimrod supports the generation of DLLs. However, there must be only one +Nim supports the generation of DLLs. However, there must be only one instance of the GC per process/address space. This instance is contained in -``nimrtl.dll``. This means that every generated Nimrod DLL depends +``nimrtl.dll``. This means that every generated Nim DLL depends on ``nimrtl.dll``. To generate the "nimrtl.dll" file, use the command:: - nimrod c -d:release lib/nimrtl.nim + nim c -d:release lib/nimrtl.nim To link against ``nimrtl.dll`` use the command:: - nimrod c -d:useNimRtl myprog.nim + nim c -d:useNimRtl myprog.nim **Note**: Currently the creation of ``nimrtl.dll`` with thread support has never been tested and is unlikely to work! @@ -243,9 +243,9 @@ Define Effect version. ``useFork`` Makes ``osproc`` use ``fork`` instead of ``posix_spawn``. ``useNimRtl`` Compile and link against ``nimrtl.dll``. -``useMalloc`` Makes Nimrod use C's `malloc`:idx: instead of Nimrod's +``useMalloc`` Makes Nim use C's `malloc`:idx: instead of Nim's own memory manager. This only works with ``gc:none``. -``useRealtimeGC`` Enables support of Nimrod's GC for *soft* realtime +``useRealtimeGC`` Enables support of Nim's GC for *soft* realtime systems. See the documentation of the `gc `_ for further information. ``nodejs`` The JS target is actually ``node.js``. @@ -258,8 +258,8 @@ Define Effect Additional Features =================== -This section describes Nimrod's additional features that are not listed in the -Nimrod manual. Some of the features here only make sense for the C code +This section describes Nim's additional features that are not listed in the +Nim manual. Some of the features here only make sense for the C code generator and are subject to change. @@ -267,13 +267,13 @@ NoDecl pragma ------------- The ``noDecl`` pragma can be applied to almost any symbol (variable, proc, type, etc.) and is sometimes useful for interoperability with C: -It tells Nimrod that it should not generate a declaration for the symbol in +It tells Nim that it should not generate a declaration for the symbol in the C code. For example: -.. code-block:: Nimrod +.. code-block:: Nim var EACCES {.importc, noDecl.}: cint # pretend EACCES was a variable, as - # Nimrod does not know its value + # Nim does not know its value However, the ``header`` pragma is often the better alternative. @@ -286,14 +286,14 @@ The ``header`` pragma is very similar to the ``noDecl`` pragma: It can be applied to almost any symbol and specifies that it should not be declared and instead the generated code should contain an ``#include``: -.. code-block:: Nimrod +.. code-block:: Nim type PFile {.importc: "FILE*", header: "".} = distinct pointer - # import C's FILE* type; Nimrod will treat it as a new pointer type + # import C's FILE* type; Nim will treat it as a new pointer type The ``header`` pragma always expects a string constant. The string contant contains the header file: As usual for C, a system header file is enclosed -in angle brackets: ``<>``. If no angle brackets are given, Nimrod +in angle brackets: ``<>``. If no angle brackets are given, Nim encloses the header file in ``""`` in the generated C code. **Note**: This will not work for the LLVM backend. @@ -304,7 +304,7 @@ IncompleteStruct pragma The ``incompleteStruct`` pragma tells the compiler to not use the underlying C ``struct`` in a ``sizeof`` expression: -.. code-block:: Nimrod +.. code-block:: Nim type TDIR* {.importc: "DIR", header: "", final, pure, incompleteStruct.} = object @@ -315,10 +315,10 @@ Compile pragma The ``compile`` pragma can be used to compile and link a C/C++ source file with the project: -.. code-block:: Nimrod +.. code-block:: Nim {.compile: "myfile.cpp".} -**Note**: Nimrod computes a CRC checksum and only recompiles the file if it +**Note**: Nim computes a CRC checksum and only recompiles the file if it has changed. You can use the ``-f`` command line option to force recompilation of the file. @@ -327,7 +327,7 @@ Link pragma ----------- The ``link`` pragma can be used to link an additional file with the project: -.. code-block:: Nimrod +.. code-block:: Nim {.link: "myfile.o".} @@ -336,13 +336,13 @@ PassC pragma The ``passC`` pragma can be used to pass additional parameters to the C compiler like you would using the commandline switch ``--passC``: -.. code-block:: Nimrod +.. code-block:: Nim {.passC: "-Wall -Werror".} Note that you can use ``gorge`` from the `system module `_ to embed parameters from an external command at compile time: -.. code-block:: Nimrod +.. code-block:: Nim {.passC: gorge("pkg-config --cflags sdl").} PassL pragma @@ -350,13 +350,13 @@ PassL pragma The ``passL`` pragma can be used to pass additional parameters to the linker like you would using the commandline switch ``--passL``: -.. code-block:: Nimrod +.. code-block:: Nim {.passL: "-lSDLmain -lSDL".} Note that you can use ``gorge`` from the `system module `_ to embed parameters from an external command at compile time: -.. code-block:: Nimrod +.. code-block:: Nim {.passL: gorge("pkg-config --libs sdl").} @@ -369,16 +369,16 @@ extremely useful for interfacing with `C++`:idx: or `Objective C`:idx: code. Example: -.. code-block:: Nimrod +.. code-block:: Nim {.emit: """ static int cvariable = 420; """.} {.push stackTrace:off.} proc embedsC() = - var nimrodVar = 89 - # use backticks to access Nimrod symbols within an emit section: - {.emit: """fprintf(stdout, "%d\n", cvariable + (int)`nimrodVar`);""".} + var nimVar = 89 + # use backticks to access Nim symbols within an emit section: + {.emit: """fprintf(stdout, "%d\n", cvariable + (int)`nimVar`);""".} {.pop.} embedsC() @@ -392,7 +392,7 @@ code then uses the C++ method calling syntax: ``obj->method(arg)``. In addition with the ``header`` and ``emit`` pragmas this allows *sloppy* interfacing with libraries written in C++: -.. code-block:: Nimrod +.. code-block:: Nim # Horrible example of how to interface with a C++ engine ... ;-) {.link: "/usr/lib/libIrrlicht.so".} @@ -431,7 +431,7 @@ generated code then uses the Objective C method calling syntax: ``[obj method param1: arg]``. In addition with the ``header`` and ``emit`` pragmas this allows *sloppy* interfacing with libraries written in Objective C: -.. code-block:: Nimrod +.. code-block:: Nim # horrible example of how to interface with GNUStep ... {.passL: "-lobjc".} @@ -475,11 +475,11 @@ emits Objective C code. CodegenDecl pragma ------------------ -The ``codegenDecl`` pragma can be used to directly influence Nimrod's code +The ``codegenDecl`` pragma can be used to directly influence Nim's code generator. It receives a format string that determines how the variable or proc is declared in the generated code: -.. code-block:: nimrod +.. code-block:: nim var a {.codegenDecl: "$# progmem $#".}: int @@ -494,7 +494,7 @@ The ``injectStmt`` pragma can be used to inject a statement before every other statement in the current module. It is only supposed to be used for debugging: -.. code-block:: nimrod +.. code-block:: nim {.injectStmt: gcInvariants().} # ... complex code here that produces crashes ... @@ -523,7 +523,7 @@ is raised. Debugger option --------------- -The ``debugger`` option enables or disables the *Embedded Nimrod Debugger*. +The ``debugger`` option enables or disables the *Embedded Nim Debugger*. See the documentation of endb_ for further information. @@ -545,11 +545,11 @@ in C/C++). Source code style ================= -Nimrod allows you to `mix freely case and underscores as identifier separators +Nim allows you to `mix freely case and underscores as identifier separators `_, so variables named ``MyPrecioussInt`` and ``my_preciouss_int`` are equivalent: -.. code-block:: Nimrod +.. code-block:: Nim var MyPrecioussInt = 3 # Following line compiles fine! echo my_preciouss_int @@ -557,16 +557,16 @@ Nimrod allows you to `mix freely case and underscores as identifier separators Since this can lead to many variants of the same source code (you can use `nimgrep `_ instead of your typical ``grep`` to ignore style problems) the compiler provides the command ``pretty`` to help unifying the -style of source code. Running ``nimrod pretty ugly_test.nim`` with this +style of source code. Running ``nim pretty ugly_test.nim`` with this example will generate a secondary file named ``ugly_test.pretty.nim`` with the following content: -.. code-block:: Nimrod +.. code-block:: Nim var MyPrecioussInt = 3 # Following line compiles fine! echo MyPrecioussInt -During execution the ``pretty`` command will also run on Nimrod's standard +During execution the ``pretty`` command will also run on Nim's standard library, since it doesn't differentiate the standard library as something special, and hence will warn of many *errors* which are out of your hand to fix, creating respective ``.pretty.nim`` files all the way. You can ignore @@ -583,11 +583,11 @@ important changes for you to review. In this case the command is warning that a variable name should not start with a capital letter, which is usually reserved to `object types `_. To learn about the accepted `camel case style `_ read `Coding Guidelines in -the Internals of Nimrod Compiler `_ or `Coding -Guidelines `_ and `NEP 1 -: Style Guide for Nimrod Code -`_ -from the Nimrod `GitHub wiki`_. +the Internals of Nim Compiler `_ or `Coding +Guidelines `_ and `NEP 1 +: Style Guide for Nim Code +`_ +from the Nim `GitHub wiki`_. This command is safe to run because it will never attempt to overwrite your existing sources, but the respective ``.pretty.nim`` files **will** be @@ -597,14 +597,14 @@ overwritten without notice. DynlibOverride ============== -By default Nimrod's ``dynlib`` pragma causes the compiler to generate +By default Nim's ``dynlib`` pragma causes the compiler to generate ``GetProcAddress`` (or their Unix counterparts) calls to bind to a DLL. With the ``dynlibOverride`` command line switch this can be prevented and then via ``--passL`` the static library can be linked against. For instance, to link statically against Lua this command might work on Linux:: - nimrod c --dynlibOverride:lua --passL:liblua.lib program.nim + nim c --dynlibOverride:lua --passL:liblua.lib program.nim Backend language options @@ -614,32 +614,32 @@ The typical compiler usage involves using the ``compile`` or ``c`` command to transform a ``.nim`` file into one or more ``.c`` files which are then compiled with the platform's C compiler into a static binary. However there are other commands to compile to C++, Objective-C or Javascript. More details -can be read in the `Nimrod Backend Integration document `_. +can be read in the `Nim Backend Integration document `_. -Nimrod documentation tools -========================== +Nim documentation tools +======================= -Nimrod provides the `doc`:idx: and `doc2`:idx: commands to generate HTML +Nim provides the `doc`:idx: and `doc2`:idx: commands to generate HTML documentation from ``.nim`` source files. Only exported symbols will appear in the output. For more details `see the docgen documentation `_. -Nimrod idetools integration -=========================== +Nim idetools integration +======================== -Nimrod provides language integration with external IDEs through the +Nim provides language integration with external IDEs through the idetools command. See the documentation of `idetools `_ for further information. -Nimrod interactive mode -======================= +Nim interactive mode +==================== -The Nimrod compiler supports an interactive mode. This is also known as -a `REPL`:idx: (*read eval print loop*). If Nimrod has been built with the +The Nim compiler supports an interactive mode. This is also known as +a `REPL`:idx: (*read eval print loop*). If Nim has been built with the ``-d:useGnuReadline`` switch, it uses the GNU readline library for terminal -input management. To start Nimrod in interactive mode use the command -``nimrod i``. To quit use the ``quit()`` command. To determine whether an input +input management. To start Nim in interactive mode use the command +``nim i``. To quit use the ``quit()`` command. To determine whether an input line is an incomplete statement to be continued these rules are used: 1. The line ends with ``[-+*/\\<>!\?\|%&$@~,;:=#^]\s*$`` (operator symbol followed by optional whitespace). @@ -648,8 +648,8 @@ line is an incomplete statement to be continued these rules are used: does not work if the line contains more than one ``"""``. -Nimrod for embedded systems -=========================== +Nim for embedded systems +======================== The standard library can be avoided to a point where C code generation for 16bit micro controllers is feasible. Use the `standalone`:idx: target @@ -661,7 +661,7 @@ target. For example, to generate code for an `AVR`:idx: processor use this command:: - nimrod c --cpu:avr --os:standalone --deadCodeElim:on --genScript x.nim + nim c --cpu:avr --os:standalone --deadCodeElim:on --genScript x.nim For the ``standalone`` target you need to provide a file ``panicoverride.nim``. @@ -669,27 +669,27 @@ See ``tests/manyloc/standalone/panicoverride.nim`` for an example implementation. -Nimrod for realtime systems -=========================== +Nim for realtime systems +======================== -See the documentation of Nimrod's soft realtime `GC `_ for further +See the documentation of Nim's soft realtime `GC `_ for further information. -Debugging with Nimrod -===================== +Debugging with Nim +================== -Nimrod comes with its own *Embedded Nimrod Debugger*. See +Nim comes with its own *Embedded Nim Debugger*. See the documentation of endb_ for further information. -Optimizing for Nimrod -===================== +Optimizing for Nim +================== -Nimrod has no separate optimizer, but the C code that is produced is very +Nim has no separate optimizer, but the C code that is produced is very efficient. Most C compilers have excellent optimizers, so usually it is -not needed to optimize one's code. Nimrod has been designed to encourage -efficient code: The most readable code in Nimrod is often the most efficient +not needed to optimize one's code. Nim has been designed to encourage +efficient code: The most readable code in Nim is often the most efficient too. However, sometimes one has to optimize. Do it in the following order: @@ -706,32 +706,32 @@ This section can only help you with the last item. Optimizing string handling -------------------------- -String assignments are sometimes expensive in Nimrod: They are required to +String assignments are sometimes expensive in Nim: They are required to copy the whole string. However, the compiler is often smart enough to not copy strings. Due to the argument passing semantics, strings are never copied when passed to subroutines. The compiler does not copy strings that are a result from a procedure call, because the callee returns a new string anyway. Thus it is efficient to do: -.. code-block:: Nimrod +.. code-block:: Nim var s = procA() # assignment will not copy the string; procA allocates a new # string already However it is not efficient to do: -.. code-block:: Nimrod +.. code-block:: Nim var s = varA # assignment has to copy the whole string into a new buffer! For ``let`` symbols a copy is not always necessary: -.. code-block:: Nimrod +.. code-block:: Nim let s = varA # may only copy a pointer if it safe to do so If you know what you're doing, you can also mark single string (or sequence) objects as `shallow`:idx:\: -.. code-block:: Nimrod +.. code-block:: Nim var s = "abc" shallow(s) # mark 's' as shallow string var x = s # now might not copy the string! @@ -744,7 +744,7 @@ The compiler optimizes string case statements: A hashing scheme is used for them if several different string constants are used. So code like this is reasonably efficient: -.. code-block:: Nimrod +.. code-block:: Nim case normalize(k.key) of "name": c.name = v of "displayname": c.displayName = v diff --git a/lib/packages/docutils/highlite.nim b/lib/packages/docutils/highlite.nim index ff371f4e17..3d55fe1fcc 100644 --- a/lib/packages/docutils/highlite.nim +++ b/lib/packages/docutils/highlite.nim @@ -1,6 +1,6 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2012 Andreas Rumpf # # See the file "copying.txt", included in this @@ -31,10 +31,10 @@ type state: TTokenClass TSourceLanguage* = enum - langNone, langNimrod, langCpp, langCsharp, langC, langJava + langNone, langNim, langCpp, langCsharp, langC, langJava const - sourceLanguageToStr*: array[TSourceLanguage, string] = ["none", "Nimrod", + sourceLanguageToStr*: array[TSourceLanguage, string] = ["none", "Nim", "C++", "C#", "C", "Java"] tokenClassToStr*: array[TTokenClass, string] = ["Eof", "None", "Whitespace", "DecNumber", "BinNumber", "HexNumber", "OctNumber", "FloatNumber", @@ -46,7 +46,7 @@ const # The following list comes from doc/keywords.txt, make sure it is # synchronized with this array by running the module itself as a test case. - nimrodKeywords = ["addr", "and", "as", "asm", "atomic", "bind", "block", + nimKeywords = ["addr", "and", "as", "asm", "atomic", "bind", "block", "break", "case", "cast", "const", "continue", "converter", "discard", "distinct", "div", "do", "elif", "else", "end", "enum", "except", "export", "finally", "for", "from", "generic", "if", "import", "in", "include", @@ -79,7 +79,7 @@ proc deinitGeneralTokenizer*(g: var TGeneralTokenizer) = discard proc nimGetKeyword(id: string): TTokenClass = - for k in nimrodKeywords: + for k in nimKeywords: if cmpIgnoreStyle(id, k) == 0: return gtKeyword result = gtIdentifier when false: @@ -542,7 +542,7 @@ proc javaNextToken(g: var TGeneralTokenizer) = proc getNextToken*(g: var TGeneralTokenizer, lang: TSourceLanguage) = case lang of langNone: assert false - of langNimrod: nimNextToken(g) + of langNim: nimNextToken(g) of langCpp: cppNextToken(g) of langCsharp: csharpNextToken(g) of langC: cNextToken(g) @@ -557,7 +557,7 @@ when isMainModule: keywords = input.split() break doAssert(not keywords.isNil, "Couldn't read any keywords.txt file!") - doAssert keywords.len == nimrodKeywords.len, "No matching lengths" + doAssert keywords.len == nimKeywords.len, "No matching lengths" for i in 0..keywords.len-1: - #echo keywords[i], " == ", nimrodKeywords[i] - doAssert keywords[i] == nimrodKeywords[i], "Unexpected keyword" + #echo keywords[i], " == ", nimKeywords[i] + doAssert keywords[i] == nimKeywords[i], "Unexpected keyword" diff --git a/lib/packages/docutils/rstgen.nim b/lib/packages/docutils/rstgen.nim index e9bae69b55..5d69fcf515 100644 --- a/lib/packages/docutils/rstgen.nim +++ b/lib/packages/docutils/rstgen.nim @@ -1,6 +1,6 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2012 Andreas Rumpf # # See the file "copying.txt", included in this @@ -103,7 +103,7 @@ proc initRstGenerator*(g: var TRstGenerator, target: TOutputTarget, ## ## Example: ## - ## .. code-block:: nimrod + ## .. code-block:: nim ## ## import packages/docutils/rstgen ## @@ -231,7 +231,7 @@ proc renderRstToOut*(d: var TRstGenerator, n: PRstNode, result: var string) ## ``initRstGenerator`` and parse a rst file with ``rstParse`` from the ## `packages/docutils/rst module `_. Example: ## - ## .. code-block:: nimrod + ## .. code-block:: nim ## ## # ...configure gen and rst vars... ## var generatedHTML = "" @@ -597,7 +597,7 @@ proc mergeIndexes*(dir: string): string = ## Merges all index files in `dir` and returns the generated index as HTML. ## ## This proc will first scan `dir` for index files with the ``.idx`` - ## extension previously created by commands like ``nimrod doc|rst2html`` + ## extension previously created by commands like ``nim doc|rst2html`` ## which use the ``--index:on`` switch. These index files are the result of ## calls to `setIndexTerm() <#setIndexTerm>`_ and `writeIndexFile() ## <#writeIndexFile>`_, so they are simple tab separated files. @@ -768,7 +768,7 @@ proc renderCodeBlock(d: PDoc, n: PRstNode, result: var string) = var langstr = strip(getArgument(n)) var lang: TSourceLanguage if langstr == "": - lang = langNimrod # default language + lang = langNim # default language else: lang = getSourceLanguage(langstr) @@ -1123,7 +1123,7 @@ proc rstToHtml*(s: string, options: TRstParseOptions, ## work. For an explanation of the ``config`` parameter see the ## ``initRstGenerator`` proc. Example: ## - ## .. code-block:: nimrod + ## .. code-block:: nim ## import packages/docutils/rstgen, strtabs ## ## echo rstToHtml("*Hello* **world**!", {}, diff --git a/lib/system.nim b/lib/system.nim index 0d8f63bd48..0ba99f9151 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -2015,7 +2015,7 @@ template accumulateResult*(iter: expr) = for x in iter: add(result, x) # we have to compute this here before turning it off in except.nim anyway ... -const nimrodStackTrace = compileOption("stacktrace") +const NimStackTrace = compileOption("stacktrace") {.push checks: off.} # obviously we cannot generate checking operations here :-) diff --git a/lib/system/alloc.nim b/lib/system/alloc.nim index 602e5c7faf..9638472c20 100644 --- a/lib/system/alloc.nim +++ b/lib/system/alloc.nim @@ -1,13 +1,13 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2012 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. # -# Low level allocator for Nimrod. Has been designed to support the GC. +# Low level allocator for Nim. Has been designed to support the GC. # TODO: # - eliminate "used" field # - make searching for block O(1) diff --git a/lib/system/ansi_c.nim b/lib/system/ansi_c.nim index e012697ae7..121cd207db 100644 --- a/lib/system/ansi_c.nim +++ b/lib/system/ansi_c.nim @@ -1,6 +1,6 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2013 Andreas Rumpf # # See the file "copying.txt", included in this @@ -8,7 +8,7 @@ # # This include file contains headers of Ansi C procs -# and definitions of Ansi C types in Nimrod syntax +# and definitions of Ansi C types in Nim syntax # All symbols are prefixed with 'c_' to avoid ambiguities {.push hints:off} diff --git a/lib/system/arithm.nim b/lib/system/arithm.nim index 7672947cdf..1cc9b41e6d 100644 --- a/lib/system/arithm.nim +++ b/lib/system/arithm.nim @@ -1,6 +1,6 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2012 Andreas Rumpf # # See the file "copying.txt", included in this diff --git a/lib/system/assign.nim b/lib/system/assign.nim index 0e27eb57fe..a213a9d978 100644 --- a/lib/system/assign.nim +++ b/lib/system/assign.nim @@ -1,6 +1,6 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2012 Andreas Rumpf # # See the file "copying.txt", included in this diff --git a/lib/system/atomics.nim b/lib/system/atomics.nim index 695a5f63e0..d5f9b35999 100644 --- a/lib/system/atomics.nim +++ b/lib/system/atomics.nim @@ -1,13 +1,13 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2014 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. # -# Atomic operations for Nimrod. +# Atomic operations for Nim. {.push stackTrace:off.} const someGcc = defined(gcc) or defined(llvm_gcc) or defined(clang) @@ -159,6 +159,7 @@ when someGcc and hasThreadSupport: elif defined(vcc) and hasThreadSupport: proc addAndFetch*(p: ptr int, val: int): int {. importc: "NimXadd", nodecl.} + proc fence*() {.importc: "_ReadWriteBarrier", header: "".} else: proc addAndFetch*(p: ptr int, val: int): int {.inline.} = diff --git a/lib/system/avltree.nim b/lib/system/avltree.nim index bced15d6a6..157799b288 100644 --- a/lib/system/avltree.nim +++ b/lib/system/avltree.nim @@ -1,6 +1,6 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2012 Andreas Rumpf # # See the file "copying.txt", included in this diff --git a/lib/system/cellsets.nim b/lib/system/cellsets.nim index 3825e5b476..653aed2416 100644 --- a/lib/system/cellsets.nim +++ b/lib/system/cellsets.nim @@ -1,6 +1,6 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2013 Andreas Rumpf # # See the file "copying.txt", included in this diff --git a/lib/system/cgprocs.nim b/lib/system/cgprocs.nim index d483c61bda..d46e715f14 100644 --- a/lib/system/cgprocs.nim +++ b/lib/system/cgprocs.nim @@ -1,6 +1,6 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2012 Andreas Rumpf # # See the file "copying.txt", included in this diff --git a/lib/system/channels.nim b/lib/system/channels.nim index df46922e4e..0715d05e55 100644 --- a/lib/system/channels.nim +++ b/lib/system/channels.nim @@ -1,6 +1,6 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2014 Andreas Rumpf # # See the file "copying.txt", included in this diff --git a/lib/system/chcks.nim b/lib/system/chcks.nim index 387b54ef18..c018a76315 100644 --- a/lib/system/chcks.nim +++ b/lib/system/chcks.nim @@ -1,6 +1,6 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2013 Andreas Rumpf # # See the file "copying.txt", included in this diff --git a/lib/system/debugger.nim b/lib/system/debugger.nim index af7b6d5157..37a7c89f67 100644 --- a/lib/system/debugger.nim +++ b/lib/system/debugger.nim @@ -1,6 +1,6 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2013 Andreas Rumpf # # See the file "copying.txt", included in this @@ -293,7 +293,7 @@ proc checkWatchpoints = Watchpoints[i].oldValue = newHash proc endb(line: int, file: cstring) {.compilerproc, noinline.} = - # This proc is called before every Nimrod code line! + # This proc is called before every Nim code line! if framePtr == nil: return if dbgWatchpointHook != nil: checkWatchpoints() framePtr.line = line # this is done here for smaller code size! diff --git a/lib/system/deepcopy.nim b/lib/system/deepcopy.nim index e7eb1cdb42..243cc85e87 100644 --- a/lib/system/deepcopy.nim +++ b/lib/system/deepcopy.nim @@ -1,6 +1,6 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2014 Andreas Rumpf # # See the file "copying.txt", included in this diff --git a/lib/system/dyncalls.nim b/lib/system/dyncalls.nim index 9ef1a99ca6..eb57559fdb 100644 --- a/lib/system/dyncalls.nim +++ b/lib/system/dyncalls.nim @@ -1,6 +1,6 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2012 Andreas Rumpf # # See the file "copying.txt", included in this diff --git a/lib/system/embedded.nim b/lib/system/embedded.nim index 661992e812..c6db9bca48 100644 --- a/lib/system/embedded.nim +++ b/lib/system/embedded.nim @@ -1,6 +1,6 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2012 Andreas Rumpf # # See the file "copying.txt", included in this diff --git a/lib/system/endb.nim b/lib/system/endb.nim index f7e95e216f..9d3ae574ca 100644 --- a/lib/system/endb.nim +++ b/lib/system/endb.nim @@ -1,6 +1,6 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2013 Andreas Rumpf # # See the file "copying.txt", included in this @@ -11,7 +11,7 @@ # with the application. Mostly we do not use dynamic memory here as that # would interfere with the GC and trigger ON/OFF errors if the # user program corrupts memory. Unfortunately, for dispaying -# variables we use the ``system.repr()`` proc which uses Nimrod +# variables we use the ``system.repr()`` proc which uses Nim # strings and thus allocates memory from the heap. Pity, but # I do not want to implement ``repr()`` twice. diff --git a/lib/system/excpt.nim b/lib/system/excpt.nim index 3c5436afb5..04a23db9dc 100644 --- a/lib/system/excpt.nim +++ b/lib/system/excpt.nim @@ -1,6 +1,6 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2014 Andreas Rumpf # # See the file "copying.txt", included in this @@ -68,8 +68,8 @@ proc popCurrentException {.compilerRtl, inl.} = # some platforms have native support for stack traces: const nativeStackTraceSupported* = (defined(macosx) or defined(linux)) and - not nimrodStackTrace - hasSomeStackTrace = nimrodStackTrace or + not NimStackTrace + hasSomeStackTrace = NimStackTrace or defined(nativeStackTrace) and nativeStackTraceSupported when defined(nativeStacktrace) and nativeStackTraceSupported: @@ -177,7 +177,7 @@ proc auxWriteStackTrace(f: PFrame, s: var string) = when hasSomeStackTrace: proc rawWriteStackTrace(s: var string) = - when nimrodStackTrace: + when NimStackTrace: if framePtr == nil: add(s, "No stack traceback available\n") else: @@ -318,7 +318,7 @@ when not defined(noSignalHandler): GC_disable() var buf = newStringOfCap(2000) rawWriteStackTrace(buf) - processSignal(sig, buf.add) # nice hu? currying a la nimrod :-) + processSignal(sig, buf.add) # nice hu? currying a la Nim :-) showErrorMessage(buf) GC_enable() else: diff --git a/lib/system/gc.nim b/lib/system/gc.nim index 0c1fc7748d..053c7df69d 100644 --- a/lib/system/gc.nim +++ b/lib/system/gc.nim @@ -1,6 +1,6 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2013 Andreas Rumpf # # See the file "copying.txt", included in this diff --git a/lib/system/gc2.nim b/lib/system/gc2.nim index 132da9885b..ee52b54f56 100644 --- a/lib/system/gc2.nim +++ b/lib/system/gc2.nim @@ -1,6 +1,6 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2012 Andreas Rumpf # # See the file "copying.txt", included in this diff --git a/lib/system/gc_ms.nim b/lib/system/gc_ms.nim index 05bcdcc82c..629219bf7b 100644 --- a/lib/system/gc_ms.nim +++ b/lib/system/gc_ms.nim @@ -1,13 +1,13 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2014 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. # -# A simple mark&sweep garbage collector for Nimrod. Define the +# A simple mark&sweep garbage collector for Nim. Define the # symbol ``gcUseBitvectors`` to generate a variant of this GC. {.push profiler:off.} diff --git a/lib/system/hti.nim b/lib/system/hti.nim index ef8f50831d..4a8ab2485d 100644 --- a/lib/system/hti.nim +++ b/lib/system/hti.nim @@ -1,6 +1,6 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2012 Andreas Rumpf # # See the file "copying.txt", included in this diff --git a/lib/system/inclrtl.nim b/lib/system/inclrtl.nim index 5c82db4da3..a975bb7c2d 100644 --- a/lib/system/inclrtl.nim +++ b/lib/system/inclrtl.nim @@ -1,6 +1,6 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2014 Andreas Rumpf # # See the file "copying.txt", included in this diff --git a/lib/system/jssys.nim b/lib/system/jssys.nim index 8766906e3a..894f259f31 100644 --- a/lib/system/jssys.nim +++ b/lib/system/jssys.nim @@ -1,6 +1,6 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2012 Andreas Rumpf # # See the file "copying.txt", included in this @@ -103,7 +103,7 @@ proc raiseException(e: ref E_Base, ename: cstring) {. if excHandler != nil: excHandler.exc = e else: - when nimrodStackTrace: + when NimStackTrace: var buf = rawWriteStackTrace() else: var buf = "" diff --git a/lib/system/mmdisp.nim b/lib/system/mmdisp.nim index a09b6cf934..803c1f5c0e 100644 --- a/lib/system/mmdisp.nim +++ b/lib/system/mmdisp.nim @@ -1,14 +1,14 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2013 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. # -# Nimrod high-level memory manager: It supports Boehm's GC, no GC and the -# native Nimrod GC. The native Nimrod GC is the default. +# Nim high-level memory manager: It supports Boehm's GC, no GC and the +# native Nim GC. The native Nim GC is the default. #{.push checks:on, assertions:on.} {.push checks:off.} @@ -259,7 +259,7 @@ elif defined(nogc) and defined(useMalloc): elif defined(nogc): # Even though we don't want the GC, we cannot simply use C's memory manager - # because Nimrod's runtime wants ``realloc`` to zero out the additional + # because Nim's runtime wants ``realloc`` to zero out the additional # space which C's ``realloc`` does not. And we cannot get the old size of an # object, because C does not support this operation... Even though every # possible implementation has to have a way to determine the object's size. diff --git a/lib/system/profiler.nim b/lib/system/profiler.nim index 8e4c51dd91..96ab6abc75 100644 --- a/lib/system/profiler.nim +++ b/lib/system/profiler.nim @@ -1,13 +1,13 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2012 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. # -# This file implements the Nimrod profiler. The profiler needs support by the +# This file implements the Nim profiler. The profiler needs support by the # code generator. The idea is to inject the instruction stream # with 'nimProfile()' calls. These calls are injected at every loop end # (except perhaps loops that have no side-effects). At every Nth call a diff --git a/lib/system/repr.nim b/lib/system/repr.nim index 8e1bc5f264..7408552f99 100644 --- a/lib/system/repr.nim +++ b/lib/system/repr.nim @@ -1,6 +1,6 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2012 Andreas Rumpf # # See the file "copying.txt", included in this diff --git a/lib/system/reprjs.nim b/lib/system/reprjs.nim index fd1cb5c8b2..57237cfffa 100644 --- a/lib/system/reprjs.nim +++ b/lib/system/reprjs.nim @@ -1,6 +1,6 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2012 Andreas Rumpf # # See the file "copying.txt", included in this diff --git a/lib/system/sets.nim b/lib/system/sets.nim index 794c65cb8e..626d43c33d 100644 --- a/lib/system/sets.nim +++ b/lib/system/sets.nim @@ -1,6 +1,6 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2012 Andreas Rumpf # # See the file "copying.txt", included in this diff --git a/lib/system/syslocks.nim b/lib/system/syslocks.nim index b8ed29cfc6..cff873cf49 100644 --- a/lib/system/syslocks.nim +++ b/lib/system/syslocks.nim @@ -1,6 +1,6 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2012 Andreas Rumpf # # See the file "copying.txt", included in this diff --git a/lib/system/sysspawn.nim b/lib/system/sysspawn.nim index 5161104a9f..04f30872d1 100644 --- a/lib/system/sysspawn.nim +++ b/lib/system/sysspawn.nim @@ -1,13 +1,13 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2014 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. # -## Implements Nimrod's 'spawn'. +## Implements Nim's 'spawn'. when not declared(NimString): {.error: "You must not import this module explicitly".} diff --git a/lib/system/sysstr.nim b/lib/system/sysstr.nim index bc79bb254d..14b24cca68 100644 --- a/lib/system/sysstr.nim +++ b/lib/system/sysstr.nim @@ -1,6 +1,6 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2012 Andreas Rumpf # # See the file "copying.txt", included in this @@ -119,7 +119,7 @@ proc addChar(s: NimString, c: char): NimString = inc(result.len) # These routines should be used like following: -# +# # s &= "Hello " & name & ", how do you feel?" # # @@ -130,7 +130,7 @@ proc addChar(s: NimString, c: char): NimString = # appendString(s, strLit3); # } # -# +# # s = "Hello " & name & ", how do you feel?" # # @@ -143,7 +143,7 @@ proc addChar(s: NimString, c: char): NimString = # s = tmp0; # } # -# +# # s = "" # # diff --git a/lib/system/threads.nim b/lib/system/threads.nim index 4717659e5f..9e945544fe 100644 --- a/lib/system/threads.nim +++ b/lib/system/threads.nim @@ -1,17 +1,17 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2012 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. # -## Thread support for Nimrod. **Note**: This is part of the system module. +## Thread support for Nim. **Note**: This is part of the system module. ## Do not import it directly. To activate thread support you need to compile ## with the ``--threads:on`` command line switch. ## -## Nimrod's memory model for threads is quite different from other common +## Nim's memory model for threads is quite different from other common ## programming languages (C, Pascal): Each thread has its own ## (garbage collected) heap and sharing of memory is restricted. This helps ## to prevent race conditions and improves efficiency. See `the manual for @@ -19,7 +19,7 @@ ## ## Example: ## -## .. code-block:: nimrod +## .. code-block:: Nim ## ## import locks ## @@ -245,14 +245,14 @@ when not defined(useNimRtl): # the GC can examine the stacks? proc stopTheWord() = discard -# We jump through some hops here to ensure that Nimrod thread procs can have -# the Nimrod calling convention. This is needed because thread procs are +# We jump through some hops here to ensure that Nim thread procs can have +# the Nim calling convention. This is needed because thread procs are # ``stdcall`` on Windows and ``noconv`` on UNIX. Alternative would be to just # use ``stdcall`` since it is mapped to ``noconv`` on UNIX anyway. type TThread* {.pure, final.}[TArg] = - object of TGcThread ## Nimrod thread. A thread is a heavy object (~14K) + object of TGcThread ## Nim thread. A thread is a heavy object (~14K) ## that **must not** be part of a message! Use ## a ``TThreadId`` for that. when TArg is void: diff --git a/lib/system/timers.nim b/lib/system/timers.nim index fa1a13a5f2..e58ff7adc0 100644 --- a/lib/system/timers.nim +++ b/lib/system/timers.nim @@ -1,6 +1,6 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2012 Andreas Rumpf # # See the file "copying.txt", included in this diff --git a/lib/system/widestrs.nim b/lib/system/widestrs.nim index cd64ff410e..1e8bc6791c 100644 --- a/lib/system/widestrs.nim +++ b/lib/system/widestrs.nim @@ -1,13 +1,13 @@ # # -# Nimrod's Runtime Library +# Nim's Runtime Library # (c) Copyright 2012 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. # -# Nimrod support for C/C++'s `wide strings`:idx:. This is part of the system +# Nim support for C/C++'s `wide strings`:idx:. This is part of the system # module! Do not import it directly! when not declared(NimString): diff --git a/tests/parallel/tflowvar.nim b/tests/parallel/tflowvar.nim index 77fab14b5c..96d42255d8 100644 --- a/tests/parallel/tflowvar.nim +++ b/tests/parallel/tflowvar.nim @@ -1,11 +1,13 @@ discard """ - output: '''foobarfoobarbazbearbazbear''' + output: '''foobarfoobar +bazbearbazbear +1''' cmd: "nimrod $target --threads:on $options $file" """ import threadpool -proc computeSomething(a, b: string): string = a & b & a & b +proc computeSomething(a, b: string): string = a & b & a & b & "\n" proc main = let fvA = spawn computeSomething("foo", "bar") @@ -15,3 +17,19 @@ proc main = main() sync() + + +type + TIntSeq = seq[int] + +proc t(): TIntSeq = + result = @[1] + +proc p(): int = + var a: FlowVar[TIntSeq] + parallel: + var aa = spawn t() + a = aa + result = (^a)[0] + +echo p() diff --git a/todo.txt b/todo.txt index d8085226da..20fba45e92 100644 --- a/todo.txt +++ b/todo.txt @@ -1,6 +1,11 @@ version 0.9.6 ============= +- fix bug #1320 +- fix tflowvar codegen test +- split idetools into separate tool +- split docgen into separate tool +- .benign pragma - scopes are still broken for generic instantiation! - implicit deref for parameter matching diff --git a/web/news.txt b/web/news.txt index 2d7086be6d..3b48140e5a 100644 --- a/web/news.txt +++ b/web/news.txt @@ -29,6 +29,8 @@ News - ``--threadanalysis:on`` is now the default. To make your program compile you can disable it but this is only a temporary solution as this option will disappear soon! + - ``system.fileHandle`` has been renamed to ``system.getFileHandle`` to + prevent name conflicts with the new type ``FileHandle``. Language Additions diff --git a/web/question.txt b/web/question.txt index be90cc67a9..e6f4d40a54 100644 --- a/web/question.txt +++ b/web/question.txt @@ -31,8 +31,8 @@ runtime or interpreter. What have been the major influences in the language's design? ------------------------------------------------------------- -The language borrows heavily from: Modula 3, Delphi, Ada, C++, Python, Lisp, -Oberon. As far as possible the list is sorted by the impact of influence. +The language borrows heavily from (in order of impact): Modula 3, Delphi, Ada, +C++, Python, Lisp, Oberon.