Commits

Vedran Miletić committed 3158bfa

Incijalni rad na Python prevoditelju u D

  • Participants

Comments (0)

Files changed (4)

+#! /usr/bin/env rdmd
+ import std.stdio; void main () { writeln("test"); writeln("test2"); writeln("kompiliramo python u strojni kod 8)"); writeln("test3");  }
+cat test.py | ./python.d > compiled.d
+chmod +x compiled.d
+./compiled.d
+
+#! /usr/bin/env rdmd
+
+import std.stdio;
+import std.exception;
+
+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 ~ " }";
+  
+  writeln(dCode);
+
+}
+
+enum tokenType {
+  whitespace,
+  symbol,
+  literal,
+}
+
+struct token {
+  tokenType type;
+  string value;
+}
+
+token[] tokenize (string input) {
+  
+  import std.string;
+  import std.regex;
+
+  token[] tokens;
+  int offset = 0;
+  string remaining = input;
+  
+  while (remaining.length > 0) {
+    
+    if (remaining.length > stripLeft(remaining).length) {
+      tokens ~= token(tokenType.whitespace, remaining[0 .. remaining.length - stripLeft(remaining).length]);
+      remaining = remaining[remaining.length - stripLeft(remaining).length .. $];
+      continue;
+    }
+
+    auto symbolRegex = ctRegex!r"^[a-z_][a-z0-9_]*";
+    auto m = match(remaining, symbolRegex);
+    if (m.captures.length > 0) {
+      tokens ~= token(tokenType.symbol, m.captures[0]);
+      remaining = remaining[m.captures[0].length .. $];
+      continue;
+    }
+
+    auto literalRegex = ctRegex!`^"(\\\\.|[^\\\\"])*"`;
+    auto m2 = match(remaining, literalRegex);
+    if (m2.captures.length > 0) {
+      tokens ~= token(tokenType.literal, m2.captures[0]);
+      remaining = remaining[m2.captures[0].length .. $];
+      continue;
+    }
+ 
+    throw new Exception("Syntax error");
+  }
+
+  //writeln(remaining);
+  
+  return tokens;
+}
+
+
+string generate (token[] tokens) {
+  int offset = 0;
+  string dCode = "";
+
+  for (offset = 0; offset < tokens.length; offset++) {
+    auto token = tokens[offset];
+    if (token.type == tokenType.whitespace)
+      continue;
+    if (token.type == tokenType.symbol) {
+      if (token.value == "print") {
+        if (tokens[offset + 1].type == tokenType.whitespace)
+          offset++;
+        assert(tokens[offset + 1].type == tokenType.literal);
+        dCode ~= "writeln(" ~ tokens[offset + 1].value ~ "); ";
+        offset++;
+      }
+    } else {
+      throw new Exception("Can't handle token");
+    }
+
+  }
+
+  return dCode;
+}
+
+
+print "test"
+print "test2"
+print "kompiliramo python u strojni kod 8)"
+print "test3"
+