All files execute.js

95.79% Statements 205/214
85.6% Branches 107/125
100% Functions 13/13
95.79% Lines 205/214

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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    1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x     972x 1138x         972x 972x 972x     972x 376x       972x 166x   972x 972x 972x                   972x 972x 249x 249x 249x 31x 31x               972x 972x                         373x 373x 373x 1881x 1881x 805x   1076x     1076x 1076x     1076x 2584x 1076x   1508x     373x           68351x 1271x   68351x       60607x 59602x   60607x 60607x 60607x                   7239x                         3582x   3582x 5x   3577x 3577x 373x 373x     373x 373x 5x           3572x                                                 3716x 3716x       3716x 68x 68x     3648x 3582x           3582x 3582x   3582x 10x 3572x 3572x         3572x 3572x 368x 368x 368x   368x 1x                     3716x 3650x   3716x                             2701x 2701x   2701x 2x   2699x   2699x 2699x       2699x       2699x 2699x 2699x 2699x 2699x 3859x 3859x     3859x 3859x   3859x     3859x 3859x 3859x 7x 7x     3859x   3859x 4x   3855x 3855x 3855x       2699x 4x     2699x                               243x   243x             243x   231x 231x 231x   231x 1x             12x               242x                                     7744x 7744x   5274x       2470x 2470x 3594x 5x               3589x         2465x   2465x     2465x 2465x   2465x     2465x 2465x   2465x 2465x     2465x 7383x 2465x     2465x 6x       2459x     2459x 1x                 2458x 2457x   2458x 2458x   2458x                   2458x 2458x   2419x 2419x 3535x 3535x             2419x 3528x 9x   3519x         2449x 2449x 2449x 2449x     2449x 35x       2449x 243x   2449x       17250x 9648x   7602x 17141x 17141x 17141x 7493x   17141x 6x                 6x 5x 5x 5x   5x 5x       5x       17141x                                   1x     7744x 7744x     7744x 7744x 109x   7744x     1x  
'use strict';
 
const { ArgumentState } = require( './argumentState.js' );
const { BaseFrame, EmptyFrame } = require( './frame.js' );
const { Composition, Implementation } = require( './implementation.js' );
const { RandomImplementationSelector } = require( './implementationSelector.js' );
const { containsError, containsValue, createZObjectKey, isRefOrString, makeWrappedResultEnvelope, quoteZObject, returnOnFirstError } = require( './utils.js' );
const { MutationType, ZWrapper } = require( './ZWrapper' );
const { resolveListType } = require( './builtins.js' );
const { error, normalError } = require( '../function-schemata/javascript/src/error.js' );
const { convertZListToItemArray, getError } = require( '../function-schemata/javascript/src/utils.js' );
const { validatesAsArgumentReference, validatesAsType } = require( '../function-schemata/javascript/src/schema.js' );
 
let execute = null;
 
async function validateAsType( Z1, invariants, scope, typeZObject = null ) {
	const wrapInZ9 = ( ZID ) => {
		return ZWrapper.create( {
			Z1K1: 'Z9',
			Z9K1: ZID
		} );
	};
	const genericSchemaValidatorZID = 'Z831';
	const genericValidatorZ8Reference = wrapInZ9( genericSchemaValidatorZID );
	const genericValidatorZ8 = ( await ( genericValidatorZ8Reference.resolve(
		invariants, scope ) ) ).Z22K1;
 
	if ( typeZObject === null ) {
		typeZObject = Z1.Z1K1;
	}
	// TODO (T292787): Make this more elegant--should be possible to avoid
	// passing strings in the first place.
	if ( typeof typeZObject === 'string' || typeZObject instanceof String ) {
		typeZObject = wrapInZ9( typeZObject );
	}
	const { runValidationFunction } = require( './validation.js' );
	const callTuples = [];
	callTuples.push(
		[
			runValidationFunction,
			[
				genericValidatorZ8, invariants, scope,
				quoteZObject( Z1 ), quoteZObject( typeZObject ) ],
			'runValidationFunction' ] );
	// TODO (T301532): Find a more reliable way to signal that no additional
	// validation needs to be run. Here we just make sure that we won't run the
	// same function twice by comparing Z8K5 references.
	const resolvedType = ( await ( typeZObject.resolve( invariants, scope ) ) ).Z22K1;
	if ( ( await validatesAsType( resolvedType.asJSON() ) ).isValid() ) {
		await ( resolvedType.resolveKey( [ 'Z4K3' ], invariants, scope ) );
		const validatorZ8 = resolvedType.Z4K3;
		if ( validatorZ8.Z8K5.Z9K1 !== genericValidatorZ8.Z8K5.Z9K1 ) {
			const { runTypeValidatorDynamic } = require( './validation.js' );
			callTuples.push(
				[
					runTypeValidatorDynamic,
					[ Z1, typeZObject, invariants, scope ],
					'runTypeValidator' ] );
		}
	}
 
	const Z22 = makeWrappedResultEnvelope( Z1, null );
	return await returnOnFirstError( Z22, callTuples, /* callback= */null, /* addZ22= */false );
}
 
/**
 * Traverses a ZObject and resolves all Z1K1s.
 *
 * @param {Object} Z1 object whose Z1K1s are to be resolved
 * @param {Invariants} invariants evaluator, resolver: invariants preserved over all function calls
 * @param {Frame} scope current variable bindings
 * @param {boolean} doValidate whether to validate types of arguments and return values
 * @return {ArgumentState|null} error state or null if no error encountered
 */
async function resolveTypes( Z1, invariants, scope, doValidate = true ) {
	Z1 = ZWrapper.create( Z1 );
	const objectQueue = [ Z1 ];
	while ( objectQueue.length > 0 ) {
		const nextObject = objectQueue.shift();
		if ( await isRefOrString( nextObject ) ) {
			continue;
		}
		await ( nextObject.resolveKey(
			[ 'Z1K1' ], invariants, scope, /* ignoreList= */ null,
			/* resolveInternals= */ false, doValidate ) );
		const typeEnvelope = nextObject.Z1K1;
		Iif ( containsError( typeEnvelope ) ) {
			return ArgumentState.ERROR( getError( typeEnvelope ) );
		}
		for ( const key of nextObject.keys() ) {
			if ( key === 'Z1K1' ) {
				continue;
			}
			objectQueue.push( nextObject[ key ] );
		}
	}
	return null;
}
 
class Frame extends BaseFrame {
 
	constructor( lastFrame = null ) {
		if ( lastFrame === null ) {
			lastFrame = new EmptyFrame();
		}
		super( lastFrame );
	}
 
	copy( lastFrame = null ) {
		if ( lastFrame === null ) {
			lastFrame = this.lastFrame_.copy();
		}
		const result = new Frame( lastFrame );
		result.names_ = new Map( this.names_ );
		return result;
	}
 
	/**
	 * Add new name and argument to this frame.
	 *
	 * @param {string} name
	 * @param {ArgumentState} argumentState an ArgumentState, what else?
	 */
	setArgument( name, argumentState ) {
		this.names_.set( name, argumentState );
	}
 
	async processArgument(
		argumentDict, invariants, doValidate, resolveInternals,
		ignoreList ) {
		// TODO (T296675): "doValidate" is a heavy-handed hack to avoid infinite
		// recursion. Better solutions include
		//  -   validating directly with schemata if the type is built-in,
		//      otherwise using a Function;
		//  -   validating directly with schemata in all the cases where
		//      doValidate is currently false, otherwise using a Function;
		//  -   caching and reusing the results of function calls
		const argumentEnvelope = await ( argumentDict.argument.resolve(
			invariants, this.lastFrame_, ignoreList, resolveInternals, doValidate ) );
		if ( containsError( argumentEnvelope ) ) {
			return ArgumentState.ERROR( getError( argumentEnvelope ) );
		}
		const argument = ZWrapper.create( argumentEnvelope.Z22K1 );
		if ( doValidate && resolveInternals ) {
			const typeError = await resolveTypes( argument, invariants, this.lastFrame_ );
			Iif ( typeError !== null ) {
				return typeError;
			}
			const actualResult = await validateAsType( argument, invariants, this.lastFrame_ );
			if ( containsError( actualResult ) ) {
				return ArgumentState.ERROR(
					normalError(
						[ error.object_type_mismatch ],
						[ argument.Z1K1, argument, getError( actualResult ) ] ) );
			}
		}
		return ArgumentState.EVALUATED( {
			name: argumentDict.name,
			argument: argument
		} );
	}
 
	/**
	 * Ascend enclosing scopes to find instantiation of argument with provided name.
	 *
	 * @param {string} argumentName
	 * @param {Invariants} invariants evaluator, resolver: invariants preserved
	 *      over all function calls
	 * @param {boolean} lazily
	 * @param {boolean} doValidate if false, then the argument will be executed
	 *      without validating return type (if it's a Z7)
	 * @param {boolean} resolveInternals if false, will evaluate typed lists via shortcut
	 *      and will not validate attributes of Z7s
	 * @param {Set(MutationType)} ignoreList which types of mutations to ignore
	 *      when resolving function calls and references
	 * @return {Object} argument instantiated with given name in lowest enclosing scope
	 * along with enclosing scope
	 */
	async retrieveArgument(
		argumentName, invariants, lazily = false,
		doValidate = true, resolveInternals = true, ignoreList = null ) {
		let boundValue = this.names_.get( argumentName );
		let doSetBoundValue = false;
 
		// Name does not exist in this scope; look in the previous one
		// (or return null if no previous scope).
		if ( boundValue === undefined ) {
			doSetBoundValue = true;
			boundValue = await this.lastFrame_.retrieveArgument(
				argumentName, invariants, lazily, doValidate,
				resolveInternals, ignoreList );
		} else if ( boundValue.state === 'UNEVALUATED' && !lazily ) {
			doSetBoundValue = true;
			// If boundValue is in the ERROR or EVALUATED state, it has already
			// been evaluated and can be returned directly.
			// If state is UNEVALUATED and evaluation is not lazy, the argument
			// may need to be evaluated before returning (e.g., if a Z9, Z18,
			// or Z7).
			const argumentDict = boundValue.argumentDict;
			const evaluatedArgument = await this.processArgument(
				argumentDict, invariants, doValidate, resolveInternals, ignoreList );
			if ( evaluatedArgument.state === 'ERROR' ) {
				boundValue = evaluatedArgument;
			} else Eif ( evaluatedArgument.state === 'EVALUATED' ) {
				const newDict = {
					name: argumentName,
					argument: evaluatedArgument.argumentDict.argument,
					declaredType: argumentDict.declaredType
				};
				boundValue = ArgumentState.EVALUATED( newDict );
				if ( doValidate && resolveInternals ) {
					const argument = newDict.argument;
					const declaredType = newDict.declaredType;
					const declaredResult = await validateAsType(
						argument, invariants, this.lastFrame_, declaredType );
					if ( containsError( declaredResult ) ) {
						boundValue = ArgumentState.ERROR(
							normalError(
								[ error.argument_type_mismatch ],
								[ declaredType, argument.Z1K1, argument,
									getError( declaredResult ) ] ) );
					}
				}
			} else {
				// TODO (T296676): Throw error here, since this shouldn't happen.
			}
		}
		if ( doSetBoundValue ) {
			this.setArgument( argumentName, boundValue );
		}
		return boundValue;
	}
 
}
 
/**
 * Retrieve argument declarations and instantiations from a Z7.
 *
 * @param {Object} zobject
 * @param {Invariants} invariants evaluator, resolver: invariants preserved over all function calls
 * @param {Frame} scope current variable bindings
 * @param {boolean} doValidate whether to validate types of arguments and return values
 * @return {Array} list of objects containing argument names
 */
async function getArgumentStates( zobject, invariants, scope, doValidate = true ) {
	const argumentStates = [];
	let Z7K1Envelope = await ( zobject.resolveKey(
		[ 'Z7K1' ], invariants, scope, /* ignoreList= */ null, /* resolveInternals= */ true, doValidate ) );
	if ( containsError( Z7K1Envelope ) ) {
		return [ ArgumentState.ERROR( 'Could not dereference Z7K1' ) ];
	}
	Z7K1Envelope = await ( zobject.Z7K1.resolve(
		invariants, scope, /* ignoreList= */ null, /* resolveInternals= */ true, doValidate ) );
	const Z7K1 = Z7K1Envelope.Z22K1;
	const Z8K1Envelope = await ( Z7K1.resolveKey(
		[ 'Z8K1' ], invariants, scope, /* ignoreList= */ null, /* resolveInternals= */ false, doValidate ) );
	// This usually happens because dereferencing can't occur during validation
	// (and is expected).
	Iif ( containsError( Z8K1Envelope ) ) {
		return [ ArgumentState.ERROR( 'Could not dereference Z8K1' ) ];
	}
	// const Z8K1 = Z8K1Envelope.Z22K1;
	const Z8K1 = Z7K1.Z8K1;
	const foundKeys = new Set( zobject.keys() );
	foundKeys.delete( 'Z1K1' );
	foundKeys.delete( 'Z7K1' );
	for ( const Z17 of convertZListToItemArray( Z8K1 ) ) {
		const argumentDict = {};
		await ( Z17.resolveKey(
			[ 'Z17K2' ], invariants, scope,
			/* ignoreList= */ null, /* resolveInternals= */ false, doValidate ) );
		const argumentName = Z17.Z17K2.Z6K1;
		argumentDict.name = argumentName;
		// TODO (T292787): This is flaky to rely on; find a better way to determine type.
		await ( Z17.resolveKey(
			[ 'Z17K1' ], invariants, scope,
			/* ignoreList= */ null, /* resolveInternals= */ false, doValidate ) );
		argumentDict.declaredType = Z17.Z17K1;
		let key = argumentName;
		if ( zobject[ key ] === undefined ) {
			const localKeyRegex = /K[1-9]\d*$/;
			key = key.match( localKeyRegex )[ 0 ];
		}
 
		const argument = zobject[ key ];
 
		if ( argument === undefined ) {
			argumentStates.push( ArgumentState.ERROR( `Could not find argument ${argumentName}.` ) );
		} else {
			foundKeys.delete( key );
			argumentDict.argument = argument;
			argumentStates.push( ArgumentState.UNEVALUATED( argumentDict ) );
		}
	}
 
	for ( const extraKey of foundKeys ) {
		argumentStates.push( ArgumentState.ERROR( `Invalid key for function call: ${extraKey}.` ) );
	}
 
	return argumentStates;
}
 
/**
 * Ensure that result of a function call comports with declared type.
 *
 * FIXME (T311055): validateReturn might require normal form. Check and document.
 *
 * @param {Object} result
 * @param {Object} zobject
 * @param {Invariants} invariants evaluator, resolver: invariants preserved over all function calls
 * @param {Frame} scope current variable bindings
 * @return {Object} zobject if validation succeeds; error tuple otherwise
 */
async function validateReturnType( result, zobject, invariants, scope ) {
	// eslint-disable-next-line no-bitwise
	const thebits = ( ( await containsValue( result ) ) << 1 ) | containsError( result );
 
	Iif ( thebits === 0 ) {
		// Neither value nor error.
		return makeWrappedResultEnvelope(
			null,
			normalError(
				[ error.not_wellformed_value ],
				[ 'Function evaluation returned an empty object.' ] ) );
	} else if ( thebits === 2 ) {
		// Value returned; validate its return type..
		await ( zobject.resolveKey( [ 'Z7K1', 'Z8K2' ], invariants, scope ) );
		const returnType = zobject.Z7K1.Z8K2;
		const returnTypeValidation = await validateAsType(
			result.Z22K1, invariants, scope, returnType );
		if ( containsError( returnTypeValidation ) ) {
			return makeWrappedResultEnvelope(
				null,
				normalError(
					[ error.return_type_mismatch ],
					[ returnType, result.Z22K1.Z1K1, result.Z22K1,
						getError( returnTypeValidation ) ] ) );
		}
	} else Iif ( thebits === 3 ) {
		// Both value and error.
		return makeWrappedResultEnvelope(
			null,
			normalError(
				[ error.not_wellformed_value ],
				[ 'Function evaluation returned both a value and an error.' ] ) );
	}
	return result;
}
 
/**
 * Same as {@link execute} but assumes a new frame has already been created in the scope and does
 * not recursively resolve the subobjects.
 *
 * @param {ZWrapper} zobject
 * @param {Invariants} invariants
 * @param {Frame} scope
 * @param {boolean} doValidate
 * @param {ImplementationSelector} implementationSelector
 * @param {boolean} resolveInternals
 * @return {ZWrapper}
 */
async function executeInternal(
	zobject, invariants, scope, doValidate = true,
	implementationSelector = null, resolveInternals = true ) {
 
	const typeKey = await createZObjectKey( zobject );
	if ( typeKey.ZID_ === 'Z881' && !resolveInternals ) {
		// TODO (T305459): Tighten number of cases where `resolveInternals` is set to false.
		return ZWrapper.create( await resolveListType( zobject.Z881K1 ) );
	}
 
	// Retrieve argument declarations and instantiations.
	const argumentStates = await getArgumentStates( zobject, invariants, scope );
	for ( const argumentState of argumentStates ) {
		if ( argumentState.state === 'ERROR' ) {
			return makeWrappedResultEnvelope(
				null,
				normalError(
					[ error.error_in_evaluation ],
					[ argumentState.error ]
				)
			);
		}
		scope.setArgument( argumentState.argumentDict.name, argumentState );
	}
 
	// Ensure Z8 (Z7K1) is dereferenced. Also ensure implementations are
	// dereferenced (Z8K4 and all elements thereof).
	const Z7K1Envelope = await ( zobject.Z7K1.resolve(
		invariants, scope, /* ignoreList= */ null, /* resolveInternals= */ false, doValidate ) );
	Iif ( containsError( Z7K1Envelope ) ) {
		return Z7K1Envelope;
	}
	const Z7K1 = Z7K1Envelope.Z22K1;
	const Z8K4Envelope = await ( Z7K1.Z8K4.resolve(
		invariants, scope, /* ignoreList= */ null, /* resolveInternals= */ false, doValidate ) );
	Iif ( containsError( Z8K4Envelope ) ) {
		return Z8K4Envelope;
	}
	const Z8K4 = Z8K4Envelope.Z22K1;
	const implementations = [];
 
	for ( let Z14 of convertZListToItemArray( Z8K4 ) ) {
		Z14 = ( await ( Z14.resolve(
			invariants, scope, /* ignoreList= */null, /* resolveInternals= */ false, doValidate
		) ) ).Z22K1;
		for ( const key of [ 'Z14K2', 'Z14K3', 'Z14K4' ] ) {
			if ( Z14[ key ] !== undefined ) {
				const implementationInternalEnvelope = await ( Z14.resolveKey(
					[ key ], invariants, scope, /* ignoreList= */null,
					/* resolveInternals= */ true, doValidate ) );
				if ( containsError( implementationInternalEnvelope ) ) {
					return implementationInternalEnvelope;
				}
			}
		}
		implementations.push( Z14 );
	}
 
	if ( implementations.length === 0 ) {
		return makeWrappedResultEnvelope(
			null,
			normalError(
				[ error.error_in_evaluation ],
				[ 'Could not find any implementations for ' + zobject.Z7K1.Z8K5.Z9K1 + '.' ]
			)
		);
	}
 
	if ( implementationSelector === null ) {
		implementationSelector = new RandomImplementationSelector();
	}
	const implementationZObject = implementationSelector.select( implementations );
	const implementation = Implementation.create( implementationZObject );
 
	Iif ( implementation === null ) {
		return makeWrappedResultEnvelope(
			null,
			normalError(
				[ error.error_in_evaluation ],
				[ 'Could not create an implementation for ' + zobject.Z7K1.Z8K5.Z9K1 + '.' ]
			)
		);
	}
 
	const argumentInstantiations = [];
	if ( !( implementation instanceof Composition ) ) {
		// Populate arguments from scope.
		const instantiationPromises = [];
		for ( const argumentState of argumentStates ) {
			const argumentDict = argumentState.argumentDict;
			instantiationPromises.push(
				scope.retrieveArgument(
					argumentDict.name, invariants,
					implementation.hasLazyVariable( argumentDict.name ),
					doValidate
				) );
		}
		for ( const instantiation of await Promise.all( instantiationPromises ) ) {
			if ( instantiation.state === 'ERROR' ) {
				return makeWrappedResultEnvelope( null, instantiation.error );
			}
			argumentInstantiations.push( instantiation.argumentDict );
		}
	}
 
	// Equip the implementation for its journey and execute.
	implementation.setScope( scope );
	implementation.setInvariants( invariants );
	implementation.setDoValidate( doValidate );
	let result = await implementation.execute( zobject, argumentInstantiations );
 
	// Execute result if implementation is lazily evaluated.
	if ( implementation.returnsLazy() ) {
		await ( result.resolveKey(
			[ 'Z22K1' ], invariants, scope, /* ignoreList= */ null,
			/* resolveInternals= */ true, doValidate ) );
	}
	if ( doValidate && resolveInternals ) {
		result = await validateReturnType( result, zobject, invariants, scope );
	}
	return result;
}
 
async function resolveDanglingReferences( zobject, invariants, scope ) {
	if ( !( zobject instanceof ZWrapper ) ) {
		return;
	}
	for ( const key of zobject.keys() ) {
		const oldValue = zobject[ key ];
		let oldValueJSON = oldValue;
		if ( oldValueJSON instanceof ZWrapper ) {
			oldValueJSON = oldValueJSON.asJSON();
		}
		if ( ( await validatesAsArgumentReference( oldValueJSON ) ).isValid() ) {
			const valueEnvelope = await ( oldValue.resolve(
				invariants, scope, /* ignoreList= */ new Set( [
					MutationType.REFERENCE, MutationType.FUNCTION_CALL,
					MutationType.GENERIC_INSTANCE
				] ), /* resolveInternals= */ false, /* doValidate= */ true ) );
			// It's okay for some Z18s not to have values assigned.
			// TODO (T305981): We should formally distinguish between unbound
			// and unassigned variables. This will constrain further the errors
			// that we let slide here.
			if ( !containsError( valueEnvelope ) ) {
				const newValue = valueEnvelope.Z22K1;
				zobject.setName( key, newValue );
				Eif ( newValue instanceof ZWrapper ) {
					let newScope;
					Eif ( oldValue instanceof ZWrapper ) {
						newScope = oldValue.getScope();
					} else {
						newScope = zobject.getScope();
					}
					zobject[ key ].setScope( newScope );
				}
			}
		}
		await resolveDanglingReferences( zobject[ key ], invariants, scope );
	}
}
 
/**
 * Given ZWrapper representing a function call ZObject, resolves the function, selects an
 * implementation, and executes it with the supplied arguments.
 *
 * @param {ZWrapper} zobject object describing a function call
 * @param {Invariants} invariants evaluator, resolver: invariants preserved over all function calls
 * @param {Frame} oldScope current variable bindings
 * @param {boolean} doValidate whether to validate types of arguments and return value
 * @param {ImplementationSelector} implementationSelector
 * @param {boolean} resolveInternals if false, will evaluate typed lists via shortcut
 *      and will not validate attributes of Z7s
 * @param {boolean} topLevel whether this is the top-level Z7 sent to the orchestrator
 * @return {ZWrapper} result of executing function call
 */
execute = async function (
	zobject, invariants, oldScope = null, doValidate = true,
	implementationSelector = null, resolveInternals = true, topLevel = false ) {
	const scope = new Frame( oldScope );
	const result = ZWrapper.create( await executeInternal(
		zobject, invariants, scope, doValidate,
		implementationSelector, resolveInternals ) );
	result.setScope( scope );
	if ( topLevel ) {
		await resolveDanglingReferences( result.Z22K1, invariants, scope );
	}
	return result;
};
 
module.exports = { execute, getArgumentStates };