# todo layout horizontally better
# todo allow export or link to online graphviz editor
def ast2viz(ast, output_inds)
  output = ""

  draw_node = -> i,label {
    style = "[shape=Msquare]" if output_inds.include? i
    output<< "a#{i} #{style} [label=#{label.inspect}];\n"
  }

  draw_arg_arrows = -> a,i,label,extra_arg {
    a.args.each.with_index{|arg,arg_ind|
      arrowhead = "[arrowhead=empty]" if arg_ind > 0
      output<< "a#{arg} -> a#{i} #{arrowhead};\n"
    }
    output<< "a#{extra_arg} -> a#{i} [style=dashed];\n" if extra_arg
    draw_node[i, label]
  }

  output<< "digraph {\n"
  ast.each.with_index{|a,i|
    label = a.label || (a.token ? a.token.str : a.type.to_s  )
    extra_arg = a.impl
    case a.type
    when :MatchedEndBracket
      label = ">"
      extra_arg = nil
    when :UnmatchedEndBracket
      label = "> sets implicit"
    when :VirtualDuped0
      extra_arg = a.token.duped_value.args[0]
    when :VirtualDuped1
      extra_arg = a.token.duped_value.args[1]
    when :ImplicitValue
      label = "implicit" # these actually have token set for parse alg reasons
    else
    end
    draw_arg_arrows[a,i,label,extra_arg]
  }
  output<< "}\n"
  output
end

# todo show if implicit ops (maybe could use arrow type for implicit ops?)
# todo show range of zip levels
def ir2viz(ir2,out_inds)
  output = ""
  output<< "digraph {\n"
  output<< "node [fontname = \"courier\", ];\n"

  ir2.each.with_index{|node,i|
    node.args.each.with_index{|arg,arg_ind|
      arrowhead = "[arrowhead=empty]" if arg_ind > 0
      output<< "a#{arg} -> a#{i} #{arrowhead};\n"
    }

    label = node.way.name == "data" ?
      to_eager_str(inspectv(node.type,node.rank,node.way.impl.call.const)).inspect :
      ("."*node.zip_level + node.way.name).inspect
    color = case node.type
      when IntType
        '[fontcolor="#ff6600"]'
      when CharType
        '[fontcolor="#005c99"]'
      else
        ""
      end
    style = "[shape=Msquare]" if out_inds.include? i
    style2 = "[style=dashed]" if node.rank == 0
    output<< "a#{i} #{color} #{style} #{style2} [peripheries=#{[node.rank,1].max}] [label=#{label}];\n"
  }
  output<< "}\n"
  output
end
