-
Notifications
You must be signed in to change notification settings - Fork 281
/
variableStore.ts
1469 lines (1271 loc) · 43.7 KB
/
variableStore.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
import * as l10n from '@vscode/l10n';
import { generate } from 'astring';
import { inject, injectable } from 'inversify';
import Cdp from '../cdp/api';
import { ICdpApi } from '../cdp/connection';
import { flatten, isInstanceOf, once } from '../common/objUtils';
import { parseSource, statementsToFunction } from '../common/sourceCodeManipulations';
import { IRenameProvider } from '../common/sourceMaps/renameProvider';
import { AnyLaunchConfiguration } from '../configuration';
import Dap from '../dap/api';
import { IDapApi } from '../dap/connection';
import * as errors from '../dap/errors';
import { ProtocolError } from '../dap/protocolError';
import { IWasmVariable, IWasmVariableEvaluation, WasmScope } from './dwarf/wasmSymbolProvider';
import * as objectPreview from './objectPreview';
import { MapPreview, SetPreview } from './objectPreview/betterTypes';
import { PreviewContextType } from './objectPreview/contexts';
import { StackFrame, StackTrace } from './stackTrace';
import { RemoteException, RemoteObjectId, getSourceSuffix } from './templates';
import { getArrayProperties } from './templates/getArrayProperties';
import { getArraySlots } from './templates/getArraySlots';
import {
getDescriptionSymbols,
getStringyProps,
getToStringIfCustom,
} from './templates/getStringyProps';
import { invokeGetter } from './templates/invokeGetter';
import { readMemory } from './templates/readMemory';
import { writeMemory } from './templates/writeMemory';
const getVariableId = (() => {
let last = 0;
const max = 0x7fffffff - 1;
return () => (last++ % max) + 1;
})();
const toCallArgument = (value: string | Cdp.Runtime.RemoteObject) => {
if (typeof value === 'string') {
return { value };
}
const object = value as Cdp.Runtime.RemoteObject;
if (object.objectId) {
return { objectId: object.objectId };
}
if (object.unserializableValue) {
return { unserializableValue: object.unserializableValue };
}
return { value: object.value };
};
// Types that allow readMemory and writeMemory
const memoryReadableTypes: ReadonlySet<Cdp.Runtime.RemoteObject['subtype']> = new Set([
'typedarray',
'dataview',
'arraybuffer',
'webassemblymemory',
]);
export interface IVariableStoreLocationProvider {
renderDebuggerLocation(location: Cdp.Debugger.Location): Promise<string>;
}
export interface IScopeRef {
stackFrame: StackFrame;
callFrameId: Cdp.Debugger.CallFrameId;
scopeNumber: number;
}
const enum SortOrder {
Error = -1,
Default = 0,
Private = 1,
Internal = 2,
}
const customStringReprMaxLength = 1024;
const identifierRe = /^[$a-z_][0-9a-z_$]*$/i;
const privatePropertyRe = /^#[0-9a-z_$]+$/i;
type AnyPropertyDescriptor = Cdp.Runtime.PropertyDescriptor | Cdp.Runtime.PrivatePropertyDescriptor;
const isPublicDescriptor = (p: AnyPropertyDescriptor): p is Cdp.Runtime.PropertyDescriptor =>
p.hasOwnProperty('configurable');
const extractFunctionFromCustomGenerator = (
parameterNames: string[],
generatorDefinition: string,
catchAndReturnErrors: boolean,
) => {
const code = statementsToFunction(
parameterNames,
parseSource(generatorDefinition),
catchAndReturnErrors,
);
return generate(code);
};
const indescribablePrefix = '<<indescribable>>';
const localizeIndescribable = (str: string) => {
if (!str.startsWith(indescribablePrefix)) {
return str;
}
let error;
let key;
try {
[error, key] = JSON.parse(str.slice(indescribablePrefix.length));
} catch {
return str;
}
return l10n.t("{0} (couldn't describe: {1})", error, key);
};
/**
* A "variable container" is a type that can be referenced in the DAP
* `variables` request and may be capable of holding nested variables.
* Specifically, this is implemented by both variables and scopes.
*/
export interface IVariableContainer {
/**
* An ID is assigned to _all_ variables. For variables that can be expanded,
* this is also their variablesReference returned from `toDap()`.
*/
readonly id: number;
getChildren(params: Dap.VariablesParams): Promise<IVariable[]>;
}
/**
* A variable container who also has a `Dap.Variable` representation.
*/
export interface IVariable extends IVariableContainer {
readonly sortOrder: number;
toDap(context: PreviewContextType, valueFormat?: Dap.ValueFormat): Promise<Dap.Variable>;
}
interface IMemoryReadable {
readMemory(offset: number, count: number): Promise<Buffer | undefined>;
writeMemory(offset: number, memory: Buffer): Promise<number>;
}
const isMemoryReadable = (t: unknown): t is IMemoryReadable =>
!!t && typeof t === 'object' && 'readMemory' in t && 'writeMemory' in t;
/**
* Configuration for the VariableStore. See the launch configuration docs
* for details on these.
*/
export interface IStoreSettings {
customDescriptionGenerator?: string;
customPropertiesGenerator?: string;
}
type VariableCtor<TRestArgs extends unknown[] = unknown[], R extends IVariable = IVariable> = {
new (context: VariableContext, ...rest: TRestArgs): R;
};
interface IContextInit {
name: string;
presentationHint?: Dap.VariablePresentationHint;
/** How this variable should be sorted in results, in ascending numeric order. */
sortOrder?: number;
}
interface IContextSettings {
customDescriptionGenerator?: string;
customPropertiesGenerator?: string;
descriptionSymbols?: Promise<Cdp.Runtime.CallArgument>;
}
const wasmScopeNames: { [K in WasmScope]: { name: string; sortOrder: number } } = {
[WasmScope.Parameter]: { name: l10n.t('Parameters'), sortOrder: -10 },
[WasmScope.Local]: { name: l10n.t('Locals'), sortOrder: -9 },
[WasmScope.Global]: { name: l10n.t('Globals'), sortOrder: -8 },
};
class VariableContext {
/** When in a Variable, the name that this variable is accessible as from its parent scope or object */
public readonly name: string;
/** PresenationHint for this variable when displayed as a child of its parent/ */
public readonly presentationHint?: Dap.VariablePresentationHint;
/** Sort order set from the parent. */
public readonly sortOrder: number;
public get customDescriptionGenerator() {
return this.settings.customDescriptionGenerator;
}
constructor(
public readonly cdp: Cdp.Api,
public readonly parent: undefined | IVariable | Scope,
ctx: IContextInit,
private readonly vars: VariablesMap,
public readonly locationProvider: IVariableStoreLocationProvider,
private readonly currentRef: undefined | (() => IVariable | Scope),
private readonly settings: IContextSettings,
) {
this.name = ctx.name;
this.presentationHint = ctx.presentationHint;
this.sortOrder = ctx.sortOrder || SortOrder.Default;
}
/**
* Creates and tracks a new Variable type.
*/
public createVariable<T extends VariableCtor<[]>>(ctor: T, ctx: IContextInit): InstanceType<T>;
public createVariable<A, T extends VariableCtor<[A]>>(
ctor: T,
ctx: IContextInit,
a: A,
): InstanceType<T>;
public createVariable<A, B, T extends VariableCtor<[A, B]>>(
ctor: T,
ctx: IContextInit,
a: A,
b: B,
): InstanceType<T>;
public createVariable<A, B, C, T extends VariableCtor<[A, B, C]>>(
ctor: T,
ctx: IContextInit,
a: A,
b: B,
c: C,
): InstanceType<T>;
public createVariable<T extends VariableCtor>(
ctor: T,
ctx: IContextInit,
...rest: T extends VariableCtor<infer U> ? U : never
): InstanceType<T> {
const v = new ctor(
new VariableContext(
this.cdp,
this.currentRef?.(),
ctx,
this.vars,
this.locationProvider,
() => v,
this.settings,
),
...rest,
) as InstanceType<T>;
if (v.id > 0) {
this.vars.add(v);
}
return v;
}
public createVariableByType(
ctx: IContextInit,
object: Cdp.Runtime.RemoteObject,
customStringRepr?: string,
) {
if (objectPreview.isArray(object)) {
return this.createVariable(ArrayVariable, ctx, object);
}
if (object.objectId) {
if (object.subtype === 'map' || object.subtype === 'set') {
return this.createVariable(SetOrMapVariable, ctx, object, customStringRepr);
} else if (!objectPreview.subtypesWithoutPreview.has(object.subtype)) {
return this.createVariable(ObjectVariable, ctx, object, customStringRepr);
}
}
return this.createVariable(Variable, ctx, object);
}
/**
* Ensures symbols for custom descriptions are available, must be used
* before getStringProps/getToStringIfCustom
*/
public async getDescriptionSymbols(objectId: string): Promise<Cdp.Runtime.CallArgument> {
this.settings.descriptionSymbols ??= getDescriptionSymbols({
cdp: this.cdp,
args: [],
objectId,
}).then(
r => ({ objectId: r.objectId }),
() => ({ value: [] }),
);
return await this.settings.descriptionSymbols;
}
/**
* Creates Variables for each property on the RemoteObject.
*/
public async createObjectPropertyVars(
object: Cdp.Runtime.RemoteObject,
evaluationOptions?: Dap.EvaluationOptions,
): Promise<Variable[]> {
const properties: (Promise<Variable[]> | Variable[])[] = [];
if (this.settings.customPropertiesGenerator) {
const { result, errorDescription } = await this.evaluateCodeForObject(
object,
this.settings.customPropertiesGenerator,
[],
);
if (result && result.type !== 'undefined') {
object = result;
} else {
properties.push([
this.createVariable(
ErrorVariable,
{ name: '', sortOrder: SortOrder.Error },
result as Cdp.Runtime.RemoteObject,
result?.description || errorDescription || l10n.t('Unknown error'),
),
]);
}
}
if (!object.objectId) {
return [];
}
if (evaluationOptions)
this.cdp.DotnetDebugger.setEvaluationOptions({
options: evaluationOptions,
type: 'variable',
});
const [accessorsProperties, ownProperties, stringyProps] = await Promise.all([
this.cdp.Runtime.getProperties({
objectId: object.objectId,
accessorPropertiesOnly: true,
ownProperties: false,
generatePreview: true,
}),
this.cdp.Runtime.getProperties({
objectId: object.objectId,
ownProperties: true,
generatePreview: true,
}),
this.cdp.Runtime.callFunctionOn({
functionDeclaration: getStringyProps.decl(
`${customStringReprMaxLength}`,
this.settings.customDescriptionGenerator || 'null',
),
arguments: [await this.getDescriptionSymbols(object.objectId)],
objectId: object.objectId,
throwOnSideEffect: true,
returnByValue: true,
})
.then(r => r?.result.value || {})
.catch(() => ({} as Record<string, string>)),
]);
if (!accessorsProperties || !ownProperties) return [];
// Merge own properties and all accessors.
const propertiesMap = new Map<string, AnyPropertyDescriptor>();
const propertySymbols: AnyPropertyDescriptor[] = [];
for (const property of accessorsProperties.result) {
if (property.symbol) {
propertySymbols.push(property);
continue;
}
// Handle updated prototype representation in recent V8 (vscode#130365)
if (
property.name === '__proto__' &&
ownProperties.internalProperties?.some(p => p.name === '[[Prototype]]')
) {
continue;
}
propertiesMap.set(property.name, property);
}
for (const property of ownProperties.result) {
if (property.get || property.set) continue;
if (property.symbol) propertySymbols.push(property);
else propertiesMap.set(property.name, property);
}
// Push own properties & accessors and symbols
for (const propertiesCollection of [propertiesMap.values(), propertySymbols.values()]) {
for (const p of propertiesCollection) {
properties.push(
this.createPropertyVar(
p,
object,
stringyProps?.hasOwnProperty(p.name)
? localizeIndescribable(stringyProps[p.name])
: undefined,
),
);
}
}
for (const property of ownProperties.privateProperties ?? []) {
properties.push(
this.createPropertyVar(property, object, undefined, {
presentationHint: { visibility: 'private' },
sortOrder: SortOrder.Private,
}),
);
}
// Push internal properties
for (const p of ownProperties.internalProperties || []) {
if (p.name === '[[StableObjectId]]') {
continue;
}
let variable: Variable | undefined;
if (
p.name === '[[FunctionLocation]]' &&
p.value &&
(p.value.subtype as string) === 'internal#location'
) {
variable = this.createVariable(
FunctionLocationVariable,
{
name: p.name,
presentationHint: { visibility: 'internal', attributes: ['readOnly'] },
sortOrder: SortOrder.Internal,
},
p.value,
);
} else if (p.value !== undefined) {
variable = this.createVariableByType(
{
name: p.name,
presentationHint: { visibility: 'internal' },
sortOrder: SortOrder.Internal,
},
p.value,
);
}
if (variable) {
properties.push([variable]);
}
}
return flatten(await Promise.all(properties));
}
private async createPropertyVar(
p: AnyPropertyDescriptor,
owner: Cdp.Runtime.RemoteObject,
customStringRepr: string | undefined,
contextInit?: Partial<IContextInit>,
): Promise<Variable[]> {
const result: Variable[] = [];
const hasGetter = p.get && p.get.type !== 'undefined';
const hasSetter = p.set && p.set.type !== 'undefined';
const ctx: Required<IContextInit> = {
name: p.name,
presentationHint: {},
sortOrder: SortOrder.Default,
...contextInit,
};
if (!contextInit) {
if (isPublicDescriptor(p)) {
// sort non-enumerable properties as private, except for getters, which
// are automatically non-enumerable but not (automatically) considered private (#1215)
if (p.enumerable === false && !hasGetter) {
ctx.presentationHint.visibility = 'internal';
ctx.sortOrder = SortOrder.Private;
}
if (p.writable === false || (hasGetter && !hasSetter)) {
ctx.presentationHint.attributes = ['readOnly'];
}
} else {
ctx.presentationHint.visibility = 'private';
ctx.sortOrder = SortOrder.Private;
}
}
// If the value is simply present, add that
if ('value' in p && p.value) {
result.push(this.createVariableByType(ctx, p.value, customStringRepr));
}
// if it's a getter, auto expand as requested
if (hasGetter) {
result.push(
this.createVariable(GetterVariable, ctx, p.get as Cdp.Runtime.RemoteObject, owner),
);
} else if (hasSetter) {
result.push(this.createVariable(SetterOnlyVariable, ctx, p.set as Cdp.Runtime.RemoteObject));
}
return result;
}
private async evaluateCodeForObject(
object: Cdp.Runtime.RemoteObject,
functionDeclaration: string,
argumentsToEvaluateWith: string[],
): Promise<{ result?: Cdp.Runtime.RemoteObject; errorDescription?: string }> {
try {
const customValueDescription = await this.cdp.Runtime.callFunctionOn({
objectId: object.objectId,
functionDeclaration,
arguments: argumentsToEvaluateWith.map(toCallArgument),
});
if (customValueDescription) {
if (customValueDescription.exceptionDetails === undefined) {
return { result: customValueDescription.result };
} else if (customValueDescription && customValueDescription.result.description) {
return { errorDescription: customValueDescription.result.description };
}
}
return { errorDescription: l10n.t('Unknown error') };
} catch (e) {
return { errorDescription: e.stack || e.message || String(e) };
}
}
}
const isNumberOrNumeric = (s: string | number) => typeof s === 'number' || /^[0-9]+$/.test(s);
class Variable implements IVariable {
public id = getVariableId();
/** Gets the variable name in its parent scope or object. */
public get name() {
return this.context.name;
}
/** Gets the presentation hint set by the parent. */
public get sortOrder() {
return this.context.sortOrder;
}
constructor(
protected readonly context: VariableContext,
protected readonly remoteObject: Cdp.Runtime.RemoteObject,
) {}
/**
* Gets the accessor though which this object can be read.
*/
public get accessor(): string {
const { parent, name } = this.context;
if (parent instanceof AccessorVariable) {
return parent.accessor;
}
if (!(parent instanceof Variable)) {
return this.context.name;
}
// Maps and sets:
const grandparent = parent.context.parent;
if (grandparent instanceof Variable) {
if ((this.remoteObject.subtype as string) === 'internal#entry') {
return `[...${grandparent.accessor}.entries()][${+name}]`;
}
if ((parent.remoteObject.subtype as string) === 'internal#entry') {
return `${parent.accessor}[${this.name === 'key' ? 0 : 1}]`;
}
}
if (isNumberOrNumeric(name)) {
return `${parent.accessor}[${name}]`;
}
// If the object property looks like a valid identifer, don't use the
// bracket syntax -- it's ugly!
if (identifierRe.test(name)) {
return `${parent.accessor}.${name}`;
}
if (parent.accessor === 'this' && privatePropertyRe.test(name)) {
return `${parent.accessor}.${name}`;
}
return `${parent.accessor}[${JSON.stringify(name)}]`;
}
/** @inheritdoc */
public async toDap(
previewContext: PreviewContextType,
valueFormat?: Dap.ValueFormat,
): Promise<Dap.Variable> {
let name = this.context.name;
if (this.context.parent instanceof Scope) {
name = await this.context.parent.getRename(name);
}
return Promise.resolve({
name,
value: objectPreview.previewRemoteObject(this.remoteObject, previewContext, valueFormat),
evaluateName: this.accessor,
type: this.remoteObject.type,
variablesReference: 0,
presentationHint: this.context.presentationHint,
});
}
/** Sets a property of the variable variable. */
public async setProperty(name: string, expression: string): Promise<Variable> {
const result = await this.context.cdp.Runtime.callFunctionOn({
objectId: this.remoteObject.objectId,
functionDeclaration: `function(a) { return this[a] = ${expression}; ${getSourceSuffix()} }`,
arguments: [toCallArgument(name)],
silent: true,
});
if (!result) {
throw new ProtocolError(errors.createSilentError(l10n.t('Unable to set variable value')));
}
if (result.exceptionDetails) {
throw new ProtocolError(errorFromException(result.exceptionDetails));
}
return this.context.createVariableByType({ name }, result.result);
}
public async getChildren(_params: Dap.VariablesParams): Promise<Variable[]> {
return Promise.resolve([]);
}
}
class OutputVariableContainer implements IVariableContainer {
public readonly id = getVariableId();
constructor(private readonly child: Variable) {}
public getChildren(): Promise<IVariable[]> {
return Promise.resolve([this.child]);
}
}
class OutputVariable extends Variable {
constructor(
context: VariableContext,
private readonly value: string,
private readonly args: ReadonlyArray<Cdp.Runtime.RemoteObject>,
private readonly stackTrace: StackTrace | undefined,
) {
super(context, { type: args[0]?.type ?? 'string' });
}
public override toDap(): Promise<Dap.Variable> {
return Promise.resolve({
name: this.context.name,
value: this.value,
variablesReference:
this.stackTrace || this.args.some(objectPreview.previewAsObject) ? this.id : 0,
});
}
public override getChildren(_params: Dap.VariablesParams): Promise<Variable[]> {
const vars: Variable[] = [];
const { args, stackTrace } = this;
for (let i = 0; i < args.length; ++i) {
if (objectPreview.previewAsObject(args[i])) {
vars.push(this.context.createVariableByType({ name: `arg${i}`, sortOrder: i }, args[i]));
}
}
if (stackTrace) {
vars.push(
this.context.createVariable(
StacktraceOutputVariable,
{ name: '', sortOrder: Number.MAX_SAFE_INTEGER },
this.remoteObject,
stackTrace,
),
);
}
return Promise.resolve(vars);
}
}
class StacktraceOutputVariable extends Variable {
constructor(
context: VariableContext,
remoteObject: Cdp.Runtime.RemoteObject,
private readonly stacktrace: StackTrace,
) {
super(context, remoteObject);
}
public override async toDap(): Promise<Dap.Variable> {
return {
name: '',
value: await this.stacktrace.format(),
variablesReference: 0,
};
}
}
class FunctionLocationVariable extends Variable {
private readonly location: Cdp.Debugger.Location;
constructor(context: VariableContext, remoteObject: Cdp.Runtime.RemoteObject) {
super(context, remoteObject);
this.location = remoteObject.value;
}
public override async toDap(): Promise<Dap.Variable> {
return {
name: this.context.name,
value: await this.context.locationProvider.renderDebuggerLocation(this.location),
variablesReference: 0,
presentationHint: { visibility: 'internal' },
};
}
}
class ErrorVariable extends Variable {
public override get accessor(): string {
if (!(this.context.parent instanceof Variable)) {
throw new Error('ErrorVariable must have a parent Variable');
}
return this.context.parent.accessor;
}
constructor(
context: VariableContext,
remoteObject: Cdp.Runtime.RemoteObject,
private readonly message: string,
) {
super(context, remoteObject);
}
public override toDap(): Promise<Dap.Variable> {
return Promise.resolve({
name: this.context.name,
value: this.message,
variablesReference: 0,
});
}
}
const NoCustomStringRepr = Symbol('NoStringRepr');
class ObjectVariable extends Variable implements IMemoryReadable {
constructor(
context: VariableContext,
remoteObject: Cdp.Runtime.RemoteObject,
private customStringRepr?: string | typeof NoCustomStringRepr,
) {
super(context, remoteObject);
}
public override async toDap(
previewContext: PreviewContextType,
valueFormat?: Dap.ValueFormat,
): Promise<Dap.Variable> {
const [parentDap, value] = await Promise.all([
await super.toDap(previewContext, valueFormat),
await this.getValueRepresentation(previewContext),
]);
return {
...parentDap,
type: this.remoteObject.className || this.remoteObject.subtype || this.remoteObject.type,
variablesReference: this.id,
memoryReference: memoryReadableTypes.has(this.remoteObject.subtype)
? String(this.id)
: undefined,
value,
};
}
private async getValueRepresentation(previewContext: PreviewContextType) {
if (typeof this.customStringRepr === 'string') {
return this.customStringRepr;
}
// for the first level of evaluations, toString it on-demand
if (
!this.context.parent &&
this.remoteObject.objectId &&
this.customStringRepr !== NoCustomStringRepr
) {
try {
const ret = await this.context.cdp.Runtime.callFunctionOn({
functionDeclaration: getToStringIfCustom.decl(
`${customStringReprMaxLength}`,
this.context.customDescriptionGenerator || 'null',
),
objectId: this.remoteObject.objectId,
returnByValue: true,
});
if (ret?.result.value) {
return (this.customStringRepr = localizeIndescribable(ret.result.value));
}
} catch (e) {
this.customStringRepr = NoCustomStringRepr;
// ignored
}
}
return (
(this.context.name === '__proto__' && this.remoteObject.description) ||
objectPreview.previewRemoteObject(this.remoteObject, previewContext)
);
}
/** @inheritdoc */
public async readMemory(offset: number, count: number): Promise<Buffer | undefined> {
const result = await readMemory({
cdp: this.context.cdp,
args: [offset, count],
objectId: this.remoteObject.objectId,
returnByValue: true,
});
return Buffer.from(result.value, 'hex');
}
/** @inheritdoc */
public async writeMemory(offset: number, memory: Buffer): Promise<number> {
const result = await writeMemory({
cdp: this.context.cdp,
args: [offset, memory.toString('hex')],
objectId: this.remoteObject.objectId,
returnByValue: true,
});
return result.value;
}
public override getChildren(_params: Dap.VariablesParamsExtended) {
return this.context.createObjectPropertyVars(this.remoteObject, _params.evaluationOptions);
}
}
const entriesVariableName = '[[Entries]]';
class SetOrMapVariable extends ObjectVariable {
private readonly size?: number;
public readonly isMap: boolean;
private readonly baseChildren = once(() => super.getChildren({ variablesReference: this.id }));
constructor(context: VariableContext, remoteObject: Cdp.Runtime.RemoteObject) {
super(context, remoteObject, NoCustomStringRepr);
this.isMap = remoteObject.subtype === 'map';
const cast = remoteObject.preview as MapPreview | SetPreview | undefined;
this.size = Number(cast?.properties.find(p => p.name === 'size')?.value) ?? undefined;
}
public override async toDap(previewContext: PreviewContextType): Promise<Dap.Variable> {
const dap = await super.toDap(previewContext);
if (this.size && this.size > 100) {
dap.indexedVariables = this.size;
}
return dap;
}
public override async getChildren(params: Dap.VariablesParams): Promise<Variable[]> {
const baseChildren = await this.baseChildren();
const entryChildren = await baseChildren
.find(c => c.name === entriesVariableName)
?.getChildren(params);
return [
// filter to only show the actualy entries, not the array prototype/length
...(entryChildren || []).filter(v => v.sortOrder === SortOrder.Default),
...baseChildren.filter(c => c.name !== entriesVariableName),
];
}
}
class ArrayVariable extends ObjectVariable {
private length = 0;
constructor(context: VariableContext, remoteObject: Cdp.Runtime.RemoteObject) {
super(context, remoteObject, NoCustomStringRepr);
const match = String(remoteObject.description).match(/\(([0-9]+)\)/);
this.length = match ? +match[1] : 0;
}
public override async toDap(previewContext: PreviewContextType): Promise<Dap.Variable> {
return {
...(await super.toDap(previewContext)),
indexedVariables: this.length > 100 ? this.length : undefined,
namedVariables: this.length > 100 ? 1 : undefined, // do not count properties proactively
};
}
public override async getChildren(params: Dap.VariablesParams): Promise<Variable[]> {
switch (params?.filter) {
case 'indexed':
return this.getArraySlots(params);
case 'named':
return this.getArrayProperties();
default:
return Promise.all([this.getArrayProperties(), this.getArraySlots()]).then(flatten);
}
}
private async getArrayProperties(): Promise<Variable[]> {
try {
const object = await getArrayProperties({
cdp: this.context.cdp,
args: [],
objectId: this.remoteObject.objectId,
generatePreview: true,
});
return this.context.createObjectPropertyVars(object);
} catch (e) {
return [];
}
}
private async getArraySlots(params?: Dap.VariablesParams): Promise<Variable[]> {
const start = params && typeof params.start !== 'undefined' ? params.start : -1;
const count = params && typeof params.count !== 'undefined' ? params.count : -1;
let slotsObject: Cdp.Runtime.RemoteObject;
try {
slotsObject = await getArraySlots({
cdp: this.context.cdp,
generatePreview: false,
args: [start, count],
objectId: this.remoteObject.objectId,
});
} catch (e) {
return [];
}
const result = await this.context.createObjectPropertyVars(slotsObject);
if (slotsObject.objectId) {
await this.context.cdp.Runtime.releaseObject({ objectId: slotsObject.objectId });
}
return result;
}
}
class OutputTableVariable extends ArrayVariable {
public override async toDap(previewContext: PreviewContextType): Promise<Dap.Variable> {
if (!this.remoteObject.preview) {
return super.toDap(previewContext);
}
return {
...(await super.toDap(previewContext)),
name: objectPreview.formatAsTable(this.remoteObject.preview),
};
}
}
abstract class AccessorVariable extends Variable {
constructor(context: VariableContext, remoteObject: Cdp.Runtime.RemoteObject) {
super(context, remoteObject);
}
public override getChildren(_params: Dap.VariablesParams) {
return this.context.createObjectPropertyVars(this.remoteObject);
}
}
class SetterOnlyVariable extends AccessorVariable {
public override async toDap(
previewContext: PreviewContextType,
valueFormat?: Dap.ValueFormat,
): Promise<Dap.Variable> {
return {
...(await super.toDap(previewContext, valueFormat)),
value: 'write-only',
variablesReference: this.id,
};
}
}
class GetterVariable extends AccessorVariable {
constructor(
context: VariableContext,
remoteObject: Cdp.Runtime.RemoteObject,
private readonly parentObject: Cdp.Runtime.RemoteObject,
) {
super(context, remoteObject);
}
public override async toDap(
previewContext: PreviewContextType,
valueFormat?: Dap.ValueFormat,
): Promise<Dap.Variable> {