Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Don't explicitly assign NULL values in setup functions:
While investigating something unrelated I stumbled across the `*_setup`
functions, and I noticed that they contain a lot of code that looks like this:

```c
self->abc = NULL;
self->xyz = NULL;
// ...
```

Something told me that assigning `NULL` to a bunch of fields is propably not
needed, and when looking at the docs for `tp_alloc()` I found this reference to
[`allocfunc`](https://docs.python.org/3/c-api/typeobj.html#c.allocfunc), the
typedef for `tp_alloc()`:

> It should return a pointer to a block of memory of adequate length for the
> instance, suitably aligned, **and initialized to zeros**, ...

Emphasis is mine.

Basically I added a simple check that removes lines similar to above which
assigns `NULL` values in setup functions. This removes about ~4100 lines from
the C file when self-compiling.
  • Loading branch information
dosisod committed Jun 6, 2023
commit 2fbf70914c66b186df1da71f870ed44793d64757
7 changes: 6 additions & 1 deletion mypyc/codegen/emitclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -578,7 +578,12 @@ def generate_setup_for_class(

for base in reversed(cl.base_mro):
for attr, rtype in base.attributes.items():
emitter.emit_line(rf"self->{emitter.attr(attr)} = {emitter.c_undefined_value(rtype)};")
value = emitter.c_undefined_value(rtype)

# We don't need to set this field to NULL since tp_alloc() already
# zero-initializes `self`.
if value != "NULL":
emitter.emit_line(rf"self->{emitter.attr(attr)} = {value};")

# Initialize attributes to default values, if necessary
if defaults_fn is not None:
Expand Down