ncc: handle switch stmt where default label appears first
[neatcc/cc.git] / npp.c
blobce5d23e51324c8d2d41ada3298fa87327a560a70
1 /*
2 * neatpp - a small and simple C preprocessor
4 * Copyright (C) 2010-2011 Ali Gholami Rudi
6 * This file is released under GNU GPL version 2.
7 */
8 #include <errno.h>
9 #include <fcntl.h>
10 #include <stdio.h>
11 #include <string.h>
12 #include <stdlib.h>
13 #include <unistd.h>
14 #include <sys/stat.h>
15 #include "tok.h"
17 #define OBUFSZ (1 << 19)
19 static int rmcomments(char *d, char *s, int l)
21 char *e = s + l;
22 char *d1 = d;
23 char *r = s;
24 while (r < e) {
25 if (r + 3 < e && r[0] == '/' && r[1] == '*') {
26 memcpy(d, s, r - s);
27 d += r - s;
28 while (r + 1 < e) {
29 r++;
30 if (r[0] == '*' && r[1] == '/') {
31 r++;
32 break;
35 s = r + 1;
37 if (r + 1 < e && (r[0] == '\'' || r[0] == '"')) {
38 char c = r[0];
39 r++;
40 while (r < e && *r != c) {
41 if (*r == '\\')
42 r++;
43 r++;
46 r++;
48 memcpy(d, s, e - s);
49 d += e - s;
50 return d - d1;
53 static int xwrite(int fd, char *buf, int len)
55 int nw = 0;
56 while (nw < len) {
57 int ret = write(fd, buf + nw, len - nw);
58 if (ret == -1 && (errno == EAGAIN || errno == EINTR))
59 continue;
60 if (ret < 0)
61 break;
62 nw += ret;
64 return nw;
67 int main(int argc, char *argv[])
69 int ofd = 1;
70 int i = 1;
71 char *s1, *s2;
72 int nr;
73 int len = 0;
74 while (i < argc && argv[i][0] == '-') {
75 if (argv[i][1] == 'I')
76 cpp_addpath(argv[i][2] ? argv[i] + 2 : argv[++i]);
77 if (argv[i][1] == 'D') {
78 char *name = argv[i] + 2;
79 char *def = "";
80 char *eq = strchr(name, '=');
81 if (eq) {
82 *eq = '\0';
83 def = eq + 1;
85 cpp_define(name, def);
87 i++;
89 if (i + 1 >= argc) {
90 printf("usage: npp [-I idir] [-D define] input output\n");
91 return 0;
93 if (cpp_init(argv[i++]))
94 die("npp: cannot open <%s>\n", argv[i - 1]);
95 ofd = open(argv[i++], O_WRONLY | O_TRUNC | O_CREAT, 0600);
96 if (ofd < 0)
97 die("npp: cannot open <%s>\n", argv[i - 1]);
98 s1 = malloc(OBUFSZ);
99 s2 = malloc(OBUFSZ);
100 if (!s1 || !s2)
101 die("npp: cannot allocate enough memory\n");
102 while ((nr = cpp_read(s1 + len)) >= 0)
103 len += nr;
104 len = rmcomments(s2, s1, len);
105 xwrite(ofd, s2, len);
106 close(ofd);
107 return 0;