Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Almost have objects for all constructs...

  • Loading branch information...
commit b7cc307b4cb9c78fdb63c8f9d8e0390d571378d9 1 parent 517b8bd
@scooby authored
Showing with 511 additions and 225 deletions.
  1. +170 −61 CodeObjects.py
  2. +53 −57 LolGrammer.py
  3. +119 −105 Responder.py
  4. +169 −2 framework.h
View
231 CodeObjects.py
@@ -15,21 +15,36 @@
# I can then link that to a C based skeleton.
class GenC(object):
- """ Mixin class to represent something that can generate C. """
+ """ Mixin class to represent something that can generate C.
+ This just double checks that the overrides return
+ valid types. """
def genC(self):
- pass
+ v = self._genC()
+ if isinstance(v, str):
+ return v
+ assert isinstance(v, tuple)
+ assert all(isinstance(x, (str, tuple)) for x in v)
+ return v
class Scope(object):
def __init__(self, **kw):
super(Scope, self).__init__(**kw)
self.declarations = dict()
self.constants = dict()
+ self.counter = 0
def declare(self, var):
if var.name in self.declarations:
raise CompileException("Variable already declared")
self.declarations[var.name] = var
-class Declaration(object):
+ def genVar(self):
+ self.counter += 1
+ return "__gen_" + str(self.counter)
+class Declaration(GenC, Stmnt):
def __init__(self, var, typ):
- assert isinstance(var, str) and typ isinstance(
+ assert isinstance(var, VarName) and isinstance(typ, LangType)
+ self.var = var
+ self.typ = typ
+ def _genC(self):
+ return (self.typ.genC(), self.var.genC(), ";")
class Function(Scope):
def __init__(self, **kw):
pass
@@ -82,7 +97,7 @@ def __init__(self, agg, key, val, **kw):
self.agg = VarName(agg)
self.key = key
self.val = val
- def genC(self):
+ def _genC(self):
if self.val is None:
return (self.agg.genC(), '.insert(', self.key.genC(), ');')
else:
@@ -94,14 +109,14 @@ def __init__(self, agg, key, **kw):
assert isinstance(key, Expr)
self.agg = VarName(agg)
self.key = key
- def genC(self):
+ def _genC(self):
return (self.agg.genC(), '.erase(', self.key.genC(), ');')
class SetStmnt(Stmnt, GenC):
def __init__(self, lagg, ragg, **kw):
super(SetStmnt, self).__init__(**kw)
self.lagg = VarName(lagg)
self.ragg = VarName(ragg)
- def genC(self):
+ def _genC(self):
return (self.head().genC(), '(', self.lagg.genC(), ',',
self.ragg.genC(), ');')
class UnionStmnt(SetStmnt):
@@ -119,7 +134,7 @@ def __init__(self, expr, **kw):
super(ExprStmnt, self).__init__(**kw)
assert isinstance(expr, Expr)
self.expr = expr
- def genC(self):
+ def _genC(self):
return (self.expr.genC(), ';')
class Assignment(Stmnt, GenC):
def __init__(self, var, expr, **kw):
@@ -127,7 +142,7 @@ def __init__(self, var, expr, **kw):
assert isinstance(expr, Expr)
self.var = VarName(var)
self.expr = expr
- def genC(self):
+ def _genC(self):
return (self.var.genC(), '=', self.expr.genC(), ';')
class InputStmnt(Stmnt, GenC):
@@ -136,7 +151,7 @@ def __init__(self, var, read, **kw):
self.var = VarName(var)
assert read in ('word', 'line', 'numbar')
self.read = read
- def genC(self):
+ def _genC(self):
return (self.var.genC(), '= input_'+self.read+'();')
class OutputStmnt(Stmnt, GenC):
def __init__(self, handle, terms, nl, **kw):
@@ -149,46 +164,125 @@ def __init__(self, handle, terms, nl, **kw):
self.nl = nl
def chandle(self):
return Simple('c' + self.handle)
- def genC(self):
+ def _genC(self):
terms = [self.chandle()] + self.terms
if self.nl:
terms.append(Simple('endl'))
return tuple(iterJoin('<<', terms)) + (';',)
class Conditional(Stmnt, GenC):
- def __init__(self, cases, **kw):
+ def __init__(self, test, blocks, **kw):
super(Conditional, self).__init__(**kw)
- self.cases = list()
- for cond, block in cases:
- self.addCase(cond, block)
- def addCond(self, cond, block):
- assert isinstance(cond, Expr)
+ self.test = test
+ self.blocks = list(blocks)
+ for cond, expr, block in cases:
+ self.addCond(cond, expr, block)
+ def addCond(self, cond, expr, block):
+ assert isinstance(cond, (bool, NoneType))
+ assert isinstance(expr, (Expr, NoneType))
assert isinstance(block, Block)
- self.cases.append((cond, block))
- def genC(self):
- if not self.cases:
- return ()
+ self.cases.append((cond, expr, block))
+ def _genC(self):
l = []
- for cond, block in self.cases:
- l.extend(("else", "if(", cond.genC(), ") {", block.genC(), "}"))
+ tv = self.genVar()
+ l.append(Assignment(var=tv, expr=self.test).genC())
+ elseClause = False
+ for cond, expr, block in self.cases:
+ ifClause = tv if cond else (expr if cond is None else NegateExpr(tv))
+ if elseClause:
+ l.append("else")
+ elseClause = True
+ l.extend(("if(", ifClause.genC(), ") {", block.genC(), "}"))
l.append(";")
- return tuple(l[1:])
+ return tuple(l)
-class Counter(Stmnt, CGen):
- def __init__(self, label, preCondExpr, body, **kw):
+class Case(Stmnt, GenC):
+ def __init__(self, test, blocks, **kw):
+ super(Conditional, self).__init__(**kw)
+ self.test = test
+ self.blocks = list(blocks)
+ for expr, block in cases:
+ self.addCase(expr, block)
+ def addCond(self, expr, block):
+ assert isinstance(expr, (Expr, NoneType))
+ assert isinstance(block, Block)
+ self.cases.append((expr, block))
+ def _genC(self):
+ l = []
+ tv = self.genVar()
+ l.append(Assignment(var=tv, expr=self.test).genC())
+ elseClause = False
+ for expr, block in self.cases:
+ ifClause = LitExpr(val=True) if expr is None else EqExpr([tv, expr])
+ if elseClause:
+ l.append("else")
+ elseClause = True
+ l.extend(("if(", ifClause.genC(), ") {", block.genC(), "}"))
+ l.append(";")
+ return tuple(l)
+
+class Counter(Stmnt, GenC):
+ def __init__(self, label, body, count, term, **kw):
super(Counter, self).__init__(**kw)
- assert isinstance(label, Label)
- assert isinstance(preCondExpr, Expr)
+ assert isinstance(label, LabelName)
+ assert isinstance(body, Block)
+ self.label = label
+ self.count = count
+ self.term = term
+ self.body = body
+ def _genC(self):
+ label = self.label.genC()
+ test = self.term.genC() if self.term is not None else ()
+ update = (self.count[0].genC(), self.count[1].genC()) \
+ if self.count is not None else ()
+ body = self.body.genC()
+ return (label, "for( ;", test, ";", update, ") {",
+ body, "}")
+
+class Iterator(Stmnt, GenC):
+ def __init__(self, label, body, count, term, **kw):
+ super(Iterator, self).__init__(**kw)
+ assert isinstance(label, LabelName)
assert isinstance(body, Block)
self.label = label
- self.preCondExpr = preCondExpr
+ self.head = head
self.body = body
+ def _genC(self):
+ label = self.label.genC()
+
+class Break(Stmnt, GenC):
+ """ Not handling labeled breaks just yet. """
+ def __init__(self, label, **kw):
+ super(Break, self).__init__(**kw)
+ assert isinstance(label, (LabelName, NoneType))
+ self.label = label
+ def _genC(self):
+ assert self.label is None
+ return "break;"
+
+class Continue(Stmnt, GenC):
+ """ Not handling labeled continue just yet. """
+ def __init__(self, label, **kw):
+ super(Continue, self).__init__(**kw)
+ assert isinstance(label, (LabelName, NoneType))
+ self.label = label
+ def _genC(self):
+ assert self.label is None
+ return "continue;"
+
+class Return(Stmnt, GenC):
+ def __init__(self, expr, **kw):
+ super(Return, self).__init__(**kw)
+ assert isinstance(expr, Expr)
+ self.expr = expr
+ def _genC(self):
+ return ("return", self.expr.genC(), ";")
class Expr(object):
def retType(self):
pass
-class LitExpr(Expr):
+class LitExpr(Expr, GenC):
def retType(self):
return { bool : BoolTyp,
int : IntTyp,
@@ -199,14 +293,14 @@ def __init__(self, val, **kw):
self.val = val
if isinstance(self.val, str):
self.subst = self.scope.allocateString(self.val)
- def genC(self):
+ def _genC(self):
t = type(self.val)
if t == bool:
- return val ? "((BoolTyp) 1)" : "((BoolTyp) 0)";
+ return val ? "((bool_t) 1)" : "((bool_t) 0)";
elif t == int:
- return "((IntTyp) " + str(self.val) + ")"
+ return "((int_t) " + str(self.val) + ")"
elif t == str:
- return ('StrObj(',) + tuple(escapeCString(self.val)) + (')',)
+ return ('str_t(',) + tuple(escapeCString(self.val)) + (')',)
else:
raise AssertionError("Unreachable, maybe val was modified?")
class CastExpr(Expr, GenC):
@@ -216,30 +310,36 @@ def __init__(self, val, typ, **kw):
assert isinstance(typ, LangTyp)
self.val = val
self.typ = typ
- def genC(self):
+ def retType(self):
+ return self.typ
+ def _genC(self):
i = self.val.retType()
o = self.typ
+
class Simple(object):
- """ Represents a keyword or punctuation in production languages. """
+ """ Represents a bareword. """
def __init__(self, term, **others):
super(Simple, self).__init__(others)
+ assert isinstance(term, str)
self.term = term
self.__dict__.update(others)
- def genC(self):
- if self.cterm is None:
- return self.term
+ def _genC(self):
+ return self.term
+ def __eq__(self, other):
+ return self.term == other.term
class VarName(Simple):
pass
class LabelName(Simple):
- pass
+ def _genC(self):
+ return self.term + ":"
class VariableExpr(Expr):
def __init__(self, var, **kw):
super(VariableExpr, self).__init__(**kw)
assert isinstance(var, Variable)
self.var = var
- def genC(self):
+ def _genC(self):
return self.var.name
class TermExpr(Expr):
@@ -262,7 +362,7 @@ def iterJoin(joiner, iterable):
class BinaryOp(TermExpr, GenC):
def op(self):
pass
- def genC(self):
+ def _genC(self):
terms = [term.genC() for term in self.terms()]
if len(terms) == 0:
return self.nullTerms().genC()
@@ -271,7 +371,7 @@ def genC(self):
class FuncOp(TermExpr, GenC):
def func(self):
pass
- def genC(self):
+ def _genC(self):
terms = [term.genC() for term in self.terms()]
func = self.func().genC()
return (func, '(',) + tuple(iterJoin(',', terms)) + (')',)
@@ -297,6 +397,9 @@ def op(self):
class LessExpr(BinaryOp):
def op(self):
return Simple('<')
+class EqExpr(BinaryOp):
+ def op(self):
+ return Simple('==')
class ConcatExpr(BinaryOp):
def op(self):
return Simple('+')
@@ -304,7 +407,7 @@ class StrLenExpr(Expr, GenC):
def __init__(self, strExpr, **kw):
super(StrLenExpr, self).__init__(**kw)
self.strExpr = strExpr
- def genC(self):
+ def _genC(self):
return (self.strExpr.genC(), '.size()')
class SlicingExpr(Expr, GenC):
def __init__(self, strExpr, **kw):
@@ -330,7 +433,7 @@ def byExpr(self):
return self.sBy
else:
return DiffExpr([StrLenExpr(self.strExpr), self.fromExpr()])
- def genC(self):
+ def _genC(self):
return ('sliceFromBy(', self.strExpr.genC(), ',',
self.fromExpr().genC(), ',',
self.byExpr().genC(), ')')
@@ -339,14 +442,14 @@ def __init__(self, agg, **kw):
super(FirstExpr, self).__init__(**kw)
assert isinstance(agg, Expr)
self.agg = agg
- def genC(self):
+ def _genC(self):
return ('(*(', self.agg.genC(), '.begin()))')
class LastExpr(Expr, GenC):
def __init__(self, agg, **kw):
super(LastExpr, self).__init__(**kw)
assert isinstance(agg, Expr)
self.agg = agg
- def genC(self):
+ def _genC(self):
return ('(*(', self.agg.genC(), '.end()))')
class MaxExpr(FuncOp):
def func(self):
@@ -367,9 +470,11 @@ def op(self):
# Types
class LangType(object):
- @property
- def name(self):
- pass
+ def __eq__(self, other):
+ if not isinstance(other, LangType):
+ return False
+ return self.name == other.name
+
class Builtin(LangType):
pass
class Atomic(Builtin, GenC):
@@ -383,13 +488,8 @@ def name(self):
@property
def pytyp(self):
return self._pytyp
- def genC(self):
- return self.name + 'T'
- def __eq__(self, other):
- return self == other or (
- isinstance(other, Atomic) and
- self.name == other.name and
- self.pytyp == other.pytyp)
+ def _genC(self):
+ return self.name + '_t'
voidTyp = Atomic('void', NoneType)
boolTyp = Atomic('bool', bool)
intTyp = Atomic('int', int)
@@ -411,13 +511,22 @@ def __init__(self, bigness, keyTyp, valTyp, **kw):
(str, False) : Simple('hash_map'),
(str, True): Simple('hash_set')
}
- def genC(self):
- k, v = (self.keyType.pytyp, self.valType.pytyp == NoneType)
+ def _genC(self):
+ k, v = (self.keyType.pytyp, self.valType.pytyp == voidTyp)
if v:
- return "%s<%s>" % (MapTyp.containers[k,v], self.keyType.genC())
+ return "%s<%s>" % (MapTyp.containers[k,v],
+ self.keyType.genC())
else:
- return "%s<%s, %s>" % (MapTyp.containers[k,v], self.keyType.genC(),
+ return "%s<%s, %s>" % (MapTyp.containers[k,v],
+ self.keyType.genC(),
self.valType.genC())
+ @property
+ def name(self):
+ if self.valType is voidTyp:
+ return "set_of_" + self.keyType.name
+ else:
+ return "map_%s_by_%s" % (self.keyType.name,
+ self.valType.name)
def allAtomicTypes():
""" Iterator that yields all possible atomic types. """
yield voidTyp
View
110 LolGrammer.py
@@ -18,7 +18,7 @@ def build(r):
# Define keywords here so I can add misspellings.
for w in ['A', 'ALL', 'AN', 'ANY', 'BAK', 'BIG', 'BIGGR', 'BIGGST',
'BOTH', 'BUKKIT', 'BY', 'DIFFRINT', 'DIFF', 'DON', 'DUZ',
- 'EITHER', 'EPIC', 'FAIL', 'FISH', 'FOUND', 'FRM', 'GIMMEH',
+ 'EITHER', 'EPIC', 'FAIL', 'FIND', 'FISH', 'FOUND', 'FRM', 'GIMMEH',
'GTFO', 'HAI', ['HAS', 'HAZ'], 'HOW', 'KEEP', 'KITTEH',
'KTHXBYE', ['I', 'AI'], 'IF', 'IM', 'IN', ['IS', 'IZ'],
'LEASTEST', 'LINE', 'LISTIN', ['MA', 'MY'], 'MAEK', 'MEBBE',
@@ -54,18 +54,18 @@ def build(r):
FuncName = ident
Label = ident
- AtomType = (~k.NOOB > r.voidT) | (~k.TROOF > r.boolT) | \
- (~k.NUMBAR > r.intT) | (~k.YARN > r.strT)
- AtomTypes = (~k.NOOBS > r.voidT) | (~k.TROOFS > r.boolT) | \
- (~k.NUMBARS > r.intT) | (~k.YARNS > r.strT)
+ AtomType = (~k.NOOB >> r.voidT) | (~k.TROOF >> r.boolT) | \
+ (~k.NUMBAR >> r.intT) | (~k.YARN >> r.strT)
+ AtomTypes = (~k.NOOBS >> r.voidT) | (~k.TROOFS >> r.boolT) | \
+ (~k.NUMBARS >> r.intT) | (~k.YARNS >> r.strT)
Bukkity = ((k.VERAH | k.BIG)[0:] & ~k.BUKKIT) > r.bigness
ComplexType = ((Bukkity & ~k.UF & AtomTypes > r.setT) | (Bukkity & ~k.LISTIN &
AtomTypes > r.listT) | (Bukkity & ~k.NAMIN & AtomTypes > r.mapT))
Type = AtomType | ComplexType
- LiteralTroof = (~k.FAIL > r.boolFalse) | (~k.WIN > r.boolTrue)
- LiteralNumbar = inttok > r.intLit
- LiteralYarn = strtok > r.strLit
+ LiteralTroof = (~k.FAIL >> r.boolFalse) | (~k.WIN >> r.boolTrue)
+ LiteralNumbar = inttok >> r.intLit
+ LiteralYarn = strtok >> r.strLit
Expr = Delayed()
@@ -78,26 +78,22 @@ def build(r):
Parenthetical = ~OPENPAREN & Expr & ~CLOSEPAREN
- NotEqual = ~k.DIFFRINT & AnPair > r.notEqual
+ NotEqual = ~k.DIFFRINT & AnPair >> r.notEqual
GreaterThan = ~k.IS & ~k.BIGGR & ThanPair > r.greaterThan
LessThan = ~k.IS & ~k.SMALLR & ThanPair > r.lessThan
BinaryEquality = ~k.BOTH & ~k.SAEM & AnPair > r.equals
Disjunction = ((~k.EITHER & OfPair > r.or_)
| (~k.ANY & OfList > r.or_))
- ExclDisjunction = ~k.WON & OfPair > r.xor
+ ExclDisjunction = ~k.WON & OfPair >> r.xor
Conjunction = ((~k.BOTH & OfPair > r.and_)
| (~k.ALL & OfList > r.and_))
- Negation = ~k.NOT & Expr > r.not_
+ Negation = ~k.NOT & Expr >> r.not_
Concatenation = ~k.SMOOSH & AnList > r.concat
- SliceFrom = k.FRM & Expr > r.sliceClause
- SliceBack = k.BAK & Expr > r.sliceClause
- SliceTo = k.TO & Expr > r.sliceClause
- SliceBy = k.BY & Expr > r.sliceClause
- Slicing = (~k.PIK & Expr & (SliceFrom | SliceBack)[0:1] &
- (SliceTo | SliceBy)[0:1]) > r.slice_
+ SliceFrom = (k.FRM | k.BAK | k.TO | k.BY) & Expr >> r.sliceClause
+ Slicing = (~k.PIK & Expr & SliceClause[0:2]) >> r.slice_
Maximum = ((~k.BIGGR & OfPair) | (~k.BIGGST & OfList)) > r.max_
Minimum = ((~k.SMALLR & OfPair) | (~k.SMALLST & OfList)) > r.min_
@@ -107,14 +103,14 @@ def build(r):
Product = ~k.PRODUKT & OfPair > r.mult
Quotient = ~k.QUOSHUNT & OfPair > r.divide
Modulus = ~k.MOD & OfPair > r.modulus
- Negative = ~k.MINUS & ~k.UF[0:1] & Expr > r.negative
+ Negative = ~k.MINUS & ~k.UF[0:1] & Expr >> r.negative
- SmallestKey = ~k.LEASTEST & ~k.UF & Expr > r.first
- GreatestKey = ~k.MOSTEST & ~k.UF & Expr > r.last
- GetValue = ~k.FISH & ~k.MA & Expr & ~k.OUTTA & Expr > r.get
+ SmallestKey = ~k.LEASTEST & ~k.UF & Expr >> r.first
+ GreatestKey = ~k.MOSTEST & ~k.UF & Expr >> r.last
+ GetValue = ~k.FISH & ~k.MA & Expr & ~k.OUTTA & Expr >> r.get
- InlineCast = ~k.MAEK & Expr & ~k.A & Type > r.cast
- FuncCall = ~k.KITTEH & FuncName & Expr[0:] & ~k.MKAY > r.call
+ InlineCast = ~k.MAEK & Expr & ~k.A & Type >> r.cast
+ FuncCall = ~k.KITTEH & FuncName & Expr[0:] & ~k.MKAY >> r.call
Expr += (Parenthetical | NotEqual | GreaterThan | LessThan |
BinaryEquality | Disjunction | ExclDisjunction | Conjunction
@@ -125,22 +121,22 @@ def build(r):
Block = Delayed()
- ExprStatement = Expr > r.exprSt
- Declaration = ~k.I & ~k.HAS & ~k.A[0:1] & Variable & ~k.IS & Type > r.decl
- Assignment = Variable & ~k.R & Expr > r.assign
+ ExprStatement = Expr >> r.exprSt
+ Declaration = ~k.I & ~k.HAS & ~k.A[0:1] & Variable & ~k.IS & Type >> r.decl
+ Assignment = Variable & ~k.R & Expr >> r.assign
InsertStatement = ~k.MA & Variable & ~k.HAS & ~k.A[0:1] & Expr & \
- (~k.BY & Expr)[0:1] > r.insertSt
+ (~k.BY & Expr)[0:1] >> r.insertSt
RemoveStatement = ~k.MA & Variable & ~k.DON & ~k.HAS & ~k.A[0:1] & \
- Expr > r.removeSt
+ Expr >> r.removeSt
UnionStatement = ~k.MIX & ~k.MA & Variable & ~k.WIV & Variable \
- > r.unionSt
+ >> r.unionSt
DiffStatement = ~k.MA & Variable & ~k.DON & ~k.HAS & ~k.FROM & \
- Variable > r.diffSt
+ Variable >> r.diffSt
InterStatement = ~k.MA & Variable & ~k.HAS & ~k.SAEM & ~k.FROM & \
- Variable > r.interSt
+ Variable >> r.interSt
- CastStatement = Variable & ~k.IS & ~k.NOW & ~k.A[0:1] & Type > r.castSt
+ CastStatement = Variable & ~k.IS & ~k.NOW & ~k.A[0:1] & Type >> r.castSt
ReadType = k.WORD | k.LINE | k.NUMBAR
InputStatement = ~k.GIMMEH & ReadType[0:1] & Variable > r.inputSt
@@ -148,42 +144,42 @@ def build(r):
| (~k.VISIBLE & Expr[1:] & ~BANG > r.outputLnSt) \
| (~k.VISIBLEZ & Expr[1:] > r.outputLnSt)
DebugStatement = (~k.INVISIBLE & Expr[1:] > r.debugSt) \
- | (~k.INVISIBLE & Expr[1:] & ~BANG > r.debugLnSt) \
- | (~k.INVISIBLEZ & Expr[1:] > r.debugLnSt)
+ | (~k.INVISIBLE & Expr[1:] & ~BANG > r.debugLnSt) \
+ | (~k.INVISIBLEZ & Expr[1:] > r.debugLnSt)
- CondBlock = ((((~k.YA & ~k.RLY) > r.posCon) | ((~k.MEBBE & Expr) > r.exprCon)
- | ((~k.NO & ~k.WAI) > r.negCon)) & ~C & Block) > r.condBlock
+ CondBlock = ((((~k.YA & ~k.RLY) >> r.posCon) | ((~k.MEBBE & Expr) >> r.exprCon)
+ | ((~k.NO & ~k.WAI) >> r.negCon)) & ~C & Block) >> r.condBlock
ConditionStatement = (Expr & ~C & ~k.O & ~k.RLY & ~QMARK[0:1] & ~C &
- CondBlock[1:] & ~k.OIC) > r.condSt
+ CondBlock[1:] & ~k.OIC) >> r.condSt
- CaseBlock = (((~k.OMG & Expr) > r.caseExpr) | ((~k.OMGWTF &
- ~BANG[0:1]) > r.caseDefault)) & C & Block
+ CaseBlock = (((~k.OMG & Expr) >> r.caseExpr) | ((~k.OMGWTF & ~BANG[0:1])
+ >> r.caseDefault)) & C & Block >> r.caseBlock
CaseStatement = (Expr & ~C & ~k.WTF & ~C & CaseBlock[1:] & ~k.OIC) \
- > r.caseSt
+ >> r.caseSt
- TermClause = (~k.TILL & Expr > r.until) | (~k.WILE & Expr > r.while_)
- LoopOpen = ~k.IM & ~k.IN & ~k.YR & Label > r.loopLabel
- LoopClose = ~k.IM & ~k.OUTTA & ~k.YR & Label > r.loopLabel
+ TermClause = (~k.TILL & Expr >> r.until) | (~k.WILE & Expr >> r.while_)
+ LoopOpen = ~k.IM & ~k.IN & ~k.YR & Label >> r.loopLabel
+ LoopClose = ~k.IM & ~k.OUTTA & ~k.YR & Label >> r.loopLabel
- CounterDir = (~k.UPPIN > r.ctrInc) | (~k.NERFIN > r.ctrDec)
- CounterHead = (CounterDir & k.YR & Variable)[0:1] & \
- TermClause[0:1] > r.ctrHead
- CounterStatement = LoopOpen & CounterHead & ~C & Block & LoopClose > r.ctrSt
+ CounterDir = ((~k.UPPIN >> r.ctrInc) | (~k.NERFIN >> r.ctrDec)) \
+ & ~k.YR & Variable >> r.ctrDir
+ CounterHead = CounterDir[0:1] & TermClause[0:1] >> r.ctrHead
+ CounterStatement = LoopOpen & CounterHead & ~C & Block & LoopClose >> r.ctrSt
IterVars = (~k.STEALIN & Variable & (~k.N & Variable)[0:1]) \
- > r.iterVars
- IterHead = (IterVars & k.YR & Variable)[0:1] & \
- TermClause[0:1] > r.iterHead
- IterStatement = LoopOpen & IterHead & ~C & Block & LoopClose > r.iterSt
+ >> r.iterVars
+ IterHead = IterVars & k.YR & Variable & \
+ TermClause[0:1] >> r.iterHead
+ IterStatement = LoopOpen & IterHead & ~C & Block & LoopClose >> r.iterSt
-
- BreakStatement = ~k.GTFO & Label[0:1] > r.breakSt
- ContinueStatement = ~k.KEEP & ~k.TRYN & Label[0:1] > r.continueSt
- ReturnStatement = ~k.FOUND & ~k.YR & Expr > r.returnSt
+ BreakStatement = ~k.GTFO & Label[0:1] >> r.breakSt
+ ContinueStatement = ~k.KEEP & ~k.TRYN & Label[0:1] >> r.continueSt
+ ReturnStatement = ~k.FOUND & ~k.YR & Expr >> r.returnSt
Arg = ~k.YR & Type[0:1] & Variable > r.arg
- ArgList = (Arg & (~k.N & Arg)[0:1])[0:1]
- FuncHead = ~k.HOW & ~k.DUZ & ~k.I & FuncName & ArgList & ~QMARK[0:1] > r.funcHead
+ ArgList = (Arg & (~k.N & Arg)[0:])[0:1] > r.args
+ ReturnClause = ~k.AN & ~k.FIND & ~k.MA & Type >> r.returnType
+ FuncHead = ~k.HOW & ~k.DUZ & ~k.I & FuncName & ArgList & ReturnClause & ~QMARK[0:1]
FuncClose = ~k.IF & ~k.U & ~k.SAY & ~k.SO
FuncDef = FuncHead & ~C & Block & FuncClose > r.funcDef
View
224 Responder.py
@@ -1,93 +1,65 @@
import CodeObjects as co
class TestResponder(object):
- def voidT(s, x):
- return "{type void}"
- def boolT(s, x):
- return "{type bool}"
- def strT(s, x):
- return "{type str}"
- def intT(s, x):
- return "{type int}"
- def bigness(s, x):
- return len(x)
- def setT(s, x):
- return "{type set valtype=%s size=%d}" % (x[1], x[0])
- def listT(s, x):
- return "{type list valtype=%s size=%d}" % (x[1], x[0])
- def mapT(s, x):
- return "{type map valtype=%s size=%d}" % (x[1], x[0])
- def boolTrue(s, x):
- return "{boolval True}"
- def boolFalse(s, x):
- return "{boolval False}"
- def intLit(s, x):
- return "{intval %s}" % x[0]
- def strLit(s, x):
- return "{strval %s}" % x[0]
def handlerFunctionClosure(s, n):
- def handlerFunction(x):
- return [n] + x
+ def handlerFunction(*x):
+ return (n,) + x
return handlerFunction
def __getattr__(s, n):
return s.handlerFunctionClosure(n)
- def posCon(s, x):
- return r.exprCon([r.boolTrue([])])
- def negCon(s, x):
- return r.exprCon([r.boolFalse([])])
class ObjResponder(object):
- def voidT(s, x):
- return co.VoidTyp()
- def boolT(s, x):
- return co.BoolTyp()
- def intT(s, x):
- return co.IntTyp()
+ def voidT(s):
+ return co.voidTyp
+ def boolT(s):
+ return co.boolTyp
+ def intT(s):
+ return co.intTyp
+ def strT(s):
+ return co.strTyp
def bigness(s, x):
return len(x)
- def setT(s, x):
- return co.mapTypOf(x[1], co.VoidTyp)(bigness=x[0])
- def listT(s, x):
+ def setT(s, t, b):
+ return co.mapTypOf(x[1], co.VoidTyp)(bigness=b)
+ def listT(s, t, b):
return co.mapTypOf(co.IntTyp, x[1])(bigness=x[0])
- def mapT(s, x):
+ def mapT(s, t, b):
return co.mapTypOf(co.StrTyp, x[1])(bigness=x[0])
- def boolTrue(s, x):
+ def boolTrue(s):
return co.LitExpr(val=True)
- def boolFalse(s, x):
+ def boolFalse(s):
return co.LitExpr(val=False)
- def intLit(s, x):
- return co.LitExpr(val=int(x[0]))
- def strLit(s, x):
+ def intLit(s, v):
+ return co.LitExpr(val=int(v))
+ def strLit(s, v):
d = { ':' : ':', ')' : '\n', '>' : '\t', 'o' : '\x07',
'"' : '"' }
return co.LitExpr(
re.sub(':(.)', lambda m: d[m.group(1)]
if m.group(1) in d
- else m.group(0), x[0][1:-1]))
- def posCon(s, x):
- return r.exprCon([r.boolTrue([])])
- def negCon(s, x):
- return r.exprCon([r.boolFalse([])])
- def notEqual(s, x):
- return co.NegateExpr(co.EqualityExpr(x[0:2]))
- def greaterThan(s, x):
- return co.GrtExpr(terms=x[0:2])
- def lessThan(s, x):
- return co.LessExpr(terms=x[0:2])
- def equals(s, x):
- return co.EqualityExpr(terms=x[0:2])
+ else m.group(0), v[1:-1]))
+ def notEqual(s, a, b):
+ return co.NegateExpr(co.EqExpr(terms=(a, b)))
+ def greaterThan(s, a, b):
+ return co.GrtExpr(terms=(a, b))
+ def lessThan(s, a, b):
+ return co.LessExpr(terms=(a, b))
+ def equals(s, a, b):
+ return co.EqExpr(terms=(a, b))
def or_(s, x):
return co.OrExpr(terms=x)
+ def xor(s, a, b):
+ return co.OrExpr(terms=(a, b))
def and_(s, x):
return co.AndExpr(terms=x)
def not_(s, x):
- return co.NegateExpr(x[0])
+ return co.NegateExpr(x)
def concat(s, x):
return co.ConcatExpr(x)
- def sliceClause(s, x):
- return (x[0].lower(), x[1])
- def slice_(s, x):
- return co.SlicingExpr(strExpr=x[0], **dict(x[1:]))
+ def sliceClause(s, o, x):
+ return (o.lower(), x)
+ def slice_(s, x, *c):
+ return co.SlicingExpr(strExpr=x, **dict(c))
def max_(s, x):
return co.MaxExpr(terms=x)
def min_(s, x):
@@ -103,37 +75,38 @@ def mult(s, x):
def modulus(s, x):
return co.ModExpr(terms=x)
def negative(s, x):
- return co.DiffExpr(terms=[0, x[0]])
+ return co.DiffExpr(terms=[0, x])
def first(s, x):
return co.FirstExpr(agg=x)
def last(s, x):
return co.LastExpr(agg=x)
- def get(s, x):
- return co.GetExpr(subj=x[1], index=x[0])
- def cast(s, x):
- return co.CastExpr(val=x[0], typ=x[1])
- def call(s, x):
- return co.CallExpr(head=x[0], args=x[1:])
+ def get(s, i, a):
+ return co.GetExpr(subj=a, index=i)
+ def cast(s, v, t):
+ return co.CastExpr(val=v, typ=t)
+ def call(s, h, *a):
+ return co.CallExpr(head=h, args=a)
def exprSt(s, x):
- return co.ExprStmnt(expr=x[0])
- def decl(s, x):
- return co.Declaration(var=x[0], typ=x[1])
- def assign(s, x):
- return co.Assignment(var=x[0], expr=x[1])
- def insertSt(s, x):
- return co.InsertStmnt(agg=x[0], key=x[1],
- val=x[2] if len(x)>2 else None)
- def removeSt(s, x):
- return co.RemoveStmnt(agg=x[0], key=x[1])
- def unionSt(s, x):
- return co.UnionStmnt(lagg=x[0], ragg=x[1])
- def diffSt(s, x):
- return co.DiffStmnt(lagg=x[0], ragg=x[1])
- def interSt(s, x):
- return co.InterStmnt(lagg=x[0], ragg=x[1])
- def castSt(s, x):
- return co.Assignment(var=x[0], expr=co.CastExpr(
- val=co.VariableExpr(var=x[0]), typ=x[1]))
+ return co.ExprStmnt(expr=x)
+ def decl(s, v, t):
+ return co.Declaration(var=v, typ=t)
+ def assign(s, v, x):
+ return co.Assignment(var=v, expr=x)
+ def insertSt(s, a, k, v*):
+ assert len(v) < 2
+ return co.InsertStmnt(agg=a, key=k,
+ val=v[0] if v else None)
+ def removeSt(s, a, k):
+ return co.RemoveStmnt(agg=a, key=k)
+ def unionSt(s, l, r):
+ return co.UnionStmnt(lagg=l, ragg=r)
+ def diffSt(s, l, r):
+ return co.DiffStmnt(lagg=l, ragg=r)
+ def interSt(s, l, r):
+ return co.InterStmnt(lagg=l, ragg=r)
+ def castSt(s, v, t):
+ return co.Assignment(var=v, expr=co.CastExpr(
+ val=co.VariableExpr(var=v), typ=t))
def inputSt(s, x):
readType, var = (['LINE'] + x)[-2:]
return co.InputStmnt(var=var, read=readType.lower())
@@ -146,24 +119,65 @@ def debugSt(s, x):
def debugLnSt(s, x):
return co.OutputStmnt(handle='err', terms=x, nl=True)
def posCon(s, x):
- return co.LitExpr(val=True)
+ return (True, None)
def negCon(s, x):
- return co.LitExpr(val=False)
+ return (False, None)
def exprCon(s, x):
- return x[0]
- def condBlock(s, x):
- e, b = x
- return (e, b)
- def condSt(s, x):
- return co.Conditional(cases=x)
+ return (None, x)
+ def condBlock(s, e, b):
+ return e + (b,)
+ def condSt(s, x, c*):
+ return co.Conditional(test=x, blocks=c)
+ def caseExpr(s, x):
+ return x
+ def caseDefault(s, x):
+ return None
+ def caseBlock(s, x, b):
+ return (x, b)
+ def caseSt(s, x, b*):
+ return co.Case(test=x, blocks=b)
def until(s, x):
- return ('until', x[0])
+ return {'term': co.NegateExpr(x)}
def while_(s, x):
- return ('while', x[0])
+ return {'term': x}
def loopLabel(s, x):
- return co.LabelName(x[0])
- def ctrInc(s, x):
- return Simple('++')
- def ctrDec(s, x):
- return Simple('--')
-
+ return co.LabelName(x)
+ def ctrInc(s):
+ return co.Simple('++')
+ def ctrDec(s):
+ return co.Simple('--')
+ def ctrDir(s, d, v):
+ return {'count': (v, d)}
+ def ctrHead(s, c*):
+ d = { 'count': None, 'term': None }
+ d.update(c)
+ return d
+ def ctrSt(s, lo, h, b, lc):
+ assert lo == lc
+ return co.Counter(lo, b, **h)
+ def iterVars(s, iv, vv=None):
+ return {'iter': iv, 'iterVal': vv }
+ def iterHead(s, v, agg, tc=None):
+ d = {}
+ d.update(v)
+ d['agg'] = agg
+ d.update(tc)
+ return d
+ def iterSt(s, lo, h, b, lc):
+ assert lo == lc
+ return co.Iterator(lo, b, **h)
+ def breakSt(s, label=None):
+ return co.Break(label)
+ def continueSt(s, label=None):
+ return co.Continue(label)
+ def returnSt(s, expr):
+ return co.Return(expr)
+ def arg(s, a):
+ d = {'var': a[-1]}
+ d['type'] = a[0] if len(a) > 1
+ def args(s, ax):
+ return tuple(ax)
+ def returnType(s, t):
+ return t
+ def funcDef(s, nm, ax, t, b):
+ return co.
View
171 framework.h
@@ -1,21 +1,188 @@
#include <memory>
#include <string>
+// For casting strings.
+#include <sstream>
+#include <map>
+#include <set>
#include <ext/hash_map>
+#include <ext/hash_set>
using namespace std;
typedef int int_t;
typedef string str_t;
typedef bool bool_t;
+struct void_t { };
const str_t str_slice_from_to(const str_t& s, int_t from, int_t to) {
- int sl = s.length();
+ const int sl = s.length();
if(from < 0)
from = 0;
if(from >= sl || to <= from)
- return str_ret(new str_t());
+ return str_t();
if(to > sl)
to = sl;
return str_t(s, from, to - from);
}
+// a = union(a, b), keeping values from b
+/*
+template<typename K, typename D>
+void unionAssign(map<K, D>& a, map<K, D>& b) {
+ typedef map<K, D> M;
+ typedef M::const_iterator MI;
+ MI b_end = b.end();
+ for(MI i = b.begin(); i != b_end; ++i)
+ a[i->first] = i->second;
+}
+
+template<typename K>
+void unionAssign(set<K>& a, set<K>& b) {
+ typedef set<K> S;
+ typedef S::const_iterator SI;
+ SI b_end = b.end();
+ for(SI i = b.begin(); i != b_end; ++i)
+ a.insert(*i);
+}
+*/
+
+template<typename M>
+void unionAssign(M& a, const M& b) {
+ a.insert(b.begin(), b.end());
+}
+
+// a = inter(a, b), keeping values from b
+template<typename K, typename D>
+void interAssign(map<K, D>& a, map<K, D>& b) {
+ typedef map<K, D> M;
+ typedef M::iterator MI;
+ MI a_end = a.end(), b_end = b.end();
+ for(MI i = a.begin(); i != a_end; ++i) {
+ MI j = b.find(i->first);
+ if(j == b_end) // key didn't exist
+ a.erase(i);
+ else
+ i->second = j->second;
+ }
+}
+
+template<typename K>
+void interAssign(set<K>& a, set<K>& b) {
+ typedef set<K> S;
+ typedef S::iterator SI;
+ SI a_end = a.end();
+ for(SI i = a.begin(); i != a_end; ++i) {
+ if(!b.count(*i))
+ a.erase(*i);
+ }
+}
+
+// a = a - b
+template<typename M>
+void diffAssign(M& a, M& b) {
+ M::iterator b_end = b.end();
+ for(M::iterator i = b.begin(); i != b_end; ++i)
+ a.erase(i->first);
+}
+
+template<class T, class U>
+const U lol_cast(const T& x) {
+ return (U) x;
+}
+
+template<>
+const bool_t lol_cast(const str_t& x) {
+ return !x.empty();
+}
+
+template<>
+const int_t lol_cast(const bool_t& x) {
+ return x ? 1 : 0;
+}
+
+template<>
+const bool_t lol_cast(const int_t& x) {
+ return x != 0;
+}
+
+template<>
+const int_t lol_cast(const str_t& x) {
+ istringstream iss(x, istringstream::in);
+ int_t v;
+ iss >> dec >> v;
+ return v;
+}
+
+template<>
+const str_t lol_cast(const bool_t x) {
+ str_t v(x ? "true" : "false");
+ return v;
+}
+
+template<>
+const str_t lol_cast(const int_t x) {
+ ostringstream oss;
+ oss << x;
+ return oss.str();
+}
+
+template<class T>
+const bool_t lol_cast(const T& x) {
+ return x.empty();
+}
+
+template<class T>
+const int_t lol_cast(const T& x) {
+ return x.size();
+}
+
+template<class T>
+const str_t lol_cast(const set<T>& x) {
+ ostringstream oss;
+ oss << "{ ";
+ for(set<T>::const_iterator i=x.begin(); i != x.end(); ++i) {
+ if(i != x.begin())
+ oss << ", ";
+ oss << *i;
+ }
+ oss << " }";
+ return oss.str();
+}
+
+template<class T, class U>
+const str_t lol_cast(const map<T, U>& x) {
+ ostringstream oss;
+ oss << "{ ";
+ for(map<T, U>::const_iterator i=x.begin(); i != x.end(); ++i) {
+ if(i != x.begin())
+ oss << ", ";
+ oss << i->first << ": " << i->second;
+ }
+ oss << " }";
+ return oss.str();
+}
+
+
+template<class T>
+const set<T> lol_cast(const T& x) {
+ set<T> s;
+ s.insert(x);
+ return s;
+}
+
+template<class T, class U>
+const set<T> lol_cast(const map<T, U>& x) {
+ set<T> s;
+ for(map<T, U>::const_iterator i=x.begin(); i != x.end(); ++i)
+ s.insert(i->first);
+ return s;
+}
+
+template<class T, class U>
+const map<T, U> lol_cast(const set<T>& x) {
+ map<T, U> m;
+ for(set<T>::const_iterator i=x.begin(); i != x.end(); ++i)
+ m.insert(pair<T, U>(*i, U()));
+ return m;
+}
+
Please sign in to comment.
Something went wrong with that request. Please try again.