Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(fast_check): better handling of non-optional parameters with an initializer #440

Merged
merged 7 commits into from
Apr 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 90 additions & 9 deletions src/fast_check/transform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -769,10 +769,19 @@ impl<'a> FastCheckTransformer<'a> {
}
}

for param in &mut n.params {
let optional_start_index =
ParamsOptionalStartIndex::build(n.params.iter().map(|p| match p {
ParamOrTsParamProp::Param(p) => &p.pat,
// should have been converted to a param
ParamOrTsParamProp::TsParamProp(_) => unreachable!(),
}));
for (i, param) in n.params.iter_mut().enumerate() {
match param {
ParamOrTsParamProp::Param(param) => {
self.handle_param_pat(&mut param.pat)?;
self.handle_param_pat(
&mut param.pat,
optional_start_index.is_optional_at_index(i),
)?;
param.decorators.clear();
}
ParamOrTsParamProp::TsParamProp(_) => {
Expand Down Expand Up @@ -1021,9 +1030,13 @@ impl<'a> FastCheckTransformer<'a> {
}));
}
}

for param in &mut n.params {
self.handle_param_pat(&mut param.pat)?;
let optional_start_index =
ParamsOptionalStartIndex::build(n.params.iter().map(|p| &p.pat));
for (i, param) in n.params.iter_mut().enumerate() {
self.handle_param_pat(
&mut param.pat,
optional_start_index.is_optional_at_index(i),
)?;
param.decorators.clear();
}

Expand Down Expand Up @@ -1105,8 +1118,10 @@ impl<'a> FastCheckTransformer<'a> {
n.is_async = false;
}

for pat in &mut n.params {
self.handle_param_pat(pat)?;
let optional_start_index = ParamsOptionalStartIndex::build(n.params.iter());
for (i, pat) in n.params.iter_mut().enumerate() {
self
.handle_param_pat(pat, optional_start_index.is_optional_at_index(i))?;
}

Ok(())
Expand All @@ -1115,6 +1130,7 @@ impl<'a> FastCheckTransformer<'a> {
fn handle_param_pat(
&mut self,
pat: &mut Pat,
is_optional: bool,
) -> Result<(), Vec<FastCheckDiagnostic>> {
match pat {
Pat::Ident(ident) => {
Expand All @@ -1134,7 +1150,11 @@ impl<'a> FastCheckTransformer<'a> {
span: DUMMY_SP,
type_ann: Box::new(t),
}));
ident.id.optional = true;
if !is_optional {
convert_optional_ident_to_nullable_type(ident);
} else {
ident.id.optional = true;
}
*pat = Pat::Ident((*ident).clone());
}
None => {
Expand All @@ -1152,7 +1172,11 @@ impl<'a> FastCheckTransformer<'a> {
}
}
} else {
ident.id.optional = true;
if !is_optional {
convert_optional_ident_to_nullable_type(ident);
} else {
ident.id.optional = true;
}
*pat = Pat::Ident((*ident).clone());
}
}
Expand Down Expand Up @@ -1687,6 +1711,25 @@ fn replacement_return_value(ty: &TsType) -> Option<Box<Expr>> {
}
}

// Converts `ident?: string` to `ident: string | undefined`
fn convert_optional_ident_to_nullable_type(ident: &mut BindingIdent) {
ident.optional = false;
if let Some(type_ann) = ident.type_ann.take() {
ident.type_ann = Some(Box::new(TsTypeAnn {
span: type_ann.span,
type_ann: Box::new(TsType::TsUnionOrIntersectionType(
TsUnionOrIntersectionType::TsUnionType(TsUnionType {
span: DUMMY_SP,
types: vec![
type_ann.type_ann,
Box::new(ts_keyword_type(TsKeywordTypeKind::TsUndefinedKeyword)),
],
}),
)),
}));
}
}

fn prefix_ident(ident: &mut Ident, prefix: &str) {
ident.sym = format!("{}{}", prefix, ident.sym).into();
}
Expand Down Expand Up @@ -1851,6 +1894,44 @@ fn infer_simple_type_from_type(t: &TsType) -> Option<TsType> {
}
}

/// Holds when the first optional parameter occurs.
struct ParamsOptionalStartIndex(Option<usize>);

impl ParamsOptionalStartIndex {
pub fn build<'a>(param_pats: impl Iterator<Item = &'a Pat>) -> Self {
fn is_param_pat_optional(pat: &Pat) -> bool {
match pat {
Pat::Ident(ident) => ident.optional,
Pat::Array(a) => a.optional,
Pat::Object(o) => o.optional,
Pat::Assign(_) | Pat::Rest(_) => true,
Pat::Invalid(_) | Pat::Expr(_) => false,
}
}

let mut optional_start_index = None;
for (i, pat) in param_pats.enumerate() {
if is_param_pat_optional(pat) {
if optional_start_index.is_none() {
optional_start_index = Some(i);
}
} else {
optional_start_index = None;
}
}

Self(optional_start_index)
}

pub fn is_optional_at_index(&self, index: usize) -> bool {
self
.0
.as_ref()
.map(|start_index| index >= *start_index)
.unwrap_or(false)
}
}

fn is_expr_ident_or_member_idents(expr: &Expr) -> bool {
match expr {
Expr::Ident(_) => true,
Expand Down
96 changes: 96 additions & 0 deletions tests/specs/graph/fast_check/function_default_before_required.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# https://jsr.io/@scope/a/meta.json
{"versions": { "1.0.0": {} } }

# https://jsr.io/@scope/a/1.0.0_meta.json
{ "exports": { ".": "./mod.ts" } }

# https://jsr.io/@scope/a/1.0.0/mod.ts
// this can be called like `test(undefined, 1)`
export function test(value: number[] = [], value2: number) {
}

export class Test {
constructor(value: number[] = [], value2: number) {
}

method(value: number[] = [], value2: number) {
}
}

export class TestParamProp {
// the type of `value` property should be `number[]`
constructor(public value: number[] = [], public value2: number) {
}
}

# mod.ts
import 'jsr:@scope/a'

# output
{
"roots": [
"file:///mod.ts"
],
"modules": [
{
"kind": "esm",
"dependencies": [
{
"specifier": "jsr:@scope/a",
"code": {
"specifier": "jsr:@scope/a",
"span": {
"start": {
"line": 0,
"character": 7
},
"end": {
"line": 0,
"character": 21
}
}
}
}
],
"size": 22,
"mediaType": "TypeScript",
"specifier": "file:///mod.ts"
},
{
"kind": "esm",
"size": 405,
"mediaType": "TypeScript",
"specifier": "https://jsr.io/@scope/a/1.0.0/mod.ts"
}
],
"redirects": {
"jsr:@scope/a": "https://jsr.io/@scope/a/1.0.0/mod.ts"
},
"packages": {
"@scope/a": "@scope/a@1.0.0"
}
}

Fast check https://jsr.io/@scope/a/1.0.0/mod.ts:
{}
export function test(value: number[] | undefined, value2: number): void {}
export class Test {
constructor(value: number[] | undefined, value2: number){}
method(value: number[] | undefined, value2: number): void {}
}
export class TestParamProp {
declare value: number[];
declare value2: number;
constructor(value: number[] | undefined, value2: number){}
}
--- DTS ---
export declare function test(value: number[] | undefined, value2: number): void;
export declare class Test {
constructor(value: number[] | undefined, value2: number);
method(value: number[] | undefined, value2: number): void;
}
export declare class TestParamProp {
value: number[];
value2: number;
constructor(value: number[] | undefined, value2: number);
}