Skip to content

Commit

Permalink
Added a pre-class directive
Browse files Browse the repository at this point in the history
  • Loading branch information
drbrain committed Mar 8, 2012
1 parent c1f45a6 commit 52a8737
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 0 deletions.
1 change: 1 addition & 0 deletions History.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
disabled with the custom_initialize variable:

%% custom_initialize = true
* Added a pre-class directive for adding class comments

* Bug fixes
* Hoe plugin now overwrites generated files
Expand Down
2 changes: 2 additions & 0 deletions README.rdoc
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,8 @@ Kpeg allows the following directives:

header::
Placed before any generated code
pre-class::
Placed before the class definition to provide a class comment

== Generating and running your parser

Expand Down
10 changes: 10 additions & 0 deletions lib/kpeg/code_generator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,13 @@ def output
code << "\n"
end

pre_class = @grammar.directives['pre-class']

if @standalone
if pre_class
code << pre_class.action.strip
code << "\n"
end
code << "class #{@name}\n"

cp = standalone_region("compiled_parser.rb")
Expand All @@ -351,6 +357,10 @@ def output
code << cp << "\n"
else
code << "require 'kpeg/compiled_parser'\n\n"
if pre_class
code << pre_class.action.strip
code << "\n"
end
code << "class #{@name} < KPeg::CompiledParser\n"
end

Expand Down
43 changes: 43 additions & 0 deletions test/test_kpeg_code_generator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1455,6 +1455,49 @@ def _root
assert cg.parse("hello")
end

def test_directive_pre_class
gram = KPeg.grammar do |g|
g.root = g.dot
g.directives['pre-class'] = g.action("\n# some comment\n")
end

str = <<-STR
require 'kpeg/compiled_parser'
# some comment
class Test < KPeg::CompiledParser
# root = .
def _root
_tmp = get_byte
set_failed_rule :_root unless _tmp
return _tmp
end
Rules = {}
Rules[:_root] = rule_info("root", ".")
end
STR

cg = KPeg::CodeGenerator.new "Test", gram

assert_equal str, cg.output

assert cg.parse("hello")
end

def test_directive_pre_class_standalone
gram = KPeg.grammar do |g|
g.root = g.dot
g.directives['pre-class'] = g.action("\n# some comment\n")
end

cg = KPeg::CodeGenerator.new "Test", gram
cg.standalone = true

assert_match %r%^# some comment%, cg.output
end

def test_setup_actions
gram = KPeg.grammar do |g|
g.root = g.dot
Expand Down

0 comments on commit 52a8737

Please sign in to comment.