class Racc::States

def lookahead

def lookahead
  #
  # lookahead algorithm ver.3 -- from bison 1.26
  #
  gotos = @gotos
  if @d_la
    puts "\n--- goto ---"
    gotos.each_with_index {|g, i| print i, ' '; p g }
  end
  ### initialize_LA()
  ### set_goto_map()
  la_rules = []
  @states.each do |state|
    state.check_la la_rules
  end
  ### initialize_F()
  f     = create_tmap(gotos.size)
  reads = []
  edge  = []
  gotos.each do |goto|
    goto.to_state.goto_table.each do |t, st|
      if t.terminal?
        f[goto.ident] |= (1 << t.ident)
      elsif t.nullable?
        edge.push goto.to_state.gotos[t].ident
      end
    end
    if edge.empty?
      reads.push nil
    else
      reads.push edge
      edge = []
    end
  end
  digraph f, reads
  if @d_la
    puts "\n--- F1 (reads) ---"
    print_tab gotos, reads, f
  end
  ### build_relations()
  ### compute_FOLLOWS
  path = nil
  edge = []
  lookback = Array.new(la_rules.size, nil)
  includes = []
  gotos.each do |goto|
    goto.symbol.heads.each do |ptr|
      path = record_path(goto.from_state, ptr.rule)
      lastgoto = path.last
      st = lastgoto ? lastgoto.to_state : goto.from_state
      if st.conflict?
        addrel lookback, st.rruleid(ptr.rule), goto
      end
      path.reverse_each do |g|
        break if     g.symbol.terminal?
        edge.push    g.ident
        break unless g.symbol.nullable?
      end
    end
    if edge.empty?
      includes.push nil
    else
      includes.push edge
      edge = []
    end
  end
  includes = transpose(includes)
  digraph f, includes
  if @d_la
    puts "\n--- F2 (includes) ---"
    print_tab gotos, includes, f
  end
  ### compute_lookaheads
  la = create_tmap(la_rules.size)
  lookback.each_with_index do |arr, i|
    if arr
      arr.each do |g|
        la[i] |= f[g.ident]
      end
    end
  end
  if @d_la
    puts "\n--- LA (lookback) ---"
    print_tab la_rules, lookback, la
  end
  la
end