# sexp.md -rw-r--r-- 1.3 KiB View raw

#s-expressions

s-expressions are the good idea hiding in Lisp. Use them in place of JSON or Protobuf for program-to-program communication.

Advantages:

s-expressions are relatively easy for a human to read and write, but you should be inspecting it more often than writing it by hand.

A <300 line C implementation is provided further down. It's used like so:

char *dept = "finance";
int salary = 90000;
char *name = "Jane Doe";
ha_sexp_printf("(ads)", dept, salary, name);
// prints (finance 90000 "Jane Doe")

To scan this back in:

char dept[16];
int salary;
char *name = NULL;
int n = ha_sexp_scanf("(ads)", &dept, sizeof(dept), &salary, &name);
if (n != 5) {
	// Input does not match spec
}
// ...
free(value);

Grammar (McKeeman form):

sexpr
	value
	'(' sexpr ')'

value
	atom
	string
	integer
	float

atom
	alnum
	atom alnum

string
	'""'
	'"' characters '"'

characters
	character
	character characters

character
	'0020' . '10FFFF' - '"' - '\'
	"\u" hex hex hex hex
	'\' '\'
	'\' '"'

digit
	'0' . '9'

digits
	digit
	digit digits

integer
	digits

float
	digits '.' digits

alnum
	digit
	'a' . 'z'
	'_'
	'-'

hex
	'a' . 'f'
	digit

Put that on your business card, Crockford.

# sexp.h -rw-r--r-- 2.3 KiB View raw
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#ifndef HA_SEXP_H
#define HA_SEXP_H

/**
 * Prints an s-expression to stdout. The spec string is a list of format
 * specifiers describing the structure of the s-expression. Unlike the stdio
 * family of printing functions, % is not used - each character is interpreted
 * directly and there is no means provided for emitting additional unstructured
 * text. The value of each specifier is provided in the remaining arguments.
 * The following format specifiers are used:
 *
 * a: atom (string: alphanumeric, plus _ and -, no spaces)
 * s: string
 * d: integer
 * f: floating point number
 * (, ): list
 * ' ', '\n', '\t': copied to output
 *
 * The return value is the number of bytes written.
 *
 * To write a variable-length list, omit the closing ) from the format string,
 * then call printf several times to write each member. Finish with a final ).
 */
int ha_sexp_printf(const char *spec, ...);

/**
 * Scans an s-expression from stdin which matches the given format specifier,
 * and populates the remaining arguments with the values found in the
 * s-expression. The same format specifiers as ha_sexp_printf are supported, but
 * with the following constraints:
 *
 * a, s: pass one char * argument and one size_t argument with the buffer
 * length. If the buffer length is exceeded, errno is set to ENOBUFS.
 *
 * A, S: pass one char ** argument, which must be initialized to NULL. The
 * buffer will be allocated. ENOMEM may be returned if the buffer cannot be
 * allocated. In the case of an error, your pointer will remain NULL and does
 * not need to be freed.
 *
 * In the case of invalid strings or atoms, errno is set to EINVAL.
 *
 * The return value is the number of values successfully scanned in. This
 * number includes ( and ), but does not include whitespace characters. The
 * caller SHOULD check that this number meets their expectations and should
 * treat this as an error if not.
 *
 * To scan a variable-length list, include the closing ) in your format string.
 * If the return value is equal to the number of values -1, there are additional
 * members to scan. Scan each of these additional members without the opening (,
 * but include the closing ). Continue scanning until the ) is included in the
 * number of successfully scanned values.
 */
int ha_sexp_scanf(const char *spec, ...);

#endif
# sexp.c -rw-r--r-- 4.2 KiB View raw
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include "sexp.h"

static int
put_atom(const char *str)
{
	int i;
	for (i = 0; str[i]; ++i) {
		assert(isalnum(str[i]) || str[i] == '-' || str[i] == '_');
		putchar(str[i]);
	}
	return i;
}

static int
put_string(const char *str)
{
	int i;
	putchar('"');
	for (i = 0; str[i]; ++i) {
		switch (str[i]) {
		case '"':
			putchar('\\');
			putchar('"');
			break;
		case '\\':
			putchar('\\');
			putchar('\\');
			break;
		default:
			if (isprint(str[i])) {
				putchar(str[i]);
			} else {
				printf("\\u%4x", str[i]);
			}
			break;
		}
	}
	putchar('"');
	return i + 2;
}

int
ha_sexp_printf(const char *s, ...)
{
	va_list ap;
	va_start(ap, s);
	int l = 0;
	char c;
	while ((c = *s)) {
		++s;
		switch (c) {
		case 'a':
			l += put_atom(va_arg(ap, const char *));
			break;
		case 'd':
			l += printf("%d", va_arg(ap, int));
			break;
		case 'f':
			l += printf("%f", va_arg(ap, double));
			break;
		case 's':
			l += put_string(va_arg(ap, const char *));
			break;
		case '(':
			putchar('(');
			++l;
			continue;
		case ')':
			putchar(')');
			++l;
			break;
		case ' ':
		case '\n':
		case '\t':
			putchar(c);
			++l;
			continue;
		default:
			assert(0);
		}
		if (*s && *s != ')') {
			putchar(' ');
			++l;
		}
	}
	va_end(ap);
	return l;
}

static char *
scan_atom(char *buf, size_t sz)
{
	size_t bufsz = 1024;
	if (sz == 0) {
		assert(buf == NULL);
		buf = malloc(bufsz);
		if (!buf) {
			errno = ENOMEM;
			goto error;
		}
	}
	char c;
	while (isspace(c = getchar()) && c != -1);
	buf[0] = c;
	for (size_t i = 1; sz == 0 || i < sz; ++i) {
		if (sz == 0 && i >= bufsz) {
			char *newbuf = realloc(buf, bufsz * 2);
			if (!newbuf) {
				errno = ENOMEM;
				goto error;
			}
			bufsz *= 2;
			buf = newbuf;
		}
		c = getchar();
		if (c == -1) {
			buf[i] = '\0';
			return buf;
		}
		if (isspace(c) || c == ')') {
			ungetc(c, stdin);
			buf[i] = '\0';
			return buf;
		}
		if (!isalnum(c) && c != '-' && c != '_') {
			errno = EINVAL;
			goto error;
		}
		buf[i] = c;
	}
	errno = ENOBUFS;
error:
	if (sz == 0) {
		free(buf);
	}
	return NULL;
}

static char *
scan_str(char *buf, size_t sz)
{
	char c;
	while (isspace(c = getchar()) && c != -1);
	if (c != '"') {
		return NULL;
	}
	size_t bufsz = 1024;
	if (sz == 0) {
		assert(buf == NULL);
		buf = malloc(bufsz);
		if (!buf) {
			errno = ENOMEM;
			goto error;
		}
	}
	for (size_t i = 0; sz == 0 || i < sz; ++i) {
		if ((c = getchar()) == -1) {
			goto inval;
		}
		if (sz == 0 && i >= bufsz) {
			char *newbuf = realloc(buf, bufsz * 2);
			if (!newbuf) {
				errno = ENOMEM;
				goto error;
			}
			bufsz *= 2;
			buf = newbuf;
		}
		if (c == '"') {
			/* Success */
			buf[i] = '\0';
			return buf;
		}
		unsigned int n;
		switch (c) {
		case '\\':
			c = getchar();
			if (c == -1) {
				goto inval;
			}
			switch (c) {
			case '"':
			case '\\':
				buf[i] = c;
				break;
			case 'u':
				if (scanf("%4x", &n) != 1) {
					goto inval;
				}
				buf[i] = (char)n;
				break;
			default:
				goto inval;
			}
			break;
		default:
			buf[i] = c;
			break;
		}
	}
	errno = ENOBUFS;
	goto error;
inval:
	errno = EINVAL;
error:
	if (sz == 0) {
		free(buf);
	}
	return NULL;
}

int
ha_sexp_scanf(const char *s, ...)
{
	va_list ap;
	va_start(ap, s);
	int n = 0, r;
	char c;
	char *str, **strptr;
	size_t sz;
	while ((c = *s)) {
		++s;
		r = 0;
		switch (c) {
		case 'a':
			str = va_arg(ap, char *);
			sz = va_arg(ap, size_t);
			r = scan_atom(str, sz) != NULL;
			break;
		case 's':
			str = va_arg(ap, char *);
			sz = va_arg(ap, size_t);
			r = scan_str(str, sz) != NULL;
			break;
		case 'A':
			strptr = va_arg(ap, char **);
			*strptr = scan_atom(NULL, 0);
			r = *strptr != NULL;
			break;
		case 'S':
			strptr = va_arg(ap, char **);
			*strptr = scan_str(NULL, 0);
			r = *strptr != NULL;
			break;
		case 'd':
			r = scanf("%d", va_arg(ap, int *));
			break;
		case 'f':
			r = scanf("%lf", va_arg(ap, double *));
			break;
		case '(':
		case ')':
			if (getchar() != c) {
				va_end(ap);
				return n;
			}
			r = 1;
			break;
		case ' ':
		case '\n':
		case '\t':
			/* no-op */
			continue;
		}
		if (r == 0) {
			/* error */
			break;
		}
		n += r;
	}
	va_end(ap);
	return n;
}
# LICENSE -rw-r--r-- 1.0 KiB View raw
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Copyright (c) 2020 Drew DeVault

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.