-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
55 lines (49 loc) · 1.7 KB
/
Copy pathapp.py
File metadata and controls
55 lines (49 loc) · 1.7 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
from flask import Flask, request, jsonify
import re
app = Flask(__name__, static_folder='.', static_url_path='')
def lexical_analyzer(code):
tokens = []
patterns = [
(r'\b(int|float|if|else|while|for)\b', 'keyword'),
(r'\b[a-zA-Z][a-zA-Z0-9_]*\b', 'identifier'),
(r'\d+\.\d*|\d+', 'number'), # Match floats and integers
(r'==', 'operator'), # Match ==
(r'\|\|', 'operator'), # Match ||
(r'[+\-*/=<]', 'operator'),
(r'[;{}]', 'delimiter'),
(r'[\(\)]', 'parenthesis'),
(r'\s+', None), # Skip whitespace
(r'.', 'error') # Catch-all for invalid chars
]
pos = 0
while pos < len(code):
match = None
for pattern, token_type in patterns:
regex = re.compile(pattern)
match = regex.match(code, pos)
if match:
if token_type:
tokens.append({"token": match.group(0), "type": token_type})
pos = match.end()
break
if not match:
tokens.append({"token": code[pos], "type": "error"})
pos += 1
return tokens
@app.route('/')
def serve_index():
return app.send_static_file('index.html')
@app.route('/analyze', methods=['POST'])
def analyze():
try:
data = request.get_json()
code = data.get('code', '')
if not code:
return jsonify([])
tokens = lexical_analyzer(code)
return jsonify(tokens)
except Exception as e:
print(f"Error in /analyze: {e}")
return jsonify([{"token": "Server Error", "type": "error"}]), 500
if __name__ == '__main__':
app.run(debug=True)