metaprogram_parser.cpp 31.9 KB
Newer Older
William Bundy's avatar
William Bundy committed
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 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
typedef uint64 Hash;

Hash hash_string(char* c, int len)
{
	Hash hash = 0;
	for(isize i = 0; i < len; ++i) {
		hash = c[i] + hash * 65599;
	}
	return hash;
}

static inline int32 dec_str_to_int(char* str, isize len)
{
	int32 result = 0;
	for(isize i = 0; i < len; ++i) {
		result = result * 10 + str[i] - '0';
	}
	return result;
}


#define hash_literal(c) hash_string(c, sizeof(c) - 1)

enum Token_Kind
{
	Token_Unknown,

	Token_Semicolon,
	Token_Backslash,
	Token_OpenBrace,
	Token_CloseBrace,
	Token_OpenParen,
	Token_CloseParen,
	Token_OpenBracket,
	Token_CloseBracket,
	Token_Tilde,
	Token_ExclamationMark,
	Token_DollarSign,
	Token_Modulo,
	Token_Caret,
	Token_Ampersand,
	Token_Asterisk,
	Token_Pipe,
	Token_Dot,
	Token_Comma,
	Token_QuestionMark,
	Token_Colon,
	Token_Plus,
	Token_Minus,
	Token_Divide, 
	Token_Equals,
	Token_GreaterThan,
	Token_LessThan,
	
	Token_CompilerDirective,
	Token_Char,
	Token_String,
	Token_Number,
	Token_Identifier,

	Token_Integer,
	Token_Float,

	Operator_LogicalAnd,
	Operator_LogicalOr,
	Operator_BooleanEquals,
	Operator_BooleanNotEquals,
	Operator_BooleanGreaterEquals,
	Operator_BooleanLessEquals,
	Operator_PtrMemberAccess,
	Operator_Decrement,
	Operator_Increment,

	Token_EndOfFile,
	Token_Kind_Count,
	
};

struct Lexer_Location
{
	isize file;
	isize line;
	isize offset;
};

struct Token
{
	Token_Kind kind;	
	char* start;
	isize len;
	Hash hash;

	Lexer_Location location;

	Token *prev, *next;
};

void print_token(Token* t, Token* start)
{
	isize sp = (isize) start;
	printf("%d<-[%d %d %.*s]->%d", ((isize)t->prev - sp) / sizeof(Token), ((isize)t - sp) / sizeof(Token), t->kind, t->len, t->start, ((isize)t->next - sp) / sizeof(Token));
}



struct Lexer_File
{
	char* filename;
	isize pathlen;
	isize index;
	Lexer_Location location;
	char* start;
	char* head;

};

void init_lexer_file(Lexer_File* file, char* filename, char* prev_path, isize prev_path_len, Memory_Arena* arena)
{
	isize len = strlen(filename);
	char* filename_copy = arena_push_array(arena, char, len + prev_path_len+1);
	memcpy(filename_copy, prev_path, prev_path_len);
	memcpy(filename_copy + prev_path_len, filename, len);
	filename_copy[len + prev_path_len] = '\0';
	//printf(">>>>%s \n", filename_copy);
	len = strlen(filename_copy);
	isize pathlen = 0;
	isize extlen = 0;
	for(isize i = len - 1; i >= 0; --i) {
		if(filename_copy[i] == '.') {
			extlen = i;
		}
		if(filename_copy[i] == '/' || filename_copy[i] == '\\') {
			pathlen = i + 1;
			break;
		}
	}
	Hash exthash = hash_string(filename_copy + extlen, len - extlen);
	if(exthash != hash_literal(".c") && exthash != hash_literal(".cpp") && exthash != hash_literal(".h")) {
		//printf("Hit invalid file suffix: %d %d %d %.*s", len, extlen, len - extlen, len - extlen, filename_copy + extlen);
		file->pathlen = pathlen;
		file->filename = filename_copy;
		file->start = NULL;
		file->head = NULL;
		return;
	}
	file->pathlen = pathlen;
	file->filename = filename_copy;
	file->start = load_file(filename_copy, NULL, arena);
	file->head = file->start;
}


struct Lexer
{
	Lexer_File* main_file;

	Lexer_File* files;
	isize files_count, files_capacity;

	isize structs_count;
	isize procedures_count;
};

void init_lexer(Lexer* lex, isize file_capacity, Memory_Arena* arena)
{
	lex->files = arena_push_array(arena, Lexer_File, file_capacity);
	lex->files_count = 0;
	lex->files_capacity = file_capacity;
	lex->main_file = lex->files;
	lex->main_file->index = 0;

	lex->structs_count = 0;
	lex->procedures_count = 0;
}

Lexer_File* get_next_file(Lexer* lex)
{
	Lexer_File* file =  lex->files + lex->files_count++;
	file->index = lex->files_count - 1;
	return file;
}



bool is_space(char c)
{
	return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f';
}

bool is_number(char c)
{
	return c >= '0' &&  c <= '9'; 
}

bool is_valid_identifier(char c)
{
	return is_number(c) || ((c >= 'A') && (c <= 'Z')) || ((c >= 'a') && (c <= 'z')) || c == '_';
}


#define nextchar do { \
		if(f->head[0] == '\n') { \
			f->location.line++; \
			f->location.offset = 0; \
		} else { \
			f->location.offset++; \
		} \
		f->head++; \
} while(0) 

#define valid ((f->head[0] != '\0') && (f->head[0] != EOF))

bool lexer_get_token(Lexer* lexer, Lexer_File* f, Token* t) 
{ 
	while(valid) {
		if(is_space(f->head[0])) {
			nextchar;
		} else if(f->head[0] == '/') {
			if(f->head[1] == '*') {
				nextchar;
				nextchar;
				while(valid && !(f->head[0] == '*' &&
							f->head[1] == '/')) {
					nextchar;
				}
				nextchar;
				nextchar;
			} else if(f->head[1] == '/') {
				nextchar;
				nextchar;
				while(valid && (f->head[0] != '\n')) {
					nextchar;	
				}
				nextchar;
			} else {
				break;
			}
		} else {
			break;
		}
	}
	
	t->start = f->head;
	t->len = 1;
	t->kind = Token_Unknown;
	f->location.file = f->index;
	t->location = f->location;
	t->next = NULL;

	//printf("%d<%c> ", f->head[0], f->head[0]);
	bool hit = true;
	switch(f->head[0]) {
		case ';':
			t->kind = Token_Semicolon;
			break;
		case '\\':
			t->kind = Token_Backslash;
			break;
		case '{':
			t->kind = Token_OpenBrace;
			break;
		case '}':
			t->kind = Token_CloseBrace;
			break;
		case '(':
			t->kind = Token_OpenParen;
			break;
		case ')':
			t->kind = Token_CloseParen;
			break;
		case '[':
			t->kind = Token_OpenBracket;
			break;
		case ']':
			t->kind = Token_CloseBracket;
			break;
		case '~':
			t->kind = Token_Tilde;
			break;
		case '!':
			t->kind = Token_ExclamationMark;
			break;
		case '#':
			t->kind = Token_CompilerDirective;
			t->location.offset++;
			t->start++;
			nextchar;
			while(valid && (f->head[0] != '\n')) {
				nextchar;
			}
			t->len = f->head - t->start;
			break;
		case '$':
			t->kind = Token_DollarSign;
			break;
		case '%':
			t->kind = Token_Modulo;
			break;
		case '^':
			t->kind = Token_Caret;
			break;
		case '&':
			t->kind = Token_Ampersand;
			break;
		case '*':
			t->kind = Token_Asterisk;
			break;
		case '|':
			t->kind = Token_Pipe;
			break;
		case '.':
			t->kind = Token_Dot;
			break;
		case ',':
			t->kind = Token_Comma;
			break;
		case '?':
			t->kind = Token_QuestionMark;
			break;
		case ':':
			t->kind = Token_Colon;
			break;
		case '+':
			t->kind = Token_Plus;
			break;
		case '-':
			t->kind = Token_Minus;
			break;
		case '/':
			t->kind = Token_Divide;
			break;
		case '=':
			t->kind = Token_Equals;
			break;
		case '>':
			t->kind = Token_GreaterThan;
			break;
		case '<':
			t->kind = Token_LessThan;
			break;
		default:
			hit = false;
			break;
	}
	if(hit) {
		nextchar;
	} else switch(f->head[0]) {		
		case '\'':
			t->kind = Token_Char;
			t->location.offset++;
			t->start++;
			nextchar;
			while(valid) {
				nextchar;
				if(f->head[0] == '\'') {
					if(f->head[-1] != '\\') {
						break;
					} else {
						if(f->head[-2] == '\\') {
							break;
						}
					}
				}
			}
			t->len = f->head - t->start;
			nextchar;
			break;
		case '"':
			t->kind = Token_String;
			t->location.offset++;
			t->start++;
			nextchar;
			while(valid) {
				if(f->head[0] == '"') {
					char* last = f->head - 1;
					if(last[0] != '\\') {
						break;
					}
				}
				nextchar;

				if(f->head[0] == '\n') {
					printf(">>> Error, encountered newline in string literal\n");
					printf(">>> line %d, char %d\n", f->location.line, f->location.offset);
					break;
				}
			}
			t->len = f->head - t->start;
			nextchar;
			break;
		case '0':
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
		case '6':
		case '7':
		case '8':
		case '9':
			t->kind = Token_Number;
			while(valid && is_number(f->head[0])) {
				nextchar;
			}
			t->len = f->head - t->start;
			break;
		case '\0':
		case EOF:
			t->kind = Token_EndOfFile;
			return false;
		default:
			if(is_valid_identifier(f->head[0])) {
				t->kind = Token_Identifier;
				while(is_valid_identifier(f->head[0])) {
					nextchar;
				}
				t->len = f->head - t->start;
			} else {
				t->kind = Token_Unknown;
			}
			break;
	}
	t->hash = hash_string(t->start, t->len);

	return true;
}
#undef nextchar
#undef valid

void parse_number_tokens(Token* head)
{
	Token* next = head->next;
	if(head->kind == Token_Number) {
		if(next && next->kind == Token_Dot) {
			head->kind = Token_Float;
			head->len++;
			head->next = next->next;
			parse_number_tokens(head);
		} else {
			head->kind = Token_Integer;
		}
	} else if(head->kind == Token_Float) {
		if(next && next->kind == Token_Number) {
			head->len += next->len;
			head->next = next->next;
		}
	}
}

void parse_include_directive(Lexer* lex, Token* directive)
{
	start_temp_arena(Temp_Arena);
	char* buf = arena_push_array(Temp_Arena, char, directive->len + 1);
	memcpy(buf, directive->start, directive->len);
	buf[directive->len] = '\0';
	Token* head = arena_push_struct(Temp_Arena, Token);
	Token* start = head;

	{
		Token t;
		Lexer_File f;
		f.head = buf;
		f.start = buf;
		while(lexer_get_token(NULL, &f, &t)) {
			*head = t;
			head->next = arena_push_struct(Temp_Arena, Token);
			head = head->next;
		}
		head->next = NULL;
	}
	if(start->hash != hash_string("include", sizeof("include") - 1)) {
		end_temp_arena(Temp_Arena);
		return;
	}

	head = start;
	do {
		if(head->kind == Token_String) {
			char* filename = arena_push_array(Temp_Arena, char, head->len + 1);
			memcpy(filename, head->start, head->len);
			filename[head->len] = '\0';
			Lexer_File* file = get_next_file(lex);
			Lexer_File* including = lex->files + directive->location.file;
			init_lexer_file(file, filename, including->filename, including->pathlen, Work_Arena);
			if(file->start != NULL) {
				Token* new_file_head = arena_push_struct(Work_Arena, Token);
				Token* new_file_start = new_file_head;
				Token* last = directive;
				Token t;
				while(lexer_get_token(lex, file, &t)) {
					*new_file_head = t;
					new_file_head->next = arena_push_struct(Work_Arena, Token);
					new_file_head->prev = last;
					last = new_file_head;
					new_file_head = new_file_head->next;
				}
				Token* oldnext = directive->next;
				directive->next = new_file_start;
				new_file_start->prev = directive;
				new_file_head->next = oldnext;
				oldnext->prev = new_file_head;
			} 
			break;
		}
	} while(head = head->next);

	end_temp_arena(Temp_Arena);
}


Token* parse_dollarsign_instructions(Token* t) 
{
	if(t->kind != Token_DollarSign) return t;
	Token* next = t->next->next;
	Token* head = t;
	if(next->hash == hash_literal("exclude")) {
		do {
			if(next->kind == Token_DollarSign) {
				Token* tk = next->next->next;
				if(tk->kind == Token_Identifier) {
					if(tk->hash == hash_literal("end")) {
						head = tk->next->next;
						break;
					}
				}
			}
		} while(next = next->next);
	} 
	return head;
}

void parse_tokens(Lexer* lex, Token* start)
{
	Token* head = start;

	do {
		head = parse_dollarsign_instructions(head);
		if(head->kind == Token_CompilerDirective && head->start[0] == 'i') {
			parse_include_directive(lex, head);
		}
	} while(head = head->next);

	head = start;

	do {
		Token* next;
		switch(head->kind) {
			case Token_DollarSign:
				head = parse_dollarsign_instructions(head);
				break;
			case Token_Ampersand:
				next = head->next;
				if(next && next->kind == Token_Ampersand) {
					head->kind = Operator_LogicalAnd;
					head->len++;
					head->next = next->next;
				}
				break;
			case Token_Pipe:
				next = head->next;
				if(next && next->kind == Token_Pipe) {
					head->kind = Operator_LogicalOr;
					head->len++;
					head->next = next->next;
				}
				break;
			case Token_Equals:
				next = head->next;
				if(next && next->kind == Token_Equals) {
					head->kind = Operator_BooleanEquals;
					head->len++;
					head->next = next->next;
				}
				break;
			case Token_ExclamationMark:
				next = head->next;
				if(next && next->kind == Token_Equals) {
					head->kind = Operator_BooleanNotEquals;
					head->len++;
					head->next = next->next;
				}
				break;
			case Token_GreaterThan:
				next = head->next;
				if(next && next->kind == Token_Equals) {
					head->kind = Operator_BooleanGreaterEquals;
					head->len++;
					head->next = next->next;
				}
				break;
			case Token_LessThan:
				next = head->next;
				if(next && next->kind == Token_Equals) {
					head->kind = Operator_BooleanLessEquals;
					head->len++;
					head->next = next->next;
				}
				break;
			case Token_Number:
				parse_number_tokens(head);
				break;
			case Token_Minus:
				next = head->next;
				if(next && next->kind == Token_GreaterThan) {
					head->kind = Operator_PtrMemberAccess;
					head->len++;
					head->next = next->next;
				} else if(next && next->kind == Token_Minus) {
					head->kind = Operator_Decrement;
					head->len++;
					head->next = next->next;
				} else if(next && next->kind == Token_Number) {
					Token_Kind prevkind = Token_Unknown;
					if(head->prev != NULL) {
						prevkind = head->prev->kind;
					}
					if(prevkind != Token_Number &&
							prevkind != Token_Integer && 
							prevkind != Token_Float && 
							prevkind != Token_Identifier ) {
						head->kind = Token_Number;
						head->len += next->len;
						head->next = next->next;
						next = head->next;
						parse_number_tokens(head);
					}
				}
				break;
			case Token_Plus:
				next = head->next;
				if(next && next->kind == Token_Plus) {
					head->kind = Operator_Increment;
					head->len++;
					head->next = next->next;
				}
			default:
				break;
		}
	} while(head = head->next);

}

void parse_sing(Token* t, int32 brace_level) 
{
	if(t->hash == hash_literal("sing")) { 
		fprintf(stderr, "[%d]", brace_level);
	}
}


struct Proc_Arg
{
	char** terms;
	isize count;

	char* defaults;
};

void init_proc_arg(Proc_Arg* arg, isize count, Memory_Arena* arena)
{
	arg->terms = arena_push_array(arena, char*, count);
	arg->defaults = NULL;
	arg->count = 0;
}

struct Proc_Prototype
{
	Token *start, *end;
	char** decorators;
	isize decorators_count;
	char* name;
	Proc_Arg* args;
	isize args_count;

	Proc_Prototype* next;
};

void print_proc_prototype(Proc_Prototype* p)
{
	if(p->name == NULL) return;

	for(isize i = 0; i < p->decorators_count; ++i) {
		printf("%s ", p->decorators[i]);
	}
	printf("%s(", p->name);

	for(isize i = 0; i < p->args_count; ++i) {
		Proc_Arg* a = p->args + i;
		for(isize j = 0; j < a->count; ++j) {
			printf("%s", a->terms[j]);
			if(j == a->count - 1) {
				if(a->defaults == NULL) {
					if(i != p->args_count - 1) printf(", ");
				} else {
					printf(" %s", a->defaults);
					if(i != p->args_count - 1) printf(" ");
				}
			} else {
				printf(" ");
			}
		}
	} 

	if(p->args_count != 0) {
		if(p->args[p->args_count - 1].defaults == NULL) 
			printf(");");
		else 
			printf(";");
	}

	printf("\n");


}

Proc_Prototype* find_proc_prototypes(Lexer* lex, Token* start, Memory_Arena* arena)
{
	//NOTE(will) will not find C-style "struct Type function() {"
	Token* head = start;
	Token* next = NULL;
	Hash structhash = hash_literal("struct");
	Hash enumhash = hash_literal("enum");

	Proc_Prototype proc = {0};
	Proc_Prototype* proc_start = arena_push_struct(arena, Proc_Prototype);
	Proc_Prototype* proc_head = proc_start;

	do {
		head = parse_dollarsign_instructions(head);
		if (head->kind == Token_Identifier) {
			if(head->hash != structhash && head->hash != enumhash) {
				//pattern: 
				//	mode 0 <identifiers...>
				//	mode 0 <open paren> 
				//	mode 1 <identifier, * identifier, comma...>
				//	mode 1 <close paren> 
				//	mode 2 <open brace>
				proc = {0};
				proc.decorators = arena_push_array(arena, char*, 256);
				proc.args = arena_push_array(arena, Proc_Arg, 256);
				proc.start = head;

				Token* sub_head = head;
				int32 mode = 0;
				Token* default_args_token = NULL;
				int32 paren_depth = 0;
				Proc_Arg* arg = proc.args;
				init_proc_arg(arg, 256, arena);
				bool quit = false;
				do {
					if(sub_head->kind == Token_Semicolon) {
						proc = {0};
						mode = -1;
						break;
					}
					sub_head = parse_dollarsign_instructions(sub_head);
					switch(mode) {
						case 0:
							if (sub_head->kind == Token_Identifier) {
								char* buf = arena_push_array(arena, char, 256);
								memcpy(buf, sub_head->start, sub_head->len);
								int len = sub_head->len;
								next = sub_head->next;
								while(next->kind == Token_Asterisk) {
									buf[len++] = '*';
									next = next->next;
								}
								buf[len] = '\0';
								proc.decorators[proc.decorators_count++] = buf;
							} else if(sub_head->kind == Token_OpenParen) {
								arg = proc.args + proc.args_count++;
								init_proc_arg(arg, 256, arena);
								proc.name = proc.decorators[--proc.decorators_count];
								mode = 1;
							} else if(sub_head->kind == Token_Asterisk) {
								continue;
							}
							break;
						case 1:
							if(sub_head->kind == Token_CloseParen) {
								if(paren_depth == 0) {
									if(default_args_token != NULL) {
										char* start = default_args_token->start;
										isize len = sub_head->start - start + sub_head->len;
										char* buf = arena_push_array(arena, char, len+1);
										memcpy(buf, start, len);
										buf[len] = '\0';
										arg->defaults = buf;
										default_args_token = NULL;
									}
									mode = 2;
								} else {
									paren_depth--;
								}
							} else if(sub_head->kind == Token_Identifier) {
								if(default_args_token == NULL) {
									char* buf = arena_push_array(arena, char, 256);
									memcpy(buf, sub_head->start, sub_head->len);
									int len = sub_head->len;
									next = sub_head->next;
									while(next->kind == Token_Asterisk) {
										buf[len++] = '*';
										next = next->next;
									}
									buf[len] = '\0';
									arg->terms[arg->count++] = buf;
								}

							} else if (sub_head->kind == Token_Equals) {
								default_args_token = sub_head;
							} else if (sub_head->kind == Token_Comma) {
								if(paren_depth == 0) {
									if(default_args_token != NULL) {
										//TODO(will) code duplication
										char* start = default_args_token->start;
										isize len = sub_head->start - start + sub_head->len;
										char* buf = arena_push_array(arena, char, len+1);
										memcpy(buf, start, len);
										buf[len] = '\0';
										arg->defaults = buf;
										default_args_token = NULL;
									}
									arg = proc.args + proc.args_count++;
									init_proc_arg(arg, 256, arena);
								}
							} else if(sub_head->kind == Token_OpenParen) {
								paren_depth++;
							}
							break;
						case 2: 
							if(sub_head->kind == Token_OpenBrace) {
								int32 brace_depth = 0;
								sub_head = sub_head->next;
								do {
									if(sub_head->kind == Token_OpenBrace) {
										brace_depth++;
									} else if(sub_head->kind == Token_CloseBrace) {
										if(brace_depth == 0) {
									//		print_token(sub_head, start);
									//		printf("\n");
											quit = true;
											break;	
										}
										brace_depth--;
									}
								} while (sub_head = sub_head->next);
							}
							break;
					}
					if(quit) {
						head = sub_head;
						proc.end = head;
						*proc_head = proc;
						proc_head->next = arena_push_struct(arena, Proc_Prototype);
						lex->procedures_count++;
						proc_head = proc_head->next;
						break;
					}
					if (sub_head == NULL) break;
				} while(sub_head = sub_head->next);
			}
		}
		if (head == NULL) break;
	} while(head = head->next);
	return proc_start;
}


enum Struct_Kind
{
	StructKind_None,
	StructKind_Struct,
	StructKind_Union,
	StructKind_Member
};

typedef union Struct_Member Struct_Member;
#define StructMemberCapacity (256)
struct Struct_Def
{
	char* name;
	Struct_Kind kind;

	isize meta_index;

	Struct_Member* members;
	Struct_Kind* member_kinds;
	isize member_count;

	Struct_Def* next;
}; 

union Struct_Member
{
	struct {
		Struct_Def def;
		char** array_sizes;
		isize array_levels;
	} anon_struct;
	struct {
		Hash namehash;
		char* name;
		char** terms;
		isize count;

		int32 asterisk_count;

		char** array_sizes;
		isize array_levels;
	} member_var;
};

void print_indent(int32 indent)
{
	for(isize i = 0; i < indent; ++i) {
		printf("\t");
	}
}

void print_struct_names(Struct_Def* def, isize index, char* prefix, isize prefix_len, Struct_Def** all_structs, isize* counter, Memory_Arena* arena)
{
	isize chars = 0;
	
	isize local_counter = *counter;
	Struct_Def** local_struct = all_structs + local_counter;

	local_struct[0] = def;
	def->meta_index = local_counter;
	*counter = local_counter + 1;
	if(index == -1) {
		chars = printf("\t%.*s_%s,\n", prefix_len, prefix, def->name);
	} else {
		if(def->name[0] == '\0') {
			//truly anonymous
			chars = printf("\t%.*s_%s%d,\n", 
					prefix_len, prefix,
					def->kind == StructKind_Struct ?
					"struct" : "union",
					index);
		} else {
			//has a variable name
			chars = printf("\t%.*s_%s,\n",
					prefix_len, prefix,
					def->name);
		}
	}
	chars -= 2;

	char* new_prefix = arena_push_array(arena, char, chars + 256);
	prefix_len = chars;
	if(index == -1) {
		snprintf(new_prefix, chars, "%.*s_%s", prefix_len, prefix, def->name);
	} else {
		if(def->name[0] == '\0') {
			//truly anonymous
			snprintf(new_prefix, chars, "%.*s_%s%d", 
					prefix_len, prefix,
					def->kind == StructKind_Struct ?
					"struct" : "union",
					index);
		} else {
			//has a variable name
			snprintf(new_prefix, chars, "%.*s_%s",
					prefix_len, prefix,
					def->name);
		}
	}

	isize subcount = 0;
	for(isize i = 0; i < def->member_count; ++i) {
		if(def->member_kinds[i] != StructKind_Member) {
			auto var = &def->members[i].anon_struct;
			print_struct_names(&var->def, subcount++, new_prefix, chars, all_structs, counter, arena);
		}
	}
}

void print_struct(Struct_Def* def, bool as_member_struct = false, int32 indent = 0)
{
	if(def->name == NULL) return;
	print_indent(indent);
	if(as_member_struct) {
		if(def->kind == StructKind_Struct) {
			printf("struct {\n");
		} else if(def->kind == StructKind_Union) {
			printf("union {\n");
		}
	} else {
		if(def->kind == StructKind_Struct) {
			printf("struct %s\n", def->name);
		} else if(def->kind == StructKind_Union) {
			printf("union %s\n", def->name);
		}
		print_indent(indent);
		printf("{\n");
	}
	indent++;
	for(isize i = 0; i < def->member_count; ++i) {
		if(def->member_kinds[i] == StructKind_Member) {
			auto var = &def->members[i].member_var;
			print_indent(indent);
			for(isize a = 0; a < var->count; ++a) {
				printf("%s ", var->terms[a]);
			}
			for(isize a = 0; a < var->asterisk_count; ++a) {
				printf("*");
			}
			printf("%s", def->members[i].member_var.name);
			for(isize a = 0; a < var->array_levels; ++a) {
				printf("[%s]", var->array_sizes[a]);
			}
			printf(";\n");
		} else {
			auto var = &def->members[i].anon_struct;
			print_struct(&var->def, true, indent);
			printf("%s", var->def.name);
			
			for(isize a = 0; a < var->array_levels; ++a) {
				printf("[%s]", var->array_sizes[a]);
			}

			printf(";\n");
		}	

	}
	indent--;
	print_indent(indent);
	if(as_member_struct) {
		if(def->name[0] == '\0')
			printf("}");
		else 
			printf("} ");
	} else {
		printf("};\n");
	}
	
}


// unsigned short**** thinga[400], **thingb, **thingc, a, b, c, d[3], e[44][55], f[44][22][44];

Token* parse_struct_member(Lexer* lex, Struct_Def* parent, Token* start, Memory_Arena* arena)
{
	Hash structhash = hash_literal("struct");
	Hash unionhash = hash_literal("union");
	Token* head = start;
	Token* next = head->next;
	
	Struct_Member* member = parent->members + parent->member_count;
	Struct_Kind* kind = parent->member_kinds + parent->member_count;

	if(head->kind == Token_Identifier) {
		if(head->hash == structhash || head->hash == unionhash) {
			lex->structs_count++;
			if(head->hash == unionhash) {
				*kind = StructKind_Union;
			} else {
				*kind = StructKind_Struct;
			}

			do {
 				head = head->next;
			} while(head->kind != Token_OpenBrace);
			head = head->next;
			Struct_Def def = {0};
			def.members = arena_push_array(arena, Struct_Member, StructMemberCapacity);
			def.member_kinds = arena_push_array(arena, Struct_Kind, StructMemberCapacity);
			def.kind = *kind;
			do {
				head = parse_struct_member(lex, &def, head, arena);
				head = head->next;
			} while(head->kind != Token_CloseBrace);

 			head = head->next;
			auto var = &member->anon_struct;
			if(head->kind != Token_Identifier) {
				if(head->kind == Token_Semicolon) {
					def.name = "";
					var->def = def;
					var->array_levels = 0;
					var->array_sizes = NULL;
					parent->member_count++;

					return head;
				} else {
					fprintf(stderr, "ERROR: wanted identifier, got %d:[%.*s] \n", 
							head->kind, head->len, head->start);
				}
			} else {
				char* buf = arena_push_array(arena, char, 256);
				memcpy(buf, head->start, head->len);
				int len = head->len;
				next = head->next;
				buf[len] = '\0';
				def.name = buf;
			}
			head = head->next;

			bool quit = false;
			do { 
				switch(head->kind) {
					case Token_Semicolon:
						quit = true;
						break;
					case Token_Comma:
						//TODO(will) Support commas like with regular variables.
						break;
					case Token_OpenBracket: {						
						head = head->next;
						if(var->array_levels == 0) {
							var->array_sizes = arena_push_array(arena, char*, 256);
						}
						char* buf = arena_push_array(arena, char, head->len + 1);
						memcpy(buf, head->start, head->len);
						int len = head->len;
						next = head->next;
						buf[len] = '\0';
						var->array_sizes[var->array_levels++] = buf;
					} break;
					default:
						break;
				}
				if(quit) break;
			} while(head = head->next);
			var->def = def;
		} else {
			*kind = StructKind_Member;
			auto var = &member->member_var;
			var->terms = arena_push_array(arena, char*, 256);
			var->count = 0;
			var->asterisk_count = 0;
			var->name = NULL;
			var->array_sizes = NULL;
			var->array_levels = 0;
			int32 mode = 0;
			bool quit = false;
			do {
				if(head->kind == Token_Comma) {
					if(mode == 0) {
						var->namehash = head->prev->hash;
						var->name = var->terms[--var->count];
					}
					parent->member_count++;
					Struct_Kind oldkind = *kind;
					member = parent->members + parent->member_count;
					kind = parent->member_kinds + parent->member_count;
					*kind = oldkind;
					member->member_var = *var;
					var = &member->member_var;
					var->asterisk_count = 0;
					var->array_levels = 0;
					var->array_sizes = NULL;
					var->name = NULL;
					mode = 1;
				} else if(head->kind == Token_Semicolon) {
					if(mode == 0) {
						var->name = var->terms[--var->count];
					}
					break;
				} else if(head->kind == Token_Identifier) {
					char* buf = arena_push_array(arena, char, head->len + 1);
					memcpy(buf, head->start, head->len);
					int len = head->len;
					next = head->next;
					buf[len] = '\0';
					if(mode == 0) {
						var->terms[var->count++] = buf;
					} else if(mode == 1) {
						var->namehash = head->hash;
						var->name = buf;
					}
				} else if(head->kind == Token_Asterisk) {
					var->asterisk_count++;
				} else if(head->kind == Token_OpenBracket) {
					head = head->next;
					if(var->array_levels == 0) {
						var->array_sizes = arena_push_array(arena, char*, 256);
					}
					char* buf = arena_push_array(arena, char, head->len + 1);
					memcpy(buf, head->start, head->len);
					int len = head->len;
					next = head->next;
					buf[len] = '\0';
					var->array_sizes[var->array_levels++] = buf;
				}
			} while(head = head->next);
		}
	}

	parent->member_count++;
	return head;
}


Struct_Def* find_struct_defs(Lexer* lex, Token* start, Memory_Arena* arena)
{
	Token* head = start;
	Token* next = NULL;

	Hash structhash = hash_literal("struct");
	Hash unionhash = hash_literal("union");
	Hash typedefhash = hash_literal("typedef");
	Struct_Def def = {0};

	Struct_Def* def_start = arena_push_struct(arena, Struct_Def);
	Struct_Def* def_head = def_start;

	int32 brace_depth = 0;
	do {
		if(head->kind == Token_DollarSign) {
			next = head->next->next;
			parse_sing(next, brace_depth);
		}
		head = parse_dollarsign_instructions(head);

		if(head->kind == Token_OpenBrace) {
			brace_depth++;
		} else if(head->kind == Token_CloseBrace) {
			brace_depth--;
		}

		if(brace_depth < 0) {
			fprintf(stderr, "\n %s line %d col %d \n", lex->files[head->location.file].filename, head->location.line, head->location.offset);
			brace_depth = 0;
		}

		if(head->hash == typedefhash) {
			do {
				head = head->next;
			} while(head->kind != Token_Semicolon);
		}

		if(brace_depth > 0 || head->kind != Token_Identifier) continue;

		Struct_Kind kind = StructKind_None;
		if(head->hash == structhash) {
			kind = StructKind_Struct;
		} else if(head->hash == unionhash) {
			kind = StructKind_Union;
		}

		if(kind != StructKind_None) {
			def = {0};
			def.kind = kind;
			def.members = arena_push_array(arena, Struct_Member, StructMemberCapacity);
			def.member_kinds = arena_push_array(arena, Struct_Kind, StructMemberCapacity);
			Token* subhead = head->next;
			do {
				if(subhead->kind == Token_Identifier) {
					//this is the name
					char* buf = arena_push_array(arena, char, subhead->len + 1);
					memcpy(buf, subhead->start, subhead->len);
					buf[subhead->len] = '\0';
					def.name = buf;
				} else if(subhead->kind == Token_OpenBrace) {
					break;
				}
			} while (subhead = subhead->next);
			subhead = subhead->next;

			do {
				subhead = parse_struct_member(lex, &def, subhead, arena);
				subhead = subhead->next;
			} while(subhead->kind != Token_CloseBrace);

			lex->structs_count++;

			*def_head = def;
			def_head->next = arena_push_struct(arena, Struct_Def); 
			def_head = def_head->next;
		}
	} while(head = head->next);

	return def_start;
}



/* Serialization "what is this thing" rules
 * 	- If something is a pointer
 * 		- if this is the only pointer in the 'class'
 * 			- assume any member named count, len, length, capacity, size 
 * 			 could be the number.
 * 		- when initializing, if something has the name
 * 			"pointer(s)_{capacity, size}
 * 			- Assume this is the size to allocate
 * 		- if something has the name
 * 			"pointer(s)_{count, length}" 
 * 			- Assume this is the number of things to (de)serialize
 * 		- if $(tag, pointername:length) is present, use that, ignore
 * 			heuristic rules
 * 	- If something is a union
 * 		- if something matches the name
 * 			"unionname_{kind,type}"
 * 			use this to index sub-structs in the union
 * 		- If a union has a base-level array that is the same size 
 * 			as the union, and no kind/type variable is present, 
 * 			(de)serialize that
 *
 */



struct Meta_Type
{
	Hash hash;
	char* name;
	bool ispointer;
	bool isunsigned;
	bool isvolatile;
	bool isconst;
	bool isarray;
	uint32 pointer_depth;

	Meta_Type* next;
};

bool meta_type_equals(Meta_Type* a, Meta_Type* b)
{
	return a->hash == b->hash;
}

void populate_meta_type(Struct_Member* member, Struct_Kind kind, Struct_Def* parent, Meta_Type* meta)
{
#define defhash(v) Hash v##hash = hash_literal(#v)
	defhash(const);
	defhash(volatile);
	defhash(unsigned);
	if(kind == StructKind_Member) {
		auto var = &member->member_var;
		for(isize i = 0; i < var->count; ++i) {
			char* term = var->terms[i];
			meta->name = var->name;

			Hash termhash = hash_string(term, strlen(term));
			if(termhash == consthash) {
				meta->isconst = true;
			} else if(termhash == volatilehash) {
				meta->isvolatile = true;
			} else if(termhash == unsignedhash) {
				meta->isunsigned = true;
			}
			meta->ispointer = var->asterisk_count > 0;
			meta->pointer_depth = var->asterisk_count;
			meta->isarray = var->array_levels > 0;
	 	}
	}
}

Meta_Type* get_types_in_struct(Struct_Def* def, Meta_Type* head, Memory_Arena* arena)
{
	for(isize i = 0; i < def->member_count; ++i) {
		populate_meta_type(def->members + i, def->member_kinds[i], def, head);
		head->next = arena_push_struct(arena, Meta_Type); 
		head = head->next;
	}
	return head;
}

enum Meta_Flags
{
	MetaFlag_IsPointer = Flag(0),
	MetaFlag_IsUnsigned = Flag(1),
	MetaFlag_IsVolatile = Flag(2),
	MetaFlag_IsConst = Flag(3),
	MetaFlag_IsArray = Flag(4),
};

struct Meta_Member
{
	uint64 flags;
	isize type_index;
	uint32 pointer_depth;
	char* parentname;
	char* name;
	uint64 offset;
};

void print_meta_member(Meta_Member* member)
{
	printf("Meta_Member{%d, %d, %d, \"%s\", (uint64)&((%s*)NULL)->%s},",
			member->flags, 
			member->type_index,
			member->pointer_depth,
			member->name,
			member->parentname,
			member->name);
}

void print_reflection_data(Struct_Def* def)
{
	printf("Meta_Member %s_Members[] = {\n", def->name);
	for(isize i = 0; i < def->member_count; ++i) {
		Meta_Member m;
		m.parentname = def->name;

	}
	printf("};\n\n");
}