2 // Copyright (c) 2014 Samsung Electronics Co., Ltd.
4 // Licensed under the Flora License, Version 1.0 (the License);
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
8 // http://floralicense.org/license/
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an AS IS BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
18 #include <dali-toolkit/internal/builder/json-parser-state.h>
35 // true if character represent a digit
36 inline bool IsDigit(char c)
38 return (c >= '0' && c <= '9');
41 // convert string to integer
42 bool StringToInteger(const char *first, const char *last, int& out)
52 else if (*first == '+')
58 // json error for int starting with zero
59 if( 0 == (*first - '0') && (first+1 != last))
65 for (; first != last && IsDigit(*first); ++first)
67 result = 10 * result + (*first - '0');
81 // convert hexadecimal string to unsigned integer
82 bool HexStringToUnsignedInteger(const char *first, const char *last, unsigned int& out)
84 unsigned int result = 0;
85 for (; first != last; ++first)
92 else if (*first >= 'a' && *first <= 'f')
94 digit = *first - 'a' + 10;
96 else if (*first >= 'A' && *first <= 'F')
98 digit = *first - 'A' + 10;
104 result = 16 * result + digit;
118 // convert string to floating point
119 bool StringToFloat(const char* first, const char* last, float& out)
130 else if (*first == '+')
138 for (; first != last && IsDigit(*first); ++first)
140 result = 10 * result + (*first - '0');
144 if (first != last && *first == '.')
148 float inv_base = 0.1f;
149 for (; first != last && IsDigit(*first); ++first)
151 result += (*first - '0') * inv_base;
156 // result w\o exponent
160 bool exponent_negative = false;
162 if (first != last && (*first == 'e' || *first == 'E'))
168 exponent_negative = true;
171 else if (*first == '+')
176 if(first == last || !IsDigit(*first))
181 for (; first != last && IsDigit(*first); ++first)
183 exponent = 10 * exponent + (*first - '0');
189 float power_of_ten = 10;
190 for (; exponent > 1; exponent--)
195 if (exponent_negative)
197 result /= power_of_ten;
201 result *= power_of_ten;
218 bool IsNumber(char c)
248 JsonParserState::JsonParserState(TreeNode* _root)
249 : mRoot(_root), mCurrent(_root),
250 mErrorDescription(NULL), mErrorNewLine(0), mErrorColumn(0), mErrorPosition(0),
251 mNumberOfParsedChars(0), mNumberOfCreatedNodes(0), mFirstParse(false),
260 TreeNode* JsonParserState::CreateNewNode(const char* name, TreeNode::NodeType type)
262 TreeNode* node = NULL;
264 node = TreeNodeManipulator::NewTreeNode();
265 TreeNodeManipulator modifyNew(node);
266 modifyNew.SetType(type);
267 modifyNew.SetName(name);
271 mCurrent = TreeNodeManipulator(mRoot);
275 mCurrent.AddChild(node);
276 mCurrent = modifyNew;
279 ++mNumberOfCreatedNodes;
285 TreeNode* JsonParserState::NewNode(const char* name, TreeNode::NodeType type)
287 TreeNode* node = NULL;
291 node = CreateNewNode(name, type);
299 const TreeNode* found = mCurrent.GetChild(name);
302 node = const_cast<TreeNode*>(found);
308 if( mCurrent.GetParent() == NULL )
316 // walk tree and deallocate children as were replacing this node
317 TreeNodeManipulator modify(node);
319 modify.SetName(name);
320 // Set the type of the existing node, this may remove children where necessary
321 // (changing from container type to value type)
322 modify.SetType(type);
328 // if not found then create new
329 node = CreateNewNode(name, type);
336 TreeNode* JsonParserState::GetRoot()
341 bool JsonParserState::Error(const char* description)
343 mErrorDescription = description;
347 bool JsonParserState::ParseWhiteSpace()
349 bool c_comment = false;
350 bool cpp_comment = false;
378 continue; // rather than carry on as comments may be back to back
381 else if( !c_comment && (c == '/' && nextChar == '/') )
388 if( c == '*' && nextChar == '/' )
395 else if( !cpp_comment && (c == '/' && nextChar == '*') )
400 if( ! (c_comment || cpp_comment) )
402 if( ! (c == '\x20' || c == '\x9' || c == '\xD' || c == '\xA' ) )
408 if( AdvanceEnded(1) )
418 bool JsonParserState::ParseSymbol(const std::string& symbol)
420 if( AtLeast( symbol.size() ) )
422 for(int i = 0; i < static_cast<int>( symbol.size() ); ++i)
424 if(*mIter != symbol[i])
438 bool JsonParserState::ParseTrue()
440 if( ParseSymbol("true") )
442 mCurrent.SetInteger(1);
443 mCurrent.SetType(TreeNode::BOOLEAN);
448 return Error("Unexpected character; expected symbol ie 'true'");
452 bool JsonParserState::ParseFalse()
454 if( ParseSymbol("false") )
456 mCurrent.SetInteger(0);
457 mCurrent.SetType(TreeNode::BOOLEAN);
462 return Error("Unexpected character; expected symbol ie 'false'");
466 bool JsonParserState::ParseNULL()
468 if( ParseSymbol("null") )
470 mCurrent.SetType(TreeNode::IS_NULL);
475 return Error("Unexpected character; expected symbol ie 'null'");
479 bool JsonParserState::ParseNumber()
481 mCurrent.SetType( TreeNode::INTEGER );
483 VectorCharIter first = mIter;
486 if( !(c == '-' || IsNumber(c) ) )
488 return Error("Number must start with '-' or 0-9");
491 while ( IsNumber(c) || c == '.' || c == 'e' || c == 'E' || c == '+' || c == '-' )
493 if (c == '.' || c == 'e' || c == 'E')
495 mCurrent.SetType( TreeNode::FLOAT );
501 if( mCurrent.GetType() == TreeNode::INTEGER )
504 if( StringToInteger(&(*first), &(*mIter), i ) )
506 mCurrent.SetInteger(i);
510 return Error("Bad integer number");
514 if(mCurrent.GetType() == TreeNode::FLOAT)
517 if( StringToFloat(&(*first), &(*mIter), f) )
519 mCurrent.SetFloat(f);
523 return Error("Bad float number");
527 return (mCurrent.GetType() == TreeNode::INTEGER) || (mCurrent.GetType() == TreeNode::FLOAT);
530 char* JsonParserState::EncodeString()
532 int substitution = 0;
533 VectorCharIter first = mIter;
534 VectorCharIter last = mIter;
538 if (static_cast<unsigned char>(*mIter) < '\x20')
540 static_cast<void>( Error("Control characters not allowed in strings") );
543 else if (*mIter == '\\' && AtLeast(2))
589 unsigned int codepoint;
592 static_cast<void>( Error("Bad unicode codepoint; not enough characters") );
595 if ( !HexStringToUnsignedInteger(&(*(mIter + 2)), &(*(mIter + 6)), codepoint) )
597 static_cast<void>( Error("Bad unicode codepoint") );
601 if (codepoint <= 0x7F)
603 *last = (char)codepoint;
605 else if (codepoint <= 0x7FF)
607 *last++ = (char)(0xC0 | (codepoint >> 6));
608 *last = (char)(0x80 | (codepoint & 0x3F));
610 else if (codepoint <= 0xFFFF)
612 *last++ = (char)(0xE0 | (codepoint >> 12));
613 *last++ = (char)(0x80 | ((codepoint >> 6) & 0x3F));
614 *last = (char)(0x80 | (codepoint & 0x3F));
619 } // case 'u' unicode
623 static_cast<void>( Error("Unrecognized escape sequence") );
631 else if (*mIter == '{')
633 if((0 == substitution) && (*last != '\\'))
640 else if (*mIter == '}')
649 else if (*mIter == '"')
663 mNumberOfParsedChars += last - first;
664 mNumberOfParsedChars += 1 ; // null terminator
671 bool JsonParserState::ParseJson(VectorChar& source)
675 if( 0 == source.size() )
677 return Error("Empty source buffer to parse");
680 mIter = source.begin();
684 char currentChar = 0;
685 char lastCharacter = 0;
687 if( !ParseWhiteSpace() )
694 lastCharacter = currentChar;
695 currentChar = Char();
701 if( '{' == currentChar )
703 NewNode(name, TreeNode::OBJECT);
704 mState = STATE_OBJECT;
706 else if( '[' == currentChar )
708 NewNode(name, TreeNode::ARRAY);
709 mState = STATE_VALUE;
713 return Error("Json must start with object {} or array []");
716 AdvanceSkipWhiteSpace(1);
721 if( '}' == currentChar )
727 mState = STATE_VALUE;
729 else if ( '"' == currentChar )
735 return Error("Unexpected character");
738 AdvanceSkipWhiteSpace(1);
743 name = EncodeString();
748 if( !ParseWhiteSpace() )
754 return Error("Expected ':'");
756 if( !ParseWhiteSpace() )
760 mState = STATE_VALUE;
762 AdvanceSkipWhiteSpace(1);
767 if( '"' == currentChar )
770 NewNode(name, TreeNode::STRING);
771 if( char* value = EncodeString() )
773 mCurrent.SetString(value);
783 AdvanceSkipWhiteSpace(0);
785 else if( IsNumber(currentChar) || currentChar == '-' )
787 NewNode(name, TreeNode::IS_NULL);
796 AdvanceSkipWhiteSpace(0);
798 else if( '{' == currentChar )
800 NewNode(name, TreeNode::OBJECT);
801 mState = STATE_OBJECT;
802 AdvanceSkipWhiteSpace(1);
804 else if( '}' == currentChar )
806 if(',' == lastCharacter)
808 return Error("Expected a value");
811 if(mCurrent.GetType() != TreeNode::OBJECT)
813 return Error("Mismatched array definition");
816 if(mCurrent.GetParent() == NULL)
827 AdvanceSkipWhiteSpace(1);
829 else if( '[' == currentChar )
831 NewNode(name, TreeNode::ARRAY);
832 mState = STATE_VALUE;
833 AdvanceSkipWhiteSpace(1);
835 else if( ']' == currentChar )
837 if(',' == lastCharacter)
839 return Error("Expected a value");
842 if(mCurrent.GetType() != TreeNode::ARRAY)
844 return Error("Mismatched braces in object definition");
847 if(mCurrent.GetParent() == NULL)
858 AdvanceSkipWhiteSpace(1);
860 else if( 't' == currentChar )
862 NewNode(name, TreeNode::BOOLEAN);
871 AdvanceSkipWhiteSpace(0);
873 else if( 'n' == currentChar )
875 NewNode(name, TreeNode::IS_NULL);
884 AdvanceSkipWhiteSpace(0);
886 else if( 'f' == currentChar)
888 NewNode(name, TreeNode::BOOLEAN);
897 AdvanceSkipWhiteSpace(0);
899 else if( ',' == currentChar )
901 if( 0 == mCurrent.Size() )
903 return Error("Missing Value");
906 if(mCurrent.GetType() == TreeNode::OBJECT)
908 mState = STATE_OBJECT; // to get '"' in '"key":val'
910 else if(mCurrent.GetType() == TreeNode::ARRAY)
912 mState = STATE_VALUE; // array so just get next value
916 return Error("Unexpected character");
918 AdvanceSkipWhiteSpace(1);
922 return Error("Unexpected character");
928 } // case STATE_VALUE
931 return Error("Unexpected character. Json must have one object or array at its root");
939 if( mState != STATE_END )
941 return Error("Unexpected termination character");
944 mIter = source.end();
951 void JsonParserState::Reset()
953 mCurrent = TreeNodeManipulator(mRoot);
955 mErrorDescription = NULL;
962 } // namespace Internal
964 } // namespace Toolkit