1use annotate_snippets::{
3 renderer::{AnsiColor, Style},
4 Annotation, AnnotationType, Renderer, Slice, Snippet, SourceAnnotation,
5};
6use anyhow::{bail, Context, Result};
7use forc_tracing::{println_action_green, println_error, println_red_err, println_yellow_err};
8use std::{
9 collections::{hash_map, HashSet},
10 fmt::Display,
11 fs::File,
12 hash::{Hash, Hasher},
13 path::{Path, PathBuf},
14 process::Termination,
15 str,
16};
17use sway_core::language::parsed::TreeType;
18use sway_error::{
19 diagnostic::{Diagnostic, Issue, Label, LabelType, Level, ToDiagnostic},
20 error::CompileError,
21 warning::CompileWarning,
22};
23use sway_types::{LineCol, LineColRange, SourceEngine, Span};
24use sway_utils::constants;
25
26pub mod bytecode;
27pub mod fs_locking;
28pub mod restricted;
29#[cfg(feature = "tx")]
30pub mod tx_utils;
31
32#[macro_use]
33pub mod cli;
34
35pub use ansiterm;
36pub use paste;
37pub use regex::Regex;
38
39pub const DEFAULT_OUTPUT_DIRECTORY: &str = "out";
40pub const DEFAULT_ERROR_EXIT_CODE: u8 = 1;
41pub const DEFAULT_SUCCESS_EXIT_CODE: u8 = 0;
42
43pub type ForcResult<T, E = ForcError> = Result<T, E>;
46
47#[derive(Debug)]
50pub struct ForcCliResult<T> {
51 result: ForcResult<T>,
52}
53
54#[derive(Debug)]
57pub struct ForcError {
58 error: anyhow::Error,
59 exit_code: u8,
60}
61
62impl ForcError {
63 pub fn new(error: anyhow::Error, exit_code: u8) -> Self {
64 Self { error, exit_code }
65 }
66
67 pub fn exit_code(self, exit_code: u8) -> Self {
69 Self {
70 error: self.error,
71 exit_code,
72 }
73 }
74}
75
76impl AsRef<anyhow::Error> for ForcError {
77 fn as_ref(&self) -> &anyhow::Error {
78 &self.error
79 }
80}
81
82impl From<&str> for ForcError {
83 fn from(value: &str) -> Self {
84 Self {
85 error: anyhow::anyhow!("{value}"),
86 exit_code: DEFAULT_ERROR_EXIT_CODE,
87 }
88 }
89}
90
91impl From<anyhow::Error> for ForcError {
92 fn from(value: anyhow::Error) -> Self {
93 Self {
94 error: value,
95 exit_code: DEFAULT_ERROR_EXIT_CODE,
96 }
97 }
98}
99
100impl From<std::io::Error> for ForcError {
101 fn from(value: std::io::Error) -> Self {
102 Self {
103 error: value.into(),
104 exit_code: DEFAULT_ERROR_EXIT_CODE,
105 }
106 }
107}
108
109impl Display for ForcError {
110 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111 self.error.fmt(f)
112 }
113}
114
115impl<T> Termination for ForcCliResult<T> {
116 fn report(self) -> std::process::ExitCode {
117 match self.result {
118 Ok(_) => DEFAULT_SUCCESS_EXIT_CODE.into(),
119 Err(e) => {
120 println_error(&format!("{}", e));
121 e.exit_code.into()
122 }
123 }
124 }
125}
126
127impl<T> From<ForcResult<T>> for ForcCliResult<T> {
128 fn from(value: ForcResult<T>) -> Self {
129 Self { result: value }
130 }
131}
132
133#[macro_export]
134macro_rules! forc_result_bail {
135 ($msg:literal $(,)?) => {
136 return $crate::ForcResult::Err(anyhow::anyhow!($msg).into())
137 };
138 ($err:expr $(,)?) => {
139 return $crate::ForcResult::Err(anyhow::anyhow!($err).into())
140 };
141 ($fmt:expr, $($arg:tt)*) => {
142 return $crate::ForcResult::Err(anyhow::anyhow!($fmt, $($arg)*).into())
143 };
144}
145
146pub fn find_file_name<'sc>(manifest_dir: &Path, entry_path: &'sc Path) -> Result<&'sc Path> {
147 let mut file_path = manifest_dir.to_path_buf();
148 file_path.pop();
149 let file_name = match entry_path.strip_prefix(file_path.clone()) {
150 Ok(o) => o,
151 Err(err) => bail!(err),
152 };
153 Ok(file_name)
154}
155
156pub fn lock_path(manifest_dir: &Path) -> PathBuf {
157 manifest_dir.join(constants::LOCK_FILE_NAME)
158}
159
160pub fn validate_project_name(name: &str) -> Result<()> {
161 restricted::is_valid_project_name_format(name)?;
162 validate_name(name, "project name")
163}
164
165pub fn validate_name(name: &str, use_case: &str) -> Result<()> {
169 restricted::contains_invalid_char(name, use_case)?;
171
172 if restricted::is_keyword(name) {
173 bail!("the name `{name}` cannot be used as a {use_case}, it is a Sway keyword");
174 }
175 if restricted::is_conflicting_artifact_name(name) {
176 bail!(
177 "the name `{name}` cannot be used as a {use_case}, \
178 it conflicts with Forc's build directory names"
179 );
180 }
181 if name.to_lowercase() == "test" {
182 bail!(
183 "the name `test` cannot be used as a {use_case}, \
184 it conflicts with Sway's built-in test library"
185 );
186 }
187 if restricted::is_conflicting_suffix(name) {
188 bail!(
189 "the name `{name}` is part of Sway's standard library\n\
190 It is recommended to use a different name to avoid problems."
191 );
192 }
193 if restricted::is_windows_reserved(name) {
194 if cfg!(windows) {
195 bail!("cannot use name `{name}`, it is a reserved Windows filename");
196 } else {
197 bail!(
198 "the name `{name}` is a reserved Windows filename\n\
199 This package will not work on Windows platforms."
200 );
201 }
202 }
203 if restricted::is_non_ascii_name(name) {
204 bail!("the name `{name}` contains non-ASCII characters which are unsupported");
205 }
206 Ok(())
207}
208
209pub fn kebab_to_snake_case(s: &str) -> String {
211 s.replace('-', "_")
212}
213
214pub fn default_output_directory(manifest_dir: &Path) -> PathBuf {
215 manifest_dir.join(DEFAULT_OUTPUT_DIRECTORY)
216}
217
218pub fn user_forc_directory() -> PathBuf {
220 dirs::home_dir()
221 .expect("unable to find the user home directory")
222 .join(constants::USER_FORC_DIRECTORY)
223}
224
225pub fn git_checkouts_directory() -> PathBuf {
227 user_forc_directory().join("git").join("checkouts")
228}
229
230fn fd_lock_path<X: AsRef<Path>>(path: X) -> PathBuf {
240 const LOCKS_DIR_NAME: &str = ".locks";
241 const LOCK_EXT: &str = "forc-lock";
242 let file_name = hash_path(path);
243 user_forc_directory()
244 .join(LOCKS_DIR_NAME)
245 .join(file_name)
246 .with_extension(LOCK_EXT)
247}
248
249fn hash_path<X: AsRef<Path>>(path: X) -> String {
252 let path = path.as_ref();
253 let mut hasher = hash_map::DefaultHasher::default();
254 path.hash(&mut hasher);
255 let hash = hasher.finish();
256 let file_name = match path.file_stem().and_then(|s| s.to_str()) {
257 None => format!("{hash:X}"),
258 Some(stem) => format!("{hash:X}-{stem}"),
259 };
260 file_name
261}
262
263pub fn path_lock<X: AsRef<Path>>(path: X) -> Result<fd_lock::RwLock<File>> {
267 let lock_path = fd_lock_path(path);
268 let lock_dir = lock_path
269 .parent()
270 .expect("lock path has no parent directory");
271 std::fs::create_dir_all(lock_dir).context("failed to create forc advisory lock directory")?;
272 let lock_file = File::create(&lock_path).context("failed to create advisory lock file")?;
273 Ok(fd_lock::RwLock::new(lock_file))
274}
275
276pub fn program_type_str(ty: &TreeType) -> &'static str {
277 match ty {
278 TreeType::Script => "script",
279 TreeType::Contract => "contract",
280 TreeType::Predicate => "predicate",
281 TreeType::Library => "library",
282 }
283}
284
285pub fn print_compiling(ty: Option<&TreeType>, name: &str, src: &dyn std::fmt::Display) {
286 let ty = match ty {
289 Some(ty) => format!("{} ", program_type_str(ty)),
290 None => "".to_string(),
291 };
292 println_action_green(
293 "Compiling",
294 &format!("{ty}{} ({src})", ansiterm::Style::new().bold().paint(name)),
295 );
296}
297
298pub fn print_warnings(
299 source_engine: &SourceEngine,
300 terse_mode: bool,
301 proj_name: &str,
302 warnings: &[CompileWarning],
303 tree_type: &TreeType,
304) {
305 if warnings.is_empty() {
306 return;
307 }
308 let type_str = program_type_str(tree_type);
309
310 if !terse_mode {
311 warnings
312 .iter()
313 .for_each(|w| format_diagnostic(&w.to_diagnostic(source_engine)));
314 }
315
316 println_yellow_err(&format!(
317 " Compiled {} {:?} with {} {}.",
318 type_str,
319 proj_name,
320 warnings.len(),
321 if warnings.len() > 1 {
322 "warnings"
323 } else {
324 "warning"
325 }
326 ));
327}
328
329pub fn print_on_failure(
330 source_engine: &SourceEngine,
331 terse_mode: bool,
332 warnings: &[CompileWarning],
333 errors: &[CompileError],
334 reverse_results: bool,
335) {
336 let e_len = errors.len();
337 let w_len = warnings.len();
338
339 if !terse_mode {
340 if reverse_results {
341 warnings
342 .iter()
343 .rev()
344 .for_each(|w| format_diagnostic(&w.to_diagnostic(source_engine)));
345 errors
346 .iter()
347 .rev()
348 .for_each(|e| format_diagnostic(&e.to_diagnostic(source_engine)));
349 } else {
350 warnings
351 .iter()
352 .for_each(|w| format_diagnostic(&w.to_diagnostic(source_engine)));
353 errors
354 .iter()
355 .for_each(|e| format_diagnostic(&e.to_diagnostic(source_engine)));
356 }
357 }
358
359 if e_len == 0 && w_len > 0 {
360 println_red_err(&format!(
361 " Aborting. {} warning(s) treated as error(s).",
362 warnings.len()
363 ));
364 } else {
365 println_red_err(&format!(
366 " Aborting due to {} {}.",
367 e_len,
368 if e_len > 1 { "errors" } else { "error" }
369 ));
370 }
371}
372
373pub fn create_diagnostics_renderer() -> Renderer {
378 Renderer::styled()
382 .warning(
383 Style::new()
384 .bold()
385 .fg_color(Some(AnsiColor::BrightYellow.into())),
386 )
387 .error(
388 Style::new()
389 .bold()
390 .fg_color(Some(AnsiColor::BrightRed.into())),
391 )
392}
393
394pub fn format_diagnostic(diagnostic: &Diagnostic) {
395 const SHOW_DIAGNOSTIC_CODE: bool = false;
398
399 if diagnostic.is_old_style() {
400 format_old_style_diagnostic(diagnostic.issue());
401 return;
402 }
403
404 let mut label = String::new();
405 get_title_label(diagnostic, &mut label);
406
407 let snippet_title = Some(Annotation {
408 label: Some(label.as_str()),
409 id: if SHOW_DIAGNOSTIC_CODE {
410 diagnostic.reason().map(|reason| reason.code())
411 } else {
412 None
413 },
414 annotation_type: diagnostic_level_to_annotation_type(diagnostic.level()),
415 });
416
417 let mut snippet_slices = Vec::<Slice<'_>>::new();
418
419 if diagnostic.issue().is_in_source() {
421 snippet_slices.push(construct_slice(diagnostic.labels_in_issue_source()))
422 }
423
424 for source_path in diagnostic.related_sources(false) {
426 snippet_slices.push(construct_slice(diagnostic.labels_in_source(source_path)))
427 }
428
429 let mut snippet_footer = Vec::<Annotation<'_>>::new();
430 for help in diagnostic.help() {
431 snippet_footer.push(Annotation {
432 id: None,
433 label: Some(help),
434 annotation_type: AnnotationType::Help,
435 });
436 }
437
438 let snippet = Snippet {
439 title: snippet_title,
440 slices: snippet_slices,
441 footer: snippet_footer,
442 };
443
444 let renderer = create_diagnostics_renderer();
445 match diagnostic.level() {
446 Level::Info => tracing::info!("{}\n____\n", renderer.render(snippet)),
447 Level::Warning => tracing::warn!("{}\n____\n", renderer.render(snippet)),
448 Level::Error => tracing::error!("{}\n____\n", renderer.render(snippet)),
449 }
450
451 fn format_old_style_diagnostic(issue: &Issue) {
452 let annotation_type = label_type_to_annotation_type(issue.label_type());
453
454 let snippet_title = Some(Annotation {
455 label: if issue.is_in_source() {
456 None
457 } else {
458 Some(issue.text())
459 },
460 id: None,
461 annotation_type,
462 });
463
464 let mut snippet_slices = vec![];
465 if issue.is_in_source() {
466 let span = issue.span();
467 let input = span.input();
468 let mut start_pos = span.start();
469 let mut end_pos = span.end();
470 let LineColRange { mut start, end } = span.line_col_one_index();
471 let input = construct_window(&mut start, end, &mut start_pos, &mut end_pos, input);
472
473 let slice = Slice {
474 source: input,
475 line_start: start.line,
476 origin: Some(issue.source_path().unwrap().as_str()),
478 fold: false,
479 annotations: vec![SourceAnnotation {
480 label: issue.text(),
481 annotation_type,
482 range: (start_pos, end_pos),
483 }],
484 };
485
486 snippet_slices.push(slice);
487 }
488
489 let snippet = Snippet {
490 title: snippet_title,
491 footer: vec![],
492 slices: snippet_slices,
493 };
494
495 let renderer = create_diagnostics_renderer();
496 tracing::error!("{}\n____\n", renderer.render(snippet));
497 }
498
499 fn get_title_label(diagnostics: &Diagnostic, label: &mut String) {
500 label.clear();
501 if let Some(reason) = diagnostics.reason() {
502 label.push_str(reason.description());
503 }
504 }
505
506 fn diagnostic_level_to_annotation_type(level: Level) -> AnnotationType {
507 match level {
508 Level::Info => AnnotationType::Info,
509 Level::Warning => AnnotationType::Warning,
510 Level::Error => AnnotationType::Error,
511 }
512 }
513}
514
515fn construct_slice(labels: Vec<&Label>) -> Slice {
516 debug_assert!(
517 !labels.is_empty(),
518 "To construct slices, at least one label must be provided."
519 );
520
521 debug_assert!(
522 labels.iter().all(|label| label.is_in_source()),
523 "Slices can be constructed only for labels that are related to a place in source code."
524 );
525
526 debug_assert!(
527 HashSet::<&str>::from_iter(labels.iter().map(|label| label.source_path().unwrap().as_str())).len() == 1,
528 "Slices can be constructed only for labels that are related to places in the same source code."
529 );
530
531 let source_file = labels[0].source_path().map(|path| path.as_str());
532 let source_code = labels[0].span().input();
533
534 let span = Span::join_all(labels.iter().map(|label| label.span().clone()));
536
537 let (source, line_start, shift_in_bytes) = construct_code_snippet(&span, source_code);
538
539 let mut annotations = vec![];
540
541 for message in labels {
542 annotations.push(SourceAnnotation {
543 label: message.text(),
544 annotation_type: label_type_to_annotation_type(message.label_type()),
545 range: get_annotation_range(message.span(), source_code, shift_in_bytes),
546 });
547 }
548
549 return Slice {
550 source,
551 line_start,
552 origin: source_file,
553 fold: true,
554 annotations,
555 };
556
557 fn get_annotation_range(
558 span: &Span,
559 source_code: &str,
560 shift_in_bytes: usize,
561 ) -> (usize, usize) {
562 let mut start_pos = span.start();
563 let mut end_pos = span.end();
564
565 let start_ix_bytes = start_pos - std::cmp::min(shift_in_bytes, start_pos);
566 let end_ix_bytes = end_pos - std::cmp::min(shift_in_bytes, end_pos);
567
568 start_pos = source_code[shift_in_bytes..(shift_in_bytes + start_ix_bytes)]
570 .chars()
571 .count();
572 end_pos = source_code[shift_in_bytes..(shift_in_bytes + end_ix_bytes)]
573 .chars()
574 .count();
575
576 (start_pos, end_pos)
577 }
578}
579
580fn label_type_to_annotation_type(label_type: LabelType) -> AnnotationType {
581 match label_type {
582 LabelType::Info => AnnotationType::Info,
583 LabelType::Help => AnnotationType::Help,
584 LabelType::Warning => AnnotationType::Warning,
585 LabelType::Error => AnnotationType::Error,
586 }
587}
588
589fn construct_code_snippet<'a>(span: &Span, input: &'a str) -> (&'a str, usize, usize) {
598 const NUM_LINES_BUFFER: usize = 2;
600
601 let LineColRange { start, end } = span.line_col_one_index();
602
603 let total_lines_in_input = input.chars().filter(|x| *x == '\n').count();
604 debug_assert!(end.line >= start.line);
605 let total_lines_of_highlight = end.line - start.line;
606 debug_assert!(total_lines_in_input >= total_lines_of_highlight);
607
608 let mut current_line = 0;
609 let mut lines_to_start_of_snippet = 0;
610 let mut calculated_start_ix = None;
611 let mut calculated_end_ix = None;
612 let mut pos = 0;
613 for character in input.chars() {
614 if character == '\n' {
615 current_line += 1
616 }
617
618 if current_line + NUM_LINES_BUFFER >= start.line && calculated_start_ix.is_none() {
619 calculated_start_ix = Some(pos);
620 lines_to_start_of_snippet = current_line;
621 }
622
623 if current_line >= end.line + NUM_LINES_BUFFER && calculated_end_ix.is_none() {
624 calculated_end_ix = Some(pos);
625 }
626
627 if calculated_start_ix.is_some() && calculated_end_ix.is_some() {
628 break;
629 }
630 pos += character.len_utf8();
631 }
632 let calculated_start_ix = calculated_start_ix.unwrap_or(0);
633 let calculated_end_ix = calculated_end_ix.unwrap_or(input.len());
634
635 (
636 &input[calculated_start_ix..calculated_end_ix],
637 lines_to_start_of_snippet,
638 calculated_start_ix,
639 )
640}
641
642fn construct_window<'a>(
651 start: &mut LineCol,
652 end: LineCol,
653 start_ix: &mut usize,
654 end_ix: &mut usize,
655 input: &'a str,
656) -> &'a str {
657 const NUM_LINES_BUFFER: usize = 2;
659
660 let total_lines_in_input = input.chars().filter(|x| *x == '\n').count();
661 debug_assert!(end.line >= start.line);
662 let total_lines_of_highlight = end.line - start.line;
663 debug_assert!(total_lines_in_input >= total_lines_of_highlight);
664
665 let mut current_line = 1usize;
666
667 let mut chars = input.char_indices().map(|(char_offset, character)| {
668 let r = (current_line, char_offset);
669 if character == '\n' {
670 current_line += 1;
671 }
672 r
673 });
674
675 let first_char = chars
677 .by_ref()
678 .find(|(current_line, _)| current_line + NUM_LINES_BUFFER >= start.line);
679
680 let last_char = chars
682 .by_ref()
683 .find(|(current_line, _)| *current_line > end.line + NUM_LINES_BUFFER)
684 .map(|x| x.1);
685
686 drop(chars);
688
689 let (first_char_line, first_char_offset, last_char_offset) = match (first_char, last_char) {
690 (Some((first_char_line, first_char_offset)), Some(last_char_offset)) => {
692 (first_char_line, first_char_offset, last_char_offset)
693 }
694 (Some((first_char_line, first_char_offset)), None) => {
696 (first_char_line, first_char_offset, input.len())
697 }
698 _ => (current_line, input.len(), input.len()),
700 };
701
702 start.line = first_char_line;
704 *start_ix = start_ix.saturating_sub(first_char_offset);
705 *end_ix = end_ix.saturating_sub(first_char_offset);
706
707 &input[first_char_offset..last_char_offset]
708}
709
710#[test]
711fn ok_construct_window() {
712 fn t(
713 start_line: usize,
714 start_col: usize,
715 end_line: usize,
716 end_col: usize,
717 start_char: usize,
718 end_char: usize,
719 input: &str,
720 ) -> (usize, usize, &str) {
721 let mut s = LineCol {
722 line: start_line,
723 col: start_col,
724 };
725 let mut start = start_char;
726 let mut end = end_char;
727 let r = construct_window(
728 &mut s,
729 LineCol {
730 line: end_line,
731 col: end_col,
732 },
733 &mut start,
734 &mut end,
735 input,
736 );
737 (start, end, r)
738 }
739
740 assert_eq!(t(0, 0, 0, 0, 0, 0, ""), (0, 0, ""));
742
743 assert_eq!(t(1, 1, 1, 1, 0, 0, ""), (0, 0, ""));
745
746 assert_eq!(t(1, 7, 1, 7, 6, 6, "script"), (6, 6, "script"));
748
749 let eight_lines = "1\n2\n3\n4\n5\n6\n7\n8";
751
752 assert_eq!(t(1, 1, 1, 1, 0, 1, eight_lines), (0, 1, "1\n2\n3\n"));
753 assert_eq!(t(2, 1, 2, 1, 2, 3, eight_lines), (2, 3, "1\n2\n3\n4\n"));
754 assert_eq!(t(3, 1, 3, 1, 4, 5, eight_lines), (4, 5, "1\n2\n3\n4\n5\n"));
755 assert_eq!(t(4, 1, 4, 1, 6, 7, eight_lines), (4, 5, "2\n3\n4\n5\n6\n"));
756 assert_eq!(t(5, 1, 5, 1, 8, 9, eight_lines), (4, 5, "3\n4\n5\n6\n7\n"));
757 assert_eq!(t(6, 1, 6, 1, 10, 11, eight_lines), (4, 5, "4\n5\n6\n7\n8"));
758 assert_eq!(t(7, 1, 7, 1, 12, 13, eight_lines), (4, 5, "5\n6\n7\n8"));
759 assert_eq!(t(8, 1, 8, 1, 14, 15, eight_lines), (4, 5, "6\n7\n8"));
760
761 assert_eq!(t(9, 1, 9, 1, 14, 15, eight_lines), (2, 3, "7\n8"));
763 assert_eq!(t(10, 1, 10, 1, 14, 15, eight_lines), (0, 1, "8"));
764 assert_eq!(t(11, 1, 11, 1, 14, 15, eight_lines), (0, 0, ""));
765}