Skip to content

Conversation

@omochi
Copy link
Owner

@omochi omochi commented Jan 1, 2025

トランスパイルするSwiftの型が var entity のようなプロパティを持っていると、
コード生成するときにJSの関数の引数の entity と、
プロパティに対応して生成されるローカル変数の const entity が衝突して、
TypeScriptとしてコンパイル不可能になってしまう。

このパッチはこの問題を回避する。

ローカル変数を生成するときに既存の名前として使用済みかどうかを調べて、
使用済みであれば代わりに連番をつけた名前を使用する。

return name
}
i += 1
}
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2から始めて衝突しなくなるまでインクリメントし続ける。

.callDecodeField(json: expr)

let varName = nameProvider.provide(base: TSKeyword.escaped(label))
names[label] = varName
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

用意された名前は後で参照する時のために辞書に入れておく

) throws -> TSObjectExpr {
return TSObjectExpr(try caseElement.associatedValues.map { (value) in
let label = value.codableLabel
let varName = try names[label].unwrap(name: "var name")
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

用意した名前を辞書から引く。
エスケープ済みの名前を格納してるので利用側のエスケープ処理が不要になっている。

)
)
block.append(j)
nameProvider.register(name: "j")
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

enumについては ej という変数も使用するが、
これとも衝突しないように利用済みの名前を追記しておく

guard let decl = try converter.decodeSignature() else { return nil }

var nameProvider = NameProvider()
nameProvider.register(signature: decl)
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

関数の仮引数名を登録しておく。

これは関数の実装部全体で有効なのでこのnameProviderをこの先で引き継ぐが、
ローカルスコープ同士の間では名前の衝突は起きない。

そこはうまく局所的な生成関数に nameProvider をコピー渡しすることで、隣のスコープ同士が影響しないようにしつつ、関数仮引数という上流のスコープの影響は引き継がせる。

@omochi omochi merged commit fb51446 into main Jan 6, 2025
1 check passed
@omochi omochi deleted the avoid-conflict-name branch January 6, 2025 06:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant