Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

459 строки
13 KiB

  1. proc string_equal(const char input[], const char check[]) -> bool {
  2. if (input == check) return true;
  3. for(int i = 0; input[i] == check[i]; i++) {
  4. if (input[i] == '\0')
  5. return true;
  6. }
  7. return false;
  8. }
  9. proc string_equal(String* str, const char check[]) -> bool {
  10. return string_equal(Memory::get_c_str(str), check);
  11. }
  12. proc string_equal(const char check[], String* str) -> bool {
  13. return string_equal(Memory::get_c_str(str), check);
  14. }
  15. proc string_equal(String* str1, String* str2) -> bool {
  16. if (str1 == str2)
  17. return true;
  18. return string_equal(Memory::get_c_str(str1), Memory::get_c_str(str2));
  19. }
  20. proc get_nibble(char c) -> char {
  21. if (c >= 'A' && c <= 'F')
  22. return (c - 'A') + 10;
  23. else if (c >= 'a' && c <= 'f')
  24. return (c - 'a') + 10;
  25. return (c - '0');
  26. }
  27. proc escape_string(char* in) -> char* {
  28. // TODO(Felix): add more escape sequences
  29. int i = 0, count = 0;
  30. while (in[i] != '\0') {
  31. switch (in[i]) {
  32. case '\\':
  33. case '\n':
  34. case '\t':
  35. ++count;
  36. default: break;
  37. }
  38. ++i;
  39. }
  40. char* ret = (char*)malloc((i+count+1)*sizeof(char));
  41. // copy in
  42. i = 0;
  43. int j = 0;
  44. while (in[i] != '\0') {
  45. switch (in[i]) {
  46. case '\\': ret[j++] = '\\'; ret[j++] = '\\'; break;
  47. case '\n': ret[j++] = '\\'; ret[j++] = 'n'; break;
  48. case '\t': ret[j++] = '\\'; ret[j++] = 't'; break;
  49. default: ret[j++] = in[i];
  50. }
  51. ++i;
  52. }
  53. ret[j++] = '\0';
  54. return ret;
  55. }
  56. proc unescape_string(char* in) -> bool {
  57. if (!in)
  58. return true;
  59. char *out = in, *p = in;
  60. const char *int_err = nullptr;
  61. while (*p && !int_err) {
  62. if (*p != '\\') {
  63. /* normal case */
  64. *out++ = *p++;
  65. } else {
  66. /* escape sequence */
  67. switch (*++p) {
  68. case '0': *out++ = '\a'; ++p; break;
  69. case 'a': *out++ = '\a'; ++p; break;
  70. case 'b': *out++ = '\b'; ++p; break;
  71. case 'f': *out++ = '\f'; ++p; break;
  72. case 'n': *out++ = '\n'; ++p; break;
  73. case 'r': *out++ = '\r'; ++p; break;
  74. case 't': *out++ = '\t'; ++p; break;
  75. case 'v': *out++ = '\v'; ++p; break;
  76. case '"':
  77. case '\'':
  78. case '\\':
  79. *out++ = *p++;
  80. case '?':
  81. break;
  82. case 'x':
  83. case 'X':
  84. if (!isxdigit(p[1]) || !isxdigit(p[2])) {
  85. create_parsing_error(
  86. "The string '%s' at %s:%d:%d could not be unescaped. "
  87. "(Invalid character on hexadecimal escape at char %d)",
  88. in, Parser::parser_file, Parser::parser_line, Parser::parser_col,
  89. (p+1)-in);
  90. } else {
  91. *out++ = (char)(get_nibble(p[1]) * 0x10 + get_nibble(p[2]));
  92. p += 3;
  93. }
  94. break;
  95. default:
  96. create_parsing_error(
  97. "The string '%s' at %s:%d:%d could not be unescaped. "
  98. "(Unexpected '\\' with no escape sequence at char %d)",
  99. in, Parser::parser_file, Parser::parser_line, Parser::parser_col,
  100. (p+1)-in);
  101. }
  102. }
  103. }
  104. /* Set the end of string. */
  105. *out = '\0';
  106. if (int_err)
  107. return false;
  108. return true;
  109. }
  110. proc read_entire_file(char* filename) -> char* {
  111. char *fileContent = nullptr;
  112. FILE *fp = fopen(filename, "r");
  113. if (fp) {
  114. /* Go to the end of the file. */
  115. if (fseek(fp, 0L, SEEK_END) == 0) {
  116. /* Get the size of the file. */
  117. long bufsize = ftell(fp) + 1;
  118. if (bufsize == 0) {
  119. fputs("Empty file", stderr);
  120. goto closeFile;
  121. }
  122. /* Go back to the start of the file. */
  123. if (fseek(fp, 0L, SEEK_SET) != 0) {
  124. fputs("Error reading file", stderr);
  125. goto closeFile;
  126. }
  127. /* Allocate our buffer to that size. */
  128. fileContent = (char*)calloc(bufsize, sizeof(char));
  129. /* Read the entire file into memory. */
  130. size_t newLen = fread(fileContent, sizeof(char), bufsize, fp);
  131. fileContent[newLen] = '\0';
  132. if (ferror(fp) != 0) {
  133. fputs("Error reading file", stderr);
  134. }
  135. }
  136. closeFile:
  137. fclose(fp);
  138. }
  139. return fileContent;
  140. /* Don't forget to call free() later! */
  141. }
  142. proc read_expression() -> char* {
  143. char* line = (char*)malloc(100);
  144. if(line == nullptr)
  145. return nullptr;
  146. char* linep = line;
  147. size_t lenmax = 100, len = lenmax;
  148. int c;
  149. int nesting = 0;
  150. while (true) {
  151. c = fgetc(stdin);
  152. if(c == EOF)
  153. break;
  154. if(--len == 0) {
  155. len = lenmax;
  156. char * linen = (char*)realloc(linep, lenmax *= 2);
  157. if(linen == nullptr) {
  158. free(linep);
  159. return nullptr;
  160. }
  161. line = linen + (line - linep);
  162. linep = linen;
  163. }
  164. *line = (char)c;
  165. if(*line == '(')
  166. ++nesting;
  167. else if(*line == ')')
  168. --nesting;
  169. else if(*line == '\n')
  170. if (nesting == 0)
  171. break;
  172. line++;
  173. }
  174. (*line)--; // we dont want the \n actually
  175. *line = '\0';
  176. return linep;
  177. }
  178. proc read_line() -> char* {
  179. char* line = (char*)malloc(100), * linep = line;
  180. size_t lenmax = 100, len = lenmax;
  181. int c;
  182. int nesting = 0;
  183. if(line == nullptr)
  184. return nullptr;
  185. for(;;) {
  186. c = fgetc(stdin);
  187. if(c == EOF)
  188. break;
  189. if(--len == 0) {
  190. len = lenmax;
  191. char* linen = (char*)realloc(linep, lenmax *= 2);
  192. if(linen == nullptr) {
  193. free(linep);
  194. return nullptr;
  195. }
  196. line = linen + (line - linep);
  197. linep = linen;
  198. }
  199. *line = (char)c;
  200. if(*line == '(')
  201. ++nesting;
  202. else if(*line == ')')
  203. --nesting;
  204. else if(*line == '\n')
  205. if (nesting == 0)
  206. break;
  207. line++;
  208. }
  209. (*line)--; // we dont want the \n actually
  210. *line = '\0';
  211. return linep;
  212. }
  213. proc log_message(Log_Level type, const char* message) -> void {
  214. if (type > Globals::log_level)
  215. return;
  216. const char* prefix;
  217. switch (type) {
  218. case Log_Level::Critical: prefix = "CRITICAL"; break;
  219. case Log_Level::Warning: prefix = "WARNING"; break;
  220. case Log_Level::Info: prefix = "INFO"; break;
  221. case Log_Level::Debug: prefix = "DEBUG"; break;
  222. default: return;
  223. }
  224. printf("%s: %s\n",prefix, message);
  225. }
  226. proc panic(char* message) -> void {
  227. log_message(Log_Level::Critical, message);
  228. exit(1);
  229. }
  230. char* wchar_to_char(const wchar_t* pwchar) {
  231. // get the number of characters in the string.
  232. int currentCharIndex = 0;
  233. char currentChar = (char)pwchar[currentCharIndex];
  234. while (currentChar != '\0')
  235. {
  236. currentCharIndex++;
  237. currentChar = (char)pwchar[currentCharIndex];
  238. }
  239. const int charCount = currentCharIndex + 1;
  240. // allocate a new block of memory size char (1 byte) instead of wide char (2 bytes)
  241. char* filePathC = (char*)malloc(sizeof(char) * charCount);
  242. for (int i = 0; i < charCount; i++)
  243. {
  244. // convert to char (1 byte)
  245. char character = (char)pwchar[i];
  246. *filePathC = character;
  247. filePathC += sizeof(char);
  248. }
  249. filePathC += '\0';
  250. filePathC -= (sizeof(char) * charCount);
  251. return filePathC;
  252. }
  253. proc print(Lisp_Object* node, bool print_repr, FILE* file) -> void {
  254. switch (Memory::get_type(node)) {
  255. case (Lisp_Object_Type::Nil): fputs("()", file); break;
  256. case (Lisp_Object_Type::T): fputs("t", file); break;
  257. case (Lisp_Object_Type::Number): {
  258. if (abs(node->value.number - (int)node->value.number) < 0.000001f)
  259. fprintf(file, "%d", (int)node->value.number);
  260. else
  261. fprintf(file, "%f", node->value.number);
  262. } break;
  263. case (Lisp_Object_Type::Keyword): fputs(":", file); // NOTE(Felix): intentionall fallthough
  264. case (Lisp_Object_Type::Symbol): fprintf(file, "%s", Memory::get_c_str(node->value.symbol.identifier)); break;
  265. case (Lisp_Object_Type::Continuation): fputs("[continuation]", file); break;
  266. case (Lisp_Object_Type::CFunction): fputs("[C-function]", file); break;
  267. case (Lisp_Object_Type::Pointer): fputs("[pointer]", file); break;
  268. case (Lisp_Object_Type::HashMap): {
  269. for_hash_map (node->value.hashMap) {
  270. fputs(" ", file);
  271. print(key, true, file);
  272. fputs(" -> ", file);
  273. print((Lisp_Object*)value, true, file);
  274. fputs("\n", file);
  275. }
  276. } break;
  277. case (Lisp_Object_Type::String): {
  278. if (print_repr) {
  279. putc('\"', file);
  280. char* escaped = escape_string(Memory::get_c_str(node->value.string));
  281. fputs(escaped, file);
  282. putc('\"', file);
  283. free(escaped);
  284. }
  285. else
  286. fputs(Memory::get_c_str(node->value.string), file);
  287. } break;
  288. case (Lisp_Object_Type::Vector): {
  289. fputs("[", file);
  290. if (node->value.vector.length > 0)
  291. print(node->value.vector.data);
  292. for (int i = 1; i < node->value.vector.length; ++i) {
  293. fputs(" ", file);
  294. print(node->value.vector.data+i);
  295. }
  296. fputs("]", file);
  297. } break;
  298. case (Lisp_Object_Type::Function): {
  299. if (node->userType) {
  300. fprintf(file, "[%s]", Memory::get_c_str(node->userType->value.symbol.identifier));
  301. break;
  302. }
  303. if (node->value.function.type == Function_Type::Lambda)
  304. fputs("[lambda]", file);
  305. // else if (node->value.function.type == Function_Type::Special_Lambda)
  306. // fputs("[special-lambda]", file);
  307. else if (node->value.function.type == Function_Type::Macro)
  308. fputs("[macro]", file);
  309. else
  310. assert(false);
  311. } break;
  312. case (Lisp_Object_Type::Pair): {
  313. Lisp_Object* head = node;
  314. // first check if it is a quotation form, in that case we want
  315. // to print it prettier
  316. if (Memory::get_type(head->value.pair.first) == Lisp_Object_Type::Symbol) {
  317. String* identifier = head->value.pair.first->value.symbol.identifier;
  318. auto symbol = head->value.pair.first;
  319. auto quote_sym = Memory::get_or_create_lisp_object_symbol("quote");
  320. auto unquote_sym = Memory::get_or_create_lisp_object_symbol("unquote");
  321. auto quasiquote_sym = Memory::get_or_create_lisp_object_symbol("quasiquote");
  322. if (symbol == quote_sym || symbol == unquote_sym)
  323. {
  324. putc(symbol == quote_sym
  325. ? '\''
  326. : ',', file);
  327. assert_type(head->value.pair.rest, Lisp_Object_Type::Pair);
  328. assert(head->value.pair.rest->value.pair.rest == Memory::nil);
  329. print(head->value.pair.rest->value.pair.first, print_repr, file);
  330. break;
  331. }
  332. else if (symbol == quasiquote_sym) {
  333. putc('`', file);
  334. assert_type(head->value.pair.rest, Lisp_Object_Type::Pair);
  335. print(head->value.pair.rest->value.pair.first, print_repr, file);
  336. break;
  337. }
  338. }
  339. putc('(', file);
  340. // NOTE(Felix): We cuold do a while true here, however in case
  341. // we want to print a broken list (for logging the error) we
  342. // should do more checks.
  343. while (head) {
  344. print(head->value.pair.first, print_repr, file);
  345. head = head->value.pair.rest;
  346. if (!head)
  347. return;
  348. if (Memory::get_type(head) != Lisp_Object_Type::Pair)
  349. break;
  350. putc(' ', file);
  351. }
  352. if (Memory::get_type(head) != Lisp_Object_Type::Nil) {
  353. fputs(" . ", file);
  354. print(head, print_repr, file);
  355. }
  356. putc(')', file);
  357. } break;
  358. }
  359. }
  360. proc print_single_call(Lisp_Object* obj) -> void {
  361. printf(console_cyan);
  362. print(obj, true);
  363. printf(console_normal);
  364. printf("\n at ");
  365. if (obj->sourceCodeLocation) {
  366. printf("%s (line %d, position %d)",
  367. Memory::get_c_str(
  368. obj->sourceCodeLocation->file),
  369. obj->sourceCodeLocation->line,
  370. obj->sourceCodeLocation->column);
  371. } else {
  372. fputs("no source code location avaliable", stdout);
  373. }
  374. }
  375. proc print_call_stack() -> void {
  376. using Globals::Current_Execution::call_stack;
  377. printf("callstack [%d] (most recent call last):\n", call_stack.next_index);
  378. for (int i = 0; i < call_stack.next_index; ++i) {
  379. printf("%2d -> ", i);
  380. print_single_call(call_stack.data[i]);
  381. printf("\n");
  382. }
  383. }
  384. proc log_error() -> void {
  385. fputs(console_red, stdout);
  386. fputs(Memory::get_c_str(Globals::error->message), stdout);
  387. puts(console_normal);
  388. fputs(" in: ", stdout);
  389. print_call_stack();
  390. puts(console_normal);
  391. Globals::Current_Execution::call_stack.next_index = 0;
  392. }