-
Notifications
You must be signed in to change notification settings - Fork 10
/
python.ts
377 lines (291 loc) · 9.96 KB
/
python.ts
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
import { CodeEditor } from "@jupyterlab/codeeditor";
import { LanguageWithOptionalSemicolons, TokenContext } from "./analyzer";
import IToken = CodeEditor.IToken;
function evaluateSkippingBrackets(tokens: ReadonlyArray<IToken>, indexShift: number, callback: Function, allowNegativeBrackets=false){
// here `nextToken` is any token, not necessarily a meaningful one
let nextToken = tokens[indexShift];
// unpacking with curly braces is not possible
const openingBrackets = '([';
const closingBrackets = ')]';
let openedBrackets = 0;
// value of token is equal to an empty string for line breaks
// a line break is the latest when the search should terminate,
// unless the left-hand tuple is spread over several lines (in brackets)
while (nextToken && (nextToken.value !== '' || openedBrackets > 0)) {
if (nextToken.value === '') {
// ignoring new-lines (when within brackets)
} else if (openingBrackets.includes(nextToken.value)) {
openedBrackets += 1;
} else if (closingBrackets.includes(nextToken.value) && (allowNegativeBrackets || openedBrackets > 0)) {
openedBrackets -= 1;
} else if (nextToken.value === ' ' || nextToken.value === '\t') {
// ignoring whitespaces
} else {
let result = callback(nextToken, indexShift);
if (result !== undefined)
return result;
}
indexShift += 1;
nextToken = tokens[indexShift];
}
return false;
}
const python_setup = `
import json
from pathlib import Path
def jupyter_lab_consumable_path(path):
# if the definition is in current notebook, the path is not known on the kernel side
if not path:
return {'path': None, 'is_symlink': False}
path = Path(path)
cwd = Path.cwd()
# the simple case
if cwd in path.parents:
return {
'path': str(path.relative_to(cwd)),
'is_symlink': False
}
symlinks_dir = Path('.jupyter_symlinks')
symlinks_dir.mkdir(exist_ok=True)
# relative pathways could lead out of the starting dir as well (e.g. using .. construct on Linux)
path = path.absolute().resolve()
# remove anchor (root slash/drive etc)
sub_path = path.relative_to(path.anchor)
# TODO: add drive to avoid confusion on Windows
symlink = symlinks_dir / sub_path
symlink.parent.mkdir(exist_ok=True, parents=True)
try:
symlink.unlink()
except FileNotFoundError:
pass
assert not symlink.is_absolute()
symlink.symlink_to(path)
return {
'path': str(symlink),
'is_symlink': True
}
`;
export class PythonAnalyzer extends LanguageWithOptionalSemicolons {
// idea for improvement:
// rename Analyzer to RuleTester, define class Rule, make Rule instances take a callback on init,
// possibly add a string with rule's name (it could be displayed as "defined in >for< loop, line 9",
// or "imported from xyz module" and in case of multiple hits, user could choose which one to jump to),
// and make the rules interface the way to go for other languages.
definitionRules = [
this.isStandaloneAssignment,
this.isImport,
this.isWithStatement,
this.isForLoopOrComprehension,
this.isTupleUnpacking,
this.isStoreMagic,
this.isRMagicOutput
];
// Matching standalone variable assignment:
isStandaloneAssignment(siblings: TokenContext) {
let { next } = siblings;
return next.exists && this.isAssignment(next)
}
_is_magic_switch(candidate: TokenContext, key: string, max_args=20) {
while (max_args && candidate.exists) {
if(candidate.value === key && candidate.simple_previous === '-') {
break;
}
candidate = candidate.previous;
max_args -= 1;
}
let is_switch = max_args !== 0;
return {
'is_switch': is_switch,
'switch': is_switch ? candidate : null
};
}
_is_magic_export(context: TokenContext, magic: string, export_arg: string, nargs: number = 1) {
let { previous } = context;
let switch_test = this._is_magic_switch(previous, export_arg, nargs);
if (!switch_test.is_switch)
return false;
let magic_token = switch_test.switch.previous.previous;
let percent = magic_token.simple_previous;
return magic_token.value === magic && percent === '%'
}
// IPython %store -r magic:
isStoreMagic(context: TokenContext) {
return this._is_magic_export(context, 'store', 'r', 20);
}
isRMagicOutput(context: TokenContext) {
return this._is_magic_export(context, 'R', 'o', 1);
}
// Matching imports:
isImport(context: TokenContext) {
let { previous } = context;
return (
previous.exists &&
previous.type === 'keyword' &&
previous.value === 'import'
)
}
isCrossFileReference(context: TokenContext): boolean {
// from a import b; from a.b import c
let previous = context.previous;
let next = context.next;
previous = this.traverse_left(previous, '.');
next = this.traverse_right(next, '.');
if (
previous.exists &&
previous.type == 'keyword' &&
previous.value == 'from' &&
next.exists &&
next.type === 'keyword' &&
next.value === 'import'
)
return true;
// import x, import a.b
let before_previous = previous.previous.previous;
if (
this.isImport(previous.next)
&&
!(
before_previous.exists &&
before_previous.type === 'keyword' &&
before_previous.value === 'from'
)
)
return true;
return false;
}
supportsKernel = true;
_breadcrumbs(context: TokenContext, allow_import_dots_upfront=false) {
let { previous, token } = context;
let parts: string[] = [];
let is_dot = previous.simple_next === '.';
while (is_dot && previous.exists) {
parts.push(previous.value);
previous = previous.previous;
is_dot = previous.simple_next === '.';
}
if (allow_import_dots_upfront) {
// relative imports
if (previous.simple_previous === '.') {
parts.push('')
}
if (previous.simple_previous === '..') {
parts.push('.')
}
}
parts = parts.reverse();
parts.push(token.value);
return parts
}
_imports_breadcrumbs(context: TokenContext) {
return this._breadcrumbs(context, true)
}
definitionLocationQuery(context: TokenContext) {
let parts = this._breadcrumbs(context);
let value = parts.join('.');
if(/^[a-zA-Z_.]+$/.test(value)) {
return python_setup + `
def _extract_object(breadcrumbs, available_objects):
obj = available_objects[breadcrumbs[0]]
for name in breadcrumbs[1:]:
obj = getattr(obj, name)
return obj
def _locate_definition(name):
"""Returns (line_number, path, is_sym_link) tuple"""
from inspect import getsourcefile, getsourcelines
available_objects = globals()
input_number = None
try:
obj = _extract_object(name.split('.'), available_objects)
except (KeyError, AttributeError):
return
try:
path = getsourcefile(obj)
path_exists = Path(path).exists()
if not path_exists:
assert path.startswith('<ipython-input-')
input_number = int(path.split('-')[2])
path = None
except (TypeError, AssertionError):
path = None
try:
source, line_number = getsourcelines(obj)
except OSError:
line_number = 0
return {
'line_number': line_number,
'input_number': input_number,
'column': len(source[0]) - len(source[0].lstrip()),
**jupyter_lab_consumable_path(path)
}
print(json.dumps(_locate_definition('` + value + `')), end='')
`
}
}
referencePathQuery(context: TokenContext) {
let parts = this._imports_breadcrumbs(context);
let value = parts.join('.');
// TODO: recognize Python version and return no query (or another Python2-compatible query)
if(/^[a-zA-Z_.]+$/.test(value)) {
// just in case to prevent arbitrary execution
return python_setup + `
def _get_path(value):
"""Returns (path, is_sym_link) tuple"""
from importlib.util import find_spec
path = find_spec(value).origin
return jupyter_lab_consumable_path(path)
print(json.dumps(_get_path('` + value + `')), end='')
`
}
}
guessReferencePath(context: TokenContext) {
let parts = this._imports_breadcrumbs(context);
let prefix = parts.join('/');
return [prefix + '.py', prefix + '/__init__.py']
}
// Matching `as`:
// e.g. `with open('name') as f:` or `except Exception as e:`
isWithStatement(context: TokenContext) {
let { previous } = context;
return (
previous.exists &&
previous.type === 'keyword' &&
previous.value === 'as'
)
}
// Matching `for` loop and comprehensions:
isForLoopOrComprehension(context: TokenContext) {
let { previous, next } = context;
return (
previous.exists &&
previous.type === 'keyword' &&
previous.value === 'for' &&
next.exists &&
next.type === 'keyword' &&
next.value === 'in'
)
}
isTupleUnpacking(context: TokenContext) {
// Matching variables in tuple unpacking:
let { tokens, index } = context;
// Considering: `a, [b, c], (d, ) = 1, [1, 2], (1,)`, if the tested
// token is `a`, then the next expected token would be a comma,
// and then one of following: a variable, an assignment symbol,
// or an opening bracket (for simplicity brackets can be ignored).
let commaExpected = true;
return evaluateSkippingBrackets(tokens, index + 1, (nextToken: IToken, indexShift: number) => {
if (nextToken.type === 'operator' && nextToken.value === '=') {
let lastToken: IToken;
evaluateSkippingBrackets(tokens, indexShift + 1, (nextToken: IToken) => {
lastToken = nextToken
});
// return true unless in a function call
if ((!lastToken || lastToken.value !== ')'))
return true;
}
if (commaExpected && nextToken.value !== ',') {
return false
}
commaExpected = !commaExpected;
}, true);
}
}