Skip to content

Rewrite Method to Function Call Has Fix

Description

In C, there is no built-in support for object-oriented programming, but some programmers use structs and function pointers to simulate classes and methods. However, this style can have some drawbacks, such as:

  • extra memory allocation and deallocation for the struct and the function pointer.
  • indirection overhead when calling the function pointer.

A possible alternative is to use a plain function call with the struct pointer as the first argument.

YAML

yaml
id: method_receiver
language: c
rule:
  pattern: $R.$METHOD($$$ARGS)
transform:
  MAYBE_COMMA:
    replace:
      source: $$$ARGS
      replace: '^.+'
      by: ', '
fix:
  $METHOD(&$R$MAYBE_COMMA$$$ARGS)

Example

c
void test_func() {
    some_struct->field.method();
    some_struct->field.other_method(1, 2, 3);
}

Diff

c
void test_func() {
    some_struct->field.method();
    method(&some_struct->field);
    some_struct->field.other_method(1, 2, 3);
    other_method(&some_struct->field, 1, 2, 3);
}

Contributed by

Surma, adapted from the original tweet

Made with ❤️ with Rust