# encoding: utf-8 # frozen_string_literal: true module Carbon module Core module Pointer # Performs memory operations on a pointer. This is mainly alloc/free. # C library functions are included in another module. This defines # the following functions on the pointer type: # # - `.alloc(size: T): self` # - `.free(self): Carbon::Void` # # These are defined for every integer except boolean. module Memory # Defines all of the memory functions relative to each integer type. # # @see #define_alloc_function # @see #define_free_function # @return [void] def define_memory_functions Ints.each do |int| next if int.size == 1 define_alloc_function(int) end define_free_function end # Defines the `alloc` function with the given integer type as the # parameter. The `alloc` function allocates a block of memory and # returns it as a pointer. # # @param int [Core::Int] The integer type to be used as a parameter. # @return [void] def define_alloc_function(int) function_name = PTYPE.call(:alloc, [int.name]) Core.define(function: function_name) do |function| function[:return] = PTYPE define_alloc_definition(int, function[:definition]) end end # Defines the `free` function. The `free` function frees the current # pointer. # # @return [void] def define_free_function function_name = PTYPE.call(:free, [PTYPE]) Core.define(function: function_name) do |function| function[:return] = Carbon::Type("Carbon::Void") define_free_definition(function[:definition]) end end private def define_alloc_definition(int, definition) entry = definition.add("entry").build size = definition.params[0] size.name = "size" size = convert_int_size(int, size, entry) entry.ret(entry.array_malloc(PTYPEGEN, size).as(PTYPE)) end def define_free_definition(definition) entry = definition.add("entry").build this = definition.params[0] this.name = "self" entry.free(this) entry.ret_void end def convert_int_size(int, value, entry) size = Int.find(sign: :unsigned, size: 32) name = int.name.call(size.cast, [int.name]) entry.call(name, value).as(size.name) end end end end end