-
Notifications
You must be signed in to change notification settings - Fork 24
/
functions.py
3002 lines (2874 loc) · 126 KB
/
functions.py
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Copyright (c) 2013-2024 Matic Kukovec.
Released under the GNU GPL3 license.
For more information check the 'LICENSE.txt' file.
For complete license information of the dependencies, check the 'additional_licenses' directory.
"""
## FILE DESCRIPTION:
## Module that holds functions for various uses
## that uses only the PyQt and standard libraries.
import os
import os.path
import re
import ast
import sys
import json
import time
import codecs
import locale
import shutil
import timeit
import datetime
import operator
import itertools
import threading
import traceback
import subprocess
import webbrowser
import qt
import data
import constants
# REPL message displaying function (that needs to be assigned at runtime!)
repl_print = None
def write_json_file(filepath, json_data):
with open(filepath, 'w+', encoding='utf-8', newline='\n') as f:
f.write(json.dumps(json_data, indent=2, ensure_ascii=False))
f.close()
def load_json_file(filepath):
with open(filepath, 'r', encoding='utf-8', newline='\n') as f:
json_data = json.load(f)
f.close()
return json_data
def count_iterator(start=0):
counter = start
while True:
yield counter
counter += 1
def create_directory(directory):
if not os.path.isdir(directory):
os.mkdir(directory)
def create_thread(func, *args):
t = threading.Thread(target=func, args=args)
t.daemon = True
t.start()
icon_cache = {}
def create_icon(icon):
"""
Function for initializing and returning an QIcon object
"""
global icon_cache
# Pixmap
if isinstance(icon, qt.QPixmap):
new_icon = qt.QIcon(icon)
# Path
elif isinstance(icon, str):
full_icon_path = unixify_join(data.resources_directory, icon)
if full_icon_path in icon_cache.keys():
cached_icon = icon_cache[full_icon_path]
return qt.QIcon(cached_icon)
if not os.path.isfile(full_icon_path):
raise Exception("Icon file doesn't exist: {}".format(full_icon_path))
new_icon = qt.QIcon(full_icon_path)
icon_cache[full_icon_path] = new_icon
# Unknown
else:
raise Exception("Unknown icon construction type: {}".format(icon))
return new_icon
def get_resource_file(relative_path):
path = unixify_join(data.resources_directory, relative_path)
if not os.path.isfile(path):
raise Exception("[Resources] File does not exist: {}".format(path))
return path
pixmap_cache = {}
def create_pixmap(pixmap_name, directory=None):
"""
Function for initializing and returning an QPixmap object
"""
global pixmap_cache
if directory == None:
directory = data.resources_directory
pixmap_path = unixify_join(directory, pixmap_name)
if pixmap_path in pixmap_cache.keys():
cached_pixmap = pixmap_cache[pixmap_path]
return qt.QPixmap(cached_pixmap)
if not os.path.isfile(pixmap_path):
raise Exception("Pixmap file doesn't exist: {}".format(pixmap_path))
new_pixmap = qt.QPixmap(pixmap_path)
pixmap_cache[pixmap_path] = new_pixmap
return new_pixmap
def create_pixmap_with_size(pixmap_name, width=None, height=None):
"""
Function for initializing and returning an QPixmap object with a size
"""
pixmap = create_pixmap(pixmap_name)
if width:
pixmap = pixmap.scaledToWidth(
int(width), qt.Qt.TransformationMode.SmoothTransformation
)
if height:
pixmap = pixmap.scaledToHeight(
int(height), qt.Qt.TransformationMode.SmoothTransformation
)
return pixmap
__overlay_cache = {}
def ovarlay_images(base_path, overlay_path):
base_pixmap = create_pixmap(base_path)
if base_pixmap.isNull():
raise Exception(f"Cannot create base pixmap: {base_path}")
overlay_pixmap = create_pixmap(overlay_path)
if overlay_pixmap.isNull():
raise Exception(f"Cannot create base pixmap: {overlay_path}")
if overlay_pixmap.size().width() > base_pixmap.size().width() or overlay_pixmap.size().height() > base_pixmap.size().height():
overlay_pixmap = overlay_pixmap.scaled(base_pixmap.size(), qt.Qt.AspectRatioMode.KeepAspectRatio)
painter = qt.QPainter()
painter.begin(base_pixmap)
painter.drawPixmap(0, 0, overlay_pixmap)
painter.end()
return base_pixmap
def get_language_file_icon(language_name):
"""
Function for getting the programming language icon from the language name
"""
language_name = language_name.lower()
if language_name == "python":
return create_icon('language_icons/logo_python.png')
elif language_name == "cython":
return create_icon('language_icons/logo_cython.png')
elif language_name == "c":
return create_icon('language_icons/logo_c.png')
elif language_name == "awk":
return create_icon('language_icons/logo_awk.png')
elif language_name == "c++":
return create_icon('language_icons/logo_cpp.png')
elif language_name == "c / c++":
return create_icon('language_icons/logo_c_cpp.png')
elif language_name == "cicode":
return create_icon('language_icons/logo_cicode.png')
elif language_name == "oberon / modula":
return create_icon('language_icons/logo_oberon.png')
elif language_name == "d":
return create_icon('language_icons/logo_d.png')
elif language_name == "nim":
return create_icon('language_icons/logo_nim.png')
elif language_name == "ada":
return create_icon('language_icons/logo_ada.png')
elif language_name == "cmake":
return create_icon('language_icons/logo_cmake.png')
elif language_name == "css":
return create_icon('language_icons/logo_css.png')
elif language_name == "html":
return create_icon('language_icons/logo_html.png')
elif language_name == "json":
return create_icon('language_icons/logo_json.png')
elif language_name == "lua":
return create_icon('language_icons/logo_lua.png')
elif language_name == "matlab":
return create_icon('language_icons/logo_matlab.png')
elif language_name == "perl":
return create_icon('language_icons/logo_perl.png')
elif language_name == "ruby":
return create_icon('language_icons/logo_ruby.png')
elif language_name == "tcl":
return create_icon('language_icons/logo_tcl.png')
elif language_name == "tex":
return create_icon('language_icons/logo_tex.png')
elif language_name == "idl":
return create_icon('language_icons/logo_idl.png')
elif language_name == "bash":
return create_icon('language_icons/logo_bash.png')
elif language_name == "batch":
return create_icon('language_icons/logo_batch.png')
elif language_name == "fortran":
return create_icon('language_icons/logo_fortran.png')
elif language_name == "fortran77":
return create_icon('language_icons/logo_fortran77.png')
elif language_name == "ini" or language_name == "makefile":
return create_icon('tango_icons/document-properties.png')
elif language_name == "coffeescript":
return create_icon('language_icons/logo_coffeescript.png')
elif language_name == "c#":
return create_icon('language_icons/logo_csharp.png')
elif language_name == "java":
return create_icon('language_icons/logo_java.png')
elif language_name == "javascript":
return create_icon('language_icons/logo_javascript.png')
elif language_name == "makefile":
return create_icon('language_icons/logo_makefile.png')
elif language_name == "octave":
return create_icon('language_icons/logo_octave.png')
elif language_name == "pascal":
return create_icon('language_icons/logo_pascal.png')
elif language_name == "postscript":
return create_icon('language_icons/logo_postscript.png')
elif language_name == "routeros":
return create_icon('language_icons/logo_routeros.png')
elif language_name == "spice":
return create_icon('language_icons/logo_spice.png')
elif language_name == "sql":
return create_icon('language_icons/logo_sql.png')
elif language_name == "verilog":
return create_icon('language_icons/logo_verilog.png')
elif language_name == "vhdl":
return create_icon('language_icons/logo_vhdl.png')
elif language_name == "xml":
return create_icon('language_icons/logo_xml.png')
elif language_name == "yaml":
return create_icon('language_icons/logo_yaml.png')
elif language_name == "text":
return create_icon('tango_icons/text-x-generic.png')
else:
return create_icon("tango_icons/file.png")
def create_language_document_icon_from_path(path, check_content=True):
file_type = get_file_type(path, check_content)
return get_language_file_icon(file_type)
def get_file_size_Mb(file_with_path):
"""Get the file size in Mb"""
size_bytes = os.path.getsize(file_with_path)
#Convert size into megabytes
size_Mb = size_bytes / (1024 * 1024)
#return the size in megabyte
return size_Mb
def find_files_with_text(search_text,
search_dir,
case_sensitive=False,
search_subdirs=True,
break_on_find=False,
file_filter=None):
"""
Search for the specified text in files in the specified directory and return a file list.
"""
#Check if the directory is valid
if os.path.isdir(search_dir) == False:
return None
#Create an empty file list
text_file_list = []
#Check if subdirectories should be included
if search_subdirs == True:
walk_tree = os.walk(search_dir)
else:
#Only use the first generator value(only the top directory)
walk_tree = [next(os.walk(search_dir))]
#"walk" through the directory tree and save the readable files to a list
for root, subFolders, files in walk_tree:
for file in files:
if file_filter is not None:
filename, file_extension = os.path.splitext(file)
if file_extension.lower() not in file_filter:
continue
#Merge the path and filename
full_with_path = os.path.join(root, file)
if test_text_file(full_with_path) != None:
#On windows, the function "os.path.join(root, file)" line gives a combination of "/" and "\\",
#which looks weird but works. The replace was added to have things consistent in the return file list.
full_with_path = full_with_path.replace("\\", "/")
text_file_list.append(full_with_path)
#Search for the text in found files
return_file_list = []
for file in text_file_list:
try:
file_text = read_file_to_string(file)
#Set the comparison according to case sensitivity
if case_sensitive == False:
compare_file_text = file_text.lower()
compare_search_text = search_text.lower()
else:
compare_file_text = file_text
compare_search_text = search_text
# print(compare_search_text)
#Check if file contains the search string
if compare_search_text in compare_file_text:
return_file_list.append(file)
#Check if break option on first find is true
if break_on_find == True:
break
except:
continue
#Return the generated list
return return_file_list
def find_files_with_text_enum(search_text,
search_dir,
case_sensitive=False,
search_subdirs=True,
break_on_find=False,
file_filter=None):
"""
Search for the specified text in files in the specified directory and return a file list and
lines where the text was found at.
"""
# Check if the directory is valid
if os.path.isdir(search_dir) == False:
return "Invalid directory!"
# Check if searching over multiple lines
elif '\n' in search_text:
return "Cannot search over multiple lines!"
elif search_text == '':
return "Cannot search for empty string!"
#Create an empty file list
text_file_list = []
#Check if subdirectories should be included
if search_subdirs == True:
walk_tree = os.walk(search_dir)
else:
#Only use the first generator value(only the top directory)
walk_tree = [next(os.walk(search_dir))]
#"walk" through the directory tree and save the readable files to a list
for root, subFolders, files in walk_tree:
for file in files:
if file_filter is not None:
filename, file_extension = os.path.splitext(file)
if file_extension.lower() not in file_filter:
continue
#Merge the path and filename
full_with_path = os.path.join(root, file)
if test_text_file(full_with_path) is not None:
#On windows, the function "os.path.join(root, file)" line gives a combination of "/" and "\\",
#which looks weird but works. The replace was added to have things consistent in the return file list.
full_with_path = full_with_path.replace("\\", "/")
text_file_list.append(full_with_path)
#Search for the text in found files
return_file_dict = {}
break_out = False
for file in text_file_list:
if break_out == True:
break
try:
file_lines = read_file_to_list(file)
#Set the comparison according to case sensitivity
if case_sensitive == False:
compare_search_text = search_text.lower()
else:
compare_search_text = search_text
#Check the file line by line
for i, line in enumerate(file_lines):
if case_sensitive == False:
line = line.lower()
if compare_search_text in line:
if file in return_file_dict:
return_file_dict[file].append(i)
else:
return_file_dict[file] = [i]
#Check if break option on first find is true
if break_on_find == True:
break_out = True
except:
continue
#Return the generated list
return return_file_dict
def replace_text_in_files(search_text,
replace_text,
search_dir,
case_sensitive=False,
search_subdirs=True,
file_filter=None):
"""
Search for the specified text in files in the specified directory and replace all instances
of the search_text with replace_text and save the changes back to the file.
"""
#Get the files with the search string in them
found_files = find_files_with_text(
search_text,
search_dir,
case_sensitive=case_sensitive,
search_subdirs=search_subdirs,
break_on_find=False,
file_filter=file_filter
)
if found_files == None:
return []
#Loop through the found list and replace the text
for file in found_files:
#Read the file
file_text = read_file_to_string(file)
#Compile the regex expression according to case sensitivity
if case_sensitive == True:
compiled_search_re = re.compile(search_text)
else:
compiled_search_re = re.compile(search_text, re.IGNORECASE)
#Replace all instances of search text with the replace text
replaced_text = re.sub(compiled_search_re, replace_text, file_text)
#Write the replaced text back to the file
write_to_file(replaced_text, file)
#Return the found files list
return found_files
def replace_text_in_files_enum(search_text,
replace_text,
search_dir,
case_sensitive=False,
search_subdirs=True,
file_filter=None):
"""
The second version of replace_text_in_files, that goes line-by-line
and replaces found instances and stores the line numbers,
at which the replacements were made
"""
# Check if the directory is valid
if os.path.isdir(search_dir) == False:
return -1
# Check if searching over multiple lines
elif '\n' in search_text:
return -2
# Get the files with the search string in them
found_files = find_files_with_text(
search_text,
search_dir,
case_sensitive=case_sensitive,
search_subdirs=search_subdirs,
break_on_find=False,
file_filter=file_filter
)
if found_files == None:
return {}
# Compile the regex expression according to case sensitivity
if case_sensitive == True:
compiled_search_re = re.compile(search_text)
else:
compiled_search_re = re.compile(search_text, re.IGNORECASE)
# Loop through the found list and replace the text
return_files = {}
for file in found_files:
# Read the file
file_text_list = read_file_to_list(file)
# Cycle through the lines, replacing text and storing the line numbers of replacements
for i in range(len(file_text_list)):
if case_sensitive == True:
line = file_text_list[i]
else:
search_text = search_text.lower()
line = file_text_list[i].lower()
if search_text in line:
if file in return_files:
return_files[file].append(i)
else:
return_files[file] = [i]
file_text_list[i] = re.sub(compiled_search_re, replace_text, file_text_list[i])
# Write the replaced text back to the file
replaced_text = "\n".join(file_text_list)
write_to_file(replaced_text, file)
# Return the found files list
return return_files
def find_files_by_name(search_filename,
search_dir,
case_sensitive=False,
search_subdirs=True):
"""
Find file with search_filename string in its name in the specified directory.
"""
#Check if the directory is valid
if os.path.isdir(search_dir) == False:
return None
#Create an empty file list
found_file_list = []
#Check if subdirectories should be included
if search_subdirs == True:
walk_tree = os.walk(search_dir)
else:
#Only use the first generator value(only the top directory)
walk_tree = [next(os.walk(search_dir))]
for root, subFolders, files in walk_tree:
for file in files:
#Merge the path and filename
full_with_path = os.path.join(root, file)
#Set the comparison according to case sensitivity
if case_sensitive == False:
compare_actual_filename = file.lower()
compare_search_filename = search_filename.lower()
else:
compare_actual_filename = file
compare_search_filename = search_filename
#Test if the name of the file contains the search string
if compare_search_filename in compare_actual_filename:
#On windows, the function "os.path.join(root, file)" line gives a combination of "/" and "\\",
#which looks weird but works. The replace was added to have things consistent in the return file list.
full_with_path = full_with_path.replace("\\", "/")
found_file_list.append(full_with_path)
#Return the generated list
return found_file_list
def get_nim_node_tree(nim_code):
"""
Parse the text and return a node tree as a list.
The text must be valid Nim/Nimrod code.
"""
class NimNode():
def __init__(self):
#Attributes
self.name = None
self.description = None
self.type = None
self.parameters = None
self.return_type = None
self.line = None
#Child node lists
self.imports = []
self.types = []
self.consts = []
self.lets = []
self.vars = []
self.procedures = []
self.forward_declarations = []
self.converters = []
self.iterators = []
self.methods = []
self.properties = []
self.templates = []
self.macros = []
self.objects = []
self.namespaces = []
#Nested function for determining the next blocks indentation level
def get_next_blocks_indentation(current_step, lines):
for ln in range(current_step, len(lines)):
if lines[ln].strip() != "" and lines[ln].strip().startswith("#") == False:
return get_line_indentation(lines[ln])
else:
return 250
#Nested function for finding the closing parenthesis of parameter definitions
def get_closing_parenthesis(current_step, lines):
for ln in range(current_step, len(lines)):
if ")" in lines[ln] and (lines[ln].count(")") == (lines[ln].count("(") + 1)):
return ln
else:
return None
#Nested function for creating a procedure, method, macro or template node
def create_node(node,
search_string,
current_line,
current_line_number,
line_list,
previous_offset=0):
#Reset the procedure's starting line adjustment variable
body_starting_line_number = None
#Reset the local skip line variable
local_skip_to_line = None
#Parse procedure name according to the line characters
if "(" in current_line:
#The procedure has parameters
base_search_string = r"{:s}\s+(.*?)\(|{:s}\s+(.*?)\:|{:s}\s+(.*?)\=".format(
search_string,
search_string,
search_string
)
proc_name_search_pattern = re.compile(
base_search_string,
re.IGNORECASE
)
name_match_object = re.search(proc_name_search_pattern, current_line)
for i in range(1, 4):
node.name = name_match_object.group(i)
if node.name != "" and node.name != None:
break
#Skip lines if the parameters stretch over multiple lines
if not(")" in current_line):
body_starting_line_number = get_closing_parenthesis(
current_line_number+1,
line_list
)
current_line = line_list[body_starting_line_number]
#Parse the procedure parameters and return type
if search_string == "proc":
return_type = None
parameters = None
#Check if the parameters are declared over multiple lines
if body_starting_line_number != None:
parameter_string = ""
open_index = line_list[current_line_number].find("(") + 1
parameter_string += line_list[current_line_number][open_index:]
for i in range(current_line_number+1, body_starting_line_number+1):
if ")" in line_list[i] and (line_list[i].count(")") == (line_list[i].count("(") + 1)):
close_index = line_list[i].find(")")
current_parameter = line_list[i][:close_index].strip()
#Filter out the parameter initialization
if "=" in current_parameter:
current_parameter = current_parameter[:current_parameter.find("=")]
parameter_string += current_parameter
else:
current_parameter = line_list[i].strip()
#Filter out the parameter initialization
if "=" in current_parameter:
current_parameter = current_parameter[:current_parameter.find("=")]
parameter_string += current_parameter
parameters = [par.strip() for par in parameter_string.split(",") if par.strip() != ""]
#Check the return type
split_line = line_list[body_starting_line_number][close_index:].split(":")
if len(split_line) > 1:
return_type = split_line[1].replace("=", "")
return_type = return_type.strip()
else:
open_index = line_list[current_line_number].find("(") + 1
close_index = line_list[current_line_number].find(")")
parameter_string = line_list[current_line_number][open_index:close_index]
parameters = [par for par in parameter_string.split(",") if par.strip() != ""]
#Check the return type
split_line = line_list[current_line_number][close_index:].split(":")
if len(split_line) > 1:
return_type = split_line[1].replace("=", "")
return_type = return_type.strip()
node.parameters = parameters
node.return_type = return_type
elif ":" in current_line:
#The procedure/macro/... has no parameters, but has a return type
node.name = current_line.replace(search_string, "", 1).split(":")[0].strip()
#Special parsing for classes
if (search_string == "class" or
search_string == "property"):
node.name = node.name.split()[0]
else:
#The procedure/macro/... has no parameters and no return type
node.name = current_line.replace(search_string, "", 1).split()[0].strip()
#Parse node
if "=" in current_line and current_line.strip().endswith("="):
#Check if the declaration is a one-liner
if ((current_line.strip().endswith("=") == False) and
((len(current_line.split("=")) == 2 and
current_line.split("=")[1].strip() != "") or
(len(current_line.split("=")) > 2 and
current_line[current_line.rfind(")"):].split("=")[1] != ""))):
#One-liner
pass
else:
#Adjust the procedure body starting line as needed
starting_line_number = current_line_number + 1
if body_starting_line_number != None:
starting_line_number = body_starting_line_number + 1
#Parse the procedure for its local child nodes
sub_node_lines = []
compare_indentation = get_next_blocks_indentation(starting_line_number, line_list)
for ln in range(starting_line_number, len(line_list)):
#Skip empty lines
if line_list[ln].strip() == "" or line_list[ln].strip().startswith("#") == True:
#Add the blank space at the correct indentation level
#to have the correct number of lines in the list
sub_node_lines.append(" " * compare_indentation)
continue
elif get_line_indentation(line_list[ln]) < compare_indentation:
#Store the end of the procedure declaration
local_skip_to_line = ln
#Reached the last line of the procedure declaration
break
else:
sub_node_lines.append(line_list[ln])
else:
#For loop looped through all of the lines, skip them
local_skip_to_line = len(line_list) - 1
starting_line_number += previous_offset
node = parse_node(node, sub_node_lines, line_offset=starting_line_number)
elif (search_string == "class" or
search_string == "namespace" or
search_string == "property"):
"""special macro identifiers: class, namespace, ..."""
#Adjust the procedure body starting line as needed
starting_line_number = current_line_number + 1
if body_starting_line_number != None:
starting_line_number = body_starting_line_number + 1
#Parse the procedure for its local child nodes
sub_node_lines = []
compare_indentation = get_next_blocks_indentation(starting_line_number, line_list)
for ln in range(starting_line_number, len(line_list)):
#Skip empty lines
if line_list[ln].strip() == "" or line_list[ln].strip().startswith("#") == True:
#Add the blank space at the correct indentation level
#to have the correct number of lines in the list
sub_node_lines.append(" " * compare_indentation)
continue
elif get_line_indentation(line_list[ln]) < compare_indentation:
#Store the end of the procedure declaration
local_skip_to_line = ln
#Reached the last line of the procedure declaration
break
else:
sub_node_lines.append(line_list[ln])
else:
#For loop looped through all of the lines, skip them
local_skip_to_line = len(line_list) - 1
starting_line_number += previous_offset
node = parse_node(node, sub_node_lines, line_offset=starting_line_number)
else:
"""The procedure is a forward declaracion"""
node.type = "forward declaration"
#Return the relevant data
return node, local_skip_to_line
#Split the Nim code into lines
nim_code_lines = nim_code.split("\n")
#Create and initialize the main node that will hold all other nodes
main_node = NimNode()
main_node.name = "main"
main_node.description = "main node"
def parse_node(input_node, code_lines, line_offset=0):
#Initialize the starting indentation levels (number of spaces)
current_indentation = 0
compare_indentation = 0
#Initialize the various state flags
import_statement = False
type_statement = False
const_statement = False
let_statement = False
var_statement = False
proc_statement = False
converter_statement = False
iterator_statement = False
method_statement = False
macro_statement = False
template_statement = False
class_statement = False
namespace_statement = False
property_statement = False
#Initialize the flag for skipping multiple lines
skip_to_line = None
#Main loop
for line_count, line in enumerate(code_lines):
#Skip blank lines
if line.strip() == "" or line.strip().startswith("#"):
continue
#Check if line needs to be skipped
if skip_to_line != None:
if line_count >= skip_to_line:
skip_to_line = None
else:
continue
#Get line indentation and strip leading/trailing whitespaces
current_indentation = get_line_indentation(line)
line = line.strip()
#Discard the comment part of a line, if it's in the line
if "#" in line:
stringing = False
string_character = None
for ch_count, ch in enumerate(line):
if ch == "\"" or ch == "\'":
#Catch the string building characters
if stringing == False:
stringing = True
string_character = ch
elif ch == string_character:
stringing = False
string_character = None
elif ch == "#" and stringing == False:
#Discrad the part of the line from the
#comment character to the end of the line
line = line[:ch_count].strip()
break
if import_statement == True:
if current_indentation == compare_indentation:
for module in line.split(","):
module_name = module.strip()
if module_name != "":
import_node = NimNode()
import_node.name = module_name
import_node.description = "import"
import_node.line = line_count + line_offset
input_node.imports.append(import_node)
elif current_indentation < compare_indentation:
import_statement = False
elif type_statement == True:
if current_indentation == compare_indentation:
type_node = NimNode()
type_node.name = line.split("=")[0].strip()
type_node.description = "type"
type_node.line = line_count + line_offset
input_node.types.append(type_node)
elif current_indentation < compare_indentation:
type_statement = False
elif const_statement == True:
if current_indentation == compare_indentation:
const_node = NimNode()
if ":" in line:
const_node.name = line.split(":")[0].strip()
const_node.type = line.split(":")[1].split("=")[0].strip()
else:
const_node.name = line.split("=")[0].strip()
const_node.type = None
if const_node.name[0].isalpha():
const_node.description = "const"
const_node.line = line_count + line_offset
input_node.consts.append(const_node)
elif current_indentation < compare_indentation:
const_statement = False
elif let_statement == True:
if current_indentation == compare_indentation:
let_node = NimNode()
if ":" in line:
let_node.name = line.split(":")[0].strip()
let_node.type = line.split(":")[1].split("=")[0].strip()
else:
let_node.name = line.split("=")[0].strip()
let_node.type = None
if let_node.name[0].isalpha():
let_node.description = "let"
let_node.line = line_count + line_offset
input_node.lets.append(let_node)
elif current_indentation < compare_indentation:
let_statement = False
elif var_statement == True:
if current_indentation == compare_indentation:
if ":" in line and "=" in line and (line.find(":") < line.find("=")):
type = line.split(":")[1].split("=")[0].strip()
line = line.split(":")[0].strip()
elif ":" in line and not("=" in line):
type = line.split(":")[1].strip()
line = line.split(":")[0].strip()
elif "=" in line:
type = line.split("=")[1][:line.find("(")].strip()
line = line.split("=")[0].strip()
for var in line.split(","):
var_name = var.strip()
if var_name != "" and var_name[0].isalpha():
var_node = NimNode()
var_node.name = var.strip()
var_node.description = "var"
var_node.type = type
var_node.line = line_count + line_offset
input_node.vars.append(var_node)
elif current_indentation < compare_indentation:
var_statement = False
elif proc_statement == True:
proc_statement = False
elif converter_statement == True:
converter_statement = False
elif iterator_statement == True:
iterator_statement = False
elif method_statement == True:
method_statement = False
elif macro_statement == True:
macro_statement = False
elif template_statement == True:
template_statement = False
elif class_statement == True:
class_statement = False
elif namespace_statement == True:
namespace_statement = False
elif property_statement == True:
property_statement = False
#Testing for base level declarations
if line.startswith("import ") or line == "import":
if line == "import":
import_statement = True
compare_indentation = get_next_blocks_indentation(line_count+1, code_lines)
else:
line = line.replace("import", "")
for module in line.split(","):
module_name = module.strip()
if module_name != "":
import_node = NimNode()
import_node.name = module_name
import_node.description = "import"
import_node.line = line_count + line_offset
input_node.imports.append(import_node)
elif line.startswith("type ") or line == "type":
if line == "type":
type_statement = True
compare_indentation = get_next_blocks_indentation(line_count+1, code_lines)
else:
line = line.replace("type", "")
type_node = NimNode()
type_node.name = line.split("=")[0].strip()
type_node.description = "type"
type_node.line = line_count + line_offset
input_node.types.append(type_node)
elif line.startswith("const ") or line == "const":
if line == "const":
const_statement = True
compare_indentation = get_next_blocks_indentation(line_count+1, code_lines)
else:
line = line.replace("const", "")
const_node = NimNode()
if ":" in line:
const_node.name = line.split(":")[0].strip()
const_node.type = line.split(":")[1].split("=")[0].strip()
else:
const_node.name = line.split("=")[0].strip()
const_node.type = None
const_node.description = "const"
const_node.line = line_count + line_offset
input_node.consts.append(const_node)
elif line.startswith("let ") or line == "let":
if line == "let":
let_statement = True
compare_indentation = get_next_blocks_indentation(line_count+1, code_lines)
else:
line = line.replace("let", "")
let_node = NimNode()
if ":" in line:
let_node.name = line.split(":")[0].strip()
let_node.type = line.split(":")[1].split("=")[0].strip()
else:
let_node.name = line.split("=")[0].strip()
let_node.type = None
let_node.description = "let"
let_node.line = line_count + line_offset
input_node.lets.append(let_node)
elif line.startswith("var ") or line == "var":
if line == "var":
var_statement = True
compare_indentation = get_next_blocks_indentation(line_count+1, code_lines)
else:
line = line.replace("var", "")
if ":" in line and "=" in line and (line.find(":") < line.find("=")):
type = line.split(":")[1].split("=")[0].strip()
line = line.split(":")[0].strip()
elif ":" in line and not("=" in line):
type = line.split(":")[1].strip()
line = line.split(":")[0].strip()
elif "=" in line:
type = line.split("=")[1][:line.find("(")].strip()
line = line.split("=")[0].strip()
for var in line.split(","):
var_name = var.strip()
if var_name != "":
var_node = NimNode()
var_node.name = var_name
var_node.description = "var"
var_node.type = type
var_node.line = line_count + line_offset
input_node.vars.append(var_node)
elif line.startswith("proc "):
#Create and add the procedure node
proc_node = NimNode()
proc_node, skip_to_line = create_node(
proc_node,
"proc",
line,
line_count,
code_lines,
line_offset
)
proc_node.description = "procedure"
proc_node.line = line_count + line_offset
#Add the procedure to the main node
if proc_node.type == "forward declaration":
input_node.forward_declarations.append(proc_node)
else:
input_node.procedures.append(proc_node)
#Set the procedure flag
proc_statement = True
elif line.startswith("converter "):
#Create and add the converter node
converter_node = NimNode()
converter_node, skip_to_line = create_node(
converter_node,
"converter",
line,
line_count,
code_lines,
line_offset
)
converter_node.description = "converter"
converter_node.line = line_count + line_offset
#Add the converter to the main node
input_node.converters.append(converter_node)
#Set the converter flag
converter_statement = True
elif line.startswith("iterator "):
#Create and add the converter node
iterator_node = NimNode()
iterator_node, skip_to_line = create_node(
iterator_node,
"iterator",
line,
line_count,