r/Compilers • • 4d ago

optimistic or pessimistic compiler?

for those that compose and craft compilers, do you find the results better and more satisfying for you if the compiler you work on is permissive/optimistic or strict/pessimistic?

permissive/optimistic here means that the starting point is the compiler assumes the line of code that it is parsing/evaluating is probably ok but needs to pass some checks before translating to the target backend? (this is “the compiler is your friend” approach)

strict/pessimistic here means that the starting point is the compiler assumes the line of code that it is parsing/evaluating has something wrong and its job is to discover that wrong thing, and it is disappointed when the line passes all checks before translating to the target backend? (this is “the compiler is the teacher we’ve all had at one point in our life where they assume you’re going to do something bad as soon as they’re not looking” - and they’re not wrong)

obviously there has to be some balance here, but i’m curious, what has been your experience with these two approaches?

6 Upvotes

16 comments sorted by

6

u/flatfinger 4d ago

The only way I can imagine a compiler embodying your style of pessimism would be if the compiler would apply a reduction to any constructs contained within the source, in arbitrary order, and treat anything that was left over without having been reduced as an error. Aside from languages specialized for particular text reduction tasks, I don't see the concept as broadly useful.

A more interesting question of "optimism" versus "pessimism" concerns program transformations that will usually improve performance without adversely affecting semantics. Some compilers are designed to only apply such transforms in cases where they can be proven never to affect program semantics, while others are designed to apply them unless if they can be proven to affect program semantics. Compilers that are designed around the latter philosophy, such as clang and gcc, will often generate more efficient code in cases where their output happens to be correct, but may sometimes generate erroneous code.

4

u/Inevitable-Ant1725 3d ago

I'm worried about optimizations that assume that nothing is wrong.

For instance imagine in C++ you're returning a std::string

and the code is return !aBoolVar ? "true" : "false";

Clang will now assume that a bool is either 0 or 1 and set the length of the string as 5^aBoolVar.

But if the variable has an invalid value, then you'll get a crash.

I know languages usually don't have annotations for this, but maybe there should be an trust annotation that has to be earned or explicitly stated for that assumption.

3

u/GoblinsGym 4d ago

Whether your code makes sense is not for the compiler to decide.

It is a question of language design in my opinion. I like to have good type checks, but also want the freedom to do pointer arithmetic when it makes sense. I don't think I could get along with heavy handed ownership checks like in Rust. I do appreciate warnings for uninitialized or unused variables, though.

The compiler is just there to maintain law and order - syntax, type check, convert into appropriate machine code.

3

u/vmcrash 4d ago

If strict means to prevent possible bugs, then I'd prefer strict.

2

u/adityazero 3d ago

The observation I have is that frontend is optimistic (follows the language grammar and if some violations happen it emits an error. Even keeps going until it finds multiple errors).

Backend is pessimistic (rejects all the bad cases and only the perfect pattern that respects the 'as-if' rule becomes a candidate of optimization).

4

u/FluxProgrammingLang 4d ago

I prefer the optimistic compiler, and built my compiler around the principle that the programmer is intelligent and knows what they’re doing. It is assumed you know what you’re doing at all times. I don’t want my compiler holding my hand or having such strict language rules that I spend more time satisfying it than myself.

2

u/matthieum 4d ago

I consider myself intelligent. Anecdotes (IQ, relatives, friends, colleagues) all point to me being intelligent.

Doesn't mean I can't trip on my own feet, accidentally omit a word when typing a phrase, or a ! sign when typing a boolean condition.

I am intelligent, but I am all too fallible, especially when my damn brain is already thinking about the next thing when I'm still typing the previous one.

2

u/nzconstructionlawyer 3d ago

Good luck ever coming up with a clever enough compiler that it can identify you left out a ! in a condition lol

1

u/matthieum 3d ago

Indeed :'(

Fortunately there are some more obvious errors for the compiler to pick, like type errors -- returning a scalar instead of a list containing that scalar -- etc...

And linters can call out on dubious code. For example, in Rust's built-in linter (Clippy) there's a lint to warn about implementing operator X using operator Y. It's not always dead-on -- implementing exponent arithmetic, for example, trips it -- but... it's caught quite a few cases of copy/pasta/oops.

0

u/FluxProgrammingLang 3d ago edited 3d ago

Those are obviously grammar and syntax errors, which are caught. Why do people insist on the “most vexing parse” when reading what someone said? It’s like me telling you the oven only goes to 450°F, and you say well mine does, my family’s oven does, my neighbors oven does, but we don’t use plastic cooking pans cause they’ll melt. No way, really? Effectively reducing what i said to its most incorrect interpretation.

Here’s an example, say I assign a u64 ptr address to a u32 ptr without casting the value. This is an error in a lot of languages. Not in mine because I have a reason to do that sometimes.

Note to OP: be prepared for people to do what matthieum does to things you say.

1

u/reini_urban 3d ago

-fstrict optionally

1

u/Far-Championship-883 3d ago

this is actually a 2 pronged problem, the language itself by specification can force either.

1

u/ArthurAGF27 2d ago

Eu gostei bastante da sua analogia haha
Porém, em geral, eu acredito que compiladores "pessimistas" são a melhor abordagem a ser seguida. A função do compilador é fazer a tradução para que "a máquina entenda o que você quer dizer a ela" e execute as operações que você mandou. Mas nem sempre o que você quis dizer é o que ela vai entender, principalmente quando você comete algum erro pequeno que passa despercebido por você e pelo compilador. Esse comportamento é potencializado com compiladores permissivos! Por exemplo, em C o programa ex.c:

#include <stdio.h>
int main() {
    int x = 10;
    if (x = 5) {
        printf("x = 5\n");
    }
}

Nesse caso, muito provavelmente o programador queria fazer a comparação x == 5 e imprimir na tela apenas caso x tivesse esse valor, que ele acredita que seja 10 por conta da atribuição anterior. No entanto, ele esqueceu um "=" no if, e compilando com gcc ex.c -o ex isso passa normalmente, sem absolutamente nenhum alerta. Em programas de larga escala, coisas assim podem causar problemas muito maiores do que um printf errado, e esse problema seria alertado caso o programador estivesse usando pelo menos a flag -Wall, e a compilação seria interrompida com a utilização conjunta de -Werror.

Por isso, na minha opinião, no caso de compiladores é bom que eles sejam "um pouco chatos" e "pessimistas". Prefiro um compilador que tente identificar possíveis problemas, mesmo quando o código é válido sintaticamente e semanticamente, do que um que simplesmente aceite tudo e deixe para descobrir os problemas durante a execução. Isso pode evitar muitos problemas...

1

u/EggplantExtra4946 2d ago edited 2d ago

Compilers should strive to be 100% correct in all situations, it should only be allowed to make inaccurate transformations when asked to (-ffast-math, omitting integer overflow if overflows are catched by default, etc..). A buggy compiler is of no use to no one.

When your compiled program has a bug, do you really want to debug your program AND the compiler? Or when you know that your program is fully correct, do you really want the compiler to produce a possibly buggy exectutable? No, you really don't.

1

u/Odd_Walk6983 2d ago

So personally, I built my own compiler and VM to execute my own custom bytecode and then lower that to native C or C++ depending on what I'm building (Frontend or backend) which typically does whatever I need it to. I spent 6 months alone just building out the custom parsers and JIT detection modules lmfao... 🤦‍♂️So long answer, both. With a happy medium depending on your needs or preferences.

1

u/matthieum 4d ago

I like using Rust.

This should tell you all you need about my thoughts on this topic.

PS: In fact, I regularly find the Rust compiler not stringent enough.