Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qqmlpreviewdiff.cpp
Go to the documentation of this file.
1// Copyright (C) 2026 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
6
7#include <private/qv4staticvalue_p.h>
8
9#include <QtCore/qmap.h>
10#include <QtCore/qscopedvaluerollback.h>
11#include <QtCore/qset.h>
12
13#include <cstring>
14
15QT_BEGIN_NAMESPACE
16
17// IMPORTANT:
18//
19// If you update the data structures in qv4compileddata_p.h, then you also need to
20// update the comparison functions below. Only after making sure the comparisons
21// are fine, bump the version in the static_assert.
22static_assert(QV4_DATA_STRUCTURE_VERSION == 0x56);
23
24namespace QV4::CompiledData {
25
28
29template <typename Data>
30Data extractData(const Data &data)
31{
32 return data;
33}
34
35static EnumHunk extractData(const Enum &e)
36{
37 EnumHunk data;
38 data.data = e;
39 for (const EnumValue *v = e.enumValuesBegin(); v != e.enumValuesEnd(); ++v)
40 data.values.append(*v);
41 return data;
42}
43
44static SignalHunk extractData(const Signal &s)
45{
46 SignalHunk data;
47 data.data = s;
48 for (quint32 i = 0; i < s.nParameters; ++i)
49 data.parameters.append(*s.parameterAt(i));
50 return data;
51}
52
53static FunctionHunk extractData(const Function &func)
54{
55 FunctionHunk data;
56 data.data = func;
57
58 for (quint16 i = 0, end = func.nFormals; i != end; ++i)
59 data.formals.append(func.formalsTable()[i]);
60
61 for (quint16 i = 0, end = func.nLocals; i != end; ++i)
62 data.locals.append(func.localsTable()[i]);
63
64 for (quint16 i = 0, end = func.nLineAndStatementNumbers; i != end; ++i)
65 data.lineAndStatementNumbers.append(func.lineAndStatementNumberTable()[i]);
66
67 for (quint32 i = 0, end = func.nLabelInfos; i != end; ++i)
68 data.labelInfos.append(func.labelInfoTable()[i]);
69
70 data.code = QByteArray(func.code(), func.codeSize);
71 return data;
72}
73
74static ObjectHunk extractData(const Object &obj)
75{
76 ObjectHunk data;
77 data.data = obj;
78
79 for (quint32 i = 0; i < obj.nFunctions; ++i)
80 data.functionIndices.append(extractData(obj.functionOffsetTable()[i]));
81
82 for (quint32 i = 0; i < obj.nBindings; ++i)
83 data.bindings.append(extractData(obj.bindingTable()[i]));
84
85 for (quint32 i = 0; i < obj.nProperties; ++i)
86 data.properties.append(extractData(obj.propertyTable()[i]));
87
88 for (quint32 i = 0; i < obj.nAliases; ++i)
89 data.aliases.append(extractData(obj.aliasTable()[i]));
90
91 for (quint32 i = 0; i < obj.nSignals; ++i)
92 data.sigs.append(extractData(*obj.signalAt(i)));
93
94 for (quint32 i = 0; i < obj.nEnums; ++i)
95 data.enums.append(extractData(*obj.enumAt(i)));
96
97 for (quint32 i = 0; i < obj.nInlineComponents; ++i)
98 data.inlineComponents.append(extractData(obj.inlineComponentTable()[i]));
99
100 for (quint32 i = 0; i < obj.nRequiredPropertyExtraData; ++i)
101 data.requiredPropertyExtraData.append(extractData(obj.requiredPropertyExtraDataTable()[i]));
102
103 return data;
104}
105
106static UnitHunk extractData(const Unit &unit)
107{
108 return unit;
109}
110
111static ClassHunk extractData(const Class &cls)
112{
113 ClassHunk data;
114 data.data = cls;
115 const Method *methods = cls.methodTable();
116 for (quint32 i = 0, end = cls.nStaticMethods + cls.nMethods; i < end; ++i)
117 data.methods.append(methods[i]);
118 return data;
119}
120
121static TemplateObjectHunk extractData(const TemplateObject &to)
122{
124 data.size = to.size;
125 const quint32_le *strings = reinterpret_cast<const quint32_le *>(&to + 1);
126 for (quint32 i = 0; i < 2u * to.size; ++i)
127 data.strings.append(strings[i]);
128 return data;
129}
130
131static JsClassHunk extractData(const JSClass &jsClass)
132{
133 JsClassHunk data;
134 data.nMembers = jsClass.nMembers;
135 const JSClassMember *members = reinterpret_cast<const JSClassMember *>(&jsClass + 1);
136 for (quint32 i = 0; i < jsClass.nMembers; ++i)
137 data.members.append(members[i]);
138 return data;
139}
140
141static BlockHunk extractData(const Block &block)
142{
143 BlockHunk data;
144 data.data = block;
145 for (quint32 i = 0; i < block.nLocals; ++i)
146 data.locals.append(block.localsTable()[i]);
147 return data;
148}
149
150// location extraction
151
152template <typename T, typename L = void>
154{
155 static bool extract(const T &) { return false; }
156};
157
158template <typename T>
160{
161 static Location extract(const T &t) { return t.location; }
162};
163
164template <>
166{
168 {
170 }
171};
172
173template <>
175{
177 {
178 return { alias.location(), alias.referenceLocation() };
179 }
180};
181
182template <>
184{
186 {
188 }
189};
190
191template <typename ElementT>
193
194#define COMPARISON_TRAITS(Element) template
195 <> struct
196 ComparisonTraits<Element> \
197{
198 static constexpr ChangeType Changed = ChangeType::Element ## Changed;
199 static constexpr ChangeType LocationChanged = ChangeType::None;
200 static constexpr ChangeType IndexChanged = ChangeType::None;
201 static constexpr ChangeType Removed = ChangeType::Element ## Removed;
202 static constexpr ChangeType Added = ChangeType::Element ## Added; \
203};
204
205
206#define COMPARISON_TRAITS_WITH_LOCATION(Element) template
207 <> struct
208 ComparisonTraits<Element> \
209{
210 static constexpr ChangeType Changed = ChangeType::Element ## Changed;
211 static constexpr ChangeType LocationChanged = ChangeType::Element ## LocationChanged;
212 static constexpr ChangeType IndexChanged = ChangeType::None;
213 static constexpr ChangeType Removed = ChangeType::Element ## Removed;
214 static constexpr ChangeType Added = ChangeType::Element ## Added; \
215};
216
217#define COMPARISON_TRAITS_WITH_LOCATION_AND_INDEX(Element) template
218 <> struct
219 ComparisonTraits<Element> \
220{
221 static constexpr ChangeType Changed = ChangeType::Element ## Changed;
222 static constexpr ChangeType LocationChanged = ChangeType::Element ## LocationChanged;
223 static constexpr ChangeType IndexChanged = ChangeType::Element ## IndexChanged;
224 static constexpr ChangeType Removed = ChangeType::Element ## Removed;
225 static constexpr ChangeType Added = ChangeType::Element ## Added; \
226};
227
237
240
249
250template <typename AccessorFn>
252{
253 AccessorFn accessor;
255};
256
257template <typename AccessorFn>
258IndexedElements(AccessorFn, quint32) -> IndexedElements<AccessorFn>;
259
261{
262 const Unit *const oldUnit;
263 const Unit *const newUnit;
266
267 template <typename ElementT, typename OldSource, typename NewSource, typename ContentEqFn>
268 void compareIndexedElements(OldSource oldSource, NewSource newSource, ContentEqFn contentEq)
269 {
270 using Traits = ComparisonTraits<ElementT>;
271 const auto &oldAccessor = oldSource.accessor;
272 const auto &newAccessor = newSource.accessor;
273 const quint32 oldCount = oldSource.count;
274 const quint32 newCount = newSource.count;
275 quint32 commonCount = qMin(oldCount, newCount);
276
277 // Compare elements at common positions
278 for (quint32 i = 0; i < commonCount; ++i) {
279 const ElementT &oldElem = oldAccessor(i);
280 const ElementT &newElem = newAccessor(i);
281
282 if (!contentEq(oldElem, newElem)) {
283 Change change;
285 change.newIndex = i;
286 change.oldIndex = i;
287 change.type = Traits::Changed;
288 change.data = extractData(newElem);
289 changes.append(change);
290 }
291
292 if (Traits::LocationChanged != ChangeType::None
293 && LocationExtractor<ElementT>::extract(oldElem)
294 != LocationExtractor<ElementT>::extract(newElem)) {
295 Change change;
297 change.newIndex = i;
298 change.oldIndex = i;
299 change.type = Traits::LocationChanged;
300 change.data = extractData(newElem);
301 changes.append(change);
302 }
303 }
304
305 // Emit Removed for extra elements in old
306 for (quint32 i = commonCount; i < oldCount; ++i) {
307 Change change;
308 change.type = Traits::Removed;
310 change.newIndex = i;
311 change.oldIndex = i;
312 changes.append(change);
313 }
314
315 // Emit Added for extra elements in new
316 for (quint32 i = commonCount; i < newCount; ++i) {
317 Change change;
318 change.type = Traits::Added;
320 change.newIndex = i;
321 change.oldIndex = i;
322 change.data = extractData(newAccessor(i));
323 changes.append(change);
324 }
325 }
326
327 // keyFn retrieves the name of the element as string, so that we can compare
328 // by name and sequential number of duplicate (if there are duplicates).
329 template <typename ElementT, typename OldSource, typename NewSource, typename KeyFn,
330 typename ContentEqFn>
331 void compareNamedElements(OldSource oldSource, NewSource newSource, KeyFn keyFn,
332 ContentEqFn contentEq)
333 {
334 using Traits = ComparisonTraits<ElementT>;
335 const auto &oldAccessor = oldSource.accessor;
336 const auto &newAccessor = newSource.accessor;
337 const quint32 oldCount = oldSource.count;
338 const quint32 newCount = newSource.count;
339
340 const auto disambiguatedKeys = [&](auto accessor, quint32 count, const Unit *unit) {
341 QList<QString> keys;
342 keys.reserve(count);
343 QHash<QString, int> seen;
344 for (quint32 i = 0; i < count; ++i) {
345 const QString base = keyFn(accessor(i), unit);
346 keys.append(base + QChar(QChar::Null) + QString::number(seen[base]++));
347 }
348 return keys;
349 };
350
351 const QList<QString> oldKeys = disambiguatedKeys(oldAccessor, oldCount, oldUnit);
352 const QList<QString> newKeys = disambiguatedKeys(newAccessor, newCount, newUnit);
353
354 QHash<QString, quint32> oldByKey;
355 oldByKey.reserve(oldCount);
356 for (quint32 i = 0; i < oldCount; ++i)
357 oldByKey.insert(oldKeys[i], i);
358
359 QList<bool> oldMatched(oldCount, false);
360 for (quint32 j = 0; j < newCount; ++j) {
361 const auto it = oldByKey.constFind(newKeys[j]);
362 if (it == oldByKey.constEnd()) {
363 changes.append(Change{ Traits::Added, m_currentObjectIndex, j, j,
364 extractData(newAccessor(j)) });
365 continue;
366 }
367
368 const quint32 i = it.value();
369 oldMatched[i] = true;
370 const ElementT &oldElem = oldAccessor(i);
371 const ElementT &newElem = newAccessor(j);
372
373 if (!contentEq(oldElem, newElem)) {
374 changes.append(Change{ Traits::Changed, m_currentObjectIndex, j, i,
375 extractData(newElem) });
376 }
377
378 if (Traits::LocationChanged != ChangeType::None
379 && LocationExtractor<ElementT>::extract(oldElem)
380 != LocationExtractor<ElementT>::extract(newElem)) {
381 changes.append(Change{ Traits::LocationChanged, m_currentObjectIndex, j, i,
382 extractData(newElem) });
383 }
384
385 if (Traits::IndexChanged != ChangeType::None && i != j) {
386 changes.append(Change{ Traits::IndexChanged, m_currentObjectIndex, j, i,
387 extractData(newElem) });
388 }
389 }
390
391 for (quint32 i = 0; i < oldCount; ++i) {
392 if (!oldMatched[i])
393 changes.append(Change{ Traits::Removed, m_currentObjectIndex, i, i, NoHunk{} });
394 }
395 }
396
397 bool stringsEqual(uint oldName, uint newName) const
398 {
399 Q_ASSERT(oldName < oldUnit->stringTableSize);
400 Q_ASSERT(newName < newUnit->stringTableSize);
401 return oldUnit->stringAtInternal(oldName) == newUnit->stringAtInternal(newName);
402 }
403
405 {
406 if (std::memcmp(oldUnit->magic, newUnit->magic, sizeof(oldUnit->magic)) != 0)
407 return false;
408
409 if (oldUnit->version != newUnit->version || oldUnit->reserved != newUnit->reserved
410 || oldUnit->sourceTimeStamp != newUnit->sourceTimeStamp
411 || oldUnit->unitSize != newUnit->unitSize) {
412 return false;
413 }
414
415 // sourceChecksum lives before md5Checksum and is therefore not covered by it.
416 if (std::memcmp(oldUnit->sourceChecksum, newUnit->sourceChecksum,
417 sizeof(oldUnit->sourceChecksum))
418 != 0) {
419 return false;
420 }
421
422 // If anything below the checksum has changed, the checksum itself has changed, too
423 return std::memcmp(oldUnit->md5Checksum, newUnit->md5Checksum, sizeof(oldUnit->md5Checksum))
424 == 0;
425 }
426
427 bool objectContentEqual(const Object &oldObj, const Object &newObj) const
428 {
429 // Keep in sync with the Object struct in qv4compileddata_p.h
430 static_assert(sizeof(Object) == 76, "Update objectContentEqual when Object layout changes");
431 if (oldObj.nFunctions != newObj.nFunctions)
432 return false;
433
434 // The object references its methods by their global function-table index. Those indices
435 // shift whenever any function is added/removed/reordered elsewhere in the unit, so compare
436 // the referenced functions by name instead of by raw index: a mere reindexing must not make
437 // the object look structurally changed (body changes are reported at the function level).
438 const quint32_le *oldFuncs = oldObj.functionOffsetTable();
439 const quint32_le *newFuncs = newObj.functionOffsetTable();
440 for (quint32 i = 0; i < oldObj.nFunctions; ++i) {
441 if (!stringsEqual(oldUnit->functionAt(oldFuncs[i])->nameIndex,
442 newUnit->functionAt(newFuncs[i])->nameIndex)) {
443 return false;
444 }
445 }
446
447 return stringsEqual(oldObj.inheritedTypeNameIndex, newObj.inheritedTypeNameIndex)
448 && stringsEqual(oldObj.idNameIndex, newObj.idNameIndex)
449 && oldObj.flags() == newObj.flags()
450 && oldObj.hasAliasAsDefaultProperty() == newObj.hasAliasAsDefaultProperty()
451 && oldObj.indexOfDefaultPropertyOrAlias == newObj.indexOfDefaultPropertyOrAlias;
452 }
453
454 bool propertyContentEqual(const Property &oldProp, const Property &newProp) const
455 {
456 // Keep in sync with the Property struct in qv4compileddata_p.h
457 static_assert(sizeof(Property) == 12, "Update propertyContentEqual when Property layout changes");
458 return stringsEqual(oldProp.nameIndex(), newProp.nameIndex())
459 && (oldProp.isCommonType() == newProp.isCommonType()
460 && (oldProp.isCommonType()
461 ? oldProp.commonTypeOrTypeNameIndex()
462 == newProp.commonTypeOrTypeNameIndex()
463 : stringsEqual(oldProp.typeNameIndex(), newProp.typeNameIndex())))
464 && oldProp.isReadOnly() == newProp.isReadOnly()
465 && oldProp.isRequired() == newProp.isRequired()
466 && oldProp.isList() == newProp.isList()
467 && oldProp.isVirtual() == newProp.isVirtual()
468 && oldProp.isOverride() == newProp.isOverride()
469 && oldProp.isFinal() == newProp.isFinal();
470 }
471
472 // In addition to structural equality, also compare the actual name strings: the integer
473 // nameIndex may be the same while the string at that index changed (property rename).
474 bool aliasContentEqual(const Alias &oldAlias, const Alias &newAlias) const
475 {
476 // Keep in sync with the Alias struct in qv4compileddata_p.h
477 static_assert(sizeof(Alias) == 20, "Update aliasContentEqual when Alias layout changes");
478 return stringsEqual(oldAlias.idIndex(), newAlias.idIndex())
479 && stringsEqual(oldAlias.nameIndex(), newAlias.nameIndex())
480 && stringsEqual(oldAlias.propertyNameIndex(), newAlias.propertyNameIndex())
481 && oldAlias.isReadOnly() == newAlias.isReadOnly();
482 }
483
484 bool enumContentEqual(const Enum &oldEnum, const Enum &newEnum) const
485 {
486 // Keep in sync with the Enum and EnumValue structs in qv4compileddata_p.h
487 static_assert(sizeof(Enum) == 12, "Update enumContentEqual when Enum layout changes");
488 static_assert(sizeof(EnumValue) == 8, "Update enumContentEqual when EnumValue layout changes");
489 if (!stringsEqual(oldEnum.nameIndex, newEnum.nameIndex)
490 || oldEnum.nEnumValues != newEnum.nEnumValues) {
491 return false;
492 }
493
494 for (quint32 i = 0; i < oldEnum.nEnumValues; ++i) {
495 const EnumValue *oldValue = oldEnum.enumValueAt(i);
496 const EnumValue *newValue = newEnum.enumValueAt(i);
497 if (oldValue->value != newValue->value
498 || !stringsEqual(oldValue->nameIndex, newValue->nameIndex)) {
499 return false;
500 }
501 }
502
503 return true;
504 }
505
506 bool signalContentEqual(const Signal &oldSig, const Signal &newSig) const
507 {
508 // Keep in sync with the Signal and Parameter structs in qv4compileddata_p.h
509 static_assert(sizeof(Signal) == 12, "Update signalContentEqual when Signal layout changes");
510 static_assert(sizeof(Parameter) == 8, "Update signalContentEqual when Parameter layout changes");
511 if (!stringsEqual(oldSig.nameIndex, newSig.nameIndex))
512 return false;
513 if (oldSig.nParameters != newSig.nParameters)
514 return false;
515 for (quint32 i = 0; i < oldSig.nParameters; ++i) {
516 const Parameter *oldP = oldSig.parameterAt(i);
517 const Parameter *newP = newSig.parameterAt(i);
518 if (!stringsEqual(oldP->nameIndex, newP->nameIndex)
519 || !parameterTypeContentEqual(oldP->type, newP->type)) {
520 return false;
521 }
522 }
523 return true;
524 }
525
526 bool bindingContentEqual(const Binding &oldBinding, const Binding &newBinding) const
527 {
528 // Keep in sync with the Binding and TranslationData structs in qv4compileddata_p.h
529 static_assert(sizeof(Binding) == 24, "Update bindingContentEqual when Binding layout changes");
530 static_assert(sizeof(TranslationData) == 16, "Update bindingContentEqual when TranslationData layout changes");
531 if (oldBinding.type() != newBinding.type() || oldBinding.flags() != newBinding.flags())
532 return false;
533
534 if (!stringsEqual(oldBinding.propertyNameIndex, newBinding.propertyNameIndex))
535 return false;
536
537 switch (oldBinding.type()) {
538 case Binding::Type_Invalid:
539 return true;
540 case Binding::Type_Boolean:
541 return oldBinding.valueAsBoolean() == newBinding.valueAsBoolean();
542 case Binding::Type_Number: {
543 const uint oldIdx = oldBinding.value.constantValueIndex;
544 const uint newIdx = newBinding.value.constantValueIndex;
545 Q_ASSERT(oldIdx < oldUnit->constantTableSize);
546 Q_ASSERT(newIdx < newUnit->constantTableSize);
547 return oldUnit->constants()[oldIdx] == newUnit->constants()[newIdx];
548 }
549 case Binding::Type_String:
550 return stringsEqual(oldBinding.stringIndex, newBinding.stringIndex);
551 case Binding::Type_Null:
552 return true;
553 case Binding::Type_Translation:
554 case Binding::Type_TranslationById: {
555 const auto &oldTrans = oldUnit->translations()[oldBinding.value.translationDataIndex];
556 const auto &newTrans = newUnit->translations()[newBinding.value.translationDataIndex];
557
558 // contextIndex uses NoContextIndex as sentinel; compare by
559 // resolved string only when both are valid indices.
560 const bool oldHasCtx = oldTrans.contextIndex != TranslationData::NoContextIndex;
561 const bool newHasCtx = newTrans.contextIndex != TranslationData::NoContextIndex;
562
563 if (oldHasCtx != newHasCtx)
564 return false;
565
566 if (oldHasCtx && !stringsEqual(oldTrans.contextIndex, newTrans.contextIndex))
567 return false;
568
569 return stringsEqual(oldBinding.stringIndex, newBinding.stringIndex)
570 && stringsEqual(oldTrans.stringIndex, newTrans.stringIndex)
571 && stringsEqual(oldTrans.commentIndex, newTrans.commentIndex)
572 && oldTrans.number == newTrans.number;
573 }
574 case Binding::Type_Script:
575 return oldBinding.value.compiledScriptIndex == newBinding.value.compiledScriptIndex;
576 case Binding::Type_Object:
577 case Binding::Type_AttachedProperty:
578 case Binding::Type_GroupedProperty:
579 return oldBinding.value.objectIndex == newBinding.value.objectIndex
580 && objectContentEqual(
581 *oldUnit->qmlUnit()->objectAt(oldBinding.value.objectIndex),
582 *newUnit->qmlUnit()->objectAt(newBinding.value.objectIndex));
583 }
584
585 return false;
586 }
587
588 bool parameterTypeContentEqual(const ParameterType &oldType, const ParameterType &newType) const
589 {
590 // Keep in sync with the ParameterType struct in qv4compileddata_p.h
591 static_assert(sizeof(ParameterType) == 4, "Update parameterTypeContentEqual when ParameterType layout changes");
592 const bool indexIsCommonType = oldType.indexIsCommonType();
593 if (newType.indexIsCommonType() != indexIsCommonType
594 || oldType.isList() != newType.isList()) {
595 return false;
596 }
597
598 return indexIsCommonType
599 ? oldType.typeNameIndexOrCommonType() == newType.typeNameIndexOrCommonType()
600 : stringsEqual(oldType.typeNameIndexOrCommonType(),
601 newType.typeNameIndexOrCommonType());
602 }
603
604 bool functionContentEqual(const Function &oldFunc, const Function &newFunc) const
605 {
606 // Keep in sync with the Function struct in qv4compileddata_p.h
607 static_assert(sizeof(Function) == 56, "Update functionContentEqual when Function layout changes");
608 if (oldFunc.nestedFunctionIndex != newFunc.nestedFunctionIndex
609 || !stringsEqual(oldFunc.nameIndex, newFunc.nameIndex) || oldFunc.flags != newFunc.flags
610 || oldFunc.nFormals != newFunc.nFormals || oldFunc.codeSize != newFunc.codeSize
611 || !parameterTypeContentEqual(oldFunc.returnType, newFunc.returnType)) {
612 return false;
613 }
614
615 for (int i = 0, end = oldFunc.nFormals; i != end; ++i) {
616 const auto &oldFormal = oldFunc.formalsTable()[i];
617 const auto &newFormal = newFunc.formalsTable()[i];
618 if (!parameterTypeContentEqual(oldFormal.type, newFormal.type))
619 return false;
620 if (!stringsEqual(oldFormal.nameIndex, newFormal.nameIndex))
621 return false;
622 }
623
624 return std::memcmp(oldFunc.code(), newFunc.code(), oldFunc.codeSize) == 0;
625 }
626
627 // Functions live in a single unit-global table, but their names are only meaningful within the
628 // object that declares them (a method "foo", or a binding's "expression for <property>"). Build a
629 // per-function key that qualifies the name with the owning object index, so two objects that both
630 // bind, say, "width" don't get matched to each other across the reload. Functions not reachable
631 // from an object's methods or script bindings (e.g. nested closures) keep their bare name.
632 QHash<const Function *, QString> functionOwnerKeys(const Unit *unit) const
633 {
634 QHash<const Function *, QString> keys;
635 const QmlUnit *qml = unit->qmlUnit();
636 if (!qml)
637 return keys;
638 for (quint32 o = 0; o < qml->nObjects; ++o) {
639 const Object *obj = qml->objectAt(o);
640 const QString prefix = QString::number(o) + QChar(QChar::Null);
641 const quint32_le *methods = obj->functionOffsetTable();
642 for (quint32 m = 0; m < obj->nFunctions; ++m) {
643 const Function *f = unit->functionAt(methods[m]);
644 keys.insert(f, prefix + unit->stringAtInternal(f->nameIndex));
645 }
646 const Binding *bindings = obj->bindingTable();
647 for (quint32 b = 0; b < obj->nBindings; ++b) {
648 if (bindings[b].type() != Binding::Type_Script)
649 continue;
650 const Function *f = unit->functionAt(bindings[b].value.compiledScriptIndex);
651 keys.insert(f, prefix + unit->stringAtInternal(f->nameIndex));
652 }
653 }
654 return keys;
655 }
656
657 bool translationContentEqual(const TranslationData &oldTrans,
658 const TranslationData &newTrans) const
659 {
660 // Keep in sync with the TranslationData struct in qv4compileddata_p.h
661 static_assert(sizeof(TranslationData) == 16, "Update translationContentEqual when TranslationData layout changes");
662 if (oldTrans.contextIndex != newTrans.contextIndex)
663 return false;
664 if (oldTrans.contextIndex != TranslationData::NoContextIndex
665 && !stringsEqual(oldTrans.contextIndex, newTrans.contextIndex)) {
666 return false;
667 }
668 return stringsEqual(oldTrans.stringIndex, newTrans.stringIndex)
669 && stringsEqual(oldTrans.commentIndex, newTrans.commentIndex)
670 && oldTrans.number == newTrans.number;
671 }
672
673 bool classContentEqual(const Class &oldCls, const Class &newCls) const
674 {
675 // Keep in sync with the Class and Method structs in qv4compileddata_p.h
676 static_assert(sizeof(Class) == 24, "Update classContentEqual when Class layout changes");
677 static_assert(sizeof(Method) == 12, "Update classContentEqual when Method layout changes");
678 if (!stringsEqual(oldCls.nameIndex, newCls.nameIndex)
679 || oldCls.scopeIndex != newCls.scopeIndex
680 || oldCls.constructorFunction != newCls.constructorFunction
681 || oldCls.nStaticMethods != newCls.nStaticMethods
682 || oldCls.nMethods != newCls.nMethods) {
683 return false;
684 }
685 const Method *oldMethods = oldCls.methodTable();
686 const Method *newMethods = newCls.methodTable();
687 for (quint32 i = 0, end = oldCls.nStaticMethods + oldCls.nMethods; i < end; ++i) {
688 if (!stringsEqual(oldMethods[i].name, newMethods[i].name)
689 || oldMethods[i].type != newMethods[i].type
690 || oldMethods[i].function != newMethods[i].function) {
691 return false;
692 }
693 }
694 return true;
695 }
696
697 bool templateObjectContentEqual(const TemplateObject &oldTO, const TemplateObject &newTO) const
698 {
699 // Keep in sync with the TemplateObject struct in qv4compileddata_p.h
700 static_assert(sizeof(TemplateObject) == 4, "Update templateObjectContentEqual when TemplateObject layout changes");
701 if (oldTO.size != newTO.size)
702 return false;
703 const quint32_le *oldStrings = reinterpret_cast<const quint32_le *>(&oldTO + 1);
704 const quint32_le *newStrings = reinterpret_cast<const quint32_le *>(&newTO + 1);
705 for (quint32 i = 0; i < 2u * oldTO.size; ++i) {
706 if (!stringsEqual(oldStrings[i], newStrings[i]))
707 return false;
708 }
709 return true;
710 }
711
712 bool jsClassContentEqual(const JSClass &oldJC, const JSClass &newJC) const
713 {
714 // Keep in sync with the JSClass and JSClassMember structs in qv4compileddata_p.h
715 static_assert(sizeof(JSClass) == 4, "Update jsClassContentEqual when JSClass layout changes");
716 static_assert(sizeof(JSClassMember) == 4, "Update jsClassContentEqual when JSClassMember layout changes");
717 if (oldJC.nMembers != newJC.nMembers)
718 return false;
719 const JSClassMember *oldMembers = reinterpret_cast<const JSClassMember *>(&oldJC + 1);
720 const JSClassMember *newMembers = reinterpret_cast<const JSClassMember *>(&newJC + 1);
721 for (quint32 i = 0; i < oldJC.nMembers; ++i) {
722 if (!stringsEqual(oldMembers[i].nameOffset(), newMembers[i].nameOffset())
723 || oldMembers[i].isAccessor() != newMembers[i].isAccessor()) {
724 return false;
725 }
726 }
727 return true;
728 }
729
730 bool blockContentEqual(const Block &oldBlock, const Block &newBlock) const
731 {
732 // Keep in sync with the Block struct in qv4compileddata_p.h
733 static_assert(sizeof(Block) == 12, "Update blockContentEqual when Block layout changes");
734 if (oldBlock.nLocals != newBlock.nLocals
735 || oldBlock.sizeOfLocalTemporalDeadZone != newBlock.sizeOfLocalTemporalDeadZone) {
736 return false;
737 }
738 for (quint32 i = 0; i < oldBlock.nLocals; ++i) {
739 if (!stringsEqual(oldBlock.localsTable()[i], newBlock.localsTable()[i]))
740 return false;
741 }
742 return true;
743 }
744
745 // Per-object comparison methods
746
747 void compareObjectProperties(const Object *oldObj, const Object *newObj)
748 {
749 const Property *oldProps = oldObj->propertyTable();
750 const Property *newProps = newObj->propertyTable();
751 compareNamedElements<Property>(
752 IndexedElements{ [oldProps](quint32 i) { return oldProps[i]; },
753 oldObj->nProperties },
754 IndexedElements{ [newProps](quint32 i) { return newProps[i]; },
755 newObj->nProperties },
756 [](const Property &p, const Unit *unit) {
757 return unit->stringAtInternal(p.nameIndex());
758 },
759 [this](const Property &a, const Property &b) {
760 return propertyContentEqual(a, b);
761 });
762 }
763
764 void compareObjectAliases(const Object *oldObj, const Object *newObj)
765 {
766 const Alias *oldAliases = oldObj->aliasesBegin();
767 const Alias *newAliases = newObj->aliasesBegin();
768 compareNamedElements<Alias>(
769 IndexedElements{ [oldAliases](quint32 i) { return oldAliases[i]; },
770 oldObj->nAliases },
771 IndexedElements{ [newAliases](quint32 i) { return newAliases[i]; },
772 newObj->nAliases },
773 [](const Alias &a, const Unit *unit) {
774 return unit->stringAtInternal(a.nameIndex());
775 },
776 [this](const Alias &a, const Alias &b) { return aliasContentEqual(a, b); });
777 }
778
779 void compareObjectEnums(const Object *oldObj, const Object *newObj)
780 {
781 compareNamedElements<Enum>(
782 IndexedElements{ [oldObj](quint32 i) -> const Enum & { return *oldObj->enumAt(i); },
783 oldObj->nEnums },
784 IndexedElements{ [newObj](quint32 i) -> const Enum & { return *newObj->enumAt(i); },
785 newObj->nEnums },
786 [](const Enum &e, const Unit *unit) { return unit->stringAtInternal(e.nameIndex); },
787 [this](const Enum &a, const Enum &b) { return enumContentEqual(a, b); });
788 }
789
790 void compareObjectSignals(const Object *oldObj, const Object *newObj)
791 {
792 compareNamedElements<Signal>(
793 IndexedElements{
794 [oldObj](quint32 i) -> const Signal & { return *oldObj->signalAt(i); },
795 oldObj->nSignals },
796 IndexedElements{
797 [newObj](quint32 i) -> const Signal & { return *newObj->signalAt(i); },
798 newObj->nSignals },
799 [](const Signal &s, const Unit *unit) {
800 return unit->stringAtInternal(s.nameIndex);
801 },
802 [this](const Signal &a, const Signal &b) { return signalContentEqual(a, b); });
803 }
804
805 void compareObjectInlineComponents(const Object *oldObj, const Object *newObj)
806 {
807 const InlineComponent *oldICs = oldObj->inlineComponentTable();
808 const InlineComponent *newICs = newObj->inlineComponentTable();
809 compareNamedElements<InlineComponent>(
810 IndexedElements{ [oldICs](quint32 i) { return oldICs[i]; },
811 oldObj->nInlineComponents },
812 IndexedElements{ [newICs](quint32 i) { return newICs[i]; },
813 newObj->nInlineComponents },
814 [](const InlineComponent &ic, const Unit *unit) {
815 return unit->stringAtInternal(ic.nameIndex);
816 },
817 [this](const InlineComponent &a, const InlineComponent &b) {
818 return a.objectIndex == b.objectIndex && stringsEqual(a.nameIndex, b.nameIndex);
819 });
820 }
821
822 void compareObjectRequiredPropertyExtraData(const Object *oldObj, const Object *newObj)
823 {
824 const RequiredPropertyExtraData *oldRPED = oldObj->requiredPropertyExtraDataTable();
825 const RequiredPropertyExtraData *newRPED = newObj->requiredPropertyExtraDataTable();
826 compareNamedElements<RequiredPropertyExtraData>(
827 IndexedElements{ [oldRPED](quint32 i) { return oldRPED[i]; },
828 oldObj->nRequiredPropertyExtraData },
829 IndexedElements{ [newRPED](quint32 i) { return newRPED[i]; },
830 newObj->nRequiredPropertyExtraData },
831 [](const RequiredPropertyExtraData &r, const Unit *unit) {
832 return unit->stringAtInternal(r.nameIndex);
833 },
834 [this](const RequiredPropertyExtraData &a, const RequiredPropertyExtraData &b) {
835 return stringsEqual(a.nameIndex, b.nameIndex);
836 });
837 }
838
839 void compareObjectBindings(const Object *oldObj, const Object *newObj)
840 {
841 const Binding *oldBindings = oldObj->bindingTable();
842 const Binding *newBindings = newObj->bindingTable();
843 compareNamedElements<Binding>(
844 IndexedElements{ [oldBindings](quint32 i) { return oldBindings[i]; },
845 oldObj->nBindings },
846 IndexedElements{ [newBindings](quint32 i) { return newBindings[i]; },
847 newObj->nBindings },
848 [](const Binding &b, const Unit *unit) {
849 return b.propertyNameIndex == 0 ? QString()
850 : unit->stringAtInternal(b.propertyNameIndex);
851 },
852 [this](const Binding &a, const Binding &b) { return bindingContentEqual(a, b); });
853 }
854
856 {
857 const QmlUnit *oldQml = oldUnit->qmlUnit();
858 const QmlUnit *newQml = newUnit->qmlUnit();
859
860 if (!oldQml || !newQml)
861 return CompilationUnitDiff();
862
863 // Check for unit metadata changes (source file, timestamp, checksum, etc.)
865 Change change;
867 change.data = extractData(*newUnit);
868 changes.append(change);
869 }
870
871 compareIndexedElements<Object>(
872 IndexedElements{
873 [oldQml](quint32 i) -> const Object & { return *oldQml->objectAt(i); },
874 oldQml->nObjects },
875 IndexedElements{
876 [newQml](quint32 i) -> const Object & { return *newQml->objectAt(i); },
877 newQml->nObjects },
878 [this](const Object &a, const Object &b) { return objectContentEqual(a, b); });
879
880 // Compare details of overlapping objects only
881 const quint32 commonCount = std::min(oldQml->nObjects, newQml->nObjects);
882 for (quint32 objectIndex = 0; objectIndex < commonCount; ++objectIndex) {
883 QScopedValueRollback guard(m_currentObjectIndex, static_cast<int>(objectIndex));
884 const Object *oldObj = oldQml->objectAt(objectIndex);
885 const Object *newObj = newQml->objectAt(objectIndex);
886
887 compareObjectProperties(oldObj, newObj);
888 compareObjectAliases(oldObj, newObj);
889 compareObjectEnums(oldObj, newObj);
890 compareObjectSignals(oldObj, newObj);
891 compareObjectInlineComponents(oldObj, newObj);
892 compareObjectRequiredPropertyExtraData(oldObj, newObj);
893 compareObjectBindings(oldObj, newObj);
894 }
895
896 compareIndexedElements<quint64_le>(
897 IndexedElements{ [this](quint32 i) { return oldUnit->constants()[i]; },
898 oldUnit->constantTableSize },
899 IndexedElements{ [this](quint32 i) { return newUnit->constants()[i]; },
900 newUnit->constantTableSize },
901 [](const quint64_le &a, const quint64_le &b) { return a == b; });
902
903 compareIndexedElements<QString>(
904 IndexedElements{ [this](quint32 i) { return oldUnit->stringAtInternal(i); },
905 oldUnit->stringTableSize },
906 IndexedElements{ [this](quint32 i) { return newUnit->stringAtInternal(i); },
907 newUnit->stringTableSize },
908 [](const QString &a, const QString &b) { return a == b; });
909
910 compareIndexedElements<Lookup>(
911 IndexedElements{ [this](quint32 i) { return oldUnit->lookupTable()[i]; },
912 oldUnit->lookupTableSize },
913 IndexedElements{ [this](quint32 i) { return newUnit->lookupTable()[i]; },
914 newUnit->lookupTableSize },
915 [this](const Lookup &a, const Lookup &b) {
916 return a.type() == b.type() && a.mode() == b.mode()
917 && stringsEqual(a.nameIndex(), b.nameIndex());
918 });
919
920 compareIndexedElements<Import>(
921 IndexedElements{ [oldQml](quint32 i) { return *oldQml->importAt(i); },
922 oldQml->nImports },
923 IndexedElements{ [newQml](quint32 i) { return *newQml->importAt(i); },
924 newQml->nImports },
925 [this](const Import &a, const Import &b) {
926 return a.type == b.type && stringsEqual(a.uriIndex, b.uriIndex)
927 && stringsEqual(a.qualifierIndex, b.qualifierIndex)
928 && a.version == b.version;
929 });
930
931 // Functions are matched by name: a named method carries its own name, and a binding's
932 // expression is named "expression for <property>" (see QmlIR::IRBuilder). Since those names
933 // are only unique within their object, the key is qualified by the owning object (see
934 // functionOwnerKeys). This keeps a function insertion/removal isolated (FunctionAdded/Removed
935 // + FunctionIndexChanged for the ones that shift) instead of a cascade of content changes.
936 const QHash<const Function *, QString> oldFunctionKeys = functionOwnerKeys(oldUnit);
937 const QHash<const Function *, QString> newFunctionKeys = functionOwnerKeys(newUnit);
938 compareNamedElements<Function>(
939 IndexedElements{
940 [this](quint32 i) -> const Function & { return *oldUnit->functionAt(i); },
941 oldUnit->functionTableSize },
942 IndexedElements{
943 [this](quint32 i) -> const Function & { return *newUnit->functionAt(i); },
944 newUnit->functionTableSize },
945 [&](const Function &f, const Unit *unit) {
946 const QHash<const Function *, QString> &keys =
947 unit == oldUnit ? oldFunctionKeys : newFunctionKeys;
948 return keys.value(&f, unit->stringAtInternal(f.nameIndex));
949 },
950 [this](const Function &a, const Function &b) {
951 return functionContentEqual(a, b);
952 });
953
954 compareIndexedElements<TranslationData>(
955 IndexedElements{ [this](quint32 i) { return oldUnit->translations()[i]; },
956 oldUnit->translationTableSize },
957 IndexedElements{ [this](quint32 i) { return newUnit->translations()[i]; },
958 newUnit->translationTableSize },
959 [this](const TranslationData &a, const TranslationData &b) {
960 return translationContentEqual(a, b);
961 });
962
963 compareIndexedElements<RegExp>(
964 IndexedElements{
965 [this](quint32 i) -> const RegExp & { return *oldUnit->regexpAt(i); },
966 oldUnit->regexpTableSize },
967 IndexedElements{
968 [this](quint32 i) -> const RegExp & { return *newUnit->regexpAt(i); },
969 newUnit->regexpTableSize },
970 [this](const RegExp &a, const RegExp &b) {
971 return a.flags() == b.flags() && stringsEqual(a.stringIndex(), b.stringIndex());
972 });
973
974 compareIndexedElements<Class>(
975 IndexedElements{
976 [this](quint32 i) -> const Class & { return *oldUnit->classAt(i); },
977 oldUnit->classTableSize },
978 IndexedElements{
979 [this](quint32 i) -> const Class & { return *newUnit->classAt(i); },
980 newUnit->classTableSize },
981 [this](const Class &a, const Class &b) { return classContentEqual(a, b); });
982
983 compareIndexedElements<TemplateObject>(
984 IndexedElements{ [this](quint32 i) -> const TemplateObject & {
985 return *oldUnit->templateObjectAt(i);
986 },
987 oldUnit->templateObjectTableSize },
988 IndexedElements{ [this](quint32 i) -> const TemplateObject & {
989 return *newUnit->templateObjectAt(i);
990 },
991 newUnit->templateObjectTableSize },
992 [this](const TemplateObject &a, const TemplateObject &b) {
993 return templateObjectContentEqual(a, b);
994 });
995
996 {
997 auto jsClassFromUnit = [](const Unit *unit, quint32 idx) -> const JSClass & {
998 const quint32_le *offsetTable = reinterpret_cast<const quint32_le *>(
999 reinterpret_cast<const char *>(unit) + unit->offsetToJSClassTable);
1000 return *reinterpret_cast<const JSClass *>(reinterpret_cast<const char *>(unit)
1001 + offsetTable[idx]);
1002 };
1003 compareIndexedElements<JSClass>(
1004 IndexedElements{ [this, jsClassFromUnit](quint32 i) -> const JSClass & {
1005 return jsClassFromUnit(oldUnit, i);
1006 },
1007 oldUnit->jsClassTableSize },
1008 IndexedElements{ [this, jsClassFromUnit](quint32 i) -> const JSClass & {
1009 return jsClassFromUnit(newUnit, i);
1010 },
1011 newUnit->jsClassTableSize },
1012 [this](const JSClass &a, const JSClass &b) {
1013 return jsClassContentEqual(a, b);
1014 });
1015 }
1016
1017 compareIndexedElements<Block>(
1018 IndexedElements{
1019 [this](quint32 i) -> const Block & { return *oldUnit->blockAt(i); },
1020 oldUnit->blockTableSize },
1021 IndexedElements{
1022 [this](quint32 i) -> const Block & { return *newUnit->blockAt(i); },
1023 newUnit->blockTableSize },
1024 [this](const Block &a, const Block &b) { return blockContentEqual(a, b); });
1025
1026 return CompilationUnitDiff{ std::move(changes), true };
1027 }
1028};
1029
1030// NB: AddObject and RemoveObject are mutually exclusive since all objects are
1031// in a global order per compilation unit. The number of objects can either
1032// grow or shrink, but not both. Likewise AddBinding and RemoveBinding, but
1033// per object. Before adding bindings, all the objects need to be present.
1034// It's a good idea to remove stale bindings before they can cause any
1035// trouble. Therefore, we do that first, before changing or adding bindings.
1046
1047static Severity classifyChange(const Change &change)
1048{
1049 switch (change.type) {
1059 return Replace;
1078 return Rebuild;
1080 return AddObject;
1082 return RemoveBinding;
1084 return ChangeBinding;
1086 return AddBinding;
1088 return RemoveObject;
1107 return Ignore;
1136 break;
1137 }
1138 return Ignore;
1139}
1140
1141static void sortChanges(QSpan<Change> changes)
1142{
1143 std::stable_sort(changes.begin(), changes.end(), [](const Change &a, const Change &b) {
1144 return quint8(classifyChange(a)) < quint8(classifyChange(b));
1145 });
1146}
1147
1148CompilationUnitDiff diffCompilationUnits(const Unit *oldUnit, const Unit *newUnit)
1149{
1150 auto diff = UnitDiffer{ oldUnit, newUnit, {} }.diff();
1151
1152 // Sort the changes so that they are easy to apply.
1153 // We want the most severe changes first.
1154 sortChanges(diff.changes);
1155
1156 return diff;
1157}
1158
1159} // namespace QV4::CompiledData
1160
1161QT_END_NAMESPACE
static Severity classifyChange(const Change &change)
CompilationUnitDiff diffCompilationUnits(const Unit *oldUnit, const Unit *newUnit)
IndexedElements(AccessorFn, quint32) -> IndexedElements< AccessorFn >
static EnumHunk extractData(const Enum &e)
Data extractData(const Data &data)
static void sortChanges(QSpan< Change > changes)
Definition qjsvalue.h:24
#define COMPARISON_TRAITS(Element)
#define COMPARISON_TRAITS_WITH_LOCATION_AND_INDEX(Element)
#define COMPARISON_TRAITS_WITH_LOCATION(Element)
bool objectContentEqual(const Object &oldObj, const Object &newObj) const
void compareObjectProperties(const Object *oldObj, const Object *newObj)
bool parameterTypeContentEqual(const ParameterType &oldType, const ParameterType &newType) const
void compareNamedElements(OldSource oldSource, NewSource newSource, KeyFn keyFn, ContentEqFn contentEq)
bool aliasContentEqual(const Alias &oldAlias, const Alias &newAlias) const
QHash< const Function *, QString > functionOwnerKeys(const Unit *unit) const
void compareObjectInlineComponents(const Object *oldObj, const Object *newObj)
bool enumContentEqual(const Enum &oldEnum, const Enum &newEnum) const
bool stringsEqual(uint oldName, uint newName) const
void compareObjectBindings(const Object *oldObj, const Object *newObj)
bool blockContentEqual(const Block &oldBlock, const Block &newBlock) const
void compareObjectRequiredPropertyExtraData(const Object *oldObj, const Object *newObj)
bool jsClassContentEqual(const JSClass &oldJC, const JSClass &newJC) const
void compareObjectAliases(const Object *oldObj, const Object *newObj)
bool translationContentEqual(const TranslationData &oldTrans, const TranslationData &newTrans) const
bool signalContentEqual(const Signal &oldSig, const Signal &newSig) const
void compareObjectEnums(const Object *oldObj, const Object *newObj)
bool templateObjectContentEqual(const TemplateObject &oldTO, const TemplateObject &newTO) const
bool propertyContentEqual(const Property &oldProp, const Property &newProp) const
bool functionContentEqual(const Function &oldFunc, const Function &newFunc) const
bool classContentEqual(const Class &oldCls, const Class &newCls) const
void compareObjectSignals(const Object *oldObj, const Object *newObj)
void compareIndexedElements(OldSource oldSource, NewSource newSource, ContentEqFn contentEq)
bool bindingContentEqual(const Binding &oldBinding, const Binding &newBinding) const