Skip to content

Clay for C++ programmers

jckarter edited this page Nov 27, 2010 · 33 revisions

This document is intended to introduce Clay to programmers familiar with C++. It isn't intended as a "Clay vs. C++" argument but as a purely informative comparison.

Clay vs C++: Executive summary

Clay's primary goal is to be a systems programming language, with a focus on performance and generic programming. Clay thus shares many features with C++:

  • Value semantics, and Resource-Acquisition-is-Initialization (RAII)
  • Raw memory access, including pointers and pointer arithmetic
  • Minimal runtime dependencies—no required VM or garbage collector
  • ABI compatibility with C
  • Templates (called generics in Clay)
  • ...

However, Clay also discards many C++ features:

  • Source compatibility with C
  • Language-level support for object-oriented programming (although Clay is flexible enough in which to implement a custom object system and to provide bindings to foreign object systems such as Cocoa, glib, or COM)
  • ...

On the other hand, it adds many new features over C++98:

  • Pervasive type propagation—nearly all types can be inferred
  • Generic specialization based on type predicates
  • Multiple dispatch through variant types
  • ...

and has many features also added by C++0x:

  • Variadic generics and types
  • Lambdas
  • Perfect forwarding
  • ...

Comparing "Hello World"

In C++:

  #include <iostream>
  int main() { std::cout << "Hello world!\n"; }

In Clay:

  main() { println("Hello world!"); }

This simple example introduces some basic differences between C++ and Clay:

  • Clay's io library is part of its prelude, a module implicitly available to every Clay module, so there is no need to include a header file to access the println function.
  • main does not need to declare its return type, because Clay will infer the type from the body of the function. Since there is no return statement, Clay infers that it returns no values. Clay also allows main to return an integer value back to the OS, as in C++.
  • Clay's println is a variadic function that prints zero or arguments to stdout, followed by a newline.

Type systems

Clay's set of fundamental types is similar to C and C++'s:

  • Sized integers: Int8, Int16, Int32, Int64 (aliased as Byte, Short, Int, and Long, respectively)
  • The corresponding unsigned integers: UInt8 etc. (with corresponding UByte etc. aliases)
  • Floating-point numbers: Float32, Float64 (aliased as Float and Double)
  • Pointers: Pointer[T] for any type T. Pointer[UInt8] is aliased as RawPointer
  • Arrays: Array[T,n] for any type T and integer size n

To ease communication with C libraries, Clay's standard library defines aliases CChar, CShort, CInt, CLong, CLongLong, CUChar, etc. that match the standard sizes for the corresponding C types.

Clay type names are also constructor/cast functions for their respective types:

  var x = Int(5.0); // x will equal the Int 5
  var y = Float(7); // y will equal the Float 7.0f
  var z = Pointer[UInt](&x); // z will be a pointer to UInt containing the address of x
  var w = Array[Int, 3](9, 18, 27); // w will be an array of the 3 Ints 9, 18, and 27

These types behave mostly similarly to their C++ counterparts; however, there are some minor differences:

  • Clay never implicitly converts between types, unlike C++. When calling functions, the parameter types must match exactly, even among integer or float types:

    foo(x: Int, y: Int) = x + y; // Function takes two Ints, returns an Int
    main() { println(foo(2u, 3u)); } // ERROR: 2u and 3u are UInt but foo expects Ints
    

    However, functions can be made generic on their inputs and perform conversions on behalf of their callers. See the Generics section for details.

  • Clay's Arrays have value semantics and do not degenerate into pointers when used in expressions or passed to functions, so this is valid and will copy x into y:

    var x = [1, 2, 3];
    var y = [4, 5, 6];
    y = x;
    

Clay also provides some primitive data structure types:

  • Tuples: Tuple[...T] for any set of types ...T. These provide anonymous structure types, similar to boost::tuple or std::tuple introduced in C++0x.
  • Unions: Union[...T] for any set of types ...T. Unlike C or C++'s unions, Clay Unions are anonymous like Tuples.

Clay has a special generic type Static[x] without a clear analog in C++. When used as a runtime value, a Clay function or type name x manifests itself as a value of the type Static[x]; for example, Int is of type Static[Int] and main is of type Static[main]. Integers and floats can also be introduced as static values using the static keyword: static 0 gives a value of the type Static[0]. A value of any of these types is empty and indistinguishable from any other value of the same type. Static values with their unique types allow compile-time constructs to be available as runtime values, and allow functions to be overloaded and specialized on numeric parameters using the unique types.

New types can be introduced with Clay using records and variants. A record, like a C++ struct, aggregates a set of member types:

  record Foo (x: Int, y: Float);

A variant is a type-safe union, similar to boost::variant in C++:

  variant Foo = Int | Float;

Unlike Clay Unions, C++ unions, or even boost::variant, Clay variants are open and can have new types introduced as instances, even from different modules. For example, in Clay any object that can be thrown must be a member of the Exception variant:

  record NoSuchFileError (filename: String);
  instance Exception = NoSuchFileError;

Records are constructed by field order:

  record Foo (x: Int, y: Float);

  var a = Foo(2, 3.0f); // a.x = 2, a.y = 3.0f

Variants are constructed from a member type:

  variant Foo = Int | Float;
  var a = Foo(5); // a contains an Int 5
  var b = Foo(7.0f); // b contains a Float 7.0f

As in C++, Clay types can be parameterized on type or numeric arguments. The primitive types Pointer[], Array[], Tuple[], Union[], and Static[] are parameterized in this way. New record or variant types can be defined with parameters too using the same [] syntax:

  record Foo[T] (x: Int, y: Array[T, 12]);
  variant Foo[T] = Int | Array[T, 12];

Operators

Both C++ and Clay allow operator overloading. In C++, operators are represented with special names of the form operator <op>:

  struct vec2 { double x, y; };
  
  vec2 operator+(vec2 a, vec2 b) { vec2 r = { a.x + b.x, a.y + b.y }; return r; }
  
  vec2 a = { 1.0, 2.0 };
  vec2 b = { 3.0, 4.0 };
  vec2 c = a + b;

In Clay, operators are treated as special syntax for a set of standard library functions. For example, the + operator invokes the add function:

  record Vec2 (x: Double, y: Double);
  
  overload add(a: Vec2, b: Vec2) = Vec2(a.x + b.x, a.y + b.y);
  
  var a = Vec2(1.0, 2.0);
  var b = Vec2(3.0, 4.0);

  var c = a + b;

Object lifecycle

Clay and C++ both allow custom types to implement custom value semantics and to control object resources by overloading copy construction, destruction, and assignment. A classic example is a string type that allocates a dynamic buffer in which to store the string contents. To safely manage its resources, the string type must allocate a new buffer when it is copied or assigned, and free the buffer when it is in destroyed. In C++, this is implemented using constructors, destructors, and operator= within a class:

  #include <cstring>
  using std::strdup;
  using std::free;

  class silly_string {
  private:
      char *str;
  public:
      silly_string(char const *s) : str(strdup(s)) {}

      silly_string(silly_string const &s)
          : str(strdup(s.str)) {}

      ~silly_string() { free(str); }
      
      silly_string &operator=(silly_string const &s) {
          free(str);
          str = strdup(s.str);
      }
  };

In Clay, constructors, destructors, and assignment are free functions. Destruction is performed by the destroy function, and assignment by the assign function:

  import libc.(strdup, free);
  
  record SillyString (str: Pointer[CChar]);
  
  overload SillyString(s: Pointer[CChar]) returned: SillyString {
      returned.str <-- strdup(s);
  }
  overload SillyString(s: SillyString) = SillyString(strdup(s.str));
  
  overload destroy(s: SillyString) { free(s.str); }
  
  overload assign(to: SillyString, from: SillyString) {
      free(to.str);
      to.str = strdup(from.str);
  }

Strings

In C++, literal strings evaluate to char const * pointers to immutable constant string data (or to arrays of char if used to initialize a character array), and the standard C++ library provides a std::string class for holding dynamically mutable, growable strings. Clay behaves similarly: Literal strings evaluate to StringConstant values, which are handles to immutable constant string data, and a String container supports dynamic strings.

Since Clay's StringConstants are a distinct type from Pointer[Char], they support high-level string and sequence operations directly without being cast to String:

  var x = "foo" + "bar"; // x will be String("foobar")
  for (c in "antidisestablishmentarianism") // iterate all the Chars in a string constant
      println(c, ": ", Int(c));

Char is also a distinct type from Int8 or UInt8, and must be explicitly converted. This allows the above example to correctly print c as a character and as an integer ASCII code. Like C++'s char, Clay Chars only represent 8-bit code points; multi-byte and Unicode support is left to the library.

...

Generics

C++ enables generic programming through template functions and template classes. Generic functions must be explicitly declared as such:

  // C++
  template<typename T>
  max(T const &x, T const &y) { return x > y ? x : y; }

In Clay, functions without type annotations are implicitly generic:

  // Clay
  max(x, y) = if (x > y) x else y;

...type patterns, parameterized types

Compile-time computation

C++ indirectly supports compile-time computation through template classes:

  template<int n>
  class factorial {
      static int value = n * factorial<n - 1>::value;
  };

  template<>
  class factorial<0> {
      static int value = 1;
  };

  int main() { std::cout << factorial<5>::value << "\n"; }

Clay directly supports compile-time computation through static values:

  [n | n > 0] factorial(static n) = n * factorial(static n - 1);
  overload factorial(static 0) = 1;
  
  main() { println(factorial(static 5)); }

Clone this wiki locally