Class: Yadriggy::Py::CodeGen

Inherits:
Checker
  • Object
show all
Defined in:
lib/yadriggy/py/codegen.rb

Constant Summary collapse

FreeVarInitName =

The name of the function for initializing free variables.

'yadpy_initialize'

Constants included from Yadriggy

DynType, Undef, VERSION, Void

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Checker

#ast, #ast_env, #check, #check_all, #check_later, #error!, #error_found!, #error_messages, #errors?, #last_error, #make_base_env, #proceed, rule

Methods included from Yadriggy

debug, debug=, define_syntax, reify, reset_pry

Constructor Details

#initialize(printer, checker) ⇒ CodeGen

Returns a new instance of CodeGen.

Parameters:



13
14
15
16
17
# File 'lib/yadriggy/py/codegen.rb', line 13

def initialize(printer, checker)
  super()
  @printer = printer
  @typechecker = checker
end

Instance Attribute Details

#printerPrinter (readonly)

Returns the printer.

Returns:



9
10
11
# File 'lib/yadriggy/py/codegen.rb', line 9

def printer
  @printer
end

Instance Method Details

#newlineObject

Starts a new line.



39
40
41
# File 'lib/yadriggy/py/codegen.rb', line 39

def newline
  @printer.nl
end

Prints a given AST by #printer.

Parameters:

Returns:



27
28
29
30
31
32
33
34
35
36
# File 'lib/yadriggy/py/codegen.rb', line 27

def print(an_ast)
  check_all(an_ast)
  if errors?
    error_messages.each do |m|
      STDERR.puts(m)
    end
    raise RuntimeError.new('Python code generation failure')
  end
  self
end

Prints a function for initializing free variables in Python.

Returns:

  • (Array<Object>)

    the arguments to the function.



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/yadriggy/py/codegen.rb', line 48

def print_free_vars_initializer
  @printer << 'def ' << FreeVarInitName << '(_yadpy_values):' << :nl
  @printer << '  global '
  @typechecker.references.each_with_index do |pair, i|
    @printer << ', ' if i > 0
    @printer << pair[1]
  end
  @printer << :nl
  args = []
  i = 0
  @typechecker.references.each do |pair|
    @printer << '  ' << pair[1] << ' = ' << '_yadpy_values[' << i.to_s << ']' << :nl
    args << pair[0]
    i += 1
  end
  @printer << :nl
  return args
end


324
325
326
327
328
329
330
# File 'lib/yadriggy/py/codegen.rb', line 324

def print_lambda(func)
  @printer << '(lambda '
  print_parameters(func.params)
  @printer << ': '
  print(func.body)    # has to be a simple expression?
  @printer << ')'
end

#python_binary_op(op) ⇒ Object



310
311
312
313
314
315
316
317
318
# File 'lib/yadriggy/py/codegen.rb', line 310

def python_binary_op(op)
  if op == :'&&'
    'and'
  elsif op == :'||'
    'or'
  else
    op
  end
end