-
Notifications
You must be signed in to change notification settings - Fork 326
Expand file tree
/
Copy pathPrelude.fs
More file actions
282 lines (244 loc) · 7.87 KB
/
Copy pathPrelude.fs
File metadata and controls
282 lines (244 loc) · 7.87 KB
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
namespace Fable.Py
open Fable
open System
module Naming =
open Fable.Core
open System.Text.RegularExpressions
/// PyPI package name (used for pip install)
[<Literal>]
let fableLibPyPIPackage = "fable-library"
/// Python import name (underscores, not hyphens)
[<Literal>]
let fableLibPyPI = "fable_library"
let lowerFirst (s: string) =
if String.IsNullOrEmpty(s) then
s
else
s.Substring(0, 1).ToLowerInvariant() + s.Substring(1)
let upperFirst (s: string) =
if String.IsNullOrEmpty(s) then
s
else
s.Substring(0, 1).ToUpperInvariant() + s.Substring(1)
let toCamelCase (name: string) =
Naming.applyCaseRule CaseRules.LowerFirst name
let toSnakeCase (name: string) =
Naming.applyCaseRule CaseRules.SnakeCase name
/// Convert an F# field name (record or union case field) to snake_case with special handling
/// for camelCase/PascalCase conflicts.
/// - If the name is PascalCase, convert to snake_case without suffix.
/// - If the name is camelCase, convert to snake_case and add '_' suffix to avoid conflict with PascalCase.
let toFieldSnakeCase (name: string) =
let snakeCase = Naming.applyCaseRule CaseRules.SnakeCase name
if name.Length > 0 && Char.IsLower(name.[0]) then
snakeCase + "_"
else
snakeCase
let toPascalCase (name: string) = upperFirst name
/// Convert name to Python naming convention.
/// - If the name starts with a lowercase letter, convert it to snake_case.
/// - If the name starts with an uppercase letter, preserve case as is.
let toPythonNaming (name: string) =
if name.Length > 0 && Char.IsLower(name.[0]) then
Naming.applyCaseRule CaseRules.SnakeCase name
else
name
let cleanNameAsPyIdentifier (name: string) =
name.Replace('.', '_').Replace('`', '_')
let pyKeywords =
// https://docs.python.org/3/reference/lexical_analysis.html#keywords
System.Collections.Generic.HashSet
[
"False"
"await"
"else"
"import"
"pass"
"None"
"break"
"except"
"in"
"raise"
"True"
"class"
"finally"
"is"
"return"
"and"
"continue"
"for"
"lambda"
"try"
"as"
"def"
"from"
"nonlocal"
"while"
"assert"
"del"
"global"
"not"
"with"
"async"
"elif"
"if"
"or"
"yield"
]
// Other global builtins we should avoid https://docs.python.org/3/library/functions.html
let pyBuiltins =
System.Collections.Generic.HashSet
[
"abs"
"len"
"str"
"int"
"float"
"set"
"enumerate"
"next"
"super"
"callable"
"hash"
"classmethod"
"staticmethod"
"list"
"dict"
"bool"
"isinstance"
"issubclass"
"hasattr"
"getattr"
// Other names
"self"
]
let pyStdlib =
System.Collections.Generic.HashSet
[
"abc"
"asyncio"
"array"
"base64"
"builtins"
"collections"
"dataclasses"
"datetime"
"decimal"
"enum"
"functools"
"inspect"
"itertools"
"io"
"locale"
"math"
"operator"
"os"
"pathlib"
"platform"
"queue"
"random"
"re"
"readline"
"posix"
"string"
"struct"
"sys"
"tempfile"
"threading"
"time"
"typing"
"unicodedata"
"urllib"
"uuid"
"warnings"
]
let reflectionSuffix = "_reflection"
let mutable uniqueIndex = 0
let getUniqueIndex () =
let idx = uniqueIndex
uniqueIndex <- uniqueIndex + 1
idx
let preventConflicts conflicts originalName =
let rec check originalName n =
let name =
if n > 0 then
originalName + "_" + (string<int> n)
else
originalName
if not (conflicts name) then
name
else
check originalName (n + 1)
check originalName 0
let isIdentChar index (c: char) =
// Digits are not allowed in first position, see #1397
c = '_' || Char.IsLetter(c) || Char.IsDigit(c) && index > 0
let hasIdentForbiddenChars (ident: string) =
let mutable found = false
for i = 0 to ident.Length - 1 do
found <- found || not (isIdentChar i ident.[i])
found
let sanitizeIdentForbiddenChars (ident: string) =
if hasIdentForbiddenChars ident then
String.Concat(
seq {
for i = 0 to (ident.Length - 1) do
let c = ident.[i]
if isIdentChar i c then
string<char> c
elif c = '$' || c = '_' || c = ' ' || c = '*' || c = '.' || c = '`' then
"_"
else
"_" + String.Format("{0:X}", int c).PadLeft(4, '0')
}
)
else
ident
let checkPyKeywords name =
if pyKeywords.Contains name then
name + "_"
else
name
let checkPyStdlib name =
if pyStdlib.Contains name then
name + "_"
else
name
let private printPart sanitize separator part overloadSuffix =
(if String.IsNullOrEmpty(part) then
""
else
separator + (sanitize part))
+ (if String.IsNullOrEmpty(overloadSuffix) then
""
else
"_" + overloadSuffix)
let private buildName sanitize name part =
(sanitize name)
+ (
match part with
| Naming.InstanceMemberPart(s, i) -> printPart sanitize "__" s i
| Naming.StaticMemberPart(s, i) -> printPart sanitize "_" s i
| Naming.NoMemberPart -> ""
)
let sanitizeIdent conflicts (name: string) part =
// Replace Forbidden Chars
buildName sanitizeIdentForbiddenChars name part
|> checkPyKeywords
// Check if it already exists
|> preventConflicts conflicts
/// Convert name to Python naming convention.
/// Removes @ suffixes and applies standard Python naming rules.
let toPropertyNaming (name: string) =
let pythonName = toPythonNaming name
// Remove @ suffix
if pythonName.EndsWith("@", StringComparison.Ordinal) then
pythonName.Substring(0, pythonName.Length - 1)
else
pythonName
let toPropertyBackingFieldNaming (name: string) =
let propertyName =
name
|> toPropertyNaming
|> fun name -> Naming.applyCaseRule CaseRules.SnakeCase name
$"_%s{propertyName}"