All files execute.js

90.25% Statements 361/400
80.16% Branches 198/247
96.67% Functions 29/30
90.18% Lines 358/397

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 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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074    1x 1x 1x 1x 1x 1x                       1x 1x 1x 1x 1x                     1x 1x 1x 1x   1x     958x               958x 958x       958x     958x 356x   958x 958x   958x 958x 958x       958x 958x 957x 957x 938x   19x                 958x           958x             958x 204x 204x 204x 31x 31x               958x 958x                       958x 958x 13667x 13667x 4040x   9627x     9627x 9627x     9627x 22336x 9627x   12709x     958x           3512x 3512x 3512x 3512x 3512x 3512x 3512x                                 2928x 2928x           2928x     2928x     2013x           2013x     2013x 2013x 11x       2928x         5276x       1174x     4102x 1764x   4102x                                   3512x     8x 8x       3504x     176x   3328x     2x   3326x     4102x   4102x 1174x 1174x   2928x 2928x     4102x 9752x 6236x   3516x 1794x 3x 1791x 1x       1x             3512x 3512x 3512x 3512x 2338x   3512x 186x           186x     186x 186x 186x   186x 186x 186x         186x 186x       3512x       4101x 3512x 101x       4000x           7235x     7235x                   3857x           1727x     1727x 6x   1721x       1721x 1721x     1721x 1x                       1720x 798x 798x     798x 798x 798x 19x               1701x                                                     2140x 2140x       2140x 291x 291x     1849x 1727x           1727x 1727x     1727x 26x 1701x 1701x         1701x         2140x 2018x   2140x                           1527x   1527x 1x   1526x       1526x 1x         1525x 1525x   1856x     1856x 1856x 3712x     3712x             1525x                     730x   730x           730x     730x     730x 730x 5x   725x                   1520x 1520x 1520x 1520x 1520x 1847x 1847x 1847x 1847x   1847x 1847x 1847x 216x 216x     1847x   1847x 3x       3x   1844x 1844x 1844x       1520x 3x       3x     1520x                           216x 160x 160x                           160x 160x 160x 160x     160x 1x                           159x     56x                   56x                     203x   203x 37x 166x 23x   143x   203x 203x 157x   203x 203x                                                   1516x                           1516x 1516x 1516x 1839x     1516x 1516x   1361x 1361x 1651x 1651x 1651x           1651x     1361x 1633x 24x   1609x         1492x 1492x 1492x                                         5719x 5719x 5719x 5719x 151x   5719x   4192x                 1527x 1527x 2x       1525x 730x 730x 5x         1520x 1520x 1847x 4x                   1516x 1516x     1516x   1516x       1521x         1521x 793x   1521x         1521x 1521x   1x 1x         1520x 1520x                       1516x 1521x 1521x   1516x 2x                 1514x 1504x     1514x 1514x 1516x 1516x 1516x 1516x     1510x   6x                   6x 6x 6x             1514x     4x                   1510x 43x     43x 43x     43x           1510x 203x       203x 203x 203x 203x 203x   203x 203x 203x 203x 2410x 2266x       203x 203x 2x     1510x                     82805x 46552x   36253x 82589x 82589x 82589x 36037x   82589x 16x                 16x 13x 13x 13x   13x 13x 13x         13x 13x       82589x                                   1x         5721x 5720x 5720x 1x       1x         5720x             5719x     5719x 216x 216x   5719x 5719x 5719x         5719x                     5719x     1x  
'use strict';
 
const { ArgumentState } = require( './argumentState.js' );
const { Invariants } = require( './Invariants.js' );
const ImplementationSelector = require( './implementationSelector.js' );
const { BaseFrame, EmptyFrame } = require( './frame.js' );
const { Composition, Implementation, Evaluated, EvaluatorError, ZResponseError } = require( './implementation.js' );
const { FirstImplementationSelector } = require( './implementationSelector.js' );
const {
	isGenericListType,
	isTrue,
	isZ24,
	makeWrappedResultEnvelope,
	safeJsonStringify,
	quoteZObject,
	returnOnFirstError,
	responseEnvelopeContainsError,
	responseEnvelopeContainsValue,
	traverseZList
} = require( './utils.js' );
const { MutationType, ZWrapper } = require( './ZWrapper.js' );
const { resolveListType } = require( './builtins.js' );
const sUtil = require( '../lib/util' );
const { error, makeErrorInNormalForm } = require( '../function-schemata/javascript/src/error.js' );
const {
	createZObjectKey,
	findFunctionIdentity,
	findTypeIdentity,
	getError,
	isGlobalKey,
	isString,
	setMetadataValues,
	wrapInQuote,
	wrapInKeyReference
} = require( '../function-schemata/javascript/src/utils.js' );
const { validatesAsArgumentReference, validatesAsFunctionCall, validatesAsReference, validatesAsString, validatesAsType } = require( '../function-schemata/javascript/src/schema.js' );
const { compareTypes } = require( '../function-schemata/javascript/src/compareTypes.js' );
const ErrorFormatter = require( '../function-schemata/javascript/src/errorFormatter.js' );
 
let execute = null;
 
async function validateAsType( Z1, invariants, typeZObject = null ) {
	const wrapInZ9 = ( ZID ) => ZWrapper.create(
		{
			Z1K1: 'Z9',
			Z9K1: ZID
		},
		// A lone reference doesn't need any scope.
		new EmptyFrame()
	);
	const callTuples = [];
	let resolvedType = Z1.getNameEphemeral( 'Z1K1' );
 
	// TODO (T292787): Make this more elegant--should be possible to avoid
	// passing strings in the first place.
	Iif ( isString( typeZObject ) ) {
		typeZObject = wrapInZ9( typeZObject );
	}
	if ( isString( resolvedType ) ) {
		resolvedType = wrapInZ9( resolvedType );
	}
	Eif ( typeZObject instanceof ZWrapper ) {
		typeZObject = typeZObject.asJSON();
	}
	let resolvedTypeJSON = resolvedType;
	Eif ( resolvedType instanceof ZWrapper ) {
		resolvedTypeJSON = resolvedType.asJSON();
	}
 
	// Run type comparison if typeZObject is provided.
	Eif ( typeZObject !== null ) {
		const runTypeComparison = ( comparand, comparator ) => {
			const typeComparison = compareTypes( comparand, comparator );
			if ( typeComparison ) {
				return makeWrappedResultEnvelope( Z1, null );
			} else {
				return makeWrappedResultEnvelope(
					null,
					makeErrorInNormalForm(
						error.unexpected_zobject_type,
						[ comparator, comparand ]
					)
				);
			}
		};
		callTuples.push(
			[
				runTypeComparison,
				[ resolvedTypeJSON, typeZObject ],
				'runTypeComparison' ] );
	}
	const genericSchemaValidatorZID = 'Z831';
 
	// 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.
	//
	// TODO (T327870): Also run the validator for typeZObject?
	if ( validatesAsType( resolvedTypeJSON ).isValid() ) {
		await ( resolvedType.resolveEphemeral( [ 'Z4K3' ], invariants ) );
		const validatorZ8 = resolvedType.Z4K3;
		if ( findFunctionIdentity( validatorZ8 ).Z9K1 !== genericSchemaValidatorZID ) {
			const { runTypeValidatorDynamic } = require( './validation.js' );
			callTuples.push(
				[
					runTypeValidatorDynamic,
					[ Z1, resolvedType, invariants ],
					'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 {boolean} doValidate whether to validate types of arguments and return values
 * @return {Promise<ArgumentState|null>} error state or null if no error encountered
 */
async function resolveTypes( Z1, invariants, doValidate = true ) {
	const objectQueue = [ Z1 ];
	while ( objectQueue.length > 0 ) {
		const nextObject = objectQueue.shift();
		if ( !( nextObject instanceof ZWrapper ) ) {
			continue;
		}
		await ( nextObject.resolveEphemeral(
			[ 'Z1K1' ], invariants, /* ignoreList= */ null,
			/* resolveInternals= */ false, doValidate ) );
		const typeEnvelope = nextObject.Z1K1;
		Iif ( responseEnvelopeContainsError( typeEnvelope ) ) {
			return ArgumentState.ERROR( getError( typeEnvelope ) );
		}
		for ( const key of nextObject.keys() ) {
			if ( key === 'Z1K1' ) {
				continue;
			}
			objectQueue.push( nextObject[ key ] );
		}
	}
	return null;
}
 
class KeyList {
 
	constructor( key, lastList, lastType ) {
		this.key = key;
		this.lastList = lastList;
		this.seenKeys = new Set( lastList === null ? undefined : lastList.seenKeys );
		this.seenKeys.add( this.key );
		this.seenTypes = new Set( lastList === null ? undefined : lastList.seenTypes );
		this.seenTypes.add( lastType );
		this.length = 1 + ( lastList === null ? 0 : lastList.length );
	}
 
	getAllKeys() {
		let result;
		if ( this.lastList !== null ) {
			result = new Array( this.lastList.getAllKeys() );
		} else {
			result = [];
		}
		result.push( this.key );
		return result;
	}
 
}
 
async function getIdentityKeys( zobject, invariants ) {
	const identityKeys = new Set();
	const keysEnvelope = await ( zobject.resolveEphemeral(
		[ 'Z1K1', 'Z4K2' ],
		invariants,
		/* ignoreList= */ null,
		/* resolveInternals= */ false,
		/* doValidate= */ false ) );
	Iif ( responseEnvelopeContainsError( keysEnvelope ) ) {
		return identityKeys;
	}
	await traverseZList(
		zobject.getNameEphemeral( 'Z1K1' ).getNameEphemeral( 'Z4K2' ),
		async ( tail ) => {
			const keyEnvelope = await tail.resolveEphemeral(
				[ 'K1' ],
				invariants,
				/* ignoreList= */ null,
				/* resolveInternals= */ false,
				/* doValidate= */ false );
			Iif ( responseEnvelopeContainsError( keyEnvelope ) ) {
				return;
			}
			const theKey = tail.getNameEphemeral( 'K1' );
			if ( isTrue( theKey.Z3K4 ) ) {
				identityKeys.add( theKey.Z3K2.Z6K1 );
			}
		}
	);
	return identityKeys;
}
 
async function eagerlyEvaluate(
	zobject, invariants, ignoreList, resolveInternals, doValidate, keyList = null ) {
	if (
		!( zobject instanceof ZWrapper ) ||
			validatesAsString( zobject ).isValid() ||
			validatesAsReference( zobject ).isValid() ) {
		return null;
	}
 
	if ( ignoreList === null ) {
		ignoreList = new Set();
	}
	const ignoreKeys = new Set( [
		// These are the identity fields defined on built-in types.
		// If we supported the `evenBuiltIns` argument in `resolveEphemeral`,
		// then we could avoid specifying these keys and identify these keys
		// using `getIdentityKeys`. However, this is inefficient and
		// unnecessary.
		'Z4K1', 'Z8K5', 'Z40K1',
		// Z1K1/Type should not be recursively expanded.
		'Z1K1',
		// Non-identity members of a Type should not be expanded.
		'Z4K2', 'Z4K3', 'Z4K4', 'Z4K5', 'Z4K6', 'Z4K7', 'Z4K8',
		// Non-identity members of a Function should not be expanded.
		'Z8K1', 'Z8K2', 'Z8K3', 'Z8K4',
		// Just say, "no," to Quotes.
		'Z99K1'
	] );
 
	function doResolve( key, someObject, someObjectJSON ) {
		if (
			validatesAsArgumentReference( someObjectJSON ).isValid() &&
			!( ignoreList.has( MutationType.ARGUMENT_REFERENCE ) ) ) {
			Eif ( someObject.getScope().hasVariable( someObjectJSON.Z18K1.Z6K1 ) ) {
				return true;
			}
			return false;
		}
		if (
			validatesAsReference( someObjectJSON ).isValid() &&
			!( ignoreList.has( MutationType.REFERENCE ) ) ) {
			return true;
		}
		if (
			validatesAsFunctionCall( someObjectJSON ).isValid() &&
			!( ignoreList.has( MutationType.FUNCTION_CALL ) ) ) {
			return true;
		}
		return false;
	}
 
	const subResultPromises = [];
	let typeIdentity, identityKeys;
	if ( isString( zobject.Z1K1 ) ) {
		typeIdentity = zobject.Z1K1;
		identityKeys = new Set();
	} else {
		typeIdentity = JSON.stringify( findTypeIdentity( zobject.Z1K1 ).asJSON() );
		identityKeys = await getIdentityKeys( zobject, invariants );
	}
 
	for ( const key of zobject.keys() ) {
		if ( identityKeys.has( key ) || ignoreKeys.has( key ) ) {
			continue;
		}
		if ( isGlobalKey( key ) && keyList !== null ) {
			if ( keyList.seenKeys.has( key ) && keyList.seenTypes.has( typeIdentity ) ) {
				continue;
			} else if ( keyList.length > 100 ) {
				invariants.logger.log(
					'warn',
					{ message: 'Recursion limit: stack limit reached or exceeded', requestId: invariants.requestId }
				);
				return makeWrappedResultEnvelope(
					null,
					makeErrorInNormalForm(
						error.orchestrator_recursion_limit,
						[ '100', 'eagerlyEvaluate' ] ) );
			}
		}
		const nextKeyList = new KeyList( key, keyList, typeIdentity );
		const oldValue = zobject[ key ];
		let oldValueJSON = oldValue;
		if ( oldValueJSON instanceof ZWrapper ) {
			oldValueJSON = oldValueJSON.asJSON();
		}
		if ( doResolve( key, oldValue, oldValueJSON ) ) {
			const valueEnvelope = await ( oldValue.resolve(
				invariants, ignoreList, resolveInternals, doValidate ) );
			// 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.
			Iif ( responseEnvelopeContainsError( valueEnvelope ) ) {
				return valueEnvelope;
			} else {
				const newValue = valueEnvelope.Z22K1;
				zobject.setName( key, newValue );
				Eif ( newValue instanceof ZWrapper ) {
					let newScope, newParent;
					Eif ( oldValue instanceof ZWrapper ) {
						newScope = oldValue.scope_;
						newParent = oldValue.parent_;
					} else {
						newScope = zobject.scope_;
						newParent = zobject.parent_;
					}
					zobject[ key ].scope_ = newScope;
					zobject[ key ].parent_ = newParent;
				}
			}
		}
		subResultPromises.push( eagerlyEvaluate(
			zobject[ key ], invariants, ignoreList, resolveInternals, doValidate, nextKeyList ) );
	}
 
	for ( const subResult of await ( Promise.all( subResultPromises ) ) ) {
		if ( subResult !== null ) {
			return subResult;
		}
	}
 
	return null;
}
 
class Frame extends BaseFrame {
 
	constructor( lastFrame = null ) {
		Iif ( lastFrame === null ) {
			lastFrame = new EmptyFrame();
		}
		super( lastFrame );
	}
 
	/**
	 * 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, doEagerlyEvaluate,
		ignoreList ) {
		const argumentEnvelope = await ( argumentDict.argument.resolve(
			invariants, ignoreList, resolveInternals, doValidate,
			/* evenBuiltins= */ true ) );
		if ( responseEnvelopeContainsError( argumentEnvelope ) ) {
			return ArgumentState.ERROR( getError( argumentEnvelope ) );
		}
		const argument = argumentEnvelope.Z22K1;
 
		// First evaluate the argument. Evaluation may be eager or shallow
		// depending on the provided flag.
		Eif ( doEagerlyEvaluate ) {
			const eagerEvaluationEnvelope = await eagerlyEvaluate(
				argument, invariants, /* ignoreList= */ null,
				resolveInternals, doValidate );
			if ( eagerEvaluationEnvelope !== null ) {
				return ArgumentState.ERROR( getError( eagerEvaluationEnvelope ) );
			}
		}
 
		// 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
		// Validate the argument as its declared type.
		if ( doValidate && resolveInternals ) {
			const typeError = await resolveTypes( argument, invariants );
			Iif ( typeError !== null ) {
				return typeError;
			}
			const declaredType = argumentDict.declaredType;
			const declaredResult = await validateAsType( argument, invariants, declaredType );
			if ( responseEnvelopeContainsError( declaredResult ) ) {
				return ArgumentState.ERROR(
					makeErrorInNormalForm(
						error.argument_type_mismatch,
						[ declaredType, argument.Z1K1, argument,
							getError( declaredResult ) ] ) );
			}
		}
 
		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 {boolean} doEagerlyEvaluate whether to eagerly evaluate the argument
	 * @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, doEagerlyEvaluate = 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, doEagerlyEvaluate, 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,
				doEagerlyEvaluate, 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 );
			} else {
				// TODO (T296676): Throw error here, since this shouldn't happen.
			}
		}
		if ( doSetBoundValue ) {
			this.setArgument( argumentName, boundValue );
		}
		return boundValue;
	}
 
}
 
/**
 * Resolves function eternals, particularly the Z7K1/Function and Z8K1/argument declarations.
 *
 * @param {ZWrapper} zobject
 * @param {Invariants} invariants evaluator, resolver: invariants preserved over all function calls
 * @param {boolean} doValidate whether to validate types of arguments and return values
 * @return {Object|null} either a Z22 containing an error state or null
 */
async function resolveFunctionInternals( zobject, invariants, doValidate ) {
	const Z7K1Envelope = await ( zobject.resolveEphemeral(
		[ 'Z7K1' ], invariants, /* ignoreList= */ null, /* resolveInternals= */ true, doValidate ) );
	if ( responseEnvelopeContainsError( Z7K1Envelope ) ) {
		return Z7K1Envelope;
	}
	const Z8K1Envelope = await ( zobject.Z7K1.resolveEphemeral(
		[ 'Z8K1' ], invariants, /* ignoreList= */ null, /* resolveInternals= */ false, doValidate ) );
	// This usually happens because dereferencing can't occur during validation
	// (and is expected).
	if ( responseEnvelopeContainsError( Z8K1Envelope ) ) {
		return Z8K1Envelope;
	}
 
	// If resolution of any Z17/Argument declaration goes badly, we should return the
	// first error. We will return null if no error occurs.
	let badEnvelope = null;
	await traverseZList( zobject.Z7K1.Z8K1, async ( tail ) => {
		// No reason to keep going if an error has already occurred.
		Iif ( badEnvelope !== null ) {
			return;
		}
		const Z17 = tail.K1;
		for ( const key of [ 'Z17K1', 'Z17K2' ] ) {
			const keyEnvelope = await ( Z17.resolveEphemeral(
				[ key ], invariants,
				/* ignoreList= */ null, /* resolveInternals= */ false, doValidate ) );
			Iif ( responseEnvelopeContainsError( keyEnvelope ) ) {
				badEnvelope = keyEnvelope;
			}
		}
	} );
 
	// This will be either the first error encountered when resolving Z17s or null.
	return badEnvelope;
}
 
/**
 * Validates the Z7K1/Function and the labels of argument declarations.
 *
 * @param {ZWrapper} zobject
 * @param {Invariants} invariants evaluator, resolver: invariants preserved over all function calls
 * @return {Object|null} either a Z22 containing an error state or null
 */
async function validateFunctionInternals( zobject, invariants ) {
	const { runTypeValidatorDynamic } = require( './validation.js' );
	async function runBuiltinTypeValidator( someObject ) {
		const theTypeEnvelope = await someObject.Z1K1.resolve(
			invariants,
			/* ignoreList= */ null,
			/* resolveInternals= */ false,
			/* doValidate= */ false,
			/* evenBuiltins= */ true );
		Iif ( responseEnvelopeContainsError( theTypeEnvelope ) ) {
			return theTypeEnvelope;
		}
		return await runTypeValidatorDynamic(
			quoteZObject( someObject ), theTypeEnvelope.Z22K1, invariants );
	}
	const functionValidationResult = await runBuiltinTypeValidator( zobject.Z7K1 );
	if ( responseEnvelopeContainsError( functionValidationResult ) ) {
		return functionValidationResult;
	}
	return null;
}
 
/**
 * Retrieve argument declarations and instantiations from a Z7.
 *
 * @param {Object} zobject
 * @return {Array} list of ArgumentStates, containing argument names or errors
 */
async function getArgumentStates( zobject ) {
	const argumentStates = [];
	const foundKeys = new Set( zobject.keys() );
	foundKeys.delete( 'Z1K1' );
	foundKeys.delete( 'Z7K1' );
	await traverseZList( zobject.Z7K1.Z8K1, ( tail ) => {
		const Z17 = tail.K1;
		const argumentDict = {};
		const argumentName = Z17.Z17K2.Z6K1;
		argumentDict.name = argumentName;
		// TODO (T292787): This is flaky to rely on; find a better way to determine type.
		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 ) {
			const subError = makeErrorInNormalForm(
				error.key_not_found,
				[ wrapInKeyReference( argumentName ), wrapInQuote( zobject.asJSON() ) ]
			);
			argumentStates.push( ArgumentState.ERROR( subError ) );
		} else {
			foundKeys.delete( key );
			argumentDict.argument = argument;
			argumentStates.push( ArgumentState.UNEVALUATED( argumentDict ) );
		}
	} );
 
	for ( const extraKey of foundKeys ) {
		const subError = makeErrorInNormalForm(
			error.invalid_key,
			[ wrapInKeyReference( extraKey ) ]
		);
		argumentStates.push( ArgumentState.ERROR( subError ) );
	}
 
	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
 * @return {Object} zobject if validation succeeds; error tuple otherwise
 */
async function validateReturnType( result, zobject, invariants ) {
	if ( !responseEnvelopeContainsError( result ) ) {
		const emptyResponseEnvelopeOk = ( findFunctionIdentity( zobject.Z7K1 ).Z9K1 === 'Z820' );
		Iif ( !responseEnvelopeContainsValue( result ) && !emptyResponseEnvelopeOk ) {
			// Neither value nor error.
			// TODO (T318293): Can we add modification of the Z22 internals to the ZWrapper concept?
			const resultJSON = result.asJSON();
			return makeWrappedResultEnvelope(
				null,
				makeErrorInNormalForm(
					error.invalid_evaluation_result,
					[ wrapInQuote( resultJSON ) ]
				)
			);
		}
 
		// Value returned; validate its return type..
		await ( zobject.resolveEphemeral( [ 'Z7K1', 'Z8K2' ], invariants ) );
		const returnType = zobject.Z7K1.Z8K2;
		await resolveTypes( result.Z22K1, invariants, /* doValidate= */ true );
		const returnTypeValidation = await validateAsType(
			result.Z22K1, invariants, returnType
		);
		if ( responseEnvelopeContainsError( returnTypeValidation ) ) {
			return makeWrappedResultEnvelope(
				null,
				makeErrorInNormalForm(
					error.return_type_mismatch,
					[
						returnType,
						result.Z22K1.Z1K1,
						result.Z22K1,
						getError( returnTypeValidation )
					]
				)
			);
		}
		// If we got here, it's got a value, no error, and validates, so return as-is.
		return result;
	}
 
	Iif ( responseEnvelopeContainsValue( result ) ) {
		// Both value and error.
		const resultJSON = result.asJSON();
		return makeWrappedResultEnvelope(
			null,
			makeErrorInNormalForm( error.invalid_evaluation_result, [ wrapInQuote( resultJSON ) ] )
		);
	}
 
	// No value but some error.
	return result;
}
 
/**
 * Add implementation-specific metadata elements to the metadata map in the
 * Evaluation result (response envelope).
 *
 * @param {Implementation} implementation
 * @param {ZWrapper} result (Z22 / Evaluation result)
 */
function addImplementationMetadata( implementation, result ) {
	const implementationId = implementation.getZID(); // Can be null
	let implementationType;
	if ( implementation instanceof Composition ) {
		implementationType = 'Z14K2';
	} else if ( implementation instanceof Evaluated ) {
		implementationType = 'Z14K3';
	} else {
		implementationType = 'Z14K4';
	}
	const newPairs = [];
	if ( implementationId !== null ) {
		newPairs.push( [ { Z1K1: 'Z6', Z6K1: 'implementationId' }, { Z1K1: 'Z6', Z6K1: implementationId } ] );
	}
	newPairs.push( [ { Z1K1: 'Z6', Z6K1: 'implementationType' }, { Z1K1: 'Z6', Z6K1: implementationType } ] );
	setMetadataValues( result, newPairs );
}
 
/**
 * Run an implementation. Raise an exception if the implmentation was Evaluated
 * and the evaluator service fails or is not running.
 *
 * @param {ZWrapper} zobject the Function Call to be run
 * @param {Invariants} invariants
 * @param {boolean} doValidate
 * @param {Implementation} implementation
 * @param {boolean} resolveInternals
 * @param {Map} argumentStates
 * @param {boolean} doEagerlyEvaluate
 * @throws {EvaluatorError}
 * @return {ZWrapper}
 */
async function runThatImplementation(
	zobject,
	invariants,
	doValidate,
	implementation,
	resolveInternals,
	argumentStates,
	doEagerlyEvaluate
) {
	Iif ( implementation === null ) {
		return makeWrappedResultEnvelope(
			null,
			makeErrorInNormalForm(
				error.not_implemented_yet,
				[ findFunctionIdentity( zobject.Z7K1 ) ]
			)
		);
	}
 
	// This additional scope allows us to capture arguments at the right time.
	// Without this, closures are bound late, and undesirable behavior emerges.
	// For example, recursive functions that operate elementwise over lists
	// will end up being called with the final list element on every iteration.
	const theScope = new Frame( implementation.getZ14().getScope() );
	implementation.getZ14().setScope( theScope );
	for ( const argumentState of argumentStates ) {
		theScope.setArgument( argumentState.argumentDict.name, argumentState );
	}
 
	const argumentInstantiations = [];
	if ( !( implementation instanceof Composition ) ) {
		// Populate arguments from scope.
		const instantiationPromises = [];
		for ( const argumentState of argumentStates ) {
			const argumentDict = argumentState.argumentDict;
			instantiationPromises.push( async function () {
				const instantiation = await theScope.retrieveArgument(
					argumentDict.name, invariants,
					implementation.hasLazyVariable( argumentDict.name ),
					doValidate,
					resolveInternals,
					doEagerlyEvaluate );
				return instantiation;
			}() );
		}
		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.invariants = invariants;
	implementation.doValidate = doValidate;
	return await implementation.execute( zobject, argumentInstantiations );
}
 
/**
 * 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 {boolean} doValidate
 * @param {ImplementationSelector} implementationSelector
 * @param {boolean} resolveInternals
 * @param {boolean} topLevel whether this is the top-level Z7 sent to the orchestrator
 * @param {boolean} doEagerlyEvaluate whether to expand arguments fully
 * @return {ZWrapper}
 */
async function executeInternal(
	zobject, invariants, doValidate = true,
	implementationSelector = null, resolveInternals = true,
	topLevel = false, doEagerlyEvaluate = true ) {
 
	const newScope = new Frame( zobject.getScope() );
	zobject.setScope( newScope );
	const zObjectKey = createZObjectKey( zobject.asJSONEphemeral() );
	if ( invariants && invariants.orchestratorConfig.addNestedMetadata ) {
		newScope.metadata.set( 'zObjectKey', zObjectKey );
	}
	if ( isGenericListType( zobject ) && !resolveInternals ) {
		// TODO (T305459): Tighten number of cases where `resolveInternals` is set to false.
		return ZWrapper.create(
			await resolveListType( zobject.Z881K1 ),
			// Use an empty scope for the outer object, the nested object should already have its
			// own scope, if any.
			new EmptyFrame()
		);
	}
 
	// Resolve all argument declarations.
	const resolutionEnvelope = await resolveFunctionInternals( zobject, invariants, doValidate );
	if ( resolutionEnvelope !== null ) {
		return resolutionEnvelope;
	}
 
	// Validate Function and Labels for Argument Declarations.
	if ( doValidate ) {
		const validationEnvelope = await validateFunctionInternals( zobject, invariants );
		if ( validationEnvelope !== null ) {
			return validationEnvelope;
		}
	}
 
	// Retrieve argument declarations and instantiations.
	const argumentStates = await getArgumentStates( zobject );
	for ( const argumentState of argumentStates ) {
		if ( argumentState.state === 'ERROR' ) {
			return makeWrappedResultEnvelope(
				null,
				makeErrorInNormalForm(
					error.error_in_evaluation,
					[ wrapInQuote( zobject.asJSON() ), argumentState.error ]
				)
			);
		}
	}
 
	const Z7K1 = zobject.Z7K1;
	Z7K1.Z8K4.resolveEphemeral(
		[ 'Z8K4' ], invariants, /* ignoreList= */ null, /* resolveInternals= */ false,
		doValidate );
	const Z8K4 = Z7K1.Z8K4;
 
	let implementations = await traverseZList( Z8K4, async ( tail ) => {
		// ZID captures the persistent ID when Z14 is a Z9 / Reference,
		// for Composition and Evaluated implementations.
		// TODO( T321998 ): If an ID key is added to Z14, this can be removed
		let ZID = null;
		// We do not call validatesAsReference here. If we did, we would first
		// need to call asJSON() on tail.K1. This is an expensive operation if Z14
		// is not a reference. Because we are only interested in literal
		// references here, it is safe just to check whether Z9K1 is undefined.
		if ( tail.K1.Z9K1 !== undefined ) {
			ZID = tail.K1.Z9K1;
		}
		const Z14Envelope = await tail.resolveEphemeral(
			[ 'K1' ],
			invariants, /* ignoreList= */null, /* resolveInternals= */ false,
			doValidate );
		let impl;
		try {
			impl = await ( Implementation.create( tail.K1, Z14Envelope, ZID ) );
		} catch ( err ) {
			Eif ( err instanceof ZResponseError ) {
				return { error: err.envelope };
			} else {
				throw err; // unknown error; rethrow
			}
		}
		Eif ( impl ) {
			return { implementation: impl };
		} else {
			const stringifiedResult = safeJsonStringify( tail.K1 );
			invariants.logger.log( 'error',
				{
					message: 'Could not create implementation from Z14',
					requestId: invariants.requestId,
					info: stringifiedResult
				}
			);
		}
	} );
	implementations = implementations
		.map( ( implementation ) => implementation.implementation )
		.filter( ( implementation ) => implementation !== undefined );
 
	if ( implementations.length === 0 ) {
		return makeWrappedResultEnvelope(
			null,
			makeErrorInNormalForm(
				error.not_implemented_yet,
				[ findFunctionIdentity( zobject.Z7K1 ) ]
			)
		);
	}
 
	if ( implementationSelector === null ) {
		implementationSelector = new FirstImplementationSelector();
	}
 
	let implementation = null, result = null, lastError = null;
	for ( const generatedImplementation of implementationSelector.generate( implementations ) ) {
		implementation = generatedImplementation;
		invariants.implementationZID = implementation.ZID_;
		try {
			result = await runThatImplementation(
				zobject, invariants, doValidate, implementation, resolveInternals,
				argumentStates, doEagerlyEvaluate );
			break;
		} catch ( err ) {
			Iif ( invariants.orchestratorConfig.generateFunctionsMetrics ) {
				const errorMessage = `function implementation: ${ invariants.implementationZID } error: ${ err }`;
				invariants.logger.log( 'error',
					{
						message: errorMessage,
						requestId: invariants.requestId
					}
				);
				sUtil.sendImplementationErrorMetrics( invariants.req, errorMessage );
			}
			Eif ( err instanceof EvaluatorError ) {
				lastError = err;
				continue;
			} else {
				throw err; // unknown error; rethrow
			}
		}
	}
 
	if ( result === null ) {
		// lastError is guaranteed to be set.
		// TODO (T350716): Test this code path.
		return makeWrappedResultEnvelope(
			null,
			ErrorFormatter.wrapMessageInEvaluationError(
				lastError.message,
				zobject.asJSONEphemeral()
			)
		);
	}
 
	// Execute result if implementation is lazily evaluated.
	if ( implementation.returnsLazy() && !isZ24( result.Z22K1 ) ) {
		await ( result.resolveKey(
			[ 'Z22K1' ], invariants, /* ignoreList= */ null,
			/* resolveInternals= */ true, doValidate ) );
		Eif ( doEagerlyEvaluate ) {
			const subResult = await eagerlyEvaluate(
				result.Z22K1, invariants, /* ignoreList= */ null,
				resolveInternals, doValidate );
			Iif ( subResult !== null ) {
				return subResult;
			}
		}
	}
 
	if ( topLevel ) {
		addImplementationMetadata( implementation, result );
		// TODO (T367787): Figure out a more robust way to attach function call's
		// nested metadata to the result's metadata, and apply that solution
		// to non-top-level objects.
		const resultMetadata = result.getScope().metadata;
		let resultNestedMetadata = resultMetadata.get( 'nestedMetadataArray' );
		Eif ( resultNestedMetadata === undefined ) {
			resultNestedMetadata = [];
			resultMetadata.set( 'nestedMetadataArray', resultNestedMetadata );
		}
		const zObjectMetadata = zobject.getScope().metadata;
		const zObjectNestedMetadata = zObjectMetadata.get( 'nestedMetadataArray' );
		Eif ( zObjectNestedMetadata ) {
			for ( const nestedMetadatum of zObjectNestedMetadata ) {
				if ( nestedMetadatum !== resultMetadata ) {
					resultNestedMetadata.push( nestedMetadatum );
				}
			}
		}
		const zObjectKey = zObjectMetadata.get( 'zObjectKey' );
		if ( zObjectKey ) {
			resultMetadata.set( 'zObjectKey', zObjectKey );
		}
	}
	return result;
}
 
/**
 * Helper recursive function that 'resolves' any remaining unresolved nested zobjects
 *
 * @param {Object} zobject
 * @param {Object} invariants
 * @return {ZWrapper} zobject instance of ZWrapper, key (i.e. Z22) of evaluated ZObject
 */
async function resolveDanglingReferences( zobject, invariants ) {
	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 ( validatesAsArgumentReference( oldValueJSON ).isValid() ) {
			const valueEnvelope = await ( oldValue.resolve(
				invariants, /* 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 ( !responseEnvelopeContainsError( valueEnvelope ) ) {
				const newValue = valueEnvelope.Z22K1;
				zobject.setName( key, newValue );
				Eif ( newValue instanceof ZWrapper ) {
					let newScope, newParent;
					Eif ( oldValue instanceof ZWrapper ) {
						newScope = oldValue.scope_;
						newParent = oldValue.parent_;
					} else {
						newScope = zobject.scope_;
						newParent = zobject.parent_;
					}
					zobject[ key ].scope_ = newScope;
					zobject[ key ].parent_ = newParent;
				}
			}
		}
		await resolveDanglingReferences( zobject[ key ], invariants );
	}
}
 
/**
 * 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 {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
 * @param {boolean} doEagerlyEvaluate whether to expand arguments fully
 * @return {ZWrapper} result of executing function call
 */
execute = async function (
	zobject, invariants = null, doValidate = true,
	implementationSelector = null, resolveInternals = true, topLevel = false,
	doEagerlyEvaluate = true ) {
 
	if ( invariants !== null ) {
		const rateLimitError = invariants.rateLimiter.increment( invariants.requestId );
		if ( rateLimitError !== null ) {
			invariants.logger.log(
				'warn',
				{ message: 'Rate limit: stack limit reached or exceeded', requestId: invariants.requestId }
			);
			return rateLimitError;
		}
	}
 
	let functionIdentity, functionMetricsInstance, startTime;
	Iif ( invariants.orchestratorConfig.generateFunctionsMetrics ) {
		functionIdentity = findFunctionIdentity( zobject.Z7K1 ).Z9K1;
		// instantiate metrics data on function performance
		startTime = performance.now();
		functionMetricsInstance = sUtil.createFunctionDurationMetrics( invariants.req.app );
	}
 
	let result = await executeInternal(
		zobject, invariants, doValidate,
		implementationSelector, resolveInternals, topLevel, doEagerlyEvaluate );
	if ( topLevel ) {
		await resolveDanglingReferences( result.Z22K1, invariants );
		result = await validateReturnType( result, zobject, invariants );
	}
	Eif ( invariants !== null ) {
		const rateLimitError = invariants.rateLimiter.decrement( invariants.requestId );
		Iif ( rateLimitError !== null ) {
			return rateLimitError;
		}
	}
 
	Iif ( invariants.orchestratorConfig.generateFunctionsMetrics ) {
		// finish creating metrics on function performance
		sUtil.submitFunctionDurationMetricsAndLog(
			invariants,
			functionMetricsInstance,
			startTime,
			functionIdentity
		);
		sUtil.sendFunctionExecutionCounterMetrics( invariants.req );
	}
 
	return result;
};
 
module.exports = { execute, getArgumentStates };