Web Inspector: Modify the type profiler runtime protocol to transfer some computation...
[WebKit-https.git] / Source / JavaScriptCore / runtime / TypeSet.cpp
1 /*
2  * Copyright (C) 2008, 2014 Apple Inc. All Rights Reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "TypeSet.h"
28
29 #include "InspectorJSProtocolTypes.h"
30 #include "JSCJSValue.h"
31 #include "JSCJSValueInlines.h"
32 #include <wtf/text/CString.h>
33 #include <wtf/text/WTFString.h>
34 #include <wtf/text/StringBuilder.h>
35 #include <wtf/Vector.h>
36
37 namespace JSC {
38
39 TypeSet::TypeSet()
40     : m_seenTypes(TypeNothing)
41     , m_isOverflown(false)
42 {
43 }
44
45 RuntimeType TypeSet::getRuntimeTypeForValue(JSValue v)
46 {
47     RuntimeType ret;
48     if (v.isFunction())
49         ret = TypeFunction;
50     else if (v.isUndefined())
51         ret = TypeUndefined;
52     else if (v.isNull())
53         ret = TypeNull;
54     else if (v.isBoolean())
55         ret = TypeBoolean;
56     else if (v.isMachineInt())
57         ret = TypeMachineInt;
58     else if (v.isNumber())
59         ret = TypeNumber;
60     else if (v.isString())
61         ret = TypeString;
62     else if (v.isObject())
63         ret = TypeObject;
64     else
65         ret = TypeNothing;
66
67     return ret;
68 }
69
70 void TypeSet::addTypeInformation(RuntimeType type, PassRefPtr<StructureShape> prpNewShape, StructureID id) 
71 {
72     RefPtr<StructureShape> newShape = prpNewShape;
73     m_seenTypes = m_seenTypes | type;
74
75     if (id && newShape && type != TypeString) {
76         ASSERT(m_structureIDCache.isValidValue(id));
77         auto addResult = m_structureIDCache.add(id);
78         if (addResult.isNewEntry) {
79             // Make one more pass making sure that: 
80             // - We don't have two instances of the same shape. (Same shapes may have different StructureIDs).
81             // - We don't have two shapes that share the same prototype chain. If these shapes share the same 
82             //   prototype chain, they will be merged into one shape.
83             bool found = false;
84             String hash = newShape->propertyHash();
85             for (size_t i = 0; i < m_structureHistory.size(); i++) {
86                 RefPtr<StructureShape>& seenShape = m_structureHistory.at(i);
87                 if (seenShape->propertyHash() == hash) {
88                     found = true;
89                     break;
90                 } 
91                 if (seenShape->hasSamePrototypeChain(newShape)) {
92                     seenShape = StructureShape::merge(seenShape, newShape);
93                     found = true;
94                     break;
95                 }
96             }
97
98             if (!found) {
99                 if (m_structureHistory.size() < 100)
100                     m_structureHistory.append(newShape);
101                 else if (!m_isOverflown)
102                     m_isOverflown = true;
103             }
104         }
105     }
106 }
107
108 void TypeSet::invalidateCache()
109 {
110     m_structureIDCache.clear();
111 }
112
113 String TypeSet::seenTypes() const
114 {
115     if (m_seenTypes == TypeNothing)
116         return ASCIILiteral("(Unreached Statement)");
117
118     StringBuilder seen;
119
120     if (m_seenTypes & TypeFunction)
121          seen.append("Function ");
122     if (m_seenTypes & TypeUndefined)
123          seen.append("Undefined ");
124     if (m_seenTypes & TypeNull)
125          seen.append("Null ");
126     if (m_seenTypes & TypeBoolean)
127          seen.append("Boolean ");
128     if (m_seenTypes & TypeMachineInt)
129          seen.append("MachineInt ");
130     if (m_seenTypes & TypeNumber)
131          seen.append("Number ");
132     if (m_seenTypes & TypeString)
133          seen.append("String ");
134     if (m_seenTypes & TypeObject)
135          seen.append("Object ");
136
137     for (size_t i = 0; i < m_structureHistory.size(); i++) {
138         RefPtr<StructureShape> shape = m_structureHistory.at(i);
139         seen.append(shape->m_constructorName);
140         seen.append(' ');
141     }
142
143     if (m_structureHistory.size()) 
144         seen.append("\nStructures:[ ");
145     for (size_t i = 0; i < m_structureHistory.size(); i++) {
146         seen.append(m_structureHistory.at(i)->stringRepresentation());
147         seen.append(' ');
148     }
149     if (m_structureHistory.size())
150         seen.append(']');
151
152     if (m_structureHistory.size()) {
153         seen.append("\nLeast Common Ancestor: ");
154         seen.append(leastCommonAncestor());
155     }
156
157     return seen.toString();
158 }
159
160 bool TypeSet::doesTypeConformTo(uint32_t test) const
161 {
162     // This function checks if our seen types conform  to the types described by the test bitstring. (i.e we haven't seen more types than test).
163     // We are <= to those types if ANDing with the bitstring doesn't zero out any of our bits.
164
165     // For example:
166
167     // 0b0110 (seen)
168     // 0b1111 (test)
169     // ------ (AND)
170     // 0b0110 == seen
171
172     // 0b0110 (seen)
173     // 0b0010 (test)
174     // ------ (AND)
175     // 0b0010 != seen
176
177     return (m_seenTypes & test) == m_seenTypes;
178 }
179
180 String TypeSet::displayName() const
181 {
182     if (m_seenTypes == TypeNothing)
183         return emptyString();
184
185     if (m_structureHistory.size() && doesTypeConformTo(TypeObject | TypeNull | TypeUndefined)) {
186         String ctorName = leastCommonAncestor(); 
187
188         if (doesTypeConformTo(TypeObject))
189             return ctorName;
190         if (doesTypeConformTo(TypeObject | TypeNull | TypeUndefined))
191             return ctorName + '?';
192     }
193
194     // The order of these checks are important. For example, if a value is only a function, it conforms to TypeFunction, but it also conforms to TypeFunction | TypeNull.
195     // Therefore, more specific types must be checked first.
196
197     if (doesTypeConformTo(TypeFunction))
198         return ASCIILiteral("Function");
199     if (doesTypeConformTo(TypeUndefined))
200         return ASCIILiteral("Undefined");
201     if (doesTypeConformTo(TypeNull))
202         return ASCIILiteral("Null");
203     if (doesTypeConformTo(TypeBoolean))
204         return ASCIILiteral("Boolean");
205     if (doesTypeConformTo(TypeMachineInt))
206         return ASCIILiteral("Integer");
207     if (doesTypeConformTo(TypeNumber | TypeMachineInt))
208         return ASCIILiteral("Number");
209     if (doesTypeConformTo(TypeString))
210         return ASCIILiteral("String");
211
212     if (doesTypeConformTo(TypeNull | TypeUndefined))
213         return ASCIILiteral("(?)");
214
215     if (doesTypeConformTo(TypeFunction | TypeNull | TypeUndefined))
216         return ASCIILiteral("Function?");
217     if (doesTypeConformTo(TypeBoolean | TypeNull | TypeUndefined))
218         return ASCIILiteral("Boolean?");
219     if (doesTypeConformTo(TypeMachineInt | TypeNull | TypeUndefined))
220         return ASCIILiteral("Integer?");
221     if (doesTypeConformTo(TypeNumber | TypeMachineInt | TypeNull | TypeUndefined))
222         return ASCIILiteral("Number?");
223     if (doesTypeConformTo(TypeString | TypeNull | TypeUndefined))
224         return ASCIILiteral("String?");
225    
226     if (doesTypeConformTo(TypeObject | TypeFunction | TypeString))
227         return ASCIILiteral("Object");
228     if (doesTypeConformTo(TypeObject | TypeFunction | TypeString | TypeNull | TypeUndefined))
229         return ASCIILiteral("Object?");
230
231     return ASCIILiteral("(many)");
232 }
233
234 PassRefPtr<Inspector::Protocol::Array<String>> TypeSet::allPrimitiveTypeNames() const
235 {
236     RefPtr<Inspector::Protocol::Array<String>> seen = Inspector::Protocol::Array<String>::create();
237     if (m_seenTypes & TypeUndefined)
238         seen->addItem(ASCIILiteral("Undefined"));
239     if (m_seenTypes & TypeNull)
240         seen->addItem(ASCIILiteral("Null"));
241     if (m_seenTypes & TypeBoolean)
242         seen->addItem(ASCIILiteral("Boolean"));
243     if (m_seenTypes & TypeMachineInt)
244         seen->addItem(ASCIILiteral("Integer"));
245     if (m_seenTypes & TypeNumber)
246         seen->addItem(ASCIILiteral("Number"));
247     if (m_seenTypes & TypeString)
248         seen->addItem(ASCIILiteral("String"));
249
250     return seen.release();
251 }
252
253 PassRefPtr<Inspector::Protocol::Array<Inspector::Protocol::Runtime::StructureDescription>> TypeSet::allStructureRepresentations() const
254 {
255     RefPtr<Inspector::Protocol::Array<Inspector::Protocol::Runtime::StructureDescription>> description = Inspector::Protocol::Array<Inspector::Protocol::Runtime::StructureDescription>::create();
256
257     for (size_t i = 0; i < m_structureHistory.size(); i++)
258         description->addItem(m_structureHistory.at(i)->inspectorRepresentation());
259
260     return description.release();
261 }
262
263 String TypeSet::leastCommonAncestor() const
264 {
265     return StructureShape::leastCommonAncestor(m_structureHistory);
266 }
267
268 PassRefPtr<Inspector::Protocol::Runtime::TypeSet> TypeSet::inspectorTypeSet() const
269 {
270     return Inspector::Protocol::Runtime::TypeSet::create()
271         .setIsFunction(doesTypeConformTo(TypeFunction))
272         .setIsUndefined(doesTypeConformTo(TypeUndefined))
273         .setIsNull(doesTypeConformTo(TypeNull))
274         .setIsBoolean(doesTypeConformTo(TypeBoolean))
275         .setIsInteger(doesTypeConformTo(TypeMachineInt))
276         .setIsNumber(doesTypeConformTo(TypeNumber))
277         .setIsString(doesTypeConformTo(TypeString))
278         .setIsObject(doesTypeConformTo(TypeObject))
279         .release();
280 }
281
282 String TypeSet::toJSONString() const
283 {
284     // This returns a JSON string representing an Object with the following properties:
285     //     displayTypeName: 'String'
286     //     primitiveTypeNames: 'Array<String>'
287     //     structures: 'Array<JSON<StructureShape>>'
288
289     StringBuilder json;
290     json.append("{");
291
292     json.append("\"displayTypeName\":");
293     json.append("\"");
294     json.append(displayName());
295     json.append("\"");
296     json.append(",");
297
298     json.append("\"primitiveTypeNames\":");
299     json.append("[");
300     bool hasAnItem = false;
301     if (m_seenTypes & TypeUndefined) {
302         hasAnItem = true;
303         json.append("\"Undefined\"");
304     }
305     if (m_seenTypes & TypeNull) {
306         if (hasAnItem)
307             json.append(",");
308         hasAnItem = true;
309         json.append("\"Null\"");
310     }
311     if (m_seenTypes & TypeBoolean) {
312         if (hasAnItem)
313             json.append(",");
314         hasAnItem = true;
315         json.append("\"Boolean\"");
316     }
317     if (m_seenTypes & TypeMachineInt) {
318         if (hasAnItem)
319             json.append(",");
320         hasAnItem = true;
321         json.append("\"Integer\"");
322     }
323     if (m_seenTypes & TypeNumber) {
324         if (hasAnItem)
325             json.append(",");
326         hasAnItem = true;
327         json.append("\"Number\"");
328     }
329     if (m_seenTypes & TypeString) {
330         if (hasAnItem)
331             json.append(",");
332         hasAnItem = true;
333         json.append("\"String\"");
334     }
335     json.append("]");
336
337     json.append(",");
338
339     json.append("\"structures\":");
340     json.append("[");
341     hasAnItem = false;
342     for (size_t i = 0; i < m_structureHistory.size(); i++) {
343         if (hasAnItem)
344             json.append(",");
345         hasAnItem = true;
346         json.append(m_structureHistory[i]->toJSONString());
347     }
348     json.append("]");
349
350     json.append("}");
351     return json.toString();
352 }
353
354 void TypeSet::dumpSeenTypes()
355 {
356     dataLog(seenTypes(), "\n");
357 }
358
359 StructureShape::StructureShape()
360     : m_proto(nullptr)
361     , m_propertyHash(nullptr)
362     , m_final(false)
363     , m_isInDictionaryMode(false)
364 {
365 }
366
367 void StructureShape::markAsFinal()
368 {
369     ASSERT(!m_final);
370     m_final = true;
371 }
372
373 void StructureShape::addProperty(RefPtr<StringImpl> impl)
374 {
375     ASSERT(!m_final);
376     m_fields.add(impl);
377 }
378
379 String StructureShape::propertyHash() 
380 {
381     ASSERT(m_final);
382     if (m_propertyHash)
383         return *m_propertyHash;
384
385     StringBuilder builder;
386     builder.append(':');
387     builder.append(m_constructorName);
388     builder.append(':');
389     
390     for (auto iter = m_fields.begin(), end = m_fields.end(); iter != end; ++iter) {
391         String property = String((*iter));
392         property.replace(":", "\\:"); // Ensure that hash({"foo:", "bar"}) != hash({"foo", ":bar"}) because we're using colons as a separator and colons are legal characters in field names in JS.
393         builder.append(property);
394     }
395
396     if (m_proto) {
397         builder.append(':');
398         builder.append("__proto__");
399         builder.append(m_proto->propertyHash());
400     }
401
402     m_propertyHash = std::make_unique<String>(builder.toString());
403     return *m_propertyHash;
404 }
405
406 String StructureShape::leastCommonAncestor(const Vector<RefPtr<StructureShape>> shapes)
407 {
408     if (!shapes.size())
409         return emptyString();
410
411     RefPtr<StructureShape> origin = shapes.at(0);
412     for (size_t i = 1; i < shapes.size(); i++) {
413         bool foundLUB = false;
414         while (!foundLUB) {
415             RefPtr<StructureShape> check = shapes.at(i);
416             String curCtorName = origin->m_constructorName;
417             while (check) {
418                 if (check->m_constructorName == curCtorName) {
419                     foundLUB = true;
420                     break;
421                 }
422                 check = check->m_proto;
423             }
424             if (!foundLUB) {
425                 origin = origin->m_proto;
426                 // All Objects must share the 'Object' Prototype. Therefore, at the very least, we should always converge on 'Object' before reaching a null prototype.
427                 RELEASE_ASSERT(origin); 
428             }
429         }
430
431         if (origin->m_constructorName == "Object")
432             break;
433     }
434
435     return origin->m_constructorName;
436 }
437
438 String StructureShape::stringRepresentation()
439 {
440     StringBuilder representation;
441     RefPtr<StructureShape> curShape = this;
442
443     representation.append('{');
444     while (curShape) {
445         for (auto it = curShape->m_fields.begin(), end = curShape->m_fields.end(); it != end; ++it) {
446             String prop((*it).get());
447             representation.append(prop);
448             representation.append(", ");
449         }
450
451         if (curShape->m_proto) {
452             String prot = makeString("__proto__ [", curShape->m_proto->m_constructorName, ']');
453             representation.append(prot);
454             representation.append(", ");
455         }
456
457         curShape = curShape->m_proto;
458     }
459
460     if (representation.length() >= 3)
461         representation.resize(representation.length() - 2);
462
463     representation.append('}');
464
465     return representation.toString();
466 }
467
468 String StructureShape::toJSONString() const
469 {
470     // This returns a JSON string representing an Object with the following properties:
471     //     constructorName: 'String'
472     //     fields: 'Array<String>'
473     //     optionalFields: 'Array<String>'
474     //     proto: 'JSON<StructureShape> | null'
475
476     StringBuilder json;
477     json.append("{");
478
479     json.append("\"constructorName\":");
480     json.append("\"");
481     json.append(m_constructorName);
482     json.append("\"");
483     json.append(",");
484
485     json.append("\"isInDictionaryMode\":");
486     if (m_isInDictionaryMode)
487         json.append("true");
488     else
489         json.append("false");
490     json.append(",");
491
492     json.append("\"fields\":");
493     json.append("[");
494     bool hasAnItem = false;
495     for (auto it = m_fields.begin(), end = m_fields.end(); it != end; ++it) {
496         if (hasAnItem)
497             json.append(",");
498         hasAnItem = true;
499
500         String fieldName((*it).get());
501         json.append("\"");
502         json.append(fieldName);
503         json.append("\"");
504     }
505     json.append("]");
506     json.append(",");
507
508     json.append("\"optionalFields\":");
509     json.append("[");
510     hasAnItem = false;
511     for (auto it = m_optionalFields.begin(), end = m_optionalFields.end(); it != end; ++it) {
512         if (hasAnItem)
513             json.append(",");
514         hasAnItem = true;
515
516         String fieldName((*it).get());
517         json.append("\"");
518         json.append(fieldName);
519         json.append("\"");
520     }
521     json.append("]");
522     json.append(",");
523
524     json.append("\"proto\":");
525     if (m_proto)
526         json.append(m_proto->toJSONString());
527     else
528         json.append("null");
529
530     json.append("}");
531
532     return json.toString();
533 }
534
535 PassRefPtr<Inspector::Protocol::Runtime::StructureDescription> StructureShape::inspectorRepresentation()
536 {
537     RefPtr<Inspector::Protocol::Runtime::StructureDescription> base = Inspector::Protocol::Runtime::StructureDescription::create();
538     RefPtr<Inspector::Protocol::Runtime::StructureDescription> currentObject = base;
539     RefPtr<StructureShape> currentShape = this;
540
541     while (currentShape) {
542         auto fields = Inspector::Protocol::Array<String>::create();
543         auto optionalFields = Inspector::Protocol::Array<String>::create();
544         for (auto field : currentShape->m_fields)
545             fields->addItem(field.get());
546         for (auto field : currentShape->m_optionalFields)
547             optionalFields->addItem(field.get());
548
549         currentObject->setFields(fields);
550         currentObject->setOptionalFields(optionalFields);
551         currentObject->setConstructorName(currentShape->m_constructorName);
552         currentObject->setIsImprecise(currentShape->m_isInDictionaryMode);
553
554         if (currentShape->m_proto) {
555             RefPtr<Inspector::Protocol::Runtime::StructureDescription> nextObject = Inspector::Protocol::Runtime::StructureDescription::create();
556             currentObject->setPrototypeStructure(nextObject);
557             currentObject = nextObject;
558         }
559
560         currentShape = currentShape->m_proto;
561     }
562
563     return base.release();
564 }
565
566 bool StructureShape::hasSamePrototypeChain(PassRefPtr<StructureShape> prpOther)
567 {
568     RefPtr<StructureShape> self = this;
569     RefPtr<StructureShape> other = prpOther;
570     while (self && other) {
571         if (self->m_constructorName != other->m_constructorName)
572             return false;
573         self = self->m_proto;
574         other = other->m_proto;
575     }
576
577     return !self && !other;
578 }
579
580 PassRefPtr<StructureShape> StructureShape::merge(const PassRefPtr<StructureShape> prpA, const PassRefPtr<StructureShape> prpB)
581 {
582     RefPtr<StructureShape> a = prpA;
583     RefPtr<StructureShape> b = prpB;
584     ASSERT(a->hasSamePrototypeChain(b));
585
586     RefPtr<StructureShape> merged = StructureShape::create();
587     for (auto field : a->m_fields) {
588         if (b->m_fields.contains(field))
589             merged->m_fields.add(field);
590         else
591             merged->m_optionalFields.add(field);
592     }
593
594     for (auto field : b->m_fields) {
595         if (!merged->m_fields.contains(field)) {
596             auto addResult = merged->m_optionalFields.add(field);
597             ASSERT_UNUSED(addResult, addResult.isNewEntry);
598         }
599     }
600
601     for (auto field : a->m_optionalFields)
602         merged->m_optionalFields.add(field);
603     for (auto field : b->m_optionalFields)
604         merged->m_optionalFields.add(field);
605
606     ASSERT(a->m_constructorName == b->m_constructorName);
607     merged->setConstructorName(a->m_constructorName);
608
609     if (a->m_proto) {
610         RELEASE_ASSERT(b->m_proto);
611         merged->setProto(StructureShape::merge(a->m_proto, b->m_proto));
612     }
613
614     merged->markAsFinal();
615
616     return merged.release();
617 }
618
619 void StructureShape::enterDictionaryMode()
620 {
621     m_isInDictionaryMode = true;
622 }
623
624 } //namespace JSC