Skip to content

Commit

Permalink
Error -> Defect for defects (nim-lang#13908)
Browse files Browse the repository at this point in the history
* Error -> Defect for defects

The distinction between Error and Defect is subjective,
context-dependent and somewhat arbitrary, so when looking at an
exception, it's hard to guess what it is - this happens often when
looking at a `raises` list _without_ opening the corresponding
definition and digging through layers of inheritance.

With the help of a little consistency in naming, it's at least possible
to start disentangling the two error types and the standard lib can set
a good example here.
  • Loading branch information
arnetheduck authored Apr 28, 2020
1 parent cd9af6b commit 7d6cbf2
Show file tree
Hide file tree
Showing 92 changed files with 323 additions and 300 deletions.
2 changes: 1 addition & 1 deletion compiler/ast.nim
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ type
sfTemplateParam # symbol is a template parameter
sfCursor # variable/field is a cursor, see RFC 177 for details
sfInjectDestructors # whether the proc needs the 'injectdestructors' transformation
sfNeverRaises # proc can never raise an exception, not even OverflowError
sfNeverRaises # proc can never raise an exception, not even OverflowDefect
# or out-of-memory

TSymFlags* = set[TSymFlag]
Expand Down
2 changes: 1 addition & 1 deletion compiler/ccgexprs.nim
Original file line number Diff line number Diff line change
Expand Up @@ -821,7 +821,7 @@ proc genFieldCheck(p: BProc, e: PNode, obj: Rope, field: PSym) =
v.r.add(".")
v.r.add(disc.sym.loc.r)
genInExprAux(p, it, u, v, test)
let msg = genFieldError(field, disc.sym)
let msg = genFieldDefect(field, disc.sym)
let strLit = genStringLiteral(p.module, newStrNode(nkStrLit, msg))
if op.magic == mNot:
linefmt(p, cpsStmts,
Expand Down
8 changes: 4 additions & 4 deletions compiler/jsgen.nim
Original file line number Diff line number Diff line change
Expand Up @@ -1131,7 +1131,7 @@ proc genCheckedFieldOp(p: PProc, n: PNode, addrTyp: PType, r: var TCompRes) =

useMagic(p, "raiseFieldError")
useMagic(p, "makeNimstrLit")
let msg = genFieldError(field, disc)
let msg = genFieldDefect(field, disc)
lineF(p, "if ($1[$2.$3]$4undefined) { raiseFieldError(makeNimstrLit($5)); }$n",
setx.res, tmp, disc.loc.r, if negCheck: ~"!==" else: ~"===",
makeJSString(msg))
Expand Down Expand Up @@ -2343,7 +2343,7 @@ proc gen(p: PProc, n: PNode, r: var TCompRes) =
if r.kind != resCallee: r.kind = resNone
#r.address = nil
r.res = nil

case n.kind
of nkSym:
genSym(p, n, r)
Expand Down Expand Up @@ -2398,7 +2398,7 @@ proc gen(p: PProc, n: PNode, r: var TCompRes) =
n.len >= 1:
genInfixCall(p, n, r)
else:
genCall(p, n, r)
genCall(p, n, r)
of nkClosure: gen(p, n[0], r)
of nkCurly: genSetConstr(p, n, r)
of nkBracket: genArrayConstr(p, n, r)
Expand Down Expand Up @@ -2602,7 +2602,7 @@ proc myClose(graph: ModuleGraph; b: PPassContext, n: PNode): PNode =
(code, map) = genSourceMap($(code), outFile.string)
writeFile(outFile.string & ".map", $(%map))
discard writeRopeIfNotEqual(code, outFile)

proc myOpen(graph: ModuleGraph; s: PSym): PPassContext =
result = newModule(graph, s)

Expand Down
6 changes: 3 additions & 3 deletions compiler/lexer.nim
Original file line number Diff line number Diff line change
Expand Up @@ -571,7 +571,7 @@ proc getNumber(L: var TLexer, result: var TToken) =
try:
len = parseBiggestUInt(result.literal, iNumber)
except ValueError:
raise newException(OverflowError, "number out of range: " & $result.literal)
raise newException(OverflowDefect, "number out of range: " & $result.literal)
if len != result.literal.len:
raise newException(ValueError, "invalid integer: " & $result.literal)
result.iNumber = cast[int64](iNumber)
Expand All @@ -581,7 +581,7 @@ proc getNumber(L: var TLexer, result: var TToken) =
try:
len = parseBiggestInt(result.literal, iNumber)
except ValueError:
raise newException(OverflowError, "number out of range: " & $result.literal)
raise newException(OverflowDefect, "number out of range: " & $result.literal)
if len != result.literal.len:
raise newException(ValueError, "invalid integer: " & $result.literal)
result.iNumber = iNumber
Expand All @@ -607,7 +607,7 @@ proc getNumber(L: var TLexer, result: var TToken) =

except ValueError:
lexMessageLitNum(L, "invalid number: '$1'", startpos)
except OverflowError, RangeError:
except OverflowDefect, RangeDefect:
lexMessageLitNum(L, "number out of range: '$1'", startpos)
tokenEnd(result, postPos-1)
L.bufpos = postPos
Expand Down
4 changes: 2 additions & 2 deletions compiler/renderer.nim
Original file line number Diff line number Diff line change
Expand Up @@ -1599,9 +1599,9 @@ proc quoteExpr*(a: string): string {.inline.} =
## can be used for quoting expressions in error msgs.
"'" & a & "'"

proc genFieldError*(field: PSym, disc: PSym): string =
proc genFieldDefect*(field: PSym, disc: PSym): string =
## this needs to be in a module accessible by jsgen, ccgexprs, and vm to
## provide this error msg FieldError; msgs would be better but it does not
## provide this error msg FieldDefect; msgs would be better but it does not
## import ast
result = field.name.s.quoteExpr & " is not accessible using discriminant " &
disc.name.s.quoteExpr & " of type " &
Expand Down
4 changes: 2 additions & 2 deletions compiler/semfold.nim
Original file line number Diff line number Diff line change
Expand Up @@ -645,9 +645,9 @@ proc getConstExpr(m: PSym, n: PNode; g: ModuleGraph): PNode =
discard
else:
result = magicCall(m, n, g)
except OverflowError:
except OverflowDefect:
localError(g.config, n.info, "over- or underflow")
except DivByZeroError:
except DivByZeroDefect:
localError(g.config, n.info, "division by zero")
of nkAddr:
var a = getConstExpr(m, n[0], g)
Expand Down
2 changes: 1 addition & 1 deletion compiler/sempass2.nim
Original file line number Diff line number Diff line change
Expand Up @@ -752,7 +752,7 @@ proc track(tracked: PEffects, n: PNode) =
createTypeBoundOps(tracked, n[0].typ, n.info)
else:
# A `raise` with no arguments means we're going to re-raise the exception
# being handled or, if outside of an `except` block, a `ReraiseError`.
# being handled or, if outside of an `except` block, a `ReraiseDefect`.
# Here we add a `Exception` tag in order to cover both the cases.
addEffect(tracked, createRaise(tracked.graph, n), nil)
of nkCallKinds:
Expand Down
2 changes: 1 addition & 1 deletion doc/lib.rst
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,7 @@ Miscellaneous
This module implements a simple logger.

* `segfaults <segfaults.html>`_
Turns access violations or segfaults into a ``NilAccessError`` exception.
Turns access violations or segfaults into a ``NilAccessDefect`` exception.

* `sugar <sugar.html>`_
This module implements nice syntactic sugar based on Nim's macro system.
Expand Down
28 changes: 14 additions & 14 deletions doc/manual.rst
Original file line number Diff line number Diff line change
Expand Up @@ -113,15 +113,15 @@ pragmas_ for details.

Whether a panic results in an exception or in a fatal error is
implementation specific. Thus the following program is invalid; even though the
code purports to catch the `IndexError` from an out-of-bounds array access, the
code purports to catch the `IndexDefect` from an out-of-bounds array access, the
compiler may instead choose to allow the program to die with a fatal error.

.. code-block:: nim
var a: array[0..1, char]
let i = 5
try:
a[i] = 'N'
except IndexError:
except IndexDefect:
echo "invalid index"
The current implementation allows to switch between these different behaviors
Expand Down Expand Up @@ -1033,10 +1033,10 @@ The IEEE standard defines five types of floating-point exceptions:
precision, for example, 2.0 / 3.0, log(1.1) and 0.1 in input.

The IEEE exceptions are either ignored during execution or mapped to the
Nim exceptions: `FloatInvalidOpError`:idx:, `FloatDivByZeroError`:idx:,
`FloatOverflowError`:idx:, `FloatUnderflowError`:idx:,
and `FloatInexactError`:idx:.
These exceptions inherit from the `FloatingPointError`:idx: base class.
Nim exceptions: `FloatInvalidOpDefect`:idx:, `FloatDivByZeroDefect`:idx:,
`FloatOverflowDefect`:idx:, `FloatUnderflowDefect`:idx:,
and `FloatInexactDefect`:idx:.
These exceptions inherit from the `FloatingPointDefect`:idx: base class.

Nim provides the pragmas `nanChecks`:idx: and `infChecks`:idx: to control
whether the IEEE exceptions are ignored or trap a Nim exception:
Expand All @@ -1045,12 +1045,12 @@ whether the IEEE exceptions are ignored or trap a Nim exception:
{.nanChecks: on, infChecks: on.}
var a = 1.0
var b = 0.0
echo b / b # raises FloatInvalidOpError
echo a / b # raises FloatOverflowError
echo b / b # raises FloatInvalidOpDefect
echo a / b # raises FloatOverflowDefect
In the current implementation ``FloatDivByZeroError`` and ``FloatInexactError``
are never raised. ``FloatOverflowError`` is raised instead of
``FloatDivByZeroError``.
In the current implementation ``FloatDivByZeroDefect`` and ``FloatInexactDefect``
are never raised. ``FloatOverflowDefect`` is raised instead of
``FloatDivByZeroDefect``.
There is also a `floatChecks`:idx: pragma that is a short-cut for the
combination of ``nanChecks`` and ``infChecks`` pragmas. ``floatChecks`` are
turned off as default.
Expand Down Expand Up @@ -1620,7 +1620,7 @@ An example:
# accessing n.thenPart is valid because the ``nkIf`` branch is active:
n.thenPart = Node(kind: nkFloat, floatVal: 2.0)
# the following statement raises an `FieldError` exception, because
# the following statement raises an `FieldDefect` exception, because
# n.kind's value does not fit and the ``nkString`` branch is not active:
n.strVal = ""
Expand Down Expand Up @@ -4063,7 +4063,7 @@ Example:
var a = readLine(f)
var b = readLine(f)
echo "sum: " & $(parseInt(a) + parseInt(b))
except OverflowError:
except OverflowDefect:
echo "overflow!"
except ValueError:
echo "could not convert string to integer"
Expand Down Expand Up @@ -4226,7 +4226,7 @@ the ``raise`` statement is the only way to raise an exception.
.. XXX document this better!
If no exception name is given, the current exception is `re-raised`:idx:. The
`ReraiseError`:idx: exception is raised if there is no exception to
`ReraiseDefect`:idx: exception is raised if there is no exception to
re-raise. It follows that the ``raise`` statement *always* raises an
exception.

Expand Down
8 changes: 4 additions & 4 deletions doc/tut2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ The syntax for type conversions is ``destination_type(expression_to_convert)``
proc getID(x: Person): int =
Student(x).id
The ``InvalidObjectConversionError`` exception is raised if ``x`` is not a
The ``InvalidObjectConversionDefect`` exception is raised if ``x`` is not a
``Student``.


Expand Down Expand Up @@ -160,7 +160,7 @@ An example:
condition, thenPart, elsePart: Node
var n = Node(kind: nkFloat, floatVal: 1.0)
# the following statement raises an `FieldError` exception, because
# the following statement raises an `FieldDefect` exception, because
# n.kind's value does not fit:
n.strVal = ""
Expand Down Expand Up @@ -388,7 +388,7 @@ The ``try`` statement handles exceptions:
let a = readLine(f)
let b = readLine(f)
echo "sum: ", parseInt(a) + parseInt(b)
except OverflowError:
except OverflowDefect:
echo "overflow!"
except ValueError:
echo "could not convert string to integer"
Expand Down Expand Up @@ -443,7 +443,7 @@ instance, if you specify that a proc raises ``IOError``, and at some point it
prevent that proc from compiling. Usage example:

.. code-block:: nim
proc complexProc() {.raises: [IOError, ArithmeticError].} =
proc complexProc() {.raises: [IOError, ArithmeticDefect].} =
...
proc simpleProc() {.raises: [].} =
Expand Down
4 changes: 2 additions & 2 deletions doc/tut3.rst
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ written.
result = quote do:
if not `arg`:
raise newException(AssertionError,$`lhs` & `op` & $`rhs`)
raise newException(AssertionDefect,$`lhs` & `op` & $`rhs`)
let a = 1
let b = 2
Expand All @@ -287,7 +287,7 @@ used to get this output.

.. code-block:: nim
if not (a != b):
raise newException(AssertionError, $a & " != " & $b)
raise newException(AssertionDefect, $a & " != " & $b)
With Power Comes Responsibility
-------------------------------
Expand Down
6 changes: 3 additions & 3 deletions examples/tunit.nim
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ proc foo: bool =
return true

proc err =
raise newException(ArithmeticError, "some exception")
raise newException(ArithmeticDefect, "some exception")

test "final test":
echo "inside suite-less test"
Expand All @@ -40,8 +40,8 @@ test "final test":
d > 10

test "arithmetic failure":
expect(ArithmeticError):
expect(ArithmeticDefect):
err()

expect(ArithmeticError, CatchableError):
expect(ArithmeticDefect, CatchableError):
discard foo()
8 changes: 4 additions & 4 deletions lib/core/typeinfo.nim
Original file line number Diff line number Diff line change
Expand Up @@ -204,14 +204,14 @@ proc `[]`*(x: Any, i: int): Any =
of tyArray:
var bs = x.rawType.base.size
if i >=% x.rawType.size div bs:
raise newException(IndexError, formatErrorIndexBound(i, x.rawType.size div bs))
raise newException(IndexDefect, formatErrorIndexBound(i, x.rawType.size div bs))
return newAny(x.value +!! i*bs, x.rawType.base)
of tySequence:
var s = cast[ppointer](x.value)[]
if s == nil: raise newException(ValueError, "sequence is nil")
var bs = x.rawType.base.size
if i >=% cast[PGenSeq](s).len:
raise newException(IndexError, formatErrorIndexBound(i, cast[PGenSeq](s).len-1))
raise newException(IndexDefect, formatErrorIndexBound(i, cast[PGenSeq](s).len-1))
return newAny(s +!! (align(GenericSeqSize, x.rawType.base.align)+i*bs), x.rawType.base)
else: assert false

Expand All @@ -221,15 +221,15 @@ proc `[]=`*(x: Any, i: int, y: Any) =
of tyArray:
var bs = x.rawType.base.size
if i >=% x.rawType.size div bs:
raise newException(IndexError, formatErrorIndexBound(i, x.rawType.size div bs))
raise newException(IndexDefect, formatErrorIndexBound(i, x.rawType.size div bs))
assert y.rawType == x.rawType.base
genericAssign(x.value +!! i*bs, y.value, y.rawType)
of tySequence:
var s = cast[ppointer](x.value)[]
if s == nil: raise newException(ValueError, "sequence is nil")
var bs = x.rawType.base.size
if i >=% cast[PGenSeq](s).len:
raise newException(IndexError, formatErrorIndexBound(i, cast[PGenSeq](s).len-1))
raise newException(IndexDefect, formatErrorIndexBound(i, cast[PGenSeq](s).len-1))
assert y.rawType == x.rawType.base
genericAssign(s +!! (align(GenericSeqSize, x.rawType.base.align)+i*bs), y.value, y.rawType)
else: assert false
Expand Down
4 changes: 2 additions & 2 deletions lib/deprecated/pure/sharedstrings.nim
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,11 @@ proc len*(s: SharedString): int = s.len

proc `[]`*(s: SharedString; i: Natural): char =
if i < s.len: result = s.buffer.data[i+s.first]
else: raise newException(IndexError, formatErrorIndexBound(i, s.len-1))
else: raise newException(IndexDefect, formatErrorIndexBound(i, s.len-1))

proc `[]=`*(s: var SharedString; i: Natural; value: char) =
if i < s.len: s.buffer.data[i+s.first] = value
else: raise newException(IndexError, formatErrorIndexBound(i, s.len-1))
else: raise newException(IndexDefect, formatErrorIndexBound(i, s.len-1))

proc `[]`*(s: SharedString; ab: HSlice[int, int]): SharedString =
#incRef(src.buffer)
Expand Down
8 changes: 4 additions & 4 deletions lib/impure/nre.nim
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ proc getinfo[T](pattern: Regex, opt: cint): T =

if retcode < 0:
# XXX Error message that doesn't expose implementation details
raise newException(FieldError, "Invalid getinfo for $1, errno $2" % [$opt, $retcode])
raise newException(FieldDefect, "Invalid getinfo for $1, errno $2" % [$opt, $retcode])

proc getNameToNumberTable(pattern: Regex): Table[string, int] =
let entryCount = getinfo[cint](pattern, pcre.INFO_NAMECOUNT)
Expand Down Expand Up @@ -331,7 +331,7 @@ func contains*(pattern: Captures, i: int): bool =
func `[]`*(pattern: CaptureBounds, i: int): HSlice[int, int] =
let pattern = RegexMatch(pattern)
if not (i in pattern.captureBounds):
raise newException(IndexError, "Group '" & $i & "' was not captured")
raise newException(IndexDefect, "Group '" & $i & "' was not captured")

let bounds = pattern.pcreMatchBounds[i + 1]
int(bounds.a)..int(bounds.b-1)
Expand Down Expand Up @@ -517,7 +517,7 @@ proc matchImpl(str: string, pattern: Regex, start, endpos: int, flags: int): Opt
of pcre.ERROR_NOMATCH:
return none(RegexMatch)
of pcre.ERROR_NULL:
raise newException(AccessViolationError, "Expected non-null parameters")
raise newException(AccessViolationDefect, "Expected non-null parameters")
of pcre.ERROR_BADOPTION:
raise RegexInternalError(msg : "Unknown pattern flag. Either a bug or " &
"outdated PCRE.")
Expand Down Expand Up @@ -718,7 +718,7 @@ proc replace*(str: string, pattern: Regex,
## - ``$#`` - first capture
## - ``$0`` - full match
##
## If a given capture is missing, ``IndexError`` thrown for un-named captures
## If a given capture is missing, ``IndexDefect`` thrown for un-named captures
## and ``KeyError`` for named captures.
replaceImpl(str, pattern, subproc(match))

Expand Down
Loading

0 comments on commit 7d6cbf2

Please sign in to comment.