aboutsummaryrefslogtreecommitdiff
path: root/crates/divina_compile/src/lib.rs
blob: 70664faee115e8b644b24aa65ee902fb10ffc895 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
// Copyright (C) 2022-2022 Fuwn <[email protected]>
// SPDX-License-Identifier: GPL-3.0-only

#![feature(stmt_expr_attributes)]
#![deny(
  warnings,
  nonstandard_style,
  unused,
  future_incompatible,
  rust_2018_idioms,
  unsafe_code
)]
#![deny(clippy::all, clippy::nursery, clippy::pedantic)]
#![recursion_limit = "128"]
#![doc(
  html_logo_url = "https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/160/twitter/282/ribbon_1f380.png",
  html_favicon_url = "https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/160/twitter/282/ribbon_1f380.png"
)]

use std::{fs, process::Command};

use divina_config::Arch;

#[derive(Debug)]
struct Source {
  filename: String,
  path:     String,
}

#[derive(Debug)]
struct Package {
  name:     String,
  sources:  Vec<Source>,
  arch:     Arch,
  compiler: String,
}

#[derive(Default, Debug)]
pub struct Compiler {
  sources:    Vec<Package>,
  is_package: bool,
}
impl Compiler {
  #[must_use]
  pub fn new() -> Self { Self::default() }

  pub fn find_sources(&mut self, config: &divina_config::Config) -> &Self {
    if config.config_type == divina_config::ConfigType::Workspace {
      for member in config.members.as_ref().expect(
        "!! could not access 'Config.members' from `workspace`, this *shouldn't* be possible",
      ) {
        let mut package = Package {
          name:     member.name.clone().expect(
            "!! could not access `Config.?.name` from `workspace`, this *shouldn't* be possible",
          ),
          sources:  Vec::new(),
          arch:     member
            .arch
            .clone()
            .expect("!! could not access 'Config.members.?.arch', this *shouldn't* be possible"),
          compiler: member
            .compiler
            .clone()
            .unwrap_or_else(|| "yasm".to_string()),
        };

        member
          .sources
          .as_ref()
          .expect(
            "!! could not access 'Config.sources' from 'workspace.members', this *shouldn't* be \
             possible",
          )
          .iter()
          .for_each(|source| {
            if !source.is_empty() {
              package.sources.push(Source {
                path:     format!(
                  "{}/{}",
                  member.path.as_ref().expect(
                    "!! could not access 'Config.members.?.path', this *shouldn't* be possible"
                  ),
                  source
                ),
                filename: {
                  let mut sources = source.split('.');
                  // Remove the file extension
                  sources.next_back();

                  sources.collect()
                },
              });
            }
          });

        self.sources.push(package);
      }
    } else {
      let mut package = Package {
        name:     config
          .name
          .clone()
          .expect("!! could not access `Config.name` from `Package`, this *shouldn't* be possible"),
        sources:  Vec::new(),
        arch:     config
          .arch
          .clone()
          .expect("!! could not access 'Config.arch', this *shouldn't* be possible"),
        compiler: if config.compiler.is_some() {
          config
            .compiler
            .clone()
            .expect("!! could not access 'Config.compiler', this *shouldn't be possible")
        } else {
          "yasm".to_string()
        },
      };

      config
        .sources
        .as_ref()
        .expect("!! could not access 'Config.sources' from 'Package', this *shouldn't* be possible")
        .iter()
        .for_each(|source| {
          if !source.is_empty() {
            package.sources.push(Source {
              path:     source.to_string(),
              filename: {
                let mut sources = source.split('.');
                // Remove the file extension
                sources.next_back();

                let sources_no_extension = sources.collect::<String>();
                sources = sources_no_extension.split('/');

                sources
                  .next_back()
                  .expect("!! could not get filename from source, this is an anomaly")
                  .to_string()
              },
            });
          }
        });

      self.sources.push(package);
    }

    self.is_package = self.sources.len() == 1;

    self
  }

  /// # Panics
  /// if caller has insufficient permissions to create a directory
  #[must_use]
  pub fn compile(&self) -> &Self {
    if !std::path::Path::new("out/").exists() {
      println!(":: creating directory 'out/'");
      fs::create_dir_all("out/").expect("!! could not create directory 'out/', check permissions");
    }

    for package in &self.sources {
      let package_out_directory = if self.is_package {
        "out/".to_string()
      } else {
        format!("out/{}/", package.name)
      };

      if !std::path::Path::new(&package_out_directory).exists() {
        println!(
          ":: {} @@ creating directory '{}'",
          package.name, package_out_directory
        );
        fs::create_dir_all(&package_out_directory).unwrap_or_else(|_| {
          panic!(
            "!! could not create directory '{}', check permissions",
            package_out_directory
          )
        });
      }

      for source in &package.sources {
        println!(
          ":: {} @@ {} ?? compiling source '{}'",
          package.name, package.compiler, source.path
        );

        #[cfg(unix)]
        Command::new(&package.compiler)
          .args([
            "-f",
            if package.arch == Arch::X86 {
              "elf32"
            } else {
              "elf64"
            },
            &source.path,
            "-o",
            if self.is_package {
              &format!("out/{}.o", source.filename)
            } else {
              &format!("out/{}/{}.o", package.name, source.filename)
            },
          ])
          .output()
          .expect(&format!(
            "!! failed to call command `{}` in `Compiler.compile`",
            package.compiler
          ));

        #[cfg(windows)]
        Command::new(&package.compiler)
          .args([
            "-f",
            if package.arch == Arch::X86 {
              "win32"
            } else {
              "win64"
            },
            &source.path,
            "-o",
            &if self.is_package {
              format!("out/{}.obj", source.filename)
            } else {
              format!("out/{}/{}.obj", package.name, source.filename)
            },
          ])
          .output()
          .unwrap_or_else(|_| {
            panic!(
              "!! failed to call command `{}` in `Compiler.compile`",
              package.compiler
            )
          });
      }
    }

    self
  }

  /// # Panics
  /// if Visual Studio 2019 is not installed
  pub fn link(&self) {
    for package in &self.sources {
      let mut filenames = Vec::new();
      #[allow(unused)]
      let mut arch = &Arch::X86;

      for source in &package.sources {
        filenames.push(format!(
          "out/{}{}.{}",
          &if self.is_package {
            "".to_string()
          } else {
            format!("{}/", &package.name)
          },
          source.filename,
          {
            if cfg!(windows) {
              "obj"
            } else {
              "o"
            }
          }
        ));

        #[allow(unused)]
        arch = &package.arch;
      }

      #[cfg(windows)]
      println!(
        ":: {} @@ entering visual studio 2019 developer command prompt environment",
        package.name
      );

      println!(
        ":: {} @@ linking source{}: '{}'",
        package.name,
        if filenames.len() > 1 { "s" } else { "" },
        filenames.join("', '")
      );

      #[cfg(unix)]
      {
        Command::new("ld")
          .args([
            "-dynamic-linker",
            "/lib64/ld-linux-x86-64.so.2",
            "-lc",
            "-o",
            if self.is_package {
              &format!("out/{}", package.name)
            } else {
              &format!("out/{}/{}", package.name, package.name)
            },
          ])
          .args(filenames.iter())
          .output()
          .expect("!! failed to call command `ld` in `Compiler.link`");
      }

      #[cfg(windows)]
      {
        if arch == &Arch::X64 {
          if self.is_package {
            windows::link_package_64(&filenames.join(" "), &package.name);
          } else {
            windows::link_workspace_64(&filenames.join(" "), &package.name);
          }
        } else if self.is_package {
          windows::link_package_32(&filenames.join(" "), &package.name);
        } else {
          windows::link_workspace_32(&filenames.join(" "), &package.name);
        }
      }
    }
  }

  #[must_use]
  pub fn print_config(&self) -> &Self {
    println!("{:?}", self);

    self
  }
}

#[cfg(windows)]
#[rustfmt::skip] // Preserve raw string literal positions
mod windows {
  /// Thank lord for the [shellfn](https://github.com/synek317/shellfn) crate...
  ///
  /// I unironically spent **SIX** hours -- give or take a few minutes... --
  /// trying to get the Windows linker working. After searching far and wide,
  /// the shellfn crate happened to come up in my search results after a
  /// random search, and it worked!
  ///
  /// Thanks, shellfn.
  #[shellfn::shell(cmd = "powershell")]
  pub fn link_workspace_32(objects: &str, filename: &str) -> String { r#"
    "link /subsystem:console /out:out/$FILENAME/$FILENAME.exe $OBJECTS kernel32.lib msvcrt.lib legacy_stdio_definitions.lib" | cmd /k "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars32.bat"
  "# }
  #[shellfn::shell(cmd = "powershell")]
  pub fn link_workspace_64(objects: &str, filename: &str) -> String { r#"
    "link /subsystem:console /out:out/$FILENAME/$FILENAME.exe $OBJECTS kernel32.lib msvcrt.lib legacy_stdio_definitions.lib" | cmd /k "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat"
  "# }
  #[shellfn::shell(cmd = "powershell")]
  pub fn link_package_32(objects: &str, filename: &str) -> String { r#"
    "link /subsystem:console /out:out/$FILENAME.exe $OBJECTS kernel32.lib msvcrt.lib legacy_stdio_definitions.lib" | cmd /k "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars32.bat"
  "# }
  #[shellfn::shell(cmd = "powershell")]
  pub fn link_package_64(objects: &str, filename: &str) -> String { r#"
    "link /subsystem:console /out:out/$FILENAME.exe $OBJECTS kernel32.lib msvcrt.lib legacy_stdio_definitions.lib" | cmd /k "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat"
  "# }
}