Commits

luka8088 committed ac20986

minor cleanup

Signed-off-by: luka8088 <luka8088@owave.net>

Comments (0)

Files changed (6)

compiled.d

-#! /usr/bin/env rdmd
- import std.stdio; void main () { writeln("test"); writeln("test2"); writeln("kompiliramo python u strojni kod 8)"); writeln("test3");  }

do.sh

-cat test.py | ./python.d > compiled.d
-chmod +x compiled.d
-./compiled.d
-
+print "test"
+print "test2"
+print "kompiliramo python u strojni kod 8)"
+print "test3"
+
 #! /usr/bin/env rdmd
 
-import std.stdio;
 import std.exception;
+import std.stdio;
+import std.file;
+import std.process;
 
-void main () {
-
-  string pyKod;
-  char[] buf;
-  while (stdin.readln(buf))
-    pyKod ~= buf;
-
-  auto generated = generate(tokenize(pyKod));
-
-  auto dCode = "#! /usr/bin/env rdmd\n import std.stdio; void main () { "
-    ~ generated ~ " }";
+void main (string[] arguments) {
+  
+  enforce(arguments.length == 2);
+  auto pythonCode = cast(string) std.file.read(arguments[1]);
   
-  writeln(dCode);
+  auto dCode = generate(tokenize(pythonCode));
+  
+  auto tempPath = std.file.tempDir ~ "/python_compiler_h1af3ijejivxkpqrduifgjbzss5gcfg37ks7bjnrluzyro5f";
+  if (std.file.exists(tempPath))
+    rmdirRecurse(tempPath);
+  mkdirRecurse(tempPath);
+  std.file.write(tempPath ~ "/program.d", dCode);
+  
+  //auto cwd = getcwd();
+  //chdir(tempPath);
+  //scope(exit) chdir(cwd);
+  
+  system("dmd -run " ~ tempPath ~ "/program.d");
 
 }
 
 
 string generate (token[] tokens) {
   int offset = 0;
-  string dCode = "";
-
+  string dCode = "import std.stdio;\n\nvoid main () {\n";
+  
   for (offset = 0; offset < tokens.length; offset++) {
     auto token = tokens[offset];
     if (token.type == tokenType.whitespace)
         if (tokens[offset + 1].type == tokenType.whitespace)
           offset++;
         assert(tokens[offset + 1].type == tokenType.literal);
-        dCode ~= "writeln(" ~ tokens[offset + 1].value ~ "); ";
+        dCode ~= "writeln(" ~ tokens[offset + 1].value ~ ");\n";
         offset++;
       }
     } else {
     }
 
   }
+  
+  dCode ~= "\n}\n";
 
   return dCode;
 }
+
+This compiler rewrites python code into D code making it compileable to native machine code.
+
+Example usage: `./python.d examples/test.py`

test.py

-print "test"
-print "test2"
-print "kompiliramo python u strojni kod 8)"
-print "test3"
-