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

require 'yaml'

# YAML file is made by manually copying keywords from https://www.mathworks.com/help/matlab/referencelist.html?type=function&listtype=alpha&category=index&blocktype=&capability=
MATLAB_SYNTAX_FILE = File.join(__dir__, "matlab/builtins.yml")
MATLAB_KEYWORDS_FILE = "./lib/rouge/lexers/matlab/keywords.rb"

namespace :builtins do
  task :matlab do
    generator = Rouge::Tasks::Builtins::Matlab.new

    input    = File.read(MATLAB_SYNTAX_FILE)
    keywords = generator.extract_keywords(input)

    output = generator.render_output(keywords)

    File.write(MATLAB_KEYWORDS_FILE, output)
  end
end

module Rouge
  module Tasks
    module Builtins
      class Matlab
        def extract_keywords(input)
          ::YAML.load(input)
        end

        def render_output(keywords, &b)
          return enum_for(:render_output, keywords).to_a.join("\n") unless b

          yield   "# -*- coding: utf-8 -*- #"
          yield   "# frozen_string_literal: true"
          yield   ""
          yield   "# DO NOT EDIT"
          yield   ""
          yield   "# This file is automatically generated by `rake builtins:matlab`."
          yield   "# See tasks/builtins/matlab.rake for more info."
          yield   ""
          yield   "module Rouge"
          yield   "  module Lexers"
          yield   "    def Matlab.builtins"
          yield   "      @builtins ||= Set.new #{keywords.inspect}"
          yield   "    end"
          yield   "  end"
          yield   "end"
        end
      end
    end
  end
end
