Commit ae833cb2 by Stalin Munoz

Proyecto inicial de bios club

parents
/*******************************************************************************
*
* GRIFFIN Software,
* Copyright (c) 2015-2019
* Instituto de Investigaciones en Matematicas Aplicadas y en Sistemas
* (IIMAS http://www.iimas.unam.mx).
* Centro de Ciencias de la Complejidad
* Universidad Nacional Autónoma de México.
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*******************************************************************************/
/**
* Grammar for boolean sentences
*
**/
grammar BooleanSentence;
init: sentence
;
sentence: TRUE #TrueSentence
| FALSE #FalseSentence
| VAR #AtomSentence
| '(' sentence ')' #ParentSentence
| NOT sentence #NotSentence
| sentence AND sentence #AndSentence
| sentence OR sentence #OrSentence
| sentence IMP sentence #ImplicationSentence
| sentence EQ sentence #EquivalenceSentence
;
TRUE: '1'
;
FALSE: '0'
;
VAR: [a-zA-Z_]+[a-zA-Z_0-9/]*
;
NOT: '~'
| '!'
| '¬'
;
AND: '&'
| '^'
| '*'
;
OR: '|'
| '||'
| '+'
;
IMP: '->'
| '=>'
;
EQ: '='
| '<->'
| '<=>'
;
BLANK: [ \t\r\n]+ -> skip
;
T__0=1
T__1=2
TRUE=3
FALSE=4
VAR=5
NOT=6
AND=7
OR=8
IMP=9
EQ=10
BLANK=11
'('=1
')'=2
'1'=3
'0'=4
# Generated from BooleanSentence.g4 by ANTLR 4.5.1
from antlr4 import *
from io import StringIO
def serializedATN():
with StringIO() as buf:
buf.write("\3\u0430\ud6d1\u8206\uad2d\u4417\uaef1\u8d80\uaadd\2\r")
buf.write("L\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7")
buf.write("\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\3\2\3\2\3\3")
buf.write("\3\3\3\4\3\4\3\5\3\5\3\6\6\6#\n\6\r\6\16\6$\3\6\7\6(\n")
buf.write("\6\f\6\16\6+\13\6\3\7\3\7\3\b\3\b\3\t\3\t\3\t\3\t\5\t")
buf.write("\65\n\t\3\n\3\n\3\n\3\n\5\n;\n\n\3\13\3\13\3\13\3\13\3")
buf.write("\13\3\13\3\13\5\13D\n\13\3\f\6\fG\n\f\r\f\16\fH\3\f\3")
buf.write("\f\2\2\r\3\3\5\4\7\5\t\6\13\7\r\b\17\t\21\n\23\13\25\f")
buf.write("\27\r\3\2\7\5\2C\\aac|\6\2\61;C\\aac|\5\2##\u0080\u0080")
buf.write("\u00ae\u00ae\5\2((,,``\5\2\13\f\17\17\"\"S\2\3\3\2\2\2")
buf.write("\2\5\3\2\2\2\2\7\3\2\2\2\2\t\3\2\2\2\2\13\3\2\2\2\2\r")
buf.write("\3\2\2\2\2\17\3\2\2\2\2\21\3\2\2\2\2\23\3\2\2\2\2\25\3")
buf.write("\2\2\2\2\27\3\2\2\2\3\31\3\2\2\2\5\33\3\2\2\2\7\35\3\2")
buf.write("\2\2\t\37\3\2\2\2\13\"\3\2\2\2\r,\3\2\2\2\17.\3\2\2\2")
buf.write("\21\64\3\2\2\2\23:\3\2\2\2\25C\3\2\2\2\27F\3\2\2\2\31")
buf.write("\32\7*\2\2\32\4\3\2\2\2\33\34\7+\2\2\34\6\3\2\2\2\35\36")
buf.write("\7\63\2\2\36\b\3\2\2\2\37 \7\62\2\2 \n\3\2\2\2!#\t\2\2")
buf.write("\2\"!\3\2\2\2#$\3\2\2\2$\"\3\2\2\2$%\3\2\2\2%)\3\2\2\2")
buf.write("&(\t\3\2\2\'&\3\2\2\2(+\3\2\2\2)\'\3\2\2\2)*\3\2\2\2*")
buf.write("\f\3\2\2\2+)\3\2\2\2,-\t\4\2\2-\16\3\2\2\2./\t\5\2\2/")
buf.write("\20\3\2\2\2\60\65\7~\2\2\61\62\7~\2\2\62\65\7~\2\2\63")
buf.write("\65\7-\2\2\64\60\3\2\2\2\64\61\3\2\2\2\64\63\3\2\2\2\65")
buf.write("\22\3\2\2\2\66\67\7/\2\2\67;\7@\2\289\7?\2\29;\7@\2\2")
buf.write(":\66\3\2\2\2:8\3\2\2\2;\24\3\2\2\2<D\7?\2\2=>\7>\2\2>")
buf.write("?\7/\2\2?D\7@\2\2@A\7>\2\2AB\7?\2\2BD\7@\2\2C<\3\2\2\2")
buf.write("C=\3\2\2\2C@\3\2\2\2D\26\3\2\2\2EG\t\6\2\2FE\3\2\2\2G")
buf.write("H\3\2\2\2HF\3\2\2\2HI\3\2\2\2IJ\3\2\2\2JK\b\f\2\2K\30")
buf.write("\3\2\2\2\t\2$)\64:CH\3\b\2\2")
return buf.getvalue()
class BooleanSentenceLexer(Lexer):
atn = ATNDeserializer().deserialize(serializedATN())
decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
T__0 = 1
T__1 = 2
TRUE = 3
FALSE = 4
VAR = 5
NOT = 6
AND = 7
OR = 8
IMP = 9
EQ = 10
BLANK = 11
modeNames = [ "DEFAULT_MODE" ]
literalNames = [ "<INVALID>",
"'('", "')'", "'1'", "'0'" ]
symbolicNames = [ "<INVALID>",
"TRUE", "FALSE", "VAR", "NOT", "AND", "OR", "IMP", "EQ", "BLANK" ]
ruleNames = [ "T__0", "T__1", "TRUE", "FALSE", "VAR", "NOT", "AND",
"OR", "IMP", "EQ", "BLANK" ]
grammarFileName = "BooleanSentence.g4"
def __init__(self, input=None):
super().__init__(input)
self.checkVersion("4.5.1")
self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())
self._actions = None
self._predicates = None
T__0=1
T__1=2
TRUE=3
FALSE=4
VAR=5
NOT=6
AND=7
OR=8
IMP=9
EQ=10
BLANK=11
'('=1
')'=2
'1'=3
'0'=4
# Generated from BooleanSentence.g4 by ANTLR 4.5.1
from antlr4 import *
if __name__ is not None and "." in __name__:
from .BooleanSentenceParser import BooleanSentenceParser
else:
from BooleanSentenceParser import BooleanSentenceParser
# This class defines a complete listener for a parse tree produced by BooleanSentenceParser.
class BooleanSentenceListener(ParseTreeListener):
# Enter a parse tree produced by BooleanSentenceParser#init.
def enterInit(self, ctx:BooleanSentenceParser.InitContext):
pass
# Exit a parse tree produced by BooleanSentenceParser#init.
def exitInit(self, ctx:BooleanSentenceParser.InitContext):
pass
# Enter a parse tree produced by BooleanSentenceParser#NotSentence.
def enterNotSentence(self, ctx:BooleanSentenceParser.NotSentenceContext):
pass
# Exit a parse tree produced by BooleanSentenceParser#NotSentence.
def exitNotSentence(self, ctx:BooleanSentenceParser.NotSentenceContext):
pass
# Enter a parse tree produced by BooleanSentenceParser#TrueSentence.
def enterTrueSentence(self, ctx:BooleanSentenceParser.TrueSentenceContext):
pass
# Exit a parse tree produced by BooleanSentenceParser#TrueSentence.
def exitTrueSentence(self, ctx:BooleanSentenceParser.TrueSentenceContext):
pass
# Enter a parse tree produced by BooleanSentenceParser#AtomSentence.
def enterAtomSentence(self, ctx:BooleanSentenceParser.AtomSentenceContext):
pass
# Exit a parse tree produced by BooleanSentenceParser#AtomSentence.
def exitAtomSentence(self, ctx:BooleanSentenceParser.AtomSentenceContext):
pass
# Enter a parse tree produced by BooleanSentenceParser#AndSentence.
def enterAndSentence(self, ctx:BooleanSentenceParser.AndSentenceContext):
pass
# Exit a parse tree produced by BooleanSentenceParser#AndSentence.
def exitAndSentence(self, ctx:BooleanSentenceParser.AndSentenceContext):
pass
# Enter a parse tree produced by BooleanSentenceParser#ParentSentence.
def enterParentSentence(self, ctx:BooleanSentenceParser.ParentSentenceContext):
pass
# Exit a parse tree produced by BooleanSentenceParser#ParentSentence.
def exitParentSentence(self, ctx:BooleanSentenceParser.ParentSentenceContext):
pass
# Enter a parse tree produced by BooleanSentenceParser#EquivalenceSentence.
def enterEquivalenceSentence(self, ctx:BooleanSentenceParser.EquivalenceSentenceContext):
pass
# Exit a parse tree produced by BooleanSentenceParser#EquivalenceSentence.
def exitEquivalenceSentence(self, ctx:BooleanSentenceParser.EquivalenceSentenceContext):
pass
# Enter a parse tree produced by BooleanSentenceParser#OrSentence.
def enterOrSentence(self, ctx:BooleanSentenceParser.OrSentenceContext):
pass
# Exit a parse tree produced by BooleanSentenceParser#OrSentence.
def exitOrSentence(self, ctx:BooleanSentenceParser.OrSentenceContext):
pass
# Enter a parse tree produced by BooleanSentenceParser#FalseSentence.
def enterFalseSentence(self, ctx:BooleanSentenceParser.FalseSentenceContext):
pass
# Exit a parse tree produced by BooleanSentenceParser#FalseSentence.
def exitFalseSentence(self, ctx:BooleanSentenceParser.FalseSentenceContext):
pass
# Enter a parse tree produced by BooleanSentenceParser#ImplicationSentence.
def enterImplicationSentence(self, ctx:BooleanSentenceParser.ImplicationSentenceContext):
pass
# Exit a parse tree produced by BooleanSentenceParser#ImplicationSentence.
def exitImplicationSentence(self, ctx:BooleanSentenceParser.ImplicationSentenceContext):
pass
# Generated from BooleanSentence.g4 by ANTLR 4.5.1
# encoding: utf-8
from antlr4 import *
from io import StringIO
def serializedATN():
with StringIO() as buf:
buf.write("\3\u0430\ud6d1\u8206\uad2d\u4417\uaef1\u8d80\uaadd\3\r")
buf.write("&\4\2\t\2\4\3\t\3\3\2\3\2\3\3\3\3\3\3\3\3\3\3\3\3\3\3")
buf.write("\3\3\3\3\3\3\5\3\23\n\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3")
buf.write("\3\3\3\3\3\3\3\3\3\7\3!\n\3\f\3\16\3$\13\3\3\3\2\3\4\4")
buf.write("\2\4\2\2+\2\6\3\2\2\2\4\22\3\2\2\2\6\7\5\4\3\2\7\3\3\2")
buf.write("\2\2\b\t\b\3\1\2\t\n\7\b\2\2\n\23\5\4\3\7\13\23\7\5\2")
buf.write("\2\f\23\7\6\2\2\r\23\7\7\2\2\16\17\7\3\2\2\17\20\5\4\3")
buf.write("\2\20\21\7\4\2\2\21\23\3\2\2\2\22\b\3\2\2\2\22\13\3\2")
buf.write("\2\2\22\f\3\2\2\2\22\r\3\2\2\2\22\16\3\2\2\2\23\"\3\2")
buf.write("\2\2\24\25\f\6\2\2\25\26\7\t\2\2\26!\5\4\3\7\27\30\f\5")
buf.write("\2\2\30\31\7\n\2\2\31!\5\4\3\6\32\33\f\4\2\2\33\34\7\13")
buf.write("\2\2\34!\5\4\3\5\35\36\f\3\2\2\36\37\7\f\2\2\37!\5\4\3")
buf.write("\4 \24\3\2\2\2 \27\3\2\2\2 \32\3\2\2\2 \35\3\2\2\2!$\3")
buf.write("\2\2\2\" \3\2\2\2\"#\3\2\2\2#\5\3\2\2\2$\"\3\2\2\2\5\22")
buf.write(" \"")
return buf.getvalue()
class BooleanSentenceParser ( Parser ):
grammarFileName = "BooleanSentence.g4"
atn = ATNDeserializer().deserialize(serializedATN())
decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
sharedContextCache = PredictionContextCache()
literalNames = [ "<INVALID>", "'('", "')'", "'1'", "'0'" ]
symbolicNames = [ "<INVALID>", "<INVALID>", "<INVALID>", "TRUE", "FALSE",
"VAR", "NOT", "AND", "OR", "IMP", "EQ", "BLANK" ]
RULE_init = 0
RULE_sentence = 1
ruleNames = [ "init", "sentence" ]
EOF = Token.EOF
T__0=1
T__1=2
TRUE=3
FALSE=4
VAR=5
NOT=6
AND=7
OR=8
IMP=9
EQ=10
BLANK=11
def __init__(self, input:TokenStream):
super().__init__(input)
self.checkVersion("4.5.1")
self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache)
self._predicates = None
class InitContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def sentence(self):
return self.getTypedRuleContext(BooleanSentenceParser.SentenceContext,0)
def getRuleIndex(self):
return BooleanSentenceParser.RULE_init
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterInit" ):
listener.enterInit(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitInit" ):
listener.exitInit(self)
def init(self):
localctx = BooleanSentenceParser.InitContext(self, self._ctx, self.state)
self.enterRule(localctx, 0, self.RULE_init)
try:
self.enterOuterAlt(localctx, 1)
self.state = 4
self.sentence(0)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class SentenceContext(ParserRuleContext):
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def getRuleIndex(self):
return BooleanSentenceParser.RULE_sentence
def copyFrom(self, ctx:ParserRuleContext):
super().copyFrom(ctx)
class NotSentenceContext(SentenceContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a BooleanSentenceParser.SentenceContext
super().__init__(parser)
self.copyFrom(ctx)
def NOT(self):
return self.getToken(BooleanSentenceParser.NOT, 0)
def sentence(self):
return self.getTypedRuleContext(BooleanSentenceParser.SentenceContext,0)
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterNotSentence" ):
listener.enterNotSentence(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitNotSentence" ):
listener.exitNotSentence(self)
class TrueSentenceContext(SentenceContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a BooleanSentenceParser.SentenceContext
super().__init__(parser)
self.copyFrom(ctx)
def TRUE(self):
return self.getToken(BooleanSentenceParser.TRUE, 0)
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterTrueSentence" ):
listener.enterTrueSentence(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitTrueSentence" ):
listener.exitTrueSentence(self)
class AtomSentenceContext(SentenceContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a BooleanSentenceParser.SentenceContext
super().__init__(parser)
self.copyFrom(ctx)
def VAR(self):
return self.getToken(BooleanSentenceParser.VAR, 0)
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterAtomSentence" ):
listener.enterAtomSentence(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitAtomSentence" ):
listener.exitAtomSentence(self)
class AndSentenceContext(SentenceContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a BooleanSentenceParser.SentenceContext
super().__init__(parser)
self.copyFrom(ctx)
def sentence(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(BooleanSentenceParser.SentenceContext)
else:
return self.getTypedRuleContext(BooleanSentenceParser.SentenceContext,i)
def AND(self):
return self.getToken(BooleanSentenceParser.AND, 0)
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterAndSentence" ):
listener.enterAndSentence(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitAndSentence" ):
listener.exitAndSentence(self)
class ParentSentenceContext(SentenceContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a BooleanSentenceParser.SentenceContext
super().__init__(parser)
self.copyFrom(ctx)
def sentence(self):
return self.getTypedRuleContext(BooleanSentenceParser.SentenceContext,0)
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterParentSentence" ):
listener.enterParentSentence(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitParentSentence" ):
listener.exitParentSentence(self)
class EquivalenceSentenceContext(SentenceContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a BooleanSentenceParser.SentenceContext
super().__init__(parser)
self.copyFrom(ctx)
def sentence(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(BooleanSentenceParser.SentenceContext)
else:
return self.getTypedRuleContext(BooleanSentenceParser.SentenceContext,i)
def EQ(self):
return self.getToken(BooleanSentenceParser.EQ, 0)
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterEquivalenceSentence" ):
listener.enterEquivalenceSentence(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitEquivalenceSentence" ):
listener.exitEquivalenceSentence(self)
class OrSentenceContext(SentenceContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a BooleanSentenceParser.SentenceContext
super().__init__(parser)
self.copyFrom(ctx)
def sentence(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(BooleanSentenceParser.SentenceContext)
else:
return self.getTypedRuleContext(BooleanSentenceParser.SentenceContext,i)
def OR(self):
return self.getToken(BooleanSentenceParser.OR, 0)
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterOrSentence" ):
listener.enterOrSentence(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitOrSentence" ):
listener.exitOrSentence(self)
class FalseSentenceContext(SentenceContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a BooleanSentenceParser.SentenceContext
super().__init__(parser)
self.copyFrom(ctx)
def FALSE(self):
return self.getToken(BooleanSentenceParser.FALSE, 0)
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterFalseSentence" ):
listener.enterFalseSentence(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitFalseSentence" ):
listener.exitFalseSentence(self)
class ImplicationSentenceContext(SentenceContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a BooleanSentenceParser.SentenceContext
super().__init__(parser)
self.copyFrom(ctx)
def sentence(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(BooleanSentenceParser.SentenceContext)
else:
return self.getTypedRuleContext(BooleanSentenceParser.SentenceContext,i)
def IMP(self):
return self.getToken(BooleanSentenceParser.IMP, 0)
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterImplicationSentence" ):
listener.enterImplicationSentence(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitImplicationSentence" ):
listener.exitImplicationSentence(self)
def sentence(self, _p:int=0):
_parentctx = self._ctx
_parentState = self.state
localctx = BooleanSentenceParser.SentenceContext(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 2
self.enterRecursionRule(localctx, 2, self.RULE_sentence, _p)
try:
self.enterOuterAlt(localctx, 1)
self.state = 16
token = self._input.LA(1)
if token in [BooleanSentenceParser.NOT]:
localctx = BooleanSentenceParser.NotSentenceContext(self, localctx)
self._ctx = localctx
_prevctx = localctx
self.state = 7
self.match(BooleanSentenceParser.NOT)
self.state = 8
self.sentence(5)
elif token in [BooleanSentenceParser.TRUE]:
localctx = BooleanSentenceParser.TrueSentenceContext(self, localctx)
self._ctx = localctx
_prevctx = localctx
self.state = 9
self.match(BooleanSentenceParser.TRUE)
elif token in [BooleanSentenceParser.FALSE]:
localctx = BooleanSentenceParser.FalseSentenceContext(self, localctx)
self._ctx = localctx
_prevctx = localctx
self.state = 10
self.match(BooleanSentenceParser.FALSE)
elif token in [BooleanSentenceParser.VAR]:
localctx = BooleanSentenceParser.AtomSentenceContext(self, localctx)
self._ctx = localctx
_prevctx = localctx
self.state = 11
self.match(BooleanSentenceParser.VAR)
elif token in [BooleanSentenceParser.T__0]:
localctx = BooleanSentenceParser.ParentSentenceContext(self, localctx)
self._ctx = localctx
_prevctx = localctx
self.state = 12
self.match(BooleanSentenceParser.T__0)
self.state = 13
self.sentence(0)
self.state = 14
self.match(BooleanSentenceParser.T__1)
else:
raise NoViableAltException(self)
self._ctx.stop = self._input.LT(-1)
self.state = 32
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,2,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
self.state = 30
la_ = self._interp.adaptivePredict(self._input,1,self._ctx)
if la_ == 1:
localctx = BooleanSentenceParser.AndSentenceContext(self, BooleanSentenceParser.SentenceContext(self, _parentctx, _parentState))
self.pushNewRecursionContext(localctx, _startState, self.RULE_sentence)
self.state = 18
if not self.precpred(self._ctx, 4):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 4)")
self.state = 19
self.match(BooleanSentenceParser.AND)
self.state = 20
self.sentence(5)
pass
elif la_ == 2:
localctx = BooleanSentenceParser.OrSentenceContext(self, BooleanSentenceParser.SentenceContext(self, _parentctx, _parentState))
self.pushNewRecursionContext(localctx, _startState, self.RULE_sentence)
self.state = 21
if not self.precpred(self._ctx, 3):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 3)")
self.state = 22
self.match(BooleanSentenceParser.OR)
self.state = 23
self.sentence(4)
pass
elif la_ == 3:
localctx = BooleanSentenceParser.ImplicationSentenceContext(self, BooleanSentenceParser.SentenceContext(self, _parentctx, _parentState))
self.pushNewRecursionContext(localctx, _startState, self.RULE_sentence)
self.state = 24
if not self.precpred(self._ctx, 2):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 2)")
self.state = 25
self.match(BooleanSentenceParser.IMP)
self.state = 26
self.sentence(3)
pass
elif la_ == 4:
localctx = BooleanSentenceParser.EquivalenceSentenceContext(self, BooleanSentenceParser.SentenceContext(self, _parentctx, _parentState))
self.pushNewRecursionContext(localctx, _startState, self.RULE_sentence)
self.state = 27
if not self.precpred(self._ctx, 1):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 1)")
self.state = 28
self.match(BooleanSentenceParser.EQ)
self.state = 29
self.sentence(2)
pass
self.state = 34
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,2,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
def sempred(self, localctx:RuleContext, ruleIndex:int, predIndex:int):
if self._predicates == None:
self._predicates = dict()
self._predicates[1] = self.sentence_sempred
pred = self._predicates.get(ruleIndex, None)
if pred is None:
raise Exception("No predicate with index:" + str(ruleIndex))
else:
return pred(localctx, predIndex)
def sentence_sempred(self, localctx:SentenceContext, predIndex:int):
if predIndex == 0:
return self.precpred(self._ctx, 4)
if predIndex == 1:
return self.precpred(self._ctx, 3)
if predIndex == 2:
return self.precpred(self._ctx, 2)
if predIndex == 3:
return self.precpred(self._ctx, 1)
name = "boolparse"
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 29 09:18:23 2019
@author: stan
"""
from antlr4 import CommonTokenStream,InputStream,ParseTreeWalker
from BooleanSentenceLexer import BooleanSentenceLexer
from BooleanSentenceParser import BooleanSentenceParser
from sentece_listener import SentenceListener
class FormulaParser:
@staticmethod
def parse(formula):
input_stream = InputStream(formula)
lexer = BooleanSentenceLexer(input_stream)
stream = CommonTokenStream(lexer)
parser = BooleanSentenceParser(stream)
tree = parser.init()
listener = SentenceListener()
walker = ParseTreeWalker()
walker.walk(listener, tree)
return (listener.get_expression(),listener.get_var_names())
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 9 09:19:22 2019
@author: stan
"""
from logic import TRUE,FALSE,Var,Not,And,Or,\
Implication,Equivalence
class CNF:
def __init__(self,formula,variables):
self.P = "__"
self.V = "Z"
self.formula = formula
self.formulaCNF = None
self.variables = variables
self.encode ={v:i+1 for i,v in enumerate(variables)}
self.index = len(variables)+1
self.dimacs = []
def next_index(self):
i = self.index
self.index +=1
return i
def switching_var(self):
var = Var(self.P+self.V+str(self.next_index())+self.P)
self.encode[var.nombre]=self.index-1
return var
def rewrite(self,formula):
if isinstance(formula,TRUE):
return formula
elif isinstance(formula,FALSE):
return formula
elif isinstance(formula,Var):
return formula
elif isinstance(formula, Not):
return Not(self.rewrite(formula.param))
elif isinstance(formula,And):
return And(
self.rewrite(formula.left),self.rewrite(formula.right))
elif isinstance(formula,Or):
return Or(
self.rewrite(formula.left),self.rewrite(formula.right))
elif isinstance(formula,Implication):
return Or(
Not(self.rewrite(formula.left)),
self.rewrite(formula.right))
elif isinstance(formula,Equivalence):
return And(
Or(
Not(self.rewrite(formula.left)),
self.rewrite(formula.right)),
Or(
Not(self.rewrite(formula.right)),
self.rewrite(formula.left)))
def apply_not(self,formula):
if isinstance(formula,Not):
if isinstance(formula.param,And):
return Or(
self.apply_not(Not(formula.param.left)),
self.apply_not(Not(formula.param.right)))
elif isinstance(formula.param,Or):
return And(
self.apply_not(Not(formula.param.left)),
self.apply_not(Not(formula.param.right)))
elif isinstance(formula.param,Not):
return self.apply_not(formula.param.param)
else:
return formula
elif isinstance(formula,And):
return And(
self.apply_not(formula.left),
self.apply_not(formula.right))
elif isinstance(formula,Or):
return Or(
self.apply_not(formula.left),
self.apply_not(formula.right))
else:
return formula
def literal(self,formula):
if isinstance(formula,Var):
return True
elif isinstance(formula,Not):
return isinstance(formula.param,Var)
else:
return False
def distribute_ors(self,formula):
if self.literal(formula):
return formula
if isinstance(formula,Or):
if self.literal(formula.left) and self.literal(formula.right):
return formula
if self.literal(formula.left):
if isinstance(formula.right,And):
return self.distribute(
formula.left,self.distribute_ors(formula.right))
else:
return Or(formula.left,
self.distribute_ors(formula.right))
if self.literal(formula.right):
if isinstance(formula.left,And):
return self.distribute(
formula.right,self.distribute_ors(formula.left))
else:
return Or(formula.right,
self.distribute_ors(formula.left))
else:
Z = self.switching_var()
return And(
self.distribute(Not(Z),self.distribute_ors(formula.left)),
self.distribute(Z,self.distribute_ors(formula.right)))
elif isinstance(formula,And):
return And(
self.distribute_ors(formula.left),
self.distribute_ors(formula.right)
)
else:
return formula
def distribute(self,variable,formula):
if self.literal(formula):
return Or(variable,formula)
elif isinstance(formula,And):
return And(
self.distribute(variable,formula.left),
self.distribute(variable,formula.right))
elif isinstance(formula,Or):
return Or(variable,formula)
def convert(self):
f = self.rewrite(self.formula)
f = self.apply_not(f)
f = self.distribute_ors(f)
self.decode = {i:v for v,i in self.encode.items()}
self.formulaCNF = f
return f
def to_dimacs(self,formula=None):
formula = self.formulaCNF if formula==None else formula
if not isinstance(formula,And):
clausula = self.encode_clausula(formula,[])
self.dimacs.append(clausula)
else:
self.to_dimacs(formula.left)
self.to_dimacs(formula.right)
return self.dimacs
def encode_clausula(self,formula,clausula=[]):
if self.literal(formula):
self.agregar_literal(formula,clausula)
else:
self.encode_clausula(formula.left,clausula)
self.encode_clausula(formula.right,clausula)
return clausula
def agregar_literal(self,literal,clausula):
if isinstance(literal,Not):
variable = literal.param
indice = -self.encode[variable.nombre]
else:
indice = self.encode[literal.nombre]
clausula.append(indice)
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 26 09:56:34 2019
@author: stan
"""
from abc import ABC,abstractmethod
class ExpresionBooleana(ABC):
@abstractmethod
def evaluate(self,assignment):
pass
def __repr__(self):
return str(self)
class TRUE(ExpresionBooleana):
def evaluate(self,assignment):
return True
def __str__(self):
return "1"
class FALSE(ExpresionBooleana):
def evaluate(false,assignment):
return False
def __str__(self):
return "0"
class Var(ExpresionBooleana):
def __init__(self,nombre):
self.nombre = nombre
def evaluate(self,assignment):
return assignment[self.nombre]
def __str__(self):
return self.nombre
class Not(ExpresionBooleana):
def __init__(self, expresion):
self.param = expresion
def evaluate(self,assignment):
return not self.param.evaluate(assignment)
def get_symbol(self):
return "~"
def __str__(self):
return self.get_symbol()+str(self.param)
class ExpresionBinaria(ExpresionBooleana,ABC):
def __init__(self,left,right):
self.left = left
self.right = right
@abstractmethod
def get_symbol(self):
pass
def __str__(self):
return "("+str(self.left)+self.get_symbol()+str(self.right)+")"
class And(ExpresionBinaria):
def __init__(self,left,right):
super().__init__(left,right)
def evaluate(self,assignment):
return self.left.evaluate(assignment) and\
self.right.evaluate(assignment)
def get_symbol(self):
return "&"
class Or(ExpresionBinaria):
def __init__(self,left,right):
super().__init__(left,right)
def evaluate(self,assignment):
return self.left.evaluate(assignment) or\
self.right.evaluate(assignment)
def get_symbol(self):
return "|"
class Implication(ExpresionBinaria):
def __init__(self,left,right):
super().__init__(left,right)
def evaluate(self,assignment):
return not self.left.evaluate(assignment) or\
self.right.evaluate(assignment)
def get_symbol(self):
return "->"
class Equivalence(ExpresionBinaria):
def __init__(self,left,right):
super().__init__(left,right)
def evaluate(self,assignment):
return self.left.evaluate(assignment) ==\
self.right.evaluate(assignment)
def get_symbol(self):
return "="
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 29 08:21:19 2019
@author: stan
"""
#%%
from logic import And, Or, Implication, Equivalence, Not, Var,TRUE,FALSE
#phi = And(Var('A'),Or(Var('B'),Not(Var('C'))))
#definiendo una constante
phi = TRUE()
print(phi,type(phi))
#%%
phi = FALSE()
print(phi,type(phi))
#%%
#definiendo una variable
phi = Var('A')
print(phi,type(phi))
#%%
#negación
phi = Not(phi)
print(phi,type(phi))
#%%
#conjunción
psi = Var('C')
phi = And(phi,psi)
print(phi)
#%%
#disyunción
phi = Or(phi,psi)
print(phi)
#%%
#implicación
phi = Implication(psi,phi)
print(phi)
#%%
#equivalencia
phi = Equivalence(phi,psi)
print(phi)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 15 08:18:45 2019
@author: stan
"""
from itertools import product
from formula_parser import FormulaParser as parser
class TruthTable:
"""
Tabla de verdad
"""
def __init__(self,variables,name,values=None,formula=None,formulastr=None):
self.n = len(variables)
self.values = values
self.name = name
self.variables = variables
self.formula = formula
self.formulastr = formulastr
t = [False,True]
g = (t for _ in range(self.n))
left = product(*g)
if values:
self.table = {k:v for k,v in zip(left,values)}
else:
self.table = {}
for tupla in left:
assignment = {var:val for var,val in zip(variables,tupla)}
self.table[tupla]=formula.evaluate(assignment)
def __getitem__(self,estado):
return self.table[estado]
def __str__(self):
s = "\n"
sep = " "
encabezado = sep.join(self.variables)+ sep+"\\"+sep + self.name + "\n"
encabezado += "-"*len(encabezado) + "\n"
s += encabezado
for tupla in sorted(self.table.items()):
l = ""
izq,der = tupla
l += sep.join("1" if i else "0" for i in izq)
l += sep+"\\"+sep
l += "1" if der else "0"
l += "\n"
s += l
return s
def __repr__(self):
return str(self)
@staticmethod
def from_formula(formula,name):
ftree,variables = parser.parse(formula)
return TruthTable(variables,name,formula=ftree,formulastr=formula)
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 29 09:11:57 2019
@author: stan
"""
from BooleanSentenceListener import BooleanSentenceListener
from collections import deque
from logic.logic import Var,TRUE,FALSE,Not,And,Or,Equivalence,Implication
class SentenceListener(BooleanSentenceListener):
def __init__(self):
self.pila = deque()
self.vars = set()
def exitTrueSentence(self, ctx):
self.pila.append(TRUE())
def exitFalseSentence(self, ctx):
self.pila.append(FALSE())
def exitAtomSentence(self, ctx):
nombre = str(ctx.VAR())
self.vars.add(nombre)
self.pila.append(Var(nombre))
def exitNotSentence(self,ctx):
self.pila.append(Not(self.pila.pop()))
def exitAndSentence(self, ctx):
right = self.pila.pop()
left = self.pila.pop()
self.pila.append(And(left,right))
def exitOrSentence(self, ctx):
right = self.pila.pop()
left = self.pila.pop()
self.pila.append(Or(left,right))
def exitEquivalenceSentence(self, ctx):
right = self.pila.pop()
left = self.pila.pop()
self.pila.append(Equivalence(left,right))
def exitImplicationSentence(self,ctx):
right = self.pila.pop()
left = self.pila.pop()
self.pila.append(Implication(left,right))
def get_expression(self):
return self.pila.pop()
def get_var_names(self):
return sorted(self.vars)
from setuptools import setup
setup(name='pypack',
version='0.1',
description='Test package',
url='http://c3.unam.mx/',
author='Stan',
author_email='stalin.munoz@c3.unam.mx',
license='LGPL',
packages=['pypack'],
zip_safe=False)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment