class Campa::Printer

Represents a Campa expression in a human readable form.

In general it tries to create a representation that is valid Campa code to make it easy(ier) to copy and paste stuff from the REPL to a file.

@example some results produced by {Printer}

printer = Printer.new

printer.call("lol") #=> "lol"
printer.call("lol") #=> 123
printer.call(List.new("bbq", 420, List.new("yes"))) #=> ("bbq" 420 ("yes"))

Constants

FORMATS

Public Instance Methods

call(expr) click to toggle source

@param expr [Object] Campa expression to be respresented in

human readable form

@return [String] human readable form (almost always valid code)

of an Expression
# File lib/campa/printer.rb, line 21
def call(expr)
  format = FORMATS.fetch(expr.class) do
    expr.is_a?(Context) ? :context : :default
  end
  send(format, expr)
end

Private Instance Methods

boolean(expr) click to toggle source
# File lib/campa/printer.rb, line 53
def boolean(expr)
  (expr == true).to_s
end
context(expr) click to toggle source
# File lib/campa/printer.rb, line 66
def context(expr)
  context_bindings(expr).join("\n")
end
context_bindings(expr, sep: "") click to toggle source
# File lib/campa/printer.rb, line 78
def context_bindings(expr, sep: "")
  own =
    expr
    .bindings
    .map { |tuple| "#{sep}#{call(tuple[0])}: #{call(tuple[1])}" }
  return own if expr.fallback.nil?

  own + context_bindings(expr.fallback, sep: "#{sep}  ")
end
default(expr) click to toggle source
# File lib/campa/printer.rb, line 74
def default(expr)
  expr
end
lambda(expr) click to toggle source
# File lib/campa/printer.rb, line 57
def lambda(expr)
  list(
    List
      .new(expr.body.map { |e| call(e) })
      .push(expr.params)
      .push(SYMBOL_LAMBDA)
  )
end
list(expr) click to toggle source
# File lib/campa/printer.rb, line 49
def list(expr)
  "(#{expr.map { |el| call(el) }.join(" ")})"
end
null(_expr) click to toggle source
# File lib/campa/printer.rb, line 70
def null(_expr)
  "NIL"
end
string(expr) click to toggle source
# File lib/campa/printer.rb, line 41
def string(expr)
  "\"#{expr}\""
end
symbol(expr) click to toggle source
# File lib/campa/printer.rb, line 45
def symbol(expr)
  expr.label
end