/*

  NewtonScript function object dump for NTK

*/

/* ex.

run on NTK:
  dumpFn:dump("local foo := 1; bar := foo + 3");

  "local foo := 1; bar := foo + 3"
{instructions: "<#instructions: 0x24, 0xA3, 0x7B, 0x27, 0x00, 0x0C, 0xC0, 0xA8, 0x70, 0x02>", 
  literals: [literals: bar], 
  argFrame: {_nextArgFrame: NIL, _parent: NIL, _implementor: NIL, foo: NIL}, 
  numArgs: 0, 
  DebuggerInfo: 2}

run on NEWT/0:
  DumpBC(<#instructions: 0x24, 0xA3, 0x7B, 0x27, 0x00, 0x0C, 0xC0, 0xA8, 0x70, 0x02>);

     0 : 24                  push-constant (b =   4)
     1 : a3                        set-var (b =   3)
     2 : 7b                        get-var (b =   3)
     3 : 27 00 0c            push-constant (b =  12)
     6 : c0                            add          
     7 : a8               find-and-set-var (b =   0)
     8 : 70                       find-var (b =   0)
     9 : 02                         return          

*/

dumpFn := {
	hexstr: func(v)
	begin
		local h := "0123456789ABCDEF";
		local s;

		s := h[v >> 4];
		s := s & h[band(v, 0x0F)];

		"0x" & s;
	end,

	convert: func(fn)
	begin
		local b;
		local s;

		fn := clone(fn);
		removeslot(fn, 'class);

		for i := 0 to length(fn.instructions) - 1 do begin
			b := extractByte(fn.instructions, i);
			s := s && :hexstr(b) & ",";
		end;

		trimString(s);
		setlength(s, length(s) - 1);
		s := "<#instructions:" && s & ">";

		fn.instructions := s;

		return fn;
	end,

	dump: func(fnStr)
	begin
		local fn;


		print(fnStr);
		fn := compile(fnStr);
		print(:convert(fn));

	end
};
