aboutsummaryrefslogtreecommitdiff
path: root/ls_minify.c
blob: 33e43074bffbfe920fc9ea263e824ca1acd59537 (plain)
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
// This software disclaims copyright. Do what you want with it. Be gay, do
// crime. Originally written by Alexis Lockwood in 2021. Ⓐ

// --- DEPENDENCIES ------------------------------------------------------------

// Supporting modules
#include "ls.h"
#include "ls_internal.h"
#include "ls_lex.h"
#include "ls_minify_identgen.h"

// External dependencies
#include <libexplain/ferror.h>
#include <libexplain/fopen.h>
#include <libexplain/malloc.h>
#include <libexplain/realloc.h>

// Standard headers
#include <stdbool.h>
#include <stddef.h>
#include <inttypes.h>
#include <stdio.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <limits.h>
#include <string.h>

// --- PRIVATE MACROS ----------------------------------------------------------
// --- PRIVATE DATATYPES -------------------------------------------------------
// --- PRIVATE CONSTANTS -------------------------------------------------------
// --- PRIVATE FUNCTION PROTOTYPES ---------------------------------------------

static int _fetcher(void * arg, uint16_t loc);
static void _usage(char const * argv0, bool short_text);
static void _minify(FILE * f_out);

static void _min_word_or_str_label(ls_token_t tok);
static void _min_number_or_num_label(ls_token_t tok);
static void _min_float(ls_token_t tok);
static ls_token_t _min_keyword(ls_token_t tok);
static void _min_string(ls_token_t tok);
static void _min_operator(ls_token_t tok);
static void _min_comma(ls_token_t tok);
static void _min_semicolon(ls_token_t tok);
static void _min_newline(ls_token_t tok);

// --- PUBLIC VARIABLES --------------------------------------------------------
// --- PRIVATE VARIABLES -------------------------------------------------------

static uint8_t 		* g_code;	///< Code being minified
static size_t		g_code_len;	///< Length of code

static FILE		* g_f_out;	///< Output stream
static ls_t		g_ls;		///< Littlescript instance
static ls_token_t	g_last_tok;	///< Last token processed
static bool		g_eol_at_end;	///< Whether an EOL was emitted at end
static bool		g_have_ident_table; ///< Ident table was found
/// Whether a space should be added before words/numbers
static bool		g_add_space;

static bool		opt_keep_rems;
static bool		opt_min_idents;
static bool		opt_emit_ident_table;
static bool		opt_un_minify;

// --- PUBLIC FUNCTIONS --------------------------------------------------------

int main(int argc, char ** argv)
{
	int opt;
	while ((opt = getopt(argc, argv, "hiIru")) != -1)
	{
		switch (opt)
		{
		default:
			_usage(argv[0], false);
			exit(opt == 'h' ? EXIT_SUCCESS : EXIT_FAILURE);
			break;

		case 'I':
			opt_emit_ident_table = true;
			// fall through
		case 'i':
			opt_min_idents = true;
			break;

		case 'r':
			opt_keep_rems = true;
			break;

		case 'u':
			opt_un_minify = true;
			break;
		}
	}

	FILE * f = NULL;

	if (optind >= argc)
		f = stdin;
	else if (!strcmp(argv[optind], "-"))
		f = stdin;
	else
		f = explain_fopen_or_die(argv[optind], "r");

	size_t sz = 512;
	g_code = explain_malloc_or_die(sz);
	g_code_len = 0;

	while (!feof(f))
	{
		explain_ferror_or_die(f);

		size_t read_sz = sz - g_code_len;
		size_t n = fread(&g_code[g_code_len], 1, sz - g_code_len, f);
		g_code_len += n;

		if (read_sz == n)
		{
			sz *= 2;
			g_code = explain_realloc_or_die(g_code, sz);
		}
	}

	if (f != stdin)
		fclose(f);

	if (optind + 1 < argc)
	{
		if (!strcmp(argv[optind + 1], "-"))
			f = stdout;
		else
			f = explain_fopen_or_die(argv[optind + 1], "w");
	}
	else
		f = stdout;

	if (opt_un_minify)
		g_have_ident_table = ls_minify_load_mit(g_code, &g_code_len);

	_minify(f);

	if (opt_emit_ident_table)
	{
		if (!g_eol_at_end)
			fprintf(f, "\n");
		ls_minify_emit_mit(f);
	}

	free(g_code);

	if (f != stdout)
		fclose(f);

	return 0;
}

// --- PRIVATE FUNCTION DEFINITIONS --------------------------------------------

static int _fetcher(void * arg, uint16_t loc)
{
	(void) arg;
	if ((size_t) loc >= g_code_len)
		return -LS_NO_MORE_PROGRAM;
	else
		return (ls_uchar) g_code[(size_t) loc];
}

static void _usage(char const * argv0, bool short_text)
{
	fprintf(stderr, "usage: %s [OPTION...] [INPUT [OUTPUT]]\n", argv0);

	if (short_text)
		return;

	fprintf(stderr, "Minify a Littlescript file\n");
	fprintf(stderr, "\n");
	fprintf(stderr, "  -h    display this help text\n");
	fprintf(stderr, "\n");
	fprintf(stderr, "  -i    minify identifiers, making the code much\n");
	fprintf(stderr, "          less readable after un-minification\n");
	fprintf(stderr, "  -I    -i, but also emit an idents table to allow\n");
	fprintf(stderr, "          full un-minification\n");
	fprintf(stderr, "  -r    keep REM comments\n");
	fprintf(stderr, "  -u    un-minify\n");
}

static void _minify(FILE * f_out)
{
	ls_value_t pool[100]; // for labels

	ls_init(&g_ls, pool, sizeof pool / sizeof pool[0]);
	g_ls.fetcher = _fetcher;
	g_ls.fetcher_arg = NULL;

	if (setjmp(g_ls._error_jmp_buf))
	{
		uint16_t line = 0, col = 0;
		ls_translate_pc(&g_ls, g_ls._pc, &line, &col);
		fprintf(stderr, "error %d at %u:%u",
			(int) g_ls._error, line, col);
		exit(EXIT_FAILURE);
	}

	g_f_out = f_out;
	g_last_tok = LS_TOK_NONE;

	bool done = false;
	while (!done)
	{
		ls_token_t tok = ls_lex(&g_ls);

		g_add_space =
			g_last_tok == LS_TOK_NUMBER ||
			g_last_tok == LS_TOK_WORD ||
			(LS_TOK_KEYWORD(g_last_tok) && opt_un_minify) ||
			(LS_TOK_OPER(g_last_tok) && opt_un_minify) ||
			(g_last_tok == LS_TOK_COMMA && opt_un_minify) ||
			tok == LS_KW_ELSE;

		ls_token_t tok_for_last_tok = tok;

		switch (tok)
		{
		case LS_TOK_NUMBER:
		case LS_TOK_NUM_LABEL:
			_min_number_or_num_label(tok);
			break;

		case LS_TOK_WORD:
		case LS_TOK_STR_LABEL:
			_min_word_or_str_label(tok);
			break;

		case LS_TOK_FLOAT:
			_min_float(tok);
			break;

		case LS_TOK_STRING:
			_min_string(tok);
			break;

		case LS_TOK_COMMA:
			_min_comma(tok);
			break;

		case LS_TOK_SEMICOLON:
			_min_semicolon(tok);
			break;

		case LS_TOK_NEWLINE:
			g_eol_at_end = true;
			_min_newline(tok);
			break;

		case LS_TOK_INVALID:
			ls_throw_err(&g_ls, LS_SYNTAX_ERROR);
			break;

		default:
			if (LS_TOK_KEYWORD(tok))
				tok_for_last_tok = _min_keyword(tok);
			else if (LS_TOK_OPER(tok))
				_min_operator(tok);
			else
				ls_throw_err(&g_ls, LS_INTERNAL_ERROR);
			break;

		case LS_TOK_NONE:
			done = true;
			g_eol_at_end =
				(g_last_tok == LS_TOK_NEWLINE);
			break;
		}

		g_last_tok = tok_for_last_tok;
	}
}

static void _min_word_or_str_label(ls_token_t tok)
{
	if (g_add_space)
		fprintf(g_f_out, " ");

	assert(g_ls._token.word[LS_IDENT_OR_KW_LEN] == 0);
	g_ls._token.word[LS_IDENT_OR_KW_LEN] = 0;

	char const * ident;
	if (opt_min_idents || g_have_ident_table)
		ident = ls_minify_identgen(g_ls._token.word);
	else
		ident = g_ls._token.word;

	fprintf(g_f_out, "%s%s", ident,
		tok == LS_TOK_WORD ? "" :
		opt_un_minify ? ": " : ":");
}

static void _min_number_or_num_label(ls_token_t tok)
{
	if (g_add_space)
		fprintf(g_f_out, " ");

	fprintf(g_f_out, "%"PRId32"%s", g_ls._token.number,
		tok == LS_TOK_NUMBER ? "" :
		opt_un_minify ? ": " : ":");
}

static void _min_float(ls_token_t tok)
{
	(void) tok;
	ls_float_t f = g_ls._token.float_;
	ls_float_t g;
	char buf[32];
	int prec;

	for (prec = 25; prec > 0; prec -= 1)
	{
		snprintf(buf, sizeof(buf), "%.*g", prec, f);
		g = strtod(buf, NULL);
		if (g != f)
			break;
	}

	if (g_add_space)
		fprintf(g_f_out, " ");

	fprintf(g_f_out, "%.*g", prec + 1, f);
}

static ls_token_t _min_keyword(ls_token_t tok)
{
	if (tok == LS_KW_REM)
	{
		if (opt_un_minify)
		{
			if (g_add_space)
				fprintf(g_f_out, " ");
			fprintf(g_f_out, "REM ");
		}
		else if (opt_keep_rems)
		{
			uint8_t c = LS_KW_REM;
			fwrite(&c, 1, 1, g_f_out);
		}

		ls_addr_t pc_start;
		ls_addr_t pc_end;
		for (pc_start = g_ls._pc;; pc_start++)
		{
			if (pc_start >= g_code_len)
				break;
			if (!(g_code[pc_start] == ' '
				|| g_code[pc_start] == '\t'))
				break;
		}
		for (pc_end = pc_start;; pc_end++)
		{
			if (pc_end >= g_code_len)
				break;
			if (g_code[pc_end] == '\n')
				break;
		}

		g_ls._pc = (ls_addr_t)(pc_end + 1);
		if (opt_un_minify || opt_keep_rems)
		{
			fwrite(&g_code[pc_start],
				(size_t)(pc_end - pc_start), 1, g_f_out);

			fprintf(g_f_out, "\n");

			// We just emitted a \n, make sure the
			// next statement reflects that
			return LS_TOK_NEWLINE;
		}
		else
		{
			// Skipped entirely...
			return (uint8_t) g_last_tok;
		}
	}
	else if (!opt_un_minify)
	{
		uint8_t c = (uint8_t) tok;
		fwrite(&c, 1, 1, g_f_out);
		return tok;
	}
	else
	{
		if (g_add_space)
			fprintf(g_f_out, " ");
		fprintf(g_f_out, "%s",
			ls_kwmap[tok - LS_KW_OFFSET].name);
		return tok;
	}
}

static void _min_string(ls_token_t tok)
{
	(void) tok;
	if (opt_un_minify)
		fprintf(g_f_out, " ");

	fprintf(g_f_out, "\"");

	for (ls_addr_t i = g_ls._token.string[0];
		i <= g_ls._token.string[1];
		i++)
	{
		fprintf(g_f_out, "%c", g_code[i]);
	}

	fprintf(g_f_out, "\"");
}

static void _min_operator(ls_token_t tok)
{
	static const unsigned char ops[][3] = {
		[LS_OP_LEQ] = "<=",
		[LS_OP_GEQ] = ">=",
		[LS_OP_NEQ] = "<>",
		[LS_OP_LPAREN] = "(",
		[LS_OP_RPAREN] = ")",
		[LS_OP_MOD] = "%",
		[LS_OP_MUL] = "*",
		[LS_OP_ADD] = "+",
		[LS_OP_SUB] = "-",
		[LS_OP_DIV] = "/",
		[LS_OP_POW] = "^",
		[LS_OP_LT] = "<",
		[LS_OP_EQ] = "=",
		[LS_OP_GT] = ">",
	};

	assert(tok <= LS_OP_GT);

	if (opt_un_minify)
		fprintf(g_f_out, " ");

	fprintf(g_f_out, "%s", ops[tok]);
}

static void _min_comma(ls_token_t tok)
{
	(void) tok;
	fprintf(g_f_out, ",");
}

static void _min_semicolon(ls_token_t tok)
{
	(void) tok;
	fprintf(g_f_out, ";");
}

static void _min_newline(ls_token_t tok)
{
	(void) tok;

	if (g_last_tok != LS_TOK_NEWLINE &&
		g_last_tok != LS_TOK_STR_LABEL &&
		g_last_tok != LS_TOK_NUM_LABEL
	)
		fprintf(g_f_out, "\n");
}