1  /* A toy re-implementation of CPython's object model.  */
       2  
       3  #include <stddef.h>
       4  #include <string.h>
       5  #include <stdlib.h>
       6  #include "analyzer-decls.h"
       7  
       8  typedef struct base_obj
       9  {
      10    struct type_obj *ob_type;
      11    int ob_refcnt;
      12  } base_obj;
      13  
      14  typedef struct type_obj
      15  {
      16    base_obj tp_base;
      17    void (*tp_dealloc) (base_obj *);
      18  } type_obj;
      19  
      20  typedef struct boxed_int_obj
      21  {
      22    base_obj int_base;
      23    int int_val;
      24  } boxed_int_obj;
      25  
      26  extern void int_del (base_obj *);
      27  
      28  type_obj type_type = {
      29    { &type_type, 1}
      30  };
      31  
      32  type_obj boxed_int_type = {
      33    { &type_type, 1},
      34    int_del
      35  };
      36  
      37  base_obj *alloc_obj (type_obj *ob_type, size_t sz)
      38  {
      39    base_obj *obj = (base_obj *)malloc (sz);
      40    if (!obj)
      41      return NULL;
      42    obj->ob_type = ob_type;
      43    obj->ob_refcnt = 1;
      44    return obj;
      45  }
      46  
      47  base_obj *new_int_obj (int val)
      48  {
      49    boxed_int_obj *int_obj
      50      = (boxed_int_obj *)alloc_obj (&boxed_int_type, sizeof (boxed_int_obj));
      51    if (!int_obj)
      52      return NULL;
      53    int_obj->int_val = val;
      54    return (base_obj *)int_obj;
      55  }
      56  
      57  void unref (base_obj *obj)
      58  {
      59    if (--obj->ob_refcnt == 0)
      60      obj->ob_type->tp_dealloc (obj);
      61  }
      62  
      63  void test_1 (const char *str)
      64  {
      65    base_obj *obj = new_int_obj (42);
      66    if (!obj)
      67      return;
      68    __analyzer_eval (((boxed_int_obj *)obj)->int_val == 42); /* { dg-warning "TRUE" } */
      69    __analyzer_eval (obj->ob_refcnt == 1); /* { dg-warning "TRUE" } */
      70    unref (obj);
      71  } /* { dg-bogus "leak" "" } */