1- ######################################
2- # cs_grammar.rb a context sensitive
3- # 1-L lsystem grammar for
4- # ruby/ruby-processing
5- # by Martin Prout (January 2013)
6- ######################################
7-
8-
9-
101##################################
112# The grammar class stores rules
123# in two Hashes, one for cs rules,
134# one for context free rules. Rules
145# are filtered on input, and context
156# is checked using get_rule in production
167##################################
17-
188class Grammar
19-
209 attr_reader :axiom , :context , :no_context , :idx , :ignore
10+
2111 def initialize ( axiom , rules , ignore = '' )
2212 @axiom = axiom
2313 @no_context = { }
@@ -39,44 +29,43 @@ def add_rule(pre, rule)
3929 elsif pre . length == 1
4030 @no_context [ pre ] = rule # key length == 1
4131 else
42- print ' unrecognized grammar '#{pre}''
32+ puts " unrecognized grammar '#{ pre } '"
4333 end
4434 end
4535
4636 def generate ( repeat = 0 ) # repeat iteration grammar rules
4737 prod = axiom
4838 repeat . times { prod = new_production ( prod ) }
49- return prod
39+ prod
5040 end
5141
52-
53- def new_production prod # single iteration grammar rules
42+ def new_production ( prod ) # single iteration grammar rules
5443 @idx = -1
5544 prod . gsub! ( /./ ) do |ch |
5645 get_rule ( prod , ch )
5746 end
5847 end
5948
60- def get_rule prod , ch
49+ def get_rule ( prod , ch )
6150 rule = ch # default is return original character as rule (no change)
6251 @idx += 1 # increment the index of axiom/production as a side effect
6352 if context . key? ( ch )
6453 if context [ ch ] [ 1 ] == '<'
6554 cs_char = context [ ch ] [ 0 ]
66- rule = no_context [ context [ ch ] ] if cs_char == get_context ( prod , idx , -1 ) # use context sensitive rule
55+ rule = no_context [ context [ ch ] ] if cs_char == get_context ( prod , idx , -1 )
6756 elsif context [ ch ] [ 1 ] == '>'
6857 cs_char = context [ ch ] [ 2 ]
69- rule = no_context [ context [ ch ] ] if cs_char == get_context ( prod , idx , 1 ) # use context sensitive rule
58+ rule = no_context [ context [ ch ] ] if cs_char == get_context ( prod , idx , 1 )
7059 end
7160 else
72- rule = no_context [ ch ] if no_context . key? ( ch ) # context free rule if it exists
61+ rule = no_context [ ch ] if no_context . key? ( ch )
7362 end
74- return rule
63+ rule
7564 end
7665
7766 def get_context ( prod , idx , inc )
7867 index = idx + inc
7968 index += inc while ignore . include? ( prod [ index ] )
80- return prod [ index ]
69+ prod [ index ]
8170 end
82- end
71+ end
0 commit comments