summaryrefslogtreecommitdiff
path: root/src/depend/depend.cpp
blob: ce42f1345e47fd021a8b9a0615f8057235ad6728 (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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
/* $Id$ */

/**
 * @file depend/depend.cpp Custom implementation of Makedepend.
 *
 * We previously used makedepend, but that could not handle the amount of
 * files we have and does not handle conditional includes in a sane manner.
 * This caused many link problems because not enough files were recompiled.
 * This has lead to the development of our own dependency generator. It is
 * meant to be a substitute to the (relatively slow) dependency generation
 * via gcc. It thus helps speeding up compilation. It will also ignore
 * system headers making it less error prone when system headers are moved
 * or renamed.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <unistd.h>
#include <map>
#include <set>
#include <stack>

/** Simple string comparator using strcmp as implementation */
struct StringCompare {
	/**
	 * Compare a to b using strcmp.
	 * @param a string to compare.
	 * @param b string to compare.
	 * @return whether a is less than b.
	 */
	bool operator () (const char *a, const char *b) const
	{
		return strcmp(a, b) < 0;
	}
};
/** Set of C-style strings. */
typedef std::set<const char*, StringCompare> StringSet;
/** Mapping of C-style string to a set of C-style strings. */
typedef std::map<const char*, StringSet*, StringCompare> StringMap;
/** Pair of C-style string and a set of C-style strings. */
typedef std::pair<const char*, StringSet*> StringMapItem;

/** Include directory to search in. */
static StringSet _include_dirs;
/** Files that have been parsed/handled with their dependencies. */
static StringMap _files;
/** Dependencies of headers. */
static StringMap _headers;
/** The current 'active' defines. */
static StringSet _defines;

/**
 * Helper class to read a file.
 */
class File {
public:
	/**
	 * Create the helper by opening the given file.
	 * @param filename the file to open
	 * @post the file is open; otherwise the application is killed.
	 */
	File(const char *filename) : filename(filename)
	{
		this->fp = fopen(filename, "r");
		if (this->fp == NULL) {
			fprintf(stdout, "Could not open %s for reading\n", filename);
			exit(1);
		}
		this->dirname = strdup(filename);
		char *last = strrchr(this->dirname, '/');
		if (last != NULL) {
			*last = '\0';
		} else {
			*this->dirname = '\0';
		}
	}

	/** Free everything we have allocated. */
	~File()
	{
		fclose(this->fp);
		free(this->dirname);
	}

	/**
	 * Get a single character from the file.
	 * If we are reading beyond the end of the file '\0' is returned.
	 * @return the read character.
	 */
	char GetChar() const
	{
		int c = fgetc(this->fp);
		return (c == EOF) ? '\0' : c;
	}

	/**
	 * Get the directory name of the file.
	 * @return the directory name.
	 */
	const char *GetDirname() const
	{
		return this->dirname;
	}

private:
	FILE *fp;             ///< The currently opened file.
	char *dirname;        ///< The directory of the file.
	const char *filename; ///< The name of the file.
};

/** A token returned by the tokenizer. */
enum Token {
	TOKEN_UNKNOWN,    ///< Unknown token
	TOKEN_END,        ///< End of document
	TOKEN_EOL,        ///< End of line
	TOKEN_SHARP,      ///< # character, usually telling something important comes.
	TOKEN_LOCAL,      ///< Read a local include
	TOKEN_GLOBAL,     ///< Read a global include
	TOKEN_IDENTIFIER, ///< Identifier within the data.
	TOKEN_DEFINE,     ///< (#)define in code
	TOKEN_IF,         ///< (#)if in code
	TOKEN_IFDEF,      ///< (#)ifdef in code
	TOKEN_IFNDEF,     ///< (#)ifndef in code
	TOKEN_ELIF,       ///< (#)elif in code
	TOKEN_ELSE,       ///< (#)else in code
	TOKEN_ENDIF,      ///< (#)endif in code
	TOKEN_UNDEF,      ///< (#)undef in code
	TOKEN_OR,         ///< '||' within #if expression
	TOKEN_AND,        ///< '&&' within #if expression
	TOKEN_DEFINED,    ///< 'defined' within #if expression
	TOKEN_OPEN,       ///< '(' within #if expression
	TOKEN_CLOSE,      ///< ')' within #if expression
	TOKEN_NOT,        ///< '!' within #if expression
	TOKEN_ZERO,       ///< '0' within #if expression
	TOKEN_INCLUDE,    ///< (#)include in code
};

/** Mapping from a C-style keyword representation to a Token. */
typedef std::map<const char*, Token, StringCompare> KeywordList;

/**
 * Lexer of a file.
 */
class Lexer {
public:
	/**
	 * Create the lexer and fill the keywords table.
	 * @param file the file to read from.
	 */
	Lexer(const File *file) : file(file), current_char('\0'), string(NULL), token(TOKEN_UNKNOWN)
	{
		this->keywords["define"]  = TOKEN_DEFINE;
		this->keywords["defined"] = TOKEN_DEFINED;
		this->keywords["if"]      = TOKEN_IF;
		this->keywords["ifdef"]   = TOKEN_IFDEF;
		this->keywords["ifndef"]  = TOKEN_IFNDEF;
		this->keywords["include"] = TOKEN_INCLUDE;
		this->keywords["elif"]    = TOKEN_ELIF;
		this->keywords["else"]    = TOKEN_ELSE;
		this->keywords["endif"]   = TOKEN_ENDIF;
		this->keywords["undef"]   = TOKEN_UNDEF;

		/* Initialise currently read character. */
		this->Next();

		/* Allocate the buffer. */
		this->buf_len = 32;
		this->buf = (char*)malloc(sizeof(*this->buf) * this->buf_len);
	}

	/** Free everything */
	~Lexer()
	{
		free(this->buf);
	}

	/**
	 * Read the next character into 'current_char'.
	 */
	void Next()
	{
		this->current_char = this->file->GetChar();
	}

	/**
	 * Get the current token.
	 * @return the token.
	 */
	Token GetToken() const
	{
		return this->token;
	}

	/**
	 * Read the currenty processed string.
	 * @return the string, can be NULL.
	 */
	const char *GetString() const
	{
		return this->string;
	}

	/**
	 * Perform the lexing/tokenizing of the file till we can return something
	 * that must be parsed.
	 */
	void Lex()
	{
		for (;;) {
			free(this->string);
			this->string = NULL;
			this->token  = TOKEN_UNKNOWN;

			switch (this->current_char) {
				/* '\0' means End-Of-File */
				case '\0': this->token = TOKEN_END; return;

				/* Skip some chars, as they don't do anything */
				case '\t': this->Next(); break;
				case '\r': this->Next(); break;
				case ' ':  this->Next(); break;

				case '\\':
					this->Next();
					if (this->current_char == '\n') this->Next();
					break;

				case '\n':
					this->token = TOKEN_EOL;
					this->Next();
					return;

				case '#':
					this->token = TOKEN_SHARP;
					this->Next();
					return;

				case '"':
					this->ReadString('"', TOKEN_LOCAL);
					this->Next();
					return;

				case '<':
					this->ReadString('>', TOKEN_GLOBAL);
					this->Next();
					return;

				case '&':
					this->Next();
					if (this->current_char == '&') {
						this->Next();
						this->token = TOKEN_AND;
						return;
					}
					break;

				case '|':
					this->Next();
					if (this->current_char == '|') {
						this->Next();
						this->token = TOKEN_OR;
						return;
					}
					break;

				case '(':
					this->Next();
					this->token = TOKEN_OPEN;
					return;

				case ')':
					this->Next();
					this->token = TOKEN_CLOSE;
					return;

				case '!':
					this->Next();
					if (this->current_char != '=') {
						this->token = TOKEN_NOT;
						return;
					}
					break;

				/* Possible begin of comment */
				case '/':
					this->Next();
					switch (this->current_char) {
						case '*': {
							this->Next();
							char previous_char = '\0';
							while ((this->current_char != '/' || previous_char != '*') && this->current_char != '\0') {
								previous_char = this->current_char;
								this->Next();
							}
							this->Next();
							break;
						}
						case '/': while (this->current_char != '\n' && this->current_char != '\0') this->Next(); break;
						default: break;
					}
					break;

				default:
					if (isalpha(this->current_char) || this->current_char == '_') {
						/* If the name starts with a letter, it is an identifier */
						this->ReadIdentifier();
						return;
					}
					if (isdigit(this->current_char)) {
						bool zero = this->current_char == '0';
						this->Next();
						if (this->current_char == 'x' || this->current_char == 'X') Next();
						while (isdigit(this->current_char) || this->current_char == '.' || (this->current_char >= 'a' && this->current_char <= 'f') || (this->current_char >= 'A' && this->current_char <= 'F')) {
							zero &= this->current_char == '0';
							this->Next();
						}
						if (zero) this->token = TOKEN_ZERO;
						return;
					}
					this->Next();
					break;
			}
		}
	}

private:
	/**
	 * The token based on keyword with a given name.
	 * @param name the actual keyword.
	 * @return the token of the keyword.
	 */
	Token FindKeyword(const char *name) const
	{
		KeywordList::const_iterator it = this->keywords.find(name);
		if (it == this->keywords.end()) return TOKEN_IDENTIFIER;
		return (*it).second;
	}

	/**
	 * Read an identifier.
	 */
	void ReadIdentifier()
	{
		size_t count = 0;

		/* Read the rest of the identifier */
		do {
			this->buf[count++] = this->current_char;
			this->Next();

			if (count >= buf_len) {
				/* Scale the buffer if required */
				this->buf_len *= 2;
				this->buf = (char *)realloc(this->buf, sizeof(*this->buf) * this->buf_len);
			}
		} while ((isalpha(this->current_char) || this->current_char == '_' || isdigit(this->current_char)));
		this->buf[count] = '\0';

		free(this->string);
		this->string = strdup(this->buf);
		this->token = FindKeyword(this->string);
	}

	/**
	 * Read a string up to a given character, then set the given token.
	 * @param end the 'marker' for the end of the string.
	 * @param token the token to set after returning.
	 */
	void ReadString(char end, Token token)
	{
		size_t count = 0;
		this->Next();
		while (this->current_char != end && this->current_char != ')' && this->current_char != '\n' && this->current_char != '\0') {
			this->buf[count++] = this->current_char;
			this->Next();

			if (count >= this->buf_len) {
				/* Scale the buffer if required */
				this->buf_len *= 2;
				this->buf = (char *)realloc(this->buf, sizeof(*this->buf) * this->buf_len);
			}
		}
		this->buf[count] = '\0';
		free(this->string);
		this->string = strdup(this->buf);
		this->token = token;
	}

	const File *file;     ///< The file to read from.
	char current_char;    ///< The current character to process.
	char *string;         ///< Currently processed string.
	Token token;          ///< The current token to process.
	char *buf;            ///< Temporary buffer.
	size_t buf_len;       ///< Length of the temporary buffer.
	KeywordList keywords; ///< All keywords we know of.
};

/**
 * Generate a path from a directory name and a relative filename.
 * If the file is not local the include directory names will be used instead
 * of the passed parameter with directory name. If the file is local both will
 * be queried where the parameter takes precedence.
 * @param dirname the directory to look in.
 * @param filename the file to look for.
 * @param local whether to look locally (in dirname) for the file.
 * @return the absolute path, or NULL if the file doesn't exist.
 */
const char *GeneratePath(const char *dirname, const char *filename, bool local)
{
	if (local) {
		if (access(filename, R_OK) == 0) return strdup(filename);

		char path[PATH_MAX];
		strcpy(path, dirname);
		const char *p = filename;
		/* Remove '..' from the begin of the filename. */
		while (*p == '.') {
			if (*(++p) == '.') {
				*(strrchr(path, '/')) = '\0';
				p += 2;
			}
		}
		strcat(path, "/");
		strcat(path, p);

		if (access(path, R_OK) == 0) return strdup(path);
	}

	for (StringSet::iterator it = _include_dirs.begin(); it != _include_dirs.end(); it++) {
		char path[PATH_MAX];
		strcpy(path, *it);
		const char *p = filename;
		/* Remove '..' from the begin of the filename. */
		while (*p == '.') {
			if (*(++p) == '.') {
				*(strrchr(path, '/')) = '\0';
				p += 2;
			}
		}
		strcat(path, "/");
		strcat(path, p);

		if (access(path, R_OK) == 0) return strdup(path);
	}

	return NULL;
}

/**
 * Try to parse a 'defined(expr)' expression.
 * @param lexer the lexer to get tokens from.
 * @param defines the set of known defines.
 * @param verbose whether to give verbose debugging information.
 * @return the value of the expression.
 */
bool ExpressionDefined(Lexer *lexer, StringSet *defines, bool verbose);

/**
 * Try to parse a 'expr || expr' expression.
 * @param lexer the lexer to get tokens from.
 * @param defines the set of known defines.
 * @param verbose whether to give verbose debugging information.
 * @return the value of the expression.
 */
bool ExpressionOr(Lexer *lexer, StringSet *defines, bool verbose);

/**
 * Try to parse a '!expr' expression. Also parses the '(expr)', '0' and
 * identifiers. Finally it also consumes any unknown tokens.
 * @param lexer the lexer to get tokens from.
 * @param defines the set of known defines.
 * @param verbose whether to give verbose debugging information.
 * @return the value of the expression.
 */
bool ExpressionNot(Lexer *lexer, StringSet *defines, bool verbose)
{
	if (lexer->GetToken() == TOKEN_NOT) {
		if (verbose) fprintf(stderr, "!");
		lexer->Lex();
		bool value = !ExpressionDefined(lexer, defines, verbose);
		if (verbose) fprintf(stderr, "[%d]", value);
		return value;
	}

	if (lexer->GetToken() == TOKEN_OPEN) {
		if (verbose) fprintf(stderr, "(");
		lexer->Lex();
		bool value = ExpressionOr(lexer, defines, verbose);
		if (verbose) fprintf(stderr, ")[%d]", value);
		lexer->Lex();
		return value;
	}

	if (lexer->GetToken() == TOKEN_ZERO) {
		if (verbose) fprintf(stderr, "0");
		lexer->Lex();
		if (verbose) fprintf(stderr, "[0]");
		return false;
	}

	bool first = true;
	while (lexer->GetToken() == TOKEN_UNKNOWN || lexer->GetToken() == TOKEN_IDENTIFIER) {
		if (verbose && first) fprintf(stderr, "<assumed true>");
		first = false;
		lexer->Lex();
	}

	return true;
}

/**
 * Try to parse a 'defined(expr)' expression.
 * @param lexer the lexer to get tokens from.
 * @param defines the set of known defines.
 * @param verbose whether to give verbose debugging information.
 * @return the value of the expression.
 */
bool ExpressionDefined(Lexer *lexer, StringSet *defines, bool verbose)
{
	bool value = ExpressionNot(lexer, defines, verbose);

	if (lexer->GetToken() != TOKEN_DEFINED) return value;
	lexer->Lex();
	if (verbose) fprintf(stderr, "defined");
	bool open = (lexer->GetToken() == TOKEN_OPEN);
	if (open) lexer->Lex();
	if (verbose) fprintf(stderr, open ? "(" : " ");
	if (lexer->GetToken() == TOKEN_IDENTIFIER) {
		if (verbose) fprintf(stderr, "%s", lexer->GetString());
		value = defines->find(lexer->GetString()) != defines->end();
	}
	if (open) {
		if (verbose) fprintf(stderr, ")");
		lexer->Lex();
	}
	lexer->Lex();
	if (verbose) fprintf(stderr, "[%d]", value);
	return value;
}

/**
 * Try to parse a 'expr && expr' expression.
 * @param lexer the lexer to get tokens from.
 * @param defines the set of known defines.
 * @param verbose whether to give verbose debugging information.
 * @return the value of the expression.
 */
bool ExpressionAnd(Lexer *lexer, StringSet *defines, bool verbose)
{
	bool value = ExpressionDefined(lexer, defines, verbose);

	while (true) {
		if (lexer->GetToken() != TOKEN_AND) return value;
		if (verbose) fprintf(stderr, " && ");
		lexer->Lex();
		value = value && ExpressionDefined(lexer, defines, verbose);
	}
}

/**
 * Try to parse a 'expr || expr' expression.
 * @param lexer the lexer to get tokens from.
 * @param defines the set of known defines.
 * @param verbose whether to give verbose debugging information.
 * @return the value of the expression.
 */
bool ExpressionOr(Lexer *lexer, StringSet *defines, bool verbose)
{
	bool value = ExpressionAnd(lexer, defines, verbose);

	while (true) {
		if (lexer->GetToken() != TOKEN_OR) return value;
		if (verbose) fprintf(stderr, " || ");
		lexer->Lex();
		value = value || ExpressionAnd(lexer, defines, verbose);
	}
}

/** Enumerator to tell how long to ignore 'stuff'. */
enum Ignore {
	NOT_IGNORE,         ///< No ignoring.
	IGNORE_UNTIL_ELSE,  ///< Ignore till a #else is reached.
	IGNORE_UNTIL_ENDIF, ///< Ignore till a #endif is reached.
};

/**
 * Scan a file for includes, defines and the lot.
 * @param filename the name of the file to scan.
 * @param ext the extension of the filename.
 * @param header whether the file is a header or not.
 * @param verbose whether to give verbose debugging information.
 */
void ScanFile(const char *filename, const char *ext, bool header, bool verbose)
{
	static StringSet defines;
	static std::stack<Ignore> ignore;
	/* Copy in the default defines (parameters of depend) */
	if (!header) {
		for (StringSet::iterator it = _defines.begin(); it != _defines.end(); it++) {
			defines.insert(strdup(*it));
		}
	}

	File file(filename);
	Lexer lexer(&file);

	/* Start the lexing! */
	lexer.Lex();

	while (lexer.GetToken() != TOKEN_END) {
		switch (lexer.GetToken()) {
			/* We reached the end of the file... yay, we're done! */
			case TOKEN_END: break;

			/* The line started with a # (minus whitespace) */
			case TOKEN_SHARP:
				lexer.Lex();
				switch (lexer.GetToken()) {
					case TOKEN_INCLUDE:
						if (verbose) fprintf(stderr, "%s #include ", filename);
						lexer.Lex();
						switch (lexer.GetToken()) {
							case TOKEN_LOCAL:
							case TOKEN_GLOBAL: {
								if (verbose) fprintf(stderr, "%s", lexer.GetString());
								if (!ignore.empty() && ignore.top() != NOT_IGNORE) {
									if (verbose) fprintf(stderr, " (ignored)");
									break;
								}
								const char *h = GeneratePath(file.GetDirname(), lexer.GetString(), lexer.GetToken() == TOKEN_LOCAL);
								if (h != NULL) {
									StringMap::iterator it = _headers.find(h);
									if (it == _headers.end()) {
										it = (_headers.insert(StringMapItem(strdup(h), new StringSet()))).first;
										if (verbose) fprintf(stderr, "\n");
										ScanFile(h, ext, true, verbose);
									}
									StringMap::iterator curfile;
									if (header) {
										curfile = _headers.find(filename);
									} else {
										/* Replace the extension with the provided extension of '.o'. */
										char path[PATH_MAX];
										strcpy(path, filename);
										*(strrchr(path, '.')) = '\0';
										strcat(path, ext != NULL ? ext : ".o");
										curfile = _files.find(path);
										if (curfile == _files.end()) {
											curfile = (_files.insert(StringMapItem(strdup(path), new StringSet()))).first;
										}
									}
									if (it != _headers.end()) {
										for (StringSet::iterator header = it->second->begin(); header != it->second->end(); header++) {
											if (curfile->second->find(*header) == curfile->second->end()) curfile->second->insert(strdup(*header));
										}
									}
									if (curfile->second->find(h) == curfile->second->end()) curfile->second->insert(strdup(h));
									free((void*)h);
								}
							}
							/* Fall through */
							default: break;
						}
						break;

					case TOKEN_DEFINE:
						if (verbose) fprintf(stderr, "%s #define ", filename);
						lexer.Lex();
						if (lexer.GetToken() == TOKEN_IDENTIFIER) {
							if (verbose) fprintf(stderr, "%s", lexer.GetString());
							if (!ignore.empty() && ignore.top() != NOT_IGNORE) {
								if (verbose) fprintf(stderr, " (ignored)");
								break;
							}
							if (defines.find(lexer.GetString()) == defines.end()) defines.insert(strdup(lexer.GetString()));
							lexer.Lex();
						}
						break;

					case TOKEN_UNDEF:
						if (verbose) fprintf(stderr, "%s #undef ", filename);
						lexer.Lex();
						if (lexer.GetToken() == TOKEN_IDENTIFIER) {
							if (verbose) fprintf(stderr, "%s", lexer.GetString());
							if (!ignore.empty() && ignore.top() != NOT_IGNORE) {
								if (verbose) fprintf(stderr, " (ignored)");
								break;
							}
							StringSet::iterator it = defines.find(lexer.GetString());
							if (it != defines.end()) {
								free((void*)*it);
								defines.erase(it);
							}
							lexer.Lex();
						}
						break;

					case TOKEN_ENDIF:
						if (verbose) fprintf(stderr, "%s #endif", filename);
						lexer.Lex();
						if (!ignore.empty()) ignore.pop();
						if (verbose) fprintf(stderr, " -> %signore", (!ignore.empty() && ignore.top() != NOT_IGNORE) ? "" : "not ");
						break;

					case TOKEN_ELSE: {
						if (verbose) fprintf(stderr, "%s #else", filename);
						lexer.Lex();
						Ignore last = ignore.empty() ? NOT_IGNORE : ignore.top();
						if (!ignore.empty()) ignore.pop();
						if (ignore.empty() || ignore.top() == NOT_IGNORE) {
							ignore.push(last == IGNORE_UNTIL_ELSE ? NOT_IGNORE : IGNORE_UNTIL_ENDIF);
						} else {
							ignore.push(IGNORE_UNTIL_ENDIF);
						}
						if (verbose) fprintf(stderr, " -> %signore", (!ignore.empty() && ignore.top() != NOT_IGNORE) ? "" : "not ");
						break;
					}

					case TOKEN_ELIF: {
						if (verbose) fprintf(stderr, "%s #elif ", filename);
						lexer.Lex();
						Ignore last = ignore.empty() ? NOT_IGNORE : ignore.top();
						if (!ignore.empty()) ignore.pop();
						if (ignore.empty() || ignore.top() == NOT_IGNORE) {
							bool value = ExpressionOr(&lexer, &defines, verbose);
							ignore.push(last == IGNORE_UNTIL_ELSE ? (value ? NOT_IGNORE : IGNORE_UNTIL_ELSE) : IGNORE_UNTIL_ENDIF);
						} else {
							ignore.push(IGNORE_UNTIL_ENDIF);
						}
						if (verbose) fprintf(stderr, " -> %signore", (!ignore.empty() && ignore.top() != NOT_IGNORE) ? "" : "not ");
						break;
					}

					case TOKEN_IF: {
						if (verbose) fprintf(stderr, "%s #if ", filename);
						lexer.Lex();
						if (ignore.empty() || ignore.top() == NOT_IGNORE) {
							bool value = ExpressionOr(&lexer, &defines, verbose);
							ignore.push(value ? NOT_IGNORE : IGNORE_UNTIL_ELSE);
						} else {
							ignore.push(IGNORE_UNTIL_ENDIF);
						}
						if (verbose) fprintf(stderr, " -> %signore", (!ignore.empty() && ignore.top() != NOT_IGNORE) ? "" : "not ");
						break;
					}

					case TOKEN_IFDEF:
						if (verbose) fprintf(stderr, "%s #ifdef ", filename);
						lexer.Lex();
						if (lexer.GetToken() == TOKEN_IDENTIFIER) {
							bool value = defines.find(lexer.GetString()) != defines.end();
							if (verbose) fprintf(stderr, "%s[%d]", lexer.GetString(), value);
							if (ignore.empty() || ignore.top() == NOT_IGNORE) {
								ignore.push(value ? NOT_IGNORE : IGNORE_UNTIL_ELSE);
							} else {
								ignore.push(IGNORE_UNTIL_ENDIF);
							}
						}
						if (verbose) fprintf(stderr, " -> %signore", (!ignore.empty() && ignore.top() != NOT_IGNORE) ? "" : "not ");
						break;

					case TOKEN_IFNDEF:
						if (verbose) fprintf(stderr, "%s #ifndef ", filename);
						lexer.Lex();
						if (lexer.GetToken() == TOKEN_IDENTIFIER) {
							bool value = defines.find(lexer.GetString()) != defines.end();
							if (verbose) fprintf(stderr, "%s[%d]", lexer.GetString(), value);
							if (ignore.empty() || ignore.top() == NOT_IGNORE) {
								ignore.push(!value ? NOT_IGNORE : IGNORE_UNTIL_ELSE);
							} else {
								ignore.push(IGNORE_UNTIL_ENDIF);
							}
						}
						if (verbose) fprintf(stderr, " -> %signore", (!ignore.empty() && ignore.top() != NOT_IGNORE) ? "" : "not ");
						break;

					default:
						if (verbose) fprintf(stderr, "%s #<unknown>", filename);
						lexer.Lex();
						break;
				}
				if (verbose) fprintf(stderr, "\n");
			/* Fall through */
			default:
				/* Ignore the rest of the garbage on this line */
				while (lexer.GetToken() != TOKEN_EOL && lexer.GetToken() != TOKEN_END) lexer.Lex();
				lexer.Lex();
				break;
		}
	}

	if (!header) {
		for (StringSet::iterator it = defines.begin(); it != defines.end(); it++) {
			free((void*)*it);
		}
		defines.clear();
		while (!ignore.empty()) ignore.pop();
	}
}

/**
 * Entry point. Arguably the most common function in all applications.
 * @param argc the number of arguments.
 * @param argv the actual arguments.
 * @return return value for the caller to tell we succeed or not.
 */
int main(int argc, char *argv[])
{
	bool ignorenext = true;
	char *filename = NULL;
	char *ext = NULL;
	bool append = false;
	bool verbose = false;

	for (int i = 0; i < argc; i++) {
		if (ignorenext) {
			ignorenext = false;
			continue;
		}
		if (argv[i][0] == '-') {
			/* Append */
			if (strncmp(argv[i], "-a", 2) == 0) append = true;
			/* Include dir */
			if (strncmp(argv[i], "-I", 2) == 0) {
				if (argv[i][2] == '\0') {
					i++;
					_include_dirs.insert(strdup(argv[i]));
				} else {
					_include_dirs.insert(strdup(&argv[i][2]));
				}
				continue;
			}
			/* Define */
			if (strncmp(argv[i], "-D", 2) == 0) {
				char *p = strchr(argv[i], '=');
				if (p != NULL) *p = '\0';
				_defines.insert(strdup(&argv[i][2]));
				continue;
			}
			/* Output file */
			if (strncmp(argv[i], "-f", 2) == 0) {
				if (filename != NULL) continue;
				filename = strdup(&argv[i][2]);
				continue;
			}
			/* Object file extension */
			if (strncmp(argv[i], "-o", 2) == 0) {
				if (ext != NULL) continue;
				ext = strdup(&argv[i][2]);
				continue;
			}
			/* Verbose */
			if (strncmp(argv[i], "-v", 2) == 0) verbose = true;
			continue;
		}
		ScanFile(argv[i], ext, false, verbose);
	}

	/* Default output file is Makefile */
	if (filename == NULL) filename = strdup("Makefile");

	char backup[PATH_MAX];
	strcpy(backup, filename);
	strcat(backup, ".bak");

	char *content = NULL;
	long size = 0;

	/* Read in the current file; so we can overwrite everything from the
	 * end of non-depend data marker down till the end. */
	FILE *src = fopen(filename, "rb");
	if (src != NULL) {
		fseek(src, 0, SEEK_END);
		size = ftell(src);
		rewind(src);
		content = (char*)malloc(size * sizeof(*content));
		fread(content, 1, size, src);
		fclose(src);
	}

	FILE *dst = fopen(backup, "wb");
	if (content != NULL) fwrite(content, 1, size, dst);
	fclose(dst);

	/* Then append it to the real file. */
	src = fopen(backup, "r");
	dst = fopen(filename, "w");
	while (fgets(content, size, src) != NULL) {
		fputs(content, dst);
		if (!append && !strncmp(content, "# DO NOT DELETE", 15)) break;
	}
	if (ftell(src) == 0) fprintf(dst, "\n# DO NOT DELETE\n");
	for (StringMap::iterator it = _files.begin(); it != _files.end(); it++) {
		for (StringSet::iterator h = it->second->begin(); h != it->second->end(); h++) {
			fprintf(dst, "%s: %s\n", it->first, *h);
		}
	}

	/* Clean up our mess. */
	fclose(dst);
	fclose(src);

	free(filename);
	free(ext);
	free(content);

	for (StringMap::iterator it = _files.begin(); it != _files.end(); it++) {
		for (StringSet::iterator h = it->second->begin(); h != it->second->end(); h++) {
			free((void*)*h);
		}
		it->second->clear();
		delete it->second;
		free((void*)it->first);
	}
	_files.clear();

	for (StringMap::iterator it = _headers.begin(); it != _headers.end(); it++) {
		for (StringSet::iterator h = it->second->begin(); h != it->second->end(); h++) {
			free((void*)*h);
		}
		it->second->clear();
		delete it->second;
		free((void*)it->first);
	}
	_headers.clear();

	for (StringSet::iterator it = _defines.begin(); it != _defines.end(); it++) {
		free((void*)*it);
	}
	_defines.clear();

	for (StringSet::iterator it = _include_dirs.begin(); it != _include_dirs.end(); it++) {
		free((void*)*it);
	}
	_include_dirs.clear();

	return 0;
}