diff options
Diffstat (limited to 'src')
47 files changed, 617 insertions, 324 deletions
diff --git a/src/apply-names.cc b/src/apply-names.cc index b7db07db..619a1026 100644 --- a/src/apply-names.cc +++ b/src/apply-names.cc @@ -97,13 +97,15 @@ string_view NameApplier::FindLabelByVar(Var* var) { if (var->is_name()) { for (int i = labels_.size() - 1; i >= 0; --i) { const std::string& label = labels_[i]; - if (label == var->name()) + if (label == var->name()) { return label; + } } return string_view(); } else { - if (var->index() >= labels_.size()) + if (var->index() >= labels_.size()) { return string_view(); + } return labels_[labels_.size() - 1 - var->index()]; } } @@ -114,62 +116,70 @@ void NameApplier::UseNameForVar(string_view name, Var* var) { return; } - if (!name.empty()) + if (!name.empty()) { var->set_name(name); + } } Result NameApplier::UseNameForFuncTypeVar(Var* var) { FuncType* func_type = module_->GetFuncType(*var); - if (!func_type) + if (!func_type) { return Result::Error; + } UseNameForVar(func_type->name, var); return Result::Ok; } Result NameApplier::UseNameForFuncVar(Var* var) { Func* func = module_->GetFunc(*var); - if (!func) + if (!func) { return Result::Error; + } UseNameForVar(func->name, var); return Result::Ok; } Result NameApplier::UseNameForGlobalVar(Var* var) { Global* global = module_->GetGlobal(*var); - if (!global) + if (!global) { return Result::Error; + } UseNameForVar(global->name, var); return Result::Ok; } Result NameApplier::UseNameForTableVar(Var* var) { Table* table = module_->GetTable(*var); - if (!table) + if (!table) { return Result::Error; + } UseNameForVar(table->name, var); return Result::Ok; } Result NameApplier::UseNameForMemoryVar(Var* var) { Memory* memory = module_->GetMemory(*var); - if (!memory) + if (!memory) { return Result::Error; + } UseNameForVar(memory->name, var); return Result::Ok; } Result NameApplier::UseNameForExceptVar(Var* var) { Exception* except = module_->GetExcept(*var); - if (!except) + if (!except) { return Result::Error; + } UseNameForVar(except->name, var); return Result::Ok; } Result NameApplier::UseNameForParamAndLocalVar(Func* func, Var* var) { Index local_index = func->GetLocalIndex(*var); - if (local_index >= func->GetNumParamsAndLocals()) + if (local_index >= func->GetNumParamsAndLocals()) { return Result::Error; + } Index num_params = func->GetNumParams(); std::string* name; @@ -272,8 +282,9 @@ Result NameApplier::OnCallExpr(CallExpr* expr) { } Result NameApplier::OnCallIndirectExpr(CallIndirectExpr* expr) { - if (expr->decl.has_func_type) + if (expr->decl.has_func_type) { CHECK_RESULT(UseNameForFuncTypeVar(&expr->decl.type_var)); + } return Result::Ok; } diff --git a/src/binary-reader-interp.cc b/src/binary-reader-interp.cc index 884ffe58..cfe2b041 100644 --- a/src/binary-reader-interp.cc +++ b/src/binary-reader-interp.cc @@ -446,8 +446,9 @@ wabt::Result BinaryReaderInterp::EmitDropKeep(uint32_t drop, uint8_t keep) { wabt::Result BinaryReaderInterp::AppendFixup( IstreamOffsetVectorVector* fixups_vector, Index index) { - if (index >= fixups_vector->size()) + if (index >= fixups_vector->size()) { fixups_vector->resize(index + 1); + } (*fixups_vector)[index].push_back(GetIstreamOffset()); return wabt::Result::Ok; } @@ -1025,8 +1026,9 @@ wabt::Result BinaryReaderInterp::OnDataSegmentData(Index index, return wabt::Result::Error; } - if (size > 0) + if (size > 0) { data_segment_infos_.emplace_back(&memory->data[address], src_data, size); + } return wabt::Result::Ok; } diff --git a/src/binary-reader-ir.cc b/src/binary-reader-ir.cc index 1ef8209b..63af3f0d 100644 --- a/src/binary-reader-ir.cc +++ b/src/binary-reader-ir.cc @@ -868,8 +868,9 @@ Result BinaryReaderIR::OnDataSegmentData(Index index, assert(index == module_->data_segments.size() - 1); DataSegment* segment = module_->data_segments[index]; segment->data.resize(size); - if (size > 0) + if (size > 0) { memcpy(segment->data.data(), data, size); + } return Result::Ok; } @@ -884,8 +885,9 @@ Result BinaryReaderIR::OnFunctionNamesCount(Index count) { } Result BinaryReaderIR::OnFunctionName(Index index, string_view name) { - if (name.empty()) + if (name.empty()) { return Result::Ok; + } Func* func = module_->funcs[index]; std::string dollar_name = std::string("$") + name.to_string(); @@ -951,8 +953,9 @@ Result BinaryReaderIR::OnInitExprI64ConstExpr(Index index, uint64_t value) { Result BinaryReaderIR::OnLocalName(Index func_index, Index local_index, string_view name) { - if (name.empty()) + if (name.empty()) { return Result::Ok; + } Func* func = module_->funcs[func_index]; Index num_params = func->GetNumParams(); diff --git a/src/binary-reader-linker.cc b/src/binary-reader-linker.cc index 0af95304..a0c63882 100644 --- a/src/binary-reader-linker.cc +++ b/src/binary-reader-linker.cc @@ -105,8 +105,9 @@ Result BinaryReaderLinker::OnRelocCount(Index count, } for (const std::unique_ptr<Section>& section : binary_->sections) { - if (section->section_code != section_code) + if (section->section_code != section_code) { continue; + } reloc_section_ = section.get(); return Result::Ok; } @@ -189,8 +190,9 @@ Result BinaryReaderLinker::BeginSection(BinarySection section_code, // Must point to one-past-the-end, but we can't dereference end(). const uint8_t* end = &binary_->data.back() + 1; size_t bytes_read = ReadU32Leb128(start, end, &sec->count); - if (bytes_read == 0) + if (bytes_read == 0) { WABT_FATAL("error reading section element count\n"); + } sec->payload_offset = sec->offset + bytes_read; sec->payload_size = sec->size - bytes_read; } @@ -200,8 +202,9 @@ Result BinaryReaderLinker::BeginSection(BinarySection section_code, Result BinaryReaderLinker::OnTable(Index index, Type elem_type, const Limits* elem_limits) { - if (elem_limits->has_max && (elem_limits->max != elem_limits->initial)) + if (elem_limits->has_max && (elem_limits->max != elem_limits->initial)) { WABT_FATAL("Tables with max != initial not supported by wabt-link\n"); + } binary_->table_elem_count = elem_limits->initial; return Result::Ok; @@ -238,8 +241,9 @@ Result BinaryReaderLinker::BeginDataSegment(Index index, Index memory_index) { Result BinaryReaderLinker::OnInitExprI32ConstExpr(Index index, uint32_t value) { Section* sec = current_section_; - if (sec->section_code != BinarySection::Data) + if (sec->section_code != BinarySection::Data) { return Result::Ok; + } DataSegment& segment = sec->data.data_segments->back(); segment.offset = value; return Result::Ok; diff --git a/src/binary-reader-logging.cc b/src/binary-reader-logging.cc index a5e6b985..236a62cf 100644 --- a/src/binary-reader-logging.cc +++ b/src/binary-reader-logging.cc @@ -80,8 +80,9 @@ void BinaryReaderLogging::LogTypes(Index type_count, Type* types) { LOGF_NOINDENT("["); for (Index i = 0; i < type_count; ++i) { LOGF_NOINDENT("%s", GetTypeName(types[i])); - if (i != type_count - 1) + if (i != type_count - 1) { LOGF_NOINDENT(", "); + } } LOGF_NOINDENT("]"); } @@ -276,8 +277,9 @@ Result BinaryReaderLogging::OnBrTableExpr(Index num_targets, LOGF("OnBrTableExpr(num_targets: %" PRIindex ", depths: [", num_targets); for (Index i = 0; i < num_targets; ++i) { LOGF_NOINDENT("%" PRIindex, target_depths[i]); - if (i != num_targets - 1) + if (i != num_targets - 1) { LOGF_NOINDENT(", "); + } } LOGF_NOINDENT("], default: %" PRIindex ")\n", default_target_depth); return reader_->OnBrTableExpr(num_targets, target_depths, diff --git a/src/binary-reader-objdump.cc b/src/binary-reader-objdump.cc index cef44c18..cf3bdc91 100644 --- a/src/binary-reader-objdump.cc +++ b/src/binary-reader-objdump.cc @@ -117,8 +117,9 @@ Result BinaryReaderObjdumpBase::BeginModule(uint32_t version) { const char* BinaryReaderObjdumpBase::GetFunctionName(Index index) const { if (index >= objdump_state_->function_names.size() || - objdump_state_->function_names[index].empty()) + objdump_state_->function_names[index].empty()) { return nullptr; + } return objdump_state_->function_names[index].c_str(); } @@ -248,8 +249,9 @@ void BinaryReaderObjdumpDisassemble::LogOpcode(const uint8_t* data, // Print binary data printf(" %06" PRIzx ":", offset - 1); - if (current_opcode.HasPrefix()) + if (current_opcode.HasPrefix()) { printf(" %02x", current_opcode.GetPrefix()); + } printf(" %02x", current_opcode.GetCode()); for (size_t i = 0; i < data_size && i < IMMEDIATE_OCTET_COUNT; i++, offset++) { @@ -309,10 +311,11 @@ Result BinaryReaderObjdumpDisassemble::OnOpcodeBare() { Result BinaryReaderObjdumpDisassemble::OnOpcodeIndex(Index value) { Offset immediate_len = state->offset - current_opcode_offset; const char* name; - if (current_opcode == Opcode::Call && (name = GetFunctionName(value))) + if (current_opcode == Opcode::Call && (name = GetFunctionName(value))) { LogOpcode(data_, immediate_len, "%d <%s>", value, name); - else + } else { LogOpcode(data_, immediate_len, "%d", value); + } return Result::Ok; } @@ -375,10 +378,11 @@ Result BinaryReaderObjdumpDisassemble::OnEndExpr() { Result BinaryReaderObjdumpDisassemble::BeginFunctionBody(Index index) { const char* name = GetFunctionName(index); - if (name) + if (name) { printf("%06" PRIzx " <%s>:\n", state->offset, name); - else + } else { printf("%06" PRIzx " func[%" PRIindex "]:\n", state->offset, index); + } last_opcode_end = 0; return Result::Ok; @@ -406,10 +410,11 @@ const char* type_name(Type type) { Result BinaryReaderObjdumpDisassemble::OnOpcodeBlockSig(Index num_types, Type* sig_types) { - if (num_types) + if (num_types) { LogOpcode(data_, 1, "%s", type_name(*sig_types)); - else + } else { LogOpcode(data_, 1, nullptr); + } indent_level++; return Result::Ok; } @@ -596,8 +601,9 @@ Result BinaryReaderObjdump::BeginSection(BinarySection section_code, bool section_match = !options_->section_name || !strcasecmp(options_->section_name, name); - if (section_match) + if (section_match) { section_found_ = true; + } switch (options_->mode) { case ObjdumpMode::Headers: @@ -607,8 +613,9 @@ Result BinaryReaderObjdump::BeginSection(BinarySection section_code, break; case ObjdumpMode::Details: if (section_match) { - if (section_code != BinarySection::Code) + if (section_code != BinarySection::Code) { printf("%s:\n", name); + } print_details_ = true; } else { print_details_ = false; @@ -629,15 +636,17 @@ Result BinaryReaderObjdump::BeginSection(BinarySection section_code, } bool BinaryReaderObjdump::ShouldPrintDetails() { - if (options_->mode != ObjdumpMode::Details) + if (options_->mode != ObjdumpMode::Details) { return false; + } return print_details_; } void WABT_PRINTF_FORMAT(2, 3) BinaryReaderObjdump::PrintDetails(const char* fmt, ...) { - if (!ShouldPrintDetails()) + if (!ShouldPrintDetails()) { return; + } va_list args; va_start(args, fmt); vprintf(fmt, args); @@ -676,8 +685,9 @@ Result BinaryReaderObjdump::OnType(Index index, Type* param_types, Index result_count, Type* result_types) { - if (!ShouldPrintDetails()) + if (!ShouldPrintDetails()) { return Result::Ok; + } printf(" - type[%" PRIindex "] (", index); for (Index i = 0; i < param_count; i++) { if (i != 0) { @@ -686,10 +696,11 @@ Result BinaryReaderObjdump::OnType(Index index, printf("%s", type_name(param_types[i])); } printf(") -> "); - if (result_count) + if (result_count) { printf("%s", type_name(result_types[0])); - else + } else { printf("nil"); + } printf("\n"); return Result::Ok; } @@ -700,8 +711,9 @@ Result BinaryReaderObjdump::OnFunctionCount(Index count) { Result BinaryReaderObjdump::OnFunction(Index index, Index sig_index) { PrintDetails(" - func[%" PRIindex "] sig=%" PRIindex, index, sig_index); - if (const char* name = GetFunctionName(index)) + if (const char* name = GetFunctionName(index)) { PrintDetails(" <%s>", name); + } PrintDetails("\n"); return Result::Ok; } @@ -729,8 +741,9 @@ Result BinaryReaderObjdump::OnImportFunc(Index import_index, Index func_index, Index sig_index) { PrintDetails(" - func[%" PRIindex "] sig=%" PRIindex, func_index, sig_index); - if (const char* name = GetFunctionName(func_index)) + if (const char* name = GetFunctionName(func_index)) { PrintDetails(" <%s>", name); + } PrintDetails(" <- " PRIstringview "." PRIstringview "\n", WABT_PRINTF_STRING_VIEW_ARG(module_name), WABT_PRINTF_STRING_VIEW_ARG(field_name)); @@ -760,8 +773,9 @@ Result BinaryReaderObjdump::OnImportMemory(Index import_index, const Limits* page_limits) { PrintDetails(" - memory[%" PRIindex "] pages: initial=%" PRId64, memory_index, page_limits->initial); - if (page_limits->has_max) + if (page_limits->has_max) { PrintDetails(" max=%" PRId64, page_limits->max); + } PrintDetails(" <- " PRIstringview "." PRIstringview "\n", WABT_PRINTF_STRING_VIEW_ARG(module_name), WABT_PRINTF_STRING_VIEW_ARG(field_name)); @@ -807,8 +821,9 @@ Result BinaryReaderObjdump::OnMemoryCount(Index count) { Result BinaryReaderObjdump::OnMemory(Index index, const Limits* page_limits) { PrintDetails(" - memory[%" PRIindex "] pages: initial=%" PRId64, index, page_limits->initial); - if (page_limits->has_max) + if (page_limits->has_max) { PrintDetails(" max=%" PRId64, page_limits->max); + } PrintDetails("\n"); return Result::Ok; } @@ -822,8 +837,9 @@ Result BinaryReaderObjdump::OnTable(Index index, const Limits* elem_limits) { PrintDetails(" - table[%" PRIindex "] type=%s initial=%" PRId64, index, GetTypeName(elem_type), elem_limits->initial); - if (elem_limits->has_max) + if (elem_limits->has_max) { PrintDetails(" max=%" PRId64, elem_limits->max); + } PrintDetails("\n"); return Result::Ok; } @@ -838,8 +854,9 @@ Result BinaryReaderObjdump::OnExport(Index index, string_view name) { PrintDetails(" - %s[%" PRIindex "]", GetKindName(kind), item_index); if (kind == ExternalKind::Func) { - if (const char* name = GetFunctionName(item_index)) + if (const char* name = GetFunctionName(item_index)) { PrintDetails(" <%s>", name); + } } PrintDetails(" -> \"" PRIstringview "\"\n", @@ -851,8 +868,9 @@ Result BinaryReaderObjdump::OnElemSegmentFunctionIndex(Index segment_index, Index func_index) { PrintDetails(" - elem[%" PRIindex "] = func[%" PRIindex "]", elem_index_, func_index); - if (const char* name = GetFunctionName(func_index)) + if (const char* name = GetFunctionName(func_index)) { PrintDetails(" <%s>", name); + } PrintDetails("\n"); elem_index_++; return Result::Ok; @@ -1000,8 +1018,9 @@ Result BinaryReaderObjdump::BeginDataSegment(Index index, Index memory_index) { Result BinaryReaderObjdump::OnDataSegmentData(Index index, const void* src_data, Address size) { - if (!ShouldPrintDetails()) + if (!ShouldPrintDetails()) { return Result::Ok; + } PrintDetails(" - segment[%" PRIindex "] size=%" PRIaddress, index, size); PrintInitExpr(data_init_expr_); @@ -1025,8 +1044,9 @@ Result BinaryReaderObjdump::OnDataSegmentData(Index index, " - "); // Print relocations from this segment. - if (!options_->relocs) + if (!options_->relocs) { return Result::Ok; + } Offset data_start = GetSectionStart(BinarySection::Data); Offset segment_start = state->offset - size; @@ -1034,8 +1054,9 @@ Result BinaryReaderObjdump::OnDataSegmentData(Index index, while (next_data_reloc_ < objdump_state_->data_relocations.size()) { const Reloc& reloc = objdump_state_->data_relocations[next_data_reloc_]; Offset abs_offset = data_start + reloc.offset; - if (abs_offset > state->offset) + if (abs_offset > state->offset) { break; + } PrintRelocation(reloc, reloc.offset - segment_offset + voffset); next_data_reloc_++; } @@ -1122,8 +1143,9 @@ Result BinaryReaderObjdump::OnExceptionCount(Index count) { } Result BinaryReaderObjdump::OnExceptionType(Index index, TypeVector& sig) { - if (!ShouldPrintDetails()) + if (!ShouldPrintDetails()) { return Result::Ok; + } printf(" - except[%" PRIindex "] (", index); for (Index i = 0; i < sig.size(); ++i) { if (i != 0) { diff --git a/src/binary-reader-opcnt.cc b/src/binary-reader-opcnt.cc index e7ab6f32..72a4fdc9 100644 --- a/src/binary-reader-opcnt.cc +++ b/src/binary-reader-opcnt.cc @@ -143,12 +143,12 @@ bool operator!=(const OpcodeInfo& lhs, const OpcodeInfo& rhs) { } bool operator<(const OpcodeInfo& lhs, const OpcodeInfo& rhs) { - if (lhs.opcode_ < rhs.opcode_) return true; - if (lhs.opcode_ > rhs.opcode_) return false; - if (lhs.kind_ < rhs.kind_) return true; - if (lhs.kind_ > rhs.kind_) return false; - if (lhs.data_ < rhs.data_) return true; - if (lhs.data_ > rhs.data_) return false; + if (lhs.opcode_ < rhs.opcode_) { return true; } + if (lhs.opcode_ > rhs.opcode_) { return false; } + if (lhs.kind_ < rhs.kind_) { return true; } + if (lhs.kind_ > rhs.kind_) { return false; } + if (lhs.data_ < rhs.data_) { return true; } + if (lhs.data_ > rhs.data_) { return false; } return false; } diff --git a/src/binary-reader.cc b/src/binary-reader.cc index 1aeef2af..f2250e64 100644 --- a/src/binary-reader.cc +++ b/src/binary-reader.cc @@ -44,10 +44,11 @@ } \ } while (0) -#define ERROR_UNLESS_OPCODE_ENABLED(opcode) \ - do { \ - if (!opcode.IsEnabled(options_->features)) \ - return ReportUnexpectedOpcode(opcode); \ +#define ERROR_UNLESS_OPCODE_ENABLED(opcode) \ + do { \ + if (!opcode.IsEnabled(options_->features)) { \ + return ReportUnexpectedOpcode(opcode); \ + } \ } while (0) #define CALLBACK0(member) \ @@ -176,8 +177,9 @@ void WABT_PRINTF_FORMAT(2, 3) BinaryReader::PrintError(const char* format, Result BinaryReader::ReportUnexpectedOpcode(Opcode opcode, const char* message) { const char* maybe_space = " "; - if (!message) + if (!message) { message = maybe_space = ""; + } if (opcode.HasPrefix()) { PrintError("unexpected opcode%s%s: %d %d (0x%x 0x%x)", maybe_space, message, opcode.GetPrefix(), opcode.GetCode(), opcode.GetPrefix(), @@ -1202,8 +1204,9 @@ Result BinaryReader::ReadRelocSection(Offset section_size) { uint32_t section; CHECK_RESULT(ReadU32Leb128(§ion, "section")); string_view section_name; - if (static_cast<BinarySection>(section) == BinarySection::Custom) + if (static_cast<BinarySection>(section) == BinarySection::Custom) { CHECK_RESULT(ReadStr(§ion_name, "section name")); + } Index num_relocs; CHECK_RESULT(ReadIndex(&num_relocs, "relocation count")); CALLBACK(OnRelocCount, num_relocs, static_cast<BinarySection>(section), @@ -1755,8 +1758,9 @@ Result BinaryReader::ReadSections() { ERROR_UNLESS(state_.offset == read_end_, "unfinished section (expected end: 0x%" PRIzx ")", read_end_); - if (section != BinarySection::Custom) + if (section != BinarySection::Custom) { last_known_section_ = section; + } } return result; diff --git a/src/binary-writer-spec.cc b/src/binary-writer-spec.cc index 5e4f95ab..334945ba 100644 --- a/src/binary-writer-spec.cc +++ b/src/binary-writer-spec.cc @@ -142,10 +142,11 @@ void BinaryWriterSpec::WriteLocation(const Location& loc) { } void BinaryWriterSpec::WriteVar(const Var& var) { - if (var.is_index()) + if (var.is_index()) { json_stream_.Writef("\"%" PRIindex "\"", var.index()); - else + } else { WriteEscapedString(var.name()); + } } void BinaryWriterSpec::WriteTypeObject(Type type) { @@ -206,8 +207,9 @@ void BinaryWriterSpec::WriteConstVector(const ConstVector& consts) { for (size_t i = 0; i < consts.size(); ++i) { const Const& const_ = consts[i]; WriteConst(const_); - if (i != consts.size() - 1) + if (i != consts.size() - 1) { WriteSeparator(); + } } json_stream_.Writef("]"); } @@ -272,8 +274,9 @@ void BinaryWriterSpec::WriteModule(string_view filename, const Module& module) { MemoryStream memory_stream(spec_options_->log_stream); result_ = WriteBinaryModule(&memory_stream, &module, &spec_options_->write_binary_options); - if (Succeeded(result_) && write_modules_) + if (Succeeded(result_) && write_modules_) { result_ = memory_stream.WriteToFile(filename); + } } void BinaryWriterSpec::WriteScriptModule(string_view filename, diff --git a/src/binary-writer.cc b/src/binary-writer.cc index 5fe5a9e3..730e27b6 100644 --- a/src/binary-writer.cc +++ b/src/binary-writer.cc @@ -63,8 +63,9 @@ void WriteLimits(Stream* stream, const Limits* limits) { flags |= limits->is_shared ? WABT_BINARY_LIMITS_IS_SHARED_FLAG : 0; WriteU32Leb128(stream, flags, "limits: flags"); WriteU32Leb128(stream, limits->initial, "limits: initial"); - if (limits->has_max) + if (limits->has_max) { WriteU32Leb128(stream, limits->max, "limits: max"); + } } void WriteDebugName(Stream* stream, string_view name, const char* desc) { @@ -909,8 +910,9 @@ Result BinaryWriter::WriteModule(const Module* module) { size_t named_functions = 0; for (const Func* func : module->funcs) { - if (!func->name.empty()) + if (!func->name.empty()) { named_functions++; + } } if (named_functions > 0) { @@ -920,8 +922,9 @@ Result BinaryWriter::WriteModule(const Module* module) { WriteU32Leb128(stream_, named_functions, "num functions"); for (size_t i = 0; i < module->funcs.size(); ++i) { const Func* func = module->funcs[i]; - if (func->name.empty()) + if (func->name.empty()) { continue; + } WriteU32Leb128(stream_, i, "function index"); wabt_snprintf(desc, sizeof(desc), "func name %" PRIzd, i); WriteDebugName(stream_, func->name, desc); diff --git a/src/binding-hash.cc b/src/binding-hash.cc index 68bbc424..f52682d7 100644 --- a/src/binding-hash.cc +++ b/src/binding-hash.cc @@ -33,8 +33,9 @@ void BindingHash::FindDuplicates(DuplicateCallback callback) const { } Index BindingHash::FindIndex(const Var& var) const { - if (var.is_name()) + if (var.is_name()) { return FindIndex(var.name()); + } return var.index(); } @@ -46,8 +47,9 @@ void BindingHash::CreateDuplicatesVector( bool is_first = true; for (auto iter = std::next(first); iter != end(); ++iter) { if (first->first == iter->first) { - if (is_first) + if (is_first) { out_duplicates->push_back(&*first); + } out_duplicates->push_back(&*iter); is_first = false; } else { @@ -78,8 +80,9 @@ void BindingHash::CallCallbacks(const ValueTypeVector& duplicates, [iter](const value_type* x) -> bool { return x->first == (*iter)->first; }); - if (first == iter) + if (first == iter) { continue; + } assert(first != duplicates.end()); callback(**first, **iter); } diff --git a/src/common.cc b/src/common.cc index d26783a1..4516ec37 100644 --- a/src/common.cc +++ b/src/common.cc @@ -88,11 +88,13 @@ Result ReadFile(string_view filename, std::vector<uint8_t>* out_data) { void InitStdio() { #if COMPILER_IS_MSVC int result = _setmode(_fileno(stdout), _O_BINARY); - if (result == -1) + if (result == -1) { perror("Cannot set mode binary to stdout"); + } result = _setmode(_fileno(stderr), _O_BINARY); - if (result == -1) + if (result == -1) { perror("Cannot set mode binary to stderr"); + } #endif } diff --git a/src/config.cc b/src/config.cc index 34ebd3d7..7433f209 100644 --- a/src/config.cc +++ b/src/config.cc @@ -25,10 +25,12 @@ #if COMPILER_IS_MSVC int wabt_vsnprintf(char* str, size_t size, const char* format, va_list ap) { int result = -1; - if (size != 0) + if (size != 0) { result = _vsnprintf_s(str, size, _TRUNCATE, format, ap); - if (result == -1) + } + if (result == -1) { result = _vscprintf(format, ap); + } return result; } diff --git a/src/error-handler.cc b/src/error-handler.cc index da61230e..7c70281f 100644 --- a/src/error-handler.cc +++ b/src/error-handler.cc @@ -103,8 +103,9 @@ bool ErrorHandlerFile::OnError(const Location& loc, } void ErrorHandlerFile::PrintErrorHeader() { - if (header_.empty()) + if (header_.empty()) { return; + } switch (print_header_) { case PrintHeader::Never: diff --git a/src/filenames.cc b/src/filenames.cc index a1e53aa9..989453c7 100644 --- a/src/filenames.cc +++ b/src/filenames.cc @@ -29,12 +29,14 @@ string_view StripExtension(string_view filename) { string_view GetBasename(string_view filename) { size_t last_slash = filename.find_last_of('/'); size_t last_backslash = filename.find_last_of('\\'); - if (last_slash == string_view::npos && last_backslash == string_view::npos) + if (last_slash == string_view::npos && last_backslash == string_view::npos) { return filename; + } if (last_slash == string_view::npos) { - if (last_backslash == string_view::npos) + if (last_backslash == string_view::npos) { return filename; + } last_slash = last_backslash; } else if (last_backslash != string_view::npos) { last_slash = std::max(last_slash, last_backslash); @@ -45,8 +47,9 @@ string_view GetBasename(string_view filename) { string_view GetExtension(string_view filename) { size_t pos = filename.find_last_of('.'); - if (pos == string_view::npos) + if (pos == string_view::npos) { return ""; + } return filename.substr(pos); } diff --git a/src/generate-names.cc b/src/generate-names.cc index 71601787..451cb3b6 100644 --- a/src/generate-names.cc +++ b/src/generate-names.cc @@ -113,10 +113,12 @@ void NameGenerator::GenerateName(const char* prefix, unsigned disambiguator, std::string* str) { *str = prefix; - if (index != kInvalidIndex) + if (index != kInvalidIndex) { *str += std::to_string(index); - if (disambiguator != 0) + } + if (disambiguator != 0) { *str += '_' + std::to_string(disambiguator); + } } // static @@ -152,8 +154,9 @@ void NameGenerator::MaybeGenerateAndBindName(BindingHash* bindings, const char* prefix, Index index, std::string* str) { - if (!HasName(*str)) + if (!HasName(*str)) { GenerateAndBindName(bindings, prefix, index, str); + } } // static @@ -179,8 +182,9 @@ void NameGenerator::GenerateAndBindLocalNames(BindingHash* bindings, const char* prefix) { for (size_t i = 0; i < index_to_name_.size(); ++i) { const std::string& old_name = index_to_name_[i]; - if (!old_name.empty()) + if (!old_name.empty()) { continue; + } std::string new_name; GenerateAndBindName(bindings, prefix, i, &new_name); diff --git a/src/interp.cc b/src/interp.cc index b5414b82..b0056c86 100644 --- a/src/interp.cc +++ b/src/interp.cc @@ -33,10 +33,11 @@ namespace interp { // Differs from the normal CHECK_RESULT because this one is meant to return the // interp Result type. #undef CHECK_RESULT -#define CHECK_RESULT(expr) \ - do { \ - if (WABT_FAILED(expr)) \ - return Result::Error; \ +#define CHECK_RESULT(expr) \ + do { \ + if (WABT_FAILED(expr)) { \ + return Result::Error; \ + } \ } while (0) // Differs from CHECK_RESULT since it can return different traps, not just @@ -83,8 +84,9 @@ void WriteTypedValue(Stream* stream, const TypedValue& tv) { void WriteTypedValues(Stream* stream, const TypedValues& values) { for (size_t i = 0; i < values.size(); ++i) { WriteTypedValue(stream, values[i]); - if (i != values.size() - 1) + if (i != values.size() - 1) { stream->Writef(", "); + } } } @@ -106,8 +108,9 @@ void WriteCall(Stream* stream, const TypedValues& args, const TypedValues& results, Result result) { - if (!module_name.empty()) + if (!module_name.empty()) { stream->Writef(PRIstringview ".", WABT_PRINTF_STRING_VIEW_ARG(module_name)); + } stream->Writef(PRIstringview "(", WABT_PRINTF_STRING_VIEW_ARG(func_name)); WriteTypedValues(stream, args); stream->Writef(") =>"); @@ -126,8 +129,9 @@ Environment::Environment() : istream_(new OutputBuffer()) {} Index Environment::FindModuleIndex(string_view name) const { auto iter = module_bindings_.find(name.to_string()); - if (iter == module_bindings_.end()) + if (iter == module_bindings_.end()) { return kInvalidIndex; + } return iter->second.index; } @@ -138,8 +142,9 @@ Module* Environment::FindModule(string_view name) { Module* Environment::FindRegisteredModule(string_view name) { auto iter = registered_module_bindings_.find(name.to_string()); - if (iter == registered_module_bindings_.end()) + if (iter == registered_module_bindings_.end()) { return nullptr; + } return modules_[iter->second.index].get(); } @@ -173,8 +178,9 @@ Module::Module(string_view name, bool is_host) Export* Module::GetExport(string_view name) { int field_index = export_bindings.FindIndex(name); - if (field_index < 0) + if (field_index < 0) { return nullptr; + } return &exports[field_index]; } @@ -202,18 +208,20 @@ void Environment::ResetToMarkPoint(const MarkPoint& mark) { // Destroy entries in the binding hash. for (size_t i = mark.modules_size; i < modules_.size(); ++i) { std::string name = modules_[i]->name; - if (!name.empty()) + if (!name.empty()) { module_bindings_.erase(name); + } } // registered_module_bindings_ maps from an arbitrary name to a module index, // so we have to iterate through the entire table to find entries to remove. auto iter = registered_module_bindings_.begin(); while (iter != registered_module_bindings_.end()) { - if (iter->second.index >= mark.modules_size) + if (iter->second.index >= mark.modules_size) { iter = registered_module_bindings_.erase(iter); - else + } else { ++iter; + } } modules_.erase(modules_.begin() + mark.modules_size, modules_.end()); @@ -542,10 +550,11 @@ template<> uint64_t GetValue<double>(Value v) { return v.f64_bits; } #define TRAP(type) return Result::Trap##type #define TRAP_UNLESS(cond, type) TRAP_IF(!(cond), type) -#define TRAP_IF(cond, type) \ - do { \ - if (WABT_UNLIKELY(cond)) \ - TRAP(type); \ +#define TRAP_IF(cond, type) \ + do { \ + if (WABT_UNLIKELY(cond)) { \ + TRAP(type); \ + } \ } while (0) #define CHECK_STACK() \ @@ -697,8 +706,9 @@ ValueTypeRep<T> Thread::PopRep() { void Thread::DropKeep(uint32_t drop_count, uint8_t keep_count) { assert(keep_count <= 1); - if (keep_count == 1) + if (keep_count == 1) { Pick(drop_count + 1) = Top(); + } value_stack_top_ -= drop_count; } @@ -1185,8 +1195,9 @@ ValueTypeRep<T> Xchg(ValueTypeRep<T> lhs_rep, ValueTypeRep<T> rhs_rep) { bool Environment::FuncSignaturesAreEqual(Index sig_index_0, Index sig_index_1) const { - if (sig_index_0 == sig_index_1) + if (sig_index_0 == sig_index_1) { return true; + } const FuncSignature* sig_0 = &sigs_[sig_index_0]; const FuncSignature* sig_1 = &sigs_[sig_index_1]; return sig_0->param_types == sig_1->param_types && @@ -1244,8 +1255,9 @@ Result Thread::Run(int num_instructions) { case Opcode::BrIf: { IstreamOffset new_pc = ReadU32(&pc); - if (Pop<uint32_t>()) + if (Pop<uint32_t>()) { GOTO(new_pc); + } break; } @@ -2161,8 +2173,9 @@ Result Thread::Run(int num_instructions) { case Opcode::InterpBrUnless: { IstreamOffset new_pc = ReadU32(&pc); - if (!Pop<uint32_t>()) + if (!Pop<uint32_t>()) { GOTO(new_pc); + } break; } @@ -2666,8 +2679,9 @@ void Environment::Disassemble(Stream* stream, IstreamOffset to) { /* TODO(binji): mark function entries */ /* TODO(binji): track value stack size */ - if (from >= istream_->data.size()) + if (from >= istream_->data.size()) { return; + } to = std::min<IstreamOffset>(to, istream_->data.size()); const uint8_t* istream = istream_->data.data(); const uint8_t* pc = &istream[from]; @@ -3093,8 +3107,9 @@ ExecResult Executor::RunFunction(Index func_index, const TypedValues& args) { exec_result.result = func->is_host ? thread_.CallHost(cast<HostFunc>(func)) : RunDefinedFunction(cast<DefinedFunc>(func)->offset); - if (exec_result.result == Result::Ok) + if (exec_result.result == Result::Ok) { CopyResults(sig, &exec_result.values); + } } thread_.Reset(); @@ -3102,8 +3117,9 @@ ExecResult Executor::RunFunction(Index func_index, const TypedValues& args) { } ExecResult Executor::RunStartFunction(DefinedModule* module) { - if (module->start_func_index == kInvalidIndex) + if (module->start_func_index == kInvalidIndex) { return ExecResult(Result::Ok); + } if (trace_stream_) { trace_stream_->Writef(">>> running start function:\n"); @@ -3129,10 +3145,12 @@ ExecResult Executor::RunExportByName(Module* module, string_view name, const TypedValues& args) { Export* export_ = module->GetExport(name); - if (!export_) + if (!export_) { return ExecResult(Result::UnknownExport); - if (export_->kind != ExternalKind::Func) + } + if (export_->kind != ExternalKind::Func) { return ExecResult(Result::ExportKindMismatch); + } return RunExport(export_, args); } @@ -3151,19 +3169,22 @@ Result Executor::RunDefinedFunction(IstreamOffset function_offset) { result = thread_.Run(kNumInstructions); } } - if (result != Result::Returned) + if (result != Result::Returned) { return result; + } // Use OK instead of RETURNED for consistency. return Result::Ok; } Result Executor::PushArgs(const FuncSignature* sig, const TypedValues& args) { - if (sig->param_types.size() != args.size()) + if (sig->param_types.size() != args.size()) { return Result::ArgumentTypeMismatch; + } for (size_t i = 0; i < sig->param_types.size(); ++i) { - if (sig->param_types[i] != args[i].type) + if (sig->param_types[i] != args[i].type) { return Result::ArgumentTypeMismatch; + } Result result = thread_.Push(args[i].value); if (result != Result::Ok) { diff --git a/src/intrusive-list.h b/src/intrusive-list.h index 61a6fb1a..38606373 100644 --- a/src/intrusive-list.h +++ b/src/intrusive-list.h @@ -527,10 +527,11 @@ inline typename intrusive_list<T>::iterator intrusive_list<T>::insert( node_p = node.release(); node_p->prev_ = pos->prev_; node_p->next_ = &*pos; - if (pos->prev_) + if (pos->prev_) { pos->prev_->next_ = node_p; - else + } else { first_ = node_p; + } pos->prev_ = node_p; size_++; } @@ -552,15 +553,17 @@ inline std::unique_ptr<T> intrusive_list<T>::extract(iterator pos) { if (first_ == last_) { first_ = last_ = nullptr; } else { - if (node->prev_) + if (node->prev_) { node->prev_->next_ = node->next_; - else + } else { first_ = node->next_; + } - if (node->next_) + if (node->next_) { node->next_->prev_ = node->prev_; - else + } else { last_ = node->prev_; + } } node->next_ = node->prev_ = nullptr; size_--; @@ -82,8 +82,9 @@ bool FuncSignature::operator==(const FuncSignature& rhs) const { const Export* Module::GetExport(string_view name) const { Index index = export_bindings.FindIndex(name); - if (index >= exports.size()) + if (index >= exports.size()) { return nullptr; + } return exports[index]; } @@ -112,16 +113,19 @@ Index Module::GetExceptIndex(const Var& var) const { } Index Func::GetLocalIndex(const Var& var) const { - if (var.is_index()) + if (var.is_index()) { return var.index(); + } Index result = param_bindings.FindIndex(var); - if (result != kInvalidIndex) + if (result != kInvalidIndex) { return result; + } result = local_bindings.FindIndex(var); - if (result == kInvalidIndex) + if (result == kInvalidIndex) { return result; + } // The locals start after all the params. return decl.GetNumParams() + result; @@ -133,8 +137,9 @@ const Func* Module::GetFunc(const Var& var) const { Func* Module::GetFunc(const Var& var) { Index index = func_bindings.FindIndex(var); - if (index >= funcs.size()) + if (index >= funcs.size()) { return nullptr; + } return funcs[index]; } @@ -144,29 +149,33 @@ const Global* Module::GetGlobal(const Var& var) const { Global* Module::GetGlobal(const Var& var) { Index index = global_bindings.FindIndex(var); - if (index >= globals.size()) + if (index >= globals.size()) { return nullptr; + } return globals[index]; } Table* Module::GetTable(const Var& var) { Index index = table_bindings.FindIndex(var); - if (index >= tables.size()) + if (index >= tables.size()) { return nullptr; + } return tables[index]; } Memory* Module::GetMemory(const Var& var) { Index index = memory_bindings.FindIndex(var); - if (index >= memories.size()) + if (index >= memories.size()) { return nullptr; + } return memories[index]; } Exception* Module::GetExcept(const Var& var) const { Index index = GetExceptIndex(var); - if (index >= excepts.size()) + if (index >= excepts.size()) { return nullptr; + } return excepts[index]; } @@ -176,16 +185,19 @@ const FuncType* Module::GetFuncType(const Var& var) const { FuncType* Module::GetFuncType(const Var& var) { Index index = func_type_bindings.FindIndex(var); - if (index >= func_types.size()) + if (index >= func_types.size()) { return nullptr; + } return func_types[index]; } Index Module::GetFuncTypeIndex(const FuncSignature& sig) const { - for (size_t i = 0; i < func_types.size(); ++i) - if (func_types[i]->sig == sig) + for (size_t i = 0; i < func_types.size(); ++i) { + if (func_types[i]->sig == sig) { return i; + } + } return kInvalidIndex; } @@ -209,8 +221,9 @@ void Module::AppendField(std::unique_ptr<ElemSegmentModuleField> field) { void Module::AppendField(std::unique_ptr<ExceptionModuleField> field) { Exception& except = field->except; - if (!except.name.empty()) + if (!except.name.empty()) { except_bindings.emplace(except.name, Binding(field->loc, excepts.size())); + } excepts.push_back(&except); fields.push_back(std::move(field)); } @@ -225,8 +238,9 @@ void Module::AppendField(std::unique_ptr<ExportModuleField> field) { void Module::AppendField(std::unique_ptr<FuncModuleField> field) { Func& func = field->func; - if (!func.name.empty()) + if (!func.name.empty()) { func_bindings.emplace(func.name, Binding(field->loc, funcs.size())); + } funcs.push_back(&func); fields.push_back(std::move(field)); } @@ -243,8 +257,9 @@ void Module::AppendField(std::unique_ptr<FuncTypeModuleField> field) { void Module::AppendField(std::unique_ptr<GlobalModuleField> field) { Global& global = field->global; - if (!global.name.empty()) + if (!global.name.empty()) { global_bindings.emplace(global.name, Binding(field->loc, globals.size())); + } globals.push_back(&global); fields.push_back(std::move(field)); } @@ -308,16 +323,18 @@ void Module::AppendField(std::unique_ptr<ImportModuleField> field) { } assert(name && bindings && index != kInvalidIndex); - if (!name->empty()) + if (!name->empty()) { bindings->emplace(*name, Binding(field->loc, index)); + } imports.push_back(import); fields.push_back(std::move(field)); } void Module::AppendField(std::unique_ptr<MemoryModuleField> field) { Memory& memory = field->memory; - if (!memory.name.empty()) + if (!memory.name.empty()) { memory_bindings.emplace(memory.name, Binding(field->loc, memories.size())); + } memories.push_back(&memory); fields.push_back(std::move(field)); } @@ -329,8 +346,9 @@ void Module::AppendField(std::unique_ptr<StartModuleField> field) { void Module::AppendField(std::unique_ptr<TableModuleField> field) { Table& table = field->table; - if (!table.name.empty()) + if (!table.name.empty()) { table_bindings.emplace(table.name, Binding(field->loc, tables.size())); + } tables.push_back(&table); fields.push_back(std::move(field)); } @@ -394,16 +412,18 @@ const Module* Script::GetFirstModule() const { Module* Script::GetFirstModule() { for (const std::unique_ptr<Command>& command : commands) { - if (auto* module_command = dyn_cast<ModuleCommand>(command.get())) + if (auto* module_command = dyn_cast<ModuleCommand>(command.get())) { return &module_command->module; + } } return nullptr; } const Module* Script::GetModule(const Var& var) const { Index index = module_bindings.FindIndex(var); - if (index >= commands.size()) + if (index >= commands.size()) { return nullptr; + } auto* command = cast<ModuleCommand>(commands[index].get()); return &command->module; } @@ -476,8 +496,9 @@ void Var::set_name(string_view name) { } void Var::Destroy() { - if (is_name()) + if (is_name()) { Destruct(name_); + } } Const::Const(I32Tag, uint32_t value, const Location& loc_) diff --git a/src/leb128.cc b/src/leb128.cc index 269723df..1f550b05 100644 --- a/src/leb128.cc +++ b/src/leb128.cc @@ -84,8 +84,9 @@ Offset WriteU32Leb128At(Stream* stream, } Offset WriteFixedU32Leb128Raw(uint8_t* data, uint8_t* end, uint32_t value) { - if (end - data < MAX_U32_LEB128_BYTES) + if (end - data < MAX_U32_LEB128_BYTES) { return 0; + } data[0] = (value & 0x7f) | 0x80; data[1] = ((value >> 7) & 0x7f) | 0x80; data[2] = ((value >> 14) & 0x7f) | 0x80; @@ -97,10 +98,11 @@ Offset WriteFixedU32Leb128Raw(uint8_t* data, uint8_t* end, uint32_t value) { static void WriteS32Leb128(Stream* stream, int32_t value, const char* desc) { uint8_t data[MAX_U32_LEB128_BYTES]; Offset length = 0; - if (value < 0) + if (value < 0) { LEB128_LOOP_UNTIL(value == -1 && (byte & 0x40)); - else + } else { LEB128_LOOP_UNTIL(value == 0 && !(byte & 0x40)); + } stream->WriteData(data, length, desc); } @@ -108,10 +110,11 @@ static void WriteS32Leb128(Stream* stream, int32_t value, const char* desc) { static void WriteS64Leb128(Stream* stream, int64_t value, const char* desc) { uint8_t data[MAX_U64_LEB128_BYTES]; Offset length = 0; - if (value < 0) + if (value < 0) { LEB128_LOOP_UNTIL(value == -1 && (byte & 0x40)); - else + } else { LEB128_LOOP_UNTIL(value == 0 && !(byte & 0x40)); + } stream->WriteData(data, length, desc); } @@ -161,8 +164,9 @@ size_t ReadU32Leb128(const uint8_t* p, return 4; } else if (p + 4 < end && (p[4] & 0x80) == 0) { // The top bits set represent values > 32 bits. - if (p[4] & 0xf0) + if (p[4] & 0xf0) { return 0; + } *out_value = LEB128_5(uint32_t); return 5; } else { diff --git a/src/lexer-source-line-finder.cc b/src/lexer-source-line-finder.cc index f71733e8..0936afa4 100644 --- a/src/lexer-source-line-finder.cc +++ b/src/lexer-source-line-finder.cc @@ -50,15 +50,17 @@ Result LexerSourceLineFinder::GetSourceLine(const Location& loc, out_source_line->line += "..."; clamped.start += 3; } - if (has_end_ellipsis) + if (has_end_ellipsis) { clamped.end -= 3; + } std::vector<char> read_line; CHECK_RESULT(source_->ReadRange(clamped, &read_line)); out_source_line->line.append(read_line.begin(), read_line.end()); - if (has_end_ellipsis) + if (has_end_ellipsis) { out_source_line->line += "..."; + } return Result::Ok; } @@ -87,8 +89,9 @@ Result LexerSourceLineFinder::GetLineOffsets(int find_line, while (!IsLineCached(find_line) && !eof_) { CHECK_RESULT(source_->Tell(&buffer_file_offset)); size_t read_size = source_->Fill(buffer.data(), buffer.size()); - if (read_size < buffer.size()) + if (read_size < buffer.size()) { eof_ = true; + } for (auto iter = buffer.begin(), end = iter + read_size; iter < end; ++iter) { @@ -134,8 +137,9 @@ OffsetRange LexerSourceLineFinder::ClampSourceLineOffsets( // the entire range fits, display it all in the center. center_on = (column_range.start + column_range.end) / 2 - 1; } - if (center_on > max_line_length / 2) + if (center_on > max_line_length / 2) { offset_range.start += center_on - max_line_length / 2; + } offset_range.start = std::min(offset_range.start, offset_range.end - max_line_length); offset_range.end = offset_range.start + max_line_length; diff --git a/src/lexer-source.cc b/src/lexer-source.cc index 1d59dd9c..2a64cffb 100644 --- a/src/lexer-source.cc +++ b/src/lexer-source.cc @@ -26,35 +26,40 @@ LexerSourceFile::LexerSourceFile(string_view filename) } LexerSourceFile::~LexerSourceFile() { - if (file_) + if (file_) { fclose(file_); + } } std::unique_ptr<LexerSource> LexerSourceFile::Clone() { std::unique_ptr<LexerSourceFile> result(new LexerSourceFile(filename_)); Offset offset = 0; - if (Failed(Tell(&offset)) || Failed(result->Seek(offset))) + if (Failed(Tell(&offset)) || Failed(result->Seek(offset))) { result.reset(); + } return std::move(result); } Result LexerSourceFile::Tell(Offset* out_offset) { - if (!file_) + if (!file_) { return Result::Error; + } long offset = ftell(file_); - if (offset < 0) + if (offset < 0) { return Result::Error; + } *out_offset = offset; return Result::Ok; } size_t LexerSourceFile::Fill(void* dest, size_t size) { - if (!file_) + if (!file_) { return 0; + } return fread(dest, 1, size, file_); } @@ -67,8 +72,9 @@ Result LexerSourceFile::ReadRange(OffsetRange range, std::vector<char> result(range.size()); if (range.size() > 0) { size_t read_size = Fill(result.data(), range.size()); - if (read_size < range.size()) + if (read_size < range.size()) { result.resize(read_size); + } } CHECK_RESULT(Seek(old_offset)); @@ -78,8 +84,9 @@ Result LexerSourceFile::ReadRange(OffsetRange range, } Result LexerSourceFile::Seek(Offset offset) { - if (!file_) + if (!file_) { return Result::Error; + } int result = fseek(file_, offset, SEEK_SET); return result < 0 ? Result::Error : Result::Ok; diff --git a/src/literal.cc b/src/literal.cc index f63c358f..223f1b5c 100644 --- a/src/literal.cc +++ b/src/literal.cc @@ -116,8 +116,9 @@ bool FloatParser<T>::StringStartsWith(const char* start, const char* end, const char* prefix) { while (start < end && *prefix) { - if (*start != *prefix) + if (*start != *prefix) { return false; + } start++; prefix++; } @@ -188,8 +189,9 @@ typename FloatParser<T>::Uint FloatParser<T>::ShiftAndRoundToNearest( int shift) { assert(shift > 0); // Round ties to even. - if (significand & (Uint(1) << shift)) + if (significand & (Uint(1) << shift)) { significand += Uint(1) << (shift - 1); + } significand >>= shift; return significand; } @@ -220,13 +222,15 @@ Result FloatParser<T>::ParseNan(const char* s, CHECK_RESULT(ParseHexdigit(*s, &digit)); tag = tag * 16 + digit; // Check for overflow. - if (tag > Traits::kSigMask) + if (tag > Traits::kSigMask) { return Result::Error; + } } // NaN cannot have a zero tag, that is reserved for infinity. - if (tag == 0) + if (tag == 0) { return Result::Error; + } } else { tag = Traits::kQuietNanTag; } @@ -269,8 +273,9 @@ Result FloatParser<T>::ParseHex(const char* s, } else if (Succeeded(ParseHexdigit(*s, &digit))) { if (Traits::kBits - Clz(significand) <= Traits::kSigPlusOneBits) { significand = (significand << 4) + digit; - if (seen_dot) + if (seen_dot) { significand_exponent -= 4; + } } else if (!seen_dot) { significand_exponent += 4; } @@ -304,19 +309,22 @@ Result FloatParser<T>::ParseHex(const char* s, } for (; s < end; ++s) { - if (*s == '_') + if (*s == '_') { continue; + } uint32_t digit = (*s - '0'); assert(digit <= 9); exponent = exponent * 10 + digit; - if (exponent + significand_exponent_add >= Traits::kMaxExp) + if (exponent + significand_exponent_add >= Traits::kMaxExp) { break; + } } } - if (exponent_is_neg) + if (exponent_is_neg) { exponent = -exponent; + } int significand_bits = Traits::kBits - Clz(significand); // -1 for the implicit 1 bit of the significand. @@ -352,8 +360,9 @@ Result FloatParser<T>::ParseHex(const char* s, if (significand_bits > Traits::kSigPlusOneBits) { significand = ShiftAndRoundToNearest( significand, significand_bits - Traits::kSigPlusOneBits); - if (significand > Traits::kSigPlusOneMask) + if (significand > Traits::kSigPlusOneMask) { exponent++; + } } else if (significand_bits < Traits::kSigPlusOneBits) { significand <<= (Traits::kSigPlusOneBits - significand_bits); } @@ -431,8 +440,9 @@ void FloatWriter<T>::WriteHex(char* out, size_t size, Uint bits) { int exp = ((bits >> Traits::kSigBits) & Traits::kExpMask) - Traits::kExpBias; Uint sig = bits & Traits::kSigMask; - if (is_neg) + if (is_neg) { *p++ = '-'; + } if (exp == Traits::kMaxExp) { // Infinity or nan. if (sig == 0) { @@ -471,10 +481,11 @@ void FloatWriter<T>::WriteHex(char* out, size_t size, Uint bits) { if (exp == Traits::kMinExp) { // Subnormal; shift the significand up, and shift out the implicit 1. Uint leading_zeroes = Clz(sig); - if (leading_zeroes < Traits::kSignShift) + if (leading_zeroes < Traits::kSignShift) { sig <<= leading_zeroes + 1; - else + } else { sig = 0; + } exp -= leading_zeroes; } @@ -496,19 +507,23 @@ void FloatWriter<T>::WriteHex(char* out, size_t size, Uint bits) { } else { *p++ = '+'; } - if (exp >= 1000) + if (exp >= 1000) { *p++ = '1'; - if (exp >= 100) + } + if (exp >= 100) { *p++ = '0' + (exp / 100) % 10; - if (exp >= 10) + } + if (exp >= 10) { *p++ = '0' + (exp / 10) % 10; + } *p++ = '0' + exp % 10; } } size_t len = p - buffer; - if (len >= size) + if (len >= size) { len = size - 1; + } memcpy(out, buffer, len); out[len] = '\0'; } @@ -530,40 +545,48 @@ Result ParseHexdigit(char c, uint32_t* out) { } Result ParseUint64(const char* s, const char* end, uint64_t* out) { - if (s == end) + if (s == end) { return Result::Error; + } uint64_t value = 0; if (*s == '0' && s + 1 < end && s[1] == 'x') { s += 2; - if (s == end) + if (s == end) { return Result::Error; + } for (; s < end; ++s) { uint32_t digit; - if (*s == '_') + if (*s == '_') { continue; + } CHECK_RESULT(ParseHexdigit(*s, &digit)); uint64_t old_value = value; value = value * 16 + digit; // Check for overflow. - if (old_value > value) + if (old_value > value) { return Result::Error; + } } } else { for (; s < end; ++s) { - if (*s == '_') + if (*s == '_') { continue; + } uint32_t digit = (*s - '0'); - if (digit > 9) + if (digit > 9) { return Result::Error; + } uint64_t old_value = value; value = value * 10 + digit; // Check for overflow. - if (old_value > value) + if (old_value > value) { return Result::Error; + } } } - if (s != end) + if (s != end) { return Result::Error; + } *out = value; return Result::Ok; } @@ -574,18 +597,21 @@ Result ParseInt64(const char* s, ParseIntType parse_type) { bool has_sign = false; if (*s == '-' || *s == '+') { - if (parse_type == ParseIntType::UnsignedOnly) + if (parse_type == ParseIntType::UnsignedOnly) { return Result::Error; - if (*s == '-') + } + if (*s == '-') { has_sign = true; + } s++; } uint64_t value = 0; Result result = ParseUint64(s, end, &value); if (has_sign) { // abs(INT64_MIN) == INT64_MAX + 1. - if (value > static_cast<uint64_t>(INT64_MAX) + 1) + if (value > static_cast<uint64_t>(INT64_MAX) + 1) { return Result::Error; + } value = UINT64_MAX - value + 1; } *out = value; @@ -599,22 +625,26 @@ Result ParseInt32(const char* s, uint64_t value; bool has_sign = false; if (*s == '-' || *s == '+') { - if (parse_type == ParseIntType::UnsignedOnly) + if (parse_type == ParseIntType::UnsignedOnly) { return Result::Error; - if (*s == '-') + } + if (*s == '-') { has_sign = true; + } s++; } CHECK_RESULT(ParseUint64(s, end, &value)); if (has_sign) { // abs(INT32_MIN) == INT32_MAX + 1. - if (value > static_cast<uint64_t>(INT32_MAX) + 1) + if (value > static_cast<uint64_t>(INT32_MAX) + 1) { return Result::Error; + } value = UINT32_MAX - value + 1; } else { - if (value > static_cast<uint64_t>(UINT32_MAX)) + if (value > static_cast<uint64_t>(UINT32_MAX)) { return Result::Error; + } } *out = static_cast<uint32_t>(value); return Result::Ok; diff --git a/src/opcode.cc b/src/opcode.cc index 7d5ed34f..1ead657a 100644 --- a/src/opcode.cc +++ b/src/opcode.cc @@ -82,8 +82,9 @@ bool Opcode::IsNaturallyAligned(Address alignment) const { } Address Opcode::GetAlignment(Address alignment) const { - if (alignment == WABT_USE_NATURAL_ALIGNMENT) + if (alignment == WABT_USE_NATURAL_ALIGNMENT) { return GetMemorySize(); + } return alignment; } diff --git a/src/option-parser.cc b/src/option-parser.cc index 168a7c9e..f0a02cdb 100644 --- a/src/option-parser.cc +++ b/src/option-parser.cc @@ -105,19 +105,23 @@ int OptionParser::Match(const char* s, if (full[i] == '\0') { // Perfect match. Return +1, so it will be preferred over a longer option // with the same prefix. - if (s[i] == '\0') + if (s[i] == '\0') { return i + 1; + } // We want to fail if s is longer than full, e.g. --foobar vs. --foo. // However, if s ends with an '=', it's OK. - if (!(has_argument && s[i] == '=')) + if (!(has_argument && s[i] == '=')) { return -1; + } break; } - if (s[i] == '\0') + if (s[i] == '\0') { break; - if (s[i] != full[i]) + } + if (s[i] != full[i]) { return -1; + } } return i; } @@ -286,19 +290,22 @@ void OptionParser::PrintHelp() { continue; } - if (length > longest_name_length) + if (length > longest_name_length) { longest_name_length = length; + } } for (const Option& option: options_) { - if (!option.short_name && option.long_name.empty()) + if (!option.short_name && option.long_name.empty()) { continue; + } std::string line; - if (option.short_name) + if (option.short_name) { line += std::string(" -") + option.short_name + ", "; - else + } else { line += " "; + } std::string flag; if (!option.long_name.empty()) { @@ -314,8 +321,9 @@ void OptionParser::PrintHelp() { size_t remaining = longest_name_length + kExtraSpace + 2 - flag.size(); line += flag + std::string(remaining, ' '); - if (!option.help.empty()) + if (!option.help.empty()) { line += option.help; + } printf("%s\n", line.c_str()); } } diff --git a/src/resolve-names.cc b/src/resolve-names.cc index 2b6199b8..7b8bf68b 100644 --- a/src/resolve-names.cc +++ b/src/resolve-names.cc @@ -188,8 +188,9 @@ void NameResolver::ResolveExceptionVar(Var* var) { void NameResolver::ResolveLocalVar(Var* var) { if (var->is_name()) { - if (!current_func_) + if (!current_func_) { return; + } Index index = current_func_->GetLocalIndex(*var); if (index == kInvalidIndex) { @@ -245,8 +246,9 @@ Result NameResolver::OnCallExpr(CallExpr* expr) { } Result NameResolver::OnCallIndirectExpr(CallIndirectExpr* expr) { - if (expr->decl.has_func_type) + if (expr->decl.has_func_type) { ResolveFuncTypeVar(&expr->decl.type_var); + } return Result::Ok; } @@ -296,8 +298,9 @@ Result NameResolver::EndTryExpr(TryExpr*) { } Result NameResolver::OnCatchExpr(TryExpr* expr, Catch* catch_) { - if (!catch_->IsCatchAll()) + if (!catch_->IsCatchAll()) { ResolveExceptionVar(&catch_->var); + } return Result::Ok; } @@ -315,8 +318,9 @@ Result NameResolver::OnRethrowExpr(RethrowExpr* expr) { void NameResolver::VisitFunc(Func* func) { current_func_ = func; - if (func->decl.has_func_type) + if (func->decl.has_func_type) { ResolveFuncTypeVar(&func->decl.type_var); + } CheckDuplicateBindings(&func->param_bindings, "parameter"); CheckDuplicateBindings(&func->local_bindings, "local"); @@ -391,8 +395,9 @@ Result NameResolver::VisitModule(Module* module) { } void NameResolver::VisitScriptModule(ScriptModule* script_module) { - if (auto* tsm = dyn_cast<TextScriptModule>(script_module)) + if (auto* tsm = dyn_cast<TextScriptModule>(script_module)) { VisitModule(&tsm->module); + } } void NameResolver::VisitCommand(Command* command) { diff --git a/src/result.h b/src/result.h index 9d737cd6..016a4248 100644 --- a/src/result.h +++ b/src/result.h @@ -49,8 +49,9 @@ inline bool Failed(Result result) { return result == Result::Error; } #define CHECK_RESULT(expr) \ do { \ - if (Failed(expr)) \ + if (Failed(expr)) { \ return ::wabt::Result::Error; \ + } \ } while (0) } // namespace wabt diff --git a/src/stream.cc b/src/stream.cc index 90d4e913..bb9b7a3b 100644 --- a/src/stream.cc +++ b/src/stream.cc @@ -41,8 +41,9 @@ void Stream::WriteDataAt(size_t at, size_t size, const char* desc, PrintChars print_chars) { - if (Failed(result_)) + if (Failed(result_)) { return; + } if (log_stream_) { log_stream_->WriteMemoryDump(src, size, at, print_chars, nullptr, desc); } @@ -58,8 +59,9 @@ void Stream::WriteData(const void* src, } void Stream::MoveData(size_t dst_offset, size_t src_offset, size_t size) { - if (Failed(result_)) + if (Failed(result_)) { return; + } if (log_stream_) { log_stream_->Writef( "; move data: [%" PRIzx ", %" PRIzx ") -> [%" PRIzx ", %" PRIzx ")\n", @@ -84,8 +86,9 @@ void Stream::WriteMemoryDump(const void* start, while (p < end) { const uint8_t* line = p; const uint8_t* line_end = p + DUMP_OCTETS_PER_LINE; - if (prefix) + if (prefix) { Writef("%s", prefix); + } Writef("%07" PRIzx ": ", reinterpret_cast<intptr_t>(p) - reinterpret_cast<intptr_t>(start) + offset); while (p < line_end) { @@ -108,8 +111,9 @@ void Stream::WriteMemoryDump(const void* start, } /* if there are multiple lines, only print the desc on the last one */ - if (p >= end && desc) + if (p >= end && desc) { Writef(" ; %s", desc); + } WriteChar('\n'); } } @@ -153,8 +157,9 @@ std::unique_ptr<OutputBuffer> MemoryStream::ReleaseOutputBuffer() { Result MemoryStream::WriteDataImpl(size_t dst_offset, const void* src, size_t size) { - if (size == 0) + if (size == 0) { return Result::Ok; + } size_t end = dst_offset + size; if (end > buf_->data.size()) { buf_->data.resize(end); @@ -167,8 +172,9 @@ Result MemoryStream::WriteDataImpl(size_t dst_offset, Result MemoryStream::MoveDataImpl(size_t dst_offset, size_t src_offset, size_t size) { - if (size == 0) + if (size == 0) { return Result::Ok; + } size_t src_end = src_offset + size; size_t dst_end = dst_offset + size; size_t end = src_end > dst_end ? src_end : dst_end; @@ -220,10 +226,12 @@ FileStream::~FileStream() { } Result FileStream::WriteDataImpl(size_t at, const void* data, size_t size) { - if (!file_) + if (!file_) { return Result::Error; - if (size == 0) + } + if (size == 0) { return Result::Ok; + } if (at != offset_) { if (fseek(file_, at, SEEK_SET) != 0) { ERROR("fseek offset=%" PRIzd " failed, errno=%d\n", size, errno); @@ -242,10 +250,12 @@ Result FileStream::WriteDataImpl(size_t at, const void* data, size_t size) { Result FileStream::MoveDataImpl(size_t dst_offset, size_t src_offset, size_t size) { - if (!file_) + if (!file_) { return Result::Error; - if (size == 0) + } + if (size == 0) { return Result::Ok; + } // TODO(binji): implement if needed. ERROR0("FileWriter::MoveData not implemented!\n"); return Result::Error; diff --git a/src/stream.h b/src/stream.h index 1e57325d..7c1f04d4 100644 --- a/src/stream.h +++ b/src/stream.h @@ -63,8 +63,9 @@ class Stream { void WriteData(const std::vector<T> src, const char* desc, PrintChars print_chars = PrintChars::No) { - if (!src.empty()) + if (!src.empty()) { WriteData(src.data(), src.size() * sizeof(T), desc, print_chars); + } } void WriteDataAt(size_t offset, diff --git a/src/test-intrusive-list.cc b/src/test-intrusive-list.cc index f2af0057..217ea251 100644 --- a/src/test-intrusive-list.cc +++ b/src/test-intrusive-list.cc @@ -50,8 +50,9 @@ struct TestObject : intrusive_list_base<TestObject> { TestObject& operator=(const TestObject&) = delete; ~TestObject() { - if (!moved) + if (!moved) { creation_count--; + } } int data; diff --git a/src/test-utf8.cc b/src/test-utf8.cc index f08be4ff..d0e95acd 100644 --- a/src/test-utf8.cc +++ b/src/test-utf8.cc @@ -98,8 +98,9 @@ TEST(utf8, valid_3_bytes_e0) { TEST(utf8, valid_3_bytes) { FOR_RANGE(cu0, 0xe1, 0xf0) { // Handle 0xed in valid_3_bytes_ed. - if (cu0 == 0xed) + if (cu0 == 0xed) { continue; + } FOR_EACH_BYTE(cu1) { FOR_EACH_BYTE(cu2) { diff --git a/src/token.cc b/src/token.cc index 2ffc24cc..78c649a8 100644 --- a/src/token.cc +++ b/src/token.cc @@ -122,8 +122,9 @@ const char* GetTokenTypeName(TokenType token_type) { "Expected TokenType names list length to match number of TokenTypes."); int x = static_cast<int>(token_type); - if (x < WABT_ENUM_COUNT(TokenType)) + if (x < WABT_ENUM_COUNT(TokenType)) { return s_names[x]; + } return "Invalid"; } diff --git a/src/tools/spectest-interp.cc b/src/tools/spectest-interp.cc index ab4c7774..c98220e1 100644 --- a/src/tools/spectest-interp.cc +++ b/src/tools/spectest-interp.cc @@ -263,8 +263,9 @@ void JSONParser::PutbackChar() { } int JSONParser::ReadChar() { - if (json_offset_ >= json_data_.size()) + if (json_offset_ >= json_data_.size()) { return -1; + } prev_loc_ = loc_; char c = json_data_[json_offset_++]; if (c == '\n') { @@ -453,8 +454,9 @@ wabt::Result JSONParser::ParseTypeVector(TypeVector* out_types) { EXPECT("["); bool first = true; while (!Match("]")) { - if (!first) + if (!first) { EXPECT(","); + } Type type; CHECK_RESULT(ParseTypeObject(&type)); first = false; @@ -514,8 +516,9 @@ wabt::Result JSONParser::ParseConstVector(TypedValues* out_values) { EXPECT("["); bool first = true; while (!Match("]")) { - if (!first) + if (!first) { EXPECT(","); + } TypedValue value; CHECK_RESULT(ParseConst(&value)); out_values->push_back(value); @@ -575,10 +578,12 @@ static string_view GetDirname(string_view path) { // s = "some\windows\directory", => "some\windows" size_t last_slash = path.find_last_of('/'); size_t last_backslash = path.find_last_of('\\'); - if (last_slash == string_view::npos) + if (last_slash == string_view::npos) { last_slash = 0; - if (last_backslash == string_view::npos) + } + if (last_backslash == string_view::npos) { last_backslash = 0; + } return path.substr(0, std::max(last_slash, last_backslash)); } @@ -743,8 +748,9 @@ wabt::Result JSONParser::ParseScript(Script* out_script) { bool first = true; while (!Match("]")) { CommandPtr command; - if (!first) + if (!first) { EXPECT(","); + } CHECK_RESULT(ParseCommand(&command)); out_script->commands.push_back(std::move(command)); first = false; @@ -1005,10 +1011,12 @@ static ExecResult GetGlobalExportByName(Environment* env, interp::Module* module, string_view name) { interp::Export* export_ = module->GetExport(name); - if (!export_) + if (!export_) { return ExecResult(interp::Result::UnknownExport); - if (export_->kind != ExternalKind::Global) + } + if (export_->kind != ExternalKind::Global) { return ExecResult(interp::Result::ExportKindMismatch); + } interp::Global* global = env->GetGlobal(export_->index); return ExecResult(interp::Result::Ok, {global->typed_value}); @@ -1087,8 +1095,9 @@ static wabt::Result ReadModule(string_view module_filename, &options, error_handler, out_module); if (Succeeded(result)) { - if (s_verbose) + if (s_verbose) { env->DisassembleModule(s_stdout_stream.get(), *out_module); + } } } return result; @@ -1258,8 +1267,9 @@ wabt::Result CommandRunner::OnAssertUninstantiableCommand( } static bool TypedValuesAreEqual(const TypedValue& tv1, const TypedValue& tv2) { - if (tv1.type != tv2.type) + if (tv1.type != tv2.type) { return false; + } switch (tv1.type) { case Type::I32: @@ -1391,8 +1401,9 @@ wabt::Result CommandRunner::OnAssertExhaustionCommand( } void CommandRunner::TallyCommand(wabt::Result result) { - if (Succeeded(result)) + if (Succeeded(result)) { passed_++; + } total_++; } diff --git a/src/tools/wasm-interp.cc b/src/tools/wasm-interp.cc index 0503e621..c3243761 100644 --- a/src/tools/wasm-interp.cc +++ b/src/tools/wasm-interp.cc @@ -145,8 +145,9 @@ static wabt::Result ReadModule(const char* module_filename, &options, error_handler, out_module); if (Succeeded(result)) { - if (s_verbose) + if (s_verbose) { env->DisassembleModule(s_stdout_stream.get(), *out_module); + } } } return result; @@ -237,8 +238,9 @@ static wabt::Result ReadAndRunModule(const char* module_filename) { Executor executor(&env, s_trace_stream, s_thread_options); ExecResult exec_result = executor.RunStartFunction(module); if (exec_result.result == interp::Result::Ok) { - if (s_run_all_exports) + if (s_run_all_exports) { RunAllExports(module, &executor, RunVerbosity::Verbose); + } } else { WriteResult(s_stdout_stream.get(), "error running start function", exec_result.result); diff --git a/src/tools/wasm-link.cc b/src/tools/wasm-link.cc index d3c7c20f..cc64aade 100644 --- a/src/tools/wasm-link.cc +++ b/src/tools/wasm-link.cc @@ -183,8 +183,9 @@ static void ApplyRelocation(const Section* section, const Reloc* r) { } static void ApplyRelocations(const Section* section) { - if (!section->relocations.size()) + if (!section->relocations.size()) { return; + } LOG_DEBUG("ApplyRelocations: %s\n", GetSectionName(section->section_code)); @@ -367,8 +368,9 @@ void Linker::WriteImportSection() { Index num_imports = 0; for (const std::unique_ptr<LinkerInputBinary>& binary: inputs_) { for (const FunctionImport& import : binary->function_imports) { - if (import.active) + if (import.active) { num_imports++; + } } num_imports += binary->global_imports.size(); } @@ -378,8 +380,9 @@ void Linker::WriteImportSection() { for (const std::unique_ptr<LinkerInputBinary>& binary: inputs_) { for (const FunctionImport& function_import : binary->function_imports) { - if (function_import.active) + if (function_import.active) { WriteFunctionImport(function_import, binary->type_index_offset); + } } for (const GlobalImport& global_import : binary->global_imports) { @@ -442,16 +445,19 @@ void Linker::WriteNamesSection() { Index total_count = 0; for (const std::unique_ptr<LinkerInputBinary>& binary : inputs_) { for (size_t i = 0; i < binary->debug_names.size(); i++) { - if (binary->debug_names[i].empty()) + if (binary->debug_names[i].empty()) { continue; - if (binary->IsInactiveFunctionImport(i)) + } + if (binary->IsInactiveFunctionImport(i)) { continue; + } total_count++; } } - if (!total_count) + if (!total_count) { return; + } stream_.WriteU8Enum(BinarySection::Custom, "section code"); Fixup fixup_section = WriteUnknownSize(); @@ -464,10 +470,12 @@ void Linker::WriteNamesSection() { // Write import names. for (const std::unique_ptr<LinkerInputBinary>& binary : inputs_) { for (size_t i = 0; i < binary->debug_names.size(); i++) { - if (binary->debug_names[i].empty() || !binary->IsFunctionImport(i)) + if (binary->debug_names[i].empty() || !binary->IsFunctionImport(i)) { continue; - if (binary->IsInactiveFunctionImport(i)) + } + if (binary->IsInactiveFunctionImport(i)) { continue; + } WriteU32Leb128(&stream_, binary->RelocateFuncIndex(i), "function index"); WriteStr(&stream_, binary->debug_names[i], "function name"); } @@ -476,8 +484,9 @@ void Linker::WriteNamesSection() { // Write non-import names. for (const std::unique_ptr<LinkerInputBinary>& binary : inputs_) { for (size_t i = 0; i < binary->debug_names.size(); i++) { - if (binary->debug_names[i].empty() || binary->IsFunctionImport(i)) + if (binary->debug_names[i].empty() || binary->IsFunctionImport(i)) { continue; + } WriteU32Leb128(&stream_, binary->RelocateFuncIndex(i), "function index"); WriteStr(&stream_, binary->debug_names[i], "function name"); } @@ -518,8 +527,9 @@ void Linker::WriteRelocSection(BinarySection section_code, for (Section* sec: sections) total_relocs += sec->relocations.size(); - if (!total_relocs) + if (!total_relocs) { return; + } std::string section_name = StringPrintf("%s.%s", WABT_BINARY_SECTION_RELOC, GetSectionName(section_code)); @@ -563,8 +573,9 @@ void Linker::WriteRelocSection(BinarySection section_code, bool Linker::WriteCombinedSection(BinarySection section_code, const SectionPtrVector& sections) { - if (!sections.size()) + if (!sections.size()) { return false; + } if (section_code == BinarySection::Start && sections.size() > 1) { WABT_FATAL("Don't know how to combine sections of type: %s\n", @@ -651,8 +662,9 @@ void Linker::ResolveSymbols() { for (FunctionImport& import: binary->function_imports) { Index export_index = export_map.FindIndex(import.name); if (export_index == kInvalidIndex) { - if (!s_relocatable) + if (!s_relocatable) { WABT_FATAL("undefined symbol: %s\n", import.name.c_str()); + } continue; } @@ -780,8 +792,9 @@ void Linker::DumpRelocOffsets() { } Result Linker::PerformLink() { - if (s_debug) + if (s_debug) { stream_.set_log_stream(s_log_stream.get()); + } LOG_DEBUG("writing file: %s\n", s_outfile); CalculateRelocOffsets(); @@ -809,18 +822,21 @@ int ProgramMain(int argc, char** argv) { LOG_DEBUG("reading file: %s\n", input_filename.c_str()); std::vector<uint8_t> file_data; result = ReadFile(input_filename.c_str(), &file_data); - if (Failed(result)) + if (Failed(result)) { return result != Result::Ok; + } auto binary = new LinkerInputBinary(input_filename.c_str(), file_data); linker.AppendBinary(binary); LinkOptions options = { NULL }; - if (s_debug) + if (s_debug) { options.log_stream = s_log_stream.get(); + } result = ReadBinaryLinker(binary, &options); - if (Failed(result)) + if (Failed(result)) { WABT_FATAL("error parsing file: %s\n", input_filename.c_str()); + } } result = linker.PerformLink(); diff --git a/src/tools/wasm2wat.cc b/src/tools/wasm2wat.cc index 2358ce7c..a0186918 100644 --- a/src/tools/wasm2wat.cc +++ b/src/tools/wasm2wat.cc @@ -115,8 +115,9 @@ int ProgramMain(int argc, char** argv) { result = ValidateModule(lexer, &module, &error_handler, &options); } - if (s_generate_names) + if (s_generate_names) { result = GenerateNames(&module); + } if (Succeeded(result)) { /* TODO(binji): This shouldn't fail; if a name can't be applied diff --git a/src/tools/wast2json.cc b/src/tools/wast2json.cc index 0243775a..d7b4ed7d 100644 --- a/src/tools/wast2json.cc +++ b/src/tools/wast2json.cc @@ -95,8 +95,9 @@ int ProgramMain(int argc, char** argv) { ParseOptions(argc, argv); std::unique_ptr<WastLexer> lexer = WastLexer::CreateFileLexer(s_infile); - if (!lexer) + if (!lexer) { WABT_FATAL("unable to read file: %s\n", s_infile); + } ErrorHandlerFile error_handler(Location::Type::Text); std::unique_ptr<Script> script; diff --git a/src/tools/wat-desugar.cc b/src/tools/wat-desugar.cc index 782dcbef..01125093 100644 --- a/src/tools/wat-desugar.cc +++ b/src/tools/wat-desugar.cc @@ -82,8 +82,9 @@ int ProgramMain(int argc, char** argv) { ParseOptions(argc, argv); std::unique_ptr<WastLexer> lexer(WastLexer::CreateFileLexer(s_infile)); - if (!lexer) + if (!lexer) { WABT_FATAL("unable to read %s\n", s_infile); + } ErrorHandlerFile error_handler(Location::Type::Text); std::unique_ptr<Script> script; @@ -93,14 +94,17 @@ int ProgramMain(int argc, char** argv) { if (Succeeded(result)) { Module* module = script->GetFirstModule(); - if (!module) + if (!module) { WABT_FATAL("no module in file.\n"); + } - if (s_generate_names) + if (s_generate_names) { result = GenerateNames(module); + } - if (Succeeded(result)) + if (Succeeded(result)) { result = ApplyNames(module); + } if (Succeeded(result)) { FileStream stream(s_outfile ? FileStream(s_outfile) : FileStream(stdout)); diff --git a/src/tools/wat2wasm.cc b/src/tools/wat2wasm.cc index e852c5b4..2f376e63 100644 --- a/src/tools/wat2wasm.cc +++ b/src/tools/wat2wasm.cc @@ -102,8 +102,9 @@ static void ParseOptions(int argc, char* argv[]) { static void WriteBufferToFile(string_view filename, const OutputBuffer& buffer) { if (s_dump_module) { - if (s_verbose) + if (s_verbose) { s_log_stream->Writef(";; dump\n"); + } if (!buffer.data.empty()) { s_log_stream->WriteMemoryDump(buffer.data.data(), buffer.data.size()); } @@ -126,8 +127,9 @@ int ProgramMain(int argc, char** argv) { ParseOptions(argc, argv); std::unique_ptr<WastLexer> lexer = WastLexer::CreateFileLexer(s_infile); - if (!lexer) + if (!lexer) { WABT_FATAL("unable to read file: %s\n", s_infile); + } ErrorHandlerFile error_handler(Location::Type::Text); std::unique_ptr<Module> module; @@ -150,8 +152,9 @@ int ProgramMain(int argc, char** argv) { WriteBinaryModule(&stream, module.get(), &s_write_binary_options); if (Succeeded(result)) { - if (s_outfile.empty()) + if (s_outfile.empty()) { s_outfile = DefaultOuputName(s_infile); + } WriteBufferToFile(s_outfile.c_str(), stream.output_buffer()); } } diff --git a/src/tracing.cc b/src/tracing.cc index c7e88c60..3208acdf 100644 --- a/src/tracing.cc +++ b/src/tracing.cc @@ -33,8 +33,9 @@ void Indent() { } void Dedent() { - if (indent) + if (indent) { --indent; + } Fill(); } diff --git a/src/type-checker.cc b/src/type-checker.cc index 47de7063..c9cd5da2 100644 --- a/src/type-checker.cc +++ b/src/type-checker.cc @@ -54,8 +54,9 @@ Result TypeChecker::TopLabel(Label** out_label) { bool TypeChecker::IsUnreachable() { Label* label; - if (Failed(TopLabel(&label))) + if (Failed(TopLabel(&label))) { return true; + } return label->unreachable; } @@ -117,8 +118,9 @@ Result TypeChecker::DropTypes(size_t drop_count) { } void TypeChecker::PushType(Type type) { - if (type != Type::Void) + if (type != Type::Void) { type_stack_.push_back(type); + } } void TypeChecker::PushTypes(const TypeVector& types) { @@ -223,13 +225,15 @@ Result TypeChecker::CheckOpcode3(Opcode opcode) { static std::string TypesToString(const TypeVector& types, const char* prefix = nullptr) { std::string result = "["; - if (prefix) + if (prefix) { result += prefix; + } for (size_t i = 0; i < types.size(); ++i) { result += GetTypeName(types[i]); - if (i < types.size() - 1) + if (i < types.size() - 1) { result += ", "; + } } result += "]"; return result; @@ -326,8 +330,9 @@ Result TypeChecker::OnBr(Index depth) { Result result = Result::Ok; Label* label; CHECK_RESULT(GetLabel(depth, &label)); - if (label->label_type != LabelType::Loop) + if (label->label_type != LabelType::Loop) { result |= CheckSignature(label->sig); + } PrintStackIfFailed(result, "br", label->sig); CHECK_RESULT(SetUnreachable()); return result; @@ -518,8 +523,9 @@ Result TypeChecker::OnRethrow(Index depth) { size_t last = label_stack_.size() - 1; for (size_t i = 0; i < label_stack_.size(); ++i) { if (label_stack_[last - i].label_type == LabelType::Catch) { - if (!candidates.empty()) + if (!candidates.empty()) { candidates.append(", "); + } candidates.append(std::to_string(i)); } } diff --git a/src/type-checker.h b/src/type-checker.h index adc07423..8f49335b 100644 --- a/src/type-checker.h +++ b/src/type-checker.h @@ -130,8 +130,9 @@ class TypeChecker { void PrintStackIfFailed(Result result, const char* desc, Args... args) { // Minor optimzation, check result before constructing the vector to pass // to the other overload of PrintStackIfFailed. - if (Failed(result)) + if (Failed(result)) { PrintStackIfFailed(result, desc, {args...}); + } } void PrintStackIfFailed(Result, const char* desc, const TypeVector&); diff --git a/src/utf8.cc b/src/utf8.cc index cabd8d27..37a8df00 100644 --- a/src/utf8.cc +++ b/src/utf8.cc @@ -55,8 +55,9 @@ bool IsValidUtf8(const char* s, size_t s_length) { while (p < end) { uint8_t cu0 = *p; int length = s_utf8_length[cu0]; - if (p + length > end) + if (p + length > end) { return false; + } switch (length) { case 0: @@ -68,8 +69,9 @@ bool IsValidUtf8(const char* s, size_t s_length) { case 2: p++; - if (!IsCont(*p++)) + if (!IsCont(*p++)) { return false; + } break; case 3: { diff --git a/src/validator.cc b/src/validator.cc index 46c8c9e9..c5feabab 100644 --- a/src/validator.cc +++ b/src/validator.cc @@ -205,8 +205,9 @@ Result Validator::CheckVar(Index max_index, const char* desc, Index* out_index) { if (var->index() < max_index) { - if (out_index) + if (out_index) { *out_index = var->index(); + } return Result::Ok; } PrintError(&var->loc, "%s variable out of range (max %" PRIindex ")", desc, @@ -217,8 +218,9 @@ Result Validator::CheckVar(Index max_index, Result Validator::CheckFuncVar(const Var* var, const Func** out_func) { Index index; CHECK_RESULT(CheckVar(current_module_->funcs.size(), var, "function", &index)); - if (out_func) + if (out_func) { *out_func = current_module_->funcs[index]; + } return Result::Ok; } @@ -228,17 +230,20 @@ Result Validator::CheckGlobalVar(const Var* var, Index index; CHECK_RESULT( CheckVar(current_module_->globals.size(), var, "global", &index)); - if (out_global) + if (out_global) { *out_global = current_module_->globals[index]; - if (out_global_index) + } + if (out_global_index) { *out_global_index = index; + } return Result::Ok; } Type Validator::GetGlobalVarTypeOrAny(const Var* var) { const Global* global; - if (Succeeded(CheckGlobalVar(var, &global, nullptr))) + if (Succeeded(CheckGlobalVar(var, &global, nullptr))) { return global->type; + } return Type::Any; } @@ -247,16 +252,18 @@ Result Validator::CheckFuncTypeVar(const Var* var, Index index; CHECK_RESULT(CheckVar(current_module_->func_types.size(), var, "function type", &index)); - if (out_func_type) + if (out_func_type) { *out_func_type = current_module_->func_types[index]; + } return Result::Ok; } Result Validator::CheckTableVar(const Var* var, const Table** out_table) { Index index; CHECK_RESULT(CheckVar(current_module_->tables.size(), var, "table", &index)); - if (out_table) + if (out_table) { *out_table = current_module_->tables[index]; + } return Result::Ok; } @@ -264,8 +271,9 @@ Result Validator::CheckMemoryVar(const Var* var, const Memory** out_memory) { Index index; CHECK_RESULT( CheckVar(current_module_->memories.size(), var, "memory", &index)); - if (out_memory) + if (out_memory) { *out_memory = current_module_->memories[index]; + } return Result::Ok; } @@ -305,8 +313,9 @@ void Validator::CheckAlign(const Location* loc, Address alignment, Address natural_alignment) { if (alignment != WABT_USE_NATURAL_ALIGNMENT) { - if (!is_power_of_two(alignment)) + if (!is_power_of_two(alignment)) { PrintError(loc, "alignment must be power-of-two"); + } if (alignment > natural_alignment) { PrintError(loc, "alignment must not be larger than natural alignment (%u)", @@ -319,8 +328,9 @@ void Validator::CheckAtomicAlign(const Location* loc, Address alignment, Address natural_alignment) { if (alignment != WABT_USE_NATURAL_ALIGNMENT) { - if (!is_power_of_two(alignment)) + if (!is_power_of_two(alignment)) { PrintError(loc, "alignment must be power-of-two"); + } if (alignment != natural_alignment) { PrintError(loc, "alignment must be equal to natural alignment (%u)", natural_alignment); @@ -385,8 +395,9 @@ void Validator::CheckConstType(const Location* loc, const ConstVector& expected, const char* desc) { TypeVector actual_types; - if (actual != Type::Void) + if (actual != Type::Void) { actual_types.push_back(actual); + } CheckConstTypes(loc, actual_types, expected, desc); } @@ -648,16 +659,18 @@ void Validator::CheckExpr(const Expr* expr) { typechecker_.OnTryBlock(&try_expr->block.sig); CheckExprList(&try_expr->loc, try_expr->block.exprs); - if (try_expr->catches.empty()) + if (try_expr->catches.empty()) { PrintError(&try_expr->loc, "TryBlock: doesn't have any catch clauses"); + } bool found_catch_all = false; for (const Catch& catch_ : try_expr->catches) { typechecker_.OnCatchBlock(&try_expr->block.sig); if (catch_.IsCatchAll()) { found_catch_all = true; } else { - if (found_catch_all) + if (found_catch_all) { PrintError(&catch_.loc, "Appears after catch all block"); + } const Exception* except = nullptr; if (Succeeded(CheckExceptVar(&catch_.var, &except))) { typechecker_.OnCatch(&except->sig); @@ -802,8 +815,9 @@ void Validator::CheckLimits(const Location* loc, const Limits* limits, } void Validator::CheckTable(const Location* loc, const Table* table) { - if (current_table_index_ == 1) + if (current_table_index_ == 1) { PrintError(loc, "only one table allowed"); + } CheckLimits(loc, &table->elem_limits, UINT32_MAX, "elems", LimitsShareable::NotAllowed); } @@ -813,8 +827,9 @@ void Validator::CheckElemSegments(const Module* module) { if (auto elem_segment_field = dyn_cast<ElemSegmentModuleField>(&field)) { auto&& elem_segment = elem_segment_field->elem_segment; const Table* table; - if (Failed(CheckTableVar(&elem_segment.table_var, &table))) + if (Failed(CheckTableVar(&elem_segment.table_var, &table))) { continue; + } for (const Var& var : elem_segment.vars) { CheckFuncVar(&var, nullptr); @@ -827,8 +842,9 @@ void Validator::CheckElemSegments(const Module* module) { } void Validator::CheckMemory(const Location* loc, const Memory* memory) { - if (current_memory_index_ == 1) + if (current_memory_index_ == 1) { PrintError(loc, "only one memory block allowed"); + } CheckLimits(loc, &memory->page_limits, WABT_MAX_PAGES, "pages", LimitsShareable::Allowed); } @@ -838,8 +854,9 @@ void Validator::CheckDataSegments(const Module* module) { if (auto data_segment_field = dyn_cast<DataSegmentModuleField>(&field)) { auto&& data_segment = data_segment_field->data_segment; const Memory* memory; - if (Failed(CheckMemoryVar(&data_segment.memory_var, &memory))) + if (Failed(CheckMemoryVar(&data_segment.memory_var, &memory))) { continue; + } CheckConstInitExpr(&field.loc, data_segment.offset, Type::I32, "data segment offset"); @@ -856,8 +873,9 @@ void Validator::CheckImport(const Location* loc, const Import* import) { case ExternalKind::Func: { auto* func_import = cast<FuncImport>(import); - if (func_import->func.decl.has_func_type) + if (func_import->func.decl.has_func_type) { CheckFuncTypeVar(&func_import->func.decl.type_var, nullptr); + } break; } @@ -1074,8 +1092,9 @@ Result Validator::CheckExceptVar(const Var* var, const Exception** out_except) { Index index; CHECK_RESULT( CheckVar(current_module_->excepts.size(), var, "except", &index)); - if (out_except) + if (out_except) { *out_except = current_module_->excepts[index]; + } return Result::Ok; } @@ -1106,10 +1125,11 @@ Validator::ActionResult Validator::CheckAction(const Action* action) { break; case ActionType::Get: - if (Succeeded(CheckGet(cast<GetAction>(action), &result.type))) + if (Succeeded(CheckGet(cast<GetAction>(action), &result.type))) { result.kind = ActionResult::Kind::Type; - else + } else { result.kind = ActionResult::Kind::Error; + } break; } @@ -1134,8 +1154,9 @@ void Validator::CheckAssertReturnNanCommand(const Action* action) { } } - if (result.kind == ActionResult::Kind::Type && result.type != Type::Any) + if (result.kind == ActionResult::Kind::Type && result.type != Type::Any) { CheckAssertReturnNanType(&action->loc, result.type, "action"); + } } void Validator::CheckCommand(const Command* command) { diff --git a/src/wast-lexer.cc b/src/wast-lexer.cc index 008bc3c1..597b1b6b 100644 --- a/src/wast-lexer.cc +++ b/src/wast-lexer.cc @@ -129,8 +129,9 @@ std::string WastLexer::GetText(size_t offset) { } Result WastLexer::Fill(size_t need) { - if (eof_) + if (eof_) { return Result::Error; + } size_t free = next_pos_ - buffer_; assert(static_cast<size_t>(cursor_ - buffer_) >= free); // Our buffer is too small, need to realloc. @@ -146,8 +147,9 @@ Result WastLexer::Fill(size_t need) { new_buffer_size *= 2; char* new_buffer = new char[new_buffer_size]; - if (limit_ > next_pos_) + if (limit_ > next_pos_) { memmove(new_buffer, next_pos_, limit_ - next_pos_); + } buffer_ = new_buffer; buffer_size_ = new_buffer_size; next_pos_ = new_buffer + (next_pos_ - old_buffer) - free; @@ -159,8 +161,9 @@ Result WastLexer::Fill(size_t need) { delete[] old_buffer; } else { // Shift everything down to make more room in the buffer. - if (limit_ > next_pos_) + if (limit_ > next_pos_) { memmove(buffer_, next_pos_, limit_ - next_pos_); + } next_pos_ -= free; marker_ -= free; cursor_ -= free; @@ -552,8 +555,9 @@ Token WastLexer::GetToken(WastParser* parser) { <LINE_COMMENT> [^\n]+ { continue; } <i> "(;" => BLOCK_COMMENT { COMMENT_NESTING = 1; continue; } <BLOCK_COMMENT> "(;" { COMMENT_NESTING++; continue; } - <BLOCK_COMMENT> ";)" { if (--COMMENT_NESTING == 0) + <BLOCK_COMMENT> ";)" { if (--COMMENT_NESTING == 0) { BEGIN(YYCOND_i); + } continue; } <BLOCK_COMMENT> "\n" { NEWLINE; continue; } <BLOCK_COMMENT> [^] { continue; } diff --git a/src/wast-parser.cc b/src/wast-parser.cc index 90412538..07316bcb 100644 --- a/src/wast-parser.cc +++ b/src/wast-parser.cc @@ -44,8 +44,9 @@ template <typename OutputIter> void RemoveEscapes(string_view text, OutputIter dest) { // Remove surrounding quotes; if any. This may be empty if the string was // invalid (e.g. if it contained a bad escape sequence). - if (text.size() <= 2) + if (text.size() <= 2) { return; + } text = text.substr(1, text.size() - 2); @@ -206,8 +207,9 @@ bool IsCatch(TokenType token_type) { } bool IsModuleField(TokenTypePair pair) { - if (pair[0] != TokenType::Lpar) + if (pair[0] != TokenType::Lpar) { return false; + } switch (pair[1]) { case TokenType::Data: @@ -228,8 +230,9 @@ bool IsModuleField(TokenTypePair pair) { } bool IsCommand(TokenTypePair pair) { - if (pair[0] != TokenType::Lpar) + if (pair[0] != TokenType::Lpar) { return false; + } switch (pair[1]) { case TokenType::AssertExhaustion: @@ -311,8 +314,9 @@ void ResolveFuncTypes(Module* module) { continue; } - if (decl) + if (decl) { ResolveFuncType(field.loc, module, decl); + } if (func) { ResolveFuncTypesExprVisitorDelegate delegate(module); @@ -351,8 +355,9 @@ void WastParser::Error(Location loc, const char* format, ...) { } Token WastParser::GetToken() { - if (tokens_.empty()) + if (tokens_.empty()) { tokens_.push_back(lexer_->GetToken(this)); + } return tokens_.front(); } @@ -421,8 +426,9 @@ Token WastParser::Consume() { Result WastParser::Synchronize(SynchronizeFunc func) { static const int kMaxConsumed = 10; for (int i = 0; i < kMaxConsumed; ++i) { - if (func(PeekPair())) + if (func(PeekPair())) { return Result::Ok; + } Token token = Consume(); if (token.token_type() == TokenType::Reserved) { @@ -436,8 +442,9 @@ Result WastParser::Synchronize(SynchronizeFunc func) { void WastParser::ErrorUnlessOpcodeEnabled(const Token& token) { Opcode opcode = token.opcode(); - if (!opcode.IsEnabled(options_->features)) + if (!opcode.IsEnabled(options_->features)) { Error(token.loc, "opcode not allowed: %s", opcode.GetName()); + } } Result WastParser::ErrorExpected(const std::vector<std::string>& expected, @@ -448,10 +455,11 @@ Result WastParser::ErrorExpected(const std::vector<std::string>& expected, expected_str = ", expected "; for (size_t i = 0; i < expected.size(); ++i) { if (i != 0) { - if (i == expected.size() - 1) + if (i == expected.size() - 1) { expected_str += " or "; - else + } else { expected_str += ", "; + } } expected_str += expected[i]; @@ -577,8 +585,9 @@ bool WastParser::ParseVarListOpt(VarVector* out_var_list) { Result WastParser::ParseValueType(Type* out_type) { WABT_TRACE(ParseValueType); - if (!PeekMatch(TokenType::ValueType)) + if (!PeekMatch(TokenType::ValueType)) { return ErrorExpected({"i32", "i64", "f32", "f64"}); + } *out_type = Consume().type(); return Result::Ok; @@ -594,8 +603,9 @@ Result WastParser::ParseValueTypeList(TypeVector* out_type_list) { Result WastParser::ParseQuotedText(std::string* text) { WABT_TRACE(ParseQuotedText); - if (!PeekMatch(TokenType::Text)) + if (!PeekMatch(TokenType::Text)) { return ErrorExpected({"a quoted string"}, "\"foo\""); + } Token token = Consume(); RemoveEscapes(token.text(), std::back_inserter(*text)); @@ -670,8 +680,9 @@ Result WastParser::ParseLimits(Limits* out_limits) { Result WastParser::ParseNat(uint64_t* out_nat) { WABT_TRACE(ParseNat); - if (!PeekMatch(TokenType::Nat)) + if (!PeekMatch(TokenType::Nat)) { return ErrorExpected({"a natural number"}, "123"); + } Token token = Consume(); string_view sv = token.literal().text; @@ -1672,8 +1683,9 @@ Result WastParser::ParseExprList(ExprList* exprs) { Result WastParser::ParseExpr(ExprList* exprs) { WABT_TRACE(ParseExpr); - if (!PeekMatch(TokenType::Lpar)) + if (!PeekMatch(TokenType::Lpar)) { return Result::Error; + } if (IsPlainInstr(Peek(1))) { Consume(); @@ -1774,8 +1786,9 @@ Result WastParser::ParseCatchInstrList(CatchVector* catches) { while (IsCatch(Peek())) { Catch catch_(GetLocation()); - if (Consume().token_type() == TokenType::Catch) + if (Consume().token_type() == TokenType::Catch) { CHECK_RESULT(ParseVar(&catch_.var)); + } CHECK_RESULT(ParseInstrList(&catch_.exprs)); catches->push_back(std::move(catch_)); @@ -1790,8 +1803,9 @@ Result WastParser::ParseCatchExprList(CatchVector* catches) { Consume(); Catch catch_(GetLocation()); - if (Consume().token_type() == TokenType::Catch) + if (Consume().token_type() == TokenType::Catch) { CHECK_RESULT(ParseVar(&catch_.var)); + } CHECK_RESULT(ParseTerminatingInstrList(&catch_.exprs)); EXPECT(Rpar); diff --git a/src/wat-writer.cc b/src/wat-writer.cc index 317c0ac0..f0333540 100644 --- a/src/wat-writer.cc +++ b/src/wat-writer.cc @@ -82,8 +82,9 @@ struct ExprTree { // For debugging. std::string describe() const { std::string result("ExprTree("); - if (expr) + if (expr) { result.append(GetExprTypeName(*expr)); + } return result + ")"; } @@ -276,8 +277,9 @@ void WatWriter::WritePutsNewline(const char* s) { } void WatWriter::WriteNewline(bool force) { - if (next_char_ == NextChar::ForceNewline) + if (next_char_ == NextChar::ForceNewline) { WriteNextChar(); + } next_char_ = force ? NextChar::ForceNewline : NextChar::Newline; } @@ -296,8 +298,9 @@ void WatWriter::WriteOpenSpace(const char* name) { } void WatWriter::WriteClose(NextChar next_char) { - if (next_char_ != NextChar::ForceNewline) + if (next_char_ != NextChar::ForceNewline) { next_char_ = NextChar::None; + } Dedent(); WritePuts(")", next_char); } @@ -335,10 +338,11 @@ void WatWriter::WriteName(string_view str, NextChar next_char) { void WatWriter::WriteNameOrIndex(string_view str, Index index, NextChar next_char) { - if (!str.empty()) + if (!str.empty()) { WriteName(str, next_char); - else + } else { Writef("(;%u;)", index); + } } void WatWriter::WriteQuotedData(const void* data, size_t length) { @@ -396,12 +400,14 @@ void WatWriter::WriteType(Type type, NextChar next_char) { void WatWriter::WriteTypes(const TypeVector& types, const char* name) { if (types.size()) { - if (name) + if (name) { WriteOpenSpace(name); + } for (Type type : types) WriteType(type, NextChar::Space); - if (name) + if (name) { WriteCloseSpace(); + } } } @@ -415,11 +421,13 @@ void WatWriter::WriteBeginBlock(LabelType label_type, const char* text) { WritePutsSpace(text); bool has_label = !block.label.empty(); - if (has_label) + if (has_label) { WriteString(block.label, NextChar::Space); + } WriteTypes(block.sig, "result"); - if (!has_label) + if (!has_label) { Writef(" ;; label = @%" PRIindex, GetLabelStackSize()); + } WriteNewline(FORCE_NEWLINE); label_stack_.emplace_back(label_type, block.label, block.sig); Indent(); @@ -487,10 +495,12 @@ template <typename T> void WatWriter::WriteLoadStoreExpr(const Expr* expr) { auto typed_expr = cast<T>(expr); WritePutsSpace(typed_expr->opcode.GetName()); - if (typed_expr->offset) + if (typed_expr->offset) { Writef("offset=%u", typed_expr->offset); - if (!typed_expr->opcode.IsNaturallyAligned(typed_expr->align)) + } + if (!typed_expr->opcode.IsNaturallyAligned(typed_expr->align)) { Writef("align=%u", typed_expr->align); + } WriteNewline(NO_FORCE_NEWLINE); } @@ -707,8 +717,9 @@ Label* WatWriter::GetLabel(const Var& var) { if (var.is_name()) { for (Index i = GetLabelStackSize(); i > 0; --i) { Label* label = &label_stack_[i - 1]; - if (label->name == var.name()) + if (label->name == var.name()) { return label; + } } } else if (var.index() < GetLabelStackSize()) { Label* label = &label_stack_[GetLabelStackSize() - var.index() - 1]; @@ -868,8 +879,9 @@ void WatWriter::PushExpr(const Expr* expr, std::move(first_operand, last_operand, std::back_inserter(tree.children)); expr_tree_stack_.erase(first_operand, last_operand); expr_tree_stack_.emplace_back(tree); - if (result_count == 0) + if (result_count == 0) { FlushExprTreeStack(); + } } else { expr_tree_stack_.emplace_back(expr); FlushExprTreeStack(); @@ -994,16 +1006,18 @@ void WatWriter::WriteTypeBindings(const char* prefix, } const std::string& name = index_to_name_[i]; - if (!name.empty()) + if (!name.empty()) { WriteString(name, NextChar::Space); + } WriteType(types[i], NextChar::Space); if (!name.empty()) { WriteCloseSpace(); is_open = false; } } - if (is_open) + if (is_open) { WriteCloseSpace(); + } } void WatWriter::WriteFunc(const Module& module, const Func& func) { @@ -1073,10 +1087,12 @@ void WatWriter::WriteException(const Exception& except) { void WatWriter::WriteLimits(const Limits& limits) { Writef("%" PRIu64, limits.initial); - if (limits.has_max) + if (limits.has_max) { Writef("%" PRIu64, limits.max); - if (limits.is_shared) + } + if (limits.is_shared) { Writef("shared"); + } } void WatWriter::WriteTable(const Table& table) { @@ -1155,8 +1171,9 @@ void WatWriter::WriteImport(const Import& import) { } void WatWriter::WriteExport(const Export& export_) { - if (options_->inline_export) + if (options_->inline_export) { return; + } WriteOpenSpace("export"); WriteQuotedString(export_.name, NextChar::Space); WriteOpenSpace(GetKindName(export_.kind)); @@ -1262,8 +1279,9 @@ void WatWriter::BuildExportMap() { } void WatWriter::WriteInlineExports(ExternalKind kind, Index index) { - if (!options_->inline_export) + if (!options_->inline_export) { return; + } auto iter_pair = export_map_.equal_range(std::make_pair(kind, index)); for (auto iter = iter_pair.first; iter != iter_pair.second; ++iter) |