• Stars
    star
    326
  • Rank 125,878 (Top 3 %)
  • Language
    C
  • Created almost 10 years ago
  • Updated almost 4 years ago

Reviews

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

Repository Details

Extending C with cmacro

Magma: cmacro extensions to C

Overview

C is a tremendously useful language: It compiles everywhere, is generally fast, has a very long history and a stable standard, and comes with few bedrock abstractions.

Higher-level languages, like Common Lisp and Haskell, provide excellent metaprogramming systems and a very expressive type system, but have the cost of various bedrock abstractions like garbage collection, dynamic typing (In the case of Lisp), and exception handling.

cmacro provides a middleground: It bridges the power and control of C with the high-level metaprogramming systems of Lisp. This library uses cmacro to extend the capabilities of the C language.

Usage

Once you've built and installed cmacro, simply put these files in a directory where they can be included by cmacro.

Functions

Anonymous Functions

Syntax

lambda (<args>*) -> <ret> { <body>* }

Description

Defines an anonymous function, returning a pointer to it.

Examples

cmacro_import "fn/lambda.c"

int main() {
  int array[] = {423, 61, 957, 133, 969,
                 829, 821, 390, 704, 596};

  qsort(array, 10, sizeof(int),
        lambda (const void* a, const void* b) -> int
        { return *(int*)a - *(int*)b; });
  for(size_t i = 0; i < 10; i++){
    printf("%i ", array[i]);
  }
  return 0;
}

Lazy Evaluation

Syntax

  • delay <expr>
  • force <expr>

Description

delay takes an expression expr and delays its computation until the required time. force takes this computation and executes it, returning its value.

Examples

force (delay 1) == 1;

Type System

Type-Inferenced Variables

Syntax

var <name> = <value>

Description

Defines an implicitly-typed variable var, giving it the value value. It is not possible to define a variable without an initial value.

Examples

/* Input */
cmacro_import "type/var.c"

void f() {
  var a = 10;
  var b = 3.14;
}

/* Output */
void f() {
  typeof(10) a = 10;
  typeof(3.14) b = 3.14;
  /* The above is, in fact, valid */
}

Algebraic Data Types

Syntax

Description

Examples

#include <stdio.h>

cmacro_import "type/adt.c"

data Token {
  Integer { int i; };
  String  { char* str; };
}

int main() {
  Token a, b;
  construct(a, Token -> Integer) { 10 };
  construct(b, Token -> String) { "test" };
  switch(a.type) {
    case TokenInteger:
      return a.Integer.i;
      break;
    case TokenString:
      puts(b.String.str);
      break;
  }
}

Tuples

Syntax

Description

Examples

/* Input */
cmacro_import "type/tuple.c"

typedef tup(int, int) pair;

pair divrem(int n, int d) {
  return (pair){n/d, n%d};
}

/* Output */
typedef struct { int first; int second; } pair;

pair divrem(int n, int d) {
  return (pair){n/d, n%d};
}

Anaphoric Macros

Anaphoric macros store the output of an important argument (Like the condition in the if statement) in a variable named it so they can be accessed in the statement body.

if

Syntax

  • aif <cond> <true-branch>
  • aif <cond> <true-branch> else <false-branch>

Description

The value of cond is stored in the variable it, which is accessible in the scope of either branch.

Examples

/* Input */
cmacro_import "anaphoric/if.c"

int main() {
  aif(5 > 1)
    return it;
}


/* Output */
int main() {
  typeof(5 > 1) it = 5 > 1;
  if(it)
    return it;
}

Utilities

doto

Syntax

doto(obj) { <fn>(<args>*);+ }

Description

Calls every fn, with obj appended to the beginning of its argument list.

Examples

/* Input */
cmacro_import "util/doto.c"

void cancelAccount(Account* account) {
  doto(account) {
    setBalance(0);
    setStatus(DISABLED);
  }
}

/* Output */
void cancelAccount(Account* account) {
  setBalance(account, 0);
  setStatus(account, DISABLED);
}

with_allocation

Syntax

  • with_allocation(<ptr>, <type>) { <body>* }
  • with_allocation(<ptr>, <type>, <length>) { <body>* }

Description

Allocates memory to hold type, optionally an array of type if length is specified. The pointer is stored in the variable ptr and free'd after body is executed.

Examples

cmacro_import "util/with_allocation.c"

int main() {
  with_allocation(ptr, int, 10) {
    size_t i;
    for(i = 0; i < 10; i++) {
      ptr[i] = i*2;
    }
  }
  with_allocation(p, int) {
    *p = 10;
    return *p;
  }
}

with_open_file

Syntax

with_open_file(<stream>, <filepath>, <mode>) { <body>* }

Description

Opens filepath with mode mode, assigning it to the variable stream, then executes body and closes the stream.

Examples

cmacro_import "util/with_open_file.c"

int main() {
  with_open_file(file, "README.md", "r") {
    printf("The first character in the README is: %c\n",
           fgetc(file));
  }
  return 0;
}

License

Copyright (c) 2014 Fernando Borretti ([email protected])

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

cmacro

Lisp macros for C
Common Lisp
876
star
2

corvus

Low-level Lisp for LLVM
Common Lisp
503
star
3

interim

Low-level Lisp with compile-time memory management
Standard ML
260
star
4

crane

An ORM for Common Lisp.
Common Lisp
197
star
5

lucerne

A web framework for Common Lisp, built on Clack
Common Lisp
142
star
6

cl-yaml

YAML parser for Common Lisp
Common Lisp
58
star
7

corona

Create and manage virtual machines from Common Lisp
Common Lisp
50
star
8

rock

Asset manager and compiler for Common Lisp web apps
Common Lisp
46
star
9

hermetic

Security for Clack-based Common Lisp web applications.
Common Lisp
43
star
10

trivial-ssh

An SSH client library for Common Lisp (Built on libssh2)
Common Lisp
40
star
11

docparser

Extract documentation from Common Lisp systems
Common Lisp
40
star
12

eco

Fast, flexible, designer-friendly templates for Common Lisp
Common Lisp
38
star
13

trivial-download

Download files from Common Lisp through Drakma.
Common Lisp
37
star
14

asdf-linguist

ASDF extensions.
Common Lisp
34
star
15

cl-pass

Password hashing and verification library
Common Lisp
30
star
16

swank-protocol

A low-level client for Swank
Common Lisp
29
star
17

spaced-repetition-tools

Scripts for generating flashcards.
Python
29
star
18

clack-errors

Error page middleware for Clack.
JavaScript
28
star
19

lime

A client for Swank
Common Lisp
25
star
20

dotfiles

Not guaranteed to work outside of My Machineβ„’
Emacs Lisp
20
star
21

find-port

Programmatically find open ports.
Common Lisp
19
star
22

trivial-open-browser

Open a browser window. From Common Lisp.
Common Lisp
18
star
23

parsing-menhir

Code for a tutorial on parsing with Menhir
OCaml
15
star
24

terminal-keypress

Read keyboard events in the terminal from Common Lisp
Common Lisp
14
star
25

eudoxia0.github.io

Personal website
HTML
14
star
26

lcm

Manage your system configuration in Common Lisp.
Common Lisp
12
star
27

astro-eog581

Astronomical calculations for The Epiphany of Gliese 581.
Common Lisp
10
star
28

terminal-size

Get the size of the terminal from Common Lisp
Common Lisp
10
star
29

parsimony

Parser combinators for Standard ML
Standard ML
9
star
30

clos-fixtures

CLOS fixtures.
Common Lisp
9
star
31

avatar-api

Get avatars from Gravatar and other services.
Common Lisp
9
star
32

postmaster

Email for humans
Common Lisp
8
star
33

arachne

A web crawling framework in Common Lisp.
Common Lisp
8
star
34

cl-virtualbox

Control VirtualBox from Common Lisp
Common Lisp
8
star
35

airloom

A reverse literate programming tool.
Haskell
7
star
36

cl-libyaml

libyaml bindings for Common Lisp
Common Lisp
6
star
37

concordia

A document preparation system
Standard ML
4
star
38

trivial-extract

Extract compressed files painlessly.
Common Lisp
4
star
39

cartesian

My personal exocortex
Python
3
star
40

l0

Linear Lisp
Standard ML
3
star
41

cl-base58

An implementation of base58 for Common Lisp
Common Lisp
3
star
42

parse-front-matter

A Jekyll-style front matter parser
Common Lisp
3
star
43

ctbnrle

Continuous Time Bayesian Network Reasoning and Learning Engine (CTBN-RLE)
C
3
star
44

which

The which command in Common Lisp
Common Lisp
2
star
45

clippings-parser

Export Kindle clippings to JSON, CSV, or Markdown.
Python
2
star
46

NeuriteTracer

An experiment in computer vision.
C++
2
star
47

lass-flexbox

Flexbox for Lass
Common Lisp
2
star
48

mlunit

A test framework for Standard ML
Standard ML
2
star
49

ocaml-nix-starter

OCaml starter project template using Nix for reproducibility.
Nix
2
star
50

git-file-history

View a file's git history, and individual commit info
Common Lisp
2
star
51

MNT

Molecular machinery built in NanoEngineer, in .mmp format.
1
star
52

sml-sqlite3

SQLite3 bindings for MLton
Standard ML
1
star
53

wax

TeX-like markup language experiment thing
Common Lisp
1
star
54

path-parse

Parse the PATH environment variable portably
Common Lisp
1
star
55

benchmarks

Common Lisp vs. the World
Common Lisp
1
star
56

texgen

Lisp DSL for generating TeX
Common Lisp
1
star
57

diy-clozemaster

Python
1
star