diff options
47 files changed, 578 insertions, 343 deletions
diff --git a/compiler/ast.nim b/compiler/ast.nim index cd002eef1..fe724f4dd 100644 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -409,7 +409,9 @@ type # efficiency nfTransf, # node has been transformed nfSem # node has been checked for semantics - nfDelegate # the call can use a delegator + nfDotField # the call can use a dot operator + nfDotSetter # the call can use a setter dot operarator + nfExplicitCall # x.y() was used instead of x.y nfExprCall # this is an attempt to call a regular expression nfIsRef # this node is a 'ref' node; used for the VM @@ -843,7 +845,8 @@ const ExportableSymKinds* = {skVar, skConst, skProc, skMethod, skType, skIterator, skMacro, skTemplate, skConverter, skEnumField, skLet, skStub} PersistentNodeFlags*: TNodeFlags = {nfBase2, nfBase8, nfBase16, - nfAllConst, nfDelegate, nfIsRef} + nfDotSetter, nfDotField, + nfAllConst,nfIsRef} namePos* = 0 patternPos* = 1 # empty except for term rewriting macros genericParamsPos* = 2 @@ -1044,6 +1047,10 @@ proc newStrNode(kind: TNodeKind, strVal: string): PNode = result = newNode(kind) result.strVal = strVal +proc withInfo*(n: PNode, info: TLineInfo): PNode = + n.info = info + return n + proc newIdentNode(ident: PIdent, info: TLineInfo): PNode = result = newNode(nkIdent) result.ident = ident diff --git a/compiler/c2nim/cparse.nim b/compiler/c2nim/cparse.nim index ffab05788..e4abe11a0 100644 --- a/compiler/c2nim/cparse.nim +++ b/compiler/c2nim/cparse.nim @@ -540,7 +540,7 @@ proc typeAtom(p: var TParser): PNode = if p.tok.s == "unsigned": isUnsigned = true elif p.tok.s == "signed" or p.tok.s == "int": - nil + discard else: add(x, p.tok.s) getTok(p, nil) @@ -746,7 +746,7 @@ proc directDeclarator(p: var TParser, a: PNode, ident: ptr PNode): PNode = result = declarator(p, a, ident) eat(p, pxParRi, result) else: - nil + discard return parseTypeSuffix(p, a) proc declarator(p: var TParser, a: PNode, ident: ptr PNode): PNode = @@ -1165,7 +1165,7 @@ proc enumSpecifier(p: var TParser): PNode = proc setBaseFlags(n: PNode, base: TNumericalBase) = case base - of base10: nil + of base10: discard of base2: incl(n.flags, nfBase2) of base8: incl(n.flags, nfBase8) of base16: incl(n.flags, nfBase16) @@ -1686,7 +1686,7 @@ proc switchStatement(p: var TParser): PNode = break of "case", "default": break - else: nil + else: discard addSon(result, statement(p)) if sonsLen(result) == 0: # translate empty statement list to Nimrod's ``nil`` statement diff --git a/compiler/c2nim/cpp.nim b/compiler/c2nim/cpp.nim index 1707b75db..84b4c4dfb 100644 --- a/compiler/c2nim/cpp.nim +++ b/compiler/c2nim/cpp.nim @@ -103,7 +103,7 @@ proc parseDefBody(p: var TParser, m: var TMacro, params: seq[string]) = m.body.add(tok) of pxDirConc: # just ignore this token: this implements token merging correctly - nil + discard else: m.body.add(p.tok) # we do not want macro expansion here: @@ -166,7 +166,7 @@ proc parseStmtList(p: var TParser): PNode = of pxDirectiveParLe, pxDirective: case p.tok.s of "else", "endif", "elif": break - else: nil + else: discard addSon(result, statement(p)) proc eatEndif(p: var TParser) = diff --git a/compiler/ccgstmts.nim b/compiler/ccgstmts.nim index af0d657f1..443d845f6 100644 --- a/compiler/ccgstmts.nim +++ b/compiler/ccgstmts.nim @@ -65,6 +65,7 @@ proc startBlock(p: BProc, start: TFormatStr = "{$n", setLen(p.blocks, result + 1) p.blocks[result].id = p.labels p.blocks[result].nestedTryStmts = p.nestedTryStmts.len.int16 + p.blocks[result].nestedExceptStmts = p.inExceptBlock.int16 proc assignLabel(b: var TBlock): PRope {.inline.} = b.label = con("LA", b.id.toRope) @@ -260,14 +261,22 @@ proc genIf(p: BProc, n: PNode, d: var TLoc) = else: internalError(n.info, "genIf()") if sonsLen(n) > 1: fixLabel(p, lend) -proc blockLeaveActions(p: BProc, howMany: int) = - var L = p.nestedTryStmts.len + +proc blockLeaveActions(p: BProc, howManyTrys, howManyExcepts: int) = + # This is called by return and break stmts. + # When jumping out of try/except/finally stmts, + # we need to pop safe points from try statements, + # execute finally-stmts, and pop exceptions + # from except stmts + + let L = p.nestedTryStmts.len + # danger of endless recursion! we workaround this here by a temp stack var stack: seq[PNode] - newSeq(stack, howMany) - for i in countup(1, howMany): + newSeq(stack, howManyTrys) + for i in countup(1, howManyTrys): stack[i-1] = p.nestedTryStmts[L-i] - setLen(p.nestedTryStmts, L-howMany) + setLen(p.nestedTryStmts, L-howManyTrys) var alreadyPoppedCnt = p.inExceptBlock for tryStmt in items(stack): @@ -276,21 +285,26 @@ proc blockLeaveActions(p: BProc, howMany: int) = dec alreadyPoppedCnt else: linefmt(p, cpsStmts, "#popSafePoint();$n") + # Find finally-stmts for this try-stmt + # and generate a copy of the finally stmts here var finallyStmt = lastSon(tryStmt) if finallyStmt.kind == nkFinally: genStmts(p, finallyStmt.sons[0]) # push old elements again: - for i in countdown(howMany-1, 0): + for i in countdown(howManyTrys-1, 0): p.nestedTryStmts.add(stack[i]) + if gCmd != cmdCompileToCpp: - for i in countdown(p.inExceptBlock-1, 0): + # Pop exceptions that was handled by the + # except-blocks we are in + for i in countdown(howManyExcepts-1, 0): linefmt(p, cpsStmts, "#popCurrentException();$n") proc genReturnStmt(p: BProc, t: PNode) = p.beforeRetNeeded = true genLineDir(p, t) if (t.sons[0].kind != nkEmpty): genStmts(p, t.sons[0]) - blockLeaveActions(p, min(1, p.nestedTryStmts.len)) + blockLeaveActions(p, min(1, p.nestedTryStmts.len), p.inExceptBlock) lineFF(p, cpsStmts, "goto BeforeRet;$n", "br label %BeforeRet$n", []) proc genComputedGoto(p: BProc; n: PNode) = @@ -450,7 +464,9 @@ proc genBreakStmt(p: BProc, t: PNode) = if idx < 0 or not p.blocks[idx].isLoop: internalError(t.info, "no loop to break") let label = assignLabel(p.blocks[idx]) - blockLeaveActions(p, p.nestedTryStmts.len - p.blocks[idx].nestedTryStmts) + blockLeaveActions(p, + p.nestedTryStmts.len - p.blocks[idx].nestedTryStmts, + p.inExceptBlock - p.blocks[idx].nestedExceptStmts) genLineDir(p, t) lineF(p, cpsStmts, "goto $1;$n", [label]) diff --git a/compiler/cgendata.nim b/compiler/cgendata.nim index 0e1148343..71479abdd 100644 --- a/compiler/cgendata.nim +++ b/compiler/cgendata.nim @@ -58,6 +58,7 @@ type sections*: TCProcSections # the code beloging isLoop*: bool # whether block is a loop nestedTryStmts*: int16 # how many try statements is it nested into + nestedExceptStmts*: int16 # how many except statements is it nested into frameLen*: int16 TCProc{.final.} = object # represents C proc that is currently generated diff --git a/compiler/docgen.nim b/compiler/docgen.nim index 343f415b3..c05b55184 100644 --- a/compiler/docgen.nim +++ b/compiler/docgen.nim @@ -42,17 +42,23 @@ proc compilerMsgHandler(filename: string, line, col: int, of mwUnsupportedLanguage: k = warnLanguageXNotSupported globalError(newLineInfo(filename, line, col), k, arg) +proc docgenFindFile(s: string): string {.procvar.} = + result = options.findFile(s) + if result.len == 0: + result = getCurrentDir() / s + if not existsFile(result): result = "" + proc parseRst(text, filename: string, line, column: int, hasToc: var bool, rstOptions: TRstParseOptions): PRstNode = result = rstParse(text, filename, line, column, hasToc, rstOptions, - options.findFile, compilerMsgHandler) + docgenFindFile, compilerMsgHandler) proc newDocumentor*(filename: string, config: PStringTable): PDoc = new(result) initRstGenerator(result[], (if gCmd != cmdRst2tex: outHtml else: outLatex), options.gConfigVars, filename, {roSupportRawDirective}, - options.findFile, compilerMsgHandler) + docgenFindFile, compilerMsgHandler) result.id = 100 proc dispA(dest: var PRope, xml, tex: string, args: openArray[PRope]) = diff --git a/compiler/parser.nim b/compiler/parser.nim index ff3324b47..5a5bfb574 100644 --- a/compiler/parser.nim +++ b/compiler/parser.nim @@ -281,7 +281,7 @@ proc parseSymbol(p: var TParser): PNode = add(result, newIdentNodeP(getIdent"{}", p)) getTok(p) eat(p, tkCurlyRi) - of tokKeywordLow..tokKeywordHigh, tkSymbol, tkOpr, tkDotDot: + of tokKeywordLow..tokKeywordHigh, tkSymbol, tkOpr, tkDot, tkDotDot: add(result, newIdentNodeP(p.tok.ident, p)) getTok(p) of tkIntLit..tkCharLit: diff --git a/compiler/pas2nim/paslex.nim b/compiler/pas2nim/paslex.nim index 67473e71f..f24b0c420 100644 --- a/compiler/pas2nim/paslex.nim +++ b/compiler/pas2nim/paslex.nim @@ -342,7 +342,7 @@ proc getSymbol(L: var TLexer, tok: var TToken) = h = h +% ord(c) h = h +% h shl 10 h = h xor (h shr 6) - of '_': nil + of '_': discard else: break inc(pos) h = h +% h shl 3 diff --git a/compiler/pas2nim/pasparse.nim b/compiler/pas2nim/pasparse.nim index 928896338..a6f8363f6 100644 --- a/compiler/pas2nim/pasparse.nim +++ b/compiler/pas2nim/pasparse.nim @@ -335,7 +335,7 @@ proc exprColonEqExprList(p: var TParser, kind, elemKind: TNodeKind, proc setBaseFlags(n: PNode, base: TNumericalBase) = case base - of base10: nil + of base10: discard of base2: incl(n.flags, nfBase2) of base8: incl(n.flags, nfBase8) of base16: incl(n.flags, nfBase16) @@ -466,7 +466,7 @@ proc lowestExprAux(p: var TParser, v: var PNode, limit: int): TTokKind = eat(p, pxCurlyDirRi) opNode.ident = getIdent("&") else: - nil + discard of pxMinus: if p.tok.xkind == pxPer: getTok(p) @@ -477,7 +477,7 @@ proc lowestExprAux(p: var TParser, v: var PNode, limit: int): TTokKind = of pxNeq: opNode.ident = getIdent("!=") else: - nil + discard skipCom(p, opNode) # read sub-expression with higher priority nextop = lowestExprAux(p, v2, opPred) addSon(node, opNode) @@ -505,7 +505,7 @@ proc fixExpr(n: PNode): PNode = (n.sons[2].kind in {nkCharLit, nkStrLit}): n.sons[0].ident = getIdent("&") # fix operator else: - nil + discard if not (n.kind in {nkEmpty..nkNilLit}): for i in countup(0, sonsLen(n) - 1): result.sons[i] = fixExpr(n.sons[i]) @@ -603,7 +603,7 @@ proc parseStmtList(p: var TParser): PNode = of pxCurlyDirLe, pxStarDirLe: if not isHandledDirective(p): break else: - nil + discard addSon(result, parseStmt(p)) if sonsLen(result) == 1: result = result.sons[0] @@ -732,7 +732,7 @@ proc parseRepeat(p: var TParser): PNode = addSon(b, c) addSon(a, b) if b.sons[0].kind == nkIdent and b.sons[0].ident.id == getIdent("false").id: - nil + discard else: addSon(s, a) addSon(result, s) @@ -840,7 +840,7 @@ proc parseParam(p: var TParser): PNode = getTok(p) v = newNodeP(nkVarTy, p) else: - nil + discard while true: case p.tok.xkind of pxSymbol: a = createIdentNodeP(p.tok.ident, p) @@ -1133,7 +1133,7 @@ proc parseRecordPart(p: var TParser): PNode = proc exSymbol(n: var PNode) = case n.kind of nkPostfix: - nil + discard of nkPragmaExpr: exSymbol(n.sons[0]) of nkIdent, nkAccQuoted: @@ -1154,7 +1154,7 @@ proc fixRecordDef(n: var PNode) = for i in countup(0, sonsLen(n) - 1): fixRecordDef(n.sons[i]) of nkIdentDefs: for i in countup(0, sonsLen(n) - 3): exSymbol(n.sons[i]) - of nkNilLit, nkEmpty: nil + of nkNilLit, nkEmpty: discard else: internalError(n.info, "fixRecordDef(): " & $n.kind) proc addPragmaToIdent(ident: var PNode, pragma: PNode) = @@ -1191,7 +1191,7 @@ proc parseRecordBody(p: var TParser, result, definition: PNode) = if definition != nil: addPragmaToIdent(definition.sons[0], parseCommand(p)) else: internalError(result.info, "anonymous record is not supported") else: - nil + discard opt(p, pxSemicolon) skipCom(p, result) @@ -1399,7 +1399,7 @@ proc fixVarSection(p: var TParser, counter: PNode) = proc exSymbols(n: PNode) = case n.kind - of nkEmpty..nkNilLit: nil + of nkEmpty..nkNilLit: discard of nkProcDef..nkIteratorDef: exSymbol(n.sons[namePos]) of nkWhenStmt, nkStmtList: for i in countup(0, sonsLen(n) - 1): exSymbols(n.sons[i]) @@ -1410,7 +1410,7 @@ proc exSymbols(n: PNode) = exSymbol(n.sons[i].sons[0]) if n.sons[i].sons[2].kind == nkObjectTy: fixRecordDef(n.sons[i].sons[2]) - else: nil + else: discard proc parseBegin(p: var TParser, result: PNode) = getTok(p) diff --git a/compiler/semcall.nim b/compiler/semcall.nim index 6b19dc359..0cd27a443 100644 --- a/compiler/semcall.nim +++ b/compiler/semcall.nim @@ -82,7 +82,7 @@ proc notFoundError*(c: PContext, n: PNode, errors: seq[string]) = # fail fast: globalError(n.info, errTypeMismatch, "") var result = msgKindToString(errTypeMismatch) - add(result, describeArgs(c, n, 1 + ord(nfDelegate in n.flags))) + add(result, describeArgs(c, n, 1 + ord(nfDotField in n.flags))) add(result, ')') var candidates = "" @@ -138,17 +138,35 @@ proc resolveOverloads(c: PContext, n, orig: PNode, let overloadsState = result.state if overloadsState != csMatch: - if nfDelegate in n.flags: - internalAssert f.kind == nkIdent - let calleeName = newStrNode(nkStrLit, f.ident.s) - calleeName.info = n.info + if nfDotField in n.flags: + internalAssert f.kind == nkIdent and n.sonsLen >= 2 + let calleeName = newStrNode(nkStrLit, f.ident.s).withInfo(n.info) - let callOp = newIdentNode(idDelegator, n.info) - n.sons[0..0] = [callOp, calleeName] - orig.sons[0..0] = [callOp, calleeName] - - pickBest(callOp) + # leave the op head symbol empty, + # we are going to try multiple variants + n.sons[0..1] = [nil, n[1], calleeName] + orig.sons[0..1] = [nil, orig[1], calleeName] + + template tryOp(x) = + let op = newIdentNode(getIdent(x), n.info) + n.sons[0] = op + orig.sons[0] = op + pickBest(op) + + if nfExplicitCall in n.flags: + tryOp ".()" + + if result.state in {csEmpty, csNoMatch}: + tryOp "." + elif nfDotSetter in n.flags: + internalAssert f.kind == nkIdent and n.sonsLen == 3 + let calleeName = newStrNode(nkStrLit, f.ident.s[0.. -2]).withInfo(n.info) + let callOp = newIdentNode(getIdent".=", n.info) + n.sons[0..1] = [callOp, n[1], calleeName] + orig.sons[0..1] = [callOp, orig[1], calleeName] + pickBest(callOp) + if overloadsState == csEmpty and result.state == csEmpty: localError(n.info, errUndeclaredIdentifier, considerAcc(f).s) return diff --git a/compiler/semdata.nim b/compiler/semdata.nim index 0bc52d6b7..234526054 100644 --- a/compiler/semdata.nim +++ b/compiler/semdata.nim @@ -213,7 +213,6 @@ proc makeTypeDesc*(c: PContext, typ: PType): PType = proc makeTypeSymNode*(c: PContext, typ: PType, info: TLineInfo): PNode = let typedesc = makeTypeDesc(c, typ) - rawAddSon(typedesc, newTypeS(tyNone, c)) let sym = newSym(skType, idAnon, getCurrOwner(), info).linkTo(typedesc) return newSymNode(sym, info) diff --git a/compiler/semdestruct.nim b/compiler/semdestruct.nim index fb05826cb..791bef823 100644 --- a/compiler/semdestruct.nim +++ b/compiler/semdestruct.nim @@ -55,7 +55,9 @@ proc doDestructorStuff(c: PContext, s: PSym, n: PNode) = useSym(destructableT.destructor), n.sons[paramsPos][1][0]])) -proc destroyField(c: PContext, field: PSym, holder: PNode): PNode = +proc destroyFieldOrFields(c: PContext, field: PNode, holder: PNode): PNode + +proc destroySym(c: PContext, field: PSym, holder: PNode): PNode = let destructableT = instantiateDestructor(c, field.typ) if destructableT != nil: result = newNode(nkCall, field.info, @[ @@ -70,56 +72,49 @@ proc destroyCase(c: PContext, n: PNode, holder: PNode): PNode = for i in countup(1, n.len - 1): # of A, B: var caseBranch = newNode(n[i].kind, n[i].info, n[i].sons[0 .. -2]) - let recList = n[i].lastSon - var destroyRecList = newNode(nkStmtList, n[i].info, @[]) - template addField(f: expr): stmt = - let stmt = destroyField(c, f, holder) - if stmt != nil: - destroyRecList.addSon(stmt) - inc nonTrivialFields - - case recList.kind - of nkSym: - addField(recList.sym) - of nkRecList: - for j in countup(0, recList.len - 1): - addField(recList[j].sym) + + let stmt = destroyFieldOrFields(c, n[i].lastSon, holder) + if stmt == nil: + caseBranch.addSon(newNode(nkStmtList, n[i].info, @[])) else: - internalAssert false - - caseBranch.addSon(destroyRecList) + caseBranch.addSon(stmt) + nonTrivialFields += stmt.len + result.addSon(caseBranch) + # maybe no fields were destroyed? if nonTrivialFields == 0: result = nil - + +proc destroyFieldOrFields(c: PContext, field: PNode, holder: PNode): PNode = + template maybeAddLine(e: expr): stmt = + let stmt = e + if stmt != nil: + if result == nil: result = newNode(nkStmtList) + result.addSon(stmt) + + case field.kind + of nkRecCase: + maybeAddLine destroyCase(c, field, holder) + of nkSym: + maybeAddLine destroySym(c, field.sym, holder) + of nkRecList: + for son in field: + maybeAddLine destroyFieldOrFields(c, son, holder) + else: + internalAssert false + proc generateDestructor(c: PContext, t: PType): PNode = ## generate a destructor for a user-defined object or tuple type ## returns nil if the destructor turns out to be trivial - template addLine(e: expr): stmt = - if result == nil: result = newNode(nkStmtList) - result.addSon(e) - # XXX: This may be true for some C-imported types such as # Tposix_spawnattr if t.n == nil or t.n.sons == nil: return internalAssert t.n.kind == nkRecList let destructedObj = newIdentNode(destructorParam, unknownLineInfo()) # call the destructods of all fields - for s in countup(0, t.n.sons.len - 1): - case t.n.sons[s].kind - of nkRecCase: - let stmt = destroyCase(c, t.n.sons[s], destructedObj) - if stmt != nil: addLine(stmt) - of nkSym: - let stmt = destroyField(c, t.n.sons[s].sym, destructedObj) - if stmt != nil: addLine(stmt) - else: - # XXX just skip it for now so that the compiler doesn't crash, but - # please zahary fix it! arbitrary nesting of nkRecList/nkRecCase is - # possible. Any thread example seems to trigger this. - discard + result = destroyFieldOrFields(c, t.n, destructedObj) # base classes' destructors will be automatically called by # semProcAux for both auto-generated and user-defined destructors diff --git a/compiler/semexprs.nim b/compiler/semexprs.nim index 3fe1367ec..f09ee1295 100644 --- a/compiler/semexprs.nim +++ b/compiler/semexprs.nim @@ -346,22 +346,21 @@ proc semIs(c: PContext, n: PNode): PNode = result = n n.typ = getSysType(tyBool) - - n.sons[1] = semExprWithType(c, n[1], {efDetermineType}) - + + n.sons[1] = semExprWithType(c, n[1], {efDetermineType, efWantIterator}) if n[2].kind notin {nkStrLit..nkTripleStrLit}: let t2 = semTypeNode(c, n[2], nil) n.sons[2] = newNodeIT(nkType, n[2].info, t2) - if n[1].typ.kind != tyTypeDesc: - n.sons[1] = makeTypeSymNode(c, n[1].typ, n[1].info) - elif n[1].typ.sonsLen == 0: + let lhsType = n[1].typ + if lhsType.kind != tyTypeDesc: + n.sons[1] = makeTypeSymNode(c, lhsType, n[1].info) + elif lhsType.base.kind == tyNone: # this is a typedesc variable, leave for evals return - let t1 = n[1].typ.sons[0] # BUGFIX: don't evaluate this too early: ``T is void`` - if not containsGenericType(t1): result = isOpImpl(c, n) + if not n[1].typ.base.containsGenericType: result = isOpImpl(c, n) proc semOpAux(c: PContext, n: PNode) = const flags = {efDetermineType} @@ -683,20 +682,21 @@ proc semOverloadedCallAnalyseEffects(c: PContext, n: PNode, nOrig: PNode, incl(c.p.owner.flags, sfSideEffect) proc semObjConstr(c: PContext, n: PNode, flags: TExprFlags): PNode -proc semIndirectOp(c: PContext, n: PNode, flags: TExprFlags): PNode = +proc semIndirectOp(c: PContext, n: PNode, flags: TExprFlags): PNode = result = nil checkMinSonsLen(n, 1) var prc = n.sons[0] - if n.sons[0].kind == nkDotExpr: + if n.sons[0].kind == nkDotExpr: checkSonsLen(n.sons[0], 2) n.sons[0] = semFieldAccess(c, n.sons[0]) - if n.sons[0].kind == nkDotCall: + if n.sons[0].kind == nkDotCall: # it is a static call! result = n.sons[0] result.kind = nkCall + result.flags.incl nfExplicitCall for i in countup(1, sonsLen(n) - 1): addSon(result, n.sons[i]) return semExpr(c, result, flags) - else: + else: n.sons[0] = semExpr(c, n.sons[0]) let nOrig = n.copyTree semOpAux(c, n) @@ -917,8 +917,8 @@ proc builtinFieldAccess(c: PContext, n: PNode, flags: TExprFlags): PNode = var ty = n.sons[0].typ var f: PSym = nil result = nil - if isTypeExpr(n.sons[0]) or ty.kind == tyTypeDesc and ty.len == 1: - if ty.kind == tyTypeDesc: ty = ty.sons[0] + if isTypeExpr(n.sons[0]) or ty.kind == tyTypeDesc and ty.base.kind != tyNone: + if ty.kind == tyTypeDesc: ty = ty.base case ty.kind of tyEnum: # look up if the identifier belongs to the enum: @@ -999,7 +999,7 @@ proc dotTransformation(c: PContext, n: PNode): PNode = else: var i = considerAcc(n.sons[1]) result = newNodeI(nkDotCall, n.info) - result.flags.incl nfDelegate + result.flags.incl nfDotField addSon(result, newIdentNode(i, n[1].info)) addSon(result, copyTree(n[0])) @@ -1082,12 +1082,13 @@ proc semArrayAccess(c: PContext, n: PNode, flags: TExprFlags): PNode = proc propertyWriteAccess(c: PContext, n, nOrig, a: PNode): PNode = var id = considerAcc(a[1]) - let setterId = newIdentNode(getIdent(id.s & '='), n.info) + var setterId = newIdentNode(getIdent(id.s & '='), n.info) # a[0] is already checked for semantics, that does ``builtinFieldAccess`` # this is ugly. XXX Semantic checking should use the ``nfSem`` flag for # nodes? let aOrig = nOrig[0] result = newNode(nkCall, n.info, sons = @[setterId, a[0], semExpr(c, n[1])]) + result.flags.incl nfDotSetter let orig = newNode(nkCall, n.info, sons = @[setterId, aOrig[0], nOrig[1]]) result = semOverloadedCallAnalyseEffects(c, result, orig, {}) @@ -1777,22 +1778,6 @@ proc semBlock(c: PContext, n: PNode): PNode = closeScope(c) dec(c.p.nestedBlockCounter) -proc buildCall(n: PNode): PNode = - if n.kind == nkDotExpr and n.len == 2: - # x.y --> y(x) - result = newNodeI(nkCall, n.info, 2) - result.sons[0] = n.sons[1] - result.sons[1] = n.sons[0] - elif n.kind in nkCallKinds and n.sons[0].kind == nkDotExpr: - # x.y(a) -> y(x, a) - let a = n.sons[0] - result = newNodeI(nkCall, n.info, n.len+1) - result.sons[0] = a.sons[1] - result.sons[1] = a.sons[0] - for i in 1 .. <n.len: result.sons[i+1] = n.sons[i] - else: - result = n - proc doBlockIsStmtList(n: PNode): bool = result = n.kind == nkDo and n[paramsPos].sonsLen == 1 and @@ -1901,7 +1886,7 @@ proc semExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode = of nkCall, nkInfix, nkPrefix, nkPostfix, nkCommand, nkCallStrLit: # check if it is an expression macro: checkMinSonsLen(n, 1) - let mode = if nfDelegate in n.flags: {} else: {checkUndeclared} + let mode = if nfDotField in n.flags: {} else: {checkUndeclared} var s = qualifiedLookUp(c, n.sons[0], mode) if s != nil: if gCmd == cmdPretty and n.sons[0].kind == nkDotExpr: @@ -1940,7 +1925,7 @@ proc semExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode = # the 'newSeq[T](x)' bug setGenericParams(c, n.sons[0]) result = semDirectOp(c, n, flags) - elif isSymChoice(n.sons[0]) or nfDelegate in n.flags: + elif isSymChoice(n.sons[0]) or nfDotField in n.flags: result = semDirectOp(c, n, flags) else: result = semIndirectOp(c, n, flags) diff --git a/compiler/sempass2.nim b/compiler/sempass2.nim index fedf19c79..a00325277 100644 --- a/compiler/sempass2.nim +++ b/compiler/sempass2.nim @@ -476,7 +476,6 @@ proc track(tracked: PEffects, n: PNode) = if warnProveField in gNotes: checkFieldAccess(tracked.guards, n) of nkTryStmt: trackTryStmt(tracked, n) of nkPragma: trackPragmaStmt(tracked, n) - of nkMacroDef, nkTemplateDef: discard of nkAsgn, nkFastAsgn: track(tracked, n.sons[1]) initVar(tracked, n.sons[0]) @@ -526,7 +525,9 @@ proc track(tracked: PEffects, n: PNode) = if sfDiscriminant in x.sons[0].sym.flags: addDiscriminantFact(tracked.guards, x) setLen(tracked.guards, oldFacts) - of nkTypeSection: discard + of nkTypeSection, nkProcDef, nkConverterDef, nkMethodDef, nkIteratorDef, + nkMacroDef, nkTemplateDef: + discard else: for i in 0 .. <safeLen(n): track(tracked, n.sons[i]) @@ -623,6 +624,9 @@ proc trackProc*(s: PSym, body: PNode) = effects.sons[tagEffects] = tagsSpec proc trackTopLevelStmt*(module: PSym; n: PNode) = + if n.kind in {nkPragma, nkMacroDef, nkTemplateDef, nkProcDef, + nkTypeSection, nkConverterDef, nkMethodDef, nkIteratorDef}: + return var effects = newNode(nkEffectList, n.info) var t: TEffects initEffects(effects, module, t) diff --git a/compiler/semtypes.nim b/compiler/semtypes.nim index 44e414e9c..184aca4f8 100644 --- a/compiler/semtypes.nim +++ b/compiler/semtypes.nim @@ -1030,9 +1030,8 @@ proc semTypeNode(c: PContext, n: PNode, prev: PType): PType = if s.kind != skError: localError(n.info, errTypeExpected) result = newOrPrevType(tyError, prev, c) elif s.kind == skParam and s.typ.kind == tyTypeDesc: - assert s.typ.len > 0 - internalAssert prev == nil - result = s.typ.sons[0] + internalAssert s.typ.base.kind != tyNone and prev == nil + result = s.typ.base elif prev == nil: result = s.typ else: diff --git a/compiler/sigmatch.nim b/compiler/sigmatch.nim index 227228f6e..fce0bdf48 100644 --- a/compiler/sigmatch.nim +++ b/compiler/sigmatch.nim @@ -866,7 +866,7 @@ proc typeRel(c: var TCandidate, f, aOrig: PType, doBind = true): TTypeRelation = else: internalAssert a.sons != nil and a.sons.len > 0 c.typedescMatched = true - result = typeRel(c, f.sons[0], a.sons[0]) + result = typeRel(c, f.base, a.base) else: result = isNone else: @@ -896,22 +896,20 @@ proc typeRel(c: var TCandidate, f, aOrig: PType, doBind = true): TTypeRelation = result = isNone of tyTypeDesc: + if a.kind != tyTypeDesc: return isNone + var prev = PType(idTableGet(c.bindings, f)) if prev == nil: - if a.kind == tyTypeDesc: - if f.sons[0].kind == tyNone: - result = isGeneric - else: - result = typeRel(c, f.sons[0], a.sons[0]) - if result != isNone: - put(c.bindings, f, a) + if f.base.kind == tyNone: + result = isGeneric else: - result = isNone + result = typeRel(c, f.base, a.base) + if result != isNone: + put(c.bindings, f, a) else: - internalAssert prev.sonsLen == 1 let toMatch = if tfUnresolved in f.flags: a - else: a.sons[0] - result = typeRel(c, prev.sons[0], toMatch) + else: a.base + result = typeRel(c, prev.base, toMatch) of tyStmt: result = isGeneric @@ -1015,7 +1013,7 @@ proc paramTypesMatchAux(m: var TCandidate, f, argType: PType, argType = arg.typ var - a = if c.inTypeClass > 0: argType.skipTypes({tyTypeDesc}) + a = if c.inTypeClass > 0: argType.skipTypes({tyTypeDesc, tyFieldAccessor}) else: argType r = typeRel(m, f, a) diff --git a/compiler/types.nim b/compiler/types.nim index db75cd3c0..55a89920a 100644 --- a/compiler/types.nim +++ b/compiler/types.nim @@ -431,8 +431,8 @@ proc typeToString(typ: PType, prefer: TPreferedDesc = preferName): string = add(result, typeToString(t.sons[i])) add(result, ']') of tyTypeDesc: - if t.len == 0: result = "typedesc" - else: result = "typedesc[" & typeToString(t.sons[0]) & "]" + if t.base.kind == tyNone: result = "typedesc" + else: result = "typedesc[" & typeToString(t.base) & "]" of tyStatic: internalAssert t.len > 0 result = "static[" & typeToString(t.sons[0]) & "]" @@ -857,7 +857,7 @@ proc sameTypeAux(x, y: PType, c: var TSameTypeClosure): bool = if a.kind != b.kind: return false of dcEqOrDistinctOf: while a.kind == tyDistinct: a = a.sons[0] - if a.kind != b.kind: return false + if a.kind != b.kind: return false case a.kind of tyEmpty, tyChar, tyBool, tyNil, tyPointer, tyString, tyCString, tyInt..tyBigNum, tyStmt, tyExpr: @@ -1231,8 +1231,7 @@ proc computeSizeAux(typ: PType, a: var BiggestInt): BiggestInt = of tyGenericInst, tyDistinct, tyGenericBody, tyMutable, tyConst, tyIter: result = computeSizeAux(lastSon(typ), a) of tyTypeDesc: - result = if typ.len == 1: computeSizeAux(typ.sons[0], a) - else: szUnknownSize + result = computeSizeAux(typ.base, a) of tyForward: return szIllegalRecursion else: #internalError("computeSizeAux()") @@ -1258,7 +1257,7 @@ proc containsGenericTypeIter(t: PType, closure: PObject): bool = return true if t.kind == tyTypeDesc: - if t.sons[0].kind == tyNone: return true + if t.base.kind == tyNone: return true if containsGenericTypeIter(t.base, closure): return true return false diff --git a/doc/manual.txt b/doc/manual.txt index fb357f7d3..53817c508 100644 --- a/doc/manual.txt +++ b/doc/manual.txt @@ -4106,6 +4106,59 @@ types that will match the typedesc param: The constraint can be a concrete type or a type class. +Special Operators +================= + +dot operators +------------- + +Nimrod 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 +Nimrod's 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 +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 +an additional static string parameter: + +.. code-block:: nimrod + a.b # becomes `.`(a, "b") + a.b(c, d) # becomes `.`(a, "b", c, d) + +The matched dot operators can be symbols of any callable kind (procs, +templates and macros), depending on the desired effect: + +.. code-block:: nimrod + proc `.` (js: PJsonNode, field: string): JSON = js[field] + + var js = parseJson("{ x: 1, y: 2}") + echo js.x # outputs 1 + echo js.y # outputs 2 + +The following dot operators are available: + +operator `.` +------------ +This operator will be matched against both field accesses and method calls. + +operator `.()` +--------------- +This operator will be matched exclusively against method calls. It has higher +precedence than the `.` operator and this allows you to handle expressions like +`x.y` and `x.y()` differently if you are interfacing with a scripting language +for example. + +operator `.=` +------------- +This operator will be matched against assignments to missing fields. + +.. code-block:: nimrod + a.b = c # becomes `.=`(a, "b", c) + Term rewriting macros ===================== @@ -4758,42 +4811,6 @@ This may change in future versions of language, but for now use the ``finalizer`` parameter to ``new``. -delegator pragma ----------------- - -**Note**: The design of the delegator feature is subject to change. - -The delegator pragma can be used to intercept and rewrite proc call and field -access attempts referring to previously undeclared symbol names. It can be used -to provide a fluent interface to objects lying outside the static confines of -the Nimrod's type system such as values from dynamic scripting languages or -dynamic file formats such as JSON or XML. - -A delegator is a special form of the `()` operator marked with the delagator -pragma. When Nimrod encounters an expression that cannot be resolved by the -standard overload resolution, any delegators in the current scope will be -matched against a rewritten form of the expression following the standard -signature matching rules. In the rewritten expression, the name of the unknown -proc or field name is inserted as an additional static string parameter always -appearing in the leading position: - -.. code-block:: nimrod - a.b => delegator("b", a) - a.b(c, d) => delegator("b", a, c) - a b, c, d => delegator("a", b, c, d) - - -The delegators can be any callable symbol type (procs, templates, macros) -depending on the desired effect: - -.. code-block:: nimrod - proc `()` (field: string, js: PJsonNode): JSON {.delegator.} = js[field] - - var js = parseJson("{ x: 1, y: 2}") - echo js.x # outputs 1 - echo js.y # outputs 2 - - procvar pragma -------------- The `procvar`:idx: pragma is used to mark a proc that it can be passed to a diff --git a/examples/htmlrefs.nim b/examples/htmlrefs.nim index 824c1d8c7..8b668325f 100644 --- a/examples/htmlrefs.nim +++ b/examples/htmlrefs.nim @@ -36,7 +36,7 @@ block mainLoop: case x.kind of xmlEof: break mainLoop of xmlElementClose: break - else: nil + else: discard x.next() # skip ``xmlElementClose`` # now we have the description for the ``a`` element var desc = "" diff --git a/koch.nim b/koch.nim index dcb66ae3e..ce01d36a5 100644 --- a/koch.nim +++ b/koch.nim @@ -104,9 +104,8 @@ proc install(args: string) = exec("sh ./install.sh $#" % args) proc web(args: string) = - exec(("$# cc -r tools/nimweb.nim web/nimrod --putenv:nimrodversion=$#" & - " --path:$#") % [findNim(), NimrodVersion, - getCurrentDir().quoteIfContainsWhite]) + exec("$# cc -r tools/nimweb.nim web/nimrod --putenv:nimrodversion=$#" % + [findNim(), NimrodVersion]) # -------------- boot --------------------------------------------------------- diff --git a/lib/pure/times.nim b/lib/pure/times.nim index de6c4e4fa..2fce235e2 100644 --- a/lib/pure/times.nim +++ b/lib/pure/times.nim @@ -557,6 +557,119 @@ proc `$`*(m: TMonth): string = "November", "December"] return lookup[m] +proc format_token(info: TTimeInfo, token: string, buf: var string) = + ## Helper of the format proc to parse individual tokens. + ## + ## Pass the found token in the user input string, and the buffer where the + ## final string is being built. This has to be a var value because certain + ## formatting tokens require modifying the previous characters. + case token + of "d": + buf.add($info.monthday) + of "dd": + if info.monthday < 10: + buf.add("0") + buf.add($info.monthday) + of "ddd": + buf.add(($info.weekday)[0 .. 2]) + of "dddd": + buf.add($info.weekday) + of "h": + buf.add($(if info.hour > 12: info.hour - 12 else: info.hour)) + of "hh": + let amerHour = if info.hour > 12: info.hour - 12 else: info.hour + if amerHour < 10: + buf.add('0') + buf.add($amerHour) + of "H": + buf.add($info.hour) + of "HH": + if info.hour < 10: + buf.add('0') + buf.add($info.hour) + of "m": + buf.add($info.minute) + of "mm": + if info.minute < 10: + buf.add('0') + buf.add($info.minute) + of "M": + buf.add($(int(info.month)+1)) + of "MM": + if info.month < mOct: + buf.add('0') + buf.add($(int(info.month)+1)) + of "MMM": + buf.add(($info.month)[0..2]) + of "MMMM": + buf.add($info.month) + of "s": + buf.add($info.second) + of "ss": + if info.second < 10: + buf.add('0') + buf.add($info.second) + of "t": + if info.hour >= 12: + buf.add('P') + else: buf.add('A') + of "tt": + if info.hour >= 12: + buf.add("PM") + else: buf.add("AM") + of "y": + var fr = ($info.year).len()-1 + if fr < 0: fr = 0 + buf.add(($info.year)[fr .. ($info.year).len()-1]) + of "yy": + var fr = ($info.year).len()-2 + if fr < 0: fr = 0 + var fyear = ($info.year)[fr .. ($info.year).len()-1] + if fyear.len != 2: fyear = repeatChar(2-fyear.len(), '0') & fyear + buf.add(fyear) + of "yyy": + var fr = ($info.year).len()-3 + if fr < 0: fr = 0 + var fyear = ($info.year)[fr .. ($info.year).len()-1] + if fyear.len != 3: fyear = repeatChar(3-fyear.len(), '0') & fyear + buf.add(fyear) + of "yyyy": + var fr = ($info.year).len()-4 + if fr < 0: fr = 0 + var fyear = ($info.year)[fr .. ($info.year).len()-1] + if fyear.len != 4: fyear = repeatChar(4-fyear.len(), '0') & fyear + buf.add(fyear) + of "yyyyy": + var fr = ($info.year).len()-5 + if fr < 0: fr = 0 + var fyear = ($info.year)[fr .. ($info.year).len()-1] + if fyear.len != 5: fyear = repeatChar(5-fyear.len(), '0') & fyear + buf.add(fyear) + of "z": + let hrs = (info.timezone div 60) div 60 + buf.add($hrs) + of "zz": + let hrs = (info.timezone div 60) div 60 + + buf.add($hrs) + if hrs.abs < 10: + var atIndex = buf.len-(($hrs).len-(if hrs < 0: 1 else: 0)) + buf.insert("0", atIndex) + of "zzz": + let hrs = (info.timezone div 60) div 60 + + buf.add($hrs & ":00") + if hrs.abs < 10: + var atIndex = buf.len-(($hrs & ":00").len-(if hrs < 0: 1 else: 0)) + buf.insert("0", atIndex) + of "ZZZ": + buf.add(info.tzname) + of "": + discard + else: + raise newException(EInvalidValue, "Invalid format string: " & token) + + proc format*(info: TTimeInfo, f: string): string = ## This function formats `info` as specified by `f`. The following format ## specifiers are available: @@ -591,8 +704,11 @@ proc format*(info: TTimeInfo, f: string): string = ## ZZZ Displays the name of the timezone. ``GMT -> GMT``, ``EST -> EST`` ## ========== ================================================================================= ================================================ ## - ## Other strings can be inserted by putting them in ``''``. For example ``hh'->'mm`` will give ``01->56``. - ## The following characters can be inserted without quoting them: ``:`` ``-`` ``(`` ``)`` ``/`` ``[`` ``]`` ``,`` + ## Other strings can be inserted by putting them in ``''``. For example + ## ``hh'->'mm`` will give ``01->56``. The following characters can be + ## inserted without quoting them: ``:`` ``-`` ``(`` ``)`` ``/`` ``[`` ``]`` + ## ``,``. However you don't need to necessarily separate format specifiers, a + ## unambiguous format string like ``yyyyMMddhhmmss`` is valid too. result = "" var i = 0 @@ -600,112 +716,8 @@ proc format*(info: TTimeInfo, f: string): string = while true: case f[i] of ' ', '-', '/', ':', '\'', '\0', '(', ')', '[', ']', ',': - case currentF - of "d": - result.add($info.monthday) - of "dd": - if info.monthday < 10: - result.add("0") - result.add($info.monthday) - of "ddd": - result.add(($info.weekday)[0 .. 2]) - of "dddd": - result.add($info.weekday) - of "h": - result.add($(if info.hour > 12: info.hour - 12 else: info.hour)) - of "hh": - let amerHour = if info.hour > 12: info.hour - 12 else: info.hour - if amerHour < 10: - result.add('0') - result.add($amerHour) - of "H": - result.add($info.hour) - of "HH": - if info.hour < 10: - result.add('0') - result.add($info.hour) - of "m": - result.add($info.minute) - of "mm": - if info.minute < 10: - result.add('0') - result.add($info.minute) - of "M": - result.add($(int(info.month)+1)) - of "MM": - if info.month < mOct: - result.add('0') - result.add($(int(info.month)+1)) - of "MMM": - result.add(($info.month)[0..2]) - of "MMMM": - result.add($info.month) - of "s": - result.add($info.second) - of "ss": - if info.second < 10: - result.add('0') - result.add($info.second) - of "t": - if info.hour >= 12: - result.add('P') - else: result.add('A') - of "tt": - if info.hour >= 12: - result.add("PM") - else: result.add("AM") - of "y": - var fr = ($info.year).len()-1 - if fr < 0: fr = 0 - result.add(($info.year)[fr .. ($info.year).len()-1]) - of "yy": - var fr = ($info.year).len()-2 - if fr < 0: fr = 0 - var fyear = ($info.year)[fr .. ($info.year).len()-1] - if fyear.len != 2: fyear = repeatChar(2-fyear.len(), '0') & fyear - result.add(fyear) - of "yyy": - var fr = ($info.year).len()-3 - if fr < 0: fr = 0 - var fyear = ($info.year)[fr .. ($info.year).len()-1] - if fyear.len != 3: fyear = repeatChar(3-fyear.len(), '0') & fyear - result.add(fyear) - of "yyyy": - var fr = ($info.year).len()-4 - if fr < 0: fr = 0 - var fyear = ($info.year)[fr .. ($info.year).len()-1] - if fyear.len != 4: fyear = repeatChar(4-fyear.len(), '0') & fyear - result.add(fyear) - of "yyyyy": - var fr = ($info.year).len()-5 - if fr < 0: fr = 0 - var fyear = ($info.year)[fr .. ($info.year).len()-1] - if fyear.len != 5: fyear = repeatChar(5-fyear.len(), '0') & fyear - result.add(fyear) - of "z": - let hrs = (info.timezone div 60) div 60 - result.add($hrs) - of "zz": - let hrs = (info.timezone div 60) div 60 - - result.add($hrs) - if hrs.abs < 10: - var atIndex = result.len-(($hrs).len-(if hrs < 0: 1 else: 0)) - result.insert("0", atIndex) - of "zzz": - let hrs = (info.timezone div 60) div 60 - - result.add($hrs & ":00") - if hrs.abs < 10: - var atIndex = result.len-(($hrs & ":00").len-(if hrs < 0: 1 else: 0)) - result.insert("0", atIndex) - of "ZZZ": - result.add(info.tzname) - of "": - discard - else: - raise newException(EInvalidValue, "Invalid format string: " & currentF) - + format_token(info, currentF, result) + currentF = "" if f[i] == '\0': break @@ -716,7 +728,15 @@ proc format*(info: TTimeInfo, f: string): string = inc(i) else: result.add(f[i]) - else: currentF.add(f[i]) + else: + # Check if the letter being added matches previous accumulated buffer. + if currentF.len < 1 or currentF[high(currentF)] == f[i]: + currentF.add(f[i]) + else: + format_token(info, currentF, result) + dec(i) # Move position back to re-process the character separately. + currentF = "" + inc(i) {.pop.} @@ -727,11 +747,15 @@ when isMainModule: var t = getGMTime(fromSeconds(2147483647)) echo t.format("ddd dd MMM hh:mm:ss ZZZ yyyy") + echo t.format("ddd ddMMMhhmmssZZZyyyy") assert t.format("ddd dd MMM hh:mm:ss ZZZ yyyy") == "Tue 19 Jan 03:14:07 UTC 2038" + assert t.format("ddd ddMMMhh:mm:ssZZZyyyy") == "Tue 19Jan03:14:07UTC2038" assert t.format("d dd ddd dddd h hh H HH m mm M MM MMM MMMM s" & " ss t tt y yy yyy yyyy yyyyy z zz zzz ZZZ") == "19 19 Tue Tuesday 3 03 3 03 14 14 1 01 Jan January 7 07 A AM 8 38 038 2038 02038 0 00 00:00 UTC" + + assert t.format("yyyyMMddhhmmss") == "20380119031407" var t2 = getGMTime(fromSeconds(160070789)) # Mon 27 Jan 16:06:29 GMT 1975 assert t2.format("d dd ddd dddd h hh H HH m mm M MM MMM MMMM s" & diff --git a/tests/ambsym/mambsym1.nim b/tests/ambsym/mambsym1.nim index cf8ac5242..d9d57b5e5 100644 --- a/tests/ambsym/mambsym1.nim +++ b/tests/ambsym/mambsym1.nim @@ -7,4 +7,4 @@ type proc ha() = var x: TExport # no error - nil + discard diff --git a/tests/ambsym/mambsys1.nim b/tests/ambsym/mambsys1.nim index 5472b5ae4..04f9561d3 100644 --- a/tests/ambsym/mambsys1.nim +++ b/tests/ambsym/mambsys1.nim @@ -4,4 +4,4 @@ type TExport* = enum x, y, z proc foo*(x: int) = - nil + discard diff --git a/tests/ambsym/mambsys2.nim b/tests/ambsym/mambsys2.nim index 395425b86..d59706865 100644 --- a/tests/ambsym/mambsys2.nim +++ b/tests/ambsym/mambsys2.nim @@ -1,4 +1,4 @@ type TExport* = enum x, y, z # exactly the same type! -proc foo*(x: int) = nil +proc foo*(x: int) = discard diff --git a/tests/casestmt/tcasestm.nim b/tests/casestmt/tcasestm.nim index 003ec6e50..b033b98ec 100644 --- a/tests/casestmt/tcasestm.nim +++ b/tests/casestmt/tcasestm.nim @@ -19,8 +19,8 @@ of eB, eC: write(stdout, "b or c") case x of "Andreas", "Rumpf": write(stdout, "Hallo Meister!") of "aa", "bb": write(stdout, "Du bist nicht mein Meister") -of "cc", "hash", "when": nil -of "will", "it", "finally", "be", "generated": nil +of "cc", "hash", "when": discard +of "will", "it", "finally", "be", "generated": discard var z = case i of 1..5, 8, 9: "aa" diff --git a/tests/concurrency/tnodeadlocks.nim b/tests/concurrency/tnodeadlocks.nim index 18fdca3e9..3f27e24f6 100644 --- a/tests/concurrency/tnodeadlocks.nim +++ b/tests/concurrency/tnodeadlocks.nim @@ -12,7 +12,7 @@ var thr: array [0..5, TThread[tuple[a, b: int]]] L, M, N: TLock -proc doNothing() = nil +proc doNothing() = discard proc threadFunc(interval: tuple[a, b: int]) {.thread.} = doNothing() diff --git a/tests/destructor/tdestructor.nim b/tests/destructor/tdestructor.nim index bb1410d92..f10c0cc9c 100644 --- a/tests/destructor/tdestructor.nim +++ b/tests/destructor/tdestructor.nim @@ -12,6 +12,13 @@ myobj destroyed ---- mygeneric3 constructed mygeneric1 destroyed +---- +mygeneric1 destroyed +---- +myobj destroyed +---- +---- +myobj destroyed ''' """ @@ -31,6 +38,22 @@ type x: A y: B z: C + + TObjKind = enum A, B, C, D + + TCaseObj = object + case kind: TObjKind + of A: + x: TMyGeneric1[int] + of B, C: + y: TMyObj + else: + case innerKind: TObjKind + of A, B, C: + p: TMyGeneric3[int, float, string] + of D: + q: TMyGeneric3[TMyObj, int, int] + r: string proc destruct(o: var TMyObj) {.destructor.} = if o.p != nil: dealloc o.p @@ -82,3 +105,24 @@ mygeneric2[int](10) echo "----" mygeneric3() +proc caseobj = + block: + echo "----" + var o1 = TCaseObj(kind: A, x: TMyGeneric1[int](x: 10)) + + block: + echo "----" + var o2 = TCaseObj(kind: B, y: open()) + + block: + echo "----" + var o3 = TCaseObj(kind: D, innerKind: B, r: "test", + p: TMyGeneric3[int, float, string](x: 10, y: 1.0, z: "test")) + + block: + echo "----" + var o4 = TCaseObj(kind: D, innerKind: D, r: "test", + q: TMyGeneric3[TMyObj, int, int](x: open(), y: 1, z: 0)) + +caseobj() + diff --git a/tests/destructor/tdictdestruct.nim b/tests/destructor/tdictdestruct.nim index ec1084105..b7043f7b7 100644 --- a/tests/destructor/tdictdestruct.nim +++ b/tests/destructor/tdictdestruct.nim @@ -6,7 +6,7 @@ type PDict[TK, TV] = ref TDict[TK, TV] proc fakeNew[T](x: var ref T, destroy: proc (a: ref T) {.nimcall.}) = - nil + discard proc destroyDict[TK, TV](a: PDict[TK, TV]) = return diff --git a/tests/exception/texceptionbreak.nim b/tests/exception/texceptionbreak.nim new file mode 100644 index 000000000..76e986787 --- /dev/null +++ b/tests/exception/texceptionbreak.nim @@ -0,0 +1,45 @@ +discard """ + file: "tnestedbreak.nim" + output: "1\n2\n3\n4" +""" + +# First variety +try: + raise newException(EOS, "Problem") +except EOS: + for y in [1, 2, 3]: + discard + try: + discard + except EOS: + discard +echo "1" + +# Second Variety +try: + raise newException(EOS, "Problem") +except EOS: + for y in [1, 2, 3]: + discard + for y in [1, 2, 3]: + discard + +echo "2" + +# Third Variety +try: + raise newException(EOS, "Problem") +except EOS: + block: + break + +echo "3" + +# Fourth Variety +block: + try: + raise newException(EOS, "Problem") + except EOS: + break + +echo "4" \ No newline at end of file diff --git a/tests/generics/tgeneric3.nim b/tests/generics/tgeneric3.nim index 3c543ecfa..963d0ccfb 100644 --- a/tests/generics/tgeneric3.nim +++ b/tests/generics/tgeneric3.nim @@ -32,7 +32,7 @@ const proc len[T,D] (n:PNode[T,D]): Int {.inline.} = return n.Count -proc clean[T: TOrdinal|TNumber](o: var T) {.inline.} = nil +proc clean[T: TOrdinal|TNumber](o: var T) {.inline.} = discard proc clean[T: string|seq](o: var T) {.inline.} = o = nil @@ -98,7 +98,7 @@ proc DeleteItem[T,D] (n: PNode[T,D], x: Int): PNode[T,D] {.inline.} = of cLen3 : setLen(n.slots, cLen3) of cLenCenter : setLen(n.slots, cLenCenter) of cLen4 : setLen(n.slots, cLen4) - else: nil + else: discard Result = n else : @@ -232,7 +232,7 @@ proc InsertItem[T,D](APath: RPath[T,D], ANode:PNode[T,D], AKey: T, AValue: D) = of cLen3: setLen(APath.Nd.slots, cLenCenter) of cLenCenter: setLen(APath.Nd.slots, cLen4) of cLen4: setLen(APath.Nd.slots, cLenMax) - else: nil + else: discard for i in countdown(APath.Nd.Count.int - 1, x + 1): shallowCopy(APath.Nd.slots[i], APath.Nd.slots[i - 1]) APath.Nd.slots[x] = setItem(AKey, AValue, ANode) diff --git a/tests/lookups/tredef.nim b/tests/lookups/tredef.nim index 02d1f7776..a1647000c 100644 --- a/tests/lookups/tredef.nim +++ b/tests/lookups/tredef.nim @@ -1,28 +1,28 @@ -template foo(a: int, b: string) = nil +template foo(a: int, b: string) = discard foo(1, "test") -proc bar(a: int, b: string) = nil +proc bar(a: int, b: string) = discard bar(1, "test") template foo(a: int, b: string) = bar(a, b) foo(1, "test") block: - proc bar(a: int, b: string) = nil - template foo(a: int, b: string) = nil + proc bar(a: int, b: string) = discard + template foo(a: int, b: string) = discard foo(1, "test") bar(1, "test") proc baz = - proc foo(a: int, b: string) = nil + proc foo(a: int, b: string) = discard proc foo(b: string) = - template bar(a: int, b: string) = nil + template bar(a: int, b: string) = discard bar(1, "test") foo("test") block: - proc foo(b: string) = nil + proc foo(b: string) = discard foo("test") foo(1, "test") diff --git a/tests/metatype/tusertypeclasses.nim b/tests/metatype/tusertypeclasses.nim index 4c2f07b85..4c8c0fc56 100644 --- a/tests/metatype/tusertypeclasses.nim +++ b/tests/metatype/tusertypeclasses.nim @@ -26,3 +26,16 @@ foo 10 foo "test" foo(@[TObj(x: 10), TObj(x: 20)]) +proc intval(x: int) = discard + +# check real and virtual fields +type + TFoo = generic T + intval T.x + intval T.y + +proc y(x: TObj): int = 10 + +proc testFoo(x: TFoo) = discard +testFoo(TObj(x: 10)) + diff --git a/tests/method/tmethods1.nim b/tests/method/tmethods1.nim index f4add6af4..43a260bca 100644 --- a/tests/method/tmethods1.nim +++ b/tests/method/tmethods1.nim @@ -14,8 +14,8 @@ type TSomethingElse = object PSomethingElse = ref TSomethingElse -method foo(a: PNode, b: PSomethingElse) = nil -method foo(a: PNodeFoo, b: PSomethingElse) = nil +method foo(a: PNode, b: PSomethingElse) = discard +method foo(a: PNodeFoo, b: PSomethingElse) = discard var o: TObject o.somethin() diff --git a/tests/overload/toverwr.nim b/tests/overload/toverwr.nim index ef25e8913..32d50faaa 100644 --- a/tests/overload/toverwr.nim +++ b/tests/overload/toverwr.nim @@ -1,13 +1,13 @@ -discard """ - file: "toverwr.nim" - output: "hello" -""" +discard """ + file: "toverwr.nim" + output: "hello" +""" # Test the overloading resolution in connection with a qualifier proc write(t: TFile, s: string) = - nil # a nop + discard # a nop system.write(stdout, "hello") #OUT hello - - + + diff --git a/tests/patterns/targlist.nim b/tests/patterns/targlist.nim index a2fa1fa48..e416edf0a 100644 --- a/tests/patterns/targlist.nim +++ b/tests/patterns/targlist.nim @@ -2,7 +2,7 @@ discard """ output: "12false3ha" """ -proc f(x: varargs[string, `$`]) = nil +proc f(x: varargs[string, `$`]) = discard template optF{f(X)}(x: varargs[expr]) = writeln(stdout, x) diff --git a/tests/range/tsubrange2.nim b/tests/range/tsubrange2.nim index 51598713b..d14111bb9 100644 --- a/tests/range/tsubrange2.nim +++ b/tests/range/tsubrange2.nim @@ -8,7 +8,7 @@ type TRange = range[0..40] proc p(r: TRange) = - nil + discard var r: TRange diff --git a/tests/range/tsubrange3.nim b/tests/range/tsubrange3.nim index b3e02fd29..9afb5018b 100644 --- a/tests/range/tsubrange3.nim +++ b/tests/range/tsubrange3.nim @@ -8,7 +8,7 @@ type TRange = range[0..40] proc p(r: TRange) = - nil + discard var r: TRange diff --git a/tests/sets/tsets.nim b/tests/sets/tsets.nim index 7b806f15b..e370209ed 100644 --- a/tests/sets/tsets.nim +++ b/tests/sets/tsets.nim @@ -1,7 +1,7 @@ -discard """ - file: "tsets.nim" - output: "Ha ein F ist in s!" -""" +discard """ + file: "tsets.nim" + output: "Ha ein F ist in s!" +""" # Test the handling of sets import @@ -38,7 +38,7 @@ type TTokTypes* = set[TTokTypeRange] const - toktypes: TTokTypes = {TTokTypeRange(tkSymbol)..pred(tkIntLit), + toktypes: TTokTypes = {TTokTypeRange(tkSymbol)..pred(tkIntLit), tkStrLit..tkTripleStrLit} var @@ -51,14 +51,14 @@ else: write(stdout, "BUG: F ist nicht in s!\n") a = {} #{'a'..'z'} for x in low(TAZ) .. high(TAZ): incl(a, x) - if x in a: nil + if x in a: discard else: write(stdout, "BUG: something not in a!\n") for x in low(TTokTypeRange) .. high(TTokTypeRange): if x in tokTypes: - nil + discard #writeln(stdout, "the token '$1' is in the set" % repr(x)) #OUT Ha ein F ist in s! - - + + diff --git a/tests/specialops/tdotops.nim b/tests/specialops/tdotops.nim new file mode 100644 index 000000000..ce5b3942d --- /dev/null +++ b/tests/specialops/tdotops.nim @@ -0,0 +1,66 @@ +discard """ + output: ''' +10 +assigning z = 20 +reading field y +20 +call to y +dot call +no params call to a +100 +no params call to b +100 +one param call to c with 10 +100''' +""" + +type + T1 = object + x*: int + + TD = distinct T1 + + T2 = object + x: int + +proc `.`*(v: T1, f: string): int = + echo "reading field ", f + return v.x + +proc `.=`(x: var T1, f: string{lit}, v: int) = + echo "assigning ", f, " = ", v + x.x = v + +template `.()`(x: T1, f: string, args: varargs[expr]): string = + echo "call to ", f + "dot call" + +echo "" + +var t = T1(x: 10) + +echo t.x +t.z = 20 +echo t.y +echo t.y() + +var d = TD(t) +assert(not compiles(d.y)) + +proc `.`(v: T2, f: string): int = + echo "no params call to ", f + return v.x + +proc `.`*(v: T2, f: string, a: int): int = + echo "one param call to ", f, " with ", a + return v.x + +var tt = T2(x: 100) + +echo tt.a +echo tt.b() +echo tt.c(10) + +assert(not compiles(tt.d("x"))) +assert(not compiles(tt.d(1, 2))) + diff --git a/tests/stdlib/tircbot.nim b/tests/stdlib/tircbot.nim index 6008838ff..71ecb0b48 100644 --- a/tests/stdlib/tircbot.nim +++ b/tests/stdlib/tircbot.nim @@ -183,7 +183,7 @@ type channel: string timestamp: TTime case kind*: TSeenType - of PSeenJoin: nil + of PSeenJoin: discard of PSeenPart, PSeenQuit, PSeenMsg: msg: string of PSeenNick: @@ -200,7 +200,7 @@ proc setSeen(d: TDb, s: TSeen) = var hashToSet = @[("type", $s.kind.int), ("channel", s.channel), ("timestamp", $s.timestamp.int)] case s.kind - of PSeenJoin: nil + of PSeenJoin: discard of PSeenPart, PSeenMsg, PSeenQuit: hashToSet.add(("msg", s.msg)) of PSeenNick: @@ -338,7 +338,7 @@ proc hubConnect(state: PState) = proc handleIrc(irc: PAsyncIRC, event: TIRCEvent, state: PState) = case event.typ - of EvConnected: nil + of EvConnected: discard of EvDisconnected: while not state.ircClient.isConnected: try: @@ -424,7 +424,7 @@ proc handleIrc(irc: PAsyncIRC, event: TIRCEvent, state: PState) = seenNick.newNick = event.params[0] state.database.setSeen(seenNick) else: - nil # TODO: ? + discard # TODO: ? proc open(port: TPort = TPort(5123)): PState = var res: PState diff --git a/tests/stdlib/tmath2.nim b/tests/stdlib/tmath2.nim index 6a1dae54d..935b08634 100644 --- a/tests/stdlib/tmath2.nim +++ b/tests/stdlib/tmath2.nim @@ -1,7 +1,7 @@ # tests for the interpreter proc loops(a: var int) = - nil + discard #var # b: int #b = glob diff --git a/tests/stdlib/tos.nim b/tests/stdlib/tos.nim index fa9993cc9..ebe577b00 100644 --- a/tests/stdlib/tos.nim +++ b/tests/stdlib/tos.nim @@ -7,6 +7,6 @@ proc walkDirTree(root: string) = case k of pcFile, pcLinkToFile: echo(f) of pcDir: walkDirTree(f) - of pcLinkToDir: nil + of pcLinkToDir: discard walkDirTree(".") diff --git a/tests/stdlib/tpegs.nim b/tests/stdlib/tpegs.nim index bdd8db0f8..7775091a1 100644 --- a/tests/stdlib/tpegs.nim +++ b/tests/stdlib/tpegs.nim @@ -72,7 +72,7 @@ type rule: TNode ## the rule that the symbol refers to TNode {.final, shallow.} = object case kind: TPegKind - of pkEmpty..pkWhitespace: nil + of pkEmpty..pkWhitespace: discard of pkTerminal, pkTerminalIgnoreCase, pkTerminalIgnoreStyle: term: string of pkChar, pkGreedyRepChar: ch: char of pkCharChoice, pkGreedyRepSet: charChoice: ref set[char] @@ -123,7 +123,7 @@ proc add(d: var TPeg, s: TPeg) {.inline.} = add(d.sons, s) proc copyPeg(a: TPeg): TPeg = result.kind = a.kind case a.kind - of pkEmpty..pkWhitespace: nil + of pkEmpty..pkWhitespace: discard of pkTerminal, pkTerminalIgnoreCase, pkTerminalIgnoreStyle: result.term = a.term of pkChar, pkGreedyRepChar: @@ -229,7 +229,7 @@ when false: case a.kind of pkEmpty, pkAny, pkAnyRune, pkGreedyAny, pkNewLine, pkTerminal, pkTerminalIgnoreCase, pkTerminalIgnoreStyle, pkChar, pkGreedyRepChar, - pkCharChoice, pkGreedyRepSet: nil + pkCharChoice, pkGreedyRepSet: discard of pkNonTerminal: return true else: for i in 0..a.sons.len-1: @@ -318,7 +318,7 @@ proc backrefIgnoreStyle*(index: range[1..MaxSubPatterns]): TPeg {. proc spaceCost(n: TPeg): int = case n.kind - of pkEmpty: nil + of pkEmpty: discard of pkTerminal, pkTerminalIgnoreCase, pkTerminalIgnoreStyle, pkChar, pkGreedyRepChar, pkCharChoice, pkGreedyRepSet, pkAny..pkWhitespace, pkGreedyAny: @@ -1111,7 +1111,7 @@ proc handleHexChar(c: var TPegLexer, xi: var int) = of 'A'..'F': xi = (xi shl 4) or (ord(c.buf[c.bufpos]) - ord('A') + 10) inc(c.bufpos) - else: nil + else: discard proc getEscapedChar(c: var TPegLexer, tok: var TToken) = inc(c.bufpos) @@ -1341,7 +1341,7 @@ proc getTok(c: var TPegLexer, tok: var TToken) = of "i": tok.modifier = modIgnoreCase of "y": tok.modifier = modIgnoreStyle of "v": tok.modifier = modVerbatim - else: nil + else: discard setLen(tok.literal, 0) if c.buf[c.bufpos] == '$': getDollar(c, tok) @@ -1488,7 +1488,7 @@ proc primary(p: var TPegParser): TPeg = of tkCurlyAt: getTok(p) return !*\primary(p).token(p) - else: nil + else: discard case p.tok.kind of tkIdentifier: if p.identIsVerbatim: diff --git a/tests/table/ttableconstr.nim b/tests/table/ttableconstr.nim index c627e68e8..1a21a18d1 100644 --- a/tests/table/ttableconstr.nim +++ b/tests/table/ttableconstr.nim @@ -1,7 +1,7 @@ # Test if the new table constructor syntax works: template ignoreExpr(e: expr): stmt {.immediate.} = - nil + discard # test first class '..' syntactical citizen: ignoreExpr x <> 2..4 diff --git a/tests/typerel/typalias.nim b/tests/typerel/typalias.nim index ba9f38ed9..40ff06765 100644 --- a/tests/typerel/typalias.nim +++ b/tests/typerel/typalias.nim @@ -9,7 +9,7 @@ proc init: TYourObj = result.y = -1 proc f(x: var TYourObj) = - nil + discard var m: TMyObj = init() f(m) diff --git a/tools/nimgrep.nim b/tools/nimgrep.nim index b20e86a68..28d92402e 100644 --- a/tools/nimgrep.nim +++ b/tools/nimgrep.nim @@ -249,7 +249,7 @@ proc walker(dir: string) = of pcDir: if optRecursive in options: walker(path) - else: nil + else: discard if existsFile(dir): processFile(dir) proc writeHelp() = diff --git a/web/news.txt b/web/news.txt index a045eb880..b28e5c64a 100644 --- a/web/news.txt +++ b/web/news.txt @@ -68,8 +68,8 @@ Language Additions - Exported templates are allowed to access hidden fields. - The ``using statement`` enables you to more easily author domain-specific languages and libraries providing OOP-like syntactic sugar. -- Added a new ``delegator pragma`` for handling calls to missing procs and - fields at compile-time. +- Added the possibility to override various dot operators in order to handle + calls to missing procs and reads from undeclared fields at compile-time. - The overload resolution now supports ``static[T]`` params that must be evaluable at compile-time. - Support for user-defined type classes has been added. |