Skip to content

Instantly share code, notes, and snippets.

@esehara
Created October 21, 2011 13:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esehara/1303879 to your computer and use it in GitHub Desktop.
Save esehara/1303879 to your computer and use it in GitHub Desktop.
HTMLF*CK
# -*- coding:utf-8 -*-
##use Module
import ply.lex as lex
import ply.yacc as yacc
#Use Token
tokens = (
'STRING'
,'P_Start'
,'P_End'
,'ID'
,'CLASS'
,'HEAD'
,'BODY'
,'DIV_Start'
,'DIV_End'
)
#Define Token
t_STRING = r'\".*?\"'
t_P_Start = r'P'
t_P_End = r'\/P'
t_ID = r'\#'
t_CLASS = r'\.'
t_HEAD = r'\@'
t_BODY = r'\&'
t_DIV_Start = r'\('
t_DIV_End = r'\)'
#Token Parse Error
def t_error(t):
t.lexer.skip(1)
lex.lex()
def p_statement_expr(t):
"statement : expression"
print "<html>\n" + t[1] + "\n</html>"
def p_expression(t):
"""
expression : P_Start_Parse expression P_End
| DIV_Start_Parse expression DIV_End
| HEAD expression HEAD
| BODY expression BODY
"""
if t[3] == "/P":
t[0] = t[1] + t[2] + "\n</p>"
if t[3] == ")":
t[0] = t[1] + t[2] + "\n</div>"
if t[1] == "@" and t[3] == "@":
t[0] = "<head>" + t[2] + "</head>"
if t[1] == "&" and t[3] == "&":
t[0] = "<body>" + t[2] + "</body>"
def double_expression(t):
"""
expression : expression expression
| expression STRING
| STRING STRING
"""
t[0] = t[1] + t[2]
def p_expression_P(t):
"""
P_Start_Parse : P_Start ID_AND_CLASS
| P_Start
"""
if len(t) == 3:
t[0] = "<p" + t[2] + ">\n"
else:
t[0] = "<p>\n"
def p_expression_div(t):
"""
DIV_Start_Parse : DIV_Start ID_AND_CLASS
| DIV_Start
"""
if len(t) == 3:
t[0] = "<div" + t[2] +">\n"
else:
t[0] = "<div>"
def p_expression_ID(t):
"""
ID_R : ID STRING
"""
t[0] = " id = " + t[2]
def p_expression_CLASS(t):
"""
CLASS_R : CLASS STRING
"""
t[0] = " class = " + t[2]
def p_expression_ID_AND_CLASS(t):
"""
ID_AND_CLASS : ID_R
| CLASS_R
| ID_R CLASS_R
| CLASS_R ID_R
"""
if len(t) == 3:
t[0] = t[1] + t[2]
else:
t[0] = t[1]
def p_expression_STRING(t):
"""
expression : STRING
"""
t[0] = t[1][1:-1]
def p_error(t):
print "Syntax error at '%s'" % t.value
yacc.yacc()
while 1:
try:
s = raw_input("HTMLF*CK >")
except EOFError:
break
yacc.parse(s)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment