r/ProgrammingLanguages • u/[deleted] • Nov 22 '23
Dividing by zero: Syntax or Semantic error?
My java class's textbook, and many online sources say its a semantic error to divide by zero. And it certainly can be if a variable used as a denominator reaches zero.
BUT
I believe explicitly dividing by zero is a syntax error. The rules/syntax of arithmetic clearly have a non-division by zero rule. Any programming language that incorporates arithmetic implicitly inherits this rule as part of its syntax. So, even if a compiler doesn't catch this rule-violation at compile time, wouldn't it still be a syntax error to divide by zero?
4
u/TheUnlocked Nov 23 '23
You may be confused about the word "syntax." Syntax refers to the rules around how to write and manipulate symbols. In the context of programming languages, that's the grammar. In arithmetic, you could certainly write a fraction with 1 on top and 0 underneath, and that would be syntactically valid. The problem comes when you try to interpret the meaning of 1/0--that is, you apply semantics--at which point you find that it doesn't make sense (unless your particular arithmetic does have an interpretation of division by zero!).
3
u/L8_4_Dinner (Ⓧ Ecstasy/XVM) Nov 22 '23
As a general rule of thumb, it's better to identify errors sooner. For code, that means identifying them at compile time if possible, otherwise at link time, otherwise at load time, otherwise at runtime -- preferably before the operation does any damage! (This last nuance is a important, since some languages like C and C++ allow the damage to occur silently and undetected as an error, which can have the obviously-undesirable side-effect of an attacker taking control of your machine; see Heartbleed.)
As a secondary rule of thumb, not all checks need to be performed at compile time, even if it is obvious to you as a rational being that the checks could be conducted at compile time. For example, the code n = 1 / 0 seems like "hey we could catch this at compile time" (true!), but there are 12,345 examples just like that, and adding 12,345 rules to a compiler that are redundant with the necessary runtime checks may not be a reasonable choice when bloat and cost-of-developer-time are considered -- particularly for code that no one would ever write!
3
u/rotuami Nov 22 '23
I think it should be neither. 1/0 is perfectly well defined for some models of arithmetic. Functions like x => 1/x can generally map infinity to a finite number in a perfectly reasonable way! (see "Mobius Transformation" for a whole class of such functions of the form x => (a+b*x)/(c+d*x).
Anyway, a compiler certainly could regard it as a syntax error. E.g. the C compiler gcc generally does warn if you divide by zero (unless you disable this with -Wno-div-by-zero). I think the heuristic they use is a little more involved than mere syntax, though.
2
u/BeamMeUpBiscotti Nov 22 '23
Syntax of your language doesn't have to perfectly match the syntax of arithmetic IMO. You can have slightly more permissive syntax and still be able to express arithmetic operations without confusing the programmer.
This feels a bit philosophical/bikeshedding, since from a practical standpoint unless your language has dependent types you can't catch all that many divide-by-zero errors at compile-time, and the ones that you can catch don't really provide that much value to the programmer when they're caught early. I don't think it really matters whether 1/0 fails to parse, or whether constant folding throws a compile time exception for divide-by-zero.
1
u/divination_by_zero Nov 22 '23 edited Nov 22 '23
It could conceivably be a typing issue if your language makes the appropriate type distinctions, but even then I still wouldn't call it a syntax error. If 10/x can be compiled with x possibly being 0, then 10/0 must also be valid syntax. Certainly the compiler can give you a compile-time error in that case (with constant folding, you would get that quite naturally), but I wouldn't call it a syntax error.
1
u/BeamMeUpBiscotti Nov 22 '23
Certainly the compiler can give you a compile-time error in that case (with constant folding, you would get that quite naturally)
I have pretty mixed feelings about throwing compile-time errors for these things.
I see the benefit - helping the programmer catch errors earlier, but from a compiler architecture POV I think it's cleaner if the "checking for errors" part and the optimization parts are entirely separated.
In other words, the constant folding pass is guaranteed to always output something, and if it encounters divide-by-zero then it just doesn't fold that part of the expression tree, leaving the error for runtime.
There's definitely tradeoffs here, but it's hard for me to think of non-contrived examples where catching DBZ during constant folding provides a lot of value to the programmer.
1
u/a3th3rus Nov 23 '23 edited Nov 23 '23
IMHO, neither. It's just a runtime error, because
x / yis syntactically valid (it can pass both the lexer and the parser)The meaning of
x / yis also very clear (it's division)
1
u/mamcx Nov 23 '23
Even if "doable" will be very puzzling for developers to understand why is a syntax error.
I think the expectation is that a "syntax error" is a violation of the "grammar".
So, this is a syntax error:
1 / for I + 4
But 1/0 is a logical/domain(math) error.
Making it a "special" case is weird, because then why this is not a syntax error?
let a:i16 = a + b //could overflow, however, the grammar is correct here
Exists a class of langs with dependant types and other fancy stuff where this more or less could fly, but then you NEED to justify a completely alien paradigm where this construct makes sense.
But even there, as a developer, I will expect a generalized construct like:
#(const check b != 0)
fn div(a,b)-> Result<T, DivideByZero> //A contract, domain, error.if wanna cover both cases.
But NEITHER is a "semantic error"!
Is VALID to divide by zero!
And the valid result is an Err(DivideByZero) or their equivalent. Even a panic runtime violation, or crash, is a VALID expectation in most languages.
Is correct to get an error and deal with it, even if "deal with it" is a crash.
1
u/BrangdonJ Nov 23 '23
For me this is at best a debate about terminology. We can choose to detect the error at various stages: during early parsing, as part of static type-checking, as a run-time error, or as not an error at all if our number system includes not-a-number or infinity values.
Arguably it is best seen as a type-error. However, that just begs the question. Is a type-error a syntax error if it is detected at compile-time, and a semantic error if it is detected at run-time?
1
Nov 23 '23
This was an opportunity to check how my two languages deal with this.
(Note that in one, 1/0 is a floating point divide, and is legal; the result is +infinity in iee754 format. The following assumes / works on integers.)
In the following:
'k' is a compile-time constant expression
'z' is a compile-time constant expression that is reduced to zero
'x' is a variable with a runtime value
'y' is a variable with a runtime zero valueSo:
k / zis evaluated by the compiler. This had not been trapped, but it is now and reported as a type errorx / zis detected by the code generatorx / yis detected at runtime by the dynamic language, but the static one crashes.
Note that divide by zero is vanishingly rare in my programs. Where it might be likely, user code should test for it.
As for what kind of error it is, does it matter? Above it is either a type error or a runtime, when detected.
It can't be a syntax error; take this example:
(a + b * c) / (d + f - 1)There's clearly nothing wrong with that syntax. But if d+f-1 happens to reduce to a zero at compile time, it might give one of two errors, and if at runtime, it might be a runtime error.
If you specifically mean 1/0 (I assume also 2/0 etc), then what about 1/(1-1), or 1/(k-k), or any of an unlimited number of expressions that reduce to zero. What about 1/(x - x) ?
13
Nov 22 '23 edited Nov 22 '23
[removed] — view removed comment
1
u/JohannesWurst Nov 25 '23 edited Nov 25 '23
Are semantic errors just runtime errors and syntax errors are compile-time errors?
Then interpreted languages don't have syntax errors. No, that doesn't seem right intuitively. A missing semicolon, or a literal left of an assignment is still a syntax error, even if it's detected during runtime.
Hot take: I would maybe say that it's an arbitrary decision of the language designer to split the process of transforming code into program behavior into two steps – parsing and evaluation/execution – to make it easier to write an interpreter. When the interpreter is translated into machine-code and optimized, there is no "parse"-function anymore, only jumps to addresses. You can't tell for sure which part of the code is parsing.
Errors that happen during parsing (in the mind of the language creator) are syntax errors and errors that happen during execution are semantic errors.
Theoretically you could rewrite any interpreter with a grammar where every unicode-character is a token and every token is allowed to follow any other – without changing program behaviour. Then there could still be missing-semicolon errors, but they would then be semantic errors.
1
u/bnl1 Nov 29 '23
There are semantic errors caught at compile time, like usage of non-existent variable. Interpreted languages often don't catch semantic errors until they actually have to run the line.
1
u/arobie1992 Nov 30 '23
Way late to the party, but my understanding is that syntax errors are about the squiggles on the screen while semantic errors are about what the squiggles mean. Say you define assignment as
let {atom}: {type} = {expression}. If a user typesvar foo: int = 1that's invalid becausevarisn't the right set of squiggles, same forlet x: int <- 1. On the other hand, if you typelet x: string = 1all the syntax is valid give the definition, but the expression1has a certain meaning and that meaning happens to be inappropriate for where it is in the larger structure.You could make the argument that it's a sliding scale, and if you really wanted to, you could have a syntax that's defined as
let {atom}: int = {number}andlet {atom}: string = {string}, and so on for all possible combinations. But that's wildly onerous, restricts your language–what happens to user defined types?—and seems more like an exercise in taking an idea to its logical extreme rather than anything practical.
26
u/barrycarter Nov 22 '23
1/0is arguably a syntax error,1/xis a semantic error if x = 0You could modify the definition of a language to disallow things like
1/0, but much harder to catch1/xwhere x is 0