Class: BasePythonQueryHook

Inherits:
Mumukit::Templates::FileHook
  • Object
show all
Defined in:
lib/base/query_hook.rb

Direct Known Subclasses

Python2QueryHook, Python3QueryHook

Instance Method Summary collapse

Instance Method Details

#command_line(filename) ⇒ Object



5
6
7
# File 'lib/base/query_hook.rb', line 5

def command_line(filename)
  "python #{filename} 2>&1"
end


57
58
59
# File 'lib/base/query_hook.rb', line 57

def compile_cookie(cookie)
  compile_state(cookie).join("\n")
end

#compile_file_content(req) ⇒ Object



9
10
11
# File 'lib/base/query_hook.rb', line 9

def compile_file_content(req)
  "#{compile_file_header(req)}\n#{compile_query(req.query)}"
end

#compile_file_header(req) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/base/query_hook.rb', line 13

def compile_file_header(req)
  <<python
# -*- coding: UTF-8 -*-
import string, sys, os

#{req.extra}
#{req.content}
sys.stdout = open(os.devnull, 'w')
#{compile_cookie(req.cookie)}
sys.stdout = sys.__stdout__
python
end

#compile_query(query, output_prefix = "=> ") ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/base/query_hook.rb', line 26

def compile_query(query, output_prefix = "=> ")
  if query.match /print *(\(| ).*|.*[^=]=[^=].*|^raise\b/
    query
  else
    <<~python
      __mumuki_error__ = None
      try:
        __mumuki_args__ = {'mumuki_query_result': eval("""#{query.gsub('"', '\"')}""")}
        print(string.Template(\"#{output_prefix}\${mumuki_query_result}\").safe_substitute(**__mumuki_args__))
      except SyntaxError as e:
        __mumuki_error__ = SyntaxError(e.msg, ('<console>', e.lineno, e.offset, e.text))
      if __mumuki_error__:
        print(__mumuki_error__.text)
        print(" "*(__mumuki_error__.offset - 1) + "^")
        print('SyntheticMumukiSyntaxError: SyntaxError: ' + str(__mumuki_error__))
        exit(1)
    python
  end
end

#compile_state(cookie) ⇒ Object



46
47
48
49
50
51
52
53
54
55
# File 'lib/base/query_hook.rb', line 46

def compile_state(cookie)
  (cookie||[]).map do |statement|
  <<~python
  try:
    #{statement}
  except:
    pass
python
  end
end

#error_patternsObject



61
62
63
64
65
# File 'lib/base/query_hook.rb', line 61

def error_patterns
  [
    Mumukit::ErrorPattern::Errored.new(syntax_error_regexp)
  ]
end

#syntax_error_regexpObject



67
68
69
# File 'lib/base/query_hook.rb', line 67

def syntax_error_regexp
  /(SyntheticMumukiSyntaxError: )|(\A  File .*\n(?m)(?=.*(SyntaxError|IndentationError)))/
end