JSONParser.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "RuntimeLibraryPch.h"
  6. #include "JSON.h"
  7. #include "JSONParser.h"
  8. using namespace Js;
  9. namespace JSON
  10. {
  11. // -------- Parser implementation ------------//
  12. void JSONParser::Finalizer()
  13. {
  14. m_scanner.Finalizer();
  15. if(arenaAllocatorObject)
  16. {
  17. this->scriptContext->ReleaseTemporaryGuestAllocator(arenaAllocatorObject);
  18. }
  19. }
  20. Js::Var JSONParser::Parse(LPCWSTR str, int length)
  21. {
  22. if (length > MIN_CACHE_LENGTH)
  23. {
  24. if (!this->arenaAllocatorObject)
  25. {
  26. this->arenaAllocatorObject = scriptContext->GetTemporaryGuestAllocator(_u("JSONParse"));
  27. this->arenaAllocator = arenaAllocatorObject->GetAllocator();
  28. }
  29. }
  30. m_scanner.Init(str, length, &m_token, scriptContext, str, this->arenaAllocator);
  31. Scan();
  32. Js::Var ret = ParseObject();
  33. if (m_token.tk != tkEOF)
  34. {
  35. m_scanner.ThrowSyntaxError(JSERR_JsonSyntax);
  36. }
  37. return ret;
  38. }
  39. Js::Var JSONParser::Parse(Js::JavascriptString* input)
  40. {
  41. return Parse(input->GetSz(), input->GetLength());
  42. }
  43. Js::Var JSONParser::Walk(Js::JavascriptString* name, Js::PropertyId id, Js::Var holder, uint32 index)
  44. {
  45. AssertMsg(reviver, "JSON post parse walk with null reviver");
  46. Js::Var value;
  47. Js::Var values[3];
  48. Js::Arguments args(0, values);
  49. Js::RecyclableObject *undefined = scriptContext->GetLibrary()->GetUndefined();
  50. if (Js::DynamicObject::IsAnyArray(holder))
  51. {
  52. // when called from an array the key is NULL and the keyId is the index.
  53. value = Js::JavascriptArray::FromAnyArray(holder)->DirectGetItem(id);
  54. name = scriptContext->GetIntegerString(id);
  55. }
  56. else
  57. {
  58. AssertMsg(Js::JavascriptOperators::GetTypeId(holder) == Js::TypeIds_Object || Js::JavascriptOperators::GetTypeId(holder) == Js::TypeIds_Arguments,
  59. "The holder argument in a JSON::Walk function must be an object or an array");
  60. if (id == Constants::NoProperty)
  61. {
  62. if (!Js::RecyclableObject::FromVar(holder)->GetItem(holder, index, &value, scriptContext))
  63. {
  64. value = undefined;
  65. }
  66. }
  67. else
  68. {
  69. if (!Js::RecyclableObject::FromVar(holder)->GetProperty(holder, id, &value, NULL, scriptContext))
  70. {
  71. value = undefined;
  72. }
  73. }
  74. }
  75. // this is a post order walk. Visit the children before calling walk on this object
  76. if (Js::DynamicObject::IsAnyArray(value))
  77. {
  78. Js::JavascriptArray* arrayVal = JavascriptArray::EnsureNonNativeArray(Js::JavascriptArray::FromAnyArray(value));
  79. Assert(!Js::JavascriptNativeIntArray::Is(arrayVal) && !Js::JavascriptNativeFloatArray::Is(arrayVal));
  80. uint length = arrayVal->GetLength();
  81. if (!arrayVal->IsCrossSiteObject())
  82. {
  83. for(uint k = 0; k < length; k++)
  84. {
  85. Js::Var newElement = Walk(0, k, value);
  86. if(Js::JavascriptOperators::IsUndefinedObject(newElement, undefined))
  87. {
  88. arrayVal->DirectDeleteItemAt<Js::Var>(k);
  89. }
  90. else
  91. {
  92. arrayVal->DirectSetItemAt(k, newElement);
  93. }
  94. }
  95. }
  96. else
  97. {
  98. for(uint k = 0; k < length; k++)
  99. {
  100. Js::Var newElement = Walk(0, k, value);
  101. if(Js::JavascriptOperators::IsUndefinedObject(newElement, undefined))
  102. {
  103. arrayVal->DirectDeleteItemAt<Js::Var>(k);
  104. }
  105. else
  106. {
  107. arrayVal->SetItem(k, newElement, Js::PropertyOperation_None);
  108. }
  109. }
  110. }
  111. }
  112. else
  113. {
  114. Js::TypeId typeId = Js::JavascriptOperators::GetTypeId(value);
  115. if (typeId == Js::TypeIds_Object || typeId == Js::TypeIds_Arguments)
  116. {
  117. Js::JavascriptStaticEnumerator enumerator;
  118. // normally we should have a JSON object here and the enumerator should be always be successful. However, the objects can be
  119. // modified by user code. It is better to skip a damaged object. ES5 spec doesn't specify an error here.
  120. if(Js::RecyclableObject::FromVar(value)->GetEnumerator(&enumerator, EnumeratorFlags::SnapShotSemantics, scriptContext))
  121. {
  122. Js::Var propertyNameVar;
  123. while (true)
  124. {
  125. Js::PropertyId idMember = Js::Constants::NoProperty;
  126. propertyNameVar = enumerator.MoveAndGetNext(idMember);
  127. if (propertyNameVar == nullptr)
  128. {
  129. break;
  130. }
  131. //NOTE: If testing key value call enumerator->GetCurrentValue() to confirm value is correct;
  132. AssertMsg(Js::JavascriptString::Is(propertyNameVar) , "bad enumeration on a JSON Object");
  133. if (idMember != Js::Constants::NoProperty)
  134. {
  135. Js::Var newElement = Walk(Js::JavascriptString::FromVar(propertyNameVar), idMember, value);
  136. if (Js::JavascriptOperators::IsUndefinedObject(newElement, undefined))
  137. {
  138. Js::JavascriptOperators::DeleteProperty(Js::RecyclableObject::FromVar(value), idMember);
  139. }
  140. else
  141. {
  142. Js::JavascriptOperators::SetProperty(value, Js::RecyclableObject::FromVar(value), idMember, newElement, scriptContext);
  143. }
  144. }
  145. // For the numeric cases the enumerator is set to a NullEnumerator (see class in ForInObjectEnumerator.h)
  146. // Numerals do not have property Ids so we need to set and delete items
  147. else
  148. {
  149. uint32 propertyIndex = enumerator.GetCurrentItemIndex();
  150. AssertMsg(Js::JavascriptArray::InvalidIndex != propertyIndex, "Not a numeric type");
  151. Js::Var newElement = Walk(Js::JavascriptString::FromVar(propertyNameVar), idMember, value, propertyIndex);
  152. if (Js::JavascriptOperators::IsUndefinedObject(newElement, undefined))
  153. {
  154. Js::JavascriptOperators::DeleteItem(Js::RecyclableObject::FromVar(value), propertyIndex);
  155. }
  156. else
  157. {
  158. Js::JavascriptOperators::SetItem(value, Js::RecyclableObject::FromVar(value), propertyIndex, newElement, scriptContext);
  159. }
  160. }
  161. }
  162. }
  163. }
  164. }
  165. // apply reviver on this node now
  166. args.Info.Count = 3;
  167. args.Values[0] = holder;
  168. args.Values[1] = name;
  169. args.Values[2] = value;
  170. value = Js::JavascriptFunction::CallFunction<true>(reviver, reviver->GetEntryPoint(), args);
  171. return value;
  172. }
  173. Js::Var JSONParser::ParseObject()
  174. {
  175. PROBE_STACK(scriptContext, Js::Constants::MinStackDefault);
  176. Js::Var retVal;
  177. switch (m_token.tk)
  178. {
  179. case tkFltCon:
  180. retVal = Js::JavascriptNumber::ToVarIntCheck(m_token.GetDouble(), scriptContext);
  181. Scan();
  182. return retVal;
  183. case tkStrCon:
  184. {
  185. // will auto-null-terminate the string (as length=len+1)
  186. uint len = m_scanner.GetCurrentStringLen();
  187. retVal = Js::JavascriptString::NewCopyBuffer(m_scanner.GetCurrentString(), len, scriptContext);
  188. Scan();
  189. return retVal;
  190. }
  191. case tkTRUE:
  192. retVal = scriptContext->GetLibrary()->GetTrue();
  193. Scan();
  194. return retVal;
  195. case tkFALSE:
  196. retVal = scriptContext->GetLibrary()->GetFalse();
  197. Scan();
  198. return retVal;
  199. case tkNULL:
  200. retVal = scriptContext->GetLibrary()->GetNull();
  201. Scan();
  202. return retVal;
  203. case tkSub: // unary minus
  204. if (Scan() == tkFltCon)
  205. {
  206. retVal = Js::JavascriptNumber::ToVarIntCheck(-m_token.GetDouble(), scriptContext);
  207. Scan();
  208. return retVal;
  209. }
  210. else
  211. {
  212. m_scanner.ThrowSyntaxError(JSERR_JsonBadNumber);
  213. }
  214. case tkLBrack:
  215. {
  216. Js::JavascriptArray* arrayObj = scriptContext->GetLibrary()->CreateArray(0);
  217. //skip '['
  218. Scan();
  219. //iterate over the array members, get JSON objects and add them in the pArrayMemberList
  220. uint k = 0;
  221. while (true)
  222. {
  223. if(tkRBrack == m_token.tk)
  224. {
  225. break;
  226. }
  227. Js::Var value = ParseObject();
  228. arrayObj->SetItem(k++, value, Js::PropertyOperation_None);
  229. // if next token is not a comma consider the end of the array member list.
  230. if (tkComma != m_token.tk)
  231. break;
  232. Scan();
  233. if(tkRBrack == m_token.tk)
  234. {
  235. m_scanner.ThrowSyntaxError(JSERR_JsonIllegalChar);
  236. }
  237. }
  238. //check and consume the ending ']'
  239. CheckCurrentToken(tkRBrack, JSERR_JsonNoRbrack);
  240. return arrayObj;
  241. }
  242. case tkLCurly:
  243. {
  244. // Parse an object, "{"name1" : ObjMember1, "name2" : ObjMember2, ...} "
  245. if(IsCaching())
  246. {
  247. if(!typeCacheList)
  248. {
  249. typeCacheList = Anew(this->arenaAllocator, JsonTypeCacheList, this->arenaAllocator, 8);
  250. }
  251. }
  252. // first, create the object
  253. Js::DynamicObject* object = scriptContext->GetLibrary()->CreateObject();
  254. JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(object));
  255. #if ENABLE_DEBUG_CONFIG_OPTIONS
  256. if (Js::Configuration::Global.flags.IsEnabled(Js::autoProxyFlag))
  257. {
  258. object = DynamicObject::FromVar(JavascriptProxy::AutoProxyWrapper(object));
  259. }
  260. #endif
  261. //next token after '{'
  262. Scan();
  263. //if empty object "{}" return;
  264. if(tkRCurly == m_token.tk)
  265. {
  266. Scan();
  267. return object;
  268. }
  269. JsonTypeCache* previousCache = nullptr;
  270. JsonTypeCache* currentCache = nullptr;
  271. //parse the list of members
  272. while(true)
  273. {
  274. // parse a list member: "name" : ObjMember
  275. // and add it to the object.
  276. //pick "name"
  277. if(tkStrCon != m_token.tk)
  278. {
  279. m_scanner.ThrowSyntaxError(JSERR_JsonIllegalChar);
  280. }
  281. // currentStrLength = length w/o null-termination
  282. WCHAR* currentStr = m_scanner.GetCurrentString();
  283. uint currentStrLength = m_scanner.GetCurrentStringLen();
  284. DynamicType* typeWithoutProperty = object->GetDynamicType();
  285. if(IsCaching())
  286. {
  287. if(!previousCache)
  288. {
  289. // This is the first property in the list - see if we have an existing cache for it.
  290. currentCache = typeCacheList->LookupWithKey(Js::HashedCharacterBuffer<WCHAR>(currentStr, currentStrLength), nullptr);
  291. }
  292. if(currentCache && currentCache->typeWithoutProperty == typeWithoutProperty &&
  293. currentCache->propertyRecord->Equals(JsUtil::CharacterBuffer<WCHAR>(currentStr, currentStrLength)))
  294. {
  295. //check and consume ":"
  296. if(Scan() != tkColon )
  297. {
  298. m_scanner.ThrowSyntaxError(JSERR_JsonNoColon);
  299. }
  300. Scan();
  301. // Cache all values from currentCache as there is a chance that ParseObject might change the cache
  302. DynamicType* typeWithProperty = currentCache->typeWithProperty;
  303. PropertyId propertyId = currentCache->propertyRecord->GetPropertyId();
  304. PropertyIndex propertyIndex = currentCache->propertyIndex;
  305. previousCache = currentCache;
  306. currentCache = currentCache->next;
  307. // fast path for type transition and property set
  308. object->EnsureSlots(typeWithoutProperty->GetTypeHandler()->GetSlotCapacity(),
  309. typeWithProperty->GetTypeHandler()->GetSlotCapacity(), scriptContext, typeWithProperty->GetTypeHandler());
  310. object->ReplaceType(typeWithProperty);
  311. Js::Var value = ParseObject();
  312. object->SetSlot(SetSlotArguments(propertyId, propertyIndex, value));
  313. // if the next token is not a comma consider the list of members done.
  314. if (tkComma != m_token.tk)
  315. break;
  316. Scan();
  317. continue;
  318. }
  319. }
  320. // slow path
  321. Js::PropertyRecord const * propertyRecord;
  322. scriptContext->GetOrAddPropertyRecord(currentStr, currentStrLength, &propertyRecord);
  323. //check and consume ":"
  324. if(Scan() != tkColon )
  325. {
  326. m_scanner.ThrowSyntaxError(JSERR_JsonNoColon);
  327. }
  328. Scan();
  329. Js::Var value = ParseObject();
  330. PropertyValueInfo info;
  331. object->SetProperty(propertyRecord->GetPropertyId(), value, PropertyOperation_None, &info);
  332. DynamicType* typeWithProperty = object->GetDynamicType();
  333. if(IsCaching() && !propertyRecord->IsNumeric() && !info.IsNoCache() && typeWithProperty->GetIsShared() && typeWithProperty->GetTypeHandler()->IsPathTypeHandler())
  334. {
  335. PropertyIndex propertyIndex = info.GetPropertyIndex();
  336. if(!previousCache)
  337. {
  338. // This is the first property in the set add it to the dictionary.
  339. currentCache = JsonTypeCache::New(this->arenaAllocator, propertyRecord, typeWithoutProperty, typeWithProperty, propertyIndex);
  340. typeCacheList->AddNew(propertyRecord, currentCache);
  341. }
  342. else if(!currentCache)
  343. {
  344. currentCache = JsonTypeCache::New(this->arenaAllocator, propertyRecord, typeWithoutProperty, typeWithProperty, propertyIndex);
  345. previousCache->next = currentCache;
  346. }
  347. else
  348. {
  349. // cache miss!!
  350. currentCache->Update(propertyRecord, typeWithoutProperty, typeWithProperty, propertyIndex);
  351. }
  352. previousCache = currentCache;
  353. currentCache = currentCache->next;
  354. }
  355. // if the next token is not a comma consider the list of members done.
  356. if (tkComma != m_token.tk)
  357. break;
  358. Scan();
  359. }
  360. // check and consume the ending '}"
  361. CheckCurrentToken(tkRCurly, JSERR_JsonNoRcurly);
  362. return object;
  363. }
  364. default:
  365. m_scanner.ThrowSyntaxError(JSERR_JsonSyntax);
  366. }
  367. }
  368. } // namespace JSON