What is «خطر»?
In short: outside خطر, the compiler checks bounds and overflow and forbids raw operations. Inside خطر: you write what is not checked: raw memory, indexing a raw pointer without a length, converting between pointer types, and بلا_فحص (unchecked) to switch off one particular check. A mistake there is your responsibility, but it is confined to a block you can see.
When you need it
Section titled “When you need it”- Raw memory:
احجز_خام(النوع, العدد)(allocate raw) and indexing it, for a buffer you pass to C, for example. - A raw pointer (
مؤشر_خام) coming from C, and reading what it points to. - Working with C when it needs memory Meem does not manage: a buffer a C function fills, or a C string without a terminating zero.
- Switching off one particular check with
بلا_فحصin a loop you know is safe.
خارجي (extern) itself, declaring a C function and calling it, does not need خطر when the types are ordinary:
خارجي "m" داله جذر_c(س كسر64) كسر64 باسم "sqrt"خارجي داله طول_c(ن نص) طبيعي64 باسم "strlen"اطبع(جذر_c(2.0))اطبع("ميم بالبايتات: ", طول_c("ميم"), "، وبالأحرف: ", طول("ميم"))خطر: م = احجز_خام(عدد32, 3) م[0] = 10 م[1] = 20 م[2] = 30 اطبع(م[0] + م[1] + م[2]) حرر(م)And why a beginner does not need it
Section titled “And why a beginner does not need it”Lists, dictionaries, structs and the standard modules are enough for most programs, and all of them are checked. A raw operation outside خطر is a compile error:
م = احجز_خام(عدد64, 2)Exit code: 2
In the error catalog: E0414
It keeps the danger in a visible place
Section titled “It keeps the danger in a visible place”When a program crashes with a memory error, you look in the خطر blocks first: they are the only places where checking was switched off. خطر داله makes the whole function unsafe, and whoever calls it needs خطر too.
But note: not every memory error is inside خطر. Using a list after حرر through another name is possible in ordinary code: the detector catches it in a direct run, and in a file built without the detector it is undefined behaviour. Details in memory in Meem.
--no-unsafe forbids it
Section titled “--no-unsafe forbids it”To run code you do not trust (someone else’s program, or a student’s exercise), the option --no-unsafe rejects any خطر, --no-ffi rejects خارجي, and --no-system rejects the two modules ملفات (files) and نظام (system):
خطر: م = احجز_خام(عدد32, 1) م[0] = 5 اطبع(م[0]) حرر(م)Exit code: 2
In the error catalog: E0415
These options restrict what can be written; they do not isolate the program: it runs with your full permissions.
See also
Section titled “See also”Lesson 21: «خطر» and calling C · The low-level layer · Calling C · What a program can do on your machine