-
Notifications
You must be signed in to change notification settings - Fork 853
Expand file tree
/
Copy pathrust.py
More file actions
393 lines (311 loc) · 9.84 KB
/
rust.py
File metadata and controls
393 lines (311 loc) · 9.84 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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
from typing import Any, Callable, TypeVar
from talon import Context, Module, actions, settings
from ...core.described_functions import create_described_insert_between
from ..tags.operators import Operators
mod = Module()
# rust specific grammar
mod.list("code_type_modifier", desc="List of type modifiers for active language")
mod.list("code_macros", desc="List of macros for active language")
mod.list("code_trait", desc="List of traits for active language")
@mod.action_class
class Actions:
def code_state_implements():
"""Inserts implements block, positioning the cursor appropriately"""
def code_insert_macro(text: str, selection: str):
"""Inserts a macro and positions the cursor appropriately"""
def code_insert_macro_array(text: str, selection: str):
"""Inserts a macro array and positions the cursor appropriately"""
def code_insert_macro_block(text: str, selection: str):
"""Inserts a macro block and positions the cursor appropriately"""
def code_state_unsafe():
"""Inserts an unsafe block and positions the cursor appropriately"""
def code_comment_documentation_block():
"""Inserts a block document comment and positions the cursor appropriately"""
def code_comment_documentation_inner():
"""Inserts an inner document comment and positions the cursor appropriately"""
def code_comment_documentation_block_inner():
"""Inserts an inner block document comment and positions the cursor appropriately"""
ctx = Context()
ctx.matches = r"""
code.language: rust
"""
scalar_types = {
"eye eight": "i8",
"you eight": "u8",
"bytes": "u8",
"eye sixteen": "i16",
"you sixteen": "u16",
"eye thirty two": "i32",
"you thirty two": "u32",
"eye sixty four": "i64",
"you sixty four": "u64",
"eye one hundred and twenty eight": "i128",
"you one hundred and twenty eight": "u128",
"eye size": "isize",
"you size": "usize",
"float thirty two": "f32",
"float sixty four": "f64",
"boolean": "bool",
"character": "char",
}
compound_types = {
"tuple": "()",
"array": "[]",
}
standard_library_types = {
"box": "Box",
"vector": "Vec",
"string": "String",
"string slice": "&str",
"os string": "OsString",
"os string slice": "&OsStr",
"see string": "CString",
"see string slice": "&CStr",
"option": "Option",
"result": "Result",
"hashmap": "HashMap",
"hash set": "HashSet",
"reference count": "Rc",
}
standard_sync_types = {
"arc": "Arc",
"barrier": "Barrier",
"condition variable": "Condvar",
"mutex": "Mutex",
"once": "Once",
"read write lock": "RwLock",
"receiver": "Receiver",
"sender": "Sender",
"sink sender": "SyncSender",
}
all_types = {
**scalar_types,
**compound_types,
**standard_library_types,
**standard_sync_types,
}
standard_function_macros = {
"panic": "panic!",
"format": "format!",
"concatenate": "concat!",
"print": "print!",
"print line": "println!",
"error print line": "eprintln!",
"to do": "todo!",
}
standard_array_macros = {
"vector": "vec!",
}
standard_block_macros = {
"macro rules": "macro_rules!",
}
logging_macros = {
"debug": "debug!",
"info": "info!",
"warning": "warn!",
"error": "error!",
}
testing_macros = {
"assert": "assert!",
"assert equal": "assert_eq!",
"assert not equal": "assert_ne!",
}
all_function_macros = {
**standard_function_macros,
**logging_macros,
**testing_macros,
}
all_array_macros = {
**standard_array_macros,
}
all_block_macros = {
**standard_block_macros,
}
all_macros = {
**all_function_macros,
**all_array_macros,
**all_block_macros,
}
all_function_macro_values = set(all_function_macros.values())
all_array_macro_values = set(all_array_macros.values())
all_block_macro_values = set(all_block_macros.values())
closure_traits = {
"closure": "Fn",
"closure once": "FnOnce",
"closure mutable": "FnMut",
}
conversion_traits = {
"into": "Into",
"from": "From",
}
iterator_traits = {
"iterator": "Iterator",
}
all_traits = {
**closure_traits,
**conversion_traits,
**iterator_traits,
}
# tag: libraries
ctx.lists["user.code_libraries"] = {
"eye oh": "std::io",
"file system": "std::fs",
"envy": "std::env",
"collections": "std::collections",
}
# tag: functions_common
ctx.lists["user.code_common_function"] = {
"drop": "drop",
"catch unwind": "catch_unwind",
"iterator": "iter",
"into iterator": "into_iter",
"from iterator": "from_iter",
**all_macros,
}
# tag: functions
ctx.lists["user.code_type"] = all_types
# rust specific grammar
ctx.lists["user.code_type_modifier"] = {
"mutable": "mut ",
"mute": "mut ",
"borrowed": "&",
"borrowed mutable": "&mut ",
"borrowed mute": "&mut ",
"mutable borrowed": "&mut ",
"mute borrowed": "&mut ",
}
@ctx.capture("user.code_type", rule="[{user.code_type_modifier}] {user.code_type}")
def code_type(m) -> str:
"""Returns a macro name"""
return "".join(m)
ctx.lists["user.code_macros"] = all_macros
ctx.lists["user.code_trait"] = all_traits
operators = Operators(
# code_operators_array
SUBSCRIPT=create_described_insert_between("[", "]"),
# code_operators_assignment
ASSIGNMENT=" = ",
ASSIGNMENT_ADDITION=" += ",
ASSIGNMENT_SUBTRACTION=" -= ",
ASSIGNMENT_MULTIPLICATION=" *= ",
ASSIGNMENT_DIVISION=" /= ",
ASSIGNMENT_MODULO=" %= ",
ASSIGNMENT_BITWISE_AND=" &= ",
ASSIGNMENT_BITWISE_OR=" |= ",
ASSIGNMENT_BITWISE_EXCLUSIVE_OR=" ^= ",
ASSIGNMENT_BITWISE_LEFT_SHIFT=" <<= ",
ASSIGNMENT_BITWISE_RIGHT_SHIFT=" >>= ",
# code_operators_bitwise
BITWISE_AND=" & ",
BITWISE_OR=" | ",
BITWISE_EXCLUSIVE_OR=" ^ ",
BITWISE_LEFT_SHIFT=" << ",
BITWISE_RIGHT_SHIFT=" >> ",
# code_operators_math
MATH_ADD=" + ",
MATH_SUBTRACT=" - ",
MATH_MULTIPLY=" * ",
MATH_DIVIDE=" / ",
MATH_MODULO=" % ",
MATH_EXPONENT=create_described_insert_between(".pow(", ")"),
MATH_EQUAL=" == ",
MATH_NOT_EQUAL=" != ",
MATH_GREATER_THAN=" > ",
MATH_GREATER_THAN_OR_EQUAL=" >= ",
MATH_LESS_THAN=" < ",
MATH_LESS_THAN_OR_EQUAL=" <= ",
MATH_AND=" && ",
MATH_OR=" || ",
ASSIGNMENT_INCREMENT=" += 1",
# code_operators_pointer
POINTER_INDIRECTION="*",
POINTER_ADDRESS_OF="&",
)
@ctx.action_class("user")
class UserActions:
def code_get_operators() -> Operators:
return operators
# tag: imperative
# tag: object_oriented
def code_operator_object_accessor():
actions.insert(".")
def code_self():
actions.insert("self")
def code_define_class():
actions.user.insert_snippet_by_name("structDeclaration")
# tag: data_bool
def code_insert_true():
actions.insert("true")
def code_insert_false():
actions.insert("false")
# tag: data_null
def code_insert_null():
actions.insert("None")
def code_insert_is_null():
actions.insert(".is_none()")
def code_insert_is_not_null():
actions.insert(".is_some()")
# tag: functions
def code_default_function(text: str):
actions.user.code_private_function(text)
def code_private_function(text: str):
actions.insert("fn ")
formatter = settings.get("user.code_private_function_formatter")
function_name = actions.user.formatted_text(text, formatter)
actions.user.code_insert_function(function_name, None)
def code_protected_function(text: str):
actions.insert("pub(crate) fn ")
formatter = settings.get("user.code_protected_function_formatter")
function_name = actions.user.formatted_text(text, formatter)
actions.user.code_insert_function(function_name, None)
def code_public_function(text: str):
actions.insert("pub fn ")
formatter = settings.get("user.code_public_function_formatter")
function_name = actions.user.formatted_text(text, formatter)
actions.user.code_insert_function(function_name, None)
def code_insert_type_annotation(type: str):
actions.insert(f": {type}")
def code_insert_return_type(type: str):
actions.insert(f" -> {type}")
# tag: functions_gui
def code_insert_function(text: str, selection: str):
code_insert_function_or_macro(text, selection, "(", ")")
# tag: libraries
def code_insert_library(text: str, selection: str):
actions.user.insert_snippet_by_name("importStatement", {"0": text})
# rust specific grammar
def code_state_implements():
actions.user.insert_snippet_by_name("implementsStruct")
def code_insert_macro(text: str, selection: str):
if text in all_array_macro_values:
code_insert_function_or_macro(text, selection, "[", "]")
elif text in all_block_macro_values:
code_insert_function_or_macro(text, selection, "{", "}")
else:
code_insert_function_or_macro(text, selection, "(", ")")
def code_state_unsafe():
actions.user.insert_snippet_by_name("unsafeBlock")
def code_comment_documentation_block():
actions.user.insert_between("/**", "*/")
actions.key("enter")
def code_comment_documentation_inner():
actions.insert("//! ")
def code_comment_documentation_block_inner():
actions.user.insert_between("/*!", "*/")
actions.key("enter")
def code_insert_function_or_macro(
text: str,
selection: str,
left_delim: str,
right_delim: str,
):
if selection:
out_text = text + f"{left_delim}{selection}{right_delim}"
else:
out_text = text + f"{left_delim}{right_delim}"
actions.user.paste(out_text)
actions.edit.left()
RT = TypeVar("RT") # return type
def repeat_call(n: int, f: Callable[..., RT], *args: Any, **kwargs: Any):
for _ in range(n):
f(*args, **kwargs)