fork download
  1. %{
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5.  
  6. int line_num = 1;
  7. int error_count = 0;
  8. int indent_level = 0;
  9. int paren_count = 0;
  10. int brace_count = 0;
  11. int bracket_count = 0;
  12.  
  13. void print_token(const char *type, const char *lexeme) {
  14. printf("Line %d: \t%-30s \t%s\n", line_num, type, lexeme);
  15. }
  16.  
  17. void print_error(const char *message, const char *lexeme) {
  18. printf("Line %d: \tERROR: %-30s \t%s\n", line_num, message, lexeme);
  19. error_count++;
  20. }
  21. %}
  22.  
  23. %option noyywrap
  24.  
  25. DIGIT [0-9]
  26. LETTER [a-zA-Z_]
  27. ALPHANUM {LETTER}|{DIGIT}
  28. ID {LETTER}{ALPHANUM}*
  29.  
  30. INT_NUM {DIGIT}+
  31. FLOAT_NUM {DIGIT}*\.{DIGIT}+([eE][-+]?{DIGIT}+)?
  32. HEX_NUM 0[xX][0-9a-fA-F]+
  33. OCT_NUM 0[oO][0-7]+
  34. BIN_NUM 0[bB][01]+
  35. COMPLEX_NUM ({FLOAT_NUM}|{INT_NUM})[jJ]
  36.  
  37. STRING_SQ \'([^'\\\n]|\\.)*\'?
  38. STRING_DQ \"([^"\\\n]|\\.)*\"?
  39. F_STRING_SQ f\'([^'\\\n]|\\.)*\'?
  40. F_STRING_DQ f\"([^"\\\n]|\\.)*\"?
  41. TRIPLE_SQ \'\'\'([^\\]|\\.)*?\'\'\'
  42. TRIPLE_DQ \"\"\"([^\\]|\\.)*?\"\"\"
  43. F_TRIPLE_SQ f\'\'\'([^\\]|\\.)*?\'\'\'
  44. F_TRIPLE_DQ f\"\"\"([^\\]|\\.)*?\"\"\"
  45.  
  46. COMMENT #.*
  47.  
  48. %%
  49.  
  50. {COMMENT} { print_token("COMMENT", yytext); }
  51.  
  52. "def" { print_token("KEYWORD_DEF", yytext); }
  53. "class" { print_token("KEYWORD_CLASS", yytext); }
  54. "return" { print_token("KEYWORD_RETURN", yytext); }
  55. "if" { print_token("KEYWORD_IF", yytext); }
  56. "elif" { print_token("KEYWORD_ELIF", yytext); }
  57. "else" { print_token("KEYWORD_ELSE", yytext); }
  58. "while" { print_token("KEYWORD_WHILE", yytext); }
  59. "for" { print_token("KEYWORD_FOR", yytext); }
  60. "in" { print_token("KEYWORD_IN", yytext); }
  61. "import" { print_token("KEYWORD_IMPORT", yytext); }
  62. "from" { print_token("KEYWORD_FROM", yytext); }
  63. "as" { print_token("KEYWORD_AS", yytext); }
  64. "try" { print_token("KEYWORD_TRY", yytext); }
  65. "except" { print_token("KEYWORD_EXCEPT", yytext); }
  66. "finally" { print_token("KEYWORD_FINALLY", yytext); }
  67. "raise" { print_token("KEYWORD_RAISE", yytext); }
  68. "assert" { print_token("KEYWORD_ASSERT", yytext); }
  69. "with" { print_token("KEYWORD_WITH", yytext); }
  70. "lambda" { print_token("KEYWORD_LAMBDA", yytext); }
  71. "pass" { print_token("KEYWORD_PASS", yytext); }
  72. "break" { print_token("KEYWORD_BREAK", yytext); }
  73. "continue" { print_token("KEYWORD_CONTINUE", yytext); }
  74. "del" { print_token("KEYWORD_DEL", yytext); }
  75. "global" { print_token("KEYWORD_GLOBAL", yytext); }
  76. "nonlocal" { print_token("KEYWORD_NONLOCAL", yytext); }
  77. "yield" { print_token("KEYWORD_YIELD", yytext); }
  78. "async" { print_token("KEYWORD_ASYNC", yytext); }
  79. "await" { print_token("KEYWORD_AWAIT", yytext); }
  80.  
  81. "and" { print_token("KEYWORD_AND", yytext); }
  82. "or" { print_token("KEYWORD_OR", yytext); }
  83. "not" { print_token("KEYWORD_NOT", yytext); }
  84. "is" { print_token("KEYWORD_IS", yytext); }
  85.  
  86. "True" { print_token("BOOLEAN_TRUE", yytext); }
  87. "False" { print_token("BOOLEAN_FALSE", yytext); }
  88. "None" { print_token("NONE_TYPE", yytext); }
  89. "Ellipsis" { print_token("ELLIPSIS_KEYWORD", yytext); }
  90.  
  91. "+" { print_token("OP_PLUS", yytext); }
  92. "-" { print_token("OP_MINUS", yytext); }
  93. "*" { print_token("OP_MULT", yytext); }
  94. "/" { print_token("OP_DIV", yytext); }
  95. "%" { print_token("OP_MOD", yytext); }
  96. "**" { print_token("OP_POWER", yytext); }
  97. "//" { print_token("OP_FLOOR_DIV", yytext); }
  98. "=" { print_token("OP_ASSIGN", yytext); }
  99. ":=" { print_token("WALRUS_OPERATOR", yytext); }
  100. "==" { print_token("OP_EQUALS", yytext); }
  101. "!=" { print_token("OP_NOT_EQ", yytext); }
  102. ">" { print_token("OP_GT", yytext); }
  103. "<" { print_token("OP_LT", yytext); }
  104. ">=" { print_token("OP_GTE", yytext); }
  105. "<=" { print_token("OP_LTE", yytext); }
  106. "+=" { print_token("OP_PLUS_ASSIGN", yytext); }
  107. "-=" { print_token("OP_MINUS_ASSIGN", yytext); }
  108. "*=" { print_token("OP_MULT_ASSIGN", yytext); }
  109. "/=" { print_token("OP_DIV_ASSIGN", yytext); }
  110. "%=" { print_token("OP_MOD_ASSIGN", yytext); }
  111. "**=" { print_token("OP_POWER_ASSIGN", yytext); }
  112. "//=" { print_token("OP_FLOOR_DIV_ASSIGN", yytext); }
  113. "&" { print_token("OP_BIT_AND", yytext); }
  114. "|" { print_token("OP_BIT_OR", yytext); }
  115. "^" { print_token("OP_BIT_XOR", yytext); }
  116. "~" { print_token("OP_BIT_NOT", yytext); }
  117. "<<" { print_token("OP_LSHIFT", yytext); }
  118. ">>" { print_token("OP_RSHIFT", yytext); }
  119. "&=" { print_token("OP_BIT_AND_ASSIGN", yytext); }
  120. "|=" { print_token("OP_BIT_OR_ASSIGN", yytext); }
  121. "^=" { print_token("OP_BIT_XOR_ASSIGN", yytext); }
  122. "<<=" { print_token("OP_LSHIFT_ASSIGN", yytext); }
  123. ">>=" { print_token("OP_RSHIFT_ASSIGN", yytext); }
  124.  
  125. "(" { paren_count++; print_token("LPAREN", yytext); }
  126. ")" { paren_count--; print_token("RPAREN", yytext); }
  127. "[" { bracket_count++; print_token("LBRACKET", yytext); }
  128. "]" { bracket_count--; print_token("RBRACKET", yytext); }
  129. "{" { brace_count++; print_token("LBRACE", yytext); }
  130. "}" { brace_count--; print_token("RBRACE", yytext); }
  131. ":" { print_token("COLON", yytext); }
  132. "," { print_token("COMMA", yytext); }
  133. "." { print_token("DOT", yytext); }
  134. "..." { print_token("ELLIPSIS", yytext); }
  135. ";" { print_token("SEMICOLON", yytext); }
  136. "@" { print_token("DECORATOR", yytext); }
  137. "->" { print_token("ARROW", yytext); }
  138.  
  139. {F_TRIPLE_SQ} { print_token("F_TRIPLE_STRING_LITERAL", yytext); }
  140. {F_TRIPLE_DQ} { print_token("F_TRIPLE_STRING_LITERAL", yytext); }
  141. {F_STRING_SQ} {
  142. if (yytext[yyleng-1] == '\'') {
  143. print_token("F_STRING_LITERAL", yytext);
  144. } else {
  145. print_error("Unclosed f-string literal", yytext);
  146. }
  147. }
  148. {F_STRING_DQ} {
  149. if (yytext[yyleng-1] == '\"') {
  150. print_token("F_STRING_LITERAL", yytext);
  151. } else {
  152. print_error("Unclosed f-string literal", yytext);
  153. }
  154. }
  155. {TRIPLE_SQ} { print_token("TRIPLE_STRING_LITERAL", yytext); }
  156. {TRIPLE_DQ} { print_token("TRIPLE_STRING_LITERAL", yytext); }
  157. {STRING_SQ} {
  158. if (yytext[yyleng-1] == '\'') {
  159. print_token("STRING_LITERAL", yytext);
  160. } else {
  161. print_error("Unclosed string literal", yytext);
  162. }
  163. }
  164. {STRING_DQ} {
  165. if (yytext[yyleng-1] == '\"') {
  166. print_token("STRING_LITERAL", yytext);
  167. } else {
  168. print_error("Unclosed string literal", yytext);
  169. }
  170. }
  171.  
  172. {BIN_NUM} { print_token("BINARY_LITERAL", yytext); }
  173. {OCT_NUM} { print_token("OCTAL_LITERAL", yytext); }
  174. {HEX_NUM} { print_token("HEX_LITERAL", yytext); }
  175. {COMPLEX_NUM} { print_token("COMPLEX_LITERAL", yytext); }
  176. {FLOAT_NUM} { print_token("FLOAT_LITERAL", yytext); }
  177. {INT_NUM} { print_token("INT_LITERAL", yytext); }
  178.  
  179. {ID} { print_token("IDENTIFIER", yytext); }
  180.  
  181. \n { line_num++; }
  182.  
  183. [ \t\r]+ { /* Ignore whitespace */ }
  184.  
  185. . { print_error("Unknown character", yytext); }
  186.  
  187. %%
  188.  
  189. int main(int argc, char **argv) {
  190. if (argc > 1) {
  191. yyin = fopen(argv[1], "r");
  192. if (!yyin) {
  193. fprintf(stderr, "Error: Could not open file %s\n", argv[1]);
  194. return 1;
  195. }
  196. } else {
  197. fprintf(stderr, "Usage: %s <input_file.py>\n", argv[0]);
  198. fprintf(stderr, "Example: %s test.py\n", argv[0]);
  199. return 1;
  200. }
  201.  
  202. printf("================================================================================\n");
  203. printf("PYTHON LEXICAL ANALYZER - SUPPORTS ALL FUNCTION TYPES\n");
  204. printf("================================================================================\n");
  205. printf("%-10s %-30s %s\n", "LINE", "TOKEN TYPE", "LEXEME");
  206. printf("--------------------------------------------------------------------------------\n");
  207.  
  208. yylex();
  209.  
  210. printf("================================================================================\n");
  211. printf("Analysis complete. Total lines: %d, Errors: %d\n", line_num, error_count);
  212.  
  213. // Check for unbalanced brackets
  214. if (paren_count != 0) printf("WARNING: Unbalanced parentheses\n");
  215. if (brace_count != 0) printf("WARNING: Unbalanced braces\n");
  216. if (bracket_count != 0) printf("WARNING: Unbalanced brackets\n");
  217.  
  218. printf("================================================================================\n");
  219.  
  220. if (yyin != stdin) {
  221. fclose(yyin);
  222. }
  223.  
  224. return error_count > 0 ? 1 : 0;
  225. }
  226.  
  227. int yywrap(void) {
  228. return 1;
  229. }
Success #stdin #stdout #stderr 0.03s 7100KB
stdin
# =============================================================================
# COMPREHENSIVE PYTHON TEST FILE - ALL LANGUAGE FEATURES
# =============================================================================

# -------------------------------
# 1. ALL DATA TYPES & LITERALS
# -------------------------------

# Numeric literals
integer_var = 42
float_var = 3.14159
hex_var = 0x1A3F
octal_var = 0o755
binary_var = 0b1101
complex_var = 3 + 4j
scientific_var = 1.23e-4

# String literals
single_quote_str = 'hello world'
double_quote_str = "python programming"
triple_single_str = '''multiline
string with triple
single quotes'''
triple_double_str = """multiline
string with triple
double quotes"""
f_string = f"formatted: {integer_var}"
raw_string = r"raw string \n no escape"

# Boolean and None
true_var = True
false_var = False
none_var = None

# Collections
list_var = [1, 2, 3, "mixed", True]
tuple_var = (1, "hello", 3.14)
dict_var = {"key1": "value1", "key2": 42}
set_var = {1, 2, 3, 2, 1}

# -------------------------------
# 2. ALL KEYWORDS
# -------------------------------

# Function definition keywords
def regular_function(param1, param2):
    """This is a regular function"""
    return param1 + param2

# Class definition
class MyClass:
    """A sample class"""
    
    def __init__(self, value):
        self.value = value
    
    def get_value(self):
        return self.value
    
    @classmethod
    def class_method(cls):
        return "class method"
    
    @staticmethod
    def static_method():
        return "static method"

# Control flow keywords
if True:
    print("if statement")
elif False:
    print("elif statement")
else:
    print("else statement")

# Loops
for i in range(5):
    print(f"for loop: {i}")
    if i == 2:
        continue
    if i == 4:
        break

while True:
    print("while loop")
    break

# Exception handling
try:
    risky_operation = 10 / 2
except ZeroDivisionError as e:
    print(f"Error: {e}")
except Exception:
    print("General exception")
finally:
    print("Finally block")

# Import keywords
import math
import os as operating_system
from sys import platform
from collections import deque, Counter

# Scope keywords
global global_variable
global_variable = "I'm global"

def scope_test():
    local_var = "I'm local"
    global global_variable
    global_variable = "modified"

# Async keywords
async def async_function():
    await some_async_operation()
    return "async result"

# Other keywords
lambda_func = lambda x: x * 2
del list_var[0]

# -------------------------------
# 3. ALL OPERATORS
# -------------------------------

# Arithmetic operators
a, b = 10, 3
add = a + b
subtract = a - b
multiply = a * b
divide = a / b
floor_divide = a // b
modulus = a % b
power = a ** b

# Assignment operators
x = 5
x += 3
x -= 2
x *= 4
x /= 2
x //= 3
x %= 5
x **= 2

# Comparison operators
eq = (a == b)
ne = (a != b)
gt = (a > b)
lt = (a < b)
ge = (a >= b)
le = (a <= b)

# Logical operators
and_result = (True and False)
or_result = (True or False)
not_result = (not True)

# Identity operators
is_result = (a is b)
is_not_result = (a is not b)

# Membership operators
in_result = (2 in [1, 2, 3])
not_in_result = (4 not in [1, 2, 3])

# Bitwise operators
bit_and = a & b
bit_or = a | b
bit_xor = a ^ b
bit_not = ~a
left_shift = a << 2
right_shift = a >> 1

# Bitwise assignment
y = 15
y &= 7
y |= 8
y ^= 4
y <<= 1
y >>= 2

# Walrus operator
if (n := len("hello")) > 3:
    print(f"Length is {n}")

# -------------------------------
# 4. ALL FUNCTION TYPES
# -------------------------------

# Regular function
def simple_func():
    return "simple"

# Function with type hints
def typed_func(name: str, age: int) -> str:
    return f"{name} is {age}"

# Function with default parameters
def default_params(a, b=10, c=None):
    if c is None:
        c = []
    return a + b

# Function with *args and **kwargs
def flexible_func(*args, **kwargs):
    return args, kwargs

# Generator function
def number_generator(limit):
    for i in range(limit):
        yield i * 2

# Async function
async def fetch_data(url):
    # Simulate async operation
    return f"data from {url}"

# Lambda function
square = lambda x: x ** 2
add_lambda = lambda x, y: x + y

# Nested function
def outer_function():
    outer_var = "outer"
    
    def inner_function():
        return outer_var + " inner"
    
    return inner_function()

# Function with decorators
def simple_decorator(func):
    def wrapper(*args, **kwargs):
        print("Before function call")
        result = func(*args, **kwargs)
        print("After function call")
        return result
    return wrapper

@simple_decorator
def decorated_function():
    return "decorated"

# Multiple decorators
def decorator1(func):
    return func

def decorator2(func):
    return func

@decorator1
@decorator2
def multi_decorated():
    return "multi-decorated"

# Class-based decorator
class ClassDecorator:
    def __init__(self, func):
        self.func = func
    
    def __call__(self, *args, **kwargs):
        return self.func(*args, **kwargs)

@ClassDecorator
def class_decorated():
    return "class decorated"

# -------------------------------
# 5. ALL CONTROL STRUCTURES
# -------------------------------

# If-elif-else chains
score = 85
if score >= 90:
    grade = 'A'
elif score >= 80:
    grade = 'B'
elif score >= 70:
    grade = 'C'
else:
    grade = 'F'

# Nested if statements
if True:
    if False:
        pass
    else:
        print("nested else")

# For loops with different iterables
for char in "hello":
    print(char)

for key, value in {"a": 1, "b": 2}.items():
    print(f"{key}: {value}")

for i, item in enumerate(["apple", "banana"]):
    print(f"{i}: {item}")

# While-else loop
count = 0
while count < 3:
    print(count)
    count += 1
else:
    print("Loop completed")

# Try-except-else-finally
def safe_divide(x, y):
    try:
        result = x / y
    except ZeroDivisionError:
        return "Cannot divide by zero"
    except TypeError as e:
        return f"Type error: {e}"
    else:
        print("Division successful")
        return result
    finally:
        print("Division attempt completed")

# Context manager (with statement)
with open('test.txt', 'w') as f:
    f.write("Hello World")

# -------------------------------
# 6. ADVANCED FEATURES
# -------------------------------

# List comprehensions
squares = [x**2 for x in range(10)]
even_squares = [x**2 for x in range(10) if x % 2 == 0]

# Dictionary comprehensions
square_dict = {x: x**2 for x in range(5)}

# Set comprehensions
unique_chars = {char for char in "hello world"}

# Generator expressions
gen_expr = (x*2 for x in range(5))

# Conditional expressions (ternary)
max_value = a if a > b else b

# Multiple assignment
x, y, z = 1, 2, 3
a = b = c = 0

# Extended unpacking
first, *middle, last = [1, 2, 3, 4, 5]

# Format strings with expressions
name = "Alice"
age = 30
formatted = f"{name.upper()} is {age + 5} years old in 5 years"

# Ellipsis
def incomplete():
    ...

class AbstractClass:
    def method(self):
        ...

# -------------------------------
# 7. COMPLEX EXAMPLES
# -------------------------------

# Complex class with inheritance
class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        raise NotImplementedError

class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof!"

class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow!"

# Multiple inheritance
class Aquatic:
    def swim(self):
        return "Swimming"

class Flying:
    def fly(self):
        return "Flying"

class Duck(Aquatic, Flying):
    def __init__(self, name):
        self.name = name

# Complex function with everything
@simple_decorator
def complex_example(
    required: str,
    optional: int = 10,
    *args: tuple,
    **kwargs: dict
) -> dict:
    """A complex function demonstrating many features"""
    
    # Walrus in comprehension
    results = {
        key: (value := val * 2) 
        for key, val in kwargs.items() 
        if (value := val * 2) > 10
    }
    
    # Multiple conditions
    if (required and 
        optional > 5 and 
        len(args) > 0 and
        'important' in kwargs):
        
        # Nested try-except
        try:
            processed = [
                item.upper() if isinstance(item, str) else item * 2
                for item in args
                if item is not None
            ]
        except Exception as e:
            print(f"Error: {e}")
            processed = []
        finally:
            print("Processing complete")
    
    else:
        processed = []
    
    return {
        'results': results,
        'processed': processed,
        'metadata': {
            'args_count': len(args),
            'kwargs_count': len(kwargs)
        }
    }

# -------------------------------
# 8. MAIN EXECUTION BLOCK
# -------------------------------

if __name__ == "__main__":
    # Test all features
    
    # Data types
    print("Data types test:")
    print(f"Integer: {integer_var}")
    print(f"Float: {float_var}")
    print(f"String: {single_quote_str}")
    print(f"F-string: {f_string}")
    
    # Functions
    print("\nFunctions test:")
    result = regular_function(5, 3)
    print(f"Regular function: {result}")
    
    # Classes
    print("\nClasses test:")
    dog = Dog("Buddy")
    print(dog.speak())
    
    # Control structures
    print("\nControl structures test:")
    for i in range(3):
        if i % 2 == 0:
            print(f"Even: {i}")
        else:
            print(f"Odd: {i}")
    
    # Operators
    print("\nOperators test:")
    print(f"Arithmetic: {add}, {subtract}, {multiply}")
    print(f"Comparison: {eq}, {ne}, {gt}")
    print(f"Logical: {and_result}, {or_result}, {not_result}")
    
    # Advanced features
    print("\nAdvanced features test:")
    print(f"List comprehension: {squares}")
    print(f"Dict comprehension: {square_dict}")
    print(f"Ternary: {max_value}")
    
    # Complex example
    print("\nComplex example test:")
    complex_result = complex_example(
        "required_value",
        15,
        "hello", "world",
        important=10,
        test=5
    )
    print(f"Complex result: {complex_result}")
    
    print("\n✅ ALL FEATURES TESTED SUCCESSFULLY!")

# -------------------------------
# END OF COMPREHENSIVE TEST FILE
# -------------------------------
stdout

	
stderr
ERROR: /home/mGMfkS/prog:2:1: Syntax error: Operator expected
ERROR: /home/mGMfkS/prog:229:0: Syntax error: Unexpected end of file
ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? ERROR: Unknown option (h for help)
   Exception: (3) program ? ERROR: Unknown option (h for help)
   Exception: (3) program ? ERROR: Unknown option (h for help)
   Exception: (3) program ? ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? ERROR: Unknown option (h for help)
   Exception: (3) program ? ERROR: Unknown option (h for help)
   Exception: (3) program ? ERROR: Unknown option (h for help)
   Exception: (3) program ? ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? ERROR: Unknown option (h for help)
   Exception: (3) program ? ERROR: Can't ignore goal at this port
ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? Options:
+:                  spy        -:              no spy
/c|e|r|f|u|a goal:  find       .:              repeat find
a:                  abort      A:              alternatives
b:                  break      c (ret, space): creep
[depth] d:          depth      e:              exit
f:                  fail       [ndepth] g:     goals (backtrace)
h (?):              help       i:              ignore
l:                  leap       L:              listing
n:                  no debug   p:              print
r:                  retry      s:              skip
u:                  up         w:              write
m:                  exception details
C:                  toggle show context
   Exception: (3) program ? ERROR: Unknown option (h for help)
   Exception: (3) program ? % Break level 1

ERROR: Syntax error: Operator expected
ERROR: complex_var = 3 + 
ERROR: ** here **
ERROR: 4j
scientific_var = 1.23e-4

# String literals
single_quote_str = 'hello world'
double_quote_str = "python programming"
triple_single_str = '''multiline
string with triple
single quotes'''
triple_double_str = """multiline
string with triple
double quotes"""
f_string = f"formatted: {integer_var}"
raw_string = r"raw string \n no escape"

# Boolean and None
true_var = True
false_var = False
none_var = None

# Collections
list_var = [1, 2, 3, "mixed", True]
tuple_var = (1, "hello", 3.14)
dict_var = {"key1": "value1", "key2": 42}
set_var = {1, 2, 3, 2, 1}

# -------------------------------
# 2 . 

ERROR: Syntax error: Operator expected
ERROR: ALL
ERROR: ** here **
ERROR:  KEYWORDS
# -------------------------------

# Function definition keywords
def regular_function(param1, param2):
    """This is a regular function"""
    return param1 + param2

# Class definition
class MyClass:
    """A sample class"""
    
    def __init__(self, value):
        self.value = value
    
    def get_value(self):
        return self.value
    
    @classmethod
    def class_method(cls):
        return "class method"
    
    @staticmethod
    def static_method():
        return "static method"

# Control flow keywords
if True:
    print("if statement")
elif False:
    print("elif statement")
else:
    print("else statement")

# Loops
for i in range(5):
    print(f"for loop: {i}")
    if i == 2:
        continue
    if i == 4:
        break

while True:
    print("while loop")
    break

# Exception handling
try:
    risky_operation = 10 / 2
except ZeroDivisionError as e:
    print(f"Error: {e}")
except Exception:
    print("General exception")
finally:
    print("Finally block")

# Import keywords
import math
import os as operating_system
from sys import platform
from collections import deque, Counter

# Scope keywords
global global_variable
global_variable = "I'm global"

def scope_test():
    local_var = "I'm local"
    global global_variable
    global_variable = "modified"

# Async keywords
async def async_function():
    await some_async_operation()
    return "async result"

# Other keywords
lambda_func = lambda x: x * 2
del list_var[0]

# -------------------------------
# 3 . 

ERROR: Syntax error: Operator expected
ERROR: ALL
ERROR: ** here **
ERROR:  OPERATORS
# -------------------------------

# Arithmetic operators
a, b = 10, 3
add = a + b
subtract = a - b
multiply = a * b
divide = a / b
floor_divide = a // b
modulus = a    
power = a ** b

# Assignment operators
x = 5
x += 3
x -= 2
x *= 4
x /= 2
x //= 3
x     
x **= 2

# Comparison operators
eq = (a == b)
ne = (a != b)
gt = (a > b)
lt = (a < b)
ge = (a >= b)
le = (a <= b)

# Logical operators
and_result = (True and False)
or_result = (True or False)
not_result = (not True)

# Identity operators
is_result = (a is b)
is_not_result = (a is not b)

# Membership operators
in_result = (2 in [1, 2, 3])
not_in_result = (4 not in [1, 2, 3])

# Bitwise operators
bit_and = a & b
bit_or = a | b
bit_xor = a ^ b
bit_not = ~a
left_shift = a << 2
right_shift = a >> 1

# Bitwise assignment
y = 15
y &= 7
y |= 8
y ^= 4
y <<= 1
y >>= 2

# Walrus operator
if (n := len("hello")) > 3:
    print(f"Length is {n}")

# -------------------------------
# 4 . 

ERROR: Syntax error: Operator expected
ERROR: ALL
ERROR: ** here **
ERROR:  FUNCTION TYPES
# -------------------------------

# Regular function
def simple_func():
    return "simple"

# Function with type hints
def typed_func(name: str, age: int) -> str:
    return f"{name} is {age}"

# Function with default parameters
def default_params(a, b=10, c=None):
    if c is None:
        c = []
    return a + b

# Function with *args and **kwargs
def flexible_func(*args, **kwargs):
    return args, kwargs

# Generator function
def number_generator(limit):
    for i in range(limit):
        yield i * 2

# Async function
async def fetch_data(url):
    # Simulate async operation
    return f"data from {url}"

# Lambda function
square = lambda x: x ** 2
add_lambda = lambda x, y: x + y

# Nested function
def outer_function():
    outer_var = "outer"
    
    def inner_function():
        return outer_var + " inner"
    
    return inner_function()

# Function with decorators
def simple_decorator(func):
    def wrapper(*args, **kwargs):
        print("Before function call")
        result = func(*args, **kwargs)
        print("After function call")
        return result
    return wrapper

@simple_decorator
def decorated_function():
    return "decorated"

# Multiple decorators
def decorator1(func):
    return func

def decorator2(func):
    return func

@decorator1
@decorator2
def multi_decorated():
    return "multi-decorated"

# Class-based decorator
class ClassDecorator:
    def __init__(self, func):
        self.func = func
    
    def __call__(self, *args, **kwargs):
        return self.func(*args, **kwargs)

@ClassDecorator
def class_decorated():
    return "class decorated"

# -------------------------------
# 5 . 

ERROR: Syntax error: Operator expected
ERROR: ALL
ERROR: ** here **
ERROR:  CONTROL STRUCTURES
# -------------------------------

# If-elif-else chains
score = 85
if score >= 90:
    grade = 'A'
elif score >= 80:
    grade = 'B'
elif score >= 70:
    grade = 'C'
else:
    grade = 'F'

# Nested if statements
if True:
    if False:
        pass
    else:
        print("nested else")

# For loops with different iterables
for char in "hello":
    print(char)

for key, value in {"a": 1, "b": 2}.items():
    print(f"{key}: {value}")

for i, item in enumerate(["apple", "banana"]):
    print(f"{i}: {item}")

# While-else loop
count = 0
while count < 3:
    print(count)
    count += 1
else:
    print("Loop completed")

# Try-except-else-finally
def safe_divide(x, y):
    try:
        result = x / y
    except ZeroDivisionError:
        return "Cannot divide by zero"
    except TypeError as e:
        return f"Type error: {e}"
    else:
        print("Division successful")
        return result
    finally:
        print("Division attempt completed")

# Context manager (with statement)
with open('test.txt', 'w') as f:
    f.write("Hello World")

# -------------------------------
# 6 . 

ERROR: Syntax error: Operator expected
ERROR: ADVANCED
ERROR: ** here **
ERROR:  FEATURES
# -------------------------------

# List comprehensions
squares = [x**2 for x in range(10)]
even_squares = [x**2 for x in range(10) if x          

# Dictionary comprehensions
square_dict = {x: x**2 for x in range(5)}

# Set comprehensions
unique_chars = {char for char in "hello world"}

# Generator expressions
gen_expr = (x*2 for x in range(5))

# Conditional expressions (ternary)
max_value = a if a > b else b

# Multiple assignment
x, y, z = 1, 2, 3
a = b = c = 0

# Extended unpacking
first, *middle, last = [1, 2, 3, 4, 5]

# Format strings with expressions
name = "Alice"
age = 30
formatted = f"{name.upper()} is {age + 5} years old in 5 years"

# Ellipsis
def incomplete():
    ...

class AbstractClass:
    def method(self):
        ...

# -------------------------------
# 7 . 

ERROR: Syntax error: Operator expected
ERROR: COMPLEX
ERROR: ** here **
ERROR:  EXAMPLES
# -------------------------------

# Complex class with inheritance
class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        raise NotImplementedError

class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof!"

class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow!"

# Multiple inheritance
class Aquatic:
    def swim(self):
        return "Swimming"

class Flying:
    def fly(self):
        return "Flying"

class Duck(Aquatic, Flying):
    def __init__(self, name):
        self.name = name

# Complex function with everything
@simple_decorator
def complex_example(
    required: str,
    optional: int = 10,
    *args: tuple,
    **kwargs: dict
) -> dict:
    """A complex function demonstrating many features"""
    
    # Walrus in comprehension
    results = {
        key: (value := val * 2) 
        for key, val in kwargs.items() 
        if (value := val * 2) > 10
    }
    
    # Multiple conditions
    if (required and 
        optional > 5 and 
        len(args) > 0 and
        'important' in kwargs):
        
        # Nested try-except
        try:
            processed = [
                item.upper() if isinstance(item, str) else item * 2
                for item in args
                if item is not None
            ]
        except Exception as e:
            print(f"Error: {e}")
            processed = []
        finally:
            print("Processing complete")
    
    else:
        processed = []
    
    return {
        'results': results,
        'processed': processed,
        'metadata': {
            'args_count': len(args),
            'kwargs_count': len(kwargs)
        }
    }

# -------------------------------
# 8 . 

ERROR: Stream user_input:1006:32 Syntax error: Unexpected end of file
% Exit break level 1
   Exception: (3) program ? EOF: exit