Class: PostScript::Runtime

Inherits:
Object
  • Object
show all
Includes:
Operators
Defined in:
lib/postscript/runtime.rb

Overview

The Runtime is responsible for evaluating procedures (as arrays output from Parser, or as strings to be parsed) and maintaining the stack.

It responds to all of the supported operators.

Examples:

Manually manipulating the runtime


ps = PostScript::Runtime.new
ps.stack  # => []
ps.push 2 # => [2]
ps.push 2 # => [2, 2]
ps.mul    # => [4]
ps.push 2 # => [4, 2]
ps.div    # => [2]
ps.stack  # => [2]

Evaluating PostScript


ps = PostScript::Runtime.new
ps.stack  # => []
ps.eval "{ 2 2 mul 2 div }"
ps.stack  # => [2]

Setting the state for a PostScript procedure


ps = PostScript::Runtime.new

# Set up the initial state
ps.push -4.0, 2.0

# Execute the "Rhomboid" spot function as defined in the PDF Spec.
ps.eval "{ abs exch abs 0.9 mul add 2 div }" # => [2.8]

Instance Method Summary collapse

Methods included from Operators::Conditional

#if, #ifelse

Methods included from Operators::Boolean

#and, #eq, #ge, #gt, #le, #lt, #ne, #not, #or, #xor

Methods included from Operators::Arithmetic

#abs, #add, #atan, #bitshift, #ceiling, #cos, #cvi, #cvr, #div, #exp, #floor, #ln, #log, #mod, #mul, #neg, #round, #sin, #sqrt, #sub, #truncate

Methods included from Operators::Stack

#copy, #dup, #exch, #index, #pop, #roll

Instance Method Details

#eval(function) ⇒ Array

Evaluates the provided PostScript function and returns the stack.

Examples:


runtime.eval "{ 40 60 add 2 div }" # => [50]


48
49
50
51
# File 'lib/postscript/runtime.rb', line 48

def eval(function)
  eval_procedure Parser.parse(function)
  stack
end

#eval_procedure(procedure) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Evaluates the result of a parsed PostScript procedure.



56
57
58
59
60
61
62
63
64
# File 'lib/postscript/runtime.rb', line 56

def eval_procedure(procedure)
  procedure.each do |operator|
    if operator.is_a? Symbol
      send operator
    else
      push operator
    end
  end
end

#push(*elements) ⇒ Object

Pushes the provided operator onto the stack. This is most useful for setting up the initial state before evaluating a PostScript function.

Examples:


runtime.push 2
runtime.eval "{ dup mult }" # => [4]


75
76
77
# File 'lib/postscript/runtime.rb', line 75

def push(*elements)
  stack.push *elements
end

#stackArray



80
81
82
# File 'lib/postscript/runtime.rb', line 80

def stack
  @stack ||= []
end