repl.rb 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. require 'readline'
  2. module Sass
  3. # Runs a SassScript read-eval-print loop.
  4. # It presents a prompt on the terminal,
  5. # reads in SassScript expressions,
  6. # evaluates them,
  7. # and prints the result.
  8. class Repl
  9. # @param options [{Symbol => Object}] An options hash.
  10. def initialize(options = {})
  11. @options = options
  12. end
  13. # Starts the read-eval-print loop.
  14. def run
  15. environment = Environment.new
  16. @line = 0
  17. loop do
  18. @line += 1
  19. unless text = Readline.readline('>> ')
  20. puts
  21. return
  22. end
  23. Readline::HISTORY << text
  24. parse_input(environment, text)
  25. end
  26. end
  27. private
  28. def parse_input(environment, text)
  29. case text
  30. when Script::MATCH
  31. name = $1
  32. guarded = !!$3
  33. val = Script::Parser.parse($2, @line, text.size - ($3 || '').size - $2.size)
  34. unless guarded && environment.var(name)
  35. environment.set_var(name, val.perform(environment))
  36. end
  37. p environment.var(name)
  38. else
  39. p Script::Parser.parse(text, @line, 0).perform(environment)
  40. end
  41. rescue Sass::SyntaxError => e
  42. puts "SyntaxError: #{e.message}"
  43. if @options[:trace]
  44. e.backtrace.each do |e|
  45. puts "\tfrom #{e}"
  46. end
  47. end
  48. end
  49. end
  50. end