Skip to content

Commit bd165e3

Browse files
gcantieffect-bot
authored andcommitted
Add Schema.isWellFormed for UTF-16 strings (#11335)
1 parent 7adc41d commit bd165e3

11 files changed

Lines changed: 331 additions & 72 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"effect": minor
3+
---
4+
5+
Add `Schema.isWellFormed()` to validate Unicode strings and generate well-formed examples with `Arbitrary.schema`.

‎packages/effect/src/Schema.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ import * as SchemaTransformation from "./SchemaTransformation.ts"
9090
import * as SemVer_ from "./SemVer.ts"
9191
import * as SemVerRange_ from "./SemVerRange.ts"
9292
import type { StandardJSONSchemaV1, StandardSchemaV1 } from "./StandardSchema.ts"
93+
import * as Str from "./String.ts"
9394
import type { Assign, Lambda, Mutable, Simplify } from "./Struct.ts"
9495
import * as Struct_ from "./Struct.ts"
9596
import type { IsUnion, RequiredKeys } from "./Types.ts"
@@ -6919,6 +6920,36 @@ export function isTrimmed(annotations?: Annotations.Filter) {
69196920
}
69206921
)
69216922
}
6923+
/**
6924+
* Validates that a string contains no unpaired UTF-16 surrogates.
6925+
*
6926+
* **When to use**
6927+
*
6928+
* Use when text must cross an encoding boundary that requires well-formed Unicode.
6929+
*
6930+
* **Details**
6931+
*
6932+
* Accepts empty strings and supplementary characters such as emoji. Arbitrary
6933+
* generation preserves complete surrogate pairs when shrinking examples.
6934+
* JSON Schema expresses this check as a Unicode pattern.
6935+
*
6936+
* @see {@link isMaxCodePoints} for limiting the code point count
6937+
* @stability stable
6938+
* @category validation
6939+
* @since 4.3.0
6940+
*/
6941+
export function isWellFormed(annotations?: Annotations.Filter) {
6942+
return makeFilter(Str.isWellFormed, {
6943+
expected: "a well-formed Unicode string",
6944+
representation: {
6945+
id: "effect/schema/isWellFormed",
6946+
payload: null
6947+
},
6948+
toJsonSchema: () => ({ pattern: /^[^\uD800-\uDFFF]*$/u.source }),
6949+
arbitraryConstraint: { wellFormed: true },
6950+
...annotations
6951+
})
6952+
}
69226953
/**
69236954
* Validates that a string matches the specified regular expression pattern.
69246955
*
@@ -19091,6 +19122,7 @@ export declare namespace Annotations {
1909119122
readonly maxLength?: number | undefined
1909219123
readonly minCodePoints?: number | undefined
1909319124
readonly maxCodePoints?: number | undefined
19125+
readonly wellFormed?: true | undefined
1909419126
readonly minSize?: number | undefined
1909519127
readonly maxSize?: number | undefined
1909619128
readonly minProperties?: number | undefined

‎packages/effect/src/SchemaRepresentation.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -805,6 +805,24 @@ export const isTrimmedReviver: FilterReviver<null> = makeReviverFilter(
805805
({ annotations }) => Schema.isTrimmed(annotations)
806806
)
807807

808+
/**
809+
* Reviver for persisted `isWellFormed` checks.
810+
*
811+
* **When to use**
812+
*
813+
* Use when reconstructing documents containing checks created by {@link Schema.isWellFormed}.
814+
*
815+
* @see {@link Schema.isWellFormed} for creating the corresponding check
816+
* @stability stable
817+
* @category validation
818+
* @since 4.3.0
819+
*/
820+
export const isWellFormedReviver: FilterReviver<null> = makeReviverFilter(
821+
"effect/schema/isWellFormed",
822+
Schema.Null,
823+
({ annotations }) => Schema.isWellFormed(annotations)
824+
)
825+
808826
/**
809827
* Reviver for persisted `isPattern` checks.
810828
*

‎packages/effect/src/internal/arbitrary/regexp.ts‎

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type * as Schema from "../../Schema.ts"
2+
import * as Str from "../../String.ts"
23
import * as Model from "./model.ts"
34

45
type Pattern = Schema.Annotations.ToArbitrary.Pattern
@@ -146,13 +147,16 @@ function concatenation(nodes: ReadonlyArray<Node>): Node {
146147
}
147148
}
148149

149-
function alternation(nodes: ReadonlyArray<Node>): Node {
150+
function alternation(nodes: ReadonlyArray<Node>, wellFormed = false): Node {
150151
const flattened: Array<Node> = []
151152
for (const node of nodes) {
152153
if (node._tag === "Alternation") flattened.push(...node.nodes)
153154
else flattened.push(node)
154155
}
155-
return flattened.length === 1 ? flattened[0] : { _tag: "Alternation", nodes: flattened }
156+
const choices = wellFormed && flattened.length > 1
157+
? flattened.filter((node) => node._tag !== "Literal" || Str.isWellFormed(node.value))
158+
: flattened
159+
return choices.length === 1 ? choices[0] : { _tag: "Alternation", nodes: choices }
156160
}
157161

158162
function normalizeIntervals(intervals: ReadonlyArray<Interval>): ReadonlyArray<Interval> {
@@ -276,25 +280,28 @@ class Parser {
276280
private index = 0
277281
private supported = true
278282
private readonly source: string
279-
private readonly dotAll: boolean
283+
private readonly flags: string
284+
private readonly wellFormed: boolean
280285

281-
constructor(source: string, dotAll: boolean) {
286+
constructor({ flags, source }: Pattern, wellFormed: boolean) {
282287
this.source = source
283-
this.dotAll = dotAll
288+
this.flags = flags
289+
this.wellFormed = wellFormed
284290
}
285291

286292
parse(): Node | undefined {
287-
const node = this.parseAlternation()
293+
const node = this.parseAlternation(true)
288294
return this.supported && this.index === this.source.length ? node : undefined
289295
}
290296

291-
private parseAlternation(): Node {
297+
private parseAlternation(root = false): Node {
292298
const nodes = [this.parseConcatenation()]
293299
while (this.peek() === "|") {
294300
this.index++
295301
nodes.push(this.parseConcatenation())
296302
}
297-
return alternation(nodes)
303+
// Without the Unicode flag, a surrogate can pair with a literal outside its group.
304+
return alternation(nodes, this.wellFormed && (root || this.flags.includes("u")))
298305
}
299306

300307
private parseConcatenation(): Node {
@@ -317,7 +324,7 @@ class Parser {
317324
case "$":
318325
return empty
319326
case ".":
320-
return character(this.dotAll ? codePointIntervals : complementIntervals(lineTerminatorIntervals))
327+
return character(this.flags.includes("s") ? codePointIntervals : complementIntervals(lineTerminatorIntervals))
321328
case "[":
322329
return this.parseCharacterClass()
323330
case "(":
@@ -789,7 +796,7 @@ function minimumLength(node: Node): number {
789796
case "Concatenation":
790797
return node.nodes.reduce((sum, child) => sum + minimumLength(child), 0)
791798
case "Repetition":
792-
return minimumLength(node.node) * node.minimum
799+
return node.minimum === 0 ? 0 : minimumLength(node.node) * node.minimum
793800
}
794801
}
795802

@@ -826,12 +833,12 @@ function addUnanchoredSurroundings(node: Node, source: string, flags: string): N
826833
* https://github.com/dubzzz/fast-check/blob/v4.9.0/packages/fast-check/src/arbitrary/stringMatching.ts
827834
*/
828835
/** @internal */
829-
export function compile(pattern: Pattern): Compiled | undefined {
836+
export function compile(pattern: Pattern, wellFormed = false): Compiled | undefined {
830837
const { flags, source } = pattern
831838
// Case folding, multiline assertions, and Unicode sets require dedicated AST semantics. Falling back preserves the
832839
// contract that a constructively supported pattern never silently ignores one of its flags.
833840
if (flags.includes("i") || flags.includes("m") || flags.includes("v")) return undefined
834-
const parsed = new Parser(source, flags.includes("s")).parse()
841+
const parsed = new Parser(pattern, wellFormed).parse()
835842
if (parsed === undefined) return undefined
836843
const restricted = flags.includes("u") ? parsed : restrictCharacterCodePoints(parsed, 0xffff)
837844
const node = addUnanchoredSurroundings(restricted, source, flags)
@@ -841,6 +848,7 @@ export function compile(pattern: Pattern): Compiled | undefined {
841848
return {
842849
minimumLength: minimum,
843850
generate: (state, minimumLength, maximumLength) => {
851+
if (minimum === Number.POSITIVE_INFINITY) return undefined
844852
const lengths = possibleLengths(node, maximumLength, cache)
845853
const candidates: Array<number> = []
846854
for (let length = minimumLength; length <= maximumLength; length++) {

0 commit comments

Comments
 (0)