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

require_relative "../task_helper"

MATHEMATICA_KEYWORDS_FILE = "./lib/rouge/lexers/mathematica/keywords.rb"

namespace :builtins do
  task :mathematica do
    MathematicaBuiltins.process(MATHEMATICA_KEYWORDS_FILE)
  end
end

class MathematicaBuiltins < BuiltinsGenerator
  MATHEMATICA_SYNTAX_URI = "https://reference.wolfram.com/language/guide/AlphabeticalListing.html"

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

  def parse
    keywords = []

    @input.scrub.scan %r(<span class="IFSans"><a href="/language/ref/(\w+)[.]html">)m do |m|
      keywords << m[0]
    end

    keywords.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:mathematica`."
    yield   "# See tasks/builtins/mathematica.rake for more info."
    yield   ""
    yield   "module Rouge"
    yield   "  module Lexers"
    yield   "    class Mathematica"
    yield   "      BUILTINS = Set#{@keywords.inspect}"
    yield   "    end"
    yield   "  end"
    yield   "end"
  end
end
