Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix forc-fmt panic when lexing fails #5011

Merged
merged 10 commits into from
Aug 25, 2023
14 changes: 7 additions & 7 deletions forc-plugins/forc-doc/src/doc/descriptor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ impl Descriptor {
item_name,
code_str: parse::parse_format::<sway_ast::ItemStruct>(
struct_decl.span.as_str(),
),
)?,
attrs_opt: attrs_opt.clone(),
item_context: ItemContext {
context_opt: context,
Expand Down Expand Up @@ -103,7 +103,7 @@ impl Descriptor {
item_name,
code_str: parse::parse_format::<sway_ast::ItemEnum>(
enum_decl.span.as_str(),
),
)?,
attrs_opt: attrs_opt.clone(),
item_context: ItemContext {
context_opt: context,
Expand Down Expand Up @@ -151,7 +151,7 @@ impl Descriptor {
item_name,
code_str: parse::parse_format::<sway_ast::ItemTrait>(
trait_decl.span.as_str(),
),
)?,
attrs_opt: attrs_opt.clone(),
item_context: ItemContext {
context_opt: context,
Expand Down Expand Up @@ -193,7 +193,7 @@ impl Descriptor {
module_info,
ty_decl: ty_decl.clone(),
item_name,
code_str: parse::parse_format::<sway_ast::ItemAbi>(abi_decl.span.as_str()),
code_str: parse::parse_format::<sway_ast::ItemAbi>(abi_decl.span.as_str())?,
attrs_opt: attrs_opt.clone(),
item_context: ItemContext {
context_opt: context,
Expand Down Expand Up @@ -228,7 +228,7 @@ impl Descriptor {
item_name,
code_str: parse::parse_format::<sway_ast::ItemStorage>(
storage_decl.span.as_str(),
),
)?,
attrs_opt: attrs_opt.clone(),
item_context: ItemContext {
context_opt: context,
Expand Down Expand Up @@ -288,7 +288,7 @@ impl Descriptor {
item_name,
code_str: trim_fn_body(parse::parse_format::<sway_ast::ItemFn>(
fn_decl.span.as_str(),
)),
)?),
attrs_opt: attrs_opt.clone(),
item_context: ItemContext {
context_opt: None,
Expand Down Expand Up @@ -321,7 +321,7 @@ impl Descriptor {
item_name,
code_str: parse::parse_format::<sway_ast::ItemConst>(
const_decl.span.as_str(),
),
)?,
attrs_opt: attrs_opt.clone(),
item_context: ItemContext {
context_opt: None,
Expand Down
16 changes: 8 additions & 8 deletions forc-plugins/forc-fmt/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ use std::{
sync::Arc,
};
use taplo::formatter as taplo_fmt;
use tracing::{error, info};
use tracing::{debug, error, info};

use forc_tracing::{init_tracing_subscriber, println_green, println_red};
use forc_tracing::{init_tracing_subscriber, println_error, println_green, println_red};
use forc_util::{find_parent_manifest_dir, is_sway_file};
use sway_core::{BuildConfig, BuildTarget};
use sway_utils::{constants, get_sway_files};
Expand Down Expand Up @@ -43,7 +43,8 @@ pub struct App {
fn main() {
init_tracing_subscriber(Default::default());
if let Err(err) = run() {
error!("Error: {:?}", err);
println_error(&format!("Formatting skipped due to error."));
sdankel marked this conversation as resolved.
Show resolved Hide resolved
println_error(&format!("{}", err));
std::process::exit(1);
}
}
Expand Down Expand Up @@ -150,11 +151,10 @@ fn format_file(
return Ok(edited);
}
Err(err) => {
// there could still be Sway files that are not part of the build
error!(
"\nThis file: {:?} is not part of the build\n{}\n",
file, err
);
// TODO: Support formatting for incomplete/invalid sway code.
// https://github.com/FuelLabs/sway/issues/5012
debug!("{}", err);
bail!("Failed to compile: {:?}", file);
}
}
}
Expand Down
12 changes: 5 additions & 7 deletions swayfmt/src/formatter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,11 @@ impl Formatter {
}

/// Collect a mapping of Span -> Comment from unformatted input.
pub fn with_comments_context(&mut self, src: &str) -> &mut Self {
let comments_context = CommentsContext::new(
CommentMap::from_src(Arc::from(src)).unwrap(),
src.to_string(),
);
pub fn with_comments_context(&mut self, src: &str) -> Result<&mut Self, FormatterError> {
let comments_context =
CommentsContext::new(CommentMap::from_src(Arc::from(src))?, src.to_string());
self.comments_context = comments_context;
self
Ok(self)
}

pub fn format(
Expand All @@ -88,7 +86,7 @@ impl Formatter {
// which will reduce the number of reallocations
let mut raw_formatted_code = String::with_capacity(src.len());

self.with_comments_context(src);
self.with_comments_context(src)?;

let module = parse_file(&self.source_engine, Arc::from(src), path.clone())?.value;
module.format(&mut raw_formatted_code, self)?;
Expand Down
10 changes: 6 additions & 4 deletions swayfmt/src/parse.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{error::ParseFileError, Formatter};
use crate::{error::ParseFileError, Formatter, FormatterError};
use std::path::PathBuf;
use std::sync::Arc;
use sway_ast::{attribute::Annotated, token::CommentedTokenStream, Module};
Expand Down Expand Up @@ -29,7 +29,9 @@ pub fn lex(input: &Arc<str>) -> Result<CommentedTokenStream, ParseFileError> {
with_handler(|h| sway_parse::lex_commented(h, input, 0, input.len(), &None))
}

pub fn parse_format<P: sway_parse::Parse + crate::Format>(input: &str) -> String {
pub fn parse_format<P: sway_parse::Parse + crate::Format>(
input: &str,
) -> Result<String, FormatterError> {
let parsed = with_handler(|handler| {
let token_stream = sway_parse::lex(handler, &input.into(), 0, input.len(), None)?;
sway_parse::Parser::new(handler, &token_stream).parse::<P>()
Expand All @@ -38,11 +40,11 @@ pub fn parse_format<P: sway_parse::Parse + crate::Format>(input: &str) -> String

// Allow test cases that include comments.
let mut formatter = Formatter::default();
formatter.with_comments_context(input);
formatter.with_comments_context(input)?;

let mut buf = <_>::default();
parsed.format(&mut buf, &mut formatter).unwrap();
buf
Ok(buf)
}

/// Partially parses an AST node that implements sway_parse::Parse.
Expand Down
2 changes: 1 addition & 1 deletion swayfmt/test_macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ macro_rules! fmt_test_inner {
paste! {
#[test]
fn [<$scope _ $name>] () {
let formatted_code = crate::parse::parse_format::<$ty>($y);
let formatted_code = crate::parse::parse_format::<$ty>($y).unwrap();
let changeset = diff_lines(&formatted_code, $desired_output);
let count_of_updates = changeset.diff().len();
if count_of_updates != 0 {
Expand Down
Loading