-
-
Notifications
You must be signed in to change notification settings - Fork 811
/
Copy patherror.rs
4029 lines (3638 loc) · 151 KB
/
error.rs
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![allow(clippy::unwrap_used, clippy::expect_used)]
use crate::build::{Outcome, Runtime, Target};
use crate::diagnostic::{Diagnostic, ExtraLabel, Label, Location};
use crate::type_::error::{
MissingAnnotation, ModuleValueUsageContext, Named, UnknownField, UnknownTypeHint,
UnsafeRecordUpdateReason,
};
use crate::type_::printer::{Names, Printer};
use crate::type_::{error::PatternMatchKind, FieldAccessUsage};
use crate::{ast::BinOp, parse::error::ParseErrorType, type_::Type};
use crate::{bit_array, diagnostic::Level, javascript, type_::UnifyErrorSituation};
use ecow::EcoString;
use heck::{ToSnakeCase, ToTitleCase, ToUpperCamelCase};
use hexpm::version::ResolutionError;
use itertools::Itertools;
use pubgrub::package::Package;
use pubgrub::report::DerivationTree;
use pubgrub::version::Version;
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::env;
use std::fmt::{Debug, Display};
use std::io::Write;
use std::path::PathBuf;
use termcolor::Buffer;
use thiserror::Error;
use vec1::Vec1;
use camino::{Utf8Path, Utf8PathBuf};
pub type Name = EcoString;
pub type Result<Ok, Err = Error> = std::result::Result<Ok, Err>;
macro_rules! wrap_format {
($($tts:tt)*) => {
wrap(&format!($($tts)*))
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct UnknownImportDetails {
pub module: Name,
pub location: crate::ast::SrcSpan,
pub path: Utf8PathBuf,
pub src: EcoString,
pub modules: Vec<EcoString>,
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ImportCycleLocationDetails {
pub location: crate::ast::SrcSpan,
pub path: Utf8PathBuf,
pub src: EcoString,
}
#[derive(Debug, Eq, PartialEq, Error, Clone)]
pub enum Error {
#[error("failed to parse Gleam source code")]
Parse {
path: Utf8PathBuf,
src: EcoString,
error: crate::parse::error::ParseError,
},
#[error("type checking failed")]
Type {
path: Utf8PathBuf,
src: EcoString,
errors: Vec1<crate::type_::Error>,
names: Names,
},
#[error("unknown import {import}")]
UnknownImport {
import: EcoString,
// Boxed to prevent this variant from being overly large
details: Box<UnknownImportDetails>,
},
#[error("duplicate module {module}")]
DuplicateModule {
module: Name,
first: Utf8PathBuf,
second: Utf8PathBuf,
},
#[error("duplicate source file {file}")]
DuplicateSourceFile { file: String },
#[error("duplicate native Erlang module {module}")]
DuplicateNativeErlangModule {
module: Name,
first: Utf8PathBuf,
second: Utf8PathBuf,
},
#[error("gleam module {module} clashes with native file of same name")]
ClashingGleamModuleAndNativeFileName {
module: Name,
gleam_file: Utf8PathBuf,
native_file: Utf8PathBuf,
},
#[error("cyclical module imports")]
ImportCycle {
modules: Vec1<(EcoString, ImportCycleLocationDetails)>,
},
#[error("cyclical package dependencies")]
PackageCycle { packages: Vec<EcoString> },
#[error("file operation failed")]
FileIo {
kind: FileKind,
action: FileIoAction,
path: Utf8PathBuf,
err: Option<String>,
},
#[error("Non Utf-8 Path: {path}")]
NonUtf8Path { path: PathBuf },
#[error("{error}")]
GitInitialization { error: String },
#[error("io operation failed")]
StandardIo {
action: StandardIoAction,
err: Option<std::io::ErrorKind>,
},
#[error("source code incorrectly formatted")]
Format { problem_files: Vec<Unformatted> },
#[error("Hex error: {0}")]
Hex(String),
#[error("{error}")]
ExpandTar { error: String },
#[error("{err}")]
AddTar { path: Utf8PathBuf, err: String },
#[error("{0}")]
TarFinish(String),
#[error("{0}")]
Gzip(String),
#[error("shell program `{program}` not found")]
ShellProgramNotFound { program: String },
#[error("shell program `{program}` failed")]
ShellCommand {
program: String,
err: Option<std::io::ErrorKind>,
},
#[error("{name} is not a valid project name")]
InvalidProjectName {
name: String,
reason: InvalidProjectNameReason,
},
#[error("{module} is not a valid module name")]
InvalidModuleName { module: String },
#[error("{module} is not module")]
ModuleDoesNotExist {
module: EcoString,
suggestion: Option<EcoString>,
},
#[error("{module} does not have a main function")]
ModuleDoesNotHaveMainFunction { module: EcoString },
#[error("{module}'s main function has the wrong arity so it can not be run")]
MainFunctionHasWrongArity { module: EcoString, arity: usize },
#[error("{module}'s main function does not support the current target")]
MainFunctionDoesNotSupportTarget { module: EcoString, target: Target },
#[error("{input} is not a valid version. {error}")]
InvalidVersionFormat { input: String, error: String },
#[error("project root already exists")]
ProjectRootAlreadyExist { path: String },
#[error("File(s) already exist in {}",
file_names.iter().map(|x| x.as_str()).join(", "))]
OutputFilesAlreadyExist { file_names: Vec<Utf8PathBuf> },
#[error("Packages not exist: {}", packages.iter().join(", "))]
RemovedPackagesNotExist { packages: Vec<String> },
#[error("unable to find project root")]
UnableToFindProjectRoot { path: String },
#[error("gleam.toml version {toml_ver} does not match .app version {app_ver}")]
VersionDoesNotMatch { toml_ver: String, app_ver: String },
#[error("metadata decoding failed")]
MetadataDecodeError { error: Option<String> },
#[error("warnings are not permitted")]
ForbiddenWarnings { count: usize },
#[error("javascript codegen failed")]
JavaScript {
path: Utf8PathBuf,
src: EcoString,
error: javascript::Error,
},
#[error("Invalid runtime for {target} target: {invalid_runtime}")]
InvalidRuntime {
target: Target,
invalid_runtime: Runtime,
},
#[error("package downloading failed: {error}")]
DownloadPackageError {
package_name: String,
package_version: String,
error: String,
},
#[error("{0}")]
Http(String),
#[error("Git dependencies are currently unsupported")]
GitDependencyUnsupported,
#[error("Failed to create canonical path for package {0}")]
DependencyCanonicalizationFailed(String),
#[error("Dependency tree resolution failed: {error}")]
DependencyResolutionFailed {
error: String,
locked_conflicts: Vec<EcoString>,
},
#[error("The package {0} is listed in dependencies and dev-dependencies")]
DuplicateDependency(EcoString),
#[error("Expected package {expected} at path {path} but found {found} instead")]
WrongDependencyProvided {
path: Utf8PathBuf,
expected: String,
found: String,
},
#[error("The package {package} is provided multiple times, as {source_1} and {source_2}")]
ProvidedDependencyConflict {
package: String,
source_1: String,
source_2: String,
},
#[error("The package was missing required fields for publishing")]
MissingHexPublishFields {
description_missing: bool,
licence_missing: bool,
},
#[error("Dependency {package:?} has not been published to Hex")]
PublishNonHexDependencies { package: String },
#[error("The package {package} uses unsupported build tools {build_tools:?}")]
UnsupportedBuildTool {
package: String,
build_tools: Vec<EcoString>,
},
#[error("Opening docs at {path} failed: {error}")]
FailedToOpenDocs { path: Utf8PathBuf, error: String },
#[error(
"The package {package} requires a Gleam version satisfying \
{required_version} and you are using v{gleam_version}"
)]
IncompatibleCompilerVersion {
package: String,
required_version: String,
gleam_version: String,
},
#[error("The --javascript-prelude flag must be given when compiling to JavaScript")]
JavaScriptPreludeRequired,
#[error("The modules {unfinished:?} contain todo expressions and so cannot be published")]
CannotPublishTodo { unfinished: Vec<EcoString> },
#[error("The modules {unfinished:?} contain internal types in their public API so cannot be published")]
CannotPublishLeakedInternalType { unfinished: Vec<EcoString> },
#[error("Publishing packages to reserve names is not permitted")]
HexPackageSquatting,
#[error("Corrupt manifest.toml")]
CorruptManifest,
#[error("The Gleam module {path} would overwrite the Erlang module {name}")]
GleamModuleWouldOverwriteStandardErlangModule { name: EcoString, path: Utf8PathBuf },
#[error("Version already published")]
HexPublishReplaceRequired { version: String },
#[error("The gleam version constraint is wrong and so cannot be published")]
CannotPublishWrongVersion {
minimum_required_version: SmallVersion,
wrongfully_allowed_version: SmallVersion,
},
#[error("Failed to encrypt data")]
FailedToEncrypt { detail: String },
#[error("Failed to decrypt data")]
FailedToDecrypt { detail: String },
}
/// This is to make clippy happy and not make the error variant too big by
/// storing an entire `hexpm::version::Version` in the error.
///
/// This is enough to report wrong Gleam compiler versions.
///
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct SmallVersion {
major: u8,
minor: u8,
patch: u8,
}
impl Display for SmallVersion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&format!("{}.{}.{}", self.major, self.minor, self.patch))
}
}
impl SmallVersion {
pub fn from_hexpm(version: hexpm::version::Version) -> Self {
Self {
major: version.major as u8,
minor: version.minor as u8,
patch: version.patch as u8,
}
}
}
impl Error {
pub fn http<E>(error: E) -> Error
where
E: std::error::Error,
{
Self::Http(error.to_string())
}
pub fn hex<E>(error: E) -> Error
where
E: std::error::Error,
{
Self::Hex(error.to_string())
}
pub fn add_tar<P, E>(path: P, error: E) -> Error
where
P: AsRef<Utf8Path>,
E: std::error::Error,
{
Self::AddTar {
path: path.as_ref().to_path_buf(),
err: error.to_string(),
}
}
pub fn finish_tar<E>(error: E) -> Error
where
E: std::error::Error,
{
Self::TarFinish(error.to_string())
}
pub fn dependency_resolution_failed(
error: ResolutionError,
locked: &HashMap<EcoString, hexpm::version::Version>,
) -> Error {
fn collect_conflicting_packages<'dt, P: Package, V: Version>(
derivation_tree: &'dt DerivationTree<P, V>,
conflicting_packages: &mut HashSet<&'dt P>,
) {
match derivation_tree {
DerivationTree::External(external) => match external {
pubgrub::report::External::NotRoot(package, _) => {
let _ = conflicting_packages.insert(package);
}
pubgrub::report::External::NoVersions(package, _) => {
let _ = conflicting_packages.insert(package);
}
pubgrub::report::External::UnavailableDependencies(package, _) => {
let _ = conflicting_packages.insert(package);
}
pubgrub::report::External::FromDependencyOf(package, _, dep_package, _) => {
let _ = conflicting_packages.insert(package);
let _ = conflicting_packages.insert(dep_package);
}
},
DerivationTree::Derived(derived) => {
collect_conflicting_packages(&derived.cause1, conflicting_packages);
collect_conflicting_packages(&derived.cause2, conflicting_packages);
}
}
}
match error {
ResolutionError::NoSolution(mut derivation_tree) => {
derivation_tree.collapse_no_versions();
let mut conflicting_packages = HashSet::new();
collect_conflicting_packages(&derivation_tree, &mut conflicting_packages);
let conflict_names: Vec<EcoString> = conflicting_packages
.iter()
.map(|pkg| (*pkg).to_string().into())
.collect();
let locked_conflicts: Vec<EcoString> = conflict_names
.iter()
.filter(|name| locked.contains_key(*name))
.cloned()
.collect();
if locked_conflicts.is_empty() {
Error::DependencyResolutionFailed {
error: format!(
"Unable to find compatible versions for the version constraints in your gleam.toml.\n\
The conflicting packages are:\n{}",
conflicting_packages.into_iter().map(|s| format!("- {s}")).join("\n")
),
locked_conflicts,
}
} else {
Error::DependencyResolutionFailed {
error: format!(
"Unable to find compatible versions for the version constraints in your gleam.toml.\n\
The conflicting packages are:\n{}",
locked_conflicts.iter().map(|s| format!("- {s}")).join("\n")
),
locked_conflicts,
}
}
}
ResolutionError::ErrorRetrievingDependencies {
package,
version,
source,
} => {
Error::DependencyResolutionFailed{
error: format!(
"An error occurred while trying to retrieve dependencies of {package}@{version}: {source}"),
locked_conflicts: vec![],
}
}
ResolutionError::DependencyOnTheEmptySet {
package,
version,
dependent,
} => {
Error::DependencyResolutionFailed{
error: format!("{package}@{version} has an impossible dependency on {dependent}"),
locked_conflicts: vec![],
}
}
ResolutionError::SelfDependency { package, version } => {
Error::DependencyResolutionFailed{
error: format!("{package}@{version} somehow depends on itself."),
locked_conflicts: vec![],
}
}
ResolutionError::ErrorChoosingPackageVersion(err) => {
Error::DependencyResolutionFailed{
error: format!("Unable to determine package versions: {err}"),
locked_conflicts: vec![],
}
}
ResolutionError::ErrorInShouldCancel(err) => {
Error::DependencyResolutionFailed{
error: format!("Dependency resolution was cancelled. {err}"),
locked_conflicts: vec![],
}
}
ResolutionError::Failure(err) => {
Error::DependencyResolutionFailed{
error: format!("An unrecoverable error happened while solving dependencies: {err}"),
locked_conflicts: vec![],
}
}
}
}
pub fn expand_tar<E>(error: E) -> Error
where
E: std::error::Error,
{
Self::ExpandTar {
error: error.to_string(),
}
}
}
impl<T> From<Error> for Outcome<T, Error> {
fn from(error: Error) -> Self {
Outcome::TotalFailure(error)
}
}
impl From<capnp::Error> for Error {
fn from(error: capnp::Error) -> Self {
Error::MetadataDecodeError {
error: Some(error.to_string()),
}
}
}
impl From<capnp::NotInSchema> for Error {
fn from(error: capnp::NotInSchema) -> Self {
Error::MetadataDecodeError {
error: Some(error.to_string()),
}
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum InvalidProjectNameReason {
Format,
GleamPrefix,
ErlangReservedWord,
ErlangStandardLibraryModule,
GleamReservedWord,
GleamReservedModule,
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum StandardIoAction {
Read,
Write,
}
impl StandardIoAction {
fn text(&self) -> &'static str {
match self {
StandardIoAction::Read => "read from",
StandardIoAction::Write => "write to",
}
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum FileIoAction {
Link,
Open,
Copy,
Read,
Parse,
Delete,
// Rename,
Create,
WriteTo,
Canonicalise,
UpdatePermissions,
FindParent,
ReadMetadata,
}
impl FileIoAction {
fn text(&self) -> &'static str {
match self {
FileIoAction::Link => "link",
FileIoAction::Open => "open",
FileIoAction::Copy => "copy",
FileIoAction::Read => "read",
FileIoAction::Parse => "parse",
FileIoAction::Delete => "delete",
// FileIoAction::Rename => "rename",
FileIoAction::Create => "create",
FileIoAction::WriteTo => "write to",
FileIoAction::FindParent => "find the parent of",
FileIoAction::Canonicalise => "canonicalise",
FileIoAction::UpdatePermissions => "update permissions of",
FileIoAction::ReadMetadata => "read metadata of",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileKind {
File,
Directory,
}
impl FileKind {
fn text(&self) -> &'static str {
match self {
FileKind::File => "file",
FileKind::Directory => "directory",
}
}
}
// https://github.com/rust-lang/rust/blob/03994e498df79aa1f97f7bbcfd52d57c8e865049/compiler/rustc_span/src/edit_distance.rs
pub fn edit_distance(a: &str, b: &str, limit: usize) -> Option<usize> {
let mut a = &a.chars().collect::<Vec<_>>()[..];
let mut b = &b.chars().collect::<Vec<_>>()[..];
if a.len() < b.len() {
std::mem::swap(&mut a, &mut b);
}
let min_dist = a.len() - b.len();
// If we know the limit will be exceeded, we can return early.
if min_dist > limit {
return None;
}
// Strip common prefix.
while !b.is_empty() && !a.is_empty() {
let (b_first, b_rest) = b.split_last().expect("Failed to split 'b' slice");
let (a_first, a_rest) = a.split_last().expect("Failed to split 'a' slice");
if b_first == a_first {
a = a_rest;
b = b_rest;
} else {
break;
}
}
// If either string is empty, the distance is the length of the other.
// We know that `b` is the shorter string, so we don't need to check `a`.
if b.is_empty() {
return Some(min_dist);
}
let mut prev_prev = vec![usize::MAX; b.len() + 1];
let mut prev = (0..=b.len()).collect::<Vec<_>>();
let mut current = vec![0; b.len() + 1];
// row by row
for i in 1..=a.len() {
if let Some(elem) = current.get_mut(0) {
*elem = i;
}
let a_idx = i - 1;
// column by column
for j in 1..=b.len() {
let b_idx = j - 1;
// There is no cost to substitute a character with itself.
let substitution_cost = match (a.get(a_idx), b.get(b_idx)) {
(Some(&a_char), Some(&b_char)) => {
if a_char == b_char {
0
} else {
1
}
}
_ => panic!("Index out of bounds"),
};
let insertion = current.get(j - 1).map_or(usize::MAX, |&x| x + 1);
if let Some(value) = current.get_mut(j) {
*value = std::cmp::min(
// deletion
prev.get(j).map_or(usize::MAX, |&x| x + 1),
std::cmp::min(
// insertion
insertion,
// substitution
prev.get(j - 1)
.map_or(usize::MAX, |&x| x + substitution_cost),
),
);
}
if (i > 1) && (j > 1) {
if let (Some(&a_val), Some(&b_val_prev), Some(&a_val_prev), Some(&b_val)) = (
a.get(a_idx),
b.get(b_idx - 1),
a.get(a_idx - 1),
b.get(b_idx),
) {
if (a_val == b_val_prev) && (a_val_prev == b_val) {
// transposition
if let Some(curr) = current.get_mut(j) {
if let Some(&prev_prev_val) = prev_prev.get(j - 2) {
*curr = std::cmp::min(*curr, prev_prev_val + 1);
}
}
}
}
}
}
// Rotate the buffers, reusing the memory.
[prev_prev, prev, current] = [prev, current, prev_prev];
}
// `prev` because we already rotated the buffers.
let distance = match prev.get(b.len()) {
Some(&d) => d,
None => usize::MAX,
};
(distance <= limit).then_some(distance)
}
fn edit_distance_with_substrings(a: &str, b: &str, limit: usize) -> Option<usize> {
let n = a.chars().count();
let m = b.chars().count();
// Check one isn't less than half the length of the other. If this is true then there is a
// big difference in length.
let big_len_diff = (n * 2) < m || (m * 2) < n;
let len_diff = if n < m { m - n } else { n - m };
let distance = edit_distance(a, b, limit + len_diff)?;
// This is the crux, subtracting length difference means exact substring matches will now be 0
let score = distance - len_diff;
// If the score is 0 but the words have different lengths then it's a substring match not a full
// word match
let score = if score == 0 && len_diff > 0 && !big_len_diff {
1 // Exact substring match, but not a total word match so return non-zero
} else if !big_len_diff {
// Not a big difference in length, discount cost of length difference
score + (len_diff + 1) / 2
} else {
// A big difference in length, add back the difference in length to the score
score + len_diff
};
(score <= limit).then_some(score)
}
fn did_you_mean(name: &str, options: &[EcoString]) -> Option<String> {
// If only one option is given, return that option.
// This seems to solve the `unknown_variable_3` test.
if options.len() == 1 {
return options
.first()
.map(|option| format!("Did you mean `{option}`?"));
}
// Check for case-insensitive matches.
// This solves the comparison to small and single character terms,
// such as the test on `type_vars_must_be_declared`.
if let Some(exact_match) = options
.iter()
.find(|&option| option.eq_ignore_ascii_case(name))
{
return Some(format!("Did you mean `{exact_match}`?"));
}
// Calculate the threshold as one third of the name's length, with a minimum of 1.
let threshold = std::cmp::max(name.chars().count() / 3, 1);
// Filter and sort options based on edit distance.
options
.iter()
.filter(|&option| option != crate::ast::CAPTURE_VARIABLE)
.sorted()
.filter_map(|option| {
edit_distance_with_substrings(option, name, threshold)
.map(|distance| (option, distance))
})
.min_by_key(|&(_, distance)| distance)
.map(|(option, _)| format!("Did you mean `{option}`?"))
}
impl Error {
pub fn pretty_string(&self) -> String {
let mut nocolor = Buffer::no_color();
self.pretty(&mut nocolor);
String::from_utf8(nocolor.into_inner()).expect("Error printing produced invalid utf8")
}
pub fn pretty(&self, buffer: &mut Buffer) {
for diagnostic in self.to_diagnostics() {
diagnostic.write(buffer);
writeln!(buffer).expect("write new line after diagnostic");
}
}
pub fn to_diagnostics(&self) -> Vec<Diagnostic> {
use crate::type_::Error as TypeError;
match self {
Error::HexPackageSquatting => {
let text =
"You appear to be attempting to reserve a name on Hex rather than publishing a
working package. This is against the Hex terms of service and can result in
package deletion or account suspension.
"
.into();
vec![Diagnostic {
title: "Invalid Hex package".into(),
text,
level: Level::Error,
location: None,
hint: None,
}]
}
Error::MetadataDecodeError { error } => {
let mut text = "A problem was encountered when decoding the metadata for one \
of the Gleam dependency modules."
.to_string();
if let Some(error) = error {
text.push_str("\nThe error from the decoder library was:\n\n");
text.push_str(error);
}
vec![Diagnostic {
title: "Failed to decode module metadata".into(),
text,
level: Level::Error,
location: None,
hint: None,
}]
}
Error::InvalidProjectName { name, reason } => {
let text = wrap_format!(
"We were not able to create your project as `{}` {}
Please try again with a different project name.",
name,
match reason {
InvalidProjectNameReason::ErlangReservedWord =>
"is a reserved word in Erlang.",
InvalidProjectNameReason::ErlangStandardLibraryModule =>
"is a standard library module in Erlang.",
InvalidProjectNameReason::GleamReservedWord =>
"is a reserved word in Gleam.",
InvalidProjectNameReason::GleamReservedModule =>
"is a reserved module name in Gleam.",
InvalidProjectNameReason::Format =>
"does not have the correct format. Project names \
must start with a lowercase letter and may only contain lowercase letters, \
numbers and underscores.",
InvalidProjectNameReason::GleamPrefix =>
"has the reserved prefix `gleam_`. \
This prefix is intended for official Gleam packages only.",
}
);
vec![Diagnostic {
title: "Invalid project name".into(),
text,
hint: None,
level: Level::Error,
location: None,
}]
}
Error::InvalidModuleName { module } => vec![Diagnostic {
title: "Invalid module name".into(),
text: format!(
"`{module}` is not a valid module name.
Module names can only contain lowercase letters, underscore, and
forward slash and must not end with a slash."
),
level: Level::Error,
location: None,
hint: None,
}],
Error::ModuleDoesNotExist { module, suggestion } => {
let hint = match suggestion {
Some(suggestion) => format!("Did you mean `{suggestion}`?"),
None => format!("Try creating the file `src/{module}.gleam`."),
};
vec![Diagnostic {
title: "Module does not exist".into(),
text: format!("Module `{module}` was not found."),
level: Level::Error,
location: None,
hint: Some(hint),
}]
}
Error::ModuleDoesNotHaveMainFunction { module } => vec![Diagnostic {
title: "Module does not have a main function".into(),
text: format!(
"`{module}` does not have a main function so the module can not be run."
),
level: Level::Error,
location: None,
hint: Some(format!(
"Add a public `main` function to \
to `src/{module}.gleam`."
)),
}],
Error::MainFunctionDoesNotSupportTarget { module, target } => vec![Diagnostic {
title: "Target not supported".into(),
text: wrap_format!(
"`{module}` has a main function, but it does not support the {target} \
target, so it cannot be run."
),
level: Level::Error,
location: None,
hint: None,
}],
Error::MainFunctionHasWrongArity { module, arity } => vec![Diagnostic {
title: "Main function has wrong arity".into(),
text: format!(
"`{module}:main` should have an arity of 0 to be run but its arity is {arity}."
),
level: Level::Error,
location: None,
hint: Some("Change the function signature of main to `pub fn main() {}`.".into()),
}],
Error::ProjectRootAlreadyExist { path } => vec![Diagnostic {
title: "Project folder already exists".into(),
text: format!("Project folder root:\n\n {path}"),
level: Level::Error,
hint: None,
location: None,
}],
Error::OutputFilesAlreadyExist { file_names } => vec![Diagnostic {
title: format!(
"{} already exist{} in target directory",
if file_names.len() == 1 {
"File"
} else {
"Files"
},
if file_names.len() == 1 { "" } else { "s" }
),
text: format!(
"{}
If you want to overwrite these files, delete them and run the command again.
",
file_names
.iter()
.map(|name| format!(" - {}", name.as_str()))
.join("\n")
),
level: Level::Error,
hint: None,
location: None,
}],
Error::RemovedPackagesNotExist { packages } => vec![
Diagnostic {
title: "Package not found".into(),
text: format!(
"These packages are not dependencies of your package so they could not
be removed.
{}
",
packages
.iter()
.map(|p| format!(" - {}", p.as_str()))
.join("\n")
),
level: Level::Error,
hint: None,
location: None,
}
],
Error::CannotPublishTodo { unfinished } => vec![Diagnostic {
title: "Cannot publish unfinished code".into(),
text: format!(
"These modules contain todo expressions and cannot be published:
{}
Please remove them and try again.
",
unfinished
.iter()
.map(|name| format!(" - {}", name.as_str()))
.join("\n")
),