<commit_before>require "../term"

module ReQL
  class FuncTerm < Term
    def inspect(io)
      vars = @args[0].as(Array)
      body = @args[1]
      if vars.size == 1
        io << "var_" << vars[0] << " => "
      else
        io << "("
        io << vars.map { |i| "var_#{i}" }.join(", ")
        io << ") => "
      end
      body.inspect(io)
    end

    def check
      expect_args 2

      mentioned_variables = Set(Int64).new
      FuncTerm.visit_variables(self) do |var|
        mentioned_variables.add(var)
      end

      args = @args[0].as(Array)
      until args.size == 0 || mentioned_variables.includes? args.last
        args.pop
      end

      @args[0] = args
    end

    def self.visit_variables(term, &block : Int64 ->)
      case term
      when Term
        term.args.each { |arg| visit_variables arg, &block }<commit_msg>fix: simplification of FuncTerm arguments on initialization<commit_after>require "../term"

module ReQL
  class FuncTerm < Term
    def initialize(args, options)
      super(args, options)

      mentioned_variables = Set(Int64).new
      FuncTerm.visit_variables(self) do |var|
        mentioned_variables.add(var)
      end

      args = @args[0].as(Array)
      until args.size == 0 || mentioned_variables.includes? args.last
        args.pop
      end

      @args[0] = args
    end

    def inspect(io)
      vars = @args[0].as(Array)
      body = @args[1]
      if vars.size == 1
        io << "var_" << vars[0] << " => "
      else
        io << "("
        io << vars.map { |i| "var_#{i}" }.join(", ")
        io << ") => "
      end
      body.inspect(io)
    end

    def check
      expect_args 2
    end

    def self.visit_variables(term, &block : Int64 ->)
      case term
      when Term
        term.args.each { |arg| visit_variables arg, &block }
{'fraction_non_alphanumeric': 0.13646408839779006, 'fraction_numerical': 0.013259668508287293, 'mean_word_length': 1.9495114006514658, 'pattern_counts': {'":': 0, '<': 29, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5487813', 'n_tokens_mistral': 610, 'n_tokens_neox': 588, 'n_words': 144}