# # # The Nimrod Compiler # (c) Copyright 2013 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. # ## this module does the semantic checking of statements # included from sem.nim proc semCommand(c: PContext, n: PNode): PNode = result = semExprNoType(c, n) proc semWhen(c: PContext, n: PNode, semCheck = true): PNode = # If semCheck is set to false, ``when`` will return the verbatim AST of # the correct branch. Otherwise the AST will be passed through semStmt. result = nil template setResult(e: expr) = if semCheck: result = semStmt(c, e) # do not open a new scope! else: result = e for i in countup(0, sonsLen(n) - 1): var it = n.sons[i] case it.kind of nkElifBranch, nkElifExpr: checkSonsLen(it, 2) var e = semConstExpr(c, it.sons[0]) if e.kind != nkIntLit: InternalError(n.info, "semWhen") elif e.intVal != 0 and result == nil: setResult(it.sons[1]) of nkElse, nkElseExpr: checkSonsLen(it, 1) if result == nil: setResult(it.sons[0]) else: illFormedAst(n) if result == nil: result = newNodeI(nkNilLit, n.info) # The ``when`` statement implements the mechanism for platform dependent # code. Thus we try to ensure here consistent ID allocation after the # ``when`` statement. IDsynchronizationPoint(200) proc semIf(c: PContext, n: PNode): PNode = result = n for i in countup(0, sonsLen(n) - 1): var it = n.sons[i] case it.kind of nkElifBranch: checkSonsLen(it, 2) it.sons[0] = forceBool(c, semExprWithType(c, it.sons[0])) openScope(c.tab) it.sons[1] = semStmt(c, it.sons[1]) closeScope(c.tab) of nkElse: if sonsLen(it) == 1: it.sons[0] = semStmtScope(c, it.sons[0]) else: illFormedAst(it) else: illFormedAst(n) proc semDiscard(c: PContext, n: PNode): PNode = result = n checkSonsLen(n, 1) if n.sons[0].kind != nkEmpty: n.sons[0] = semExprWithType(c, n.sons[0]) if isEmptyType(n.sons[0].typ): localError(n.info, errInvalidDiscard) proc semBreakOrContinue(c: PContext, n: PNode): PNode = result = n checkSonsLen(n, 1) if n.sons[0].kind != nkEmpty: var s: PSym case n.sons[0].kind of nkIdent: s = lookUp(c, n.sons[0]) of nkSym: s = n.sons[0].sym else: illFormedAst(n) if s.kind == skLabel and s.owner.id == c.p.owner.id: var x = newSymNode(s) x.info = n.info incl(s.flags, sfUsed) n.sons[0] = x suggestSym(x, s) else: localError(n.info, errInvalidControlFlowX, s.name.s) elif (c.p.nestedLoopCounter <= 0) and (c.p.nestedBlockCounter <= 0): localError(n.info, errInvalidControlFlowX, renderTree(n, {renderNoComments})) proc semBlock(c: PContext, n: PNode): PNode = result = n Inc(c.p.nestedBlockCounter) checkSonsLen(n, 2) openScope(c.tab) # BUGFIX: label is in the scope of block! if n.sons[0].kind != nkEmpty: var labl = newSymG(skLabel, n.sons[0], c) if sfGenSym notin labl.flags: addDecl(c, labl) n.sons[0] = newSymNode(labl, n.sons[0].info) suggestSym(n.sons[0], labl) n.sons[1] = semStmt(c, n.sons[1]) closeScope(c.tab) Dec(c.p.nestedBlockCounter) proc semAsm(con: PContext, n: PNode): PNode = checkSonsLen(n, 2) var marker = pragmaAsm(con, n.sons[0]) if marker == '\0': marker = '`' # default marker result = semAsmOrEmit(con, n, marker) proc semWhile(c: PContext, n: PNode): PNode = result = n checkSonsLen(n, 2) openScope(c.tab) n.sons[0] = forceBool(c, semExprWithType(c, n.sons[0])) inc(c.p.nestedLoopCounter) n.sons[1] = semStmt(c, n.sons[1]) dec(c.p.nestedLoopCounter) closeScope(c.tab) proc toCover(t: PType): biggestInt = var t2 = skipTypes(t, abstractVarRange-{tyTypeDesc}) if t2.kind == tyEnum and enumHasHoles(t2): result = sonsLen(t2.n) else: result = lengthOrd(skipTypes(t, abstractVar-{tyTypeDesc})) proc semCase(c: PContext, n: PNode): PNode = # check selector: result = n checkMinSonsLen(n, 2) openScope(c.tab) n.sons[0] = semExprWithType(c, n.sons[0]) var chckCovered = false var covered: biggestint = 0 case skipTypes(n.sons[0].Typ, abstractVarRange-{tyTypeDesc}).Kind of tyInt..tyInt64, tyChar, tyEnum: chckCovered = true of tyFloat..tyFloat128, tyString, tyError: nil else: LocalError(n.info, errSelectorMustBeOfCertainTypes) return for i in countup(1, sonsLen(n) - 1): var x = n.sons[i] case x.kind of nkOfBranch: checkMinSonsLen(x, 2) semCaseBranch(c, n, x, i, covered) var length = sonsLen(x) x.sons[length - 1] = semStmtScope(c, x.sons[length - 1]) of nkElifBranch: chckCovered = false checkSonsLen(x, 2) x.sons[0] = forceBool(c, semExprWithType(c, x.sons[0])) x.sons[1] = semStmtScope(c, x.sons[1]) of nkElse: chckCovered = false checkSonsLen(x, 1) x.sons[0] = semStmtScope(c, x.sons[0]) else: illFormedAst(x) if chckCovered and (covered != toCover(n.sons[0].typ)): localError(n.info, errNotAllCasesCovered) closeScope(c.tab) proc fitRemoveHiddenConv(c: PContext, typ: Ptype, n: PNode): PNode = result = fitNode(c, typ, n) if result.kind in {nkHiddenStdConv, nkHiddenSubConv}: changeType(result.sons[1], typ) result = result.sons[1] elif not sameType(result.typ, typ): changeType(result, typ) proc findShadowedVar(c: PContext, v: PSym): PSym = for i in countdown(c.tab.tos - 2, ModuleTablePos+1): let shadowed = StrTableGet(c.tab.stack[i], v.name) if shadowed != nil and shadowed.kind in skLocalVars: return shadowed proc identWithin(n: PNode, s: PIdent): bool = for i in 0 .. n.safeLen-1: if identWithin(n.sons[i], s): return true result = n.kind == nkSym and n.sym.name.id == s.id proc semIdentDef(c: PContext, n: PNode, kind: TSymKind): PSym = if isTopLevel(c): result = semIdentWithPragma(c, kind, n, {sfExported}) incl(result.flags, sfGlobal) else: result = semIdentWithPragma(c, kind, n, {}) suggestSym(n, result) proc semVarOrLet(c: PContext, n: PNode, symkind: TSymKind): PNode = var b: PNode result = copyNode(n) for i in countup(0, sonsLen(n)-1): var a = n.sons[i] if gCmd == cmdIdeTools: suggestStmt(c, a) if a.kind == nkCommentStmt: continue if a.kind notin {nkIdentDefs, nkVarTuple, nkConstDef}: IllFormedAst(a) checkMinSonsLen(a, 3) var length = sonsLen(a) var typ: PType if a.sons[length-2].kind != nkEmpty: typ = semTypeNode(c, a.sons[length-2], nil) else: typ = nil var def: PNode if a.sons[length-1].kind != nkEmpty: def = semExprWithType(c, a.sons[length-1]) # BUGFIX: ``fitNode`` is needed here! # check type compability between def.typ and typ: if typ != nil: def = fitNode(c, typ, def) else: typ = skipIntLit(def.typ) else: def = ast.emptyNode if symkind == skLet: LocalError(a.info, errLetNeedsInit) # this can only happen for errornous var statements: if typ == nil: continue if not typeAllowed(typ, symkind): LocalError(a.info, errXisNoType, typeToString(typ)) var tup = skipTypes(typ, {tyGenericInst}) if a.kind == nkVarTuple: if tup.kind != tyTuple: localError(a.info, errXExpected, "tuple") elif length-2 != sonsLen(tup): localError(a.info, errWrongNumberOfVariables) else: b = newNodeI(nkVarTuple, a.info) newSons(b, length) b.sons[length-2] = a.sons[length-2] # keep type desc for doc generator b.sons[length-1] = def addSon(result, b) elif tup.kind == tyTuple and def.kind == nkPar and a.kind == nkIdentDefs and a.len > 3: Message(a.info, warnEachIdentIsTuple) for j in countup(0, length-3): var v = semIdentDef(c, a.sons[j], symkind) if sfGenSym notin v.flags: addInterfaceDecl(c, v) when oKeepVariableNames: if c.InUnrolledContext > 0: v.flags.incl(sfShadowed) else: let shadowed = findShadowedVar(c, v) if shadowed != nil: shadowed.flags.incl(sfShadowed) # a shadowed variable is an error unless it appears on the right # side of the '=': if warnShadowIdent in gNotes and not identWithin(def, v.name): Message(a.info, warnShadowIdent, v.name.s) if def != nil and def.kind != nkEmpty: # this is only needed for the evaluation pass: v.ast = def if sfThread in v.flags: LocalError(def.info, errThreadvarCannotInit) if a.kind != nkVarTuple: v.typ = typ b = newNodeI(nkIdentDefs, a.info) if importantComments(): # keep documentation information: b.comment = a.comment addSon(b, newSymNode(v)) addSon(b, a.sons[length-2]) # keep type desc for doc generator addSon(b, copyTree(def)) addSon(result, b) else: v.typ = tup.sons[j] b.sons[j] = newSymNode(v) proc semConst(c: PContext, n: PNode): PNode = result = copyNode(n) for i in countup(0, sonsLen(n) - 1): var a = n.sons[i] if gCmd == cmdIdeTools: suggestStmt(c, a) if a.kind == nkCommentStmt: continue if (a.kind != nkConstDef): IllFormedAst(a) checkSonsLen(a, 3) var v = semIdentDef(c, a.sons[0], skConst) var typ: PType = nil if a.sons[1].kind != nkEmpty: typ = semTypeNode(c, a.sons[1], nil) var def = semConstExpr(c, a.sons[2]) if def == nil: LocalError(a.sons[2].info, errConstExprExpected) continue # check type compatibility between def.typ and typ: if typ != nil: def = fitRemoveHiddenConv(c, typ, def) else: typ = def.typ if typ == nil: continue if not typeAllowed(typ, skConst): LocalError(a.info, errXisNoType, typeToString(typ)) continue v.typ = typ v.ast = def # no need to copy if sfGenSym notin v.flags: addInterfaceDecl(c, v) var b = newNodeI(nkConstDef, a.info) if importantComments(): b.comment = a.comment addSon(b, newSymNode(v)) addSon(b, ast.emptyNode) # no type description addSon(b, copyTree(def)) addSon(result, b) type TFieldInstCtx = object # either 'tup[i]' or 'field' is valid tupleType: PType # if != nil we're traversing a tuple tupleIndex: int field: PSym replaceByFieldName: bool proc instFieldLoopBody(c: TFieldInstCtx, n: PNode, forLoop: PNode): PNode = case n.kind of nkEmpty..pred(nkIdent), succ(nkIdent)..nkNilLit: result = n of nkIdent: result = n var L = sonsLen(forLoop) if c.replaceByFieldName: if n.ident.id == forLoop[0].ident.id: let fieldName = if c.tupleType.isNil: c.field.name.s elif c.tupleType.n.isNil: "Field" & $c.tupleIndex else: c.tupleType.n.sons[c.tupleIndex].sym.name.s result = newStrNode(nkStrLit, fieldName) return # other fields: for i in ord(c.replaceByFieldName)..L-3: if n.ident.id == forLoop[i].ident.id: var call = forLoop.sons[L-2] var tupl = call.sons[i+1-ord(c.replaceByFieldName)] if c.field.isNil: result = newNodeI(nkBracketExpr, n.info) result.add(tupl) result.add(newIntNode(nkIntLit, c.tupleIndex)) else: result = newNodeI(nkDotExpr, n.info) result.add(tupl) result.add(newSymNode(c.field, n.info)) break else: if n.kind == nkContinueStmt: localError(n.info, errGenerated, "'continue' not supported in a 'fields' loop") result = copyNode(n) newSons(result, sonsLen(n)) for i in countup(0, sonsLen(n)-1): result.sons[i] = instFieldLoopBody(c, n.sons[i], forLoop) type TFieldsCtx = object c: PContext m: TMagic proc semForObjectFields(c: TFieldsCtx, typ, forLoop, father: PNode) = case typ.kind of nkSym: var fc: TFieldInstCtx # either 'tup[i]' or 'field' is valid fc.field = typ.sym fc.replaceByFieldName = c.m == mFieldPairs openScope(c.c.tab) inc c.c.InUnrolledContext let body = instFieldLoopBody(fc, lastSon(forLoop), forLoop) father.add(SemStmt(c.c, body)) dec c.c.InUnrolledContext closeScope(c.c.tab) of nkNilLit: nil of nkRecCase: let L = forLoop.len let call = forLoop.sons[L-2] if call.len > 2: LocalError(forLoop.info, errGenerated, "parallel 'fields' iterator does not work for 'case' objects") return # iterate over the selector: semForObjectFields(c, typ[0], forLoop, father) # we need to generate a case statement: var caseStmt = newNodeI(nkCaseStmt, forLoop.info) # generate selector: var access = newNodeI(nkDotExpr, forLoop.info, 2) access.sons[0] = call.sons[1] access.sons[1] = newSymNode(typ.sons[0].sym, forLoop.info) caseStmt.add(semExprWithType(c.c, access)) # copy the branches over, but replace the fields with the for loop body: for i in 1 .. 0: if n.sons[genericParamsPos].kind == nkEmpty: # we have a list of implicit type parameters: n.sons[genericParamsPos] = gp # check for semantics again: # semParamList(c, n.sons[ParamsPos], nil, s) else: s.typ = newTypeS(tyProc, c) rawAddSon(s.typ, nil) if n.sons[patternPos].kind != nkEmpty: n.sons[patternPos] = semPattern(c, n.sons[patternPos]) if s.kind == skIterator: s.typ.flags.incl(tfIterator) var proto = SearchForProc(c, s, c.tab.tos-2) # -2 because we have a scope # open for parameters if proto == nil: s.typ.callConv = lastOptionEntry(c).defaultCC # add it here, so that recursive procs are possible: # -2 because we have a scope open for parameters if sfGenSym in s.flags: nil elif kind in OverloadableSyms: addInterfaceOverloadableSymAt(c, s, c.tab.tos - 2) else: addInterfaceDeclAt(c, s, c.tab.tos - 2) if n.sons[pragmasPos].kind != nkEmpty: pragma(c, s, n.sons[pragmasPos], validPragmas) else: implictPragmas(c, s, n, validPragmas) else: if n.sons[pragmasPos].kind != nkEmpty: LocalError(n.sons[pragmasPos].info, errPragmaOnlyInHeaderOfProc) if sfForward notin proto.flags: WrongRedefinition(n.info, proto.name.s) excl(proto.flags, sfForward) closeScope(c.tab) # close scope with wrong parameter symbols openScope(c.tab) # open scope for old (correct) parameter symbols if proto.ast.sons[genericParamsPos].kind != nkEmpty: addGenericParamListToScope(c, proto.ast.sons[genericParamsPos]) addParams(c, proto.typ.n, proto.kind) proto.info = s.info # more accurate line information s.typ = proto.typ s = proto n.sons[genericParamsPos] = proto.ast.sons[genericParamsPos] n.sons[paramsPos] = proto.ast.sons[paramsPos] n.sons[pragmasPos] = proto.ast.sons[pragmasPos] if n.sons[namePos].kind != nkSym: InternalError(n.info, "semProcAux") n.sons[namePos].sym = proto if importantComments() and not isNil(proto.ast.comment): n.comment = proto.ast.comment proto.ast = n # needed for code generation popOwner() pushOwner(s) s.options = gOptions if sfDestructor in s.flags: doDestructorStuff(c, s, n) if n.sons[bodyPos].kind != nkEmpty: # for DLL generation it is annoying to check for sfImportc! if sfBorrow in s.flags: LocalError(n.sons[bodyPos].info, errImplOfXNotAllowed, s.name.s) if n.sons[genericParamsPos].kind == nkEmpty: ParamsTypeCheck(c, s.typ) pushProcCon(c, s) maybeAddResult(c, s, n) if sfImportc notin s.flags: # no semantic checking for importc: let semBody = hloBody(c, semProcBody(c, n.sons[bodyPos])) # unfortunately we cannot skip this step when in 'system.compiles' # context as it may even be evaluated in 'system.compiles': n.sons[bodyPos] = transformBody(c.module, semBody, s) popProcCon(c) else: if s.typ.sons[0] != nil and kind != skIterator: addDecl(c, newSym(skUnknown, getIdent"result", nil, n.info)) var toBind = initIntSet() n.sons[bodyPos] = semGenericStmtScope(c, n.sons[bodyPos], {}, toBind) fixupInstantiatedSymbols(c, s) if sfImportc in s.flags: # so we just ignore the body after semantic checking for importc: n.sons[bodyPos] = ast.emptyNode else: if proto != nil: LocalError(n.info, errImplOfXexpected, proto.name.s) if {sfImportc, sfBorrow} * s.flags == {} and s.magic == mNone: incl(s.flags, sfForward) elif sfBorrow in s.flags: semBorrow(c, n, s) sideEffectsCheck(c, s) closeScope(c.tab) # close scope for parameters popOwner() if n.sons[patternPos].kind != nkEmpty: c.patterns.add(s) proc semIterator(c: PContext, n: PNode): PNode = result = semProcAux(c, n, skIterator, iteratorPragmas) var s = result.sons[namePos].sym var t = s.typ if t.sons[0] == nil and s.typ.callConv != ccClosure: LocalError(n.info, errXNeedsReturnType, "iterator") # iterators are either 'inline' or 'closure'; for backwards compatibility, # we require first class iterators to be marked with 'closure' explicitly # -- at least for 0.9.2. if s.typ.callConv == ccClosure: incl(s.typ.flags, tfCapturesEnv) when false: if s.typ.callConv != ccInline: s.typ.callConv = ccClosure # and they always at least use the 'env' for the state field: incl(s.typ.flags, tfCapturesEnv) if n.sons[bodyPos].kind == nkEmpty and s.magic == mNone: LocalError(n.info, errImplOfXexpected, s.name.s) proc semProc(c: PContext, n: PNode): PNode = result = semProcAux(c, n, skProc, procPragmas) proc hasObjParam(s: PSym): bool = var t = s.typ for col in countup(1, sonsLen(t)-1): if skipTypes(t.sons[col], skipPtrs).kind == tyObject: return true proc finishMethod(c: PContext, s: PSym) = if hasObjParam(s): methodDef(s, false) proc semMethod(c: PContext, n: PNode): PNode = if not isTopLevel(c): LocalError(n.info, errXOnlyAtModuleScope, "method") result = semProcAux(c, n, skMethod, methodPragmas) var s = result.sons[namePos].sym if not isGenericRoutine(s): if hasObjParam(s): methodDef(s, false) else: LocalError(n.info, errXNeedsParamObjectType, "method") proc semConverterDef(c: PContext, n: PNode): PNode = if not isTopLevel(c): LocalError(n.info, errXOnlyAtModuleScope, "converter") checkSonsLen(n, bodyPos + 1) result = semProcAux(c, n, skConverter, converterPragmas) var s = result.sons[namePos].sym var t = s.typ if t.sons[0] == nil: LocalError(n.info, errXNeedsReturnType, "converter") if sonsLen(t) != 2: LocalError(n.info, errXRequiresOneArgument, "converter") addConverter(c, s) proc semMacroDef(c: PContext, n: PNode): PNode = checkSonsLen(n, bodyPos + 1) result = semProcAux(c, n, skMacro, macroPragmas) var s = result.sons[namePos].sym var t = s.typ if t.sons[0] == nil: LocalError(n.info, errXNeedsReturnType, "macro") if n.sons[bodyPos].kind == nkEmpty: LocalError(n.info, errImplOfXexpected, s.name.s) proc evalInclude(c: PContext, n: PNode): PNode = result = newNodeI(nkStmtList, n.info) addSon(result, n) for i in countup(0, sonsLen(n) - 1): var f = checkModuleName(n.sons[i]) if f != InvalidFileIDX: if ContainsOrIncl(c.includedFiles, f): LocalError(n.info, errRecursiveDependencyX, f.toFilename) else: addSon(result, semStmt(c, gIncludeFile(c.module, f))) Excl(c.includedFiles, f) proc setLine(n: PNode, info: TLineInfo) = for i in 0 .. 0: var lastStmt = lastSon(result) if lastStmt.kind != nkNilLit and not ImplicitlyDiscardable(lastStmt): result.typ = lastStmt.typ #localError(lastStmt.info, errGenerated, # "Last expression must be explicitly returned if it " & # "is discardable or discarded") proc SemStmt(c: PContext, n: PNode): PNode = # now: simply an alias: result = semExprNoType(c, n) proc semStmtScope(c: PContext, n: PNode): PNode = openScope(c.tab) result = semStmt(c, n) closeScope(c.tab)