Allow instruction group definitions in .bin_fmt files to omit width and infer it from the base format.

- Update `instruction_group_def` in `BinFormat.g4` (`width=index?`) so single instruction groups can omit `[width]`.
- Update `BinFormatVisitor::VisitInstructionGroupDef` in `bin_format_visitor.cc` to infer the group width from the base format when `[width]` is omitted, keep width-mismatch and `<= 64`-bit validation, and guard against null base formats when format validation fails.
- Document optional `[width]` inference on `instruction group` in `decoder/doc/binary-encoding.md`.
- Add unit tests in `decoder/test/bin_format_visitor_test.cc` covering inferred group widths (including inherited base format widths and merged groups) and error diagnostics.

PiperOrigin-RevId: 1025893271
Change-Id: I13e351718cefa9be1c9a124034b1f6be4d96c71f
diff --git a/mpact/sim/decoder/BinFormat.g4 b/mpact/sim/decoder/BinFormat.g4
index 67c8bbd..7d538a9 100644
--- a/mpact/sim/decoder/BinFormat.g4
+++ b/mpact/sim/decoder/BinFormat.g4
@@ -38,8 +38,9 @@
 //      structs and unions alongside functional extractors/inserters.
 //
 // 3. Instruction groups ('instruction group'):
-//    - Group instruction encodings that share a bit width (up to 64 bits) and
-//      whose formats match or derive from a common base format, or merge
+//    - Group instruction encodings that share a bit width (up to 64 bits,
+//      either declared explicitly or inferred from the group's base format)
+//      and whose formats match or derive from a common base format, or merge
 //      existing compatible instruction groups ('= { Group1, Group2 }').
 //    - Each instruction encoding constrains fields or overlays using relational
 //      operators ('==', '!=', '>', '>=', '<', '<=') against numeric literals or
@@ -199,12 +200,15 @@
   ;
 
 // Defines either:
-//   1. A single instruction group of 'number'-bit instructions (up to 64 bits)
-//      whose encoding formats are 'inst_format' or derive from 'inst_format'.
+//   1. A single instruction group of instructions (up to 64 bits wide) whose
+//      encoding formats are 'inst_format' or derive from 'inst_format'. The
+//      explicit bit width ('[number]') is optional; when omitted, the group's
+//      width is inferred from 'inst_format' (if both are given, they must
+//      match).
 //   2. A composite instruction group formed by merging two or more previously
 //      defined instruction groups that share the same width and base format.
 instruction_group_def
-  : INSTRUCTION GROUP name=IDENT '[' number ']' ':' inst_format=IDENT
+  : INSTRUCTION GROUP name=IDENT width=index? ':' inst_format=IDENT
     '{' instruction_def_list '}' ';'?
   | INSTRUCTION GROUP name=IDENT '=' '{' group_name_list '}' ';'?
   ;
diff --git a/mpact/sim/decoder/bin_format_visitor.cc b/mpact/sim/decoder/bin_format_visitor.cc
index 03729b6..e640bd8 100644
--- a/mpact/sim/decoder/bin_format_visitor.cc
+++ b/mpact/sim/decoder/bin_format_visitor.cc
@@ -944,10 +944,10 @@
         file_names_[context_file_map_.at(ctx)], ctx->start,
         absl::StrCat(group_name, ": illegal use of format name"));
   }
-  // If the width is specified, this is a single instruction group with
-  // format definitions.
-  if (ctx->number() != nullptr) {
-    int width = ConvertToInt(ctx->number());
+  // If an instruction format is specified, this is a single instruction group
+  // with format definitions (the width may be explicit or inferred from the
+  // base format).
+  if (ctx->inst_format != nullptr) {
     std::string format_name = ctx->inst_format->getText();
     auto iter = format_decl_map_.find(format_name);
     if (iter == format_decl_map_.end()) {
@@ -956,27 +956,30 @@
           absl::StrCat("Undefined format '", format_name,
                        "' used by instruction group '", group_name, "'"));
       return nullptr;
-    } else {
-      VisitFormatDef(iter->second, encoding_info);
-      auto* format = encoding_info->GetFormat(format_name);
-      // Verify that the format width = declared width and also <= 64 bits wide.
-      if (format->declared_width() != width) {
-        error_listener_->semanticError(
-            file_names_[context_file_map_.at(format_decl_map_.at(format_name))],
-            ctx->start,
-            absl::StrCat("Width of format '", format_name, "' (",
-                         format->declared_width(),
-                         ") differs from the declared width of instruction "
-                         "group '",
-                         group_name, "' (", width, ")"));
-      }
-      if (format->declared_width() > 64) {
-        error_listener_->semanticError(
-            file_names_[context_file_map_.at(format_decl_map_.at(format_name))],
-            ctx->start,
-            absl::StrCat("Instruction group '", group_name,
-                         "': width must be <= 64 bits"));
-      }
+    }
+    VisitFormatDef(iter->second, encoding_info);
+    auto* format = encoding_info->GetFormat(format_name);
+    if (format == nullptr) return nullptr;
+    int width = (ctx->width != nullptr) ? ConvertToInt(ctx->width->number())
+                                        : format->declared_width();
+    // Verify that the format width matches any declared width and is <= 64
+    // bits wide.
+    if ((ctx->width != nullptr) && (format->declared_width() != width)) {
+      error_listener_->semanticError(
+          file_names_[context_file_map_.at(format_decl_map_.at(format_name))],
+          ctx->start,
+          absl::StrCat("Width of format '", format_name, "' (",
+                       format->declared_width(),
+                       ") differs from the declared width of instruction "
+                       "group '",
+                       group_name, "' (", width, ")"));
+    }
+    if ((width > 64) || (format->declared_width() > 64)) {
+      error_listener_->semanticError(
+          file_names_[context_file_map_.at(format_decl_map_.at(format_name))],
+          ctx->start,
+          absl::StrCat("Instruction group '", group_name,
+                       "': width must be <= 64 bits"));
     }
     auto inst_group_res =
         encoding_info->AddInstructionGroup(group_name, width, format_name);
diff --git a/mpact/sim/decoder/doc/binary-encoding.md b/mpact/sim/decoder/doc/binary-encoding.md
index 08fe6cf..5766009 100644
--- a/mpact/sim/decoder/doc/binary-encoding.md
+++ b/mpact/sim/decoder/doc/binary-encoding.md
@@ -129,7 +129,8 @@
 };
 
 // 3. Define the instruction encodings and field constraints.
-instruction group MiniRisc32[32] : Inst32 {
+//    ('[32]' is optional here; when omitted, Inst32's width is inferred.)
+instruction group MiniRisc32 : Inst32 {
   add  : RType : funct7 == 0b000'0000, funct3 == 0b000, opcode == 0b011'0011;
   addi : IType : funct3 == 0b000, opcode == 0b001'0011;
   beq  : BType : funct3 == 0b000, opcode == 0b110'0011;
@@ -402,10 +403,13 @@
 1.  **Width inheritance & checking**: If `[width]` is omitted on the child
     format, it inherits the parent format's bit width. If `[width]` is specified
     on both, `bin_format_gen` verifies that they match.
-2.  **Instruction group membership**: Every `instruction group` specifies a base
-    format (`instruction group Name[width] : BaseFormat`). Only formats equal to
+2.  **Instruction group membership & width inference**: Every
+    `instruction group` specifies a base format
+    (`instruction group Name : BaseFormat` or
+    `instruction group Name[width] : BaseFormat`). Only formats equal to
     `BaseFormat` or transitively derived from `BaseFormat` may be used in that
-    group.
+    group, and when `[width]` is omitted on the group, its bit width is inferred
+    directly from `BaseFormat`.
 3.  **Extractor promotion**: Non-conflicting field and overlay extractors
     defined in child formats are automatically promoted into their ancestor
     format's namespace as convenience wrappers (provided no sibling/ancestor
@@ -542,6 +546,11 @@
 ### Single Instruction Group
 
 ```c
+instruction group GroupName : BaseFormat {
+  // instruction encodings...
+};
+
+// Or with an explicit '[width]' (checked against BaseFormat):
 instruction group GroupName[width] : BaseFormat {
   // instruction encodings...
 };
@@ -549,17 +558,20 @@
 
 Rules for a single instruction group:
 
-*   **`[width]`**: Every instruction in the group has this exact bit width (**up
-    to 64 bits**). If your ISA has both 16-bit compressed instructions and
-    32-bit standard instructions (like RISC-V C + G), place the 16-bit
-    instructions in a `[16]` group and the 32-bit instructions in a `[32]`
-    group. (For VLIW bundles wider than 64 bits, define a bundle `format` for
-    the full bundle width and define separate `instruction group`s for each
-    `<= 64`-bit instruction slot format!)
+*   **Bit width (`[width]`, optional)**: Every instruction in the group has the
+    same bit width (**up to 64 bits**). When `[width]` is omitted, the group's
+    bit width is inferred automatically from `BaseFormat` (including when
+    `BaseFormat` itself inherits its width from an ancestor format). When
+    `[width]` is specified explicitly, `bin_format_gen` verifies that it matches
+    `BaseFormat`'s width. If your ISA has both 16-bit compressed instructions
+    and 32-bit standard instructions (like RISC-V C + G), place the 16-bit
+    instructions in a 16-bit group (`: Inst16Base`) and the 32-bit instructions
+    in a 32-bit group (`: Inst32Base`). (For VLIW bundles wider than 64 bits,
+    define a bundle `format` for the full bundle width and define separate
+    `instruction group`s for each `<= 64`-bit instruction slot format!)
 *   **`: BaseFormat`**: Every instruction encoding in the group must reference
     either `BaseFormat` itself or a format that inherits (directly or
-    indirectly) from `BaseFormat`, and `BaseFormat`'s width must equal
-    `[width]`.
+    indirectly) from `BaseFormat`.
 
 ### Standard Instruction Encoding and Constraints
 
@@ -932,6 +944,11 @@
     formats shares identical C++ extractor namespaces (`r_type::ExtractRs1`,
     `v_arith::ExtractVm`), allowing C++ operand getter libraries (`*_getters.h`)
     to be reused across multiple simulator variants.
+3.  **Decoupled group widths**: Because `instruction group Name : BaseFormat`
+    infers its bit width from `BaseFormat` when `[width]` is omitted, shared
+    instruction-encoding files do not need to hardcode slot widths—making it
+    easy to reuse encoding groups across related ISA or VLIW variants whose
+    format files widen or narrow a slot while preserving field names.
 
 ### 2. Split Instruction Encodings by Extension or Functional Unit
 
@@ -1115,10 +1132,11 @@
     points to the C++ `OpcodeEnum` namespace from `.isa`, and
     `includes { #include "<prefix>_enums.h" }` is present in `decoder { ... }`.
 *   **VLIW bundle wider than 64 bits**: Do **not** create an `instruction group`
-    with `[width]` > 64. Instead, define a `format Bundle[128]` (or `[256]`)
+    wider than 64 bits (whether via an explicit `[width]` > 64 or a `BaseFormat`
+    wider than 64 bits). Instead, define a `format Bundle[128]` (or `[256]`)
     containing sub-formats for each slot (`format AluSlot alu[2];`), and define
-    separate `instruction group AluGroup[42] : AluSlot { ... };` blocks for each
-    slot!
+    separate `instruction group AluGroup : AluSlot { ... };` blocks for each
+    `<= 64`-bit slot!
 
 --------------------------------------------------------------------------------
 
diff --git a/mpact/sim/decoder/test/bin_format_visitor_test.cc b/mpact/sim/decoder/test/bin_format_visitor_test.cc
index b1da3ed..51e447e 100644
--- a/mpact/sim/decoder/test/bin_format_visitor_test.cc
+++ b/mpact/sim/decoder/test/bin_format_visitor_test.cc
@@ -637,4 +637,171 @@
   EXPECT_TRUE(ptr != std::string::npos);
 }
 
+TEST_F(BinFormatVisitorTest, InstructionGroupInferredWidth) {
+  std::string file_name = testing::TempDir() + "/inferred_group_width.bin_fmt";
+  std::ofstream output_file(file_name, std::ofstream::out);
+  CHECK(output_file.good());
+  output_file << R"bin_fmt(
+decoder InferredWidthDecoder {
+  namespace sim::inferred_width;
+  opcode_enum = "isa::OpcodeEnum";
+  Inst16Group;
+  Combined32 = { Inst32GroupA, Inst32GroupB };
+};
+
+format Inst16Format[16] {
+  fields:
+    unsigned func4[4];
+    unsigned rs1[5];
+    unsigned rs2[5];
+    unsigned op[2];
+};
+
+format Inst32Format[32] {
+  fields:
+    unsigned bits[25];
+    unsigned opcode[7];
+};
+
+// Base format whose own width is inherited from Inst32Format.
+format SubBase32 : Inst32Format {
+  fields:
+    unsigned imm12[12];
+    unsigned rs1[5];
+    unsigned func3[3];
+    unsigned rd[5];
+    unsigned opcode[7];
+};
+
+// Group omitting '[width]' on a 16-bit base format.
+instruction group Inst16Group : Inst16Format {
+  c_add : Inst16Format : func4 == 0b1001, op == 0b10;
+};
+
+// Group omitting '[width]' on a base format with inherited 32-bit width,
+// merged with a sibling group that declares '[32]' explicitly.
+instruction group Inst32GroupA : SubBase32 {
+  addi : SubBase32 : func3 == 0b000, opcode == 0b001'0011;
+};
+
+instruction group Inst32GroupB[32] : SubBase32 {
+  ori : SubBase32 : func3 == 0b110, opcode == 0b001'0011;
+};
+)bin_fmt";
+  output_file.close();
+
+  std::vector<std::string> input_files = {file_name};
+  std::string output_dir = getenv(kTestUndeclaredOutputsDir);
+  constexpr char kPrefix[] = "inferred_group_width";
+
+  BinFormatVisitor visitor;
+  LogSink log_sink;
+  absl::AddLogSink(&log_sink);
+  EXPECT_TRUE(visitor
+                  .Process(input_files, "InferredWidthDecoder", kPrefix, paths_,
+                           output_dir)
+                  .ok())
+      << log_sink.error_log();
+  absl::RemoveLogSink(&log_sink);
+  EXPECT_TRUE(log_sink.error_log().empty()) << log_sink.error_log();
+
+  std::string decoder_hdr_path =
+      absl::StrCat(output_dir, "/", kPrefix, "_bin_decoder.h");
+  ASSERT_TRUE(FileExists(decoder_hdr_path));
+  std::ifstream decoder_hdr(decoder_hdr_path);
+  CHECK(decoder_hdr.good());
+  std::string hdr_str((std::istreambuf_iterator<char>(decoder_hdr)),
+                      (std::istreambuf_iterator<char>()));
+  EXPECT_TRUE(RE2::PartialMatch(hdr_str, R"(DecodeInst16Group\(uint16_t\b)"))
+      << hdr_str;
+  EXPECT_TRUE(RE2::PartialMatch(hdr_str, R"(DecodeCombined32\(uint32_t\b)"))
+      << hdr_str;
+}
+
+TEST_F(BinFormatVisitorTest, InstructionGroupInferredWidthErrors) {
+  std::string file_name =
+      testing::TempDir() + "/inferred_group_width_errors.bin_fmt";
+  std::ofstream output_file(file_name, std::ofstream::out);
+  CHECK(output_file.good());
+  output_file << R"bin_fmt(
+decoder InferredWidthErrors {
+  namespace sim::inferred_width_errors;
+  opcode_enum = "isa::OpcodeEnum";
+  WideGroup;
+  Group32;
+  UndefBaseGroup;
+  InvalidBaseGroup;
+};
+
+format Inst32Format[32] {
+  fields:
+    unsigned bits[32];
+};
+
+format Format33[33] {
+  fields:
+    unsigned bits[33];
+};
+
+format Inst72Format[72] {
+  fields:
+    unsigned bits[72];
+};
+
+format NoWidthFormat {
+  fields:
+    unsigned bits[32];
+};
+
+instruction group WideGroup : Inst72Format {
+  wide_inst : Inst72Format : bits == 0;
+};
+
+instruction group Group32 : Inst32Format {
+  bad_len : Format33 : bits == 0;
+};
+
+instruction group UndefBaseGroup : MissingFormat {
+};
+
+instruction group InvalidBaseGroup : NoWidthFormat {
+  bad_base : NoWidthFormat : bits == 0;
+};
+)bin_fmt";
+  output_file.close();
+
+  std::vector<std::string> input_files = {file_name};
+  std::string output_dir = getenv(kTestUndeclaredOutputsDir);
+
+  BinFormatVisitor visitor;
+  LogSink log_sink;
+  absl::AddLogSink(&log_sink);
+  EXPECT_FALSE(visitor
+                   .Process(input_files, "InferredWidthErrors",
+                            "inferred_group_width_errors", paths_, output_dir)
+                   .ok());
+  absl::RemoveLogSink(&log_sink);
+
+  EXPECT_NE(
+      log_sink.error_log().find(
+          "Error: Instruction group 'WideGroup': width must be <= 64 bits"),
+      std::string::npos)
+      << log_sink.error_log();
+  EXPECT_NE(log_sink.error_log().find(
+                "Error: Length of format 'Format33' (33) differs from the "
+                "declared width of the instruction group (32)"),
+            std::string::npos)
+      << log_sink.error_log();
+  EXPECT_NE(log_sink.error_log().find(
+                "Error: Undefined format 'MissingFormat' used by instruction "
+                "group 'UndefBaseGroup'"),
+            std::string::npos)
+      << log_sink.error_log();
+  EXPECT_NE(log_sink.error_log().find(
+                "Error: Format 'NoWidthFormat': must specify a width or "
+                "inherited format"),
+            std::string::npos)
+      << log_sink.error_log();
+}
+
 }  // namespace