1 require 'escape_helper'
4 # A Monoglot is a compile-time code generator.
5 # It generates C source code which defines the states and transitions
6 # required for a single language parser.
8 # To create a parser which spans multiple languages, use a Polyglot.
12 # The name must be unique
15 # A collection of State objects representing possible states
18 # The Transition objects defining transitions between states
19 attr_reader :transitions
21 def initialize(name, states = [], transitions = [])
24 @transitions = transitions
27 # Emit the generated C code for the state machine definition.
29 Monoglot::print_banner(io, name)
32 print_polyglot_def(io)
35 def self.print_banner(io, name)
37 io.puts "/*****************************************************************************"
38 left = (80 - name.size)/2
41 io.puts "*****************************************************************************/"
45 "#{ @name.upcase }_POLYGLOT"
51 io.puts "/* States */"
56 # now define the collection
57 io.write "State *#{ name.upcase }_STATES[] = { "
59 io.write "&#{ s.definition }, "
64 def print_transitions(io)
65 io.puts "/* Transitions */"
66 # print each transition
67 @transitions.each do |t|
71 #aggregate the transitions
72 io.write "Transition *#{ name.upcase }_TRANSITIONS[] = {"
73 @transitions.each do |t|
74 io.write " &#{ t.definition },"
79 def print_polyglot_def(io)
81 Polyglot #{ definition } = {
82 "#{ @name.downcase }",
83 #{ @name.upcase }_STATES,
84 #{ @name.upcase }_TRANSITIONS,