v / cmd / tools / translate.v
70 lines · 65 sloc · 1.97 KB · b6314dba313b330fa5eec98ad9b958bee1da70cd
Raw
1// Copyright (c) 2019-2023 Alexander Medvednikov. All rights reserved.
2// Use of this source code is governed by an MIT license that can be found in the LICENSE file.
3module main
4
5import os
6import v.util
7
8const vexe = os.getenv('VEXE')
9
10fn normalize_translate_args(args []string) []string {
11 if args.len > 0 && args[0] == '-wrapper' {
12 mut normalized := []string{cap: args.len}
13 normalized << 'wrapper'
14 normalized << args[1..]
15 return normalized
16 }
17 return args.clone()
18}
19
20fn show_usage_and_exit() {
21 eprintln('Wrong number of arguments. Use `v translate file.c` or `v translate wrapper file.c`.')
22 exit(3)
23}
24
25fn main() {
26 vmodules := os.vmodules_dir()
27 c2v_dir := os.join_path(vmodules, 'c2v')
28 mut c2v_bin := os.join_path(c2v_dir, 'c2v')
29 $if windows {
30 c2v_bin += '.exe'
31 }
32 // Git clone c2v
33 if !os.exists(c2v_dir) {
34 os.mkdir_all(vmodules)!
35 println('C2V is not installed. Cloning C2V to ${c2v_dir} ...')
36 os.chdir(vmodules)!
37 res :=
38 os.execute('${os.quoted_path(vexe)} retry -- git clone --filter=blob:none https://github.com/vlang/c2v')
39 if res.exit_code != 0 {
40 eprintln('Failed to download C2V.')
41 exit(1)
42 }
43 }
44 // Compile c2v
45 if !os.exists(c2v_bin) {
46 os.chdir(c2v_dir)!
47 println('Compiling c2v ...')
48 res2 :=
49 os.execute('${os.quoted_path(vexe)} -o ${os.quoted_path(c2v_bin)} -keepc -g -experimental .')
50 if res2.exit_code != 0 {
51 eprintln(res2.output)
52 eprintln('Failed to compile C2V. This should not happen. Please report it via GitHub.')
53 exit(2)
54 }
55 }
56 translate_args := normalize_translate_args(os.args[2..])
57 if translate_args.len == 0 || (translate_args.len == 1 && translate_args[0] == 'wrapper') {
58 show_usage_and_exit()
59 }
60 passed_args := util.args_quote_paths(translate_args)
61 // println(passed_args)
62 os.chdir(os.wd_at_startup)!
63 c2v_cmd := '${os.quoted_path(c2v_bin)} ${passed_args}'
64 res := os.system(c2v_cmd)
65 if res != 0 {
66 eprintln('C2V command: ${c2v_cmd}')
67 eprintln('C2V failed to translate the C files. Please report it via GitHub.')
68 exit(4)
69 }
70}
71