# -*- coding: utf-8 -*- #
# frozen_string_literal: true

require_relative "../task_helper"

LUA_KEYWORDS_FILE = "./lib/rouge/lexers/lua/keywords.rb"

namespace :builtins do
  task :lua do
    LuaBuiltins.process(LUA_KEYWORDS_FILE)
  end
end

class LuaBuiltins < BuiltinsGenerator
  LUA_SYNTAX_VERSION = "5.3"
  LUA_SYNTAX_URI = "https://www.lua.org/manual/#{LUA_SYNTAX_VERSION}/"

  def fetch
    URI.open(LUA_SYNTAX_URI) { |f| f.read }
  end

  def parse
    keywords = Hash.new { |h,k| h[k] = Array.new }

    @input.scrub.scan(%r[<a href="manual.html#pdf-(.+?)">\1</a>]im) do |m|
      name = m[0].downcase

      key = if name.start_with? "package"
              "modules"
            elsif name.include? "."
              name.split(".").first
            elsif %w(require module).include? name
              "modules"
            else
              "basic"
            end

      keywords[key].push name
    end

    keywords.transform_values { |v| v.sort.uniq }
  end

  def generate
    yield   "# -*- coding: utf-8 -*- #"
    yield   "# frozen_string_literal: true"
    yield   ""
    yield   "# DO NOT EDIT"
    yield   ""
    yield   "# This file is automatically generated by `rake builtins:lua`."
    yield   "# See tasks/builtins/lua.rake for more info."
    yield   ""
    yield   "module Rouge"
    yield   "  module Lexers"
    yield   "    class Lua"
    yield   "      BUILTINS = {}.tap do |b|"
    @keywords.each do |n, fs|
      yield "        b[#{n.inspect}] = Set#{fs.uniq.inspect}"
    end
    yield   "      end"
    yield   "    end"
    yield   "  end"
    yield   "end"
  end
end
