규칙 7.10
이 페이지에서

규칙 7.10

7장, 표현식과 문 테스트

T | undefined and T | null are optional values. Both use the same ordinary struct containing value: T and present: bool; their logical types distinguish which absent value the flag represents. T | null | undefined adds isNull: bool, read only when absent: false means undefined, true means null (change 0098). Logical identity must survive aliases, inferred locals, fields, fixed-array elements, callback signatures and generic specialization, despite shared two-state storage. T is what a function-scope struct field may hold: a scalar, a vector, a matrix, an emulated f64 or vecNf64, an array with a size, a struct or a key type; repeated absent members and aliases of optional unions flatten to the same logical type. An optional cannot hold a texture, sampler, atomic, array with no size, Map, Set or void (TS8002). An absent-only type has no payload and is refused. Loose comparisons with either absent literal test presence; strict comparisons distinguish the two absent states. A strict comparison with an excluded absent literal is constant, while its operand still runs once (change 0098, D3). An optional value may be a local, with or without a type annotation; a parameter of a function that is no entry point and no kernel function, of a method or of a local function; the result of such a function, written or inferred (Rule 8.19); a parameter or the result of a function-typed parameter (Rule 8.18); and, in function scope, a field of a class, an interface or a type literal (a parameter property included) and an element of an array with a size, array<T | undefined, N>, where function scope means the struct or the array is the type of a local, a parameter, a function’s result or a function-typed parameter’s parameter or result, or a field or an element of one of these (change 0093, decision D1). An enum member, a Map value and a Record value must be refused (TS8002), each in one sentence that names the position; a binding, a module variable, a module constant, an override, an entry point’s parameter, an entry point’s result (an IO struct), a kernel function’s parameter (a storage array’s element, a Map or Set value) and a kernel function’s result (#792) that hold an optional directly, or through a field or an element, must be refused (TS8002) at the declaration, in one sentence that names the position and, through a struct or an array, the field or the element that holds it (change 0093, decision D1); an optional, a struct with an optional field, an array of optionals and an optional parameter have no host value (Rule 8.21). A field f?: T is the same type as f: T | undefined, and an object literal may omit it, the omitted field absent (change 0093, decision D3); f?: T and x?: T whose T an optional may not hold must be refused (TS8002), as T | undefined is. undefined written for a field or an element, in an object literal, in a constructor argument, in an array literal or in an assignment (h.n = undefined), is the absent value, a T written there is present, a class field with no initializer starts null if only null is admitted, otherwise undefined, in new C() (change 0098, D7; class zero initialization differs from JavaScript and from local definite assignment), and a class field with an initializer starts as the initializer says (change 0093, decision D4); a field read h.n and an element read xs[i] are optional values and take every form of this rule. Each internal struct is declared before the first struct of the module that holds it and after the struct its T names, and one no declared struct holds after every declared struct, on every target (change 0093, decision D11). undefined written where an optional is expected is the absent value, the zero of T and false; a value of T written there is present, that value and true; a let whose type includes undefined starts undefined; a local of T | null with no initializer is unassigned and a premature read is TS8075; undefined anywhere else must be refused (TS8003). A parameter x?: T of a function that is no entry point and no kernel function, of a method, of a static function, of a constructor, of a local function, of a function-typed parameter’s type (Rule 8.18) and of an arrow function written as an argument declares x as T | undefined in the body; a call may omit it, and the omitted argument is the absent value, filled where the call is as a default is (surface §14), or may write undefined for it; a call with too few arguments counts an optional parameter as one with a default (TS8019); an integer literal handed to an i32 | undefined takes the i32 first (change 0093, decisions D5 and D6). x?: T on an entry point, whose parameters come from the pipeline, and on a kernel function, whose parameters come from the host, x?: T = d (TypeScript’s TS1015) and a required parameter after an optional one (TypeScript’s TS1016) must be refused (TS8020), each in one sentence that names the edit, since the compiler reads no checker (Rule 12.7). The compiler must follow TypeScript’s narrowing of a local or a parameter read by its name, and of a member path rooted at one, h.n or h.a.n (change 0093, decision D2), for these forms: v === undefined, v !== undefined, v == undefined and v != undefined, in either operand order and through !; the conditions of if, ?:, &&, ||, while and for; an early return, break or continue; an assignment or an initializer, after which v is present when the value is a T and absent when it is undefined; and v ??= d, after which v is present. Inside a local function or an arrow function, a const keeps its narrowing, and a let or a parameter keeps it only when nothing assigns it after the closure, as TypeScript keeps them; a bare discard (Rule 7.7) does not end a path for the walk, since TypeScript’s flow does not know it, so a read after if (v === undefined) { discard; } is refused in both halves. A member path is cleared, and read un-narrowed, after an assignment to a prefix of the path or to the root (h = …, h.a = …), after a compound assignment, ++ or -- on the path, a prefix or the root, and after a call that takes the root by reference: f(h) where f is a function of the file that writes its parameter at that index (Rule 8.25), and h.m() where m is a method of a class of the file that writes through this (Rule 8.10) or a setter; inside a local function or an arrow function a path keeps no narrowing, since TypeScript keeps one there only for a readonly field, which the walk does not read, and an element access xs[i] is not narrowed, with a literal index either; each of the two is a recorded divergence (Rule 7.2), and the refusal of an element read names the copy to test, const x = xs[i]; if (x !== undefined) (change 0093). A loose v == null or v != null test follows the same narrowing as v == undefined or v != undefined, including member paths and all control-flow forms below. The tested expression runs once, including a call or getter with effects (change 0098, D4). A narrowed read of v is v.value, and of a path h.n.value; a read of an optional where a T is needed that nothing narrowed, a name, a path, an element, a call or any other expression, must be refused (TS8003), in TypeScript’s TS18048 place (Rule 12.7), with the test and the fallback to write, at a return, a declaration, an assignment, a compound assignment and a builtin’s or a constructor’s argument as at an operator or a call (change 0093); a user type guard, an aliased condition, typeof v === "undefined" and switch (true) are not followed, and each is a recorded divergence (Rule 7.2). v ?? d is v’s value where v is present and d otherwise, d evaluated only then (Rule 7.9), and is optional where d is; o?.f, o?.xy and o?.[i] give undefined for an absent receiver and preserve the member value for a present receiver; a nullable member therefore produces a three-state optional; v === x with x a T is v.present && v.value == x, v === w with two optionals is true when both are present and equal, or both hold the same absent value; loose equality treats null and undefined as equal, and both apply only where === applies to T (Rule 7.1); v ??= d assigns d where v is absent. A value read twice by a lowering (f(x) ?? d reads the flag and the value) is bound to a temporary inside the branch that evaluates it, and refused where no statement can take it (TS8099). A two-state optional widens to the three-state type without changing its absent identity; a present T lifts into any optional of T. Un-narrowed null-only and undefined-only types cannot be assigned, passed or returned as each other. Strict tests can exclude one absent state, permitting conversion to the remaining two-state type; a reference argument requires the exact logical storage type. A conditional joins the absent states of its arms. A nullish expression removes all left-side absence and retains only the right-side absent states. ?:, ??, ??= and logical short-circuit forms evaluate only the selected branch, including conversion temporaries. Nullable class values and nullable fields obey the same rules, including accessors, private/protected/readonly fields, inherited fields, constructor parameters, static methods, function-valued fields and generic classes. Optional static data fields remain refused as module state. Only a field written ? may be omitted from an object literal, and omission means undefined even when its payload includes null. An optional as a condition (if (v), v && …, !v), the assertion v!, an optional call (o?.m(), f?.()) and a function with no written result that returns undefined and no value must be refused, each with the edit to write. In a function with an optional result, a bare return; and a path that ends the body without a return are the result’s absent value (change 0099): null for a null-only result, and undefined when admitted. The null-only case differs from TypeScript. A bare return; where the result is a plain T stays refused, as TypeScript refuses it.

규칙 본문과 그 아래 항목은 설계 문서에 적힌 컴파일러 원문이라 한국어 페이지에서도 영어로 둡니다.

근거

a TypeScript author writes “no value” as undefined, and before this rule TS8002 asked the author to carry a bool by hand; libraries invented a sentinel value instead, which no checker tests (TypePlot’s 1e20, TypeCV’s 1e30), and changes/0088-optional-values.md records four curve visibility defects that came from that gap. The flag is a bool field of an ordinary struct, which every target and the CPU oracle already carry, so the IR gains no node, nothing depends on NaN (which WGSL lets an implementation assume absent, surface §44), and an analysis gap can at worst miss a refusal: an absent value reads the zero the compiler stored, on every target. The positions are the ones no layout reaches: WGSL forbids a bool in host-shareable memory, a struct field or an array element in a binding would change a layout reflect() reports (Rule 6.8), and an entry’s IO has no bool interstage form; in function scope a struct field and an array element reach no layout, so change 0093 allows them there, with the lowering change 0088 already had as the field’s or the element’s type, and moves the refusal to the position that cannot hold the flag, which names the field. An optional parameter is where a TypeScript author writes a signature’s “no value”: the default that meant “none”, which change 0088 left as the remedy, was the sentinel moved to the signature (change 0093, Alternatives (e)); the declaration order of decision D11 is one every target, the oracle and a reader can rely on, since GLSL ES 3.00 needs a struct declared before its use. The editor’s TypeScript checker already types and narrows T | undefined, so the compiler follows the same forms (decision D2) and the two halves stay one vocabulary (Rule 12.7); the forms it does not follow are recorded so that the refusal names the test to write. The number of this rule, surface §76 and the example id are decision D9 of the proposal; the examples are examples/gallery/optional-values/optional-values.shade.ts and, for the positions of change 0093, examples/gallery/optional-fields/optional-fields.shade.ts (its decision D10), which the compile gate compiles on Tint and WebGL2 and whose suite, examples/shade-examples.test.ts, is the evidence for them once its Verifies tag names this rule.

출처

changes/0088-optional-values.md (decisions D1 to D9); changes/0093-optional-positions.md (decisions D1 to D11); TypeScript’s optional properties and optional parameters; TypeScript’s narrowing (equality narrowing, control flow analysis, assignments) and its rule for a closure (TypeScript 5.4, “Preserved Narrowing in Closures Following Last Assignments”); ECMAScript ??, optional chains and IsStrictlyEqual; WGSL Structure Types and Host-shareable Types (no bool); Rule 2.2 (the internal struct is not authorable); Rule 7.1; Rule 7.2; Rule 7.6; Rule 7.8; Rule 7.9; Rule 8.8; Rule 8.10; Rule 8.18; Rule 8.19; Rule 8.21; Rule 8.25; Rule 12.7; surface §7, §14, §28, §49, §62, §64 and §76.

검증 방식

테스트로 확인합니다. 테스트나 게이트 스크립트, CI 워크플로가 이 규칙을 가리키고, 아래 파일 가운데 하나라도 규칙을 더는 가리키지 않으면 추적 검사가 실패합니다.

컴파일러가 이 규칙을 적용하는 곳을 규칙이 직접 적은 내용입니다.

src/compiler/ts/optional.ts, the one place the representation is spelled (optionalT, optionalStructName, absentOf, presentOf, mayBeOptional, refuseOptionalAt, and for change 0093 optionalWithin, the first optional a struct or an array holds through a field or an element, refusedOptionalPosition, optionalDeclaredType, the type of f?: T and x?: T, and orderedStructDecls, the declaration order of decision D11, which src/compiler/ts/source-file.ts applies); src/compiler/ts/narrowing.ts, the flow walk (narrowingAt), which keys a member path under its root and reads the file’s written object parameters (referenceOf in src/compiler/ts/object-reference/written.ts) and writing methods for the calls that clear one; src/compiler/ts/lower/optional-values.ts, the lowering of each form (lowerOptionalMember for a field read, v.value where the path is present, and refuseOptionalWhereInnerWanted for an optional lowered where the position wants its T); src/compiler/ts/lower/param-defaults.ts, whose paramDefault fills an omitted optional parameter with the absent value where the call is, as it fills a default; TS8002 UNKNOWN_TYPE from mapUnion in src/compiler/ts/type-map.ts for a T an optional may not hold ("texture_2d<f32> | undefined" would hold a texture_2d<f32> and a flag saying whether it is there, and an optional holds what a function-scope struct field may: a scalar, a vector, a matrix, an array with a size or a struct.), from optionalDeclaredType for f?: T or x?: T with such a T ("t?" on "Q" would hold a texture_2d<f32> and a flag saying whether it is there, and an optional holds what a function-scope struct field may: a scalar, a vector, a matrix, an array with a size or a struct., the subject parameter "t?" for a parameter), and from refuseOptionalAt for a refused position ("f32 | undefined" holds a value and a flag saying whether it is there, which a local, a parameter, a function's result, a struct field or an array element may hold; a binding may not. Carry a u32 flag beside the value, "f32"., and through a field or an element "U" holds "w: f32 | undefined", a value and a flag saying whether it is there, which a local, a parameter, a function's result, a struct field or an array element may hold; a binding may not. Carry a u32 flag beside the value, "f32"., the path u.w, [i] or xs[i] where the holder nests, and the position one of a binding, a module variable, a module constant, an override, an entry point's parameter, an entry point's result, a kernel function's parameter, a kernel function's result, a Map value and a Record value; for a kernel function’s result the remedy reads Carry a u32 flag beside the value, "f32", in an array the function writes, or return a struct with a "found: u32" field beside it., #792); TS8003 TYPE_MISMATCH for an un-narrowed read ("v" is "f32 | undefined" here, and "*" takes an f32. Test it first, "if (v !== undefined)", or give the absent case a value, "v ?? 0.".; with the path for a member read, "h.k" is "f32 | undefined" here, and the result here is an f32. Test it first, "if (h.k !== undefined)", or give the absent case a value, "h.k ?? 0.".; it for a call or any other expression, "f(x)" is "f32 | undefined" here, …, "if (it !== undefined)", …, "it ?? 0.".; and for an element read "xs[0]" is "f32 | undefined" here, and "*" takes an f32. Take it in a const first, "const x = xs[0]; if (x !== undefined)", or give the absent case a value, "xs[0] ?? 0.".), for an optional as a condition (A condition is a bool, and "v" is "f32 | undefined". Write "v !== undefined"., and "v === true", or "v ?? false" for a bool), for v! ("v!" asserts that "v" is there, which a shader cannot check. …), for undefined where no optional is expected ("undefined" is the absent value of an optional type, "T | undefined", and nothing here declares one (Rule 7.10). …, on the statement for a return) and for a comparison of a value that is always there with undefined; TS8099 UNSUPPORTED for o?.m() and f?.() ("?." before a call tests a function value, and a shader has none. …), for typeof v === "undefined" (lowerBinary in src/compiler/ts/lower/expression.ts) and for a value read twice where no statement can take the temporary; TS8021 RETURN_SHAPE for a function that returns undefined and no value (src/compiler/ts/lower/function.ts); the absent value for a bare return; in src/compiler/ts/lower/statement.ts and for a path that ends the body in src/compiler/ts/lower/function.ts, which appends the return (change 0099), pinned by src/compiler/ts/optional-values.test.ts (“a bare return and a path that ends the body are the absent value”) against the program that writes return undefined;, byte for byte on WGSL and GLSL ES 3.00 and value for value on the CPU oracle; TS8020 FUNCTION_SHAPE from src/compiler/ts/lower/function.ts for an optional parameter where none may be (change 0093): an entry point’s (An entry's parameters come from the pipeline, not from a call, so "w" cannot be optional. Write "w: T".), a kernel function’s (A kernel function's parameters come from the host, not from a call, so "k" cannot be optional. Write "k: T".), x?: T = d ("k?: T = d" gives "k" two fillers: a parameter is optional, or has a default, not both (TypeScript's TS1015). Write "k?: T" or "k: T = d".) and a required parameter after an optional one ("x" is required and follows the optional parameter "k": a required parameter cannot follow an optional one (TypeScript's TS1016). Write "x?: T", or move it before "k".); TS8019 ARITY_MISMATCH counting an optional parameter as one with a default ("r9" takes 1 to 2 argument(s), got 0.); the host face’s hostTypeOf (Rule 8.21) for the host value an optional, a struct with an optional field, an array of optionals and an optional parameter do not have; the editor’s SAME_MISTAKE pairs for TypeScript’s TS18048, TS2532 and TS2538, and for TS1015 and TS1016 (change 0093), in src/language-service/diagnostics/same-mistake.ts and its hover f32 | undefined in src/language-service/hover.ts, for an optional field and an optional parameter too; pinned by src/compiler/ts/optional-values.test.ts, which reads both halves of each form and each refusal (its section “change 0093” for the positions, the member path and the optional parameter), and by src/language-service/ambient-parity.test.ts; examples/gallery/optional-values/optional-values.shade.ts (decision D9) and examples/gallery/optional-fields/optional-fields.shade.ts (change 0093, decision D10), compiled by examples/shade-examples.test.ts with their emit goldens and by the compile gate on Tint and WebGL2.

커밋 af54ddad5에서 이 규칙을 확인하는 파일입니다. 파일마다 규칙을 처음 가리키는 줄로 연결했습니다.

설명하는 절

커밋 af54ddad5의 언어 문서에서 이 규칙을 설명하는 절입니다.

적용하는 오류 코드

규칙이 Enforced by 항목에서 가리키는 진단 코드와, 레지스트리 설명에서 이 규칙을 가리키는 진단 코드입니다.

TS8002 UNKNOWN_TYPE
아무것도 선언하지 않은 타입 이름입니다. 매개변수, 타입 인자, 별칭, implements 절, 기반 클래스 어디에 써도 걸리고, 이 표면이 매퍼가 읽는 자리에서 받지 않는 타입도 여기에 속합니다(규칙 2.1). 파일이 선언했지만 구조체로 모으지 않은 기반은 STRUCT_FIELD입니다.
TS8003 TYPE_MISMATCH
연산자나 조건, 선언, 반환, 인자처럼 두 값이 만나는 자리에서 타입이 서로 맞지 않거나, 검사로 좁히지 않은 선택적 값(T | undefined, T | null, T | null | undefined)을 읽거나(규칙 7.10), 컴파일러가 접는 상수를 WGSL이 거부합니다. 31을 넘는 시프트 양, 0인 제수, 서로 엇갈린 clamp 경계, 범위를 넘는 f32 값, Math.pow(-2., 2.)처럼 정의역 밖에서 부르는 내장 함수가 그렇습니다.
TS8019 ARITY_MISMATCH
호출이나 생성자에서 인자, 요소, 필드의 개수가 맞지 않습니다.
TS8020 FUNCTION_SHAPE
TypeShade가 지원하지 않는 함수 선언이나 매개변수 모양입니다. 이름이나 본문이 없는 경우, 나머지 매개변수, 구조 분해 매개변수가 그렇습니다.
TS8021 RETURN_SHAPE
return의 모양이 잘못되었습니다. 값이 필요한 곳의 값 없는 return, undefined를 반환하면서 값은 없는 함수, 반환 타입 표기가 없는데 값을 반환하는 compute 진입점이 그렇습니다.
TS8099 UNSUPPORTED
자기 코드를 받을 만하지 않은 진단을 위한 포괄 코드입니다. 순차 범위 뒤인 TS8099에 따로 둡니다.

함께 보기

소스

커밋 af54ddad5의 규칙 원문:

이 페이지 편집 문제 보고