More to come...
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

400 行
28KB

  1. /*
  2. Copyright (c) 2023 : Ognjen 'xolatile' Milan Robovic
  3. Xhartae is free software! You will redistribute it or modify it under the terms of the GNU General Public License by Free Software Foundation.
  4. And when you do redistribute it or modify it, it will use either version 3 of the License, or (at yours truly opinion) any later version.
  5. It is distributed in the hope that it will be useful or harmful, it really depends... But no warranty what so ever, seriously. See GNU/GPLv3.
  6. */
  7. #ifndef CHAPTER_4_SOURCE
  8. #define CHAPTER_4_SOURCE
  9. #include "chapter_4.h"
  10. /*
  11. Of course, we could just write something like 'preview_unhighlighted_text_file' function (name is obviously a joke), but this would stylize (apply colour and effect character
  12. attributes) to our entire text file. When we're writing programs, syntax highlighting makes a lot of difference to readability, the same way the code formatting does, and initial
  13. program design structure. If you use a lot of external variables everywhere, the entire programs starts to be messy or difficult to maintain, write and debug (or both). However,
  14. if you use a lot of variables, and you pass each of them separately into functions, or if you have one huge monolithic structure (this time literal 'struct'), you aren't doing
  15. much better, except the compiler will have easier time to optimize your code, even tho that kind of code becomes pain to write. So, having few external functions, that do one
  16. thing well, and having few external variables, that won't be edited outside of that file is the best in my opinion.
  17. Your function calls won't be long, if you don't want to make those external ("global") variables visible to some other file, just move them to C source file instead of C header
  18. file, and redeclare them as 'static', making them internal variables. Keep in mind, you have to use brain more in that case, and think about what you're modifying, where and why.
  19. Well, if you want to write programs, and not to think about them, just close this and read Jin Ping Mei instead or something. There's no cheatsheet for making good programs, you
  20. choose your constraints, your program design structure, and you start working on it. Sometimes you'll have to choose between performance, maintainability, simplicity or low memory
  21. usage, and even if you are smart and manage to get three of them to work out in your project, fourth won't. I can't teach you how to choose, maybe you want to learn embedded or
  22. game development, and they each have their own advantages and disadvantages.
  23. @C
  24. void preview_unhighlighted_text_file (char * text_file, int x, int y) {
  25. char * text_data;
  26. text_data = file_record (text_file);
  27. for (curses_active = 1; curses_active != 0; ) {
  28. curses_render_background (' ', COLOUR_WHITE, EFFECT_NORMAL);
  29. curses_render_string (text_data, COLOUR_WHITE, EFFECT_NORMAL, x, x);
  30. curses_synchronize ();
  31. }
  32. text_data = deallocate (text_data);
  33. }
  34. @
  35. So, lets write very basic C programming language syntax highlighting, explain how can we easily do it in little more than 150 lines of (scarily verbose and nicely aligned) code
  36. and why we don't need regular expressions for it. You can use these 'syntax_*' functions to tokenize some source code, highlight the syntax of it or something else that I didn't
  37. even think about if you're creative. Of course, we can use it to highlight syntax of some other programming language, not only C, and we'll use it later to highlight assembly,
  38. Ada, C++, and maybe few more programming languages.
  39. Note that regular expressions are way more powerful way of achieving the same results, and doing even more things like replacing some parts of the strings. This is simple solution
  40. for simple problem. We'll define some internal variables below, functions 'syntax_delete' (that'll be called automatically when we exit the program), 'syntax_define' to make rules
  41. about our character and string matching and 'syntax_select' to process our text file (which is just an array of character, also known as, low and behold, a string). Last function,
  42. 'syntax_select', will return index of the syntax rule that matches to our offset in string and store size of the match in 'length' variable, we'll look into it.
  43. */
  44. static int syntax_count = 0; // Number of previously defined syntax rules.
  45. static int * syntax_enrange = NULL; // Syntax rule can start with any character from 'syntax_begin' if this value is TRUE.
  46. static int * syntax_derange = NULL; // Syntax rule can start with any character from 'syntax_end' if this value is TRUE.
  47. static char * * syntax_begin = NULL; // Strings containing valid character (sub)sequence for begining the scan.
  48. static char * * syntax_end = NULL; // Strings containing valid character (sub)sequence for ending the scan.
  49. static char * syntax_escape = NULL; // Escape sequence for the rule, useful for line-breaks in C macros and line-based languages.
  50. static int * syntax_colour = NULL; // Colour for our token, these two could be completely independent, but I like to keep them here.
  51. static int * syntax_effect = NULL; // Effect for our token.
  52. /*
  53. Lets go in more details about how this function works. Standard library function 'atexit' will take as an argument function pointer of form 'extern void name (void)' that will,
  54. imagine my shock, be executed at the exit point of our little program. We can make mistakes using it, if we don't think while we write our programs, the error will be obvious,
  55. memory will be leaked or double-freed, Valgrind will detect it, we'd fix it. Also keep in mind, you can't have too much functions executed at the end, you can check for the value
  56. of 'ATEXIT_MAX', which is at least 32 by some standards (POSIX).
  57. So the goal is, we think a bit more when we structure our program, and we don't worry about if we forgot to deinitialize something. We'll reuse this in chapter five, but use
  58. contra-approach, where we want to explicitly deinitialize syntax. If you take a look in the next function, 'syntax_define', you'll see that we'll use 'atexit' function only once,
  59. when 'syntax_active' is FALSE, we'll change it to true, so 'atexit' won't be executed every time we call 'syntax_define', which is good. Lastly, in the 'syntax_delete' function,
  60. we're just deallocating (freeing) the memory, so we don't leak it and generate Valgrind warnings.
  61. */
  62. static void syntax_delete (void) {
  63. int offset;
  64. if (syntax_count == 0) { // If syntax "library" wasn't used, we don't want to deallocate memory, we just return.
  65. return;
  66. }
  67. // We could reverse-loop through this without a local variable 'offset' using this approach, but I consider this bad for readability.
  68. // --syntax_count;
  69. // do {
  70. // syntax_begin [syntax_count] = deallocate (syntax_begin [syntax_count]);
  71. // syntax_end [syntax_count] = deallocate (syntax_end [syntax_count]);
  72. // } while (--syntax_count != -1);
  73. for (offset = 0; offset < syntax_count; ++offset) {
  74. syntax_begin [offset] = deallocate (syntax_begin [offset]); // Since these two are arrays of strings, we need to deallocate, otherwise we'll leak memory.
  75. syntax_end [offset] = deallocate (syntax_end [offset]); // We're basically freeing memory one by one string, you'll see below how we allocate it.
  76. }
  77. syntax_enrange = deallocate (syntax_enrange); // And now we're deallocating the rest of arrays, so no memory is leaked.
  78. syntax_derange = deallocate (syntax_derange);
  79. syntax_begin = deallocate (syntax_begin);
  80. syntax_end = deallocate (syntax_end);
  81. syntax_escape = deallocate (syntax_escape);
  82. syntax_colour = deallocate (syntax_colour);
  83. syntax_effect = deallocate (syntax_effect);
  84. syntax_count = 0; // Lastly, I like to do this, but you don't have to. We'll use it in later chapter tho.
  85. }
  86. /*
  87. In 'syntax_define' function we're reallocating (enlarging) memory, effectively adding a new element into our arrays, and assigning or copying data to them. These syntax rules will
  88. be used with 'syntax_select' function to make our syntax highlighting. Lets explain what those function arguments do:
  89. @C
  90. int syntax_define (int enrange, // Strict matching of string 'begin' in buffer range if FALSE, any character matching if TRUE.
  91. int derange, // Strict matching of string 'end' in buffer range if FALSE, and again, any character matching if TRUE.
  92. char * begin, // String of array of characters to begin matching.
  93. char * end, // String of array of characters to end matching, I don't know why I explain these...
  94. char escape, // Escape character, useful for C preprocessor.
  95. int colour, // Colour.
  96. int effect); // Effect, I hate explaining the code when the identifiers are descriptive.
  97. @
  98. */
  99. int syntax_define (int enrange, int derange, char * begin, char * end, char escape, int colour, int effect) {
  100. if (syntax_count == 0) { // If our syntax isn't active, we'll execute this only once.
  101. atexit (syntax_delete); // Mark this function to be executed at program exit point.
  102. } // It's same if we use more 'syntax_highlight_*' functions.
  103. fatal_failure (begin == NULL, "syntax_define: Begin string is null pointer."); // I don't like checking for errors, but here, voila.
  104. fatal_failure (end == NULL, "syntax_define: End string is null pointer.");
  105. ++syntax_count;
  106. syntax_enrange = reallocate (syntax_enrange, syntax_count * (int) sizeof (* syntax_enrange)); // Now, we have block of memory reallocation for syntax data:
  107. syntax_derange = reallocate (syntax_derange, syntax_count * (int) sizeof (* syntax_derange));
  108. syntax_begin = reallocate (syntax_begin, syntax_count * (int) sizeof (* syntax_begin));
  109. syntax_end = reallocate (syntax_end, syntax_count * (int) sizeof (* syntax_end));
  110. syntax_escape = reallocate (syntax_escape, syntax_count * (int) sizeof (* syntax_escape));
  111. syntax_colour = reallocate (syntax_colour, syntax_count * (int) sizeof (* syntax_colour));
  112. syntax_effect = reallocate (syntax_effect, syntax_count * (int) sizeof (* syntax_effect));
  113. syntax_enrange [syntax_count - 1] = enrange; // In order to "make space" for our actual data.
  114. syntax_derange [syntax_count - 1] = derange;
  115. syntax_escape [syntax_count - 1] = escape;
  116. syntax_colour [syntax_count - 1] = colour;
  117. syntax_effect [syntax_count - 1] = effect;
  118. syntax_begin [syntax_count - 1] = allocate ((string_length (begin) + 1) * (int) sizeof (* * syntax_begin)); // We need to allocate enough memory for our strings now.
  119. syntax_end [syntax_count - 1] = allocate ((string_length (end) + 1) * (int) sizeof (* * syntax_end)); // Notice, we won't REallocate, just allocate!
  120. string_copy (syntax_begin [syntax_count - 1], begin); // Finally, we're copying our strings into syntax data.
  121. string_copy (syntax_end [syntax_count - 1], end);
  122. return (syntax_count - 1); // We return the index, but we won't use it in this chapter.
  123. }
  124. /*
  125. This is more complex, but if you use your eyes to look, your brain to comprehend and your heart to love, I'm sure that you'll understand it.
  126. */
  127. int syntax_select (char * string, int * length) {
  128. int offset, select;
  129. if (syntax_count == 0) { // Don't select without rules, return!
  130. return (syntax_count);
  131. }
  132. fatal_failure (string == NULL, "syntax_select: String is null.");
  133. fatal_failure (length == NULL, "syntax_select: Length is null.");
  134. // In this first part of the function, we need to check if our syntax rule has been detected at the string offset we've provided. We're looping defined syntax rules and
  135. // choosing whether to compare any of the characters, or full string, depending on 'syntax_enrange' value which is essentially boolean, true or false, which I express with
  136. // 'int' type for "type-safety simplicity". Keep in mind that we're not returning or modifying the string we provided, so it won't be null-terminated, instead I think
  137. // it's best to modify only variable 'length', hence we check with 'string_compare_limit' function.
  138. for (select = offset = 0; select != syntax_count; ++select) { // We're looping defined syntax rules:
  139. int begin = string_length (syntax_begin [select]);
  140. if (syntax_enrange [select] == FALSE) { // Choosing the comparisson based on 'syntax_enrange':
  141. if (syntax_derange [select] == FALSE) { // Either full string, or any character in it.
  142. if (string_compare_limit (string, syntax_begin [select], begin) == TRUE) { // Limiting our string comparisson.
  143. break; // If strings are same, we exit the loop.
  144. }
  145. } else {
  146. if ((string_compare_limit (string, syntax_begin [select], begin) == TRUE) // We need to see if we found our string, and:
  147. && (character_compare_array (string [offset + begin], syntax_end [select]) == TRUE)) { // If next character, after the string is in 'syntax_end'.
  148. break;
  149. } // Otherwise, we implcitly continue the loop.
  150. }
  151. } else { // Else, we compare any character.
  152. if (character_compare_array (string [offset], syntax_begin [select]) == TRUE) { // With our obviously named function...
  153. break; // We found it, exit the loop!
  154. } // If we didn't, just continue.
  155. }
  156. } // And now we have our 'select' value.
  157. // If there was no syntax rule detected, we need to return from a function, and increment the offset by setting variable 'length' to 1. If we don't increment it, at the
  158. // first unrecognized character, our second nested-loop inside function 'syntax_render_file' would use uninitialized or zero value, depending on how we structured our code
  159. // before that. We also return 'syntax_count' as the syntax rule index, which is invalid, and would produce Valgrind warning if we didn't handle it. In my unimportant
  160. // opinion, this if statement is the ugliest part of the function.
  161. if (select >= syntax_count) { // If we didn't found our string, return.
  162. * length = 1;
  163. return (syntax_count);
  164. }
  165. // In this second part, we have our 'select' value, index of the syntax rule, and we want to know the 'length' value, by trying to match with 'syntax_end' string. We have
  166. // to again, separate two cases for matching any character or full string, except that we use it to determine its' match-length. Important difference is also that there's
  167. // special case where we have escape character matching, and where 'syntax_end' string is empty (but not NULL), so in that case we match only one character. We could have
  168. // nested loop there, and second loop would need goto statement to exit it, so we only use one loop.
  169. for (offset = 1; string [offset - 1] != '\0'; ++offset) { // Now, offset must be 1, and we loop...
  170. int end = string_length (syntax_end [select]);
  171. if (string [offset] == syntax_escape [select]) { // Here's our escape exception.
  172. ++offset;
  173. continue;
  174. }
  175. if (syntax_derange [select] == FALSE) { // Choosing what to compare, yet again...
  176. if (string_compare_limit (& string [offset], syntax_end [select], end) == TRUE) { // Again, we're comparing full string.
  177. * length = offset + end; // We found it, yaay!
  178. break;
  179. }
  180. } else {
  181. if (syntax_end [select] [0] == CHARACTER_NULL) { // And here's our empty string exception.
  182. * length = offset; // On that case, we break from loop.
  183. break;
  184. }
  185. if (character_compare_array (string [offset], syntax_end [select]) == TRUE) { // Otherwise, we compare to see if the end is near!
  186. * length = offset;
  187. break;
  188. }
  189. } // These two loops look similar, but no!
  190. } // And now we have our 'length' value.
  191. return (select); // Lastly, return syntax rule index.
  192. }
  193. /*
  194. Imagine my shock, we can now print coloured text, without regular expressions. Nothing much, we can print it without using 'curses_*' functions, but if we want to preview large,
  195. well more than 24 line of code, we'd want to scroll it or modify it if we're making a text editor, hence, using curses is good. Lets see how our "mini-main" subprogram-like
  196. function does its' work, and how we use 'syntax_*' functions in them, and I also want to make few syntax highlighting abstractions. We can call multiple 'syntax_highlight_*'
  197. functions, but it would mix the highlighting of those languages in that case, so we use 'syntax_delete' to reset it.
  198. Before we begin (Ada pun intended, remove this in final version), I won't (re)align 'separators' and 'keywords', because they fuck-up my comments, which I never write in my
  199. "official" programs. I write comments only here, to explain stuff in more details. Have fun... Oh, and type of variable 'keywords' an array of string pointers of automatic length,
  200. which we get with "sizeof (keywords) / sizeof (keywords [0])" part, for those keywords, it would be 32UL, and we cast it to integer. I use "long" comments outside of functions,
  201. and "short" comments inside them, while aligning them to the longest line of code, or current indentation level.
  202. */
  203. void syntax_highlight_c (void) {
  204. char * separators = ".,:;<=>+*-/%!&~^?|()[]{}'\" \t\r\n";
  205. char * keywords [] = {
  206. "register", "volatile", "auto", "const", "static", "extern", "if", "else",
  207. "do", "while", "for", "continue", "switch", "case", "default", "break",
  208. "enum", "union", "struct", "typedef", "goto", "void", "return", "sizeof",
  209. "char", "short", "int", "long", "signed", "unsigned", "float", "double"
  210. };
  211. int word;
  212. if (syntax_count != 0) { // If syntax was used, free it, then we can redefine them.
  213. syntax_delete (); // This way, we won't mix syntaces if we use this multiple times.
  214. }
  215. syntax_define (FALSE, FALSE, "/*", "*/", '\0', COLOUR_GREY, EFFECT_BOLD); // Below, we're simply using our 'syntax_define' function.
  216. syntax_define (FALSE, FALSE, "//", "\n", '\0', COLOUR_GREY, EFFECT_BOLD); // I really don't think I need to explain those, so...
  217. syntax_define (FALSE, FALSE, "#", "\n", '\\', COLOUR_YELLOW, EFFECT_ITALIC);
  218. syntax_define (FALSE, FALSE, "'", "'", '\\', COLOUR_PINK, EFFECT_BOLD);
  219. syntax_define (FALSE, FALSE, "\"", "\"", '\\', COLOUR_PINK, EFFECT_NORMAL);
  220. for (word = 0; word != (int) (sizeof (keywords) / sizeof (keywords [0])); ++word) {
  221. syntax_define (FALSE, TRUE, keywords [word], separators, '\0', COLOUR_YELLOW, EFFECT_BOLD);
  222. }
  223. syntax_define (TRUE, FALSE, "()[]{}", "", '\0', COLOUR_BLUE, EFFECT_NORMAL);
  224. syntax_define (TRUE, FALSE, ".,:;<=>+*-/%!&~^?|", "", '\0', COLOUR_CYAN, EFFECT_NORMAL);
  225. syntax_define (TRUE, TRUE, "0123456789", separators, '\0', COLOUR_PINK, EFFECT_BOLD);
  226. syntax_define (TRUE, TRUE, "abcdefghijklmnopqrstuvwxyz", separators, '\0', COLOUR_WHITE, EFFECT_NORMAL);
  227. syntax_define (TRUE, TRUE, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", separators, '\0', COLOUR_WHITE, EFFECT_BOLD);
  228. syntax_define (TRUE, TRUE, "_", separators, '\0', COLOUR_WHITE, EFFECT_ITALIC);
  229. }
  230. void syntax_highlight_ada (void) {
  231. char * separators = ".,:;<=>#+*-/&|()'\" \t\r\n";
  232. char * keywords [] = {
  233. "abort", "else", "new", "return", "abs", "elsif", "not", "reverse",
  234. "abstract", "end", "null", "accept", "entry", "select", "access", "of",
  235. "separate", "aliased", "exit", "or", "some", "all", "others", "subtype",
  236. "and", "for", "out", "array", "function", "at", "tagged", "generic",
  237. "package", "task", "begin", "goto", "pragma", "body", "private", "then",
  238. "type", "case", "in", "constant", "until", "is", "raise", "use",
  239. "if", "declare", "range", "delay", "limited", "record", "when", "delta",
  240. "loop", "rem", "while", "digits", "renames", "with", "do", "mod",
  241. "requeue", "xor", "procedure", "protected", "interface", "synchronized", "exception", "overriding",
  242. "terminate"
  243. };
  244. int word;
  245. if (syntax_count != 0) {
  246. syntax_delete ();
  247. }
  248. syntax_define (FALSE, FALSE, "--", "\n", '\0', COLOUR_GREY, EFFECT_BOLD);
  249. syntax_define (FALSE, FALSE, "'", "'", '\\', COLOUR_PINK, EFFECT_BOLD);
  250. syntax_define (FALSE, FALSE, "\"", "\"", '\\', COLOUR_PINK, EFFECT_NORMAL);
  251. for (word = 0; word != (int) (sizeof (keywords) / sizeof (keywords [0])); ++word) {
  252. syntax_define (FALSE, TRUE, keywords [word], separators, '\0', COLOUR_YELLOW, EFFECT_BOLD);
  253. }
  254. syntax_define (TRUE, FALSE, "()#", "", '\0', COLOUR_BLUE, EFFECT_NORMAL);
  255. syntax_define (TRUE, FALSE, ".,:;<=>+*-/&|'", "", '\0', COLOUR_CYAN, EFFECT_NORMAL);
  256. syntax_define (TRUE, TRUE, "0123456789", separators, '\0', COLOUR_PINK, EFFECT_BOLD);
  257. syntax_define (TRUE, TRUE, "abcdefghijklmnopqrstuvwxyz", separators, '\0', COLOUR_WHITE, EFFECT_NORMAL);
  258. syntax_define (TRUE, TRUE, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", separators, '\0', COLOUR_WHITE, EFFECT_BOLD);
  259. syntax_define (TRUE, TRUE, "_", separators, '\0', COLOUR_WHITE, EFFECT_ITALIC);
  260. }
  261. void syntax_render_file (char * text_file, int x, int y) {
  262. char * text_data; // This local variable will hold our data.
  263. int reset_x, reset_y; // Since we're using curses, we want to reset the offset.
  264. curses_configure (); // Curses configuration, aka printing ugly text.
  265. switch (file_type (text_file)) { // Depending on our file extension, we select highlighting.
  266. case FILE_TYPE_C_SOURCE:
  267. case FILE_TYPE_C_HEADER:
  268. syntax_highlight_c ();
  269. break;
  270. case FILE_TYPE_ADA_BODY:
  271. case FILE_TYPE_ADA_SPECIFICATION:
  272. syntax_highlight_ada ();
  273. break;
  274. default:
  275. break;
  276. }
  277. text_data = file_record (text_file); // And, imagine, importing our file data into a buffer!
  278. reset_x = x;
  279. reset_y = y;
  280. for (curses_active = 1; curses_active != 0; ) { // We enter our main subprogram loop.
  281. int offset, select, length;
  282. curses_render_background (' ', COLOUR_WHITE, EFFECT_NORMAL); // We need to clear the screen buffer before rendering.
  283. x = reset_x;
  284. y = reset_y;
  285. select = syntax_count; // I intentionally set this to an invalid value.
  286. length = 0;
  287. for (offset = 0; offset < string_length (text_data); offset += length) { // And it's time to start rendering our file.
  288. int suboffset, colour, effect;
  289. select = syntax_select (& text_data [offset], & length); // Here we're evaluating variables 'select' and 'length'.
  290. // We can do the same thing in 2 lines of code, but it's less readable in my opinion, I prefer longer verbose way below...
  291. // colour = (select >= syntax_count) ? COLOUR_WHITE : syntax_colour [select];
  292. // effect = (select >= syntax_count) ? EFFECT_NORMAL : syntax_effect [select];
  293. // Or, if you find this more intuitive:
  294. // colour = (select < syntax_count) ? syntax_colour [select] : COLOUR_WHITE;
  295. // effect = (select < syntax_count) ? syntax_effect [select] : EFFECT_NORMAL;
  296. if (select >= syntax_count) { // Here, we're handling error value of 'syntax_select'.
  297. colour = COLOUR_WHITE;
  298. effect = EFFECT_NORMAL;
  299. } else {
  300. colour = syntax_colour [select];
  301. effect = syntax_effect [select];
  302. }
  303. for (suboffset = 0; suboffset < length; ++suboffset) { // Sadly, we need to render them one by one character.
  304. if (text_data [offset + suboffset] == CHARACTER_LINE_FEED) { // Rendering of blank characters isn't counted, so:
  305. x = reset_x; // If there's a new line, we need to reset 'x' value.
  306. y += 1; // And increment 'y' value.
  307. } else if (text_data [offset + suboffset] == CHARACTER_TAB_HORIZONTAL) { // If there's a tab, we offset 'x' value by normal count.
  308. x += 8; // Normal indentation is 8-characters wide.
  309. } else {
  310. curses_render_character (text_data [offset + suboffset], colour, effect, x, y); // Finally, we can render it character by character.
  311. x += 1;
  312. }
  313. }
  314. }
  315. curses_synchronize (); // Lastly, we synchronize our terminal.
  316. }
  317. text_data = deallocate (text_data); // And deallocate the memory when we exit the subprogram.
  318. }
  319. #endif