CodeGenerator.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.Linq;
  3. namespace csharp_sccd_compiler
  4. {
  5. public abstract class CodeGenerator : Visitor
  6. {
  7. protected Platform current_platform;
  8. protected Platform[] supported_platforms;
  9. protected FileOutputer output_file;
  10. public enum Platform {
  11. THREADS,
  12. GAMELOOP
  13. };
  14. private enum IndentType {
  15. NOT_SET,
  16. SPACES,
  17. TABS
  18. }
  19. public CodeGenerator(Platform[] supported_platforms)
  20. {
  21. this.supported_platforms = supported_platforms;
  22. }
  23. public bool generate(ClassDiagram class_diagram, string output_file_path, Platform current_platform)
  24. {
  25. this.current_platform = current_platform;
  26. if (! this.supported_platforms.Contains(this.current_platform))
  27. {
  28. Logger.displayError("Unsupported platform.");
  29. return false;
  30. }
  31. try
  32. {
  33. this.output_file = new FileOutputer(output_file_path);
  34. class_diagram.accept(this);
  35. }
  36. finally
  37. {
  38. this.output_file.close();
  39. }
  40. return true;
  41. }
  42. protected void writeCorrectIndent(string code)
  43. {
  44. string[] lines = code.Split('\n');
  45. int begin_index = 0;
  46. while (begin_index < lines.Length && lines[begin_index].Trim() == "")
  47. begin_index += 1;
  48. if (begin_index >= lines.Length)
  49. return;
  50. int end_index = lines.Length - 1;
  51. while (end_index > begin_index && lines[end_index].Trim() == "")
  52. {
  53. end_index -= 1;
  54. }
  55. //first index where valid code is present
  56. int to_strip_length = lines[begin_index].TrimEnd().Length - lines[begin_index].Trim().Length;
  57. IndentType indent_type = IndentType.NOT_SET;
  58. for(int index = begin_index; index <= end_index; ++index)
  59. {
  60. string strip_part = lines[index].Substring (0, to_strip_length);
  61. if ((strip_part.Contains ('\t') && strip_part.Contains (' ')) ||
  62. (indent_type == IndentType.SPACES && strip_part.Contains ('\t')) ||
  63. (indent_type == IndentType.TABS && strip_part.Contains (' '))
  64. )
  65. throw new CodeBlockException ("Mixed tab and space indentation!");
  66. if (indent_type == IndentType.NOT_SET) {
  67. if (strip_part.Contains (' '))
  68. indent_type = IndentType.SPACES;
  69. else if (strip_part.Contains ('\t'))
  70. indent_type = IndentType.TABS;
  71. }
  72. this.output_file.write (lines[index].Substring (to_strip_length));
  73. }
  74. }
  75. }
  76. }