From 5c56acb2e8482631a692a798c42f889cb5b203e6 Mon Sep 17 00:00:00 2001 From: Takashi Kokubun Date: Tue, 3 Nov 2015 14:55:39 +0900 Subject: [PATCH] Parse nested array comma --- lib/hamlit/hash_parser.rb | 19 ++++++++++++++----- test/hamlit/hash_parser_test.rb | 18 ++++++++++++++++-- 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/lib/hamlit/hash_parser.rb b/lib/hamlit/hash_parser.rb index 26e8e125..bf65268e 100644 --- a/lib/hamlit/hash_parser.rb +++ b/lib/hamlit/hash_parser.rb @@ -47,7 +47,7 @@ module Hamlit end key else - raise InternalError.new("Unexpected type: #{type}") + raise ParseSkip end end @@ -64,15 +64,24 @@ module Hamlit def each_attr(tokens) attr_tokens = [] + array_open = 0 + tokens.each do |token| (row, col), type, str = token case type when :on_comma - yield(attr_tokens) - attr_tokens = [] - else - attr_tokens << token + if array_open == 0 + yield(attr_tokens) + attr_tokens = [] + next + end + when :on_lbracket + array_open += 1 + when :on_rbracket + array_open -= 1 end + + attr_tokens << token end yield(attr_tokens) unless attr_tokens.empty? end diff --git a/test/hamlit/hash_parser_test.rb b/test/hamlit/hash_parser_test.rb index d1221378..6a5d4b46 100644 --- a/test/hamlit/hash_parser_test.rb +++ b/test/hamlit/hash_parser_test.rb @@ -4,10 +4,19 @@ describe Hamlit::HashParser do assert_equal result, Hamlit::HashParser.parse(text) end - it { assert_parse(' hash ', nil) } - it { assert_parse('hash, foo: bar', nil) } it { assert_parse('', {}) } + describe 'invalid hash' do + it { assert_parse(' hash ', nil) } + it { assert_parse('hash, foo: bar', nil) } + end + + describe 'dynamic key' do + it { assert_parse('foo => bar', nil) } + it { assert_parse('[] => bar', nil) } + it { assert_parse('[1,2,3] => bar', nil) } + end + describe 'foo: bar' do it { assert_parse('_:1,', { '_' => '1' }) } it { assert_parse(' foo: bar ', { 'foo' => 'bar' }) } @@ -44,5 +53,10 @@ describe Hamlit::HashParser do it { assert_parse('"#{foo}": bar', nil) } end end + + describe 'array value' do + it { assert_parse('foo: [1,2,],', { 'foo' => '[1,2,]' }) } + it { assert_parse('foo: [1,2,[3,4],5],', { 'foo' => '[1,2,[3,4],5]' }) } + end end end