|
|
Log in / Subscribe / Register

MISRA

MISRA

Posted Sep 19, 2021 5:14 UTC (Sun) by NYKevin (subscriber, #129325)
In reply to: MISRA by tialaramex
Parent article: Conill: The long-term consequences of maintainers’ actions

> Some of the 16.x rules are forbidding things no sane C programmer would do, and many would be surprised to discover are legal, such as trying to declare variables in one part of a switch and then use them in a different part even though presumably either declaration or usage won't happen when the statement is executed. Sure enough these things aren't legal Rust. But what's much nicer is that Rust also covers off some MISRA rules that apply to real C code that real programmers write. MISRA is worried about two things C programmers actually do that can hide terrible faults. Falling through, and inexhaustive matching. The C rules cover these by requiring break; religiously for each clause, and by requiring default religiously in every switch statement.

Just riffing off of this point: A switch statement is a computed goto in a funny hat. It happens to be the least-bad way of expressing "At compile time, I have N different possibilities, and I want to select and execute exactly one of them at runtime," but it isn't actually designed to provide that invariant. You can freely interleave case statements and any other program logic you like, leading to abuses like Duff's device (admittedly, an extreme example, which I have no doubt that MISRA forbids six ways to Sunday).

OTOH, a Rust match statement, to my understanding, *is* specifically designed to provide the "exactly one branch gets executed" invariant, and so you don't need (as many) rules telling you how to use it.


to post comments

MISRA

Posted Sep 19, 2021 18:12 UTC (Sun) by tialaramex (subscriber, #21167) [Link]

Technically match is actually an expression, and so it's logically _obliged_ to follow only one arm because the expression obviously only has one value, and in fact the values in each arm must be type compatible, the Rust compiler will conclude that whichever type is compatible with all the arms is in fact the type of the expression, if there is no suitable type that's an error.

https://play.rust-lang.org/?version=stable&mode=debug...

The compiler points out that two of the arms are clearly integers while another is an &str (in this case a string literal).

In many cases the idiomatic Rust way to express what you wanted actually does involve values from each arm, but of course it is possible for your match to be full of procedural code in which case those values are just the empty tuple -- or for it to have statements which outright leave the match (such as "return" or "break") and these are in fact type compatible with anything.


Copyright © 2026, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds