forked from tree-sitter/tree-sitter-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgrammar.js
More file actions
148 lines (121 loc) · 2.61 KB
/
grammar.js
File metadata and controls
148 lines (121 loc) · 2.61 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
/**
* @file Python grammar for tree-sitter - Dict/Expression Only
* @author Max Brunsfeld <maxbrunsfeld@gmail.com>
* @license MIT
*/
/// <reference types="tree-sitter-cli/dsl" />
// @ts-check
module.exports = grammar({
name: 'python',
extras: $ => [
$.comment,
/[\s\f\uFEFF\u2060\u200B]|\r?\n/,
$.line_continuation,
],
conflicts: $ => [
],
supertypes: $ => [
$.expression,
],
externals: $ => [
$.string,
],
inline: $ => [
],
word: $ => $.identifier,
rules: {
source_file: $ => $.expression,
expression: $ => choice(
$.string,
$.integer,
$.float,
$.true,
$.false,
$.none,
$.list,
$.dictionary,
$.set,
$.tuple,
),
// Literals
list: $ => seq(
'[',
optional($._collection_elements),
']',
),
set: $ => seq(
'{',
$._collection_elements,
'}',
),
tuple: $ => seq(
'(',
optional($._collection_elements),
')',
),
dictionary: $ => seq(
'{',
optional(commaSep1(choice($.pair))),
optional(','),
'}',
),
pair: $ => seq(
field('key', $.expression),
':',
field('value', $.expression),
),
_collection_elements: $ => seq(
commaSep1($.expression),
optional(','),
),
// String is handled by external scanner
integer: _ => token(choice(
seq(
choice('0x', '0X'),
repeat1(/_?[A-Fa-f0-9]+/),
optional(/[Ll]/),
),
seq(
choice('0o', '0O'),
repeat1(/_?[0-7]+/),
optional(/[Ll]/),
),
seq(
choice('0b', '0B'),
repeat1(/_?[0-1]+/),
optional(/[Ll]/),
),
seq(
repeat1(/[0-9]+_?/),
choice(
optional(/[Ll]/),
optional(/[jJ]/),
),
),
)),
float: _ => {
const digits = repeat1(/[0-9]+_?/);
const exponent = seq(/[eE][\+-]?/, digits);
return token(seq(
choice(
seq(digits, '.', optional(digits), optional(exponent)),
seq(optional(digits), '.', digits, optional(exponent)),
seq(digits, exponent),
),
optional(/[jJ]/),
));
},
identifier: _ => /[_\p{XID_Start}][_\p{XID_Continue}]*/,
true: _ => 'True',
false: _ => 'False',
none: _ => 'None',
comment: _ => token(seq('#', /.*/)),
line_continuation: _ => token(seq('\\', choice(seq(optional('\r'), '\n'), '\0'))),
},
});
function commaSep1(rule) {
return sep1(rule, ',');
}
function sep1(rule, separator) {
return seq(rule, repeat(seq(separator, rule)));
}