textbringer-tree-sitter 1.2.0 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,303 @@
1
+ <?php
2
+ // Line comment
3
+ # Hash comment
4
+ /* Block comment */
5
+ /**
6
+ * PHPDoc comment
7
+ * @param string $name
8
+ * @return string
9
+ */
10
+
11
+ declare(strict_types=1);
12
+
13
+ namespace App\Sample;
14
+
15
+ use App\Models\User;
16
+ use App\Services\{AuthService, MailService};
17
+ use function array_map;
18
+
19
+ // --- Constants ---
20
+ const APP_VERSION = '1.0.0';
21
+ define('MAX_RETRIES', 3);
22
+
23
+ // --- Interface ---
24
+ interface Greeter
25
+ {
26
+ public function greet(string $name): string;
27
+ }
28
+
29
+ // --- Trait ---
30
+ trait Loggable
31
+ {
32
+ private function log(string $message): void
33
+ {
34
+ echo "[LOG] {$message}\n";
35
+ }
36
+ }
37
+
38
+ // --- Abstract class ---
39
+ abstract class Animal
40
+ {
41
+ public function __construct(
42
+ protected readonly string $name,
43
+ protected int $age = 0,
44
+ ) {}
45
+
46
+ abstract public function speak(): string;
47
+
48
+ public function __toString(): string
49
+ {
50
+ return "{$this->name}: {$this->speak()}";
51
+ }
52
+ }
53
+
54
+ // --- Enum (PHP 8.1+) ---
55
+ enum Color: string
56
+ {
57
+ case Red = 'red';
58
+ case Green = 'green';
59
+ case Blue = 'blue';
60
+
61
+ public function label(): string
62
+ {
63
+ return match($this) {
64
+ self::Red => 'Red Color',
65
+ self::Green => 'Green Color',
66
+ self::Blue => 'Blue Color',
67
+ };
68
+ }
69
+ }
70
+
71
+ // --- Class ---
72
+ class Dog extends Animal implements Greeter
73
+ {
74
+ use Loggable;
75
+
76
+ private static int $count = 0;
77
+
78
+ public function __construct(
79
+ string $name,
80
+ int $age,
81
+ private readonly string $breed = 'Mixed',
82
+ ) {
83
+ parent::__construct($name, $age);
84
+ self::$count++;
85
+ }
86
+
87
+ public function speak(): string
88
+ {
89
+ return 'Woof!';
90
+ }
91
+
92
+ public function greet(string $name): string
93
+ {
94
+ $this->log("Greeting {$name}");
95
+ return "Woof! Hello, {$name}!";
96
+ }
97
+
98
+ public static function getCount(): int
99
+ {
100
+ return static::$count;
101
+ }
102
+
103
+ public function __destruct()
104
+ {
105
+ self::$count--;
106
+ }
107
+ }
108
+
109
+ // --- Strings ---
110
+ $single = 'single quoted';
111
+ $double = "Hello, {$_SERVER['SERVER_NAME']}!";
112
+ $heredoc = <<<EOT
113
+ This is a heredoc
114
+ with variable: $single
115
+ and expression: {$_SERVER['SERVER_NAME']}
116
+ EOT;
117
+ $nowdoc = <<<'EOT'
118
+ This is a nowdoc
119
+ no interpolation: $single
120
+ EOT;
121
+ $escaped = "tab\tnewline\n\\backslash";
122
+ $shell = `echo hello`;
123
+
124
+ // --- Numbers ---
125
+ $integer = 42;
126
+ $negative = -17;
127
+ $hex = 0xFF;
128
+ $octal = 0o77;
129
+ $binary = 0b1010;
130
+ $float = 3.14;
131
+ $scientific = 1.5e10;
132
+ $separator = 1_000_000;
133
+
134
+ // --- Booleans & Null ---
135
+ $yes = true;
136
+ $no = false;
137
+ $nothing = null;
138
+
139
+ // --- Arrays ---
140
+ $indexed = [1, 2, 3, 4, 5];
141
+ $assoc = [
142
+ 'name' => 'Alice',
143
+ 'age' => 30,
144
+ 'active' => true,
145
+ ];
146
+ $nested = [
147
+ 'users' => [
148
+ ['id' => 1, 'name' => 'Alice'],
149
+ ['id' => 2, 'name' => 'Bob'],
150
+ ],
151
+ ];
152
+
153
+ // --- Control flow ---
154
+ if ($integer > 0) {
155
+ echo "positive\n";
156
+ } elseif ($integer < 0) {
157
+ echo "negative\n";
158
+ } else {
159
+ echo "zero\n";
160
+ }
161
+
162
+ // --- Match expression (PHP 8.0+) ---
163
+ $result = match($integer) {
164
+ 0 => 'zero',
165
+ 1, 2, 3 => 'small',
166
+ default => 'other',
167
+ };
168
+
169
+ // --- Switch ---
170
+ switch ($integer) {
171
+ case 1:
172
+ echo "one\n";
173
+ break;
174
+ case 2:
175
+ echo "two\n";
176
+ break;
177
+ default:
178
+ echo "other\n";
179
+ break;
180
+ }
181
+
182
+ // --- Loops ---
183
+ for ($i = 0; $i < 10; $i++) {
184
+ if ($i === 5) break;
185
+ if ($i === 3) continue;
186
+ }
187
+
188
+ foreach ($indexed as $value) {
189
+ echo "{$value}\n";
190
+ }
191
+
192
+ foreach ($assoc as $key => $value) {
193
+ echo "{$key}: {$value}\n";
194
+ }
195
+
196
+ $j = 10;
197
+ while ($j > 0) {
198
+ $j--;
199
+ }
200
+
201
+ do {
202
+ $j++;
203
+ } while ($j < 5);
204
+
205
+ // --- Functions ---
206
+ function add(int $a, int $b): int
207
+ {
208
+ return $a + $b;
209
+ }
210
+
211
+ function greetPerson(string $name, string $greeting = 'Hello'): string
212
+ {
213
+ return "{$greeting}, {$name}!";
214
+ }
215
+
216
+ // --- Arrow function (PHP 7.4+) ---
217
+ $double = fn(int $x): int => $x * 2;
218
+
219
+ // --- Closure ---
220
+ $multiplier = 3;
221
+ $multiply = function (int $x) use ($multiplier): int {
222
+ return $x * $multiplier;
223
+ };
224
+
225
+ // --- Variadic ---
226
+ function sum(int ...$numbers): int
227
+ {
228
+ return array_sum($numbers);
229
+ }
230
+
231
+ // --- Named arguments (PHP 8.0+) ---
232
+ $greeting = greetPerson(name: 'World', greeting: 'Hi');
233
+
234
+ // --- Type declarations ---
235
+ function process(int|string $value, ?array $options = null): string|false
236
+ {
237
+ if (is_int($value)) {
238
+ return (string) $value;
239
+ }
240
+ return $value ?: false;
241
+ }
242
+
243
+ // --- Operators ---
244
+ $sum = 1 + 2;
245
+ $concat = 'Hello' . ' ' . 'World';
246
+ $spaceship = 1 <=> 2;
247
+ $nullCoalesce = $nothing ?? 'default';
248
+ $nullAssign = $nothing ??= 'assigned';
249
+ $spread = [...$indexed, 6, 7];
250
+
251
+ // --- Exception handling ---
252
+ try {
253
+ throw new \RuntimeException('Something went wrong');
254
+ } catch (\RuntimeException $e) {
255
+ echo "Caught: {$e->getMessage()}\n";
256
+ } catch (\Exception $e) {
257
+ echo "General: {$e->getMessage()}\n";
258
+ } finally {
259
+ echo "cleanup\n";
260
+ }
261
+
262
+ // --- Instanceof ---
263
+ $dog = new Dog('Rex', 5, 'Labrador');
264
+ if ($dog instanceof Animal) {
265
+ echo $dog->speak() . "\n";
266
+ }
267
+
268
+ // --- Clone ---
269
+ $clone = clone $dog;
270
+
271
+ // --- Goto ---
272
+ goto end;
273
+ echo "skipped\n";
274
+ end:
275
+ echo "done\n";
276
+
277
+ // --- Yield ---
278
+ function fibonacci(): \Generator
279
+ {
280
+ $a = 0;
281
+ $b = 1;
282
+ while (true) {
283
+ yield $a;
284
+ [$a, $b] = [$b, $a + $b];
285
+ }
286
+ }
287
+
288
+ // --- Include/Require ---
289
+ // include 'header.php';
290
+ // include_once 'config.php';
291
+ // require 'functions.php';
292
+ // require_once 'autoload.php';
293
+
294
+ // --- Global ---
295
+ function useGlobal(): void
296
+ {
297
+ global $integer;
298
+ echo $integer;
299
+ }
300
+
301
+ // --- Print/Echo ---
302
+ echo "Hello\n";
303
+ print("World\n");
data/samples/sample.py ADDED
@@ -0,0 +1,290 @@
1
+ # Single line comment
2
+
3
+ """
4
+ Module docstring.
5
+ Multi-line string used as comment.
6
+ """
7
+
8
+ # --- Imports ---
9
+ import os
10
+ import sys
11
+ from pathlib import Path
12
+ from typing import (
13
+ Any,
14
+ Dict,
15
+ List,
16
+ Optional,
17
+ Tuple,
18
+ Union,
19
+ )
20
+ from collections import defaultdict
21
+ from functools import wraps
22
+ import json as json_module
23
+
24
+ # --- Constants ---
25
+ MAX_SIZE = 100
26
+ PI = 3.14159
27
+ __all__ = ["Animal", "Dog", "greet"]
28
+
29
+ # --- Numbers ---
30
+ integer = 42
31
+ negative = -17
32
+ hex_val = 0xFF
33
+ octal = 0o77
34
+ binary = 0b1010
35
+ float_val = 3.14
36
+ scientific = 1.5e10
37
+ complex_val = 3 + 4j
38
+ separator = 1_000_000
39
+
40
+ # --- Strings ---
41
+ single = 'single quoted'
42
+ double = "double quoted"
43
+ triple_single = '''
44
+ triple single
45
+ quoted
46
+ '''
47
+ triple_double = """
48
+ triple double
49
+ quoted
50
+ """
51
+ raw = r"raw string \n no escape"
52
+ byte = b"byte string"
53
+ fstring = f"formatted: {integer + 1}"
54
+ fstring_nested = f"nested: {','.join(['a', 'b', 'c'])}"
55
+ escaped = "tab\tnewline\nnull\0"
56
+ unicode = "\u0048\u0065\u006C\u006C\u006F"
57
+
58
+ # --- Booleans & None ---
59
+ yes = True
60
+ no = False
61
+ nothing = None
62
+
63
+ # --- Variables ---
64
+ local_var = "local"
65
+
66
+ # --- Operators ---
67
+ sum_val = 1 + 2
68
+ diff = 5 - 3
69
+ prod = 4 * 2
70
+ quot = 10 / 3
71
+ floor_div = 10 // 3
72
+ modulo = 10 % 3
73
+ power = 2 ** 8
74
+ bit_and = 0xFF & 0x0F
75
+ bit_or = 0x10 | 0x01
76
+ bit_xor = 0xFF ^ 0x0F
77
+ bit_not = ~0
78
+ lshift = 1 << 4
79
+ rshift = 16 >> 2
80
+ logic = True and False or not None
81
+ identity = integer is not None
82
+ membership = 1 in [1, 2, 3]
83
+ comparison = 1 < 2 <= 3
84
+ walrus = (n := 10)
85
+ ternary = "yes" if yes else "no"
86
+
87
+ # --- Data structures ---
88
+ my_list = [1, 2, 3, 4, 5]
89
+ my_tuple = (1, 2, 3)
90
+ my_set = {1, 2, 3}
91
+ my_dict = {"name": "Alice", "age": 30}
92
+ empty_dict = {}
93
+ empty_list = []
94
+ empty_tuple = ()
95
+ empty_set = set()
96
+
97
+ # --- Comprehensions ---
98
+ list_comp = [x * 2 for x in range(10) if x % 2 == 0]
99
+ dict_comp = {k: v for k, v in my_dict.items()}
100
+ set_comp = {x ** 2 for x in range(5)}
101
+ gen_expr = sum(x for x in range(100))
102
+
103
+ # --- Functions ---
104
+ def greet(name: str, greeting: str = "Hello") -> str:
105
+ """Greet someone."""
106
+ return f"{greeting}, {name}!"
107
+
108
+
109
+ def variadic(*args: Any, **kwargs: Any) -> None:
110
+ """Function with variadic arguments."""
111
+ for arg in args:
112
+ print(arg)
113
+ for key, value in kwargs.items():
114
+ print(f"{key}={value}")
115
+
116
+
117
+ # --- Lambda ---
118
+ double = lambda x: x * 2
119
+ key_func = lambda item: item[1]
120
+
121
+ # --- Decorators ---
122
+ def my_decorator(func):
123
+ @wraps(func)
124
+ def wrapper(*args, **kwargs):
125
+ print(f"Calling {func.__name__}")
126
+ result = func(*args, **kwargs)
127
+ print(f"Done {func.__name__}")
128
+ return result
129
+ return wrapper
130
+
131
+
132
+ @my_decorator
133
+ def decorated_function():
134
+ """A decorated function."""
135
+ pass
136
+
137
+
138
+ # --- Classes ---
139
+ class Animal:
140
+ """Base animal class."""
141
+ count: int = 0
142
+
143
+ def __init__(self, name: str, age: int = 0) -> None:
144
+ self.name = name
145
+ self.age = age
146
+ Animal.count += 1
147
+
148
+ def speak(self) -> str:
149
+ raise NotImplementedError
150
+
151
+ def __repr__(self) -> str:
152
+ return f"{self.__class__.__name__}({self.name!r})"
153
+
154
+ def __str__(self) -> str:
155
+ return f"{self.name}: {self.speak()}"
156
+
157
+ @classmethod
158
+ def get_count(cls) -> int:
159
+ return cls.count
160
+
161
+ @staticmethod
162
+ def is_valid_name(name: str) -> bool:
163
+ return len(name) > 0
164
+
165
+ @property
166
+ def info(self) -> str:
167
+ return f"{self.name} (age {self.age})"
168
+
169
+
170
+ class Dog(Animal):
171
+ """Dog class."""
172
+
173
+ def __init__(self, name: str, age: int, breed: str = "Mixed") -> None:
174
+ super().__init__(name, age)
175
+ self._breed = breed
176
+
177
+ def speak(self) -> str:
178
+ return "Woof!"
179
+
180
+
181
+ # --- Control flow ---
182
+ if integer > 0:
183
+ print("positive")
184
+ elif integer < 0:
185
+ print("negative")
186
+ else:
187
+ print("zero")
188
+
189
+ # --- Match statement (Python 3.10+) ---
190
+ match integer:
191
+ case 0:
192
+ print("zero")
193
+ case n if n > 0:
194
+ print(f"positive: {n}")
195
+ case _:
196
+ print("negative")
197
+
198
+ match my_dict:
199
+ case {"name": str() as name, "age": int() as age}:
200
+ print(f"{name} is {age}")
201
+
202
+ # --- Loops ---
203
+ for i in range(10):
204
+ if i == 5:
205
+ break
206
+ if i == 3:
207
+ continue
208
+ print(i)
209
+ else:
210
+ print("completed")
211
+
212
+ j = 10
213
+ while j > 0:
214
+ j -= 1
215
+ else:
216
+ print("done")
217
+
218
+ # --- Exception handling ---
219
+ try:
220
+ raise ValueError("something went wrong")
221
+ except ValueError as e:
222
+ print(f"Caught: {e}")
223
+ except (TypeError, KeyError):
224
+ print("Type or Key error")
225
+ except Exception:
226
+ print("Unexpected")
227
+ else:
228
+ print("No error")
229
+ finally:
230
+ print("cleanup")
231
+
232
+ # --- Context manager ---
233
+ with open("/dev/null", "r") as f:
234
+ content = f.read()
235
+
236
+ # --- Assert ---
237
+ assert integer == 42, "Expected 42"
238
+
239
+ # --- Delete ---
240
+ temp = "to be deleted"
241
+ del temp
242
+
243
+ # --- Global/Nonlocal ---
244
+ def outer():
245
+ x = 10
246
+ def inner():
247
+ nonlocal x
248
+ x = 20
249
+ inner()
250
+
251
+ def use_global():
252
+ global integer
253
+ integer = 0
254
+
255
+ # --- Async/Await ---
256
+ async def fetch_data(url: str) -> dict:
257
+ """Async function example."""
258
+ pass
259
+
260
+ async def main():
261
+ result = await fetch_data("https://example.com")
262
+
263
+ # --- Generators ---
264
+ def fibonacci():
265
+ a, b = 0, 1
266
+ while True:
267
+ yield a
268
+ a, b = b, a + b
269
+
270
+ # --- Type aliases (Python 3.12+) ---
271
+ type Vector = list[float]
272
+ type Matrix = list[Vector]
273
+
274
+ # --- Unpacking ---
275
+ a, b, *rest = [1, 2, 3, 4, 5]
276
+ first, *middle, last = range(10)
277
+ {**my_dict, "extra": True}
278
+
279
+ # --- Slice ---
280
+ sliced = my_list[1:4]
281
+ stepped = my_list[::2]
282
+ reversed_list = my_list[::-1]
283
+
284
+ # --- Ellipsis ---
285
+ def placeholder() -> None:
286
+ ...
287
+
288
+ # --- exec/print as keywords ---
289
+ # (Python 2 compatibility noted in node map)
290
+ print("Hello, World!")