Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 23 additions & 12 deletions crates/core/src/source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,36 +37,46 @@ impl Files {
pub struct Source {
s: String,
indent: usize,
in_line_comment: bool,
}

impl Source {
pub fn append_src(&mut self, src: &Source) {
self.s.push_str(&src.s);
self.indent += src.indent;
self.in_line_comment = src.in_line_comment;
}

pub fn push_str(&mut self, src: &str) {
let lines = src.lines().collect::<Vec<_>>();
for (i, line) in lines.iter().enumerate() {
let trimmed = line.trim();
if trimmed.starts_with('}') && self.s.ends_with(" ") {
self.s.pop();
self.s.pop();
if trimmed.starts_with("//") {
self.in_line_comment = true;
}

if !self.in_line_comment {
if trimmed.starts_with('}') && self.s.ends_with(" ") {
self.s.pop();
self.s.pop();
}
}
self.s.push_str(if lines.len() == 1 {
line
} else {
line.trim_start()
});
if trimmed.ends_with('{') {
self.indent += 1;
}
if trimmed.starts_with('}') {
// Note that a `saturating_sub` is used here to prevent a panic
// here in the case of invalid code being generated in debug
// mode. It's typically easier to debug those issues through
// looking at the source code rather than getting a panic.
self.indent = self.indent.saturating_sub(1);
if !self.in_line_comment {
if trimmed.ends_with('{') {
self.indent += 1;
}
if trimmed.starts_with('}') {
// Note that a `saturating_sub` is used here to prevent a panic
// here in the case of invalid code being generated in debug
// mode. It's typically easier to debug those issues through
// looking at the source code rather than getting a panic.
self.indent = self.indent.saturating_sub(1);
}
}
if i != lines.len() - 1 || src.ends_with('\n') {
self.newline();
Expand All @@ -83,6 +93,7 @@ impl Source {
}

fn newline(&mut self) {
self.in_line_comment = false;
self.s.push('\n');
for _ in 0..self.indent {
self.s.push_str(" ");
Expand Down
1 change: 0 additions & 1 deletion crates/go/src/interface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1073,7 +1073,6 @@ impl<'a> wit_bindgen_core::InterfaceGenerator<'a> for InterfaceGenerator<'a> {
self.preamble
.push_str(&format!("// typedef struct {c_typedef_target} "));
self.preamble.push_str("{");
self.preamble.deindent(1);
self.preamble.push_str("\n");
self.preamble.push_str("// int32_t __handle; \n");
self.preamble.push_str("// ");
Expand Down