@@ -133,17 +133,18 @@ def __str__(m):
133
133
def print_token_count (num_tokens , ** kwargs ):
134
134
print_size ("tokens" , num_tokens , 8192 , ** kwargs )
135
135
136
- def process_code (ctxt , source , input_count = False , count = False , lint = False , minify = False , rename = False , fail = True , want_count = True ):
136
+ def process_code (ctxt , source , input_count = False , count = False , lint = False , minify = False , rename = False , fail = True , want_count = True , annotate = False ):
137
137
need_lint = lint not in (None , False )
138
138
need_minify = minify not in (None , False )
139
139
need_rename = rename not in (None , False )
140
+ need_annotate = annotate not in (None , False )
140
141
141
- if not need_lint and not need_minify and not (want_count and (count or input_count )):
142
+ if not need_lint and not need_minify and not (want_count and (count or input_count )) and not need_annotate :
142
143
return True , ()
143
144
144
145
ok = False
145
146
tokens , errors = tokenize (source , ctxt )
146
- if not errors and (need_lint or need_minify ):
147
+ if not errors and (need_lint or need_minify or need_annotate ):
147
148
root , errors = parse (source , tokens )
148
149
149
150
if not errors :
@@ -164,10 +165,30 @@ def process_code(ctxt, source, input_count=False, count=False, lint=False, minif
164
165
if count :
165
166
print_token_count (count_tokens (tokens ), handler = count )
166
167
168
+ if annotate :
169
+ annotate_code (ctxt , source , root )
170
+
167
171
if fail and errors :
168
172
raise Exception ("\n " .join (map (str , errors )))
169
173
return ok , errors
170
174
175
+ # Calls function for the descendants of node, then for node
176
+ def apply_node_tree (node , func ):
177
+ if hasattr (node , "extra_children" ):
178
+ for child in reversed (node .extra_children ):
179
+ apply_node_tree (child , func )
180
+ for child in reversed (node .children ):
181
+ apply_node_tree (child , func )
182
+ func (node )
183
+
184
+ def annotate_code (ctxt , source , root ):
185
+ def comment_before_function (node , source = source ):
186
+ if node .type == NodeType .function :
187
+ tokens , errors = tokenize (PicoSource ("temp" , source .text [node .idx :node .endidx ]), ctxt )
188
+ count = count_tokens (tokens )
189
+ source .text = f'{ source .text [:node .idx ]} -- token count: { count } \n { source .text [node .idx :]} '
190
+ apply_node_tree (root , comment_before_function )
191
+
171
192
def echo_code (code , echo = True ):
172
193
code = from_pico_chars (code )
173
194
if echo == True :
@@ -181,6 +202,7 @@ def echo_code(code, echo=True):
181
202
from pico_lint import lint_code
182
203
from pico_minify import minify_code
183
204
from pico_rename import rename_tokens
205
+ from pico_parse import NodeType
184
206
185
207
# re-export some things for examples/etc.
186
208
from pico_tokenize import is_identifier , is_ident_char , CustomPreprocessor
0 commit comments