Skip to content

Add raw pointers and pointer types. #30

@elucent

Description

@elucent

Basil compiles directly to native code, so it should be relatively straightforward to support unsafe pointer types and pointer arithmetic, at least from a codegen perspective. While the primary means of passing around reference types should be through garbage-collected pointers, supporting raw pointers would allow Basil to more easily express low-level function prototypes - useful for interacting with foreign functions.

I propose we introduce a new primitive type kind, "Pointer", that has a single parameter - the type it points to. We'll tentatively denote the type of a pointer to some type T as T ptr. Pointer types can be coerced generically to pointer types that point to a generic type like Any or a type variable. Besides this, pointer types support no other implicit coercions.

Pointers should, at minimum, support a few primary operations:

  • deref : T? ptr -> T?: dereferences a pointer and returns the value it points to.
  • addr : T? -> T? ptr: computes the address of a value and returns it as a pointer value. The parameter to addr must be an lvalue!
  • T? ptr as U? ptr: converts one pointer type to another. This is unchecked - unsafe pointer coercion is not a runtime or compile error!
  • T? ptr as Int: converts a pointer to an integer value.
  • Int as T? ptr: converts an integer to a pointer value. Between this and the previous conversion, rudimentary pointer arithmetic is achievable.

A few open questions:

  • Should we introduce new syntax for dereference and address-of operations? We could replicate C-style &val and *ptr syntax with a few new tokens. One less-invasive alternative would be Zig-style dot syntax: val.& and ptr.* would be easily expressed in the current Basil semantics.
  • Perhaps we could add some easier pointer arithmetic instructions than converting to and from Int? Maybe it could be type-based: ptr + Int could add the size of an Int to the address contained in ptr.

Metadata

Metadata

Assignees

No one assigned

    Labels

    planned featurePlanned feature for upcoming language revision.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions