r/Compilers • u/Trave11er3427 • 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
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.
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:Nesse caso, muito provavelmente o programador queria fazer a comparação
x == 5e imprimir na tela apenas caso x tivesse esse valor, que ele acredita que seja10por conta da atribuição anterior. No entanto, ele esqueceu um "=" noif, e compilando comgcc ex.c -o exisso passa normalmente, sem absolutamente nenhum alerta. Em programas de larga escala, coisas assim podem causar problemas muito maiores do que umprintferrado, 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.