dopp_parser.d 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import dopp;
  2. // Parser checks tokens for correct program
  3. //export void parse(Token[] tokens){
  4. export string parse(Token[] tokens){
  5. string result;
  6. auto i = 0;
  7. while(i < tokens.length){
  8. /+
  9. if(tokens[i].type == TokenType.Keyword && tokens[i].lexeme == "if"){
  10. if(i + 2 < tokens.length && tokens[i+1].type == TokenType.Symbol && tokens[i+1].lexeme == "("){ // if begins
  11. writeln("Found 'if' statement");
  12. i++; // goto (
  13. // here parsing inside ( .. ) can be extended
  14. while(i < tokens.length && tokens[i].lexeme != ")"){
  15. i++;
  16. }
  17. if(i < tokens.length && tokens[i].lexeme == ")"){
  18. i++; // goto )
  19. if(i < tokens.length && tokens[i].lexeme == "{"){ // block of code
  20. writeln("Opening block for if statement");
  21. // here parsing inside { .. } can be extended
  22. while(i < tokens.length && tokens[i].lexeme != "}"){
  23. i++;
  24. }
  25. if(i < tokens.length && tokens[i].lexeme == "}"){
  26. writeln("Closing block for if statement");
  27. i++;
  28. }else{
  29. writeln("Error: Missing closing brace for if block");
  30. return;
  31. }
  32. }else{
  33. writeln("Error: Expected opening brace after if condition");
  34. return;
  35. }
  36. }else{
  37. writeln("Error: Missing closing parenthesis for if condition");
  38. return;
  39. }
  40. }else{
  41. writeln("Error: Invalid if statement syntax");
  42. return;
  43. }
  44. }
  45. +/
  46. if( (tokens[i].type != TokenType.New_Line) &&
  47. (tokens[i].type != TokenType.Indent_Incr) &&
  48. (tokens[i].type != TokenType.Indent_Decr) &&
  49. (tokens[i].type != TokenType.Round_Bracket) &&
  50. ( (i + 1) < tokens.length ) && (tokens[i + 1].lexeme != ";") &&
  51. (tokens[i + 1].type != TokenType.New_Line) &&
  52. (tokens[i + 1].type != TokenType.Indent_Incr) &&
  53. (tokens[i + 1].type != TokenType.Indent_Decr) &&
  54. (tokens[i + 1].type != TokenType.Round_Bracket) ){
  55. result ~= tokens[i].lexeme ~ " "; // add whitespace between lexemes, but not after "\n" new_line, ";", "{", "}", "(", ")"
  56. }else{
  57. result ~= tokens[i].lexeme; // for just show all text
  58. }
  59. i++; // goto next token
  60. }
  61. return result;
  62. }