Enum erg_common::config::Input
source · Expand description
入力はファイルからだけとは限らないので Inputで操作を一本化する
Variants§
File(PathBuf)
REPL
Pipe(String)
same content as cfg.command
Str(String)
from command option | eval
Dummy
Implementations§
source§impl Input
impl Input
sourcepub fn is_repl(&self) -> bool
pub fn is_repl(&self) -> bool
Examples found in repository?
error.rs (line 344)
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
fn format_context<E: ErrorDisplay + ?Sized>(
e: &E,
ln_begin: usize,
ln_end: usize,
col_begin: usize,
col_end: usize,
err_color: Color,
gutter_color: Color,
// for formatting points
chars: &Characters,
// kinds of error for specify the color
mark: char,
sub_msg: &[String],
hint: Option<&String>,
) -> String {
let mark = mark.to_string();
let codes = if e.input().is_repl() {
vec![e.input().reread()]
} else {
e.input().reread_lines(ln_begin, ln_end)
};
let mut context = StyledStrings::default();
let final_step = ln_end - ln_begin;
let max_digit = ln_end.to_string().len();
let (vbreak, vbar) = chars.gutters();
let offset = format!("{} {} ", &" ".repeat(max_digit), vbreak);
for (i, lineno) in (ln_begin..=ln_end).enumerate() {
context.push_str_with_color(
&format!("{:<max_digit$} {vbar} ", lineno, vbar = vbar),
gutter_color,
);
context.push_str(codes.get(i).unwrap_or(&String::new()));
context.push_str("\n");
context.push_str_with_color(&offset, gutter_color);
if i == 0 && i == final_step {
context.push_str(&" ".repeat(col_begin));
context.push_str_with_color(
&mark.repeat(cmp::max(1, col_end.saturating_sub(col_begin))),
err_color,
);
} else if i == 0 {
context.push_str(&" ".repeat(col_begin));
context.push_str_with_color(
&mark.repeat(cmp::max(1, codes[i].len().saturating_sub(col_begin))),
err_color,
);
} else if i == final_step {
context.push_str_with_color(&mark.repeat(col_end), err_color);
} else {
context.push_str_with_color(&mark.repeat(cmp::max(1, codes[i].len())), err_color);
}
context.push_str("\n");
}
let msg_num = sub_msg.len().saturating_sub(1);
for (i, msg) in sub_msg.iter().enumerate() {
context.push_str_with_color(&offset, gutter_color);
context.push_str(&" ".repeat(col_end.saturating_sub(1)));
if i == msg_num && hint.is_none() {
context.push_str_with_color(&chars.left_bottom_line(), err_color);
} else {
context.push_str_with_color(&chars.left_cross(), err_color);
}
context.push_str(msg);
context.push_str("\n")
}
if let Some(hint) = hint {
context.push_str_with_color(&offset, gutter_color);
context.push_str(&" ".repeat(col_end.saturating_sub(1)));
context.push_str_with_color(&chars.left_bottom_line(), err_color);
context.push_str(hint);
context.push_str("\n")
}
context.to_string() + "\n"
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SubMessage {
pub loc: Location,
pub msg: Vec<String>,
pub hint: Option<String>,
}
impl SubMessage {
///
/// Used when the msg or hint si empty.
/// `msg` is Vec\<String\> instead of Option\<String\> because it can be used when there are multiple `msg`s as well as multiple lines.
/// # Example
/// ```
/// let msg = SubMessage::ambiguous_new(loc, vec![], None); // this code same as only_loc()
///
/// let hint = Some("hint message here".to_string())
/// let msg = SubMessage::ambiguous_new(loc, vec![], hint);
/// /* example
/// -------
/// `- hint message here
/// */
///
/// let hint = Some("hint here".to_string())
/// let first = StyledString::new("1th message", Color::Red, None);
/// let second = StyledString::new("2th message", Color::White, None);
/// :
/// let nth = StyledString::new("nth message", Color::Green, None);
/// let msg = SubMessage::ambiguous_new(
/// loc,
/// vec![
/// first.to_string(),
/// second.to_string(),
/// ...,
/// nth.to_string(),
/// ],
/// hint);
/// /* example
/// -------
/// :- 1th message
/// :- 2th message
/// :
/// :- nth message
/// `- hint here
/// */
///
/// ```
///
pub fn ambiguous_new(loc: Location, msg: Vec<String>, hint: Option<String>) -> Self {
Self { loc, msg, hint }
}
///
/// Used when only Location is fixed.
/// In this case, error position is just modified
/// # Example
/// ```
/// let sub_msg = SubMessage::only_loc(loc);
/// ```
pub fn only_loc(loc: Location) -> Self {
Self {
loc,
msg: Vec::new(),
hint: None,
}
}
pub fn set_hint<S: Into<String>>(&mut self, hint: S) {
self.hint = Some(hint.into());
}
pub fn get_hint(&self) -> Option<&str> {
self.hint.as_deref()
}
pub fn get_msg(&self) -> &[String] {
self.msg.as_ref()
}
// Line breaks are not included except for line breaks that signify the end of a sentence.
// In other words, do not include blank lines for formatting purposes.
fn format_code_and_pointer<E: ErrorDisplay + ?Sized>(
&self,
e: &E,
err_color: Color,
gutter_color: Color,
mark: char,
chars: &Characters,
) -> String {
match self.loc.unknown_or(e.core().loc) {
Location::Range {
ln_begin,
col_begin,
ln_end,
col_end,
} => format_context(
e,
ln_begin,
ln_end,
col_begin,
col_end,
err_color,
gutter_color,
chars,
mark,
&self.msg,
self.hint.as_ref(),
),
Location::LineRange(ln_begin, ln_end) => {
let input = e.input();
let (vbreak, vbar) = chars.gutters();
let mut cxt = StyledStrings::default();
let codes = if input.is_repl() {
vec![input.reread()]
} else {
input.reread_lines(ln_begin, ln_end)
};
let mark = mark.to_string();
for (i, lineno) in (ln_begin..=ln_end).enumerate() {
cxt.push_str_with_color(&format!("{lineno} {vbar} "), gutter_color);
cxt.push_str(codes.get(i).unwrap_or(&String::new()));
cxt.push_str("\n");
cxt.push_str_with_color(
&format!("{} {}", &" ".repeat(lineno.to_string().len()), vbreak),
gutter_color,
);
cxt.push_str(&" ".repeat(lineno.to_string().len()));
cxt.push_str_with_color(&mark.repeat(cmp::max(1, codes[i].len())), err_color);
cxt.push_str("\n");
}
cxt.push_str("\n");
for msg in self.msg.iter() {
cxt.push_str(msg);
cxt.push_str("\n");
}
if let Some(hint) = self.hint.as_ref() {
cxt.push_str(hint);
cxt.push_str("\n");
}
cxt.to_string()
}
Location::Line(lineno) => {
let input = e.input();
let (_, vbar) = chars.gutters();
let code = if input.is_repl() {
input.reread()
} else {
input.reread_lines(lineno, lineno).remove(0)
};
let mut cxt = StyledStrings::default();
cxt.push_str_with_color(&format!(" {lineno} {} ", vbar), gutter_color);
cxt.push_str(&code);
cxt.push_str("\n");
for msg in self.msg.iter() {
cxt.push_str(msg);
cxt.push_str("\n");
}
if let Some(hint) = self.hint.as_ref() {
cxt.push_str(hint);
cxt.push_str("\n");
}
cxt.push_str("\n");
cxt.to_string()
}
Location::Unknown => match e.input() {
Input::File(_) => "\n".to_string(),
other => {
let (_, vbar) = chars.gutters();
let mut cxt = StyledStrings::default();
cxt.push_str_with_color(&format!(" ? {} ", vbar), gutter_color);
cxt.push_str(&other.reread());
cxt.push_str("\n");
for msg in self.msg.iter() {
cxt.push_str(msg);
cxt.push_str("\n");
}
if let Some(hint) = self.hint.as_ref() {
cxt.push_str(hint);
cxt.push_str("\n");
}
cxt.push_str("\n");
cxt.to_string()
}
},
}
}
sourcepub fn enclosed_name(&self) -> &str
pub fn enclosed_name(&self) -> &str
Examples found in repository?
error.rs (line 762)
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
fn show(&self) -> String {
let core = self.core();
let (color, mark) = core.specified_theme();
let (gutter_color, chars) = core.theme.characters();
let mut msg = String::new();
msg += &core.fmt_header(color, self.caused_by(), self.input().enclosed_name());
msg += "\n\n";
for sub_msg in &core.sub_messages {
msg += &sub_msg.format_code_and_pointer(self, color, gutter_color, mark, chars);
}
msg += &core.kind.to_string();
msg += ": ";
msg += &core.main_message;
msg += "\n\n";
msg
}
/// for fmt::Display
fn format(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let core = self.core();
let (color, mark) = core.specified_theme();
let (gutter_color, chars) = core.theme.characters();
write!(
f,
"{}\n\n",
core.fmt_header(color, self.caused_by(), self.input().enclosed_name())
)?;
for sub_msg in &core.sub_messages {
write!(
f,
"{}",
&sub_msg.format_code_and_pointer(self, color, gutter_color, mark, chars)
)?;
}
write!(f, "{}\n\n", core.main_message)?;
if let Some(inner) = self.ref_inner() {
inner.format(f)
} else {
Ok(())
}
}
sourcepub fn filename(&self) -> &str
pub fn filename(&self) -> &str
Examples found in repository?
config.rs (line 260)
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
pub fn dump_path(&self) -> String {
if let Some(output) = &self.output_dir {
format!("{output}/{}", self.input.filename())
} else {
self.input.full_path().to_string()
}
}
pub fn dump_filename(&self) -> String {
if let Some(output) = &self.output_dir {
format!("{output}/{}", self.input.filename())
} else {
self.input.filename().to_string()
}
}
sourcepub fn read(&self) -> String
pub fn read(&self) -> String
Examples found in repository?
traits.rs (line 450)
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
fn run(cfg: ErgConfig) {
let quiet_repl = cfg.quiet_repl;
let mut instance = Self::new(cfg);
let res = match instance.input() {
Input::File(_) | Input::Pipe(_) | Input::Str(_) => instance.exec(),
Input::REPL => {
let output = stdout();
let mut output = BufWriter::new(output.lock());
if !quiet_repl {
log!(info_f output, "The REPL has started.\n");
output
.write_all(instance.start_message().as_bytes())
.unwrap();
}
output.write_all(instance.ps1().as_bytes()).unwrap();
output.flush().unwrap();
let mut in_block = false;
let mut lines = String::new();
loop {
let line = chomp(&instance.input().read());
match &line[..] {
":quit" | ":exit" => {
instance.quit_successfully(output);
}
":clear" => {
output.write_all("\x1b[2J\x1b[1;1H".as_bytes()).unwrap();
output.flush().unwrap();
output.write_all(instance.ps1().as_bytes()).unwrap();
output.flush().unwrap();
instance.clear();
continue;
}
_ => {}
}
let line = if let Some(comment_start) = line.find('#') {
&line[..comment_start]
} else {
&line[..]
};
lines.push_str(line);
if in_block {
if is_in_the_expected_block(line, &lines, &mut in_block) {
lines += "\n";
output.write_all(instance.ps2().as_bytes()).unwrap();
output.flush().unwrap();
continue;
}
} else if expect_block(line) {
in_block = true;
lines += "\n";
output.write_all(instance.ps2().as_bytes()).unwrap();
output.flush().unwrap();
continue;
}
match instance.eval(mem::take(&mut lines)) {
Ok(out) => {
output.write_all((out + "\n").as_bytes()).unwrap();
output.flush().unwrap();
}
Err(errs) => {
if errs
.first()
.map(|e| e.core().kind == ErrorKind::SystemExit)
.unwrap_or(false)
{
instance.quit_successfully(output);
}
errs.fmt_all_stderr();
}
}
output.write_all(instance.ps1().as_bytes()).unwrap();
output.flush().unwrap();
instance.clear();
}
}
Input::Dummy => switch_unreachable!(),
};
if let Err(e) = res {
e.fmt_all_stderr();
instance.quit(1);
}
}
sourcepub fn reread_lines(&self, ln_begin: usize, ln_end: usize) -> Vec<String>
pub fn reread_lines(&self, ln_begin: usize, ln_end: usize) -> Vec<String>
Examples found in repository?
error.rs (line 347)
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
fn format_context<E: ErrorDisplay + ?Sized>(
e: &E,
ln_begin: usize,
ln_end: usize,
col_begin: usize,
col_end: usize,
err_color: Color,
gutter_color: Color,
// for formatting points
chars: &Characters,
// kinds of error for specify the color
mark: char,
sub_msg: &[String],
hint: Option<&String>,
) -> String {
let mark = mark.to_string();
let codes = if e.input().is_repl() {
vec![e.input().reread()]
} else {
e.input().reread_lines(ln_begin, ln_end)
};
let mut context = StyledStrings::default();
let final_step = ln_end - ln_begin;
let max_digit = ln_end.to_string().len();
let (vbreak, vbar) = chars.gutters();
let offset = format!("{} {} ", &" ".repeat(max_digit), vbreak);
for (i, lineno) in (ln_begin..=ln_end).enumerate() {
context.push_str_with_color(
&format!("{:<max_digit$} {vbar} ", lineno, vbar = vbar),
gutter_color,
);
context.push_str(codes.get(i).unwrap_or(&String::new()));
context.push_str("\n");
context.push_str_with_color(&offset, gutter_color);
if i == 0 && i == final_step {
context.push_str(&" ".repeat(col_begin));
context.push_str_with_color(
&mark.repeat(cmp::max(1, col_end.saturating_sub(col_begin))),
err_color,
);
} else if i == 0 {
context.push_str(&" ".repeat(col_begin));
context.push_str_with_color(
&mark.repeat(cmp::max(1, codes[i].len().saturating_sub(col_begin))),
err_color,
);
} else if i == final_step {
context.push_str_with_color(&mark.repeat(col_end), err_color);
} else {
context.push_str_with_color(&mark.repeat(cmp::max(1, codes[i].len())), err_color);
}
context.push_str("\n");
}
let msg_num = sub_msg.len().saturating_sub(1);
for (i, msg) in sub_msg.iter().enumerate() {
context.push_str_with_color(&offset, gutter_color);
context.push_str(&" ".repeat(col_end.saturating_sub(1)));
if i == msg_num && hint.is_none() {
context.push_str_with_color(&chars.left_bottom_line(), err_color);
} else {
context.push_str_with_color(&chars.left_cross(), err_color);
}
context.push_str(msg);
context.push_str("\n")
}
if let Some(hint) = hint {
context.push_str_with_color(&offset, gutter_color);
context.push_str(&" ".repeat(col_end.saturating_sub(1)));
context.push_str_with_color(&chars.left_bottom_line(), err_color);
context.push_str(hint);
context.push_str("\n")
}
context.to_string() + "\n"
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SubMessage {
pub loc: Location,
pub msg: Vec<String>,
pub hint: Option<String>,
}
impl SubMessage {
///
/// Used when the msg or hint si empty.
/// `msg` is Vec\<String\> instead of Option\<String\> because it can be used when there are multiple `msg`s as well as multiple lines.
/// # Example
/// ```
/// let msg = SubMessage::ambiguous_new(loc, vec![], None); // this code same as only_loc()
///
/// let hint = Some("hint message here".to_string())
/// let msg = SubMessage::ambiguous_new(loc, vec![], hint);
/// /* example
/// -------
/// `- hint message here
/// */
///
/// let hint = Some("hint here".to_string())
/// let first = StyledString::new("1th message", Color::Red, None);
/// let second = StyledString::new("2th message", Color::White, None);
/// :
/// let nth = StyledString::new("nth message", Color::Green, None);
/// let msg = SubMessage::ambiguous_new(
/// loc,
/// vec![
/// first.to_string(),
/// second.to_string(),
/// ...,
/// nth.to_string(),
/// ],
/// hint);
/// /* example
/// -------
/// :- 1th message
/// :- 2th message
/// :
/// :- nth message
/// `- hint here
/// */
///
/// ```
///
pub fn ambiguous_new(loc: Location, msg: Vec<String>, hint: Option<String>) -> Self {
Self { loc, msg, hint }
}
///
/// Used when only Location is fixed.
/// In this case, error position is just modified
/// # Example
/// ```
/// let sub_msg = SubMessage::only_loc(loc);
/// ```
pub fn only_loc(loc: Location) -> Self {
Self {
loc,
msg: Vec::new(),
hint: None,
}
}
pub fn set_hint<S: Into<String>>(&mut self, hint: S) {
self.hint = Some(hint.into());
}
pub fn get_hint(&self) -> Option<&str> {
self.hint.as_deref()
}
pub fn get_msg(&self) -> &[String] {
self.msg.as_ref()
}
// Line breaks are not included except for line breaks that signify the end of a sentence.
// In other words, do not include blank lines for formatting purposes.
fn format_code_and_pointer<E: ErrorDisplay + ?Sized>(
&self,
e: &E,
err_color: Color,
gutter_color: Color,
mark: char,
chars: &Characters,
) -> String {
match self.loc.unknown_or(e.core().loc) {
Location::Range {
ln_begin,
col_begin,
ln_end,
col_end,
} => format_context(
e,
ln_begin,
ln_end,
col_begin,
col_end,
err_color,
gutter_color,
chars,
mark,
&self.msg,
self.hint.as_ref(),
),
Location::LineRange(ln_begin, ln_end) => {
let input = e.input();
let (vbreak, vbar) = chars.gutters();
let mut cxt = StyledStrings::default();
let codes = if input.is_repl() {
vec![input.reread()]
} else {
input.reread_lines(ln_begin, ln_end)
};
let mark = mark.to_string();
for (i, lineno) in (ln_begin..=ln_end).enumerate() {
cxt.push_str_with_color(&format!("{lineno} {vbar} "), gutter_color);
cxt.push_str(codes.get(i).unwrap_or(&String::new()));
cxt.push_str("\n");
cxt.push_str_with_color(
&format!("{} {}", &" ".repeat(lineno.to_string().len()), vbreak),
gutter_color,
);
cxt.push_str(&" ".repeat(lineno.to_string().len()));
cxt.push_str_with_color(&mark.repeat(cmp::max(1, codes[i].len())), err_color);
cxt.push_str("\n");
}
cxt.push_str("\n");
for msg in self.msg.iter() {
cxt.push_str(msg);
cxt.push_str("\n");
}
if let Some(hint) = self.hint.as_ref() {
cxt.push_str(hint);
cxt.push_str("\n");
}
cxt.to_string()
}
Location::Line(lineno) => {
let input = e.input();
let (_, vbar) = chars.gutters();
let code = if input.is_repl() {
input.reread()
} else {
input.reread_lines(lineno, lineno).remove(0)
};
let mut cxt = StyledStrings::default();
cxt.push_str_with_color(&format!(" {lineno} {} ", vbar), gutter_color);
cxt.push_str(&code);
cxt.push_str("\n");
for msg in self.msg.iter() {
cxt.push_str(msg);
cxt.push_str("\n");
}
if let Some(hint) = self.hint.as_ref() {
cxt.push_str(hint);
cxt.push_str("\n");
}
cxt.push_str("\n");
cxt.to_string()
}
Location::Unknown => match e.input() {
Input::File(_) => "\n".to_string(),
other => {
let (_, vbar) = chars.gutters();
let mut cxt = StyledStrings::default();
cxt.push_str_with_color(&format!(" ? {} ", vbar), gutter_color);
cxt.push_str(&other.reread());
cxt.push_str("\n");
for msg in self.msg.iter() {
cxt.push_str(msg);
cxt.push_str("\n");
}
if let Some(hint) = self.hint.as_ref() {
cxt.push_str(hint);
cxt.push_str("\n");
}
cxt.push_str("\n");
cxt.to_string()
}
},
}
}
sourcepub fn reread(&self) -> String
pub fn reread(&self) -> String
Examples found in repository?
error.rs (line 345)
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
fn format_context<E: ErrorDisplay + ?Sized>(
e: &E,
ln_begin: usize,
ln_end: usize,
col_begin: usize,
col_end: usize,
err_color: Color,
gutter_color: Color,
// for formatting points
chars: &Characters,
// kinds of error for specify the color
mark: char,
sub_msg: &[String],
hint: Option<&String>,
) -> String {
let mark = mark.to_string();
let codes = if e.input().is_repl() {
vec![e.input().reread()]
} else {
e.input().reread_lines(ln_begin, ln_end)
};
let mut context = StyledStrings::default();
let final_step = ln_end - ln_begin;
let max_digit = ln_end.to_string().len();
let (vbreak, vbar) = chars.gutters();
let offset = format!("{} {} ", &" ".repeat(max_digit), vbreak);
for (i, lineno) in (ln_begin..=ln_end).enumerate() {
context.push_str_with_color(
&format!("{:<max_digit$} {vbar} ", lineno, vbar = vbar),
gutter_color,
);
context.push_str(codes.get(i).unwrap_or(&String::new()));
context.push_str("\n");
context.push_str_with_color(&offset, gutter_color);
if i == 0 && i == final_step {
context.push_str(&" ".repeat(col_begin));
context.push_str_with_color(
&mark.repeat(cmp::max(1, col_end.saturating_sub(col_begin))),
err_color,
);
} else if i == 0 {
context.push_str(&" ".repeat(col_begin));
context.push_str_with_color(
&mark.repeat(cmp::max(1, codes[i].len().saturating_sub(col_begin))),
err_color,
);
} else if i == final_step {
context.push_str_with_color(&mark.repeat(col_end), err_color);
} else {
context.push_str_with_color(&mark.repeat(cmp::max(1, codes[i].len())), err_color);
}
context.push_str("\n");
}
let msg_num = sub_msg.len().saturating_sub(1);
for (i, msg) in sub_msg.iter().enumerate() {
context.push_str_with_color(&offset, gutter_color);
context.push_str(&" ".repeat(col_end.saturating_sub(1)));
if i == msg_num && hint.is_none() {
context.push_str_with_color(&chars.left_bottom_line(), err_color);
} else {
context.push_str_with_color(&chars.left_cross(), err_color);
}
context.push_str(msg);
context.push_str("\n")
}
if let Some(hint) = hint {
context.push_str_with_color(&offset, gutter_color);
context.push_str(&" ".repeat(col_end.saturating_sub(1)));
context.push_str_with_color(&chars.left_bottom_line(), err_color);
context.push_str(hint);
context.push_str("\n")
}
context.to_string() + "\n"
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SubMessage {
pub loc: Location,
pub msg: Vec<String>,
pub hint: Option<String>,
}
impl SubMessage {
///
/// Used when the msg or hint si empty.
/// `msg` is Vec\<String\> instead of Option\<String\> because it can be used when there are multiple `msg`s as well as multiple lines.
/// # Example
/// ```
/// let msg = SubMessage::ambiguous_new(loc, vec![], None); // this code same as only_loc()
///
/// let hint = Some("hint message here".to_string())
/// let msg = SubMessage::ambiguous_new(loc, vec![], hint);
/// /* example
/// -------
/// `- hint message here
/// */
///
/// let hint = Some("hint here".to_string())
/// let first = StyledString::new("1th message", Color::Red, None);
/// let second = StyledString::new("2th message", Color::White, None);
/// :
/// let nth = StyledString::new("nth message", Color::Green, None);
/// let msg = SubMessage::ambiguous_new(
/// loc,
/// vec![
/// first.to_string(),
/// second.to_string(),
/// ...,
/// nth.to_string(),
/// ],
/// hint);
/// /* example
/// -------
/// :- 1th message
/// :- 2th message
/// :
/// :- nth message
/// `- hint here
/// */
///
/// ```
///
pub fn ambiguous_new(loc: Location, msg: Vec<String>, hint: Option<String>) -> Self {
Self { loc, msg, hint }
}
///
/// Used when only Location is fixed.
/// In this case, error position is just modified
/// # Example
/// ```
/// let sub_msg = SubMessage::only_loc(loc);
/// ```
pub fn only_loc(loc: Location) -> Self {
Self {
loc,
msg: Vec::new(),
hint: None,
}
}
pub fn set_hint<S: Into<String>>(&mut self, hint: S) {
self.hint = Some(hint.into());
}
pub fn get_hint(&self) -> Option<&str> {
self.hint.as_deref()
}
pub fn get_msg(&self) -> &[String] {
self.msg.as_ref()
}
// Line breaks are not included except for line breaks that signify the end of a sentence.
// In other words, do not include blank lines for formatting purposes.
fn format_code_and_pointer<E: ErrorDisplay + ?Sized>(
&self,
e: &E,
err_color: Color,
gutter_color: Color,
mark: char,
chars: &Characters,
) -> String {
match self.loc.unknown_or(e.core().loc) {
Location::Range {
ln_begin,
col_begin,
ln_end,
col_end,
} => format_context(
e,
ln_begin,
ln_end,
col_begin,
col_end,
err_color,
gutter_color,
chars,
mark,
&self.msg,
self.hint.as_ref(),
),
Location::LineRange(ln_begin, ln_end) => {
let input = e.input();
let (vbreak, vbar) = chars.gutters();
let mut cxt = StyledStrings::default();
let codes = if input.is_repl() {
vec![input.reread()]
} else {
input.reread_lines(ln_begin, ln_end)
};
let mark = mark.to_string();
for (i, lineno) in (ln_begin..=ln_end).enumerate() {
cxt.push_str_with_color(&format!("{lineno} {vbar} "), gutter_color);
cxt.push_str(codes.get(i).unwrap_or(&String::new()));
cxt.push_str("\n");
cxt.push_str_with_color(
&format!("{} {}", &" ".repeat(lineno.to_string().len()), vbreak),
gutter_color,
);
cxt.push_str(&" ".repeat(lineno.to_string().len()));
cxt.push_str_with_color(&mark.repeat(cmp::max(1, codes[i].len())), err_color);
cxt.push_str("\n");
}
cxt.push_str("\n");
for msg in self.msg.iter() {
cxt.push_str(msg);
cxt.push_str("\n");
}
if let Some(hint) = self.hint.as_ref() {
cxt.push_str(hint);
cxt.push_str("\n");
}
cxt.to_string()
}
Location::Line(lineno) => {
let input = e.input();
let (_, vbar) = chars.gutters();
let code = if input.is_repl() {
input.reread()
} else {
input.reread_lines(lineno, lineno).remove(0)
};
let mut cxt = StyledStrings::default();
cxt.push_str_with_color(&format!(" {lineno} {} ", vbar), gutter_color);
cxt.push_str(&code);
cxt.push_str("\n");
for msg in self.msg.iter() {
cxt.push_str(msg);
cxt.push_str("\n");
}
if let Some(hint) = self.hint.as_ref() {
cxt.push_str(hint);
cxt.push_str("\n");
}
cxt.push_str("\n");
cxt.to_string()
}
Location::Unknown => match e.input() {
Input::File(_) => "\n".to_string(),
other => {
let (_, vbar) = chars.gutters();
let mut cxt = StyledStrings::default();
cxt.push_str_with_color(&format!(" ? {} ", vbar), gutter_color);
cxt.push_str(&other.reread());
cxt.push_str("\n");
for msg in self.msg.iter() {
cxt.push_str(msg);
cxt.push_str("\n");
}
if let Some(hint) = self.hint.as_ref() {
cxt.push_str(hint);
cxt.push_str("\n");
}
cxt.push_str("\n");
cxt.to_string()
}
},
}
}