# # # The Nim 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 for expressions # included from sem.nim when defined(nimCompilerStackraceHints): import std/stackframes const errExprXHasNoType = "expression '$1' has no type (or is ambiguous)" errXExpectsTypeOrValue = "'$1' expects a type or value" errVarForOutParamNeededX = "for a 'var' type a variable needs to be passed; but '$1' is immutable" errXStackEscape = "address of '$1' may not escape its stack frame" errExprHasNoAddress = "expression has no address" errCannotInterpretNodeX = "cannot evaluate '$1'" errNamedExprExpected = "named expression expected" errNamedExprNotAllowed = "named expression not allowed here" errFieldInitTwice = "field initialized twice: '$1'" errUndeclaredFieldX = "undeclared field: '$1'" proc semTemplateExpr(c: PContext, n: PNode, s: PSym, flags: TExprFlags = {}): PNode = let info = getCallLineInfo(n) markUsed(c, info, s) onUse(info, s) # Note: This is n.info on purpose. It prevents template from creating an info # context when called from an another template pushInfoContext(c.config, n.info, s.detailedInfo) result = evalTemplate(n, s, getCurrOwner(c), c.config, c.cache, efFromHlo in flags) if efNoSemCheck notin flags: result = semAfterMacroCall(c, n, result, s, flags) popInfoContext(c.config) # XXX: A more elaborate line info rewrite might be needed result.info = info proc semFieldAccess(c: PContext, n: PNode, flags: TExprFlags = {}): PNode template rejectEmptyNode(n: PNode) = # No matter what a nkEmpty node is not what we want here if n.kind == nkEmpty: illFormedAst(n, c.config) proc semOperand(c: PContext, n: PNode, flags: TExprFlags = {}): PNode = rejectEmptyNode(n) # same as 'semExprWithType' but doesn't check for proc vars result = semExpr(c, n, flags + {efOperand}) if result.typ != nil: # XXX tyGenericInst here? if result.typ.kind == tyProc and tfUnresolved in result.typ.flags: localError(c.config, n.info, errProcHasNoConcreteType % n.renderTree) if result.typ.kind in {tyVar, tyLent}: result = newDeref(result) elif {efWantStmt, efAllowStmt} * flags != {}: result.typ = newTypeS(tyVoid, c) else: localError(c.config, n.info, errExprXHasNoType % renderTree(result, {renderNoComments})) result.typ = errorType(c) proc semExprCheck(c: PContext, n: PNode, flags: TExprFlags): PNode = rejectEmptyNode(n) result = semExpr(c, n, flags+{efWantValue}) if result.kind == nkEmpty: # bug #12741, redundant error messages are the lesser evil here: localError(c.config, n.info, errExprXHasNoType % renderTree(result, {renderNoComments})) # do not produce another redundant error message: result = errorNode(c, n) proc semExprWithType(c: PContext, n: PNode, flags: TExprFlags = {}): PNode = result = semExprCheck(c, n, flags) if result.typ == nil or result.typ == c.enforceVoidContext: localError(c.config, n.info, errExprXHasNoType % renderTree(result, {renderNoComments})) result.typ = errorType(c) else: if result.typ.kind in {tyVar, tyLent}: result = newDeref(result) proc semExprNoDeref(c: PContext, n: PNode, flags: TExprFlags = {}): PNode = result = semExprCheck(c, n, flags) if result.typ == nil: localError(c.config, n.info, errExprXHasNoType % renderTree(result, {renderNoComments})) result.typ = errorType(c) proc semSymGenericInstantiation(c: PContext, n: PNode, s: PSym): PNode = result = symChoice(c, n, s, scClosed) proc inlineConst(c: PContext, n: PNode, s: PSym): PNode {.inline.} = result = copyTree(s.ast) if result.isNil: localError(c.config, n.info, "constant of type '" & typeToString(s.typ) & "' has no value") result = newSymNode(s) else: result.typ = s.typ result.info = n.info type TConvStatus = enum convOK, convNotNeedeed, convNotLegal, convNotInRange proc checkConversionBetweenObjects(castDest, src: PType; pointers: int): TConvStatus = let diff = inheritanceDiff(castDest, src) return if diff == high(int) or (pointers > 1 and diff != 0): convNotLegal else: convOK const IntegralTypes = {tyBool, tyEnum, tyChar, tyInt..tyUInt64} proc checkConvertible(c: PContext, targetTyp: PType, src: PNode): TConvStatus = let srcTyp = src.typ.skipTypes({tyStatic}) result = convOK if sameType(targetTyp, srcTyp) and targetTyp.sym == srcTyp.sym: # don't annoy conversions that may be needed on another processor: if targetTyp.kind notin IntegralTypes+{tyRange}: result = convNotNeedeed return var d = skipTypes(targetTyp, abstractVar) var s = srcTyp if s.kind in tyUserTypeClasses and s.isResolvedUserTypeClass: s = s.lastSon s = skipTypes(s, abstractVar-{tyTypeDesc, tyOwned}) if s.kind == tyOwned and d.kind != tyOwned: s = s.lastSon var pointers = 0 while (d != nil) and (d.kind in {tyPtr, tyRef, tyOwned}): if s.kind == tyOwned and d.kind != tyOwned: s = s.lastSon elif d.kind != s.kind: break else: d = d.lastSon s = s.lastSon inc pointers let targetBaseTyp = skipTypes(targetTyp, abstractVarRange) let srcBaseTyp = skipTypes(srcTyp, abstractVarRange-{tyTypeDesc}) if d == nil: result = convNotLegal elif d.skipTypes(abstractInst).kind == tyObject and s.skipTypes(abstractInst).kind == tyObject: result = checkConversionBetweenObjects(d.skipTypes(abstractInst), s.skipTypes(abstractInst), pointers) elif (targetBaseTyp.kind in IntegralTypes) and (srcBaseTyp.kind in IntegralTypes): if targetTyp.kind == tyBool: discard "convOk" elif targetTyp.isOrdinalType: if src.kind in nkCharLit..nkUInt64Lit and src.getInt notin firstOrd(c.config, targetTyp)..lastOrd(c.config, targetTyp): result = convNotInRange elif src.kind in nkFloatLit..nkFloat64Lit and (classify(src.floatVal) in {fcNan, fcNegInf, fcInf} or src.floatVal.int64 notin firstOrd(c.config, targetTyp)..lastOrd(c.config, targetTyp)): result = convNotInRange elif targetBaseTyp.kind in tyFloat..tyFloat64: if src.kind in nkFloatLit..nkFloat64Lit and not floatRangeCheck(src.floatVal, targetTyp): result = convNotInRange elif src.kind in nkCharLit..nkUInt64Lit and not floatRangeCheck(src.intVal.float, targetTyp): result = convNotInRange else: # we use d, s here to speed up that operation a bit: case cmpTypes(c, d, s) of isNone, isGeneric: if not compareTypes(targetTyp.skipTypes(abstractVar), srcTyp.skipTypes({tyOwned}), dcEqIgnoreDistinct): result = convNotLegal else: discard proc isCastable(conf: ConfigRef; dst, src: PType): bool = ## Checks whether the source type can be cast to the destination type. ## Casting is very unrestrictive; casts are allowed as long as ## castDest.size >= src.size, and typeAllowed(dst, skParam) #const # castableTypeKinds = {tyInt, tyPtr, tyRef, tyCstring, tyString, # tySequence, tyPointer, tyNil, tyOpenArray, # tyProc, tySet, tyEnum, tyBool, tyChar} let src = src.skipTypes(tyUserTypeClasses) if skipTypes(dst, abstractInst-{tyOpenArray}).kind == tyOpenArray: return false if skipTypes(src, abstractInst-{tyTypeDesc}).kind == tyTypeDesc: return false if conf.selectedGC in {gcArc, gcOrc}: let d = skipTypes(dst, abstractInst) let s = skipTypes(src, abstractInst) if d.kind == tyRef and s.kind == tyRef and s[0].isFinal != d[0].isFinal: return false var dstSize, srcSize: BiggestInt dstSize = computeSize(conf, dst) srcSize = computeSize(conf, src) if dstSize == -3 or srcSize == -3: # szUnknownSize # The Nim compiler can't detect if it's legal or not. # Just assume the programmer knows what he is doing. return true if dstSize < 0: result = false elif srcSize < 0: result = false elif typeAllowed(dst, skParam) != nil: result = false elif dst.kind == tyProc and dst.callConv == ccClosure: result = src.kind == tyProc and src.callConv == ccClosure else: result = (dstSize >= srcSize) or (skipTypes(dst, abstractInst).kind in IntegralTypes) or (skipTypes(src, abstractInst-{tyTypeDesc}).kind in IntegralTypes) if result and src.kind == tyNil: result = dst.size <= conf.target.ptrSize proc isSymChoice(n: PNode): bool {.inline.} = result = n.kind in nkSymChoices proc maybeLiftType(t: var PType, c: PContext, info: TLineInfo) = # XXX: liftParamType started to perform addDecl # we could do that instead in semTypeNode by snooping for added # gnrc. params, then it won't be necessary to open a new scope here openScope(c) var lifted = liftParamType(c, skType, newNodeI(nkArgList, info), t, ":anon", info) closeScope(c) if lifted != nil: t = lifted proc isOwnedSym(c: PContext; n: PNode): bool = let s = qualifiedLookUp(c, n, {}) result = s != nil and sfSystemModule in s.owner.flags and s.name.s == "owned" proc semConv(c: PContext, n: PNode): PNode = if n.len != 2: localError(c.config, n.info, "a type conversion takes exactly one argument") return n result = newNodeI(nkConv, n.info) var targetType = semTypeNode(c, n[0], nil) case targetType.kind of tyTypeDesc: internalAssert c.config, targetType.len > 0 if targetType.base.kind == tyNone: return semTypeOf(c, n) else: targetType = targetType.base of tyStatic: var evaluated = semStaticExpr(c, n[1]) if evaluated.kind == nkType or evaluated.typ.kind == tyTypeDesc: result = n result.typ = c.makeTypeDesc semStaticType(c, evaluated, nil) return elif targetType.base.kind == tyNone: return evaluated else: targetType = targetType.base else: discard maybeLiftType(targetType, c, n[0].info) if targetType.kind in {tySink, tyLent} or isOwnedSym(c, n[0]): let baseType = semTypeNode(c, n[1], nil).skipTypes({tyTypeDesc}) let t = newTypeS(targetType.kind, c) if targetType.kind == tyOwned: t.flags.incl tfHasOwned t.rawAddSonNoPropagationOfTypeFlags baseType result = newNodeI(nkType, n.info) result.typ = makeTypeDesc(c, t) return result.add copyTree(n[0]) # special case to make MyObject(x = 3) produce a nicer error message: if n[1].kind == nkExprEqExpr and targetType.skipTypes(abstractPtrs).kind == tyObject: localError(c.config, n.info, "object construction uses ':', not '='") var op = semExprWithType(c, n[1]) if targetType.kind != tyGenericParam and targetType.isMetaType: let final = inferWithMetatype(c, targetType, op, true) result.add final result.typ = final.typ return result.typ = targetType # XXX op is overwritten later on, this is likely added too early # here or needs to be overwritten too then. result.add op if targetType.kind == tyGenericParam: result.typ = makeTypeFromExpr(c, copyTree(result)) return result if not isSymChoice(op): let status = checkConvertible(c, result.typ, op) case status of convOK: # handle SomeProcType(SomeGenericProc) if op.kind == nkSym and op.sym.isGenericRoutine: result[1] = fitNode(c, result.typ, result[1], result.info) elif op.kind in {nkPar, nkTupleConstr} and targetType.kind == tyTuple: op = fitNode(c, targetType, op, result.info) of convNotNeedeed: message(c.config, n.info, hintConvFromXtoItselfNotNeeded, result.typ.typeToString) of convNotLegal: result = fitNode(c, result.typ, result[1], result.info) if result == nil: localError(c.config, n.info, "illegal conversion from '$1' to '$2'" % [op.typ.typeToString, result.typ.typeToString]) of convNotInRange: let value = if op.kind in {nkCharLit..nkUInt64Lit}: $op.getInt else: $op.getFloat localError(c.config, n.info, errGenerated, value & " can't be converted to " & result.typ.typeToString) else: for i in 0..= isSubtype # isNone # `res = sameType(t1, t2)` would be wrong, eg for `int is (int|float)` result = newIntNode(nkIntLit, ord(res)) result.typ = n.typ proc semIs(c: PContext, n: PNode, flags: TExprFlags): PNode = if n.len != 3: localError(c.config, n.info, "'is' operator takes 2 arguments") let boolType = getSysType(c.graph, n.info, tyBool) result = n n.typ = boolType var liftLhs = true n[1] = semExprWithType(c, n[1], {efDetermineType, efWantIterator}) if n[2].kind notin {nkStrLit..nkTripleStrLit}: let t2 = semTypeNode(c, n[2], nil) n[2] = newNodeIT(nkType, n[2].info, t2) if t2.kind == tyStatic: let evaluated = tryConstExpr(c, n[1]) if evaluated != nil: c.fixupStaticType(evaluated) n[1] = evaluated else: result = newIntNode(nkIntLit, 0) result.typ = boolType return elif t2.kind == tyTypeDesc and (t2.base.kind == tyNone or tfExplicit in t2.flags): # When the right-hand side is an explicit type, we must # not allow regular values to be matched against the type: liftLhs = false else: n[2] = semExpr(c, n[2]) var lhsType = n[1].typ if lhsType.kind != tyTypeDesc: if liftLhs: n[1] = makeTypeSymNode(c, lhsType, n[1].info) lhsType = n[1].typ else: if lhsType.base.kind == tyNone or (c.inGenericContext > 0 and lhsType.base.containsGenericType): # BUGFIX: don't evaluate this too early: ``T is void`` return result = isOpImpl(c, n, flags) proc semOpAux(c: PContext, n: PNode) = const flags = {efDetermineType} for i in 1.. 0 and n[0].kind == nkExprColonExpr: # named tuple? for i in 0.. lastOrd(c.config, newType): localError(c.config, n.info, "cannot convert " & $value & " to " & typeToString(newType)) of nkFloatLit..nkFloat64Lit: if check and not floatRangeCheck(n.floatVal, newType): localError(c.config, n.info, errFloatToString % [$n.floatVal, typeToString(newType)]) else: discard n.typ = newType proc arrayConstrType(c: PContext, n: PNode): PType = var typ = newTypeS(tyArray, c) rawAddSon(typ, nil) # index type if n.len == 0: rawAddSon(typ, newTypeS(tyEmpty, c)) # needs an empty basetype! else: var t = skipTypes(n[0].typ, {tyGenericInst, tyVar, tyLent, tyOrdinal, tyAlias, tySink}) addSonSkipIntLit(typ, t) typ[0] = makeRangeType(c, 0, n.len - 1, n.info) result = typ proc semArrayConstr(c: PContext, n: PNode, flags: TExprFlags): PNode = result = newNodeI(nkBracket, n.info) result.typ = newTypeS(tyArray, c) rawAddSon(result.typ, nil) # index type var firstIndex, lastIndex: Int128 indexType = getSysType(c.graph, n.info, tyInt) lastValidIndex = lastOrd(c.config, indexType) if n.len == 0: rawAddSon(result.typ, newTypeS(tyEmpty, c)) # needs an empty basetype! lastIndex = toInt128(-1) else: var x = n[0] if x.kind == nkExprColonExpr and x.len == 2: var idx = semConstExpr(c, x[0]) if not isOrdinalType(idx.typ): localError(c.config, idx.info, "expected ordinal value for array " & "index, got '$1'" % renderTree(idx)) else: firstIndex = getOrdValue(idx) lastIndex = firstIndex indexType = idx.typ lastValidIndex = lastOrd(c.config, indexType) x = x[1] let yy = semExprWithType(c, x) var typ = yy.typ result.add yy #var typ = skipTypes(result[0].typ, {tyGenericInst, tyVar, tyLent, tyOrdinal}) for i in 1.. 1: for i in 1.. we don't want the restriction # to 'skIterator' anymore; skIterator is preferred in sigmatch already # for typeof support. # for ``type(countup(1,3))``, see ``tests/ttoseq``. result = semOverloadedCall(c, n, nOrig, {skProc, skFunc, skMethod, skConverter, skMacro, skTemplate, skIterator}, flags) else: result = semOverloadedCall(c, n, nOrig, {skProc, skFunc, skMethod, skConverter, skMacro, skTemplate}, flags) if result != nil: if result[0].kind != nkSym: internalError(c.config, "semOverloadedCallAnalyseEffects") return let callee = result[0].sym case callee.kind of skMacro, skTemplate: discard else: if callee.kind == skIterator and callee.id == c.p.owner.id: localError(c.config, n.info, errRecursiveDependencyIteratorX % callee.name.s) # error correction, prevents endless for loop elimination in transf. # See bug #2051: result[0] = newSymNode(errorSym(c, n)) proc semObjConstr(c: PContext, n: PNode, flags: TExprFlags): PNode proc resolveIndirectCall(c: PContext; n, nOrig: PNode; t: PType): TCandidate = initCandidate(c, result, t) matches(c, n, nOrig, result) if result.state != csMatch: # try to deref the first argument: if implicitDeref in c.features and canDeref(n): n[1] = n[1].tryDeref initCandidate(c, result, t) matches(c, n, nOrig, result) proc bracketedMacro(n: PNode): PSym = if n.len >= 1 and n[0].kind == nkSym: result = n[0].sym if result.kind notin {skMacro, skTemplate}: result = nil proc setGenericParams(c: PContext, n: PNode) = for i in 1.. 1: msg.add(", ") let nt = n[i].typ msg.add(typeToString(nt)) if nt.kind == tyError: hasErrorType = true break if not hasErrorType: msg.add(">\nbut expected one of: \n" & typeToString(n[0].typ)) localError(c.config, n.info, msg) return errorNode(c, n) result = nil else: result = m.call instGenericConvertersSons(c, result, m) elif t != nil and t.kind == tyTypeDesc: if n.len == 1: return semObjConstr(c, n, flags) return semConv(c, n) else: result = overloadedCallOpr(c, n) # Now that nkSym does not imply an iteration over the proc/iterator space, # the old ``prc`` (which is likely an nkIdent) has to be restored: if result == nil: # XXX: hmm, what kind of symbols will end up here? # do we really need to try the overload resolution? n[0] = prc nOrig[0] = prc n.flags.incl nfExprCall result = semOverloadedCallAnalyseEffects(c, n, nOrig, flags) if result == nil: return errorNode(c, n) elif result.kind notin nkCallKinds: # the semExpr() in overloadedCallOpr can even break this condition! # See bug #904 of how to trigger it: return result #result = afterCallActions(c, result, nOrig, flags) if result[0].kind == nkSym: result = afterCallActions(c, result, nOrig, flags) else: fixAbstractType(c, result) analyseIfAddressTakenInCall(c, result) proc semDirectOp(c: PContext, n: PNode, flags: TExprFlags): PNode = # this seems to be a hotspot in the compiler! let nOrig = n.copyTree #semLazyOpAux(c, n) result = semOverloadedCallAnalyseEffects(c, n, nOrig, flags) if result != nil: result = afterCallActions(c, result, nOrig, flags) else: result = errorNode(c, n) proc buildEchoStmt(c: PContext, n: PNode): PNode = # we MUST not check 'n' for semantics again here! But for now we give up: result = newNodeI(nkCall, n.info) var e = strTableGet(c.graph.systemModule.tab, getIdent(c.cache, "echo")) if e != nil: result.add(newSymNode(e)) else: localError(c.config, n.info, "system needs: echo") result.add(errorNode(c, n)) result.add(n) result = semExpr(c, result) proc semExprNoType(c: PContext, n: PNode): PNode = let isPush = c.config.hasHint(hintExtendedContext) if isPush: pushInfoContext(c.config, n.info) result = semExpr(c, n, {efWantStmt}) discardCheck(c, result, {}) if isPush: popInfoContext(c.config) proc isTypeExpr(n: PNode): bool = case n.kind of nkType, nkTypeOfExpr: result = true of nkSym: result = n.sym.kind == skType else: result = false proc createSetType(c: PContext; baseType: PType): PType = assert baseType != nil result = newTypeS(tySet, c) rawAddSon(result, baseType) proc lookupInRecordAndBuildCheck(c: PContext, n, r: PNode, field: PIdent, check: var PNode): PSym = # transform in a node that contains the runtime check for the # field, if it is in a case-part... result = nil case r.kind of nkRecList: for i in 0.. 0 or (n.kind notin nkCallKinds and s.requiredParams > 0): markUsed(c, n.info, s) onUse(n.info, s) result = symChoice(c, n, s, scClosed) else: result = semMacroExpr(c, n, n, s, flags) of skTemplate: if efNoEvaluateGeneric in flags and s.ast[genericParamsPos].len > 0 or (n.kind notin nkCallKinds and s.requiredParams > 0) or sfCustomPragma in sym.flags: let info = getCallLineInfo(n) markUsed(c, info, s) onUse(info, s) result = symChoice(c, n, s, scClosed) else: result = semTemplateExpr(c, n, s, flags) of skParam: markUsed(c, n.info, s) onUse(n.info, s) if s.typ != nil and s.typ.kind == tyStatic and s.typ.n != nil: # XXX see the hack in sigmatch.nim ... return s.typ.n elif sfGenSym in s.flags: # the owner should have been set by now by addParamOrResult internalAssert c.config, s.owner != nil if c.p.wasForwarded: # gensym'ed parameters that nevertheless have been forward declared # need a special fixup: let realParam = c.p.owner.typ.n[s.position+1] internalAssert c.config, realParam.kind == nkSym and realParam.sym.kind == skParam return newSymNode(c.p.owner.typ.n[s.position+1].sym, n.info) elif c.p.owner.kind == skMacro: # gensym'ed macro parameters need a similar hack (see bug #1944): var u = searchInScopes(c, s.name) internalAssert c.config, u != nil and u.kind == skParam and u.owner == s.owner return newSymNode(u, n.info) result = newSymNode(s, n.info) of skVar, skLet, skResult, skForVar: if s.magic == mNimvm: localError(c.config, n.info, "illegal context for 'nimvm' magic") markUsed(c, n.info, s) onUse(n.info, s) result = newSymNode(s, n.info) # We cannot check for access to outer vars for example because it's still # not sure the symbol really ends up being used: # var len = 0 # but won't be called # genericThatUsesLen(x) # marked as taking a closure? of skGenericParam: onUse(n.info, s) if s.typ.kind == tyStatic: result = newSymNode(s, n.info) result.typ = s.typ elif s.ast != nil: result = semExpr(c, s.ast) else: n.typ = s.typ return n of skType: markUsed(c, n.info, s) onUse(n.info, s) if s.typ.kind == tyStatic and s.typ.base.kind != tyNone and s.typ.n != nil: return s.typ.n result = newSymNode(s, n.info) result.typ = makeTypeDesc(c, s.typ) of skField: var p = c.p while p != nil and p.selfSym == nil: p = p.next if p != nil and p.selfSym != nil: var ty = skipTypes(p.selfSym.typ, {tyGenericInst, tyVar, tyLent, tyPtr, tyRef, tyAlias, tySink, tyOwned}) while tfBorrowDot in ty.flags: ty = ty.skipTypes({tyDistinct}) var check: PNode = nil if ty.kind == tyObject: while true: check = nil let f = lookupInRecordAndBuildCheck(c, n, ty.n, s.name, check) if f != nil and fieldVisible(c, f): # is the access to a public field or in the same module or in a friend? doAssert f == s markUsed(c, n.info, f) onUse(n.info, f) result = newNodeIT(nkDotExpr, n.info, f.typ) result.add makeDeref(newSymNode(p.selfSym)) result.add newSymNode(f) # we now have the correct field if check != nil: check[0] = result check.typ = result.typ result = check return result if ty[0] == nil: break ty = skipTypes(ty[0], skipPtrs) # old code, not sure if it's live code: markUsed(c, n.info, s) onUse(n.info, s) result = newSymNode(s, n.info) else: let info = getCallLineInfo(n) #if efInCall notin flags: markUsed(c, info, s) onUse(info, s) result = newSymNode(s, info) proc tryReadingGenericParam(c: PContext, n: PNode, i: PIdent, t: PType): PNode = case t.kind of tyTypeParamsHolders: result = readTypeParameter(c, t, i, n.info) if result == c.graph.emptyNode: result = n n.typ = makeTypeFromExpr(c, n.copyTree) of tyUserTypeClasses: if t.isResolvedUserTypeClass: result = readTypeParameter(c, t, i, n.info) else: n.typ = makeTypeFromExpr(c, copyTree(n)) result = n of tyGenericParam, tyAnything: n.typ = makeTypeFromExpr(c, copyTree(n)) result = n else: discard proc tryReadingTypeField(c: PContext, n: PNode, i: PIdent, ty: PType): PNode = var ty = ty.skipTypes(tyDotOpTransparent) case ty.kind of tyEnum: # look up if the identifier belongs to the enum: var f = PSym(nil) while ty != nil: f = getSymFromList(ty.n, i) if f != nil: break ty = ty.sons[0] # enum inheritance if f != nil: result = newSymNode(f) result.info = n.info result.typ = ty markUsed(c, n.info, f) onUse(n.info, f) of tyObject, tyTuple: if ty.n != nil and ty.n.kind == nkRecList: let field = lookupInRecord(ty.n, i) if field != nil: n.typ = makeTypeDesc(c, field.typ) result = n of tyGenericInst: result = tryReadingTypeField(c, n, i, ty.lastSon) if result == nil: result = tryReadingGenericParam(c, n, i, ty) else: result = tryReadingGenericParam(c, n, i, ty) proc builtinFieldAccess(c: PContext, n: PNode, flags: TExprFlags): PNode = ## returns nil if it's not a built-in field access checkSonsLen(n, 2, c.config) # tests/bind/tbindoverload.nim wants an early exit here, but seems to # work without now. template/tsymchoicefield doesn't like an early exit # here at all! #if isSymChoice(n[1]): return when defined(nimsuggest): if c.config.cmd == cmdIdeTools: suggestExpr(c, n) if exactEquals(c.config.m.trackPos, n[1].info): suggestExprNoCheck(c, n) var s = qualifiedLookUp(c, n, {checkAmbiguity, checkUndeclared, checkModule}) if s != nil: if s.kind in OverloadableSyms: result = symChoice(c, n, s, scClosed) if result.kind == nkSym: result = semSym(c, n, s, flags) else: markUsed(c, n[1].info, s) result = semSym(c, n, s, flags) onUse(n[1].info, s) return n[0] = semExprWithType(c, n[0], flags+{efDetermineType}) #restoreOldStyleType(n[0]) var i = considerQuotedIdent(c, n[1], n) var ty = n[0].typ var f: PSym = nil result = nil if ty.kind == tyTypeDesc: if ty.base.kind == tyNone: # This is a still unresolved typedesc parameter. # If this is a regular proc, then all bets are off and we must return # tyFromExpr, but when this happen in a macro this is not a built-in # field access and we leave the compiler to compile a normal call: if getCurrOwner(c).kind != skMacro: n.typ = makeTypeFromExpr(c, n.copyTree) return n else: return nil else: return tryReadingTypeField(c, n, i, ty.base) elif isTypeExpr(n.sons[0]): return tryReadingTypeField(c, n, i, ty) if ty.kind in tyUserTypeClasses and ty.isResolvedUserTypeClass: ty = ty.lastSon ty = skipTypes(ty, {tyGenericInst, tyVar, tyLent, tyPtr, tyRef, tyOwned, tyAlias, tySink}) while tfBorrowDot in ty.flags: ty = ty.skipTypes({tyDistinct}) var check: PNode = nil if ty.kind == tyObject: while true: check = nil f = lookupInRecordAndBuildCheck(c, n, ty.n, i, check) if f != nil: break if ty[0] == nil: break ty = skipTypes(ty[0], skipPtrs) if f != nil: let visibilityCheckNeeded = if n[1].kind == nkSym and n[1].sym == f: false # field lookup was done already, likely by hygienic template or bindSym else: true if not visibilityCheckNeeded or fieldVisible(c, f): # is the access to a public field or in the same module or in a friend? markUsed(c, n[1].info, f) onUse(n[1].info, f) n[0] = makeDeref(n[0]) n[1] = newSymNode(f) # we now have the correct field n.typ = f.typ if check == nil: result = n else: check[0] = n check.typ = n.typ result = check elif ty.kind == tyTuple and ty.n != nil: f = getSymFromList(ty.n, i) if f != nil: markUsed(c, n[1].info, f) onUse(n[1].info, f) n[0] = makeDeref(n[0]) n[1] = newSymNode(f) n.typ = f.typ result = n # we didn't find any field, let's look for a generic param if result == nil: let t = n[0].typ.skipTypes(tyDotOpTransparent) result = tryReadingGenericParam(c, n, i, t) proc dotTransformation(c: PContext, n: PNode): PNode = if isSymChoice(n[1]): result = newNodeI(nkDotCall, n.info) result.add n[1] result.add copyTree(n[0]) else: var i = considerQuotedIdent(c, n[1], n) result = newNodeI(nkDotCall, n.info) result.flags.incl nfDotField result.add newIdentNode(i, n[1].info) result.add copyTree(n[0]) proc semFieldAccess(c: PContext, n: PNode, flags: TExprFlags): PNode = # this is difficult, because the '.' is used in many different contexts # in Nim. We first allow types in the semantic checking. result = builtinFieldAccess(c, n, flags) if result == nil: result = dotTransformation(c, n) proc buildOverloadedSubscripts(n: PNode, ident: PIdent): PNode = result = newNodeI(nkCall, n.info) result.add(newIdentNode(ident, n.info)) for s in n: result.add s proc semDeref(c: PContext, n: PNode): PNode = checkSonsLen(n, 1, c.config) n[0] = semExprWithType(c, n[0]) result = n var t = skipTypes(n[0].typ, {tyGenericInst, tyVar, tyLent, tyAlias, tySink, tyOwned}) case t.kind of tyRef, tyPtr: n.typ = t.lastSon else: result = nil #GlobalError(n[0].info, errCircumNeedsPointer) proc semSubscript(c: PContext, n: PNode, flags: TExprFlags): PNode = ## returns nil if not a built-in subscript operator; also called for the ## checking of assignments if n.len == 1: let x = semDeref(c, n) if x == nil: return nil result = newNodeIT(nkDerefExpr, x.info, x.typ) result.add(x[0]) return checkMinSonsLen(n, 2, c.config) # make sure we don't evaluate generic macros/templates n[0] = semExprWithType(c, n[0], {efNoEvaluateGeneric}) var arr = skipTypes(n[0].typ, {tyGenericInst, tyUserTypeClassInst, tyOwned, tyVar, tyLent, tyPtr, tyRef, tyAlias, tySink}) if arr.kind == tyStatic: if arr.base.kind == tyNone: result = n result.typ = semStaticType(c, n[1], nil) return elif arr.n != nil: return semSubscript(c, arr.n, flags) else: arr = arr.base case arr.kind of tyArray, tyOpenArray, tyVarargs, tySequence, tyString, tyCString, tyUncheckedArray: if n.len != 2: return nil n[0] = makeDeref(n[0]) for i in 1..= 0 and idx < arr.len: n.typ = arr[toInt(idx)] else: localError(c.config, n.info, "invalid index value for tuple subscript") result = n else: result = nil else: let s = if n[0].kind == nkSym: n[0].sym elif n[0].kind in nkSymChoices: n[0][0].sym else: nil if s != nil: case s.kind of skProc, skFunc, skMethod, skConverter, skIterator: # type parameters: partial generic specialization n[0] = semSymGenericInstantiation(c, n[0], s) result = explicitGenericInstantiation(c, n, s) if result == n: n[0] = copyTree(result) else: n[0] = result of skMacro, skTemplate: if efInCall in flags: # We are processing macroOrTmpl[] in macroOrTmpl[](...) call. # Return as is, so it can be transformed into complete macro or # template call in semIndirectOp caller. result = n else: # We are processing macroOrTmpl[] not in call. Transform it to the # macro or template call with generic arguments here. n.transitionSonsKind(nkCall) case s.kind of skMacro: result = semMacroExpr(c, n, n, s, flags) of skTemplate: result = semTemplateExpr(c, n, s, flags) else: discard of skType: result = symNodeFromType(c, semTypeNode(c, n, nil), n.info) else: discard proc semArrayAccess(c: PContext, n: PNode, flags: TExprFlags): PNode = result = semSubscript(c, n, flags) if result == nil: # overloaded [] operator: result = semExpr(c, buildOverloadedSubscripts(n, getIdent(c.cache, "[]"))) proc propertyWriteAccess(c: PContext, n, nOrig, a: PNode): PNode = var id = considerQuotedIdent(c, a[1], a) var setterId = newIdentNode(getIdent(c.cache, 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], semExprWithType(c, n[1])]) result.flags.incl nfDotSetter let orig = newNode(nkCall, n.info, sons = @[setterId, aOrig[0], nOrig[1]]) result = semOverloadedCallAnalyseEffects(c, result, orig, {}) if result != nil: result = afterCallActions(c, result, nOrig, {}) #fixAbstractType(c, result) #analyseIfAddressTakenInCall(c, result) proc takeImplicitAddr(c: PContext, n: PNode; isLent: bool): PNode = # See RFC #7373, calls returning 'var T' are assumed to # return a view into the first argument (if there is one): let root = exprRoot(n) if root != nil and root.owner == c.p.owner: if root.kind in {skLet, skVar, skTemp} and sfGlobal notin root.flags: localError(c.config, n.info, "'$1' escapes its stack frame; context: '$2'; see $3/var_t_return.html" % [ root.name.s, renderTree(n, {renderNoComments}), explanationsBaseUrl]) elif root.kind == skParam and root.position != 0: localError(c.config, n.info, "'$1' is not the first parameter; context: '$2'; see $3/var_t_return.html" % [ root.name.s, renderTree(n, {renderNoComments}), explanationsBaseUrl]) case n.kind of nkHiddenAddr, nkAddr: return n of nkDerefExpr: return n[0] of nkBracketExpr: if n.len == 1: return n[0] of nkHiddenDeref: # issue #13848 # `proc fun(a: var int): var int = a` discard else: discard let valid = isAssignable(c, n, isLent) if valid != arLValue: if valid == arLocalLValue: localError(c.config, n.info, errXStackEscape % renderTree(n, {renderNoComments})) else: localError(c.config, n.info, errExprHasNoAddress) result = newNodeIT(nkHiddenAddr, n.info, makePtrType(c, n.typ)) result.add(n) proc asgnToResultVar(c: PContext, n, le, ri: PNode) {.inline.} = if le.kind == nkHiddenDeref: var x = le[0] if x.typ.kind in {tyVar, tyLent} and x.kind == nkSym and x.sym.kind == skResult: n[0] = x # 'result[]' --> 'result' n[1] = takeImplicitAddr(c, ri, x.typ.kind == tyLent) x.typ.flags.incl tfVarIsPtr #echo x.info, " setting it for this type ", typeToString(x.typ), " ", n.info proc borrowCheck(c: PContext, n, le, ri: PNode) = const PathKinds0 = {nkDotExpr, nkCheckedFieldExpr, nkBracketExpr, nkAddr, nkHiddenAddr, nkObjDownConv, nkObjUpConv} PathKinds1 = {nkHiddenStdConv, nkHiddenSubConv} proc getRoot(n: PNode; followDeref: bool): PNode = result = n while true: case result.kind of nkDerefExpr, nkHiddenDeref: if followDeref: result = result[0] else: break of PathKinds0: result = result[0] of PathKinds1: result = result[1] else: break proc scopedLifetime(c: PContext; ri: PNode): bool {.inline.} = let n = getRoot(ri, followDeref = false) result = (ri.kind in nkCallKinds+{nkObjConstr}) or (n.kind == nkSym and n.sym.owner == c.p.owner and n.sym.kind != skResult) proc escapes(c: PContext; le: PNode): bool {.inline.} = # param[].foo[] = self definitely escapes, we don't need to # care about pointer derefs: let n = getRoot(le, followDeref = true) result = n.kind == nkSym and n.sym.kind == skParam # Special typing rule: do not allow to pass 'owned T' to 'T' in 'result = x': const absInst = abstractInst - {tyOwned} if ri.typ != nil and ri.typ.skipTypes(absInst).kind == tyOwned and le.typ != nil and le.typ.skipTypes(absInst).kind != tyOwned and scopedLifetime(c, ri): if le.kind == nkSym and le.sym.kind == skResult: localError(c.config, n.info, "cannot return an owned pointer as an unowned pointer; " & "use 'owned(" & typeToString(le.typ) & ")' as the return type") elif escapes(c, le): localError(c.config, n.info, "assignment produces a dangling ref: the unowned ref lives longer than the owned ref") template resultTypeIsInferrable(typ: PType): untyped = typ.isMetaType and typ.kind != tyTypeDesc proc goodLineInfo(arg: PNode): TLineInfo = if arg.kind == nkStmtListExpr and arg.len > 0: goodLineInfo(arg[^1]) else: arg.info proc semAsgn(c: PContext, n: PNode; mode=asgnNormal): PNode = checkSonsLen(n, 2, c.config) var a = n[0] case a.kind of nkDotExpr: # r.f = x # --> `f=` (r, x) let nOrig = n.copyTree a = builtinFieldAccess(c, a, {efLValue}) if a == nil: a = propertyWriteAccess(c, n, nOrig, n[0]) if a != nil: return a # we try without the '='; proc that return 'var' or macros are still # possible: a = dotTransformation(c, n[0]) if a.kind == nkDotCall: a.transitionSonsKind(nkCall) a = semExprWithType(c, a, {efLValue}) of nkBracketExpr: # a[i] = x # --> `[]=`(a, i, x) a = semSubscript(c, a, {efLValue}) if a == nil: result = buildOverloadedSubscripts(n[0], getIdent(c.cache, "[]=")) result.add(n[1]) if mode == noOverloadedSubscript: bracketNotFoundError(c, result) return n else: result = semExprNoType(c, result) return result of nkCurlyExpr: # a{i} = x --> `{}=`(a, i, x) result = buildOverloadedSubscripts(n[0], getIdent(c.cache, "{}=")) result.add(n[1]) return semExprNoType(c, result) of nkPar, nkTupleConstr: if a.len >= 2: # unfortunately we need to rewrite ``(x, y) = foo()`` already here so # that overloading of the assignment operator still works. Usually we # prefer to do these rewritings in transf.nim: return semStmt(c, lowerTupleUnpackingForAsgn(c.graph, n, c.p.owner), {}) else: a = semExprWithType(c, a, {efLValue}) else: a = semExprWithType(c, a, {efLValue}) n[0] = a # a = b # both are vars, means: a[] = b[] # a = b # b no 'var T' means: a = addr(b) var le = a.typ if le == nil: localError(c.config, a.info, "expression has no type") elif (skipTypes(le, {tyGenericInst, tyAlias, tySink}).kind != tyVar and isAssignable(c, a) == arNone) or skipTypes(le, abstractVar).kind in {tyOpenArray, tyVarargs}: # Direct assignment to a discriminant is allowed! localError(c.config, a.info, errXCannotBeAssignedTo % renderTree(a, {renderNoComments})) else: let lhs = n[0] lhsIsResult = lhs.kind == nkSym and lhs.sym.kind == skResult var rhs = semExprWithType(c, n[1], if lhsIsResult: {efAllowDestructor} else: {}) if lhsIsResult: n.typ = c.enforceVoidContext if c.p.owner.kind != skMacro and resultTypeIsInferrable(lhs.sym.typ): var rhsTyp = rhs.typ if rhsTyp.kind in tyUserTypeClasses and rhsTyp.isResolvedUserTypeClass: rhsTyp = rhsTyp.lastSon if cmpTypes(c, lhs.typ, rhsTyp) in {isGeneric, isEqual}: internalAssert c.config, c.p.resultSym != nil # Make sure the type is valid for the result variable typeAllowedCheck(c.config, n.info, rhsTyp, skResult) lhs.typ = rhsTyp c.p.resultSym.typ = rhsTyp c.p.owner.typ[0] = rhsTyp else: typeMismatch(c.config, n.info, lhs.typ, rhsTyp) borrowCheck(c, n, lhs, rhs) n[1] = fitNode(c, le, rhs, goodLineInfo(n[1])) when false: liftTypeBoundOps(c, lhs.typ, lhs.info) fixAbstractType(c, n) asgnToResultVar(c, n, n[0], n[1]) result = n proc semReturn(c: PContext, n: PNode): PNode = result = n checkSonsLen(n, 1, c.config) if c.p.owner.kind in {skConverter, skMethod, skProc, skFunc, skMacro} or (not c.p.owner.typ.isNil and isClosureIterator(c.p.owner.typ)): if n[0].kind != nkEmpty: # transform ``return expr`` to ``result = expr; return`` if c.p.resultSym != nil: var a = newNodeI(nkAsgn, n[0].info) a.add newSymNode(c.p.resultSym) a.add n[0] n[0] = semAsgn(c, a) # optimize away ``result = result``: if n[0][1].kind == nkSym and n[0][1].sym == c.p.resultSym: n[0] = c.graph.emptyNode else: localError(c.config, n.info, errNoReturnTypeDeclared) else: localError(c.config, n.info, "'return' not allowed here") proc semProcBody(c: PContext, n: PNode): PNode = openScope(c) result = semExpr(c, n) if c.p.resultSym != nil and not isEmptyType(result.typ): if result.kind == nkNilLit: # or ImplicitlyDiscardable(result): # new semantic: 'result = x' triggers the void context result.typ = nil elif result.kind == nkStmtListExpr and result.typ.kind == tyNil: # to keep backwards compatibility bodies like: # nil # # comment # are not expressions: fixNilType(c, result) else: var a = newNodeI(nkAsgn, n.info, 2) a[0] = newSymNode(c.p.resultSym) a[1] = result result = semAsgn(c, a) else: discardCheck(c, result, {}) if c.p.owner.kind notin {skMacro, skTemplate} and c.p.resultSym != nil and c.p.resultSym.typ.isMetaType: if isEmptyType(result.typ): # we inferred a 'void' return type: c.p.resultSym.typ = errorType(c) c.p.owner.typ[0] = nil else: localError(c.config, c.p.resultSym.info, errCannotInferReturnType % c.p.owner.name.s) if isInlineIterator(c.p.owner.typ) and c.p.owner.typ[0] != nil and c.p.owner.typ[0].kind == tyUntyped: localError(c.config, c.p.owner.info, errCannotInferReturnType % c.p.owner.name.s) closeScope(c) proc semYieldVarResult(c: PContext, n: PNode, restype: PType) = var t = skipTypes(restype, {tyGenericInst, tyAlias, tySink}) case t.kind of tyVar, tyLent: t.flags.incl tfVarIsPtr # bugfix for #4048, #4910, #6892 if n[0].kind in {nkHiddenStdConv, nkHiddenSubConv}: n[0] = n[0][1] n[0] = takeImplicitAddr(c, n[0], t.kind == tyLent) of tyTuple: for i in 0..= 2: localError(c.config, n.info, "ambiguous symbol in 'getAst' context: " & $macroCall) else: let info = macroCall[0].info macroCall[0] = newSymNode(cand, info) markUsed(c, info, cand) onUse(info, cand) # we just perform overloading resolution here: #n[1] = semOverloadedCall(c, macroCall, macroCall, {skTemplate, skMacro}) else: localError(c.config, n.info, "getAst takes a call, but got " & n.renderTree) # Preserve the magic symbol in order to be handled in evals.nim internalAssert c.config, n[0].sym.magic == mExpandToAst #n.typ = getSysSym("NimNode").typ # expandedSym.getReturnType if n.kind == nkStmtList and n.len == 1: result = n[0] else: result = n result.typ = sysTypeFromName(c.graph, n.info, "NimNode") proc semExpandToAst(c: PContext, n: PNode, magicSym: PSym, flags: TExprFlags = {}): PNode = if n.len == 2: n[0] = newSymNode(magicSym, n.info) result = semExpandToAst(c, n) else: result = semDirectOp(c, n, flags) proc processQuotations(c: PContext; n: var PNode, op: string, quotes: var seq[PNode], ids: var seq[PNode]) = template returnQuote(q) = quotes.add q n = newIdentNode(getIdent(c.cache, $quotes.len), n.info) ids.add n return if n.kind == nkPrefix: checkSonsLen(n, 2, c.config) if n[0].kind == nkIdent: var examinedOp = n[0].ident.s if examinedOp == op: returnQuote n[1] elif examinedOp.startsWith(op): n[0] = newIdentNode(getIdent(c.cache, examinedOp.substr(op.len)), n.info) elif n.kind == nkAccQuoted and op == "``": returnQuote n[0] elif n.kind == nkIdent: if n.ident.s == "result": n = ids[0] for i in 0.. 0: dummyTemplate[paramsPos] = newNodeI(nkFormalParams, n.info) dummyTemplate[paramsPos].add getSysSym(c.graph, n.info, "untyped").newSymNode # return type ids.add getSysSym(c.graph, n.info, "untyped").newSymNode # params type ids.add c.graph.emptyNode # no default value dummyTemplate[paramsPos].add newNode(nkIdentDefs, n.info, ids) var tmpl = semTemplateDef(c, dummyTemplate) quotes[0] = tmpl[namePos] # This adds a call to newIdentNode("result") as the first argument to the template call let identNodeSym = getCompilerProc(c.graph, "newIdentNode") # so that new Nim compilers can compile old macros.nim versions, we check for 'nil' # here and provide the old fallback solution: let identNode = if identNodeSym == nil: newIdentNode(getIdent(c.cache, "newIdentNode"), n.info) else: identNodeSym.newSymNode quotes[1] = newNode(nkCall, n.info, @[identNode, newStrNode(nkStrLit, "result")]) result = newNode(nkCall, n.info, @[ createMagic(c.graph, "getAst", mExpandToAst).newSymNode, newNode(nkCall, n.info, quotes)]) result = semExpandToAst(c, result) proc tryExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode = # watch out, hacks ahead: let oldErrorCount = c.config.errorCounter let oldErrorMax = c.config.errorMax let oldCompilesId = c.compilesContextId # if this is a nested 'when compiles', do not increase the ID so that # generic instantiations can still be cached for this level. if c.compilesContextId == 0: inc c.compilesContextIdGenerator c.compilesContextId = c.compilesContextIdGenerator # do not halt after first error: c.config.errorMax = high(int) # open a scope for temporary symbol inclusions: let oldScope = c.currentScope openScope(c) let oldOwnerLen = c.graph.owners.len let oldGenerics = c.generics let oldErrorOutputs = c.config.m.errorOutputs if efExplain notin flags: c.config.m.errorOutputs = {} let oldContextLen = msgs.getInfoContextLen(c.config) let oldInGenericContext = c.inGenericContext let oldInUnrolledContext = c.inUnrolledContext let oldInGenericInst = c.inGenericInst let oldInStaticContext = c.inStaticContext let oldProcCon = c.p c.generics = @[] var err: string try: result = semExpr(c, n, flags) if result != nil and efNoSem2Check notin flags: trackStmt(c, c.module, result, isTopLevel = false) if c.config.errorCounter != oldErrorCount: result = nil except ERecoverableError: discard # undo symbol table changes (as far as it's possible): c.compilesContextId = oldCompilesId c.generics = oldGenerics c.inGenericContext = oldInGenericContext c.inUnrolledContext = oldInUnrolledContext c.inGenericInst = oldInGenericInst c.inStaticContext = oldInStaticContext c.p = oldProcCon msgs.setInfoContextLen(c.config, oldContextLen) setLen(c.graph.owners, oldOwnerLen) c.currentScope = oldScope c.config.m.errorOutputs = oldErrorOutputs c.config.errorCounter = oldErrorCount c.config.errorMax = oldErrorMax proc semCompiles(c: PContext, n: PNode, flags: TExprFlags): PNode = # we replace this node by a 'true' or 'false' node: if n.len != 2: return semDirectOp(c, n, flags) result = newIntNode(nkIntLit, ord(tryExpr(c, n[1], flags) != nil)) result.info = n.info result.typ = getSysType(c.graph, n.info, tyBool) proc semShallowCopy(c: PContext, n: PNode, flags: TExprFlags): PNode = if n.len == 3: # XXX ugh this is really a hack: shallowCopy() can be overloaded only # with procs that take not 2 parameters: result = newNodeI(nkFastAsgn, n.info) result.add(n[1]) result.add(n[2]) result = semAsgn(c, result) else: result = semDirectOp(c, n, flags) proc createFlowVar(c: PContext; t: PType; info: TLineInfo): PType = result = newType(tyGenericInvocation, c.module) addSonSkipIntLit(result, magicsys.getCompilerProc(c.graph, "FlowVar").typ) addSonSkipIntLit(result, t) result = instGenericContainer(c, info, result, allowMetaTypes = false) proc instantiateCreateFlowVarCall(c: PContext; t: PType; info: TLineInfo): PSym = let sym = magicsys.getCompilerProc(c.graph, "nimCreateFlowVar") if sym == nil: localError(c.config, info, "system needs: nimCreateFlowVar") var bindings: TIdTable initIdTable(bindings) bindings.idTablePut(sym.ast[genericParamsPos][0].typ, t) result = c.semGenerateInstance(c, sym, bindings, info) # since it's an instantiation, we unmark it as a compilerproc. Otherwise # codegen would fail: if sfCompilerProc in result.flags: result.flags = result.flags - {sfCompilerProc, sfExportc, sfImportc} result.loc.r = nil proc setMs(n: PNode, s: PSym): PNode = result = n n[0] = newSymNode(s) n[0].info = n.info proc semSizeof(c: PContext, n: PNode): PNode = if n.len != 2: localError(c.config, n.info, errXExpectsTypeOrValue % "sizeof") else: n[1] = semExprWithType(c, n[1], {efDetermineType}) #restoreOldStyleType(n[1]) n.typ = getSysType(c.graph, n.info, tyInt) result = foldSizeOf(c.config, n, n) proc semMagic(c: PContext, n: PNode, s: PSym, flags: TExprFlags): PNode = # this is a hotspot in the compiler! result = n case s.magic # magics that need special treatment of mAddr: markUsed(c, n.info, s) checkSonsLen(n, 2, c.config) result[0] = newSymNode(s, n[0].info) result[1] = semAddrArg(c, n[1], s.name.s == "unsafeAddr") result.typ = makePtrType(c, result[1].typ) of mTypeOf: markUsed(c, n.info, s) result = semTypeOf(c, n) of mDefined: markUsed(c, n.info, s) result = semDefined(c, setMs(n, s), false) of mDefinedInScope: markUsed(c, n.info, s) result = semDefined(c, setMs(n, s), true) of mCompiles: markUsed(c, n.info, s) result = semCompiles(c, setMs(n, s), flags) of mIs: markUsed(c, n.info, s) result = semIs(c, setMs(n, s), flags) of mShallowCopy: markUsed(c, n.info, s) result = semShallowCopy(c, n, flags) of mExpandToAst: markUsed(c, n.info, s) result = semExpandToAst(c, n, s, flags) of mQuoteAst: markUsed(c, n.info, s) result = semQuoteAst(c, n) of mAstToStr: markUsed(c, n.info, s) checkSonsLen(n, 2, c.config) result = newStrNodeT(renderTree(n[1], {renderNoComments}), n, c.graph) result.typ = getSysType(c.graph, n.info, tyString) of mParallel: markUsed(c, n.info, s) if parallel notin c.features: localError(c.config, n.info, "use the {.experimental.} pragma to enable 'parallel'") result = setMs(n, s) var x = n.lastSon if x.kind == nkDo: x = x[bodyPos] inc c.inParallelStmt result[1] = semStmt(c, x, {}) dec c.inParallelStmt of mSpawn: markUsed(c, n.info, s) when defined(leanCompiler): localError(c.config, n.info, "compiler was built without 'spawn' support") result = n else: result = setMs(n, s) for i in 1.. 0) == srFlowVar: result.typ = createFlowVar(c, typ, n.info) else: result.typ = typ result.add instantiateCreateFlowVarCall(c, typ, n.info).newSymNode else: result.add c.graph.emptyNode of mProcCall: markUsed(c, n.info, s) result = setMs(n, s) result[1] = semExpr(c, n[1]) result.typ = n[1].typ of mPlugin: markUsed(c, n.info, s) # semDirectOp with conditional 'afterCallActions': let nOrig = n.copyTree #semLazyOpAux(c, n) result = semOverloadedCallAnalyseEffects(c, n, nOrig, flags) if result == nil: result = errorNode(c, n) else: let callee = result[0].sym if callee.magic == mNone: semFinishOperands(c, result) activate(c, result) fixAbstractType(c, result) analyseIfAddressTakenInCall(c, result) if callee.magic != mNone: result = magicsAfterOverloadResolution(c, result, flags) of mRunnableExamples: markUsed(c, n.info, s) if c.config.cmd == cmdDoc and n.len >= 2 and n.lastSon.kind == nkStmtList: when false: # some of this dead code was moved to `prepareExamples` if sfMainModule in c.module.flags: let inp = toFullPath(c.config, c.module.info) if c.runnableExamples == nil: c.runnableExamples = newTree(nkStmtList, newTree(nkImportStmt, newStrNode(nkStrLit, expandFilename(inp)))) let imports = newTree(nkStmtList) var savedLastSon = copyTree n.lastSon extractImports(savedLastSon, imports) for imp in imports: c.runnableExamples.add imp c.runnableExamples.add newTree(nkBlockStmt, c.graph.emptyNode, copyTree savedLastSon) result = setMs(n, s) else: result = c.graph.emptyNode of mSizeOf: markUsed(c, n.info, s) result = semSizeof(c, setMs(n, s)) else: result = semDirectOp(c, n, flags) 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: untyped) = if semCheck: result = semExpr(c, e) # do not open a new scope! else: result = e # Check if the node is "when nimvm" # when nimvm: # ... # else: # ... var whenNimvm = false var typ = commonTypeBegin if n.len == 2 and n[0].kind == nkElifBranch and n[1].kind == nkElse: let exprNode = n[0][0] if exprNode.kind == nkIdent: whenNimvm = lookUp(c, exprNode).magic == mNimvm elif exprNode.kind == nkSym: whenNimvm = exprNode.sym.magic == mNimvm if whenNimvm: n.flags.incl nfLL for i in 0.. MaxSetElements: typ = makeRangeType(c, 0, MaxSetElements-1, n.info) addSonSkipIntLit(result.typ, typ) for i in 0.. 0: # don't interpret () as type isTupleType = tupexp[0].typ.kind == tyTypeDesc # check if either everything or nothing is tyTypeDesc for i in 1.. 2 + c.compilesContextId: localError(c.config, n.info, errXOnlyAtModuleScope % "import") result = evalImport(c, n) of nkImportExceptStmt: if not isTopLevel(c): localError(c.config, n.info, errXOnlyAtModuleScope % "import") result = evalImportExcept(c, n) of nkFromStmt: if not isTopLevel(c): localError(c.config, n.info, errXOnlyAtModuleScope % "from") result = evalFrom(c, n) of nkIncludeStmt: #if not isTopLevel(c): localError(c.config, n.info, errXOnlyAtModuleScope % "include") result = evalInclude(c, n) of nkExportStmt: if not isTopLevel(c): localError(c.config, n.info, errXOnlyAtModuleScope % "export") result = semExport(c, n) of nkExportExceptStmt: if not isTopLevel(c): localError(c.config, n.info, errXOnlyAtModuleScope % "export") result = semExportExcept(c, n) of nkPragmaBlock: result = semPragmaBlock(c, n) of nkStaticStmt: result = semStaticStmt(c, n) of nkDefer: if c.currentScope == c.topLevelScope: localError(c.config, n.info, "defer statement not supported at top level") n[0] = semExpr(c, n[0]) if not n[0].typ.isEmptyType and not implicitlyDiscardable(n[0]): localError(c.config, n.info, "'defer' takes a 'void' expression") #localError(c.config, n.info, errGenerated, "'defer' not allowed in this context") of nkGotoState, nkState: if n.len != 1 and n.len != 2: illFormedAst(n, c.config) for i in 0..