Write memory.init operands in the order the text format expects (#2838) The text format names the memory before the data segment: ``` (memory.init $mem $data ...) ``` `ParseMemoryInstrVar()` reads them in that order, but the writer emitted the data segment first and the memory second, which is the operand order of the *binary* encoding.
diff --git a/src/wat-writer.cc b/src/wat-writer.cc index f00332d..f3a52b6 100644 --- a/src/wat-writer.cc +++ b/src/wat-writer.cc
@@ -852,8 +852,11 @@ Result WatWriter::ExprVisitorDelegate::OnMemoryInitExpr(MemoryInitExpr* expr) { writer_->WritePutsSpace(Opcode::MemoryInit_Opcode.GetName()); - writer_->WriteVar(expr->var, NextChar::Space); + // The text format names the memory before the data segment, which is the + // opposite of the operand order used by the binary encoding. table.init has + // the same shape; ParseMemoryInstrVar() is the parser side of this. writer_->WriteMemoryVarUnlessZero(expr->memidx, NextChar::Space); + writer_->WriteVar(expr->var, NextChar::Space); writer_->WriteNewline(NO_FORCE_NEWLINE); return Result::Ok; }
diff --git a/test/roundtrip/data-nonzero-memory.txt b/test/roundtrip/data-nonzero-memory.txt new file mode 100644 index 0000000..fa6f5ee --- /dev/null +++ b/test/roundtrip/data-nonzero-memory.txt
@@ -0,0 +1,21 @@ +;;; TOOL: run-roundtrip +;;; ARGS: --stdout +(module + (memory $mem1 1) + (memory $mem2 1) + (data $d "\01\02\03\04") + (func + (memory.init $mem2 $d (i32.const 0) (i32.const 0) (i32.const 4))) +) +(;; STDOUT ;;; +(module + (type (;0;) (func)) + (func (;0;) (type 0) + i32.const 0 + i32.const 0 + i32.const 4 + memory.init 1 0) + (memory (;0;) 1) + (memory (;1;) 1) + (data (;0;) "\01\02\03\04")) +;;; STDOUT ;;)