-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpy_extractor.go
More file actions
1520 lines (1348 loc) · 31.1 KB
/
py_extractor.go
File metadata and controls
1520 lines (1348 loc) · 31.1 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
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
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
)
// PyExtractor extracts API surface from Python source files.
type PyExtractor struct{}
func init() {
registerExtractor(&PyExtractor{})
}
func (e *PyExtractor) Extensions() []string {
return []string{".py", ".pyi"}
}
func (e *PyExtractor) Extract(filePath string, exportedOnly bool) (*FileShape, error) {
data, err := os.ReadFile(filePath)
if err != nil {
return nil, fmt.Errorf("read error: %w", err)
}
ext := filepath.Ext(filePath)
base := filepath.Base(filePath)
pkg := strings.TrimSuffix(base, ext)
s := &pyScanner{src: string(data), line: 1, exportedOnly: exportedOnly}
shape := &FileShape{
File: filePath,
Package: pkg,
}
s.parse(shape)
return shape, nil
}
// Scanner
type pyScanner struct {
src string
pos int
line int
classIndent int // indent of current class line, -1 when not in class
skipIndent int // indent of block being skipped, -1 when not skipping
exportedOnly bool
currentClass *TypeDef // pointer to the class being built
}
func (s *pyScanner) eof() bool { return s.pos >= len(s.src) }
func (s *pyScanner) peek() byte {
if s.eof() {
return 0
}
return s.src[s.pos]
}
func (s *pyScanner) advance() {
if s.pos < len(s.src) {
if s.src[s.pos] == '\n' {
s.line++
}
s.pos++
}
}
// Line reading
// measureIndent counts the number of spaces at the beginning of the current line.
// Tabs count as 4 spaces each (matching Python convention).
func (s *pyScanner) measureIndent() int {
indent := 0
i := s.pos
for i < len(s.src) {
if s.src[i] == ' ' {
indent++
i++
} else if s.src[i] == '\t' {
indent += 4
i++
} else {
break
}
}
return indent
}
// skipToEndOfLine advances past everything until (and including) the newline.
func (s *pyScanner) skipToEndOfLine() {
for s.pos < len(s.src) && s.src[s.pos] != '\n' {
s.pos++
}
if s.pos < len(s.src) {
s.line++
s.pos++
}
}
// skipToNextLine is the same as skipToEndOfLine (alias for clarity).
func (s *pyScanner) skipToNextLine() {
s.skipToEndOfLine()
}
// skipIndentWhitespace advances past leading whitespace (spaces, tabs) without crossing newlines.
func (s *pyScanner) skipIndentWhitespace() {
for s.pos < len(s.src) {
ch := s.src[s.pos]
if ch == ' ' || ch == '\t' {
s.pos++
} else {
return
}
}
}
// isBlankLine checks if the current position is at a blank line (only whitespace before newline/EOF).
func (s *pyScanner) isBlankLine() bool {
i := s.pos
for i < len(s.src) {
ch := s.src[i]
if ch == '\n' || ch == '\r' {
return true
}
if ch != ' ' && ch != '\t' {
return false
}
i++
}
return true // EOF counts as blank
}
// isCommentLine checks if the current line (after indent whitespace) starts with #.
func (s *pyScanner) isCommentLine() bool {
i := s.pos
for i < len(s.src) {
ch := s.src[i]
if ch == '#' {
return true
}
if ch != ' ' && ch != '\t' {
return false
}
i++
}
return false
}
// Identifiers
func pyIsIdentStart(ch byte) bool {
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '_'
}
func pyIsIdentChar(ch byte) bool {
return pyIsIdentStart(ch) || (ch >= '0' && ch <= '9')
}
func (s *pyScanner) readWord() string {
start := s.pos
for s.pos < len(s.src) && pyIsIdentChar(s.src[s.pos]) {
s.pos++
}
return s.src[start:s.pos]
}
func (s *pyScanner) peekWord() string {
saved := s.pos
w := s.readWord()
s.pos = saved
return w
}
// Strings
// skipTripleQuotedString skips a triple-quoted string (""" or ”').
// The opening triple-quote has already been consumed.
func (s *pyScanner) skipTripleQuotedString(quote byte) {
for s.pos < len(s.src) {
if s.src[s.pos] == '\\' {
s.advance()
if !s.eof() {
s.advance()
}
continue
}
if s.src[s.pos] == quote && s.pos+2 < len(s.src) && s.src[s.pos+1] == quote && s.src[s.pos+2] == quote {
s.advance()
s.advance()
s.advance()
return
}
if s.src[s.pos] == '\n' {
s.line++
}
s.pos++
}
}
// isTripleQuote checks if current pos starts a triple-quote.
func (s *pyScanner) isTripleQuote() (byte, bool) {
if s.pos+2 >= len(s.src) {
return 0, false
}
ch := s.src[s.pos]
if (ch == '"' || ch == '\'') && s.src[s.pos+1] == ch && s.src[s.pos+2] == ch {
return ch, true
}
return 0, false
}
// skipSingleQuotedString skips a single-quoted string. The opening quote has NOT been consumed.
func (s *pyScanner) skipSingleQuotedString() {
quote := s.src[s.pos]
s.advance()
for !s.eof() {
c := s.src[s.pos]
if c == '\\' {
s.advance()
if !s.eof() {
s.advance()
}
continue
}
if c == quote {
s.advance()
return
}
if c == '\n' {
return
}
s.advance()
}
}
// skipStringAtPos skips any string literal at current position (checking for triple quotes first).
func (s *pyScanner) skipStringAtPos() {
if q, ok := s.isTripleQuote(); ok {
s.advance()
s.advance()
s.advance()
s.skipTripleQuotedString(q)
} else {
s.skipSingleQuotedString()
}
}
// skipStringPrefix skips f/r/b/u/rb/br string prefixes and returns true if a quote follows.
func (s *pyScanner) skipStringPrefix() bool {
start := s.pos
for s.pos < len(s.src) {
ch := s.src[s.pos]
if ch == 'f' || ch == 'r' || ch == 'b' || ch == 'u' || ch == 'F' || ch == 'R' || ch == 'B' || ch == 'U' {
s.pos++
} else {
break
}
}
if s.pos > start && s.pos < len(s.src) && (s.src[s.pos] == '"' || s.src[s.pos] == '\'') {
return true
}
s.pos = start
return false
}
// Comments
func (s *pyScanner) skipComment() {
for s.pos < len(s.src) && s.src[s.pos] != '\n' {
s.pos++
}
}
// Visibility
func pyIsPrivate(name string) bool {
if len(name) == 0 {
return false
}
// Dunder names (__name__) are public
if len(name) >= 4 && name[0] == '_' && name[1] == '_' && name[len(name)-1] == '_' && name[len(name)-2] == '_' {
return false
}
// Single underscore prefix or double underscore prefix (name mangling) = private
if name[0] == '_' {
return true
}
return false
}
// Import parsing
// readDottedName reads a dotted name like "foo.bar.baz".
// For relative imports, leading dots are preserved.
func (s *pyScanner) readDottedName() string {
var buf strings.Builder
// Handle leading dots for relative imports
for s.pos < len(s.src) && s.src[s.pos] == '.' {
buf.WriteByte('.')
s.pos++
}
s.skipInlineWhitespace()
// Check if next word is a keyword like "import" - don't consume it
if s.pos < len(s.src) && pyIsIdentStart(s.src[s.pos]) {
w := s.peekWord()
if w == "import" {
return buf.String()
}
s.readWord()
buf.WriteString(w)
for s.pos < len(s.src) && s.src[s.pos] == '.' {
s.pos++
if s.pos < len(s.src) && pyIsIdentStart(s.src[s.pos]) {
next := s.peekWord()
if next == "import" {
// Put the dot back - it was a separator before "import"
// Actually we consumed the dot, but "import" is the keyword
// This shouldn't happen in valid Python, but be safe
s.pos-- // unconsume the dot
break
}
s.readWord()
buf.WriteByte('.')
buf.WriteString(next)
}
}
}
return buf.String()
}
// skipInlineWhitespace skips spaces and tabs but not newlines.
func (s *pyScanner) skipInlineWhitespace() {
for s.pos < len(s.src) {
ch := s.src[s.pos]
if ch == ' ' || ch == '\t' {
s.pos++
} else {
return
}
}
}
// skipInlineWhitespaceAndComments skips spaces, tabs, and # comments within a line.
// Also handles backslash line continuation.
func (s *pyScanner) skipInlineWhitespaceAndContinuation() {
for s.pos < len(s.src) {
ch := s.src[s.pos]
if ch == ' ' || ch == '\t' {
s.pos++
} else if ch == '\\' && s.pos+1 < len(s.src) && s.src[s.pos+1] == '\n' {
s.pos++
s.line++
s.pos++
} else if ch == '#' {
for s.pos < len(s.src) && s.src[s.pos] != '\n' {
s.pos++
}
} else {
return
}
}
}
// parseImportStatement parses "import foo, foo.bar as baz".
func (s *pyScanner) parseImportStatement(shape *FileShape) {
s.skipInlineWhitespace()
for {
s.skipInlineWhitespace()
if s.eof() || s.src[s.pos] == '\n' || s.src[s.pos] == '#' {
break
}
module := s.readDottedName()
if module == "" {
break
}
s.skipInlineWhitespace()
if s.peekWord() == "as" {
s.readWord()
s.skipInlineWhitespace()
alias := s.readWord()
if alias != "" {
shape.Imports = append(shape.Imports, alias+" "+module)
} else {
shape.Imports = append(shape.Imports, module)
}
} else {
shape.Imports = append(shape.Imports, module)
}
s.skipInlineWhitespace()
if s.pos < len(s.src) && s.src[s.pos] == ',' {
s.pos++
} else {
break
}
}
}
// parseFromImportStatement parses "from foo import bar, baz as qux".
func (s *pyScanner) parseFromImportStatement(shape *FileShape) {
s.skipInlineWhitespace()
module := s.readDottedName()
if module == "" {
s.skipToEndOfLine()
return
}
s.skipInlineWhitespace()
if s.peekWord() != "import" {
s.skipToEndOfLine()
return
}
s.readWord() // consume "import"
s.skipInlineWhitespace()
// Check for parenthesized imports
paren := false
if s.pos < len(s.src) && s.src[s.pos] == '(' {
paren = true
s.pos++
}
// Check for star import
if s.pos < len(s.src) && s.src[s.pos] == '*' {
s.pos++
shape.Imports = append(shape.Imports, module+".*")
s.skipToEndOfLine()
return
}
for {
if paren {
s.skipParenWhitespace()
} else {
s.skipInlineWhitespace()
}
if s.eof() {
break
}
if paren && s.src[s.pos] == ')' {
s.pos++
break
}
if !paren && (s.src[s.pos] == '\n' || s.src[s.pos] == '#') {
break
}
name := s.readWord()
if name == "" {
if paren {
// Skip any stray characters
s.advance()
continue
}
break
}
if paren {
s.skipParenWhitespace()
} else {
s.skipInlineWhitespace()
}
if s.peekWord() == "as" {
s.readWord()
if paren {
s.skipParenWhitespace()
} else {
s.skipInlineWhitespace()
}
alias := s.readWord()
if alias != "" {
shape.Imports = append(shape.Imports, alias+" "+module+"."+name)
} else {
shape.Imports = append(shape.Imports, module+"."+name)
}
} else {
shape.Imports = append(shape.Imports, module+"."+name)
}
if paren {
s.skipParenWhitespace()
} else {
s.skipInlineWhitespace()
}
if s.pos < len(s.src) && s.src[s.pos] == ',' {
s.pos++
} else if !paren {
break
}
}
}
// skipParenWhitespace skips whitespace including newlines inside parenthesized imports.
func (s *pyScanner) skipParenWhitespace() {
for s.pos < len(s.src) {
ch := s.src[s.pos]
if ch == ' ' || ch == '\t' || ch == '\r' {
s.pos++
} else if ch == '\n' {
s.line++
s.pos++
} else if ch == '#' {
for s.pos < len(s.src) && s.src[s.pos] != '\n' {
s.pos++
}
} else if ch == '\\' && s.pos+1 < len(s.src) && s.src[s.pos+1] == '\n' {
s.pos++
s.line++
s.pos++
} else {
return
}
}
}
// Signature reading
// readSignature reads a function signature from the current position (starting at '(')
// and returns the normalized signature string. Handles multi-line signatures, comments,
// and type annotations.
func (s *pyScanner) readSignature() string {
if s.eof() || s.src[s.pos] != '(' {
return "()"
}
s.pos++ // skip (
depth := 1
var parts []byte
parts = append(parts, '(')
lastWasSpace := false
for !s.eof() && depth > 0 {
ch := s.src[s.pos]
switch {
case ch == '#':
// Skip comment to end of line
for s.pos < len(s.src) && s.src[s.pos] != '\n' {
s.pos++
}
continue
case ch == '\n':
s.line++
s.pos++
// Treat newline as space
if !lastWasSpace && len(parts) > 0 && parts[len(parts)-1] != '(' {
parts = append(parts, ' ')
lastWasSpace = true
}
continue
case ch == '\r':
s.pos++
continue
case ch == '\\' && s.pos+1 < len(s.src) && s.src[s.pos+1] == '\n':
s.pos++
s.line++
s.pos++
continue
case ch == '(':
depth++
parts = append(parts, ch)
lastWasSpace = false
s.pos++
case ch == ')':
depth--
if depth == 0 {
// Trim trailing space and comma before )
for len(parts) > 1 && (parts[len(parts)-1] == ' ' || parts[len(parts)-1] == ',') {
parts = parts[:len(parts)-1]
}
parts = append(parts, ')')
s.pos++
} else {
parts = append(parts, ch)
lastWasSpace = false
s.pos++
}
case ch == '[':
// Read bracket expression (type annotations like List[int])
parts = append(parts, ch)
lastWasSpace = false
s.pos++
case ch == ']':
parts = append(parts, ch)
lastWasSpace = false
s.pos++
case ch == '"' || ch == '\'':
// String in default value
start := s.pos
s.skipStringAtPos()
parts = append(parts, s.src[start:s.pos]...)
lastWasSpace = false
case ch == ' ' || ch == '\t':
if !lastWasSpace && len(parts) > 0 && parts[len(parts)-1] != '(' {
parts = append(parts, ' ')
lastWasSpace = true
}
s.pos++
default:
parts = append(parts, ch)
lastWasSpace = false
s.pos++
}
}
// Read return type annotation
s.skipInlineWhitespace()
if s.pos+1 < len(s.src) && s.src[s.pos] == '-' && s.src[s.pos+1] == '>' {
s.pos += 2
s.skipInlineWhitespace()
retStart := s.pos
// Read until colon or newline
bracketDepth := 0
for s.pos < len(s.src) {
rc := s.src[s.pos]
if rc == '[' {
bracketDepth++
s.pos++
} else if rc == ']' {
bracketDepth--
s.pos++
} else if rc == ':' && bracketDepth == 0 {
break
} else if rc == '\n' {
break
} else if rc == '#' {
break
} else {
s.pos++
}
}
retType := strings.TrimSpace(s.src[retStart:s.pos])
if retType != "" {
return string(parts) + " -> " + retType
}
}
return string(parts)
}
// Simple value reading
// peekSimpleValue reads a simple literal value without advancing the scanner permanently.
func (s *pyScanner) peekSimpleValue() string {
saved := s.pos
savedLine := s.line
s.skipInlineWhitespace()
if s.eof() || s.src[s.pos] == '\n' {
s.pos = saved
s.line = savedLine
return ""
}
ch := s.peek()
var result string
switch {
case ch == '"' || ch == '\'':
if q, ok := s.isTripleQuote(); ok {
// Triple-quoted string: read it but don't extract value (too long)
_ = q
} else {
start := s.pos
s.skipSingleQuotedString()
result = s.src[start:s.pos]
}
case ch >= '0' && ch <= '9':
start := s.pos
for !s.eof() {
c := s.peek()
isDigit := c >= '0' && c <= '9'
isHex := (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
isMeta := c == '.' || c == 'x' || c == 'X' || c == 'e' || c == 'E' || c == '+' || c == '-' || c == '_' || c == 'o' || c == 'O' || c == 'b' || c == 'B' || c == 'j' || c == 'J'
if !isDigit && !isHex && !isMeta {
break
}
s.advance()
}
result = s.src[start:s.pos]
case ch == '-' && s.pos+1 < len(s.src) && s.src[s.pos+1] >= '0' && s.src[s.pos+1] <= '9':
start := s.pos
s.advance() // skip -
for !s.eof() {
c := s.peek()
isDigit := c >= '0' && c <= '9'
isMeta := c == '.' || c == 'e' || c == 'E' || c == '+' || c == '-' || c == '_' || c == 'j' || c == 'J'
if !isDigit && !isMeta {
break
}
s.advance()
}
result = s.src[start:s.pos]
default:
if pyIsIdentStart(ch) {
w := s.peekWord()
if w == "True" || w == "False" || w == "None" {
result = w
} else if ch == 'f' || ch == 'r' || ch == 'b' || ch == 'u' || ch == 'F' || ch == 'R' || ch == 'B' || ch == 'U' {
// Check for string prefix
prefixStart := s.pos
if s.skipStringPrefix() {
start := prefixStart
s.skipStringAtPos()
result = s.src[start:s.pos]
}
}
}
}
s.pos = saved
s.line = savedLine
return result
}
// Decorator reading
// readFirstDecorator reads a single decorator when the scanner is already positioned at '@'.
func (s *pyScanner) readFirstDecorator() []string {
s.pos++ // skip @
name := s.readWord()
for s.pos < len(s.src) && s.src[s.pos] == '.' {
s.pos++
name += "." + s.readWord()
}
// Skip decorator arguments if present
if s.pos < len(s.src) && s.src[s.pos] == '(' {
depth := 1
s.pos++
for s.pos < len(s.src) && depth > 0 {
c := s.src[s.pos]
if c == '(' {
depth++
} else if c == ')' {
depth--
} else if c == '\n' {
s.line++
} else if c == '"' || c == '\'' {
s.skipStringAtPos()
continue
}
s.pos++
}
}
result := []string{"@" + name}
s.skipToNextLine()
return result
}
// readDecorators reads decorator lines starting with @ and returns them as a list.
func (s *pyScanner) readDecorators(indent int) []string {
var decorators []string
for {
savedPos := s.pos
savedLine := s.line
// Check if current line is blank or comment - skip
if s.isBlankLine() {
s.skipToNextLine()
continue
}
if s.isCommentLine() {
s.skipToNextLine()
continue
}
lineIndent := s.measureIndent()
if lineIndent != indent {
s.pos = savedPos
s.line = savedLine
break
}
s.skipIndentWhitespace()
if s.eof() || s.src[s.pos] != '@' {
s.pos = savedPos
s.line = savedLine
break
}
s.pos++ // skip @
// Read decorator name (possibly dotted)
name := s.readWord()
for s.pos < len(s.src) && s.src[s.pos] == '.' {
s.pos++
name += "." + s.readWord()
}
// Skip decorator arguments if present
if s.pos < len(s.src) && s.src[s.pos] == '(' {
depth := 1
s.pos++
for s.pos < len(s.src) && depth > 0 {
c := s.src[s.pos]
if c == '(' {
depth++
} else if c == ')' {
depth--
} else if c == '\n' {
s.line++
} else if c == '"' || c == '\'' {
s.skipStringAtPos()
continue
}
s.pos++
}
}
decorators = append(decorators, "@"+name)
s.skipToNextLine()
}
return decorators
}
// Main parse loop
func (s *pyScanner) parse(shape *FileShape) {
s.classIndent = -1
s.skipIndent = -1
for !s.eof() {
// Skip blank lines (no scope transitions)
if s.isBlankLine() {
s.skipToNextLine()
continue
}
// Skip comment-only lines (no scope transitions)
if s.isCommentLine() {
s.skipToNextLine()
continue
}
indent := s.measureIndent()
s.skipIndentWhitespace()
if s.eof() {
break
}
ch := s.src[s.pos]
// Handle triple-quoted strings at any position (docstrings, etc.)
if ch == '"' || ch == '\'' {
if q, ok := s.isTripleQuote(); ok {
s.advance()
s.advance()
s.advance()
s.skipTripleQuotedString(q)
s.skipToNextLine()
continue
}
}
// Scope transitions based on indentation
// If we are skipping a block and this line is deeper, skip it
if s.skipIndent >= 0 && indent > s.skipIndent {
s.skipToNextLine()
continue
}
// If we were skipping and line is at or less than skipIndent, stop skipping
if s.skipIndent >= 0 && indent <= s.skipIndent {
s.skipIndent = -1
}
// If we are in a class and this line is at or less than classIndent, leave class
if s.classIndent >= 0 && indent <= s.classIndent {
s.finishClass(shape)
}
// Determine what level we're at
atModuleLevel := indent == 0 && s.classIndent < 0
atClassLevel := s.classIndent >= 0 && indent > s.classIndent && s.skipIndent < 0
// Handle string prefixes (f"...", r"...", etc.)
if pyIsIdentStart(ch) {
savedPos := s.pos
if s.skipStringPrefix() {
s.skipStringAtPos()
s.skipToNextLine()
continue
}
s.pos = savedPos
}
// Parse based on first keyword
word := s.peekWord()
switch word {
case "import":
if atModuleLevel {
s.readWord()
s.parseImportStatement(shape)
}
s.skipToNextLine()
case "from":
if atModuleLevel {
s.readWord()
s.parseFromImportStatement(shape)
}
s.skipToNextLine()
case "class":
if atModuleLevel {
s.parseClassDef(shape, indent)
} else if atClassLevel {
// Nested class inside a class body: skip its block
s.skipIndent = indent
s.skipToNextLine()
} else {
s.skipToNextLine()
}
case "def":
if atModuleLevel {
s.parseFuncDef(shape, nil, indent)
} else if atClassLevel {
s.parseFuncDef(shape, s.currentClass, indent)
} else {
s.skipToNextLine()
}
case "async":
s.readWord()
s.skipInlineWhitespace()
if s.peekWord() == "def" {
if atModuleLevel {
s.parseAsyncFuncDef(shape, nil, indent)
} else if atClassLevel {
s.parseAsyncFuncDef(shape, s.currentClass, indent)
} else {
s.skipToNextLine()
}
} else {
s.skipToNextLine()
}
case "if", "for", "while", "with", "try", "except", "finally", "else", "elif":
if atModuleLevel || atClassLevel {
s.skipIndent = indent
}
s.skipToNextLine()
case "":
if ch == '@' {
// Read the first decorator (we're already positioned at @)
decorators := s.readFirstDecorator()
// Read any subsequent decorators from following lines
more := s.readDecorators(indent)
decorators = append(decorators, more...)
// After decorators, we should be at the def/class line
if !s.eof() {
nextIndent := s.measureIndent()
s.skipIndentWhitespace()
nextWord := s.peekWord()
switch nextWord {
case "def":
if atModuleLevel {
s.parseDecoratedFuncDef(shape, nil, nextIndent, decorators)
} else if atClassLevel {
s.parseDecoratedFuncDef(shape, s.currentClass, nextIndent, decorators)
} else {
s.skipToNextLine()
}
case "async":
s.readWord()
s.skipInlineWhitespace()
if s.peekWord() == "def" {
if atModuleLevel {
s.parseDecoratedAsyncFuncDef(shape, nil, nextIndent, decorators)
} else if atClassLevel {
s.parseDecoratedAsyncFuncDef(shape, s.currentClass, nextIndent, decorators)
} else {
s.skipToNextLine()
}
} else {
s.skipToNextLine()
}
case "class":
if indent == 0 && s.classIndent < 0 {
s.parseDecoratedClassDef(shape, nextIndent, decorators)
} else {
s.skipToNextLine()
}
default:
s.skipToNextLine()