Skip to content

Commit

Permalink
Add example
Browse files Browse the repository at this point in the history
  • Loading branch information
lierdakil committed Nov 3, 2020
1 parent 5e30a9d commit 4ee8804
Show file tree
Hide file tree
Showing 5 changed files with 630 additions and 0 deletions.
3 changes: 3 additions & 0 deletions examples/jack-analyzer/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
lexer.*
parser.*
__pycache__
81 changes: 81 additions & 0 deletions examples/jack-analyzer/JackAnalyzer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
#!/usr/bin/env python3

from lexer import Lexer, TokenType
from parser import Parser
from sys import argv
from parserTypes import escape
import glob
import os

def replaceSym(s):
return s.replace('&', '&')\
.replace('"', '"')\
.replace('<', '&lt;')\
.replace('>', '&gt;')

debug=False
fn = argv[1]

def analyzeFile(fn):
tokenClass = {
'class': 'keyword',
'primType': 'keyword',
'propType': 'keyword',
'methodCategory': 'keyword',
'if': 'keyword',
'do': 'keyword',
'while': 'keyword',
'let': 'keyword',
'return': 'keyword',
'else': 'keyword',
'void': 'keyword',
'var': 'keyword',
'primVal': 'keyword',

'identifier': 'identifier',
'integerConstant': 'integerConstant',
'stringConstant': 'stringConstant',

'lb': 'symbol',
'rb': 'symbol',
'binOp': 'symbol',
'equals': 'symbol',
'minus': 'symbol',
'not': 'symbol',
'lp': 'symbol',
'rp': 'symbol',
'c': 'symbol',
'dot': 'symbol',
'sc': 'symbol',
'lbr': 'symbol',
'rbr': 'symbol',
}


print(f"<!-- Analyzing {fn} #-->")
# Lexer part
with open(fn) as f:
lex = Lexer(f.read(), debug)
tok, s = lex.getNextToken()
print('<tokens>')
while tok is not TokenType.eof:
t = tokenClass[tok.name[4:]]
if t == 'symbol':
s = escape(s)
print(f'<{t}> {s} </{t}>')
tok, s = lex.getNextToken()
print('</tokens>')

# Parser part
with open(fn) as f:
lex = Lexer(f.read(), debug)
parser = Parser(lex, debug)
expr = parser.parse()
res = "\n".join(filter(lambda x: len(x)>0, str(expr).split("\n")))
print(res)

if os.path.isdir(fn):
for fn in glob.glob(os.path.join(fn,'*.jack')):
analyzeFile(fn)
else:
analyzeFile(fn)
9 changes: 9 additions & 0 deletions examples/jack-analyzer/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Jack Analyzer

This is a quick and dirty implementation of <https://www.nand2tetris.org/project10> using ALPACA.

The grammar is SLR, the default LALR parser obviously works, too.

The implementation language is Python.

Invoke ALPACA with `alpaca -lpy syntax.xy`
Loading

0 comments on commit 4ee8804

Please sign in to comment.