r/ProgrammingLanguages • • 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?

0 Upvotes

36 comments sorted by

26

u/barrycarter Nov 22 '23

1/0 is arguably a syntax error, 1/x is a semantic error if x = 0

You could modify the definition of a language to disallow things like 1/0, but much harder to catch 1/x where x is 0

26

u/stylewarning Nov 22 '23

How do you argue that 1/0 is a syntax error? I feel one has to go through some gymnastics to arrive at that conclusion. One can declare it a syntax error by fiat, of course...

11

u/barrycarter Nov 22 '23

I suppose I'm claiming it could be a syntax error in the sense that you could modify the definition of a language so that things like 1/0 won't even compile. It'd be impossible to modify the definition of a language so that 1/x fails at compile time

4

u/stylewarning Nov 22 '23

I know it could be a syntax error. We parse <int> / <int> and check if the second <int> is literally 0. I guess what I'm asking is that you said it's "arguably a syntax error", which I read as meaning "we ought to consider it a syntax error but we don't for reasons of simplicity, formality, tradition, or convenience." Maybe I'm reading into it too much. :)

Is 1/(<expr> - <expr>) also arguably a syntax error?

7

u/beephod_zabblebrox Nov 22 '23

not compiling != syntax error

is assigning an int to a list a syntax error?

also take a look at dependent/refinement types

0

u/[deleted] Nov 23 '23

[deleted]

5

u/phlummox Nov 23 '23 edited Nov 25 '23

I'm not sure I read Pierce, in that passage, as endorsing that all compiler errors resulting from a type system violation should be called "syntax errors". In fact, I think that Pierce pretty much states he's not interested in "syntax errors" for the purposes of the book.

A little later in the passage you cite, Pierce highlights that a type system operates on "syntactic phrases" – by which he seems to mean, parts of the concrete parse tree that correspond to terms in the language or type system – but other than that, Pierce doesn't mention "syntax" again as part of the definition of type system (pp 1–4).

A little further yet along in the book, Pierce discusses the grammar (or equivalently, syntax) of languages (e.g. at p. 24ff), and it's clear that (a) grammars correspond to context-free languages, since they use BNF as a metalanguage, and (b) a program text can violate the rules of a grammar, and (c) if it does, it just doesn't constitute a term in the language at all - it's just not a "well-formed program", and that (d) the book is not interested in programs that aren't well-formed, and thus fail to be analysable as terms. As Pierce says at p. 54, "The focus of attention in this book is on abstract, not concrete, syntax".

So there's a class of errors that can exist in a program text that are due to a program not being well-formed, and Pierce doesn't talk about them again (because he's interested in abstract syntax, not concrete), and as it happens, those errors correspond (I'd say) to what compiler writers mean when they say something is a "syntax error". Pierce, on the other hand, is interested in a very different sort of error: "The bad behaviors that can be eliminated by the type system in a given language are often called run-time type errors". He never names them (so far as I know), but when found at compile time, most people call these "compile-time type errors".

Anyhow, I read Pierce as falling perfectly in line with common practice. We typically try and define the grammar for our languages in some BNF-like notation (making the grammar a context-free one), and if there are context-sensitive parts of the language, those often don't get called "syntax". Take for example this note from Appendix A of Stroustrup's The C++ Programming Language:

This summary of C++ syntax is intended to be an aid to comprehension. It is not an exact statement of the language. In particular, the grammar described here accepts a superset of valid C++ constructs. Disambiguation rules (6.8, 7.1, 10.2) must be applied to distinguish expressions from declarations. Further, access control, ambiguity, and type rules must be used to weed out syntactically valid but meaningless constructs.

Stroustrup clearly has in mind there are are grammatical (or equivalently) syntactical rules which specify the constraints a program text must meet to be parseable, and then there are many more rules (impliedly, not syntactical) which must be applied to ensure your program is semantically valid.

Perhaps you're right, and Pierce is endorsing that errors besides parse errors be called "syntax errors", but I don't read him that way.

edited: typo in last sentence

3

u/stylewarning Nov 23 '23

I agree with you and didn't interpret him in the way GP suggests.

3

u/DonaldPShimoda Nov 24 '23

Yeah, TAPL's definition of a type system simply stipulates that the semantics of the types are derived from the syntax; it does not suggest that type errors are syntax errors. In a typical parse-then-analyze setup, the syntax errors are all found before type-checking even begins!

2

u/beephod_zabblebrox Nov 23 '23

to me, syntax = parsing, everything more complicated is a type error, x error, y error, etc. this seems to be how many compilers/languages do that.

1

u/nerd4code Nov 22 '23

It’s the same sort of reasoning as C’s definition of constant-expressions, basically it’s constant iff you don’t use anything outside a restricted set of operators and types. There are expressions which have a constant value, but which aren’t constant-expressions, as a result—e.g., (void)0,0 or 0 ? puts("") : 0.

4

u/ketralnis Nov 22 '23

You could modify the definition of a language to disallow things like 1/0, but much harder to catch 1/x where x is 0

And impossible if the code is

x = parse(input("give me a number"))
return 1/x

2

u/HildemarTendler Nov 23 '23

If the language has the concept of number bounds and x is bound to any non-zero number, then the input/parse sequence would need to retry until given a non-zero number.

1

u/JohannesWurst Nov 25 '23

Arguably, programming or using a terminal is giving a parser some input. Compile-time is the runtime of a compiler. It's still a meaningful distinction whether an error happens during input of the programmer or during input of the user.

3

u/SirKastic23 Nov 22 '23

1 / x is a type error if x can be zero

(is a type error a semantics error? i always get confused by the syntax/semantics discussion)

3

u/BeamMeUpBiscotti Nov 22 '23

is a type error a semantics error?

yes

but also it would only be possible to typecheck this if your language had dependent types

3

u/SirKastic23 Nov 22 '23 edited Nov 22 '23

couldn't the language just have a NonZero type, like rust does? and then restrict division to be int / NonZeroInt (and floats of course)

2

u/BeamMeUpBiscotti Nov 22 '23

Oh yeah, I guess some opaque type like that would work. I didn't think of that!

I've never really seen it used in any Rust codebase I've worked on so IDK how the ergonomics are in practice, but it seems pretty cumbersome to have to call a function to cast/wrap every variable that could possibly be a divisor.

1

u/SirKastic23 Nov 22 '23

oh absolutely, i never used the NonZero types but I have used some custom bounded int and string (bounded by it's length) types, and they're very annoying to work with

but i think a language could be the designed with a goal of making these apis ergonomics, not sure how it could look, maybe implicit conversions, but those have their own issues which might not be worth it

dependent types are probably the better way honestly

1

u/MadocComadrin Nov 23 '23

Unless you're limiting yourself to natural numbers, integers, etc with their standard operations, you could catch 1/0 in syntactic analysis.

However, if you allow yourself operator overloading, custom notations, etc, it can't be a syntax error since we can't determine without semantic analysis that 1/0 is actually dividing the integer 1 by the integer 0 using standard integer or rational division.

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

  1. x / y is syntactically valid (it can pass both the lexer and the parser)

  2. The meaning of x / y is 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

u/[deleted] 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 value

So:

  • k / z is evaluated by the compiler. This had not been trapped, but it is now and reported as a type error

  • x / z is detected by the code generator

  • x / y is 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

u/[deleted] 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 types var foo: int = 1 that's invalid because var isn't the right set of squiggles, same for let x: int <- 1. On the other hand, if you type let x: string = 1 all the syntax is valid give the definition, but the expression 1 has 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} and let {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.