mirror of
https://github.com/nim-lang/Nim.git
synced 2026-09-01 19:33:42 +00:00
Compare commits
4 Commits
pr_when_ty
...
pr_full_of
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8f3c86a67e | ||
|
|
33e5bfa424 | ||
|
|
b4efcbdbf6 | ||
|
|
269b4985af |
@@ -35,10 +35,6 @@ errors.
|
||||
|
||||
- Adds a new warning `--warning:ImplicitRangeConversion` that detects downsizing implicit conversions to range types (e.g., `int -> range[0..255]` or `range[1..256] -> range[0..255]`) that could cause runtime panics. Safe conversions like `range[0..255] -> range[0..65535]` and explicit casts do not trigger warnings. `int` to `Natural` and `Positive` conversions do not trigger warnings, which can be enabled with `--warning:systemRangeConversion`.
|
||||
|
||||
- Procedure compatibility also checks the backend representation of the
|
||||
parameter and result types, not just their source-level shape. Use
|
||||
`--legacy:procParamTypeBackendAliases` to restore the older behavior.
|
||||
|
||||
## Standard library additions and changes
|
||||
|
||||
[//]: # "Additions:"
|
||||
|
||||
@@ -230,7 +230,7 @@ proc blockLeaveActions(p: BProc, howManyTrys, howManyExcepts: int, isReturnStmt
|
||||
# Called by return and break stmts.
|
||||
# Deals with issues faced when jumping out of try/except/finally stmts.
|
||||
|
||||
var stack = newSeq[tuple[fin: PNode, inExcept: bool, isHidden: bool, label: Natural]](0)
|
||||
var stack = newSeq[tuple[fin: PNode, inExcept: bool, label: Natural]](0)
|
||||
|
||||
inc p.withinBlockLeaveActions
|
||||
for i in 1..howManyTrys:
|
||||
@@ -836,26 +836,12 @@ proc raiseExitCleanup(p: BProc, destroy: string) =
|
||||
p.s(cpsStmts).addGoto("LA" & $p.nestedTryStmts[^1].label & "_")
|
||||
|
||||
proc finallyActions(p: BProc) =
|
||||
if p.config.exc != excGoto:
|
||||
# Walk past compiler-injected `nkHiddenTryStmt` wrappers (e.g. ARC's
|
||||
# destructor try/finally that wraps `except T as e:` bodies) to reach
|
||||
# the user's actual try. We must NOT walk past a real user try whose
|
||||
# body we are currently in, because a raise from there will be caught
|
||||
# by that try's own except branches rather than escaping outward.
|
||||
#
|
||||
# If after skipping wrappers the next entry is a user try in its
|
||||
# except branch (inExcept=true), inline its finally body before the
|
||||
# raise propagates — without this, the C++ sibling-catch rule would
|
||||
# cause the user's catch(...)/finally pair to be bypassed and the
|
||||
# finally would be silently dropped.
|
||||
for i in countdown(p.nestedTryStmts.high, 0):
|
||||
if p.nestedTryStmts[i].isHidden:
|
||||
continue
|
||||
if p.nestedTryStmts[i].inExcept:
|
||||
let finallyBlock = p.nestedTryStmts[i].fin
|
||||
if finallyBlock != nil:
|
||||
genSimpleBlock(p, finallyBlock[0])
|
||||
return
|
||||
if p.config.exc != excGoto and p.nestedTryStmts.len > 0 and p.nestedTryStmts[^1].inExcept:
|
||||
# if the current try stmt have a finally block,
|
||||
# we must execute it before reraising
|
||||
let finallyBlock = p.nestedTryStmts[^1].fin
|
||||
if finallyBlock != nil:
|
||||
genSimpleBlock(p, finallyBlock[0])
|
||||
|
||||
proc raiseInstr(p: BProc; result: var Builder) =
|
||||
if p.config.exc == excGoto:
|
||||
@@ -1199,7 +1185,7 @@ proc genTryCpp(p: BProc, t: PNode, d: var TLoc) =
|
||||
lineCg(p, cpsLocals, "std::exception_ptr T$1_;$n", [etmp])
|
||||
|
||||
let fin = if t[^1].kind == nkFinally: t[^1] else: nil
|
||||
p.nestedTryStmts.add((fin, false, t.kind == nkHiddenTryStmt, 0.Natural))
|
||||
p.nestedTryStmts.add((fin, false, 0.Natural))
|
||||
|
||||
if t.kind == nkHiddenTryStmt:
|
||||
lineCg(p, cpsStmts, "try {$n", [])
|
||||
@@ -1385,7 +1371,7 @@ proc genTryCppOld(p: BProc, t: PNode, d: var TLoc) =
|
||||
genLineDir(p, t)
|
||||
cgsym(p.module, "popCurrentExceptionEx")
|
||||
let fin = if t[^1].kind == nkFinally: t[^1] else: nil
|
||||
p.nestedTryStmts.add((fin, false, t.kind == nkHiddenTryStmt, 0.Natural))
|
||||
p.nestedTryStmts.add((fin, false, 0.Natural))
|
||||
startBlockWith(p):
|
||||
p.s(cpsStmts).add("try {\n")
|
||||
expr(p, t[0], d)
|
||||
@@ -1464,7 +1450,7 @@ proc genTryGoto(p: BProc; t: PNode; d: var TLoc) =
|
||||
let lab = p.labels
|
||||
let hasExcept = t[1].kind == nkExceptBranch
|
||||
if hasExcept: inc p.withinTryWithExcept
|
||||
p.nestedTryStmts.add((fin, false, t.kind == nkHiddenTryStmt, Natural lab))
|
||||
p.nestedTryStmts.add((fin, false, Natural lab))
|
||||
|
||||
p.flags.incl nimErrorFlagAccessed
|
||||
|
||||
@@ -1670,7 +1656,7 @@ proc genTrySetjmp(p: BProc, t: PNode, d: var TLoc) =
|
||||
initElifBranch(p.s(cpsStmts), nonQuirkyIf, removeSinglePar(
|
||||
cOp(Equal, dotField(safePoint, "status"), cIntValue(0))))
|
||||
let fin = if t[^1].kind == nkFinally: t[^1] else: nil
|
||||
p.nestedTryStmts.add((fin, quirkyExceptions, t.kind == nkHiddenTryStmt, 0.Natural))
|
||||
p.nestedTryStmts.add((fin, quirkyExceptions, 0.Natural))
|
||||
expr(p, t[0], d)
|
||||
var quirkyIf = default(IfBuilder)
|
||||
var quirkyScope = default(ScopeBuilder)
|
||||
|
||||
@@ -75,13 +75,10 @@ type
|
||||
flags*: set[TCProcFlag]
|
||||
lastLineInfo*: TLineInfo # to avoid generating excessive 'nimln' statements
|
||||
currLineInfo*: TLineInfo # AST codegen will make this superfluous
|
||||
nestedTryStmts*: seq[tuple[fin: PNode, inExcept: bool, isHidden: bool, label: Natural]]
|
||||
nestedTryStmts*: seq[tuple[fin: PNode, inExcept: bool, label: Natural]]
|
||||
# in how many nested try statements we are
|
||||
# (the vars must be volatile then)
|
||||
# `inExcept` is true when we are in the except part of a try block.
|
||||
# `isHidden` is true for compiler-injected `nkHiddenTryStmt` wrappers
|
||||
# (e.g. ARC's destructor try/finally around `except T as e:` bodies);
|
||||
# finallyActions walks past such wrappers to reach the user's try.
|
||||
# bool is true when are in the except part of a try block
|
||||
finallySafePoints*: seq[Rope] # For correctly cleaning up exceptions when
|
||||
# using return in finally statements
|
||||
labels*: Natural # for generating unique labels in the C proc
|
||||
|
||||
@@ -930,7 +930,7 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
|
||||
if m.len == 0:
|
||||
localError(conf, info, "Cannot resolve filename: " & arg)
|
||||
else:
|
||||
conf.implicitImports.add(if arg.startsWith(stdPrefix): arg else: m)
|
||||
conf.implicitImports.add m
|
||||
of "include":
|
||||
expectArg(conf, switch, arg, pass, info)
|
||||
if pass in {passCmd2, passPP}:
|
||||
|
||||
@@ -488,19 +488,10 @@ proc generateBuildFile(c: DepContext): string =
|
||||
let exeFile = changeFileExt(c.nodes[0].files[0].nimFile, ExeExt)
|
||||
b.addTree "do"
|
||||
b.addIdent "nim_nifc"
|
||||
# Input: .nim file (expanded as argument)
|
||||
# Input: .nim file (expanded as argument) and .nif file (dependency)
|
||||
b.addTree "input"
|
||||
b.addStrLit mainNif
|
||||
b.endTree()
|
||||
# Also depend on the semmed .nif files of the main module and all its
|
||||
# dependencies. nifmake's topological sort orders nodes by depth; without
|
||||
# these inputs the nim_nifc node sits at depth 1 (no recognized inputs)
|
||||
# alongside the nifler nodes and runs *before* the nim_m steps that
|
||||
# produce the .nif files it needs to read.
|
||||
for node in c.nodes:
|
||||
b.addTree "input"
|
||||
b.addStrLit c.semmedFile(node.files[0])
|
||||
b.endTree()
|
||||
b.addTree "output"
|
||||
b.addStrLit exeFile
|
||||
b.endTree()
|
||||
|
||||
@@ -13,7 +13,7 @@ import
|
||||
ast, msgs, options, idents, lookups,
|
||||
semdata, modulepaths, sigmatch, lineinfos,
|
||||
modulegraphs, wordrecg
|
||||
from std/strutils import `%`, startsWith, replace
|
||||
from std/strutils import `%`, startsWith
|
||||
from std/sequtils import addUnique
|
||||
import std/[sets, tables, intsets]
|
||||
|
||||
@@ -304,9 +304,9 @@ proc myImportModule(c: PContext, n: var PNode, importStmtResult: PNode): PSym =
|
||||
var prefix = ""
|
||||
if realModule.constraint != nil: prefix = realModule.constraint.strVal & "; "
|
||||
message(c.config, n.info, warnDeprecated, prefix & realModule.name.s & " is deprecated")
|
||||
let moduleNameNorm = getModuleName(c.config, n).replace("\\", "/")
|
||||
if belongsToStdlib(c.graph, result) and not startsWith(moduleNameNorm, stdPrefix) and
|
||||
not startsWith(moduleNameNorm, "system/") and not startsWith(moduleNameNorm, "packages/"):
|
||||
let moduleName = getModuleName(c.config, n)
|
||||
if belongsToStdlib(c.graph, result) and not startsWith(moduleName, stdPrefix) and
|
||||
not startsWith(moduleName, "system/") and not startsWith(moduleName, "packages/"):
|
||||
message(c.config, n.info, warnStdPrefix, realModule.name.s)
|
||||
|
||||
proc suggestMod(n: PNode; s: PSym) =
|
||||
|
||||
@@ -1349,7 +1349,7 @@ proc rawGetTok*(L: var Lexer, tok: var Token) =
|
||||
lexMessage(L, errGenerated, "invalid token: no whitespace between number and identifier")
|
||||
of '-':
|
||||
if L.buf[L.bufpos+1] in {'0'..'9'} and
|
||||
(L.bufpos == 0 or L.buf[L.bufpos-1] in UnaryMinusWhitelist):
|
||||
(L.bufpos-1 == 0 or L.buf[L.bufpos-1] in UnaryMinusWhitelist):
|
||||
# x)-23 # binary minus
|
||||
# ,-23 # unary minus
|
||||
# \n-78 # unary minus? Yes.
|
||||
|
||||
@@ -259,9 +259,6 @@ type
|
||||
## Old transformation for closures in JS backend
|
||||
noPanicOnExcept
|
||||
## don't panic on bare except
|
||||
procParamTypeBackendAliases
|
||||
## Keep the old proc type compatibility rules that ignore backend
|
||||
## c type aliases.
|
||||
|
||||
SymbolFilesOption* = enum
|
||||
disabledSf, writeOnlySf, readOnlySf, v2Sf, stressTest
|
||||
|
||||
@@ -454,26 +454,6 @@ proc resetSemFlag(n: PNode) =
|
||||
for i in 0..<n.safeLen:
|
||||
resetSemFlag(n[i])
|
||||
|
||||
proc normalizeTypedescMacroResult(c: PContext, n: PNode): PNode =
|
||||
result = n
|
||||
if result.kind == nkStmtList:
|
||||
result.transitionSonsKind(nkStmtListType)
|
||||
|
||||
const maxTypedescMacroNormalizationPasses = 32
|
||||
# Resolve surviving compile-time branches so later passes don't walk
|
||||
# unevaluated type AST for a typedesc expression.
|
||||
for _ in 0..<maxTypedescMacroNormalizationPasses:
|
||||
if result.kind == nkWhenStmt:
|
||||
result = semWhen(c, result, false)
|
||||
if result.kind == nkStmtList:
|
||||
result.transitionSonsKind(nkStmtListType)
|
||||
elif result.kind == nkStmtListType and result.len > 0 and result[^1].kind == nkWhenStmt:
|
||||
result[^1] = semWhen(c, result[^1], false)
|
||||
if result[^1].kind == nkStmtList:
|
||||
result[^1].transitionSonsKind(nkStmtListType)
|
||||
else:
|
||||
break
|
||||
|
||||
proc semAfterMacroCall(c: PContext, call, macroResult: PNode,
|
||||
s: PSym, flags: TExprFlags; expectedType: PType = nil): PNode =
|
||||
## Semantically check the output of a macro.
|
||||
@@ -504,7 +484,7 @@ proc semAfterMacroCall(c: PContext, call, macroResult: PNode,
|
||||
# More restrictive version.
|
||||
result = semExprWithType(c, result, flags, expectedType)
|
||||
of tyTypeDesc:
|
||||
result = normalizeTypedescMacroResult(c, result)
|
||||
if result.kind == nkStmtList: result.transitionSonsKind(nkStmtListType)
|
||||
var typ = semTypeNode(c, result, nil)
|
||||
if typ == nil:
|
||||
localError(c.config, result.info, "expression has no type: " &
|
||||
@@ -512,7 +492,7 @@ proc semAfterMacroCall(c: PContext, call, macroResult: PNode,
|
||||
result = newSymNode(errorSym(c, result))
|
||||
else:
|
||||
result.typ = makeTypeDesc(c, typ)
|
||||
#result = symNodeFromType(c, typ, n.info)
|
||||
#result = symNodeFromType(c, typ, n.info)
|
||||
else:
|
||||
if s.ast[genericParamsPos] != nil and retType.isMetaType:
|
||||
# The return type may depend on the Macro arguments
|
||||
|
||||
@@ -637,11 +637,6 @@ proc renderNotLValue*(n: PNode): string =
|
||||
elif n.kind in {nkHiddenStdConv, nkHiddenSubConv} and n.len == 2:
|
||||
result = typeToString(n.typ.skipTypes(abstractVar)) & "(" & result & ")"
|
||||
|
||||
proc isSsoStringIndex*(conf: ConfigRef; n: PNode): bool =
|
||||
result = conf.usesSso() and n.kind == nkBracketExpr and n.len >= 1 and
|
||||
n[0].typ != nil and
|
||||
n[0].typ.skipTypes(abstractVar + abstractInst - {tyTypeDesc}).kind == tyString
|
||||
|
||||
proc isAssignable(c: PContext, n: PNode): TAssignableResult =
|
||||
result = parampatterns.isAssignable(c.p.owner, n)
|
||||
|
||||
|
||||
@@ -652,9 +652,6 @@ proc overloadedCallOpr(c: PContext, n: PNode): PNode =
|
||||
result = semExpr(c, result, flags = {efNoUndeclared})
|
||||
|
||||
proc changeType(c: PContext; n: PNode, newType: PType, check: bool) =
|
||||
template isViewTarget(t: PType): bool =
|
||||
t.skipTypes({tyGenericInst, tyAlias, tySink}).kind in {tyVar, tyLent}
|
||||
|
||||
case n.kind
|
||||
of nkCurly:
|
||||
for i in 0..<n.len:
|
||||
@@ -683,15 +680,12 @@ proc changeType(c: PContext; n: PNode, newType: PType, check: bool) =
|
||||
if f == nil:
|
||||
globalError(c.config, m.info, "unknown identifier: " & m.sym.name.s)
|
||||
return
|
||||
if not isViewTarget(f.typ):
|
||||
changeType(c, n[i][1], f.typ, check)
|
||||
changeType(c, n[i][1], f.typ, check)
|
||||
else:
|
||||
if not isViewTarget(tup[i]):
|
||||
changeType(c, n[i][1], tup[i], check)
|
||||
changeType(c, n[i][1], tup[i], check)
|
||||
else:
|
||||
for i in 0..<n.len:
|
||||
if not isViewTarget(tup[i]):
|
||||
changeType(c, n[i], tup[i], check)
|
||||
changeType(c, n[i], tup[i], check)
|
||||
when false:
|
||||
var m = n[i]
|
||||
var a = newNodeIT(nkExprColonExpr, m.info, newType[i])
|
||||
@@ -714,7 +708,6 @@ proc changeType(c: PContext; n: PNode, newType: PType, check: bool) =
|
||||
localError(c.config, n.info, "cannot convert '" & n.sym.name.s &
|
||||
"' to '" & typeNameAndDesc(newType) & "'")
|
||||
else: discard
|
||||
|
||||
n.typ = newType
|
||||
|
||||
proc arrayConstrType(c: PContext, n: PNode): PType =
|
||||
|
||||
@@ -248,13 +248,10 @@ proc evalTypeTrait(c: PContext; traitCall: PNode, operand: PType, context: PSym)
|
||||
assert operand.kind == tyTuple, $operand.kind
|
||||
result = newIntNodeT(toInt128(operand.len), traitCall, c.idgen, c.graph)
|
||||
of "distinctBase":
|
||||
var arg = operand.skipTypes(skippedTypes)
|
||||
var arg = operand.skipTypes({tyGenericInst})
|
||||
let rec = semConstExpr(c, traitCall[2]).intVal != 0
|
||||
while true:
|
||||
let distinctArg = arg.skipTypes(skippedTypes + {tyGenericInst})
|
||||
if distinctArg.kind != tyDistinct:
|
||||
break
|
||||
arg = distinctArg.base.skipTypes(skippedTypes)
|
||||
while arg.kind == tyDistinct:
|
||||
arg = arg.base.skipTypes(skippedTypes + {tyGenericInst})
|
||||
if not rec: break
|
||||
result = getTypeDescNode(c, arg, operand.owner, traitCall.info)
|
||||
of "rangeBase":
|
||||
|
||||
@@ -486,11 +486,6 @@ proc semObjConstr(c: PContext, n: PNode, flags: TExprFlags; expectedType: PType
|
||||
# we have to watch out, there are also 'owned proc' types that can be used
|
||||
# multiple times as long as they don't have closures.
|
||||
result.typ.incl tfHasOwned
|
||||
if t.kind == tyForward and efDetermineType in flags:
|
||||
# a forward object type does not error during determine-type analysis;
|
||||
# it now stays unresolved long enough for the existing delayed field-default pass to resolve it after the type section finishes.
|
||||
result.typ = t
|
||||
return result
|
||||
if t.kind != tyObject:
|
||||
return localErrorNode(c, result, if t.kind != tyGenericBody:
|
||||
"object constructor needs an object type".dup(addTypeNodeDeclaredLoc(c.config, t))
|
||||
|
||||
@@ -809,10 +809,6 @@ proc trackOperandForIndirectCall(tracked: PEffects, n: PNode, formals: PType; ar
|
||||
markSideEffect(tracked, a, n.info)
|
||||
let paramType = if formals != nil and argIndex < formals.signatureLen: formals[argIndex] else: nil
|
||||
if paramType != nil and paramType.kind in {tyVar}:
|
||||
let arg = n.skipAddr()
|
||||
if isSsoStringIndex(tracked.config, arg):
|
||||
localError(tracked.config, arg.info,
|
||||
"expression '$1' is immutable, not 'var'" % renderNotLValue(arg))
|
||||
invalidateFacts(tracked.guards, n)
|
||||
if n.kind == nkSym and isLocalSym(tracked, n.sym):
|
||||
makeVolatile(tracked, n.sym)
|
||||
|
||||
@@ -370,7 +370,6 @@ proc semFieldDefault(c: PContext; owner, expectedType: PType; field: PNode): PTy
|
||||
propagateToOwner(owner, result)
|
||||
|
||||
proc semDelayedFieldDefault(c: PContext; owner, expectedType: PType; field: PNode) =
|
||||
resetSemFlag(field[^1])
|
||||
fitDefaultNode(c, field[^1], expectedType)
|
||||
propagateToOwner(owner, field[^1].typ.skipIntLit(c.idgen))
|
||||
|
||||
|
||||
@@ -784,17 +784,6 @@ proc procParamTypeRel(c: var TCandidate; f, a: PType): TTypeRelation =
|
||||
# if f is metatype.
|
||||
result = typeRel(c, f, a)
|
||||
|
||||
if result == isEqual and
|
||||
procParamTypeBackendAliases notin c.c.config.legacyFeatures:
|
||||
# Ensure types that are semantically equal also match at the backend level.
|
||||
# E.g. reject assigning proc(csize_t) to proc(uint) since these map to
|
||||
# different C types (size_t vs unsigned long long).
|
||||
let fCheck = concreteType(c, f)
|
||||
let aCheck = concreteType(c, a)
|
||||
if fCheck != nil and aCheck != nil and
|
||||
not sameBackendTypePickyAliases(fCheck, aCheck):
|
||||
result = isNone
|
||||
|
||||
if result <= isSubrange or inconsistentVarTypes(f, a):
|
||||
result = isNone
|
||||
|
||||
@@ -1436,13 +1425,17 @@ proc typeRel(c: var TCandidate, f, aOrig: PType,
|
||||
if a.kind == tyArray:
|
||||
var fRange = f.indexType
|
||||
var aRange = a.indexType
|
||||
# Keep index matching separate so array[N, T] stays generic when only the
|
||||
# index matched through a generic parameter.
|
||||
var indexRel = isEqual
|
||||
if fRange.kind in {tyGenericParam, tyAnything}:
|
||||
var prev = lookup(c.bindings, fRange)
|
||||
if prev == nil:
|
||||
if typeRel(c, fRange, aRange) == isNone:
|
||||
indexRel = typeRel(c, fRange, aRange)
|
||||
if indexRel == isNone:
|
||||
return isNone
|
||||
put(c, fRange, a.indexType)
|
||||
fRange = a
|
||||
fRange = aRange
|
||||
else:
|
||||
fRange = prev
|
||||
let ff = f[1].skipTypes({tyTypeDesc})
|
||||
@@ -1453,6 +1446,8 @@ proc typeRel(c: var TCandidate, f, aOrig: PType,
|
||||
result = isGeneric
|
||||
else:
|
||||
result = typeRel(c, ff, aa, flags)
|
||||
if indexRel == isGeneric and result > isGeneric:
|
||||
result = isGeneric
|
||||
if result < isGeneric:
|
||||
if nimEnableCovariance and
|
||||
trNoCovariance notin flags and
|
||||
@@ -1463,13 +1458,25 @@ proc typeRel(c: var TCandidate, f, aOrig: PType,
|
||||
return isNone
|
||||
|
||||
if fRange.rangeHasUnresolvedStatic:
|
||||
# During reverse generic checks, a plain generic array index must not be
|
||||
# treated as specific enough to infer a static range overload.
|
||||
if trCheckGeneric in flags and aOrig.kind == tyArray and
|
||||
aOrig.indexType.kind == tyGenericParam:
|
||||
return isNone
|
||||
if (aRange.kind in {tyGenericParam} and aRange.reduceToBase() == aRange) or
|
||||
(aRange.kind == tyRange and aRange.rangeHasUnresolvedStatic):
|
||||
return
|
||||
return isNone
|
||||
return inferStaticsInRange(c, fRange, a)
|
||||
elif c.c.matchedConcept != nil and aRange.rangeHasUnresolvedStatic:
|
||||
return inferStaticsInRange(c, aRange, f)
|
||||
elif result == isGeneric and concreteType(c, aa, ff) == nil:
|
||||
# If the element type is still unresolved, only keep the match alive
|
||||
# when the array index already established the generic relationship.
|
||||
if indexRel != isGeneric:
|
||||
return isNone
|
||||
elif trCheckGeneric in flags and aRange.kind == tyGenericParam:
|
||||
# Reverse generic disambiguation should stop before exact length
|
||||
# comparison if the actual array index is still generic.
|
||||
return isNone
|
||||
else:
|
||||
if lengthOrd(c.c.config, fRange) != lengthOrd(c.c.config, aRange):
|
||||
|
||||
@@ -897,7 +897,7 @@ proc sameTypeAux(x, y: PType, c: var TSameTypeClosure): bool =
|
||||
c.flags = oldFlags
|
||||
|
||||
if x == y: return true
|
||||
let aliasSkipSet = maybeSkipRange({tyAlias, tyInferred})
|
||||
let aliasSkipSet = maybeSkipRange({tyAlias})
|
||||
var a = skipTypes(x, aliasSkipSet)
|
||||
while a.kind == tyUserTypeClass and tfResolved in a.flags:
|
||||
a = skipTypes(a.last, aliasSkipSet)
|
||||
|
||||
@@ -33,7 +33,7 @@ The text representation is particularly valuable for debugging and introspection
|
||||
Each ``.nim`` module produces its own ``.nif`` file during compilation.
|
||||
The NIF format contains:
|
||||
|
||||
- **Header** - Version information (e.g., `(.nif27)`)
|
||||
- **Header** - Version information (e.g., `(.nif26)`)
|
||||
- **Dependencies** - List of source files and dependencies
|
||||
- **Interface** - Exported symbols and their indices
|
||||
- **Body** - The intermediate representation of the module's code in Lisp-like syntax
|
||||
|
||||
@@ -34,10 +34,10 @@ To learn how to compile Nim programs and generate documentation see
|
||||
the [Compiler User Guide](nimc.html) and the [DocGen Tools Guide](docgen.html).
|
||||
|
||||
The language constructs are explained using an extended BNF, in which `(a)*`
|
||||
means 0 or more *a*'s, `a+` means 1 or more *a*'s, and `(a)?` means an
|
||||
means 0 or more `a`'s, `a+` means 1 or more `a`'s, and `(a)?` means an
|
||||
optional *a*. Parentheses may be used to group elements.
|
||||
|
||||
`&` is the lookahead operator; `&a` means that an *a* is expected but
|
||||
`&` is the lookahead operator; `&a` means that an `a` is expected but
|
||||
not consumed. It will be consumed in the following rule.
|
||||
|
||||
The `|`, `/` symbols are used to mark alternatives and have the lowest
|
||||
@@ -1024,9 +1024,6 @@ These are the major type classes:
|
||||
* procedural type
|
||||
* generic type
|
||||
|
||||
The compiler's internal type zoo is richer than this summary suggests:
|
||||
some types that are structurally equal still differ in backend representation.
|
||||
|
||||
|
||||
Ordinal types
|
||||
-------------
|
||||
@@ -2177,10 +2174,6 @@ Procedural type
|
||||
A procedural type is internally a pointer to a procedure. `nil` is
|
||||
an allowed value for a variable of a procedural type.
|
||||
|
||||
Procedure compatibility also checks the backend representation of the
|
||||
parameter and result types, not just their source-level shape. Use
|
||||
`--legacy:procParamTypeBackendAliases` to restore the older behavior.
|
||||
|
||||
Examples:
|
||||
|
||||
```nim
|
||||
@@ -8874,7 +8867,7 @@ Byref pragma
|
||||
The `byref` pragma can be applied to an object or tuple type or a proc param.
|
||||
When applied to a type it instructs the compiler to pass the type by reference
|
||||
(hidden pointer) to procs. When applied to a param it will take precedence, even
|
||||
if the type was marked as `bycopy`. When an `importc` type has a `byref` pragma or
|
||||
if the the type was marked as `bycopy`. When an `importc` type has a `byref` pragma or
|
||||
parameters are marked as `byref` in an `importc` proc, these params translate to pointers.
|
||||
When an `importcpp` type has a `byref` pragma, these params translate to
|
||||
C++ references `&`.
|
||||
|
||||
@@ -1144,7 +1144,7 @@ there is a difference between the `$` and `repr` outputs:
|
||||
echo myCharacter, ":", repr(myCharacter)
|
||||
# --> n:'n'
|
||||
echo myString, ":", repr(myString)
|
||||
# --> nim:"nim"
|
||||
# --> nim:0x10fa8c050"nim"
|
||||
echo myInteger, ":", repr(myInteger)
|
||||
# --> 42:42
|
||||
echo myFloat, ":", repr(myFloat)
|
||||
|
||||
4
koch.nim
4
koch.nim
@@ -16,11 +16,11 @@ const
|
||||
ChecksumsStableCommit = "0b8e46379c5bc1bf73d8b3011908389c60fb9b98" # 2.0.1
|
||||
SatStableCommit = "e63eaea8baf00bed8bcd5a29ffd8823abb265b39"
|
||||
|
||||
NimonyStableCommit = "750aa47f2139fe5ad69f04b44428b752011fe873" # unversioned \
|
||||
NimonyStableCommit = "c189ef438598878b2f02f6a2ff91d08febafc04b" # unversioned \
|
||||
# Note that Nimony uses Nim as a git submodule but we don't want to install
|
||||
# Nimony's dependency to Nim as we are Nim. So a `git clone` without --recursive
|
||||
# is **required** here.
|
||||
# Commit from 2026-05-05
|
||||
# Commit from 2026-04-27
|
||||
|
||||
# examples of possible values for fusion: #head, #ea82b54, 1.2.3
|
||||
FusionStableHash = "#562467452b32cb7a97410ea177f083e6d8405734"
|
||||
|
||||
@@ -153,7 +153,7 @@ proc parseProtocol(protocol: string): tuple[orig: string, major, minor: int] =
|
||||
protocol)
|
||||
result.orig = protocol
|
||||
i.inc protocol.parseSaturatedNatural(result.major, i)
|
||||
if i < protocol.len: inc i # Skip .
|
||||
i.inc # Skip .
|
||||
i.inc protocol.parseSaturatedNatural(result.minor, i)
|
||||
|
||||
proc sendStatus(client: AsyncSocket, status: string): Future[void] =
|
||||
|
||||
@@ -2694,9 +2694,7 @@ when hasAlloc or defined(nimscript):
|
||||
setLen(x, xl+item.len)
|
||||
var j = xl-1
|
||||
while j >= i:
|
||||
when defined(nimsso):
|
||||
x[j+item.len] = x[j]
|
||||
elif defined(gcArc) or defined(gcOrc) or defined(gcYrc) or defined(gcAtomicArc):
|
||||
when defined(gcArc) or defined(gcOrc) or defined(gcYrc) or defined(gcAtomicArc):
|
||||
x[j+item.len] = move x[j]
|
||||
else:
|
||||
shallowCopy(x[j+item.len], x[j])
|
||||
|
||||
@@ -691,7 +691,7 @@ proc getBigChunk(a: var MemRegion, size: int): PBigChunk =
|
||||
removeChunkFromMatrix2(a, result, fl, sl)
|
||||
if result.size >= size + PageSize:
|
||||
splitChunk(a, result, size)
|
||||
# set 'used' to true:
|
||||
# set 'used' to to true:
|
||||
result.prevSize = 1
|
||||
track("setUsedToFalse", addr result.size, sizeof(int))
|
||||
sysAssert result.owner == addr a, "getBigChunk: No owner set!"
|
||||
@@ -708,7 +708,7 @@ proc getHugeChunk(a: var MemRegion; size: int): PBigChunk =
|
||||
result.next = nil
|
||||
result.prev = nil
|
||||
result.size = size
|
||||
# set 'used' to true:
|
||||
# set 'used' to to true:
|
||||
result.prevSize = 1
|
||||
result.owner = addr a
|
||||
incl(a, a.chunkStarts, pageIndex(result))
|
||||
|
||||
@@ -143,7 +143,7 @@ when nimCoroutines:
|
||||
|
||||
proc find(first: var GcStack, bottom: pointer): ptr GcStack =
|
||||
## Find stack struct based on bottom pointer. If `bottom` is nil then main
|
||||
## thread stack is returned.
|
||||
## thread stack is is returned.
|
||||
if bottom == nil:
|
||||
return addr(gch.stack)
|
||||
|
||||
|
||||
@@ -59,35 +59,16 @@ template `[]=`*(s: string; i: int; val: char) = arrPut(s, i, val)
|
||||
template `^^`(s, i: untyped): untyped =
|
||||
(when i is BackwardsIndex: s.len - int(i) else: int(i))
|
||||
|
||||
template spliceStringImpl(s, a, L, b: typed): untyped =
|
||||
template spliceImpl(s, a, L, b: typed): untyped =
|
||||
# make room for additional elements or cut:
|
||||
var shift = b.len - max(0,L) # ignore negative slice size
|
||||
var newLen = s.len + shift
|
||||
if shift > 0:
|
||||
# enlarge:
|
||||
setLen(s, newLen)
|
||||
for i in countdown(newLen-1, a+b.len):
|
||||
s[i] = s[i-shift]
|
||||
for i in countdown(newLen-1, a+b.len): movingCopy(s[i], s[i-shift])
|
||||
else:
|
||||
for i in countup(a+b.len, newLen-1):
|
||||
s[i] = s[i-shift]
|
||||
# cut down:
|
||||
setLen(s, newLen)
|
||||
# fill the hole:
|
||||
for i in 0 ..< b.len: s[a+i] = b[i]
|
||||
|
||||
template spliceSeqImpl(s, a, L, b: typed): untyped =
|
||||
# make room for additional elements or cut:
|
||||
var shift = b.len - max(0,L) # ignore negative slice size
|
||||
var newLen = s.len + shift
|
||||
if shift > 0:
|
||||
# enlarge:
|
||||
setLen(s, newLen)
|
||||
for i in countdown(newLen-1, a+b.len):
|
||||
movingCopy(s[i], s[i-shift])
|
||||
else:
|
||||
for i in countup(a+b.len, newLen-1):
|
||||
movingCopy(s[i], s[i-shift])
|
||||
for i in countup(a+b.len, newLen-1): movingCopy(s[i], s[i-shift])
|
||||
# cut down:
|
||||
setLen(s, newLen)
|
||||
# fill the hole:
|
||||
@@ -121,7 +102,7 @@ proc `[]=`*[T, U: Ordinal](s: var string, x: HSlice[T, U], b: string) {.systemRa
|
||||
if L == b.len:
|
||||
for i in 0..<L: s[i+a] = b[i]
|
||||
else:
|
||||
spliceStringImpl(s, a, L, b)
|
||||
spliceImpl(s, a, L, b)
|
||||
|
||||
proc `[]`*[Idx, T; U, V: Ordinal](a: array[Idx, T], x: HSlice[U, V]): seq[T] {.systemRaisesDefect.} =
|
||||
## Slice operation for arrays.
|
||||
@@ -181,4 +162,4 @@ proc `[]=`*[T; U, V: Ordinal](s: var seq[T], x: HSlice[U, V], b: openArray[T]) {
|
||||
if L == b.len:
|
||||
for i in 0 ..< L: s[i+a] = b[i]
|
||||
else:
|
||||
spliceSeqImpl(s, a, L, b)
|
||||
spliceImpl(s, a, L, b)
|
||||
|
||||
@@ -224,14 +224,13 @@ proc cmpStringPtrs(a, b: ptr SmallString): int {.inline.} =
|
||||
minLen - AlwaysAvail)
|
||||
if result == 0: result = aslen - bslen
|
||||
return
|
||||
# At least one is long. Hot prefix mirrors heap data, but only up to fullLen:
|
||||
# shrinking can leave stale bytes in the inline cache past the logical length.
|
||||
# At least one is long. Hot prefix: inlinePtr[0..AlwaysAvail-1] mirrors heap data.
|
||||
let pfxLen = min(min(aslen, bslen), AlwaysAvail)
|
||||
result = cmpInlineBytes(inlinePtrOf(a), inlinePtrOf(b), pfxLen)
|
||||
if result != 0: return
|
||||
let la = if aslen > PayloadSize: a.more.fullLen else: aslen
|
||||
let lb = if bslen > PayloadSize: b.more.fullLen else: bslen
|
||||
let minLen = min(la, lb)
|
||||
let pfxLen = min(minLen, AlwaysAvail)
|
||||
result = cmpInlineBytes(inlinePtrOf(a), inlinePtrOf(b), pfxLen)
|
||||
if result != 0: return
|
||||
if minLen <= AlwaysAvail:
|
||||
result = la - lb
|
||||
return
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
discard """
|
||||
matrix: "-d:nimPreviewSlimSystem --warning:StdPrefix:on --warningAsError:StdPrefix:on --import:std/objectdollar"
|
||||
output: "(a: 23, b: 45)"
|
||||
"""
|
||||
|
||||
type Foo = object
|
||||
a, b: int
|
||||
|
||||
let x = Foo(a: 23, b: 45)
|
||||
echo x
|
||||
@@ -176,42 +176,6 @@ block t6462:
|
||||
var s = SeqGen[int](fil: FilterMixin[int](test: nil, trans: nil))
|
||||
doAssert s.test() == nil
|
||||
|
||||
block concept_with_cint:
|
||||
# Generic proc matching through concepts with cint should still work
|
||||
type
|
||||
FilterMixin[T] = ref object
|
||||
test: (T) -> bool
|
||||
trans: (T) -> T
|
||||
|
||||
SeqGen[T] = ref object
|
||||
fil: FilterMixin[T]
|
||||
|
||||
WithFilter[T] = concept a
|
||||
a.fil is FilterMixin[T]
|
||||
|
||||
proc test[T](a: WithFilter[T]): (T) -> bool =
|
||||
a.fil.test
|
||||
|
||||
var s = SeqGen[cint](fil: FilterMixin[cint](test: nil, trans: nil))
|
||||
doAssert s.test() == nil
|
||||
|
||||
block concept_with_int:
|
||||
type
|
||||
FilterMixin[T] = ref object
|
||||
test: (T) -> bool
|
||||
trans: (T) -> T
|
||||
|
||||
SeqGen[T] = ref object
|
||||
fil: FilterMixin[T]
|
||||
|
||||
WithFilter[T] = concept a
|
||||
a.fil is FilterMixin[T]
|
||||
|
||||
proc test[T](a: WithFilter[T]): (T) -> bool =
|
||||
a.fil.test
|
||||
|
||||
var s = SeqGen[int](fil: FilterMixin[int](test: nil, trans: nil))
|
||||
doAssert s.test() == nil
|
||||
|
||||
|
||||
block t6770:
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
discard """
|
||||
cmd: "nim check --strings:sso --mm:orc --hints:off $file"
|
||||
action: "reject"
|
||||
nimout: '''
|
||||
tsso_string_index_var.nim(13, 12) Error: expression 's[0]' is immutable, not 'var'
|
||||
'''
|
||||
"""
|
||||
|
||||
proc passByVar(c: var char) =
|
||||
c = 'x'
|
||||
|
||||
var s = "abc"
|
||||
passByVar(s[0])
|
||||
@@ -1,61 +0,0 @@
|
||||
discard """
|
||||
targets: "cpp"
|
||||
matrix: "--mm:arc; --mm:orc; --mm:refc"
|
||||
output: '''
|
||||
inner: orig
|
||||
finally
|
||||
outer: re:orig
|
||||
inner-typeless: orig
|
||||
finally-typeless
|
||||
outer-typeless: re-tl:orig
|
||||
no-catch-finally
|
||||
caught-propagated: prop
|
||||
'''
|
||||
"""
|
||||
|
||||
# When an `except` handler raises a new exception, the enclosing `finally`
|
||||
# block must still run before the new exception propagates to the outer
|
||||
# try.
|
||||
#
|
||||
# The C++ backend previously emitted the finally's `catch (...)` as a
|
||||
# sibling of the user-written catches. C++ does not allow sibling catches
|
||||
# to catch each other's throws, so a handler-raised exception bypassed the
|
||||
# finally entirely. The fix wraps the inner try/catch sequence in an
|
||||
# outer try, so any escaping exception (whether from the body or from a
|
||||
# handler) is captured before the finally runs.
|
||||
|
||||
block typed_except:
|
||||
try:
|
||||
try:
|
||||
raise newException(CatchableError, "orig")
|
||||
except CatchableError as e:
|
||||
echo "inner: ", e.msg
|
||||
raise newException(CatchableError, "re:" & e.msg)
|
||||
finally:
|
||||
echo "finally"
|
||||
except CatchableError as outer:
|
||||
echo "outer: ", outer.msg
|
||||
|
||||
block typeless_except:
|
||||
try:
|
||||
try:
|
||||
raise newException(CatchableError, "orig")
|
||||
except:
|
||||
let e = getCurrentException()
|
||||
echo "inner-typeless: ", e.msg
|
||||
raise newException(CatchableError, "re-tl:" & e.msg)
|
||||
finally:
|
||||
echo "finally-typeless"
|
||||
except CatchableError as outer:
|
||||
echo "outer-typeless: ", outer.msg
|
||||
|
||||
# try/finally without an except: the body's exception must still propagate
|
||||
# after the finally runs.
|
||||
block no_catch_finally:
|
||||
try:
|
||||
try:
|
||||
raise newException(CatchableError, "prop")
|
||||
finally:
|
||||
echo "no-catch-finally"
|
||||
except CatchableError as e:
|
||||
echo "caught-propagated: ", e.msg
|
||||
@@ -1,5 +1,5 @@
|
||||
discard """
|
||||
matrix: "--mm:refc; --mm:orc"
|
||||
matrix: "--mm:refc"
|
||||
targets: "cpp"
|
||||
output: '''
|
||||
caught as std::exception
|
||||
|
||||
@@ -252,3 +252,9 @@ block: # issue #9381
|
||||
|
||||
var x: GenericObj[int]
|
||||
static: doAssert evalCount == 1
|
||||
|
||||
block: # bug #22861
|
||||
proc fromHex[N](A: type array[N, int]) = discard
|
||||
proc fromHex (T: typedesc[array[1, int]]) = discard
|
||||
fromHex(array[1, int])
|
||||
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
discard """
|
||||
errormsg: "expression has no address"
|
||||
"""
|
||||
|
||||
iterator foo(x: int): (lent int, lent int) =
|
||||
yield (x, x + 1)
|
||||
|
||||
|
||||
var x = 12
|
||||
for i in foo(x):
|
||||
echo i[0]
|
||||
echo i[1]
|
||||
@@ -434,32 +434,3 @@ block: # bug #24378
|
||||
type Win222[T] = typeof("foobar")
|
||||
doAssert not supportsCopyMem((int, Win222[int]))
|
||||
doAssert not supportsCopyMem(tuple[a: int, b: Win222[int]])
|
||||
|
||||
block: # bug #25789
|
||||
type
|
||||
L[T; N: static int] = distinct seq[T]
|
||||
EPF = distinct L[int, 100]
|
||||
|
||||
var e: EPF = EPF(L[int, 100](@[1, 2, 3]))
|
||||
|
||||
template classifyGeneric[T](x: T): bool =
|
||||
when typeof(x) is L:
|
||||
true
|
||||
else:
|
||||
false
|
||||
|
||||
template classifyConcrete[T](x: T): bool =
|
||||
when typeof(x) is L[int, 100]:
|
||||
true
|
||||
else:
|
||||
false
|
||||
|
||||
let viaConv = L[int, 100](e)
|
||||
doAssert $type(viaConv) == "L[system.int, 100]"
|
||||
doAssert classifyGeneric(viaConv)
|
||||
doAssert classifyConcrete(viaConv)
|
||||
|
||||
let viaDB = distinctBase(e, recursive = false)
|
||||
doAssert $type(viaDB) == "L[system.int, 100]"
|
||||
doAssert classifyGeneric(viaDB)
|
||||
doAssert classifyConcrete(viaDB)
|
||||
|
||||
@@ -833,37 +833,4 @@ proc overloaded[T: object](x: T) =
|
||||
var v: typeof(val)
|
||||
overloaded(v)
|
||||
|
||||
overloaded(Thing())
|
||||
|
||||
block:
|
||||
type
|
||||
Foo = object
|
||||
x = Bar()
|
||||
|
||||
Bar = object
|
||||
x: int
|
||||
|
||||
var f = Foo()
|
||||
doassert f.x.x == 0
|
||||
|
||||
block:
|
||||
type
|
||||
Foo = object
|
||||
x = Bar(x: 55)
|
||||
|
||||
Bar = object
|
||||
x: int
|
||||
|
||||
var f = Foo()
|
||||
doassert f.x.x == 55
|
||||
|
||||
block:
|
||||
type
|
||||
Bar = object
|
||||
x: int
|
||||
|
||||
Foo = object
|
||||
x = Bar()
|
||||
|
||||
var f = Foo()
|
||||
doassert f.x.x == 0
|
||||
overloaded(Thing())
|
||||
@@ -1,44 +0,0 @@
|
||||
# bug #25617
|
||||
# Ensure that proc types with backend type alias mismatches
|
||||
# (e.g. uint vs csize_t) are rejected at the Nim level rather
|
||||
# than producing invalid C code.
|
||||
|
||||
discard """
|
||||
cmd: "nim check --hints:off --warnings:off --errorMax:0 $file"
|
||||
action: "reject"
|
||||
nimout: '''
|
||||
tbackendtypealias.nim(21, 7) Error: type mismatch: got <proc (len: csize_t){.closure.}> but expected 'proc (len: uint){.closure.}'
|
||||
tbackendtypealias.nim(28, 7) Error: type mismatch: got <proc (len: uint){.closure.}> but expected 'proc (len: csize_t){.closure.}'
|
||||
'''
|
||||
"""
|
||||
|
||||
block direct_assignment:
|
||||
# Direct proc variable assignment with backend type alias mismatch
|
||||
var
|
||||
a: proc (len: uint)
|
||||
b: proc (len: csize_t)
|
||||
c = a
|
||||
c = b
|
||||
|
||||
block direct_assignment_reverse:
|
||||
var
|
||||
a: proc (len: csize_t)
|
||||
b: proc (len: uint)
|
||||
c = a
|
||||
c = b
|
||||
|
||||
block same_backend_type:
|
||||
# Same backend type should still work
|
||||
var
|
||||
a: proc (len: uint)
|
||||
b: proc (len: uint)
|
||||
c = a
|
||||
c = b
|
||||
|
||||
block cint_same_type:
|
||||
# cint to cint should work
|
||||
var
|
||||
a: proc (len: cint)
|
||||
b: proc (len: cint)
|
||||
c = a
|
||||
c = b
|
||||
@@ -544,12 +544,6 @@ proc main() =
|
||||
var x = 5
|
||||
doAssert fmt"{(x=7;123.456)=:13e}" == "(x=7;123.456)= 1.234560e+02"
|
||||
doAssert x==7
|
||||
|
||||
block: # binary operators in interpolated expressions
|
||||
let n = 1
|
||||
doAssert &"{n-1}" == "0"
|
||||
doAssert fmt"{n-1}" == "0"
|
||||
|
||||
block: #curly bracket expressions and tuples
|
||||
proc formatValue(result: var string; value:Table|bool|JsonNode; specifier:string) = result.add $value
|
||||
|
||||
|
||||
@@ -45,12 +45,3 @@ elif compiles(nonexistent):
|
||||
else:
|
||||
output("whenElse")
|
||||
|
||||
|
||||
template test(): typedesc =
|
||||
when true:
|
||||
int
|
||||
else:
|
||||
bool
|
||||
|
||||
const c = default(test())
|
||||
echo c
|
||||
|
||||
Reference in New Issue
Block a user