• Stars
    star
    196
  • Rank 198,553 (Top 4 %)
  • Language
    C
  • License
    Apache License 2.0
  • Created about 2 years ago
  • Updated 12 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Contemporary systems programming language in the spirit of C

Compis is a contemporary systems programming language in the spirit of C.

The compiler supports writing programs in mixed Compis and C; you can mix .c and .co source files. It accomplishes this by bundling some LLVM tools, like clang and lld into one executable. The LLVM dependency might go away someday.

"Compis" is a variation on the Swedish word "kompis", meaning "buddy" or "comrade." It's also a nod to one of the first computers I used as a kid.

Note: Compis is under development

Usage:

$ compis build -o foo main.co
$ ./foo

Since Compis bundles clang & lld, you can use it as a C and C++ compiler with cross-compilation capabilities:

$ compis cc hello.c -o hello
$ ./hello
Hello world
$ compis cc --target=aarch64-macos hello.c -o hello-mac
$ file hello-mac
hello-mac: Mach-O 64-bit executable arm64
$ compis c++ --target=wasm32-wasi hello.cc -o hello.wasm
$ wasmtime hello.wasm
Hello world

Features

  • Memory safety via ownership let x *Thing = thing // move, not copy
  • Simple: primitive values, arrays, structs and functions.
  • Convention over configuration: Sensible defaults. One way to do something.
  • Compiler is a statically-linked, single executable.
  • Hackable pragmatic compiler (parse β†’ type-check β†’ static analysis β†’ codegen β†’ link)

Tour of the language

Clarity

Compis attempts to make local reasoning about code as easy as possible. There are no implicit type conversion, no side effects from language constructs and the lifetime constraints of a value is explicitly encoded in its type.

Memory safety

Compis manages the lifetime of values which are considered "owners." In other words, memory allocation and deallocation is automatically managed. There's an escape hatch ("unsafe" blocks & functions; unimplemented) for when you need precise control.

A type is either considered "copyable" or "owning":

  • Copyable types can be trivially copied without side effects. For example, all primitive types, like int and bool, are copyable. The lifetime of a copyable value is simply the lifetime of its owning variable, parameter or expression.

  • Owning types have managed, linear lifetimes. They can only be copiedβ€”as in diverge, or "fork" if you willβ€”by explicit user code. When a value of owning type ceases to exist it is "dropped"; any drop() function defined for the type is called and if the type is stored in heap memory, it is freed.

Assigning a copyable value to variable (or using it as an rvalue expression in any situation, like passing it as an argument to a call) creates a distinct "deep" copy:

type Vec2 { x, y int }
type Line { start, end Vec2 }
var Line a
var b = a  // 'a' is copied
b.start.x = 2
assert(a.start.x == 0)

Assigning an owning value to a variable moves the value; its previous owner becomes inaccessible and any attempt to use the old owner causes a compile-time error.

type Vec2 { x, y int }
type Line { start, end Vec2 }
// implementing "drop" for Vec2 makes is an "owning" type
fun Vec2.drop(mut this) {}
var Line a
var b = a // 'a's value moves to 'b'
b.start.x = 2
a.start.x // error: 'a' has moved

References

References are used for "lending" a value somewhere, without a change in storage or ownership. Reference types are defined with a leading ampersand &T and created with the & prefix operation: &expr.

type Vec2 { x, y int }
fun rightmost(a, b &Vec2) int {
  // 'a' and 'b' are read-only references here
  if a.x >= b.x { a.x } else { b.x }
}
fun main() {
  var a = Vec2(1, 1)
  var b = Vec2(2, 2)
  rightmost(&a, &b) // => 2
}

Mutable reference types are denoted with the keyword "mut": mut&T. Mutable references are useful when you want to allow a function to modify a value without copying the value or transferring its ownership back and forth.

type Vec2 { x, y int }
fun translate_x(v mut&Vec2, int delta) {
  v.x += delta
}
fun main() {
  var a = Vec2(1, 1)
  translate_x(&a, 2)  // lends a mutable reference to callee
  assert(a.x == 3)
}

Compis does not enforce exclusive mutable borrowing, like for example Rust does. This makes Compis a little more forgiving and flexible at the expense of aliasing; it is possible to have multiple pointers to a value which may change at any time:

type Vec2 { x, y int }
type Line { start, end mut&Vec2 }
fun main() {
  var a = Vec2(1, 1)
  var line = Line(&a, &a)
  a.x = 2
  assert(line.start.x == 2)
  assert(line.end.x == 2)   // same value
}

This may change and Compis may introduce "borrow checking" or some version of it, that enforces that no aliasing can occur when dealing with references. Mutable Value Semantics is another interesting idea on this topic.

References are semantically more similar to values than pointers: a reference used as an rvalue does not need to be "dereferenced" (but pointers do.)

fun add(x int, y &int) int {
  let result = x + y  // no need to deref '*y' here
  assert(result == 2)
  return result
}

The only situations where a reference needs to be "dereferenced" is when replacing a mutable reference to a copyable value with a new value:

var a = 1
var b mut&int = &a
*b = 2   // must explicitly deref mutable refs in assignment
assert(a == 2)

Pointers

A pointer is an address to a value stored in long-term memory, "on the heap". It's written as *T. Pointers are "owned" types and have the same semantics as regular "owned" values, meaning their lifetime is managed by the compiler. Pointers can never be "null". A pointer value which may or may not hold a value is made optional, i.e. ?*T.

Planned feature: unmanaged "raw" pointer rawptr T which can only be created or dereferenced inside "unsafe" blocks.

type Vec2 { x, y int }
fun translate_x(v mut&Vec2, int delta) {
  v.x += delta
}
fun example(v *Vec2) {
  v.x = 1            // pointer types are mutable
  translate_x(&a, 2) // lends a mutable reference to callee
  assert(v.x == 1)
  // v's memory is freed here
}

Ownership

In this example, Thing is considered an "owning" type since it has a "drop" function defined. Compis will, at compile time, make sure that there's exactly one owner of a "Thing" (that it is not copied.)

type Thing {
  x i32
}
fun Thing.drop(mut this) {
  print("Thing dropped")
}
fun example(thing Thing) i32 {
  return thing.x
} // "Thing dropped"

When the scope of an owning value ends that value is "dropped":

  1. If the type is optional and empty, do nothing, else
  2. If there's a "drop" type function defined for the type of value, that function is called to do any custom cleanup like closing a file descriptor.
  3. If the value has subvalues that are owners, like a struct field, those are dropped.
  4. If the value is heap-allocated, its memory is freed.

Optional

Compis has optional types ?T rather than nullable types.

fun example(x ?i32) {
  // let y i32 = x  // error
  if x {
    // type of x is "i32" here, not "?i32"
    let y i32 = x // ok
  }
}

No uninitialized memory

Memory in Compis is always initialized. When no initializer or initial value is provided, memory is zeroed. Therefore, all types in Compis are valid when their memory is all zero.

type Vec3 { x, y, z f32 }
var v Vec3 // initialized to {0.0, 0.0, 0.0}

Variables

Compis has variables var and one-time bindings let. let bindings are not variable, they can not be reassigned once defined to. The type can be omitted if a value is provided (the type is inferred from the value.) The value can be omitted for var if type is defined.

var b i32 = 1 // a 32-bit signed integer
var a = 1     // type inferred as "int"
a = 2         // update value of a to 2
var c u8      // zero initialized
let d i64 = 1 // a 64-bit signed integer
let e = 1     // type inferred as "int"
e = 2         // error: cannot assign to binding
let f i8      // error: missing value

FUTURE: introduce a const type for immutable compile-time constants

FUTURE: support deferred binding, e.g. let x i8; x = 8

Building

Build an optimized product:

./build.sh

Build a debug product:

./build.sh -debug

Run co:

out/debug/co build -o out/hello examples/hello.c examples/foo.co
out/hello

Build & run debug product in continuous mode:

./build.sh -debug -wf=examples/foo.co \
  -run='out/debug/co build examples/hello.c examples/foo.co && build/debug/main'

More Repositories

1

inter

The Inter font family
Python
16,727
star
2

peertalk

iOS and Mac Cocoa library for communicating over USB
Objective-C
3,424
star
3

fb-mac-messenger

⚑️ Mac app wrapping Facebook's Messenger for desktop
Objective-C
2,856
star
4

kod

Programmers' editor for OS X [DEAD PROJECT]
Objective-C
2,296
star
5

node-imagemagick

Imagemagick module for NodeJS β€” NEW MAINTAINER: @yourdeveloper
JavaScript
1,807
star
6

markdown-wasm

Very fast Markdown parser and HTML generator implemented in WebAssembly, based on md4c
C
1,446
star
7

gotalk

Async peer communication protocol & library
Go
1,193
star
8

estrella

Lightweight and versatile build tool based on the esbuild compiler
TypeScript
1,098
star
9

raster

Raster β€” simple CSS grid system
CSS
806
star
10

js-lru

A fast, simple & universal Least Recently Used (LRU) map for JavaScript
JavaScript
774
star
11

sol

A sunny little virtual machine
C
516
star
12

scrup

Take a screenshot (in OS X) β€” paste the URL somewhere a second later
Objective-C
405
star
13

chromium-tabs

[historical] Chromium tabs for cocoa applications (project no longer maintained)
Objective-C
388
star
14

wasm-util

WebAssembly utilities
TypeScript
353
star
15

figplug

Figma plugin builder
TypeScript
336
star
16

cocui

Cocoa meets WebKit for more rapid UI development
Objective-C
329
star
17

ec2-webapp

A template I use to quickly set up Node.js-backed web apps on Amazon EC2
324
star
18

llvmbox

Self contained, fully static llvm tools & libs
C
317
star
19

move

A simple, functional-biased, prototypal and powerful programming language that runs on any ES3 (or better) JavaScript platform, aimed toward people new to programming
JavaScript
302
star
20

immutable-cpp

Persistent immutable data structures for C++
C++
281
star
21

rsm

Virtual computer
C
267
star
22

uilayer

CALayer-style API for building rich, high-performance UI graphics in WebKit
JavaScript
192
star
23

sublime-theme

My Sublime Text theme
Python
187
star
24

scripter

The Scripter Figma plugin
JavaScript
178
star
25

hue

A functional programming language
C++
170
star
26

gitblog

Git-based blog/cms for PHP, meant as a replacement for Wordpress
PHP
164
star
27

co

A programming language in early development
TypeScript
147
star
28

graphviz

Graphviz web app
JavaScript
118
star
29

LazyDispatch

Thin API and concept on top of libdispatch (aka Grand Central Dispatch) for Cocoa Objective-C code.
Objective-C
102
star
30

afcgi

Asynchronous/multiplexing FastCGI for nginx (incl. ref server implementation)
C
101
star
31

rsms-utils

Collection of CLI programs to help with everyday computer life
Shell
99
star
32

colang

Programming language and compiler β€”WORK IN PROGRESSβ€”
C
71
star
33

xsys

A well-defined system API for abstracting the OS platform
C
68
star
34

figma-plugins

Collection of Figma plugins
TypeScript
67
star
35

mkweb

simple static website generator
JavaScript
63
star
36

fontkit

JS & WASM library for working with fonts
C
62
star
37

js-object-merge

3-way JavaScript Object merging -- Object.merge(v1, v1a, v1b) -> v2
JavaScript
54
star
38

tc

Tokyo Cabinet Python bindings β€” In need of a new maintainer
C
54
star
39

smolmsg

Simple messages
Go
54
star
40

js-wasmc

Simplifies building of WebAssembly modules in C/C++ and JS
JavaScript
53
star
41

sigi-pixel-font

Sigi pixel fonts [archived]
52
star
42

WebView-OSX-Screensaver

WebKit web view as a screensaver on OS X
Objective-C
52
star
43

Go.tmbundle

TextMate bundle for the Go programming language
51
star
44

oui

Web-app client-server framework developed as part of dropular.net
JavaScript
49
star
45

wlang

Programming language in development
C
47
star
46

smisk

High performance web service framework, written in C but controlled by Python. Used by Spotify infra 2009–2015.
Python
45
star
47

memex

Software for archiving my digital stuff like tweets
Go
45
star
48

workenv

My personal work environment
Emacs Lisp
44
star
49

ckit

The little C kit
C
44
star
50

dropub

DroPub β€” drop and publish. Simple OS X MenuItem managing secure transfer of files in the background
Objective-C
42
star
51

serve-http

Simple, safe single-file local web server
JavaScript
42
star
52

go-uuid

Binary sortable universally unique identifier
Go
38
star
53

ghp

Go Hypertext Preprocessor
Go
38
star
54

TypoFig

Mac app for assisting type design in Figma
Objective-C
38
star
55

opencv-face-track-basics

Basic code for tracking faces and eyes using OpenCV
C++
37
star
56

qemu-macos-x86-arm64

Run arm64 Linux Alpine virtualized on macOS x86_64 with QEMU
Shell
35
star
57

tspkg

Create small, fast and easily-distributable packages from TypeScript projects
JavaScript
34
star
58

go-immutable

Immutable data structures for Go
Go
34
star
59

webkit-editor

Experimental text editor which runs in the browser
JavaScript
32
star
60

html5-video

Video player in HTML5
JavaScript
30
star
61

hovden-stitch

A typeface weekend project from 2002 with a classic "stitching"/"embroidery" look
30
star
62

jo

Go-style JavaScript ES6 compiler and packager, based on Babel
JavaScript
30
star
63

libcss-osx

Building libcss as Mac OS X universal binary. Developed as part of Kod (rsms/kod)
Objective-C
29
star
64

tumblr-theme-hunch

The theme used on my blog
28
star
65

dawn-lib

Builds Dawn on Linux and macOS as one single easier-to-use library
Shell
28
star
66

browser-require

CommonJS module require() for web browsers
JavaScript
25
star
67

jsont

A minimal and portable JSON tokenizer for building highly effective and strict parsers (in C and C++)
C
25
star
68

prog-lang-tutorial

JavaScript
25
star
69

node-fsdocs

Simple, ACID and versioned file-system based document database
JavaScript
25
star
70

js-fragment

Client-side templating for modern thinkers
JavaScript
24
star
71

node-couchdb-min

Simplistic CouchDB client with a minimal level of abstraction and connection pooling.
JavaScript
24
star
72

fontctrl

Font manager, keeping font files up to date with a distributed repository model
Go
23
star
73

web-clipboard-promise

Demonstrates lazily-evaluated clipboard data on the Web platform
JavaScript
22
star
74

bezier-tangent

BΓ©zier curve toy
JavaScript
22
star
75

twitter-icon

Alternative icon for Twitter.app
21
star
76

dropular-2010

Redacted snapshot of dropular.net, May 2010
JavaScript
21
star
77

dawn-wire-example

[WIP] Demo of a minimal but functional Dawn-based WebGPU client and server
C++
21
star
78

phpab

Abstract Base – universal PHP runtime library
PHP
18
star
79

NodeCocoa

Embed node.js in Cocoa or write whole Cocoa apps in node.js
Objective-C
17
star
80

ortho-remote

Some code for playing with the Teenage Engineering Ortho Remote
Objective-C
16
star
81

ml-kern

Kerning done by machines (a project to learn more about ML)
JavaScript
16
star
82

asl-logging

Convenience functions and example code for using ASL (Apple System Log facility)
C
14
star
83

js-miniglob

Minimal glob JavaScript implementation ported from Go's path/filepath
JavaScript
13
star
84

hunch-cocoa

An assortment of Cocoa β€” mixed extensions and additions to Cocoa
Objective-C
13
star
85

wasm-loader

WebAssembly module loader with import resolution
TypeScript
12
star
86

cgui

super duper simple gui for C, wrapping imgui and stb
C
12
star
87

cmdr

Helps writing command-line programs with subcommands in Go
Go
12
star
88

spotifycocoa

Cocoa framework of libspotify
Objective-C
12
star
89

macfusion

Fork of http://svn.macfusionapp.org/macfusion2/trunk/ β€” With mainly UI changes like menu item icon and OS-standard volume icons) β€” Download latest release build: http://cloud.github.com/downloads/rsms/Macfusion/Macfusion.zip
Objective-C
12
star
90

hunch-upload

Multiple concurrent files uploads with progress in pure HTML
JavaScript
11
star
91

functional.js

Work in a functional style with JavaScript and TypeScript
JavaScript
11
star
92

coxlang

Programming language w/ subproject that implements the Go scheduler in C++
C++
11
star
93

lolcatos

The lolcat operating system
Assembly
11
star
94

cometps

Simple comet pub/sub
C
9
star
95

node-imgdb

Image fingerprinting
C++
8
star
96

ssl-client-auth-demo

Demonstrates "client-authenticated TLS handshake"
Shell
8
star
97

connect_facebook

Facebook session support for Connect
8
star
98

mode

Node module manager and repository
JavaScript
8
star
99

flup

Drag-and-drop to quickly put images on Flickr
Objective-C
8
star
100

ipvec

Educational persistent vector implementation in C
C
8
star