main.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. COMPILER_PATH = "interface/HUTN"
  2. import sys
  3. sys.path.append(COMPILER_PATH)
  4. sys.path.append("wrappers")
  5. from hutn_compiler.compiler import main as do_compile
  6. from modelverse import *
  7. import os
  8. import time
  9. init(sys.argv[1])
  10. login("HUTN", "HUTN")
  11. def clean_code(code):
  12. if code == "":
  13. return code
  14. code_fragments = code.split("\n")
  15. code_fragments = [i.rstrip() for i in code_fragments if i.strip() != ""]
  16. code_fragments = [i.replace(" ", "\t") for i in code_fragments]
  17. initial_tabs = min([len(i) - len(i.lstrip("\t")) for i in code_fragments])
  18. code_fragments = [i[initial_tabs:] for i in code_fragments]
  19. code_fragments.append("")
  20. code = "\n".join(code_fragments)
  21. return code.encode('ascii', 'replace')
  22. def compile_service(port):
  23. start = time.time()
  24. temp_file = ".tmp_%s" % port
  25. def compile_AL(code):
  26. code = clean_code(code)
  27. if code == "":
  28. return [0]
  29. with open(temp_file, "w") as f:
  30. f.write(code.decode())
  31. f.flush()
  32. compiled = do_compile(temp_file, COMPILER_PATH + "/grammars/actionlanguage.g", "CS")
  33. print("Compiled: " + str(compiled))
  34. os.remove(temp_file)
  35. return compiled
  36. def compile_model(code):
  37. code = clean_code(code)
  38. if code == "":
  39. return [0]
  40. with open(temp_file, "w") as f:
  41. f.write(code.decode())
  42. f.flush()
  43. compiled = do_compile(temp_file, COMPILER_PATH + "/grammars/modelling.g", "M")
  44. os.remove(temp_file)
  45. return compiled
  46. mode = service_get(port)
  47. code = service_get(port)
  48. try:
  49. if mode == "code":
  50. compiled = compile_AL(code)
  51. service_set(port, "OK")
  52. service_set(port, compiled)
  53. elif mode == "model":
  54. compiled = compile_model(code)
  55. service_set(port, "OK")
  56. service_set(port, compiled)
  57. else:
  58. raise Exception("No such mode: " + mode)
  59. except Exception as e:
  60. service_set(port, str(e))
  61. raise
  62. service_register("compiler", compile_service)
  63. try:
  64. if sys.version_info[0] < 3:
  65. while raw_input() != "STOP":
  66. pass
  67. else:
  68. while input() != "STOP":
  69. pass
  70. except EOFError:
  71. import time
  72. while 1:
  73. time.sleep(1.0)
  74. finally:
  75. service_stop()