Last active
August 29, 2015 14:06
-
-
Save maxattack/f5203c6bac3f88d58335 to your computer and use it in GitHub Desktop.
Cx - Syntax Proposal for an "easier" C Syntax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Runs on C runtime, exports C-ABI. | |
// No Headers | |
import cstdlib; | |
import cstdio; | |
struct vec2 { | |
float x, y; | |
// struct methods | |
float length() { | |
return sqrt(x*x + y*y); | |
} | |
} | |
// multiple return values | |
(float,float) components(vec2 v) { | |
return (v.x, v.y); | |
} | |
(FILE*, int) open_file(char[] filename, char[] mode) { | |
// local type inference | |
result := fopen(filename, mode); | |
if (result == 0) { | |
return (0, errno); | |
} else { | |
return (result, 0); | |
} | |
} | |
// operator overloading | |
vec2 operator*(float k, vec2 v) { return { k * v.x, k * v.y }; } | |
vec2 operator+(vec2 u, vec2 v) { return { u.x + v.x, u.y + v.y }; } | |
// go-like interfaces | |
interface updater { | |
void update(float dt); | |
} | |
/* | |
Storage equivalent to: | |
struct updater { | |
void *p_receiver; | |
void (*p_update)(void *self, float dt); | |
} | |
*/ | |
struct particle { | |
vec2 pos, speed; | |
void update(float dt) { | |
pos = pos + dt * speed; | |
} | |
} | |
struct shiny_particle { | |
particle; // go-style struct embedding | |
float shimmer; | |
void init() { | |
pos = { 0, 0 }; | |
speed = { 0, 0 }; | |
shimmer = 0; | |
} | |
particle* getp() { | |
// type name can also be used as a field accessor, too | |
return &this.particle; | |
} | |
} | |
void main(char[][] args) { | |
puts("Hello, World"); | |
// pointers just like in C | |
particle[100] buf; | |
particle* ptr = buf; | |
// interfaces validated/populated on assignment | |
updater up = ptr; // OK | |
up.update(0.333f); | |
vec2 v; | |
up = &v; // compiler error | |
// no "->" | |
printf("%f, %f\n", ptr.x, ptr.y); | |
// no exceptions, just error codes | |
fd, err := open_file("foo.txt", "r"); | |
if (err != 0) { | |
puts("derp"); | |
return -1; | |
} | |
// slices | |
particle[] first_half = buf[0:50]; | |
particle[] second_half buf[50:100]; | |
first_half[51]; // segfault | |
// checked access | |
p, err := second_half[20]; | |
if (err != 0) { | |
puts("derp, derp"); | |
return -2; | |
} | |
return 0; | |
} | |
// go-like namespace-level name visibility | |
namespace my_package { | |
struct foo { | |
int bar; | |
private int baz; | |
} | |
private void frob() { | |
puts("frob"); | |
} | |
void print_baz(foo x) { | |
printf("%d\n", x.baz); // legal, in namespace | |
} | |
} | |
void print_baz(my_package.foo x) { | |
my_package.frob(); // illegal | |
printf("%d\n", x.baz); // illegal | |
my_package.print_baz(x); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment