Class: Code::Object::Function

Inherits:
Code::Object show all
Defined in:
lib/code/object/function.rb

Direct Known Subclasses

Super

Constant Summary collapse

CLASS_DOCUMENTATION =
{
  name: "Function",
  description:
    "stores a callable block with parameters, captured context, and documentation.",
  examples: [
    "Function.new",
    "((value) => { value + 1 }).call(1)",
    "((value) => { value }).parameters.length"
  ]
}.freeze
INSTANCE_FUNCTIONS =
{
  "call" => {
    name: "call",
    description:
      "evaluates the function body with the provided arguments.",
    examples: [
      "((value) => { value + 1 }).call(1)",
      "((name:) => { name }).call(name: :ada)",
      "((a, b = 2) => { a + b }).call(3)"
    ]
  },
  "new" => {
    name: "new",
    description:
      "evaluates the function body as a constructor with the provided arguments.",
    examples: [
      "Widget = () => { self.name = :widget return(self) } Widget.new.name",
      "User = (name:) => { self.name = name return(self) } User.new(name: :ada).name",
      "Counter = () => { self.count = 0 return(self) } Counter.new.count"
    ]
  },
  "extend" => {
    name: "extend",
    description:
      "creates a child function that can call the receiver through super.",
    examples: [
      "Base = () => { self.name = :base } Child = Base.extend(() => { super() }) Child().name",
      "Base = () => { 1 } Child = Base.extend(() => { super() }) Child()",
      "Base = (name) => { self.name = name } Child = Base.extend((...) => { super(...) }) Child(:a).name"
    ]
  },
  "documentation" => {
    name: "documentation",
    description:
      "returns or replaces the function documentation dictionary.",
    examples: [
      "f = () => { 1 } f.documentation",
      "f = () => { 1 } f.documentation(description: \"returns one\", examples: [\"f()\"])",
      "f = () => { 1 } f.documentation(description: \"returns one\", examples: [\"f()\"]).description"
    ]
  },
  "documentation=" => {
    name: "documentation=",
    description: "replaces the function documentation dictionary.",
    examples: [
      "f = () => { 1 } f.documentation = { description: \"returns one\", examples: [\"f()\"] }",
      "f = () => { 1 } f.documentation = { name: \"one\", description: \"returns one\", examples: [\"one()\"] } f.documentation.name",
      "f = () => { 1 } f.documentation = { description: \"returns one\", examples: [\"f()\"] } f.documentation.examples.first"
    ]
  },
  "parameters" => {
    name: "parameters",
    description:
      "returns a list of parameter descriptors for the function.",
    examples: [
      "((name) => { name }).parameters.first.name",
      "((name = :a) => { name }).parameters.first.default",
      "((...values) => { values }).parameters.first.spread?"
    ]
  },
  "to_string" => {
    name: "to_string",
    description: "formats the function as source code.",
    examples: [
      "(() => { 1 }).to_string",
      "((value) => { value + 1 }).to_string",
      "((name:) => { name }).to_string"
    ]
  }
}.freeze

Constants inherited from Code::Object

CLASS_FUNCTIONS, NUMBER_CLASSES

Constants included from Concerns::Shared

Concerns::Shared::COMPOUND_ASSIGNMENT_OPERATORS, Concerns::Shared::OPERATOR_METHOD_ALIASES, Concerns::Shared::SHARED_OPERATORS

Instance Attribute Summary collapse

Attributes included from Concerns::Shared

#functions, #raw

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Code::Object

class_documentation, class_functions, code_new, #code_new, documentation, documentation_for, documented_functions_for, function_documentation_for, function_documentation_registry_for, functions, inherited_function_documentation_for, instance_functions, maybe, #name, repeat, sorted_dictionary, |

Methods included from Concerns::Shared

#<=>, #==, #as_json, #blank?, #code_and, #code_as_json, #code_blank?, #code_compare, #code_different, #code_documentable_functions, #code_documentation, #code_duplicate, #code_dynamic_call, #code_equal, #code_exclamation_mark, #code_exclusive_range, #code_false?, #code_falsy?, code_fetch, code_get, #code_greater, #code_greater_or_equal, #code_inclusive_range, #code_inspect, #code_instance_of?, #code_is_a?, #code_itself, #code_less, #code_less_or_equal, #code_name, #code_nothing?, #code_or, #code_presence, #code_presence_in, #code_present?, #code_respond_to?, #code_same_object?, #code_self, #code_send, code_set, #code_something?, #code_strict_different, #code_strict_equal, #code_tap, #code_then, #code_to_boolean, #code_to_class, #code_to_date, #code_to_decimal, #code_to_dictionary, #code_to_duration, #code_to_integer, #code_to_json, #code_to_list, #code_to_nothing, #code_to_parameter, #code_to_range, #code_to_time, #code_true?, #code_truthy?, #eql?, #falsy?, #hash, #inspect, #multi_fetch, #nothing?, #present?, #sig, #something?, #succ, #to_code, #to_i, #to_json, #to_s, #truthy?

Constructor Details

#initialize(*args, parent: nil, functions: nil, **_kargs, &_block) ⇒ Function

Returns a new instance of Function.



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/code/object/function.rb', line 101

def initialize(*args, parent: nil, functions: nil, **_kargs, &_block)
  @code_parameters =
    List
      .new(args.first)
      .raw
      .map { |parameter| Parameter.new(parameter) }
      .to_code

  @code_body = Code.new(args.second.presence)
  @definition_context = args.third if args.third.is_a?(Context)
  @definition_object = args.fourth if args.fourth.is_a?(Object)
  @parent = parent.to_code
  self.functions = functions.to_code
  self.functions = Dictionary.new if self.functions.nothing?
  @instance_functions = Dictionary.new
  self.documentation =
    Dictionary.new(
      "name" => String.new(""),
      "description" => String.new(""),
      "examples" => List.new
    )

  self.raw = List.new([code_parameters, code_body])
end

Instance Attribute Details

#code_bodyObject (readonly)

Returns the value of attribute code_body.



94
95
96
# File 'lib/code/object/function.rb', line 94

def code_body
  @code_body
end

#code_parametersObject (readonly)

Returns the value of attribute code_parameters.



94
95
96
# File 'lib/code/object/function.rb', line 94

def code_parameters
  @code_parameters
end

#definition_contextObject (readonly)

Returns the value of attribute definition_context.



94
95
96
# File 'lib/code/object/function.rb', line 94

def definition_context
  @definition_context
end

#definition_objectObject (readonly)

Returns the value of attribute definition_object.



94
95
96
# File 'lib/code/object/function.rb', line 94

def definition_object
  @definition_object
end

#documentationObject

Returns the value of attribute documentation.



93
94
95
# File 'lib/code/object/function.rb', line 93

def documentation
  @documentation
end

#instance_functionsObject (readonly)

Returns the value of attribute instance_functions.



94
95
96
# File 'lib/code/object/function.rb', line 94

def instance_functions
  @instance_functions
end

#parentObject (readonly)

Returns the value of attribute parent.



94
95
96
# File 'lib/code/object/function.rb', line 94

def parent
  @parent
end

Class Method Details

.function_documentation(scope) ⇒ Object



87
88
89
90
91
# File 'lib/code/object/function.rb', line 87

def self.function_documentation(scope)
  return INSTANCE_FUNCTIONS if scope == :instance

  {}
end

Instance Method Details

#call(**args) ⇒ Object



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/code/object/function.rb', line 126

def call(**args)
  code_operator = args.fetch(:operator, nil).to_code
  code_arguments = args.fetch(:arguments, List.new).to_code
  code_value = code_arguments.code_first
  globals = multi_fetch(args, *GLOBALS)
  operator_name = code_operator.to_s
  operator_name = "" if operator_name == "new" &&
    code_has_key?(code_operator).falsy?

  case operator_name
  when "", "call"
    sig(args) { signature_for_call }
    code_call(
      *code_arguments.raw,
      explicit_arguments: args.fetch(:explicit_arguments, true),
      bound_self: args.fetch(:bound_self, nil),
      constructing_literal_classes:
        args.fetch(:constructing_literal_classes, nil),
      **globals
    )
  when "extend"
    sig(args) { Function }
    code_extend(code_arguments.code_first)
  when "documentation"
    if code_arguments.any?
      sig(args) { Dictionary }
      self.documentation = code_value.code_to_dictionary
    else
      sig(args)
      documentation
    end
  when "documentation="
    sig(args) { Dictionary }
    self.documentation = code_value.code_to_dictionary
  when "parameters"
    sig(args)
    code_parameters
  when /=$/
    sig(args) { Object }
    code_set(code_operator.to_s.chop, code_value)
  when ->(operator) { code_has_key?(operator).truthy? }
    result = code_fetch(code_operator)

    if result.is_a?(Function)
      result.call(**args, operator: nil, bound_self: self)
    else
      sig(args)
      result
    end
  else
    super
  end
end

#code_call(*arguments, explicit_arguments: true, bound_self: nil, constructing_literal_classes: nil, **globals) ⇒ Object



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/code/object/function.rb', line 180

def code_call(
  *arguments,
  explicit_arguments: true,
  bound_self: nil,
  constructing_literal_classes: nil,
  **globals
)
  code_arguments = arguments.to_code
  code_context = Context.new({}, definition_context || globals[:context])
  evaluation_object = definition_object || globals.fetch(:previous_object)
  code_self = bound_self.to_code
  if (code_self.nil? || code_self.nothing?) && parent.is_a?(Class)
    code_self = parent.code_call(*arguments, **globals)
  end
  code_self = Dictionary.new if code_self.nil? || code_self.nothing?
  code_parent = captured_self.to_code

  code_context.code_set("self", code_self)
  bind_parent(code_context, code_self, code_parent)

  if parent.is_a?(Function) || parent.is_a?(Class)
    code_context.code_set(
      "super",
      Super.new(
        parent,
        code_arguments,
        code_self,
        definition_context || globals[:context],
        explicit_arguments: explicit_arguments
      )
    )
  end

  captures_function_arguments =
    code_parameters.raw.any? do |parameter|
      parameter.block? || parameter.blocks?
    end
  reserved_function_arguments =
    captures_function_arguments ? code_arguments.raw.grep(Function) : []
  code_block_argument =
    if code_parameters.raw.any?(&:block?)
      code_arguments.raw.detect { |argument| argument.is_a?(Function) }
    end

  code_parameters.raw.each.with_index do |code_parameter, index|
    code_argument =
      if code_parameter.spread?
        code_arguments
      elsif code_parameter.regular_splat?
        Object::List.new(
          code_arguments.raw.reject do |argument|
            argument.is_a?(Dictionary) ||
              reserved_function_arguments.include?(argument)
          end
        )
      elsif code_parameter.keyword_splat?
        code_arguments
          .raw
          .grep(Dictionary)
          .inject(Dictionary.new) do |memo, argument|
            memo.code_merge!(argument)
          end
      elsif code_parameter.block?
        code_block_argument.to_code
      elsif code_parameter.blocks?
        Object::List.new(
          code_arguments
            .raw
            .grep(Function)
            .reject { |argument| argument == code_block_argument }
        )
      elsif code_parameter.keyword?
        code_arguments
          .raw
          .grep(Dictionary)
          .detect do |code_dictionary|
            code_dictionary.code_has_key?(
              code_parameter.code_name
            ).truthy?
          end
          &.code_get(code_parameter.code_name)
          .to_code
      else
        code_arguments.raw[index].to_code
      end

    if code_argument.nothing?
      code_default = code_parameter.code_default
      code_argument =
        if code_default.is_a?(Code)
          code_default.code_evaluate(
            **globals,
            context: code_context,
            object: evaluation_object,
            previous_object: evaluation_object
          )
        else
          code_default
        end
    end

    code_name = code_parameter.code_name
    unless code_name.blank?
      code_context.code_set(code_name, code_argument)
    end
  end

  code_body
    .code_evaluate(
      **globals,
      constructing_literal_classes: constructing_literal_classes,
      context: code_context,
      object: evaluation_object,
      previous_object: evaluation_object
    )
    .tap { persist_instance_functions(code_self) }
rescue Error::Return => e
  persist_instance_functions(code_self)
  e.code_value
end

#code_class_functionsObject



428
429
430
# File 'lib/code/object/function.rb', line 428

def code_class_functions
  function_dictionary_for(functions)
end

#code_deep_duplicateObject



370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
# File 'lib/code/object/function.rb', line 370

def code_deep_duplicate
  duplicate = Function.new

  duplicate.code_replace(
    code_parameters: code_parameters.code_deep_duplicate,
    code_body: code_body.code_deep_duplicate,
    definition_context: definition_context&.code_deep_duplicate,
    definition_object: definition_object,
    parent:
      parent.is_a?(Function) ? parent.code_deep_duplicate : parent,
    functions: functions.code_deep_duplicate,
    instance_functions: instance_functions.code_deep_duplicate,
    documentation: documentation.code_deep_duplicate
  )
  duplicate
end

#code_extend(function) ⇒ Object



353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
# File 'lib/code/object/function.rb', line 353

def code_extend(function)
  code_function = function.to_code

  Function
    .new(
      code_function.code_parameters,
      code_function.code_body.raw,
      code_function.definition_context,
      code_function.definition_object,
      parent: self,
      functions: functions.code_deep_duplicate
    )
    .tap do |extended_function|
      extended_function.instance_functions.code_merge!(instance_functions)
    end
end

#code_fetch(key) ⇒ Object



432
433
434
# File 'lib/code/object/function.rb', line 432

def code_fetch(key)
  functions.code_fetch(key)
end

#code_functionsObject



409
410
411
# File 'lib/code/object/function.rb', line 409

def code_functions
  code_class_functions
end

#code_get(key) ⇒ Object



436
437
438
# File 'lib/code/object/function.rb', line 436

def code_get(key)
  functions.code_get(key)
end

#code_has_key?(key) ⇒ Boolean

Returns:



440
441
442
# File 'lib/code/object/function.rb', line 440

def code_has_key?(key)
  functions.code_has_key?(key)
end

#code_instance_functionsObject



413
414
415
416
417
418
419
420
421
422
423
424
425
426
# File 'lib/code/object/function.rb', line 413

def code_instance_functions
  parent_functions =
    if parent.is_a?(Function)
      parent.code_instance_functions
    else
      Dictionary.new
    end

  Object.sorted_dictionary(
    parent_functions.code_merge(
      function_dictionary_for(instance_functions)
    ).raw
  )
end

#code_replace(code_parameters:, code_body:, definition_context:, parent:, functions:, instance_functions:, documentation:, definition_object: nil) ⇒ Object



387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
# File 'lib/code/object/function.rb', line 387

def code_replace(
  code_parameters:,
  code_body:,
  definition_context:,
  parent:,
  functions:,
  instance_functions:,
  documentation:,
  definition_object: nil
)
  @code_parameters = code_parameters
  @code_body = code_body
  @definition_context = definition_context
  @definition_object = definition_object
  @parent = parent
  self.functions = functions
  @instance_functions = instance_functions
  self.documentation = documentation
  self.raw = List.new([code_parameters, code_body])
  self
end

#code_set(key, value) ⇒ Object



444
445
446
# File 'lib/code/object/function.rb', line 444

def code_set(key, value)
  functions.code_set(key, value)
end

#code_to_stringObject



335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'lib/code/object/function.rb', line 335

def code_to_string
  String.new(
    Format.format(
      [
        {
          function: {
            parameters:
              code_parameters.raw.map do |parameter|
                parameter_to_raw(parameter)
              end,
            body: code_body.raw.to_raw
          }
        }
      ]
    )
  )
end

#signature_for_callObject



301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# File 'lib/code/object/function.rb', line 301

def signature_for_call
  code_parameters
    .raw
    .inject([]) do |signature, code_parameter|
      if code_parameter.spread? || code_parameter.regular_splat?
        signature + [Object.repeat]
      elsif code_parameter.blocks?
        signature + [Function.repeat]
      elsif code_parameter.block?
        signature + [Function.maybe]
      elsif code_parameter.keyword_splat?
        signature + [Dictionary.maybe]
      elsif code_parameter.keyword? && code_parameter.required?
        if signature.last.is_a?(::Hash)
          signature.last[code_parameter.code_name] = Object
          signature
        else
          signature + [{ code_parameter.code_name => Object }]
        end
      elsif code_parameter.keyword?
        if signature.last.is_a?(::Hash)
          signature.last[code_parameter.code_name] = Object.maybe
          signature
        else
          signature + [{ code_parameter.code_name => Object.maybe }]
        end
      elsif code_parameter.required?
        signature + [Object]
      else
        signature + [Object.maybe]
      end
    end + [Object.repeat]
end