navid/haze / 4aab20aa1d3fcd84f6c3892dfa837c7a9acf3b4f132cf92ec13930df341ac679 / src/driver.cpp

driver.cpp

← src · 14338 bytes · raw · download

#include "xyz.h"
#include "libqbe.h"

#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

#if defined(_WIN32)
#include <process.h>
#else
#include <sys/wait.h>
#include <unistd.h>
#endif

namespace fs = std::filesystem;

namespace {

struct Options {
  std::string input;
  std::string output;
  std::string target;
  std::string cc;
  std::string runtime;
  bool emit_il = false;
  bool emit_asm = false;
  bool emit_obj = false;
  bool run = false;
  bool keep = false;
  bool verbose = false;
};

void usage(FILE *f) {
  std::fprintf(f,
               "usage: xyz [options] file.xyz\n"
               "\n"
               "  -o file       output path\n"
               "  -target name  UQBE target (amd64_sysv, amd64_apple, amd64_win,\n"
               "                arm64, arm64_apple, arm64_win, rv64)\n"
               "  -S            stop after assembly\n"
               "  -c            stop after object file\n"
               "  -qbe          stop after QBE IL\n"
               "  -run          run the produced executable\n"
               "  -keep         keep temporary files\n"
               "  -cc path      C compiler used for assembly/linking\n"
               "  -runtime path path to libxyzrt.a\n"
               "  -v            print version\n"
               "  -h            print this help\n");
}

std::string lower(std::string s) {
  for (char &c : s)
    c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
  return s;
}

std::string canonical_target(std::string name) {
  name = lower(std::move(name));
  if (name == "amd64_sysv" || name == "amd64_apple" || name == "amd64_win" ||
      name == "arm64" || name == "arm64_apple" || name == "arm64_win" ||
      name == "rv64")
    return name;
  if (name == "linux/amd64" || name == "freebsd/amd64" ||
      name == "openbsd/amd64" || name == "netbsd/amd64" ||
      name == "dragonfly/amd64")
    return "amd64_sysv";
  if (name == "linux/arm64" || name == "freebsd/arm64" ||
      name == "openbsd/arm64" || name == "netbsd/arm64")
    return "arm64";
  if (name == "linux/riscv64")
    return "rv64";
  if (name == "darwin/amd64" || name == "macos/amd64" ||
      name == "macosx/amd64")
    return "amd64_apple";
  if (name == "darwin/arm64" || name == "macos/arm64" ||
      name == "macosx/arm64")
    return "arm64_apple";
  if (name == "windows/amd64" || name == "win/amd64")
    return "amd64_win";
  if (name == "windows/arm64" || name == "win/arm64")
    return "arm64_win";
  return name;
}

std::string read_file(const fs::path &p) {
  std::ifstream in(p, std::ios::binary);
  if (!in)
    throw std::runtime_error("cannot read '" + p.string() + "'");
  std::ostringstream ss;
  ss << in.rdbuf();
  return ss.str();
}

void write_file(const fs::path &p, const std::string &s) {
  std::ofstream out(p, std::ios::binary);
  if (!out)
    throw std::runtime_error("cannot write '" + p.string() + "'");
  out << s;
}

std::string shell_quote(const std::string &s) {
#if defined(_WIN32)
  std::string out = "\"";
  for (char c : s) {
    if (c == '"')
      out += "\\\"";
    else
      out.push_back(c);
  }
  out += "\"";
  return out;
#else
  std::string out = "'";
  for (char c : s) {
    if (c == '\'')
      out += "'\\''";
    else
      out.push_back(c);
  }
  out += "'";
  return out;
#endif
}

int run_tool(const std::vector<std::string> &argv, bool verbose) {
  std::ostringstream cmd;
  for (size_t i = 0; i < argv.size(); i++) {
    if (i)
      cmd << ' ';
    cmd << shell_quote(argv[i]);
  }
  if (verbose)
    std::fprintf(stderr, "+ %s\n", cmd.str().c_str());
  int rc = std::system(cmd.str().c_str());
#if defined(_WIN32)
  return rc;
#else
  if (rc == -1)
    return 1;
  if (WIFEXITED(rc))
    return WEXITSTATUS(rc);
  return 1;
#endif
}

bool is_executable_file(const fs::path &p) {
  std::error_code ec;
  return fs::is_regular_file(p, ec);
}

std::string find_in_path(const std::string &name) {
  fs::path direct(name);
  if (direct.has_parent_path()) {
    std::error_code ec;
    if (fs::is_regular_file(direct, ec))
      return fs::absolute(direct).string();
    return {};
  }
  const char *path = std::getenv("PATH");
  if (!path)
    return {};
#if defined(_WIN32)
  char sep = ';';
#else
  char sep = ':';
#endif
  std::string all(path);
  size_t start = 0;
  while (start <= all.size()) {
    size_t end = all.find(sep, start);
    if (end == std::string::npos)
      end = all.size();
    fs::path dir = all.substr(start, end - start);
    if (!dir.empty()) {
      fs::path cand = dir / name;
      if (is_executable_file(cand))
        return cand.string();
#if defined(_WIN32)
      cand = dir / (name + ".exe");
      if (is_executable_file(cand))
        return cand.string();
#endif
    }
    if (end == all.size())
      break;
    start = end + 1;
  }
  return {};
}

fs::path executable_dir(const char *argv0) {
  std::error_code ec;
  fs::path p = argv0 && *argv0 ? fs::path(argv0) : fs::path("xyz");
  if (!p.has_parent_path()) {
    std::string found = find_in_path(p.string());
    if (!found.empty())
      p = found;
  }
  p = fs::absolute(p, ec);
  if (ec)
    p = fs::path(argv0 ? argv0 : "xyz");
  p = fs::weakly_canonical(p, ec);
  return p.parent_path();
}

std::string find_runtime(const Options &o, const fs::path &exe_dir) {
  if (!o.runtime.empty()) {
    if (!is_executable_file(o.runtime))
      throw std::runtime_error("runtime archive not found: " + o.runtime);
    return fs::absolute(o.runtime).string();
  }
  if (const char *env = std::getenv("XYZ_RUNTIME")) {
    if (*env && is_executable_file(env))
      return fs::absolute(env).string();
  }
  std::vector<fs::path> dirs = {exe_dir, exe_dir / ".." / "lib",
                                exe_dir / ".." / "lib" / "xyz",
                                fs::current_path()};
  const char *names[] = {"libxyzrt.a", "xyzrt.lib", "libxyzrt.lib",
                         "xyzrt.o"};
  for (auto &d : dirs) {
    for (const char *n : names) {
      fs::path p = d / n;
      std::error_code ec;
      if (fs::is_regular_file(p, ec))
        return fs::weakly_canonical(p, ec).string();
    }
  }
  throw std::runtime_error(
      "cannot find libxyzrt.a; build it with xmake or pass -runtime path");
}

std::string find_cc(const Options &o) {
  if (!o.cc.empty()) {
    std::string p = find_in_path(o.cc);
    if (p.empty())
      throw std::runtime_error("C compiler not found: " + o.cc);
    return p;
  }
  if (const char *env = std::getenv("XYZ_CC")) {
    if (*env) {
      std::string p = find_in_path(env);
      if (!p.empty())
        return p;
    }
  }
  if (const char *env = std::getenv("CC")) {
    if (*env) {
      std::string p = find_in_path(env);
      if (!p.empty())
        return p;
    }
  }
  const char *tries[] = {
#if defined(_WIN32)
      "clang", "gcc", "cc", "cl"
#else
      "cc", "clang", "gcc"
#endif
  };
  for (const char *t : tries) {
    std::string p = find_in_path(t);
    if (!p.empty())
      return p;
  }
  throw std::runtime_error("no C compiler found; pass -cc path");
}

std::string default_output(const std::string &input, const char *ext) {
  fs::path p(input);
  p.replace_extension(ext);
  return p.string();
}

#if defined(_WIN32)
unsigned long process_id() { return static_cast<unsigned long>(_getpid()); }
#else
unsigned long process_id() { return static_cast<unsigned long>(getpid()); }
#endif

fs::path make_temp_dir() {
  std::error_code ec;
  fs::path base = fs::temp_directory_path(ec);
  if (ec)
    base = fs::current_path();
  base /= "xyz";
  fs::create_directories(base, ec);
  for (int i = 0; i < 1000; i++) {
    fs::path p = base / ("work-" + std::to_string(process_id()) + "-" +
                         std::to_string(i));
    if (fs::create_directory(p, ec))
      return p;
  }
  throw std::runtime_error("cannot create temporary directory");
}

std::string format_error(const std::string &file, const xyz::Error &e) {
  std::ostringstream ss;
  ss << file << ':' << e.pos.line << ':' << e.pos.col << ": error: "
     << e.what();
  return ss.str();
}

} // namespace

int main(int argc, char **argv) {
  Options opt;
  std::vector<std::string> positional;

  for (int i = 1; i < argc; i++) {
    std::string a = argv[i];
    if (a == "-h") {
      usage(stdout);
      return 0;
    }
    if (a == "-v") {
      std::printf("xyz 0.1 (UQBE target %s)\n", qbe_default_target());
      return 0;
    }
    if (a == "-S") {
      opt.emit_asm = true;
      continue;
    }
    if (a == "-c") {
      opt.emit_obj = true;
      continue;
    }
    if (a == "-qbe") {
      opt.emit_il = true;
      continue;
    }
    if (a == "-run") {
      opt.run = true;
      continue;
    }
    if (a == "-keep") {
      opt.keep = true;
      continue;
    }
    if (a == "-verbose") {
      opt.verbose = true;
      continue;
    }
    if (a == "-o" || a == "-target" || a == "-cc" || a == "-runtime") {
      if (i + 1 >= argc) {
        std::fprintf(stderr, "xyz: missing value after %s\n", a.c_str());
        return 1;
      }
      std::string v = argv[++i];
      if (a == "-o")
        opt.output = v;
      else if (a == "-target")
        opt.target = v;
      else if (a == "-cc")
        opt.cc = v;
      else
        opt.runtime = v;
      continue;
    }
    if (a.size() > 2 && a[0] == '-' && a[1] == 'o')
      opt.output = a.substr(2);
    else if (a.size() > 7 && a.substr(0, 7) == "-target")
      opt.target = a.substr(7);
    else if (a.size() > 3 && a.substr(0, 3) == "-cc")
      opt.cc = a.substr(3);
    else if (a.size() > 8 && a.substr(0, 8) == "-runtime")
      opt.runtime = a.substr(8);
    else if (!a.empty() && a[0] == '-') {
      if (a.size() > 1 && a[1] == '-') {
        std::fprintf(stderr,
                     "xyz: GNU-style flag '%s' rejected; use single-dash "
                     "Plan 9 flags such as -target\n",
                     a.c_str());
        return 1;
      }
      std::fprintf(stderr, "xyz: unknown flag '%s' (try -h)\n", a.c_str());
      return 1;
    } else {
      positional.push_back(a);
    }
  }

  if (!positional.empty()) {
    const std::string &first = positional.front();
    if (first == "build" || first == "check" || first == "run" ||
        first == "qbe" || first == "asm" || first == "compile") {
      if (first == "run")
        opt.run = true;
      if (first == "qbe")
        opt.emit_il = true;
      if (first == "asm")
        opt.emit_asm = true;
      positional.erase(positional.begin());
    }
  }

  if (positional.size() != 1) {
    usage(stderr);
    return 2;
  }
  opt.input = positional[0];

  try {
    fs::path input(opt.input);
    if (!fs::is_regular_file(input))
      throw std::runtime_error("input file not found: " + opt.input);
    if (lower(input.extension().string()) != ".xyz")
      throw std::runtime_error("xyz expects a .xyz source file");

    std::string target = opt.target.empty() ? qbe_default_target()
                                            : canonical_target(opt.target);
    if (!qbe_target_supported(target.c_str()))
      throw std::runtime_error("unknown target '" + target +
                               "'; supported: " + qbe_target_list());

    std::string source = read_file(input);
    xyz::Program program = xyz::parse_program(source);
    xyz::check_program(program);
    std::string il = xyz::generate_qbe(program, input.filename().string());

    if (opt.emit_il) {
      std::string out = opt.output.empty() ? default_output(opt.input, ".ssa")
                                           : opt.output;
      if (out == "-")
        std::fwrite(il.data(), 1, il.size(), stdout);
      else {
        write_file(out, il);
        if (opt.verbose)
          std::fprintf(stderr, "xyz: wrote %s\n", out.c_str());
      }
      return 0;
    }

    fs::path tmp = make_temp_dir();
    fs::path ilpath = tmp / "unit.ssa";
    fs::path asmpath = tmp / "unit.s";
    write_file(ilpath, il);

    if (qbe_compile_file(ilpath.string().c_str(), asmpath.string().c_str(),
                         target.c_str()) != 0)
      throw std::runtime_error("UQBE failed to compile the generated IL");

    if (opt.emit_asm) {
      std::string out = opt.output.empty() ? default_output(opt.input, ".s")
                                           : opt.output;
      if (out == "-")
        std::fputs(read_file(asmpath).c_str(), stdout);
      else
        fs::copy_file(asmpath, out, fs::copy_options::overwrite_existing);
      if (opt.keep)
        std::fprintf(stderr, "xyz: kept %s\n", tmp.string().c_str());
      else
        fs::remove_all(tmp);
      return 0;
    }

    std::string cc = find_cc(opt);
    fs::path exe_dir = executable_dir(argv[0]);
    std::string runtime = find_runtime(opt, exe_dir);

    if (opt.emit_obj) {
      std::string out = opt.output.empty() ? default_output(opt.input, ".o")
                                           : opt.output;
      std::vector<std::string> cmd = {cc, "-c", asmpath.string(), "-o", out};
      int rc = run_tool(cmd, opt.verbose);
      if (rc != 0)
        throw std::runtime_error("assembler failed");
      if (opt.keep)
        std::fprintf(stderr, "xyz: kept %s\n", tmp.string().c_str());
      else
        fs::remove_all(tmp);
      return 0;
    }

    std::string out = opt.output;
    if (out.empty()) {
      out = default_output(opt.input, "");
#if defined(_WIN32)
      if (fs::path(out).extension().empty())
        out += ".exe";
#endif
    }

    std::vector<std::string> cmd = {cc, asmpath.string(), runtime, "-o", out};
    int rc = run_tool(cmd, opt.verbose);
    if (rc != 0)
      throw std::runtime_error("linker failed");

    if (opt.keep)
      std::fprintf(stderr, "xyz: kept %s\n", tmp.string().c_str());
    else
      fs::remove_all(tmp);

    if (opt.run) {
      std::string runpath = out;
#if !defined(_WIN32)
      if (runpath.find('/') == std::string::npos)
        runpath = "./" + runpath;
#endif
      return run_tool({runpath}, opt.verbose);
    }
    return 0;
  } catch (const xyz::Error &e) {
    std::fprintf(stderr, "%s\n", format_error(opt.input, e).c_str());
    return 1;
  } catch (const std::exception &e) {
    std::fprintf(stderr, "xyz: %s\n", e.what());
    return 1;
  }
}