code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
#! /usr/bin/python
# -*- coding: utf-8 -*-
#######################################################################################
# #
# File: main.py #
# Part of 2dgal-cheater #
# Home: http://2dgal-cheater.googlecode.com #
# #
# The MIT License #
# #
# Copyright (c) 2010-2011 <araya.akashic@gmail.com> #
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy #
# of this software and associated documentation files (the "Software"), to deal #
# in the Software without restriction, including without limitation the rights #
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #
# copies of the Software, and to permit persons to whom the Software is #
# furnished to do so, subject to the following conditions: #
# #
# The above copyright notice and this permission notice shall be included in #
# all copies or substantial portions of the Software. #
# #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #
# THE SOFTWARE. #
# #
#######################################################################################
'''
Created on May 14, 2011
@author: flyxian
'''
import time, sys
import random
import sqlite3
import threading
import urllib2
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from ui.Core import *
import browser_bogus
import ad_auto
import achievement
from user_agent_lib import get_random_user_agent
VERSION = "2.5.0"
ad_auto_threads = []
achievement_threads = []
ad_auto_accounts = []
achievement_accounts = []
app = QApplication(sys.argv)
window = MainWindow()
achievement_update_timer = QTimer()
ad_auto_update_timer = QTimer()
try:
_fromUtf8 = QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class AdAutoWorker(QThread):
def __init__(self, username, passwd, itemdata, parent=None):
super(AdAutoWorker, self).__init__(parent)
self.browser = browser_bogus.Browser(username, passwd, get_random_user_agent())
self.itemdata = itemdata
self.stopevent = threading.Event()
def do_ad_auto(self):
while not self.stopevent.isSet():
submit_success = -1
try:
self.itemdata[2] = _fromUtf8("正在登录")
ad_auto.login(self.browser)
self.itemdata[2] = _fromUtf8("已登录")
while submit_success < 0:
try:
submit_success = ad_auto.ad_auto(self.browser)
self.itemdata[2] = _fromUtf8("点击广告")
self.itemdata[3] = _fromUtf8(time.strftime("%y-%m-%d %H:%M:%S"))
except ad_auto.ExamNotAvailable:
self.itemdata[2] = _fromUtf8("未到下一次任务时间")
break
#print submit_success
self.itemdata[2] = _fromUtf8("正在注销")
ad_auto.logout(self.browser)
self.itemdata[2] = _fromUtf8("已注销")
except urllib2.URLError:
self.itemdata[2] = _fromUtf8("网络连接不正常")
except urllib2.HTTPError, err:
self.itemdata[2] = _fromUtf8("请求被拒绝 %d" % err.code)
except ad_auto.LoginFailed:
self.itemdata[2] = _fromUtf8("登录失败")
except:
self.itemdata[2] = _fromUtf8("未知异常")
pass
# ad_auto._perform_cheating(self.self.browser)
self.sleep(ad_auto.delay)
def run(self):
self.do_ad_auto()
self.exec_()
def quit(self):
self.stopevent.set()
# self.logout()
self.itemdata[2] = _fromUtf8("已停止")
super(AdAutoWorker, self).quit()
class AchievementWorker(QThread):
def __init__(self, username, passwd, itemdata, parent=None):
super(AchievementWorker, self).__init__(parent)
self.browser = browser_bogus.Browser(username, passwd, get_random_user_agent())
# self.setDaemon(True)
self.stopevent = threading.Event()
self.itemdata = itemdata
def do_achievement(self):
while not self.stopevent.isSet():
submit_success = -1
try:
self.itemdata[2] = _fromUtf8("正在登录")
achievement.login(self.browser)
self.itemdata[2] = _fromUtf8("已登录")
while submit_success < 0:
try:
submit_success = achievement.achievement_cheat(self.browser)
self.itemdata[2] = _fromUtf8("完成答题")
except achievement.ExamNotAvailable, e:
self.itemdata[2] = _fromUtf8("到下一次还有: %d" % e.value)
break
#print submit_success
self.itemdata[2] = _fromUtf8("正在注销")
achievement.logout(self.browser)
self.itemdata[2] = _fromUtf8("已注销")
except urllib2.URLError:
self.itemdata[2] = _fromUtf8("网络连接不正常")
except urllib2.HTTPError, err:
self.itemdata[2] = _fromUtf8("请求被拒绝 %d" % err.code)
except achievement.LoginFailed:
self.itemdata[2] = _fromUtf8("登录失败")
# except:
# self.itemdata[2] = _fromUtf8("未知异常")
# pass
self.sleep(achievement.delay)
def run(self):
self.do_achievement()
#enter event loop
self.exec_()
def quit(self):
self.stopevent.set()
self.itemdata[2] = _fromUtf8("已停止")
super(AchievementWorker, self).quit()
def read_account(filename="accounts.db"):
# file = open(filename, "r")
# lines = file.readlines()
# file.close()
#
# for line in lines:
# if line[0] == "#":
# continue
# if line[0] == "o":
# account_data = line.strip().split(",")[1:]
# achievement_accounts.append([QString.fromUtf8(account_data[0]),
# QString.fromUtf8(account_data[1]),
# QString.fromUtf8('##')])
# if line[0] == "d":
# account_data = line.strip().split(",")[1:]
# ad_auto_accounts.append([QString.fromUtf8(account_data[0]),
# QString.fromUtf8(account_data[1]),
# QString.fromUtf8('##'),
# QString.fromUtf8('##')])
conn = sqlite3.connect(filename)
c = conn.cursor()
c.execute("""SELECT * FROM achievement_accounts""")
items = c.fetchall()
for item in items:
achievement_accounts.append([QString(item[0]),
QString(item[1]),
QString.fromUtf8('##')])
c.execute("""SELECT * FROM ad_auto_accounts""")
items = c.fetchall()
for item in items:
ad_auto_accounts.append([QString(item[0]),
QString(item[1]),
QString.fromUtf8('##'),
QString.fromUtf8('##')])
conn.close()
def write_account(filename="accounts.db"):
conn = sqlite3.connect(filename)
c = conn.cursor()
c.execute("DROP TABLE achievement_accounts")
c.execute("DROP TABLE ad_auto_accounts")
c.execute("""CREATE TABLE achievement_accounts
(username TEXT PRIMARY KEY, passwd TEXT)""")
c.execute("""CREATE TABLE ad_auto_accounts
(username TEXT PRIMARY KEY, passwd TEXT)""")
for item in achievement_accounts:
c.execute("INSERT INTO achievement_accounts VALUES (?,?)",
(item[0].__str__(), item[1].__str__()))
for item in ad_auto_accounts:
c.execute("INSERT INTO ad_auto_accounts VALUES (?,?)",
(item[0].__str__(), item[1].__str__()))
conn.commit()
conn.close()
# file = open(filename, "w")
# for item in achievement_accounts:
# if QString.toUtf8(item[0]) == "##":
# continue
# file.write("o," + QString.toUtf8(item[0]) + "," + QString.toUtf8(item[1]) + "\n")
# for item in ad_auto_accounts:
# if QString.toUtf8(item[0]) == "##":
# continue
# file.write("d," + QString.toUtf8(item[0]) + "," + QString.toUtf8(item[1]) + "\n")
#
# file.close()
# print ad_auto_threads
# print achievement_threads
def start_achievement():
QTextCodec.setCodecForCStrings(QTextCodec.codecForName("GB18030-0"))
window.achievement_start()
print window.pushButton_achievement_start.state
if window.pushButton_achievement_start.state:
for item in achievement_accounts:
worker = AchievementWorker(unicode(QString(item[0])).encode("gbk"), \
unicode(QString(item[1])).encode("gbk"), item)
achievement_threads.append(worker)
for worker in achievement_threads:
worker.start()
print achievement_threads
achievement_update_timer.start(2000)
else:
print "stop workers"
for worker in achievement_threads:
worker.quit()
achievement_update_timer.stop()
while len(achievement_threads) > 0:
achievement_threads.pop()
print achievement_threads
def start_ad_auto():
# QTextCodec.setCodecForCStrings(QTextCodec.codecForName("GB18030-0"))
window.ad_auto_start()
if window.pushButton_ad_auto_start.state:
for item in ad_auto_accounts:
worker = AdAutoWorker(unicode(QString(item[0])).encode("gbk"), \
unicode(QString(item[1])).encode("gbk"), item)
ad_auto_threads.append(worker)
for worker in ad_auto_threads:
worker.start()
ad_auto_update_timer.start(2000)
else:
for worker in ad_auto_threads:
worker.quit()
while len(ad_auto_threads) > 0:
ad_auto_threads.pop()
ad_auto_update_timer.stop()
#if __name__ == "__main__":
# signal.signal(signal.SIGINT, sigint_handler)
# signal.signal(signal.SIGTERM, sigint_handler)
# read_account()
# start_all()
# while True:
# time.sleep(1000000)
if __name__ == "__main__":
random.seed()
try:
read_account()
except:
QMessageBox.information(window, _fromUtf8("错误"),
_fromUtf8("无法打开账户文件accounts.db"))
# print ad_auto_accounts
# print achievement_accounts
# app = QApplication(sys.argv)
# window = MainWindow()
window.update_achievement_account_list(achievement_accounts)
window.update_ad_auto_account_list(ad_auto_accounts)
window.init_display_properties()
window.init_signals()
QObject.connect(achievement_update_timer,
SIGNAL(_fromUtf8("timeout()")),
window.achievement_account_list.reset)
QObject.connect(ad_auto_update_timer,
SIGNAL(_fromUtf8("timeout()")),
window.ad_auto_account_list.reset)
QObject.connect(window.pushButton_achievement_start,
SIGNAL(QString.fromUtf8("clicked()")),
start_achievement)
QObject.connect(window.pushButton_ad_auto_start,
SIGNAL(QString.fromUtf8("clicked()")),
start_ad_auto)
QObject.connect(window.achievement_dataModel,
SIGNAL(QString.fromUtf8("dataChanged()")),
write_account)
window.write_account_signal.connect(write_account)
QApplication.setQuitOnLastWindowClosed(False)
window.show()
sys.exit(app.exec_()) | Python |
#! /usr/bin/python
#######################################################################################
# #
# File: gojuon_gen.py #
# Part of 2dgal-cheater #
# Home: http://2dgal-cheater.googlecode.com #
# #
# The MIT License #
# #
# Copyright (c) 2010-2011 <araya.akashic@gmail.com> #
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy #
# of this software and associated documentation files (the "Software"), to deal #
# in the Software without restriction, including without limitation the rights #
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #
# copies of the Software, and to permit persons to whom the Software is #
# furnished to do so, subject to the following conditions: #
# #
# The above copyright notice and this permission notice shall be included in #
# all copies or substantial portions of the Software. #
# #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #
# THE SOFTWARE. #
# #
#######################################################################################
#This is to generate the library of encoded gojuon to phonetic symbol
#Author: Araya
import urllib
file = open("gojuon.csv", "r")
lines = file.readlines()
file.close()
file = open("gojuon.py", "w")
for line in lines:
items = line.strip().split(",")
hiragana = urllib.urlencode({"":items[0]})
katakana = urllib.urlencode({"":items[1]})
phonetic = urllib.urlencode({"":items[2]})
output_line = "\t\"" + hiragana + "\":\"" + items[2] + "\",\n"
file.write(output_line)
#print output_line
output_line = "\t\"" + katakana + "\":\"" + items[2] + "\",\n"
file.write(output_line)
#print output_line
file.close()
| Python |
#! /usr/bin/python
from distutils.core import setup
import py2exe
import main
from glob import glob
data_files = [("Microsoft.VC100.CRT",
glob(r'D:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\redist\x86\Microsoft.VC100.CRT\*.*'))]
setup(
options = {"py2exe": {"optimize": 2,
"compressed": 1,
"bundle_files": 1,
"includes": ["sip"]} },
name = "stage1st_cheater",
version = main.VERSION,
description = "Stage1st BBS Cheating Tools",
zipfile = None,
# data_files=data_files,
windows=[{'script': 'main.py',
"icon_resources": [(1, "./images/trash.ico")]}],
data_files = [('images', ['./images/trash.png'])])
| Python |
#! /usr/bin/python
from distutils.core import setup
import py2exe
import main
from glob import glob
data_files = [("Microsoft.VC100.CRT",
glob(r'D:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\redist\x86\Microsoft.VC100.CRT\*.*'))]
setup(
options = {"py2exe": {"optimize": 2,
"compressed": 1,
"bundle_files": 1,
"includes": ["sip"]} },
name = "stage1st_cheater",
version = main.VERSION,
description = "Stage1st BBS Cheating Tools",
zipfile = None,
# data_files=data_files,
windows=[{'script': 'main.py',
"icon_resources": [(1, "./images/trash.ico")]}],
data_files = [('images', ['./images/trash.png'])])
| Python |
#! /usr/bin/python
#######################################################################################
# #
# File: gojuon_gen.py #
# Part of 2dgal-cheater #
# Home: http://2dgal-cheater.googlecode.com #
# #
# The MIT License #
# #
# Copyright (c) 2010-2011 <araya.akashic@gmail.com> #
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy #
# of this software and associated documentation files (the "Software"), to deal #
# in the Software without restriction, including without limitation the rights #
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #
# copies of the Software, and to permit persons to whom the Software is #
# furnished to do so, subject to the following conditions: #
# #
# The above copyright notice and this permission notice shall be included in #
# all copies or substantial portions of the Software. #
# #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #
# THE SOFTWARE. #
# #
#######################################################################################
#This is to generate the library of encoded gojuon to phonetic symbol
#Author: Araya
import urllib
file = open("gojuon.csv", "r")
lines = file.readlines()
file.close()
file = open("gojuon.py", "w")
for line in lines:
items = line.strip().split(",")
hiragana = urllib.urlencode({"":items[0]})
katakana = urllib.urlencode({"":items[1]})
phonetic = urllib.urlencode({"":items[2]})
output_line = "\t\"" + hiragana + "\":\"" + items[2] + "\",\n"
file.write(output_line)
#print output_line
output_line = "\t\"" + katakana + "\":\"" + items[2] + "\",\n"
file.write(output_line)
#print output_line
file.close()
| Python |
#This contains global definition of Browser class and other useful thing
#######################################################################################
# #
# File: browser_bogus.py #
# Part of 2dgal-cheater #
# Home: http://2dgal-cheater.googlecode.com #
# #
# The MIT License #
# #
# Copyright (c) 2010-2011 <araya.akashic@gmail.com> #
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy #
# of this software and associated documentation files (the "Software"), to deal #
# in the Software without restriction, including without limitation the rights #
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #
# copies of the Software, and to permit persons to whom the Software is #
# furnished to do so, subject to the following conditions: #
# #
# The above copyright notice and this permission notice shall be included in #
# all copies or substantial portions of the Software. #
# #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #
# THE SOFTWARE. #
# #
#######################################################################################
#Author: Araya
import urllib2
import cookielib
class Browser():
def __init__(self, user, passwd):
self.username = user
self.password = passwd
self.cookie = cookielib.CookieJar()
self.urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie))
self.logout_URI = ""
#ad link
self.ad_link = "" | Python |
#! /usr/bin/python
#######################################################################################
# #
# File: ad_auto.py #
# Part of 2dgal-cheater #
# Home: http://2dgal-cheater.googlecode.com #
# #
# The MIT License #
# #
# Copyright (c) 2010-2011 <araya.akashic@gmail.com> #
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy #
# of this software and associated documentation files (the "Software"), to deal #
# in the Software without restriction, including without limitation the rights #
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #
# copies of the Software, and to permit persons to whom the Software is #
# furnished to do so, subject to the following conditions: #
# #
# The above copyright notice and this permission notice shall be included in #
# all copies or substantial portions of the Software. #
# #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #
# THE SOFTWARE. #
# #
#######################################################################################
# This code is to automatically click ads on kf bbs
# Author: Araya
import time
import urllib
import urllib2
from browser_bogus import Browser
#customized these
#adding account as "username":"password"
account_list = {"":"",
"":""}
#total attempts
cycle = 1
#wait 1 hr 10 s before each attempt
delay = 3600 * 5
#do not change below this
siteurl = "http://bbs.2dgal.com"
login_page = "login.php"
star1_page = "kf_star_1.php"
#ad link character
ad_char = "diy_ad_move.php"
#method login
def login(user):
logindata = {"pwuser":user.username,
"pwpwd":user.password,
"hideid":"0",
"cktime":"0",
"forward":"index.php",
"jumpurl":"index.php",
"step":"2"}
en_logindata = urllib.urlencode(logindata)
url = siteurl + "/" + login_page
request = urllib2.Request(url)
result = user.urlOpener.open(request)
#print "Getting login page"
url = url + "?"
request = urllib2.Request(url, en_logindata)
result = user.urlOpener.open(request)
print "Login " + user.username
#print cookie
def ad_auto(user):
question = []
answer = ""
#print "Getting star 1 question"
url = siteurl + "/" + star1_page
request = urllib2.Request(url)
result = user.urlOpener.open(request)
pagelines = result.readlines()
#print len(pagelines)
#extracting logout URI
line = pagelines[74]
user.logout_URI = line.split("=\"")[-1].split("\"")[0]
for line in pagelines:
match = line.find(ad_char)
if match >= 0:
words = line.split("=\"")
for word in words:
if word.find(ad_char) >= 0:
user.ad_link = word.split("\"")[0]
print user.ad_link
url = siteurl + "/" + user.ad_link
request = urllib2.Request(url)
result = user.urlOpener.open(request)
print "Ad click sent"
result_data = result.read()
return result_data.find("<meta http-equiv=\"refresh\"")
# return 1
def logout(user):
url = siteurl + "/" + user.logout_URI
request = urllib2.Request(url)
result = user.urlOpener.open(request)
print "Logout " + user.username
def perform_ad_auto():
for n, p in account_list.iteritems():
user = Browser(n, p)
submit_success = -1
try:
login(user)
while submit_success < 0:
submit_success = ad_auto(user)
print submit_success
logout(user)
except:
pass
if __name__ == "__main__":
while cycle:
print "------------------------------------------"
print time.strftime("%a, %b %d %Y %H:%M:%S", time.localtime()) + "-----------------"
perform_ad_auto()
if cycle > 1:
time.sleep(delay)
cycle = cycle - 1 | Python |
#######################################################################################
# #
# File: gojuon.py #
# Part of 2dgal-cheater #
# Home: http://2dgal-cheater.googlecode.com #
# #
# The MIT License #
# #
# Copyright (c) 2010-2011 <araya.akashic@gmail.com> #
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy #
# of this software and associated documentation files (the "Software"), to deal #
# in the Software without restriction, including without limitation the rights #
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #
# copies of the Software, and to permit persons to whom the Software is #
# furnished to do so, subject to the following conditions: #
# #
# The above copyright notice and this permission notice shall be included in #
# all copies or substantial portions of the Software. #
# #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #
# THE SOFTWARE. #
# #
#######################################################################################
#This is the library of encoded gojuon to phonetic symbol
#Author: Araya
gojuon = {
"=%A4%A2":"a",
"=%A5%A2":"a",
"=%A4%A4":"i",
"=%A5%A4":"i",
"=%A4%A6":"u",
"=%A5%A6":"u",
"=%A4%A8":"e",
"=%A5%A8":"e",
"=%A4%AA":"o",
"=%A5%AA":"o",
"=%A4%AB":"ka",
"=%A5%AB":"ka",
"=%A4%AD":"ki",
"=%A5%AD":"ki",
"=%A4%AF":"ku",
"=%A5%AF":"ku",
"=%A4%B1":"ke",
"=%A5%B1":"ke",
"=%A4%B3":"ko",
"=%A5%B3":"ko",
"=%A4%B5":"sa",
"=%A5%B5":"sa",
"=%A4%B7":"shi",
"=%A5%B7":"shi",
"=%A4%B9":"su",
"=%A5%B9":"su",
"=%A4%BB":"se",
"=%A5%BB":"se",
"=%A4%BD":"so",
"=%A5%BD":"so",
"=%A4%BF":"ta",
"=%A5%BF":"ta",
"=%A4%C1":"chi",
"=%A5%C1":"chi",
"=%A4%C4":"tsu",
"=%A5%C4":"tsu",
"=%A4%C6":"te",
"=%A5%C6":"te",
"=%A4%C8":"to",
"=%A5%C8":"to",
"=%A4%CA":"na",
"=%A5%CA":"na",
"=%A4%CB":"ni",
"=%A5%CB":"ni",
"=%A4%CC":"nu",
"=%A5%CC":"nu",
"=%A4%CD":"ne",
"=%A5%CD":"ne",
"=%A4%CE":"no",
"=%A5%CE":"no",
"=%A4%CF":"ha",
"=%A5%CF":"ha",
"=%A4%D2":"hi",
"=%A5%D2":"hi",
"=%A4%D5":"fu",
"=%A5%D5":"fu",
"=%A4%D8":"he",
"=%A5%D8":"he",
"=%A4%DB":"ho",
"=%A5%DB":"ho",
"=%A4%DE":"ma",
"=%A5%DE":"ma",
"=%A4%DF":"mi",
"=%A5%DF":"mi",
"=%A4%E0":"mu",
"=%A5%E0":"mu",
"=%A4%E1":"me",
"=%A5%E1":"me",
"=%A4%E2":"mo",
"=%A5%E2":"mo",
"=%A4%E4":"ya",
"=%A5%E4":"ya",
"=%A4%E6":"yu",
"=%A5%E6":"yu",
"=%A4%E8":"yo",
"=%A5%E8":"yo",
"=%A4%E9":"ra",
"=%A5%E9":"ra",
"=%A4%EA":"ri",
"=%A5%EA":"ri",
"=%A4%EB":"ru",
"=%A5%EB":"ru",
"=%A4%EC":"re",
"=%A5%EC":"re",
"=%A4%ED":"ro",
"=%A5%ED":"ro",
"=%A4%EF":"wa",
"=%A5%EF":"wa",
"=%A4%F2":"o",
"=%A5%F2":"o",
"=%A4%F3":"n",
"=%A5%F3":"n",
"=":"",
"=":"",
"=%A4%AC":"ga",
"=%A5%AC":"ga",
"=%A4%AE":"gi",
"=%A5%AE":"gi",
"=%A4%B0":"gu",
"=%A5%B0":"gu",
"=%A4%B2":"ge",
"=%A5%B2":"ge",
"=%A4%B4":"go",
"=%A5%B4":"go",
"=%A4%B6":"za",
"=%A5%B6":"za",
"=%A4%B8":"ji",
"=%A5%B8":"ji",
"=%A4%BA":"zu",
"=%A5%BA":"zu",
"=%A4%BC":"ze",
"=%A5%BC":"ze",
"=%A4%BE":"zo",
"=%A5%BE":"zo",
"=%A4%C0":"da",
"=%A5%C0":"da",
"=%A4%C2":"ji",
"=%A5%C2":"ji",
"=%A4%C5":"zu",
"=%A5%C5":"zu",
"=%A4%C7":"de",
"=%A5%C7":"de",
"=%A4%C9":"do",
"=%A5%C9":"do",
"=%A4%D0":"ba",
"=%A5%D0":"ba",
"=%A4%D3":"bi",
"=%A5%D3":"bi",
"=%A4%D6":"bu",
"=%A5%D6":"bu",
"=%A4%D9":"be",
"=%A5%D9":"be",
"=%A4%DC":"bo",
"=%A5%DC":"bo",
"=%A4%D1":"pa",
"=%A5%D1":"pa",
"=%A4%D4":"pi",
"=%A5%D4":"pi",
"=%A4%D7":"pu",
"=%A5%D7":"pu",
"=%A4%DA":"pe",
"=%A5%DA":"pe",
"=%A4%DD":"po",
"=%A5%DD":"po",
"=%A4%AD%A4%E3":"kya",
"=%A5%AD%A5%E3":"kya",
"=%A4%AD%A4%E5":"jyu",
"=%A5%AD%A5%E5":"jyu",
"=%A4%AD%A4%E7":"kyo",
"=%A5%AD%A5%E7":"kyo",
"=%A4%B7%A4%E3":"sha",
"=%A5%B7%A5%E3":"sha",
"=%A4%B7%A4%E5":"shu",
"=%A5%B7%A5%E5":"shu",
"=%A4%B7%A4%E7":"sho",
"=%A5%B7%A5%E7":"sho",
"=%A4%C1%A4%E3":"cha",
"=%A5%C1%A5%E3":"cha",
"=%A4%C1%A4%E5":"chu",
"=%A5%C1%A5%E5":"chu",
"=%A4%C1%A4%E7":"cho",
"=%A5%C1%A5%E7":"cho",
"=%A4%CB%A4%E3":"nya",
"=%A5%CB%A5%E3":"nya",
"=%A4%CB%A4%E5":"nyu",
"=%A5%CB%A5%E5":"nyu",
"=%A4%CB%A4%E7":"nyo",
"=%A5%CB%A5%E7":"nyo",
"=%A4%D2%A4%E3":"hya",
"=%A5%D2%A5%E3":"hya",
"=%A4%D2%A4%E5":"hyu",
"=%A5%D2%A5%E5":"hyu",
"=%A4%D2%A4%E7":"hyo",
"=%A5%D2%A5%E7":"hyo",
"=%A4%DF%A4%E3":"mya",
"=%A5%DF%A5%E3":"mya",
"=%A4%DF%A4%E5":"mya",
"=%A5%DF%A5%E5":"mya",
"=%A4%DF%A4%E7":"myo",
"=%A5%DF%A5%E7":"myo",
"=%A4%EA%A4%E3":"rya",
"=%A5%EA%A5%E3":"rya",
"=%A4%EA%A4%E5":"ryu",
"=%A5%EA%A5%E5":"ryu",
"=%A4%EA%A4%E7":"ryo",
"=%A5%EA%A5%E7":"ryo",
"=%A4%AE%A4%E3":"gya",
"=%A5%AE%A5%E3":"gya",
"=%A4%AE%A4%E5":"gyu",
"=%A5%AE%A5%E5":"gyu",
"=%A4%AE%A4%E7":"gyo",
"=%A5%AE%A5%E7":"gyo",
"=%A4%B8%A4%E3":"ja",
"=%A5%B8%A5%E3":"ja",
"=%A4%B8%A4%E5":"ju",
"=%A5%B8%A5%E5":"ju",
"=%A4%B8%A4%E7":"jo",
"=%A5%B8%A5%E7":"jo",
"=%A4%C2%A4%E3":"ja",
"=%A5%C2%A5%E3":"ja",
"=%A4%C2%A4%E5":"ju",
"=%A5%C2%A5%E5":"ju",
"=%A4%C2%A4%E7":"jo",
"=%A5%C2%A5%E7":"jo",
"=%A4%D3%A4%E3":"bya",
"=%A5%D3%A5%E3":"bya",
"=%A4%D3%A4%E5":"byu",
"=%A5%D3%A5%E5":"byu",
"=%A4%D3%A4%E7":"byo",
"=%A5%D3%A5%E7":"byo",
"=%A4%D4%A4%E3":"pya",
"=%A5%D4%A5%E3":"pya",
"=%A4%D4%A4%E5":"pyu",
"=%A5%D4%A5%E5":"pyu",
"=%A4%D4%A4%E7":"pyo",
"=%A5%D4%A5%E7":"pyo"} | Python |
#! /usr/bin/python
#######################################################################################
# #
# File: kf_star_1.py #
# Part of 2dgal-cheater #
# Home: http://2dgal-cheater.googlecode.com #
# #
# The MIT License #
# #
# Copyright (c) 2010-2011 <araya.akashic@gmail.com> #
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy #
# of this software and associated documentation files (the "Software"), to deal #
# in the Software without restriction, including without limitation the rights #
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #
# copies of the Software, and to permit persons to whom the Software is #
# furnished to do so, subject to the following conditions: #
# #
# The above copyright notice and this permission notice shall be included in #
# all copies or substantial portions of the Software. #
# #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #
# THE SOFTWARE. #
# #
#######################################################################################
# This code is to automatically submit test result for 2dgal bbs star 1
# Created as CKJ's demand (wtf)
# Author: Araya
import time
import urllib
import urllib2
import gojuon
from browser_bogus import Browser
#customized these
#adding account as "username":"password"
account_list = {"":"",
"":""}
#total attempts
cycle = 1
#wait 1 hr 10 s before each attempt
delay = 3610
#do not change below this
siteurl = "http://bbs.2dgal.com"
login_page = "login.php"
star1_page = "kf_star_1.php"
#submit data tail
data_tail = "ok=99&submit=%BF%AA%CA%BC%B2%E2%CA%D4"
class ExamNotAvailable(Exception):
def __init__(self, time):
self.value = time
def __str__(self):
return repr(self.value)
#method login
def login(user):
logindata = {"pwuser":user.username,
"pwpwd":user.password,
"hideid":"0",
"cktime":"0",
"forward":"index.php",
"jumpurl":"index.php",
"step":"2"}
en_logindata = urllib.urlencode(logindata)
url = siteurl + "/" + login_page
request = urllib2.Request(url)
result = user.urlOpener.open(request)
#print "Getting login page"
url = url + "?"
request = urllib2.Request(url, en_logindata)
result = user.urlOpener.open(request)
print "Login " + user.username
#print cookie
def star1_cheat(user):
question = []
answer = ""
#print "Getting star 1 question"
url = siteurl + "/" + star1_page
request = urllib2.Request(url)
result = user.urlOpener.open(request)
pagelines = result.readlines()
#print len(pagelines)
for line in pagelines:
#extracting logout URI
if line.find(login_page) >= 0:
user.logout_URI = line.split("=\"")[-1].split("\"")[0]
#checking time to next exam
try:
timetoexam = int(pagelines[166][:2])
except:
timetoexam = 0
if timetoexam > 0:
raise ExamNotAvailable(timetoexam)
#parse questions
for i in range(0,5):
for line in pagelines:
search_str = "\"s1_" + str(i) + "\""
if line.find(search_str) >= 0:
ques = line.split("=\"")[-1].split("\"")[0]
print ques,
question.append(urllib.urlencode({"":ques}))
print " "
#print "Answer:"
for i in range(0,5):
phonetic = gojuon.gojuon[question[i]]
print phonetic + " ",
ans = "s1_%d%s&s1_%d_ans=%s&" % (i, question[i], i, phonetic)
if i == 0:
answer = ans
else:
answer = answer + ans
print " "
#print "Answer: " + answer
answer_data = answer + data_tail
request = urllib2.Request(url, answer_data)
result = user.urlOpener.open(request)
print "Answer sent"
result_data = result.read()
return result_data.find("+1")
# return 1
def logout(user):
url = siteurl + "/" + user.logout_URI
request = urllib2.Request(url)
result = user.urlOpener.open(request)
print "Logout " + user.username
def perform_cheating():
for n, p in account_list.iteritems():
user = Browser(n, p)
submit_success = -1
try:
login(user)
while submit_success < 0:
try:
submit_success = star1_cheat(user)
except ExamNotAvailable, e:
print "Time to next exam is: " + str(e.value)
break
#print submit_success
logout(user)
except:
pass
if __name__ == "__main__":
while cycle:
print "------------------------------------------"
print time.strftime("%a, %b %d %Y %H:%M:%S", time.localtime()) + "-----------------"
perform_cheating()
if cycle > 1:
time.sleep(delay)
cycle = cycle - 1 | Python |
#! /usr/bin/python
#######################################################################################
# #
# File: ad_auto.py #
# Part of 2dgal-cheater #
# Home: http://2dgal-cheater.googlecode.com #
# #
# The MIT License #
# #
# Copyright (c) 2010-2011 <araya.akashic@gmail.com> #
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy #
# of this software and associated documentation files (the "Software"), to deal #
# in the Software without restriction, including without limitation the rights #
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #
# copies of the Software, and to permit persons to whom the Software is #
# furnished to do so, subject to the following conditions: #
# #
# The above copyright notice and this permission notice shall be included in #
# all copies or substantial portions of the Software. #
# #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #
# THE SOFTWARE. #
# #
#######################################################################################
# This code is to automatically click ads on kf bbs
# Author: Araya
import time
import urllib
import urllib2
from browser_bogus import Browser
#customized these
#adding account as "username":"password"
account_list = {"":"",
"":""}
#total attempts
cycle = 1
#wait 1 hr 10 s before each attempt
delay = 3600 * 5
#do not change below this
siteurl = "http://bbs.2dgal.com"
login_page = "login.php"
star1_page = "kf_star_1.php"
#ad link character
ad_char = "diy_ad_move.php"
#method login
def login(user):
logindata = {"pwuser":user.username,
"pwpwd":user.password,
"hideid":"0",
"cktime":"0",
"forward":"index.php",
"jumpurl":"index.php",
"step":"2"}
en_logindata = urllib.urlencode(logindata)
url = siteurl + "/" + login_page
request = urllib2.Request(url)
result = user.urlOpener.open(request)
#print "Getting login page"
url = url + "?"
request = urllib2.Request(url, en_logindata)
result = user.urlOpener.open(request)
print "Login " + user.username
#print cookie
def ad_auto(user):
question = []
answer = ""
#print "Getting star 1 question"
url = siteurl + "/" + star1_page
request = urllib2.Request(url)
result = user.urlOpener.open(request)
pagelines = result.readlines()
#print len(pagelines)
#extracting logout URI
line = pagelines[74]
user.logout_URI = line.split("=\"")[-1].split("\"")[0]
for line in pagelines:
match = line.find(ad_char)
if match >= 0:
words = line.split("=\"")
for word in words:
if word.find(ad_char) >= 0:
user.ad_link = word.split("\"")[0]
print user.ad_link
url = siteurl + "/" + user.ad_link
request = urllib2.Request(url)
result = user.urlOpener.open(request)
print "Ad click sent"
result_data = result.read()
return result_data.find("<meta http-equiv=\"refresh\"")
# return 1
def logout(user):
url = siteurl + "/" + user.logout_URI
request = urllib2.Request(url)
result = user.urlOpener.open(request)
print "Logout " + user.username
def perform_ad_auto():
for n, p in account_list.iteritems():
user = Browser(n, p)
submit_success = -1
try:
login(user)
while submit_success < 0:
submit_success = ad_auto(user)
print submit_success
logout(user)
except:
pass
if __name__ == "__main__":
while cycle:
print "------------------------------------------"
print time.strftime("%a, %b %d %Y %H:%M:%S", time.localtime()) + "-----------------"
perform_ad_auto()
if cycle > 1:
time.sleep(delay)
cycle = cycle - 1 | Python |
#! /usr/bin/python
#######################################################################################
# #
# File: gojuon_gen.py #
# Part of 2dgal-cheater #
# Home: http://2dgal-cheater.googlecode.com #
# #
# The MIT License #
# #
# Copyright (c) 2010-2011 <araya.akashic@gmail.com> #
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy #
# of this software and associated documentation files (the "Software"), to deal #
# in the Software without restriction, including without limitation the rights #
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #
# copies of the Software, and to permit persons to whom the Software is #
# furnished to do so, subject to the following conditions: #
# #
# The above copyright notice and this permission notice shall be included in #
# all copies or substantial portions of the Software. #
# #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #
# THE SOFTWARE. #
# #
#######################################################################################
#This is to generate the library of encoded gojuon to phonetic symbol
#Author: Araya
import urllib
file = open("gojuon.csv", "r")
lines = file.readlines()
file.close()
file = open("gojuon.py", "w")
for line in lines:
items = line.strip().split(",")
hiragana = urllib.urlencode({"":items[0]})
katakana = urllib.urlencode({"":items[1]})
phonetic = urllib.urlencode({"":items[2]})
output_line = "\t\"" + hiragana + "\":\"" + items[2] + "\",\n"
file.write(output_line)
#print output_line
output_line = "\t\"" + katakana + "\":\"" + items[2] + "\",\n"
file.write(output_line)
#print output_line
file.close()
| Python |
#! /usr/bin/python
#######################################################################################
# #
# File: kf_star_1.py #
# Part of 2dgal-cheater #
# Home: http://2dgal-cheater.googlecode.com #
# #
# The MIT License #
# #
# Copyright (c) 2010-2011 <araya.akashic@gmail.com> #
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy #
# of this software and associated documentation files (the "Software"), to deal #
# in the Software without restriction, including without limitation the rights #
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #
# copies of the Software, and to permit persons to whom the Software is #
# furnished to do so, subject to the following conditions: #
# #
# The above copyright notice and this permission notice shall be included in #
# all copies or substantial portions of the Software. #
# #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #
# THE SOFTWARE. #
# #
#######################################################################################
# This code is to automatically submit test result for 2dgal bbs star 1
# Created as CKJ's demand (wtf)
# Author: Araya
import time
import urllib
import urllib2
import gojuon
from browser_bogus import Browser
#customized these
#adding account as "username":"password"
account_list = {"":"",
"":""}
#total attempts
cycle = 1
#wait 1 hr 10 s before each attempt
delay = 3610
#do not change below this
siteurl = "http://bbs.2dgal.com"
login_page = "login.php"
star1_page = "kf_star_1.php"
#submit data tail
data_tail = "ok=99&submit=%BF%AA%CA%BC%B2%E2%CA%D4"
class ExamNotAvailable(Exception):
def __init__(self, time):
self.value = time
def __str__(self):
return repr(self.value)
#method login
def login(user):
logindata = {"pwuser":user.username,
"pwpwd":user.password,
"hideid":"0",
"cktime":"0",
"forward":"index.php",
"jumpurl":"index.php",
"step":"2"}
en_logindata = urllib.urlencode(logindata)
url = siteurl + "/" + login_page
request = urllib2.Request(url)
result = user.urlOpener.open(request)
#print "Getting login page"
url = url + "?"
request = urllib2.Request(url, en_logindata)
result = user.urlOpener.open(request)
print "Login " + user.username
#print cookie
def star1_cheat(user):
question = []
answer = ""
#print "Getting star 1 question"
url = siteurl + "/" + star1_page
request = urllib2.Request(url)
result = user.urlOpener.open(request)
pagelines = result.readlines()
#print len(pagelines)
for line in pagelines:
#extracting logout URI
if line.find(login_page) >= 0:
user.logout_URI = line.split("=\"")[-1].split("\"")[0]
#checking time to next exam
try:
timetoexam = int(pagelines[166][:2])
except:
timetoexam = 0
if timetoexam > 0:
raise ExamNotAvailable(timetoexam)
#parse questions
for i in range(0,5):
for line in pagelines:
search_str = "\"s1_" + str(i) + "\""
if line.find(search_str) >= 0:
ques = line.split("=\"")[-1].split("\"")[0]
print ques,
question.append(urllib.urlencode({"":ques}))
print " "
#print "Answer:"
for i in range(0,5):
phonetic = gojuon.gojuon[question[i]]
print phonetic + " ",
ans = "s1_%d%s&s1_%d_ans=%s&" % (i, question[i], i, phonetic)
if i == 0:
answer = ans
else:
answer = answer + ans
print " "
#print "Answer: " + answer
answer_data = answer + data_tail
request = urllib2.Request(url, answer_data)
result = user.urlOpener.open(request)
print "Answer sent"
result_data = result.read()
return result_data.find("+1")
# return 1
def logout(user):
url = siteurl + "/" + user.logout_URI
request = urllib2.Request(url)
result = user.urlOpener.open(request)
print "Logout " + user.username
def perform_cheating():
for n, p in account_list.iteritems():
user = Browser(n, p)
submit_success = -1
try:
login(user)
while submit_success < 0:
try:
submit_success = star1_cheat(user)
except ExamNotAvailable, e:
print "Time to next exam is: " + str(e.value)
break
#print submit_success
logout(user)
except:
pass
if __name__ == "__main__":
while cycle:
print "------------------------------------------"
print time.strftime("%a, %b %d %Y %H:%M:%S", time.localtime()) + "-----------------"
perform_cheating()
if cycle > 1:
time.sleep(delay)
cycle = cycle - 1 | Python |
#! /usr/bin/python
#######################################################################################
# #
# File: gojuon_gen.py #
# Part of 2dgal-cheater #
# Home: http://2dgal-cheater.googlecode.com #
# #
# The MIT License #
# #
# Copyright (c) 2010-2011 <araya.akashic@gmail.com> #
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy #
# of this software and associated documentation files (the "Software"), to deal #
# in the Software without restriction, including without limitation the rights #
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #
# copies of the Software, and to permit persons to whom the Software is #
# furnished to do so, subject to the following conditions: #
# #
# The above copyright notice and this permission notice shall be included in #
# all copies or substantial portions of the Software. #
# #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #
# THE SOFTWARE. #
# #
#######################################################################################
#This is to generate the library of encoded gojuon to phonetic symbol
#Author: Araya
import urllib
file = open("gojuon.csv", "r")
lines = file.readlines()
file.close()
file = open("gojuon.py", "w")
for line in lines:
items = line.strip().split(",")
hiragana = urllib.urlencode({"":items[0]})
katakana = urllib.urlencode({"":items[1]})
phonetic = urllib.urlencode({"":items[2]})
output_line = "\t\"" + hiragana + "\":\"" + items[2] + "\",\n"
file.write(output_line)
#print output_line
output_line = "\t\"" + katakana + "\":\"" + items[2] + "\",\n"
file.write(output_line)
#print output_line
file.close()
| Python |
import unittest
import bots.inmessage as inmessage
import bots.botslib as botslib
import bots.botsinit as botsinit
import utilsunit
'''plugin unitinmessageedifact.zip'''
class TestInmessage(unittest.TestCase):
def testEdifact0401(self):
''' 0401 Errors in records'''
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0401/040101.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0401/040102.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0401/040103.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0401/040104.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0401/040105.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0401/040106.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0401/040107.edi')
def testedifact0403(self):
#~ #test charsets
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0403/040301.edi') #UNOA-regular OK for UNOA as UNOC
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0403/040302F-generated.edi') #UNOA-regular OK for UNOA as UNOC
in0= inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0403/040303.edi') #UNOA-regular also UNOA-strict
in1= inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0403/040306.edi') #UNOA regular
in2= inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0403/T0000000005.edi') #UNOA regular
in3= inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0403/T0000000006.edi') #UNOA regular
for in1node,in2node,in3node in zip(in1.nextmessage(),in2.nextmessage(),in3.nextmessage()):
self.failUnless(utilsunit.comparenode(in1node.root,in2node.root),'compare')
self.failUnless(utilsunit.comparenode(in1node.root,in3node.root),'compare')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0403/040305.edi') #needs UNOA regular
#~ in1= inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0403/040305.edi') #needs UNOA extended
in7= inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0403/040304.edi') #UNOB-regular
in5= inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0403/T0000000008.edi') #UNOB regular
in4= inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0403/T0000000007-generated.edi') #UNOB regular
in6= inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0403/T0000000009.edi') #UNOC
def testedifact0404(self):
#envelope tests
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040401.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040402.edi')
self.failUnless(inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040403.edi'), 'standaard test')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040404.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040405.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040406.edi')
#self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040407.edi') #syntax version '0'; is not checked anymore
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040408.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040409.edi')
self.failUnless(inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040410.edi'), 'standaard test')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040411.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040412.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040413.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040414.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040415.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040416.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040417.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040418.edi')
def testedifact0407(self):
#lex test with characters in strange places
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0407/040701.edi')
self.failUnless(inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0407/040702.edi'), 'standaard test')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0407/040703.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0407/040704.edi')
self.failUnless(inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0407/040705.edi'), 'standaard test')
self.failUnless(inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0407/040706.edi'), 'UNOA Crtl-Z at end')
self.failUnless(inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0407/040707.edi'), 'UNOB Crtl-Z at end')
self.failUnless(inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0407/040708.edi'), 'UNOC Crtl-Z at end')
def testedifact0408(self):
#differentenvelopingsamecontent: 1rst UNH per UNB, 2nd has 2 UNB for all UNH's, 3rd has UNG-UNE
in1= inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0408/040801.edi')
in2= inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0408/040802.edi')
in3= inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0408/040803.edi')
for in1node,in2node,in3node in zip(in1.nextmessage(),in2.nextmessage(),in3.nextmessage()):
self.failUnless(utilsunit.comparenode(in1node.root,in2node.root),'compare')
self.failUnless(utilsunit.comparenode(in1node.root,in3node.root),'compare')
if __name__ == '__main__':
botsinit.generalinit('config')
botsinit.initenginelogging()
unittest.main()
| Python |
#!/usr/bin/env python
from bots import engine
if __name__ == '__main__':
engine.start()
| Python |
import os
import sys
from distutils.core import setup
from distutils.command.install import INSTALL_SCHEMES
#install data file in the same way as *.py
for scheme in INSTALL_SCHEMES.values():
scheme['data'] = scheme['purelib']
def fullsplit(path, result=None):
"""
Split a pathname into components (the opposite of os.path.join) in a
platform-neutral way.
"""
if result is None:
result = []
head, tail = os.path.split(path)
if head == '':
return [tail] + result
if head == path:
return result
return fullsplit(head, [tail] + result)
# Compile the list of packages available, because distutils doesn't have
# an easy way to do this.
packages, data_files = [], []
root_dir = os.path.dirname(__file__)
if root_dir != '':
os.chdir(root_dir)
for dirpath, dirnames, filenames in os.walk('bots'):
# Ignore dirnames that start with '.'
#~ for i, dirname in enumerate(dirnames):
#~ if dirname.startswith('.'): del dirnames[i]
if '__init__.py' in filenames:
packages.append('.'.join(fullsplit(dirpath)))
if len(filenames) > 1:
data_files.append([dirpath, [os.path.join(dirpath, f) for f in filenames if not f.endswith('.pyc') and not f.endswith('.py')]])
elif filenames:
data_files.append([dirpath, [os.path.join(dirpath, f) for f in filenames if not f.endswith('.pyc') and not f.endswith('.py')]])
setup(
name="bots",
version="2.1.0",
author = "hjebbers",
author_email = "hjebbers@gmail.com",
url = "http://bots.sourceforge.net/",
description="Bots open source edi translator",
long_description = "Bots is complete software for edi (Electronic Data Interchange): translate and communicate. All major edi data formats are supported: edifact, x12, tradacoms, xml",
platforms="OS Independent (Written in an interpreted language)",
license="GNU General Public License (GPL)",
classifiers = [
'Development Status :: 5 - Production/Stable',
'Operating System :: OS Independent',
'Programming Language :: Python',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Topic :: Office/Business',
'Topic :: Office/Business :: Financial',
'Topic :: Other/Nonlisted Topic',
'Topic :: Communications',
'Environment :: Console',
'Environment :: Web Environment',
],
scripts = [ 'bots-webserver.py',
'bots-engine.py',
'bots-grammarcheck.py',
'bots-xml2botsgrammar.py',
#~ 'bots/bots-updatedb.py',
],
packages = packages,
data_files = data_files,
)
| Python |
import os
import sys
from distutils.core import setup
from distutils.command.install import INSTALL_SCHEMES
#install data file in the same way as *.py
for scheme in INSTALL_SCHEMES.values():
scheme['data'] = scheme['purelib']
def fullsplit(path, result=None):
"""
Split a pathname into components (the opposite of os.path.join) in a
platform-neutral way.
"""
if result is None:
result = []
head, tail = os.path.split(path)
if head == '':
return [tail] + result
if head == path:
return result
return fullsplit(head, [tail] + result)
# Compile the list of packages available, because distutils doesn't have
# an easy way to do this.
packages, data_files = [], []
root_dir = os.path.dirname(__file__)
if root_dir != '':
os.chdir(root_dir)
for dirpath, dirnames, filenames in os.walk('bots'):
# Ignore dirnames that start with '.'
#~ for i, dirname in enumerate(dirnames):
#~ if dirname.startswith('.'): del dirnames[i]
if '__init__.py' in filenames:
packages.append('.'.join(fullsplit(dirpath)))
if len(filenames) > 1:
data_files.append([dirpath, [os.path.join(dirpath, f) for f in filenames if not f.endswith('.pyc') and not f.endswith('.py')]])
elif filenames:
data_files.append([dirpath, [os.path.join(dirpath, f) for f in filenames if not f.endswith('.pyc') and not f.endswith('.py')]])
setup(
name="bots",
version="2.1.0",
author = "hjebbers",
author_email = "hjebbers@gmail.com",
url = "http://bots.sourceforge.net/",
description="Bots open source edi translator",
long_description = "Bots is complete software for edi (Electronic Data Interchange): translate and communicate. All major edi data formats are supported: edifact, x12, tradacoms, xml",
platforms="OS Independent (Written in an interpreted language)",
license="GNU General Public License (GPL)",
classifiers = [
'Development Status :: 5 - Production/Stable',
'Operating System :: OS Independent',
'Programming Language :: Python',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Topic :: Office/Business',
'Topic :: Office/Business :: Financial',
'Topic :: Other/Nonlisted Topic',
'Topic :: Communications',
'Environment :: Console',
'Environment :: Web Environment',
],
scripts = [ 'bots-webserver.py',
'bots-engine.py',
'bots-grammarcheck.py',
'bots-xml2botsgrammar.py',
#~ 'bots/bots-updatedb.py',
],
packages = packages,
data_files = data_files,
)
| Python |
#!/usr/bin/env python
from bots import xml2botsgrammar
if __name__=='__main__':
xml2botsgrammar.start()
| Python |
import os
import unittest
import shutil
import bots.inmessage as inmessage
import bots.outmessage as outmessage
import filecmp
try:
import json as simplejson
except ImportError:
import simplejson
import bots.botslib as botslib
import bots.botsinit as botsinit
import utilsunit
''' pluging unitinisout.zip'''
class Testinisoutedifact(unittest.TestCase):
def testedifact02(self):
infile ='botssys/infile/unitinisout/org/inisout02.edi'
outfile='botssys/infile/unitinisout/output/inisout02.edi'
inn = inmessage.edifromfile(editype='edifact',messagetype='orderswithenvelope',filename=infile)
out = outmessage.outmessage_init(editype='edifact',messagetype='orderswithenvelope',filename=outfile,divtext='',topartner='') #make outmessage object
out.root = inn.root
out.writeall()
self.failUnless(filecmp.cmp('bots/' + outfile,'bots/' + infile))
def testedifact03(self):
#~ #takes quite long
infile ='botssys/infile/unitinisout/org/inisout03.edi'
outfile='botssys/infile/unitinisout/output/inisout03.edi'
inn = inmessage.edifromfile(editype='edifact',messagetype='invoicwithenvelope',filename=infile)
out = outmessage.outmessage_init(editype='edifact',messagetype='invoicwithenvelope',filename=outfile,divtext='',topartner='') #make outmessage object
out.root = inn.root
out.writeall()
self.failUnless(filecmp.cmp('bots/' + outfile,'bots/' + infile))
def testedifact04(self):
utilsunit.readwrite(editype='edifact',
messagetype='orderswithenvelope',
filenamein='botssys/infile/unitinisout/0406edifact/040601.edi',
filenameout='botssys/infile/unitinisout/output/040601.edi')
utilsunit.readwrite(editype='edifact',
messagetype='orderswithenvelope',
filenamein='botssys/infile/unitinisout/0406edifact/040602.edi',
filenameout='botssys/infile/unitinisout/output/040602.edi')
utilsunit.readwrite(editype='edifact',
messagetype='orderswithenvelope',
filenamein='botssys/infile/unitinisout/0406edifact/040603.edi',
filenameout='botssys/infile/unitinisout/output/040603.edi')
utilsunit.readwrite(editype='edifact',
messagetype='orderswithenvelope',
filenamein='botssys/infile/unitinisout/0406edifact/040604.edi',
filenameout='botssys/infile/unitinisout/output/040604.edi')
utilsunit.readwrite(editype='edifact',
messagetype='orderswithenvelope',
filenamein='botssys/infile/unitinisout/0406edifact/040605.edi',
filenameout='botssys/infile/unitinisout/output/040605.edi')
utilsunit.readwrite(editype='edifact',
messagetype='orderswithenvelope',
filenamein='botssys/infile/unitinisout/0406edifact/040606.edi',
filenameout='botssys/infile/unitinisout/output/040606.edi')
utilsunit.readwrite(editype='edifact',
messagetype='orderswithenvelope',
filenamein='botssys/infile/unitinisout/0406edifact/040607.edi',
filenameout='botssys/infile/unitinisout/output/040607.edi')
utilsunit.readwrite(editype='edifact',
messagetype='orderswithenvelope',
filenamein='botssys/infile/unitinisout/0406edifact/040608.edi',
filenameout='botssys/infile/unitinisout/output/040608.edi')
self.failUnless(filecmp.cmp('bots/botssys/infile/unitinisout/output/040601.edi','bots/botssys/infile/unitinisout/output/040602.edi'))
self.failUnless(filecmp.cmp('bots/botssys/infile/unitinisout/output/040601.edi','bots/botssys/infile/unitinisout/output/040603.edi'))
self.failUnless(filecmp.cmp('bots/botssys/infile/unitinisout/output/040601.edi','bots/botssys/infile/unitinisout/output/040604.edi'))
self.failUnless(filecmp.cmp('bots/botssys/infile/unitinisout/output/040601.edi','bots/botssys/infile/unitinisout/output/040605.edi'))
self.failUnless(filecmp.cmp('bots/botssys/infile/unitinisout/output/040601.edi','bots/botssys/infile/unitinisout/output/040606.edi'))
self.failUnless(filecmp.cmp('bots/botssys/infile/unitinisout/output/040601.edi','bots/botssys/infile/unitinisout/output/040607.edi'))
self.failUnless(filecmp.cmp('bots/botssys/infile/unitinisout/output/040601.edi','bots/botssys/infile/unitinisout/output/040608.edi'))
class Testinisoutinh(unittest.TestCase):
def testinh01(self):
filenamein='botssys/infile/unitinisout/org/inisout01.inh'
filenameout='botssys/infile/unitinisout/output/inisout01.inh'
inn = inmessage.edifromfile(editype='fixed',messagetype='invoicfixed',filename=filenamein)
out = outmessage.outmessage_init(editype='fixed',messagetype='invoicfixed',filename=filenameout,divtext='',topartner='') #make outmessage object
out.root = inn.root
out.writeall()
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamein))
def testidoc01(self):
filenamein='botssys/infile/unitinisout/org/inisout01.idoc'
filenameout='botssys/infile/unitinisout/output/inisout01.idoc'
inn = inmessage.edifromfile(editype='idoc',messagetype='WP_PLU02',filename=filenamein)
out = outmessage.outmessage_init(editype='idoc',messagetype='WP_PLU02',filename=filenameout,divtext='',topartner='') #make outmessage object
out.root = inn.root
out.writeall()
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamein))
class Testinisoutx12(unittest.TestCase):
def testx12_01(self):
filenamein='botssys/infile/unitinisout/org/inisout01.x12'
filenameout='botssys/infile/unitinisout/output/inisout01.x12'
inn = inmessage.edifromfile(editype='x12',messagetype='850withenvelope',filename=filenamein)
out = outmessage.outmessage_init(editype='x12',messagetype='850withenvelope',filename=filenameout,divtext='',topartner='') #make outmessage object
out.root = inn.root
out.writeall()
linesfile1 = utilsunit.readfilelines('bots/' + filenamein)
linesfile2 = utilsunit.readfilelines('bots/' + filenameout)
self.assertEqual(linesfile1[0][:103],linesfile2[0][:103],'first part of ISA')
for line1,line2 in zip(linesfile1[1:],linesfile2[1:]):
self.assertEqual(line1,line2,'Cmplines')
def testx12_02(self):
filenamein='botssys/infile/unitinisout/org/inisout02.x12'
filenameout='botssys/infile/unitinisout/output/inisout02.x12'
inn = inmessage.edifromfile(editype='x12',messagetype='850withenvelope',filename=filenamein)
out = outmessage.outmessage_init(add_crlfafterrecord_sep='',editype='x12',messagetype='850withenvelope',filename=filenameout,divtext='',topartner='') #make outmessage object
out.root = inn.root
out.writeall()
linesfile1 = utilsunit.readfile('bots/' + filenamein)
linesfile2 = utilsunit.readfile('bots/' + filenameout)
self.assertEqual(linesfile1[:103],linesfile2[:103],'first part of ISA')
self.assertEqual(linesfile1[105:],linesfile2[103:],'rest of message')
class Testinisoutcsv(unittest.TestCase):
def testcsv001(self):
filenamein='botssys/infile/unitinisout/org/inisout01.csv'
filenameout='botssys/infile/unitinisout/output/inisout01.csv'
utilsunit.readwrite(editype='csv',messagetype='invoic',filenamein=filenamein,filenameout=filenameout)
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamein))
def testcsv003(self):
#utf-charset
filenamein='botssys/infile/unitinisout/org/inisout03.csv'
filenameout='botssys/infile/unitinisout/output/inisout03.csv'
utilsunit.readwrite(editype='csv',messagetype='invoic',filenamein=filenamein,filenameout=filenameout)
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamein))
#~ #utf-charset with BOM **error. BOM is not removed by python.
#~ #utilsunit.readwrite(editype='csv',
#~ # messagetype='invoic',
#~ # filenamein='botssys/infile/unitinisout/inisout04.csv',
#~ # filenameout='botssys/infile/unitinisout/output/inisout04.csv')
#~ #self.failUnless(filecmp.cmp('botssys/infile/unitinisout/output/inisout04.csv','botssys/infile/unitinisout/inisout04.csv'))
if __name__ == '__main__':
botsinit.generalinit('config')
#~ botslib.initbotscharsets()
botsinit.initenginelogging()
shutil.rmtree('bots/botssys/infile/unitinisout/output',ignore_errors=True) #remove whole output directory
os.mkdir('bots/botssys/infile/unitinisout/output')
unittest.main()
| Python |
#!/usr/bin/env python
from bots import grammarcheck
if __name__=='__main__':
grammarcheck.start()
| Python |
import os
import sys
from distutils.core import setup
def fullsplit(path, result=None):
"""
Split a pathname into components (the opposite of os.path.join) in a
platform-neutral way.
"""
if result is None:
result = []
head, tail = os.path.split(path)
if head == '':
return [tail] + result
if head == path:
return result
return fullsplit(head, [tail] + result)
# Compile the list of packages available, because distutils doesn't have
# an easy way to do this.
packages, data_files = [], []
root_dir = os.path.dirname(__file__)
if root_dir != '':
os.chdir(root_dir)
for dirpath, dirnames, filenames in os.walk('bots'):
# Ignore dirnames that start with '.'
#~ for i, dirname in enumerate(dirnames):
#~ if dirname.startswith('.'): del dirnames[i]
if '__init__.py' in filenames:
packages.append('.'.join(fullsplit(dirpath)))
data_files.append([dirpath, [os.path.join(dirpath, f) for f in filenames if not f.endswith('.pyc')]])
elif filenames:
data_files.append([dirpath, [os.path.join(dirpath, f) for f in filenames if not f.endswith('.pyc')]])
#~ # Small hack for working with bdist_wininst.
#~ # See http://mail.python.org/pipermail/distutils-sig/2004-August/004134.html
#~ if len(sys.argv) > 1 and 'bdist_wininst' in sys.argv[1:]:
if len(sys.argv) > 1 and 'bdist_wininst' in sys.argv[1:]:
for file_info in data_files:
file_info[0] = '\\PURELIB\\%s' % file_info[0]
setup(
name="bots",
version="2.1.0",
author = "hjebbers",
author_email = "hjebbers@gmail.com",
url = "http://bots.sourceforge.net/",
description="Bots open source edi translator",
long_description = "Bots is complete software for edi (Electronic Data Interchange): translate and communicate. All major edi data formats are supported: edifact, x12, tradacoms, xml",
platforms="OS Independent (Written in an interpreted language)",
license="GNU General Public License (GPL)",
classifiers = [
'Development Status :: 5 - Production/Stable',
'Operating System :: OS Independent',
'Programming Language :: Python',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Topic :: Office/Business',
'Topic :: Office/Business :: Financial',
'Topic :: Other/Nonlisted Topic',
'Topic :: Communications',
'Environment :: Console',
'Environment :: Web Environment',
],
scripts = [ 'bots-webserver.py',
'bots-engine.py',
'postinstallation.py',
'bots-grammarcheck.py',
'bots-xml2botsgrammar.py',
#~ 'bots/bots-updatedb.py',
],
packages = packages,
data_files = data_files,
)
| Python |
#!/usr/bin/env python
if __name__ == '__main__':
import cProfile
cProfile.run('from bots import engine; engine.start()','profile.tmp')
import pstats
p = pstats.Stats('profile.tmp')
#~ p.sort_stats('cumulative').print_stats(25)
p.sort_stats('time').print_stats(25)
#~ p.print_callees('deepcopy').print_stats(1)
p.print_callees('mydeepcopy')
#~ p.sort_stats('time').print_stats('grammar.py',50)
| Python |
import os
import unittest
import shutil
import bots.inmessage as inmessage
import bots.outmessage as outmessage
import filecmp
import bots.botslib as botslib
import bots.botsinit as botsinit
import utilsunit
''' pluging unitinmessagexml.zip'''
class TestInmessage(unittest.TestCase):
''' Read messages; some should be OK (True), some shoudl give errors (False).
Tets per editype.
'''
def setUp(self):
pass
def testxml(self):
#~ #empty file
self.assertRaises(SyntaxError,inmessage.edifromfile, editype='xmlnocheck',messagetype='xmlnocheck',filename='botssys/infile/unitinmessagexml/xml/110401.xml')
self.assertRaises(SyntaxError,inmessage.edifromfile, editype='xml',messagetype='testxml', filename='botssys/infile/unitinmessagexml/xml/110401.xml')
self.assertRaises(SyntaxError,inmessage.edifromfile, editype='xml',messagetype='testxml',checkunknownentities=True, filename='botssys/infile/unitinmessagexml/xml/110401.xml')
self.assertRaises(SyntaxError,inmessage.edifromfile, editype='xml',messagetype='testxmlflatten', filename='botssys/infile/unitinmessagexml/xml/110401.xml')
#only root record in 110402.xml
self.failUnless(inmessage.edifromfile(editype='xmlnocheck',messagetype='xmlnocheck',filename='botssys/infile/unitinmessagexml/xml/110402.xml'), 'only a root tag; should be OK')
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='xml',messagetype='testxml',filename='botssys/infile/unitinmessagexml/xml/110402.xml')
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='xml',messagetype='testxml',checkunknownentities=True, filename='botssys/infile/unitinmessagexml/xml/110402.xml')
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='xml',messagetype='testxmlflatten',filename='botssys/infile/unitinmessagexml/xml/110402.xml')
#root tag different from grammar
self.assertRaises(botslib.InMessageError,inmessage.edifromfile, editype='xml',messagetype='testxml',filename='botssys/infile/unitinmessagexml/xml/110406.xml')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile, editype='xml',messagetype='testxml',checkunknownentities=True, filename='botssys/infile/unitinmessagexml/xml/110406.xml')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile, editype='xml',messagetype='testxmlflatten',filename='botssys/infile/unitinmessagexml/xml/110406.xml')
#root tag is double
self.assertRaises(SyntaxError,inmessage.edifromfile, editype='xmlnocheck',messagetype='xmlnocheck',filename='botssys/infile/unitinmessagexml/xml/110407.xml')
#invalid: no closing tag
self.assertRaises(SyntaxError,inmessage.edifromfile, editype='xmlnocheck',messagetype='xmlnocheck',filename='botssys/infile/unitinmessagexml/xml/110408.xml')
#invalid: extra closing tag
self.assertRaises(SyntaxError,inmessage.edifromfile, editype='xmlnocheck',messagetype='xmlnocheck',filename='botssys/infile/unitinmessagexml/xml/110409.xml')
#invalid: mandatory xml-element missing
self.failUnless(inmessage.edifromfile(editype='xmlnocheck',messagetype='xmlnocheck',filename='botssys/infile/unitinmessagexml/xml/110410.xml'), '')
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='xml',messagetype='testxml',filename='botssys/infile/unitinmessagexml/xml/110410.xml')
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='xml',messagetype='testxml',checkunknownentities=True, filename='botssys/infile/unitinmessagexml/xml/110410.xml')
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='xml',messagetype='testxmlflatten',filename='botssys/infile/unitinmessagexml/xml/110410.xml')
#invalid: to many occurences
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='xml',messagetype='testxml',filename='botssys/infile/unitinmessagexml/xml/110411.xml')
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='xml',messagetype='testxml',checkunknownentities=True, filename='botssys/infile/unitinmessagexml/xml/110411.xml')
#invalid: missing mandatory xml attribute
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='xml',messagetype='testxml',filename='botssys/infile/unitinmessagexml/xml/110412.xml')
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='xml',messagetype='testxml',checkunknownentities=True,filename='botssys/infile/unitinmessagexml/xml/110412.xml')
#unknown xml element
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='xml',messagetype='testxml',checkunknownentities=True,filename='botssys/infile/unitinmessagexml/xml/110413.xml')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile, editype='xml',messagetype='testxml',checkunknownentities=True,filename='botssys/infile/unitinmessagexml/xml/110414.xml')
#2x the same xml attribute
self.assertRaises(SyntaxError,inmessage.edifromfile, editype='xml',messagetype='testxml',filename='botssys/infile/unitinmessagexml/xml/110415.xml')
self.assertRaises(SyntaxError,inmessage.edifromfile, editype='xml',messagetype='testxml',checkunknownentities=True,filename='botssys/infile/unitinmessagexml/xml/110415.xml')
#messages with all max occurences, use attributes, etc
in1 = inmessage.edifromfile(editype='xml',messagetype='testxml',filename='botssys/infile/unitinmessagexml/xml/110416.xml') #all elements, attributes
#other order of xml elements; should esult in the same node tree
in1 = inmessage.edifromfile(editype='xml',messagetype='testxml',filename='botssys/infile/unitinmessagexml/xml/110417.xml') #as 18., other order of elements
in2 = inmessage.edifromfile(editype='xml',messagetype='testxml',filename='botssys/infile/unitinmessagexml/xml/110418.xml')
self.failUnless(utilsunit.comparenode(in2.root,in1.root),'compare')
#??what is tested here??
inn7= inmessage.edifromfile(editype='xml',messagetype='testxml',checkunknownentities=True,filename='botssys/infile/unitinmessagexml/xml/110405.xml') #with <?xml version="1.0" encoding="utf-8"?>
inn8= inmessage.edifromfile(editype='xml',messagetype='testxmlflatten',checkunknownentities=True,filename='botssys/infile/unitinmessagexml/xml/110405.xml') #with <?xml version="1.0" encoding="utf-8"?>
self.failUnless(utilsunit.comparenode(inn7.root,inn8.root),'compare')
#~ #test different file which should give equal results
in1= inmessage.edifromfile(editype='xmlnocheck',messagetype='xmlnocheck',filename='botssys/infile/unitinmessagexml/xml/110403.xml') #no grammar used
in5= inmessage.edifromfile(editype='xmlnocheck',messagetype='xmlnocheck',filename='botssys/infile/unitinmessagexml/xml/110404.xml') #no grammar used
in6= inmessage.edifromfile(editype='xmlnocheck',messagetype='xmlnocheck',filename='botssys/infile/unitinmessagexml/xml/110405.xml') #no grammar used
in2= inmessage.edifromfile(editype='xml',messagetype='testxml',filename='botssys/infile/unitinmessagexml/xml/110403.xml') #with <?xml version="1.0" encoding="utf-8"?>
in3= inmessage.edifromfile(editype='xml',messagetype='testxml',filename='botssys/infile/unitinmessagexml/xml/110404.xml') #without <?xml version="1.0" encoding="utf-8"?>
in4= inmessage.edifromfile(editype='xml',messagetype='testxml',filename='botssys/infile/unitinmessagexml/xml/110405.xml') #use cr/lf and whitespace for 'nice' xml
self.failUnless(utilsunit.comparenode(in2.root,in1.root),'compare')
self.failUnless(utilsunit.comparenode(in2.root,in3.root),'compare')
self.failUnless(utilsunit.comparenode(in2.root,in4.root),'compare')
self.failUnless(utilsunit.comparenode(in2.root,in5.root),'compare')
self.failUnless(utilsunit.comparenode(in2.root,in6.root),'compare')
#~ #test different file which should give equal results; flattenxml=True,
in1= inmessage.edifromfile(editype='xmlnocheck',messagetype='xmlnocheck',filename='botssys/infile/unitinmessagexml/xml/110403.xml') #no grammar used
in5= inmessage.edifromfile(editype='xmlnocheck',messagetype='xmlnocheck',filename='botssys/infile/unitinmessagexml/xml/110404.xml') #no grammar used
in6= inmessage.edifromfile(editype='xmlnocheck',messagetype='xmlnocheck',filename='botssys/infile/unitinmessagexml/xml/110405.xml') #no grammar used
in4= inmessage.edifromfile(editype='xml',messagetype='testxmlflatten',filename='botssys/infile/unitinmessagexml/xml/110405.xml') #use cr/lf and whitespace for 'nice' xml
in2= inmessage.edifromfile(editype='xml',messagetype='testxmlflatten',filename='botssys/infile/unitinmessagexml/xml/110403.xml') #with <?xml version="1.0" encoding="utf-8"?>
in3= inmessage.edifromfile(editype='xml',messagetype='testxmlflatten',filename='botssys/infile/unitinmessagexml/xml/110404.xml') #without <?xml version="1.0" encoding="utf-8"?>
self.failUnless(utilsunit.comparenode(in2.root,in1.root),'compare')
self.failUnless(utilsunit.comparenode(in2.root,in3.root),'compare')
self.failUnless(utilsunit.comparenode(in2.root,in4.root),'compare')
self.failUnless(utilsunit.comparenode(in2.root,in5.root),'compare')
self.failUnless(utilsunit.comparenode(in2.root,in6.root),'compare')
class Testinisoutxml(unittest.TestCase):
def testxml01a(self):
''' check xml; new behaviour'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout02.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout01a.xml'
utilsunit.readwrite(editype='xml',messagetype='xmlorder',filenamein=filenamein,filenameout=filenameout)
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamein))
def testxml02a(self):
''' check xmlnoccheck; new behaviour'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout02.xml'
filenametmp='botssys/infile/unitinmessagexml/output/inisout02tmpa.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout02a.xml'
utilsunit.readwrite(editype='xmlnocheck',messagetype='xmlnocheck',filenamein=filenamein,filenameout=filenametmp)
utilsunit.readwrite(editype='xml',messagetype='xmlorder',filenamein=filenametmp,filenameout=filenameout)
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamein))
def testxml03(self):
''' check xml (different grammar)'''
filenamein='botssys/infile/unitinmessagexml/xml/110419.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout03.xml'
utilsunit.readwrite(editype='xml',messagetype='testxmlflatten',charset='utf-8',filenamein=filenamein,filenameout=filenameout)
self.failUnless(filecmp.cmp('bots/' + filenamein,'bots/' + filenameout))
def testxml04(self):
''' check xmlnoccheck'''
filenamein='botssys/infile/unitinmessagexml/xml/110419.xml'
filenametmp='botssys/infile/unitinmessagexml/output/inisout04tmp.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout04.xml'
utilsunit.readwrite(editype='xmlnocheck',messagetype='xmlnocheck',charset='utf-8',filenamein=filenamein,filenameout=filenametmp)
utilsunit.readwrite(editype='xml',messagetype='testxmlflatten',charset='utf-8',filenamein=filenametmp,filenameout=filenameout)
self.failUnless(filecmp.cmp('bots/' + filenamein,'bots/' + filenameout))
def testxml05(self):
''' test xml; iso-8859-1'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout03.xml'
filenamecmp='botssys/infile/unitinmessagexml/xml/inisoutcompare05.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout05.xml'
utilsunit.readwrite(editype='xml',messagetype='testxml',filenamein=filenamein,filenameout=filenameout,charset='ISO-8859-1')
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamecmp))
def testxml06(self):
''' test xmlnocheck; iso-8859-1'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout03.xml'
filenametmp='botssys/infile/unitinmessagexml/output/inisout05tmp.xml'
filenamecmp='botssys/infile/unitinmessagexml/xml/inisoutcompare05.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout05a.xml'
utilsunit.readwrite(editype='xmlnocheck',messagetype='xmlnocheck',filenamein=filenamein,filenameout=filenametmp,charset='ISO-8859-1')
utilsunit.readwrite(editype='xml',messagetype='testxml',filenamein=filenametmp,filenameout=filenameout,charset='ISO-8859-1')
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamecmp))
def testxml09(self):
''' BOM;; BOM is not written....'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout05.xml'
filenamecmp='botssys/infile/unitinmessagexml/xml/inisout04.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout09.xml'
utilsunit.readwrite(editype='xml',messagetype='testxml',filenamein=filenamein,filenameout=filenameout,charset='utf-8')
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamecmp))
def testxml10(self):
''' BOM;; BOM is not written....'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout05.xml'
filenametmp='botssys/infile/unitinmessagexml/output/inisout10tmp.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout10.xml'
filenamecmp='botssys/infile/unitinmessagexml/xml/inisout04.xml'
utilsunit.readwrite(editype='xmlnocheck',messagetype='xmlnocheck',filenamein=filenamein,filenameout=filenametmp)
utilsunit.readwrite(editype='xml',messagetype='testxml',filenamein=filenametmp,filenameout=filenameout,charset='utf-8')
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamecmp))
def testxml11(self):
''' check xml; new behaviour; use standalone parameter'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout06.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout11.xml'
filenamecmp='botssys/infile/unitinmessagexml/xml/inisout02.xml'
utilsunit.readwrite(editype='xml',messagetype='xmlorder',filenamein=filenamein,filenameout=filenameout,standalone=None)
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamecmp))
def testxml11a(self):
''' check xml; new behaviour; use standalone parameter'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout06.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout11a.xml'
utilsunit.readwrite(editype='xml',messagetype='xmlorder',filenamein=filenamein,filenameout=filenameout,standalone='no')
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamein))
def testxml12(self):
''' check xmlnoccheck; new behaviour use standalone parameter'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout06.xml'
filenametmp='botssys/infile/unitinmessagexml/output/inisout12tmp.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout12.xml'
utilsunit.readwrite(editype='xmlnocheck',messagetype='xmlnocheck',filenamein=filenamein,filenameout=filenametmp,standalone='no')
utilsunit.readwrite(editype='xml',messagetype='xmlorder',filenamein=filenametmp,filenameout=filenameout,standalone='no')
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamein))
def testxml13(self):
''' check xml; read doctype&write doctype'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout13.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout13.xml'
utilsunit.readwrite(editype='xml',messagetype='xmlorder',filenamein=filenamein,filenameout=filenameout,DOCTYPE = 'mydoctype SYSTEM "mydoctype.dtd"')
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamein))
def testxml14(self):
''' check xmlnoccheck; read doctype&write doctype'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout13.xml'
filenametmp='botssys/infile/unitinmessagexml/output/inisout14tmp.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout14.xml'
utilsunit.readwrite(editype='xmlnocheck',messagetype='xmlnocheck',filenamein=filenamein,filenameout=filenametmp,DOCTYPE = 'mydoctype SYSTEM "mydoctype.dtd"')
utilsunit.readwrite(editype='xml',messagetype='xmlorder',filenamein=filenametmp,filenameout=filenameout,DOCTYPE = 'mydoctype SYSTEM "mydoctype.dtd"')
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamein))
def testxml15(self):
''' check xml; read processing_instructions&write processing_instructions'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout15.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout15.xml'
utilsunit.readwrite(editype='xml',messagetype='xmlorder',filenamein=filenamein,filenameout=filenameout,processing_instructions=[('xml-stylesheet' ,'href="mystylesheet.xsl" type="text/xml"'),('type-of-ppi' ,'attr1="value1" attr2="value2"')])
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamein))
def testxml16(self):
''' check xmlnoccheck; read processing_instructions&write processing_instructions'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout15.xml'
filenametmp='botssys/infile/unitinmessagexml/output/inisout16tmp.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout16.xml'
utilsunit.readwrite(editype='xmlnocheck',messagetype='xmlnocheck',filenamein=filenamein,filenameout=filenametmp,processing_instructions=[('xml-stylesheet' ,'href="mystylesheet.xsl" type="text/xml"'),('type-of-ppi' ,'attr1="value1" attr2="value2"')])
utilsunit.readwrite(editype='xml',messagetype='xmlorder',filenamein=filenametmp,filenameout=filenameout,processing_instructions=[('xml-stylesheet' ,'href="mystylesheet.xsl" type="text/xml"'),('type-of-ppi' ,'attr1="value1" attr2="value2"')])
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamein))
def testxml17(self):
''' check xml; read processing_instructions&doctype&comments. Do not write these.'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout17.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout17.xml'
filenamecmp='botssys/infile/unitinmessagexml/xml/inisout02.xml'
utilsunit.readwrite(editype='xml',messagetype='xmlorder',filenamein=filenamein,filenameout=filenameout)
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamecmp))
def testxml18(self):
''' check xml; read processing_instructions&doctype&comments. Do not write these.'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout17.xml'
filenametmp='botssys/infile/unitinmessagexml/output/inisout18tmp.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout18.xml'
filenamecmp='botssys/infile/unitinmessagexml/xml/inisout02.xml'
utilsunit.readwrite(editype='xmlnocheck',messagetype='xmlnocheck',filenamein=filenamein,filenameout=filenametmp)
utilsunit.readwrite(editype='xml',messagetype='xmlorder',filenamein=filenametmp,filenameout=filenameout)
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamecmp))
def testxml19(self):
''' check xml; indented; use lot of options.'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout02.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout19.xml'
filenamecmp='botssys/infile/unitinmessagexml/xml/inisout19.xml'
utilsunit.readwrite(editype='xml',messagetype='xmlorder',filenamein=filenamein,filenameout=filenameout,indented=True,standalone='yes',DOCTYPE = 'mydoctype SYSTEM "mydoctype.dtd"',processing_instructions=[('xml-stylesheet' ,'href="mystylesheet.xsl" type="text/xml"'),('type-of-ppi' ,'attr1="value1" attr2="value2"')])
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamecmp))
def testxml20(self):
''' check xml; indented; use lot of options.'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout02.xml'
filenametmp='botssys/infile/unitinmessagexml/output/inisout20tmp.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout20.xml'
filenamecmp='botssys/infile/unitinmessagexml/xml/inisout19.xml'
utilsunit.readwrite(editype='xmlnocheck',messagetype='xmlnocheck',filenamein=filenamein,filenameout=filenametmp,indented=True,standalone='yes',DOCTYPE = 'mydoctype SYSTEM "mydoctype.dtd"',processing_instructions=[('xml-stylesheet' ,'href="mystylesheet.xsl" type="text/xml"'),('type-of-ppi' ,'attr1="value1" attr2="value2"')])
utilsunit.readwrite(editype='xml',messagetype='xmlorder',filenamein=filenametmp,filenameout=filenameout,indented=True,standalone='yes',DOCTYPE = 'mydoctype SYSTEM "mydoctype.dtd"',processing_instructions=[('xml-stylesheet' ,'href="mystylesheet.xsl" type="text/xml"'),('type-of-ppi' ,'attr1="value1" attr2="value2"')])
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamecmp))
if __name__ == '__main__':
botsinit.generalinit('config')
#~ botslib.initbotscharsets()
botsinit.initenginelogging()
shutil.rmtree('bots/botssys/infile/unitinmessagexml/output',ignore_errors=True) #remove whole output directory
os.mkdir('bots/botssys/infile/unitinmessagexml/output')
unittest.main()
| Python |
#!/usr/bin/env python
from bots import webserver
if __name__ == '__main__':
webserver.start()
| Python |
import filecmp
import glob
import shutil
import os
import sys
import subprocess
import logging
import logging
import bots.botslib as botslib
import bots.botsinit as botsinit
import bots.botsglobal as botsglobal
from bots.botsconfig import *
'''plugin unitretry.zip'''
#!!!activate rotues
''' input: mime (complex structure); 2 different edi attachments, and ' tekst' attachemnt
some user scripts are written in this unit test; so one runs errors will occur; write user script which prevents error in next run
before running: delete all transactions.
runs OK if no errors in unit tests
'''
def dummylogger():
botsglobal.logger = logging.getLogger('dummy')
botsglobal.logger.setLevel(logging.ERROR)
botsglobal.logger.addHandler(logging.StreamHandler(sys.stdout))
def getlastreport():
for row in botslib.query(u'''SELECT *
FROM report
ORDER BY idta DESC
'''):
#~ print row
return row
def mycompare(dict1,dict2):
for key,value in dict1.items():
if value != dict2[key]:
raise Exception('error comparing "%s": should be %s but is %s (in db),'%(key,value,dict2[key]))
def scriptwrite(path,content):
f = open(path,'w')
f.write(content)
f.close()
if __name__ == '__main__':
pythoninterpreter = 'python2.7'
newcommand = [pythoninterpreter,'bots-engine.py',]
retrycommand = [pythoninterpreter,'bots-engine.py','--retry']
botsinit.generalinit('config')
botssys = botsglobal.ini.get('directories','botssys')
usersys = botsglobal.ini.get('directories','usersysabs')
dummylogger()
botsinit.connect()
try:
os.remove(os.path.join(usersys,'mappings','edifact','unitretry_2.py'))
os.remove(os.path.join(usersys,'mappings','edifact','unitretry_2.pyc'))
except:
pass
scriptwrite(os.path.join(usersys,'mappings','edifact','unitretry_2.py'),
'''
import bots.transform as transform
def main(inn,out):
raise Exception('test mapping')
transform.inn2out(inn,out)''')
#~ os.remove(os.path.join(usersys,'communicationscripts','unitretry_mime1_in.py'))
#~ os.remove(os.path.join(usersys,'communicationscripts','unitretry_mime1_in.pyc'))
scriptwrite(os.path.join(usersys,'communicationscripts','unitretry_mime1_in.py'),
'''
def accept_incoming_attachment(channeldict,ta,charset,content,contenttype):
if not content.startswith('UNB'):
raise Exception('test')
return True
''')
#
#new; error in mime-handling
subprocess.call(newcommand)
mycompare({'status':1,'lastreceived':1,'lasterror':1,'lastdone':0,'send':0},getlastreport())
#retry: again same error
subprocess.call(retrycommand)
mycompare({'status':1,'lastreceived':1,'lasterror':1,'lastdone':0,'send':0},getlastreport())
#
os.remove(os.path.join(usersys,'communicationscripts','unitretry_mime1_in.py'))
os.remove(os.path.join(usersys,'communicationscripts','unitretry_mime1_in.pyc'))
scriptwrite(os.path.join(usersys,'communicationscripts','unitretry_mime1_in.py'),
'''
def accept_incoming_attachment(channeldict,ta,charset,content,contenttype):
if not content.startswith('UNB'):
return False
return True
''')
#retry: mime is OK< but mapping error will occur
subprocess.call(retrycommand)
mycompare({'status':1,'lastreceived':1,'lasterror':1,'lastdone':0,'send':1},getlastreport())
#retry: mime is OK, same mapping error
subprocess.call(retrycommand)
mycompare({'status':1,'lastreceived':1,'lasterror':1,'lastdone':0,'send':0},getlastreport())
os.remove(os.path.join(usersys,'mappings','edifact','unitretry_2.py'))
os.remove(os.path.join(usersys,'mappings','edifact','unitretry_2.pyc'))
scriptwrite(os.path.join(usersys,'mappings','edifact','unitretry_2.py'),
'''
import bots.transform as transform
def main(inn,out):
transform.inn2out(inn,out)''')
#retry: whole translation is OK
subprocess.call(retrycommand)
mycompare({'status':0,'lastreceived':1,'lasterror':0,'lastdone':1,'send':2},getlastreport())
#new; whole transaltion is OK
subprocess.call(newcommand)
mycompare({'status':0,'lastreceived':1,'lasterror':0,'lastdone':1,'send':2},getlastreport())
logging.shutdown()
botsglobal.db.close | Python |
import unittest
import bots.botslib as botslib
import bots.botsinit as botsinit
import bots.grammar as grammar
import bots.inmessage as inmessage
import bots.outmessage as outmessage
import utilsunit
''' plugin unitgrammar.zip '''
class TestGrammar(unittest.TestCase):
def testgeneralgrammarerrors(self):
self.assertRaises(botslib.GrammarError,grammar.grammarread,'flup','edifact') #not eexisting editype
self.assertRaises(botslib.GrammarError,grammar.syntaxread,'grammars','flup','edifact') #not eexisting editype
self.assertRaises(ImportError,grammar.grammarread,'edifact','flup') #not existing messagetype
self.assertRaises(ImportError,grammar.syntaxread,'grammars','edifact','flup') #not existing messagetype
self.assertRaises(botslib.GrammarError,grammar.grammarread,'test','test3') #no structure
self.assertRaises(ImportError,grammar.grammarread,'test','test4') #No tabel - Reference to not-existing tabel
self.assertRaises(botslib.ScriptImportError,grammar.grammarread,'test','test5') #Error in tabel: structure is not valid python list (syntax-error)
self.assertRaises(botslib.GrammarError,grammar.grammarread,'test','test6') #Error in tabel: record in structure not in recorddefs
self.assertRaises(ImportError,grammar.grammarread,'edifact','test7') #error in syntax
self.assertRaises(ImportError,grammar.syntaxread,'grammars','edifact','test7') #error in syntax
def testgramfieldedifact_and_general(self):
tabel = grammar.grammarread('edifact','edifact')
gramfield = tabel._checkfield
#edifact formats to bots formats
field = ['S001.0001','M', 1,'A']
fieldresult = ['S001.0001','M', 1,'A',True,0,0,'A']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4,'N']
fieldresult = ['S001.0001','M', 4,'N',True,0,0,'R']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4,'AN']
fieldresult = ['S001.0001','M', 4,'AN',True,0,0,'A']
gramfield(field,'')
self.assertEqual(field,fieldresult)
#min&max length
field = ['S001.0001','M', (2,4),'AN']
fieldresult = ['S001.0001','M', 4,'AN',True,0,2,'A']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', (0,4),'AN']
fieldresult = ['S001.0001','M', 4,'AN',True,0,0,'A']
gramfield(field,'')
self.assertEqual(field,fieldresult)
#decimals
field = ['S001.0001','M', 3.2,'N']
fieldresult = ['S001.0001','M', 3,'N',True,2,0,'R']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', (4,4.3),'N']
fieldresult = ['S001.0001','M', 4,'N',True,3,4,'R']
gramfield(field,'')
self.assertEqual(field,fieldresult),
field = ['S001.0001','M', (3.2,4.2),'N']
fieldresult = ['S001.0001','M', 4,'N',True,2,3,'R']
gramfield(field,'')
self.assertEqual(field,fieldresult),
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#test all types of fields (I,R,N,A,D,T); tests not needed repeat for other editypes
#check field itself
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',4],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',4,'','M', 4,'','M'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',4,'','M', 4,''],'')
#check ID
self.assertRaises(botslib.GrammarError,gramfield,['','M', 4,'A'],'')
self.assertRaises(botslib.GrammarError,gramfield,[None,'M', 4,'A'],'')
#check M/C
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','A',4,'I'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','',4,'I'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001',[],4,'I'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','MC',4,'I'],'')
#check format
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',4,'I'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',4,'N7'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',4,''],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',4,5],'')
#check length
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M','N','N'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',0,'N'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',-2,'N'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',-3.2,'N'],'')
#length for formats without float
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',2.1,'A'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',(2.1,3),'A'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',(2,3.2),'A'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',(3,2),'A'],'')
#length for formats with float
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',1.1,'N'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',('A',5),'N'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',(-1,1),'N'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',(5,None),'N'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',(0,1.1),'N'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',(0,0),'N'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',(2,1),'N'],'')
def testgramfieldx12(self):
tabel = grammar.grammarread('x12','x12')
gramfield = tabel._checkfield
#x12 formats to bots formats
field = ['S001.0001','M', 1,'AN']
fieldresult = ['S001.0001','M', 1,'AN',True,0,0,'A']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4,'DT']
fieldresult = ['S001.0001','M', 4,'DT',True,0,0,'D']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4,'TM']
fieldresult = ['S001.0001','M', 4,'TM',True,0,0,'T']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4,'B']
fieldresult = ['S001.0001','M', 4,'B',True,0,0,'A']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4,'ID']
fieldresult = ['S001.0001','M', 4,'ID',True,0,0,'A']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4,'R']
fieldresult = ['S001.0001','M', 4,'R',True,0,0,'R']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4,'N']
fieldresult = ['S001.0001','M', 4,'N',True,0,0,'I']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4,'N0']
fieldresult = ['S001.0001','M', 4,'N0',True,0,0,'I']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4,'N3']
fieldresult = ['S001.0001','M', 4,'N3',True,3,0,'I']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4,'N9']
fieldresult = ['S001.0001','M', 4,'N9',True,9,0,'I']
gramfield(field,'')
self.assertEqual(field,fieldresult)
#decimals
field = ['S001.0001','M', 3,'R']
fieldresult = ['S001.0001','M', 3,'R',True,0,0,'R']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M',4.3,'R']
fieldresult = ['S001.0001','M', 4,'R',True,3,0,'R']
gramfield(field,'')
self.assertEqual(field,fieldresult)
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',4,'D'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',4.3,'I'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',4.3,'NO'],'')
def testgramfieldfixed(self):
tabel = grammar.grammarread('fixed','invoicfixed')
gramfield = tabel._checkfield
#fixed formats to bots formats
field = ['S001.0001','M', 1,'A']
fieldresult = ['S001.0001','M', 1,'A',True,0,1,'A']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4,'D']
fieldresult = ['S001.0001','M', 4,'D',True,0,4,'D']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4,'T']
fieldresult = ['S001.0001','M', 4,'T',True,0,4,'T']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4,'R']
fieldresult = ['S001.0001','M', 4,'R',True,0,4,'R']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4.3,'N']
fieldresult = ['S001.0001','M', 4,'N',True,3,4,'N']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4.3,'I']
fieldresult = ['S001.0001','M', 4,'I',True,3,4,'I']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M',4.3,'R']
fieldresult = ['S001.0001','M', 4,'R',True,3,4,'R']
gramfield(field,'')
self.assertEqual(field,fieldresult)
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',4,'B'],'')
if __name__ == '__main__':
botsinit.generalinit('config')
#~ botslib.initbotscharsets()
botsinit.initenginelogging()
unittest.main()
| Python |
import unittest
import bots.botsglobal as botsglobal
import bots.inmessage as inmessage
import bots.botslib as botslib
import bots.transform as transform
import pickle
import bots.botsinit as botsinit
import utilsunit
'''plugin unittranslateutils.zip '''
#as the max length is
class TestTranslate(unittest.TestCase):
def setUp(self):
pass
def testpersist(self):
#~ inn = inmessage.edifromfile(editype='edifact',messagetype='orderswithenvelope',filename='botssys/infile/tests/inisout02.edi')
domein=u'test'
botskey=u'test'
value= u'xxxxxxxxxxxxxxxxx'
value2= u'IEFJUKAHE*FMhrt4hr f.wch shjeriw'
value3= u'1'*3024
transform.persist_delete(domein,botskey)
#~ self.assertRaises(botslib.PersistError,transform.persist_add,domein,botskey,value3) #content is too long
transform.persist_add(domein,botskey,value)
self.assertRaises(botslib.PersistError,transform.persist_add,domein,botskey,value) #is already present
self.assertEqual(value,transform.persist_lookup(domein,botskey),'basis')
transform.persist_update(domein,botskey,value2)
self.assertEqual(value2,transform.persist_lookup(domein,botskey),'basis')
#~ self.assertRaises(botslib.PersistError,transform.persist_update,domein,botskey,value3) #content is too long
transform.persist_delete(domein,botskey)
self.assertEqual(None,transform.persist_lookup(domein,botskey),'basis')
transform.persist_update(domein,botskey,value) #test-tet is not there. gives no error...
def testpersistunicode(self):
domein=u'test'
botskey=u'1235:\ufb52\ufb66\ufedb'
value= u'xxxxxxxxxxxxxxxxx'
value2= u'IEFJUKAHE*FMhr\u0302\u0267t4hr f.wch shjeriw'
value3= u'1'*1024
transform.persist_delete(domein,botskey)
#~ self.assertRaises(botslib.PersistError,transform.persist_add,domein,botskey,value3) #content is too long
transform.persist_add(domein,botskey,value)
self.assertRaises(botslib.PersistError,transform.persist_add,domein,botskey,value) #is already present
self.assertEqual(value,transform.persist_lookup(domein,botskey),'basis')
transform.persist_update(domein,botskey,value2)
self.assertEqual(value2,transform.persist_lookup(domein,botskey),'basis')
#~ self.assertRaises(botslib.PersistError,transform.persist_update,domein,botskey,value3) #content is too long
transform.persist_delete(domein,botskey)
self.assertEqual(None,transform.persist_lookup(domein,botskey),'basis')
transform.persist_update(domein,botskey,value) #is not there. gives no error...
def testcodeconversion(self):
self.assertEqual('TESTOUT',transform.codeconversion('aperakrff2qualifer','TESTIN'),'basis')
self.assertRaises(botslib.CodeConversionError,transform.codeconversion,'aperakrff2qualifer','TESTINNOT')
self.assertEqual('TESTIN',transform.rcodeconversion('aperakrff2qualifer','TESTOUT'),'basis')
self.assertRaises(botslib.CodeConversionError,transform.rcodeconversion,'aperakrff2qualifer','TESTINNOT')
#need article in ccodelist:
self.assertEqual('TESTOUT',transform.codetconversion('artikel','TESTIN'),'basis')
self.assertRaises(botslib.CodeConversionError,transform.codetconversion,'artikel','TESTINNOT')
self.assertEqual('TESTIN',transform.rcodetconversion('artikel','TESTOUT'),'basis')
self.assertRaises(botslib.CodeConversionError,transform.rcodetconversion,'artikel','TESTINNOT')
self.assertEqual('TESTATTR1',transform.codetconversion('artikel','TESTIN','attr1'),'basis')
def testunique(self):
newdomain = 'test' + transform.unique('test')
self.assertEqual('1',transform.unique(newdomain),'init new domain')
self.assertEqual('2',transform.unique(newdomain),'next one')
def testunique(self):
newdomain = 'test' + transform.unique('test')
self.assertEqual(True,transform.checkunique(newdomain,1),'init new domain')
self.assertEqual(False,transform.checkunique(newdomain,1),'seq should be 2')
self.assertEqual(False,transform.checkunique(newdomain,3),'seq should be 2')
self.assertEqual(True,transform.checkunique(newdomain,2),'next one')
def testean(self):
self.assertEqual('123456789012',transform.addeancheckdigit('12345678901'),'UPC')
self.assertEqual('2',transform.calceancheckdigit('12345678901'),'UPC')
self.assertEqual(True,transform.checkean('123456789012'),'UPC')
self.assertEqual(False,transform.checkean('123456789011'),'UPC')
self.assertEqual(False,transform.checkean('123456789013'),'UPC')
self.assertEqual('123456789012',transform.addeancheckdigit('12345678901'),'UPC')
self.assertEqual('2',transform.calceancheckdigit('12345678901'),'UPC')
self.assertEqual(True,transform.checkean('123456789012'),'UPC')
self.assertEqual(False,transform.checkean('123456789011'),'UPC')
self.assertEqual(False,transform.checkean('123456789013'),'UPC')
self.assertEqual('12345670',transform.addeancheckdigit('1234567'),'EAN8')
self.assertEqual('0',transform.calceancheckdigit('1234567'),'EAN8')
self.assertEqual(True,transform.checkean('12345670'),'EAN8')
self.assertEqual(False,transform.checkean('12345679'),'EAN8')
self.assertEqual(False,transform.checkean('12345671'),'EAN8')
self.assertEqual('1234567890128',transform.addeancheckdigit('123456789012'),'EAN13')
self.assertEqual('8',transform.calceancheckdigit('123456789012'),'EAN13')
self.assertEqual(True,transform.checkean('1234567890128'),'EAN13')
self.assertEqual(False,transform.checkean('1234567890125'),'EAN13')
self.assertEqual(False,transform.checkean('1234567890120'),'EAN13')
self.assertEqual('12345678901231',transform.addeancheckdigit('1234567890123'),'EAN14')
self.assertEqual('1',transform.calceancheckdigit('1234567890123'),'EAN14')
self.assertEqual(True,transform.checkean('12345678901231'),'EAN14')
self.assertEqual(False,transform.checkean('12345678901230'),'EAN14')
self.assertEqual(False,transform.checkean('12345678901236'),'EAN14')
self.assertEqual('123456789012345675',transform.addeancheckdigit('12345678901234567'),'UPC')
self.assertEqual('5',transform.calceancheckdigit('12345678901234567'),'UPC')
self.assertEqual(True,transform.checkean('123456789012345675'),'UPC')
self.assertEqual(False,transform.checkean('123456789012345670'),'UPC')
self.assertEqual(False,transform.checkean('123456789012345677'),'UPC')
if __name__ == '__main__':
botsinit.generalinit('config')
botsinit.initenginelogging()
botsinit.connect()
try:
unittest.main()
except:
pass
botsglobal.db.close()
| Python |
import unittest
import filecmp
import glob
import shutil
import os
import subprocess
import logging
import utilsunit
import bots.botslib as botslib
import bots.botsinit as botsinit
import bots.botsglobal as botsglobal
from bots.botsconfig import *
'''
plugin unitconfirm.zip
before each run: clear transactions!
'''
botssys = 'bots/botssys'
class TestMain(unittest.TestCase):
def testroutetestmdn(self):
lijst = utilsunit.getdir(os.path.join(botssys,'outfile/confirm/mdn/*'))
self.failUnless(len(lijst)==0)
nr_rows = 0
for row in botslib.query(u'''SELECT idta,confirmed,confirmidta
FROM ta
WHERE status=%(status)s
AND statust=%(statust)s
AND idroute=%(idroute)s
AND confirmtype=%(confirmtype)s
AND confirmasked=%(confirmasked)s
ORDER BY idta DESC
''',
{'status':210,'statust':DONE,'idroute':'testmdn','confirmtype':'send-email-MDN','confirmasked':True}):
nr_rows += 1
self.failUnless(row[1])
self.failUnless(row[2]!=0)
else:
self.failUnless(nr_rows==1)
nr_rows = 0
for row in botslib.query(u'''SELECT idta,confirmed,confirmidta
FROM ta
WHERE status=%(status)s
AND statust=%(statust)s
AND idroute=%(idroute)s
AND confirmtype=%(confirmtype)s
AND confirmasked=%(confirmasked)s
ORDER BY idta DESC
''',
{'status':510,'statust':DONE,'idroute':'testmdn','confirmtype':'ask-email-MDN','confirmasked':True}):
nr_rows += 1
self.failUnless(row[1])
self.failUnless(row[2]!=0)
else:
self.failUnless(nr_rows==1)
def testroutetestmdn2(self):
lijst = utilsunit.getdir(os.path.join(botssys,'outfile/confirm/mdn2/*'))
self.failUnless(len(lijst)==0)
nr_rows = 0
for row in botslib.query(u'''SELECT idta,confirmed,confirmidta
FROM ta
WHERE status=%(status)s
AND statust=%(statust)s
AND idroute=%(idroute)s
AND confirmtype=%(confirmtype)s
AND confirmasked=%(confirmasked)s
ORDER BY idta DESC
''',
{'status':510,'statust':DONE,'idroute':'testmdn2','confirmtype':'ask-email-MDN','confirmasked':True}):
nr_rows += 1
self.failUnless(not row[1])
self.failUnless(row[2]==0)
else:
self.failUnless(nr_rows==1)
def testrouteotherx12(self):
lijst = utilsunit.getdir(os.path.join(botssys,'outfile/confirm/otherx12/*'))
self.failUnless(len(lijst)==15)
def testroutetest997(self):
'''
test997 1: pickup 850*1 ask confirm 850*2 gen & send 850*2
send confirm 850*1 gen & send 997*1
test997 2: receive 997*1 confirm 850*1 gen xml*1
receive 850*2 ask confirm 850*3 gen 850*3
send confirm 850*2 gen & send 997*2
test997 3: receive 997*2 confirm 850*2 gen & send xml (to trash)
send 850*3 (to trash)
send xml (to trash)
'''
lijst = utilsunit.getdir(os.path.join(botssys,'outfile/confirm/x12/*'))
self.failUnless(len(lijst)==0)
lijst = utilsunit.getdir(os.path.join(botssys,'outfile/confirm/trash/*'))
self.failUnless(len(lijst)==6)
counter=0
for row in botslib.query(u'''SELECT idta,confirmed,confirmidta
FROM ta
WHERE status=%(status)s
AND statust=%(statust)s
AND idroute=%(idroute)s
AND confirmtype=%(confirmtype)s
AND confirmasked=%(confirmasked)s
ORDER BY idta DESC
''',
{'status':400,'statust':DONE,'idroute':'test997','confirmtype':'ask-x12-997','confirmasked':True}):
counter += 1
if counter == 1:
self.failUnless(not row[1])
self.failUnless(row[2]==0)
elif counter == 2:
self.failUnless(row[1])
self.failUnless(row[2]!=0)
else:
break
else:
self.failUnless(counter!=0)
for row in botslib.query(u'''SELECT idta,confirmed,confirmidta
FROM ta
WHERE status=%(status)s
AND statust=%(statust)s
AND idroute=%(idroute)s
AND confirmtype=%(confirmtype)s
AND confirmasked=%(confirmasked)s
ORDER BY idta DESC
''',
{'status':310,'statust':DONE,'idroute':'test997','confirmtype':'send-x12-997','confirmasked':True}):
counter += 1
if counter <= 2:
self.failUnless(row[1])
self.failUnless(row[2]!=0)
else:
break
else:
self.failUnless(counter!=0)
def testroutetestcontrl(self):
'''
test997 1: pickup ORDERS*1 ask confirm ORDERS*2 gen & send ORDERS*2
send confirm ORDERS*1 gen & send CONTRL*1
test997 2: receive CONTRL*1 confirm ORDERS*1 gen xml*1
receive ORDERS*2 ask confirm ORDERS*3 gen ORDERS*3
send confirm ORDERS*2 gen & send CONTRL*2
test997 3: receive CONTRL*2 confirm ORDERS*2 gen & send xml (to trash)
send ORDERS*3 (to trash)
send xml (to trash)
'''
lijst = utilsunit.getdir(os.path.join(botssys,'outfile/confirm/edifact/*'))
self.failUnless(len(lijst)==0)
lijst = utilsunit.getdir(os.path.join(botssys,'outfile/confirm/trash/*'))
self.failUnless(len(lijst)==6)
counter=0
for row in botslib.query(u'''SELECT idta,confirmed,confirmidta
FROM ta
WHERE status=%(status)s
AND statust=%(statust)s
AND idroute=%(idroute)s
AND confirmtype=%(confirmtype)s
AND confirmasked=%(confirmasked)s
ORDER BY idta DESC
''',
{'status':400,'statust':DONE,'idroute':'testcontrl','confirmtype':'ask-edifact-CONTRL','confirmasked':True}):
counter += 1
if counter == 1:
self.failUnless(not row[1])
self.failUnless(row[2]==0)
elif counter == 2:
self.failUnless(row[1])
self.failUnless(row[2]!=0)
else:
break
else:
self.failUnless(counter!=0)
for row in botslib.query(u'''SELECT idta,confirmed,confirmidta
FROM ta
WHERE status=%(status)s
AND statust=%(statust)s
AND idroute=%(idroute)s
AND confirmtype=%(confirmtype)s
AND confirmasked=%(confirmasked)s
ORDER BY idta DESC
''',
{'status':310,'statust':DONE,'idroute':'testcontrl','confirmtype':'send-edifact-CONTRL','confirmasked':True}):
counter += 1
if counter <= 2:
self.failUnless(row[1])
self.failUnless(row[2]!=0)
else:
break
else:
self.failUnless(counter!=0)
if __name__ == '__main__':
pythoninterpreter = 'python'
newcommand = [pythoninterpreter,'bots-engine.py',]
shutil.rmtree(os.path.join(botssys, 'outfile'),ignore_errors=True) #remove whole output directory
subprocess.call(newcommand)
botsinit.generalinit('config')
botsinit.initenginelogging()
botsinit.connect()
print '''expect:
21 files received/processed in run.
17 files without errors,
4 files with errors,
30 files send in run.
'''
unittest.main()
logging.shutdown()
botsglobal.db.close()
| Python |
import unittest
import bots.botslib as botslib
import bots.botsinit as botsinit
import bots.inmessage as inmessage
import bots.outmessage as outmessage
from bots.botsconfig import *
import utilsunit
''' plugin unitformats '''
#python 2.6 treats -0 different. in outmessage this is adapted, for inmessage: python 2.6 does this correct
testdummy={MPATH:'dummy for tests'}
class TestFormatFieldVariableOutmessage(unittest.TestCase):
def setUp(self):
self.edi = outmessage.outmessage_init(messagetype='edifact',editype='edifact')
def test_out_formatfield_var_R(self):
self.edi.ta_info['lengthnumericbare']=True
self.edi.ta_info['decimaal']='.'
tfield1 = ['TEST1','M',3,'R',True,0, 0, 'R']
# length decimals minlength format
self.assertEqual(self.edi._formatfield('',tfield1,testdummy), '','empty string')
self.assertEqual(self.edi._formatfield('1',tfield1,testdummy), '1', 'basic')
self.assertEqual(self.edi._formatfield(' 1',tfield1,testdummy), '1', 'basic')
self.assertEqual(self.edi._formatfield('1 ',tfield1,testdummy), '1', 'basic')
self.assertEqual(self.edi._formatfield('0',tfield1,testdummy), '0','zero stays zero')
self.assertEqual(self.edi._formatfield('-0',tfield1,testdummy), '-0','neg.zero stays neg.zero')
self.assertEqual(self.edi._formatfield('-0.00',tfield1,testdummy), '-0.00','')
self.assertEqual(self.edi._formatfield('-.12',tfield1,testdummy), '-0.12','no zero before dec,sign is OK')
self.assertEqual(self.edi._formatfield('123',tfield1,testdummy), '123','numeric field at max')
self.assertEqual(self.edi._formatfield('001',tfield1,testdummy), '1','leading zeroes are removed')
self.assertEqual(self.edi._formatfield('0.10',tfield1,testdummy), '0.10','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('-1.23',tfield1,testdummy), '-1.23','numeric field at max with minus and decimal sign')
self.assertEqual(self.edi._formatfield('0001',tfield1,testdummy), '1','strips leading zeroes if possobel')
self.assertEqual(self.edi._formatfield('+123',tfield1,testdummy), '123','strips leading zeroes if possobel')
self.edi.ta_info['decimaal']=','
self.assertEqual(self.edi._formatfield('1.23',tfield1,testdummy), '1,23','other dec.sig, replace')
self.edi.ta_info['decimaal']='.'
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1234',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'-1.234',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1<3',tfield1,testdummy) #wrong char
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1-3',tfield1,testdummy) #'-' in middel of number
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'123-',tfield1,testdummy) #'-' at end of number
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1,3',tfield1,testdummy) #',', where ',' is not traid sep.
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1+3',tfield1,testdummy) #'+' in middle of number (no exp)
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1E3',tfield1,testdummy) #'+' in middle of number (no exp)
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'13+',tfield1,testdummy) #'+' at end
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'0.100',tfield1,testdummy) #field too big
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'.',tfield1,testdummy) #no num
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'-',tfield1,testdummy) #no num
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'.001',tfield1,testdummy) #bots adds 0 before dec, thus too big
#~ #test filling up to min length
tfield2 = ['TEST1', 'M', 8, 'R', True, 0, 5,'R']
self.assertEqual(self.edi._formatfield('12345',tfield2,testdummy), '12345','just large enough')
self.assertEqual(self.edi._formatfield('0.1000',tfield2,testdummy), '0.1000','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('00001',tfield2,testdummy), '00001','keep leading zeroes')
self.assertEqual(self.edi._formatfield('123',tfield2,testdummy), '00123','add leading zeroes')
self.assertEqual(self.edi._formatfield('.1',tfield2,testdummy), '0000.1','add leading zeroes')
#~ #test exp
self.assertEqual(self.edi._formatfield('12E+3',tfield2,testdummy), '12000','Exponent notation is possible')
self.assertEqual(self.edi._formatfield('12E3',tfield2,testdummy), '12000','Exponent notation is possible->to std notation')
self.assertEqual(self.edi._formatfield('12e+3',tfield2,testdummy), '12000','Exponent notation is possible; e->E')
self.assertEqual(self.edi._formatfield('12e3',tfield2,testdummy), '12000','Exponent notation is possible; e->E')
self.assertEqual(self.edi._formatfield('12345E+3',tfield2,testdummy), '12345000','do not count + and E')
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'12345678E+3',tfield2,testdummy) #too big with exp
tfield3 = ['TEST1', 'M', 8, 'R', True, 3, 5,'R']
#~ print '\n>>>',self.edi._formatfield('12E-3',tfield3,testdummy)
#~ self.assertEqual(self.edi._formatfield('12E-3',tfield3,testdummy), '00.012','Exponent notation is possible')
#~ self.assertEqual(self.edi._formatfield('12e-3',tfield2,testdummy), '00.012','Exponent notation is possible; e->E')
#~ self.assertEqual(self.edi._formatfield('12345678E-3',tfield2,testdummy), '12345.678','do not count + and E')
#~ self.assertEqual(self.edi._formatfield('12345678E-7',tfield2,testdummy), '1.2345678','do not count + and E')
#~ self.assertEqual(self.edi._formatfield('123456E-7',tfield2,testdummy), '0.0123456','do not count + and E')
#~ self.assertEqual(self.edi._formatfield('1234567E-7',tfield2,testdummy), '0.1234567','do not count + and E')
#~ self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'12345678E-8',tfield2,testdummy) #gets 0.12345678, is too big
#~ self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'12345678E+3',tfield2,testdummy) #too big with exp
tfield4 = ['TEST1', 'M', 80, 'R', True, 3, 0,'R']
self.assertEqual(self.edi._formatfield('12345678901234560',tfield4,testdummy), '12345678901234560','lot of digits')
#test for lentgh checks if:
self.edi.ta_info['lengthnumericbare']=False
self.assertEqual(self.edi._formatfield('-1.45',tfield2,testdummy), '-1.45','just large enough')
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'-12345678',tfield2,testdummy) #field too large
def test_out_formatfield_var_N(self):
self.edi.ta_info['decimaal']='.'
self.edi.ta_info['lengthnumericbare']=True
tfield1 = ['TEST1','M',5,'N',True,2, 0, 'N']
# length decimals minlength format
self.assertEqual(self.edi._formatfield('',tfield1,testdummy), '','empty string')
self.assertEqual(self.edi._formatfield('1',tfield1,testdummy), '1.00', 'basic')
self.assertEqual(self.edi._formatfield(' 1',tfield1,testdummy), '1.00', 'basic')
self.assertEqual(self.edi._formatfield('1 ',tfield1,testdummy), '1.00', 'basic')
self.assertEqual(self.edi._formatfield('0',tfield1,testdummy), '0.00','zero stays zero')
self.assertEqual(self.edi._formatfield('-0',tfield1,testdummy), '-0.00','neg.zero stays neg.zero')
self.assertEqual(self.edi._formatfield('-0.00',tfield1,testdummy), '-0.00','')
self.assertEqual(self.edi._formatfield('-0.001',tfield1,testdummy), '-0.00','')
self.assertEqual(self.edi._formatfield('-.12',tfield1,testdummy), '-0.12','no zero before dec,sign is OK')
self.assertEqual(self.edi._formatfield('123',tfield1,testdummy), '123.00','numeric field at max')
self.assertEqual(self.edi._formatfield('001',tfield1,testdummy), '1.00','leading zeroes are removed')
self.assertEqual(self.edi._formatfield('0.10',tfield1,testdummy), '0.10','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('123.1049',tfield1,testdummy), '123.10','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('-1.23',tfield1,testdummy), '-1.23','numeric field at max with minus and decimal sign')
self.assertEqual(self.edi._formatfield('0001',tfield1,testdummy), '1.00','strips leading zeroes if possobel')
self.assertEqual(self.edi._formatfield('+123',tfield1,testdummy), '123.00','strips leading zeroes if possobel')
self.edi.ta_info['decimaal']=','
self.assertEqual(self.edi._formatfield('1.23',tfield1,testdummy), '1,23','other dec.sig, replace')
self.edi.ta_info['decimaal']='.'
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1234',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'-1234.56',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1<3',tfield1,testdummy) #wrong char
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1-3',tfield1,testdummy) #'-' in middel of number
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'123-',tfield1,testdummy) #'-' at end of number
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1,3',tfield1,testdummy) #',', where ',' is not traid sep.
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1+3',tfield1,testdummy) #'+' in middle of number (no exp)
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1E3',tfield1,testdummy) #'+' in middle of number (no exp)
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'13+',tfield1,testdummy) #'+' at end
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1234.100',tfield1,testdummy) #field too big
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'.',tfield1,testdummy) #no num
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'-',tfield1,testdummy) #no num
# #test filling up to min length
tfield23 = ['TEST1', 'M', 8, 'N', True, 0, 5,'N']
#~ print self.edi._formatfield('12345.5',tfield23,testdummy)
self.assertEqual(self.edi._formatfield('12345.5',tfield23,testdummy), '12346','just large enough')
tfield2 = ['TEST1', 'M', 8, 'N', True, 2, 5,'N']
self.assertEqual(self.edi._formatfield('123.45',tfield2,testdummy), '123.45','just large enough')
self.assertEqual(self.edi._formatfield('123.4549',tfield2,testdummy), '123.45','just large enough')
#~ print self.edi._formatfield('123.455',tfield2,testdummy)
self.assertEqual(self.edi._formatfield('123.455',tfield2,testdummy), '123.46','just large enough')
self.assertEqual(self.edi._formatfield('0.1000',tfield2,testdummy), '000.10','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('00001',tfield2,testdummy), '001.00','keep leading zeroes')
self.assertEqual(self.edi._formatfield('12',tfield2,testdummy), '012.00','add leading zeroes')
self.assertEqual(self.edi._formatfield('.1',tfield2,testdummy), '000.10','add leading zeroes')
#test exp; bots tries to convert to normal
self.assertEqual(self.edi._formatfield('178E+3',tfield2,testdummy), '178000.00','add leading zeroes')
self.assertEqual(self.edi._formatfield('-178E+3',tfield2,testdummy), '-178000.00','add leading zeroes')
self.assertEqual(self.edi._formatfield('-178e-3',tfield2,testdummy), '-000.18','add leading zeroes')
self.assertEqual(self.edi._formatfield('-178e-5',tfield2,testdummy), '-000.00','add leading zeroes')
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'178E+4',tfield2,testdummy) #too big with exp
tfield4 = ['TEST1', 'M', 80, 'N', True, 3, 0,'N']
self.assertEqual(self.edi._formatfield('12345678901234560',tfield4,testdummy), '12345678901234560.000','lot of digits')
self.assertEqual(self.edi._formatfield('1234567890123456789012345',tfield4,testdummy), '1234567890123456789012345.000','lot of digits')
def test_out_formatfield_var_I(self):
self.edi.ta_info['lengthnumericbare']=True
self.edi.ta_info['decimaal']='.'
tfield1 = ['TEST1','M',5,'I',True,2, 0, 'I']
# length decimals minlength format
self.assertEqual(self.edi._formatfield('',tfield1,testdummy), '','empty string')
self.assertEqual(self.edi._formatfield('1',tfield1,testdummy), '100', 'basic')
self.assertEqual(self.edi._formatfield(' 1',tfield1,testdummy), '100', 'basic')
self.assertEqual(self.edi._formatfield('1 ',tfield1,testdummy), '100', 'basic')
self.assertEqual(self.edi._formatfield('0',tfield1,testdummy), '0','zero stays zero')
self.assertEqual(self.edi._formatfield('-0',tfield1,testdummy), '-0','neg.zero stays neg.zero')
self.assertEqual(self.edi._formatfield('-0.00',tfield1,testdummy), '-0','')
self.assertEqual(self.edi._formatfield('-0.001',tfield1,testdummy), '-0','')
self.assertEqual(self.edi._formatfield('-.12',tfield1,testdummy), '-12','no zero before dec,sign is OK') #TODO: puts ) in front
self.assertEqual(self.edi._formatfield('123',tfield1,testdummy), '12300','numeric field at max')
self.assertEqual(self.edi._formatfield('001',tfield1,testdummy), '100','leading zeroes are removed')
self.assertEqual(self.edi._formatfield('0.10',tfield1,testdummy), '10','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('123.1049',tfield1,testdummy), '12310','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('-1.23',tfield1,testdummy), '-123','numeric field at max with minus and decimal sign')
self.assertEqual(self.edi._formatfield('0001',tfield1,testdummy), '100','strips leading zeroes if possobel')
self.assertEqual(self.edi._formatfield('+123',tfield1,testdummy), '12300','strips leading zeroes if possobel')
self.edi.ta_info['decimaal']=','
self.assertEqual(self.edi._formatfield('1.23',tfield1,testdummy), '123','other dec.sig, replace')
self.edi.ta_info['decimaal']='.'
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1234',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'-1234.56',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1<3',tfield1,testdummy) #wrong char
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1-3',tfield1,testdummy) #'-' in middel of number
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'123-',tfield1,testdummy) #'-' at end of number
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1,3',tfield1,testdummy) #',', where ',' is not traid sep.
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1+3',tfield1,testdummy) #'+' in middle of number (no exp)
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1E3',tfield1,testdummy) #'+' in middle of number (no exp)
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'13+',tfield1,testdummy) #'+' at end
self.assertEqual(self.edi._formatfield('+13',tfield1,testdummy), '1300','other dec.sig, replace')
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1+3',tfield1,testdummy) #'+' in middle of number
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1234.100',tfield1,testdummy) #field too big
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'.',tfield1,testdummy) #no num
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'-',tfield1,testdummy) #no num
#~ #test filling up to min length
tfield2 = ['TEST1', 'M', 8, 'I', True, 2, 5,'I']
self.assertEqual(self.edi._formatfield('123.45',tfield2,testdummy), '12345','just large enough')
self.assertEqual(self.edi._formatfield('123.4549',tfield2,testdummy), '12345','just large enough')
self.assertEqual(self.edi._formatfield('123.455',tfield2,testdummy), '12346','just large enough')
self.assertEqual(self.edi._formatfield('0.1000',tfield2,testdummy), '00010','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('00001',tfield2,testdummy), '00100','keep leading zeroes')
self.assertEqual(self.edi._formatfield('12',tfield2,testdummy), '01200','add leading zeroes')
self.assertEqual(self.edi._formatfield('.1',tfield2,testdummy), '00010','add leading zeroes')
#test exp; bots tries to convert to normal
self.assertEqual(self.edi._formatfield('178E+3',tfield2,testdummy), '17800000','add leading zeroes')
self.assertEqual(self.edi._formatfield('-178E+3',tfield2,testdummy), '-17800000','add leading zeroes')
self.assertEqual(self.edi._formatfield('-178e-3',tfield2,testdummy), '-00018','add leading zeroes')
self.assertEqual(self.edi._formatfield('-178e-5',tfield2,testdummy), '-00000','add leading zeroes')
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'178E+4',tfield2,testdummy) #too big with exp
tfield4 = ['TEST1', 'M', 80, 'I', True, 3, 0,'I']
self.assertEqual(self.edi._formatfield('123456789012340',tfield4,testdummy), '123456789012340000','lot of digits')
def test_out_formatfield_var_D(self):
tfield1 = ['TEST1', 'M', 20, 'D', True, 0, 0,'D']
# length decimals minlength
self.assertEqual(self.edi._formatfield('20071001',tfield1,testdummy), '20071001','basic')
self.assertEqual(self.edi._formatfield('071001',tfield1,testdummy), '071001','basic')
self.assertEqual(self.edi._formatfield('99991001',tfield1,testdummy), '99991001','max year')
self.assertEqual(self.edi._formatfield('00011001',tfield1,testdummy), '00011001','min year')
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'2007093112',tfield1,testdummy) #too long
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'20070931',tfield1,testdummy) #no valid date
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'-0070931',tfield1,testdummy) #no valid date
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'70931',tfield1,testdummy) #too short
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'0931',tfield1,testdummy) #too short
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'0931BC',tfield1,testdummy) #alfanum
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'OOOOBC',tfield1,testdummy) #alfanum
def test_out_formatfield_var_T(self):
tfield1 = ['TEST1', 'M', 10, 'T', True, 0, 0,'T']
# length decimals minlength
self.assertEqual(self.edi._formatfield('2359',tfield1,testdummy), '2359','basic')
self.assertEqual(self.edi._formatfield('0000',tfield1,testdummy), '0000','basic')
self.assertEqual(self.edi._formatfield('000000',tfield1,testdummy), '000000','basic')
self.assertEqual(self.edi._formatfield('230000',tfield1,testdummy), '230000','basic')
self.assertEqual(self.edi._formatfield('235959',tfield1,testdummy), '235959','basic')
self.assertEqual(self.edi._formatfield('123456',tfield1,testdummy), '123456','basic')
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'12345678',tfield1,testdummy) #no valid time
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'240001',tfield1,testdummy) #no valid time
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'126101',tfield1,testdummy) #no valid time
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'120062',tfield1,testdummy) #no valid time - python allows 61 secnds?
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'240000',tfield1,testdummy) #no valid time
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'250001',tfield1,testdummy) #no valid time
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'-12000',tfield1,testdummy) #no valid time
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'120',tfield1,testdummy) #no valid time
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'0931233',tfield1,testdummy) #too short
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'11PM',tfield1,testdummy) #alfanum
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'TIME',tfield1,testdummy) #alfanum
tfield2 = ['TEST1', 'M', 4, 'T', True, 0, 4,'T']
# length decimals minlength
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'230001',tfield2,testdummy) #time too long
tfield3 = ['TEST1', 'M', 6, 'T', True, 0, 6,'T']
# length decimals minlength
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'2300',tfield3,testdummy) #time too short
def test_out_formatfield_var_A(self):
tfield1 = ['TEST1', 'M', 5, 'A', True, 0, 0,'A']
# length decimals minlength
self.assertEqual(self.edi._formatfield('abcde',tfield1,testdummy), 'abcde','basic')
self.assertEqual(self.edi._formatfield('',tfield1,testdummy), '','basic')
self.assertEqual(self.edi._formatfield('a b',tfield1,testdummy), 'a b','basic')
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'abcdef',tfield1,testdummy) #no valid date
tfield1 = ['TEST1', 'M', 5, 'A', True, 0, 2,'A']
# length decimals minlength
self.assertEqual(self.edi._formatfield('abcde',tfield1,testdummy), 'abcde','basic')
self.assertEqual(self.edi._formatfield('a b',tfield1,testdummy), 'a b','basic')
self.assertEqual(self.edi._formatfield('aa',tfield1,testdummy), 'aa','basic')
self.assertEqual(self.edi._formatfield('aaa',tfield1,testdummy), 'aaa','basic')
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'a',tfield1,testdummy) #field too small
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,' ',tfield1,testdummy) #field too small
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'',tfield1,testdummy) #field too small
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'abcdef',tfield1,testdummy) #no valid date
class TestFormatFieldFixedOutmessage(unittest.TestCase):
def setUp(self):
self.edi = outmessage.outmessage_init(editype='fixed',messagetype='ordersfixed')
def test_out_formatfield_fixedR(self):
self.edi.ta_info['lengthnumericbare']=False
self.edi.ta_info['decimaal']='.'
tfield1 = ['TEST1','M',3,'R',True,0, 3, 'R']
# length decimals minlength format
self.assertEqual(self.edi._formatfield('',tfield1,testdummy), '000','empty string')
self.assertEqual(self.edi._formatfield('1',tfield1,testdummy), '001', 'basic')
self.assertEqual(self.edi._formatfield(' 1',tfield1,testdummy), '001', 'basic')
self.assertEqual(self.edi._formatfield('1 ',tfield1,testdummy), '001', 'basic')
self.assertEqual(self.edi._formatfield('0',tfield1,testdummy), '000','zero stays zero')
self.assertEqual(self.edi._formatfield('-0',tfield1,testdummy), '-00','neg.zero stays neg.zero')
tfield3 = ['TEST1','M',5,'R',True,2, 3, 'R']
self.assertEqual(self.edi._formatfield('-0.00',tfield3,testdummy), '-0.00','')
self.assertEqual(self.edi._formatfield('0.10',tfield3,testdummy), '0.10','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('123',tfield1,testdummy), '123','numeric field at max')
self.assertEqual(self.edi._formatfield('001',tfield1,testdummy), '001','leading zeroes are removed')
self.assertEqual(self.edi._formatfield('0001',tfield1,testdummy), '001','strips leading zeroes if possobel')
self.assertEqual(self.edi._formatfield('+123',tfield1,testdummy), '123','strips leading zeroes if possobel')
self.edi.ta_info['decimaal']=','
self.assertEqual(self.edi._formatfield('1.2',tfield1,testdummy), '1,2','other dec.sig, replace')
self.edi.ta_info['decimaal']='.'
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'.12',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'-.12',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1234',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'-1.234',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1<3',tfield1,testdummy) #wrong char
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1-3',tfield1,testdummy) #'-' in middel of number
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'123-',tfield1,testdummy) #'-' at end of number
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1,3',tfield1,testdummy) #',', where ',' is not traid sep.
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1+3',tfield1,testdummy) #'+' in middle of number (no exp)
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1E3',tfield1,testdummy) #'+' in middle of number (no exp)
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'13+',tfield1,testdummy) #'+' at end
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1+3',tfield1,testdummy) #'+' in middle of number
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'0.100',tfield1,testdummy) #field too big
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'.',tfield1,testdummy) #no num
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'-',tfield1,testdummy) #no num
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'.001',tfield1,testdummy) #bots adds 0 before dec, thus too big
# #test filling up to min length
tfield2 = ['TEST1', 'M', 8, 'R', True, 0, 8,'R']
self.assertEqual(self.edi._formatfield('12345',tfield2,testdummy), '00012345','just large enough')
self.assertEqual(self.edi._formatfield('0.1000',tfield2,testdummy), '000.1000','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('00001',tfield2,testdummy), '00000001','keep leading zeroes')
self.assertEqual(self.edi._formatfield('123',tfield2,testdummy), '00000123','add leading zeroes')
self.assertEqual(self.edi._formatfield('.1',tfield2,testdummy), '000000.1','add leading zeroes')
self.assertEqual(self.edi._formatfield('-1.23',tfield2,testdummy), '-0001.23','numeric field at max with minus and decimal sign')
#test exp
self.assertEqual(self.edi._formatfield('12E+3',tfield2,testdummy), '00012000','Exponent notation is possible')
self.assertEqual(self.edi._formatfield('12E3',tfield2,testdummy), '00012000','Exponent notation is possible->to std notation')
self.assertEqual(self.edi._formatfield('12e+3',tfield2,testdummy), '00012000','Exponent notation is possible; e->E')
self.assertEqual(self.edi._formatfield('12e3',tfield2,testdummy), '00012000','Exponent notation is possible; e->E')
self.assertEqual(self.edi._formatfield('4567E+3',tfield2,testdummy), '04567000','do not count + and E')
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'12345678E+3',tfield2,testdummy) #too big with exp
#~ #print '>>',self.edi._formatfield('12E-3',tfield2,testdummy)
#~ self.assertEqual(self.edi._formatfield('12E-3',tfield2,testdummy), '0000.012','Exponent notation is possible')
#~ self.assertEqual(self.edi._formatfield('12e-3',tfield2,testdummy), '0000.012','Exponent notation is possible; e->E')
#~ self.assertEqual(self.edi._formatfield('1234567E-3',tfield2,testdummy), '1234.567','do not count + and E')
#~ self.assertEqual(self.edi._formatfield('1234567E-6',tfield2,testdummy), '1.234567','do not count + and E')
#~ self.assertEqual(self.edi._formatfield('123456E-6',tfield2,testdummy), '0.123456','do not count + and E')
#~ self.assertEqual(self.edi._formatfield('-12345E-5',tfield2,testdummy), '-0.12345','do not count + and E')
#~ self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'12345678E-8',tfield2,testdummy) #gets 0.12345678, is too big
#~ self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'12345678E+3',tfield2,testdummy) #too big with exp
tfield4 = ['TEST1', 'M', 30, 'R', True, 3, 30,'R']
self.assertEqual(self.edi._formatfield('12345678901234560',tfield4,testdummy), '000000000000012345678901234560','lot of digits')
tfield5 = ['TEST1','M',4,'R',True,2, 4, 'R']
self.assertEqual(self.edi._formatfield('0.00',tfield5,testdummy), '0.00','lot of digits')
tfield6 = ['TEST1','M',5,'R',True,2, 5, 'R']
self.assertEqual(self.edi._formatfield('12.45',tfield6,testdummy), '12.45','lot of digits')
def test_out_formatfield_fixedRL(self):
self.edi.ta_info['lengthnumericbare']=False
self.edi.ta_info['decimaal']='.'
tfield1 = ['TEST1','M',3,'RL',True,0, 3, 'R']
# length decimals minlength format
self.assertEqual(self.edi._formatfield('',tfield1,testdummy), '0 ','empty string')
self.assertEqual(self.edi._formatfield('1',tfield1,testdummy), '1 ', 'basic')
self.assertEqual(self.edi._formatfield(' 1',tfield1,testdummy), '1 ', 'basic')
self.assertEqual(self.edi._formatfield('1 ',tfield1,testdummy), '1 ', 'basic')
self.assertEqual(self.edi._formatfield('0',tfield1,testdummy), '0 ','zero stays zero')
self.assertEqual(self.edi._formatfield('-0',tfield1,testdummy), '-0 ','neg.zero stays neg.zero')
tfield3 = ['TEST1','M',5,'RL',True,2, 3, 'R']
self.assertEqual(self.edi._formatfield('-0.00',tfield3,testdummy), '-0.00','')
self.assertEqual(self.edi._formatfield('0.10',tfield3,testdummy), '0.10','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('123',tfield1,testdummy), '123','numeric field at max')
self.assertEqual(self.edi._formatfield('001',tfield1,testdummy), '1 ','leading zeroes are removed')
self.assertEqual(self.edi._formatfield('0001',tfield1,testdummy), '1 ','strips leading zeroes if possobel')
self.assertEqual(self.edi._formatfield('+123',tfield1,testdummy), '123','strips leading zeroes if possobel')
self.edi.ta_info['decimaal']=','
self.assertEqual(self.edi._formatfield('1.2',tfield1,testdummy), '1,2','other dec.sig, replace')
self.edi.ta_info['decimaal']='.'
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'.12',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'-.12',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1234',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'-1.234',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1<3',tfield1,testdummy) #wrong char
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1-3',tfield1,testdummy) #'-' in middel of number
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'123-',tfield1,testdummy) #'-' at end of number
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1,3',tfield1,testdummy) #',', where ',' is not traid sep.
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1+3',tfield1,testdummy) #'+' in middle of number (no exp)
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1E3',tfield1,testdummy) #'+' in middle of number (no exp)
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'13+',tfield1,testdummy) #'+' at end
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1+3',tfield1,testdummy) #'+' in middle of number
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'0.100',tfield1,testdummy) #field too big
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'.',tfield1,testdummy) #no num
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'-',tfield1,testdummy) #no num
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'.001',tfield1,testdummy) #bots adds 0 before dec, thus too big
# #test filling up to min length
tfield2 = ['TEST1', 'M', 8, 'RL', True, 0, 8,'R']
self.assertEqual(self.edi._formatfield('12345',tfield2,testdummy), '12345 ','just large enough')
self.assertEqual(self.edi._formatfield('0.1000',tfield2,testdummy), '0.1000 ','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('00001',tfield2,testdummy), '1 ','keep leading zeroes')
self.assertEqual(self.edi._formatfield('123',tfield2,testdummy), '123 ','add leading zeroes')
self.assertEqual(self.edi._formatfield('.1',tfield2,testdummy), '0.1 ','add leading zeroes')
self.assertEqual(self.edi._formatfield('-1.23',tfield2,testdummy), '-1.23 ','numeric field at max with minus and decimal sign')
#test exp
self.assertEqual(self.edi._formatfield('12E+3',tfield2,testdummy), '12000 ','Exponent notation is possible')
self.assertEqual(self.edi._formatfield('12E3',tfield2,testdummy), '12000 ','Exponent notation is possible->to std notation')
self.assertEqual(self.edi._formatfield('12e+3',tfield2,testdummy), '12000 ','Exponent notation is possible; e->E')
self.assertEqual(self.edi._formatfield('12e3',tfield2,testdummy), '12000 ','Exponent notation is possible; e->E')
self.assertEqual(self.edi._formatfield('4567E+3',tfield2,testdummy), '4567000 ','do not count + and E')
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'12345678E+3',tfield2,testdummy) #too big with exp
#~ #print '>>',self.edi._formatfield('12E-3',tfield2,testdummy)
#~ self.assertEqual(self.edi._formatfield('12E-3',tfield2,testdummy), '0000.012','Exponent notation is possible')
#~ self.assertEqual(self.edi._formatfield('12e-3',tfield2,testdummy), '0000.012','Exponent notation is possible; e->E')
#~ self.assertEqual(self.edi._formatfield('1234567E-3',tfield2,testdummy), '1234.567','do not count + and E')
#~ self.assertEqual(self.edi._formatfield('1234567E-6',tfield2,testdummy), '1.234567','do not count + and E')
#~ self.assertEqual(self.edi._formatfield('123456E-6',tfield2,testdummy), '0.123456','do not count + and E')
#~ self.assertEqual(self.edi._formatfield('-12345E-5',tfield2,testdummy), '-0.12345','do not count + and E')
#~ self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'12345678E-8',tfield2,testdummy) #gets 0.12345678, is too big
#~ self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'12345678E+3',tfield2,testdummy) #too big with exp
tfield4 = ['TEST1', 'M', 30, 'RL', True, 3, 30,'R']
self.assertEqual(self.edi._formatfield('12345678901234560',tfield4,testdummy), '12345678901234560 ','lot of digits')
tfield5 = ['TEST1','M',4,'RL',True,2, 4, 'N']
self.assertEqual(self.edi._formatfield('0.00',tfield5,testdummy), '0.00','lot of digits')
tfield6 = ['TEST1','M',5,'RL',True,2, 5, 'N']
self.assertEqual(self.edi._formatfield('12.45',tfield6,testdummy), '12.45','lot of digits')
def test_out_formatfield_fixedRR(self):
self.edi.ta_info['lengthnumericbare']=False
self.edi.ta_info['decimaal']='.'
tfield1 = ['TEST1','M',3,'RR',True,0, 3, 'R']
# length decimals minlength format
self.assertEqual(self.edi._formatfield('',tfield1,testdummy), ' 0','empty string')
self.assertEqual(self.edi._formatfield('1',tfield1,testdummy), ' 1', 'basic')
self.assertEqual(self.edi._formatfield(' 1',tfield1,testdummy), ' 1', 'basic')
self.assertEqual(self.edi._formatfield('1 ',tfield1,testdummy), ' 1', 'basic')
self.assertEqual(self.edi._formatfield('0',tfield1,testdummy), ' 0','zero stays zero')
self.assertEqual(self.edi._formatfield('-0',tfield1,testdummy), ' -0','neg.zero stays neg.zero')
tfield3 = ['TEST1','M',5,'RR',True,2, 3, 'R']
self.assertEqual(self.edi._formatfield('-0.00',tfield3,testdummy), '-0.00','')
self.assertEqual(self.edi._formatfield('0.10',tfield3,testdummy), '0.10','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('123',tfield1,testdummy), '123','numeric field at max')
self.assertEqual(self.edi._formatfield('001',tfield1,testdummy), ' 1','leading zeroes are removed')
self.assertEqual(self.edi._formatfield('0001',tfield1,testdummy), ' 1','strips leading zeroes if possobel')
self.assertEqual(self.edi._formatfield('+123',tfield1,testdummy), '123','strips leading zeroes if possobel')
self.edi.ta_info['decimaal']=','
self.assertEqual(self.edi._formatfield('1.2',tfield1,testdummy), '1,2','other dec.sig, replace')
self.edi.ta_info['decimaal']='.'
self.assertRaises(botslib.OutMessageError,self.edi._formatfield, '.12',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield, '-.12',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield, '1234',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield, '-1.234',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield, '1<3',tfield1,testdummy) #wrong char
self.assertRaises(botslib.OutMessageError,self.edi._formatfield, '1-3',tfield1,testdummy) #'-' in middel of number
self.assertRaises(botslib.OutMessageError,self.edi._formatfield, '123-',tfield1,testdummy) #'-' at end of number
self.assertRaises(botslib.OutMessageError,self.edi._formatfield, '1,3',tfield1,testdummy) #',', where ',' is not traid sep.
self.assertRaises(botslib.OutMessageError,self.edi._formatfield, '1+3',tfield1,testdummy) #'+' in middle of number (no exp)
self.assertRaises(botslib.OutMessageError,self.edi._formatfield, '1E3',tfield1,testdummy) #'+' in middle of number (no exp)
self.assertRaises(botslib.OutMessageError,self.edi._formatfield, '13+',tfield1,testdummy) #'+' at end
self.assertRaises(botslib.OutMessageError,self.edi._formatfield, '1+3',tfield1,testdummy) #'+' in middle of number
self.assertRaises(botslib.OutMessageError,self.edi._formatfield, '0.100',tfield1,testdummy) #field too big
self.assertRaises(botslib.OutMessageError,self.edi._formatfield, '.',tfield1,testdummy) #no num
self.assertRaises(botslib.OutMessageError,self.edi._formatfield, '-',tfield1,testdummy) #no num
self.assertRaises(botslib.OutMessageError,self.edi._formatfield, '.001',tfield1,testdummy) #bots adds 0 before dec, thus too big
# #test filling up to min length
tfield2 = ['TEST1', 'M', 8, 'RR', True, 0, 8,'R']
self.assertEqual(self.edi._formatfield('12345',tfield2,testdummy), ' 12345','just large enough')
self.assertEqual(self.edi._formatfield('0.1000',tfield2,testdummy), ' 0.1000','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('00001',tfield2,testdummy), ' 1','keep leading zeroes')
self.assertEqual(self.edi._formatfield('123',tfield2,testdummy), ' 123','add leading zeroes')
self.assertEqual(self.edi._formatfield('.1',tfield2,testdummy), ' 0.1','add leading zeroes')
self.assertEqual(self.edi._formatfield('-1.23',tfield2,testdummy), ' -1.23','numeric field at max with minus and decimal sign')
#test exp
self.assertEqual(self.edi._formatfield('12E+3',tfield2,testdummy), ' 12000','Exponent notation is possible')
self.assertEqual(self.edi._formatfield('12E3',tfield2,testdummy), ' 12000','Exponent notation is possible->to std notation')
self.assertEqual(self.edi._formatfield('12e+3',tfield2,testdummy), ' 12000','Exponent notation is possible; e->E')
self.assertEqual(self.edi._formatfield('12e3',tfield2,testdummy), ' 12000','Exponent notation is possible; e->E')
self.assertEqual(self.edi._formatfield('4567E+3',tfield2,testdummy), ' 4567000','do not count + and E')
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'12345678E+3',tfield2,testdummy) #too big with exp
#~ #print '>>',self.edi._formatfield('12E-3',tfield2,testdummy)
#~ self.assertEqual(self.edi._formatfield('12E-3',tfield2,testdummy), '0000.012','Exponent notation is possible')
#~ self.assertEqual(self.edi._formatfield('12e-3',tfield2,testdummy), '0000.012','Exponent notation is possible; e->E')
#~ self.assertEqual(self.edi._formatfield('1234567E-3',tfield2,testdummy), '1234.567','do not count + and E')
#~ self.assertEqual(self.edi._formatfield('1234567E-6',tfield2,testdummy), '1.234567','do not count + and E')
#~ self.assertEqual(self.edi._formatfield('123456E-6',tfield2,testdummy), '0.123456','do not count + and E')
#~ self.assertEqual(self.edi._formatfield('-12345E-5',tfield2,testdummy), '-0.12345','do not count + and E')
#~ self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'12345678E-8',tfield2,testdummy) #gets 0.12345678, is too big
#~ self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'12345678E+3',tfield2,testdummy) #too big with exp
tfield4 = ['TEST1', 'M', 30, 'RR', True, 3, 30,'R']
self.assertEqual(self.edi._formatfield('12345678901234560',tfield4,testdummy), ' 12345678901234560','lot of digits')
tfield5 = ['TEST1','M',4,'RR',True,2, 4, 'N']
self.assertEqual(self.edi._formatfield('0.00',tfield5,testdummy), '0.00','lot of digits')
tfield6 = ['TEST1','M',5,'RR',True,2, 5, 'N']
self.assertEqual(self.edi._formatfield('12.45',tfield6,testdummy), '12.45','lot of digits')
def test_out_formatfield_fixedN(self):
self.edi.ta_info['decimaal']='.'
self.edi.ta_info['lengthnumericbare']=False
tfield1 = ['TEST1','M',5,'N',True,2, 5, 'N']
# length decimals minlength format
self.assertEqual(self.edi._formatfield('',tfield1,testdummy), '00.00','empty string')
self.assertEqual(self.edi._formatfield('1',tfield1,testdummy), '01.00', 'basic')
self.assertEqual(self.edi._formatfield(' 1',tfield1,testdummy), '01.00', 'basic')
self.assertEqual(self.edi._formatfield('1 ',tfield1,testdummy), '01.00', 'basic')
self.assertEqual(self.edi._formatfield('0',tfield1,testdummy), '00.00','zero stays zero')
self.assertEqual(self.edi._formatfield('-0',tfield1,testdummy), '-0.00','neg.zero stays neg.zero')
self.assertEqual(self.edi._formatfield('-0.00',tfield1,testdummy), '-0.00','')
self.assertEqual(self.edi._formatfield('-0.001',tfield1,testdummy), '-0.00','')
self.assertEqual(self.edi._formatfield('-.12',tfield1,testdummy), '-0.12','no zero before dec,sign is OK')
self.assertEqual(self.edi._formatfield('001',tfield1,testdummy), '01.00','leading zeroes are removed')
self.assertEqual(self.edi._formatfield('0.10',tfield1,testdummy), '00.10','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('12.1049',tfield1,testdummy), '12.10','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('-1.23',tfield1,testdummy), '-1.23','numeric field at max with minus and decimal sign')
self.assertEqual(self.edi._formatfield('0001',tfield1,testdummy), '01.00','strips leading zeroes if possobel')
self.assertEqual(self.edi._formatfield('+13',tfield1,testdummy), '13.00','strips leading zeroes if possobel')
self.edi.ta_info['decimaal']=','
self.assertEqual(self.edi._formatfield('1.23',tfield1,testdummy), '01,23','other dec.sig, replace')
self.edi.ta_info['decimaal']='.'
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'123.1049',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'123',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1234',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'-1234.56',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1<3',tfield1,testdummy) #wrong char
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1-3',tfield1,testdummy) #'-' in middel of number
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'123-',tfield1,testdummy) #'-' at end of number
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1,3',tfield1,testdummy) #',', where ',' is not traid sep.
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1+3',tfield1,testdummy) #'+' in middle of number (no exp)
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1E3',tfield1,testdummy) #'+' in middle of number (no exp)
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'13+',tfield1,testdummy) #'+' at end
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1234.100',tfield1,testdummy) #field too big
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'.',tfield1,testdummy) #no num
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'-',tfield1,testdummy) #no num
# #test filling up to min length
tfield2 = ['TEST1', 'M', 8, 'N', True, 2, 8,'N']
self.assertEqual(self.edi._formatfield('123.45',tfield2,testdummy), '00123.45','just large enough')
self.assertEqual(self.edi._formatfield('123.4549',tfield2,testdummy), '00123.45','just large enough')
self.assertEqual(self.edi._formatfield('123.455',tfield2,testdummy), '00123.46','just large enough')
self.assertEqual(self.edi._formatfield('0.1000',tfield2,testdummy), '00000.10','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('00001',tfield2,testdummy), '00001.00','keep leading zeroes')
self.assertEqual(self.edi._formatfield('12',tfield2,testdummy), '00012.00','add leading zeroes')
self.assertEqual(self.edi._formatfield('.1',tfield2,testdummy), '00000.10','add leading zeroes')
#test exp; bots tries to convert to normal
self.assertEqual(self.edi._formatfield('78E+3',tfield2,testdummy), '78000.00','add leading zeroes')
self.assertEqual(self.edi._formatfield('-8E+3',tfield2,testdummy), '-8000.00','add leading zeroes')
self.assertEqual(self.edi._formatfield('-178e-3',tfield2,testdummy), '-0000.18','add leading zeroes')
self.assertEqual(self.edi._formatfield('-178e-5',tfield2,testdummy), '-0000.00','add leading zeroes')
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'178E+4',tfield2,testdummy) #too big with exp
tfield4 = ['TEST1', 'M', 30, 'N', True, 3, 30,'N']
self.assertEqual(self.edi._formatfield('1234567890123456',tfield4,testdummy), '00000000001234567890123456.000','lot of digits')
#test N format, zero decimals
tfield7 = ['TEST1', 'M', 5, 'N', True, 0, 5, 'N']
# length decimals minlength format
self.assertEqual(self.edi._formatfield('12345',tfield7,testdummy), '12345','')
self.assertEqual(self.edi._formatfield('1.234',tfield7,testdummy), '00001','')
self.assertEqual(self.edi._formatfield('123.4',tfield7,testdummy), '00123','')
self.assertEqual(self.edi._formatfield('0.0',tfield7,testdummy), '00000','')
def test_out_formatfield_fixedNL(self):
self.edi.ta_info['decimaal']='.'
self.edi.ta_info['lengthnumericbare']=False
tfield1 = ['TEST1','M',5,'NL',True,2, 5, 'N']
# length decimals minlength format
self.assertEqual(self.edi._formatfield('',tfield1,testdummy), '0.00 ','empty string')
self.assertEqual(self.edi._formatfield('1',tfield1,testdummy), '1.00 ', 'basic')
self.assertEqual(self.edi._formatfield(' 1',tfield1,testdummy), '1.00 ', 'basic')
self.assertEqual(self.edi._formatfield('1 ',tfield1,testdummy), '1.00 ', 'basic')
self.assertEqual(self.edi._formatfield('0',tfield1,testdummy), '0.00 ','zero stays zero')
self.assertEqual(self.edi._formatfield('-0',tfield1,testdummy), '-0.00','neg.zero stays neg.zero')
self.assertEqual(self.edi._formatfield('-0.00',tfield1,testdummy), '-0.00','')
self.assertEqual(self.edi._formatfield('-0.001',tfield1,testdummy), '-0.00','')
self.assertEqual(self.edi._formatfield('-.12',tfield1,testdummy), '-0.12','no zero before dec,sign is OK')
self.assertEqual(self.edi._formatfield('001',tfield1,testdummy), '1.00 ','leading zeroes are removed')
self.assertEqual(self.edi._formatfield('0.10',tfield1,testdummy), '0.10 ','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('12.1049',tfield1,testdummy), '12.10','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('-1.23',tfield1,testdummy), '-1.23','numeric field at max with minus and decimal sign')
self.assertEqual(self.edi._formatfield('0001',tfield1,testdummy), '1.00 ','strips leading zeroes if possobel')
self.assertEqual(self.edi._formatfield('+13',tfield1,testdummy), '13.00','strips leading zeroes if possobel')
self.edi.ta_info['decimaal']=','
self.assertEqual(self.edi._formatfield('1.23',tfield1,testdummy), '1,23 ','other dec.sig, replace')
self.edi.ta_info['decimaal']='.'
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'123.1049',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'123',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1234',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'-1234.56',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1<3',tfield1,testdummy) #wrong char
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1-3',tfield1,testdummy) #'-' in middel of number
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'123-',tfield1,testdummy) #'-' at end of number
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1,3',tfield1,testdummy) #',', where ',' is not traid sep.
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1+3',tfield1,testdummy) #'+' in middle of number (no exp)
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1E3',tfield1,testdummy) #'+' in middle of number (no exp)
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'13+',tfield1,testdummy) #'+' at end
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1234.100',tfield1,testdummy) #field too big
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'.',tfield1,testdummy) #no num
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'-',tfield1,testdummy) #no num
# #test filling up to min length
tfield2 = ['TEST1', 'M', 8, 'NL', True, 2, 8,'N']
self.assertEqual(self.edi._formatfield('123.45',tfield2,testdummy), '123.45 ','just large enough')
self.assertEqual(self.edi._formatfield('123.4549',tfield2,testdummy), '123.45 ','just large enough')
self.assertEqual(self.edi._formatfield('123.455',tfield2,testdummy), '123.46 ','just large enough')
self.assertEqual(self.edi._formatfield('0.1000',tfield2,testdummy), '0.10 ','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('00001',tfield2,testdummy), '1.00 ','keep leading zeroes')
self.assertEqual(self.edi._formatfield('12',tfield2,testdummy), '12.00 ','add leading zeroes')
self.assertEqual(self.edi._formatfield('.1',tfield2,testdummy), '0.10 ','add leading zeroes')
#test exp; bots tries to convert to normal
self.assertEqual(self.edi._formatfield('78E+3',tfield2,testdummy), '78000.00','add leading zeroes')
self.assertEqual(self.edi._formatfield('-8E+3',tfield2,testdummy), '-8000.00','add leading zeroes')
self.assertEqual(self.edi._formatfield('-178e-3',tfield2,testdummy), '-0.18 ','add leading zeroes')
self.assertEqual(self.edi._formatfield('-178e-5',tfield2,testdummy), '-0.00 ','add leading zeroes')
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'178E+4',tfield2,testdummy) #too big with exp
tfield4 = ['TEST1', 'M', 30, 'NL', True, 3, 30,'N']
self.assertEqual(self.edi._formatfield('1234567890123456',tfield4,testdummy), '1234567890123456.000 ','lot of digits')
#test N format, zero decimals
tfield7 = ['TEST1', 'M', 5, 'NL', True, 0, 5, 'N']
# length decimals minlength format
self.assertEqual(self.edi._formatfield('12345',tfield7,testdummy), '12345','')
self.assertEqual(self.edi._formatfield('1.234',tfield7,testdummy), '1 ','')
self.assertEqual(self.edi._formatfield('123.4',tfield7,testdummy), '123 ','')
self.assertEqual(self.edi._formatfield('0.0',tfield7,testdummy), '0 ','')
def test_out_formatfield_fixedNR(self):
self.edi.ta_info['decimaal']='.'
self.edi.ta_info['lengthnumericbare']=False
tfield1 = ['TEST1','M',5,'NR',True,2, 5, 'N']
# length decimals minlength format
self.assertEqual(self.edi._formatfield('',tfield1,testdummy), ' 0.00','empty string')
self.assertEqual(self.edi._formatfield('1',tfield1,testdummy), ' 1.00', 'basic')
self.assertEqual(self.edi._formatfield(' 1',tfield1,testdummy), ' 1.00', 'basic')
self.assertEqual(self.edi._formatfield('1 ',tfield1,testdummy), ' 1.00', 'basic')
self.assertEqual(self.edi._formatfield('0',tfield1,testdummy), ' 0.00','zero stays zero')
self.assertEqual(self.edi._formatfield('-0',tfield1,testdummy), '-0.00','neg.zero stays neg.zero')
self.assertEqual(self.edi._formatfield('-0.00',tfield1,testdummy), '-0.00','')
self.assertEqual(self.edi._formatfield('-0.001',tfield1,testdummy), '-0.00','')
self.assertEqual(self.edi._formatfield('-.12',tfield1,testdummy), '-0.12','no zero before dec,sign is OK')
self.assertEqual(self.edi._formatfield('001',tfield1,testdummy), ' 1.00','leading zeroes are removed')
self.assertEqual(self.edi._formatfield('0.10',tfield1,testdummy), ' 0.10','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('12.1049',tfield1,testdummy), '12.10','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('-1.23',tfield1,testdummy), '-1.23','numeric field at max with minus and decimal sign')
self.assertEqual(self.edi._formatfield('0001',tfield1,testdummy), ' 1.00','strips leading zeroes if possobel')
self.assertEqual(self.edi._formatfield('+13',tfield1,testdummy), '13.00','strips leading zeroes if possobel')
self.edi.ta_info['decimaal']=','
self.assertEqual(self.edi._formatfield('1.23',tfield1,testdummy), ' 1,23','other dec.sig, replace')
self.edi.ta_info['decimaal']='.'
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'123.1049',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'123',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1234',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'-1234.56',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1<3',tfield1,testdummy) #wrong char
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1-3',tfield1,testdummy) #'-' in middel of number
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'123-',tfield1,testdummy) #'-' at end of number
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1,3',tfield1,testdummy) #',', where ',' is not traid sep.
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1+3',tfield1,testdummy) #'+' in middle of number (no exp)
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1E3',tfield1,testdummy) #'+' in middle of number (no exp)
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'13+',tfield1,testdummy) #'+' at end
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1234.100',tfield1,testdummy) #field too big
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'.',tfield1,testdummy) #no num
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'-',tfield1,testdummy) #no num
# #test filling up to min length
tfield2 = ['TEST1', 'M', 8, 'NR', True, 2, 8,'N']
self.assertEqual(self.edi._formatfield('123.45',tfield2,testdummy), ' 123.45','just large enough')
self.assertEqual(self.edi._formatfield('123.4549',tfield2,testdummy), ' 123.45','just large enough')
self.assertEqual(self.edi._formatfield('123.455',tfield2,testdummy), ' 123.46','just large enough')
self.assertEqual(self.edi._formatfield('0.1000',tfield2,testdummy), ' 0.10','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('00001',tfield2,testdummy), ' 1.00','keep leading zeroes')
self.assertEqual(self.edi._formatfield('12',tfield2,testdummy), ' 12.00','add leading zeroes')
self.assertEqual(self.edi._formatfield('.1',tfield2,testdummy), ' 0.10','add leading zeroes')
#test exp; bots tries to convert to normal
self.assertEqual(self.edi._formatfield('78E+3',tfield2,testdummy), '78000.00','add leading zeroes')
self.assertEqual(self.edi._formatfield('-8E+3',tfield2,testdummy), '-8000.00','add leading zeroes')
self.assertEqual(self.edi._formatfield('-178e-3',tfield2,testdummy), ' -0.18','add leading zeroes')
self.assertEqual(self.edi._formatfield('-178e-5',tfield2,testdummy), ' -0.00','add leading zeroes')
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'178E+4',tfield2,testdummy) #too big with exp
tfield4 = ['TEST1', 'M', 30, 'NR', True, 3, 30,'N']
self.assertEqual(self.edi._formatfield('1234567890123456',tfield4,testdummy), ' 1234567890123456.000','lot of digits')
#test N format, zero decimals
tfield7 = ['TEST1', 'M', 5, 'NR', True, 0, 5, 'N']
# length decimals minlength format
self.assertEqual(self.edi._formatfield('12345',tfield7,testdummy), '12345','')
self.assertEqual(self.edi._formatfield('1.234',tfield7,testdummy), ' 1','')
self.assertEqual(self.edi._formatfield('123.4',tfield7,testdummy), ' 123','')
self.assertEqual(self.edi._formatfield('0.0',tfield7,testdummy), ' 0','')
def test_out_formatfield_fixedI(self):
self.edi.ta_info['lengthnumericbare']=False
self.edi.ta_info['decimaal']='.'
tfield1 = ['TEST1','M',5,'I',True,2, 5, 'I']
# length decimals minlength format
self.assertEqual(self.edi._formatfield('',tfield1,testdummy), '00000','empty string is initialised as 00000')
self.assertEqual(self.edi._formatfield('1',tfield1,testdummy), '00100', 'basic')
self.assertEqual(self.edi._formatfield(' 1',tfield1,testdummy), '00100', 'basic')
self.assertEqual(self.edi._formatfield('1 ',tfield1,testdummy), '00100', 'basic')
self.assertEqual(self.edi._formatfield('0',tfield1,testdummy), '00000','zero stays zero')
self.assertEqual(self.edi._formatfield('-0',tfield1,testdummy), '-0000','neg.zero stays neg.zero')
self.assertEqual(self.edi._formatfield('-0.00',tfield1,testdummy), '-0000','')
self.assertEqual(self.edi._formatfield('-0.001',tfield1,testdummy), '-0000','')
self.assertEqual(self.edi._formatfield('-.12',tfield1,testdummy), '-0012','no zero before dec,sign is OK') #TODO: puts ) in front
self.assertEqual(self.edi._formatfield('123',tfield1,testdummy), '12300','numeric field at max')
self.assertEqual(self.edi._formatfield('001',tfield1,testdummy), '00100','leading zeroes are removed')
self.assertEqual(self.edi._formatfield('0.10',tfield1,testdummy), '00010','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('123.1049',tfield1,testdummy), '12310','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('-1.23',tfield1,testdummy), '-0123','numeric field at max with minus and decimal sign')
self.assertEqual(self.edi._formatfield('0001',tfield1,testdummy), '00100','strips leading zeroes if possobel')
self.assertEqual(self.edi._formatfield('+123',tfield1,testdummy), '12300','strips leading zeroes if possobel')
self.edi.ta_info['decimaal']=','
self.assertEqual(self.edi._formatfield('1.23',tfield1,testdummy), '00123','other dec.sig, replace')
self.edi.ta_info['decimaal']='.'
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1234',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'-1234.56',tfield1,testdummy) #field too large
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1<3',tfield1,testdummy) #wrong char
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1-3',tfield1,testdummy) #'-' in middel of number
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'123-',tfield1,testdummy) #'-' at end of number
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1,3',tfield1,testdummy) #',', where ',' is not traid sep.
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1+3',tfield1,testdummy) #'+' in middle of number (no exp)
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1E3',tfield1,testdummy) #'+' in middle of number (no exp)
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'13+',tfield1,testdummy) #'+' at end
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1234.100',tfield1,testdummy) #field too big
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'.',tfield1,testdummy) #no num
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'-',tfield1,testdummy) #no num
#~ #test filling up to min length
tfield2 = ['TEST1', 'M', 8, 'I', True, 2, 8,'I']
self.assertEqual(self.edi._formatfield('123.45',tfield2,testdummy), '00012345','just large enough')
self.assertEqual(self.edi._formatfield('123.4549',tfield2,testdummy), '00012345','just large enough')
self.assertEqual(self.edi._formatfield('123.455',tfield2,testdummy), '00012346','just large enough')
self.assertEqual(self.edi._formatfield('0.1000',tfield2,testdummy), '00000010','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('00001',tfield2,testdummy), '00000100','keep leading zeroes')
self.assertEqual(self.edi._formatfield('12',tfield2,testdummy), '00001200','add leading zeroes')
self.assertEqual(self.edi._formatfield('.1',tfield2,testdummy), '00000010','add leading zeroes')
#test exp; bots tries to convert to normal
self.assertEqual(self.edi._formatfield('178E+3',tfield2,testdummy), '17800000','add leading zeroes')
self.assertEqual(self.edi._formatfield('-17E+3',tfield2,testdummy), '-1700000','add leading zeroes')
self.assertEqual(self.edi._formatfield('-178e-3',tfield2,testdummy), '-0000018','add leading zeroes')
self.assertEqual(self.edi._formatfield('-178e-5',tfield2,testdummy), '-0000000','add leading zeroes')
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'178E+4',tfield2,testdummy) #too big with exp
tfield4 = ['TEST1', 'M', 80, 'I', True, 3, 0,'I']
self.assertEqual(self.edi._formatfield('123456789012340',tfield4,testdummy), '123456789012340000','lot of digits')
def test_out_formatfield_fixedD(self):
tfield1 = ['TEST1', 'M', 8, 'D', True, 0, 8,'D']
# length decimals minlength
self.assertEqual(self.edi._formatfield('20071001',tfield1,testdummy), '20071001','basic')
self.assertEqual(self.edi._formatfield('99991001',tfield1,testdummy), '99991001','max year')
self.assertEqual(self.edi._formatfield('00011001',tfield1,testdummy), '00011001','min year')
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'2007093112',tfield1,testdummy) #too long
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'20070931',tfield1,testdummy) #no valid date
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'-0070931',tfield1,testdummy) #no valid date
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'70931',tfield1,testdummy) #too short
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'0931',tfield1,testdummy) #too short
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'0931BC',tfield1,testdummy) #alfanum
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'OOOOBC',tfield1,testdummy) #alfanum
tfield2 = ['TEST1', 'M', 6, 'D', True, 0, 6,'D']
# length decimals minlength
self.assertEqual(self.edi._formatfield('071001',tfield2,testdummy), '071001','basic')
def test_out_formatfield_fixedT(self):
tfield1 = ['TEST1', 'M', 4, 'T', True, 0, 4,'T']
# length decimals minlength
self.assertEqual(self.edi._formatfield('2359',tfield1,testdummy), '2359','basic')
self.assertEqual(self.edi._formatfield('0000',tfield1,testdummy), '0000','basic')
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'2401',tfield1,testdummy) #no valid date
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1261',tfield1,testdummy) #no valid date
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1262',tfield1,testdummy) #no valid date - python allows 61 secnds?
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'2400',tfield1,testdummy) #no valid date
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'2501',tfield1,testdummy) #no valid date
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'-1200',tfield1,testdummy) #no valid date
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'120',tfield1,testdummy) #too short
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'093123',tfield1,testdummy) #too long
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'11PM',tfield1,testdummy) #alfanum
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'TIME',tfield1,testdummy) #alfanum
tfield2 = ['TEST1', 'M', 6, 'T', True, 0, 6,'T']
# length decimals minlength
self.assertEqual(self.edi._formatfield('000000',tfield2,testdummy), '000000','basic')
self.assertEqual(self.edi._formatfield('230000',tfield2,testdummy), '230000','basic')
self.assertEqual(self.edi._formatfield('235959',tfield2,testdummy), '235959','basic')
self.assertEqual(self.edi._formatfield('123456',tfield2,testdummy), '123456','basic')
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'240001',tfield2,testdummy) #no valid date
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'126101',tfield2,testdummy) #no valid date
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'120062',tfield2,testdummy) #no valid date - python allows 61 secnds?
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'240000',tfield2,testdummy) #no valid date
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'250001',tfield2,testdummy) #no valid date
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'-12000',tfield2,testdummy) #no valid date
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'120',tfield2,testdummy) #too short
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'0931233',tfield2,testdummy) #too short
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'1100PM',tfield2,testdummy) #alfanum
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'11TIME',tfield2,testdummy) #alfanum
def test_out_formatfield_fixedA(self):
tfield1 = ['TEST1', 'M', 5, 'A', True, 0, 5,'A']
# length decimals minlength
self.assertEqual(self.edi._formatfield('abcde',tfield1,testdummy), 'abcde','basic')
self.assertEqual(self.edi._formatfield('',tfield1,testdummy), ' ','basic')
self.assertEqual(self.edi._formatfield('ab ',tfield1,testdummy), 'ab ','basic')
self.assertEqual(self.edi._formatfield('a b',tfield1,testdummy), 'a b ','basic')
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'abcdef',tfield1,testdummy) #no valid date
tfield1 = ['TEST1', 'M', 5, 'A', True, 0, 5,'A']
# length decimals minlength
self.assertEqual(self.edi._formatfield('abcde',tfield1,testdummy), 'abcde','basic')
self.assertEqual(self.edi._formatfield('ab ',tfield1,testdummy), 'ab ','basic')
self.assertEqual(self.edi._formatfield('a b',tfield1,testdummy), 'a b ','basic')
self.assertEqual(self.edi._formatfield('a',tfield1,testdummy), 'a ','basic')
self.assertEqual(self.edi._formatfield(' ',tfield1,testdummy), ' ','basic')
self.assertEqual(self.edi._formatfield(' ',tfield1,testdummy), ' ','basic')
self.assertEqual(self.edi._formatfield(' ',tfield1,testdummy), ' ','basic')
self.assertEqual(self.edi._formatfield('',tfield1,testdummy), ' ','basic')
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'abcdef',tfield1,testdummy) #no valid date
def test_out_formatfield_fixedAR(self):
tfield1 = ['TEST1', 'M', 5, 'AR', True, 0, 5,'A']
# length decimals minlength
self.assertEqual(self.edi._formatfield('abcde',tfield1,testdummy), 'abcde','basic')
self.assertEqual(self.edi._formatfield('',tfield1,testdummy), ' ','basic')
self.assertEqual(self.edi._formatfield('ab ',tfield1,testdummy), ' ab ','basic')
self.assertEqual(self.edi._formatfield('a b',tfield1,testdummy), ' a b','basic')
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'abcdef',tfield1,testdummy) #no valid date
tfield1 = ['TEST1', 'M', 5, 'AR', True, 0, 5,'A']
# length decimals minlength
self.assertEqual(self.edi._formatfield('abcde',tfield1,testdummy), 'abcde','basic')
self.assertEqual(self.edi._formatfield('ab ',tfield1,testdummy), ' ab ','basic')
self.assertEqual(self.edi._formatfield('a b',tfield1,testdummy), ' a b','basic')
self.assertEqual(self.edi._formatfield('a',tfield1,testdummy), ' a','basic')
self.assertEqual(self.edi._formatfield(' ',tfield1,testdummy), ' ','basic')
self.assertEqual(self.edi._formatfield(' ',tfield1,testdummy), ' ','basic')
self.assertEqual(self.edi._formatfield(' ',tfield1,testdummy), ' ','basic')
self.assertEqual(self.edi._formatfield('',tfield1,testdummy), ' ','basic')
self.assertRaises(botslib.OutMessageError,self.edi._formatfield,'abcdef',tfield1,testdummy) #no valid date
class TestFormatFieldInmessage(unittest.TestCase):
#both var and fixed fields are tested. Is not much difference (white-box testing)
def setUp(self):
#need to have a inmessage-object for tests. Read is a edifile and a grammar.
self.edi = inmessage.edifromfile(frompartner='',
topartner='',
filename='botssys/infile/unitformats/formats01.edi',
messagetype='edifact',
testindicator='0',
editype='edifact',
charset='UNOA',
alt='')
def testformatfieldR(self):
self.edi.ta_info['lengthnumericbare']=True
tfield1 = ['TEST1','M',3,'N',True,0, 0, 'R']
# length decimals minlength format
self.assertEqual(self.edi._formatfield('',tfield1,testdummy), '0', 'empty numeric string is accepted, is zero')
self.assertEqual(self.edi._formatfield('1',tfield1,testdummy), '1', 'basic')
self.assertEqual(self.edi._formatfield('0',tfield1,testdummy), '0','zero stays zero')
self.assertEqual(self.edi._formatfield('-0',tfield1,testdummy), '-0','neg.zero stays neg.zero')
self.assertEqual(self.edi._formatfield('-0.00',tfield1,testdummy), '-0.00','')
self.assertEqual(self.edi._formatfield('-.12',tfield1,testdummy), '-0.12','no zero before dec,sign is OK')
self.assertEqual(self.edi._formatfield('123',tfield1,testdummy), '123','numeric field at max')
self.assertEqual(self.edi._formatfield('001',tfield1,testdummy), '1','leading zeroes are removed')
self.assertEqual(self.edi._formatfield('0.10',tfield1,testdummy), '0.10','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('-1.23',tfield1,testdummy), '-1.23','numeric field at max with minus and decimal sign')
self.edi.ta_info['decimaal']=','
self.assertEqual(self.edi._formatfield('1,23-',tfield1,testdummy), '-1.23','other dec.sig, replace')
self.edi.ta_info['decimaal']='.'
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'1234',tfield1,testdummy) #field too large
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'0001',tfield1,testdummy) #leading zeroes; field too large
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'-1.234',tfield1,testdummy) #field too large
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'1<3',tfield1,testdummy) #wrong char
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'1-3',tfield1,testdummy) #'-' in middel of number
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'1,3',tfield1,testdummy) #',', where ',' is not traid sep.
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'1+3',tfield1,testdummy) #'+' in middle of number
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'13+',tfield1,testdummy) #'+' in middle of number
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'0.100',tfield1,testdummy) #field too big
#test field to short
tfield2 = ['TEST1', 'M', 8, 'N', True, 0, 5,'R']
self.assertEqual(self.edi._formatfield('12345',tfield2,testdummy), '12345','just large enough')
self.assertEqual(self.edi._formatfield('0.1000',tfield2,testdummy), '0.1000','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('00001',tfield2,testdummy), '1','remove leading zeroes')
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'1235',tfield2,testdummy) #field too short
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'-12.34',tfield2,testdummy) #field too short
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'-',tfield2,testdummy) #field too short
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'.',tfield2,testdummy) #field too short
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'-.',tfield2,testdummy) #field too short
#WARN: dubious tests. This is Bots filosophy: be flexible in input, be right in output.
self.assertEqual(self.edi._formatfield('123-',tfield1,testdummy), '-123','numeric field minus at end')
self.assertEqual(self.edi._formatfield('.001',tfield1,testdummy), '0.001','if no zero before dec.sign, length>max.length')
self.assertEqual(self.edi._formatfield('+13',tfield1,testdummy), '13','plus is allowed') #WARN: if plus used, plus is countd in length!!
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'12E+3',tfield2,testdummy) #field too large
tfield4 = ['TEST1', 'M', 8, 'N', True, 3, 0,'R']
self.assertEqual(self.edi._formatfield('123.4561',tfield4,testdummy), '123.4561','no checking to many digits incoming') #should round here?
tfield4 = ['TEST1', 'M', 80, 'N', True, 3, 0,'R']
self.assertEqual(self.edi._formatfield('12345678901234560',tfield4,testdummy), '12345678901234560','lot of digits')
self.edi.ta_info['lengthnumericbare']=False
self.assertEqual(self.edi._formatfield('-1.45',tfield2,testdummy), '-1.45','just large enough')
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'-12345678',tfield2,testdummy) #field too large
def testformatfieldN(self):
self.edi.ta_info['lengthnumericbare']=True
tfield1 = ['TEST1', 'M', 3, 'R', True, 2, 0,'N']
# length decimals minlength
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'',tfield1,testdummy) #empty string
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'1',tfield1,testdummy) #empty string
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'0',tfield1,testdummy) #empty string
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'-0',tfield1,testdummy) #empty string
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'01.00',tfield1,testdummy) #empty string
self.assertEqual(self.edi._formatfield('1.00',tfield1,testdummy), '1.00', 'basic')
self.assertEqual(self.edi._formatfield('0.00',tfield1,testdummy), '0.00','zero stays zero')
self.assertEqual(self.edi._formatfield('-0.00',tfield1,testdummy), '-0.00','neg.zero stays neg.zero')
self.assertEqual(self.edi._formatfield('-.12',tfield1,testdummy), '-0.12','no zero before dec,sign is OK')
self.assertEqual(self.edi._formatfield('1.23',tfield1,testdummy), '1.23','numeric field at max')
self.assertEqual(self.edi._formatfield('0.10',tfield1,testdummy), '0.10','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('-1.23',tfield1,testdummy), '-1.23','numeric field at max with minus and decimal sign')
self.edi.ta_info['decimaal']=','
self.assertEqual(self.edi._formatfield('1,23-',tfield1,testdummy), '-1.23','other dec.sig, replace')
self.edi.ta_info['decimaal']='.'
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'1234',tfield1,testdummy) #field too large
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'0001',tfield1,testdummy) #leading zeroes; field too large
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'-1.234',tfield1,testdummy) #field too large
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'1<3',tfield1,testdummy) #wrong char
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'1-3',tfield1,testdummy) #'-' in middel of number
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'1,3',tfield1,testdummy) #',', where ',' is not traid sep.
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'1+3',tfield1,testdummy) #'+' in middle of number
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'13+',tfield1,testdummy) #'+' in middle of number
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'0.100',tfield1,testdummy) #field too big
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'12E+3',tfield1,testdummy) #no exp
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'.',tfield1,testdummy) #no exp
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'-',tfield1,testdummy) #no exp
#test field to short
tfield2 = ['TEST1', 'M', 8, 'R', True, 4, 5,'N']
self.assertEqual(self.edi._formatfield('1.2345',tfield2,testdummy), '1.2345','just large enough')
self.assertEqual(self.edi._formatfield('0.1000',tfield2,testdummy), '0.1000','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('001.1234',tfield2,testdummy), '1.1234','remove leading zeroes')
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'1235',tfield2,testdummy) #field too short
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'-12.34',tfield2,testdummy) #field too short
#WARN: dubious tests. This is Bots filosophy: be flexible in input, be right in output.
self.assertEqual(self.edi._formatfield('1234.1234-',tfield2,testdummy), '-1234.1234','numeric field - minus at end')
self.assertEqual(self.edi._formatfield('.01',tfield1,testdummy), '0.01','if no zero before dec.sign, length>max.length')
self.assertEqual(self.edi._formatfield('+13.1234',tfield2,testdummy), '13.1234','plus is allowed') #WARN: if plus used, plus is counted in length!!
tfield3 = ['TEST1', 'M', 18, 'R', True, 0, 0,'N']
tfield4 = ['TEST1', 'M', 8, 'R', True, 3, 0,'N']
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'123.4561',tfield4,testdummy) #to many digits
def testformatfieldI(self):
self.edi.ta_info['lengthnumericbare']=True
tfield1 = ['TEST1', 'M', 5, 'I', True, 2, 0,'I']
# length decimals minlength
self.assertEqual(self.edi._formatfield('',tfield1,testdummy), '0.00', 'empty numeric is accepted, is zero')
self.assertEqual(self.edi._formatfield('123',tfield1,testdummy), '1.23', 'basic')
self.assertEqual(self.edi._formatfield('1',tfield1,testdummy), '0.01', 'basic')
self.assertEqual(self.edi._formatfield('0',tfield1,testdummy), '0.00','zero stays zero')
self.assertEqual(self.edi._formatfield('-0',tfield1,testdummy), '-0.00','neg.zero stays neg.zero')
self.assertEqual(self.edi._formatfield('-000',tfield1,testdummy), '-0.00','')
self.assertEqual(self.edi._formatfield('-12',tfield1,testdummy), '-0.12','no zero before dec,sign is OK')
self.assertEqual(self.edi._formatfield('12345',tfield1,testdummy), '123.45','numeric field at max')
self.assertEqual(self.edi._formatfield('00001',tfield1,testdummy), '0.01','leading zeroes are removed')
self.assertEqual(self.edi._formatfield('010',tfield1,testdummy), '0.10','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('-99123',tfield1,testdummy), '-991.23','numeric field at max with minus and decimal sign')
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'123456',tfield1,testdummy) #field too large
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'000100',tfield1,testdummy) #field too large
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'000001',tfield1,testdummy) #leading zeroes; field too large
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'12<3',tfield1,testdummy) #wrong char
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'12-3',tfield1,testdummy) #'-' in middel of number
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'12,3',tfield1,testdummy) #','.
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'12+3',tfield1,testdummy) #'+' in middle of number
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'123+',tfield1,testdummy) #'+'
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'12E+3',tfield1,testdummy) #'+'
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'-',tfield1,testdummy) #only -
#~ #test field to short
tfield2 = ['TEST1', 'M', 8, 'I', True, 2, 5,'I']
self.assertEqual(self.edi._formatfield('12345',tfield2,testdummy), '123.45','just large enough')
self.assertEqual(self.edi._formatfield('10000',tfield2,testdummy), '100.00','keep zeroes after last dec.digit')
self.assertEqual(self.edi._formatfield('00100',tfield2,testdummy), '1.00','remove leading zeroes')
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'1235',tfield2,testdummy) #field too short
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'-1234',tfield2,testdummy) #field too short
tfield3 = ['TEST1', 'M', 18, 'I', True, 0, 0,'I']
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'12E+3',tfield3,testdummy) #no exponent
#~ #WARN: dubious tests. This is Bots filosophy: be flexible in input, be right in output.
self.assertEqual(self.edi._formatfield('123-',tfield1,testdummy), '-1.23','numeric field minus at end')
self.assertEqual(self.edi._formatfield('+13',tfield1,testdummy), '0.13','plus is allowed') #WARN: if plus used, plus is countd in length!!
def testformatfieldD(self):
tfield1 = ['TEST1', 'M', 20, 'D', True, 0, 0,'D']
# length decimals minlength
self.assertEqual(self.edi._formatfield('20071001',tfield1,testdummy), '20071001','basic')
self.assertEqual(self.edi._formatfield('071001',tfield1,testdummy), '071001','basic')
self.assertEqual(self.edi._formatfield('99991001',tfield1,testdummy), '99991001','max year')
self.assertEqual(self.edi._formatfield('00011001',tfield1,testdummy), '00011001','min year')
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'2007093112',tfield1,testdummy) #too long
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'20070931',tfield1,testdummy) #no valid date
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'-0070931',tfield1,testdummy) #no valid date
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'70931',tfield1,testdummy) #too short
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'0931',tfield1,testdummy) #too short
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'0931BC',tfield1,testdummy) #alfanum
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'OOOOBC',tfield1,testdummy) #alfanum
def testformatfieldT(self):
tfield1 = ['TEST1', 'M', 10, 'T', True, 0, 0,'T']
# length decimals minlength
self.assertEqual(self.edi._formatfield('2359',tfield1,testdummy), '2359','basic')
self.assertEqual(self.edi._formatfield('0000',tfield1,testdummy), '0000','basic')
self.assertEqual(self.edi._formatfield('000000',tfield1,testdummy), '000000','basic')
self.assertEqual(self.edi._formatfield('230000',tfield1,testdummy), '230000','basic')
self.assertEqual(self.edi._formatfield('235959',tfield1,testdummy), '235959','basic')
self.assertEqual(self.edi._formatfield('123456',tfield1,testdummy), '123456','basic')
self.assertEqual(self.edi._formatfield('0931233',tfield1,testdummy), '0931233','basic')
self.assertEqual(self.edi._formatfield('09312334',tfield1,testdummy), '09312334','basic')
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'240001',tfield1,testdummy) #no valid date
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'126101',tfield1,testdummy) #no valid date
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'120062',tfield1,testdummy) #no valid date - python allows 61 secnds?
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'240000',tfield1,testdummy) #no valid date
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'250001',tfield1,testdummy) #no valid date
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'-12000',tfield1,testdummy) #no valid date
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'120',tfield1,testdummy) #too short
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'11PM',tfield1,testdummy) #alfanum
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'TIME',tfield1,testdummy) #alfanum
def testformatfieldA(self):
tfield1 = ['TEST1', 'M', 5, 'T', True, 0, 0,'A']
# length decimals minlength
self.assertEqual(self.edi._formatfield('abcde',tfield1,testdummy), 'abcde','basic')
self.assertEqual(self.edi._formatfield('',tfield1,testdummy), '','basic')
self.assertEqual(self.edi._formatfield('',tfield1,testdummy), '','basic')
self.assertEqual(self.edi._formatfield(' ab',tfield1,testdummy), 'ab','basic')
self.assertEqual(self.edi._formatfield('ab ',tfield1,testdummy), 'ab','basic')
self.assertEqual(self.edi._formatfield(' ab',tfield1,testdummy), 'ab','basic')
self.assertEqual(self.edi._formatfield('ab ',tfield1,testdummy), 'ab','basic')
self.assertEqual(self.edi._formatfield('a b',tfield1,testdummy), 'a b','basic')
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'abcdef',tfield1,testdummy) #no valid date
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'ab ',tfield1,testdummy) #no valid date
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,' ab',tfield1,testdummy) #no valid date - python allows 61 secnds?
tfield1 = ['TEST1', 'M', 5, 'T', True, 0, 2,'A']
# length decimals minlength
self.assertEqual(self.edi._formatfield('abcde',tfield1,testdummy), 'abcde','basic')
self.assertEqual(self.edi._formatfield(' ab',tfield1,testdummy), 'ab','basic')
self.assertEqual(self.edi._formatfield('ab ',tfield1,testdummy), 'ab','basic')
self.assertEqual(self.edi._formatfield(' ab',tfield1,testdummy), 'ab','basic')
self.assertEqual(self.edi._formatfield('ab ',tfield1,testdummy), 'ab','basic')
self.assertEqual(self.edi._formatfield('a b',tfield1,testdummy), 'a b','basic')
self.assertEqual(self.edi._formatfield(' ',tfield1,testdummy), '','basic')
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'a',tfield1,testdummy) #no valid date
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'abcdef',tfield1,testdummy) #no valid date
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'ab ',tfield1,testdummy) #no valid date
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,' ab',tfield1,testdummy) #no valid date - python allows 61 secnds?
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,' ',tfield1,testdummy) #no valid date - python allows 61 secnds?
self.assertRaises(botslib.InMessageFieldError,self.edi._formatfield,'',tfield1,testdummy) #no valid date - python allows 61 secnds?
def testEdifact0402(self):
# old format test are run
self.assertRaises(botslib.InMessageFieldError,inmessage.edifromfile,editype='edifact',
messagetype='edifact',filename='botssys/infile/unitformats/040201F.edi')
self.assertRaises(botslib.InMessageFieldError,inmessage.edifromfile,editype='edifact',
messagetype='edifact',filename='botssys/infile/unitformats/040202F.edi')
self.assertRaises(botslib.InMessageFieldError,inmessage.edifromfile,editype='edifact',
messagetype='edifact',filename='botssys/infile/unitformats/040203F.edi')
self.assertRaises(botslib.InMessageFieldError,inmessage.edifromfile,editype='edifact',
messagetype='edifact',filename='botssys/infile/unitformats/040204F.edi')
self.assertRaises(botslib.InMessageFieldError,inmessage.edifromfile,editype='edifact',
messagetype='edifact',filename='botssys/infile/unitformats/040205F.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',
messagetype='edifact',filename='botssys/infile/unitformats/040206F.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',
messagetype='edifact',filename='botssys/infile/unitformats/040207F.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',
messagetype='edifact',filename='botssys/infile/unitformats/040208F.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',
messagetype='edifact',filename='botssys/infile/unitformats/040209F.edi')
self.assertRaises(botslib.InMessageFieldError,inmessage.edifromfile,editype='edifact',
messagetype='edifact',filename='botssys/infile/unitformats/040210F.edi')
self.assertRaises(botslib.InMessageFieldError,inmessage.edifromfile,editype='edifact',
messagetype='edifact',filename='botssys/infile/unitformats/040211F.edi')
self.assertRaises(botslib.InMessageFieldError,inmessage.edifromfile,editype='edifact',
messagetype='edifact',filename='botssys/infile/unitformats/040212F.edi')
self.failUnless(inmessage.edifromfile(editype='edifact',
messagetype='edifact',filename='botssys/infile/unitformats/040214T.edi'), 'standaard test')
self.assertRaises(botslib.InMessageFieldError,inmessage.edifromfile,editype='edifact',
messagetype='edifact',filename='botssys/infile/unitformats/040215F.edi')
self.assertRaises(botslib.InMessageFieldError,inmessage.edifromfile,editype='edifact',
messagetype='edifact',filename='botssys/infile/unitformats/040217F.edi')
self.assertRaises(botslib.InMessageFieldError,inmessage.edifromfile,editype='edifact',
messagetype='edifact',filename='botssys/infile/unitformats/040218F.edi')
self.assertRaises(botslib.InMessageFieldError,inmessage.edifromfile,editype='edifact',
messagetype='edifact',filename='botssys/infile/unitformats/040219F.edi')
if __name__ == '__main__':
botsinit.generalinit('config')
#~ botslib.initbotscharsets()
botsinit.initenginelogging()
unittest.main()
| Python |
import os
import sys
import posixpath
try:
import cPickle as pickle
except:
import pickle
import time
import datetime
import email
import email.Utils
import email.Generator
import email.Message
import email.encoders
import glob
import shutil
import fnmatch
import codecs
if os.name == 'nt':
import msvcrt
elif os.name == 'posix':
import fcntl
try:
import json as simplejson
except ImportError:
import simplejson
import smtplib
import poplib
import imaplib
import ftplib
import xmlrpclib
from django.utils.translation import ugettext as _
#Bots modules
import botslib
import botsglobal
import inmessage
import outmessage
from botsconfig import *
@botslib.log_session
def run(idchannel,idroute=''):
'''run a communication session (dispatcher for communication functions).'''
for channeldict in botslib.query('''SELECT *
FROM channel
WHERE idchannel=%(idchannel)s''',
{'idchannel':idchannel}):
botsglobal.logger.debug(u'start communication channel "%s" type %s %s.',channeldict['idchannel'],channeldict['type'],channeldict['inorout'])
#update communication/run process with idchannel
ta_run = botslib.OldTransaction(botslib._Transaction.processlist[-1])
if channeldict['inorout'] == 'in':
ta_run.update(fromchannel=channeldict['idchannel'])
else:
ta_run.update(tochannel=channeldict['idchannel'])
try:
userscript,scriptname = botslib.botsimport('communicationscripts',channeldict['idchannel'])
except ImportError:
userscript = scriptname = None
#get the communication class to use:
if userscript and hasattr(userscript,channeldict['type']): #check communication class in user script (sub classing)
classtocall = getattr(userscript,channeldict['type'])
elif userscript and hasattr(userscript,'UserCommunicationClass'): #check for communication class called 'UserCommunicationClass' in user script. 20110920: Obsolete, depreciated. Keep this for now.
classtocall = getattr(userscript,'UserCommunicationClass')
else:
classtocall = globals()[channeldict['type']] #get the communication class from this module
classtocall(channeldict,idroute,userscript,scriptname) #call the class for this type of channel
botsglobal.logger.debug(u'finished communication channel "%s" type %s %s.',channeldict['idchannel'],channeldict['type'],channeldict['inorout'])
break #there can only be one channel; this break takes care that if found, the 'else'-clause is skipped
else:
raise botslib.CommunicationError(_(u'Channel "$idchannel" is unknown.'),idchannel=idchannel)
class _comsession(object):
''' Abstract class for communication-session. Use only subclasses.
Subclasses are called by dispatcher function 'run'
Often 'idroute' is passed as a parameter. This is ONLY because of the @botslib.log_session-wrapper!
use self.idroute!!
'''
def __init__(self,channeldict,idroute,userscript,scriptname):
''' All communication is performed in init.'''
self.channeldict=channeldict
self.idroute=idroute
self.userscript=userscript
self.scriptname=scriptname
if self.channeldict['inorout']=='out':
#routes can have the same outchannel.
#the different outchannels can be 'direct' or deferred (in route)
nroffiles = self.precommunicate(FILEOUT,RAWOUT)
if self.countoutfiles() > 0: #for out-comm: send if something to send
self.connect()
self.outcommunicate()
self.disconnect()
self.archive()
else: #incommunication
if botsglobal.incommunicate: #for in-communication: only communicate for new run
#handle maxsecondsperchannel: use global value from bots.ini unless specified in channel. (In database this is field 'rsrv2'.)
#~ print "self.channeldict['rsrv2']",self.channeldict['rsrv2']
if self.channeldict['rsrv2'] <= 0:
self.maxsecondsperchannel = botsglobal.ini.getint('settings','maxsecondsperchannel',sys.maxint)
else:
self.maxsecondsperchannel = self.channeldict['rsrv2']
self.connect()
self.incommunicate()
self.disconnect()
self.postcommunicate(RAWIN,FILEIN)
self.archive()
def archive(self):
'''archive received or send files; archive only if receive is correct.'''
if not self.channeldict['archivepath']:
return
if self.channeldict['inorout'] == 'in':
status = FILEIN
statust = OK
channel = 'fromchannel'
else:
status = FILEOUT
statust = DONE
channel = 'tochannel'
if self.userscript and hasattr(self.userscript,'archivepath'):
archivepath = botslib.runscript(self.userscript,self.scriptname,'archivepath',channeldict=self.channeldict)
else:
archivepath = botslib.join(self.channeldict['archivepath'],time.strftime('%Y%m%d'))
checkedifarchivepathisthere = False #for a outchannel that is less used, lots of empty dirs will be created. This var is used to check within loop if dir exist, but this is only checked one time.
for row in botslib.query('''SELECT filename,idta
FROM ta
WHERE idta>%(rootidta)s
AND status=%(status)s
AND statust=%(statust)s
AND ''' + channel + '''=%(idchannel)s
AND idroute=%(idroute)s
''',
{'idchannel':self.channeldict['idchannel'],'status':status,
'statust':statust,'idroute':self.idroute,'rootidta':botslib.get_minta4query()}):
if not checkedifarchivepathisthere:
botslib.dirshouldbethere(archivepath)
checkedifarchivepathisthere = True
absfilename = botslib.abspathdata(row['filename'])
if self.userscript and hasattr(self.userscript,'archivename'):
archivename = botslib.runscript(self.userscript,self.scriptname,'archivename',channeldict=self.channeldict,idta=row['idta'],filename=absfilename)
shutil.copy(absfilename,botslib.join(archivepath,archivename))
else:
shutil.copy(absfilename,archivepath)
def countoutfiles(self):
''' counts the number of edifiles to be transmitted.'''
for row in botslib.query('''SELECT COUNT(*) as count
FROM ta
WHERE idta>%(rootidta)s
AND status=%(status)s
AND statust=%(statust)s
AND tochannel=%(tochannel)s
''',
{'idroute':self.idroute,'status':RAWOUT,'statust':OK,
'tochannel':self.channeldict['idchannel'],'rootidta':botslib.get_minta4query()}):
return row['count']
@botslib.log_session
def postcommunicate(self,fromstatus,tostatus):
''' transfer communication-file from status RAWIN to FILEIN '''
return botslib.addinfo(change={'status':tostatus},where={'status':fromstatus,'fromchannel':self.channeldict['idchannel'],'idroute':self.idroute})
@botslib.log_session
def precommunicate(self,fromstatus,tostatus):
''' transfer communication-file from status FILEOUT to RAWOUT'''
return botslib.addinfo(change={'status':tostatus},where={'status':fromstatus,'tochannel':self.channeldict['idchannel']})
def file2mime(self,fromstatus,tostatus):
''' transfer communication-file from status FILEOUT to RAWOUT and convert to mime.
1 part/file always in 1 mail.
'''
counter = 0 #count the number of correct processed files
#select files with right statust, status and channel.
for row in botslib.query('''SELECT idta,filename,frompartner,topartner,charset,contenttype,editype
FROM ta
WHERE idta>%(rootidta)s
AND status=%(status)s
AND statust=%(statust)s
AND tochannel=%(idchannel)s
''',
{'idchannel':self.channeldict['idchannel'],'status':fromstatus,
'statust':OK,'idroute':self.idroute,'rootidta':botslib.get_minta4query()}):
try:
ta_from = botslib.OldTransaction(row['idta'])
ta_to = ta_from.copyta(status=tostatus)
ta_to.synall() #needed for user exits: get all parameters of ta_to from database;
confirmtype = u''
confirmasked = False
charset = row['charset']
if row['editype'] == 'email-confirmation': #outgoing MDN: message is already assembled
outfilename = row['filename']
else: #assemble message: headers and payload. Bots uses simple MIME-envelope; by default payload is an attachment
message = email.Message.Message()
#set 'from' header (sender)
frommail,ccfrom = self.idpartner2mailaddress(row['frompartner']) #lookup email address for partnerID
message.add_header('From', frommail)
#set 'to' header (receiver)
if self.userscript and hasattr(self.userscript,'getmailaddressforreceiver'): #user exit to determine to-address/receiver
tomail,ccto = botslib.runscript(self.userscript,self.scriptname,'getmailaddressforreceiver',channeldict=self.channeldict,ta=ta_to)
else:
tomail,ccto = self.idpartner2mailaddress(row['topartner']) #lookup email address for partnerID
message.add_header('To',tomail)
if ccto:
message.add_header('CC',ccto)
#set Message-ID
reference=email.Utils.make_msgid(str(ta_to.idta)) #use transaction idta in message id.
message.add_header('Message-ID',reference)
ta_to.update(frommail=frommail,tomail=tomail,cc=ccto,reference=reference) #update now (in order to use correct & updated ta_to in user script)
#set date-time stamp
message.add_header("Date",email.Utils.formatdate(localtime=True))
#set Disposition-Notification-To: ask/ask not a a MDN?
if botslib.checkconfirmrules('ask-email-MDN',idroute=self.idroute,idchannel=self.channeldict['idchannel'],
frompartner=row['frompartner'],topartner=row['topartner']):
message.add_header("Disposition-Notification-To",frommail)
confirmtype = u'ask-email-MDN'
confirmasked = True
#set subject
subject=str(row['idta'])
content = botslib.readdata(row['filename']) #get attachment from data file
if self.userscript and hasattr(self.userscript,'subject'): #user exit to determine subject
subject = botslib.runscript(self.userscript,self.scriptname,'subject',channeldict=self.channeldict,ta=ta_to,subjectstring=subject,content=content)
message.add_header('Subject',subject)
#set MIME-version
message.add_header('MIME-Version','1.0')
#set attachment filename
#create default attachment filename
unique = str(botslib.unique(self.channeldict['idchannel'])) #create unique part for attachment-filename
if self.channeldict['filename']:
attachmentfilename = self.channeldict['filename'].replace('*',unique) #filename is filename in channel where '*' is replaced by idta
else:
attachmentfilename = unique
if self.userscript and hasattr(self.userscript,'filename'): #user exit to determine attachmentname
attachmentfilename = botslib.runscript(self.userscript,self.scriptname,'filename',channeldict=self.channeldict,ta=ta_to,filename=attachmentfilename)
if attachmentfilename: #Tric: if attachmentfilename is None or empty string: do not send as an attachment.
message.add_header("Content-Disposition",'attachment',filename=attachmentfilename)
#set Content-Type and charset
charset = self.convertcodecformime(row['charset'])
message.add_header('Content-Type',row['contenttype'].lower(),charset=charset) #contenttype is set in grammar.syntax
#set attachment/payload; the Content-Transfer-Encoding is set by python encoder
message.set_payload(content) #do not use charset; this lead to unwanted encodings...bots always uses base64
if self.channeldict['askmdn'] == 'never': #channeldict['askmdn'] is the Mime encoding
email.encoders.encode_7or8bit(message) #no encoding; but the Content-Transfer-Encoding is set to 7-bit or 8-bt
elif self.channeldict['askmdn'] == 'ascii' and charset=='us-ascii':
pass #do nothing: ascii is default encoding
else: #if Mime encoding is 'always' or (Mime encoding == 'ascii' and charset!='us-ascii'): use base64
email.encoders.encode_base64(message)
#*******write email to file***************************
outfilename = str(ta_to.idta)
outfile = botslib.opendata(outfilename, 'wb')
g = email.Generator.Generator(outfile, mangle_from_=False, maxheaderlen=78)
g.flatten(message,unixfrom=False)
outfile.close()
except:
txt=botslib.txtexc()
ta_to.update(statust=ERROR,errortext=txt)
else:
counter += 1
ta_from.update(statust=DONE)
ta_to.update(statust=OK,filename=outfilename,confirmtype=confirmtype,confirmasked=confirmasked,charset=charset)
return counter
def mime2file(self,fromstatus,tostatus):
''' transfer communication-file from RAWIN to FILEIN, convert from Mime to file.
process mime-files:
- extract information (eg sender-address)
- do emailtransport-handling: generate MDN, process MDN
- save 'attachments' as files
- generate MDN if asked and OK from bots-configuration
'''
whitelist_multipart=['multipart/mixed','multipart/digest','multipart/signed','multipart/report','message/rfc822','multipart/alternative']
whitelist_major=['text','application']
blacklist_contenttype=['text/html','text/enriched','text/rtf','text/richtext','application/postscript']
def savemime(msg):
''' save contents of email as separate files.
is a nested function.
3x filtering:
- whitelist of multipart-contenttype
- whitelist of body-contentmajor
- blacklist of body-contentytpe
'''
nrmimesaved = 0
contenttype = msg.get_content_type()
if msg.is_multipart():
if contenttype in whitelist_multipart:
for part in msg.get_payload():
nrmimesaved += savemime(part)
else: #is not a multipart
if msg.get_content_maintype() not in whitelist_major or contenttype in blacklist_contenttype:
return 0
content = msg.get_payload(decode=True)
if not content or content.isspace():
return 0
charset=msg.get_content_charset('')
if not charset:
charset = self.channeldict['charset']
if self.userscript and hasattr(self.userscript,'accept_incoming_attachment'):
accept_attachment = botslib.runscript(self.userscript,self.scriptname,'accept_incoming_attachment',channeldict=self.channeldict,ta=ta_mime,charset=charset,content=content,contenttype=contenttype)
if accept_attachment == False:
return 0
ta_file = ta_mime.copyta(status=tostatus)
outfilename = str(ta_file.idta)
outfile = botslib.opendata(outfilename, 'wb')
outfile.write(content)
outfile.close()
nrmimesaved+=1
ta_file.update(statust=OK,
contenttype=contenttype,
charset=charset,
filename=outfilename)
return nrmimesaved
#*****************end of nested function savemime***************************
@botslib.log_session
def mdnreceive():
tmp = msg.get_param('reporttype')
if tmp is None or email.Utils.collapse_rfc2231_value(tmp)!='disposition-notification': #invalid MDN
raise botslib.CommunicationInError(_(u'Received email-MDN with errors.'))
for part in msg.get_payload():
if part.get_content_type()=='message/disposition-notification':
originalmessageid = part['original-message-id']
if originalmessageid is not None:
break
else: #invalid MDN: 'message/disposition-notification' not in email
raise botslib.CommunicationInError(_(u'Received email-MDN with errors.'))
botslib.change('''UPDATE ta
SET confirmed=%(confirmed)s, confirmidta=%(confirmidta)s
WHERE reference=%(reference)s
AND status=%(status)s
AND confirmasked=%(confirmasked)s
AND confirmtype=%(confirmtype)s
''',
{'status':RAWOUT,'reference':originalmessageid,'confirmed':True,'confirmtype':'ask-email-MDN','confirmidta':ta_mail.idta,'confirmasked':True})
#for now no checking if processing was OK.....
#performance: not good. Another way is to extract the original idta from the original messageid
@botslib.log_session
def mdnsend():
if not botslib.checkconfirmrules('send-email-MDN',idroute=self.idroute,idchannel=self.channeldict['idchannel'],
frompartner=frompartner,topartner=topartner):
return 0 #do not send
#make message
message = email.Message.Message()
message.add_header('From',tomail)
dispositionnotificationto = email.Utils.parseaddr(msg['disposition-notification-to'])[1]
message.add_header('To', dispositionnotificationto)
message.add_header('Subject', 'Return Receipt (displayed) - '+subject)
message.add_header("Date", email.Utils.formatdate(localtime=True))
message.add_header('MIME-Version','1.0')
message.add_header('Content-Type','multipart/report',reporttype='disposition-notification')
#~ message.set_type('multipart/report')
#~ message.set_param('reporttype','disposition-notification')
#make human readable message
humanmessage = email.Message.Message()
humanmessage.add_header('Content-Type', 'text/plain')
humanmessage.set_payload('This is an return receipt for the mail that you send to '+tomail)
message.attach(humanmessage)
#make machine readable message
machinemessage = email.Message.Message()
machinemessage.add_header('Content-Type', 'message/disposition-notification')
machinemessage.add_header('Original-Message-ID', reference)
nep = email.Message.Message()
machinemessage.attach(nep)
message.attach(machinemessage)
#write email to file;
ta_mdn=botslib.NewTransaction(status=MERGED) #new transaction for group-file
mdn_reference = email.Utils.make_msgid(str(ta_mdn.idta)) #we first have to get the mda-ta to make this reference
message.add_header('Message-ID', mdn_reference)
mdnfilename = str(ta_mdn.idta)
mdnfile = botslib.opendata(mdnfilename, 'wb')
g = email.Generator.Generator(mdnfile, mangle_from_=False, maxheaderlen=78)
g.flatten(message,unixfrom=False)
mdnfile.close()
ta_mdn.update(statust=OK,
idroute=self.idroute,
filename=mdnfilename,
editype='email-confirmation',
frompartner=topartner,
topartner=frompartner,
frommail=tomail,
tomail=dispositionnotificationto,
reference=mdn_reference,
content='multipart/report',
fromchannel=self.channeldict['idchannel'],
charset='ascii')
return ta_mdn.idta
#*****************end of nested function dispositionnotification***************************
#select received mails for channel
for row in botslib.query('''SELECT idta,filename
FROM ta
WHERE idta>%(rootidta)s
AND status=%(status)s
AND statust=%(statust)s
AND fromchannel=%(fromchannel)s
''',
{'status':fromstatus,'statust':OK,'rootidta':botslib.get_minta4query(),
'fromchannel':self.channeldict['idchannel'],'idroute':self.idroute}):
try:
confirmtype = ''
confirmed = False
confirmasked = False
confirmidta = 0
ta_mail = botslib.OldTransaction(row['idta'])
ta_mime = ta_mail.copyta(status=MIMEIN)
infile = botslib.opendata(row['filename'], 'rb')
msg = email.message_from_file(infile) #read and parse mail
infile.close()
frommail = email.Utils.parseaddr(msg['from'])[1]
tos = email.Utils.getaddresses(msg.get_all('to', []))
ccs = email.Utils.getaddresses(msg.get_all('cc', []))
#~ tomail = tos[0][1] #tomail is the email address of the first "To"-recipient
cc = ','.join([emailaddress[1] for emailaddress in (tos + ccs)])
reference = msg['message-id']
subject = msg['subject']
contenttype = msg.get_content_type()
#authorize: find the frompartner for the email addresses in the message
frompartner = ''
if not self.channeldict['starttls']: #reusing old database name; 'no check on "from:" email adress'
frompartner = self.mailaddress2idpartner(frommail)
topartner = '' #initialise topartner
tomail = '' #initialise tomail
if not self.channeldict['apop']: #reusing old database name; 'no check on "to:" email adress'
for toname,tomail_tmp in tos: #all tos-addresses are checked; only one needs to be authorised.
try:
topartner = self.mailaddress2idpartner(tomail_tmp)
tomail = tomail_tmp
break
except botslib.CommunicationInError:
pass
else:
if not topartner:
emailtos = [address[1] for address in tos]
raise botslib.CommunicationInError(_(u'Emailaddress(es) $email not authorised/unknown (channel "$idchannel").'),email=emailtos,idchannel=self.channeldict['idchannel'])
#update transaction of mail with information found in mail
ta_mime.update(frommail=frommail, #why now why not later: because ta_mime is copied to separate files later, so need the info now
tomail=tomail,
reference=reference,
contenttype=contenttype,
frompartner=frompartner,
topartner=topartner,
cc = cc)
if contenttype == 'multipart/report': #process received MDN confirmation
mdnreceive()
else:
if msg.has_key('disposition-notification-To'): #sender requests a MDN
confirmidta = mdnsend()
if confirmidta:
confirmtype = 'send-email-MDN'
confirmed = True
confirmasked = True
nrmimesaved = savemime(msg)
if not nrmimesaved:
raise botslib.CommunicationInError (_(u'No valid attachment in received email'))
except:
txt=botslib.txtexc()
ta_mime.failure()
ta_mime.update(statust=ERROR,errortext=txt)
else:
ta_mime.update(statust=DONE)
ta_mail.update(statust=DONE,confirmtype=confirmtype,confirmed=confirmed,confirmasked=confirmasked,confirmidta=confirmidta)
return 0 #is not useful, as mime2file is used in postcommunication, and #files processed is not checked in postcommunication.
def mailaddress2idpartner(self,mailaddress):
for row in botslib.query(u'''SELECT chanpar.idpartner_id as idpartner
FROM chanpar,channel,partner
WHERE chanpar.idchannel_id=channel.idchannel
AND chanpar.idpartner_id=partner.idpartner
AND partner.active=%(active)s
AND chanpar.idchannel_id=%(idchannel)s
AND LOWER(chanpar.mail)=%(mail)s''',
{'active':True,'idchannel':self.channeldict['idchannel'],'mail':mailaddress.lower()}):
return row['idpartner']
else: #if not found
for row in botslib.query(u'''SELECT idpartner
FROM partner
WHERE active=%(active)s
AND LOWER(mail)=%(mail)s''',
{'active':True,'mail':mailaddress.lower()}):
return row['idpartner']
raise botslib.CommunicationInError(_(u'Emailaddress "$email" unknown (or not authorised for channel "$idchannel").'),email=mailaddress,idchannel=self.channeldict['idchannel'])
def idpartner2mailaddress(self,idpartner):
for row in botslib.query(u'''SELECT chanpar.mail as mail,chanpar.cc as cc
FROM chanpar,channel,partner
WHERE chanpar.idchannel_id=channel.idchannel
AND chanpar.idpartner_id=partner.idpartner
AND partner.active=%(active)s
AND chanpar.idchannel_id=%(idchannel)s
AND chanpar.idpartner_id=%(idpartner)s''',
{'active':True,'idchannel':self.channeldict['idchannel'],'idpartner':idpartner}):
if row['mail']:
return row['mail'],row['cc']
else: #if not found
for row in botslib.query(u'''SELECT mail,cc
FROM partner
WHERE active=%(active)s
AND idpartner=%(idpartner)s''',
{'active':True,'idpartner':idpartner}):
if row['mail']:
return row['mail'],row['cc']
else:
raise botslib.CommunicationOutError(_(u'No mail-address for partner "$partner" (channel "$idchannel").'),partner=idpartner,idchannel=self.channeldict['idchannel'])
def connect(self):
pass
def disconnect(self):
pass
@staticmethod
def convertcodecformime(codec_in):
convertdict = {
'ascii' : 'us-ascii',
'unoa' : 'us-ascii',
'unob' : 'us-ascii',
'unoc' : 'iso-8859-1',
}
codec_in = codec_in.lower().replace('_','-')
return convertdict.get(codec_in,codec_in)
class pop3(_comsession):
def connect(self):
self.session = poplib.POP3(host=self.channeldict['host'],port=int(self.channeldict['port']))
self.session.set_debuglevel(botsglobal.ini.getint('settings','pop3debug',0)) #if used, gives information about session (on screen), for debugging pop3
self.session.user(self.channeldict['username'])
self.session.pass_(self.channeldict['secret'])
@botslib.log_session
def incommunicate(self):
''' Fetch messages from Pop3-mailbox.
A bad connection is tricky, because mails are actually deleted on the server when QUIT is successful.
A solution would be to connect, fetch, delete and quit for each mail, but this might introduce other problems.
So: keep a list of idta received OK.
If QUIT is not successful than delete these ta's
'''
self.listoftamarkedfordelete = []
maillist = self.session.list()[1] #get list of messages #alt: (response, messagelist, octets) = popsession.list() #get list of messages
startdatetime = datetime.datetime.now()
for mail in maillist:
try:
ta_from = botslib.NewTransaction(filename='pop3://'+self.channeldict['username']+'@'+self.channeldict['host'],
status=EXTERNIN,
fromchannel=self.channeldict['idchannel'],idroute=self.idroute)
ta_to = ta_from.copyta(status=RAWIN)
filename = str(ta_to.idta)
mailID = int(mail.split()[0]) #first 'word' is the message number/ID
maillines = self.session.retr(mailID)[1] #alt: (header, messagelines, octets) = popsession.retr(messageID)
fp = botslib.opendata(filename, 'wb')
fp.write(os.linesep.join(maillines))
fp.close()
if self.channeldict['remove']: #on server side mail is marked to be deleted. The pop3-server will actually delete the file if the QUIT commnd is receieved!
self.session.dele(mailID)
#add idta's of received mail in a list. If connection is not OK, QUIT command to POP3 server will not work. delete these as they will NOT
self.listoftamarkedfordelete += [ta_from.idta,ta_to.idta]
except: #something went wrong for this mail.
txt=botslib.txtexc()
botslib.ErrorProcess(functionname='pop3-incommunicate',errortext=txt,channeldict=self.channeldict)
ta_from.delete()
ta_to.delete()
#test connection. if connection is not OK stop fetching mails.
try:
self.session.noop()
except:
self.session = None #indicate session is not valid anymore
break
else:
ta_from.update(statust=DONE)
ta_to.update(statust=OK,filename=filename)
finally:
if (datetime.datetime.now()-startdatetime).seconds >= self.maxsecondsperchannel:
break
def disconnect(self):
try:
if not self.session:
raise botslib.CommunicationInError(_(u'Pop3 connection not OK'))
resp = self.session.quit() #pop3 server will now actually delete the mails
if resp[:1] != '+':
raise botslib.CommunicationInError(_(u'QUIT command to POP3 server failed'))
except:
botslib.ErrorProcess(functionname='pop3-incommunicate',errortext='Could not fetch emails via POP3; probably communication problems',channeldict=self.channeldict)
for idta in self.listoftamarkedfordelete:
ta = botslib.OldTransaction(idta)
ta.delete()
@botslib.log_session
def postcommunicate(self,fromstatus,tostatus):
self.mime2file(fromstatus,tostatus)
class pop3s(pop3):
def connect(self):
self.session = poplib.POP3_SSL(host=self.channeldict['host'],port=int(self.channeldict['port']))
self.session.set_debuglevel(botsglobal.ini.getint('settings','pop3debug',0)) #if used, gives information about session (on screen), for debugging pop3
self.session.user(self.channeldict['username'])
self.session.pass_(self.channeldict['secret'])
class pop3apop(pop3):
def connect(self):
self.session = poplib.POP3(host=self.channeldict['host'],port=int(self.channeldict['port']))
self.session.set_debuglevel(botsglobal.ini.getint('settings','pop3debug',0)) #if used, gives information about session (on screen), for debugging pop3
self.session.apop(self.channeldict['username'],self.channeldict['secret']) #python handles apop password encryption
class imap4(_comsession):
''' Fetch email from IMAP server.
'''
def connect(self):
imaplib.Debug = botsglobal.ini.getint('settings','imap4debug',0) #if used, gives information about session (on screen), for debugging imap4
self.session = imaplib.IMAP4(host=self.channeldict['host'],port=int(self.channeldict['port']))
self.session.login(self.channeldict['username'],self.channeldict['secret'])
@botslib.log_session
def incommunicate(self):
''' Fetch messages from imap4-mailbox.
'''
# path may contain a mailbox name, otherwise use INBOX
if self.channeldict['path']:
mailbox_name = self.channeldict['path']
else:
mailbox_name = 'INBOX'
response, data = self.session.select(mailbox_name)
if response != 'OK': # eg. mailbox does not exist
raise botslib.CommunicationError(mailbox_name + ': ' + data[0])
# Get the message UIDs that should be read
response, data = self.session.uid('search', None, '(UNDELETED)')
if response != 'OK': # have never seen this happen, but just in case!
raise botslib.CommunicationError(mailbox_name + ': ' + data[0])
maillist = data[0].split()
startdatetime = datetime.datetime.now()
for mail in maillist:
try:
ta_from = botslib.NewTransaction(filename='imap4://'+self.channeldict['username']+'@'+self.channeldict['host'],
status=EXTERNIN,
fromchannel=self.channeldict['idchannel'],idroute=self.idroute)
ta_to = ta_from.copyta(status=RAWIN)
filename = str(ta_to.idta)
# Get the message (header and body)
response, msg_data = self.session.uid('fetch',mail, '(RFC822)')
fp = botslib.opendata(filename, 'wb')
fp.write(msg_data[0][1])
fp.close()
# Flag message for deletion AND expunge. Direct expunge has advantages for bad (internet)connections.
if self.channeldict['remove']:
self.session.uid('store',mail, '+FLAGS', r'(\Deleted)')
self.session.expunge()
except:
txt=botslib.txtexc()
botslib.ErrorProcess(functionname='imap4-incommunicate',errortext=txt,channeldict=self.channeldict)
ta_from.delete()
ta_to.delete()
else:
ta_from.update(statust=DONE)
ta_to.update(statust=OK,filename=filename)
finally:
if (datetime.datetime.now()-startdatetime).seconds >= self.maxsecondsperchannel:
break
@botslib.log_session
def postcommunicate(self,fromstatus,tostatus):
self.mime2file(fromstatus,tostatus)
def disconnect(self):
self.session.close() #Close currently selected mailbox. This is the recommended command before 'LOGOUT'.
self.session.logout()
class imap4s(imap4):
def connect(self):
imaplib.Debug = botsglobal.ini.getint('settings','imap4debug',0) #if used, gives information about session (on screen), for debugging imap4
self.session = imaplib.IMAP4_SSL(host=self.channeldict['host'],port=int(self.channeldict['port']))
self.session.login(self.channeldict['username'],self.channeldict['secret'])
class smtp(_comsession):
@botslib.log_session
def precommunicate(self,fromstatus,tostatus):
return self.file2mime(fromstatus,tostatus)
def connect(self):
self.session = smtplib.SMTP(host=self.channeldict['host'],port=int(self.channeldict['port'])) #make connection
self.session.set_debuglevel(botsglobal.ini.getint('settings','smtpdebug',0)) #if used, gives information about session (on screen), for debugging smtp
self.login()
def login(self):
if self.channeldict['username'] and self.channeldict['secret']:
try:
#error in python 2.6.4....user and password can not be unicode
self.session.login(str(self.channeldict['username']),str(self.channeldict['secret']))
except smtplib.SMTPAuthenticationError:
raise botslib.CommunicationOutError(_(u'SMTP server did not accept user/password combination.'))
except:
txt=botslib.txtexc()
raise botslib.CommunicationOutError(_(u'SMTP login failed. Error:\n$txt'),txt=txt)
@botslib.log_session
def outcommunicate(self):
''' does smtp-session.
SSL/TLS supported (no keys-file/cert-file supported yet)
SMTP does not allow rollback. So if the sending of a mail fails, other mails may have been send.
'''
#send messages
for row in botslib.query(u'''SELECT idta,filename,frommail,tomail,cc
FROM ta
WHERE idta>%(rootidta)s
AND status=%(status)s
AND statust=%(statust)s
AND tochannel=%(tochannel)s
''',
{'status':RAWOUT,'statust':OK,'rootidta':botslib.get_minta4query(),
'tochannel':self.channeldict['idchannel']}):
try:
ta_from = botslib.OldTransaction(row['idta'])
ta_to = ta_from.copyta(status=EXTERNOUT)
addresslist = [x for x in (row['tomail'],row['cc']) if x]
sendfile = botslib.opendata(row['filename'], 'rb')
msg = sendfile.read()
sendfile.close()
self.session.sendmail(row['frommail'], addresslist, msg)
except:
txt=botslib.txtexc()
ta_to.update(statust=ERROR,errortext=txt,filename='smtp://'+self.channeldict['username']+'@'+self.channeldict['host'])
else:
ta_from.update(statust=DONE)
ta_to.update(statust=DONE,filename='smtp://'+self.channeldict['username']+'@'+self.channeldict['host'])
def disconnect(self):
try: #Google gives/gave error closing connection. Not a real problem.
self.session.quit()
except:
pass
class smtps(smtp):
def connect(self):
if hasattr(smtplib,'SMTP_SSL'):
self.session = smtplib.SMTP_SSL(host=self.channeldict['host'],port=int(self.channeldict['port'])) #make connection
else: #smtp_ssl not in standard lib for python<=2.5; if not, use 'own' smtps module.
import bots.smtpssllib as smtpssllib
self.session = smtpssllib.SMTP_SSL(host=self.channeldict['host'],port=int(self.channeldict['port'])) #make connection
self.session.set_debuglevel(botsglobal.ini.getint('settings','smtpdebug',0)) #if used, gives information about session (on screen), for debugging smtp
self.login()
class smtpstarttls(smtp):
def connect(self):
self.session = smtplib.SMTP(host=self.channeldict['host'],port=int(self.channeldict['port'])) #make connection
self.session.set_debuglevel(botsglobal.ini.getint('settings','smtpdebug',0)) #if used, gives information about session (on screen), for debugging smtp
self.session.ehlo()
self.session.starttls()
self.session.ehlo()
self.login()
class file(_comsession):
def connect(self):
if self.channeldict['lockname']: #directory locking: create lock-file. If the lockfile is already present an exception is raised.
lockname = botslib.join(self.channeldict['path'],self.channeldict['lockname'])
lock = os.open(lockname,os.O_WRONLY | os.O_CREAT | os.O_EXCL)
os.close(lock)
@botslib.log_session
def incommunicate(self):
''' gets files from filesystem. To be used via receive-dispatcher.
each to be imported file is transaction.
each imported file is transaction.
IF error in importing: imported files are either OK or ERROR.
what could not be imported is not removed
'''
frompath = botslib.join(self.channeldict['path'],self.channeldict['filename'])
#fetch messages from filesystem.
startdatetime = datetime.datetime.now()
for fromfilename in [c for c in glob.glob(frompath) if os.path.isfile(c)]:
try:
ta_from = botslib.NewTransaction(filename=fromfilename,
status=EXTERNIN,
fromchannel=self.channeldict['idchannel'],
charset=self.channeldict['charset'],idroute=self.idroute)
ta_to = ta_from.copyta(status=RAWIN)
#open fromfile, syslock if indicated
fromfile = open(fromfilename,'rb')
if self.channeldict['syslock']:
if os.name == 'nt':
msvcrt.locking(fromfile.fileno(), msvcrt.LK_LOCK, 0x0fffffff)
elif os.name == 'posix':
fcntl.lockf(fromfile.fileno(), fcntl.LOCK_SH|fcntl.LOCK_NB)
else:
raise botslib.LockedFileError(_(u'Can not do a systemlock on this platform'))
#open tofile
tofilename = str(ta_to.idta)
tofile = botslib.opendata(tofilename, 'wb')
#copy
shutil.copyfileobj(fromfile,tofile)
fromfile.close()
tofile.close()
if self.channeldict['remove']:
os.remove(fromfilename)
except:
txt=botslib.txtexc()
botslib.ErrorProcess(functionname='file-incommunicate',errortext=txt,channeldict=self.channeldict)
ta_from.delete()
ta_to.delete()
else:
ta_from.update(statust=DONE)
ta_to.update(filename=tofilename,statust=OK)
finally:
if (datetime.datetime.now()-startdatetime).seconds >= self.maxsecondsperchannel:
break
@botslib.log_session
def outcommunicate(self):
''' does output of files to filesystem. To be used via send-dispatcher.
Output is either:
1. 1 outputfile, messages are appended; filename is a fixed name
2. to directory; new file for each db-ta; if file exits: overwrite. File has to have a unique name.
'''
#check if output dir exists, else create it.
outputdir = botslib.join(self.channeldict['path'])
botslib.dirshouldbethere(outputdir)
#output to one file or a queue of files (with unique names)
if not self.channeldict['filename'] or '*' not in self.channeldict['filename']:
mode = 'ab' #fixed filename; not unique: append to file
else:
mode = 'wb' #unique filenames; (over)write
#select the db-ta's for this channel
for row in botslib.query(u'''SELECT idta,filename,charset
FROM ta
WHERE idta>%(rootidta)s
AND status=%(status)s
AND statust=%(statust)s
AND tochannel=%(tochannel)s
''',
{'tochannel':self.channeldict['idchannel'],'rootidta':botslib.get_minta4query(),
'status':RAWOUT,'statust':OK}):
try: #for each db-ta:
ta_from = botslib.OldTransaction(row['idta'])
ta_to = ta_from.copyta(status=EXTERNOUT)
botslib.checkcodeciscompatible(row['charset'],self.channeldict['charset'])
#open tofile, incl syslock if indicated
unique = str(botslib.unique(self.channeldict['idchannel'])) #create unique part for filename
if self.channeldict['filename']:
filename = self.channeldict['filename'].replace('*',unique) #filename is filename in channel where '*' is replaced by idta
else:
filename = unique
if self.userscript and hasattr(self.userscript,'filename'):
filename = botslib.runscript(self.userscript,self.scriptname,'filename',channeldict=self.channeldict,filename=filename,ta=ta_from)
tofilename = botslib.join(outputdir,filename)
tofile = open(tofilename, mode)
if self.channeldict['syslock']:
if os.name == 'nt':
msvcrt.locking(tofile.fileno(), msvcrt.LK_LOCK, 0x0fffffff)
elif os.name == 'posix':
fcntl.lockf(tofile.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB)
else:
raise botslib.LockedFileError(_(u'Can not do a systemlock on this platform'))
#open fromfile
fromfile = botslib.opendata(row['filename'], 'rb')
#copy
shutil.copyfileobj(fromfile,tofile)
fromfile.close()
tofile.close()
except:
txt=botslib.txtexc()
ta_to.update(statust=ERROR,errortext=txt)
else:
ta_from.update(statust=DONE)
ta_to.update(statust=DONE,filename=tofilename)
def disconnect(self):
#delete directory-lockfile
if self.channeldict['lockname']:
os.remove(lockname)
class mimefile(file):
@botslib.log_session
def postcommunicate(self,fromstatus,tostatus):
self.mime2file(fromstatus,tostatus)
@botslib.log_session
def precommunicate(self,fromstatus,tostatus):
return self.file2mime(fromstatus,tostatus)
class ftp(_comsession):
def connect(self):
botslib.settimeout(botsglobal.ini.getint('settings','ftptimeout',10))
self.session = ftplib.FTP()
self.session.set_debuglevel(botsglobal.ini.getint('settings','ftpdebug',0)) #set debug level (0=no, 1=medium, 2=full debug)
self.session.set_pasv(not self.channeldict['ftpactive']) #active or passive ftp
self.session.connect(host=self.channeldict['host'],port=int(self.channeldict['port']))
self.session.login(user=self.channeldict['username'],passwd=self.channeldict['secret'],acct=self.channeldict['ftpaccount'])
self.set_cwd()
def set_cwd(self):
self.dirpath = self.session.pwd()
if self.channeldict['path']:
self.dirpath = posixpath.normpath(posixpath.join(self.dirpath,self.channeldict['path']))
try:
self.session.cwd(self.dirpath) #set right path on ftp-server
except:
self.session.mkd(self.dirpath) #set right path on ftp-server; no nested directories
self.session.cwd(self.dirpath) #set right path on ftp-server
@botslib.log_session
def incommunicate(self):
''' do ftp: receive files. To be used via receive-dispatcher.
each to be imported file is transaction.
each imported file is transaction.
'''
startdatetime = datetime.datetime.now()
files = []
try: #some ftp servers give errors when directory is empty; catch these errors here
files = self.session.nlst()
except (ftplib.error_perm,ftplib.error_temp),resp:
if str(resp)[:3] not in ['550','450']:
raise
lijst = fnmatch.filter(files,self.channeldict['filename'])
for fromfilename in lijst: #fetch messages from ftp-server.
try:
ta_from = botslib.NewTransaction(filename='ftp:/'+posixpath.join(self.dirpath,fromfilename),
status=EXTERNIN,
fromchannel=self.channeldict['idchannel'],
charset=self.channeldict['charset'],idroute=self.idroute)
ta_to = ta_from.copyta(status=RAWIN)
tofilename = str(ta_to.idta)
tofile = botslib.opendata(tofilename, 'wb')
try:
if self.channeldict['ftpbinary']:
self.session.retrbinary("RETR " + fromfilename, tofile.write)
else:
self.session.retrlines("RETR " + fromfilename, lambda s, w=tofile.write: w(s+"\n"))
except ftplib.error_perm, resp:
if str(resp)[:3] in ['550',]: #we are trying to download a directory...
raise botslib.BotsError(u'To be catched')
else:
raise
tofile.close()
filesize = os.path.getsize(botslib.abspathdata(tofilename))
if not filesize:
raise botslib.BotsError(u'To be catched')
if self.channeldict['remove']:
self.session.delete(fromfilename)
except botslib.BotsError: #catch this exception and handle it
tofile.close()
ta_from.delete()
ta_to.delete()
except:
tofile.close()
txt=botslib.txtexc()
botslib.ErrorProcess(functionname='ftp-incommunicate',errortext=txt,channeldict=self.channeldict)
ta_from.delete()
ta_to.delete()
else:
ta_from.update(statust=DONE)
ta_to.update(filename=tofilename,statust=OK)
finally:
if (datetime.datetime.now()-startdatetime).seconds >= self.maxsecondsperchannel:
break
@botslib.log_session
def outcommunicate(self):
''' do ftp: send files. To be used via receive-dispatcher.
each to be send file is transaction.
each send file is transaction.
NB: ftp command APPE should be supported by server
'''
#check if one file or queue of files with unique names
if not self.channeldict['filename'] or '*'not in self.channeldict['filename']:
mode = 'APPE ' #fixed filename; not unique: append to file
else:
mode = 'STOR ' #unique filenames; (over)write
for row in botslib.query('''SELECT idta,filename,charset
FROM ta
WHERE idta>%(rootidta)s
AND status=%(status)s
AND statust=%(statust)s
AND tochannel=%(tochannel)s
''',
{'tochannel':self.channeldict['idchannel'],'rootidta':botslib.get_minta4query(),
'status':RAWOUT,'statust':OK}):
try:
ta_from = botslib.OldTransaction(row['idta'])
ta_to = ta_from.copyta(status=EXTERNOUT)
unique = str(botslib.unique(self.channeldict['idchannel'])) #create unique part for filename
if self.channeldict['filename']:
tofilename = self.channeldict['filename'].replace('*',unique) #filename is filename in channel where '*' is replaced by idta
else:
tofilename = unique
if self.userscript and hasattr(self.userscript,'filename'):
tofilename = botslib.runscript(self.userscript,self.scriptname,'filename',channeldict=self.channeldict,filename=tofilename,ta=ta_from)
if self.channeldict['ftpbinary']:
botslib.checkcodeciscompatible(row['charset'],self.channeldict['charset'])
fromfile = botslib.opendata(row['filename'], 'rb')
self.session.storbinary(mode + tofilename, fromfile)
else:
#~ self.channeldict['charset'] = 'us-ascii'
botslib.checkcodeciscompatible(row['charset'],self.channeldict['charset'])
fromfile = botslib.opendata(row['filename'], 'r')
self.session.storlines(mode + tofilename, fromfile)
fromfile.close()
except:
txt=botslib.txtexc()
ta_to.update(statust=ERROR,errortext=txt,filename='ftp:/'+posixpath.join(self.dirpath,tofilename))
else:
ta_from.update(statust=DONE)
ta_to.update(statust=DONE,filename='ftp:/'+posixpath.join(self.dirpath,tofilename))
def disconnect(self):
try:
self.session.quit()
except:
self.session.close()
botslib.settimeout(botsglobal.ini.getint('settings','globaltimeout',10))
class ftps(ftp):
''' explicit ftps as defined in RFC 2228 and RFC 4217.
standard port to connect to is as in normal FTP (port 21)
ftps is supported by python >= 2.7
'''
def connect(self):
botslib.settimeout(botsglobal.ini.getint('settings','ftptimeout',10))
if not hasattr(ftplib,'FTP_TLS'):
raise botslib.CommunicationError(_(u'ftps is not supported by your python version, use >=2.7'))
self.session = ftplib.FTP_TLS()
self.session.set_debuglevel(botsglobal.ini.getint('settings','ftpdebug',0)) #set debug level (0=no, 1=medium, 2=full debug)
self.session.set_pasv(not self.channeldict['ftpactive']) #active or passive ftp
self.session.connect(host=self.channeldict['host'],port=int(self.channeldict['port']))
#support key files (PEM, cert)?
self.session.auth()
self.session.login(user=self.channeldict['username'],passwd=self.channeldict['secret'],acct=self.channeldict['ftpaccount'])
self.session.prot_p()
self.set_cwd()
#sub classing of ftplib for ftpis
if hasattr(ftplib,'FTP_TLS'):
class FTP_TLS_IMPLICIT(ftplib.FTP_TLS):
''' FTPS implicit is not directly supported by python; python>=2.7 supports only ftps explicit.
So class ftplib.FTP_TLS is sub-classed here, with the needed modifications.
(code is nicked from ftplib.ftp v. 2.7; additions/changes are indicated)
'''
def connect(self, host='', port=0, timeout=-999):
#added hje 20110713: directly use SSL in FTPIS
import socket
import ssl
#end added
if host != '':
self.host = host
if port > 0:
self.port = port
if timeout != -999:
self.timeout = timeout
self.sock = socket.create_connection((self.host, self.port), self.timeout)
self.af = self.sock.family
#added hje 20110713: directly use SSL in FTPIS
self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile,ssl_version=self.ssl_version)
#end added
self.file = self.sock.makefile('rb')
self.welcome = self.getresp()
return self.welcome
def prot_p(self):
#Inovis FTPIS gives errors on 'PBSZ 0' and 'PROT P', vsftp does not work without these commands.
#These errors are just catched, nothing is done with them.
try:
self.voidcmd('PBSZ 0')
except ftplib.error_perm:
pass
try:
resp = self.voidcmd('PROT P')
except ftplib.error_perm:
resp = None
self._prot_p = True
return resp
class ftpis(ftp):
''' FTPS implicit; is not defined in a RFC.
standard port to connect is port 990.
FTPS implicit is not supported by python.
python>=2.7 supports ftps explicit.
So used is the sub-class FTP_TLS_IMPLICIT.
Tested with Inovis and VSFTPd.
Python library FTP_TLS uses ssl_version = ssl.PROTOCOL_TLSv1
Inovis seems to need PROTOCOL_SSLv3
This is 'solved' by using 'parameters' in the channel.
~ ssl.PROTOCOL_SSLv2 = 0
~ ssl.PROTOCOL_SSLv3 = 1
~ ssl.PROTOCOL_SSLv23 = 2
~ ssl.PROTOCOL_TLSv1 = 3
'''
def connect(self):
botslib.settimeout(botsglobal.ini.getint('settings','ftptimeout',10))
if not hasattr(ftplib,'FTP_TLS'):
raise botslib.CommunicationError(_(u'ftpis is not supported by your python version, use >=2.7'))
self.session = FTP_TLS_IMPLICIT()
if self.channeldict['parameters']:
self.session.ssl_version = int(self.channeldict['parameters'])
self.session.set_debuglevel(botsglobal.ini.getint('settings','ftpdebug',0)) #set debug level (0=no, 1=medium, 2=full debug)
self.session.set_pasv(not self.channeldict['ftpactive']) #active or passive ftp
self.session.connect(host=self.channeldict['host'],port=int(self.channeldict['port']))
#support key files (PEM, cert)?
#~ self.session.auth()
self.session.login(user=self.channeldict['username'],passwd=self.channeldict['secret'],acct=self.channeldict['ftpaccount'])
self.session.prot_p()
self.set_cwd()
class sftp(_comsession):
''' SSH File Transfer Protocol (SFTP is not FTP run over SSH, SFTP is not Simple File Transfer Protocol)
standard port to connect to is port 22.
requires paramiko and pycrypto to be installed
based on class ftp and ftps above with code from demo_sftp.py which is included with paramiko
Mike Griffin 16/10/2010
Henk-jan ebbers 20110802: when testing I found that the transport also needs to be closed. So changed transport ->self.transport, and close this in disconnect
henk-jan ebbers 20111019: disabled the host_key part for now (but is very interesting). Is not tested; keys should be integrated in bots also for other protocols.
'''
def connect(self):
# check dependencies
try:
import paramiko
except:
txt=botslib.txtexc()
raise ImportError(_(u'Dependency failure: communicationtype "sftp" requires python library "paramiko". Error:\n%s'%txt))
try:
from Crypto import Cipher
except:
txt=botslib.txtexc()
raise ImportError(_(u'Dependency failure: communicationtype "sftp" requires python library "pycrypto". Error:\n%s'%txt))
# setup logging if required
ftpdebug = botsglobal.ini.getint('settings','ftpdebug',0)
if ftpdebug > 0:
log_file = botslib.join(botsglobal.ini.get('directories','logging'),'sftp.log')
# Convert ftpdebug to paramiko logging level (1=20=info, 2=10=debug)
paramiko.util.log_to_file(log_file, 30-(ftpdebug*10))
# Get hostname and port to use
hostname = self.channeldict['host']
try:
port = int(self.channeldict['port'])
except:
port = 22 # default port for sftp
# get host key, if we know one
# (I have not tested this, just copied from demo)
hostkeytype = None
hostkey = None
#~ try:
#~ host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
#~ except IOError:
#~ try: # try ~/ssh/ too, because windows can't have a folder named ~/.ssh/
#~ host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts'))
#~ except IOError:
#~ host_keys = {}
#~ botsglobal.logger.debug(u'No host keys found for sftp')
#~ if host_keys.has_key(hostname):
#~ hostkeytype = host_keys[hostname].keys()[0]
#~ hostkey = host_keys[hostname][hostkeytype]
#~ botsglobal.logger.debug(u'Using host key of type "%s" for sftp',hostkeytype)
# now, connect and use paramiko Transport to negotiate SSH2 across the connection
self.transport = paramiko.Transport((hostname,port))
self.transport.connect(username=self.channeldict['username'],password=self.channeldict['secret'],hostkey=hostkey)
self.session = paramiko.SFTPClient.from_transport(self.transport)
channel = self.session.get_channel()
channel.settimeout(botsglobal.ini.getint('settings','ftptimeout',10))
self.session.chdir('.') # getcwd does not work without this chdir first!
self.dirpath = self.session.getcwd()
#set right path on ftp-server
if self.channeldict['path']:
self.dirpath = posixpath.normpath(posixpath.join(self.dirpath,self.channeldict['path']))
try:
self.session.chdir(self.dirpath)
except:
self.session.mkdir(self.dirpath)
self.session.chdir(self.dirpath)
def disconnect(self):
self.session.close()
self.transport.close()
@botslib.log_session
def incommunicate(self):
''' do ftp: receive files. To be used via receive-dispatcher.
each to be imported file is transaction.
each imported file is transaction.
'''
startdatetime = datetime.datetime.now()
files = self.session.listdir('.')
lijst = fnmatch.filter(files,self.channeldict['filename'])
for fromfilename in lijst: #fetch messages from sftp-server.
try:
ta_from = botslib.NewTransaction(filename='sftp:/'+posixpath.join(self.dirpath,fromfilename),
status=EXTERNIN,
fromchannel=self.channeldict['idchannel'],
charset=self.channeldict['charset'],idroute=self.idroute)
ta_to = ta_from.copyta(status=RAWIN)
tofilename = str(ta_to.idta)
# SSH treats all files as binary
tofile = botslib.opendata(tofilename, 'wb')
tofile.write(self.session.open(fromfilename, 'r').read())
tofile.close()
if self.channeldict['remove']:
self.session.remove(fromfilename)
except:
txt=botslib.txtexc()
botslib.ErrorProcess(functionname='sftp-incommunicate',errortext=txt,channeldict=self.channeldict)
ta_from.delete()
ta_to.delete()
else:
ta_from.update(statust=DONE)
ta_to.update(filename=tofilename,statust=OK)
finally:
if (datetime.datetime.now()-startdatetime).seconds >= self.maxsecondsperchannel:
break
@botslib.log_session
def outcommunicate(self):
''' do ftp: send files. To be used via receive-dispatcher.
each to be send file is transaction.
each send file is transaction.
'''
#check if one file or queue of files with unique names
if not self.channeldict['filename'] or '*'not in self.channeldict['filename']:
mode = 'a' #fixed filename; not unique: append to file
else:
mode = 'w' #unique filenames; (over)write
for row in botslib.query('''SELECT idta,filename,charset
FROM ta
WHERE idta>%(rootidta)s
AND status=%(status)s
AND statust=%(statust)s
AND tochannel=%(tochannel)s
''',
{'tochannel':self.channeldict['idchannel'],'rootidta':botslib.get_minta4query(),
'status':RAWOUT,'statust':OK}):
try:
ta_from = botslib.OldTransaction(row['idta'])
ta_to = ta_from.copyta(status=EXTERNOUT)
unique = str(botslib.unique(self.channeldict['idchannel'])) #create unique part for filename
if self.channeldict['filename']:
tofilename = self.channeldict['filename'].replace('*',unique) #filename is filename in channel where '*' is replaced by idta
else:
tofilename = unique
if self.userscript and hasattr(self.userscript,'filename'):
tofilename = botslib.runscript(self.userscript,self.scriptname,'filename',channeldict=self.channeldict,filename=tofilename,ta=ta_from)
# SSH treats all files as binary
botslib.checkcodeciscompatible(row['charset'],self.channeldict['charset'])
fromfile = botslib.opendata(row['filename'], 'rb')
self.session.open(tofilename, mode).write(fromfile.read())
fromfile.close()
except:
txt=botslib.txtexc()
ta_to.update(statust=ERROR,errortext=txt,filename='sftp:/'+posixpath.join(self.dirpath,tofilename))
else:
ta_from.update(statust=DONE)
ta_to.update(statust=DONE,filename='sftp:/'+posixpath.join(self.dirpath,tofilename))
class xmlrpc(_comsession):
scheme = 'http'
def connect(self):
self.uri = botslib.Uri(scheme=self.scheme,username=self.channeldict['username'],password=self.channeldict['secret'],host=self.channeldict['host'],port=self.channeldict['port'],path=self.channeldict['path'])
self.session = xmlrpclib.ServerProxy(self.uri.uri)
@botslib.log_session
def outcommunicate(self):
''' do xml-rpc: send files. To be used via receive-dispatcher.
each to be send file is transaction.
each send file is transaction.
'''
for row in botslib.query('''SELECT idta,filename,charset
FROM ta
WHERE tochannel=%(tochannel)s
AND status=%(status)s
AND statust=%(statust)s
AND idta>%(rootidta)s
''',
{'tochannel':self.channeldict['idchannel'],'rootidta':botslib.get_minta4query(),
'status':RAWOUT,'statust':OK}):
try:
ta_from = botslib.OldTransaction(row['idta'])
ta_to = ta_from.copyta(status=EXTERNOUT)
botslib.checkcodeciscompatible(row['charset'],self.channeldict['charset'])
fromfile = botslib.opendata(row['fromfilename'], 'rb',row['charset'])
content = fromfile.read()
fromfile.close()
tocall = getattr(self.session,self.channeldict['filename'])
filename = tocall(content)
except:
txt=botslib.txtexc()
ta_to.update(statust=ERROR,errortext=txt)
else:
ta_from.update(statust=DONE)
ta_to.update(statust=DONE,filename=self.uri.update(path=self.channeldict['path'],filename=str(filename)))
@botslib.log_session
def incommunicate(self):
startdatetime = datetime.datetime.now()
while (True):
try:
tocall = getattr(self.session,self.channeldict['path'])
content = tocall()
if content is None:
break #nothing (more) to receive.
ta_from = botslib.NewTransaction(filename=self.uri.update(path=self.channeldict['path'],filename=self.channeldict['filename']),
status=EXTERNIN,
fromchannel=self.channeldict['idchannel'],
charset=self.channeldict['charset'],idroute=self.idroute)
ta_to = ta_from.copyta(status=RAWIN)
tofilename = str(ta_to.idta)
tofile = botslib.opendata(tofilename, 'wb')
simplejson.dump(content, tofile, skipkeys=False, ensure_ascii=False, check_circular=False)
tofile.close()
except:
txt=botslib.txtexc()
botslib.ErrorProcess(functionname='xmlprc-incommunicate',errortext=txt,channeldict=self.channeldict)
ta_from.delete()
ta_to.delete()
else:
ta_from.update(statust=DONE)
ta_to.update(filename=tofilename,statust=OK)
finally:
if (datetime.datetime.now()-startdatetime).seconds >= self.maxsecondsperchannel:
break
class intercommit(_comsession):
def connect(self):
#TODO: check if intercommit program is installed/reachable
pass
@botslib.log_session
def incommunicate(self):
botslib.runexternprogram(botsglobal.ini.get('intercommit','path'), '-R')
frompath = botslib.join(self.channeldict['path'],self.channeldict['filename'])
for fromheadername in [c for c in glob.glob(frompath) if os.path.isfile(c)]: #get intercommit xml-header
try:
#open db-ta's
ta_from = botslib.NewTransaction(filename=fromheadername,
status=EXTERNIN,
fromchannel=self.channeldict['idchannel'],
charset=self.channeldict['charset'],
idroute=self.idroute)
ta_to = ta_from.copyta(status=RAWIN)
#parse the intercommit 'header'-file (named *.edi)
self.parsestuurbestand(filename=fromheadername,charset=self.channeldict['charset'])
#convert parameters (mail-addresses to partners-ID's; flename)
self.p['frompartner'] = self.mailaddress2idpartner(self.p['frommail'])
self.p['topartner'] = self.mailaddress2idpartner(self.p['tomail'])
fromfilename = botslib.join(self.channeldict['path'],self.p['Attachment'])
self.p['filename'] = str(ta_to.idta)
#read/write files (xml=header is already done
fromfile = open(fromfilename,'rb')
tofile = botslib.opendata(self.p['filename'], 'wb')
shutil.copyfileobj(fromfile,tofile)
fromfile.close()
tofile.close()
if self.channeldict['remove']:
os.remove(fromfilename)
os.remove(fromheadername)
except:
txt=botslib.txtexc()
ta_from.update(statust=ERROR,errortext=txt,filename=fromfilename)
ta_to.delete()
else:
ta_from.update(statust=DONE,filename=fromfilename)
ta_to.update(statust=OK,**self.p)
def parsestuurbestand(self,filename,charset):
self.p = {}
edifile = inmessage.edifromfile(filename=filename,messagetype='intercommitenvelope',editype='xml',charset=charset)
for inn in edifile.nextmessage():
break
self.p['frommail'] = inn.get({'BOTSID':'Edicon'},{'BOTSID':'Header'},{'BOTSID':'From','BOTSCONTENT':None})
self.p['tomail'] = inn.get({'BOTSID':'Edicon'},{'BOTSID':'Header'},{'BOTSID':'To','BOTSCONTENT':None})
self.p['reference'] = inn.get({'BOTSID':'Edicon'},{'BOTSID':'Header'},{'BOTSID':'X-ClientMsgID','BOTSCONTENT':None})
self.p['Subject'] = inn.get({'BOTSID':'Edicon'},{'BOTSID':'Header'},{'BOTSID':'Subject','BOTSCONTENT':None})
self.p['Attachment'] = inn.get({'BOTSID':'Edicon'},{'BOTSID':'Body'},{'BOTSID':'Attachment','BOTSCONTENT':None})
@botslib.log_session
def outcommunicate(self):
#check if output dir exists, else create it.
dirforintercommitsend = botslib.join(self.channeldict['path'])
botslib.dirshouldbethere(dirforintercommitsend)
#output to one file or a queue of files (with unique names)
if not self.channeldict['filename'] or '*'not in self.channeldict['filename']:
raise botslib.CommunicationOutError(_(u'channel "$channel" needs unique filenames (no queue-file); use eg *.edi as value for "filename"'),channel=self.channeldict['idchannel'])
else:
mode = 'wb' #unique filenames; (over)write
#select the db-ta's for this channel
for row in botslib.query('''SELECT idta,filename,frompartner,topartner,charset
FROM ta
WHERE idta>%(rootidta)s
AND status=%(status)s
AND statust=%(statust)s
AND tochannel=%(idchannel)s
AND idroute=%(idroute)s
''',
{'idchannel':self.channeldict['idchannel'],'rootidta':botslib.get_minta4query(),
'status':RAWOUT,'statust':OK,'idroute':self.idroute}):
try: #for each db-ta:
ta_attr={} #ta_attr contains attributes used for updating ta
ta_from = botslib.OldTransaction(row['idta'])
ta_to = ta_from.copyta(status=EXTERNOUT)
#check encoding for outchannel
botslib.checkcodeciscompatible(row['charset'],self.channeldict['charset'])
#create unique for filenames of xml-header file and contentfile
uniquepart = str(botslib.unique(self.channeldict['idchannel'])) #create unique part for filenames
statusfilename = self.channeldict['filename'].replace('*',uniquepart) #filename is filename in channel where '*' is replaced by idta
statusfilenamewithpath = botslib.join(dirforintercommitsend,statusfilename)
(filenamewithoutext,ext)=os.path.splitext(statusfilename)
datafilename = filenamewithoutext + '.dat'
ta_attr['filename'] = botslib.join(dirforintercommitsend,datafilename)
ta_attr['frompartner'],nep = self.idpartner2mailaddress(row['frompartner'])
ta_attr['topartner'],nep = self.idpartner2mailaddress(row['topartner'])
ta_attr['reference'] = email.Utils.make_msgid(str(row['idta']))[1:-1] #[1:-1]: strip angle brackets
#create xml-headerfile
out = outmessage.outmessage_init(messagetype='intercommitenvelope',editype='xml',filename=statusfilenamewithpath) #make outmessage object
out.put({'BOTSID':'Edicon'},{'BOTSID':'Header'},{'BOTSID':'From','BOTSCONTENT':ta_attr['frompartner']})
out.put({'BOTSID':'Edicon'},{'BOTSID':'Header'},{'BOTSID':'To','BOTSCONTENT':ta_attr['topartner']})
out.put({'BOTSID':'Edicon'},{'BOTSID':'Header'},{'BOTSID':'Subject','BOTSCONTENT':ta_attr['reference']})
out.put({'BOTSID':'Edicon'},{'BOTSID':'Body'},{'BOTSID':'Attachment','Type':'external','BOTSCONTENT':datafilename})
out.put({'BOTSID':'Edicon'},{'BOTSID':'Header'},{'BOTSID':'X-mtype','BOTSCONTENT':'EDI'})
out.writeall() #write tomessage (result of translation)
#read/write datafiles
tofile = open(ta_attr['filename'], mode)
fromfile = open(row['filename'], 'rb')
shutil.copyfileobj(fromfile,tofile)
fromfile.close()
tofile.close()
except:
txt=botslib.txtexc()
ta_to.update(statust=ERROR,errortext=txt)
else:
ta_from.update(statust=DONE)
ta_to.update(statust=DONE,**ta_attr)
botslib.runexternprogram(botsglobal.ini.get('intercommit','path'),'-s')
def disconnect(self):
statusfilenaam = botslib.join(botsglobal.ini.get('intercommit','logfile'))
edifile = inmessage.edifromfile(filename=statusfilenaam,messagetype='intercommitstatus',editype='csv',charset='utf-8')
for inn in edifile.nextmessage():
for inline in inn.getloop({'BOTSID':'regel'}):
statuse = int(inline.get({'BOTSID':'regel','Berichtstatus':None}))
ICID = inline.get({'BOTSID':'regel','X-ClientMsgID':None})
if statuse==2:
subject = inline.get({'BOTSID':'regel','Onderwerp':None})
botslib.change(u'''UPDATE ta
SET statuse=%(statuse)s, reference=%(newref)s
WHERE reference = %(oldref)s
AND status=%(status)s''',
{'status':EXTERNOUT,'oldref':subject,'newref':ICID,'statuse':statuse})
else:
botslib.change(u'''UPDATE ta
SET statuse=%(statuse)s
WHERE reference = %(reference)s
AND status=%(status)s''',
{'status':EXTERNOUT,'reference':ICID,'statuse':statuse})
os.remove(statusfilenaam)
class database(_comsession):
''' ***this class is obsolete and only heere for compatibility reasons.
***this class is replaced by class db
communicate with a database; directly read or write from a database.
the user HAS to provide a script that does the actual import/export using SQLalchemy API.
use of channel parameters:
- path: contains the connection string (a sqlachlemy db uri)
- idchannel: name user script that does the database query & data formatting. in usersys/dbconnectors. ' main' function is called.
incommunicate (read from database) expects a json object. In the mapping script this is presented the usual way - use inn.get() etc.
outcommunicate (write to database) gets a json object.
'''
def connect(self):
self.dbscript,self.dbscriptname = botslib.botsimport('dbconnectors',self.channeldict['idchannel']) #get the dbconnector-script
if not hasattr(self.dbscript,'main'):
raise botslib.ScriptImportError(_(u'No function "$function" in imported script "$script".'),function='main',script=self.dbscript)
try:
import sqlalchemy
except:
txt=botslib.txtexc()
raise ImportError(_(u'Dependency failure: communication type "database" requires python library "sqlalchemy". Error:\n%s'%txt))
from sqlalchemy.orm import sessionmaker
engine = sqlalchemy.create_engine(self.channeldict['path'],strategy='threadlocal')
self.metadata = sqlalchemy.MetaData()
self.metadata.bind = engine
Session = sessionmaker(bind=engine, autoflush=False, transactional=True)
self.session = Session()
@botslib.log_session
def incommunicate(self):
''' read data from database.
'''
jsonobject = botslib.runscript(self.dbscript,self.dbscriptname,'main',channeldict=self.channeldict,session=self.session,metadata=self.metadata)
self.session.flush()
self.session.commit()
#should be checked more elaborate if jsonobject has 'real' data?
if jsonobject:
ta_from = botslib.NewTransaction(filename=self.channeldict['path'],
status=EXTERNIN,
fromchannel=self.channeldict['idchannel'],
charset=self.channeldict['charset'],idroute=self.idroute)
ta_to = ta_from.copyta(status=RAWIN)
tofilename = str(ta_to.idta)
tofile = botslib.opendata(tofilename,'wb',charset=u'utf-8')
simplejson.dump(jsonobject, tofile, skipkeys=False, ensure_ascii=False, check_circular=False)
tofile.close()
ta_from.update(statust=DONE)
ta_to.update(filename=tofilename,statust=OK)
@botslib.log_session
def outcommunicate(self):
''' write data to database.
'''
for row in botslib.query('''SELECT idta,filename
FROM ta
WHERE idta>%(rootidta)s
AND status=%(status)s
AND statust=%(statust)s
AND tochannel=%(tochannel)s
''',
{'tochannel':self.channeldict['idchannel'],'rootidta':botslib.get_minta4query(),
'status':RAWOUT,'statust':OK}):
try:
ta_from = botslib.OldTransaction(row['idta'])
ta_to = ta_from.copyta(status=EXTERNOUT)
fromfile = botslib.opendata(row['filename'], 'rb',charset=u'utf-8')
jsonobject = simplejson.load(fromfile)
fromfile.close()
botslib.runscript(self.dbscript,self.dbscriptname,'main',channeldict=self.channeldict,session=self.session,metadata=self.metadata,content=jsonobject)
self.session.flush()
self.session.commit()
except:
self.session.rollback()
txt=botslib.txtexc()
ta_to.update(statust=ERROR,errortext=txt,filename=self.channeldict['path'])
else:
ta_from.update(statust=DONE)
ta_to.update(statust=DONE,filename=self.channeldict['path'])
def disconnect(self):
self.session.close()
#~ pass
class db(_comsession):
''' communicate with a database; directly read or write from a database.
the user HAS to provide a script file in usersys/communicationscripts that does the actual import/export using **some** python database library.
the user script file should contain:
- connect
- (for incoming) incommunicate
- (for outgoing) outcommunicate
- disconnect
Other parameters are passed, use them for your own convenience.
Bots 'pickles' the results returned from the user scripts (and unpickles for the translation).
'''
def connect(self):
if self.userscript is None:
raise ImportError(_(u'Channel "%s" is type "db", but no communicationscript exists.'%self.channeldict['idchannel']))
#check functions bots assumes to be present in user script:
if not hasattr(self.userscript,'connect'):
raise botslib.ScriptImportError(_(u'No function "connect" in imported script "$script".'),script=self.scriptname)
if self.channeldict['inorout']=='in' and not hasattr(self.userscript,'incommunicate'):
raise botslib.ScriptImportError(_(u'No function "incommunicate" in imported script "$script".'),script=self.scriptname)
if self.channeldict['inorout']=='out' and not hasattr(self.userscript,'outcommunicate'):
raise botslib.ScriptImportError(_(u'No function "outcommunicate" in imported script "$script".'),script=self.scriptname)
if not hasattr(self.userscript,'disconnect'):
raise botslib.ScriptImportError(_(u'No function "disconnect" in imported script "$script".'),script=self.scriptname)
self.dbconnection = botslib.runscript(self.userscript,self.scriptname,'connect',channeldict=self.channeldict)
@botslib.log_session
def incommunicate(self):
''' read data from database.
returns db_objects;
if this is None, do nothing
if this is a list, treat each member of the list as a separate 'message'
'''
db_objects = botslib.runscript(self.userscript,self.scriptname,'incommunicate',channeldict=self.channeldict,dbconnection=self.dbconnection)
if not db_objects:
return
if not isinstance(db_objects,list):
db_objects = [db_objects]
for db_object in db_objects:
ta_from = botslib.NewTransaction(filename=self.channeldict['path'],
status=EXTERNIN,
fromchannel=self.channeldict['idchannel'],
charset=self.channeldict['charset'],
idroute=self.idroute)
ta_to = ta_from.copyta(status=RAWIN)
tofilename = str(ta_to.idta)
tofile = botslib.opendata(tofilename,'wb')
pickle.dump(db_object, tofile,2)
tofile.close()
ta_from.update(statust=DONE)
ta_to.update(filename=tofilename,statust=OK)
@botslib.log_session
def outcommunicate(self):
''' write data to database.
'''
for row in botslib.query('''SELECT idta,filename
FROM ta
WHERE idta>%(rootidta)s
AND status=%(status)s
AND statust=%(statust)s
AND tochannel=%(tochannel)s
''',
{'tochannel':self.channeldict['idchannel'],'rootidta':botslib.get_minta4query(),
'status':RAWOUT,'statust':OK}):
try:
ta_from = botslib.OldTransaction(row['idta'])
ta_to = ta_from.copyta(status=EXTERNOUT)
fromfile = botslib.opendata(row['filename'], 'rb')
db_object = pickle.load(fromfile)
fromfile.close()
botslib.runscript(self.userscript,self.scriptname,'outcommunicate',channeldict=self.channeldict,dbconnection=self.dbconnection,db_object=db_object)
except:
txt=botslib.txtexc()
ta_to.update(statust=ERROR,errortext=txt,filename=self.channeldict['path'])
else:
ta_from.update(statust=DONE)
ta_to.update(statust=DONE,filename=self.channeldict['path'])
def disconnect(self):
botslib.runscript(self.userscript,self.scriptname,'disconnect',channeldict=self.channeldict,dbconnection=self.dbconnection)
class communicationscript(_comsession):
"""
For running an (user maintained) communication script.
Examples of use:
- call external communication program
- call external program that extract messages from ERP-database
- call external program that imports messages in ERP system
- communication method not available in Bots ***or use sub-classing for this***
- specialised I/O wishes; eg specific naming of output files. (eg including partner name) ***beter: use sub-classing or have more user exits***
place of communication scripts: bots/usersys/communicationscripts
name of communication script: same name as channel (the channelID)
in this communication script some functions will be called:
- connect (required)
- main (optional, 'main' should handle files one by one)
- disconnect (required)
arguments: dict 'channel' which has all channel attributes
more parameters/data for communication script: hard code this in communication script; or use bots.ini
Different ways of working:
1. for incoming files (bots receives the files):
1.1 connect puts all files in a directory, there is no 'main' function. bots can remove the files (if you use the 'remove' switch of the channel).
1.2 connect only builds the connection, 'main' is a generator that passes the messages one by one (using 'yield'). bots can remove the files (if you use the 'remove' switch of the channel).
2. for outgoing files (bots sends the files):
2.1 if there is a 'main' function: the 'main' function is called by bots after writing each file. bots can remove the files (if you use the 'remove' switch of the channel).
2.2 no 'main' function: the processing of all the files can be done in 'disconnect'. bots can remove the files (if you use the 'remove' switch of the channel).
"""
def connect(self):
if self.userscript is None or not botslib.tryrunscript(self.userscript,self.scriptname,'connect',channeldict=self.channeldict):
raise ImportError(_(u'Channel "%s" is type "communicationscript", but no communicationscript exists.'%self.channeldict['idchannel']))
@botslib.log_session
def incommunicate(self):
startdatetime = datetime.datetime.now()
if hasattr(self.userscript,'main'): #process files one by one; script has to be a generator
for fromfilename in botslib.runscriptyield(self.userscript,self.scriptname,'main',channeldict=self.channeldict):
try:
ta_from = botslib.NewTransaction(filename = fromfilename,
status = EXTERNIN,
fromchannel = self.channeldict['idchannel'],
charset = self.channeldict['charset'], idroute = self.idroute)
ta_to = ta_from.copyta(status = RAWIN)
fromfile = open(fromfilename, 'rb')
tofilename = str(ta_to.idta)
tofile = botslib.opendata(tofilename, 'wb')
shutil.copyfileobj(fromfile,tofile)
fromfile.close()
tofile.close()
if self.channeldict['remove']:
os.remove(fromfilename)
except:
txt=botslib.txtexc()
botslib.ErrorProcess(functionname='communicationscript-incommunicate',errortext=txt,channeldict=self.channeldict)
ta_from.delete()
ta_to.delete()
else:
ta_from.update(statust=DONE)
ta_to.update(filename=tofilename,statust=OK)
finally:
if (datetime.datetime.now()-startdatetime).seconds >= self.maxsecondsperchannel:
break
else: #all files have been set ready by external script using 'connect'.
frompath = botslib.join(self.channeldict['path'], self.channeldict['filename'])
for fromfilename in [c for c in glob.glob(frompath) if os.path.isfile(c)]:
try:
ta_from = botslib.NewTransaction(filename = fromfilename,
status = EXTERNIN,
fromchannel = self.channeldict['idchannel'],
charset = self.channeldict['charset'], idroute = self.idroute)
ta_to = ta_from.copyta(status = RAWIN)
fromfile = open(fromfilename, 'rb')
tofilename = str(ta_to.idta)
tofile = botslib.opendata(tofilename, 'wb')
shutil.copyfileobj(fromfile,tofile)
fromfile.close()
tofile.close()
if self.channeldict['remove']:
os.remove(fromfilename)
except:
txt=botslib.txtexc()
botslib.ErrorProcess(functionname='communicationscript-incommunicate',errortext=txt,channeldict=self.channeldict)
ta_from.delete()
ta_to.delete()
else:
ta_from.update(statust=DONE)
ta_to.update(filename=tofilename,statust=OK)
finally:
if (datetime.datetime.now()-startdatetime).seconds >= self.maxsecondsperchannel:
break
@botslib.log_session
def outcommunicate(self):
#check if output dir exists, else create it.
outputdir = botslib.join(self.channeldict['path'])
botslib.dirshouldbethere(outputdir)
#output to one file or a queue of files (with unique names)
if not self.channeldict['filename'] or '*'not in self.channeldict['filename']:
mode = 'ab' #fixed filename; not unique: append to file
else:
mode = 'wb' #unique filenames; (over)write
#select the db-ta's for this channel
for row in botslib.query(u'''SELECT idta,filename,charset
FROM ta
WHERE idta>%(rootidta)s
AND status=%(status)s
AND statust=%(statust)s
AND tochannel=%(tochannel)s
''',
{'tochannel':self.channeldict['idchannel'],'rootidta':botslib.get_minta4query(),
'status':RAWOUT,'statust':OK}):
try: #for each db-ta:
ta_from = botslib.OldTransaction(row['idta'])
ta_to = ta_from.copyta(status=EXTERNOUT)
botslib.checkcodeciscompatible(row['charset'],self.channeldict['charset'])
#open tofile, incl syslock if indicated
unique = str(botslib.unique(self.channeldict['idchannel'])) #create unique part for filename
if self.channeldict['filename']:
filename = self.channeldict['filename'].replace('*',unique) #filename is filename in channel where '*' is replaced by idta
else:
filename = unique
tofilename = botslib.join(outputdir,filename)
tofile = open(tofilename, mode)
#open fromfile
fromfile = botslib.opendata(row['filename'], 'rb')
#copy
shutil.copyfileobj(fromfile,tofile)
fromfile.close()
tofile.close()
#one file is written; call external
if botslib.tryrunscript(self.userscript,self.scriptname,'main',channeldict=self.channeldict,filename=tofilename):
if self.channeldict['remove']:
os.remove(tofilename)
except:
txt=botslib.txtexc()
ta_to.update(statust=ERROR,errortext=txt)
else:
ta_from.update(statust=DONE)
ta_to.update(statust=DONE,filename=tofilename)
def disconnect(self):
botslib.tryrunscript(self.userscript,self.scriptname,'disconnect',channeldict=self.channeldict)
if self.channeldict['remove'] and not hasattr(self.userscript,'main'): #if bots should remove the files, and all files are passed at once, delete these files.
outputdir = botslib.join(self.channeldict['path'], self.channeldict['filename'])
for filename in [c for c in glob.glob(outputdir) if os.path.isfile(c)]:
try:
os.remove(filename)
except:
pass
| Python |
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext as _
'''
django is not excellent in generating db. But they have provided a way to customize the generated database using SQL. see bots/sql/*.
'''
STATUST = [
(0, _(u'Open')),
(1, _(u'Error')),
(2, _(u'Stuck')),
(3, _(u'Done')),
]
STATUS = [
(1,_(u'process')),
(3,_(u'discarded')),
(200,_(u'FileReceive')),
(210,_(u'RawInfile')),
(215,_(u'Mimein')),
(220,_(u'Infile')),
(230,_(u'Set for preprocess')),
(231,_(u'Preprocess')),
(232,_(u'Set for preprocess')),
(233,_(u'Preprocess')),
(234,_(u'Set for preprocess')),
(235,_(u'Preprocess')),
(236,_(u'Set for preprocess')),
(237,_(u'Preprocess')),
(238,_(u'Set for preprocess')),
(239,_(u'Preprocess')),
(300,_(u'Translate')),
(310,_(u'Parsed')),
(320,_(u'Splitup')),
(330,_(u'Translated')),
(400,_(u'Merged')),
(500,_(u'Outfile')),
(510,_(u'RawOutfile')),
(520,_(u'FileSend')),
]
EDITYPES = [
('csv', _(u'csv')),
('database', _(u'database (old)')),
('db', _(u'db')),
('edifact', _(u'edifact')),
('email-confirmation',_(u'email-confirmation')),
('fixed', _(u'fixed')),
('idoc', _(u'idoc')),
('json', _(u'json')),
('jsonnocheck', _(u'jsonnocheck')),
('mailbag', _(u'mailbag')),
('raw', _(u'raw')),
('template', _(u'template')),
('templatehtml', _(u'template-html')),
('tradacoms', _(u'tradacoms')),
('xml', _(u'xml')),
('xmlnocheck', _(u'xmlnocheck')),
('x12', _(u'x12')),
]
INOROUT = (
('in', _(u'in')),
('out', _(u'out')),
)
CHANNELTYPE = (
('file', _(u'file')),
('smtp', _(u'smtp')),
('smtps', _(u'smtps')),
('smtpstarttls', _(u'smtpstarttls')),
('pop3', _(u'pop3')),
('pop3s', _(u'pop3s')),
('pop3apop', _(u'pop3apop')),
('imap4', _(u'imap4')),
('imap4s', _(u'imap4s')),
('ftp', _(u'ftp')),
('ftps', _(u'ftps (explicit)')),
('ftpis', _(u'ftps (implicit)')),
('sftp', _(u'sftp (ssh)')),
('xmlrpc', _(u'xmlrpc')),
('mimefile', _(u'mimefile')),
('communicationscript', _(u'communicationscript')),
('db', _(u'db')),
('database', _(u'database (old)')),
('intercommit', _(u'intercommit')),
)
CONFIRMTYPE = [
('ask-email-MDN',_(u'ask an email confirmation (MDN) when sending')),
('send-email-MDN',_(u'send an email confirmation (MDN) when receiving')),
('ask-x12-997',_(u'ask a x12 confirmation (997) when sending')),
('send-x12-997',_(u'send a x12 confirmation (997) when receiving')),
('ask-edifact-CONTRL',_(u'ask an edifact confirmation (CONTRL) when sending')),
('send-edifact-CONTRL',_(u'send an edifact confirmation (CONTRL) when receiving')),
]
RULETYPE = (
('all',_(u'all')),
('route',_(u'route')),
('channel',_(u'channel')),
('frompartner',_(u'frompartner')),
('topartner',_(u'topartner')),
('messagetype',_(u'messagetype')),
)
ENCODE_MIME = (
('always',_(u'base64')),
('never',_(u'never')),
('ascii',_(u'base64 if not ascii')),
)
class StripCharField(models.CharField):
''' strip values before saving to database. this is not default in django #%^&*'''
def get_db_prep_value(self, value,*args,**kwargs):
"""Returns field's value prepared for interacting with the database
backend.
Used by the default implementations of ``get_db_prep_save``and
`get_db_prep_lookup```
"""
if isinstance(value, basestring):
return value.strip()
else:
return value
class botsmodel(models.Model):
class Meta:
abstract = True
def delete(self, *args, **kwargs):
''' bots does not use cascaded deletes!; so for delete: set references to null'''
self.clear_nullable_related()
super(botsmodel, self).delete(*args, **kwargs)
def clear_nullable_related(self):
"""
Recursively clears any nullable foreign key fields on related objects.
Django is hard-wired for cascading deletes, which is very dangerous for
us. This simulates ON DELETE SET NULL behavior manually.
"""
for related in self._meta.get_all_related_objects():
accessor = related.get_accessor_name()
related_set = getattr(self, accessor)
if related.field.null:
related_set.clear()
else:
for related_object in related_set.all():
related_object.clear_nullable_related()
#***********************************************************************************
#******** written by webserver ********************************************************
#***********************************************************************************
class confirmrule(botsmodel):
#~ id = models.IntegerField(primary_key=True)
active = models.BooleanField(default=False)
confirmtype = StripCharField(max_length=35,choices=CONFIRMTYPE)
ruletype = StripCharField(max_length=35,choices=RULETYPE)
negativerule = models.BooleanField(default=False)
frompartner = models.ForeignKey('partner',related_name='cfrompartner',null=True,blank=True)
topartner = models.ForeignKey('partner',related_name='ctopartner',null=True,blank=True)
#~ idroute = models.ForeignKey('routes',null=True,blank=True,verbose_name='route')
idroute = StripCharField(max_length=35,null=True,blank=True,verbose_name=_(u'route'))
idchannel = models.ForeignKey('channel',null=True,blank=True,verbose_name=_(u'channel'))
editype = StripCharField(max_length=35,choices=EDITYPES,blank=True)
messagetype = StripCharField(max_length=35,blank=True)
rsrv1 = StripCharField(max_length=35,blank=True,null=True) #added 20100501
rsrv2 = models.IntegerField(null=True) #added 20100501
def __unicode__(self):
return unicode(self.confirmtype) + u' ' + unicode(self.ruletype)
class Meta:
db_table = 'confirmrule'
verbose_name = _(u'confirm rule')
ordering = ['confirmtype','ruletype']
class ccodetrigger(botsmodel):
ccodeid = StripCharField(primary_key=True,max_length=35,verbose_name=_(u'type code'))
ccodeid_desc = StripCharField(max_length=35,null=True,blank=True)
def __unicode__(self):
return unicode(self.ccodeid)
class Meta:
db_table = 'ccodetrigger'
verbose_name = _(u'user code type')
ordering = ['ccodeid']
class ccode(botsmodel):
#~ id = models.IntegerField(primary_key=True) #added 20091221
ccodeid = models.ForeignKey(ccodetrigger,verbose_name=_(u'type code'))
leftcode = StripCharField(max_length=35,db_index=True)
rightcode = StripCharField(max_length=35,db_index=True)
attr1 = StripCharField(max_length=35,blank=True)
attr2 = StripCharField(max_length=35,blank=True)
attr3 = StripCharField(max_length=35,blank=True)
attr4 = StripCharField(max_length=35,blank=True)
attr5 = StripCharField(max_length=35,blank=True)
attr6 = StripCharField(max_length=35,blank=True)
attr7 = StripCharField(max_length=35,blank=True)
attr8 = StripCharField(max_length=35,blank=True)
def __unicode__(self):
return unicode(self.ccodeid) + u' ' + unicode(self.leftcode) + u' ' + unicode(self.rightcode)
class Meta:
db_table = 'ccode'
verbose_name = _(u'user code')
unique_together = (('ccodeid','leftcode','rightcode'),)
ordering = ['ccodeid']
class channel(botsmodel):
idchannel = StripCharField(max_length=35,primary_key=True)
inorout = StripCharField(max_length=35,choices=INOROUT,verbose_name=_(u'in/out'))
type = StripCharField(max_length=35,choices=CHANNELTYPE) #protocol type
charset = StripCharField(max_length=35,default=u'us-ascii')
host = StripCharField(max_length=256,blank=True)
port = models.PositiveIntegerField(default=0,blank=True,null=True)
username = StripCharField(max_length=35,blank=True)
secret = StripCharField(max_length=35,blank=True,verbose_name=_(u'password'))
starttls = models.BooleanField(default=False,verbose_name='No check from-address',help_text=_(u"Do not check if an incoming 'from' email addresses is known.")) #20091027: used as 'no check on "from:" email address'
apop = models.BooleanField(default=False,verbose_name='No check to-address',help_text=_(u"Do not check if an incoming 'to' email addresses is known.")) #not used anymore (is in 'type' now) #20110104: used as 'no check on "to:" email address'
remove = models.BooleanField(default=False,help_text=_(u'For in-channels: remove the edi files after successful reading. Note: in production you do want to remove the edi files, else these are read over and over again!'))
path = StripCharField(max_length=256,blank=True) #different from host - in ftp both are used
filename = StripCharField(max_length=35,blank=True,help_text=_(u'For "type" ftp and file; read or write this filename. Wildcards allowed, eg "*.edi". Note for out-channels: if no wildcard is used, all edi message are written to one file.'))
lockname = StripCharField(max_length=35,blank=True,help_text=_(u'When reading or writing edi files in this directory use this file to indicate a directory lock.'))
syslock = models.BooleanField(default=False,help_text=_(u'Use system file locking for reading & writing edi files on windows, *nix.'))
parameters = StripCharField(max_length=70,blank=True)
ftpaccount = StripCharField(max_length=35,blank=True)
ftpactive = models.BooleanField(default=False)
ftpbinary = models.BooleanField(default=False)
askmdn = StripCharField(max_length=17,blank=True,choices=ENCODE_MIME,verbose_name=_(u'mime encoding'),help_text=_(u'Should edi-files be base64-encoded in email. Using base64 for edi (default) is often a good choice.')) #not used anymore 20091019: 20100703: used to indicate mime-encoding
sendmdn = StripCharField(max_length=17,blank=True) #not used anymore 20091019
mdnchannel = StripCharField(max_length=35,blank=True) #not used anymore 20091019
archivepath = StripCharField(max_length=256,blank=True,verbose_name=_(u'Archive path'),help_text=_(u'Write incoming or outgoing edi files to an archive. Use absolute or relative path; relative path is relative to bots directory. Eg: "botssys/archive/mychannel".')) #added 20091028
desc = models.TextField(max_length=256,null=True,blank=True)
rsrv1 = StripCharField(max_length=35,blank=True,null=True) #added 20100501
rsrv2 = models.IntegerField(null=True,blank=True,verbose_name=_(u'Max seconds'),help_text=_(u'Max seconds used for the in-communication time for this channel.')) #added 20100501. 20110906: max communication time.
class Meta:
ordering = ['idchannel']
db_table = 'channel'
def __unicode__(self):
return self.idchannel
class partner(botsmodel):
idpartner = StripCharField(max_length=35,primary_key=True,verbose_name=_(u'partner identification'))
active = models.BooleanField(default=False)
isgroup = models.BooleanField(default=False)
name = StripCharField(max_length=256) #only used for user information
mail = StripCharField(max_length=256,blank=True)
cc = models.EmailField(max_length=256,blank=True)
mail2 = models.ManyToManyField(channel, through='chanpar',blank=True)
group = models.ManyToManyField("self",db_table='partnergroup',blank=True,symmetrical=False,limit_choices_to = {'isgroup': True})
rsrv1 = StripCharField(max_length=35,blank=True,null=True) #added 20100501
rsrv2 = models.IntegerField(null=True) #added 20100501
class Meta:
ordering = ['idpartner']
db_table = 'partner'
def __unicode__(self):
return unicode(self.idpartner)
class chanpar(botsmodel):
#~ id = models.IntegerField(primary_key=True) #added 20091221
idpartner = models.ForeignKey(partner,verbose_name=_(u'partner'))
idchannel = models.ForeignKey(channel,verbose_name=_(u'channel'))
mail = StripCharField(max_length=256)
cc = models.EmailField(max_length=256,blank=True) #added 20091111
askmdn = models.BooleanField(default=False) #not used anymore 20091019
sendmdn = models.BooleanField(default=False) #not used anymore 20091019
class Meta:
unique_together = (("idpartner","idchannel"),)
db_table = 'chanpar'
verbose_name = _(u'email address per channel')
verbose_name_plural = _(u'email address per channel')
def __unicode__(self):
return str(self.idpartner) + ' ' + str(self.idchannel) + ' ' + str(self.mail)
class translate(botsmodel):
#~ id = models.IntegerField(primary_key=True)
active = models.BooleanField(default=False)
fromeditype = StripCharField(max_length=35,choices=EDITYPES,help_text=_(u'Editype to translate from.'))
frommessagetype = StripCharField(max_length=35,help_text=_(u'Messagetype to translate from.'))
alt = StripCharField(max_length=35,null=False,blank=True,verbose_name=_(u'Alternative translation'),help_text=_(u'Do this translation only for this alternative translation.'))
frompartner = models.ForeignKey(partner,related_name='tfrompartner',null=True,blank=True,help_text=_(u'Do this translation only for this frompartner.'))
topartner = models.ForeignKey(partner,related_name='ttopartner',null=True,blank=True,help_text=_(u'Do this translation only for this topartner.'))
tscript = StripCharField(max_length=35,help_text=_(u'User mapping script to use for translation.'))
toeditype = StripCharField(max_length=35,choices=EDITYPES,help_text=_(u'Editype to translate to.'))
tomessagetype = StripCharField(max_length=35,help_text=_(u'Messagetype to translate to.'))
desc = models.TextField(max_length=256,null=True,blank=True)
rsrv1 = StripCharField(max_length=35,blank=True,null=True) #added 20100501
rsrv2 = models.IntegerField(null=True) #added 20100501
class Meta:
db_table = 'translate'
verbose_name = _(u'translation')
ordering = ['fromeditype','frommessagetype']
def __unicode__(self):
return unicode(self.fromeditype) + u' ' + unicode(self.frommessagetype) + u' ' + unicode(self.alt) + u' ' + unicode(self.frompartner) + u' ' + unicode(self.topartner)
class routes(botsmodel):
#~ id = models.IntegerField(primary_key=True)
idroute = StripCharField(max_length=35,db_index=True,help_text=_(u'identification of route; one route can consist of multiple parts having the same "idroute".'))
seq = models.PositiveIntegerField(default=1,help_text=_(u'for routes consisting of multiple parts, "seq" indicates the order these parts are run.'))
active = models.BooleanField(default=False)
fromchannel = models.ForeignKey(channel,related_name='rfromchannel',null=True,blank=True,verbose_name=_(u'incoming channel'),limit_choices_to = {'inorout': 'in'})
fromeditype = StripCharField(max_length=35,choices=EDITYPES,blank=True,help_text=_(u'the editype of the incoming edi files.'))
frommessagetype = StripCharField(max_length=35,blank=True,help_text=_(u'the messagetype of incoming edi files. For edifact: messagetype=edifact; for x12: messagetype=x12.'))
tochannel = models.ForeignKey(channel,related_name='rtochannel',null=True,blank=True,verbose_name=_(u'outgoing channel'),limit_choices_to = {'inorout': 'out'})
toeditype = StripCharField(max_length=35,choices=EDITYPES,blank=True,help_text=_(u'Only edi files with this editype to this outgoing channel.'))
tomessagetype = StripCharField(max_length=35,blank=True,help_text=_(u'Only edi files of this messagetype to this outgoing channel.'))
alt = StripCharField(max_length=35,default=u'',blank=True,verbose_name='Alternative translation',help_text=_(u'Only use if there is more than one "translation" for the same editype and messagetype. Advanced use, seldom needed.'))
frompartner = models.ForeignKey(partner,related_name='rfrompartner',null=True,blank=True,help_text=_(u'The frompartner of the incoming edi files. Seldom needed.'))
topartner = models.ForeignKey(partner,related_name='rtopartner',null=True,blank=True,help_text=_(u'The topartner of the incoming edi files. Seldom needed.'))
frompartner_tochannel = models.ForeignKey(partner,related_name='rfrompartner_tochannel',null=True,blank=True,help_text=_(u'Only edi files from this partner/partnergroup for this outgoing channel'))
topartner_tochannel = models.ForeignKey(partner,related_name='rtopartner_tochannel',null=True,blank=True,help_text=_(u'Only edi files to this partner/partnergroup to this channel'))
testindicator = StripCharField(max_length=1,blank=True,help_text=_(u'Only edi files with this testindicator to this outgoing channel.'))
translateind = models.BooleanField(default=True,blank=True,verbose_name='translate',help_text=_(u'Do a translation in this route.'))
notindefaultrun = models.BooleanField(default=False,blank=True,help_text=_(u'Do not use this route in a normal run. Advanced, related to scheduling specific routes or not.'))
desc = models.TextField(max_length=256,null=True,blank=True)
rsrv1 = StripCharField(max_length=35,blank=True,null=True) #added 20100501
rsrv2 = models.IntegerField(null=True) #added 20100501
defer = models.BooleanField(default=False,blank=True,help_text=_(u'Set ready for communication, but defer actual communication (this is done in another route)')) #added 20100601
class Meta:
db_table = 'routes'
verbose_name = _(u'route')
unique_together = (("idroute","seq"),)
ordering = ['idroute','seq']
def __unicode__(self):
return unicode(self.idroute) + u' ' + unicode(self.seq)
#***********************************************************************************
#******** written by engine ********************************************************
#***********************************************************************************
class filereport(botsmodel):
#~ id = models.IntegerField(primary_key=True)
idta = models.IntegerField(db_index=True)
reportidta = models.IntegerField(db_index=True)
statust = models.IntegerField(choices=STATUST)
retransmit = models.IntegerField()
idroute = StripCharField(max_length=35)
fromchannel = StripCharField(max_length=35)
tochannel = StripCharField(max_length=35)
frompartner = StripCharField(max_length=35)
topartner = StripCharField(max_length=35)
frommail = StripCharField(max_length=256)
tomail = StripCharField(max_length=256)
ineditype = StripCharField(max_length=35,choices=EDITYPES)
inmessagetype = StripCharField(max_length=35)
outeditype = StripCharField(max_length=35,choices=EDITYPES)
outmessagetype = StripCharField(max_length=35)
incontenttype = StripCharField(max_length=35)
outcontenttype = StripCharField(max_length=35)
nrmessages = models.IntegerField()
ts = models.DateTimeField(db_index=True) #copied from ta
infilename = StripCharField(max_length=256)
inidta = models.IntegerField(null=True) #not used anymore
outfilename = StripCharField(max_length=256)
outidta = models.IntegerField()
divtext = StripCharField(max_length=35)
errortext = StripCharField(max_length=2048)
rsrv1 = StripCharField(max_length=35,blank=True,null=True) #added 20100501
rsrv2 = models.IntegerField(null=True) #added 20100501
class Meta:
db_table = 'filereport'
unique_together = (("idta","reportidta"),)
class mutex(botsmodel):
#specific SQL is used (database defaults are used)
mutexk = models.IntegerField(primary_key=True)
mutexer = models.IntegerField()
ts = models.DateTimeField()
class Meta:
db_table = 'mutex'
class persist(botsmodel):
#OK, this has gone wrong. There is no primary key here, so django generates this. But there is no ID in the custom sql.
#Django still uses the ID in sql manager. This leads to an error in snapshot plugin. Disabled this in snapshot function; to fix this really database has to be changed.
#specific SQL is used (database defaults are used)
domein = StripCharField(max_length=35)
botskey = StripCharField(max_length=35)
content = StripCharField(max_length=1024)
ts = models.DateTimeField()
class Meta:
db_table = 'persist'
unique_together = (("domein","botskey"),)
class report(botsmodel):
idta = models.IntegerField(primary_key=True) #rename to reportidta
lastreceived = models.IntegerField()
lastdone = models.IntegerField()
lastopen = models.IntegerField()
lastok = models.IntegerField()
lasterror = models.IntegerField()
send = models.IntegerField()
processerrors = models.IntegerField()
ts = models.DateTimeField() #copied from (runroot)ta
type = StripCharField(max_length=35)
status = models.BooleanField()
rsrv1 = StripCharField(max_length=35,blank=True,null=True) #added 20100501
rsrv2 = models.IntegerField(null=True) ##added 20100501
class Meta:
db_table = 'report'
#~ #trigger for sqlite to use local time (instead of utc). I can not add this to sqlite specific sql code, as django does not allow complex (begin ... end) sql here.
#~ CREATE TRIGGER uselocaltime AFTER INSERT ON ta
#~ BEGIN
#~ UPDATE ta
#~ SET ts = datetime('now','localtime')
#~ WHERE idta = new.idta ;
#~ END;
class ta(botsmodel):
#specific SQL is used (database defaults are used)
idta = models.AutoField(primary_key=True)
statust = models.IntegerField(choices=STATUST)
status = models.IntegerField(choices=STATUS)
parent = models.IntegerField(db_index=True)
child = models.IntegerField()
script = models.IntegerField(db_index=True)
idroute = StripCharField(max_length=35)
filename = StripCharField(max_length=256)
frompartner = StripCharField(max_length=35)
topartner = StripCharField(max_length=35)
fromchannel = StripCharField(max_length=35)
tochannel = StripCharField(max_length=35)
editype = StripCharField(max_length=35)
messagetype = StripCharField(max_length=35)
alt = StripCharField(max_length=35)
divtext = StripCharField(max_length=35)
merge = models.BooleanField()
nrmessages = models.IntegerField()
testindicator = StripCharField(max_length=10) #0:production; 1:test. Length to 1?
reference = StripCharField(max_length=70)
frommail = StripCharField(max_length=256)
tomail = StripCharField(max_length=256)
charset = StripCharField(max_length=35)
statuse = models.IntegerField() #obsolete 20091019 but still used by intercommit comm. module
retransmit = models.BooleanField() #20070831: only retransmit, not rereceive
contenttype = StripCharField(max_length=35)
errortext = StripCharField(max_length=2048)
ts = models.DateTimeField()
confirmasked = models.BooleanField() #added 20091019; confirmation asked or send
confirmed = models.BooleanField() #added 20091019; is confirmation received (when asked)
confirmtype = StripCharField(max_length=35) #added 20091019
confirmidta = models.IntegerField() #added 20091019
envelope = StripCharField(max_length=35) #added 20091024
botskey = StripCharField(max_length=35) #added 20091024
cc = StripCharField(max_length=512) #added 20091111
rsrv1 = StripCharField(max_length=35) #added 20100501
rsrv2 = models.IntegerField(null=True) #added 20100501
rsrv3 = StripCharField(max_length=35) #added 20100501
rsrv4 = models.IntegerField(null=True) #added 20100501
class Meta:
db_table = 'ta'
class uniek(botsmodel):
#specific SQL is used (database defaults are used)
domein = StripCharField(max_length=35,primary_key=True)
nummer = models.IntegerField()
class Meta:
db_table = 'uniek'
verbose_name = _(u'counter')
ordering = ['domein']
| Python |
''' Reading/lexing/parsing/splitting an edifile.'''
import StringIO
import time
import sys
try:
import cPickle as pickle
except:
import pickle
try:
import cElementTree as ET
except ImportError:
try:
import elementtree.ElementTree as ET
except ImportError:
try:
from xml.etree import cElementTree as ET
except ImportError:
from xml.etree import ElementTree as ET
try:
import json as simplejson
except ImportError:
import simplejson
from django.utils.translation import ugettext as _
import botslib
import botsglobal
import outmessage
import message
import node
import grammar
from botsconfig import *
def edifromfile(**ta_info):
''' Read,lex, parse edi-file. Is a dispatch function for Inmessage and subclasses.'''
try:
classtocall = globals()[ta_info['editype']] #get inmessage class to call (subclass of Inmessage)
except KeyError:
raise botslib.InMessageError(_(u'Unknown editype for incoming message: $editype'),editype=ta_info['editype'])
ediobject = classtocall(ta_info)
ediobject.initfromfile()
return ediobject
def _edifromparsed(editype,inode,ta_info):
''' Get a edi-message (inmessage-object) from node in tree.
is used in splitting edi-messages.'''
classtocall = globals()[editype]
ediobject = classtocall(ta_info)
ediobject.initfromparsed(inode)
return ediobject
#*****************************************************************************
class Inmessage(message.Message):
''' abstract class for incoming ediobject (file or message).
Can be initialised from a file or a tree.
'''
def __init__(self,ta_info):
super(Inmessage,self).__init__()
self.records = [] #init list of records
self.confirminfo = {}
self.ta_info = ta_info #here ta_info is only filled with parameters from db-ta
def initfromfile(self):
''' initialisation from a edi file '''
self.defmessage = grammar.grammarread(self.ta_info['editype'],self.ta_info['messagetype']) #read grammar, after sniffing. Information from sniffing can be used (eg name editype for edifact, using version info from UNB)
botslib.updateunlessset(self.ta_info,self.defmessage.syntax) #write values from grammar to self.ta_info - unless these values are already set
self.ta_info['charset'] =self.defmessage.syntax['charset'] #always use charset of edi file.
self._readcontent_edifile()
self._sniff() #some hard-coded parsing of edi file; eg ta_info can be overruled by syntax-parameters in edi-file
#start lexing and parsing
self._lex()
del self.rawinput
#~ self.display(self.records) #show lexed records (for protocol debugging)
self.root = node.Node() #make root Node None.
result = self._parse(self.defmessage.structure,self._nextrecord(self.records),self.root)
if result:
raise botslib.InMessageError(_(u'Unknown data beyond end of message; mostly problem with separators or message structure: "$content"'),content=result)
del self.records
#end parsing; self.root is root of a tree (of nodes).
self.checkenvelope()
#~ self.root.display() #show tree of nodes (for protocol debugging)
#~ self.root.displayqueries() #show queries in tree of nodes (for protocol debugging)
def initfromparsed(self,node):
''' initialisation from a tree (node is passed).
to initialise message in an envelope
'''
self.root = node
def handleconfirm(self,ta_fromfile,error):
''' end of edi file handling.
eg writing of confirmations etc.
'''
pass
def _formatfield(self,value,grammarfield,record):
''' Format of a field is checked and converted if needed.
Input: value (string), field definition.
Output: the formatted value (string)
Parameters of self.ta_info are used: triad, decimaal
for fixed field: same handling; length is not checked.
'''
if grammarfield[BFORMAT] in ['A','D','T']:
if isinstance(self,var): #check length fields in variable records
valuelength=len(value)
if valuelength > grammarfield[LENGTH]:
raise botslib.InMessageFieldError(_(u'Record "$record" field "$field" too big (max $max): "$content".'),record=record,field=grammarfield[ID],content=value,max=grammarfield[LENGTH])
if valuelength < grammarfield[MINLENGTH]:
raise botslib.InMessageFieldError(_(u'Record "$record" field "$field" too small (min $min): "$content".'),record=record,field=grammarfield[ID],content=value,min=grammarfield[MINLENGTH])
value = value.strip()
if not value:
pass
elif grammarfield[BFORMAT] == 'A':
pass
elif grammarfield[BFORMAT] == 'D':
try:
lenght = len(value)
if lenght==6:
time.strptime(value,'%y%m%d')
elif lenght==8:
time.strptime(value,'%Y%m%d')
else:
raise ValueError(u'To be catched')
except ValueError:
raise botslib.InMessageFieldError(_(u'Record "$record" date field "$field" not a valid date: "$content".'),record=record,field=grammarfield[ID],content=value)
elif grammarfield[BFORMAT] == 'T':
try:
lenght = len(value)
if lenght==4:
time.strptime(value,'%H%M')
elif lenght==6:
time.strptime(value,'%H%M%S')
elif lenght==7 or lenght==8:
time.strptime(value[0:6],'%H%M%S')
if not value[6:].isdigit():
raise ValueError(u'To be catched')
else:
raise ValueError(u'To be catched')
except ValueError:
raise botslib.InMessageFieldError(_(u'Record "$record" time field "$field" not a valid time: "$content".'),record=record,field=grammarfield[ID],content=value)
else: #numerics (R, N, I)
value = value.strip()
if not value:
if self.ta_info['acceptspaceinnumfield']:
value='0'
else:
raise botslib.InMessageFieldError(_(u'Record "$record" field "$field" has numeric format but contains only space.'),record=record,field=grammarfield[ID])
#~ return '' #when num field has spaces as content, spaces are stripped. Field should be numeric.
if value[-1] == u'-': #if minus-sign at the end, put it in front.
value = value[-1] + value[:-1]
value = value.replace(self.ta_info['triad'],u'') #strip triad-separators
value = value.replace(self.ta_info['decimaal'],u'.',1) #replace decimal sign by canonical decimal sign
if 'E' in value or 'e' in value:
raise botslib.InMessageFieldError(_(u'Record "$record" field "$field" format "$format" contains exponent: "$content".'),record=record,field=grammarfield[ID],content=value,format=grammarfield[BFORMAT])
if isinstance(self,var): #check length num fields in variable records
if self.ta_info['lengthnumericbare']:
length = botslib.countunripchars(value,'-+.')
else:
length = len(value)
if length > grammarfield[LENGTH]:
raise botslib.InMessageFieldError(_(u'Record "$record" field "$field" too big (max $max): "$content".'),record=record,field=grammarfield[ID],content=value,max=grammarfield[LENGTH])
if length < grammarfield[MINLENGTH]:
raise botslib.InMessageFieldError(_(u'Record "$record" field "$field" too small (min $min): "$content".'),record=record,field=grammarfield[ID],content=value,min=grammarfield[MINLENGTH])
if grammarfield[BFORMAT] == 'I':
if '.' in value:
raise botslib.InMessageFieldError(_(u'Record "$record" field "$field" has format "I" but contains decimal sign: "$content".'),record=record,field=grammarfield[ID],content=value)
try: #convert to decimal in order to check validity
valuedecimal = float(value)
valuedecimal = valuedecimal / 10**grammarfield[DECIMALS]
value = '%.*F'%(grammarfield[DECIMALS],valuedecimal)
except:
raise botslib.InMessageFieldError(_(u'Record "$record" numeric field "$field" has non-numerical content: "$content".'),record=record,field=grammarfield[ID],content=value)
elif grammarfield[BFORMAT] == 'N':
lendecimal = len(value[value.find('.'):])-1
if lendecimal != grammarfield[DECIMALS]:
raise botslib.InMessageFieldError(_(u'Record "$record" numeric field "$field" has invalid nr of decimals: "$content".'),record=record,field=grammarfield[ID],content=value)
try: #convert to decimal in order to check validity
valuedecimal = float(value)
value = '%.*F'%(lendecimal,valuedecimal)
except:
raise botslib.InMessageFieldError(_(u'Record "$record" numeric field "$field" has non-numerical content: "$content".'),record=record,field=grammarfield[ID],content=value)
elif grammarfield[BFORMAT] == 'R':
lendecimal = len(value[value.find('.'):])-1
try: #convert to decimal in order to check validity
valuedecimal = float(value)
value = '%.*F'%(lendecimal,valuedecimal)
except:
raise botslib.InMessageFieldError(_(u'Record "$record" numeric field "$field" has non-numerical content: "$content".'),record=record,field=grammarfield[ID],content=value)
return value
def _parse(self,tab,_nextrecord,inode,rec2parse=None,argmessagetype=None,argnewnode=None):
''' parse the lexed records. validate message against grammar.
add grammar-info to records in self.records: field-tag,mpath.
Tab: current grammar/segmentgroup of the grammar-structure.
Read the records one by one.
Lookup record in tab.
if found:
if headersegment (tabrecord has own tab):
go recursive.
if not found:
if trailer:
jump back recursive, returning the unparsed record.
'''
for tabrec in tab: #clear counts for tab-records (start fresh).
tabrec[COUNT] = 0
tabindex = 0
tabmax = len(tab)
if rec2parse is None:
parsenext = True
subparse=False
else: #only for subparsing
parsenext = False
subparse=True
while 1:
if parsenext:
try:
rec2parse = _nextrecord.next()
except StopIteration: #catch when no more rec2parse.
rec2parse = None
parsenext = False
if rec2parse is None or tab[tabindex][ID] != rec2parse[ID][VALUE]:
#for StopIteration(loop rest of grammar) or when rec2parse
if tab[tabindex][COUNT] < tab[tabindex][MIN]:
try:
raise botslib.InMessageError(_(u'line:$line pos:$pos; record:"$record" not in grammar; looked in grammar until mandatory record: "$looked".'),record=rec2parse[ID][VALUE],line=rec2parse[ID][LIN],pos=rec2parse[ID][POS],looked=tab[tabindex][MPATH])
except TypeError:
raise botslib.InMessageError(_(u'missing mandatory record at message-level: "$record"'),record=tab[tabindex][MPATH])
#TODO: line/pos of original file in error...when this is possible, XML?
tabindex += 1
if tabindex >= tabmax: #rec2parse is not in this level. Go level up
return rec2parse #return either None (for StopIteration) or the last record2parse (not found in this level)
#continue while-loop (parsenext is false)
else: #if found in grammar
tab[tabindex][COUNT] += 1
if tab[tabindex][COUNT] > tab[tabindex][MAX]:
raise botslib.InMessageError(_(u'line:$line pos:$pos; too many repeats record "$record".'),line=rec2parse[ID][LIN],pos=rec2parse[ID][POS],record=tab[tabindex][ID])
if argmessagetype: #that is, header segment of subtranslation
newnode = argnewnode #use old node that is already parsed
newnode.queries = {'messagetype':argmessagetype} #copy messagetype into 1st segment of subtranslation (eg UNH, ST)
argmessagetype=None
else:
newnode = node.Node(record=self._parsefields(rec2parse,tab[tabindex][FIELDS]),BOTSIDnr=tab[tabindex][BOTSIDnr]) #make new node
if botsglobal.ini.getboolean('settings','readrecorddebug',False):
botsglobal.logger.debug(u'read record "%s" (line %s pos %s):',tab[tabindex][ID],rec2parse[ID][LIN],rec2parse[ID][POS])
for key,value in newnode.record.items():
botsglobal.logger.debug(u' "%s" : "%s"',key,value)
if SUBTRANSLATION in tab[tabindex]: # subparse starts here: tree is build for this messagetype; the messagetype is read from the edifile
messagetype = self._getmessagetype(newnode.enhancedget(tab[tabindex][SUBTRANSLATION],replace=True),inode)
if not messagetype:
raise botslib.InMessageError(_(u'could not find SUBTRANSLATION "$sub" in (sub)message.'),sub=tab[tabindex][SUBTRANSLATION])
defmessage = grammar.grammarread(self.__class__.__name__,messagetype)
rec2parse = self._parse(defmessage.structure,_nextrecord,inode,rec2parse=rec2parse,argmessagetype=messagetype,argnewnode=newnode)
#~ end subparse for messagetype
else:
inode.append(newnode) #append new node to current node
if LEVEL in tab[tabindex]: #if header, go to subgroup
rec2parse = self._parse(tab[tabindex][LEVEL],_nextrecord,newnode)
if subparse: #back in top level of subparse: return (to motherparse)
return rec2parse
else:
parsenext = True
self.get_queries_from_edi(inode.children[-1],tab[tabindex])
def _getmessagetype(self,messagetypefromsubtranslation,inode):
return messagetypefromsubtranslation
def get_queries_from_edi(self,node,trecord):
''' extract information from edifile using QUERIES in grammar.structure; information will be placed in ta_info and in db-ta
'''
if QUERIES in trecord:
#~ print 'Print QUERIES'
tmpdict = {}
#~ print trecord[QUERIES]
for key,value in trecord[QUERIES].items():
found = node.enhancedget(value) #search in last added node
if found:
#~ print ' found',found,value
tmpdict[key] = found #copy key to avoid memory problems
#~ else:
#~ print ' not found',value
node.queries = tmpdict
def _readcontent_edifile(self):
''' read content of edi file to memory.
'''
#TODO test, catch exceptions
botsglobal.logger.debug(u'read edi file "%s".',self.ta_info['filename'])
self.rawinput = botslib.readdata(filename=self.ta_info['filename'],charset=self.ta_info['charset'],errors=self.ta_info['checkcharsetin'])
def _sniff(self):
''' sniffing: hard coded parsing of edi file.
method is specified in subclasses.
'''
pass
def checkenvelope(self):
pass
@staticmethod
def _nextrecord(records):
''' generator for records that are lexed.'''
for record in records:
yield record
def nextmessage(self):
''' Generates each message as a separate Inmessage.
'''
#~ self.root.display()
if self.defmessage.nextmessage is not None: #if nextmessage defined in grammar: split up messages
first = True
for message in self.getloop(*self.defmessage.nextmessage): #get node of each message
if first:
self.root.processqueries({},len(self.defmessage.nextmessage))
first = False
ta_info = self.ta_info.copy()
ta_info.update(message.queries)
#~ ta_info['botsroot']=self.root
yield _edifromparsed(self.__class__.__name__,message,ta_info)
if self.defmessage.nextmessage2 is not None: #edifact needs nextmessage2...OK
first = True
for message in self.getloop(*self.defmessage.nextmessage2):
if first:
self.root.processqueries({},len(self.defmessage.nextmessage2))
first = False
ta_info = self.ta_info.copy()
ta_info.update(message.queries)
#~ ta_info['botsroot']=self.root
yield _edifromparsed(self.__class__.__name__,message,ta_info)
elif self.defmessage.nextmessageblock is not None: #for csv/fixed: nextmessageblock indicates which field determines a message (as long as the field is the same, it is one message)
#there is only one recordtype (this is checked in grammar.py).
first = True
for line in self.root.children:
kriterium = line.get(self.defmessage.nextmessageblock)
if first:
first = False
newroot = node.Node() #make new empty root node.
oldkriterium = kriterium
elif kriterium != oldkriterium:
ta_info = self.ta_info.copy()
ta_info.update(oldline.queries) #update ta_info with information (from previous line) 20100905
#~ ta_info['botsroot']=self.root #give mapping script access to all information in edi file: all records
yield _edifromparsed(self.__class__.__name__,newroot,ta_info)
newroot = node.Node() #make new empty root node.
oldkriterium = kriterium
else:
pass #if kriterium is the same
newroot.append(line)
oldline = line #save line 20100905
else:
if not first:
ta_info = self.ta_info.copy()
ta_info.update(line.queries) #update ta_info with information (from last line) 20100904
#~ ta_info['botsroot']=self.root
yield _edifromparsed(self.__class__.__name__,newroot,ta_info)
else: #no split up indicated in grammar;
if self.root.record or self.ta_info['pass_all']: #if contains root-record or explicitly indicated (csv): pass whole tree
ta_info = self.ta_info.copy()
ta_info.update(self.root.queries)
#~ ta_info['botsroot']=None #??is the same as self.root, so I use None??.
yield _edifromparsed(self.__class__.__name__,self.root,ta_info)
else: #pass nodes under root one by one
for child in self.root.children:
ta_info = self.ta_info.copy()
ta_info.update(child.queries)
#~ ta_info['botsroot']=self.root #give mapping script access to all information in edi file: all roots
yield _edifromparsed(self.__class__.__name__,child,ta_info)
class fixed(Inmessage):
''' class for record of fixed length.'''
def _lex(self):
''' lexes file with fixed records to list of records (self.records).'''
linenr = 0
startrecordID = self.ta_info['startrecordID']
endrecordID = self.ta_info['endrecordID']
self.rawinputfile = StringIO.StringIO(self.rawinput) #self.rawinputfile is an iterator
for line in self.rawinputfile:
linenr += 1
line=line.rstrip('\r\n')
self.records += [ [{VALUE:line[startrecordID:endrecordID].strip(),LIN:linenr,POS:0,FIXEDLINE:line}] ] #append record to recordlist
self.rawinputfile.close()
def _parsefields(self,recordEdiFile,trecord):
''' Parse fields from one fixed message-record (from recordEdiFile[ID][FIXEDLINE] using positions.
fields are placed in dict, where key=field-info from grammar and value is from fixedrecord.'''
recorddict = {} #start with empty dict
fixedrecord = recordEdiFile[ID][FIXEDLINE] #shortcut to fixed record we are parsing
lenfixed = len(fixedrecord)
recordlength = 0
for field in trecord: #calculate total length of record from field lengths
recordlength += field[LENGTH]
if recordlength > lenfixed and self.ta_info['checkfixedrecordtooshort']:
raise botslib.InMessageError(_(u'line $line record "$record" too short; is $pos pos, defined is $defpos pos: "$content".'),line=recordEdiFile[ID][LIN],record=recordEdiFile[ID][VALUE],pos=lenfixed,defpos=recordlength,content=fixedrecord)
if recordlength < lenfixed and self.ta_info['checkfixedrecordtoolong']:
raise botslib.InMessageError(_(u'line $line record "$record" too long; is $pos pos, defined is $defpos pos: "$content".'),line=recordEdiFile[ID][LIN],record=recordEdiFile[ID][VALUE],pos=lenfixed,defpos=recordlength,content=fixedrecord)
pos = 0
for field in trecord: #for fields in this record
value = fixedrecord[pos:pos+field[LENGTH]]
try:
value = self._formatfield(value,field,fixedrecord)
except botslib.InMessageFieldError:
txt=botslib.txtexc()
raise botslib.InMessageFieldError(_(u'line:$line pos:$pos. Error:\n$txt'),line=recordEdiFile[ID][LIN],pos=pos,txt=txt)
if value:
recorddict[field[ID][:]] = value #copy id string to avoid memory problem ; value is already a copy
else:
if field[MANDATORY]==u'M':
raise botslib.InMessageFieldError(_(u'line:$line pos:$pos; mandatory field "$field" not in record "$record".'),line=recordEdiFile[ID][LIN],pos=pos,field=field[ID],record=recordEdiFile[ID][VALUE])
pos += field[LENGTH]
#~ if pos > lenfixed:
#~ break
return recorddict
class idoc(fixed):
''' class for idoc ediobjects.
for incoming the same as fixed.
SAP does strip all empty fields for record; is catered for in grammar.defaultsyntax
'''
def _sniff(self):
''' examine a read file for syntax parameters and correctness of protocol
eg parse UNA, find UNB, get charset and version
'''
#goto char that is not whitespace
for count,c in enumerate(self.rawinput):
if not c.isspace():
self.rawinput = self.rawinput[count:] #here the interchange should start
break
else:
raise botslib.InMessageError(_(u'edi file only contains whitespace.'))
if self.rawinput[:6] != 'EDI_DC':
raise botslib.InMessageError(_(u'expect "EDI_DC", found "$content". Probably no SAP idoc.'),content=self.rawinput[:6])
class var(Inmessage):
''' abstract class for ediobjects with records of variabele length.'''
def _lex(self):
''' lexes file with variable records to list of records, fields and subfields (self.records).'''
quote_char = self.ta_info['quote_char']
skip_char = self.ta_info['skip_char'] #skip char (ignore);
escape = self.ta_info['escape'] #char after escape-char is not interpreted as seperator
field_sep = self.ta_info['field_sep'] + self.ta_info['record_tag_sep'] #for tradacoms; field_sep and record_tag_sep have same function.
sfield_sep = self.ta_info['sfield_sep']
record_sep = self.ta_info['record_sep']
mode_escape = 0 #0=not escaping, 1=escaping
mode_quote = 0 #0=not in quote, 1=in quote
mode_2quote = 0 #0=not escaping quote, 1=escaping quote.
mode_inrecord = 0 #indicates if lexing a record. If mode_inrecord==0: skip whitespace
sfield = False # True: is subveld, False is geen subveld
value = u'' #the value of the current token
record = []
valueline = 1 #starting line of token
valuepos = 1 #starting position of token
countline = 1
countpos = 0
#bepaal tekenset, separators etc adhv UNA/UNOB
for c in self.rawinput: #get next char
if c == u'\n': #line within file
countline += 1
countpos = 0 #new line, pos back to 0
#no continue, because \n can be record separator. In edifact: catched with skip_char
else:
countpos += 1 #position within line
if mode_quote: #within a quote: quote-char is also escape-char
if mode_2quote and c == quote_char: #thus we were escaping quote_char
mode_2quote = 0
value += c #append quote_char
continue
elif mode_escape: #tricky: escaping a quote char
mode_escape = 0
value += c
continue
elif mode_2quote: #thus is was a end-quote
mode_2quote = 0
mode_quote= 0
#go on parsing
elif c==quote_char: #either end-quote or escaping quote_char,we do not know yet
mode_2quote = 1
continue
elif c == escape:
mode_escape = 1
continue
else:
value += c
continue
if mode_inrecord:
pass #do nothing, is already in mode_inrecord
else:
if c.isspace():
continue #not in mode_inrecord, and a space: ignore space between records.
else:
mode_inrecord = 1
if c in skip_char: #after mode_quote, but before mode_escape!!
continue
if mode_escape: #always append in escaped_mode
mode_escape = 0
value += c
continue
if not value: #if no char in token: this is a new token, get line and pos for (new) token
valueline = countline
valuepos = countpos
if c == quote_char:
mode_quote = 1
continue
if c == escape:
mode_escape = 1
continue
if c in field_sep: #for tradacoms: record_tag_sep is appended to field_sep; in lexing they have the same function
record += [{VALUE:value,SFIELD:sfield,LIN:valueline,POS:valuepos}] #append element in record
value = u''
sfield = False
continue
if c == sfield_sep:
record += [{VALUE:value,SFIELD:sfield,LIN:valueline,POS:valuepos}] #append element in record
value = u''
sfield = True
continue
if c in record_sep:
record += [{VALUE:value,SFIELD:sfield,LIN:valueline,POS:valuepos}] #append element in record
self.records += [record] #write record to recordlist
record=[]
value = u''
sfield = False
mode_inrecord=0
continue
value += c #just a char: append char to value
#end of for-loop. all characters have been processed.
#in a perfect world, value should always be empty now, but:
#it appears a csv record is not always closed properly, so force the closing of the last record of csv file:
if mode_inrecord and isinstance(self,csv) and self.ta_info['allow_lastrecordnotclosedproperly']:
record += [{VALUE:value,SFIELD:sfield,LIN:valueline,POS:valuepos}] #append element in record
self.records += [record] #write record to recordlist
elif value.strip('\x00\x1a'):
raise botslib.InMessageError(_(u'translation problem with lexing; probably a seperator-problem, or extra characters after interchange'))
def _striprecord(self,recordEdiFile):
#~ return [field[VALUE] for field in recordEdiFile]
terug = ''
for field in recordEdiFile:
terug += field[VALUE] + ' '
if len(terug) > 35:
terug = terug[:35] + ' (etc)'
return terug
def _parsefields(self,recordEdiFile,trecord):
''' Check all fields in message-record with field-info in grammar
Build a dictionary of fields (field-IDs are unique within record), and return this.
'''
recorddict = {}
#****************** first: identify fields: assign field id to lexed fields
tindex = -1 #elementcounter; composites count as one
tsubindex=0 #sub-element couner (witin composite))
for rfield in recordEdiFile: #handle both fields and sub-fields
if rfield[SFIELD]:
tsubindex += 1
try:
field = trecord[tindex][SUBFIELDS][tsubindex]
except TypeError: #field has no SUBFIELDS
raise botslib.InMessageFieldError(_(u'line:$line pos:$pos; expect field, is a subfield; record "$record".'),line=rfield[LIN],pos=rfield[POS],record=self._striprecord(recordEdiFile))
except IndexError: #tsubindex is not in the subfields
raise botslib.InMessageFieldError(_(u'line:$line pos:$pos; too many subfields; record "$record".'),line=rfield[LIN],pos=rfield[POS],record=self._striprecord(recordEdiFile))
else:
tindex += 1
try:
field = trecord[tindex]
except IndexError:
raise botslib.InMessageFieldError(_(u'line:$line pos:$pos; too many fields; record "$record".'),line=rfield[LIN],pos=rfield[POS],record=self._striprecord(recordEdiFile))
if not field[ISFIELD]: #if field is subfield
tsubindex = 0
field = trecord[tindex][SUBFIELDS][tsubindex]
#*********if field has content: check format and add to recorddictionary
if rfield[VALUE]:
try:
rfield[VALUE] = self._formatfield(rfield[VALUE],field,recordEdiFile[0][VALUE])
except botslib.InMessageFieldError:
txt=botslib.txtexc()
raise botslib.InMessageFieldError(_(u'line:$line pos:$pos. Error:\n$txt'),line=rfield[LIN],pos=rfield[POS],txt=txt)
recorddict[field[ID][:]]=rfield[VALUE][:] #copy string to avoid memory problems
#****************** then: check M/C
for tfield in trecord:
if tfield[ISFIELD]: #tfield is normal field (not a composite)
if tfield[MANDATORY]==u'M' and tfield[ID] not in recorddict:
raise botslib.InMessageError(_(u'line:$line mandatory field "$field" not in record "$record".'),line=recordEdiFile[0][LIN],field=tfield[ID],record=self._striprecord(recordEdiFile))
else:
compositefilled = False
for sfield in tfield[SUBFIELDS]: #t[2]: subfields in grammar
if sfield[ID] in recorddict:
compositefilled = True
break
if compositefilled:
for sfield in tfield[SUBFIELDS]: #t[2]: subfields in grammar
if sfield[MANDATORY]==u'M' and sfield[ID] not in recorddict:
raise botslib.InMessageError(_(u'line:$line mandatory subfield "$field" not in composite, record "$record".'),line=recordEdiFile[0][LIN],field=sfield[ID],record=self._striprecord(recordEdiFile))
if not compositefilled and tfield[MANDATORY]==u'M':
raise botslib.InMessageError(_(u'line:$line mandatory composite "$field" not in record "$record".'),line=recordEdiFile[0][LIN],field=tfield[ID],record=self._striprecord(recordEdiFile))
return recorddict
class csv(var):
''' class for ediobjects with Comma Separated Values'''
def _lex(self):
super(csv,self)._lex()
if self.ta_info['skip_firstline']: #if first line for CSV should be skipped (contains field names)
del self.records[0]
if self.ta_info['noBOTSID']: #if read records contain no BOTSID: add it
botsid = self.defmessage.structure[0][ID] #add the recordname as BOTSID
for record in self.records:
record[0:0]=[{VALUE: botsid, POS: 0, LIN: 0, SFIELD: False}]
class edifact(var):
''' class for edifact inmessage objects.'''
def _readcontent_edifile(self):
''' read content of edi file in memory.
For edifact: not unicode. after sniffing unicode is used to check charset (UNOA etc)
In sniff: determine charset; then decode according to charset
'''
botsglobal.logger.debug(u'read edi file "%s".',self.ta_info['filename'])
self.rawinput = botslib.readdata(filename=self.ta_info['filename'],errors=self.ta_info['checkcharsetin'])
def _sniff(self):
''' examine a read file for syntax parameters and correctness of protocol
eg parse UNA, find UNB, get charset and version
'''
#goto char that is alphanumeric
for count,c in enumerate(self.rawinput):
if c.isalnum():
break
else:
raise botslib.InMessageError(_(u'edi file only contains whitespace.'))
if self.rawinput[count:count+3] == 'UNA':
unacharset=True
self.ta_info['sfield_sep'] = self.rawinput[count+3]
self.ta_info['field_sep'] = self.rawinput[count+4]
self.ta_info['decimaal'] = self.rawinput[count+5]
self.ta_info['escape'] = self.rawinput[count+6]
self.ta_info['reserve'] = '' #self.rawinput[count+7] #for now: no support of repeating dataelements
self.ta_info['record_sep'] = self.rawinput[count+8]
#goto char that is alphanumeric
for count2,c in enumerate(self.rawinput[count+9:]):
if c.isalnum():
break
self.rawinput = self.rawinput[count+count2+9:] #here the interchange should start; UNA is no longer needed
else:
unacharset=False
self.rawinput = self.rawinput[count:] #here the interchange should start
if self.rawinput[:3] != 'UNB':
raise botslib.InMessageError(_(u'No "UNB" at the start of file. Maybe not edifact.'))
self.ta_info['charset'] = self.rawinput[4:8]
self.ta_info['version'] = self.rawinput[9:10]
if not unacharset:
if self.rawinput[3:4]=='+' and self.rawinput[8:9]==':': #assume standard separators.
self.ta_info['sfield_sep'] = ':'
self.ta_info['field_sep'] = '+'
self.ta_info['decimaal'] = '.'
self.ta_info['escape'] = '?'
self.ta_info['reserve'] = '' #for now: no support of repeating dataelements
self.ta_info['record_sep'] = "'"
elif self.rawinput[3:4]=='\x1D' and self.rawinput[8:9]=='\x1F': #check if UNOB separators are used
self.ta_info['sfield_sep'] = '\x1F'
self.ta_info['field_sep'] = '\x1D'
self.ta_info['decimaal'] = '.'
self.ta_info['escape'] = ''
self.ta_info['reserve'] = '' #for now: no support of repeating dataelements
self.ta_info['record_sep'] = '\x1C'
else:
raise botslib.InMessageError(_(u'Incoming edi file uses non-standard separators - should use UNA.'))
try:
self.rawinput = self.rawinput.decode(self.ta_info['charset'],self.ta_info['checkcharsetin'])
except LookupError:
raise botslib.InMessageError(_(u'Incoming edi file has unknown charset "$charset".'),charset=self.ta_info['charset'])
except UnicodeDecodeError, flup:
raise botslib.InMessageError(_(u'not allowed chars in incoming edi file (for translation) at/after filepos: $content'),content=flup[2])
def checkenvelope(self):
self.confirmationlist = [] #information about the edifact file for confirmation/CONTRL; for edifact this is done per interchange (UNB-UNZ)
for nodeunb in self.getloop({'BOTSID':'UNB'}):
botsglobal.logmap.debug(u'Start parsing edifact envelopes')
sender = nodeunb.get({'BOTSID':'UNB','S002.0004':None})
receiver = nodeunb.get({'BOTSID':'UNB','S003.0010':None})
UNBreference = nodeunb.get({'BOTSID':'UNB','0020':None})
UNZreference = nodeunb.get({'BOTSID':'UNB'},{'BOTSID':'UNZ','0020':None})
if UNBreference != UNZreference:
raise botslib.InMessageError(_(u'UNB-reference is "$UNBreference"; should be equal to UNZ-reference "$UNZreference".'),UNBreference=UNBreference,UNZreference=UNZreference)
UNZcount = nodeunb.get({'BOTSID':'UNB'},{'BOTSID':'UNZ','0036':None})
messagecount = len(nodeunb.children) - 1
if int(UNZcount) != messagecount:
raise botslib.InMessageError(_(u'Count in messages in UNZ is $UNZcount; should be equal to number of messages $messagecount.'),UNZcount=UNZcount,messagecount=messagecount)
self.confirmationlist.append({'UNBreference':UNBreference,'UNZcount':UNZcount,'sender':sender,'receiver':receiver,'UNHlist':[]}) #gather information about functional group (GS-GE)
for nodeunh in nodeunb.getloop({'BOTSID':'UNB'},{'BOTSID':'UNH'}):
UNHtype = nodeunh.get({'BOTSID':'UNH','S009.0065':None})
UNHversion = nodeunh.get({'BOTSID':'UNH','S009.0052':None})
UNHrelease = nodeunh.get({'BOTSID':'UNH','S009.0054':None})
UNHcontrollingagency = nodeunh.get({'BOTSID':'UNH','S009.0051':None})
UNHassociationassigned = nodeunh.get({'BOTSID':'UNH','S009.0057':None})
UNHreference = nodeunh.get({'BOTSID':'UNH','0062':None})
UNTreference = nodeunh.get({'BOTSID':'UNH'},{'BOTSID':'UNT','0062':None})
if UNHreference != UNTreference:
raise botslib.InMessageError(_(u'UNH-reference is "$UNHreference"; should be equal to UNT-reference "$UNTreference".'),UNHreference=UNHreference,UNTreference=UNTreference)
UNTcount = nodeunh.get({'BOTSID':'UNH'},{'BOTSID':'UNT','0074':None})
segmentcount = nodeunh.getcount()
if int(UNTcount) != segmentcount:
raise botslib.InMessageError(_(u'Segmentcount in UNT is $UNTcount; should be equal to number of segments $segmentcount.'),UNTcount=UNTcount,segmentcount=segmentcount)
self.confirmationlist[-1]['UNHlist'].append({'UNHreference':UNHreference,'UNHtype':UNHtype,'UNHversion':UNHversion,'UNHrelease':UNHrelease,'UNHcontrollingagency':UNHcontrollingagency,'UNHassociationassigned':UNHassociationassigned}) #add info per message to interchange
for nodeung in nodeunb.getloop({'BOTSID':'UNB'},{'BOTSID':'UNG'}):
UNGreference = nodeung.get({'BOTSID':'UNG','0048':None})
UNEreference = nodeung.get({'BOTSID':'UNG'},{'BOTSID':'UNE','0048':None})
if UNGreference != UNEreference:
raise botslib.InMessageError(_(u'UNG-reference is "$UNGreference"; should be equal to UNE-reference "$UNEreference".'),UNGreference=UNGreference,UNEreference=UNEreference)
UNEcount = nodeung.get({'BOTSID':'UNG'},{'BOTSID':'UNE','0060':None})
groupcount = len(nodeung.children) - 1
if int(UNEcount) != groupcount:
raise botslib.InMessageError(_(u'Groupcount in UNE is $UNEcount; should be equal to number of groups $groupcount.'),UNEcount=UNEcount,groupcount=groupcount)
for nodeunh in nodeung.getloop({'BOTSID':'UNG'},{'BOTSID':'UNH'}):
UNHreference = nodeunh.get({'BOTSID':'UNH','0062':None})
UNTreference = nodeunh.get({'BOTSID':'UNH'},{'BOTSID':'UNT','0062':None})
if UNHreference != UNTreference:
raise botslib.InMessageError(_(u'UNH-reference is "$UNHreference"; should be equal to UNT-reference "$UNTreference".'),UNHreference=UNHreference,UNTreference=UNTreference)
UNTcount = nodeunh.get({'BOTSID':'UNH'},{'BOTSID':'UNT','0074':None})
segmentcount = nodeunh.getcount()
if int(UNTcount) != segmentcount:
raise botslib.InMessageError(_(u'Segmentcount in UNT is $UNTcount; should be equal to number of segments $segmentcount.'),UNTcount=UNTcount,segmentcount=segmentcount)
botsglobal.logmap.debug(u'Parsing edifact envelopes is OK')
def handleconfirm(self,ta_fromfile,error):
''' end of edi file handling.
eg writing of confirmations etc.
send CONTRL messages
parameter 'error' is not used
'''
#filter the confirmationlist
tmpconfirmationlist = []
for confirmation in self.confirmationlist:
tmpmessagelist = []
for message in confirmation['UNHlist']:
if message['UNHtype'] == 'CONTRL': #do not generate CONTRL for a CONTRL message
continue
if botslib.checkconfirmrules('send-edifact-CONTRL',idroute=self.ta_info['idroute'],idchannel=self.ta_info['fromchannel'],
topartner=confirmation['sender'],frompartner=confirmation['receiver'],
editype='edifact',messagetype=message['UNHtype']):
tmpmessagelist.append(message)
confirmation['UNHlist'] = tmpmessagelist
if not tmpmessagelist: #if no messages/transactions in interchange
continue
tmpconfirmationlist.append(confirmation)
self.confirmationlist = tmpconfirmationlist
for confirmation in self.confirmationlist:
reference=str(botslib.unique('messagecounter'))
ta_confirmation = ta_fromfile.copyta(status=TRANSLATED,reference=reference)
filename = str(ta_confirmation.idta)
out = outmessage.outmessage_init(editype='edifact',messagetype='CONTRL22UNEAN002',filename=filename) #make outmessage object
out.ta_info['frompartner']=confirmation['receiver']
out.ta_info['topartner']=confirmation['sender']
out.put({'BOTSID':'UNH','0062':reference,'S009.0065':'CONTRL','S009.0052':'2','S009.0054':'2','S009.0051':'UN','S009.0057':'EAN002'})
out.put({'BOTSID':'UNH'},{'BOTSID':'UCI','0083':'8','S002.0004':confirmation['sender'],'S003.0010':confirmation['sender'],'0020':confirmation['UNBreference']}) #8: interchange received
for message in confirmation['UNHlist']:
lou = out.putloop({'BOTSID':'UNH'},{'BOTSID':'UCM'})
lou.put({'BOTSID':'UCM','0083':'7','S009.0065':message['UNHtype'],'S009.0052':message['UNHversion'],'S009.0054':message['UNHrelease'],'S009.0051':message['UNHcontrollingagency'],'0062':message['UNHreference']})
lou.put({'BOTSID':'UCM','S009.0057':message['UNHassociationassigned']})
out.put({'BOTSID':'UNH'},{'BOTSID':'UNT','0074':out.getcount()+1,'0062':reference}) #last line (counts the segments produced in out-message)
out.writeall() #write tomessage (result of translation)
botsglobal.logger.debug(u'Send edifact confirmation (CONTRL) route "%s" fromchannel "%s" frompartner "%s" topartner "%s".',
self.ta_info['idroute'],self.ta_info['fromchannel'],confirmation['receiver'],confirmation['sender'])
self.confirminfo = dict(confirmtype='send-edifact-CONTRL',confirmed=True,confirmasked = True,confirmidta=ta_confirmation.idta) #this info is used in transform.py to update the ta.....ugly...
ta_confirmation.update(statust=OK,**out.ta_info) #update ta for confirmation
class x12(var):
''' class for edifact inmessage objects.'''
def _getmessagetype(self,messagetypefromsubtranslation,inode):
if messagetypefromsubtranslation is None:
return None
return messagetypefromsubtranslation + inode.record['GS08']
def _sniff(self):
''' examine a file for syntax parameters and correctness of protocol
eg parse ISA, get charset and version
'''
#goto char that is not whitespace
for count,c in enumerate(self.rawinput):
if not c.isspace():
self.rawinput = self.rawinput[count:] #here the interchange should start
break
else:
raise botslib.InMessageError(_(u'edifile only contains whitespace.'))
if self.rawinput[:3] != 'ISA':
raise botslib.InMessageError(_(u'expect "ISA", found "$content". Probably no x12?'),content=self.rawinput[:7])
count = 0
for c in self.rawinput[:120]:
if c in '\r\n' and count!=105:
continue
count +=1
if count==4:
self.ta_info['field_sep'] = c
elif count==105:
self.ta_info['sfield_sep'] = c
elif count==106:
self.ta_info['record_sep'] = c
break
# ISA-version: if <004030: SHOULD use repeating element?
self.ta_info['reserve']=''
self.ta_info['skip_char'] = self.ta_info['skip_char'].replace(self.ta_info['record_sep'],'') #if <CR> is segment terminator: cannot be in the skip_char-string!
#more ISA's in file: find IEA+
def checkenvelope(self):
''' check envelopes, gather information to generate 997 '''
self.confirmationlist = [] #information about the x12 file for confirmation/997; for x12 this is done per functional group
#~ self.root.display()
for nodeisa in self.getloop({'BOTSID':'ISA'}):
botsglobal.logmap.debug(u'Start parsing X12 envelopes')
sender = nodeisa.get({'BOTSID':'ISA','ISA06':None})
receiver = nodeisa.get({'BOTSID':'ISA','ISA08':None})
ISAreference = nodeisa.get({'BOTSID':'ISA','ISA13':None})
IEAreference = nodeisa.get({'BOTSID':'ISA'},{'BOTSID':'IEA','IEA02':None})
if ISAreference != IEAreference:
raise botslib.InMessageError(_(u'ISA-reference is "$ISAreference"; should be equal to IEA-reference "$IEAreference".'),ISAreference=ISAreference,IEAreference=IEAreference)
IEAcount = nodeisa.get({'BOTSID':'ISA'},{'BOTSID':'IEA','IEA01':None})
groupcount = nodeisa.getcountoccurrences({'BOTSID':'ISA'},{'BOTSID':'GS'})
if int(IEAcount) != groupcount:
raise botslib.InMessageError(_(u'Count in IEA-IEA01 is $IEAcount; should be equal to number of groups $groupcount.'),IEAcount=IEAcount,groupcount=groupcount)
for nodegs in nodeisa.getloop({'BOTSID':'ISA'},{'BOTSID':'GS'}):
GSqualifier = nodegs.get({'BOTSID':'GS','GS01':None})
GSreference = nodegs.get({'BOTSID':'GS','GS06':None})
GEreference = nodegs.get({'BOTSID':'GS'},{'BOTSID':'GE','GE02':None})
if GSreference != GEreference:
raise botslib.InMessageError(_(u'GS-reference is "$GSreference"; should be equal to GE-reference "$GEreference".'),GSreference=GSreference,GEreference=GEreference)
GEcount = nodegs.get({'BOTSID':'GS'},{'BOTSID':'GE','GE01':None})
messagecount = len(nodegs.children) - 1
if int(GEcount) != messagecount:
raise botslib.InMessageError(_(u'Count in GE-GE01 is $GEcount; should be equal to number of transactions: $messagecount.'),GEcount=GEcount,messagecount=messagecount)
self.confirmationlist.append({'GSqualifier':GSqualifier,'GSreference':GSreference,'GEcount':GEcount,'sender':sender,'receiver':receiver,'STlist':[]}) #gather information about functional group (GS-GE)
for nodest in nodegs.getloop({'BOTSID':'GS'},{'BOTSID':'ST'}):
STqualifier = nodest.get({'BOTSID':'ST','ST01':None})
STreference = nodest.get({'BOTSID':'ST','ST02':None})
SEreference = nodest.get({'BOTSID':'ST'},{'BOTSID':'SE','SE02':None})
#referencefields are numerical; should I compare values??
if STreference != SEreference:
raise botslib.InMessageError(_(u'ST-reference is "$STreference"; should be equal to SE-reference "$SEreference".'),STreference=STreference,SEreference=SEreference)
SEcount = nodest.get({'BOTSID':'ST'},{'BOTSID':'SE','SE01':None})
segmentcount = nodest.getcount()
if int(SEcount) != segmentcount:
raise botslib.InMessageError(_(u'Count in SE-SE01 is $SEcount; should be equal to number of segments $segmentcount.'),SEcount=SEcount,segmentcount=segmentcount)
self.confirmationlist[-1]['STlist'].append({'STreference':STreference,'STqualifier':STqualifier}) #add info per message to functional group
botsglobal.logmap.debug(u'Parsing X12 envelopes is OK')
def handleconfirm(self,ta_fromfile,error):
''' end of edi file handling.
eg writing of confirmations etc.
send 997 messages
parameter 'error' is not used
'''
#filter the confirmationlist
tmpconfirmationlist = []
for confirmation in self.confirmationlist:
if confirmation['GSqualifier'] == 'FA': #do not generate 997 for 997
continue
tmpmessagelist = []
for message in confirmation['STlist']:
if botslib.checkconfirmrules('send-x12-997',idroute=self.ta_info['idroute'],idchannel=self.ta_info['fromchannel'],
topartner=confirmation['sender'],frompartner=confirmation['receiver'],
editype='x12',messagetype=message['STqualifier']):
tmpmessagelist.append(message)
confirmation['STlist'] = tmpmessagelist
if not tmpmessagelist: #if no messages/transactions in GS-GE
continue
tmpconfirmationlist.append(confirmation)
self.confirmationlist = tmpconfirmationlist
for confirmation in self.confirmationlist:
reference=str(botslib.unique('messagecounter'))
ta_confirmation = ta_fromfile.copyta(status=TRANSLATED,reference=reference)
filename = str(ta_confirmation.idta)
out = outmessage.outmessage_init(editype='x12',messagetype='997004010',filename=filename) #make outmessage object
out.ta_info['frompartner']=confirmation['receiver']
out.ta_info['topartner']=confirmation['sender']
out.put({'BOTSID':'ST','ST01':'997','ST02':reference})
out.put({'BOTSID':'ST'},{'BOTSID':'AK1','AK101':confirmation['GSqualifier'],'AK102':confirmation['GSreference']})
out.put({'BOTSID':'ST'},{'BOTSID':'AK9','AK901':'A','AK902':confirmation['GEcount'],'AK903':confirmation['GEcount'],'AK904':confirmation['GEcount']})
for message in confirmation['STlist']:
lou = out.putloop({'BOTSID':'ST'},{'BOTSID':'AK2'})
lou.put({'BOTSID':'AK2','AK201':message['STqualifier'],'AK202':message['STreference']})
lou.put({'BOTSID':'AK2'},{'BOTSID':'AK5','AK501':'A'})
out.put({'BOTSID':'ST'},{'BOTSID':'SE','SE01':out.getcount()+1,'SE02':reference}) #last line (counts the segments produced in out-message)
out.writeall() #write tomessage (result of translation)
botsglobal.logger.debug(u'Send x12 confirmation (997) route "%s" fromchannel "%s" frompartner "%s" topartner "%s".',
self.ta_info['idroute'],self.ta_info['fromchannel'],confirmation['receiver'],confirmation['sender'])
self.confirminfo = dict(confirmtype='send-x12-997',confirmed=True,confirmasked = True,confirmidta=ta_confirmation.idta) #this info is used in transform.py to update the ta.....ugly...
ta_confirmation.update(statust=OK,**out.ta_info) #update ta for confirmation
class tradacoms(var):
def checkenvelope(self):
for nodeSTX in self.getloop({'BOTSID':'STX'}):
botsglobal.logmap.debug(u'Start parsing tradacoms envelopes')
ENDcount = nodeSTX.get({'BOTSID':'STX'},{'BOTSID':'END','NMST':None})
messagecount = len(nodeSTX.children) - 1
if int(ENDcount) != messagecount:
raise botslib.InMessageError(_(u'Count in messages in END is $ENDcount; should be equal to number of messages $messagecount'),ENDcount=ENDcount,messagecount=messagecount)
firstmessage = True
for nodeMHD in nodeSTX.getloop({'BOTSID':'STX'},{'BOTSID':'MHD'}):
if firstmessage: #
nodeSTX.queries = {'messagetype':nodeMHD.queries['messagetype']}
firstmessage = False
MTRcount = nodeMHD.get({'BOTSID':'MHD'},{'BOTSID':'MTR','NOSG':None})
segmentcount = nodeMHD.getcount()
if int(MTRcount) != segmentcount:
raise botslib.InMessageError(_(u'Segmentcount in MTR is $MTRcount; should be equal to number of segments $segmentcount'),MTRcount=MTRcount,segmentcount=segmentcount)
botsglobal.logmap.debug(u'Parsing tradacoms envelopes is OK')
class xml(var):
''' class for ediobjects in XML. Uses ElementTree'''
def initfromfile(self):
botsglobal.logger.debug(u'read edi file "%s".',self.ta_info['filename'])
filename=botslib.abspathdata(self.ta_info['filename'])
if self.ta_info['messagetype'] == 'mailbag':
''' the messagetype is not know.
bots reads file usersys/grammars/xml/mailbag.py, and uses 'mailbagsearch' to determine the messagetype
mailbagsearch is a list, containing python dicts. Dict consist of 'xpath', 'messagetype' and (optionally) 'content'.
'xpath' is a xpath to use on xml-file (using elementtree xpath functionality)
if found, and 'content' in the dict; if 'content' is equal to value found by xpath-search, then set messagetype.
if found, and no 'content' in the dict; set messagetype.
'''
try:
module,grammarname = botslib.botsimport('grammars','xml.mailbag')
mailbagsearch = getattr(module, 'mailbagsearch')
except AttributeError:
botsglobal.logger.error(u'missing mailbagsearch in mailbag definitions for xml.')
raise
except ImportError:
botsglobal.logger.error(u'missing mailbag definitions for xml, should be there.')
raise
parser = ET.XMLParser()
try:
extra_character_entity = getattr(module, 'extra_character_entity')
for key,value in extra_character_entity.items():
parser.entity[key] = value
except AttributeError:
pass #there is no extra_character_entity in the mailbag definitions, is OK.
etree = ET.ElementTree() #ElementTree: lexes, parses, makes etree; etree is quite similar to bots-node trees but conversion is needed
etreeroot = etree.parse(filename, parser)
for item in mailbagsearch:
if 'xpath' not in item or 'messagetype' not in item:
raise botslib.InMessageError(_(u'invalid search parameters in xml mailbag.'))
#~ print 'search' ,item
found = etree.find(item['xpath'])
if found is not None:
#~ print ' found'
if 'content' in item and found.text != item['content']:
continue
self.ta_info['messagetype'] = item['messagetype']
#~ print ' found right messagedefinition'
#~ continue
break
else:
raise botslib.InMessageError(_(u'could not find right xml messagetype for mailbag.'))
self.defmessage = grammar.grammarread(self.ta_info['editype'],self.ta_info['messagetype'])
botslib.updateunlessset(self.ta_info,self.defmessage.syntax) #write values from grammar to self.ta_info - unless these values are already set eg by sniffing
else:
self.defmessage = grammar.grammarread(self.ta_info['editype'],self.ta_info['messagetype'])
botslib.updateunlessset(self.ta_info,self.defmessage.syntax) #write values from grammar to self.ta_info - unless these values are already set eg by sniffing
parser = ET.XMLParser()
for key,value in self.ta_info['extra_character_entity'].items():
parser.entity[key] = value
etree = ET.ElementTree() #ElementTree: lexes, parses, makes etree; etree is quite similar to bots-node trees but conversion is needed
etreeroot = etree.parse(filename, parser)
self.stack = []
self.root = self.etree2botstree(etreeroot) #convert etree to bots-nodes-tree
self.normalisetree(self.root)
def etree2botstree(self,xmlnode):
self.stack.append(xmlnode.tag)
newnode = node.Node(record=self.etreenode2botstreenode(xmlnode))
for xmlchildnode in xmlnode: #for every node in mpathtree
if self.isfield(xmlchildnode): #if no child entities: treat as 'field': this misses xml where attributes are used as fields....testing for repeating is no good...
if xmlchildnode.text and not xmlchildnode.text.isspace(): #skip empty xml entity
newnode.record[xmlchildnode.tag]=xmlchildnode.text #add as a field
hastxt = True
else:
hastxt = False
for key,value in xmlchildnode.items(): #convert attributes to fields.
if not hastxt:
newnode.record[xmlchildnode.tag]='' #add empty content
hastxt = True
newnode.record[xmlchildnode.tag + self.ta_info['attributemarker'] + key]=value #add as a field
else: #xmlchildnode is a record
newnode.append(self.etree2botstree(xmlchildnode)) #add as a node/record
#~ if botsglobal.ini.getboolean('settings','readrecorddebug',False):
#~ botsglobal.logger.debug('read record "%s":',newnode.record['BOTSID'])
#~ for key,value in newnode.record.items():
#~ botsglobal.logger.debug(' "%s" : "%s"',key,value)
self.stack.pop()
#~ print self.stack
return newnode
def etreenode2botstreenode(self,xmlnode):
''' build a dict from xml-node'''
build = dict((xmlnode.tag + self.ta_info['attributemarker'] + key,value) for key,value in xmlnode.items()) #convert attributes to fields.
build['BOTSID']=xmlnode.tag #'record' tag
if xmlnode.text and not xmlnode.text.isspace():
build['BOTSCONTENT']=xmlnode.text
return build
def isfield(self,xmlchildnode):
''' check if xmlchildnode is field (or record)'''
#~ print 'examine record in stack',xmlchildnode.tag,self.stack
str_recordlist = self.defmessage.structure
for record in self.stack: #find right level in structure
for str_record in str_recordlist:
#~ print ' find right level comparing',record,str_record[0]
if record == str_record[0]:
if 4 not in str_record: #structure record contains no level: must be an attribute
return True
str_recordlist = str_record[4]
break
else:
raise botslib.InMessageError(_(u'Unknown XML-tag in "$record".'),record=record)
for str_record in str_recordlist: #see if xmlchildnode is in structure
#~ print ' is xmlhildnode in this level comparing',xmlchildnode.tag,str_record[0]
if xmlchildnode.tag == str_record[0]:
#~ print 'found'
return False
#xml tag not found in structure: so must be field; validity is check later on with grammar
if len(xmlchildnode)==0:
return True
return False
class xmlnocheck(xml):
''' class for ediobjects in XML. Uses ElementTree'''
def normalisetree(self,node):
pass
def isfield(self,xmlchildnode):
if len(xmlchildnode)==0:
return True
return False
class json(var):
def initfromfile(self):
self.defmessage = grammar.grammarread(self.ta_info['editype'],self.ta_info['messagetype'])
botslib.updateunlessset(self.ta_info,self.defmessage.syntax) #write values from grammar to self.ta_info - unless these values are already set eg by sniffing
self._readcontent_edifile()
jsonobject = simplejson.loads(self.rawinput)
del self.rawinput
if isinstance(jsonobject,list):
self.root=node.Node() #initialise empty node.
self.root.children = self.dojsonlist(jsonobject,self.getrootID()) #fill root with children
for child in self.root.children:
if not child.record: #sanity test: the children must have content
raise botslib.InMessageError(_(u'no usable content.'))
self.normalisetree(child)
elif isinstance(jsonobject,dict):
if len(jsonobject)==1 and isinstance(jsonobject.values()[0],dict):
# best structure: {rootid:{id2:<dict, list>}}
self.root = self.dojsonobject(jsonobject.values()[0],jsonobject.keys()[0])
elif len(jsonobject)==1 and isinstance(jsonobject.values()[0],list) :
#root dict has no name; use value from grammar for rootID; {id2:<dict, list>}
self.root=node.Node(record={'BOTSID': self.getrootID()}) #initialise empty node.
self.root.children = self.dojsonlist(jsonobject.values()[0],jsonobject.keys()[0])
else:
#~ print self.getrootID()
self.root = self.dojsonobject(jsonobject,self.getrootID())
#~ print self.root
if not self.root:
raise botslib.InMessageError(_(u'no usable content.'))
self.normalisetree(self.root)
else:
#root in JSON is neither dict or list.
raise botslib.InMessageError(_(u'Content must be a "list" or "object".'))
def getrootID(self):
return self.defmessage.structure[0][ID]
def dojsonlist(self,jsonobject,name):
lijst=[] #initialise empty list, used to append a listof (converted) json objects
for i in jsonobject:
if isinstance(i,dict): #check list item is dict/object
newnode = self.dojsonobject(i,name)
if newnode:
lijst.append(newnode)
elif self.ta_info['checkunknownentities']:
raise botslib.InMessageError(_(u'List content in must be a "object".'))
return lijst
def dojsonobject(self,jsonobject,name):
thisnode=node.Node(record={}) #initialise empty node.
for key,value in jsonobject.items():
if value is None:
continue
elif isinstance(value,basestring): #json field; map to field in node.record
thisnode.record[key]=value
elif isinstance(value,dict):
newnode = self.dojsonobject(value,key)
if newnode:
thisnode.append(newnode)
elif isinstance(value,list):
thisnode.children.extend(self.dojsonlist(value,key))
elif isinstance(value,(int,long,float)): #json field; map to field in node.record
thisnode.record[key]=str(value)
else:
if self.ta_info['checkunknownentities']:
raise botslib.InMessageError(_(u'Key "$key" value "$value": is not string, list or dict.'),key=key,value=value)
thisnode.record[key]=str(value)
if not thisnode.record and not thisnode.children:
return None #node is empty...
thisnode.record['BOTSID']=name
return thisnode
class jsonnocheck(json):
def normalisetree(self,node):
pass
def getrootID(self):
return self.ta_info['defaultBOTSIDroot'] #as there is no structure in grammar, use value form syntax.
class database(jsonnocheck):
pass
class db(Inmessage):
''' the database-object is unpickled, and passed to the mapping script.
'''
def initfromfile(self):
botsglobal.logger.debug(u'read edi file "%s".',self.ta_info['filename'])
f = botslib.opendata(filename=self.ta_info['filename'],mode='rb')
self.root = pickle.load(f)
f.close()
def nextmessage(self):
yield self
class raw(Inmessage):
''' the file object is just read and passed to the mapping script.
'''
def initfromfile(self):
botsglobal.logger.debug(u'read edi file "%s".',self.ta_info['filename'])
f = botslib.opendata(filename=self.ta_info['filename'],mode='rb')
self.root = f.read()
f.close()
def nextmessage(self):
yield self
| Python |
codeconversions = {
'351':'AAK',
'35E':'AAK',
'220':'ON',
'224':'ON',
'50E':'ON',
'83':'IV',
'380':'IV',
'384':'IV',
'TESTIN':'TESTOUT',
}
| Python |
""" Python Character Mapping Codec generated from CP1252.TXT with gencodec.py.
Written by Marc-Andre Lemburg (mal@lemburg.com).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
(c) Copyright 2000 Guido van Rossum.
Adapted by Henk-Jan Ebbers for Bots open source EDI translator
Regular UNOA: UNOA char, CR, LF and Crtl-Z
"""
import codecs
import sys
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_map)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_map)
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
def getregentry():
return codecs.CodecInfo(
name='unoa',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
### Decoding Map
#decoding_map = codecs.make_identity_dict(range(128))
#decoding_map.update({
decoding_map = {
# 0x0000:0x0000, #NUL
# 0x0001:0x0000, #SOH
# 0x0002:0x0000, #STX
# 0x0003:0x0000, #ETX
# 0x0004:0x0000, #EOT
# 0x0005:0x0000, #ENQ
# 0x0006:0x0000, #ACK
# 0x0007:0x0000, #Bell
# 0x0008:0x0000, #BackSpace
# 0x0009:0x0000, #Tab
0x000a:0x000a, #lf
# 0x000b:0x0000, #Vertical Tab
# 0x000c:0x0000, #FormFeed
0x000d:0x000d, #cr
# 0x000e:0x0000, #SO
# 0x000f:0x0000, #SI
# 0x0010:0x0000, #DLE
# 0x0011:0x0000, #DC1
# 0x0012:0x0000, #DC2
# 0x0013:0x0000, #DC3
# 0x0014:0x0000, #DC4
# 0x0015:0x0000, #NAK
# 0x0016:0x0000, #SYN
# 0x0017:0x0000, #ETB
# 0x0018:0x0000, #CAN
# 0x0019:0x0000, #EM
0x001a:0x001a, #SUB, cntrl-Z
# 0x001b:0x0000, #ESC
# 0x001c:0x0000, #FS
# 0x001d:0x0000, #GS
# 0x001e:0x0000, #RS
# 0x001f:0x0000, #US
0x0020:0x0020, #<space>
0x0021:0x0021, #!
0x0022:0x0022, #"
# 0x0023:0x0023, ##
# 0x0024:0x0024, #$
0x0025:0x0025, #%
0x0026:0x0026, #&
0x0027:0x0027, #'
0x0028:0x0028, #(
0x0029:0x0029, #)
0x002a:0x002a, #*
0x002b:0x002b, #+
0x002c:0x002c, #,
0x002d:0x002d, #-
0x002e:0x002e, #.
0x002f:0x002f, #/
0x0030:0x0030, #0
0x0031:0x0031, #1
0x0032:0x0032, #2
0x0033:0x0033, #3
0x0034:0x0034, #4
0x0035:0x0035, #5
0x0036:0x0036, #6
0x0037:0x0037, #7
0x0038:0x0038, #8
0x0039:0x0039, #9
0x003a:0x003a, #:
0x003b:0x003b, #;
0x003c:0x003c, #<
0x003d:0x003d, #=
0x003e:0x003e, #>
0x003f:0x003f, #?
# 0x0040:0x0040, #@
0X0041:0X0041, #A
0X0042:0X0042, #B
0X0043:0X0043, #C
0X0044:0X0044, #D
0X0045:0X0045, #E
0X0046:0X0046, #F
0X0047:0X0047, #G
0X0048:0X0048, #H
0X0049:0X0049, #I
0X004A:0X004A, #J
0X004B:0X004B, #K
0X004C:0X004C, #L
0X004D:0X004D, #M
0X004E:0X004E, #N
0X004F:0X004F, #O
0X0050:0X0050, #P
0X0051:0X0051, #Q
0X0052:0X0052, #R
0X0053:0X0053, #S
0X0054:0X0054, #T
0X0055:0X0055, #U
0X0056:0X0056, #V
0X0057:0X0057, #W
0X0058:0X0058, #X
0X0059:0X0059, #Y
0X005A:0X005A, #Z
# 0x005b:0x005b, #[
# 0x005c:0x005c, #\
# 0x005d:0x005d, #]
# 0x005e:0x005e, #^
# 0x005f:0x005f, #_
# 0x0060:0x0060, #`
# 0x0061:0x0041, #a
# 0x0062:0x0042, #b
# 0x0063:0x0043, #c
# 0x0064:0x0044, #d
# 0x0065:0x0045, #e
# 0x0066:0x0046, #f
# 0x0067:0x0047, #g
# 0x0068:0x0048, #h
# 0x0069:0x0049, #i
# 0x006a:0x004a, #j
# 0x006b:0x004b, #k
# 0x006c:0x004c, #l
# 0x006d:0x004d, #m
# 0x006e:0x004e, #n
# 0x006f:0x004f, #o
# 0x0070:0x0050, #p
# 0x0071:0x0051, #q
# 0x0072:0x0052, #r
# 0x0073:0x0053, #s
# 0x0074:0x0054, #t
# 0x0075:0x0055, #u
# 0x0076:0x0056, #v
# 0x0077:0x0057, #w
# 0x0078:0x0058, #x
# 0x0079:0x0059, #y
# 0x007a:0x005a, #z
# 0x007b:0x007b, #{
# 0x007c:0x007c, #|
# 0x007d:0x007d, #}
# 0x007e:0x007e, #~
# 0x007f:0x007f, #del
}
### Encoding Map
encoding_map = codecs.make_encoding_map(decoding_map)
| Python |
""" Python Character Mapping Codec generated from CP1252.TXT with gencodec.py.
Written by Marc-Andre Lemburg (mal@lemburg.com).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
(c) Copyright 2000 Guido van Rossum.
Adapted by Henk-Jan Ebbers for Bots open source EDI translator
Regular UNOB: UNOB char, CR, LF and Crtl-Z
"""
import codecs
import sys
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_map)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_map)
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
def getregentry():
return codecs.CodecInfo(
name='unob',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
### Decoding Map
#decoding_map = codecs.make_identity_dict(range(128))
#decoding_map.update({
decoding_map = {
# 0x0000:0x0000, #NUL
# 0x0001:0x0000, #SOH
# 0x0002:0x0000, #STX
# 0x0003:0x0000, #ETX
# 0x0004:0x0000, #EOT
# 0x0005:0x0000, #ENQ
# 0x0006:0x0000, #ACK
# 0x0007:0x0000, #Bell
# 0x0008:0x0000, #BackSpace
# 0x0009:0x0000, #Tab
0x000a:0x000a, #lf
# 0x000b:0x0000, #Vertical Tab
# 0x000c:0x0000, #FormFeed
0x000d:0x000d, #cr
# 0x000e:0x0000, #SO
# 0x000f:0x0000, #SI
# 0x0010:0x0000, #DLE
# 0x0011:0x0000, #DC1
# 0x0012:0x0000, #DC2
# 0x0013:0x0000, #DC3
# 0x0014:0x0000, #DC4
# 0x0015:0x0000, #NAK
# 0x0016:0x0000, #SYN
# 0x0017:0x0000, #ETB
# 0x0018:0x0000, #CAN
# 0x0019:0x0000, #EM
0x001a:0x001a, #SUB, cntrl-Z
# 0x001b:0x0000, #ESC
0x001c:0x001c, #FS
0x001d:0x001d, #GS
# 0x001e:0x0000, #RS
0x001f:0x001f, #US
0x0020:0x0020, #<SPACE>
0x0021:0x0021, #!
0x0022:0x0022, #"
# 0x0023:0x0023, ##
# 0x0024:0x0024, #$
0x0025:0x0025, #%
0x0026:0x0026, #&
0x0027:0x0027, #'
0x0028:0x0028, #(
0x0029:0x0029, #)
0x002A:0x002A, #*
0x002B:0x002B, #+
0x002C:0x002C, #,
0x002D:0x002D, #-
0x002E:0x002E, #.
0x002F:0x002F, #/
0x0030:0x0030, #0
0x0031:0x0031, #1
0x0032:0x0032, #2
0x0033:0x0033, #3
0x0034:0x0034, #4
0x0035:0x0035, #5
0x0036:0x0036, #6
0x0037:0x0037, #7
0x0038:0x0038, #8
0x0039:0x0039, #9
0x003A:0x003A, #:
0x003B:0x003B, #;
0x003C:0x003C, #<
0x003D:0x003D, #=
0x003E:0x003E, #>
0x003F:0x003F, #?
# 0x0040:0x0040, #@
0x0041:0x0041, #A
0x0042:0x0042, #B
0x0043:0x0043, #C
0x0044:0x0044, #D
0x0045:0x0045, #E
0x0046:0x0046, #F
0x0047:0x0047, #G
0x0048:0x0048, #H
0x0049:0x0049, #I
0x004A:0x004A, #J
0x004B:0x004B, #K
0x004C:0x004C, #L
0x004D:0x004D, #M
0x004E:0x004E, #N
0x004F:0x004F, #O
0x0050:0x0050, #P
0x0051:0x0051, #Q
0x0052:0x0052, #R
0x0053:0x0053, #S
0x0054:0x0054, #T
0x0055:0x0055, #U
0x0056:0x0056, #V
0x0057:0x0057, #W
0x0058:0x0058, #X
0x0059:0x0059, #Y
0x005A:0x005A, #Z
# 0x005B:0x005B, #[
# 0x005C:0x005C, #\
# 0x005D:0x005D, #]
# 0x005E:0x005E, #^
# 0x005F:0x005F, #_
# 0x0060:0x0060, #`
0x0061:0x0061, #a
0x0062:0x0062, #b
0x0063:0x0063, #c
0x0064:0x0064, #d
0x0065:0x0065, #e
0x0066:0x0066, #f
0x0067:0x0067, #g
0x0068:0x0068, #h
0x0069:0x0069, #i
0x006a:0x006a, #j
0x006b:0x006b, #k
0x006c:0x006c, #l
0x006d:0x006d, #m
0x006e:0x006e, #n
0x006f:0x006f, #o
0x0070:0x0070, #p
0x0071:0x0071, #q
0x0072:0x0072, #r
0x0073:0x0073, #s
0x0074:0x0074, #t
0x0075:0x0075, #u
0x0076:0x0076, #v
0x0077:0x0077, #w
0x0078:0x0078, #x
0x0079:0x0079, #y
0x007a:0x007a, #z
# 0x007B:0x007B, #{
# 0x007C:0x007C, #|
# 0x007D:0x007D, #}
# 0x007E:0x007E, #~
# 0x007F:0x007F, #DEL
}
### Encoding Map
encoding_map = codecs.make_encoding_map(decoding_map)
| Python |
import shutil
import time
from django.utils.translation import ugettext as _
#bots-modules
import botslib
import botsglobal
import grammar
import outmessage
from botsconfig import *
@botslib.log_session
def mergemessages(startstatus=TRANSLATED,endstatus=MERGED,idroute=''):
''' Merges en envelopes several messages to one file;
In db-ta: attribute 'merge' indicates message should be merged with similar messages; 'merge' is generated in translation from messagetype-grammar
If merge==False: 1 message per envelope - no merging, else append all similar messages to one file
Implementation as separate loops: one for merge&envelope, another for enveloping only
db-ta status TRANSLATED---->MERGED
'''
outerqueryparameters = {'status':startstatus,'statust':OK,'idroute':idroute,'rootidta':botslib.get_minta4query(),'merge':False}
#**********for messages only to envelope (no merging)
for row in botslib.query(u'''SELECT editype,messagetype,frompartner,topartner,testindicator,charset,contenttype,tochannel,envelope,nrmessages,idta,filename,idroute,merge
FROM ta
WHERE idta>%(rootidta)s
AND status=%(status)s
AND statust=%(statust)s
AND idroute=%(idroute)s
AND merge=%(merge)s
''',
outerqueryparameters):
try:
ta_info = dict([(key,row[key]) for key in row.keys()])
#~ ta_info={'merge':False,'idroute':idroute}
#~ for key in row.keys():
#~ ta_info[key] = row[key]
ta_fromfile = botslib.OldTransaction(row['idta']) #edi message to envelope
ta_tofile=ta_fromfile.copyta(status=endstatus) #edifile for enveloped message; attributes of not-enveloped message are copied...
#~ ta_fromfile.update(child=ta_tofile.idta) #??there is already a parent-child relation (1-1)...
ta_info['filename'] = str(ta_tofile.idta) #create filename for enveloped message
botsglobal.logger.debug(u'Envelope 1 message editype: %s, messagetype: %s.',ta_info['editype'],ta_info['messagetype'])
envelope(ta_info,[row['filename']])
except:
txt=botslib.txtexc()
ta_tofile.update(statust=ERROR,errortext=txt)
else:
ta_fromfile.update(statust=DONE)
ta_tofile.update(statust=OK,**ta_info) #selection is used to update enveloped message;
#**********for messages to merge & envelope
#all GROUP BY fields must be used in SELECT!
#as files get merged: can not copy idta; must extract relevant attributes.
outerqueryparameters['merge']=True
for row in botslib.query(u'''SELECT editype,messagetype,frompartner,topartner,tochannel,testindicator,charset,contenttype,envelope,sum(nrmessages) as nrmessages
FROM ta
WHERE idta>%(rootidta)s
AND status=%(status)s
AND statust=%(statust)s
AND idroute=%(idroute)s
AND merge=%(merge)s
GROUP BY editype,messagetype,frompartner,topartner,tochannel,testindicator,charset,contenttype,envelope
''',
outerqueryparameters):
try:
ta_info = dict([(key,row[key]) for key in row.keys()])
ta_info.update({'merge':False,'idroute':idroute})
#~ for key in row.keys():
#~ ta_info[key] = row[key]
ta_tofile=botslib.NewTransaction(status=endstatus,idroute=idroute) #edifile for enveloped messages
ta_info['filename'] = str(ta_tofile.idta) #create filename for enveloped message
innerqueryparameters = ta_info.copy()
innerqueryparameters.update(outerqueryparameters)
ta_list=[]
#gather individual idta and filenames
#explicitly allow formpartner/topartner to be None/NULL
for row2 in botslib.query(u'''SELECT idta, filename
FROM ta
WHERE idta>%(rootidta)s
AND status=%(status)s
AND statust=%(statust)s
AND merge=%(merge)s
AND editype=%(editype)s
AND messagetype=%(messagetype)s
AND (frompartner=%(frompartner)s OR frompartner IS NULL)
AND (topartner=%(topartner)s OR topartner IS NULL)
AND tochannel=%(tochannel)s
AND testindicator=%(testindicator)s
AND charset=%(charset)s
AND idroute=%(idroute)s
''',
innerqueryparameters):
ta_fromfile = botslib.OldTransaction(row2['idta']) #edi message to envelope
ta_fromfile.update(statust=DONE,child=ta_tofile.idta) #st child because of n->1 relation
ta_list.append(row2['filename'])
botsglobal.logger.debug(u'Merge and envelope: editype: %s, messagetype: %s, %s messages',ta_info['editype'],ta_info['messagetype'],ta_info['nrmessages'])
envelope(ta_info,ta_list)
except:
txt=botslib.txtexc()
ta_tofile.mergefailure()
ta_tofile.update(statust=ERROR,errortext=txt)
else:
ta_tofile.update(statust=OK,**ta_info)
def envelope(ta_info,ta_list):
''' dispatch function for class Envelope and subclasses.
editype, edimessage and envelope essential for enveloping.
determine the class for enveloping:
1. empty string: no enveloping (class noenvelope); file(s) is/are just copied. No user scripting for envelope.
2. if envelope is a class in this module, use it
3. if editype is a class in this module, use it
4. if user defined enveloping in usersys/envelope/<editype>/<envelope>.<envelope>, use it (user defined scripting overrides)
Always check if user envelope script. user exits extends/replaces default enveloping.
'''
#determine which class to use for enveloping
userscript = scriptname = None
if not ta_info['envelope']: #used when enveloping is just appending files.
classtocall = noenvelope
else:
try: #see if the is user scripted enveloping
userscript,scriptname = botslib.botsimport('envelopescripts',ta_info['editype'] + '.' + ta_info['envelope'])
except ImportError: #other errors, eg syntax errors are just passed
pass
#first: check if there is a class with name ta_info['envelope'] in the user scripting
#this allows complete enveloping in user scripting
if userscript and hasattr(userscript,ta_info['envelope']):
classtocall = getattr(userscript,ta_info['envelope'])
else:
try: #check if there is a envelope class with name ta_info['envelope'] in this file (envelope.py)
classtocall = globals()[ta_info['envelope']]
except KeyError:
try: #check if there is a envelope class with name ta_info['editype'] in this file (envelope.py).
#20110919: this should disappear in the long run....use this now for orders2printenvelope and myxmlenvelop
#reason to disappear: confusing when setting up.
classtocall = globals()[ta_info['editype']]
except KeyError:
raise botslib.OutMessageError(_(u'Not found envelope "$envelope".'),envelope=ta_info['editype'])
env = classtocall(ta_info,ta_list,userscript,scriptname)
env.run()
class Envelope(object):
''' Base Class for enveloping; use subclasses.'''
def __init__(self,ta_info,ta_list,userscript,scriptname):
self.ta_info = ta_info
self.ta_list = ta_list
self.userscript = userscript
self.scriptname = scriptname
def _openoutenvelope(self,editype, messagetype_or_envelope):
''' make an outmessage object; read the grammar.'''
#self.ta_info now contains information from ta: editype, messagetype,testindicator,charset,envelope, contenttype
self.out = outmessage.outmessage_init(**self.ta_info) #make outmessage object. Init with self.out.ta_info
#read grammar for envelopesyntax. Remark: self.ta_info is not updated now
self.out.outmessagegrammarread(editype, messagetype_or_envelope)
#self.out.ta_info can contain partner dependent parameters. the partner dependent parameters have overwritten parameters fro mmessage/envelope
def writefilelist(self,tofile):
for filename in self.ta_list:
fromfile = botslib.opendata(filename, 'rb',self.ta_info['charset'])
shutil.copyfileobj(fromfile,tofile)
fromfile.close()
def filelist2absolutepaths(self):
''' utility function; some classes need absolute filenames eg for xml-including'''
return [botslib.abspathdata(filename) for filename in self.ta_list]
class noenvelope(Envelope):
''' Only copies the input files to one output file.'''
def run(self):
botslib.tryrunscript(self.userscript,self.scriptname,'ta_infocontent',ta_info=self.ta_info)
tofile = botslib.opendata(self.ta_info['filename'],'wb',self.ta_info['charset'])
self.writefilelist(tofile)
tofile.close()
class fixed(noenvelope):
pass
class csv(noenvelope):
pass
class csvheader(Envelope):
def run(self):
self._openoutenvelope(self.ta_info['editype'],self.ta_info['messagetype'])
botslib.tryrunscript(self.userscript,self.scriptname,'ta_infocontent',ta_info=self.ta_info)
#self.ta_info is not overwritten
tofile = botslib.opendata(self.ta_info['filename'],'wb',self.ta_info['charset'])
headers = dict([(field[ID],field[ID]) for field in self.out.defmessage.structure[0][FIELDS]])
self.out.put(headers)
self.out.tree2records(self.out.root)
tofile.write(self.out._record2string(self.out.records[0]))
self.writefilelist(tofile)
tofile.close()
class edifact(Envelope):
''' Generate UNB and UNZ segment; fill with data, write to interchange-file.'''
def run(self):
if not self.ta_info['topartner'] or not self.ta_info['frompartner']:
raise botslib.OutMessageError(_(u'In enveloping "frompartner" or "topartner" unknown: "$ta_info".'),ta_info=self.ta_info)
self._openoutenvelope(self.ta_info['editype'],self.ta_info['envelope'])
self.ta_info.update(self.out.ta_info)
botslib.tryrunscript(self.userscript,self.scriptname,'ta_infocontent',ta_info=self.ta_info)
#version dependent enveloping
writeUNA = False
if self.ta_info['version']<'4':
date = time.strftime('%y%m%d')
reserve = ' '
if self.ta_info['charset'] != 'UNOA':
writeUNA = True
else:
date = time.strftime('%Y%m%d')
reserve = self.ta_info['reserve']
if self.ta_info['charset'] not in ['UNOA','UNOB']:
writeUNA = True
#UNB counter is per sender or receiver
if botsglobal.ini.getboolean('settings','interchangecontrolperpartner',False):
self.ta_info['reference'] = str(botslib.unique('unbcounter_' + self.ta_info['topartner']))
else:
self.ta_info['reference'] = str(botslib.unique('unbcounter_' + self.ta_info['frompartner']))
#testindicator is more complex:
if self.ta_info['testindicator'] and self.ta_info['testindicator']!='0': #first check value from ta; do not use default
testindicator = '1'
elif self.ta_info['UNB.0035'] != '0': #than check values from grammar
testindicator = '1'
else:
testindicator = ''
#build the envelope segments (that is, the tree from which the segments will be generated)
self.out.put({'BOTSID':'UNB',
'S001.0001':self.ta_info['charset'],
'S001.0002':self.ta_info['version'],
'S002.0004':self.ta_info['frompartner'],
'S003.0010':self.ta_info['topartner'],
'S004.0017':date,
'S004.0019':time.strftime('%H%M'),
'0020':self.ta_info['reference']})
#the following fields are conditional; do not write these when empty string (separator compression does take empty strings into account)
if self.ta_info['UNB.S002.0007']:
self.out.put({'BOTSID':'UNB','S002.0007': self.ta_info['UNB.S002.0007']})
if self.ta_info['UNB.S003.0007']:
self.out.put({'BOTSID':'UNB','S003.0007': self.ta_info['UNB.S003.0007']})
if self.ta_info['UNB.0026']:
self.out.put({'BOTSID':'UNB','0026': self.ta_info['UNB.0026']})
if testindicator:
self.out.put({'BOTSID':'UNB','0035': testindicator})
self.out.put({'BOTSID':'UNB'},{'BOTSID':'UNZ','0036':self.ta_info['nrmessages'],'0020':self.ta_info['reference']}) #dummy segment; is not used
#user exit
botslib.tryrunscript(self.userscript,self.scriptname,'envelopecontent',ta_info=self.ta_info,out=self.out)
#convert the tree into segments; here only the UNB is written (first segment)
self.out.normalisetree(self.out.root)
self.out.tree2records(self.out.root)
#start doing the actual writing:
tofile = botslib.opendata(self.ta_info['filename'],'wb',self.ta_info['charset'])
if writeUNA or self.ta_info['forceUNA']:
tofile.write('UNA'+self.ta_info['sfield_sep']+self.ta_info['field_sep']+self.ta_info['decimaal']+self.ta_info['escape']+ reserve +self.ta_info['record_sep']+self.ta_info['add_crlfafterrecord_sep'])
tofile.write(self.out._record2string(self.out.records[0]))
self.writefilelist(tofile)
tofile.write(self.out._record2string(self.out.records[-1]))
tofile.close()
if self.ta_info['messagetype'][:6]!='CONTRL' and botslib.checkconfirmrules('ask-edifact-CONTRL',idroute=self.ta_info['idroute'],idchannel=self.ta_info['tochannel'],
topartner=self.ta_info['topartner'],frompartner=self.ta_info['frompartner'],
editype=self.ta_info['editype'],messagetype=self.ta_info['messagetype']):
self.ta_info['confirmtype'] = u'ask-edifact-CONTRL'
self.ta_info['confirmasked'] = True
class tradacoms(Envelope):
''' Generate STX and END segment; fill with appropriate data, write to interchange file.'''
def run(self):
if not self.ta_info['topartner'] or not self.ta_info['frompartner']:
raise botslib.OutMessageError(_(u'In enveloping "frompartner" or "topartner" unknown: "$ta_info".'),ta_info=self.ta_info)
self._openoutenvelope(self.ta_info['editype'],self.ta_info['envelope'])
self.ta_info.update(self.out.ta_info)
botslib.tryrunscript(self.userscript,self.scriptname,'ta_infocontent',ta_info=self.ta_info)
#prepare data for envelope
if botsglobal.ini.getboolean('settings','interchangecontrolperpartner',False):
self.ta_info['reference'] = str(botslib.unique('stxcounter_' + self.ta_info['topartner']))
else:
self.ta_info['reference'] = str(botslib.unique('stxcounter_' + self.ta_info['frompartner']))
#build the envelope segments (that is, the tree from which the segments will be generated)
self.out.put({'BOTSID':'STX',
'STDS1':self.ta_info['STX.STDS1'],
'STDS2':self.ta_info['STX.STDS2'],
'FROM.01':self.ta_info['frompartner'],
'UNTO.01':self.ta_info['topartner'],
'TRDT.01':time.strftime('%y%m%d'),
'TRDT.02':time.strftime('%H%M%S'),
'SNRF':self.ta_info['reference']})
if self.ta_info['STX.FROM.02']:
self.out.put({'BOTSID':'STX','FROM.02':self.ta_info['STX.FROM.02']})
if self.ta_info['STX.UNTO.02']:
self.out.put({'BOTSID':'STX','UNTO.02':self.ta_info['STX.UNTO.02']})
if self.ta_info['STX.APRF']:
self.out.put({'BOTSID':'STX','APRF':self.ta_info['STX.APRF']})
if self.ta_info['STX.PRCD']:
self.out.put({'BOTSID':'STX','PRCD':self.ta_info['STX.PRCD']})
self.out.put({'BOTSID':'STX'},{'BOTSID':'END','NMST':self.ta_info['nrmessages']}) #dummy segment; is not used
#user exit
botslib.tryrunscript(self.userscript,self.scriptname,'envelopecontent',ta_info=self.ta_info,out=self.out)
#convert the tree into segments; here only the STX is written (first segment)
self.out.normalisetree(self.out.root)
self.out.tree2records(self.out.root)
#start doing the actual writing:
tofile = botslib.opendata(self.ta_info['filename'],'wb',self.ta_info['charset'])
tofile.write(self.out._record2string(self.out.records[0]))
self.writefilelist(tofile)
tofile.write(self.out._record2string(self.out.records[-1]))
tofile.close()
class template(Envelope):
def run(self):
''' class for (test) orderprint; delevers a valid html-file.
Uses a kid-template for the enveloping/merging.
use kid to write; no envelope grammar is used
'''
try:
import kid
except:
txt=botslib.txtexc()
raise ImportError(_(u'Dependency failure: editype "template" requires python library "kid". Error:\n%s'%txt))
defmessage = grammar.grammarread(self.ta_info['editype'],self.ta_info['messagetype']) #needed because we do not know envelope; read syntax for editype/messagetype
self.ta_info.update(defmessage.syntax)
botslib.tryrunscript(self.userscript,self.scriptname,'ta_infocontent',ta_info=self.ta_info)
if not self.ta_info['envelope-template']:
raise botslib.OutMessageError(_(u'While enveloping in "$editype.$messagetype": syntax option "envelope-template" not filled; is required.'),editype=self.ta_info['editype'],messagetype=self.ta_info['messagetype'])
templatefile = botslib.abspath('templates',self.ta_info['envelope-template'])
ta_list = self.filelist2absolutepaths()
try:
botsglobal.logger.debug(u'Start writing envelope to file "%s".',self.ta_info['filename'])
ediprint = kid.Template(file=templatefile, data=ta_list) #init template; pass list with filenames
except:
txt=botslib.txtexc()
raise botslib.OutMessageError(_(u'While enveloping in "$editype.$messagetype", error:\n$txt'),editype=self.ta_info['editype'],messagetype=self.ta_info['messagetype'],txt=txt)
try:
f = botslib.opendata(self.ta_info['filename'],'wb')
ediprint.write(f,
encoding=self.ta_info['charset'],
output=self.ta_info['output'])
except:
txt=botslib.txtexc()
raise botslib.OutMessageError(_(u'While enveloping in "$editype.$messagetype", error:\n$txt'),editype=self.ta_info['editype'],messagetype=self.ta_info['messagetype'],txt=txt)
class orders2printenvelope(template):
pass
class templatehtml(Envelope):
def run(self):
''' class for (test) orderprint; delevers a valid html-file.
Uses a kid-template for the enveloping/merging.
use kid to write; no envelope grammar is used
'''
try:
from genshi.template import TemplateLoader
except:
txt=botslib.txtexc()
raise ImportError(_(u'Dependency failure: editype "template" requires python library "genshi". Error:\n%s'%txt))
defmessage = grammar.grammarread(self.ta_info['editype'],self.ta_info['messagetype']) #needed because we do not know envelope; read syntax for editype/messagetype
self.ta_info.update(defmessage.syntax)
botslib.tryrunscript(self.userscript,self.scriptname,'ta_infocontent',ta_info=self.ta_info)
if not self.ta_info['envelope-template']:
raise botslib.OutMessageError(_(u'While enveloping in "$editype.$messagetype": syntax option "envelope-template" not filled; is required.'),editype=self.ta_info['editype'],messagetype=self.ta_info['messagetype'])
templatefile = botslib.abspath('templateshtml',self.ta_info['envelope-template'])
ta_list = self.filelist2absolutepaths()
try:
botsglobal.logger.debug(u'Start writing envelope to file "%s".',self.ta_info['filename'])
loader = TemplateLoader(auto_reload=False)
tmpl = loader.load(templatefile)
except:
txt=botslib.txtexc()
raise botslib.OutMessageError(_(u'While enveloping in "$editype.$messagetype", error:\n$txt'),editype=self.ta_info['editype'],messagetype=self.ta_info['messagetype'],txt=txt)
try:
f = botslib.opendata(self.ta_info['filename'],'wb')
stream = tmpl.generate(data=ta_list)
stream.render(method='xhtml',encoding=self.ta_info['charset'],out=f)
except:
txt=botslib.txtexc()
raise botslib.OutMessageError(_(u'While enveloping in "$editype.$messagetype", error:\n$txt'),editype=self.ta_info['editype'],messagetype=self.ta_info['messagetype'],txt=txt)
class x12(Envelope):
''' Generate envelope segments; fill with appropriate data, write to interchange-file.'''
def run(self):
if not self.ta_info['topartner'] or not self.ta_info['frompartner']:
raise botslib.OutMessageError(_(u'In enveloping "frompartner" or "topartner" unknown: "$ta_info".'),ta_info=self.ta_info)
self._openoutenvelope(self.ta_info['editype'],self.ta_info['envelope'])
self.ta_info.update(self.out.ta_info)
#need to know the functionalgroup code:
defmessage = grammar.grammarread(self.ta_info['editype'],self.ta_info['messagetype'])
self.ta_info['functionalgroup'] = defmessage.syntax['functionalgroup']
botslib.tryrunscript(self.userscript,self.scriptname,'ta_infocontent',ta_info=self.ta_info)
#prepare data for envelope
ISA09date = time.strftime('%y%m%d')
#test indicator can either be from configuration (self.ta_info['ISA15']) or by mapping (self.ta_info['testindicator'])
#mapping overrules.
if self.ta_info['testindicator'] and self.ta_info['testindicator']!='0': #'0' is default value (in db)
testindicator = self.ta_info['testindicator']
else:
testindicator = self.ta_info['ISA15']
#~ print self.ta_info['messagetype'], 'grammar:',self.ta_info['ISA15'],'ta:',self.ta_info['testindicator'],'out:',testindicator
if botsglobal.ini.getboolean('settings','interchangecontrolperpartner',False):
self.ta_info['reference'] = str(botslib.unique('isacounter_' + self.ta_info['topartner']))
else:
self.ta_info['reference'] = str(botslib.unique('isacounter_' + self.ta_info['frompartner']))
#ISA06 and GS02 can be different; eg ISA06 is a service provider.
#ISA06 and GS02 can be in the syntax....
ISA06 = self.ta_info.get('ISA06',self.ta_info['frompartner'])
ISA06 = ISA06.ljust(15) #add spaces; is fixed length
GS02 = self.ta_info.get('GS02',self.ta_info['frompartner'])
#also for ISA08 and GS03
ISA08 = self.ta_info.get('ISA08',self.ta_info['topartner'])
ISA08 = ISA08.ljust(15) #add spaces; is fixed length
GS03 = self.ta_info.get('GS03',self.ta_info['topartner'])
#build the envelope segments (that is, the tree from which the segments will be generated)
self.out.put({'BOTSID':'ISA',
'ISA01':self.ta_info['ISA01'],
'ISA02':self.ta_info['ISA02'],
'ISA03':self.ta_info['ISA03'],
'ISA04':self.ta_info['ISA04'],
'ISA05':self.ta_info['ISA05'],
'ISA06':ISA06,
'ISA07':self.ta_info['ISA07'],
'ISA08':ISA08,
'ISA09':ISA09date,
'ISA10':time.strftime('%H%M'),
'ISA11':self.ta_info['ISA11'], #if ISA version > 00403, replaced by reprtion separator
'ISA12':self.ta_info['version'],
'ISA13':self.ta_info['reference'],
'ISA14':self.ta_info['ISA14'],
'ISA15':testindicator},strip=False) #MIND: strip=False: ISA fields shoudl not be stripped as it is soemwhat like fixed-length
self.out.put({'BOTSID':'ISA'},{'BOTSID':'IEA','IEA01':'1','IEA02':self.ta_info['reference']})
GS08 = self.ta_info['messagetype'][3:]
if GS08[:6]<'004010':
GS04date = time.strftime('%y%m%d')
else:
GS04date = time.strftime('%Y%m%d')
self.out.put({'BOTSID':'ISA'},{'BOTSID':'GS',
'GS01':self.ta_info['functionalgroup'],
'GS02':GS02,
'GS03':GS03,
'GS04':GS04date,
'GS05':time.strftime('%H%M'),
'GS06':self.ta_info['reference'],
'GS07':self.ta_info['GS07'],
'GS08':GS08})
self.out.put({'BOTSID':'ISA'},{'BOTSID':'GS'},{'BOTSID':'GE','GE01':self.ta_info['nrmessages'],'GE02':self.ta_info['reference']}) #dummy segment; is not used
#user exit
botslib.tryrunscript(self.userscript,self.scriptname,'envelopecontent',ta_info=self.ta_info,out=self.out)
#convert the tree into segments; here only the UNB is written (first segment)
self.out.normalisetree(self.out.root)
self.out.tree2records(self.out.root)
#start doing the actual writing:
tofile = botslib.opendata(self.ta_info['filename'],'wb',self.ta_info['charset'])
ISAstring = self.out._record2string(self.out.records[0])
if self.ta_info['version']<'00403':
ISAstring = ISAstring[:103] + self.ta_info['field_sep']+ self.ta_info['sfield_sep'] + ISAstring[103:] #hack for strange characters at end of ISA; hardcoded
else:
ISAstring = ISAstring[:82] +self.ta_info['reserve'] + ISAstring[83:103] + self.ta_info['field_sep']+ self.ta_info['sfield_sep'] + ISAstring[103:] #hack for strange characters at end of ISA; hardcoded
tofile.write(ISAstring) #write ISA
tofile.write(self.out._record2string(self.out.records[1])) #write GS
self.writefilelist(tofile)
tofile.write(self.out._record2string(self.out.records[-2])) #write GE
tofile.write(self.out._record2string(self.out.records[-1])) #write IEA
tofile.close()
if self.ta_info['functionalgroup']!='FA' and botslib.checkconfirmrules('ask-x12-997',idroute=self.ta_info['idroute'],idchannel=self.ta_info['tochannel'],
topartner=self.ta_info['topartner'],frompartner=self.ta_info['frompartner'],
editype=self.ta_info['editype'],messagetype=self.ta_info['messagetype']):
self.ta_info['confirmtype'] = u'ask-x12-997'
self.ta_info['confirmasked'] = True
class jsonnocheck(noenvelope):
pass
class json(noenvelope):
pass
class xmlnocheck(noenvelope):
pass
class xml(noenvelope):
pass
class myxmlenvelop(xml):
''' old xml enveloping; name is kept for upward comp. & as example for xml enveloping'''
def run(self):
''' class for (test) xml envelope. There is no standardised XML-envelope!
writes a new XML-tree; uses places-holders for XML-files to include; real enveloping is done by ElementTree's include'''
include = '{http://www.w3.org/2001/XInclude}include'
self._openoutenvelope(self.ta_info['editype'],self.ta_info['envelope'])
botslib.tryrunscript(self.userscript,self.scriptname,'ta_infocontent',ta_info=self.ta_info)
#~ self.out.put({'BOTSID':'root','xmlns:xi':"http://www.w3.org/2001/XInclude"}) #works, but attribute is not removed bij ETI.include
self.out.put({'BOTSID':'root'}) #start filling out-tree
ta_list = self.filelist2absolutepaths()
for filename in ta_list:
self.out.put({'BOTSID':'root'},{'BOTSID':include,include + '__parse':'xml',include + '__href':filename})
self.out.envelopewrite(self.out.root) #'resolves' the included xml files
class db(Envelope):
''' Only copies the input files to one output file.'''
def run(self):
botslib.tryrunscript(self.userscript,self.scriptname,'ta_infocontent',ta_info=self.ta_info)
self.ta_info['filename'] = self.ta_list[0]
class raw(Envelope):
''' Only copies the input files to one output file.'''
def run(self):
botslib.tryrunscript(self.userscript,self.scriptname,'ta_infocontent',ta_info=self.ta_info)
self.ta_info['filename'] = self.ta_list[0]
| Python |
# Django settings for bots project.
import os
import bots
#*******settings for bots error reports**********************************
MANAGERS = ( #bots will send error reports to the MANAGERS
('name_manager', 'manager@domain.org'),
)
#~ EMAIL_HOST = 'smtp.gmail.com' #Default: 'localhost'
#~ EMAIL_PORT = '587' #Default: 25
#~ EMAIL_USE_TLS = True #Default: False
#~ EMAIL_HOST_USER = 'user@gmail.com' #Default: ''. Username to use for the SMTP server defined in EMAIL_HOST. If empty, Django won't attempt authentication.
#~ EMAIL_HOST_PASSWORD = '' #Default: ''. PASSWORD to use for the SMTP server defined in EMAIL_HOST. If empty, Django won't attempt authentication.
#~ SERVER_EMAIL = 'user@gmail.com' #Sender of bots error reports. Default: 'root@localhost'
#~ EMAIL_SUBJECT_PREFIX = '' #This is prepended on email subject.
#*********path settings*************************advised is not to change these values!!
PROJECT_PATH = os.path.abspath(os.path.dirname(bots.__file__))
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = PROJECT_PATH + '/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
#~ FILE_UPLOAD_TEMP_DIR = os.path.join(PROJECT_PATH, 'botssys/pluginsuploaded') #set in bots.ini
ROOT_URLCONF = 'bots.urls'
LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/'
LOGOUT_URL = '/logout/'
#~ LOGOUT_REDIRECT_URL = #??not such parameter; is set in urls
TEMPLATE_DIRS = (
os.path.join(PROJECT_PATH, 'templates'),
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
#*********database settings*************************
#django-admin syncdb --pythonpath='/home/hje/botsup' --settings='bots.config.settings'
#SQLITE:
DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = os.path.join(PROJECT_PATH, 'botssys/sqlitedb/botsdb') #path to database; if relative path: interpreted relative to bots root directory
DATABASE_USER = ''
DATABASE_PASSWORD = ''
DATABASE_HOST = ''
DATABASE_PORT = ''
DATABASE_OPTIONS = {}
#~ #MySQL:
#~ DATABASE_ENGINE = 'mysql'
#~ DATABASE_NAME = 'botsdb'
#~ DATABASE_USER = 'bots'
#~ DATABASE_PASSWORD = 'botsbots'
#~ DATABASE_HOST = '192.168.0.7'
#~ DATABASE_PORT = '3306'
#~ DATABASE_OPTIONS = {'use_unicode':True,'charset':'utf8',"init_command": 'SET storage_engine=INNODB'}
#PostgreSQL:
#~ DATABASE_ENGINE = 'postgresql_psycopg2'
#~ DATABASE_NAME = 'botsdb'
#~ DATABASE_USER = 'bots'
#~ DATABASE_PASSWORD = 'botsbots'
#~ DATABASE_HOST = '192.168.0.7'
#~ DATABASE_PORT = '5432'
#~ DATABASE_OPTIONS = {}
#*********sessions, cookies, log out time*************************
SESSION_EXPIRE_AT_BROWSER_CLOSE = True #True: always log in when browser is closed
SESSION_COOKIE_AGE = 3600 #seconds a user needs to login when no activity
SESSION_SAVE_EVERY_REQUEST = True #if True: SESSION_COOKIE_AGE is interpreted as: since last activity
#*********localization*************************
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/Amsterdam'
DATE_FORMAT = "Y-m-d"
DATETIME_FORMAT = "Y-m-d G:i"
TIME_FORMAT = "G:i"
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
#~ LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'en'
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
#*************************************************************************
#*********other django setting. please consult django docs.***************
#set in bots.ini
#~ DEBUG = True
#~ TEMPLATE_DEBUG = DEBUG
SITE_ID = 1
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'm@-u37qiujmeqfbu$daaaaz)sp^7an4u@h=wfx9dd$$$zl2i*x9#awojdc'
ADMINS = (
('bots', 'your_email@domain.com'),
)
#save uploaded file (=plugin) always to file. no path for temp storage is used, so system default is used.
FILE_UPLOAD_HANDLERS = (
"django.core.files.uploadhandler.TemporaryFileUploadHandler",
)
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
#'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'bots.persistfilters.FilterPersistMiddleware',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
'bots',
)
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.request",
)
| Python |
import sys
from django.utils.translation import ugettext as _
#bots-modules
import communication
import envelope
import transform
import botslib
import botsglobal
import preprocess
from botsconfig import *
@botslib.log_session
def prepareretransmit():
''' prepare the retransmittable files. Return: indication if files should be retransmitted.'''
retransmit = False #indicate retransmit
#for rereceive
for row in botslib.query('''SELECT idta,reportidta
FROM filereport
WHERE retransmit=%(retransmit)s ''',
{'retransmit':True}):
retransmit = True
botslib.change('''UPDATE filereport
SET retransmit=%(retransmit)s
WHERE idta=%(idta)s
AND reportidta=%(reportidta)s ''',
{'idta':row['idta'],'reportidta':row['reportidta'],'retransmit':False})
for row2 in botslib.query('''SELECT idta
FROM ta
WHERE parent=%(parent)s
AND status=%(status)s''',
{'parent':row['idta'],
'status':RAWIN}):
ta_rereceive = botslib.OldTransaction(row2['idta'])
ta_externin = ta_rereceive.copyta(status=EXTERNIN,statust=DONE,parent=0) #inject; status is DONE so this ta is not used further
ta_raw = ta_externin.copyta(status=RAWIN,statust=OK) #reinjected file is ready as new input
#for resend; this one is slow. Can be improved by having a separate list of idta to resend
for row in botslib.query('''SELECT idta,parent
FROM ta
WHERE retransmit=%(retransmit)s
AND status=%(status)s''',
{'retransmit':True,
'status':EXTERNOUT}):
retransmit = True
ta_outgoing = botslib.OldTransaction(row['idta'])
ta_outgoing.update(retransmit=False) #is reinjected; set retransmit back to False
ta_resend = botslib.OldTransaction(row['parent']) #parent ta with status RAWOUT; this is where the outgoing file is kept
ta_externin = ta_resend.copyta(status=EXTERNIN,statust=DONE,parent=0) #inject; status is DONE so this ta is not used further
ta_raw = ta_externin.copyta(status=RAWOUT,statust=OK) #reinjected file is ready as new input
return retransmit
@botslib.log_session
def preparerecommunication():
#for each out-communication process that went wrong:
retransmit = False #indicate retransmit
for row in botslib.query('''SELECT idta,tochannel
FROM ta
WHERE statust!=%(statust)s
AND status=%(status)s
AND retransmit=%(retransmit)s ''',
{'status':PROCESS,'retransmit':True,'statust':DONE}):
run_outgoing = botslib.OldTransaction(row['idta'])
run_outgoing.update(retransmit=False) #set retransmit back to False
#get rootidta of run where communication failed
for row2 in botslib.query('''SELECT max(idta) as rootidta
FROM ta
WHERE script=%(script)s
AND idta<%(thisidta)s ''',
{'script':0,'thisidta':row['idta']}):
rootidta = row2['rootidta']
#get endidta of run where communication failed
for row3 in botslib.query('''SELECT min(idta) as endidta
FROM ta
WHERE script=%(script)s
AND idta>%(thisidta)s ''',
{'script':0,'thisidta':row['idta']}):
endidta = row3['endidta']
if not endidta:
endidta = sys.maxint - 1
#reinject
for row4 in botslib.query('''SELECT idta
FROM ta
WHERE idta<%(endidta)s
AND idta>%(rootidta)s
AND status=%(status)s
AND statust=%(statust)s
AND tochannel=%(tochannel)s ''',
{'statust':OK,'status':RAWOUT,'rootidta':rootidta,'endidta':endidta,'tochannel':row['tochannel']}):
retransmit = True
ta_outgoing = botslib.OldTransaction(row4['idta'])
ta_outgoing_copy = ta_outgoing.copyta(status=RAWOUT,statust=OK)
ta_outgoing.update(statust=DONE)
return retransmit
@botslib.log_session
def prepareautomaticrecommunication():
''' reinjects all files for which communication failed (status = RAWOUT)
'''
retransmit = False #indicate retransmit
#bots keeps track of last time automaticretrycommunication was done; reason is mainly performance
startidta = max(botslib.keeptrackoflastretry('bots__automaticretrycommunication',botslib.getlastrun()),botslib.get_idta_last_error())
#reinject
for row4 in botslib.query('''SELECT idta
FROM ta
WHERE idta>%(startidta)s
AND status=%(status)s
AND statust=%(statust)s ''',
{'statust':OK,'status':RAWOUT,'startidta':startidta}):
retransmit = True
ta_outgoing = botslib.OldTransaction(row4['idta'])
ta_outgoing_copy = ta_outgoing.copyta(status=RAWOUT,statust=OK)
ta_outgoing.update(statust=DONE)
return retransmit
@botslib.log_session
def prepareretry():
''' reinjects all files for which communication failed (status = RAWOUT)
'''
retransmit = False #indicate retransmit
#bots keeps track of last time retry was done; reason is mainly performance
startidta = max(botslib.keeptrackoflastretry('bots__retry',botslib.getlastrun()),botslib.get_idta_last_error())
#reinject
for row4 in botslib.query('''SELECT idta,status
FROM ta
WHERE idta>%(startidta)s
AND statust=%(statust)s ''',
{'statust':OK,'startidta':startidta}):
retransmit = True
ta_outgoing = botslib.OldTransaction(row4['idta'])
ta_outgoing_copy = ta_outgoing.copyta(status=row4['status'],statust=OK)
ta_outgoing.update(statust=DONE)
return retransmit
@botslib.log_session
def routedispatcher(routestorun,type=None):
''' run all route(s). '''
if type == '--retransmit':
if not prepareretransmit():
return 0
elif type == '--retrycommunication':
if not preparerecommunication():
return 0
elif type == '--automaticretrycommunication':
if not prepareautomaticrecommunication():
return 0
elif type == '--retry':
if not prepareretry():
return 0
stuff2evaluate = botslib.getlastrun()
botslib.set_minta4query()
for route in routestorun:
foundroute=False
botslib.setpreprocessnumber(SET_FOR_PROCESSING)
for routedict in botslib.query('''SELECT idroute ,
fromchannel_id as fromchannel,
tochannel_id as tochannel,
fromeditype,
frommessagetype,
alt,
frompartner_id as frompartner,
topartner_id as topartner,
toeditype,
tomessagetype,
seq,
frompartner_tochannel_id,
topartner_tochannel_id,
testindicator,
translateind,
defer
FROM routes
WHERE idroute=%(idroute)s
AND active=%(active)s
ORDER BY seq''',
{'idroute':route,'active':True}):
botsglobal.logger.info(_(u'running route %(idroute)s %(seq)s'),{'idroute':routedict['idroute'],'seq':routedict['seq']})
botslib.setrouteid(routedict['idroute'])
foundroute=True
router(routedict)
botslib.setrouteid('')
botsglobal.logger.debug(u'finished route %s %s',routedict['idroute'],routedict['seq'])
if not foundroute:
botsglobal.logger.warning(_(u'there is no (active) route "%s".'),route)
return stuff2evaluate
@botslib.log_session
def router(routedict):
''' communication.run one route. variants:
- a route can be just script;
- a route can do only incoming
- a route can do only outgoing
- a route can do both incoming and outgoing
- at several points functions from a route script are called - if function is in route script
'''
#is there a user route script?
try:
userscript,scriptname = botslib.botsimport('routescripts',routedict['idroute'])
except ImportError: #other errors, eg syntax errors are just passed
userscript = scriptname = None
#if user route script has function 'main': communication.run 'main' (and do nothing else)
if botslib.tryrunscript(userscript,scriptname,'main',routedict=routedict):
return #so: if function ' main' : communication.run only the routescript, nothing else.
if not (userscript or routedict['fromchannel'] or routedict['tochannel'] or routedict['translateind']):
raise botslib.ScriptError(_(u'Route "$route" is empty: no script, not enough parameters.'),route=routedict['idroute'])
botslib.tryrunscript(userscript,scriptname,'start',routedict=routedict)
#communication.run incoming channel
if routedict['fromchannel']: #do incoming part of route: in-communication; set ready for translation; translate
botslib.tryrunscript(userscript,scriptname,'preincommunication',routedict=routedict)
communication.run(idchannel=routedict['fromchannel'],idroute=routedict['idroute']) #communication.run incommunication
#add attributes from route to the received files
where={'status':FILEIN,'fromchannel':routedict['fromchannel'],'idroute':routedict['idroute']}
change={'editype':routedict['fromeditype'],'messagetype':routedict['frommessagetype'],'frompartner':routedict['frompartner'],'topartner':routedict['topartner'],'alt':routedict['alt']}
botslib.updateinfo(change=change,where=where)
#all received files have status FILEIN
botslib.tryrunscript(userscript,scriptname,'postincommunication',routedict=routedict)
if routedict['fromeditype'] == 'mailbag': #mailbag for the route.
preprocess.preprocess(routedict,preprocess.mailbag)
#communication.run translation
if routedict['translateind']:
botslib.tryrunscript(userscript,scriptname,'pretranslation',routedict=routedict)
botslib.addinfo(change={'status':TRANSLATE},where={'status':FILEIN,'idroute':routedict['idroute']})
transform.translate(idroute=routedict['idroute'])
botslib.tryrunscript(userscript,scriptname,'posttranslation',routedict=routedict)
#merge messages & communication.run outgoing channel
if routedict['tochannel']: #do outgoing part of route
botslib.tryrunscript(userscript,scriptname,'premerge',routedict=routedict)
envelope.mergemessages(idroute=routedict['idroute'])
botslib.tryrunscript(userscript,scriptname,'postmerge',routedict=routedict)
#communication.run outgoing channel
#build for query: towhere (dict) and wherestring
towhere=dict(status=MERGED,
idroute=routedict['idroute'],
editype=routedict['toeditype'],
messagetype=routedict['tomessagetype'],
testindicator=routedict['testindicator'])
towhere=dict([(key, value) for (key, value) in towhere.iteritems() if value]) #remove nul-values from dict
wherestring = ' AND '.join([key+'=%('+key+')s' for key in towhere])
if routedict['frompartner_tochannel_id']: #use frompartner_tochannel in where-clause of query (partner/group dependent outchannel
towhere['frompartner_tochannel_id']=routedict['frompartner_tochannel_id']
wherestring += ''' AND (frompartner=%(frompartner_tochannel_id)s
OR frompartner in (SELECT from_partner_id
FROM partnergroup
WHERE to_partner_id =%(frompartner_tochannel_id)s ))'''
if routedict['topartner_tochannel_id']: #use topartner_tochannel in where-clause of query (partner/group dependent outchannel
towhere['topartner_tochannel_id']=routedict['topartner_tochannel_id']
wherestring += ''' AND (topartner=%(topartner_tochannel_id)s
OR topartner in (SELECT from_partner_id
FROM partnergroup
WHERE to_partner_id=%(topartner_tochannel_id)s ))'''
toset={'tochannel':routedict['tochannel'],'status':FILEOUT}
botslib.addinfocore(change=toset,where=towhere,wherestring=wherestring)
if not routedict['defer']: #do outgoing part of route
botslib.tryrunscript(userscript,scriptname,'preoutcommunication',routedict=routedict)
communication.run(idchannel=routedict['tochannel'],idroute=routedict['idroute']) #communication.run outcommunication
botslib.tryrunscript(userscript,scriptname,'postoutcommunication',routedict=routedict)
botslib.tryrunscript(userscript,scriptname,'end',routedict=routedict)
| Python |
import os
import sys
import time
import zipfile
import zipimport
import operator
import django
from django.core import serializers
from django.utils.translation import ugettext as _
import models
import botslib
import botsglobal
'''
some tabel have 'id' as primary key. This is always an artificial key.
this is not usable for plugins: 'id' is never written to a plugin.
often a tabel with 'id' has an 'unique together' attribute.
than this is used to check if the entry already exists (this is reported).
existing entries are always overwritten.
exceptions:
- confirmrule; there is no clear unique key. AFAICS this will never be a problem.
- translate: may be confusing. But anyway, no existing translate will be overwritten....
'''
#plugincomparelist is used for filtering and sorting the plugins.
plugincomparelist = ['uniek','persist','mutex','ta','filereport','report','ccodetrigger','ccode', 'channel','partner','chanpar','translate','routes','confirmrule']
def pluglistcmp(key1,key2):
#sort by plugincomparelist
return plugincomparelist.index(key1) - plugincomparelist.index(key2)
def pluglistcmpisgroup(plug1,plug2):
#sort partnergroups before parters
if plug1['plugintype'] == 'partner' and plug2['plugintype'] == 'partner':
return int(plug2['isgroup']) - int(plug1['isgroup'])
else:
return 0
def writetodatabase(orgpluglist):
#sanity checks on pluglist
if not orgpluglist: #list of plugins is empty: is OK. DO nothing
return
if not isinstance(orgpluglist,list): #has to be a list!!
raise botslib.PluginError(_(u'plugins should be list of dicts. Nothing is written.'))
for plug in orgpluglist:
if not isinstance(plug,dict):
raise botslib.PluginError(_(u'plugins should be list of dicts. Nothing is written.'))
for key in plug.keys():
if not isinstance(key,basestring):
raise botslib.PluginError(_(u'key of dict is not a string: "%s". Nothing is written.')%(plug))
if 'plugintype' not in plug:
raise botslib.PluginError(_(u'"plugintype" missing in: "%s". Nothing is written.')%(plug))
#special case: compatibility with bots 1.* plugins.
#in bots 1.*, partnergroup was in separate tabel; in bots 2.* partnergroup is in partner
#later on, partnergroup will get filtered
for plug in orgpluglist[:]:
if plug['plugintype'] == 'partnergroup':
for plugpartner in orgpluglist:
if plugpartner['plugintype'] == 'partner' and plugpartner['idpartner'] == plug['idpartner']:
if 'group' in plugpartner:
plugpartner['group'].append(plug['idpartnergroup'])
else:
plugpartner['group'] = [plug['idpartnergroup']]
break
#copy & filter orgpluglist; do plugtype specific adaptions
pluglist = []
for plug in orgpluglist:
if plug['plugintype'] == 'ccode': #add ccodetrigger. #20101223: this is NOT needed; codetrigger shoudl be in plugin.
for seachccodetriggerplug in pluglist:
if seachccodetriggerplug['plugintype']=='ccodetrigger' and seachccodetriggerplug['ccodeid']==plug['ccodeid']:
break
else:
pluglist.append({'plugintype':'ccodetrigger','ccodeid':plug['ccodeid']})
elif plug['plugintype'] == 'translate': #make some fields None instead of '' (translate formpartner, topartner)
if not plug['frompartner']:
plug['frompartner'] = None
if not plug['topartner']:
plug['topartner'] = None
elif plug['plugintype'] in ['ta','filereport']: #sqlite can have errortexts that are to long. Chop these
plug['errortext'] = plug['errortext'][:2047]
elif plug['plugintype'] == 'routes':
plug['active'] = False
if not 'defer' in plug:
plug['defer'] = False
else:
if plug['defer'] is None:
plug['defer'] = False
elif plug['plugintype'] == 'confirmrule':
plug.pop('id', None) #id is an artificial key, delete,
elif plug['plugintype'] not in plugincomparelist: #if not in plugincomparelist: do not use
continue
pluglist.append(plug)
#sort pluglist: this is needed for relationships
pluglist.sort(cmp=pluglistcmp,key=operator.itemgetter('plugintype'))
#2nd sort: sort partenergroups before partners
pluglist.sort(cmp=pluglistcmpisgroup)
#~ for plug in pluglist:
#~ print 'list:',plug
for plug in pluglist:
botsglobal.logger.info(u' Start write to database for: "%s".'%plug)
#remember the plugintype
plugintype = plug['plugintype']
#~ print '\nstart plug', plug
table = django.db.models.get_model('bots',plug['plugintype'])
#~ print table
#delete fields not in model (create compatibility plugin-version)
loopdictionary = plug.keys()
for key in loopdictionary:
try:
table._meta.get_field(key)
except django.db.models.fields.FieldDoesNotExist:
del plug[key]
#get key(s), put in dict 'sleutel'
pk = table._meta.pk.name
if pk == 'id':
sleutel = {}
if table._meta.unique_together:
for key in table._meta.unique_together[0]:
sleutel[key]=plug.pop(key)
else:
sleutel = {pk:plug.pop(pk)}
#now we have:
#- sleutel: unique key fields. mind: translate and confirmrule have empty 'sleutel' now
#- plug: rest of database fields
sleutelorg = sleutel.copy() #make a copy of the original sleutel; this is needed later
#get real column names for fields in plug
loopdictionary = plug.keys()
for fieldname in loopdictionary:
fieldobject = table._meta.get_field_by_name(fieldname)[0]
try:
if fieldobject.column != fieldname: #if name in plug is not the real field name (in database)
plug[fieldobject.column] = plug[fieldname] #add new key in plug
del plug[fieldname] #delete old key in plug
#~ print 'replace _id for:',fieldname
except:
print 'no field column for:',fieldname #should this be raised?
#get real column names for fields in sleutel; basically the same loop but now for sleutel
loopdictionary = sleutel.keys()
for fieldname in loopdictionary:
fieldobject = table._meta.get_field_by_name(fieldname)[0]
try:
if fieldobject.column != fieldname:
sleutel[fieldobject.column] = sleutel[fieldname]
del sleutel[fieldname]
except:
print 'no field column for',fieldname
#now we have:
#- sleutel: unique key fields. mind: translate and confirmrule have empty 'sleutel' now
#- sleutelorg: original key fields
#- plug: rest of database fields
#- plugintype
#all fields have the right database name
#~ print 'plug attr',plug
#~ print 'orgsleutel',sleutelorg
#~ print 'sleutel',sleutel
#existing ccodetriggers are not overwritten (as deleting ccodetrigger also deletes ccodes)
if plugintype == 'ccodetrigger':
listexistingentries = table.objects.filter(**sleutelorg).all()
if listexistingentries:
continue
#now find the entry using the keys in sleutelorg; delete the existing entry.
elif sleutelorg: #not for translate and confirmrule; these have an have an empty 'sleutel'
listexistingentries = table.objects.filter(**sleutelorg).all()
elif plugintype == 'translate': #for translate: delete existing entry
listexistingentries = table.objects.filter(fromeditype=plug['fromeditype'],frommessagetype=plug['frommessagetype'],alt=plug['alt'],frompartner=plug['frompartner_id'],topartner=plug['topartner_id']).all()
elif plugintype == 'confirmrule': #for confirmrule: delete existing entry; but how to find this??? what are keys???
listexistingentries = table.objects.filter(confirmtype=plug['confirmtype'],
ruletype=plug['ruletype'],
negativerule=plug['negativerule'],
idroute=plug.get('idroute'),
idchannel=plug.get('idchannel_id'),
editype=plug.get('editype'),
messagetype=plug.get('messagetype'),
frompartner=plug.get('frompartner_id'),
topartner=plug.get('topartner_id')).all()
if listexistingentries:
for entry in listexistingentries:
entry.delete()
botsglobal.logger.info(_(u' Existing entry in database is deleted.'))
dbobject = table(**sleutel) #create db-object
if plugintype == 'partner': #for partners, first the partner needs to be saved before groups can be made
dbobject.save()
for key,value in plug.items():
setattr(dbobject,key,value)
dbobject.save()
botsglobal.logger.info(_(u' Write to database is OK.'))
@django.db.transaction.commit_on_success #if no exception raised: commit, else rollback.
def load(pathzipfile):
''' process uploaded plugin. '''
#test is valid zipfile
if not zipfile.is_zipfile(pathzipfile):
raise botslib.PluginError(_(u'Plugin is not a valid file.'))
#read index file
try:
Zipimporter = zipimport.zipimporter(pathzipfile)
importedbotsindex = Zipimporter.load_module('botsindex')
pluglist = importedbotsindex.plugins[:]
if 'botsindex' in sys.modules:
del sys.modules['botsindex']
except:
txt = botslib.txtexc()
raise botslib.PluginError(_(u'Error in plugin. Nothing is written. Error:\n%s')%(txt))
else:
botsglobal.logger.info(_(u'Plugin is OK.'))
botsglobal.logger.info(_(u'Start writing to database.'))
#write content of index file to the bots database
try:
writetodatabase(pluglist)
except:
txt = botslib.txtexc()
raise botslib.PluginError(_(u'Error writing plugin to database. Nothing is written. Error:\n%s'%(txt)))
else:
botsglobal.logger.info(u'Writing to database is OK.')
botsglobal.logger.info(u'Start writing to files')
#write files to the file system.
try:
warnrenamed = False #to report in GUI files have been overwritten.
z = zipfile.ZipFile(pathzipfile, mode="r")
orgtargetpath = botsglobal.ini.get('directories','botspath')
if (orgtargetpath[-1:] in (os.path.sep, os.path.altsep) and len(os.path.splitdrive(orgtargetpath)[1]) > 1):
orgtargetpath = orgtargetpath[:-1]
for f in z.infolist():
if f.filename not in ['botsindex.py','README','botssys/sqlitedb/botsdb','config/bots.ini'] and os.path.splitext(f.filename)[1] not in ['.pyo','.pyc']:
#~ botsglobal.logger.info(u'filename in zip "%s".',f.filename)
if f.filename[0] == '/':
targetpath = f.filename[1:]
else:
targetpath = f.filename
targetpath = targetpath.replace('usersys',botsglobal.ini.get('directories','usersysabs'),1)
targetpath = targetpath.replace('botssys',botsglobal.ini.get('directories','botssys'),1)
targetpath = botslib.join(orgtargetpath, targetpath)
#targetpath is OK now.
botsglobal.logger.info(_(u' Start writing file: "%s".'),targetpath)
if botslib.dirshouldbethere(os.path.dirname(targetpath)):
botsglobal.logger.info(_(u' Create directory "%s".'),os.path.dirname(targetpath))
if f.filename[-1] == '/': #check if this is a dir; if so continue
continue
if os.path.isfile(targetpath): #check if file already exists
try: #this ***sometimes*** fails. (python25, for static/help/home.html...only there...)
os.rename(targetpath,targetpath+'.'+time.strftime('%Y%m%d%H%M%S'))
warnrenamed=True
botsglobal.logger.info(_(u' Renamed existing file "%(from)s" to "%(to)s".'),{'from':targetpath,'to':targetpath+time.strftime('%Y%m%d%H%M%S')})
except:
pass
source = z.read(f.filename)
target = open(targetpath, "wb")
target.write(source)
target.close()
botsglobal.logger.info(_(u' File written: "%s".'),targetpath)
except:
txt = botslib.txtexc()
z.close()
raise botslib.PluginError(_(u'Error writing files to system. Nothing is written to database. Error:\n%s')%(txt))
else:
z.close()
botsglobal.logger.info(_(u'Writing files to filesystem is OK.'))
return warnrenamed
#*************************************************************
# generate a plugin (plugout)
#*************************************************************
def plugoutcore(cleaned_data):
pluginzipfilehandler = zipfile.ZipFile(cleaned_data['filename'], 'w', zipfile.ZIP_DEFLATED)
tmpbotsindex = plugout_database(cleaned_data)
pluginzipfilehandler.writestr('botsindex.py',tmpbotsindex) #write index file to pluginfile
files4plugin = plugout_files(cleaned_data)
for dirname, defaultdirname in files4plugin:
pluginzipfilehandler.write(dirname,defaultdirname)
botsglobal.logger.debug(_(u' write file "%s".'),defaultdirname)
pluginzipfilehandler.close()
def plugout_database(cleaned_data):
#collect all database objects
db_objects = []
if cleaned_data['databaseconfiguration']:
db_objects += \
list(models.channel.objects.all()) + \
list(models.partner.objects.all()) + \
list(models.chanpar.objects.all()) + \
list(models.translate.objects.all()) + \
list(models.routes.objects.all()) + \
list(models.confirmrule.objects.all())
if cleaned_data['umlists']:
db_objects += \
list(models.ccodetrigger.objects.all()) + \
list(models.ccode.objects.all())
if cleaned_data['databasetransactions']:
db_objects += \
list(models.uniek.objects.all()) + \
list(models.mutex.objects.all()) + \
list(models.ta.objects.all()) + \
list(models.filereport.objects.all()) + \
list(models.report.objects.all())
#~ list(models.persist.objects.all()) + \ #commetned out......does this need testing?
#serialize database objects
orgplugs = serializers.serialize("python", db_objects)
#write serialized objects to str/buffer
tmpbotsindex = u'import datetime\nversion = 2\nplugins = [\n'
for plug in orgplugs:
app,tablename = plug['model'].split('.',1)
plug['fields']['plugintype'] = tablename
table = django.db.models.get_model(app,tablename)
pk = table._meta.pk.name
if pk != 'id':
plug['fields'][pk] = plug['pk']
tmpbotsindex += repr(plug['fields']) + u',\n'
botsglobal.logger.debug(u' write in index: %s',plug['fields'])
#check confirmrule: id is non-artifical key?
tmpbotsindex += u']\n'
return tmpbotsindex
def plugout_files(cleaned_data):
''' gather list of files for the plugin that is generated '''
files2return = []
usersys = botsglobal.ini.get('directories','usersysabs')
botssys = botsglobal.ini.get('directories','botssys')
if cleaned_data['fileconfiguration']: #gather from usersys
files2return.extend(plugout_files_bydir(usersys,'usersys'))
if not cleaned_data['charset']: #if edifact charsets are not needed: remove them (are included in default bots installation).
charsetdirs = plugout_files_bydir(os.path.join(usersys,'charsets'),'usersys/charsets')
for charset in charsetdirs:
try:
index = files2return.index(charset)
files2return.pop(index)
except ValueError:
pass
if cleaned_data['config']:
config = botsglobal.ini.get('directories','config')
files2return.extend(plugout_files_bydir(config,'config'))
if cleaned_data['data']:
data = botsglobal.ini.get('directories','data')
files2return.extend(plugout_files_bydir(data,'botssys/data'))
if cleaned_data['database']:
files2return.extend(plugout_files_bydir(os.path.join(botssys,'sqlitedb'),'botssys/sqlitedb.copy')) #yeah...readign a plugin with a new database will cause a crash...do this manually...
if cleaned_data['infiles']:
files2return.extend(plugout_files_bydir(os.path.join(botssys,'infile'),'botssys/infile'))
if cleaned_data['logfiles']:
log_file = botsglobal.ini.get('directories','logging')
files2return.extend(plugout_files_bydir(log_file,'botssys/logging'))
return files2return
def plugout_files_bydir(dirname,defaultdirname):
''' gather all files from directory dirname'''
files2return = []
for root, dirs, files in os.walk(dirname):
head, tail = os.path.split(root)
if tail in ['.svn']: #skip .svn directries
del dirs[:] #os.walk will not look in subdirectories
continue
rootinplugin = root.replace(dirname,defaultdirname,1)
for bestand in files:
ext = os.path.splitext(bestand)[1]
if ext and (ext in ['.pyc','.pyo'] or bestand in ['__init__.py'] or (len(ext) == 15 and ext[1:].isdigit())):
continue
files2return.append([os.path.join(root,bestand),os.path.join(rootinplugin,bestand)])
return files2return
| Python |
import time
import django
import models
import viewlib
import botslib
import botsglobal
django.contrib.admin.widgets.AdminSplitDateTime
HiddenInput = django.forms.widgets.HiddenInput
DEFAULT_ENTRY = ('',"---------")
editypelist=[DEFAULT_ENTRY] + sorted(models.EDITYPES)
confirmtypelist=[DEFAULT_ENTRY] + models.CONFIRMTYPE
def getroutelist(): #needed because the routeid is needed (and this is not theprimary key
return [DEFAULT_ENTRY]+[(l,l) for l in models.routes.objects.values_list('idroute', flat=True).order_by('idroute').distinct() ]
def getinmessagetypes():
return [DEFAULT_ENTRY]+[(l,l) for l in models.translate.objects.values_list('frommessagetype', flat=True).order_by('frommessagetype').distinct() ]
def getoutmessagetypes():
return [DEFAULT_ENTRY]+[(l,l) for l in models.translate.objects.values_list('tomessagetype', flat=True).order_by('tomessagetype').distinct() ]
def getallmessagetypes():
return [DEFAULT_ENTRY]+[(l,l) for l in sorted(set(list(models.translate.objects.values_list('tomessagetype', flat=True).all()) + list(models.translate.objects.values_list('frommessagetype', flat=True).all()) )) ]
def getpartners():
return [DEFAULT_ENTRY]+[(l,l) for l in models.partner.objects.values_list('idpartner', flat=True).filter(isgroup=False,active=True).order_by('idpartner') ]
def getfromchannels():
return [DEFAULT_ENTRY]+[(l,l) for l in models.channel.objects.values_list('idchannel', flat=True).filter(inorout='in').order_by('idchannel') ]
def gettochannels():
return [DEFAULT_ENTRY]+[(l,l) for l in models.channel.objects.values_list('idchannel', flat=True).filter(inorout='out').order_by('idchannel') ]
class Select(django.forms.Form):
datefrom = django.forms.DateTimeField(initial=viewlib.datetimefrom)
dateuntil = django.forms.DateTimeField(initial=viewlib.datetimeuntil)
page = django.forms.IntegerField(required=False,initial=1,widget=HiddenInput())
sortedby = django.forms.CharField(initial='ts',widget=HiddenInput())
sortedasc = django.forms.BooleanField(initial=False,required=False,widget=HiddenInput())
class View(django.forms.Form):
datefrom = django.forms.DateTimeField(required=False,initial=viewlib.datetimefrom,widget=HiddenInput())
dateuntil = django.forms.DateTimeField(required=False,initial=viewlib.datetimeuntil,widget=HiddenInput())
page = django.forms.IntegerField(required=False,initial=1,widget=HiddenInput())
sortedby = django.forms.CharField(required=False,initial='ts',widget=HiddenInput())
sortedasc = django.forms.BooleanField(required=False,initial=False,widget=HiddenInput())
class SelectReports(Select):
template = 'bots/selectform.html'
action = '/reports/'
status = django.forms.ChoiceField([DEFAULT_ENTRY,('1',"Error"),('0',"Done")],required=False,initial='')
class ViewReports(View):
template = 'bots/reports.html'
action = '/reports/'
status = django.forms.IntegerField(required=False,initial='',widget=HiddenInput())
class SelectIncoming(Select):
template = 'bots/selectform.html'
action = '/incoming/'
statust = django.forms.ChoiceField([DEFAULT_ENTRY,('1',"Error"),('3',"Done")],required=False,initial='')
idroute = django.forms.ChoiceField([],required=False,initial='')
frompartner = django.forms.ChoiceField([],required=False)
topartner = django.forms.ChoiceField([],required=False)
ineditype = django.forms.ChoiceField(editypelist,required=False)
inmessagetype = django.forms.ChoiceField([],required=False)
outeditype = django.forms.ChoiceField(editypelist,required=False)
outmessagetype = django.forms.ChoiceField([],required=False)
lastrun = django.forms.BooleanField(required=False,initial=False)
def __init__(self, *args, **kwargs):
super(SelectIncoming, self).__init__(*args, **kwargs)
self.fields['idroute'].choices = getroutelist()
self.fields['inmessagetype'].choices = getinmessagetypes()
self.fields['outmessagetype'].choices = getoutmessagetypes()
self.fields['frompartner'].choices = getpartners()
self.fields['topartner'].choices = getpartners()
class ViewIncoming(View):
template = 'bots/incoming.html'
action = '/incoming/'
statust = django.forms.IntegerField(required=False,initial='',widget=HiddenInput())
idroute = django.forms.CharField(required=False,widget=HiddenInput())
frompartner = django.forms.CharField(required=False,widget=HiddenInput())
topartner = django.forms.CharField(required=False,widget=HiddenInput())
ineditype = django.forms.CharField(required=False,widget=HiddenInput())
inmessagetype = django.forms.CharField(required=False,widget=HiddenInput())
outeditype = django.forms.CharField(required=False,widget=HiddenInput())
outmessagetype = django.forms.CharField(required=False,widget=HiddenInput())
lastrun = django.forms.BooleanField(required=False,initial=False,widget=HiddenInput())
botskey = django.forms.CharField(required=False,widget=HiddenInput())
class SelectDocument(Select):
template = 'bots/selectform.html'
action = '/document/'
idroute = django.forms.ChoiceField([],required=False,initial='')
frompartner = django.forms.ChoiceField([],required=False)
topartner = django.forms.ChoiceField([],required=False)
editype = django.forms.ChoiceField(editypelist,required=False)
messagetype = django.forms.ChoiceField(required=False)
lastrun = django.forms.BooleanField(required=False,initial=False)
botskey = django.forms.CharField(required=False,label='Document number',max_length=35)
def __init__(self, *args, **kwargs):
super(SelectDocument, self).__init__(*args, **kwargs)
self.fields['idroute'].choices = getroutelist()
self.fields['messagetype'].choices = getoutmessagetypes()
self.fields['frompartner'].choices = getpartners()
self.fields['topartner'].choices = getpartners()
class ViewDocument(View):
template = 'bots/document.html'
action = '/document/'
idroute = django.forms.CharField(required=False,widget=HiddenInput())
frompartner = django.forms.CharField(required=False,widget=HiddenInput())
topartner = django.forms.CharField(required=False,widget=HiddenInput())
editype = django.forms.CharField(required=False,widget=HiddenInput())
messagetype = django.forms.CharField(required=False,widget=HiddenInput())
lastrun = django.forms.BooleanField(required=False,initial=False,widget=HiddenInput())
botskey = django.forms.CharField(required=False,widget=HiddenInput())
class SelectOutgoing(Select):
template = 'bots/selectform.html'
action = '/outgoing/'
idroute = django.forms.ChoiceField([],required=False,initial='')
frompartner = django.forms.ChoiceField([],required=False)
topartner = django.forms.ChoiceField([],required=False)
editype = django.forms.ChoiceField(editypelist,required=False)
messagetype = django.forms.ChoiceField(required=False)
lastrun = django.forms.BooleanField(required=False,initial=False)
def __init__(self, *args, **kwargs):
super(SelectOutgoing, self).__init__(*args, **kwargs)
self.fields['idroute'].choices = getroutelist()
self.fields['messagetype'].choices = getoutmessagetypes()
self.fields['frompartner'].choices = getpartners()
self.fields['topartner'].choices = getpartners()
class ViewOutgoing(View):
template = 'bots/outgoing.html'
action = '/outgoing/'
idroute = django.forms.CharField(required=False,widget=HiddenInput())
frompartner = django.forms.CharField(required=False,widget=HiddenInput())
topartner = django.forms.CharField(required=False,widget=HiddenInput())
editype = django.forms.CharField(required=False,widget=HiddenInput())
messagetype = django.forms.CharField(required=False,widget=HiddenInput())
lastrun = django.forms.BooleanField(required=False,initial=False,widget=HiddenInput())
class SelectProcess(Select):
template = 'bots/selectform.html'
action = '/process/'
idroute = django.forms.ChoiceField([],required=False,initial='')
lastrun = django.forms.BooleanField(required=False,initial=False)
def __init__(self, *args, **kwargs):
super(SelectProcess, self).__init__(*args, **kwargs)
self.fields['idroute'].choices = getroutelist()
class ViewProcess(View):
template = 'bots/process.html'
action = '/process/'
idroute = django.forms.CharField(required=False,widget=HiddenInput())
lastrun = django.forms.BooleanField(required=False,initial=False,widget=HiddenInput())
class SelectConfirm(Select):
template = 'bots/selectform.html'
action = '/confirm/'
confirmtype = django.forms.ChoiceField(confirmtypelist,required=False,initial='0')
confirmed = django.forms.ChoiceField([('0',"All runs"),('1',"Current run"),('2',"Last run")],required=False,initial='0')
idroute = django.forms.ChoiceField([],required=False,initial='')
editype = django.forms.ChoiceField(editypelist,required=False)
messagetype = django.forms.ChoiceField([],required=False)
frompartner = django.forms.ChoiceField([],required=False)
topartner = django.forms.ChoiceField([],required=False)
fromchannel = django.forms.ChoiceField([],required=False)
tochannel = django.forms.ChoiceField([],required=False)
def __init__(self, *args, **kwargs):
super(SelectConfirm, self).__init__(*args, **kwargs)
self.fields['idroute'].choices = getroutelist()
self.fields['messagetype'].choices = getallmessagetypes()
self.fields['frompartner'].choices = getpartners()
self.fields['topartner'].choices = getpartners()
self.fields['fromchannel'].choices = getfromchannels()
self.fields['tochannel'].choices = gettochannels()
class ViewConfirm(View):
template = 'bots/confirm.html'
action = '/confirm/'
confirmtype = django.forms.CharField(required=False,widget=HiddenInput())
confirmed = django.forms.CharField(required=False,widget=HiddenInput())
idroute = django.forms.CharField(required=False,widget=HiddenInput())
editype = django.forms.CharField(required=False,widget=HiddenInput())
messagetype = django.forms.CharField(required=False,widget=HiddenInput())
frompartner = django.forms.CharField(required=False,widget=HiddenInput())
topartner = django.forms.CharField(required=False,widget=HiddenInput())
fromchannel = django.forms.CharField(required=False,widget=HiddenInput())
tochannel = django.forms.CharField(required=False,widget=HiddenInput())
class UploadFileForm(django.forms.Form):
file = django.forms.FileField(label='Plugin to read',required=True,widget=django.forms.widgets.FileInput(attrs={'size':'100'}))
class PlugoutForm(django.forms.Form):
databaseconfiguration = django.forms.BooleanField(required=False,initial=True,help_text='Routes, channels, translations, partners, etc.')
umlists = django.forms.BooleanField(required=False,initial=True,label='User maintained code lists',help_text='')
fileconfiguration = django.forms.BooleanField(required=False,initial=True,help_text='Grammars, mapping scrips, routes scripts, etc. (bots/usersys)')
infiles = django.forms.BooleanField(required=False,initial=True,help_text='Examples edi file in bots/botssys/infile')
charset = django.forms.BooleanField(required=False,initial=False,label='(Edifact) files with character sets',help_text='seldom needed.')
databasetransactions = django.forms.BooleanField(required=False,initial=False,help_text='From the database: Runs, incoming files, outgoing files, documents; only for support purposes, on request.')
data = django.forms.BooleanField(required=False,initial=False,label='All transaction files',help_text='bots/botssys/data; only for support purposes, on request.')
logfiles = django.forms.BooleanField(required=False,initial=False,label='Log files',help_text='bots/botssys/logging; only for support purposes, on request.')
config = django.forms.BooleanField(required=False,initial=False,label='configuration files',help_text='bots/config; only for support purposes, on request.')
database = django.forms.BooleanField(required=False,initial=False,label='SQLite database',help_text='Only for support purposes, on request.')
filename = django.forms.CharField(required=True,label='Plugin filename',max_length=250)
def __init__(self, *args, **kwargs):
super(PlugoutForm, self).__init__(*args, **kwargs)
self.fields['filename'].initial = botslib.join(botsglobal.ini.get('directories','botssys'),'myplugin' + time.strftime('_%Y%m%d') + '.zip')
class DeleteForm(django.forms.Form):
delbackup = django.forms.BooleanField(required=False,label='Delete backups of user scripts',initial=True,help_text='Delete backup files in usersys (purge).')
deltransactions = django.forms.BooleanField(required=False,label='Delete transactions',initial=True,help_text='Delete runs, reports, incoming, outgoing, data files.')
delconfiguration = django.forms.BooleanField(required=False,label='Delete configuration',initial=False,help_text='Delete routes, channels, translations, partners etc.')
delcodelists = django.forms.BooleanField(required=False,label='Delete user code lists',initial=False,help_text='Delete user code lists.')
deluserscripts = django.forms.BooleanField(required=False,label='Delete all user scripts',initial=False,help_text='Delete all scripts in usersys (grammars, mappings etc) except charsets.')
delinfile = django.forms.BooleanField(required=False,label='Delete botssys/infiles',initial=False,help_text='Delete files in botssys/infile.')
deloutfile = django.forms.BooleanField(required=False,label='Delete botssys/outfiles',initial=False,help_text='Delete files in botssys/outfile.')
| Python |
'''module contains the functions to be called from user scripts'''
try:
import cPickle as pickle
except:
import pickle
import copy
import collections
from django.utils.translation import ugettext as _
#bots-modules
import botslib
import botsglobal
import inmessage
import outmessage
from botsconfig import *
#*******************************************************************************************************************
#****** functions imported from other modules. reason: user scripting uses primary transform functions *************
#*******************************************************************************************************************
from botslib import addinfo,updateinfo,changestatustinfo,checkunique
from envelope import mergemessages
from communication import run
@botslib.log_session
def translate(startstatus=TRANSLATE,endstatus=TRANSLATED,idroute=''):
''' translates edifiles in one or more edimessages.
reads and parses edifiles that have to be translated.
tries to split files into messages (using 'nextmessage' of grammar); if no splitting: edifile is one message.
searches the right translation in translate-table;
runs the mapping-script for the translation;
Function takes db-ta with status=TRANSLATE->PARSED->SPLITUP->TRANSLATED
'''
#select edifiles to translate; fill ta-object
#~ import gc
#~ gc.disable()
for row in botslib.query(u'''SELECT idta,frompartner,topartner,filename,messagetype,testindicator,editype,charset,alt,fromchannel
FROM ta
WHERE idta>%(rootidta)s
AND status=%(status)s
AND statust=%(statust)s
AND idroute=%(idroute)s
''',
{'status':startstatus,'statust':OK,'idroute':idroute,'rootidta':botslib.get_minta4query()}):
try:
ta_fromfile=botslib.OldTransaction(row['idta']) #TRANSLATE ta
ta_parsedfile = ta_fromfile.copyta(status=PARSED) #copy TRANSLATE to PARSED ta
#whole edi-file is read, parsed and made into a inmessage-object:
edifile = inmessage.edifromfile(frompartner=row['frompartner'],
topartner=row['topartner'],
filename=row['filename'],
messagetype=row['messagetype'],
testindicator=row['testindicator'],
editype=row['editype'],
charset=row['charset'],
alt=row['alt'],
fromchannel=row['fromchannel'],
idroute=idroute)
botsglobal.logger.debug(u'start read and parse input file "%s" editype "%s" messagetype "%s".',row['filename'],row['editype'],row['messagetype'])
for inn in edifile.nextmessage(): #for each message in the edifile:
#inn.ta_info: parameters from inmessage.edifromfile(), syntax-information and parse-information
ta_frommes=ta_parsedfile.copyta(status=SPLITUP) #copy PARSED to SPLITUP ta
inn.ta_info['idta_fromfile'] = ta_fromfile.idta #for confirmations in user script; used to give idta of 'confirming message'
ta_frommes.update(**inn.ta_info) #update ta-record SLIPTUP with info from message content and/or grammar
while 1: #whileloop continues as long as there are alt-translations
#************select parameters for translation(script):
for row2 in botslib.query(u'''SELECT tscript,tomessagetype,toeditype
FROM translate
WHERE frommessagetype = %(frommessagetype)s
AND fromeditype = %(fromeditype)s
AND active=%(booll)s
AND alt=%(alt)s
AND (frompartner_id IS NULL OR frompartner_id=%(frompartner)s OR frompartner_id in (SELECT to_partner_id
FROM partnergroup
WHERE from_partner_id=%(frompartner)s ))
AND (topartner_id IS NULL OR topartner_id=%(topartner)s OR topartner_id in (SELECT to_partner_id
FROM partnergroup
WHERE from_partner_id=%(topartner)s ))
ORDER BY alt DESC,
CASE WHEN frompartner_id IS NULL THEN 1 ELSE 0 END, frompartner_id ,
CASE WHEN topartner_id IS NULL THEN 1 ELSE 0 END, topartner_id ''',
{'frommessagetype':inn.ta_info['messagetype'],
'fromeditype':inn.ta_info['editype'],
'alt':inn.ta_info['alt'],
'frompartner':inn.ta_info['frompartner'],
'topartner':inn.ta_info['topartner'],
'booll':True}):
break #escape if found; we need only the first - ORDER BY in the query
else: #no translation record is found
raise botslib.TranslationNotFoundError(_(u'Editype "$editype", messagetype "$messagetype", frompartner "$frompartner", topartner "$topartner", alt "$alt"'),
editype=inn.ta_info['editype'],
messagetype=inn.ta_info['messagetype'],
frompartner=inn.ta_info['frompartner'],
topartner=inn.ta_info['topartner'],
alt=inn.ta_info['alt'])
ta_tomes=ta_frommes.copyta(status=endstatus) #copy SPLITUP to TRANSLATED ta
tofilename = str(ta_tomes.idta)
tscript=row2['tscript']
tomessage = outmessage.outmessage_init(messagetype=row2['tomessagetype'],editype=row2['toeditype'],filename=tofilename,reference=unique('messagecounter'),statust=OK,divtext=tscript) #make outmessage object
#copy ta_info
botsglobal.logger.debug(u'script "%s" translates messagetype "%s" to messagetype "%s".',tscript,inn.ta_info['messagetype'],tomessage.ta_info['messagetype'])
translationscript,scriptfilename = botslib.botsimport('mappings',inn.ta_info['editype'] + '.' + tscript) #get the mapping-script
doalttranslation = botslib.runscript(translationscript,scriptfilename,'main',inn=inn,out=tomessage)
botsglobal.logger.debug(u'script "%s" finished.',tscript)
if 'topartner' not in tomessage.ta_info: #tomessage does not contain values from ta......
tomessage.ta_info['topartner']=inn.ta_info['topartner']
if tomessage.ta_info['statust'] == DONE: #if indicated in user script the message should be discarded
botsglobal.logger.debug(u'No output file because mapping script explicitly indicated this.')
tomessage.ta_info['filename'] = ''
tomessage.ta_info['status'] = DISCARD
else:
botsglobal.logger.debug(u'Start writing output file editype "%s" messagetype "%s".',tomessage.ta_info['editype'],tomessage.ta_info['messagetype'])
tomessage.writeall() #write tomessage (result of translation).
#problem is that not all values ta_tomes are know to to_message....
#~ print 'tomessage.ta_info',tomessage.ta_info
ta_tomes.update(**tomessage.ta_info) #update outmessage transaction with ta_info;
del tomessage
#~ gc.collect()
if not doalttranslation:
break #out of while loop
else:
inn.ta_info['alt'] = doalttranslation
#end of while-loop
#~ print inn.ta_info
ta_frommes.update(statust=DONE,**inn.ta_info) #update db. inn.ta_info could be changed by script. Is this useful?
del inn
#~ gc.collect()
#exceptions file_in-level
except:
#~ edifile.handleconfirm(ta_fromfile,error=True) #only useful if errors are reported in acknowledgement (eg x12 997). Not used now.
txt=botslib.txtexc()
ta_parsedfile.failure()
ta_parsedfile.update(statust=ERROR,errortext=txt)
botsglobal.logger.debug(u'error in translating input file "%s":\n%s',row['filename'],txt)
else:
edifile.handleconfirm(ta_fromfile,error=False)
ta_fromfile.update(statust=DONE)
ta_parsedfile.update(statust=DONE,**edifile.confirminfo)
botsglobal.logger.debug(u'translated input file "%s".',row['filename'])
del edifile
#~ gc.collect()
#~ gc.enable()
#*********************************************************************
#*** utily functions for persist: store things in the bots database.
#*** this is intended as a memory stretching across messages.
#*********************************************************************
def persist_add(domein,botskey,value):
''' store persistent values in db.
'''
content = pickle.dumps(value,0)
if botsglobal.settings.DATABASE_ENGINE != 'sqlite3' and len(content)>1024:
raise botslib.PersistError(_(u'Data too long for domein "$domein", botskey "$botskey", value "$value".'),domein=domein,botskey=botskey,value=value)
try:
botslib.change(u'''INSERT INTO persist (domein,botskey,content)
VALUES (%(domein)s,%(botskey)s,%(content)s)''',
{'domein':domein,'botskey':botskey,'content':content})
except:
raise botslib.PersistError(_(u'Failed to add for domein "$domein", botskey "$botskey", value "$value".'),domein=domein,botskey=botskey,value=value)
def persist_update(domein,botskey,value):
''' store persistent values in db.
'''
content = pickle.dumps(value,0)
if botsglobal.settings.DATABASE_ENGINE != 'sqlite3' and len(content)>1024:
raise botslib.PersistError(_(u'Data too long for domein "$domein", botskey "$botskey", value "$value".'),domein=domein,botskey=botskey,value=value)
botslib.change(u'''UPDATE persist
SET content=%(content)s
WHERE domein=%(domein)s
AND botskey=%(botskey)s''',
{'domein':domein,'botskey':botskey,'content':content})
def persist_add_update(domein,botskey,value):
# add the record, or update it if already there.
try:
persist_add(domein,botskey,value)
except:
persist_update(domein,botskey,value)
def persist_delete(domein,botskey):
''' store persistent values in db.
'''
botslib.change(u'''DELETE FROM persist
WHERE domein=%(domein)s
AND botskey=%(botskey)s''',
{'domein':domein,'botskey':botskey})
def persist_lookup(domein,botskey):
''' lookup persistent values in db.
'''
for row in botslib.query(u'''SELECT content
FROM persist
WHERE domein=%(domein)s
AND botskey=%(botskey)s''',
{'domein':domein,'botskey':botskey}):
return pickle.loads(str(row['content']))
return None
#*********************************************************************
#*** utily functions for codeconversion
#*** 2 types: codeconversion via database tabel ccode, and via file.
#*** 20111116: codeconversion via file is depreciated, will disappear.
#*********************************************************************
#***code conversion via database tabel ccode
def ccode(ccodeid,leftcode,field='rightcode'):
''' converts code using a db-table.
converted value is returned, exception if not there.
'''
for row in botslib.query(u'''SELECT ''' +field+ '''
FROM ccode
WHERE ccodeid_id = %(ccodeid)s
AND leftcode = %(leftcode)s''',
{'ccodeid':ccodeid,
'leftcode':leftcode,
}):
return row[field]
raise botslib.CodeConversionError(_(u'Value "$value" not in code-conversion, user table "$table".'),value=leftcode,table=ccodeid)
codetconversion = ccode
def safe_ccode(ccodeid,leftcode,field='rightcode'):
''' converts code using a db-table.
converted value is returned, if not there return orginal code
'''
try:
return ccode(ccodeid,leftcode,field)
except botslib.CodeConversionError:
return leftcode
safecodetconversion = safe_ccode
def reverse_ccode(ccodeid,rightcode,field='leftcode'):
''' as ccode but reversed lookup.'''
for row in botslib.query(u'''SELECT ''' +field+ '''
FROM ccode
WHERE ccodeid_id = %(ccodeid)s
AND rightcode = %(rightcode)s''',
{'ccodeid':ccodeid,
'rightcode':rightcode,
}):
return row[field]
raise botslib.CodeConversionError(_(u'Value "$value" not in code-conversion, user table "$table".'),value=rightcode,table=ccodeid)
rcodetconversion = reverse_ccode
def safe_reverse_ccode(ccodeid,rightcode,field='leftcode'):
''' as safe_ccode but reversed lookup.'''
try:
return ccode(ccodeid,rightcode,field)
except botslib.CodeConversionError:
return rightcode
safercodetconversion = safe_reverse_ccode
def getcodeset(ccodeid,leftcode,field='rightcode'):
''' Get a code set
'''
return list(botslib.query(u'''SELECT ''' +field+ '''
FROM ccode
WHERE ccodeid_id = %(ccodeid)s
AND leftcode = %(leftcode)s''',
{'ccodeid':ccodeid,
'leftcode':leftcode,
}))
#***code conversion via file. 20111116: depreciated
def safecodeconversion(modulename,value):
''' converts code using a codelist.
converted value is returned.
codelist is first imported from file in codeconversions (lookup right place/mudule in bots.ini)
'''
module,filename = botslib.botsimport('codeconversions',modulename)
try:
return module.codeconversions[value]
except KeyError:
return value
def codeconversion(modulename,value):
''' converts code using a codelist.
converted value is returned.
codelist is first imported from file in codeconversions (lookup right place/mudule in bots.ini)
'''
module,filename = botslib.botsimport('codeconversions',modulename)
try:
return module.codeconversions[value]
except KeyError:
raise botslib.CodeConversionError(_(u'Value "$value" not in file for codeconversion "$filename".'),value=value,filename=filename)
def safercodeconversion(modulename,value):
''' as codeconversion but reverses the dictionary first'''
module,filename = botslib.botsimport('codeconversions',modulename)
if not hasattr(module,'botsreversed'+'codeconversions'):
reversedict = dict((value,key) for key,value in module.codeconversions.items())
setattr(module,'botsreversed'+'codeconversions',reversedict)
try:
return module.botsreversedcodeconversions[value]
except KeyError:
return value
def rcodeconversion(modulename,value):
''' as codeconversion but reverses the dictionary first'''
module,filename = botslib.botsimport('codeconversions',modulename)
if not hasattr(module,'botsreversed'+'codeconversions'):
reversedict = dict((value,key) for key,value in module.codeconversions.items())
setattr(module,'botsreversed'+'codeconversions',reversedict)
try:
return module.botsreversedcodeconversions[value]
except KeyError:
raise botslib.CodeConversionError(_(u'Value "$value" not in file for reversed codeconversion "$filename".'),value=value,filename=filename)
#*********************************************************************
#*** utily functions for calculating/generating/checking EAN/GTIN/GLN
#*********************************************************************
def calceancheckdigit(ean):
''' input: EAN without checkdigit; returns the checkdigit'''
try:
if not ean.isdigit():
raise botslib.EanError(_(u'GTIN "$ean" should be string with only numericals'),ean=ean)
except AttributeError:
raise botslib.EanError(_(u'GTIN "$ean" should be string, but is a "$type"'),ean=ean,type=type(ean))
sum1=sum([int(x)*3 for x in ean[-1::-2]]) + sum([int(x) for x in ean[-2::-2]])
return str((1000-sum1)%10)
def calceancheckdigit2(ean):
''' just for fun: slightly different algoritm for calculating the ean checkdigit. same results; is 10% faster.
'''
sum1 = 0
factor = 3
for i in ean[-1::-1]:
sum1 += int(i) * factor
factor = 4 - factor #factor flip-flops between 3 and 1...
return str(((1000 - sum1) % 10))
def checkean(ean):
''' input: EAN; returns: True (valid EAN) of False (EAN not valid)'''
return (ean[-1] == calceancheckdigit(ean[:-1]))
def addeancheckdigit(ean):
''' input: EAN without checkdigit; returns EAN with checkdigit'''
return ean+calceancheckdigit(ean)
#*********************************************************************
#*** div utily functions for mappings
#*********************************************************************
def unique(domein):
''' generate unique number within range domein.
uses db to keep track of last generated number.
if domein not used before, initialized with 1.
'''
return str(botslib.unique(domein))
def inn2out(inn,out):
''' copies inn-message to outmessage
'''
out.root = copy.deepcopy(inn.root)
def useoneof(*args):
for arg in args:
if arg:
return arg
else:
return None
def dateformat(date):
''' for edifact: return right format code for the date. '''
if not date:
return None
if len(date)==8:
return '102'
if len(date)==12:
return '203'
if len(date)==16:
return '718'
return None
def datemask(value,frommask,tomask):
''' value is formatted according as in frommask;
returned is the value formatted according to tomask.
'''
if not value:
return value
convdict = collections.defaultdict(list)
for key,value in zip(frommask,value):
convdict[key].append(value)
#~ return ''.join([convdict.get(c,[c]).pop(0) for c in tomask]) #very short, but not faster....
terug = ''
for c in tomask:
terug += convdict.get(c,[c]).pop(0)
return terug
| Python |
import os
import sys
import atexit
import traceback
import logging
#import bots-modules
import bots.botslib as botslib
import bots.botsglobal as botsglobal
def showusage():
print ' Update existing bots database for new release 1.6.0'
print ' Options:'
print " -c<directory> directory for configuration files (default: config)."
def start(configdir = 'config'):
#********command line arguments**************************
for arg in sys.argv[1:]:
if not arg:
continue
if arg.startswith('-c'):
configdir = arg[2:]
if not configdir:
print 'Indicated Bots should use specific .ini file but no file name was given.'
sys.exit(1)
elif arg in ["?", "/?"] or arg.startswith('-'):
showusage()
sys.exit(0)
else: #pick up names of routes to run
showusage()
#**************initialise configuration file******************************
try:
botsinit.generalinit(configdir)
botslib.settimeout(botsglobal.ini.getint('settings','globaltimeout',10)) #
except:
traceback.print_exc()
print 'Error in reading/initializing ini-file.'
sys.exit(1)
#**************initialise logging******************************
try:
botsinit.initenginelogging()
except:
traceback.print_exc()
print 'Error in initialising logging system.'
sys.exit(1)
else:
atexit.register(logging.shutdown)
botsglobal.logger.info('Python version: "%s".',sys.version)
botsglobal.logger.info('Bots configuration file: "%s".',botsinifile)
botsglobal.logger.info('Bots database configuration file: "%s".',botslib.join('config',os.path.basename(botsglobal.ini.get('directories','tgconfig','botstg.cfg'))))
#**************connect to database**********************************
try:
botslib.connect()
except:
traceback.print_exc()
print 'Error connecting to database.'
sys.exit(1)
else:
atexit.register(botsglobal.db.close)
try:
cursor = botsglobal.db.cursor()
cursor.execute('''ALTER TABLE routes ADD COLUMN notindefaultrun BOOLEAN''',None)
cursor.execute('''ALTER TABLE channel ADD COLUMN archivepath VARCHAR(256)''',None)
cursor.execute('''ALTER TABLE partner ADD COLUMN mail VARCHAR(256)''',None)
cursor.execute('''ALTER TABLE partner ADD COLUMN cc VARCHAR(256)''',None)
cursor.execute('''ALTER TABLE chanpar ADD COLUMN cc VARCHAR(256)''',None)
cursor.execute('''ALTER TABLE ta ADD COLUMN confirmasked BOOLEAN''',None)
cursor.execute('''ALTER TABLE ta ADD COLUMN confirmed BOOLEAN''',None)
cursor.execute('''ALTER TABLE ta ADD COLUMN confirmtype VARCHAR(35) DEFAULT '' ''',None)
cursor.execute('''ALTER TABLE ta ADD COLUMN confirmidta INTEGER DEFAULT 0''',None)
cursor.execute('''ALTER TABLE ta ADD COLUMN envelope VARCHAR(35) DEFAULT '' ''',None)
cursor.execute('''ALTER TABLE ta ADD COLUMN botskey VARCHAR(35) DEFAULT '' ''',None)
cursor.execute('''ALTER TABLE ta ADD COLUMN cc VARCHAR(512) DEFAULT '' ''',None)
if botsglobal.dbinfo.drivername == 'mysql':
cursor.execute('''ALTER TABLE ta MODIFY errortext VARCHAR(2048)''',None)
elif botsglobal.dbinfo.drivername == 'postgres':
cursor.execute('''ALTER TABLE ta ALTER COLUMN errortext type VARCHAR(2048)''',None)
#else: #sqlite does not allow modifying existing field, but does not check lengths either so this works.
cursor.execute('''CREATE TABLE confirmrule (
id INTEGER PRIMARY KEY,
active BOOLEAN,
confirmtype VARCHAR(35),
ruletype VARCHAR(35),
negativerule BOOLEAN,
frompartner VARCHAR(35),
topartner VARCHAR(35),
idchannel VARCHAR(35),
idroute VARCHAR(35),
editype VARCHAR(35),
messagetype VARCHAR(35) )
''',None)
except:
traceback.print_exc()
print 'Error while updating the database. Database is not updated.'
botsglobal.db.rollback()
sys.exit(1)
botsglobal.db.commit()
cursor.close()
print 'Database is updated.'
sys.exit(0)
| Python |
from django.conf.urls.defaults import *
from django.contrib import admin,auth
from django.views.generic.simple import redirect_to
from django.contrib.auth.decorators import login_required,user_passes_test
from bots import views
admin.autodiscover()
staff_required = user_passes_test(lambda u: u.is_staff)
superuser_required = user_passes_test(lambda u: u.is_superuser)
urlpatterns = patterns('',
(r'^login.*', 'django.contrib.auth.views.login', {'template_name': 'admin/login.html'}),
(r'^logout.*', 'django.contrib.auth.views.logout',{'next_page': '/'}),
#login required
(r'^home.*', login_required(views.home)),
(r'^incoming.*', login_required(views.incoming)),
(r'^detail.*', login_required(views.detail)),
(r'^process.*', login_required(views.process)),
(r'^outgoing.*', login_required(views.outgoing)),
(r'^document.*', login_required(views.document)),
(r'^reports.*', login_required(views.reports)),
(r'^confirm.*', login_required(views.confirm)),
(r'^filer.*', login_required(views.filer)),
#only staff
(r'^admin/$', login_required(views.home)), #do not show django admin root page
(r'^admin/bots/$', login_required(views.home)), #do not show django admin root page
(r'^admin/bots/uniek/.+$', redirect_to, {'url': '/admin/bots/uniek/'}), #hack. uniek counters can be changed (on main page), but never added. This rule disables the edit/add uniek pages.
(r'^admin/', include(admin.site.urls)),
(r'^runengine.+', staff_required(views.runengine)),
#only superuser
(r'^delete.*', superuser_required(views.delete)),
(r'^plugin.*', superuser_required(views.plugin)),
(r'^plugout.*', superuser_required(views.plugout)),
(r'^unlock.*', superuser_required(views.unlock)),
(r'^sendtestmail.*', superuser_required(views.sendtestmailmanagers)),
#catch-all
(r'^.*', 'bots.views.index'),
)
handler500='bots.views.server_error'
| Python |
from django import template
register = template.Library()
@register.filter
def url2path(value):
if value.startswith('/admin/bots/'):
value = value[12:]
else:
value = value[1:]
if value:
if value[-1] == '/':
value = value[:-1]
else:
value = 'home'
return value
| Python |
#!/usr/bin/env python
import os
import optparse
import subprocess
import sys
here = os.path.dirname(__file__)
def main():
usage = "usage: %prog [file1..fileN]"
description = """With no file paths given this script will automatically
compress all jQuery-based files of the admin app. Requires the Google Closure
Compiler library and Java version 6 or later."""
parser = optparse.OptionParser(usage, description=description)
parser.add_option("-c", dest="compiler", default="~/bin/compiler.jar",
help="path to Closure Compiler jar file")
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose")
(options, args) = parser.parse_args()
compiler = os.path.expanduser(options.compiler)
if not os.path.exists(compiler):
sys.exit("Google Closure compiler jar file %s not found. Please use the -c option to specify the path." % compiler)
if not args:
if options.verbose:
sys.stdout.write("No filenames given; defaulting to admin scripts\n")
args = [os.path.join(here, f) for f in [
"actions.js", "collapse.js", "inlines.js", "prepopulate.js"]]
for arg in args:
if not arg.endswith(".js"):
arg = arg + ".js"
to_compress = os.path.expanduser(arg)
if os.path.exists(to_compress):
to_compress_min = "%s.min.js" % "".join(arg.rsplit(".js"))
cmd = "java -jar %s --js %s --js_output_file %s" % (compiler, to_compress, to_compress_min)
if options.verbose:
sys.stdout.write("Running: %s\n" % cmd)
subprocess.call(cmd.split())
else:
sys.stdout.write("File %s not found. Sure it exists?\n" % to_compress)
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/env python
import os
import optparse
import subprocess
import sys
here = os.path.dirname(__file__)
def main():
usage = "usage: %prog [file1..fileN]"
description = """With no file paths given this script will automatically
compress all jQuery-based files of the admin app. Requires the Google Closure
Compiler library and Java version 6 or later."""
parser = optparse.OptionParser(usage, description=description)
parser.add_option("-c", dest="compiler", default="~/bin/compiler.jar",
help="path to Closure Compiler jar file")
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose")
(options, args) = parser.parse_args()
compiler = os.path.expanduser(options.compiler)
if not os.path.exists(compiler):
sys.exit("Google Closure compiler jar file %s not found. Please use the -c option to specify the path." % compiler)
if not args:
if options.verbose:
sys.stdout.write("No filenames given; defaulting to admin scripts\n")
args = [os.path.join(here, f) for f in [
"actions.js", "collapse.js", "inlines.js", "prepopulate.js"]]
for arg in args:
if not arg.endswith(".js"):
arg = arg + ".js"
to_compress = os.path.expanduser(arg)
if os.path.exists(to_compress):
to_compress_min = "%s.min.js" % "".join(arg.rsplit(".js"))
cmd = "java -jar %s --js %s --js_output_file %s" % (compiler, to_compress, to_compress_min)
if options.verbose:
sys.stdout.write("Running: %s\n" % cmd)
subprocess.call(cmd.split())
else:
sys.stdout.write("File %s not found. Sure it exists?\n" % to_compress)
if __name__ == '__main__':
main()
| Python |
"""SMTP over SSL client.
used for python < 2.5
in python 2.6 and up the smtp-library has a class SMTP_SSL
Public class: SMTP_SSL
Public errors: SMTPSSLException
"""
# Author: Matt Butcher <mbutche@luc.edu>, Feb. 2007
# License: MIT License (or, at your option, the GPL, v.2 or later as posted at
# http://gnu.org).
##
## Begin License
#
# Copyright (c) 2007 M Butcher
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
##
##End License
#
# This is just a minor modification to the smtplib code by Dragon De Monsyn.
import smtplib, socket
__version__ = "1.00"
__all__ = ['SMTPSSLException', 'SMTP_SSL']
SSMTP_PORT = 465
class SMTPSSLException(smtplib.SMTPException):
"""Base class for exceptions resulting from SSL negotiation."""
class SMTP_SSL (smtplib.SMTP):
"""This class provides SSL access to an SMTP server.
SMTP over SSL typical listens on port 465. Unlike StartTLS, SMTP over SSL
makes an SSL connection before doing a helo/ehlo. All transactions, then,
are done over an encrypted channel.
This class is a simple subclass of the smtplib.SMTP class that comes with
Python. It overrides the connect() method to use an SSL socket, and it
overrides the starttls() function to throw an error (you can't do
starttls within an SSL session).
"""
certfile = None
keyfile = None
def __init__(self, host='', port=0, local_hostname=None, keyfile=None, certfile=None):
"""Initialize a new SSL SMTP object.
If specified, `host' is the name of the remote host to which this object
will connect. If specified, `port' specifies the port (on `host') to
which this object will connect. `local_hostname' is the name of the
localhost. By default, the value of socket.getfqdn() is used.
An SMTPConnectError is raised if the SMTP host does not respond
correctly.
An SMTPSSLError is raised if SSL negotiation fails.
Warning: This object uses socket.ssl(), which does not do client-side
verification of the server's cert.
"""
self.certfile = certfile
self.keyfile = keyfile
smtplib.SMTP.__init__(self, host, port, local_hostname)
def connect(self, host='localhost', port=0):
"""Connect to an SMTP server using SSL.
`host' is localhost by default. Port will be set to 465 (the default
SSL SMTP port) if no port is specified.
If the host name ends with a colon (`:') followed by a number,
that suffix will be stripped off and the
number interpreted as the port number to use. This will override the
`port' parameter.
Note: This method is automatically invoked by __init__, if a host is
specified during instantiation.
"""
# MB: Most of this (Except for the socket connection code) is from
# the SMTP.connect() method. I changed only the bare minimum for the
# sake of compatibility.
if not port and (host.find(':') == host.rfind(':')):
i = host.rfind(':')
if i >= 0:
host, port = host[:i], host[i+1:]
try: port = int(port)
except ValueError:
raise socket.error, "nonnumeric port"
if not port: port = SSMTP_PORT
if self.debuglevel > 0: print>>stderr, 'connect:', (host, port)
msg = "getaddrinfo returns an empty list"
self.sock = None
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
self.sock = socket.socket(af, socktype, proto)
if self.debuglevel > 0: print>>stderr, 'connect:', (host, port)
self.sock.connect(sa)
# MB: Make the SSL connection.
sslobj = socket.ssl(self.sock, self.keyfile, self.certfile)
except socket.error, msg:
if self.debuglevel > 0:
print>>stderr, 'connect fail:', (host, port)
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
raise socket.error, msg
# MB: Now set up fake socket and fake file classes.
# Thanks to the design of smtplib, this is all we need to do
# to get SSL working with all other methods.
self.sock = smtplib.SSLFakeSocket(self.sock, sslobj)
self.file = smtplib.SSLFakeFile(sslobj);
(code, msg) = self.getreply()
if self.debuglevel > 0: print>>stderr, "connect:", msg
return (code, msg)
def setkeyfile(self, keyfile):
"""Set the absolute path to a file containing a private key.
This method will only be effective if it is called before connect().
This key will be used to make the SSL connection."""
self.keyfile = keyfile
def setcertfile(self, certfile):
"""Set the absolute path to a file containing a x.509 certificate.
This method will only be effective if it is called before connect().
This certificate will be used to make the SSL connection."""
self.certfile = certfile
def starttls():
"""Raises an exception.
You cannot do StartTLS inside of an ssl session. Calling starttls() will
return an SMTPSSLException"""
raise SMTPSSLException, "Cannot perform StartTLS within SSL session."
| Python |
import os
import sys
import copy
import inmessage
import outmessage
import botslib
import botsinit
import botsglobal
from botsconfig import *
#buggy
#in usersys/grammars/xmlnocheck should be a file xmlnocheck
#usage: c:\python25\python bots-xml2botsgrammar.py botssys/infile/test.xml botssys/infile/resultgrammar.py -cconfig
def treewalker(node,mpath):
mpath.append({'BOTSID':node.record['BOTSID']})
for childnode in node.children:
yield childnode,mpath[:]
for terugnode,terugmpath in treewalker(childnode,mpath):
yield terugnode,terugmpath
mpath.pop()
def writefields(tree,node,mpath):
putmpath = copy.deepcopy(mpath)
#~ print mpath
#~ print node.record
for key in node.record.keys():
#~ print key
if key != 'BOTSID':
putmpath[-1][key]=u'dummy'
#~ print 'mpath used',mpath
#~ putmpath = copy.deepcopy(mpath)
tree.put(*putmpath)
#~ del mpath[-1][key]
#~ print '\n'
def tree2grammar(node,structure,recorddefs):
structure.append({ID:node.record['BOTSID'],MIN:0,MAX:99999,LEVEL:[]})
recordlist = []
for key in node.record.keys():
recordlist.append([key, 'C', 256, 'AN'])
if node.record['BOTSID'] in recorddefs:
recorddefs[node.record['BOTSID']] = removedoublesfromlist(recorddefs[node.record['BOTSID']] + recordlist)
#~ recorddefs[node.record['BOTSID']].extend(recordlist)
else:
recorddefs[node.record['BOTSID']] = recordlist
for childnode in node.children:
tree2grammar(childnode,structure[-1][LEVEL],recorddefs)
def recorddefs2string(recorddefs,sortedstructurelist):
recorddefsstring = "{\n"
for i in sortedstructurelist:
#~ for key, value in recorddefs.items():
recorddefsstring += " '%s':\n [\n"%i
for field in recorddefs[i]:
if field[0]=='BOTSID':
field[1]='M'
recorddefsstring += " %s,\n"%field
break
for field in recorddefs[i]:
if '__' in field[0]:
recorddefsstring += " %s,\n"%field
for field in recorddefs[i]:
if field[0]!='BOTSID' and '__' not in field[0]:
recorddefsstring += " %s,\n"%field
recorddefsstring += " ],\n"
recorddefsstring += " }\n"
return recorddefsstring
def structure2string(structure,level=0):
structurestring = ""
for i in structure:
structurestring += level*" " + "{ID:'%s',MIN:%s,MAX:%s"%(i[ID],i[MIN],i[MAX])
recursivestructurestring = structure2string(i[LEVEL],level+1)
if recursivestructurestring:
structurestring += ",LEVEL:[\n" + recursivestructurestring + level*" " + "]},\n"
else:
structurestring += "},\n"
return structurestring
def structure2list(structure):
structurelist = structure2listcore(structure)
return removedoublesfromlist(structurelist)
def removedoublesfromlist(orglist):
list2return = []
for e in orglist:
if e not in list2return:
list2return.append(e)
return list2return
def structure2listcore(structure):
structurelist = []
for i in structure:
structurelist.append(i[ID])
structurelist.extend(structure2listcore(i[LEVEL]))
return structurelist
def showusage():
print
print 'Usage:'
print ' %s -c<directory> <xml_file> <xml_grammar_file>'%os.path.basename(sys.argv[0])
print
print ' Creates a grammar from an xml file.'
print ' Options:'
print " -c<directory> directory for configuration files (default: config)."
print ' <xml_file> name of the xml file to read'
print ' <xml_grammar_file> name of the grammar file to write'
print
sys.exit(0)
def start():
#********command line arguments**************************
edifile =''
grammarfile = ''
configdir = 'config'
for arg in sys.argv[1:]:
if not arg:
continue
if arg.startswith('-c'):
configdir = arg[2:]
if not configdir:
print ' !!Indicated Bots should use specific .ini file but no file name was given.'
showusage()
elif arg in ["?", "/?"] or arg.startswith('-'):
showusage()
else:
if not edifile:
edifile = arg
else:
grammarfile = arg
if not (edifile and grammarfile):
print ' !!Both edifile and grammarfile are required.'
showusage()
#********end handling command line arguments**************************
editype='xmlnocheck'
messagetype='xmlnocheckxxxtemporaryforxml2grammar'
mpath = []
botsinit.generalinit(configdir)
os.chdir(botsglobal.ini.get('directories','botspath'))
botsinit.initenginelogging()
#the xml file is parsed as an xmlnocheck message....so a (temp) xmlnocheck grammar is needed....without content... this file is not removed....
tmpgrammarfile = botslib.join(botsglobal.ini.get('directories','usersysabs'),'grammars',editype,messagetype+'.py')
f = open(tmpgrammarfile,'w')
f.close()
inn = inmessage.edifromfile(editype=editype,messagetype=messagetype,filename=edifile)
#~ inn.root.display()
out = outmessage.outmessage_init(editype=editype,messagetype=messagetype,filename='botssys/infile/unitnode/output/inisout03.edi',divtext='',topartner='') #make outmessage object
#handle root
rootmpath = [{'BOTSID':inn.root.record['BOTSID']}]
out.put(*rootmpath)
writefields(out,inn.root,rootmpath)
#walk tree; write results to out-tree
for node,mpath in treewalker(inn.root,mpath):
mpath.append({'BOTSID':node.record['BOTSID']})
if out.get(*mpath) is None:
out.put(*mpath)
writefields(out,node,mpath)
#~ out.root.display()
#out-tree is finished; represents ' normalised' tree suited for writing as a grammar
structure = []
recorddefs = {}
tree2grammar(out.root,structure,recorddefs)
#~ for key,value in recorddefs.items():
#~ print key,value
#~ print '\n'
sortedstructurelist = structure2list(structure)
recorddefsstring = recorddefs2string(recorddefs,sortedstructurelist)
structurestring = structure2string(structure)
#write grammar file
grammar = open(grammarfile,'wb')
grammar.write('#grammar automatically generated by bots open source edi translator.')
grammar.write('\n')
grammar.write('from bots.botsconfig import *')
grammar.write('\n\n')
grammar.write('syntax = {}')
grammar.write('\n\n')
grammar.write('structure = [\n%s]\n'%(structurestring))
grammar.write('\n\n')
grammar.write('recorddefs = %s'%(recorddefsstring))
grammar.write('\n\n')
grammar.close()
print 'grammar file is written',grammarfile
if __name__ == '__main__':
start()
| Python |
import sys
import copy
import datetime
import django
from django.core.paginator import Paginator,EmptyPage, InvalidPage
from django.utils.translation import ugettext as _
import models
import botsglobal
from botsconfig import *
def preparereport2view(post,runidta):
terugpost = post.copy()
thisrun = models.report.objects.get(idta=runidta)
terugpost['datefrom'] = thisrun.ts
try:
nextrun = thisrun.get_next_by_ts()
terugpost['dateuntil'] = nextrun.ts
except:
terugpost['dateuntil'] = datetimeuntil()
return terugpost
def changepostparameters(post,type):
terugpost = post.copy()
if type == 'confirm2in':
for key in ['confirmtype','confirmed','fromchannel','tochannel']:
terugpost.pop(key)[0]
terugpost['ineditype'] = terugpost.pop('editype')[0]
terugpost['inmessagetype'] = terugpost.pop('messagetype')[0]
#~ terugpost['outeditype'] = ''
#~ terugpost['outmessagetype'] = ''
elif type == 'confirm2out':
for key in ['confirmtype','confirmed','fromchannel','tochannel']:
terugpost.pop(key)[0]
elif type == 'out2in':
terugpost['outeditype'] = terugpost.pop('editype')[0]
terugpost['outmessagetype'] = terugpost.pop('messagetype')[0]
#~ terugpost['ineditype'] = ''
#~ terugpost['inmessagetype'] = ''
elif type == 'out2confirm':
for key in ['lastrun']:
terugpost.pop(key)[0]
elif type == 'in2out':
terugpost['editype'] = terugpost.pop('outeditype')[0]
terugpost['messagetype'] = terugpost.pop('outmessagetype')[0]
for key in ['ineditype','inmessagetype']:
terugpost.pop(key)[0]
elif type == 'in2confirm':
terugpost['editype'] = terugpost.pop('outeditype')[0]
terugpost['messagetype'] = terugpost.pop('outmessagetype')[0]
for key in ['lastrun','statust','ineditype','inmessagetype']:
terugpost.pop(key)[0]
elif type == '2process':
for key in terugpost.keys():
if key not in ['datefrom','dateuntil','lastrun','idroute']:
terugpost.pop(key)[0]
elif type == 'fromprocess':
pass #is OK, all values are used
terugpost['sortedby'] = 'ts'
terugpost['sortedasc'] = False
terugpost['page'] = 1
return terugpost
def django_trace_origin(idta,where):
''' bots traces back all from the current step/ta.
where is a dict that is used to indicate a condition.
eg: {'status':EXTERNIN}
If bots finds a ta for which this is true, the ta is added to a list.
The list is returned when all tracing is done, and contains all ta's for which 'where' is True
'''
def trace_recurse(ta):
''' recursive
walk over ta's backward (to origin).
if condition is met, add the ta to a list
'''
for parent in get_parent(ta):
donelijst.append(parent.idta)
for key,value in where.items():
if getattr(parent,key) != value:
break
else: #all where-criteria are true; check if we already have this ta
teruglijst.append(parent)
trace_recurse(parent)
def get_parent(ta):
''' yields the parents of a ta '''
if ta.parent:
if ta.parent not in donelijst: #search via parent
yield models.ta.objects.get(idta=ta.parent)
else:
for parent in models.ta.objects.filter(child=ta.idta).all():
if parent.idta in donelijst:
continue
yield parent
donelijst = []
teruglijst = []
ta = models.ta.objects.get(idta=idta)
trace_recurse(ta)
return teruglijst
def trace_document(pquery):
''' trace forward & backwardfrom the current step/ta (status SPLITUP).
gathers confirm information
'''
def trace_forward(ta):
''' recursive. walk over ta's forward (to exit). '''
if ta.child:
child = models.ta.objects.get(idta=ta.child)
else:
try:
child = models.ta.objects.filter(parent=ta.idta).all()[0]
except IndexError:
return #no result, return
if child.confirmasked:
taorg.confirmtext += _(u'Confirm send: %(confirmasked)s; confirmed: %(confirmed)s; confirmtype: %(confirmtype)s\n')%{'confirmasked':child.confirmasked,'confirmed':child.confirmed,'confirmtype':child.confirmtype}
if child.status==EXTERNOUT:
taorg.outgoing = child.idta
taorg.channel = child.tochannel
trace_forward(child)
def trace_back(ta):
''' recursive. walk over ta's backward (to origin). '''
if ta.parent:
parent = models.ta.objects.get(idta=ta.parent)
else:
try:
parent = models.ta.objects.filter(child=ta.idta).all()[0] #just get one parent
except IndexError:
return #no result, return
if parent.confirmasked:
taorg.confirmtext += u'Confirm asked: %(confirmasked)s; confirmed: %(confirmed)s; confirmtype: %(confirmtype)s\n'%{'confirmasked':parent.confirmasked,'confirmed':parent.confirmed,'confirmtype':parent.confirmtype}
if parent.status==EXTERNIN:
taorg.incoming = parent.idta
taorg.channel = parent.fromchannel
trace_back(parent)
#main for trace_document*****************
for taorg in pquery.object_list:
taorg.confirmtext = u''
if taorg.status == SPLITUP:
trace_back(taorg)
else:
trace_forward(taorg)
if not taorg.confirmtext:
taorg.confirmtext = u'---'
def gettrace(ta):
''' recursive. Build trace (tree of ta's).'''
if ta.child: #has a explicit child
ta.talijst = [models.ta.objects.get(idta=ta.child)]
else: #search in ta-table who is reffering to ta
ta.talijst = list(models.ta.objects.filter(parent=ta.idta).all())
for child in ta.talijst:
gettrace(child)
def trace2delete(trace):
def gathermember(ta):
memberlist.append(ta)
for child in ta.talijst:
gathermember(child)
def gatherdelete(ta):
if ta.status==MERGED:
for includedta in models.ta.objects.filter(child=ta.idta,status=TRANSLATED).all(): #select all db-ta's included in MERGED ta
if includedta not in memberlist:
#~ print 'not found idta',includedta.idta, 'not to deletelist:',ta.idta
return
deletelist.append(ta)
for child in ta.talijst:
gatherdelete(child)
memberlist=[]
gathermember(trace) #zet alle idta in memberlist
#~ printlijst(memberlist, 'memberlist')
#~ printlijst(deletelist, 'deletelist')
deletelist=[]
gatherdelete(trace) #zet alle te deleten idta in deletelijst
#~ printlijst(deletelist, 'deletelist')
for ta in deletelist:
ta.delete()
def trace2detail(ta):
def newbranche(ta,level=0):
def dota(ta, isfirststep = False):
if isfirststep:
if not level:
ta.ind= _(u'in')
else:
ta.ind = _(u'split>>>')
elif ta.status==MERGED and ta.nrmessages>1:
ta.ind = _(u'merge<<<')
elif ta.status==EXTERNOUT:
ta.ind = _(u'out')
else:
ta.ind =''
#~ ta.action = models.ta.objects.only('filename').get(idta=ta.script)
ta.channel=ta.fromchannel
if ta.tochannel:
ta.channel=ta.tochannel
detaillist.append(ta)
lengtetalijst = len(ta.talijst)
if lengtetalijst > 1:
for child in ta.talijst:
newbranche(child,level=level+1)
elif lengtetalijst == 1:
dota(ta.talijst[0])
#start new level
dota(ta,isfirststep = True)
detaillist=[]
newbranche(ta)
return detaillist
def datetimefrom():
#~ terug = datetime.datetime.today()-datetime.timedelta(1860)
terug = datetime.datetime.today()-datetime.timedelta(days=botsglobal.ini.getint('settings','maxdays',30))
#~ return terug.strftime('%Y-%m-%d %H:%M:%S')
return terug.strftime('%Y-%m-%d 00:00:00')
def datetimeuntil():
terug = datetime.datetime.today()
#~ return terug.strftime('%Y-%m-%d %H:%M:%S')
return terug.strftime('%Y-%m-%d 23:59:59')
def handlepagination(requestpost,cleaned_data):
''' use requestpost to set criteria for pagination in cleaned_data'''
if "first" in requestpost:
cleaned_data['page'] = 1
elif "previous" in requestpost:
cleaned_data['page'] = cleaned_data['page'] - 1
elif "next" in requestpost:
cleaned_data['page'] = cleaned_data['page'] + 1
elif "last" in requestpost:
cleaned_data['page']=sys.maxint
elif "order" in requestpost: #change the sorting order
if requestpost['order'] == cleaned_data['sortedby']: #sort same row, but desc->asc etc
cleaned_data['sortedasc'] = not cleaned_data['sortedasc']
else:
cleaned_data['sortedby'] = requestpost['order'].lower()
if cleaned_data['sortedby'] == 'ts':
cleaned_data['sortedasc'] = False
else:
cleaned_data['sortedasc'] = True
def render(request,form,query=None):
return django.shortcuts.render_to_response(form.template, {'form': form,"queryset":query},context_instance=django.template.RequestContext(request))
def getidtalastrun():
return models.filereport.objects.all().aggregate(django.db.models.Max('reportidta'))['reportidta__max']
def filterquery(query , org_cleaned_data, incoming=False):
''' use the data of the form (mostly in hidden fields) to do the query.'''
#~ print 'filterquery',org_cleaned_data
#~ sortedasc2str =
cleaned_data = copy.copy(org_cleaned_data) #copy because it it destroyed in setting up query
page = cleaned_data.pop('page') #do not use this in query, use in paginator
if 'dateuntil' in cleaned_data:
query = query.filter(ts__lt=cleaned_data.pop('dateuntil'))
if 'datefrom' in cleaned_data:
query = query.filter(ts__gte=cleaned_data.pop('datefrom'))
if 'botskey' in cleaned_data and cleaned_data['botskey']:
#~ query = query.filter(botskey__icontains=cleaned_data.pop('botskey')) #is slow for big databases.
query = query.filter(botskey__exact=cleaned_data.pop('botskey'))
if 'sortedby' in cleaned_data:
query = query.order_by({True:'',False:'-'}[cleaned_data.pop('sortedasc')] + cleaned_data.pop('sortedby'))
if 'lastrun' in cleaned_data:
if cleaned_data.pop('lastrun'):
idtalastrun = getidtalastrun()
if idtalastrun: #if no result (=None): there are no filereports.
if incoming: #detect if incoming; do other selection
query = query.filter(reportidta=idtalastrun)
else:
query = query.filter(idta__gt=idtalastrun)
for key,value in cleaned_data.items():
if not value:
del cleaned_data[key]
query = query.filter(**cleaned_data)
paginator = Paginator(query, botsglobal.ini.getint('settings','limit',30))
try:
return paginator.page(page)
except EmptyPage, InvalidPage: #page does not exist: use last page
lastpage = paginator.num_pages
org_cleaned_data['page']=lastpage #change value in form as well!!
return paginator.page(lastpage)
| Python |
'''
code found at code.djangoproject.com/ticket/3777
'''
from django import http
class FilterPersistMiddleware(object):
def _get_default(self, key):
""" Gets any set default filters for the admin. Returns None if no
default is set. """
default = None
#~ default = settings.ADMIN_DEFAULT_FILTERS.get(key, None)
# Filters are allowed to be functions. If this key is one, call it.
if hasattr(default, '__call__'):
default = default()
return default
def process_request(self, request):
if '/admin/' not in request.path or request.method == 'POST':
return None
if request.META.has_key('HTTP_REFERER'):
referrer = request.META['HTTP_REFERER'].split('?')[0]
referrer = referrer[referrer.find('/admin'):len(referrer)]
else:
referrer = u''
popup = 'pop=1' in request.META['QUERY_STRING']
path = request.path
query_string = request.META['QUERY_STRING']
session = request.session
if session.get('redirected', False):#so that we dont loop once redirected
del session['redirected']
return None
key = 'key'+path.replace('/','_')
if popup:
key = 'popup'+key
if path == referrer:
""" We are in the same page as before. We assume that filters were
changed and update them. """
if query_string == '': #Filter is empty, delete it
if session.has_key(key):
del session[key]
return None
else:
request.session[key] = query_string
else:
""" We are are coming from another page. Set querystring to
saved or default value. """
query_string=session.get(key, self._get_default(key))
if query_string is not None:
redirect_to = path+'?'+query_string
request.session['redirected'] = True
return http.HttpResponseRedirect(redirect_to)
else:
return None
'''
Sample default filters:
from datetime import date
def _today():
return 'starttime__gte=' + date.today().isoformat()
# Default filters. Format: 'key_$url', where $url has slashes replaced
# with underscores
# value can either be a function or a string
ADMIN_DEFAULT_FILTERS= {
# display only events starting today
'key_admin_event_calendar_event_': _today,
# display active members
'key_admin_users_member_': 'is_active__exact=1',
# only show new suggestions
'key_admin_suggestions_suggestion_': 'status__exact=new',
}
''' | Python |
import time
import sys
try:
import cPickle as pickle
except:
import pickle
import decimal
NODECIMAL = decimal.Decimal(1)
try:
import cElementTree as ET
#~ print 'imported cElementTree'
except ImportError:
try:
import elementtree.ElementTree as ET
#~ print 'imported elementtree.ElementTree'
except ImportError:
try:
from xml.etree import cElementTree as ET
#~ print 'imported xml.etree.cElementTree'
except ImportError:
from xml.etree import ElementTree as ET
#~ print 'imported xml.etree.ElementTree'
#~ print ET.VERSION
try:
import elementtree.ElementInclude as ETI
except ImportError:
from xml.etree import ElementInclude as ETI
try:
import json as simplejson
except ImportError:
import simplejson
from django.utils.translation import ugettext as _
#bots-modules
import botslib
import botsglobal
import grammar
import message
import node
from botsconfig import *
def outmessage_init(**ta_info):
''' dispatch function class Outmessage or subclass
ta_info: needed is editype, messagetype, filename, charset, merge
'''
try:
classtocall = globals()[ta_info['editype']]
except KeyError:
raise botslib.OutMessageError(_(u'Unknown editype for outgoing message: $editype'),editype=ta_info['editype'])
return classtocall(ta_info)
class Outmessage(message.Message):
''' abstract class; represents a outgoing edi message.
subclassing is necessary for the editype (csv, edi, x12, etc)
A tree of nodes is build form the mpaths received from put()or putloop(). tree starts at self.root.
Put() recieves mpaths from mappingscript
The next algorithm is used to 'map' a mpath into the tree:
For each part of a mpath: search node in 'current' level of tree
If part already as a node:
recursively search node-children
If part not as a node:
append new node to tree;
recursively append next parts to tree
After the mapping-script is finished, the resulting tree is converted to records (self.records).
These records are written to file.
Structure of self.records:
list of record;
record is list of field
field is dict. Keys in field:
- ID field ID (id within this record). For in-file
- VALUE value, content of field
- MPATH mpath of record, only for first field(=recordID)
- LIN linenr of field in in-file
- POS positionnr within line in in-file
- SFIELD True if subfield (edifact-only)
first field for record is recordID.
'''
def __init__(self,ta_info):
self.ta_info = ta_info
self.root = node.Node(record={}) #message tree; build via put()-interface in mapping-script. Initialise with empty dict
super(Outmessage,self).__init__()
def outmessagegrammarread(self,editype,messagetype):
''' read the grammar for a out-message.
try to read the topartner dependent grammar syntax.
'''
self.defmessage = grammar.grammarread(editype,messagetype)
self.defmessage.display(self.defmessage.structure)
#~ print 'self.ta_info',self.ta_info
#~ print 'self.defmessage.syntax',self.defmessage.syntax
botslib.updateunlessset(self.ta_info,self.defmessage.syntax) #write values from grammar to self.ta_info - unless these values are already set eg by mapping script
if self.ta_info['topartner']: #read syntax-file for partner dependent syntax
try:
partnersyntax = grammar.syntaxread('partners',editype,self.ta_info['topartner'])
self.ta_info.update(partnersyntax.syntax) #partner syntax overrules!
except ImportError:
pass #No partner specific syntax found (is not an error).
def writeall(self):
''' writeall is called for writing all 'real' outmessage objects; but not for envelopes.
writeall is call from transform.translate()
'''
self.outmessagegrammarread(self.ta_info['editype'],self.ta_info['messagetype'])
self.nrmessagewritten = 0
if self.root.record: #root record contains information; write whole tree in one time
self.multiplewrite = False
self.normalisetree(self.root)
self._initwrite()
self._write(self.root)
self.nrmessagewritten = 1
self._closewrite()
elif not self.root.children:
raise botslib.OutMessageError(_(u'No outgoing message')) #then there is nothing to write...
else:
self.multiplewrite = True
for childnode in self.root.children:
self.normalisetree(childnode)
self._initwrite()
for childnode in self.root.children:
self._write(childnode)
self.nrmessagewritten += 1
self._closewrite()
def _initwrite(self):
botsglobal.logger.debug(u'Start writing to file "%s".',self.ta_info['filename'])
self._outstream = botslib.opendata(self.ta_info['filename'],'wb',charset=self.ta_info['charset'],errors=self.ta_info['checkcharsetout'])
def _closewrite(self):
botsglobal.logger.debug(u'End writing to file "%s".',self.ta_info['filename'])
self._outstream.close()
def _write(self,node):
''' the write method for most classes.
tree is serialised to sequential records; records are written to file.
Classses that write using other libraries (xml, json, template, db) use specific write methods.
'''
self.tree2records(node)
self._records2file()
def tree2records(self,node):
self.records = [] #tree of nodes is flattened to these records
self._tree2recordscore(node,self.defmessage.structure[0])
def _tree2recordscore(self,node,structure):
''' Write tree of nodes to flat records.
The nodes are already sorted
'''
self._tree2recordfields(node.record,structure) #write root node->first record
for childnode in node.children: #for every node in mpathtree, these are already sorted#SPEED: node.children is already sorted!
for structure_record in structure[LEVEL]: #for structure_record of this level in grammar
if childnode.record['BOTSID'] == structure_record[ID] and childnode.record['BOTSIDnr'] == structure_record[BOTSIDnr]: #if is is the right node:
self._tree2recordscore(childnode,structure_record) #use rest of index in deeper level
def _tree2recordfields(self,noderecord,structure_record):
''' appends fields in noderecord to (raw)record; use structure_record as guide.
complex because is is used for: editypes that have compression rules (edifact), var editypes without compression, fixed protocols
'''
buildrecord = [] #the record that is going to be build; list of dicts. Each dict is a field.
buffer = []
for grammarfield in structure_record[FIELDS]: #loop all fields in grammar-definition
if grammarfield[ISFIELD]: #if field (no composite)
if grammarfield[ID] in noderecord and noderecord[grammarfield[ID]]: #field exists in outgoing message and has data
buildrecord += buffer #write the buffer to buildrecord
buffer=[] #clear the buffer
buildrecord += [{VALUE:noderecord[grammarfield[ID]],SFIELD:False,FORMATFROMGRAMMAR:grammarfield[FORMAT]}] #append new field
else: #there is no data for this field
if self.ta_info['stripfield_sep']:
buffer += [{VALUE:'',SFIELD:False,FORMATFROMGRAMMAR:grammarfield[FORMAT]}] #append new empty to buffer;
else:
value = self._formatfield('',grammarfield,structure_record) #generate field
buildrecord += [{VALUE:value,SFIELD:False,FORMATFROMGRAMMAR:grammarfield[FORMAT]}] #append new field
else: #if composite
donefirst = False #used because first subfield in composite is marked as a field (not a subfield).
subbuffer=[] #buffer for this composite.
subiswritten=False #check if composite contains data
for grammarsubfield in grammarfield[SUBFIELDS]: #loop subfields
if grammarsubfield[ID] in noderecord and noderecord[grammarsubfield[ID]]: #field exists in outgoing message and has data
buildrecord += buffer #write buffer
buffer=[] #clear buffer
buildrecord += subbuffer #write subbuffer
subbuffer=[] #clear subbuffer
buildrecord += [{VALUE:noderecord[grammarsubfield[ID]],SFIELD:donefirst}] #append field
subiswritten = True
else:
if self.ta_info['stripfield_sep']:
subbuffer += [{VALUE:'',SFIELD:donefirst}] #append new empty to buffer;
else:
value = self._formatfield('',grammarsubfield,structure_record) #generate & append new field. For eg fixed and csv: all field have to be present
subbuffer += [{VALUE:value,SFIELD:donefirst}] #generate & append new field
donefirst = True
if not subiswritten: #if composite has no data: write placeholder for composite (stripping is done later)
buffer += [{VALUE:'',SFIELD:False}]
#~ print [buildrecord]
self.records += [buildrecord]
def _formatfield(self,value, grammarfield,record):
''' Input: value (as a string) and field definition.
Some parameters of self.syntax are used: decimaal
Format is checked and converted (if needed).
return the formatted value
'''
if grammarfield[BFORMAT] == 'A':
if isinstance(self,fixed): #check length fields in variable records
if grammarfield[FORMAT] == 'AR': #if field format is alfanumeric right aligned
value = value.rjust(grammarfield[MINLENGTH])
else:
value = value.ljust(grammarfield[MINLENGTH]) #add spaces (left, because A-field is right aligned)
valuelength=len(value)
if valuelength > grammarfield[LENGTH]:
raise botslib.OutMessageError(_(u'record "$mpath" field "$field" too big (max $max): "$content".'),field=grammarfield[ID],content=value,mpath=record[MPATH],max=grammarfield[LENGTH])
if valuelength < grammarfield[MINLENGTH]:
raise botslib.OutMessageError(_(u'record "$mpath" field "$field" too small (min $min): "$content".'),field=grammarfield[ID],content=value,mpath=record[MPATH],min=grammarfield[MINLENGTH])
elif grammarfield[BFORMAT] == 'D':
try:
lenght = len(value)
if lenght==6:
time.strptime(value,'%y%m%d')
elif lenght==8:
time.strptime(value,'%Y%m%d')
else:
raise ValueError(u'To be catched')
except ValueError:
raise botslib.OutMessageError(_(u'record "$mpath" field "$field" no valid date: "$content".'),field=grammarfield[ID],content=value,mpath=record[MPATH])
valuelength=len(value)
if valuelength > grammarfield[LENGTH]:
raise botslib.OutMessageError(_(u'record "$mpath" field "$field" too big (max $max): "$content".'),field=grammarfield[ID],content=value,mpath=record[MPATH],max=grammarfield[LENGTH])
if valuelength < grammarfield[MINLENGTH]:
raise botslib.OutMessageError(_(u'record "$mpath" field "$field" too small (min $min): "$content".'),field=grammarfield[ID],content=value,mpath=record[MPATH],min=grammarfield[MINLENGTH])
elif grammarfield[BFORMAT] == 'T':
try:
lenght = len(value)
if lenght==4:
time.strptime(value,'%H%M')
elif lenght==6:
time.strptime(value,'%H%M%S')
else: #lenght==8: #tsja...just use first part of field
raise ValueError(u'To be catched')
except ValueError:
raise botslib.OutMessageError(_(u'record "$mpath" field "$field" no valid time: "$content".'),field=grammarfield[ID],content=value,mpath=record[MPATH])
valuelength=len(value)
if valuelength > grammarfield[LENGTH]:
raise botslib.OutMessageError(_(u'record "$mpath" field "$field" too big (max $max): "$content".'),field=grammarfield[ID],content=value,mpath=record[MPATH],max=grammarfield[LENGTH])
if valuelength < grammarfield[MINLENGTH]:
raise botslib.OutMessageError(_(u'record "$mpath" field "$field" too small (min $min): "$content".'),field=grammarfield[ID],content=value,mpath=record[MPATH],min=grammarfield[MINLENGTH])
else: #numerics
if value or isinstance(self,fixed): #if empty string for non-fixed: just return. Later on, ta_info[stripemptyfield] determines what to do with them
if not value: #see last if; if a numerical fixed field has content '' , change this to '0' (init)
value='0'
else:
value = value.strip()
if value[0]=='-':
minussign = '-'
absvalue = value[1:]
else:
minussign = ''
absvalue = value
digits,decimalsign,decimals = absvalue.partition('.')
if not digits and not decimals:# and decimalsign:
raise botslib.OutMessageError(_(u'record "$mpath" field "$field" numerical format not valid: "$content".'),field=grammarfield[ID],content=value,mpath=record[MPATH])
if not digits:
digits = '0'
lengthcorrection = 0 #for some formats (if self.ta_info['lengthnumericbare']=True; eg edifact) length is calculated without decimal sing and/or minus sign.
if grammarfield[BFORMAT] == 'R': #floating point: use all decimals received
if self.ta_info['lengthnumericbare']:
if minussign:
lengthcorrection += 1
if decimalsign:
lengthcorrection += 1
try:
value = str(decimal.Decimal(minussign + digits + decimalsign + decimals).quantize(decimal.Decimal(10) ** -len(decimals)))
except:
raise botslib.OutMessageError(_(u'record "$mpath" field "$field" numerical format not valid: "$content".'),field=grammarfield[ID],content=value,mpath=record[MPATH])
if grammarfield[FORMAT] == 'RL': #if field format is numeric right aligned
value = value.ljust(grammarfield[MINLENGTH] + lengthcorrection)
elif grammarfield[FORMAT] == 'RR': #if field format is numeric right aligned
value = value.rjust(grammarfield[MINLENGTH] + lengthcorrection)
else:
value = value.zfill(grammarfield[MINLENGTH] + lengthcorrection)
value = value.replace('.',self.ta_info['decimaal'],1) #replace '.' by required decimal sep.
elif grammarfield[BFORMAT] == 'N': #fixed decimals; round
if self.ta_info['lengthnumericbare']:
if minussign:
lengthcorrection += 1
if grammarfield[DECIMALS]:
lengthcorrection += 1
try:
value = str(decimal.Decimal(minussign + digits + decimalsign + decimals).quantize(decimal.Decimal(10) ** -grammarfield[DECIMALS]))
except:
raise botslib.OutMessageError(_(u'record "$mpath" field "$field" numerical format not valid: "$content".'),field=grammarfield[ID],content=value,mpath=record[MPATH])
if grammarfield[FORMAT] == 'NL': #if field format is numeric right aligned
value = value.ljust(grammarfield[MINLENGTH] + lengthcorrection)
elif grammarfield[FORMAT] == 'NR': #if field format is numeric right aligned
value = value.rjust(grammarfield[MINLENGTH] + lengthcorrection)
else:
value = value.zfill(grammarfield[MINLENGTH] + lengthcorrection)
value = value.replace('.',self.ta_info['decimaal'],1) #replace '.' by required decimal sep.
elif grammarfield[BFORMAT] == 'I': #implicit decimals
if self.ta_info['lengthnumericbare']:
if minussign:
lengthcorrection += 1
try:
d = decimal.Decimal(minussign + digits + decimalsign + decimals) * 10**grammarfield[DECIMALS]
except:
raise botslib.OutMessageError(_(u'record "$mpath" field "$field" numerical format not valid: "$content".'),field=grammarfield[ID],content=value,mpath=record[MPATH])
value = str(d.quantize(NODECIMAL ))
value = value.zfill(grammarfield[MINLENGTH] + lengthcorrection)
if len(value)-lengthcorrection > grammarfield[LENGTH]:
raise botslib.OutMessageError(_(u'record "$mpath" field "$field": content to large: "$content".'),field=grammarfield[ID],content=value,mpath=record[MPATH])
return value
def _records2file(self):
''' convert self.records to a file.
using the right editype (edifact, x12, etc) and charset.
'''
wrap_length = int(self.ta_info.get('wrap_length', 0))
if wrap_length:
s = ''.join(self._record2string(r) for r in self.records) # join all records
for i in range(0,len(s),wrap_length): # then split in fixed lengths
try:
self._outstream.write(s[i:i+wrap_length] + '\r\n')
except UnicodeEncodeError:
raise botslib.OutMessageError(_(u'Chars in outmessage not in charset "$char": $content'),char=self.ta_info['charset'],content=s[i:i+wrap_length])
else:
for record in self.records: #loop all records
try:
self._outstream.write(self._record2string(record))
except UnicodeEncodeError: #, flup: testing with 2.7: flup did not contain the content.
raise botslib.OutMessageError(_(u'Chars in outmessage not in charset "$char": $content'),char=self.ta_info['charset'],content=str(record))
#code before 7 aug 2007 had other handling for flup. May have changed because python2.4->2.5?
def _record2string(self,record):
''' write (all fields of) a record using the right separators, escape etc
'''
sfield_sep = self.ta_info['sfield_sep']
if self.ta_info['record_tag_sep']:
record_tag_sep = self.ta_info['record_tag_sep']
else:
record_tag_sep = self.ta_info['field_sep']
field_sep = self.ta_info['field_sep']
quote_char = self.ta_info['quote_char']
escape = self.ta_info['escape']
record_sep = self.ta_info['record_sep'] + self.ta_info['add_crlfafterrecord_sep']
forcequote = self.ta_info['forcequote']
escapechars = self.getescapechars()
value = u'' #to collect separator/escape plus field content
fieldcount = 0
mode_quote = False
if self.ta_info['noBOTSID']: #for some csv-files: do not write BOTSID so remove it
del record[0]
for field in record: #loop all fields in record
if field[SFIELD]:
value += sfield_sep
else: #is a field:
if fieldcount == 0: #do nothing because first field in record is not preceded by a separator
fieldcount = 1
elif fieldcount == 1:
value += record_tag_sep
fieldcount = 2
else:
value += field_sep
if quote_char: #quote char only used for csv
start_to__quote=False
if forcequote == 2:
if field[FORMATFROMGRAMMAR] in ['AN','A','AR']:
start_to__quote=True
elif forcequote: #always quote; this catches values 1, '1', '0'
start_to__quote=True
else:
if field_sep in field[VALUE] or quote_char in field[VALUE] or record_sep in field[VALUE]:
start_to__quote=True
#TO DO test. if quote_char='' this works OK. Alt: check first if quote_char
if start_to__quote:
value += quote_char
mode_quote = True
for char in field[VALUE]: #use escape (edifact, tradacom). For x12 is warned if content contains separator
if char in escapechars:
if isinstance(self,x12):
if self.ta_info['replacechar']:
char = self.ta_info['replacechar']
else:
raise botslib.OutMessageError(_(u'Character "$char" is in use as separator in this x12 file. Field: "$data".'),char=char,data=field[VALUE])
else:
value +=escape
elif mode_quote and char==quote_char:
value +=quote_char
value += char
if mode_quote:
value += quote_char
mode_quote = False
value += record_sep
return value
def getescapechars(self):
return ''
class fixed(Outmessage):
pass
class idoc(fixed):
def _canonicalfields(self,noderecord,structure_record,headerrecordnumber):
if self.ta_info['automaticcount']:
noderecord.update({'MANDT':self.ta_info['MANDT'],'DOCNUM':self.ta_info['DOCNUM'],'SEGNUM':str(self.recordnumber),'PSGNUM':str(headerrecordnumber),'HLEVEL':str(len(structure_record[MPATH]))})
else:
noderecord.update({'MANDT':self.ta_info['MANDT'],'DOCNUM':self.ta_info['DOCNUM']})
super(idoc,self)._canonicalfields(noderecord,structure_record,headerrecordnumber)
self.recordnumber += 1 #tricky. EDI_DC is not counted, so I count after writing.
class var(Outmessage):
pass
class csv(var):
def getescapechars(self):
return self.ta_info['escape']
class edifact(var):
def getescapechars(self):
terug = self.ta_info['record_sep']+self.ta_info['field_sep']+self.ta_info['sfield_sep']+self.ta_info['escape']
if self.ta_info['version']>='4':
terug += self.ta_info['reserve']
return terug
class tradacoms(var):
def getescapechars(self):
terug = self.ta_info['record_sep']+self.ta_info['field_sep']+self.ta_info['sfield_sep']+self.ta_info['escape']+self.ta_info['record_tag_sep']
return terug
def writeall(self):
''' writeall is called for writing all 'real' outmessage objects; but not for enveloping.
writeall is call from transform.translate()
'''
self.nrmessagewritten = 0
if not self.root.children:
raise botslib.OutMessageError(_(u'No outgoing message')) #then there is nothing to write...
for message in self.root.getloop({'BOTSID':'STX'},{'BOTSID':'MHD'}):
self.outmessagegrammarread(self.ta_info['editype'],message.get({'BOTSID':'MHD','TYPE.01':None}) + message.get({'BOTSID':'MHD','TYPE.02':None}))
if not self.nrmessagewritten:
self._initwrite()
self.normalisetree(message)
self._write(message)
self.nrmessagewritten += 1
self._closewrite()
self.ta_info['nrmessages'] = self.nrmessagewritten
class x12(var):
def getescapechars(self):
terug = self.ta_info['record_sep']+self.ta_info['field_sep']+self.ta_info['sfield_sep']
if self.ta_info['version']>='00403':
terug += self.ta_info['reserve']
return terug
class xml(Outmessage):
''' 20110919: code for _write is almost the same as for envelopewrite.
this could be one method.
Some problems with right xml prolog, standalone, DOCTYPE, processing instructons: Different ET versions give different results:
celementtree in 2.7 is version 1.0.6, but different implementation in 2.6??
So: this works OK for python 2.7
For python <2.7: do not generate standalone, DOCTYPE, processing instructions for encoding !=utf-8,ascii OR if elementtree package is installed (version 1.3.0 or bigger)
'''
def _write(self,node):
''' write normal XML messages (no envelope)'''
xmltree = ET.ElementTree(self._node2xml(node))
root = xmltree.getroot()
self._xmlcorewrite(xmltree,root)
def envelopewrite(self,node):
''' write envelope for XML messages'''
self._initwrite()
self.normalisetree(node)
xmltree = ET.ElementTree(self._node2xml(node))
root = xmltree.getroot()
ETI.include(root)
self._xmlcorewrite(xmltree,root)
self._closewrite()
def _xmlcorewrite(self,xmltree,root):
#xml prolog: always use.*********************************
#standalone, DOCTYPE, processing instructions: only possible in python >= 2.7 or if encoding is utf-8/ascii
if sys.version >= '2.7.0' or self.ta_info['charset'] in ['us-ascii','utf-8'] or ET.VERSION >= '1.3.0':
if self.ta_info['indented']:
indentstring = '\n'
else:
indentstring = ''
if self.ta_info['standalone']:
standalonestring = 'standalone="%s" '%(self.ta_info['standalone'])
else:
standalonestring = ''
PI = ET.ProcessingInstruction('xml', 'version="%s" encoding="%s" %s'%(self.ta_info['version'],self.ta_info['charset'], standalonestring))
self._outstream.write(ET.tostring(PI) + indentstring) #do not use encoding here. gives double xml prolog; possibly because ET.ElementTree.write i used again by write()
#doctype /DTD **************************************
if self.ta_info['DOCTYPE']:
self._outstream.write('<!DOCTYPE %s>'%(self.ta_info['DOCTYPE']) + indentstring)
#processing instructions (other than prolog) ************
if self.ta_info['processing_instructions']:
for pi in self.ta_info['processing_instructions']:
PI = ET.ProcessingInstruction(pi[0], pi[1])
self._outstream.write(ET.tostring(PI) + indentstring) #do not use encoding here. gives double xml prolog; possibly because ET.ElementTree.write i used again by write()
#indent the xml elements
if self.ta_info['indented']:
self.botsindent(root)
#write tree to file; this is differnt for different python/elementtree versions
if sys.version < '2.7.0' and ET.VERSION < '1.3.0':
xmltree.write(self._outstream,encoding=self.ta_info['charset'])
else:
xmltree.write(self._outstream,encoding=self.ta_info['charset'],xml_declaration=False)
def botsindent(self,elem, level=0,indentstring=' '):
i = "\n" + level*indentstring
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + indentstring
for e in elem:
self.botsindent(e, level+1)
if not e.tail or not e.tail.strip():
e.tail = i + indentstring
if not e.tail or not e.tail.strip():
e.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
def _node2xml(self,node):
''' recursive method.
'''
newnode = self._node2xmlfields(node.record)
for childnode in node.children:
newnode.append(self._node2xml(childnode))
return newnode
def _node2xmlfields(self,noderecord):
''' fields in a node are written to xml fields; output is sorted according to grammar
'''
#first generate the xml-'record'
#~ print 'record',noderecord['BOTSID']
attributedict = {}
recordtag = noderecord['BOTSID']
attributemarker = recordtag + self.ta_info['attributemarker'] #attributemarker is a marker in the fieldname used to find out if field is an attribute of either xml-'record' or xml-element
#~ print ' rec_att_mark',attributemarker
for key,value in noderecord.items(): #find attributes belonging to xml-'record' and store in attributedict
if key.startswith(attributemarker):
#~ print ' record attribute',key,value
attributedict[key[len(attributemarker):]] = value
xmlrecord = ET.Element(recordtag,attributedict) #make the xml ET node
if 'BOTSCONTENT' in noderecord: #BOTSCONTENT is used to store the value/text of the xml-record itself.
xmlrecord.text = noderecord['BOTSCONTENT']
del noderecord['BOTSCONTENT']
for key in attributedict.keys(): #remove used fields
del noderecord[attributemarker+key]
del noderecord['BOTSID'] #remove 'record' tag
#generate xml-'fields' in xml-'record'; sort these by looping over records definition
for field_def in self.defmessage.recorddefs[recordtag]: #loop over fields in 'record'
if field_def[ID] not in noderecord: #if field not in outmessage: skip
continue
#~ print ' field',field_def
attributedict = {}
attributemarker = field_def[ID] + self.ta_info['attributemarker']
#~ print ' field_att_mark',attributemarker
for key,value in noderecord.items():
if key.startswith(attributemarker):
#~ print ' field attribute',key,value
attributedict[key[len(attributemarker):]] = value
ET.SubElement(xmlrecord, field_def[ID],attributedict).text=noderecord[field_def[ID]] #add xml element to xml record
for key in attributedict.keys(): #remove used fields
del noderecord[attributemarker+key]
del noderecord[field_def[ID]] #remove xml entity tag
return xmlrecord
def _initwrite(self):
botsglobal.logger.debug(u'Start writing to file "%s".',self.ta_info['filename'])
self._outstream = botslib.opendata(self.ta_info['filename'],"wb")
class xmlnocheck(xml):
def normalisetree(self,node):
pass
def _node2xmlfields(self,noderecord):
''' fields in a node are written to xml fields; output is sorted according to grammar
'''
if 'BOTSID' not in noderecord:
raise botslib.OutMessageError(_(u'No field "BOTSID" in xml-output in: "$record"'),record=noderecord)
#first generate the xml-'record'
attributedict = {}
recordtag = noderecord['BOTSID']
attributemarker = recordtag + self.ta_info['attributemarker']
for key,value in noderecord.items(): #find the attributes for the xml-record, put these in attributedict
if key.startswith(attributemarker):
attributedict[key[len(attributemarker):]] = value
xmlrecord = ET.Element(recordtag,attributedict) #make the xml ET node
if 'BOTSCONTENT' in noderecord:
xmlrecord.text = noderecord['BOTSCONTENT']
del noderecord['BOTSCONTENT']
for key in attributedict.keys(): #remove used fields
del noderecord[attributemarker+key]
del noderecord['BOTSID'] #remove 'record' tag
#generate xml-'fields' in xml-'record'; not sorted
noderecordcopy = noderecord.copy()
for key,value in noderecordcopy.items():
if key not in noderecord or self.ta_info['attributemarker'] in key: #if field not in outmessage: skip
continue
attributedict = {}
attributemarker = key + self.ta_info['attributemarker']
for key2,value2 in noderecord.items():
if key2.startswith(attributemarker):
attributedict[key2[len(attributemarker):]] = value2
ET.SubElement(xmlrecord, key,attributedict).text=value #add xml element to xml record
for key2 in attributedict.keys(): #remove used fields
del noderecord[attributemarker+key2]
del noderecord[key] #remove xml entity tag
return xmlrecord
class json(Outmessage):
def _initwrite(self):
super(json,self)._initwrite()
if self.multiplewrite:
self._outstream.write(u'[')
def _write(self,node):
''' convert node tree to appropriate python object.
python objects are written to json by simplejson.
'''
if self.nrmessagewritten:
self._outstream.write(u',')
jsonobject = {node.record['BOTSID']:self._node2json(node)}
if self.ta_info['indented']:
indent=2
else:
indent=None
simplejson.dump(jsonobject, self._outstream, skipkeys=False, ensure_ascii=False, check_circular=False, indent=indent)
def _closewrite(self):
if self.multiplewrite:
self._outstream.write(u']')
super(json,self)._closewrite()
def _node2json(self,node):
''' recursive method.
'''
#newjsonobject is the json object assembled in the function.
newjsonobject = node.record.copy() #init newjsonobject with record fields from node
for childnode in node.children: #fill newjsonobject with the records from childnodes.
key=childnode.record['BOTSID']
if key in newjsonobject:
newjsonobject[key].append(self._node2json(childnode))
else:
newjsonobject[key]=[self._node2json(childnode)]
del newjsonobject['BOTSID']
return newjsonobject
def _node2jsonold(self,node):
''' recursive method.
'''
newdict = node.record.copy()
if node.children: #if this node has records in it.
sortedchildren={} #empty dict
for childnode in node.children:
botsid=childnode.record['BOTSID']
if botsid in sortedchildren:
sortedchildren[botsid].append(self._node2json(childnode))
else:
sortedchildren[botsid]=[self._node2json(childnode)]
for key,value in sortedchildren.items():
if len(value)==1:
newdict[key]=value[0]
else:
newdict[key]=value
del newdict['BOTSID']
return newdict
class jsonnocheck(json):
def normalisetree(self,node):
pass
class template(Outmessage):
''' uses Kid library for templating.'''
class TemplateData(object):
pass
def __init__(self,ta_info):
self.data = template.TemplateData() #self.data is used by mapping script as container for content
super(template,self).__init__(ta_info)
def writeall(self):
''' Very different writeall:
there is no tree of nodes; there is no grammar.structure/recorddefs; kid opens file by itself.
'''
try:
import kid
except:
txt=botslib.txtexc()
raise ImportError(_(u'Dependency failure: editype "template" requires python library "kid". Error:\n%s'%txt))
#for template-grammar: only syntax is used. Section 'syntax' has to have 'template'
self.outmessagegrammarread(self.ta_info['editype'],self.ta_info['messagetype'])
templatefile = botslib.abspath(u'templates',self.ta_info['template'])
try:
botsglobal.logger.debug(u'Start writing to file "%s".',self.ta_info['filename'])
ediprint = kid.Template(file=templatefile, data=self.data)
except:
txt=botslib.txtexc()
raise botslib.OutMessageError(_(u'While templating "$editype.$messagetype", error:\n$txt'),editype=self.ta_info['editype'],messagetype=self.ta_info['messagetype'],txt=txt)
try:
f = botslib.opendata(self.ta_info['filename'],'wb')
ediprint.write(f,
#~ ediprint.write(botslib.abspathdata(self.ta_info['filename']),
encoding=self.ta_info['charset'],
output=self.ta_info['output'], #output is specific parameter for class; init from grammar.syntax
fragment=self.ta_info['merge'])
except:
txt=botslib.txtexc()
raise botslib.OutMessageError(_(u'While templating "$editype.$messagetype", error:\n$txt'),editype=self.ta_info['editype'],messagetype=self.ta_info['messagetype'],txt=txt)
botsglobal.logger.debug(_(u'End writing to file "%s".'),self.ta_info['filename'])
class templatehtml(Outmessage):
''' uses Genshi library for templating. Genshi is very similar to Kid, and is the fork/follow-up of Kid.
Kid is not being deveolped further; in time Kid will not be in repositories etc.
Templates for Genshi are like Kid templates. Changes:
- other namespace: xmlns:py="http://genshi.edgewall.org/" instead of xmlns:py="http://purl.org/kid/ns#"
- enveloping is different: <xi:include href="${message}" /> instead of <div py:replace="document(message)"/>
'''
class TemplateData(object):
pass
def __init__(self,ta_info):
self.data = template.TemplateData() #self.data is used by mapping script as container for content
super(templatehtml,self).__init__(ta_info)
def writeall(self):
''' Very different writeall:
there is no tree of nodes; there is no grammar.structure/recorddefs; kid opens file by itself.
'''
try:
from genshi.template import TemplateLoader
except:
txt=botslib.txtexc()
raise ImportError(_(u'Dependency failure: editype "template" requires python library "genshi". Error:\n%s'%txt))
#for template-grammar: only syntax is used. Section 'syntax' has to have 'template'
self.outmessagegrammarread(self.ta_info['editype'],self.ta_info['messagetype'])
templatefile = botslib.abspath(u'templateshtml',self.ta_info['template'])
try:
botsglobal.logger.debug(u'Start writing to file "%s".',self.ta_info['filename'])
loader = TemplateLoader(auto_reload=False)
tmpl = loader.load(templatefile)
except:
txt=botslib.txtexc()
raise botslib.OutMessageError(_(u'While templating "$editype.$messagetype", error:\n$txt'),editype=self.ta_info['editype'],messagetype=self.ta_info['messagetype'],txt=txt)
try:
f = botslib.opendata(self.ta_info['filename'],'wb')
stream = tmpl.generate(data=self.data)
stream.render(method='xhtml',encoding=self.ta_info['charset'],out=f)
except:
txt=botslib.txtexc()
raise botslib.OutMessageError(_(u'While templating "$editype.$messagetype", error:\n$txt'),editype=self.ta_info['editype'],messagetype=self.ta_info['messagetype'],txt=txt)
botsglobal.logger.debug(_(u'End writing to file "%s".'),self.ta_info['filename'])
class database(jsonnocheck):
pass
class db(Outmessage):
''' out.root is pickled, and saved.
'''
def __init__(self,ta_info):
super(db,self).__init__(ta_info)
self.root = None #make root None; root is not a Node-object anyway; None can easy be tested when writing.
def writeall(self):
if self.root is None:
raise botslib.OutMessageError(_(u'No outgoing message')) #then there is nothing to write...
botsglobal.logger.debug(u'Start writing to file "%s".',self.ta_info['filename'])
self._outstream = botslib.opendata(self.ta_info['filename'],'wb')
db_object = pickle.dump(self.root,self._outstream,2)
self._outstream.close()
botsglobal.logger.debug(u'End writing to file "%s".',self.ta_info['filename'])
self.ta_info['envelope'] = 'db' #use right enveloping for db: no coping etc, use same file.
class raw(Outmessage):
''' out.root is just saved.
'''
def __init__(self,ta_info):
super(raw,self).__init__(ta_info)
self.root = None #make root None; root is not a Node-object anyway; None can easy be tested when writing.
def writeall(self):
if self.root is None:
raise botslib.OutMessageError(_(u'No outgoing message')) #then there is nothing to write...
botsglobal.logger.debug(u'Start writing to file "%s".',self.ta_info['filename'])
self._outstream = botslib.opendata(self.ta_info['filename'],'wb')
self._outstream.write(self.root)
self._outstream.close()
botsglobal.logger.debug(u'End writing to file "%s".',self.ta_info['filename'])
self.ta_info['envelope'] = 'raw' #use right enveloping for raw: no coping etc, use same file.
| Python |
import os
import glob
import time
import datetime
import stat
import shutil
from django.utils.translation import ugettext as _
#bots modules
import botslib
import botsglobal
from botsconfig import *
def cleanup():
''' public function, does all cleanup of the database and file system.'''
try:
_cleanupsession()
_cleandatafile()
_cleanarchive()
_cleanpersist()
_cleantransactions()
_cleanprocessnothingreceived()
except:
botsglobal.logger.exception(u'Cleanup error.')
def _cleanupsession():
''' delete all expired sessions. Bots-engine starts up much more often than web-server.'''
vanaf = datetime.datetime.today()
botslib.change('''DELETE FROM django_session WHERE expire_date < %(vanaf)s''', {'vanaf':vanaf})
def _cleanarchive():
''' delete all archive directories older than maxdaysarchive days.'''
vanaf = (datetime.date.today()-datetime.timedelta(days=botsglobal.ini.getint('settings','maxdaysarchive',180))).strftime('%Y%m%d')
for row in botslib.query('''SELECT archivepath FROM channel '''):
if row['archivepath']:
vanafdir = botslib.join(row['archivepath'],vanaf)
for dir in glob.glob(botslib.join(row['archivepath'],'*')):
if dir < vanafdir:
shutil.rmtree(dir,ignore_errors=True)
def _cleandatafile():
''' delete all data files older than xx days.'''
vanaf = time.time() - (botsglobal.ini.getint('settings','maxdays',30) * 3600 * 24)
frompath = botslib.join(botsglobal.ini.get('directories','data','botssys/data'),'*')
for filename in glob.glob(frompath):
statinfo = os.stat(filename)
if not stat.S_ISDIR(statinfo.st_mode):
try:
os.remove(filename) #remove files - should be no files in root of data dir
except:
botsglobal.logger.exception(_(u'Cleanup could not remove file'))
elif statinfo.st_mtime > vanaf :
continue #directory is newer than maxdays, which is also true for the data files in it. Skip it.
else: #check files in dir and remove all older than maxdays
frompath2 = botslib.join(filename,'*')
emptydir=True #track check if directory is empty after loop (should directory itself be deleted/)
for filename2 in glob.glob(frompath2):
statinfo2 = os.stat(filename2)
if statinfo2.st_mtime > vanaf or stat.S_ISDIR(statinfo2.st_mode): #check files in dir and remove all older than maxdays
emptydir = False
else:
try:
os.remove(filename2)
except:
botsglobal.logger.exception(_(u'Cleanup could not remove file'))
if emptydir:
try:
os.rmdir(filename)
except:
botsglobal.logger.exception(_(u'Cleanup could not remove directory'))
def _cleanpersist():
'''delete all persist older than xx days.'''
vanaf = datetime.datetime.today() - datetime.timedelta(days=botsglobal.ini.getint('settings','maxdayspersist',30))
botslib.change('''DELETE FROM persist WHERE ts < %(vanaf)s''',{'vanaf':vanaf})
def _cleantransactions():
''' delete records from report, filereport and ta.
best indexes are on idta/reportidta; this should go fast.
'''
vanaf = datetime.datetime.today() - datetime.timedelta(days=botsglobal.ini.getint('settings','maxdays',30))
for row in botslib.query('''SELECT max(idta) as max FROM report WHERE ts < %(vanaf)s''',{'vanaf':vanaf}):
maxidta = row['max']
break
else: #if there is no maxidta to delete, do nothing
return
botslib.change('''DELETE FROM report WHERE idta < %(maxidta)s''',{'maxidta':maxidta})
botslib.change('''DELETE FROM filereport WHERE reportidta < %(maxidta)s''',{'maxidta':maxidta})
botslib.change('''DELETE FROM ta WHERE idta < %(maxidta)s''',{'maxidta':maxidta})
#the most recent run that is older than maxdays is kept (using < instead of <=).
#Reason: when deleting in ta this would leave the ta-records of the most recent run older than maxdays (except the first ta-record).
#this will not lead to problems.
def _cleanprocessnothingreceived():
''' delete all --new runs that received no files; including all process under the run
processes are organised as trees, so recursive.
'''
def core(idta):
#select db-ta's referring to this db-ta
for row in botslib.query('''SELECT idta
FROM ta
WHERE idta > %(idta)s
AND script=%(idta)s''',
{'idta':idta}):
core(row['idta'])
ta=botslib.OldTransaction(idta)
ta.delete()
return
#select root-processes older than hoursnotrefferedarekept
vanaf = datetime.datetime.today() - datetime.timedelta(hours=botsglobal.ini.getint('settings','hoursrunwithoutresultiskept',1))
for row in botslib.query('''SELECT idta
FROM report
WHERE type = 'new'
AND lastreceived=0
AND ts < %(vanaf)s''',
{'vanaf':vanaf}):
core(row['idta'])
#delete report
botslib.change('''DELETE FROM report WHERE idta=%(idta)s ''',{'idta':row['idta']})
| Python |
#Globals used by Bots
incommunicate = False #used to set all incommunication off
db = None #db-object
ini = None #ini-file-object that is read (bots.ini)
routeid = '' #current route. This is used to set routeid for Processes.
preprocessnumber = 0 #different preprocessnumbers are needed for different preprocessing.
version = '2.1.0' #bots version
minta4query = 0 #used in retry; this determines which ta's are queried in a route
######################################
| Python |
import copy
from django.utils.translation import ugettext as _
import botslib
import botsglobal
from botsconfig import *
def grammarread(editype,grammarname):
''' dispatch function for class Grammar or subclass
read whole grammar
'''
try:
classtocall = globals()[editype]
except KeyError:
raise botslib.GrammarError(_(u'Read grammar for editype "$editype" messagetype "$messagetype", but editype is unknown.'), editype=editype, messagetype=grammarname)
terug = classtocall('grammars',editype,grammarname)
terug.initsyntax(includedefault=True)
terug.initrestofgrammar()
return terug
def syntaxread(soortpythonfile,editype,grammarname):
''' dispatch function for class Grammar or subclass
read only grammar
'''
try:
classtocall = globals()[editype]
except KeyError:
raise botslib.GrammarError(_(u'Read grammar for type "$soort" editype "$editype" messagetype "$messagetype", but editype is unknown.'), soort=soortpythonfile,editype=editype, messagetype=grammarname)
terug = classtocall(soortpythonfile,editype,grammarname)
terug.initsyntax(includedefault=False)
return terug
class Grammar(object):
''' Class for translation grammar. The grammar is used in reading or writing an edi file.
Description of the grammar file: see user manual.
The grammar is read from the grammar file.
Grammar file has several grammar parts , eg 'structure'and 'recorddefs'.
every grammar part is in a module is either the grammar part itself or a import from another module.
every module is read once, (default python import-machinery).
The information in a grammar is checked and manipulated.
structure of self.grammar:
is a list of dict
attributes of dict: see header.py
- ID record id
- MIN min #occurences record or group
- MAX max #occurences record of group
- COUNT added after read
- MPATH mpath of record (only record-ids). added after read
- FIELDS tuple of the fields in record. Added ather read from separate record.py-file
- LEVEL child-records
structure of fields:
fields is tuple of (field or subfield)
field is tuple of (ID, MANDATORY, LENGTH, FORMAT)
subfield is tuple of (ID, MANDATORY, tuple of fields)
if a structure or recorddef has been read, Bots remembers this and skip most of the checks.
'''
_checkstructurerequired=True
def __init__(self,soortpythonfile,editype,grammarname):
self.module,self.grammarname = botslib.botsimport(soortpythonfile,editype + '.' + grammarname)
def initsyntax(self,includedefault):
''' Update default syntax from class with syntax read from grammar. '''
if includedefault:
self.syntax = copy.deepcopy(self.__class__.defaultsyntax) #copy syntax from class data
else:
self.syntax = {}
try:
syntaxfromgrammar = getattr(self.module, 'syntax')
except AttributeError:
pass #there is no syntax in the grammar, is OK.
else:
if not isinstance(syntaxfromgrammar,dict):
raise botslib.GrammarError(_(u'Grammar "$grammar": syntax is not a dict{}.'),grammar=self.grammarname)
self.syntax.update(syntaxfromgrammar)
def initrestofgrammar(self):
try:
self.nextmessage = getattr(self.module, 'nextmessage')
except AttributeError: #if grammarpart does not exist set to None; test required grammarpart elsewhere
self.nextmessage = None
try:
self.nextmessage2 = getattr(self.module, 'nextmessage2')
if self.nextmessage is None:
raise botslib.GrammarError(_(u'Grammar "$grammar": if nextmessage2: nextmessage has to be used.'),grammar=self.grammarname)
except AttributeError: #if grammarpart does not exist set to None; test required grammarpart elsewhere
self.nextmessage2 = None
try:
self.nextmessageblock = getattr(self.module, 'nextmessageblock')
if self.nextmessage:
raise botslib.GrammarError(_(u'Grammar "$grammar": nextmessageblock and nextmessage not both allowed.'),grammar=self.grammarname)
except AttributeError: #if grammarpart does not exist set to None; test required grammarpart elsewhere
self.nextmessageblock = None
if self._checkstructurerequired:
try:
self._dostructure()
except AttributeError: #if grammarpart does not exist set to None; test required grammarpart elsewhere
raise botslib.GrammarError(_(u'Grammar "$grammar": no structure, is required.'),grammar=self.grammarname)
except:
self.structurefromgrammar[0]['error'] = True #mark the structure as having errors
raise
try:
self._dorecorddefs()
except:
self.recorddefs['BOTS_1$@#%_error'] = True #mark structure has been read with errors
raise
else:
self.recorddefs['BOTS_1$@#%_error'] = False #mark structure has been read and checked
self.structure = copy.deepcopy(self.structurefromgrammar) #(deep)copy structure for use in translation (in translation values are changed, so use a copy)
self._checkbotscollision(self.structure)
self._linkrecorddefs2structure(self.structure)
def _dorecorddefs(self):
''' 1. check the recorddefinitions for validity.
2. adapt in field-records: normalise length lists, set bool ISFIELD, etc
'''
try:
self.recorddefs = getattr(self.module, 'recorddefs')
except AttributeError:
raise botslib.GrammarError(_(u'Grammar "$grammar": no recorddefs.'),grammar=self.grammarname)
if not isinstance(self.recorddefs,dict):
raise botslib.GrammarError(_(u'Grammar "$grammar": recorddefs is not a dict{}.'),grammar=self.grammarname)
#check if grammar is read & checked earlier in this run. If so, we can skip all checks.
if 'BOTS_1$@#%_error' in self.recorddefs: #if checked before
if self.recorddefs['BOTS_1$@#%_error']: #if grammar had errors
raise botslib.GrammarError(_(u'Grammar "$grammar" has error that is already reported in this run.'),grammar=self.grammarname)
return #no error, skip checks
for recordID ,fields in self.recorddefs.iteritems():
if not isinstance(recordID,basestring):
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record": is not a string.'),grammar=self.grammarname,record=recordID)
if not recordID:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record": recordID with empty string.'),grammar=self.grammarname,record=recordID)
if not isinstance(fields,list):
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record": no correct fields found.'),grammar=self.grammarname,record=recordID)
if isinstance(self,(xml,json)):
if len (fields) < 1:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record": too few fields.'),grammar=self.grammarname,record=recordID)
else:
if len (fields) < 2:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record": too few fields.'),grammar=self.grammarname,record=recordID)
hasBOTSID = False #to check if BOTSID is present
fieldnamelist = [] #to check for double fieldnames
for field in fields:
self._checkfield(field,recordID)
if not field[ISFIELD]: # if composite
for sfield in field[SUBFIELDS]:
self._checkfield(sfield,recordID)
if sfield[ID] in fieldnamelist:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record": field "$field" appears twice. Field names should be unique within a record.'),grammar=self.grammarname,record=recordID,field=sfield[ID])
fieldnamelist.append(sfield[ID])
else:
if field[ID] == 'BOTSID':
hasBOTSID = True
if field[ID] in fieldnamelist:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record": field "$field" appears twice. Field names should be unique within a record.'),grammar=self.grammarname,record=recordID,field=field[ID])
fieldnamelist.append(field[ID])
if not hasBOTSID: #there is no field 'BOTSID' in record
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record": no field BOTSID.'),grammar=self.grammarname,record=recordID)
if self.syntax['noBOTSID'] and len(self.recorddefs) != 1:
raise botslib.GrammarError(_(u'Grammar "$grammar": if syntax["noBOTSID"]: there can be only one record in recorddefs.'),grammar=self.grammarname)
if self.nextmessageblock is not None and len(self.recorddefs) != 1:
raise botslib.GrammarError(_(u'Grammar "$grammar": if nextmessageblock: there can be only one record in recorddefs.'),grammar=self.grammarname)
def _checkfield(self,field,recordID):
#'normalise' field: make list equal length
if len(field) == 3: # that is: composite
field +=[None,False,None,None,'A']
elif len(field) == 4: # that is: field (not a composite)
field +=[True,0,0,'A']
elif len(field) == 8: # this happens when there are errors in a table and table is read again
raise botslib.GrammarError(_(u'Grammar "$grammar": error in grammar; error is already reported in this run.'),grammar=self.grammarname)
else:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": list has invalid number of arguments.') ,grammar=self.grammarname,record=recordID,field=field[ID])
if not isinstance(field[ID],basestring) or not field[ID]:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": fieldID has to be a string.'),grammar=self.grammarname,record=recordID,field=field[ID])
if not isinstance(field[MANDATORY],basestring):
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": mandatory/conditional has to be a string.'),grammar=self.grammarname,record=recordID,field=field[ID])
if not field[MANDATORY] or field[MANDATORY] not in ['M','C']:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": mandatory/conditional must be "M" or "C".'),grammar=self.grammarname,record=recordID,field=field[ID])
if field[ISFIELD]: # that is: field, and not a composite
#get MINLENGTH (from tuple or if fixed
if isinstance(field[LENGTH],tuple):
if not isinstance(field[LENGTH][0],(int,float)):
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": min length "$min" has to be a number.'),grammar=self.grammarname,record=recordID,field=field[ID],min=field[LENGTH])
if not isinstance(field[LENGTH][1],(int,float)):
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": max length "$max" has to be a number.'),grammar=self.grammarname,record=recordID,field=field[ID],max=field[LENGTH])
if field[LENGTH][0] > field[LENGTH][1]:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": min length "$min" must be > max length "$max".'),grammar=self.grammarname,record=recordID,field=field[ID],min=field[LENGTH][0],max=field[LENGTH][1])
field[MINLENGTH]=field[LENGTH][0]
field[LENGTH]=field[LENGTH][1]
elif isinstance(field[LENGTH],(int,float)):
if isinstance(self,fixed):
field[MINLENGTH]=field[LENGTH]
else:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": length "$len" has to be number or (min,max).'),grammar=self.grammarname,record=recordID,field=field[ID],len=field[LENGTH])
if field[LENGTH] < 1:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": length "$len" has to be at least 1.'),grammar=self.grammarname,record=recordID,field=field[ID],len=field[LENGTH])
if field[MINLENGTH] < 0:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": minlength "$len" has to be at least 0.'),grammar=self.grammarname,record=recordID,field=field[ID],len=field[LENGTH])
#format
if not isinstance(field[FORMAT],basestring):
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": format "$format" has to be a string.'),grammar=self.grammarname,record=recordID,field=field[ID],format=field[FORMAT])
self._manipulatefieldformat(field,recordID)
if field[BFORMAT] in ['N','I','R']:
if isinstance(field[LENGTH],float):
field[DECIMALS] = int( round((field[LENGTH]-int(field[LENGTH]))*10) ) #fill DECIMALS
field[LENGTH] = int( round(field[LENGTH]))
if field[DECIMALS] >= field[LENGTH]:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": field length "$len" has to be greater that nr of decimals "$decimals".'),grammar=self.grammarname,record=recordID,field=field[ID],len=field[LENGTH],decimals=field[DECIMALS])
if isinstance(field[MINLENGTH],float):
field[MINLENGTH] = int( round(field[MINLENGTH]))
else: #if format 'R', A, D, T
if isinstance(field[LENGTH],float):
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": if format "$format", no length "$len".'),grammar=self.grammarname,record=recordID,field=field[ID],format=field[FORMAT],len=field[LENGTH])
if isinstance(field[MINLENGTH],float):
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": if format "$format", no minlength "$len".'),grammar=self.grammarname,record=recordID,field=field[ID],format=field[FORMAT],len=field[MINLENGTH])
else: #check composite
if not isinstance(field[SUBFIELDS],list):
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": is a composite field, has to have subfields.'),grammar=self.grammarname,record=recordID,field=field[ID])
if len(field[SUBFIELDS]) < 2:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field" has < 2 sfields.'),grammar=self.grammarname,record=recordID,field=field[ID])
def _linkrecorddefs2structure(self,structure):
''' recursive
for each record in structure: add the pointer to the right recorddefinition.
'''
for i in structure:
try:
i[FIELDS] = self.recorddefs[i[ID]]
except KeyError:
raise botslib.GrammarError(_(u'Grammar "$grammar": in recorddef no record "$record".'),grammar=self.grammarname,record=i[ID])
if LEVEL in i:
self._linkrecorddefs2structure(i[LEVEL])
def _dostructure(self):
''' 1. check the structure for validity.
2. adapt in structure: Add keys: mpath, count
3. remember that structure is checked and adapted (so when grammar is read again, no checking/adapt needed)
'''
self.structurefromgrammar = getattr(self.module, 'structure')
if len(self.structurefromgrammar) != 1: #every structure has only 1 root!!
raise botslib.GrammarError(_(u'Grammar "$grammar", in structure: only one root record allowed.'),grammar=self.grammarname)
#check if structure is read & checked earlier in this run. If so, we can skip all checks.
if 'error' in self.structurefromgrammar[0]:
pass # grammar has been read before, but there are errors. Do nothing here, same errors will be raised again.
elif MPATH in self.structurefromgrammar[0]:
return # grammar has been red before, with no errors. Do no checks.
self._checkstructure(self.structurefromgrammar,[])
if self.syntax['checkcollision']:
self._checkbackcollision(self.structurefromgrammar)
self._checknestedcollision(self.structurefromgrammar)
def _checkstructure(self,structure,mpath):
''' Recursive
1. Check structure.
2. Add keys: mpath, count
'''
if not isinstance(structure,list):
raise botslib.GrammarError(_(u'Grammar "$grammar", in structure, at "$mpath": not a list.'),grammar=self.grammarname,mpath=mpath)
for i in structure:
if not isinstance(i,dict):
raise botslib.GrammarError(_(u'Grammar "$grammar", in structure, at "$mpath": record should be a dict: "$record".'),grammar=self.grammarname,mpath=mpath,record=i)
if ID not in i:
raise botslib.GrammarError(_(u'Grammar "$grammar", in structure, at "$mpath": record without ID: "$record".'),grammar=self.grammarname,mpath=mpath,record=i)
if not isinstance(i[ID],basestring):
raise botslib.GrammarError(_(u'Grammar "$grammar", in structure, at "$mpath": recordID of record is not a string: "$record".'),grammar=self.grammarname,mpath=mpath,record=i)
if not i[ID]:
raise botslib.GrammarError(_(u'Grammar "$grammar", in structure, at "$mpath": recordID of record is empty: "$record".'),grammar=self.grammarname,mpath=mpath,record=i)
if MIN not in i:
raise botslib.GrammarError(_(u'Grammar "$grammar", in structure, at "$mpath": record without MIN: "$record".'),grammar=self.grammarname,mpath=mpath,record=i)
if MAX not in i:
raise botslib.GrammarError(_(u'Grammar "$grammar", in structure, at "$mpath": record without MAX: "$record".'),grammar=self.grammarname,mpath=mpath,record=i)
if not isinstance(i[MIN],int):
raise botslib.GrammarError(_(u'Grammar "$grammar", in structure, at "$mpath": record where MIN is not whole number: "$record".'),grammar=self.grammarname,mpath=mpath,record=i)
if not isinstance(i[MAX],int):
raise botslib.GrammarError(_(u'Grammar "$grammar", in structure, at "$mpath": record where MAX is not whole number: "$record".'),grammar=self.grammarname,mpath=mpath,record=i)
if i[MIN] > i[MAX]:
raise botslib.GrammarError(_(u'Grammar "$grammar", in structure, at "$mpath": record where MIN > MAX: "$record".'),grammar=self.grammarname,mpath=mpath,record=str(i)[:100])
i[MPATH]=mpath+[[i[ID]]]
i[COUNT]=0
if LEVEL in i:
self._checkstructure(i[LEVEL],i[MPATH])
def _checkbackcollision(self,structure,collision=None):
''' Recursive.
Check if grammar has collision problem.
A message with collision problems is ambiguous.
'''
headerissave = False
if not collision:
collision=[]
for i in structure:
#~ print 'check back',i[MPATH], 'with',collision
if i[ID] in collision:
raise botslib.GrammarError(_(u'Grammar "$grammar", in structure: back-collision detected at record "$mpath".'),grammar=self.grammarname,mpath=i[MPATH])
if i[MIN]:
collision = []
headerissave = True
collision.append(i[ID])
if LEVEL in i:
returncollision,returnheaderissave = self._checkbackcollision(i[LEVEL],[i[ID]])
collision += returncollision
if returnheaderissave: #if one of segment(groups) is required, there is always a segment after the header segment; so remove header from nowcollision:
collision.remove(i[ID])
return collision,headerissave #collision is used to update on higher level; cleared indicates the header segment can not collide anymore
def _checkbotscollision(self,structure):
''' Recursive.
Within one level: if twice the same tag: use BOTSIDnr.
'''
collision={}
for i in structure:
if i[ID] in collision:
#~ raise botslib.GrammarError(_(u'Grammar "$grammar", in structure: bots-collision detected at record "$mpath".'),grammar=self.grammarname,mpath=i[MPATH])
i[BOTSIDnr] = str(collision[i[ID]] + 1)
collision[i[ID]] = collision[i[ID]] + 1
else:
i[BOTSIDnr] = '1'
collision[i[ID]] = 1
if LEVEL in i:
self._checkbotscollision(i[LEVEL])
return
def _checknestedcollision(self,structure,collision=None):
''' Recursive.
Check if grammar has collision problem.
A message with collision problems is ambiguous.
'''
if not collision:
levelcollision = []
else:
levelcollision = collision[:]
for i in reversed(structure):
checkthissegment = True
if LEVEL in i:
checkthissegment = self._checknestedcollision(i[LEVEL],levelcollision + [i[ID]])
#~ print 'check nested',checkthissegment, i[MPATH], 'with',levelcollision
if checkthissegment and i[ID] in levelcollision:
raise botslib.GrammarError(_(u'Grammar "$grammar", in structure: nesting collision detected at record "$mpath".'),grammar=self.grammarname,mpath=i[MPATH])
if i[MIN]:
levelcollision = [] #enecessarympty uppercollision
return bool(levelcollision)
def display(self,structure,level=0):
''' Draw grammar, with indentation for levels.
For debugging.
'''
for i in structure:
print 'Record: ',i[MPATH],i
for field in i[FIELDS]:
print ' Field: ',field
if LEVEL in i:
self.display(i[LEVEL],level+1)
#bots interpretats the format from the grammer; left side are the allowed values; right side are the internal forams bots uses.
#the list directly below are the default values for the formats, subclasses can have their own list.
#this makes it possible to use x12-formats for x12, edifact-formats for edifact etc
formatconvert = {
'A':'A', #alfanumerical
'AN':'A', #alfanumerical
#~ 'AR':'A', #right aligned alfanumerical field, used in fixed records.
'D':'D', #date
'DT':'D', #date-time
'T':'T', #time
'TM':'T', #time
'N':'N', #numerical, fixed decimal. Fixed nr of decimals; if no decimal used: whole number, integer
#~ 'NL':'N', #numerical, fixed decimal. In fixed format: no preceding zeros, left aligned,
#~ 'NR':'N', #numerical, fixed decimal. In fixed format: preceding blancs, right aligned,
'R':'R', #numerical, any number of decimals; the decimal point is 'floating'
#~ 'RL':'R', #numerical, any number of decimals. fixed: no preceding zeros, left aligned
#~ 'RR':'R', #numerical, any number of decimals. fixed: preceding blancs, right aligned
'I':'I', #numercial, implicit decimal
}
def _manipulatefieldformat(self,field,recordID):
try:
field[BFORMAT] = self.formatconvert[field[FORMAT]]
except KeyError:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": format "$format" has to be one of "$keys".'),grammar=self.grammarname,record=recordID,field=field[ID],format=field[FORMAT],keys=self.formatconvert.keys())
#grammar subclasses. contain the defaultsyntax
class test(Grammar):
defaultsyntax = {
'checkcollision':True,
'noBOTSID':False,
}
class csv(Grammar):
defaultsyntax = {
'acceptspaceinnumfield':True, #only really used in fixed formats
'add_crlfafterrecord_sep':'',
'allow_lastrecordnotclosedproperly':False, #in csv sometimes the last record is no closed correctly. This is related to communciation over email. Beware: when using this, other checks will not be enforced!
'charset':'utf-8',
'checkcharsetin':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcharsetout':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcollision':True,
'checkunknownentities': True,
'contenttype':'text/csv',
'decimaal':'.',
'envelope':'',
'escape':"",
'field_sep':':',
'forcequote': 1, #(if quote_char is set) 0:no force: only quote if necessary:1:always force: 2:quote if alfanumeric
'lengthnumericbare':False,
'merge':True,
'noBOTSID':False,
'pass_all':True,
'quote_char':"'",
'record_sep':"\r\n",
'record_tag_sep':"", #Tradacoms/GTDI
'reserve':'',
'sfield_sep':'',
'skip_char':'',
'skip_firstline':False,
'stripfield_sep':False, #safe choice, as csv is no real standard
'triad':'',
'wrap_length':0, #for producing wrapped format, where a file consists of fixed length records ending with crr/lf. Often seen in mainframe, as400
}
class fixed(Grammar):
formatconvert = {
'A':'A', #alfanumerical
'AN':'A', #alfanumerical
'AR':'A', #right aligned alfanumerical field, used in fixed records.
'D':'D', #date
'DT':'D', #date-time
'T':'T', #time
'TM':'T', #time
'N':'N', #numerical, fixed decimal. Fixed nr of decimals; if no decimal used: whole number, integer
'NL':'N', #numerical, fixed decimal. In fixed format: no preceding zeros, left aligned,
'NR':'N', #numerical, fixed decimal. In fixed format: preceding blancs, right aligned,
'R':'R', #numerical, any number of decimals; the decimal point is 'floating'
'RL':'R', #numerical, any number of decimals. fixed: no preceding zeros, left aligned
'RR':'R', #numerical, any number of decimals. fixed: preceding blancs, right aligned
'I':'I', #numercial, implicit decimal
}
defaultsyntax = {
'acceptspaceinnumfield':True, #only really used in fixed formats
'add_crlfafterrecord_sep':'',
'charset':'us-ascii',
'checkcharsetin':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcharsetout':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcollision':True,
'checkfixedrecordtoolong':True,
'checkfixedrecordtooshort':False,
'checkunknownentities': True,
'contenttype':'text/plain',
'decimaal':'.',
'endrecordID':3,
'envelope':'',
'escape':'',
'field_sep':'',
'forcequote':0, #csv only
'lengthnumericbare':False,
'merge':True,
'noBOTSID':False,
'pass_all':False,
'quote_char':"",
'record_sep':"\r\n",
'record_tag_sep':"", #Tradacoms/GTDI
'reserve':'',
'sfield_sep':'',
'skip_char':'',
'startrecordID':0,
'stripfield_sep':False,
'triad':'',
'wrap_length':0, #for producing wrapped format, where a file consists of fixed length records ending with crr/lf. Often seen in mainframe, as400
}
class idoc(fixed):
defaultsyntax = {
'acceptspaceinnumfield':True, #only really used in fixed formats
'add_crlfafterrecord_sep':'',
'automaticcount':True,
'charset':'us-ascii',
'checkcharsetin':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcharsetout':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcollision':True,
'checkfixedrecordtoolong':False,
'checkfixedrecordtooshort':False,
'checkunknownentities': True,
'contenttype':'text/plain',
'decimaal':'.',
'endrecordID':10,
'envelope':'',
'escape':'',
'field_sep':'',
'forcequote':0, #csv only
'lengthnumericbare':False,
'merge':False,
'noBOTSID':False,
'pass_all':False,
'quote_char':"",
'record_sep':"\r\n",
'record_tag_sep':"", #Tradacoms/GTDI
'reserve':'',
'sfield_sep':'',
'skip_char':'',
'startrecordID':0,
'stripfield_sep':False,
'triad':'',
'wrap_length':0, #for producing wrapped format, where a file consists of fixed length records ending with crr/lf. Often seen in mainframe, as400
'MANDT':'0',
'DOCNUM':'0',
}
class xml(Grammar):
defaultsyntax = {
'add_crlfafterrecord_sep':'',
'acceptspaceinnumfield':True, #only really used in fixed formats
'attributemarker':'__',
'charset':'utf-8',
'checkcharsetin':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcharsetout':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcollision':False,
'checkunknownentities': True, #??changed later
'contenttype':'text/xml ',
'decimaal':'.',
'DOCTYPE':'', #doctype declaration to use in xml header. DOCTYPE = 'mydoctype SYSTEM "mydoctype.dtd"' will lead to: <!DOCTYPE mydoctype SYSTEM "mydoctype.dtd">
'envelope':'',
'extra_character_entity':{}, #additional character entities to resolve when parsing XML; mostly html character entities. Not in python 2.4. Example: {'euro':u'','nbsp':unichr(160),'apos':u'\u0027'}
'escape':'',
'field_sep':'',
'forcequote':0, #csv only
'indented':False, #False: xml output is one string (no cr/lf); True: xml output is indented/human readable
'lengthnumericbare':False,
'merge':False,
'noBOTSID':False,
'pass_all':False,
'processing_instructions': None, #to generate processing instruction in xml prolog. is a list, consisting of tuples, each tuple consists of type of instruction and text for instruction.
#Example: processing_instructions': [('xml-stylesheet' ,'href="mystylesheet.xsl" type="text/xml"'),('type-of-ppi' ,'attr1="value1" attr2="value2"')]
#leads to this output in xml-file: <?xml-stylesheet href="mystylesheet.xsl" type="text/xml"?><?type-of-ppi attr1="value1" attr2="value2"?>
'quote_char':"",
'record_sep':"",
'record_tag_sep':"", #Tradacoms/GTDI
'reserve':'',
'sfield_sep':'',
'skip_char':'',
'standalone':None, #as used in xml prolog; values: 'yes' , 'no' or None (not used)
'stripfield_sep':False,
'triad':'',
'version':'1.0', #as used in xml prolog
}
class xmlnocheck(xml):
_checkstructurerequired=False
defaultsyntax = {
'add_crlfafterrecord_sep':'',
'acceptspaceinnumfield':True, #only really used in fixed formats
'attributemarker':'__',
'charset':'utf-8',
'checkcharsetin':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcharsetout':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcollision':False,
'checkunknownentities': False,
'contenttype':'text/xml ',
'decimaal':'.',
'DOCTYPE':'', #doctype declaration to use in xml header. DOCTYPE = 'mydoctype SYSTEM "mydoctype.dtd"' will lead to: <!DOCTYPE mydoctype SYSTEM "mydoctype.dtd">
'envelope':'',
'escape':'',
'extra_character_entity':{}, #additional character entities to resolve when parsing XML; mostly html character entities. Not in python 2.4. Example: {'euro':u'','nbsp':unichr(160),'apos':u'\u0027'}
'field_sep':'',
'forcequote':0, #csv only
'indented':False, #False: xml output is one string (no cr/lf); True: xml output is indented/human readable
'lengthnumericbare':False,
'merge':False,
'noBOTSID':False,
'pass_all':False,
'processing_instructions': None, #to generate processing instruction in xml prolog. is a list, consisting of tuples, each tuple consists of type of instruction and text for instruction.
#Example: processing_instructions': [('xml-stylesheet' ,'href="mystylesheet.xsl" type="text/xml"'),('type-of-ppi' ,'attr1="value1" attr2="value2"')]
#leads to this output in xml-file: <?xml-stylesheet href="mystylesheet.xsl" type="text/xml"?><?type-of-ppi attr1="value1" attr2="value2"?>
'quote_char':"",
'record_sep':"",
'record_tag_sep':"", #Tradacoms/GTDI
'reserve':'',
'sfield_sep':'',
'skip_char':'',
'standalone':None, #as used in xml prolog; values: 'yes' , 'no' or None (not used)
'stripfield_sep':False,
'triad':'',
'version':'1.0', #as used in xml prolog
}
class template(Grammar):
_checkstructurerequired=False
defaultsyntax = { \
'add_crlfafterrecord_sep':'',
'charset':'utf-8',
'checkcharsetin':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcharsetout':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcollision':False,
'contenttype':'text/xml',
'checkunknownentities': True,
'decimaal':'.',
'envelope':'template',
'envelope-template':'',
'escape':'',
'field_sep':'',
'forcequote':0, #csv only
'lengthnumericbare':False,
'merge':True,
'noBOTSID':False,
'output':'xhtml-strict',
'quote_char':"",
'pass_all':False,
'record_sep':"",
'record_tag_sep':"", #Tradacoms/GTDI
'reserve':'',
'sfield_sep':'',
'skip_char':'',
'stripfield_sep':False,
'triad':'',
}
class templatehtml(Grammar):
_checkstructurerequired=False
defaultsyntax = { \
'add_crlfafterrecord_sep':'',
'charset':'utf-8',
'checkcharsetin':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcharsetout':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcollision':False,
'contenttype':'text/xml',
'checkunknownentities': True,
'decimaal':'.',
'envelope':'templatehtml',
'envelope-template':'',
'escape':'',
'field_sep':'',
'forcequote':0, #csv only
'lengthnumericbare':False,
'merge':True,
'noBOTSID':False,
'output':'xhtml-strict',
'quote_char':"",
'pass_all':False,
'record_sep':"",
'record_tag_sep':"", #Tradacoms/GTDI
'reserve':'',
'sfield_sep':'',
'skip_char':'',
'stripfield_sep':False,
'triad':'',
}
class edifact(Grammar):
defaultsyntax = {
'add_crlfafterrecord_sep':'\r\n',
'acceptspaceinnumfield':True, #only really used in fixed formats
'charset':'UNOA',
'checkcharsetin':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcharsetout':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcollision':True,
'checkunknownentities': True,
'contenttype':'application/EDIFACT',
'decimaal':'.',
'envelope':'edifact',
'escape':'?',
'field_sep':'+',
'forcequote':0, #csv only
'forceUNA' : False,
'lengthnumericbare':True,
'merge':True,
'noBOTSID':False,
'pass_all':False,
'quote_char':'',
'record_sep':"'",
'record_tag_sep':"", #Tradacoms/GTDI
'reserve':'*',
'sfield_sep':':',
'skip_char':'\r\n',
'stripfield_sep':True,
'triad':'',
'version':'3',
'wrap_length':0, #for producing wrapped format, where a file consists of fixed length records ending with crr/lf. Often seen in mainframe, as400
'UNB.S002.0007':'14',
'UNB.S003.0007':'14',
'UNB.0026':'',
'UNB.0035':'0',
}
formatconvert = {
'A':'A',
'AN':'A',
'N':'R',
}
class x12(Grammar):
defaultsyntax = {
'add_crlfafterrecord_sep':'\r\n',
'acceptspaceinnumfield':True, #only really used in fixed formats
'charset':'us-ascii',
'checkcharsetin':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcharsetout':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcollision':True,
'checkunknownentities': True,
'contenttype':'application/X12',
'decimaal':'.',
'envelope':'x12',
'escape':'',
'field_sep':'*',
'forcequote':0, #csv only
'functionalgroup' : 'XX',
'lengthnumericbare':True,
'merge':True,
'noBOTSID':False,
'pass_all':False,
'quote_char':'',
'record_sep':"~",
'record_tag_sep':"", #Tradacoms/GTDI
'replacechar':'', #if separator found, replace by this character; if replacechar is an empty string: raise error
'reserve':'^',
'sfield_sep':'>', #advised '\'?
'skip_char':'\r\n',
'stripfield_sep':True,
'triad':'',
'version':'00403',
'wrap_length':0, #for producing wrapped format, where a file consists of fixed length records ending with crr/lf. Often seen in mainframe, as400
'ISA01':'00',
'ISA02':' ',
'ISA03':'00',
'ISA04':' ',
'ISA05':'01',
'ISA07':'01',
'ISA11':'U', #since ISA version 00403 this is the reserve/repetition separator. Bots does not use this anymore for ISA version >00403
'ISA14':'1',
'ISA15':'P',
'GS07':'X',
}
formatconvert = {
'AN':'A',
'DT':'D',
'TM':'T',
'N':'I',
'N0':'I',
'N1':'I',
'N2':'I',
'N3':'I',
'N4':'I',
'N5':'I',
'N6':'I',
'N7':'I',
'N8':'I',
'N9':'I',
'R':'R',
'B':'A',
'ID':'A',
}
def _manipulatefieldformat(self,field,recordID):
super(x12,self)._manipulatefieldformat(field,recordID)
if field[BFORMAT]=='I':
if field[FORMAT][1:]:
field[DECIMALS] = int(field[FORMAT][1])
else:
field[DECIMALS] = 0
class json(Grammar):
defaultsyntax = {
'add_crlfafterrecord_sep':'',
'acceptspaceinnumfield':True, #only really used in fixed formats
'charset':'utf-8',
'checkcharsetin':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcharsetout':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcollision':False,
'checkunknownentities': True, #??changed later
'contenttype':'text/xml ',
'decimaal':'.',
'defaultBOTSIDroot':'ROOT',
'envelope':'',
'escape':'',
'field_sep':'',
'forcequote':0, #csv only
'indented':False, #False: output is one string (no cr/lf); True: output is indented/human readable
'lengthnumericbare':False,
'merge':False,
'noBOTSID':False,
'pass_all':False,
'quote_char':"",
'record_sep':"",
'record_tag_sep':"", #Tradacoms/GTDI
'reserve':'',
'sfield_sep':'',
'skip_char':'',
'stripfield_sep':False,
'triad':'',
}
class jsonnocheck(json):
_checkstructurerequired=False
defaultsyntax = {
'add_crlfafterrecord_sep':'',
'acceptspaceinnumfield':True, #only really used in fixed formats
'charset':'utf-8',
'checkcharsetin':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcharsetout':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcollision':False,
'checkunknownentities': False,
'contenttype':'text/xml ',
'decimaal':'.',
'defaultBOTSIDroot':'ROOT',
'envelope':'',
'escape':'',
'field_sep':'',
'forcequote':0, #csv only
'indented':False, #False: output is one string (no cr/lf); True: output is indented/human readable
'lengthnumericbare':False,
'merge':False,
'noBOTSID':False,
'pass_all':False,
'quote_char':"",
'record_sep':"",
'record_tag_sep':"", #Tradacoms/GTDI
'reserve':'',
'sfield_sep':'',
'skip_char':'',
'stripfield_sep':False,
'triad':'',
}
class tradacoms(Grammar):
defaultsyntax = {
'add_crlfafterrecord_sep':'\n',
'acceptspaceinnumfield':True, #only really used in fixed formats
'charset':'us-ascii',
'checkcharsetin':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcharsetout':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcollision':True,
'checkunknownentities': True,
'contenttype':'application/text',
'decimaal':'.',
'envelope':'tradacoms',
'escape':'?',
'field_sep':'+',
'forcequote':0, #csv only
'indented':False, #False: output is one string (no cr/lf); True: output is indented/human readable
'lengthnumericbare':True,
'merge':False,
'noBOTSID':False,
'pass_all':False,
'quote_char':'',
'record_sep':"'",
'record_tag_sep':"=", #Tradacoms/GTDI
'reserve':'',
'sfield_sep':':',
'skip_char':'\r\n',
'stripfield_sep':True,
'triad':'',
'wrap_length':0, #for producing wrapped format, where a file consists of fixed length records ending with crr/lf. Often seen in mainframe, as400
'STX.STDS1':'ANA',
'STX.STDS2':'1',
'STX.FROM.02':'',
'STX.UNTO.02':'',
'STX.APRF':'',
'STX.PRCD':'',
}
formatconvert = {
'X':'A',
'9':'R',
'9V9':'I',
}
class database(jsonnocheck):
pass
| Python |
#!/usr/bin/env python
import sys
import os
import logging
from logging.handlers import TimedRotatingFileHandler
from django.core.handlers.wsgi import WSGIHandler
from django.utils.translation import ugettext as _
import cherrypy
from cherrypy import wsgiserver
import botslib
import botsglobal
import botsinit
def showusage():
usage = '''
This is "%(name)s", a part of Bots open source edi translator - http://bots.sourceforge.net.
The %(name)s is the web server for bots; the interface (bots-monitor) can be accessed in a browser, eg 'http://localhost:8080'.
Usage:
%(name)s -c<directory>
Options:
-c<directory> directory for configuration files (default: config).
'''%{'name':os.path.basename(sys.argv[0])}
print usage
sys.exit(0)
def start():
#NOTE bots is always on PYTHONPATH!!! - otherwise it will not start.
#***command line arguments**************************
configdir = 'config'
for arg in sys.argv[1:]:
if not arg:
continue
if arg.startswith('-c'):
configdir = arg[2:]
if not configdir:
print 'Configuration directory indicated, but no directory name.'
sys.exit(1)
elif arg in ["?", "/?"] or arg.startswith('-'):
showusage()
else:
showusage()
#***init general: find locating of bots, configfiles, init paths etc.***********************
botsinit.generalinit(configdir)
#***initialise logging. This logging only contains the logging from bots-webserver, not from cherrypy.
botsglobal.logger = logging.getLogger('bots-webserver')
botsglobal.logger.setLevel(logging.DEBUG)
h = TimedRotatingFileHandler(botslib.join(botsglobal.ini.get('directories','logging'),'webserver.log'), backupCount=10)
fileformat = logging.Formatter("%(asctime)s %(levelname)-8s: %(message)s",'%Y%m%d %H:%M:%S')
h.setFormatter(fileformat)
botsglobal.logger.addHandler(h)
#***init cherrypy as webserver*********************************************
#global configuration for cherrypy
cherrypy.config.update({'global': {'log.screen': False, 'server.environment': botsglobal.ini.get('webserver','environment','production')}})
#cherrypy handling of static files
conf = {'/': {'tools.staticdir.on' : True,'tools.staticdir.dir' : 'media' ,'tools.staticdir.root': botsglobal.ini.get('directories','botspath')}}
servestaticfiles = cherrypy.tree.mount(None, '/media', conf) #None: no cherrypy application (as this only serves static files)
#cherrypy handling of django
servedjango = WSGIHandler() #was: servedjango = AdminMediaHandler(WSGIHandler()) but django does not need the AdminMediaHandler in this setup. is much faster.
#cherrypy uses a dispatcher in order to handle the serving of static files and django.
dispatcher = wsgiserver.WSGIPathInfoDispatcher({'/': servedjango, '/media': servestaticfiles})
botswebserver = wsgiserver.CherryPyWSGIServer(bind_addr=('0.0.0.0', botsglobal.ini.getint('webserver','port',8080)), wsgi_app=dispatcher, server_name=botsglobal.ini.get('webserver','name','bots-webserver'))
botsglobal.logger.info(_(u'Bots web-server started.'))
#handle ssl: cherrypy < 3.2 always uses pyOpenssl. cherrypy >= 3.2 uses python buildin ssl (python >= 2.6 has buildin support for ssl).
ssl_certificate = botsglobal.ini.get('webserver','ssl_certificate',None)
ssl_private_key = botsglobal.ini.get('webserver','ssl_private_key',None)
if ssl_certificate and ssl_private_key:
if cherrypy.__version__ >= '3.2.0':
adapter_class = wsgiserver.get_ssl_adapter_class('builtin')
botswebserver.ssl_adapter = adapter_class(ssl_certificate,ssl_private_key)
else:
#but: pyOpenssl should be there!
botswebserver.ssl_certificate = ssl_certificate
botswebserver.ssl_private_key = ssl_private_key
botsglobal.logger.info(_(u'Bots web-server uses ssl (https).'))
else:
botsglobal.logger.info(_(u'Bots web-server uses plain http (no ssl).'))
#***start the cherrypy webserver.
try:
botswebserver.start()
except KeyboardInterrupt:
botswebserver.stop()
if __name__=='__main__':
start()
| Python |
#!/usr/bin/env python
''' This script starts bots-engine.'''
import sys
import os
import atexit
import traceback
import logging
import datetime
logging.raiseExceptions = 0 #if errors occur in writing to log: ignore error; this will lead to a missing log line.
#it is better to have a missing log line than an error in a translation....
from django.utils.translation import ugettext as _
#bots-modules
import botslib
import botsinit
import botsglobal
import router
import automaticmaintenance
import cleanup
from botsconfig import *
def showusage():
usage = '''
This is "%(name)s", a part of Bots open source edi translator - http://bots.sourceforge.net.
The %(name)s does the actual translations and communications; it's the workhorse. It does not have a fancy interface.
Usage:
%(name)s [run-options] [config-option] [routes]
Run-options (can be combined, except for crashrecovery):
--new receive new edi files (default: if no run-option given: run as new).
--retransmit resend and rereceive as indicated by user.
--retry retry previous errors.
--crashrecovery reruns the run where the crash occurred. (when database is locked).
--automaticretrycommunication - automatically retry outgoing communication.
--retrycommunication retry outgoing communication process errors as indicated by user.
--cleanup remove older data from database.
Config-option:
-c<directory> directory for configuration files (default: config).
Routes: list of routes to run. Default: all active routes (in the database)
'''%{'name':os.path.basename(sys.argv[0])}
print usage
def start():
#exit codes:
# 0: OK, no errors
# 1: (system) errors
# 2: bots ran OK, but there are errors/process errors in the run
# 3: Database is locked, but "maxruntime" has not been exceeded.
#********command line arguments**************************
commandspossible = ['--new','--retry','--retransmit','--cleanup','--crashrecovery','--retrycommunication','--automaticretrycommunication']
commandstorun = []
routestorun = [] #list with routes to run
configdir = 'config'
for arg in sys.argv[1:]:
if not arg:
continue
if arg.startswith('-c'):
configdir = arg[2:]
if not configdir:
print 'Configuration directory indicated, but no directory name.'
sys.exit(1)
elif arg in commandspossible:
commandstorun.append(arg)
elif arg in ["?", "/?"] or arg.startswith('-'):
showusage()
sys.exit(0)
else: #pick up names of routes to run
routestorun.append(arg)
if not commandstorun: #if no command on command line, use new (default)
commandstorun = ['--new']
#**************init general: find locating of bots, configfiles, init paths etc.****************
botsinit.generalinit(configdir)
#set current working directory to botspath
#~ old_current_directory = os.getcwdu()
os.chdir(botsglobal.ini.get('directories','botspath'))
#**************initialise logging******************************
try:
botsinit.initenginelogging()
except:
print _('Error in initialising logging system.')
traceback.print_exc()
sys.exit(1)
else:
atexit.register(logging.shutdown)
for key,value in botslib.botsinfo(): #log start info
botsglobal.logger.info(u'%s: "%s".',key,value)
#**************connect to database**********************************
try:
botsinit.connect()
except:
botsglobal.logger.exception(_(u'Could not connect to database. Database settings are in bots/config/settings.py.'))
sys.exit(1)
else:
botsglobal.logger.info(_(u'Connected to database.'))
atexit.register(botsglobal.db.close)
#initialise user exits for the whole bots-engine (this script file)
try:
userscript,scriptname = botslib.botsimport('routescripts','botsengine')
except ImportError:
userscript = scriptname = None
#**************handle database lock****************************************
#try to set a lock on the database; if this is not possible, the database is already locked. Either:
#1 another instance bots bots-engine is (still) running
#2 or bots-engine had a severe crash.
#What to do?
#first: check ts of database lock. If below a certain value (set in bots.ini) we assume an other instance is running. Exit quietly - no errors, no logging.
# else: Warn user, give advise on what to do. gather data: nr files in, errors.
#next: warn with report & logging. advise a crashrecovery.
if not botslib.set_database_lock():
if '--crashrecovery' in commandstorun: #user starts recovery operation; the databaselock is ignored; the databaselock is unlocked when routes have run.
commandstorun = ['--crashrecovery'] #is an exclusive option!
else:
#when scheduling bots it is possible that the last run is still running. Check if maxruntime has passed:
vanaf = datetime.datetime.today() - datetime.timedelta(minutes=botsglobal.ini.getint('settings','maxruntime',60))
for row in botslib.query('''SELECT ts FROM mutex WHERE ts < %(vanaf)s ''',{'vanaf':vanaf}):
warn = _(u'!Bots database is locked!\nBots-engine has ended in an unexpected way during the last run.\nThis happens, but is very very rare.\nPossible causes: bots-engine terminated by user, system crash, power-down, etc.\nA forced retry of the last run is advised; bots will (try to) repair the last run.')
botsglobal.logger.critical(warn)
botslib.sendbotserrorreport(_(u'[Bots severe error]Database is locked'),warn)
#add: count errors etc.
sys.exit(1)
else: #maxruntime has not passed. Exit silently, nothing reported
botsglobal.logger.info(_(u'Database is locked, but "maxruntime" has not been exceeded.'))
sys.exit(3)
else:
if '--crashrecovery' in commandstorun: #user starts recovery operation but there is no databaselock.
warn = _(u'User started a forced retry of the last run.\nOnly use this when the database is locked.\nThe database was not locked (database is OK).\nSo Bots has done nothing now.')
botsglobal.logger.error(warn)
botslib.sendbotserrorreport(_(u'[Bots Error Report] User started a forced retry of last run, but this was not needed'),warn)
botslib.remove_database_lock()
sys.exit(1)
#*************get list of routes to run****************************************
#~ raise Exception('locked database') #for testing database lock: abort, database will be locked
if routestorun:
botsglobal.logger.info(u'Run routes from command line: "%s".',str(routestorun))
else: # no routes from command line parameters: fetch all active routes from database
for row in botslib.query('''SELECT DISTINCT idroute
FROM routes
WHERE active=%(active)s
AND (notindefaultrun=%(notindefaultrun)s OR notindefaultrun IS NULL)
ORDER BY idroute ''',
{'active':True,'notindefaultrun':False}):
routestorun.append(row['idroute'])
botsglobal.logger.info(_(u'Run active routes from database: "%s".'),str(routestorun))
#routestorun is now either a list with routes from commandline, or the list of active routes for the routes table in the db.
#**************run the routes for retry, retransmit and new runs*************************************
try:
#commandstorun determines the type(s) of run
#routes to run is a listof the routes that are runs (for each command to run
#botsglobal.incommunicate is used to control if there is communication in; only 'new' incommunicates.
#botsglobal.minta4query controls which ta's are queried by the routes.
#stuff2evaluate controls what is evaluated in automatic maintenance.
errorinrun = 0 #detect if there has been some error. Only used for good exit() code
botsglobal.incommunicate = False
if '--crashrecovery' in commandstorun:
botsglobal.logger.info(_(u'Run crash recovery.'))
stuff2evaluate = botslib.set_minta4query_crashrecovery()
if stuff2evaluate:
router.routedispatcher(routestorun)
errorinrun += automaticmaintenance.evaluate('--crashrecovery',stuff2evaluate)
else:
botsglobal.logger.info(_(u'No retry of the last run - there was no last run.'))
if userscript and hasattr(userscript,'postcrashrecovery'):
botslib.runscript(userscript,scriptname,'postcrashrecovery',routestorun=routestorun)
if '--retrycommunication' in commandstorun:
botsglobal.logger.info(_(u'Run communication retry.'))
stuff2evaluate = router.routedispatcher(routestorun,'--retrycommunication')
if stuff2evaluate:
errorinrun += automaticmaintenance.evaluate('--retrycommunication',stuff2evaluate)
else:
botsglobal.logger.info(_(u'Run recommunicate: nothing to recommunicate.'))
if userscript and hasattr(userscript,'postretrycommunication'):
botslib.runscript(userscript,scriptname,'postretrycommunication',routestorun=routestorun)
if '--automaticretrycommunication' in commandstorun:
botsglobal.logger.info(_(u'Run automatic communication retry.'))
stuff2evaluate = router.routedispatcher(routestorun,'--automaticretrycommunication')
if stuff2evaluate:
errorinrun += automaticmaintenance.evaluate('--automaticretrycommunication',stuff2evaluate)
else:
botsglobal.logger.info(_(u'Run automatic recommunicate: nothing to recommunicate.'))
if userscript and hasattr(userscript,'postautomaticretrycommunication'):
botslib.runscript(userscript,scriptname,'postautomaticretrycommunication',routestorun=routestorun)
if '--retry' in commandstorun:
botsglobal.logger.info(u'Run retry.')
stuff2evaluate = router.routedispatcher(routestorun,'--retry')
if stuff2evaluate:
errorinrun += automaticmaintenance.evaluate('--retry',stuff2evaluate)
else:
botsglobal.logger.info(_(u'Run retry: nothing to retry.'))
if userscript and hasattr(userscript,'postretry'):
botslib.runscript(userscript,scriptname,'postretry',routestorun=routestorun)
if '--retransmit' in commandstorun:
botsglobal.logger.info(u'Run retransmit.')
stuff2evaluate = router.routedispatcher(routestorun,'--retransmit')
if stuff2evaluate:
errorinrun += automaticmaintenance.evaluate('--retransmit',stuff2evaluate)
else:
botsglobal.logger.info(_(u'Run retransmit: nothing to retransmit.'))
if userscript and hasattr(userscript,'postretransmit'):
botslib.runscript(userscript,scriptname,'postretransmit',routestorun=routestorun)
if '--new' in commandstorun:
botsglobal.logger.info('Run new.')
botsglobal.incommunicate = True
botsglobal.minta4query = 0 #meaning: reset. the actual value is set later (in routedispatcher)
stuff2evaluate = router.routedispatcher(routestorun)
errorinrun += automaticmaintenance.evaluate('--new',stuff2evaluate)
if userscript and hasattr(userscript,'postnewrun'):
botslib.runscript(userscript,scriptname,'postnewrun',routestorun=routestorun)
if '--cleanup' in commandstorun or botsglobal.ini.get('settings','whencleanup','always')=='always':
botsglobal.logger.debug(u'Do cleanup.')
cleanup.cleanup()
botslib.remove_database_lock()
except Exception,e:
botsglobal.logger.exception(_(u'Severe error in bots system:\n%s')%(e)) #of course this 'should' not happen.
sys.exit(1)
else:
if errorinrun:
sys.exit(2) #indicate: error(s) in run(s)
else:
sys.exit(0) #OK
if __name__=='__main__':
start()
| Python |
import sys
import os
import time
import shutil
import subprocess
import django
from django.utils.translation import ugettext as _
import forms
import models
import viewlib
import botslib
import pluglib
import botsglobal
import glob
from botsconfig import *
def server_error(request, template_name='500.html'):
""" the 500 error handler.
Templates: `500.html`
Context: None
"""
import traceback
exc_info = traceback.format_exc(None).decode('utf-8','ignore')
botsglobal.logger.info(_(u'Ran into server error: "%s"'),str(exc_info))
t = django.template.loader.get_template(template_name) # You need to create a 500.html template.
return django.http.HttpResponseServerError(t.render(django.template.Context({'exc_info':exc_info})))
def index(request,*kw,**kwargs):
return django.shortcuts.render_to_response('admin/base.html', {},context_instance=django.template.RequestContext(request))
def home(request,*kw,**kwargs):
return django.shortcuts.render_to_response('bots/about.html', {'botsinfo':botslib.botsinfo()},context_instance=django.template.RequestContext(request))
def reports(request,*kw,**kwargs):
#~ print 'reports received',kw,kwargs,request.POST,request.GET
if request.method == 'GET':
if 'select' in request.GET: #via menu, go to select form
formout = forms.SelectReports()
return viewlib.render(request,formout)
else: #via menu, go to view form
cleaned_data = {'page':1,'sortedby':'ts','sortedasc':False}
else: # request.method == 'POST'
if 'fromselect' in request.POST: #coming from select criteria screen
formin = forms.SelectReports(request.POST)
if not formin.is_valid():
return viewlib.render(request,formin)
else:
formin = forms.ViewReports(request.POST)
if not formin.is_valid():
return viewlib.render(request,formin)
if '2select' in request.POST: #coming from ViewIncoming, change the selection criteria, go to select form
formout = forms.SelectReports(formin.cleaned_data)
return viewlib.render(request,formout)
elif 'report2incoming' in request.POST: #coming from ViewIncoming, go to incoming
request.POST = viewlib.preparereport2view(request.POST,int(request.POST['report2incoming']))
return incoming(request)
elif 'report2outgoing' in request.POST: #coming from ViewIncoming, go to incoming
request.POST = viewlib.preparereport2view(request.POST,int(request.POST['report2outgoing']))
return outgoing(request)
elif 'report2process' in request.POST: #coming from ViewIncoming, go to incoming
request.POST = viewlib.preparereport2view(request.POST,int(request.POST['report2process']))
return process(request)
elif 'report2errors' in request.POST: #coming from ViewIncoming, go to incoming
newpost = viewlib.preparereport2view(request.POST,int(request.POST['report2errors']))
newpost['statust'] = ERROR
request.POST = newpost
return incoming(request)
else: #coming from ViewIncoming
viewlib.handlepagination(request.POST,formin.cleaned_data)
cleaned_data = formin.cleaned_data
query = models.report.objects.all()
pquery = viewlib.filterquery(query,cleaned_data)
formout = forms.ViewReports(initial=cleaned_data)
return viewlib.render(request,formout,pquery)
def incoming(request,*kw,**kwargs):
if request.method == 'GET':
if 'select' in request.GET: #via menu, go to select form
formout = forms.SelectIncoming()
return viewlib.render(request,formout)
elif 'all' in request.GET: #via menu, go to all runs
cleaned_data = {'page':1,'sortedby':'ts','sortedasc':False}
else: #via menu, go to view form for last run
cleaned_data = {'page':1,'lastrun':True,'sortedby':'ts','sortedasc':False}
else: # request.method == 'POST'
if '2outgoing' in request.POST: #coming from ViewIncoming, go to outgoing form using same criteria
request.POST = viewlib.changepostparameters(request.POST,type='in2out')
return outgoing(request)
elif '2process' in request.POST: #coming from ViewIncoming, go to outgoing form using same criteria
request.POST = viewlib.changepostparameters(request.POST,type='2process')
return process(request)
elif '2confirm' in request.POST: #coming from ViewIncoming, go to outgoing form using same criteria
request.POST = viewlib.changepostparameters(request.POST,type='in2confirm')
return process(request)
elif 'fromselect' in request.POST: #coming from select criteria screen
formin = forms.SelectIncoming(request.POST)
if not formin.is_valid():
return viewlib.render(request,formin)
else: #coming from ViewIncoming
formin = forms.ViewIncoming(request.POST)
if not formin.is_valid():
return viewlib.render(request,formin)
elif '2select' in request.POST: #go to select form using same criteria
formout = forms.SelectIncoming(formin.cleaned_data)
return viewlib.render(request,formout)
elif 'retransmit' in request.POST: #coming from ViewIncoming
idta,reportidta = request.POST[u'retransmit'].split('-')
filereport = models.filereport.objects.get(idta=int(idta),reportidta=int(reportidta))
filereport.retransmit = not filereport.retransmit
filereport.save()
elif 'delete' in request.POST: #coming from ViewIncoming
idta = int(request.POST[u'delete'])
#~ query = models.filereport.objects.filter(idta=int(idta)).all().delete()
models.filereport.objects.filter(idta=idta).delete()
ta = models.ta.objects.get(idta=idta)
viewlib.gettrace(ta)
viewlib.trace2delete(ta)
else: #coming from ViewIncoming
viewlib.handlepagination(request.POST,formin.cleaned_data)
cleaned_data = formin.cleaned_data
query = models.filereport.objects.all()
pquery = viewlib.filterquery(query,cleaned_data,incoming=True)
formout = forms.ViewIncoming(initial=cleaned_data)
return viewlib.render(request,formout,pquery)
def outgoing(request,*kw,**kwargs):
if request.method == 'GET':
if 'select' in request.GET: #via menu, go to select form
formout = forms.SelectOutgoing()
return viewlib.render(request,formout)
elif 'all' in request.GET: #via menu, go to all runs
cleaned_data = {'page':1,'sortedby':'ts','sortedasc':False}
else: #via menu, go to view form for last run
cleaned_data = {'page':1,'lastrun':True,'sortedby':'ts','sortedasc':False}
else: # request.method == 'POST'
if '2incoming' in request.POST: #coming from ViewIncoming, go to outgoing form using same criteria
request.POST = viewlib.changepostparameters(request.POST,type='out2in')
return incoming(request)
elif '2process' in request.POST: #coming from ViewIncoming, go to outgoing form using same criteria
request.POST = viewlib.changepostparameters(request.POST,type='2process')
return process(request)
elif '2confirm' in request.POST: #coming from ViewIncoming, go to outgoing form using same criteria
request.POST = viewlib.changepostparameters(request.POST,type='out2confirm')
return process(request)
elif 'fromselect' in request.POST: #coming from select criteria screen
formin = forms.SelectOutgoing(request.POST)
if not formin.is_valid():
return viewlib.render(request,formin)
else:
formin = forms.ViewOutgoing(request.POST)
if not formin.is_valid():
return viewlib.render(request,formin)
elif '2select' in request.POST: #coming from ViewIncoming, change the selection criteria, go to select form
formout = forms.SelectOutgoing(formin.cleaned_data)
return viewlib.render(request,formout)
elif 'retransmit' in request.POST: #coming from ViewIncoming
ta = models.ta.objects.get(idta=int(request.POST[u'retransmit']))
ta.retransmit = not ta.retransmit
ta.save()
else: #coming from ViewIncoming
viewlib.handlepagination(request.POST,formin.cleaned_data)
cleaned_data = formin.cleaned_data
query = models.ta.objects.filter(status=EXTERNOUT,statust=DONE).all()
pquery = viewlib.filterquery(query,cleaned_data)
formout = forms.ViewOutgoing(initial=cleaned_data)
return viewlib.render(request,formout,pquery)
def document(request,*kw,**kwargs):
if request.method == 'GET':
if 'select' in request.GET: #via menu, go to select form
formout = forms.SelectDocument()
return viewlib.render(request,formout)
elif 'all' in request.GET: #via menu, go to all runs
cleaned_data = {'page':1,'sortedby':'idta','sortedasc':False}
else: #via menu, go to view form for last run
cleaned_data = {'page':1,'lastrun':True,'sortedby':'idta','sortedasc':False}
else: # request.method == 'POST'
if 'fromselect' in request.POST: #coming from select criteria screen
formin = forms.SelectDocument(request.POST)
if not formin.is_valid():
return viewlib.render(request,formin)
else:
formin = forms.ViewDocument(request.POST)
if not formin.is_valid():
return viewlib.render(request,formin)
elif '2select' in request.POST: #coming from ViewIncoming, change the selection criteria, go to select form
formout = forms.SelectDocument(formin.cleaned_data)
return viewlib.render(request,formout)
elif 'retransmit' in request.POST: #coming from Documents, no reportidta
idta = request.POST[u'retransmit']
filereport = models.filereport.objects.get(idta=int(idta),statust=DONE)
filereport.retransmit = not filereport.retransmit
filereport.save()
else: #coming from ViewIncoming
viewlib.handlepagination(request.POST,formin.cleaned_data)
cleaned_data = formin.cleaned_data
query = models.ta.objects.filter(django.db.models.Q(status=SPLITUP)|django.db.models.Q(status=TRANSLATED)).all()
pquery = viewlib.filterquery(query,cleaned_data)
viewlib.trace_document(pquery)
formout = forms.ViewDocument(initial=cleaned_data)
#~ from django.db import connections
#~ print django.db.connection.queries
return viewlib.render(request,formout,pquery)
def process(request,*kw,**kwargs):
if request.method == 'GET':
if 'select' in request.GET: #via menu, go to select form
formout = forms.SelectProcess()
return viewlib.render(request,formout)
elif 'all' in request.GET: #via menu, go to all runs
cleaned_data = {'page':1,'sortedby':'ts','sortedasc':False}
else: #via menu, go to view form for last run
cleaned_data = {'page':1,'lastrun':True,'sortedby':'ts','sortedasc':False}
else: # request.method == 'POST'
if '2incoming' in request.POST: #coming from ViewIncoming, go to outgoing form using same criteria
request.POST = viewlib.changepostparameters(request.POST,type='fromprocess')
return incoming(request)
elif '2outgoing' in request.POST: #coming from ViewIncoming, go to outgoing form using same criteria
request.POST = viewlib.changepostparameters(request.POST,type='fromprocess')
return outgoing(request)
elif 'fromselect' in request.POST: #coming from select criteria screen
formin = forms.SelectProcess(request.POST)
if not formin.is_valid():
return viewlib.render(request,formin)
else:
if 'retry' in request.POST:
idta = request.POST[u'retry']
ta = models.ta.objects.get(idta=int(idta))
ta.retransmit = not ta.retransmit
ta.save()
formin = forms.ViewProcess(request.POST)
if not formin.is_valid():
return viewlib.render(request,formin)
elif '2select' in request.POST: #coming from ViewIncoming, change the selection criteria, go to select form
formout = forms.SelectProcess(formin.cleaned_data)
return viewlib.render(request,formout)
else: #coming from ViewIncoming
viewlib.handlepagination(request.POST,formin.cleaned_data)
cleaned_data = formin.cleaned_data
query = models.ta.objects.filter(status=PROCESS,statust=ERROR).all()
pquery = viewlib.filterquery(query,cleaned_data)
formout = forms.ViewProcess(initial=cleaned_data)
return viewlib.render(request,formout,pquery)
def detail(request,*kw,**kwargs):
''' in: the idta, either as parameter in or out.
in: is idta of incoming file.
out: idta of outgoing file, need to trace back for incoming file.
return list of ta's for display in detail template.
This list is formatted and ordered for display.
first, get a tree (trace) starting with the incoming ta ;
than make up the details for the trace
'''
if request.method == 'GET':
if 'inidta' in request.GET:
rootta = models.ta.objects.get(idta=int(request.GET['inidta']))
viewlib.gettrace(rootta)
detaillist = viewlib.trace2detail(rootta)
return django.shortcuts.render_to_response('bots/detail.html', {'detaillist':detaillist,'rootta':rootta,},context_instance=django.template.RequestContext(request))
else:
#trace back to root:
rootta = viewlib.django_trace_origin(int(request.GET['outidta']),{'status':EXTERNIN})[0]
viewlib.gettrace(rootta)
detaillist = viewlib.trace2detail(rootta)
return django.shortcuts.render_to_response('bots/detail.html', {'detaillist':detaillist,'rootta':rootta,},context_instance=django.template.RequestContext(request))
def confirm(request,*kw,**kwargs):
if request.method == 'GET':
if 'select' in request.GET: #via menu, go to select form
formout = forms.SelectConfirm()
return viewlib.render(request,formout)
else: #via menu, go to view form for last run
cleaned_data = {'page':1,'sortedby':'ts','sortedasc':False}
else: # request.method == 'POST'
if '2incoming' in request.POST: #coming from ViewIncoming, go to outgoing form using same criteria
request.POST = viewlib.changepostparameters(request.POST,type='confirm2in')
return incoming(request)
elif '2outgoing' in request.POST: #coming from ViewIncoming, go to outgoing form using same criteria
request.POST = viewlib.changepostparameters(request.POST,type='confirm2out')
return outgoing(request)
elif 'fromselect' in request.POST: #coming from select criteria screen
formin = forms.SelectConfirm(request.POST)
if not formin.is_valid():
return viewlib.render(request,formin)
elif 'confirm' in request.POST: #coming from 'star' menu 'Manual confirm'
ta = models.ta.objects.get(idta=int(request.POST[u'confirm']))
if ta.confirmed == False and ta.confirmtype.startswith('ask'):
ta.confirmed = True
ta.confirmidta = '-1' # to indicate a manual confirmation
ta.save()
request.user.message_set.create(message='Manual confirmed.')
else:
request.user.message_set.create(message='Manual confirm not possible.')
# then just refresh the current view
formin = forms.ViewConfirm(request.POST)
if not formin.is_valid():
return viewlib.render(request,formin)
else:
formin = forms.ViewConfirm(request.POST)
if not formin.is_valid():
return viewlib.render(request,formin)
elif '2select' in request.POST: #coming from ViewIncoming, change the selection criteria, go to select form
formout = forms.SelectConfirm(formin.cleaned_data)
return viewlib.render(request,formout)
else: #coming from ViewIncoming
viewlib.handlepagination(request.POST,formin.cleaned_data)
cleaned_data = formin.cleaned_data
query = models.ta.objects.filter(confirmasked=True).all()
pquery = viewlib.filterquery(query,cleaned_data)
formout = forms.ViewConfirm(initial=cleaned_data)
return viewlib.render(request,formout,pquery)
def filer(request,*kw,**kwargs):
''' handles bots file viewer. Only files in data dir of Bots are displayed.'''
nosuchfile = _(u'No such file.')
if request.method == 'GET':
try:
idta = request.GET['idta']
except:
return django.shortcuts.render_to_response('bots/filer.html', {'error_content': nosuchfile},context_instance=django.template.RequestContext(request))
if idta == 0: #for the 'starred' file names (eg multiple output)
return django.shortcuts.render_to_response('bots/filer.html', {'error_content': nosuchfile},context_instance=django.template.RequestContext(request))
try:
currentta = list(models.ta.objects.filter(idta=idta))[0]
if request.GET['action']=='downl':
response = django.http.HttpResponse(mimetype=currentta.contenttype)
if currentta.contenttype == 'text/html':
dispositiontype = 'inline'
else:
dispositiontype = 'attachment'
response['Content-Disposition'] = dispositiontype + '; filename=' + currentta.filename + '.txt'
#~ response['Content-Length'] = os.path.getsize(absfilename)
response.write(botslib.readdata(currentta.filename,charset=currentta.charset,errors='ignore'))
return response
elif request.GET['action']=='previous':
if currentta.parent: #has a explicit parent
talijst = list(models.ta.objects.filter(idta=currentta.parent))
else: #get list of ta's referring to this idta as child
talijst = list(models.ta.objects.filter(child=currentta.idta))
elif request.GET['action']=='this':
if currentta.status == EXTERNIN: #jump strait to next file, as EXTERNIN can not be displayed.
talijst = list(models.ta.objects.filter(parent=currentta.idta))
elif currentta.status == EXTERNOUT:
talijst = list(models.ta.objects.filter(idta=currentta.parent))
else:
talijst = [currentta]
elif request.GET['action']=='next':
if currentta.child: #has a explicit child
talijst = list(models.ta.objects.filter(idta=currentta.child))
else:
talijst = list(models.ta.objects.filter(parent=currentta.idta))
for ta in talijst:
ta.has_next = True
if ta.status == EXTERNIN:
ta.content = _(u'External file. Can not be displayed. Use "next".')
elif ta.status == EXTERNOUT:
ta.content = _(u'External file. Can not be displayed. Use "previous".')
ta.has_next = False
elif ta.statust in [OPEN,ERROR]:
ta.content = _(u'File has error status and does not exist. Use "previous".')
ta.has_next = False
elif not ta.filename:
ta.content = _(u'File can not be displayed.')
else:
if ta.charset: #guess charset; uft-8 is reasonable
ta.content = botslib.readdata(ta.filename,charset=ta.charset,errors='ignore')
else:
ta.content = botslib.readdata(ta.filename,charset='utf-8',errors='ignore')
return django.shortcuts.render_to_response('bots/filer.html', {'idtas': talijst},context_instance=django.template.RequestContext(request))
except:
#~ print botslib.txtexc()
return django.shortcuts.render_to_response('bots/filer.html', {'error_content': nosuchfile},context_instance=django.template.RequestContext(request))
def plugin(request,*kw,**kwargs):
if request.method == 'GET':
form = forms.UploadFileForm()
return django.shortcuts.render_to_response('bots/plugin.html', {'form': form},context_instance=django.template.RequestContext(request))
else:
if 'submit' in request.POST: #coming from ViewIncoming, go to outgoing form using same criteria
form = forms.UploadFileForm(request.POST, request.FILES)
if form.is_valid():
botsglobal.logger.info(_(u'Start reading plugin "%s".'),request.FILES['file'].name)
try:
if pluglib.load(request.FILES['file'].temporary_file_path()):
request.user.message_set.create(message='Renamed existing files.')
except botslib.PluginError,txt:
botsglobal.logger.info(u'%s',str(txt))
request.user.message_set.create(message='%s'%txt)
else:
botsglobal.logger.info(_(u'Finished reading plugin "%s" successful.'),request.FILES['file'].name)
request.user.message_set.create(message='Plugin "%s" is read successful.'%request.FILES['file'].name)
request.FILES['file'].close()
else:
request.user.message_set.create(message=_(u'No plugin read.'))
return django.shortcuts.redirect('/home')
def plugout(request,*kw,**kwargs):
if request.method == 'GET':
form = forms.PlugoutForm()
return django.shortcuts.render_to_response('bots/plugout.html', {'form': form},context_instance=django.template.RequestContext(request))
else:
if 'submit' in request.POST:
form = forms.PlugoutForm(request.POST)
if form.is_valid():
botsglobal.logger.info(_(u'Start writing plugin "%s".'),form.cleaned_data['filename'])
try:
pluglib.plugoutcore(form.cleaned_data)
except botslib.PluginError, txt:
botsglobal.logger.info(u'%s',str(txt))
request.user.message_set.create(message='%s'%txt)
else:
botsglobal.logger.info(_(u'Plugin "%s" created successful.'),form.cleaned_data['filename'])
request.user.message_set.create(message=_(u'Plugin %s created successful.')%form.cleaned_data['filename'])
return django.shortcuts.redirect('/home')
def delete(request,*kw,**kwargs):
if request.method == 'GET':
form = forms.DeleteForm()
return django.shortcuts.render_to_response('bots/delete.html', {'form': form},context_instance=django.template.RequestContext(request))
else:
if 'submit' in request.POST:
form = forms.DeleteForm(request.POST)
if form.is_valid():
botsglobal.logger.info(_(u'Start deleting in configuration.'))
if form.cleaned_data['deltransactions']:
#while testing with very big loads, deleting transaction when wrong. Using raw SQL solved this.
from django.db import connection, transaction
cursor = connection.cursor()
cursor.execute("DELETE FROM ta")
cursor.execute("DELETE FROM filereport")
cursor.execute("DELETE FROM report")
transaction.commit_unless_managed()
request.user.message_set.create(message=_(u'Transactions are deleted.'))
botsglobal.logger.info(_(u' Transactions are deleted.'))
#clean data files
deletefrompath = botsglobal.ini.get('directories','data','botssys/data')
shutil.rmtree(deletefrompath,ignore_errors=True)
botslib.dirshouldbethere(deletefrompath)
request.user.message_set.create(message=_(u'Data files are deleted.'))
botsglobal.logger.info(_(u' Data files are deleted.'))
if form.cleaned_data['delconfiguration']:
models.confirmrule.objects.all().delete()
models.channel.objects.all().delete()
models.chanpar.objects.all().delete()
models.partner.objects.all().delete()
models.translate.objects.all().delete()
models.routes.objects.all().delete()
request.user.message_set.create(message=_(u'Database configuration is deleted.'))
botsglobal.logger.info(_(u' Database configuration is deleted.'))
if form.cleaned_data['delcodelists']:
models.ccode.objects.all().delete()
models.ccodetrigger.objects.all().delete()
request.user.message_set.create(message=_(u'User code lists are deleted.'))
botsglobal.logger.info(_(u' User code lists are deleted.'))
if form.cleaned_data['delinfile']:
deletefrompath = botslib.join(botsglobal.ini.get('directories','botssys','botssys'),'infile')
shutil.rmtree('bots/botssys/infile',ignore_errors=True)
request.user.message_set.create(message=_(u'Files in botssys/infile are deleted.'))
botsglobal.logger.info(_(u' Files in botssys/infile are deleted.'))
if form.cleaned_data['deloutfile']:
deletefrompath = botslib.join(botsglobal.ini.get('directories','botssys','botssys'),'outfile')
shutil.rmtree('bots/botssys/outfile',ignore_errors=True)
request.user.message_set.create(message=_(u'Files in botssys/outfile are deleted.'))
botsglobal.logger.info(_(u' Files in botssys/outfile are deleted.'))
if form.cleaned_data['deluserscripts']:
deletefrompath = botsglobal.ini.get('directories','usersysabs')
for root, dirs, files in os.walk(deletefrompath):
head, tail = os.path.split(root)
if tail == 'charsets':
del dirs[:]
continue
for bestand in files:
if bestand != '__init__.py':
os.remove(os.path.join(root,bestand))
request.user.message_set.create(message=_(u'User scripts are deleted (in usersys).'))
botsglobal.logger.info(_(u' User scripts are deleted (in usersys).'))
elif form.cleaned_data['delbackup']:
deletefrompath = botsglobal.ini.get('directories','usersysabs')
for root, dirs, files in os.walk(deletefrompath):
head, tail = os.path.split(root)
if tail == 'charsets':
del dirs[:]
continue
for bestand in files:
name,ext = os.path.splitext(bestand)
if ext and len(ext) == 15 and ext[1:].isdigit() :
os.remove(os.path.join(root,bestand))
request.user.message_set.create(message=_(u'Backupped user scripts are deleted/purged (in usersys).'))
botsglobal.logger.info(_(u' Backupped user scripts are deleted/purged (in usersys).'))
botsglobal.logger.info(_(u'Finished deleting in configuration.'))
return django.shortcuts.redirect('/home')
def runengine(request,*kw,**kwargs):
if request.method == 'GET':
#check if bots-engine is not already running
if list(models.mutex.objects.filter(mutexk=1).all()):
request.user.message_set.create(message=_(u'Trying to run "bots-engine", but database is locked by another run in progress. Please try again later.'))
botsglobal.logger.info(_(u'Trying to run "bots-engine", but database is locked by another run in progress.'))
return django.shortcuts.redirect('/home')
#find out the right arguments to use
botsenginepath = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])),'bots-engine.py') #find the bots-engine
lijst = [sys.executable,botsenginepath] + sys.argv[1:]
if 'clparameter' in request.GET:
lijst.append(request.GET['clparameter'])
try:
botsglobal.logger.info(_(u'Run bots-engine with parameters: "%s"'),str(lijst))
terug = subprocess.Popen(lijst).pid
request.user.message_set.create(message=_(u'Bots-engine is started.'))
except:
txt = botslib.txtexc()
request.user.message_set.create(message=_(u'Errors while trying to run bots-engine.'))
botsglobal.logger.info(_(u'Errors while trying to run bots-engine:\n%s.'),txt)
return django.shortcuts.redirect('/home')
def unlock(request,*kw,**kwargs):
if request.method == 'GET':
lijst = list(models.mutex.objects.filter(mutexk=1).all())
if lijst:
lijst[0].delete()
request.user.message_set.create(message=_(u'Unlocked database.'))
botsglobal.logger.info(_(u'Unlocked database.'))
else:
request.user.message_set.create(message=_(u'Request to unlock database, but database was not locked.'))
botsglobal.logger.info(_(u'Request to unlock database, but database was not locked.'))
return django.shortcuts.redirect('/home')
def sendtestmailmanagers(request,*kw,**kwargs):
try:
sendornot = botsglobal.ini.getboolean('settings','sendreportiferror',False)
except botslib.BotsError:
sendornot = False
if not sendornot:
botsglobal.logger.info(_(u'Trying to send test mail, but in bots.ini, section [settings], "sendreportiferror" is not "True".'))
request.user.message_set.create(message=_(u'Trying to send test mail, but in bots.ini, section [settings], "sendreportiferror" is not "True".'))
return django.shortcuts.redirect('/home')
from django.core.mail import mail_managers
try:
mail_managers(_(u'testsubject'), _(u'test content of report'))
except:
txt = botslib.txtexc()
request.user.message_set.create(message=_(u'Sending test mail failed.'))
botsglobal.logger.info(_(u'Sending test mail failed, error:\n%s'), txt)
return django.shortcuts.redirect('/home')
request.user.message_set.create(message=_(u'Sending test mail succeeded.'))
botsglobal.logger.info(_(u'Sending test mail succeeded.'))
return django.shortcuts.redirect('/home')
| Python |
import os
import re
import zipfile
from django.utils.translation import ugettext as _
#bots-modules
import botslib
import botsglobal
from botsconfig import *
@botslib.log_session
def preprocess(routedict,function, status=FILEIN,**argv):
''' for pre- and postprocessing of files.
these are NOT translations; translation involve grammars, mapping scripts etc. think of eg:
- unzipping zipped files.
- convert excel to csv
- password protected files.
Select files from INFILE -> SET_FOR_PROCESSING using criteria
Than the actual processing function is called.
The processing function does: SET_FOR_PROCESSING -> PROCESSING -> FILEIN
If errors occur during processing, no ta are left with status FILEIN !
preprocess is called right after the in-communicatiation
'''
nr_files = 0
preprocessnumber = botslib.getpreprocessnumber()
if not botslib.addinfo(change={'status':preprocessnumber},where={'status':status,'idroute':routedict['idroute'],'fromchannel':routedict['fromchannel']}): #check if there is something to do
return 0
for row in botslib.query(u'''SELECT idta,filename,charset
FROM ta
WHERE idta>%(rootidta)s
AND status=%(status)s
AND statust=%(statust)s
AND idroute=%(idroute)s
AND fromchannel=%(fromchannel)s
''',
{'status':preprocessnumber,'statust':OK,'idroute':routedict['idroute'],'fromchannel':routedict['fromchannel'],'rootidta':botslib.get_minta4query()}):
try:
botsglobal.logmap.debug(u'Start preprocessing "%s" for file "%s".',function.__name__,row['filename'])
ta_set_for_processing = botslib.OldTransaction(row['idta'])
ta_processing = ta_set_for_processing.copyta(status=preprocessnumber+1)
ta_processing.filename=row['filename']
function(ta_from=ta_processing,endstatus=status,routedict=routedict,**argv)
except:
txt=botslib.txtexc()
ta_processing.failure()
ta_processing.update(statust=ERROR,errortext=txt)
else:
botsglobal.logmap.debug(u'OK preprocessing "%s" for file "%s".',function.__name__,row['filename'])
ta_set_for_processing.update(statust=DONE)
ta_processing.update(statust=DONE)
nr_files += 1
return nr_files
header = re.compile('(\s*(ISA))|(\s*(UNA.{6})?\s*(U\s*N\s*B)s*.{1}(.{4}).{1}(.{1}))',re.DOTALL)
# group: 1 2 3 4 5 6 7
def mailbag(ta_from,endstatus,**argv):
''' split 'mailbag' files to separate files each containing one interchange (ISA-IEA or UNA/UNB-UNZ).
handles x12 and edifact; these can be mixed.
recognizes xml files. messagetype 'xml' has a special handling when reading xml-files.
about auto-detect/mailbag:
- in US mailbag is used: one file for all received edi messages...appended in one file. I heard that edifact and x12 can be mixed,
but have actually never seen this.
- bots needs a 'splitter': one edi-file, more interchanges. it is preferred to split these first.
- handle multiple UNA in one file, including different charsets.
- auto-detect: is is x12, edifact, xml, or??
'''
edifile = botslib.readdata(filename=ta_from.filename) #read as binary...
startpos=0
while (1):
found = header.search(edifile[startpos:])
if found is None:
if startpos: #ISA/UNB have been found in file; no new ISA/UNB is found. So all processing is done.
break
#guess if this is an xml file.....
sniffxml = edifile[:25]
sniffxml = sniffxml.lstrip(' \t\n\r\f\v\xFF\xFE\xEF\xBB\xBF\x00') #to find first ' real' data; some char are because of BOM, UTF-16 etc
if sniffxml and sniffxml[0]=='<':
ta_to=ta_from.copyta(status=endstatus,statust=OK,filename=ta_from.filename,editype='xml',messagetype='mailbag') #make transaction for translated message; gets ta_info of ta_frommes
#~ ta_tomes.update(status=STATUSTMP,statust=OK,filename=ta_set_for_processing.filename,editype='xml') #update outmessage transaction with ta_info;
break;
else:
raise botslib.InMessageError(_(u'Found no content in mailbag.'))
elif found.group(1):
editype='x12'
headpos=startpos+ found.start(2)
count=0
for c in edifile[headpos:headpos+120]: #search first 120 characters to find separators
if c in '\r\n' and count!=105:
continue
count +=1
if count==4:
field_sep = c
elif count==106:
record_sep = c
break
#~ foundtrailer = re.search(re.escape(record_sep)+'\s*IEA'+re.escape(field_sep)+'.+?'+re.escape(record_sep),edifile[headpos:],re.DOTALL)
foundtrailer = re.search(re.escape(record_sep)+'\s*I\s*E\s*A\s*'+re.escape(field_sep)+'.+?'+re.escape(record_sep),edifile[headpos:],re.DOTALL)
elif found.group(3):
editype='edifact'
if found.group(4):
field_sep = edifile[startpos + found.start(4) + 4]
record_sep = edifile[startpos + found.start(4) + 8]
headpos=startpos+ found.start(4)
else:
field_sep = '+'
record_sep = "'"
headpos=startpos+ found.start(5)
foundtrailer = re.search(re.escape(record_sep)+'\s*U\s*N\s*Z\s*'+re.escape(field_sep)+'.+?'+re.escape(record_sep),edifile[headpos:],re.DOTALL)
if not foundtrailer:
raise botslib.InMessageError(_(u'Found no valid envelope trailer in mailbag.'))
endpos = headpos+foundtrailer.end()
#so: interchange is from headerpos untill endpos
#~ if header.search(edifile[headpos+25:endpos]): #check if there is another header in the interchange
#~ raise botslib.InMessageError(u'Error in mailbag format: found no valid envelope trailer.')
ta_to = ta_from.copyta(status=endstatus) #make transaction for translated message; gets ta_info of ta_frommes
tofilename = str(ta_to.idta)
tofile = botslib.opendata(tofilename,'wb')
tofile.write(edifile[headpos:endpos])
tofile.close()
ta_to.update(statust=OK,filename=tofilename,editype=editype,messagetype=editype) #update outmessage transaction with ta_info;
startpos=endpos
botsglobal.logger.debug(_(u' File written: "%s".'),tofilename)
def botsunzip(ta_from,endstatus,password=None,pass_non_zip=False,**argv):
''' unzip file;
editype & messagetype are unchanged.
'''
try:
z = zipfile.ZipFile(botslib.abspathdata(filename=ta_from.filename),mode='r')
except zipfile.BadZipfile:
botsglobal.logger.debug(_(u'File is not a zip-file.'))
if pass_non_zip: #just pass the file
botsglobal.logger.debug(_(u'"pass_non_zip" is True, just pass the file.'))
ta_to = ta_from.copyta(status=endstatus,statust=OK)
return
raise botslib.InMessageError(_(u'File is not a zip-file.'))
if password:
z.setpassword(password)
for f in z.infolist():
if f.filename[-1] == '/': #check if this is a dir; if so continue
continue
ta_to = ta_from.copyta(status=endstatus)
tofilename = str(ta_to.idta)
tofile = botslib.opendata(tofilename,'wb')
tofile.write(z.read(f.filename))
tofile.close()
ta_to.update(statust=OK,filename=tofilename) #update outmessage transaction with ta_info;
botsglobal.logger.debug(_(u' File written: "%s".'),tofilename)
def extractpdf(ta_from,endstatus,**argv):
''' Try to extract text content of a PDF file to a csv.
You know this is not a great idea, right? But we'll do the best we can anyway!
Page and line numbers are added to each row.
Columns and rows are based on the x and y coordinates of each text element within tolerance allowed.
Multiple text elements may combine to make one field, some PDFs have every character separated!
You may need to experiment with x_group and y_group values, but defaults seem ok for most files.
Output csv is UTF-8 encoded - The csv module doesn't directly support reading and writing Unicode
If the PDF is just an image, all bets are off. Maybe try OCR, good luck with that!
Mike Griffin 14/12/2011
'''
from pdfminer.pdfinterp import PDFResourceManager, process_pdf
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams, LTContainer, LTText, LTTextBox
import csv
class CsvConverter(TextConverter):
def __init__(self, *args, **kwargs):
TextConverter.__init__(self, *args, **kwargs)
def receive_layout(self, ltpage):
# recursively get every text element and it's coordinates
def render(item):
if isinstance(item, LTContainer):
for child in item:
render(child)
elif isinstance(item, LTText):
(_,_,x,y) = item.bbox
# group the y values (rows) within group tolerance
for v in yv:
if y > v-y_group and y < v+y_group:
y = v
yv.append(y)
line = lines[int(-y)]
line[x] = item.get_text().encode('utf-8')
from collections import defaultdict
lines = defaultdict(lambda : {})
yv = []
render(ltpage)
lineid = 0
for y in sorted(lines.keys()):
line = lines[y]
lineid += 1
csvdata = [ltpage.pageid,lineid] # first 2 columns are page and line numbers
# group the x values (fields) within group tolerance
p = 0
field_txt=''
for x in sorted(line.keys()):
gap = x - p
if p > 0 and gap > x_group:
csvdata.append(field_txt)
field_txt=''
field_txt += line[x]
p = x
csvdata.append(field_txt)
csvout.writerow(csvdata)
if lineid == 0:
raise botslib.InMessageError(_(u'PDF text extraction failed, it may contain just image(s)?'))
#get some optional parameters
x_group = argv.get('x_group',10) # group text closer than this as one field
y_group = argv.get('y_group',5) # group lines closer than this as one line
password = argv.get('password','')
quotechar = argv.get('quotechar','"')
field_sep = argv.get('field_sep',',')
escape = argv.get('escape','\\')
charset = argv.get('charset','utf-8')
if not escape:
doublequote = True
else:
doublequote = False
try:
pdf_stream = botslib.opendata(ta_from.filename, 'rb')
ta_to = ta_from.copyta(status=endstatus)
tofilename = str(ta_to.idta)
csv_stream = botslib.opendata(tofilename,'wb')
csvout = csv.writer(csv_stream, quotechar=quotechar, delimiter=field_sep, doublequote=doublequote, escapechar=escape)
# Process PDF
rsrcmgr = PDFResourceManager(caching=True)
device = CsvConverter(rsrcmgr, csv_stream, codec=charset)
process_pdf(rsrcmgr, device, pdf_stream, pagenos=set(), password=password, caching=True, check_extractable=True)
device.close()
pdf_stream.close()
csv_stream.close()
ta_to.update(statust=OK,filename=tofilename) #update outmessage transaction with ta_info;
botsglobal.logger.debug(_(u' File written: "%s".'),tofilename)
except:
txt=botslib.txtexc()
botsglobal.logger.error(_(u'PDF extraction failed, may not be a PDF file? Error:\n%s'),txt)
raise botslib.InMessageError(_(u'PDF extraction failed, may not be a PDF file? Error:\n$error'),error=txt)
def extractexcel(ta_from,endstatus,**argv):
''' extract excel file.
editype & messagetype are unchanged.
'''
#***functions used by extractexcel
#-------------------------------------------------------------------------------
def read_xls(infilename):
# Read excel first sheet into a 2-d array
book = xlrd.open_workbook(infilename)
sheet = book.sheet_by_index(0)
formatter = lambda(t,v): format_excelval(book,t,v,False)
xlsdata = []
for row in range(sheet.nrows):
(types, values) = (sheet.row_types(row), sheet.row_values(row))
xlsdata.append(map(formatter, zip(types, values)))
return xlsdata
#-------------------------------------------------------------------------------
def dump_csv(xlsdata, tofilename):
stream = botslib.opendata(tofilename, 'wb')
csvout = csv.writer(stream, quotechar=quotechar, delimiter=field_sep, doublequote=doublequote, escapechar=escape)
csvout.writerows( map(utf8ize, xlsdata) )
stream.close()
#-------------------------------------------------------------------------------
def format_excelval(book, type, value, wanttupledate):
# Clean up the incoming excel data for some data types
returnrow = []
if type == 2:
if value == int(value):
value = int(value)
elif type == 3:
datetuple = xlrd.xldate_as_tuple(value, book.datemode)
value = datetuple if wanttupledate else tupledate_to_isodate(datetuple)
elif type == 5:
value = xlrd.error_text_from_code[value]
return value
#-------------------------------------------------------------------------------
def tupledate_to_isodate(tupledate):
# Turns a gregorian (year, month, day, hour, minute, nearest_second) into a
# standard YYYY-MM-DDTHH:MM:SS ISO date.
(y,m,d, hh,mm,ss) = tupledate
nonzero = lambda n: n!=0
date = "%04d-%02d-%02d" % (y,m,d) if filter(nonzero, (y,m,d)) else ''
time = "T%02d:%02d:%02d" % (hh,mm,ss) if filter(nonzero, (hh,mm,ss)) or not date else ''
return date+time
#-------------------------------------------------------------------------------
def utf8ize(l):
# Make string-like things into utf-8, leave other things alone
return [unicode(s).encode(charset) if hasattr(s,'encode') else s for s in l]
#***end functions used by extractexcel
import xlrd
import csv
#get parameters for csv-format; defaults are as the csv defaults (in grammar.py)
charset = argv.get('charset',"utf-8")
quotechar = argv.get('quotechar',"'")
field_sep = argv.get('field_sep',':')
escape = argv.get('escape','')
if escape:
doublequote = False
else:
doublequote = True
try:
infilename = botslib.abspathdata(ta_from.filename)
xlsdata = read_xls(infilename)
ta_to = ta_from.copyta(status=endstatus)
tofilename = str(ta_to.idta)
dump_csv(xlsdata,tofilename)
ta_to.update(statust=OK,filename=tofilename) #update outmessage transaction with ta_info;
botsglobal.logger.debug(_(u' File written: "%s".'),tofilename)
except:
txt=botslib.txtexc()
botsglobal.logger.error(_(u'Excel extraction failed, may not be an Excel file? Error:\n%s'),txt)
raise botslib.InMessageError(_(u'Excel extraction failed, may not be an Excel file? Error:\n$error'),error=txt)
| Python |
from django.utils.translation import ugettext as _
#bots-modules
import botslib
import node
from botsconfig import *
class Message(object):
''' abstract class; represents a edi message.
is subclassed as outmessage or inmessage object.
'''
def __init__(self):
self.recordnumber=0 #segment counter. Is not used for UNT of SE record; some editypes want sequential recordnumbering
def kill(self):
""" explicitly del big attributes....."""
if hasattr(self,'ta_info'): del self.ta_info
if hasattr(self,'root'): del self.root
if hasattr(self,'defmessage'): del self.defmessage
if hasattr(self,'records'): del self.records
if hasattr(self,'rawinput'): del self.rawinput
@staticmethod
def display(records):
'''for debugging lexed records.'''
for record in records:
t = 0
for veld in record:
if t==0:
print '%s (Record-id)'%(veld[VALUE])
else:
if veld[SFIELD]:
print ' %s (sub)'%(veld[VALUE])
else:
print ' %s (veld)'%(veld[VALUE])
t += 1
def change(self,where,change):
''' query tree (self.root) with where; if found replace with change; return True if change, return False if not changed.'''
if self.root.record is None:
raise botslib.MappingRootError(_(u'change($where,$change"): "root" of incoming message is empty; either split messages or use inn.getloop'),where=where,change=change)
return self.root.change(where,change)
def delete(self,*mpaths):
''' query tree (self.root) with mpath; delete if found. return True if deleted, return False if not deleted.'''
if self.root.record is None:
raise botslib.MappingRootError(_(u'delete($mpath): "root" of incoming message is empty; either split messages or use inn.getloop'),mpath=mpaths)
return self.root.delete(*mpaths)
def get(self,*mpaths):
''' query tree (self.root) with mpath; get value (string); get None if not found.'''
if self.root.record is None:
raise botslib.MappingRootError(_(u'get($mpath): "root" of incoming message is empty; either split messages or use inn.getloop'),mpath=mpaths)
return self.root.get(*mpaths)
def getnozero(self,*mpaths):
''' like get, returns None is value is zero (0) or not numeric.
Is sometimes usefull in mapping.'''
if self.root.record is None:
raise botslib.MappingRootError(_(u'get($mpath): "root" of incoming message is empty; either split messages or use inn.getloop'),mpath=mpaths)
return self.root.getnozero(*mpaths)
def getcount(self):
''' count number of nodes in self.root. Number of nodes is number of records.'''
return self.root.getcount()
def getcountoccurrences(self,*mpaths):
''' count number of nodes in self.root. Number of nodes is number of records.'''
count = 0
for value in self.getloop(*mpaths):
count += 1
return count
def getcountsum(self,*mpaths):
''' return the sum for all values found in mpath. Eg total number of ordered quantities.'''
if self.root.record is None:
raise botslib.MappingRootError(_(u'get($mpath): "root" of incoming message is empty; either split messages or use inn.getloop'),mpath=mpaths)
return self.root.getcountsum(*mpaths)
def getloop(self,*mpaths):
''' query tree with mpath; generates all the nodes. Is typically used as: for record in inn.get(mpath):
'''
if self.root.record: #self.root is a real root
for terug in self.root.getloop(*mpaths): #search recursive for rest of mpaths
yield terug
else: #self.root is dummy root
for childnode in self.root.children:
for terug in childnode.getloop(*mpaths): #search recursive for rest of mpaths
yield terug
def put(self,*mpaths,**kwargs):
if self.root.record is None and self.root.children:
raise botslib.MappingRootError(_(u'put($mpath): "root" of outgoing message is empty; use out.putloop'),mpath=mpaths)
return self.root.put(*mpaths,**kwargs)
def putloop(self,*mpaths):
if not self.root.record: #no input yet, and start with a putloop(): dummy root
if len(mpaths) == 1:
self.root.append(node.Node(mpaths[0]))
return self.root.children[-1]
else: #TODO: what if self.root.record is None and len(mpaths) > 1?
raise botslib.MappingRootError(_(u'putloop($mpath): mpath too long???'),mpath=mpaths)
return self.root.putloop(*mpaths)
def sort(self,*mpaths):
if self.root.record is None:
raise botslib.MappingRootError(_(u'get($mpath): "root" of message is empty; either split messages or use inn.getloop'),mpath=mpaths)
self.root.sort(*mpaths)
def normalisetree(self,node):
''' The node tree is check, sorted, fields are formatted etc.
Always use this method before writing output.
'''
self._checktree(node,self.defmessage.structure[0])
#~ node.display()
self._canonicaltree(node,self.defmessage.structure[0])
def _checktree(self,tree,structure):
''' checks tree with table:
- all records should be in table at the right place in hierarchy
- for each record, all fields should be in grammar
This function checks the root of grammar-structure with root of node tree
'''
if tree.record['BOTSID'] == structure[ID]:
#check tree recursively with structure
self._checktreecore(tree,structure)
else:
raise botslib.MessageError(_(u'Grammar "$grammar" has (root)record "$grammarroot"; found "$root".'),root=tree.record['BOTSID'],grammarroot=structure[ID],grammar=self.defmessage.grammarname)
def _checktreecore(self,node,structure):
''' recursive
'''
deletelist=[]
self._checkfields(node.record,structure)
if node.children and not LEVEL in structure:
if self.ta_info['checkunknownentities']:
raise botslib.MessageError(_(u'Record "$record" in message has children, but grammar "$grammar" not. Found "$xx".'),record=node.record['BOTSID'],grammar=self.defmessage.grammarname,xx=node.children[0].record['BOTSID'])
node.children=[]
return
for childnode in node.children: #for every node:
for structure_record in structure[LEVEL]: #search in grammar-records
if childnode.record['BOTSID'] == structure_record[ID]: #if found right structure_record
#check children recursive
self._checktreecore(childnode,structure_record)
break #check next mpathnode
else: #checked all structure_record in grammar, but nothing found
if self.ta_info['checkunknownentities']:
raise botslib.MessageError(_(u'Record "$record" in message not in structure of grammar "$grammar". Whole record: "$content".'),record=childnode.record['BOTSID'],grammar=self.defmessage.grammarname,content=childnode.record)
deletelist.append(childnode)
for child in deletelist:
node.children.remove(child)
def _checkfields(self,record,structure_record):
''' checks for every field in record if field exists in structure_record (from grammar).
'''
deletelist=[]
for field in record.keys(): #all fields in record should exist in structure_record
if field == 'BOTSIDnr':
continue
for grammarfield in structure_record[FIELDS]:
if grammarfield[ISFIELD]: #if field (no composite)
if field == grammarfield[ID]:
break
else: #if composite
for grammarsubfield in grammarfield[SUBFIELDS]: #loop subfields
if field == grammarsubfield[ID]:
break
else:
continue
break
else:
if self.ta_info['checkunknownentities']:
raise botslib.MessageError(_(u'Record: "$mpath" field "$field" does not exist.'),field=field,mpath=structure_record[MPATH])
deletelist.append(field)
for field in deletelist:
del record[field]
def _canonicaltree(self,node,structure,headerrecordnumber=0):
''' For nodes: check min and max occurence; sort the records conform grammar
'''
sortednodelist = []
self._canonicalfields(node.record,structure,headerrecordnumber) #handle fields of this record
if LEVEL in structure:
for structure_record in structure[LEVEL]: #for structure_record of this level in grammar
count = 0 #count number of occurences of record
for childnode in node.children: #for every node in mpathtree; SPEED: delete nodes from list when found
if childnode.record['BOTSID'] != structure_record[ID] or childnode.record['BOTSIDnr'] != structure_record[BOTSIDnr]: #if it is not the right NODE":
continue
count += 1
self._canonicaltree(childnode,structure_record,self.recordnumber) #use rest of index in deeper level
sortednodelist.append(childnode)
if structure_record[MIN] > count:
raise botslib.MessageError(_(u'Record "$mpath" mandatory but not present.'),mpath=structure_record[MPATH])
if structure_record[MAX] < count:
raise botslib.MessageError(_(u'Record "$mpath" occurs to often ($count times).'),mpath=structure_record[MPATH],count=count)
node.children=sortednodelist
if hasattr(self,'get_queries_from_edi'):
self.get_queries_from_edi(node,structure)
def _canonicalfields(self,noderecord,structure_record,headerrecordnumber):
''' For fields: check M/C; format the fields. Fields are not sorted (a dict can not be sorted).
Fields are never added.
'''
for grammarfield in structure_record[FIELDS]:
if grammarfield[ISFIELD]: #if field (no composite)
value = noderecord.get(grammarfield[ID])
#~ print '(message)field',noderecord,grammarfield
if not value:
#~ print 'field',grammarfield[ID], 'has no value'
if grammarfield[MANDATORY] == 'M':
raise botslib.MessageError(_(u'Record "$mpath" field "$field" is mandatory.'),mpath=structure_record[MPATH],field=grammarfield[ID])
continue
#~ print 'field',grammarfield[ID], 'value', value
noderecord[grammarfield[ID]] = self._formatfield(value,grammarfield,structure_record)
else: #if composite
for grammarsubfield in grammarfield[SUBFIELDS]: #loop subfields to see if data in composite
if noderecord.get(grammarsubfield[ID]):
break #composite has data.
else: #composite has no data
if grammarfield[MANDATORY]=='M':
raise botslib.MessageError(_(u'Record "$mpath" composite "$field" is mandatory.'),mpath=structure_record[MPATH],field=grammarfield[ID])
continue
#there is data in the composite!
for grammarsubfield in grammarfield[SUBFIELDS]: #loop subfields
value = noderecord.get(grammarsubfield[ID])
if not value:
if grammarsubfield[MANDATORY]=='M':
raise botslib.MessageError(_(u'Record "$mpath" subfield "$field" is mandatory: "$record".'),mpath=structure_record[MPATH],field=grammarsubfield[ID],record=noderecord)
continue
noderecord[grammarsubfield[ID]] = self._formatfield(value,grammarsubfield,structure_record)
| Python |
import decimal
import copy
from django.utils.translation import ugettext as _
import botslib
import botsglobal
from botsconfig import *
comparekey=None
def nodecompare(node):
global comparekey
return node.get(*comparekey)
class Node(object):
''' Node class for building trees in inmessage and outmessage
'''
def __init__(self,record=None,BOTSIDnr=None):
self.record = record #record is a dict with fields
if self.record is not None:
if BOTSIDnr is None:
if not 'BOTSIDnr' in self.record:
self.record['BOTSIDnr'] = '1'
else:
self.record['BOTSIDnr'] = BOTSIDnr
self.children = []
self._queries = None
def getquerie(self):
''' get queries of a node '''
if self._queries:
return self._queries
else:
return {}
def updatequerie(self,updatequeries):
''' set/update queries of a node with dict queries.
'''
if updatequeries:
if self._queries is None:
self._queries = updatequeries.copy()
else:
self._queries.update(updatequeries)
queries = property(getquerie,updatequerie)
def processqueries(self,queries,maxlevel):
''' copies values for queries 'down the tree' untill right level.
So when edi file is split up in messages,
querie-info from higher levels is copied to message.'''
self.queries = queries
if self.record and not maxlevel:
return
for child in self.children:
child.processqueries(self.queries,maxlevel-1)
def append(self,node):
'''append child to node'''
self.children += [node]
def display(self,level=0):
'''for debugging
usage: in mapping script: inn.root.display()
'''
if level==0:
print 'displaying all nodes in node tree:'
print ' '*level,self.record
for child in self.children:
child.display(level+1)
def displayqueries(self,level=0):
'''for debugging
usage: in mapping script: inn.root.displayqueries()
'''
if level==0:
print 'displaying queries for nodes in tree'
print ' '*level,'node:',
if self.record:
print self.record['BOTSID'],
else:
print 'None',
print '',
print self.queries
for child in self.children:
child.displayqueries(level+1)
def enhancedget(self,mpaths,replace=False):
''' to get QUERIES or SUBTRANSLATION while parsing edifile;
mpath can be
- dict: do get(mpath); can not be a mpath with multiple
- tuple: do get(mpath); can be multiple dicts in mapth
- list: for each listmembr do a get(); append the results
Used by:
- QUERIES
- SUBTRANSLATION
'''
if isinstance(mpaths,dict):
return self.get(mpaths)
elif isinstance(mpaths,tuple):
return self.get(*mpaths)
elif isinstance(mpaths,list):
collect = u''
for mpath in mpaths:
found = self.get(mpath)
if found:
if replace:
found = found.replace('.','_')
collect += found
return collect
else:
raise botslib.MappingFormatError(_(u'must be dict, list or tuple: enhancedget($mpath)'),mpath=mpaths)
def change(self,where,change):
''' '''
#find first matching node using 'where'. Do not look at other matching nodes (is a feature)
#prohibit change of BOTSID?
mpaths = where #diff from getcore
if not mpaths or not isinstance(mpaths,tuple):
raise botslib.MappingFormatError(_(u'parameter "where" must be tuple: change(where=$where,change=$change)'),where=where,change=change)
#check: 'BOTSID' is required
#check: all values should be strings
for part in mpaths:
if not isinstance(part,dict):
raise botslib.MappingFormatError(_(u'parameter "where" must be dicts in a tuple: change(where=$where,change=$change)'),where=where,change=change)
if not 'BOTSID' in part:
raise botslib.MappingFormatError(_(u'section without "BOTSID": change(where=$where,change=$change)'),where=where,change=change)
for key,value in part.iteritems():
if not isinstance(key,basestring):
raise botslib.MappingFormatError(_(u'keys must be strings: change(where=$where,change=$change)'),where=where,change=change)
if not isinstance(value,basestring):
raise botslib.MappingFormatError(_(u'values must be strings: change(where=$where,change=$change)'),where=where,change=change)
#check change parameter
if not change or not isinstance(change,dict):
raise botslib.MappingFormatError(_(u'parameter "change" must be dict: change(where=$where,change=$change)'),where=where,change=change)
#remove 'BOTSID' from change.
#check: all values should be strings
change.pop('BOTSID','nep')
for key,value in change.iteritems():
if not isinstance(key,basestring):
raise botslib.MappingFormatError(_(u'keys in "change" must be strings: change(where=$where,change=$change)'),where=where,change=change)
if not isinstance(value,basestring) and value is not None:
raise botslib.MappingFormatError(_(u'values in "change" must be strings or "None": change(where=$where,change=$change)'),where=where,change=change)
#go get it!
terug = self._changecore(where,change)
botsglobal.logmap.debug(u'"%s" for change(where=%s,change=%s)',terug,str(where),str(change))
return terug
def _changecore(self,where,change): #diff from getcore
mpaths = where #diff from getcore
mpath = mpaths[0]
if self.record['BOTSID'] == mpath['BOTSID']: #is record-id equal to mpath-botsid? Not strictly needed, but gives much beter performance...
for part in mpath: #check all mpath-parts;
if part in self.record:
if mpath[part] == self.record[part]:
continue
else: #content of record-field and mpath-part do not match
return False
else: #not all parts of mpath are in record, so no match:
return False
else: #all parts are matched, and OK.
if len(mpaths) == 1: #mpath is exhausted; so we are there!!! #replace values with values in 'change'; delete if None
for key,value in change.iteritems():
if value is None:
self.record.pop(key,'dummy for pop')
else:
self.record[key]=value
return True
else:
for childnode in self.children:
terug = childnode._changecore(mpaths[1:],change) #search recursive for rest of mpaths #diff from getcore
if terug:
return terug
else: #no child has given a valid return
return False
else: #record-id is not equal to mpath-botsid, so no match
return False
def delete(self,*mpaths):
''' delete the last record of mpath if found (first: find/identify, than delete. '''
if not mpaths or not isinstance(mpaths,tuple):
raise botslib.MappingFormatError(_(u'must be dicts in tuple: delete($mpath)'),mpath=mpaths)
if len(mpaths) ==1:
raise botslib.MappingFormatError(_(u'only one dict: not allowed. Use different solution: delete($mpath)'),mpath=mpaths)
#check: None only allowed in last section of Mpath (check firsts sections)
#check: 'BOTSID' is required
#check: all values should be strings
for part in mpaths:
if not isinstance(part,dict):
raise botslib.MappingFormatError(_(u'must be dicts in tuple: delete($mpath)'),mpath=mpaths)
if not 'BOTSID' in part:
raise botslib.MappingFormatError(_(u'section without "BOTSID": delete($mpath)'),mpath=mpaths)
for key,value in part.iteritems():
if not isinstance(key,basestring):
raise botslib.MappingFormatError(_(u'keys must be strings: delete($mpath)'),mpath=mpaths)
if not isinstance(value,basestring):
raise botslib.MappingFormatError(_(u'values must be strings: delete($mpath)'),mpath=mpaths)
#go get it!
terug = bool(self._deletecore(*mpaths))
botsglobal.logmap.debug(u'"%s" for delete%s',terug,str(mpaths))
return terug #return False if not removed, return True if removed
def _deletecore(self,*mpaths):
mpath = mpaths[0]
if self.record['BOTSID'] == mpath['BOTSID']: #is record-id equal to mpath-botsid? Not strictly needed, but gives much beter performance...
for part in mpath: #check all mpath-parts;
if part in self.record:
if mpath[part] == self.record[part]:
continue
else: #content of record-field and mpath-part do not match
return 0
else: #not all parts of mpath are in record, so no match:
return 0
else: #all parts are matched, and OK.
if len(mpaths) == 1: #mpath is exhausted; so we are there!!!
return 2
else:
for i, childnode in enumerate(self.children):
terug = childnode._deletecore(*mpaths[1:]) #search recursive for rest of mpaths
if terug == 2: #indicates node should be removed
del self.children[i] #remove node
return 1 #this indicates: deleted successfull, do not remove anymore (no removal of parents)
if terug:
return terug
else: #no child has given a valid return
return 0
else: #record-id is not equal to mpath-botsid, so no match
return 0
def get(self,*mpaths):
''' get value of a field in a record from a edi-message
mpath is xpath-alike query to identify the record/field
function returns 1 value; return None if nothing found.
if more than one value can be found: first one is returned
starts searching in current node, then deeper
'''
if not mpaths or not isinstance(mpaths,tuple):
raise botslib.MappingFormatError(_(u'must be dicts in tuple: get($mpath)'),mpath=mpaths)
for part in mpaths:
if not isinstance(part,dict):
raise botslib.MappingFormatError(_(u'must be dicts in tuple: get($mpath)'),mpath=mpaths)
#check: None only allowed in last section of Mpath (check firsts sections)
#check: 'BOTSID' is required
#check: all values should be strings
for part in mpaths[:-1]:
if not 'BOTSID' in part:
raise botslib.MappingFormatError(_(u'section without "BOTSID": get($mpath)'),mpath=mpaths)
if not 'BOTSIDnr' in part:
part['BOTSIDnr'] = '1'
for key,value in part.iteritems():
if not isinstance(key,basestring):
raise botslib.MappingFormatError(_(u'keys must be strings: get($mpath)'),mpath=mpaths)
if not isinstance(value,basestring):
raise botslib.MappingFormatError(_(u'values must be strings: get($mpath)'),mpath=mpaths)
#check: None only allowed in last section of Mpath (check last section)
#check: 'BOTSID' is required
#check: all values should be strings
if not 'BOTSID' in mpaths[-1]:
raise botslib.MappingFormatError(_(u'last section without "BOTSID": get($mpath)'),mpath=mpaths)
if not 'BOTSIDnr' in mpaths[-1]:
mpaths[-1]['BOTSIDnr'] = '1'
count = 0
for key,value in mpaths[-1].iteritems():
if not isinstance(key,basestring):
raise botslib.MappingFormatError(_(u'keys must be strings in last section: get($mpath)'),mpath=mpaths)
if value is None:
count += 1
elif not isinstance(value,basestring):
raise botslib.MappingFormatError(_(u'values must be strings (or none) in last section: get($mpath)'),mpath=mpaths)
if count > 1:
raise botslib.MappingFormatError(_(u'max one "None" in last section: get($mpath)'),mpath=mpaths)
#go get it!
terug = self._getcore(*mpaths)
botsglobal.logmap.debug(u'"%s" for get%s',terug,str(mpaths))
return terug
def _getcore(self,*mpaths):
mpath = mpaths[0]
terug = 1 #if there is no 'None' in the mpath, but everything is matched, 1 is returned (like True)
if self.record['BOTSID'] == mpath['BOTSID']: #is record-id equal to mpath-botsid? Not strictly needed, but gives much beter performance...
for part in mpath: #check all mpath-parts;
if part in self.record:
if mpath[part] is None: #this is the field we are looking for; but not all matches have been made so remember value
terug = self.record[part][:] #copy to avoid memory problems
else: #compare values of mpath-part and recordfield
if mpath[part] == self.record[part]:
continue
else: #content of record-field and mpath-part do not match
return None
else: #not all parts of mpath are in record, so no match:
return None
else: #all parts are matched, and OK.
if len(mpaths) == 1: #mpath is exhausted; so we are there!!!
return terug
else:
for childnode in self.children:
terug = childnode._getcore(*mpaths[1:]) #search recursive for rest of mpaths
if terug:
return terug
else: #no child has given a valid return
return None
else: #record-id is not equal to mpath-botsid, so no match
return None
def getcount(self):
'''count the number of nodes/records uner the node/in whole tree'''
count = 0
if self.record:
count += 1 #count itself
for child in self.children:
count += child.getcount()
return count
def getcountoccurrences(self,*mpaths):
''' count number of occurences of mpath. Eg count nr of LIN's'''
count = 0
for value in self.getloop(*mpaths):
count += 1
return count
def getcountsum(self,*mpaths):
''' return the sum for all values found in mpath. Eg total number of ordered quantities.'''
count = decimal.Decimal(0)
mpathscopy = copy.deepcopy(mpaths)
for key,value in mpaths[-1].items():
if value is None:
del mpathscopy[-1][key]
for i in self.getloop(*mpathscopy):
value = i.get(mpaths[-1])
if value:
count += decimal.Decimal(value)
return unicode(count)
def getloop(self,*mpaths):
''' generator. Returns one by one the nodes as indicated in mpath
'''
#check validity mpaths
if not mpaths or not isinstance(mpaths,tuple):
raise botslib.MappingFormatError(_(u'must be dicts in tuple: getloop($mpath)'),mpath=mpaths)
for part in mpaths:
if not isinstance(part,dict):
raise botslib.MappingFormatError(_(u'must be dicts in tuple: getloop($mpath)'),mpath=mpaths)
if not 'BOTSID' in part:
raise botslib.MappingFormatError(_(u'section without "BOTSID": getloop($mpath)'),mpath=mpaths)
if not 'BOTSIDnr' in part:
part['BOTSIDnr'] = '1'
for key,value in part.iteritems():
if not isinstance(key,basestring):
raise botslib.MappingFormatError(_(u'keys must be strings: getloop($mpath)'),mpath=mpaths)
if not isinstance(value,basestring):
raise botslib.MappingFormatError(_(u'values must be strings: getloop($mpath)'),mpath=mpaths)
for terug in self._getloopcore(*mpaths):
botsglobal.logmap.debug(u'getloop %s returns "%s".',mpaths,terug.record)
yield terug
def _getloopcore(self,*mpaths):
''' recursive part of getloop()
'''
mpath = mpaths[0]
if self.record['BOTSID'] == mpath['BOTSID']: #found right record
for part in mpath:
if not part in self.record or mpath[part] != self.record[part]:
return
else: #all parts are checked, and OK.
if len(mpaths) == 1:
yield self
else:
for childnode in self.children:
for terug in childnode._getloopcore(*mpaths[1:]): #search recursive for rest of mpaths
yield terug
return
def getnozero(self,*mpaths):
terug = self.get(*mpaths)
try:
value = float(terug)
except TypeError:
return None
except ValueError:
return None
if value == 0:
return None
return terug
def put(self,*mpaths,**kwargs):
if not mpaths or not isinstance(mpaths,tuple):
raise botslib.MappingFormatError(_(u'must be dicts in tuple: put($mpath)'),mpath=mpaths)
for part in mpaths:
if not isinstance(part,dict):
raise botslib.MappingFormatError(_(u'must be dicts in tuple: put($mpath)'),mpath=mpaths)
#check: 'BOTSID' is required
#check: all values should be strings
for part in mpaths:
if not 'BOTSID' in part:
raise botslib.MappingFormatError(_(u'section without "BOTSID": put($mpath)'),mpath=mpaths)
if not 'BOTSIDnr' in part:
part['BOTSIDnr'] = '1'
for key,value in part.iteritems():
if value is None:
botsglobal.logmap.debug(u'"None" in put %s.',str(mpaths))
return False
if not isinstance(key,basestring):
raise botslib.MappingFormatError(_(u'keys must be strings: put($mpath)'),mpath=mpaths)
if kwargs and 'strip' in kwargs and kwargs['strip'] == False:
part[key] = unicode(value) #used for fixed ISA header of x12
else:
part[key] = unicode(value).strip() #leading and trailing spaces are stripped from the values
if self.sameoccurence(mpaths[0]):
self._putcore(*mpaths[1:])
else:
raise botslib.MappingRootError(_(u'error in root put "$mpath".'),mpath=mpaths[0])
botsglobal.logmap.debug(u'"True" for put %s',str(mpaths))
return True
def _putcore(self,*mpaths):
if not mpaths: #newmpath is exhausted, stop searching.
return True
for node in self.children:
if node.record['BOTSID']==mpaths[0]['BOTSID'] and node.sameoccurence(mpaths[0]):
node._putcore(*mpaths[1:])
return
else: #is not present in children, so append
self.append(Node(mpaths[0]))
self.children[-1]._putcore(*mpaths[1:])
def putloop(self,*mpaths):
if not mpaths or not isinstance(mpaths,tuple):
raise botslib.MappingFormatError(_(u'must be dicts in tuple: putloop($mpath)'),mpath=mpaths)
for part in mpaths:
if not isinstance(part,dict):
raise botslib.MappingFormatError(_(u'must be dicts in tuple: putloop($mpath)'),mpath=mpaths)
#check: 'BOTSID' is required
#check: all values should be strings
for part in mpaths:
if not 'BOTSID' in part:
raise botslib.MappingFormatError(_(u'section without "BOTSID": putloop($mpath)'),mpath=mpaths)
if not 'BOTSIDnr' in part:
part['BOTSIDnr'] = '1'
for key,value in part.iteritems():
if not isinstance(key,basestring):
raise botslib.MappingFormatError(_(u'keys must be strings: putloop($mpath)'),mpath=mpaths)
if value is None:
return False
#~ if not isinstance(value,basestring):
#~ raise botslib.MappingFormatError(_(u'values must be strings in putloop%s'%(str(mpaths)))
part[key] = unicode(value).strip()
if self.sameoccurence(mpaths[0]):
if len(mpaths)==1:
return self
return self._putloopcore(*mpaths[1:])
else:
raise botslib.MappingRootError(_(u'error in root putloop "$mpath".'),mpath=mpaths[0])
def _putloopcore(self,*mpaths):
if len(mpaths) ==1: #end of mpath reached; always make new child-node
self.append(Node(mpaths[0]))
return self.children[-1]
for node in self.children: #if first part of mpaths exists already in children go recursive
if node.record['BOTSID']==mpaths[0]['BOTSID'] and node.record['BOTSIDnr']==mpaths[0]['BOTSIDnr'] and node.sameoccurence(mpaths[0]):
return node._putloopcore(*mpaths[1:])
else: #is not present in children, so append a child, and go recursive
self.append(Node(mpaths[0]))
return self.children[-1]._putloopcore(*mpaths[1:])
def sameoccurence(self, mpath):
for key,value in self.record.iteritems():
if (key in mpath) and (mpath[key]!=value):
return False
else: #all equal keys have same values, thus both are 'equal'.
self.record.update(mpath)
return True
def sort(self,*mpaths):
global comparekey
comparekey = mpaths[1:]
self.children.sort(key=nodecompare)
| Python |
import sys
import os
import encodings
import codecs
import ConfigParser
import logging, logging.handlers
from django.utils.translation import ugettext as _
#Bots-modules
from botsconfig import *
import botsglobal
import botslib
class BotsConfig(ConfigParser.SafeConfigParser):
''' See SafeConfigParser.
'''
def get(self,section, option, default=''):
try:
return ConfigParser.SafeConfigParser.get(self,section,option)
except: #if there is no such section,option
if default == '':
raise botslib.BotsError(_(u'No entry "$entry" in section "$section" in "bots.ini".'),entry=option,section=section)
return default
def getint(self,section, option, default):
try:
return ConfigParser.SafeConfigParser.getint(self,section,option)
except:
return default
def getboolean(self,section, option, default):
try:
return ConfigParser.SafeConfigParser.getboolean(self,section,option)
except:
return default
def generalinit(configdir):
#Set Configdir
#Configdir MUST be importable. So configdir is relative to PYTHONPATH. Try several options for this import.
try: #configdir outside bots-directory: import configdir.settings.py
importnameforsettings = os.path.normpath(os.path.join(configdir,'settings')).replace(os.sep,'.')
settings = botslib.botsbaseimport(importnameforsettings)
except ImportError: #configdir is in bots directory: import bots.configdir.settings.py
try:
importnameforsettings = os.path.normpath(os.path.join('bots',configdir,'settings')).replace(os.sep,'.')
settings = botslib.botsbaseimport(importnameforsettings)
except ImportError: #set pythonpath to config directory first
if not os.path.exists(configdir): #check if configdir exists.
raise botslib.BotsError(_(u'In initilisation: path to configuration does not exists: "$path".'),path=configdir)
addtopythonpath = os.path.abspath(os.path.dirname(configdir))
#~ print 'add pythonpath for usersys',addtopythonpath
moduletoimport = os.path.basename(configdir)
sys.path.append(addtopythonpath)
importnameforsettings = os.path.normpath(os.path.join(moduletoimport,'settings')).replace(os.sep,'.')
settings = botslib.botsbaseimport(importnameforsettings)
#settings are accessed using botsglobal
botsglobal.settings = settings
#Find pathname configdir using imported settings.py.
configdirectory = os.path.abspath(os.path.dirname(settings.__file__))
#Read configuration-file bots.ini.
botsglobal.ini = BotsConfig()
cfgfile = open(os.path.join(configdirectory,'bots.ini'), 'r')
botsglobal.ini.readfp(cfgfile)
cfgfile.close()
#Set usersys.
#usersys MUST be importable. So usersys is relative to PYTHONPATH. Try several options for this import.
usersys = botsglobal.ini.get('directories','usersys','usersys')
try: #usersys outside bots-directory: import usersys
importnameforusersys = os.path.normpath(usersys).replace(os.sep,'.')
importedusersys = botslib.botsbaseimport(importnameforusersys)
except ImportError: #usersys is in bots directory: import bots.usersys
try:
importnameforusersys = os.path.normpath(os.path.join('bots',usersys)).replace(os.sep,'.')
importedusersys = botslib.botsbaseimport(importnameforusersys)
except ImportError: #set pythonpath to usersys directory first
if not os.path.exists(usersys): #check if configdir exists.
raise botslib.BotsError(_(u'In initilisation: path to configuration does not exists: "$path".'),path=usersys)
addtopythonpath = os.path.abspath(os.path.dirname(usersys)) #????
moduletoimport = os.path.basename(usersys)
#~ print 'add pythonpath for usersys',addtopythonpath
sys.path.append(addtopythonpath)
importnameforusersys = os.path.normpath(usersys).replace(os.sep,'.')
importedusersys = botslib.botsbaseimport(importnameforusersys)
#set directory settings in bots.ini************************************************************
botsglobal.ini.set('directories','botspath',botsglobal.settings.PROJECT_PATH)
botsglobal.ini.set('directories','config',configdirectory)
botsglobal.ini.set('directories','usersysabs',os.path.abspath(os.path.dirname(importedusersys.__file__))) #???Find pathname usersys using imported usersys
botsglobal.usersysimportpath = importnameforusersys
botssys = botsglobal.ini.get('directories','botssys','botssys')
botsglobal.ini.set('directories','botssys',botslib.join(botssys))
botsglobal.ini.set('directories','data',botslib.join(botssys,'data'))
botslib.dirshouldbethere(botsglobal.ini.get('directories','data'))
botsglobal.ini.set('directories','logging',botslib.join(botssys,'logging'))
botslib.dirshouldbethere(botsglobal.ini.get('directories','logging'))
botsglobal.ini.set('directories','templates',botslib.join(botsglobal.ini.get('directories','usersysabs'),'grammars/template/templates'))
botsglobal.ini.set('directories','templateshtml',botslib.join(botsglobal.ini.get('directories','usersysabs'),'grammars/templatehtml/templates'))
#set values in setting.py**********************************************************************
if botsglobal.ini.get('webserver','environment','development') == 'development': #values in bots.ini are also used in setting up cherrypy
settings.DEBUG = True
else:
settings.DEBUG = False
settings.TEMPLATE_DEBUG = settings.DEBUG
#set paths in settings.py:
#~ settings.FILE_UPLOAD_TEMP_DIR = os.path.join(settings.PROJECT_PATH, 'botssys/pluginsuploaded')
#start initializing bots charsets
initbotscharsets()
#set environment for django to start***************************************************************************************************
os.environ['DJANGO_SETTINGS_MODULE'] = importnameforsettings
initbotscharsets()
botslib.settimeout(botsglobal.ini.getint('settings','globaltimeout',10)) #
def initbotscharsets():
'''set up right charset handling for specific charsets (UNOA, UNOB, UNOC, etc).'''
codecs.register(codec_search_function) #tell python how to search a codec defined by bots. These are the codecs in usersys/charset
botsglobal.botsreplacechar = unicode(botsglobal.ini.get('settings','botsreplacechar',u' '))
codecs.register_error('botsreplace', botscharsetreplace) #define the ' botsreplace' error handling for codecs/charsets.
for key, value in botsglobal.ini.items('charsets'): #set aliases for charsets in bots.ini
encodings.aliases.aliases[key]=value
def codec_search_function(encoding):
try:
module,filename = botslib.botsimport('charsets',encoding)
except:
return None
else:
if hasattr(module,'getregentry'):
return module.getregentry()
else:
return None
def botscharsetreplace(info):
'''replaces an char outside a charset by a user defined char. Useful eg for fixed records: recordlength does not change. Do not know if this works for eg UTF-8...'''
return (botsglobal.botsreplacechar, info.start+1)
def initenginelogging():
convertini2logger={'DEBUG':logging.DEBUG,'INFO':logging.INFO,'WARNING':logging.WARNING,'ERROR':logging.ERROR,'CRITICAL':logging.CRITICAL}
# create main logger 'bots'
botsglobal.logger = logging.getLogger('bots')
botsglobal.logger.setLevel(logging.DEBUG)
# create rotating file handler
log_file = botslib.join(botsglobal.ini.get('directories','logging'),'engine.log')
rotatingfile = logging.handlers.RotatingFileHandler(log_file,backupCount=botsglobal.ini.getint('settings','log_file_number',10))
rotatingfile.setLevel(convertini2logger[botsglobal.ini.get('settings','log_file_level','ERROR')])
fileformat = logging.Formatter("%(asctime)s %(levelname)-8s %(name)s : %(message)s",'%Y%m%d %H:%M:%S')
rotatingfile.setFormatter(fileformat)
rotatingfile.doRollover() #each run a new log file is used; old one is rotated
# add rotating file handler to main logger
botsglobal.logger.addHandler(rotatingfile)
#logger for trace of mapping; tried to use filters but got this not to work.....
botsglobal.logmap = logging.getLogger('bots.map')
if not botsglobal.ini.getboolean('settings','mappingdebug',False):
botsglobal.logmap.setLevel(logging.CRITICAL)
#logger for reading edifile. is now used only very limited (1 place); is done with 'if'
#~ botsglobal.ini.getboolean('settings','readrecorddebug',False)
# create console handler
if botsglobal.ini.getboolean('settings','log_console',True):
console = logging.StreamHandler()
console.setLevel(logging.INFO)
consuleformat = logging.Formatter("%(levelname)-8s %(message)s")
console.setFormatter(consuleformat) # add formatter to console
botsglobal.logger.addHandler(console) # add console to logger
def connect():
#different connect code per tyoe of database
if botsglobal.settings.DATABASE_ENGINE == 'sqlite3':
#sqlite has some more fiddling; in separate file. Mainly because of some other method of parameter passing.
if not os.path.isfile(botsglobal.settings.DATABASE_NAME):
raise botslib.PanicError(_(u'Could not find database file for SQLite'))
import botssqlite
botsglobal.db = botssqlite.connect(database = botsglobal.settings.DATABASE_NAME)
elif botsglobal.settings.DATABASE_ENGINE == 'mysql':
import MySQLdb
from MySQLdb import cursors
botsglobal.db = MySQLdb.connect(host=botsglobal.settings.DATABASE_HOST,
port=int(botsglobal.settings.DATABASE_PORT),
db=botsglobal.settings.DATABASE_NAME,
user=botsglobal.settings.DATABASE_USER,
passwd=botsglobal.settings.DATABASE_PASSWORD,
cursorclass=cursors.DictCursor,
**botsglobal.settings.DATABASE_OPTIONS)
elif botsglobal.settings.DATABASE_ENGINE == 'postgresql_psycopg2':
import psycopg2
import psycopg2.extensions
import psycopg2.extras
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
botsglobal.db = psycopg2.connect( 'host=%s dbname=%s user=%s password=%s'%( botsglobal.settings.DATABASE_HOST,
botsglobal.settings.DATABASE_NAME,
botsglobal.settings.DATABASE_USER,
botsglobal.settings.DATABASE_PASSWORD),connection_factory=psycopg2.extras.DictConnection)
botsglobal.db.set_client_encoding('UNICODE')
| Python |
# Django settings for bots project.
import os
import bots
#*******settings for bots error reports**********************************
MANAGERS = ( #bots will send error reports to the MANAGERS
('name_manager', 'manager@domain.org'),
)
#~ EMAIL_HOST = 'smtp.gmail.com' #Default: 'localhost'
#~ EMAIL_PORT = '587' #Default: 25
#~ EMAIL_USE_TLS = True #Default: False
#~ EMAIL_HOST_USER = 'user@gmail.com' #Default: ''. Username to use for the SMTP server defined in EMAIL_HOST. If empty, Django won't attempt authentication.
#~ EMAIL_HOST_PASSWORD = '' #Default: ''. PASSWORD to use for the SMTP server defined in EMAIL_HOST. If empty, Django won't attempt authentication.
#~ SERVER_EMAIL = 'user@gmail.com' #Sender of bots error reports. Default: 'root@localhost'
#~ EMAIL_SUBJECT_PREFIX = '' #This is prepended on email subject.
#*********path settings*************************advised is not to change these values!!
PROJECT_PATH = os.path.abspath(os.path.dirname(bots.__file__))
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = PROJECT_PATH + '/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
#~ FILE_UPLOAD_TEMP_DIR = os.path.join(PROJECT_PATH, 'botssys/pluginsuploaded') #set in bots.ini
ROOT_URLCONF = 'bots.urls'
LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/'
LOGOUT_URL = '/logout/'
#~ LOGOUT_REDIRECT_URL = #??not such parameter; is set in urls
TEMPLATE_DIRS = (
os.path.join(PROJECT_PATH, 'templates'),
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
#*********database settings*************************
#django-admin syncdb --pythonpath='/home/hje/botsup' --settings='bots.config.settings'
#SQLITE:
DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = os.path.join(PROJECT_PATH, 'botssys/sqlitedb/botsdb') #path to database; if relative path: interpreted relative to bots root directory
DATABASE_USER = ''
DATABASE_PASSWORD = ''
DATABASE_HOST = ''
DATABASE_PORT = ''
DATABASE_OPTIONS = {}
#~ #MySQL:
#~ DATABASE_ENGINE = 'mysql'
#~ DATABASE_NAME = 'botsdb'
#~ DATABASE_USER = 'bots'
#~ DATABASE_PASSWORD = 'botsbots'
#~ DATABASE_HOST = '192.168.0.7'
#~ DATABASE_PORT = '3306'
#~ DATABASE_OPTIONS = {'use_unicode':True,'charset':'utf8',"init_command": 'SET storage_engine=INNODB'}
#PostgreSQL:
#~ DATABASE_ENGINE = 'postgresql_psycopg2'
#~ DATABASE_NAME = 'botsdb'
#~ DATABASE_USER = 'bots'
#~ DATABASE_PASSWORD = 'botsbots'
#~ DATABASE_HOST = '192.168.0.7'
#~ DATABASE_PORT = '5432'
#~ DATABASE_OPTIONS = {}
#*********sessions, cookies, log out time*************************
SESSION_EXPIRE_AT_BROWSER_CLOSE = True #True: always log in when browser is closed
SESSION_COOKIE_AGE = 3600 #seconds a user needs to login when no activity
SESSION_SAVE_EVERY_REQUEST = True #if True: SESSION_COOKIE_AGE is interpreted as: since last activity
#*********localization*************************
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/Amsterdam'
DATE_FORMAT = "Y-m-d"
DATETIME_FORMAT = "Y-m-d G:i"
TIME_FORMAT = "G:i"
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
#~ LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'en'
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
#*************************************************************************
#*********other django setting. please consult django docs.***************
#set in bots.ini
#~ DEBUG = True
#~ TEMPLATE_DEBUG = DEBUG
SITE_ID = 1
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'm@-u37qiujmeqfbu$daaaaz)sp^7an4u@h=wfx9dd$$$zl2i*x9#awojdc'
ADMINS = (
('bots', 'your_email@domain.com'),
)
#save uploaded file (=plugin) always to file. no path for temp storage is used, so system default is used.
FILE_UPLOAD_HANDLERS = (
"django.core.files.uploadhandler.TemporaryFileUploadHandler",
)
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
#'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'bots.persistfilters.FilterPersistMiddleware',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
'bots',
)
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.request",
)
| Python |
''' Base library for bots. Botslib should not import from other Bots-modules.'''
import sys
import os
import codecs
import traceback
import subprocess
import socket #to set a time-out for connections
import string
import urlparse
import urllib
import platform
import django
from django.utils.translation import ugettext as _
#Bots-modules
from botsconfig import *
import botsglobal #as botsglobal
def botsinfo():
return [
(_(u'server name'),botsglobal.ini.get('webserver','name','bots-webserver')),
(_(u'served at port'),botsglobal.ini.getint('webserver','port',8080)),
(_(u'platform'),platform.platform()),
(_(u'machine'),platform.machine()),
(_(u'python version'),sys.version),
(_(u'django version'),django.VERSION),
(_(u'bots version'),botsglobal.version),
(_(u'bots installation path'),botsglobal.ini.get('directories','botspath')),
(_(u'config path'),botsglobal.ini.get('directories','config')),
(_(u'botssys path'),botsglobal.ini.get('directories','botssys')),
(_(u'usersys path'),botsglobal.ini.get('directories','usersysabs')),
(u'DATABASE_ENGINE',botsglobal.settings.DATABASE_ENGINE),
(u'DATABASE_NAME',botsglobal.settings.DATABASE_NAME),
(u'DATABASE_USER',botsglobal.settings.DATABASE_USER),
(u'DATABASE_HOST',botsglobal.settings.DATABASE_HOST),
(u'DATABASE_PORT',botsglobal.settings.DATABASE_PORT),
(u'DATABASE_OPTIONS',botsglobal.settings.DATABASE_OPTIONS),
]
#**********************************************************/**
#**************getters/setters for some globals***********************/**
#**********************************************************/**
def get_minta4query():
''' get the first idta for queries etc.'''
return botsglobal.minta4query
def set_minta4query():
if botsglobal.minta4query: #if already set, do nothing
return
else:
botsglobal.minta4query = _Transaction.processlist[1] #set root-idta of current run
def set_minta4query_retry():
botsglobal.minta4query = get_idta_last_error()
return botsglobal.minta4query
def get_idta_last_error():
for row in query('''SELECT idta
FROM filereport
GROUP BY idta
HAVING MAX(statust) != %(statust)s''',
{'statust':DONE}):
#found incoming file with error
for row2 in query('''SELECT min(reportidta) as min
FROM filereport
WHERE idta = %(idta)s ''',
{'idta':row['idta']}):
return row2['min']
return 0 #if no error found.
def set_minta4query_crashrecovery():
''' set/return rootidta of last run - that is supposed to crashed'''
for row in query('''SELECT max(idta) as max
FROM ta
WHERE script= 0
'''):
if row['max'] is None:
return 0
botsglobal.minta4query = row['max']
return botsglobal.minta4query
return 0
def getlastrun():
return _Transaction.processlist[1] #get root-idta of last run
def setrouteid(routeid):
botsglobal.routeid = routeid
def getrouteid():
return botsglobal.routeid
def setpreprocessnumber(statusnumber):
botsglobal.preprocessnumber = statusnumber
def getpreprocessnumber():
terug = botsglobal.preprocessnumber
botsglobal.preprocessnumber +=2
return terug
#**********************************************************/**
#***************** class Transaction *********************/**
#**********************************************************/**
class _Transaction(object):
''' abstract class for db-ta.
This class is used for communication with db-ta.
'''
#filtering values fo db handling (to avoid unknown fields in db.
filterlist=['statust','status','divtext','parent','child','script','frompartner','topartner','fromchannel','tochannel','editype','messagetype','merge',
'testindicator','reference','frommail','tomail','contenttype','errortext','filename','charset','alt','idroute','nrmessages','retransmit',
'confirmasked','confirmed','confirmtype','confirmidta','envelope','botskey','cc']
processlist=[0] #stack for bots-processes. last one is the current process; starts with 1 element in list: root
def update(self,**ta_info):
''' Updates db-ta with named-parameters/dict.
Use a filter to update only valid fields in db-ta
'''
setstring = ','.join([key+'=%('+key+')s' for key in ta_info if key in _Transaction.filterlist])
if not setstring: #nothing to update
return
ta_info['selfid'] = self.idta #always set this...I'm not sure if this is needed...take no chances
cursor = botsglobal.db.cursor()
cursor.execute(u'''UPDATE ta
SET '''+setstring+ '''
WHERE idta=%(selfid)s''',
ta_info)
botsglobal.db.commit()
cursor.close()
def delete(self):
'''Deletes current transaction '''
cursor = botsglobal.db.cursor()
cursor.execute(u'''DELETE FROM ta
WHERE idta=%(selfid)s''',
{'selfid':self.idta})
botsglobal.db.commit()
cursor.close()
def failure(self):
'''Failure: deletes all children of transaction (and children of children etc)'''
cursor = botsglobal.db.cursor()
cursor.execute(u'''SELECT idta FROM ta
WHERE idta>%(rootidta)s
AND parent=%(selfid)s''',
{'selfid':self.idta,'rootidta':get_minta4query()})
rows = cursor.fetchall()
for row in rows:
ta=OldTransaction(row['idta'])
ta.failure()
cursor.execute(u'''DELETE FROM ta
WHERE idta>%(rootidta)s
AND parent=%(selfid)s''',
{'selfid':self.idta,'rootidta':get_minta4query()})
botsglobal.db.commit()
cursor.close()
def mergefailure(self):
'''Failure while merging: all parents of transaction get status OK (turn back)'''
cursor = botsglobal.db.cursor()
cursor.execute(u'''UPDATE ta
SET statust=%(statustnew)s
WHERE idta>%(rootidta)s
AND child=%(selfid)s
AND statust=%(statustold)s''',
{'selfid':self.idta,'statustold':DONE,'statustnew':OK,'rootidta':get_minta4query()})
botsglobal.db.commit()
cursor.close()
def syn(self,*ta_vars):
'''access of attributes of transaction as ta.fromid, ta.filename etc'''
cursor = botsglobal.db.cursor()
varsstring = ','.join(ta_vars)
cursor.execute(u'''SELECT ''' + varsstring + '''
FROM ta
WHERE idta=%(selfid)s''',
{'selfid':self.idta})
result = cursor.fetchone()
for key in result.keys():
setattr(self,key,result[key])
cursor.close()
def synall(self):
'''access of attributes of transaction as ta.fromid, ta.filename etc'''
cursor = botsglobal.db.cursor()
varsstring = ','.join(self.filterlist)
cursor.execute(u'''SELECT ''' + varsstring + '''
FROM ta
WHERE idta=%(selfid)s''',
{'selfid':self.idta})
result = cursor.fetchone()
for key in result.keys():
setattr(self,key,result[key])
cursor.close()
def copyta(self,status,**ta_info):
''' copy: make a new transaction, copy '''
script = _Transaction.processlist[-1]
cursor = botsglobal.db.cursor()
cursor.execute(u'''INSERT INTO ta (script, status, parent,frompartner,topartner,fromchannel,tochannel,editype,messagetype,alt,merge,testindicator,reference,frommail,tomail,charset,contenttype,filename,idroute,nrmessages,botskey)
SELECT %(script)s,%(newstatus)s,idta,frompartner,topartner,fromchannel,tochannel,editype,messagetype,alt,merge,testindicator,reference,frommail,tomail,charset,contenttype,filename,idroute,nrmessages,botskey
FROM ta
WHERE idta=%(selfid)s''',
{'selfid':self.idta,'script':script,'newstatus':status})
newidta = cursor.lastrowid
if not newidta: #if botsglobal.settings.DATABASE_ENGINE ==
cursor.execute('''SELECT lastval() as idta''')
newidta = cursor.fetchone()['idta']
botsglobal.db.commit()
cursor.close()
newdbta = OldTransaction(newidta)
newdbta.update(**ta_info)
return newdbta
class OldTransaction(_Transaction):
def __init__(self,idta,**ta_info):
'''Use old transaction '''
self.idta = idta
self.talijst=[]
for key in ta_info.keys(): #only used by trace
setattr(self,key,ta_info[key]) #could be done better, but SQLite does not support .items()
class NewTransaction(_Transaction):
def __init__(self,**ta_info):
'''Generates new transaction, returns key of transaction '''
updatedict = dict([(key,value) for key,value in ta_info.items() if key in _Transaction.filterlist])
updatedict['script'] = _Transaction.processlist[-1]
namesstring = ','.join([key for key in updatedict])
varsstring = ','.join(['%('+key+')s' for key in updatedict])
cursor = botsglobal.db.cursor()
cursor.execute(u'''INSERT INTO ta (''' + namesstring + ''')
VALUES (''' + varsstring + ''')''',
updatedict)
self.idta = cursor.lastrowid
if not self.idta:
cursor.execute('''SELECT lastval() as idta''')
self.idta = cursor.fetchone()['idta']
botsglobal.db.commit()
cursor.close()
class NewProcess(NewTransaction):
''' Used in logging of processes. Each process is placed on stack processlist'''
def __init__(self,functionname=''):
super(NewProcess,self).__init__(filename=functionname,status=PROCESS,idroute=getrouteid())
_Transaction.processlist.append(self.idta)
def update(self,**ta_info):
super(NewProcess,self).update(**ta_info)
_Transaction.processlist.pop()
def trace_origin(ta,where=None):
''' bots traces back all from the current step/ta.
where is a dict that is used to indicate a condition.
eg: {'status':EXTERNIN}
If bots finds a ta for which this is true, the ta is added to a list.
The list is returned when all tracing is done, and contains all ta's for which 'where' is True
'''
def trace_recurse(ta):
''' recursive
walk over ta's backward (to origin).
if condition is met, add the ta to a list
'''
for idta in get_parent(ta):
donelijst.append(idta)
taparent=OldTransaction(idta=idta)
taparent.synall()
for key,value in where.items():
if getattr(taparent,key) != value:
break
else: #all where-criteria are true; check if we already have this ta
teruglijst.append(taparent)
trace_recurse(taparent)
def get_parent(ta):
''' yields the parents of a ta '''
if ta.parent: #the is a parent via the normal parent-pointer
if ta.parent not in donelijst:
yield ta.parent
else: #no parent via parent-link, so look via child-link
for row in query('''SELECT idta
FROM ta
WHERE idta>%(rootidta)s
AND child=%(idta)s''',
{'idta':ta.idta,'rootidta':get_minta4query()}):
if row['idta'] in donelijst:
continue
yield row['idta']
donelijst = []
teruglijst = []
ta.syn('parent')
trace_recurse(ta)
return teruglijst
def addinfocore(change,where,wherestring):
''' core function for add/changes information in db-ta's.
where-dict selects db-ta's, change-dict sets values;
returns the number of db-ta that have been changed.
'''
if 'rootidta' not in where:
where['rootidta']=get_minta4query()
wherestring = ' idta > %(rootidta)s AND ' + wherestring
if 'statust' not in where: #by default: look only for statust is OK
where['statust']=OK
wherestring += ' AND statust = %(statust)s '
if 'statust' not in change: #by default: new ta is OK
change['statust']= OK
counter = 0 #count the number of dbta changed
for row in query(u'''SELECT idta FROM ta WHERE '''+wherestring,where):
counter += 1
ta_from = OldTransaction(row['idta'])
ta_from.copyta(**change) #make new ta from ta_from, using parameters from change
ta_from.update(statust=DONE) #update 'old' ta
return counter
def addinfo(change,where):
''' add/changes information in db-ta's by coping the ta's; the status is updated.
using only change and where dict.'''
wherestring = ' AND '.join([key+'=%('+key+')s ' for key in where]) #wherestring for copy & done
return addinfocore(change=change,where=where,wherestring=wherestring)
def updateinfo(change,where):
''' update info in ta if not set; no status change.
where-dict selects db-ta's, change-dict sets values;
returns the number of db-ta that have been changed.
'''
if 'statust' not in where:
where['statust']=OK
wherestring = ' AND '.join([key+'=%('+key+')s ' for key in where]) #wherestring for copy & done
if 'rootidta' not in where:
where['rootidta']=get_minta4query()
wherestring = ' idta > %(rootidta)s AND ' + wherestring
counter = 0 #count the number of dbta changed
for row in query(u'''SELECT idta FROM ta WHERE '''+wherestring,where):
counter += 1
ta_from = OldTransaction(row['idta'])
ta_from.synall()
defchange = {}
for key,value in change.items():
if value and not getattr(ta_from,key,None): #if there is a value and the key is not set in ta_from:
defchange[key]=value
ta_from.update(**defchange)
return counter
def changestatustinfo(change,where):
''' update info in ta if not set; no status change.
where-dict selects db-ta's, change is the new statust;
returns the number of db-ta that have been changed.
'''
if not isinstance(change,int):
raise BotsError(_(u'change not valid: expect status to be an integer. Programming error.'))
if 'statust' not in where:
where['statust']=OK
wherestring = ' AND '.join([key+'=%('+key+')s ' for key in where]) #wherestring for copy & done
if 'rootidta' not in where:
where['rootidta']=get_minta4query()
wherestring = ' idta > %(rootidta)s AND ' + wherestring
counter = 0 #count the number of dbta changed
for row in query(u'''SELECT idta FROM ta WHERE '''+wherestring,where):
counter += 1
ta_from = OldTransaction(row['idta'])
ta_from.update(statust = change)
return counter
#**********************************************************/**
#*************************Database***********************/**
#**********************************************************/**
def set_database_lock():
try:
change(u'''INSERT INTO mutex (mutexk) VALUES (1)''')
except:
return False
return True
def remove_database_lock():
change('''DELETE FROM mutex WHERE mutexk=1''')
def query(querystring,*args):
''' general query. yields rows from query '''
cursor = botsglobal.db.cursor()
cursor.execute(querystring,*args)
results = cursor.fetchall()
cursor.close()
for result in results:
yield result
def change(querystring,*args):
'''general inset/update. no return'''
cursor = botsglobal.db.cursor()
try:
cursor.execute(querystring,*args)
except: #IntegrityError from postgresql
botsglobal.db.rollback()
raise
botsglobal.db.commit()
cursor.close()
def unique(domein):
''' generate unique number within range domain.
uses db to keep track of last generated number
if domain not used before, initialize with 1.
'''
cursor = botsglobal.db.cursor()
try:
cursor.execute(u'''UPDATE uniek SET nummer=nummer+1 WHERE domein=%(domein)s''',{'domein':domein})
cursor.execute(u'''SELECT nummer FROM uniek WHERE domein=%(domein)s''',{'domein':domein})
nummer = cursor.fetchone()['nummer']
except: # ???.DatabaseError; domein does not exist
cursor.execute(u'''INSERT INTO uniek (domein) VALUES (%(domein)s)''',{'domein': domein})
nummer = 1
if nummer > sys.maxint-2:
nummer = 1
cursor.execute(u'''UPDATE uniek SET nummer=1 WHERE domein=%(domein)s''',{'domein':domein})
botsglobal.db.commit()
cursor.close()
return nummer
def checkunique(domein, receivednumber):
''' to check of received number is sequential: value is compare with earlier received value.
if domain not used before, initialize it . '1' is the first value expected.
'''
cursor = botsglobal.db.cursor()
try:
cursor.execute(u'''SELECT nummer FROM uniek WHERE domein=%(domein)s''',{'domein':domein})
expectednumber = cursor.fetchone()['nummer'] + 1
except: # ???.DatabaseError; domein does not exist
cursor.execute(u'''INSERT INTO uniek (domein,nummer) VALUES (%(domein)s,0)''',{'domein': domein})
expectednumber = 1
if expectednumber == receivednumber:
if expectednumber > sys.maxint-2:
nummer = 1
cursor.execute(u'''UPDATE uniek SET nummer=nummer+1 WHERE domein=%(domein)s''',{'domein':domein})
terug = True
else:
terug = False
botsglobal.db.commit()
cursor.close()
return terug
def keeptrackoflastretry(domein,newlastta):
''' keep track of last automaticretrycommunication/retry
if domain not used before, initialize it . '1' is the first value expected.
'''
cursor = botsglobal.db.cursor()
try:
cursor.execute(u'''SELECT nummer FROM uniek WHERE domein=%(domein)s''',{'domein':domein})
oldlastta = cursor.fetchone()['nummer']
except: # ???.DatabaseError; domein does not exist
cursor.execute(u'''INSERT INTO uniek (domein) VALUES (%(domein)s)''',{'domein': domein})
oldlastta = 1
cursor.execute(u'''UPDATE uniek SET nummer=%(nummer)s WHERE domein=%(domein)s''',{'domein':domein,'nummer':newlastta})
botsglobal.db.commit()
cursor.close()
return oldlastta
#**********************************************************/**
#*************************Logging, Error handling********************/**
#**********************************************************/**
def sendbotserrorreport(subject,reporttext):
if botsglobal.ini.getboolean('settings','sendreportiferror',False):
from django.core.mail import mail_managers
try:
mail_managers(subject, reporttext)
except:
botsglobal.logger.debug(u'Error in sending error report: %s',txtexc())
def log_session(f):
''' used as decorator.
The decorated functions are logged as processes.
Errors in these functions are caught and logged.
'''
def wrapper(*args,**argv):
try:
ta_session = NewProcess(f.__name__)
except:
botsglobal.logger.exception(u'System error - no new session made')
raise
try:
terug =f(*args,**argv)
except:
txt=txtexc()
botsglobal.logger.debug(u'Error in process: %s',txt)
ta_session.update(statust=ERROR,errortext=txt)
else:
ta_session.update(statust=DONE)
return terug
return wrapper
def txtexc():
''' Get text from last exception '''
if botsglobal.ini:
if botsglobal.ini.getboolean('settings','debug',False):
limit = None
else:
limit=0
else:
limit=0
#problems with char set for some input data that are reported in traces....so always decode this;
terug = traceback.format_exc(limit).decode('utf-8','ignore')
#~ botsglobal.logger.debug(u'exception %s',terug)
if hasattr(botsglobal,'dbinfo') and botsglobal.dbinfo.drivername != 'sqlite': #sqlite does not enforce strict lengths
return terug[-1848:] #filed isze is 2048; but more text can be prepended.
else:
return terug
class ErrorProcess(NewTransaction):
''' Used in logging of errors in processes.
20110828: used in communication.py
'''
def __init__(self,functionname='',errortext='',channeldict=None):
fromchannel = tochannel = ''
if channeldict:
if channeldict['inorout'] == 'in':
fromchannel = channeldict['idchannel']
else:
tochannel = channeldict['idchannel']
super(ErrorProcess,self).__init__(filename=functionname,status=PROCESS,idroute=getrouteid(),statust=ERROR,errortext=errortext,fromchannel=fromchannel,tochannel=tochannel)
#**********************************************************/**
#*************************File handling os.path, imports etc***********************/**
#**********************************************************/**
def botsbaseimport(modulename):
''' Do a dynamic import.
Errors/exceptions are handled in calling functions.
'''
if modulename.startswith('.'):
modulename = modulename[1:]
module = __import__(modulename)
components = modulename.split('.')
for comp in components[1:]:
module = getattr(module, comp)
return module
def botsimport(soort,modulename):
''' import modules from usersys.
return: imported module, filename imported module;
if could not be found or error in module: raise
'''
try: #__import__ is picky on the charset used. Might be different for different OS'es. So: test if charset is us-ascii
modulename.encode('ascii')
except UnicodeEncodeError: #if not us-ascii, convert to punycode
modulename = modulename.encode('punycode')
modulepath = '.'.join((botsglobal.usersysimportpath,soort,modulename)) #assemble import string
modulefile = join(botsglobal.usersysimportpath,soort,modulename) #assemble abs filename for errortexts
try:
module = botsbaseimport(modulepath)
except ImportError: #if module not found
botsglobal.logger.debug(u'no import of "%s".',modulefile)
raise
except: #other errors
txt=txtexc()
raise ScriptImportError(_(u'import error in "$module", error:\n$txt'),module=modulefile,txt=txt)
else:
botsglobal.logger.debug(u'import "%s".',modulefile)
return module,modulefile
def join(*paths):
'''Does does more as join.....
- join the paths (compare os.path.join)
- if path is not absolute, interpretate this as relative from bots directory.
- normalize'''
return os.path.normpath(os.path.join(botsglobal.ini.get('directories','botspath'),*paths))
def dirshouldbethere(path):
if path and not os.path.exists(path):
os.makedirs(path)
return True
return False
def abspath(soort,filename):
''' get absolute path for internal files; path is a section in bots.ini '''
directory = botsglobal.ini.get('directories',soort)
return join(directory,filename)
def abspathdata(filename):
''' abspathdata if filename incl dir: return absolute path; else (only filename): return absolute path (datadir)'''
if '/' in filename: #if filename already contains path
return join(filename)
else:
directory = botsglobal.ini.get('directories','data')
datasubdir = filename[:-3]
if not datasubdir:
datasubdir = '0'
return join(directory,datasubdir,filename)
def opendata(filename,mode,charset=None,errors=None):
''' open internal data file. if no encoding specified: read file raw/binary.'''
filename = abspathdata(filename)
if 'w' in mode:
dirshouldbethere(os.path.dirname(filename))
if charset:
return codecs.open(filename,mode,charset,errors)
else:
return open(filename,mode)
def readdata(filename,charset=None,errors=None):
''' read internal data file in memory using the right encoding or no encoding'''
f = opendata(filename,'rb',charset,errors)
content = f.read()
f.close()
return content
#**********************************************************/**
#*************************calling modules, programs***********************/**
#**********************************************************/**
def runscript(module,modulefile,functioninscript,**argv):
''' Execute user script. Functioninscript is supposed to be there; if not AttributeError is raised.
Often is checked in advance if Functioninscript does exist.
'''
botsglobal.logger.debug(u'run user script "%s" in "%s".',functioninscript,modulefile)
functiontorun = getattr(module, functioninscript)
try:
return functiontorun(**argv)
except:
txt=txtexc()
raise ScriptError(_(u'Script file "$filename": "$txt".'),filename=modulefile,txt=txt)
def tryrunscript(module,modulefile,functioninscript,**argv):
if module and hasattr(module,functioninscript):
runscript(module,modulefile,functioninscript,**argv)
return True
return False
def runscriptyield(module,modulefile,functioninscript,**argv):
botsglobal.logger.debug(u'run user (yield) script "%s" in "%s".',functioninscript,modulefile)
functiontorun = getattr(module, functioninscript)
try:
for result in functiontorun(**argv):
yield result
except:
txt=txtexc()
raise ScriptError(_(u'Script file "$filename": "$txt".'),filename=modulefile,txt=txt)
def runexternprogram(*args):
botsglobal.logger.debug(u'run external program "%s".',args)
path = os.path.dirname(args[0])
try:
subprocess.call(list(args),cwd=path)
except:
txt=txtexc()
raise OSError(_(u'error running extern program "%(program)s", error:\n%(error)s'%{'program':args,'error':txt}))
#**********************************************************/**
#***************############### mdn #############
#**********************************************************/**
def checkconfirmrules(confirmtype,**kwargs):
terug = False #boolean to return: ask a confirm of not?
for confirmdict in query(u'''SELECT ruletype,idroute,idchannel_id as idchannel,frompartner_id as frompartner,topartner_id as topartner,editype,messagetype,negativerule
FROM confirmrule
WHERE active=%(active)s
AND confirmtype=%(confirmtype)s
ORDER BY negativerule ASC
''',
{'active':True,'confirmtype':confirmtype}):
if confirmdict['ruletype']=='all':
terug = not confirmdict['negativerule']
elif confirmdict['ruletype']=='route':
if 'idroute' in kwargs and confirmdict['idroute'] == kwargs['idroute']:
terug = not confirmdict['negativerule']
elif confirmdict['ruletype']=='channel':
if 'idchannel' in kwargs and confirmdict['idchannel'] == kwargs['idchannel']:
terug = not confirmdict['negativerule']
elif confirmdict['ruletype']=='frompartner':
if 'frompartner' in kwargs and confirmdict['frompartner'] == kwargs['frompartner']:
terug = not confirmdict['negativerule']
elif confirmdict['ruletype']=='topartner':
if 'topartner' in kwargs and confirmdict['topartner'] == kwargs['topartner']:
terug = not confirmdict['negativerule']
elif confirmdict['ruletype']=='messagetype':
if 'editype' in kwargs and confirmdict['editype'] == kwargs['editype'] and 'messagetype' in kwargs and confirmdict['messagetype'] == kwargs['messagetype']:
terug = not confirmdict['negativerule']
#~ print '>>>>>>>>>>>>', terug,confirmtype,kwargs
return terug
#**********************************************************/**
#***************############### codecs #############
#**********************************************************/**
def getcodeccanonicalname(codecname):
c = codecs.lookup(codecname)
return c.name
def checkcodeciscompatible(charset1,charset2):
''' check if charset of edifile) is 'compatible' with charset of channel: OK; else: raise exception
'''
#some codecs are upward compatible (subsets); charsetcompatible is used to check if charsets are upward compatibel with each other.
#some charset are 1 byte (ascii, ISO-8859-*). others are more bytes (UTF-16, utf-32. UTF-8 is more bytes, but is ascii compatible.
charsetcompatible = {
'unoa':['unob','ascii','utf-8','iso8859-1','cp1252','iso8859-15'],
'unob':['ascii','utf-8','iso8859-1','cp1252','iso8859-15'],
'ascii':['utf-8','iso8859-1','cp1252','iso8859-15'],
}
charset_edifile = getcodeccanonicalname(charset1)
charset_channel = getcodeccanonicalname(charset2)
if charset_channel == charset_edifile:
return True
if charset_edifile in charsetcompatible and charset_channel in charsetcompatible[charset_edifile]:
return True
raise CommunicationOutError(_(u'Charset "$charset2" for channel not matching with charset "$charset1" for edi-file.'),charset1=charset1,charset2=charset2)
#**********************************************************/**
#***************############### misc. #############
#**********************************************************/**
class Uri(object):
''' generate uri from parts. '''
def __init__(self,**kw):
self.uriparts = dict(scheme='',username='',password='',host='',port='',path='',parameters='',filename='',query={},fragment='')
self.uriparts.update(**kw)
def update(self,**kw):
self.uriparts.update(kw)
return self.uri
@property #the getter
def uri(self):
if not self.uriparts['scheme']:
raise BotsError(_(u'No scheme in uri.'))
#assemble complete host name
fullhost = ''
if self.uriparts['username']: #always use both?
fullhost += self.uriparts['username'] + '@'
if self.uriparts['host']:
fullhost += self.uriparts['host']
if self.uriparts['port']:
fullhost += ':' + str(self.uriparts['port'])
#assemble complete path
if self.uriparts['path'].strip().endswith('/'):
fullpath = self.uriparts['path'] + self.uriparts['filename']
else:
fullpath = self.uriparts['path'] + '/' + self.uriparts['filename']
if fullpath.endswith('/'):
fullpath = fullpath[:-1]
_uri = urlparse.urlunparse((self.uriparts['scheme'],fullhost,fullpath,self.uriparts['parameters'],urllib.urlencode(self.uriparts['query']),self.uriparts['fragment']))
if not _uri:
raise BotsError(_(u'Uri is empty.'))
return _uri
def settimeout(milliseconds):
socket.setdefaulttimeout(milliseconds) #set a time-out for TCP-IP connections
def countunripchars(value,delchars):
return len([c for c in value if c not in delchars])
def updateunlessset(updatedict,fromdict):
for key, value in fromdict.items():
if key not in updatedict:
updatedict[key]=value
#**********************************************************/**
#************** Exception classes ***************************
#**********************************************************/**
class BotsError(Exception):
def __init__(self, msg,**kwargs):
self.msg = msg
self.kwargs = kwargs
def __str__(self):
s = string.Template(self.msg).safe_substitute(self.kwargs)
return s.encode(u'utf-8',u'ignore')
class CodeConversionError(BotsError):
pass
class CommunicationError(BotsError):
pass
class CommunicationInError(BotsError):
pass
class CommunicationOutError(BotsError):
pass
class EanError(BotsError):
pass
class GrammarError(BotsError): #grammar.py
pass
class InMessageError(BotsError):
pass
class InMessageFieldError(BotsError):
pass
class LockedFileError(BotsError):
pass
class MessageError(BotsError):
pass
class MappingRootError(BotsError):
pass
class MappingFormatError(BotsError): #mpath is not valid; mapth will mostly come from mapping-script
pass
class OutMessageError(BotsError):
pass
class PanicError(BotsError):
pass
class PersistError(BotsError):
pass
class PluginError(BotsError):
pass
class ScriptImportError(BotsError): #can not find script; not for errors in a script
pass
class ScriptError(BotsError): #runtime errors in a script
pass
class TraceError(BotsError):
pass
class TraceNotPickedUpError(BotsError):
pass
class TranslationNotFoundError(BotsError):
pass
| Python |
"""
sef2bots.py
Command line params: sourcefile.sef targetfile.py
Optional command line params: -seq, -struct
Converts a SEF grammar into a Bots grammar. If targetfile exists (and is writeable),
it will be overwritten.
If -seq is specified, field names in record definitions will be
sequential (TAG01, TAG02, ..., where TAG is the record tag) instead of
the 'normal' field names.
If -struct is specified, only the Bots grammar variable 'structure' will be
constructed, i.e. the 'recorddefs' variable will be left out.
Parses the .SETS, .SEGS, .COMS and .ELMS sections. Any other sections are ignored.
(Mostly) assumes correct SEF syntax. May well break on some syntax errors.
If there are multiple .SETS sections, only the last one is processed. If there are
multiple message definitions in the (last) .SETS section, only the last one is
processed.
If there are multiple definitions of a segment, only the first one is taken
into account.
If there are multiple definitions of a field, only the last one is taken into
account.
Skips ^ and ignores .!$-&*@ in segment/field refs.
Also ignores syntax rules and dependency notes.
Changes seg max of '>1' to 99999 and elm maxlength to 99999 if 0 or > 99999
If you don't like that, change the 'constants' MAXMAX and/or MAXLEN below
"""
MAXMAX = 99999 # for dealing with segs/groups with max '>1'
MAXLEN = 99999 # for overly large elm maxlengths
TAB = ' '
import sys
import os
import copy
import atexit
import traceback
def showusage(scriptname):
print "Usage: python %s [-seq] [-nostruct] [-norecords] sourcefile targetfile" % scriptname
print " Convert SEF grammar in <sourcefile> into Bots grammar in <targetfile>."
print " Option -seq : use sequential numbered fields in record definitions instead of field names/ID's."
print " Option -nostruct : the 'structure' will not be written."
print " Option -norecords : the 'records' will not be written."
print
sys.exit(0)
class SEFError(Exception):
pass
class StructComp(object):
""" For components of the Bots grammar variable 'structure' """
def __init__(self, tag, min, max, sub = None):
self.id = tag
self.min = min
self.max = max
if sub:
self.sub = sub
else:
self.sub = []
def tostring(self, tablevel = 0):
s = tablevel*TAB + "{ID: '%s', MIN: %d, MAX: %d" % (self.id, self.min, self.max)
if self.sub:
s += ", LEVEL: [\n" \
+ ",\n".join([subcomp.tostring(tablevel + 1) for subcomp in self.sub]) + "," \
+ "\n" + tablevel * TAB + "]"
s += "}"
return s
class RecDef(object):
""" For records/segments; these end up in the Bots grammar variable 'recorddefs' """
def __init__(self, tag, sub = None):
self.id = tag
if sub:
self.sub = sub
else:
self.sub = []
def tostring(self, useseq = False, tablevel = 0):
return tablevel*TAB + \
"'%s': [\n"%(self.id) + \
"\n".join([c.tostring(useseq, tablevel+1) for c in self.sub]) +\
"\n" + \
tablevel*TAB + "],"
class FieldDef(object):
""" For composite and non-composite fields """
def __init__(self, tag, req = 'C', minlen = '', maxlen = '', type = 'AN', sub = None, freq = 1, seq = None):
self.id = tag
self.req = req
self.minlen = minlen
self.maxlen = maxlen
self.type = type
self.sub = sub
if not sub:
self.sub = []
self.freq = freq
self.seq = seq
def tostring(self, useseq = False, tablevel = 0):
if not useseq:
fldname = self.id
else:
fldname = self.seq
if not self.sub:
if self.minlen.strip() == '1':
return tablevel * TAB + "['%s', '%s', %s, '%s']" %\
(fldname, self.req, self.maxlen, self.type) + ","
else:
return tablevel * TAB + "['%s', '%s', (%s, %s), '%s']" %\
(fldname, self.req, self.minlen, self.maxlen, self.type) + ","
else:
return tablevel * TAB + "['%s', '%s', [\n" % (fldname, self.req) \
+ "\n".join([field.tostring(useseq, tablevel + 1) for field in self.sub]) \
+ "\n" + tablevel * TAB + "]],"
def split2(line, seps):
"""
Split <line> on whichever character in <seps> occurs in <line> first.
Return pair (line_up_to_first_sep_found, first_sep_found_plus_rest_of_line)
If none of <seps> occurs, return pair ('', <line>)
"""
i = 0
length = len(line)
while i < length and line[i] not in seps:
i += 1
if i == length:
return '', line
return line[:i], line[i:]
def do_set(line):
"""
Reads the (current) .SETS section and converts it into a Bots grammar 'structure'.
Returns the *contents* of the structure, as a string.
"""
definition = line.split('=')
line = definition[1].lstrip('^')
comps = readcomps(line)
tree = comps[0]
tree.sub = comps[1:]
return tree.tostring()
def readcomps(line):
""" Reads all components from a .SETS line, and returns them in a nested list """
comps = []
while line:
comp, line = readcomp(line)
comps.append(comp)
#~ displaystructure(comps)
return comps
def displaystructure(comps,tablevel=0):
for i in comps:
print tablevel*TAB, i.id,i.min,i.max
if i.sub:
displaystructure(i.sub,tablevel+1)
def readcomp(line):
"""
Reads a component, which can be either a segment or a segment group.
Returns pair (component, rest_of_line)
"""
discard, line = split2(line, "[{")
if not line:
return None, ''
if line[0] == '[':
return readseg(line)
if line[0] == '{':
return readgroup(line)
raise SEFError("readcomp() - unexpected character at start of: %s" % line)
def readseg(line):
""" Reads a single segment. Returns pair (segment, rest_of_line) """
discard, line = line.split('[', 1)
segstr, line = line.split(']', 1)
components = segstr.split(',')
num = len(components)
maxstr = ''
if num == 3:
tag, req, maxstr = components
elif num == 2:
tag, req = components
elif num == 1:
tag, req = components[0], 'C'
if req == 'M':
min = 1
else:
min = 0
if tag[0] in ".!$-&":
tag = tag[1:]
if '*' in tag:
tag = tag.split('*')[0]
if '@' in tag:
tag = tag.split('@')[0]
if tag.upper() == 'LS':
print "LS segment found"
if not maxstr:
max = 1
elif maxstr == '>1':
max = MAXMAX
print "Changed max for seg '%s' to %d (orig. %s)" % (tag, MAXMAX, maxstr)
else:
max = int(maxstr)
return StructComp(tag, min, max), line
def readgroup(line):
""" Reads a segment group. Returns pair (segment_group, rest_of_line) """
discard, line = line.split('{', 1)
#~ print '>>',line
tag, line = split2(line, ':+-[{')
#~ print '>>',tag,'>>',line
maxstr = ''
if line[0] == ':': # next element can be group.max
maxstr, line = split2(line[1:], '+-[{')
#~ print '>>',line
discard, line = split2(line, "[{")
group = StructComp(tag, 0, 0) # dummy values for group. This is later on adjusted
done = False
while not done:
if not line or line[0] == '}':
done = True
else:
comp, line = readcomp(line)
group.sub.append(comp)
if group.sub:
header = group.sub[0]
group.id = header.id #use right tag for header segment
if header.min > group.min:
group.min = header.min
group.sub = group.sub[1:]
if not maxstr:
group.max = 1
else:
if maxstr != '>1':
group.max = int(maxstr)
else:
group.max = MAXMAX
if tag:
oldtag = tag
else:
oldtag = group.id
print "Changed max for group '%s' to %d (orig. %s)" % (oldtag, MAXMAX, maxstr)
return group, line[1:]
def comdef(line, issegdef = False):
"""
Reads segment or composite definition (syntactically identical; defaults to composite).
Returns RecDef (for segment) or FieldDef (for composite)
"""
tag, spec = line.split('=')
if issegdef:
com = RecDef(tag)
else:
com = FieldDef(tag)
com.sub = getfields(spec)[0]
return com
def getfields(line, isgroup = False):
""" Returns pair (fieldlist, rest_of_line) """
if isgroup and line[0] == '}':
return [], line[1:]
if not isgroup and not line:
return [], ''
if not isgroup and line[0] in ",+":
return [], line[1:]
if line[0] == '[':
field, line = getfield(line[1:])
multifield = [field]
for i in range(1, field.freq):
extrafield = copy.deepcopy(field)
extrafield.req = 'C'
multifield.append(extrafield)
fields, line = getfields(line, isgroup)
return multifield + fields, line
if line[0] == '{':
multstr, line = split2(line[1:], "[{")
if not multstr:
mult = 1
else:
mult = int(multstr)
group, line = getfields(line, True)
repgroup = []
for i in range(mult):
repgroup += copy.deepcopy(group)
fields, line = getfields(line, isgroup)
return repgroup + fields, line
def getfield(line):
""" Returns pair (single_field_ref, rest_of_line) """
splits = line.split(']', 1)
field = fielddef(splits[0])
if len(splits) == 1:
return field, ''
return field, splits[1]
def fielddef(line):
"""
Get a field's tag, its req (M or else C), its min and max lengths, and its frequency (repeat count).
Return FieldDef
"""
if line[0] in ".!$-&":
line = line[1:]
if ',' not in line:
req, freq = 'C', 1
else:
splits = line.split(',')
num = len(splits)
if num == 3:
line, req, freq = splits
freq = int(freq)
elif num == 2:
(line, req), freq = splits, 1
else:
line, req, freq = splits[0], 'C', 1
if req != 'M':
req = 'C'
if ';' not in line:
lenstr = ''
else:
line, lenstr = line.split(';')
if '@' in line:
line, discard = line.split('@', 1)
if not lenstr:
minlen = maxlen = ''
else:
if ':' in lenstr:
minlen, maxlen = lenstr.split(':')
else:
minlen = lenstr
return FieldDef(line, req = req, minlen = minlen, maxlen = maxlen, freq = freq)
def elmdef(line):
""" Reads elm definition (min and max lengths and data type), returns FieldDef """
tag, spec = line.split('=')
type, minlenstr, maxlenstr = spec.split(',')
try:
maxlen = int(maxlenstr)
except ValueError:
maxlen = 0
if maxlen == 0 or maxlen > MAXLEN:
print "Changed max length for elm '%s' to %d (orig. %s)" % (tag, MAXLEN, maxlenstr)
maxlenstr = str(MAXLEN)
elm = FieldDef(tag, minlen = minlenstr, maxlen = maxlenstr, type = type)
return elm
def getelmsinfo(elms, coms):
"""
Get types and lengths from elm defs into com defs,
and rename multiple occurrences of subfields
"""
for comid in coms:
com = coms[comid]
counters = {}
sfids = [sf.id for sf in com.sub]
for i, sfield in enumerate(com.sub):
sfield.seq = "%02d" % (i + 1)
if sfield.id not in elms:
raise SEFError("getelmsinfo() - no subfield definition found for element '%s'" % sfield.id)
elm = elms[sfield.id]
if not sfield.minlen:
sfield.minlen = elm.minlen
if not sfield.maxlen:
sfield.maxlen = elm.maxlen
sfield.type = elm.type
if sfield.id not in counters:
counters[sfield.id] = 1
else:
counters[sfield.id] += 1
if counters[sfield.id] > 1 or sfield.id in sfids[i + 1:]:
sfield.id += "#%d" % counters[sfield.id]
def getfieldsinfo(elms, coms, segs):
"""
Get types and lengths from elm defs and com defs into seg defs,
and rename multiple occurrences of fields. Also rename subfields
of composites to include the name of their parents.
Finally, add the necessary BOTSID element.
"""
for seg in segs:
counters = {}
fids = [f.id for f in seg.sub]
for i, field in enumerate(seg.sub):
field.seq = "%s%02d" % (seg.id, i + 1)
iscomposite = False
if field.id in elms:
elm = elms[field.id]
field.type = elm.type
if not field.minlen:
field.minlen = elm.minlen
if not field.maxlen:
field.maxlen = elm.maxlen
elif field.id in coms:
iscomposite = True
com = coms[field.id]
field.sub = copy.deepcopy(com.sub)
else:
raise SEFError("getfieldsinfo() - no field definition found for element '%s'" % field.id)
if not field.id in counters:
counters[field.id] = 1
else:
counters[field.id] += 1
if counters[field.id] > 1 or field.id in fids[i + 1:]:
field.id += "#%d" % counters[field.id]
if iscomposite:
for sfield in field.sub:
sfield.id = field.id + '.' + sfield.id
sfield.seq = field.seq + '.' + sfield.seq
seg.sub.insert(0, FieldDef('BOTSID', req = 'M', minlen = "1", maxlen = "3", type = "AN", seq = 'BOTSID'))
def convertfile(infile, outfile, useseq, nostruct, norecords,edifactversionID):
struct = ""
segdefs, segdict, comdefs, elmdefs = [], {}, {}, {}
# segdict just keeps a list of segs already found, so they don't get re-defined
in_sets = in_segs = in_coms = in_elms = False
#*******reading sef grammar***********************
for line in infile:
line = line.strip('\n')
if line:
if line[0] == '*': # a comment, skip
pass
elif line[0] == '.':
line = line.upper()
in_sets = in_segs = in_coms = in_elms = False
if line == '.SETS':
in_sets = True
elif line == '.SEGS':
in_segs = True
elif line == '.COMS':
in_coms = True
elif line == '.ELMS':
in_elms = True
else:
if in_sets:
struct = do_set(line)
elif not norecords: #if record need to be written
if in_segs:
seg = comdef(line, issegdef = True)
# if multiple defs for this seg, only do first one
if seg.id not in segdict:
segdict[seg.id] = 1
segdefs.append(seg)
elif in_coms:
com = comdef(line)
comdefs[com.id] = com
elif in_elms:
elm = elmdef(line)
elmdefs[elm.id] = elm
#*****writing bots grammar **************
outfile.write('from bots.botsconfig import *\n')
if not nostruct: #if structure: need syntax
outfile.write('from edifactsyntax3 import syntax\n')
if norecords: #if record need to import thee
outfile.write('from records%s import recorddefs\n\n'%edifactversionID)
#****************************************
if not nostruct:
outfile.write("\nstructure = [\n%s\n]\n" % struct)
if not norecords:
getelmsinfo(elmdefs, comdefs)
getfieldsinfo(elmdefs, comdefs, segdefs)
outfile.write("\nrecorddefs = {\n%s\n}\n" % "\n".join([seg.tostring(useseq) for seg in segdefs]))
def start(args):
useseq, nostruct, norecords, infilename, outfilename = False, False, False, None, None
for arg in args:
if not arg:
continue
if arg in ["-h", "--help", "?", "/?", "-?"]:
showusage(args[0].split(os.sep)[-1])
if arg == "-seq":
useseq = True
elif arg == "-nostruct":
nostruct = True
elif arg == "-norecords":
norecords = True
elif not infilename:
infilename = arg
elif not outfilename:
outfilename = arg
else:
showusage(args[0].split(os.sep)[-1])
if not infilename or not outfilename:
showusage(args[0].split(os.sep)[-1])
#************************************
infile = open(infilename, 'r')
outfile = open(outfilename, 'w')
edifactversionID = os.path.splitext(os.path.basename(outfilename))[0][6:]
print ' Convert sef->bots "%s".'%(outfilename)
convertfile(infile, outfile, useseq, nostruct, norecords,edifactversionID)
infile.close()
outfile.close()
if __name__ == "__main__":
try:
start(sys.argv[1:])
except:
traceback.print_exc()
else:
print "Done"
| Python |
#constants/definitions for Bots
#to be used as from bots.config import *
#for statust in ta:
OPEN = 0 #Bots always closes transaction. OPEN is severe error
ERROR = 1 #error in transaction.
OK = 2 #successfull, result is 'save'. But processing has stopped: next step with error, or no next steps defined
DONE = 3 #successfull, and result is picked up by next step
#for status in ta:
PROCESS = 1
DISCARD= 3
EXTERNIN = 200 #transaction is OK; file is exported; out of reach
RAWIN = 210 #the file as received, unprocessed; eg mail is in email-format (headers, body, attachments)
MIMEIN = 215 #mime is checked and read; mime-info (sender, receiver) is in db-ta
FILEIN = 220 #received edifile; ready for further use
SET_FOR_PROCESSING = 230
TRANSLATE = 300 #file to be translated
PARSED = 310 #the edifile is lexed and parsed
SPLITUP = 320 #the edimessages in the PARSED edifile have been split up
TRANSLATED = 330 #edimessage is result of translation
MERGED = 400 #is enveloped
FILEOUT = 500 #edifile ready to be 'send' (just the edi-file)
RAWOUT = 510 #file in send format eg email format (including headers, body, attachemnts)
EXTERNOUT = 520 #transaction is complete; file is exported; out of reach
#grammar.structure: keys in grammarrecords
ID = 0
MIN = 1
MAX = 2
COUNT = 3
LEVEL = 4
MPATH = 5
FIELDS = 6
QUERIES = 7
SUBTRANSLATION = 8
BOTSIDnr = 9
#grammar.recorddefs: dict keys for fields of record er: record[FIELDS][ID] == 'C124.0034'
#already definedID = 0
MANDATORY = 1
LENGTH = 2
SUBFIELDS = 2 #for composites
FORMAT = 3 #format in grammar file
ISFIELD = 4
DECIMALS = 5
MINLENGTH = 6
BFORMAT = 7 #internal bots format; formats in grammar are convertd to bformat
#modules inmessage, outmessage; record in self.records; ex:
#already defined ID = 0
VALUE = 1
POS = 2
LIN = 3
SFIELD = 4 #boolean: True: is subfield, False: field or first element composite
#already defined MPATH = 5 #only for first field (=recordID)
FIXEDLINE = 6 #for fixed records; tmp storage of fixed record
FORMATFROMGRAMMAR = 7 #to store FORMAT field has in grammar
| Python |
import django
from django.contrib import admin
from django.utils.translation import ugettext as _
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.contrib.admin.util import unquote, flatten_fieldsets, get_deleted_objects, model_ngettext, model_format_dict
from django.core.exceptions import PermissionDenied
from django.utils.encoding import force_unicode
from django.utils.html import escape
from django.utils.safestring import mark_safe
from django.utils.text import capfirst, get_text_list
#***********
import models
import botsglobal
admin.site.disable_action('delete_selected')
class BotsAdmin(admin.ModelAdmin):
list_per_page = botsglobal.ini.getint('settings','adminlimit',botsglobal.ini.getint('settings','limit',30))
save_as = True
def delete_view(self, request, object_id, extra_context=None):
''' copy from admin.ModelAdmin; adapted: do not check references: no cascading deletes; no confirmation.'''
opts = self.model._meta
app_label = opts.app_label
try:
obj = self.queryset(request).get(pk=unquote(object_id))
except self.model.DoesNotExist:
obj = None
if not self.has_delete_permission(request, obj):
raise PermissionDenied(_(u'Permission denied'))
if obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_unicode(opts.verbose_name), 'key': escape(object_id)})
obj_display = force_unicode(obj)
self.log_deletion(request, obj, obj_display)
obj.delete()
self.message_user(request, _('The %(name)s "%(obj)s" was deleted successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj_display)})
if not self.has_change_permission(request, None):
return HttpResponseRedirect("../../../../")
return HttpResponseRedirect("../../")
def activate(self, request, queryset):
''' admin action.'''
for obj in queryset:
obj.active = not obj.active
obj.save()
activate.short_description = _(u'activate/de-activate')
def bulk_delete(self, request, queryset):
''' admin action.'''
for obj in queryset:
obj.delete()
bulk_delete.short_description = _(u'delete selected')
#*****************************************************************************************************
class CcodeAdmin(BotsAdmin):
actions = ('bulk_delete',)
list_display = ('ccodeid','leftcode','rightcode','attr1','attr2','attr3','attr4','attr5','attr6','attr7','attr8')
list_display_links = ('ccodeid',)
list_filter = ('ccodeid',)
ordering = ('ccodeid','leftcode')
search_fields = ('ccodeid__ccodeid','leftcode','rightcode','attr1','attr2','attr3','attr4','attr5','attr6','attr7','attr8')
def lookup_allowed(self, lookup, *args, **kwargs):
if lookup.startswith('ccodeid'):
return True
return super(CcodeAdmin, self).lookup_allowed(lookup, *args, **kwargs)
admin.site.register(models.ccode,CcodeAdmin)
class CcodetriggerAdmin(BotsAdmin):
actions = ('bulk_delete',)
list_display = ('ccodeid','ccodeid_desc',)
list_display_links = ('ccodeid',)
ordering = ('ccodeid',)
search_fields = ('ccodeid','ccodeid_desc')
admin.site.register(models.ccodetrigger,CcodetriggerAdmin)
class ChannelAdmin(BotsAdmin):
actions = ('bulk_delete',)
list_display = ('idchannel', 'inorout', 'type','host', 'port', 'username', 'secret', 'path', 'filename', 'remove', 'charset', 'archivepath','rsrv2','ftpactive', 'ftpbinary','askmdn', 'syslock', 'starttls','apop')
list_filter = ('inorout','type')
ordering = ('idchannel',)
search_fields = ('idchannel', 'inorout', 'type','host', 'username', 'path', 'filename', 'archivepath', 'charset')
fieldsets = (
(None, {'fields': ('idchannel', ('inorout','type'), ('host','port'), ('username', 'secret'), ('path', 'filename'), 'remove', 'archivepath', 'charset','desc')
}),
(_(u'FTP specific data'),{'fields': ('ftpactive', 'ftpbinary', 'ftpaccount' ),
'classes': ('collapse',)
}),
(_(u'Advanced'),{'fields': (('lockname', 'syslock'), 'parameters', 'starttls','apop','askmdn','rsrv2'),
'classes': ('collapse',)
}),
)
admin.site.register(models.channel,ChannelAdmin)
class ConfirmruleAdmin(BotsAdmin):
actions = ('activate','bulk_delete')
list_display = ('active','negativerule','confirmtype','ruletype', 'frompartner', 'topartner','idroute','idchannel','editype','messagetype')
list_display_links = ('confirmtype',)
list_filter = ('active','confirmtype','ruletype')
search_fields = ('confirmtype','ruletype', 'frompartner__idpartner', 'topartner__idpartner', 'idroute', 'idchannel__idchannel', 'editype', 'messagetype')
ordering = ('confirmtype','ruletype')
fieldsets = (
(None, {'fields': ('active','negativerule','confirmtype','ruletype','frompartner', 'topartner','idroute','idchannel',('editype','messagetype'))}),
)
admin.site.register(models.confirmrule,ConfirmruleAdmin)
class MailInline(admin.TabularInline):
model = models.chanpar
fields = ('idchannel','mail', 'cc')
extra = 1
class MyPartnerAdminForm(django.forms.ModelForm):
''' customs form for partners to check if group has groups'''
class Meta:
model = models.partner
def clean(self):
super(MyPartnerAdminForm, self).clean()
if self.cleaned_data['isgroup'] and self.cleaned_data['group']:
raise django.forms.util.ValidationError(_(u'A group can not be part of a group.'))
return self.cleaned_data
class PartnerAdmin(BotsAdmin):
actions = ('bulk_delete','activate')
form = MyPartnerAdminForm
fields = ('active', 'isgroup', 'idpartner', 'name','mail','cc','group')
filter_horizontal = ('group',)
inlines = (MailInline,)
list_display = ('active','isgroup','idpartner', 'name','mail','cc')
list_display_links = ('idpartner',)
list_filter = ('active','isgroup')
ordering = ('idpartner',)
search_fields = ('idpartner','name','mail','cc')
admin.site.register(models.partner,PartnerAdmin)
class RoutesAdmin(BotsAdmin):
actions = ('bulk_delete','activate')
list_display = ('active', 'idroute', 'seq', 'fromchannel', 'fromeditype', 'frommessagetype', 'alt', 'frompartner', 'topartner', 'translateind', 'tochannel', 'defer', 'toeditype', 'tomessagetype', 'frompartner_tochannel', 'topartner_tochannel', 'testindicator', 'notindefaultrun')
list_display_links = ('idroute',)
list_filter = ('idroute','active','fromeditype')
ordering = ('idroute','seq')
search_fields = ('idroute', 'fromchannel__idchannel','fromeditype', 'frommessagetype', 'alt', 'tochannel__idchannel','toeditype', 'tomessagetype')
fieldsets = (
(None, {'fields': ('active',('idroute', 'seq'),'fromchannel', ('fromeditype', 'frommessagetype'),'translateind','tochannel','desc')}),
(_(u'Filtering for outchannel'),{'fields':('toeditype', 'tomessagetype','frompartner_tochannel', 'topartner_tochannel', 'testindicator'),
'classes': ('collapse',)
}),
(_(u'Advanced'),{'fields': ('alt', 'frompartner', 'topartner', 'notindefaultrun','defer'),
'classes': ('collapse',)
}),
)
admin.site.register(models.routes,RoutesAdmin)
class MyTranslateAdminForm(django.forms.ModelForm):
''' customs form for translations to check if entry exists (unique_together not validated right (because of null values in partner fields))'''
class Meta:
model = models.translate
def clean(self):
super(MyTranslateAdminForm, self).clean()
b = models.translate.objects.filter(fromeditype=self.cleaned_data['fromeditype'],
frommessagetype=self.cleaned_data['frommessagetype'],
alt=self.cleaned_data['alt'],
frompartner=self.cleaned_data['frompartner'],
topartner=self.cleaned_data['topartner'])
if b and (self.instance.pk is None or self.instance.pk != b[0].id):
raise django.forms.util.ValidationError(_(u'Combination of fromeditype,frommessagetype,alt,frompartner,topartner already exists.'))
return self.cleaned_data
class TranslateAdmin(BotsAdmin):
actions = ('bulk_delete','activate')
form = MyTranslateAdminForm
list_display = ('active', 'fromeditype', 'frommessagetype', 'alt', 'frompartner', 'topartner', 'tscript', 'toeditype', 'tomessagetype')
list_display_links = ('fromeditype',)
list_filter = ('active','fromeditype','toeditype')
ordering = ('fromeditype','frommessagetype')
search_fields = ('fromeditype', 'frommessagetype', 'alt', 'frompartner__idpartner', 'topartner__idpartner', 'tscript', 'toeditype', 'tomessagetype')
fieldsets = (
(None, {'fields': ('active', ('fromeditype', 'frommessagetype'),'tscript', ('toeditype', 'tomessagetype','desc'))
}),
(_(u'Advanced - multiple translations per editype/messagetype'),{'fields': ('alt', 'frompartner', 'topartner'),
'classes': ('collapse',)
}),
)
admin.site.register(models.translate,TranslateAdmin)
class UniekAdmin(BotsAdmin): #AKA counters
actions = None
list_display = ('domein', 'nummer')
list_editable = ('nummer',)
ordering = ('domein',)
search_fields = ('domein',)
admin.site.register(models.uniek,UniekAdmin)
#User - change the default display of user screen
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
UserAdmin.list_display = ('username', 'first_name', 'last_name','email', 'is_active', 'is_staff', 'is_superuser', 'date_joined','last_login')
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
| Python |
#bots modules
import botslib
import botsglobal
from botsconfig import *
from django.utils.translation import ugettext as _
tavars = 'idta,statust,divtext,child,ts,filename,status,idroute,fromchannel,tochannel,frompartner,topartner,frommail,tomail,contenttype,nrmessages,editype,messagetype,errortext,script'
def evaluate(type,stuff2evaluate):
# try: catch errors in retry....this should of course not happen...
try:
if type in ['--retry','--retrycommunication','--automaticretrycommunication']:
return evaluateretryrun(type,stuff2evaluate)
else:
return evaluaterun(type,stuff2evaluate)
except:
botsglobal.logger.exception(_(u'Error in automatic maintenance.'))
return 1 #there has been an error!
def evaluaterun(type,stuff2evaluate):
''' traces all received files.
Write a filereport for each file,
and writes a report for the run.
'''
resultlast={OPEN:0,ERROR:0,OK:0,DONE:0} #gather results of all filereports for runreport
#look at infiles from this run; trace them to determine their tracestatus.
for tadict in botslib.query('''SELECT ''' + tavars + '''
FROM ta
WHERE idta > %(rootidta)s
AND status=%(status)s ''',
{'status':EXTERNIN,'rootidta':stuff2evaluate}):
botsglobal.logger.debug(u'evaluate %s.',tadict['idta'])
mytrace = Trace(tadict,stuff2evaluate)
resultlast[mytrace.statusttree]+=1
insert_filereport(mytrace)
del mytrace.ta
del mytrace
return finish_evaluation(stuff2evaluate,resultlast,type)
def evaluateretryrun(type,stuff2evaluate):
resultlast={OPEN:0,ERROR:0,OK:0,DONE:0}
didretry = False
for row in botslib.query('''SELECT idta
FROM filereport
GROUP BY idta
HAVING MAX(statust) != %(statust)s''',
{'statust':DONE}):
didretry = True
for tadict in botslib.query('''SELECT ''' + tavars + '''
FROM ta
WHERE idta= %(idta)s ''',
{'idta':row['idta']}):
break
else: #there really should be a corresponding ta
raise botslib.PanicError(_(u'MaintenanceRetry: could not find transaction "$txt".'),txt=row['idta'])
mytrace = Trace(tadict,stuff2evaluate)
resultlast[mytrace.statusttree]+=1
if mytrace.statusttree == DONE:
mytrace.errortext = ''
#~ mytrace.ta.update(tracestatus=mytrace.statusttree)
#ts for retried filereports is tricky: is this the time the file was originally received? best would be to use ts of prepare...
#that is quite difficult, so use time of this run
rootta=botslib.OldTransaction(stuff2evaluate)
rootta.syn('ts') #get the timestamp of this run
mytrace.ts = rootta.ts
insert_filereport(mytrace)
del mytrace.ta
del mytrace
if not didretry:
return 0 #no error
return finish_evaluation(stuff2evaluate,resultlast,type)
def insert_filereport(mytrace):
botslib.change(u'''INSERT INTO filereport (idta,statust,reportidta,retransmit,idroute,fromchannel,ts,
infilename,tochannel,frompartner,topartner,frommail,
tomail,ineditype,inmessagetype,outeditype,outmessagetype,
incontenttype,outcontenttype,nrmessages,outfilename,errortext,
divtext,outidta)
VALUES (%(idta)s,%(statust)s,%(reportidta)s,%(retransmit)s,%(idroute)s,%(fromchannel)s,%(ts)s,
%(infilename)s,%(tochannel)s,%(frompartner)s,%(topartner)s,%(frommail)s,
%(tomail)s,%(ineditype)s,%(inmessagetype)s,%(outeditype)s,%(outmessagetype)s,
%(incontenttype)s,%(outcontenttype)s,%(nrmessages)s,%(outfilename)s,%(errortext)s,
%(divtext)s,%(outidta)s )
''',
{'idta':mytrace.idta,'statust':mytrace.statusttree,'reportidta':mytrace.reportidta,
'retransmit':mytrace.retransmit,'idroute':mytrace.idroute,'fromchannel':mytrace.fromchannel,
'ts':mytrace.ts,'infilename':mytrace.infilename,'tochannel':mytrace.tochannel,
'frompartner':mytrace.frompartner,'topartner':mytrace.topartner,'frommail':mytrace.frommail,
'tomail':mytrace.tomail,'ineditype':mytrace.ineditype,'inmessagetype':mytrace.inmessagetype,
'outeditype':mytrace.outeditype,'outmessagetype':mytrace.outmessagetype,
'incontenttype':mytrace.incontenttype,'outcontenttype':mytrace.outcontenttype,
'nrmessages':mytrace.nrmessages,'outfilename':mytrace.outfilename,'errortext':mytrace.errortext,
'divtext':mytrace.divtext,'outidta':mytrace.outidta})
def finish_evaluation(stuff2evaluate,resultlast,type):
#count nr files send
for row in botslib.query('''SELECT COUNT(*) as count
FROM ta
WHERE idta > %(rootidta)s
AND status=%(status)s
AND statust=%(statust)s ''',
{'status':EXTERNOUT,'rootidta':stuff2evaluate,'statust':DONE}):
send = row['count']
#count process errors
for row in botslib.query('''SELECT COUNT(*) as count
FROM ta
WHERE idta >= %(rootidta)s
AND status=%(status)s
AND statust=%(statust)s''',
{'status':PROCESS,'rootidta':stuff2evaluate,'statust':ERROR}):
processerrors = row['count']
#generate report (in database)
rootta=botslib.OldTransaction(stuff2evaluate)
rootta.syn('ts') #get the timestamp of this run
LastReceived=resultlast[DONE]+resultlast[OK]+resultlast[OPEN]+resultlast[ERROR]
status = bool(resultlast[OK]+resultlast[OPEN]+resultlast[ERROR]+processerrors)
botslib.change(u'''INSERT INTO report (idta,lastopen,lasterror,lastok,lastdone,
send,processerrors,ts,lastreceived,status,type)
VALUES (%(idta)s,
%(lastopen)s,%(lasterror)s,%(lastok)s,%(lastdone)s,
%(send)s,%(processerrors)s,%(ts)s,%(lastreceived)s,%(status)s,%(type)s)
''',
{'idta':stuff2evaluate,
'lastopen':resultlast[OPEN],'lasterror':resultlast[ERROR],'lastok':resultlast[OK],'lastdone':resultlast[DONE],
'send':send,'processerrors':processerrors,'ts':rootta.ts,'lastreceived':LastReceived,'status':status,'type':type[2:]})
return generate_report(stuff2evaluate) #return report status: 0 (no error) or 1 (error)
def generate_report(stuff2evaluate):
for results in botslib.query('''SELECT idta,lastopen,lasterror,lastok,lastdone,
send,processerrors,ts,lastreceived,type,status
FROM report
WHERE idta=%(rootidta)s''',
{'rootidta':stuff2evaluate}):
break
else:
raise botslib.PanicError(_(u'In generate report: could not find report?'))
subject = _(u'[Bots Error Report] %(time)s')%{'time':str(results['ts'])[:16]}
reporttext = _(u'Bots Report; type: %(type)s, time: %(time)s\n')%{'type':results['type'],'time':str(results['ts'])[:19]}
reporttext += _(u' %d files received/processed in run.\n')%(results['lastreceived'])
if results['lastdone']:
reporttext += _(u' %d files without errors,\n')%(results['lastdone'])
if results['lasterror']:
subject += _(u'; %d file errors')%(results['lasterror'])
reporttext += _(u' %d files with errors,\n')%(results['lasterror'])
if results['lastok']:
subject += _(u'; %d files stuck')%(results['lastok'])
reporttext += _(u' %d files got stuck,\n')%(results['lastok'])
if results['lastopen']:
subject += _(u'; %d system errors')%(results['lastopen'])
reporttext += _(u' %d system errors,\n')%(results['lastopen'])
if results['processerrors']:
subject += _(u'; %d process errors')%(results['processerrors'])
reporttext += _(u' %d errors in processes.\n')%(results['processerrors'])
reporttext += _(u' %d files send in run.\n')%(results['send'])
botsglobal.logger.info(reporttext)
# sendreportifprocesserror allows blocking of email reports for process errors
if (results['lasterror'] or results['lastopen'] or results['lastok'] or
(results['processerrors'] and botsglobal.ini.getboolean('settings','sendreportifprocesserror',True))):
botslib.sendbotserrorreport(subject,reporttext)
return int(results['status']) #return report status: 0 (no error) or 1 (error)
class Trace(object):
''' ediobject-ta's form a tree; the incoming ediobject-ta (status EXTERNIN) is root.
(yes, this works for merging, strange but inherent).
tree gets a (one) statust, by walking the tree and evaluating the statust of nodes.
all nodes are put into a tree of ta-objects;
'''
def __init__(self,tadict,stuff2evaluate):
realdict = dict([(key,tadict[key]) for key in tadict.keys()])
self.ta=botslib.OldTransaction(**realdict)
self.rootidta = stuff2evaluate
self._buildevaluationstructure(self.ta)
#~ self.display(self.ta)
self._evaluatestatus()
self._gatherfilereportdata()
def display(self,currentta,level=0):
print level*' ',currentta.idta,currentta.statust,currentta.talijst
for ta in currentta.talijst:
self.display(ta,level+1)
def _buildevaluationstructure(self,tacurrent):
''' recursive,for each db-ta:
- fill global talist with the children (and children of children, etc)
'''
#gather next steps/ta's for tacurrent;
if tacurrent.child: #find successor by using child relation ship
for row in botslib.query('''SELECT ''' + tavars + '''
FROM ta
WHERE idta=%(child)s''',
{'child':tacurrent.child}):
realdict = dict([(key,row[key]) for key in row.keys()])
tacurrent.talijst = [botslib.OldTransaction(**realdict)]
else: #find successor by using parent-relationship; mostly this relation except for merge operations
talijst = []
for row in botslib.query('''SELECT ''' + tavars + '''
FROM ta
WHERE idta > %(currentidta)s
AND parent=%(currentidta)s ''', #adding the idta > %(parent)s to selection speeds up a lot.
{'currentidta':tacurrent.idta}):
realdict = dict([(key,row[key]) for key in row.keys()])
talijst.append(botslib.OldTransaction(**realdict))
#filter:
#one ta might have multiple children; 2 possible reasons for that:
#1. split up
#2. error is processing the file; and retried
#Here case 2 (error/retry) is filtered; it is not interesting to evaluate the older errors!
#So: if the same filename and different script: use newest idta
#shortcut: when an error occurs in a split all is turned back.
#so: split up is OK as a whole or because of retries.
#so: if split, and different scripts: split is becaue of retries: use newest idta.
#~ print tacurrent.talijst
if len(talijst) > 1 and talijst[0].script != talijst[1].script:
#find higest idta
highest_ta = talijst[0]
for ta in talijst[1:]:
if ta.idta > highest_ta.idta:
highest_ta = ta
tacurrent.talijst = [highest_ta]
else:
tacurrent.talijst = talijst
#recursive build:
for child in tacurrent.talijst:
self._buildevaluationstructure(child)
def _evaluatestatus(self):
self.done = False
try:
self.statusttree = self._evaluatetreestatus(self.ta)
if self.statusttree == OK:
self.statusttree = ERROR #this is ugly!!
except botslib.TraceNotPickedUpError:
self.statusttree = OK
except: #botslib.TraceError:
self.statusttree = OPEN
def _evaluatetreestatus(self,tacurrent):
''' recursive, walks tree of ediobject-ta, depth-first
for each db-ta:
- get statust of all child-db-ta (recursive); count these statust's
- evaluate this
rules for evaluating:
- typical error-situation: DONE->OK->ERROR
- Db-ta with statust OK will be picked up next botsrun.
- if succes on next botsrun: DONE-> DONE-> ERROR
-> DONE
- one db-ta can have more children; each of these children has to evaluated
- not possible is: DONE-> ERROR (because there should always be statust OK)
'''
statustcount = [0,0,0,0] #count of statust: number of OPEN, ERROR, OK, DONE
for child in tacurrent.talijst:
if child.idta > self.rootidta:
self.done = True
statustcount[self._evaluatetreestatus(child)]+=1
else: #evaluate & return statust of current ta & children;
if tacurrent.statust==DONE:
if statustcount[OK]:
return OK #at least one of the child-trees is not DONE
elif statustcount[DONE]:
return DONE #all is OK
elif statustcount[ERROR]:
raise botslib.TraceError(_(u'DONE but no child is DONE or OK (idta: $idta).'),idta=tacurrent.idta)
else: #if no ERROR and has no children: end of trace
return DONE
elif tacurrent.statust==OK:
if statustcount[ERROR]:
return OK #child(ren) ERROR, this is expected
elif statustcount[DONE]:
raise botslib.TraceError(_(u'OK but child is DONE (idta: $idta). Changing setup while errors are pending?'),idta=tacurrent.idta)
elif statustcount[OK]:
raise botslib.TraceError(_(u'OK but child is OK (idta: $idta). Changing setup while errors are pending?'),idta=tacurrent.idta)
else:
raise botslib.TraceNotPickedUpError(_(u'OK but file is not processed further (idta: $idta).'),idta=tacurrent.idta)
elif tacurrent.statust==ERROR:
if tacurrent.talijst:
raise botslib.TraceError(_(u'ERROR but has child(ren) (idta: $idta). Changing setup while errors are pending?'),idta=tacurrent.idta)
else:
#~ self.errorta += [tacurrent]
return ERROR
else: #tacurrent.statust==OPEN
raise botslib.TraceError(_(u'Severe error: found statust (idta: $idta).'),idta=tacurrent.idta)
def _gatherfilereportdata(self):
''' Walk the ta-tree again in order to retrieve information/data belonging to incoming file; statust (OK, DONE, ERROR etc) is NOT done here.
If information is different in different ta's: place '*'
Start 'root'-ta; a file coming in; status=EXTERNIN. Retrieve as much information from ta's as possible for the filereport.
'''
def core(ta):
if ta.status==MIMEIN:
self.frommail=ta.frommail
self.tomail=ta.tomail
self.incontenttype=ta.contenttype
elif ta.status==RAWOUT:
if ta.frommail:
if self.frommail:
if self.frommail != ta.frommail and asterisk:
self.frommail='*'
else:
self.frommail=ta.frommail
if ta.tomail:
if self.tomail:
if self.tomail != ta.tomail and asterisk:
self.tomail='*'
else:
self.tomail=ta.tomail
if ta.contenttype:
if self.outcontenttype:
if self.outcontenttype != ta.contenttype and asterisk:
self.outcontenttype='*'
else:
self.outcontenttype=ta.contenttype
if ta.idta:
if self.outidta:
if self.outidta != ta.idta and asterisk:
self.outidta=0
else:
self.outidta=ta.idta
elif ta.status==TRANSLATE:
#self.ineditype=ta.editype
if self.ineditype:
if self.ineditype!=ta.editype and asterisk:
self.ineditype='*'
else:
self.ineditype=ta.editype
elif ta.status==SPLITUP:
self.nrmessages+=1
if self.inmessagetype:
if self.inmessagetype!=ta.messagetype and asterisk:
self.inmessagetype='*'
else:
self.inmessagetype=ta.messagetype
elif ta.status==TRANSLATED:
#self.outeditype=ta.editype
if self.outeditype:
if self.outeditype!=ta.editype and asterisk:
self.outeditype='*'
else:
self.outeditype=ta.editype
if self.outmessagetype:
if self.outmessagetype!=ta.messagetype and asterisk:
self.outmessagetype='*'
else:
self.outmessagetype=ta.messagetype
if self.divtext:
if self.divtext!=ta.divtext and asterisk:
self.divtext='*'
else:
self.divtext=ta.divtext
elif ta.status==EXTERNOUT:
if self.outfilename:
if self.outfilename != ta.filename and asterisk:
self.outfilename='*'
else:
self.outfilename=ta.filename
if self.tochannel:
if self.tochannel != ta.tochannel and asterisk:
self.tochannel='*'
else:
self.tochannel=ta.tochannel
if ta.frompartner:
if not self.frompartner:
self.frompartner=ta.frompartner
elif self.frompartner!=ta.frompartner and asterisk:
self.frompartner='*'
if ta.topartner:
if not self.topartner:
self.topartner=ta.topartner
elif self.topartner!=ta.topartner and asterisk:
self.topartner='*'
if ta.errortext:
self.errortext = ta.errortext
for child in ta.talijst:
core(child)
#end of core function
asterisk = botsglobal.ini.getboolean('settings','multiplevaluesasterisk',True)
self.idta = self.ta.idta
self.reportidta = self.rootidta
self.retransmit = 0
self.idroute = self.ta.idroute
self.fromchannel = self.ta.fromchannel
self.ts = self.ta.ts
self.infilename = self.ta.filename
self.tochannel = ''
self.frompartner = ''
self.topartner = ''
self.frommail = ''
self.tomail = ''
self.ineditype = ''
self.inmessagetype = ''
self.outeditype = ''
self.outmessagetype = ''
self.incontenttype = ''
self.outcontenttype = ''
self.nrmessages = 0
self.outfilename = ''
self.outidta = 0
self.errortext = ''
self.divtext = ''
core(self.ta)
| Python |
try:
from pysqlite2 import dbapi2 as sqlite #prefer external modules for pylite
except ImportError:
import sqlite3 as sqlite #works OK for python26
#~ #bots engine uses:
#~ ''' SELECT *
#~ FROM ta
#~ WHERE idta=%(idta)s ''',
#~ {'idta':12345})
#~ #SQLite wants:
#~ ''' SELECT *
#~ FROM ta
#~ WHERE idta=:idta ''',
#~ {'idta': 12345}
import re
reformatparamstyle = re.compile(u'%\((?P<name>[^)]+)\)s')
def adapter4bool(boolfrompython):
#SQLite expects a string
if boolfrompython:
return '1'
else:
return '0'
def converter4bool(strfromdb):
#SQLite returns a string
if strfromdb == '1':
return True
else:
return False
sqlite.register_adapter(bool,adapter4bool)
sqlite.register_converter('BOOLEAN',converter4bool)
def connect(database):
con = sqlite.connect(database, factory=BotsConnection,detect_types=sqlite.PARSE_DECLTYPES, timeout=99.0, isolation_level='IMMEDIATE')
con.row_factory = sqlite.Row
con.execute('''PRAGMA synchronous=OFF''')
return con
class BotsConnection(sqlite.Connection):
def cursor(self):
return sqlite.Connection.cursor(self, factory=BotsCursor)
class BotsCursor(sqlite.Cursor):
def execute(self,string,parameters=None):
if parameters is None:
sqlite.Cursor.execute(self,string)
else:
sqlite.Cursor.execute(self,reformatparamstyle.sub(u''':\g<name>''',string),parameters)
| Python |
import sys
import os
import botsinit
import botslib
import grammar
def showusage():
print
print " Usage: %s -c<directory> <editype> <messagetype>"%os.path.basename(sys.argv[0])
print
print " Checks a Bots grammar."
print " Same checks are used as in translations with bots-engine."
print " Searches for grammar in regular place: bots/usersys/grammars/<editype>/<messagetype>.py"
print " Options:"
print " -c<directory> directory for configuration files (default: config)."
print " Example:"
print " %s -cconfig edifact ORDERSD96AUNEAN008"%os.path.basename(sys.argv[0])
print
sys.exit(0)
def startmulti(grammardir,editype):
''' used in seperate tool for bulk checking of gramamrs while developing edifact->botsgramamrs '''
import glob
botslib.generalinit('config')
botslib.initenginelogging()
for g in glob.glob(grammardir):
g1 = os.path.basename(g)
g2 = os.path.splitext(g1)[0]
if g1 in ['__init__.py']:
continue
if g1.startswith('edifact'):
continue
if g1.startswith('records') or g1.endswith('records.py'):
continue
try:
grammar.grammarread(editype,g2)
except:
#~ print 'Found error in grammar:',g
print botslib.txtexc()
print '\n'
else:
print 'OK - no error found in grammar',g,'\n'
def start():
#********command line arguments**************************
editype =''
messagetype = ''
configdir = 'config'
for arg in sys.argv[1:]:
if not arg:
continue
if arg.startswith('-c'):
configdir = arg[2:]
if not configdir:
print ' !!Indicated Bots should use specific .ini file but no file name was given.'
showusage()
elif arg in ["?", "/?"] or arg.startswith('-'):
showusage()
else:
if not editype:
editype = arg
else:
messagetype = arg
if not (editype and messagetype):
print ' !!Both editype and messagetype are required.'
showusage()
#********end handling command line arguments**************************
try:
botsinit.generalinit(configdir)
botsinit.initenginelogging()
grammar.grammarread(editype,messagetype)
except:
print 'Found error in grammar:'
print botslib.txtexc()
else:
print 'OK - no error found in grammar'
if __name__=='__main__':
start()
| Python |
import sys
import os
import tarfile
import glob
import shutil
import subprocess
import traceback
import bots.botsglobal as botsglobal
def join(path,*paths):
return os.path.normpath(os.path.join(path,*paths))
#******************************************************************************
#*** start *********************************************
#******************************************************************************
def start():
print 'Installation of bots open source edi translator.'
#python version dependencies
version = str(sys.version_info[0]) + str(sys.version_info[1])
if version == '25':
pass
elif version == '26':
pass
elif version == '27':
pass
else:
raise Exception('Wrong python version, use python 2.5.*, 2.6.* or 2.7.*')
botsdir = os.path.dirname(botsglobal.__file__)
print ' Installed bots in "%s".'%(botsdir)
#******************************************************************************
#*** shortcuts *******************************************************
#******************************************************************************
scriptpath = join(sys.prefix,'Scripts')
shortcutdir = join(get_special_folder_path('CSIDL_COMMON_PROGRAMS'),'Bots2.1')
try:
os.mkdir(shortcutdir)
except:
pass
else:
directory_created(shortcutdir)
try:
#~ create_shortcut(join(scriptpath,'botswebserver'),'Bots open source EDI translator',join(shortcutdir,'Bots-webserver.lnk'))
create_shortcut(join(sys.prefix,'python'),'bots open source edi translator',join(shortcutdir,'bots-webserver.lnk'),join(scriptpath,'bots-webserver.py'))
file_created(join(shortcutdir,'bots-webserver.lnk'))
except:
print ' Failed to install shortcut/link for bots in your menu.'
else:
print ' Installed shortcut in "Program Files".'
#******************************************************************************
#*** install libraries, dependencies ***************************************
#******************************************************************************
for library in glob.glob(join(botsdir,'installwin','*.gz')):
tar = tarfile.open(library)
tar.extractall(path=os.path.dirname(library))
tar.close()
untar_dir = library[:-len('.tar.gz')]
subprocess.call([join(sys.prefix,'pythonw'), 'setup.py','install'],cwd=untar_dir,stdin=open(os.devnull,'r'),stdout=open(os.devnull,'w'),stderr=open(os.devnull,'w'))
shutil.rmtree(untar_dir, ignore_errors=True)
print ' Installed needed libraries.'
#******************************************************************************
#*** install configuration files **************************************
#******************************************************************************
if os.path.exists(join(botsdir,'config','settings.py')): #use this to see if this is an existing installation
print ' Found existing configuration files'
print ' Configuration files bots.ini and settings.py not overwritten.'
print ' Manual action is needed.'
print ' See bots web site-documentation-migrate for more info.'
else:
shutil.copy(join(botsdir,'install','bots.ini'),join(botsdir,'config','bots.ini'))
shutil.copy(join(botsdir,'install','settings.py'),join(botsdir,'config','settings.py'))
print ' Installed configuration files'
#******************************************************************************
#*** install database; upgrade existing db *********************************
#******************************************************************************
sqlitedir = join(botsdir,'botssys','sqlitedb')
if os.path.exists(join(sqlitedir,'botsdb')): #use this to see if this is an existing installation
print ' Found existing database file botssys/sqlitedb/botsdb'
print ' Manual action is needed - there is a tool/program to update the database.'
print ' See bots web site-documentation-migrate for more info.'
else:
if not os.path.exists(sqlitedir): #use this to see if this is an existing installation
os.makedirs(sqlitedir)
shutil.copy(join(botsdir,'install','botsdb'),join(sqlitedir,'botsdb'))
print ' Installed SQLite database'
#******************************************************************************
#******************************************************************************
if __name__=='__main__':
if len(sys.argv)>1 and sys.argv[1]=='-install':
try:
start()
except:
print traceback.format_exc(0)
print
print 'Bots installation failed.'
else:
print
print 'Bots installation succeeded.'
| Python |
import copy
import os
import glob
import bots.inmessage as inmessage
import bots.outmessage as outmessage
def comparenode(node1,node2org):
node2 = copy.deepcopy(node2org)
if node1.record is not None and node2.record is None:
print 'node2 is "None"'
return False
if node1.record is None and node2.record is not None:
print 'node1 is "None"'
return False
return comparenodecore(node1,node2)
def comparenodecore(node1,node2):
if node1.record is None and node2.record is None:
pass
else:
for key,value in node1.record.items():
if key not in node2.record:
print 'key not in node2', key,value
return False
elif node2.record[key]!=value:
print 'unequal attr', key,value,node2.record[key]
return False
for key,value in node2.record.items():
if key not in node1.record:
print 'key not in node1', key,value
return False
elif node1.record[key]!=value:
print 'unequal attr', key,value,node1.record[key]
return False
if len(node1.children) != len(node2.children):
print 'number of children not equal'
return False
for child1 in node1.children:
for i,child2 in enumerate(node2.children):
if child1.record['BOTSID'] == child2.record['BOTSID']:
if comparenodecore(child1,child2) != True:
return False
del node2.children[i:i+1]
break
else:
print 'Found no matching record in node2 for',child1.record
return False
return True
def readfilelines(bestand):
fp = open(bestand,'rU')
terug=fp.readlines()
fp.close()
return terug
def readfile(bestand):
fp = open(bestand,'rU')
terug=fp.read()
fp.close()
return terug
def readwrite(filenamein='',filenameout='',**args):
inn = inmessage.edifromfile(filename=filenamein,**args)
out = outmessage.outmessage_init(filename=filenameout,divtext='',topartner='',**args) #make outmessage object
out.root = inn.root
out.writeall()
def getdirbysize(path):
''' read fils in directory path, return as a sorted list.'''
lijst = getdir(path)
lijst.sort(key=lambda s: os.path.getsize(s))
return lijst
def getdir(path):
''' read files in directory path, return incl length.'''
return [s for s in glob.glob(path) if os.path.isfile(s)]
| Python |
import os
import unittest
import shutil
import bots.inmessage as inmessage
import bots.outmessage as outmessage
import filecmp
try:
import json as simplejson
except ImportError:
import simplejson
import bots.botslib as botslib
import bots.botsinit as botsinit
import utilsunit
try:
import cElementTree as ET
except ImportError:
try:
import elementtree.ElementTree as ET
except ImportError:
try:
from xml.etree import cElementTree as ET
except ImportError:
from xml.etree import ElementTree as ET
'''
PLUGIN: unitinmessagejson.zip
'''
class InmessageJson(unittest.TestCase):
#~ #***********************************************************************
#~ #***********test json eg list of article (as eg used in database comm *******
#~ #***********************************************************************
def testjson01(self):
filein = 'botssys/infile/unitinmessagejson/org/01.jsn'
filecomp = 'botssys/infile/unitinmessagejson/comp/01.xml'
inn1 = inmessage.edifromfile(filename=filein,editype='json',messagetype='articles')
inn2 = inmessage.edifromfile(filename=filecomp,editype='xml',messagetype='articles')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
def testjson01nocheck(self):
filein = 'botssys/infile/unitinmessagejson/org/01.jsn'
filecomp = 'botssys/infile/unitinmessagejson/comp/01.xml'
inn1 = inmessage.edifromfile(filename=filein,editype='jsonnocheck',messagetype='articles')
inn2 = inmessage.edifromfile(filename=filecomp,editype='xml',messagetype='articles')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
def testjson11(self):
filein = 'botssys/infile/unitinmessagejson/org/11.jsn'
filecomp = 'botssys/infile/unitinmessagejson/comp/01.xml'
inn1 = inmessage.edifromfile(filename=filein,editype='json',messagetype='articles')
inn2 = inmessage.edifromfile(filename=filecomp,editype='xml',messagetype='articles')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
def testjson11nocheck(self):
filein = 'botssys/infile/unitinmessagejson/org/11.jsn'
filecomp = 'botssys/infile/unitinmessagejson/comp/01.xml'
inn1 = inmessage.edifromfile(filename=filein,editype='jsonnocheck',messagetype='articles')
inn2 = inmessage.edifromfile(filename=filecomp,editype='xml',messagetype='articles')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
#***********************************************************************
#*********json incoming tests complex structure*************************
#***********************************************************************
def testjsoninvoic01(self):
filein = 'botssys/infile/unitinmessagejson/org/invoic01.jsn'
filecomp = 'botssys/infile/unitinmessagejson/comp/invoic01.xml'
inn1 = inmessage.edifromfile(filename=filein,editype='json',messagetype='invoic')
inn2 = inmessage.edifromfile(filename=filecomp,editype='xml',messagetype='invoic')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
def testjsoninvoic01nocheck(self):
filein = 'botssys/infile/unitinmessagejson/org/invoic01.jsn'
filecomp = 'botssys/infile/unitinmessagejson/comp/invoic01.xml'
inn1 = inmessage.edifromfile(filename=filein,editype='jsonnocheck',messagetype='invoic')
inn2 = inmessage.edifromfile(filename=filecomp,editype='xml',messagetype='invoic')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
def testjsoninvoic02(self):
''' check 01.xml the same after rad&write/check '''
filein = 'botssys/infile/unitinmessagejson/org/invoic02.jsn'
filecomp = 'botssys/infile/unitinmessagejson/comp/invoic01.xml'
inn1 = inmessage.edifromfile(filename=filein,editype='json',messagetype='invoic')
inn2 = inmessage.edifromfile(filename=filecomp,editype='xml',messagetype='invoic')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
def testjsoninvoic02nocheck(self):
''' check 01.xml the same after rad&write/check '''
filein = 'botssys/infile/unitinmessagejson/org/invoic02.jsn'
filecomp = 'botssys/infile/unitinmessagejson/comp/invoic01.xml'
inn1 = inmessage.edifromfile(filename=filein,editype='jsonnocheck',messagetype='invoic')
inn2 = inmessage.edifromfile(filename=filecomp,editype='xml',messagetype='invoic')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
#***********************************************************************
#*********json incoming tests int,float*********************************
#***********************************************************************
def testjsoninvoic03(self):
''' test int, float in json '''
filein = 'botssys/infile/unitinmessagejson/org/invoic03.jsn'
filecomp = 'botssys/infile/unitinmessagejson/comp/invoic02.xml'
inn1 = inmessage.edifromfile(filename=filein,editype='json',messagetype='invoic')
inn2 = inmessage.edifromfile(filename=filecomp,editype='xml',messagetype='invoic')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
def testjsoninvoic03xmlnocheck(self):
''' test int, float in json '''
filein = 'botssys/infile/unitinmessagejson/org/invoic03.jsn'
filecomp = 'botssys/infile/unitinmessagejson/comp/invoic02.xml'
inn1 = inmessage.edifromfile(filename=filein,editype='json',messagetype='invoic')
inn2 = inmessage.edifromfile(filename=filecomp,editype='xmlnocheck',messagetype='invoic')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
def testjsoninvoic03nocheck(self):
''' test int, float in json '''
filein = 'botssys/infile/unitinmessagejson/org/invoic03.jsn'
filecomp = 'botssys/infile/unitinmessagejson/comp/invoic02.xml'
inn1 = inmessage.edifromfile(filename=filein,editype='jsonnocheck',messagetype='invoic')
inn2 = inmessage.edifromfile(filename=filecomp,editype='xml',messagetype='invoic')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
def testjsoninvoic03nocheckxmlnocheck(self):
''' test int, float in json '''
filein = 'botssys/infile/unitinmessagejson/org/invoic03.jsn'
filecomp = 'botssys/infile/unitinmessagejson/comp/invoic02.xml'
inn1 = inmessage.edifromfile(filename=filein,editype='jsonnocheck',messagetype='invoic')
inn2 = inmessage.edifromfile(filename=filecomp,editype='xmlnocheck',messagetype='invoic')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
def testjsondiv(self):
self.failUnless(inmessage.edifromfile(editype='json',messagetype='testjsonorder01',checkunknownentities=True,filename='botssys/infile/unitinmessagejson/org/130101.json'), 'standaard test')
self.failUnless(inmessage.edifromfile(editype='jsonnocheck',messagetype='jsonnocheck',filename='botssys/infile/unitinmessagejson/org/130101.json'), 'standaard test')
#empty object
self.assertRaises(botslib.InMessageError,inmessage.edifromfile, editype='json',messagetype='testjsonorder01',checkunknownentities=True,filename='botssys/infile/unitinmessagejson/org/130102.json')
#unknown field
self.failUnless(inmessage.edifromfile(editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130103.json'), 'unknown field')
self.failUnless(inmessage.edifromfile(editype='jsonnocheck',messagetype='jsonnocheck',filename='botssys/infile/unitinmessagejson/org/130103.json'), 'unknown field')
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='json',messagetype='testjsonorder01',checkunknownentities=True,filename='botssys/infile/unitinmessagejson/org/130103.json') #unknown field
#compare standard test with standard est with extra unknown fields and objects: must give same tree:
in1 = inmessage.edifromfile(editype='json',messagetype='testjsonorder01',checkunknownentities=True,filename='botssys/infile/unitinmessagejson/org/130101.json')
in2 = inmessage.edifromfile(editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130115.json')
self.failUnless(utilsunit.comparenode(in1.root,in2.root),'compare')
#numeriek field
self.failUnless(inmessage.edifromfile(editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130104.json'), 'numeriek field')
self.failUnless(inmessage.edifromfile(editype='jsonnocheck',messagetype='jsonnocheck',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130104.json'), 'numeriek field')
self.failUnless(inmessage.edifromfile(editype='json',messagetype='testjsonorder01',checkunknownentities=True,filename='botssys/infile/unitinmessagejson/org/130104.json'), 'numeriek field')
self.failUnless(inmessage.edifromfile(editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130105.json'), 'fucked up')
self.failUnless(inmessage.edifromfile(editype='jsonnocheck',messagetype='jsonnocheck',filename='botssys/infile/unitinmessagejson/org/130105.json'), 'fucked up')
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='json',messagetype='testjsonorder01',checkunknownentities=True,filename='botssys/infile/unitinmessagejson/org/130105.json') #fucked up
self.failUnless(inmessage.edifromfile(editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130106.json'), 'fucked up')
self.failUnless(inmessage.edifromfile(editype='jsonnocheck',messagetype='jsonnocheck',filename='botssys/infile/unitinmessagejson/org/130106.json'), 'fucked up')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile, editype='json',messagetype='testjsonorder01',checkunknownentities=True,filename='botssys/infile/unitinmessagejson/org/130106.json') #fucked up
self.failUnless(inmessage.edifromfile(editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130107.json'), 'fucked up')
self.failUnless(inmessage.edifromfile(editype='jsonnocheck',messagetype='jsonnocheck',filename='botssys/infile/unitinmessagejson/org/130107.json'), 'fucked up')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile, editype='json',messagetype='testjsonorder01',checkunknownentities=True,filename='botssys/infile/unitinmessagejson/org/130107.json') #fucked up
#root is list with 3 messagetrees
inn = inmessage.edifromfile(editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130108.json')
self.assertEqual(len(inn.root.children), 3,'should deliver 3 messagetrees')
inn = inmessage.edifromfile(editype='jsonnocheck',messagetype='jsonnocheck',filename='botssys/infile/unitinmessagejson/org/130108.json')
self.assertEqual(len(inn.root.children), 3,'should deliver 3 messagetrees')
#root is list, but list has a non-object member
self.failUnless(inmessage.edifromfile(editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130109.json'), 'root is list, but list has a non-object member')
self.failUnless(inmessage.edifromfile(editype='jsonnocheck',messagetype='jsonnocheck',filename='botssys/infile/unitinmessagejson/org/130109.json'), 'root is list, but list has a non-object member')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile, editype='json',messagetype='testjsonorder01',checkunknownentities=True,filename='botssys/infile/unitinmessagejson/org/130109.json') #root is list, but list has a non-object member
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130110.json') #too many occurences
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130111.json') #ent TEST1 should have a TEST2
self.failUnless(inmessage.edifromfile(editype='jsonnocheck',messagetype='jsonnocheck',filename='botssys/infile/unitinmessagejson/org/130111.json'), 'ent TEST1 should have a TEST2')
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='json',messagetype='testjsonorder01',checkunknownentities=True,filename='botssys/infile/unitinmessagejson/org/130111.json') #ent TEST1 should have a TEST2
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130112.json') #ent TEST1 has a TEST2
self.failUnless(inmessage.edifromfile(editype='jsonnocheck',messagetype='jsonnocheck',filename='botssys/infile/unitinmessagejson/org/130112.json'), 'ent TEST1 has a TEST2')
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='json',messagetype='testjsonorder01',checkunknownentities=True,filename='botssys/infile/unitinmessagejson/org/130112.json') #ent TEST1 has a TEST2
#unknown entries
inn = inmessage.edifromfile(editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130113.json')
#empty file
self.assertRaises(ValueError,inmessage.edifromfile, editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130114.json') #empty file
self.assertRaises(ValueError,inmessage.edifromfile, editype='jsonnocheck',messagetype='jsonnocheck',filename='botssys/infile/unitinmessagejson/org/130114.json') #empty file
#numeric key
self.assertRaises(ValueError,inmessage.edifromfile, editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130116.json')
#key is list
self.assertRaises(ValueError,inmessage.edifromfile, editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130117.json')
def testinisoutjson01(self):
filein = 'botssys/infile/unitinmessagejson/org/inisout01.json'
fileout1 = 'botssys/infile/unitinmessagejson/output/inisout01.json'
fileout3 = 'botssys/infile/unitinmessagejson/output/inisout03.json'
utilsunit.readwrite(editype='json',messagetype='jsonorder',filenamein=filein,filenameout=fileout1)
utilsunit.readwrite(editype='jsonnocheck',messagetype='jsonnocheck',filenamein=filein,filenameout=fileout3)
inn1 = inmessage.edifromfile(filename=fileout1,editype='jsonnocheck',messagetype='jsonnocheck')
inn2 = inmessage.edifromfile(filename=fileout3,editype='jsonnocheck',messagetype='jsonnocheck')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
def testinisoutjson02(self):
#fails. this is because list of messages is read; and these are written in one time....nice for next release...
filein = 'botssys/infile/unitinmessagejson/org/inisout05.json'
fileout = 'botssys/infile/unitinmessagejson/output/inisout05.json'
inn = inmessage.edifromfile(editype='json',messagetype='jsoninvoic',filename=filein)
out = outmessage.outmessage_init(editype='json',messagetype='jsoninvoic',filename=fileout,divtext='',topartner='') #make outmessage object
#~ inn.root.display()
out.root = inn.root
out.writeall()
inn1 = inmessage.edifromfile(filename=filein,editype='jsonnocheck',messagetype='jsonnocheck',defaultBOTSIDroot='HEA')
inn2 = inmessage.edifromfile(filename=fileout,editype='jsonnocheck',messagetype='jsonnocheck')
#~ inn1.root.display()
#~ inn2.root.display()
#~ self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
#~ rawfile1 = utilsunit.readfile(filein)
#~ rawfile2 = utilsunit.readfile(fileout)
#~ jsonobject1 = simplejson.loads(rawfile1)
#~ jsonobject2 = simplejson.loads(rawfile2)
#~ self.assertEqual(jsonobject1,jsonobject2,'CmpJson')
def testinisoutjson03(self):
''' non-ascii-char'''
filein = 'botssys/infile/unitinmessagejson/org/inisout04.json'
fileout = 'botssys/infile/unitinmessagejson/output/inisout04.json'
utilsunit.readwrite(editype='json',messagetype='jsonorder',filenamein=filein,filenameout=fileout)
inn1 = inmessage.edifromfile(filename=filein,editype='jsonnocheck',messagetype='jsonnocheck')
inn2 = inmessage.edifromfile(filename=fileout,editype='jsonnocheck',messagetype='jsonnocheck')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
def testinisoutjson04(self):
filein = 'botssys/infile/unitinmessagejson/org/inisout05.json'
inn1 = inmessage.edifromfile(filename=filein,editype='jsonnocheck',messagetype='jsonnocheck',defaultBOTSIDroot='HEA')
inn2 = inmessage.edifromfile(filename=filein,editype='json',messagetype='jsoninvoic')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
if __name__ == '__main__':
botsinit.generalinit('config')
botsinit.initenginelogging()
shutil.rmtree('bots/botssys/infile/unitinmessagejson/output/',ignore_errors=True) #remove whole output directory
os.mkdir('bots/botssys/infile/unitinmessagejson/output')
unittest.main()
| Python |
import os
import unittest
import shutil
import filecmp
import bots.inmessage as inmessage
import bots.outmessage as outmessage
import bots.botslib as botslib
import bots.botsinit as botsinit
'''plugin unitnode.zip'''
class Testnode(unittest.TestCase):
''' test node.py and message.py.
'''
def testedifact01(self):
inn = inmessage.edifromfile(editype='edifact',messagetype='invoicwithenvelope',filename='botssys/infile/unitnode/nodetest01.edi')
out = outmessage.outmessage_init(editype='edifact',messagetype='invoicwithenvelope',filename='botssys/infile/unitnode/output/inisout03.edi',divtext='',topartner='') #make outmessage object
out.root = inn.root
#* getloop **************************************
count = 0
for t in inn.getloop({'BOTSID':'XXX'}):
count += 1
self.assertEqual(count,0,'Cmplines')
count = 0
for t in inn.getloop({'BOTSID':'UNB'}):
count += 1
self.assertEqual(count,2,'Cmplines')
count = 0
for t in out.getloop({'BOTSID':'UNB'},{'BOTSID':'XXX'}):
count += 1
self.assertEqual(count,0,'Cmplines')
count = 0
for t in out.getloop({'BOTSID':'UNB'},{'BOTSID':'UNH'}):
count += 1
self.assertEqual(count,3,'Cmplines')
count = 0
for t in inn.getloop({'BOTSID':'UNB'},{'BOTSID':'UNH'},{'BOTSID':'XXX'}):
count += 1
self.assertEqual(count,0,'Cmplines')
count = 0
for t in inn.getloop({'BOTSID':'UNB'},{'BOTSID':'UNH'},{'BOTSID':'LIN'}):
count += 1
self.assertEqual(count,6,'Cmplines')
count = 0
for t in inn.getloop({'BOTSID':'UNB'},{'BOTSID':'XXX'},{'BOTSID':'LIN'},{'BOTSID':'QTY'}):
count += 1
self.assertEqual(count,0,'Cmplines')
count = 0
for t in inn.getloop({'BOTSID':'UNB'},{'BOTSID':'UNH'},{'BOTSID':'LIN'},{'BOTSID':'XXX'}):
count += 1
self.assertEqual(count,0,'Cmplines')
count = 0
for t in inn.getloop({'BOTSID':'UNB'},{'BOTSID':'UNH'},{'BOTSID':'LIN'},{'BOTSID':'QTY'}):
count += 1
self.assertEqual(count,6,'Cmplines')
#* getcount, getcountmpath **************************************
count = 0
countlist=[5,0,1]
nrsegmentslist=[132,10,12]
for t in out.getloop({'BOTSID':'UNB'},{'BOTSID':'UNH'}):
count2 = 0
for u in t.getloop({'BOTSID':'UNH'},{'BOTSID':'LIN'}):
count2 += 1
count3 = t.getcountoccurrences({'BOTSID':'UNH'},{'BOTSID':'LIN'})
self.assertEqual(t.getcount(),nrsegmentslist[count],'Cmplines')
self.assertEqual(count2,countlist[count],'Cmplines')
self.assertEqual(count3,countlist[count],'Cmplines')
count += 1
self.assertEqual(out.getcountoccurrences({'BOTSID':'UNB'},{'BOTSID':'UNH'}),count,'Cmplines')
self.assertEqual(out.getcount(),sum(nrsegmentslist,4),'Cmplines')
#* get, getnozero, countmpath, sort**************************************
for t in out.getloop({'BOTSID':'UNB'},{'BOTSID':'UNH'}):
self.assertRaises(botslib.MappingRootError,out.get,())
self.assertRaises(botslib.MappingRootError,out.getnozero,())
self.assertRaises(botslib.MappingRootError,out.get,0)
self.assertRaises(botslib.MappingRootError,out.getnozero,0)
t.sort({'BOTSID':'UNH'},{'BOTSID':'LIN','C212.7140':None})
start='0'
for u in t.getloop({'BOTSID':'UNH'},{'BOTSID':'LIN'}):
nextstart = u.get({'BOTSID':'LIN','C212.7140':None})
self.failUnless(start<nextstart)
start = nextstart
t.sort({'BOTSID':'UNH'},{'BOTSID':'LIN','1082':None})
start='0'
for u in t.getloop({'BOTSID':'UNH'},{'BOTSID':'LIN'}):
nextstart = u.get({'BOTSID':'LIN','1082':None})
self.failUnless(start<nextstart)
start = nextstart
self.assertRaises(botslib.MappingRootError,out.get,())
self.assertRaises(botslib.MappingRootError,out.getnozero,())
#~ # self.assertRaises(botslib.MpathError,out.get,())
first=True
for t in out.getloop({'BOTSID':'UNB'}):
if first:
self.assertEqual('15',t.getcountsum({'BOTSID':'UNB'},{'BOTSID':'UNH'},{'BOTSID':'LIN','1082':None}),'Cmplines')
self.assertEqual('8',t.getcountsum({'BOTSID':'UNB'},{'BOTSID':'UNH'},{'BOTSID':'LIN'},{'BOTSID':'QTY','C186.6063':'47','C186.6060':None}),'Cmplines')
self.assertEqual('0',t.getcountsum({'BOTSID':'UNB'},{'BOTSID':'UNH'},{'BOTSID':'LIN'},{'BOTSID':'QTY','C186.6063':'12','C186.6060':None}),'Cmplines')
self.assertEqual('54.4',t.getcountsum({'BOTSID':'UNB'},{'BOTSID':'UNH'},{'BOTSID':'LIN'},{'BOTSID':'MOA','C516.5025':'203','C516.5004':None}),'Cmplines')
first = False
else:
self.assertEqual('1',t.getcountsum({'BOTSID':'UNB'},{'BOTSID':'UNH'},{'BOTSID':'LIN'},{'BOTSID':'QTY','C186.6063':'47','C186.6060':None}),'Cmplines')
self.assertEqual('0',t.getcountsum({'BOTSID':'UNB'},{'BOTSID':'UNH'},{'BOTSID':'LIN'},{'BOTSID':'QTY','C186.6063':'12','C186.6060':None}),'Cmplines')
self.assertEqual('0',t.getcountsum({'BOTSID':'UNB'},{'BOTSID':'UNH'},{'BOTSID':'LIN'},{'BOTSID':'MOA','C516.5025':'203','C516.5004':None}),'Cmplines')
def testedifact02(self):
#~ #display query correct? incluuding propagating 'down the tree'?
inn = inmessage.edifromfile(editype='edifact',messagetype='invoicwithenvelopetestquery',filename='botssys/infile/unitnode/nodetest01.edi')
inn.root.processqueries({},2)
inn.root.displayqueries()
if __name__ == '__main__':
import datetime
botsinit.generalinit('config')
botsinit.initenginelogging()
shutil.rmtree('bots/botssys/infile/unitnode/output',ignore_errors=True) #remove whole output directory
os.mkdir('bots/botssys/infile/unitnode/output')
unittest.main()
unittest.main()
unittest.main()
| Python |
#!/usr/bin/python2.6
#
# Simple http server to emulate api.playfoursquare.com
import logging
import shutil
import sys
import urlparse
import SimpleHTTPServer
import BaseHTTPServer
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""Handle playfoursquare.com requests, for testing."""
def do_GET(self):
logging.warn('do_GET: %s, %s', self.command, self.path)
url = urlparse.urlparse(self.path)
logging.warn('do_GET: %s', url)
query = urlparse.parse_qs(url.query)
query_keys = [pair[0] for pair in query]
response = self.handle_url(url)
if response != None:
self.send_200()
shutil.copyfileobj(response, self.wfile)
self.wfile.close()
do_POST = do_GET
def handle_url(self, url):
path = None
if url.path == '/v1/venue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/addvenue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/venues':
path = '../captures/api/v1/venues.xml'
elif url.path == '/v1/user':
path = '../captures/api/v1/user.xml'
elif url.path == '/v1/checkcity':
path = '../captures/api/v1/checkcity.xml'
elif url.path == '/v1/checkins':
path = '../captures/api/v1/checkins.xml'
elif url.path == '/v1/cities':
path = '../captures/api/v1/cities.xml'
elif url.path == '/v1/switchcity':
path = '../captures/api/v1/switchcity.xml'
elif url.path == '/v1/tips':
path = '../captures/api/v1/tips.xml'
elif url.path == '/v1/checkin':
path = '../captures/api/v1/checkin.xml'
elif url.path == '/history/12345.rss':
path = '../captures/api/v1/feed.xml'
if path is None:
self.send_error(404)
else:
logging.warn('Using: %s' % path)
return open(path)
def send_200(self):
self.send_response(200)
self.send_header('Content-type', 'text/xml')
self.end_headers()
def main():
if len(sys.argv) > 1:
port = int(sys.argv[1])
else:
port = 8080
server_address = ('0.0.0.0', port)
httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/python
import datetime
import sys
import textwrap
import common
from xml.dom import pulldom
PARSER = """\
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.parsers;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.types.%(type_name)s;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Auto-generated: %(timestamp)s
*
* @author Joe LaPenna (joe@joelapenna.com)
* @param <T>
*/
public class %(type_name)sParser extends AbstractParser<%(type_name)s> {
private static final Logger LOG = Logger.getLogger(%(type_name)sParser.class.getCanonicalName());
private static final boolean DEBUG = Foursquare.PARSER_DEBUG;
@Override
public %(type_name)s parseInner(XmlPullParser parser) throws XmlPullParserException, IOException,
FoursquareError, FoursquareParseException {
parser.require(XmlPullParser.START_TAG, null, null);
%(type_name)s %(top_node_name)s = new %(type_name)s();
while (parser.nextTag() == XmlPullParser.START_TAG) {
String name = parser.getName();
%(stanzas)s
} else {
// Consume something we don't understand.
if (DEBUG) LOG.log(Level.FINE, "Found tag that we don't recognize: " + name);
skipSubTree(parser);
}
}
return %(top_node_name)s;
}
}"""
BOOLEAN_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(Boolean.valueOf(parser.nextText()));
"""
GROUP_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new GroupParser(new %(sub_parser_camel_case)s()).parse(parser));
"""
COMPLEX_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new %(parser_name)s().parse(parser));
"""
STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(parser.nextText());
"""
def main():
type_name, top_node_name, attributes = common.WalkNodesForAttributes(
sys.argv[1])
GenerateClass(type_name, top_node_name, attributes)
def GenerateClass(type_name, top_node_name, attributes):
"""generate it.
type_name: the type of object the parser returns
top_node_name: the name of the object the parser returns.
per common.WalkNodsForAttributes
"""
stanzas = []
for name in sorted(attributes):
typ, children = attributes[name]
replacements = Replacements(top_node_name, name, typ, children)
if typ == common.BOOLEAN:
stanzas.append(BOOLEAN_STANZA % replacements)
elif typ == common.GROUP:
stanzas.append(GROUP_STANZA % replacements)
elif typ in common.COMPLEX:
stanzas.append(COMPLEX_STANZA % replacements)
else:
stanzas.append(STANZA % replacements)
if stanzas:
# pop off the extranious } else for the first conditional stanza.
stanzas[0] = stanzas[0].replace('} else ', '', 1)
replacements = Replacements(top_node_name, name, typ, [None])
replacements['stanzas'] = '\n'.join(stanzas).strip()
print PARSER % replacements
def Replacements(top_node_name, name, typ, children):
# CameCaseClassName
type_name = ''.join([word.capitalize() for word in top_node_name.split('_')])
# CamelCaseClassName
camel_name = ''.join([word.capitalize() for word in name.split('_')])
# camelCaseLocalName
attribute_name = camel_name.lower().capitalize()
# mFieldName
field_name = 'm' + camel_name
if children[0]:
sub_parser_camel_case = children[0] + 'Parser'
else:
sub_parser_camel_case = (camel_name[:-1] + 'Parser')
return {
'type_name': type_name,
'name': name,
'top_node_name': top_node_name,
'camel_name': camel_name,
'parser_name': typ + 'Parser',
'attribute_name': attribute_name,
'field_name': field_name,
'typ': typ,
'timestamp': datetime.datetime.now(),
'sub_parser_camel_case': sub_parser_camel_case,
'sub_type': children[0]
}
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/python
"""
Pull a oAuth protected page from foursquare.
Expects ~/.oget to contain (one on each line):
CONSUMER_KEY
CONSUMER_KEY_SECRET
USERNAME
PASSWORD
Don't forget to chmod 600 the file!
"""
import httplib
import os
import re
import sys
import urllib
import urllib2
import urlparse
import user
from xml.dom import pulldom
from xml.dom import minidom
import oauth
"""From: http://groups.google.com/group/foursquare-api/web/oauth
@consumer = OAuth::Consumer.new("consumer_token","consumer_secret", {
:site => "http://foursquare.com",
:scheme => :header,
:http_method => :post,
:request_token_path => "/oauth/request_token",
:access_token_path => "/oauth/access_token",
:authorize_path => "/oauth/authorize"
})
"""
SERVER = 'api.foursquare.com:80'
CONTENT_TYPE_HEADER = {'Content-Type' :'application/x-www-form-urlencoded'}
SIGNATURE_METHOD = oauth.OAuthSignatureMethod_HMAC_SHA1()
AUTHEXCHANGE_URL = 'http://api.foursquare.com/v1/authexchange'
def parse_auth_response(auth_response):
return (
re.search('<oauth_token>(.*)</oauth_token>', auth_response).groups()[0],
re.search('<oauth_token_secret>(.*)</oauth_token_secret>',
auth_response).groups()[0]
)
def create_signed_oauth_request(username, password, consumer):
oauth_request = oauth.OAuthRequest.from_consumer_and_token(
consumer, http_method='POST', http_url=AUTHEXCHANGE_URL,
parameters=dict(fs_username=username, fs_password=password))
oauth_request.sign_request(SIGNATURE_METHOD, consumer, None)
return oauth_request
def main():
url = urlparse.urlparse(sys.argv[1])
# Nevermind that the query can have repeated keys.
parameters = dict(urlparse.parse_qsl(url.query))
password_file = open(os.path.join(user.home, '.oget'))
lines = [line.strip() for line in password_file.readlines()]
if len(lines) == 4:
cons_key, cons_key_secret, username, password = lines
access_token = None
else:
cons_key, cons_key_secret, username, password, token, secret = lines
access_token = oauth.OAuthToken(token, secret)
consumer = oauth.OAuthConsumer(cons_key, cons_key_secret)
if not access_token:
oauth_request = create_signed_oauth_request(username, password, consumer)
connection = httplib.HTTPConnection(SERVER)
headers = {'Content-Type' :'application/x-www-form-urlencoded'}
connection.request(oauth_request.http_method, AUTHEXCHANGE_URL,
body=oauth_request.to_postdata(), headers=headers)
auth_response = connection.getresponse().read()
token = parse_auth_response(auth_response)
access_token = oauth.OAuthToken(*token)
open(os.path.join(user.home, '.oget'), 'w').write('\n'.join((
cons_key, cons_key_secret, username, password, token[0], token[1])))
oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer,
access_token, http_method='POST', http_url=url.geturl(),
parameters=parameters)
oauth_request.sign_request(SIGNATURE_METHOD, consumer, access_token)
connection = httplib.HTTPConnection(SERVER)
connection.request(oauth_request.http_method, oauth_request.to_url(),
body=oauth_request.to_postdata(), headers=CONTENT_TYPE_HEADER)
print connection.getresponse().read()
#print minidom.parse(connection.getresponse()).toprettyxml(indent=' ')
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/python
import os
import subprocess
import sys
BASEDIR = '../main/src/com/joelapenna/foursquare'
TYPESDIR = '../captures/types/v1'
captures = sys.argv[1:]
if not captures:
captures = os.listdir(TYPESDIR)
for f in captures:
basename = f.split('.')[0]
javaname = ''.join([c.capitalize() for c in basename.split('_')])
fullpath = os.path.join(TYPESDIR, f)
typepath = os.path.join(BASEDIR, 'types', javaname + '.java')
parserpath = os.path.join(BASEDIR, 'parsers', javaname + 'Parser.java')
cmd = 'python gen_class.py %s > %s' % (fullpath, typepath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
cmd = 'python gen_parser.py %s > %s' % (fullpath, parserpath)
print cmd
subprocess.call(cmd, stdout=sys.stdout, shell=True)
| Python |
#!/usr/bin/python
import logging
from xml.dom import minidom
from xml.dom import pulldom
BOOLEAN = "boolean"
STRING = "String"
GROUP = "Group"
# Interfaces that all FoursquareTypes implement.
DEFAULT_INTERFACES = ['FoursquareType']
# Interfaces that specific FoursqureTypes implement.
INTERFACES = {
}
DEFAULT_CLASS_IMPORTS = [
]
CLASS_IMPORTS = {
# 'Checkin': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Venue': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Tip': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
}
COMPLEX = [
'Group',
'Badge',
'Beenhere',
'Checkin',
'CheckinResponse',
'City',
'Credentials',
'Data',
'Mayor',
'Rank',
'Score',
'Scoring',
'Settings',
'Stats',
'Tags',
'Tip',
'User',
'Venue',
]
TYPES = COMPLEX + ['boolean']
def WalkNodesForAttributes(path):
"""Parse the xml file getting all attributes.
<venue>
<attribute>value</attribute>
</venue>
Returns:
type_name - The java-style name the top node will have. "Venue"
top_node_name - unadultured name of the xml stanza, probably the type of
java class we're creating. "venue"
attributes - {'attribute': 'value'}
"""
doc = pulldom.parse(path)
type_name = None
top_node_name = None
attributes = {}
level = 0
for event, node in doc:
# For skipping parts of a tree.
if level > 0:
if event == pulldom.END_ELEMENT:
level-=1
logging.warn('(%s) Skip end: %s' % (str(level), node))
continue
elif event == pulldom.START_ELEMENT:
logging.warn('(%s) Skipping: %s' % (str(level), node))
level+=1
continue
if event == pulldom.START_ELEMENT:
logging.warn('Parsing: ' + node.tagName)
# Get the type name to use.
if type_name is None:
type_name = ''.join([word.capitalize()
for word in node.tagName.split('_')])
top_node_name = node.tagName
logging.warn('Found Top Node Name: ' + top_node_name)
continue
typ = node.getAttribute('type')
child = node.getAttribute('child')
# We don't want to walk complex types.
if typ in COMPLEX:
logging.warn('Found Complex: ' + node.tagName)
level = 1
elif typ not in TYPES:
logging.warn('Found String: ' + typ)
typ = STRING
else:
logging.warn('Found Type: ' + typ)
logging.warn('Adding: ' + str((node, typ)))
attributes.setdefault(node.tagName, (typ, [child]))
logging.warn('Attr: ' + str((type_name, top_node_name, attributes)))
return type_name, top_node_name, attributes
| Python |
#====================================================================
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ====================================================================
#
# This software consists of voluntary contributions made by many
# individuals on behalf of the Apache Software Foundation. For more
# information on the Apache Software Foundation, please see
# <http://www.apache.org/>.
#
import os
import re
import tempfile
import shutil
ignore_pattern = re.compile('^(.svn|target|bin|classes)')
java_pattern = re.compile('^.*\.java')
annot_pattern = re.compile('import org\.apache\.http\.annotation\.')
def process_dir(dir):
files = os.listdir(dir)
for file in files:
f = os.path.join(dir, file)
if os.path.isdir(f):
if not ignore_pattern.match(file):
process_dir(f)
else:
if java_pattern.match(file):
process_source(f)
def process_source(filename):
tmp = tempfile.mkstemp()
tmpfd = tmp[0]
tmpfile = tmp[1]
try:
changed = False
dst = os.fdopen(tmpfd, 'w')
try:
src = open(filename)
try:
for line in src:
if annot_pattern.match(line):
changed = True
line = line.replace('import org.apache.http.annotation.', 'import net.jcip.annotations.')
dst.write(line)
finally:
src.close()
finally:
dst.close();
if changed:
shutil.move(tmpfile, filename)
else:
os.remove(tmpfile)
except:
os.remove(tmpfile)
process_dir('.')
| Python |
import time
import pprint
def fib6(x):
if x==0 or x==1:
return 1
else:
return fib6(x-2)+fib6(x-1)
def main():
beg = time.clock()
print fib6(33)
end = time.clock()
return end - beg
print __name__
print fib6, fib6.__code__
print fib6.__code__.co_c_function
#pprint.pprint(dir(fib6))
print main
if __name__ == '__main__':
d1 = main()
import _c_fibtest
d2 = _c_fibtest.main()
print 'koef', d1 / d2 | Python |
#!/usr/bin/python
# Back-Propagation Neural Networks
#
# Written in Python. See http://www.python.org/
#
# Neil Schemenauer <nascheme@enme.ucalgary.ca>
import math
import random as random
import operator
import string
#import psyco
#psyco.full()
#from psyco.classes import *
#psyco.log()
#psyco.profile()
#__metaclass__ = type
random.seed(0)
def time(fn, *args):
import time, traceback
begin = time.clock()
result = fn(*args)
end = time.clock()
return result, end-begin
# calculate a random number where: a <= rand < b
def rand(a, b):
return (b-a)*random.random() + a
# Make a matrix (we could use NumPy to speed this up)
def makeMatrix(I, J, fill=0.0):
m = []
for i in range(I):
m.append([fill]*J)
return m
class NN:
# print 'class NN'
def __init__(self, ni, nh, no):
# number of input, hidden, and output nodes
self.ni = ni + 1 # +1 for bias node
self.nh = nh
self.no = no
# activations for nodes
self.ai = [1.0]*self.ni
self.ah = [1.0]*self.nh
self.ao = [1.0]*self.no
# create weights
self.wi = makeMatrix(self.ni, self.nh)
self.wo = makeMatrix(self.nh, self.no)
# set them to random vaules
for i in range(self.ni):
for j in range(self.nh):
self.wi[i][j] = rand(-2.0, 2.0)
for j in range(self.nh):
for k in range(self.no):
self.wo[j][k] = rand(-2.0, 2.0)
# last change in weights for momentum
self.ci = makeMatrix(self.ni, self.nh)
self.co = makeMatrix(self.nh, self.no)
def update(self, inputs):
# print 'update', inputs
if len(inputs) != self.ni-1:
raise ValueError, 'wrong number of inputs'
# input activations
for i in range(self.ni-1):
#self.ai[i] = 1.0/(1.0+math.exp(-inputs[i]))
self.ai[i] = inputs[i]
# hidden activations
for j in range(self.nh):
sum = 0.0
for i in range(self.ni):
sum = sum + self.ai[i] * self.wi[i][j]
self.ah[j] = 1.0/(1.0+math.exp(-sum))
# output activations
for k in range(self.no):
sum = 0.0
for j in range(self.nh):
sum = sum + self.ah[j] * self.wo[j][k]
self.ao[k] = 1.0/(1.0+math.exp(-sum))
return self.ao[:]
def backPropagate(self, targets, N, M):
# print N, M
if len(targets) != self.no:
raise ValueError, 'wrong number of target values'
# calculate error terms for output
output_deltas = [0.0] * self.no
# print self.no
for k in range(self.no):
ao = self.ao[k]
output_deltas[k] = ao*(1-ao)*(targets[k]-ao)
# calculate error terms for hidden
hidden_deltas = [0.0] * self.nh
for j in range(self.nh):
sum = 0.0
for k in range(self.no):
sum = sum + output_deltas[k]*self.wo[j][k]
hidden_deltas[j] = self.ah[j]*(1-self.ah[j])*sum
# update output weights
for j in range(self.nh):
for k in range(self.no):
change = output_deltas[k]*self.ah[j]
self.wo[j][k] = self.wo[j][k] + N*change + M*self.co[j][k]
self.co[j][k] = change
# update input weights
for i in range(self.ni):
for j in range(self.nh):
change = hidden_deltas[j]*self.ai[i]
self.wi[i][j] = self.wi[i][j] + N*change + M*self.ci[i][j]
self.ci[i][j] = change
# calculate error
error = 0.0
for k in range(len(targets)):
error = error + 0.5*(targets[k]-self.ao[k])**2
return error
def test(self, patterns):
for p in patterns:
print p[0], '->', self.update(p[0])
def weights(self):
print 'Input weights:'
for i in range(self.ni):
print self.wi[i]
print
print 'Output weights:'
for j in range(self.nh):
print self.wo[j]
def train(self, patterns, iterations=2000, N=0.5, M=0.1):
# N: learning rate
# M: momentum factor
for i in xrange(iterations):
error = 0.0
for p in patterns:
inputs = p[0]
targets = p[1]
self.update(inputs)
error = error + self.backPropagate(targets, N, M)
if i % 100 == 0:
print i, 'error %-14f' % error
def demo():
# Teach network XOR function
pat = [
[[0,0], [0]],
[[0,1], [1]],
[[1,0], [1]],
[[1,1], [0]]
]
# create a network with two input, two hidden, and two output nodes
n = NN(2, 3, 1)
# train it with some patterns
n.train(pat, 5000)
# test it
n.test(pat)
def demo2():
t = 0
cnt = 10
for i in range(cnt):
v, t1 = time(demo)
t = t + t1
print t / cnt
return t / cnt
if __name__ == '__main__':
t1 = demo2()
try:
import _c_bpnn3
t2 = _c_bpnn3.demo2()
print 'KOEF opt =', t1 / t2
except:
pass
| Python |
# based on a Java version:
# Based on original version written in BCPL by Dr Martin Richards
# in 1981 at Cambridge University Computer Laboratory, England
# and a C++ version derived from a Smalltalk version written by
# L Peter Deutsch.
# Java version: Copyright (C) 1995 Sun Microsystems, Inc.
# Translation from C++, Mario Wolczko
# Outer loop added by Alex Jacoby
# Task IDs
I_IDLE = 1
I_WORK = 2
I_HANDLERA = 3
I_HANDLERB = 4
I_DEVA = 5
I_DEVB = 6
# Packet types
K_DEV = 1000
K_WORK = 1001
# Packet
BUFSIZE = 4
BUFSIZE_RANGE = range(BUFSIZE)
class Packet(object):
def __init__(self,l,i,k):
self.link = l
self.ident = i
self.kind = k
self.datum = 0
self.data = [0] * BUFSIZE
def append_to(self,lst):
self.link = None
if lst is None:
return self
else:
p = lst
next = p.link
while next is not None:
p = next
next = p.link
p.link = self
return lst
# Task Records
class TaskRec(object):
pass
class DeviceTaskRec(TaskRec):
def __init__(self):
self.pending = None
class IdleTaskRec(TaskRec):
def __init__(self):
self.control = 1
self.count = 10000
class HandlerTaskRec(TaskRec):
def __init__(self):
self.work_in = None
self.device_in = None
def workInAdd(self,p):
self.work_in = p.append_to(self.work_in)
return self.work_in
def deviceInAdd(self,p):
self.device_in = p.append_to(self.device_in)
return self.device_in
class WorkerTaskRec(TaskRec):
def __init__(self):
self.destination = I_HANDLERA
self.count = 0
# Task
class TaskState(object):
def __init__(self):
self.packet_pending = True
self.task_waiting = False
self.task_holding = False
def packetPending(self):
self.packet_pending = True
self.task_waiting = False
self.task_holding = False
return self
def waiting(self):
self.packet_pending = False
self.task_waiting = True
self.task_holding = False
return self
def running(self):
self.packet_pending = False
self.task_waiting = False
self.task_holding = False
return self
def waitingWithPacket(self):
self.packet_pending = True
self.task_waiting = True
self.task_holding = False
return self
def isPacketPending(self):
return self.packet_pending
def isTaskWaiting(self):
return self.task_waiting
def isTaskHolding(self):
return self.task_holding
def isTaskHoldingOrWaiting(self):
return self.task_holding or (not self.packet_pending and self.task_waiting)
def isWaitingWithPacket(self):
return self.packet_pending and self.task_waiting and not self.task_holding
tracing = False
layout = 0
def trace(a):
global layout
layout -= 1
if layout <= 0:
print
layout = 50
print a,
TASKTABSIZE = 10
class TaskWorkArea(object):
def __init__(self):
self.taskTab = [None] * TASKTABSIZE
self.taskList = None
self.holdCount = 0
self.qpktCount = 0
taskWorkArea = TaskWorkArea()
class Task(TaskState):
def __init__(self,i,p,w,initialState,r):
self.link = taskWorkArea.taskList
self.ident = i
self.priority = p
self.input = w
self.packet_pending = initialState.isPacketPending()
self.task_waiting = initialState.isTaskWaiting()
self.task_holding = initialState.isTaskHolding()
self.handle = r
taskWorkArea.taskList = self
taskWorkArea.taskTab[i] = self
def fn(self,pkt,r):
raise NotImplementedError
def addPacket(self,p,old):
if self.input is None:
self.input = p
self.packet_pending = True
if self.priority > old.priority:
return self
else:
p.append_to(self.input)
return old
def runTask(self):
if self.isWaitingWithPacket():
msg = self.input
self.input = msg.link
if self.input is None:
self.running()
else:
self.packetPending()
else:
msg = None
return self.fn(msg,self.handle)
def waitTask(self):
self.task_waiting = True
return self
def hold(self):
taskWorkArea.holdCount += 1
self.task_holding = True
return self.link
def release(self,i):
t = self.findtcb(i)
t.task_holding = False
if t.priority > self.priority:
return t
else:
return self
def qpkt(self,pkt):
t = self.findtcb(pkt.ident)
taskWorkArea.qpktCount += 1
pkt.link = None
pkt.ident = self.ident
return t.addPacket(pkt,self)
def findtcb(self,id):
t = taskWorkArea.taskTab[id]
if t is None:
raise Exception("Bad task id %d" % id)
return t
# DeviceTask
class DeviceTask(Task):
def __init__(self,i,p,w,s,r):
Task.__init__(self,i,p,w,s,r)
def fn(self,pkt,r):
d = r
assert isinstance(d, DeviceTaskRec)
if pkt is None:
pkt = d.pending
if pkt is None:
return self.waitTask()
else:
d.pending = None
return self.qpkt(pkt)
else:
d.pending = pkt
if tracing: trace(pkt.datum)
return self.hold()
class HandlerTask(Task):
def __init__(self,i,p,w,s,r):
Task.__init__(self,i,p,w,s,r)
def fn(self,pkt,r):
h = r
assert isinstance(h, HandlerTaskRec)
if pkt is not None:
if pkt.kind == K_WORK:
h.workInAdd(pkt)
else:
h.deviceInAdd(pkt)
work = h.work_in
if work is None:
return self.waitTask()
count = work.datum
if count >= BUFSIZE:
h.work_in = work.link
return self.qpkt(work)
dev = h.device_in
if dev is None:
return self.waitTask()
h.device_in = dev.link
dev.datum = work.data[count]
work.datum = count + 1
return self.qpkt(dev)
# IdleTask
class IdleTask(Task):
def __init__(self,i,p,w,s,r):
Task.__init__(self,i,0,None,s,r)
def fn(self,pkt,r):
i = r
assert isinstance(i, IdleTaskRec)
i.count -= 1
if i.count == 0:
return self.hold()
elif i.control & 1 == 0:
i.control /= 2
return self.release(I_DEVA)
else:
i.control = i.control/2 ^ 0xd008
return self.release(I_DEVB)
# WorkTask
A = ord('A')
class WorkTask(Task):
def __init__(self,i,p,w,s,r):
Task.__init__(self,i,p,w,s,r)
def fn(self,pkt,r):
w = r
assert isinstance(w, WorkerTaskRec)
if pkt is None:
return self.waitTask()
if w.destination == I_HANDLERA:
dest = I_HANDLERB
else:
dest = I_HANDLERA
w.destination = dest
pkt.ident = dest
pkt.datum = 0
for i in BUFSIZE_RANGE: # xrange(BUFSIZE)
w.count += 1
if w.count > 26:
w.count = 1
pkt.data[i] = A + w.count - 1
return self.qpkt(pkt)
import time
def schedule():
t = taskWorkArea.taskList
while t is not None:
pkt = None
# print '-----', 218, t
if tracing:
print "tcb =",t.ident
# print '-----', 219, t
if t.isTaskHoldingOrWaiting():
t = t.link
# print '-----', 220, t
else:
# print '-----', 221, t
if tracing: trace(chr(ord("0")+t.ident))
# print '-----', 222, t
t = t.runTask()
# print '-----', 223, t
class Richards(object):
def run(self, iterations):
for i in xrange(iterations):
taskWorkArea.holdCount = 0
taskWorkArea.qpktCount = 0
# print '--- 111', i
IdleTask(I_IDLE, 1, 10000, TaskState().running(), IdleTaskRec())
# print '--- 112', i
wkq = Packet(None, 0, K_WORK)
wkq = Packet(wkq , 0, K_WORK)
WorkTask(I_WORK, 1000, wkq, TaskState().waitingWithPacket(), WorkerTaskRec())
# print '--- 113', i
wkq = Packet(None, I_DEVA, K_DEV)
wkq = Packet(wkq , I_DEVA, K_DEV)
wkq = Packet(wkq , I_DEVA, K_DEV)
HandlerTask(I_HANDLERA, 2000, wkq, TaskState().waitingWithPacket(), HandlerTaskRec())
# print '--- 114', i
wkq = Packet(None, I_DEVB, K_DEV)
wkq = Packet(wkq , I_DEVB, K_DEV)
wkq = Packet(wkq , I_DEVB, K_DEV)
HandlerTask(I_HANDLERB, 3000, wkq, TaskState().waitingWithPacket(), HandlerTaskRec())
# print '--- 115', i
wkq = None;
DeviceTask(I_DEVA, 4000, wkq, TaskState().waiting(), DeviceTaskRec());
# print '--- 116', i
DeviceTask(I_DEVB, 5000, wkq, TaskState().waiting(), DeviceTaskRec());
# print '--- 117', i
schedule()
# print '--- 118', i
if taskWorkArea.holdCount == 9297 and taskWorkArea.qpktCount == 23246:
pass
else:
return False
return True
def entry_point(iterations):
r = Richards()
startTime = time.time()
result = r.run(iterations)
endTime = time.time()
return result, startTime, endTime
def main(entry_point = entry_point, iterations = 3):
print "Richards benchmark (Python) starting... [%r]" % entry_point
result, startTime, endTime = entry_point(iterations)
if not result:
print "Incorrect results!"
return -1
print "finished."
total_s = endTime - startTime
print "Total time for %d iterations: %.2f secs" %(iterations,total_s)
print "Average time per iteration: %.2f ms" %(total_s*1000/iterations)
return 42
if __name__ == '__main__':
import sys
if len(sys.argv) >= 2:
main(iterations = int(sys.argv[1]))
else:
main()
# import profile
# profile.runctx('main()', globals(), locals())
import _c_richards
if len(sys.argv) >= 2:
_c_richards.main(iterations = int(sys.argv[1]))
else:
_c_richards.main()
| Python |
#! /usr/bin/env python
"""
"PYSTONE" Benchmark Program
Version: Python/1.1 (corresponds to C/1.1 plus 2 Pystone fixes)
Author: Reinhold P. Weicker, CACM Vol 27, No 10, 10/84 pg. 1013.
Translated from ADA to C by Rick Richardson.
Every method to preserve ADA-likeness has been used,
at the expense of C-ness.
Translated from C to Python by Guido van Rossum.
Version History:
Version 1.1 corrects two bugs in version 1.0:
First, it leaked memory: in Proc1(), NextRecord ends
up having a pointer to itself. I have corrected this
by zapping NextRecord.PtrComp at the end of Proc1().
Second, Proc3() used the operator != to compare a
record to None. This is rather inefficient and not
true to the intention of the original benchmark (where
a pointer comparison to None is intended; the !=
operator attempts to find a method __cmp__ to do value
comparison of the record). Version 1.1 runs 5-10
percent faster than version 1.0, so benchmark figures
of different versions can't be compared directly.
"""
LOOPS = 100000
from time import clock
__version__ = "1.1"
[Ident1, Ident2, Ident3, Ident4, Ident5] = range(1, 6)
class Record:
def __init__(self, PtrComp = None, Discr = 0, EnumComp = 0,
IntComp = 0, StringComp = 0):
self.PtrComp = PtrComp
self.Discr = Discr
self.EnumComp = EnumComp
self.IntComp = IntComp
self.StringComp = StringComp
def copy(self):
return Record(self.PtrComp, self.Discr, self.EnumComp,
self.IntComp, self.StringComp)
TRUE = 1
FALSE = 0
def main():
benchtime, s1 = Proc0(LOOPS)
print "Pystone(%s) (first time) time for %d passes = %g" % \
(__version__, LOOPS, benchtime)
print "This machine benchmarks at %g pystones/second" % s1
benchtime, s2 = Proc0(LOOPS)
print "Pystone(%s) (second time) time for %d passes = %g" % \
(__version__, LOOPS, benchtime)
print "This machine benchmarks at %g pystones/second" % s2
print
print "Pystone executed %g times faster the second time" % (s2/float(s1))
IntGlob = 0
BoolGlob = FALSE
Char1Glob = '\0'
Char2Glob = '\0'
Array1Glob = [0]*51
Array2Glob = map(lambda x: x[:], [Array1Glob]*51)
PtrGlb = None
PtrGlbNext = None
def Proc0(loops=LOOPS):
global IntGlob
global BoolGlob
global Char1Glob
global Char2Glob
global Array1Glob
global Array2Glob
global PtrGlb
global PtrGlbNext
starttime = clock()
for i in range(loops):
pass
nulltime = clock() - starttime
PtrGlbNext = Record()
PtrGlb = Record()
PtrGlb.PtrComp = PtrGlbNext
PtrGlb.Discr = Ident1
PtrGlb.EnumComp = Ident3
PtrGlb.IntComp = 40
PtrGlb.StringComp = "DHRYSTONE PROGRAM, SOME STRING"
String1Loc = "DHRYSTONE PROGRAM, 1'ST STRING"
Array2Glob[8][7] = 10
starttime = clock()
for i in range(loops):
Proc5()
Proc4()
IntLoc1 = 2
IntLoc2 = 3
String2Loc = "DHRYSTONE PROGRAM, 2'ND STRING"
EnumLoc = Ident2
BoolGlob = not Func2(String1Loc, String2Loc)
while IntLoc1 < IntLoc2:
IntLoc3 = 5 * IntLoc1 - IntLoc2
IntLoc3 = Proc7(IntLoc1, IntLoc2)
IntLoc1 = IntLoc1 + 1
Proc8(Array1Glob, Array2Glob, IntLoc1, IntLoc3)
PtrGlb = Proc1(PtrGlb)
CharIndex = 'A'
while CharIndex <= Char2Glob:
if EnumLoc == Func1(CharIndex, 'C'):
EnumLoc = Proc6(Ident1)
CharIndex = chr(ord(CharIndex)+1)
IntLoc3 = IntLoc2 * IntLoc1
IntLoc2 = IntLoc3 / IntLoc1
IntLoc2 = 7 * (IntLoc3 - IntLoc2) - IntLoc1
IntLoc1 = Proc2(IntLoc1)
benchtime = clock() - starttime - nulltime
return benchtime, (loops / benchtime)
def Proc1(PtrParIn):
PtrParIn.PtrComp = NextRecord = PtrGlb.copy()
PtrParIn.IntComp = 5
NextRecord.IntComp = PtrParIn.IntComp
NextRecord.PtrComp = PtrParIn.PtrComp
NextRecord.PtrComp = Proc3(NextRecord.PtrComp)
if NextRecord.Discr == Ident1:
NextRecord.IntComp = 6
NextRecord.EnumComp = Proc6(PtrParIn.EnumComp)
NextRecord.PtrComp = PtrGlb.PtrComp
NextRecord.IntComp = Proc7(NextRecord.IntComp, 10)
else:
PtrParIn = NextRecord.copy()
NextRecord.PtrComp = None
return PtrParIn
def Proc2(IntParIO):
IntLoc = IntParIO + 10
while 1:
if Char1Glob == 'A':
IntLoc = IntLoc - 1
IntParIO = IntLoc - IntGlob
EnumLoc = Ident1
if EnumLoc == Ident1:
break
return IntParIO
def Proc3(PtrParOut):
global IntGlob
if PtrGlb is not None:
PtrParOut = PtrGlb.PtrComp
else:
IntGlob = 100
PtrGlb.IntComp = Proc7(10, IntGlob)
return PtrParOut
def Proc4():
global Char2Glob
BoolLoc = Char1Glob == 'A'
BoolLoc = BoolLoc or BoolGlob
Char2Glob = 'B'
def Proc5():
global Char1Glob
global BoolGlob
Char1Glob = 'A'
BoolGlob = FALSE
def Proc6(EnumParIn):
EnumParOut = EnumParIn
if not Func3(EnumParIn):
EnumParOut = Ident4
if EnumParIn == Ident1:
EnumParOut = Ident1
elif EnumParIn == Ident2:
if IntGlob > 100:
EnumParOut = Ident1
else:
EnumParOut = Ident4
elif EnumParIn == Ident3:
EnumParOut = Ident2
elif EnumParIn == Ident4:
pass
elif EnumParIn == Ident5:
EnumParOut = Ident3
return EnumParOut
def Proc7(IntParI1, IntParI2):
IntLoc = IntParI1 + 2
IntParOut = IntParI2 + IntLoc
return IntParOut
def Proc8(Array1Par, Array2Par, IntParI1, IntParI2):
global IntGlob
IntLoc = IntParI1 + 5
Array1Par[IntLoc] = IntParI2
Array1Par[IntLoc+1] = Array1Par[IntLoc]
Array1Par[IntLoc+30] = IntLoc
for IntIndex in range(IntLoc, IntLoc+2):
Array2Par[IntLoc][IntIndex] = IntLoc
Array2Par[IntLoc][IntLoc-1] = Array2Par[IntLoc][IntLoc-1] + 1
Array2Par[IntLoc+20][IntLoc] = Array1Par[IntLoc]
IntGlob = 5
def Func1(CharPar1, CharPar2):
CharLoc1 = CharPar1
CharLoc2 = CharLoc1
if CharLoc2 != CharPar2:
return Ident1
else:
return Ident2
def Func2(StrParI1, StrParI2):
IntLoc = 1
while IntLoc <= 1:
if Func1(StrParI1[IntLoc], StrParI2[IntLoc+1]) == Ident1:
CharLoc = 'A'
IntLoc = IntLoc + 1
if CharLoc >= 'W' and CharLoc <= 'Z':
IntLoc = 7
if CharLoc == 'X':
return TRUE
else:
if StrParI1 > StrParI2:
IntLoc = IntLoc + 7
return TRUE
else:
return FALSE
def Func3(EnumParIn):
EnumLoc = EnumParIn
if EnumLoc == Ident3: return TRUE
return FALSE
if __name__ == '__main__':
main()
print ' *** '
import _c_pystone
_c_pystone.main() | Python |
"""2c.py -- Python-to-C compiler"""
Author = "Bulatov Vladislav"
## 2c.py is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
## 2c.py 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 General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
import types
import sys
import glob
import traceback
import gc
import os
import time
#from distutils.command import build_ext
from distutils.ccompiler import new_compiler
from optparse import OptionParser
is_pypy = 'PyPy' in sys.version
try:
import android
sys.argv.extend(['-c -e ', \
'/mnt/sdcard/sl4a/scripts/zipfile.py']) # = sys.argv + [sys.argv[0]]
sys.stdout = open(sys.argv[0] + '.log', 'w')
except:
pass
import warnings
from cStringIO import StringIO as _StringIO
def pprint(object, stream=None, indent=1, width=80, depth=None):
printer = PrettyPrinter(
stream=stream, indent=indent, width=width, depth=depth)
printer.pprint(object)
##def pformat(object, indent=1, width=80, depth=None):
## return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)
class PrettyPrinter:
def __init__(self, indent=1, width=80, depth=None, stream=None):
indent = int(indent)
width = int(width)
assert indent >= 0, "indent must be >= 0"
assert depth is None or depth > 0, "depth must be > 0"
assert width, "width must be != 0"
self._depth = depth
self._indent_per_level = indent
self._width = width
if stream is not None:
self._stream = stream
else:
self._stream = sys.stdout
def pprint(self, object):
self._format(object, self._stream, 0, 0, {}, 0)
self._stream.write("\n")
def pformat(self, object):
sio = _StringIO()
self._format(object, sio, 0, 0, {}, 0)
### print self._width, ' ??? '
return sio.getvalue()
def isrecursive(self, object):
return self.format(object, {}, 0, 0)[2]
def isreadable(self, object):
s, readable, recursive = self.format(object, {}, 0, 0)
return readable and not recursive
def _format(self, object, stream, indent, allowance, context, level):
level = level + 1
objid = id(object)
if objid in context:
stream.write(_recursion(object))
self._recursive = True
self._readable = False
return
rep = self._repr(object, context, level - 1)
typ = type(object)
sepLines = len(rep) > (self._width - 1 - indent - allowance)
if self._depth and level > self._depth:
stream.write(rep)
return
r = getattr(typ, "__repr__", None)
if issubclass(typ, dict) and r is dict.__repr__:
stream.write('{')
if self._indent_per_level > 1:
stream.write((self._indent_per_level - 1) * ' ')
length = len(object)
if length:
context[objid] = 1
indent = indent + self._indent_per_level
items = object.items()
key, ent = items[0]
rep = self._repr(key, context, level)
stream.write(rep)
stream.write(': ')
self._format(ent, stream, indent + len(rep) + 2,
allowance + 1, context, level)
if length > 1:
for key, ent in items[1:]:
rep = self._repr(key, context, level)
if sepLines:
stream.write(',\n%s%s: ' % (' '*indent, rep))
else:
stream.write(', %s: ' % rep)
self._format(ent, stream, indent + len(rep) + 2,
allowance + 1, context, level)
indent = indent - self._indent_per_level
del context[objid]
stream.write('}')
return
if ((issubclass(typ, list) and r == list.__repr__) or
(issubclass(typ, tuple) and r == tuple.__repr__) or
(issubclass(typ, set) and r == set.__repr__) or
(issubclass(typ, frozenset) and r == frozenset.__repr__)
):
length = len(object)
if issubclass(typ, list):
stream.write('[')
endchar = ']'
elif issubclass(typ, set):
if not length:
stream.write('set()')
return
stream.write('set([')
endchar = '])'
## object = sorted(object)
indent += 4
elif issubclass(typ, frozenset):
if not length:
stream.write('frozenset()')
return
stream.write('frozenset([')
endchar = '])'
## object = sorted(object)
indent += 10
else:
stream.write('(')
endchar = ')'
if self._indent_per_level > 1 and sepLines:
stream.write((self._indent_per_level - 1) * ' ')
if length:
context[objid] = 1
indent = indent + self._indent_per_level
self._format(object[0], stream, indent, allowance + 1,
context, level)
if length > 1:
for ent in object[1:]:
if sepLines:
stream.write(',\n' + ' '*indent)
else:
stream.write(', ')
self._format(ent, stream, indent,
allowance + 1, context, level)
indent = indent - self._indent_per_level
del context[objid]
if issubclass(typ, tuple) and length == 1:
stream.write(',')
stream.write(endchar)
return
stream.write(rep)
def _repr(self, object, context, level):
repr, readable, recursive = self.format(object, context.copy(),
self._depth, level)
if not readable:
self._readable = False
if recursive:
self._recursive = True
return repr
def format(self, object, context, maxlevels, level):
return _safe_repr(object, context, maxlevels, level)
# Return triple (repr_string, isreadable, isrecursive).
def _safe_repr(object, context, maxlevels, level):
typ = type(object)
assert type(context) is dict
if type(object) is str:
if 'locale' not in sys.modules:
return repr(object), True, False
if "'" in object and '"' not in object:
closure = '"'
quotes = {'"': '\\"'}
else:
closure = "'"
quotes = {"'": "\\'"}
sio = _StringIO()
for char in object:
if char.isalpha():
sio.write(char)
else:
sio.write(quotes.get(char, repr(char)[1:-1]))
return ("%s%s%s" % (closure, sio.getvalue(), closure)), True, False
r = getattr(typ, "__repr__", None)
if issubclass(typ, dict) and r == dict.__repr__:
if not object:
return "{}", True, False
objid = id(object)
if maxlevels and level >= maxlevels:
return "{...}", False, objid in context
if objid in context:
return _recursion(object), False, True
context[objid] = 1
readable = True
recursive = False
components = []
level += 1
for k, v in object.items():
krepr, kreadable, krecur = _safe_repr(k, context, maxlevels, level)
vrepr, vreadable, vrecur = _safe_repr(v, context, maxlevels, level)
components.append("%s: %s" % (krepr, vrepr))
readable = readable and kreadable and vreadable
if krecur or vrecur:
recursive = True
del context[objid]
return "{%s}" % ", ".join(components), readable, recursive
if (issubclass(typ, list) and r == list.__repr__) or \
(issubclass(typ, tuple) and r == tuple.__repr__):
if issubclass(typ, list):
if not object:
return "[]", True, False
format = "[%s]"
elif len(object) == 1:
format = "(%s,)"
else:
if not object:
return "()", True, False
format = "(%s)"
objid = id(object)
if maxlevels and level >= maxlevels:
return format % "...", False, objid in context
if objid in context:
return _recursion(object), False, True
context[objid] = 1
readable = True
recursive = False
components = []
level += 1
for o in object:
orepr, oreadable, orecur = _safe_repr(o, context, maxlevels, level)
components.append(orepr)
if not oreadable:
readable = False
if orecur:
recursive = True
del context[objid]
return format % ", ".join(components), readable, recursive
rep = repr(object)
return rep, (rep and not rep.startswith('<')), False
def saferepr(object):
return _safe_repr(object, {}, None, 0)[0]
def isreadable(object):
return _safe_repr(object, {}, None, 0)[1]
def isrecursive(object):
return _safe_repr(object, {}, None, 0)[2]
def _recursion(object):
return ("<Recursion on %s with id=%s>"
% (type(object).__name__, id(object)))
d_built = {'ArithmeticError': ArithmeticError,
'AssertionError': AssertionError,
'AttributeError': AttributeError,
'BaseException': BaseException,
#'BufferError': BufferError,
#'BytesWarning': BytesWarning,
'DeprecationWarning': DeprecationWarning,
'EOFError': EOFError,
'Ellipsis': Ellipsis,
'EnvironmentError': EnvironmentError,
'Exception': Exception,
'False': False,
'FloatingPointError': FloatingPointError,
'FutureWarning': FutureWarning,
'GeneratorExit': GeneratorExit,
'IOError': IOError,
'ImportError': ImportError,
'ImportWarning': ImportWarning,
'IndentationError': IndentationError,
'IndexError': IndexError,
'KeyError': KeyError,
'KeyboardInterrupt': KeyboardInterrupt,
'LookupError': LookupError,
'MemoryError': MemoryError,
'NameError': NameError,
'None': None,
'NotImplemented': NotImplemented,
'NotImplementedError': NotImplementedError,
'OSError': OSError,
'OverflowError': OverflowError,
'PendingDeprecationWarning': PendingDeprecationWarning,
'ReferenceError': ReferenceError,
'RuntimeError': RuntimeError,
'RuntimeWarning': RuntimeWarning,
'StandardError': StandardError,
'StopIteration': StopIteration,
'SyntaxError': SyntaxError,
'SyntaxWarning': SyntaxWarning,
'SystemError': SystemError,
'SystemExit': SystemExit,
'TabError': TabError,
'True': True,
'TypeError': TypeError,
'UnboundLocalError': UnboundLocalError,
'UnicodeDecodeError': UnicodeDecodeError,
'UnicodeEncodeError': UnicodeEncodeError,
'UnicodeError': UnicodeError,
'UnicodeTranslateError': UnicodeTranslateError,
'UnicodeWarning': UnicodeWarning,
'UserWarning': UserWarning,
'ValueError': ValueError,
'Warning': Warning,
'ZeroDivisionError': ZeroDivisionError,
##'__debug__': __debug__,
##'__doc__': __doc__,
'__import__': __import__,
##'__name__': __name__,
##'__package__': __package__,
'abs': abs,
'all': all,
'any': any,
'apply': apply,
'basestring': basestring,
#'bin': bin,
'bool': bool,
'buffer': buffer,
#'bytearray': bytearray,
#'bytes': bytes,
'callable': callable,
'chr': chr,
'classmethod': classmethod,
'cmp': cmp,
'coerce': coerce,
'compile': compile,
'complex': complex,
'copyright': copyright,
'credits': credits,
'delattr': delattr,
'dict': dict,
'dir': dir,
'divmod': divmod,
'enumerate': enumerate,
'eval': eval,
'execfile': execfile,
'exit': exit,
'file': file,
'filter': filter,
'float': float,
#'format': format,
'frozenset': frozenset,
'getattr': getattr,
'globals': globals,
'hasattr': hasattr,
'hash': hash,
'help': help,
'hex': hex,
'id': id,
'input': input,
'int': int,
'intern': intern,
'isinstance': isinstance,
'issubclass': issubclass,
'iter': iter,
'len': len,
'license': license,
'list': list,
'locals': locals,
'long': long,
'map': map,
'max': max,
'min': min,
##'next': next,
'object': object,
'oct': oct,
'open': open,
'ord': ord,
'pow': pow,
##'print': print,
'property': property,
'quit': quit,
'range': range,
'raw_input': raw_input,
'reduce': reduce,
'reload': reload,
'repr': repr,
'reversed': reversed,
'round': round,
'set': set,
'setattr': setattr,
'slice': slice,
'sorted': sorted,
'staticmethod': staticmethod,
'str': str,
'sum': sum,
'super': super,
'tuple': tuple,
'type': type,
'unichr': unichr,
'unicode': unicode,
'vars': vars,
'xrange': xrange,
'zip': zip}
if tuple(sys.version_info)[:2] > (2,5):
d_built['BufferError'] = BufferError
d_built['BytesWarning'] = BytesWarning
d_built['bin'] = bin
d_built['bytearray'] = bytearray
d_built['bytes'] = bytes
d_built['format'] = format
d_built['next'] = next
if tuple(sys.version_info)[:2] > (2,6):
d_built['memoryview'] = memoryview
# d_built['print'] = print
d_built_inv = dict([(y,x) for x,y in d_built.iteritems()])
import math
import StringIO
import operator
import csv
import distutils.core
out = -1
out3 = -1
debug = False
filename = ""
global Pass
global Prev_Time
global Prev_Pass
global Pass_Exit
Pass = {}
Prev_Time = None
Prev_Pass = None
Pass_Exit = None
tags_one_step_expr = ('CONST', 'FAST', 'BUILTIN', 'TYPED_TEMP', \
'LOAD_CLOSURE', 'PY_TEMP', \
# 'CODEFUNC', \
'f->f_locals', \
'bdict', 'CALC_CONST', 'PY_TYPE')
TRUE = ('CONST', True) #True #cmd2mem(('LOAD_CONST', True))
pos__a = pos__b = pos__c = pos__d = pos__e = pos__f = pos__g = pos__h = pos__i = pos__j = pos__k = pos__l = ""
call = ('CALL_FUNCTION_VAR', 'CALL_FUNCTION_KW', 'CALL_FUNCTION_VAR_KW', 'CALL_FUNCTION', 'CALL_METHOD')
set_var = ('STORE_FAST', 'STORE_NAME', 'STORE_GLOBAL', 'STORE_DEREF')
set_any = set_var + ('PyObject_SetAttr', 'PyObject_SetItem','STORE_SLICE_LV+0',\
'STORE_SLICE_LV+1', 'STORE_SLICE_LV+2','STORE_SLICE_LV+3',\
'SET_VARS')
build_executable = False
no_compiled = {}
detected_attr_type = {}
detected_return_type = {}
default_args = {}
mnemonic_constant = {}
all_calc_const = {}
calc_const_value = {}
val_direct_code = {}
direct_code = {}
list_import = {}
global start_sys_modules
start_sys_modules = None
redefined_builtin = {}
redefined_attribute = True
all_trin = {}
global Line2Addr
Line2Addr = []
global direct_args
direct_args = {}
redefined_all = False
count_define_set = {}
count_define_get = {}
matched_tail_label = ''
self_attr_type = {}
## global is_current & IS_DIRECT
## is_current = IS_CALLABLE_COMPILABLE
## global is_current & IS_CFUNC
## is_current & IS_CFUNC = False
IS_CFUNC = 0x1
IS_DIRECT = 0x2
IS_CODEFUNC = 0x4
IS_PCODE = 0x8
IS_CALLABLE_COMPILABLE = (IS_CFUNC | IS_CODEFUNC )
global is_current
is_current = 0
type_def = {}
list_cname_exe = []
calc_const_old_class = {}
calc_const_new_class = {}
##global generate_declaration
##generate_declaration = False
def _3(nm, attr, value):
global all_trin
all_trin[(nm,attr,value)] = True
## pprint(all_trin.keys())
flag_stat = False
stat_3 = {}
def Val3(nm, attr):
if flag_stat:
if not (attr in stat_3):
stat_3[attr] = 0
stat_3[attr] += 1
for a,b,c in all_trin.keys():
if nm is not None and a != nm:
continue
if attr is not None and b != attr:
continue
return c
return None
def Is3(nm, attr, value=None):
if flag_stat:
if not (attr in stat_3):
stat_3[attr] = 0
stat_3[attr] += 1
for a,b,c in all_trin.keys():
if nm is not None and a != nm:
continue
if attr is not None and b != attr:
continue
if value is not None and c != value:
continue
return True
return False
def Iter3(nm, attr, value):
if flag_stat:
if not (attr in stat_3):
stat_3[attr] = 0
stat_3[attr] += 1
ret = []
for a,b,c in all_trin.keys():
if nm is not None and a != nm:
continue
if attr is not None and b != attr:
continue
if value is not None and c != value:
continue
ret.append((a,b,c))
return ret
linear_debug = True
def HideDebug(*args):
pass
uniq_debug_messages = {}
def Debug(*args):
if hide_debug:
return
if linear_debug:
s = ' '.join([repr(v) for v in args])
s = s.replace('\"', '\'')
# if len(s) < 1998:
uniq_debug_messages[s] = None
else:
stream = StringIO.StringIO()
for v in args:
pprint(v, stream, 1, 98)
ls = stream.getvalue().split('\n')
if ls[-1] == '':
del ls[-1]
stream.close()
ls.insert(0, '<<<')
ls.append('>>>')
for iit in ls:
print ('-- ' + iit)
def FlushDebug():
l = uniq_debug_messages.keys()
l.sort()
for s in l:
print ('-- ' + s)
uniq_debug_messages.clear()
def Fatal(msg, *args):
FlushDebug()
print (msg + ' ' + str(args))
## Debug(*args)
## FlushDebug()
assert False
T_OLD_CL_TYP = 'OldClassType'
T_OLD_CL_INST = 'OldClassInstance'
T_NEW_CL_TYP = 'NewClassType'
T_NEW_CL_INST = 'NewClassInstance'
def is_old_class_inst(t):
return t[0] == T_OLD_CL_INST
def is_old_class_typ(t):
return t[0] == T_OLD_CL_TYP
def is_new_class_inst(t):
return t[0] == T_NEW_CL_INST
def is_new_class_typ(t):
return t[0] == T_NEW_CL_TYP
def IsModule(t):
return t is not None and t[0] is types.ModuleType
def IsInt(t):
return t is not None and t[0] is int
def IsIntOnly(t):
return t is not None and t[0] is int and t[1] is None
def IsShort(t):
return t is not None and t[0] is int and t[1] == 'ssize'
def IsStr(t):
return t is not None and t[0] is str
def IsLong(t):
return t is not None and t[0] is long
def IsChar(t):
return t is not None and t[0] is str and t[1] == 1
def IsBool(t):
return t is not None and t[0] is bool
def IsFloat(t):
return t is not None and t[0] is float
def IsNoneOrInt(t):
return t is None or t[0] is int
def IsNoneOrIntOrFloat(t):
return t is None or t[0] is int or t[0] is float
def IsKlNone(t):
return t is not None and t[0] is types.NoneType
def IsIntOrFloat(t):
return t is not None and (t[0] is int or t[0] is float)
def IsIntUndefSize(t):
return t is not None and (t[0] == 'IntOrLong')
def IsTuple(t):
return t is not None and t[0] is tuple
def IsInTupleInd(t, ind):
t2 = t[1]
assert type(ind) is int and ind >= 0
if type(t2) is int and ind < t2:
return True
if type(t2) is tuple and ind < len(t2):
return True
return False
def IsList(t):
if t is None:
return False
if t[0] is list:
return True
return False
def IsListAll(t):
if t is None:
return False
if t[0] is list:
return True
if t[0] == T_NEW_CL_INST and Is3(t[1], 'Derived', ('!LOAD_BUILTIN', 'list')):
return True
return False
def IsDict(t):
return t is not None and t[0] is dict
## def IsMayBe(t, f=None):
## return bool(t is not None and t[0] == 'MayBe' and (f is None or f(t[1])))
def IsNot(t, t2=None):
if t is not None and t[0] == 'Not':
if t2 is not None:
return t2 in t[1]
else:
return True
return False
Kl_String = (str, None)
Kl_Unicode = (unicode, None)
if tuple(sys.version_info)[:2] > (2,5):
Kl_ByteArray = (bytearray, None)
Kl_Char = (str, 1)
Kl_IntUndefSize = ('IntOrLong', None)
Kl_Int = (int, None)
Kl_Short = (int, 'ssize')
Kl_Float = (float, None)
Kl_List = (list, None)
Kl_Tuple = (tuple, None)
Kl_Dict = (dict, None)
Kl_Set = (set, None)
Kl_FrozenSet = (frozenset, None)
Kl_Long = (long, None)
Kl_Type = (type, None)
##Kl_TypeType = Kl_Type
Kl_None = (types.NoneType, None)
Kl_File = (types.FileType, None)
Kl_Slice = (types.SliceType, None)
Kl_Buffer = (types.BufferType, None)
Kl_XRange = (types.XRangeType, None)
Kl_Boolean = (bool, None)
Kl_BuiltinFunction = (types.BuiltinFunctionType, None)
Kl_Function = (types.FunctionType, None)
Kl_StaticMethod = (types.MethodType, 'static')
Kl_ClassMethod = (types.MethodType, 'class')
Kl_Method = (types.MethodType, 'instance')
Kl_Generator = (types.GeneratorType, None)
Kl_Complex = (complex, None)
##Kl_Unicode = (unicode, None)
Kl_OldType = (T_OLD_CL_TYP, None)
Kl_OldInst = (T_OLD_CL_INST, None)
Kl_NewType = (T_NEW_CL_TYP, None)
Kl_NewInst = (T_NEW_CL_INST, None)
Kl_RegexObject = (T_OLD_CL_INST, 'RegexObject')
Kl_MatchObject = (T_OLD_CL_INST, 'MatchObject')
## Nm_Klass = {Kl_String : 'Kl_String', Kl_Int : 'Kl_Int', Kl_Float : 'Kl_Float',
## Kl_List : 'Kl_List', Kl_Tuple : 'Kl_Tuple', Kl_Dict : 'Kl_Dict',
## Kl_None : 'Kl_None', Kl_Boolean : 'Kl_Boolean', Kl_OldType : 'Kl_OldType',
## Kl_OldInst : 'Kl_OldInst', Kl_NewType : 'Kl_NewType', Kl_NewInst : 'Kl_NewInst',
## Kl_File : 'Kl_File', Kl_Slice : 'Kl_Slice', Kl_XRange : 'Kl_XRange',
## Kl_Buffer: 'Kl_Buffer', Kl_StaticMethod : 'Kl_StaticMethod',
## Kl_ClassMethod : 'Kl_ClassMethod', Kl_Method : 'Kl_Method',
## Kl_Complex : 'Kl_Complex', Kl_Char : 'Kl_Char', Kl_RegexObject : 'Kl_RegexObject',
## Kl_MatchObject : 'Kl_MatchObject', Kl_Set : 'Kl_Set', Kl_FrozenSet : 'Kl_FrozenSet',
## Kl_Long : 'Kl_Long', Kl_Type : 'Kl_Type', # Kl_ByteArray : 'Kl_ByteArray',
## Kl_Generator : 'Kl_Generator', Kl_BuiltinFunction: 'Kl_BuiltinFunction',
## Kl_Function: 'Kl_Function', Kl_Short : 'Kl_Short', Kl_Unicode:'Kl_Unicode',
## Kl_IntUndefSize: 'Kl_IntUndefSize'}
def Kl_Module(a):
return (types.ModuleType, a)
def Kl_MayBe(a):
return ('MayBe', a)
_Kl_Simples = frozenset((Kl_List, Kl_Tuple, Kl_Int, Kl_String, Kl_Char, Kl_Dict,
Kl_Float, Kl_Boolean, Kl_None, Kl_File, Kl_Complex, Kl_Buffer,
Kl_Char, Kl_Long, Kl_Type, Kl_RegexObject, Kl_Set,
Kl_Short, 'Kl_Unicode'))
matched_i = None
matched_p = None
matched_len = -1
jump = ('JUMP', 'JUMP_CONTINUE', 'JUMP_BREAK')
_n2c = {}
global seqcode
all_co = {}
seqcode = []
##nm_attr = {}
#n_seq = 0
def subroutine_can_be_direct(nm, cnt_args):
co = N2C(nm)
if not hasattr(co, 'can_be_direct_call'):
co.can_be_direct_call = can_be_direct_call(co.cmds[1])
if co.can_be_direct_call == True:
if co.co_flags & 0x28 == 0 and len(co.co_cellvars) == 0 and len(co.co_freevars) == 0:
if co.co_flags & 0x4 == 0:
return match_count_args(nm, cnt_args)
return True
return False
def match_count_args(nm, cnt_args):
c_args = N2C(nm).co_argcount
if cnt_args > c_args:
return False
if cnt_args < c_args:
if nm in default_args:
defau = default_args[nm]
if defau is None or len(defau) == 0:
pass
elif defau[0] in ('CONST', '!BUILD_TUPLE'):
cnt_args += len(defau[1])
else:
Fatal('Strange match_count_args', nm, defau)
if cnt_args < c_args :
return False
else:
return False
return True
calculated_const = {}
pregenerated = []
known_modules = ('math', 'cmath', 'operator', 'string',
'binascii', 'marshal', 're', 'struct', 'sys', 'os', 'types',
'array', 'exceptions', 'Tkinter', 'ctypes',
'code', 'new')
CFuncFloatOfFloat = {('math', 'exp'):'exp', ('math', 'sin'):'sin', ('math', 'cos'):'cos', ('math', 'sqrt'):'sqrt',
('math', 'sinh'):'sinh', ('math', 'cosh'):'cosh',
('math', 'asin'):'asin', ('math', 'acos'):'acos', ('math', 'tan'):'tan',
('math', 'atan'):'atan', ('math', 'tanh'):'tanh', ('math', 'fabs'):'fabs'}
t_imp = {}
######################(
######################)
def add_math_float(a):
global t_imp
for f in a:
t_imp[('math', f, '()')] = Kl_Float
add_math_float(('fabs', 'factorial', 'fmod', 'fsum', 'ldexp', 'exp', 'expm1', \
'log', 'log1p', 'log10', 'pow', 'sqrt', 'acos', 'asin', 'atan', \
'atan2', 'hypot', 'cos', 'sin', 'tan', 'degrees', 'radians', \
'acosh', 'asinh', 'atanh', 'cosh', 'sinh', 'tanh', 'floor',
'erf', 'erfc', 'ldexp', 'fsum'))
t_imp[('math', 'frexp', '()')] = (tuple, (Kl_Float, Kl_Int))
t_imp[('math', 'isnan', '()')] = Kl_Boolean
t_imp[('math', 'isinf', '()')] = Kl_Boolean
t_imp[('types', 'CodeType', 'val')] = Kl_Type
t_imp[('types', 'ModuleType', 'val')] = Kl_Type
t_imp[('types', 'NoneType', 'val')] = Kl_Type
t_imp[('types', 'FunctionType', 'val')] = Kl_Type
t_imp[('types', 'InstanceType', 'val')] = Kl_Type
t_imp[('types', 'EllipsisType', 'val')] = Kl_Type
t_imp[('random', 'random', '()')] = Kl_Float
t_imp[('re', 'compile', '()')] = Kl_RegexObject
t_imp[('re', 'sub', '()')] = Kl_String
t_imp[('re', 'subn', '()')] = Kl_Tuple
t_imp[('re', 'search', '()')] = None
t_imp[('re', 'match', '()')] = None
#t_imp[('array', 'array', 'val')] = Klass(T_OLD_CL_INST, 'array')
#t_imp[('UserDict', 'UserDict', 'val')] = Klass(T_OLD_CL_INST, 'UserDict')
t_imp[('tempfile', 'mktemp', '()')] = Kl_String
#t_imp[('threading', 'Thread', 'val')] = Klass(T_OLD_CL_INST, 'Thread')
t_imp[('zipfile', 'ZipFile', 'val')] = (T_OLD_CL_TYP, 'ZipFile')
t_imp[('zipfile', 'ZipFile', '()')] = (T_OLD_CL_INST, 'ZipFile')
t_imp[('cStringIO', 'StringIO', 'val')] = (T_NEW_CL_TYP, 'StringIO')
t_imp[('inspect', 'getsourcefile', '()')] = Kl_String
t_imp[('inspect', 'getmembers', '()')] = Kl_List
t_imp[('inspect', 'getmodule', '()')] = None
t_imp[('inspect', 'currentframe', '()')] = (types.FrameType, None)
t_imp[('getopt', 'getopt', '()')] = Kl_Tuple
t_imp[('locale', 'getdefaultlocale', '()')] = Kl_Tuple
t_imp[('locale', 'getpreferredencoding', '()')] = Kl_String
t_imp[('codecs', 'lookup', '()')] = (T_NEW_CL_INST, 'CodecInfo')
t_imp[('tarfile', 'open', '()')] = (T_NEW_CL_INST, 'TarFile')
t_imp[('string', 'atoi', '()')] = Kl_Int
t_imp[('string', 'atof', '()')] = Kl_Float
t_imp[('string', 'split', '()')] = Kl_List
t_imp[('string', 'rsplit', '()')] = Kl_List
t_imp[('string', 'replace', '()')] = Kl_String
t_imp[('string', 'upper', '()')] = Kl_String
t_imp[('string', 'lower', '()')] = Kl_String
t_imp[('string', 'strip', '()')] = Kl_String
t_imp[('string', 'rstrip', '()')] = Kl_String
t_imp[('string', 'rfind', '()')] = Kl_Int
t_imp[('string', 'find', '()')] = Kl_Int
t_imp[('string', 'rjust', '()')] = Kl_String
t_imp[('string', 'ljust', '()')] = Kl_String
t_imp[('code', 'InteractiveInterpreter', 'val')] = (T_NEW_CL_TYP, 'InteractiveInterpreter')
t_imp[('code', 'InteractiveConsole', 'val')] = (T_NEW_CL_TYP, 'InteractiveConsole')
t_imp[('cPickle', 'load', '()')] = None
t_imp[('glob', 'glob', '()')] = Kl_List
t_imp[('imp', 'load_source', '()')] = None
t_imp[('copy', 'copy', '()')] = None
t_imp[('copy', 'deepcopy', '()')] = None
t_imp[('subprocess', 'Popen', 'val')] = (T_NEW_CL_TYP, 'Popen')
t_imp[('tempfile', 'gettempprefix', '()')] = Kl_String
t_imp[('tempfile', 'mkdtemp', '()')] = Kl_String
t_imp[('doctest', 'testmod', '()')] = Kl_Tuple
t_imp[('time', 'ctime', '()')] = Kl_String
t_imp[('repr', 'repr', '()')] = Kl_String
t_imp[('os', 'system', '()')] = Kl_Int
t_imp[('os', 'uname', '()')] = Kl_Tuple
t_imp[('os', 'listdir', '()')] = Kl_List
t_imp[('os', 'popen', '()')] = Kl_File
t_imp[('os', 'getenv', '()')] = None
t_imp[('os', 'getpid', '()')] = None
t_imp[('os', 'getcwd', '()')] = Kl_String
t_imp[('os.path', 'split', '()')] = Kl_Tuple
t_imp[('os.path', 'join', '()')] = Kl_String
t_imp[('os.path', 'dirname', '()')] = Kl_String
t_imp[('urllib', 'urlretrieve', '()')] = Kl_Tuple
t_imp[('time', 'time', '()')] = Kl_Float
t_imp[('time', 'clock', '()')] = Kl_Float
t_imp[('tempfile', 'gettempdir', '()')] = Kl_String
t_imp[('parser', 'expr', '()')] = None
t_imp[('parser', 'suite', '()')] = None
t_imp[('ctypes', 'pointer', 'val')] = (T_NEW_CL_TYP, 'ctypes_pointer')
t_imp[('ctypes', 'POINTER', '()')] = (T_NEW_CL_INST, 'ctypes_pointer')
t_imp[('ctypes', 'sizeof', '()')] = Kl_Int
t_imp[('ctypes', 'create_string_buffer', '()')] = None
t_imp[('ctypes', 'c_void_p', 'val')] = (T_NEW_CL_TYP, 'ctypes_c_c_void_p')
t_imp[('ctypes', 'c_int', 'val')] = (T_NEW_CL_TYP, 'ctypes_c_int')
t_imp[('ctypes', 'c_uint', 'val')] = (T_NEW_CL_TYP, 'ctypes_c_uint')
t_imp[('ctypes', 'CFUNCTYPE', 'val')] = (T_NEW_CL_TYP, 'ctypes_CFUNCTYPE')
t_imp[('ctypes', 'Structure', 'val')] = (T_NEW_CL_TYP, 'ctypes_Structure')
t_imp[('random', 'random', '()')] = Kl_Float
t_imp[('binascii', 'hexlify', '()')] = Kl_String
t_imp[('binascii', 'unhexlify', '()')] = Kl_String
t_imp[('marshal', 'loads', '()')] = None
t_imp[('struct', 'pack', '()')] = Kl_String
t_imp[('struct', 'unpack', '()')] = Kl_Tuple
t_imp[('struct', 'calcsize', '()')] = Kl_Int
t_imp[('sys', 'stdin', 'val')] = Kl_File
t_imp[('sys', 'stdout', 'val')] = Kl_File
t_imp[('sys', 'stderr', 'val')] = Kl_File
t_imp[('sys', 'modules', 'val')] = Kl_Dict
t_imp[('sys', 'exc_info', '()')] = Kl_Tuple
t_imp[('random', 'choice', '()')] = None
t_imp[('math', 'pi', 'val')] = Kl_Float
t_imp[('exceptions', 'Exception', 'val')] = Kl_NewType
t_imp[('struct', 'calcsize', '()')] = Kl_Int
#################
_unjump_cmds = ('.:', '3CMP_BEG_3', 'BASE_LIST_COMPR', 'BUILD_LIST',
'BUILD_MAP', 'BUILD_TUPLE', 'CALL_FUNCTION_1', 'CALL_FUNCTION_KW_1',
'CALL_FUNCTION_VAR_1', 'CALL_FUNCTION_VAR_KW_1', 'CHECK_EXCEPTION',
'COMPARE_OP', 'CONTINUE_LOOP', 'DUP_TOP', 'END_FINALLY', 'GET_ITER',
'IMPORT_AND_STORE_AS', 'LIST_APPEND', 'LOAD_ATTR_1', 'PyObject_GetAttr',
'LOAD_CLOSURE', 'LOAD_CODEFUNC', 'LOAD_DEREF', 'LOAD_GLOBAL',
'LOAD_LOCALS', 'LOAD_NAME', 'MAKE_CLOSURE', 'MAKE_FUNCTION',
'MK_CLOSURE', 'MK_FUNK', 'POP_BLOCK', 'POP_TOP', 'POP_TOP3',
'PRINT_ITEM_0', 'PRINT_ITEM_TO_0', 'PRINT_NEWLINE_TO_0', 'ROT_THREE',
'ROT_TWO', 'SEQ_ASSIGN_0', 'SET_VARS', 'STORE_MAP', 'STORE_SLICE+1',
'STORE_SLICE+2', 'STORE_SLICE+3', 'STORE_SLICE+0', 'STORE_SUBSCR_0', 'STORE_ATTR_1',
'UNPACK_SEQ_AND_STORE', 'WITH_CLEANUP', 'CONST', 'FAST', 'PyList_Append',
'YIELD_VALUE', 'BUILD_SET')
anagr = {}
def set_anagr(a,b):
global anagr
anagr[a] = b
anagr[b] = a
set_anagr('JUMP_IF2_FALSE_POP_CONTINUE', 'JUMP_IF2_TRUE_POP_CONTINUE')
set_anagr('JUMP_IF_FALSE_POP_CONTINUE', 'JUMP_IF_TRUE_POP_CONTINUE')
set_anagr('JUMP_IF2_FALSE_POP', 'JUMP_IF2_TRUE_POP')
set_anagr('JUMP_IF_FALSE_POP', 'JUMP_IF_TRUE_POP')
set_anagr('JUMP_IF_FALSE', 'JUMP_IF_TRUE')
#collect_stat = False
p2l = {}
used_cmpl = {}
used_cmp = {}
used_line = {}
matched_cmpl = {}
matched_cmp = {}
matched_line = {}
op_2_c_op = {'<':'Py_LT', '<=':'Py_LE', '==':'Py_EQ', '!=':'Py_NE',
'>':'Py_GT', '>=':'Py_GE'} #, 'is':'Py_IS', 'is not':'Py_IS_NOT'}
c_2_op_op = {'Py_LT':'<', 'Py_LE':'<=', 'Py_EQ':'==', 'Py_NE':'!=',
'Py_GT':'>', 'Py_GE':'>='} #, 'is':'Py_IS', 'is not':'Py_IS_NOT'}
## ##op_2_inv_op = {} #'<':'>=', '<=':'>', '==':'!=', '!=':'==',
## #'>':'<=', '>=':'<'}
## op_2_inv_op_ = {} #'<':'>', '<=':'>=', '==':'!=', '!=':'==',
## #'>=':'<=', '>':'<'}
recode_binary = {'BINARY_POWER': 'PyNumber_Power+Py_None', 'BINARY_MULTIPLY':'PyNumber_Multiply',
'BINARY_DIVIDE':'PyNumber_Divide', 'BINARY_TRUE_DIVIDE':'PyNumber_TrueDivide',
'BINARY_FLOOR_DIVIDE':'PyNumber_FloorDivide', 'BINARY_MODULO':'PyNumber_Remainder',
'BINARY_ADD':'PyNumber_Add', 'BINARY_SUBTRACT':'PyNumber_Subtract',
'BINARY_SUBSCR':'PyObject_GetItem', 'BINARY_LSHIFT':'PyNumber_Lshift',
'BINARY_RSHIFT':'PyNumber_Rshift', 'BINARY_AND':'PyNumber_And',
'BINARY_XOR':'PyNumber_Xor', 'BINARY_OR':'PyNumber_Or'}
recode_unary = {'UNARY_POSITIVE':'PyNumber_Positive', 'UNARY_NEGATIVE':'PyNumber_Negative',
'UNARY_CONVERT':'PyObject_Repr', 'UNARY_INVERT':'PyNumber_Invert'}
recode_inplace = {'INPLACE_POWER':'PyNumber_InPlacePower+',
'INPLACE_MULTIPLY':'PyNumber_InPlaceMultiply',
'INPLACE_ADD':'PyNumber_InPlaceAdd',
'INPLACE_SUBTRACT':'PyNumber_InPlaceSubtract',
'INPLACE_DIVIDE':'PyNumber_InPlaceDivide',
'INPLACE_TRUE_DIVIDE':'PyNumber_InPlaceTrueDivide',
'INPLACE_FLOOR_DIVIDE':'PyNumber_InPlaceFloorDivide',
'INPLACE_MODULO':'PyNumber_InPlaceRemainder',
'INPLACE_LSHIFT':'PyNumber_InPlaceLshift',
'INPLACE_RSHIFT':'PyNumber_InPlaceRshift',
'INPLACE_AND':'PyNumber_InPlaceAnd',
'INPLACE_XOR':'PyNumber_InPlaceXor',
'INPLACE_OR':'PyNumber_InPlaceOr'}
from opcode import HAVE_ARGUMENT, hasjrel, opname, EXTENDED_ARG, \
hasconst, hasname, haslocal, hascompare, hasfree, cmp_op
# PARAMETERS
detect_float = True
full_pycode = True
print_cline = False
print_pyline = False
print_pycmd = False
opt_flag = []
stat_func = ''
range2for = True
enumerate2for = True
calc_ref_total = False
recalc_refcnt = False
direct_call = True
no_fastlocals = False
##c_line_exceptions = False
no_generate_comment = False
dirty_iteritems = False
hide_debug = True
##simple_generate = False
##fast_instance = True - all
###fast_global = False # It' too early - don't use
check_recursive_call = not is_pypy
expand_BINARY_SUBSCR = False
make_indent = False
line_number = True
no_build = False
inline_flag = False
print_tree_node = False
c_name = '?'
hash_compile = 0
##use_cash_refcnt = False
checkmaxref = 0
try_jump_context = [False]
dropped_temp = []
filename = ""
genfilename = ''
func = ""
current_co = None
tempgen = []
typed_gen = []
labels = []
labl = ''
CO_GENERATOR = 0x0020
## cfuncs = {}
len_family = ('!PyObject_Size', '!PyString_GET_SIZE', '!PyString_Size',
'!PySet_GET_SIZE', '!PySet_Size', '!PyList_GET_SIZE',
'!PyList_Size', '!PyTuple_GET_SIZE', '!PyTuple_Size',
'!PyDict_Size', '!PyUnicode_GET_SIZE', '!PyUnicode_GetSize',
'!PyByteArray_GET_SIZE', '!PyByteArray_Size')
CFuncNeedINCREF = ('PyDict_GetItem', 'PyObject_GenericGetAttr', 'PyList_GET_ITEM', \
'PyTuple_GetItem', 'PyList_GetItem', 'PyTuple_GET_ITEM')
CFuncNotNeedINCREF = ('PyObject_GetAttr', 'PyObject_GetItem', \
'PyDict_New', 'PyNumber_Add', \
'PyCell_Get', \
'PyNumber_Divide', 'PyNumber_TrueDivide', 'PyNumber_Multiply', 'PyNumber_Negative', \
'PyNumber_Power', 'PyNumber_Remainder', 'PyNumber_Subtract',\
'PyNumber_Positive',\
'PyNumber_Absolute',\
'PyNumber_And', 'PyNumber_Or', 'PyNumber_Rshift', 'PyNumber_Lshift',\
'PyNumber_InPlaceSubtract', 'PyNumber_InPlaceAdd', 'PyNumber_InPlaceAnd', \
'PyNumber_Invert', 'PyNumber_FloorDivide', \
'PyNumber_InPlaceMultiply', 'PyNumber_FloorDivide', 'PyNumber_Xor',\
'PyNumber_InPlaceDivide', 'PyNumber_InPlaceTrueDivide',\
'PyNumber_InPlaceOr', 'PyNumber_InPlaceFloorDivide',\
'PyNumber_InPlacePower',\
'PyNumber_InPlaceRshift',\
'PyNumber_InPlaceLshift',\
'PyNumber_InPlaceRemainder',\
'PyNumber_InPlaceXor', '_GET_ITEM_2', '_GET_ITEM_1', '_GET_ITEM_0', '_GET_ITEM_LAST',\
'PyNumber_Int', 'PyNumber_Long', 'PyNumber_Float',\
'PyObject_Dir', 'PyObject_Format', \
'PySlice_New', '_PyEval_ApplySlice', \
'PyTuple_Pack', 'PyObject_Call', 'PyObject_GetIter', 'PyIter_Next',\
'Py2CFunction_New_Simple', 'Py2CFunction_New', 'PyFunction_New', \
'PyObject_RichCompare', 'c_LOAD_NAME',\
'c_LOAD_GLOBAL', 'PyNumber_InPlaceAdd', '_PyEval_BuildClass',\
'PyList_GetSlice', 'PyTuple_GetSlice', 'PySequence_GetSlice', \
'PyInt_FromSsize_t', 'PyEval_CallObject',
'from_ceval_BINARY_SUBSCR', 'Py_CLEAR', 'Py_BuildValue', \
'_PyDict_NewPresized', 'PyInt_FromSsize_t', 'PyTuple_New', 'PyList_New',\
'from_ceval_BINARY_ADD_Int', 'from_ceval_BINARY_SUBTRACT_Int',\
'PyDict_New', 'PyDict_Copy', 'PyBool_FromLong', 'PyObject_Type', 'PyObject_Repr',\
'PyObject_Dir', 'PySet_New', 'PyFrozenSet_New', 'PySequence_Tuple', 'PySequence_List',\
'PyFloat_FromDouble', 'PyObject_Str', 'PyCFunction_Call', \
'PyLong_FromVoidPtr', 'PyNumber_ToBase', 'PyInt_Type.tp_str', \
'PyComplex_Type.tp_new',
'PyInt_Type.tp_new', 'PyLong_Type.tp_new', 'PyFloat_Type.tp_new', \
'PyBool_Type.tp_new', 'PyBaseObject_Type.tp_new', 'PyUnicode_Type.tp_new', \
'PyString_FromStringAndSize', 'PyInt_FromLong', 'PyString_Format', \
'STR_CONCAT2', 'STR_CONCAT3', 'STR_CONCAT', 'STR_CONCAT_N', \
'PySequence_Repeat', 'FirstCFunctionCall', 'FastCall', 'FastCall0',\
'UNICODE_CONCAT2', 'UNICODE_CONCAT3', 'c_BINARY_SUBSCR_SUBSCR_Int_Int',\
'_c_BINARY_SUBSCR_Int', '_c_BINARY_SUBSCR_ADDED_INT',\
'PyInstance_New', 'PyInstance_NewRaw', '_PyString_Join', '_PyList_Extend', 'PyList_AsTuple',\
'PyDict_Keys', 'PyDict_Items', 'PyDict_Values', 'PyFile_FromString',\
'_PyInt_Format', '_PyList_Pop')
# PyObject_Type eq o->ob_type without incref
CFuncVoid = ('PyFrame_FastToLocals', 'PyFrame_LocalsToFast', 'SETLOCAL', 'LETLOCAL', 'SETSTATIC', \
'COPYTEMP', 'PyList_SET_ITEM', 'SET_CODE_C_FUNC', \
'_PyEval_DoRaise', 'printf', 'Py_INCREF', 'Py_CLEAR', \
'PyTuple_SET_ITEM', 'PyFrame_BlockSetup', 'PyFrame_BlockPop',\
'PyErr_Restore', 'PyErr_Fetch', 'PyErr_NormalizeException',\
'_PyEval_set_exc_info', '_PyEval_reset_exc_info', 'PyDict_Clear')
CFuncNoCheck = ('SETLOCAL', 'LETLOCAL', 'SETSTATIC', 'COPYTEMP', 'PyList_SET_ITEM', 'SET_CODE_C_FUNC',\
'_PyEval_DoRaise', 'PyIter_Next', 'printf', 'Py_INCREF', 'Py_CLEAR',\
'PyInt_AsSsize_t', 'PyTuple_SET_ITEM', 'PyObject_HasAttr',\
'PyFrame_FastToLocals', 'PyFrame_LocalsToFast', 'PyErr_ExceptionMatches',\
'PyFloat_AS_DOUBLE', 'PyInt_AsLong', 'PyInt_AS_LONG', 'PyFloat_AsDouble',\
'(double)PyInt_AsLong')
CFuncPyObjectRef = ('FirstCFunctionCall', 'FastCall', 'FastCall0', 'GETLOCAL', 'PyBaseObject_Type.tp_new',\
'PyBool_FromLong', 'PyBool_Type.tp_new', 'PyCFunction_Call', 'PyCell_Get', \
'PyDict_GetItem', 'PyDict_Items', 'PyDict_Keys', 'PyDict_New', 'PyDict_Values', 'PyDict_Copy',\
'PyEval_CallObject', 'PyFile_FromString',\
'PyFloat_FromDouble', 'PyFloat_Type.tp_new',\
'PyFrozenSet_New', 'PyFunction_New', 'Py2CFunction_New_Simple', 'Py2CFunction_New', \
'PyInstance_New', 'PyInstance_NewRaw',\
'PyInt_FromLong', 'PyInt_FromSsize_t', 'PyInt_Type.tp_new', 'PyComplex_Type.tp_new',\
'PyList_GET_ITEM', 'PyList_GetItem', 'PyList_New', 'PyList_AsTuple', \
'PyLong_FromSsize_t', 'PyLong_FromVoidPtr', 'PyLong_Type.tp_new',\
'PyNumber_Absolute', 'PyNumber_Add', 'PyNumber_And', 'PyNumber_Divide',\
'PyNumber_FloorDivide', 'PyNumber_InPlaceAdd', 'PyNumber_InPlaceAdd',\
'PyNumber_InPlaceAnd', 'PyNumber_InPlaceDivide', 'PyNumber_InPlaceFloorDivide',\
'PyNumber_InPlaceLshift', 'PyNumber_InPlaceMultiply', 'PyNumber_InPlaceOr',\
'PyNumber_InPlacePower', 'PyNumber_InPlaceRemainder', 'PyNumber_InPlaceRshift',\
'PyNumber_InPlaceSubtract', 'PyNumber_InPlaceTrueDivide', 'PyNumber_InPlaceXor',\
'PyNumber_Invert', 'PyNumber_Lshift', 'PyNumber_Multiply', 'PyNumber_Negative',\
'PyNumber_Or', 'PyNumber_Positive', 'PyNumber_Power', 'PyNumber_Remainder',\
'PyNumber_Rshift', 'PyNumber_Subtract', 'PyNumber_ToBase', 'PyNumber_TrueDivide',\
'PyNumber_Xor', '_GET_ITEM_2', '_GET_ITEM_1', '_GET_ITEM_0', '_GET_ITEM_LAST', \
'PyNumber_Int', 'PyNumber_Long', 'PyNumber_Float',\
'PyObject_Call', 'PyObject_Dir', 'PyObject_GetAttr', 'PyObject_GenericGetAttr', 'PyObject_GetItem',\
'PyObject_GetIter', 'PyObject_Repr', 'PyObject_RichCompare', 'PyObject_Str',\
'PyObject_Type', 'PyObject_Dir', 'PyObject_Format', 'PyInt_Type.tp_str', \
'PySequence_GetSlice', 'PySequence_List', 'PySequence_Repeat', 'PySequence_Tuple',\
'PySet_New', 'PySlice_New', 'PyList_GetSlice', 'PyTuple_GetSlice',\
'PyString_Format', 'PyString_FromStringAndSize',\
'PyTuple_GET_ITEM', 'PyTuple_GetItem', 'PyTuple_New', 'PyTuple_Pack',\
'PyUnicode_Type.tp_new', 'Py_BuildValue', \
'STR_CONCAT2', 'STR_CONCAT3', 'STR_CONCAT', 'STR_CONCAT_N', 'UNICODE_CONCAT2', 'UNICODE_CONCAT3',\
'_PyDict_NewPresized', '_PyEval_ApplySlice', '_PyEval_BuildClass',\
'_PyList_Extend', '_PyString_Join',\
'_c_BINARY_SUBSCR_ADDED_INT', '_c_BINARY_SUBSCR_Int', 'c_BINARY_SUBSCR_SUBSCR_Int_Int',\
'from_ceval_BINARY_ADD_Int', 'from_ceval_BINARY_SUBSCR', 'from_ceval_BINARY_SUBTRACT_Int',\
'c_LOAD_GLOBAL', 'c_LOAD_NAME', '_PyInt_Format', '_PyList_Pop')
CFuncIntCheck = ('PyCell_Set', 'PySequence_DelSlice', \
'PyDict_DelItem', 'PyDict_SetItem', 'PyDict_Size', 'PyDict_Update', 'PyDict_Contains',\
'PyDict_MergeFromSeq2', 'PyDict_DelItem', \
'PyFunction_SetClosure', 'PyFunction_SetDefaults',\
'Py2CFunction_SetClosure', 'Py2CFunction_SetDefaults',\
'PyList_Append', 'PyList_GET_SIZE', 'PyList_Insert', 'PyList_Reverse', \
'PyList_SetItem', 'PyList_SetSlice', 'PyList_Sort', \
'PyObject_DelItem', 'PyObject_IsInstance', 'PyObject_IsSubclass', \
'PyObject_IsTrue', 'PyObject_Not', 'PyObject_RichCompareBool',\
'PyObject_SetAttr', 'PyObject_SetItem', 'PyObject_Size',\
'PySequence_Contains', 'PySet_Contains', \
'PyString_GET_SIZE', 'PyTuple_GET_SIZE', 'PySet_Size', \
'PyUnicode_GetSize', 'PySet_Add', \
'_PyEval_AssignSlice', '_PyEval_ExecStatement', '_PyEval_ImportAllFrom',\
'_PyEval_PRINT_ITEM_1', '_PyEval_PRINT_ITEM_TO_2', '_PyEval_PRINT_NEWLINE_TO_1',\
'c_Py_EQ_Int', 'c_Py_EQ_String', 'c_Py_GE_Int', 'c_Py_GE_String',\
'c_Py_GT_Int', 'c_Py_GT_String', 'c_Py_LE_Int', 'c_Py_LE_String',\
'c_Py_LT_Int', 'c_Py_LT_String', 'c_Py_NE_Int', 'c_Py_NE_String',\
'PyString_AsStringAndSize', 'PyObject_Cmp')
API_cmp_2_PyObject = ('!PySequence_Contains', '!PyObject_HasAttr', \
'!PyObject_IsSubclass', '!PyObject_IsInstance', '!PyDict_Contains', '!PySet_Contains')
CFuncIntNotCheck = ('PyInt_AsSsize_t', 'PyObject_HasAttr', 'PyErr_ExceptionMatches')
CFuncFloatNotCheck = ('PyFloat_AS_DOUBLE', 'PyFloat_AsDouble', '(double)PyInt_AsLong')
CFuncLongNotCheck = ('PyInt_AsLong', 'PyInt_AS_LONG')
CFuncLongCheck = ('PyObject_Hash', )
CFuncIntAndErrCheck = ()
set_IntCheck = set(CFuncIntCheck + CFuncLongCheck + CFuncIntAndErrCheck)
consts = []
consts_dict = {}
loaded_builtin = []
def nmrecode(n):
if n == '<genexpr>':
n = 'genexpr__'
if n == '<genexp>':
n = 'genexpr__'
elif n == '<module>':
n = 'Init_filename'
elif n[:8] == '<lambda>':
n = 'lambda_' + n[8:]
elif n == '<dictcomp>':
n = 'dict_comp__'
elif n == '<setcomp>':
n = 'set_comp__'
return n
## def C2N(c):
## # global n_seq
## global _n2c, all_co
## if c in all_co:
## if hasattr(c, 'c_name'):
## n = c.c_name
## return n
## n = c.co_name
## n = nmrecode(n)
## if n in _n2c and not c in all_co:
## i = 1
## n2 = n
## while n2 in _n2c:
## n2 = n + repr(i)
## i = i + 1
## n = n2
## if not c in all_co:
## # cco.n_seq = n_seq
## all_co[c] = True
## # n_seq += 1
## c.c_name = n
## _n2c[n] = c
## return n
def N2C(n):
return _n2c[n]
def dis(x=None):
"""Disassemble classes, methods, functions, or code.
With no argument, disassemble the last traceback.
"""
## if x is None:
## distb()
## return
# if type(x) is types.InstanceType:
# x = x.__class__
if hasattr(x, 'im_func'):
x = x.im_func
if hasattr(x, 'func_code'):
x = x.func_code
if hasattr(x, '__dict__'):
items = x.__dict__.items()
items.sort()
for name, x1 in items:
if type(x1) in (types.MethodType,
types.FunctionType,
types.CodeType,
types.ClassType):
dis(x1)
elif hasattr(x, 'co_code'):
pre_disassemble(x)
else:
raise TypeError ( \
"don't know how to disassemble %s objects" % \
type(x).__name__)
from dis import findlabels, findlinestarts
global nm_pass
nm_pass = {}
def line2addr(co):
pairs = list(findlinestarts(co))
pairs.sort()
lines = {}
for addr, line in pairs:
if not line in lines:
lines[line] = addr
return lines
prev_refcnt = 0
##t_opt = 0
def SetPass(p):
global seqcode
## print p
global prev_refcnt
global Pass, Prev_Pass, Prev_Time, Pass_Exit
## global t_opt
## if 'entry_point' in _n2c:
## for c, cmds in seqcode:
## if c.co_name == 'entry_point':
## print p
## pprint(cmds)
if p == Pass_Exit:
Fatal('Cancelled at pass %s' % p)
if p in nm_pass:
p = nm_pass[p]
else:
s = str(len(nm_pass))
if len(s) < 2:
s = '0' + s
nm_pass[p] = s + ':' + p
p = nm_pass[p]
ti = time.clock()
if Prev_Time is not None:
Pass[Prev_Pass] = ti - Prev_Time
if flag_stat and not is_pypy and hasattr(sys, 'gettotalrefcount'):
refcnt = sys.gettotalrefcount()
print ('After ' + str(Prev_Pass) + ' ' + str(refcnt) + ' delta = ' + str(refcnt - prev_refcnt))
prev_refcnt = refcnt
Prev_Time = ti
Prev_Pass = p
## if t_opt != 0:
## print 'Time optimisation', t_optint.pprin
## t_opt = 0
def disassemble_base(co):
"""Disassemble a code object."""
code = co.co_code
labels = findlabels(code)
linestarts = dict(findlinestarts(co))
n = len(code)
i = 0
extended_arg = 0
free = None
cmds = []
N = co.c_name
cmds.append(('(BEGIN_DEF', N))
if type(code) is str:
while i < n:
label = -1
nline = -1
opcmd, codearg, arg = (None,None,None)
c = code[i]
op = ord(c)
if i in linestarts:
nline = linestarts[i]
if i in labels:
label = i
opcmd = opname[op] #.ljust(20),
i = i+1
recalc = False
if op >= HAVE_ARGUMENT:
## print ord(code[i]), ord(code[i+1])*256, extended_arg
oparg = ord(code[i]) + ord(code[i+1])*256 + extended_arg
## print oparg, extended_arg
extended_arg = 0
i = i+2
if op == EXTENDED_ARG:
extended_arg = oparg*65536
codearg = oparg
recalc = False
if op in hasconst:
arg = co.co_consts[oparg]
recalc = True
elif op in hasname:
arg = co.co_names[oparg]
recalc = True
elif op in hasjrel:
arg = i + oparg
recalc = True
elif op in haslocal:
arg = co.co_varnames[oparg]
recalc = True
elif op in hascompare:
arg = cmp_op[oparg]
recalc = True
elif op in hasfree:
if free is None:
free = co.co_cellvars + co.co_freevars
arg = free[oparg]
recalc = True
## print i, recalc, op, oparg, arg, codearg, opcmd
if label != -1:
cmds.append(('.:', label))
if nline != -1:
cmds.append(('.L', nline ))
if opcmd == 'JUMP_ABSOLUTE' or opcmd == 'JUMP_FORWARD':
opcmd = 'JUMP'
if opcmd == 'FOR_ITER':
opcmd = 'J_FOR_ITER'
if opcmd == 'SETUP_LOOP':
opcmd = 'J_SETUP_LOOP'
if opcmd == 'SETUP_EXCEPT':
opcmd = 'J_SETUP_EXCEPT'
if opcmd == 'SETUP_FINALLY':
opcmd = 'J_SETUP_FINALLY'
if opcmd == 'PRINT_ITEM':
opcmd = 'PRINT_ITEM_0'
if opcmd == 'PRINT_ITEM_TO':
opcmd = 'PRINT_ITEM_TO_0'
if opcmd == 'PRINT_NEWLINE_TO':
opcmd = 'PRINT_NEWLINE_TO_0'
if opcmd == 'STORE_SUBSCR':
opcmd = 'STORE_SUBSCR_0'
if opcmd == 'STORE_ATTR':
opcmd = 'STORE_ATTR_1'
if opcmd == 'DELETE_ATTR':
opcmd = 'DELETE_ATTR_1'
if opcmd == 'LOAD_ATTR':
opcmd = 'LOAD_ATTR_1'
if opcmd == 'LOOKUP_METHOD':
opcmd = 'LOAD_ATTR_1'
arg = co.co_names[oparg]
recalc = True
if opcmd == 'CONTINUE_LOOP':
opcmd = 'JUMP_CONTINUE'
if opcmd == 'POP_JUMP_IF_FALSE':
opcmd = 'JUMP_IF_FALSE_POP'
if opcmd == 'POP_JUMP_IF_TRUE':
opcmd = 'JUMP_IF_TRUE_POP'
if opcmd == 'SETUP_WITH':
opcmd = 'J_SETUP_WITH'
## if opcmd ='BUILD_LIST_FROM_ARG':
## opcmd = 'BUILD_LIST'
## if type(opcmd) is str and opcmd in codes:
## opcmd = codes[opcmd]
if opcmd == 'JUMP_IF_FALSE_OR_POP':
cmds.append(('JUMP_IF_FALSE', codearg))
cmds.append(('POP_TOP', ))
elif opcmd == 'JUMP_IF_TRUE_OR_POP':
cmds.append(('JUMP_IF_TRUE', codearg))
cmds.append(('POP_TOP', ))
elif recalc:
cmds.append((opcmd, arg))
elif arg is None and codearg is None:
cmds.append((opcmd,))
elif arg is None: # and opcmd != 'LOAD_CONST':
if opcmd in call:
if opcmd == 'CALL_FUNCTION':
opcmd = 'CALL_FUNCTION_1'
if opcmd == 'CALL_METHOD':
opcmd = 'CALL_FUNCTION_1'
cmds.append((opcmd, codearg & 255, (), codearg >> 8, ()))
else:
cmds.append((opcmd,codearg))
else:
cmds.append((opcmd, codearg, arg ))
if len(cmds) > 0 and cmds[-1][0][0] == 'J':
assert cmds[-1][1] > 0
## pprint(cmds)
co.cmds[:] = cmds
def find_redefined_builtin(cmds):
global redefined_all, count_define_set, count_define_get
for i,cmd in enumerate(cmds):
## if cmd[0] == 'IMPORT_STAR':
## redefined_all = True
if cmd[0] in ('DELETE_GLOBAL', 'STORE_GLOBAL', 'DELETE_NAME', 'STORE_NAME') and \
cmd[1] in d_built and cmd[1] != '__doc__':
redefined_builtin[cmd[1]] = True
if cmd[0] in ('LOAD_GLOBAL', 'LOAD_NAME'): #, 'LOAD_DEREF', 'LOAD_CLOSURE'):
if not (cmd[1] in count_define_get):
count_define_get[cmd[1]] = 1
else:
count_define_get[cmd[1]] += 1
if not (cmd[1] in count_define_set):
count_define_set[cmd[1]] = 2
if cmd[0] in ('STORE_GLOBAL', 'STORE_NAME'):
if cmd[1] in count_define_set:
count_define_set[cmd[1]] += 1
else:
count_define_set[cmd[1]] = 1
if cmd[0] in ('DELETE_GLOBAL', 'DELETE_NAME'):
if cmd[1] in count_define_set:
count_define_set[cmd[1]] += 2
else:
count_define_set[cmd[1]] = 2
if cmd == ('IMPORT_NAME', '__builtin__') and __file__ not in ('2c.py', '2c.pyc', '2c.pyo'):
redefined_all = True
if cmd[0] == 'IMPORT_NAME' and cmds[i+1][0] == 'IMPORT_STAR':
CheckExistListImport(cmd[1])
## li = get_list_names_module_raw(cmd[1])
if cmd[1] in list_import:
for x in list_import[cmd[1]]:
if x in count_define_set:
count_define_set[x] += 1
else:
count_define_set[x] = 1
def light_opt_at_cmd_level(cmds):
for i,cmd in enumerate(cmds):
if cmd[0] == 'LOAD_CONST' and type(cmd[1]) is types.CodeType:
cmds[i] = ('LOAD_CODEFUNC', code_extended(cmd[1]).c_name)
find_redefined_builtin(cmds)
NoGoToGo(cmds)
revert_conditional_jump_over_uncond_jump(cmds)
NoGoToGo(cmds)
def clear_module(nm):
assert nm != 'sys'
assert nm != '__name__'
if sys.modules[nm] is None:
del sys.modules[nm]
return
v = sys.modules[nm]
todel = []
for k1,v1 in v.__dict__.iteritems():
if type(v1) is types.ModuleType:
todel.append(k1)
for k1 in todel:
del v.__dict__[k1]
del sys.modules[nm]
if nm in list_import:
del list_import[nm]
if nm in imported_modules:
del imported_modules[nm]
def clear_after_all_files():
global start_sys_modules
clear_one_file()
list_import.clear()
self_attr_type.clear()
if hasattr(sys, '_clear_type_cache'):
sys._clear_type_cache()
imported_modules.clear()
start_sys_modules.clear()
del list_cname_exe[:]
def clear_one_file():
global redefined_all
global Pass, Prev_Time, Prev_Pass, start_sys_modules, seqcode
direct_args.clear()
all_co.clear()
## nm_attr.clear()
# n_seq = 0
_n2c.clear()
all_trin.clear()
redefined_all = False
count_define_set.clear()
count_define_get.clear()
del consts[:]
consts_dict.clear()
del pregenerated[:]
del loaded_builtin[:]
calculated_const.clear()
Pass.clear()
Prev_Time = None
Prev_Pass = None
no_compiled.clear()
detected_attr_type.clear()
detected_return_type.clear()
default_args.clear()
mnemonic_constant.clear()
all_calc_const.clear()
direct_code.clear()
val_direct_code.clear()
calc_const_value.clear()
redefined_builtin.clear()
uniq_debug_messages.clear()
type_def.clear()
fastglob.clear()
dict_global_used_at_generator.clear()
global_type.clear()
local_type.clear()
detected_global_type.clear()
predeclared_chars.clear()
calc_const_new_class.clear()
calc_const_old_class.clear()
attr_instance.clear()
del try_jump_context[:]
try_jump_context.append(False)
del dropped_temp[:]
del tempgen[:]
del typed_gen[:]
del labels[:]
del g_acc2[:]
del g_refs2[:]
del g_len_acc[:]
del seqcode[:]
end_sys_modules = sys.modules.copy()
for k in end_sys_modules:
if k not in start_sys_modules and not k.startswith('distutils.'):
clear_module(k)
self_attr_type.clear()
self_attr_type['object'] = {None:True}
self_attr_type['am_pm'] = {Kl_List:True}
self_attr_type['co_flags'] = {Kl_Int:True}
self_attr_type['co_stacksize'] = {Kl_Int:True}
self_attr_type['co_nlocals'] = {Kl_Int:True}
self_attr_type['co_fistlineno'] = {Kl_Int:True}
self_attr_type['co_argcount'] = {Kl_Int:True}
self_attr_type['co_name'] = {Kl_String:True}
self_attr_type['co_filename'] = {Kl_String:True}
self_attr_type['co_lnotab'] = {Kl_String:True}
self_attr_type['co_code'] = {Kl_String:True}
self_attr_type['co_cellvars'] = {Kl_Tuple:True}
self_attr_type['co_freevars'] = {Kl_Tuple:True}
self_attr_type['co_consts'] = {Kl_Tuple:True}
self_attr_type['co_varnames'] = {Kl_Tuple:True}
self_attr_type['co_names'] = {Kl_Tuple:True}
def dump(obj):
if not print_pycmd:
return
print_to(out, 'Code ' + obj.co_name)
for attr in dir(obj):
if attr.startswith('co_') and attr not in ( 'co_code', 'co_lnotab'):
val = getattr(obj, attr)
if attr == 'co_flags':
print_to(out,"\t" + attr + ' ' + hex(val))
elif attr in ('co_consts', 'co_name'):
pass
else:
print_to(out,"\t" + attr + ' ' + repr(val))
class code_extended(object):
def __init__(self, co, copy = False):
if co in all_co and not copy:
assert type(co) is not code_extended
self.__dict__ = all_co[co].__dict__
return
if copy:
assert co not in all_co and type(co) is code_extended
self.__dict__ = co.__dict__.clone()
return
self.co_argcount = co.co_argcount
self.co_nlocals = co.co_nlocals
self.co_stacksize = co.co_stacksize
self.co_flags = co.co_flags
self.co_code = co.co_code
self.co_consts = co.co_consts
self.co_names = co.co_names
self.co_varnames = list(co.co_varnames) ## for .index method at pypy
self.co_freevars = co.co_freevars
self.co_cellvars = co.co_cellvars
self.co_filename = co.co_filename
self.co_name = co.co_name
self.co_firstlineno = co.co_firstlineno
self.co_lnotab = co.co_lnotab
self.co_original = co
## self.self_dict_getattr_used = False
## self.self_dict_setattr_used = False
self.method_old_class = False
self.method_new_class = False
self.method_class = None
self.new_stacksize = 0
self.dict_getattr_used = {}
self.detected_type = {}
self.detected_type_may_be = {}
self.typed_arg_direct = {}
self.typed_arg_direct_changed = {}
self.cmds = []
self.direct_cmds = None
self.returns_direct = {}
self.returns_cfunc = {}
self.return_cnt = 0
self.used_return_labels = {}
self.used_fastlocals = {}
self.list_compr_in_progress = False
self.used_label = {}
self.is_partly_executed = False
self.to_exception = {}
for i in range(co.co_argcount + bool(co.co_flags & 0x4)):
self.used_fastlocals[co.co_varnames[i]] = True
self.used_fastlocals[nmvar_to_loc(co.co_varnames[i])] = True
nm = nmrecode(co.co_name)
for i in xrange(100000):
if i == 0:
nm2 = nm
else:
nm2 = nm + repr(i)
if nm2 not in _n2c:
self.c_name = nm2
_n2c[nm2] = self
break
all_co[co] = self
seqcode.append((self, self.cmds))
seqcode.sort()
def __lt__(self,a):
return self.co_firstlineno < a.co_firstlineno
def __gt__(self,a):
return self.co_firstlineno > a.co_firstlineno
def __str__(self):
return 'code_extended('+self.co_name+')'
def __repr__(self):
return 'code_extended('+self.co_name+')'
def Use_all_fastlocals(self):
for i in range(len(self.co_varnames)):
self.used_fastlocals[self.co_varnames[i]] = True
self.used_fastlocals[nmvar_to_loc(self.co_varnames[i])] = True
def can_be_codefunc(self):
n = self.c_name
if n in no_compiled or n.startswith('__new__') or n.startswith('__del__'):
return False
if self.co_flags & CO_GENERATOR:
return False
return True
def can_be_cfunc(self):
global no_cfunc
if no_cfunc:
return False
n = self.c_name
if n in no_compiled:
return False
if self.co_flags & CO_GENERATOR:
return False
if self.co_flags & 0x8:
return False
if can_be_direct_call(self.cmds[1]) != True:
return False
if len(self.co_cellvars + self.co_freevars) > 0:
return False
## if n == 'Out':
## print self
## print self.co_original
## print self.__dict__
## pprint(self.__dict__)
## func = self.c_name
## if func in direct_args and direct_call and self.direct_cmds == self.cmds[1] and \
## len(self.hidden_arg_direct) == 0 and len(self.typed_arg_direct) == 0:
## return False
return True
def can_C(self):
if self.can_be_cfunc():
return True
if self.can_be_codefunc():
return True
return False
def strip_unused_fast(self):
if len(self.co_cellvars) == 0 and len(self.co_freevars) == 0:
cmds = self.cmds[1]
srepr = repr(cmds)
if 'STORE_FAST' not in srepr and 'DELETE_FAST' not in srepr:
i = len(self.co_varnames)
changed = False
while i > self.co_argcount:
i -= 1
nm = self.co_varnames[i]
if repr(('FAST', nm)) not in srepr:
self.co_nlocals -= 1
del self.co_varnames[i]
changed = True
return changed
return False
def mark_method_class(self):
if len(self.co_varnames) > 0 and self.co_varnames[0] == 'self' and \
IsAnyMethod(self.co_name, self.c_name) and\
not Is3(None, ('ClassMethod', self.co_name), self.c_name) and\
not Is3(None, ('StaticMethod', self.co_name), self.c_name) and \
self.co_argcount > 0 and \
len(self.co_cellvars) == 0 and \
len(self.co_freevars) == 0:
li = IterMethod(self.co_name, self.c_name)
assert len(li) == 1
cl = li[0][0]
self.method_class = cl
if cl in calc_const_new_class and cl not in calc_const_old_class:
self.method_new_class = True
elif cl in calc_const_old_class and cl not in calc_const_new_class:
self.method_old_class = True
def TypeVar(self, it):
typ = None
if type(it) is tuple and it[0] == 'FAST':
dete = self.detected_type
if it[1] in dete:
typ = dete[it[1]]
if it[1] not in self.co_varnames:
Fatal('', self.co_name, self.c_name, self.co_varnames, it)
pos = self.co_varnames.index(it[1])
typed_arg = self.typed_arg_direct
if pos in typed_arg and is_current & IS_DIRECT:
typ = typed_arg[pos]
return typ
def IsIntVar(self, it):
return IsInt(self.TypeVar(it))
def IsBoolVar(self, it):
return IsBool(self.TypeVar(it))
def IsCharVar(self, it):
return self.TypeVar(it) == Kl_Char
def IsRealVar(self, it):
return IsFloat(self.TypeVar(it))
def IsCVar(self, it):
return IsCType(self.TypeVar(it))
def ReturnType(self):
if self.c_name in detected_return_type:
return detected_return_type[self.c_name]
return None
def IsRetVoid(self):
return self.c_name in detected_return_type and IsKlNone(detected_return_type[self.c_name])
def IsRetBool(self):
return self.c_name in detected_return_type and IsBool(detected_return_type[self.c_name])
def IsRetInt(self):
return self.c_name in detected_return_type and IsInt(detected_return_type[self.c_name])
def IsRetFloat(self):
return self.c_name in detected_return_type and IsFloat(detected_return_type[self.c_name])
def IsRetChar(self):
return self.c_name in detected_return_type and IsChar(detected_return_type[self.c_name])
def IsCType(t):
return IsInt(t) or t == Kl_Char or IsBool(t) or IsFloat(t)
def Type2CType(t):
if IsInt(t):
return 'long'
if IsBool(t):
return 'int'
if IsFloat(t):
return 'double'
if t == Kl_Char:
return 'char'
assert False
def CType2Py(o, ref2, cnm, t):
if IsInt(t):
o.PushInt(ref2, cnm)
elif IsFloat(t):
o.Raw(ref2, ' = PyFloat_FromDouble (', cnm, ');')
elif IsBool(t):
o.Raw(ref2, ' = PyBool_FromLong(', cnm, ');')
elif t == Kl_Char:
o.Raw(ref2, ' = PyString_FromStringAndSize(&', cnm, ', 1);')
return ref2
def pre_disassemble(_co):
# global n_seq
if not _co in all_co:
co = code_extended(_co)
else:
co = all_co[_co]
disassemble_base(co)
light_opt_at_cmd_level(co.cmds)
## co.cmds = co.cmds[:]
def can_be_direct_call(it):
if tag_in_expr('!IMPORT_NAME', it):
return 'statement IMPORT_NAME'
if tag_in_expr('EXEC_STMT', it):
return 'exec stmt'
if tag_in_expr('EXEC_STMT_3', it):
return 'exec stmt'
if tag_in_expr('IMPORT_FROM_AS', it):
return 'import from as'
## if '_getframe' in s:
## return 'probably get frame'
## if 'thread' in s:
## return 'probably threads'
## if 'Thread' in s:
## return 'probably threads'
## ## ## if tag_in_expr('(TRY', it):
## ## ## return 'statement try:'
## ## ## if tag_in_expr('(TRY_FINALLY', it):
## ## ## return 'statement try finally:'
if tag_in_expr('(WITH', it):
return 'statement with:'
if tag_in_expr('YEILD', it):
return 'statement yeild'
if tag_in_expr('LOAD_NAME', it):
return 'command LOAD_NAME'
if tag_in_expr('!LOAD_NAME', it):
return 'command LOAD_NAME'
if tag_in_expr('STORE_NAME', it):
return 'command STORE_NAME'
return True
def IsBegEnd(tag):
return type(tag) is str and tag[0] in ')('
def IsBeg(tag):
return type(tag) is str and tag[0] == '('
def uniq_list_type(v):
if len(v) == 1:
return v
v_tu = [x for x in v if x is not None and x[0] is tuple]
v_ntu = [x for x in v if x is None or x[0] is not tuple]
if len(v_tu) > 1:
if Kl_Tuple in v_tu:
v_tu = [Kl_Tuple]
if len(v_tu) > 1:
sdsc = [x[1] for x in v_tu]
ls = []
for x in sdsc:
if type(x) is tuple:
x = len(x)
ls.append(x)
## ls = [len(x) for x in sdsc]
if max(ls) != min(ls):
if min(ls) > 0:
v_tu = [(tuple, min(ls))]
else:
v_tu = [Kl_Tuple]
else:
## pprint(sdsc)
l = ls[0]
ty = [{} for i in range(l)]
## ty = range(l)
## for i in range(l):
## ty[i] = {}
for tu in sdsc:
for i in range(l):
ty[i][tu[i]] = None
ret = []
for dic in ty:
if len(dic) == 1:
ret.append(dic.keys()[0])
else:
ret.append(None)
ret = tuple(ret)
v_tu = [(tuple, ret)]
v = v_tu + v_ntu
if len(v) == 3:
if IsStr(v[0]) and IsStr(v[1]) and IsStr(v[2]):
return [Kl_String]
if IsInt(v[0]) and IsInt(v[1]) and IsInt(v[2]):
return [Kl_Int]
if IsInt(v[0]) and IsIntUndefSize(v[1]) and IsInt(v[2]):
return [Kl_IntUndefSize]
if IsIntUndefSize(v[0]) and IsInt(v[1]) and IsInt(v[2]):
return [Kl_IntUndefSize]
if IsInt(v[0]) and IsInt(v[1]) and IsIntUndefSize(v[2]):
return [Kl_IntUndefSize]
if len(v) == 2:
if IsStr(v[0]) and IsStr(v[1]):
return [Kl_String ]
if IsInt(v[0]) and IsInt(v[1]):
return [Kl_Int]
if IsIntUndefSize(v[0]) and IsInt(v[1]):
return [Kl_IntUndefSize]
if IsInt(v[0]) and IsIntUndefSize(v[1]):
return [Kl_IntUndefSize]
elif IsKlNone(v[0]) and v[1] is not None:
return [Kl_MayBe(v[1])]
elif IsKlNone(v[1]) and v[0] is not None:
return [Kl_MayBe(v[0])]
return v
def post_disassemble():
global no_build, redefined_all, current_co, Line2Addr, detected_global_type, seqcode, is_current
SetPass('HalfRecompile')
## seqcode = [(c, c.cmds) for c in all_co.itervalues()]
## seqcode.sort()
is_current = IS_CALLABLE_COMPILABLE
for current_co, cmds in seqcode:
assert cmds is not None
assert current_co.cmds is not None
jump_to_continue_and_break(current_co.cmds)
half_recompile(current_co.cmds, current_co)
SetPass('ParseClasses-0')
for current_co, cmds in seqcode:
if '__metaclass__' in repr(cmds[1]):
_3(cmds[0][1], 'HaveMetaClass', '???')
SetPass('FirstRepl')
single_define = [k for k,v in count_define_set.iteritems() \
if v == 1 and (k in count_define_get or k == '__all__')]
for current_co, cmds in seqcode:
cmds[1] = ortogonal(cmds[1], repl)
SetPass('FindCalcConst')
initcod = None
for _co, cmds in seqcode:
if cmds[0][1] == 'Init_filename':
initcod = cmds[1]
do_del = []
if initcod is not None:
initcod = [st for st in initcod if type(st) is tuple and \
len(st) > 0 and not IsBegEnd(st[0])]
for st in initcod:
for k in single_define:
p = find_statement_calculate_const(st, k)
if p != False:
filter_founded_calc_const(p, k, do_del)
for k in do_del:
if k in single_define:
del single_define[single_define.index(k)]
## res = False
SetPass('ImportManipulation')
## for k, attr, v in Iter3(None, 'ImportedM',None):
## if v in known_modules:
## _3(k, 'ImportedKnownM', v)
for current_co, cmds in seqcode:
if tag_in_expr('IMPORT_STAR', cmds[1]):
redefined_all = True
SetPass('UpgardeOp')
for current_co, cmds in seqcode:
cmds[1] = tree_pass(cmds[1], upgrade_op, None, cmds[0][1])
SetPass('UpgardeOp2')
for current_co, cmds in seqcode:
cmds[1] = tree_pass_upgrade_op2(cmds[1], None, cmds[0][1])
global type_def, self_attr_type, self_attr_store, self_attr_use
type_def.clear()
SetPass('RecursiveTypeDetect-1')
for current_co, cmds in seqcode:
cmds[1] = recursive_type_detect(cmds[1], cmds[0][1])
SetPass('UpgradeRepl-3')
for current_co, cmds in seqcode:
cmds[1] = tree_pass_upgrade_repl(cmds[1], None, cmds[0][1])
SetPass('UpgardeOp3')
for current_co, cmds in seqcode:
cmds[1] = tree_pass_upgrade_op2(cmds[1], None, cmds[0][1])
SetPass('CollectTypeReturn')
pass_detect_return_type()
SetPass('ParseClasses')
for current_co, cmds in seqcode:
if IsAnyClass(cmds[0][1]) and cmds[1][-1] == ('RETURN_VALUE', ('f->f_locals',)):
parse_class_def(cmds[0][1], cmds[1][:-1])
if Is3(cmds[0][1], 'IsClassCreator', None) and \
cmds[1][-1] == ('RETURN_VALUE', ('f->f_locals',)):
parse_for_special_slot_class(cmds[0][1], cmds[1][:-1], Val3(cmds[0][1], 'IsClassCreator'))
tree_pass(cmds[1], collect_default_args, None, cmds[0][1])
SetPass('UpgardeRepl-1')
for current_co, cmds in seqcode:
cmds[1] = tree_pass_upgrade_repl(cmds[1], None, cmds[0][1])
SetPass('CollectSetAttr')
for current_co, cmds in seqcode:
cmds[1] = tree_pass(cmds[1], collect_set_attr, None, cmds[0][1])
for current_co, cmds in seqcode:
cmds[1] = tree_pass(cmds[1], collect_set_attr, None, cmds[0][1])
for k1, v1 in self_attr_type.iteritems():
v = v1.keys()
v = [Kl_Function if x is not None and x[0] == Kl_Function[0] else x for x in v]
v = dict.fromkeys(v).keys()
if len(v) == 1 and v[0] is not None and v[0] != Kl_None:
detected_attr_type[k1] = v[0]
elif len(v) == 2 and IsInt(v[0]) and IsInt(v[1]):
detected_attr_type[k1] = Kl_Int
else:
Debug('Not detected attr type', k1, v)
SetPass('RecursiveTypeDetect-2')
for current_co, cmds in seqcode:
cmds[1] = recursive_type_detect(cmds[1], cmds[0][1])
SetPass('CollectTypeLocal1')
pass_local_type_detect()
SetPass('CollectTypeGlobal')
pass_global_type_detect()
SetPass('CollectTypeLocal2')
pass_local_type_detect()
SetPass('ReplaceLocalConstDetected')
for current_co, cmds in seqcode:
cmds[1] = replace_local_const_detect(cmds[1], cmds[0][1])
SetPass('UpgradeRepl-4')
for current_co, cmds in seqcode:
cmds[1] = tree_pass_upgrade_repl(cmds[1], None, cmds[0][1])
if direct_call:
SetPass('ConcretizeDirectCall-1')
concretize_direct_call()
SetPass('SetCondMethCall-0')
## d = globals()
## dd = {}
## for k,v in d.iteritems():
## if type(v) == type(SetPass) or k in ('Tx_compiled', 'Tx_fast', 'Tx_pre_compiled'):
## pass
## ## elif type(v) is code_extended:
## ## dd[k] = None
## ## elif k == '_n2c':
## ## dd[k] = v.keys()
## else:
## dd[k] = v
## pprint(dd, out)
for current_co, cmds in seqcode:
if current_co.can_be_codefunc():
is_current = IS_CALLABLE_COMPILABLE
cmds[1] = tree_pass__(cmds[1], upgrade_repl_if_type_direct_call, None, cmds[0][1])
cmds[1] = tree_pass(cmds[1], upgrade_op, None, cmds[0][1])
is_current = IS_DIRECT
current_co.direct_cmds = tree_pass__(current_co.direct_cmds, upgrade_repl_if_type_direct_call, None, cmds[0][1])
current_co.direct_cmds = tree_pass(current_co.direct_cmds, upgrade_op, None, cmds[0][1])
is_current = IS_CALLABLE_COMPILABLE
SetPass('ConcretizeDirectCall-2')
concretize_direct_call()
if build_executable:
SetPass('SupressUnusedCodefunc')
supress_unused_codefunc()
SetPass('ConcretizeDirectCall-3')
concretize_direct_call()
SetPass('CollectTypeLocal3')
pass_local_type_detect()
SetPass('CollectTypeGlobal3')
pass_global_type_detect()
SetPass('CollectTypeLocal4')
pass_local_type_detect()
SetPass('CollectTypeReturn-3')
pass_detect_return_type()
if direct_call:
SetPass('ConcretizeDirectCall-5')
concretize_direct_call()
SetPass('CollectTypeLocal5')
pass_local_type_detect()
SetPass('CollectTypeGlobal5')
pass_global_type_detect()
SetPass('CollectTypeLocal6')
pass_local_type_detect()
SetPass('CollectTypeReturn-5')
pass_detect_return_type()
SetPass('LabelMethod')
for current_co, cmds in seqcode:
current_co.mark_method_class()
SetPass('Formire')
for current_co, cmds in seqcode:
## print 'Code for ', current_co.co_name
dump(current_co)
print_cmds(cmds)
if current_co.direct_cmds is not None:
if len(current_co.hidden_arg_direct) == 0 and current_co.direct_cmds == cmds[1]:
pass
elif print_pycmd:
print >>out, 'Hidden args', current_co.hidden_arg_direct
print_cmds([('(DIRECT_DEF', cmds[0][1]), current_co.direct_cmds])
if not current_co.decompile_fail:
if hasattr(current_co, 'no_codefunc') and current_co.no_codefunc:
Line2Addr = line2addr(current_co)
else:
generate(cmds, current_co, filename)
is_current = IS_DIRECT
generate_direct(cmds, current_co, filename)
is_current = IS_CALLABLE_COMPILABLE
c_fname, nmmodule = Pynm2Cnm(filename)
SetPass('WriteAsC')
write_as_c(out3, nmmodule)
out3.close()
FlushDebug()
if make_indent:
SetPass('Indent')
os.system('indent ' + c_fname)
if no_build:
pass
else:
SetPass('Compile')
compile_c(filename, c_fname)
SetPass('WorkDone')
global Pass
global Tx_cnt
if flag_stat:
print ('Passess...')
its = Pass.items()
its.sort()
for k,v in its:
print (' ' + str(k) + ' ' + str(round(v, 3)))
print ('Attribute uses...' )
its = [(s,k) for k,s in stat_3.iteritems()]
its.sort()
for s,k in its:
print (' ' + str(k) + ' ' + str(s))
sta = [(v,k) for k,v in Tx_cnt.iteritems()]
sta.sort()
print '--- patterns ---'
for s,k in sta:
pprint(k)
print ' ' , s
return None
def pass_detect_return_type():
global current_co, is_current, seqcode
len_detected_return_type = len(detected_return_type)
## detected_return_type.clear()
while True:
type_def.clear()
for current_co, cmds in seqcode:
if current_co.co_flags & CO_GENERATOR:
detected_return_type[cmds[0][1]] = Kl_Generator
else:
is_current = IS_CALLABLE_COMPILABLE
if hasattr(current_co, 'no_codefunc') and current_co.no_codefunc:
pass
else:
tree_pass(cmds[1], collect_type_return, None, cmds[0][1])
is_current = IS_DIRECT
tree_pass(current_co.direct_cmds, collect_type_return, None, cmds[0][1])
is_current = IS_CALLABLE_COMPILABLE
for k1, v1 in type_def.iteritems():
v = v1.keys()
v = uniq_list_type(v)
Debug('def %s, return %s' % (k1, v))
if len(v) == 1 and v[0] is not None:
detected_return_type[k1] = v[0]
elif len(v) == 2:
if IsStr(v[0]) and IsStr(v[1]):
detected_return_type[k1] = Kl_String
elif IsKlNone(v[0]) and v[1] is not None:
detected_return_type[k1] = Kl_MayBe(v[1])
elif IsKlNone(v[1]) and v[0] is not None:
detected_return_type[k1] = Kl_MayBe(v[0])
else:
Debug('Not detected return type', k1, v)
else:
Debug('Not detected return type', k1, v)
if len_detected_return_type == len(detected_return_type):
break
len_detected_return_type = len(detected_return_type)
type_def.clear()
def pass_global_type_detect():
global global_type, detected_global_type, current_co, is_current, seqcode
global_type.clear()
for current_co, cmds in seqcode:
## tree_pass(cmds[1], collect_set_global, None, cmds[0][1])
is_current = IS_CALLABLE_COMPILABLE
if hasattr(current_co, 'no_codefunc') and current_co.no_codefunc:
pass
else:
tree_pass(cmds[1], collect_set_global, None, cmds[0][1])
is_current = IS_DIRECT
tree_pass(current_co.direct_cmds, collect_set_global, None, cmds[0][1])
is_current = IS_CALLABLE_COMPILABLE
for k1, v1 in global_type.iteritems():
v = v1.keys()
v = uniq_list_type(v)
if len(v) == 1 and v[0] is not None:
detected_global_type[k1] = v[0]
elif len(v) == 2:
if IsStr(v[0]) and IsStr(v[1]):
detected_global_type[k1] = Kl_String
elif IsKlNone(v[0]) and v[1] is not None:
detected_global_type[k1] = Kl_MayBe(v[1])
elif IsKlNone(v[1]) and v[0] is not None:
detected_global_type[k1] = Kl_MayBe(v[0])
else:
Debug('Not detected global type', k1, v)
else:
Debug('Not detected global type', k1, v)
Debug('Detected global type var', detected_global_type)
def pass_local_type_detect():
global local_type, current_co, is_current, seqcode
for current_co, cmds in seqcode:
local_type.clear()
if not current_co.can_be_codefunc():
continue
is_current = IS_CALLABLE_COMPILABLE
if hasattr(current_co, 'no_codefunc') and current_co.no_codefunc:
pass
else:
collect_set_local( cmds[1], cmds[0][1])
is_current = IS_DIRECT
collect_set_local( current_co.direct_cmds, cmds[0][1])
is_current = IS_CALLABLE_COMPILABLE
for k1, v1 in local_type.iteritems():
v = v1.keys()
v = uniq_list_type(v)
if len(v) == 2:
if IsStr(v[0]) and IsStr(v[1]):
v = [Kl_String ]
elif IsKlNone(v[0]) and v[1] is not None:
v = [Kl_MayBe(v[1])]
elif IsKlNone(v[1]) and v[0] is not None:
v = [Kl_MayBe(v[0])]
if len(v) != 1 or v[0] is None:
not_loc_detec(k1, v)
continue
if k1 in current_co.co_varnames and \
len([True for i, nm in enumerate(current_co.co_varnames) if i < current_co.co_argcount and nm == k1]) > 0:
current_co.detected_type_may_be[k1] = v[0]
continue
current_co.detected_type[k1] = v[0]
changed_arg_type_detect(current_co)
if len(current_co.detected_type) > 0:
for k, v in current_co.detected_type.iteritems():
Debug('def %s, var %s -- local type detected (%s)' % (current_co.co_name, k, v))
## Debug('def %s -- local type detected' % co.co_name, k, v)
def changed_arg_type_detect(co):
if len(co.detected_type_may_be) > 0 and len(co.typed_arg_direct_changed) > 0:
todel = {}
for nm, kl in co.detected_type_may_be.iteritems():
ind = co.co_varnames.index(nm)
if ind in co.typed_arg_direct_changed and co.typed_arg_direct_changed[ind] == kl:
co.typed_arg_direct[ind] = kl
del co.typed_arg_direct_changed[ind]
todel[nm] = True
for nm in todel.iterkeys():
del co.detected_type_may_be[nm]
global list_calcconst_codefunc
used_calcconst_codefunc = {}
def supress_unused_codefunc():
global current_co, seqcode
initcod = None
for current_co, initcmds in seqcode:
if initcmds[0][1] == 'Init_filename':
initcod = initcmds[1]
break
if initcod is None:
return
used_calcconst_codefunc.clear()
for st in initcod:
v = []
if type(st) is tuple and len(st) == 3 and type(st[0]) is str and st[0] == 'STORE' and\
TCmp(st, v, ('STORE', \
(('STORE_CALC_CONST', \
('STORE_NAME', '?')),), \
(('!MK_FUNK', '?', ('CONST', '?')),))) and v[0] == v[1]:
used_calcconst_codefunc[v[0]] = False
for current_co, cmds in seqcode:
tree_pass(cmds[1], find_use_calcconst_codefunc, None, cmds[0][1])
for nmcodefunc, used in used_calcconst_codefunc.iteritems():
if not used:
co = N2C(nmcodefunc)
co.no_codefunc = True
new_initcod = []
for st in initcod:
v = []
if type(st) is tuple and len(st) == 3 and type(st[0]) is str and st[0] == 'STORE' and\
TCmp(st, v, ('STORE', \
(('STORE_CALC_CONST', \
('STORE_NAME', '?')),), \
(('!MK_FUNK', '?', ('CONST', '?')),))) and \
v[0] in used_calcconst_codefunc and \
not used_calcconst_codefunc[v[0]]:
pass
else:
new_initcod.append(st)
initcmds[1] = new_initcod
def find_use_calcconst_codefunc(it, nm):
if type(it) is tuple and len(it) >= 2 and type(it[0]) is str:
if it[0] in ('!CALL_CALC_CONST', 'STORE_NAME', 'STORE_GLOBAL', '!MK_FUNK', 'FAST'):
pass
elif it[1] in used_calcconst_codefunc:
used_calcconst_codefunc[it[1]] = True
return it
def concretize_direct_call():
global current_co, is_current, seqcode
global list_cmds, prev_list_cmds
list_cmds = [None]
prev_list_cmds = []
## if flag_stat and hasattr(sys, 'gettotalrefcount'):
## prev_refcnt = sys.gettotalrefcount()
while True:
direct_args.clear()
for current_co, cmds in seqcode:
if current_co.can_be_codefunc():
is_current = IS_CALLABLE_COMPILABLE
if hasattr(current_co, 'no_codefunc') and current_co.no_codefunc:
pass
else:
tree_pass_readonly(cmds[1], None, cmds[0][1])
is_current = IS_DIRECT
tree_pass_readonly(current_co.direct_cmds, None, cmds[0][1])
is_current = IS_CALLABLE_COMPILABLE
prev_list_cmds = list_cmds
list_cmds = [(co,cmds) for co, cmds in seqcode \
if cmds[0][1] in direct_args and co.can_be_codefunc()]
if list_cmds == prev_list_cmds:
break
for current_co, cmds in list_cmds:
concretize_code_direct_call(cmds[0][1], cmds[1], current_co)
changed_arg_type_detect(current_co)
def is_const_value1(v):
if v[0] == 'CONST':
return True
if v[0] == '!LOAD_NAME' and (type(v[1]) is float or v[1] in ('nan', 'inf')):
return True
if v[0] == 'CALC_CONST':
return True
if v[0] == '!CLASS_CALC_CONST':
return True
if v[0] == '!BUILD_LIST' and all([is_const_value1(x) for x in v[1]]):
return True
if v[0] == '!BUILD_TUPLE' and all([is_const_value1(x) for x in v[1]]):
return True
if v[0] == '!PyObject_GetAttr' and is_const_value1(v[1]) and is_const_value1(v[2]):
return True
if v == ('!PyDict_New',):
return True
if v[0] in ('!LOAD_BUILTIN',):
return True
if v[0] == '!MK_FUNK' and is_const_value1(v[2]):
return True
if v[0] == '!PyObject_Type':
return is_const_value1(v[1])
return False
def is_const_default_value(v):
if v[0] == 'CONST':
return True
if v[0] == '!BUILD_TUPLE' and all([is_const_value1(x) for x in v[1]]):
return True
if v[0] == '!PyDict_New' and len(v) == 1:
Fatal('??? where ???', v)
return True
Debug('not const', v)
return False
def get_default_value1(v):
# if v[0] == 'CONST':
return v
# Fatal('', '')
# return v[1]
def is_simple_attr(expr):
t = TypeExpr(expr)
if t is not None and (t in _Kl_Simples or t[0] in (types.ModuleType, T_OLD_CL_TYP, T_NEW_CL_TYP)):
return True
if expr[0].startswith('PyNumber_'):
if len(expr) == 3 and (is_simple_attr(expr[1]) or is_simple_attr(expr[2])):
return True
if len(expr) == 4 and (is_simple_attr(expr[1]) or is_simple_attr(expr[2]) or is_simple_attr(expr[2])):
return True
if len(expr) == 2 and is_simple_attr(expr[1]):
return True
return False
def get_nmcode(nmcl, expr):
nm_code = None
if expr[0] == '!MK_FUNK':
nm_code, default_arg = expr[1:3]
if is_const_default_value(default_arg):
default = get_default_value1(default_arg)
default_args[nm_code] = default
return nm_code
Debug('*Not const default args meth|attr', expr)
if expr[0] == '!LOAD_NAME':
nm_prev = expr[1]
if IsMethod(nmcl, nm_prev):
nm_code = ValMethod(nmcl, nm_prev)
if expr[0] == 'PY_TYPE' and expr[3][0] == '!LOAD_NAME':
nm_prev = expr[3][1]
if IsMethod(nmcl, nm_prev):
nm_code = ValMethod(nmcl, nm_prev)
if nm_code is None:
t = TypeExpr(expr)
if t is not None and t[0] is types.FunctionType and t[1] is not None:
nm_code = t[1]
return nm_code
def one_store_clause(nmcl, nmslot, expr):
v2 = []
if nmslot in ('__doc__', '__module__'):
return True
if nmslot in ('__new__', '__del__'):
nm_code = get_nmcode(nmcl, expr)
if nm_code is None and expr[0] == '!MK_CLOSURE':
nm_code = expr[1]
if nm_code is not None:
no_compiled[nm_code] = True
else:
Fatal('', expr, 'Is', 'NoCompiled')
if is_simple_attr(expr):
_3(nmcl, ('Attribute', nmslot), expr)
return True
nm_code = get_nmcode(nmcl, expr)
if nm_code is not None:
_3(nmcl, ('Method', nmslot), nm_code)
if nmslot == '__init__':
parse_constructor(nmcl, nm_code)
return True
if expr[0] == '!PyObject_Call':
if TCmp(expr, v2, ('!PyObject_Call', ('!LOAD_BUILTIN', 'property'), '?', '?')):
_3(nmcl, 'Property', nmslot)
return one_store_property_clause(nmcl, nmslot, v2[0], v2[1])
if TCmp(expr, v2, ('!PyObject_Call', \
('!LOAD_BUILTIN', 'staticmethod'),\
('!BUILD_TUPLE', ('?',)), ('NULL',)) ):
return one_store_modificator_clause(nmcl, nmslot, 'StaticMethod', v2[0])
if TCmp(expr, v2, ('!PyObject_Call', \
('!LOAD_BUILTIN', 'classmethod'),\
('!BUILD_TUPLE', ('?',)), ('NULL',)) ):
return one_store_modificator_clause(nmcl, nmslot, 'ClassMethod', v2[0])
return False
def one_store_modificator_clause(nmcl, nmslot, Modificator, expr):
nm_code = get_nmcode(nmcl, expr)
if nm_code is not None:
_3(nmcl, ('Method', nmslot), nm_code)
_3(nmcl, (Modificator, nmslot), nm_code)
return True
Debug('*Not const default args %s meth|attr' % Modificator, expr)
return False
def one_store_property_clause(nmcl, nmslot, tupl, dic):
getter, setter, deleter, doc = None, None, None, None
if tupl[0] == '!BUILD_TUPLE':
_tupl = list(tupl[1])
while len(_tupl) < 4:
_tupl.append(None)
getter, setter, deleter, doc = _tupl
elif tupl == ('CONST', ()):
pass
else:
Debug('*Undefined property positional arg', nmcl, nmslot, tupl, dic)
if dic == ('NULL',):
pass
elif dic[0] == '!BUILD_MAP':
for (k,v) in dic[1]:
if k == ('CONST', 'doc'):
assert doc is None
doc = v
elif k == ('CONST', 'fget'):
assert getter is None
getter = v
elif k == ('CONST', 'fset'):
assert setter is None
setter = v
elif k == ('CONST', 'fdel'):
assert deleter is None
deleter = v
else:
Debug('*Undefined property key arg', nmcl, nmslot, tupl, dic)
return False
for k,v in (('Getter', getter), ('Setter', setter), ('Deleter', deleter)):
if v is None or v == ('CONST', None):
continue
nm_code = get_nmcode(nmcl, v)
if nm_code is not None:
_3(nmcl, (k, nmslot), nm_code)
continue
Debug('*Access %s property class %s -> %s UNPARSE method %s ' % (k, nmcl, nmslot, nm_code))
return False
return True
def parse_class_def(nm, seq):
i = -1
while i < len(seq)-1:
assert type(i) is int
i += 1
v = seq[i]
if v[0] == '.L':
continue
if v[0] == 'UNPUSH':
Debug('*Ignored stmt in class def', v)
continue
v2 = []
if len(v) > 0 and type(v[0]) is str and v[0] == 'STORE':
if TCmp(v, v2, ('STORE', (('STORE_NAME', '?'),), ('?',))):
if not one_store_clause(nm, v2[0], v2[1]):
Debug('*Parse store clause illegal', v)
continue
if TCmp(v, v2, ('STORE', (('PyObject_SetItem', ('!LOAD_NAME', '?'), '?'),), ('?',))):
continue
if TCmp(v, v2, ('STORE', (('PyObject_SetItem', ('PY_TYPE', '?', '?', ('!LOAD_NAME', '?'), None), '?'),), ('?',))):
continue
if TCmp(v, v2, ('STORE', (('PyObject_SetAttr', ('!LOAD_NAME', '?'), '?'),), ('?',))):
continue
if TCmp(v, v2, ('STORE', (('PyObject_SetAttr', ('PY_TYPE', '?', '?', ('!LOAD_NAME', '?'), None), '?'),), ('?',))):
continue
## if TCmp(v, v2, ('SEQ_ASSIGN', '?', '?')):
## for v2_0 in v2[0]:
## v2__ = []
## if TCmp(v2_0, v2__, ('STORE_NAME', '?')):
## if not one_store_clause(nm, v2__[0], None):
## Debug('*Parse store clause illegal', v2_0)
## continue
## continue
if IsBeg(v[0]):
oldi = i
i = get_closed_pair(seq, i)
_3(nm, 'ComplcatedClassDef', True)
Debug('*Complicated meth|attr', seq[oldi:i+1])
continue
Debug('*Parse class def error', v)
def parse_for_special_slot_class(nmcod, seq, nmcl):
i = -1
while i < len(seq)-1:
assert type(i) is int
i += 1
v = seq[i]
if v[0] == '.L':
continue
if v[0] == 'UNPUSH':
continue
v2 = []
if len(v) > 0 and type(v[0]) is str and v[0] == 'STORE':
if TCmp(v, v2, ('STORE', (('STORE_NAME', '?'),), ('?',))) and v2[0] in ('__new__', '__del__'):
v3 = []
if TCmp(v2[1], v3, ('!PyObject_Call',('!LOAD_BUILTIN', 'staticmethod'), \
('!BUILD_TUPLE', ('?',)), ('NULL',))):
v2[1] = v3[0]
elif TCmp(v2[1], v3, ('!PyObject_Call',('!LOAD_NAME', 'staticmethod'), \
('!BUILD_TUPLE', ('?',)), ('NULL',))):
v2[1] = v3[0]
nm_code = get_nmcode(nmcl, v2[1])
if nm_code is None and v2[1][0] == '!MK_CLOSURE':
nm_code = v2[1][1]
if nm_code is not None:
no_compiled[nm_code] = True
else:
Fatal('Can\'t detect code for %s.%s method' % (nmcod, v2[0]), v)
continue
def parse_constructor(nmclass, nmcode):
seq = N2C(nmcode).cmds[1]
for v in seq:
v2 = []
if type(v) is tuple and len(v) == 3 and type(v[0]) is str and v[0] == 'STORE' and\
TCmp(v, v2, ('STORE', (('PyObject_SetAttr', ('?', 'self'), ('CONST', '?')),), ('?',))):
SetAttrInstance(nmclass, v2[1])
def repl_in_if_store(ret, old, new, stor, dele):
ret = list(ret)
if not (repr(stor) in repr(ret[0])) and ret[0][0] == '(IF':
ret[0] = replace_subexpr(ret[0], old, new)
else:
return ret
if len(ret) == 3 or len(ret) == 2:
ret[1] = repl_in_list_if_store(ret[1], old, new, stor, dele)
elif len(ret) == 5 or len(ret) == 4:
ret[1] = repl_in_list_if_store(ret[1], old, new, stor, dele)
ret[3] = repl_in_list_if_store(ret[3], old, new, stor, dele)
return ret
def repl_in_list_if_store(ret, old, new, stor, dele):
j = 0
s_repr_stor = repr(stor)
s_repr_dele = repr(dele)
while j < len(ret):
if IsBeg(ret[j][0]):
j1 = get_closed_pair(ret, j)
srepr = repr(ret[j:j1])
if s_repr_stor in srepr or s_repr_dele in srepr:
if ret[j][0] == '(IF':
ret[j:j1] = repl_in_if_store(ret[j:j1], old, new, stor, dele)
break
ret[j:j1] = replace_subexpr(ret[j:j1], old, new)
j = j1 + 1
else:
srepr = repr(ret[j])
if s_repr_stor in srepr:
if ret[j][0] == 'STORE' and len(ret[j][1]) == 1 and \
ret[j][1][0] == stor and len(ret[j][2]) == 1:
v2 = replace_subexpr(ret[j][2][0], old, new)
ret[j] = ('STORE', ret[j][1], (v2,))
break
elif s_repr_dele in srepr:
break
ret[j] = replace_subexpr(ret[j], old, new)
j = j + 1
return ret
def apply_typ(ret, d):
for old, t in d.iteritems():
if t is None:
continue
## t = (typ, None)
old_old = old
if old_old[0] == 'PY_TYPE':
if old_old[1] != t[0]:
Debug('def %s: change detected type' % current_co.co_name, old_old[1], t[0],ret)
return ret
old_old = old[3]
assert old_old[0] != 'PY_TYPE'
new = ('PY_TYPE', t[0], t[1], old_old, None)
if old != new:
ret = replace_subexpr(ret, old, new)
return ret
def type_in_if(ret, d):
if ret[0] == '!BOOLEAN':
return ('!BOOLEAN', type_in_if(ret[1], d))
if ret[0] in ('!AND_JUMP', '!AND_BOOLEAN'):
return (ret[0],) + tuple([type_in_if(r, d) for r in ret[1:]])
if ret[0] in ('!OR_JUMP', '!OR_BOOLEAN'):
return apply_typ((ret[0],) + tuple([type_in_if(r, {}) for r in ret[1:]]), d)
v = []
old, nm, built = None, None, None
if TCmp(ret, v, ('!_EQ_', ('!PyObject_Type', '?'), \
('!LOAD_BUILTIN', '?'))):
old, nm = v
built = True
elif TCmp(ret, v, ('!_EQ_', ('!LOAD_BUILTIN', '?'), \
('!PyObject_Type', '?'))):
nm, old = v
built = True
elif TCmp(ret, v, ('!_EQ_', ('!PyObject_Type', '?'), \
('CALC_CONST', '?'))):
old, nm = v
built = False
elif TCmp(ret, v, ('!_EQ_', ('CALC_CONST', '?'), \
('!PyObject_Type', '?'))):
nm, old = v
built = False
elif TCmp(ret, v, ('!PyObject_RichCompare(', ('!LOAD_BUILTIN', '?'), \
('!PyObject_Type', '?'), 'Py_EQ')):
nm, old = v
built = True
elif TCmp(ret, v, ('!PyObject_RichCompare(', ('!PyObject_Type', '?'), \
('!LOAD_BUILTIN', '?'), 'Py_EQ')):
old, nm = v
built = True
elif '!LOAD_BUILTIN' in repr(ret):
Debug('Unhandled builtin (can be type) at condition', ret)
if nm in d_built and built:
ret = apply_typ(ret, d)
if not old in d:
d[old] = (d_built[nm], None)
else:
d[old] = None
return ret
else:
isoldclass = nm in calc_const_old_class
isnewclass = nm in calc_const_new_class
if isoldclass:
ret = apply_typ(ret, d)
if not old in d:
d[old] = (T_OLD_CL_INST, nm)
else:
d[old] = None
return ret
elif isnewclass:
ret = apply_typ(ret, d)
if not old in d:
d[old] = (T_NEW_CL_INST, nm)
else:
d[old] = None
return ret
ret = apply_typ(ret, d)
return apply_typ(ret, d)
def only_fast(d):
d2 = {}
for k,v in d.iteritems():
if k[0] == 'FAST':
d2[k] = v
return d2
def list_typed_var_after_stmt(v, nmdef):
if v[0] == 'STORE' and len(v[1]) == 1 and v[1][0][0] in ('STORE_FAST', 'STORE_NAME') and \
len(v[2]) == 1:
t = TypeExpr(v[2][0])
## if t is not None:
## assert t.__class__.__name__ == 'Klass'
if IsKlNone(t) and v[1][0][0] == 'STORE_NAME' and nmdef == 'Init_filename':
return []
elif t is None:
return []
stor = v[1][0]
dele = v[1][0]
dele = ('DELETE_' + dele[0][6:], dele[1])
nm1 = v[1][0][1]
if v[1][0][0] == 'STORE_FAST':
nm2 = ('FAST', nm1)
else:
nm2 = ('!LOAD_NAME', nm1)
old = nm2
if IsList(t):
t = Kl_List
assert nm2[0] != 'PY_TYPE'
new = ('PY_TYPE', t[0], t[1], nm2, None)
if t in _Kl_Simples and v[2][0][0] == 'CONST':
new = v[2][0]
if v[2][0][0] == '!CLASS_CALC_CONST':
assert v[2][0][1][0] != 'PY_TYPE'
new = ('PY_TYPE', t[0], v[2][0][1], nm2, None)
elif v[2][0][0] == '!CLASS_CALC_CONST_NEW':
assert v[2][0][1][0] != 'PY_TYPE'
new = ('PY_TYPE', t[0], v[2][0][1], nm2, None)
v2 = []
if TCmp(v[2][0], v2, ('!MK_FUNK', '?', ('CONST', ()))):
new = v[2][0]
## vectorlist = False
## if IsList(t) and v[2][0][0] == '!LIST_COMPR' and \
## len(v[2][0][1]) == 1 and IsList(TypeExpr(v[2][0][1][0])):
## vectorlist = True
return [(old, new, stor, dele)]
if v[0] == 'STORE' and len(v[1]) == 1 and v[1][0][0] == 'SET_VARS' and len(v[2]) == 1:
t = TypeExpr(v[2][0])
## if t is not None:
## assert t.__class__.__name__ == 'Klass'
if not IsTuple(t):
return []
if type(t[1]) is tuple and len(t[1]) == len(v[1][0][1]):
t_prev = t
lis = []
for i,t in enumerate(t_prev[1]):
assign = v[1][0][1][i]
if IsKlNone(t) and assign[0] == 'STORE_NAME' and nmdef == 'Init_filename':
continue
if t is None:
continue
if IsList(t):
t = Kl_List
if assign[0] not in ('STORE_FAST', 'STORE_NAME'):
continue
stor = assign
dele = assign[:]
dele = ('DELETE_' + dele[0][6:], dele[1])
nm1 = assign[1]
if stor[0] == 'STORE_FAST':
nm2 = ('FAST', nm1)
else:
nm2 = ('!LOAD_NAME', nm1)
old = nm2
assert nm2[0] != 'PY_TYPE'
new = ('PY_TYPE', t[0], t[1], nm2, None)
lis.append((old, new, stor, dele))
return lis
if v[0] == 'SET_EXPRS_TO_VARS' and len(v[1]) == len(v[2]):
_v = v
lis = []
for i in range(len(_v[1])):
t = TypeExpr(v[2][i])
## if t is not None:
## assert t.__class__.__name__ == 'Klass'
if IsKlNone(t) and v[1][i][0] == 'STORE_NAME' and nmdef == 'Init_filename':
return []
elif t is None:
return []
if v[1][i][0] != 'STORE_FAST':
continue
stor = v[1][i]
dele = v[1][i]
dele = ('DELETE_' + dele[0][6:], dele[1])
nm1 = v[1][i][1]
nm2 = ('FAST', nm1)
old = nm2
if IsList(t):
t = Kl_List
assert nm2[0] != 'PY_TYPE'
new = ('PY_TYPE', t[0], t[1], nm2, None)
if t in _Kl_Simples and v[2][i][0] == 'CONST':
new = v[2][i]
if v[2][i][0] == '!CLASS_CALC_CONST':
assert v[2][i][1][0] != 'PY_TYPE'
new = ('PY_TYPE', t[0], v[2][i][1], nm2, None)
elif v[2][i][0] == '!CLASS_CALC_CONST_NEW':
assert v[2][i][1][0] != 'PY_TYPE'
new = ('PY_TYPE', t[0], v[2][i][1], nm2, None)
v2 = []
if TCmp(v[2][i], v2, ('!MK_FUNK', '?', ('CONST', ()))):
new = v[2][i]
## vectorlist = False
## if IsList(t) and v[2][0][0] == '!LIST_COMPR' and \
## len(v[2][0][1]) == 1 and IsList(TypeExpr(v[2][0][1][0])):
## vectorlist = True
lis.append((old, new, stor, dele))
return lis
return []
def recursive_type_detect(ret, nmdef):
if type(ret) != list:
return ret
ret = ret[:]
i = 0
while i < len(ret):
assert type(i) is int
v = ret[i]
## head = v[0]
if v[0] == '(FOR' and len(v[1]) == 1 and v[1][0][0] in ('STORE_FAST', 'STORE_NAME'):
t = TypeExpr(v[2])
if t == Kl_File or IsStr(t):
assign = v[1][0]
stor = assign
dele = assign[:]
dele = ('DELETE_' + dele[0][6:], dele[1])
nm1 = assign[1]
if stor[0] == 'STORE_FAST':
nm2 = ('FAST', nm1)
else:
nm2 = ('!LOAD_NAME', nm1)
old = nm2
assert nm2[0] != 'PY_TYPE'
if IsStr(t):
new = ('PY_TYPE', str, 1, nm2, None)
else:
new = ('PY_TYPE', str, None, nm2, None)
j = i + 1
s_repr = repr(ret[j])
if repr(stor) not in s_repr and repr(dele) not in s_repr:
ret[j] = replace_subexpr(ret[j], old, new)
i = i + 1
continue
v2 = []
if type(v) is tuple and len(v) > 0 and type(v[0]) is str and v[0] == '(FOR':
if len(v[1]) == 1 and len(v[1][0]) == 2 and v[1][0][0] == 'STORE_FAST' and 'range' in repr(v[2]):
v2 = [v[1][0][1]]
v3 = []
if TCmp(v[2], v3, \
('!PyObject_Call', ('!LOAD_BUILTIN', 'xrange'), ('CONST', (int, int)), \
('NULL',))) or \
TCmp(v[2], v3, \
('!PyObject_Call', ('!LOAD_BUILTIN', 'range'), ('CONST', (int, int)), \
('NULL',))) or \
TCmp(v[2], v3, \
('!PyObject_Call', ('!LOAD_BUILTIN', 'xrange'), ('CONST', (int,)), \
('NULL',))) or \
TCmp(v[2], v3, \
('!PyObject_Call', ('!LOAD_BUILTIN', 'range'), ('CONST', (int,)), \
('NULL',))):
stor = ('STORE_FAST', v2[0])
dele = ('DELETE_FAST', v2[0])
old = ('FAST', v2[0])
new = ('PY_TYPE', int, None, old, None)
j = i + 1
s_repr = repr(ret[j])
if repr(stor) not in s_repr and repr(dele) not in s_repr:
ret[j] = replace_subexpr(ret[j], old, new)
i = i + 1
continue
v2 = []
if ( TCmp(v, v2, ('(FOR', (('STORE_FAST', '?'),), \
('!PyObject_Call', ('!LOAD_BUILTIN', 'xrange'), ('!BUILD_TUPLE', ('?',)), \
('NULL',)))) or \
TCmp(v, v2, ('(FOR', (('STORE_FAST', '?'),), \
('!PyObject_Call', ('!LOAD_BUILTIN', 'range'), ('!BUILD_TUPLE', ('?',)), \
('NULL',))))) and IsInt(TypeExpr(v2[1])):
stor = ('STORE_FAST', v2[0])
dele = ('DELETE_FAST', v2[0])
old = ('FAST', v2[0])
new = ('PY_TYPE', int, None, old, None)
j = i + 1
s_repr = repr(ret[j])
if repr(stor) not in s_repr and repr(dele) not in s_repr:
ret[j] = replace_subexpr(ret[j], old, new)
i = i + 1
continue
if v[0] == '(IF' and v[1][0] == '!1NOT' and len(ret[i+1]) == 1 and \
ret[i+1][0] in (('RAISE_VARARGS', 0, (('!LOAD_BUILTIN', 'AssertionError'),)), ('CONTINUE',), ('BREAK',)) and \
ret[i+2] == (')ENDIF',):
d = {}
ret[i] = ('(IF', ('!1NOT', type_in_if(v[1][1], d)))
d = only_fast(d)
li = []
for k, v in d.iteritems():
li.append((k, ('PY_TYPE', v[0], v[1], k, None), ('STORE_FAST', k[1]), ('DELETE_FAST', k[1])))
for old, new, stor, dele in li:
j = i+1
replace_concretised_at_list_from_pos(ret, i+3, old, new, stor, dele)
i += 3
continue
if v[0] == '(IF':
d = {}
ret[i] = ('(IF', type_in_if(v[1], d))
d = only_fast(d)
li = []
for k, v in d.iteritems():
if v is not None:
li.append((k, ('PY_TYPE', v[0], v[1], k, None), ('STORE_FAST', k[1]), ('DELETE_FAST', k[1])))
for old, new, stor, dele in li:
j = i+1
replace_concretised_at_list_from_pos(ret[i + 1], 0, old, new, stor, dele)
i += 1
continue
li = list_typed_var_after_stmt(v, nmdef)
for old, new, stor, dele in li:
j = i+1
replace_concretised_at_list_from_pos(ret, i + 1, old, new, stor, dele)
if type(ret[i]) is list:
ret[i] = recursive_type_detect(ret[i], nmdef)
i += 1
return ret
def replace_concretised_at_list_from_pos(ret, j, old, new, stor, dele):
## assert stor[0] == 'STORE_FAST'
## s_stor = repr(stor)
## s_dele = repr(dele)
while j < len(ret):
if IsBeg(ret[j][0]):
j1 = get_closed_pair(ret, j)
if (new[0] == 'CONST' and type(new[1]) is int) :
v = []
v2 = []
if TCmp(ret[j], v, ('(WHILE', ('!BOOLEAN', \
('!c_Py_LT_Int', old, ('CONST', '?'))))) and\
( TCmp(ret[j+1][-1], v2, ('STORE', (stor,), \
(('!PyNumber_Add', old, ('CONST', 1)),))) or \
TCmp(ret[j+1][-1], v2, ('STORE', (stor,), \
(('!PyNumber_InPlaceAdd', old, ('CONST', 1)),))) ):
dic = {}
collect_store_and_delete_and_access(ret[j+1][:-1], dic)
if not stor in dic and not dele in dic and new[1] < v[0]:
oold = ('PY_TYPE', int, 'ssize', old[:], None)
if IsShort(TypeExpr(new)) and IsShort(TypeExpr(('CONST', v[0]))):
ret[j+1][:-1] = replace_subexpr(ret[j+1][:-1], old, ('PY_TYPE', int, 'ssize', old[:], None))
ret[j+1][-1] = ('STORE', (stor[:],), \
(('PY_TYPE', int, 'ssize', ('!PyNumber_Add', oold[:], ('CONST', 1)),None),))
else:
ret[j+1][:-1] = replace_subexpr(ret[j+1][:-1], old, ('PY_TYPE', int, None, old[:], None))
ret[j+1][-1] = ('STORE', (stor[:],), \
(('PY_TYPE', int, None, ('!PyNumber_Add', oold[:], ('CONST', 1)),None),))
ret[j+1:j+3] = [ret[j+1], ret[j+2], ('STORE', (stor[:],), (('CONST', v[0]),))]
continue
elif TCmp(ret[j], v, ('(WHILE', ('!BOOLEAN', \
('!c_Py_LE_Int', old, ('CONST', '?'))))) and\
( TCmp(ret[j+1][-1], v2, ('STORE', (stor,), \
(('!PyNumber_Add', old, ('CONST', 1)),))) or \
TCmp(ret[j+1][-1], v2, ('STORE', (stor,), \
(('!PyNumber_InPlaceAdd', old, ('CONST', 1)),))) ):
dic = {}
collect_store_and_delete_and_access(ret[j+1][:-1], dic)
if not stor in dic and not dele in dic and new[1] <= v[0]:
oold = ('PY_TYPE', int, 'ssize', old[:], None)
if IsShort(TypeExpr(new)) and IsShort(TypeExpr(('CONST', v[0]))):
ret[j+1][:-1] = replace_subexpr(ret[j+1][:-1], old, ('PY_TYPE', int, 'ssize', old[:], None))
ret[j+1][-1] = ('STORE', (stor[:],), \
(('PY_TYPE', int, 'ssize', ('!PyNumber_Add', oold[:], ('CONST', 1)),None),))
else:
ret[j+1][:-1] = replace_subexpr(ret[j+1][:-1], old, ('PY_TYPE', int, None, old[:], None))
ret[j+1][-1] = ('STORE', (stor[:],), \
(('PY_TYPE', int, None, ('!PyNumber_Add', oold[:], ('CONST', 1)),None),))
ret[j+1:j+3] = [ret[j+1], ret[j+2], ('STORE', (stor[:],), (('CONST', v[0] + 1),))]
continue
elif ( TCmp(ret[j], v, \
('(WHILE', ('!PyObject_RichCompare(', old, \
'?', 'Py_LT'))) or\
TCmp(ret[j], v, \
('(WHILE', ('!PyObject_RichCompare(', old, \
'?', 'Py_LE'))) ) \
and\
( TCmp(ret[j+1][-1], v2, ('STORE', (stor,), \
(('!PyNumber_Add', old, ('CONST', 1)),))) or\
TCmp(ret[j+1][-1], v2, ('STORE', (stor,), \
(('!PyNumber_InPlaceAdd', old, ('CONST', 1)),))) ):
dic = {}
collect_store_and_delete_and_access(ret[j+1][:-1], dic)
if not stor in dic and not dele in dic and IsInt(TypeExpr(v[0])):
oold = ('PY_TYPE', int, 'ssize', old[:], None)
if IsShort(TypeExpr(new)):
ret[j+1][:-1] = replace_subexpr(ret[j+1][:-1], old, ('PY_TYPE', int, 'ssize', old[:], None))
ret[j+1][-1] = ('STORE', (stor[:],), \
(('PY_TYPE', int, 'ssize', ('!PyNumber_Add', oold[:], ('CONST', 1)),None),))
else:
ret[j+1][:-1] = replace_subexpr(ret[j+1][:-1], old, ('PY_TYPE', int, None, old[:], None))
ret[j+1][-1] = ('STORE', (stor[:],), \
(('PY_TYPE', int, None, ('!PyNumber_Add', oold[:], ('CONST', 1)),None),))
continue
ret_j_j1 = ret[j:j1]
dic = {}
collect_store_and_delete_and_access(ret_j_j1, dic)
if stor in dic and not dele in dic:
if ret[j][0] == '(IF':
ret[j:j1] = repl_in_if_store(ret_j_j1, old, new, stor, dele)
break
elif stor in dic or dele in dic:
break
ret[j:j1] = replace_subexpr(ret_j_j1, old, new)
j = j1 + 1
continue
dic = {}
collect_store_and_delete_and_access(ret[j], dic)
if stor in dic:
if ret[j][0] == 'STORE' and len(ret[j][1]) == 1 and \
ret[j][1][0] == stor and len(ret[j][2]) == 1:
v2 = replace_subexpr(ret[j][2][0], old, new)
ret[j] = ('STORE', ret[j][1], (v2,))
break
elif dele in dic:
break
ret[j] = replace_subexpr(ret[j], old, new)
j = j + 1
def collect_store_and_delete_and_fast(it, dic):
if type(it) is list:
for v in it:
collect_store_and_delete_and_fast(v, dic)
return
if type(it) is tuple:
if len(it) == 2:
if it[0] in ('STORE_FAST', 'DELETE_FAST', 'FAST'):
dic[it] = True
for v in it:
if type(v) is tuple:
collect_store_and_delete_and_fast(v, dic)
return
def collect_store_and_delete_and_access(it, dic):
if type(it) is list:
for v in it:
collect_store_and_delete_and_access(v, dic)
return
if type(it) is tuple:
if len(it) == 2:
if it[0] in ('STORE_FAST', 'DELETE_FAST', 'FAST', 'STORE_NAME', 'DELETE_NAME', '!LOAD_NAME'):
dic[it] = True
for v in it:
if type(v) is tuple:
collect_store_and_delete_and_access(v, dic)
return
def replace_local_const_detect(ret, nmdef):
if type(ret) != list:
return ret
ret = ret[:]
i = 0
while i < len(ret):
assert type(i) is int
v = ret[i]
## head = v[0]
li1 = list_typed_var_after_stmt(v, nmdef)
li = [(old, new, stor, dele) for old, new, stor, dele in li1 if old[0] == 'FAST' and new[0] != 'PY_TYPE']
if len(li) > 0:
dic = {}
collect_store_and_delete_and_fast(ret[i+1:], dic)
for old, new, stor, dele in li:
if stor in dic or dele in dic:
continue
if not old in dic:
if new[0] in ('CONST', '!MK_FUNK') and ret[i] == ('STORE', (stor,), (new,)):
del ret[i]
else:
ret[i+1:] = replace_subexpr(ret[i+1:], old, new)
i += 1
return ret
def join_defined_calls(_calls, argcount, nm, is_varargs):
l = []
# if nm == 'HideDebug':
# print '/1', _calls, argcount, nm, is_varargs
if is_varargs:
argcount += 1
for c, typs in _calls:
a = []
if c[0] == 'CONST':
for _a in c[1]:
a.append(('CONST', _a))
# print '/3', a
elif c[0] == '!BUILD_TUPLE':
for i, _a in enumerate(c[1]):
if _a[0] == 'CONST':
a.append(_a)
elif _a[0] == 'PY_TYPE':
a.append((_a[1], _a[2]))
else:
t = typs[i]
# t = TypeExpr(_a)
if t is not None:
assert len(t) == 2
a.append(t)
else:
a.append((None, None))
# print '/4', a
else:
Fatal('Can\'t join calls', c, _calls)
# print '/7', a
if argcount != len(a) and not is_varargs:
if argcount > len(a):
if nm in default_args:
cc = default_args[nm]
if cc[0] == 'CONST':
_refs2 = [('CONST', x) for x in cc[1]]
else:
assert cc[0] == '!BUILD_TUPLE'
_refs2 = [x for x in cc[1]]
add_args = argcount - len(a)
pos_args = len(_refs2) - add_args
a = a + _refs2[pos_args:]
# print '/5', a
elif is_varargs:
if argcount -1 > len(a):
if nm in default_args:
cc = default_args[nm]
if cc[0] == 'CONST':
_refs2 = [('CONST', x) for x in cc[1]]
else:
assert cc[0] == '!BUILD_TUPLE'
_refs2 = [x for x in cc[1]]
add_args = ( argcount - 1 ) - len(a)
pos_args = len(_refs2) - add_args
a = a + _refs2[pos_args:]
new_a = []
for i in range(argcount-1):
new_a.append(a[i])
new_a.append((tuple, None))
a = new_a
# print '/6', a
if len(a) != argcount: # or nm == 'HideDebug':
Fatal('', _calls, a, argcount, nm, is_varargs)
# print '/8', a
assert len(a) == argcount
l.append(a)
l2 = []
for i in range(argcount):
d = {}
for ll in l:
d[ll[i]] = True
if len(d) > 1:
d2 = {}
for k,v in d.iteritems():
if type(k) is tuple and k[0] == 'CONST':
k = TypeExpr(k)
d2[k] = v
d = d2
if len(d) > 1:
if len(d) > 1 and None not in d and (None, None) not in d:
ts = [(x[0], x[1]) for x in d.keys()]
ts = uniq_list_type(ts)
if len(ts) == 1:
d = {ts[0]:True}
if len(d) > 1:
d = {None:True}
l2.append(d.keys()[0])
l = l2
return l
def dotted_name_to_first_name(nm):
if '.' in nm:
return nm.split('.')[0]
return nm
def filter_founded_calc_const(p, k, do_del):
v = []
if TCmp(p, v, ('STORE', (('STORE_NAME', '?'),), \
(('!IMPORT_NAME', '?', ('CONST', -1), ('CONST', None)),))):
if v[0] == k:
all_calc_const[k] = p[2][0]
_3(k, 'ImportedM', dotted_name_to_first_name(v[1]))
elif p[0] == 'STORE' and len(p[1]) == len(p[2]) == 1:
if p[2][0][0] in ('!LOAD_NAME', '!LOAD_GLOBAL') and p[2][0][1] in all_calc_const:
if p[1][0][0] in ('STORE_NAME', 'STORE_GLOBAL') and p[1][0][1] == k:
ok = p[2][0][1]
all_calc_const[k] = all_calc_const[ok]
if ok in no_compiled:
no_compiled[k] = no_compiled[ok]
if ok in default_args:
default_args[k] = default_args[ok]
if ok in mnemonic_constant:
mnemonic_constant[k] = mnemonic_constant[ok]
if ok in direct_code:
direct_code[k] = direct_code[ok]
if ok in val_direct_code:
val_direct_code[k] = val_direct_code[ok]
if ok in detected_return_type:
detected_return_type[k] = detected_return_type[ok]
if ok in calc_const_value:
calc_const_value[k] = calc_const_value[ok]
for a,b,c in Iter3(ok, None, None):
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
_3(k, b,c)
elif p[2][0][0] == 'CONST' or\
TCmp(p[2][0], v, ('!PyObject_GetAttr', ('CONST', '?'), ('CONST', '?'))):
if p[2][0][1] is not None:
if p[1][0][0] in ('STORE_NAME', 'STORE_GLOBAL') and p[1][0][1] == k:
all_calc_const[k] = p[2][0]
mnemonic_constant[k] = p[2][0]
elif p[1][0][0] == 'SET_VARS' and ('STORE_NAME', k) in p[1][0][1] and p[2][0][0] == 'CONST' and type(p[2][0][1]) is tuple and p[1][0][1].index(('STORE_NAME', k)) < len(p[2][0][1]):
pos_ = p[1][0][1].index(('STORE_NAME', k))
all_calc_const[k] = ('CONST', p[2][0][1][pos_])
mnemonic_constant[k] = ('CONST', p[2][0][1][pos_])
elif p[1][0][0] == 'SET_VARS' and ('STORE_GLOBAL', k) in p[1][0][1] and p[2][0][0] == 'CONST' and type(p[2][0][1]) is tuple and p[1][0][1].index(('STORE_NAME', k)) < len(p[2][0][1]):
pos_ = p[1][0][1].index(('STORE_GLOBAL', k))
all_calc_const[k] = ('CONST', p[2][0][1][pos_])
mnemonic_constant[k] = ('CONST', p[2][0][1][pos_])
else:
Fatal('--590--', p)
return
# elif p[2][0][0] == 'CALC_CONST':
# if p[1][0][0] in ('STORE_NAME', 'STORE_GLOBAL') and p[1][0][1] == k:
elif p[2][0][0] == '!IMPORT_NAME':
if p[1][0][0] in ('STORE_NAME', 'STORE_GLOBAL') and p[1][0][1] == k and\
p[2][0][2] == ('CONST', -1) and p[2][0][3] == ('CONST', None):
all_calc_const[k] = p[2][0]
_3(k, 'ImportedM', dotted_name_to_first_name(p[2][0][1]))
else:
Fatal('--597--', p)
return
else:
if p[1][0][0] in ('STORE_NAME', 'STORE_GLOBAL') and p[1][0][1] == k:
all_calc_const[k] = p[2][0]
return
# if p[2][0][0][0] == '!':
# return
elif p[0] == 'IMPORT_STAR':
print (p)
elif p[0] == 'IMPORT_FROM_AS' and\
TCmp(p, v, ('IMPORT_FROM_AS', '?', ('CONST', '?'), ('CONST', '?'), '?')):
## sreti = []
del v[1] ## Hack !!!!!!!!!!!!!!!!!!!!!!!!!!!
imp, consts_, stores = v
for i, reti in enumerate(stores):
v = []
if reti[0] in ('STORE_NAME', 'STORE_GLOBAL') and reti[1] == k:
all_calc_const[k] = '???'
v = IfConstImp(imp, consts_[i])
if v is not None:
mnemonic_constant[k] = v
else:
_3(k, 'ImportedM', (imp, consts_[i]))
if (imp, consts_[i], 'val') in t_imp:
t = t_imp[(imp, consts_[i], 'val')]
if is_new_class_typ(t):
calc_const_new_class[k] = '???'
## _3(k, 'CalcConstNewClass', '???')
elif is_old_class_typ(t):
calc_const_old_class[k] = '???'
## _3(k, 'CalcConstOldClass', '???')
return
elif p[0] in (')(EXCEPT', '(FOR'):
do_del.append(k)
return
elif p[0] == 'SEQ_ASSIGN':
if ('STORE_NAME', k) in p[1]:
all_calc_const[k] = p[2]
else:
for pi in p[1]:
if pi[0] == 'SET_VARS':
if ('STORE_NAME', k) in pi[1]:
all_calc_const[k] = p[2]
elif p[0] == 'SEQ_ASSIGN' and ('STORE_NAME', k) in p[1]:
all_calc_const[k] = p[2]
elif p[0] == 'SET_EXPRS_TO_VARS' and ('STORE_NAME', k) in p[1]:
all_calc_const[k] = p[2]
elif p[0] == 'UNPUSH':
return
elif p[0] == '!LIST_COMPR':
return
elif p[0] == 'PRINT_ITEM_1':
return
else:
Fatal('can\'t handle CALC_CONST', p, k)
list_ext = []
from distutils import sysconfig
cc2 = None
def compile_c(base, cname):
global cc2
global list_cname_exe
optio = [] ## ['-O0']
if len(opt_flag) > 0:
optio = opt_flag
preargs = optio + ['-Wall']
if build_executable:
if cc2 is None:
cc = distutils.ccompiler.get_default_compiler(os.name, sys.platform)
cc2 = new_compiler(os.name,cc, 1)
cc2.set_include_dirs([sysconfig.get_python_inc()])
## if 'gettotalrefcount' in sys.__dict__ and sys.platform != 'win32':
## preargs += ['-DPy_DEBUG']
cc2.compile([cname], output_dir=None, macros=None, include_dirs=None, debug=1, extra_preargs=preargs, extra_postargs=preargs, depends=None)
link_exe(cname)
return
example_mod = distutils.core.Extension(cname[0:-2], sources = [cname], \
extra_compile_args = optio, \
extra_link_args = [])
distutils.core.setup(name = cname[0:-2],
version = "1.0",
description = "Compiled to C Python code " + base,
ext_modules = [example_mod],
script_name = 'install' ,
script_args = ['build_ext']
)
list_ext.append(example_mod)
def link_exe(cname):
if sys.platform == 'win32':
optio = []
else:
optio = ['-Os']
if len(opt_flag) > 0:
optio = opt_flag
if sys.platform == 'win32':
pyver = '%d%d' % sys.version_info[:2]
else:
pyver = sysconfig.get_config_var('VERSION')
## includes = '-I' + sysconfig.get_python_inc() + ' ' + \
## '-I' + sysconfig.get_python_inc(plat_specific=True)
## ldflags = sysconfig.get_config_var('LIBS') + ' ' + \
## sysconfig.get_config_var('SYSLIBS') + ' ' + \
## '-lpython'+pyver
## if not sysconfig.get_config_var('Py_ENABLE_SHARED'):
## ldflags += ' -L' + sysconfig.get_config_var('LIBPL')
# cc2.set_include_dirs([sysconfig.get_python_inc()])
## sysconfig.customize_compiler(cc2)
libdir = sysconfig.get_python_lib()
if sys.platform == 'win32':
libs = [libdir, sysconfig.PREFIX + '\\bin', \
sysconfig.PREFIX + '\\lib', sysconfig.PREFIX + '\\libs']
else:
libs = [libdir, sysconfig.PREFIX + '/bin', \
sysconfig.PREFIX + '/lib', sysconfig.PREFIX + '/config']
if libdir.endswith('/site-packages'):
libs.append(libdir[:-14])
libs = [libdir[:-14]+'/config'] + libs
if hasattr(sys, 'gettotalrefcount') and sys.platform != 'win32':
libraries=['python'+pyver + '_d']
else:
libraries=['python'+pyver]
if sys.platform == 'win32':
cc2.link_executable([cname[:-2]+'.obj'], cname[:-2], output_dir=None, libraries = ['python'+pyver], library_dirs=[sysconfig.get_python_lib()] + libs, runtime_library_dirs=[], debug=0, extra_preargs=[] + optio, extra_postargs=optio, target_lang=None)
else:
cc2.link_executable([cname[:-2]+'.o'], cname[:-2], output_dir=None, libraries = libraries, library_dirs=[sysconfig.get_python_lib()] + libs, runtime_library_dirs=[], debug=1, extra_preargs=['-pg'] + optio, extra_postargs=optio, target_lang=None)
return
def link_c():
if len(list_ext) != 0:
distutils.core.setup(name = 'install_all',
version = "1.0",
description = "Compiled to C Python code",
ext_modules = list_ext,
script_name = 'install' ,
script_args = ['install']
)
def unjumpable(cmd):
if len(cmd) == 1:
if cmd[0] in ('RETURN_VALUE', 'EXEC_STMT'):
return False
if cmd[0][0:6] in ('BINARY', 'UNARY_'):
return False
if cmd[0] in set_any:
return False
if cmd[0] in _unjump_cmds:
return False
if cmd[0] == 'RAISE_VARARGS' and cmd[1] != 0:
return False
if cmd[0] in ('STORE', 'SEQ_ASSIGN', 'SET_EXPRS_TO_VARS', 'UNPUSH'):
return True
if cmd[0][0] in ('J', '(', ')') :
return False
if cmd[0] == 'LOAD_CONST':
return False
return not type(cmd) is list and \
cmd[0] is not None and cmd[0][0] != '!' and cmd[0] not in ('LOAD_FAST', 'LOAD_CLOSURE') and \
cmd[0][0] not in ('J', '(', ')') and cmd[0][0:2] != '.:'
def linear_to_seq(cmds):
ret = []
i = 0
while i < len(cmds):
assert type(i) is int
cmd = cmds[i]
if not unjumpable(cmd):
ret.append(cmd)
i = i + 1
continue
ret2 = []
while unjumpable(cmd) or type(cmd) is list:
if type(cmd) is list:
ret2.extend(cmd[:])
else:
ret2.append(cmd)
i = i + 1
if i < len(cmds):
cmd = cmds[i]
else:
break
if len(ret) > 0 and type(ret[-1]) is list:
ret[-1] = ret[-1] + ret2
else:
ret.append(ret2)
continue
cmds[:] = ret[:]
def jump_to_continue_and_break(cmds):
i = 0
loops = [(i,pos_label(cmds, x[1])) for i,x in enumerate(cmds) if x[0] in ('J_SETUP_LOOP', 'J_SETUP_LOOP_FOR')]
## breaks = {}
continues = {}
ranges = {}
for a,b in loops:
j = a + 1
while j < len(cmds) and j < b:
if cmds[j][0] == '.:':
continues[a] = cmds[j][1]
break
if (cmds[j][0][0:4] == 'JUMP' or cmds[j][0][0:7] == 'J_SETUP'):
break
j = j + 1
ranges[a] = set([i for i in range(a,b) if cmds[i][0][0] == 'J'])
inter = [(a1,b1, a2,b2) for a1,b1 in loops for a2,b2 in loops if a2 > a1 and b2 < b1]
for a1,b1,a2,b2 in inter:
ranges[a1] = ranges[a1] - ranges[a2]
for a,b in loops:
for i in ranges[a]:
cmd = cmds[i]
if cmd[0] in jump and a in continues and cmd[1] == continues[a]:
cmds[i] = ('JUMP_CONTINUE',) + cmd[1:]
if cmd[0] == 'JUMP_IF_TRUE_POP' and a in continues and cmd[1] == continues[a]:
cmds[i] = ('JUMP_IF_TRUE_POP_CONTINUE',) + cmd[1:]
if cmd[0] == 'JUMP_IF_FALSE_POP' and a in continues and cmd[1] == continues[a]:
cmds[i] = ('JUMP_IF_FALSE_POP_CONTINUE',) + cmd[1:]
if cmd[0] == 'JUMP_IF2_TRUE_POP' and a in continues and cmd[1] == continues[a]:
cmds[i] = ('JUMP_IF2_TRUE_POP_CONTINUE',) + cmd[1:]
if cmd[0] == 'JUMP_IF2_FALSE_POP' and a in continues and cmd[1] == continues[a]:
cmds[i] = ('JUMP_IF2_FALSE_POP_CONTINUE',) + cmd[1:]
## def prin(n,cmd,cmds = None):
## if not print_pycmd:
## return
## if isblock(cmd):
## print >>out,n, '{'
## print_cmds2(cmd, 2)
## print >>out,'}'
## elif cmd[0] == '.:':
## print >>out,n,cmd, CountJumpCache(cmd[1],cmds)
## else:
## print >>out,n,cmd
def label(j,l):
return bool(j[0][0] == 'J' and l[0] == '.:' and l[1] == j[1])
def endlabel(j,l):
return bool(j[0][0] == 'J' and (l[0] == '.:' or l[0] in jump) and l[1] == j[1])
def cmds_join(i,cmds):
if i >= len(cmds):
return
if i > 0 and type(cmds[i]) is list and type(cmds[i-1]) is list:
cmds[i-1] = cmds[i-1] + cmds[i]
del cmds[i]
cmds_join(max(0,i-1),cmds)
cmds_join(i,cmds)
cmds_join(min(len(cmds)-1,i+1),cmds)
return
if i < len(cmds)-1 and type(cmds[i]) is list and type(cmds[i+1]) is list:
cmds[i] = cmds[i] + cmds[i+1]
del cmds[i+1]
cmds_join(max(0,i-1),cmds)
cmds_join(i,cmds)
cmds_join(min(len(cmds)-1,i+1),cmds)
return
if i < len(cmds)-1 and i > 0 and \
type(cmds[i-1]) is list and unjumpable(cmds[i]) and type(cmds[i+1]) is list:
cmds[i] = cmds[i-1] + [cmds[i]] + cmds[i+1]
del cmds[i-1]
del cmds[i]
cmds_join(max(0,i-1),cmds)
cmds_join(i,cmds)
cmds_join(min(len(cmds)-1,i+1),cmds)
return
if i > 0 and unjumpable(cmds[i]) and type(cmds[i-1]) is list:
cmds[i-1] = cmds[i-1] + [cmds[i]]
del cmds[i]
cmds_join(max(0,i-1),cmds)
cmds_join(i,cmds)
cmds_join(min(len(cmds)-1,i+1),cmds)
return
if i < len(cmds)-1 and type(cmds[i]) is list and unjumpable(cmds[i+1]):
cmds[i] = cmds[i] + [cmds[i+1]]
del cmds[i+1]
cmds_join(max(0,i-1),cmds)
cmds_join(i,cmds)
cmds_join(min(len(cmds)-1,i+1),cmds)
return
if i < len(cmds)-1 and type(cmds[i+1]) is list and unjumpable(cmds[i]):
cmds[i] = [cmds[i]] + cmds[i+1]
del cmds[i+1]
cmds_join(max(0,i-1),cmds)
cmds_join(i,cmds)
cmds_join(min(len(cmds)-1,i+1),cmds)
return
if i > 0 and unjumpable(cmds[i]) and not type(cmds[i]) is list and\
not type(cmds[i-1]) is list and cmds[i-1][0] == '.L':
cmds[i-1] = [cmds[i-1],cmds[i]]
del cmds[i]
cmds_join(max(0,i-1),cmds)
return
if unjumpable(cmds[i]) and not type(cmds[i]) is list :
cmds[i] = [cmds[i]]
return
def prin(a,b,c):
print >>out, a
print >>out, b
def print_pr(cmds):
if not print_pycmd:
return
global pos__a,pos__b,pos__c,pos__d,pos__e,pos__f,pos__g,pos__h,pos__i,pos__j,pos__k,pos__l
prin (1,pos__a, cmds)
prin (2,pos__b, cmds)
prin (3,pos__c, cmds)
prin (4,pos__d, cmds)
prin (5,pos__e, cmds)
prin (6,pos__f, cmds)
prin (7,pos__g, cmds)
prin (8,pos__h, cmds)
prin (9,pos__i, cmds)
prin (10,pos__j, cmds)
prin (11,pos__k, cmds)
prin (12,pos__l, cmds)
print >>out, ''
def half_recompile(cmds, co):
global debug
global pos__a,pos__b,pos__c,pos__d,pos__e,pos__f,pos__g,pos__h,pos__i,pos__j,pos__k,pos__l
i = 0
totemp = [(None,)] * 12
oldi = -1
first = True
last = False
added_pass = False
# debug = False
only_matched = False
ClearJumpCache()
if debug:
if print_pycmd:
print >>out, 'Step 0'
print_cmds(cmds)
ClearJumpCache()
while i <= len(cmds):
assert type(i) is int
if first and i == len(cmds):
ClearJumpCache()
if debug and print_pycmd:
print >>out, 'Step 1'
print_cmds(cmds)
linear_to_seq(cmds)
NoGoToGo(cmds)
jump_to_continue_and_break(cmds)
i = 0
first = False
elif not first and i == len(cmds) and not last and len(cmds) > 2:
ClearJumpCache()
if debug and print_pycmd:
print >>out, 'Step 2'
print_cmds(cmds)
added_pass = True
NoGoToGo(cmds)
NoGoToReturn(cmds)
jump_to_continue_and_break(cmds)
i = 0
first = False
last = True
i = 0
while i < len(cmds):
assert type(i) is int
if islineblock(cmds[i]):
del cmds[i]
continue
i = i + 1
i = 0
bingo = False
assert type(i) is int
if oldi == i:
bingo = True
ClearJumpCache()
## prevlen = len(cmds)
if debug == True:
tempor = cmds[i:i+12]
while len(tempor) < 12:
tempor.append((None,))
pos__a,pos__b,pos__c,pos__d,pos__e,pos__f,pos__g,pos__h,pos__i,pos__j,pos__k,pos__l = tempor
if print_pycmd:
print >>out, '!!!!!!',i, '!!!!!!'
print_pr(cmds)
_len = len(cmds)
cmds_join(i,cmds)
i -= 12
if len(cmds) < _len:
i -= _len - len(cmds)
if i < 0:
i = 0
## del_all_unused_label(cmds, i)
if i < 0:
i = 0
oldi = i
tempor = cmds[i:i+12]
if len(tempor) < 12:
tempor = (tempor + totemp)[:12]
pos__a,pos__b,pos__c,pos__d,pos__e,pos__f,pos__g,pos__h,pos__i,pos__j,pos__k,pos__l = tempor
if debug == True and print_pycmd and not only_matched:
if bingo:
print >>out, '*****',i, '*****'
else:
print >>out, '--',i, '--'
print_pr(cmds)
begin_cmp()
if type(pos__a) is tuple and len(pos__a) >= 1:
if pos__a[0] is not None and pos__a[0][0:4] == 'JUMP' and\
pos__a[0] != 'JUMP_IF_NOT_EXCEPTION_POP':
changed_jump = process_jump(cmds,i,added_pass)
if changed_jump:
continue
if pos__a[0] == 'J_FOR_ITER':
if pos__b[0] in set_any:
cmds[i:i+2] = [('J_LOOP_VARS', pos__a[1], (pos__b,))]
continue
if islineblock(pos__b) and pos__c[0] in set_any:
cmds[i:i+3] = [('J_LOOP_VARS', pos__a[1], (pos__c,))]
continue
if pos__b[0] == 'UNPACK_SEQ_AND_STORE' and pos__b[1] == 0:
b2 = pos__b[2]
if len(b2) == 1:
b2 += (None,)
cmds[i:i+2] = [('J_LOOP_VARS', pos__a[1], b2)]
continue
if pos__a[0] == '.:' and pos__b[0] == 'J_LOOP_VARS':
if pos__e[0] == 'JUMP' and is_cmdmem(pos__c):
if SCmp(cmds, i, ((':', 4), 'J_LOOP_VARS', '>', \
'LIST_APPEND', 'JUMP', '.:')) and \
pos__a[1] != pos__b[1] and pos__f[0] != pos__b[1] and len(pos__d) == 2:
rpl(cmds, [pos__a, ('J_BASE_LIST_COMPR', pos__b[1], (cmd2mem(pos__c),), (pos__b[2], None, ())),pos__f] )
continue
if SCmp(cmds, i, ((':', 4), 'J_LOOP_VARS', '>', \
('SET_ADD', 2), 'JUMP', '.:')) and \
pos__a[1] != pos__b[1] and pos__f[0] != pos__b[1] :
rpl(cmds, [pos__a, ('J_BASE_SET_COMPR', pos__b[1], (cmd2mem(pos__c),), (pos__b[2], None, ())),pos__f] )
continue
if pos__f[0] == 'JUMP' and is_cmdmem(pos__c) and is_cmdmem(pos__d):
if SCmp(cmds, i, ((':', 5), 'J_LOOP_VARS', '>', '>', \
('MAP_ADD', 2), 'JUMP', '.:')) and \
pos__a[1] != pos__b[1] and pos__g[0] != pos__b[1] :
rpl(cmds, [pos__a, ('J_BASE_MAP_COMPR', pos__b[1], (cmd2mem(pos__d),cmd2mem(pos__c),), (pos__b[2], None, ())),pos__g] )
continue
if pos__e[0] == 'LIST_APPEND':
if SCmp(cmds, i, ((':', 5), 'J_LOOP_VARS', 'JUMP_IF2_TRUE_POP', '>', \
'LIST_APPEND', 'JUMP', '.:')) and \
pos__a[1] != pos__b[1] and pos__g[0] != pos__b[1] and len(pos__e) == 2:
rpl(cmds, [pos__a, ('J_BASE_LIST_COMPR', pos__b[1], (cmd2mem(pos__d),), (pos__b[2], None, (Not(pos__c[2]),))),pos__g] )
continue
if SCmp(cmds, i, ((':', 5), 'J_LOOP_VARS', 'JUMP_IF2_FALSE_POP', '>', \
'LIST_APPEND', 'JUMP', '.:')) and \
pos__a[1] != pos__b[1] and pos__g[0] != pos__b[1] and len(pos__e) == 2:
rpl(cmds, [pos__a, ('J_BASE_LIST_COMPR', pos__b[1], (cmd2mem(pos__d),), (pos__b[2], None, (pos__c[2],))),pos__g] )
continue
if pos__a[0] == '.L':
if pos__b[0] in jump and len(pos__b) == 2:
cmds[i:i+2] = [(pos__b[0], pos__b[1], pos__a[1])]
continue
if pos__b[0] == 'J_SETUP_LOOP' and len(pos__b) == 2:
cmds[i:i+2] = [('J_SETUP_LOOP', pos__b[1], pos__a[1])]
continue
if pos__b[0] == '.L':
cmds[i:i+2] = [pos__b]
continue
if pos__b[0] == 'DUP_TOP' and is_cmdmem(pos__c) and \
len(pos__d) == 2 and pos__d[0] == 'COMPARE_OP' and pos__d[1] == 'exception match':
cmds[i:i+4] = [('CHECK_EXCEPTION', cmd2mem(pos__c), pos__a[1])]
continue
if pos__a[0] == 'DELETE_FAST' and pos__a[1][0:2] == '_[':
cmds[i] = (')END_LIST_COMPR', ('FAST', pos__a[1]))
continue
if pos__a[0] == 'DELETE_NAME' and pos__a[1][0:2] == '_[':
cmds[i] = (')END_LIST_COMPR', ('NAME', pos__a[1]))
continue
if pos__a[0] == 'UNPACK_SEQUENCE' and len(pos__a) == 2 and pos__a[1] > 0 and pos__b[0] in set_any:
cmds[i] = ('UNPACK_SEQ_AND_STORE', pos__a[1], ())
continue
if pos__a[0] == 'UNPACK_SEQUENCE' and len(pos__a) == 2 and pos__a[1] > 0 and pos__b[0] == 'UNPACK_SEQ_AND_STORE':
cmds[i] = ('UNPACK_SEQ_AND_STORE', pos__a[1], ())
continue
if pos__a[0] == 'UNPACK_SEQ_AND_STORE':
if pos__a[1] == 0:
cmds[i] = ('SET_VARS', pos__a[2])
continue
if pos__a[1] > 0 and pos__b[0] == '.L' and pos__c[0] in set_any:
cmds[i:i+3] = [('UNPACK_SEQ_AND_STORE', pos__a[1]-1, pos__a[2] + (pos__c,))]
continue
if pos__a[1] > 0 and pos__b[0] in set_any:
cmds[i:i+2] = [('UNPACK_SEQ_AND_STORE', pos__a[1]-1, pos__a[2] + (pos__b,))]
continue
if pos__a[1] > 0 and pos__b[0] == 'UNPACK_SEQ_AND_STORE' and pos__b[1] == 0 :
cmds[i:i+2] = [('UNPACK_SEQ_AND_STORE', pos__a[1]-1, pos__a[2] + (pos__b,))]
continue
if pos__a[0] == 'LOAD_CODEFUNC' and pos__b[0] == 'MAKE_FUNCTION':
cmds[i:i+2] = [('MK_FUNK', pos__a[1], pos__b[1], ())]
continue
if pos__a[0] == 'MK_FUNK' and pos__a[2] == 0:
cmds[i:i+1] = [('!MK_FUNK', pos__a[1], TupleFromArgs(pos__a[3]))]
continue
if pos__a[0] == 'MK_CLOSURE' and pos__a[2] == 0:
cmds[i:i+1] = [('!MK_CLOSURE', pos__a[1], pos__a[3], TupleFromArgs(pos__a[4]))]
continue
if pos__a[0] == 'IMPORT_FROM' and pos__b[0] in set_any:
cmds[i:i+2] = [('IMPORT_AND_STORE_AS', (pos__a[1],), (pos__b,))]
continue
if pos__a[0] == 'IMPORT_AND_STORE_AS' and pos__b[0] == 'IMPORT_AND_STORE_AS':
cmds[i:i+2] = [('IMPORT_AND_STORE_AS', pos__a[1] + pos__b[1], pos__a[2] + pos__b[2])]
continue
if pos__a[0] == '!IMPORT_NAME' and pos__b[0] == 'IMPORT_AND_STORE_AS' and pos__c[0] == 'POP_TOP' and pos__a[3][1] == pos__b[1]:
cmds[i:i+3] = [('IMPORT_FROM_AS', pos__a[1], pos__a[2], pos__a[3], pos__b[2])]
continue
# LOAD_CLOSURE and LOAD_DEREF marked as 'pure' ? or not ?
if pos__a[0] in ('LOAD_GLOBAL', 'LOAD_NAME'):
if pos__a[1] in ('True', 'False', 'None'):
if pos__a[1] == 'True':
cmds[i] = ('LOAD_CONST', True)
elif pos__a[1] == 'False':
cmds[i] = ('LOAD_CONST', False)
elif pos__a[1] == 'None':
cmds[i] = ('LOAD_CONST', None)
continue
if not redefined_all and pos__a[1] in d_built and \
(pos__a[1][0:2] != '__' or pos__a[1] in ('__import__',) )and \
not pos__a[1] in redefined_builtin:
cmds[i] = ('!LOAD_BUILTIN', pos__a[1])
continue
if pos__a[0] == 'LOAD_GLOBAL':
cmds[i] = ('!LOAD_GLOBAL', pos__a[1])
continue
if pos__a[0] == 'LOAD_NAME':
cmds[i] = ('!LOAD_NAME', pos__a[1])
continue
if pos__a[0] == 'LOAD_DEREF':
cmds[i] = ('!LOAD_DEREF', pos__a[1])
continue
if pos__a[0] == 'BUILD_LIST' and pos__a[1] == 0:
if len(pos__a) == 3:
cmds[i] = ('!BUILD_LIST', pos__a[2])
else:
cmds[i] = ('!BUILD_LIST', ())
continue
if pos__a == ('!BUILD_LIST', ()) and pos__b[0] == '!GET_ITER':
changed_list_compr = process_list_compr_2(cmds,i,added_pass)
if changed_list_compr:
continue
if pos__a[0] == 'BUILD_TUPLE' and pos__a[1] == 0:
if len(pos__a) == 3:
cmds[i] = TupleFromArgs(pos__a[2])
else:
cmds[i] = ('CONST', ())
continue
if pos__a[0] == 'BUILD_SET':
if pos__a[1] == 0 and len(pos__a) == 3 :
cmds[i] = ('!BUILD_SET', pos__a[2])
continue
if pos__a[1] == 0 and len(pos__a) == 2:
cmds[i] = ('!BUILD_SET', ())
continue
if pos__a == ('!BUILD_SET', ()) and pos__b == ('LOAD_FAST', '.0') and \
pos__c[0] == 'J_BASE_SET_COMPR' and pos__d == ('.:', pos__c[1]):
if pos__c[3][1] is None:
if pos__c[3][2] == ():
cmds[i:i+4] = [('!SET_COMPR', pos__c[2], (pos__c[3][0], (cmd2mem(pos__b),), None))]
continue
else:
cmds[i:i+4] = [('!SET_COMPR', pos__c[2], (pos__c[3][0], (cmd2mem(pos__b),), pos__c[3][2]))]
continue
if pos__a == ('!PyDict_New',) and pos__b == ('LOAD_FAST', '.0') and \
pos__c[0] == 'J_BASE_MAP_COMPR' and pos__d == ('.:', pos__c[1]):
if pos__c[3][1] is None:
if pos__c[3][2] == ():
cmds[i:i+4] = [('!MAP_COMPR', pos__c[2], (pos__c[3][0], (cmd2mem(pos__b),), None))]
continue
else:
cmds[i:i+4] = [('!MAP_COMPR', pos__c[2], (pos__c[3][0], (cmd2mem(pos__b),), pos__c[3][2]))]
continue
if pos__a[0] == '!PyDict_New' and pos__b[0] == 'STORE_MAP':
if len(pos__a) == 1:
cmds[i] = ('!BUILD_MAP', (pos__b[1:],))
del cmds[i+1]
continue
if pos__a[0] == '!BUILD_MAP' and pos__b[0] == 'STORE_MAP':
cmds[i] = ('!BUILD_MAP', pos__a[1] + (pos__b[1:],))
del cmds[i+1]
continue
if pos__a[0] == 'BUILD_MAP':
if pos__a[1] == 0 and len(pos__a) == 2:
cmds[i] = ('!PyDict_New',)
continue
if pos__a[1] > 0 and len(pos__a) == 2:
cmds[i] = ('BUILD_MAP', pos__a[1], ())
continue
if pos__a[1] > 0 and len(pos__a) == 3 and pos__b[0] == 'STORE_MAP':
cmds[i:i+2] = [('BUILD_MAP', pos__a[1]-1, pos__a[2] + ((pos__b[1], pos__b[2]),))]
continue
if pos__a[1] == 0 and len(pos__a) == 3 :
cmds[i] = ('!BUILD_MAP', pos__a[2])
continue
if pos__a[1] > 0 and len(pos__a) == 3 and pos__b[0] == '.L':
cmds[i:i+2] = [pos__a]
continue
if pos__a[0] == 'YIELD_VALUE' and len(pos__a) == 2 and pos__b[0] == 'POP_TOP':
cmds[i:i+2] = [('YIELD_STMT', pos__a[1])]
continue
if pos__a[0] == 'LOAD_LOCALS' and pos__b[0] == 'RETURN_VALUE' and len(pos__b) == 1:
cmds[i:i+2] = [(pos__b[0], ('f->f_locals',))]
continue
if pos__a[0] == 'RAISE_VARARGS' and pos__a[1] == 0 and pos__b[0] == 'POP_TOP':
cmds[i:i+2] = [('RAISE_VARARGS_STMT',) + pos__a[1:]]
continue
if pos__a[0] == '.:':
if CountJumpCache(pos__a[1], cmds) == 0:
del cmds[i]
continue
if pos__b[0] == 'J_LOOP_VARS' and pos__c[0] == 'JUMP_IF2_FALSE_POP_CONTINUE' and\
pos__c[1] == pos__a[1] and isretblock(pos__d) and pos__e[0] == '.:' and pos__b[1] == pos__e[1]:
cmds[i:i+5] = [pos__a,pos__b,[('(IF',) + pos__c[2:], pos__d, (')ENDIF',)],('JUMP_CONTINUE', pos__a[1]),pos__e]
continue
if pos__b[0] == 'J_LOOP_VARS' and pos__c[0] == 'JUMP_IF2_FALSE_POP_CONTINUE' and\
pos__c[1] == pos__a[1] and isblock(pos__d) and pos__e[0] == '.:' and pos__b[1] == pos__e[1]:
cmds[i:i+5] = [pos__a,pos__b,[('(IF',) + pos__c[2:], pos__d, (')(ELSE',), [('CONTINUE',)],(')ENDIF',)],pos__e]
continue
if pos__b[0] == '.:':
for iii in range(len(cmds)):
if cmds[iii][0][0] == 'J' and cmds[iii][1] == pos__a[1]:
li = list(cmds[iii])
li[1] = pos__b[1]
cmds[iii] = tuple(li)
del cmds[i]
continue
if pos__a[0] == 'DUP_TOP' and is_cmdmem(pos__b) and \
len(pos__c) == 2 and pos__c[0] == 'COMPARE_OP' and pos__c[1] == 'exception match':
cmds[i:i+3] = [('CHECK_EXCEPTION', cmd2mem(pos__b))]
continue
if pos__a[0] == 'CHECK_EXCEPTION':
if pos__b[0] == 'JUMP_IF_FALSE_POP' and\
pos__c[0] == 'POP_TOP3' :
cmds[i:i+3] = [('JUMP_IF_NOT_EXCEPTION_POP', pos__b[1], pos__a[1:],())]
continue
if pos__b[0] == 'JUMP_IF_FALSE_POP' and\
pos__c[0] == 'POP_TOP' and pos__d[0] in set_any and\
pos__e[0] == 'POP_TOP':
cmds[i:i+5] = [('JUMP_IF_NOT_EXCEPTION_POP', pos__b[1], pos__a[1:], (pos__d,))]
continue
if pos__b[0] == 'JUMP_IF_FALSE_POP' and\
pos__c[0] == 'POP_TOP' and pos__d[0] in ('UNPACK_SEQ_AND_STORE',) and pos__d[1] == 0 and\
pos__e[0] == 'POP_TOP':
cmds[i:i+5] = [('JUMP_IF_NOT_EXCEPTION_POP', pos__b[1], pos__a[1:], pos__d[:])]
continue
if pos__a[0] == 'POP_TOP' and pos__b[0] == 'POP_TOP' and pos__c[0] == 'POP_TOP':
cmds[i:i+3] = [('POP_TOP3',)]
continue
if pos__a[0] == '!GET_ITER':
if pos__b[0] == '.:' and\
pos__c[0] == 'J_LOOP_VARS' and\
pos__d[0] in ('JUMP_IF2_FALSE_POP', 'JUMP_IF2_FALSE_POP_CONTINUE') and\
pos__e[0] == 'PyList_Append' and \
pos__f[0] in ('JUMP', 'JUMP_CONTINUE') and\
pos__g[0] == '.:'and\
pos__h[0] == ')END_LIST_COMPR':
cmds[i:i+8] = [('BASE_LIST_COMPR', pos__e[2:], (pos__c[2], pos__a[1:], (pos__d[2],))),pos__g,pos__h] # vars in for, iter in fors, condidion
continue
if pos__b[0] == '.:' and\
pos__c[0] == 'J_LOOP_VARS' and\
pos__d[0] in ('JUMP_IF2_TRUE_POP', 'JUMP_IF2_TRUE_POP_CONTINUE') and\
pos__e[0] == 'PyList_Append' and \
pos__f[0] in ('JUMP', 'JUMP_CONTINUE') and\
pos__g[0] == '.:'and\
pos__h[0] == ')END_LIST_COMPR':
cmds[i:i+8] = [('BASE_LIST_COMPR', pos__e[2:], (pos__c[2], pos__a[1:], (Not(pos__d[2]),))),pos__g,pos__h] # vars in for, iter in fors, condidion
continue
if pos__b[0] == '.:' and\
pos__c[0] == 'J_LOOP_VARS' and\
pos__d[0] == 'PyList_Append' and \
pos__e[0] in ('JUMP', 'JUMP_CONTINUE') and\
pos__f[0] == '.:'and\
pos__g[0] == ')END_LIST_COMPR':
cmds[i:i+7] = [('BASE_LIST_COMPR', pos__d[2:], (pos__c[2], pos__a[1:], None)),pos__f,pos__g] # vars in for, iter in fors, condidion
continue
if pos__b[0] == '.:' and\
pos__c[0] == 'J_LOOP_VARS' and\
pos__d[0] in ('JUMP_IF2_FALSE_POP', 'JUMP_IF2_FALSE_POP_CONTINUE') and\
pos__e[0] == 'BASE_LIST_COMPR' and\
pos__f[0] == '.:' and \
pos__g[0] == ')END_LIST_COMPR':
cmds[i:i+7] = [('BASE_LIST_COMPR', pos__e[1], (pos__c[2], pos__a[1:], (pos__d[2],)) +pos__e[2]),pos__f,pos__g]
continue
if pos__b[0] == '.:' and\
pos__c[0] == 'J_LOOP_VARS' and\
pos__d[0] == 'JUMP_IF2_TRUE_POP' and\
pos__e[0] == 'BASE_LIST_COMPR' and\
pos__f[0] == '.:' and \
pos__g[0] == ')END_LIST_COMPR':
cmds[i:i+7] = [('BASE_LIST_COMPR', pos__e[1], (pos__c[2], pos__a[1:], (pos__d[2],)) +pos__e[2]),pos__f,pos__g]
continue
if pos__b[0] == '.:' and\
pos__c[0] == 'J_LOOP_VARS' and\
pos__d[0] == 'BASE_LIST_COMPR' and\
pos__e[0] == '.:' and \
pos__f[0] == ')END_LIST_COMPR':
cmds[i:i+6] = [('BASE_LIST_COMPR', pos__d[1], (pos__c[2], pos__a[1:], None) +pos__d[2]),pos__e,pos__f]
continue
if pos__b[0] == '.:' and\
pos__c[0] == 'J_LOOP_VARS' and\
pos__d[0] == '.L' and\
pos__e[0] == 'BASE_LIST_COMPR' and\
pos__f[0] == '.:' and \
pos__g[0] == ')END_LIST_COMPR':
cmds[i:i+7] = [('BASE_LIST_COMPR', pos__e[1], (pos__c[2], pos__a[1:], None) +pos__e[2]),pos__f,pos__g]
continue
if pos__a[0] == '(BEGIN_LIST_COMPR':
if pos__b[0] == '.L' and pos__c[0] == 'BASE_LIST_COMPR' and pos__d[0] == ')END_LIST_COMPR':
cmds[i:i+4] = [('!LIST_COMPR', pos__c[1], pos__c[2])]
continue
if pos__b[0] == 'BASE_LIST_COMPR' and pos__c[0] == ')END_LIST_COMPR':
cmds[i:i+3] = [('!LIST_COMPR', pos__b[1], pos__b[2])]
continue
if pos__a[0] == 'RAISE_VARARGS' and pos__a[1] == 0 and pos__b[0] == 'POP_TOP':
cmds[i:i+2] = [('RAISE_VARARGS_STMT',) + pos__a[1:]]
continue
if type(pos__a) is list and isblock(pos__a):
if pos__b[0] == 'JUMP_IF2_TRUE_POP_CONTINUE' and islineblock(pos__c):
if type(pos__c) is tuple:
cmds[i:i+3] = [pos__a+[('(IF',) + pos__b[2:], [pos__c,('CONTINUE',)], (')ENDIF',)]]
continue
if type(pos__c) is list:
cmds[i:i+3] = [pos__a+[('(IF',) + pos__b[2:], pos__c+[('CONTINUE',)], (')ENDIF',)]]
continue
if pos__b[0] == 'JUMP_IF2_FALSE_POP_CONTINUE' and isretblock(pos__c):
cmds[i:i+3] = [pos__a+[('(IF',) + pos__b[2:], pos__c, (')ENDIF',)], ('JUMP_CONTINUE', pos__b[1])]
continue
if type(pos__a) is tuple and len(pos__a) >= 1:
if pos__a[0] == '3CMP_BEG_3':
if SCmp(cmds,i, ('3CMP_BEG_3', 'JUMP_IF_FALSE', 'POP_TOP', \
'>', 'COMPARE_OP', 'JUMP', (':', 1,1), \
'ROT_TWO', 'POP_TOP', ('::', 5))):
rpl(cmds, [New_3Cmp(('!3CMP',) + pos__a[1:] + (pos__e[1],) + (cmd2mem(pos__d),))])
continue
if SCmp(cmds,i, ('3CMP_BEG_3', 'JUMP_IF_FALSE', \
'POP_TOP', '>', 'DUP_TOP', 'ROT_THREE', 'COMPARE_OP', \
'JUMP_IF_FALSE')) and pos__b[1] == pos__h[1]:
rpl(cmds, [('J_NCMP', pos__h[1]) + pos__a[1:] + (pos__g[1], cmd2mem(pos__d))])
continue
if SCmp(cmds,i, ('3CMP_BEG_3', 'JUMP_IF_FALSE', 'POP_TOP', \
'>', 'COMPARE_OP', 'RETURN_VALUE', (':', 1,1), \
'ROT_TWO', 'POP_TOP', 'RETURN_VALUE')):
rpl(cmds, [('RETURN_VALUE',New_3Cmp(('!3CMP',) + pos__a[1:] + (pos__e[1],) + (cmd2mem(pos__d),)))])
continue
if pos__a[0] == 'J_NCMP':
if SCmp(cmds,i, ('J_NCMP', \
'POP_TOP', '>', 'DUP_TOP', 'ROT_THREE', 'COMPARE_OP', \
'JUMP_IF_FALSE')) and pos__a[1] == pos__g[1]:
rpl(cmds, [pos__a + (pos__f[1], cmd2mem(pos__c))])
continue
if SCmp(cmds,i, ('J_NCMP', \
'POP_TOP', '.L', '>', 'DUP_TOP', 'ROT_THREE', 'COMPARE_OP', \
'JUMP_IF_FALSE')) and pos__a[1] == pos__h[1]:
rpl(cmds, [pos__a + (pos__g[1], cmd2mem(pos__d))])
continue
if SCmp(cmds,i, ('J_NCMP', 'POP_TOP', \
'>', 'COMPARE_OP', 'JUMP', (':', 0,1), \
'ROT_TWO', 'POP_TOP', ('::', 4))): # 1
rpl(cmds, [New_NCmp(pos__a[2:] + (pos__d[1], cmd2mem(pos__c)))])
continue
if SCmp(cmds,i, ('J_NCMP', 'POP_TOP', \
'.L', '>', 'COMPARE_OP', 'JUMP', (':', 0,1), \
'ROT_TWO', 'POP_TOP', ('::', 5))): # 1
rpl(cmds, [New_NCmp(pos__a[2:] + (pos__e[1], cmd2mem(pos__d)))])
continue
if SCmp(cmds,i, ('J_NCMP', 'POP_TOP', \
'>', 'COMPARE_OP', 'RETURN_VALUE', (':', 0,1), \
'ROT_TWO', 'POP_TOP', 'RETURN_VALUE')):
rpl(cmds, [('RETURN_VALUE', New_NCmp(pos__a[2:] + (pos__d[1], cmd2mem(pos__c))))])
continue
if SCmp(cmds,i, ('J_NCMP', 'POP_TOP', \
'.L', '>', 'COMPARE_OP', 'RETURN_VALUE', (':', 0,1), \
'ROT_TWO', 'POP_TOP', 'RETURN_VALUE')):
rpl(cmds, [('RETURN_VALUE', New_NCmp(pos__a[2:] + (pos__e[1], cmd2mem(pos__d))))])
continue
if pos__a[0] == 'LOAD_CODEFUNC' and SCmp(cmds,i, ('LOAD_CODEFUNC', 'MAKE_FUNCTION', '!GET_ITER', 'CALL_FUNCTION_1')) and\
pos__b[1] == 0 and pos__d[1] == 1:
cmds[i:i+4] = [('!GENERATOR_EXPR_NOCLOSURE',) + pos__a[1:] + (pos__c[1],)]
continue
if pos__a[0] == '!MK_CLOSURE':
if pos__b[0] == 'GET_ITER' and\
pos__c[0] == 'CALL_FUNCTION_1' and pos__c[1] == 1:
cmds[i:i+3] = [('!GENERATOR_EXPR',) + pos__a[1:] + (pos__b[1],)]
continue
if pos__b[0] == '.L':
cmds[i:i+2] = [pos__a]
continue
if pos__a[0] == 'MAKE_CLOSURE' and pos__b[0] == '.L':
cmds[i:i+2] = [pos__a]
continue
if pos__a[0] == 'LOAD_CONST':
changed_load_const = process_load_const(cmds,i, added_pass)
if changed_load_const:
continue
if pos__a[0] == 'J_SETUP_FINALLY':
changed_j_setup_fin = process_j_setup_finally(cmds,i, added_pass)
if changed_j_setup_fin:
process_after_try_detect(cmds,i)
continue
if pos__a[0] == 'J_BEGIN_WITH':
changed_j_with = process_j_begin_with(cmds,i, added_pass)
if changed_j_with:
continue
if pos__a[0] == 'J_SETUP_LOOP':
changed_loop = process_j_setup_loop(cmds,i, added_pass)
if changed_loop:
continue
if pos__a[0] == 'J_SETUP_LOOP_FOR':
changed_loopfor = process_j_setup_loop_for(cmds,i)
if changed_loopfor:
continue
if pos__a[0] == '(BEGIN_TRY':
changed_exc = process_begin_try(cmds,i)
if changed_exc:
process_after_try_detect(cmds,i)
continue
if pos__a[0] == 'J_SETUP_EXCEPT':
changed_exc = process_setup_except(cmds,i)
if changed_exc:
process_after_try_detect(cmds,i)
continue
if pos__a[0] in ('JUMP_IF_NOT_EXCEPTION_POP', 'POP_TOP3'):
changed_exc = process_except_clause(cmds,i)
if changed_exc:
continue
if is_cmdmem(pos__a):
if is_cmdmem(pos__b):
changed_push = process_push2(cmds,i, added_pass)
if changed_push:
continue
else:
changed_push = process_push(cmds,i, added_pass)
if changed_push:
continue
if pos__a[0] == 'SEQ_ASSIGN_0':
if SCmp(cmds,i, ('SEQ_ASSIGN_0', '=')) and pos__a[1] > 0:
rpl(cmds,[('SEQ_ASSIGN_0', pos__a[1]-1, pos__a[2] + (pos__b,), pos__a[3])])
continue
if SCmp(cmds,i, ('SEQ_ASSIGN_0', 'DUP_TOP')):
rpl(cmds,[('SEQ_ASSIGN_0', pos__a[1]+1, pos__a[2], pos__a[3])])
continue
if pos__a[1] == 0:
assert len(pos__a) == 4
cmds[i] = ('SEQ_ASSIGN', pos__a[2], pos__a[3])
continue
if pos__c[0] == 'ROT_TWO':
if pos__a[0] == 'LOAD_FAST' and SCmp(cmds,i, ('LOAD_FAST', '>', 'ROT_TWO')):
rpl(cmds,[pos__b[:], pos__a[:]])
continue
if pos__a[0] == 'LOAD_NAME' and SCmp(cmds,i, ('LOAD_NAME', '>', 'ROT_TWO')):
rpl(cmds,[pos__b[:], pos__a[:]])
continue
if pos__b[0] == 'J_LOOP_VARS' and pos__a[0] == '.:':
if SCmp(cmds,i, ((':', 3,0), 'J_LOOP_VARS', '*n', 'xJUMP_IF2_FALSE_POP_CONTINUE', '*')):
rpl(cmds,[pos__a,pos__b,pos__c+[('(IF', Not(pos__d[2])), [('CONTINUE',)], (')ENDIF',)]+pos__e])
continue
if SCmp(cmds,i, ((':', 3,0), 'J_LOOP_VARS', '*n', 'xJUMP_IF2_FALSE_POP_CONTINUE', '*l')):
if type(pos__e) is tuple:
rpl(cmds,[pos__a,pos__b,pos__c+[('(IF', Not(pos__d[2])), [('CONTINUE',)], (')ENDIF',)],pos__e])
else:
rpl(cmds,[pos__a,pos__b,pos__c+[('(IF', Not(pos__d[2])), [('CONTINUE',)], (')ENDIF',)]+pos__e])
continue
if SCmp(cmds,i, ((':', 3,0), 'J_LOOP_VARS', '*n', 'xJUMP_IF2_FALSE_POP_CONTINUE')):
rpl(cmds,[pos__a,pos__b,pos__c+[('(IF', Not(pos__d[2])), [('CONTINUE',)], (')ENDIF',)]])
continue
if added_pass:
if pos__a[0] == 'JUMP' and type(pos__b) is tuple and \
pos__b[0] not in ('.:', 'POP_BLOCK', 'END_FINALLY', None, '^^'):
del cmds[i+1]
continue
if pos__a[0] == 'RETURN_VALUE' and type(pos__b) is tuple and \
pos__b[0] not in ('.:', 'POP_BLOCK', 'END_FINALLY', None, '^^'):
del cmds[i+1]
continue
if pos__a[0] == '(BEGIN_DEF':
if len(cmds) > 2 and SCmp(cmds,i, ('(BEGIN_DEF', '*r')):
del cmds[2:]
continue
if pos__a[0] == 'J_COND_PUSH':
if SCmp(cmds,i, ('J_COND_PUSH', 'J_COND_PUSH')) and pos__a[1] == pos__b[1]:
rpl(cmds,[pos__a[:] + pos__b[2:]])
continue
if SCmp(cmds,i, ('J_COND_PUSH', '>', ('::', 0))):
rpl(cmds,[('!COND_EXPR',) + pos__a[2:] + (cmd2mem(pos__b),)])
continue
i = i + 1
if len(cmds) > 2:
print (filename + ":Can't decompile " + cmds[0][1] + ' ' + str( co.co_firstlineno))
N2C(cmds[0][1]).decompile_fail = True
else:
N2C(cmds[0][1]).decompile_fail = False
return cmds
def process_list_compr_2(cmds,i,added_pass):
if SCmp(cmds, i, (('!BUILD_LIST', ()), '!GET_ITER', (':', 5, 1),\
'J_LOOP_VARS', '!GET_ITER', 'J_BASE_LIST_COMPR', \
('::', 3))):
if pos__f[3][2] == ():
rpl(cmds, [('!LIST_COMPR', pos__f[2], (pos__d[2], (pos__b[1],), None, pos__f[3][0], (pos__e[1],), None))])
return True
else:
rpl(cmds, [('!LIST_COMPR', pos__f[2], (pos__d[2], (pos__b[1],), None, pos__f[3][0], (pos__e[1],), pos__f[3][2]))])
return True
if SCmp(cmds, i, (('!BUILD_LIST', ()), \
'!GET_ITER', (':', 6, 1), 'J_LOOP_VARS', \
'!GET_ITER', (':', 8, 1), 'J_LOOP_VARS', \
'!GET_ITER', 'J_BASE_LIST_COMPR', ('::', 3))):
if pos__i[3][2] == ():
rpl(cmds, [('!LIST_COMPR', pos__i[2], (pos__d[2], (pos__b[1],), None, pos__g[2], (pos__e[1],), None, pos__i[3][0], (pos__h[1],), None))])
return True
else:
rpl(cmds, [('!LIST_COMPR', pos__i[2], (pos__d[2], (pos__b[1],), None, pos__g[2], (pos__e[1],), None, pos__i[3][0], (pos__h[1],), pos__i[3][2]))])
return True
if SCmp(cmds, i, (('!BUILD_LIST', ()), '!GET_ITER', (':', (4,6)),\
'J_LOOP_VARS', 'JUMP_IF2_TRUE_POP','!GET_ITER', \
'J_BASE_LIST_COMPR', ('::', 3))):
if pos__g[3][2] == ():
rpl(cmds, [('!LIST_COMPR', pos__g[2], (pos__d[2], (pos__b[1],), (Not(pos__e[2]),), pos__g[3][0], (pos__f[1],), None))])
return True
else:
rpl(cmds, [('!LIST_COMPR', pos__g[2], (pos__d[2], (pos__b[1],), (Not(pos__e[2]),), pos__g[3][0], (pos__f[1],), pos__g[3][2]))])
return True
if SCmp(cmds, i, (('!BUILD_LIST', ()), '!GET_ITER', (':', (4,6)),\
'J_LOOP_VARS', 'JUMP_IF2_FALSE_POP','!GET_ITER', \
'J_BASE_LIST_COMPR', ('::', 3))):
if pos__g[3][2] == ():
rpl(cmds, [('!LIST_COMPR', pos__g[2], (pos__d[2], (pos__b[1],), (pos__e[2],), pos__g[3][0], (pos__f[1],), None))])
return True
else:
rpl(cmds, [('!LIST_COMPR', pos__g[2], (pos__d[2], (pos__b[1],), (pos__e[2],), pos__g[3][0], (pos__f[1],), pos__g[3][2]))])
return True
if SCmp(cmds,i, (('!BUILD_LIST', ()), '!GET_ITER', 'J_BASE_LIST_COMPR', ('::', 2))):
if pos__c[3][1] is None:
if pos__c[3][2] == ():
rpl(cmds, [('!LIST_COMPR', pos__c[2], (pos__c[3][0], (pos__b[1],), None))])
return True
else:
rpl(cmds, [('!LIST_COMPR', pos__c[2], (pos__c[3][0], (pos__b[1],), pos__c[3][2]))])
return True
if SCmp(cmds,i, (('!BUILD_LIST', ()), '!GET_ITER', (':', 6,1), \
'J_LOOP_VARS', '>', ('LIST_APPEND', 2), 'JUMP', \
('::', 3))):
rpl(cmds, [('!LIST_COMPR', (cmd2mem(pos__e),), (pos__d[2], (pos__b[1],), None))] )
return True
if SCmp(cmds,i, (('!BUILD_LIST', ()), '!GET_ITER', (':', 6,1), \
'J_LOOP_VARS', '>', ('LIST_APPEND', 2), 'JUMP_CONTINUE', \
('::', 3))):
rpl(cmds, [('!LIST_COMPR', (cmd2mem(pos__e),), (pos__d[2], (pos__b[1],), None))] )
return True
if SCmp(cmds,i, (('!BUILD_LIST', ()), '!GET_ITER', (':', (4, 7)),\
'J_LOOP_VARS', 'JUMP_IF2_FALSE_POP', \
'>', ('LIST_APPEND', 2), 'JUMP',\
('::', 3))):
rpl(cmds, [('!LIST_COMPR', (cmd2mem(pos__f),), (pos__d[2], (pos__b[1],), (pos__e[2],)))] )
return True
if SCmp(cmds,i, (('!BUILD_LIST', ()), '!GET_ITER', (':', (4, 7)),\
'J_LOOP_VARS', 'JUMP_IF2_FALSE_POP', \
'>', ('LIST_APPEND', 2), 'JUMP_CONTINUE',\
('::', 3))):
rpl(cmds, [('!LIST_COMPR', (cmd2mem(pos__f),), (pos__d[2], (pos__b[1],), (pos__e[2],)))] )
return True
if SCmp(cmds,i, (('!BUILD_LIST', ()), '!GET_ITER', (':', (4, 7)),\
'J_LOOP_VARS', 'JUMP_IF2_FALSE_POP_CONTINUE', \
'>', ('LIST_APPEND', 2), 'JUMP_CONTINUE',\
('::', 3))):
rpl(cmds, [('!LIST_COMPR', (cmd2mem(pos__f),), (pos__d[2], (pos__b[1],), (pos__e[2],)))] )
return True
if SCmp(cmds,i, (('!BUILD_LIST', ()), '!GET_ITER', (':', (4, 7)),\
'J_LOOP_VARS', 'JUMP_IF2_TRUE_POP', \
'>', ('LIST_APPEND', 2), 'JUMP',\
('::', 3))):
rpl(cmds, [('!LIST_COMPR', (cmd2mem(pos__f),), (pos__d[2], (pos__b[1],), (Not(pos__e[2]),)))] )
return True
if SCmp(cmds,i, (('!BUILD_LIST', ()), '!GET_ITER', (':', (4, 7)),\
'J_LOOP_VARS', 'JUMP_IF2_TRUE_POP', \
'>', ('LIST_APPEND', 2), 'JUMP_CONTINUE',\
('::', 3))):
rpl(cmds, [('!LIST_COMPR', (cmd2mem(pos__f),), (pos__d[2], (pos__b[1],), (Not(pos__e[2]),)))] )
return True
if SCmp(cmds,i, (('!BUILD_LIST', ()), '!GET_ITER', (':', (4, 7)),\
'J_LOOP_VARS', 'JUMP_IF2_TRUE_POP_CONTINUE', \
'>', ('LIST_APPEND', 2), 'JUMP_CONTINUE',\
('::', 3))):
rpl(cmds, [('!LIST_COMPR', (cmd2mem(pos__f),), (pos__d[2], (pos__b[1],), (Not(pos__e[2]),)))] )
return True
return False
def process_push(cmds,i,added_pass):
aa = cmd2mem(pos__a)
if SCmp(cmds,i, ('LOAD_FAST', (':', 4, 1), 'J_LOOP_VARS', '*', 'JUMP', (':', 2, 1))):
rpl(cmds,[[('(FOR_DIRECT_ITER', aa, pos__c[2]), pos__d, (')FOR_DIRECT_ITER',)]])
return True
if SCmp(cmds,i, ('LOAD_FAST', (':', 5, 1), 'J_LOOP_VARS', '!GET_ITER', (':', 7, 1), \
'J_LOOP_VARS', '*', 'JUMP', (':', 2, 1))):
rpl(cmds,[[('(FOR_DIRECT_ITER2', aa, pos__c[2], pos__d[1]), pos__g, (')FOR_DIRECT_ITER2',)]])
return True
if SCmp(cmds,i, ('>', ('BUILD_LIST_FROM_ARG', 0), 'GET_ITER')):
rpl(cmds,[ ('BUILD_LIST', 0), aa, pos__c])
return True
if SCmp(cmds,i, ('>', 'J_SETUP_WITH', 'POP_TOP')):
rpl(cmds,[('J_BEGIN_WITH', pos__b[1], aa, ())])
return True
if SCmp(cmds,i, ('>', 'J_SETUP_WITH', '=')):
rpl(cmds,[('J_BEGIN_WITH', pos__b[1], aa, (pos__c,))])
return True
if SCmp(cmds,i, ('>', 'JUMP_IF_TRUE_OR_POP', '>', (':', 1, 1))):
rpl(cmds,[Or_j_s(pos__a, pos__c)])
return True
if SCmp(cmds,i, ('>', 'JUMP_IF_FALSE_OR_POP', '>', (':', 1, 1))):
rpl(cmds,[And_j_s(pos__a, pos__c)])
return True
if pos__a[0] == '!BUILD_LIST' and len(pos__a[1]) == 0 and pos__b[0] == 'DUP_TOP' and\
pos__c[0] == 'STORE_FAST' and pos__c[1][0:2] == '_[': # and pos__d[0] == 'GET_ITER':
cmds[i:i+3] = [('(BEGIN_LIST_COMPR', ('FAST', pos__c[1]))] #, pos__d[1])]
return True
if pos__a[0] == '!BUILD_LIST' and len(pos__a[1]) == 0 and pos__b[0] == 'DUP_TOP' and\
pos__c[0] == 'STORE_NAME' and pos__c[1][0:2] == '_[':# and pos__d[0] == 'GET_ITER':
cmds[i:i+3] = [('(BEGIN_LIST_COMPR', ('!NAME', pos__c[1]))] #, pos__d[1])]
return True
if pos__a[0] == '!BUILD_TUPLE' and pos__b[0] == 'POP_TOP':
cmds[i:i+2] = [('UNPUSH', aa)]
return True
if pos__b is not None and pos__b[0] == 'DUP_TOP':
if SCmp(cmds,i, ('>', 'DUP_TOP', ('LOAD_ATTR_1', '__exit__'), \
'ROT_TWO', ('LOAD_ATTR_1', '__enter__'), ('CALL_FUNCTION_1', 0),\
'POP_TOP', 'J_SETUP_FINALLY')):
cmds[i:i+8] = [('J_BEGIN_WITH', pos__h[1], aa,())]
return True
if SCmp(cmds,i, ('>', 'DUP_TOP', ('LOAD_ATTR_1', '__exit__'), 'STORE_FAST',\
('LOAD_ATTR_1', '__enter__'), ('CALL_FUNCTION_1', 0), 'POP_TOP', 'J_SETUP_FINALLY')):
cmds[i:i+8] = [('J_BEGIN_WITH', pos__h[1], aa,())]
return True
if SCmp(cmds,i, ('>', 'DUP_TOP', ('LOAD_ATTR_1', '__exit__'), \
'ROT_TWO', ('LOAD_ATTR_1', '__enter__'), \
('CALL_FUNCTION_1', 0), 'STORE_FAST', \
'J_SETUP_FINALLY', 'LOAD_FAST', \
'DELETE_FAST', '=')) and pos__g[1] == pos__i[1] and pos__g[1] == pos__j[1]:
cmds[i:i+11] = [('J_BEGIN_WITH', pos__h[1], aa, (pos__k))]
return True
if SCmp(cmds,i, ('>', 'DUP_TOP', ('LOAD_ATTR_1', '__exit__'), \
'ROT_TWO', ('LOAD_ATTR_1', '__enter__'), ('CALL_FUNCTION_1', 0),\
'STORE_FAST', 'J_SETUP_FINALLY', 'LOAD_FAST', \
')END_LIST_COMPR', '=')) and pos__g[1] == pos__i[1] and pos__g[1] == pos__j[1][1]:
cmds[i:i+11] = [('J_BEGIN_WITH', pos__h[1], aa, (pos__k))]
return True
if (pos__a[0] == '!LOAD_DEREF' or pos__a[0] == '!LOAD_NAME' or pos__a[0] == '!LOAD_GLOBAL' or \
pos__a[0] == '!PyDict_GetItem(glob,' or\
pos__a[0] == 'LOAD_FAST' or pos__a[0] == '!PyObject_GetAttr'):
cmds[i:i+2] = [pos__a[:], pos__a[:]]
return True
if SCmp(cmds,i, ('>', 'DUP_TOP', '=', '=')):
cmds[i:i+4] = [('SET_EXPRS_TO_VARS', (pos__d,pos__c), ('CLONE', aa))]
return True
if SCmp(cmds,i, ('>', 'DUP_TOP', 'UNPACK_SEQ_AND_STORE', '=')) and pos__c[1] == 0:
cmds[i:i+4] = [('SET_EXPRS_TO_VARS', (pos__d,pos__c), ('CLONE', aa))]
return True
if SCmp(cmds,i, ('>', 'DUP_TOP', '>', 'ROT_TWO', \
'PRINT_ITEM_TO_0', 'PRINT_NEWLINE_TO_0')):
cmds[i:i+6] = [('PRINT_ITEM_AND_NEWLINE_TO_2', aa, cmd2mem(pos__c))]
return True
if SCmp(cmds,i, ('>', 'DUP_TOP', '>', 'ROT_TWO', \
'PRINT_ITEM_TO_0',
'DUP_TOP', '>', 'ROT_TWO', 'PRINT_ITEM_TO_0',
'PRINT_NEWLINE_TO_0')):
cmds[i:i+10] = [('PRINT_ITEM_AND_NEWLINE_TO_3', aa, cmd2mem(pos__c), cmd2mem(pos__g))]
return True
if SCmp(cmds,i, ('>', 'DUP_TOP', '>', 'ROT_TWO', 'PRINT_ITEM_TO_0', 'POP_TOP')):
rpl(cmds,[('PRINT_ITEM_TO_2', aa, cmd2mem(pos__c))])
return True
if SCmp(cmds,i, ('>', 'DUP_TOP', 'LOAD_ATTR_1', '>', 'INPLACE_ADD',\
'ROT_TWO', 'STORE_ATTR_1')) and pos__g[1] == pos__c[1]:
rpl(cmds,[('STORE', (('PyObject_SetAttr', aa, ('CONST', pos__g[1])),), \
(('!' + recode_inplace['INPLACE_ADD'], ('!PyObject_GetAttr', aa, ('CONST', pos__c[1])), cmd2mem(pos__d)),))])
return True
if SCmp(cmds,i, ('>', 'DUP_TOP', 'LOAD_ATTR_1', '>', 'INPLACE_MULTIPLY',\
'ROT_TWO', 'STORE_ATTR_1')) and pos__g[1] == pos__c[1]:
rpl(cmds,[('STORE', (('PyObject_SetAttr', aa, ('CONST', pos__g[1])),),
(('!' + recode_inplace['INPLACE_MULTIPLY'], ('!PyObject_GetAttr', aa, ('CONST', pos__c[1])), cmd2mem(pos__d)),))])
return True
if SCmp(cmds,i, ('>', 'DUP_TOP', 'STORE_GLOBAL', 'STORE_FAST')):
rpl(cmds,[pos__a, pos__d, ('LOAD_FAST', pos__d[1]), pos__c])
return True
if SCmp(cmds,i, ('>', 'DUP_TOP', 'STORE_FAST', 'STORE_GLOBAL')):
rpl(cmds,[pos__a, pos__c, ('LOAD_FAST', pos__c[1]), pos__d])
return True
if SCmp(cmds,i, ('>', 'DUP_TOP', '=')):
rpl(cmds,[('SEQ_ASSIGN_0', 1, (pos__c,), aa)])
return True
if SCmp(cmds,i, ('>', 'DUP_TOP', 'STORE_FAST')):
rpl(cmds,[pos__a, pos__c, ('LOAD_FAST', pos__c[1])])
return True
## if SCmp(cmds,i, ('>', 'DUP_TOP', ('LOAD_ATTR_1', '__exit__'),\ # By CloneDigger
## 'ROT_TWO', ('LOAD_ATTR_1', '__enter__'), \
## ('CALL_FUNCTION_1', 0), 'STORE_FAST', \
## 'J_SETUP_FINALLY', 'LOAD_FAST', \
## 'DELETE_FAST', '=')) and pos__g[1] == pos__i[1] and pos__g[1] == pos__j[1]:
## cmds[i:i+11] = [('J_BEGIN_WITH', pos__h[1], aa, (pos__k))]
## return True
if SCmp(cmds,i, ('!PyObject_GetAttr', 'STORE', 'J_SETUP_FINALLY', \
'LOAD_FAST', ')END_LIST_COMPR', '=')) and\
pos__a[2][1] == '__exit__' and \
pos__b[1][0][1][:2] == '_[' and \
pos__d[1] == pos__b[1][0][1]:
cmds[i:i+6] = [('J_BEGIN_WITH', pos__c[1], pos__a[1], (pos__f,))]
return True
if SCmp(cmds,i, ('!PyObject_GetAttr', 'STORE', 'J_SETUP_FINALLY', '!LOAD_NAME', \
')END_LIST_COMPR', '=')) and pos__a[2][1] == '__exit__' and pos__d[1] == pos__e[1][1]:
rpl(cmds,[('J_BEGIN_WITH', pos__c[1], pos__a[1], (pos__f))])
return True
if isblock(pos__b) and len(pos__b) == 1 and type(pos__b[0]) is tuple:
cmds[i+1:i+2] = pos__b
return True
if is_cmdmem(pos__c) and pos__b[0] == '.L':
del cmds[i+1]
return True
if pos__c[0] == 'MK_FUNK' and pos__c[2] > 0 and pos__b[0] == '.L':
cmds[i:i+3] = [('MK_FUNK', pos__c[1], pos__c[2]-1, (aa,)+pos__c[3])]
return True
if pos__b[0] == 'MK_FUNK' and pos__b[2] > 0:
cmds[i:i+2] = [('MK_FUNK', pos__b[1], pos__b[2]-1, (aa,)+pos__b[3])]
return True
if pos__b[0] == 'LOAD_CODEFUNC' and pos__c[0] == 'MAKE_CLOSURE':
cmds[i:i+3] = [('MK_CLOSURE', pos__b[1], pos__c[1], aa, ())]
return True
if pos__b[0] == 'MK_CLOSURE' and pos__b[2] > 0:
cmds[i:i+2] = [('MK_CLOSURE', pos__b[1], pos__b[2]-1, pos__b[3], (aa,)+pos__b[4])]
return True
if SCmp(cmds,i, ('>', 'JUMP', '>', (':', 1, 1))):
cmds[i:i+4] = [pos__a[:]]
return True
if SCmp(cmds,i, ('>', 'JUMP', '>', (':', 1, 2))):
cmds[i:i+4] = [pos__a[:], pos__d[:]]
return True
if pos__b[0] == 'PRINT_ITEM_TO_2' and \
pos__c[0] == 'DUP_TOP':
cmds[i:i+3] = [pos__b[:], pos__a, pos__c]
return True
if pos__b[0] == 'PRINT_ITEM_TO_2' and \
pos__c[0] == 'PRINT_NEWLINE_TO_0':
cmds[i:i+3] = [pos__b[:], ('PRINT_NEWLINE_TO_1', aa)]
return True
if pos__b[0] == 'PRINT_NEWLINE_TO_0':
cmds[i:i+2] = [('PRINT_NEWLINE_TO_1', aa)]
return True
if is_cmdmem(pos__c) and pos__b[0] == '.L':
cmds[i:i+3] = pos__b, pos__a, pos__c
return True
if pos__b[0] == 'STORE_ATTR_1':
cmds[i:i+2] = [('PyObject_SetAttr', aa, ('CONST', pos__b[1]))]
return True
if pos__b[0] in set_any:
cmds[i:i+2] = [('STORE',(pos__b,), (aa,))]
return True
if pos__b[0] == 'PRINT_ITEM_0':
cmds[i:i+2] = [('PRINT_ITEM_1',) + (aa,)]
return True
if ( pos__b[0] in ('JUMP_IF_FALSE_POP_BREAK','JUMP_IF_FALSE_POP_CONTINUE',\
'JUMP_IF_TRUE_POP_BREAK','JUMP_IF_TRUE_POP_CONTINUE',\
'JUMP_IF_FALSE_POP', 'JUMP_IF_TRUE_POP') and len(pos__b) == 2 ):
bb = 'JUMP_IF2_' + pos__b[0][8:]
cmds[i:i+2] = [(bb, pos__b[1], aa)]
return True
if pos__b[0] == 'RETURN_VALUE' and len(pos__b) == 1:
cmds[i:i+2] = [pos__b + (aa,)]
return True
if pos__b[0] == 'IMPORT_STAR' and len(pos__b) == 1 and pos__a[0] == '!IMPORT_NAME':
cmds[i:i+2] = make_import_star(aa)
return True
if pos__b[0] == 'IMPORT_STAR' and len(pos__b) == 1:
cmds[i:i+2] = [pos__b + (aa,)]
return True
if pos__b[0] == 'GET_ITER' and len( pos__b) == 1 :
cmds[i:i+2] = [('!GET_ITER',) + (aa,)]
return True
if pos__b[0] == 'BUILD_LIST' and pos__b[1] > 0:
if len(pos__b) == 2:
b_ = (pos__b[0], pos__b[1], ())
else:
b_ = pos__b
cmds[i:i+2] = [('BUILD_LIST', b_[1] - 1, (aa,) + b_[2])]
return True
if pos__b[0] == 'BUILD_TUPLE' and pos__b[1] > 0:
if len(pos__b) == 2:
b_ = (pos__b[0], pos__b[1], ())
else:
b_ = pos__b
cmds[i:i+2] = [('BUILD_TUPLE', b_[1] - 1, (aa,) + b_[2])]
return True
if pos__b[0] == 'BUILD_SET' and pos__b[1] > 0:
if len(pos__b) == 2:
b_ = (pos__b[0], pos__b[1], ())
else:
b_ = pos__b
cmds[i:i+2] = [('BUILD_SET', b_[1] - 1, (aa,) + b_[2])]
return True
if pos__b[0] == 'LOAD_ATTR_1':
cmds[i:i+2] = [('!PyObject_GetAttr', aa, ('CONST', pos__b[1]))]
return True
if pos__b[0] == 'SLICE+0' and len(pos__b) == 1:
cmds[i:i+2] = [('!PySequence_GetSlice', aa, 0, 'PY_SSIZE_T_MAX')]
return True
if pos__b[0] == 'YIELD_VALUE' and len(pos__b) == 1 and pos__c[0] == 'POP_TOP':
cmds[i:i+3] = [('YIELD_STMT', aa)]
return True
if pos__b[0] == 'YIELD_VALUE' and len(pos__b) == 1:
cmds[i:i+2] = [('!YIELD_VALUE', aa)]
return True
if pos__b[0] == 'RAISE_VARARGS':
if len(pos__b) == 2 and pos__b[1] == 1 and pos__c[0] == 'POP_TOP':
cmds[i:i+3] = [('RAISE_VARARGS_STMT', 0, (aa,))]
return True
if len(pos__b) == 3 and pos__b[1] == 1 and pos__c[0] == 'POP_TOP':
cmds[i:i+3] = [('RAISE_VARARGS_STMT', 0, (aa,)+ pos__b[2])]
return True
if len(pos__b) == 2 and pos__b[1] == 1:
cmds[i:i+2] = [('RAISE_VARARGS', 0, (aa,))]
return True
if len(pos__b) == 2 and pos__b[1] >= 1:
cmds[i:i+2] = [('RAISE_VARARGS', pos__b[1]-1, (aa,))]
return True
if len(pos__b) == 3 and pos__b[1] >= 1:
cmds[i:i+2] = [('RAISE_VARARGS', pos__b[1]-1, (aa,) + pos__b[2])]
return True
if pos__b[0] in recode_unary:
cmds[i:i+2] = [('!' +recode_unary[pos__b[0]], aa)]
return True
if pos__b[0] == 'UNARY_NOT':
cmds[i:i+2] = [Not(aa)]
return True
if pos__b[0][:6] == 'UNARY_':
cmds[i:i+2] = [('!1' + pos__b[0][6:], aa)]
return True
if pos__b[0] == 'DELETE_SLICE+0' and len(pos__b) == 1:
cmds[i:i+2] = [('DELETE_SLICE+0', aa)]
return True
if SCmp(cmds,i, ('>', 'CALL_FUNCTION_1')) and pos__b[1] > 0:
cmds[i:i+2] = [(pos__b[0], pos__b[1]-1, (aa,) + pos__b[2], pos__b[3], pos__b[4])]
return True
if SCmp(cmds,i, ('>', 'CALL_FUNCTION_1')) and pos__b[1] == 0 and pos__b[3] == 0:
if len(pos__b[4]) == 0:
# must be after type dectection
if pos__a[0] =='!LOAD_BUILTIN':
cm = attempt_direct_builtin(pos__a[1],pos__b[2], TupleFromArgs(pos__b[2]))
if cm is not None:
cmds[i:i+2] = [cm]
return True
if len(pos__b[2]) == 0:
cmds[i:i+2] = [('!PyObject_Call', aa, ('CONST',()), ('NULL',))]
return True
cmds[i:i+2] = [('!PyObject_Call', aa, TupleFromArgs(pos__b[2]), ('NULL',))]
return True
else:
if len(pos__b[2]) == 0:
cmds[i:i+2] = [('!PyObject_Call', aa, ('CONST',()), DictFromArgs(pos__b[4]))]
return True
cmds[i:i+2] = [('!PyObject_Call', aa, TupleFromArgs(pos__b[2]), DictFromArgs(pos__b[4]))]
return True
if SCmp(cmds,i, ('>', 'CALL_FUNCTION_KW')):
cmds[i:i+2] = [('CALL_FUNCTION_KW_1',) + pos__b[1:] + (aa,)]
return True
if SCmp(cmds,i, ('>', 'CALL_FUNCTION_KW_1')) and pos__b[1] > 0:
cmds[i:i+2] = [(pos__b[0], pos__b[1]-1, (aa,) + pos__b[2], pos__b[3], pos__b[4], pos__b[5])]
return True
if SCmp(cmds,i, ('>', 'CALL_FUNCTION_KW_1')) and pos__b[1] == 0 and pos__b[3] == 0:
if len(pos__b[4]) == 0:
cmds[i:i+2] = [('!PyObject_Call', aa, TupleFromArgs(pos__b[2]), pos__b[5])]
return True
else:
cmds[i:i+2] = [('!PyObject_Call', aa, TupleFromArgs(pos__b[2]), ('!$PyDict_SymmetricUpdate', DictFromArgs(pos__b[4]), pos__b[5]))]
return True
if SCmp(cmds,i, ('>', 'CALL_FUNCTION_VAR')):
cmds[i:i+2] = [('CALL_FUNCTION_VAR_1',) + pos__b[1:] + (aa,)]
return True
if SCmp(cmds,i, ('>', 'CALL_FUNCTION_VAR_1')) and pos__b[1] > 0:
cmds[i:i+2] = [(pos__b[0], pos__b[1]-1, (aa,) + pos__b[2], pos__b[3], pos__b[4], pos__b[5])]
return True
if SCmp(cmds,i, ('>', 'CALL_FUNCTION_VAR_1')) and pos__b[1] == 0 and pos__b[3] == 0:
if len(pos__b[4]) == 0:
t = TypeExpr(pos__b[5])
if len(pos__b[2]) == 0:
if IsTuple(t):
cmds[i:i+2] = [('!PyObject_Call', aa, pos__b[5], ('NULL',))]
elif IsList(t):
cmds[i:i+2] = [('!PyObject_Call', aa, ('!PyList_AsTuple', pos__b[5]), ('NULL',))]
else:
cmds[i:i+2] = [('!PyObject_Call', aa, ('!PySequence_Tuple', pos__b[5]), ('NULL',))]
return True
if IsTuple(t):
cmds[i:i+2] = [('!PyObject_Call', aa, ('!PyNumber_Add', TupleFromArgs(pos__b[2]), pos__b[5]), ('NULL',))]
elif IsList(t):
cmds[i:i+2] = [('!PyObject_Call', aa, ('!PyNumber_Add', TupleFromArgs(pos__b[2]), ('!PyList_AsTuple', pos__b[5])), ('NULL',))]
else:
cmds[i:i+2] = [('!PyObject_Call', aa, ('!PyNumber_Add', TupleFromArgs(pos__b[2]), ('!PySequence_Tuple', pos__b[5])), ('NULL',))]
return True
else:
t = TypeExpr(pos__b[5])
if len(pos__b[2]) == 0:
if IsTuple(t):
cmds[i:i+2] = [('!PyObject_Call', aa, pos__b[5], DictFromArgs(pos__b[4]))]
elif IsList(t):
cmds[i:i+2] = [('!PyObject_Call', aa, ('!PyList_AsTuple', pos__b[5]), DictFromArgs(pos__b[4]))]
else:
cmds[i:i+2] = [('!PyObject_Call', aa, ('!PySequence_Tuple', pos__b[5]), DictFromArgs(pos__b[4]))]
return True
if IsTuple(t):
cmds[i:i+2] = [('!PyObject_Call', aa, ('!PyNumber_Add', TupleFromArgs(pos__b[2]), pos__b[5]), DictFromArgs(pos__b[4]))]
elif IsList(t):
cmds[i:i+2] = [('!PyObject_Call', aa, ('!PyNumber_Add', TupleFromArgs(pos__b[2]), ('!PyList_AsTuple', pos__b[5])), DictFromArgs(pos__b[4]))]
else:
cmds[i:i+2] = [('!PyObject_Call', aa, ('!PyNumber_Add', TupleFromArgs(pos__b[2]), ('!PySequence_Tuple', pos__b[5])), DictFromArgs(pos__b[4]))]
return True
if SCmp(cmds,i, ('>', 'CALL_FUNCTION_VAR_KW_1')) and pos__b[1] > 0:
cmds[i:i+2] = [(pos__b[0], pos__b[1]-1, (aa,) + pos__b[2], pos__b[3], pos__b[4], pos__b[5],pos__b[6])]
return True
if SCmp(cmds,i, ('>', 'CALL_FUNCTION_VAR_KW_1')) and pos__b[1] == 0 and pos__b[3] == 0:
t = TypeExpr(pos__b[5])
if len(pos__b[4]) == 0 and len(pos__b[2]) == 0:
if IsTuple(t):
cmds[i:i+2] = [('!PyObject_Call', aa, pos__b[5], pos__b[6])]
elif IsList(t):
cmds[i:i+2] = [('!PyObject_Call', aa, ('!PyList_AsTuple', pos__b[5]), pos__b[6])]
else:
cmds[i:i+2] = [('!PyObject_Call', aa, ('!PySequence_Tuple', pos__b[5]), pos__b[6])]
return True
if len(pos__b[2]) > 0:
if IsTuple(t):
tup = ('!PyNumber_Add', TupleFromArgs(pos__b[2]), pos__b[5])
elif IsList(t):
tup = ('!PyNumber_Add', TupleFromArgs(pos__b[2]), ('!PyList_AsTuple',pos__b[5]))
else:
tup = ('!PyNumber_Add', TupleFromArgs(pos__b[2]), ('!PySequence_Tuple',pos__b[5]))
else:
tup = pos__b[5]
if len(pos__b[4]) > 0:
dic = ('!$PyDict_SymmetricUpdate', DictFromArgs(pos__b[4]), pos__b[6])
else:
dic = pos__b[6]
cmds[i:i+2] = [('!PyObject_Call', aa, tup, dic)]
return True
if SCmp(cmds,i, ('>', '.L', 'CALL_FUNCTION_1')):
rpl(cmds,[pos__a,pos__c])
return True
if SCmp(cmds,i, ('>', 'POP_TOP')):
rpl(cmds,[('UNPUSH', aa)])
return True
if SCmp(cmds,i, ('>', 'DELETE_ATTR_1')):
rpl(cmds,[('DELETE_ATTR_2', aa, ('CONST', pos__b[1]))])
return True
if SCmp(cmds,i, ('>', 'STORE_SLICE+0')):
rpl(cmds,[('STORE_SLICE_LV+0', aa)])
return True
if SCmp(cmds,i, ('>', 'BOXING_UNBOXING', 'UNPACK_SEQ_AND_STORE')) and pos__c[1] == 0:
rpl(cmds,[pos__b,pos__a,pos__c])
return True
if SCmp(cmds,i, ('>', 'PRINT_ITEM_TO_2', 'POP_TOP')):
rpl(cmds,[('UNPUSH', aa), pos__b])
return True
if SCmp(cmds,i, ('>', 'SET_VARS')):
rpl(cmds,[('SET_EXPRS_TO_VARS', pos__b[1], aa)])
return True
if SCmp(cmds,i, ('>', 'SET_EXPRS_TO_VARS', '=')):
rpl(cmds,[('SET_EXPRS_TO_VARS', (pos__c,) + pos__b[1], (aa,) + pos__b[2])])
return True
if SCmp(cmds,i, ('>', 'SET_EXPRS_TO_VARS', 'SET_VARS')):
rpl(cmds,[('SET_EXPRS_TO_VARS', (pos__b[1],) + (pos__c[1],), (pos__b[2],) + (aa,))])
return True
if SCmp(cmds,i, ('>', 'STORE', '=')):
if len(pos__b[1]) == len(pos__b[2]) == 1:
rpl(cmds,[('SET_EXPRS_TO_VARS', pos__b[1] + (pos__c,), pos__b[2] + (aa,))])
else:
assert False
## rpl(cmds,[('SET_EXPRS_TO_VARS', (pos__b[1],) + (pos__c,), (pos__b[2],) + (aa,))])
return True
if SCmp(cmds,i, ('>', 'STORE', 'DUP_TOP')) and pos__b[2] == (aa,):
rpl(cmds,[('SEQ_ASSIGN_0', 2, pos__b[1], aa)])
return True
if SCmp(cmds,i, ('>', 'STORE', 'DUP_TOP')) and pos__b[2] == aa:
rpl(cmds,[('SEQ_ASSIGN_0', 2, (pos__b[1],), aa)])
return True
if SCmp(cmds,i, ('!PyDict_New', 'DUP_TOP', '>', 'ROT_TWO', '>', 'STORE_SUBSCR_0')):
rpl(cmds, [('!BUILD_MAP', ((cmd2mem(pos__e), cmd2mem(pos__c)),))])
return True
if SCmp(cmds,i, ('!BUILD_MAP', 'DUP_TOP', '>', 'ROT_TWO', '>', 'STORE_SUBSCR_0')):
rpl(cmds, [('!BUILD_MAP', pos__a[1] + ((cmd2mem(pos__e), cmd2mem(pos__c)),))])
return True
if pos__b is not None and pos__b[0] == 'JUMP_IF_FALSE':
if pos__b[0] == 'JUMP_IF_FALSE' and pos__c[0] == 'POP_TOP' and is_cmdmem(pos__d):
if label(pos__b, pos__e):
if OneJumpCache(pos__e[1], cmds):
cmds[i:i+5] = [And_j_s(aa, pos__d)]
else:
cmds[i:i+5] = [And_j_s(aa, pos__d), pos__e]
return True
if pos__e[0] == 'JUMP_IF_FALSE' and pos__b[1] == pos__e[1] and pos__f[0] == 'POP_TOP':
cmds[i:i+6] = [And_j_s(aa, pos__d),pos__b,pos__c]
return True
if pos__b[0] == 'JUMP_IF_FALSE' and pos__c[0] == 'POP_TOP' and islineblock(pos__d) and\
is_cmdmem(pos__e):
del cmds[i+3]
return True
if SCmp(cmds,i, ('>', 'JUMP_IF_FALSE', 'POP_TOP', '3CMP_BEG_3', \
'JUMP_IF_FALSE', 'POP_TOP', '>', 'COMPARE_OP', \
'RETURN_VALUE', (':', 4,1), 'ROT_TWO', 'POP_TOP',\
(':', 1,1), 'RETURN_VALUE')):
rpl(cmds, [('RETURN_VALUE', And_j_s(pos__a, \
New_3Cmp(('!3CMP', pos__d[1], pos__d[2], pos__d[3], pos__h[1], cmd2mem(pos__g)))))])
return True
if SCmp(cmds,i, ('>', 'JUMP_IF_FALSE', 'POP_TOP',\
'JUMP_IF2_TRUE_POP_CONTINUE', '>', (':', 1,1),\
'JUMP_IF_TRUE_POP_CONTINUE')) and pos__d[1] == pos__g[1]:
rpl(cmds,[And_j_s(pos__a, Or_j_s(pos__d[2],pos__e)),pos__g])
return True
if SCmp(cmds,i, ('>', 'JUMP_IF_FALSE', 'POP_TOP',\
'JUMP_IF2_TRUE_POP', '>', (':', 1,1),\
'JUMP_IF_TRUE_POP')) and pos__d[1] == pos__g[1]:
rpl(cmds,[And_j_s(pos__a, Or_j_s(pos__d[2],pos__e)),pos__g])
return True
if SCmp(cmds,i, ('>', 'JUMP_IF_FALSE', 'POP_TOP', 'JUMP_IF2_FALSE_POP', \
'>', (':', 1,1), 'JUMP_IF_TRUE', 'POP_TOP', (':', 3, 1),\
'>', ('::', 6))):
temp1 = And_j_s(pos__a, pos__d[2])
temp2 = And_j_s(temp1, pos__e)
rpl(cmds,[Or_j_s(temp2, pos__j)])
return True
if SCmp(cmds,i, ('>', 'JUMP_IF_FALSE', 'POP_TOP', '>', 'JUMP')) and pos__b[1] == pos__e[1]:
rpl(cmds, [And_j_s(pos__a, pos__d), pos__e])
return True
if pos__b is not None and pos__b[0] == 'JUMP_IF_TRUE':
if pos__b[0] == 'JUMP_IF_TRUE' and pos__c[0] == 'POP_TOP' and is_cmdmem(pos__d):
if label(pos__b, pos__e):
if OneJumpCache(pos__e[1], cmds):
cmds[i:i+5] = [Or_j_s(aa, pos__d)]
else:
cmds[i:i+5] = [Or_j_s(aa, pos__d), pos__e]
return True
if pos__e[0] == 'JUMP_IF_TRUE' and pos__b[1] == pos__e[1] and pos__f[0] == 'POP_TOP':
cmds[i:i+6] = [Or_j_s(aa, pos__d),pos__b,pos__c]
return True
if SCmp(cmds,i, ('>', 'JUMP_IF_TRUE', 'POP_TOP', '3CMP_BEG_3', \
'JUMP_IF_FALSE', 'POP_TOP', '>', 'COMPARE_OP', \
'RETURN_VALUE', (':', 4,1), 'ROT_TWO', 'POP_TOP',\
(':', 1,1), 'RETURN_VALUE')):
rpl(cmds, [('RETURN_VALUE', Or_j_s(pos__a, \
New_3Cmp(('!3CMP', pos__d[1], pos__d[2], pos__d[3], pos__h[1], cmd2mem(pos__g)))))])
return True
if SCmp(cmds,i, ('>', 'JUMP_IF_TRUE', 'POP_TOP', 'JUMP_IF2_FALSE_POP', \
'>', 'JUMP_IF_TRUE', 'POP_TOP', (':', 3, 1), \
'>', (':', 1, 2))) and pos__b[1] == pos__f[1] and CountJumpCache(pos__j[1],cmds) == 2:
rpl(cmds,[Or_j_s(pos__a, Or_j_s(And_j_s(pos__d[2], pos__e), pos__i))])
return True
if SCmp(cmds,i, ('>', 'JUMP_IF_TRUE', 'POP_TOP', 'JUMP_IF2_FALSE_POP', \
'>', (':', 1,1), 'JUMP_IF_FALSE_POP')) and pos__d[1] == pos__g[1]:
rpl(cmds,[Or_j_s(aa, And_j_s(pos__d[2],pos__e)),pos__g])
return True
if SCmp(cmds,i, ('>', 'JUMP_IF_TRUE', 'POP_TOP', 'JUMP_IF2_FALSE_POP_CONTINUE', \
'>', (':', 1, 1), '=', 'ju')) and pos__d[1] == pos__h[1]:
# re.match_nl or (match_bol and re.nullable)
rpl(cmds,[Or_j_s(pos__a, And_j_s(pos__d[2],pos__e)),pos__g,pos__h])
return True
if SCmp(cmds,i, ('>', 'JUMP_IF_TRUE', 'POP_TOP', '>', 'JUMP')) and pos__b[1] == pos__e[1]:
rpl(cmds, [Or_j_s(pos__a, pos__d), pos__e])
return True
if SCmp(cmds,i, ('>', 'JUMP_IF_TRUE', 'POP_TOP', 'JUMP_IF2_TRUE_POP', \
'LOAD_CONST', (':', 1, 1), 'STORE_FAST', ('::', 3))) and\
pos__d[2][0] == 'FAST' and pos__d[2][1] == pos__g[1]:
rpl(cmds, [Or_j_s(Or_j_s(pos__a, pos__d[2]), pos__e),pos__g])
return True
return False
def process_push2(cmds,i,added_pass):
aa = cmd2mem(pos__a)
bb = cmd2mem(pos__b)
if pos__c[0] == 'BUILD_SLICE' and len(pos__c) == 2 and pos__c[1] == 2:
cmds[i:i+3] = [('!PySlice_New', aa, bb, 'NULL')]
return True
if pos__c[0] == 'STORE_MAP' and len(pos__c) == 1:
cmds[i:i+3] = [('STORE_MAP', bb, aa)]
return True
if pos__c[0] == 'ROT_TWO' and pos__d[0] == 'STORE_ATTR_1':
cmds[i:i+4] = [('STORE', (('PyObject_SetAttr', aa, ('CONST', pos__d[1])),), (pos__b,))]
return True
if SCmp(cmds,i, ('>','>', '>', 'BUILD_CLASS')):
rpl(cmds,[('!_PyEval_BuildClass', cmd2mem(pos__c), bb, aa)])
return True
if pos__c[0] == 'ROT_TWO':
if aa[0] in ('!LOAD_GLOBAL', 'CONST', 'FAST', '!PyObject_Repr', '!PyObject_GetAttr') or \
bb[0] in ('!LOAD_GLOBAL', 'CONST', 'FAST', '!PyObject_Repr', '!PyObject_GetAttr'):
cmds[i:i+3] = [pos__b[:], pos__a[:]]
return True
## if pos__c[0] == 'ROT_TWO':
## cmds[i:i+3] = [pos__b[:], pos__a[:]]
## return True
if pos__c[0] == 'DELETE_SLICE+1' and len(pos__c) == 1:
cmds[i:i+3] = [('DELETE_SLICE+1', aa, bb)]
return True
if pos__c[0] == 'IMPORT_NAME' and len(pos__c) == 2:
cmds[i:i+3] = [('!IMPORT_NAME', pos__c[1], aa, bb)]
return True
if pos__c[0] == 'COMPARE_OP':
cmds[i:i+3] = process_compare_op(pos__c[1],pos__a,pos__b)
return True
if pos__c[0] == 'LIST_APPEND' and len(pos__c) == 1:
cmds[i:i+3] = [('PyList_Append', aa, bb)]
return True
if pos__c[0] == 'SLICE+1' and len(pos__c) == 1:
if isintconst(bb):
cmds[i:i+3] = [('!PySequence_GetSlice', aa, bb[1], 'PY_SSIZE_T_MAX')]
else:
cmds[i:i+3] = [('!_PyEval_ApplySlice', aa, bb, 'NULL')]
return True
if pos__c[0] == 'SLICE+2' and len(pos__c) == 1:
if isintconst(bb):
cmds[i:i+3] = [('!PySequence_GetSlice', aa, 0, bb[1])]
else:
cmds[i:i+3] = [('!_PyEval_ApplySlice', aa, 'NULL', bb)]
return True
## if pos__c[0] == 'BINARY_ADD' and bb[0] == 'CONST' and \
## type(bb[1]) is int and bb[1] >= 0:
## cmds[i:i+3] = [('!from_ceval_BINARY_ADD_Int', aa, bb[1], bb)]
## return True
if pos__c[0] == 'BINARY_MODULO' and aa[0] == 'CONST' and \
type(aa[1]) is str and bb[0] == '!BUILD_TUPLE':
cmds[i:i+3] = [('!PyString_Format', aa, bb)]
return True
if pos__c[0] == 'BINARY_MULTIPLY' and (aa[0] == '!STR_CONCAT' or (aa[0] == 'CONST' and \
(type(aa[1]) is str or type(aa[1]) is list or type(aa[1]) is tuple))):
cmds[i:i+3] = [('!PySequence_Repeat', aa, bb)]
return True
if pos__c[0] == 'BINARY_ADD' and aa[0] == '!STR_CONCAT' and bb[0] == '!STR_CONCAT':
cmds[i:i+3] = [aa + bb[1:]]
return True
if pos__c[0] == 'BINARY_ADD' and aa[0] == '!PyNumber_Add' and bb[0] == '!STR_CONCAT':
cmds[i:i+3] = [(bb[0], aa[1], aa[2]) + bb[1:]]
return True
if pos__c[0] == 'BINARY_ADD' and bb[0] == '!PyNumber_Add' and aa[0] == '!STR_CONCAT':
cmds[i:i+3] = [(aa[0], aa[1], aa[2]) + bb[1:]]
return True
if pos__c[0] == 'BINARY_ADD' and bb[0] == '!STR_CONCAT':
cmds[i:i+3] = [('!STR_CONCAT', aa) + bb[1:]]
return True
if pos__c[0] == 'BINARY_ADD' and aa[0] == '!STR_CONCAT':
cmds[i:i+3] = [aa + (bb,)]
return True
if pos__c[0] == 'BINARY_ADD' and bb[0] == 'CONST' and \
type(bb[1]) is str and aa[0] == '!PyNumber_Add':
cmds[i:i+3] = [('!STR_CONCAT', aa[1], aa[2], bb)]
return True
if pos__c[0] == 'BINARY_ADD' and bb[0] == 'CONST' and \
type(bb[1]) is str:
cmds[i:i+3] = [('!STR_CONCAT', aa, bb)]
return True
if pos__c[0] == 'BINARY_ADD' and aa[0] == 'CONST' and \
type(aa[1]) is str:
cmds[i:i+3] = [('!STR_CONCAT', aa, bb)]
return True
if pos__c[0] == 'BINARY_SUBSCR' and bb[0] == 'CONST' and \
type(bb[1]) is int: # and bb[1] >= 0:
cmds[i:i+3] = [('!BINARY_SUBSCR_Int', aa, bb)]
return True
if pos__c[0] == 'BINARY_SUBSCR' :
cmds[i:i+3] = [('!from_ceval_BINARY_SUBSCR', aa, bb)]
return True
if pos__c[0] in recode_binary:
if recode_binary[pos__c[0]] == 'PyNumber_Power+Py_None':
cmds[i:i+3] = [('!PyNumber_Power', aa, bb, 'Py_None')]
else:
cmds[i:i+3] = [('!' +recode_binary[pos__c[0]], aa, bb)]
return True
if pos__c[0] == 'INPLACE_POWER':
cmds[i:i+3] = [('!PyNumber_InPlacePower', aa, bb, 'Py_None')]
return True
if pos__c[0] in recode_inplace:
cmds[i:i+3] = [('!' +recode_inplace[pos__c[0]], aa, bb)]
return True
if pos__c[0][:8] == 'INPLACE_':
cmds[i:i+3] = [('!#=' + pos__c[0][8:], aa, bb)]
return True
if pos__c[0] == 'DELETE_SUBSCR' and len(pos__c) == 1:
cmds[i:i+3] = [('DELETE_SUBSCR', aa, bb)]
return True
if pos__c[0] == 'DUP_TOPX' and pos__c[1] == 2:
cmds[i:i+3] = [pos__a,pos__b,pos__a,pos__b]
return True
if SCmp(cmds,i, ('>', '>', '=', '=')):
cmds[i:i+4] = [('SET_EXPRS_TO_VARS', (pos__c,pos__d), (bb,aa))]
return True
if pos__c[0] == 'CALL_FUNCTION_KW_1' and pos__c[3] > 0:
cmds[i:i+3] = [(pos__c[0], pos__c[1], pos__c[2], pos__c[3]-1, pos__c[4] + ((aa, bb),), pos__c[5])]
return True
if is_cmdmem(pos__c):
cc = cmd2mem(pos__c)
if pos__d[0] == 'STORE_SUBSCR_0':
cmds[i:i+4] = [('STORE',(('PyObject_SetItem', bb, cc),), (aa,))]
return True
if pos__d[0] == 'SLICE+3' and len(pos__d) == 1:
cmds[i:i+4] = [('!_PyEval_ApplySlice',) + (aa,) + (bb,) + (cc,)]
return True
if pos__d[0] == 'BUILD_SLICE' and len(pos__d) == 2 and pos__d[1] == 3:
cmds[i:i+4] = [('!PySlice_New', aa, bb, cc)]
return True
if pos__d[0] == 'DELETE_SLICE+3':
cmds[i:i+4] = [('DELETE_SLICE+3', aa, bb, cc)]
return True
if pos__d[0] == 'DUP_TOPX' and pos__d[1] == 3:
cmds[i:i+4] = [pos__a,pos__b,pos__c,pos__a,pos__b,pos__c]
return True
if pos__d[0] == 'ROT_THREE' and pos__e[0] in ('STORE_SUBSCR_0', 'STORE_SLICE+2', 'STORE_SLICE+1'):
cmds[i:i+4] = [pos__c,pos__a,pos__b]
return True
if SCmp(cmds,i, ('>','>', '>', '=', '=', '=')):
cmds[i:i+6] = [('SET_EXPRS_TO_VARS', (pos__f,pos__e,pos__d), (aa,bb,cc))]
return True
if SCmp(cmds,i, ('>', '>','>', '>', '=', '=', '=', '=')):
cmds[i:i+8] = [('SET_EXPRS_TO_VARS', \
(pos__h,pos__g,pos__f,pos__e), \
(aa, bb, cc, cmd2mem(pos__d)))]
return True
if SCmp(cmds,i, ('>', '>', '>','>', '>', '=', '=', '=', '=', '=')):
cmds[i:i+10] = [('SET_EXPRS_TO_VARS', \
(pos__j,pos__i,pos__h,pos__g,pos__f), \
(aa, bb, cc, cmd2mem(pos__d),cmd2mem(pos__e)))]
return True
if SCmp(cmds,i, ('>', '>', '>', '>','>', '>', '=', '=', '=', '=', '=', '=')):
cmds[i:i+12] = [('SET_EXPRS_TO_VARS', \
(pos__l,pos__k,pos__j,pos__i,pos__h,pos__g), \
(aa, bb, cc, cmd2mem(pos__d), cmd2mem(pos__e),cmd2mem(pos__f)))]
return True
if SCmp(cmds,i, ('>', '>', '>', 'ROT_THREE', 'ROT_TWO', '=', '=', '=')):
cmds[i:i+8] = [('SET_EXPRS_TO_VARS', (pos__f,pos__g,pos__h), (aa,bb,cc))]
return True
if SCmp(cmds,i, ('>','>','>', 'EXEC_STMT')):
rpl(cmds,[('EXEC_STMT_3', aa, bb, cc)])
return True
if SCmp(cmds,i, ('>', '>', '>', 'STORE_SLICE+3')):
rpl(cmds,[('STORE_SLICE_LV+3', aa, bb, cc)])
return True
if SCmp(cmds,i, ('>', '>', '>', '>', 'ROT_FOUR')):
rpl(cmds,[pos__d,pos__a,pos__b,pos__c])
return True
if pos__c[0] == 'DELETE_SLICE+2' and SCmp(cmds,i, ('>', '>', 'DELETE_SLICE+2')) and len(pos__c) == 1:
cmds[i:i+3] = [(pos__c[0], aa, bb)]
return True
if pos__c[0] == 'ROT_TWO' and SCmp(cmds,i, ('>', '>', 'ROT_TWO', '=', '=')):
cmds[i:i+5] = [('SET_EXPRS_TO_VARS', (pos__d,pos__e), (aa,bb))]
return True
if pos__c[0] == 'CALL_FUNCTION_1' and SCmp(cmds,i, ('>', '>', 'CALL_FUNCTION_1')) and pos__c[3] > 0:
cmds[i:i+3] = [(pos__c[0], pos__c[1], pos__c[2], pos__c[3]-1, pos__c[4] + ((aa, bb),))]
return True
if pos__c[0] == 'CALL_FUNCTION_VAR_1' and SCmp(cmds,i, ('>', '>', 'CALL_FUNCTION_VAR_1')) and pos__c[3] > 0:
rpl(cmds, [(pos__c[0], pos__c[1], pos__c[2], pos__c[3]-1, pos__c[4] + ((aa, bb),), pos__c[5])])
return True
if pos__c[0] == 'CALL_FUNCTION_VAR_KW' and SCmp(cmds,i, ('>', '>', 'CALL_FUNCTION_VAR_KW')):
cmds[i:i+3] = [('CALL_FUNCTION_VAR_KW_1',) + pos__c[1:] + (aa,bb)]
return True
if pos__c[0] == 'CALL_FUNCTION_VAR_KW_1' and SCmp(cmds,i, ('>', '>', 'CALL_FUNCTION_VAR_KW_1')) and pos__c[3] > 0:
cmds[i:i+3] = [(pos__c[0], pos__c[1], pos__c[2], pos__c[3]-1, pos__c[4] + ((aa, bb),), pos__c[5],pos__c[6])]
return True
if pos__c[0] == 'STORE_SLICE+2' and SCmp(cmds,i, ('>','>', 'STORE_SLICE+2')):
rpl(cmds,[('STORE_SLICE_LV+2', aa, bb)])
return True
if pos__c[0] == 'STORE_SLICE+1' and SCmp(cmds,i, ('>', '>', 'STORE_SLICE+1')):
rpl(cmds,[('STORE_SLICE_LV+1', aa, bb)])
return True
if pos__c[0] == 'DUP_TOP' and SCmp(cmds,i, ('>','>', 'DUP_TOP', 'ROT_THREE', 'COMPARE_OP')):
rpl(cmds, [('3CMP_BEG_3', aa, pos__e[1], bb)])
return True
if pos__c[0] == 'DUP_TOP' and SCmp(cmds,i, ('>', '>', 'DUP_TOP', 'EXEC_STMT')):
rpl(cmds,[('EXEC_STMT_3', aa, bb, bb)])
return True
if pos__c[0] == 'PRINT_ITEM_TO_0':
cmds[i:i+3] = [('PRINT_ITEM_TO_2', bb,aa)]
return True
if pos__c[0] == 'STORE_SUBSCR_0':
cmds[i:i+3] = [('PyObject_SetItem',) + (aa,) + (bb,)]
return True
return False
imported_modules = {}
def module_dict_to_type_dict(pos__d):
d2 = dict(pos__d)
for k in pos__d.keys():
v = pos__d[k]
t = type(v)
if t is types.InstanceType:
t2 = None
try:
t2 = (T_OLD_CL_INST, v.__class__.__name__)
except:
pass
if t2 is not None:
t = t2
else:
if type(t) != type:
t = (T_NEW_CL_INST, v.__class__.__name__)
else:
t = (t, None)
d2[k] = t
return d2
def CheckExistListImport(nm, fromlist=None,level=-1):
global filename
if nm in ('org.python.core',):
return
this = None
## if nm[0:3] == '_c_':
## nm = nm[3:]
if nm + '.py' == filename:
return
if nm in list_import:
return
if nm in imported_modules:
this = imported_modules[nm]
elif nm in sys.modules:
this = sys.modules[nm]
imported_modules[nm] = this
list_import[nm] = module_dict_to_type_dict(this.__dict__)
FillListImport(this)
return
elif Is3(nm, 'ImportedM'):
v = Val3(nm, 'ImportedM')
if type(v) is tuple and len(v) == 2:
return CheckExistListImport(v[0] + '.' + v[1])
elif type(v) is str and v != nm:
return CheckExistListImport(v)
if v != nm:
Fatal(nm, v)
if this is None:
# if nm == '':
# Fatal('can\'t import empty module')
try:
if fromlist is None and level == -1 and nm != '':
this = __import__(nm)
imported_modules[nm] = this
elif nm == '' and level != -1 and len(fromlist) == 1:
this = __import__()
imported_modules[fromlist[0]] = this
else:
this = __import__(nm,{},{}, fromlist)
imported_modules[nm] = this
except TypeError:
if nm != '':
Fatal('', nm, sys.exc_info())
Debug(sys.exc_info()[:2])
## if nm == '__builtin__.__dict__':
## assert False
if level == -1:
Debug('Module %s import unsuccessful2' % nm, fromlist)
else:
Debug('Module %s relative import unsuccessful2' % nm)
return
except ImportError:
Debug(sys.exc_info()[:2])
## if nm == '__builtin__.__dict__':
## assert False
if level == -1:
Debug('Module %s import unsuccessful2' % nm, fromlist)
else:
Debug('Module %s relative import unsuccessful2' % nm)
return
except:
print (nm)
print (sys.exc_info())
if nm != '' and nm[0] != '.':
Fatal('',nm,sys.exc_info())
return
nms = nm.split('.')
s = ''
old_this = this
if fromlist is not None:
assert this.__name__ == nm
list_import[nm] = module_dict_to_type_dict(this.__dict__)
imported_modules[nm] = this
else:
for v in nms:
pos__d2 = None
if s != '':
s += '.'
if v not in pos__d or pos__d is None:
if fromlist is None:
Debug('Module %s %s (%s) import unsuccessful3' % (s, v, nm), fromlist)
break
this = pos__d2[v]
pos__d2 = this.__dict__
s += v
assert type(this) is types.ModuleType
list_import[s] = module_dict_to_type_dict(pos__d2)
imported_modules[s] = this
FillListImport(old_this)
def FillListImport(module, nm = None, list_added = []):
if nm is None:
nm = module.__name__
if not nm in imported_modules:
imported_modules[nm] = module
if not nm in list_import:
list_import[nm] = module_dict_to_type_dict(module.__dict__)
if module in list_added:
return
list_added.append(module)
for k, v in module.__dict__.iteritems():
if type(v) is types.ModuleType:
FillListImport(v, nm + '.' + k, list_added)
FillListImport(sys)
FillListImport(types)
##FillListImport(pprint)
FillListImport(glob)
FillListImport(traceback)
FillListImport(gc)
FillListImport(os)
FillListImport(math)
FillListImport(StringIO)
FillListImport(operator)
FillListImport(csv)
FillListImport(distutils)
def MyImport(nm):
assert nm is not None
if nm.startswith('__main__'):
return None, {}
CheckExistListImport(nm)
if nm not in imported_modules:
return None, {}
this = imported_modules[nm]
pos__d = this.__dict__
if '.' in nm:
nms = nm.split('.')
pos__d = this.__dict__
if hasattr(this, '__file__') and this.__file__.endswith(nms[-1] + '.pyc'):
return this, pos__d
if this.__name__ == nm:
return this, pos__d
for i in range(1, len(nms)):
if nms[i] in this.__dict__ and type(this.__dict__[nms[i]]) is types.ModuleType:
this = pos__d[nms[i]]
pos__d = this.__dict__
else:
if nms[i] in pos__d:
this = pos__d[nms[i]]
pos__d = this.__dict__
else:
Debug('Import Error', nm, this, i, nms)
return None, {}
## Debug('Import Error', nm, this, i, nms)
return this, pos__d
def make_import_star(aa):
## nm = aa[1]
if aa[1] in known_modules and aa[2] == ('CONST', -1):
d = None
# try:
this, d = MyImport(aa[1])
# except:
# Debug('Module %s import unsuccessful' % aa[1])
# return [('IMPORT_STAR', aa)]
if '__all__' in d:
d2 = {}
for k in d['__all__']:
if k in d:
d2[k] = d[k]
d = d2
r1 = []
r2 = []
for v in d:
if v not in ('__name__', '__module__', '__file__') and \
v in count_define_get:
r1.append(v)
r2.append(('STORE_NAME', v))
r1 = ('CONST', tuple(r1))
r2 = tuple(r2)
return [('IMPORT_FROM_AS', aa[1], ('CONST', -1), r1, r2)]
else:
Debug('Module %s star import unsuccessful - not in knows' % aa[1])
return [('IMPORT_STAR', aa)]
def val_imp(nm, k):
assert nm is not None
## if nm.startswith('_c_'):
## nm = nm[3:]
if nm == filename[:-3]:
return None
if Is3(nm, 'ImportedM'):
v = Val3(nm, 'ImportedM')
if type(v) is tuple and len(v) == 2:
if v[0] in list_import and v[1] in list_import[v[0]] and not IsModule(list_import[v[0]][v[1]]):
return None
this, d = MyImport(nm)
if this is None:
if Is3(nm, 'ImportedM'):
v = Val3(nm, 'ImportedM')
if type(v) is tuple and len(v) == 2:
## imp = v[0] + '.' + v[1]
return val_imp(v[0] + '.' + v[1], k)
elif type(v) is str and v != nm:
return val_imp(v, k)
# return None
if k not in d:
this, d = MyImport(nm + '.' + k)
if this is not None and this.__name__ == (nm + '.' + k):
return this
## if this is None:
## if Is3(nm, 'ImportedM'):
## v = Val3(nm, 'ImportedM')
## if type(v) is tuple and len(v) == 2:
## return val_imp(v[0] + '.' + v[1], k)
## return None
if this is None:
return None
return d[k]
def _process_compare_op_const(op, pos__a,pos__b):
try:
if op == '==':
return('CONST', pos__a[1] == pos__b[1])
if op == '!=':
return('CONST', pos__a[1] != pos__b[1])
if op == '>=':
return('CONST', pos__a[1] >= pos__b[1])
if op == '<=':
return('CONST', pos__a[1] <= pos__b[1])
if op == '<':
return('CONST', pos__a[1] < pos__b[1])
if op == '>':
return('CONST', pos__a[1] > pos__b[1])
except:
pass
return None
def _process_compare_op(op, a,b):
if a[0] in ('LOAD_CONST', 'CONST') and b[0] in ('LOAD_CONST', 'CONST'):
const_r = _process_compare_op_const(op, a,b)
if const_r is not None:
return const_r
if a[0] in ('LOAD_CONST', 'CONST') and type(a[1]) is int:
if op in ('==', '!='):
if op in op_2_c_op and op not in('is', 'is not'):
return('!BOOLEAN', ('!c_' + op_2_c_op[op] + '_Int', cmd2mem(b), cmd2mem(a)))
## elif op in op_2_inv_op_:
## op = op_2_inv_op_[op]
## if int(a[1]) == a[1] and \
## op in op_2_c_op and op not in('is', 'is not'):
## return('!BOOLEAN', ('!c_' + op_2_c_op[op] + '_Int', cmd2mem(b), a[1]))
if a[0] == '!PY_SSIZE_T' and b[0] in ('LOAD_CONST', 'CONST') and type(b[1]) is int:
if op in op_2_c_op and op not in('is', 'is not'):
return('!BOOLEAN', ('!SSIZE_T' + op, a[1], b[1]))
if b[0] in ('LOAD_CONST', 'CONST') and type(b[1]) is int:
if int(b[1]) == b[1] and \
op in op_2_c_op and op not in('is', 'is not'):
return('!BOOLEAN', ('!c_' + op_2_c_op[op] + '_Int', cmd2mem(a), cmd2mem(b)))
if b[0] in ('LOAD_CONST', 'CONST') and type(b[1]) is str:
if op in ('==', '!='):
return('!BOOLEAN', ('!c_' + op_2_c_op[op] + '_String', cmd2mem(a), cmd2mem(b)))
# 11.06.2010 !!!
if a[0] in ('LOAD_CONST', 'CONST') and type(a[1]) is str:
if op in ('==', '!='):
return('!BOOLEAN', ('!c_' + op_2_c_op[op] + '_String', cmd2mem(b), cmd2mem(a)))
## if b[0] == '!PY_SSIZE_T':
## if op in op_2_c_op and op not in('is', 'is not'):
## return ('!BOOLEAN', ('!c_' + op_2_c_op[op] + '_Int', cmd2mem(a), b))
if op == 'not in':
return Not(('!BOOLEAN', ('!PySequence_Contains(', cmd2mem(b), cmd2mem(a))))
if op == 'in':
return ('!BOOLEAN', ('!PySequence_Contains(', cmd2mem(b), cmd2mem(a)))
if op == 'is':
return ('!BOOLEAN',('!_EQ_', cmd2mem(a), cmd2mem(b)))
if op == 'is not':
return ('!BOOLEAN',('!_NEQ_', cmd2mem(a), cmd2mem(b)))
return None
def process_compare_op(op, a,b):
ret = _process_compare_op(op,a,b)
if ret is not None:
return [ret]
if op in op_2_c_op:
return [('!PyObject_RichCompare(', cmd2mem(a), cmd2mem(b), op_2_c_op[op])]
Fatal('Can\'t handle compare_op', op, a, b)
def process_load_const_test1(cmds):
try:
if pos__a[1]:
rpl(cmds,[pos__a, ('JUMP',) + pos__b[1:]])
else:
rpl(cmds,[])
return True
except:
pass
return False
def process_load_const_test2(cmds):
try:
if not pos__a[1]:
rpl(cmds,[pos__a, ('JUMP',) + pos__b[1:]])
else:
rpl(cmds,[])
return True
except:
pass
return False
def process_load_const_test3(cmds):
try:
if pos__a[1]:
rpl(cmds,[pos__a, ('JUMP',) + pos__b[1:]])
else:
rpl(cmds,[pos__a])
return True
except:
pass
return False
def process_load_const_test4(cmds):
try:
if not pos__a[1]:
rpl(cmds,[pos__a, ('JUMP',) + pos__b[1:]])
else:
rpl(cmds,[pos__a])
return True
except:
pass
return False
def process_load_const(cmds,i,added_pass):
if pos__a[0] == 'LOAD_CONST' and pos__b[0] == 'UNPACK_SEQUENCE' and pos__a[1] is not None and pos__b[1] == len(pos__a[1]):
cmds[i:i+2] = [('LOAD_CONST', x) for x in reversed(pos__a[1])]
return True
if pos__a[0] == 'LOAD_CONST' and pos__b[0] == 'STORE':
cmds[i:i+2] = [pos__b, pos__a]
return True
if pos__a[0] == 'LOAD_CONST' and pos__b[0] == 'DUP_TOP':
cmds[i:i+2] = [pos__a, pos__a[:]]
return True
if SCmp(cmds,i, ('LOAD_CONST', '-')):
rpl(cmds,[pos__b,pos__a])
return True
if SCmp(cmds,i,('LOAD_CONST', 'JUMP_IF_TRUE', 'POP_TOP')):
if process_load_const_test1(cmds):
return True
if SCmp(cmds,i,('LOAD_CONST', 'JUMP_IF_FALSE', 'POP_TOP')):
if process_load_const_test2(cmds):
return True
if SCmp(cmds,i,('LOAD_CONST', 'JUMP_IF_TRUE')):
if process_load_const_test3(cmds):
return True
if SCmp(cmds,i,('LOAD_CONST', 'JUMP_IF_FALSE')):
if process_load_const_test4(cmds):
return True
return False
def process_j_setup_finally(cmds,i,added_pass):
if SCmp(cmds,i, ('J_SETUP_FINALLY', '*', 'POP_BLOCK', 'LOAD_CONST', \
(':',0,1), '*', 'END_FINALLY')) and pos__d[1] is None:
rpl(cmds,[[('(TRY',), pos__b, (')(FINALLY',), pos__f, (')ENDTRY',)]])
return True
if SCmp(cmds,i, ('J_SETUP_FINALLY', '*', 'POP_BLOCK', 'LOAD_CONST', \
(':',0,1), 'END_FINALLY')) and pos__d[1] is None:
rpl(cmds,[[('(TRY',), pos__b, (')(FINALLY',), [('PASS',)], (')ENDTRY',)]])
return True
if SCmp(cmds,i, ('J_SETUP_FINALLY', 'POP_BLOCK', 'LOAD_CONST', \
(':',0,1), 'END_FINALLY')) and pos__c[1] is None:
rpl(cmds,[[('(TRY',), [('PASS',)], (')(FINALLY',), [('PASS',)], (')ENDTRY',)]])
return True
if SCmp(cmds,i, ('J_SETUP_FINALLY', 'JUMP_CONTINUE', 'POP_BLOCK', \
'LOAD_CONST', (':', 0, 1), '**n', 'END_FINALLY', \
'JUMP_CONTINUE')) and pos__b[1] == pos__h[1]:
rpl(cmds,[[('(TRY',), [('CONTINUE',)], (')(FINALLY',), pos__f, (')ENDTRY',)],pos__h])
return True
if SCmp(cmds,i, ('J_SETUP_FINALLY', '*n','JUMP_CONTINUE', 'POP_BLOCK', \
'LOAD_CONST', (':', 0, 1), '**n', 'END_FINALLY', \
'JUMP_CONTINUE')) and pos__c[1] == pos__i[1]:
rpl(cmds,[[('(TRY',), pos__b + [('CONTINUE',)], (')(FINALLY',), pos__g, (')ENDTRY',)],pos__h])
return True
if SCmp(cmds,i, ('J_SETUP_FINALLY', 'POP_BLOCK', 'LOAD_CONST', \
(':',0,1), '*', 'END_FINALLY')) and pos__c[1] is None:
rpl(cmds,[[('(TRY',), [('PASS',)], (')(FINALLY',), pos__e, (')ENDTRY',)]])
return True
if SCmp(cmds,i, ('J_SETUP_FINALLY', '*r', (':',0,1), '*', 'END_FINALLY')):
rpl(cmds,[[('(TRY',), pos__b, (')(FINALLY',), pos__d, (')ENDTRY',)]])
return True
if SCmp(cmds,i, ('J_SETUP_FINALLY', '*n', 'LOAD_CONST', (':',0,1), \
'*', 'END_FINALLY')) and pos__c[1] is None:
rpl(cmds,[[('(TRY',), pos__b, (')(FINALLY',), pos__e, (')ENDTRY',)]])
return True
return False
def process_j_begin_with(cmds,i,added_pass):
if SCmp(cmds,i, ('J_BEGIN_WITH', 'POP_BLOCK',('LOAD_CONST', None),\
(':', 0, 1), 'WITH_CLEANUP', 'END_FINALLY')):
rpl(cmds,[[('(WITH',) + pos__a[2:],[('PASS',)], (')ENDWITH',)]])
return True
if SCmp(cmds,i, ('J_BEGIN_WITH', '*', 'POP_BLOCK',('LOAD_CONST', None),\
(':', 0, 1), 'WITH_CLEANUP', 'END_FINALLY')):
rpl(cmds,[[('(WITH',) + pos__a[2:], pos__b, (')ENDWITH',)]])
return True
if SCmp(cmds,i, ('J_BEGIN_WITH', '*', 'JUMP_CONTINUE', 'POP_BLOCK',('LOAD_CONST', None),\
(':', 0, 1), 'WITH_CLEANUP', 'END_FINALLY')):
rpl(cmds,[[('(WITH',) + pos__a[2:], pos__b + [('CONTINUE',)], (')ENDWITH',)]])
return True
if SCmp(cmds,i, ('J_BEGIN_WITH', 'JUMP_CONTINUE', 'POP_BLOCK',('LOAD_CONST', None),\
(':', 0, 1), 'WITH_CLEANUP', 'END_FINALLY')):
rpl(cmds,[[('(WITH',) + pos__a[2:], [('CONTINUE',)], (')ENDWITH',)]])
return True
if SCmp(cmds,i, ('J_BEGIN_WITH', '*l', 'POP_BLOCK',('LOAD_CONST', None),\
(':', 0, 1), 'WITH_CLEANUP', 'END_FINALLY')):
rpl(cmds,[[('(WITH',) + pos__a[2:], [('PASS',)], (')ENDWITH',)]])
return True
if SCmp(cmds,i, ('J_BEGIN_WITH', '*r',\
(':', 0, 1), 'WITH_CLEANUP', 'END_FINALLY')):
rpl(cmds,[[('(WITH',) + pos__a[2:], pos__b, (')ENDWITH',)]])
return True
return False
def process_j_setup_loop(cmds,i,added_pass):
if pos__a[0] == 'J_SETUP_LOOP':
if len(pos__a) == 2 and pos__b[0] == '!GET_ITER' and len(pos__b) == 2:
cmds[i:i+2] = [('J_SETUP_LOOP_FOR', pos__a[1], pos__b[1])]
return True
if len(pos__a) == 3 and pos__b[0] == '!GET_ITER' and len(pos__b) == 2:
cmds[i:i+2] = [('.L', pos__a[2]),('J_SETUP_LOOP_FOR', pos__a[1], pos__b[1])]
return True
if len(pos__a) == 2 and pos__b[0] == '.L' and pos__c[0] == '!GET_ITER' and len(pos__c) == 2:
cmds[i:i+3] = [('J_SETUP_LOOP_FOR', pos__a[1], pos__c[1])]
return True
if len(pos__a) == 3 and pos__b[0] == '.L' and pos__c[0] == '!GET_ITER' and len(pos__c) == 2:
cmds[i:i+3] = [('.L', pos__a[2]),('J_SETUP_LOOP_FOR', pos__a[1], pos__c[1])]
return True
if SCmp(cmds,i, ('J_SETUP_LOOP', ('!', '(IF', '*c', ')ENDIF'), 'POP_BLOCK', 'JUMP')) and\
pos__a[0] != pos__d[1]:
bod = pos__b[1][:-1]
if len(bod) == 0:
bod = [('PASS',)]
cmds[i:i+4] = [[('(WHILE',) + pos__b[0][1:], bod, (')ENDWHILE',)],pos__d]
return True
if isblock(pos__b) and pos__c[0] == 'POP_BLOCK' and \
pos__d[0] == '.:' and pos__d[1] == pos__a[1] and OneJumpCache(pos__d[1], cmds) and len(pos__b) == 3 and\
pos__b[0][0] == '(IF' and pos__b[2][0] == ')ENDIF' and type(pos__b[1]) is list:
cmds[i:i+4] = [[('(WHILE',) + pos__b[0][1:], pos__b[1], (')ENDWHILE',)]]
return True
if pos__b[0] == '.:' and pos__c[0] == 'JUMP_IF2_FALSE_POP' and\
isblock(pos__d) and pos__e[0] in jump and pos__e[1] == pos__b[1] and \
pos__f[0] == '.:' and pos__f[1] == pos__c[1] and pos__g[0] == 'POP_BLOCK' and \
pos__h[0] == '.:' and pos__h[1] == pos__a[1] and\
OneJumpCache(pos__b[1], cmds) and\
OneJumpCache(pos__f[1], cmds) and\
OneJumpCache(pos__h[1], cmds):
cmds[i:i+8] = [[('(WHILE',) + pos__c[2:], pos__d[:], (')ENDWHILE',)]]
return True
if pos__b[0] == '.:' and pos__c[0] == 'JUMP_IF2_FALSE_POP' and\
isblock(pos__d) and pos__e[0] in jump and pos__e[1] == pos__b[1] and \
pos__f[0] == '.:' and pos__f[1] == pos__c[1] and pos__g[0] == 'POP_BLOCK' and \
pos__h[0] == '.:' and pos__h[1] == pos__a[1] and\
OneJumpCache(pos__b[1], cmds) and\
OneJumpCache(pos__f[1], cmds) and\
CountJumpCache(pos__h[1], cmds) > 1:
cmds[i:i+8] = [[('(WHILE',) + pos__c[2:], pos__d[:], (')ENDWHILE',)],pos__h]
return True
if SCmp(cmds,i, ('J_SETUP_LOOP', 'LOAD_FAST', (':', 5, 1),\
'J_LOOP_VARS', '*', 'JUMP_CONTINUE', (':',3,1),\
'POP_BLOCK', ('::', 0))) and pos__b[1][0] == '.':
rpl(cmds,[[('(FOR_ITER', pos__d[2], cmd2mem(pos__b)), pos__e, (')ENDFOR_ITER',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP', 'JUMP_IF2_FALSE_POP_CONTINUE', '*r',
(':', 1, 1), 'POP_BLOCK', ('::',0))):
rpl(cmds,[[('(WHILE',) + pos__b[2:] , pos__c, (')ENDWHILE',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP', 'LOAD_FAST', (':', 5, 1), \
'J_FOR_ITER',\
'*', 'JUMP_CONTINUE', \
(':', 3, 1), 'POP_BLOCK', ('::', 0))) and\
pos__e[0][0] == 'UNPACK_SEQ_AND_STORE' and pos__e[0][1] == 0 and pos__b[1][0] == '.':
rpl(cmds,[[('(FOR_GENERATOR', pos__e[0][2]), pos__e[1:], (')ENDFOR_GENERATOR',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP', 'LOAD_FAST', (':', 5, 1), \
'J_FOR_ITER',\
'*', 'JUMP_CONTINUE', \
(':', 3, 1), 'POP_BLOCK', ('::', 0))) and\
pos__e[0][0] == '.L' and pos__e[1][0] == 'UNPACK_SEQ_AND_STORE' and pos__e[1][1] == 0 and pos__b[1][0] == '.':
rpl(cmds,[[('(FOR_GENERATOR', pos__e[1][2]), pos__e[2:], (')ENDFOR_GENERATOR',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP', (':', 3, 1), '*', 'JUMP_CONTINUE', ('::', 0))):
rpl(cmds,[[('(WHILE', TRUE), pos__c, (')ENDWHILE',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP', (':', 4,1), 'JUMP_IF2_FALSE_POP', '*',\
'JUMP_CONTINUE', (':', 2, 1), 'POP_BLOCK', ('::', 0))) :
rpl(cmds, [[('(WHILE',) + pos__c[2:], pos__d, (')ENDWHILE',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP', (':', 4, 1), 'JUMP_IF2_TRUE_POP', \
'*', 'JUMP_CONTINUE', (':',2, 1), 'POP_BLOCK', ('::',0))):
rpl(cmds,[[('(WHILE', Not(pos__c[2])), pos__d, (')ENDWHILE',)]])
return True
# {'*' removed
if SCmp(cmds,i, ('J_SETUP_LOOP', ('!', '(IF', '*c', ')ENDIF'), \
'POP_BLOCK', '*r', (':',0,1), '*r')):
rpl(cmds,[[('(WHILE', pos__b[0][1]), pos__b[1], (')(ELSE',), pos__d, (')ENDWHILE',)],pos__f])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP', ('!', '(IF', '*r', ')ENDIF'), \
'POP_BLOCK', '*r', (':',0,1), '*r')):
rpl(cmds,[[('(WHILE', pos__b[0][1]), pos__b[1], (')(ELSE',), pos__d, (')ENDWHILE',)],pos__f])
return True
# }end '*' removed
if SCmp(cmds,i, ('J_SETUP_LOOP', (':', 3, 1), '*', 'JUMP_CONTINUE')):
rpl(cmds,[[('(WHILE', TRUE), pos__c, (')ENDWHILE',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP', '*r', (':', 0,1), 'POP_BLOCK')):
rpl(cmds,[[('(WHILE', TRUE), pos__b, (')ENDWHILE',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP', '*n', ('::', 0))):
rpl(cmds,[[('(WHILE', TRUE), pos__b, (')ENDWHILE',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP', '*r', ('::', 0))):
rpl(cmds,[[('(WHILE', TRUE), pos__b, (')ENDWHILE',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP', ('!', '(IF', '*c', ')ENDIF'),\
'POP_BLOCK', '*n', ('::', 0))):
rpl(cmds,[[('(WHILE',) + pos__b[0][1:], pos__b[1], (')(ELSE',),pos__d,(')ENDWHILE',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP', (':', 2, 1), 'JUMP_IF2_TRUE_POP_CONTINUE', \
'POP_BLOCK', ('::', 0))):
rpl(cmds,[[('(WHILE',) + pos__c[2:], [('PASS',)],(')ENDWHILE',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP', ('!', '(IF', '*c', ')ENDIF'), 'POP_BLOCK',\
'ju')) and pos__d[1] == pos__a[1]:
bod = pos__b[1][:-1]
if len(bod) == 0:
bod = [('PASS',)]
rpl(cmds,[[('(WHILE',) + pos__b[0][1:], bod,(')ENDWHILE',)],pos__d])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP', (':', 4,1), 'JUMP_IF2_FALSE_POP', \
'*n', 'J_SETUP_LOOP', (':', 7, 1), '*n', 'JUMP', \
(':', 2,1), 'POP_BLOCK', ('::', 0))):
rpl(cmds,[[('(WHILE',) + pos__c[2:], pos__d + [('(WHILE', TRUE), pos__g, (')ENDWHILE',)], (')ENDWHILE',)]])
return True
## if SCmp(cmds,i, ('J_SETUP_LOOP', ('!', '(IF', '*c', ')ENDIF'),\ # By CloneDigger
## 'POP_BLOCK', '*n', ('::',0))):
## rpl(cmds,[[('(WHILE',) + pos__b[0][1:], pos__b[1], (')(ELSE',), pos__d, (')ENDWHILE',)]])
## return True
if SCmp(cmds,i, ('J_SETUP_LOOP', ('!', '(IF', '*c', ')ENDIF'),\
'POP_BLOCK', '*n', 'jc')) and pos__a[1] == pos__e[1]:
rpl(cmds,[[('(WHILE',) + pos__b[0][1:], pos__b[1], (')(ELSE',), pos__d, (')ENDWHILE',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP', ('!', '(IF', '*c', ')ENDIF'),\
'POP_BLOCK', '*r', ('::',0))):
rpl(cmds,[[('(WHILE',) + pos__b[0][1:], pos__b[1], (')(ELSE',), pos__d, (')ENDWHILE',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP', ('!', '(IF', '*r', ')ENDIF'),\
'POP_BLOCK', '*n', ('::',0))):
rpl(cmds,[[('(WHILE',) + pos__b[0][1:], pos__b[1], (')(ELSE',), pos__d, (')ENDWHILE',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP', ('!', '(IF', '*c', ')ENDIF'), \
'POP_BLOCK', ('::', 0))): # 4
rpl(cmds,[[('(WHILE',) + pos__b[0][1:], pos__b[1], (')ENDWHILE',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP', ('!', '.L', '(IF', '*c', ')ENDIF'), \
'POP_BLOCK', ('::', 0))): # 4
rpl(cmds,[[('(WHILE',) + pos__b[1][1:], pos__b[2], (')ENDWHILE',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP', (':', 2, 1), 'JUMP_CONTINUE', ('::', 0))):
rpl(cmds,[[('(WHILE', TRUE), [('PASS',)], (')ENDWHILE',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP', (':', 2,1), 'JUMP_IF2_TRUE_POP_CONTINUE',\
'POP_BLOCK', ('::', 0))):
rpl(cmds,[[('(WHILE',) + pos__c[2:], [('PASS',)], (')ENDWHILE',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP', (':', 2,1), 'JUMP_IF2_FALSE_POP_CONTINUE',\
'POP_BLOCK', ('::', 0))):
rpl(cmds,[[('(WHILE', Not(pos__c[2])), [('PASS',)], (')ENDWHILE',)]])
return True
return False
def process_jump(cmds,i, added_pass):
global pos__a,pos__b,pos__c,pos__d,pos__e,pos__f,pos__g,pos__h,pos__i,pos__j,pos__k,pos__l
if pos__a[0] == 'JUMP_IF_TRUE' and pos__b[0] == 'JUMP' and pos__c[0] == '.:' and \
pos__a[1] == pos__c[1] and pos__b[1] != pos__a[1]:
if CountJumpCache(pos__a[1], cmds) == 1:
cmds[i:i+3] = [('JUMP_IF_FALSE', pos__b[1])]
else:
cmds[i:i+3] = [('JUMP_IF_FALSE', pos__b[1]), pos__c]
return True
if pos__a[0] == 'JUMP_IF_FALSE' and pos__b[0] == 'JUMP' and pos__c[0] == '.:' and \
pos__a[1] == pos__c[1] and pos__b[1] != pos__a[1]:
if CountJumpCache(pos__a[1], cmds) == 1:
cmds[i:i+3] = [('JUMP_IF_TRUE', pos__b[1])]
else:
cmds[i:i+3] = [('JUMP_IF_TRUE', pos__b[1]), pos__c]
return True
if len(pos__a) >= 3 and len(pos__b) >= 3 and pos__a[2] == pos__b[2]:
if SCmp(cmds,i,('JUMP_IF2_FALSE_POP', 'JUMP_IF2_FALSE_POP')) and pos__a[2] == pos__b[2]:
rpl(cmds,[pos__a])
return True
if SCmp(cmds,i,('JUMP_IF2_TRUE_POP', 'JUMP_IF2_TRUE_POP')) and pos__a[2] == pos__b[2]:
rpl(cmds,[pos__a])
return True
if len(pos__a) >= 2 and len(pos__b) >= 2 and pos__a[1] == pos__b[1]:
if SCmp(cmds,i,('JUMP_IF2_FALSE_POP', 'JUMP_IF2_FALSE_POP')) and pos__a[1] == pos__b[1]:
rpl(cmds,[('JUMP_IF2_FALSE_POP', pos__a[1], And_j(pos__a[2], pos__b[2]))])
return True
if SCmp(cmds,i,('JUMP_IF2_TRUE_POP', 'JUMP_IF2_TRUE_POP')) and pos__a[1] == pos__b[1]:
rpl(cmds,[('JUMP_IF2_TRUE_POP', pos__a[1], Or_j(pos__a[2], pos__b[2]))])
return True
if SCmp(cmds,i,('JUMP_IF2_TRUE_POP', 'JUMP_IF2_FALSE_POP')) and pos__a[1] == pos__b[1]:
rpl(cmds,[('JUMP_IF2_TRUE_POP', pos__a[1], Or_j(pos__a[2], Not(pos__b[2])))])
return True
if SCmp(cmds,i,('JUMP_IF2_FALSE_POP_CONTINUE', 'JUMP_IF2_FALSE_POP_CONTINUE')) and pos__a[1] == pos__b[1]:
rpl(cmds,[('JUMP_IF2_FALSE_POP_CONTINUE', pos__a[1], And_j(pos__a[2], pos__b[2]))])
return True
if SCmp(cmds,i,('JUMP_IF2_TRUE_POP_CONTINUE', 'JUMP_IF2_TRUE_POP_CONTINUE')) and pos__a[1] == pos__b[1]:
rpl(cmds,[('JUMP_IF2_TRUE_POP_CONTINUE', pos__a[1], Or_j(pos__a[2], pos__b[2]))])
return True
if SCmp(cmds,i,('JUMP_IF2_TRUE_POP_CONTINUE', 'JUMP_IF2_FALSE_POP_CONTINUE')) and pos__a[1] == pos__b[1]:
rpl(cmds,[('JUMP_IF2_TRUE_POP_CONTINUE', pos__a[1], Or_j(pos__a[2], Not(pos__b[2]) ))])
return True
if SCmp(cmds,i,('JUMP_IF2_FALSE_POP', 'JUMP_IF2_TRUE_POP')) and pos__a[1] == pos__b[1]:
rpl(cmds,[('JUMP_IF2_FALSE_POP', pos__a[1], And_j(pos__a[2], Not(pos__b[2])))])
return True
if SCmp(cmds,i,('JUMP_IF2_FALSE_POP_CONTINUE', 'JUMP_IF2_TRUE_POP_CONTINUE')) and pos__a[1] == pos__b[1]:
rpl(cmds,[('JUMP_IF2_FALSE_POP_CONTINUE', pos__a[1], And_j(pos__a[2], Not(pos__b[2])))])
return True
if type(pos__b) is list:
if SCmp(cmds,i,('xJUMP_IF2_FALSE_POP', '*', 'ju', (':', 0,1), '*', ('::',2))):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b, (')(ELSE',), pos__e, (')ENDIF',)]])
return True
if SCmp(cmds,i,('xJUMP_IF2_FALSE_POP', ('!', '.L', '(IF', '*', ')ENDIF'), ('::',0))):
rpl(cmds,[[('(IF', And_j(pos__a[2], pos__b[1][1])), pos__b[2], (')ENDIF',)]])
return True
if SCmp(cmds,i,('xJUMP_IF2_FALSE_POP', '*', ('::',0))):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b, (')ENDIF',)]])
return True
if pos__a[0] == 'JUMP_IF2_TRUE_POP':
if SCmp(cmds,i,('JUMP_IF2_TRUE_POP','JUMP_IF2_TRUE_POP', ('::', 0))):
rpl(cmds,[(pos__b[0], pos__b[1], Or_j(pos__a[2], Not(pos__b[2])))])
return True
if SCmp(cmds,i,('JUMP_IF2_TRUE_POP','JUMP_IF2_FALSE_POP', ('::', 0))):
rpl(cmds,[(pos__b[0], pos__b[1], Or_j(pos__a[2], pos__b[2]))])
return True
if SCmp(cmds,i,('JUMP_IF2_TRUE_POP','JUMP_IF2_FALSE_POP_CONTINUE', ('::', 0))):
rpl(cmds,[(pos__b[0], pos__b[1], Or_j(pos__a[2], pos__b[2]))])
return True
if SCmp(cmds,i, ('JUMP_IF2_TRUE_POP', '*', ('::',0))):
rpl(cmds,[[('(IF', Not(pos__a[2])), pos__b, (')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_TRUE_POP', ('::',0))):
rpl(cmds,[('UNPUSH', (pos__a[2]))])
return True
if SCmp(cmds,i, ('JUMP_IF2_TRUE_POP', '*', 'JUMP_CONTINUE', (':',0,1), '*', \
('::',2))):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__e, (')(ELSE',),pos__b, (')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_TRUE_POP', 'JUMP_IF2_FALSE_POP_CONTINUE', (':',0,1), \
'*', ('::',1))):
ifexpr = Or_j(pos__a[2], pos__b[2])
rpl(cmds,[[('(IF', ifexpr), pos__d, (')ENDIF',), ('CONTINUE',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_TRUE_POP', '*', 'JUMP', (':',0,1), '*', ('::',2))):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__e, (')(ELSE',), pos__b, (')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_TRUE_POP', '*', 'JUMP_CONTINUE', ('::', 0))):
rpl(cmds,[[('(IF', Not(pos__a[2])), pos__b + [('CONTINUE',)], (')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_TRUE_POP', '>', 'JUMP_IF_FALSE', 'POP_TOP', ('::',0))):
rpl(cmds,[Or_j_s(pos__a[2], pos__b), pos__c,pos__d])
return True
if SCmp(cmds,i, ('JUMP_IF2_TRUE_POP', '*l', '>', 'JUMP_IF_FALSE', 'POP_TOP', ('::',0))):
rpl(cmds,[Or_j_s(pos__a[2], pos__c), pos__d,pos__e])
return True
if SCmp(cmds,i, ('JUMP_IF2_TRUE_POP', '*l', ('::',0))):
rpl(cmds,[('UNPUSH', pos__a[2])])
return True
if SCmp(cmds,i, ('JUMP_IF2_TRUE_POP', 'JUMP_IF2_TRUE_POP', \
'*n', 'JUMP', (':', 1,1), '*r', (':', 0,1), '*n',\
('::', 3))):
rpl(cmds,[[('(IF', Not(pos__a[2])), \
[('(IF',) + pos__b[2:], pos__f,\
(')(ELSE',), pos__c, (')ENDIF',)],\
(')(ELSE',), pos__h, (')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_TRUE_POP', 'JUMP_CONTINUE', ('::', 0))):
rpl(cmds,[('JUMP_IF2_FALSE_POP_CONTINUE', pos__b[1]) + pos__a[2:]])
return True
elif pos__a[0] == 'JUMP_IF2_FALSE_POP':
if pos__b[0][0] == 'J':
if pos__b[0] == 'J_SETUP_LOOP':
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', 'J_SETUP_LOOP', ('!', '(IF', '*c', ')ENDIF'),\
'POP_BLOCK', 'JUMP', (':', 0,0))): # 1
rpl(cmds,[pos__a,[('(WHILE',) + pos__c[0][1:], pos__c[1], (')ENDWHILE',)],pos__e,pos__f])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', 'J_SETUP_LOOP', ('!', '(IF', '*c', ')ENDIF'),\
'POP_BLOCK', '*n', (':', (0,1),0))) and CountJumpCache(pos__f[1],cmds) == 2: # 1
rpl(cmds,[pos__a,[('(WHILE',) + pos__c[0][1:], pos__c[1], (')(ELSE',), pos__e, (')ENDWHILE',)],pos__f])
return True
if SCmp(cmds,i, ('JUMP_IF2_TRUE_POP', 'J_SETUP_LOOP', ('!', '(IF', '*c', ')ENDIF'),\
'POP_BLOCK', '*n', (':', (0,1),0))) and CountJumpCache(pos__f[1],cmds) == 2: # 1
rpl(cmds,[pos__a,[('(WHILE',) + pos__c[0][1:], pos__c[1], (')(ELSE',), pos__e, (')ENDWHILE',)],pos__f])
return True
if SCmp(cmds,i,('JUMP_IF2_FALSE_POP','JUMP_IF2_FALSE_POP', ('::', 0))):
rpl(cmds,[(pos__b[0], pos__b[1], Or_j(Not(pos__a[2]), pos__b[2]))])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', 'JUMP_IF2_TRUE_POP_CONTINUE', '*l', ('::',0))):
rpl(cmds,[(pos__b[0], pos__b[1], And_j(pos__a[2], pos__b[2])),pos__c])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', 'JUMP_IF2_TRUE_POP_CONTINUE', ('::',0))):
rpl(cmds,[(pos__b[0], pos__b[1], And_j(pos__a[2], pos__b[2]))])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', 'JUMP_IF2_TRUE_POP', (':',0,1),\
'JUMP_IF2_FALSE_POP', (':', 1,1), '*', 'JUMP_CONTINUE', ('::',3))):
tt = Or_j( And_j(pos__a[2], pos__b[2]),pos__d[2])
rpl(cmds,[[('(IF', tt), pos__f + [('CONTINUE',)], (')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', 'JUMP_IF2_TRUE_POP', (':',0,1),\
'JUMP_IF2_FALSE_POP', ('::', 1))):
tt = Or_j( And_j(pos__a[2], pos__b[2]),pos__d[2])
rpl(cmds,[('JUMP_IF2_FALSE_POP', pos__d[1], tt) + pos__a[2:]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', 'JUMP_CONTINUE', ('::',0))):
rpl(cmds,[[('(IF',) + pos__a[2:], [('CONTINUE',)], (')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', 'JUMP', ('::',0))):
rpl(cmds,[('JUMP_IF2_TRUE_POP', pos__b[1]) + pos__a[2:]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', 'JUMP_IF2_FALSE_POP_CONTINUE', '*r',\
(':',0,1), 'JUMP_IF2_FALSE_POP_CONTINUE', '*r')) and pos__e[1] == pos__b[1]:
rpl(cmds,[[('(IF',) + pos__a[2:],
[('(IF',) +pos__b[2:], pos__c, (')ENDIF',)], (')(ELSE',),\
[('(IF',) +pos__e[2:], pos__f, (')ENDIF',)], (')ENDIF',)], ('JUMP_CONTINUE', pos__b[1])])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', 'JUMP_IF2_FALSE_POP_CONTINUE', \
(':', 0,1), '*n', ('::',1))):
rpl(cmds,[[('(IF',) + pos__a[2:], [('(IF', Not(pos__b[2])), [('CONTINUE',)], (')ENDIF',)], (')(ELSE',), pos__d,(')ENDIF',)],pos__e])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', 'J_SETUP_LOOP_FOR', (':', 5,1),\
'J_LOOP_VARS', '*n', 'JUMP_CONTINUE', (':', 3,1), \
'POP_BLOCK', '*r', (':', 0, 1))):
rpl(cmds,[pos__a, [('(FOR', pos__d[2], pos__b[2]) , pos__e, (')(ELSE',),pos__i, (')ENDFOR',)],pos__j])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', 'J_SETUP_LOOP_FOR', (':', 5,1),\
'J_LOOP_VARS', '*n', 'JUMP_CONTINUE', (':', 3,1),\
'POP_BLOCK', 'JUMP', (':', 0,1))):
rpl(cmds,[pos__a, [('(FOR', pos__d[2], pos__b[2]) , pos__e, (')ENDFOR',)],pos__i,pos__j])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', 'JUMP_IF2_TRUE_POP', ('::',0))):
rpl(cmds,[('JUMP_IF2_TRUE_POP', pos__b[1], And_j(pos__a[2], pos__b[2]))])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', 'JUMP_IF2_FALSE_POP', '*n', 'JUMP',\
(':', 1,1), '*n', 'JUMP_CONTINUE', (':', (0,3), 2))):
rpl(cmds,[pos__a,[('(IF',) + pos__b[2:], pos__c, (')(ELSE',),pos__f +[('CONTINUE',)], (')ENDIF',)],pos__h])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', 'JUMP_IF2_TRUE_POP', '*r', \
(':', 0,1), '*n', ('::', 1))):
rpl(cmds,[[('(IF',) + pos__a[2:],[('(IF', Not(pos__b[2])), pos__c, (')ENDIF',)],
(')(ELSE',), pos__e, (')ENDIF',) ]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', 'JUMP_IF2_FALSE_POP_CONTINUE', ('::', 0))):
rpl(cmds,[[('(IF',) + pos__a[2:], [('(IF', Not(pos__b[2])), [('CONTINUE',)], (')ENDIF',)],\
(')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', 'JUMP_IF2_FALSE_POP_CONTINUE', '*r', ('::', 0))):
rpl(cmds,[[('(IF',Not(pos__a[2])), [('(IF',) + pos__b[2:], [('CONTINUE',)], (')ENDIF',)] + pos__c,\
(')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', 'JUMP_IF2_TRUE_POP', \
'*n', 'JUMP', (':', 1,1), '*r', (':', 0,1), '*n',\
('::', 3))):
rpl(cmds,[[('(IF',) + pos__a[2:], \
[('(IF',) + pos__b[2:], pos__f,\
(')(ELSE',), pos__c, (')ENDIF',)],\
(')(ELSE',), pos__h, (')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', 'JUMP_IF2_FALSE_POP_CONTINUE', \
'*n', 'JUMP', (':', 0,1), '*n', ('::', 3))):
rpl(cmds,[[('(IF',) + pos__a[2:], \
[('(IF',) + pos__b[2:], pos__c, (')(ELSE',), [('CONTINUE',)],(')ENDIF',)],\
(')(ELSE',), pos__f, (')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', 'JUMP_IF2_FALSE_POP', 'JUMP_IF2_TRUE_POP', \
'*r', (':', 1, 1), '*n', ('::', (0,2)))):
rpl(cmds,[[('(IF',) + pos__a[2:],\
[('(IF',) + pos__b[2:], \
[('(IF', Not(pos__c[2])), pos__d, (')ENDIF',)],\
(')(ELSE',), pos__f, (')ENDIF',)],\
(')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', 'JUMP_IF2_TRUE_POP', '*n', 'JUMP',\
(':', 0,1), '*n', (':', 3,2), ('::',1))):
rpl(cmds,[[('(IF',) + pos__a[2:], \
[('(IF',) + pos__b[2:], [('CONTINUE',)], (')ENDIF',)] + pos__c, \
(')(ELSE',), pos__f, (')ENDIF',)], pos__g,pos__h])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', 'JUMP_IF2_TRUE_POP', '*n', 'JUMP',\
(':', 0,1), '*n', (':', 3,1), ('::',1))) and pos__b[1] == pos__h[1]:
rpl(cmds,[[('(IF',) + pos__a[2:], \
[('(IF',) + pos__b[2:], [('CONTINUE',)], (')ENDIF',)] + pos__c, \
(')(ELSE',), pos__f, (')ENDIF',)], pos__h])
return True
elif type(pos__b) is list:
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*', 'JUMP_IF2_FALSE_POP', '*', ('::', (0,2)))):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b+ [('(IF',) + pos__c[2:], pos__d, (')ENDIF',)], (')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*', 'ju', (':', 0,1), 'JUMP_IF2_FALSE_POP',\
'*', ('::', (2,4)))):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b, (')(ELSE',), [('(IF',) + pos__e[2:], pos__f, (')ENDIF',)],(')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*', 'JUMP_CONTINUE', ('::',0))):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b+ [('CONTINUE',)], (')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*', 'JUMP_CONTINUE', (':', 0, 1), \
'*', ('::',2))):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b, (')(ELSE',), pos__e, (')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*', 'JUMP_CONTINUE', (':', 0, 2), \
'*', ('::',2))):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b + [('CONTINUE',)], (')ENDIF',)],pos__d,pos__e])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*r')):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b, (')ENDIF',)], ('JUMP', pos__a[1])])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*', 'JUMP', (':',0,1), '*', ('::',2))):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b, (')(ELSE',), pos__e, (')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*l', 'J_SETUP_LOOP_FOR')):
rpl(cmds,[pos__a,pos__c])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*', 'JUMP_IF2_FALSE_POP_CONTINUE', '*r',\
('::', 0))):
rpl(cmds,[[('(IF',) +pos__a[2:] ,pos__b+ [('(IF',) + pos__c[2:], pos__d, \
(')ENDIF',), ('CONTINUE',)], (')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*', 'JUMP_IF2_FALSE_POP_CONTINUE', '*',\
('::', 0))):
rpl(cmds,[[('(IF',) +pos__a[2:] ,pos__b+ [('(IF',) + pos__c[2:], pos__d, \
(')(ELSE',), [('CONTINUE',)], \
(')ENDIF',)], (')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*l', ('::',0))):
if type(pos__b) is tuple:
rpl(cmds,[[pos__b, ('UNPUSH', pos__a[2])]])
return True
if type(pos__b) is list:
rpl(cmds,[pos__b + [('UNPUSH', pos__a[2])]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*', 'JUMP_IF2_FALSE_POP_CONTINUE', '*l',\
('::',0,))):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b, (')(ELSE',), \
[('(IF', Not(pos__c[2])), [('CONTINUE',)], (')ENDIF',)], \
(')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*n', 'J_SETUP_LOOP_FOR', \
(':', 6,1), 'J_LOOP_VARS', '*n', 'ju', (':', 4,1),\
'POP_BLOCK', 'ju', (':', 0,1))) and pos__c[1] != pos__j[1]:
rpl(cmds,[pos__a, pos__b+[('(FOR', pos__e[2], pos__c[2]) , pos__f, (')ENDFOR',)],pos__j,pos__k])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*n', 'JUMP', (':', 0, 1),\
'JUMP_IF2_FALSE_POP_CONTINUE', '*n', ('::', 2))): # 1
rpl(cmds,[[('(IF',) +pos__a[2:], pos__b, (')(ELSE',), [('(IF', Not(pos__e[2])), [('CONTINUE',)], (')ENDIF',)] + pos__f, (')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*n', 'JUMP_IF2_FALSE_POP_CONTINUE', ('::', 0))):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b + [('(IF', Not(pos__c[2])), [('CONTINUE',)], (')ENDIF',)],\
(')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*n', 'JUMP_IF2_TRUE_POP', '*n',\
'JUMP_CONTINUE', ('::', (0,2)))):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b + [('(IF', Not(pos__c[2])), pos__d+[('CONTINUE',)], (')ENDIF',)],\
(')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*n', 'JUMP_IF2_TRUE_POP', '*r',\
(':', 0, 1), '*n', ('::', 2))):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b + [('(IF', Not(pos__c[2])), pos__d, (')ENDIF',)], (')(ELSE',), pos__f,(')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*n', 'JUMP_IF2_FALSE_POP', '*r',\
(':', 0, 1), '*n', ('::', 2))):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b + [('(IF',) +pos__c[2:], pos__d, (')ENDIF',)], (')(ELSE',), pos__f, (')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*n', 'JUMP', (':', 0,1),\
'JUMP_IF2_FALSE_POP', '*n', ('::', 2))) and islooplabel(pos__e[1],cmds): # 1
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b, (')(ELSE',), \
[('(IF',) + pos__e[2:], pos__f, (')(ELSE',), [('CONTINUE',)], (')ENDIF',)], (')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*n', 'jc', (':', 0,1), '*n',\
(':', None, 0), ('::',2))) and pos__c[1] != pos__f[1] and pos__a[1] != pos__f[1]:
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b, (')(ELSE',), pos__e, (')ENDIF',)], ('JUMP_CONTINUE', pos__c[1]), pos__f,('JUMP_CONTINUE', pos__c[1])])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*n', 'ju', (':', 0,1), ('::',2))):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b, (')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*n', 'JUMP', (':', 0,1), \
'JUMP_CONTINUE', ('::', 2))):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b, (')(ELSE',), [('CONTINUE',)], (')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*n', 'JUMP_IF2_FALSE_POP', 'jc', \
(':', 0,1), '*n', ('::', 2))):
rpl(cmds,[[('(IF',) + pos__a[2:], \
pos__b + [('(IF',) + pos__c[2:], [('CONTINUE',)], (')ENDIF',)],(')(ELSE',), pos__f, (')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*n', 'jc', ('::', 0))):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b + [('CONTINUE',)], (')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*n', 'ju', (':', 0,1), \
'JUMP_IF2_FALSE_POP_CONTINUE', '*n', ('::', 2))):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b, (')(ELSE',), \
[('(IF',) + pos__e[2:], pos__f, (')(ELSE',),[('CONTINUE',)], (')ENDIF',)]]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*n', 'JUMP_IF2_FALSE_POP', \
'*n', 'jc', (':', 0,1), '*n', ('::', 2))) and pos__e[1] not in (pos__f[1],pos__h[1]):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b + \
[('(IF',) + pos__c[2:], pos__d+ [('CONTINUE',)], (')ENDIF',)], \
(')(ELSE',), pos__g, (')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*n', \
'JUMP_IF2_FALSE_POP', '*n', \
'JUMP_IF2_FALSE_POP', '*n', \
'JUMP_IF2_TRUE_POP', '*r', \
(':', 2,1), '*r', \
(':', (0, 4, 6), 2), '*r')) and CountJumpCache(pos__k[1],cmds) == 3:
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b +\
[('(IF',) + pos__c[2:], pos__d +\
[('(IF',) + pos__e[2:], pos__f +\
[('(IF', Not(pos__g[2])), pos__h, (')ENDIF',)],\
(')ENDIF',)],\
(')(ELSE',), pos__j, \
(')ENDIF',)],\
(')ENDIF',)] +pos__l])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*n',\
'JUMP_IF2_TRUE_POP', \
'JUMP_IF2_FALSE_POP', '*n',\
'JUMP_IF2_FALSE_POP', 'JUMP_CONTINUE', \
(':', 3,1), '*n', \
(':', (0,2, 5)))) and CountJumpCache(pos__j[1],cmds) == 3:
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b +\
[('(IF',) + pos__c[2:], [('PASS',)], (')(ELSE',),\
[('(IF',) + pos__d[2:], pos__e +\
[('(IF',) + pos__f[2:], [('CONTINUE',)], (')ENDIF',)],\
(')(ELSE',), pos__i,
(')ENDIF',)],\
(')ENDIF',)],\
(')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*n', \
'JUMP_IF2_FALSE_POP', '*n', 'JUMP', \
(':', 2,1), '*n', 'JUMP_CONTINUE', \
(':', 0,1), '*n', ('::', 4))):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b +\
[('(IF',) + pos__c[2:], pos__d, (')(ELSE',),
pos__g + [('CONTINUE',)], (')ENDIF',)],\
(')(ELSE',), pos__j, (')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*n','xJUMP_IF2_TRUE_POP', '*n', 'JUMP',\
(':', 0,1), '*n', (':', 4,2), ('::', 2))):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b +\
[('(IF',) + pos__c[2:], [('CONTINUE',)], (')ENDIF',)] + pos__d, \
(')(ELSE',), pos__g, (')ENDIF',)], pos__h,pos__i])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*n', 'JUMP_CONTINUE', (':', 0, 1),\
'*n', 'JUMP_CONTINUE')) and pos__c[1] == pos__f[1]:
rpl(cmds,[[('(IF', pos__a[2]), pos__b , (')(ELSE',), pos__e , (')ENDIF',)], pos__f])
return True
elif is_cmdmem(pos__b):
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '>', 'JUMP_IF_TRUE', 'POP_TOP',\
(':', 0,1), '>', ('::', 2))):
rpl(cmds,[Or_j_s(And_j_s(pos__a[2], pos__b),pos__f)])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '>', 'JUMP', (':', 0, 1), '*l', '>', ('::', 2))):
rpl(cmds,[('!COND_EXPR', pos__a[2], cmd2mem(pos__b),cmd2mem(pos__f))])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '>', 'JUMP', (':', 0, 1), '>', ('::', 2))):
rpl(cmds,[('!COND_EXPR', pos__a[2], cmd2mem(pos__b),cmd2mem(pos__e))])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '>', 'JUMP_IF_TRUE', 'POP_TOP',\
(':', 0, 1), '*l', '>', ('::', 2))):
rpl(cmds,[Or_j_s(And_j_s(pos__a[2], pos__b), pos__g)])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '>', 'JUMP_IF_TRUE', 'POP_TOP',\
(':', 0,1), 'JUMP_IF2_FALSE_POP', '>', \
'JUMP_IF_TRUE', 'POP_TOP', (':', 5,1), '>', \
('::', (2,7)))):
rpl(cmds,[Or_j_s(And_j_s(pos__a[2],pos__b), Or_j_s(And_j_s(pos__f[2],pos__g),pos__k))])
return True
elif pos__b[0] == '.:':
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', ('::',0))):
rpl(cmds,[('UNPUSH', (pos__a[2]))])
return True
else:
pass
elif pos__a[0] == 'JUMP_IF2_FALSE_POP_CONTINUE':
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP_CONTINUE', '*', ('::',0))):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b, (')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP_CONTINUE', '*c')):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b, (')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP_CONTINUE', '*n', ('::',0))):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b, (')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP_CONTINUE', '*r')):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b , (')ENDIF',)], ('JUMP_CONTINUE', pos__a[1])])
return True
elif pos__a[0] == 'JUMP_IF2_TRUE_POP_CONTINUE':
if SCmp(cmds,i, ('JUMP_IF2_TRUE_POP_CONTINUE', '*')):
rpl(cmds,[[('(IF',) + pos__a[2:], [('CONTINUE',)], (')ENDIF',)]+pos__b])
return True
if SCmp(cmds,i, ('JUMP_IF2_TRUE_POP_CONTINUE', 'JUMP_IF2_TRUE_POP', '*',\
'JUMP_CONTINUE', (':', 1, 2))) and pos__d[1] == pos__a[1]:
rpl(cmds,[[('(IF',) + pos__a[2:], [('CONTINUE',)],\
(')(ELSE',), [('(IF', Not(pos__b[2])), pos__c + [('CONTINUE',)], (')ENDIF',)](')ENDIF',)],pos__e])
return True
elif pos__a[0] == 'JUMP_IF_TRUE':
if SCmp(cmds,i, ('JUMP_IF_TRUE', 'POP_TOP', '.L', '>')):
rpl(cmds,[pos__a,pos__b,pos__d])
return True
elif pos__a[0] == 'JUMP_IF_FALSE':
if SCmp(cmds,i, ('JUMP_IF_FALSE', 'POP_TOP', '.L', '>')):
rpl(cmds,[pos__a,pos__b,pos__d])
return True
else:
if SCmp(cmds,i, ('ju', '.:', 'JUMP_CONTINUE')) and pos__a[1] == pos__c[1] and pos__a[1] != pos__b[1]:
rpl(cmds,[pos__b,pos__c])
return True
if SCmp(cmds,i, ('JUMP', ('::',0))):
rpl(cmds,[])
return True
if SCmp(cmds,i, ('JUMP', '*', ('::',0))):
rpl(cmds,[])
return True
if SCmp(cmds,i, ('JUMP', '*', 'JUMP', ('::',0))):
rpl(cmds,[])
return True
if SCmp(cmds,i, ('JUMP', 'POP_BLOCK', 'JUMP', ('::',0))):
rpl(cmds,[])
return True
if SCmp(cmds,i, ('JUMP', (':', 4, 1), 'xJUMP_IF2_FALSE_POP', '*', 'JUMP')):
rpl(cmds,[pos__a])
return True
if SCmp(cmds,i, ('JUMP_CONTINUE', 'JUMP_CONTINUE')) and pos__a[1] == pos__b[1]:
rpl(cmds,[pos__a])
return True
if SCmp(cmds,i, ('JUMP','JUMP')) and pos__a[1] == pos__b[1]:
rpl(cmds,[pos__a])
return True
if SCmp(cmds,i, ('JUMP', 'JUMP_CONTINUE')):
rpl(cmds,[pos__a])
return True
if SCmp(cmds,i, ('JUMP_CONTINUE', 'JUMP')):
rpl(cmds,[pos__a])
return True
if SCmp(cmds,i, ('JUMP', '.:', 'JUMP')) and pos__a[1] == pos__c[1]:
rpl(cmds,[pos__b,pos__c])
return True
if SCmp(cmds,i, ('JUMP_CONTINUE', '.:', 'JUMP')) and pos__a[1] == pos__c[1]:
rpl(cmds,[pos__b,pos__a])
return True
if SCmp(cmds,i, ('JUMP', '.:', 'JUMP_CONTINUE')) and pos__a[1] == pos__c[1]:
rpl(cmds,[pos__b,pos__c])
return True
if SCmp(cmds,i, ('JUMP_CONTINUE', '.:', 'JUMP_CONTINUE')) and pos__a[1] == pos__c[1]:
rpl(cmds,[pos__b,pos__c])
return True
if SCmp(cmds, i, ('JUMP', '.:', 'JUMP_IF2_FALSE_POP', '*', (':', 0), 'JUMP')) and pos__f[1] == pos__c[1]:
rpl(cmds,[pos__a,pos__b, [('(IF', pos__c[2]), pos__d, (')IF',)], pos__e, pos__f ])
return True
## if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP', '*', 'JUMP', (':', 0,1), '*r')):
## if type(pos__b) is list:
## rpl(cmds,[[('(IF',) + pos__a[2:], pos__b, (')ENDIF',)],pos__c, pos__d])
## else:
## rpl(cmds,[[('(IF',) + pos__a[2:], pos__b, (')ENDIF',)],pos__c, pos__d])
## return True
if pos__a[0] == 'JUMP_IF2_FALSE_POP_CONTINUE' or pos__a[0] == 'JUMP_IF2_TRUE_POP_CONTINUE':
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP_CONTINUE', 'JUMP_CONTINUE')) and pos__a[1] == pos__b[1]:
rpl(cmds,[('UNPUSH', pos__a[2]),pos__b])
return True
if SCmp(cmds,i, ('xJUMP_IF2_TRUE_POP_CONTINUE', 'xJUMP_IF2_FALSE_POP', \
'JUMP_CONTINUE')) and pos__a[1] == pos__c[1]:
rpl(cmds,[[('(IF', Or_j(pos__a[2], pos__b[2])), [('CONTINUE',)], (')ENDIF',)], ('JUMP', pos__b[1])])
return True
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP_CONTINUE', '*')):
rpl(cmds,[[('(IF', Not(pos__a[2])), [('CONTINUE',)], (')ENDIF',)]+pos__b])
return True
if pos__a[0] == 'JUMP_IF2_FALSE_POP' or pos__a[0] == 'JUMP_IF2_TRUE_POP':
if type(pos__b) is list:
if pos__c[0] == 'J_SETUP_LOOP':
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', '*n', 'J_SETUP_LOOP', \
(':', 5, 1), '*n', 'ju', ('::', 0))):
rpl(cmds,[[('(IF',) + pos__a[2:],pos__b + [('(WHILE', TRUE), pos__e, (')ENDWHILE',)], (')ENDIF',)]])
return True
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', '*n', 'J_SETUP_LOOP', \
('!', '(IF', '*c', ')ENDIF'), 'POP_BLOCK', '*n', \
'JUMP_CONTINUE', (':', 0,0))) and pos__c[1] != pos__a[1] != pos__g[1]:
rpl(cmds,[pos__a, pos__b + [('(WHILE',) + pos__d[0][1:], pos__d[1][:-1], (')(ELSE',), pos__f, (')ENDWHILE',)],pos__g,pos__h])
return True
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', '*n', 'J_SETUP_LOOP', \
('!', '(IF', '*r', ')ENDIF'), 'POP_BLOCK', ('::', (0,2)))):
rpl(cmds,[pos__a, pos__b + [('(WHILE',) + pos__d[0][1:], pos__d[1][:-1], (')ENDWHILE',)],pos__f])
return True
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', '*n', 'J_SETUP_LOOP', \
('!', '(IF', '*r', ')ENDIF'), 'POP_BLOCK', 'JUMP', (':', 0, 0))) and\
pos__a[1] != pos__c[1] and pos__a[1] != pos__f[1]:
rpl(cmds,[pos__a,pos__b+[('(WHILE',) + pos__d[0][1:], pos__d[1], (')ENDWHILE',)],pos__f,pos__g])
return True
elif pos__c[0] == 'JUMP':
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', '*n', 'JUMP', (':', 0,1),\
'*n', 'JUMP_CONTINUE', ('::', 2))):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b , (')(ELSE',), pos__e + [('CONTINUE',)], (')ENDIF',)]])
return True
if SCmp(cmds,i, ('xJUMP_IF2_TRUE_POP', '*n', 'JUMP', (':', 0,1),\
'*n', 'JUMP_CONTINUE', ('::', 2))):
rpl(cmds,[[('(IF', Not(pos__a[2])), pos__b, (')(ELSE',), pos__e + [('CONTINUE',)], (')ENDIF',)]])
return True
if SCmp(cmds,i, ('xJUMP_IF2_TRUE_POP', '*n', 'JUMP', (':', 0,1),\
'JUMP_CONTINUE', ('::', 2))):
rpl(cmds,[[('(IF', Not(pos__a[2])), pos__b, (')(ELSE',), [('CONTINUE',)], (')ENDIF',)]])
return True
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', '*n', 'JUMP', (':', 0, 1),\
'xJUMP_IF2_TRUE_POP_CONTINUE', (':', 2,1), '*n', \
('::', 4))):
rpl(cmds,[[('(IF', pos__a[2]), pos__b, (')(ELSE',), [('(IF', pos__e[2]), [('CONTINUE',)], (')ENDIF',)]+pos__g, (')ENDIF',)]])
return True
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', '*n', 'JUMP', (':', 0, 1),\
'xJUMP_IF2_TRUE_POP_CONTINUE', (':', 2,1), \
('::', 4))):
rpl(cmds,[[('(IF', pos__a[2]), pos__b, (')(ELSE',), [('(IF', pos__e[2]), [('CONTINUE',)], (')ENDIF',)], (')ENDIF',)]])
return True
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', '*n', 'JUMP', (':', 0,1),\
'*n', 'JUMP_CONTINUE')) and pos__c[1] not in (pos__a[1], pos__d[1], pos__f[1]):
rpl(cmds,[[('(IF', pos__a[2]), pos__b, (')(ELSE',), pos__e + [('CONTINUE',)], (')ENDIF',)], pos__c])
return True
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', '*n', 'JUMP', (':', 0,1),\
'JUMP_CONTINUE')) and pos__c[1] not in (pos__a[1], pos__d[1], pos__e[1]):
rpl(cmds,[[('(IF', pos__a[2]), pos__b, (')(ELSE',), [('CONTINUE',)], (')ENDIF',)], pos__c])
return True
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', '*n', 'JUMP', (':', 0,1), '*r', \
'.:')) and pos__c[1] != pos__f[1]:
rpl(cmds,[[('(IF', pos__a[2]), pos__b , (')(ELSE',), pos__e, (')ENDIF',)], pos__c,pos__f])
return True
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', '*n', 'JUMP', (':', 0,1), '*n',\
'jc', ('::', 2))):
rpl(cmds,[[('(IF', pos__a[2]), pos__b , (')(ELSE',), pos__e + [('CONTINUE',)], (')ENDIF',)]])
return True
elif is_cmdmem(pos__c):
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', '*l', '>', 'JUMP_IF_TRUE', 'POP_TOP',\
(':', 0,1), '>', ('::', 3))):
rpl(cmds,[Or_j_s(And_j_s(pos__a[2], pos__c), pos__g)])
return True
elif pos__c[0] == '.:':
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', '*r', ('::',0))):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b, (')ENDIF',)]])
return True
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', '*r', (':', None,0), 'END_FINALLY', ('::', 0))):
rpl(cmds,[[('(IF', pos__a[2]), pos__b, (')ENDIF',)], pos__c,pos__d])
return True
if SCmp(cmds,i, ('xJUMP_IF2_TRUE_POP', '*r', '.:', '*n', (':', 0, 0))):
rpl(cmds,[[('(IF', Not(pos__a[2])), pos__b, (')ENDIF',)], ('JUMP', pos__a[1]), pos__c,pos__d,pos__e])
return True
elif pos__c[0] == 'JUMP_CONTINUE':
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', '*n', 'JUMP_CONTINUE')):
rpl(cmds,[[('(IF', pos__a[2]), pos__b + [('CONTINUE',)], (')ENDIF',)], ('JUMP', pos__a[1])])
return True
elif pos__c[0] == 'J_SETUP_LOOP_FOR':
if SCmp(cmds,i, ('xJUMP_IF2_TRUE_POP', '**n', 'J_SETUP_LOOP_FOR', (':', 6,1),\
'J_LOOP_VARS', '**n', 'JUMP_CONTINUE', (':', 4, 1),\
'POP_BLOCK', 'JUMP', (':', 0,1), '*n', (':', 2,1),\
'JUMP')):
cmds[i:i+9] = [pos__a,pos__b+[('(FOR', pos__e[2], pos__c[2]), pos__f[:], (')ENDFOR',)]]
return True
if SCmp(cmds,i, ('xJUMP_IF2_TRUE_POP', '*n', 'J_SETUP_LOOP_FOR', \
(':', 6, 1), 'J_LOOP_VARS', '*n', 'JUMP_CONTINUE', \
(':', 4, 1), 'POP_BLOCK', 'JUMP_CONTINUE', (':', 0, 0))) and \
pos__a[1] != pos__c[1] != pos__j[1]:
rpl(cmds,[pos__a, pos__b +[('(FOR', pos__e[2], pos__c[2]), pos__f[:], (')ENDFOR',)],pos__j, pos__k])
return True
elif pos__e[0] == 'JUMP':
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', '*n','xJUMP_IF2_TRUE_POP', '*n', 'JUMP',\
(':', 0,1), '*n', (':', 4,1), ('::', 2))):
rpl(cmds,[[('(IF',) + pos__a[2:], pos__b +\
[('(IF',) + pos__c[2:], [('CONTINUE',)], (')ENDIF',)] + pos__d, \
(')(ELSE',), pos__g, (')ENDIF',)],pos__i])
return True
elif pos__d[0] == '.:':
if SCmp(cmds,i, ('xJUMP_IF2_TRUE_POP', '*n',\
'xJUMP_IF2_TRUE_POP_CONTINUE', ('::', 0))):
rpl(cmds,[[('(IF', Not(pos__a[2])), pos__b + [('(IF', pos__c[2]), [('CONTINUE',)], (')ENDIF',)], (')ENDIF',)]])
return True
elif pos__e[0] == '.:':
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', '*n', 'xJUMP_IF2_TRUE_POP', '*r',\
(':', 0,1), '*r', ('::', 2))):
rpl(cmds,[[('(IF', pos__a[2]), pos__b + [('(IF', Not(pos__c[2])), pos__d, (')ENDIF',)], (')(ELSE',), pos__f , (')ENDIF',)]])
return True
elif pos__f[0] == 'JUMP_CONTINUE':
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', '**n', 'xJUMP_IF2_FALSE_POP', '**n', \
'xJUMP_IF2_FALSE_POP', 'JUMP_CONTINUE', (':', 0, 1), \
'**n', ('::', (2, 4)))):
rpl(cmds,[[('(IF', pos__a[2]), pos__b + [('(IF', pos__c[2]), \
pos__d + [('(IF', pos__e[2]), [('CONTINUE',)], (')ENDIF',)], \
(')ENDIF',)],\
(')(ELSE',), pos__h, (')ENDIF',)]])
return True
elif pos__g[0] == 'JUMP_CONTINUE':
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', '**n', 'xJUMP_IF2_FALSE_POP', '**n', \
'xJUMP_IF2_FALSE_POP', '**n', 'JUMP_CONTINUE', (':', 0, 1), \
'**n', ('::', (2, 4)))):
rpl(cmds,[[('(IF', pos__a[2]), pos__b + [('(IF', pos__c[2]), \
pos__d + [('(IF', pos__e[2]), pos__f + [('CONTINUE',)], (')ENDIF',)], \
(')ENDIF',)],\
(')(ELSE',), pos__i, (')ENDIF',)]])
return True
elif pos__b[0] == '(BEGIN_TRY':
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', '(BEGIN_TRY', '*n', ')END_BEGIN_TRY',\
'J_IF_NO_EXCEPT_IN_TRY', '*e', 'J_AFTER_EXCEPT_HANDLE', \
'END_FINALLY', (':', 4, 1), '*r', (':', 0, 1), '*r', ('::', 6))):
rpl(cmds,[[('(IF', pos__a[2]), concatenate_try_except(pos__c,pos__f, pos__j), (')(ELSE',), pos__l, (')ENDIF',)]])
return True
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', '(BEGIN_TRY', '*n', ')END_BEGIN_TRY',\
'J_IF_NO_EXCEPT_IN_TRY', '*e', 'J_AFTER_EXCEPT_HANDLE', \
'END_FINALLY', (':', 4, 1), '*r', (':', 0, 1), '*n', ('::', 6))):
rpl(cmds,[[('(IF', pos__a[2]), concatenate_try_except(pos__c,pos__f, pos__j), (')(ELSE',), pos__l, (')ENDIF',)]])
return True
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', '(BEGIN_TRY', '*n', ')END_BEGIN_TRY',\
'J_IF_NO_EXCEPT_IN_TRY', '*e', 'J_AFTER_EXCEPT_HANDLE', \
'END_FINALLY', 'JUMP', (':', 0,None))) and pos__e[1] == pos__i[1]:
rpl(cmds,[pos__a, concatenate_try_except(pos__c, pos__f),pos__j])
return True
elif pos__b[0] == 'J_SETUP_LOOP_FOR':
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', 'J_SETUP_LOOP_FOR', 'J_LOOP_VARS', \
'*', (':', 2,1), 'POP_BLOCK', '*r', (':', 0,1), '*',(':', 1,1))):
rpl(cmds,[pos__a, [('(FOR', pos__c[2], pos__b[2]) , pos__d, (')(ELSE',),pos__g, (')ENDFOR',)],pos__h,pos__i,pos__j])
return True
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', 'J_SETUP_LOOP_FOR', 'J_LOOP_VARS', \
'*r', (':', 2, 1), 'POP_BLOCK', 'JUMP', (':', 0, 1))) and\
pos__g[1] not in (pos__a[1], pos__b[1], pos__c[1]):
rpl(cmds,[pos__a, [('(FOR', pos__c[2], pos__b[2]) , pos__d, (')ENDFOR',)],pos__g,pos__h])
return True
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', 'J_SETUP_LOOP_FOR', (':', 5, 1),\
'J_LOOP_VARS', '*n', 'JUMP_CONTINUE', (':', 3, 1),\
'POP_BLOCK', '*n', 'JUMP_CONTINUE', (':', 0, 1), '*n',\
(':', 1,1), ('::', 9))):
rpl(cmds,[pos__a, [('(FOR', pos__d[2], pos__b[2]), pos__e[:], (')(ELSE',), pos__i,(')ENDFOR',)],pos__j,pos__k,pos__l,cmds[i+12]])
return True
if SCmp(cmds,i, ('xJUMP_IF2_TRUE_POP', 'J_SETUP_LOOP_FOR', (':', 5, 1),\
'J_LOOP_VARS', '*n', 'JUMP_CONTINUE', (':', 3, 1),\
'POP_BLOCK', 'JUMP_CONTINUE', (':', 0, 0))) and \
pos__i[1] not in (pos__a[1], pos__b[1], pos__d[1], pos__f[1]):
rpl(cmds,[pos__a, [('(FOR', pos__d[2], pos__b[2]), pos__e[:], (')ENDFOR',)],pos__i,pos__j])
return True
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', 'J_SETUP_LOOP_FOR', (':', 5, 1),\
'J_LOOP_VARS', '*n', 'JUMP_CONTINUE', (':', 3, 1), \
'POP_BLOCK', '*n', 'JUMP', ('::', 0))) and pos__b[1] != pos__j[1] and \
pos__b[1] not in (pos__a[1],pos__c[1], pos__d[1]): # 1
rpl(cmds,[pos__a, [('(FOR', pos__d[2], pos__b[2]), pos__e[:], (')(ELSE',), pos__i,(')ENDFOR',)],pos__j,pos__k])
return True
elif pos__b[0] == 'J_SETUP_LOOP':
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', 'J_SETUP_LOOP', \
(':', 4, 1), '*n', 'ju', ('::', 0))):
rpl(cmds,[[('(IF',) + pos__a[2:],[('(WHILE', TRUE), pos__d, (')ENDWHILE',)], (')ENDIF',)]])
return True
elif pos__b[0] == 'JUMP':
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', 'JUMP')) and pos__a[1] == pos__b[1]:
rpl(cmds,[('UNPUSH', pos__a[2]),pos__b])
return True
if SCmp(cmds,i, ('xJUMP_IF2_TRUE_POP', 'JUMP', (':', 0,1),\
'*n', 'JUMP_CONTINUE', ('::', 1))):
rpl(cmds,[[('(IF', pos__a[2]), pos__e + [('CONTINUE',)], (')ENDIF',)]])
return True
if SCmp(cmds,i, ('xJUMP_IF2_TRUE_POP', 'JUMP', (':', 0,1),\
'JUMP_CONTINUE', ('::', 1))):
rpl(cmds,[[('(IF', pos__a[2]), [('CONTINUE',)], (')ENDIF',)]])
return True
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', 'JUMP', (':', 0, 1),\
'xJUMP_IF2_TRUE_POP_CONTINUE', (':', 1,1), '*n', \
('::', 3))):
rpl(cmds,[[('(IF', Not(pos__a[2])),[('(IF', pos__d[2]), [('CONTINUE',)], (')ENDIF',)]+pos__f, (')ENDIF',)]])
return True
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', 'JUMP', (':', 0, 1),\
'xJUMP_IF2_TRUE_POP_CONTINUE', (':', 1,1), \
('::', 3))):
rpl(cmds,[[('(IF', Not(pos__a[2])),[('(IF', pos__d[2]), [('CONTINUE',)], (')ENDIF',)], (')ENDIF',)]])
return True
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', 'JUMP', (':', 0,1),\
'*n', 'JUMP_CONTINUE')) and pos__b[1] not in (pos__a[1], pos__c[1], pos__e[1]):
rpl(cmds,[[('(IF', pos__a[2]), [('PASS',)], (')(ELSE',), pos__d + [('CONTINUE',)], (')ENDIF',)], pos__b])
return True
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', 'JUMP', (':', 0,1),\
'JUMP_CONTINUE')) and pos__b[1] not in (pos__a[1], pos__c[1], pos__d[1]):
rpl(cmds,[[('(IF', pos__a[2]), [('PASS',)], (')(ELSE',), [('CONTINUE',)], (')ENDIF',)], pos__b])
return True
elif pos__b[0][0] == 'J':
if SCmp(cmds,i, ('xJUMP_IF2_TRUE_POP',\
'xJUMP_IF2_TRUE_POP_CONTINUE', ('::', 0))):
rpl(cmds,[[('(IF', Not(pos__a[2])), [('(IF', pos__b[2]), [('CONTINUE',)], (')ENDIF',)], (')ENDIF',)]])
return True
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', 'xJUMP_IF2_TRUE_POP', '*r',\
(':', 0,1), '*r', ('::', 1))):
rpl(cmds,[[('(IF', pos__a[2]), [('(IF', Not(pos__b[2])), pos__c, (')ENDIF',)], (')(ELSE',), pos__e , (')ENDIF',)]])
return True
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', 'xJUMP_IF2_FALSE_POP', '*n',\
'ju', (':', 0, 1), '*n', (':', 1, 1),\
'*n', ('::', 3))):
rpl(cmds,[[('(IF', pos__a[2]),[('(IF', pos__b[2]), pos__c, (')(ELSE',), pos__h, (')ENDIF',)], (')(ELSE',), pos__f, (')ENDIF',)]])
return True
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', 'xJUMP_IF2_FALSE_POP', \
'ju', (':', 0, 1), '*n', (':', 1, 1),\
'*n', ('::', 2))):
pos__c,pos__d,pos__e,pos__f,pos__g,pos__h,pos__i = [('PASS',)],pos__c,pos__d,pos__e,pos__f,pos__g,pos__h
rpl(cmds,[[('(IF', pos__a[2]),[('(IF', pos__b[2]), pos__c, (')(ELSE',), pos__h, (')ENDIF',)], (')(ELSE',), pos__f, (')ENDIF',)]])
return True
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', 'xJUMP_IF2_FALSE_POP', '**n', \
'xJUMP_IF2_FALSE_POP', 'JUMP_CONTINUE', (':', 0, 1), \
'**n', ('::', (1, 3)))):
rpl(cmds,[[('(IF', pos__a[2]), [('(IF', pos__b[2]), \
pos__c + [('(IF', pos__d[2]), [('CONTINUE',)], (')ENDIF',)], \
(')ENDIF',)],\
(')(ELSE',), pos__g, (')ENDIF',)]])
return True
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', 'J_COND_PUSH', (':', 0, 1),\
'>', ('::', 1))):
rpl(cmds,[('!COND_EXPR', pos__a[2], ('!COND_EXPR',) + pos__b[2:] + (cmd2mem(pos__d),), cmd2mem(pos__d))])
return True
elif pos__b[0] == 'RETURN_VALUE':
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', 'RETURN_VALUE', ('::',0))) and len(pos__b) == 2:
rpl(cmds,[[('(IF', pos__a[2]), [pos__b], (')ENDIF',)]])
return True
elif is_cmdmem(pos__b):
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', '>', 'JUMP', ('::', 0))) and pos__c[1] != pos__d[1]:
rpl(cmds,[('J_COND_PUSH', pos__c[1], pos__a[2], cmd2mem(pos__b))])
return True
else:
pass
if added_pass:
if SCmp(cmds,i, ('xJUMP_IF2_TRUE_POP_CONTINUE',)):
rpl(cmds,[[('(IF', pos__a[2]), [('CONTINUE',)], (')ENDIF',)]])
return True
if SCmp(cmds,i, ('JUMP_IF2_TRUE_POP',)) and islooplabel(pos__a[1],cmds):
rpl(cmds,[('JUMP_IF2_TRUE_POP_CONTINUE',) + pos__a[1:]])
return True
if SCmp(cmds,i, ('JUMP_IF2_FALSE_POP',)) and islooplabel(pos__a[1],cmds):
rpl(cmds,[('JUMP_IF2_FALSE_POP_CONTINUE',) + pos__a[1:]])
return True
if SCmp(cmds,i, ('JUMP',)) and islooplabel(pos__a[1],cmds):
rpl(cmds,[('JUMP_CONTINUE',) + pos__a[1:]])
return True
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', 'xJUMP_IF2_FALSE_POP', 'JUMP_CONTINUE', \
(':', 0,0), '*n', (':', 1,0))):
rpl(cmds,[pos__a,[('(IF', pos__b[2]), [('CONTINUE',)], (')ENDIF',)],('JUMP', pos__b[1]), pos__d,pos__e,pos__f])
return True
if SCmp(cmds,i, ('xJUMP_IF2_FALSE_POP', 'JUMP_CONTINUE', '.:')) and pos__a[1] != pos__b[1] != pos__c[1]:
rpl(cmds,[[('(IF', pos__a[2]), [('CONTINUE',)], (')ENDIF',)],('JUMP', pos__a[1]),pos__c])
return True
return False
def process_j_setup_loop_for(cmds,i):
global pos__a,pos__b,pos__c,pos__d,pos__e,pos__f,pos__g,pos__h,pos__i,pos__j,pos__k,pos__l
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', (':',4,1), 'J_LOOP_VARS', '*', 'ju',
(':',2,1), 'POP_BLOCK', ('::',0))):
rpl(cmds,[[('(FOR', pos__c[2], pos__a[2]), pos__d[:], (')ENDFOR',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', 'J_LOOP_VARS', '*', (':',1,1), 'POP_BLOCK',\
'JUMP')) and pos__a[1] == pos__f[1]:
rpl(cmds,[[('(FOR', pos__b[2], pos__a[2]), pos__c[:], (')ENDFOR',)],pos__f])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', (':',4,1), 'J_LOOP_VARS', '*n',\
'ju', (':',2,1), 'POP_BLOCK', '*n', 'jc', ('::',0)))and\
pos__i[1] != pos__e[1]:
rpl(cmds,[[('(FOR', pos__c[2], pos__a[2]), pos__d[:], (')(ELSE',), pos__h + [('CONTINUE',)],(')ENDFOR',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', 'J_LOOP_VARS', '*', (':', 1, 1),\
'POP_BLOCK', ('::',0))):
rpl(cmds,[[('(FOR', pos__b[2], pos__a[2]), pos__c[:], (')ENDFOR',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', (':', 3,0), 'J_LOOP_VARS',\
'xJUMP_IF2_FALSE_POP_CONTINUE', '*r')):
rpl(cmds,[pos__a,pos__b,pos__c,[('(IF',) + pos__d[2:], pos__e, (')ENDIF',)], ('JUMP_CONTINUE',pos__d[1])])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', (':', 3,0), 'J_LOOP_VARS',\
'xJUMP_IF2_FALSE_POP', '*r')):
rpl(cmds,[pos__a,pos__b,pos__c,[('(IF',) + pos__d[2:], pos__e, (')ENDIF',)], ('JUMP',pos__d[1])])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', 'J_LOOP_VARS', '*', (':',1,1), 'POP_BLOCK', ('::', 0))):
rpl(cmds,[[('(FOR', pos__b[2], pos__a[2]) , pos__c, (')ENDFOR',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', (':', 3, 2), 'J_LOOP_VARS', \
'xJUMP_IF2_TRUE_POP_CONTINUE', '*', 'JUMP_CONTINUE', \
(':', 2, 1), 'POP_BLOCK', ('::', 0))) and pos__d[1] == pos__f[1]:
rpl(cmds,[[('(FOR', pos__c[2], pos__a[2]) , [('(IF',) +pos__d[2:],\
[('CONTINUE',)],(')ENDIF',)]+ pos__e, (')ENDFOR',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', (':', 3, 1), 'J_LOOP_VARS', \
'JUMP_CONTINUE', (':', 2, 1), 'POP_BLOCK', ('::', 0))):
rpl(cmds,[[('(FOR', pos__c[2], pos__a[2]) , [('PASS',)], (')ENDFOR',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', 'J_LOOP_VARS', '*n', (':', 1,1),\
'POP_BLOCK', '*r', ('::', 0))):
rpl(cmds,[[('(FOR', pos__b[2], pos__a[2]) , pos__c, (')(ELSE',),pos__f, (')ENDFOR',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', (':', 4,1), 'J_LOOP_VARS', '*n',\
'xJUMP_IF2_FALSE_POP_CONTINUE', '*n', (':', 2, 1),\
'POP_BLOCK', ('::', 0))): # 1
rpl(cmds,[[('(FOR', pos__c[2], pos__a[2]) , \
pos__d + [('(IF',) + pos__e[2:], pos__f, (')ENDIF',)], \
(')ENDFOR',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', (':', 4,2), 'J_LOOP_VARS', '*n',\
'xJUMP_IF2_FALSE_POP_CONTINUE', '*n', 'JUMP_CONTINUE')):
rpl(cmds,[pos__a,pos__b,pos__c,pos__d + [('(IF',) +pos__e[2:], pos__f, (')ENDIF',)], pos__g])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', (':', 3, 2), 'J_LOOP_VARS', \
'xJUMP_IF2_TRUE_POP')):
if type(cmds[i+4]) is list:
cmds[i:i+5] = [pos__a,pos__b,pos__c, [('(IF',) +pos__d[2:], [('CONTINUE',)], (')ENDIF',)]+cmds[i+4]]
else:
cmds[i:i+4] = [pos__a,pos__b,pos__c, [('(IF',) +pos__d[2:], [('CONTINUE',)], (')ENDIF',)]]
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', (':', 3,1), 'J_LOOP_VARS', \
'xJUMP_IF2_TRUE_POP')):
if type(cmds[i+4]) is list:
cmds[i:i+5] = [pos__a,pos__c, [('(IF',) +pos__d[2:], [('CONTINUE',)], (')ENDIF',)]+cmds[i+4]]
else:
cmds[i:i+4] = [pos__a,pos__c, [('(IF',) +pos__d[2:], [('CONTINUE',)], (')ENDIF',)]]
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', (':', 4,2), 'J_LOOP_VARS', '*n',\
'xJUMP_IF2_FALSE_POP_CONTINUE', '*n')):
rpl(cmds,[pos__a,pos__b,pos__c,pos__d+ [('(IF', Not(pos__e[2])), [('CONTINUE',)], (')ENDIF',)]+pos__f])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', (':', 4,0), 'J_LOOP_VARS', '*n', 'JUMP')):
rpl(cmds,[pos__a,pos__b,pos__c,pos__d,('JUMP_CONTINUE',) + pos__e[1:]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', 'J_LOOP_VARS', '*r', (':', 1,1),\
'POP_BLOCK', '*n', ('::', 0))):
rpl(cmds,[[('(FOR', pos__b[2], pos__a[2]), pos__c[:], (')(ELSE',),pos__f,(')ENDFOR',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', (':', 4,1), 'J_LOOP_VARS', '*n',\
'JUMP_CONTINUE', (':', 2,1), 'POP_BLOCK', '*n', ('::', 0))):
rpl(cmds,[[('(FOR', pos__c[2], pos__a[2]), pos__d[:], (')(ELSE',),pos__h,(')ENDFOR',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', (':', 4,1), 'J_LOOP_VARS', '*n',\
'ju', (':', 2,1), 'POP_BLOCK', '*r', ('::', 0))):
rpl(cmds,[[('(FOR', pos__c[2], pos__a[2]), pos__d[:], (')(ELSE',),pos__h,(')ENDFOR',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', (':', 4, 1), 'J_LOOP_VARS', '*n', 'ju',\
(':', 2,1), 'POP_BLOCK', '*n', 'ju')) and pos__a[1] == pos__i[1]:
rpl(cmds,[[('(FOR', pos__c[2], pos__a[2]), pos__d[:], (')(ELSE',),pos__h,(')ENDFOR',)],pos__i])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', (':', 4,1), 'J_LOOP_VARS', '*n',\
'JUMP_CONTINUE', (':', 2, 1), 'POP_BLOCK', 'JUMP')) and pos__h[1] == pos__a[1]:
rpl(cmds,[[('(FOR', pos__c[2], pos__a[2]), pos__d[:], (')ENDFOR',)],pos__h])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', (':', 4,1), 'J_LOOP_VARS', '*n',\
'JUMP_CONTINUE', (':', 2, 1), 'POP_BLOCK', 'JUMP_CONTINUE')) and pos__h[1] == pos__a[1]:
rpl(cmds,[[('(FOR', pos__c[2], pos__a[2]), pos__d[:], (')ENDFOR',)],pos__h])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', (':', 4,1), 'J_LOOP_VARS', '*n',\
'JUMP_CONTINUE', (':', 2,1), 'POP_BLOCK', 'jc',\
('::', 0))) and pos__h[1] not in (pos__b[1],pos__f[1],pos__i[1]):
rpl(cmds,[[('(FOR', pos__c[2], pos__a[2]), pos__d[:], (')(ELSE',), [('CONTINUE',)],(')ENDFOR',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', (':', 4,1), 'J_LOOP_VARS', '*n',\
'JUMP_CONTINUE', (':', 2,1), 'POP_BLOCK', 'ju', \
'.:', 'END_FINALLY', ('::', 0))) and \
pos__h[1] not in (pos__a[1], pos__b[1],pos__c[1],pos__e[1],pos__f[1]) and\
pos__i[1] not in (pos__a[1], pos__b[1],pos__c[1],pos__e[1],pos__f[1]):
rpl(cmds,[[('(FOR', pos__c[2], pos__a[2]), pos__d[:], (')ENDFOR',)],pos__h,pos__i,pos__j])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', (':', 4,1), 'J_LOOP_VARS', '*n',\
'JUMP_CONTINUE', (':', 2, 1), 'POP_BLOCK', '*r',\
'.:', 'END_FINALLY', ('::', 0))) and pos__i[1] not in [pos__b[1], pos__f[1],pos__k[1]]:
rpl(cmds,[[('(FOR', pos__c[2], pos__a[2]), pos__d[:], (')(ELSE',), pos__h,(')ENDFOR',)],pos__i,pos__j])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', 'J_LOOP_VARS', '*r', (':', 1,1), \
'POP_BLOCK', '*r', ('::', 0))):
rpl(cmds,[[('(FOR', pos__b[2], pos__a[2]), pos__c[:], (')(ELSE',), pos__f,(')ENDFOR',)]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', 'J_LOOP_VARS', '*r', (':', 1,1),\
'POP_BLOCK', 'JUMP_CONTINUE')) and pos__a[1] == pos__f[1]:
rpl(cmds,[[('(FOR', pos__b[2], pos__a[2]), pos__c[:], (')ENDFOR',)],pos__f])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', 'J_LOOP_VARS', '*r', (':', 1,1),\
'POP_BLOCK', 'JUMP')) and pos__a[1] == pos__f[1]:
rpl(cmds,[[('(FOR', pos__b[2], pos__a[2]), pos__c[:], (')ENDFOR',)],pos__f])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', (':', 4,1), 'J_LOOP_VARS', '*n',\
'JUMP_CONTINUE', (':', 2,1), 'POP_BLOCK', '*r', '.:')) \
and pos__i[1] != pos__a[1]:
rpl(cmds,[[('(FOR', pos__c[2], pos__a[2]), pos__d[:], (')(ELSE',), pos__h, (')ENDFOR',)],pos__i])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', (':', 4,2), 'J_LOOP_VARS', '*n',\
'xJUMP_IF2_TRUE_POP')):
rpl(cmds,[pos__a,pos__b,pos__c,pos__d,('JUMP_IF2_TRUE_POP_CONTINUE',) + pos__e[1:]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', (':', 4,1), 'J_LOOP_VARS', '*n',\
'xJUMP_IF2_TRUE_POP')):
rpl(cmds,[pos__a,pos__c,pos__d,('JUMP_IF2_TRUE_POP_CONTINUE',) + pos__e[1:]])
return True
if SCmp(cmds,i, ('J_SETUP_LOOP_FOR', (':', 4, 1), 'J_LOOP_VARS', '*n', \
'JUMP_CONTINUE', (':', 2, 1), 'POP_BLOCK', '*r',\
'END_FINALLY', ('::', 0))):
rpl(cmds,[[('(FOR', pos__c[2], pos__a[2]), pos__d[:], (')(ELSE',), pos__h, (')ENDFOR',)],pos__i])
return True
return False
def process_begin_try(cmds,i):
global pos__a,pos__b,pos__c,pos__d,pos__e,pos__f,pos__g,pos__h,pos__i,pos__j,pos__k,pos__l
if SCmp(cmds,i, ('(BEGIN_TRY', '*', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'JUMP_IF_NOT_EXCEPTION_POP', '*', 'JUMP_CONTINUE', (':', 4, 1),\
'END_FINALLY', (':', 3, 1), '*r')):
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',) + pos__e[2:], pos__f, (')(ELSE',),pos__k, (')ENDTRY',)],pos__g])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'JUMP_IF_NOT_EXCEPTION_POP', '*', 'JUMP', (':', 4, 1),\
'END_FINALLY', (':', 3, 1), '*r')) and pos__g[1] not in (pos__d[1],pos__e[1]):
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',) + pos__e[2:], pos__f, (')(ELSE',),pos__k, (')ENDTRY',)],pos__g])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'JUMP_IF_NOT_EXCEPTION_POP', 'JUMP', (':', 4, 1), 'END_FINALLY',\
(':', 3, 1), '*r', ('::', 5))):
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',) + pos__e[2:], [('PASS',)], (')(ELSE',),pos__j, (')ENDTRY',)]])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY',\
'JUMP_IF_NOT_EXCEPTION_POP', '*n', 'JUMP', (':', 4,1), 'END_FINALLY',\
(':', 3, 1), '*n', ('::', 6))):
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',) + pos__e[2:], pos__f, (')(ELSE',),pos__k, (')ENDTRY',)]])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'JUMP_IF_NOT_EXCEPTION_POP', 'JUMP', (':', 4, 1), 'END_FINALLY',\
(':', 3, 1), '*n', ('::', 5))):
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',) + pos__e[2:], [('PASS',)], (')(ELSE',),pos__j, (')ENDTRY',)]])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'JUMP_IF_NOT_EXCEPTION_POP', 'JUMP', (':', 4, 1),\
'END_FINALLY', ('::', (3,5)))):
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',) + pos__e[2:], [('PASS',)],(')ENDTRY',)]])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*r', ')END_BEGIN_TRY', \
'JUMP_IF_NOT_EXCEPTION_POP', 'JUMP', (':', 3, 1),\
'END_FINALLY', ('::', 4))):
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',) + pos__d[2:], [('PASS',)],(')ENDTRY',)]])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'JUMP_IF_NOT_EXCEPTION_POP', '*', 'JUMP', (':', 4, 1),\
'END_FINALLY', ('::', (3,6)))):
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',) + pos__e[2:], pos__f, (')ENDTRY',)]])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'*l', 'POP_TOP3', '*', 'JUMP', 'END_FINALLY', ('::', (3,7)))):
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',), pos__g, (')ENDTRY',)]])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'*l', 'POP_TOP3', 'JUMP', 'END_FINALLY', ('::', (3,6)))):
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',), [('PASS',)], (')ENDTRY',)]])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'POP_TOP3', '*n', 'END_FINALLY', ('::', 3))):
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',), pos__f, (')ENDTRY',)]])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*r', ')END_BEGIN_TRY', 'JUMP_IF_NOT_EXCEPTION_POP', \
'*', 'JUMP', (':', 3, 1), 'END_FINALLY', ('::', 5))):
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',) + pos__d[2:], pos__e, (')ENDTRY',)]])
return True
## if SCmp(cmds,i, ('(BEGIN_TRY', '*r', ')END_BEGIN_TRY', 'JUMP_IF_NOT_EXCEPTION_POP',\ # By CloneDigger
## 'JUMP', (':', 3, 1), 'END_FINALLY', ('::', 4))):
## rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',) + pos__d[2:], [('PASS',)], (')ENDTRY',)]])
## return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*r', ')END_BEGIN_TRY', 'JUMP_IF_NOT_EXCEPTION_POP', \
'*', 'JUMP', (':', 3, 1), 'END_FINALLY', 'JUMP')) and pos__f[1] == pos__i[1]:
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',) + pos__d[2:], pos__e, (')ENDTRY',)],pos__i])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*r', ')END_BEGIN_TRY', 'JUMP_IF_NOT_EXCEPTION_POP', \
'JUMP', (':', 3,1), 'END_FINALLY', 'JUMP')) and pos__e[1] == pos__h[1]:
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',) + pos__d[2:], [('PASS',)], (')ENDTRY',)],pos__h])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*r', ')END_BEGIN_TRY', 'JUMP_IF_NOT_EXCEPTION_POP', \
'*r', (':', 3,1), 'END_FINALLY')):
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',) + pos__d[2:], pos__e, (')ENDTRY',)]])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY',\
'JUMP_IF_NOT_EXCEPTION_POP', '*r', (':', 4, 1), 'END_FINALLY',\
(':', 3,1), '*n', 'JUMP')) and pos__k[1] not in(pos__d[1],pos__e[1]):
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',) + pos__e[2:], pos__f, (')(ELSE',),pos__j, (')ENDTRY',)],pos__k])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY',\
'JUMP_IF_NOT_EXCEPTION_POP', '*r', (':', 4, 1), 'END_FINALLY',\
('::', 3))):
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',) + pos__e[2:], pos__f, (')ENDTRY',)]])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', ('!', 'PASS'), ')END_BEGIN_TRY',\
'J_IF_NO_EXCEPT_IN_TRY', 'J_AFTER_EXCEPT_HANDLE', \
'END_FINALLY', (':', 3,1), '*n', ('::', 4))):
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',), [('PASS',)],(')(ELSE',),pos__h, (')ENDTRY',)]])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', ('!', 'PASS'), ')END_BEGIN_TRY',\
'J_IF_NO_EXCEPT_IN_TRY', 'J_AFTER_EXCEPT_HANDLE', \
'END_FINALLY', ('::', (3,4)))):
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',), [('PASS',)],(')ENDTRY',)]])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'JUMP_IF_NOT_EXCEPTION_POP', 'JUMP_CONTINUE', \
(':', 4,1), 'END_FINALLY', (':', 3,1), '*n', 'JUMP_CONTINUE')) and pos__f[1] == pos__k[1]:
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',) + pos__e[2:], [('CONTINUE',)], (')(ELSE',),pos__j, (')ENDTRY',)],pos__k])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'JUMP_IF_NOT_EXCEPTION_POP', 'JUMP_CONTINUE', \
(':', 4,1), 'END_FINALLY', (':', 3,1), '*n', 'JUMP')) and pos__f[1] == pos__k[1]:
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',) + pos__e[2:], [('CONTINUE',)], (')(ELSE',),pos__j, (')ENDTRY',)],pos__k])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'*e', 'END_FINALLY', ('::', 3))):
rpl(cmds,[concatenate_try_except(pos__b, pos__e)])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'JUMP_IF_NOT_EXCEPTION_POP', '*', 'JUMP', (':', 4, 1),\
'END_FINALLY', 'JUMP')) and pos__d[1] == pos__g[1] and pos__d[1] == pos__j[1]:
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',) + pos__e[2:], pos__f, (')ENDTRY',)],pos__g])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'JUMP_IF_NOT_EXCEPTION_POP', '*', 'JUMP_CONTINUE', (':', 4, 1),\
'END_FINALLY', 'JUMP_CONTINUE')) and pos__d[1] == pos__g[1] and pos__d[1] == pos__j[1]:
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',) + pos__e[2:], pos__f, (')ENDTRY',)],pos__g])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'JUMP_IF_NOT_EXCEPTION_POP', 'JUMP_CONTINUE', (':', 4, 1),\
'END_FINALLY', 'JUMP_CONTINUE')) and pos__d[1] == pos__f[1] and pos__d[1] == pos__i[1]:
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',) + pos__e[2:], [('PASS',)], (')ENDTRY',)],pos__f])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', \
'J_IF_NO_EXCEPT_IN_TRY', '*e',\
'J_AFTER_EXCEPT_HANDLE_CONTINUE', 'END_FINALLY',\
'JUMP_CONTINUE')) and\
pos__d[1] == pos__f[1] and pos__d[1] == pos__h[1]:
rpl(cmds,[concatenate_try_except(pos__b,pos__e), pos__h])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', \
'J_IF_NO_EXCEPT_IN_TRY', '*e',\
'J_AFTER_EXCEPT_HANDLE', 'END_FINALLY',\
'.:', 'ju')) and\
pos__d[1] == pos__f[1] and pos__d[1] == pos__i[1] and pos__h[1] not in (pos__d[1], pos__f[1], pos__i[1]):
rpl(cmds,[concatenate_try_except(pos__b,pos__e), pos__h, pos__i])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', \
'J_IF_NO_EXCEPT_IN_TRY', '*e',\
'J_AFTER_EXCEPT_HANDLE', 'END_FINALLY',\
'ju')) and\
pos__d[1] == pos__f[1] and pos__d[1] == pos__h[1]:
rpl(cmds,[concatenate_try_except(pos__b,pos__e), pos__h])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', \
'J_IF_NO_EXCEPT_IN_TRY', '*e',\
'J_AFTER_EXCEPT_HANDLE', 'END_FINALLY',\
('::', (3,5)))):
rpl(cmds,[concatenate_try_except(pos__b,pos__e)])
return True
## if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \ # By CloneDigger
## 'JUMP_IF_NOT_EXCEPTION_POP', '*r', (':', 4, 1), 'END_FINALLY',\
## ('::', 3))):
## rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',) + pos__e[2:], pos__f, (')ENDTRY',)]])
## return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'*e', 'END_FINALLY', 'JUMP')) and pos__d[1] == pos__g[1]:
rpl(cmds,[concatenate_try_except(pos__b,pos__e), pos__g])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'*e', 'END_FINALLY', 'JUMP_CONTINUE')) and pos__d[1] == pos__g[1]:
rpl(cmds,[concatenate_try_except(pos__b,pos__e), pos__g])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'JUMP_IF_NOT_EXCEPTION_POP', '*n', 'JUMP_CONTINUE', \
(':', 4,1), 'END_FINALLY', ('::', 3))):
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',) + pos__e[2:], pos__f + [('CONTINUE',)], (')ENDTRY',)]])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'*e', 'J_AFTER_EXCEPT_HANDLE', 'END_FINALLY', (':', 3, 1),\
'*n', ('::', 5))):
rpl(cmds,[concatenate_try_except(pos__b,pos__e,pos__i)])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*r', ')END_BEGIN_TRY', '*e', 'J_AFTER_EXCEPT_HANDLE', \
'END_FINALLY', ('::', 4))):
rpl(cmds,[concatenate_try_except(pos__b,pos__d)])
return True
## if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \ # By CloneDigger
## '*e', 'J_AFTER_EXCEPT_HANDLE', 'END_FINALLY', (':', 3, 1),\
## '*n', ('::', 5))):
## rpl(cmds,[concatenate_try_except(pos__b,pos__e,pos__i)])
## return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'JUMP_IF_NOT_EXCEPTION_POP', 'JUMP', (':', 4,1), 'END_FINALLY', \
(':', 3, 1), '*n', ('::', 5))):
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',) + pos__e[2:], [('PASS',)], (')(ELSE',),pos__j, (')ENDTRY',)]])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*r', ')END_BEGIN_TRY', 'JUMP_IF_NOT_EXCEPTION_POP', \
'*n', (':', 3, 1), 'END_FINALLY')):
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',) + pos__d[2:], pos__e, (')ENDTRY',)]])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'*e', 'J_AFTER_EXCEPT_HANDLE', 'END_FINALLY', 'JUMP_CONTINUE')) and\
pos__d[1] == pos__f[1] and pos__f[1] == pos__h[1]:
rpl(cmds,[concatenate_try_except(pos__b,pos__e),pos__h])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'*e', 'J_AFTER_EXCEPT_HANDLE_CONTINUE', 'END_FINALLY',\
(':', 3, 1), '*n', 'JUMP_CONTINUE')) and pos__f[1] == pos__j[1]:
rpl(cmds,[concatenate_try_except(pos__b,pos__e,pos__i),pos__j])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*r', ')END_BEGIN_TRY', '*e', 'J_AFTER_EXCEPT_HANDLE_CONTINUE',\
'END_FINALLY', 'JUMP_CONTINUE')) and pos__e[1] == pos__g[1]:
rpl(cmds,[concatenate_try_except(pos__b,pos__d),pos__g])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*r', ')END_BEGIN_TRY', '*e', 'J_AFTER_EXCEPT_HANDLE',\
'END_FINALLY', 'JUMP')) and pos__e[1] == pos__g[1]:
rpl(cmds,[concatenate_try_except(pos__b,pos__d),pos__g])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'*l', 'POP_TOP3', 'JUMP', 'END_FINALLY', (':', 3,1),\
'*n', ('::', 6))):
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',), [('PASS',)], (')(ELSE',),pos__j, (')ENDTRY',)]])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'JUMP_IF_NOT_EXCEPTION_POP', 'JUMP', (':', 4, 1), 'END_FINALLY',\
'JUMP')) and pos__d[1] == pos__f[1] and pos__f[1] ==pos__i[1]:
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',) +pos__e[2:], [('PASS', )], (')ENDTRY',)],pos__i])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'JUMP_IF_NOT_EXCEPTION_POP', '*r', (':', 4,1), 'END_FINALLY',\
'JUMP')) and pos__d[1] == pos__i[1]:
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',) +pos__e[2:], pos__f, (')ENDTRY',)],pos__i])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'JUMP_IF_NOT_EXCEPTION_POP', '*r', (':', 4,1), 'END_FINALLY',\
'JUMP_CONTINUE')) and pos__d[1] == pos__i[1]:
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',) +pos__e[2:], pos__f, (')ENDTRY',)],pos__i])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'JUMP_IF_NOT_EXCEPTION_POP', 'JUMP_CONTINUE', (':', 4, 1),\
'END_FINALLY', ('::', 3))): # 1
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',) +pos__e[2:], [('CONTINUE',)], (')ENDTRY',)]])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'*e', 'END_FINALLY', ('::',3))):
rpl(cmds,[concatenate_try_except(pos__b,pos__e)])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*r', ')END_BEGIN_TRY', '*e', \
'J_AFTER_EXCEPT_HANDLE', 'END_FINALLY', ('::', 4))):
rpl(cmds,[concatenate_try_except(pos__b,pos__d)])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY',\
('!', '(EXCEPT1', '*n', ')ENDEXCEPT'), 'J_AFTER_EXCEPT_HANDLE_CONTINUE', \
'END_FINALLY', 'JUMP')) and\
pos__d[1] == pos__h[1] and pos__f[1] != pos__d[1]:
tempor = pos__e[:-1]
if len(tempor[-1][0]) > 0 and tempor[-1][0][0] == 'PASS':
tempor[-1] = [('CONTINUE',)]
else:
tempor[-1].append(('CONTINUE',))
tempor = tempor + [pos__e[-1]]
rpl(cmds,[concatenate_try_except(pos__b,tempor), pos__h])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY',\
('!', '(EXCEPT1', '*n', ')ENDEXCEPT'), 'J_AFTER_EXCEPT_HANDLE_CONTINUE', \
'END_FINALLY', ('::',3))) and pos__f[1] != pos__d[1]:
tempor = pos__e[:-1]
if len(tempor[-1][0]) > 0 and tempor[-1][0][0] == 'PASS':
tempor[-1] = [('CONTINUE',)]
else:
tempor[-1].append(('CONTINUE',))
tempor = tempor + [pos__e[-1]]
rpl(cmds,[concatenate_try_except(pos__b,tempor)])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'*e', 'J_AFTER_EXCEPT_HANDLE', 'END_FINALLY', (':', 3, 1),\
'*r', ('::', 5))): # 1
rpl(cmds,[concatenate_try_except(pos__b,pos__e,pos__i)])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*c', ')END_BEGIN_TRY', '*e', 'J_AFTER_EXCEPT_HANDLE', \
'END_FINALLY', ('::', 4))):
rpl(cmds,[concatenate_try_except(pos__b,pos__d)])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'*e', 'J_AFTER_EXCEPT_HANDLE', 'END_FINALLY', (':', 3,1),\
'*n', 'JUMP')) and pos__f[1] == pos__j[1]:
rpl(cmds,[concatenate_try_except(pos__b,pos__e,pos__i),pos__j])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*r', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'*e', 'J_AFTER_EXCEPT_HANDLE', 'END_FINALLY', ('::', (3,5)))):
rpl(cmds,[concatenate_try_except(pos__b,pos__e)])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*r', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'*e', 'END_FINALLY', 'JUMP')) and pos__d[1] == pos__g[1]:
rpl(cmds,[concatenate_try_except(pos__b,pos__e),pos__g])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*r', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'*e', 'END_FINALLY', ('::', 3))): # 2
rpl(cmds,[concatenate_try_except(pos__b,pos__e)])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*r', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'*e', 'J_AFTER_EXCEPT_HANDLE', 'END_FINALLY', 'JUMP')) and\
pos__d[1] == pos__f[1] == pos__h[1]:
rpl(cmds,[concatenate_try_except(pos__b,pos__e),pos__h])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*r', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'*e', 'END_FINALLY', 'ju')) and pos__d[1] == pos__g[1]:
rpl(cmds,[concatenate_try_except(pos__b,pos__e),pos__g])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'*e', 'J_AFTER_EXCEPT_HANDLE', 'END_FINALLY', (':', 3,1), '*n',\
'JUMP_CONTINUE')) and pos__f[1] == pos__j[1]:
rpl(cmds,[concatenate_try_except(pos__b,pos__e,pos__i),pos__j])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*r', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY',\
'*e', 'J_AFTER_EXCEPT_HANDLE_CONTINUE', 'END_FINALLY', 'JUMP_CONTINUE')) and\
pos__d[1] == pos__f[1] == pos__h[1]:
rpl(cmds,[concatenate_try_except(pos__b,pos__e),pos__h])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*r', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY',\
('!', '(EXCEPT1', ('!', 'PASS'), ')ENDEXCEPT'), \
'J_AFTER_EXCEPT_HANDLE_CONTINUE', 'END_FINALLY', ('::', 3))):
rpl(cmds,[[('(TRY',), pos__b, ('(EXCEPT',) + pos__e[0][1:], [('CONTINUE',)], (')ENDTRY',)]])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', \
'J_IF_NO_EXCEPT_IN_TRY', 'JUMP_IF_NOT_EXCEPTION_POP', \
'*n', 'JUMP_CONTINUE', (':', 4,1), 'END_FINALLY', ('::', 3))):
rpl(cmds,[[('(TRY',), pos__b, ('(EXCEPT',) + pos__e[2:], pos__f+[('CONTINUE',)], (')ENDTRY',)]])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', '*e', \
'J_AFTER_EXCEPT_HANDLE_CONTINUE', 'END_FINALLY',\
'JUMP_CONTINUE')) and pos__e[1] == pos__g[1]:
rpl(cmds,[concatenate_try_except(pos__b,pos__d),pos__g])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*r', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'*e', 'J_AFTER_EXCEPT_HANDLE', 'END_FINALLY', (':', 3,1),\
'*n', ('::', 5))):
rpl(cmds,[concatenate_try_except(pos__b,pos__e,pos__i)])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY',\
'J_IF_NO_EXCEPT_IN_TRY', '*e', \
'J_AFTER_EXCEPT_HANDLE_CONTINUE', 'END_FINALLY',\
(':', 3, 1), '*r')):
rpl(cmds,[concatenate_try_except(pos__b,pos__e,pos__i),('JUMP_CONTINUE', pos__f[1])])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
('!', '.L', '(EXCEPT0', ('!', 'PASS'), ')ENDEXCEPT'),\
'J_AFTER_EXCEPT_HANDLE_CONTINUE', 'END_FINALLY', ('::', 3))): # 2
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',), [('CONTINUE',)], (')ENDTRY',)]])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
('!', '(EXCEPT0', ('!', 'PASS'), ')ENDEXCEPT'),\
'J_AFTER_EXCEPT_HANDLE_CONTINUE', 'END_FINALLY', ('::', 3))): # 2
rpl(cmds,[[('(TRY',), pos__b, (')(EXCEPT',), [('CONTINUE',)], (')ENDTRY',)]])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
('!', '.L', '(EXCEPT1', ('!', 'PASS'), ')ENDEXCEPT'),\
'J_AFTER_EXCEPT_HANDLE_CONTINUE', 'END_FINALLY', ('::', 3))): # 2
rpl(cmds,[[('(TRY',pos__e[1][1]), pos__b, (')(EXCEPT',), [('CONTINUE',)], (')ENDTRY',)]])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
('!', '(EXCEPT1', ('!', 'PASS'), ')ENDEXCEPT'),\
'J_AFTER_EXCEPT_HANDLE_CONTINUE', 'END_FINALLY', ('::', 3))): # 2
rpl(cmds,[[('(TRY',pos__e[0][1]), pos__b, (')(EXCEPT',), [('CONTINUE',)], (')ENDTRY',)]])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'*e', 'J_AFTER_EXCEPT_HANDLE', 'END_FINALLY', 'JUMP_CONTINUE', \
('::', 5))) and pos__d[1] == pos__h[1]: # 1
rpl(cmds,[concatenate_try_except(pos__b,pos__e,[('CONTINUE',)])])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'*e', 'J_AFTER_EXCEPT_HANDLE', 'END_FINALLY', (':', 3, 1),\
'*', '.:', 'END_FINALLY', ('::', 5))) and not islineblock(pos__i) and\
pos__j[1] not in (pos__d[1],pos__f[1]):
rpl(cmds,[concatenate_try_except(pos__b,pos__e,pos__i), pos__j,pos__k])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY', '*e', 'END_FINALLY')):
rpl(cmds,[concatenate_try_except(pos__b,pos__d)])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY',\
'J_IF_NO_EXCEPT_IN_TRY', '*e', 'J_AFTER_EXCEPT_HANDLE', \
'END_FINALLY', 'JUMP_CONTINUE', '.:', '*n', (':', (3,5), 1),\
'JUMP_CONTINUE')) and pos__h[1] == pos__l[1] and pos__i[1] not in (pos__d[1], pos__h[1]):
rpl(cmds,[concatenate_try_except(pos__b,pos__e),pos__h,pos__i,pos__j,pos__l])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*n', ')END_BEGIN_TRY',\
'J_IF_NO_EXCEPT_IN_TRY', '*e', 'J_AFTER_EXCEPT_HANDLE', \
'END_FINALLY', 'JUMP_CONTINUE', '.:', '*n', (':', (3,5), 2),\
'JUMP_CONTINUE')) and pos__h[1] == pos__l[1] and pos__i[1] not in (pos__d[1], pos__h[1]):
rpl(cmds,[concatenate_try_except(pos__b,pos__e),pos__h,pos__i,pos__j,pos__k,pos__l])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*r', ')END_BEGIN_TRY', 'J_IF_NO_EXCEPT_IN_TRY', \
'*e', 'J_AFTER_EXCEPT_HANDLE', 'END_FINALLY', (':', 3, 1),\
'*r', ('::', 5))):
rpl(cmds,[concatenate_try_except(pos__b,pos__e,pos__i)])
return True
if SCmp(cmds,i, ('(BEGIN_TRY', '*r', ')END_BEGIN_TRY', '*l', 'POP_TOP3', '*r', 'END_FINALLY')):
rpl(cmds, [[('(TRY',), pos__b, (')(EXCEPT',), pos__f, (')ENDTRY',)]])
return True
return False
def process_except_clause(cmds,i):
global pos__a,pos__b,pos__c,pos__d,pos__e,pos__f,pos__g,pos__h,pos__i,pos__j,pos__k,pos__l
if SCmp(cmds,i, ('POP_TOP3', '*r', 'END_FINALLY')):
rpl(cmds,[[('(EXCEPT0',), pos__b, (')ENDEXCEPT',)],pos__c])
return True
if SCmp(cmds,i, ('POP_TOP3', '*n', 'JUMP_CONTINUE', 'END_FINALLY')):
rpl(cmds,[[('(EXCEPT0',), pos__b + [('CONTINUE',)], (')ENDEXCEPT',)],pos__d])
return True
if SCmp(cmds,i, ('POP_TOP3', 'JUMP_CONTINUE', 'END_FINALLY')):
rpl(cmds,[[('(EXCEPT0',), [('CONTINUE',)], (')ENDEXCEPT',)],pos__c])
return True
if SCmp(cmds,i, ('POP_TOP3', 'JUMP', 'END_FINALLY')):
if not islooplabel(pos__b[1],cmds):
rpl(cmds,[[('(EXCEPT0',), [('PASS',)], (')ENDEXCEPT',)],('J_AFTER_EXCEPT_HANDLE', pos__b[1]),pos__c])
else:
rpl(cmds,[[('(EXCEPT0',), [('CONTINUE',)], (')ENDEXCEPT',)],pos__c])
return True
if SCmp(cmds,i, ('POP_TOP3', '*n', 'JUMP', 'END_FINALLY')):
rpl(cmds,[[('(EXCEPT0',), pos__b, (')ENDEXCEPT',)],('J_AFTER_EXCEPT_HANDLE', pos__c[1]),pos__d])
return True
if SCmp(cmds,i, ('JUMP_IF_NOT_EXCEPTION_POP', '*n', 'JUMP', (':', 0,1), 'END_FINALLY')):
rpl(cmds,[[('(EXCEPT1',) +pos__a[2:], pos__b, (')ENDEXCEPT',)],('J_AFTER_EXCEPT_HANDLE', pos__c[1]),pos__e])
return True
if SCmp(cmds,i, ('JUMP_IF_NOT_EXCEPTION_POP', '*n', 'JUMP_CONTINUE', (':', 0,1), 'END_FINALLY')):
rpl(cmds,[[('(EXCEPT1',) +pos__a[2:], pos__b + [('CONTINUE',)], (')ENDEXCEPT',)],pos__e])
return True
if SCmp(cmds,i, ('JUMP_IF_NOT_EXCEPTION_POP', '*r', (':', 0,1), 'END_FINALLY')):
rpl(cmds,[[('(EXCEPT1',) +pos__a[2:], pos__b, (')ENDEXCEPT',)],pos__d])
return True
if SCmp(cmds,i, ('JUMP_IF_NOT_EXCEPTION_POP', 'JUMP', (':', 0,1), 'END_FINALLY')):
rpl(cmds,[[('(EXCEPT1',) +pos__a[2:], [('PASS',)], (')ENDEXCEPT',)],('J_AFTER_EXCEPT_HANDLE', pos__b[1]),pos__d])
return True
if SCmp(cmds,i, ('JUMP_IF_NOT_EXCEPTION_POP', 'JUMP_CONTINUE', (':', 0,1), 'END_FINALLY')):
rpl(cmds,[[('(EXCEPT1',) +pos__a[2:], [('CONTINUE',)], (')ENDEXCEPT',)],pos__d])
return True
if SCmp(cmds,i, ('JUMP_IF_NOT_EXCEPTION_POP', '*n', (':', 0,1), 'END_FINALLY')):
rpl(cmds,[[('(EXCEPT1',) +pos__a[2:], pos__b, (')ENDEXCEPT',)], pos__d])
return True
if SCmp(cmds,i, ('JUMP_IF_NOT_EXCEPTION_POP', 'xJUMP_IF2_FALSE_POP', '*r',\
(':', 0, 1), 'END_FINALLY', '.:', '*n', ('::', 1))) and\
pos__a[1] != pos__f[1] != pos__b[1]:
rpl(cmds,[pos__a, [('(IF', pos__b[2]), pos__c, (')ENDIF',)], pos__d,pos__e,pos__f,pos__g])
return True
if SCmp(cmds,i, ('JUMP_IF_NOT_EXCEPTION_POP', '*n',\
'xJUMP_IF2_FALSE_POP', '*n', \
'JUMP_CONTINUE', (':',0 ,1), \
'END_FINALLY', ('::', 2))):
rpl(cmds,[[('(EXCEPT1',) +pos__a[2:], pos__b + \
[('(IF',) + pos__c[2:], pos__d + [('CONTINUE',)], (')ENDIF',)],\
(')ENDEXCEPT',)], pos__g])
return True
if SCmp(cmds,i, ('JUMP_IF_NOT_EXCEPTION_POP', '*n', 'JUMP_CONTINUE', (':', 0, 1), \
('!', '(EXCEPT1', '*r', ')ENDEXCEPT'), 'END_FINALLY')):
cmds[i:i+6] = [concatenate_except(pos__a[2:], pos__b + [('CONTINUE',)], pos__e),pos__f]
return True
if SCmp(cmds,i, ('JUMP_IF_NOT_EXCEPTION_POP', '*n', 'JUMP_CONTINUE', (':', 0, 1), \
'*e', 'J_AFTER_EXCEPT_HANDLE')) and pos__c[1] == pos__f[1]:
cmds[i:i+6] = [concatenate_except(pos__a[2:], pos__b + [('CONTINUE',)], pos__e),pos__f]
return True
if SCmp(cmds,i, ('JUMP_IF_NOT_EXCEPTION_POP', '*n', 'JUMP', (':', 0, 1), \
'*e', 'J_AFTER_EXCEPT_HANDLE')) and pos__c[1] == pos__f[1]:
cmds[i:i+6] = [concatenate_except(pos__a[2:], pos__b, pos__e),pos__f]
return True
if SCmp(cmds,i, ('JUMP_IF_NOT_EXCEPTION_POP', 'JUMP_CONTINUE', (':', 0, 1), \
'*e', 'J_AFTER_EXCEPT_HANDLE_CONTINUE')) and pos__b[1] == pos__e[1]:
cmds[i:i+5] = [concatenate_except(pos__a[2:], [('PASS',)], pos__d),pos__e]
return True
if SCmp(cmds,i, ('JUMP_IF_NOT_EXCEPTION_POP', '*n', 'JUMP_CONTINUE', (':', 0, 1), \
'*e', 'END_FINALLY', 'JUMP_CONTINUE')) and pos__c[1] == pos__g[1]:
cmds[i:i+7] = [concatenate_except(pos__a[2:], pos__b, pos__e),pos__f,pos__g]
return True
if SCmp(cmds,i, ('JUMP_IF_NOT_EXCEPTION_POP', '*n', 'JUMP_CONTINUE', \
(':', 0, 1), '*e', 'J_AFTER_EXCEPT_HANDLE')) and pos__c[1] != pos__f[1]:
rpl(cmds,[concatenate_except(pos__a[2:], pos__b + [('CONTINUE',)], pos__e),pos__f])
return True
if SCmp(cmds,i, ('JUMP_IF_NOT_EXCEPTION_POP', 'JUMP', (':', 0, 1), \
'*e', 'J_AFTER_EXCEPT_HANDLE')) and pos__b[1] == pos__e[1]:
cmds[i:i+5] = [concatenate_except(pos__a[2:], [('PASS',)], pos__d),pos__e]
return True
## if SCmp(cmds,i, ('JUMP_IF_NOT_EXCEPTION_POP', 'JUMP', (':', 0, 1), \ # By CloneDigger
## '*e', 'J_AFTER_EXCEPT_HANDLE')) and pos__b[1] == pos__e[1]:
## cmds[i:i+5] = [concatenate_except(pos__a[2:], [('PASS',)], pos__d),pos__e]
## return True
if SCmp(cmds,i, ('JUMP_IF_NOT_EXCEPTION_POP', '*', 'JUMP', (':', 0,1), '*e',
'END_FINALLY', ('::', 2))):
rpl(cmds,[concatenate_except(pos__a[2:], pos__b, pos__e),pos__f])
return True
if SCmp(cmds,i, ('JUMP_IF_NOT_EXCEPTION_POP', '*r', (':', 0, 1), '*e',\
'J_AFTER_EXCEPT_HANDLE', 'END_FINALLY', (':', 4, 2))):
cmds[i:i+7] = [concatenate_except(pos__a[2:], pos__b, pos__d),pos__e,pos__f,pos__g]
return True
if SCmp(cmds,i, ('JUMP_IF_NOT_EXCEPTION_POP', '*r', (':', 0, 1), '*e',\
'J_AFTER_EXCEPT_HANDLE', 'END_FINALLY', (':', 4, 1))):
cmds[i:i+7] = [concatenate_except(pos__a[2:], pos__b, pos__d),pos__f]
return True
if SCmp(cmds,i, ('JUMP_IF_NOT_EXCEPTION_POP', '*r', (':', 0, 1), '*e',\
'END_FINALLY')):
cmds[i:i+5] = [concatenate_except(pos__a[2:], pos__b, pos__d),pos__e]
return True
if SCmp(cmds,i, ('JUMP_IF_NOT_EXCEPTION_POP', '*r', (':', 0,1), '*e')):
cmds[i:i+4] = [concatenate_except(pos__a[2:], pos__b, pos__d)]
return True
if SCmp(cmds,i, ('JUMP_IF_NOT_EXCEPTION_POP', '*ra', 'JUMP', (':', 0,1), '*e')) and\
pos__c[1] != pos__a[1]:
rpl(cmds,[concatenate_except(pos__a[2:], pos__b, pos__e)])
return True
if SCmp(cmds,i, ('JUMP_IF_NOT_EXCEPTION_POP', 'JUMP', (':', 0, 1), '*e',\
'END_FINALLY', ('::', 1))):
rpl(cmds,[concatenate_except(pos__a[2:], [('PASS',)], pos__d),pos__e])
return True
if SCmp(cmds,i, ('JUMP_IF_NOT_EXCEPTION_POP', '*n', 'JUMP_CONTINUE', \
(':', 0, 1), '*e', 'END_FINALLY')):
rpl(cmds,[concatenate_except(pos__a[2:], pos__b + [('CONTINUE',)], pos__e),pos__f])
return True
if SCmp(cmds,i, ('JUMP_IF_NOT_EXCEPTION_POP', 'JUMP_CONTINUE', \
(':', 0, 1), '*e', 'END_FINALLY')):
rpl(cmds,[concatenate_except(pos__a[2:], [('CONTINUE',)], pos__d),pos__e])
return True
return False
def process_after_try_detect(cmds,_i):
global count_define_set
aa = cmds[_i]
v0,v1,v2 = [], [], []
## i = 0
if len(aa) == 5 and aa[0] == ('(TRY',) and \
len(aa[1]) == 2 and aa[1][0][0] == '.L' and\
TCmp(aa[1][1], v0, ('STORE', (('STORE_NAME', '?'),), \
(('!IMPORT_NAME', '?', '?', '?'),))) and \
TCmp(aa[2], v1, (')(EXCEPT', (('!LOAD_BUILTIN', 'ImportError'), '?'), ())) and\
len(aa[3]) == 2 and aa[3][0][0] == '.L' and\
TCmp(aa[3][1], v2, ('STORE', (('STORE_NAME', '?'),), (('CONST', None),))) and \
aa[4] == (')ENDTRY',) and v0[0] == v0[1] and v0[0] == v2[0]:
this, d = None, None
this, d = MyImport(v0[1])
cmds[_i] = aa[1]
if v0[0] in count_define_set and count_define_set[v0[0]] > 1:
count_define_set[v0[0]] -= 1
def process_setup_except(cmds,i):
global pos__a,pos__b,pos__c,pos__d,pos__e,pos__f,pos__g,pos__h,pos__i,pos__j,pos__k,pos__l
if SCmp(cmds,i, ('J_SETUP_EXCEPT', 'xJUMP_IF2_TRUE_POP_CONTINUE', '*l', 'POP_BLOCK')):
if type(pos__c) is tuple:
rpl(cmds,[pos__a, [('(IF',) + pos__b[2:], [('CONTINUE',)], (')ENDIF',)]+[pos__c],pos__d])
else:
rpl(cmds,[pos__a, [('(IF',) + pos__b[2:], [('CONTINUE',)], (')ENDIF',)]+pos__c,pos__d])
return True
if SCmp(cmds,i, ('J_SETUP_EXCEPT', '*', 'POP_BLOCK', 'JUMP', ('::', 0))) and pos__d[1] != pos__e[1]:
rpl(cmds,[('(BEGIN_TRY',), pos__b, (')END_BEGIN_TRY',), ('J_IF_NO_EXCEPT_IN_TRY', pos__d[1])])
return True
if SCmp(cmds,i, ('J_SETUP_EXCEPT', 'POP_BLOCK', 'JUMP', ('::', 0))) and pos__d[1] != pos__c[1]:
rpl(cmds,[('(BEGIN_TRY',), [('PASS',)], (')END_BEGIN_TRY',), ('J_IF_NO_EXCEPT_IN_TRY', pos__c[1])])
return True
if SCmp(cmds,i, ('J_SETUP_EXCEPT', 'JUMP_CONTINUE', 'POP_BLOCK', 'JUMP_CONTINUE', \
(':', 0, 1))) and pos__b[1] == pos__d[1]:
rpl(cmds,[('(BEGIN_TRY',), [('CONTINUE',)], (')END_BEGIN_TRY',)])
return True
if SCmp(cmds,i, ('J_SETUP_EXCEPT', 'POP_BLOCK', 'JUMP_CONTINUE', \
(':', 0, 1))):
rpl(cmds,[('(BEGIN_TRY',), [('CONTINUE',)], (')END_BEGIN_TRY',)])
return True
if SCmp(cmds,i, ('J_SETUP_EXCEPT', '*', 'JUMP_CONTINUE', \
'POP_BLOCK', 'JUMP', ('::', 0))) and pos__e[1] != pos__f[1]:
rpl(cmds,[('(BEGIN_TRY',), pos__b + [('CONTINUE',)], (')END_BEGIN_TRY',), \
('J_IF_NO_EXCEPT_IN_TRY', pos__e[1])])
return True
if SCmp(cmds,i, ('J_SETUP_EXCEPT', '*n', 'JUMP', ('::', 0))) and pos__c[1] != pos__d[1]:
rpl(cmds,[('(BEGIN_TRY',), pos__b, (')END_BEGIN_TRY',), ('J_IF_NO_EXCEPT_IN_TRY', pos__c[1])])
return True
if SCmp(cmds,i, ('J_SETUP_EXCEPT', '*n', 'JUMP_CONTINUE', ('::', 0))) and pos__c[1] != pos__d[1]:
rpl(cmds,[('(BEGIN_TRY',), pos__b +[('CONTINUE',)], (')END_BEGIN_TRY',)])
return True
if SCmp(cmds,i, ('J_SETUP_EXCEPT', '*n', 'JUMP_CONTINUE', 'POP_BLOCK',\
'JUMP_CONTINUE', (':', 0,1), '*e')):
rpl(cmds,[('(BEGIN_TRY',), pos__b +[('CONTINUE',)], (')END_BEGIN_TRY',),pos__g])
return True
if SCmp(cmds,i, ('J_SETUP_EXCEPT', '*', 'POP_BLOCK', 'JUMP_CONTINUE', ('::', 0))) and pos__d[1] != pos__e[1]:
rpl(cmds,[('(BEGIN_TRY',), pos__b, (')END_BEGIN_TRY',), ('J_IF_NO_EXCEPT_IN_TRY', pos__d[1])])
return True
if SCmp(cmds,i, ('J_SETUP_EXCEPT', '*r', ('::', 0))):
rpl(cmds,[('(BEGIN_TRY',), pos__b, (')END_BEGIN_TRY',)])
return True
if SCmp(cmds,i, ('J_SETUP_EXCEPT', 'JUMP_CONTINUE', 'POP_BLOCK',\
'JUMP_CONTINUE', (':', 0,1), '*e', \
'J_AFTER_EXCEPT_HANDLE_CONTINUE', 'END_FINALLY',\
'JUMP_CONTINUE')) and pos__b[1] == pos__d[1] == pos__g[1] == pos__i[1]:
rpl(cmds,[concatenate_try_except([('CONTINUE',)],pos__f), pos__i])
return True
if SCmp(cmds,i, ('J_SETUP_EXCEPT', 'POP_BLOCK', 'JUMP_CONTINUE', (':', 0, 1),\
'*e', 'J_AFTER_EXCEPT_HANDLE_CONTINUE', 'END_FINALLY',\
'JUMP_CONTINUE')) and pos__c[1] == pos__f[1] == pos__h[1]:
rpl(cmds,[concatenate_try_except([('PASS',)],pos__e), pos__h])
return True
return False
def concatenate_try_except(bl1, exc_tail, else_tail = None):
out = []
out.append(('(TRY',))
out.append(bl1)
if exc_tail is None:
if else_tail is not None:
out.append((')(ELSE',))
out.append(else_tail)
out.append((')ENDTRY',) )
return out
tail = exc_tail[:]
while len(tail) > 0 and tail[0][0] == '.L':
del tail[0]
if tail[0][0] in ('(EXCEPT','(EXCEPT0','(EXCEPT1'):
t1 = (')(EXCEPT',) + tail[0][1:]
out.append(t1)
return add_endtry(out, tail, bl1, exc_tail, else_tail)
elif tail[0][0] == '(EXCEPT0':
out.append((')(EXCEPT',))
return add_endtry(out, tail, bl1, exc_tail, else_tail)
Fatal('Error in exception sequence', bl1, exc_tail, else_tail)
return '~'
def add_endtry(out, tail, bl1, exc_tail, else_tail):
del tail[0]
out.extend(tail[:-1])
if tail[-1][0] != ')ENDEXCEPT':
Fatal('Must be ENDEXCEPT', bl1, exc_tail, else_tail)
return '%%'
if else_tail is not None:
out.append((')(ELSE',))
out.append(else_tail)
out.append((')ENDTRY',))
return out
def concatenate_except(cond, bl1, exc_tail):
out = []
out.append(('(EXCEPT',) + cond)
out.append(bl1)
if exc_tail is None:
out.append((')ENDEXCEPT',) )
return out
tail = exc_tail[:]
while len(tail) > 0 and tail[0][0] == '.L':
del tail[0]
if len(tail) == 0:
out.append((')ENDEXCEPT',) )
return out
if tail[0][0] in ('(EXCEPT','(EXCEPT0','(EXCEPT1'):
t1 = (')(EXCEPT',) + tail[0][1:]
out.append(t1)
del tail[0]
out.extend(tail)
return out
elif tail[0][0] == '(EXCEPT0':
t1 = (')(EXCEPT',)
out.append(t1)
del tail[0]
out.extend(tail)
return out
Fatal('Error in concatenate except', filename)
return '~'
def New_3Cmp(tupl):
t = ('!NCMP', tuple(tupl[1:]))
return ('!BOOLEAN', t)
def New_NCmp(tupl):
t = ('!NCMP', tupl)
return ('!BOOLEAN', t)
def isintconst(b):
return type(b) is tuple and len(b) == 2 and b[0] == 'CONST' \
and type(b[1]) is int
def rpl(cmds,new):
global matched_tail_label
if matched_tail_label is not None and (matched_tail_label[1] > 0 or matched_tail_label[3]):
new = new + [matched_tail_label[2]]
if type(new) is list:
if len(new) >= 2 and type(new[-1]) is tuple and type(new[-2]) is tuple and\
len(new[-1]) == 2 and len(new[-2]) == 2 and new[-1][0] == '.:' and new[-2][0] == '.:' and\
new[-1][1] == new[-2][1]:
Fatal("Dublicate label")
cmds[matched_i:matched_i+matched_len] = new
return
def begin_cmp():
global matched_i
global matched_p
global matched_len
global matched_tail_label
matched_i = -1
matched_p = None
matched_len = -1
matched_tail_label = None
stats__ = {}
def SCmp(cmds,i0,pattern,recursive=False):
global matched_i
global matched_p
global matched_len
global matched_tail_label
global used_cmpl, used_cmp, used_line, matched_cmpl, matched_cmp,matched_line,collect_stat,p2l
global pos__a,pos__b,pos__c,pos__d,pos__e,pos__f,pos__g,pos__h,pos__i,pos__j,pos__k,pos__l
if type(cmds) is tuple:
return False
assert type(cmds) is list
assert type(i0) is int
## if pattern not in stats__:
## stats__[pattern] = 1
## else:
## stats__[pattern] = stats__[pattern] + 1
tempor = cmds[i0:i0+len(pattern)]
if len(tempor) != len(pattern):
return False
for i,p in enumerate(pattern):
assert type(tempor) is list
if i >= len(tempor):
return False
tempi = tempor[i]
# if type(tempi) is not int and type(p) is str and tempi[0] == p:
if type(p) is str:
if tempi[0] == p:
continue
if p[:9] == 'xJUMP_IF2':
if p[1:] in anagr:
if tempi[0] == p[1:]:
continue
elif tempi[0] == anagr[p[1:]]:
tempi = list(tempi)
tempi[2] = Not(tempi[2])
tempi[0] = p[1:]
tempi = tempor[i] = tuple(tempi)
continue
return False
if p == 'ju':
if tempi[0] not in ('JUMP', 'JUMP_CONTINUE'):
return False
continue
elif p == 'jc':
if tempi[0] not in ('JUMP', 'JUMP_CONTINUE') or not islooplabel(tempi[1],cmds):
return False
continue
elif p == '>':
if type(tempi) is tuple and len(tempi) >= 1 and\
(tempi[0] in ('CONST', 'FAST', 'LOAD_FAST', 'LOAD_CONST', 'LOAD_CLOSURE', 'PY_TYPE') or\
tempi[0][0] == '!'):
continue
return False
elif p == '=':
if tempi[0] in set_any:
continue
return False
elif p == '*':
if type(tempi) is list and (len(tempi) > 1 or tempi[0][0] != '.L'):
continue
return False
elif p == '*r':
if type(tempi) is list and tempi[-1][0] == 'RETURN_VALUE':
continue
return False
elif p == '*ra':
if type(tempi) is list and tempi[-1][0] == 'RAISE_VARARGS':
continue
return False
elif p == '*c':
if type(tempi) is list and tempi[-1][0] == 'CONTINUE':
continue
return False
elif p == '*l':
if type(tempi) is list and len(tempi) == 1 and tempi[0][0] == '.L':
continue
elif tempi[0] == '.L':
continue
return False
elif p == '*e':
if not (type(tempi) is list):
return False
if not isexceptblock(tempi):
return False
continue
elif p == '*n':
if type(tempi) is list and (len(tempi) > 1 or tempi[0][0] != '.L'):
if tempi[-1][0] == 'RETURN_VALUE' or isexceptblock(tempi):
return False
continue
return False
elif p == '**n':
if type(tempi) is list and (len(tempi) > 1 or tempi[0][0] != '.L'):
if tempi[-1][0] == 'RETURN_VALUE' or isexceptblock(tempi):
return False
else:
tempor[i:i+1] = [[('PASS',)], tempi]
tempor = tempor[0:len(pattern)]
continue
elif type(p) is tuple:
if p[0] == '!':
if len(tempi) == len(p)-1 and type(tempi) is list and SCmp(tempi,0, p[1:],True):
continue
return False
elif p[0] == ':':
if len(p) == 3:
if type(p[1]) is tuple:
for pp in p[1]:
if pp>= len(tempor) or not label(tempor[pp], tempi):
return False
elif p[1] is not None:
if p[1] >= len(tempor) or not label(tempor[p[1]], tempi):
return False
is_one = OneJumpCache(tempi[1],cmds)
if p[2] == 1 and not is_one:
return False
if p[2] == 2 and is_one:
return False
elif p[0] == '::':
if len(p) == 2:
ltemp = 0
isjump = False
cnt_ju = None
if tempi[0] == '.:':
if type(p[1]) is tuple:
ltemp = len(p[1])
for pp in p[1]:
if not label(cmds[i0+pp], tempi):
return False
elif p[1] is not None:
ltemp = 1
if not label(cmds[i0+p[1]], tempi):
return False
cnt_ju = CountJumpCache(tempi[1],cmds)
if cnt_ju == 0:
return False
elif tempi[0] in jump:
isjump = True
if type(p[1]) is tuple:
ltemp = len(p[1])
for pp in p[1]:
if not endlabel(cmds[i0+pp], tempi):
return False
elif p[1] is not None:
ltemp = 1
if not endlabel(cmds[i0+p[1]], tempi):
return False
cnt_ju = CountJumpCache(tempi[1],cmds)
if cnt_ju == 0:
return False
else:
return False
if i == len(pattern)-1:
if cnt_ju is None:
cnt_ju = CountJumpCache(tempi[1],cmds)
matched_tail_label = (p, cnt_ju-ltemp, tempi, isjump)
elif len(p) == 2:
if len(tempi) < 2 or not (p[0] == tempi[0] and p[1] == tempi[1]):
return False
continue
if type(tempi) is int or tempi[0] != p:
return False
if not recursive:
matched_i = i0
matched_p = pattern
matched_len = len(pattern)
## if not recursive:
tempor = tempor[0:min(len(pattern),12)]
while len(tempor) < 12:
tempor.append('^^') # ibo nefig
pos__a,pos__b,pos__c,pos__d,pos__e,pos__f,pos__g,pos__h,pos__i,pos__j,pos__k,pos__l = tempor
return True
def islineblock(a):
if type(a) is list:
if len(a) == 1 and a[0][0] == '.L':
return True
elif a[0] == '.L':
return True
return False
def isblock(a):
if type(a) is list:
if len(a) > 1:
return True
if a[0][0] == '.L':
return False
else:
return True
else:
return False
def isretblock(a):
return type(a) is list and a[-1][0] == 'RETURN_VALUE'
def islooplabel(label,cmds):
if type(label) is int and type(cmds) is list:
for i in range(1, len(cmds)-1):
v = cmds[i]
if type(v) is tuple:
assert type(v) is tuple
if v[0] == '.:' and v[1] == label:
if cmds[i-1][0] == 'J_SETUP_LOOP_FOR' and cmds[i+1][0] == 'J_LOOP_VARS':
return True
if cmds[i-1][0] == 'J_SETUP_LOOP':
return True
return False
def isexceptblock(a):
if type(a) is list:
if a[-1][0] == ')ENDEXCEPT':
if a[0][0] in ('(EXCEPT', '(EXCEPT0', '(EXCEPT1'):
return True
if a[0][0] == '.L' and a[1][0] in ('(EXCEPT', '(EXCEPT0', '(EXCEPT1'):
return True
return False
def revert_conditional_jump_over_uncond_jump(cmds):
i = 0
while i < ( len(cmds) - 4):
a = cmds[i]
if a[0][:8] == 'JUMP_IF_' and a[0][-4:] == '_POP':
b,c, d = cmds[i+1], cmds[i+2], cmds[i+3]
if b[0] == '.L' and c[0] in jump and d[0] == '.:' and a[1] == d[1]:
if a[0] == 'JUMP_IF_FALSE_POP':
e = 'JUMP_IF_TRUE_POP'
else:
e = 'JUMP_IF_FALSE_POP'
oldlabel = a[1]
cmds[i:i+4] = [(e, c[1]),b,d]
del_if_unused_label(cmds, oldlabel)
continue
elif b[0] in jump and c[0] == '.:' and a[1] == c[1]:
if a[0] == 'JUMP_IF_FALSE_POP':
e = 'JUMP_IF_TRUE_POP'
else:
e = 'JUMP_IF_FALSE_POP'
oldlabel = a[1]
cmds[i:i+3] = [(e, b[1]),c]
del_if_unused_label(cmds, oldlabel)
continue
i = i + 1
def del_dead_code(cmds):
i = 0
updated = False
while i < (len(cmds) - 1):
cmd = cmds[i]
if cmd[0] in jump:
cmd2 = cmds[i+1]
if cmd2[0] not in ('END_FINALLY', 'POP_BLOCK') and (type(cmd2[0]) != str or cmd2[0][0] != '.'):
del cmds[i+1]
updated = True
continue
elif cmd2[0] == '.L':
del cmds[i+1]
updated = True
continue
elif cmd2[0] == '.:' and cmd2[1] == cmd[1]:
oldlabel = cmd[1]
del cmds[i]
del_if_unused_label(cmds, oldlabel)
i = max(0, i-3)
updated = True
continue
i = i + 1
i = 0
while i < (len(cmds) - 1):
cmd = cmds[i]
if cmd[0] == 'RETURN_VALUE' and \
(type(cmds[i+1][0]) != str or cmds[i+1][0][0] != '.') and \
cmds[i+1][0] not in ('END_FINALLY', 'POP_BLOCK'):
del cmds[i+1]
updated = True
continue
elif cmd[0] == 'RETURN_VALUE' and cmds[i+1][0] == '.L':
del cmds[i+1]
updated = True
continue
i = i + 1
return updated
def set_conditional_jump_popped(cmds):
i = 0
updated = False
## print '10', cmds
while i < (len(cmds) - 1):
cmd,b = cmds[i], cmds[i+1]
if (( cmd[0] == 'JUMP_IF_FALSE' or cmd[0] == 'JUMP_IF_TRUE' ) and b[0] == 'POP_TOP'):
to_label, pos_to_label = after_label(cmds, cmd[1], 3)
oldlabel = cmd[1]
if to_label[1][0] == 'POP_TOP':
if to_label[2][0] == '.:':
cmds[i:i+2] = [(cmd[0] + '_POP', to_label[2][1])]
del_if_unused_label(cmds, oldlabel)
i = max(0, i-3)
updated = True
continue
elif pos_to_label > i+2:
new_label = gen_new_label(cmds)
cmds.insert(pos_to_label+2, ('.:', new_label))
cmds[i:i+2] = [(cmd[0] + '_POP', new_label)]
del_if_unused_label(cmds, oldlabel)
i = max(0, i-3)
updated = True
continue
elif pos_to_label < i:
new_label = gen_new_label(cmds)
cmds[i:i+2] = [(cmd[0] + '_POP', new_label)]
cmds.insert(pos_to_label+2, ('.:', new_label))
del_if_unused_label(cmds, oldlabel)
i = max(0, pos_to_label-3) ### 27 08 2010 erlier pos_label (name of func)
updated = True
continue
else:
Fatal('/3', 'Unhandled', to_label, '???', pos_to_label)
i = i + 1
i = 0
## print '11', cmds
while i < (len(cmds) - 1):
cmd,b = cmds[i], cmds[i+1]
if (( cmd[0] == 'JUMP_IF_FALSE' or cmd[0] == 'JUMP_IF_TRUE' ) and b[0] == 'POP_TOP'):
to_label, pos_to_label = after_label(cmds, cmd[1], 3)
oldlabel = cmd[1]
if ( to_label[1][0] == 'JUMP_IF_FALSE_POP' and cmd[0] == 'JUMP_IF_FALSE') or\
( to_label[1][0] == 'JUMP_IF_TRUE_POP' and cmd[0] == 'JUMP_IF_TRUE'):
cmds[i:i+2] = [(cmd[0] + '_POP', to_label[1][1])]
del_if_unused_label(cmds, oldlabel)
i = max(0, i-3)
updated = True
continue
i = i + 1
i = 0
## print '12', cmds
while i < (len(cmds) - 1):
cmd,b = cmds[i], cmds[i+1]
if (( cmd[0] == 'JUMP_IF_FALSE' or cmd[0] == 'JUMP_IF_TRUE' ) and b[0] == 'POP_TOP'):
to_label, pos_to_label = after_label(cmds, cmd[1], 3)
oldlabel = cmd[1]
if len(to_label) >= 3 and to_label[2][0] == '.:' and \
(( to_label[1][0] == 'JUMP_IF_FALSE_POP' and cmd[0] == 'JUMP_IF_TRUE') or\
( to_label[1][0] == 'JUMP_IF_TRUE_POP' and cmd[0] == 'JUMP_IF_FALSE')):
cmds[i:i+2] = [(cmd[0] + '_POP', to_label[2][1])]
del_if_unused_label(cmds, oldlabel)
i = max(0, i-3)
updated = True
continue
i = i + 1
i = 1
## print '12-1', cmds
while i < (len(cmds) - 1) and i > 0:
prev,cmd,b = cmds[i-1],cmds[i], cmds[i+1]
if (( cmd[0] == 'JUMP_IF_FALSE' or cmd[0] == 'JUMP_IF_TRUE' ) and b[0] == 'POP_TOP' and prev[0] == 'LOAD_FAST'):
to_label, pos_to_label = after_label(cmds, cmd[1], 3)
oldlabel = cmd[1]
if ( to_label[1][0] == 'STORE_FAST' and \
to_label[1][1] == prev[1]):
if to_label[2][0] == '.:':
cmds[i:i+2] = [(cmd[0] + '_POP', to_label[2][1])]
del_if_unused_label(cmds, oldlabel)
i = max(0, i-3)
updated = True
continue
elif pos_to_label > i+2:
new_label = gen_new_label(cmds)
cmds.insert(pos_to_label+2, ('.:', new_label))
cmds[i:i+2] = [(cmd[0] + '_POP', new_label)]
del_if_unused_label(cmds, oldlabel)
i = max(0, i-3)
updated = True
continue
elif pos_to_label < i:
new_label = gen_new_label(cmds)
cmds[i:i+2] = [(cmd[0] + '_POP', new_label)]
cmds.insert(pos_to_label+2, ('.:', new_label))
del_if_unused_label(cmds, oldlabel)
i = max(0, pos_to_label-3)
updated = True
continue
i = i + 1
## print '15', cmds
return updated
## def print_cmds2(cmds, skip):
## if not print_pycmd:
## return
## pprint(cmds, out, 4, 120)
## return None
## ## skip += 4
## ## for cmd in cmds:
## ## if type(cmd) is list:
## ## print >>out, '{'
## ## print_cmds2(cmd, skip)
## ## print >>out, '}'
## ## continue
## ## if cmd[0] == '.L':
## ## print >>out, ' .L', cmd[1]
## ## elif cmd[0] == '.:':
## ## # decompile_fail = True
## ## print >>out, '^^',' ' * skip, cmd, ' # ', len(ref_to_label(cmd[1], cmds))
## ## elif is_cmdmem(cmd):
## ## # decompile_fail = True
## ## print >>out, '^^', ' ' * skip, cmd
## ## else:
## ## pprint(cmd, out, skip, 120)
## ## print >>out, ' ' * skip, cmd
def print_cmds(cmds):
if not print_pycmd:
return
print >>out, 'co_const:'
pprint(consts_from_cmds(cmds),out)
## skip = 0
pprint(cmds, out, 4, 120)
return None
## for cmd in cmds:
## if type(cmd) is list:
## print >>out, '{'
## print_cmds2(cmd, skip)
## print >>out, '}'
## continue
## if cmd[0] == '.L':
## print >>out, '^^',' .L', cmd[1]
## elif cmd[0] == '.:':
## print >>out, '^^',' ' * skip, cmd, ' # ', len(ref_to_label(cmd[1], cmds))
## elif cmd[0][0] == 'J':
## print >>out, '^^',' ' * skip, cmd, ' # ', len(ref_to_label(cmd[1], cmds))
## elif is_cmdmem(cmd):
## print >>out, '^^', ' ' * skip, cmd
## elif is_cmdmem(cmd):
## print >>out, '^^', ' ' * skip, cmd
## else:
## pprint(cmd, out, skip, 120)
## ## print >>out, ' ' * skip, cmd
## def ref_to_label(label, cmds):
## if type(cmds) is list and type(label) is int:
## return [i for i, x in enumerate(cmds) if type(x) is tuple and x[0][0] == 'J' and x[1] == label]
## else:
## Fatal('ref_to_label of tuple', label, cmds)
## return []
## def CntJump(label, cmds):
## if type(cmds) is list and type(label) is int:
## return len([x for x in cmds if type(x) is tuple and x[0][0] == 'J' and x[1] == label])
## else:
## Fatal('CntJump of tuple', label, cmds)
## return -1
## def OneJump(label, cmds):
## if type(cmds) is list and type(label) is int:
## return len([x for x in cmds if type(x) is tuple and x[0][0] == 'J' and x[1] == label]) == 1
## else:
## Fatal('OneJump of tuple', label, cmds)
## return False
cache_jumps = {}
def ClearJumpCache():
cache_jumps.clear()
def CountJumpCache(label, cmds):
if label in cache_jumps:
return cache_jumps[label]
if type(cmds) is list and type(label) is int:
v = len([x for x in cmds if type(x) is tuple and x[0][0] == 'J' and x[1] == label])
cache_jumps[label] = v
return v
else:
Fatal('CntJump of tuple', label, cmds)
return -1
def OneJumpCache(label, cmds):
if label in cache_jumps:
return cache_jumps[label] == 1
if type(cmds) is list and type(label) is int:
v = len([x for x in cmds if type(x) is tuple and x[0][0] == 'J' and x[1] == label])
cache_jumps[label] = v
return v == 1
else:
Fatal('OneJump of tuple', label, cmds)
return False
def TupleFromArgs(args):
if len(args) > 0 and args[0] in ('!BUILD_TUPLE', 'CONST'):
return args
if len([x for x in args if x[0] != 'CONST']) == 0:
return ('CONST', tuple([x[1] for x in args]))
return ('!BUILD_TUPLE', args)
def DictFromArgs(args):
return ('!BUILD_MAP', args)
def cmd2mem(cmd):
cm = cmd[0]
if cm == 'LOAD_CLOSURE':
return ('LOAD_CLOSURE', cmd[1])
if cm == 'LOAD_FAST':
return ('FAST', cmd[1])
if cm == 'LOAD_CONST':
return ('CONST', cmd[1])
if type(cmd) is tuple and type(cm) is str:
if cm[0:1] == '!':
return cmd
if cm in ('CONST', 'FAST'):
return cmd
if cm == 'PY_TYPE':
return cmd
Fatal('Illegal cms2mem', cmd)
return ()
def is_cmdmem(cmd):
a = cmd[0]
return a in ('CONST', 'FAST', 'LOAD_FAST', 'LOAD_CONST', 'LOAD_CLOSURE', 'PY_TYPE') \
or (a is not None and a[0] == '!')
def del_if_unused_label(cmds, oldlabel):
## print '/30', cmds
## print oldlabel, sys.getrefcount(oldlabel)
la = [x[1] for x in cmds if x[0][0] == 'J']
if oldlabel not in la:
i = 0
while i < len(cmds):
assert type(i) is int
cmd = cmds[i]
if cmd[0] == '.:' and cmd[1] == oldlabel:
if i > 0 and cmds[i-1][0] in jump and i < (len(cmds) - 1) and cmds[i+1][0] == 'POP_TOP':
del cmds[i]
del cmds[i]
continue
else:
del cmds[i]
if i > 0 and cmds[i][0] == '.L' and cmds[i-1][0] == '.L':
del cmds[i]
continue
return
i = i + 1
## print '/31', cmds
## print oldlabel, sys.getrefcount(oldlabel)
def gen_new_label(cmds):
return max( [x[1] for x in cmds if x[0] == '.:']) + 1
def after_label(cmds, label, n):
for i in range(len(cmds)):
cmd = cmds[i]
if type(cmd) is tuple and cmd[0] == '.:' and cmd[1] == label:
return cmds[i:i+n], i
def pos_label(cmds, label):
i = 0
while i < len(cmds):
assert type(i) is int
## cmd = cmds[i]
if cmds[i][0] == '.:' and cmds[i][1] == label:
return i
i = i + 1
def NoGoToGo(cmds):
## print '/1', cmds
while True:
updated = False
i = 0
while i < (len(cmds) - 3):
if cmds[i][0] == 'JUMP_IF_TRUE' and cmds[i+1][0] == 'JUMP' and cmds[i+2][0] == '.:' and \
cmds[i][1] == cmds[i+2][1] and cmds[i][1] != cmds[i+1][1]:
## if CountJumpCache(cmds[i][1], cmds) == 1:
## cmds[i:i+3] = [('JUMP_IF_FALSE', cmds[i+1][1])]
## else:
oldlabel = cmds[i+2][1]
## print '/1', sys.getrefcount(oldlabel)
cmds[i:i+3] = [('JUMP_IF_FALSE', cmds[i+1][1]), cmds[i+2]]
del_if_unused_label(cmds, oldlabel)
i = max(0, i-3)
updated = True
continue
if cmds[i][0] == 'JUMP_IF_FALSE' and cmds[i+1][0] == 'JUMP' and cmds[i+2][0] == '.:' and \
cmds[i][1] == cmds[i+2][1] and cmds[i][1] != cmds[i+1][1]:
## if CountJumpCache(cmds[i][1], cmds) == 1:
## cmds[i:i+3] = [('JUMP_IF_TRUE', cmds[i+1][1])]
## else:
oldlabel = cmds[i+2][1]
## print '/2', sys.getrefcount(oldlabel)
cmds[i:i+3] = [('JUMP_IF_TRUE', cmds[i+1][1]), cmds[i+2]]
del_if_unused_label(cmds, oldlabel)
i = max(0, i-3)
updated = True
continue
i += 1
## print '/2', cmds
i = 0
while i < len(cmds)-1:
assert type(i) is int
a,b = cmds[i], cmds[i+1]
if b[0] == '.:' and ((a[0] == 'JUMP_ABSOLUTE' or \
a[0] in jump) and a[1] == b[1]):
oldlabel = a[1]
del cmds[i]
updated = True
del_if_unused_label(cmds, oldlabel)
continue
i += 1
## print '/3', cmds
crossjump = {}
for i in range(len(cmds) - 1):
a,b = cmds[i], cmds[i+1]
if a[0] == '.:' and ((b[0] == 'JUMP_ABSOLUTE' or \
b[0] in jump) and a[1] != b[1]):
crossjump[a[1]] = b[1]
loopes = {}
## print '/4', cmds
for i in range(len(cmds)):
a = cmds[i]
if a[0] in ('J_SETUP_LOOP', 'J_SETUP_LOOP_FOR') and a[1] in crossjump:
loopes[a[1]] = i
i = 0
## print '/5', cmds
while i < len(cmds):
assert type(i) is int
## pre_cmd = ('',)
## if i > 0:
## pre_cmd = cmds[i-1]
cmd = cmds[i]
if cmd[0][0] == 'J' and cmd[1] in crossjump:
if cmd[1] not in loopes or (cmd[1] in loopes and loopes[cmd[1]] > i):
oldlabel = cmd[1]
cmds[i] = (cmd[0], crossjump[cmd[1]]) + cmd[2:]
del_if_unused_label(cmds, oldlabel)
updated = True
continue
i = i + 1
## print '/6', cmds
if not updated:
## print '/6.5', cmds
updated = set_conditional_jump_popped(cmds)
## print '/7', cmds
if not updated:
updated = del_dead_code(cmds)
## print '/8', cmds
if not updated:
return
## print '/9', cmds
def NoGoToReturn(cmds):
## crossjump = {}
return None
## for i in range(len(cmds) - 1):
## a,b = cmds[i], cmds[i+1]
## if a[0] == '.:' and b[0] == 'RETURN_VALUE' and len(b) == 2:
## crossjump[a[1]] = b
## elif a[0] == '.:' and type(b) is list and len(b) == 1 and \
## b[0][0] == 'RETURN_VALUE' and len(b[0]) == 2:
## crossjump[a[1]] = b[0]
## elif a[0] == '.:' and type(b) is list and len(b) == 2 and \
## b[0][0] == '.L' and b[1][0] == 'RETURN_VALUE' and len(b[0]) == 2:
## crossjump[a[1]] = b[1]
## i = 0
## while i < len(cmds):
## pre_cmd = ('',)
## if i > 0:
## pre_cmd = cmds[i-1]
## cmd = cmds[i]
## if cmd[0] in jump and cmd[1] in crossjump:
## oldlabel = cmd[1]
## cmds[i] = crossjump[cmd[1]]
## if type(cmds[i-1]) is list:
## cmds[i-1] += [cmds[i]]
## del cmds[i]
## del_if_unused_label(cmds, oldlabel)
## continue
## i = i + 1
def consts_from_cmds(cmds):
return dict.fromkeys([x[1] for x in cmds if x[0] == 'LOAD_CONST']).keys()
def walk(co, match=None):
if match is None or co.co_name == match:
dis(co)
for obj in co.co_consts:
if type(obj) is types.CodeType:
walk(obj, match)
def Pynm2Cnm(filename):
global c_name
pair = os.path.split(filename)
nmmodule = nmvar_to_loc(pair[1][:-3])
if c_name is not None:
outnm = c_name + '.c'
elif not build_executable:
outnm = nmmodule + '.c'
else:
## print filename, nmmodule, '.c'
outnm = nmmodule + '.c'
outnm = os.path.join(pair[0], outnm)
return outnm, nmmodule
def main():
global out
global out3
global debug
# global collect_stat
global filename
global TRUE
global no_build
global print_cline
global print_pyline
global make_indent
global direct_call
global stat_func
global Pass_Exit
global flag_stat
global opt_flag
global start_sys_modules
global hash_compile
global hide_debug
global dirty_iteritems
global redefined_attribute
global line_number
global build_executable
global no_generate_comment
global c_name
global calc_ref_total
global recalc_refcnt
global debug_tx
global no_tx
global no_cfunc
global print_pycmd
global inline_flag
global print_tree_node
global no_fastlocals
global current_co
TRUE = cmd2mem(('LOAD_CONST', True))
c_name = None
parser = OptionParser()
parser.add_option("-e", "--build-executable", action="store_true", dest="build_executable", default=False, help="build executable (not extension module)")
parser.add_option("", "--show-debug", action="store_false", dest="hide_debug", default=True, help="show compiler debug messages")
parser.add_option("-S", "--show-statistic", action="store_true", dest="flag_stat", default=False, help="show compiler internal statistic")
parser.add_option("", "--no-line-numbers", action="store_false", dest="line_number", default=True, help="supress line number code")
parser.add_option("", "--no-generate-comments", action="store_true", dest="no_generate_comment", default=False, help="supress internal tree comment")
parser.add_option("-c", "--no-compile", action="store_true", dest="no_build", default=False, help="only generate C-code, no compile")
parser.add_option("-i", "--indent", action="store_true", dest="make_indent", default=False, help="run \'indent\' for generated C file")
parser.add_option("-L", "--trace-py-line-numbers", action="store_true", dest="print_pyline", default=False, help="trace python line numbers")
parser.add_option("-l", "--trace-c-line-numbers", action="store_true", dest="print_cline", default=False, help="trace C line numbers")
parser.add_option("", "--no-direct-call", action="store_false", dest="direct_call", default=True, help="supress direct C call convenction")
parser.add_option("-d", "--decompiler-debug", action="store_true", dest="debug", default=False, help="trace decompilation")
parser.add_option("", "--decompiler-print", action="store_true", dest="print_pycmd", default=False, help="print decompilation psevdocode")
parser.add_option("", "--optimiser-debug", action="store_true", dest="debug_tx", default=False, help="trace optimisation")
parser.add_option("", "--no-optimiser", action="store_true", dest="no_tx", default=False, help="no text optimisation")
parser.add_option("", "--inline-subst", action="store_true", dest="inline_flag", default=False, help="inline subst of small's def")
parser.add_option("", "--not-use-fastlocals-array", action="store_true", dest="no_fastlocals", default=False, help="no faslocals array")
parser.add_option("", "--print-tree-node", action="store_true", dest="print_tree_node", default=False, help="print all passed tree node")
parser.add_option("-f", "--compiler-flag", action="store", type="string", dest="opt_flag")
parser.add_option("-n", "--c-named-as", action="store", type="string", dest="c_name")
parser.add_option("", "--no-cfunc", action="store_true", dest="no_cfunc", default=False, help="not generate cfunc")
(options, argv) = parser.parse_args()
debug = bool(options.debug)
no_fastlocals = bool(options.no_fastlocals)
print_pycmd = bool(options.print_pycmd)
build_executable = bool(options.build_executable)
hide_debug = bool(options.hide_debug)
flag_stat = bool(options.flag_stat)
line_number = bool(options.line_number)
no_generate_comment = bool(options.no_generate_comment)
no_build = bool(options.no_build)
make_indent = bool(options.make_indent)
print_pyline = bool(options.print_pyline)
print_cline = bool(options.print_cline)
direct_call = bool(options.direct_call)
debug_tx = bool(options.debug_tx)
no_tx = bool(options.no_tx)
no_cfunc = bool(options.no_cfunc)
opt_flag = options.opt_flag
if opt_flag is None:
opt_flag = ''
if len(opt_flag) > 0:
if ' ' in opt_flag:
opt_flag = opt_flag.split()
else:
opt_flag = [opt_flag]
else:
opt_flag = []
inline_flag = bool(options.inline_flag)
print_tree_node = bool(options.print_tree_node)
debug = options.debug
c_name = options.c_name
## codename = None
if calc_ref_total and "gettotalrefcount" not in sys.__dict__:
calc_ref_total = False
Debug('Can\'t generate "calc_ref_total" code for not Py_REF_DEBUG python')
if recalc_refcnt and "gettotalrefcount" not in sys.__dict__:
recalc_refcnt = False
Debug('Can\'t generate "recalc_refcnt" code for not Py_REF_DEBUG python')
if len(argv) == 0:
exit(1)
filenames = argv[0:]
listf1 = []
for filename in filenames:
listf = glob.glob(filename)
listf1.extend(listf)
listf = listf1
if len(listf) == 0:
print ('Files not found')
exit(1)
start_sys_modules = sys.modules.copy()
for filename in listf:
clear_one_file()
compilable = True
if filename.endswith('.py') or filename.endswith('.PY'):
print ('Compile ' + filename)
buf = open(filename).read()
redefined_attribute = ( '__slots__' in buf or '__get__' in buf or \
'__set__' in buf or '__delete__' in buf or \
'__getattribute__' in buf or \
'__delattr__' in buf or '__getattr__' in buf or \
'__delattr__' in buf )\
and filename != '2c.py'
if print_pycmd:
outnm = filename[:-3] + '.pycmd'
out = open(outnm, 'w')
else:
out = None
outnm, nmmodule = Pynm2Cnm(filename)
out3 = open(outnm, 'w')
is_compile = True
hash_compile = hash(buf)
try:
co = compile(buf, filename, "exec")
except SyntaxError:
buf = buf.replace('\r\n', '\n')
is_compile = False
if not is_compile:
try:
co = compile(buf, filename, "exec")
except:
print ('Error in ' + filename)
compilable = False
if compilable:
if co.co_flags & 0x10000 and not 'print' in d_built:
b = __import__('__builtin__')
d_built['print'] = b.__dict__["print"]
b = None
else:
if 'print' in d_built:
del d_built['print']
SetPass('DisAssemble')
walk(co)
post_disassemble()
clear_one_file()
co = None
current_co = None
if out is not None:
out.close()
if out3 is not None:
out3.close()
link_c()
co = compile('print 1\n', 'test.py', "exec")
clear_after_all_files()
co = None
current_co = None
def And_j_s(a,b):
a,b = cmd2mem(a), cmd2mem(b)
if a[0] == '!BOOLEAN' == b[0]:
return ('!BOOLEAN', And_bool(a,b))
if b[0] == '!AND_JUMPED_STACKED':
return ('!AND_JUMPED_STACKED', a) + b[1:]
if a[0] == '!AND_JUMPED_STACKED':
return a + (b,)
return ('!AND_JUMPED_STACKED', a,b)
def Or_j_s(a,b):
a,b = cmd2mem(a), cmd2mem(b)
if a[0] == '!BOOLEAN' == b[0]:
return ('!BOOLEAN', Or_bool(a,b))
if b[0] == '!OR_JUMPED_STACKED':
return ('!OR_JUMPED_STACKED', a) + b[1:]
if a[0] == '!OR_JUMPED_STACKED':
return a + (b,)
return ('!OR_JUMPED_STACKED', a,b)
def And_j(a,b):
a,b = cmd2mem(a), cmd2mem(b)
if a[0] == '!BOOLEAN' == b[0]:
return ('!BOOLEAN', And_bool(a,b))
if b[0] == '!AND_JUMP' == a[0]:
return a + b[1:]
if b[0] == '!AND_JUMP':
return ('!AND_JUMP', a) + b[1:]
if a[0] == '!AND_JUMP':
return a + (b,)
return ('!AND_JUMP', a,b)
def And_bool(a,b):
a,b = cmd2mem(a), cmd2mem(b)
if b[1][0] == '!AND_BOOLEAN' == a[1][0]:
return a[1] + b[1][1:]
if b[1][0] == '!AND_BOOLEAN':
return ('!AND_BOOLEAN', a) + b[1][1:]
if a[1][0] == '!AND_BOOLEAN':
return a[1] + (b,)
return ('!AND_BOOLEAN', a,b)
def Or_j(a,b):
a,b = cmd2mem(a), cmd2mem(b)
if a[0] == '!BOOLEAN' == b[0]:
return ('!BOOLEAN', Or_bool(a,b))
if b[0] == '!OR_JUMP' == a[0]:
return a + b[1:]
if b[0] == '!OR_JUMP':
return ('!OR_JUMP', a) + b[1:]
if a[0] == '!OR_JUMP':
return a + (b,)
return ('!OR_JUMP', a,b)
def Or_bool(a,b):
a,b = cmd2mem(a), cmd2mem(b)
if b[1][0] == '!OR_BOOLEAN' == a[1][0]:
return a[1] + b[1][1:]
if b[1][0] == '!OR_BOOLEAN':
return ('!OR_BOOLEAN', a) + b[1][1:]
if a[1][0] == '!OR_BOOLEAN':
return a[1] + (b,)
return ('!OR_BOOLEAN', a,b)
def Not(b):
if b[0] == '!1NOT':
return b[1]
return ('!1NOT', b)
def formire_call(t):
if '(' in t[2] and ')' in t[2]:
if t[2][-1] == ')':
t = list(t)
i = t[2].index('(')
t[2] = t[2][0:-1]
i = t[2].index('(')
t[2:3] = [t[2][:i], '(', t[2][i+1:]]
t = tuple(t) + (')',)
elif t[2][-1] != ')':
if t[2][-1] == '(':
t = list(t)
t[2] = t[2][0:-1]
t = tuple(t)
t = list(t)
t[2:3] = [t[2], '(']
i = 4
while i < len(t)-1:
assert type(i) is int
if t[i+1] != ',':
t[i:i+1] = [t[i], ',']
i += 2
t = tuple(t) + (')',)
return t
def Cls1(o, v):
if istempref(v):
clearref(o, v)
elif istemptyped(v):
clear_typed(v)
class Out(list):
def print_to(self, s):
self.append(s)
def append_cline(self):
if print_cline :
self.append('if (PyErr_Occurred()) {printf (\"ERROR %s\\n\",PyObject_REPR(PyErr_Occurred()));}')
self.append('printf (\"cline %d\\n\", __LINE__);')
def Cls(self, *vv):
for v in vv:
if istempref(v):
clearref(self, v)
elif istemptyped(v):
clear_typed(v)
else:
pass
def ZeroTemp(self, g):
if istempref(g):
self.Raw(g, ' = 0;')
if len(self) > 1 and self[-1] == self[-2]:
del self[-1]
def CLEAR(self, ref):
assert istempref(ref) or ref.startswith('temp[') or ref.startswith('GETLOCAL(') or ref.startswith('GETFREEVAR(')
self.append('Py_CLEAR(' + CVar(ref) + ');')
def INCREF(self, ref):
## assert istempref(ref)
self.append('Py_INCREF(' + CVar(ref) + ');')
def DECREF(self, ref):
## assert istempref(ref)
self.append('Py_DECREF(' + CVar(ref) + ');')
def XINCREF(self, ref):
## assert istempref(ref)
self.append('Py_XINCREF(' + CVar(ref) + ');')
def ClsFict(self, v):
if istempref(v):
clearref(self, v, True)
elif istemptyped(v):
clear_typed(v)
else:
pass
def Comment(self, it):
if no_generate_comment:
return None
if not isinstance(it, types.StringTypes):
##def pformat(object, indent=1, width=80, depth=None):
s = PrettyPrinter(indent=2, width=144).pformat(it)
## s = pformat(it, 2, 144)
if '/*' in s:
s = s.replace('/*', '/?*')
if '*/' in s:
s = s.replace('*/', '*?/')
ls = list(s.split('\n'))
if ls[-1] == '':
del ls[-1]
self.append('')
for iit in ls:
self.append('/* ' + iit + ' */')
def check_err(self, t0, eq):
if eq == 'NULL':
eq = '0'
self.Raw('if (', t0, ' == ', eq, ') goto ', labl, ';')
## add2 = ('if (', t0, '==', eq, ') goto', labl)
UseLabl()
## s = do_str(add2)
## self.append(s)
def PushInt(self, t, i):
assert istempref(t)
## self.Raw('PushInt ', t[1], ' ', i)
self.Raw(t, ' = PyInt_FromLong ( ', i, ' );')
## self.Raw('if ((', t, ' = PyInt_FromLong ( ', i, ' )) == 0) goto ', labl, ';')
## UseLabl()
def PushFloat(self, t, i):
assert istempref(t)
## self.Raw('PushInt ', t[1], ' ', i)
self.Raw(t, ' = PyFloat_FromDouble ( ', i, ' );')
## self.Raw('if ((', t, ' = PyInt_FromLong ( ', i, ' )) == 0) goto ', labl, ';')
## UseLabl()
def Raw(self, *t):
self.append(''.join([CVar(x) for x in t]))
# for it in t:
# s += CVar(it)
# self.append(s)
def Stmt(self, *t):
## if len(t) == 1 and t[0] == '':
## self.append('')
## return
if len(t) == 2 and t[0] == 'CLEARREF' and istempref(t[1]):
self.append('CLEARTEMP('+str(t[1][1]) + ');')
return
elif len(t) == 3 and type(t[0]) is tuple and t[1] == '='and IsCalcConst(t[0]):
self.append(do_str(t))
self.append_cline()
return
elif t[0] in CFuncVoid:
if t[0] == 'SETLOCAL' and t[1] not in current_co.used_fastlocals:
current_co.used_fastlocals[t[1]] = True
if current_co.list_compr_in_progress == False:
self.Stmt('LETLOCAL', t[1], t[2])
return
Used(t[0])
t2 = [t[0], '(']
for v in t[1:]:
t2.append(v)
t2.append(',')
if len(t) == 1:
t2.append(')')
else:
t2[-1] = ')'
self.append(do_str(tuple([CVar(x) for x in t2])))
self.append_cline()
return
elif t[0] in CFuncIntCheck:
Used(t[0])
t2 = mk_t2(t)
t2.append(') == -1) goto ' + CVar(labl))
UseLabl()
self.append(do_str(t2))
self.append_cline()
return
elif t[0] in CFuncIntAndErrCheck:
Used(t[0])
t2 = mk_t2(t)
t2.append(') == -1 && PyErr_Occurred()) goto ' + CVar(labl))
UseLabl()
self.append(do_str(t2))
self.append_cline()
return
elif t[0] in CFuncPyObjectRef:
Used(t[0])
t2 = mk_t2(t)
assert labl is not None
t2.append(') == 0) goto ' + CVar(labl))
UseLabl()
self.append(do_str(t2))
self.append_cline()
return
elif len(t) >= 3 and t[1] == '=' and t[0] != 'f->f_lineno' and \
(type(t[2]) != int and type(t[2]) != long and (type(t[2]) != tuple or t[2][0] != 'CONST')):
if len(t) == 5 and t[3] in ('==', '!='):
self.append(do_str(t))
self.append_cline()
return
if len(t) == 3 and t[2][0] == 'FAST' and t[0][0] == 'PY_TEMP':
self.append(do_str(t))
self.append_cline()
return
if len(t) == 4 and t[2][0] == '!' and t[0][0] == 'TYPED_TEMP' and t[3][0] == 'TYPED_TEMP':
self.append(do_str(t))
self.append_cline()
return
if istemptyped(t[2]) and istemptyped(t[0]):
self.append(do_str(t))
self.append_cline()
return
if istempref(t[0]) and t[2] in ('Py_True', 'Py_False'):
self.append(do_str(t))
self.append_cline()
return
if type(t[2]) is str and t[2].endswith('(glob,'):
t = list(t)
t[2:3] = [t[2][:-6], 'glob']
t = tuple(t)
t = formire_call(t)
if t[2] in CFuncNoCheck:
Used(t[2])
assign_py = t[0][0] == 'PY_TEMP'
t = [CVar(x) for x in t]
self.append(do_str(t))
self.append_cline()
if assign_py:
if t[2] not in ( 'PyIter_Next', 'Py_INCREF'):
Fatal(t, '???', t[2], 'Py_INCREF(' + t[0] + ');')
elif t[2] not in CFuncIntNotCheck and t[2] not in CFuncFloatNotCheck \
and t[2] not in CFuncLongNotCheck:
Fatal(t)
return
if t[2] in CFuncPyObjectRef:
Used(t[2])
assign_py = type(t[0]) is tuple and \
(t[0][0] == 'PY_TEMP' or t[0][:9] == 'GETLOCAL(')
t = [CVar(x) for x in t]
self.append(do_str(t))
self.append_cline()
if assign_py:
### COND_METH STRANGE
if self[-1].startswith(ConC(t[0], ' = ')) and self[-1].endswith(';'):
s0 = '(' + self[-1][:-1] + ')'
del self[-1]
self.check_err(s0, 'NULL')
else:
self.check_err(t[0], 'NULL')
if t[2] in CFuncNeedINCREF:
self.append('Py_INCREF(' + t[0] + ');')
elif not t[2] in CFuncNotNeedINCREF:
Debug('INCREF?', t)
self.append('Py_INCREF(' + t[0] + ');')
if checkmaxref != 0 and not is_pypy:
self.append('if ((' + t[0] + ')->ob_refcnt > ' + str(checkmaxref) + ') printf("line %5d, refcnt %6d \\n", __LINE__,(' + t[0] + ')->ob_refcnt);')
else:
Fatal(t)
return
if t[2] in set_IntCheck: #CFuncIntCheck or t[2] in CFuncLongCheck:
Used(t[2])
assign_temp = t[0][0] == 'TYPED_TEMP'
t = [CVar(x) for x in t]
self.append(do_str(t))
self.append_cline()
if assign_temp:
if self[-1].startswith(ConC(t[0], ' = ')) and self[-1].endswith(';'):
s0 = '(' + self[-1][:-1] + ')'
del self[-1]
self.check_err(s0, '-1' if t[2] not in CFuncIntAndErrCheck else '-1 && PyErr_Occurred()')
else:
self.check_err(t[0], '-1' if t[2] not in CFuncIntAndErrCheck else '-1 && PyErr_Occurred()')
# self.check_err(t[0], '-1' if t[2] not in CFuncIntAndErrCheck else '-1 && PyErr_Occurred()')
else:
Fatal(t)
return
elif type(t[2]) is str and t[2].startswith('_Direct_'):
assign_py = type(t[0]) is tuple and \
(t[0][0] == 'PY_TEMP' or t[0][:9] == 'GETLOCAL(')
t = [CVar(x) for x in t]
self.append(do_str(t))
self.append_cline()
if assign_py:
if self[-1].startswith(ConC(t[0], ' = ')) and self[-1].endswith(';'):
s0 = '(' + self[-1][:-1] + ')'
del self[-1]
self.check_err(s0, 'NULL')
else:
self.check_err(t[0], 'NULL')
if checkmaxref != 0 and not is_pypy:
self.append('if ((' + t[0] + ')->ob_refcnt > ' + str(checkmaxref) + ') printf("line %5d, refcnt %6d \\n", __LINE__,(' + t[0] + ')->ob_refcnt);')
else:
Fatal(t)
return
Fatal('Call undefined C-function', t[2], t)
elif t[0] in ( '}', '{', 'if'):
pass
elif maybe_call(t[0]):
t = list(t)
t[0:1] = [t[0], '(']
i = 2
while i < len(t)-1:
assert type(i) is int
if t[i+1] != ',':
t[i:i+1] = [t[i], ',']
i += 2
t = tuple(t) + (')',)
Used(t[0])
if t[0] not in CFuncVoid:
Fatal('Call undefined C-function', t[0],t)
self.append(do_str(t))
def TextMatch(s, p, v):
for i, p2 in enumerate(p):
if p2 == '*':
if i == len(p) - 1:
v.append(s)
return True
else:
ind = s.find(p[i+1])
if ind == -1:
return False
v.append(s[:ind])
s = s[ind:]
else:
if s.startswith(p2):
s = s[len(p2):]
else:
return False
if len(s) != 0:
return False
return True
Tx_compiled = {}
Tx_pre_compiled = {}
Tx_fast = {}
Tx_len_match = 0
Tx_pos_match = 0
Tx_pattern = None
Tx_cnt = {}
def TxMatch(o, pos_z, p2_, li, debug = False):
global Tx_cnt
if p2_ in Tx_cnt:
Tx_cnt[p2_] += 1
else:
Tx_cnt[p2_] = 1
if type(pos_z) is int and type(o) is Out and type(li) is list:
pos = pos_z
if p2_ in Tx_fast and not o[pos].startswith(Tx_fast[p2_]):
return False
if type(p2_) is str:
if p2_ not in Tx_pre_compiled:
p2 = TxPreCompile(p2_)
Tx_pre_compiled[p2_] = p2
else:
p2 = Tx_pre_compiled[p2_]
else:
p2 = p2_
if p2 not in Tx_compiled:
Tx_compiled[p2] = TxCompile(p2)
if type(Tx_compiled[p2][0][0]) is str:
Tx_fast[p2] = Tx_compiled[p2][0][0]
if p2 != p2_:
Tx_fast[p2_] = Tx_compiled[p2][0][0]
if pos >= len(o):
return False
o1 = o[pos]
assert type(o1) is str
if (o1 == '' or o1.startswith('/*') or\
o1.startswith('PyLine = ') or\
o1.startswith('PyAddr = ') or\
o1.startswith('f->f_lineno = ') or\
o1.startswith('f->f_lasti = ')):
return False
li[:] = (None, None, None, None, None, None, None, None, None, None, \
None, None, None, None, None, None, None, None, None, None) * 5
## pprint(Tx_compiled[p2])
## pprint(o)
pos_i = TxBaseMatch(pos, Tx_compiled[p2], o, li, debug)
## print li[:10]
if pos_i > 0:
global Tx_len_match, Tx_pattern, Tx_pos_match
Tx_len_match = pos_i - pos
Tx_pattern = p2
Tx_pos_match = pos
return True
return False
def TxBaseMatch(pos_i, patt, o, li, debug):
i = 0
if type(o) is Out and type(patt) is tuple and type(pos_i) is int and type(li) is list and type(debug) is bool:
while i < len(patt):
assert type(i) is int
assert type(pos_i) is int
while pos_i < len(o) and \
(o[pos_i] == '' or \
o[pos_i].startswith('/*') or\
o[pos_i].startswith('PyLine = ') or\
o[pos_i].startswith('PyAddr = ') or\
o[pos_i].startswith('f->f_lineno = ') or\
o[pos_i].startswith('f->f_lasti = ')):
pos_i += 1
if pos_i >= len(o):
return -1
p = patt[i]
if type(p) is tuple:
## print p, i
if TxMatch__(o[pos_i], p, li, debug):
if debug:
print ('/ %d success' % i, o[pos_i], p, li)
pos_i += 1
if i == len(patt) - 1:
return pos_i
elif pos_i >= len(o):
return -1
i += 1
continue
if debug:
print ('/ %d fail' % i, o[pos_i], p, li)
return -1
if type(p) is int:
if 60 > p >= 30 and li[p] is None:
i2 = pos_i
success = False
while i2 < len(o):
if o[i2].startswith('/*') or\
o[i2].startswith('PyLine = ') or\
o[i2].startswith('PyAddr = ') or\
o[i2].startswith('f->f_lineno = ') or\
o[i2].startswith('f->f_lasti = '):
return -1
## print p, i, i+1, patt[i+1]
## pprint(patt)
if type(patt[i+1]) is tuple and o[i2].startswith(patt[i+1][0]) :
li2 = li[:]
if TxMatch__(o[i2], patt[i+1], li2, False):
li[:] = li2
if debug:
print ('/ %d success' % i, o[pos_i:i2], p, li)
li[p] = o[pos_i:i2]
pos_i = i2
success = True
i += 1
break
if debug:
print ('/ %d fail' % i, o[pos_i:i2], o[i2], patt[i+1], li)
return -1
elif '{' in o[i2] or '}' in o[i2]:
if debug:
pprint(patt)
pprint(o[i2])
print (i+1)
print ('/ %d fail 93' % i, o[pos_i:i2], o[i2], patt[i+1], li)
return -1
##***
i2 += 1
if success == False:
if debug:
print ('/ %d fail 0' % i, o[pos_i:i2], o[i2], patt[i+1], li)
return -1
else:
continue
elif 90 > p >= 60 and li[p] is None:
i2 = pos_i
success = False
## print 'i2', i2
while i2 < len(o):
## print 'i2-0', i2
if o[i2].startswith('/*') or\
o[i2].startswith('PyLine = ') or\
o[i2].startswith('PyAddr = ') or\
o[i2].startswith('f->f_lineno = ') or\
o[i2].startswith('f->f_lasti = '):
return -1
## ## print p, i, i+1, patt[i+1]
## ## pprint(patt)
## print 'i2=', i2, 'i=', i, 'o[i2]=', o[i2], 'patt[i+1]=', patt[i+1]
if i + 1 == len(patt):
s3 = o[i2]
if not (s3.startswith('CLEARTEMP(') or\
s3.startswith('Py_CLEAR(temp[') or\
( s3.startswith('temp[') and \
s3.endswith('] = 0;'))):
if debug:
print ('/ %d success' % i, o[pos_i:i2], p, li)
li[p] = o[pos_i:i2]
pos_i = i2
success = True
i += 1
break
elif type(patt[i+1]) is tuple and o[i2].startswith(patt[i+1][0]) :
li2 = li[:]
## print 'li2'
if TxMatch__(o[i2], patt[i+1], li2, False):
li[:] = li2
if debug:
print ('/ %d success' % i, o[pos_i:i2], p, li)
li[p] = o[pos_i:i2]
pos_i = i2
for s3 in o[pos_i:i2]:
if not (s3.startswith('CLEARTEMP(') or\
s3.startswith('Py_CLEAR(temp[') or\
( s3.startswith('temp[') and \
s3.endswith('] = 0;'))):
if debug:
print ('/ %d fail 1 ' % i, o[pos_i:i2], o[i2], patt[i+1], li)
return -1
success = True
i += 1
break
if debug:
print ('/ %d fail' % i, o[pos_i:i2], o[i2], patt[i+1], li)
return -1
elif '{' in o[i2] or '}' in o[i2]:
if debug:
pprint(patt)
pprint(o[i2])
print (i+1)
print ('/ %d fail 9' % i, o[pos_i:i2], o[i2], patt[i+1], li)
return -1
##***
i2 += 1
## print 'i2+', i2
if success == False:
if debug:
print ('/ %d fail 5' % i, o[pos_i:i2], o[i2], patt[i+1], li)
return -1
else:
continue
elif 60 > p >= 30 and li[p] is not None:
if li[p] == o[pos_i:pos_i+len(li[p])]:
pos_i += len(li[p])
i += 1
continue
print (p, i)
pprint(patt)
assert False
else:
Fatal('massaraksh')
return 0
return pos_i
debug_tx = False
def TxRepl(o, pos, p2, li, used = None):
global debug_tx
global Tx_pos_match
pos = Tx_pos_match
if p2 not in Tx_compiled:
Tx_compiled[p2] = TxCompile(TxPreCompile(p2))
new = []
for p in Tx_compiled[p2]:
if type(p) is int:
new.extend(li[p])
else:
new.append(TxRepl__(p, li))
## new = [TxRepl__(p, li) for p in Tx_compiled[p2]]
print_patterns = True
if debug_tx:
print ('')
print ('')
print (' === BEFORE ' + pos)
for v in o[max(pos-2, 0):pos]:
print ' ', v
for v in o[pos:pos+Tx_len_match]:
print '>>', v
for v in o[pos+Tx_len_match:min(pos+Tx_len_match +2, len(o) - 1)]:
print ' ', v
if print_patterns:
print
print ' === Apply:'
for v in Tx_pattern:
print '??', v
print
print ' === Replace:'
if type(p2) is tuple:
for v in p2:
print '!!', v
elif type(p2) is str:
for v in p2.split('\n'):
v = v.strip()
if v != '':
print '!!', v.strip()
print
print ' === Memo:'
di = dict([(i, li1) for i,li1 in enumerate(li) if li1 is not None])
pprint(di)
print
print ' === After', pos
if o[pos:pos+Tx_len_match] == new:
Fatal ('Cycle modification', new)
o[pos:pos+Tx_len_match] = new
if debug_tx:
for v in o[max(pos-2, 0):pos]:
print ' ', v
for v in o[pos:pos+len(new)]:
print '<<', v
for v in o[pos+len(new):min(pos+len(new) +2, len(o) - 1)]:
print ' ', v
if used is not None:
for x in used:
Used(x)
def TxPreCompile(tupl):
if type(tupl) is str:
## tupl0 = tupl
tupl = tupl.strip()
tupl = tupl.splitlines()
tupl = [t.strip() for t in tupl if t.strip() != '']
tupl = [t.replace('\r', '') for t in tupl]
tupl = [t.replace('\n', '') for t in tupl]
tupl = [t.strip() for t in tupl if t.strip() != '']
tupl = [t.strip() for t in tupl if t.strip() != '']
tupl = tuple(tupl)
return tupl
def TxCompile(tupl):
compiled = []
for p in tupl:
assert type(p) is str
if len(p) > 0 and p[0] == '>' and len(p) >= 2 and len(p) <= 3:
compiled.append(int(p[1:]) + 30)
elif len(p) > 0 and p[0] == '<' and len(p) >= 2 and len(p) <= 3:
compiled.append(int(p[1:]) + 60)
else:
p = p.replace('$', '`$').split('`')
s3 = []
if len(p[0]) == 0:
p = p[1:]
for _s in p:
if _s[0] == '$':
assert len(_s) >= 2
if _s[1] == '1' and len(_s) > 2 and _s[2] >= '0' and _s[2] <= '9':
s3.append(int(_s[1] + _s[2]))
if len(_s) > 3:
s3.append(_s[3:])
else:
s3.append(int(_s[1]))
if len(_s) > 2:
s3.append(_s[2:])
else:
s3.append(_s)
compiled.append(tuple(s3))
return tuple(compiled)
def TxMatch__(s, p, li, debug = False):
if type(s) is str and type(li) is list and type(p) is tuple and type(debug) is bool:
for i, p2 in enumerate(p):
assert type(s) is str
if type(p2) is int:
if li[p2] == None:
if i == len(p) - 1:
li[p2] = s
return True
else:
p3 = p[i+1]
if type(p3) is str:
ind = s.find(p3)
assert type(ind) is int
if ind == -1:
if debug:
print p3 , 'not found'
return False
## assert type(s) is str
li[p2] = s[:ind]
s = s[ind:]
else:
Fatal('not str', p3)
return False
else:
p2 = li[p2]
if type(p2) is str:
if s.startswith(p2):
s = s[len(p2):]
else:
if debug:
print 'not started with2', p2, ':::', p
return False
if len(s) != 0:
return False
assert len(s) == 0
return True
else:
Fatal('strange types')
return False
def TxRepl__(p, li):
s = ''
## pprint(p)
## print li[:10]
for p2 in p:
## print repr(s), repr(p2)
if type(p2) is int:
## print li[p2]
s += li[p2]
else:
s += p2
return s
def repl_sk_typed_loc(s, beg, replbeg):
assert type(s) is str
l1, l2 = s.split(beg, 1)
if ')' not in l2:
return s
l2, l3 = l2.split(')', 1)
if ''.join(l2.split('_')).isalnum():
return l1 + replbeg + l2 + l3
return s
no_tx = False
no_cfunc = False
def optimize(o):
global current_co, debug_tx
## t1 = time.clock()
global no_tx
if no_tx:
return
assert type(o) is Out
i = 0
while i < len(o) - 1:
assert type(i) is int
## print 'ReStart optimise', i, current_co.co_name
for i in range(max(i - 200, 0), len(o)):
v2 = []
## v3 = []
# prev_i = int(i)
## if TxMatch(o, i, (), v2, True):
## TxRepl(o, i, (), v2)
## break
oi = o[i]
assert type(oi) is str
oiold = oi
if '(Loc_' in oi:
if '((Loc_' in oi:
oi = repl_sk_typed_loc(oi, '((Loc_', '(Loc_')
if '( (Loc_' in oi:
oi = repl_sk_typed_loc(oi, '( (Loc_', '( Loc_')
if ')(Loc_' in oi:
oi = repl_sk_typed_loc(oi, ')(Loc_', ')Loc_')
if '!(Loc_' in oi:
oi = repl_sk_typed_loc(oi, '!(Loc_', '!Loc_')
if '= (Loc_' in oi:
oi = repl_sk_typed_loc(oi, '= (Loc_', '= Loc_')
if oi is not oiold:
o[i] = oi
assert type(oi) is str
if i + 1 < len(o):
oi1 = o[i+1]
assert type(oi1) is str
if (oi1.startswith('CLEARTEMP(') or \
(oi1.startswith('temp[') and \
oi1.endswith('] = 0;') ) ):
if '{' not in oi and '}' not in oi and \
':' not in oi and \
'Trace' not in oi and \
' ;' not in oi and \
'Py_CLEAR' not in oi and \
'Py_INCREF' not in oi and \
'Py_DECREF' not in oi and \
not oi.startswith('CLEARTEMP(') and \
not oi.startswith('PyObject ') and \
not oi.startswith('long ') and \
not oi.startswith('int ') and \
not oi.startswith('temp = ') and \
not (oi.startswith('temp[') and oi.endswith('] = 0;') ) and \
';' in oi:
if 'temp[' not in o[i]:
o[i], o[i+1] = o[i+1], o[i]
## print 'success1', o[i], o[i+1]
break
else:
if o[i+1].startswith('CLEARTEMP('):
tempn = 'temp[' +o[i+1][10:-2] + ']'
else:
tempn = o[i+1][:-5]
if '(' in tempn or ')' in tempn or not tempn.startswith('temp[') or not tempn.endswith(']'):
Fatal('Unsiccess', o[i], o[i+1], tempn)
if tempn not in o[i]:
o[i], o[i+1] = o[i+1], o[i]
## print 'success2', tempn, o[i], o[i+1]
break
if not o[i].startswith('if ('):
if o[i] == '{':
if TxMatch(o, i, """
{
char __s[1];
__s[0] = (unsigned char)$3;
if ((temp[$0] = PyString_FromStringAndSize ( __s , 1 )) == 0) goto label_$10;
}
int_$11 = PyString_GET_SIZE ($12 );
temp[$1] = PyString_FromStringAndSize(NULL, 1 + int_$11);
charref_$7 = PyString_AS_STRING ( temp[$1] );
*charref_$7++ = *PyString_AS_STRING ( temp[$0] );
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
int_$11 = PyString_GET_SIZE ($12 );
temp[$1] = PyString_FromStringAndSize(NULL, 1 + int_$11);
charref_$7 = PyString_AS_STRING ( temp[$1] );
*charref_$7++ = (unsigned char)$3;
""", v2)
break
if o[i].startswith('temp['):
if tune_let_temp(o, i):
break
if o[i].startswith('Py_CLEAR(temp['):
if TxMatch(o, i, ('Py_CLEAR(temp[$1]);',
'temp[$1] = 0;'), v2):
TxRepl(o, i, ('CLEARTEMP($1);',), v2)
break
if TxMatch(o, i, ('Py_CLEAR(temp[$0]);',), v2):
TxRepl(o, i, ('CLEARTEMP($0);',), v2)
break
if 'PyInt_AsSsize_t' in o[i]:
if TxMatch(o, i, ('$1 = PyInt_AsSsize_t ( $8 );',
'if (PyInt_CheckExact( $8 ) && ($3 = PyInt_AS_LONG ( $8 )) < (INT_MAX-$4) ) {',
'temp[$0] = PyInt_FromLong ( $3 + $5 );',
'} else if (PyFloat_CheckExact( $8 )) {',
'temp[$0] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($8) + ((double)$5));',
'} else {',
'if ((temp[$0] = PyNumber_Add ( $8 , $6 )) == 0) goto $7;',
'}',
'$2 = PyInt_AsSsize_t ( temp[$0] );',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('$1 = PyInt_AsSsize_t ( $8 );',
'$2 = $1 + $5;'), v2)
break
if TxMatch(o, i, ('$1 = PyInt_AsSsize_t ( $8 );',
'if (PyInt_CheckExact( $8 ) && ($3 = PyInt_AS_LONG ( $8 )) < (INT_MAX-$4) ) {',
'temp[$0] = PyInt_FromLong ( $3 + $5 );',
'} else {',
'if ((temp[$0] = PyNumber_Add ( $8 , $6 )) == 0) goto $7;',
'}',
'$2 = PyInt_AsSsize_t ( temp[$0] );',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('$1 = PyInt_AsSsize_t ( $8 );',
'$2 = $1 + $5;'), v2)
break
if TxMatch(o, i, ('$2 = PyInt_AsSsize_t ( temp[$1] );',
'CLEARTEMP($1);',
'if (PyInt_CheckExact( $3 )) {',
'$5 = PyInt_AS_LONG ( $3 ) $7 $2;',
'} else {',
'if ((temp[$0] = PyInt_FromSsize_t($2)) == 0) goto $4;',
'if (($5 = PyObject_RichCompareBool ( $3 , temp[$0] , Py_$8 )) == -1) goto $4;',
'CLEARTEMP($0);',
'}'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $3 )) {',
'$2 = PyInt_AsSsize_t ( temp[$1] );',
'CLEARTEMP($1);',
'$5 = PyInt_AS_LONG ( $3 ) $7 $2;',
'} else {',
'if (($5 = PyObject_RichCompareBool ( $3 , temp[$1] , Py_$8 )) == -1) goto $4;',
'CLEARTEMP($1);',
'}'), v2)
break
if o[i].startswith('Py_INCREF') and i+1 < len(o):
if o[i+1].startswith('Py_INCREF'):
if TxMatch(o, i, """
Py_INCREF($1);
Py_INCREF($2);
Py_INCREF($5);
Py_INCREF($6);
Py_INCREF($7);
Py_INCREF($8);
Py_INCREF($9);
if ((temp[$3] = PyTuple_New ( 7 )) == 0) goto label_$4;
PyTuple_SET_ITEM ( temp[$3] , 0 , $1 );
PyTuple_SET_ITEM ( temp[$3] , 1 , $2 );
PyTuple_SET_ITEM ( temp[$3] , 2 , $5 );
PyTuple_SET_ITEM ( temp[$3] , 3 , $6 );
PyTuple_SET_ITEM ( temp[$3] , 4 , $7 );
PyTuple_SET_ITEM ( temp[$3] , 5 , $8 );
PyTuple_SET_ITEM ( temp[$3] , 6 , $9 );
""", v2):
TxRepl(o, i, """
if ((temp[$3] = PyTuple_Pack ( 7 , $1 , $2 , $5 , $6 , $7 , $8 , $9 )) == 0) goto label_$4;
""", v2)
break
if TxMatch(o, i, """
Py_INCREF($1);
Py_INCREF($2);
Py_INCREF($5);
Py_INCREF($6);
Py_INCREF($7);
Py_INCREF($8);
if ((temp[$3] = PyTuple_New ( 6 )) == 0) goto label_$4;
PyTuple_SET_ITEM ( temp[$3] , 0 , $1 );
PyTuple_SET_ITEM ( temp[$3] , 1 , $2 );
PyTuple_SET_ITEM ( temp[$3] , 2 , $5 );
PyTuple_SET_ITEM ( temp[$3] , 3 , $6 );
PyTuple_SET_ITEM ( temp[$3] , 4 , $7 );
PyTuple_SET_ITEM ( temp[$3] , 5 , $8 );
""", v2):
TxRepl(o, i, """
if ((temp[$3] = PyTuple_Pack ( 6 , $1 , $2 , $5 , $6 , $7 , $8 )) == 0) goto label_$4;
""", v2)
break
if TxMatch(o, i, """
Py_INCREF($1);
Py_INCREF($2);
Py_INCREF($5);
Py_INCREF($6);
Py_INCREF($7);
if ((temp[$3] = PyTuple_New ( 5 )) == 0) goto label_$4;
PyTuple_SET_ITEM ( temp[$3] , 0 , $1 );
PyTuple_SET_ITEM ( temp[$3] , 1 , $2 );
PyTuple_SET_ITEM ( temp[$3] , 2 , $5 );
PyTuple_SET_ITEM ( temp[$3] , 3 , $6 );
PyTuple_SET_ITEM ( temp[$3] , 4 , $7 );
""", v2):
TxRepl(o, i, """
if ((temp[$3] = PyTuple_Pack ( 5 , $1 , $2 , $5 , $6 , $7 )) == 0) goto label_$4;
""", v2)
break
if TxMatch(o, i, """
Py_INCREF($1);
Py_INCREF($2);
Py_INCREF($5);
Py_INCREF($6);
if ((temp[$3] = PyTuple_New ( 4 )) == 0) goto label_$4;
PyTuple_SET_ITEM ( temp[$3] , 0 , $1 );
PyTuple_SET_ITEM ( temp[$3] , 1 , $2 );
PyTuple_SET_ITEM ( temp[$3] , 2 , $5 );
PyTuple_SET_ITEM ( temp[$3] , 3 , $6 );
""", v2):
TxRepl(o, i, """
if ((temp[$3] = PyTuple_Pack ( 4 , $1 , $2 , $5 , $6 )) == 0) goto label_$4;
""", v2)
break
if TxMatch(o, i, """
Py_INCREF($1);
Py_INCREF($2);
Py_INCREF($5);
if ((temp[$3] = PyTuple_New ( 3 )) == 0) goto label_$4;
PyTuple_SET_ITEM ( temp[$3] , 0 , $1 );
PyTuple_SET_ITEM ( temp[$3] , 1 , $2 );
PyTuple_SET_ITEM ( temp[$3] , 2 , $5 );
""", v2):
TxRepl(o, i, """
if ((temp[$3] = PyTuple_Pack ( 3 , $1 , $2 , $5 )) == 0) goto label_$4;
""", v2)
break
if TxMatch(o, i, """
Py_INCREF($1);
Py_INCREF($2);
if ((temp[$3] = PyTuple_New ( 2 )) == 0) goto label_$4;
PyTuple_SET_ITEM ( temp[$3] , 0 , $1 );
PyTuple_SET_ITEM ( temp[$3] , 1 , $2 );
""", v2):
TxRepl(o, i, """
if ((temp[$3] = PyTuple_Pack ( 2 , $1 , $2 )) == 0) goto label_$4;
""", v2)
break
elif o[i] == 'Py_INCREF(Py_None);' and TxMatch(o, i, """
Py_INCREF(Py_None);
temp[$0] = Py_None;
CLEARTEMP($0);
""", v2):
TxRepl(o, i, '', v2)
break
elif 'PyInt_CheckExact' in o[i+1]:
if TxMatch(o, i, ('Py_INCREF($1);',
'if (PyInt_CheckExact( $1 ) && ($6 = PyInt_AS_LONG ( $1 )) < (INT_MAX-$2) ) {',
'temp[$0] = PyInt_FromLong ( $6 + $3 );',
'} else if (PyFloat_CheckExact( $1 )) {',
'temp[$0] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) + ((double)$3));',
'} else {',
'if ((temp[$0] = PyNumber_Add ( $1 , $4 )) == 0) goto $5;',
'}',
'if (PyInt_CheckExact( temp[$0] )) {',
'$7 = PyInt_AS_LONG ( temp[$0] );',
'if ( $7 < 0) {',
'$7 += PyList_GET_SIZE($8);',
'}',
'if ( PyList_SetItem ( $8 , $7 , $1 ) == -1) goto $5;',
'} else {',
'if ( PyObject_SetItem ( $8 , temp[$0] , $1 ) == -1) goto $5;',
'Py_DECREF($1);',
'}',
'CLEARTEMP($0);'), v2) and v2[6] != v2[7]:
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && ($6 = PyInt_AS_LONG ( $1 )) < (INT_MAX-$2) ) {',
'$7 = $6 + $3;',
'if ( $7 < 0) {',
'$7 += PyList_GET_SIZE($8);',
'}',
'Py_INCREF($1);',
'if ( PyList_SetItem ( $8 , $7 , $1 ) == -1) goto $5;',
'} else {',
'if ((temp[$0] = PyNumber_Add ( $1 , $4 )) == 0) goto $5;',
'if ( PyObject_SetItem ( $8 , temp[$0] , $1 ) == -1) goto $5;',
'CLEARTEMP($0);',
'}'), v2)
break
if TxMatch(o, i, ('Py_INCREF($6);',
'if (PyInt_CheckExact( $5 ) && ($9 = PyInt_AS_LONG ( $5 )) > INT_MIN ) {',
'temp[$2] = PyInt_FromLong ( $9 - 1 );',
'} else if (PyFloat_CheckExact( $5 )) {',
'temp[$2] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($5) - ((double)1));',
'} else {',
'if ((temp[$2] = PyNumber_Subtract ( $5 , $18 )) == 0) goto $8;',
'}',
'if (PyInt_CheckExact( temp[$2] )) {',
'$10 = PyInt_AS_LONG ( temp[$2] );',
'if ( $10 < 0) {',
'$10 += PyList_GET_SIZE($7);',
'}',
'if ( PyList_SetItem ( $7 , $10 , $6 ) == -1) goto $8;',
'} else {',
'if ( PyObject_SetItem ( $7 , temp[$2] , $6 ) == -1) goto $8;',
'Py_DECREF($6);',
'}',
'CLEARTEMP(2);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $5 ) && ($9 = PyInt_AS_LONG ( $5 )) > INT_MIN ) {',
'$10 = $9 - 1;',
'if ( $10 < 0) {',
'$10 += PyList_GET_SIZE($7);',
'}',
'Py_INCREF($6);',
'if ( PyList_SetItem ( $7 , $10 , $6 ) == -1) goto $8;',
'} else {',
'if ((temp[$2] = PyNumber_Subtract ( $5 , $18 )) == 0) goto $8;',
'if ( PyObject_SetItem ( $7 , temp[$2] , $6 ) == -1) goto $8;',
'CLEARTEMP(2);',
'}'), v2)
break
if TxMatch(o, i, ('Py_INCREF($6);',
'if (PyInt_CheckExact( $5 ) && ($9 = PyInt_AS_LONG ( $5 )) > INT_MIN ) {',
'temp[$2] = PyInt_FromLong ( $9 - 1 );',
'} else {',
'if ((temp[$2] = PyNumber_Subtract ( $5 , $18 )) == 0) goto $8;',
'}',
'if (PyInt_CheckExact( temp[$2] )) {',
'$10 = PyInt_AS_LONG ( temp[$2] );',
'if ( $10 < 0) {',
'$10 += PyList_GET_SIZE($7);',
'}',
'if ( PyList_SetItem ( $7 , $10 , $6 ) == -1) goto $8;',
'} else {',
'if ( PyObject_SetItem ( $7 , temp[$2] , $6 ) == -1) goto $8;',
'Py_DECREF($6);',
'}',
'CLEARTEMP(2);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $5 ) && ($9 = PyInt_AS_LONG ( $5 )) > INT_MIN ) {',
'$10 = $9 - 1;',
'if ( $10 < 0) {',
'$10 += PyList_GET_SIZE($7);',
'}',
'Py_INCREF($6);',
'if ( PyList_SetItem ( $7 , $10 , $6 ) == -1) goto $8;',
'} else {',
'if ((temp[$2] = PyNumber_Subtract ( $5 , $18 )) == 0) goto $8;',
'if ( PyObject_SetItem ( $7 , temp[$2] , $6 ) == -1) goto $8;',
'CLEARTEMP(2);',
'}'), v2)
break
if TxMatch(o, i, """
Py_INCREF(temp[$0]);
if (PyInt_CheckExact$2) {
long_$13 = $3;
long_$12 = $4;
if ($5) goto label_$16 ;
temp[$1] = PyInt_FromLong ($6);
} else if (PyFloat_CheckExact$7) {
temp[$1] = PyFloat_FromDouble($8);
} else { label_$16 :;
if ((temp[$1] = PyNumber_$9) == 0) goto label_$10;
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact$2) {
long_$13 = $3;
long_$12 = $4;
if ($5) goto label_$16 ;
temp[$1] = PyInt_FromLong ($6);
temp[$0] = 0;
} else if (PyFloat_CheckExact$7) {
temp[$1] = PyFloat_FromDouble($8);
temp[$0] = 0;
} else { label_$16 :;
Py_INCREF(temp[$0]);
if ((temp[$1] = PyNumber_$9) == 0) goto label_$10;
CLEARTEMP($0);
}
""", v2)
break
elif o[i+1].startswith('SETLOCAL'):
if TxMatch(o, i, """
Py_INCREF(Py_None);
SETLOCAL ( $0 , Py_None );
""", v2):
TxRepl(o, i, """
Py_XDECREF(GETLOCAL($0));
Py_INCREF(Py_None);
GETLOCAL($0) = Py_None;
""", v2)
break
if o[i+1].startswith('temp['):
if TxMatch(o, i, """
Py_INCREF(temp[$1]);
temp[$0] = 0;
if ((int_$3 = PyObject_IsTrue ( temp[$1] )) == -1) goto label_$4;
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
temp[$0] = 0;
if ((int_$3 = PyObject_IsTrue ( temp[$1] )) == -1) goto label_$4;
temp[$1] = 0;
""", v2)
break
if TxMatch(o, i, """
Py_INCREF(temp[$1]);
temp[$0] = 0;
if ((int_$3 = PyObject_Not ( temp[$1] )) == -1) goto label_$4;
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
temp[$0] = 0;
if ((int_$3 = PyObject_Not ( temp[$1] )) == -1) goto label_$4;
temp[$1] = 0;
""", v2)
break
if o[i+1].startswith('if ((int_'):
if TxMatch(o, i, """
Py_INCREF(temp[$1]);
if ((int_$3 = PyObject_IsTrue ( temp[$1] )) == -1) goto label_$4;
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if ((int_$3 = PyObject_IsTrue ( temp[$1] )) == -1) goto label_$4;
temp[$1] = 0;
""", v2)
break
if TxMatch(o, i, """
Py_INCREF(temp[$1]);
if ((int_$3 = PyObject_Not ( temp[$1] )) == -1) goto label_$4;
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if ((int_$3 = PyObject_Not ( temp[$1] )) == -1) goto label_$4;
temp[$1] = 0;
""", v2)
break
if TxMatch(o, i, """
Py_INCREF(temp[$1]);
CLEARTEMP($0);
int_$2 = temp[$1] $5= $3;
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
CLEARTEMP($0);
int_$2 = temp[$1] $5= $3;
temp[$1] = 0;
""", v2)
break
if True:
if i+2 < len(o):
if 'PyList_GetItem' in o[i+1] and TxMatch(o, i, """
Py_INCREF($3);
if ((temp[$0] = PyList_GetItem ( $4 , $5 )) == 0) goto label_$2;
Py_INCREF(temp[$0]);
if ((temp[$1] = PyTuple_New ( 2 )) == 0) goto label_$2;
PyTuple_SET_ITEM ( temp[$1] , 0 , $3 );
PyTuple_SET_ITEM ( temp[$1] , 1 , temp[$0] );
temp[$0] = 0;""", v2):
TxRepl(o, i, """
if ((temp[$0] = PyList_GetItem ( $4 , $5 )) == 0) goto label_$2;
if ((temp[$1] = PyTuple_Pack ( 2 , $3 , temp[$0] )) == 0) goto label_$2;
temp[$0] = 0;
""", v2)
break
if o[i+2].startswith('PyTuple_SET_ITEM') and TxMatch(o, i, """
Py_INCREF($1);
if ((temp[$3] = PyTuple_New ( 1 )) == 0) goto label_$4;
PyTuple_SET_ITEM ( temp[$3] , 0 , $1 );
""", v2):
TxRepl(o, i, """
if ((temp[$3] = PyTuple_Pack ( 1 , $1 )) == 0) goto label_$4;
""", v2)
break
if o[i].startswith('Py_INCREF(temp[') and o[i+2].startswith('CLEARTEMP('):
if TxMatch(o, i, ('Py_INCREF(temp[$2]);',
'if ((temp[$1] = __c_BINARY_SUBSCR_Int ( temp[$2] , $3 )) == 0) goto $4;',
'CLEARTEMP($2);'), v2):
TxRepl(o, i, ('if ((temp[$1] = ___c_BINARY_SUBSCR_Int ( temp[$2] , $3 )) == 0) goto $4;',
'temp[$2] = 0;'), v2, ('___c_BINARY_SUBSCR_Int',))
break
if TxMatch(o, i, ('Py_INCREF(temp[$0]);',
'if ((int_$1 = PyObject_IsTrue ( temp[$0] )) == -1) goto $3;',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('if ((int_$1 = PyObject_IsTrue ( temp[$0] )) == -1) goto $3;',
'temp[$0] = 0;'), v2)
break
if TxMatch(o, i, """
Py_INCREF(temp[$0]);
$1 = temp[$0];
CLEARTEMP($0);""", v2):
TxRepl(o, i, """
$1 = temp[$0];
temp[$0] = 0;""", v2)
if o[i] == '} else if (1) {' and TxMatch(o, i, ('} else if (1) {', '$1', '} else {', '$2', '}'), v2):
if '{' not in v2[1] and '{' not in v2[2] and \
'}' not in v2[1] and '}' not in v2[2] and \
':' not in v2[1] and ':' not in v2[2]:
TxRepl(o, i, ('} else {', '$1', '}'), v2)
break
if o[i].startswith('} else if (Py'):
if TxMatch(o, i, """
} else if (Py$1_CheckExact( $2 ) && Py$1_CheckExact( $2 )) {
""", v2):
TxRepl(o, i, """
} else if (Py$1_CheckExact( $2 )) {
""", v2)
break
if TxMatch(o, i, """
} else if (Py$1_CheckExact( temp[$2] ) && Py$1_CheckExact( temp[$2] )) {
""", v2):
TxRepl(o, i, """
} else if (Py$1_CheckExact( temp[$2] )) {
""", v2)
break
if TxMatch(o, i, """
} else if (PyInt_CheckExact( $9 )) {
long_$6 = PyInt_AS_LONG ( $9 );
long_$7 = PyInt_AS_LONG ( $9 );
if (long_$6 && long_$7 && (long_$6 * long_$7) / long_$7 == long_$6) {
temp[$0] = PyInt_FromLong ( long_$6 * long_$7 );
} else {
""", v2):
TxRepl(o, i, """
} else if (PyInt_CheckExact( $9 )) {
long_$6 = PyInt_AS_LONG ( $9 );
if (long_$6 && (long_$6 * long_$6) / long_$6 == long_$6) {
temp[$0] = PyInt_FromLong ( long_$6 * long_$6 );
} else {
""", v2)
break
if TxMatch(o, i, """
} else if (PyInt_CheckExact( temp[$9] )) {
long_$6 = PyInt_AS_LONG ( temp[$9] );
long_$7 = PyInt_AS_LONG ( temp[$9] );
if (long_$6 && long_$7 && (long_$6 * long_$7) / long_$7 == long_$6) {
temp[$0] = PyInt_FromLong ( long_$6 * long_$7 );
} else {
""", v2):
TxRepl(o, i, """
} else if (PyInt_CheckExact( temp[$9] )) {
long_$6 = PyInt_AS_LONG ( temp[$9] );
if (long_$6 && (long_$6 * long_$6) / long_$6 == long_$6) {
temp[$0] = PyInt_FromLong ( long_$6 * long_$6 );
} else {
""", v2)
break
if TxMatch(o, i, """
} else if (PyInt_CheckExact( temp[$12] )) {
long_$1 = PyInt_AS_LONG ( temp[$12] );
long_$2 = PyInt_AS_LONG ( temp[$12] );
if (!long_$1 || !long_$2 || (long_$1 * long_$2) / long_$2 == long_$1) {
temp[$3] = PyInt_FromLong ( long_$1 * long_$2 );
} else {
""", v2):
TxRepl(o, i, """
} else if (PyInt_CheckExact( temp[$12] )) {
long_$1 = PyInt_AS_LONG ( temp[$12] );
if (!long_$1 || (long_$1 * long_$1) / long_$1 == long_$1) {
temp[$3] = PyInt_FromLong ( long_$1 * long_$1 );
} else {
""", v2)
break
if o[i] == '{':
if TxMatch(o, i, """
{
char __s[1];
__s[0] = (unsigned char)long_$2;
if ((temp[$0] = PyString_FromStringAndSize ( __s , 1 )) == 0) goto $3;
}
int_$5 = PyString_GET_SIZE ( $4 );
int_$6 = PyString_GET_SIZE ( temp[$0] );
temp[$1] = PyString_FromStringAndSize(NULL, int_$5 + int_$6);
charref_$8 = PyString_AS_STRING ( temp[$1] );
memcpy(charref_$8, PyString_AS_STRING ( $4 ), int_$5);
charref_$8 += int_$5;
memcpy(charref_$8, PyString_AS_STRING ( temp[$0] ), int_$6);
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
int_$5 = PyString_GET_SIZE ( $4 );
temp[$1] = PyString_FromStringAndSize(NULL, int_$5 + 1);
charref_$8 = PyString_AS_STRING ( temp[$1] );
memcpy(charref_$8, PyString_AS_STRING ( $4 ), int_$5);
charref_$8 += int_$5;
charref_$8[0] = (unsigned char)long_$2;
""", v2)
break
if TxMatch(o, i, """
{
char __s[1];
__s[0] = (unsigned char)long_$11;
if ((temp[$0] = PyString_FromStringAndSize ( __s , 1 )) == 0) goto $3;
}
if (PyString_CheckExact(temp[$1])) {
int_$4 = (PyString_GET_SIZE(temp[$1]) == PyString_GET_SIZE(temp[$0])) && (PyString_AS_STRING(temp[$1])[0] == PyString_AS_STRING(temp[$0])[0]) && (memcmp(PyString_AS_STRING(temp[$1]), PyString_AS_STRING(temp[$0]), PyString_GET_SIZE(temp[$1])) == 0);
} else {
if ((int_$4 = PyObject_RichCompareBool ( temp[$1] , temp[$0] , Py_EQ )) == -1) goto $3;
}
CLEARTEMP($1);
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (PyString_CheckExact(temp[$1])) {
int_$4 = (PyString_GET_SIZE(temp[$1]) == 1) && (PyString_AS_STRING(temp[$1])[0] == (unsigned char)long_$11);
} else {
char __s[1];
__s[0] = (unsigned char)long_$11;
if ((temp[$0] = PyString_FromStringAndSize ( __s , 1 )) == 0) goto $3;
if ((int_$4 = PyObject_RichCompareBool ( temp[$1] , temp[$0] , Py_EQ )) == -1) goto $3;
CLEARTEMP($0);
}
CLEARTEMP($1);
""", v2)
break
if o[i].startswith('int_'):
if 'int_' in o[i][4:]:
if TxMatch(o, i, ('int_$1 = int_$1 ;',), v2):
TxRepl(o, i, (), v2)
break
if TxMatch(o, i, ('int_$1 = int_$1;',), v2):
TxRepl(o, i, (), v2)
break
if TxMatch(o, i, ('int_$1 = int_$1;',), v2):
TxRepl(o, i, (), v2)
break
if i+1 < len(o) and o[i+1].startswith('if ('):
if TxMatch(o, i, ('int_$1 = $12;',
'if (!( int_$1 )) {',
'int_$1 = $11;',
'}'), v2):
TxRepl(o, i, ('int_$1 = ($12) || ($11);',), v2)
break
if TxMatch(o, i, ('int_$1 = $12;',
'if ( !(int_$1) ) {',
'int_$1 = $11;',
'}'), v2):
TxRepl(o, i, ('int_$1 = ($12) || ($11);',), v2)
break
if TxMatch(o, i, ('int_$1 = $12;',
'if ( !int_$1 ) {',
'int_$1 = $11;',
'}'), v2):
TxRepl(o, i, ('int_$1 = ($12) || ($11);',), v2)
break
if TxMatch(o, i, ('int_$1 = $12;',
'if ( int_$1 ) {',
'int_$1 = $11;',
'}'), v2):
TxRepl(o, i, ('int_$1 = ($12) && ($11);',), v2)
break
else:
if TxMatch(o, i, """
int_$1 = $2temp[$3]$4;
CLEARTEMP($3);
Loc_int_$5 = int_$1;""", v2):
TxRepl(o, i, """
Loc_int_$5 = $2temp[$3]$4;
CLEARTEMP($3);""", v2)
break
if o[i] == '{' and TxMatch(o, i, ('{',
'char __s[1];',
'__s[0] = (unsigned char)$6;',
'if ((temp[$0] = PyString_FromStringAndSize ( __s , 1 )) == 0) goto $5;',
'}',
'$2 = *PyString_AS_STRING(temp[$0]);',
'Py_CLEAR(temp[$0]);',
'temp[$0] = 0;'), v2):
TxRepl(o, i, ('$2 = (unsigned char)$6;',), v2)
break
if o[i] == '{' and TxMatch(o, i, ('{',
'char __s[1];',
'__s[0] = (unsigned char)$6;',
'if ((temp[$0] = PyString_FromStringAndSize ( __s , 1 )) == 0) goto $5;',
'}',
'$2 = *PyString_AS_STRING ( temp[$0] );',
'Py_CLEAR(temp[$0]);',
'temp[$0] = 0;'), v2):
TxRepl(o, i, ('$2 = (unsigned char)$6;',), v2)
break
if o[i].startswith('double'):
if TxMatch(o, i, ('double_$4 = $3;',
'if ((temp[$0] = PyFloat_FromDouble ( double_$4 )) == 0) goto label_$0;',
'$5 = PyFloat_AsDouble(temp[$0]);',
'CLEARTEMP($0);',), v2):
TxRepl(o, i, ('$5 = $3;',), v2)
break
if TxMatch(o, i, ('double_$3 = Loc_double_$11;',
'double_$4 = Loc_double_$12;',
'double_$5 = double_$3 $0 double_$4;'), v2):
TxRepl(o, i, ('double_$5 = Loc_double_$11 $0 Loc_double_$12;',), v2)
break
if TxMatch(o, i, ('double_$3 = Loc_double_$11;',
'double_$4 = (double)PyInt_AsLong ( $15 );',
'double_$5 = double_$3 $0 double_$4;'), v2):
TxRepl(o, i, ('double_$5 = Loc_double_$11 $0 (double)PyInt_AsLong ( $15 );',), v2)
break
if TxMatch(o, i, ('double_$1 = $0;',
'return double_$1;'), v2):
TxRepl(o, i, ('return $0;',), v2)
break
if TxMatch(o, i, ('double_$5 = $0;',
'if ((temp[$6] = PyFloat_FromDouble ( double_$5 )) == 0) goto $10;'), v2):
TxRepl(o, i, ('if ((temp[$6] = PyFloat_FromDouble ( $0 )) == 0) goto $10;',), v2)
break
if TxMatch(o, i, ('$1 = PyFloat_AsDouble ( GETLOCAL($4) );',
'$2 = PyFloat_AsDouble ( GETLOCAL($5) );',
'$3 = $1 - $2;',
'if ((temp[$0] = PyFloat_FromDouble ( $3 )) == 0) goto $6;'), v2):
TxRepl(o, i, ('$3 = PyFloat_AsDouble ( GETLOCAL($4) ) - PyFloat_AsDouble ( GETLOCAL($5) );',
'if ((temp[$0] = PyFloat_FromDouble ( $3 )) == 0) goto $6;'), v2)
break
if TxMatch(o, i, """
double_$3 = PyFloat_AsDouble ( GETLOCAL($5) );
double_$4 = PyFloat_AsDouble ( GETLOCAL($5) );
if ((temp[$0] = PyFloat_FromDouble ( double_$3 $7 double_$4 )) == 0) goto label_$10;
""", v2) and not ' ' in v2[7]:
TxRepl(o, i, """
double_$3 = PyFloat_AsDouble ( GETLOCAL($5) );
if ((temp[$0] = PyFloat_FromDouble ( double_$3 $7 double_$3 )) == 0) goto label_$10;
""", v2)
break
if TxMatch(o, i, """
double_$3 = PyFloat_AsDouble ( GETLOCAL($11) );
double_$4 = PyFloat_AsDouble ( GETLOCAL($11) );
double_$9 = double_$3 + double_$4;
""", v2):
TxRepl(o, i, """
double_$9 = PyFloat_AsDouble ( GETLOCAL($11) ) * 2;
""", v2)
break
if TxMatch(o, i, """
double_$3 = PyFloat_AsDouble ( GETLOCAL($11) );
double_$4 = PyFloat_AsDouble ( GETLOCAL($11) );
double_$9 = double_$3 $7 double_$4;
""", v2) and not ' ' in v2[7]:
TxRepl(o, i, """
double_$3 = PyFloat_AsDouble ( GETLOCAL($11) );
double_$9 = double_$3 $7 double_$3;
""", v2)
break
if TxMatch(o, i, """
double_$3 = PyFloat_AsDouble ( GETLOCAL($5) );
double_$4 = PyFloat_AsDouble ( GETLOCAL($6) );
if ((temp[$0] = PyFloat_FromDouble ( double_$3 $7 double_$4 )) == 0) goto label_$10;
""", v2) and not ' ' in v2[7]:
TxRepl(o, i, """
if ((temp[$0] = PyFloat_FromDouble ( PyFloat_AsDouble ( GETLOCAL($5) ) $7 PyFloat_AsDouble ( GETLOCAL($6) ) )) == 0) goto label_$10;
""", v2)
break
if TxMatch(o, i, """
double_$3 = PyFloat_AsDouble ( GETLOCAL($11) );
double_$4 = PyFloat_AsDouble ( GETLOCAL($12) );
double_$9 = double_$3 $7 double_$4;
""", v2) and not ' ' in v2[7]:
TxRepl(o, i, """
double_$9 = PyFloat_AsDouble ( GETLOCAL($11) ) $7 PyFloat_AsDouble ( GETLOCAL($12) );
""", v2)
break
if TxMatch(o, i, """
double_$3 = $11;
double_$4 = Loc_double_$12;
double_$9 = double_$3 $7 double_$4;
""", v2) and not ' ' in v2[7] and ' ' in v2[11]:
TxRepl(o, i, """
double_$9 = ($11) $7 Loc_double_$12;
""", v2)
break
if TxMatch(o, i, """
double_$3 = (double)( Loc_long_$10 );
double_$4 = double_$3 $7 $11;
""", v2) and not ' ' in v2[7]:
TxRepl(o, i, """
double_$4 = (double)( Loc_long_$10 ) $7 $11;
""", v2)
break
## if TxMatch(o, i, """
## double_$3 = $14;
## double_$4 = double_$3 $7 $11;
## """, v2) and not ' ' in v2[7] and ' ' in v2[14]:
## TxRepl(o, i, """
## double_$4 = ($14) $7 $11;
## """, v2)
## break
if TxMatch(o, i, """
double_$4 = $14;
Loc_double_$15 = double_$4 $7 $11;
""", v2) and not ' ' in v2[7] and ' ' in v2[14]:
TxRepl(o, i, """
Loc_double_$15 = ($14) $7 $11;
""", v2)
break
if TxMatch(o, i, """
double_$13 = exp ( double_$12 );
double_$12 = $14 $15 double_$13;
""", v2) and not ' ' in v2[14] and not ' ' in v2[15]:
TxRepl(o, i, """
double_$12 = $14 $15 exp ( double_$12 );
""", v2)
break
if TxMatch(o, i, """
double_$13 = $3;
double_$12 = $14 $15 double_$13;
""", v2) and not ' ' in v2[14] and not ' ' in v2[15] and ' ' in v2[3]:
TxRepl(o, i, """
double_$12 = $14 $15 ( $3 );
""", v2)
break
if TxMatch(o, i, """
double_$17 = PyFloat_AS_DOUBLE ( temp[$1] );
if ((temp[$2] = PyFloat_FromDouble ($18)) == 0) goto label_$0;
} else {
""", v2) and v2[18].count('(double_' + v2[17] + ')') == 1:
tupl = v2[18].rpartition('(double_' + v2[17] + ')')
v2[18] = tupl[0] + 'PyFloat_AS_DOUBLE ( temp[' + v2[1] + '] )' + tupl[2]
TxRepl(o, i, """
if ((temp[$2] = PyFloat_FromDouble ($18)) == 0) goto label_$0;
} else {
""", v2)
break
if TxMatch(o, i, """
double_$17 = PyFloat_AS_DOUBLE ( GETLOCAL($1) );
if ((temp[$2] = PyFloat_FromDouble ($18)) == 0) goto label_$0;
} else {
""", v2) and v2[18].count('(double_' + v2[17] + ')') == 1:
tupl = v2[18].rpartition('(double_' + v2[17] + ')')
v2[18] = tupl[0] + 'PyFloat_AS_DOUBLE ( GETLOCAL(' + v2[1] + ') )' + tupl[2]
TxRepl(o, i, """
if ((temp[$2] = PyFloat_FromDouble ($18)) == 0) goto label_$0;
} else {
""", v2)
break
if o[i].startswith('long'):
if TxMatch(o, i, """
long_$4 = ($6_GET_SIZE($7));
temp[$0] = PyInt_FromLong ( (long_$4 $5 $1) );
""", v2):
TxRepl(o, i, """temp[$0] = PyInt_FromLong ( $6_GET_SIZE($7) $5 $1 );""", v2)
break
if TxMatch(o, i, """
long_$4 = $5;
temp[$14] = PyInt_FromLong ( long_$4 );
""", v2):
TxRepl(o, i, """temp[$14] = PyInt_FromLong ( $5 );""", v2)
break
if TxMatch(o, i, """
long_$2 = ($6_GET_SIZE($7));
long_$4 = long_$2 $3 $8;
""", v2):
TxRepl(o, i, """long_$4 = ($6_GET_SIZE($7)) $3 $8;""", v2)
break
if TxMatch(o, i, """
long_$4 = ( Py$7_GET_SIZE($8) $9 $10 );
if ( !(($6 $5 long_$4)) ) {
""", v2):
TxRepl(o, i, """if ( !($6 $5 ( Py$7_GET_SIZE($8) $9 $10 )) ) {""", v2)
break
if TxMatch(o, i, ('long_$8 = $18;',
'long_$11 = Loc_long_$19;',
'long_$7 = long_$8 + long_$11;',
'if (( long_$7 ^ long_$8 ) < 0 && ( long_$7 ^ long_$11 ) < 0) goto label_$12 ;'), v2):
TxRepl(o, i, ('long_$8 = $18;',
'long_$7 = long_$8 + Loc_long_$19;',
'if (( long_$7 ^ long_$8 ) < 0 && ( long_$7 ^ Loc_long_$19 ) < 0) goto label_$12 ;'), v2)
break
## if TxMatch(o, i, ('long_$4 = $1;',
## 'if ((temp[$2] = PyInt_FromLong ( long_$4 )) == 0) goto $0;'), v2):
## TxRepl(o, i, ('if ((temp[$2] = PyInt_FromLong ( $1 )) == 0) goto $0;',), v2)
## break
if TxMatch(o, i, ('long_$1 = (long)$3;',
'long_$2 = long_$1;',
'long_$1 = long_$2 + 1;'), v2):
TxRepl(o, i, ('long_$1 = ((long)$3) + 1;',), v2)
break
if TxMatch(o, i, ('long_$4 = $2;',
'temp[$1] = PyInt_FromLong ( long_$4 );',
'long_$4 = PyInt_AS_LONG ( temp[$1] );',
'CLEARTEMP($1);'), v2):
v2[2] = v2[2].strip()
TxRepl(o, i, ('long_$4 = $2;', ), v2)
break
if TxMatch(o, i, ('long_$2 = $1;',
'long_$4 = $3;',
'int_$11 = long_$2 $5 long_$4;'), v2):
v2[1] = v2[1].strip()
v2[3] = v2[3].strip()
TxRepl(o, i, ('int_$11 = ($1) $5 ($3);', ), v2)
break
if TxMatch(o, i, ('long_$4 = $1;',
'Py_ssize_t_$2 = long_$4;'), v2):
TxRepl(o, i, ('Py_ssize_t_$2 = $1;',), v2)
break
if TxMatch(o, i, ('long_$2 = long_$1 + 1;',
'long_$1 = long_$2;'), v2):
TxRepl(o, i, ('long_$1 = long_$1 + 1;',), v2)
break
if TxMatch(o, i, ('long_$2 = $3;', 'long_$1 = long_$2;'), v2):
TxRepl(o, i, ('long_$1 = $3;',), v2)
break
if TxMatch(o, i, ('long_$4 = $1;',
'Loc_long_$2 = long_$4;'), v2):
TxRepl(o, i, ('Loc_long_$2 = $1;',), v2)
break
if TxMatch(o, i, ('long_$1 = $2;',
'long_$1 = long_$1 + 1;'), v2):
TxRepl(o, i, ('long_$1 = ($2) + 1;',), v2)
break
if TxMatch(o, i, """long_$0 = $3;
long_$1 = Glob_long_$4;
long_$2 = long_$0 - long_$1;
if (( long_$2 ^ long_$0 ) < 0 && ( long_$2 ^~ long_$1 ) < 0) goto $5 ;""", v2) and\
not ' ' in v2[4]:
TxRepl(o, i, """long_$0 = $3;
long_$2 = long_$0 - Glob_long_$4;
if (( long_$2 ^ long_$0 ) < 0 && ( long_$2 ^~ Glob_long_$4 ) < 0) goto $5 ;""", v2)
break
if TxMatch(o, i, """long_$0 = $3;
long_$1 = Loc_long_$4;
long_$2 = long_$0 - long_$1;
if (( long_$2 ^ long_$0 ) < 0 && ( long_$2 ^~ long_$1 ) < 0) goto $5 ;""", v2) and\
not ' ' in v2[4]:
TxRepl(o, i, """long_$0 = $3;
long_$2 = long_$0 - Loc_long_$4;
if (( long_$2 ^ long_$0 ) < 0 && ( long_$2 ^~ Loc_long_$4 ) < 0) goto $5 ;""", v2)
break
if TxMatch(o, i, """long_$2 = Loc_long_$6;
long_$4 = PyInt_AS_LONG ( $5 );
long_$1 = long_$2 + long_$4;
if (( long_$1 ^ long_$2 ) < 0 && ( long_$1 ^ long_$4 ) < 0) goto $9 ;""", v2):
TxRepl(o, i, """long_$4 = PyInt_AS_LONG ( $5 );
long_$1 = Loc_long_$6 + long_$4;
if (( long_$1 ^ Loc_long_$6 ) < 0 && ( long_$1 ^ long_$4 ) < 0) goto $9 ;""", v2)
break
if TxMatch(o, i, """
long_$3 = $10;
long_$4 = long_$3 * $5;
if (long_$4 / $5 == long_$3) {
temp[$2] = PyInt_FromLong (long_$4);
} else {
temp[$0] = $11;
temp[$2] = $12;
CLEARTEMP($0);
}
long_$15 = PyInt_AS_LONG ( temp[$2] );
""", v2):
TxRepl(o, i, """
long_$3 = $10;
temp[$2] = PyInt_FromLong (long_$3 * $5);
long_$15 = PyInt_AS_LONG ( temp[$2] );
""", v2)
break
if TxMatch(o, i, "long_$2 = ( long_$5 );", v2) and ' ' not in v2[5]:
TxRepl(o, i, "long_$2 = long_$5;", v2)
break
if TxMatch(o, i, """
long_$3 = $0 + 1;
Loc_long_$2 = ( long_$3 );
""", v2):
v2[0] = v2[0].strip()
TxRepl(o, i, "Loc_long_$2 = $0 + 1;", v2)
break
if TxMatch(o, i, """
long_$4 = $1;
Loc_long_$2 = ( long_$4 );""", v2):
v2[1] = v2[1].strip()
TxRepl(o, i, "Loc_long_$2 = ( $1 );", v2)
break
if TxMatch(o, i, ('$2 = PyInt_AS_LONG ( $1 );',
'$3 = 0 - $2;',
'temp[$4] = PyInt_FromLong ( $3 );'), v2):
TxRepl(o, i, ('temp[$4] = PyInt_FromLong ( - PyInt_AS_LONG ( $1 ) );',), v2)
break
if TxMatch(o, i, """
long_$2 = PyInt_AS_LONG ( $5 );
if (PyInt_CheckExact( $6 )) {
int_$1 = long_$2 $7 PyInt_AS_LONG ( $6 );
} else {
if ((int_$1 = PyObject_RichCompareBool ( $5 , $6 , Py_$8 )) == -1) goto label_$0;
}
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $6 )) {
int_$1 = PyInt_AS_LONG ( $5 ) $7 PyInt_AS_LONG ( $6 );
} else {
if ((int_$1 = PyObject_RichCompareBool ( $5 , $6 , Py_$8 )) == -1) goto label_$0;
}
""", v2)
break
if TxMatch(o, i, """
long_$5 = $9 ;
long_$6 = long_$5 - 1;
temp[$0] = PyInt_FromLong ( long_$6 );
if ((temp[$1] = $11) == 0) goto label_$10;
CLEARTEMP($0);
""", v2) and ' ' not in v2[9]:
TxRepl(o, i, """
temp[$0] = PyInt_FromLong ( $9 - 1 );
if ((temp[$1] = $11) == 0) goto label_$10;
CLEARTEMP($0);
""", v2)
break
if TxMatch(o, i, """
long_$5 = $9 ;
long_$6 = long_$5 $2 $3;
temp[$0] = PyInt_FromLong ( long_$6 );
if ($15) goto label_$10;
CLEARTEMP($0);
""", v2) and ' ' not in v2[9] and v2[2] in '+-' and v2[3].isdigit():
TxRepl(o, i, """
temp[$0] = PyInt_FromLong ( $9 $2 $3 );
if ($15) goto label_$10;
CLEARTEMP($0);
""", v2)
break
if TxMatch(o, i, """
long_$4 = $1 ;
long_$4 = long_$4 $2 $3;
""", v2) and ' ' not in v2[1] and v2[2] in '+-' and v2[3].isdigit():
TxRepl(o, i, """
long_$4 = $1 $2 $3;
""", v2)
break
if TxMatch(o, i, """
long_$4 = $3;
temp[$1] = PyInt_FromLong ( long_$4 );
if ( _PyEval_AssignSlice ( $5 , temp[$1] , NULL , temp[$0] ) == -1) goto label_$6;
CLEARTEMP($0);
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if ( PySequence_SetSlice ( $5 , $3 , PY_SSIZE_T_MAX , temp[$0] ) == -1) goto label_$6;
CLEARTEMP($0);
""", v2)
break
if TxMatch(o, i, """
long_$6 = PyInt_AS_LONG ( $2 );
long_$5 = long_$6 + $7;
temp[$1] = PyInt_FromLong ( long_$5 );
if ( _PyEval_AssignSlice ( $4 , $2 , temp[$1] , temp[$0] ) == -1) goto label_$3;
CLEARTEMP($0);
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
long_$6 = PyInt_AS_LONG ( $2 );
if ( PySequence_SetSlice ( $4 , long_$6 , long_$6 + $7 , temp[$0] ) == -1) goto label_$3;
CLEARTEMP($0);
""", v2)
break
if TxMatch(o, i, """
long_$3 = 0;
if ((temp[$1] = PyList_GetItem ( $5 , long_$3 )) == 0) goto label_$0;
Py_INCREF(temp[$1]);
long_$4 = long_$3 + 1;
if ( PyList_SetSlice ( $5 , long_$3 , long_$4 , NULL ) == -1) goto label_$0;
""", v2):
TxRepl(o, i, """
if ((temp[$1] = PyList_GetItem ( $5 , 0 )) == 0) goto label_$0;
Py_INCREF(temp[$1]);
if ( PyList_SetSlice ( $5 , 0 , 1 , NULL ) == -1) goto label_$0;
""", v2)
break
if TxMatch(o, i, """
long_$3 = PyInt_AS_LONG ( $11 ) $12 $14;
temp[$0] = PyInt_FromLong ( long_$3 );
int_$2 = PyInt_AS_LONG ( temp[$0] ) $15 $16;
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
int_$2 = ( PyInt_AS_LONG ( $11 ) $12 $14 ) $15 $16;
""", v2)
break
if TxMatch(o, i, ('long_$1 = long_$1;',), v2):
TxRepl(o, i, (), v2)
break
if TxMatch(o, i, """
long_$11 = PyInt_AS_LONG ( $10 );
if (long_$11 < LONG_BIT) {
temp[$0] = PyInt_FromLong ( 0x1 << long_$11 );
} else {
if ((temp[$0] = PyNumber_Lshift($4, $10)) == 0) goto label_$2;
}
if (PyInt_CheckExact( temp[$0] )) {
long_$13 = PyInt_AS_LONG ( temp[$0] );
long_$12 = long_$13 $7 $5;
if ($18) goto label_$3 ;
temp[$1] = PyInt_FromLong ( long_$12 );
} else if (PyFloat_CheckExact( temp[$0] )) {
temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$0]) $7 ((double)$5));
} else { label_$3 :;
if ((temp[$1] = PyNumber_$8 ( temp[$0] , $6 )) == 0) goto label_$2;
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
long_$11 = PyInt_AS_LONG ( $10 );
if (long_$11 < LONG_BIT) {
long_$13 = 0x1 << long_$11;
long_$12 = long_$13 $7 $5;
if ($18) goto label_$3 ;
temp[$1] = PyInt_FromLong ( long_$12 );
} else { label_$3 :;
if ((temp[$0] = PyNumber_Lshift($4, $10)) == 0) goto label_$2;
if ((temp[$1] = PyNumber_$8 ( temp[$0] , $6 )) == 0) goto label_$2;
CLEARTEMP($0);
}
""", v2)
break
if TxMatch(o, i, """
long_$6 = PyInt_AS_LONG ( GETLOCAL($1) );
long_$5 = long_$6 $12 $11;
temp[$0] = PyInt_FromLong ( long_$5 );
SETLOCAL ( $1 , temp[$0] );
temp[$0] = 0;
""", v2):
TxRepl(o, i, """
long_$6 = PyInt_AS_LONG ( GETLOCAL($1) );
Py_DECREF(GETLOCAL($1));
GETLOCAL($1) = PyInt_FromLong ( long_$6 $12 $11 );
""", v2)
break
if TxMatch(o, i, """
long_$6 = PyInt_AS_LONG ( GETLOCAL($1) );
long_$5 = long_$6 $12 $11;
temp[$0] = PyInt_FromLong ( long_$5 );
""", v2):
TxRepl(o, i, """
temp[$0] = PyInt_FromLong ( PyInt_AS_LONG ( GETLOCAL($1) ) $12 $11 );
""", v2)
break
if TxMatch(o, i, """
long_$0 = $10;
long_$1 = PyInt_AS_LONG ( $9 );
long_$2 = long_$1 + long_$0;
if (( long_$2 ^ long_$1 ) < 0 && ( long_$2 ^ long_$0 ) < 0) goto label_$3 ;
temp[$5] = PyInt_FromLong ( long_$2 );
if (1) {
} else { label_$3 :;
temp[$6] = PyInt_FromLong ( long_$0 );
if ((temp[$5] = PyNumber_Add ( $9 , temp[$6] )) == 0) goto label_$4;
CLEARTEMP($6);
}
if (($7 = _PyEval_ApplySlice ( $8 , $9 , temp[$5] )) == 0) goto label_$4;
CLEARTEMP($5);
""", v2):
TxRepl(o, i, """
long_$0 = $10;
long_$1 = PyInt_AS_LONG ( $9 );
long_$2 = long_$1 + long_$0;
if (( long_$2 ^ long_$1 ) < 0 && ( long_$2 ^ long_$0 ) < 0) goto label_$3 ;
if (($7 = PySequence_GetSlice ( $8 , long_$1 , long_$2 )) == 0) goto label_$4;
if (0) { label_$3 :;
temp[$6] = PyInt_FromLong ( long_$0 );
if ((temp[$5] = PyNumber_Add ( $9 , temp[$6] )) == 0) goto label_$4;
CLEARTEMP($6);
if (($7 = _PyEval_ApplySlice ( $8 , $9 , temp[$5] )) == 0) goto label_$4;
CLEARTEMP($5);
}
""", v2)
break
if o[i].startswith('Py_ssize_t'):
if TxMatch(o, i, ('Py_ssize_t_$2 = $11;',
'CLEARTEMP($0);',
'int_$1 = Py_ssize_t_$2 == $10;'), v2):
TxRepl(o, i, ('int_$1 = $11 == $10;',
'CLEARTEMP($0);'), v2)
break
if TxMatch(o, i, ('Py_ssize_t_$2 = $11;',
'CLEARTEMP($0);',
'int_$1 = Py_ssize_t_$2 >= $10;'), v2):
TxRepl(o, i, ('int_$1 = $11 >= $10;',
'CLEARTEMP($0);'), v2)
break
if TxMatch(o, i, ('Py_ssize_t_$2 = $11;',
'CLEARTEMP($0);',
'int_$1 = Py_ssize_t_$2 > $10;'), v2):
TxRepl(o, i, ('int_$1 = $11 > $10;',
'CLEARTEMP($0);'), v2)
break
if TxMatch(o, i, ('Py_ssize_t_$1 = Py_ssize_t_$1 ;',), v2):
TxRepl(o, i, (), v2)
if o[i].startswith('CLEARTEMP'):
if i+1 < len(o):
if o[i] == o[i+1]:
del o[i+1]
break
if o[i+1].startswith('temp[') and TxMatch(o, i, ('CLEARTEMP($0);', 'temp[$0] = 0;'), v2):
del o[i+1]
break
if i < (len(o) - 1) and ' = ' in o[i] and o[i+1].startswith('temp['):
if TxMatch(o, i, ('$2 = $3;',
'temp[$1] = PyInt_FromLong ( $2 );',
'if (PyInt_CheckExact( $6 )) {',
'$7 = PyInt_AS_LONG ( $6 );',
'$8 = PyInt_AS_LONG ( temp[$1] );',
'$9 = $7 + $8;',
'if (( $9 ^ $7 ) < 0 && ( $9 ^ $8 ) < 0) goto $5 ;',
'temp[$0] = PyInt_FromLong ( $9 );',
'} else if (PyFloat_CheckExact( $6 )) {',
'temp[$0] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($6) + (double)PyInt_AS_LONG ( temp[$1] ));',
'} else { $5 :;',
'if ((temp[$0] = PyNumber_$15Add ( $6 , temp[$1] )) == 0) goto $4;',
'}',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $6 )) {',
'$7 = PyInt_AS_LONG ( $6 );',
'$8 = $3;',
'$9 = $7 + $8;',
'if (( $9 ^ $7 ) < 0 && ( $9 ^ $8 ) < 0) goto $5 ;',
'temp[$0] = PyInt_FromLong ( $9 );',
'} else if (PyFloat_CheckExact( $6 )) {',
'temp[$0] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($6) + (double)($3));',
'} else { $5 :;',
'temp[$1] = PyInt_FromLong ( $3 );',
'if ((temp[$0] = PyNumber_$15Add ( $6 , temp[$1] )) == 0) goto $4;',
'CLEARTEMP($1);',
'}'), v2)
break
if TxMatch(o, i, ('$2 = $3;',
'temp[$1] = PyInt_FromLong ( $2 );',
'if (PyInt_CheckExact( $6 )) {',
'$7 = PyInt_AS_LONG ( $6 );',
'$8 = PyInt_AS_LONG ( temp[$1] );',
'$9 = $7 + $8;',
'if (( $9 ^ $7 ) < 0 && ( $9 ^ $8 ) < 0) goto $5 ;',
'temp[$0] = PyInt_FromLong ( $9 );',
'} else { $5 :;',
'if ((temp[$0] = PyNumber_$15Add ( $6 , temp[$1] )) == 0) goto $4;',
'}',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $6 )) {',
'$7 = PyInt_AS_LONG ( $6 );',
'$8 = $3;',
'$9 = $7 + $8;',
'if (( $9 ^ $7 ) < 0 && ( $9 ^ $8 ) < 0) goto $5 ;',
'temp[$0] = PyInt_FromLong ( $9 );',
'} else { $5 :;',
'temp[$1] = PyInt_FromLong ( $3 );',
'if ((temp[$0] = PyNumber_$15Add ( $6 , temp[$1] )) == 0) goto $4;',
'CLEARTEMP($1);',
'}'), v2)
break
if TxMatch(o, i, ('$2 = $3;',
'temp[$1] = PyInt_FromLong ( $2 );',
'if (PyInt_CheckExact( $6 )) {',
'$7 = PyInt_AS_LONG ( $6 );',
'$8 = PyInt_AS_LONG ( temp[$1] );',
'$9 = $7 + $8;',
'if (( $9 ^ $7 ) < 0 && ( $9 ^ $8 ) < 0) goto $5 ;',
'temp[$0] = PyInt_FromLong ( $9 );',
'} else if (PyFloat_CheckExact( $6 )) {',
'temp[$0] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($6) + (double)PyInt_AS_LONG ( temp[$1] ));',
'} else { $5 :;',
'if ((temp[$0] = PyNumber_$15Add ( $6 , temp[$1] )) == 0) goto $4;',
'}',
'CLEARTEMP($14);',
'CLEARTEMP($1);'), v2) and v2[1] != v2[14]:
TxRepl(o, i, ('if (PyInt_CheckExact( $6 )) {',
'$7 = PyInt_AS_LONG ( $6 );',
'$8 = $3;',
'$9 = $7 + $8;',
'if (( $9 ^ $7 ) < 0 && ( $9 ^ $8 ) < 0) goto $5 ;',
'temp[$0] = PyInt_FromLong ( $9 );',
'} else if (PyFloat_CheckExact( $6 )) {',
'temp[$0] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($6) + (double)($3));',
'} else { $5 :;',
'temp[$1] = PyInt_FromLong ( $3 );',
'if ((temp[$0] = PyNumber_$15Add ( $6 , temp[$1] )) == 0) goto $4;',
'CLEARTEMP($1);',
'}',
'CLEARTEMP($14);'), v2)
break
if TxMatch(o, i, ('$2 = $3;',
'temp[$1] = PyInt_FromLong ( $2 );',
'if (PyInt_CheckExact( $6 )) {',
'$7 = PyInt_AS_LONG ( $6 );',
'$8 = PyInt_AS_LONG ( temp[$1] );',
'$9 = $7 + $8;',
'if (( $9 ^ $7 ) < 0 && ( $9 ^ $8 ) < 0) goto $5 ;',
'temp[$0] = PyInt_FromLong ( $9 );',
'} else { $5 :;',
'if ((temp[$0] = PyNumber_$15Add ( $6 , temp[$1] )) == 0) goto $4;',
'}',
'CLEARTEMP($14);',
'CLEARTEMP($1);'), v2) and v2[1] != v2[14]:
TxRepl(o, i, ('if (PyInt_CheckExact( $6 )) {',
'$7 = PyInt_AS_LONG ( $6 );',
'$8 = $3;',
'$9 = $7 + $8;',
'if (( $9 ^ $7 ) < 0 && ( $9 ^ $8 ) < 0) goto $5 ;',
'temp[$0] = PyInt_FromLong ( $9 );',
'} else { $5 :;',
'temp[$1] = PyInt_FromLong ( $3 );',
'if ((temp[$0] = PyNumber_$15Add ( $6 , temp[$1] )) == 0) goto $4;',
'CLEARTEMP($1);',
'}',
'CLEARTEMP($14);'), v2)
break
if i < (len(o) - 1) and o[i] == '} else' and o[i+1] == '{':
o[i] = '} else {'
del o[i+1]
break
if o[i].startswith('f->f_lineno = ') and TxMatch(o, i, ('f->f_lineno = $0;',
'f->f_lasti = $1;',
'f->f_lineno = $2;',
'f->f_lasti = $3;'), v2):
TxRepl(o, i, ('f->f_lineno = $2;',
'f->f_lasti = $3;'), v2)
break
if o[i] == 'for (;;) {' and TxMatch(o, i, ('for (;;) {',
'int_$0 = $1;',
'if (!( int_$0 )) break;'), v2):
TxRepl(o, i, ('while ($1) {',), v2)
break
if len(o) > i + 1 and \
(o[i].startswith('goto ') or o[i].startswith('return ') or \
o[i].startswith('break;') or o[i].startswith('continue;')):
i2 = i+1
while i2 < len(o) and (o[i2].startswith('/*') or o[i2] == ''):
i2 += 1
if i2 < len(o):
if o[i2].startswith('PyErr_Restore'):
del o[i2]
break
if o[i2].startswith('_PyEval_reset_exc_info'):
del o[i2]
break
if TxMatch(o, i2, """
Py_INCREF($1);""", v2):
TxRepl(o, i2, '', v2)
break
if TxMatch(o, i2, """
Py_CLEAR($1);""", v2):
TxRepl(o, i2, '', v2)
break
if TxMatch(o, i2, """
CLEARTEMP($1);""", v2):
TxRepl(o, i2, '', v2)
break
if TxMatch(o, i2, """
return $1;""", v2):
TxRepl(o, i2, '', v2)
break
if TxMatch(o, i2, """
if (tstate->frame->f_exc_type != NULL) {
_PyEval_reset_exc_info ( f->f_tstate );
}""", v2):
TxRepl(o, i2, '', v2)
break
if TxMatch(o, i2, """Py_LeaveRecursiveCall();""", v2):
TxRepl(o, i2, '', v2)
break
if TxMatch(o, i2, """tstate->frame = f->f_back;""", v2):
TxRepl(o, i2, '', v2)
break
if o[i].startswith('if ('):
if o[i].endswith(';'):
if tune_if_dotcomma(o, i):
break
elif o[i].endswith('{'):
if tune_if_sk(o, i):
break
if o[i] == 'if (1) {' and o[i+2] == '} else {' and o[i+4] == '}' and \
'{' not in o[i+1] and '{' not in o[i+3] and \
'}' not in o[i+1] and '}' not in o[i+3] and \
':' not in o[i+1] and ':' not in o[i+3]:
o[i:i+5] = [o[i+1]]
break
if '= long_' in o[i]:
if TxMatch(o, i, ('if $0((long_$1 = long_$1)$2',), v2):
TxRepl(o, i, ('if $0(long_$1$2',), v2)
break
for i in range(len(o)):
if o[i].startswith('SETLOCAL ( ') and o[i].endswith('] );') and 'temp[' in o[i]:
if TxMatch(o, i, ('SETLOCAL ( $0 , temp[$1] );',), v2):
TxRepl(o, i, ('SETLOCAL2 ( $0 , temp[$1] );',), v2)
## t2 = time.clock()
## global t_opt
## t_opt += t2 - t1
## pprint(o)
def tune_let_temp(o, i):
v2 = []
if '*_PyObject_GetDictPtr' in o[i]:
if TxMatch(o, i, """
temp[$1] = *_PyObject_GetDictPtr($5);
if ((temp[$2] = PyDict_GetItem ( temp[$1] , $6 )) == 0) goto label_$4;
Py_INCREF(temp[$2]);
temp[$1] = 0;
if ((int_$3 = Py$8 ( temp[$2] )) == -1) goto label_$4;
CLEARTEMP($2);
if ( !(int_$3)) {
temp[$0] = Py_$9;
Py_INCREF(temp[$0]);
} else {
temp[$1] = *_PyObject_GetDictPtr($5);
if ((temp[$0] = PyDict_GetItem ( temp[$1] , $7 )) == 0) goto label_$4;
Py_INCREF(temp[$0]);
temp[$1] = 0;
}
""" , v2):
TxRepl(o, i, """
temp[$1] = *_PyObject_GetDictPtr($5);
if ((temp[$2] = PyDict_GetItem ( temp[$1] , $6 )) == 0) goto label_$4;
Py_INCREF(temp[$2]);
if ((int_$3 = Py$8 ( temp[$2] )) == -1) goto label_$4;
CLEARTEMP($2);
if ( !(int_$3)) {
temp[$0] = Py_$9;
Py_INCREF(temp[$0]);
} else {
if ((temp[$0] = PyDict_GetItem ( temp[$1] , $7 )) == 0) goto label_$4;
Py_INCREF(temp[$0]);
}
temp[$1] = 0;
""", v2)
return True
if TxMatch(o, i, """
temp[$1] = *_PyObject_GetDictPtr($0);
Py_INCREF(temp[$1]);
if ((temp[$2] = PyDict_GetItem ( temp[$1] , $3 )) == 0) goto label_$4;
Py_INCREF(temp[$2]);
CLEARTEMP($1);
""" , v2):
TxRepl(o, i, """
temp[$1] = *_PyObject_GetDictPtr($0);
if ((temp[$2] = PyDict_GetItem ( temp[$1] , $3 )) == 0) goto label_$4;
Py_INCREF(temp[$2]);
temp[$1] = 0;
""", v2)
return True
if TxMatch(o, i, """
temp[$0] = *_PyObject_GetDictPtr($9);
if ((temp[$1] = PyDict_GetItem ( temp[$0] , $3 )) == 0) goto label_$10;
temp[$0] = 0;
if ((int_$7 = PyObject_$5 ( temp[$1] )) == -1) goto label_$10;
temp[$1] = 0;
if ( $19int_$7 ) {
temp[$0] = *_PyObject_GetDictPtr($9);
if ((temp[$1] = PyDict_GetItem ( temp[$0] , $4 )) == 0) goto label_$10;
temp[$0] = 0;
if ((int_$7 = PyObject_$6 ( temp[$1] )) == -1) goto label_$10;
temp[$1] = 0;
}
""" , v2):
TxRepl(o, i, """
temp[$0] = *_PyObject_GetDictPtr($9);
if ((temp[$1] = PyDict_GetItem ( temp[$0] , $3 )) == 0) goto label_$10;
if ((int_$7 = PyObject_$5 ( temp[$1] )) == -1) goto label_$10;
temp[$1] = 0;
if ( $19int_$7 ) {
if ((temp[$1] = PyDict_GetItem ( temp[$0] , $4 )) == 0) goto label_$10;
if ((int_$7 = PyObject_$6 ( temp[$1] )) == -1) goto label_$10;
temp[$1] = 0;
}
temp[$0] = 0;
""", v2)
return True
if TxMatch(o, i, """
temp[$0] = *_PyObject_GetDictPtr($3);
if ((temp[$1] = PyDict_GetItem ( temp[$0] , $4 )) == 0) goto label_$2;
temp[$0] = 0;
if ((int_$11 = PyObject_$9 ( temp[$1] )) == -1) goto label_$2;
temp[$1] = 0;
if ( $7int_$11 ) {
temp[$0] = *_PyObject_GetDictPtr($3);
if ((temp[$1] = PyDict_GetItem ( temp[$0] , $5 )) == 0) goto label_$2;
if ((int_$11 = PyObject_$10 ( temp[$1] )) == -1) goto label_$2;
temp[$1] = 0;
if ( $8int_$11 ) {
if ((temp[$1] = PyDict_GetItem ( temp[$0] , $6 )) == 0) goto label_$2;
if ((int_$11 = PyObject_IsTrue ( temp[$1] )) == -1) goto label_$2;
temp[$1] = 0;
}
temp[$0] = 0;
}
""" , v2):
TxRepl(o, i, """
temp[$0] = *_PyObject_GetDictPtr($3);
if ((temp[$1] = PyDict_GetItem ( temp[$0] , $4 )) == 0) goto label_$2;
if ((int_$11 = PyObject_$9 ( temp[$1] )) == -1) goto label_$2;
temp[$1] = 0;
if ( $7int_$11 ) {
if ((temp[$1] = PyDict_GetItem ( temp[$0] , $5 )) == 0) goto label_$2;
if ((int_$11 = PyObject_$10 ( temp[$1] )) == -1) goto label_$2;
temp[$1] = 0;
if ( $8int_$11 ) {
if ((temp[$1] = PyDict_GetItem ( temp[$0] , $6 )) == 0) goto label_$2;
if ((int_$11 = PyObject_IsTrue ( temp[$1] )) == -1) goto label_$2;
temp[$1] = 0;
}
}
temp[$0] = 0;
""", v2)
return True
if TxMatch(o, i, """
temp[$0] = *_PyObject_GetDictPtr($9);
if ((temp[$1] = PyDict_GetItem ( temp[$0] , $8 )) == 0) goto label_$7;
Py_INCREF(temp[$1]);
temp[$0] = 0;
CLEARTEMP($1);
""" , v2):
TxRepl(o, i, '', v2)
return True
if 'PyDict_GetItem' in o[i]:
if TxMatch(o, i, """
temp[$0] = PyDict_GetItem(_$3_dict, $1);
Py_INCREF(temp[$0]);
if (_$4_dict) {
if (PyDict_SetItem(_$4_dict, $2, temp[$0]) == -1) goto label_$10;
} else {
if ( PyObject_SetAttr ( GETLOCAL($4) , $2 , temp[$0] ) == -1) goto label_$10;
}
CLEARTEMP($0);
""" , v2):
TxRepl(o, i, """
if (_$4_dict) {
if (PyDict_SetItem(_$4_dict, $2, PyDict_GetItem(_$3_dict, $1)) == -1) goto label_$10;
} else {
temp[$0] = PyDict_GetItem(_$3_dict, $1);
Py_INCREF(temp[$0]);
if ( PyObject_SetAttr ( GETLOCAL($4) , $2 , temp[$0] ) == -1) goto label_$10;
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
temp[$0] = PyDict_GetItem$15($11,$12);
if ((int_$1 = PyObject_IsTrue ( temp[$0] )) == -1) goto label_$10;
temp[$0] = 0;
""" , v2):
TxRepl(o, i, """
if ((int_$1 = PyObject_IsTrue ( PyDict_GetItem$15($11,$12) )) == -1) goto label_$10;
""", v2)
return True
if TxMatch(o, i, """
temp[$0] = PyDict_GetItem$15($11,$12);
if ((int_$1 = PyObject_Not ( temp[$0] )) == -1) goto label_$10;
temp[$0] = 0;
""" , v2):
TxRepl(o, i, """
if ((int_$1 = PyObject_Not ( PyDict_GetItem$15($11,$12) )) == -1) goto label_$10;
""", v2)
return True
if TxMatch(o, i, """
temp[$0] = PyDict_GetItem($3, $4);
Py_INCREF(temp[$0]);
Py_ssize_t_$2 = PyInt_AsSsize_t ( temp[$0] );
CLEARTEMP($0);
""" , v2):
TxRepl(o, i, """
Py_ssize_t_$2 = PyInt_AsSsize_t ( PyDict_GetItem($3, $4) );
""", v2)
return True
if TxMatch(o, i, """
temp[$0] = PyDict_GetItem($3, $4);
Py_INCREF(temp[$0]);
if ((temp[$1] = PyList_GetItem ( temp[$0] , $5 )) == 0) goto label_$2;
Py_INCREF(temp[$1]);
CLEARTEMP($0);
""" , v2) and ('temp[%s]' % v2[0]) not in v2[5]:
TxRepl(o, i, """
if ((temp[$1] = PyList_GetItem ( PyDict_GetItem($3, $4) , $5 )) == 0) goto label_$2;
Py_INCREF(temp[$1]);
""", v2)
return True
if TxMatch(o, i, """
temp[$0] = PyDict_GetItem($9, $4);
Py_INCREF(temp[$0]);
temp[$1] = PyDict_GetItem($11, $5);
Py_INCREF(temp[$1]);
if ((temp[$2] = _Direct_$7 ( temp[$0] , temp[$1] )) == 0) goto label_$10;
CLEARTEMP($0);
CLEARTEMP($1);
if (PyDict_SetItem($12, $6, temp[$2]) == -1) goto label_$10;
CLEARTEMP($2);
""" , v2):
TxRepl(o, i, """
if ((temp[$2] = _Direct_$7 ( PyDict_GetItem($9, $4) , PyDict_GetItem($11, $5) )) == 0) goto label_$10;
if (PyDict_SetItem($12, $6, temp[$2]) == -1) goto label_$10;
CLEARTEMP($2);
""", v2)
return True
if 'PyInt_FromLong' in o[i]:
if let_temp_PyInt_FromLong(o, i):
return True
if 'PyFloat_FromDouble' in o[i]:
if TxMatch(o, i, """
temp[$1] = PyFloat_FromDouble($10);
temp[$2] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$1])$11);
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
temp[$2] = PyFloat_FromDouble(($10)$11);
""", v2)
return True
if TxMatch(o, i, ('temp[$1] = PyFloat_FromDouble ($2);',
'double_$3 = PyFloat_AsDouble ( temp[$1] );',
'CLEARTEMP($1);'), v2):
v2[2] = v2[2].strip()
TxRepl(o, i, ('double_$3 = $2;',), v2)
return True
if TxMatch(o, i, ('temp[$1] = PyFloat_FromDouble ($3);',
'if (PyFloat_CheckExact( temp[$0] )) {',
'temp[$2] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$0]) $5 PyFloat_AS_DOUBLE(temp[$1]));',
'} else {',
'if ((temp[$2] = PyNumber_$6 ( temp[$0] , temp[$1] )) == 0) goto $4;',
'}',
'CLEARTEMP($0);',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if (PyFloat_CheckExact( temp[$0] )) {',
'temp[$2] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$0]) $5 $3);',
'} else {',
'temp[$1] = PyFloat_FromDouble ($3);',
'if ((temp[$2] = PyNumber_$6 ( temp[$0] , temp[$1] )) == 0) goto $4;',
'CLEARTEMP($1);',
'}',
'CLEARTEMP($0);'), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyFloat_FromDouble ($5);',
'temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$0]) $6);',
'CLEARTEMP($0);'), v2) and ('temp[' + v2[0] + ']') not in v2[6]:
TxRepl(o, i, ('temp[$1] = PyFloat_FromDouble(($5) $6);',), v2)
return True
if TxMatch(o, i, """
temp[$0] = PyFloat_FromDouble ($11);
int_$5 = PyFloat_CheckExact( temp[$0] );
CLEARTEMP($0);
""", v2):
TxRepl(o, i, ('int_$5 = 1;',), v2)
return True
if 'PyBool_FromLong' in o[i]:
if TxMatch(o, i, """
temp[$0] = PyBool_FromLong($11);
if ((int_$1 = PyObject_IsTrue ( temp[$0] )) == -1) goto label_$10;
if ( int_$1 ) {
""", v2):
TxRepl(o, i, """
temp[$0] = PyBool_FromLong($11);
int_$1 = $11;
if ( int_$1 ) {
""", v2)
return True
if TxMatch(o, i, """
temp[$0] = PyBool_FromLong($11);
if ((int_$1 = PyObject_Not ( temp[$0] )) == -1) goto label_$10;
if ( int_$1 ) {
""", v2):
TxRepl(o, i, """
temp[$0] = PyBool_FromLong($11);
int_$1 = !$11;
if ( int_$1 ) {
""", v2)
return True
if TxMatch(o, i, ('temp[$0] = PyBool_FromLong($2);',
'if (($1 = PyObject_IsTrue ( temp[$0] )) == -1) goto $4;',
'CLEARTEMP($0);'), v2):
v2[2] = v2[2].strip()
if v2[2] != v2[1]:
TxRepl(o, i, ('$1 = $2;',), v2)
else:
TxRepl(o, i, ('$1 = $2;',), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyBool_FromLong($2);',
'if (($1 = PyObject_Not ( temp[$0] )) == -1) goto $4;',
'CLEARTEMP($0);'), v2):
v2[2] = v2[2].strip()
TxRepl(o, i, ('$1 = ! $2;',), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyBool_FromLong($2);',
'$1 = PyObject_IsTrue ( temp[$0] ));',
'CLEARTEMP($0);'), v2):
v2[2] = v2[2].strip()
if v2[2] != v2[1]:
TxRepl(o, i, ('$1 = $2;',), v2)
else:
TxRepl(o, i, (), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyBool_FromLong($2);',
'$1 = PyObject_Not ( temp[$0] ));',
'CLEARTEMP($0);'), v2):
v2[2] = v2[2].strip()
TxRepl(o, i, ('$1 = ! $2;',), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyBool_FromLong ($2);',
'$2 = PyObject_IsTrue ( temp[$0] );',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, (), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyBool_FromLong(int_$1);',
'int_$1 = PyObject_IsTrue ( temp[$0] );',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, (), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyBool_FromLong($1);',
'if (($1 = PyObject_IsTrue ( temp[$0] )) == -1) goto $2;'), v2):
TxRepl(o, i, ('temp[$0] = PyBool_FromLong($1);',), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyBool_FromLong($1);',
'$2 = PyObject_IsTrue(temp[$0]);',
'CLEARTEMP($0);'), v2):
v2[1] = v2[1].strip()
TxRepl(o, i, ('$2 = $1;',), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyBool_FromLong(int_$1);', 'CLEARTEMP($0);'), v2):
TxRepl(o, i, (), v2)
return True
if 'PyString_FromStringAndSize' in o[i]:
if TxMatch(o, i, ('temp[$0] = PyString_FromStringAndSize(&$2, 1);',
'$3 = PyString_AS_STRING(temp[$0])[0] $6 PyString_AS_STRING($4)[0];',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('$3 = $2 $6 PyString_AS_STRING($4)[0];',), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyString_FromStringAndSize(&$3, 1);',
'if (PyString_CheckExact( temp[$0] ) && PyString_GET_SIZE( temp[$0] ) == 1) {',
'$4 = (long)((unsigned char)*PyString_AS_STRING(temp[$0]));',
'temp[$1] = PyInt_FromLong ( $4 );',
'} else {',
'if ((temp[$2] = PyTuple_New ( 1 )) == 0) goto $5;',
'PyTuple_SET_ITEM ( temp[$2] , 0 , temp[$0] );',
'temp[$0] = 0;',
'if ((temp[$1] = PyCFunction_Call ( loaded_builtin[$6] , temp[$2] , NULL )) == 0) goto $5;',
'CLEARTEMP($2);',
'}',
'Py_CLEAR(temp[$0]);'), v2):
TxRepl(o, i, ('$4 = (long)((unsigned char)$3);',
'temp[$1] = PyInt_FromLong ( $4 );'), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyString_FromStringAndSize(&$2, 1);',
'$6 = PyString_AS_STRING(temp[$0])[0] $7 $5;',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('$6 = $2 $7 $5;',), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyString_FromStringAndSize(&$6, 1);',
'$5 = c_Py_EQ_String(temp[$0], 1, \"$4\", $3);',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('$5 = $6 == \'$4\';',), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyString_FromStringAndSize(&$6, 1);',
'$5 = c_Py_NE_String(temp[$0], 1, \"$4\", $3);',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('$5 = $6 != \'$4\';',), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyString_FromStringAndSize(&$2, 1);',
'temp[$1] = PyString_FromStringAndSize(&$3, 1);',
'$6 = PyString_AS_STRING(temp[$0])[0] $4 PyString_AS_STRING(temp[$1])[0];',
'CLEARTEMP($0);',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('$6 = $2 $4 $3;',), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyString_FromStringAndSize(&$3, 1);',
'long_$1 = (long)((unsigned char)*PyString_AS_STRING(temp[$0]));',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('long_$1 = (long)((unsigned char)$3);',), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyString_FromStringAndSize(&$2, 1);',
'$9 = *PyString_AS_STRING ( temp[$0] );',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('$9 = $2;',), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyString_FromStringAndSize(&$2, 1);',
'$9 = *PyString_AS_STRING(temp[$0]);',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('$9 = $2;',), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyString_FromStringAndSize($2, 1);',
'$9 = *PyString_AS_STRING ( temp[$0] );',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('$9 = *($2);',), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyString_FromStringAndSize(&$2, 1);',
'int_$1 = *PyString_AS_STRING(temp[$0]) $3 \'$4\';',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('int_$1 = $2 $3 \'$4\';',), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyString_FromStringAndSize(&$4, 1);',
'temp[$1] = PyString_FromStringAndSize(&$5, 1);',
'int_$2 = *PyString_AS_STRING(temp[$0]) $3 *PyString_AS_STRING(temp[$1]);',
'CLEARTEMP($0);',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('int_$2 = $4 $3 $5;',), v2)
return True
if TxMatch(o, i, """
temp[$0] = PyString_FromStringAndSize(&$1, 1);
long_$2 = (long)((unsigned char)*PyString_AS_STRING ( temp[$0] ));
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
long_$2 = (long)$1;
""", v2)
return True
if TxMatch(o, i, """
temp[$0] = PyString_FromStringAndSize(&$2, 1);
int_$1 = *PyString_AS_STRING ( temp[$0] ) $5 $6;
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
int_$1 = $2 $5 $6;
""", v2)
return True
if TxMatch(o, i, """
temp[$0] = PyString_FromStringAndSize(&$5, 1);
temp[$1] = PyString_FromStringAndSize(&$4, 1);
int_$2 = *PyString_AS_STRING ( temp[$0] ) $3 *PyString_AS_STRING ( temp[$1] );
CLEARTEMP($0);
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
int_$2 = $5 $3 $4;
""", v2)
return True
if TxMatch(o, i, """
temp[$0] = 0;
if ((temp[$0] = $1""", v2):
TxRepl(o, i, """if ((temp[$0] = $1""", v2)
return True
if TxMatch(o, i, """
temp[$0] = 0;
temp[$0] = $1;""", v2):
TxRepl(o, i, """temp[$0] = $1""", v2)
return True
return False
def let_temp_PyInt_FromLong(o, i):
v2 = []
if TxMatch(o, i, """
temp[$1] = PyInt_FromLong($11);
Loc_$12 = PyInt_AsLong(temp[$1]);
CLEARTEMP($1);
""", v2) :
TxRepl(o, i, """
Loc_$12 = $11;
""", v2)
return True
if TxMatch(o, i, """
temp[$0] = PyInt_FromLong ( long_$3 );
if ((Py_ssize_t_$18 = PyObject_Size ( $1 )) == -1) goto label_$10;
int_$11 = PyInt_AS_LONG ( temp[$0] ) $15 Py_ssize_t_$18;
CLEARTEMP($0);
""", v2) and 'Py_ssize_t_' not in v2[3]:
TxRepl(o, i, """
if ((Py_ssize_t_$18 = PyObject_Size ( $1 )) == -1) goto label_$10;
int_$11 = ( long_$3 ) $15 Py_ssize_t_$18;
""", v2)
return True
if TxMatch(o, i, """
temp[$2] = PyInt_FromLong ( $1 );
if (PyInt_CheckExact( $3 )) {
>0
} else {
>1
}
CLEARTEMP($2);
""", v2) and ('temp[%s]' % v2[2]) not in v2[3]:
TxRepl(o, i, """
if (PyInt_CheckExact( $3 )) {
temp[$2] = PyInt_FromLong ( $1 );
>0
CLEARTEMP($2);
} else {
temp[$2] = PyInt_FromLong ( $1 );
>1
CLEARTEMP($2);
}
""", v2)
return True
if TxMatch(o, i, """
temp[$0] = PyInt_FromLong ( $3 );
$1 = $11;
long_$2 = PyInt_AS_LONG ( temp[$0] );
""", v2) and ('temp[%s]' % v2[0]) not in v2[1] and ('temp[%s]' % v2[0]) not in v2[11] and v2[1] not in v2[3]:
TxRepl(o, i, """
long_$2 = $3;
$1 = $11;
temp[$0] = PyInt_FromLong ( long_$2 );
""", v2)
return True
if TxMatch(o, i, """
temp[$0] = PyInt_FromLong ( $2 );
if ($3) {
temp[$1] = PyInt_FromLong ( $4 );
} else {
temp[$1] = $5temp[$0]$6;
}
CLEARTEMP($0);
""", v2) and ('temp[%s]' % v2[0]) not in v2[3] and ('temp[%s]' % v2[0]) not in v2[4]:
TxRepl(o, i, """
if ($3) {
temp[$1] = PyInt_FromLong ( $4 );
} else {
temp[$0] = PyInt_FromLong ( $2 );
temp[$1] = $5temp[$0]$6;
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
temp[$2] = PyInt_FromLong ($10);
if (PyInt_CheckExact( GETLOCAL(crc) ) && PyInt_CheckExact( temp[$2] )) {
>0
} else {
>1
}
CLEARTEMP($2);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( GETLOCAL(crc) )) {
temp[$2] = PyInt_FromLong ($10);
>0
CLEARTEMP($2);
} else {
temp[$2] = PyInt_FromLong ($10);
>1
CLEARTEMP($2);
}
""", v2)
return True
if TxMatch(o, i, ('temp[$0] = PyInt_FromLong ($1);',
'long_$4 = PyInt_AS_LONG ( temp[$0] );',
'if ( long_$4 < 0) {',
'long_$4 += $5;',
'}',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('long_$4 = $1;',
'if ( long_$4 < 0) {',
'long_$4 += $5;',
'}'), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyInt_FromLong ($1);',
'$2 = PyInt_AS_LONG ( temp[$0] ) $3;',
'CLEARTEMP($0);'), v2):
v2[1] = v2[1].strip()
TxRepl(o, i, ('$2 = ($1) $3;',), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyInt_FromLong ($2);',
'if (PyInt_CheckExact( $1 )) {',
'$3 = PyInt_AS_LONG ( $1 );',
'$4 = PyInt_AS_LONG ( temp[$0] );',
'$5 = $3 - $4;',
'if (( $5 ^ $3 ) < 0 && ( $5 ^~ $4 ) < 0) goto $6 ;',
'temp[$8] = PyInt_FromLong ( $5 );',
'} else if (PyFloat_CheckExact( $1 )) {',
'temp[$8] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) - (double)PyInt_AS_LONG ( temp[$0] ));',
'} else { $6 :;',
'if ((temp[$8] = PyNumber_Subtract ( $1 , temp[$0] )) == 0) goto $7;',
'}',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $1 )) {',
'$3 = PyInt_AS_LONG ( $1 );',
'$4 = $2;',
'$5 = $3 - $4;',
'if (( $5 ^ $3 ) < 0 && ( $5 ^~ $4 ) < 0) goto $6 ;',
'temp[$8] = PyInt_FromLong ( $5 );',
'} else if (PyFloat_CheckExact( $1 )) {',
'temp[$8] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) - (double)$2);',
'} else { $6 :;',
'temp[$0] = PyInt_FromLong ($2);',
'if ((temp[$8] = PyNumber_Subtract ( $1 , temp[$0] )) == 0) goto $7;',
'CLEARTEMP($0);',
'}'), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyInt_FromLong ($2);',
'if (PyInt_CheckExact( $1 )) {',
'$3 = PyInt_AS_LONG ( $1 );',
'$4 = PyInt_AS_LONG ( temp[$0] );',
'$5 = $3 - $4;',
'if (( $5 ^ $3 ) < 0 && ( $5 ^~ $4 ) < 0) goto $6 ;',
'temp[$8] = PyInt_FromLong ( $5 );',
'} else { $6 :;',
'if ((temp[$8] = PyNumber_Subtract ( $1 , temp[$0] )) == 0) goto $7;',
'}',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $1 )) {',
'$3 = PyInt_AS_LONG ( $1 );',
'$4 = $2;',
'$5 = $3 - $4;',
'if (( $5 ^ $3 ) < 0 && ( $5 ^~ $4 ) < 0) goto $6 ;',
'temp[$8] = PyInt_FromLong ( $5 );',
'} else { $6 :;',
'temp[$0] = PyInt_FromLong ($2);',
'if ((temp[$8] = PyNumber_Subtract ( $1 , temp[$0] )) == 0) goto $7;',
'CLEARTEMP($0);',
'}'), v2)
return True
if TxMatch(o, i, ('temp[$1] = PyInt_FromLong (PyInt_AS_LONG ( temp[$0] )$2);',
'CLEARTEMP($0);',
'$5 = PyInt_AS_LONG ( temp[$1] ) $3 $4;',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('$5 = (PyInt_AS_LONG ( temp[$0] )$2) $3 $4;',
'CLEARTEMP($0);'), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyInt_FromLong ($2);',
'if (PyInt_CheckExact( $3 )) {',
'$4 = PyInt_AS_LONG ( temp[$0] );',
'$5 = PyInt_AS_LONG ( $3 );',
'$6 = $4 + $5;',
'if (( $6 ^ $4 ) < 0 && ( $6 ^ $5 ) < 0) goto $7 ;',
'temp[$1] = PyInt_FromLong ( $6 );',
'} else if (PyFloat_CheckExact( $3 )) {',
'temp[$1] = PyFloat_FromDouble((double)PyInt_AS_LONG ( temp[$0] ) + PyFloat_AS_DOUBLE($3));',
'} else { $7 :;',
'if ((temp[$1] = PyNumber_Add ( temp[$0] , $3 )) == 0) goto $8;',
'}',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, (
'if (PyInt_CheckExact( $3 )) {',
'$4 = $2;',
'$5 = PyInt_AS_LONG ( $3 );',
'$6 = $4 + $5;',
'if (( $6 ^ $4 ) < 0 && ( $6 ^ $5 ) < 0) goto $7 ;',
'temp[$1] = PyInt_FromLong ( $6 );',
'} else if (PyFloat_CheckExact( $3 )) {',
'temp[$1] = PyFloat_FromDouble((double)$2 + PyFloat_AS_DOUBLE($3));',
'} else { $7 :;',
'temp[$0] = PyInt_FromLong ($2);',
'if ((temp[$1] = PyNumber_Add ( temp[$0] , $3 )) == 0) goto $8;',
'CLEARTEMP($0);',
'}'), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyInt_FromLong ($2);',
'if (PyInt_CheckExact( $3 )) {',
'$4 = PyInt_AS_LONG ( temp[$0] );',
'$5 = PyInt_AS_LONG ( $3 );',
'$6 = $4 + $5;',
'if (( $6 ^ $4 ) < 0 && ( $6 ^ $5 ) < 0) goto $7 ;',
'temp[$1] = PyInt_FromLong ( $6 );',
'} else { $7 :;',
'if ((temp[$1] = PyNumber_Add ( temp[$0] , $3 )) == 0) goto $8;',
'}',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, (
'if (PyInt_CheckExact( $3 )) {',
'$4 = $2;',
'$5 = PyInt_AS_LONG ( $3 );',
'$6 = $4 + $5;',
'if (( $6 ^ $4 ) < 0 && ( $6 ^ $5 ) < 0) goto $7 ;',
'temp[$1] = PyInt_FromLong ( $6 );',
'} else { $7 :;',
'temp[$0] = PyInt_FromLong ($2);',
'if ((temp[$1] = PyNumber_Add ( temp[$0] , $3 )) == 0) goto $8;',
'CLEARTEMP($0);',
'}'), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyInt_FromLong ( $1 );',
'if (($3 = PyObject_Not ( temp[$0] )) == -1) goto $2;',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('$3 = ! $1;',), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyInt_FromLong ( $1 );',
'if (PyInt_CheckExact( $2 )) {',
'$3 = PyInt_AsSsize_t ( temp[$0] );',
'CLEARTEMP($0);',
'$4 = PyInt_AS_LONG ( $2 ) $5 $3;',
'} else {',
'if (($4 = PyObject_RichCompareBool ( $2 , temp[$0] , Py_$6 )) == -1) goto $7;',
'CLEARTEMP($0);',
'}'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $2 )) {',
'$4 = PyInt_AS_LONG ( $2 ) $5 $1;',
'} else {',
'temp[$0] = PyInt_FromLong ( $1 );',
'if (($4 = PyObject_RichCompareBool ( $2 , temp[$0] , Py_$6 )) == -1) goto $7;',
'CLEARTEMP($0);',
'}'), v2)
return True
if TxMatch(o, i, ('temp[$1] = PyInt_FromLong ($2);',
'if ((temp[$0] = _c_BINARY_SUBSCR_Int ( $3 , $4 , temp[$1] )) == 0) goto $5;',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if ((temp[$0] = __c_BINARY_SUBSCR_Int ( $3 , $4 )) == 0) goto $5;',), v2, ('__c_BINARY_SUBSCR_Int',))
return True
if TxMatch(o, i, """
temp[$3] = PyInt_FromLong ( Loc_long_$4 );
if ((temp[$2] = _c_BINARY_SUBSCR_Int ( temp[$1] , Py_ssize_t_$5 , temp[$3] )) == 0) goto label_$0;
CLEARTEMP($3);""", v2):
TxRepl(o, i, ('if ((temp[$2] = __c_BINARY_SUBSCR_Int ( temp[$1] , Py_ssize_t_$5 )) == 0) goto label_$0;',), v2, ('__c_BINARY_SUBSCR_Int',))
return True
if TxMatch(o, i, ('temp[$0] = PyInt_FromLong ($11);',
'if (PyInt_CheckExact( $2 )) {',
'int_$1 = PyInt_AS_LONG ( $2 ) $4 PyInt_AS_LONG ( temp[$0] );',
'} else {',
'if ((int_$1 = PyObject_RichCompareBool ( $2 , temp[$0] , Py_$5 )) == -1) goto $6;',
'}',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $2 )) {',
'int_$1 = PyInt_AS_LONG ( $2 ) $4 $11;',
'} else {',
'temp[$0] = PyInt_FromLong ($11);',
'if ((int_$1 = PyObject_RichCompareBool ( $2 , temp[$0] , Py_$5 )) == -1) goto $6;',
'CLEARTEMP($0);',
'}'), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyInt_FromLong ($5);',
'if (1) {',
'$4 = PyInt_AS_LONG ( temp[$0] );',
'$3 = $4 + 1;',
'if (( $3 ^ $4 ) < 0 && ( $3 ^ 1 ) < 0) goto $6 ;',
'temp[$1] = PyInt_FromLong ( $3 );',
'} else { $6 :;',
'if ((temp[$1] = PyNumber_Add ( temp[$0] , $9 )) == 0) goto $7;',
'}',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('if ($5 < INT_MAX) {',
'temp[$1] = PyInt_FromLong ( $5 + 1 );',
'} else {',
'temp[$0] = PyInt_FromLong ($5);',
'if ((temp[$1] = PyNumber_Add ( temp[$0] , $9 )) == 0) goto $7;',
'CLEARTEMP($0);',
'}'), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyInt_FromLong ($2);',
'if (($5 = $3) == -1) goto $4;',
'if ((temp[$1] = PyInt_FromSsize_t ( $5 )) == 0) goto $4;',
'$6 = PyInt_AS_LONG ( temp[$0] );',
'$7 = PyInt_AS_LONG ( temp[$1] );',
'$8 = $6 - $7;',
'temp[$2] = PyInt_FromLong ( $8 );',
'CLEARTEMP($0);',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('$6 = $2;',
'if (($7 = $3) == -1) goto $4;',
'temp[$2] = PyInt_FromLong ( $6 - $7 );'), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyInt_FromLong ($2);',
'$4 = PyInt_AS_LONG ( $3 );',
'$5 = PyInt_AS_LONG ( temp[$0] );',
'$6 = $4 + $5;',
'if (( $6 ^ $4 ) < 0 && ( $6 ^ $5 ) < 0) {',
'if ((temp[$1] = PyNumber_Add ( GETLOCAL(a) , temp[$0] )) == 0) goto $7;',
'} else {',
'temp[$1] = PyInt_FromLong ( $6 );',
'}',
'CLEARTEMP($0);'), v2):
v2[2] = v2[2].strip()
TxRepl(o, i, ('$4 = PyInt_AS_LONG ( $3 );',
'$5 = $2;',
'$6 = $4 + $5;',
'if (( $6 ^ $4 ) < 0 && ( $6 ^ $5 ) < 0) {',
'temp[$0] = PyInt_FromLong ($2);',
'if ((temp[$1] = PyNumber_Add ( $3 , temp[$0] )) == 0) goto $7;',
'CLEARTEMP($0);',
'} else {',
'temp[$1] = PyInt_FromLong ( $6 );',
'}'), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyInt_FromLong ($3);',
'if ((temp[$1] = PyInt_Type.tp_str ( temp[$0] )) == 0) goto $4;',
'CLEARTEMP($0);',
'temp[$0] = PyInt_FromLong ($3);',
'if ((temp[$2] = PyInt_Type.tp_str ( temp[$0] )) == 0) goto $4;',
'CLEARTEMP($0);'), v2):
v2[3] = v2[3].strip()
TxRepl(o, i, ('temp[$0] = PyInt_FromLong ($3);',
'if ((temp[$1] = PyInt_Type.tp_str ( temp[$0] )) == 0) goto $4;',
'CLEARTEMP($0);',
'temp[$2] = temp[$1];',
'Py_INCREF(temp[$2]);'), v2)
return True
if TxMatch(o, i, ('temp[$2] = PyInt_FromLong ($3);',
'CLEARTEMP($0);',
'$4 = PyInt_AsLong(temp[$2]);',
'CLEARTEMP($2);'), v2):
TxRepl(o, i, ('$4 = ($3);',
'CLEARTEMP($0);'), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyInt_FromLong ($2);',
'$1 = PyInt_CheckExact( temp[$0] );',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('$1 = 1;',), v2)
return True
if TxMatch(o, i, ('temp[$1] = PyInt_FromLong ($3);',
'CLEARTEMP($0);',
'if ((int_$4 = PyObject_Not ( temp[$1] )) == -1) goto $2;',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('int_$4 = !($3);',
'CLEARTEMP($0);'), v2)
return True
if TxMatch(o, i, ('temp[$4] = PyInt_FromLong ($1);',
'if ((temp[$5] = PyObject_GetItem ( $2 , temp[$4] )) == 0) goto $0;',
'CLEARTEMP($4);'), v2):
v2[1] = v2[1].strip()
TxRepl(o, i, ('if ((temp[$5] = __c_BINARY_SUBSCR_Int ( $2, $1 )) == 0) goto $0;',), v2, ('__c_BINARY_SUBSCR_Int',))
return True
if TxMatch(o, i, ('temp[$4] = PyInt_FromLong ($1);',
'if ((temp[$5] = PyObject_GetItem ( temp[$2] , temp[$4] )) == 0) goto $0;',
'CLEARTEMP($4);'), v2):
v2[1] = v2[1].strip()
TxRepl(o, i, ('if ((temp[$5] = __c_BINARY_SUBSCR_Int ( temp[$2], $1 )) == 0) goto $0;',), v2, ('__c_BINARY_SUBSCR_Int',))
return True
if TxMatch(o, i, ('temp[$0] = PyInt_FromLong ($3);',
'if (($5 = $6) == -1) goto $4;',
'if ((temp[$1] = PyInt_FromSsize_t ( $5 )) == 0) goto $4;',
'$7 = PyInt_AS_LONG ( temp[$0] );',
'$8 = PyInt_AS_LONG ( temp[$1] );',
'$9 = $7 $10 $8;',
'temp[$2] = PyInt_FromLong ( $9 );',
'CLEARTEMP($0);',
'CLEARTEMP($1);'), v2):
v2[3] = v2[3].strip()
TxRepl(o, i, ('$7 = $3;',
'$8 = $6;',
'$9 = $7 $10 $8;',
'temp[$2] = PyInt_FromLong ( $9 );'), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyInt_FromLong (Loc_long_$4);',
'if (Loc_long_$4 < INT_MAX) {',
'temp[$3] = PyInt_FromLong ( Loc_long_$4 + 1 );',
'} else {',
'temp[$2] = PyInt_FromLong (Loc_long_$4);',
'if ((temp[$3] = PyNumber_Add ( temp[$2] , $6 )) == 0) goto $5;',
'CLEARTEMP(2);',
'}',
'if ( _PyEval_AssignSlice ( $7 , temp[$0] , temp[$3] , temp[$1] ) == -1) goto $5;',
'CLEARTEMP(1);',
'CLEARTEMP(0);',
'CLEARTEMP(3);'), v2):
TxRepl(o, i, ('if ( PySequence_SetSlice ( $7 , Loc_long_$4 , Loc_long_$4 + 1 , temp[$1] ) == -1) goto $5;',
'CLEARTEMP(1);'), v2)
return True
if TxMatch(o, i, """
temp[$0] = PyInt_FromLong ($1);
if ($1 < $3) {
temp[$2] = PyInt_FromLong ( $1 + $4 );
} else {
temp[$5] = PyInt_FromLong ($1);
if ((temp[$2] = PyNumber_$6) == 0) goto label_$7;
CLEARTEMP($5);
}
if ( _PyEval_AssignSlice ( $8 , temp[$0] , temp[$2] , temp[$9] ) == -1) goto label_$7;
CLEARTEMP($9);
CLEARTEMP($0);
CLEARTEMP($2);
""", v2):
TxRepl(o, i, """
if ($1 < $3) {
if ( PySequence_SetSlice ( $8 , $1 , $1 + $4 , temp[$9] ) == -1) goto label_$7;
} else {
temp[$5] = PyInt_FromLong ($1);
if ((temp[$2] = PyNumber_$6) == 0) goto label_$7;
if ( _PyEval_AssignSlice ( $8 , temp[$5] , temp[$2] , temp[$9] ) == -1) goto label_$7;
CLEARTEMP($0);
CLEARTEMP($5);
}
CLEARTEMP($9);
""", v2)
return True
if TxMatch(o, i, """
temp[$1] = PyInt_FromLong ($0);
long_$3 = $0 $4 $5;
temp[$2] = PyInt_FromLong ( long_$3 );
if ( _PyEval_AssignSlice ( $6 , temp[$1] , temp[$2] , temp[$10] ) == -1) goto label_$11;
CLEARTEMP($10);
CLEARTEMP($1);
CLEARTEMP($2);
""", v2):
TxRepl(o, i, """
if ( PySequence_SetSlice ( $6 , $0 , $0 $4 $5 , temp[$10] ) == -1) goto label_$11;
CLEARTEMP($10);
""", v2)
return True
if TxMatch(o, i, """
temp[$1] = PyInt_FromLong ( $4 );
if ( _PyEval_AssignSlice ( $3 , temp[$1] , NULL , temp[$0] ) == -1) goto label_$2;
CLEARTEMP($0);
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if ( PySequence_SetSlice ( $3 , $4 , PY_SSIZE_T_MAX , temp[$0] ) == -1) goto label_$2;
CLEARTEMP($0);
""", v2)
return True
if TxMatch(o, i, """
temp[$0] = PyInt_FromLong ( $12 );
if ((temp[$1] = _PyEval_ApplySlice ( $10 , NULL , temp[$0] )) == 0) goto label_$11;
CLEARTEMP($0);""", v2):
TxRepl(o, i, """
if ((temp[$1] = PySequence_GetSlice ( $10 , 0 , $12 )) == 0) goto label_$11;
""", v2)
return True
if TxMatch(o, i, ('temp[$0] = PyInt_FromLong ($5);',
'$6 = $5 + $10;',
'temp[$1] = PyInt_FromLong ( $6 );',
'if ((temp[$2] = _PyEval_ApplySlice ( $4 , temp[$0] , temp[$1] )) == 0) goto $3;',
'CLEARTEMP($0);',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if ((temp[$2] = PySequence_GetSlice ( $4 , $5 , $5 + $10 )) == 0) goto $3;',), v2)
return True
if TxMatch(o, i, """
temp[$0] = PyInt_FromLong ( $1 );
long_$2 = $1 ;
long_$3 = long_$2 + $4;
if ($12) goto label_$5 ;
temp[$6] = PyInt_FromLong ( long_$3 );
if (0) { label_$5 :;
temp[$7] = PyInt_FromLong ( $1 );
if ((temp[$6] = PyNumber_$9) == 0) goto label_$10;
CLEARTEMP($7);
}
if ((temp[$8] = _PyEval_ApplySlice ( $11 , temp[$0] , temp[$6] )) == 0) goto label_$10;
CLEARTEMP($0);
CLEARTEMP($6);
""", v2):
TxRepl(o, i, """
long_$2 = $1;
long_$3 = long_$2 + $4;
if (!($12)) {
if ((temp[$8] = PySequence_GetSlice ( $11 , $1 , long_$3 )) == 0) goto label_$10;
} else {
temp[$7] = PyInt_FromLong ( $1 );
if ((temp[$6] = PyNumber_$9) == 0) goto label_$10;
if ((temp[$8] = _PyEval_ApplySlice ( $11 , temp[$7] , temp[$6] )) == 0) goto label_$10;
CLEARTEMP($7);
CLEARTEMP($6);
}
""", v2)
return True
if TxMatch(o, i, ('temp[$0] = PyInt_FromLong ($2);',
'if ((temp[$1] = _PyEval_ApplySlice ( $4 , temp[$0] , NULL )) == 0) goto $5;',
'CLEARTEMP($0);'), v2):
v2[2] = v2[2].strip()
TxRepl(o, i, ('if ((temp[$1] = PySequence_GetSlice ( $4 , $2 , PY_SSIZE_T_MAX )) == 0) goto $5;',), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyInt_FromLong (Loc_long_$1);',
'Py_ssize_t_$2 = PyInt_AsSsize_t ( temp[$0] );',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('Py_ssize_t_$2 = Loc_long_$1;',), v2)
return True
if TxMatch(o, i, ('temp[$2] = PyInt_FromLong ($10);',
'if (PyInt_CheckExact( $6 )) {',
'$7 = PyInt_AS_LONG ( $6 );',
'$8 = PyInt_AS_LONG ( temp[$2] );',
'$9 = $7 + $8;',
'if (( $9 ^ $7 ) < 0 && ( $9 ^ $8 ) < 0) goto $5 ;',
'temp[$3] = PyInt_FromLong ( $9 );',
'} else if (PyFloat_CheckExact( $6 )) {',
'temp[$3] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($6) + (double)PyInt_AS_LONG ( temp[$2] ));',
'} else { $5 :;',
'if ((temp[$3] = PyNumber_Add ( $6 , temp[$2] )) == 0) goto $4;',
'}',
'CLEARTEMP($2);'), v2):
v2[10] = v2[10].strip()
TxRepl(o, i, ('if (PyInt_CheckExact( $6 )) {',
'$7 = PyInt_AS_LONG ( $6 );',
'$8 = $10;',
'$9 = $7 + $8;',
'if (( $9 ^ $7 ) < 0 && ( $9 ^ $8 ) < 0) goto $5 ;',
'temp[$3] = PyInt_FromLong ( $9 );',
'} else if (PyFloat_CheckExact( $6 )) {',
'temp[$3] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($6) + (double)$10);',
'} else { $5 :;',
'temp[$2] = PyInt_FromLong ($10);',
'if ((temp[$3] = PyNumber_Add ( $6 , temp[$2] )) == 0) goto $4;',
'CLEARTEMP($2);',
'}'), v2)
return True
if TxMatch(o, i, ('temp[$2] = PyInt_FromLong ($10);',
'if (PyInt_CheckExact( $6 )) {',
'$7 = PyInt_AS_LONG ( $6 );',
'$8 = PyInt_AS_LONG ( temp[$2] );',
'$9 = $7 + $8;',
'if (( $9 ^ $7 ) < 0 && ( $9 ^ $8 ) < 0) goto $5 ;',
'temp[$3] = PyInt_FromLong ( $9 );',
'} else { $5 :;',
'if ((temp[$3] = PyNumber_Add ( $6 , temp[$2] )) == 0) goto $4;',
'}',
'CLEARTEMP($2);'), v2):
v2[10] = v2[10].strip()
TxRepl(o, i, ('if (PyInt_CheckExact( $6 )) {',
'$7 = PyInt_AS_LONG ( $6 );',
'$8 = $10;',
'$9 = $7 + $8;',
'if (( $9 ^ $7 ) < 0 && ( $9 ^ $8 ) < 0) goto $5 ;',
'temp[$3] = PyInt_FromLong ( $9 );',
'} else { $5 :;',
'temp[$2] = PyInt_FromLong ($10);',
'if ((temp[$3] = PyNumber_Add ( $6 , temp[$2] )) == 0) goto $4;',
'CLEARTEMP($2);',
'}'), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyInt_FromLong ($5);',
'$3 = PyInt_AS_LONG ( temp[$0] );',
'$4 = $3 $6 1;',
'temp[$1] = PyInt_FromLong ( $4 );',
'CLEARTEMP($0);'), v2):
v2[5] = v2[5].strip()
TxRepl(o, i, ('$3 = $5;', '$4 = $3 $6 1;',
'temp[$1] = PyInt_FromLong ( $4 );'), v2)
return True
if TxMatch(o, i, ('temp[$2] = PyInt_FromLong ($0);',
'$3 = PyInt_AS_LONG ( temp[$2] );',
'if ( $3 < 0) {',
'$3 += PyList_GET_SIZE($1);',
'}',
'if ((temp[$11] = PyList_GetItem ( $1 , $3 )) == 0) goto $10;',
'Py_INCREF(temp[$11]);',
'CLEARTEMP($2);'), v2):
TxRepl(o, i, ('$3 = $0;',
'if ( $3 < 0) {',
'$3 += PyList_GET_SIZE($1);',
'}',
'if ((temp[$11] = PyList_GetItem ( $1 , $3 )) == 0) goto $10;',
'Py_INCREF(temp[$11]);'), v2)
return True
if TxMatch(o, i, ('temp[$2] = PyInt_FromLong ($8);',
'if (($9 = $6) == -1) goto $7;',
'if ((temp[$4] = PyInt_FromSsize_t ( $9 )) == 0) goto $7;',
'$10 = PyInt_AS_LONG ( temp[$2] );',
'$11 = PyInt_AS_LONG ( temp[$4] );',
'$12 = $10 + $11;',
'if (( $12 ^ $10 ) < 0 && ( $12 ^ $11 ) < 0) {',
'if ((temp[$5] = PyNumber_Add ( temp[$2] , temp[$4] )) == 0) goto $7;',
'} else {',
'temp[$5] = PyInt_FromLong ( $12 );',
'}',
'CLEARTEMP($2);',
'CLEARTEMP($4);'), v2):
TxRepl(o, i, ('$10 = $8;',
'$11 = $6;',
'$12 = $10 + $11;',
'if (( $12 ^ $10 ) < 0 && ( $12 ^ $11 ) < 0) {',
'temp[$2] = PyInt_FromLong ( $10 );',
'temp[$4] = PyInt_FromLong ( $11 );',
'if ((temp[$5] = PyNumber_Add ( temp[$2] , temp[$4] )) == 0) goto $7;',
'CLEARTEMP($2);',
'CLEARTEMP($4);',
'} else {',
'temp[$5] = PyInt_FromLong ( $12 );',
'}'), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyInt_FromLong (Loc_long_$2);',
'if (1) {',
'$3 = PyInt_AS_LONG ( temp[$0] );',
'$4 = $3 - 1;',
'if (( $4 ^ $3 ) < 0 && ( $4 ^~ 1 ) < 0) goto $6 ;',
'temp[$1] = PyInt_FromLong ( $4 );',
'} else { $6 :;',
'if ((temp[$1] = PyNumber_Subtract ( temp[$0] , $7 )) == 0) goto $5;',
'}',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('temp[$1] = PyInt_FromLong ( Loc_long_$2 - 1 );',), v2)
return True
v2 = []
## v3 = []
if TextMatch(o[i], ('temp[', '*', '] = PyInt_FromLong (', '*', ');'), v2):
patt = 'PyInt_AsLong(temp[' + v2[0] + '])'
if i < (len(o) - 2) and patt in o[i+1] and\
TextMatch(o[i+2], ('CLEARTEMP(', v2[0],');'), []):
o[i+1] = o[i+1].replace(patt, '(' + v2[1] + ')')
del o[i+2]
del o[i]
return True
if TextMatch(o[i], ('temp[', '*', '] = PyInt_FromLong (', '*', ');'), v2):
patt = 'PyInt_AsLong ( temp[' + v2[0] + '] )'
if i < (len(o) - 2) and patt in o[i+1] and\
TextMatch(o[i+2], ('CLEARTEMP(', v2[0],');'), []):
o[i+1] = o[i+1].replace(patt, '(' + v2[1] + ')')
del o[i+2]
del o[i]
return True
v2 = []
## v3 = []
if TextMatch(o[i], ('temp[', '*', '] = PyInt_FromLong (', '*', ');'), v2):
patt = 'PyInt_AS_LONG ( temp[' + v2[0] + '] )'
if i < (len(o) - 2) and patt in o[i+1] and\
TextMatch(o[i+2], ('CLEARTEMP(', v2[0],');'), []):
o[i+1] = o[i+1].replace(patt, '(' + v2[1] + ')')
del o[i+2]
del o[i]
return True
if TxMatch(o, i, """
temp[$1] = PyInt_FromLong ($4);
if (($5 = PyObject_Size ( $8 )) == -1) goto $6;
if ((temp[$2] = PyInt_FromSsize_t ( $5 )) == 0) goto $6;
long_$9 = PyInt_AS_LONG ( temp[$1] );
long_$10 = PyInt_AS_LONG ( temp[$2] );
long_$11 = long_$9 + long_$10;
if (( long_$11 ^ long_$9 ) < 0 && ( long_$11 ^ long_$10 ) < 0) goto $7 ;
temp[$3] = PyInt_FromLong ( long_$11 );
if (1) {
} else { $7 :;
if ((temp[$3] = PyNumber_Add ( temp[$1] , temp[$2] )) == 0) goto $6;
}
CLEARTEMP($1);
CLEARTEMP($2);
""", v2):
TxRepl(o, i, """
long_$9 = $4;
if ((long_$10 = PyObject_Size ( $8 )) == -1) goto $6;
long_$11 = long_$9 + long_$10;
if (( long_$11 ^ long_$9 ) < 0 && ( long_$11 ^ long_$10 ) < 0) goto $7 ;
temp[$3] = PyInt_FromLong ( long_$11 );
if (0) { $7 :;
temp[$1] = PyInt_FromLong ($4);
if ((temp[$2] = PyInt_FromSsize_t ( long_$10 )) == 0) goto $6;
if ((temp[$3] = PyNumber_Add ( temp[$1] , temp[$2] )) == 0) goto $6;
CLEARTEMP($1);
CLEARTEMP($2);
}
""", v2)
if TxMatch(o, i, """
temp[$0] = PyInt_FromLong ($2);
long_$3 = PyInt_AS_LONG ( temp[$0] );
long_$4 = long_$3 + $8;
if (( long_$4 ^ long_$3 ) < 0 && ( long_$4 ^ $8 ) < 0) goto $6 ;
temp[$1] = PyInt_FromLong ( long_$4 );
if (1) {
} else { $6 :;
if ((temp[$1] = PyNumber_Add ( temp[$0] , $7 )) == 0) goto $5;
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
long_$3 = $2;
long_$4 = long_$3 + $8;
if (( long_$4 ^ long_$3 ) < 0 && ( long_$4 ^ $8 ) < 0) goto $6 ;
temp[$1] = PyInt_FromLong ( long_$4 );
if (0) { $6 :;
temp[$0] = PyInt_FromLong ($2);
if ((temp[$1] = PyNumber_Add ( temp[$0] , $7 )) == 0) goto $5;
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
temp[$0] = PyInt_FromLong ($4);
long_$3 = PyInt_AS_LONG ( temp[$0] );
temp[$1] = PyInt_FromLong ( long_$3 $5 );
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
temp[$1] = PyInt_FromLong ( ($4) $5 );
""", v2)
return True
if TxMatch(o, i, """
temp[$0] = PyInt_FromLong ($2);
if ((int_$1 = PyObject_Not ( temp[$0] )) == -1) goto $3;
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
int_$1 = !($2);
""", v2)
return True
if TxMatch(o, i, """
temp[$1] = PyInt_FromLong ($2);
long_$3 = PyInt_AS_LONG ( temp[$1] );
long_$6 = long_$3 * $5;
if (long_$6 / $5 == long_$3) {
temp[$12] = PyInt_FromLong (long_$6);
} else {
temp[$12] = PyInt_Type.tp_as_number->nb_multiply(consts[$10], temp[$1]);
}
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
long_$3 = $2;
long_$6 = long_$3 * $5;
if (long_$6 / $5 == long_$3) {
temp[$12] = PyInt_FromLong (long_$6);
} else {
temp[$1] = PyInt_FromLong (long_$3);
temp[$12] = PyInt_Type.tp_as_number->nb_multiply(consts[$10], temp[$1]);
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
temp[$0] = PyInt_FromLong ($2);
long_$3 = PyInt_AS_LONG ( temp[$0] );
long_$4 = long_$3 * $12;
if (long_$4 / $12 == long_$3) {
temp[$1] = PyInt_FromLong (long_$4);
} else {
temp[$1] = PyInt_Type.tp_as_number->nb_multiply(temp[$0], consts[$5]);
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
long_$3 = $2;
long_$4 = long_$3 * $12;
if (long_$4 / $12 == long_$3) {
temp[$1] = PyInt_FromLong (long_$4);
} else {
temp[$0] = PyInt_FromLong ($2);
temp[$1] = PyInt_Type.tp_as_number->nb_multiply(temp[$0], consts[$5]);
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
temp[$2] = PyInt_FromLong ($4);
if (PyInt_CheckExact( temp[$1] ) && PyInt_CheckExact( temp[$2] )) {
temp[$0] = PyInt_FromLong (PyInt_AS_LONG ( temp[$1] ) $12 PyInt_AS_LONG ( temp[$2] ));
} else {
if ((temp[$0] = PyNumber_$11 ( temp[$1] , temp[$2] )) == 0) goto label_$10;
}
CLEARTEMP($1);
CLEARTEMP($2);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( temp[$1] )) {
temp[$0] = PyInt_FromLong (PyInt_AS_LONG ( temp[$1] ) $12 ($4));
} else {
temp[$2] = PyInt_FromLong ($4);
if ((temp[$0] = PyNumber_$11 ( temp[$1] , temp[$2] )) == 0) goto label_$10;
CLEARTEMP($2);
}
CLEARTEMP($1);
""", v2)
return True
if TxMatch(o, i, """
temp[$2] = PyInt_FromLong ($4);
if (PyInt_CheckExact( $1 ) && PyInt_CheckExact( temp[$2] )) {
temp[$0] = PyInt_FromLong (PyInt_AS_LONG ( $1 ) $12 PyInt_AS_LONG ( temp[$2] ));
} else {
if ((temp[$0] = PyNumber_$11 ( $1 , temp[$2] )) == 0) goto label_$10;
}
CLEARTEMP($2);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $1 )) {
temp[$0] = PyInt_FromLong (PyInt_AS_LONG ( $1 ) $12 ($4));
} else {
temp[$2] = PyInt_FromLong ($4);
if ((temp[$0] = PyNumber_$11 ( $1 , temp[$2] )) == 0) goto label_$10;
CLEARTEMP($2);
}
""", v2)
return True
if TxMatch(o, i, """
temp[$1] = PyInt_FromLong ($10);
long_$4 = PyInt_AS_LONG ( temp[$1] );
long_$3 = $11;
if ($12) goto label_$18 ;
temp[$2] = PyInt_FromLong ( long_$3 );
if (1) {
} else { label_$18 :;
if ((temp[$2] = $15) == 0) goto label_$0;
}
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
long_$4 = $10;
long_$3 = $11;
if ($12) goto label_$18 ;
temp[$2] = PyInt_FromLong ( long_$3 );
if (1) {
} else { label_$18 :;
temp[$1] = PyInt_FromLong ($10);
if ((temp[$2] = $15) == 0) goto label_$0;
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
temp[$0] = PyInt_FromLong ( $10 );
long_$3 = PyInt_AS_LONG ( temp[$0] );
long_$4 = long_$3 * $2;
if (long_$4 / $2 == long_$3) {
temp[$1] = PyInt_FromLong ( long_$4 );
} else {
temp[$1] = PyInt_Type.tp_as_number->nb_multiply(temp[$0], $11);
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
long_$3 = $10;
long_$4 = long_$3 * $2;
if (long_$4 / $2 == long_$3) {
temp[$1] = PyInt_FromLong ( long_$4 );
} else {
temp[$0] = PyInt_FromLong ( $10 );
temp[$1] = PyInt_Type.tp_as_number->nb_multiply(temp[$0], $11);
CLEARTEMP($0);
}
""", v2)
if TxMatch(o, i, ('temp[$0] = PyInt_FromLong ( $1 );',
'int_$3 = PyInt_AS_LONG ( temp[$0] ) $4;',
'CLEARTEMP($0);'), v2) and ('temp[' + v2[0] + ']') not in v2[4]:
TxRepl(o, i, ('int_$3 = ($1) $4;',), v2)
return True
if TxMatch(o, i, ('temp[$1] = PyInt_FromLong ( $2 );',
'if ((temp[$4] = _PyEval_ApplySlice ( $5 , temp[$1] , NULL )) == 0) goto $3;',
'CLEARTEMP($1);'), v2):
v2[2] = v2[2].strip()
TxRepl(o, i, ('if ((temp[$4] = PySequence_GetSlice ( $5 , $2 , PY_SSIZE_T_MAX )) == 0) goto $3;',), v2)
return True
if TxMatch(o, i, ('temp[$1] = PyInt_FromLong ( $2 );',
'temp[$0] = 0;',
'if (PyInt_CheckExact( $3 )) {',
'$4 = PyInt_AS_LONG ( $3 ) $7 PyInt_AS_LONG ( temp[$1] );',
'} else {',
'if (($4 = PyObject_RichCompareBool ( $3 , temp[$1] , Py_$6 )) == -1) goto $5;',
'}',
'CLEARTEMP($1);'), v2) and v2[0] != v2[1]:
TxRepl(o, i, ('temp[$0] = 0;',
'if (PyInt_CheckExact( $3 )) {',
'$4 = PyInt_AS_LONG ( $3 ) $7 $2;',
'} else {',
'temp[$1] = PyInt_FromLong ( $2 );',
'if (($4 = PyObject_RichCompareBool ( $3 , temp[$1] , Py_$6 )) == -1) goto $5;',
'CLEARTEMP($1);',
'}'), v2)
return True
if TxMatch(o, i, ('temp[$1] = PyInt_FromLong ( $2 );',
'if (PyInt_CheckExact( $3 )) {',
'$4 = PyInt_AS_LONG ( $3 ) $7 PyInt_AS_LONG ( temp[$1] );',
'} else {',
'if (($4 = PyObject_RichCompareBool ( $3 , temp[$1] , Py_$6 )) == -1) goto $5;',
'}',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $3 )) {',
'$4 = PyInt_AS_LONG ( $3 ) $7 $2;',
'} else {',
'temp[$1] = PyInt_FromLong ( $2 );',
'if (($4 = PyObject_RichCompareBool ( $3 , temp[$1] , Py_$6 )) == -1) goto $5;',
'CLEARTEMP($1);',
'}'), v2)
return True
if TxMatch(o, i, ('temp[$1] = PyInt_FromLong ( $3 );',
'CLEARTEMP($2);',
'$3 = PyInt_AsLong ( temp[$1] );',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('CLEARTEMP($2);',), v2)
return True
if TxMatch(o, i, ('temp[$1] = PyInt_FromLong ( $2 );',
'$3 = PyInt_AS_LONG ( temp[$1] );',
'$4 = $3 + 1;',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('$3 = $2;',
'$4 = $3 + 1;'), v2)
return True
if TxMatch(o, i, ('temp[$1] = PyInt_FromLong ($2);',
'if ((temp[$0] = _c_BINARY_SUBSCR_Int ( $3 , $4 , temp[$1] )) == 0) goto $5;',
'CLEARTEMP($1);'), v2):
v2[2] = v2[2].strip()
TxRepl(o, i, ('if ((temp[$0] = __c_BINARY_SUBSCR_Int ( $3 , $4 )) == 0) goto $5;',), v2, ('__c_BINARY_SUBSCR_Int',))
return True
if TxMatch(o, i, ('temp[$1] = PyInt_FromLong ($2);',
'$4 = PyInt_AsLong(temp[$1]);',
'CLEARTEMP($1);'), v2):
v2[2] = v2[2].strip()
v2[4] = v2[4].strip()
TxRepl(o, i, ('$4 = $2;',), v2)
return True
if TxMatch(o, i, ('temp[$1] = PyInt_FromLong ( $0 );',
'$3 = PyInt_AsLong(temp[$1]);',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('$3 = $0;',), v2)
return True
if TxMatch(o, i, ('temp[$1] = PyInt_FromLong ( int_$2 );',
'$4 = PyInt_AsLong(temp[$1]);', # 1202 line 1238
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('$4 = int_$2;',), v2)
return True
if TxMatch(o, i, ('temp[$1] = PyInt_FromLong ( $3 );',
'$2 = PyInt_AS_LONG ( temp[$1] );',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('$2 = $3;',), v2)
return True
if TxMatch(o, i, ('temp[$1] = PyInt_FromLong ( $4 );',
'if (PyInt_CheckExact( $3 )) {',
'$5 = PyInt_AS_LONG ( $3 );',
'$6 = PyInt_AS_LONG ( temp[$1] );',
'$7 = $5 - $6;',
'if (( $7 ^ $5 ) < 0 && ( $7 ^~ $6 ) < 0) goto $8 ;',
'temp[$0] = PyInt_FromLong ( $7 );',
'} else if (PyFloat_CheckExact( $3 )) {',
'temp[$0] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($3) - (double)PyInt_AS_LONG ( temp[$1] ));',
'} else { $8 :;',
'if ((temp[$0] = PyNumber_InPlaceSubtract ( $3 , temp[$1] )) == 0) goto $2;',
'}',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('$6 = $4;',
'if (PyInt_CheckExact( $3 )) {',
'$5 = PyInt_AS_LONG ( $3 );',
'$7 = $5 - $6;',
'if (( $7 ^ $5 ) < 0 && ( $7 ^~ $6 ) < 0) goto $8 ;',
'temp[$0] = PyInt_FromLong ( $7 );',
'} else if (PyFloat_CheckExact( $3 )) {',
'temp[$0] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($3) - (double)( $6 ));',
'} else { $8 :;',
'temp[$1] = PyInt_FromLong ( $6 );',
'if ((temp[$0] = PyNumber_InPlaceSubtract ( $3 , temp[$1] )) == 0) goto $2;',
'CLEARTEMP($1);',
'}'), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyInt_FromLong ( $2 );',
'CLEARTEMP($1);',
'$6 = PyInt_AsLong ( temp[$0] );',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('$6 = $2;',
'CLEARTEMP($1);'), v2)
return True
if TxMatch(o, i, ('temp[$2] = PyInt_FromLong ( long_$1 );',
'CLEARTEMP($0);',
'long_$1 = PyInt_AS_LONG ( temp[$2] );',
'long_$1 = long_$1 + 1;',
'CLEARTEMP($2);'), v2):
TxRepl(o, i, ('CLEARTEMP($0);', 'long_$1 = long_$1 + 1;'), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyInt_FromLong ( $1 );',
'$2 = PyInt_AS_LONG ( temp[$0] );',
'$3 = $2 * $5;',
'if ($3 / $5 == $2) {',
'temp[$11] = PyInt_FromLong ($3);',
'} else {',
'temp[$11] = PyInt_Type.tp_as_number->nb_multiply(consts[$4], temp[$0]);',
'}',
'CLEARTEMP($0);'),v2):
TxRepl(o, i, ('$2 = $1;',
'$3 = $2 * $5;',
'if ($3 / $5 == $2) {',
'temp[$11] = PyInt_FromLong ($3);',
'} else {',
'temp[$0] = PyInt_FromLong ( $2 );',
'temp[$11] = PyInt_Type.tp_as_number->nb_multiply(consts[$4], temp[$0]);',
'CLEARTEMP($0);',
'}'), v2)
return True
if TxMatch(o, i, ('temp[$1] = PyInt_FromLong ( $4 );',
'$2 = PyInt_AsSsize_t ( temp[$1] );',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('$2 = $4;',), v2)
return True
if TxMatch(o, i, ('temp[$0] = PyInt_FromLong ( $3 );',
'if ((temp[$1] = PyObject_GetItem ( $4 , temp[$0] )) == 0) goto $2;',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('if ((temp[$1] = __c_BINARY_SUBSCR_Int ( $4 , $3 )) == 0) goto $2;',), v2, ('__c_BINARY_SUBSCR_Int',))
return True
if TxMatch(o, i, """
temp[$0] = PyInt_FromLong ( $3 );
temp[$2] = PyInt_FromLong (PyInt_AS_LONG ( temp[$0] ) << $8);
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
temp[$2] = PyInt_FromLong (($3) << $8);
""", v2)
return True
if TxMatch(o, i, """
temp[$0] = PyInt_FromLong ( $3 );
temp[$2] = PyInt_FromLong (PyInt_AS_LONG ( temp[$0] ) >> $8);
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
temp[$2] = PyInt_FromLong (($3) >> $8);
""", v2)
return True
if TxMatch(o, i, """
temp[$0] = PyInt_FromLong ( $5 );
temp[$1] = PyInt_FromLong (PyInt_AS_LONG ( temp[$0] ) $11);
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
temp[$1] = PyInt_FromLong (($5) $11);
""", v2)
return True
if TxMatch(o, i, """
temp[$0] = PyInt_FromLong ( $3 );
if (PyInt_CheckExact( temp[$1] )) {
long_$6 = PyInt_AS_LONG ( temp[$1] );
long_$7 = PyInt_AS_LONG ( temp[$0] );
long_$8 = long_$6 $9 long_$7;
if ($10) goto $5 ;
temp[$2] = PyInt_FromLong ( long_$8 );
} else if (PyFloat_CheckExact( temp[$1] )) {
temp[$2] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$1]) + (double)PyInt_AS_LONG ( temp[$0] ));
} else { $5 :;
if ((temp[$2] = PyNumber_Add ( temp[$1] , temp[$0] )) == 0) goto $4;
}
CLEARTEMP($1);
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( temp[$1] )) {
long_$7 = $3;
long_$6 = PyInt_AS_LONG ( temp[$1] );
long_$8 = long_$6 $9 long_$7;
if ($10) goto $5 ;
temp[$2] = PyInt_FromLong ( long_$8 );
} else if (PyFloat_CheckExact( temp[$1] )) {
temp[$2] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$1]) + (double)($3));
} else { $5 :;
temp[$0] = PyInt_FromLong ( $3 );
if ((temp[$2] = PyNumber_Add ( temp[$1] , temp[$0] )) == 0) goto $4;
CLEARTEMP($0);
}
CLEARTEMP($1);
""", v2)
return True
if TxMatch(o, i, """
temp[$0] = PyInt_FromLong ( long_$14 );
long_$3 = PyInt_AS_LONG ( temp[$0] );
long_$4 = long_$3 * $6;
if (long_$4 / $6 == long_$3) {
temp[$2] = PyInt_FromLong (long_$4);
} else {
temp[$2] = PyInt_Type.tp_as_number->nb_multiply(temp[$0], $7);
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
long_$3 = long_$14;
long_$4 = long_$3 * $6;
if (long_$4 / $6 == long_$3) {
temp[$2] = PyInt_FromLong (long_$4);
} else {
temp[$0] = PyInt_FromLong ( long_$3 );
temp[$2] = PyInt_Type.tp_as_number->nb_multiply(temp[$0], $7);
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
temp[$2] = PyInt_FromLong ( $10 );
if (PyInt_CheckExact( temp[$1] ) && PyInt_CheckExact( temp[$2] )) {
temp[$0] = PyInt_FromLong ( PyInt_AS_LONG ( temp[$1] ) $4 PyInt_AS_LONG ( temp[$2] ) );
} else {
if ((temp[$0] = PyNumber_$5 ( temp[$1] , temp[$2] )) == 0) goto $6;
}
CLEARTEMP($1);
CLEARTEMP($2);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( temp[$1] )) {
temp[$0] = PyInt_FromLong ( PyInt_AS_LONG ( temp[$1] ) $4 ($10) );
} else {
temp[$2] = PyInt_FromLong ( $10 );
if ((temp[$0] = PyNumber_$5 ( temp[$1] , temp[$2] )) == 0) goto $6;
CLEARTEMP($2);
}
CLEARTEMP($1);
""", v2)
return True
if TxMatch(o, i, """
temp[$0] = PyInt_FromLong ( $5 );
long_$3 = PyInt_AS_LONG ( temp[$0] );
long_$2 = $4;
temp[$1] = PyInt_FromLong ( long_$2 );
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
long_$3 = $5;
long_$2 = $4;
temp[$1] = PyInt_FromLong ( long_$2 );
""", v2)
return True
if TxMatch(o, i, """
temp[$1] = PyInt_FromLong ( $10 );
long_$5 = PyInt_AS_LONG ( temp[$1] );
long_$6 = $7;
if ($8) {
temp[$2] = PyInt_FromLong ( long_$6 );
} else {
temp[$2] = PyInt_Type.tp_as_number->nb$9;
}
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
long_$5 = $10;
long_$6 = $7;
if ($8) {
temp[$2] = PyInt_FromLong ( long_$6 );
} else {
temp[$1] = PyInt_FromLong ( $10 );
temp[$2] = PyInt_Type.tp_as_number->nb$9;
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
temp[$1] = PyInt_FromLong ( $10 );
if (PyInt_CheckExact( $11 )) {
long_$5 = PyInt_AS_LONG ( temp[$1] );
long_$7 = PyInt_AS_LONG ( $11 );
long_$4 = long_$5 $6 long_$7;
if ($9) goto $8 ;
temp[$2] = PyInt_FromLong ( long_$4 );
} else if (PyFloat_CheckExact( $11 )) {
temp[$2] = PyFloat_FromDouble((double)PyInt_AS_LONG ( temp[$1] ) $6 PyFloat_AS_DOUBLE($11));
} else { $8 :;
if ((temp[$2] = PyNumber_$12) == 0) goto $13;
}
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $11 )) {
long_$5 = $10;
long_$7 = PyInt_AS_LONG ( $11 );
long_$4 = long_$5 $6 long_$7;
if ($9) goto $8 ;
temp[$2] = PyInt_FromLong ( long_$4 );
} else if (PyFloat_CheckExact( $11 )) {
temp[$2] = PyFloat_FromDouble((double)($10) $6 PyFloat_AS_DOUBLE($11));
} else { $8 :;
temp[$1] = PyInt_FromLong ( $10 );
if ((temp[$2] = PyNumber_$12) == 0) goto $13;
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
temp[$0] = PyInt_FromLong ( $10 );
if (PyInt_CheckExact( temp[$1] )) {
long_$12 = PyInt_AS_LONG ( temp[$1] );
long_$14 = PyInt_AS_LONG ( temp[$0] );
long_$15;
if ($16) goto label_$7 ;
temp[$2] = PyInt_FromLong ( long_$17 );
} else if (PyFloat_CheckExact( temp[$1] )) {
temp[$2] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$1]) + (double)PyInt_AS_LONG ( temp[$0] ));
} else { label_$7 :;
if ((temp[$2] = PyNumber_$18) == 0) goto label_$11;
}
CLEARTEMP($1);
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( temp[$1] )) {
long_$12 = PyInt_AS_LONG ( temp[$1] );
long_$14 = ($10);
long_$15;
if ($16) goto label_$7 ;
temp[$2] = PyInt_FromLong ( long_$17 );
} else if (PyFloat_CheckExact( temp[$1] )) {
temp[$2] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$1]) + (double)($10));
} else { label_$7 :;
temp[$0] = PyInt_FromLong ( $10 );
if ((temp[$2] = PyNumber_$18) == 0) goto label_$11;
CLEARTEMP($0);
}
CLEARTEMP($1);
""", v2)
return True
if TxMatch(o, i, """
temp[$0] = PyInt_FromLong ( $7 );
if (PyInt_CheckExact( $3 )) {
long_$4 = PyInt_AS_LONG ( $3 );
long_$5 = PyInt_AS_LONG ( temp[$0] );
long_$2 = long_$4 + long_$5;
if (( long_$2 ^ long_$4 ) < 0 && ( long_$2 ^ long_$5 ) < 0) goto label_$6 ;
temp[$1] = PyInt_FromLong ( long_$2 );
} else if (PyFloat_CheckExact( $3 )) {
temp[1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($3) + (double)PyInt_AS_LONG ( temp[$0] ));
} else { label_$6 :;
if ((temp[1] = PyNumber_$9Add ( $3 , temp[$0] )) == 0) goto label_$10;
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $3 )) {
long_$4 = PyInt_AS_LONG ( $3 );
long_$5 = $7;
long_$2 = long_$4 + long_$5;
if (( long_$2 ^ long_$4 ) < 0 && ( long_$2 ^ long_$5 ) < 0) goto label_$6 ;
temp[$1] = PyInt_FromLong ( long_$2 );
} else if (PyFloat_CheckExact( $3 )) {
temp[1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($3) + (double)($7));
} else { label_$6 :;
temp[$0] = PyInt_FromLong ( $7 );
if ((temp[1] = PyNumber_$9Add ( $3 , temp[$0] )) == 0) goto label_$10;
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
temp[$0] = PyInt_FromLong ( $1 );
if ( PyObject_SetAttr ( $3 ) == -1) goto label_$4;
CLEARTEMP($0);
temp[$0] = PyInt_FromLong ( $1 );
""", v2):
TxRepl(o, i, """
temp[$0] = PyInt_FromLong ( $1 );
if ( PyObject_SetAttr ( $3 ) == -1) goto label_$4;
""", v2)
return True
return False
def tune_if_dotcomma(o, i):
v2 = []
if 'PyString_AsStringAndSize' in o[i]:
if TxMatch(o, i, """
if ( PyString_AsStringAndSize ( $0 , &charref_$4 , &Py_ssize_t_$3 ) == -1) goto label_$10;
int_$11 = $16;
if ( !int_$11 ) {
if ( PyString_AsStringAndSize ( $0 , &charref_$4 , &Py_ssize_t_$3 ) == -1) goto label_$10;
int_$11 = $17;
}""", v2):
TxRepl(o, i, """
if ( PyString_AsStringAndSize ( $0 , &charref_$4 , &Py_ssize_t_$3 ) == -1) goto label_$10;
int_$11 = $16;
if ( !int_$11 ) {
int_$11 = $17;
}""", v2)
return True
if TxMatch(o, i, """
if ( PyString_AsStringAndSize ( $0 , &$1 , &$12 ) == -1) goto label_$3;
int_$4 = $12 - $7;
charref_$5 = $1 + int_$4;
int_$6 = ($12 >= $7 && 0 == memcmp($8, charref_$5, $7));
""", v2):
TxRepl(o, i, """
if ( PyString_AsStringAndSize ( $0 , &$1 , &$12 ) == -1) goto label_$3;
int_$6 = ($12 >= $7 && 0 == memcmp($8, $1 + ($12 - $7), $7));
""", v2)
return True
if o[i].startswith('if ((Py_ssize_t_'):
if TxMatch(o, i, """
if ((Py_ssize_t_$2 = PyObject_Size ( temp[$0] )) == -1) goto label_$10;
CLEARTEMP($0);
long_$3 = Py_ssize_t_$2;""", v2):
TxRepl(o, i, """
if ((long_$3 = PyObject_Size ( temp[$0] )) == -1) goto label_$10;
CLEARTEMP($0);""", v2)
return True
if TxMatch(o, i, """
if ((Py_ssize_t_$1 = $2) == -1) goto $3;
Loc_long_$4 = ( Py_ssize_t_$1 );""", v2):
TxRepl(o, i, "if ((Loc_long_$4 = $2) == -1) goto $3;", v2)
return True
if TxMatch(o, i, """
if ((Py_ssize_t_$2 = $5) == -1) goto label_$0;
long_$3 = Py_ssize_t_$2 $9;
if (PyInt_CheckExact( $6 )) {
int_$1 = PyInt_AS_LONG ( $6 ) $8 long_$3 ;
} else {
temp[$4] = PyInt_FromLong ( long_$3 );
if ((int_$1 = PyObject_RichCompareBool ( $6 , temp[$4] , Py_$7 )) == -1) goto label_$0;
CLEARTEMP($4);
}
""", v2):
TxRepl(o, i, """
if ((Py_ssize_t_$2 = $5) == -1) goto label_$0;
if (PyInt_CheckExact( $6 )) {
int_$1 = PyInt_AS_LONG ( $6 ) $8 (Py_ssize_t_$2 $9);
} else {
temp[$4] = PyInt_FromLong ( Py_ssize_t_$2 $9 );
if ((int_$1 = PyObject_RichCompareBool ( $6 , temp[$4] , Py_$7 )) == -1) goto label_$0;
CLEARTEMP($4);
}
""", v2)
return True
if TxMatch(o, i, """
if ((Py_ssize_t_$8 = $10 )) == -1) goto label_$4;
temp[$1] = PyInt_FromLong ( Py_ssize_t_$8 );
long_$7 = PyInt_AS_LONG ( temp[$1] );
long_$6 = $9 + long_$7;
if (( long_$6 ^ $9 ) < 0 && ( long_$6 ^ long_$7 ) < 0) goto label_$5 ;
temp[$2] = PyInt_FromLong ( long_$6 );
if (1) {
} else { label_$5 :;
temp[$3] = PyInt_FromLong ( $9 );
if ((temp[$2] = PyNumber_Add ( temp[$3] , temp[$1] )) == 0) goto label_$4;
CLEARTEMP($3);
}
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if ((long_$7 = $10 )) == -1) goto label_$4;
long_$6 = $9 + long_$7;
if (( long_$6 ^ $9 ) < 0 && ( long_$6 ^ long_$7 ) < 0) {
temp[$1] = PyInt_FromLong ( long_$7 );
temp[$3] = PyInt_FromLong ( $9 );
if ((temp[$2] = PyNumber_Add ( temp[$3] , temp[$1] )) == 0) goto label_$4;
CLEARTEMP($3);
CLEARTEMP($1);
} else {
temp[$2] = PyInt_FromLong ( long_$6 );
}
""", v2) ### line 32938
return True
elif o[i].startswith('if ((int_'):
if '_Direct_' in o[i]:
if TxMatch(o, i, ('if ((int_$8 = _Direct_$19;',
'Loc_int_$2 = int_$8;'), v2):
TxRepl(o, i, ('if ((Loc_int_$2 = _Direct_$19;',), v2)
return True
if TxMatch(o, i, ('if ((int_$8 = _Direct_$19;',
'CLEARTEMP($0);',
'Loc_int_$2 = int_$8;'), v2):
TxRepl(o, i, ('if ((Loc_int_$2 = _Direct_$19;',
'CLEARTEMP($0);'), v2)
return True
if TxMatch(o, i, ('if ((int_$8 = _Direct_$19;',
'CLEARTEMP($0);',
'CLEARTEMP($1);',
'Loc_int_$2 = int_$8;'), v2):
TxRepl(o, i, ('if ((Loc_int_$2 = _Direct_$19;',
'CLEARTEMP($0);',
'CLEARTEMP($1);'), v2)
return True
if TxMatch(o, i, ('if ((int_$3 = _Direct_$1) == -1) goto label_$0;',
'int_$2 = int_$3;'), v2):
TxRepl(o, i, ('if ((int_$2 = _Direct_$1) == -1) goto label_$0;',), v2)
return True
if TxMatch(o, i, ('if ((int_$2 = _Direct_$0) == -1) goto $3;',
'CLEARTEMP($4);',
'int_$1 = int_$2;',
'if ( int_$1 ) {'), v2) and v2[2] != v2[1]:
TxRepl(o, i, ('if ((int_$1 = _Direct_$0) == -1) goto $3;',
'CLEARTEMP($4);',
'if ( int_$1 ) {'), v2)
return True
if TxMatch(o, i, ('if ((int_$2 = _Direct_$0) == -1) goto $3;',
'CLEARTEMP($4);',
'int_$1 = int_$2;',
'}'), v2) and v2[2] != v2[1]:
TxRepl(o, i, ('if ((int_$1 = _Direct_$0) == -1) goto $3;',
'CLEARTEMP($4);',
'}'), v2)
return True
if TxMatch(o, i, ('if (($2 = _Direct_$5) == -1) goto $3;',
'temp[$0] = PyBool_FromLong($2);',
'$12 = PyObject_IsTrue ( temp[$0] );',
'CLEARTEMP($0);'), v2) and v2[2] != v2[12]:
TxRepl(o, i, ('if (($12 = _Direct_$5) == -1) goto $3;',), v2)
return True
if TxMatch(o, i, ('if (($2 = _Direct_$5) == -1) goto $3;',
'if ((temp[$0] = PyBool_FromLong ( $2 )) == 0) goto $3;',
'$12 = PyObject_IsTrue ( temp[$0] );',
'CLEARTEMP($0);'), v2) and v2[2] != v2[12]:
TxRepl(o, i, ('if (($12 = _Direct_$5) == -1) goto $3;',), v2)
return True
if TxMatch(o, i, ('if (($2 = _Direct_$5) == -1) goto $3;',
'CLEARTEMP($6);',
'temp[$0] = PyBool_FromLong($2);',
'$12 = PyObject_IsTrue ( temp[$0] );',
'CLEARTEMP($0);'), v2) and v2[2] != v2[12]:
TxRepl(o, i, ('if (($12 = _Direct_$5) == -1) goto $3;',
'CLEARTEMP($6);'), v2)
return True
if TxMatch(o, i, ('if (($2 = _Direct_$5) == -1) goto $3;',
'CLEARTEMP($6);',
'if ((temp[$0] = PyBool_FromLong ( $2 )) == 0) goto $3;',
'$12 = PyObject_IsTrue ( temp[$0] );',
'CLEARTEMP($0);'), v2) and v2[2] != v2[12]:
TxRepl(o, i, ('if (($12 = _Direct_$5) == -1) goto $3;',
'CLEARTEMP($6);'), v2)
return True
if TxMatch(o, i, ('if (($2 = _Direct_$5) == -1) goto $3;',
'CLEARTEMP($6);',
'CLEARTEMP($7);',
'if ((temp[$0] = PyBool_FromLong ( $2 )) == 0) goto $3;',
'$12 = PyObject_IsTrue ( temp[$0] );',
'CLEARTEMP($0);'), v2) and v2[2] != v2[12]:
TxRepl(o, i, ('if (($12 = _Direct_$5) == -1) goto $3;',
'CLEARTEMP($6);',
'CLEARTEMP($7);'), v2)
return True
if TxMatch(o, i, ('if (($2 = _Direct_$5) == -1) goto $3;',
'if ((temp[$0] = PyBool_FromLong ( $2 )) == 0) goto $3;',
'$12 = PyObject_Not ( temp[$0] );',
'CLEARTEMP($0);'), v2) and v2[2] != v2[12]:
TxRepl(o, i, ('if (($12 = !_Direct_$5) == -1) goto $3;',), v2)
return True
if TxMatch(o, i, ('if (($2 = _Direct_$5) == -1) goto $3;',
'CLEARTEMP($6);',
'if ((temp[$0] = PyBool_FromLong ( $2 )) == 0) goto $3;',
'$12 = PyObject_Not ( temp[$0] );',
'CLEARTEMP($0);'), v2) and v2[2] != v2[12]:
TxRepl(o, i, ('if (($12 = !_Direct_$5) == -1) goto $3;',
'CLEARTEMP($6);'), v2)
return True
if TxMatch(o, i, ('if (($2 = _Direct_$5) == -1) goto $3;',
'CLEARTEMP($6);',
'CLEARTEMP($7);',
'if ((temp[$0] = PyBool_FromLong ( $2 )) == 0) goto $3;',
'$12 = PyObject_Not ( temp[$0] );',
'CLEARTEMP($0);'), v2) and v2[2] != v2[12]:
TxRepl(o, i, ('if (($12 = !_Direct_$5) == -1) goto $3;',
'CLEARTEMP($6);',
'CLEARTEMP($7);'), v2)
return True
if TxMatch(o, i, """
if ((int_$1 = $9temp[$10]$11) == -1) goto label_$0;
CLEARTEMP($10);
Loc_int_$3 = int_$1;
""", v2):
TxRepl(o, i, """
if ((Loc_int_$3 = $9temp[$10]$11) == -1) goto label_$0;
CLEARTEMP($10);
""", v2)
return True
if TxMatch(o, i, """
if ((int_$3 = $4) == -1) goto label_$0;
Loc_int_$5 = int_$3;
""", v2):
TxRepl(o, i, """
if ((Loc_int_$5 = $4) == -1) goto label_$0;
""", v2)
return True
elif o[i].startswith('if ((temp['):
if 'SUBSCR' in o[i]:
if i+1 < len(o) and o[i+1].startswith('int_'):
if TxMatch(o, i, ('if ((temp[$0] = _c_BINARY_SUBSCR_Int ( $2 , $4 , $3 )) == 0) goto $7;',
'int_$1 = $12;',
'CLEARTEMP($0);',
'if (!( int_$1 )) {',
'if ((temp[$0] = _c_BINARY_SUBSCR_Int ( $2 , $4 , $3 )) == 0) goto $7;',
'int_$1 = $11;',
'CLEARTEMP($0);',
'}'), v2):
TxRepl(o, i, ('if ((temp[$0] = _c_BINARY_SUBSCR_Int ( $2 , $4 , $3 )) == 0) goto $7;',
'int_$1 = ($12) || ($11);',
'CLEARTEMP($0);'), v2)
return True
if TxMatch(o, i, ('if ((temp[$0] = _c_BINARY_SUBSCR_Int ( $2 , $4 , $3 )) == 0) goto $7;',
'int_$1 = $12;',
'CLEARTEMP($0);',
'if ( !int_$1 ) {',
'if ((temp[$0] = _c_BINARY_SUBSCR_Int ( $2 , $4 , $3 )) == 0) goto $7;',
'int_$1 = $11;',
'CLEARTEMP($0);',
'}'), v2):
TxRepl(o, i, ('if ((temp[$0] = _c_BINARY_SUBSCR_Int ( $2 , $4 , $3 )) == 0) goto $7;',
'int_$1 = ($12) || ($11);',
'CLEARTEMP($0);'), v2)
return True
if TxMatch(o, i, ('if ((temp[$0] = _c_BINARY_SUBSCR_Int ( $2 , $4 , $3 )) == 0) goto $7;',
'int_$1 = $12;',
'CLEARTEMP($0);',
'if ( int_$1 ) {',
'if ((temp[$0] = _c_BINARY_SUBSCR_Int ( $2 , $4 , $3 )) == 0) goto $7;',
'int_$1 = $11;',
'CLEARTEMP($0);',
'}'), v2):
TxRepl(o, i, ('if ((temp[$0] = _c_BINARY_SUBSCR_Int ( $2 , $4 , $3 )) == 0) goto $7;',
'int_$1 = ($12) && ($11);',
'CLEARTEMP($0);'), v2)
return True
## if ' , consts[' in o[i]:
## if TxMatch(o, i, ('if ((temp[$0] = _c_BINARY_SUBSCR_Int ( $3 , 0 , consts[$9] )) == 0) goto $5;',), v2):
## TxRepl(o, i, ('if ((temp[$0] = _GET_ITEM_0 ( $3 )) == 0) goto $5;',), v2, ('_GET_ITEM_0',))
## return True
## if TxMatch(o, i, ('if ((temp[$0] = _c_BINARY_SUBSCR_Int ( $3 , -1 , consts[$9] )) == 0) goto $5;',), v2):
## TxRepl(o, i, ('if ((temp[$0] = _GET_ITEM_LAST ( $3 )) == 0) goto $5;',), v2, ('_GET_ITEM_LAST',))
## return True
## if TxMatch(o, i, ('if ((temp[$0] = _c_BINARY_SUBSCR_Int ( $3 , 1 , consts[$9] )) == 0) goto $5;',), v2):
## TxRepl(o, i, ('if ((temp[$0] = _GET_ITEM_1 ( $3 )) == 0) goto $5;',), v2, ('_GET_ITEM_1',))
## return True
## if TxMatch(o, i, ('if ((temp[$0] = _c_BINARY_SUBSCR_Int ( $3 , 2 , consts[$9] )) == 0) goto $5;',), v2):
## TxRepl(o, i, ('if ((temp[$0] = _GET_ITEM_2 ( $3 )) == 0) goto $5;',), v2, ('_GET_ITEM_2',))
## return True
## if TxMatch(o, i, ('if ((temp[$0] = _c_BINARY_SUBSCR_Int ( temp[$3] , 0 , consts[$9] )) == 0) goto $5;',), v2):
## TxRepl(o, i, ('if ((temp[$0] = _GET_ITEM_0 ( temp[$3] )) == 0) goto $5;',), v2, ('_GET_ITEM_0',))
## return True
## if TxMatch(o, i, ('if ((temp[$0] = _c_BINARY_SUBSCR_Int ( temp[$3] , -1 , consts[$9] )) == 0) goto $5;',), v2):
## TxRepl(o, i, ('if ((temp[$0] = _GET_ITEM_LAST ( temp[$3] )) == 0) goto $5;',), v2, ('_GET_ITEM_LAST',))
## return True
## if TxMatch(o, i, ('if ((temp[$0] = _c_BINARY_SUBSCR_Int ( temp[$3] , 1 , consts[$9] )) == 0) goto $5;',), v2):
## TxRepl(o, i, ('if ((temp[$0] = _GET_ITEM_1 ( temp[$3] )) == 0) goto $5;',), v2, ('_GET_ITEM_1',))
## return True
## if TxMatch(o, i, ('if ((temp[$0] = _c_BINARY_SUBSCR_Int ( temp[$3] , 2 , consts[$9] )) == 0) goto $5;',), v2):
## TxRepl(o, i, ('if ((temp[$0] = _GET_ITEM_2 ( temp[$3] )) == 0) goto $5;',), v2, ('_GET_ITEM_2',))
## return True
if 'PyList_GetItem' in o[i]:
if TxMatch(o, i, """
if ((temp[$0] = PyList_GetItem ($10)) == 0) goto label_$11;
Py_INCREF(temp[$0]);
if ((temp[$1] = _Direct_$12 ( temp[$0] )) == 0) goto label_$11;
CLEARTEMP($0);""", v2):
TxRepl(o, i, """
if ((temp[$0] = PyList_GetItem ($10)) == 0) goto label_$11;
if ((temp[$1] = _Direct_$12 ( temp[$0] )) == 0) goto label_$11;
temp[$0] = 0;""", v2)
return True
if TxMatch(o, i, """
if ((temp[$0] = PyList_GetItem ($11)) == 0) goto label_$10;
Py_INCREF(temp[$0]);
if (($15 = _Direct_$12(temp[$0])) == -1) goto label_$10;
CLEARTEMP($0);""", v2):
TxRepl(o, i, """
if ((temp[$0] = PyList_GetItem ($11)) == 0) goto label_$10;
if (($15 = _Direct_$12(temp[$0])) == -1) goto label_$10;
temp[$0] = 0;""", v2)
return True
if TxMatch(o, i, """
if ((temp[$0] = PyList_GetItem ($16)) == 0) goto label_$15;
Py_INCREF(temp[$0]);
if ((temp[$1] = PyList_GetItem ($16)) == 0) goto label_$15;
Py_INCREF(temp[$1]);
if (($11 = _Direct_$12($13)) == $14) goto label_$15;
CLEARTEMP($0);
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if ((temp[$0] = PyList_GetItem ($16)) == 0) goto label_$15;
if ((temp[$1] = PyList_GetItem ($16)) == 0) goto label_$15;
if (($11 = _Direct_$12($13)) == $14) goto label_$15;
temp[$0] = 0;
temp[$1] = 0;""", v2)
return True
if TxMatch(o, i, """
if ((temp[$0] = PyList_GetItem ($10)) == 0) goto label_$11;
Py_INCREF(temp[$0]);
if (($5 = _Direct_$12 ( temp[$0] ))$6) goto label_$11;
CLEARTEMP($0);""", v2):
TxRepl(o, i, """
if ((temp[$0] = PyList_GetItem ($10)) == 0) goto label_$11;
if (($5 = _Direct_$12 ( temp[$0] ))$6) goto label_$11;
temp[$0] = 0;""", v2)
return True
if TxMatch(o, i, """
if ((temp[$0] = PyList_GetItem ($10)) == 0) goto label_$11;
Py_INCREF(temp[$0]);
if (($5 = _Direct_$12 ($7temp[$0]$8))$6) goto label_$11;
CLEARTEMP($0);""", v2):
TxRepl(o, i, """
if ((temp[$0] = PyList_GetItem ($10)) == 0) goto label_$11;
if (($5 = _Direct_$12 ($7temp[$0]$8))$6) goto label_$11;
temp[$0] = 0;""", v2)
return True
if 'PyFloat_FromDouble' in o[i]:
if TxMatch(o, i, ('if ((temp[$0] = PyFloat_FromDouble ( double_$1 )) == 0) goto $9;',
'if ((double_$1 = PyFloat_AsDouble ( temp[$0] )) == -1) goto $9;',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, (), v2)
return True
if TxMatch(o, i, ('if ((temp[$0] = PyFloat_FromDouble ( $2 )) == 0) goto $3;',
'if ((double_$4 = PyFloat_AsDouble ( temp[$0] )) == -1) goto $3;',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('double_$4 = $2;',), v2)
return True
if TxMatch(o, i, """
if ((temp[$0] = PyFloat_FromDouble ( $3 )) == 0) goto label_$15;
int_$5 = PyFloat_AS_DOUBLE( temp[$0] ) $10;
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """int_$5 = ( $3 ) $10;""", v2)
return True
if '_PyEval_ApplySlice' in o[i]:
if TxMatch(o, i, ('if ((temp[$1] = _PyEval_ApplySlice ( $3 , $4 , NULL )) == 0) goto $5;',
'if (PyInt_CheckExact( $7 ) && PyInt_CheckExact( temp[$1] )) {',
'$8 = PyInt_AS_LONG ( $7 );',
'$9 = PyInt_AS_LONG ( temp[$1] );',
'$10 = $8 + $9;',
'if (( $10 ^ $8 ) < 0 && ( $10 ^ $9 ) < 0) goto $6 ;',
'temp[$2] = PyInt_FromLong ( $10 );',
'} else if (PyFloat_CheckExact( $7 ) && PyFloat_CheckExact( temp[$1] )) {',
'temp[$2] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($7) + PyFloat_AS_DOUBLE(temp[$1]));',
'} else { $6 :;',
'if ((temp[$2] = PyNumber_Add ( $7 , temp[$1] )) == 0) goto $5;',
'}'), v2):
TxRepl(o, i, ('if ((temp[$1] = _PyEval_ApplySlice ( $3 , $4 , NULL )) == 0) goto $5;',
'if ((temp[$2] = PyNumber_Add ( $7 , temp[$1] )) == 0) goto $5;'), v2)
return True
if TxMatch(o, i, ('if ((temp[$1] = _PyEval_ApplySlice ( $3 , $4 , NULL )) == 0) goto $5;',
'if (PyInt_CheckExact( $7 ) && PyInt_CheckExact( temp[$1] )) {',
'$8 = PyInt_AS_LONG ( $7 );',
'$9 = PyInt_AS_LONG ( temp[$1] );',
'$10 = $8 + $9;',
'if (( $10 ^ $8 ) < 0 && ( $10 ^ $9 ) < 0) goto $6 ;',
'temp[$2] = PyInt_FromLong ( $10 );',
'} else { $6 :;',
'if ((temp[$2] = PyNumber_Add ( $7 , temp[$1] )) == 0) goto $5;',
'}'), v2):
TxRepl(o, i, ('if ((temp[$1] = _PyEval_ApplySlice ( $3 , $4 , NULL )) == 0) goto $5;',
'if ((temp[$2] = PyNumber_Add ( $7 , temp[$1] )) == 0) goto $5;'), v2)
return True
if 'PyBool_FromLong' in o[i]:
if TxMatch(o, i, """
if ((temp[$1] = PyBool_FromLong ($9)) == 0) goto label_$0;
if ((int_$3 = PyObject_Not ( temp[$1] )) == -1) goto label_$0;
CLEARTEMP($1);""", v2):
TxRepl(o, i, """
if ((int_$3 = ! ($9)) == -1) goto label_$0;""", v2)
return True
if TxMatch(o, i, ('if ((temp[$0] = PyBool_FromLong ( $2 )) == 0) goto $3;',
'$2 = PyObject_IsTrue ( temp[$0] );',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, (), v2)
return True
if TxMatch(o, i, ('if ((temp[$0] = PyBool_FromLong ($6)) == 0) goto $3;',
'SETLOCAL ( $1 , temp[$0] );',
'temp[$0] = 0;',
'if ((int_$4 = PyObject_IsTrue ( GETLOCAL($1) )) == -1) goto $3;'), v2):
v2[6] = v2[6].strip()
TxRepl(o, i, ('int_$4 = $6;',
'if ((temp[$0] = PyBool_FromLong ( int_$4 )) == 0) goto $3;',
'SETLOCAL ( $1 , temp[$0] );',
'temp[$0] = 0;'), v2)
return True
if TxMatch(o, i, ('if ((temp[$0] = PyBool_FromLong ( $1 )) == 0) goto $3;',
'int_$2 = PyObject_IsTrue ( temp[$0] );',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('int_$2 = $1;',), v2)
return True
if TxMatch(o, i, ('if ((temp[$1] = PyBool_FromLong ( $2 )) == 0) goto $0;',
'if (($3 = PyObject_IsTrue ( temp[$1] )) == -1) goto $0;',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('$3 = ($2);',), v2)
return True
if TxMatch(o, i, ('if ((temp[$0] = PyBool_FromLong ($1)) == 0) goto $5;',
'$2 = PyObject_IsTrue(temp[$0]);',
'CLEARTEMP($0);'), v2):
v2[1] = v2[1].strip()
TxRepl(o, i, ('$2 = $1;',), v2)
return True
if TxMatch(o, i, """
if ((temp[$0] = PyBool_FromLong ( int_$10 )) == 0) goto label_$12;
if ((temp[$1] = PyTuple_New ( 1 )) == 0) goto label_$12;
PyTuple_SET_ITEM ( temp[$1] , 0 , temp[$0] );
if ((temp[$0] = PyBool_Type.tp_new ( &PyBool_Type , temp[$1] , NULL )) == 0) goto label_$12;
CLEARTEMP($1);
int_$10 = PyObject_IsTrue ( temp[$0] );""", v2):
TxRepl(o, i, '', v2)
return True
if TxMatch(o, i, """
if ((temp[$0] = PyBool_FromLong ( int_$10 )) == 0) goto label_$12;
if ((temp[$1] = PyTuple_New ( 1 )) == 0) goto label_$12;
PyTuple_SET_ITEM ( temp[$1] , 0 , temp[$0] );
if ((temp[$0] = PyBool_Type.tp_new ( &PyBool_Type , temp[$1] , NULL )) == 0) goto label_$12;
CLEARTEMP($1);
int_$15 = PyObject_IsTrue ( temp[$0] );""", v2):
TxRepl(o, i, ('int_$15 = int_$10;',), v2)
return True
if TxMatch(o, i, ('if ((temp[$4] = PyBool_FromLong ($1)) == 0) goto $5;',
'CLEARTEMP($0);',
'if (($2 = PyObject_IsTrue ( temp[$4] )) == -1) goto $5;',
'CLEARTEMP($4);'), v2):
v2[1] = v2[1].strip()
TxRepl(o, i, ('$2 = $1;',
'CLEARTEMP($0);'), v2)
return True
if TxMatch(o, i, """
if ((temp[$2] = PyBool_FromLong ( $6 )) == 0) goto label_$5;
if ((temp[$3] = PyTuple_New ( 1 )) == 0) goto label_$5;
PyTuple_SET_ITEM ( temp[$3] , 0 , temp[$2] );
if ((temp[$2] = PyBool_Type.tp_new ( &PyBool_Type , temp[$3] , NULL )) == 0) goto label_$5;
CLEARTEMP($3);
if ((int_$7 = PyObject_IsTrue ( temp[$2] )) == -1) goto label_$5;
CLEARTEMP($2);
""", v2):
TxRepl(o, i, """int_$7 = $6;""", v2)
return True
if 'PyInt_FromSsize_t' in o[i]:
if TxMatch(o, i, ('if ((temp[$1] = PyInt_FromSsize_t ($2)) == 0) goto $3;',
'Py_ssize_t_$4 = PyInt_AsSsize_t ( temp[$1] );',
'CLEARTEMP($1);'), v2):
v2[3] = v2[3].strip()
TxRepl(o, i, ('Py_ssize_t_$4 = $2;',), v2)
return True
if TxMatch(o, i, ('if ((temp[$0] = PyInt_FromSsize_t ( $1 )) == 0) goto $3;',
'if (PyInt_CheckExact( $2 )) {',
'$5 = PyInt_AS_LONG ( $2 );',
'$6 = PyInt_AS_LONG ( temp[$0] );',
'$7 = $5 + $6;',
'if (( $7 ^ $5 ) < 0 && ( $7 ^ $6 ) < 0) goto $4 ;',
'temp[$11] = PyInt_FromLong ( $7 );',
'} else if (PyFloat_CheckExact( $2 )) {',
'temp[$11] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($2) + (double)PyInt_AS_LONG ( temp[$0] ));',
'} else { $4 :;',
'if ((temp[$11] = PyNumber_InPlaceAdd ( $2 , temp[$0] )) == 0) goto $3;',
'}',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $2 )) {',
'$5 = PyInt_AS_LONG ( $2 );',
'$6 = $1;',
'$7 = $5 + $6;',
'if (( $7 ^ $5 ) < 0 && ( $7 ^ $6 ) < 0) goto $4 ;',
'temp[$11] = PyInt_FromLong ( $7 );',
'} else if (PyFloat_CheckExact( $2 )) {',
'temp[$11] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($2) + (double)($1));',
'} else { $4 :;',
'if ((temp[$0] = PyInt_FromSsize_t ( $1 )) == 0) goto $3;',
'if ((temp[$11] = PyNumber_InPlaceAdd ( $2 , temp[$0] )) == 0) goto $3;',
'CLEARTEMP($0);'
'}'), v2)
return True
if TxMatch(o, i, ('if ((temp[$0] = PyInt_FromSsize_t ( $1 )) == 0) goto $3;',
'if (PyInt_CheckExact( $2 )) {',
'$5 = PyInt_AS_LONG ( $2 );',
'$6 = PyInt_AS_LONG ( temp[$0] );',
'$7 = $5 + $6;',
'if (( $7 ^ $5 ) < 0 && ( $7 ^ $6 ) < 0) goto $4 ;',
'temp[$11] = PyInt_FromLong ( $7 );',
'} else { $4 :;',
'if ((temp[$11] = PyNumber_InPlaceAdd ( $2 , temp[$0] )) == 0) goto $3;',
'}',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $2 )) {',
'$5 = PyInt_AS_LONG ( $2 );',
'$6 = $1;',
'$7 = $5 + $6;',
'if (( $7 ^ $5 ) < 0 && ( $7 ^ $6 ) < 0) goto $4 ;',
'temp[$11] = PyInt_FromLong ( $7 );',
'} else { $4 :;',
'if ((temp[$0] = PyInt_FromSsize_t ( $1 )) == 0) goto $3;',
'if ((temp[$11] = PyNumber_InPlaceAdd ( $2 , temp[$0] )) == 0) goto $3;',
'CLEARTEMP($0);'
'}'), v2)
return True
if TxMatch(o, i, ('if ((temp[$0] = PyInt_FromSsize_t ( $1 )) == 0) goto $2;',
'$3 = PyInt_AsLong(temp[$0]);',
'Py_CLEAR(temp[$0]);',
'temp[$0] = 0;'), v2):
TxRepl(o, i, ('$3 = $1;',), v2)
return True
if TxMatch(o, i, ('if ((temp[$0] = PyInt_FromSsize_t ($2)) == 0) goto $3;',
'long_$5 = PyInt_AS_LONG ( temp[$0] );',
'long_$4 = long_$5 - $6;',
'temp[$1] = PyInt_FromLong ( long_$4 );',
'CLEARTEMP($0);'), v2):
v2[2] = v2[2].strip()
TxRepl(o, i, ('long_$4 = ($2) - $6;',
'temp[$1] = PyInt_FromLong ( long_$4 );'), v2)
return True
if TxMatch(o, i, ('if ((temp[$0] = PyInt_FromSsize_t ($2)) == 0) goto $3;',
'long_$5 = PyInt_AS_LONG ( temp[$0] );',
'long_$4 = long_$5 + $6;',
'temp[$1] = PyInt_FromLong ( long_$4 );',
'CLEARTEMP($0);'), v2):
v2[2] = v2[2].strip()
TxRepl(o, i, ('long_$4 = ($2) + $6;',
'temp[$1] = PyInt_FromLong ( long_$4 );'), v2)
return True
if TxMatch(o, i, ('if ((temp[$1] = PyInt_FromSsize_t ( $10 )) == 0) goto $0;',
'if (PyInt_CheckExact( $3 )) {',
'$4 = PyInt_AS_LONG ( $3 );',
'$5 = PyInt_AS_LONG ( temp[$1] );',
'$6 = $4 - $5;',
'if (( $6 ^ $4 ) < 0 && ( $6 ^~ $5 ) < 0) goto $7 ;',
'temp[$2] = PyInt_FromLong ( $6 );',
'} else if (PyFloat_CheckExact( $3 )) {',
'temp[$2] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($3) - (double)PyInt_AS_LONG ( temp[$1] ));',
'} else { $7 :;',
'if ((temp[$2] = PyNumber_Subtract ( $3 , temp[$1] )) == 0) goto $0;',
'}',
'CLEARTEMP($1);'),v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $3 )) {',
'$4 = PyInt_AS_LONG ( $3 );',
'$5 = $10;',
'$6 = $4 - $5;',
'if (( $6 ^ $4 ) < 0 && ( $6 ^~ $5 ) < 0) goto $7 ;',
'temp[$2] = PyInt_FromLong ( $6 );',
'} else if (PyFloat_CheckExact( $3 )) {',
'temp[$2] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($3) - (double)$10);',
'} else { $7 :;',
'if ((temp[$1] = PyInt_FromSsize_t ( $10 )) == 0) goto $0;',
'if ((temp[$2] = PyNumber_Subtract ( $3 , temp[$1] )) == 0) goto $0;',
'CLEARTEMP($1);'
'}'), v2)
return True
if TxMatch(o, i, ('if ((temp[$1] = PyInt_FromSsize_t ( $10 )) == 0) goto $0;',
'if (PyInt_CheckExact( $3 )) {',
'$4 = PyInt_AS_LONG ( $3 );',
'$5 = PyInt_AS_LONG ( temp[$1] );',
'$6 = $4 - $5;',
'if (( $6 ^ $4 ) < 0 && ( $6 ^~ $5 ) < 0) goto $7 ;',
'temp[$2] = PyInt_FromLong ( $6 );',
'} else { $7 :;',
'if ((temp[$2] = PyNumber_Subtract ( $3 , temp[$1] )) == 0) goto $0;',
'}',
'CLEARTEMP($1);'),v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $3 )) {',
'$4 = PyInt_AS_LONG ( $3 );',
'$5 = $10;',
'$6 = $4 - $5;',
'if (( $6 ^ $4 ) < 0 && ( $6 ^~ $5 ) < 0) goto $7 ;',
'temp[$2] = PyInt_FromLong ( $6 );',
'} else { $7 :;',
'if ((temp[$1] = PyInt_FromSsize_t ( $10 )) == 0) goto $0;',
'if ((temp[$2] = PyNumber_Subtract ( $3 , temp[$1] )) == 0) goto $0;',
'CLEARTEMP($1);'
'}'), v2)
return True
if TxMatch(o, i, ('if ((temp[$1] = PyInt_FromSsize_t ( $10 )) == 0) goto $0;',
'if (PyInt_CheckExact( $3 )) {',
'$4 = PyInt_AS_LONG ( temp[$1] );',
'$5 = PyInt_AS_LONG ( $3 );',
'$6 = $4 - $5;',
'if (( $6 ^ $4 ) < 0 && ( $6 ^~ $5 ) < 0) goto $7 ;',
'temp[$2] = PyInt_FromLong ( $6 );',
'} else if (PyFloat_CheckExact( $3 )) {',
'temp[$2] = PyFloat_FromDouble((double)PyInt_AS_LONG ( temp[$1] ) - PyFloat_AS_DOUBLE($3));',
'} else { $7 :;',
'if ((temp[$2] = PyNumber_Subtract ( temp[$1] , $3 )) == 0) goto $0;',
'}',
'CLEARTEMP($1);'),v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $3 )) {',
'$4 = $10;',
'$5 = PyInt_AS_LONG ( $3 );',
'$6 = $4 - $5;',
'if (( $6 ^ $4 ) < 0 && ( $6 ^~ $5 ) < 0) goto $7 ;',
'temp[$2] = PyInt_FromLong ( $6 );',
'} else if (PyFloat_CheckExact( $3 )) {',
'temp[$2] = PyFloat_FromDouble((double)$10 - PyFloat_AS_DOUBLE($3));',
'} else { $7 :;',
'if ((temp[$1] = PyInt_FromSsize_t ( $10 )) == 0) goto $0;',
'if ((temp[$2] = PyNumber_Subtract ( temp[$1] , $3 )) == 0) goto $0;',
'CLEARTEMP($1);',
'}'), v2)
return True
if TxMatch(o, i, ('if ((temp[$1] = PyInt_FromSsize_t ( $10 )) == 0) goto $0;',
'if (PyInt_CheckExact( $3 )) {',
'$4 = PyInt_AS_LONG ( temp[$1] );',
'$5 = PyInt_AS_LONG ( $3 );',
'$6 = $4 - $5;',
'if (( $6 ^ $4 ) < 0 && ( $6 ^~ $5 ) < 0) goto $7 ;',
'temp[$2] = PyInt_FromLong ( $6 );',
'} else { $7 :;',
'if ((temp[$2] = PyNumber_Subtract ( temp[$1] , $3 )) == 0) goto $0;',
'}',
'CLEARTEMP($1);'),v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $3 )) {',
'$4 = $10;',
'$5 = PyInt_AS_LONG ( $3 );',
'$6 = $4 - $5;',
'if (( $6 ^ $4 ) < 0 && ( $6 ^~ $5 ) < 0) goto $7 ;',
'temp[$2] = PyInt_FromLong ( $6 );',
'} else { $7 :;',
'if ((temp[$1] = PyInt_FromSsize_t ( $10 )) == 0) goto $0;',
'if ((temp[$2] = PyNumber_Subtract ( temp[$1] , $3 )) == 0) goto $0;',
'CLEARTEMP($1);'
'}'), v2)
return True
if TxMatch(o, i, ('if ((temp[$0] = PyInt_FromSsize_t ( $1 )) == 0) goto $3;',
'if ((long_$4 = PyInt_AsLong ( temp[$0] )) == -1) goto $3;',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('long_$4 = $1;',), v2)
return True
if TxMatch(o, i, ('if ((temp[$19] = PyInt_FromSsize_t ( $17 )) == 0) goto $12;',
'if ($11) {',
'long_$18 = PyInt_AS_LONG ( temp[$19] );',
'if ((int_$3 = $14) == -1) goto $12;',
'temp[$0] = PyBool_FromLong(int_$3);',
'} else {',
'if ((temp[$2] = $15) == 0) goto $12;',
'if ((temp[$0] = $16) == 0) goto $12;',
'CLEARTEMP($2);',
'}',
'CLEARTEMP($19);',
'if ((int_$1 = PyObject_IsTrue ( temp[$0] )) == -1) goto $12;',
'CLEARTEMP($0);'), v2) and v2[19] != v2[0] and v2[19] != v2[2] and ('temp[' + v2[19] + ']') not in v2[14]:
TxRepl(o, i, ('if ($11) {',
'long_$18 = $17;',
'if ((int_$1 = $14) == -1) goto $12;',
'} else {',
'if ((temp[$19] = PyInt_FromSsize_t ( $17 )) == 0) goto $12;',
'if ((temp[$2] = $15) == 0) goto $12;',
'if ((temp[$0] = $16) == 0) goto $12;',
'CLEARTEMP($2);',
'CLEARTEMP($19);',
'if ((int_$1 = PyObject_IsTrue ( temp[$0] )) == -1) goto $12;',
'CLEARTEMP($0);',
'}'), v2)
return True
if TxMatch(o, i, ('if ((temp[$0] = PyInt_FromSsize_t ( $1 )) == 0) goto $2;',
'$3 = PyInt_AS_LONG ( temp[$0] );',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('$3 = $1;',), v2)
return True
if TxMatch(o, i, ('if ((temp[$0] = PyInt_FromSsize_t ( $8 )) == 0) goto $4;',
'if (PyInt_CheckExact( $2 )) {',
'$5 = PyInt_AS_LONG ( $2 );',
'$6 = PyInt_AS_LONG ( temp[$0] );',
'$7 = $5 + $6;',
'if (( $7 ^ $5 ) < 0 && ( $7 ^ $6 ) < 0) goto $3 ;',
'temp[$1] = PyInt_FromLong ( $7 );',
'} else { $3 :;',
'if ((temp[$1] = PyNumber_Add ( $2 , temp[$0] )) == 0) goto $4;',
'}',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $2 )) {',
'$5 = PyInt_AS_LONG ( $2 );',
'$6 = $8;',
'$7 = $5 + $6;',
'if (( $7 ^ $5 ) < 0 && ( $7 ^ $6 ) < 0) goto $3 ;',
'temp[$1] = PyInt_FromLong ( $7 );',
'} else { $3 :;',
'if ((temp[$0] = PyInt_FromSsize_t ( $8 )) == 0) goto $4;',
'if ((temp[$1] = PyNumber_Add ( $2 , temp[$0] )) == 0) goto $4;',
'CLEARTEMP($0);',
'}'), v2)
return True
if TxMatch(o, i, ('if ((temp[$0] = PyInt_FromSsize_t ( $2 )) == 0) goto $3;',
'$4 = PyInt_AS_LONG ( temp[$0] );',
'$5 = $6 - $4;',
'temp[$1] = PyInt_FromLong ( $5 );',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('$4 = $2;',
'$5 = $6 - $4;',
'temp[$1] = PyInt_FromLong ( $5 );'), v2)
return True
if TxMatch(o, i, ('if ((temp[$2] = PyInt_FromSsize_t ( $7 )) == 0) goto $6;',
'if (PyInt_CheckExact( $4 )) {',
'$8 = PyInt_AS_LONG ( $4 );',
'$9 = PyInt_AS_LONG ( temp[$2] );',
'$10 = $8 + $9;',
'if (( $10 ^ $8 ) < 0 && ( $10 ^ $9 ) < 0) goto $5 ;',
'temp[$3] = PyInt_FromLong ( $10 );',
'} else if (PyFloat_CheckExact( $4 )) {',
'temp[$3] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($4) + (double)PyInt_AS_LONG ( temp[$2] ));',
'} else { $5 :;',
'if ((temp[$3] = PyNumber_Add ( $4 , temp[$2] )) == 0) goto $6;',
'}',
'CLEARTEMP($2);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $4 )) {',
'$8 = PyInt_AS_LONG ( $4 );',
'$9 = $7;',
'$10 = $8 + $9;',
'if (( $10 ^ $8 ) < 0 && ( $10 ^ $9 ) < 0) goto $5 ;',
'temp[$3] = PyInt_FromLong ( $10 );',
'} else if (PyFloat_CheckExact( $4 )) {',
'temp[$3] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($4) + (double)$7);',
'} else { $5 :;',
'if ((temp[$2] = PyInt_FromSsize_t ( $7 )) == 0) goto $6;',
'if ((temp[$3] = PyNumber_Add ( $4 , temp[$2] )) == 0) goto $6;',
'CLEARTEMP($2);',
'}'), v2)
return True
if TxMatch(o, i, """if ((temp[$0] = PyInt_FromSsize_t ( $2 )) == 0) goto $5;
if ((temp[$1] = _PyEval_ApplySlice ( $4 , temp[$0] , NULL )) == 0) goto $5;
CLEARTEMP($0);""", v2):
TxRepl(o, i, ('if ((temp[$1] = PySequence_GetSlice ( $4 , $2 , PY_SSIZE_T_MAX )) == 0) goto $5;',), v2)
return True
if 'PyTuple_New' in o[i]:
if TxMatch(o, i, """
if ((temp[$1] = PyTuple_New ( 1 )) == 0) goto label_$2;
PyTuple_SET_ITEM ( temp[$1] , 0 , temp[$0] );
if ((temp[$0] = PyBool_Type.tp_new ( &PyBool_Type , temp[$1] , NULL )) == 0) goto label_$2;
CLEARTEMP($1);
int_$3 = PyObject_IsTrue ( temp[$0] );
""", v2):
TxRepl(o, i, ('if ((int_$3 = PyObject_IsTrue ( temp[$0] )) == -1) goto label_$2;',), v2)
return True
if TxMatch(o, i, """
if ((temp[$1] = PyTuple_New ( 1 )) == 0) goto label_$2;
PyTuple_SET_ITEM ( temp[$1] , 0 , temp[$0] );
if ((temp[$0] = PyBool_Type.tp_new ( &PyBool_Type , temp[$1] , NULL )) == 0) goto label_$2;
CLEARTEMP($1);
if ((int_$3 = PyObject_IsTrue ( temp[$0] )) == -1) goto label_$2;
""", v2):
TxRepl(o, i, ('if ((int_$3 = PyObject_IsTrue ( temp[$0] )) == -1) goto label_$2;',), v2)
return True
v2 = []
v3 = []
if 'PyDict_GetItem' in o[i]:
if TextMatch(o[i], ('if ((temp[', '*', '] = PyDict_GetItem', '*'), v2):
if i < (len(o) - 4) and TextMatch(o[i+1], ('Py_INCREF(temp[', v2[0], ']);'), []) and\
TextMatch(o[i+2], ('if ((temp[', '*', '] = PyList_GetItem ( temp[', v2[0], ']', '*'), v3) and\
TextMatch(o[i+3], ('Py_INCREF(temp[', v3[0], ']);'), []) and\
TextMatch(o[i+4], ('CLEARTEMP(', v2[0], ');'), []):
o[i+4] = 'temp[' + v2[0] + '] = 0;'
del o[i+1]
return True
if TxMatch(o, i, ('if ((temp[$1] = PyDict_GetItem ($2)) == 0) goto $3;',
'Py_INCREF(temp[$1]);',
'$4 = PyInt_AsSsize_t ( temp[$1] );',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if ((temp[$1] = PyDict_GetItem ($2)) == 0) goto $3;',
'$4 = PyInt_AsSsize_t ( temp[$1] );',
'temp[$1] = 0;'), v2)
return True
if TxMatch(o, i, ('if ((temp[$0] = PyDict_GetItem ($3)) == 0) goto $12;',
'if ((temp[$1] = PyList_GetItem ( temp[$0] , $4 )) == 0) goto $5;',
'Py_INCREF(temp[$1]);',
'if ((temp[$0] = PyDict_GetItem ($3)) == 0) goto $12;',
'if ((temp[$2] = PyList_GetItem ( temp[$0] , $4 )) == 0) goto $5;',
'Py_INCREF(temp[$2]);',
'temp[$0] = 0;'), v2):
TxRepl(o, i, ('if ((temp[$0] = PyDict_GetItem ($3)) == 0) goto $12;',
'if ((temp[$1] = PyList_GetItem ( temp[$0] , $4 )) == 0) goto $5;',
'Py_INCREF(temp[$1]);',
'temp[$2] = temp[$1];',
'Py_INCREF(temp[$2]);',
'temp[$0] = 0;'), v2)
return True
if TxMatch(o, i, ('if ((temp[$1] = PyDict_GetItem ( $6 , $5 )) == 0) goto $3;',
'Py_INCREF(temp[$1]);',
'if ((temp[$2] = PyObject_GetItem ( temp[$1] , $4 )) == 0) goto $3;',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if ((temp[$1] = PyDict_GetItem ( $6 , $5 )) == 0) goto $3;',
'if ((temp[$2] = PyObject_GetItem ( temp[$1] , $4 )) == 0) goto $3;',
'temp[$1] = 0;'), v2)
return True
if TxMatch(o, i, ('if ((temp[$1] = PyDict_GetItem ( $6 , $5 )) == 0) goto $3;',
'Py_INCREF(temp[$1]);',
'if ((Py_ssize_t_$7 = PyObject_Size ( temp[$1] )) == -1) goto $3;',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if ((temp[$1] = PyDict_GetItem ( $6 , $5 )) == 0) goto $3;',
'if ((Py_ssize_t_$7 = PyObject_Size ( temp[$1] )) == -1) goto $3;',
'temp[$1] = 0;'), v2)
return True
if TxMatch(o, i, ('if ((temp[$1] = PyDict_GetItem ( $3 , $4 )) == 0) goto $0;',
'Py_INCREF(temp[$1]);',
'if ((temp[$2] = PyObject_GetAttr ( temp[$1] , $5 )) == 0) goto $0;',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if ((temp[$1] = PyDict_GetItem ( $3 , $4 )) == 0) goto $0;',
'if ((temp[$2] = PyObject_GetAttr ( temp[$1] , $5 )) == 0) goto $0;',
'temp[$1] = 0;'), v2)
return True
if TxMatch(o, i, ('if ((temp[$0] = PyDict_GetItem ($5)) == 0) goto $3;',
'Py_INCREF(temp[$0]);',
'if ((int_$1 = PyObject_IsTrue ( temp[$0] )) == -1) goto $3;',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('if ((temp[$0] = PyDict_GetItem ($5)) == 0) goto $3;',
'if ((int_$1 = PyObject_IsTrue ( temp[$0] )) == -1) goto $3;',
'temp[$0] = 0;'), v2)
return True
if TxMatch(o, i, """
if ((temp[$0] = PyDict_GetItem ( $5 )) == 0) goto label_$2;
Py_INCREF(temp[$0]);
if (PyInt_CheckExact( $3 )) {
long_$4 = PyInt_AS_LONG ( $3 );
if ( long_$4 < 0) {
long_$4 += PyList_GET_SIZE(temp[$0]);
}
if ((temp[$1] = PyList_GetItem ( temp[$0] , long_$4 )) == 0) goto label_$2;
Py_INCREF(temp[$1]);
} else {
if ((temp[$1] = PyObject_GetItem ( temp[$0] , $3 )) == 0) goto label_$2;
}
CLEARTEMP($0);
LETLOCAL ( $10 , temp[$1] );
temp[$1] = 0;
""", v2):
TxRepl(o, i, """
if ((temp[$0] = PyDict_GetItem ( $5 )) == 0) goto label_$2;
if (PyInt_CheckExact( $3 )) {
long_$4 = PyInt_AS_LONG ( $3 );
if ( long_$4 < 0) {
long_$4 += PyList_GET_SIZE(temp[$0]);
}
if ((GETLOCAL($10) = PyList_GetItem ( temp[$0] , long_$4 )) == 0) goto label_$2;
Py_INCREF(GETLOCAL($10));
} else {
if ((GETLOCAL($10) = PyObject_GetItem ( temp[$0] , $3 )) == 0) goto label_$2;
}
temp[$0] = 0;
""", v2)
return True
if TxMatch(o, i, """
if ((temp[$0] = PyDict_GetItem ( $5 )) == 0) goto label_$2;
Py_INCREF(temp[$0]);
if (PyInt_CheckExact( $3 )) {
long_$4 = PyInt_AS_LONG ( $3 );
if ( long_$4 < 0) {
long_$4 += PyList_GET_SIZE(temp[$0]);
}
if ((temp[$1] = PyList_GetItem ( temp[$0] , long_$4 )) == 0) goto label_$2;
Py_INCREF(temp[$1]);
} else {
if ((temp[$1] = PyObject_GetItem ( temp[$0] , $3 )) == 0) goto label_$2;
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if ((temp[$0] = PyDict_GetItem ( $5 )) == 0) goto label_$2;
if (PyInt_CheckExact( $3 )) {
long_$4 = PyInt_AS_LONG ( $3 );
if ( long_$4 < 0) {
long_$4 += PyList_GET_SIZE(temp[$0]);
}
if ((temp[$1] = PyList_GetItem ( temp[$0] , long_$4 )) == 0) goto label_$2;
Py_INCREF(temp[$1]);
} else {
if ((temp[$1] = PyObject_GetItem ( temp[$0] , $3 )) == 0) goto label_$2;
}
temp[$0] = 0;
""", v2)
return True
if TxMatch(o, i, """
if ((temp[$2] = PyDict_GetItem ( $3 )) == 0) goto label_$0;
Py_INCREF(temp[$2]);
if ((int_$4 = PyObject_Not ( temp[$2] )) == -1) goto label_$0;
CLEARTEMP($2);
""", v2):
TxRepl(o, i, """
if ((temp[$2] = PyDict_GetItem ( $3 )) == 0) goto label_$0;
if ((int_$4 = PyObject_Not ( temp[$2] )) == -1) goto label_$0;
temp[$2] = 0;
""", v2)
return True
if 'PyObject_GetItem' in o[i]:
if TxMatch(o, i, ('if ((temp[$0] = PyObject_GetItem ( $6 , $7 )) == 0) goto $5;',
'if (PyInt_CheckExact( $7 ) && ($4 = PyInt_AS_LONG ( $7 )) < INT_MAX ) {',
'$4 = $4 + 1;',
'if ((temp[$2] = __c_BINARY_SUBSCR_Int ( $6 , $4 )) == 0) goto $5;',
'} else {',
'if ((temp[$1] = PyNumber_Add ( $7 , consts[$3] )) == 0) goto $5;',
'if ((temp[$2] = PyObject_GetItem ( $6 , temp[$1] )) == 0) goto $5;',
'CLEARTEMP($1);',
'}'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $7 ) && ($4 = PyInt_AS_LONG ( $7 )) < INT_MAX ) {',
'if ((temp[$0] = _c_BINARY_SUBSCR_Int ( $6 , $4 , $7 )) == 0) goto $5;',
'if ((temp[$2] = __c_BINARY_SUBSCR_Int ( $6 , $4 + 1 )) == 0) goto $5;',
'} else {',
'if ((temp[$0] = PyObject_GetItem ( $6 , $7 )) == 0) goto $5;',
'if ((temp[$1] = PyNumber_Add ( $7 , consts[$3] )) == 0) goto $5;',
'if ((temp[$2] = PyObject_GetItem ( $6 , temp[$1] )) == 0) goto $5;',
'CLEARTEMP($1);',
'}'), v2)
return True
if i+1 < len(o) and o[i+1].startswith('Py_INCREF(temp['):
if i < len(o) - 10:
v2 = []
v3 = []
if TextMatch(o[i], ('if ((temp[', '*', '] = PyList_GetItem', '*'), v2):
if TextMatch(o[i+1], ('Py_INCREF(temp[', v2[0], ']);'), []) and\
TextMatch(o[i+2], ('if (PyList_CheckExact( temp[', v2[0], '] )) {'), []) and\
TextMatch(o[i+3], ('if ( PyList_SetItem ( temp[', v2[0], '] , ', '*'), []) and\
TextMatch(o[i+4], ('} else {',), []) and\
TextMatch(o[i+5], ('if ( PyObject_SetItem ( temp[', v2[0], '] , ', '*'), []) and\
TextMatch(o[i+6], ('Py_CLEAR(temp[', '*', ']);'), v3) and\
TextMatch(o[i+7], ('}',), []) and\
TextMatch(o[i+8], ('CLEARTEMP(', v2[0],');'), []) and\
TextMatch(o[i+9], ('temp[', v3[0], '] = 0;'), []) and v3[0] != v2[0]:
o[i+8] = 'temp[' + v2[0] + '] = 0;'
del o[i+1]
return True
if TxMatch(o, i, ('if ((temp[$0] = Py$11_GetItem ( $1 , $2 )) == 0) goto $3;',
'Py_INCREF(temp[$0]);',
'$12',
'CLEARTEMP($0);'), v2):
typ = v2[11]
temp = v2[0]
n1, n2, n3 = v2[1], v2[2], v2[3]
action = v2[12]
if typ in ('Dict', 'List', 'Tuple') and '_Direct_' not in action and allowed_no_incref(action, temp, v2[3]):
TxRepl(o, i, ('if ((temp[$0] = Py$11_GetItem ( $1 , $2 )) == 0) goto $3;',
'$12',
'temp[$0] = 0;'), v2)
return True
## else:
## if '_Direct_' not in action and 'PyObject_GetIter' not in action:
## pprint(['!!!!!!'] + o[i:i+6])
elif TxMatch(o, i, ('if ((temp[$0] = Py$11_GetItem ( $1 , $2 )) == 0) goto $3;',
'Py_INCREF(temp[$0]);',
'CLEARTEMP($15);',
'$12',
'CLEARTEMP($0);'), v2) and v2[15] != v2[0] and ('temp['+v2[15]+']') in o[i]:
typ = v2[11]
temp = v2[0]
n1, n2, n3 = v2[1], v2[2], v2[3]
action = v2[12]
if typ in ('Dict', 'List', 'Tuple') and '_Direct_' not in action and allowed_no_incref(action, temp, v2[3]):
TxRepl(o, i, ('if ((temp[$0] = Py$11_GetItem ( $1 , $2 )) == 0) goto $3;',
'CLEARTEMP($15);',
'$12',
'temp[$0] = 0;'), v2)
return True
elif TxMatch(o, i, """
if ((temp[$0] = PyTuple_GetItem ( $15 , $16 )) == 0) goto label_$10;
Py_INCREF(temp[$0]);
if ((temp[$1] = Py$3_GetItem($2, temp[$0])) == 0) goto label_$12;
Py_INCREF(temp[$1]);
CLEARTEMP($0);""", v2):
TxRepl(o, i, """
if ((temp[$0] = PyTuple_GetItem ( $15 , $16 )) == 0) goto label_$10;
if ((temp[$1] = Py$3_GetItem($2, temp[$0])) == 0) goto label_$12;
Py_INCREF(temp[$1]);
temp[$0] = 0;""", v2)
return True
elif TxMatch(o, i, """
if ((temp[$0] = PyList_GetItem ( $15 , $16 )) == 0) goto label_$10;
Py_INCREF(temp[$0]);
if ((temp[$1] = Py$3_GetItem($2, temp[$0])) == 0) goto label_$12;
Py_INCREF(temp[$1]);
CLEARTEMP($0);""", v2):
TxRepl(o, i, """
if ((temp[$0] = PyList_GetItem ( $15 , $16 )) == 0) goto label_$10;
if ((temp[$1] = Py$3_GetItem($2, temp[$0])) == 0) goto label_$12;
Py_INCREF(temp[$1]);
temp[$0] = 0;""", v2)
return True
elif TxMatch(o, i, """
if ((temp[$0] = PyDict_GetItem ( $15 , $16 )) == 0) goto label_$10;
Py_INCREF(temp[$0]);
if ((temp[$1] = Py$3_GetItem($2, temp[$0])) == 0) goto label_$12;
Py_INCREF(temp[$1]);
CLEARTEMP($0);""", v2):
TxRepl(o, i, """
if ((temp[$0] = PyDict_GetItem ( $15 , $16 )) == 0) goto label_$10;
if ((temp[$1] = Py$3_GetItem($2, temp[$0])) == 0) goto label_$12;
Py_INCREF(temp[$1]);
temp[$0] = 0;""", v2)
return True
if i+2 < len(o) and o[i+2].startswith('Py_INCREF(temp['):
if TxMatch(o, i, """
if ((temp[$0] = $3) == 0) goto label_$2;
if ((temp[$1] = PyTuple_GetItem ( $4 , $5 )) == 0) goto label_$2;
Py_INCREF(temp[$1]);
if ((int_$6 = PySequence_Contains ( temp[$0] , temp[$1] )) == -1) goto label_$2;
CLEARTEMP($0);
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if ((temp[$0] = $3) == 0) goto label_$2;
if ((temp[$1] = PyTuple_GetItem ( $4 , $5 )) == 0) goto label_$2;
if ((int_$6 = PySequence_Contains ( temp[$0] , temp[$1] )) == -1) goto label_$2;
CLEARTEMP($0);
temp[$1] = 0;
""", v2)
return True
elif TxMatch(o, i, """
if ((temp[$0] = $3) == 0) goto label_$2;
if ((temp[$1] = PyList_GetItem ( $4 , $5 )) == 0) goto label_$2;
Py_INCREF(temp[$1]);
if ((int_$6 = PySequence_Contains ( temp[$0] , temp[$1] )) == -1) goto label_$2;
CLEARTEMP($0);
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if ((temp[$0] = $3) == 0) goto label_$2;
if ((temp[$1] = PyList_GetItem ( $4 , $5 )) == 0) goto label_$2;
if ((int_$6 = PySequence_Contains ( temp[$0] , temp[$1] )) == -1) goto label_$2;
CLEARTEMP($0);
temp[$1] = 0;
""", v2)
return True
elif TxMatch(o, i, """
if ((temp[$0] = $3) == 0) goto label_$2;
if ((temp[$1] = PyDict_GetItem ( $4 , $5 )) == 0) goto label_$2;
Py_INCREF(temp[$1]);
if ((int_$6 = PySequence_Contains ( temp[$0] , temp[$1] )) == -1) goto label_$2;
CLEARTEMP($0);
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if ((temp[$0] = $3) == 0) goto label_$2;
if ((temp[$1] = PyDict_GetItem ( $4 , $5 )) == 0) goto label_$2;
if ((int_$6 = PySequence_Contains ( temp[$0] , temp[$1] )) == -1) goto label_$2;
CLEARTEMP($0);
temp[$1] = 0;
""", v2)
elif TxMatch(o, i, """
if ((temp[$0] = $3) == 0) goto label_$2;
if ((temp[$1] = PyTuple_GetItem ( $4 , $5 )) == 0) goto label_$2;
Py_INCREF(temp[$1]);
if ((int_$6 = PyObject_RichCompareBool ( temp[$0] , temp[$1] , Py_$18 )) == -1) goto label_$2;
CLEARTEMP($0);
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if ((temp[$0] = $3) == 0) goto label_$2;
if ((temp[$1] = PyTuple_GetItem ( $4 , $5 )) == 0) goto label_$2;
if ((int_$6 = PyObject_RichCompareBool ( temp[$0] , temp[$1] , Py_$18 )) == -1) goto label_$2;
CLEARTEMP($0);
temp[$1] = 0;
""", v2)
return True
elif TxMatch(o, i, """
if ((temp[$0] = $3) == 0) goto label_$2;
if ((temp[$1] = PyList_GetItem ( $4 , $5 )) == 0) goto label_$2;
Py_INCREF(temp[$1]);
if ((int_$6 = PyObject_RichCompareBool ( temp[$0] , temp[$1] , Py_$18 )) == -1) goto label_$2;
CLEARTEMP($0);
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if ((temp[$0] = $3) == 0) goto label_$2;
if ((temp[$1] = PyList_GetItem ( $4 , $5 )) == 0) goto label_$2;
if ((int_$6 = PyObject_RichCompareBool ( temp[$0] , temp[$1] , Py_$18 )) == -1) goto label_$2;
CLEARTEMP($0);
temp[$1] = 0;
""", v2)
return True
elif TxMatch(o, i, """
if ((temp[$0] = $3) == 0) goto label_$2;
if ((temp[$1] = PyDict_GetItem ( $4 , $5 )) == 0) goto label_$2;
Py_INCREF(temp[$1]);
if ((int_$6 = PyObject_RichCompareBool ( temp[$0] , temp[$1] , Py_$18 )) == -1) goto label_$2;
CLEARTEMP($0);
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if ((temp[$0] = $3) == 0) goto label_$2;
if ((temp[$1] = PyDict_GetItem ( $4 , $5 )) == 0) goto label_$2;
if ((int_$6 = PyObject_RichCompareBool ( temp[$0] , temp[$1] , Py_$18 )) == -1) goto label_$2;
CLEARTEMP($0);
temp[$1] = 0;
""", v2)
return True
if 'PyFloat_FromDouble' in o[i] and TxMatch(o, i, """
if ((temp[$0] = PyFloat_FromDouble ( $2 )) == 0) goto $3;
Loc_double_$1 = PyFloat_AsDouble(temp[$0]);
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
Loc_double_$1 = $2;
""", v2)
return True
if i+3 <len(o) and o[i+3].startswith('LETLOCAL (') and TxMatch(o, i, """
if ((temp[$2] = $10) == 0) goto label_$11;
CLEARTEMP($1);
CLEARTEMP($0);
LETLOCAL ( $5 , temp[$2] );
temp[$2] = 0;
""", v2):
TxRepl(o, i, """
if ((GETLOCAL($5) = $10) == 0) goto label_$11;
CLEARTEMP($1);
CLEARTEMP($0);""", v2)
return True
if i+4 <len(o) and o[i+4].startswith('LETLOCAL (') and TxMatch(o, i, """
if ((temp[$2] = $10) == 0) goto label_$11;
CLEARTEMP($1);
CLEARTEMP($0);
CLEARTEMP($12);
LETLOCAL ( $5 , temp[$2] );
temp[$2] = 0;
""", v2):
TxRepl(o, i, """
if ((GETLOCAL($5) = $10) == 0) goto label_$11;
CLEARTEMP($1);
CLEARTEMP($0);
CLEARTEMP($12);
""", v2)
return True
if i+2 <len(o) and o[i+2].startswith('LETLOCAL (') and TxMatch(o, i, """
if ((temp[$2] = $10) == 0) goto label_$11;
CLEARTEMP($1);
LETLOCAL ( $5 , temp[$2] );
temp[$2] = 0;
""", v2):
TxRepl(o, i, """
if ((GETLOCAL($5) = $10) == 0) goto label_$11;
CLEARTEMP($1);
""", v2)
return True
if i+1 <len(o) and o[i+1].startswith('LETLOCAL (') and TxMatch(o, i, """
if ((temp[$0] = $10) == 0) goto label_$11;
LETLOCAL ( $5 , temp[$0] );
temp[$0] = 0;
""", v2):
TxRepl(o, i, """
if ((GETLOCAL($5) = $10) == 0) goto label_$11;
""", v2)
return True
if i+2 <len(o) and o[i+2].startswith('LETLOCAL ('):
if TxMatch(o, i, """
if ((temp[$0] = $1) == 0) goto label_$10;
Py_INCREF(temp[$0]);
LETLOCAL ( $5 , temp[$0] );
temp[$0] = 0;
""", v2):
TxRepl(o, i, """
if ((GETLOCAL($5) = $1) == 0) goto label_$10;
Py_INCREF(GETLOCAL($5));
""", v2)
return True
if TxMatch(o, i, """
if ((temp[$1] = $11) == 0) goto label_$10;
Py_INCREF(temp[$1]);
LETLOCAL ( $5 , temp[$1] );
if ((temp[$1] = $12) == 0) goto label_$10;
""", v2):
TxRepl(o, i, """
if ((GETLOCAL($5) = $11) == 0) goto label_$10;
Py_INCREF(GETLOCAL($5));
if ((temp[$1] = $12) == 0) goto label_$10;
""", v2)
return True
if i+3 <len(o) and o[i+3].startswith('LETLOCAL (') and TxMatch(o, i, """
if ((temp[$0] = $6) == 0) goto label_$10;
if ((temp[$1] = $7) == 0) goto label_$10;
temp[$0] = 0;
LETLOCAL ( $5 , temp[$1] );
temp[$1] = 0;
""", v2):
TxRepl(o, i, """
if ((temp[$0] = $6) == 0) goto label_$10;
if ((GETLOCAL($5) = $7) == 0) goto label_$10;
temp[$0] = 0;
""", v2)
return True
if 'PyInt_FromLong' in o[i]:
if TxMatch(o, i, ('if ((temp[$0] = PyInt_FromLong ($1)) == 0) goto label_$2;',), v2):
TxRepl(o, i, ('temp[$0] = PyInt_FromLong ($1);',), v2)
return True
if 'PyInt_FromSsize_t' in o[i]:
if TxMatch(o, i, """
if ((temp[$4] = PyInt_FromSsize_t ( $2 )) == 0) goto $1;
if (PyInt_CheckExact( temp[$3] )) {
long_$7 = PyInt_AS_LONG ( temp[$3] );
long_$8 = PyInt_AS_LONG ( temp[$4] );
long_$9 = long_$7 + long_$8;
if (( long_$9 ^ long_$7 ) < 0 && ( long_$9 ^ long_$8 ) < 0) goto $0 ;
temp[$5] = PyInt_FromLong ( long_$9 );
} else if (PyFloat_CheckExact( temp[$3] )) {
temp[$5] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$3]) + (double)PyInt_AS_LONG ( temp[$4] ));
} else { $0 :;
if ((temp[$5] = PyNumber_Add ( temp[$3] , temp[$4] )) == 0) goto $1;
}
""", v2):
TxRepl(o, i, """
if ((temp[$4] = PyInt_FromSsize_t ( $2 )) == 0) goto $1;
if (PyInt_CheckExact( temp[$3] )) {
long_$7 = PyInt_AS_LONG ( temp[$3] );
long_$8 = $2;
long_$9 = long_$7 + long_$8;
if (( long_$9 ^ long_$7 ) < 0 && ( long_$9 ^ long_$8 ) < 0) goto $0 ;
temp[$5] = PyInt_FromLong ( long_$9 );
} else if (PyFloat_CheckExact( temp[$3] )) {
temp[$5] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$3]) + (double)$2);
} else { $0 :;
if ((temp[$5] = PyNumber_Add ( temp[$3] , temp[$4] )) == 0) goto $1;
}
""", v2)
return True
if TxMatch(o, i, """
if ((temp[$0] = PyInt_FromSsize_t ( $14 )) == 0) goto $4;
if (_self_dict && (temp[$1] = $5) != 0) {
Py_INCREF(temp[$1]);
} else {
if ((temp[$1] = $6) == 0) goto $4;
}
if (PyInt_CheckExact( temp[$1] )) {
$7 = PyInt_AS_LONG ( temp[$0] );
$8 = PyInt_AS_LONG ( temp[$1] );
$11 = $7 $9 $8;
if ($10) goto $3 ;
temp[$2] = PyInt_FromLong ( $11 );
} else if (PyFloat_CheckExact( temp[$1] )) {
temp[$2] = PyFloat_FromDouble((double)PyInt_AS_LONG ( temp[$0] ) - PyFloat_AS_DOUBLE(temp[$1]));
} else { $3 :;
if ((temp[$2] = PyNumber_$12) == 0) goto $4;
}
CLEARTEMP($0);
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if (_self_dict && (temp[$1] = $5) != 0) {
Py_INCREF(temp[$1]);
} else {
if ((temp[$1] = $6) == 0) goto $4;
}
if (PyInt_CheckExact( temp[$1] )) {
$7 = $14;
$8 = PyInt_AS_LONG ( temp[$1] );
$11 = $7 $9 $8;
if ($10) goto $3 ;
temp[$2] = PyInt_FromLong ( $11 );
} else if (PyFloat_CheckExact( temp[$1] )) {
temp[$2] = PyFloat_FromDouble((double)($14) - PyFloat_AS_DOUBLE(temp[$1]));
} else { $3 :;
if ((temp[$0] = PyInt_FromSsize_t ( $14 )) == 0) goto $4;
if ((temp[$2] = PyNumber_$12) == 0) goto $4;
CLEARTEMP($0);
}
CLEARTEMP($1);
""", v2)
return True
if TxMatch(o, i, """
if ((temp[$0] = PyInt_FromSsize_t ( $14 )) == 0) goto $4;
if ((temp[$1] = $5) == 0) goto $4;
Py_INCREF(temp[$1]);
if (PyInt_CheckExact( temp[$1] )) {
$7 = PyInt_AS_LONG ( temp[$0] );
$8 = PyInt_AS_LONG ( temp[$1] );
$11 = $7 $9 $8;
if ($10) goto $3 ;
temp[$2] = PyInt_FromLong ( $11 );
} else if (PyFloat_CheckExact( temp[$1] )) {
temp[$2] = PyFloat_FromDouble((double)PyInt_AS_LONG ( temp[$0] ) - PyFloat_AS_DOUBLE(temp[$1]));
} else { $3 :;
if ((temp[$2] = PyNumber_$12) == 0) goto $4;
}
CLEARTEMP($0);
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if ((temp[$1] = $5) == 0) goto $4;
if (PyInt_CheckExact( temp[$1] )) {
$7 = $14;
$8 = PyInt_AS_LONG ( temp[$1] );
$11 = $7 $9 $8;
if ($10) goto $3 ;
temp[$2] = PyInt_FromLong ( $11 );
} else if (PyFloat_CheckExact( temp[$1] )) {
temp[$2] = PyFloat_FromDouble((double)($14) - PyFloat_AS_DOUBLE(temp[$1]));
} else { $3 :;
if ((temp[$0] = PyInt_FromSsize_t ( $14 )) == 0) goto $4;
if ((temp[$2] = PyNumber_$12) == 0) goto $4;
CLEARTEMP($0);
}
CLEARTEMP($1);
""", v2)
return True
if TxMatch(o, i, """
if ((temp[$3] = PyInt_FromSsize_t ( $1 )) == 0) goto $0;
long_$13 = PyInt_AS_LONG ( temp[$3] );
temp[$4] = PyInt_FromLong ( long_$13 $14 );
CLEARTEMP($3);
""", v2):
TxRepl(o, i, """
temp[$4] = PyInt_FromLong ( ($1) $14 );
""", v2)
return True
if TxMatch(o, i, """
if ((temp[$1] = PyInt_FromSsize_t ( $5 )) == 0) goto $3;
if (PyInt_CheckExact( temp[$0] )) {
long_$14 = PyInt_AS_LONG ( temp[$0] );
long_$15 = $5;
long_$13 = long_$14 $16 long_$15;
if ($18) goto $4 ;
temp[$2] = PyInt_FromLong ( long_$13 );
} else if (PyFloat_CheckExact( temp[$0] )) {
temp[$2] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$0]) $16 (double)$5);
} else { $4 :;
if ((temp[$2] = PyNumber_$17 ( temp[$0] , temp[$1] )) == 0) goto $3;
}
CLEARTEMP($0);
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( temp[$0] )) {
long_$14 = PyInt_AS_LONG ( temp[$0] );
long_$15 = $5;
long_$13 = long_$14 $16 long_$15;
if ($18) goto $4 ;
temp[$2] = PyInt_FromLong ( long_$13 );
} else if (PyFloat_CheckExact( temp[$0] )) {
temp[$2] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$0]) $16 (double)$5);
} else { $4 :;
if ((temp[$1] = PyInt_FromSsize_t ( $5 )) == 0) goto $3;
if ((temp[$2] = PyNumber_$17 ( temp[$0] , temp[$1] )) == 0) goto $3;
CLEARTEMP($1);
}
CLEARTEMP($0);
""", v2)
return True
## if '_GET_ITEM' in o[i]:
## if TxMatch(o, i, """
## if ((temp[$0] = _GET_ITEM_$4 ( $2 )) == 0) goto label_$3;
## if ((temp[$1] = _GET_ITEM_$5 ( temp[$0] )) == 0) goto label_$3;
## CLEARTEMP($0);
## long_$6 = PyInt_AS_LONG ( temp[$1] );
## CLEARTEMP($1);
## if ( $7 ) {
## if ((temp[$0] = _GET_ITEM_$4 ( $2 )) == 0) goto label_$3;
## if ((temp[$1] = _GET_ITEM_$5 ( temp[$0] )) == 0) goto label_$3;
## CLEARTEMP($0);
## $8 PyInt_AS_LONG ( temp[$1] ) $9;
## CLEARTEMP($1);
## """, v2):
## _s = 'long_' + v2[6]
## if _s not in v2[8] and _s not in v2[9]:
## TxRepl(o, i, """
## if ((temp[$0] = _GET_ITEM_$4 ( $2 )) == 0) goto label_$3;
## if ((temp[$1] = _GET_ITEM_$5 ( temp[$0] )) == 0) goto label_$3;
## CLEARTEMP($0);
## long_$6 = PyInt_AS_LONG ( temp[$1] );
## CLEARTEMP($1);
## if ( $7 ) {
## $8 long_$6 $9;
## """, v2)
## return True
if 'PyObject_Type' in o[i]:
if TxMatch(o, i, """
if ((temp[$0] = PyObject_Type ( $11 )) == 0) goto label_$10;
int_$15 = temp[$0] == loaded_builtin[$14];
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
int_$15 = Py_TYPE ( $11 ) == loaded_builtin[$14];
""", v2)
return True
if i+1 < len(o) and 'PyInt_FromSsize_t' in o[i+1]:
if TxMatch(o, i, ('if (($7 = PyObject_Size ( $3 )) == -1) goto $5;',
'if ((temp[$1] = PyInt_FromSsize_t ( $7 )) == 0) goto $5;',
'if (PyInt_CheckExact( $4 )) {',
'$8 = PyInt_AS_LONG ( temp[$1] );',
'$9 = PyInt_AS_LONG ( $4 );',
'$10 = $8 - $9;',
'if (( $10 ^ $8 ) < 0 && ( $10 ^~ $9 ) < 0) goto $6 ;',
'temp[$2] = PyInt_FromLong ( $10 );',
'} else if (PyFloat_CheckExact( $4 )) {',
'temp[$2] = PyFloat_FromDouble((double)PyInt_AS_LONG ( temp[$1] ) - PyFloat_AS_DOUBLE($4));',
'} else { $6 :;',
'if ((temp[$2] = PyNumber_Subtract ( temp[$1] , $4 )) == 0) goto $5;',
'}',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if (($8 = PyObject_Size ( $3 )) == -1) goto $5;',
'if (PyInt_CheckExact( $4 )) {',
'$9 = PyInt_AS_LONG ( $4 );',
'$10 = $8 - $9;',
'if (( $10 ^ $8 ) < 0 && ( $10 ^~ $9 ) < 0) goto $6 ;',
'temp[$2] = PyInt_FromLong ( $10 );',
'} else { $6 :;',
'if ((temp[$1] = PyInt_FromSsize_t ( $8 )) == 0) goto $5;',
'if ((temp[$2] = PyNumber_Subtract ( temp[$1] , $4 )) == 0) goto $5;',
'CLEARTEMP($1);',
'}'), v2)
return True
if TxMatch(o, i, ('if (($7 = PyObject_Size ( $3 )) == -1) goto $5;',
'if ((temp[$1] = PyInt_FromSsize_t ( $7 )) == 0) goto $5;',
'if (PyInt_CheckExact( $4 )) {',
'$8 = PyInt_AS_LONG ( temp[$1] );',
'$9 = PyInt_AS_LONG ( $4 );',
'$10 = $8 - $9;',
'if (( $10 ^ $8 ) < 0 && ( $10 ^~ $9 ) < 0) goto $6 ;',
'temp[$2] = PyInt_FromLong ( $10 );',
'} else { $6 :;',
'if ((temp[$2] = PyNumber_Subtract ( temp[$1] , $4 )) == 0) goto $5;',
'}',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if (($8 = PyObject_Size ( $3 )) == -1) goto $5;',
'if (PyInt_CheckExact( $4 )) {',
'$9 = PyInt_AS_LONG ( $4 );',
'$10 = $8 - $9;',
'if (( $10 ^ $8 ) < 0 && ( $10 ^~ $9 ) < 0) goto $6 ;',
'temp[$2] = PyInt_FromLong ( $10 );',
'} else { $6 :;',
'if ((temp[$1] = PyInt_FromSsize_t ( $8 )) == 0) goto $5;',
'if ((temp[$2] = PyNumber_Subtract ( temp[$1] , $4 )) == 0) goto $5;',
'CLEARTEMP($1);',
'}'), v2)
return True
if TxMatch(o, i, ('if (($4 = $3) == -1) goto $2;',
'if ((temp[$0] = PyInt_FromSsize_t ( $4 )) == 0) goto $2;',
'if (PyInt_CheckExact( $5 )) {',
'$7 = PyInt_AS_LONG ( $5 );',
'$8 = PyInt_AS_LONG ( temp[$0] );',
'$9 = $7 + $8;',
'if (( $9 ^ $7 ) < 0 && ( $9 ^ $8 ) < 0) goto $6 ;',
'temp[$1] = PyInt_FromLong ( $9 );',
'} else if (PyFloat_CheckExact( $5 )) {',
'temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($5) + (double)PyInt_AS_LONG ( temp[$0] ));',
'} else { $6 :;',
'if ((temp[$1] = PyNumber_Add ( $5 , temp[$0] )) == 0) goto $2;',
'}',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('if (($4 = $3) == -1) goto $2;',
'if (PyInt_CheckExact( $5 )) {',
'$7 = PyInt_AS_LONG ( $5 );',
'$8 = $4;',
'$9 = $7 + $8;',
'if (( $9 ^ $7 ) < 0 && ( $9 ^ $8 ) < 0) goto $6 ;',
'temp[$1] = PyInt_FromLong ( $9 );',
'} else { $6 :;',
'if ((temp[$0] = PyInt_FromSsize_t ( $4 )) == 0) goto $2;',
'if ((temp[$1] = PyNumber_Add ( $5 , temp[$0] )) == 0) goto $2;',
'CLEARTEMP($0);',
'}'), v2)
return True
if TxMatch(o, i, ('if (($4 = $3) == -1) goto $2;',
'if ((temp[$0] = PyInt_FromSsize_t ( $4 )) == 0) goto $2;',
'if (PyInt_CheckExact( $5 )) {',
'$7 = PyInt_AS_LONG ( $5 );',
'$8 = PyInt_AS_LONG ( temp[$0] );',
'$9 = $7 + $8;',
'if (( $9 ^ $7 ) < 0 && ( $9 ^ $8 ) < 0) goto $6 ;',
'temp[$1] = PyInt_FromLong ( $9 );',
'} else { $6 :;',
'if ((temp[$1] = PyNumber_Add ( $5 , temp[$0] )) == 0) goto $2;',
'}',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('if (($4 = $3) == -1) goto $2;',
'if (PyInt_CheckExact( $5 )) {',
'$7 = PyInt_AS_LONG ( $5 );',
'$8 = $4;',
'$9 = $7 + $8;',
'if (( $9 ^ $7 ) < 0 && ( $9 ^ $8 ) < 0) goto $6 ;',
'temp[$1] = PyInt_FromLong ( $9 );',
'} else { $6 :;',
'if ((temp[$0] = PyInt_FromSsize_t ( $4 )) == 0) goto $2;',
'if ((temp[$1] = PyNumber_Add ( $5 , temp[$0] )) == 0) goto $2;',
'CLEARTEMP($0);',
'}'), v2)
return True
if TxMatch(o, i, """
if ((Py_ssize_t_$1 = $2) == -1) goto $7;
if ((temp[$11] = PyInt_FromSsize_t ( Py_ssize_t_$1 )) == 0) goto $7;
if (PyInt_CheckExact( temp[$10] )) {
temp[$12] = PyInt_FromLong ( PyInt_AS_LONG ( temp[$10] ) / PyInt_AS_LONG ( temp[$11] ));
} else {
if ((temp[$12] = PyNumber_Divide ( temp[$10] , temp[$11] )) == 0) goto $7;
}
CLEARTEMP($10);
CLEARTEMP($11);
""", v2):
TxRepl(o, i, """
if ((Py_ssize_t_$1 = $2) == -1) goto $7;
if (PyInt_CheckExact( temp[$10] )) {
temp[$12] = PyInt_FromLong ( PyInt_AS_LONG ( temp[$10] ) / (Py_ssize_t_$1));
} else {
if ((temp[$11] = PyInt_FromSsize_t ( Py_ssize_t_$1 )) == 0) goto $7;
if ((temp[$12] = PyNumber_Divide ( temp[$10] , temp[$11] )) == 0) goto $7;
CLEARTEMP($11);
}
CLEARTEMP($10);
""", v2)
return True
if '_PyEval_AssignSlice' in o[i]:
if TxMatch(o, i, ('if ( _PyEval_AssignSlice ( $1 , NULL , NULL , temp[$2] ) == -1) goto $3;',), v2):
TxRepl(o, i, ('if ( PySequence_SetSlice ( $1 , 0 , PY_SSIZE_T_MAX , temp[$2] ) == -1) goto $3;',), v2)
return True
if TxMatch(o, i, ('if ( _PyEval_AssignSlice ( $1 , NULL , NULL , GETLOCAL($2) ) == -1) goto $3;',), v2):
TxRepl(o, i, ('if ( PySequence_SetSlice ( $1 , 0 , PY_SSIZE_T_MAX , GETLOCAL($2) ) == -1) goto $3;',), v2)
return True
if TxMatch(o, i, ('if ( _PyEval_AssignSlice ( $1 , NULL , NULL , NULL ) == -1) goto $3;',), v2):
TxRepl(o, i, ('if ( PySequence_DelSlice ( $1 , 0 , PY_SSIZE_T_MAX ) == -1) goto $3;',), v2)
return True
if o[i].endswith(' ;'):
if TxMatch(o, i, """
if ($6) goto label_$19 ;
temp[$2] = PyInt_FromLong ( long_$18 );
if (1) {
} else { label_$19 :;
>0
if ((temp[$2] = PyNumber_$5) == 0) goto label_$0;
<1
}
if (PyInt_CheckExact( temp[$2] ) && (long_$4 = PyInt_AS_LONG ( temp[$2] )) < $7 ) {
temp[$3] = PyInt_FromLong ( long_$4 + $8 );
} else {
>2
}
CLEARTEMP($2);
""", v2):
TxRepl(o, i, """
if (!($6) && long_$18 < $7 ) {
temp[$3] = PyInt_FromLong ( long_$18 + $8 );
} else {
>0
if ((temp[$2] = PyNumber_$5) == 0) goto label_$0;
<1
>2
CLEARTEMP($2);
}
""", v2)
return True
if TxMatch(o, i, """
if ($11) goto label_$5 ;
temp[$0] = PyInt_FromLong ( $3 );
if (0) { label_$5 :;
temp[$2] = PyInt_FromLong ($4);
if ((temp[$0] = PyNumber_$6) == 0) goto label_$9;
CLEARTEMP($2);
}
if ((temp[$2] = PyObject_GetItem ( GETLOCAL(data) , temp[$0] )) == 0) goto label_$9;
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if ($11) goto label_$5 ;
temp[$0] = PyInt_FromLong ( $3 );
if ((temp[$2] = PyObject_GetItem ( GETLOCAL(data) , temp[$0] )) == 0) goto label_$9;
CLEARTEMP($0);
if (0) { label_$5 :;
temp[$2] = PyInt_FromLong ($4);
if ((temp[$0] = PyNumber_$6) == 0) goto label_$9;
CLEARTEMP($2);
if ((temp[$2] = PyObject_GetItem ( GETLOCAL(data) , temp[$0] )) == 0) goto label_$9;
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
if ($10) goto $11 ;
temp[$0] = PyInt_FromLong ( $12 );
if (1) {
} else { $11 :;
if ((temp[$0] = PyNumber_$13) == 0) goto $14;
}
if ((temp[$2] = PyObject_GetItem ( $15 , temp[$0] )) == 0) goto $14;
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if ($10) {
if ((temp[$0] = PyNumber_$13) == 0) goto $14;
if ((temp[$2] = PyObject_GetItem ( $15 , temp[$0] )) == 0) goto $14;
CLEARTEMP($0);
} else {
temp[$0] = PyInt_FromLong ( $12 );
if ((temp[$2] = PyObject_GetItem ( $15 , temp[$0] )) == 0) goto $14;
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
if ($10) goto label_$8 ;
temp[$0] = PyInt_FromLong ( long_$3 );
if (1) {
} else { label_$8 :;
if ((temp[$0] = PyNumber_$17) == 0) goto label_$11;
}
CLEARTEMP($1);
CLEARTEMP($2);
if (PyInt_CheckExact( temp[$0] ) && PyInt_CheckExact( $12 )) {
long_$14 = PyInt_AS_LONG ( temp[$0] );
long_$16 = PyInt_AS_LONG ( $12 );
long_$13 = long_4 + long_6;
if (( long_$13 ^ long_$14 ) < 0 && ( long_$13 ^ long_$16 ) < 0) goto label_$9 ;
temp[$10] = PyInt_FromLong ( long_$13 );
} else { label_$9 :;
if ((temp[$10] = PyNumber_$18Add ( temp[$0] , $12 )) == 0) goto label_$11;
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (!($10) && PyInt_CheckExact( $12 )) {
CLEARTEMP($1);
CLEARTEMP($2);
long_$14 = long_$3;
long_$16 = PyInt_AS_LONG ( $12 );
long_$13 = long_4 + long_6;
if (( long_$13 ^ long_$14 ) < 0 && ( long_$13 ^ long_$16 ) < 0) goto label_$9 ;
temp[$10] = PyInt_FromLong ( long_$13 );
} else { label_$9 :;
if ((temp[$0] = PyNumber_$17) == 0) goto label_$11;
CLEARTEMP($1);
CLEARTEMP($2);
if ((temp[$10] = PyNumber_$18Add ( temp[$0] , $12 )) == 0) goto label_$11;
CLEARTEMP($0);
}
""", v2)
return True
if 'PyObject_SetAttr' in o[i]:
if TxMatch(o, i, """
if ( PyObject_SetAttr ( $3 , $4 , temp[$1] ) == -1) goto label_$5;
CLEARTEMP($1);
if ((temp[$1] = PyObject_GetAttr ( $3 , $4 )) == 0) goto label_$5;
""", v2):
TxRepl(o, i, """
if ( PyObject_SetAttr ( $3 , $4 , temp[$1] ) == -1) goto label_$5;
""", v2)
return True
if TxMatch(o, i, """
if ( PyObject_SetAttr ( $3 , $4 , temp[$1] ) == -1) goto label_$5;
CLEARTEMP($1);
if ((temp[$0] = PyObject_GetAttr ( $3 , $4 )) == 0) goto label_$5;
""", v2) and v2[0] != v2[1]:
## print 'Replace temp to temp', i
TxRepl(o, i, """
if ( PyObject_SetAttr ( $3 , $4 , temp[$1] ) == -1) goto label_$5;
temp[$0] = temp[$1];
temp[$1] = 0;
""", v2)
return True
return False
def end_call_1(action, nms, arg, label):
if arg not in action:
return False
for nm in nms:
if nm not in action:
continue
if 'goto' not in action:
if action.endswith(' = ' + nm + '(' + arg + ');'):
return True
if action.endswith(' = ' + nm + '( ' + arg + ' );'):
return True
if action.endswith(' = ' + nm + ' ( ' + arg + ' );'):
return True
else:
if action.startswith('if ('):
if (' = ' + nm + ' ( ' + arg + ' )) == ') in action and action.endswith('goto ' + label + ';'):
return True
if (' = ' + nm + '( ' + arg + ' )) == ') in action and action.endswith('goto ' + label + ';'):
return True
if (' = ' + nm + '(' + arg + ')) == ') in action and action.endswith('goto ' + label + ';'):
return True
if (' = ' + nm + ' (' + arg + ')) == ') in action and action.endswith('goto ' + label + ';'):
return True
return False
def end_call_first_of_two(action, nms, arg, label):
if arg not in action:
return False
for nm in nms:
if nm not in action:
continue
if 'goto' not in action:
if TextMatch(action, ('*', ' = ' + nm + '(' + arg + ',', '*', ');'), []):
return True
if TextMatch(action, ('*', ' = ' + nm + '(' + arg + ' ,', '*', ');'), []):
return True
if TextMatch(action, ('*', ' = ' + nm + '( ' + arg + ',', '*', ');'), []):
return True
if TextMatch(action, ('*', ' = ' + nm + '( ' + arg + ' ,', '*', ');'), []):
return True
if TextMatch(action, ('*', ' = ' + nm + ' ( ' + arg + ',', '*', ');'), []):
return True
if TextMatch(action, ('*', ' = ' + nm + ' ( ' + arg + ' ,', '*', ');'), []):
return True
else:
if action.startswith('if ('):
if TextMatch(action, ('if ((', '*', ' = ' + nm + ' ( ', arg, ' ,', '*', ') goto ', label, ';'), []):
return True
if TextMatch(action, ('if ((', '*', ' = ' + nm + '( ', arg, ' ,', '*', ') goto ', label, ';'), []):
return True
if TextMatch(action, ('if ((', '*', ' = ' + nm + ' ( ', arg, ',', '*', ') goto ', label, ';'), []):
return True
if TextMatch(action, ('if ((', '*', ' = ' + nm + '( ', arg, ',', '*', ') goto ', label, ';'), []):
return True
if TextMatch(action, ('if ((', '*', ' = ' + nm + '(', arg, ' ,', '*', ') goto ', label, ';'), []):
return True
if TextMatch(action, ('if ((', '*', ' = ' + nm + ' (', arg, ',', '*', ') goto ', label, ';'), []):
return True
return False
def end_call_second_of_two(action, nms, arg, label):
if arg not in action:
return False
for nm in nms:
if nm not in action:
continue
if 'goto' not in action:
if TextMatch(action, ('*', ' = ' + nm + '(', '*', ',', arg, ');'), []):
return True
if TextMatch(action, ('*', ' = ' + nm + '(', '*', ', ', arg, ');'), []):
return True
if TextMatch(action, ('*', ' = ' + nm + '(', '*', ', ', arg, ' );'), []):
return True
if TextMatch(action, ('*', ' = ' + nm + ' (', '*', ',', arg, ');'), []):
return True
if TextMatch(action, ('*', ' = ' + nm + ' (', '*', ', ', arg, ');'), []):
return True
if TextMatch(action, ('*', ' = ' + nm + ' (', '*', ', ', arg, ' );'), []):
return True
else:
if action.startswith('if ('):
if TextMatch(action, ('if ((', '*', ' = ' + nm + '(', '*', ',', arg, ')) == ', '*', ';'), []):
return True
if TextMatch(action, ('if ((', '*', ' = ' + nm + ' (', '*', ',', arg, ')) == ', '*', ';'), []):
return True
if TextMatch(action, ('if ((', '*', ' = ' + nm + '(', '*', ', ', arg, ')) == ', '*', ';'), []):
return True
if TextMatch(action, ('if ((', '*', ' = ' + nm + ' (', '*', ', ', arg, ')) == ', '*', ';'), []):
return True
if TextMatch(action, ('if ((', '*', ' = ' + nm + '(', '*', ',', arg, ' )) == ', '*', ';'), []):
return True
if TextMatch(action, ('if ((', '*', ' = ' + nm + ' (', '*', ',', arg, ' )) == ', '*', ';'), []):
return True
if TextMatch(action, ('if ((', '*', ' = ' + nm + '(', '*', ', ', arg, ' )) == ', '*', ';'), []):
return True
if TextMatch(action, ('if ((', '*', ' = ' + nm + ' (', '*', ', ', arg, ' )) == ', '*', ';'), []):
return True
return False
def allowed_no_incref(action, temp, label):
t_temp = 'temp[' + temp + ']'
if end_call_1(action, ('PyLong_CheckExact', 'PyTuple_CheckExact',
'PyBool_Check', 'PyList_CheckExact',
'PyGen_CheckExact', 'PyBytes_CheckExact',
'PyComplex_CheckExact', 'PyByteArray_CheckExact',
'PyFile_CheckExact', 'PySet_CheckExact',
'PyAnySet_CheckExact', 'PyDict_CheckExact',
'PyString_CheckExact', 'PyDate_CheckExact',
'PyTime_CheckExact', 'PyDateTime_CheckExact',
'PyType_CheckExact', 'PyUnicode_CheckExact',
'PyModule_CheckExact', 'PyInt_CheckExact',
'PyFloat_CheckExact',
'PyTuple_GET_SIZE', 'PyList_GET_SIZE',
'PyObject_Size', 'PyObject_Str',
'PyNumber_Int'), t_temp, label):
return True
if end_call_first_of_two(action, ('_c_BINARY_SUBSCR_Int', 'PyObject_GetItem',
'c_Py_EQ_String', 'c_Py_NE_String',
'c_Py_GT_Int', 'c_Py_GE_Int',
'c_Py_LT_Int', 'c_Py_LE_Int',
'c_Py_EQ_Int', 'c_Py_NE_Int',
'PySequence_GetSlice', 'PyObject_GetAttr',
'PySequence_Contains', 'PyDict_Contains',
'PySet_Contains'), t_temp, label):
return True
if end_call_second_of_two(action,
('PySequence_Contains', 'PyDict_Contains', 'PySet_Contains'),
t_temp, label):
return True
if ( 'STR_CONCAT_N ( ' in action or 'STR_CONCAT3 ( ' in action or 'STR_CONCAT2 ( ' in action ) and t_temp in action:
return True
if (' = ' + t_temp + ' == calculated_const[') in action or (' = ' + t_temp + ' != calculated_const[') in action:
return True
return False
op_to_oper = {'Py_EQ':' == ', 'Py_NE':' != ', 'Py_LT':' < ', \
'Py_LE':' <= ', 'Py_GT':' > ', 'Py_GE':' >= '}
def tune_if_sk(o, i):
v2 = []
if o[i] == 'if (1) {':
if TxMatch(o, i, ('if (1) {',
'$1;'), v2) and not ':' in o[i+1] and not '}' in o[i+1] and not '{' in o[i+1]:
TxRepl(o, i, ('$1;', 'if (1) {'), v2)
return True
if TxMatch(o, i, ('if (1) {',
'} else {'), v2):
TxRepl(o, i, ('if (0) {',), v2)
return True
if TxMatch(o, i, ('if (1) {',
'long_$6 = PyInt_AS_LONG ( $1 );',
'long_$7 = PyInt_AS_LONG ( $2 );',
'long_$8 = long_$6 + long_$7;',
'if (( long_$8 ^ long_$6 ) < 0 && ( long_$8 ^ long_$7 ) < 0) goto $5 ;',
'temp[$3] = PyInt_FromLong ( long_$8 );',
'} else { $5 :;',
'if ((temp[$3] = PyNumber_Add ( $1 , $2 )) == 0) goto $9;',
'}'), v2):
TxRepl(o, i, ('long_$6 = PyInt_AS_LONG ( $1 );',
'long_$7 = PyInt_AS_LONG ( $2 );',
'long_$8 = long_$6 + long_$7;',
'if (( long_$8 ^ long_$6 ) < 0 && ( long_$8 ^ long_$7 ) < 0) {',
'if ((temp[$3] = PyNumber_Add ( $1 , $2 )) == 0) goto $9;',
'} else {',
'temp[$3] = PyInt_FromLong ( long_$8 );',
'}'), v2)
return True
if TxMatch(o, i, ('if (1) {',
'long_$2 = PyInt_AS_LONG ( $1 );',
'long_$3 = long_$2 + 1;',
'if (( long_$3 ^ long_$2 ) < 0 && ( long_$3 ^ 1 ) < 0) goto $8 ;',
'temp[$0] = PyInt_FromLong ( long_$3 );',
'} else { $8 :;',
'if ((temp[$0] = PyNumber_Add ( $1 , consts[$11] )) == 0) goto $10;',
'}'), v2):
TxRepl(o, i, ('if ((long_$2 = PyInt_AS_LONG ( $1 )) < INT_MAX ) {',
'temp[$0] = PyInt_FromLong ( long_$2 + 1 );',
'} else {',
'if ((temp[$0] = PyNumber_Add ( $1 , consts[$11] )) == 0) goto $10;',
'}'), v2)
return True
if o[i] == 'if (0) {':
if TxMatch(o, i, ('if (0) {',
'$1;'), v2) and not ':' in o[i+1] and not '}' in o[i+1] and not '{' in o[i+1]:
TxRepl(o, i, ('if (0) {',), v2)
return True
if TxMatch(o, i, ('if (0) {',
'}'), v2):
TxRepl(o, i, (), v2)
return True
if o[i] == 'if (_self_dict) {':
if TxMatch(o, i, """
if (_self_dict) {
if (PyDict_SetItem(_self_dict, $1, $2) == -1) goto label_$0;
} else {
if ( PyObject_SetAttr ( GETLOCAL(self) , $1 , $2 ) == -1) goto label_$0;
}
if (_self_dict) {
if (PyDict_SetItem(_self_dict, $3, $4) == -1) goto label_$0;
} else {
if ( PyObject_SetAttr ( GETLOCAL(self) , $3 , $4 ) == -1) goto label_$0;
}
""", v2):
TxRepl(o, i, """
if (_self_dict) {
if (PyDict_SetItem(_self_dict, $1, $2) == -1) goto label_$0;
if (PyDict_SetItem(_self_dict, $3, $4) == -1) goto label_$0;
} else {
if ( PyObject_SetAttr ( GETLOCAL(self) , $1 , $2 ) == -1) goto label_$0;
if ( PyObject_SetAttr ( GETLOCAL(self) , $3 , $4 ) == -1) goto label_$0;
}
""", v2)
return True
if TxMatch(o, i, """
if (_self_dict) {
if (PyDict_SetItem(_self_dict, $1, $2) == -1) goto label_$0;
} else {
if ( PyObject_SetAttr ( GETLOCAL(self) , $1 , $2 ) == -1) goto label_$0;
}
f->f_lineno = $5;
f->f_lasti = $6;
if (_self_dict) {
if (PyDict_SetItem(_self_dict, $3, $4) == -1) goto label_$0;
} else {
if ( PyObject_SetAttr ( GETLOCAL(self) , $3 , $4 ) == -1) goto label_$0;
}
""", v2):
TxRepl(o, i, """
if (_self_dict) {
if (PyDict_SetItem(_self_dict, $1, $2) == -1) goto label_$0;
if (PyDict_SetItem(_self_dict, $3, $4) == -1) goto label_$0;
} else {
if ( PyObject_SetAttr ( GETLOCAL(self) , $1 , $2 ) == -1) goto label_$0;
if ( PyObject_SetAttr ( GETLOCAL(self) , $3 , $4 ) == -1) goto label_$0;
}
""", v2)
return True
if TxMatch(o, i, """
if (_self_dict) {
if (PyDict_SetItem(_self_dict, $2, temp[$0]) == -1) goto label_0;
} else {
if ( PyObject_SetAttr ( GETLOCAL(self) , $2 , temp[$0] ) == -1) goto label_$10;
}
CLEARTEMP($0);
if (_self_dict && (temp[$0] = PyDict_GetItem(_self_dict, $2)) != 0) {
Py_INCREF(temp[$0]);
} else {
if ((temp[$0] = PyObject_GetAttr ( GETLOCAL(self) , $2 )) == 0) goto label_$10;
}
""", v2):
TxRepl(o, i, """
if (_self_dict) {
if (PyDict_SetItem(_self_dict, $2, temp[$0]) == -1) goto label_0;
} else {
if ( PyObject_SetAttr ( GETLOCAL(self) , $2 , temp[$0] ) == -1) goto label_$10;
}
""", v2)
return True
if TxMatch(o, i, """
if (_self_dict) {
if (PyDict_SetItem(_self_dict, $1, $3) == -1) goto label_$0;
if (PyDict_SetItem(_self_dict, $2, $4) == -1) goto label_$0;
} else {
if ( PyObject_SetAttr ( GETLOCAL(self) , $1 , $3 ) == -1) goto label_$0;
if ( PyObject_SetAttr ( GETLOCAL(self) , $2 , $4 ) == -1) goto label_$0;
}
if (_self_dict) {
if (PyDict_SetItem(_self_dict, $5, $6) == -1) goto label_$0;
} else {
if ( PyObject_SetAttr ( GETLOCAL(self) , $5 , $6 ) == -1) goto label_$0;
}
""", v2):
TxRepl(o, i, """
if (_self_dict) {
if (PyDict_SetItem(_self_dict, $1, $3) == -1) goto label_$0;
if (PyDict_SetItem(_self_dict, $2, $4) == -1) goto label_$0;
if (PyDict_SetItem(_self_dict, $5, $6) == -1) goto label_$0;
} else {
if ( PyObject_SetAttr ( GETLOCAL(self) , $1 , $3 ) == -1) goto label_$0;
if ( PyObject_SetAttr ( GETLOCAL(self) , $2 , $4 ) == -1) goto label_$0;
if ( PyObject_SetAttr ( GETLOCAL(self) , $5 , $6 ) == -1) goto label_$0;
}
""", v2)
return True
if TxMatch(o, i, """
if (_self_dict) {
if (PyDict_SetItem(_self_dict, $1, $2) == -1) goto label_$0;
if (PyDict_SetItem(_self_dict, $3, $4) == -1) goto label_$0;
if (PyDict_SetItem(_self_dict, $5, $6) == -1) goto label_$0;
} else {
if ( PyObject_SetAttr ( GETLOCAL(self) , $1 , $2 ) == -1) goto label_$0;
if ( PyObject_SetAttr ( GETLOCAL(self) , $3 , $4 ) == -1) goto label_$0;
if ( PyObject_SetAttr ( GETLOCAL(self) , $5 , $6 ) == -1) goto label_$0;
}
if (_self_dict) {
if (PyDict_SetItem(_self_dict, $7, $8) == -1) goto label_$0;
} else {
if ( PyObject_SetAttr ( GETLOCAL(self) , $7 , $8 ) == -1) goto label_$0;
}
""", v2):
TxRepl(o, i, """
if (_self_dict) {
if (PyDict_SetItem(_self_dict, $1, $2) == -1) goto label_$0;
if (PyDict_SetItem(_self_dict, $3, $4) == -1) goto label_$0;
if (PyDict_SetItem(_self_dict, $5, $6) == -1) goto label_$0;
if (PyDict_SetItem(_self_dict, $7, $8) == -1) goto label_$0;
} else {
if ( PyObject_SetAttr ( GETLOCAL(self) , $1 , $2 ) == -1) goto label_$0;
if ( PyObject_SetAttr ( GETLOCAL(self) , $3 , $4 ) == -1) goto label_$0;
if ( PyObject_SetAttr ( GETLOCAL(self) , $5 , $6 ) == -1) goto label_$0;
if ( PyObject_SetAttr ( GETLOCAL(self) , $7 , $8 ) == -1) goto label_$0;
}
""", v2)
return True
if TxMatch(o, i, """
if (_self_dict) {
if (PyDict_SetItem(_self_dict, $5, temp[$0]) == -1) goto label_$7;
CLEARTEMP($0);
if (PyDict_SetItem(_self_dict, $6, $12) == -1) goto label_$7;
} else {
if ( PyObject_SetAttr ( GETLOCAL(self) , $5 , temp[$0] ) == -1) goto label_$7;
CLEARTEMP($0);
if ( PyObject_SetAttr ( GETLOCAL(self) , $6 , $12 ) == -1) goto label_$7;
}
if (_self_dict) {
if (PyDict_SetItem(_self_dict, $8, $10) == -1) goto label_$7;
if (PyDict_SetItem(_self_dict, $9, $11) == -1) goto label_$7;
} else {
if ( PyObject_SetAttr ( GETLOCAL(self) , $8 , $10 ) == -1) goto label_$7;
if ( PyObject_SetAttr ( GETLOCAL(self) , $9 , $11 ) == -1) goto label_$7;
}
""", v2):
TxRepl(o, i, """
if (_self_dict) {
if (PyDict_SetItem(_self_dict, $5, temp[$0]) == -1) goto label_$7;
CLEARTEMP($0);
if (PyDict_SetItem(_self_dict, $6, $12) == -1) goto label_$7;
if (PyDict_SetItem(_self_dict, $8, $10) == -1) goto label_$7;
if (PyDict_SetItem(_self_dict, $9, $11) == -1) goto label_$7;
} else {
if ( PyObject_SetAttr ( GETLOCAL(self) , $5 , temp[$0] ) == -1) goto label_$7;
CLEARTEMP($0);
if ( PyObject_SetAttr ( GETLOCAL(self) , $6 , $12 ) == -1) goto label_$7;
if ( PyObject_SetAttr ( GETLOCAL(self) , $8 , $10 ) == -1) goto label_$7;
if ( PyObject_SetAttr ( GETLOCAL(self) , $9 , $11 ) == -1) goto label_$7;
}
""", v2)
return True
if o[i].startswith('if (_self_dict'):
if TxMatch(o, i, """
if (_self_dict && (temp[$0] = PyDict_GetItem(_self_dict, $1)) != 0) {
Py_INCREF(temp[$0]);
} else {
if ((temp[$0] = PyObject_GetAttr ( GETLOCAL(self) , $1 )) == 0) goto label_$10;
}
LETLOCAL ( $2 , temp[$0] );
temp[$0] = 0;
""",v2):
TxRepl(o, i, """
if (_self_dict && (GETLOCAL($2) = PyDict_GetItem(_self_dict, $1)) != 0) {
Py_INCREF(GETLOCAL($2));
} else {
if ((GETLOCAL($2) = PyObject_GetAttr ( GETLOCAL(self) , $1 )) == 0) goto label_$10;
}
""", v2)
return True
if TxMatch(o, i, """
if (_self_dict && (temp[$0] = PyDict_GetItem(_self_dict, $1)) != 0) {
Py_INCREF(temp[$0]);
} else {
if ((temp[$0] = PyObject_GetAttr ( GETLOCAL(self) , $1 )) == 0) goto label_$10;
}
LETLOCAL ( $2 , temp[$0] );
temp[$0] = 0;
""",v2):
TxRepl(o, i, """
if (_self_dict && (GETLOCAL($2) = PyDict_GetItem(_self_dict, $1)) != 0) {
Py_INCREF(GETLOCAL($2));
} else {
if ((GETLOCAL($2) = PyObject_GetAttr ( GETLOCAL(self) , $1 )) == 0) goto label_$10;
}
""", v2)
return True
if TxMatch(o, i, """
if (_self_dict && (temp[$1] = PyDict_GetItem(_self_dict, $2)) != 0) {
Py_INCREF(temp[$1]);
} else {
if ((temp[$1] = PyObject_GetAttr ( GETLOCAL(self) , $2 )) == 0) goto label_$3;
}
if ((temp[$0] = _Direct_$4 ( GETLOCAL(self) $5 temp[$1] )) == 0) goto label_$3;
CLEARTEMP($1);
""",v2):
TxRepl(o, i, """
if ((temp[$0] = _Direct_$4 ( GETLOCAL(self) $5 PyDict_GetItem(_self_dict, $2) )) == 0) goto label_$3;
""", v2)
return True
if TxMatch(o, i, """
if (_self_dict && (temp[$1] = PyDict_GetItem(_self_dict, $2)) != 0) {
Py_INCREF(temp[$1]);
} else {
if ((temp[$1] = PyObject_GetAttr ( GETLOCAL(self) , $2 )) == 0) goto label_$3;
}
if (_Direct_fn(GETLOCAL(self)$5 temp[$1]) == -1) goto label_$3;
CLEARTEMP($1);
temp[$0] = Py_None;
Py_INCREF(temp[$0]);
""",v2):
TxRepl(o, i, """
if (_Direct_fn(GETLOCAL(self)$5 PyDict_GetItem(_self_dict, $2)) == -1) goto label_$3;
temp[$0] = Py_None;
Py_INCREF(temp[$0]);
""", v2)
return True
if TxMatch(o, i, """
if (_self_dict && (temp[$0] = PyDict_GetItem(_self_dict, $4)) != 0) {
Py_INCREF(temp[$0]);
} else {
if ((temp[$0] = PyObject_GetAttr ( GETLOCAL(self) , $4 )) == 0) goto label_$3;
}
if ((temp[$1] = _Direct_$5 ($9temp[$0]$10)) == 0) goto label_$3;
CLEARTEMP($0);
if (_self_dict) {
if (PyDict_SetItem(_self_dict, $4, temp[$1]) == -1) goto label_$3;
} else {
if ( PyObject_SetAttr ( GETLOCAL(self) , $4 , temp[$1] ) == -1) goto label_$3;
}
CLEARTEMP($1);
""",v2):
TxRepl(o, i, """
if (_self_dict && (temp[$0] = PyDict_GetItem(_self_dict, $4)) != 0) {
if ((temp[$1] = _Direct_$5 ($9temp[$0]$10)) == 0) goto label_$3;
temp[$0] = 0;
if (PyDict_SetItem(_self_dict, $4, temp[$1]) == -1) goto label_$3;
CLEARTEMP($1);
} else {
if ((temp[$0] = PyObject_GetAttr ( GETLOCAL(self) , $4 )) == 0) goto label_$3;
if ((temp[$1] = _Direct_$5 ($9temp[$0]$10)) == 0) goto label_$3;
CLEARTEMP($0);
if ( PyObject_SetAttr ( GETLOCAL(self) , $4 , temp[$1] ) == -1) goto label_$3;
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if (_$6_dict && (temp[$0] = PyDict_GetItem(_$6_dict, $3)) != 0) {
Py_INCREF(temp[$0]);
} else {
if ((temp[$0] = PyObject_GetAttr ( GETLOCAL($6) , $3 )) == 0) goto label_$5;
}
if (_$6_dict && (temp[$1] = PyDict_GetItem(_$6_dict, $4)) != 0) {
Py_INCREF(temp[$1]);
} else {
if ((temp[$1] = PyObject_GetAttr ( GETLOCAL($6) , $4 )) == 0) goto label_$5;
}
if ((temp[$2] = _Direct_$7 ( temp[$0] , temp[$1] )) == 0) goto label_$5;
CLEARTEMP($0);
CLEARTEMP($1);
if (_$6_dict) {
if (PyDict_SetItem(_$6_dict, $8, temp[$2]) == -1) goto label_$5;
} else {
if ( PyObject_SetAttr ( GETLOCAL($6) , $8 , temp[$2] ) == -1) goto label_$5;
}
CLEARTEMP($2);
""",v2):
TxRepl(o, i, """
if (_$6_dict && (temp[$0] = PyDict_GetItem(_$6_dict, $3)) != 0 && (temp[$1] = PyDict_GetItem(_$6_dict, $4)) != 0) {
if ((temp[$2] = _Direct_$7 ( temp[$0] , temp[$1] )) == 0) goto label_$5;
temp[$0] = 0;
temp[$1] = 0;
if (PyDict_SetItem(_$6_dict, $8, temp[$2]) == -1) goto label_$5;
} else {
if ((temp[$0] = PyObject_GetAttr ( GETLOCAL($6) , $3 )) == 0) goto label_$5;
if ((temp[$1] = PyObject_GetAttr ( GETLOCAL($6) , $4 )) == 0) goto label_$5;
if ((temp[$2] = _Direct_$7 ( temp[$0] , temp[$1] )) == 0) goto label_$5;
CLEARTEMP($0);
CLEARTEMP($1);
if ( PyObject_SetAttr ( GETLOCAL($6) , $8 , temp[$2] ) == -1) goto label_$5;
}
CLEARTEMP($2);
""", v2)
return True
if o[i].endswith('_dict) {'):
if TxMatch(o, i, """
if (_$10_dict) {
if (PyDict_SetItem(_$10_dict, $12, temp[$0]) == -1) goto label_$11;
} else {
if ( PyObject_SetAttr ( GETLOCAL($10) , $12 , temp[$0] ) == -1) goto label_$11;
}
CLEARTEMP($0);
if (_$10_dict) {
if (PyDict_SetItem(_$10_dict, $14, $15) == -1) goto label_$11;
} else {
if ( PyObject_SetAttr ( GETLOCAL($10) , $14 , $15 ) == -1) goto label_$11;
}
""",v2):
TxRepl(o, i, """
if (_$10_dict) {
if (PyDict_SetItem(_$10_dict, $12, temp[$0]) == -1) goto label_$11;
CLEARTEMP($0);
if (PyDict_SetItem(_$10_dict, $14, $15) == -1) goto label_$11;
} else {
if ( PyObject_SetAttr ( GETLOCAL($10) , $12 , temp[$0] ) == -1) goto label_$11;
CLEARTEMP($0);
if ( PyObject_SetAttr ( GETLOCAL($10) , $14 , $15 ) == -1) goto label_$11;
}
""", v2)
return True
if 'Py_TYPE' in o[i]:
if TxMatch(o, i, """
if ($9) {
if ((temp[$0] = _Direct_$3 ( $10 )) == 0) goto label_$11;
} else {
if ((temp[$1] = PyObject_GetAttr ( $10 , $12 )) == 0) goto label_$11;
if ((temp[$0] = FastCall0(temp[$1])) == 0) goto label_$11;
CLEARTEMP($1);
}
if (_self_dict) {
if (PyDict_SetItem(_self_dict, $13, temp[$0]) == -1) goto label_$11;
} else {
if ( PyObject_SetAttr ( GETLOCAL(self) , $13 , temp[$0] ) == -1) goto label_$11;
}
CLEARTEMP($0);
if ($9) {
if ((temp[$0] = _Direct_$4 ( $10 )) == 0) goto label_$11;
} else {
if ((temp[$1] = PyObject_GetAttr ( $10 , $14 )) == 0) goto label_$11;
if ((temp[$0] = FastCall0(temp[$1])) == 0) goto label_$11;
CLEARTEMP($1);
}
if (_self_dict) {
if (PyDict_SetItem(_self_dict, $15, temp[$0]) == -1) goto label_$11;
} else {
if ( PyObject_SetAttr ( GETLOCAL(self) , $15 , temp[$0] ) == -1) goto label_$11;
}
CLEARTEMP($0);
if ($9) {
if ((temp[$0] = _Direct_$5 ( $10 )) == 0) goto label_$11;
} else {
if ((temp[$1] = PyObject_GetAttr ( $10 , $16 )) == 0) goto label_$11;
if ((temp[$0] = FastCall0(temp[$1])) == 0) goto label_$11;
CLEARTEMP($1);
}
if (_self_dict) {
if (PyDict_SetItem(_self_dict, $17, temp[$0]) == -1) goto label_$11;
} else {
if ( PyObject_SetAttr ( GETLOCAL(self) , $17 , temp[$0] ) == -1) goto label_$11;
}
CLEARTEMP($0);
""",v2):
TxRepl(o, i, """
if ($9) {
if (_self_dict) {
if ((temp[$0] = _Direct_$3 ( $10 )) == 0) goto label_$11;
if (PyDict_SetItem(_self_dict, $13, temp[$0]) == -1) goto label_$11;
CLEARTEMP($0);
if ((temp[$0] = _Direct_$4 ( $10 )) == 0) goto label_$11;
if (PyDict_SetItem(_self_dict, $15, temp[$0]) == -1) goto label_$11;
CLEARTEMP($0);
if ((temp[$0] = _Direct_$5 ( $10 )) == 0) goto label_$11;
if (PyDict_SetItem(_self_dict, $17, temp[$0]) == -1) goto label_$11;
} else {
if ((temp[$0] = _Direct_$3 ( $10 )) == 0) goto label_$11;
if ( PyObject_SetAttr ( GETLOCAL(self) , $13 , temp[$0] ) == -1) goto label_$11;
CLEARTEMP($0);
if ((temp[$0] = _Direct_$4 ( $10 )) == 0) goto label_$11;
if ( PyObject_SetAttr ( GETLOCAL(self) , $15 , temp[$0] ) == -1) goto label_$11;
CLEARTEMP($0);
if ((temp[$0] = _Direct_$5 ( $10 )) == 0) goto label_$11;
if ( PyObject_SetAttr ( GETLOCAL(self) , $17 , temp[$0] ) == -1) goto label_$11;
}
} else {
if ((temp[$1] = PyObject_GetAttr ( $10 , $12 )) == 0) goto label_$11;
if ((temp[$0] = FastCall0(temp[$1])) == 0) goto label_$11;
CLEARTEMP($1);
if (_self_dict) {
if (PyDict_SetItem(_self_dict, $13, temp[$0]) == -1) goto label_$11;
} else {
if ( PyObject_SetAttr ( GETLOCAL(self) , $13 , temp[$0] ) == -1) goto label_$11;
}
CLEARTEMP($0);
if ((temp[$1] = PyObject_GetAttr ( $10 , $14 )) == 0) goto label_$11;
if ((temp[$0] = FastCall0(temp[$1])) == 0) goto label_$11;
CLEARTEMP($1);
if (_self_dict) {
if (PyDict_SetItem(_self_dict, $15, temp[$0]) == -1) goto label_$11;
} else {
if ( PyObject_SetAttr ( GETLOCAL(self) , $15 , temp[$0] ) == -1) goto label_$11;
}
CLEARTEMP($0);
if ((temp[$1] = PyObject_GetAttr ( $10 , $16 )) == 0) goto label_$11;
if ((temp[$0] = FastCall0(temp[$1])) == 0) goto label_$11;
CLEARTEMP($1);
if (_self_dict) {
if (PyDict_SetItem(_self_dict, $17, temp[$0]) == -1) goto label_$11;
} else {
if ( PyObject_SetAttr ( GETLOCAL(self) , $17 , temp[$0] ) == -1) goto label_$11;
}
}
""", v2)
return True
if TxMatch(o, i, """
if ($11) {
>0
if ( long_$13 < 0) {
long_$13 += PyString_GET_SIZE($10);
}
if (long_$13 < 0 || long_$13 >= PyString_GET_SIZE($10)) goto label_$4;
temp[$2] = PyString_FromStringAndSize((PyString_AS_STRING ( $3 ) + long_$13), 1);
<1
} else {
>2
}
if (PyString_GET_SIZE( temp[$2] ) == 1) {
temp[$0] = PyInt_FromLong ( (long)((unsigned char)*PyString_AS_STRING ( temp[$2] )) );
} else {
>3
}
CLEARTEMP($2);
""", v2):
TxRepl(o, i, """
if ($11) {
>0
if ( long_$13 < 0) {
long_$13 += PyString_GET_SIZE($10);
}
if (long_$13 < 0 || long_$13 >= PyString_GET_SIZE($10)) goto label_$4;
temp[$0] = PyInt_FromLong ( (long)((unsigned char)*(PyString_AS_STRING ( $3 ) + long_$13)) );
<1
} else {
>2
>3
CLEARTEMP($2);
}
""", v2)
return True
if TxMatch(o, i, """
if ($18) {
>0
if ( long_$13 < 0) {
long_$13 += $14;
}
>1
temp[$0] = PyInt_FromLong ($15);
} else {
>2
}
long_$16 = PyInt_AS_LONG ( temp[$0] );
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if ($18) {
>0
if ( long_$13 < 0) {
long_$13 += $14;
}
>1
long_$16 = ($15);
} else {
>2
long_$16 = PyInt_AS_LONG ( temp[$0] );
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
if ($10) {
>0
temp[$1] = PyInt_FromLong ( $4 );
<1
} else if ($13) {
>2
temp[$1] = PyFloat_FromDouble($5);
<3
} else { label_$3 :;
>4
if ((temp[$1] = $6) == 0) goto label_$9;
<5
}
<6
if ( PyObject_SetAttr ($8 temp[$1] ) == -1) goto label_$9;
temp[$0] = temp[$1];
temp[$1] = 0;
if ((int_$16 = c_$7_Int ( temp[$0] , $12 , $11 )) == -1) goto label_$9;
CLEARTEMP($0);""", v2):
## if True and v2[7] in op_to_oper:
## pass
v2[14] = op_to_oper[v2[7]]
## pprint(o[i:])
TxRepl(o, i, """
if ($10) {
>0
temp[$1] = PyInt_FromLong ( $4 );
int_$16 = ($4) $14 $12;
<1
<6
} else if ($13) {
>2
temp[$1] = PyFloat_FromDouble($5);
int_$16 = PyFloat_AS_DOUBLE(temp[$1]) $14 $12;
<3
<6
} else { label_$3 :;
>4
if ((temp[$1] = $6) == 0) goto label_$9;
if ((int_$16 = PyObject_RichCompareBool ( temp[$1] , $11 , $7 )) == -1) goto label_$9;
<5
<6
}
if ( PyObject_SetAttr ($8 temp[$1] ) == -1) goto label_$9;
CLEARTEMP($1);
""", v2)
## pprint(o[i:])
return True
if TxMatch(o, i, """
if ($10) {
>0
temp[$1] = PyInt_FromLong ( $4 );
<1
} else if ($13) {
>2
temp[$1] = PyFloat_FromDouble($5);
<3
} else {
>4
if ((temp[$1] = $6) == 0) goto label_$9;
<5
}
<6
if ( PyObject_SetAttr ($8 temp[$1] ) == -1) goto label_$9;
temp[$0] = temp[$1];
temp[$1] = 0;
if ((int_$16 = c_$7_Int ( temp[$0] , $12 , $11 )) == -1) goto label_$9;
CLEARTEMP($0);""", v2):
## if True and v2[7] in op_to_oper:
## pass
v2[14] = op_to_oper[v2[7]]
## pprint(o[i:])
TxRepl(o, i, """
if ($10) {
>0
temp[$1] = PyInt_FromLong ( $4 );
int_$16 = ($4) $14 $12;
<1
<6
} else if ($13) {
>2
temp[$1] = PyFloat_FromDouble($5);
int_$16 = PyFloat_AS_DOUBLE(temp[$1]) $14 $12;
<3
<6
} else {
>4
if ((temp[$1] = $6) == 0) goto label_$9;
if ((int_$16 = PyObject_RichCompareBool ( temp[$1] , $11 , $7 )) == -1) goto label_$9;
<5
<6
}
if ( PyObject_SetAttr ($8 temp[$1] ) == -1) goto label_$9;
CLEARTEMP($1);
""", v2)
## pprint(o[i:])
return True
if TxMatch(o, i, """
if ($11) {
>0
temp[$10] = PyInt_FromLong ( $12 );
<1
} else {
>2
if ((temp[$10] = $14) == 0) goto label_$15;
<3
}
<4
if (PyInt_CheckExact( temp[$10] )) {
>5
} else {
>6
}
<7
""", v2):
TxRepl(o, i, """
if ($11) {
>0
temp[$10] = PyInt_FromLong ( $12 );
<1
<4
>5
<7
} else {
>2
if ((temp[$10] = $14) == 0) goto label_$15;
<3
<4
>6
<7
}
""", v2)
return True
if TxMatch(o, i, """
if ($1) {
>0
temp[$10] = PyInt_FromLong ( $3 );
<1
} else if ($2) {
>2
temp[$10] = PyFloat_FromDouble($4);
<3
} else { label_$6 :;
>4
if ((temp[$10] = $5) == 0) goto label_$7;
<5
}
<6
if (PyInt_CheckExact( temp[$10] )) {
>7
} else if (PyFloat_CheckExact( temp[$10] )) {
>8
} else { label_$8 :;
>9
}
<10
""", v2):
TxRepl(o, i, """
if ($1) {
>0
temp[$10] = PyInt_FromLong ( $3 );
<1
<6
>7
<10
} else if ($2) {
>2
temp[$10] = PyFloat_FromDouble($4);
<3
<6
>8
<10
} else { label_$6 :;
>4
if ((temp[$10] = $5) == 0) goto label_$7;
<5
<6
label_$8 :;
>9
<10
}
""", v2)
return True
if TxMatch(o, i, """
if ($1) {
>0
temp[$10] = PyInt_FromLong ( $3 );
<1
} else if ($2) {
>2
temp[$10] = PyFloat_FromDouble($4);
<3
} else { label_$6 :;
>4
if ((temp[$10] = $5) == 0) goto label_$7;
<5
}
<6
if (PyInt_CheckExact( temp[$10] ) && PyInt_CheckExact( GETLOCAL($11) )) {
>7
} else if (PyFloat_CheckExact( temp[$10] ) && PyFloat_CheckExact( GETLOCAL($11) )) {
>8
} else { label_$8 :;
>9
}
<10
""", v2):
TxRepl(o, i, """
if ($1 && PyInt_CheckExact( GETLOCAL($11) )) {
>0
temp[$10] = PyInt_FromLong ( $3 );
<1
<6
>7
<10
} else if ($2 && PyFloat_CheckExact( GETLOCAL($11) )) {
>2
temp[$10] = PyFloat_FromDouble($4);
<3
<6
>8
<10
} else { label_$6 :;
>4
if ((temp[$10] = $5) == 0) goto label_$7;
<5
<6
label_$8 :;
>9
<10
}
""", v2)
return True
if TxMatch(o, i, """
if ($0) {
>0
temp[$11] = PyInt_FromLong ( $1 );
<1
} else if ($2) {
>2
temp[$11] = PyFloat_FromDouble($3);
<3
} else {
>4
if ((temp[$11] = $4) == 0) goto label_$5;
<5
}
<6
if (PyInt_CheckExact( temp[$11] ) && (long_$6 = PyInt_AS_LONG ( temp[$11] )) $7 $8 && long_$6 $9 $10) {
>7
temp[$13] = PyInt_FromLong ( $12 );
<8
} else {
>9
if ((temp[$13] = $14) == 0) goto label_$5;
>10
}
CLEARTEMP($11);
""", v2):
TxRepl(o, i, """
if ($0) {
>0
long_$6 = $1;
<1
<6
if (long_$6 $7 $8 && long_$6 $9 $10) {
>7
temp[$13] = PyInt_FromLong ( $12 );
<8
} else {
temp[$11] = PyInt_FromLong ( long_$6 );
>9
if ((temp[$13] = $14) == 0) goto label_$5;
>10
CLEARTEMP($11);
}
} else {
>4
if ((temp[$11] = $4) == 0) goto label_$5;
<5
<6
>9
if ((temp[$13] = $14) == 0) goto label_$5;
>10
CLEARTEMP($11);
}
""", v2)
return True
if TxMatch(o, i, """
if ($0) {
>0
temp[$1] = PyInt_FromLong ( $2 );
<1
} else {
>2
if ((temp[$1] = $3) == 0) goto label_$4;
<3
}
<4
if ($10 && PyInt_CheckExact( temp[$1] )) {
>5
if (( long_4 ^ long_1 ) < 0 && ( long_4 ^ long_2 ) < 0) goto label_$7 ;
temp[$6] = PyInt_FromLong ( long_4 );
<6
} else if ($9 && PyFloat_CheckExact( temp[$1] )) {
>7
temp[$6] = PyFloat_FromDouble($8);
<8
} else { label_$7 :;
>9
if ((temp[$6] = $11) == 0) goto label_$4;
<10
}
CLEARTEMP($5);
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if ($10 && $0) {
>0
temp[$1] = PyInt_FromLong ( $2 );
<1
<4
>5
if (( long_4 ^ long_1 ) < 0 && ( long_4 ^ long_2 ) < 0) goto label_$7 ;
temp[$6] = PyInt_FromLong ( long_4 );
<6
CLEARTEMP($5);
CLEARTEMP($1);
} else {
>2
if ((temp[$1] = $3) == 0) goto label_$4;
<3
<4
label_$7 :;
>9
if ((temp[$6] = $11) == 0) goto label_$4;
<10
CLEARTEMP($5);
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if ($0) {
>0
temp[$2] = PyInt_FromLong ($1);
<1
} else {
>2
}
if (PyInt_CheckExact( temp[$2] )) {
long_$6 = PyInt_AS_LONG ( temp[$2] );
if ( long_$6 < 0) {
long_$6 += PyList_GET_SIZE($4);
}
if ((temp[$5] = PyList_GetItem ( $4 , long_$6 )) == 0) goto label_$10;
Py_INCREF(temp[$5]);
} else {
if ((temp[$5] = PyObject_GetItem ( $4 , temp[$2] )) == 0) goto label_$10;
}
CLEARTEMP($2);
""", v2):
TxRepl(o, i, """
if ($0) {
>0
temp[$2] = PyInt_FromLong ($1);
<1
long_$6 = PyInt_AS_LONG ( temp[$2] );
CLEARTEMP($2);
if ( long_$6 < 0) {
long_$6 += PyList_GET_SIZE($4);
}
if ((temp[$5] = PyList_GetItem ( $4 , long_$6 )) == 0) goto label_$10;
Py_INCREF(temp[$5]);
} else {
>2
if ((temp[$5] = PyObject_GetItem ( $4 , temp[$2] )) == 0) goto label_$10;
CLEARTEMP($2);
}
""", v2)
return True
if TxMatch(o, i, """
if ($10) {
>0
if ($11) {
>1
temp[$1] = PyInt_FromLong ( $12 );
<2
} else {
>3
}
} else {
>5
}
if (PyInt_CheckExact( temp[$1] )) {
>7
} else {
>8
}
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if ($10) {
>0
if ($11) {
>1
temp[$1] = PyInt_FromLong ( $12 );
<2
>7
CLEARTEMP($1);
} else {
>3
>8
CLEARTEMP($1);
}
} else {
>5
>8
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if ($7) {
>0
if ($3) goto label_$10 ;
temp[$1] = PyInt_FromLong ( long_$6 );
>1
if ($4) goto label_$11 ;
CLEARTEMP($1);
temp[$2] = PyInt_FromLong ( long_$19 );
} else if ($17) {
temp[$2] = PyFloat_FromDouble($8);
} else { label_$10 :;
if ((temp[$1] = PyNumber_$18) == 0) goto label_$12;
label_$11 :;
if ((temp[$2] = PyNumber_$9) == 0) goto label_$12;
CLEARTEMP($1);
}
""", v2):
TxRepl(o, i, """
if ($7) {
>0
if ($3) goto label_$10 ;
temp[$1] = PyInt_FromLong ( long_$6 );
>1
CLEARTEMP($1);
if ($4) goto label_$10 ;
temp[$2] = PyInt_FromLong ( long_$19 );
} else if ($17) {
temp[$2] = PyFloat_FromDouble($8);
} else { label_$10 :;
if ((temp[$1] = PyNumber_$18) == 0) goto label_$12;
if ((temp[$2] = PyNumber_$9) == 0) goto label_$12;
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if ($1) {
>2
temp[$3] = PyInt_FromLong ($4);
} else {
>5
}
long_$6 = PyInt_AsLong ( temp[$3] );
CLEARTEMP($3);
""", v2):
TxRepl(o, i, """
if ($1) {
>2
temp[$3] = PyInt_FromLong ($4);
long_$6 = PyInt_AsLong ( temp[$3] );
CLEARTEMP($3);
} else {
>5
long_$6 = PyInt_AsLong ( temp[$3] );
CLEARTEMP($3);
}
""", v2)
return True
if TxMatch(o, i, """
if ($0) {
>0
temp[$2] = PyInt_FromLong ( $3 );
<1
} else {
>2
}
<3
if ((temp[$1] = $4) == 0) goto label_$10;
if (PyInt_CheckExact( temp[$2] ) && $11) {
>4
} else {
>5
}
""", v2) and v2[2] != v2[1]:
TxRepl(o, i, """
if ($0) {
>0
temp[$2] = PyInt_FromLong ( $3 );
<1
<3
if ((temp[$1] = $4) == 0) goto label_$10;
if ($11) {
>4
} else {
>5
}
} else {
>2
<3
if ((temp[$1] = $4) == 0) goto label_$10;
>5
}
""", v2)
return True
if TxMatch(o, i, """
if ($0) {
>1
if ((temp[$2] = PyBool_FromLong ($3)) == 0) goto label_$10;
} else {
>4
}
if ((int_$5 = PyObject_IsTrue ( temp[$2] )) == -1) goto label_$10;
CLEARTEMP($2);
""", v2):
TxRepl(o, i, """
if ($0) {
>1
int_$5 = ($3);
} else {
>4
if ((int_$5 = PyObject_IsTrue ( temp[$2] )) == -1) goto label_$10;
CLEARTEMP($2);
}
""", v2)
return True
if TxMatch(o, i, """
if ($0) {
>1
temp[$10] = PyBool_FromLong($2);
} else {
temp[$10] = consts[$11];
Py_INCREF(temp[$10]);
}
int_$3 = PyObject_IsTrue ( temp[$10] );
CLEARTEMP($10);
""", v2):
TxRepl(o, i, """
if ($0) {
>1
int_$3 = ($2);
} else {
int_$3 = PyObject_IsTrue ( consts[$11] );
}
""", v2)
return True
if TxMatch(o, i, """
if ($10) {
temp[$0] = PyInt_FromLong ( $11 );
} else {
>0
}
$12 = PyInt_AsLong(temp[$0]);
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if ($10) {
$12 = $11;
} else {
>0
$12 = PyInt_AsLong(temp[$0]);
CLEARTEMP($0);
}
""", v2)
return True
if 'if (PyInt_CheckExact(' in o[i]:
if TxMatch(o, i, """
if (PyInt_CheckExact( $0 )) {
>0
if ($9) goto label_$4 ;
temp[$1] = PyInt_FromLong ( long_$7 );
} else { label_$4 :;
if ((temp[$1] = PyNumber_$11) == 0) goto label_$6;
}
if (PyInt_CheckExact( temp[$1] ) && PyInt_CheckExact( $3 )) {
long_$13 = PyInt_AS_LONG ( temp[$1] );
>1
if ($10) goto label_$5 ;
temp[$2] = PyInt_FromLong ( long_$8 );
} else { label_$5 :;
if ((temp[$2] = PyNumber_$12) == 0) goto label_$6;
}
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $0 ) && PyInt_CheckExact( $3 )) {
>0
if ($9) goto label_$4 ;
long_$13 = long_$7;
>1
if ($10) goto label_$4 ;
temp[$2] = PyInt_FromLong ( long_$8 );
} else { label_$4 :;
if ((temp[$1] = PyNumber_$11) == 0) goto label_$6;
if ((temp[$2] = PyNumber_$12) == 0) goto label_$6;
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( temp[$0] )$4) {
temp[$1] = PyInt_FromLong ( $5 );
} else {
if ((temp[$1] = $6) == 0) goto label_$9;
}
CLEARTEMP($0);
if (PyInt_CheckExact( temp[$2] ) && PyInt_CheckExact( temp[$1] )) {
temp[$3] = PyInt_FromLong ( PyInt_AS_LONG ( temp[$2] ) $7 PyInt_AS_LONG ( temp[$1] ) );
} else {
if ((temp[$3] = PyNumber_$8 ( temp[$2] , temp[$1] )) == 0) goto label_$9;
}
CLEARTEMP($2);
CLEARTEMP($1);
""", v2) and ('temp[%s]' % v2[0]) not in v2[5]:
TxRepl(o, i, """
if (PyInt_CheckExact( temp[$2] ) && PyInt_CheckExact( temp[$0] )$4) {
CLEARTEMP($0);
temp[$3] = PyInt_FromLong ( PyInt_AS_LONG ( temp[$2] ) $7 ($5) );
CLEARTEMP($2);
} else {
if ((temp[$1] = $6) == 0) goto label_$9;
CLEARTEMP($0);
if ((temp[$3] = PyNumber_$8 ( temp[$2] , temp[$1] )) == 0) goto label_$9;
CLEARTEMP($2);
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $0 )) {
>0
temp[$1] = PyInt_FromLong ( $4 );
<1
} else {
>2
if ((temp[$1] = $5) == 0) goto label_$3;
<3
}
<4
if (PyInt_CheckExact( $0 ) && PyInt_CheckExact( temp[$1] )) {
>5
if ($11) {
temp[$2] = PyInt_FromLong ( $12 );
} else {
temp[$2] = PyInt_Type.tp_as_number->nb_multiply($13);
}
} else {
if ((temp[$2] = $14) == 0) goto label_$3;
}
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $0 )) {
>0
temp[$1] = PyInt_FromLong ( $4 );
<1
<4
>5
if ($11) {
temp[$2] = PyInt_FromLong ( $12 );
} else {
temp[$2] = PyInt_Type.tp_as_number->nb_multiply($13);
}
CLEARTEMP($1);
} else {
>2
if ((temp[$1] = $5) == 0) goto label_$3;
<3
<4
if ((temp[$2] = $14) == 0) goto label_$3;
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if ($10) {
Py_DECREF($11);
$11 = PyInt_FromLong ( $12 );
} else {
>0
}
if (PyInt_CheckExact( $11 )) {
>1
} else {
>2
}
<3
""", v2):
TxRepl(o, i, """
if ($10) {
Py_DECREF($11);
$11 = PyInt_FromLong ( $12 );
>1
<3
} else {
>0
>2
<3
}
""", v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 ) && ($2 = PyInt_AS_LONG ( $1 )) < INT_MAX ) {',
'temp[$5] = PyInt_FromLong ( $2 + 1 );',
'} else if (PyFloat_CheckExact( $1 )) {',
'temp[$5] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) + ((double)1));',
'} else {',
'if ((temp[$5] = PyNumber_Add ( $1 , $7 )) == 0) goto $3;',
'}',
'if ((temp[$6] = PyObject_GetItem ( $4 , temp[$5] )) == 0) goto $3;',
'CLEARTEMP($5);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && ($2 = PyInt_AS_LONG ( $1 )) < INT_MAX ) {',
'$2 = $2 + 1;',
'temp[$5] = PyInt_FromLong ( $2 );',
'if ((temp[$6] = _c_BINARY_SUBSCR_Int ( $4 , $2 , temp[$5] )) == 0) goto $3;',
'} else {',
'if ((temp[$5] = PyNumber_Add ( $1 , $7 )) == 0) goto $3;',
'if ((temp[$6] = PyObject_GetItem ( $4 , temp[$5] )) == 0) goto $3;',
'}',
'CLEARTEMP($5);'), v2, ('_c_BINARY_SUBSCR_Int',))
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 ) && ($2 = PyInt_AS_LONG ( $1 )) < INT_MAX ) {',
'temp[$5] = PyInt_FromLong ( $2 + 1 );',
'} else {',
'if ((temp[$5] = PyNumber_Add ( $1 , $7 )) == 0) goto $3;',
'}',
'if ((temp[$6] = PyObject_GetItem ( $4 , temp[$5] )) == 0) goto $3;',
'CLEARTEMP($5);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && ($2 = PyInt_AS_LONG ( $1 )) < INT_MAX ) {',
'$2 = $2 + 1;',
'temp[$5] = PyInt_FromLong ( $2 );',
'if ((temp[$6] = _c_BINARY_SUBSCR_Int ( $4 , $2 , temp[$5] )) == 0) goto $3;',
'} else {',
'if ((temp[$5] = PyNumber_Add ( $1 , $7 )) == 0) goto $3;',
'if ((temp[$6] = PyObject_GetItem ( $4 , temp[$5] )) == 0) goto $3;',
'}',
'CLEARTEMP($5);'), v2, ('_c_BINARY_SUBSCR_Int',))
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 ) && ($2 = PyInt_AS_LONG ( $1 )) > INT_MIN ) {',
'temp[$5] = PyInt_FromLong ( $2 - 1 );',
'} else if (PyFloat_CheckExact( $1 )) {',
'temp[$5] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) - ((double)1));',
'} else {',
'if ((temp[$5] = PyNumber_Subtract ( $1 , $7 )) == 0) goto $3;',
'}',
'if ((temp[$6] = PyObject_GetItem ( $4 , temp[$5] )) == 0) goto $3;',
'CLEARTEMP($5);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && ($2 = PyInt_AS_LONG ( $1 )) > INT_MIN ) {',
'$2 = $2 - 1;',
'temp[$5] = PyInt_FromLong ( $2 );',
'if ((temp[$6] = _c_BINARY_SUBSCR_Int ( $4 , $2 , temp[$5] )) == 0) goto $3;',
'} else {',
'if ((temp[$5] = PyNumber_Subtract ( $1 , $7 )) == 0) goto $3;',
'if ((temp[$6] = PyObject_GetItem ( $4 , temp[$5] )) == 0) goto $3;',
'}',
'CLEARTEMP($5);'), v2, ('_c_BINARY_SUBSCR_Int',))
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 ) && ($2 = PyInt_AS_LONG ( $1 )) > INT_MIN ) {',
'temp[$5] = PyInt_FromLong ( $2 - 1 );',
'} else {',
'if ((temp[$5] = PyNumber_Subtract ( $1 , $7 )) == 0) goto $3;',
'}',
'if ((temp[$6] = PyObject_GetItem ( $4 , temp[$5] )) == 0) goto $3;',
'CLEARTEMP($5);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && ($2 = PyInt_AS_LONG ( $1 )) > INT_MIN ) {',
'$2 = $2 - 1;',
'temp[$5] = PyInt_FromLong ( $2 );',
'if ((temp[$6] = _c_BINARY_SUBSCR_Int ( $4 , $2 , temp[$5] )) == 0) goto $3;',
'} else {',
'if ((temp[$5] = PyNumber_Subtract ( $1 , $7 )) == 0) goto $3;',
'if ((temp[$6] = PyObject_GetItem ( $4 , temp[$5] )) == 0) goto $3;',
'}',
'CLEARTEMP($5);'), v2, ('_c_BINARY_SUBSCR_Int',))
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $5 ) && ($1 = PyInt_AS_LONG ( $5 )) < (INT_MAX-$6) ) {',
'temp[$3] = PyInt_FromLong ( $1 + $7 );',
'} else if (PyFloat_CheckExact( $5 )) {',
'temp[$3] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($5) + ((double)$7));',
'} else {',
'if ((temp[$3] = PyNumber_Add ( $5 , $8 )) == 0) goto $10;',
'}',
'if (PyInt_CheckExact( temp[$3] )) {',
'$2 = PyInt_AS_LONG ( temp[$3] );',
'if ( $2 < 0) {',
'$2 += PyList_GET_SIZE($9);',
'}',
'if ((temp[$4] = PyList_GetItem ( $9 , $2 )) == 0) goto $10;',
'Py_INCREF(temp[$4]);',
'} else {',
'if ((temp[$4] = PyObject_GetItem ( $9 , temp[$3] )) == 0) goto $10;',
'}',
'CLEARTEMP($3);'), v2) and v2[1] != v2[2]:
TxRepl(o, i, ('if (PyInt_CheckExact( $5 ) && ($1 = PyInt_AS_LONG ( $5 )) < (INT_MAX-$6) ) {',
'$2 = $1 + $7;',
'if ( $2 < 0) {',
'$2 += PyList_GET_SIZE($9);',
'}',
'if ((temp[$4] = PyList_GetItem ( $9 , $2 )) == 0) goto $10;',
'Py_INCREF(temp[$4]);',
'} else {',
'if ((temp[$3] = PyNumber_Add ( $5 , $8 )) == 0) goto $10;',
'if ((temp[$4] = PyObject_GetItem ( $9 , temp[$3] )) == 0) goto $10;',
'CLEARTEMP($3);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $5 ) && ($1 = PyInt_AS_LONG ( $5 )) < (INT_MAX-$6) ) {',
'temp[$3] = PyInt_FromLong ( $1 + $7 );',
'} else {',
'if ((temp[$3] = PyNumber_Add ( $5 , $8 )) == 0) goto $10;',
'}',
'if (PyInt_CheckExact( temp[$3] )) {',
'$2 = PyInt_AS_LONG ( temp[$3] );',
'if ( $2 < 0) {',
'$2 += PyList_GET_SIZE($9);',
'}',
'if ((temp[$4] = PyList_GetItem ( $9 , $2 )) == 0) goto $10;',
'Py_INCREF(temp[$4]);',
'} else {',
'if ((temp[$4] = PyObject_GetItem ( $9 , temp[$3] )) == 0) goto $10;',
'}',
'CLEARTEMP($3);'), v2) and v2[1] != v2[2]:
TxRepl(o, i, ('if (PyInt_CheckExact( $5 ) && ($1 = PyInt_AS_LONG ( $5 )) < (INT_MAX-$6) ) {',
'$2 = $1 + $7;',
'if ( $2 < 0) {',
'$2 += PyList_GET_SIZE($9);',
'}',
'if ((temp[$4] = PyList_GetItem ( $9 , $2 )) == 0) goto $10;',
'Py_INCREF(temp[$4]);',
'} else {',
'if ((temp[$3] = PyNumber_Add ( $5 , $8 )) == 0) goto $10;',
'if ((temp[$4] = PyObject_GetItem ( $9 , temp[$3] )) == 0) goto $10;',
'CLEARTEMP($3);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 )) {',
'$4 = PyInt_AS_LONG ( $1 );',
'if ( $4 < 0) {',
'$4 += PyList_GET_SIZE($2);',
'}',
'if ((temp[$0] = PyList_GetItem ( $2 , $4 )) == 0) goto $3;',
'Py_INCREF(temp[$0]);',
'} else {',
'if ((temp[$0] = PyObject_GetItem ( $2 , $1 )) == 0) goto $3;',
'}',
'if (PyInt_CheckExact( $1 ) && ($5 = PyInt_AS_LONG ( $1 )) > INT_MIN ) {',
'temp[$6] = PyInt_FromLong ( $5 - 1 );',
'} else if (PyFloat_CheckExact( $1 )) {',
'temp[$6] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) - ((double)1));',
'} else {',
'if ((temp[$6] = PyNumber_Subtract ( $1 , consts[$11] )) == 0) goto $3;',
'}'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && ($4 = PyInt_AS_LONG ( $1 )) > INT_MIN ) {',
'$4 = PyInt_AS_LONG ( $1 );',
'temp[$6] = PyInt_FromLong ( $4 - 1 );',
'if ( $4 < 0) {',
'$4 += PyList_GET_SIZE($2);',
'}',
'if ((temp[$0] = PyList_GetItem ( $2 , $4 )) == 0) goto $3;',
'Py_INCREF(temp[$0]);',
'} else {',
'if ((temp[$0] = PyObject_GetItem ( $2 , $1 )) == 0) goto $3;',
'if ((temp[$6] = PyNumber_Subtract ( $1 , consts[$11] )) == 0) goto $3;',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 )) {',
'$4 = PyInt_AS_LONG ( $1 );',
'if ( $4 < 0) {',
'$4 += PyList_GET_SIZE($2);',
'}',
'if ((temp[$0] = PyList_GetItem ( $2 , $4 )) == 0) goto $3;',
'Py_INCREF(temp[$0]);',
'} else {',
'if ((temp[$0] = PyObject_GetItem ( $2 , $1 )) == 0) goto $3;',
'}',
'if (PyInt_CheckExact( $1 ) && ($5 = PyInt_AS_LONG ( $1 )) > INT_MIN ) {',
'temp[$6] = PyInt_FromLong ( $5 - 1 );',
'} else {',
'if ((temp[$6] = PyNumber_Subtract ( $1 , consts[$11] )) == 0) goto $3;',
'}'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && ($4 = PyInt_AS_LONG ( $1 )) > INT_MIN ) {',
'$4 = PyInt_AS_LONG ( $1 );',
'temp[$6] = PyInt_FromLong ( $4 - 1 );',
'if ( $4 < 0) {',
'$4 += PyList_GET_SIZE($2);',
'}',
'if ((temp[$0] = PyList_GetItem ( $2 , $4 )) == 0) goto $3;',
'Py_INCREF(temp[$0]);',
'} else {',
'if ((temp[$0] = PyObject_GetItem ( $2 , $1 )) == 0) goto $3;',
'if ((temp[$6] = PyNumber_Subtract ( $1 , consts[$11] )) == 0) goto $3;',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 )) {',
'$2 = PyInt_AS_LONG ( $1 );',
'if ( $2 < 0) {',
'$2 += PyList_GET_SIZE($0);',
'}',
'if ((temp[$4] = PyList_GetItem ( $0 , $2 )) == 0) goto $6;',
'Py_INCREF(temp[$4]);',
'} else {',
'if ((temp[$4] = PyObject_GetItem ( $0 , $1 )) == 0) goto $6;',
'}',
'if (PyInt_CheckExact( $1 ) && ($3 = PyInt_AS_LONG ( $1 )) < INT_MAX ) {',
'$2 = $3 + 1;',
'if ( $2 < 0) {',
'$2 += PyList_GET_SIZE($0);',
'}',
'if ( PyList_SetItem ( $0 , $2 , temp[$4] ) == -1) goto $6;',
'} else {',
'if ((temp[$5] = PyNumber_Add ( $1 , $7 )) == 0) goto $6;',
'if ( PyObject_SetItem ( $0 , temp[$5] , temp[$4] ) == -1) goto $6;',
'Py_DECREF(temp[$4]);',
'CLEARTEMP($5);',
'}',
'temp[$4] = 0;'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $1 )) {',
'$3 = PyInt_AS_LONG ( $1 );',
'$2 = $3 + 1;',
'if ( $2 < 0) {',
'$2 += PyList_GET_SIZE($0);',
'}',
'if ( $3 < 0) {',
'$3 += PyList_GET_SIZE($0);',
'}',
'if ((temp[$4] = PyList_GetItem ( $0 , $3 )) == 0) goto $6;',
'Py_INCREF(temp[$4]);',
'if ( PyList_SetItem ( $0 , $2 , temp[$4] ) == -1) goto $6;',
'} else {',
'if ((temp[$4] = PyObject_GetItem ( $0 , $1 )) == 0) goto $6;',
'if ((temp[$5] = PyNumber_Add ( $1 , $7 )) == 0) goto $6;',
'if ( PyObject_SetItem ( $0 , temp[$5] , temp[$4] ) == -1) goto $6;',
'Py_DECREF(temp[$4]);',
'CLEARTEMP($5);',
'}',
'temp[$4] = 0;'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $2 ) && ($5 = PyInt_AS_LONG ( $2 )) < (INT_MAX-$9) ) {',
'temp[$4] = PyInt_FromLong ( $5 + $8 );',
'} else if (PyFloat_CheckExact( $2 )) {',
'temp[$4] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($2) + ((double)$8));',
'} else {',
'if ((temp[$4] = PyNumber_Add ( $2 , $10 )) == 0) goto $7;',
'}',
'SETLOCAL ( $1 , temp[$4] );',
'temp[$4] = 0;',
'Py_INCREF($3);',
'if (PyInt_CheckExact( GETLOCAL($1) )) {',
'$6 = PyInt_AS_LONG ( GETLOCAL($1) );',
'if ( $6 < 0) {',
'$6 += PyList_GET_SIZE($11);',
'}',
'if ( PyList_SetItem ( $11 , $6 , $3 ) == -1) goto $7;',
'} else {',
'if ( PyObject_SetItem ( $11 , GETLOCAL($1) , $3 ) == -1) goto $7;',
'Py_DECREF($3);',
'}'), v2) and v2[6] != v2[5]:
TxRepl(o, i, ('if (PyInt_CheckExact( $2 ) && ($5 = PyInt_AS_LONG ( $2 )) < (INT_MAX-$9) ) {',
'$6 = $5 + $8;',
'temp[$4] = PyInt_FromLong ( $6 );',
'SETLOCAL ( $1 , temp[$4] );',
'temp[$4] = 0;',
'if ( $6 < 0) {',
'$6 += PyList_GET_SIZE($11);',
'}',
'Py_INCREF($3);',
'if ( PyList_SetItem ( $11 , $6 , $3 ) == -1) goto $7;',
'} else {',
'if ((temp[$4] = PyNumber_Add ( $2 , $10 )) == 0) goto $7;',
'SETLOCAL ( $1 , temp[$4] );',
'temp[$4] = 0;',
'if ( PyObject_SetItem ( $11 , GETLOCAL($1) , $3 ) == -1) goto $7;',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $2 ) && ($5 = PyInt_AS_LONG ( $2 )) < (INT_MAX-$9) ) {',
'temp[$4] = PyInt_FromLong ( $5 + $8 );',
'} else {',
'if ((temp[$4] = PyNumber_Add ( $2 , $10 )) == 0) goto $7;',
'}',
'SETLOCAL ( $1 , temp[$4] );',
'temp[$4] = 0;',
'Py_INCREF($3);',
'if (PyInt_CheckExact( GETLOCAL($1) )) {',
'$6 = PyInt_AS_LONG ( GETLOCAL($1) );',
'if ( $6 < 0) {',
'$6 += PyList_GET_SIZE($11);',
'}',
'if ( PyList_SetItem ( $11 , $6 , $3 ) == -1) goto $7;',
'} else {',
'if ( PyObject_SetItem ( $11 , GETLOCAL($1) , $3 ) == -1) goto $7;',
'Py_DECREF($3);',
'}'), v2) and v2[6] != v2[5]:
TxRepl(o, i, ('if (PyInt_CheckExact( $2 ) && ($5 = PyInt_AS_LONG ( $2 )) < (INT_MAX-$9) ) {',
'$6 = $5 + $8;',
'temp[$4] = PyInt_FromLong ( $6 );',
'SETLOCAL ( $1 , temp[$4] );',
'temp[$4] = 0;',
'if ( $6 < 0) {',
'$6 += PyList_GET_SIZE($11);',
'}',
'Py_INCREF($3);',
'if ( PyList_SetItem ( $11 , $6 , $3 ) == -1) goto $7;',
'} else {',
'if ((temp[$4] = PyNumber_Add ( $2 , $10 )) == 0) goto $7;',
'SETLOCAL ( $1 , temp[$4] );',
'temp[$4] = 0;',
'if ( PyObject_SetItem ( $11 , GETLOCAL($1) , $3 ) == -1) goto $7;',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( temp[$0] ) && ($8 = PyInt_AS_LONG ( temp[$0] )) > $10 ) {',
'temp[$1] = PyInt_FromLong ( $8 - $11 );',
'} else if (PyFloat_CheckExact( temp[$0] )) {',
'temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$0]) - ((double)$11));',
'} else {',
'if ((temp[$1] = PyNumber_Subtract ( temp[$0] , $9 )) == 0) goto $2;',
'}',
'CLEARTEMP($0);',
'if (PyInt_CheckExact( temp[$1] )) {',
'$5 = $6 $7 PyInt_AS_LONG ( temp[$1] );',
'} else {',
'if ((temp[$3] = PyInt_FromSsize_t($6)) == 0) goto $2;',
'if (($5 = PyObject_RichCompareBool ( temp[$3] , temp[$1] , $4 )) == -1) goto $2;',
'CLEARTEMP($3);',
'}',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( temp[$0] ) && ($8 = PyInt_AS_LONG ( temp[$0] )) > $10 ) {',
'CLEARTEMP($0);',
'$5 = $6 $7 ($8 - $11);',
'} else {',
'if ((temp[$1] = PyNumber_Subtract ( temp[$0] , $9 )) == 0) goto $2;',
'CLEARTEMP($0);',
'if ((temp[$3] = PyInt_FromSsize_t($6)) == 0) goto $2;',
'if (($5 = PyObject_RichCompareBool ( temp[$3] , temp[$1] , $4 )) == -1) goto $2;',
'CLEARTEMP($1);',
'CLEARTEMP($3);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( temp[$0] ) && ($8 = PyInt_AS_LONG ( temp[$0] )) > $10 ) {',
'temp[$1] = PyInt_FromLong ( $8 - $11 );',
'} else {',
'if ((temp[$1] = PyNumber_Subtract ( temp[$0] , $9 )) == 0) goto $2;',
'}',
'CLEARTEMP($0);',
'if (PyInt_CheckExact( temp[$1] )) {',
'$5 = $6 $7 PyInt_AS_LONG ( temp[$1] );',
'} else {',
'if ((temp[$3] = PyInt_FromSsize_t($6)) == 0) goto $2;',
'if (($5 = PyObject_RichCompareBool ( temp[$3] , temp[$1] , $4 )) == -1) goto $2;',
'CLEARTEMP($3);',
'}',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( temp[$0] ) && ($8 = PyInt_AS_LONG ( temp[$0] )) > $10 ) {',
'CLEARTEMP($0);',
'$5 = $6 $7 ($8 - $11);',
'} else {',
'if ((temp[$1] = PyNumber_Subtract ( temp[$0] , $9 )) == 0) goto $2;',
'CLEARTEMP($0);',
'if ((temp[$3] = PyInt_FromSsize_t($6)) == 0) goto $2;',
'if (($5 = PyObject_RichCompareBool ( temp[$3] , temp[$1] , $4 )) == -1) goto $2;',
'CLEARTEMP($1);',
'CLEARTEMP($3);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( temp[$0] ) && ($8 = PyInt_AS_LONG ( temp[$0] )) > $10 ) {',
'temp[$1] = PyInt_FromLong ( $8 - $11 );',
'} else if (PyFloat_CheckExact( temp[$0] )) {',
'temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$0]) - ((double)$11));',
'} else {',
'if ((temp[$1] = PyNumber_Subtract ( temp[$0] , $9 )) == 0) goto $2;',
'}',
'CLEARTEMP($0);',
'$6 = PyInt_AsSsize_t ( temp[$1] );',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( temp[$0] ) && ($8 = PyInt_AS_LONG ( temp[$0] )) > $10 ) {',
'CLEARTEMP($0);',
'$6 = $8 - $11;',
'} else {',
'if ((temp[$1] = PyNumber_Subtract ( temp[$0] , $9 )) == 0) goto $2;',
'CLEARTEMP($0);',
'$6 = PyInt_AsSsize_t ( temp[$1] );',
'CLEARTEMP($1);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( temp[$0] ) && ($8 = PyInt_AS_LONG ( temp[$0] )) > $10 ) {',
'temp[$1] = PyInt_FromLong ( $8 - $11 );',
'} else {',
'if ((temp[$1] = PyNumber_Subtract ( temp[$0] , $9 )) == 0) goto $2;',
'}',
'CLEARTEMP($0);',
'$6 = PyInt_AsSsize_t ( temp[$1] );',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( temp[$0] ) && ($8 = PyInt_AS_LONG ( temp[$0] )) > $10 ) {',
'CLEARTEMP($0);',
'$6 = $8 - $11;',
'} else {',
'if ((temp[$1] = PyNumber_Subtract ( temp[$0] , $9 )) == 0) goto $2;',
'CLEARTEMP($0);',
'$6 = PyInt_AsSsize_t ( temp[$1] );',
'CLEARTEMP($1);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( temp[$1] )) {',
'temp[$2] = PyInt_FromLong (PyInt_AS_LONG ( temp[$1] )&$8);',
'} else {',
'if ((temp[$2] = PyNumber_And ( temp[$1] , $7 )) == 0) goto $5;',
'}',
'CLEARTEMP($1);',
'if (PyInt_CheckExact( temp[$2] )) {',
'$4 = PyInt_AS_LONG ( temp[$2] );',
'if ( $4 < 0) {',
'$4 += PyList_GET_SIZE($6);',
'}',
'if ((temp[$3] = PyList_GetItem ( $6 , $4 )) == 0) goto $5;',
'Py_INCREF(temp[$3]);',
'} else {',
'if ((temp[$3] = PyObject_GetItem ( $6 , temp[$2] )) == 0) goto $5;',
'}',
'CLEARTEMP($2);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( temp[$1] )) {',
'$4 = PyInt_AS_LONG ( temp[$1] )&$8;',
'CLEARTEMP($1);',
'if ( $4 < 0) {',
'$4 += PyList_GET_SIZE($6);',
'}',
'if ((temp[$3] = PyList_GetItem ( $6 , $4 )) == 0) goto $5;',
'Py_INCREF(temp[$3]);',
'} else {',
'if ((temp[$2] = PyNumber_And ( temp[$1] , $7 )) == 0) goto $5;',
'CLEARTEMP($1);',
'if ((temp[$3] = PyObject_GetItem ( $6 , temp[$2] )) == 0) goto $5;',
'}',
'CLEARTEMP($2);'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 ) && ($3 = PyInt_AS_LONG ( $1 )) < $5 ) {',
'temp[$9] = PyInt_FromLong ( $3 + $6 );',
'} else if (PyFloat_CheckExact( $1 )) {',
'temp[$9] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) + ((double)$6));',
'} else {',
'if ((temp[$9] = PyNumber_Add ( $1 , $7 )) == 0) goto $8;',
'}',
'if (PyInt_CheckExact( temp[$9] )) {',
'$4 = PyInt_AS_LONG ( temp[$9] );',
'if ( $4 < 0) {',
'$4 += PyList_GET_SIZE($2);',
'}',
'if ( PyList_SetItem ( $2 , $4 , temp[$10] ) == -1) goto $8;',
'} else {',
'if ( PyObject_SetItem ( $2 , temp[$9] , temp[$10] ) == -1) goto $8;',
'Py_DECREF(temp[$10]);',
'}',
'CLEARTEMP($9);',
'temp[$10] = 0;'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && ($3 = PyInt_AS_LONG ( $1 )) < $5 ) {',
'$4 = $3 + $6;',
'if ( $4 < 0) {',
'$4 += PyList_GET_SIZE($2);',
'}',
'if ( PyList_SetItem ( $2 , $4 , temp[$10] ) == -1) goto $8;',
'} else {',
'if ((temp[$9] = PyNumber_Add ( $1 , $7 )) == 0) goto $8;',
'if ( PyObject_SetItem ( $2 , temp[$9] , temp[$10] ) == -1) goto $8;',
'Py_DECREF(temp[$10]);',
'CLEARTEMP($9);',
'}',
'temp[$10] = 0;'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 ) && ($3 = PyInt_AS_LONG ( $1 )) < $5 ) {',
'temp[$9] = PyInt_FromLong ( $3 + $6 );',
'} else {',
'if ((temp[$9] = PyNumber_Add ( $1 , $7 )) == 0) goto $8;',
'}',
'if (PyInt_CheckExact( temp[$9] )) {',
'$4 = PyInt_AS_LONG ( temp[$9] );',
'if ( $4 < 0) {',
'$4 += PyList_GET_SIZE($2);',
'}',
'if ( PyList_SetItem ( $2 , $4 , temp[$10] ) == -1) goto $8;',
'} else {',
'if ( PyObject_SetItem ( $2 , temp[$9] , temp[$10] ) == -1) goto $8;',
'Py_DECREF(temp[$10]);',
'}',
'CLEARTEMP($9);',
'temp[$10] = 0;'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && ($3 = PyInt_AS_LONG ( $1 )) < $5 ) {',
'$4 = $3 + $6;',
'if ( $4 < 0) {',
'$4 += PyList_GET_SIZE($2);',
'}',
'if ( PyList_SetItem ( $2 , $4 , temp[$10] ) == -1) goto $8;',
'} else {',
'if ((temp[$9] = PyNumber_Add ( $1 , $7 )) == 0) goto $8;',
'if ( PyObject_SetItem ( $2 , temp[$9] , temp[$10] ) == -1) goto $8;',
'Py_DECREF(temp[$10]);',
'CLEARTEMP($9);',
'}',
'temp[$10] = 0;'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( temp[$1] ) && ($4 = PyInt_AS_LONG ( temp[$1] )) < $5 ) {',
'temp[$2] = PyInt_FromLong ( $4 + $6 );',
'} else if (PyFloat_CheckExact( temp[$1] )) {',
'temp[$2] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$1]) + ((double)$6));',
'} else {',
'if ((temp[$2] = PyNumber_Add ( temp[$1] , $7 )) == 0) goto $8;',
'}',
'CLEARTEMP($1);',
'if (PyInt_CheckExact( temp[$2] )) {',
'$9 = PyInt_AS_LONG ( temp[$2] );',
'$9 = Py_ARITHMETIC_RIGHT_SHIFT(long, $9, $10);',
'temp[$3] = PyInt_FromLong ($9);',
'} else {',
'if ((temp[$3] = PyNumber_Rshift(temp[$2], $11)) == 0) goto $8;',
'}',
'CLEARTEMP($2);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( temp[$1] ) && ($4 = PyInt_AS_LONG ( temp[$1] )) < $5 ) {',
'CLEARTEMP($1);',
'$9 = $4 + $6;',
'$9 = Py_ARITHMETIC_RIGHT_SHIFT(long, $9, $10);',
'temp[$3] = PyInt_FromLong ($9);',
'} else {',
'if ((temp[$2] = PyNumber_Add ( temp[$1] , $7 )) == 0) goto $8;',
'CLEARTEMP($1);',
'if ((temp[$3] = PyNumber_Rshift(temp[$2], $11)) == 0) goto $8;',
'CLEARTEMP($2);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( temp[$1] ) && ($4 = PyInt_AS_LONG ( temp[$1] )) < $5 ) {',
'temp[$2] = PyInt_FromLong ( $4 + $6 );',
'} else {',
'if ((temp[$2] = PyNumber_Add ( temp[$1] , $7 )) == 0) goto $8;',
'}',
'CLEARTEMP($1);',
'if (PyInt_CheckExact( temp[$2] )) {',
'$9 = PyInt_AS_LONG ( temp[$2] );',
'$9 = Py_ARITHMETIC_RIGHT_SHIFT(long, $9, $10);',
'temp[$3] = PyInt_FromLong ($9);',
'} else {',
'if ((temp[$3] = PyNumber_Rshift(temp[$2], $11)) == 0) goto $8;',
'}',
'CLEARTEMP($2);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( temp[$1] ) && ($4 = PyInt_AS_LONG ( temp[$1] )) < $5 ) {',
'CLEARTEMP($1);',
'$9 = $4 + $6;',
'$9 = Py_ARITHMETIC_RIGHT_SHIFT(long, $9, $10);',
'temp[$3] = PyInt_FromLong ($9);',
'} else {',
'if ((temp[$2] = PyNumber_Add ( temp[$1] , $7 )) == 0) goto $8;',
'CLEARTEMP($1);',
'if ((temp[$3] = PyNumber_Rshift(temp[$2], $11)) == 0) goto $8;',
'CLEARTEMP($2);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 ) && ($2 = PyInt_AS_LONG ( $1 )) > INT_MIN ) {',
'temp[$3] = PyInt_FromLong ( $2 - 1 );',
'} else if (PyFloat_CheckExact( $1 )) {',
'temp[$3] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) - ((double)1));',
'} else {',
'if ((temp[$3] = PyNumber_Subtract ( $1 , $5 )) == 0) goto $4;',
'}',
'if (PyInt_CheckExact( temp[$3] )) {',
'$6 = PyInt_AS_LONG ( temp[$3] );',
'if ( $6 < 0) {',
'$6 += PyList_GET_SIZE($7);',
'}',
'if ((temp[$8] = PyList_GetItem ( $7 , $6 )) == 0) goto $4;',
'Py_INCREF(temp[$8]);',
'} else {',
'if ((temp[$8] = PyObject_GetItem ( $7 , temp[$3] )) == 0) goto $4;',
'}',
'CLEARTEMP($3);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && ($2 = PyInt_AS_LONG ( $1 )) > INT_MIN ) {',
'$6 = $2 - 1;',
'if ( $6 < 0) {',
'$6 += PyList_GET_SIZE($7);',
'}',
'if ((temp[$8] = PyList_GetItem ( $7 , $6 )) == 0) goto $4;',
'Py_INCREF(temp[$8]);',
'temp[$3] = 0;',
'} else {',
'if ((temp[$3] = PyNumber_Subtract ( $1 , $5 )) == 0) goto $4;',
'if ((temp[$8] = PyObject_GetItem ( $7 , temp[$3] )) == 0) goto $4;',
'CLEARTEMP($3);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 ) && ($2 = PyInt_AS_LONG ( $1 )) > INT_MIN ) {',
'temp[$3] = PyInt_FromLong ( $2 - 1 );',
'} else {',
'if ((temp[$3] = PyNumber_Subtract ( $1 , $5 )) == 0) goto $4;',
'}',
'if (PyInt_CheckExact( temp[$3] )) {',
'$6 = PyInt_AS_LONG ( temp[$3] );',
'if ( $6 < 0) {',
'$6 += PyList_GET_SIZE($7);',
'}',
'if ((temp[$8] = PyList_GetItem ( $7 , $6 )) == 0) goto $4;',
'Py_INCREF(temp[$8]);',
'} else {',
'if ((temp[$8] = PyObject_GetItem ( $7 , temp[$3] )) == 0) goto $4;',
'}',
'CLEARTEMP($3);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && ($2 = PyInt_AS_LONG ( $1 )) > INT_MIN ) {',
'$6 = $2 - 1;',
'if ( $6 < 0) {',
'$6 += PyList_GET_SIZE($7);',
'}',
'if ((temp[$8] = PyList_GetItem ( $7 , $6 )) == 0) goto $4;',
'Py_INCREF(temp[$8]);',
'temp[$3] = 0;',
'} else {',
'if ((temp[$3] = PyNumber_Subtract ( $1 , $5 )) == 0) goto $4;',
'if ((temp[$8] = PyObject_GetItem ( $7 , temp[$3] )) == 0) goto $4;',
'CLEARTEMP($3);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 )) {',
'long_$2 = PyInt_AS_LONG ( $1 );',
'long_$2 = Py_ARITHMETIC_RIGHT_SHIFT(long, long_$2, $3);',
'temp[$5] = PyInt_FromLong (long_$2);',
'} else {',
'if ((temp[$5] = PyNumber_Rshift($1, consts[$4])) == 0) goto $6;',
'}',
'if (PyInt_CheckExact( temp[$5] )) {',
'temp[$0] = PyInt_FromLong ($8);',
'} else {',
'if ((temp[$0] = $9 ( temp[$5] , consts[$7] )) == 0) goto $6;',
'}',
'CLEARTEMP($5);'), v2):
fr = ('PyInt_AS_LONG ( temp[' + v2[5] +'] )')
if fr in v2[8]:
v2[8] = v2[8].replace(fr, 'long_' + v2[2])
TxRepl(o, i, ('if (PyInt_CheckExact( $1 )) {',
'long_$2 = PyInt_AS_LONG ( $1 );',
'long_$2 = Py_ARITHMETIC_RIGHT_SHIFT(long, long_$2, $3);',
'temp[$0] = PyInt_FromLong ($8);',
'} else {',
'if ((temp[$5] = PyNumber_Rshift($1, consts[$4])) == 0) goto $6;',
'if ((temp[$0] = $9 ( temp[$5] , consts[$7] )) == 0) goto $6;',
'CLEARTEMP($5);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 )) {',
'$2 = PyInt_AS_LONG ( $1 );',
'if ( $2 < 0) {',
'$2 += PyList_GET_SIZE($0);',
'}',
'if ((temp[$4] = PyList_GetItem ( $0 , $2 )) == 0) goto $3;',
'Py_INCREF(temp[$4]);',
'} else {',
'if ((temp[$4] = PyObject_GetItem ( $0 , $1 )) == 0) goto $3;',
'}',
'if ((int_$11 = PyObject_RichCompareBool ( temp[$4] , $5 , $6 )) == -1) goto $3;',
'CLEARTEMP($4);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $1 )) {',
'$2 = PyInt_AS_LONG ( $1 );',
'if ( $2 < 0) {',
'$2 += PyList_GET_SIZE($0);',
'}',
'if ((temp[$4] = PyList_GetItem ( $0 , $2 )) == 0) goto $3;',
'if ((int_$11 = PyObject_RichCompareBool ( temp[$4] , $5 , $6 )) == -1) goto $3;',
'temp[$4] = 0;',
'} else {',
'if ((temp[$4] = PyObject_GetItem ( $0 , $1 )) == 0) goto $3;',
'if ((int_$11 = PyObject_RichCompareBool ( temp[$4] , $5 , $6 )) == -1) goto $3;',
'CLEARTEMP($4);',
'}'), v2)
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 )) {',
'$2 = PyInt_AS_LONG ( $1 );',
'$3 = $2 - 1;',
'if (( $3 ^ $2 ) < 0 && ( $3 ^~ 1 ) < 0) goto $4 ;',
'temp[$5] = PyInt_FromLong ( $3 );',
'} else if (PyFloat_CheckExact( $1 )) {',
'temp[$5] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) - ((double)1));',
'} else { $4 :;',
'if ((temp[$5] = PyNumber_Subtract ( $1 , consts[$7] )) == 0) goto $6;',
'}'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && ($2 = PyInt_AS_LONG ( $1 )) > INT_MIN ) {',
'temp[$5] = PyInt_FromLong ( $2 - 1 );',
'} else if (PyFloat_CheckExact( $1 )) {',
'temp[$5] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) - ((double)1));',
'} else {',
'if ((temp[$5] = PyNumber_Subtract ( $1 , consts[$7] )) == 0) goto $6;',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 )) {',
'$2 = PyInt_AS_LONG ( $1 );',
'$3 = $2 - 1;',
'if (( $3 ^ $2 ) < 0 && ( $3 ^~ 1 ) < 0) goto $4 ;',
'temp[$5] = PyInt_FromLong ( $3 );',
'} else { $4 :;',
'if ((temp[$5] = PyNumber_Subtract ( $1 , consts[$7] )) == 0) goto $6;',
'}'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && ($2 = PyInt_AS_LONG ( $1 )) > INT_MIN ) {',
'temp[$5] = PyInt_FromLong ( $2 - 1 );',
'} else {',
'if ((temp[$5] = PyNumber_Subtract ( $1 , consts[$7] )) == 0) goto $6;',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 )) {',
'$2 = PyInt_AS_LONG ( $1 );',
'$3 = $2 - 1;',
'if (( $3 ^ $2 ) < 0 && ( $3 ^~ 1 ) < 0) goto $4 ;',
'temp[$5] = PyInt_FromLong ( $3 );',
'} else if (PyFloat_CheckExact( $1 )) {',
'temp[$5] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) - ((double)1));',
'} else { $4 :;',
'if ((temp[$5] = PyNumber_InPlaceSubtract ( $1 , consts[$7] )) == 0) goto $6;',
'}'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && ($2 = PyInt_AS_LONG ( $1 )) > INT_MIN ) {',
'temp[$5] = PyInt_FromLong ( $2 - 1 );',
'} else if (PyFloat_CheckExact( $1 )) {',
'temp[$5] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) - ((double)1));',
'} else {',
'if ((temp[$5] = PyNumber_InPlaceSubtract ( $1 , consts[$7] )) == 0) goto $6;',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 )) {',
'$2 = PyInt_AS_LONG ( $1 );',
'$3 = $2 - 1;',
'if (( $3 ^ $2 ) < 0 && ( $3 ^~ 1 ) < 0) goto $4 ;',
'temp[$5] = PyInt_FromLong ( $3 );',
'} else { $4 :;',
'if ((temp[$5] = PyNumber_InPlaceSubtract ( $1 , consts[$7] )) == 0) goto $6;',
'}'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && ($2 = PyInt_AS_LONG ( $1 )) > INT_MIN ) {',
'temp[$5] = PyInt_FromLong ( $2 - 1 );',
'} else {',
'if ((temp[$5] = PyNumber_InPlaceSubtract ( $1 , consts[$7] )) == 0) goto $6;',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 )) {',
'$2 = PyInt_AS_LONG ( $1 );',
'$3 = $2 - $0;',
'if (( $3 ^ $2 ) < 0 && ( $3 ^~ $0 ) < 0) goto $4 ;',
'temp[$5] = PyInt_FromLong ( $3 );',
'} else if (PyFloat_CheckExact( $1 )) {',
'temp[$5] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) - ((double)$0));',
'} else { $4 :;',
'if ((temp[$5] = PyNumber_Subtract ( $1 , consts[$7] )) == 0) goto $6;',
'}'), v2) and int(v2[0]) > 0:
v2[8] = str(int(v2[0])-1)
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && ($2 = PyInt_AS_LONG ( $1 )) > (INT_MIN+$8) ) {',
'temp[$5] = PyInt_FromLong ( $2 - $0 );',
'} else if (PyFloat_CheckExact( $1 )) {',
'temp[$5] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) - ((double)$0));',
'} else {',
'if ((temp[$5] = PyNumber_Subtract ( $1 , consts[$7] )) == 0) goto $6;',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 )) {',
'$2 = PyInt_AS_LONG ( $1 );',
'$3 = $2 - $0;',
'if (( $3 ^ $2 ) < 0 && ( $3 ^~ $0 ) < 0) goto $4 ;',
'temp[$5] = PyInt_FromLong ( $3 );',
'} else { $4 :;',
'if ((temp[$5] = PyNumber_Subtract ( $1 , consts[$7] )) == 0) goto $6;',
'}'), v2) and int(v2[0]) > 0:
v2[8] = str(int(v2[0])-1)
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && ($2 = PyInt_AS_LONG ( $1 )) > (INT_MIN+$8) ) {',
'temp[$5] = PyInt_FromLong ( $2 - $0 );',
'} else {',
'if ((temp[$5] = PyNumber_Subtract ( $1 , consts[$7] )) == 0) goto $6;',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 )) {',
'$2 = PyInt_AS_LONG ( $1 );',
'$3 = $2 - $0;',
'if (( $3 ^ $2 ) < 0 && ( $3 ^~ $0 ) < 0) goto $4 ;',
'temp[$5] = PyInt_FromLong ( $3 );',
'} else if (PyFloat_CheckExact( $1 )) {',
'temp[$5] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) - ((double)$0));',
'} else { $4 :;',
'if ((temp[$5] = PyNumber_InPlaceSubtract ( $1 , consts[$7] )) == 0) goto $6;',
'}'), v2) and int(v2[0]) > 0:
v2[8] = str(int(v2[0])-1)
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && ($2 = PyInt_AS_LONG ( $1 )) > (INT_MIN+$8) ) {',
'temp[$5] = PyInt_FromLong ( $2 - $0 );',
'} else if (PyFloat_CheckExact( $1 )) {',
'temp[$5] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) - ((double)$0));',
'} else {',
'if ((temp[$5] = PyNumber_InPlaceSubtract ( $1 , consts[$7] )) == 0) goto $6;',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 )) {',
'$2 = PyInt_AS_LONG ( $1 );',
'$3 = $2 - $0;',
'if (( $3 ^ $2 ) < 0 && ( $3 ^~ $0 ) < 0) goto $4 ;',
'temp[$5] = PyInt_FromLong ( $3 );',
'} else { $4 :;',
'if ((temp[$5] = PyNumber_InPlaceSubtract ( $1 , consts[$7] )) == 0) goto $6;',
'}'), v2) and int(v2[0]) > 0:
v2[8] = str(int(v2[0])-1)
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && ($2 = PyInt_AS_LONG ( $1 )) > (INT_MIN+$8) ) {',
'temp[$5] = PyInt_FromLong ( $2 - $0 );',
'} else {',
'if ((temp[$5] = PyNumber_InPlaceSubtract ( $1 , consts[$7] )) == 0) goto $6;',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( temp[$1] )) {',
'$2 = PyInt_AS_LONG ( temp[$1] );',
'$3 = $2 - $0;',
'if (( $3 ^ $2 ) < 0 && ( $3 ^~ $0 ) < 0) goto $4 ;',
'temp[$5] = PyInt_FromLong ( $3 );',
'} else { $4 :;',
'if ((temp[$5] = PyNumber_Subtract ( temp[$1] , consts[$7] )) == 0) goto $6;',
'}',
'CLEARTEMP($1);'), v2) and int(v2[0]) > 0:
v2[8] = str(int(v2[0])-1)
TxRepl(o, i, ('if (PyInt_CheckExact( temp[$1] ) && ($2 = PyInt_AS_LONG ( temp[$1] )) > (INT_MIN+$8) ) {',
'temp[$5] = PyInt_FromLong ( $2 - $0 );',
'} else {',
'if ((temp[$5] = PyNumber_Subtract ( temp[$1] , consts[$7] )) == 0) goto $6;',
'}',
'CLEARTEMP($1);'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( temp[$1] )) {',
'$2 = PyInt_AS_LONG ( temp[$1] );',
'$3 = $2 - $0;',
'if (( $3 ^ $2 ) < 0 && ( $3 ^~ $0 ) < 0) goto $4 ;',
'temp[$5] = PyInt_FromLong ( $3 );',
'} else { $4 :;',
'if ((temp[$5] = PyNumber_InPlaceSubtract ( temp[$1] , consts[$7] )) == 0) goto $6;',
'}',
'CLEARTEMP($1);'), v2) and int(v2[0]) > 0:
v2[8] = str(int(v2[0])-1)
TxRepl(o, i, ('if (PyInt_CheckExact( temp[$1] ) && ($2 = PyInt_AS_LONG ( temp[$1] )) > (INT_MIN+$8) ) {',
'temp[$5] = PyInt_FromLong ( $2 - $0 );',
'} else {',
'if ((temp[$5] = PyNumber_InPlaceSubtract ( temp[$1] , consts[$7] )) == 0) goto $6;',
'}',
'CLEARTEMP($1);'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 )) {',
'$2 = PyInt_AS_LONG ( $1 );',
'$3 = $2 + 1;',
'if (( $3 ^ $2 ) < 0 && ( $3 ^ 1 ) < 0) goto $4 ;',
'temp[$5] = PyInt_FromLong ( $3 );',
'} else if (PyFloat_CheckExact( $1 )) {',
'temp[$5] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) + ((double)1));',
'} else { $4 :;',
'if ((temp[$5] = PyNumber_Add ( $1 , consts[$7] )) == 0) goto $6;',
'}'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && ($2 = PyInt_AS_LONG ( $1 )) < INT_MAX ) {',
'temp[$5] = PyInt_FromLong ( $2 + 1 );',
'} else if (PyFloat_CheckExact( $1 )) {',
'temp[$5] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) + ((double)1));',
'} else {',
'if ((temp[$5] = PyNumber_Add ( $1 , consts[$7] )) == 0) goto $6;',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 )) {',
'$2 = PyInt_AS_LONG ( $1 );',
'$3 = $2 + 1;',
'if (( $3 ^ $2 ) < 0 && ( $3 ^ 1 ) < 0) goto $4 ;',
'temp[$5] = PyInt_FromLong ( $3 );',
'} else { $4 :;',
'if ((temp[$5] = PyNumber_Add ( $1 , consts[$7] )) == 0) goto $6;',
'}'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && ($2 = PyInt_AS_LONG ( $1 )) < INT_MAX ) {',
'temp[$5] = PyInt_FromLong ( $2 + 1 );',
'} else {',
'if ((temp[$5] = PyNumber_Add ( $1 , consts[$7] )) == 0) goto $6;',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 )) {',
'$2 = PyInt_AS_LONG ( $1 );',
'$3 = $2 + 1;',
'if (( $3 ^ $2 ) < 0 && ( $3 ^ 1 ) < 0) goto $4 ;',
'temp[$5] = PyInt_FromLong ( $3 );',
'} else if (PyFloat_CheckExact( $1 )) {',
'temp[$5] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) + ((double)1));',
'} else { $4 :;',
'if ((temp[$5] = PyNumber_InPlaceAdd ( $1 , consts[$7] )) == 0) goto $6;',
'}'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && ($2 = PyInt_AS_LONG ( $1 )) < INT_MAX ) {',
'temp[$5] = PyInt_FromLong ( $2 + 1 );',
'} else if (PyFloat_CheckExact( $1 )) {',
'temp[$5] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) + ((double)1));',
'} else {',
'if ((temp[$5] = PyNumber_InPlaceAdd ( $1 , consts[$7] )) == 0) goto $6;',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 )) {',
'$2 = PyInt_AS_LONG ( $1 );',
'$3 = $2 + 1;',
'if (( $3 ^ $2 ) < 0 && ( $3 ^ 1 ) < 0) goto $4 ;',
'temp[$5] = PyInt_FromLong ( $3 );',
'} else { $4 :;',
'if ((temp[$5] = PyNumber_InPlaceAdd ( $1 , consts[$7] )) == 0) goto $6;',
'}'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && ($2 = PyInt_AS_LONG ( $1 )) < INT_MAX ) {',
'temp[$5] = PyInt_FromLong ( $2 + 1 );',
'} else {',
'if ((temp[$5] = PyNumber_InPlaceAdd ( $1 , consts[$7] )) == 0) goto $6;',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 )) {',
'$2 = PyInt_AS_LONG ( $1 );',
'$3 = $2 + $0;',
'if (( $3 ^ $2 ) < 0 && ( $3 ^ $0 ) < 0) goto $4 ;',
'temp[$5] = PyInt_FromLong ( $3 );',
'} else if (PyFloat_CheckExact( $1 )) {',
'temp[$5] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) + ((double)$0));',
'} else { $4 :;',
'if ((temp[$5] = PyNumber_Add ( $1 , consts[$7] )) == 0) goto $6;',
'}'), v2) and int(v2[0]) > 0:
v2[8] = str(int(v2[0])-1)
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && ($2 = PyInt_AS_LONG ( $1 )) < (INT_MAX-$8) ) {',
'temp[$5] = PyInt_FromLong ( $2 + $0 );',
'} else if (PyFloat_CheckExact( $1 )) {',
'temp[$5] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) + ((double)$0));',
'} else {',
'if ((temp[$5] = PyNumber_Add ( $1 , consts[$7] )) == 0) goto $6;',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 )) {',
'$2 = PyInt_AS_LONG ( $1 );',
'$3 = $2 + $0;',
'if (( $3 ^ $2 ) < 0 && ( $3 ^ $0 ) < 0) goto $4 ;',
'temp[$5] = PyInt_FromLong ( $3 );',
'} else { $4 :;',
'if ((temp[$5] = PyNumber_Add ( $1 , consts[$7] )) == 0) goto $6;',
'}'), v2) and int(v2[0]) > 0:
v2[8] = str(int(v2[0])-1)
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && ($2 = PyInt_AS_LONG ( $1 )) < (INT_MAX-$8) ) {',
'temp[$5] = PyInt_FromLong ( $2 + $0 );',
'} else {',
'if ((temp[$5] = PyNumber_Add ( $1 , consts[$7] )) == 0) goto $6;',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( temp[$1] )) {',
'temp[$2] = PyInt_FromLong ($3);',
'} else {',
'if ((temp[$2] = $5) == 0) goto label_$11;',
'}',
'CLEARTEMP($1);',
'long_$4 = PyInt_AsLong ( temp[$2] );',
'CLEARTEMP($2);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( temp[$1] )) {',
'long_$4 = ($3);',
'} else {',
'if ((temp[$2] = $5) == 0) goto label_$11;',
'long_$4 = PyInt_AsLong ( temp[$2] );',
'CLEARTEMP($2);',
'}',
'CLEARTEMP($1);'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $2 ) && ($3 = PyInt_AS_LONG ( $2 )) < INT_MAX ) {',
'temp[$0] = PyInt_FromLong ( $3 + 1 );',
'} else if (PyFloat_CheckExact( $2 )) {',
'temp[$0] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($2) + ((double)1));',
'} else {',
'if ((temp[$0] = PyNumber_Add ( $2 , $6 )) == 0) goto $5;',
'}',
'if (PyInt_CheckExact( temp[$0] )) {',
'$4 = PyInt_AS_LONG ( temp[$0] );',
'if ( $4 < 0) {',
'$4 += PyList_GET_SIZE(GETLOCAL(cmds));',
'}',
'if ((temp[$1] = PyList_GetItem ( GETLOCAL(cmds) , $4 )) == 0) goto $5;',
'Py_INCREF(temp[$1]);',
'} else {',
'if ((temp[$1] = PyObject_GetItem ( GETLOCAL(cmds) , temp[$0] )) == 0) goto $5;',
'}',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $2 ) && ($3 = PyInt_AS_LONG ( $2 )) < INT_MAX ) {',
'$4 = $3 + 1;',
'if ( $4 < 0) {',
'$4 += PyList_GET_SIZE(GETLOCAL(cmds));',
'}',
'if ((temp[$1] = PyList_GetItem ( GETLOCAL(cmds) , $4 )) == 0) goto $5;',
'Py_INCREF(temp[$1]);',
'} else {',
'if ((temp[$0] = PyNumber_Add ( $2 , $6 )) == 0) goto $5;',
'if ((temp[$1] = PyObject_GetItem ( GETLOCAL(cmds) , temp[$0] )) == 0) goto $5;',
'CLEARTEMP($0);'
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $2 ) && ($3 = PyInt_AS_LONG ( $2 )) < INT_MAX ) {',
'temp[$0] = PyInt_FromLong ( $3 + 1 );',
'} else {',
'if ((temp[$0] = PyNumber_Add ( $2 , $6 )) == 0) goto $5;',
'}',
'if (PyInt_CheckExact( temp[$0] )) {',
'$4 = PyInt_AS_LONG ( temp[$0] );',
'if ( $4 < 0) {',
'$4 += PyList_GET_SIZE(GETLOCAL(cmds));',
'}',
'if ((temp[$1] = PyList_GetItem ( GETLOCAL(cmds) , $4 )) == 0) goto $5;',
'Py_INCREF(temp[$1]);',
'} else {',
'if ((temp[$1] = PyObject_GetItem ( GETLOCAL(cmds) , temp[$0] )) == 0) goto $5;',
'}',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $2 ) && ($3 = PyInt_AS_LONG ( $2 )) < INT_MAX ) {',
'$4 = $3 + 1;',
'if ( $4 < 0) {',
'$4 += PyList_GET_SIZE(GETLOCAL(cmds));',
'}',
'if ((temp[$1] = PyList_GetItem ( GETLOCAL(cmds) , $4 )) == 0) goto $5;',
'Py_INCREF(temp[$1]);',
'} else {',
'if ((temp[$0] = PyNumber_Add ( $2 , $6 )) == 0) goto $5;',
'if ((temp[$1] = PyObject_GetItem ( GETLOCAL(cmds) , temp[$0] )) == 0) goto $5;',
'CLEARTEMP($0);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $3 ) && ($4 = PyInt_AS_LONG ( $3 )) < INT_MAX ) {',
'temp[$1] = PyInt_FromLong ( $4 + 1 );',
'} else if (PyFloat_CheckExact( $3 )) {',
'temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($3) + ((double)1));',
'} else {',
'if ((temp[$1] = PyNumber_Add ( $3 , $7 )) == 0) goto $5;',
'}',
'if ((temp[$2] = _PyEval_ApplySlice ( $6 , temp[$1] , NULL )) == 0) goto $5;',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $3 ) && ($4 = PyInt_AS_LONG ( $3 )) < INT_MAX ) {',
'if ((temp[$2] = PySequence_GetSlice ( $6 , $4 + 1 , PY_SSIZE_T_MAX )) == 0) goto $5;',
'} else {',
'if ((temp[$1] = PyNumber_Add ( $3 , $7 )) == 0) goto $5;',
'if ((temp[$2] = _PyEval_ApplySlice ( $6 , temp[$1] , NULL )) == 0) goto $5;',
'CLEARTEMP($1);',
'}'), v2)
return True
if TxMatch(o, i, """
if ($1) {
>0
temp[$10] = PyInt_FromLong ( $15 );
<1
} else {
>2
if ((temp[$10] = $14) == 0) goto label_$12;
<3
}
<4
if ((temp[$11] = _PyEval_ApplySlice ( $16 , temp[$10] , NULL )) == 0) goto label_$12;
<5
CLEARTEMP($10);
""", v2):
TxRepl(o, i, """
if ($1) {
>0
<1
if ((temp[$11] = PySequence_GetSlice ( $16 , $15 , PY_SSIZE_T_MAX )) == 0) goto label_$12;
<4
<5
} else {
>2
if ((temp[$10] = $14) == 0) goto label_$12;
<3
<4
if ((temp[$11] = _PyEval_ApplySlice ( $16 , temp[$10] , NULL )) == 0) goto label_$12;
<5
CLEARTEMP($10);
}
""", v2)
return True
if TxMatch(o, i, """
if ($10) {
>0
if ($11) goto label_$4 ;
temp[$4] = PyInt_FromLong ($12);
<2
} else if ($14) {
>5
temp[$4] = PyFloat_FromDouble($15);
<3
} else { label_$4 :;
>6
if ((temp[$4] = PyNumber_$18 ($16)) == 0) goto label_$0;
<4
}
<1
if ((temp[$17] = PyObject_GetIter ( temp[$4] )) == 0) goto label_$0;
CLEARTEMP($4);
""", v2):
TxRepl(o, i, """
>6
if ((temp[$4] = PyNumber_$18 ($16)) == 0) goto label_$0;
<4
<1
if ((temp[$17] = PyObject_GetIter ( temp[$4] )) == 0) goto label_$0;
CLEARTEMP($4);
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $0 ) && (long_$1 = PyInt_AS_LONG ( $0 )) < (INT_MAX-$2) ) {
temp[$5] = PyInt_FromLong ( long_$1 + $3 );
} else {
if ((temp[$5] = PyNumber_Add ( $0 , $4 )) == 0) goto label_$7;
}
if ((temp[$6] = _PyEval_ApplySlice ( $8 , $0 , temp[$5] )) == 0) goto label_$7;
CLEARTEMP($5);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $0 ) && (long_$1 = PyInt_AS_LONG ( $0 )) < (INT_MAX-$2) ) {
if ((temp[$6] = PySequence_GetSlice ( $8 , long_$1 , long_$1 + $3 )) == 0) goto label_$7;
} else {
if ((temp[$5] = PyNumber_Add ( $0 , $4 )) == 0) goto label_$7;
if ((temp[$6] = _PyEval_ApplySlice ( $8 , $0 , temp[$5] )) == 0) goto label_$7;
CLEARTEMP($5);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $0 )) {
long_$4 = PyInt_AS_LONG ( $1 );
long_$5 = PyInt_AS_LONG ( $0 );
long_$6 = long_$4 $11 long_$5;
if ($10) goto label_$2 ;
temp[$7] = PyInt_FromLong ( long_$6 );
} else { label_$2 :;
if ((temp[$7] = PyNumber_$12 ( $1 , $0 )) == 0) goto label_$3;
}
if ((temp[$8] = _PyEval_ApplySlice ( $9 , $1 , temp[$7] )) == 0) goto label_$3;
CLEARTEMP($7);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $0 )) {
long_$4 = PyInt_AS_LONG ( $1 );
long_$5 = PyInt_AS_LONG ( $0 );
long_$6 = long_$4 $11 long_$5;
if ($10) goto label_$2 ;
if ((temp[$8] = PySequence_GetSlice ( $9 , long_$4 , long_$6 )) == 0) goto label_$3;
} else { label_$2 :;
if ((temp[$7] = PyNumber_$12 ( $1 , $0 )) == 0) goto label_$3;
if ((temp[$8] = _PyEval_ApplySlice ( $9 , $1 , temp[$7] )) == 0) goto label_$3;
CLEARTEMP($7);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $0 )) {
long_$5 = PyInt_AS_LONG ( $0 );
long_$6 = $8;
long_$7 = long_$5 + long_$6;
if (( long_$7 ^ long_$5 ) < 0 && ( long_$7 ^ long_$6 ) < 0) goto label_$3 ;
temp[$9] = PyInt_FromLong ( long_$7 );
} else { label_$3 :;
temp[$10] = PyInt_FromLong ($8);
if ((temp[$9] = PyNumber_Add ( $0 , temp[$10] )) == 0) goto label_$4;
CLEARTEMP($10);
}
if (($1 = _PyEval_ApplySlice ( $2 , $0 , temp[$9] )) == 0) goto label_$4;
CLEARTEMP($9);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $0 )) {
long_$5 = PyInt_AS_LONG ( $0 );
long_$6 = $8;
long_$7 = long_$5 + long_$6;
if (( long_$7 ^ long_$5 ) < 0 && ( long_$7 ^ long_$6 ) < 0) goto label_$3 ;
if (($1 = PySequence_GetSlice ( $2 , long_$5 , long_$7 )) == 0) goto label_$4;
} else { label_$3 :;
temp[$10] = PyInt_FromLong ($8);
if ((temp[$9] = PyNumber_Add ( $0 , temp[$10] )) == 0) goto label_$4;
CLEARTEMP($10);
if (($1 = _PyEval_ApplySlice ( $2 , $0 , temp[$9] )) == 0) goto label_$4;
CLEARTEMP($9);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $0 ) && (long_$1 = PyInt_AS_LONG ( $0 )) $5 $2 ) {
temp[$3] = PyInt_FromLong ($4);
} else {
if ((temp[$3] = PyNumber_$7 ( $0 , $6 )) == 0) goto label_$8;
}
if ((temp[$9] = _PyEval_ApplySlice ( $10 , $11 , temp[$3] )) == 0) goto label_$8;
CLEARTEMP($3);
""", v2) and v2[0] != v2[11] and not 'NULL' in v2[11]:
TxRepl(o, i, """
if (PyInt_CheckExact( $11 ) && PyInt_CheckExact( $0 ) && (long_$1 = PyInt_AS_LONG ( $0 )) $5 $2 ) {
if ((temp[$9] = PySequence_GetSlice ( $10 , PyInt_AS_LONG ( $11 ) , $4 )) == 0) goto label_$8;
} else {
if ((temp[$3] = PyNumber_$7 ( $0 , $6 )) == 0) goto label_$8;
if ((temp[$9] = _PyEval_ApplySlice ( $10 , $11 , temp[$3] )) == 0) goto label_$8;
CLEARTEMP($3);
}
""", v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $3 ) && ($4 = PyInt_AS_LONG ( $3 )) < INT_MAX ) {',
'temp[$1] = PyInt_FromLong ( $4 + 1 );',
'} else {',
'if ((temp[$1] = PyNumber_Add ( $3 , $7 )) == 0) goto $5;',
'}',
'if ((temp[$2] = _PyEval_ApplySlice ( $6 , temp[$1] , NULL )) == 0) goto $5;',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $3 ) && ($4 = PyInt_AS_LONG ( $3 )) < INT_MAX ) {',
'if ((temp[$2] = PySequence_GetSlice ( $6 , $4 + 1 , PY_SSIZE_T_MAX )) == 0) goto $5;',
'} else {',
'if ((temp[$1] = PyNumber_Add ( $3 , $7 )) == 0) goto $5;',
'if ((temp[$2] = _PyEval_ApplySlice ( $6 , temp[$1] , NULL )) == 0) goto $5;',
'CLEARTEMP($1);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $3 ) && ($5 = PyInt_AS_LONG ( $3 )) > INT_MIN ) {',
'temp[$1] = PyInt_FromLong ( $5 - 1 );',
'} else if (PyFloat_CheckExact( $3 )) {',
'temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($3) - ((double)1));',
'} else {',
'if ((temp[$1] = PyNumber_Subtract ( $3 , $4 )) == 0) goto $6;',
'}',
'if (($8 = PyObject_Size ( $10 )) == -1) goto $6;',
'if (PyInt_CheckExact( temp[$1] )) {',
'$9 = PyInt_AS_LONG ( temp[$1] ) $15 $8;',
'} else {',
'if ((temp[$2] = PyInt_FromSsize_t($8)) == 0) goto $6;',
'if (($9 = PyObject_RichCompareBool ( temp[$1] , temp[$2] , Py_$7 )) == -1) goto $6;',
'CLEARTEMP($2);',
'}',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $3 ) && ($5 = PyInt_AS_LONG ( $3 )) > INT_MIN ) {',
'if (($8 = PyObject_Size ( $10 )) == -1) goto $6;',
'$9 = ($5 - 1) $15 $8;',
'} else {',
'if ((temp[$1] = PyNumber_Subtract ( $3 , $4 )) == 0) goto $6;',
'if (($8 = PyObject_Size ( $10 )) == -1) goto $6;',
'if ((temp[$2] = PyInt_FromSsize_t($8)) == 0) goto $6;',
'if (($9 = PyObject_RichCompareBool ( temp[$1] , temp[$2] , Py_$7 )) == -1) goto $6;',
'CLEARTEMP($2);',
'CLEARTEMP($1);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $3 ) && ($5 = PyInt_AS_LONG ( $3 )) > INT_MIN ) {',
'temp[$1] = PyInt_FromLong ( $5 - 1 );',
'} else {',
'if ((temp[$1] = PyNumber_Subtract ( $3 , $4 )) == 0) goto $6;',
'}',
'if (($8 = PyObject_Size ( $10 )) == -1) goto $6;',
'if (PyInt_CheckExact( temp[$1] )) {',
'$9 = PyInt_AS_LONG ( temp[$1] ) $15 $8;',
'} else {',
'if ((temp[$2] = PyInt_FromSsize_t($8)) == 0) goto $6;',
'if (($9 = PyObject_RichCompareBool ( temp[$1] , temp[$2] , Py_$7 )) == -1) goto $6;',
'CLEARTEMP($2);',
'}',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $3 ) && ($5 = PyInt_AS_LONG ( $3 )) > INT_MIN ) {',
'if (($8 = PyObject_Size ( $10 )) == -1) goto $6;',
'$9 = ($5 - 1) $15 $8;',
'} else {',
'if ((temp[$1] = PyNumber_Subtract ( $3 , $4 )) == 0) goto $6;',
'if (($8 = PyObject_Size ( $10 )) == -1) goto $6;',
'if ((temp[$2] = PyInt_FromSsize_t($8)) == 0) goto $6;',
'if (($9 = PyObject_RichCompareBool ( temp[$1] , temp[$2] , Py_$7 )) == -1) goto $6;',
'CLEARTEMP($2);',
'CLEARTEMP($1);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $6 ) && ($17 = PyInt_AS_LONG ( $6 )) > INT_MIN ) {',
'temp[$1] = PyInt_FromLong ( $17 - 1 );',
'} else if (PyFloat_CheckExact( $6 )) {',
'temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($6) - ((double)1));',
'} else {',
'if ((temp[$1] = PyNumber_Subtract ( $6 , $10 )) == 0) goto $4;',
'}',
'if (($12 = PyObject_Size ( $11 )) == -1) goto $4;',
'if ((temp[$2] = PyInt_FromSsize_t ( $12 )) == 0) goto $4;',
'if (PyInt_CheckExact( temp[$1] )) {',
'$7 = PyInt_AS_LONG ( temp[$1] );',
'$8 = PyInt_AS_LONG ( temp[$2] );',
'$9 = $7 - $8;',
'if (( $9 ^ $7 ) < 0 && ( $9 ^~ $8 ) < 0) goto $5 ;',
'temp[$3] = PyInt_FromLong ( $9 );',
'} else if (PyFloat_CheckExact( temp[$1] )) {',
'temp[$3] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$1]) - (double)PyInt_AS_LONG ( temp[$2] ));',
'} else { $5 :;',
'if ((temp[$3] = PyNumber_Subtract ( temp[$1] , temp[$2] )) == 0) goto $4;',
'}',
'CLEARTEMP($1);',
'CLEARTEMP($2);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $6 ) && ($7 = PyInt_AS_LONG ( $6 )) > INT_MIN ) {',
'$7 = $7 - 1;',
'if (($8 = PyObject_Size ( $11 )) == -1) goto $4;',
'$9 = $7 - $8;',
'if (( $9 ^ $7 ) < 0 && ( $9 ^~ $8 ) < 0) goto $5 ;',
'temp[$3] = PyInt_FromLong ( $9 );',
'} else { $5 :;',
'if ((temp[$1] = PyNumber_Subtract ( $6 , $10 )) == 0) goto $4;',
'if (($12 = PyObject_Size ( $11 )) == -1) goto $4;',
'if ((temp[$2] = PyInt_FromSsize_t ( $12 )) == 0) goto $4;',
'if ((temp[$3] = PyNumber_Subtract ( temp[$1] , temp[$2] )) == 0) goto $4;',
'}',
'CLEARTEMP($1);',
'CLEARTEMP($2);'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $2 ) && ($3 = PyInt_AS_LONG ( $2 )) > INT_MIN ) {',
'temp[$1] = PyInt_FromLong ( $3 - 1 );',
'} else if (PyFloat_CheckExact( $2 )) {',
'temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($2) - ((double)1));',
'} else {',
'if ((temp[$1] = PyNumber_Subtract ( $2 , $5 )) == 0) goto $4;',
'}',
'$6 = PyInt_AsSsize_t ( temp[$1] );',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $2 ) && ($3 = PyInt_AS_LONG ( $2 )) > INT_MIN ) {',
'$6 = $3 - 1;',
'} else {',
'if ((temp[$1] = PyNumber_Subtract ( $2 , $5 )) == 0) goto $4;',
'$6 = PyInt_AsSsize_t ( temp[$1] );',
'CLEARTEMP($1);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $2 ) && ($3 = PyInt_AS_LONG ( $2 )) > INT_MIN ) {',
'temp[$1] = PyInt_FromLong ( $3 - 1 );',
'} else {',
'if ((temp[$1] = PyNumber_Subtract ( $2 , $5 )) == 0) goto $4;',
'}',
'$6 = PyInt_AsSsize_t ( temp[$1] );',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $2 ) && ($3 = PyInt_AS_LONG ( $2 )) > INT_MIN ) {',
'$6 = $3 - 1;',
'} else {',
'if ((temp[$1] = PyNumber_Subtract ( $2 , $5 )) == 0) goto $4;',
'$6 = PyInt_AsSsize_t ( temp[$1] );',
'CLEARTEMP($1);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $2 )) {',
'$5 = PyInt_AS_LONG ( $2 );',
'$6 = 1 - $5;',
'if (( $6 ^ 1 ) < 0 && ( $6 ^~ $5 ) < 0) goto $3 ;',
'temp[$0] = PyInt_FromLong ( $6 );',
'} else if (PyFloat_CheckExact( $2 )) {',
'temp[$0] = PyFloat_FromDouble(((double)1) - PyFloat_AS_DOUBLE($2));',
'} else { $3 :;',
'if ((temp[$0] = PyNumber_Subtract ( $7 , $2 )) == 0) goto $4;',
'}',
'if (PyFloat_CheckExact( $2 ) && PyFloat_CheckExact( temp[$0] )) {',
'temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($2) * PyFloat_AS_DOUBLE(temp[$0]));',
'} else if (PyInt_CheckExact( $2 ) && PyInt_CheckExact( temp[$0] )) {',
'temp[$1] = PyInt_Type.tp_as_number->nb_multiply($2, temp[$0]);',
'} else {',
'if ((temp[$1] = PyNumber_Multiply ( $2 , temp[$0] )) == 0) goto $4;',
'}',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $2 )) {',
'$5 = PyInt_AS_LONG ( $2 );',
'$6 = 1 - $5;',
'if (( $6 ^ 1 ) < 0 && ( $6 ^~ $5 ) < 0) goto $3 ;',
'if ($6 != 0 && $5 == (($5 * $6) / $6)) {',
'temp[$1] = PyInt_FromLong ( $5 * $6 );',
'} else {',
'temp[$0] = PyInt_FromLong ( $6 );',
'temp[$1] = PyInt_Type.tp_as_number->nb_multiply($2, temp[$0]);',
'CLEARTEMP($0);',
'}',
'} else if (PyFloat_CheckExact( $2 )) {',
'temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($2) * (((double)1) - PyFloat_AS_DOUBLE($2)));',
'} else { $3 :;',
'if ((temp[$0] = PyNumber_Subtract ( $7 , $2 )) == 0) goto $4;',
'if ((temp[$1] = PyNumber_Multiply ( $2 , temp[$0] )) == 0) goto $4;',
'CLEARTEMP($0);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $3 ) && ($4 = PyInt_AS_LONG ( $3 )) < INT_MAX ) {',
'temp[$1] = PyInt_FromLong ( $4 + 1 );',
'} else if (PyFloat_CheckExact( $3 )) {',
'temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($3) + ((double)1));',
'} else {',
'if ((temp[$1] = PyNumber_Add ( $3 , $8 )) == 0) goto $7;',
'}',
'if (PyInt_CheckExact( temp[$1] )) {',
'$5 = PyInt_AS_LONG ( temp[$1] );',
'if ( $5 < 0) {',
'$5 += $10;',
'}',
'$6 = $11[$5];',
'temp[$2] = PyString_FromStringAndSize(&$6, 1);',
'} else {',
'if ((temp[$2] = PyObject_GetItem ( $9 , temp[$1] )) == 0) goto $7;',
'}',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $3 ) && ($4 = PyInt_AS_LONG ( $3 )) < INT_MAX ) {',
'$5 = $4 + 1;',
'if ( $5 < 0) {',
'$5 += $10;',
'}',
'$6 = $11[$5];',
'temp[$2] = PyString_FromStringAndSize(&$6, 1);',
'} else {',
'if ((temp[$1] = PyNumber_Add ( $3 , $8 )) == 0) goto $7;',
'if ((temp[$2] = PyObject_GetItem ( $9 , temp[$1] )) == 0) goto $7;',
'CLEARTEMP($1);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $3 ) && ($4 = PyInt_AS_LONG ( $3 )) < INT_MAX ) {',
'temp[$1] = PyInt_FromLong ( $4 + 1 );',
'} else {',
'if ((temp[$1] = PyNumber_Add ( $3 , $8 )) == 0) goto $7;',
'}',
'if (PyInt_CheckExact( temp[$1] )) {',
'$5 = PyInt_AS_LONG ( temp[$1] );',
'if ( $5 < 0) {',
'$5 += $10;',
'}',
'$6 = $11[$5];',
'temp[$2] = PyString_FromStringAndSize(&$6, 1);',
'} else {',
'if ((temp[$2] = PyObject_GetItem ( $9 , temp[$1] )) == 0) goto $7;',
'}',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $3 ) && ($4 = PyInt_AS_LONG ( $3 )) < INT_MAX ) {',
'$5 = $4 + 1;',
'if ( $5 < 0) {',
'$5 += $10;',
'}',
'$6 = $11[$5];',
'temp[$2] = PyString_FromStringAndSize(&$6, 1);',
'} else {',
'if ((temp[$1] = PyNumber_Add ( $3 , $8 )) == 0) goto $7;',
'if ((temp[$2] = PyObject_GetItem ( $9 , temp[$1] )) == 0) goto $7;',
'CLEARTEMP($1);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $2 ) && ($3 = PyInt_AS_LONG ( $2 )) < INT_MAX ) {',
'$3 = $3 + 1;',
'temp[$0] = PyInt_FromLong ( $3 );',
'if ((temp[$1] = _c_BINARY_SUBSCR_Int ( $5 , $3 , temp[$0] )) == 0) goto $4;',
'} else {',
'if ((temp[$0] = PyNumber_Add ( $2 , $6 )) == 0) goto $4;',
'if ((temp[$1] = PyObject_GetItem ( $5 , temp[$0] )) == 0) goto $4;',
'}',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $2 ) && ($3 = PyInt_AS_LONG ( $2 )) < INT_MAX ) {',
'$3 = $3 + 1;',
'if ((temp[$1] = __c_BINARY_SUBSCR_Int ( $5 , $3 )) == 0) goto $4;',
'} else {',
'if ((temp[$0] = PyNumber_Add ( $2 , $6 )) == 0) goto $4;',
'if ((temp[$1] = PyObject_GetItem ( $5 , temp[$0] )) == 0) goto $4;',
'CLEARTEMP($0);',
'}'), v2, ('__c_BINARY_SUBSCR_Int',))
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $2 ) && ($3 = PyInt_AS_LONG ( $2 )) > INT_MIN ) {',
'$3 = $3 - 1;',
'temp[$0] = PyInt_FromLong ( $3 );',
'if ((temp[$1] = _c_BINARY_SUBSCR_Int ( $5 , $3 , temp[$0] )) == 0) goto $4;',
'} else {',
'if ((temp[$0] = PyNumber_Subtract ( $2 , $6 )) == 0) goto $4;',
'if ((temp[$1] = PyObject_GetItem ( $5 , temp[$0] )) == 0) goto $4;',
'}',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $2 ) && ($3 = PyInt_AS_LONG ( $2 )) > INT_MIN ) {',
'$3 = $3 - 1;',
'if ((temp[$1] = __c_BINARY_SUBSCR_Int ( $5 , $3 )) == 0) goto $4;',
'} else {',
'if ((temp[$0] = PyNumber_Subtract ( $2 , $6 )) == 0) goto $4;',
'if ((temp[$1] = PyObject_GetItem ( $5 , temp[$0] )) == 0) goto $4;',
'CLEARTEMP($0);',
'}'), v2, ('__c_BINARY_SUBSCR_Int',))
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $2 ) && ($7 = PyInt_AS_LONG ( $2 )) < (INT_MAX-$4) ) {',
'temp[$0] = PyInt_FromLong ( $7 + $5 );',
'} else if (PyFloat_CheckExact( $2 )) {',
'temp[$0] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($2) + ((double)$5));',
'} else {',
'if ((temp[$0] = PyNumber_Add ( $2 , $6 )) == 0) goto $3;',
'}',
'if ((temp[$1] = PyObject_GetItem ( $9 , temp[$0] )) == 0) goto $3;',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $2 ) && ($7 = PyInt_AS_LONG ( $2 )) < (INT_MAX-$4) ) {',
'if ((temp[$1] = __c_BINARY_SUBSCR_Int ( $9 , $7 + $5 )) == 0) goto $3;',
'} else {',
'if ((temp[$0] = PyNumber_Add ( $2 , $6 )) == 0) goto $3;',
'if ((temp[$1] = PyObject_GetItem ( $9 , temp[$0] )) == 0) goto $3;',
'CLEARTEMP($0);',
'}'), v2, ('__c_BINARY_SUBSCR_Int',))
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $2 ) && ($7 = PyInt_AS_LONG ( $2 )) < (INT_MAX-$4) ) {',
'temp[$0] = PyInt_FromLong ( $7 + $5 );',
'} else {',
'if ((temp[$0] = PyNumber_Add ( $2 , $6 )) == 0) goto $3;',
'}',
'if ((temp[$1] = PyObject_GetItem ( $9 , temp[$0] )) == 0) goto $3;',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $2 ) && ($7 = PyInt_AS_LONG ( $2 )) < (INT_MAX-$4) ) {',
'if ((temp[$1] = __c_BINARY_SUBSCR_Int ( $9 , $7 + $5 )) == 0) goto $3;',
'} else {',
'if ((temp[$0] = PyNumber_Add ( $2 , $6 )) == 0) goto $3;',
'if ((temp[$1] = PyObject_GetItem ( $9 , temp[$0] )) == 0) goto $3;',
'CLEARTEMP($0);',
'}'), v2, ('__c_BINARY_SUBSCR_Int',))
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 ) && ($3 = PyInt_AS_LONG ( $1 )) < INT_MAX ) {',
'temp[$0] = PyInt_FromLong ( $3 + 1 );',
'} else if (PyFloat_CheckExact( $1 )) {',
'temp[$0] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) + ((double)1));',
'} else {',
'if ((temp[$0] = PyNumber_Add ( $1 , $5 )) == 0) goto $4;',
'}',
'SETLOCAL ( $2 , temp[$0] );',
'temp[$0] = 0;'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && ($3 = PyInt_AS_LONG ( $1 )) < INT_MAX ) {',
'temp[$0] = PyInt_FromLong ( $3 + 1 );',
'} else {',
'if ((temp[$0] = PyNumber_Add ( $1 , $5 )) == 0) goto $4;',
'}',
'SETLOCAL ( $2 , temp[$0] );',
'temp[$0] = 0;'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 ) && ($3 = PyInt_AS_LONG ( $1 )) < INT_MAX ) {',
'temp[$0] = PyInt_FromLong ( $3 + 1 );',
'} else if (PyFloat_CheckExact( $1 )) {',
'temp[$0] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) + ((double)1));',
'} else {',
'if ((temp[$0] = PyNumber_InPlaceAdd ( $1 , $5 )) == 0) goto $4;',
'}',
'SETLOCAL ( $2 , temp[$0] );',
'temp[$0] = 0;'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && ($3 = PyInt_AS_LONG ( $1 )) < INT_MAX ) {',
'temp[$0] = PyInt_FromLong ( $3 + 1 );',
'} else {',
'if ((temp[$0] = PyNumber_InPlaceAdd ( $1 , $5 )) == 0) goto $4;',
'}',
'SETLOCAL ( $2 , temp[$0] );',
'temp[$0] = 0;'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $2 ) && ($4 = PyInt_AS_LONG ( $2 )) < INT_MAX ) {',
'temp[$0] = PyInt_FromLong ( $4 + 1 );',
'} else if (PyFloat_CheckExact( $2 )) {',
'temp[$0] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($2) + ((double)1));',
'} else {',
'if ((temp[$0] = PyNumber_Add ( $2 , $5 )) == 0) goto $3;',
'}',
'if ((temp[$1] = _PyEval_ApplySlice ( $6 , $7 , temp[$0] )) == 0) goto $3;',
'CLEARTEMP(0);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $2 ) && ($4 = PyInt_AS_LONG ( $2 )) < INT_MAX ) {',
'temp[$0] = PyInt_FromLong ( $4 + 1 );',
'} else {',
'if ((temp[$0] = PyNumber_Add ( $2 , $5 )) == 0) goto $3;',
'}',
'if ((temp[$1] = _PyEval_ApplySlice ( $6 , $7 , temp[$0] )) == 0) goto $3;',
'CLEARTEMP(0);'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $5 ) && ($6 = PyInt_AS_LONG ( $5 )) > INT_MIN ) {',
'temp[$2] = PyInt_FromLong ( $6 - 1 );',
'} else if (PyFloat_CheckExact( $5 )) {',
'temp[$2] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($5) - ((double)1));',
'} else {',
'if ((temp[$2] = PyNumber_Subtract ( $5 , $15 )) == 0) goto $7;',
'}',
'if (PyInt_CheckExact( temp[$2] )) {',
'$11 = PyInt_AS_LONG ( temp[$2] );',
'if ( $11 < 0) {',
'$11 += PyList_GET_SIZE($8);',
'}',
'if ( PyList_SetItem ( $8 , $11 , temp[$1] ) == -1) goto $7;',
'} else {',
'if ( PyObject_SetItem ( $8 , temp[$2] , temp[$1] ) == -1) goto $7;',
'Py_DECREF(temp[$1]);',
'}',
'CLEARTEMP($2);',
'temp[$1] = 0;'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $5 ) && ($6 = PyInt_AS_LONG ( $5 )) > INT_MIN ) {',
'$11 = $6 - 1;',
'if ( $11 < 0) {',
'$11 += PyList_GET_SIZE($8);',
'}',
'if ( PyList_SetItem ( $8 , $11 , temp[$1] ) == -1) goto $7;',
'} else {',
'if ((temp[$2] = PyNumber_Subtract ( $5 , $15 )) == 0) goto $7;',
'if ( PyObject_SetItem ( $8 , temp[$2] , temp[$1] ) == -1) goto $7;',
'Py_DECREF(temp[$1]);',
'CLEARTEMP($2);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $5 ) && ($6 = PyInt_AS_LONG ( $5 )) > INT_MIN ) {',
'temp[$2] = PyInt_FromLong ( $6 - 1 );',
'} else {',
'if ((temp[$2] = PyNumber_Subtract ( $5 , $15 )) == 0) goto $7;',
'}',
'if (PyInt_CheckExact( temp[$2] )) {',
'$11 = PyInt_AS_LONG ( temp[$2] );',
'if ( $11 < 0) {',
'$11 += PyList_GET_SIZE($8);',
'}',
'if ( PyList_SetItem ( $8 , $11 , temp[$1] ) == -1) goto $7;',
'} else {',
'if ( PyObject_SetItem ( $8 , temp[$2] , temp[$1] ) == -1) goto $7;',
'Py_DECREF(temp[$1]);',
'}',
'CLEARTEMP($2);',
'temp[$1] = 0;'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $5 ) && ($6 = PyInt_AS_LONG ( $5 )) > INT_MIN ) {',
'$11 = $6 - 1;',
'if ( $11 < 0) {',
'$11 += PyList_GET_SIZE($8);',
'}',
'if ( PyList_SetItem ( $8 , $11 , temp[$1] ) == -1) goto $7;',
'} else {',
'if ((temp[$2] = PyNumber_Subtract ( $5 , $15 )) == 0) goto $7;',
'if ( PyObject_SetItem ( $8 , temp[$2] , temp[$1] ) == -1) goto $7;',
'Py_DECREF(temp[$1]);',
'CLEARTEMP($2);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $4 ) && PyInt_CheckExact( $5 )) {',
'$6 = PyInt_AS_LONG ( $4 );',
'$7 = PyInt_AS_LONG ( $5 );',
'$8 = $6 + $7;',
'if (( $8 ^ $6 ) < 0 && ( $8 ^ $7 ) < 0) goto $9 ;',
'temp[$2] = PyInt_FromLong ( $8 );',
'} else if (PyFloat_CheckExact( $4 ) && PyFloat_CheckExact( $5 )) {',
'temp[$2] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($4) + PyFloat_AS_DOUBLE($5));',
'} else { $9 :;',
'if ((temp[$2] = PyNumber_Add ( $4 , $5 )) == 0) goto $10;',
'}',
'if ((temp[$3] = PyObject_GetItem ( $1 , temp[$2] )) == 0) goto $10;',
'CLEARTEMP($2);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $4 ) && PyInt_CheckExact( $5 )) {',
'$6 = PyInt_AS_LONG ( $4 );',
'$7 = PyInt_AS_LONG ( $5 );',
'$8 = $6 + $7;',
'if (( $8 ^ $6 ) < 0 && ( $8 ^ $7 ) < 0) goto $9 ;',
'if ((temp[$3] = __c_BINARY_SUBSCR_Int ( $1 , $8 )) == 0) goto $10;',
'} else { $9 :;',
'if ((temp[$2] = PyNumber_Add ( $4 , $5 )) == 0) goto $10;',
'if ((temp[$3] = PyObject_GetItem ( $1 , temp[$2] )) == 0) goto $10;',
'CLEARTEMP($2);',
'}'), v2, ('__c_BINARY_SUBSCR_Int',))
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $4 ) && PyInt_CheckExact( $5 )) {',
'$6 = PyInt_AS_LONG ( $4 );',
'$7 = PyInt_AS_LONG ( $5 );',
'$8 = $6 + $7;',
'if (( $8 ^ $6 ) < 0 && ( $8 ^ $7 ) < 0) goto $9 ;',
'temp[$2] = PyInt_FromLong ( $8 );',
'} else { $9 :;',
'if ((temp[$2] = PyNumber_Add ( $4 , $5 )) == 0) goto $10;',
'}',
'if ((temp[$3] = PyObject_GetItem ( $1 , temp[$2] )) == 0) goto $10;',
'CLEARTEMP($2);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $4 ) && PyInt_CheckExact( $5 )) {',
'$6 = PyInt_AS_LONG ( $4 );',
'$7 = PyInt_AS_LONG ( $5 );',
'$8 = $6 + $7;',
'if (( $8 ^ $6 ) < 0 && ( $8 ^ $7 ) < 0) goto $9 ;',
'if ((temp[$3] = __c_BINARY_SUBSCR_Int ( $1 , $8 )) == 0) goto $10;',
'} else { $9 :;',
'if ((temp[$2] = PyNumber_Add ( $4 , $5 )) == 0) goto $10;',
'if ((temp[$3] = PyObject_GetItem ( $1 , temp[$2] )) == 0) goto $10;',
'CLEARTEMP($2);',
'}'), v2, ('__c_BINARY_SUBSCR_Int',))
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 ) && PyInt_CheckExact( $2 )) {',
'$4 = PyInt_AS_LONG ( $1 );',
'$5 = PyInt_AS_LONG ( $2 );',
'$6 = $4 - $5;',
'if (( $6 ^ $4 ) < 0 && ( $6 ^~ $5 ) < 0) goto $7 ;',
'temp[$3] = PyInt_FromLong ( $6 );',
'} else if (PyFloat_CheckExact( $1 ) && PyFloat_CheckExact( $2 )) {',
'temp[$3] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) - PyFloat_AS_DOUBLE($2));',
'} else { $7 :;',
'if ((temp[$3] = PyNumber_Subtract ( $1 , $2 )) == 0) goto $8;',
'}',
'if (($11 = PyObject_RichCompareBool ( temp[$3] , $9 , $12 )) == -1) goto $8;',
'CLEARTEMP($3);'), v2) and v2[12] in op_to_oper:
v2[15] = op_to_oper[v2[12]].strip()
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && PyInt_CheckExact( $2 ) && PyInt_CheckExact( $9 )) {',
'$4 = PyInt_AS_LONG ( $1 );',
'$5 = PyInt_AS_LONG ( $2 );',
'$6 = $4 - $5;',
'if (( $6 ^ $4 ) < 0 && ( $6 ^~ $5 ) < 0) goto $7 ;',
'$11 = $6 $15 PyInt_AS_LONG ( $9 );',
'} else if (PyFloat_CheckExact( $1 ) && PyFloat_CheckExact( $2 ) && PyFloat_CheckExact( $9 )) {',
'$11 = (PyFloat_AS_DOUBLE($1) - PyFloat_AS_DOUBLE($2)) $15 PyFloat_AS_DOUBLE($9);',
'} else { $7 :;',
'if ((temp[$3] = PyNumber_Subtract ( $1 , $2 )) == 0) goto $8;',
'if (($11 = PyObject_RichCompareBool ( temp[$3] , $9 , $12 )) == -1) goto $8;',
'CLEARTEMP($3);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 ) && PyInt_CheckExact( $2 )) {',
'$4 = PyInt_AS_LONG ( $1 );',
'$5 = PyInt_AS_LONG ( $2 );',
'$6 = $4 - $5;',
'if (( $6 ^ $4 ) < 0 && ( $6 ^~ $5 ) < 0) goto $7 ;',
'temp[$3] = PyInt_FromLong ( $6 );',
'} else { $7 :;',
'if ((temp[$3] = PyNumber_Subtract ( $1 , $2 )) == 0) goto $8;',
'}',
'if (($11 = PyObject_RichCompareBool ( temp[$3] , $9 , $12 )) == -1) goto $8;',
'CLEARTEMP($3);'), v2) and v2[12] in op_to_oper:
v2[15] = op_to_oper[v2[12]].strip()
TxRepl(o, i, ('if (PyInt_CheckExact( $1 ) && PyInt_CheckExact( $2 ) && PyInt_CheckExact( $9 )) {',
'$4 = PyInt_AS_LONG ( $1 );',
'$5 = PyInt_AS_LONG ( $2 );',
'$6 = $4 - $5;',
'if (( $6 ^ $4 ) < 0 && ( $6 ^~ $5 ) < 0) goto $7 ;',
'$11 = $6 $15 PyInt_AS_LONG ( $9 );',
'} else { $7 :;',
'if ((temp[$3] = PyNumber_Subtract ( $1 , $2 )) == 0) goto $8;',
'if (($11 = PyObject_RichCompareBool ( temp[$3] , $9 , $12 )) == -1) goto $8;',
'CLEARTEMP($3);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $2 ) && ($3 = PyInt_AS_LONG ( $2 )) < INT_MAX ) {',
'temp[$1] = PyInt_FromLong ( $3 + 1 );',
'} else if (PyFloat_CheckExact( $2 )) {',
'temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($2) + ((double)1));',
'} else {',
'if ((temp[$1] = PyNumber_Add ( $2 , $5 )) == 0) goto $4;',
'}',
'if (($6 = PyObject_RichCompareBool ( $7 , temp[$1] , $12 )) == -1) goto $4;',
'CLEARTEMP($1);'), v2) and v2[12] in op_to_oper:
v2[15] = op_to_oper[v2[12]].strip()
TxRepl(o, i, ('if (PyInt_CheckExact( $2 ) && ($3 = PyInt_AS_LONG ( $2 )) < INT_MAX && PyInt_CheckExact( $7 )) {',
'$6 = PyInt_AS_LONG ( $7 ) $15 $3;',
'} else if (PyFloat_CheckExact( $2 ) && PyFloat_CheckExact( $7 )) {',
'$6 = PyFloat_AS_DOUBLE ( $7 ) $15 (PyFloat_AS_DOUBLE($2) + ((double)1));',
'} else {',
'if ((temp[$1] = PyNumber_Add ( $2 , $5 )) == 0) goto $4;',
'if (($6 = PyObject_RichCompareBool ( $7 , temp[$1] , $12 )) == -1) goto $4;',
'CLEARTEMP($1);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $2 ) && ($3 = PyInt_AS_LONG ( $2 )) < INT_MAX ) {',
'temp[$1] = PyInt_FromLong ( $3 + 1 );',
'} else {',
'if ((temp[$1] = PyNumber_Add ( $2 , $5 )) == 0) goto $4;',
'}',
'if (($6 = PyObject_RichCompareBool ( $7 , temp[$1] , $12 )) == -1) goto $4;',
'CLEARTEMP($1);'), v2) and v2[12] in op_to_oper:
v2[15] = op_to_oper[v2[12]].strip()
TxRepl(o, i, ('if (PyInt_CheckExact( $2 ) && ($3 = PyInt_AS_LONG ( $2 )) < INT_MAX && PyInt_CheckExact( $7 )) {',
'$6 = PyInt_AS_LONG ( $7 ) $15 $3;',
'} else {',
'if ((temp[$1] = PyNumber_Add ( $2 , $5 )) == 0) goto $4;',
'if (($6 = PyObject_RichCompareBool ( $7 , temp[$1] , $12 )) == -1) goto $4;',
'CLEARTEMP($1);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $3 ) && ($4 = PyInt_AS_LONG ( $3 )) < (INT_MAX-$6) ) {',
'temp[$0] = PyInt_FromLong ( $4 + $7 );',
'} else if (PyFloat_CheckExact( $3 )) {',
'temp[$0] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($3) + ((double)$7));',
'} else {',
'if ((temp[$0] = PyNumber_Add ( $3 , $9 )) == 0) goto $5;',
'}',
'if (($1 = PyObject_RichCompareBool ( $8 , temp[$0] , $10 )) == -1) goto $5;',
'CLEARTEMP($0);'), v2) and v2[10] in op_to_oper:
v2[15] = op_to_oper[v2[10]].strip()
TxRepl(o, i, ('if (PyInt_CheckExact( $3 ) && ($4 = PyInt_AS_LONG ( $3 )) < (INT_MAX-$6) && PyInt_CheckExact( $8 )) {',
'$1 = PyInt_AS_LONG ( $8 ) $15 ( $4 + $7 );',
'} else if (PyFloat_CheckExact( $3 ) && PyFloat_CheckExact( $8 )) {',
'$1 = PyFloat_AS_DOUBLE ( $8 ) $15 (PyFloat_AS_DOUBLE($3) + ((double)$7));',
'} else {',
'if ((temp[$0] = PyNumber_Add ( $3 , $9 )) == 0) goto $5;',
'if (($1 = PyObject_RichCompareBool ( $8 , temp[$0] , $10 )) == -1) goto $5;',
'CLEARTEMP($0);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $3 ) && ($4 = PyInt_AS_LONG ( $3 )) < (INT_MAX-$6) ) {',
'temp[$0] = PyInt_FromLong ( $4 + $7 );',
'} else {',
'if ((temp[$0] = PyNumber_Add ( $3 , $9 )) == 0) goto $5;',
'}',
'if (($1 = PyObject_RichCompareBool ( $8 , temp[$0] , $10 )) == -1) goto $5;',
'CLEARTEMP($0);'), v2) and v2[10] in op_to_oper:
v2[15] = op_to_oper[v2[10]].strip()
TxRepl(o, i, ('if (PyInt_CheckExact( $3 ) && ($4 = PyInt_AS_LONG ( $3 )) < (INT_MAX-$6) && PyInt_CheckExact( $8 )) {',
'$1 = PyInt_AS_LONG ( $8 ) $15 ( $4 + $7 );',
'} else {',
'if ((temp[$0] = PyNumber_Add ( $3 , $9 )) == 0) goto $5;',
'if (($1 = PyObject_RichCompareBool ( $8 , temp[$0] , $10 )) == -1) goto $5;',
'CLEARTEMP($0);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $1 )) {',
'$2 = PyInt_AS_LONG ( $1 );',
'$3 = $9;',
'$4 = $2 + $3;',
'if (( $4 ^ $2 ) < 0 && ( $4 ^ $3 ) < 0) goto $5 ;',
'temp[$6] = PyInt_FromLong ( $4 );',
'} else { $5 :;',
'if ((temp[$7] = $10) == 0) goto $8;',
'if ((temp[$6] = PyNumber_Add ( $1 , temp[$7] )) == 0) goto $8;',
'CLEARTEMP($7);',
'}',
'if ((temp[$17] = _PyEval_ApplySlice ( $11 , $1 , temp[$6] )) == 0) goto $8;',
'CLEARTEMP($6);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $1 )) {',
'$2 = PyInt_AS_LONG ( $1 );',
'$3 = $9;',
'$4 = $2 + $3;',
'if (( $4 ^ $2 ) < 0 && ( $4 ^ $3 ) < 0) goto $5 ;',
'if ((temp[$17] = PySequence_GetSlice ( $11 , $2 , $4 )) == 0) goto $8;',
'} else { $5 :;',
'if ((temp[$7] = $10) == 0) goto $8;',
'if ((temp[$6] = PyNumber_Add ( $1 , temp[$7] )) == 0) goto $8;',
'CLEARTEMP($7);',
'if ((temp[$17] = _PyEval_ApplySlice ( $11 , $1 , temp[$6] )) == 0) goto $8;',
'CLEARTEMP($6);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $0 ) && ($2 = PyInt_AS_LONG ( $0 )) < (INT_MAX-$3) ) {',
'temp[$5] = PyInt_FromLong ( $2 + $4 );',
'} else {',
'if ((temp[$5] = PyNumber_Add ( $0 , $11 )) == 0) goto $1;',
'}',
'if ((temp[$6] = _PyEval_ApplySlice ( temp[$7] , $0 , temp[$5] )) == 0) goto $1;',
'CLEARTEMP($7);',
'CLEARTEMP($5);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $0 ) && ($2 = PyInt_AS_LONG ( $0 )) < (INT_MAX-$3) ) {',
'if ((temp[$6] = PySequence_GetSlice ( temp[$7] , $2 , $2 + $4 )) == 0) goto $1;',
'} else {',
'if ((temp[$5] = PyNumber_Add ( $0 , $11 )) == 0) goto $1;',
'if ((temp[$6] = _PyEval_ApplySlice ( temp[$7] , $0 , temp[$5] )) == 0) goto $1;',
'CLEARTEMP($5);',
'}',
'CLEARTEMP($7);'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $0 ) && PyInt_CheckExact( $1 )) {',
'$2 = PyInt_AS_LONG ( $0 );',
'$3 = PyInt_AS_LONG ( $1 );',
'$4 = $2 + $3;',
'if (( $4 ^ $2 ) < 0 && ( $4 ^ $3 ) < 0) goto $5 ;',
'temp[$6] = PyInt_FromLong ( $4 );',
'} else { $5 :;',
'if ((temp[$6] = PyNumber_Add ( $0 , $1 )) == 0) goto $7;',
'}',
'if ((temp[$11] = _PyEval_ApplySlice ( temp[$8] , $0 , temp[$6] )) == 0) goto $7;',
'CLEARTEMP($8);',
'CLEARTEMP($6);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $0 ) && PyInt_CheckExact( $1 )) {',
'$2 = PyInt_AS_LONG ( $0 );',
'$3 = PyInt_AS_LONG ( $1 );',
'$4 = $2 + $3;',
'if (( $4 ^ $2 ) < 0 && ( $4 ^ $3 ) < 0) goto $5 ;',
'if ((temp[$11] = PySequence_GetSlice ( temp[$8] , $2 , $4 )) == 0) goto $7;',
'} else { $5 :;',
'if ((temp[$6] = PyNumber_Add ( $0 , $1 )) == 0) goto $7;',
'if ((temp[$11] = _PyEval_ApplySlice ( temp[$8] , $0 , temp[$6] )) == 0) goto $7;',
'CLEARTEMP($6);',
'}',
'CLEARTEMP($8);'), v2)
return True
if TxMatch(o, i, """if ($1)) {
long_$5 = $3;
long_$6 = $4;
long_$7 = long_$5 - long_$6;
if (( long_$7 ^ long_$5 ) < 0 && ( long_$7 ^~ long_$6 ) < 0) goto label_$8 ;
temp[$9] = PyInt_FromLong ( long_$7 );
} else if ($2)) {
temp[$9] = PyFloat_FromDouble($10);
} else { label_$8 :;
temp[$11] = PyInt_FromLong ($12);
if ((temp[$9] = PyNumber_Subtract ( temp[$11] , $13 )) == 0) goto label_$14;
CLEARTEMP($11);
}
SETLOCAL ( $17 , temp[$9] );
temp[$9] = 0;
if ((temp[$15] = _PyEval_ApplySlice ( $16 , GETLOCAL($16) , NULL )) == 0) goto label_$14;""", v2):
TxRepl(o, i, """if ($1)) {
long_$5 = $3;
long_$6 = $4;
long_$7 = long_$5 - long_$6;
if (( long_$7 ^ long_$5 ) < 0 && ( long_$7 ^~ long_$6 ) < 0) goto label_$8 ;
SETLOCAL ( $17 , PyInt_FromLong ( long_$7 ) );
if ((temp[$15] = PySequence_GetSlice ( $16 , long_$7 , PY_SSIZE_T_MAX )) == 0) goto $label_$14;',
} else { label_$8 :;
temp[$11] = PyInt_FromLong ($12);
if ((temp[$9] = PyNumber_Subtract ( temp[$11] , $13 )) == 0) goto label_$14;
CLEARTEMP($11);
SETLOCAL ( $17 , temp[$9] );
temp[$9] = 0;
if ((temp[$15] = _PyEval_ApplySlice ( $16 , GETLOCAL($16) , NULL )) == 0) goto label_$14;
}""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $8 ) && (long_$6 = PyInt_AS_LONG ( GETLOCAL(i) )) < $5 ) {
temp[$2] = PyInt_FromLong ( long_$6 + $7 );
} else {
if ((temp[$2] = PyNumber_Add ( $8 , $9 )) == 0) goto label_$4;
}
if ((temp[$3] = _PyEval_ApplySlice ( temp[$0] , temp[$2] , NULL )) == 0) goto label_$4;
CLEARTEMP($0);
CLEARTEMP($2);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $8 ) && (long_$6 = PyInt_AS_LONG ( GETLOCAL(i) )) < $5 ) {
if ((temp[$3] = PySequence_GetSlice ( temp[$0] , long_$6 + $7 , PY_SSIZE_T_MAX )) == 0) goto label_$4;
CLEARTEMP($0);
} else {
if ((temp[$2] = PyNumber_Add ( $8 , $9 )) == 0) goto label_$4;
if ((temp[$3] = _PyEval_ApplySlice ( temp[$0] , temp[$2] , NULL )) == 0) goto label_$4;
CLEARTEMP($0);
CLEARTEMP($2);
}
""", v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $7 ) && ($4 = PyInt_AS_LONG ( $7 )) > INT_MIN ) {',
'$4 = $4 - 1;',
'if ((temp[$1] = __c_BINARY_SUBSCR_Int ( $6 , $4 )) == 0) goto $5;',
'} else {',
'if ((temp[$0] = PyNumber_Subtract ( $7 , consts[$3] )) == 0) goto $5;',
'if ((temp[$1] = PyObject_GetItem ( $6 , temp[$0] )) == 0) goto $5;',
'CLEARTEMP($0);',
'}',
'if ((temp[$9] = PyObject_GetItem ( $6 , $7 )) == 0) goto $5;'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $7 ) && ($4 = PyInt_AS_LONG ( $7 )) > INT_MIN ) {',
'if ((temp[$1] = __c_BINARY_SUBSCR_Int ( $6 , $4 - 1 )) == 0) goto $5;',
'if ((temp[$9] = _c_BINARY_SUBSCR_Int ( $6 , $4 , $7 )) == 0) goto $5;',
'} else {',
'if ((temp[$0] = PyNumber_Subtract ( $7 , consts[$3] )) == 0) goto $5;',
'if ((temp[$1] = PyObject_GetItem ( $6 , temp[$0] )) == 0) goto $5;',
'CLEARTEMP($0);',
'if ((temp[$9] = PyObject_GetItem ( $6 , $7 )) == 0) goto $5;',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $5 ) && ($7 = PyInt_AS_LONG ( $5 )) < INT_MAX ) {',
'temp[$1] = PyInt_FromLong ( $7 + 1 );',
'} else if (PyFloat_CheckExact( $5 )) {',
'temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($5) + ((double)1));',
'} else {',
'if ((temp[$1] = PyNumber_Add ( $5 , consts[$9] )) == 0) goto $8;',
'}',
'if ( _PyEval_AssignSlice ( $6 , temp[$1] , NULL , temp[$0] ) == -1) goto $8;',
'CLEARTEMP($0);',
'CLEARTEMP($1);',
'temp[$0] = 0;'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $5 ) && ($7 = PyInt_AS_LONG ( $5 )) < INT_MAX ) {',
'if ( PySequence_SetSlice ( $6 , $7 + 1 , PY_SSIZE_T_MAX , temp[$0] ) == -1) goto $8;',
'} else {',
'if ((temp[$1] = PyNumber_Add ( $5 , consts[$9] )) == 0) goto $8;',
'if ( _PyEval_AssignSlice ( $6 , temp[$1] , NULL , temp[$0] ) == -1) goto $8;',
'CLEARTEMP($1);',
'}',
'CLEARTEMP($0);'), v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $1 ) && (long_$2 = PyInt_AS_LONG ( $1 )) < $6 ) {
temp[$0] = PyInt_FromLong ( long_$2 + $4 );
} else if (PyFloat_CheckExact( $1 )) {
temp[$0] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) + ((double)$4));
} else {
if ((temp[$0] = PyNumber_Add ( $1 , $5 )) == 0) goto label_$3;
}
if ( _PyEval_AssignSlice ( $7 , $1 , temp[$0] , NULL ) == -1) goto label_$3;
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $1 ) && (long_$2 = PyInt_AS_LONG ( $1 )) < $6 ) {
if ( PySequence_DelSlice ( $7 , long_$2 , long_$2 + $4 ) == -1) goto label_$3;
} else {
if ((temp[$0] = PyNumber_Add ( $1 , $5 )) == 0) goto label_$3;
if ( _PyEval_AssignSlice ( $7 , $1 , temp[$0] , NULL ) == -1) goto label_$3;
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $4 ) && (long_$3 = PyInt_AS_LONG ( $4 )) > $5 ) {
temp[$0] = PyInt_FromLong ( long_$3 - $6 );
} else if (PyFloat_CheckExact( $4 )) {
temp[$0] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($4) - ((double)$6));
} else {
if ((temp[$0] = PyNumber_Subtract ( $4 , $7 )) == 0) goto label_$2;
}
if (PyInt_CheckExact( $4 ) && (long_$3 = PyInt_AS_LONG ( $4 )) > $8 ) {
temp[$1] = PyInt_FromLong ( long_$3 - $9 );
} else if (PyFloat_CheckExact( $4 )) {
temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($4) - ((double)$9));
} else {
if ((temp[$1] = PyNumber_Subtract ( $4 , $10 )) == 0) goto label_$2;
}
if ( _PyEval_AssignSlice ( $11 , temp[$0] , temp[$1] , NULL ) == -1) goto label_$2;
CLEARTEMP($0);
CLEARTEMP($1);
""", v2) and v2[6].isdigit() and v2[9].isdigit() and int(v2[6]) >= int(v2[9]):
TxRepl(o, i, """
if (PyInt_CheckExact( $4 ) && (long_$3 = PyInt_AS_LONG ( $4 )) > $5 ) {
if ( PySequence_DelSlice ( $11 , long_$3 - $6 , long_$3 - $9 ) == -1) goto label_$2;
} else {
if ((temp[$0] = PyNumber_Subtract ( $4 , $7 )) == 0) goto label_$2;
if ((temp[$1] = PyNumber_Subtract ( $4 , $10 )) == 0) goto label_$2;
if ( _PyEval_AssignSlice ( $11 , temp[$0] , temp[$1] , NULL ) == -1) goto label_$2;
CLEARTEMP($0);
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $0 ) && (long_$1 = PyInt_AS_LONG ( $0 )) < INT_MAX ) {
temp[$2] = PyInt_FromLong ( long_$1 + 1 );
} else if (PyFloat_CheckExact( $0 )) {
temp[$2] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($0) + ((double)1));
} else {
if ((temp[$2] = PyNumber_Add ( $0 , $7 )) == 0) goto label_$4;
}
if (PyInt_CheckExact( $0 ) && (long_$1 = PyInt_AS_LONG ( $0 )) < (INT_MAX-$9) ) {
temp[$3] = PyInt_FromLong ( long_$1 + $10 );
} else if (PyFloat_CheckExact( $0 )) {
temp[$3] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($0) + ((double)$10));
} else {
if ((temp[$3] = PyNumber_Add ( $0 , $8 )) == 0) goto label_$4;
}
if ( _PyEval_AssignSlice ( $5 , temp[$2] , temp[$3] , $6 ) == -1) goto label_$4;
CLEARTEMP($2);
CLEARTEMP($3);""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $0 ) && (long_$1 = PyInt_AS_LONG ( $0 )) < (INT_MAX-$9) ) {
if ( PySequence_SetSlice ( $5 , long_$1 + 1 , long_$1 + $10 , $6 ) == -1) goto label_$4;
} else {
if ((temp[$2] = PyNumber_Add ( $0 , $7 )) == 0) goto label_$4;
if ((temp[$3] = PyNumber_Add ( $0 , $8 )) == 0) goto label_$4;
if ( _PyEval_AssignSlice ( $5 , temp[$2] , temp[$3] , $6 ) == -1) goto label_$4;
CLEARTEMP($2);
CLEARTEMP($3);
}""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $3 ) && (long_$4 = PyInt_AS_LONG ( $3 )) < INT_MAX ) {
temp[$1] = PyInt_FromLong ( long_$4 + $9 );
} else if (PyFloat_CheckExact( $3 )) {
temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($3) + ((double)$9));
} else {
if ((temp[$1] = PyNumber_Add ( $3 , $11 )) == 0) goto label_$6;
}
if (PyInt_CheckExact( $3 ) && (long_$4 = PyInt_AS_LONG ( $3 )) < $8 ) {
temp[$2] = PyInt_FromLong ( long_$4 + $10 );
} else if (PyFloat_CheckExact( $3 )) {
temp[$2] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($3) + ((double)$10));
} else {
if ((temp[$2] = PyNumber_Add ( $3 , $12 )) == 0) goto label_$6;
}
if ( _PyEval_AssignSlice ( $5 , temp[$1] , temp[$2] , temp[$0] ) == -1) goto label_$6;
CLEARTEMP($0);
CLEARTEMP($1);
CLEARTEMP($2);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $3 ) && (long_$4 = PyInt_AS_LONG ( $3 )) < $8 ) {
if ( PySequence_SetSlice ( $5 , long_$4 + $9 , long_$4 + $10 , temp[$0] ) == -1) goto label_$6;
CLEARTEMP($0);
} else {
if ((temp[$1] = PyNumber_Add ( $3 , $11 )) == 0) goto label_$6;
if ((temp[$2] = PyNumber_Add ( $3 , $12 )) == 0) goto label_$6;
if ( _PyEval_AssignSlice ( $5 , temp[$1] , temp[$2] , temp[$0] ) == -1) goto label_$6;
CLEARTEMP($1);
CLEARTEMP($2);
CLEARTEMP($0);
}""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $0 )) {
long_$7 = PyInt_AS_LONG ( $1 );
long_$8 = PyInt_AS_LONG ( $0 );
long_$9 = long_$7 + long_$8;
if (( long_$9 ^ long_$7 ) < 0 && ( long_$9 ^ long_$8 ) < 0) goto label_$2 ;
temp[$6] = PyInt_FromLong ( long_$9 );
} else if (PyFloat_CheckExact( $0 )) {
temp[$6] = PyFloat_FromDouble((double)PyInt_AS_LONG ( $1 ) + PyFloat_AS_DOUBLE($0));
} else { label_$2 :;
if ((temp[$6] = PyNumber_Add ( $1 , $0 )) == 0) goto label_$3;
}
if ( _PyEval_AssignSlice ( $4 , $1 , temp[$6] , $5 ) == -1) goto label_$3;
CLEARTEMP($6);""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $0 )) {
long_$7 = PyInt_AS_LONG ( $1 );
long_$8 = PyInt_AS_LONG ( $0 );
long_$9 = long_$7 + long_$8;
if (( long_$9 ^ long_$7 ) < 0 && ( long_$9 ^ long_$8 ) < 0) goto label_$2 ;
if ( PySequence_SetSlice ( $4 , long_$7 , long_$9 , $5 ) == -1) goto label_$3;
} else { label_$2 :;
if ((temp[$6] = PyNumber_Add ( $1 , $0 )) == 0) goto label_$3;
if ( _PyEval_AssignSlice ( $4 , $1 , temp[$6] , $5 ) == -1) goto label_$3;
CLEARTEMP($6);
}""", v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $5 ) && ($7 = PyInt_AS_LONG ( $5 )) < INT_MAX ) {',
'temp[$1] = PyInt_FromLong ( $7 + 1 );',
'} else if (PyFloat_CheckExact( $5 )) {',
'temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($5) + ((double)1));',
'} else {',
'if ((temp[$1] = PyNumber_Add ( $5 , consts[$9] )) == 0) goto $8;',
'}',
'if ( _PyEval_AssignSlice ( $6 , $5 , temp[$1] , temp[$0] ) == -1) goto $8;',
'CLEARTEMP($0);',
'CLEARTEMP($1);',
'temp[$0] = 0;'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $5 ) && ($7 = PyInt_AS_LONG ( $5 )) < INT_MAX ) {',
'if ( PySequence_SetSlice ( $6 , $7 , $7 + 1 , temp[$0] ) == -1) goto $8;',
'} else {',
'if ((temp[$1] = PyNumber_Add ( $5 , consts[$9] )) == 0) goto $8;',
'if ( _PyEval_AssignSlice ( $6 , $5 , temp[$1] , temp[$0] ) == -1) goto $8;',
'CLEARTEMP($1);',
'}',
'CLEARTEMP($0);'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $5 ) && ($7 = PyInt_AS_LONG ( $5 )) < INT_MAX ) {',
'temp[$1] = PyInt_FromLong ( $7 + 1 );',
'} else if (PyFloat_CheckExact( $5 )) {',
'temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($5) + ((double)1));',
'} else {',
'if ((temp[$1] = PyNumber_Add ( $5 , consts[$9] )) == 0) goto $8;',
'}',
'if ( _PyEval_AssignSlice ( $6 , $5 , temp[$1] , GETLOCAL($0) ) == -1) goto $8;',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $5 ) && ($7 = PyInt_AS_LONG ( $5 )) < INT_MAX ) {',
'if ( PySequence_SetSlice ( $6 , $7 , $7 + 1 , GETLOCAL($0) ) == -1) goto $8;',
'} else {',
'if ((temp[$1] = PyNumber_Add ( $5 , consts[$9] )) == 0) goto $8;',
'if ( _PyEval_AssignSlice ( $6 , $5 , temp[$1] , GETLOCAL($0) ) == -1) goto $8;',
'CLEARTEMP($1);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $5 ) && ($7 = PyInt_AS_LONG ( $5 )) < (INT_MAX-$11) ) {',
'temp[$1] = PyInt_FromLong ( $7 + $12 );',
'} else if (PyFloat_CheckExact( $5 )) {',
'temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($5) + ((double)$12));',
'} else {',
'if ((temp[$1] = PyNumber_Add ( $5 , consts[$9] )) == 0) goto $8;',
'}',
'if ( _PyEval_AssignSlice ( $6 , $5 , temp[$1] , temp[$0] ) == -1) goto $8;',
'CLEARTEMP($0);',
'CLEARTEMP($1);',
'temp[$0] = 0;'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $5 ) && ($7 = PyInt_AS_LONG ( $5 )) < (INT_MAX-$11) ) {',
'if ( PySequence_SetSlice ( $6 , $7 , $7 + $12 , temp[$0] ) == -1) goto $8;',
'} else {',
'if ((temp[$1] = PyNumber_Add ( $5 , consts[$9] )) == 0) goto $8;',
'if ( _PyEval_AssignSlice ( $6 , $5 , temp[$1] , temp[$0] ) == -1) goto $8;',
'CLEARTEMP($1);',
'}',
'CLEARTEMP($0);'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $5 ) && ($7 = PyInt_AS_LONG ( $5 )) < (INT_MAX-$11) ) {',
'temp[$1] = PyInt_FromLong ( $7 + $12 );',
'} else if (PyFloat_CheckExact( $5 )) {',
'temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($5) + ((double)$12));',
'} else {',
'if ((temp[$1] = PyNumber_Add ( $5 , consts[$9] )) == 0) goto $8;',
'}',
'if ( _PyEval_AssignSlice ( $6 , $5 , temp[$1] , GETLOCAL($0) ) == -1) goto $8;',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $5 ) && ($7 = PyInt_AS_LONG ( $5 )) < (INT_MAX-$11) ) {',
'if ( PySequence_SetSlice ( $6 , $7 , $7 + $12 , GETLOCAL($0) ) == -1) goto $8;',
'} else {',
'if ((temp[$1] = PyNumber_Add ( $5 , consts[$9] )) == 0) goto $8;',
'if ( _PyEval_AssignSlice ( $6 , $5 , temp[$1] , GETLOCAL($0) ) == -1) goto $8;',
'CLEARTEMP($1);',
'}'), v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $1 ) && (long_$2 = PyInt_AS_LONG ( $1 )) < $3 ) {
temp[$0] = PyInt_FromLong ( long_$2 + $4 );
} else if (PyFloat_CheckExact( $1 )) {
temp[$0] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) + ((double)$4));
} else {
if ((temp[$0] = PyNumber_Add ( $1 , $5 )) == 0) goto label_$6;
}
if ( _PyEval_AssignSlice ( $7 , $1 , temp[$0] , NULL ) == -1) goto label_$6;
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $1 ) && (long_$2 = PyInt_AS_LONG ( $1 )) < $3 ) {
if ( PySequence_DelSlice ( $7 , long_$2 , long_$2 + $4 ) == -1) goto label_$6;
} else {
if ((temp[$0] = PyNumber_Add ( $1 , $5 )) == 0) goto label_$6;
if ( _PyEval_AssignSlice ( $7 , $1 , temp[$0] , NULL ) == -1) goto label_$6;
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $5 )) {',
'$7 = PyInt_AS_LONG ( $5 );',
'$12 = $9;',
'$14 = $7 + $12;',
'if (( $14 ^ $7 ) < 0 && ( $14 ^ $12 ) < 0) goto $11 ;',
'temp[$1] = PyInt_FromLong ( $14 );',
'} else if (PyFloat_CheckExact( $5 )) {',
'temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($5) + (double)$9);',
'} else { $11 :;',
'temp[$0] = $10;',
'if ((temp[$1] = PyNumber_Add ( $5 , temp[$0] )) == 0) goto $8;',
'CLEARTEMP($0);',
'}',
'if ( _PyEval_AssignSlice ( $17 , $5 , temp[$1] , $15 ) == -1) goto $8;',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $5 )) {',
'$7 = PyInt_AS_LONG ( $5 );',
'$12 = $9;',
'$14 = $7 + $12;',
'if (( $14 ^ $7 ) < 0 && ( $14 ^ $12 ) < 0) goto $11 ;',
'if ( PySequence_SetSlice ( $17 , $7 , $14 , $15 ) == -1) goto $8;',
'} else { $11 :;',
'temp[$0] = $10;',
'if ((temp[$1] = PyNumber_Add ( $5 , temp[$0] )) == 0) goto $8;',
'CLEARTEMP($0);',
'if ( _PyEval_AssignSlice ( $17 , $5 , temp[$1] , $15 ) == -1) goto $8;',
'CLEARTEMP($1);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $10 ) && ($12 = PyInt_AS_LONG ( $10 )) < INT_MAX ) {',
'temp[$0] = PyInt_FromLong ( $12 + 1 );',
'} else {',
'if ((temp[$0] = PyNumber_Add ( $10 , $16 )) == 0) goto $14;',
'}',
'if (PyInt_CheckExact( temp[$0] )) {',
'$15 = PyInt_AS_LONG ( temp[$0] );',
'if ( $15 < 0) {',
'$15 += PyList_GET_SIZE($11);',
'}',
'if ((temp[$4] = PyList_GetItem ( $11 , $15 )) == 0) goto $14;',
'Py_INCREF(temp[$4]);',
'} else {',
'if ((temp[$4] = PyObject_GetItem ( $11 , temp[$0] )) == 0) goto $14;',
'}',
'CLEARTEMP(0);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $10 ) && ($12 = PyInt_AS_LONG ( $10 )) < INT_MAX ) {',
'$15 = $12 + 1;',
'if ( $15 < 0) {',
'$15 += PyList_GET_SIZE($11);',
'}',
'if ((temp[$4] = PyList_GetItem ( $11 , $15 )) == 0) goto $14;',
'Py_INCREF(temp[$4]);',
'} else {',
'if ((temp[$0] = PyNumber_Add ( $10 , $16 )) == 0) goto $14;',
'if ((temp[$4] = PyObject_GetItem ( $11 , temp[$0] )) == 0) goto $14;',
'CLEARTEMP(0);',
'}'), v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $3 ) && PyInt_CheckExact( $4 )) {
$5 = PyInt_AS_LONG ( $3 );
$6 = PyInt_AS_LONG ( $4 );
$7 = $5 - $6;
if (( $7 ^ $5 ) < 0 && ( $7 ^~ $6 ) < 0) goto $12 ;
temp[$0] = PyInt_FromLong ( $7 );
} else if (PyFloat_CheckExact( $3 ) && PyFloat_CheckExact( $4 )) {
temp[$0] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($3) - PyFloat_AS_DOUBLE($4));
} else { $12 :;
if ((temp[$0] = PyNumber_Subtract ( $3 , $4 )) == 0) goto $11;
}
if ((temp[$1] = PyInt_FromSsize_t ( $15 )) == 0) goto $11;
if (PyInt_CheckExact( temp[$0] )) {
$8 = PyInt_AS_LONG ( temp[$0] );
$9 = PyInt_AS_LONG ( temp[$1] );
$10 = $8 + $9;
if (( $10 ^ $8 ) < 0 && ( $10 ^ $9 ) < 0) goto $13 ;
temp[$2] = PyInt_FromLong ( $10 );
} else if (PyFloat_CheckExact( temp[$0] )) {
temp[$2] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$0]) + (double)PyInt_AS_LONG ( temp[$1] ));
} else { $13 :;
if ((temp[$2] = PyNumber_Add ( temp[$0] , temp[$1] )) == 0) goto $11;
}
CLEARTEMP($0);
CLEARTEMP($1);
""", v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $3 ) && PyInt_CheckExact( $4 )) {',
'$5 = PyInt_AS_LONG ( $3 );',
'$6 = PyInt_AS_LONG ( $4 );',
'$7 = $5 - $6;',
'if (( $7 ^ $5 ) < 0 && ( $7 ^~ $6 ) < 0) goto $12 ;',
'$8 = $7;',
'$9 = $15;',
'$10 = $8 + $9;',
'if (( $10 ^ $8 ) < 0 && ( $10 ^ $9 ) < 0) goto $12 ;',
'temp[$2] = PyInt_FromLong ( $10 );',
'} else if (PyFloat_CheckExact( $3 ) && PyFloat_CheckExact( $4 )) {',
'temp[$2] = PyFloat_FromDouble((PyFloat_AS_DOUBLE($3) - PyFloat_AS_DOUBLE($4)) + (double)$15);',
'} else { $12 :;',
'if ((temp[$0] = PyNumber_Subtract ( $3 , $4 )) == 0) goto $11;',
'if ((temp[$1] = PyInt_FromSsize_t ( $15 )) == 0) goto $11;',
'if ((temp[$2] = PyNumber_Add ( temp[$0] , temp[$1] )) == 0) goto $11;',
'CLEARTEMP($0);',
'CLEARTEMP($1);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $0 ) && PyInt_CheckExact( $1 )) {',
'$4 = PyInt_AS_LONG ( $0 );',
'$5 = PyInt_AS_LONG ( $1 );',
'$6 = $4 + $5;',
'if (( $6 ^ $4 ) < 0 && ( $6 ^ $5 ) < 0) goto $7 ;',
'temp[$2] = PyInt_FromLong ( $6 );',
'} else if (PyFloat_CheckExact( $0 ) && PyFloat_CheckExact( $1 )) {',
'temp[$2] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($0) + PyFloat_AS_DOUBLE($1));',
'} else { $7 :;',
'if ((temp[$2] = PyNumber_Add ( $0 , $1 )) == 0) goto $8;',
'}',
'if (PyInt_CheckExact( temp[$2] ) && ($4 = PyInt_AS_LONG ( temp[$2] )) < (INT_MAX-$9) ) {',
'temp[$3] = PyInt_FromLong ( $4 + $10 );',
'} else if (PyFloat_CheckExact( temp[$2] )) {',
'temp[$3] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$2]) + ((double)$10));',
'} else {',
'if ((temp[$3] = PyNumber_Add ( temp[$2] , $11 )) == 0) goto $8;',
'}',
'CLEARTEMP($2);'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $0 ) && PyInt_CheckExact( $1 )) {',
'$4 = PyInt_AS_LONG ( $0 );',
'$5 = PyInt_AS_LONG ( $1 );',
'$6 = $4 + $5;',
'if ((( $6 ^ $4 ) < 0 && ( $6 ^ $5 ) < 0) || $6 >= (INT_MAX-$9) ) goto $7 ;',
'temp[$3] = PyInt_FromLong ( $4 + $10 );',
'} else if (PyFloat_CheckExact( $0 ) && PyFloat_CheckExact( $1 )) {',
'temp[$3] = PyFloat_FromDouble((PyFloat_AS_DOUBLE($0) + PyFloat_AS_DOUBLE($1)) + ((double)$10));',
'} else { $7 :;',
'if ((temp[$2] = PyNumber_Add ( $0 , $1 )) == 0) goto $8;',
'if ((temp[$3] = PyNumber_Add ( temp[$2] , $11 )) == 0) goto $8;',
'CLEARTEMP($2);',
'}'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $0 ) && ($1 = PyInt_AS_LONG ( $0 )) > INT_MIN ) {',
'temp[$2] = PyInt_FromLong ( $1 - 1 );',
'} else if (PyFloat_CheckExact( $0 )) {',
'temp[$2] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($0) - ((double)1));',
'} else {',
'if ((temp[$2] = PyNumber_Subtract ( $0 , $5 )) == 0) goto $4;',
'}',
'if ( PyObject_SetItem ( $6 , temp[$2] , temp[$3] ) == -1) goto $4;',
'CLEARTEMP($3);',
'CLEARTEMP($2);',
'temp[$3] = 0;'), v2):
TxRepl(o, i, ('if (PyInt_CheckExact( $0 ) && ($1 = PyInt_AS_LONG ( $0 )) > INT_MIN ) {',
'temp[$2] = PyInt_FromLong ( $1 - 1 );',
'} else {',
'if ((temp[$2] = PyNumber_Subtract ( $0 , $5 )) == 0) goto $4;',
'}',
'if ( PyObject_SetItem ( $6 , temp[$2] , temp[$3] ) == -1) goto $4;',
'CLEARTEMP($3);',
'CLEARTEMP($2);',
'temp[$3] = 0;'), v2)
return True
if TxMatch(o, i, ('if (PyInt_CheckExact( $0 ) && PyInt_CheckExact( $1 )) {',
'$2 = PyInt_AS_LONG ( $0 );',
'$3 = PyInt_AS_LONG ( $1 );',
'$4 = $2 $14 $3;',
'if (( $4 $15) goto $6 ;',
'temp[$7] = PyInt_FromLong ( $4 );',
'} else if (PyFloat_CheckExact( $0 ) && PyFloat_CheckExact( $1 )) {',
'temp[$7] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($0) $14 PyFloat_AS_DOUBLE($1));',
'} else { $6 :;',
'if ((temp[$7] = PyNumber_$13 ( $0 , $1 )) == 0) goto $5;',
'}',
'if (PyFloat_CheckExact( temp[$7] )) {',
'temp[$8] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$7]) $11 $10);',
'} else {',
'temp[$9] = PyFloat_FromDouble ($10);',
'if ((temp[$8] = PyNumber_$12 ( temp[$7] , temp[$9] )) == 0) goto $5;',
'CLEARTEMP($9);',
'}',
'CLEARTEMP($7);'), v2):
TxRepl(o, i, ('if (PyFloat_CheckExact( $0 ) && PyFloat_CheckExact( $1 )) {',
'temp[$8] = PyFloat_FromDouble((PyFloat_AS_DOUBLE($0) $14 PyFloat_AS_DOUBLE($1)) $11 $10);',
'} else {',
'if ((temp[$7] = PyNumber_$13 ( $0 , $1 )) == 0) goto $5;',
'temp[$9] = PyFloat_FromDouble ($10);',
'if ((temp[$8] = PyNumber_$12 ( temp[$7] , temp[$9] )) == 0) goto $5;',
'CLEARTEMP($9);',
'CLEARTEMP($7);',
'}'), v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( temp[$0] )) {
temp[$1] = PyInt_FromLong ($3);
} else {
if ((temp[$1] = PyNumber_$4) == 0) goto $5;
}
CLEARTEMP($0);
if ((int_$6 = c_Py_EQ_Int ( temp[$1] , $7 , $8 )) == -1) goto $5;
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( temp[$0] )) {
int_$6 = ($3) == $7;
CLEARTEMP($0);
} else {
if ((temp[$1] = PyNumber_$4) == 0) goto $5;
CLEARTEMP($0);
if ((int_$6 = c_Py_EQ_Int ( temp[$1] , $7 , $8 )) == -1) goto $5;
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $10 )) {
temp[$0] = PyInt_FromLong ($1 $3 PyInt_AS_LONG ( $10 ));
} else {
if ((temp[$0] = PyNumber_Or ( $2 , $10 )) == 0) goto $4;
}
long_$5 = PyInt_AsLong ( temp[$0] );
CLEARTEMP($0);
""", v2) and v2[0] != v2[3]:
TxRepl(o, i, """
if (PyInt_CheckExact( $10 )) {
long_$5 = $1 $3 PyInt_AS_LONG ( $10 );
} else {
if ((temp[$0] = PyNumber_Or ( $2 , $10 )) == 0) goto $4;
long_$5 = PyInt_AsLong ( temp[$0] );
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $3 )) {
temp[$0] = PyInt_FromLong (PyInt_AS_LONG ( $3 ) $5);
} else {
if ((temp[$0] = PyNumber_$6 ( $3 , $7 )) == 0) goto label_$4;
}
if (PyInt_CheckExact( temp[$0] )) {
temp[$1] = PyInt_FromLong ($8 PyInt_AS_LONG ( temp[$0] ));
} else {
if ((temp[$1] = PyNumber_$9 ( $10 , temp[$0] )) == 0) goto label_$4;
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $3 )) {
temp[$1] = PyInt_FromLong ($8 (PyInt_AS_LONG ( $3 ) $5));
} else {
if ((temp[$0] = PyNumber_$6 ( $3 , $7 )) == 0) goto label_$4;
if ((temp[$1] = PyNumber_$9 ( $10 , temp[$0] )) == 0) goto label_$4;
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $2 )) {
temp[$0] = PyInt_FromLong (PyInt_AS_LONG ( $2 ) $3);
} else {
if ((temp[$0] = PyNumber_$9 ( $2 , $8 )) == 0) goto $4;
}
if (PyInt_CheckExact( temp[$0] )) {
$6 = PyInt_AS_LONG ( temp[$0] );
$7 = $10;
if ($15) goto $5 ;
temp[$1] = PyInt_FromLong ( $7 );
} else if (PyFloat_CheckExact( temp[$0] )) {
temp[$1] = PyFloat_FromDouble($12);
} else { $5 :;
if ((temp[$1] = PyNumber_$14 ( $11 , temp[$0] )) == 0) goto $4;
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $2 )) {
$6 = (PyInt_AS_LONG ( $2 ) $3);
$7 = $10;
if ($15) goto $5 ;
temp[$1] = PyInt_FromLong ( $7 );
} else { $5 :;
if ((temp[$0] = PyNumber_$9 ( $2 , $8 )) == 0) goto $4;
if ((temp[$1] = PyNumber_$14 ( $11 , temp[$0] )) == 0) goto $4;
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $3 )) {
temp[$1] = PyInt_FromLong ( $6 );
} else {
if ((temp[$1] = PyNumber_$11 ( $7 )) == 0) goto $5;
}
if (PyInt_CheckExact( $3 ) && PyInt_CheckExact( temp[$1] )) {
$8 = PyInt_AS_LONG ( $3 );
$9 = PyInt_AS_LONG ( temp[$1] );
$10 = $8 - $9;
if (( $10 ^ $8 ) < 0 && ( $10 ^~ $9 ) < 0) goto $4 ;
temp[$2] = PyInt_FromLong ( $10 );
} else { $4 :;
if ((temp[$2] = PyNumber_Subtract ( $3 , temp[$1] )) == 0) goto $5;
}
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $3 )) {
$8 = PyInt_AS_LONG ( $3 );
$9 = $6;
$10 = $8 - $9;
if (( $10 ^ $8 ) < 0 && ( $10 ^~ $9 ) < 0) goto $4 ;
temp[$2] = PyInt_FromLong ( $10 );
} else { $4 :;
if ((temp[$1] = PyNumber_$11 ( $7 )) == 0) goto $5;
if ((temp[$2] = PyNumber_Subtract ( $3 , temp[$1] )) == 0) goto $5;
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $3 ) && PyInt_CheckExact( temp[$2] )) {
long_$8;
long_$9;
long_$10;
if ($11) goto $5 ;
temp[$0] = PyInt_FromLong ( long_$12 );
} else { $5 :;
if ((temp[$0] = PyNumber_$18 ( $3 , temp[$2] )) == 0) goto $4;
}
CLEARTEMP($2);
if (PyInt_CheckExact( temp[$0] ) && PyInt_CheckExact( $7 )) {
long_$13 = PyInt_AS_LONG ( temp[$0] );
long_$14 = PyInt_AS_LONG ( $7 );
long_$15;
if ($16) goto $6 ;
temp[$1] = PyInt_FromLong ( long_$17 );
} else { $6 :;
if ((temp[$1] = PyNumber_$19 ( temp[$0] , $7 )) == 0) goto $4;
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $3 ) && PyInt_CheckExact( temp[$2] ) && PyInt_CheckExact( $7 )) {
long_$8;
long_$9;
long_$10;
if ($11) goto $5 ;
long_$13 = long_$12;
long_$14 = PyInt_AS_LONG ( $7 );
long_$15;
if ($16) goto $5 ;
temp[$1] = PyInt_FromLong ( long_$17 );
} else { $5 :;
if ((temp[$0] = PyNumber_$18 ( $3 , temp[$2] )) == 0) goto $4;
CLEARTEMP($2);
if ((temp[$1] = PyNumber_$19 ( temp[$0] , $7 )) == 0) goto $4;
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact($1)) {
temp[$0] = PyInt_FromLong ($3);
} else {
if ((temp[$0] = PyNumber_$4) == 0) goto $2;
}
long_$5 = PyInt_AsLong ( temp[$0] );
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact($1)) {
long_$5 = ($3);
} else {
if ((temp[$0] = PyNumber_$4) == 0) goto $2;
long_$5 = PyInt_AsLong ( temp[$0] );
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( temp[$2] ) && ($4 = PyInt_AS_LONG ( temp[$2] )) < INT_MAX ) {
temp[$0] = PyInt_FromLong ( $4 + 1 );
} else if (PyFloat_CheckExact( temp[$2] )) {
temp[$0] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$2]) + ((double)1));
} else {
if ((temp[$0] = PyNumber_Add ( temp[$2] , $5 )) == 0) goto $3;
}
CLEARTEMP($2);
Py_ssize_t_$7 = PyInt_AsSsize_t ( temp[$0] );
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
Py_ssize_t_$7 = PyInt_AS_LONG ( temp[$2] ) + 1;
CLEARTEMP($2);
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( temp[$2] ) && ($1 = PyInt_AS_LONG ( temp[$2] )) < $5) {
temp[$3] = PyInt_FromLong ( $1 + $6 );
} else if (PyFloat_CheckExact( temp[$2] )) {
temp[$3] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$2]) + ((double)$6));
} else {
if ((temp[$3] = PyNumber_$7 ( temp[$2] , $8 )) == 0) goto $14;
}
CLEARTEMP($2);
if (PyInt_CheckExact( temp[$3] )) {
temp[$12] = PyInt_FromLong (PyInt_AS_LONG ( temp[$3] ) $15);
} else {
if ((temp[$12] = PyNumber_$16 ( temp[$3] , $13 )) == 0) goto $14;
}
CLEARTEMP($3);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( temp[$2] ) && ($1 = PyInt_AS_LONG ( temp[$2] )) < $5) {
CLEARTEMP($2);
temp[$12] = PyInt_FromLong (( $1 + $6 ) $15);
} else {
if ((temp[$3] = PyNumber_$7 ( temp[$2] , $8 )) == 0) goto $14;
CLEARTEMP($2);
if ((temp[$12] = PyNumber_$16 ( temp[$3] , $13 )) == 0) goto $14;
CLEARTEMP($3);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $2 ) && (($12 = PyInt_AS_LONG ( $2 )), $12 == (($12 * $6) / $6))) {
temp[$4] = PyInt_FromLong ($12 * $6);
} else {
if ((temp[$4] = PyNumber_Multiply ( $2 , $7 )) == 0) goto $1;
}
if (PyInt_CheckExact( temp[$4] ) && ($8 = PyInt_AS_LONG ( temp[$4] )) $9 ) {
temp[$5] = PyInt_FromLong ( $8 $10 );
} else {
if ((temp[$5] = PyNumber_$15 ( temp[$4] , $11 )) == 0) goto $1;
}
CLEARTEMP($4);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $2 ) && (($12 = PyInt_AS_LONG ( $2 )), $12 == (($12 * $6) / $6)) && ($8 = ($12 * $6)) $9 ) {
temp[$5] = PyInt_FromLong ( $8 $10 );
} else {
if ((temp[$4] = PyNumber_Multiply ( $2 , $7 )) == 0) goto $1;
if ((temp[$5] = PyNumber_$15 ( temp[$4] , $11 )) == 0) goto $1;
CLEARTEMP($4);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( temp[$0] )) {
temp[$1] = PyInt_FromLong (PyInt_AS_LONG ( temp[$0] ) & $3);
} else {
if ((temp[$1] = PyNumber_And ( temp[$0] , $4 )) == 0) goto $5;
}
CLEARTEMP($0);
if ((int_$6 = PyObject_Not ( temp[$1] )) == -1) goto $5;
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( temp[$0] )) {
int_$6 = !(PyInt_AS_LONG ( temp[$0] ) & $3);
CLEARTEMP($0);
} else {
if ((temp[$1] = PyNumber_And ( temp[$0] , $4 )) == 0) goto $5;
CLEARTEMP($0);
if ((int_$6 = PyObject_Not ( temp[$1] )) == -1) goto $5;
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( temp[$0] )) {
temp[$1] = PyInt_FromLong (PyInt_AS_LONG ( temp[$0] ) $3);
} else {
if ((temp[$1] = PyNumber_$11 ( temp[$0] , $4 )) == 0) goto $5;
}
CLEARTEMP($0);
if ((int_$6 = PyObject_Not ( temp[$1] )) == -1) goto $5;
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( temp[$0] )) {
int_$6 = !(PyInt_AS_LONG ( temp[$0] ) $3);
CLEARTEMP($0);
} else {
if ((temp[$1] = PyNumber_$11 ( temp[$0] , $4 )) == 0) goto $5;
CLEARTEMP($0);
if ((int_$6 = PyObject_Not ( temp[$1] )) == -1) goto $5;
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( temp[$0] )) {
temp[$1] = PyInt_FromLong (PyInt_AS_LONG ( temp[$0] ) $3);
} else {
if ((temp[$1] = PyNumber_$11 ( temp[$0] , $4 )) == 0) goto $5;
}
CLEARTEMP($0);
if ((int_$6 = PyObject_IsTrue ( temp[$1] )) == -1) goto $5;
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( temp[$0] )) {
int_$6 = (PyInt_AS_LONG ( temp[$0] ) $3);
CLEARTEMP($0);
} else {
if ((temp[$1] = PyNumber_$11 ( temp[$0] , $4 )) == 0) goto $5;
CLEARTEMP($0);
if ((int_$6 = PyObject_IsTrue ( temp[$1] )) == -1) goto $5;
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $0 ) && PyInt_CheckExact( $1 )) {
$2 = PyInt_AS_LONG ( $0 );
$3 = PyInt_AS_LONG ( $1 );
$4 = $2 $12 $3;
if ($12) goto $5 ;
temp[$8] = PyInt_FromLong ( $4 );
} else if (PyFloat_CheckExact( $0 ) && PyFloat_CheckExact( $1 )) {
temp[$8] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($0) $12 PyFloat_AS_DOUBLE($1));
} else { $5 :;
if ((temp[$8] = PyNumber_$14 ( $0 , $1 )) == 0) goto $6;
}
if (($10 = PyObject_Size ( $9 )) == -1) goto $6;
if (PyInt_CheckExact( temp[$8] )) {
$2 = PyInt_AS_LONG ( temp[$8] );
$3 = $10;
$4 = $2 $15 $3;
if ($16) goto $7 ;
temp[$11] = PyInt_FromLong ( $4 );
} else if (PyFloat_CheckExact( temp[$8] )) {
temp[$11] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$8]) $15 (double)$10);
} else { $7 :;
if ((temp[$18] = PyInt_FromSsize_t ( $10 )) == 0) goto $6;
if ((temp[$11] = PyNumber_$17 ( temp[$8] , temp[$18] )) == 0) goto $6;
CLEARTEMP($18);
}
CLEARTEMP($8);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $0 ) && PyInt_CheckExact( $1 )) {
$2 = PyInt_AS_LONG ( $0 );
$3 = PyInt_AS_LONG ( $1 );
$4 = $2 $12 $3;
if ($12) goto $5 ;
if (($10 = PyObject_Size ( $9 )) == -1) goto $6;
$2 = $4;
$3 = $10;
$4 = $2 $15 $3;
if ($16) goto $5 ;
temp[$11] = PyInt_FromLong ( $4 );
} else if (PyFloat_CheckExact( $0 ) && PyFloat_CheckExact( $1 )) {
if (($10 = PyObject_Size ( $9 )) == -1) goto $6;
temp[$11] = PyFloat_FromDouble((PyFloat_AS_DOUBLE($0) $12 PyFloat_AS_DOUBLE($1)) $15 (double)$10);
} else { $5 :;
if ((temp[$8] = PyNumber_$14 ( $0 , $1 )) == 0) goto $6;
if (($10 = PyObject_Size ( $9 )) == -1) goto $6;
if ((temp[$18] = PyInt_FromSsize_t ( $10 )) == 0) goto $6;
if ((temp[$11] = PyNumber_$17 ( temp[$8] , temp[$18] )) == 0) goto $6;
CLEARTEMP($18);
CLEARTEMP($8);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $3 )) {
long_$4 = PyInt_AS_LONG ( $3 );
long_$4 = $5;
temp[$0] = PyInt_FromLong (long_$4);
} else {
if ((temp[$0] = PyNumber_$6) == 0) goto $7;
}
if (PyInt_CheckExact( temp[$0] )) {
long_$8 = $9 PyInt_AS_LONG ( temp[$0] );
} else {
if ((temp[2] = PyNumber_$10 temp[$0] )) == 0) goto $7;
long_$8 = PyInt_AsLong ( temp[$2] );
CLEARTEMP($2);
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $3 )) {
long_$4 = PyInt_AS_LONG ( $3 );
long_$4 = $5;
long_$8 = $9 long_$4;
} else {
if ((temp[$0] = PyNumber_$6) == 0) goto $7;
if ((temp[2] = PyNumber_$10 temp[$0] )) == 0) goto $7;
CLEARTEMP($0);
long_$8 = PyInt_AsLong ( temp[$2] );
CLEARTEMP($2);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $5 )) {
temp[$0] = PyInt_FromLong ( $6 );
} else {
if ((temp[$0] = PyNumber_$7) == 0) goto $8;
}
$9 = PyInt_AsSsize_t ( temp[$0] );
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $5 )) {
$9 = $6;
} else {
if ((temp[$0] = PyNumber_$7) == 0) goto $8;
$9 = PyInt_AsSsize_t ( temp[$0] );
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $10 )) {
temp[$0] = PyInt_FromLong ( PyInt_AS_LONG ( $10 ) $11 );
} else {
if ((temp[$0] = PyNumber_$12 ( $10 , $13 )) == 0) goto $14;
}
if (PyInt_CheckExact( temp[$0] )) {
long_$4 = PyInt_AS_LONG ( temp[$0] );
long_$3 = $16;
if ($17) goto $15 ;
temp[$1] = PyInt_FromLong ( long_$3 );
} else if (PyFloat_CheckExact( temp[$0] )) {
temp[$1] = PyFloat_FromDouble($18);
} else { $15 :;
if ((temp[$1] = PyNumber_$19) == 0) goto $14;
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $10 )) {
long_$4 = PyInt_AS_LONG ( $10 ) $11;
long_$3 = $16;
if ($17) goto $15 ;
temp[$1] = PyInt_FromLong ( long_$3 );
} else { $15 :;
if ((temp[$0] = PyNumber_$12 ( $10 , $13 )) == 0) goto $14;
if ((temp[$1] = PyNumber_$19) == 0) goto $14;
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $2 )) {
long_$4 = PyInt_AS_LONG ( $2 ) $5;
long_$3 = $6;
if ($7) goto $8 ;
temp[$1] = PyInt_FromLong ( long_$3 );
} else { $8 :;
if ((temp[$0] = PyNumber_$9) == 0) goto $11;
if ((temp[$1] = PyNumber_$10) == 0) goto $11;
CLEARTEMP($0);
}
if (PyInt_CheckExact( temp[$1] )) {
temp[$12] = PyInt_FromLong ( PyInt_AS_LONG ( temp[$1] ) $13 );
} else {
if ((temp[$12] = PyNumber_$14) == 0) goto $11;
}
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $2 )) {
long_$4 = PyInt_AS_LONG ( $2 ) $5;
long_$3 = $6;
if ($7) goto $8 ;
temp[$12] = PyInt_FromLong ( long_$3 $13 );
} else { $8 :;
if ((temp[$0] = PyNumber_$9) == 0) goto $11;
if ((temp[$1] = PyNumber_$10) == 0) goto $11;
CLEARTEMP($0);
if ((temp[$12] = PyNumber_$14) == 0) goto $11;
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( temp[$0] )) {
long_$3 = PyInt_AS_LONG ( temp[$0] );
long_$2 = $4;
if ($6) goto $5 ;
temp[$1] = PyInt_FromLong ( long_$2 );
} else if (PyFloat_CheckExact( temp[$0] )) {
temp[$1] = PyFloat_FromDouble($7);
} else { $5 :;
if ((temp[$1] = PyNumber_$8) == 0) goto $9;
}
CLEARTEMP($0);
if (PyInt_CheckExact( temp[$1] )) {
temp[$10] = PyInt_FromLong ( PyInt_AS_LONG ( temp[$1] ) $11 );
} else {
if ((temp[$10] = PyNumber_$12) == 0) goto $9;
}
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( temp[$0] )) {
long_$3 = PyInt_AS_LONG ( temp[$0] );
long_$2 = $4;
if ($6) goto $5 ;
temp[$10] = PyInt_FromLong ( long_$2 $11 );
} else { $5 :;
if ((temp[$1] = PyNumber_$8) == 0) goto $9;
CLEARTEMP($0);
if ((temp[$10] = PyNumber_$12) == 0) goto $9;
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $10 )) {
temp[$0] = PyInt_FromLong ( PyInt_AS_LONG ( $10 ) $11 );
} else {
if ((temp[$0] = PyNumber_$12) == 0) goto $13;
}
if (PyInt_CheckExact( temp[$0] )) {
temp[$1] = PyInt_FromLong ( $14 PyInt_AS_LONG ( temp[$0] ) );
} else {
if ((temp[$1] = PyNumber_$15 ( $16 , temp[$0] )) == 0) goto $13;
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $10 )) {
temp[$1] = PyInt_FromLong ( $14 (PyInt_AS_LONG ( $10 ) $11) );
} else {
if ((temp[$0] = PyNumber_$12) == 0) goto $13;
if ((temp[$1] = PyNumber_$15 ( $16 , temp[$0] )) == 0) goto $13;
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $5 )) {
long_$2 = PyInt_AS_LONG ( $5 );
long_$2 = $3;
temp[$0] = PyInt_FromLong ( long_$2 );
} else {
if ((temp[$0] = PyNumber_$6) == 0) goto $7;
}
if (PyInt_CheckExact( temp[$0] )) {
long_$8 = ( $9 PyInt_AS_LONG ( temp[$0] ) );
} else {
if ((temp[$12] = PyNumber_$13) == 0) goto $7;
long_$8 = PyInt_AsLong ( temp[$12] );
CLEARTEMP($12);
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $5 )) {
long_$2 = PyInt_AS_LONG ( $5 );
long_$2 = $3;
long_$8 = ( $9 long_$2 );
} else {
if ((temp[$0] = PyNumber_$6) == 0) goto $7;
if ((temp[$12] = PyNumber_$13) == 0) goto $7;
CLEARTEMP($0);
long_$8 = PyInt_AsLong ( temp[$12] );
CLEARTEMP($12);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $5 )) {
long_$3 = PyInt_AS_LONG ( $5 );
long_$3 = $4;
temp[$0] = PyInt_FromLong ( long_$3 );
} else {
if ((temp[$0] = PyNumber_$6) == 0) goto $7;
}
if (PyInt_CheckExact( temp[$0] )) {
long_$8 = ( PyInt_AS_LONG ( temp[$0] ) $9 );
} else {
if ((temp[$11] = PyNumber_$10) == 0) goto $7;
long_$8 = PyInt_AsLong ( temp[$11] );
CLEARTEMP($11);
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $5 )) {
long_$3 = PyInt_AS_LONG ( $5 );
long_$3 = $4;
long_$8 = ( long_$3 $9 );
} else {
if ((temp[$0] = PyNumber_$6) == 0) goto $7;
if ((temp[$11] = PyNumber_$10) == 0) goto $7;
CLEARTEMP($0);
long_$8 = PyInt_AsLong ( temp[$11] );
CLEARTEMP($11);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $10 ) && PyInt_CheckExact( $11 )) {
long_$2 = PyInt_AS_LONG ( $10 );
long_$6 = PyInt_AS_LONG ( $11 );
long_$1 = long_$2 $12 long_$6;
if ($13) < 0) goto $14 ;
temp[$0] = PyInt_FromLong ( long_$1 );
} else { $14 :;
if ((temp[$0] = PyNumber_$15) == 0) goto $16;
}
if (PyInt_CheckExact( temp[$0] )) {
int_$8 = $17 $18 PyInt_AS_LONG ( temp[$0] );
} else {
temp[$19] = PyInt_FromLong ( $17 );
if ((int_$8 = PyObject_RichCompareBool ( temp[$19] , temp[$0] , $18 )) == -1) goto $16;
CLEARTEMP($19);
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $10 ) && PyInt_CheckExact( $11 )) {
long_$2 = PyInt_AS_LONG ( $10 );
long_$6 = PyInt_AS_LONG ( $11 );
long_$1 = long_$2 $12 long_$6;
if ($13) < 0) goto $14 ;
int_$8 = $17 $18 long_$1;
} else { $14 :;
if ((temp[$0] = PyNumber_$15) == 0) goto $16;
temp[$19] = PyInt_FromLong ( $17 );
if ((int_$8 = PyObject_RichCompareBool ( temp[$19] , temp[$0] , $18 )) == -1) goto $16;
CLEARTEMP($19);
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $1 )) {
long_$4 = PyInt_AS_LONG ( $1 );
long_$3 = $6 long_$4;
if ($5) goto label_$14 ;
temp[$0] = PyInt_FromLong ( long_$3 );
} else { label_$14 :;
if ((temp[$0] = PyNumber_$9) == 0) goto label_$8;
}
if (PyInt_CheckExact( temp[$0] )) {
int_$7 = $11 $12 PyInt_AS_LONG ( temp[$0] );
} else {
temp[$2] = PyInt_FromLong ( $11 );
if ((int_$7 = PyObject_RichCompareBool ( temp[$2] , temp[$0] , $15 )) == -1) goto label_$8;
CLEARTEMP($2);
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $1 )) {
long_$4 = PyInt_AS_LONG ( $1 );
long_$3 = $6 long_$4;
if ($5) goto label_$14 ;
int_$7 = $11 $12 long_$3;
} else { label_$14 :;
if ((temp[$0] = PyNumber_$9) == 0) goto label_$8;
temp[$2] = PyInt_FromLong ( $11 );
if ((int_$7 = PyObject_RichCompareBool ( temp[$2] , temp[$0] , $15 )) == -1) goto label_$8;
CLEARTEMP($2);
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $4 ) && (long_$5 = PyInt_AS_LONG ( $4 )) $7 ) {
temp[$1] = PyInt_FromLong ( $8 );
} else {
if ((temp[$1] = PyNumber_$9) == 0) goto label_$10;
}
if ((temp[$2] = $13) == 0) goto label_$10;
if ((Py_ssize_t_$3 = $14 ( temp[$2] )) == -1) goto label_$10;
CLEARTEMP($2);
if (PyInt_CheckExact( temp[$1] )) {
int_$6 = PyInt_AS_LONG ( temp[$1] ) $15 Py_ssize_t_$3;
} else {
temp[$11] = PyInt_FromLong ( Py_ssize_t_$3 );
if ((int_$6 = PyObject_RichCompareBool ( temp[$1] , temp[$11] , $16 )) == -1) goto label_$10;
CLEARTEMP($11);
}
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $4 ) && (long_$5 = PyInt_AS_LONG ( $4 )) $7 ) {
if ((temp[$2] = $13) == 0) goto label_$10;
if ((Py_ssize_t_$3 = $14 ( temp[$2] )) == -1) goto label_$10;
CLEARTEMP($2);
int_$6 = ($8) $15 Py_ssize_t_$3;
} else {
if ((temp[$1] = PyNumber_$9) == 0) goto label_$10;
if ((temp[$2] = $13) == 0) goto label_$10;
if ((Py_ssize_t_$3 = $14 ( temp[$2] )) == -1) goto label_$10;
CLEARTEMP($2);
temp[$11] = PyInt_FromLong ( Py_ssize_t_$3 );
if ((int_$6 = PyObject_RichCompareBool ( temp[$11] , temp[$2] , $16 )) == -1) goto label_$10;
CLEARTEMP($11);
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $3 ) && (long_$5 = PyInt_AS_LONG ( $3 )) $6 ) {
temp[$0] = PyInt_FromLong ( $7 );
} else {
if ((temp[$0] = PyNumber_$8) == 0) goto $2;
}
if (PyInt_CheckExact( temp[$0] )) {
long_$9 = PyInt_AS_LONG ( temp[$0] );
CLEARTEMP($0);
if ( long_$9 < 0) {
long_$9 += PyList_GET_SIZE($4);
}
if ((temp[$1] = PyList_GetItem ( $4 , long_$9 )) == 0) goto $2;
Py_INCREF(temp[$1]);
} else {
if ((temp[$1] = PyObject_GetItem ( $4 , temp[$0] )) == 0) goto $2;
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $3 ) && (long_$5 = PyInt_AS_LONG ( $3 )) $6 ) {
long_$9 = $7;
if ( long_$9 < 0) {
long_$9 += PyList_GET_SIZE($4);
}
if ((temp[$1] = PyList_GetItem ( $4 , long_$9 )) == 0) goto $2;
Py_INCREF(temp[$1]);
} else {
if ((temp[$0] = PyNumber_$8) == 0) goto $2;
if ((temp[$1] = PyObject_GetItem ( $4 , temp[$0] )) == 0) goto $2;
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $2 )) {
long_$3 = PyInt_AS_LONG ( $2 );
long_$3 = $5;
temp[$0] = PyInt_FromLong ( long_$3 );
} else {
if ((temp[$0] = PyNumber_$9) == 0) goto $6;
}
if (PyInt_CheckExact( temp[$0] )) {
temp[$1] = PyInt_FromLong ( PyInt_AS_LONG ( temp[$0] ) $7 );
} else {
if ((temp[$1] = PyNumber_$8) == 0) goto $6;
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $2 )) {
long_$3 = PyInt_AS_LONG ( $2 );
long_$3 = $5;
temp[$1] = PyInt_FromLong ( long_$3 $7 );
} else {
if ((temp[$0] = PyNumber_$9) == 0) goto $6;
if ((temp[$1] = PyNumber_$8) == 0) goto $6;
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $10 ) && (long_$5 = PyInt_AS_LONG ( $10 )) $6 ) {
temp[$1] = PyInt_FromLong ( $7 );
} else {
if ((temp[$1] = PyNumber_$8) == 0) goto $9;
}
if ((temp[$2] = PyObject_$10) == 0) goto $9;
if ((Py_ssize_t_$3 = $11 ( temp[$2] )) == -1) goto $9;
CLEARTEMP($2);
if (PyInt_CheckExact( temp[$1] )) {
int_$15 = PyInt_AS_LONG ( temp[$1] ) $12 Py_ssize_t_$3;
} else {
temp[$13] = PyInt_FromLong ( Py_ssize_t_$3 );
if ((int_$15 = PyObject_RichCompareBool ( temp[$1] , temp[$13] , $14 )) == -1) goto $9;
CLEARTEMP($13);
}
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $10 ) && (long_$5 = PyInt_AS_LONG ( $10 )) $6 ) {
if ((temp[$2] = PyObject_$10) == 0) goto $9;
if ((Py_ssize_t_$3 = $11 ( temp[$2] )) == -1) goto $9;
CLEARTEMP($2);
int_$15 = ($7) $12 Py_ssize_t_$3;
} else {
if ((temp[$1] = PyNumber_$8) == 0) goto $9;
if ((temp[$2] = PyObject_$10) == 0) goto $9;
if ((Py_ssize_t_$3 = $11 ( temp[$2] )) == -1) goto $9;
CLEARTEMP($2);
temp[$13] = PyInt_FromLong ( Py_ssize_t_$3 );
if ((int_$15 = PyObject_RichCompareBool ( temp[$1] , temp[$13] , $14 )) == -1) goto $9;
CLEARTEMP($13);
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( GETLOCAL($1) ) && (long_$5 = PyInt_AS_LONG ( GETLOCAL($1) )) < INT_MAX ) {
temp[$0] = PyInt_FromLong ( long_$5 + 1 );
} else {
if ((temp[$0] = PyNumber_$10Add ( GETLOCAL($1) , consts[$11] )) == 0) goto label_$12;
}
SETLOCAL ( $1 , temp[$0] );
temp[$0] = 0;
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( GETLOCAL($1) ) && (long_$5 = PyInt_AS_LONG ( GETLOCAL($1) )) < INT_MAX ) {
Py_DECREF(GETLOCAL($1));
GETLOCAL($1) = PyInt_FromLong ( long_$5 + 1 );
} else {
SETLOCAL ( $1 , PyNumber_$10Add ( GETLOCAL($1) , consts[$11] ) );
if (GETLOCAL($1) == 0) goto label_$12;
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( GETLOCAL($1) ) && (long_$4 = PyInt_AS_LONG ( GETLOCAL($1) )) < INT_MAX ) {
long_$4 = long_$4 + 1;
if ((temp[$10] = __c_BINARY_SUBSCR_Int ( $3 , long_$4 )) == 0) goto label_$12;
} else {
if ((temp[$0] = PyNumber_Add ( GETLOCAL($1) , consts[$11] )) == 0) goto label_$12;
if ((temp[$10] = PyObject_GetItem ( $3 , temp[$0] )) == 0) goto label_$12;
CLEARTEMP($0);
}
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( GETLOCAL($1) ) && (long_$4 = PyInt_AS_LONG ( GETLOCAL($1) )) < INT_MAX ) {
if ((temp[$10] = __c_BINARY_SUBSCR_Int ( $3 , long_$4 + 1 )) == 0) goto label_$12;
} else {
if ((temp[$0] = PyNumber_Add ( GETLOCAL($1) , consts[$11] )) == 0) goto label_$12;
if ((temp[$10] = PyObject_GetItem ( $3 , temp[$0] )) == 0) goto label_$12;
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( GETLOCAL($11) )) {
int_$1 = PyInt_AS_LONG ( GETLOCAL($11) ) < $2;
} else {
temp[$10] = PyInt_FromLong ( $2 );
if ((int_$1 = PyObject_RichCompareBool ( GETLOCAL($11) , temp[$10] , Py_LT )) == -1) goto label_$0;
CLEARTEMP($10);
}
if (!( int_$1 )) break;
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( GETLOCAL($11) )) {
if (PyInt_AS_LONG ( GETLOCAL($11) ) >= $2) break;
} else {
temp[$10] = PyInt_FromLong ( $2 );
if ((int_$1 = PyObject_RichCompareBool ( GETLOCAL($11) , temp[$10] , Py_LT )) == -1) goto label_$0;
CLEARTEMP($10);
if (!int_$1) break;
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( GETLOCAL($11) )) {
int_$1 = PyInt_AS_LONG ( GETLOCAL($11) ) < ($2);
} else {
temp[$10] = PyInt_FromLong ( $2 );
if ((int_$1 = PyObject_RichCompareBool ( GETLOCAL($11) , temp[$10] , Py_LT )) == -1) goto label_$0;
CLEARTEMP($10);
}
if (!( int_$1 )) break;
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( GETLOCAL($11) )) {
if (PyInt_AS_LONG ( GETLOCAL($11) ) >= ($2)) break;
} else {
temp[$10] = PyInt_FromLong ( $2 );
if ((int_$1 = PyObject_RichCompareBool ( GETLOCAL($11) , temp[$10] , Py_LT )) == -1) goto label_$0;
CLEARTEMP($10);
if (!int_$1) break;
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( GETLOCAL($10) ) && PyInt_CheckExact( $11 )) {
$14 = PyInt_AS_LONG ( GETLOCAL($10) );
$15 = PyInt_AS_LONG ( $11 );
$16 = $14 + $15;
if (( $16 ^ $14 ) < 0 && ( $16 ^ $15 ) < 0) goto $12 ;
temp[$17] = PyInt_FromLong ( $16 );
} else if (PyFloat_CheckExact( GETLOCAL($10) ) && PyFloat_CheckExact( $11 )) {
temp[$17] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(GETLOCAL($10)) + PyFloat_AS_DOUBLE($11));
} else { $12 :;
if ((temp[$17] = PyNumber_$5Add ( GETLOCAL($10) , $11 )) == 0) goto $13;
}
SETLOCAL ( $10 , temp[$17] );
temp[$17] = 0;
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( GETLOCAL($10) ) && PyInt_CheckExact( $11 )) {
$14 = PyInt_AS_LONG ( GETLOCAL($10) );
$15 = PyInt_AS_LONG ( $11 );
$16 = $14 + $15;
if (( $16 ^ $14 ) < 0 && ( $16 ^ $15 ) < 0) goto $12 ;
Py_DECREF(GETLOCAL($10));
GETLOCAL($10) = PyInt_FromLong ( $16 );
} else if (PyFloat_CheckExact( GETLOCAL($10) ) && PyFloat_CheckExact( $11 )) {
SETLOCAL ( $10 , PyFloat_FromDouble(PyFloat_AS_DOUBLE(GETLOCAL($10)) + PyFloat_AS_DOUBLE($11)) );
if (GETLOCAL($10) == 0) goto $13;
} else { $12 :;
SETLOCAL ( $10 , PyNumber_$5Add ( GETLOCAL($10) , $11 ) );
if (GETLOCAL($10) == 0) goto $13;
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $0 )) {
long_$2 = PyInt_AS_LONG ( $1 );
long_$3 = PyInt_AS_LONG ( $0 );
long_$4 = long_$2 $6 long_$3;
if ($5) goto label_$7 ;
temp[$9] = PyInt_FromLong ( long_$4 );
} else if (PyFloat_CheckExact( $0 )) {
temp[$9] = PyFloat_FromDouble((double)PyInt_AS_LONG ( $1 ) $6 PyFloat_AS_DOUBLE($0));
} else { label_$7 :;
if ((temp[$9] = PyNumber_$10 ( $1 , $0 )) == 0) goto label_$8;
}
if (PyInt_CheckExact( temp[$9] )) {
long_$11 = PyInt_AS_LONG ( temp[$9] );
long_$12 = long_$11 $18 $15;
if ($17) goto label_$13 ;
temp[$14] = PyInt_FromLong ( long_$12 );
} else if (PyFloat_CheckExact( temp[$9] )) {
temp[$14] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$9]) $18 ((double)$15));
} else { label_$13 :;
if ((temp[$14] = PyNumber_$19 ( temp[$9] , $16 )) == 0) goto label_$8;
}
CLEARTEMP($9);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $0 )) {
long_$2 = PyInt_AS_LONG ( $1 );
long_$3 = PyInt_AS_LONG ( $0 );
long_$4 = long_$2 $6 long_$3;
if ($5) goto label_$7 ;
long_$11 = long_$4;
long_$12 = long_$11 $18 $15;
if ($17) goto label_$7 ;
temp[$14] = PyInt_FromLong ( long_$12 );
} else if (PyFloat_CheckExact( $0 )) {
temp[$14] = PyFloat_FromDouble(((double)PyInt_AS_LONG ( $1 ) $6 PyFloat_AS_DOUBLE($0)) $18 ((double)$15));
} else { label_$7 :;
if ((temp[$9] = PyNumber_$10 ( $1 , $0 )) == 0) goto label_$8;
if ((temp[$14] = PyNumber_$19 ( temp[$9] , $16 )) == 0) goto label_$8;
CLEARTEMP($9);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( temp[$0] )) {
temp[$1] = PyInt_FromLong ( PyInt_AS_LONG ( temp[$0] ) $10 );
} else {
if ((temp[$1] = PyNumber_$12 ( temp[$0] , $13 )) == 0) goto label_$11;
}
CLEARTEMP($0);
if (PyInt_CheckExact( temp[$1] )) {
temp[$2] = PyInt_FromLong ( PyInt_AS_LONG ( temp[$1] ) $14 );
} else {
if ((temp[$2] = PyNumber_$16 ( temp[$1] , $15 )) == 0) goto label_$11;
}
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( temp[$0] )) {
temp[$2] = PyInt_FromLong ( (PyInt_AS_LONG ( temp[$0] ) $10) $14 );
} else {
if ((temp[$1] = PyNumber_$12 ( temp[$0] , $13 )) == 0) goto label_$11;
CLEARTEMP($0);
if ((temp[$2] = PyNumber_$16 ( temp[$1] , $15 )) == 0) goto label_$11;
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( temp[$0] )) {
long_$5 = PyInt_AS_LONG ( temp[$0] );
long_$6 = $12long_$5;
if ($10) goto label_$3 ;
temp[$1] = PyInt_FromLong ( long_$6 );
} else if (PyFloat_CheckExact( temp[$0] )) {
temp[$1] = PyFloat_FromDouble($14PyFloat_AS_DOUBLE(temp[$0]));
} else { label_$3 :;
if ((temp[$1] = PyNumber_Add ( $16 , temp[$0] )) == 0) goto label_$4;
}
CLEARTEMP($0);
if (PyInt_CheckExact( temp[$1] )) {
long_$7 = PyInt_AS_LONG ( temp[$1] );
long_$8 = long_$7 $13;
if ($11) goto label_$9 ;
temp[$2] = PyInt_FromLong ( long_$6 );
} else if (PyFloat_CheckExact( temp[$1] )) {
temp[$2] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$1])$15);
} else { label_$9 :;
if ((temp[$2] = PyNumber_Subtract ( temp[$1] , $17 )) == 0) goto label_$4;
}
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( temp[$0] )) {
long_$5 = PyInt_AS_LONG ( temp[$0] );
long_$6 = $12long_$5;
if ($10) goto label_$3 ;
long_$7 = long_$6;
long_$8 = long_$7 $13;
if ($11) goto label_$3 ;
temp[$2] = PyInt_FromLong ( long_$6 );
} else if (PyFloat_CheckExact( temp[$0] )) {
temp[$2] = PyFloat_FromDouble(($14PyFloat_AS_DOUBLE(temp[$0]))$15);
} else { label_$3 :;
if ((temp[$1] = PyNumber_Add ( $16 , temp[$0] )) == 0) goto label_$4;
CLEARTEMP($0);
if ((temp[$2] = PyNumber_Subtract ( temp[$1] , $17 )) == 0) goto label_$4;
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $14 )) {
long_$15 = PyInt_AS_LONG ( $14 );
long_$16 = long_$15 + $13;
if (( long_$16 ^ long_$15 ) < 0 && ( long_$16 ^ $13 ) < 0) goto label_$11 ;
temp[$18] = PyInt_FromLong ( long_$16 );
} else if (PyFloat_CheckExact( $14 )) {
temp[$18] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($14) + (double)$13);
} else { label_$11 :;
temp[$17] = PyInt_FromLong ($13);
if ((temp[$18] = PyNumber_Add ( $14 , temp[$17] )) == 0) goto label_$7;
CLEARTEMP($17);
}
if (PyInt_CheckExact( temp[$18] )) {
long_$19 = PyInt_AS_LONG ( temp[$18] );
long_$10 = long_$19 + 1;
if (( long_$10 ^ long_$19 ) < 0 && ( long_$10 ^ 1 ) < 0) goto label_$12 ;
temp[$9] = PyInt_FromLong ( long_$10 );
} else if (PyFloat_CheckExact( temp[$18] )) {
temp[$9] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$18]) + ((double)1));
} else { label_$12 :;
if ((temp[$9] = PyNumber_Add ( temp[$18] , $8 )) == 0) goto label_$7;
}
CLEARTEMP($18);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $14 )) {
long_$15 = PyInt_AS_LONG ( $14 );
long_$16 = long_$15 + $13;
if (( long_$16 ^ long_$15 ) < 0 && ( long_$16 ^ $13 ) < 0) goto label_$11 ;
long_$19 = long_$16;
long_$10 = long_$19 + 1;
if (( long_$10 ^ long_$19 ) < 0 && ( long_$10 ^ 1 ) < 0) goto label_$11 ;
temp[$9] = PyInt_FromLong ( long_$10 );
} else if (PyFloat_CheckExact( $14 )) {
temp[$9] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($14) + (double)$13 + ((double)1));
} else { label_$11 :;
temp[$17] = PyInt_FromLong ($13);
if ((temp[$18] = PyNumber_Add ( $14 , temp[$17] )) == 0) goto label_$7;
CLEARTEMP($17);
if ((temp[$9] = PyNumber_Add ( temp[$18] , $8 )) == 0) goto label_$7;
CLEARTEMP($18);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( temp[$2] )) {
long_$5 = PyInt_AS_LONG ( temp[$2] );
long_$6 = long_$5 + $7;
if (( long_$6 ^ long_$5 ) < 0 && ( long_$6 ^ $7 ) < 0) goto label_$4 ;
temp[$0] = PyInt_FromLong ( long_$6 );
} else if (PyFloat_CheckExact( temp[$2] )) {
temp[$0] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$2]) + ((double)$7));
} else { label_$4 :;
if ((temp[$0] = PyNumber_Add ( temp[$2] , $8 )) == 0) goto label_$1;
}
CLEARTEMP($2);
Py_ssize_t_$15 = PyInt_AsSsize_t ( temp[$0] );
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( temp[$2] )) {
long_$5 = PyInt_AS_LONG ( temp[$2] );
long_$6 = long_$5 + $7;
if (( long_$6 ^ long_$5 ) < 0 && ( long_$6 ^ $7 ) < 0) goto label_$4 ;
CLEARTEMP($2);
Py_ssize_t_$15 = long_$6;
} else { label_$4 :;
if ((temp[$0] = PyNumber_Add ( temp[$2] , $8 )) == 0) goto label_$1;
CLEARTEMP($2);
Py_ssize_t_$15 = PyInt_AsSsize_t ( temp[$0] );
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $1 ) && PyInt_CheckExact( $2 )) {
long_$5 = PyInt_AS_LONG ( $1 );
long_$6 = PyInt_AS_LONG ( $2 );
long_$7 = long_$5 + long_$6;
if (( long_$7 ^ long_$5 ) < 0 && ( long_$7 ^ long_$6 ) < 0) goto label_$4 ;
temp[$0] = PyInt_FromLong ( long_$7 );
} else if (PyFloat_CheckExact( $1 ) && PyFloat_CheckExact( $2 )) {
temp[$0] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) + PyFloat_AS_DOUBLE($2));
} else { label_$4 :;
if ((temp[$0] = PyNumber_Add ( $1 , $2 )) == 0) goto label_$3;
}
if ((int_$8 = c_$9_Int ( temp[$0] , $10 , $11 )) == -1) goto label_$3;
CLEARTEMP($0);
""", v2) and v2[9] in c_2_op_op:
v2[12] = c_2_op_op[v2[9]]
TxRepl(o, i, """
if (PyInt_CheckExact( $1 ) && PyInt_CheckExact( $2 )) {
long_$5 = PyInt_AS_LONG ( $1 );
long_$6 = PyInt_AS_LONG ( $2 );
long_$7 = long_$5 + long_$6;
if (( long_$7 ^ long_$5 ) < 0 && ( long_$7 ^ long_$6 ) < 0) goto label_$4 ;
int_$8 = long_$7 $12 $10;
} else if (PyFloat_CheckExact( $1 ) && PyFloat_CheckExact( $2 )) {
int_$8 = (PyFloat_AS_DOUBLE($1) + PyFloat_AS_DOUBLE($2)) $12 $10;
} else { label_$4 :;
if ((temp[$0] = PyNumber_Add ( $1 , $2 )) == 0) goto label_$3;
if ((int_$8 = PyObject_RichCompareBool ( temp[$0] , $11 , $9 )) == -1) goto label_$3;
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $10 )) {
long_$3 = PyInt_AS_LONG ( $10 );
long_$4 = PyInt_AS_LONG ( $10 );
long_$5 = long_$3 + long_$4;
if (( long_$5 ^ long_$3 ) < 0 && ( long_$5 ^ long_$4 ) < 0) goto label_$6 ;
temp[$0] = PyInt_FromLong ( long_$5 );
} else if (PyFloat_CheckExact( $10 )) {
temp[$0] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($10) + PyFloat_AS_DOUBLE($10));
} else { label_$6 :;
if ((temp[$0] = PyNumber_Add ( $10 , $10 )) == 0) goto label_$7;
}
if (PyFloat_CheckExact( temp[$0] )) {
temp[$2] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$0]) + $8);
} else {
temp[$1] = PyFloat_FromDouble ($8);
if ((temp[$2] = PyNumber_Add ( temp[$0] , temp[$1] )) == 0) goto label_$7;
CLEARTEMP($1);
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (PyFloat_CheckExact( $10 )) {
temp[$2] = PyFloat_FromDouble((PyFloat_AS_DOUBLE($10) * 2) + $8);
} else {
if ((temp[$0] = PyNumber_Add ( $10 , $10 )) == 0) goto label_$7;
temp[$1] = PyFloat_FromDouble ($8);
if ((temp[$2] = PyNumber_Add ( temp[$0] , temp[$1] )) == 0) goto label_$7;
CLEARTEMP($1);
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( temp[$0] ) && (long_$3 = PyInt_AS_LONG ( temp[$0] )) > $4 ) {
temp[$1] = PyInt_FromLong ( long_$3 $5 $6 );
} else {
if ((temp[$1] = PyNumber_$7 ( temp[$0] , $8 )) == 0) goto label_$9;
}
CLEARTEMP($0);
if (PyInt_CheckExact( temp[$1] )) {
int_$10 = $11 $12 PyInt_AS_LONG ( temp[$1] );
} else {
temp[$2] = PyInt_FromLong ( $11 );
if ((int_$10 = PyObject_RichCompareBool ( temp[$2] , temp[$1] , $13 )) == -1) goto label_$9;
CLEARTEMP($2);
}
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( temp[$0] ) && (long_$3 = PyInt_AS_LONG ( temp[$0] )) > $4 ) {
CLEARTEMP($0);
int_$10 = $11 $12 ( long_$3 $5 $6 );
} else {
if ((temp[$1] = PyNumber_$7 ( temp[$0] , $8 )) == 0) goto label_$9;
CLEARTEMP($0);
temp[$2] = PyInt_FromLong ( $11 );
if ((int_$10 = PyObject_RichCompareBool ( temp[$2] , temp[$1] , $13 )) == -1) goto label_$9;
CLEARTEMP($2);
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( temp[$0] )) {
long_$4 = PyInt_AS_LONG ( temp[$0] );
long_$5 = long_$4 $6 $7;
if ($8) goto label_$2 ;
temp[$1] = PyInt_FromLong ( long_$5 );
} else if (PyFloat_CheckExact( temp[$0] )) {
temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$0]) $6 ((double)$7));
} else { label_$2 :;
if ((temp[$1] = PyNumber_$10 ( temp[$0] , $11 )) == 0) goto label_$3;
}
CLEARTEMP($0);
Py_ssize_t_$12 = PyInt_AsSsize_t ( temp[$1] );
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( temp[$0] )) {
long_$4 = PyInt_AS_LONG ( temp[$0] );
long_$5 = long_$4 $6 $7;
if ($8) goto label_$2 ;
CLEARTEMP($0);
Py_ssize_t_$12 = long_$5;
} else { label_$2 :;
if ((temp[$1] = PyNumber_$10 ( temp[$0] , $11 )) == 0) goto label_$3;
CLEARTEMP($0);
Py_ssize_t_$12 = PyInt_AsSsize_t ( temp[$1] );
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( temp[$0] )) {
long_$4 = PyInt_AS_LONG ( temp[$0] );
long_$5 = long_$4 $6 $7;
if ($8) goto label_$2 ;
temp[$1] = PyInt_FromLong ( long_$5 );
temp[$0] = 0;
} else if (PyFloat_CheckExact( temp[$0] )) {
temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$0]) $6 ((double)$7));
temp[$0] = 0;
} else { label_$2 :;
Py_INCREF(temp[$0]);
if ((temp[$1] = PyNumber_$10 ( temp[$0] , $11 )) == 0) goto label_$3;
CLEARTEMP($0);
}
Py_ssize_t_$12 = PyInt_AsSsize_t ( temp[$1] );
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( temp[$0] )) {
long_$4 = PyInt_AS_LONG ( temp[$0] );
long_$5 = long_$4 $6 $7;
if ($8) goto label_$2 ;
temp[$0] = 0;
Py_ssize_t_$12 = long_$5;
} else { label_$2 :;
Py_INCREF(temp[$0]);
if ((temp[$1] = PyNumber_$10 ( temp[$0] , $11 )) == 0) goto label_$3;
CLEARTEMP($0);
Py_ssize_t_$12 = PyInt_AsSsize_t ( temp[$1] );
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $10 )) {
long_$11 = PyInt_AS_LONG ( $10 );
long_$12 = $14 - long_$11;
if (( long_$12 ^ $14 ) < 0 && ( long_$12 ^~ long_$11 ) < 0) goto label_$13 ;
temp[$0] = PyInt_FromLong ( long_$12 );
} else if (PyFloat_CheckExact( $10 )) {
temp[$0] = PyFloat_FromDouble(((double)$14) - PyFloat_AS_DOUBLE($10));
} else { label_$13 :;
if ((temp[$0] = PyNumber_Subtract ( $15 , $10 )) == 0) goto label_$16;
}
if (PyFloat_CheckExact( $10 ) && PyFloat_CheckExact( temp[$0] )) {
temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($10) * PyFloat_AS_DOUBLE(temp[$0]));
} else if (PyInt_CheckExact( $10 ) && PyInt_CheckExact( temp[$0] )) {
long_$17 = PyInt_AS_LONG ( $10 );
long_$18 = PyInt_AS_LONG ( temp[$0] );
if (long_$17 && long_$18 && (long_$17 * long_$18) / long_$18 == long_$17) {
temp[$1] = PyInt_FromLong ( long_$17 * long_$18 );
} else {
temp[$1] = PyInt_Type.tp_as_number->nb_multiply($10, temp[$0]);
}
} else {
if ((temp[$1] = PyNumber_Multiply ( $10 , temp[$0] )) == 0) goto label_$16;
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $10 )) {
long_$11 = PyInt_AS_LONG ( $10 );
long_$12 = $14 - long_$11;
if (( long_$12 ^ $14 ) < 0 && ( long_$12 ^~ long_$11 ) < 0) goto label_$13 ;
long_$18 = long_$12;
long_$17 = PyInt_AS_LONG ( $10 );
if (long_$17 && long_$18 && (long_$17 * long_$18) / long_$18 == long_$17) {
temp[$1] = PyInt_FromLong ( long_$17 * long_$18 );
} else { goto label_$13 ; }
} else if (PyFloat_CheckExact( $10 )) {
temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($10) * (((double)$14) - PyFloat_AS_DOUBLE($10)));
} else { label_$13 :;
if ((temp[$0] = PyNumber_Subtract ( $15 , $10 )) == 0) goto label_$16;
if ((temp[$1] = PyNumber_Multiply ( $10 , temp[$0] )) == 0) goto label_$16;
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( temp[$0] ) && PyInt_CheckExact( $4 )) {
long_$7 = PyInt_AS_LONG ( temp[$0] );
long_$8 = PyInt_AS_LONG ( $4 );
long_$9 = long_$7 - long_$8;
if (( long_$9 ^ long_$7 ) < 0 && ( long_$9 ^~ long_$8 ) < 0) goto label_$6 ;
temp[$2] = PyInt_FromLong ( long_$9 );
} else if (PyFloat_CheckExact( temp[$0] ) && PyFloat_CheckExact( $4 )) {
temp[$2] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$0]) - PyFloat_AS_DOUBLE($4));
} else { label_$6 :;
if ((temp[$2] = PyNumber_Subtract ( temp[$0] , $4 )) == 0) goto label_$5;
}
CLEARTEMP($0);
if (PyFloat_CheckExact( temp[$3] ) && PyFloat_CheckExact( temp[$2] )) {
temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$3]) * PyFloat_AS_DOUBLE(temp[$2]));
} else if (PyInt_CheckExact( temp[$3] ) && PyInt_CheckExact( temp[$2] )) {
long_$10 = PyInt_AS_LONG ( temp[$3] );
long_$11 = PyInt_AS_LONG ( temp[$2] );
if (long_$10 && long_$11 && (long_$10 * long_$11) / long_$11 == long_$10) {
temp[$1] = PyInt_FromLong ( long_$10 * long_$11 );
} else {
temp[$1] = PyInt_Type.tp_as_number->nb_multiply(temp[$3], temp[$2]);
}
} else {
if ((temp[$1] = PyNumber_Multiply ( temp[$3] , temp[$2] )) == 0) goto label_$5;
}
CLEARTEMP($3);
CLEARTEMP($2);
if ( PyList_SetItem ( $15 , $16 , temp[$1] ) == -1) goto label_$5;
temp[$1] = 0;
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( temp[$0] ) && PyInt_CheckExact( $4 ) && PyInt_CheckExact( temp[$3] )) {
long_$7 = PyInt_AS_LONG ( temp[$0] );
long_$8 = PyInt_AS_LONG ( $4 );
long_$9 = long_$7 - long_$8;
if (( long_$9 ^ long_$7 ) < 0 && ( long_$9 ^~ long_$8 ) < 0) goto label_$6 ;
long_$11 = long_$9;
long_$10 = PyInt_AS_LONG ( temp[$3] );
if (long_$10 && long_$11 && (long_$10 * long_$11) / long_$11 == long_$10) {
CLEARTEMP($0);
CLEARTEMP($3);
if ( PyList_SetItem ( $15 , $16 , PyInt_FromLong ( long_$10 * long_$11 ) ) == -1) goto label_$5;
} else { goto label_$6 ; }
} else if (PyFloat_CheckExact( temp[$0] ) && PyFloat_CheckExact( $4 ) && PyFloat_CheckExact( temp[$3] )) {
if ( PyList_SetItem ( $15 , $16 , PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$3]) * (PyFloat_AS_DOUBLE(temp[$0]) - PyFloat_AS_DOUBLE($4))) ) == -1) goto label_$5;
CLEARTEMP($0);
CLEARTEMP($3);
} else { label_$6 :;
if ((temp[$2] = PyNumber_Subtract ( temp[$0] , $4 )) == 0) goto label_$5;
CLEARTEMP($0);
if ((temp[$1] = PyNumber_Multiply ( temp[$3] , temp[$2] )) == 0) goto label_$5;
CLEARTEMP($2);
CLEARTEMP($3);
if ( PyList_SetItem ( $15 , $16 , temp[$1] ) == -1) goto label_$5;
temp[$1] = 0;
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $1 )) {
temp[$0] = $6;
} else {
if ((temp[$0] = $7) == 0) goto label_$3;
}
if ( _PyEval_PRINT_ITEM_1 ( temp[$0] ) == -1) goto label_$3;
CLEARTEMP($0);
if ( _PyEval_PRINT_NEWLINE_TO_1 ( NULL ) == -1) goto label_$3;
if (PyInt_CheckExact( $1 )) {
temp[$0] = $6;
} else {
if ((temp[$0] = $7) == 0) goto label_$3;
}
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $1 )) {
temp[$0] = $6;
} else {
if ((temp[$0] = $7) == 0) goto label_$3;
}
if ( _PyEval_PRINT_ITEM_1 ( temp[$0] ) == -1) goto label_$3;
if ( _PyEval_PRINT_NEWLINE_TO_1 ( NULL ) == -1) goto label_$3;
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( GETLOCAL($1) ) && (long_$2 = PyInt_AS_LONG ( GETLOCAL($1) )) < (INT_MAX >> $3) && long_$2 >= 0) {
temp[$0] = PyInt_FromLong ( long_$2 << $3 );
} else {
if ((temp[$0] = PyNumber_$5Lshift(GETLOCAL($1), $4)) == 0) goto label_$6;
}
SETLOCAL ( $1 , temp[$0] );
temp[$0] = 0;
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( GETLOCAL($1) ) && (long_$2 = PyInt_AS_LONG ( GETLOCAL($1) )) < (INT_MAX >> $3) && long_$2 >= 0) {
Py_DECREF(GETLOCAL($1));
GETLOCAL($1) = PyInt_FromLong ( long_$2 << $3 );
} else {
if ((temp[$0] = PyNumber_$5Lshift(GETLOCAL($1), $4)) == 0) goto label_$6;
SETLOCAL ( $1 , temp[$0] );
temp[$0] = 0;
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( temp[$0] )) {
long_$3 = PyInt_AS_LONG ( temp[$0] );
long_$4 = long_$3 + $7;
if (( long_$4 ^ long_$3 ) < 0 && ( long_$4 ^ $7 ) < 0) goto label_$5 ;
temp[$1] = PyInt_FromLong ( long_$4 );
} else if (PyFloat_CheckExact( temp[$0] )) {
temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$0]) + ((double)$7));
} else { label_$5 :;
if ((temp[$1] = PyNumber_Add ( temp[$0] , $9 )) == 0) goto label_$11;
}
CLEARTEMP($0);
if (PyInt_CheckExact( temp[$1] )) {
long_$3 = PyInt_AS_LONG ( temp[$1] );
long_$4 = $8 + long_$3;
if (( long_$4 ^ $8 ) < 0 && ( long_$4 ^ long_$3 ) < 0) goto label_$6 ;
temp[$2] = PyInt_FromLong ( long_$4 );
} else if (PyFloat_CheckExact( temp[$1] )) {
temp[$2] = PyFloat_FromDouble(((double)$8) + PyFloat_AS_DOUBLE(temp[$1]));
} else { label_$6 :;
if ((temp[$2] = PyNumber_Add ( $10 , temp[$1] )) == 0) goto label_$11;
}
CLEARTEMP($1);
""", v2) and v2[7].isdigit() and v2[8].isdigit():
v2[12] = '(' + v2[7] + ' + ' + v2[8] + ')'
TxRepl(o, i, """
if (PyInt_CheckExact( temp[$0] )) {
long_$3 = PyInt_AS_LONG ( temp[$0] );
long_$4 = long_$3 + $12;
if (( long_$4 ^ long_$3 ) < 0 && ( long_$4 ^ $12 ) < 0) goto label_$5 ;
CLEARTEMP($0);
temp[$2] = PyInt_FromLong ( long_$4 );
} else { label_$5 :;
if ((temp[$1] = PyNumber_Add ( temp[$0] , $9 )) == 0) goto label_$11;
CLEARTEMP($0);
if ((temp[$2] = PyNumber_Add ( $10 , temp[$1] )) == 0) goto label_$11;
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if ($9) {
temp[$0] = PyInt_FromLong ( $10 );
} else {
if ((temp[$0] = PyNumber_$11) == 0) goto label_$12;
}
if (PyInt_CheckExact( temp[$0] )) {
long_$5 = PyInt_AS_LONG ( temp[$0] );
long_$6 = long_$5 $15 $14;
if ($16) goto label_$13 ;
temp[$1] = PyInt_FromLong ( long_$6 );
} else if (PyFloat_CheckExact( temp[$0] )) {
temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$0]) $15 ((double)$14));
} else { label_$13 :;
if ((temp[$1] = PyNumber_$17 ( temp[$0] , $18 )) == 0) goto label_$12;
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if ($9) {
long_$5 = $10;
long_$6 = long_$5 $15 $14;
if ($16) goto label_$13 ;
temp[$1] = PyInt_FromLong ( long_$6 );
} else { label_$13 :;
if ((temp[$0] = PyNumber_$11) == 0) goto label_$12;
if ((temp[$1] = PyNumber_$17 ( temp[$0] , $18 )) == 0) goto label_$12;
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $1 ) && (long_$3 = PyInt_AS_LONG ( $1 )) $6 ) {
temp[$0] = PyInt_FromLong ( long_$3 $7 );
} else {
if ((temp[$0] = PyNumber_$8 ( $1 , $9 )) == 0) goto label_$5;
}
if (PyInt_CheckExact( temp[$0] )) {
long_$4 = PyInt_AS_LONG ( temp[$0] );
if ( long_$4 < 0) {
long_$4 += PyString_GET_SIZE($10);
}
if (long_$4 < 0 || long_$4 >= PyString_GET_SIZE($10)) goto label_$18;
temp[$2] = PyString_FromStringAndSize((PyString_AS_STRING ( $10 ) + long_$4), 1);
} else {
if ((temp[$2] = PyObject_GetItem ( $10 , temp[$0] )) == 0) goto label_$5;
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $1 ) && (long_$3 = PyInt_AS_LONG ( $1 )) $6 ) {
long_$3 = long_$3 $7;
if ( long_$3 < 0) {
long_$3 += PyString_GET_SIZE($10);
}
if (long_$3 < 0 || long_$3 >= PyString_GET_SIZE($10)) goto label_$18;
temp[$2] = PyString_FromStringAndSize((PyString_AS_STRING ( $10 ) + long_$3), 1);
} else {
if ((temp[$0] = PyNumber_$8 ( $1 , $9 )) == 0) goto label_$5;
if ((temp[$2] = PyObject_GetItem ( $10 , temp[$0] )) == 0) goto label_$5;
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $0 )) {
long_$2 = PyInt_AS_LONG ( $0 );
if ( long_$2 < 0) {
long_$2 += PyString_GET_SIZE($1);
}
if (long_$2 < 0 || long_$2 >= PyString_GET_SIZE($1)) goto label_$3;
temp[$4] = PyString_FromStringAndSize((PyString_AS_STRING ( $1 ) + long_$2), 1);
} else {
if ((temp[$4] = PyObject_GetItem ( $1 , $0 )) == 0) goto label_$5;
}
if (PyString_GET_SIZE( temp[$4] ) == 1) {
long_$12 = (long)((unsigned char)*PyString_AS_STRING ( temp[$4] ));
temp[$6] = PyInt_FromLong ( long_$12 );
} else {
if ((temp[$7] = PyTuple_New ( 1 )) == 0) goto label_$5;
PyTuple_SET_ITEM ( temp[$7] , 0 , temp[$4] );
temp[$4] = 0;
if ((temp[$6] = PyCFunction_Call ( loaded_builtin[$8] , temp[$7] , NULL )) == 0) goto label_$5;
CLEARTEMP($7);
}
CLEARTEMP($4);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $0 )) {
long_$2 = PyInt_AS_LONG ( $0 );
if ( long_$2 < 0) {
long_$2 += PyString_GET_SIZE($1);
}
if (long_$2 < 0 || long_$2 >= PyString_GET_SIZE($1)) goto label_$3;
temp[$6] = PyInt_FromLong ( (long)((unsigned char) PyString_AS_STRING ( $1 )[long_$2] ) );
} else {
if ((temp[$4] = PyObject_GetItem ( $1 , $0 )) == 0) goto label_$5;
if ((temp[$7] = PyTuple_New ( 1 )) == 0) goto label_$5;
PyTuple_SET_ITEM ( temp[$7] , 0 , temp[$4] );
temp[$4] = 0;
if ((temp[$6] = PyCFunction_Call ( loaded_builtin[$8] , temp[$7] , NULL )) == 0) goto label_$5;
CLEARTEMP($7);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $0 ) && (long_$1 = PyInt_AS_LONG ( $0 )) $2 ) {
long_$1 = long_$1 $3;
if ( long_$1 < 0) {
long_$1 += PyString_GET_SIZE($4);
}
if (long_$1 < 0 || long_$1 >= PyString_GET_SIZE($4)) goto label_$5;
temp[$9] = PyString_FromStringAndSize((PyString_AS_STRING ( $4 ) + long_$1), 1);
} else {
if ((temp[$8] = PyNumber_Add ( $0 , $7 )) == 0) goto label_$6;
if ((temp[$9] = PyObject_GetItem ( $4 , temp[$8] )) == 0) goto label_$6;
CLEARTEMP($8);
}
if (PyString_GET_SIZE( temp[$9] ) == 1) {
long_$12 = (long)((unsigned char)*PyString_AS_STRING ( temp[$9] ));
temp[$8] = PyInt_FromLong ( long_$12 );
} else {
if ((temp[$19] = PyTuple_New ( 1 )) == 0) goto label_$6;
PyTuple_SET_ITEM ( temp[$10] , 0 , temp[$9] );
temp[$9] = 0;
if ((temp[$8] = PyCFunction_Call ( loaded_builtin[$11] , temp[$10] , NULL )) == 0) goto label_$6;
CLEARTEMP($10);
}
CLEARTEMP($9);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $0 ) && (long_$1 = PyInt_AS_LONG ( $0 )) $2 ) {
long_$1 = long_$1 $3;
if ( long_$1 < 0) {
long_$1 += PyString_GET_SIZE($4);
}
if (long_$1 < 0 || long_$1 >= PyString_GET_SIZE($4)) goto label_$5;
temp[$8] = PyInt_FromLong ( (long)((unsigned char)PyString_AS_STRING ( $4 )[long_$1] ) );
} else {
if ((temp[$8] = PyNumber_Add ( $0 , $7 )) == 0) goto label_$6;
if ((temp[$9] = PyObject_GetItem ( $4 , temp[$8] )) == 0) goto label_$6;
CLEARTEMP($8);
if ((temp[$10] = PyTuple_New ( 1 )) == 0) goto label_$6;
PyTuple_SET_ITEM ( temp[$10] , 0 , temp[$9] );
temp[$9] = 0;
if ((temp[$8] = PyCFunction_Call ( loaded_builtin[$11] , temp[$10] , NULL )) == 0) goto label_$6;
CLEARTEMP($10);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $0 ) && (long_$1 = PyInt_AS_LONG ( $0 )) $4 ) {
temp[$2] = PyInt_FromLong ( long_$1 $5 );
} else {
if ((temp[$2] = PyNumber_Subtract ( $0 , $7 )) == 0) goto label_$6;
}
if ((Py_ssize_t_$8 = PyObject_Size ( $15 )) == -1) goto label_$6;
if (PyInt_CheckExact( temp[$2] )) {
int_$9 = PyInt_AS_LONG ( temp[$2] ) $11 Py_ssize_t_$8;
} else {
temp[$10] = PyInt_FromLong ( Py_ssize_t_$8 );
if ((int_$9 = PyObject_RichCompareBool ( temp[$2] , temp[$10] , $12 )) == -1) goto label_$6;
CLEARTEMP($10);
}
CLEARTEMP($2);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $0 ) && (long_$1 = PyInt_AS_LONG ( $0 )) $4 ) {
if ((Py_ssize_t_$8 = PyObject_Size ( $15 )) == -1) goto label_$6;
int_$9 = ( long_$1 $5 ) $11 Py_ssize_t_$8;
} else {
if ((temp[$2] = PyNumber_Subtract ( $0 , $7 )) == 0) goto label_$6;
if ((Py_ssize_t_$8 = PyObject_Size ( $15 )) == -1) goto label_$6;
temp[$10] = PyInt_FromLong ( Py_ssize_t_$8 );
if ((int_$9 = PyObject_RichCompareBool ( temp[$2] , temp[$10] , $12 )) == -1) goto label_$6;
CLEARTEMP($10);
CLEARTEMP($2);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( temp[$0] )) {
temp[$1] = PyInt_FromLong ( $2 );
} else {
if ((temp[$1] = PyNumber_$3) == 0) goto label_$10;
}
CLEARTEMP($0);
if ((int_$4 = PyObject_IsTrue ( temp[$1] )) == -1) goto label_$10;
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( temp[$0] )) {
int_$4 = ( $2 ) != 0;
CLEARTEMP($0);
} else {
if ((temp[$1] = PyNumber_$3) == 0) goto label_$10;
CLEARTEMP($0);
if ((int_$4 = PyObject_IsTrue ( temp[$1] )) == -1) goto label_$10;
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $19 )) {
long_$18 = PyInt_AS_LONG ( $19 );
if ( long_$18 < 0) {
long_$18 += PyString_GET_SIZE($17);
}
if (long_$18 < 0 || long_$18 >= PyString_GET_SIZE($17)) goto label_$16;
temp[$15] = PyString_FromStringAndSize((PyString_AS_STRING ( $17 ) + long_$18), 1);
} else {
if ((temp[$15] = PyObject_GetItem ( $17 , $19 )) == 0) goto label_$14;
}
if (PyString_GET_SIZE( temp[$15] ) == 1) {
long_$18 = (long)((unsigned char)*PyString_AS_STRING ( temp[$15] ));
temp[$13] = PyInt_FromLong ( long_$18 );
} else {
if ((temp[$12] = PyTuple_New ( 1 )) == 0) goto label_$14;
PyTuple_SET_ITEM ( temp[$12] , 0 , temp[$15] );
temp[$15] = 0;
if ((temp[$13] = PyCFunction_Call ( $11 , temp[$12] , NULL )) == 0) goto label_$14;
CLEARTEMP($12);
}
Py_CLEAR(temp[$15]);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $19 )) {
long_$18 = PyInt_AS_LONG ( $19 );
if ( long_$18 < 0) {
long_$18 += PyString_GET_SIZE($17);
}
if (long_$18 < 0 || long_$18 >= PyString_GET_SIZE($17)) goto label_$16;
temp[$13] = PyInt_FromLong ( (long)(unsigned char)(PyString_AS_STRING ( $17 )[long_$18]) );
} else {
if ((temp[$15] = PyObject_GetItem ( $17 , $19 )) == 0) goto label_$14;
if ((temp[$12] = PyTuple_New ( 1 )) == 0) goto label_$14;
PyTuple_SET_ITEM ( temp[$12] , 0 , temp[$15] );
temp[$15] = 0;
if ((temp[$13] = PyCFunction_Call ( $11 , temp[$12] , NULL )) == 0) goto label_$14;
CLEARTEMP($12);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $1 ) && (long_$2 = PyInt_AS_LONG ( $1 )) $3 ) {
temp[$8] = PyInt_FromLong ( long_$2 $4 );
} else if (PyFloat_CheckExact( $1 )) {
temp[$8] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($1) $5);
} else {
if ((temp[$8] = PyNumber_$7 ( $1 , consts[$6] )) == 0) goto label_$10;
}
if (PyInt_CheckExact( temp[$8] )) {
temp[$9] = PyInt_FromLong ( PyInt_AS_LONG ( temp[$8] ) $11 );
} else {
if ((temp[$9] = PyNumber_$12 ( temp[$8] , consts[$14] )) == 0) goto label_$10;
}
CLEARTEMP($8);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $1 ) && (long_$2 = PyInt_AS_LONG ( $1 )) $3 ) {
temp[$9] = PyInt_FromLong ( ( long_$2 $4 ) $11 );
} else {
if ((temp[$8] = PyNumber_$7 ( $1 , consts[$6] )) == 0) goto label_$10;
if ((temp[$9] = PyNumber_$12 ( temp[$8] , consts[$14] )) == 0) goto label_$10;
CLEARTEMP($8);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( $5 ) && (long_$6 = PyInt_AS_LONG ( $5 )) $7 ) {
temp[$1] = PyInt_FromLong ( $8 );
} else {
if ((temp[$0] = PyNumber_$9 ( $11 )) == 0) goto label_$4;
if ((temp[$1] = PyNumber_$10 ( $12 )) == 0) goto label_$4;
CLEARTEMP($0);
}
if (PyInt_CheckExact( temp[$1] )) {
long_$13 = PyInt_AS_LONG ( temp[$1] );
long_$14 = long_$13 $15;
if ($16) goto label_$3 ;
temp[$2] = PyInt_FromLong ( long_$14 );
} else if (PyFloat_CheckExact( temp[$1] )) {
temp[$2] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$1]) $17);
} else { label_$3 :;
if ((temp[$2] = PyNumber_$18 ( $19 )) == 0) goto label_$4;
}
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if (PyInt_CheckExact( $5 ) && (long_$6 = PyInt_AS_LONG ( $5 )) $7 ) {
long_$13 = $8;
long_$14 = long_$13 $15;
if ($16) goto label_$3 ;
temp[$2] = PyInt_FromLong ( long_$14 );
} else { label_$3 :;
if ((temp[$0] = PyNumber_$9 ( $11 )) == 0) goto label_$4;
if ((temp[$1] = PyNumber_$10 ( $12 )) == 0) goto label_$4;
CLEARTEMP($0);
if ((temp[$2] = PyNumber_$18 ( $19 )) == 0) goto label_$4;
CLEARTEMP($1);
}
""", v2)
return True
if '_CheckExact' in o[i]:
if TxMatch(o, i, """
if (Py$1_CheckExact( $2 ) && Py$1_CheckExact( $2 )) {
""", v2):
TxRepl(o, i, """
if (Py$1_CheckExact( $2 )) {
""", v2)
return True
if TxMatch(o, i, """
if (Py$1_CheckExact( temp[$2] ) && Py$1_CheckExact( temp[$2] )) {
""", v2):
TxRepl(o, i, """
if (Py$1_CheckExact( temp[$2] )) {
""", v2)
return True
if TxMatch(o, i, """
if (PyInt_CheckExact( temp[$1] ) && PyInt_CheckExact( temp[$3] )) {
long_$7;
long_$8;
long_$9;
if ($19) goto label_$6 ;
temp[$0] = PyInt_FromLong ( long_$18 );
} else if (PyFloat_CheckExact( temp[$1] ) && PyFloat_CheckExact( temp[$3] )) {
temp[$0] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$1]) $17 PyFloat_AS_DOUBLE(temp[$3]));
} else { label_$6 :;
if ((temp[$0] = PyNumber_$16 ( temp[$1] , temp[$3] )) == 0) goto label_$5;
}
CLEARTEMP($1);
CLEARTEMP($3);
if (PyFloat_CheckExact( temp[$0] )) {
temp[$1] = PyFloat_FromDouble($10);
} else {
if ((temp[$1] = PyNumber_$11) == 0) goto label_$5;
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (PyFloat_CheckExact( temp[$1] ) && PyFloat_CheckExact( temp[$3] )) {
temp[$0] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$1]) $17 PyFloat_AS_DOUBLE(temp[$3]));
} else {
if ((temp[$0] = PyNumber_$16 ( temp[$1] , temp[$3] )) == 0) goto label_$5;
}
CLEARTEMP($1);
CLEARTEMP($3);
if (PyFloat_CheckExact( temp[$0] )) {
temp[$1] = PyFloat_FromDouble($10);
} else {
if ((temp[$1] = PyNumber_$11) == 0) goto label_$5;
}
CLEARTEMP($0);
""", v2)
return True
if 'PyFloat_CheckExact' in o[i]:
if TxMatch(o, i, """
if (PyFloat_CheckExact( temp[$0] )) {
temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$0]) * PyFloat_AS_DOUBLE(temp[$0]));
} else if (PyInt_CheckExact( temp[$0] )) {
long_$3 = PyInt_AS_LONG ( temp[$0] );
if (!long_$3 || (long_$3 * long_$3) / long_$3 == long_$3) {
temp[$1] = PyInt_FromLong ( long_$3 * long_$3 );
} else {
temp[$1] = PyInt_Type.tp_as_number->nb_multiply(temp[$0], temp[$0]);
}
} else {
if ((temp[$1] = PyNumber_Multiply ( temp[$0] , temp[$0] )) == 0) goto label_$2;
}
CLEARTEMP($0);
if (PyFloat_CheckExact( temp[$1] )) {
temp[$0] = PyFloat_FromDouble($5);
} else {
if ((temp[$0] = PyNumber_$6) == 0) goto label_$2;
}
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if (PyFloat_CheckExact( temp[$0] )) {
temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$0]) * PyFloat_AS_DOUBLE(temp[$0]));
} else {
if ((temp[$1] = PyNumber_Multiply ( temp[$0] , temp[$0] )) == 0) goto label_$2;
}
CLEARTEMP($0);
if (PyFloat_CheckExact( temp[$1] )) {
temp[$0] = PyFloat_FromDouble($5);
} else {
if ((temp[$0] = PyNumber_$6) == 0) goto label_$2;
}
CLEARTEMP($1);
""", v2)
return True
if TxMatch(o, i, """
if (PyFloat_CheckExact( temp[$0] )) {
temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$0]) * PyFloat_AS_DOUBLE(temp[$0]));
} else if (PyInt_CheckExact( temp[$0] )) {
long_$3 = PyInt_AS_LONG ( temp[$0] );
if (!long_$3 || (long_$3 * long_$3) / long_$3 == long_$3) {
temp[$1] = PyInt_FromLong ( long_$3 * long_$3 );
} else {
temp[$1] = PyInt_Type.tp_as_number->nb_multiply(temp[$0], temp[$0]);
}
} else {
if ((temp[$1] = PyNumber_Multiply ( temp[$0] , temp[$0] )) == 0) goto label_$2;
}
CLEARTEMP($0);
if (PyFloat_CheckExact( temp[$1] )) {
temp[$0] = PyFloat_FromDouble($5 * PyFloat_AS_DOUBLE(temp[$1]));
} else {
if ((temp[$0] = PyNumber_Multiply ( $6 , temp[$1] )) == 0) goto label_$2;
}
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if (PyFloat_CheckExact( temp[$0] )) {
temp[$1] = temp[$0];
temp[$0] = PyFloat_FromDouble($5 * (PyFloat_AS_DOUBLE(temp[$0]) * PyFloat_AS_DOUBLE(temp[$0])));
CLEARTEMP($1);
} else {
if ((temp[$1] = PyNumber_Multiply ( temp[$0] , temp[$0] )) == 0) goto label_$2;
CLEARTEMP($0);
if ((temp[$0] = PyNumber_Multiply ( $6 , temp[$1] )) == 0) goto label_$2;
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyFloat_CheckExact( temp[$1] )) {
temp[$0] = PyFloat_FromDouble($5 $16 PyFloat_AS_DOUBLE(temp[$1]));
} else {
if ((temp[$0] = PyNumber_$17 ( $6 , temp[$1] )) == 0) goto label_$3;
}
CLEARTEMP($1);
if (PyInt_CheckExact( $2 ) && PyInt_CheckExact( temp[$0] )) {
long_$7 = $10;
long_$8 = $11;
long_$9 = $12;
if ($13) goto label_$4 ;
temp[$1] = PyInt_FromLong ( long_$9 );
} else if (PyFloat_CheckExact( $2 ) && PyFloat_CheckExact( temp[$0] )) {
temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($2) $14 PyFloat_AS_DOUBLE(temp[$0]));
} else { label_$4 :;
if ((temp[$1] = PyNumber_$15 ( $2 , temp[$0] )) == 0) goto label_$3;
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (PyFloat_CheckExact( temp[$1] )) {
temp[$0] = PyFloat_FromDouble($5 $16 PyFloat_AS_DOUBLE(temp[$1]));
} else {
if ((temp[$0] = PyNumber_$17 ( $6 , temp[$1] )) == 0) goto label_$3;
}
CLEARTEMP($1);
if (PyFloat_CheckExact( $2 ) && PyFloat_CheckExact( temp[$0] )) {
temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($2) $14 PyFloat_AS_DOUBLE(temp[$0]));
} else {
if ((temp[$1] = PyNumber_$15 ( $2 , temp[$0] )) == 0) goto label_$3;
}
CLEARTEMP($0);
""", v2)
return True
if TxMatch(o, i, """
if (PyFloat_CheckExact( temp[$1] ) && PyFloat_CheckExact( temp[$3] )) {
temp[$0] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$1]) $4 PyFloat_AS_DOUBLE(temp[$3]));
} else {
if ((temp[$0] = PyNumber_$5 ( temp[$1] , temp[$3] )) == 0) goto label_0;
}
CLEARTEMP($1);
CLEARTEMP($3);
if (PyFloat_CheckExact( temp[$0] )) {
temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$0]) $6 PyFloat_AS_DOUBLE(temp[$0]));
} else {
if ((temp[$1] = PyNumber_$7 ( temp[$0] , temp[$0] )) == 0) goto label_0;
}
""", v2):
TxRepl(o, i, """
if (PyFloat_CheckExact( temp[$1] ) && PyFloat_CheckExact( temp[$3] )) {
temp[$0] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$1]) $4 PyFloat_AS_DOUBLE(temp[$3]));
CLEARTEMP($1);
CLEARTEMP($3);
temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$0]) $6 PyFloat_AS_DOUBLE(temp[$0]));
} else {
if ((temp[$0] = PyNumber_$5 ( temp[$1] , temp[$3] )) == 0) goto label_0;
CLEARTEMP($1);
CLEARTEMP($3);
if ((temp[$1] = PyNumber_$7 ( temp[$0] , temp[$0] )) == 0) goto label_0;
}
""", v2)
return True
if TxMatch(o, i, """
if ($10) {
temp[$0] = PyFloat_FromDouble($11);
CLEARTEMP($1);
CLEARTEMP($3);
temp[$1] = PyFloat_FromDouble($12);
} else {
if ((temp[$0] = PyNumber_$13) == 0) goto label_$17;
CLEARTEMP($1);
CLEARTEMP($3);
if ((temp[$1] = PyNumber_$14) == 0) goto label_$17;
}
CLEARTEMP($0);
if (PyFloat_CheckExact( temp[$1] )) {
temp[$0] = PyFloat_FromDouble($15);
} else {
if ((temp[$0] = PyNumber_$16) == 0) goto label_$17;
}
""", v2):
TxRepl(o, i, """
if ($10) {
temp[$0] = PyFloat_FromDouble($11);
CLEARTEMP($1);
CLEARTEMP($3);
temp[$1] = PyFloat_FromDouble($12);
CLEARTEMP($0);
temp[$0] = PyFloat_FromDouble($15);
} else {
if ((temp[$0] = PyNumber_$13) == 0) goto label_$17;
CLEARTEMP($1);
CLEARTEMP($3);
if ((temp[$1] = PyNumber_$14) == 0) goto label_$17;
CLEARTEMP($0);
if ((temp[$0] = PyNumber_$16) == 0) goto label_$17;
}
""", v2)
return True
if TxMatch(o, i, """
if ($10) {
temp[$0] = PyFloat_FromDouble($11);
CLEARTEMP($1);
temp[$1] = PyFloat_FromDouble($12);
} else {
if ((temp[$0] = PyNumber_$13) == 0) goto label_$17;
CLEARTEMP($1);
if ((temp[$1] = PyNumber_$14) == 0) goto label_$17;
}
CLEARTEMP($0);
if (PyFloat_CheckExact( temp[$1] )) {
temp[$0] = PyFloat_FromDouble($15);
} else {
if ((temp[$0] = PyNumber_$16) == 0) goto label_$17;
}
""", v2):
TxRepl(o, i, """
if ($10) {
temp[$0] = PyFloat_FromDouble($11);
CLEARTEMP($1);
temp[$1] = PyFloat_FromDouble($12);
CLEARTEMP($0);
temp[$0] = PyFloat_FromDouble($15);
} else {
if ((temp[$0] = PyNumber_$13) == 0) goto label_$17;
CLEARTEMP($1);
if ((temp[$1] = PyNumber_$14) == 0) goto label_$17;
CLEARTEMP($0);
if ((temp[$0] = PyNumber_$16) == 0) goto label_$17;
}
""", v2)
return True
if TxMatch(o, i, """
if ($10) {
temp[$0] = PyFloat_FromDouble($11);
temp[$1] = PyFloat_FromDouble($12);
} else {
if ((temp[$0] = PyNumber_$13) == 0) goto label_$17;
if ((temp[$1] = PyNumber_$14) == 0) goto label_$17;
}
CLEARTEMP($0);
if (PyFloat_CheckExact( temp[$1] )) {
temp[$0] = PyFloat_FromDouble($15);
} else {
if ((temp[$0] = PyNumber_$16) == 0) goto label_$17;
}
""", v2):
TxRepl(o, i, """
if ($10) {
temp[$0] = PyFloat_FromDouble($11);
temp[$1] = PyFloat_FromDouble($12);
CLEARTEMP($0);
temp[$0] = PyFloat_FromDouble($15);
} else {
if ((temp[$0] = PyNumber_$13) == 0) goto label_$17;
if ((temp[$1] = PyNumber_$14) == 0) goto label_$17;
CLEARTEMP($0);
if ((temp[$0] = PyNumber_$16) == 0) goto label_$17;
}
""", v2)
return True
if 'if (PyInstance_Check(' in o[i]:
if TxMatch(o, i, ('if (PyInstance_Check($1) && ((PyInstanceObject *)$1)->in_class == (PyClassObject*)$2) {',
'if ((temp[$7] = $5) == 0) goto $0;',
'} else',
'if (PyInstance_Check($1) && ((PyInstanceObject *)$1)->in_class == (PyClassObject*)$3) {',
'if ((temp[$7] = $5) == 0) goto $0;',
'} else'), v2):
TxRepl(o, i, ('if (PyInstance_Check($1) && (((PyInstanceObject *)$1)->in_class == (PyClassObject*)$2 || (((PyInstanceObject *)$1)->in_class == (PyClassObject*)$3))) {',
'if ((temp[$7] = $5) == 0) goto $0;',
'} else'), v2)
return True
if TxMatch(o, i, ('if (PyInstance_Check($1) && (((PyInstanceObject *)$1)->in_class == (PyClassObject*)$2 || ($9))) {',
'if ((temp[$7] = $5) == 0) goto $0;',
'} else',
'if (PyInstance_Check($1) && ((PyInstanceObject *)$1)->in_class == (PyClassObject*)$3) {',
'if ((temp[$7] = $5) == 0) goto $0;',
'} else'), v2):
TxRepl(o, i, ('if (PyInstance_Check($1) && (((PyInstanceObject *)$1)->in_class == (PyClassObject*)$2 || ($9 || (((PyInstanceObject *)$1)->in_class == (PyClassObject*)$3)))) {',
'if ((temp[$7] = $5) == 0) goto $0;',
'} else'), v2)
return True
if TxMatch(o, i, """
if (PyInstance_Check($3) && $4) {
if ((temp[$10] = _Direct_$17 ( $3 $5)) == 0) goto label_$0;
} else {
if ((temp[$11] = PyObject_GetAttr ( $3 , $6 )) == 0) goto label_$0;
if ((temp[$10] = FastCall($7)) == 0) goto label_$0;
CLEARTEMP($11);
}
CLEARTEMP($10);
""", v2):
TxRepl(o, i, """
if (PyInstance_Check($3) && $4) {
if ((temp[$10] = _Direct_$17 ( $3 $5)) == 0) goto label_$0;
CLEARTEMP($10);
} else {
if ((temp[$11] = PyObject_GetAttr ( $3 , $6 )) == 0) goto label_$0;
if ((temp[$10] = FastCall($7)) == 0) goto label_$0;
CLEARTEMP($10);
CLEARTEMP($11);
}
""", v2)
return True
if 'Py_TYPE' in o[i]:
if TxMatch(o, i, ('if (((PyObject *)Py_TYPE($1)) == $2) {',
'if ((temp[$7] = $5) == 0) goto $0;',
'} else',
'if (((PyObject *)Py_TYPE($1)) == $3) {',
'if ((temp[$7] = $5) == 0) goto $0;',
'} else'), v2):
TxRepl(o, i, ('if (((PyObject *)Py_TYPE($1)) == $2 || (((PyObject *)Py_TYPE($1)) == $3)) {',
'if ((temp[$7] = $5) == 0) goto $0;',
'} else'), v2)
return True
if TxMatch(o, i, ('if (((PyObject *)Py_TYPE($1)) == $2 || ($6)) {',
'if ((temp[$7] = $5) == 0) goto $0;',
'} else',
'if (((PyObject *)Py_TYPE($1)) == $3) {',
'if ((temp[$7] = $5) == 0) goto $0;',
'} else'), v2):
TxRepl(o, i, ('if (((PyObject *)Py_TYPE($1)) == $2 || (($6) || ((PyObject *)Py_TYPE($1)) == $3)) {',
'if ((temp[$7] = $5) == 0) goto $0;',
'} else'), v2)
return True
if TxMatch(o, i, ('if (((PyObject *)Py_TYPE($4)) == calculated_const[$5]) {',
'if ((int_$8 = _Direct_$9($4)) == -1) goto $3;',
'temp[$1] = PyBool_FromLong(int_$8);',
'} else',
'{',
'if ((temp[$2] = PyObject_GetAttr ( $4 , $6 )) == 0) goto $3;',
'if ((temp[$1] = FastCall0(temp[$2])) == 0) goto $3;',
'CLEARTEMP($2);',
'}',
'if ((int_$7 = PyObject_IsTrue ( temp[$1] )) == -1) goto $3;',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if (((PyObject *)Py_TYPE($4)) == calculated_const[$5]) {',
'if ((int_$7 = _Direct_$9($4)) == -1) goto $3;',
'} else',
'{',
'if ((temp[$2] = PyObject_GetAttr ( $4 , $6 )) == 0) goto $3;',
'if ((temp[$1] = FastCall0(temp[$2])) == 0) goto $3;',
'CLEARTEMP($2);',
'if ((int_$7 = PyObject_IsTrue ( temp[$1] )) == -1) goto $3;',
'CLEARTEMP($1);',
'}'), v2)
return True
if o[i].startswith('if (_'):
if TxMatch(o, i, ('if (_$1_dict && (temp[$3] = PyDict_GetItem(_$1_dict, $4)) != 0) {',
'Py_INCREF(temp[$3]);',
'} else {',
'if ((temp[$3] = PyObject_GetAttr ( GETLOCAL($1) , $4 )) == 0) goto $2;',
'}',
'if ( PyList_SetItem ( temp[$3] , $5 , $6 ) == -1) goto $2;',
'CLEARTEMP($3);'), v2):
TxRepl(o, i, ('if (_$1_dict && (temp[$3] = PyDict_GetItem(_$1_dict, $4)) != 0) {',
'if ( PyList_SetItem ( temp[$3] , $5 , $6 ) == -1) goto $2;',
'temp[$3] = 0;',
'} else {',
'if ((temp[$3] = PyObject_GetAttr ( GETLOCAL($1) , $4 )) == 0) goto $2;',
'if ( PyList_SetItem ( temp[$3] , $5 , $6 ) == -1) goto $2;',
'CLEARTEMP($3);',
'}'), v2)
return True
if TxMatch(o, i, ('if (_$1_dict && (temp[$3] = PyDict_GetItem(_$1_dict, $2)) != 0) {',
'Py_INCREF(temp[$3]);',
'} else {',
'if ((temp[$3] = PyObject_GetAttr ( GETLOCAL($1) , $2 )) == 0) goto $5;',
'}',
'$4 = PyInt_AsSsize_t ( temp[$3] );',
'CLEARTEMP($3);'), v2):
TxRepl(o, i, ('if (_$1_dict && (temp[$3] = PyDict_GetItem(_$1_dict, $2)) != 0) {',
'$4 = PyInt_AsSsize_t ( temp[$3] );',
'temp[$3] = 0;',
'} else {',
'if ((temp[$3] = PyObject_GetAttr ( GETLOCAL($1) , $2 )) == 0) goto $5;',
'$4 = PyInt_AsSsize_t ( temp[$3] );',
'CLEARTEMP($3);',
'}'), v2)
return True
if TxMatch(o, i, ('if (_$1_dict && (temp[$3] = PyDict_GetItem(_$1_dict, $2)) != 0) {',
'Py_INCREF(temp[$3]);',
'} else {',
'if ((temp[$3] = PyObject_GetAttr ( GETLOCAL($1) , $2 )) == 0) goto $5;',
'}',
'if ((temp[$6] = PyList_GetItem ( temp[$3] , $7 )) == 0) goto $5;',
'Py_INCREF(temp[$6]);',
'CLEARTEMP($3);'), v2):
TxRepl(o, i, ('if (_$1_dict && (temp[$3] = PyDict_GetItem(_$1_dict, $2)) != 0) {',
'if ((temp[$6] = PyList_GetItem ( temp[$3] , $7 )) == 0) goto $5;',
'temp[$3] = 0;',
'} else {',
'if ((temp[$3] = PyObject_GetAttr ( GETLOCAL($1) , $2 )) == 0) goto $5;',
'if ((temp[$6] = PyList_GetItem ( temp[$3] , $7 )) == 0) goto $5;',
'CLEARTEMP($3);',
'}',
'Py_INCREF(temp[$6]);'), v2)
return True
if TxMatch(o, i, ('if (_$3_dict && (temp[$0] = PyDict_GetItem(_$3_dict, $4)) != 0) {',
'Py_INCREF(temp[$0]);',
'} else {',
'if ((temp[$0] = PyObject_GetAttr ( GETLOCAL($3) , $4 )) == 0) goto $5;',
'}',
'if (PyInt_CheckExact( temp[$0] ) && ($7 = PyInt_AS_LONG ( temp[$0] )) > INT_MIN ) {',
'CLEARTEMP($0);',
'$6 = $8 $9 ($7 - 1);',
'} else {',
'if ((temp[$1] = PyNumber_Subtract ( temp[$0] , $15 )) == 0) goto $5;',
'CLEARTEMP($0);',
'if ((temp[$2] = PyInt_FromSsize_t($8)) == 0) goto $5;',
'if (($6 = PyObject_RichCompareBool ( temp[$2] , temp[$1] , Py_$10 )) == -1) goto $5;',
'CLEARTEMP($1);',
'CLEARTEMP($2);',
'}'), v2):
TxRepl(o, i, ('if (_$3_dict && (temp[$0] = PyDict_GetItem(_$3_dict, $4)) != 0) {',
'if (PyInt_CheckExact( temp[$0] ) && ($7 = PyInt_AS_LONG ( temp[$0] )) > INT_MIN ) {',
'$6 = $8 $9 ($7 - 1);',
'} else {',
'Py_INCREF(temp[$0]);',
'if ((temp[$1] = PyNumber_Subtract ( temp[$0] , $15 )) == 0) goto $5;',
'CLEARTEMP($0);',
'if ((temp[$2] = PyInt_FromSsize_t($8)) == 0) goto $5;',
'if (($6 = PyObject_RichCompareBool ( temp[$2] , temp[$1] , Py_$10 )) == -1) goto $5;',
'CLEARTEMP($1);',
'CLEARTEMP($2);',
'}',
'} else {',
'if ((temp[$0] = PyObject_GetAttr ( GETLOCAL($3) , $4 )) == 0) goto $5;',
'if (PyInt_CheckExact( temp[$0] ) && ($7 = PyInt_AS_LONG ( temp[$0] )) > INT_MIN ) {',
'CLEARTEMP($0);',
'$6 = $8 $9 ($7 - 1);',
'} else {',
'if ((temp[$1] = PyNumber_Subtract ( temp[$0] , $15 )) == 0) goto $5;',
'CLEARTEMP($0);',
'if ((temp[$2] = PyInt_FromSsize_t($8)) == 0) goto $5;',
'if (($6 = PyObject_RichCompareBool ( temp[$2] , temp[$1] , Py_$10 )) == -1) goto $5;',
'CLEARTEMP($1);',
'CLEARTEMP($2);',
'}',
'}'), v2)
return True
if TxMatch(o, i, ('if (_$2_dict && (temp[$0] = PyDict_GetItem(_$2_dict, $3)) != 0) {',
'Py_INCREF(temp[$0]);',
'} else {',
'if ((temp[$0] = PyObject_GetAttr ( GETLOCAL($2) , $3 )) == 0) goto $4;',
'}',
'if (PyInt_CheckExact( temp[$0] ) && ($5 = PyInt_AS_LONG ( temp[$0] )) > INT_MIN ) {',
'CLEARTEMP($0);',
'$6 = $5 - 1;',
'} else {',
'if ((temp[$1] = PyNumber_Subtract ( temp[$0] , $7 )) == 0) goto $4;',
'CLEARTEMP($0);',
'$6 = PyInt_AsSsize_t ( temp[$1] );',
'CLEARTEMP($1);',
'}'), v2):
TxRepl(o, i, ('if (_$2_dict && (temp[$0] = PyDict_GetItem(_$2_dict, $3)) != 0) {',
'if (PyInt_CheckExact( temp[$0] ) && ($5 = PyInt_AS_LONG ( temp[$0] )) > INT_MIN ) {',
'$6 = $5 - 1;',
'} else {',
'Py_INCREF(temp[$0]);',
'if ((temp[$1] = PyNumber_Subtract ( temp[$0] , $7 )) == 0) goto $4;',
'CLEARTEMP($0);',
'$6 = PyInt_AsSsize_t ( temp[$1] );',
'CLEARTEMP($1);',
'}',
'} else {',
'if ((temp[$0] = PyObject_GetAttr ( GETLOCAL($2) , $3 )) == 0) goto $4;',
'if (PyInt_CheckExact( temp[$0] ) && ($5 = PyInt_AS_LONG ( temp[$0] )) > INT_MIN ) {',
'CLEARTEMP($0);',
'$6 = $5 - 1;',
'} else {',
'if ((temp[$1] = PyNumber_Subtract ( temp[$0] , $7 )) == 0) goto $4;',
'CLEARTEMP($0);',
'$6 = PyInt_AsSsize_t ( temp[$1] );',
'CLEARTEMP($1);',
'}',
'}'), v2)
return True
if TxMatch(o, i, ('if (_$3_dict && (temp[$0] = PyDict_GetItem(_$3_dict, $5)) != 0) {',
'if ((temp[$1] = PyList_GetItem ( temp[$0] , $4 )) == 0) goto $6;',
'temp[$0] = 0;',
'} else {',
'if ((temp[$0] = PyObject_GetAttr ( GETLOCAL($3) , $5 )) == 0) goto $6;',
'if ((temp[$1] = PyList_GetItem ( temp[$0] , $4 )) == 0) goto $6;',
'CLEARTEMP($0);',
'}',
'Py_INCREF(temp[$1]);',
'if (_$3_dict && (temp[$0] = PyDict_GetItem(_$3_dict, $5)) != 0) {',
'if ((temp[$2] = PyList_GetItem ( temp[$0] , $4 )) == 0) goto $6;',
'temp[$0] = 0;',
'} else {',
'if ((temp[$0] = PyObject_GetAttr ( GETLOCAL($3) , $5 )) == 0) goto $6;',
'if ((temp[$2] = PyList_GetItem ( temp[$0] , $4 )) == 0) goto $6;',
'CLEARTEMP($0);',
'}',
'Py_INCREF(temp[$2]);'), v2):
TxRepl(o, i, ('if (_$3_dict && (temp[$0] = PyDict_GetItem(_$3_dict, $5)) != 0) {',
'if ((temp[$1] = PyList_GetItem ( temp[$0] , $4 )) == 0) goto $6;',
'temp[$0] = 0;',
'} else {',
'if ((temp[$0] = PyObject_GetAttr ( GETLOCAL($3) , $5 )) == 0) goto $6;',
'if ((temp[$1] = PyList_GetItem ( temp[$0] , $4 )) == 0) goto $6;',
'CLEARTEMP($0);',
'}',
'Py_INCREF(temp[$1]);',
'temp[$2] = temp[$1];',
'Py_INCREF(temp[$2]);'), v2)
return True
if TxMatch(o, i, """
if (_$9_dict && (temp[$0] = PyDict_GetItem(_$9_dict, $8)) != 0) {
Py_INCREF(temp[$0]);
} else {
if ((temp[$0] = PyObject_GetAttr ( GETLOCAL($9) , $8 )) == 0) goto label_$10;
}
if ((int_$11 = c_Py_$12_Int ($15)) == -1) goto label_$10;
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (_$9_dict && (temp[$0] = PyDict_GetItem(_$9_dict, $8)) != 0) {
if ((int_$11 = c_Py_$12_Int ($15)) == -1) goto label_$10;
} else {
if ((temp[$0] = PyObject_GetAttr ( GETLOCAL($9) , $8 )) == 0) goto label_$10;
if ((int_$11 = c_Py_$12_Int ($15)) == -1) goto label_$10;
CLEARTEMP($0);
}
""", v2)
return True
if o[i].startswith('if ( int_') and o[i].endswith(') {'):
if TxMatch(o, i, ('if ( int_$2 ) {',
'temp[$0] = Py_True;',
'} else {',
'temp[$0] = Py_False;',
'}',
'Py_INCREF(temp[$0]);',
'if ((int_$2 = PyObject_IsTrue ( temp[$0] )) == -1) goto $3;',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, (), v2)
return True
if TxMatch(o, i, ('if ( int_$2 ) {',
'temp[$0] = Py_True;',
'} else {',
'temp[$0] = Py_False;',
'}',
'Py_INCREF(temp[$0]);',
'int_$2 = PyObject_IsTrue ( temp[$0] );',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, (), v2)
return True
if TxMatch(o, i, ('if ( int_$2 ) {',
'temp[$0] = Py_True;',
'} else {',
'temp[$0] = Py_False;',
'}',
'Py_INCREF(temp[$0]);',
'if ((int_$2 = PyObject_IsTrue ( temp[$0] )) == -1) goto $3;'), v2):
TxRepl(o, i, ('if ( int_$2 ) {',
'temp[$0] = Py_True;',
'} else {',
'temp[$0] = Py_False;',
'}',
'Py_INCREF(temp[$0]);'), v2)
return True
if TxMatch(o, i, """
if ( int_$3 ) {
temp[$0] = Py_True;
} else {
temp[$0] = Py_False;
}
Py_INCREF(temp[$0]);
if ( int_$3 ) {
CLEARTEMP($0);
if ((temp[$0] = PyDict_GetItem ( $4 )) == 0) goto label_$10;
Py_INCREF(temp[$0]);
}
""", v2):
TxRepl(o, i, """
if ( int_$3 ) {
if ((temp[$0] = PyDict_GetItem ( $4 )) == 0) goto label_$10;
Py_INCREF(temp[$0]);
} else {
Py_INCREF(Py_False);
temp[$0] = Py_False;
}
""", v2)
return True
if TxMatch(o, i, """
if ( int_$2 ) {
temp[$0] = Py_True;
} else {
temp[$0] = Py_False;
}
Py_INCREF(temp[$0]);
if ( int_$2 ) {
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if ( !(int_$2)) {
temp[$0] = Py_False;
Py_INCREF(temp[$0]);
} else {
""", v2)
return True
if i+1 < len(o) and o[i+1].startswith('if ((int_'):
if TxMatch(o, i, ('if ($11) {',
'if ((int_$3 = $14) == -1) goto $12;',
'temp[$0] = PyBool_FromLong(int_$3);',
'} else {',
'if ((temp[$2] = $15) == 0) goto $12;',
'if ((temp[$0] = $16) == 0) goto $12;',
'CLEARTEMP($2);',
'}',
'CLEARTEMP($19);',
'if ((int_$1 = PyObject_IsTrue ( temp[$0] )) == -1) goto $12;',
'CLEARTEMP($0);'), v2) and v2[19] != v2[0] and v2[19] != v2[2]:
TxRepl(o, i, ('if ($11) {',
'if ((int_$1 = $14) == -1) goto $12;',
'} else {',
'if ((temp[$2] = $15) == 0) goto $12;',
'if ((temp[$0] = $16) == 0) goto $12;',
'CLEARTEMP($2);',
'if ((int_$1 = PyObject_IsTrue ( temp[$0] )) == -1) goto $12;',
'CLEARTEMP($0);',
'}',
'CLEARTEMP($19);'), v2)
return True
if TxMatch(o, i, ('if ($11) {',
'if ((int_$3 = $14) == -1) goto $12;',
'temp[$0] = PyBool_FromLong(int_$3);',
'} else {',
'if ((temp[$2] = $15) == 0) goto $12;',
'if ((temp[$0] = $16) == 0) goto $12;',
'CLEARTEMP($2);',
'}',
'if ((int_$1 = PyObject_IsTrue ( temp[$0] )) == -1) goto $12;',
'CLEARTEMP($0);'), v2):
TxRepl(o, i, ('if ($11) {',
'if ((int_$1 = $14) == -1) goto $12;',
'} else {',
'if ((temp[$2] = $15) == 0) goto $12;',
'if ((temp[$0] = $16) == 0) goto $12;',
'CLEARTEMP($2);',
'if ((int_$1 = PyObject_IsTrue ( temp[$0] )) == -1) goto $12;',
'CLEARTEMP($0);',
'}'), v2)
return True
if 'PyString_GET_SIZE' in o[i]:
if TxMatch(o, i, """
if ($10) {
long_$3 = (long)$16;
} else if ($11) {
long_$3 = (long)$17;
} else if ($12) {
long_$3 = (long)$18;
} else {
>0
long_$3 = PyInt_AsLong ( temp[$1] );
CLEARTEMP($1);
}
$15 = ( long_$3 );
""", v2):
TxRepl(o, i, """
if ($10) {
$15 = (long)$16;
} else if ($11) {
$15 = (long)$17;
} else if ($12) {
$15 = (long)$18;
} else {
>0
$15 = PyInt_AsLong ( temp[$1] );
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, ('if (PyString_GET_SIZE( temp[$2] ) == 1) {',
'$1 = (long)((unsigned char)*PyString_AS_STRING(temp[$2]));',
'temp[$0] = PyInt_FromLong ( $1 );',
'} else {',
'if ((temp[$4] = PyTuple_New ( 1 )) == 0) goto $3;',
'PyTuple_SET_ITEM ( temp[$4] , 0 , temp[$2] );',
'temp[$2] = 0;',
'if ((temp[$0] = PyCFunction_Call ( loaded_builtin[$5] , temp[$4] , NULL )) == 0) goto $3;',
'CLEARTEMP($4);',
'}',
'CLEARTEMP($2);',
'$6 = PyInt_AS_LONG ( temp[$0] );',
'$9 = $6 * $10;',
'if ($9 / $10 == $6) {',
'temp[$7] = PyInt_FromLong ($9);',
'} else {',
'temp[$7] = PyInt_Type.tp_as_number->nb_multiply(temp[$0], consts[$8]);',
'}',
'CLEARTEMP($0);'), v2) and abs(int(v2[10])) < 70000:
TxRepl(o, i, ('if (PyString_GET_SIZE( temp[$2] ) == 1) {',
'$9 = ((long)((unsigned char)*PyString_AS_STRING(temp[$2]))) * $10;',
'CLEARTEMP($2);',
'temp[$7] = PyInt_FromLong ( $9 );',
'} else {',
'if ((temp[$4] = PyTuple_New ( 1 )) == 0) goto $3;',
'PyTuple_SET_ITEM ( temp[$4] , 0 , temp[$2] );',
'temp[$2] = 0;',
'if ((temp[$0] = PyCFunction_Call ( loaded_builtin[$5] , temp[$4] , NULL )) == 0) goto $3;',
'CLEARTEMP($4);',
'$6 = PyInt_AS_LONG ( temp[$0] );',
'$9 = $6 * $10;',
'if ($9 / $10 == $6) {',
'temp[$7] = PyInt_FromLong ($9);',
'} else {',
'temp[$7] = PyInt_Type.tp_as_number->nb_multiply(temp[$0], consts[$8]);',
'}',
'CLEARTEMP($0);',
'}'), v2)
return True
if TxMatch(o, i, """
if (PyString_GET_SIZE( $9 ) == 1) {
long_$3 = (long)((unsigned char)*PyString_AS_STRING ( $9 ));
temp[$0] = PyInt_FromLong ( long_$3 );
} else {
if ((temp[$1] = PyTuple_Pack ( 1 , $9 )) == 0) goto label_$10;
if ((temp[$0] = PyCFunction_Call ( loaded_builtin[$11] , temp[$1] , NULL )) == 0) goto label_$10;
CLEARTEMP($1);
}
$15 = PyInt_AsLong(temp[$0]);
CLEARTEMP($0);""", v2):
TxRepl(o, i, """
if (PyString_GET_SIZE( $9 ) == 1) {
$15 = (long)((unsigned char)*PyString_AS_STRING ( $9 ));
} else {
if ((temp[$1] = PyTuple_Pack ( 1 , $9 )) == 0) goto label_$10;
if ((temp[$0] = PyCFunction_Call ( loaded_builtin[$11] , temp[$1] , NULL )) == 0) goto label_$10;
CLEARTEMP($1);
$15 = PyInt_AsLong(temp[$0]);
CLEARTEMP($0);
}""", v2)
return True
if i+1 < len(o) and 'PyInt_FromLong' in o[i+1]:
if TxMatch(o, i, """
if ($9) {
temp[$1] = PyInt_FromLong ($8);
} else {
temp[$0] = $7;
if ((temp[$1] = PyNumber_$6 ( temp[$0] , $5 )) == 0) goto label_$12;
CLEARTEMP($0);
}
if ((temp[$10] = PyObject_GetItem ( $14 , temp[$1] )) == 0) goto label_$12;
CLEARTEMP($1);""", v2):
v2[9] = v2[9].strip()
v2[8] = v2[8].strip()
TxRepl(o, i, """
if ( $9 ) {
temp[$1] = PyInt_FromLong ( $8 );
if ((temp[$10] = PyObject_GetItem ( $14 , temp[$1] )) == 0) goto label_$12;
CLEARTEMP($1);
} else {
temp[$0] = $7;
if ((temp[$1] = PyNumber_$6 ( temp[$0] , $5 )) == 0) goto label_$12;
CLEARTEMP($0);
if ((temp[$10] = PyObject_GetItem ( $14 , temp[$1] )) == 0) goto label_$12;
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, ('if (Loc_long_$2 < INT_MAX) {',
'temp[$1] = PyInt_FromLong ( Loc_long_$2 + 1 );',
'} else {',
'temp[$0] = PyInt_FromLong (Loc_long_$2);',
'if ((temp[$1] = PyNumber_Add ( temp[$0] , $5 )) == 0) goto $3;',
'CLEARTEMP($0);',
'}',
'if ((temp[$0] = PyObject_GetItem ( $4 , temp[$1] )) == 0) goto $3;',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if ((temp[$0] = __c_BINARY_SUBSCR_Int ( $4 , Loc_long_$2 + 1 )) == 0) goto $3;',), v2, ('__c_BINARY_SUBSCR_Int',))
return True
if TxMatch(o, i, ('if ($2 < INT_MAX) {',
'temp[$1] = PyInt_FromLong ( $2 + 1 );',
'} else {',
'temp[$0] = PyInt_FromLong ($2);',
'if ((temp[$1] = PyNumber_Add ( temp[$0] , $4 )) == 0) goto $3;',
'CLEARTEMP($0);',
'}',
'$2 = PyInt_AsLong(temp[$1]);',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('$2 += 1;',), v2)
return True
if TxMatch(o, i, ('if ($3) {',
'temp[$1] = PyInt_FromLong ($4);',
'} else {',
'temp[$0] = PyInt_FromLong ( $5 );',
'temp[$1] = $6;',
'CLEARTEMP($0);',
'}',
'if (PyInt_CheckExact( temp[$1] ) && ($7 = PyInt_AS_LONG ( temp[$1] )) > (INT_MIN+$8) ) {',
'temp[$0] = PyInt_FromLong ( $7 - $9 );',
'} else {',
'if ((temp[$0] = PyNumber_Subtract ( temp[$1] , $10 )) == 0) goto $2;',
'}',
'CLEARTEMP($1);'), v2):
TxRepl(o, i, ('if ($3 && (($7 = $4) > (INT_MIN+$8))) {',
'temp[$0] = PyInt_FromLong ( $7 - $9 );',
'} else {',
'temp[$0] = PyInt_FromLong ( $5 );',
'temp[$1] = $6;',
'CLEARTEMP($0);',
'if ((temp[$0] = PyNumber_Subtract ( temp[$1] , $10 )) == 0) goto $2;',
'CLEARTEMP($1);',
'}'), v2)
return True
if TxMatch(o, i, """
if ($5) {
temp[$1] = PyInt_FromLong ($7);
} else if ($6) {
temp[$1] = PyFloat_FromDouble($8);
} else {
if ((temp[$1] = PyNumber_$9) == 0) goto $3;
}
if ((temp[$2] = PyNumber_Float ( temp[$1] )) == 0) goto $3;
CLEARTEMP($1);
$4 = PyFloat_AsDouble ( temp[$2] );
CLEARTEMP($2);
""", v2):
TxRepl(o, i, """
if ($5) {
$4 = (double)($7);
} else if ($6) {
$4 = $8;
} else {
if ((temp[$1] = PyNumber_$9) == 0) goto $3;
if ((temp[$2] = PyNumber_Float ( temp[$1] )) == 0) goto $3;
CLEARTEMP($1);
$4 = PyFloat_AsDouble ( temp[$2] );
CLEARTEMP($2);
}
""", v2)
return True
if TxMatch(o, i, """
if ($5) {
temp[$1] = PyInt_FromLong ($6);
} else {
temp[$0] = $7;
temp[$1] = $8;
CLEARTEMP($0);
}
if ((temp[$3] = PyObject_GetItem ( $9 , temp[$1] )) == 0) goto label_$10;
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if ($5) {
temp[$1] = PyInt_FromLong ($6);
if ((temp[$3] = PyObject_GetItem ( $9 , temp[$1] )) == 0) goto label_$10;
CLEARTEMP($1);
} else {
temp[$0] = $7;
temp[$1] = $8;
CLEARTEMP($0);
if ((temp[$3] = PyObject_GetItem ( $9 , temp[$1] )) == 0) goto label_$10;
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if ($5) {
temp[$1] = PyInt_FromLong ( $6 );
} else {
if ((temp[$1] = PyNumber_$7 ($8)) == 0) goto $9;
}
if ((temp[$2] = $10) == 0) goto $9;
if ((Py_ssize_t_$11 = $12 ( temp[$2] )) == -1) goto $9;
CLEARTEMP($2);
if (PyInt_CheckExact( temp[$1] )) {
int_$16 = PyInt_AS_LONG ( temp[$1] ) $14 Py_ssize_t_$11;
} else {
if ((temp[$3] = PyInt_FromSsize_t(Py_ssize_t_$11)) == 0) goto $9;
if ((int_$16 = PyObject_RichCompareBool ( temp[$1] , temp[$3] , $13 )) == -1) goto $9;
CLEARTEMP($3);
}
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if ($5) {
if ((temp[$2] = $10) == 0) goto $9;
if ((Py_ssize_t_$11 = $12 ( temp[$2] )) == -1) goto $9;
CLEARTEMP($2);
int_$16 = ($6) $14 Py_ssize_t_$11;
} else {
if ((temp[$1] = PyNumber_$7 ($8)) == 0) goto $9;
if ((temp[$2] = $10) == 0) goto $9;
if ((Py_ssize_t_$11 = $12 ( temp[$2] )) == -1) goto $9;
CLEARTEMP($2);
if ((temp[$3] = PyInt_FromSsize_t(Py_ssize_t_$11)) == 0) goto $9;
if ((int_$16 = PyObject_RichCompareBool ( temp[$1] , temp[$3] , $13 )) == -1) goto $9;
CLEARTEMP($3);
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if ($3) {
temp[$0] = PyInt_FromLong ($4);
} else {
if ((temp[$0] = PyNumber_$5) == 0) goto label_$10;
}
if ((int_$1 = PyObject_IsTrue ( temp[$0] )) == -1) goto label_$10;
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if ($3) {
int_$1 = ($4) != 0;
} else {
if ((temp[$0] = PyNumber_$5) == 0) goto label_$10;
if ((int_$1 = PyObject_IsTrue ( temp[$0] )) == -1) goto label_$10;
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
if ($3) {
temp[$1] = PyInt_FromLong ($4);
} else {
temp[$0] = $5;
temp[$1] = $6;
CLEARTEMP($0);
}
if (PyInt_CheckExact( temp[$1] )) {
long_$7 = PyInt_AS_LONG ( temp[$1] );
long_$8;
if ($9) goto $10 ;
temp[$2] = PyInt_FromLong ( $19 );
} else { $10 :;
if ((temp[$2] = PyNumber_$11) == 0) goto $12;
}
CLEARTEMP($1);
""", v2):
TxRepl(o, i, """
if ($3) {
long_$7 = $4;
long_$8;
if ($9) goto $10 ;
temp[$2] = PyInt_FromLong ( $19 );
} else { $10 :;
temp[$0] = $5;
temp[$1] = $6;
CLEARTEMP($0);
if ((temp[$2] = PyNumber_$11) == 0) goto $12;
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if ($2) {
temp[$1] = PyInt_FromLong ( $4 );
} else if ($3) {
temp[$1] = PyFloat_FromDouble($5);
} else {
if ((temp[$1] = PyNumber_$6) == 0) goto $7;
}
CLEARTEMP($0);
if (PyInt_CheckExact( temp[$1] )) {
temp[$10] = PyInt_FromLong ( PyInt_AS_LONG ( temp[$1] ) $8 );
} else {
if ((temp[$10] = PyNumber_$9 ( temp[$1] , $11 )) == 0) goto $7;
}
CLEARTEMP($1);
""", v2) and not ('temp[' + v2[0] + ']') in v2[4] and not ('temp[' + v2[0] + ']') in v2[8]:
TxRepl(o, i, """
if ($2) {
CLEARTEMP($0);
temp[$10] = PyInt_FromLong ( ($4) $8 );
} else {
if ((temp[$1] = PyNumber_$6) == 0) goto $7;
CLEARTEMP($0);
if ((temp[$10] = PyNumber_$9 ( temp[$1] , $11 )) == 0) goto $7;
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if ($3) {
temp[$1] = PyInt_FromLong ($4);
} else {
if ((temp[$1] = PyNumber_$5) == 0) goto $6;
}
CLEARTEMP($0);
if ((int_$7 = c_Py_$11_Int ( temp[$1] , $8 , $9 )) == -1) goto $6;
CLEARTEMP($1);
""", v2):
pycmp = 'Py_' + v2[11]
if pycmp in c_2_op_op:
v2[12] = c_2_op_op[pycmp]
if v2[12] != None:
TxRepl(o, i, """
if ($3) {
int_$7 = ($4) $12 $8;
CLEARTEMP($0);
} else {
if ((temp[$1] = PyNumber_$5) == 0) goto $6;
CLEARTEMP($0);
if ((int_$7 = c_Py_$11_Int ( temp[$1] , $8 , $9 )) == -1) goto $6;
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if ($5) {
temp[$0] = PyInt_FromLong ( $6 );
} else {
if ((temp[$0] = PyNumber_$8) == 0) goto $7;
}
if ((Py_ssize_t_$9 = $10 )) == -1) goto $7;
if (PyInt_CheckExact( temp[$0] )) {
int_$14 = PyInt_AS_LONG ( temp[$0] ) $12 Py_ssize_t_$9;
} else {
if ((temp[$1] = PyInt_FromSsize_t(Py_ssize_t_$9)) == 0) goto $7;
if ((int_$14 = PyObject_RichCompareBool ( temp[$0] , temp[$1] , $11 )) == -1) goto $7;
CLEARTEMP($1);
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if ($5) {
if ((Py_ssize_t_$9 = $10 )) == -1) goto $7;
int_$14 = ($6) $12 Py_ssize_t_$9;
} else {
if ((temp[$0] = PyNumber_$8) == 0) goto $7;
if ((Py_ssize_t_$9 = $10 )) == -1) goto $7;
if ((temp[$1] = PyInt_FromSsize_t(Py_ssize_t_$9)) == 0) goto $7;
if ((int_$14 = PyObject_RichCompareBool ( temp[$0] , temp[$1] , $11 )) == -1) goto $7;
CLEARTEMP($1);
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
if (long_$4 / $10 == long_$3) {
temp[$2] = PyInt_FromLong (long_$4);
} else {
temp[$0] = PyInt_FromLong ( long_$3 );
temp[$2] = PyInt_Type.tp_as_number->nb_multiply(temp[$0], $10);
CLEARTEMP($0);
}
long_$14 = PyInt_AS_LONG ( temp[$1] );
long_$6 = PyInt_AS_LONG ( temp[$2] );
long_$13 = long_$14 + long_$6;
if (( long_$13 ^ long_$14 ) < 0 && ( long_$13 ^ long_$6 ) < 0) goto $12 ;
temp[$0] = PyInt_FromLong ( long_$13 );
if (1) {
} else { $12 :;
if ((temp[$0] = PyNumber_Add ( temp[$1] , temp[$2] )) == 0) goto $11;
}
CLEARTEMP($1);
CLEARTEMP($2);
""", v2):
TxRepl(o, i, """
long_$6 = long_$4;
long_$14 = PyInt_AS_LONG ( temp[$1] );
long_$13 = long_$14 + long_$6;
if (( long_$13 ^ long_$14 ) < 0 && ( long_$13 ^ long_$6 ) < 0) goto $12 ;
temp[$0] = PyInt_FromLong ( long_$13 );
if (1) {
} else { $12 :;
if ((temp[$0] = PyNumber_Add ( temp[$1] , temp[$2] )) == 0) goto $11;
}
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if ($11) {
temp[$2] = PyInt_FromLong ( $12 );
} else {
temp[$0] = PyInt_FromLong ( $13 );
temp[$2] = PyInt_Type.tp_as_number->nb_multiply($14);
CLEARTEMP($0);
}
long_$4 = PyInt_AS_LONG ( temp[$2] );
long_$3 = $15;
if ($16) goto $17 ;
temp[$18] = PyInt_FromLong ( long_$3 );
if (1) {
} else { $17 :;
if ((temp[$18] = PyNumber_$19) == 0) goto $10;
}
CLEARTEMP($2);
""", v2):
TxRepl(o, i, """
long_$4 = $12;
long_$3 = $15;
if ($16) goto $17 ;
temp[$18] = PyInt_FromLong ( long_$3 );
if (1) {
} else { $17 :;
if ((temp[$18] = PyNumber_$19) == 0) goto $10;
}
""", v2)
return True
if TxMatch(o, i, """
if (long_$6 / $7 == $8) {
temp[$0] = PyInt_FromLong ( long_$6 );
} else {
temp[$0] = PyInt_Type.tp_as_number->nb_multiply($9, $10);
}
long_$6 = PyInt_AS_LONG ( temp[$0] );
long_$5 = long_$6 - $4;
if (( long_$5 ^ long_$6 ) < 0 && ( long_$5 ^~ $4 ) < 0) goto label_$17 ;
temp[$1] = PyInt_FromLong ( long_$5 );
if (1) {
} else { label_$17 :;
if ((temp[1] = PyNumber_Subtract ( temp[$0] , $11 )) == 0) goto label_$12;
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
long_$5 = long_$6 - $4;
if (( long_$5 ^ long_$6 ) < 0 && ( long_$5 ^~ $4 ) < 0) goto label_$17 ;
temp[$1] = PyInt_FromLong ( long_$5 );
if (0) { label_$17 :;
temp[$0] = PyInt_FromLong ( long_$6 );
if ((temp[1] = PyNumber_Subtract ( temp[$0] , $11 )) == 0) goto label_$12;
CLEARTEMP($0);
}
""", v2)
return True
if 'int_' in o[i] and '=' not in o[i]:
if '!' in o[i]:
if TxMatch(o, i, ('if ( !(int_$1) ) {',), v2) and v2[1].isdigit():
TxRepl(o, i, ('if ( !int_$1 ) {',), v2)
return True
if TxMatch(o, i, ('if ( (!(int_$1)) ) {',), v2) and v2[1].isdigit():
TxRepl(o, i, ('if ( !int_$1 ) {',), v2)
return True
if TxMatch(o, i, ('if (!( int_$1 )) {',), v2) and v2[1].isdigit():
TxRepl(o, i, ('if ( !int_$1 ) {',), v2)
return True
else:
if TxMatch(o, i, ('if ( ((int_$1)) ) {',), v2) and v2[1].isdigit():
TxRepl(o, i, ('if ( int_$1 ) {',), v2)
return True
if TxMatch(o, i, ('if ( (int_$1) ) {',), v2) and v2[1].isdigit():
TxRepl(o, i, ('if ( int_$1 ) {',), v2)
return True
if TxMatch(o, i, ('if (( int_$1 )) {',), v2) and v2[1].isdigit():
TxRepl(o, i, ('if ( int_$1 ) {',), v2)
return True
if i+1 < len(o) and 'Loc_int_' in o[i+1] and TxMatch(o, i, """
if ( int_$1 ) {
int_$1 = Loc_int_$3;
int_$1 = !(int_$1);
}
""", v2) and ' ' not in v2[3]:
TxRepl(o, i, """
if ( int_$1 ) {
int_$1 = !Loc_int_$3;
}""", v2)
return True
if i+1 < len(o) and 'PyFloat_FromDouble' in o[i+1]:
if TxMatch(o, i, """
if ($11)) {
temp[$2] = PyFloat_FromDouble($12);
} else if (PyInt_CheckExact( temp[$1] ) && PyInt_CheckExact( temp[$0] )) {
$4 = PyInt_AS_LONG ( temp[$1] );
$5 = PyInt_AS_LONG ( temp[$0] );
if ($4 && $5 && ($4 * $5) / $5 == $4) {
temp[$2] = PyInt_FromLong ($4 * $5);
} else {
temp[$2] = PyInt_Type.tp_as_number->nb_multiply(temp[$1], temp[$0]);
}
} else {
""", v2):
TxRepl(o, i, """
if ($11)) {
temp[$2] = PyFloat_FromDouble($12);
} else if (PyInt_CheckExact( temp[$1] ) && PyInt_CheckExact( temp[$0] ) && ($4 = PyInt_AS_LONG ( temp[$1] )) && ($5 = PyInt_AS_LONG ( temp[$0] )) && (($4 * $5) / $5 == $4)) {
temp[$2] = PyInt_FromLong ($4 * $5);
} else {
""", v2)
return True
if TxMatch(o, i, """
if ($4) {
temp[$2] = PyFloat_FromDouble($5);
} else if ($6) {
temp[$2] = PyInt_FromLong ($7);
} else {
if ((temp[$2] = PyNumber_Multiply ($8)) == 0) goto $9;
}
CLEARTEMP($1);
CLEARTEMP($0);
if (PyInt_CheckExact( $10 ) && PyInt_CheckExact( temp[$2] )) {
long_$12 = PyInt_AS_LONG ( $10 );
long_$13 = PyInt_AS_LONG ( temp[$2] );
long_$14 = long_$12 + long_$13;
if (( long_$14 ^ long_$12 ) < 0 && ( long_$14 ^ long_$13 ) < 0) goto $11 ;
temp[$15] = PyInt_FromLong ( long_$14 );
} else if (PyFloat_CheckExact( $10 ) && PyFloat_CheckExact( temp[$2] )) {
temp[$15] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($10) + PyFloat_AS_DOUBLE(temp[$2]));
} else { $11 :;
if ((temp[$15] = PyNumber_Add ( $10 , temp[$2] )) == 0) goto $9;
}
CLEARTEMP($2);
""", v2):
TxRepl(o, i, """
if (PyFloat_CheckExact( $10 ) && ($4)) {
temp[$15] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($10) + ($5));
} else if (PyInt_CheckExact( $10 ) && ($4)) {
temp[$15] = PyFloat_FromDouble(PyInt_AS_LONG($10) + ($5));
} else if (PyInt_CheckExact( $10 ) && $6) {
long_$13 = $7;
long_$12 = PyInt_AS_LONG ( $10 );
long_$14 = long_$12 + long_$13;
if (( long_$14 ^ long_$12 ) < 0 && ( long_$14 ^ long_$13 ) < 0) goto $11 ;
temp[$15] = PyInt_FromLong ( long_$14 );
} else { $11 :;
if ((temp[$2] = PyNumber_Multiply ($8)) == 0) goto $9;
CLEARTEMP($1);
CLEARTEMP($0);
if ((temp[$15] = PyNumber_Add ( $10 , temp[$2] )) == 0) goto $9;
CLEARTEMP($2);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyFloat_CheckExact( temp[$0] ) && PyFloat_CheckExact( temp[$0] )) {
temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$0]) * PyFloat_AS_DOUBLE(temp[$0]));
} else if (PyInt_CheckExact( temp[$0] ) && PyInt_CheckExact( temp[$0] ) && (long_$4 = PyInt_AS_LONG ( temp[$0] )) && (long_$5 = PyInt_AS_LONG ( temp[$0] )) && ((long_$4 * long_$5) / long_$5 == long_$4)) {
temp[$1] = PyInt_FromLong (long_$4 * long_$5);
} else {
if ((temp[$1] = PyNumber_Multiply ( temp[$0] , temp[$0] )) == 0) goto $9;
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if (PyFloat_CheckExact( temp[$0] )) {
temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$0]) * PyFloat_AS_DOUBLE(temp[$0]));
} else if (PyInt_CheckExact( temp[$0] ) && (long_$4 = PyInt_AS_LONG ( temp[$0] )) && ((long_$4 * long_$4) / long_$4 == long_$4)) {
temp[$1] = PyInt_FromLong (long_$4 * long_$4);
} else {
if ((temp[$1] = PyNumber_Multiply ( temp[$0] , temp[$0] )) == 0) goto $9;
}
CLEARTEMP($0);
""", v2)
return True
if TxMatch(o, i, """
if ($11) {
temp[$1] = PyFloat_FromDouble($12);
} else if ($13) {
temp[$1] = PyInt_FromLong ($14);
} else {
if ((temp[$1] = PyNumber_$15) == 0) goto $16;
}
CLEARTEMP($0);
if (PyFloat_CheckExact( temp[$1] )) {
temp[$3] = PyFloat_FromDouble($17PyFloat_AS_DOUBLE(temp[$1]));
} else {
if ((temp[$3] = PyNumber_$18 temp[$1] )) == 0) goto $16;
}
CLEARTEMP($1);
""", v2) and v2[0] != v2[3]:
TxRepl(o, i, """
if ($11) {
temp[$3] = PyFloat_FromDouble($17($12));
CLEARTEMP($0);
} else if ($13) {
temp[$3] = PyFloat_FromDouble($17(double)($14));
CLEARTEMP($0);
} else {
if ((temp[$1] = PyNumber_$15) == 0) goto $16;
CLEARTEMP($0);
if ((temp[$3] = PyNumber_$18 temp[$1] )) == 0) goto $16;
CLEARTEMP($1);
}
""", v2)
return True
if TxMatch(o, i, """
if ($11) {
temp[$4] = PyFloat_FromDouble($5);
} else if ($6) {
temp[$4] = PyInt_FromLong ($7);
} else {
if ((temp[$4] = PyNumber_$10) == 0) goto $8;
}
CLEARTEMP($1);
CLEARTEMP($3);
if (PyInt_CheckExact( temp[$4] )) {
long_$12 = PyInt_AS_LONG ( temp[$4] );
long_$13;
if ($14) goto $9 ;
temp[$1] = PyInt_FromLong ( $15 );
} else if (PyFloat_CheckExact( temp[$4] )) {
temp[$1] = PyFloat_FromDouble($16);
} else { $9 :;
if ((temp[$1] = PyNumber_$17) == 0) goto $8;
}
CLEARTEMP($4);
""", v2):
TxRepl(o, i, """
if ($6) {
long_$12 = ($7);
CLEARTEMP($1);
CLEARTEMP($3);
long_$13;
if ($14) goto $9 ;
temp[$1] = PyInt_FromLong ( $15 );
} else { $9 :;
if ((temp[$4] = PyNumber_$10) == 0) goto $8;
CLEARTEMP($1);
CLEARTEMP($3);
if ((temp[$1] = PyNumber_$17) == 0) goto $8;
CLEARTEMP($4);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyFloat_CheckExact( temp[$1] ) && PyFloat_CheckExact( temp[$3] )) {
temp[$4] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$1]) * PyFloat_AS_DOUBLE(temp[$3]));
} else if (PyInt_CheckExact( temp[$1] ) && PyInt_CheckExact( temp[$3] )) {
long_$10 = PyInt_AS_LONG ( temp[$1] );
long_$11 = PyInt_AS_LONG ( temp[$3] );
if (long_$10 && long_$11 && (long_$10 * long_$11) / long_$11 == long_$10) {
temp[$4] = PyInt_FromLong ( long_$10 * long_$11 );
} else {
temp[$4] = PyInt_Type.tp_as_number->nb_multiply(temp[$1], temp[$3]);
}
} else {
if ((temp[$4] = PyNumber_Multiply ( temp[$1] , temp[$3] )) == 0) goto $5;
}
CLEARTEMP($1);
CLEARTEMP($3);
if (PyInt_CheckExact( temp[$4] )) {
long_$12 = PyInt_AS_LONG ( temp[$4] );
long_$13 = $14;
if ($15) goto $7 ;
temp[$6] = PyInt_FromLong ( long_$13 );
} else if (PyFloat_CheckExact( temp[$4] )) {
temp[$6] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$4]) $9);
} else { $7 :;
if ((temp[$6] = PyNumber_$8) == 0) goto $5;
}
CLEARTEMP($4);
""", v2):
TxRepl(o, i, """
if (PyFloat_CheckExact( temp[$1] ) && PyFloat_CheckExact( temp[$3] )) {
temp[$6] = PyFloat_FromDouble((PyFloat_AS_DOUBLE(temp[$1]) * PyFloat_AS_DOUBLE(temp[$3])) $9);
} else if (PyInt_CheckExact( temp[$1] ) && PyInt_CheckExact( temp[$3] )) {
long_$10 = PyInt_AS_LONG ( temp[$1] );
long_$11 = PyInt_AS_LONG ( temp[$3] );
if (!(long_$10 && long_$11 && (long_$10 * long_$11) / long_$11 == long_$10)) goto $7 ;
long_$12 = long_$10 * long_$11;
long_$13 = $14;
if ($15) goto $7 ;
temp[$6] = PyInt_FromLong ( long_$13 );
} else { $7 :;
if ((temp[$4] = PyNumber_Multiply ( temp[$1] , temp[$3] )) == 0) goto $5;
CLEARTEMP($1);
CLEARTEMP($3);
if ((temp[$6] = PyNumber_$8) == 0) goto $5;
CLEARTEMP($4);
}
""", v2)
return True
if TxMatch(o, i, """
if (PyFloat_CheckExact( temp[$1] ) && PyFloat_CheckExact( temp[$0] )) {
temp[$2] = PyFloat_FromDouble(PyFloat_AS_DOUBLE(temp[$1]) * PyFloat_AS_DOUBLE(temp[$0]));
} else if (PyInt_CheckExact( temp[$1] ) && PyInt_CheckExact( temp[$0] )) {
long_$4 = PyInt_AS_LONG ( temp[$1] );
long_$5 = PyInt_AS_LONG ( temp[$0] );
if (long_$4 && long_$5 && (long_$4 * long_$5) / long_$5 == long_$4) {
temp[$2] = PyInt_FromLong ( long_$4 * long_$5 );
} else {
temp[$2] = PyInt_Type.tp_as_number->nb_multiply(temp[$1], temp[$0]);
}
} else {
if ((temp[$2] = PyNumber_Multiply ( temp[$1] , temp[$0] )) == 0) goto label_$9;
}
CLEARTEMP($1);
CLEARTEMP($0);
if (PyInt_CheckExact( $11 ) && PyInt_CheckExact( temp[$2] )) {
long_$6 = PyInt_AS_LONG ( $11 );
long_$7 = PyInt_AS_LONG ( temp[$2] );
long_$8 = long_$6 + long_$7;
if ($19) goto label_$10 ;
temp[$3] = PyInt_FromLong ( long_$8 );
} else if (PyFloat_CheckExact( $11 ) && PyFloat_CheckExact( temp[$2] )) {
temp[$3] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($11) + PyFloat_AS_DOUBLE(temp[$2]));
} else { label_$10 :;
if ((temp[$3] = PyNumber_Add ( $11 , temp[$2] )) == 0) goto label_$9;
}
CLEARTEMP($2);
SETLOCAL ( $15 , temp[$3] );
temp[0] = 0;
""", v2):
TxRepl(o, i, """
if (PyFloat_CheckExact( temp[$1] ) && PyFloat_CheckExact( temp[$0] ) && PyFloat_CheckExact( $11 )) {
SETLOCAL ( $15 , PyFloat_FromDouble(PyFloat_AS_DOUBLE($11) + (PyFloat_AS_DOUBLE(temp[$1]) * PyFloat_AS_DOUBLE(temp[$0]))) );
CLEARTEMP($1);
CLEARTEMP($0);
} else if (PyInt_CheckExact( temp[$1] ) && PyInt_CheckExact( temp[$0] ) && PyInt_CheckExact( $11 )) {
long_$4 = PyInt_AS_LONG ( temp[$1] );
long_$5 = PyInt_AS_LONG ( temp[$0] );
if (long_$4 && long_$5 && (long_$4 * long_$5) / long_$5 != long_$4) goto label_$10 ;
long_$7 = long_$4 * long_$5;
long_$6 = PyInt_AS_LONG ( $11 );
long_$8 = long_$6 + long_$7;
if ($19) goto label_$10 ;
CLEARTEMP($1);
CLEARTEMP($0);
SETLOCAL ( $15 , PyInt_FromLong ( long_$8 ) );
} else { label_$10 :;
if ((temp[$2] = PyNumber_Multiply ( temp[$1] , temp[$0] )) == 0) goto label_$9;
CLEARTEMP($1);
CLEARTEMP($0);
if ((temp[$3] = PyNumber_Add ( $11 , temp[$2] )) == 0) goto label_$9;
CLEARTEMP($2);
SETLOCAL ( $15 , temp[$3] );
temp[$3] = 0;
}
""", v2)
return True
if i+1 < len(o) and o[i+1].startswith('long_'):
if TxMatch(o, i, """
if ($3) {
long_$4;
long_$5;
long_$17;
if ($6) goto label_$7 ;
temp[$0] = PyInt_FromLong ( $9 );
} else { label_$7 :;
if ((temp[$0] = PyNumber_$10) == 0) goto $8;
}
if (PyInt_CheckExact( temp[$0] )) {
int_$11 = Py_ssize_t_$12 $15 PyInt_AS_LONG ( temp[$0] );
} else {
if ((temp[$2] = PyInt_FromSsize_t(Py_ssize_t_$12)) == 0) goto $8;
if ((int_$11 = PyObject_RichCompareBool ( temp[$2] , temp[$0] , $14 )) == -1) goto $8;
CLEARTEMP($2);
}
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
if ($3) {
long_$4;
long_$5;
long_$17;
if ($6) goto label_$7 ;
int_$11 = Py_ssize_t_$12 $15 ($9);
} else { label_$7 :;
if ((temp[$0] = PyNumber_$10) == 0) goto $8;
if ((temp[$2] = PyInt_FromSsize_t(Py_ssize_t_$12)) == 0) goto $8;
if ((int_$11 = PyObject_RichCompareBool ( temp[$2] , temp[$0] , $14 )) == -1) goto $8;
CLEARTEMP($2);
CLEARTEMP($0);
}
""", v2)
return True
if TxMatch(o, i, """
if ($1) {
long_$2;
long_$3;
temp[$4] = PyInt_FromLong ($5);
} else {
if ((temp[$6] = PyNumber_$7) == 0) goto $9;
if ((temp[$4] = PyNumber_$8) == 0) goto $9;
CLEARTEMP($6);
}
long_$10 = PyInt_AsLong ( temp[$4] );
CLEARTEMP($4);
""", v2):
TxRepl(o, i, """
if ($1) {
long_$2;
long_$3;
long_$10 = ($5);
} else {
if ((temp[$6] = PyNumber_$7) == 0) goto $9;
if ((temp[$4] = PyNumber_$8) == 0) goto $9;
CLEARTEMP($6);
long_$10 = PyInt_AsLong ( temp[$4] );
CLEARTEMP($4);
}
""", v2)
return True
if 'PyDict_GetItem' in o[i]:
if TxMatch(o, i, """
if ((temp[$0] = PyDict_GetItem($7, $6)) == 0) {
if (!(temp[$1] = PyTuple_Pack(1, $6))) goto label_$11;
PyErr_SetObject(PyExc_KeyError, temp[$1]);
CLEARTEMP($1);
goto label_$11;
}
Py_INCREF(temp[$0]);
LETLOCAL ( $5 , temp[$0] );
temp[$0] = 0;
""", v2):
TxRepl(o, i, """
if ((GETLOCAL($5) = PyDict_GetItem($7, $6)) == 0) {
if (!(temp[$1] = PyTuple_Pack(1, $6))) goto label_$11;
PyErr_SetObject(PyExc_KeyError, temp[$1]);
CLEARTEMP($1);
goto label_$11;
}
Py_INCREF(GETLOCAL($5));
""", v2)
return True
if TxMatch(o, i, """
if ((temp[$0] = PyDict_GetItem(temp[$7], $6)) == 0) {
if (!(temp[$1] = PyTuple_Pack(1, $6))) goto label_$11;
PyErr_SetObject(PyExc_KeyError, temp[$1]);
CLEARTEMP($1);
goto label_$11;
}
Py_INCREF(temp[$0]);
CLEARTEMP($7);
LETLOCAL ( $5 , temp[$0] );
temp[$0] = 0;
""", v2):
TxRepl(o, i, """
if ((GETLOCAL($5) = PyDict_GetItem(temp[$7], $6)) == 0) {
if (!(temp[$1] = PyTuple_Pack(1, $6))) goto label_$11;
PyErr_SetObject(PyExc_KeyError, temp[$1]);
CLEARTEMP($1);
goto label_$11;
}
Py_INCREF(GETLOCAL($5));
CLEARTEMP($7);
""", v2)
return True
if i+1 < len(o) and 'Py_True' in o[i+1]:
if TxMatch(o, i, """
if ($9) {
temp[$0] = Py_True;
} else {
temp[$0] = Py_False;
}
Py_INCREF(temp[$0]);
$2 = PyObject_IsTrue(temp[$0]);
CLEARTEMP($0);
""", v2):
TxRepl(o, i, """
$2 = $9;
""", v2)
return True
return False
def ConC(*t):
s = ''
for it in t:
s += CVar(it)
return s
def mk_t2(t):
t2 = ['if (', t[0], '(']
for v in t[1:]:
t2.append(v)
t2.append(',')
if len(t) == 1:
t2.append(')')
return t2[:-1]
def maybe_call(to):
return to != 'f->f_lineno' and not istempref(to) and \
not istemptyped(to) and to[0] not in ('{', '}') and\
to[-1] not in ('{', '}') and to[0:3] != 'if ' and \
to not in ('continue;', 'break;', 'return') and \
to[0:4] not in ('for ', 'for(') and to != 'goto'
def do_str(add2):
add3 = [CVar(x) for x in add2]
s = ''
if add3[0] in ('{', '}') and len(add3) == 1:
return add3[0]
for i, st in enumerate(add3):
if i != len(add3)-1:
s += st + ' '
elif st[-1] in ('{', '}'):
s += st
else:
if st[-1] != ';':
s += st + ';'
else:
s += st
## cons = [const_by_n(int(x[7:-1]))
## for x in add2 if x.startswith('consts[') and \
## x.endswith(']') ]
## cons = [x for x in cons if type(x) != types.CodeType]
## if len (cons) > 0 and not no_generate_comment:
## s += ' /* '
## for cco in cons:
## s += repr(cco).replace('/*', '/?*').replace('*/', '*?/') + ', '
## s += ' */'
return s
def generate(cmds, co, filename_):
global filename, func, tempgen, typed_gen, _n2c, pregenerated,\
genfilename, current_co, is_current, Line2Addr
assert len(cmds) == 2
func = co.c_name
filename = filename_
genfilename, nmmodule = Pynm2Cnm(filename)
if not co.can_be_codefunc(): ##co.co_flags & CO_GENERATOR:
stub_generator(co)
return
is_current = IS_CODEFUNC
if co.can_be_cfunc():
is_current = IS_CFUNC
del tempgen[:]
del typed_gen[:]
o = Out()
global try_jump_context, dropped_temp
del try_jump_context[:]
del dropped_temp[:]
label_exc = New('label')
set_toerr_new(o, label_exc)
current_co = co
Line2Addr = line2addr(co)
current_co.to_exception = {}
if func in direct_args and direct_call and not is_current & IS_CFUNC:
seq2 = co.direct_cmds
if seq2 == cmds[1] and len(co.hidden_arg_direct) == 0 and len(co.typed_arg_direct) == 0:
generate_from_frame_to_direct_stube(co, o, co.c_name, cmds)
return
if stat_func == func:
o.append('{')
o.Raw('FILE * _refs = fopen(\"%s_start\", \"w+\");' % func)
o.Raw('_Py_PrintReferences2(_refs);')
o.Raw('fclose(_refs);')
o.append('}')
o = generate_list(cmds[1], o)
optimize(o)
if is_current & IS_CFUNC:
generate_cfunc_header(cmds[0][1], o, co, typed_gen, co.detected_type)
else:
generate_header(cmds[0][1], o, co, typed_gen, co.detected_type)
generate_default_exception_handler(o, co.c_name)
o.append('}')
set_toerr_back(o)
del_unused_ret_label(o)
optimize(o)
if len(tempgen) > co.co_stacksize:
co.co_stacksize = len(tempgen)
pregenerated.append((cmds, o, co))
def list_direct_args(nm):
if nm in direct_args:
return direct_args[nm].keys()
return []
def add_direct_arg(nm, tupl):
a = N2C(nm)
if a.can_be_direct_call is None:
a.can_be_direct_call = can_be_direct_call(a.cmds[1])
if a.can_be_direct_call != True:
return None
if nm not in direct_args:
direct_args[nm] = {}
dic = direct_args[nm]
typ = ()
if type(tupl) is tuple and len(tupl) == 2:
if tupl[0] == '!BUILD_TUPLE':
typ = tuple([TypeExpr(x) for x in tupl[1]])
elif tupl[0] == 'CONST':
typ = tuple([TypeExpr(('CONST', x)) for x in tupl[1]])
if (tupl, typ) not in dic:
dic[(tupl, typ)] = True
def fill_direct_args(it, nm):
if type(it) is tuple and len(it) >= 1 and type(it[0]) is str:
if it[0] == '!CALL_CALC_CONST':
add_direct_arg(it[1], it[2])
elif it[0] == '!CLASS_CALC_CONST_DIRECT' and it[3][0] == '!BUILD_TUPLE':
slf = ('PY_TYPE', T_OLD_CL_INST, it[1], ('PSEVDO', 'self'), None)
add_direct_arg(CodeInit(it[1]), ('!BUILD_TUPLE', (slf,) +it[3][1]))
elif it[0] == '!CLASS_CALC_CONST_DIRECT' and it[3][0] == 'CONST':
slf = ('PY_TYPE', T_OLD_CL_INST, it[1], ('PSEVDO', 'self'), None)
tu = tuple([('CONST', x) for x in it[3][1]])
add_direct_arg(CodeInit(it[1]), ('!BUILD_TUPLE', (slf,) +tu))
return
def concretize_code_direct_call(nm, seq, co):
calls = list_direct_args(nm)
call = join_defined_calls(calls, co.co_argcount, nm, (co.co_flags & 0x4) != 0)
call_changed_arg = {}
dic = {}
collect_store_and_delete_and_fast(seq, dic)
for i, arg in enumerate(call):
assert i < co.co_argcount or (co.co_flags & 0x4 and i == co.co_argcount)
s = ('DELETE_FAST', co.co_varnames[i])
if s in dic:
call[i] = None
continue
s = ('STORE_FAST', co.co_varnames[i])
if s in dic and call[i] != (None, None):
call_changed_arg[i] = call[i]
call[i] = None
seq2 = seq[:]
typed = {}
typed_changed = {}
for i, arg in enumerate(call):
if type(arg) is tuple and \
(arg[0] == 'CONST' or (len(arg) != 2 and len(arg) >= 1 and type(arg[0]) is str) or \
(len(arg) >= 1 and type(arg[0]) is str and arg[0][0] == '!') ):
seq2 = replace_subexpr(seq2, ('FAST', co.co_varnames[i]), arg)
t = TypeExpr(arg)
if t is None:
t = (None, None)
typed[i] = (t[0], t[1])
elif arg is not None and arg != (None, None):
seq2 = replace_subexpr(seq2, ('FAST', co.co_varnames[i]), ('PY_TYPE',) + arg + (('FAST', co.co_varnames[i]),None))
typed[i] = arg
assert type(seq2) is list
for i, arg in call_changed_arg.iteritems():
old = ('FAST', co.co_varnames[i])
stor = ('STORE_FAST', co.co_varnames[i])
dele = ('DELETE_FAST', co.co_varnames[i])
if type(arg) is tuple and arg[0] == 'CONST':
new = arg
replace_concretised_at_list_from_pos(seq2, 0, old, new, stor, dele)
t = TypeExpr(arg)
typed_changed[i] = (t[0], t[1])
elif arg is not None and arg != (None, None):
new = ('PY_TYPE',) + arg + (('FAST', co.co_varnames[i]), None)
replace_concretised_at_list_from_pos(seq2, 0, old, new, stor, dele)
typed_changed[i] = arg
while True:
seq2_ = seq2
seq2 = tree_pass_upgrade_repl(seq2, None, nm)
seq2 = recursive_type_detect(seq2, nm)
if seq2 == seq2_:
break
if co.co_flags & 0x4:
hidden = []
else:
hidden = [i for i, arg in enumerate(call) if type(arg) is tuple and arg[0] == 'CONST']
seq2 = tree_pass_upgrade_repl(seq2, None, nm)
for k,v in typed.iteritems():
Debug('def %s, arg %s -- local type %s' %(nm, co.co_varnames[k], v))
for k,v in typed_changed.iteritems():
Debug('def %s, arg %s changed -- local type %s' %(nm, co.co_varnames[k], v))
co.direct_cmds = seq2
co.hidden_arg_direct = hidden
co.typed_arg_direct = typed
co.typed_arg_direct_changed = typed_changed
## co.changed_arg = {}
## co.all_arg = {}
## for i in range(co.co_argcount + bool(co.co_flags & 0x4)):
## assert i < co.co_argcount or (co.co_flags & 0x4 and i == co.co_argcount)
## co.all_arg[i] = True
## co.all_arg[co.co_varnames[i]] = True
## s = ('DELETE_FAST', co.co_varnames[i])
## if repr(s) in srepr:
## co.changed_arg[i] = True
## co.changed_arg[co.co_varnames[i]] = True
## continue
## s = ('STORE_FAST', co.co_varnames[i])
## if repr(s) in srepr:
## co.changed_arg[i] = True
## co.changed_arg[co.co_varnames[i]] = True
## continue
## if 'STORE_GLOBAL' in srepr or 'DELETE_' in srepr or 'STORE_NAME' in srepr:
## co.changed_arg[i] = True
## co.changed_arg[co.co_varnames[i]] = True
## continue
def generate_direct(cmds, co, filename_):
global filename, func, tempgen, typed_gen, _n2c, pregenerated,\
genfilename, current_co, is_current
assert len(cmds) == 2
func = co.c_name
filename = filename_
genfilename, nmmodule = Pynm2Cnm(filename)
if not co.can_be_codefunc(): ##co.co_flags & CO_GENERATOR:
stub_generator(co)
return
if func in direct_args and direct_call:
is_current = IS_DIRECT
else:
return None
del tempgen[:]
del typed_gen[:]
o = Out()
global try_jump_context, dropped_temp
del try_jump_context[:]
del dropped_temp[:]
label_exc = New('label')
set_toerr_new(o, label_exc)
current_co = co
current_co.to_exception = {}
if stat_func == func:
o.append('{')
o.Raw('FILE * _refs = fopen(\"%s_start\", \"w+\");' % func)
o.Raw('_Py_PrintReferences2(_refs);')
o.Raw('fclose(_refs);')
o.append('}')
strict_varnames(co)
o = generate_list(co.direct_cmds, o)
optimize(o)
i = len(tempgen) - 1
## repro = repr(o)
while i >= 0:
s1 = 'temp[%d]' % i
s2 = 'CLEARTEMP(%d)' % i
if not string_in_o(s1, o) and not string_in_o(s2, o):
del tempgen[i]
i -= 1
continue
else:
break
l1 = len(o)
## have_try = 'TRY' in repr(co.direct_cmds)
generate_default_exception_handler(o, co.c_name)
l2 = len(o)
o.append('}')
set_toerr_back(o)
del_unused_ret_label(o)
optimize(o)
co.co_stacksize = len(tempgen)
generate_header_direct(cmds[0][1], o, co, typed_gen, \
co.typed_arg_direct, co.detected_type)
if l2 == l1 and not have_try(co.direct_cmds):
strip_pyline_pyaddr(o)
o = from_fastlocals_to_single(o)
pregenerated.append((cmds, o, co))
def have_try(cmds):
assert type(cmds) is list
for v in cmds:
if type(v) is list:
if have_try(v):
return True
if type(v) is tuple and len(v) > 0 and v[0] in ('(TRY', '(TRY_FINALLY'):
return True
return False
def string_in_o(s, o):
assert type(o) is Out
for s2 in o:
if s in s2:
return True
return False
def strip_pyline_pyaddr(o):
i = 0
while i < len(o):
assert type(i) is int
if o[i].startswith('PyLine = '):
del o[i]
continue
if o[i].startswith('PyAddr = '):
del o[i]
continue
if o[i].startswith('int PyLine = '):
del o[i]
continue
if o[i].startswith('int PyAddr = '):
del o[i]
continue
i += 1
def from_fastlocals_to_single(o):
global no_fastlocals
if not no_fastlocals:
return o
o2 = Out()
for v in o:
v = v.replace('GETLOCAL(', 'GETFAST(')
v = v.replace('SETLOCAL(', 'SETFAST(')
v = v.replace('SETLOCAL (', 'SETFAST(')
v = v.replace('SETLOCAL2(', 'SETFAST2(')
v = v.replace('SETLOCAL2 (', 'SETFAST2(')
v = v.replace('LETLOCAL(', 'LETFAST(')
v = v.replace('LETLOCAL (', 'LETFAST(')
o2.append(v)
return o2
def strict_varnames(co):
li = []
s2 = repr(co.direct_cmds)
for i, v in enumerate(co.co_varnames):
if i < co.co_argcount:
li.append(v)
continue
if repr(('FAST', v)) in s2 or repr(('STORE_FAST', v)) in s2 or repr(('DELETE_FAST', v)) in s2:
li.append(v)
continue
co.co_varnames_direct = li
def generate_default_exception_handler(o, nm):
if IsUsedLabl(labl) or len(current_co.to_exception) > 0:
clabl = CVar(labl)
found = False
for s in o:
if clabl in s:
found = True
break
if not found and len(current_co.to_exception) == 0:
return
o.Raw('if (0) {')
for tu, lb in current_co.to_exception.iteritems():
o.Raw(lb, ':;')
o.extend(tu)
o.Raw(labl, ':;')
if is_current & IS_CODEFUNC:
o.append('PyTraceBack_Here(f);')
else:
cod = const_to(current_co)
Used('Direct_AddTraceback')
if line_number:
o.Raw('Direct_AddTraceback((PyCodeObject *)', cod, ', PyLine, PyAddr);')
else:
o.Raw('Direct_AddTraceback((PyCodeObject *)', cod, ', 0, 0);')
if is_current & IS_DIRECT:
hid = {}
for i in current_co.hidden_arg_direct:
hid[current_co.co_varnames[i]] = True
for i,v in enumerate(current_co.co_varnames_direct):
if v in hid:
continue
## if v in current_co.all_arg and v not in current_co.changed_arg:
## continue
nmvar = nmvar_to_loc(v)
if not current_co.IsCVar(('FAST', v)):
o.CLEAR('GETLOCAL(' + nmvar + ')')
for i in range(len(tempgen)):
o.Raw('CLEARTEMP(', str(i), ');')
if calc_ref_total:
o.Raw('if ((_Py_RefTotal - l_Py_RefTotal) > 0) {printf ("func ', current_co.co_name, ' delta ref = %d\\n", (int)(_Py_RefTotal - l_Py_RefTotal));}')
if is_current & IS_CODEFUNC:
if check_recursive_call:
o.append('Py_LeaveRecursiveCall();')
if is_current & IS_CODEFUNC and not is_pypy:
o.append('tstate->frame = f->f_back;')
if is_current & IS_DIRECT and \
(current_co.IsRetVoid() or IsCType(current_co.ReturnType())):
o.Raw('return -1;')
else:
if nm == 'Init_filename' and build_executable:
o.Raw('PyErr_Print();')
o.Stmt('return', 'NULL;')
o.append('}')
c_head1 = """
/* Generated by 2C Python */
#include "Python.h"
#include "frameobject.h"
#include "funcobject.h"
#include "code.h"
#include "dictobject.h"
#include "listobject.h"
#include "abstract.h"
#include "structmember.h"
#include "object.h"
PyTypeObject Py2CCode_Type;
PyTypeObject Py2CFunction_Type;
#define Py2CCode_CheckExact(op) (Py_TYPE(op) == &Py2CCode_Type)
#define Py2CCode_Check(op) PyObject_TypeCheck(op, &Py2CCode_Type)
#define Py2CFunction_CheckExact(op) (Py_TYPE(op) == &Py2CFunction_Type)
#define Py2CFunction_Check(op) PyObject_TypeCheck(op, &Py2CFunction_Type)
typedef struct {
PyCodeObject _body;
void *co_function; /* Python code compiled to C function */
} Py2CCodeObject;
/* Public interface */
static Py2CCodeObject * Py2CCode_New(
int, int, int, int, PyObject *, PyObject *, PyObject *, PyObject *,
PyObject *, PyObject *, PyObject *, PyObject *, int, PyObject *, void *);
static PyObject * b = NULL;
static PyObject * bdict = NULL;
/*#define DEBUG_LOCAL_REFCNT*/
/* Local variable macros */
#ifdef DEBUG_LOCAL_REFCNT
#define GETLOCAL(i) printf("Get local %s line %5d refcnt %d\\n", #i, __LINE__, (int)(fastlocals[Loc_##i]->ob_refcnt)),fastlocals[Loc_##i]
#define GETFAST(i) printf("Get local %s line %5d refcnt %d\\n", #i, __LINE__, (int)(_Fast_##i->ob_refcnt)), _Fast_##i
#else
#define GETLOCAL(i) (fastlocals[Loc_##i])
#define GETFAST(i) _Fast_##i
#endif
#define GETFREEVAR(i) (freevars[Loc2_##i])
#define GETSTATIC(i) (fastglob[Glob_##i])
/* The SETLOCAL() macro must not DECREF the local variable in-place and
then store the new value; it must copy the old value to a temporary
value, then store the new value, and then DECREF the temporary value.
This is because it is possible that during the DECREF the frame is
accessed by other code (e.g. a __del__ method or gc.collect()) and the
variable would be pointing to already-freed memory. */
#ifdef DEBUG_LOCAL_REFCNT
#define SETLOCAL(i, value) do { PyObject *tmp = fastlocals[Loc_##i]; \
if (tmp != NULL) \
printf("Replace local %s line %5d refcnt %d\\n", #i, __LINE__, (int)(tmp->ob_refcnt));\
fastlocals[Loc_##i] = value; \
printf("New local %s line %5d refcnt %d\\n", #i, __LINE__, (int)(fastlocals[Loc_##i]->ob_refcnt));\
Py_XDECREF(tmp); } while (0)
#define SETLOCAL2(i, value) SETLOCAL(i, value)
#define SETFAST(i, value) do { PyObject *tmp = _Fast_##i; \
if (tmp != NULL) \
printf("Replace local %s line %5d refcnt %d\\n", #i, __LINE__, (int)(tmp->ob_refcnt));\
_Fast_##i = value; \
printf("New local %s line %5d refcnt %d\\n", #i, __LINE__, (int)(_Fast_##i->ob_refcnt));\
Py_XDECREF(tmp); } while (0)
#define SETFAST2(i, value) SETFAST(i, value)
#else
#define SETLOCAL(i, value) do { PyObject *tmp = fastlocals[Loc_##i]; \
fastlocals[Loc_##i] = value; \
Py_XDECREF(tmp); } while (0)
#define SETLOCAL2(i, value) do { Py_XDECREF(fastlocals[Loc_##i]);\
fastlocals[Loc_##i] = value; } while (0)
#define SETFAST(i, value) do { PyObject *tmp = _Fast_##i; \
_Fast_##i = value; \
Py_XDECREF(tmp); } while (0)
#define SETFAST2(i, value) do { Py_XDECREF(_Fast_##i);\
_Fast_##i = value; } while (0)
#endif
#define LETLOCAL(i, value) fastlocals[Loc_##i] = (value)
#define LETFAST(i, value) _Fast_##i = (value)
#define SETSTATIC(i, value) do { PyObject *tmp = fastglob[Glob_##i]; \
fastglob[Glob_##i] = value; \
Py_XDECREF(tmp); } while (0)
#define COPYTEMP(new, old) do { new = old; \
old = NULL; } while (0)
#define CLEARTEMP(x) Py_CLEAR(temp[x])
typedef char *charref;
typedef long *longref;
"""
c_head2 = """
static PyObject * consts[];
static PyObject * loaded_builtin[];
static PyObject * calculated_const[];
"""
c_head3 = """
static PyObject * glob;
static PyObject * empty_tuple;
/*void static check_const_refcnt(void);*/
/* Status code for main loop (reason for stack unwind) */
enum why_code {
WHY_NOT = 0x0001, /* No error */
WHY_EXCEPTION = 0x0002, /* Exception occurred */
WHY_RERAISE = 0x0004, /* Exception re-raised by 'finally' */
WHY_RETURN = 0x0008, /* 'return' statement */
WHY_BREAK = 0x0010, /* 'break' statement */
WHY_CONTINUE = 0x0020, /* 'continue' statement */
WHY_YIELD = 0x0040 /* 'yield' operator */
};
#define NAME_ERROR_MSG \
"name '%.200s' is not defined"
#define GLOBAL_NAME_ERROR_MSG \
"global name '%.200s' is not defined"
#define UNBOUNDLOCAL_ERROR_MSG \
"local variable '%.200s' referenced before assignment"
#define UNBOUNDFREE_ERROR_MSG \
"free variable '%.200s' referenced before assignment" \
" in enclosing scope"
#define c_Py_GT_Int(v,l,w) ((PyInt_CheckExact(v))?(PyInt_AS_LONG(v) > l) : (PyObject_RichCompareBool(v, w, Py_GT)))
#define c_Py_LT_Int(v,l,w) ((PyInt_CheckExact(v))?(PyInt_AS_LONG(v) < l) : (PyObject_RichCompareBool(v, w, Py_LT)))
#define c_Py_GE_Int(v,l,w) ((PyInt_CheckExact(v))?(PyInt_AS_LONG(v) >= l) : (PyObject_RichCompareBool(v, w, Py_GE)))
#define c_Py_LE_Int(v,l,w) ((PyInt_CheckExact(v))?(PyInt_AS_LONG(v) <= l) : (PyObject_RichCompareBool(v, w, Py_LE)))
#define c_Py_EQ_Int(v,l,w) ((PyInt_CheckExact(v))?(PyInt_AS_LONG(v) == l) : (PyObject_RichCompareBool(v, w, Py_EQ)))
#define c_Py_NE_Int(v,l,w) ((PyInt_CheckExact(v))?(PyInt_AS_LONG(v) != l) : (PyObject_RichCompareBool(v, w, Py_NE)))
#define c_Py_EQ_String(v,l,w,w2) ((PyString_CheckExact(v))?(PyString_GET_SIZE(v) == l && memcmp(PyString_AS_STRING(v),w,l) == 0) : (PyObject_RichCompareBool(v, w2, Py_EQ)))
#define c_Py_NE_String(v,l,w,w2) ((PyString_CheckExact(v))?(PyString_GET_SIZE(v) != l || memcmp(PyString_AS_STRING(v),w,l) != 0) : (PyObject_RichCompareBool(v, w2, Py_NE)))
#ifndef PYPY_VERSION
#define FirstCFunctionCall(a,b,c) ((PyCFunction_Check (a)) ? ( PyCFunction_Call(a,b,c) ) : ( PyObject_Call(a,b,c) ))
#else
#define FirstCFunctionCall(a,b,c) PyObject_Call(a,b,c)
#endif
#define GET_ATTR_LOCAL(n, nm, attr, labl) if (_ ##nm##_dict && (temp[n] = PyDict_GetItem(_##nm##_dict, attr)) != 0) { Py_INCREF(temp[n]); } else if ((temp[n] = PyObject_GetAttr ( GETLOCAL(nm) , attr )) == 0) goto labl; else
static void patch_code2c(void);
static PyObject *
PyImport_Exec2CCodeModuleEx(char *name, PyObject *co);
"""
c_tail = """
#ifndef PYPY_VERSION
#define NAME_CHARS \
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"
/* all_name_chars(s): true iff all chars in s are valid NAME_CHARS */
static int
all_name_chars(unsigned char *s)
{
static char ok_name_char[256];
static unsigned char *name_chars = (unsigned char *)NAME_CHARS;
if (ok_name_char[*name_chars] == 0) {
unsigned char *p;
for (p = name_chars; *p; p++)
ok_name_char[*p] = 1;
}
while (*s) {
if (ok_name_char[*s++] == 0)
return 0;
}
return 1;
}
static void
intern_strings(PyObject *tuple)
{
Py_ssize_t i;
for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
PyObject *v = PyTuple_GET_ITEM(tuple, i);
if (v == 0 || !PyString_CheckExact(v)) {
Py_FatalError("non-string found in code slot");
}
PyString_InternInPlace(&PyTuple_GET_ITEM(tuple, i));
}
}
#endif
static Py2CCodeObject *
Py2CCode_New(int argcount, int nlocals, int stacksize, int flags,
PyObject *code, PyObject *consts, PyObject *names,
PyObject *varnames, PyObject *freevars, PyObject *cellvars,
PyObject *filename, PyObject *name, int firstlineno,
PyObject *lnotab, void * func)
{
PyCodeObject *co;
Py_ssize_t i;
/* Check argument types */
if (argcount < 0 || nlocals < 0 ||
code == 0 ||
consts == 0 || !PyTuple_Check(consts) ||
names == 0 || !PyTuple_Check(names) ||
varnames == 0 || !PyTuple_Check(varnames) ||
freevars == 0 || !PyTuple_Check(freevars) ||
cellvars == 0 || !PyTuple_Check(cellvars) ||
name == 0 || !PyString_Check(name) ||
filename == 0 || !PyString_Check(filename) ||
lnotab == 0 || !PyString_Check(lnotab) ||
func == 0 ||
!PyObject_CheckReadBuffer(code)) {
PyErr_BadInternalCall();
return NULL;
}
#ifndef PYPY_VERSION
intern_strings(names);
intern_strings(varnames);
intern_strings(freevars);
intern_strings(cellvars);
/* Intern selected string constants */
for (i = PyTuple_Size(consts); --i >= 0; ) {
PyObject *v = PyTuple_GetItem(consts, i);
if (!PyString_Check(v))
continue;
if (!all_name_chars((unsigned char *)PyString_AS_STRING(v)))
continue;
PyString_InternInPlace(&PyTuple_GET_ITEM(consts, i));
}
#endif
co = (PyCodeObject *)PyObject_NEW(Py2CCodeObject, &Py2CCode_Type);
if (co != NULL) {
co->co_argcount = argcount;
co->co_nlocals = nlocals;
co->co_stacksize = stacksize;
co->co_flags = flags;
Py_INCREF(code);
co->co_code = code;
Py_INCREF(consts);
co->co_consts = consts;
Py_INCREF(names);
co->co_names = names;
Py_INCREF(varnames);
co->co_varnames = varnames;
Py_INCREF(freevars);
co->co_freevars = freevars;
Py_INCREF(cellvars);
co->co_cellvars = cellvars;
Py_INCREF(filename);
co->co_filename = filename;
Py_INCREF(name);
co->co_name = name;
co->co_firstlineno = firstlineno;
Py_INCREF(lnotab);
co->co_lnotab = lnotab;
co->co_zombieframe = NULL;
((Py2CCodeObject *)co)->co_function = func;
}
return ((Py2CCodeObject *)co);
}
static PyObject * code_repr(PyCodeObject *co)
{
char buf[500];
int lineno = -1;
char *filename = "???";
char *name = "???";
PyObject * o_filename;
PyObject * o_name;
o_filename = 0;
o_name = 0;
#ifdef PYPY_VERSION
{
PyObject * o_first;
o_first = PyObject_GetAttrString((PyObject *)co, "co_firstlineno");
assert(o_first != 0);
o_filename = PyObject_GetAttrString((PyObject *)co, "co_filename");
assert(o_filename != 0);
o_name = PyObject_GetAttrString((PyObject *)co, "co_name");
assert(o_name != 0);
lineno = PyInt_AsLong(o_first);
Py_CLEAR(o_first);
}
#else
o_filename = co->co_filename;
o_name = co->co_name;
if (co->co_firstlineno != 0)
lineno = co->co_firstlineno;
#endif
if (o_filename && PyString_Check(o_filename))
filename = PyString_AS_STRING(o_filename);
if (o_name && PyString_Check(o_name))
name = PyString_AS_STRING(o_name);
PyOS_snprintf(buf, sizeof(buf),
"<code object %.100s at %p(%p), file \\"%.300s\\", line %d>",
name, co, ((Py2CCodeObject *)co)->co_function, filename, lineno);
#ifdef PYPY_VERSION
Py_CLEAR(o_filename);
Py_CLEAR(o_name);
#endif
return PyString_FromString(buf);
}
static int code_compare(PyObject *co, PyObject *cp)
{
int cmp;
cmp = PyCode_Type.tp_compare(co, cp);
if (cmp) return cmp;
cmp = (long)((Py2CCodeObject *)co)->co_function - (long)((Py2CCodeObject *)cp)->co_function;
if (cmp) goto normalize;
return cmp;
normalize:
if (cmp > 0)
return 1;
else if (cmp < 0)
return -1;
else
return 0;
}
static PyObject * code_richcompare(PyObject *self, PyObject *other, int op)
{
int eq;
PyObject *res;
if ((op == Py_EQ || op == Py_NE) && Py2CCode_CheckExact(self) && Py2CCode_CheckExact(other)) {
eq = ((Py2CCodeObject *)self)->co_function == ((Py2CCodeObject *)other)->co_function;
if (!eq) goto unequal;
if (op == Py_EQ)
res = Py_True;
else
res = Py_False;
goto done;
unequal:
if (eq < 0)
return NULL;
if (op == Py_NE)
res = Py_True;
else
res = Py_False;
done:
Py_INCREF(res);
return res;
}
if ((op != Py_EQ && op != Py_NE) ||
!PyCode_Check(self) ||
!PyCode_Check(other)) {
/* Py3K warning if types are not equal and comparison
isn't == or != */
if (PyErr_WarnPy3k("code inequality comparisons not supported "
"in 3.x", 1) < 0) {
return NULL;
}
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
}
return PyCode_Type.tp_richcompare(self, other, op);
}
static long code_hash(PyCodeObject *co)
{
return (long)(((Py2CCodeObject *)co)->co_function);
}
PyTypeObject Py2CCode_Type;
/* Function object implementation */
#include "eval.h"
static PyObject *
function_call(PyObject *func, PyObject *arg, PyObject *kw)
{
PyObject *result;
PyObject *argdefs;
PyObject **d, **k;
Py_ssize_t nk, nd;
argdefs = PyFunction_GET_DEFAULTS(func);
if (argdefs != NULL && PyTuple_Check(argdefs)) {
d = &PyTuple_GET_ITEM((PyTupleObject *)argdefs, 0);
nd = PyTuple_Size(argdefs);
}
else {
d = NULL;
nd = 0;
}
if (kw != NULL && PyDict_Check(kw)) {
Py_ssize_t pos, i;
nk = PyDict_Size(kw);
k = PyMem_NEW(PyObject *, 2*nk);
if (k == 0) {
PyErr_NoMemory();
return NULL;
}
pos = i = 0;
while (PyDict_Next(kw, &pos, &k[i], &k[i+1]))
i += 2;
nk = i/2;
/* XXX This is broken if the caller deletes dict items! */
}
else {
k = NULL;
nk = 0;
}
result = PyEval_Eval2CCodeEx(
(PyCodeObject *)PyFunction_GET_CODE(func),
(PyObject *)NULL,
&PyTuple_GET_ITEM(arg, 0), PyTuple_Size(arg),
k, nk, d, nd
#ifndef PYPY_VERSION
,
PyFunction_GET_CLOSURE(func));
#else
);
#endif
if (k != NULL)
PyMem_DEL(k);
return result;
}
#define ISINDEX(x) ((x) == 0 || \
PyInt_Check(x) || PyLong_Check(x) || PyIndex_Check(x))
/* Remove name from sys.modules, if it's there. */
static void
_RemoveModule(const char *name)
{
PyObject *modules = PyImport_GetModuleDict();
if (PyDict_GetItemString(modules, name) == 0)
return;
if (PyDict_DelItemString(modules, name) < 0)
Py_FatalError("import: deleting existing key in"
"sys.modules failed");
}
static PyObject *
PyImport_Exec2CCodeModuleEx(char *name, PyObject *co)
{
PyObject *modules = PyImport_GetModuleDict();
PyObject *m, *d, *v;
m = PyImport_AddModule(name);
if (m == 0)
return NULL;
/* If the module is being reloaded, we get the old module back
and re-use its dict to exec the new code. */
d = PyModule_GetDict(m);
if (PyDict_GetItemString(d, "__builtins__") == 0) {
if (PyDict_SetItemString(d, "__builtins__",
PyEval_GetBuiltins()) != 0)
goto error;
}
/* Remember the filename as the __file__ attribute */
#ifndef PYPY_VERSION
v = ((PyCodeObject *)co)->co_filename;
/* v = PyString_FromString(src_name);*/
Py_INCREF(v);
#else
v = PyObject_GetAttrString(co, "co_filename");
#endif
if (PyDict_SetItemString(d, "__file__", v) != 0)
PyErr_Clear(); /* Not important enough to report */
Py_DECREF(v);
v = PyString_FromString(name);
Py_INCREF(v);
if (PyDict_SetItemString(d, "__name__", v) != 0)
PyErr_Clear(); /* Not important enough to report */
Py_DECREF(v);
glob = d;
v = PyEval_Eval2CCodeEx((PyCodeObject *)co,
d,
(PyObject **)NULL, 0,
(PyObject **)NULL, 0,
(PyObject **)NULL, 0
#ifndef PYPY_VERSION
,
NULL);
#else
);
#endif
if (v == 0)
goto error;
Py_DECREF(v);
if ((m = PyDict_GetItemString(modules, name)) == 0) {
PyErr_Format(PyExc_ImportError,
"Loaded module %.200s not found in sys.modules",
name);
return NULL;
}
Py_INCREF(m);
return m;
error:
_RemoveModule(name);
return NULL;
}
static void patch_code2c(void){
Py2CCode_Type = PyCode_Type;
Py2CCode_Type.ob_type = &PyType_Type;
Py2CCode_Type.tp_richcompare = code_richcompare;
Py2CCode_Type.tp_compare = (cmpfunc)code_compare;
Py2CCode_Type.tp_repr = (reprfunc)code_repr;
Py2CCode_Type.tp_hash = (hashfunc)code_hash;
Py2CCode_Type.tp_new = 0;
Py2CCode_Type.tp_name = "code2c";
Py2CCode_Type.tp_basicsize = sizeof(Py2CCodeObject);
Py2CFunction_Type = PyFunction_Type;
Py2CFunction_Type.ob_type = &PyType_Type;
Py2CFunction_Type.tp_new = 0;
Py2CFunction_Type.tp_name = "function2c";
Py2CFunction_Type.tp_call = function_call;
}
"""
def UseLabl():
current_co.used_label[labl] = True
## def UseThisLabel(label):
## current_co.used_label[label] = True
## ## _3(func, 'UseLabel', labl)
def IsUsedLabl(labl):
return labl in current_co.used_label
libr_depends = {'_PyEval_PRINT_ITEM_1' : ('_PyEval_PRINT_ITEM_TO_2',),\
'from_ceval_call_exc_trace' : ('from_ceval_call_trace',),\
'PyEval_Eval2CCodeEx': ('kwd_as_string',)}
def Used(nm):
## depends = {'_PyEval_PRINT_ITEM_1' : ('_PyEval_PRINT_ITEM_TO_2',),\
## 'from_ceval_call_exc_trace' : ('from_ceval_call_trace',),\
## 'PyEval_Eval2CCodeEx': ('kwd_as_string',)}
_3(nm, 'Used', True)
if nm in libr_depends:
for nm2 in libr_depends[nm]:
Used(nm2)
_Libr = {}
def IsLibr(nm):
return nm in _Libr
def Libr(nm, dcl, defin):
_Libr[nm] = (dcl, defin)
def LibrDcl(nm):
return _Libr[nm][0]
def LibrDef(nm):
return _Libr[nm][1]
if tuple(sys.version_info)[:2] == (2,6):
Libr('PyEval_Eval2CCodeEx',
"""
static PyObject *
PyEval_Eval2CCodeEx(PyCodeObject *, PyObject *,
PyObject **, int , PyObject **, int ,
PyObject **, int
#ifndef PYPY_VERSION
, PyObject *);
#else
);
#endif
""",
"""
/* Local variable macros */
#undef GETLOCAL
#undef SETLOCAL
#define GETLOCAL(i) (fastlocals[i])
#define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \
GETLOCAL(i) = value; \
Py_XDECREF(tmp); } while (0)
static PyObject *
PyEval_Eval2CCodeEx(PyCodeObject *co, PyObject *locals,
PyObject **args, int argcount, PyObject **kws, int kwcount,
PyObject **defs, int defcount
#ifndef PYPY_VERSION
, PyObject *closure)
#else
)
#endif
{
register PyFrameObject *f;
register PyObject *retval = NULL;
register PyObject **fastlocals, **freevars;
PyThreadState *tstate = PyThreadState_GET();
PyObject *x, *u;
PyObject *(*c_func)(PyFrameObject *);
assert(tstate != NULL);
f = PyFrame_New(tstate, co, glob, locals);
if (f == 0)
return NULL;
fastlocals = f->f_localsplus;
freevars = f->f_localsplus + co->co_nlocals;
if (co->co_argcount > 0 ||
co->co_flags & (CO_VARARGS | CO_VARKEYWORDS)) {
int i;
int n = argcount;
PyObject *kwdict = NULL;
if (co->co_flags & CO_VARKEYWORDS) {
kwdict = PyDict_New();
if (kwdict == 0)
goto fail;
i = co->co_argcount;
if (co->co_flags & CO_VARARGS)
i++;
SETLOCAL(i, kwdict);
}
if (argcount > co->co_argcount) {
if (!(co->co_flags & CO_VARARGS)) {
PyErr_Format(PyExc_TypeError,
"%.200s() takes %s %d "
"%sargument%s (%d given)",
PyString_AsString(co->co_name),
defcount ? "at most" : "exactly",
co->co_argcount,
kwcount ? "non-keyword " : "",
co->co_argcount == 1 ? "" : "s",
argcount);
goto fail;
}
n = co->co_argcount;
}
for (i = 0; i < n; i++) {
x = args[i];
Py_INCREF(x);
SETLOCAL(i, x);
}
if (co->co_flags & CO_VARARGS) {
u = PyTuple_New(argcount - n);
if (u == 0)
goto fail;
SETLOCAL(co->co_argcount, u);
for (i = n; i < argcount; i++) {
x = args[i];
Py_INCREF(x);
PyTuple_SET_ITEM(u, i-n, x);
}
}
for (i = 0; i < kwcount; i++) {
PyObject **co_varnames;
PyObject *keyword = kws[2*i];
PyObject *value = kws[2*i + 1];
int j;
if (keyword == 0 || !PyString_Check(keyword)) {
PyErr_Format(PyExc_TypeError,
"%.200s() keywords must be strings",
PyString_AsString(co->co_name));
goto fail;
}
/* Speed hack: do raw pointer compares. As names are
normally interned this should almost always hit. */
co_varnames = PySequence_Fast_ITEMS(co->co_varnames);
for (j = 0; j < co->co_argcount; j++) {
PyObject *nm = co_varnames[j];
if (nm == keyword)
goto kw_found;
}
/* Slow fallback, just in case */
for (j = 0; j < co->co_argcount; j++) {
PyObject *nm = co_varnames[j];
int cmp = PyObject_RichCompareBool(
keyword, nm, Py_EQ);
if (cmp > 0)
goto kw_found;
else if (cmp < 0)
goto fail;
}
/* Check errors from Compare */
if (PyErr_Occurred())
goto fail;
if (j >= co->co_argcount) {
if (kwdict == 0) {
PyErr_Format(PyExc_TypeError,
"%.200s() got an unexpected "
"keyword argument '%.400s'",
PyString_AsString(co->co_name),
PyString_AsString(keyword));
goto fail;
}
PyDict_SetItem(kwdict, keyword, value);
continue;
}
kw_found:
if (GETLOCAL(j) != NULL) {
PyErr_Format(PyExc_TypeError,
"%.200s() got multiple "
"values for keyword "
"argument '%.400s'",
PyString_AsString(co->co_name),
PyString_AsString(keyword));
goto fail;
}
Py_INCREF(value);
SETLOCAL(j, value);
}
if (argcount < co->co_argcount) {
int m = co->co_argcount - defcount;
for (i = argcount; i < m; i++) {
if (GETLOCAL(i) == 0) {
PyErr_Format(PyExc_TypeError,
"%.200s() takes %s %d "
"%sargument%s (%d given)",
PyString_AsString(co->co_name),
((co->co_flags & CO_VARARGS) ||
defcount) ? "at least"
: "exactly",
m, kwcount ? "non-keyword " : "",
m == 1 ? "" : "s", i);
goto fail;
}
}
if (n > m)
i = n - m;
else
i = 0;
for (; i < defcount; i++) {
if (GETLOCAL(m+i) == 0) {
PyObject *def = defs[i];
Py_INCREF(def);
SETLOCAL(m+i, def);
}
}
}
}
else {
if (argcount > 0 || kwcount > 0) {
PyErr_Format(PyExc_TypeError,
"%.200s() takes no arguments (%d given)",
PyString_AsString(co->co_name),
argcount + kwcount);
goto fail;
}
}
/* Allocate and initialize storage for cell vars, and copy free
vars into frame. This isn't too efficient right now. */
if (PyTuple_GET_SIZE(co->co_cellvars)) {
int i, j, nargs, found;
char *cellname, *argname;
PyObject *c;
nargs = co->co_argcount;
if (co->co_flags & CO_VARARGS)
nargs++;
if (co->co_flags & CO_VARKEYWORDS)
nargs++;
/* Initialize each cell var, taking into account
cell vars that are initialized from arguments.
Should arrange for the compiler to put cellvars
that are arguments at the beginning of the cellvars
list so that we can march over it more efficiently?
*/
for (i = 0; i < PyTuple_GET_SIZE(co->co_cellvars); ++i) {
cellname = PyString_AS_STRING(
PyTuple_GET_ITEM(co->co_cellvars, i));
found = 0;
for (j = 0; j < nargs; j++) {
argname = PyString_AS_STRING(
PyTuple_GET_ITEM(co->co_varnames, j));
if (strcmp(cellname, argname) == 0) {
c = PyCell_New(GETLOCAL(j));
if (c == 0)
goto fail;
GETLOCAL(co->co_nlocals + i) = c;
found = 1;
break;
}
}
if (found == 0) {
c = PyCell_New(NULL);
if (c == 0)
goto fail;
SETLOCAL(co->co_nlocals + i, c);
}
}
}
#ifndef PYPY_VERSION
if (PyTuple_GET_SIZE(co->co_freevars)) {
int i;
for (i = 0; i < PyTuple_GET_SIZE(co->co_freevars); ++i) {
PyObject *o = PyTuple_GET_ITEM(closure, i);
Py_INCREF(o);
freevars[PyTuple_GET_SIZE(co->co_cellvars) + i] = o;
}
}
#endif
c_func = ((Py2CCodeObject *)co)->co_function;
retval = c_func(f);
fail: /* Jump here from prelude on failure */
/* decref'ing the frame can cause __del__ methods to get invoked,
which can call back into Python. While we're done with the
current Python frame (f), the associated C stack is still in use,
so recursion_depth must be boosted for the duration.
*/
assert(tstate != NULL);
#ifndef PYPY_VERSION
++tstate->recursion_depth;
#endif
Py_DECREF(f);
#ifndef PYPY_VERSION
--tstate->recursion_depth;
#endif
return retval;
}
""")
elif tuple(sys.version_info)[:2] == (2,7):
Libr('PyEval_Eval2CCodeEx',
"""
static PyObject *
PyEval_Eval2CCodeEx(PyCodeObject *, PyObject *,
PyObject **, int , PyObject **, int ,
PyObject **, int
#ifndef PYPY_VERSION
, PyObject *);
#else
);
#endif
""",
"""
/* Local variable macros */
#undef GETLOCAL
#undef SETLOCAL
#define GETLOCAL(i) (fastlocals[i])
#define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \
GETLOCAL(i) = value; \
Py_XDECREF(tmp); } while (0)
static PyObject *
PyEval_Eval2CCodeEx(PyCodeObject *co, PyObject *locals,
PyObject **args, int argcount, PyObject **kws, int kwcount,
PyObject **defs, int defcount
#ifndef PYPY_VERSION
, PyObject *closure)
#else
)
#endif
{
register PyFrameObject *f;
register PyObject *retval = NULL;
register PyObject **fastlocals, **freevars;
PyThreadState *tstate = PyThreadState_GET();
PyObject *x, *u;
PyObject *(*c_func)(PyFrameObject *);
assert(tstate != NULL);
f = PyFrame_New(tstate, co, glob, locals);
if (f == 0)
return NULL;
fastlocals = f->f_localsplus;
freevars = f->f_localsplus + co->co_nlocals;
if (co->co_argcount > 0 ||
co->co_flags & (CO_VARARGS | CO_VARKEYWORDS)) {
int i;
int n = argcount;
PyObject *kwdict = NULL;
if (co->co_flags & CO_VARKEYWORDS) {
kwdict = PyDict_New();
if (kwdict == 0)
goto fail;
i = co->co_argcount;
if (co->co_flags & CO_VARARGS)
i++;
SETLOCAL(i, kwdict);
}
if (argcount > co->co_argcount) {
if (!(co->co_flags & CO_VARARGS)) {
PyErr_Format(PyExc_TypeError,
"%.200s() takes %s %d "
"%sargument%s (%d given)",
PyString_AsString(co->co_name),
defcount ? "at most" : "exactly",
co->co_argcount,
kwcount ? "non-keyword " : "",
co->co_argcount == 1 ? "" : "s",
argcount);
goto fail;
}
n = co->co_argcount;
}
for (i = 0; i < n; i++) {
x = args[i];
Py_INCREF(x);
SETLOCAL(i, x);
}
if (co->co_flags & CO_VARARGS) {
u = PyTuple_New(argcount - n);
if (u == 0)
goto fail;
SETLOCAL(co->co_argcount, u);
for (i = n; i < argcount; i++) {
x = args[i];
Py_INCREF(x);
PyTuple_SET_ITEM(u, i-n, x);
}
}
for (i = 0; i < kwcount; i++) {
PyObject **co_varnames;
PyObject *keyword = kws[2*i];
PyObject *value = kws[2*i + 1];
int j;
if (keyword == 0 || !(PyString_Check(keyword)
#ifdef Py_USING_UNICODE
|| PyUnicode_Check(keyword)
#endif
)) {
PyErr_Format(PyExc_TypeError,
"%.200s() keywords must be strings",
PyString_AsString(co->co_name));
goto fail;
}
/* Speed hack: do raw pointer compares. As names are
normally interned this should almost always hit. */
co_varnames = ((PyTupleObject *)(co->co_varnames))->ob_item;
for (j = 0; j < co->co_argcount; j++) {
PyObject *nm = co_varnames[j];
if (nm == keyword)
goto kw_found;
}
/* Slow fallback, just in case */
for (j = 0; j < co->co_argcount; j++) {
PyObject *nm = co_varnames[j];
int cmp = PyObject_RichCompareBool(
keyword, nm, Py_EQ);
if (cmp > 0)
goto kw_found;
else if (cmp < 0)
goto fail;
}
if (kwdict == 0) {
PyObject *kwd_str = kwd_as_string(keyword);
if (kwd_str) {
PyErr_Format(PyExc_TypeError,
"%.200s() got an unexpected "
"keyword argument '%.400s'",
PyString_AsString(co->co_name),
PyString_AsString(kwd_str));
Py_DECREF(kwd_str);
}
goto fail;
}
PyDict_SetItem(kwdict, keyword, value);
continue;
kw_found:
if (GETLOCAL(j) != NULL) {
PyObject *kwd_str = kwd_as_string(keyword);
if (kwd_str) {
PyErr_Format(PyExc_TypeError,
"%.200s() got multiple "
"values for keyword "
"argument '%.400s'",
PyString_AsString(co->co_name),
PyString_AsString(kwd_str));
Py_DECREF(kwd_str);
}
}
Py_INCREF(value);
SETLOCAL(j, value);
}
if (argcount < co->co_argcount) {
int m = co->co_argcount - defcount;
for (i = argcount; i < m; i++) {
if (GETLOCAL(i) == 0) {
int j, given = 0;
for (j = 0; j < co->co_argcount; j++)
if (GETLOCAL(j))
given++;
PyErr_Format(PyExc_TypeError,
"%.200s() takes %s %d "
"argument%s (%d given)",
PyString_AsString(co->co_name),
((co->co_flags & CO_VARARGS) ||
defcount) ? "at least"
: "exactly",
m, m == 1 ? "" : "s", given);
goto fail;
}
}
if (n > m)
i = n - m;
else
i = 0;
for (; i < defcount; i++) {
if (GETLOCAL(m+i) == 0) {
PyObject *def = defs[i];
Py_INCREF(def);
SETLOCAL(m+i, def);
}
}
}
}
else {
if (argcount > 0 || kwcount > 0) {
PyErr_Format(PyExc_TypeError,
"%.200s() takes no arguments (%d given)",
PyString_AsString(co->co_name),
argcount + kwcount);
goto fail;
}
}
/* Allocate and initialize storage for cell vars, and copy free
vars into frame. This isn't too efficient right now. */
if (PyTuple_GET_SIZE(co->co_cellvars)) {
int i, j, nargs, found;
char *cellname, *argname;
PyObject *c;
nargs = co->co_argcount;
if (co->co_flags & CO_VARARGS)
nargs++;
if (co->co_flags & CO_VARKEYWORDS)
nargs++;
/* Initialize each cell var, taking into account
cell vars that are initialized from arguments.
Should arrange for the compiler to put cellvars
that are arguments at the beginning of the cellvars
list so that we can march over it more efficiently?
*/
for (i = 0; i < PyTuple_GET_SIZE(co->co_cellvars); ++i) {
cellname = PyString_AS_STRING(
PyTuple_GET_ITEM(co->co_cellvars, i));
found = 0;
for (j = 0; j < nargs; j++) {
argname = PyString_AS_STRING(
PyTuple_GET_ITEM(co->co_varnames, j));
if (strcmp(cellname, argname) == 0) {
c = PyCell_New(GETLOCAL(j));
if (c == 0)
goto fail;
GETLOCAL(co->co_nlocals + i) = c;
found = 1;
break;
}
}
if (found == 0) {
c = PyCell_New(NULL);
if (c == 0)
goto fail;
SETLOCAL(co->co_nlocals + i, c);
}
}
}
#ifndef PYPY_VERSION
if (PyTuple_GET_SIZE(co->co_freevars)) {
int i;
for (i = 0; i < PyTuple_GET_SIZE(co->co_freevars); ++i) {
PyObject *o = PyTuple_GET_ITEM(closure, i);
Py_INCREF(o);
freevars[PyTuple_GET_SIZE(co->co_cellvars) + i] = o;
}
}
#endif
assert(!(co->co_flags & CO_GENERATOR));
c_func = ((Py2CCodeObject *)co)->co_function;
retval = c_func(f);
fail: /* Jump here from prelude on failure */
/* decref'ing the frame can cause __del__ methods to get invoked,
which can call back into Python. While we're done with the
current Python frame (f), the associated C stack is still in use,
so recursion_depth must be boosted for the duration.
*/
assert(tstate != NULL);
#ifndef PYPY_VERSION
++tstate->recursion_depth;
#endif
Py_DECREF(f);
#ifndef PYPY_VERSION
--tstate->recursion_depth;
#endif
return retval;
}
""")
if tuple(sys.version_info)[:2] == (2,7):
Libr('kwd_as_string',
"""static PyObject * kwd_as_string(PyObject *);""",
"""
static PyObject *
kwd_as_string(PyObject *kwd) {
#ifdef Py_USING_UNICODE
if (PyString_Check(kwd)) {
#else
assert(PyString_Check(kwd));
#endif
Py_INCREF(kwd);
return kwd;
#ifdef Py_USING_UNICODE
}
return _PyUnicode_AsDefaultEncodedString(kwd, "replace");
#endif
}
""")
else:
Libr('kwd_as_string',
"""
#define kwd_as_string(a) (a)
""",
"""
""")
Libr('ctype',
"""
#include <ctype.h>
""", """
""")
Libr('fastsearch', """
#define FAST_COUNT 0
#define FAST_SEARCH 1
#define FAST_RSEARCH 2
Py_ssize_t fastsearch(const char* s, Py_ssize_t n,
const char* p, Py_ssize_t m,
Py_ssize_t maxcount, int mode);""",
"""
/* Copy from stringlib CPython 2.7.3 */
/* fast search/count implementation, based on a mix between boyer-
moore and horspool, with a few more bells and whistles on the top.
for some more background, see: http://effbot.org/zone/stringlib.htm */
/* note: fastsearch may access s[n], which isn't a problem when using
Python's ordinary string types, but may cause problems if you're
using this code in other contexts. also, the count mode returns -1
if there cannot possible be a match in the target string, and 0 if
it has actually checked for matches, but didn't find any. callers
beware! */
#if LONG_BIT >= 128
#define STRINGLIB_BLOOM_WIDTH 128
#elif LONG_BIT >= 64
#define STRINGLIB_BLOOM_WIDTH 64
#elif LONG_BIT >= 32
#define STRINGLIB_BLOOM_WIDTH 32
#else
#error "LONG_BIT is smaller than 32"
#endif
#define STRINGLIB_BLOOM_ADD(mask, ch) \
((mask |= (1UL << ((ch) & (STRINGLIB_BLOOM_WIDTH -1)))))
#define STRINGLIB_BLOOM(mask, ch) \
((mask & (1UL << ((ch) & (STRINGLIB_BLOOM_WIDTH -1)))))
Py_ssize_t
fastsearch(const char* s, Py_ssize_t n,
const char* p, Py_ssize_t m,
Py_ssize_t maxcount, int mode)
{
unsigned long mask;
Py_ssize_t skip, count = 0;
Py_ssize_t i, j, mlast, w;
w = n - m;
if (w < 0 || (mode == FAST_COUNT && maxcount == 0))
return -1;
/* look for special cases */
if (m <= 1) {
if (m <= 0)
return -1;
/* use special case for 1-character strings */
if (mode == FAST_COUNT) {
for (i = 0; i < n; i++)
if (s[i] == p[0]) {
count++;
if (count == maxcount)
return maxcount;
}
return count;
} else if (mode == FAST_SEARCH) {
for (i = 0; i < n; i++)
if (s[i] == p[0])
return i;
} else { /* FAST_RSEARCH */
for (i = n - 1; i > -1; i--)
if (s[i] == p[0])
return i;
}
return -1;
}
mlast = m - 1;
skip = mlast - 1;
mask = 0;
if (mode != FAST_RSEARCH) {
/* create compressed boyer-moore delta 1 table */
/* process pattern[:-1] */
for (i = 0; i < mlast; i++) {
STRINGLIB_BLOOM_ADD(mask, p[i]);
if (p[i] == p[mlast])
skip = mlast - i - 1;
}
/* process pattern[-1] outside the loop */
STRINGLIB_BLOOM_ADD(mask, p[mlast]);
for (i = 0; i <= w; i++) {
/* note: using mlast in the skip path slows things down on x86 */
if (s[i+m-1] == p[m-1]) {
/* candidate match */
for (j = 0; j < mlast; j++)
if (s[i+j] != p[j])
break;
if (j == mlast) {
/* got a match! */
if (mode != FAST_COUNT)
return i;
count++;
if (count == maxcount)
return maxcount;
i = i + mlast;
continue;
}
/* miss: check if next character is part of pattern */
if (!STRINGLIB_BLOOM(mask, s[i+m]))
i = i + m;
else
i = i + skip;
} else {
/* skip: check if next character is part of pattern */
if (!STRINGLIB_BLOOM(mask, s[i+m]))
i = i + m;
}
}
} else { /* FAST_RSEARCH */
/* create compressed boyer-moore delta 1 table */
/* process pattern[0] outside the loop */
STRINGLIB_BLOOM_ADD(mask, p[0]);
/* process pattern[:0:-1] */
for (i = mlast; i > 0; i--) {
STRINGLIB_BLOOM_ADD(mask, p[i]);
if (p[i] == p[0])
skip = i - 1;
}
for (i = w; i >= 0; i--) {
if (s[i] == p[0]) {
/* candidate match */
for (j = mlast; j > 0; j--)
if (s[i+j] != p[j])
break;
if (j == 0)
/* got a match! */
return i;
/* miss: check if previous character is part of pattern */
if (i > 0 && !STRINGLIB_BLOOM(mask, s[i-1]))
i = i - m;
else
i = i - skip;
} else {
/* skip: check if previous character is part of pattern */
if (i > 0 && !STRINGLIB_BLOOM(mask, s[i-1]))
i = i - m;
}
}
}
if (mode != FAST_COUNT)
return -1;
return count;
}
""")
Libr('main', 'int main(int argc, char *argv[]);',
"""
int main(int argc, char *argv[])
{
Py_Initialize();
PySys_SetArgv(argc, argv);
init_main();
Py_Finalize();
return 0;
}
""")
Libr('from_ceval_2_7_special_lookup',
"""
static PyObject * from_ceval_2_7_enter = NULL;
static PyObject * from_ceval_2_7_exit = NULL;
static PyObject * from_ceval_2_7_special_lookup(PyObject *, char *, PyObject **);
""",
"""
static PyObject *
from_ceval_2_7_special_lookup(PyObject *o, char *meth, PyObject **cache)
{
PyObject *res;
if (PyInstance_Check(o)) {
if (!*cache)
return PyObject_GetAttrString(o, meth);
else
return PyObject_GetAttr(o, *cache);
}
res = _PyObject_LookupSpecial(o, meth, cache);
if (res == 0 && !PyErr_Occurred()) {
PyErr_SetObject(PyExc_AttributeError, *cache);
return NULL;
}
return res;
}
""")
Libr('Direct_AddTraceback',
"""
static void Direct_AddTraceback (PyCodeObject *, int, int);
""",
"""
static void Direct_AddTraceback (PyCodeObject * py_code, int lineno, int addr)
{
PyFrameObject *py_frame = 0;
py_frame = PyFrame_New (PyThreadState_GET (), /*PyThreadState *tstate, */
py_code, /*PyCodeObject *code, */
glob, /*PyObject *globals, */
0 /*PyObject *locals */
);
if (!py_frame)
goto bad;
/* printf("--- line %d\\n", lineno); */
py_frame->f_lineno = lineno;
#ifndef PYPY_VERSION
py_frame->f_lasti = addr;
#endif
PyTraceBack_Here (py_frame);
bad:
Py_XDECREF (py_frame);
}
""")
Libr('STR_CONCAT2',
"""
static PyObject * STR_CONCAT2( PyObject *, PyObject * );
""",
"""
static PyObject * STR_CONCAT2( PyObject *a, PyObject * b)
{
if (PyString_CheckExact(a) && PyString_CheckExact(b)) {
PyObject * r;
char buf[1024];
Py_ssize_t l_a, l_b, l_r;
l_a = PyString_GET_SIZE(a);
l_b = PyString_GET_SIZE(b);
if (l_b == 0) {
Py_INCREF(a);
return a;
}
if (l_a == 0) {
Py_INCREF(b);
return b;
}
if ((l_r = (l_a + l_b)) < 1024) {
Py_MEMCPY(buf, PyString_AS_STRING(a), l_a);
Py_MEMCPY(buf + l_a, PyString_AS_STRING(b), l_b);
r = PyString_FromStringAndSize(buf, l_r);
} else {
r = PyString_FromStringAndSize(PyString_AS_STRING(a), l_a);
PyString_Concat(&r, b);
}
return r;
} else {
return PyNumber_Add(a,b);
}
}
""")
Libr('STR_CONCAT3',
"""
static PyObject * STR_CONCAT3( PyObject *, PyObject *, PyObject *);
""",
"""
static PyObject * STR_CONCAT3( PyObject *a, PyObject * b, PyObject * c)
{
PyObject * r, *r1;
if (PyString_CheckExact(a) && PyString_CheckExact(b) && PyString_CheckExact(c)) {
char buf[1024];
Py_ssize_t l_a, l_b, l_c, l_r;
l_a = PyString_GET_SIZE(a);
l_b = PyString_GET_SIZE(b);
l_c = PyString_GET_SIZE(c);
if ((l_r = (l_a + l_b + l_c)) < 1024) {
Py_MEMCPY(buf, PyString_AS_STRING(a), l_a);
Py_MEMCPY(buf + l_a, PyString_AS_STRING(b), l_b);
Py_MEMCPY(buf + (l_a + l_b), PyString_AS_STRING(c), l_c);
r = PyString_FromStringAndSize(buf, l_r);
} else {
r = PyString_FromStringAndSize(PyString_AS_STRING(a), l_a);
PyString_Concat(&r, b);
PyString_Concat(&r, c);
}
return r;
} else {
r = PyNumber_Add(a,b);
r1 = PyNumber_Add(r,c);
Py_DECREF(r);
return r1;
}
}
""")
Libr('STR_CONCAT_N',
"""
static PyObject * STR_CONCAT_N( int, PyObject *, ...);
""",
"""
static PyObject * STR_CONCAT_N( int na, PyObject *a, ...)
{
typedef PyObject * pyref;
pyref args[64];
int len[64];
int i;
va_list vargs;
int strflag = 1;
Py_ssize_t l_r;
PyObject * r, *r1;
char * s;
assert(na>=2);
args[0] = a;
va_start(vargs, a);
for (i = 1; i < na; i++) {
args[i] = va_arg(vargs, PyObject *);
}
va_end(vargs);
strflag = 1;
l_r = 0;
for (i = 0; i < na; i ++) {
strflag = PyString_CheckExact(args[i]);
if (!strflag) break;
l_r += (len[i] = PyString_GET_SIZE(args[i]));
}
if (strflag) {
r = PyString_FromStringAndSize(NULL, l_r);
s = PyString_AS_STRING(r);
for (i = 0; i < na; i ++) {
Py_MEMCPY(s, PyString_AS_STRING(args[i]), len[i]);
s += len[i];
}
return r;
}
r = PyNumber_Add(args[0], args[1]);
for (i = 2; i < na; i ++) {
r1 = PyNumber_Add(r, args[i]);
Py_DECREF(r);
r = r1;
}
return r;
}
""")
Libr('from_ceval_call_exc_trace',
"""
static void
from_ceval_call_exc_trace(Py_tracefunc, PyObject *, PyFrameObject *);
""",
"""
static void
from_ceval_call_exc_trace(Py_tracefunc func, PyObject *self, PyFrameObject *f)
{
PyObject *type, *value, *traceback, *arg;
int err;
PyErr_Fetch(&type, &value, &traceback);
if (value == 0) {
value = Py_None;
Py_INCREF(value);
}
arg = PyTuple_Pack(3, type, value, traceback);
if (arg == 0) {
PyErr_Restore(type, value, traceback);
return;
}
err = from_ceval_call_trace(func, self, f, PyTrace_EXCEPTION, arg);
Py_DECREF(arg);
if (err == 0)
PyErr_Restore(type, value, traceback);
else {
Py_XDECREF(type);
Py_XDECREF(value);
Py_XDECREF(traceback);
}
}
""")
Libr('from_ceval_call_trace',
"""
static int
from_ceval_call_trace(Py_tracefunc , PyObject *, PyFrameObject *,
int , PyObject *);
""",
"""
static int
from_ceval_call_trace(Py_tracefunc func, PyObject *obj, PyFrameObject *frame,
int what, PyObject *arg)
{
register PyThreadState *tstate = frame->f_tstate;
int result;
if (tstate->tracing)
return 0;
tstate->tracing++;
tstate->use_tracing = 0;
result = func(obj, frame, what, arg);
tstate->use_tracing = ((tstate->c_tracefunc != NULL)
|| (tstate->c_profilefunc != NULL));
tstate->tracing--;
return result;
}
""")
Libr('from_ceval_BINARY_SUBSCR',
"""
static PyObject * from_ceval_BINARY_SUBSCR ( PyObject *, PyObject *);
""",
"""
static PyObject * from_ceval_BINARY_SUBSCR ( PyObject *v, PyObject *w)
{
PyObject * x = NULL;
/*# goto slow_get;*/
if (PyList_CheckExact(v) && PyInt_CheckExact(w)) {
/* INLINE: list[int] */
Py_ssize_t i = PyInt_AS_LONG(w);
if (i < 0)
i += PyList_GET_SIZE(v);
if (i >= 0 && i < PyList_GET_SIZE(v)) {
x = PyList_GET_ITEM(v, i);
Py_INCREF(x);
return x;
}
else
goto slow_get;
}
else if (PyTuple_CheckExact(v) && PyInt_CheckExact(w)) {
/* INLINE: list[int] */
Py_ssize_t i = PyInt_AS_LONG(w);
if (i < 0)
i += PyTuple_GET_SIZE(v);
if (i >= 0 && i < PyTuple_GET_SIZE(v)) {
x = PyTuple_GET_ITEM(v, i);
Py_INCREF(x);
return x;
}
else
goto slow_get;
}
slow_get:
x = PyObject_GetItem(v, w);
return x;
}
""")
Libr('c_LOAD_NAME',
"""
static PyObject * c_LOAD_NAME (PyFrameObject *, PyObject *);
""",
"""
static PyObject * c_LOAD_NAME (PyFrameObject *f, PyObject *w)
{
PyObject * v;
PyObject * x;
if ((v = f->f_locals) == 0) {
PyErr_Format(PyExc_SystemError,
"no locals when loading %s",
PyObject_REPR(w));
return NULL;
}
if (PyDict_CheckExact(v)) {
x = PyDict_GetItem(v, w);
Py_XINCREF(x);
}
else {
x = PyObject_GetItem(v, w);
if (x == 0 && PyErr_Occurred()) {
if (!PyErr_ExceptionMatches(
PyExc_KeyError))
return NULL;
PyErr_Clear();
}
}
if (x == 0) {
x = PyDict_GetItem(glob, w);
if (x == 0) {
x = PyDict_GetItem(bdict, w);
if (x == 0) {
char *obj_str;
obj_str = PyString_AsString(w);
if (obj_str)
PyErr_Format(PyExc_NameError, NAME_ERROR_MSG, obj_str);
return NULL;
}
}
Py_INCREF(x);
}
return x;
}
""")
if not is_pypy:
Libr('c_LOAD_GLOBAL',
"""
static PyObject * c_LOAD_GLOBAL ( PyObject *, long);
""",
"""
static PyObject * c_LOAD_GLOBAL ( PyObject *w, long hash)
{
PyObject * x;
/* Inline the PyDict_GetItem() calls.
WARNING: this is an extreme speed hack.
Do not try this at home. */
if (hash != -1) {
PyDictObject *d;
PyDictEntry *e;
d = (PyDictObject *)(glob);
e = d->ma_lookup(d, w, hash);
if (e == 0) {
x = NULL;
return NULL;
}
x = e->me_value;
if (x != NULL) {
Py_INCREF(x);
return x;
}
d = (PyDictObject *)(bdict);
e = d->ma_lookup(d, w, hash);
if (e == 0) {
x = NULL;
return NULL;
}
x = e->me_value;
if (x != NULL) {
Py_INCREF(x);
return x;
}
goto load_global_error;
}
/* This is the un-inlined version of the code above */
x = PyDict_GetItem(glob, w);
if (x == 0) {
x = PyDict_GetItem(b, w);
if (x == 0) {
load_global_error:
PyErr_Format(PyExc_NameError, GLOBAL_NAME_ERROR_MSG,
PyString_AsString(w));
return NULL;
}
}
Py_INCREF(x);
return x;
}
""")
else:
Libr('c_LOAD_GLOBAL',
"""
static PyObject * c_LOAD_GLOBAL ( PyObject *, long);
""",
"""
static PyObject * c_LOAD_GLOBAL ( PyObject *w, long hash)
{
PyObject * x;
/* This is the un-inlined version of the code above */
x = PyDict_GetItem(glob, w);
if (x == 0) {
x = PyDict_GetItem(b, w);
if (x == 0) {
PyErr_Format(PyExc_NameError, GLOBAL_NAME_ERROR_MSG,
PyString_AsString(w));
return NULL;
}
}
Py_INCREF(x);
return x;
}
""")
Libr('c_BINARY_SUBSCR_SUBSCR_Int_Int',
"""
static PyObject * c_BINARY_SUBSCR_SUBSCR_Int_Int(PyObject *, int, PyObject *, int, PyObject *);
""",
"""
static PyObject * c_BINARY_SUBSCR_SUBSCR_Int_Int(PyObject *v, Py_ssize_t i1,
PyObject *const_i1, Py_ssize_t i2, PyObject * const_i2)
{
PyObject * x = NULL;
PyObject * x0 = NULL;
if (PyList_CheckExact(v)) {
Py_ssize_t l = PyList_GET_SIZE(v);
/* INLINE: list[int] */
if (i1 < 0)
i1 += l;
if (i1 >= 0 && i1 < l) {
x = PyList_GET_ITEM(v, i1);
Py_INCREF(x);
goto next;
}
else
goto slow_get;
}
else if (PyTuple_CheckExact(v)) {
Py_ssize_t l = PyTuple_GET_SIZE(v);
/* INLINE: list[int] */
if (i1 < 0)
i1 += l;
if (i1 >= 0 && i1 < l) {
x = PyTuple_GET_ITEM(v, i1);
Py_INCREF(x);
goto next;
}
else
goto slow_get;
}
else
slow_get:
x = PyObject_GetItem(v, const_i1);
next:
x0 = x;
v = x;
if (v == 0) return v;
if (PyList_CheckExact(v)) {
Py_ssize_t l = PyList_GET_SIZE(v);
/* INLINE: list[int] */
if (i2 < 0)
i2 += l;
if (i2 >= 0 && i2 < l) {
x = PyList_GET_ITEM(v, i2);
Py_INCREF(x);
Py_DECREF(x0);
return x;
}
else
goto slow_get2;
}
else if (PyTuple_CheckExact(v)) {
Py_ssize_t l = PyTuple_GET_SIZE(v);
/* INLINE: list[int] */
if (i2 < 0)
i2 += l;
if (i2 >= 0 && i2 < l) {
x = PyTuple_GET_ITEM(v, i2);
Py_INCREF(x);
Py_DECREF(x0);
return x;
}
else
goto slow_get2;
}
else
slow_get2:
x = PyObject_GetItem(v, const_i2);
Py_DECREF(x0);
return x;
}
""")
Libr('__c_BINARY_SUBSCR_Int',
"""
static PyObject * __c_BINARY_SUBSCR_Int(PyObject *, Py_ssize_t);
""",
"""
static PyObject * __c_BINARY_SUBSCR_Int(PyObject *v, Py_ssize_t i1)
{
PyObject *const_i1 = NULL;
PyObject * x = NULL;
if (PyList_CheckExact(v)) {
Py_ssize_t l;
/* INLINE: list[int] */
l = PyList_GET_SIZE(v);
if (i1 < 0)
i1 += l;
if (i1 >= 0 && i1 < l) {
x = PyList_GET_ITEM(v, i1);
Py_INCREF(x);
return x;
}
else
goto slow_get;
}
else if (PyTuple_CheckExact(v)) {
Py_ssize_t l;
/* INLINE: list[int] */
l = PyTuple_GET_SIZE(v);
if (i1 < 0)
i1 += l;
if (i1 >= 0 && i1 < l) {
x = PyTuple_GET_ITEM(v, i1);
Py_INCREF(x);
return x;
}
else
goto slow_get;
}
else
slow_get:
const_i1 = PyInt_FromLong (i1);
x = PyObject_GetItem(v, const_i1);
Py_CLEAR(const_i1);
return x;
}
""")
Libr('_c_BINARY_SUBSCR_Int',
"""
static PyObject * _c_BINARY_SUBSCR_Int(PyObject *, Py_ssize_t, PyObject *);
""",
"""
static PyObject * _c_BINARY_SUBSCR_Int(PyObject *v, Py_ssize_t i1, PyObject *const_i1)
{
PyObject * x = NULL;
if (PyList_CheckExact(v)) {
Py_ssize_t l;
/* INLINE: list[int] */
l = PyList_GET_SIZE(v);
if (i1 < 0)
i1 += l;
if (i1 >= 0 && i1 < l) {
x = PyList_GET_ITEM(v, i1);
Py_INCREF(x);
return x;
}
else
goto slow_get;
}
else if (PyTuple_CheckExact(v)) {
Py_ssize_t l;
/* INLINE: list[int] */
l = PyTuple_GET_SIZE(v);
if (i1 < 0)
i1 += l;
if (i1 >= 0 && i1 < l) {
x = PyTuple_GET_ITEM(v, i1);
Py_INCREF(x);
return x;
}
else
goto slow_get;
}
else
slow_get:
x = PyObject_GetItem(v, const_i1);
return x;
}
""")
Libr('___c_BINARY_SUBSCR_Int',
"""
static PyObject * ___c_BINARY_SUBSCR_Int(PyObject *, Py_ssize_t);
""",
"""
static PyObject * ___c_BINARY_SUBSCR_Int(PyObject *v, Py_ssize_t i1)
{
PyObject *const_i1 = NULL;
PyObject * x = NULL;
if (PyList_CheckExact(v)) {
Py_ssize_t l;
/* INLINE: list[int] */
l = PyList_GET_SIZE(v);
if (i1 < 0)
i1 += l;
if (i1 >= 0 && i1 < l) {
x = PyList_GET_ITEM(v, i1);
Py_INCREF(x);
return x;
}
else
goto slow_get;
}
else if (PyTuple_CheckExact(v)) {
Py_ssize_t l;
/* INLINE: list[int] */
l = PyTuple_GET_SIZE(v);
if (i1 < 0)
i1 += l;
if (i1 >= 0 && i1 < l) {
x = PyTuple_GET_ITEM(v, i1);
Py_INCREF(x);
return x;
}
else
goto slow_get;
}
else
slow_get:
const_i1 = PyInt_FromLong (i1);
Py_INCREF(v);
x = PyObject_GetItem(v, const_i1);
Py_DECREF(v);
Py_DECREF(const_i1);
return x;
}
""")
Libr('Py2CFunction_New',
"""
static PyObject * Py2CFunction_New(PyObject *);
""",
"""
static PyObject * Py2CFunction_New(PyObject *code)
{
PyFunctionObject *op = PyObject_GC_New(PyFunctionObject,
&Py2CFunction_Type);
static PyObject *__name__ = 0;
if (op != NULL) {
PyObject *doc;
PyObject *consts;
PyObject *module;
op->func_weakreflist = NULL;
Py_INCREF(code);
op->func_code = code;
Py_INCREF(glob);
op->func_globals = glob;
op->func_name = ((PyCodeObject *)code)->co_name;
Py_INCREF(op->func_name);
op->func_defaults = NULL; /* No default arguments */
op->func_closure = NULL;
consts = ((PyCodeObject *)code)->co_consts;
if (PyTuple_Size(consts) >= 1) {
doc = PyTuple_GetItem(consts, 0);
if (!PyString_Check(doc) && !PyUnicode_Check(doc))
doc = Py_None;
}
else
doc = Py_None;
Py_INCREF(doc);
op->func_doc = doc;
op->func_dict = NULL;
op->func_module = NULL;
/* __module__: If module name is in globals, use it.
Otherwise, use None.
*/
if (!__name__) {
__name__ = PyString_InternFromString("__name__");
if (!__name__) {
Py_DECREF(op);
return NULL;
}
}
module = PyDict_GetItem(glob, __name__);
if (module) {
Py_INCREF(module);
op->func_module = module;
}
}
else
return NULL;
PyObject_GC_Track(op);
return (PyObject *)op;
}
""")
Libr('Py2CFunction_New_Simple',
"""
static PyObject * Py2CFunction_New_Simple(PyObject *, PyTypeObject *);
""",
"""
static PyObject * Py2CFunction_New_Simple(PyObject *code, PyTypeObject * ty)
{
PyFunctionObject *op = PyObject_GC_New(PyFunctionObject,
ty);
static PyObject *__name__ = 0;
if (op != NULL) {
PyObject *doc;
PyObject *consts;
PyObject *module;
op->func_weakreflist = NULL;
Py_INCREF(code);
op->func_code = code;
Py_INCREF(glob);
op->func_globals = glob;
op->func_name = ((PyCodeObject *)code)->co_name;
Py_INCREF(op->func_name);
op->func_defaults = NULL; /* No default arguments */
op->func_closure = NULL;
consts = ((PyCodeObject *)code)->co_consts;
if (PyTuple_Size(consts) >= 1) {
doc = PyTuple_GetItem(consts, 0);
if (!PyString_Check(doc) && !PyUnicode_Check(doc))
doc = Py_None;
}
else
doc = Py_None;
Py_INCREF(doc);
op->func_doc = doc;
op->func_dict = NULL;
op->func_module = NULL;
/* __module__: If module name is in globals, use it.
Otherwise, use None.
*/
if (!__name__) {
__name__ = PyString_InternFromString("__name__");
if (!__name__) {
Py_DECREF(op);
return NULL;
}
}
module = PyDict_GetItem(glob, __name__);
if (module) {
Py_INCREF(module);
op->func_module = module;
}
}
else
return NULL;
PyObject_GC_Track(op);
return (PyObject *)op;
}
""")
Libr('Py2CFunction_SetClosure',
"""
static int
Py2CFunction_SetClosure(PyObject *, PyObject *);
""",
"""
static int
Py2CFunction_SetClosure(PyObject *op, PyObject *closure)
{
if (closure == Py_None)
closure = NULL;
else if (PyTuple_Check(closure)) {
Py_INCREF(closure);
}
else {
PyErr_Format(PyExc_SystemError,
"expected tuple for closure, got '%.100s'",
closure->ob_type->tp_name);
return -1;
}
Py_XDECREF(((PyFunctionObject *) op) -> func_closure);
((PyFunctionObject *) op) -> func_closure = closure;
return 0;
}
""")
Libr('Py2CFunction_SetDefaults',
"""
static int
Py2CFunction_SetDefaults(PyObject *o, PyObject *);
""",
"""
static int
Py2CFunction_SetDefaults(PyObject *op, PyObject *defaults)
{
if (defaults == Py_None)
defaults = NULL;
else if (defaults && PyTuple_Check(defaults)) {
Py_INCREF(defaults);
}
else {
PyErr_SetString(PyExc_SystemError, "non-tuple default args");
return -1;
}
Py_XDECREF(((PyFunctionObject *) op) -> func_defaults);
((PyFunctionObject *) op) -> func_defaults = defaults;
return 0;
}
""")
Libr('_PyEval_PRINT_ITEM_1',
"""
static int _PyEval_PRINT_ITEM_1 ( PyObject * );
""",
"""
static int _PyEval_PRINT_ITEM_1 ( PyObject * v)
{
return _PyEval_PRINT_ITEM_TO_2 ( NULL, v );
}
""")
Libr('_PyEval_PRINT_ITEM_TO_2',
"""
static int _PyEval_PRINT_ITEM_TO_2 ( PyObject * , PyObject *);
""",
"""
static int _PyEval_PRINT_ITEM_TO_2 ( PyObject * stream, PyObject * v)
{
PyObject * w = stream;
int err = 0;
if (stream == 0 || stream == Py_None) {
w = PySys_GetObject("stdout");
if (w == 0) {
PyErr_SetString(PyExc_RuntimeError,
"lost sys.stdout");
err = -1;
}
}
/* PyFile_SoftSpace() can exececute arbitrary code
if sys.stdout is an instance with a __getattr__.
If __getattr__ raises an exception, w will
be freed, so we need to prevent that temporarily. */
Py_XINCREF(w);
if (w != NULL && PyFile_SoftSpace(w, 0))
err = PyFile_WriteString(" ", w);
if (err == 0)
err = PyFile_WriteObject(v, w, Py_PRINT_RAW);
if (err == 0) {
/* XXX move into writeobject() ? */
if (PyString_Check(v)) {
char *s = PyString_AS_STRING(v);
Py_ssize_t len = PyString_GET_SIZE(v);
if (len == 0 ||
!isspace(Py_CHARMASK(s[len-1])) ||
s[len-1] == ' ')
PyFile_SoftSpace(w, 1);
}
#ifdef Py_USING_UNICODE
else if (PyUnicode_Check(v)) {
Py_UNICODE *s = PyUnicode_AS_UNICODE(v);
Py_ssize_t len = PyUnicode_GET_SIZE(v);
if (len == 0 ||
!Py_UNICODE_ISSPACE(s[len-1]) ||
s[len-1] == ' ')
PyFile_SoftSpace(w, 1);
}
#endif
else
PyFile_SoftSpace(w, 1);
}
Py_XDECREF(w);
/* Py_DECREF(v); */
if (w != stream) {
Py_XDECREF(stream);
}
stream = NULL;
return err;
}
""")
Libr('_PyEval_PRINT_NEWLINE_TO_1',
"""
static int _PyEval_PRINT_NEWLINE_TO_1 ( PyObject * );
""",
"""
static int _PyEval_PRINT_NEWLINE_TO_1 ( PyObject * stream )
{
PyObject * w = stream;
int err = 0;
if (stream == 0 || stream == Py_None) {
w = PySys_GetObject("stdout");
if (w == 0) {
PyErr_SetString(PyExc_RuntimeError,
"lost sys.stdout");
return -1;
}
}
if (w != NULL) {
/* w.write() may replace sys.stdout, so we
* have to keep our reference to it */
Py_INCREF(w);
err = PyFile_WriteString("\\n", w);
if (err == 0)
PyFile_SoftSpace(w, 0);
Py_DECREF(w);
}
if (w != stream) {
Py_XDECREF(stream);
}
stream = NULL;
return err;
}
""")
Libr('_PyEval_set_exc_info',
"""
static void
_PyEval_set_exc_info(PyThreadState *tstate,
PyObject *type, PyObject *value, PyObject *tb);
""",
"""
static void
_PyEval_set_exc_info(PyThreadState *tstate,
PyObject *type, PyObject *value, PyObject *tb)
{
PyFrameObject *frame = tstate->frame;
PyObject *tmp_type, *tmp_value, *tmp_tb;
assert(type != NULL);
assert(frame != NULL);
if (frame->f_exc_type == 0) {
assert(frame->f_exc_value == 0);
assert(frame->f_exc_traceback == 0);
/* This frame didn't catch an exception before. */
/* Save previous exception of this thread in this frame. */
if (tstate->exc_type == 0) {
/* XXX Why is this set to Py_None? */
Py_INCREF(Py_None);
tstate->exc_type = Py_None;
}
Py_INCREF(tstate->exc_type);
Py_XINCREF(tstate->exc_value);
Py_XINCREF(tstate->exc_traceback);
frame->f_exc_type = tstate->exc_type;
frame->f_exc_value = tstate->exc_value;
frame->f_exc_traceback = tstate->exc_traceback;
}
/* Set new exception for this thread. */
tmp_type = tstate->exc_type;
tmp_value = tstate->exc_value;
tmp_tb = tstate->exc_traceback;
Py_INCREF(type);
Py_XINCREF(value);
Py_XINCREF(tb);
tstate->exc_type = type;
tstate->exc_value = value;
tstate->exc_traceback = tb;
Py_XDECREF(tmp_type);
Py_XDECREF(tmp_value);
Py_XDECREF(tmp_tb);
/* For b/w compatibility */
PySys_SetObject("exc_type", type);
PySys_SetObject("exc_value", value);
PySys_SetObject("exc_traceback", tb);
}
""")
if not is_pypy:
Libr('_PyEval_reset_exc_info',
"""
static void _PyEval_reset_exc_info(PyThreadState *);
""",
"""
static void
_PyEval_reset_exc_info(PyThreadState *tstate)
{
PyFrameObject *frame;
PyObject *tmp_type, *tmp_value, *tmp_tb;
/* It's a precondition that the thread state's frame caught an
* exception -- verify in a debug build.
*/
assert(tstate != NULL);
frame = tstate->frame;
assert(frame != NULL);
assert(frame->f_exc_type != NULL);
/* Copy the frame's exception info back to the thread state. */
tmp_type = tstate->exc_type;
tmp_value = tstate->exc_value;
tmp_tb = tstate->exc_traceback;
Py_INCREF(frame->f_exc_type);
Py_XINCREF(frame->f_exc_value);
Py_XINCREF(frame->f_exc_traceback);
tstate->exc_type = frame->f_exc_type;
tstate->exc_value = frame->f_exc_value;
tstate->exc_traceback = frame->f_exc_traceback;
Py_XDECREF(tmp_type);
Py_XDECREF(tmp_value);
Py_XDECREF(tmp_tb);
/* For b/w compatibility */
PySys_SetObject("exc_type", frame->f_exc_type);
PySys_SetObject("exc_value", frame->f_exc_value);
PySys_SetObject("exc_traceback", frame->f_exc_traceback);
/* Clear the frame's exception info. */
tmp_type = frame->f_exc_type;
tmp_value = frame->f_exc_value;
tmp_tb = frame->f_exc_traceback;
frame->f_exc_type = NULL;
frame->f_exc_value = NULL;
frame->f_exc_traceback = NULL;
Py_DECREF(tmp_type);
Py_XDECREF(tmp_value);
Py_XDECREF(tmp_tb);
}
""")
else:
Libr('_PyEval_reset_exc_info',
"""
static void _PyEval_reset_exc_info(PyThreadState *);
""",
"""
static void
_PyEval_reset_exc_info(PyThreadState *tstate)
{
/* It's a precondition that the thread state's frame caught an
* exception -- verify in a debug build.
*/
assert(tstate != NULL);
/* For b/w compatibility */
PySys_SetObject("exc_type", tstate->exc_type);
PySys_SetObject("exc_value", tstate->exc_value);
PySys_SetObject("exc_traceback", tstate->exc_traceback);
}
""")
Libr('_PyEval_ApplySlice',
"""
static PyObject *
_PyEval_ApplySlice(PyObject *, PyObject *, PyObject *);
""",
"""
static PyObject *
_PyEval_ApplySlice(PyObject *u, PyObject *v, PyObject *w) /* return u[v:w] */
{
PyTypeObject *tp = u->ob_type;
PySequenceMethods *sq = tp->tp_as_sequence;
if (sq && sq->sq_slice && ISINDEX(v) && ISINDEX(w)) {
Py_ssize_t ilow = 0, ihigh = PY_SSIZE_T_MAX;
if (!_PyEval_SliceIndex(v, &ilow))
return NULL;
if (!_PyEval_SliceIndex(w, &ihigh))
return NULL;
return PySequence_GetSlice(u, ilow, ihigh);
}
else {
PyObject *slice = PySlice_New(v, w, NULL);
if (slice != NULL) {
PyObject *res = PyObject_GetItem(u, slice);
Py_DECREF(slice);
return res;
}
else
return NULL;
}
}
""")
Libr('_PyEval_AssignSlice',
"""
static int
_PyEval_AssignSlice(PyObject *, PyObject *, PyObject *, PyObject *);
""",
"""
static int
_PyEval_AssignSlice(PyObject *u, PyObject *v, PyObject *w, PyObject *x)
/* u[v:w] = x */
{
PyTypeObject *tp = u->ob_type;
PySequenceMethods *sq = tp->tp_as_sequence;
if (sq && sq->sq_ass_slice && ISINDEX(v) && ISINDEX(w)) {
Py_ssize_t ilow = 0, ihigh = PY_SSIZE_T_MAX;
if (!_PyEval_SliceIndex(v, &ilow))
return -1;
if (!_PyEval_SliceIndex(w, &ihigh))
return -1;
if (x == 0)
return PySequence_DelSlice(u, ilow, ihigh);
else
return PySequence_SetSlice(u, ilow, ihigh, x);
}
else {
PyObject *slice = PySlice_New(v, w, NULL);
if (slice != NULL) {
int res;
if (x != NULL)
res = PyObject_SetItem(u, slice, x);
else
res = PyObject_DelItem(u, slice);
Py_DECREF(slice);
return res;
}
else
return -1;
}
}
""")
Libr('_Call_CompiledWithFrame',
"""
static PyObject * _Call_CompiledWithFrame(void *, PyObject *, int, ...);
""",
"""
static PyObject * _Call_CompiledWithFrame(void * func, PyObject *_co, int cnt_arg, ...)
{
PyCodeObject *co = (PyCodeObject *)_co;
PyFrameObject *f;
PyObject *retval = NULL;
PyThreadState *tstate = PyThreadState_GET();
PyObject **fastlocals;
PyObject *o;
int i;
PyObject *(*c_func)(PyFrameObject *);
va_list vargs;
va_start(vargs, cnt_arg);
/* XXX Perhaps we should create a specialized
PyFrame_New() that doesn't take locals, but does
take builtins without sanity checking them.
*/
assert(tstate != NULL);
f = PyFrame_New(tstate, co, glob, NULL);
if (f == 0)
return NULL;
fastlocals = f->f_localsplus;
for (i = 0; i < cnt_arg; i++) {
o = va_arg(vargs, PyObject *);
Py_INCREF(o);
fastlocals[i] = o;
}
va_end(vargs);
c_func = func;
retval = c_func(f);
#ifndef PYPY_VERSION
++tstate->recursion_depth;
#endif
Py_DECREF(f);
#ifndef PYPY_VERSION
--tstate->recursion_depth;
#endif
return retval;
}
""")
Libr('FastCall',
"""
static PyObject * FastCall(int, PyObject *, ...);
""",
"""
static PyObject * FastCall(int na, PyObject *v,...)
{
typedef PyObject * pyref;
pyref args[18];
pyref * r_arg;
PyObject *func;
int i;
va_list vargs;
// r_arg = args+1;
// printf ("=fastcall\\n");
func = v;
Py_INCREF(func);
va_start(vargs, v);
args[0] = NULL;
for (i = 0; i < na; i++)
args[i+1] = va_arg(vargs, PyObject *);
va_end(vargs);
r_arg = args+1;
if (PyCFunction_Check(func)) {
int flags = PyCFunction_GET_FLAGS(func);
PyObject *x;
// printf ("=cfunc 1\\n");
if (flags & (METH_NOARGS | METH_O)) {
PyCFunction meth = PyCFunction_GET_FUNCTION(func);
PyObject *self = PyCFunction_GET_SELF(func);
if (flags & METH_NOARGS && na == 0) {
x = (*meth)(self,NULL);
Py_DECREF(func);
return x;
}
else if (flags & METH_O && na == 1) {
Py_INCREF(args[1]);
x = (*meth)(self,args[1]);
Py_DECREF(args[1]);
Py_DECREF(func);
return x;
} else
goto stand_c;
}
else { stand_c:
{
PyObject *callargs = PyTuple_New(na);
for (i = 0; i < na; i++) {
Py_INCREF(args[i+1]);
PyTuple_SET_ITEM(callargs, i, args[i+1]);
}
x = PyCFunction_Call(func,callargs,NULL);
Py_XDECREF(callargs);
Py_DECREF(func);
return x;
}
}
}
if (PyMethod_Check(func) && PyMethod_GET_SELF(func) != NULL) {
PyObject *oldfunc = func;
args[0] = PyMethod_GET_SELF(func);
func = PyMethod_GET_FUNCTION(func);
Py_INCREF(func);
Py_DECREF(oldfunc);
na++;
// printf ("=meth 1\\n");
r_arg = args;
} // else {
// Py_INCREF(func);
//}
if (Py2CFunction_Check(func)) {
Py2CCodeObject *co = (Py2CCodeObject *)PyFunction_GET_CODE(func);
PyObject *globals = PyFunction_GET_GLOBALS(func);
PyObject *argdefs = PyFunction_GET_DEFAULTS(func);
PyObject **d = NULL;
PyObject *(*c_func)(PyFrameObject *);
int nd = 0;
// printf ("=2Cfunc 1\\n");
if (argdefs == 0 && co->_body.co_argcount == na &&
co->_body.co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) {
PyFrameObject *f;
PyObject *retval = NULL;
PyThreadState *tstate = PyThreadState_GET();
PyObject **fastlocals;
int i;
assert(globals != NULL);
assert(tstate != NULL);
f = PyFrame_New(tstate, (PyCodeObject *)co, globals, NULL);
if (f == 0) {
return NULL;
}
fastlocals = f->f_localsplus;
for (i = 0; i < na; i++) {
Py_INCREF(r_arg[i]);
fastlocals[i] = r_arg[i];
}
c_func = co->co_function;
retval = c_func(f);
#ifndef PYPY_VERSION
++tstate->recursion_depth;
#endif
Py_DECREF(f);
#ifndef PYPY_VERSION
--tstate->recursion_depth;
#endif
Py_DECREF(func);
return retval;
}
if (argdefs != NULL) {
d = &PyTuple_GET_ITEM(argdefs, 0);
nd = Py_SIZE(argdefs);
}
Py_DECREF(func);
return PyEval_Eval2CCodeEx((PyCodeObject *)co,
(PyObject *)NULL, r_arg, na,
NULL, 0, d, nd
#ifndef PYPY_VERSION
,
PyFunction_GET_CLOSURE(func));
#else
);
#endif
}
else if (PyFunction_Check(func)) {
PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func);
PyObject *globals = PyFunction_GET_GLOBALS(func);
PyObject *argdefs = PyFunction_GET_DEFAULTS(func);
PyObject **d = NULL;
int nd = 0;
// printf ("=Func 1\\n");
if (argdefs == 0 && co->co_argcount == na &&
co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) {
PyFrameObject *f;
PyObject *retval = NULL;
PyThreadState *tstate = PyThreadState_GET();
PyObject **fastlocals;
int i;
assert(globals != NULL);
assert(tstate != NULL);
f = PyFrame_New(tstate, (PyCodeObject *)co, globals, NULL);
if (f == 0)
return NULL;
fastlocals = f->f_localsplus;
for (i = 0; i < na; i++) {
Py_INCREF(r_arg[i]);
fastlocals[i] = r_arg[i];
}
retval = PyEval_EvalFrameEx(f,0);
#ifndef PYPY_VERSION
++tstate->recursion_depth;
#endif
Py_DECREF(f);
#ifndef PYPY_VERSION
--tstate->recursion_depth;
#endif
Py_DECREF(func);
return retval;
}
if (argdefs != NULL) {
d = &PyTuple_GET_ITEM(argdefs, 0);
nd = Py_SIZE(argdefs);
}
Py_DECREF(func);
return PyEval_EvalCodeEx(co, globals,
(PyObject *)NULL, r_arg, na,
NULL, 0, d, nd,
PyFunction_GET_CLOSURE(func));
} else {
// printf ("=others 1\\n");
PyObject *callargs = PyTuple_New(na);
PyObject *x;
for (i = 0; i < na; i++) {
Py_INCREF(r_arg[i]);
PyTuple_SET_ITEM(callargs, i, r_arg[i]);
}
x = PyObject_Call(func,callargs,NULL);
Py_XDECREF(callargs);
Py_DECREF(func);
return x;
}
}
""")
if not is_pypy:
Libr('FastCall0',
"""
static PyObject * FastCall0(PyObject *);
""",
"""
static PyObject * FastCall0(PyObject *v)
{
typedef PyObject * pyref;
PyObject *func;
PyObject *self = NULL;
func = v;
Py_INCREF(func);
if (PyCFunction_Check(func)) {
int flags = PyCFunction_GET_FLAGS(func);
PyObject *self = PyCFunction_GET_SELF(func);
PyObject *x;
if (flags & METH_NOARGS) {
PyCFunction meth = PyCFunction_GET_FUNCTION(func);
x = (*meth)(self,NULL);
}
else {
Py_INCREF(empty_tuple);
x = PyCFunction_Call(func,empty_tuple,NULL);
Py_DECREF(empty_tuple);
}
Py_DECREF(func);
return x;
}
if (PyMethod_Check(func) && PyMethod_GET_SELF(func) != NULL) {
PyObject *oldfunc = func;
self = PyMethod_GET_SELF(func);
func = PyMethod_GET_FUNCTION(func);
Py_INCREF(func);
Py_DECREF(oldfunc);
if (Py2CFunction_Check(func)) {
Py2CCodeObject *co = (Py2CCodeObject *)PyFunction_GET_CODE(func);
PyObject *globals = PyFunction_GET_GLOBALS(func);
PyObject *argdefs = PyFunction_GET_DEFAULTS(func);
PyObject **d = NULL;
PyObject *(*c_func)(PyFrameObject *);
int nd = 0;
if (argdefs == 0 && co->_body.co_argcount == 1 &&
co->_body.co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) {
PyFrameObject *f;
PyObject *retval = NULL;
PyThreadState *tstate = PyThreadState_GET();
PyObject **fastlocals;
assert(globals != NULL);
assert(tstate != NULL);
f = PyFrame_New(tstate, (PyCodeObject *)co, globals, NULL);
if (f == 0) {
return NULL;
}
fastlocals = f->f_localsplus;
Py_INCREF(self);
fastlocals[0] = self;
c_func = co->co_function;
retval = c_func(f);
++tstate->recursion_depth;
Py_DECREF(f);
--tstate->recursion_depth;
Py_DECREF(func);
return retval;
}
if (argdefs != NULL) {
d = &PyTuple_GET_ITEM(argdefs, 0);
nd = Py_SIZE(argdefs);
}
Py_DECREF(func);
return PyEval_Eval2CCodeEx((PyCodeObject *)co,
(PyObject *)NULL, &self, 1,
NULL, 0, d, nd
#ifndef PYPY_VERSION
,
PyFunction_GET_CLOSURE(func));
#else
);
#endif
}
else if (PyFunction_Check(func)) {
PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func);
PyObject *globals = PyFunction_GET_GLOBALS(func);
PyObject *argdefs = PyFunction_GET_DEFAULTS(func);
PyObject **d = NULL;
int nd = 0;
if (argdefs == 0 && co->co_argcount == 1 &&
co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) {
PyFrameObject *f;
PyObject *retval = NULL;
PyThreadState *tstate = PyThreadState_GET();
PyObject **fastlocals;
assert(globals != NULL);
assert(tstate != NULL);
f = PyFrame_New(tstate, (PyCodeObject *)co, globals, NULL);
if (f == 0)
return NULL;
fastlocals = f->f_localsplus;
Py_INCREF(self);
fastlocals[0] = self;
retval = PyEval_EvalFrameEx(f,0);
++tstate->recursion_depth;
Py_DECREF(f);
--tstate->recursion_depth;
Py_DECREF(func);
return retval;
}
if (argdefs != NULL) {
d = &PyTuple_GET_ITEM(argdefs, 0);
nd = Py_SIZE(argdefs);
}
Py_DECREF(func);
return PyEval_EvalCodeEx(co, globals,
(PyObject *)NULL, &self, 1,
NULL, 0, d, nd,
PyFunction_GET_CLOSURE(func));
} else {
PyObject *callargs = PyTuple_Pack(1, self);
PyObject *x;
x = PyObject_Call(func,callargs,NULL);
Py_XDECREF(callargs);
Py_DECREF(func);
return x;
}
} else {
if (Py2CFunction_Check(func)) {
Py2CCodeObject *co = (Py2CCodeObject *)PyFunction_GET_CODE(func);
PyObject *globals = PyFunction_GET_GLOBALS(func);
PyObject *argdefs = PyFunction_GET_DEFAULTS(func);
PyObject **d = NULL;
PyObject *(*c_func)(PyFrameObject *);
int nd = 0;
if (argdefs == 0 && co->_body.co_argcount == 0 &&
co->_body.co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) {
PyFrameObject *f;
PyObject *retval = NULL;
PyThreadState *tstate = PyThreadState_GET();
assert(globals != NULL);
assert(tstate != NULL);
f = PyFrame_New(tstate, (PyCodeObject *)co, globals, NULL);
if (f == 0) {
return NULL;
}
c_func = co->co_function;
retval = c_func(f);
++tstate->recursion_depth;
Py_DECREF(f);
--tstate->recursion_depth;
Py_DECREF(func);
return retval;
}
if (argdefs != NULL) {
d = &PyTuple_GET_ITEM(argdefs, 0);
nd = Py_SIZE(argdefs);
}
Py_DECREF(func);
return PyEval_Eval2CCodeEx((PyCodeObject *)co,
(PyObject *)NULL, NULL, 0,
NULL, 0, d, nd
#ifndef PYPY_VERSION
,
PyFunction_GET_CLOSURE(func));
#else
);
#endif
}
else if (PyFunction_Check(func)) {
PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func);
PyObject *globals = PyFunction_GET_GLOBALS(func);
PyObject *argdefs = PyFunction_GET_DEFAULTS(func);
PyObject **d = NULL;
int nd = 0;
if (argdefs == 0 && co->co_argcount == 0 &&
co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) {
PyFrameObject *f;
PyObject *retval = NULL;
PyThreadState *tstate = PyThreadState_GET();
assert(globals != NULL);
assert(tstate != NULL);
f = PyFrame_New(tstate, (PyCodeObject *)co, globals, NULL);
if (f == 0)
return NULL;
retval = PyEval_EvalFrameEx(f,0);
++tstate->recursion_depth;
Py_DECREF(f);
--tstate->recursion_depth;
Py_DECREF(func);
return retval;
}
if (argdefs != NULL) {
d = &PyTuple_GET_ITEM(argdefs, 0);
nd = Py_SIZE(argdefs);
}
Py_DECREF(func);
return PyEval_EvalCodeEx(co, globals,
(PyObject *)NULL, NULL, 0,
NULL, 0, d, nd,
PyFunction_GET_CLOSURE(func));
} else {
PyObject *x;
x = PyObject_Call(func,empty_tuple,NULL);
Py_DECREF(func);
return x;
}
}
}
""")
else:
Libr('FastCall0',
"""
#define FastCall0(v) PyObject_Call(v,empty_tuple,NULL)
""",
"""
""")
Libr('_PyEval_DoRaise',
"""
static int
_PyEval_DoRaise(PyObject *, PyObject *, PyObject *);
""",
"""
static int
_PyEval_DoRaise(PyObject *type, PyObject *value, PyObject *tb)
{
if (type == 0) {
/* Reraise */
PyThreadState *tstate = PyThreadState_GET();
type = tstate->exc_type == 0 ? Py_None : tstate->exc_type;
value = tstate->exc_value;
tb = tstate->exc_traceback;
Py_XINCREF(type);
Py_XINCREF(value);
Py_XINCREF(tb);
}
/* We support the following forms of raise:
raise <class>, <classinstance>
raise <class>, <argument tuple>
raise <class>, None
raise <class>, <argument>
raise <classinstance>, None
raise <string>, <object>
raise <string>, None
An omitted second argument is the same as None.
In addition, raise <tuple>, <anything> is the same as
raising the tuple's first item (and it better have one!);
this rule is applied recursively.
Finally, an optional third argument can be supplied, which
gives the traceback to be substituted (useful when
re-raising an exception after examining it). */
/* First, check the traceback argument, replacing None with
NULL. */
if (tb == Py_None) {
Py_DECREF(tb);
tb = NULL;
}
else if (tb != NULL && !PyTraceBack_Check(tb)) {
PyErr_SetString(PyExc_TypeError,
"raise: arg 3 must be a traceback or None");
goto raise_error;
}
/* Next, replace a missing value with None */
if (value == 0) {
value = Py_None;
Py_INCREF(value);
}
/* Next, repeatedly, replace a tuple exception with its first item */
while (PyTuple_Check(type) && PyTuple_Size(type) > 0) {
PyObject *tmp = type;
type = PyTuple_GET_ITEM(type, 0);
Py_INCREF(type);
Py_DECREF(tmp);
}
if (PyExceptionClass_Check(type))
PyErr_NormalizeException(&type, &value, &tb);
else if (PyExceptionInstance_Check(type)) {
/* Raising an instance. The value should be a dummy. */
if (value != Py_None) {
PyErr_SetString(PyExc_TypeError,
"instance exception may not have a separate value");
goto raise_error;
}
else {
/* Normalize to raise <class>, <instance> */
Py_DECREF(value);
value = type;
type = PyExceptionInstance_Class(type);
Py_INCREF(type);
}
}
else {
/* Not something you can raise. You get an exception
anyway, just not what you specified :-) */
PyErr_Format(PyExc_TypeError,
"exceptions must be classes or instances, not %s",
type->ob_type->tp_name);
goto raise_error;
}
assert(PyExceptionClass_Check(type));
if (Py_Py3kWarningFlag && PyClass_Check(type)) {
if (PyErr_WarnEx(PyExc_DeprecationWarning,
"exceptions must derive from BaseException "
"in 3.x", 1) < 0)
goto raise_error;
}
PyErr_Restore(type, value, tb);
if (tb == 0)
return WHY_EXCEPTION;
else
return WHY_RERAISE;
raise_error:
Py_XDECREF(value);
Py_XDECREF(type);
Py_XDECREF(tb);
return WHY_EXCEPTION;
}
""")
Libr('_PyEval_ImportAllFrom',
"""
static int
_PyEval_ImportAllFrom(PyObject *, PyObject *);
""",
"""
static int
_PyEval_ImportAllFrom(PyObject *locals, PyObject *v)
{
PyObject *all = PyObject_GetAttrString(v, "__all__");
PyObject *dict, *name, *value;
int skip_leading_underscores = 0;
int pos, err;
if (all == 0) {
if (!PyErr_ExceptionMatches(PyExc_AttributeError))
return -1; /* Unexpected error */
PyErr_Clear();
dict = PyObject_GetAttrString(v, "__dict__");
if (dict == 0) {
if (!PyErr_ExceptionMatches(PyExc_AttributeError))
return -1;
PyErr_SetString(PyExc_ImportError,
"from-import-* object has no __dict__ and no __all__");
return -1;
}
all = PyMapping_Keys(dict);
Py_DECREF(dict);
if (all == 0)
return -1;
skip_leading_underscores = 1;
}
for (pos = 0, err = 0; ; pos++) {
name = PySequence_GetItem(all, pos);
if (name == 0) {
if (!PyErr_ExceptionMatches(PyExc_IndexError))
err = -1;
else
PyErr_Clear();
break;
}
if (skip_leading_underscores &&
PyString_Check(name) &&
PyString_AS_STRING(name)[0] == '_')
{
Py_DECREF(name);
continue;
}
value = PyObject_GetAttr(v, name);
if (value == 0)
err = -1;
else if (PyDict_CheckExact(locals))
err = PyDict_SetItem(locals, name, value);
else
err = PyObject_SetItem(locals, name, value);
Py_DECREF(name);
Py_XDECREF(value);
if (err != 0)
break;
}
Py_DECREF(all);
return err;
}
""")
Libr('_PyEval_BuildClass',
"""
static PyObject *
_PyEval_BuildClass(PyObject *, PyObject *, PyObject *);
""",
"""
static PyObject *
_PyEval_BuildClass(PyObject *methods, PyObject *bases, PyObject *name)
{
PyObject *metaclass = NULL, *result, *base;
if (PyDict_Check(methods))
metaclass = PyDict_GetItemString(methods, "__metaclass__");
if (metaclass != NULL)
Py_INCREF(metaclass);
else if (PyTuple_Check(bases) && PyTuple_GET_SIZE(bases) > 0) {
base = PyTuple_GET_ITEM(bases, 0);
metaclass = PyObject_GetAttrString(base, "__class__");
if (metaclass == 0) {
PyErr_Clear();
metaclass = (PyObject *)base->ob_type;
Py_INCREF(metaclass);
}
}
else {
PyObject *g = PyEval_GetGlobals();
if (g != NULL && PyDict_Check(g))
metaclass = PyDict_GetItemString(g, "__metaclass__");
if (metaclass == 0)
metaclass = (PyObject *) &PyClass_Type;
Py_INCREF(metaclass);
}
result = PyObject_CallFunctionObjArgs(metaclass, name, bases, methods,
NULL);
Py_DECREF(metaclass);
if (result == 0 && PyErr_ExceptionMatches(PyExc_TypeError)) {
/* A type error here likely means that the user passed
in a base that was not a class (such the random module
instead of the random.random type). Help them out with
by augmenting the error message with more information.*/
PyObject *ptype, *pvalue, *ptraceback;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
if (PyString_Check(pvalue)) {
PyObject *newmsg;
newmsg = PyString_FromFormat(
"Error when calling the metaclass bases\\n"
" %s",
PyString_AS_STRING(pvalue));
if (newmsg != NULL) {
Py_DECREF(pvalue);
pvalue = newmsg;
}
}
PyErr_Restore(ptype, pvalue, ptraceback);
}
return result;
}
""")
Libr('_PyEval_ExecStatement',
"""static int
_PyEval_ExecStatement(PyFrameObject * , PyObject *, PyObject *, PyObject *);
""",
"""
static int
_PyEval_ExecStatement(PyFrameObject * f, PyObject *prog, PyObject *globals,
PyObject *locals)
{
int n;
PyObject *v;
int plain = 0;
if (PyTuple_Check(prog) && globals == Py_None && locals == Py_None &&
((n = PyTuple_Size(prog)) == 2 || n == 3)) {
/* Backward compatibility hack */
globals = PyTuple_GetItem(prog, 1);
if (n == 3)
locals = PyTuple_GetItem(prog, 2);
prog = PyTuple_GetItem(prog, 0);
}
if (globals == Py_None) {
globals = PyEval_GetGlobals();
if (locals == Py_None) {
locals = PyEval_GetLocals();
plain = 1;
}
if (!globals || !locals) {
PyErr_SetString(PyExc_SystemError,
"globals and locals cannot be NULL");
return -1;
}
}
else if (locals == Py_None)
locals = globals;
if (!PyString_Check(prog) &&
!PyUnicode_Check(prog) &&
!PyCode_Check(prog) &&
!PyFile_Check(prog)) {
PyErr_SetString(PyExc_TypeError,
"exec: arg 1 must be a string, file, or code object");
return -1;
}
if (!PyDict_Check(globals)) {
PyErr_SetString(PyExc_TypeError,
"exec: arg 2 must be a dictionary or None");
return -1;
}
if (!PyMapping_Check(locals)) {
PyErr_SetString(PyExc_TypeError,
"exec: arg 3 must be a mapping or None");
return -1;
}
if (PyDict_GetItemString(globals, "__builtins__") == 0)
PyDict_SetItemString(globals, "__builtins__", b);
if (PyCode_Check(prog)) {
if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
PyErr_SetString(PyExc_TypeError,
"code object passed to exec may not contain free variables");
return -1;
}
v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
}
else if (PyFile_Check(prog)) {
FILE *fp = PyFile_AsFile(prog);
char *name = PyString_AsString(PyFile_Name(prog));
PyCompilerFlags cf;
if (name == 0)
return -1;
cf.cf_flags = 0;
if (PyEval_MergeCompilerFlags(&cf))
v = PyRun_FileFlags(fp, name, Py_file_input, globals,
locals, &cf);
else
v = PyRun_File(fp, name, Py_file_input, globals,
locals);
}
else {
PyObject *tmp = NULL;
char *str;
PyCompilerFlags cf;
cf.cf_flags = 0;
#ifdef Py_USING_UNICODE
if (PyUnicode_Check(prog)) {
tmp = PyUnicode_AsUTF8String(prog);
if (tmp == 0)
return -1;
prog = tmp;
cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
}
#endif
if (PyString_AsStringAndSize(prog, &str, NULL))
return -1;
if (PyEval_MergeCompilerFlags(&cf))
v = PyRun_StringFlags(str, Py_file_input, globals,
locals, &cf);
else
v = PyRun_String(str, Py_file_input, globals, locals);
Py_XDECREF(tmp);
}
if (plain)
PyFrame_LocalsToFast(f, 0);
if (v == 0)
return -1;
Py_DECREF(v);
return 0;
}
""")
Libr('__pyx_binding_PyCFunctionType_NewEx',
"""
typedef struct {
PyCFunctionObject func;
} __pyx_binding_PyCFunctionType_object;
static PyTypeObject __pyx_binding_PyCFunctionType_type;
static PyTypeObject *__pyx_binding_PyCFunctionType = NULL;
static PyObject *__pyx_binding_PyCFunctionType_NewEx(PyMethodDef *ml, PyObject *self, PyObject *module); /* proto */
#define __pyx_binding_PyCFunctionType_New(ml, self) __pyx_binding_PyCFunctionType_NewEx(ml, self, NULL)
static int __pyx_binding_PyCFunctionType_init(void); /* proto */
""",
"""
static PyObject *__pyx_binding_PyCFunctionType_NewEx(PyMethodDef *ml, PyObject *self, PyObject *module) {
__pyx_binding_PyCFunctionType_object *op = PyObject_GC_New(__pyx_binding_PyCFunctionType_object, __pyx_binding_PyCFunctionType);
if (op == NULL)
return NULL;
op->func.m_ml = ml;
Py_XINCREF(self);
op->func.m_self = self;
Py_XINCREF(module);
op->func.m_module = module;
PyObject_GC_Track(op);
return (PyObject *)op;
}
static void __pyx_binding_PyCFunctionType_dealloc(__pyx_binding_PyCFunctionType_object *m) {
PyObject_GC_UnTrack(m);
Py_XDECREF(m->func.m_self);
Py_XDECREF(m->func.m_module);
PyObject_GC_Del(m);
}
static PyObject *__pyx_binding_PyCFunctionType_descr_get(PyObject *func, PyObject *obj, PyObject *type) {
if (obj == Py_None)
obj = NULL;
return PyMethod_New(func, obj, type);
}
static int __pyx_binding_PyCFunctionType_init(void) {
__pyx_binding_PyCFunctionType_type = PyCFunction_Type;
__pyx_binding_PyCFunctionType_type.tp_name = "cython_binding_builtin_function_or_method";
__pyx_binding_PyCFunctionType_type.tp_dealloc = (destructor)__pyx_binding_PyCFunctionType_dealloc;
__pyx_binding_PyCFunctionType_type.tp_descr_get = __pyx_binding_PyCFunctionType_descr_get;
if (PyType_Ready(&__pyx_binding_PyCFunctionType_type) < 0) {
return -1;
}
__pyx_binding_PyCFunctionType = &__pyx_binding_PyCFunctionType_type;
return 0;
}
""")
Libr('empty_number_protocol',
"""static PyNumberMethods empty_number_protocol;""",
"""static PyNumberMethods empty_number_protocol = {
0, /*nb_add*/
0, /*nb_subtract*/
0, /*nb_multiply*/
#if PY_MAJOR_VERSION < 3
0, /*nb_divide*/
#endif
0, /*nb_remainder*/
0, /*nb_divmod*/
0, /*nb_power*/
0, /*nb_negative*/
0, /*nb_positive*/
0, /*nb_absolute*/
0, /*nb_nonzero*/
0, /*nb_invert*/
0, /*nb_lshift*/
0, /*nb_rshift*/
0, /*nb_and*/
0, /*nb_xor*/
0, /*nb_or*/
#if PY_MAJOR_VERSION < 3
0, /*nb_coerce*/
#endif
0, /*nb_int*/
#if PY_MAJOR_VERSION < 3
0, /*nb_long*/
#else
0, /*reserved*/
#endif
0, /*nb_float*/
#if PY_MAJOR_VERSION < 3
0, /*nb_oct*/
#endif
#if PY_MAJOR_VERSION < 3
0, /*nb_hex*/
#endif
0, /*nb_inplace_add*/
0, /*nb_inplace_subtract*/
0, /*nb_inplace_multiply*/
#if PY_MAJOR_VERSION < 3
0, /*nb_inplace_divide*/
#endif
0, /*nb_inplace_remainder*/
0, /*nb_inplace_power*/
0, /*nb_inplace_lshift*/
0, /*nb_inplace_rshift*/
0, /*nb_inplace_and*/
0, /*nb_inplace_xor*/
0, /*nb_inplace_or*/
0, /*nb_floor_divide*/
0, /*nb_true_divide*/
0, /*nb_inplace_floor_divide*/
0, /*nb_inplace_true_divide*/
#if PY_VERSION_HEX >= 0x02050000
0, /*nb_index*/
#endif
};
""")
Libr('empty_seq_protocol',
"""static PySequenceMethods empty_seq_protocol;""",
"""static PySequenceMethods empty_seq_protocol = {
0, /*sq_length*/
0, /*sq_concat*/
0, /*sq_repeat*/
0, /*sq_item*/
0, /*sq_slice*/
0, /*sq_ass_item*/
0, /*sq_ass_slice*/
0, /*sq_contains*/
0, /*sq_inplace_concat*/
0, /*sq_inplace_repeat*/
};
""")
Libr('empty_map_protocol',
"""static PyMappingMethods empty_map_protocol;""",
"""static PyMappingMethods empty_map_protocol = {
0, /*mp_length*/
0, /*mp_subscript*/
0, /*mp_ass_subscript*/
};
""")
Libr('empty_buf_protocol',
"""static PyBufferProcs empty_buf_protocol;""",
"""static PyBufferProcs empty_buf_protocol = {
#if PY_MAJOR_VERSION < 3
0, /*bf_getreadbuffer*/
#endif
#if PY_MAJOR_VERSION < 3
0, /*bf_getwritebuffer*/
#endif
#if PY_MAJOR_VERSION < 3
0, /*bf_getsegcount*/
#endif
#if PY_MAJOR_VERSION < 3
0, /*bf_getcharbuffer*/
#endif
#if PY_VERSION_HEX >= 0x02060000
0, /*bf_getbuffer*/
#endif
#if PY_VERSION_HEX >= 0x02060000
0, /*bf_releasebuffer*/
#endif
};
""")
Libr('ping_threading',
"""
static int ping_threading (void);
""",
"""
#if PYTHON_VERSION < 300
// We share this with CPython bytecode main loop.
PyAPI_DATA(volatile int) _Py_Ticker;
#else
extern volatile int _Py_Ticker;
#define _Py_CheckInterval 20
#endif
static int ping_threading (void)
{
if ( --_Py_Ticker < 0 )
{
PyThreadState *tstate = 0;
_Py_Ticker = _Py_CheckInterval;
if (Py_MakePendingCalls() < 0) return -1;
tstate = PyThreadState_GET();
assert (tstate);
if (tstate->async_exc != NULL) {
PyObject * x = tstate->async_exc;
tstate->async_exc = NULL;
PyErr_SetNone(x);
Py_DECREF(x);
return -1;\
}
}
return 0;
}
""")
Libr('parse_arguments',
"""
static int parse_arguments (PyObject *func, PyObject *arg, PyObject *kw, PyObject * co, PyObject * argdefs, PyObject ** fastlocals);
""",
"""
static int
PyEval_Eval3CCodeEx(PyCodeObject *co, PyObject *locals,
PyObject **args, int argcount, PyObject **kws, int kwcount,
PyObject **defs, int defcount
#ifndef PYPY_VERSION
, PyObject *closure, PyObject ** fastlocals);
#else
, PyObject ** fastlocals);
#endif
static int parse_arguments (PyObject *func, PyObject *arg, PyObject *kw, PyObject * co, PyObject * argdefs, PyObject ** fastlocals)
{
int result;
PyObject **d, **k;
Py_ssize_t nk, nd;
if (argdefs != NULL && PyTuple_Check(argdefs)) {
d = &PyTuple_GET_ITEM((PyTupleObject *)argdefs, 0);
nd = PyTuple_Size(argdefs);
}
else {
d = NULL;
nd = 0;
}
if (kw != NULL && PyDict_Check(kw)) {
Py_ssize_t pos, i;
nk = PyDict_Size(kw);
k = PyMem_NEW(PyObject *, 2*nk);
if (k == 0) {
PyErr_NoMemory();
return -1;
}
pos = i = 0;
while (PyDict_Next(kw, &pos, &k[i], &k[i+1]))
i += 2;
nk = i/2;
/* XXX This is broken if the caller deletes dict items! */
}
else {
k = NULL;
nk = 0;
}
result = PyEval_Eval3CCodeEx(
(PyCodeObject *)co,
(PyObject *)NULL,
&PyTuple_GET_ITEM(arg, 0), PyTuple_Size(arg),
k, nk, d, nd, 0, fastlocals);
if (k != NULL)
PyMem_DEL(k);
return result;
}
/* Local variable macros */
#undef GETLOCAL
#undef SETLOCAL
#define GETLOCAL(i) (fastlocals[i])
#define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \
GETLOCAL(i) = value; \
Py_XDECREF(tmp); } while (0)
static int
PyEval_Eval3CCodeEx(PyCodeObject *co, PyObject *locals,
PyObject **args, int argcount, PyObject **kws, int kwcount,
PyObject **defs, int defcount
#ifndef PYPY_VERSION
, PyObject *closure, PyObject ** fastlocals)
#else
, PyObject ** fastlocals)
#endif
{
PyThreadState *tstate = PyThreadState_GET();
PyObject *x, *u;
assert(tstate != NULL);
if (co->co_argcount > 0 ||
co->co_flags & (CO_VARARGS | CO_VARKEYWORDS)) {
int i;
int n = argcount;
PyObject *kwdict = NULL;
if (co->co_flags & CO_VARKEYWORDS) {
kwdict = PyDict_New();
if (kwdict == 0)
goto fail;
i = co->co_argcount;
if (co->co_flags & CO_VARARGS)
i++;
SETLOCAL(i, kwdict);
}
if (argcount > co->co_argcount) {
if (!(co->co_flags & CO_VARARGS)) {
PyErr_Format(PyExc_TypeError,
"%.200s() takes %s %d "
"%sargument%s (%d given)",
PyString_AsString(co->co_name),
defcount ? "at most" : "exactly",
co->co_argcount,
kwcount ? "non-keyword " : "",
co->co_argcount == 1 ? "" : "s",
argcount);
goto fail;
}
n = co->co_argcount;
}
for (i = 0; i < n; i++) {
x = args[i];
Py_INCREF(x);
SETLOCAL(i, x);
}
if (co->co_flags & CO_VARARGS) {
u = PyTuple_New(argcount - n);
if (u == 0)
goto fail;
SETLOCAL(co->co_argcount, u);
for (i = n; i < argcount; i++) {
x = args[i];
Py_INCREF(x);
PyTuple_SET_ITEM(u, i-n, x);
}
}
for (i = 0; i < kwcount; i++) {
PyObject **co_varnames;
PyObject *keyword = kws[2*i];
PyObject *value = kws[2*i + 1];
int j;
if (keyword == 0 || !(PyString_Check(keyword)
#ifdef Py_USING_UNICODE
|| PyUnicode_Check(keyword)
#endif
)) {
PyErr_Format(PyExc_TypeError,
"%.200s() keywords must be strings",
PyString_AsString(co->co_name));
goto fail;
}
/* Speed hack: do raw pointer compares. As names are
normally interned this should almost always hit. */
co_varnames = ((PyTupleObject *)(co->co_varnames))->ob_item;
for (j = 0; j < co->co_argcount; j++) {
PyObject *nm = co_varnames[j];
if (nm == keyword)
goto kw_found;
}
/* Slow fallback, just in case */
for (j = 0; j < co->co_argcount; j++) {
PyObject *nm = co_varnames[j];
int cmp = PyObject_RichCompareBool(
keyword, nm, Py_EQ);
if (cmp > 0)
goto kw_found;
else if (cmp < 0)
goto fail;
}
if (kwdict == 0) {
PyObject *kwd_str = kwd_as_string(keyword);
if (kwd_str) {
PyErr_Format(PyExc_TypeError,
"%.200s() got an unexpected "
"keyword argument '%.400s'",
PyString_AsString(co->co_name),
PyString_AsString(kwd_str));
Py_DECREF(kwd_str);
}
goto fail;
}
PyDict_SetItem(kwdict, keyword, value);
continue;
kw_found:
if (GETLOCAL(j) != NULL) {
PyObject *kwd_str = kwd_as_string(keyword);
if (kwd_str) {
PyErr_Format(PyExc_TypeError,
"%.200s() got multiple "
"values for keyword "
"argument '%.400s'",
PyString_AsString(co->co_name),
PyString_AsString(kwd_str));
Py_DECREF(kwd_str);
}
}
Py_INCREF(value);
SETLOCAL(j, value);
}
if (argcount < co->co_argcount) {
int m = co->co_argcount - defcount;
for (i = argcount; i < m; i++) {
if (GETLOCAL(i) == 0) {
int j, given = 0;
for (j = 0; j < co->co_argcount; j++)
if (GETLOCAL(j))
given++;
PyErr_Format(PyExc_TypeError,
"%.200s() takes %s %d "
"argument%s (%d given)",
PyString_AsString(co->co_name),
((co->co_flags & CO_VARARGS) ||
defcount) ? "at least"
: "exactly",
m, m == 1 ? "" : "s", given);
goto fail;
}
}
if (n > m)
i = n - m;
else
i = 0;
for (; i < defcount; i++) {
if (GETLOCAL(m+i) == 0) {
PyObject *def = defs[i];
Py_INCREF(def);
SETLOCAL(m+i, def);
}
}
}
}
else {
if (argcount > 0 || kwcount > 0) {
PyErr_Format(PyExc_TypeError,
"%.200s() takes no arguments (%d given)",
PyString_AsString(co->co_name),
argcount + kwcount);
goto fail;
}
}
/* Allocate and initialize storage for cell vars, and copy free
vars into frame. This isn't too efficient right now. */
if (PyTuple_GET_SIZE(co->co_cellvars)) {
int i, j, nargs, found;
char *cellname, *argname;
PyObject *c;
nargs = co->co_argcount;
if (co->co_flags & CO_VARARGS)
nargs++;
if (co->co_flags & CO_VARKEYWORDS)
nargs++;
/* Initialize each cell var, taking into account
cell vars that are initialized from arguments.
Should arrange for the compiler to put cellvars
that are arguments at the beginning of the cellvars
list so that we can march over it more efficiently?
*/
for (i = 0; i < PyTuple_GET_SIZE(co->co_cellvars); ++i) {
cellname = PyString_AS_STRING(
PyTuple_GET_ITEM(co->co_cellvars, i));
found = 0;
for (j = 0; j < nargs; j++) {
argname = PyString_AS_STRING(
PyTuple_GET_ITEM(co->co_varnames, j));
if (strcmp(cellname, argname) == 0) {
c = PyCell_New(GETLOCAL(j));
if (c == 0)
goto fail;
GETLOCAL(co->co_nlocals + i) = c;
found = 1;
break;
}
}
if (found == 0) {
c = PyCell_New(NULL);
if (c == 0)
goto fail;
SETLOCAL(co->co_nlocals + i, c);
}
}
}
#ifndef PYPY_VERSION
if (PyTuple_GET_SIZE(co->co_freevars)) {
assert(0);
}
#endif
assert(!(co->co_flags & CO_GENERATOR));
fail: /* Jump here from prelude on failure */
/* decref'ing the frame can cause __del__ methods to get invoked,
which can call back into Python. While we're done with the
current Python frame (f), the associated C stack is still in use,
so recursion_depth must be boosted for the duration.
*/
assert(tstate != NULL);
return 0;
}
""")
Libr('cfunc_parse_args',
"""
static int cfunc_parse_args(PyObject *arg, PyObject *kw, PyObject *argdefs, PyCodeObject * co, PyObject ** fastlocals);
""",
"""
static int cfunc_parse_args(PyObject *arg, PyObject *kw, PyObject *argdefs, PyCodeObject * co, PyObject ** fastlocals)
{
PyObject *result;
PyObject **d, **k;
Py_ssize_t nk, nd;
if (argdefs != NULL)) {
d = &PyTuple_GET_ITEM((PyTupleObject *)argdefs, 0);
nd = PyTuple_Size(argdefs);
}
else {
d = NULL;
nd = 0;
}
if (kw != NULL && PyDict_Check(kw)) {
Py_ssize_t pos, i;
nk = PyDict_Size(kw);
k = PyMem_NEW(PyObject *, 2*nk);
if (k == 0) {
PyErr_NoMemory();
return -1
}
pos = i = 0;
while (PyDict_Next(kw, &pos, &k[i], &k[i+1]))
i += 2;
nk = i/2;
/* XXX This is broken if the caller deletes dict items! */
}
else {
k = NULL;
nk = 0;
}
result = PyEval_Eval2CCodeEx(
co,
(PyObject *)NULL,
&PyTuple_GET_ITEM(arg, 0), PyTuple_Size(arg),
k, nk, d, nd
#ifndef PYPY_VERSION
,
PyFunction_GET_CLOSURE(func));
#else
);
#endif
if (k != NULL)
PyMem_DEL(k);
return result;
}
""")
fastglob = {}
def add_fast_glob(nm):
fastglob[nm] = True
def type_methfunc(co):
if ( ( co.co_flags & (0x4 + 0x8) ) == 0):
if co.method_class is None:
if co.co_argcount == 1:
return "METH_O", False
elif co.co_argcount == 0:
return "METH_NOARGS", False
return "METH_VARARGS|METH_KEYWORDS", False
if co.method_class is not None and co.co_argcount == 0:
return "METH_NOARGS", True
if co.method_class is not None and co.co_argcount == 1:
return "METH_O", True
return "METH_VARARGS|METH_KEYWORDS", co.method_class is not None
def write_as_c(cfile, nmmodule):
global pregenerated
global predeclared_chars
first, first2, first3 = Out(), Out(), Out()
first.print_to(c_head1)
## first2.print_to(c_head2)
first3.print_to(c_head3)
if len(fastglob) > 0:
s = 'enum{'
n = 0
for k in fastglob.iterkeys():
if k in detected_global_type and IsCType(detected_global_type[k]):
cty = Type2CType(detected_global_type[k])
first3.print_to('static %s Glob_%s_%s;\n' % (cty, cty, k))
else:
s += 'Glob_' + k + ','
n += 1
s = s[:-1] + '};\n'
if n > 0:
first3.print_to('PyObject * fastglob[' + str(n) + '];\n')
first3.print_to(s)
## for k in predeclared_chars.iterkeys():
## first2.print_to('static char const_string_' + str(k) + '[];\n')
di = {}
for cmds, o, co in pregenerated:
if not hasattr(co, 'no_codefunc') or not co.no_codefunc:
if co.c_name in di:
continue
di[co.c_name] = 0
if co.can_be_cfunc():
met, ismeth = type_methfunc(co)
if met == "METH_O" or met == "METH_NOARGS":
first3.print_to('static PyObject * cfunc_' + co.c_name +'(PyObject *, PyObject *);')
else:
first3.print_to('static PyObject * cfunc_' + co.c_name +'(PyObject *, PyObject *, PyObject *);')
first3.Raw("static PyMethodDef methfunc_", co.c_name, " = {\"", co.co_name, "\", (PyCFunction)cfunc_", co.c_name, ", ", met, ", 0};")
else:
first3.print_to('static PyObject * codefunc_' + co.c_name +'(PyFrameObject *);')
Used('PyEval_Eval2CCodeEx')
if co.c_name in direct_args: # and direct_call and subroutine_can_be_direct(nm):
arg = ""
coarg = co.co_argcount
hidden = co.hidden_arg_direct
typed_arg = co.typed_arg_direct
if co.co_flags & 0x4:
assert len(hidden) == 0
coarg += 1
if coarg == 0:
arg = '(void)'
else:
arg = ''
i = 0
while coarg > 1:
if i not in hidden:
if i in typed_arg and IsCType(typed_arg[i]):
arg += ', ' + Type2CType(typed_arg[i])
else:
arg += ', PyObject *'
coarg -= 1
i += 1
if i not in hidden:
if i in typed_arg and IsCType(typed_arg[i]):
arg += ', ' + Type2CType(typed_arg[i])
else:
arg += ', PyObject *'
if arg == '':
arg = ' void'
arg = '(' + arg[2:] + ')'
if co.IsRetVoid():
first3.print_to('static int _Direct_' + co.c_name + arg + ';')
elif IsCType(co.ReturnType()):
first3.print_to(('static %s _Direct_' % Type2CType(co.ReturnType())) + co.c_name + arg + ';')
else:
first3.print_to('static PyObject * _Direct_' + co.c_name + arg + ';')
to_check = {'_c_BINARY_SUBSCR_Int':'= _c_BINARY_SUBSCR_Int', '_PyEval_AssignSlice':'( _PyEval_AssignSlice', '_PyEval_ApplySlice':' = _PyEval_ApplySlice'}
checked = {}
for k, v in to_check.iteritems():
for cmds, o, co in pregenerated:
for s in o:
if v in s:
checked[k] = True
for a,b,c in Iter3(None, 'Used', True):
if IsLibr(a):
if a not in to_check or (a in checked and checked[a]):
first3.print_to(LibrDcl(a))
for cmds, o, co in pregenerated:
first3.extend(o)
pregenerate_code_objects()
generate_consts(first2, first3)
generate_calculated_consts(first2)
generate_builtin(first2, first3)
generate_init(first3, nmmodule)
if build_executable:
Used('main')
first3.print_to(c_tail)
for a,b,c in Iter3(None, 'Used', True):
if IsLibr(a):
if a not in to_check or (a in checked and checked[a]):
first3.print_to(LibrDef(a))
for s in first + first2 + first3:
print_to(cfile, s)
def generate_init(first3, nmmodule):
global labl
if not build_executable:
if c_name is None:
first3.print_to('PyMODINIT_FUNC init' + nmmodule+'(void);')
first3.print_to('PyMODINIT_FUNC init' + nmmodule+'(void){')
else:
first3.print_to('PyMODINIT_FUNC init' + c_name+'(void);')
first3.print_to('PyMODINIT_FUNC init' + c_name+'(void){')
else:
first3.print_to('static void init_main(void);')
first3.print_to('static void init_main(void){')
first3.print_to(' patch_code2c();')
if Is3('__pyx_binding_PyCFunctionType_NewEx', 'Used'):
first3.print_to(' __pyx_binding_PyCFunctionType_init();')
first3.print_to(' b = PyImport_AddModule("__builtin__");')
first3.print_to(' bdict = PyModule_GetDict(b);')
if len(loaded_builtin) > 0:
first3.print_to(' load_builtin();')
first3.print_to(' init_consts();')
## o = Out()
if c_name is None:
first3.print_to(' PyImport_Exec2CCodeModuleEx(\"' + nmmodule +'", ' +const_to(_n2c['Init_filename']) +');')
first3.print_to(' PyDict_SetItemString(glob, \"__compile_hash__\", PyInt_FromString(\"' + str(hash_compile) + '\", NULL, 0));')
else:
first3.print_to(' PyImport_Exec2CCodeModuleEx(\"' + c_name +'", ' +const_to(_n2c['Init_filename']) +');')
first3.print_to(' PyDict_SetItemString(glob, \"__compile_hash__\", PyInt_FromString(\"' + str(hash_compile) + '\", NULL, 0));')
first3.print_to('}')
def nmvar_to_loc(v):
if '(' in v or ')' in v or '[' in v or ']' in v or '.' in v or '-' in v:
v = v.replace('[', '_1_')
v = v.replace(']', '_9_')
v = v.replace('(', '_2_')
v = v.replace(')', '_7_')
v = v.replace('.', '_5_')
v = v.replace('-', '_6_')
return v
def generate_stand_header(l, co, typed, o, typed_local, isdirect, hidden):
global no_fastlocals
orepr = repr(o)
for i,(f,t) in enumerate(typed):
nm = t + '_' + str(i)
if t != 'label' and t != 'longref' and nm in orepr:
orepr = may_be_append_to_o(l, orepr, t, nm, o)
## l.append(t + ' ' + nm + ';')
if isdirect and no_fastlocals:
pass
else:
s = 'enum{'
cnt = 0
if isdirect:
names = co.co_varnames_direct
else:
names = co.co_varnames
for v in names:
if co.IsCVar(('FAST', v)) or v in hidden:
if isdirect:
continue
else:
v += '_missing_'
if s != 'enum{':
s += ', '
v = nmvar_to_loc(v)
s += 'Loc_' + v
cnt += 1
s += '};'
if s != 'enum{};':
l.append(s)
for k, v in typed_local.iteritems():
if IsCType(v):
ty = Type2CType(v)
cnm = 'Loc_%s_%s' %(ty, k)
orepr = may_be_append_to_o(l, orepr, ty, cnm, o)
return cnt
def may_be_append_to_o(l, orepr, ty, cnm, o, debug = False):
if cnm in orepr:
if orepr.count(cnm) == orepr.count(cnm + ' = '):
for i in range(len(o)):
if (cnm + ' = ') in o[i]:
o[i] = o[i].replace(cnm + ' = ', '')
if o[i] in ('0;', '1;'):
o[i] = ''
elif o[i].startswith('( Py_ssize_t_') and o[i].endswith(' );'):
o[i] = ''
elif o[i][0].isdigit():
o[i] = ''
elif o[i].startswith('PyObject_IsTrue(temp[') and o[i].endswith(']);'):
o[i] = ''
elif o[i].startswith('PyInt_AsLong(temp[') and o[i].endswith(']);'):
o[i] = ''
elif o[i].startswith('int_') and o[i].endswith(';') and o[i][4:-1].isdigit():
o[i] = ''
else:
print o[i], 'o[i]', '12345678'
o[:] = [x for x in o if x != '']
orepr = repr(o)
if cnm in orepr:
l.append(ty + ' ' + cnm + ';')
return orepr
def generate_parse_cfunc_args(co, cntvar, o, cntarg, ismeth):
global labl
assert labl is not None
assert type(labl) is tuple
ismeth = False
## for i in range(cntvar):
## o.Raw('fastlocals[', i, '] = 0;')
defa = None
if co.c_name in default_args:
defa = default_args[co.c_name]
if defa == ('CONST', ()):
defa = None
if defa is not None:
if defa[0] == 'CONST':
defaul = defa
defa = tuple([('CONST', x) for x in defa[1]])
else:
defaul = 'GETSTATIC(__default_arg___' + co.c_name + ')'
defa = defa[1] # BUILD_TUPLE
else:
defaul = 'NULL'
if ( ( co.co_flags & (0x4 + 0x8) ) == 0):
o.Raw(cntarg, ' = PyTuple_GET_SIZE(args);')
if defa is None:
o.Raw('if (kw == 0) {')
if not ismeth:
o.Raw('if ( ', cntarg, ' != ', co.co_argcount, ' ) {')
else:
o.Raw('if ( ', cntarg, ' != ', co.co_argcount-1, ' ) {')
if co.co_argcount != 1:
o.Raw("PyErr_Format(PyExc_TypeError, \"", co.co_name, "() takes exactly ", co.co_argcount, " arguments (%d given)\", ", cntarg, ');')
else:
o.Raw("PyErr_Format(PyExc_TypeError, \"", co.co_name, "() takes exactly ", co.co_argcount, " argument (%d given)\", ", cntarg, ');')
o.Raw('goto ', labl, ';')
UseLabl()
o.Raw('}')
if not ismeth:
for i in range(co.co_argcount):
o.Raw('fastlocals[', i, '] = PyTuple_GET_ITEM (args, ', i, ');')
o.Raw('Py_INCREF(fastlocals[', i, ']);')
else:
for i in range(co.co_argcount):
if i == 0:
o.Raw('fastlocals[', i, '] = self;')
o.Raw('Py_INCREF(fastlocals[', i, ']);')
else:
o.Raw('fastlocals[', i, '] = PyTuple_GET_ITEM (args, ', i-1, ');')
o.Raw('Py_INCREF(fastlocals[', i, ']);')
o.Raw('} else {')
if not ismeth:
o.Raw('static char *kwlist[] = {', ', '.join(['"' + co.co_varnames[i] + '"' for i in range(co.co_argcount)] + ['NULL']), '};')
listargs = ' , '.join(['fastlocals+' + str(i) for i in range(co.co_argcount)])
form = ''.join(['O' for i in range(co.co_argcount)])
else:
o.Raw('static char *kwlist[] = {', ', '.join(['"' + co.co_varnames[i] + '"' for i in range(1, co.co_argcount)] + ['NULL']), '};')
listargs = ' , '.join(['fastlocals+' + str(i) for i in range(1, co.co_argcount)])
form = ''.join(['O' for i in range(1, co.co_argcount)])
o.Raw('fastlocals[', i, '] = self;')
o.Raw('Py_INCREF(fastlocals[', i, ']);')
o.Raw('if ( !PyArg_ParseTupleAndKeywords ( args , kw , \"', form, '\" , kwlist , ', listargs, ' ) ) goto ', labl, ';')
o.Raw('}')
else:
minarg = co.co_argcount - len(defa)
assert minarg >= 0
o.Raw('if (kw == 0) {')
if not ismeth:
o.Raw('if ( ', cntarg, ' < ', minarg, ' ) {')
if minarg != 1:
o.Raw("PyErr_Format(PyExc_TypeError, \"", co.co_name, "() takes at least ", minarg, " arguments (%d given)\", ", cntarg, ');')
else:
o.Raw("PyErr_Format(PyExc_TypeError, \"", co.co_name, "() takes at least ", minarg, " argument (%d given)\", ", cntarg, ');')
else:
o.Raw('if ( ', cntarg, ' < ', minarg-1, ' ) {')
if minarg != 0:
o.Raw("PyErr_Format(PyExc_TypeError, \"", co.co_name, "() takes at least ", minarg, " arguments (%d given)\", ", cntarg, ');')
else:
o.Raw("PyErr_Format(PyExc_TypeError, \"", co.co_name, "() takes at least ", minarg, " argument (%d given)\", ", cntarg, ');')
o.Raw('goto ', labl, ';')
UseLabl()
o.Raw('}')
for i in range(co.co_argcount):
if i < minarg:
if not ismeth:
o.Raw('fastlocals[', i, '] = PyTuple_GET_ITEM (args, ', i, ');')
o.Raw('Py_INCREF(fastlocals[', i, ']);')
elif i == 0:
o.Raw('fastlocals[', i, '] = self;')
o.Raw('Py_INCREF(fastlocals[', i, ']);')
else:
o.Raw('fastlocals[', i, '] = PyTuple_GET_ITEM (args, ', i-1, ');')
o.Raw('Py_INCREF(fastlocals[', i, ']);')
else:
if not ismeth:
o.Raw('if ( ', i, ' < ', cntarg, ' ) {')
o.Raw('fastlocals[', i, '] = PyTuple_GET_ITEM (args, ', i, ');')
o.Raw('Py_INCREF(fastlocals[', i, ']);')
else:
if i == 0:
o.Raw('fastlocals[', i, '] = self;')
o.Raw('Py_INCREF(fastlocals[', i, ']);')
else:
o.Raw('if ( ', i, ' < ', cntarg, ' ) {')
o.Raw('fastlocals[', i, '] = PyTuple_GET_ITEM (args, ', i-1, ');')
o.Raw('Py_INCREF(fastlocals[', i, ']);')
o.Raw('} else {')
if not ismeth:
assert (i-minarg) >= 0
edefa = defa[i-minarg]
if edefa[0] == 'CONST':
o.Raw('fastlocals[', i, '] = ', edefa, ';')
o.Raw('Py_INCREF(fastlocals[', i, ']);')
else:
o.Raw('fastlocals[', i, '] = PyTuple_GET_ITEM ( GETSTATIC(__default_arg___', co.c_name, ') , ', i-minarg, ');')
o.Raw('Py_INCREF(fastlocals[', i, ']);')
## print edefa, co.c_name
## edefa = Expr1(edefa, o)
## o.Raw('fastlocals[', i, '] = ', edefa, ';')
o.Raw('} ')
o.Raw('} else {')
o.Raw('if ( parse_arguments (self, args, kw, ', const_to(co), ', ', defaul, ', fastlocals) == -1) goto ', labl, ';')
UseLabl()
Used('parse_arguments')
## for i in range(co.co_argcount):
## if i < minarg:
## o.Raw('fastlocals[', i, '] = PyTuple_GET_ITEM (args, ', i, ');')
## else:
## o.Raw('if ( ', i, ' < ', cntarg, ' ) {')
## o.Raw('fastlocals[', i, '] = PyTuple_GET_ITEM (args, ', i, ');')
## o.Raw('} else {')
## assert (i-minarg) >= 0
## edefa = defa[i-minarg]
## if edefa[0] == 'CONST':
## o.Raw('fastlocals[', i, '] = ', edefa, ';')
## o.Raw('Py_INCREF(fastlocals[', i, ']);')
## else:
## o.Raw('fastlocals[', i, '] = PyTuple_GET_ITEM ( GETSTATIC(__default_arg___', co.c_name, ') , ', i-minarg, ');')
## o.Raw('Py_INCREF(fastlocals[', i, ']);')
## ## print edefa
## ## edefa = Expr1(edefa, o)
## ## o.Raw('fastlocals[', i, '] = ', edefa, ';')
## o.Raw('} ')
## o.Raw('Py_INCREF(fastlocals[', i, ']);')
o.Raw('}')
o.Cls(cntarg)
return
if ( ( co.co_flags & (0x4 + 0x8) ) == 0x4):
defa = None
if co.c_name in default_args:
defa = default_args[co.c_name]
if defa == ('CONST', ()):
defa = None
if defa is None:
o.Raw(cntarg, ' = PyTuple_GET_SIZE(args);')
o.Raw('if (kw == 0) {')
if co.co_argcount > 0:
o.Raw('if ( ', cntarg, ' < ', co.co_argcount, ' ) {')
if co.co_argcount != 1:
o.Raw("PyErr_Format(PyExc_TypeError, \"", co.co_name, "() takes at least ", co.co_argcount, " arguments (%d given)\", ", cntarg, ');')
else:
o.Raw("PyErr_Format(PyExc_TypeError, \"", co.co_name, "() takes at least ", co.co_argcount, " argument (%d given)\", ", cntarg, ');')
o.Raw('goto ', labl, ';')
UseLabl()
o.Raw('}')
for i in range(co.co_argcount):
o.Raw('fastlocals[', i, '] = PyTuple_GET_ITEM (args, ', i, ');')
o.Raw('Py_INCREF(fastlocals[', i, ']);')
o.Raw('fastlocals[', co.co_argcount, '] = PySequence_GetSlice ( args , ', co.co_argcount , ', PY_SSIZE_T_MAX );')
o.Raw('} else {')
o.Raw('if ( parse_arguments (self, args, kw, ', const_to(co), ', ', defaul, ', fastlocals) == -1) goto ', labl, ';')
UseLabl()
Used('parse_arguments')
o.Raw('}')
return
else:
o.Raw('if ( parse_arguments (self, args, kw, ', const_to(co), ', ', defaul, ', fastlocals) == -1) goto ', labl, ';')
UseLabl()
Used('parse_arguments')
return
Fatal('Unhandeled cfunc', co)
def generate_cfunc_header(nm, o, co, typed, typed_local):
global tempgen
l = Out()
l.append('')
to_count_arg = None
met, ismeth = type_methfunc(co)
have_fastlocal = False
for s in o:
if 'LOCAL' in s:
have_fastlocal = True
if met == "METH_NOARGS":
l.append('static PyObject * cfunc_' + nm +'(PyObject * self, PyObject * UNUSED) {')
elif met == "METH_O" or met == "METH_NOARGS":
l.append('static PyObject * cfunc_' + nm +'(PyObject * self, PyObject * args) {')
else:
l.append('static PyObject * cfunc_' + nm +'(PyObject * self, PyObject * args, PyObject *kw) {')
if have_fastlocal:
l.append('int len_args = 0;')
to_count_arg = 'len_args'
cntvar = generate_stand_header(l, co, typed, o, typed_local, False, {})
if line_number:
l.Raw('int PyLine = ', co.co_firstlineno, ';')
l.append('int PyAddr = 0;')
if len(co.co_cellvars + co.co_freevars) > 0:
Fatal("Can\'t make cfunc with cellvars & freevars")
return None
sfree = None
if have_fastlocal:
l.Raw('PyObject *fastlocals[', cntvar, '];')
is_tstate = False
for s in o:
if 'tstate' in s:
is_tstate = True
if is_tstate:
l.append('PyThreadState *tstate = PyThreadState_GET();')
if not redefined_attribute:
for k in co.dict_getattr_used.iterkeys():
if ( len(calc_const_old_class) > 0 and not is_pypy ) or len(calc_const_new_class) > 0:
l.append('PyObject *_%s_dict = 0;' %k)
if calc_ref_total:
l.append('Py_ssize_t l_Py_RefTotal;')
l_fast = Out()
if nm == 'Init_filename':
if is_pypy:
l_fast.Raw('glob = PyObject_GetAttrString((PyObject *)f, "f_locals");')
else:
l_fast.Raw('glob = f->f_locals;')
l_fast = Out()
if have_fastlocal:
if met == "METH_NOARGS":
for i in range(cntvar):
l_fast.append('fastlocals[' + str(i) + '] = 0;')
elif met == "METH_O" or met == "METH_NOARGS":
l_fast.append('fastlocals[0] = args;')
l_fast.append('Py_INCREF(fastlocals[0]);')
for i in range(1, cntvar):
l_fast.append('fastlocals[' + str(i) + '] = 0;')
else:
for i in range(cntvar):
l_fast.append('fastlocals[' + str(i) + '] = 0;')
generate_parse_cfunc_args(co, cntvar, l_fast, to_count_arg, ismeth)
# l.append('static PyObject * cfunc_' + nm +'(PyObject * self, PyObject * args, PyObject *kw) {')
if len(tempgen) != 0:
l.Raw('PyObject * temp[', max(1, len(tempgen)), '];')
for i in range(len(tempgen)):
l.append('temp[' + str(i) + '] = 0;')
l.extend(l_fast)
l_fast = None
if not redefined_attribute:
for k in co.dict_getattr_used.iterkeys():
if ( len(calc_const_old_class) > 0 and not is_pypy ) and len(calc_const_new_class) > 0:
l.append('if (PyInstance_Check(GETLOCAL(%s))) {' % k)
l.append('_%s_dict = ((PyInstanceObject *)GETLOCAL(%s))->in_dict;' %(k,k))
l.append('} else {')
l.append('PyObject **refdict = _PyObject_GetDictPtr(GETLOCAL(%s));' %k)
l.append('if (refdict && *refdict) _%s_dict = *refdict;' %k )
l.append('}')
elif len(calc_const_old_class) > 0 and len(calc_const_new_class) == 0 and not is_pypy:
l.append('if (PyInstance_Check(GETLOCAL(%s))) {' % k)
l.append('_%s_dict = ((PyInstanceObject *)GETLOCAL(%s))->in_dict;' %(k,k))
l.append('}')
elif ( len(calc_const_old_class) == 0 or is_pypy ) and len(calc_const_new_class) > 0:
l.append('{')
l.append('PyObject **refdict = _PyObject_GetDictPtr(GETLOCAL(%s));' %k)
l.append('if (refdict && *refdict) _%s_dict = *refdict;' %k )
l.append('}')
if calc_ref_total:
l.append('l_Py_RefTotal = _Py_RefTotal;')
l.Raw('')
l.extend(o)
o[:] = l[:]
cnt_temp = 0
for s in o:
if 'temp[' in s or 'CLEAETEMP(' in s:
cnt_temp += 1
if cnt_temp == 1:
for i in range(len(o)):
if o[i].startswith('PyObject * temp['):
del o[i]
break
return
def generate_header(nm, o, co, typed, typed_local):
global tempgen
l = Out()
l.append('')
l.append('static PyObject * codefunc_' + nm +'(PyFrameObject *f) {')
cntvar = generate_stand_header(l, co, typed, o, typed_local, False, {})
if co.co_stacksize != 0:
if is_pypy:
l.Raw('PyObject * temp[', co.co_stacksize, '];')
else:
l.append('PyObject ** temp;')
sfree = 'enum{' + ', '.join(['Loc2_' + nmvar_to_loc(v) for v in co.co_cellvars + co.co_freevars]) + '};'
## for i,v in enumerate(co.co_cellvars + co.co_freevars):
## if i > 0:
## s += ', '
## v = nmvar_to_loc(v)
## s += 'Loc2_' + v
## s += '};'
have_fastlocal = False
if sfree != 'enum{};':
l.Raw(sfree)
l.append('register PyObject **fastlocals, **freevars;')
have_fastlocal = True
else:
sfree = None
if cntvar != 0:
for s in o:
if 'LOCAL' in s:
have_fastlocal = True
if have_fastlocal:
l.append('register PyObject **fastlocals;')
l.append('PyThreadState *tstate = PyThreadState_GET();')
if not redefined_attribute:
## if co.self_dict_getattr_used:
## if co.method_new_class:
## l.append('PyObject **self_dict;')
## elif co.method_old_class:
## l.append('PyObject *self_dict;')
## else:
## Fatal('')
for k in co.dict_getattr_used.iterkeys():
if ( len(calc_const_old_class) > 0 and not is_pypy ) or len(calc_const_new_class) > 0:
l.append('PyObject *_%s_dict = 0;' %k)
if calc_ref_total:
l.append('Py_ssize_t l_Py_RefTotal;')
## if line_number and is_pypy:
## l.append('int PyAddr = 0;')
if nm == 'Init_filename':
if is_pypy:
l.Raw('glob = PyObject_GetAttrString((PyObject *)f, "f_locals");')
else:
l.Raw('glob = f->f_locals;')
l.append('if (f == 0) return NULL;')
if check_recursive_call:
l.append('if (Py_EnterRecursiveCall("")) return NULL;')
if not is_pypy:
l.append('tstate->frame = f;')
if sfree is not None or cntvar != 0:
if have_fastlocal:
l.append('fastlocals = f->f_localsplus;')
if sfree is not None:
l.append('freevars = fastlocals + f->f_code->co_nlocals;')
if co.co_stacksize != 0:
if not is_pypy:
l.append('temp = f->f_stacktop;')
## l.Raw('printf(\"top=%x, val=%x\\n\", f->f_stacktop, f->f_valuestack);')
l.append('assert(temp != NULL);')
for i in range(min(co.co_stacksize, len(tempgen))):
l.append('temp[' + str(i) + '] = 0;')
if not is_pypy:
l.append('f->f_stacktop = NULL;')
if not redefined_attribute:
## if co.self_dict_getattr_used:
## if co.method_new_class:
## l.append('self_dict = _PyObject_GetDictPtr(GETLOCAL(self));')
## elif co.method_old_class:
## l.append('self_dict = ((PyInstanceObject *)GETLOCAL(self))->in_dict;')
## else:
## Fatal('')
for k in co.dict_getattr_used.iterkeys():
## if k == 'self':
## if co.method_new_class:
## l.append('_self_dict = *_PyObject_GetDictPtr(GETLOCAL(self));')
## elif co.method_old_class:
## l.append('_self_dict = ((PyInstanceObject *)GETLOCAL(self))->in_dict;')
## else:
## l.append('if (PyInstance_Check(GETLOCAL(%s))) {' % k)
## l.append('_%s_dict = ((PyInstanceObject *)GETLOCAL(%s))->in_dict;' %(k,k))
## l.append('} else {')
## l.append('PyObject **refdict = _PyObject_GetDictPtr(GETLOCAL(%s));' %k)
## l.append('if (refdict && *refdict) _%s_dict = *refdict;' %k )
## l.append('}')
## else:
if ( len(calc_const_old_class) > 0 and not is_pypy ) and len(calc_const_new_class) > 0:
l.append('if (PyInstance_Check(GETLOCAL(%s))) {' % k)
l.append('_%s_dict = ((PyInstanceObject *)GETLOCAL(%s))->in_dict;' %(k,k))
l.append('} else {')
l.append('PyObject **refdict = _PyObject_GetDictPtr(GETLOCAL(%s));' %k)
l.append('if (refdict && *refdict) _%s_dict = *refdict;' %k )
l.append('}')
elif ( len(calc_const_old_class) > 0 and not is_pypy ) and len(calc_const_new_class) == 0:
l.append('if (PyInstance_Check(GETLOCAL(%s))) {' % k)
l.append('_%s_dict = ((PyInstanceObject *)GETLOCAL(%s))->in_dict;' %(k,k))
l.append('}')
elif ( len(calc_const_old_class) == 0 or is_pypy ) and len(calc_const_new_class) > 0:
l.append('{')
l.append('PyObject **refdict = _PyObject_GetDictPtr(GETLOCAL(%s));' %k)
l.append('if (refdict && *refdict) _%s_dict = *refdict;' %k )
l.append('}')
if calc_ref_total:
l.append('l_Py_RefTotal = _Py_RefTotal;')
l.Raw('')
l.extend(o)
o[:] = l[:]
return
def generate_from_frame_to_direct_stube(co, o, nm, cmds):
l = []
l.append('')
l.append('static PyObject * codefunc_' + nm +'(PyFrameObject *f) {')
cntvar = generate_stand_header(l, co, [], o, {}, False, {})
s = 'enum{' + ', '.join(['Loc2_' + nmvar_to_loc(v) for v in co.co_cellvars + co.co_freevars]) + '};'
## s = 'enum{'
## for i,v in enumerate(co.co_cellvars + co.co_freevars):
## if i > 0:
## s += ', '
## v = nmvar_to_loc(v)
## s += 'Loc2_' + v
## s += '};'
if s != 'enum{};':
l.append(s)
if s != 'enum{};' or cntvar != 0:
l.append('register PyObject **fastlocals;')
l.append('PyThreadState *tstate = PyThreadState_GET();')
if not co.IsRetVoid() and not IsCType(co.ReturnType()):
l.append('PyObject * ret;')
if IsCType(co.ReturnType()):
l.append('%s ret;' % Type2CType(co.ReturnType()))
l.append('if (f == 0) return NULL;')
## if check_recursive_call:
## l.append('if (Py_EnterRecursiveCall("")) return NULL;')
if not is_pypy:
l.append('tstate->frame = f;')
if s != 'enum{};' or cntvar != 0:
l.append('fastlocals = f->f_localsplus;')
l.append('')
arg = ""
coarg = co.co_argcount
if co.co_flags & 0x4:
coarg += 1
## cnt_arg = coarg
## arg = ''
## i = 0
arg = '(' + ', '.join(['GETLOCAL(' + nmvar_to_loc(x) + ')' for i, x in enumerate(co.co_varnames) if i < coarg]) + ')'
## for i in range(coarg):
## v = nmvar_to_loc(co.co_varnames[i])
## if i != 0:
## arg += ', '
## arg += 'GETLOCAL(' + v + ')'
## arg = '(' + arg + ')'
if co.IsRetVoid():
l.append('if (_Direct_' + nm + arg + ' == -1) {')
if not is_pypy:
l.append('tstate->frame = f->f_back;')
l.append('return NULL;')
l.append('} else {')
if not is_pypy:
l.append('tstate->frame = f->f_back;')
l.append('Py_INCREF(Py_None);')
l.append('return Py_None;')
l.append('}')
elif co.IsRetBool():
l.append('if ((ret = _Direct_' + nm + arg + ') == -1) {')
if not is_pypy:
l.append('tstate->frame = f->f_back;')
l.append('return NULL;')
l.append('} else {')
if not is_pypy:
l.append('tstate->frame = f->f_back;')
l.append('if (ret) {')
l.append('Py_INCREF(Py_True);')
l.append('return Py_True;')
l.append('} else {')
l.append('Py_INCREF(Py_False);')
l.append('return Py_False;')
l.append('}')
l.append('}')
elif co.IsRetInt():
l.append('if ((ret = _Direct_' + nm + arg + ') == -1 && PyErr_Occurred()) {')
if not is_pypy:
l.append('tstate->frame = f->f_back;')
l.append('return NULL;')
l.append('} else {')
if not is_pypy:
l.append('tstate->frame = f->f_back;')
l.append('return PyInt_FromLong (ret);')
l.append('}')
elif co.IsRetChar():
l.append('if ((ret = _Direct_' + nm + arg + ') == 255 && PyErr_Occurred()) {')
if not is_pypy:
l.append('tstate->frame = f->f_back;')
l.append('return NULL;')
l.append('} else {')
if not is_pypy:
l.append('tstate->frame = f->f_back;')
l.append('return PyString_FromStringAndSize (&ret, 1);')
l.append('}')
elif co.IsRetFloat():
l.append('if ((ret = _Direct_' + nm + arg + ') == -1 && PyErr_Occurred()) {')
if not is_pypy:
l.append('tstate->frame = f->f_back;')
l.append('return NULL;')
l.append('} else {')
if not is_pypy:
l.append('tstate->frame = f->f_back;')
l.append('return PyFloat_FromDouble (ret);')
l.append('}')
else:
l.append('ret = _Direct_' + nm + arg + ';')
if not is_pypy:
l.append('tstate->frame = f->f_back;')
l.append('return ret;')
o[:] = l[:]
o.append('}')
pregenerated.append((cmds, o, co))
def declare_arg(i, typed_arg, co):
global no_fastlocals
if i in typed_arg:
t = typed_arg[i]
if IsCType(t):
cty = Type2CType(t)
return True, '%s Loc_%s_%s' % (cty, cty, co.co_varnames[i])
if no_fastlocals:
return False, 'PyObject * _Fast_%s' % co.co_varnames[i]
return False, 'PyObject * Arg_' + str(i)
def generate_stand_direct_header(l, co, typed, o, typed_local, hidden, cnt_arg):
global no_fastlocals
orepr = repr(o)
for i,(f,t) in enumerate(typed):
nm = t + '_' + str(i)
if t != 'label' and t != 'longref' and nm in orepr:
orepr = may_be_append_to_o(l, orepr, t, nm, o)
## l.append(t + ' ' + nm + ';')
if no_fastlocals:
li = [(ii, nmvar_to_loc(v)) \
for (ii, v) in enumerate(co.co_varnames_direct) \
if not co.IsCVar(('FAST', v)) and v not in hidden]
li = li[cnt_arg:]
else:
li = [(ii, nmvar_to_loc(v)) \
for (ii, v) in enumerate(co.co_varnames_direct) \
if not co.IsCVar(('FAST', v)) and v not in hidden]
cnt = len(li)
if cnt > 0:
if no_fastlocals:
l.extend(['PyObject * _Fast_' + v + ' = 0;' for ii, v in li])
else:
l.append('enum{' + ', '.join(['Loc_' + v for ii, v in li]) + '};')
for k, v in typed_local.iteritems():
if IsCType(v):
ty = Type2CType(v)
cnm = 'Loc_%s_%s' %(ty, k)
orepr = may_be_append_to_o(l, orepr, ty, cnm, o)
return cnt
def generate_header_direct(nm, o, co, typed, typed_arg, typed_local):
global no_fastlocals
l = Out()
assert type(co) is code_extended
l.Raw('')
arg = ""
coarg = co.co_argcount
if co.co_flags & 0x4:
assert len(co.hidden_arg_direct) == 0
coarg += 1
cnt_arg = coarg
if coarg == 0:
arg = '(void)'
i = 0
ii = 0
else:
arg = ''
i = 0
ii = 0
while coarg > 1:
if not i in co.hidden_arg_direct:
cty, _arg = declare_arg(i, typed_arg, co)
arg += ', ' + _arg
if not cty:
ii += 1
i += 1
coarg -= 1
if not i in co.hidden_arg_direct:
cty, _arg = declare_arg(i, typed_arg, co)
arg += ', ' + _arg
if not cty:
ii += 1
if arg == '':
arg = ' void'
arg = '(' + arg[2:] + ')'
if co.IsRetVoid() or co.IsRetBool():
l.Raw('static int _Direct_', nm, arg, '{')
elif co.IsRetInt():
l.Raw('static long _Direct_', nm, arg, '{')
elif co.IsRetFloat():
l.Raw('static double _Direct_', nm, arg, '{')
elif co.IsRetChar():
l.Raw('static char _Direct_', nm, arg, '{')
else:
l.Raw('static PyObject * _Direct_', nm, arg, '{')
hid = {}
for i in co.hidden_arg_direct:
hid[co.co_varnames_direct[i]] = True
cntvar = generate_stand_direct_header(l, co, typed, o, typed_local, hid, ii)
if co.co_stacksize != 0:
l.Raw('PyObject * temp[', co.co_stacksize, '];')
## s = 'enum{'
if len(co.co_varnames) > 0 and cntvar > 0:
if no_fastlocals:
pass
else:
l.Raw('PyObject *fastlocals[', cntvar, '];')
if calc_ref_total:
l.append('Py_ssize_t l_Py_RefTotal;')
l.append('l_Py_RefTotal = _Py_RefTotal;')
if line_number:
l.Raw('int PyLine = ', co.co_firstlineno, ';')
l.append('int PyAddr = 0;')
if not redefined_attribute:
## if co.self_dict_getattr_used:
## if co.method_new_class:
## l.append('PyObject **self_dict;')
## elif co.method_old_class:
## l.append('PyObject *self_dict;')
for k in co.dict_getattr_used.iterkeys():
if ( len(calc_const_old_class) > 0 and not is_pypy ) or len(calc_const_new_class) > 0:
l.Raw('PyObject *_', k, '_dict = 0;')
ii = 0
for i in range(cnt_arg):
if i in co.hidden_arg_direct:
continue
if i in typed_arg and typed_arg[i][0] is int:
pass
elif i in typed_arg and typed_arg[i][0] is float:
pass
elif i in typed_arg and typed_arg[i][0] is bool:
pass
elif i in typed_arg and typed_arg[i] == (str, 1):
pass
elif ii < cntvar:
if no_fastlocals:
l.Raw('Py_INCREF(_Fast_%s);' % co.co_varnames_direct[i])
else:
l.Raw('fastlocals[', ii, '] = Arg_', i, ';')
## if i in co.changed_arg:
l.Raw('Py_INCREF(Arg_', i, ');')
ii += 1
for i in range(ii, cntvar):
if no_fastlocals:
pass
else:
l.Raw('fastlocals[', i, '] = NULL;')
if not redefined_attribute:
## if co.self_dict_getattr_used:
## if co.method_new_class:
## l.append('self_dict = _PyObject_GetDictPtr(GETLOCAL(self));')
## elif co.method_old_class:
## l.append('self_dict = ((PyInstanceObject *)GETLOCAL(self))->in_dict;')
for k in co.dict_getattr_used.iterkeys():
## l.append('if (PyInstance_Check(GETLOCAL(%s))) {' % k)
## l.append('_%s_dict = ((PyInstanceObject *)GETLOCAL(%s))->in_dict;' %(k,k))
## l.append('} else {')
## l.append('PyObject **refdict = _PyObject_GetDictPtr(GETLOCAL(%s));' %k)
## l.append('if (refdict && *refdict) _%s_dict = *refdict;' %k )
## l.append('}')
if ( len(calc_const_old_class) > 0 and not is_pypy ) and len(calc_const_new_class) > 0:
l.append('if (PyInstance_Check(GETLOCAL(%s))) {' % k)
l.append('_%s_dict = ((PyInstanceObject *)GETLOCAL(%s))->in_dict;' %(k,k))
l.append('} else {')
l.append('PyObject **refdict = _PyObject_GetDictPtr(GETLOCAL(%s));' %k)
l.append('if (refdict && *refdict) _%s_dict = *refdict;' %k )
l.append('}')
elif ( len(calc_const_old_class) > 0 and not is_pypy ) and len(calc_const_new_class) == 0:
l.append('if (PyInstance_Check(GETLOCAL(%s))) {' % k)
l.append('_%s_dict = ((PyInstanceObject *)GETLOCAL(%s))->in_dict;' %(k,k))
l.append('}')
elif ( len(calc_const_old_class) == 0 or is_pypy ) and len(calc_const_new_class) > 0:
l.append('{')
l.append('PyObject **refdict = _PyObject_GetDictPtr(GETLOCAL(%s));' %k)
l.append('if (refdict && *refdict) _%s_dict = *refdict;' %k )
l.append('}')
for i in range(co.co_stacksize):
l.Raw('temp[', i, '] = 0;')
l.Raw('')
l.extend(o)
o[:] = l[:]
return
def stub_generator(co):
pass
def generate_list(lis, o = None):
i = 0
if o is None:
o = []
## have_compaund = False
## len_o = 0
## if o is not None:
## len_o = len(o)
if recalc_refcnt:
cnt_prev = New('Py_ssize_t')
line_prev = New('int')
o.Raw(cnt_prev, '= _Py_RefTotal;')
o.Raw(line_prev, '= __LINE__;')
while i < len(lis):
assert type(i) is int
it = lis[i]
head = it[0]
assert head[0] != ')' and head[0:2] != ')('
if IsBeg(head):
i1 = get_closed_pair(lis, i)
o.Comment(it)
generate_compaund_statement(head[1:], lis[i:i1+1], o)
i = i1 + 1
## have_compaund = True
else:
o.Comment(it)
generate_statement(head, it, o)
i += 1
if recalc_refcnt:
o.Raw('if ((int)(_Py_RefTotal -', cnt_prev, ')) { printf("\\nfunc %s, line %5d:%5d, refcnt %d\\n", "', func, '", ',\
line_prev, ',__LINE__, (int)(_Py_RefTotal -', cnt_prev, '));} ',\
cnt_prev, '= _Py_RefTotal; ', line_prev, '= __LINE__;')
if recalc_refcnt:
o.Cls(cnt_prev, line_prev)
return o
def get_closed_pair(lis,i):
if type(lis) is list:
for i1 in range(i+1, len(lis)):
lis2 = lis[i1]
if type(lis2) is tuple:
lis3 = lis2[0]
if type(lis3) is str:
if lis3[0] == ')' and lis3[0:2] != ')(':
return i1
Fatal('Can\'t get closed pair', lis)
def generate_return_statement(it, o):
global try_jump_context, dropped_temp
global traced_tempgen
current_co.return_cnt += 1
place = len(o)
## current_co.returns[len(o)] = 0
retlabl = ConC('ret_label_', current_co.return_cnt)
o.Raw(retlabl, ':;')
o.Raw('if (ping_threading () == -1) goto ', labl, ';')
UseLabl()
Used('ping_threading')
for drop in dropped_temp:
for t in drop[1]:
if istempref(t):
o.Raw('Py_CLEAR(', t, ');')
try_jump = try_jump_context[:]
if len(it[1]) == 1 and it[1][0] == 'f->f_locals':
ref = New()
if is_current & IS_CFUNC:
o.Raw(ref, ' = glob;')
else:
assert is_current & IS_CODEFUNC
o.Raw(ref, ' = ', it[1][0], ';')
o.INCREF(ref)
PopClearAll(o)
if checkmaxref != 0 and not is_pypy:
o.Raw('if ((', ref, ')->ob_refcnt > ', checkmaxref, ') printf("line %5d, line %6d \\n", __LINE__,(', ref, ')->ob_refcnt);')
if is_current & IS_CODEFUNC:
if check_recursive_call:
o.append('Py_LeaveRecursiveCall();')
if not is_pypy:
o.append('tstate->frame = f->f_back;')
o.Raw('return ', ref, ';')
Cls1(o, ref)
return
if is_current & IS_DIRECT:
isvoid = current_co.IsRetVoid()
isbool = current_co.IsRetBool()
isint = current_co.IsRetInt()
isfloat = current_co.IsRetFloat()
ischar = current_co.IsRetChar()
else:
isvoid = False
isbool = False
isint = False
isfloat = False
ischar = False
if isvoid:
assert IsKlNone(TypeExpr(it[1]))
ref = it[1]
if isvoid:
ref = Expr1(ref, o)
Cls1(o, ref)
ref = None
elif IsCVar(ref):
logical = CVarName(ref)
if is_current & IS_CALLABLE_COMPILABLE:
ref = Expr1(ref, o)
elif ref[0] == 'CONST' and isbool:
if ref[1]:
logical = 1
else:
logical = 0
elif ref[0] == 'CONST' and (isint or isfloat or ischar):
logical = ref[1]
elif isbool:
ref = Expr1(ref, o)
logical = New('int')
o.Raw(logical, ' = PyObject_IsTrue ( ', ref, ' );')
Cls1(o, ref)
elif isint:
ref = Expr1(ref, o)
logical = New('long')
o.Raw('if ((', logical, ' = PyInt_AsLong ( ', ref, ' )) == -1) goto ', labl, ';')
UseLabl()
Cls1(o, ref)
elif ischar:
## print it
## assert False
ref = Expr1(ref, o)
logical = New('char')
o.Raw('if (PyString_AsString ( ', ref, ' ) == 0) goto ', labl, ';')
o.Raw('if (PyString_Size ( ', ref, ' ) != 1) goto ', labl, ';')
o.Raw(logical, ' = *PyString_AsString ( ', ref, ' );')
UseLabl()
Cls1(o, ref)
elif isfloat:
ref = Expr1(ref, o)
logical = New('double')
o.Raw('if ((', logical, ' = PyFloat_AsDouble ( ', ref, ' )) == -1) goto ', labl, ';')
UseLabl()
Cls1(o, ref)
else:
ref = Expr1(ref, o)
if not istempref(ref) and not ( is_current & (IS_DIRECT | IS_CFUNC ) and ref[0] == 'FAST'):
o.INCREF(ref)
if is_current & IS_CODEFUNC:
while len(try_jump) > 0:
if try_jump[-1]:
if type(try_jump[-1]) is list:
o.Comment((')(FINALLY',))
o.append('{')
generate_list(try_jump[-1],o)
o.append('}')
del try_jump[-1]
if is_current & IS_DIRECT:
hid = {}
for i in current_co.hidden_arg_direct:
hid[current_co.co_varnames[i]] = True
for i,v in enumerate(current_co.co_varnames_direct):
if v in hid:
continue
## if v in current_co.all_arg and v not in current_co.changed_arg:
## continue
nmvar = nmvar_to_loc(v)
if isvoid or isbool or isint or isfloat or \
(len(ref) != 2 or ref[0] != 'FAST' or ref[1] != nmvar):
if not current_co.IsCVar(('FAST', v)) and \
(nmvar in current_co.used_fastlocals or current_co.list_compr_in_progress == True):
o.CLEAR('GETLOCAL(' + nmvar + ')')
elif is_current & IS_CFUNC:
for i,v in enumerate(current_co.co_varnames):
nmvar = nmvar_to_loc(v)
if (len(ref) != 2 or ref[0] != 'FAST' or ref[1] != nmvar):
if not current_co.IsCVar(('FAST', v)) and \
(nmvar in current_co.used_fastlocals or current_co.list_compr_in_progress == True):
o.CLEAR('GETLOCAL(' + nmvar + ')')
for i,v in enumerate(current_co.co_freevars):
nmvar = nmvar_to_loc(v)
if isvoid or isbool or (len(ref) != 2 or ref[0] != 'LOAD_CLOSURE' or ref[1] != nmvar):
o.CLEAR('GETFREEVAR(' + nmvar + ')')
PopClearAll(o)
if calc_ref_total:
o.Raw('if ((_Py_RefTotal - l_Py_RefTotal) > 0) {printf ("func ', current_co.co_name, ' delta ref = %d\\n", (int)(_Py_RefTotal - l_Py_RefTotal));}')
if stat_func == func:
o.append('{')
o.append('FILE * _refs = fopen(\"%s_end\", \"w+\");' % func)
o.append('_Py_PrintReferences2(_refs);')
o.append('fclose(_refs);')
o.append('}')
if is_current & IS_CODEFUNC:
if not is_pypy:
o.append('if (tstate->frame->f_exc_type != NULL) {')
PyEval_reset_exc_info(o)
o.append('}')
if check_recursive_call:
o.append('Py_LeaveRecursiveCall();')
if not is_pypy:
o.append('tstate->frame = f->f_back;')
if isvoid:
o.append('return 0;')
elif isbool:
o.Raw('return ', logical, ';')
Cls1(o, logical)
elif isint:
o.Raw('return ', logical, ';')
Cls1(o, logical)
elif ischar:
if istemptyped(logical):
o.Raw('return ', logical, ';')
else:
o.Raw('return ', Char_for_C(logical), ';')
Cls1(o, logical)
elif isfloat:
o.Raw('return ', logical, ';')
Cls1(o, logical)
else:
if IsCVar(it[1]):
if is_current & IS_CALLABLE_COMPILABLE:
o.Stmt('return', ref)
else:
ref3 = New()
CType2Py(o, ref3, logical, TypeExpr(it[1]))
o.Stmt('return', ref3)
o.ClsFict(ref3)
else:
o.Stmt('return', ref)
o.ClsFict(ref)
if is_current & IS_DIRECT:
if tuple(o[place+1:]) in current_co.returns_direct:
rets = current_co.returns_direct[tuple(o[place+1:])]
o[place:] = ['goto ' + rets[1] + ';']
current_co.used_return_labels[rets[1]] = True
return
current_co.returns_direct[tuple(o[place+1:])] = (place, retlabl)
if is_current & IS_CFUNC:
if tuple(o[place+1:]) in current_co.returns_cfunc:
rets = current_co.returns_cfunc[tuple(o[place+1:])]
o[place:] = ['goto ' + rets[1] + ';']
current_co.used_return_labels[rets[1]] = True
return
current_co.returns_cfunc[tuple(o[place+1:])] = (place, retlabl)
return
def del_unused_ret_label(o):
i = 0
while i < len(o):
assert type(i) is int
s = o[i]
if s.startswith('ret_label_') and s.endswith(':;'):
retlabl = s[:-2]
if retlabl not in current_co.used_return_labels:
del o[i]
continue
i += 1
def generate_statement(head, it, o):
global current_co, Line2Addr
if type(it) is not tuple:
Fatal('Not tuple', it)
if head == '.L':
if line_number:
if is_current & IS_DIRECT or is_current & IS_CFUNC:
o.Raw('PyLine = ', str(it[1]), ';')
else:
o.Stmt('f->f_lineno', '=', it[1])
if it[1] in Line2Addr:
if is_current & IS_DIRECT or is_current & IS_CFUNC:
o.Raw('PyAddr = ', str(Line2Addr[it[1]]), ';')
elif not is_pypy:
o.Raw('f->f_lasti = ', str(Line2Addr[it[1]]), ';')
if print_pyline:
o.Stmt('printf', '\"Py:' + filename +':%5d\\n\"', it[1])
return
if head == 'STORE':
if len(it) == 3 and len(it[1]) == 1 and len(it[2]) == 1:
if it[1][0][0] == 'STORE_FAST' and IsCVar(('FAST', it[1][0][1])):
if CSetVariable(o, ('FAST', it[1][0][1]), it[2][0]):
return
elif (it[1][0][0] == 'STORE_GLOBAL' or (it[1][0][0] == 'STORE_NAME' and func == 'Init_filename')) and IsCVar(('!LOAD_GLOBAL', it[1][0][1])):
add_fast_glob(it[1][0][1])
if CSetVariable(o, ('!LOAD_GLOBAL', it[1][0][1]), it[2][0]):
return
if len(it[2]) == 1 and len(it[1]) == 1:
if is_like_float(it[2][0]) and it[2][0][0] != 'CONST':
acc = []
isfloat = {}
if parse_for_float_expr(it[2][0], acc, isfloat):
if len(acc) >= 2 or \
(len(acc) == 1 and acc[0][0] == 'CONST' and \
type(acc[0][1]) is float):
return generate_mixed_float_expr(it,acc,o, isfloat)
acc = detect_repeated_subexpr(it[1][0], it[2][0]).keys()
refs = Expr(o, acc) #[Expr1(x, o) for x in acc]
PushAcc(acc, refs)
## if len(acc) > 0:
## pprint(acc)
ref = Expr1(it[2][0], o)
if it[2][0][0] == 'FAST':
stor = ('STORE_FAST', it[2][0][1])
if repr(stor) in repr(it[1][0]):
ref2 = New()
o.Raw(ref2, ' = ', ref, ';')
o.INCREF(ref2)
ref = ref2
ref2 = None
generate_store(it[1][0], ref, o, it[2][0])
PopAcc(o)
o.Cls(*refs)
Cls1(o, ref)
if ref not in g_refs2:
o.ZeroTemp(ref)
return
Fatal('MultyStore', it)
if head == 'SEQ_ASSIGN':
ref = Expr1(it[2], o)
PushAcc([ref], [ref])
for i in range(len(it[1])-1):
o.INCREF(ref)
for iit in it[1]:
generate_store(iit, ref, o, it[2])
PopAcc(o, False)
Cls1(o, ref)
return
if head == 'SET_EXPRS_TO_VARS':
if len(it[1]) == 2 and it[2][0] == 'CLONE':
ref = Expr1(it[2][1],o)
o.ClsFict(ref)
generate_store(it[1][0], ref, o, it[2][1])
generate_store(it[1][1], ref, o, it[2][1])
if istempref(ref):
o.CLEAR(ref)
return
assert len(it[2]) == len(it[1])
stor = dict.fromkeys([x[0] for x in it[1]]).keys()
srepr = repr(it[2])
if len(stor) == 1 and stor[0] == 'STORE_FAST':
gets = [('FAST', x[1]) for x in it[1]]
gets.extend([('LOAD_FAST', x[1]) for x in it[1]])
pure = True
for ge in gets:
if repr(ge) in srepr:
pure = False
if pure:
for i,iit in enumerate(it[1]):
ref1 = Expr1(it[2][i], o)
generate_store(iit,ref1,o, it[2][i])
Cls1(o, ref1)
return
expr = TupleFromArgs(it[2])
ref = Expr1(expr, o)
its = it[1]
## s_ref = CVar(ref)
for i,iit in enumerate(its):
ref1 = New()
o.Stmt(ref1, '=', 'PyTuple_GET_ITEM', ref, i)
generate_store(iit,ref1,o, ('!PyTuple_GET_ITEM',))
Cls1(o, ref1)
Cls1(o, ref)
return
if head == 'RETURN_VALUE':
generate_return_statement(it, o)
return
if head == 'CALL_PROC':
Fatal('Illegal', it)
return
if head == 'UNPUSH':
if like_append(it[1]):
generate_may_be_append(it[1], o)
return
_v = []
if like_append_const(it[1], _v):
generate_may_be_append_const(it[1], o, _v)
return
if it[1][0] == '!COND_METH_EXPR':
generate_cond_meth_expr_new(it[1], o, None, True)
return
t = TypeExpr(it[1])
if t is not None and t != Kl_None:
if ( IsCType(t) or IsIntUndefSize(t) ) and it[1][0] in ('!PyNumber_Subtract', '!PyNumber_Add', '!PyNumber_And','!PyNumber_Or', '!PyNumber_Divide', '!_EQ_', '!_NEQ_'):
generate_statement('UNPUSH', it[1][1], o)
generate_statement('UNPUSH', it[1][2], o)
return
## print '/3', 'UNPUSH', it[1][0], TypeExpr(it[1])
ref = Expr1(it[1], o)
Cls1(o, ref)
return
if head == 'PYAPI_CALL':
iit = it[1]
gen = []
for i in range(len(iit)):
if i > 0:
if type(iit[i]) is tuple and len(iit[i]) > 0:
gen.append(Expr1(iit[i], o))
else:
gen.append(iit[i])
if iit[0] in CFuncIntCheck:
# Debug('iiy', iit, gen)
args = (iit[0],) + tuple(gen)
o.Stmt(*args)
o.Cls(*gen)
return
elif iit[0] in CFuncVoid:
args = (iit[0],) + tuple(gen)
o.Stmt(*args)
o.Cls(*gen)
return
else:
Fatal('', it)
if head == 'IMPORT_FROM_AS':
if it[3][0] == 'CONST' and len(it[3][1]) == len(it[4]):
ref = Expr1(('!IMPORT_NAME', it[1],it[2],it[3]), o)
for i in range(len(it[4])):
ref1 = New()
o.Raw('if ((', ref1, ' = PyObject_GetAttr( ', ref, ', ', ('CONST', it[3][1][i]), ')) == 0) {')
o.Raw('if (PyErr_ExceptionMatches(PyExc_AttributeError)) {')
o.Raw('PyErr_Format(PyExc_ImportError, ', ('"cannot import name %s"' % it[3][1][i]), ');')
o.append('}')
o.Raw('goto ', labl, ';')
UseLabl()
o.append('}')
generate_store(it[4][i], ref1,o, it)
Cls1(o, ref)
return
Fatal('', it)
return
if head == 'PRINT_ITEM_TO_2':
ref1, ref2 = Expr(o, it[1:])
o.Stmt('_PyEval_PRINT_ITEM_TO_2', ref1, ref2)
o.Cls(ref1, ref2)
return
if head == 'PRINT_ITEM_AND_NEWLINE_TO_2':
ref1, ref2 = Expr(o, it[1:])
o.Stmt('_PyEval_PRINT_ITEM_TO_2', ref1, ref2)
o.Stmt('_PyEval_PRINT_NEWLINE_TO_1', ref1)
o.Cls(ref1, ref2)
return
if head == 'PRINT_ITEM_AND_NEWLINE_TO_3':
ref1, ref2, ref3 = Expr(o, it[1:])
o.Stmt('_PyEval_PRINT_ITEM_TO_2', ref1, ref2)
o.Stmt('_PyEval_PRINT_ITEM_TO_2', ref1, ref3)
o.Stmt('_PyEval_PRINT_NEWLINE_TO_1', ref1)
o.Cls(ref1, ref2, ref3)
return
if head == 'PRINT_ITEM_1':
ref1 = Expr1(it[1], o)
o.Stmt('_PyEval_PRINT_ITEM_1', ref1)
Cls1(o, ref1)
return
if head == 'PRINT_NEWLINE_TO_1':
ref1 = Expr1(it[1], o)
o.Stmt('_PyEval_PRINT_NEWLINE_TO_1', ref1)
Cls1(o, ref1)
return
if head == 'PRINT_NEWLINE':
o.Stmt('_PyEval_PRINT_NEWLINE_TO_1', 'NULL')
return
if head == 'DELETE_ATTR_2':
ref1, ref2 = Expr(o, it[1:])
o.Stmt('PyObject_SetAttr', ref1, ref2, 'NULL')
o.Cls(ref1, ref2)
return
if head == 'DELETE_SUBSCR':
t = TypeExpr(it[1])
t_ind = TypeExpr(it[2])
if IsList(t) and IsInt(t_ind):
ref1 = Expr1(it[1],o)
o2,ind1 = shortage(generate_ssize_t_expr(it[2]))
o.extend(o2)
if type(ind1) is int:
if ind1 < 0:
ind2 = New('long')
o.Raw(ind2, ' = PyList_GET_SIZE(', ref1, ');')
_ind1 = New('long')
o.Stmt(_ind1, '=', ind1, '+', ind2)
ind1 = _ind1
else:
ind2 = ind1 + 1
elif ind1[0] == 'CONST':
if ind1[1] < 0:
ind2 = New('long')
o.Raw(ind2, ' = PyList_GET_SIZE(', ref1, ');')
_ind1 = New('long')
o.Stmt(_ind1, '=', ind1[1], '+', ind2)
ind1 = _ind1
else:
ind1, ind2 = ind1[1], ind1[1]+1
else:
ind2 = New('long')
o.Raw(ind2, ' = PyList_GET_SIZE(', ref1, ');')
if not istemptyped(ind1):
ind_ = New('long')
o.Raw(ind_, ' = ', ind1, ';')
ind1 = ind_
o.Stmt('if (', ind1, '< 0) {')
o.Stmt(ind1, '=', ind1, '+', ind2)
o.append('}')
if type(ind2) is not int:
o.Stmt(ind2, '=', ind1, '+', 1)
o.Stmt('PyList_SetSlice', ref1, ind1, ind2, 'NULL')
o.Cls(ref1, ind1, ind2)
return
if t is not None and t != Kl_Dict:
Debug('Typed ' + head, t, it)
ref1, ref2 = Expr(o, it[1:])
if IsDict(t):
o.Stmt('PyDict_DelItem', ref1, ref2)
else:
o.Stmt('PyObject_DelItem', ref1, ref2)
o.Cls(ref1, ref2)
return
if head == 'DELETE_SLICE+0':
t = TypeExpr(it[1])
if IsList(t):
assign_list_slice(it, o, 'NULL')
return
if t is not None:
Debug('Typed ' + head, t, it)
ref1 = Expr1(it[1], o)
o.Stmt('PySequence_DelSlice', ref1, 0, 'PY_SSIZE_T_MAX')
## o.Stmt('_PyEval_AssignSlice', ref1, 'NULL', 'NULL', 'NULL')
Cls1(o, ref1)
return
if head == 'DELETE_SLICE+1':
t = TypeExpr(it[1])
if IsList(t):
assign_list_slice(it, o, 'NULL')
return
if t is not None:
Debug('Typed ' + head, t, it)
ref1, ref2 = Expr(o, it[1:])
if isintconst(ref2):
o.Stmt('PySequence_DelSlice', ref1, ref2[1], 'PY_SSIZE_T_MAX')
else:
o.Stmt('_PyEval_AssignSlice', ref1, ref2, 'NULL', 'NULL')
o.Cls(ref1, ref2)
return
if head == 'DELETE_SLICE+2':
t = TypeExpr(it[1])
if t is not None:
Debug('Typed ' + head, t, it)
ref1, ref2 = Expr(o, it[1:])
if isintconst(ref2):
o.Stmt('PySequence_DelSlice', ref1, 0, ref2[1])
else:
o.Stmt('_PyEval_AssignSlice', ref1, 'NULL', ref2, 'NULL')
o.Cls(ref1, ref2)
return
if head == 'DELETE_SLICE+3':
t = TypeExpr(it[1])
if t is not None:
Debug('Typed ' + head, t, it)
ref1, ref2, ref3 = Expr(o, it[1:])
if isintconst(ref2) and isintconst(ref3):
o.Stmt('PySequence_DelSlice', ref1, ref2[1], ref3[1])
else:
o.Stmt('_PyEval_AssignSlice', ref1, ref2, ref3, 'NULL')
o.Cls(ref1, ref2, ref3)
return
if head == 'DELETE_GLOBAL':
if build_executable and it[1] not in d_built and it[1][0] != '_' and \
not redefined_all and not global_used_at_generator(it[1]):
add_fast_glob(it[1])
o.Stmt('SETSTATIC', it[1], 'NULL')
return
ref1 = Expr1(('CONST', it[1]),o)
o.Stmt('PyDict_DelItem', ('glob',), ref1)
Cls1(o, ref1)
return
if head == 'CONTINUE':
if try_jump_context[-1]:
if type(try_jump_context[-1]) is list:
o.Comment((')(FINALLY',))
o.append('{')
generate_list(try_jump_context[-1],o)
o.append('}')
## o.Stmt('PyFrame_BlockPop', 'f')
o.append('continue;')
return
if head == 'BREAK_LOOP':
if try_jump_context[-1]:
if type(try_jump_context[-1]) is list:
o.Comment((')(FINALLY',))
o.append('{')
generate_list(try_jump_context[-1],o)
o.append('}')
## o.Stmt('PyFrame_BlockPop', 'f')
o.append('break;')
return
if head == 'EXEC_STMT_3':
current_co.Use_all_fastlocals()
r1, r2, r3 = Expr(o, it[1:])
plain = False
if r2 == ('CONST', None) == r3:
if it[1][0] == '!BUILD_TUPLE' and len(it[1][1]) in (2,3):
pass
else:
r2 = 'glob'
o.append('PyFrame_FastToLocals(f);')
r3 = 'f->f_locals'
plain = True
if r2 != ('CONST', None) and ('CONST', None) == r3:
r3 = r2
## o.INCREF(r1)
## o.INCREF(r2)
## o.INCREF(r3)
o.Stmt('_PyEval_ExecStatement', 'f', r1,r2,r3)
if plain:
o.append('PyFrame_LocalsToFast(f, 0);')
## o.DECREF(r1)
## o.DECREF(r2)
## o.DECREF(r3)
o.Cls(r1, r2, r3)
return
if head == 'DELETE_NAME':
ref1 = Expr1(('CONST', it[1]),o)
o.Stmt('PyObject_DelItem', 'f->f_locals', ref1)
Cls1(o, ref1)
return
if head == 'RAISE_VARARGS_STMT' or head == 'RAISE_VARARGS':
assert it[1] == 0
if len(it) < 3:
refn = []
else:
refn = Expr(o, it[2])
while len(refn) < 3:
refn.append('NULL')
assert len(refn) == 3
if refn[0] != 'NULL':
o.INCREF(refn[0])
if refn[1] != 'NULL':
o.INCREF(refn[1])
if refn[2] != 'NULL':
o.INCREF(refn[2])
o.Stmt('_PyEval_DoRaise', refn[0], refn[1], refn[2])
# if not istempref(refn[0]):
o.Cls(*refn)
o.Stmt('goto', labl)
UseLabl()
return
if head == 'IMPORT_STAR':
current_co.Use_all_fastlocals()
o.Stmt('PyFrame_FastToLocals', 'f')
ref1 = Expr1(it[1],o)
o.Stmt('_PyEval_ImportAllFrom', 'f->f_locals', ref1);
o.Stmt('PyFrame_LocalsToFast', 'f', 0)
Cls1(o, ref1)
return
if head == 'DELETE_FAST':
o.Stmt('SETLOCAL', it[1], 'NULL')
return
if head == 'PASS':
pass
return
Fatal('HEAD', head, it)
def like_append(it):
v = []
return TCmp(it,v,('!PyObject_Call', ('!PyObject_GetAttr', '?', ('CONST', 'append')),\
('!BUILD_TUPLE', ('?',)), ('NULL',)))
def like_append_const(it, v):
return TCmp(it,v,('!PyObject_Call', ('!PyObject_GetAttr', '?', ('CONST', 'append')),\
('CONST', ('?',)), ('NULL',)))
## try:
## return it[0] == '!PyObject_Call' and it[1][0] == '!PyObject_GetAttr' and\
## it[1][2][0] == 'CONST' and it[1][2][1] == 'append' and \
## it[2][0] == '!BUILD_TUPLE' and len(it[2][1]) == 1 and \
## len(it[2]) == 2 and it[3][0] == 'NULL'
## except:
## pass
## return False
def generate_may_be_append(it, o):
ref_list = Expr1(it[1][1], o)
ref_value = Expr1(it[2][1][0], o)
t = TypeExpr(it[1][1])
islist = False
if t is None:
pass
elif IsList(t):
islist = True
elif t[0] == T_NEW_CL_INST and Is3(t[1], 'Derived', ('!LOAD_BUILTIN', 'list')):
islist = True
_generate_may_be_append(ref_list, ref_value, o, islist)
o.Cls(ref_value, ref_list)
def generate_may_be_append_const(it, o, v):
ref_list = Expr1(v[0], o)
## ref_value = Expr1(it[2][1][0], o)
t = TypeExpr(v[0])
islist = False
if t is None:
pass
elif IsList(t):
islist = True
elif t[0] == T_NEW_CL_INST and Is3(t[1], 'Derived', ('!LOAD_BUILTIN', 'list')):
islist = True
_generate_may_be_append_const(ref_list, v[1], o, islist)
Cls1(o, ref_list)
def _generate_may_be_append_const(ref_list, v1, o, islist = False):
if not islist:
o.Stmt('if (PyList_Check(', ref_list, ')) {')
o.Stmt('PyList_Append', ref_list, ('CONST', v1))
if not islist:
o.append('} else {')
ref_attr = New()
o.Stmt(ref_attr, '=', 'PyObject_GetAttr', ref_list, ('CONST', 'append'))
ref_return = New()
o.Stmt(ref_return, '=', 'FirstCFunctionCall', ref_attr, ('CONST', (v1,)), ('NULL',))
o.Cls(ref_return, ref_attr)
o.append('}')
def _generate_may_be_append(ref_list, ref_value, o, islist = False):
if not islist:
o.Stmt('if (PyList_Check(', ref_list, ')) {')
o.Stmt('PyList_Append', ref_list, ref_value)
if not islist:
o.append('} else {')
ref_attr = New()
o.Stmt(ref_attr, '=', 'PyObject_GetAttr', ref_list, ('CONST', 'append'))
ref_tuple = New()
o.Stmt(ref_tuple, '=', 'PyTuple_New', 1)
o.INCREF(ref_value)
o.Stmt('PyTuple_SET_ITEM', ref_tuple, 0, ref_value)
ref_return = New()
o.Stmt(ref_return, '=', 'FirstCFunctionCall', ref_attr, ref_tuple, ('NULL',))
o.Cls(ref_return, ref_tuple, ref_attr)
o.append('}')
def _detect_r_subexpr(e, acc2):
if not (type(e) is tuple) or len(e) == 0 or \
e[0] in ('CONST', 'FAST', 'CALC_CONST', 'TYPED_TEMP', '!@PyInt_FromSsize_t'):
return
if type(e) is tuple and len(e) > 0 and e[0] == 'PY_TYPE':
return _detect_r_subexpr(e[3], acc2)
if e in acc2:
acc2[e] = acc2[e] + 1
else:
acc2[e] = 1
if type(e) is tuple and len(e) > 0:
if e[0] == '!BUILD_MAP':
e = e[1]
for i,it in enumerate(e):
if i == 0 or not (type(it[0]) is tuple) or len(it[0]) == 0 or \
it[0][0] in ('CONST', 'FAST', 'CALC_CONST', 'TYPED_TEMP', '!@PyInt_FromSsize_t'):
pass
else:
_detect_r_subexpr(it[0], acc2)
if i == 0 or not (type(it[1]) is tuple) or len(it[1]) == 0 or \
it[1][0] in ('CONST', 'FAST', 'CALC_CONST', 'TYPED_TEMP', '!@PyInt_FromSsize_t'):
pass
else:
_detect_r_subexpr(it[1], acc2)
return
if e[0] in ('!BUILD_LIST', '!BUILD_TUPLE'):
e = e[1]
for i,it in enumerate(e):
acc2[it] = -100000
for i,it in enumerate(e):
if i == 0 or not (type(it) is tuple) or len(it) == 0 or \
it[0] in ('CONST', 'FAST', 'CALC_CONST', 'TYPED_TEMP', '!@PyInt_FromSsize_t'):
continue
_detect_r_subexpr(it, acc2)
return
def cond_in_expr(e):
s_repr_e = repr(e)
return 'AND' in s_repr_e or 'OR' in s_repr_e or 'COND' in s_repr_e
def detect_repeated_subexpr(store, expr):
acc2 = {}
if cond_in_expr(expr):
return {}
_detect_r_subexpr(expr,acc2)
if len(store) > 0 and store[0] in ('PyObject_SetItem', 'PyObject_SetAttr'):
if cond_in_expr(store[1]) or cond_in_expr(store[2]):
return {}
_detect_r_subexpr(store[1],acc2)
_detect_r_subexpr(store[2],acc2)
d = {}
for k,v in acc2.iteritems():
if v > 1:
d[k] = v
todel = {}
for k,v in d.iteritems():
if k[0] in ('!BUILD_LIST', '!BUILD_TUPLE', '!BUILD_MAP', 'CONST', \
'!CLASS_CALC_CONST', '!CLASS_CALC_CONST_NEW', \
'!PyObject_Call', '!FirstCFunctionCall', '!FastCall') or k[0] != '!from_ceval_BINARY_SUBSCR':
todel[k] = True
else:
## pprint(k)
try:
t = TypeExpr(k)
except:
t = None
# if not IsIntOrFloat(t):
todel[k] = True
for k in todel.keys():
del d[k]
todel = {}
for k,v in d.iteritems():
s_repr_k = repr(k)
for k1,v1 in d.iteritems():
if k != k1 and repr(k1) in s_repr_k and v1 == v:
todel[k1] = True
for k in todel.keys():
del d[k]
return d
def find_common_subexpr_for_float(it,acc):
d = detect_repeated_subexpr(it[1][0], it[2][0])
subfloat = {}
upfloat = {}
todel = {}
for k in d.iterkeys():
for x in acc:
if k == x:
todel[k] = True
for k in todel.keys():
del d[k]
for k in d.iterkeys():
s_repr_k = repr(k)
for x in acc:
s_repr_x = repr(x)
if s_repr_k in s_repr_x:
subfloat[k] = subfloat.get(k,0) + 1
if s_repr_x in s_repr_k:
upfloat[k] = upfloat.get(k,0) + 1
# k1 and k2 is uniq => todel is uniq
#--
# I don't know... And I don't
for k in [k1 for k1 in upfloat.iterkeys() \
for k2 in subfloat.iterkeys() if k1 == k2]:
del subfloat[k]
del upfloat[k]
return subfloat.keys()
def generate_mixed_float_expr(it,acc,o,isfloat):
assert (it[1] is None or len(it[1]) == 1) and len(it[2]) == 1
acc_subfloat = find_common_subexpr_for_float(it,acc)
refs_subfloat = Expr(o, acc_subfloat) #[Expr1(x, o) for x in acc_subfloat]
PushAcc(acc_subfloat, refs_subfloat)
refs = Expr(o, acc) #[Expr1(x, o) for x in acc]
PopAcc(o)
seq = 'if ('
for i,x in enumerate(refs):
if x[0] != 'CONST' and not IsFloat(TypeExpr(acc[i])) :
seq = seq + 'PyFloat_CheckExact(' + CVar(x) + ')'
seq = seq + ' && '
if seq == 'if (':
seq = 'if (1) {'
else:
seq = seq[:-4] + ') {'
o.append(seq)
floats = []
for x in refs:
if x[0] == 'CONST':
if hasattr(math, 'isnan') and math.isnan(x[1]):
if not '-' in str(x[1]):
floats.append('Py_NAN')
else:
floats.append('(-(Py_NAN))')
elif hasattr(math, 'isinf') and math.isinf(x[1]):
if not '-' in str(x[1]):
floats.append('Py_HUGE_VAL')
else:
floats.append('-Py_HUGE_VAL')
else:
floats.append(x)
else:
floats.append(New('double'))
text_floats = []
for x in floats:
if x[0] == 'CONST':
text_floats.append(str(x[1]))
else:
text_floats.append(CVar(x))
for i, x in enumerate(floats):
if istemptyped(x):
o.Stmt(x, '=', 'PyFloat_AS_DOUBLE', refs[i])
float_seq = generate_float_expr(it[2][0], acc, text_floats)
ref = New()
o.Stmt(ref, '=', 'PyFloat_FromDouble', float_seq)
o.Cls(*floats)
o.append('} else {')
PushAcc(acc_subfloat+acc, refs_subfloat+refs)
if len(floats) <= 2:
ref = GenExpr(it[2][0], o, ref,None,True)
else:
ref = GenExpr(it[2][0], o, ref)
PopAcc(o, False)
o.append('}')
o.Cls(*refs)
PushAcc(acc_subfloat, refs_subfloat)
if it[1] is not None:
generate_store(it[1][0], ref, o, acc)
PopAcc(o, False)
o.Cls(*refs_subfloat)
if it[1] is not None:
Cls1(o, ref)
else:
return ref
return
def generate_compaund_statement(head,it,o):
if head == 'IF':
generate_if(it,o)
return
if head == 'PREEXPR':
generate_preexpr(it,o)
return
if head == 'WHILE':
prev_compr = current_co.list_compr_in_progress
current_co.list_compr_in_progress = True
generate_while(it,o)
current_co.list_compr_in_progress = prev_compr
return
if head == 'FOR':
prev_compr = current_co.list_compr_in_progress
current_co.list_compr_in_progress = True
## current_co.Use_all_fastlocals()
generate_for_new(it,o)
current_co.list_compr_in_progress = prev_compr
return
if head == 'TRY':
current_co.Use_all_fastlocals()
if attempt_iteration_try(it, o):
return
generate_try(it,o)
return
if head == 'TRY_FINALLY':
current_co.Use_all_fastlocals()
generate_try_finally(it,o)
return
if head == 'WITH':
current_co.Use_all_fastlocals()
generate_with(it,o)
return
Fatal('', it)
def generate_with(it,o):
global try_jump_context, dropped_temp
global traced_tempgen
## raised = None
try_j = try_jump_context[:]
assert len(it) == 3 and it[2] == (')ENDWITH',) and len(it[0]) == 3 and it[0][0] == '(WITH'
r0 = Expr1(it[0][1], o)
o.INCREF(r0)
r1 = New()
r2 = New()
ref1 = New()
if tuple(sys.version_info)[:2] < (2,7):
o.Raw('if ((', r1, ' = PyObject_GetAttr(', r0, ', ', ('CONST', '__enter__'), ')) == 0) goto ', labl, ';')
o.Raw('if ((', r2, ' = PyObject_GetAttr(', r0, ', ', ('CONST', '__exit__'), ')) == 0) goto ', labl, ';')
else:
o.Raw('if ((', r1, ' = from_ceval_2_7_special_lookup(', r0, ', "__enter__", &from_ceval_2_7_enter)) == 0) goto ', labl, ';')
o.Raw('if ((', r2, ' = from_ceval_2_7_special_lookup(', r0, ', "__exit__", &from_ceval_2_7_exit)) == 0) goto ', labl, ';')
Used('from_ceval_2_7_special_lookup')
o.Raw('if ((', ref1, ' = PyObject_Call(', r1, ', ', ('CONST', ()), ', NULL)) == 0) goto ', labl, ';')
Cls1(o, r1)
if it[0][2] == ():
pass
elif len(it[0][2]) == 1 and it[0][2][0][0] in set_any:
generate_store(it[0][2][0], ref1, o, 'Store clause at WITH statement')
elif it[0][2][0] == 'SET_VARS':
generate_store(it[0][2], ref1, o, 'Multy store clause at WITH statement')
elif len(it[0][2]) == 2 and it[0][2][0] in set_any:
generate_store(it[0][2], ref1, o, 'Store clause at WITH statement')
elif len(it[0][2]) == 3 and it[0][2][0] in ('PyObject_SetAttr', 'PyObject_SetItem'):
generate_store(it[0][2], ref1, o, 'Store clause at WITH statement')
else:
Fatal('WITH error', len(it[0][2]), it[0][2], it)
Cls1(o, ref1)
## if it[1] == [('PASS',)]:
## ref2 = New()
## o.Raw('if ((', ref2, ' = PyObject_Call(', r2, ', ', ('CONST', (None,None,None)), ', NULL)) == 0) goto ', labl, ';')
## UseLabl()
## o.Cls(r2, ref2, r0)
## try_jump_context[:] = try_j
## return
try_jump_context.append(True)
o.append('{')
label_exc = New('label')
global traced_tempgen
a,b,c = New(), New(), New()
o.Stmt('PyErr_Fetch', ('&', a), ('&', b), ('&', c))
set_toerr_new(o, label_exc)
o.XINCREF(a)
o.XINCREF(b)
o.XINCREF(c)
## o.Stmt('PyFrame_BlockSetup', 'f', 'SETUP_EXCEPT',-1, -1)
dropped_temp.append(('WITH', (ref1, r2, a,b,c)))
traced_tempgen.append({})
generate_list(it[1],o)
traced_temp = traced_tempgen[-1].keys()
del traced_tempgen[-1]
if len(traced_tempgen) > 0:
for k in traced_temp:
traced_tempgen[-1][k] = True
## o.Stmt('PyFrame_BlockPop', 'f')
set_toerr_back(o)
o.Stmt('PyErr_Restore', a,b,c)
ref2 = New()
o.Raw('if ((', ref2, ' = PyObject_Call(', r2, ', ', ('CONST', (None,None,None)), ', NULL)) == 0) goto ', labl, ';')
bool_ret = None
## o.Cls(ref2, r2)
UseLabl()
raised = None
## ref2 = Expr1(('!PyObject_Call', r2, ('CONST', (None,None,None)), 'NULL'),o)
if IsUsedLabl(label_exc):
raised = New('int')
o.Raw(raised, ' = 0;')
o.Stmt('if (0) { ', label_exc, ':')
o.Stmt(raised, '=', 1)
o.append('PyTraceBack_Here(f);')
generate_clear_temp_on_exception(o, traced_temp)
ae,be,ce = get_exc_info(o)
o.XINCREF(ae)
o.XINCREF(be)
o.XINCREF(ce)
tupl = New()
o.Raw(tupl, ' = PyTuple_Pack(3, ', ae, ', ', be, ', ', ce, ');')
ref2 = New()
o.Raw('if ((', ref2, ' = PyObject_Call(', r2, ', ', tupl, ', NULL)) == 0) goto ', labl, ';')
o.Cls(tupl, r2)
bool_ret = New('int')
o.Raw('if (', ref2, ' == Py_None) ', bool_ret, ' = 0;')
o.Raw('else {')
o.Raw('if ((', bool_ret, ' = PyObject_IsTrue(', ref2, ')) == -1) goto ', labl, ';')
o.append('}')
Cls1(o, ref2)
UseLabl()
## o.Stmt('PyFrame_BlockPop', 'f')
o.Raw('if (', bool_ret, ') {')
o.Stmt('PyErr_Restore', a,b,c)
PyEval_reset_exc_info(o)
o.append('} else {')
o.Stmt('PyErr_Restore', ae,be,ce)
o.append('}')
o.Cls(ae, be, ce)
## o.Stmt('PyErr_Restore', a,b,c)
o.append('}')
o.append('}')
o.DECREF(r0)
o.Cls(ref2, a, b, c, r0, r2, r1)
# o.Cls(*refs)
if raised is not None:
o.Raw('if (', raised, ' && !', bool_ret,') { goto ',labl, '; }')
UseLabl()
o.Cls(raised, bool_ret)
set_toerr_final(o)
del dropped_temp[-1]
try_jump_context[:] = try_j
return
def attempt_iteration_try(it, o):
if len(it) != 5:
return False
body = it[1]
exc = it[2]
handle = it[3]
while len(body) > 0 and body[0][0] == '.L':
body = body[1:]
if len(body) == 0:
return False
stmt = body[0]
no_append = False
iter = None
if stmt[0] == 'STORE':
if len(stmt[1]) != 1 or len(stmt[2]) != 1:
return False
action = stmt[2][0]
iter = is_attr_next_call(action)
if iter == False:
return False
no_append = True
elif 'next' in repr(stmt):
if stmt[0] != 'UNPUSH':
return False
if not like_append(stmt[1]):
return False
## expr_list = stmt[1][1][1]
expr_value = stmt[1][2][1][0]
iter = is_attr_next_call(expr_value)
if iter == False:
return False
no_append = False
if exc[0] != ')(EXCEPT':
return False
if len(exc) >= 3 and exc[2] != ():
return False
if len(exc) < 2:
return False
excarg = exc[1]
if len(excarg) == 2:
if type(excarg[1]) is int:
excarg = (excarg[0],)
if len(excarg) == 1 and type(excarg) is tuple:
excarg = excarg[0]
if len(excarg) != 2:
return False
if excarg[1] != 'StopIteration':
return False
if iter is None:
return False
ref_iter = Expr1(iter,o)
o.Stmt('if (PyIter_Check(', ref_iter, ')) {')
val_iter = New()
o.Stmt(val_iter, '=', 'PyIter_Next', ref_iter)
o.Raw('if (PyErr_Occurred()) goto ', labl, ';')
UseLabl()
o.Stmt('if (', val_iter, '!= NULL ) {')
Cls1(o, ref_iter)
if no_append:
generate_store(stmt[1][0], val_iter, o, stmt)
o.ZeroTemp(val_iter)
else:
ref_list = Expr1(stmt[1][1][1], o)
_generate_may_be_append(ref_list, val_iter, o, IsList(TypeExpr(stmt[1][1][1])))
Cls1(o, ref_list)
Cls1(o, val_iter)
generate_list(body[1:], o)
o.append('} else {')
generate_list(handle, o)
o.append('}')
o.append('} else {')
generate_try(it, o)
o.append('}')
return True
def is_attr_next_call(action):
if action[0] != '!PyObject_Call':
return False
if len(action[2]) != 2:
return False
if action[2][0] != 'CONST':
return False
if action[2][1] != ():
return False
if len(action[3]) != 1:
return False
if action[3][0] != 'NULL':
return False
if len(action[1]) != 3:
return False
if action[1][0] != '!PyObject_GetAttr':
return False
if len(action[1][2]) != 2:
return False
if action[1][2][0] != 'CONST':
return False
if action[1][2][1] != 'next':
return False
return action[1][1]
def generate_try(it,o2):
global try_jump_context, dropped_temp, Line2Addr, line_number
o = Out()
else_cod = None
i = 2
while i < len(it):
assert type(i) is int
if it[i][0] == ')(EXCEPT':
i += 2
continue
elif it[i][0] == ')(ELSE':
else_cod = it[i+1]
del it[i]
del it[i]
continue
elif it[i][0] == ')ENDTRY':
del it[i]
else:
Fatal('', it, i, it[i])
try_jump_context.append(True)
## o.append('{')
to_else = New('int')
o.Stmt(to_else, '=', 1)
label_exc = New('label')
global traced_tempgen
a = New()
b = New()
c = New()
o.Stmt('PyErr_Fetch', ('&', a), ('&', b), ('&', c))
dropped_temp.append(('TRY', (a,b,c)))
## o.XINCREF(a)
## o.XINCREF(b)
## o.XINCREF(c)
set_toerr_new(o, label_exc)
## o.Stmt('PyFrame_BlockSetup', 'f', 'SETUP_EXCEPT',-1, -1)
traced_tempgen.append({})
generate_list(it[1],o)
traced_temp = traced_tempgen[-1].keys()
del traced_tempgen[-1]
if len(traced_tempgen) > 0:
for k in traced_temp:
traced_tempgen[-1][k] = True
## o.Stmt('PyFrame_BlockPop', 'f')
set_toerr_back(o)
o.Stmt('PyErr_Restore', a,b,c)
a1,b1,c1 = None,None,None
i = 2
## first_except = True
if not IsUsedLabl(label_exc):
del try_jump_context[-1]
if else_cod is not None:
o.Comment((')(ELSE',))
o.Stmt('if (', to_else, ') {')
generate_list(else_cod,o)
o.append('}')
o.Cls(a, b, c)
## if else_cod is not None:
Cls1(o, to_else)
set_toerr_final(o)
try_opt(o, to_else)
o2.extend(o)
del dropped_temp[-1]
return None
global tempgen
o.Stmt('if (0) { ', label_exc, ':')
if is_current & IS_CODEFUNC:
o.append('PyTraceBack_Here(f);')
else:
cod = const_to(current_co)
Used('Direct_AddTraceback')
if line_number:
o.Raw('Direct_AddTraceback((PyCodeObject *)', cod, ', PyLine, PyAddr);')
else:
o.Raw('Direct_AddTraceback((PyCodeObject *)', cod, ', 0, 0);')
## to_else = New('int')
## o.Stmt(to_else, '=', 1)
# finally_cod = None
handled = False
generate_clear_temp_on_exception(o, traced_temp)
while i < len(it):
assert type(i) is int
if it[i][0] == ')(EXCEPT' and len(it[i]) == 1:
o.Comment(it[i])
## if else_cod is not None:
o.Raw('if (', to_else, ') {')
ae,be,ce = get_exc_info(o)
o.Cls(ae, be, ce)
## o.Stmt('PyFrame_BlockPop', 'f')
o.Stmt('PyErr_Restore', a,b,c)
o.Stmt(to_else, '=', 0)
generate_list(it[i+1],o)
PyEval_reset_exc_info(o)
o.append('}')
handled = True
i += 2
continue
if it[i][0] == ')(EXCEPT' and len(it[i]) > 1:
if ((len (it[i][1]) == 2 and type(it[i][1][1]) is int) or len (it[i][1]) == 1) and \
len(it[i][2]) == 0:
iti = it[i]
o.Comment(iti)
## assert not is_current & IS_DIRECT and not is_current & IS_CFUNC
o.Raw('if (', to_else, ') {')
if len (iti[1]) == 2 and type(iti[1][1]) is int:
if line_number:
if is_current & IS_CODEFUNC:
o.Stmt('f->f_lineno', '=', iti[1][1])
else:
o.Raw('PyLine = ', str(iti[1][1]), ';')
if iti[1][1] in Line2Addr:
if is_current & IS_CODEFUNC:
if not is_pypy:
o.Raw('f->f_lasti = ', str(Line2Addr[iti[1][1]]), ';')
else:
o.Raw('PyAddr = ', str(Line2Addr[iti[1][1]]), ';')
ref_ = Expr1(iti[1][0],o)
ref1 = New('int')
o.Stmt(ref1, '=', 'PyErr_ExceptionMatches', ref_)
Cls1(o, ref_)
o.Stmt('if (', ref1, ') {')
ae,be,ce = get_exc_info(o)
o.Cls(ae, be, ce)
## o.Stmt('PyFrame_BlockPop', 'f')
o.Stmt('PyErr_Restore', a,b,c)
o.Stmt(to_else, '=', 0)
generate_list(it[i+1],o)
PyEval_reset_exc_info(o)
o.append('}')
Cls1(o, ref1)
o.append('}')
i += 2
continue
if ((len (it[i][1]) == 2 and type(it[i][1][1]) is int) or len (it[i][1]) == 1) and \
len(it[i][2]) >= 1:
iti = it[i]
o.Comment(iti)
## assert not is_current & IS_DIRECT and not is_current & IS_CFUNC
o.Raw('if (', to_else, ') {')
if len (iti[1]) == 2 and type(iti[1][1]) is int:
if is_current & IS_DIRECT or is_current & IS_CFUNC:
o.Raw('PyLine = ', str(iti[1][1]), ';')
else:
o.Stmt('f->f_lineno', '=', iti[1][1])
if iti[1][1] in Line2Addr:
if is_current & IS_DIRECT or is_current & IS_CFUNC:
o.Raw('PyAddr = ', str(Line2Addr[iti[1][1]]), ';')
elif not is_pypy:
o.Raw('f->f_lasti = ', str(Line2Addr[iti[1][1]]), ';')
ref_ = Expr1(iti[1][0],o)
ref1 = New('int')
o.Stmt(ref1, '=', 'PyErr_ExceptionMatches', ref_)
Cls1(o, ref_)
o.Stmt('if (', ref1, ') {')
ae,be,ce = get_exc_info(o)
if len(it[i][2]) == 1 and it[i][2][0][0] in set_any:
generate_store(it[i][2][0], be, o, 'Object Exception')
elif len(it[i][2]) >= 1 and it[i][2][0] == 'UNPACK_SEQ_AND_STORE':
generate_store(it[i][2], be, o, 'Object Exception')
else:
Fatal('TRY error', it[i])
o.Cls(ae, be, ce)
## o.Stmt('PyFrame_BlockPop', 'f')
o.Stmt('PyErr_Restore', a,b,c)
## if else_cod is not None:
o.Stmt(to_else, '=', 0)
generate_list(it[i+1],o)
PyEval_reset_exc_info(o)
o.append('}')
Cls1(o, ref1)
o.append('}')
i += 2
continue
Fatal('TRY error', it[i], it[i][0], it[i][1], it[i][1][0], it[i][2], it[i][2][0])
else:
Fatal('', it, i, it[i])
del try_jump_context[-1]
## if not handled:
## assert not is_current & IS_DIRECT and not is_current & IS_CFUNC
## o.Stmt('if (', to_else, ') {')
## o.Stmt('PyFrame_BlockPop', 'f')
#### o.Stmt('PyErr_Restore', a,b,c)
## o.append('}')
if not handled and else_cod is None:
## assert not is_current & IS_DIRECT and not is_current & IS_CFUNC
o.Stmt('if (', to_else, ') {')
o.Stmt('goto', labl)
UseLabl()
o.append('}')
o.append('}')
if else_cod is not None:
o.Comment((')(ELSE',))
o.Stmt('if (', to_else, ') {')
generate_list(else_cod,o)
o.append('}')
## handled = True
global tempgen
o.Cls(a, b, c)
o.Cls(a1, b1, c1)
## PyEval_reset_exc_info(o)
del dropped_temp[-1]
if else_cod is not None:
Cls1(o, to_else)
set_toerr_final(o)
try_opt(o, to_else)
o2.extend(o)
def PyEval_reset_exc_info(o):
if is_current & IS_DIRECT or is_current & IS_CFUNC or is_pypy:
o.Stmt('_PyEval_reset_exc_info', 'PyThreadState_GET()')
else:
o.Stmt('_PyEval_reset_exc_info', 'f->f_tstate')
def PyEval_set_exc_info(o, ae, be, ce):
if is_current & IS_DIRECT or is_current & IS_CFUNC or is_pypy:
o.Stmt('_PyEval_set_exc_info', 'PyThreadState_GET()', ae, be, ce)
else:
o.Stmt('_PyEval_set_exc_info', 'f->f_tstate', ae, be, ce)
def try_opt(o, to_else):
may_be_append_to_o([], repr(o), 'int', ConC(to_else), o, False)
def generate_try_finally(it,o2):
global try_jump_context, dropped_temp
o = Out()
while 2 < len(it):
if it[2][0] == ')ENDTRY_FINALLY':
del it[2]
elif it[2][0] == ')(FINALLY':
finally_cod = it[2+1]
del it[2]
del it[2]
continue
else:
Fatal('', it, 2, it[2])
try_jump_context.append(finally_cod)
## o.append('{')
label_exc = New('label')
global traced_tempgen
a = New()
b = New()
c = New()
o.Stmt('PyErr_Fetch', ('&', a), ('&', b), ('&', c))
dropped_temp.append(('TRY', (a,b,c)))
## o.XINCREF(a)
## o.XINCREF(b)
## o.XINCREF(c)
set_toerr_new(o, label_exc)
## o.Stmt('PyFrame_BlockSetup', 'f', 'SETUP_FINALLY',-1, -1)
traced_tempgen.append({})
generate_list(it[1],o)
traced_temp = traced_tempgen[-1].keys()
del traced_tempgen[-1]
if len(traced_tempgen) > 0:
for k in traced_temp:
traced_tempgen[-1][k] = True
## o.Stmt('PyFrame_BlockPop', 'f')
set_toerr_back(o)
o.Stmt('PyErr_Restore', a,b,c)
a1,b1,c1 = None,None,None
## first_except = True
if not IsUsedLabl(label_exc):
del try_jump_context[-1]
generate_list(finally_cod,o)
o.Cls(a, b, c)
set_toerr_final(o)
o2.extend(o)
del dropped_temp[-1]
return None
global tempgen
raised = New('int')
o.Stmt(raised, '=', 0)
o.Stmt('if (0) { ', label_exc, ':')
if is_current & IS_CODEFUNC:
o.append('PyTraceBack_Here(f);')
else:
cod = const_to(current_co)
Used('Direct_AddTraceback')
if line_number:
o.Raw('Direct_AddTraceback((PyCodeObject *)', cod, ', PyLine, PyAddr);')
else:
o.Raw('Direct_AddTraceback((PyCodeObject *)', cod, ', 0, 0);')
o.Stmt(raised, '=', 1)
generate_clear_temp_on_exception(o, traced_temp)
o.append('}')
if 2 < len(it):
Fatal('', it)
del try_jump_context[-1]
o.Comment((')(FINALLY',))
generate_list(finally_cod,o)
global tempgen
o.Cls(a, b, c)
o.Cls(a1, b1, c1)
Cls1(o, raised)
o.Raw('if (', raised, ') { goto ',labl, '; }')
UseLabl()
del dropped_temp[-1]
set_toerr_final(o)
o2.extend(o)
def generate_clear_temp_on_exception(o, traced_temp):
for k, n in traced_temp:
o.CLEAR('temp[' + str(n) + ']')
def get_exc_info(o):
ae,be,ce = New(), New(), New()
o.Stmt('PyErr_Fetch', ('&', ae), ('&', be), ('&', ce))
## o.XINCREF(ae)
## o.XINCREF(be)
## o.XINCREF(ce)
o.Stmt('if (', be, '== 0) {')
o.Raw(be, '= Py_None;')
o.INCREF(be)
o.append('}')
o.Stmt('PyErr_NormalizeException', ('&', ae), ('&', be), ('&', ce))
PyEval_set_exc_info(o, ae, be, ce)
o.Stmt('if (', ce, '== 0) {')
o.Raw(ce, '= Py_None;')
o.INCREF(ce)
o.append('}')
return ae, be, ce
def set_toerr_new(o, label_err):
global labels, labl
labels.append(label_err)
labl = label_err
def set_toerr_back(o):
global labels, labl
del labels[-1]
if len(labels) > 0:
labl = labels[-1]
else:
labl = None
def set_toerr_final(o):
pass
IsObject = ('!LOAD_NAME', '!LOAD_GLOBAL', 'FAST', '!PyObject_Call', '!CALL_CALC_CONST', '!CALL_CALC_CONST_INDIRECT',\
'!PyDict_GetItem(glob,', '!BINARY_SUBSCR_Int',\
'!PyObject_GetAttr', '!PyNumber_And', '!PyNumber_Or', \
'!from_ceval_BINARY_SUBSCR', '!PySequence_GetSlice', '!LOAD_DEREF', 'CALC_CONST',\
'!PyList_GetSlice', '!PyTuple_GetSlice',
'!BUILD_MAP', '!BUILD_SET', '!MK_FUNK', '!_PyEval_ApplySlice', \
'!LIST_COMPR', '!BUILD_TUPLE', '!ORD_BUILTIN')
IsFloatOp = {'!PyNumber_Add':'+', '!PyNumber_InPlaceAdd':'+', \
'!PyNumber_Divide':'/', '!PyNumber_Multiply':'*', '!PyNumber_Negative':'-', \
'!PyNumber_Subtract':'-', '!PyNumber_InPlaceSubtract':'-', '!PyNumber_Power':None}
def parse_for_float_expr(it, acc, isfloat):
if it in acc:
return True
t = TypeExpr(it)
if IsInt(t) or IsStr(t) or t == Kl_IntUndefSize or IsList(t) or IsTuple(t):
## print it, t
## assert 'sqrt' not in repr(it)
return False
if type(it) is float:
acc.append(('CONST', it))
return True
if type(it) is tuple :
if it[0] == 'CONST' and type(it[1]) is float:
acc.append(it)
return True
if it[0] == 'CONST' and type(it[1]) is int:
acc.append(it)
return True
if it[0] == '!PyNumber_Power':
if not parse_for_float_expr(it[1], acc, isfloat):
return False
if it[2][0] == 'CONST' and type(it[2][1]) is int and\
it[3] == 'Py_None' and it[2][1] >= 2 and it[2][1] <= 5:
return True
assert 'sqrt' not in repr(it)
return False
if it[0] in IsFloatOp:
if it[0] in ('!PyNumber_Add', '!PyNumber_Subtract'):
if it[1][0] == 'CONST' and type(it[1][1]) is int:
return parse_for_float_expr(it[2], acc, isfloat)
if it[2][0] == 'CONST' and type(it[2][1]) is int:
return parse_for_float_expr(it[1], acc, isfloat)
ret = True
for i in it[1:]:
ret = ret and parse_for_float_expr(i, acc, isfloat)
## if not ret:
## pprint(it)
## assert 'sqrt' not in repr(it)
return ret
if it[0] == '!PyObject_Call' and it[1][0] == 'CALC_CONST':
t = it[1][1]
if len(t) == 2:
t = (Val3(t[0], 'ImportedM'), t[1])
if t in CFuncFloatOfFloat:
if it[2][0] == 'CONST' and len(it[2][1]) == 1:
return parse_for_float_expr(('CONST', it[2][1][0]), acc,isfloat)
return parse_for_float_expr(it[2][1][0], acc,isfloat)
t = Val3(t, 'ImportedM')
if t in CFuncFloatOfFloat:
if it[2][0] == 'CONST' and len(it[2][1]) == 1:
return parse_for_float_expr(('CONST', it[2][1][0]), acc,isfloat)
return parse_for_float_expr(it[2][1][0], acc,isfloat)
if it[0] in IsObject:
acc.append(it)
isfloat[it] = True
return True
# pprint(it)
# assert 'sqrt' not in repr(it)
return False
def generate_float_expr(it, acc, refs):
if type(it) is float:
return str(it)
if it[0] in IsFloatOp:
op = IsFloatOp[it[0]]
if op is None:
if it[2] == ('CONST', 2):
iit = generate_float_expr(it[1], acc, refs)
return '(' + iit + ') * (' + iit + ')'
elif it[2] == ('CONST', 3):
iit = generate_float_expr(it[1], acc, refs)
return '(' + iit + ') * (' + iit + ') * (' + iit + ')'
elif it[2] == ('CONST', 4):
iit = generate_float_expr(it[1], acc, refs)
return '(' + iit + ') * (' + iit + ') * (' + iit + ') * (' + iit + ')'
elif it[2] == ('CONST', 5):
iit = generate_float_expr(it[1], acc, refs)
return '(' + iit + ') * (' + iit + ') * (' + iit + ') * (' + iit + ') * (' + iit + ')'
Fatal('generate float EXPR', it)
if len(it) == 3:
return '(' + generate_float_expr(it[1], acc, refs) + ') ' + op + ' (' + generate_float_expr(it[2], acc, refs) + ')'
if len(it) == 2:
return op + '(' + generate_float_expr(it[1], acc, refs) + ')'
Fatal('generate float EXPR', it)
if it[0] == '!PyObject_Call' and it[1][0] == 'CALC_CONST':
t = it[1][1]
if type(t) is str:
t = Val3(t, 'ImportedM')
## print 'ppp', t2
elif len(t) == 2:
t = (Val3(t[0], 'ImportedM'), t[1])
if t in CFuncFloatOfFloat:
return CFuncFloatOfFloat[t] + ' ( ' + generate_float_expr(it[2][1][0], acc, refs) +' )'
if it in acc:
i = acc.index(it)
return refs[i]
if it[0] == 'CONST' and type(it[1]) is int:
return ' ' + str(it[1]) + ' '
Fatal('generate float EXPR', it)
def generate_ssize_t_expr(it):
if type(it) is int:
return Out(), it
if it[0] == 'PY_TYPE' and IsInt(TypeExpr(it)):
return generate_ssize_t_expr(it[3])
if it[0] == '!PY_SSIZE_T':
return generate_ssize_t_expr(it[1])
if it[0] == 'CONST' and type(it[1]) is int:
return Out(), it[1]
if IsCVar(it) and IsInt(TypeExpr(it)):
return Out(), CVarName(it)
if it[0] in len_family:
if it[0] != '!PyObject_Size':
if it[1][0] == '!LIST_COMPR':
o = Out()
prev_compr = current_co.list_compr_in_progress
current_co.list_compr_in_progress = True
size_t = generate_len_list_compr(it[1][1],it[1][2],o)
current_co.list_compr_in_progress = prev_compr
return o, size_t
nm = it[0][1:]
else:
nm = 'PyObject_Size'
t = TypeExpr(it[1])
if t is not None:
if IsListAll(t):
if it[1][0] == '!LIST_COMPR':
o = Out()
prev_compr = current_co.list_compr_in_progress
current_co.list_compr_in_progress = True
size_t = generate_len_list_compr(it[1][1],it[1][2],o)
current_co.list_compr_in_progress = prev_compr
return o, size_t
nm = 'PyList_GET_SIZE'
elif IsTuple(t):
nm = 'PyTuple_GET_SIZE'
elif IsStr(t):
nm = 'PyString_GET_SIZE'
elif IsDict(t):
nm = 'PyDict_Size'
elif t == Kl_Set:
nm = 'PySet_Size'
elif t == Kl_Unicode:
nm = 'PyUnicode_GetSize'
elif t == Kl_Buffer:
nm = 'PyObject_Size'
elif t == Kl_XRange:
nm = 'PyObject_Size'
elif t in (Kl_Generator, Kl_Int, Kl_Short):
nm = 'PyObject_Size'
elif IsKlNone(t):
Debug("len(None) construction detected", it)
nm = 'PyObject_Size'
elif t[0] in (T_OLD_CL_INST, T_NEW_CL_INST):
nm = 'PyObject_Size'
elif t is not None:
nm = 'PyObject_Size'
Debug('len of new known type', t, it[1], func)
size_t = New('Py_ssize_t')
o = Out()
ref1 = Expr1(it[1], o)
if nm.endswith('_GET_SIZE'):
o.Raw(size_t, ' = ', nm, '(', ref1, ');')
else:
o.Stmt(size_t, '=', nm, ref1)
Cls1(o, ref1)
return o, size_t
plusminus = {'!PyNumber_Add':0, '!PyNumber_Subtract':1}
if it[0] in plusminus:
t1 = TypeExpr(it[1])
t2 = TypeExpr(it[2])
if IsInt(t1) and IsInt(t2):
o1, v1 = shortage(generate_ssize_t_expr(it[1]))
o2, v2 = shortage(generate_ssize_t_expr(it[2]))
size_t = New('Py_ssize_t')
o = Out()
o.extend(o1)
o.extend(o2)
op = (' + ', ' - ')[plusminus[it[0]]]
o.Raw(size_t, ' = ', v1, op, v2, ';')
o.Cls(v1, v2)
return o, size_t
if it[0] == '!PyNumber_Negative':
t1 = TypeExpr(it[1])
if IsInt(t1):
o1, v1 = shortage(generate_ssize_t_expr(it[1]))
size_t = New('Py_ssize_t')
o = Out()
o.extend(o1)
o.Raw(size_t, ' = 0 - ', v1, ';')
Cls1(o, v1)
return o, size_t
if it[0] == '!@PyInt_FromSsize_t':
return Out(), ConC(it[1]) # for prevent Cls of temp 'for' count
o = Out()
ref2 = Expr1(it, o)
ind = New('Py_ssize_t')
o.Stmt(ind, '=', 'PyInt_AsSsize_t', ref2)
Cls1(o, ref2)
return o, ind
type_to_check = {'tuple' : 'PyTuple_CheckExact', 'list' : 'PyList_CheckExact',
'dict' : 'PyDict_CheckExact', 'int' : 'PyInt_CheckExact',
'str' : 'PyString_CheckExact', 'long' : 'PyLong_CheckExact',
'float' : 'PyFloat_CheckExact', 'complex' : 'PyComplex_CheckExact',
'unicode' : 'PyUnicode_CheckExact', 'bool' : 'PyBool_Check'}
type_to_check_t = {tuple : 'PyTuple_CheckExact', list : 'PyList_CheckExact',
dict : 'PyDict_CheckExact', int : 'PyInt_CheckExact',
str : 'PyString_CheckExact', long : 'PyLong_CheckExact',
float : 'PyFloat_CheckExact', complex : 'PyComplex_CheckExact',
unicode : 'PyUnicode_CheckExact', bool : 'PyBool_Check'}
type_to_check_str = {tuple : 'tuple', list : 'list',
dict : 'dict', int : 'int',
str : 'str', long : 'long',
float : 'float', complex : 'complex',
unicode : 'unicode', bool : 'bool'}
##op_to_oper = {'Py_EQ':' == ', 'Py_NE':' != ', 'Py_LT':' < ', \
## 'Py_LE':' <= ', 'Py_GT':' > ', 'Py_GE':' >= '}
def generate_rich_compare(it,logic,o):
## v = []
it1 = it[1]
it2 = it[2]
t1 = TypeExpr(it1)
t2 = TypeExpr(it2)
op = it[3]
if t1 == Kl_Type and t2 == Kl_Type and op in ('Py_EQ', 'Py_NE'):
oper = op_to_oper[op]
built = None
valu = None
if it1[0] == '!LOAD_BUILTIN' and it2[0] == '!PyObject_Type':
built = it1[1]
valu = it2[1]
elif it2[0] == '!LOAD_BUILTIN' and it2[0] == '!PyObject_Type':
built = it2[1]
valu = it1[1]
if built in type_to_check:
ref1 = Expr1(valu, o)
ret = ConC(type_to_check[built], '( ', ref1, ' );')
if op == 'Py_NE':
ret = '!' + ret
o.Raw(logic, ' = ', ret)
Cls1(o, ref1)
return o, logic
if it1[0] == '!PyObject_Type':
ref1 = Expr1(it1[1], o)
op1 = ConC('(PyObject *)Py_TYPE(',ref1,')')
else:
op1 = ref1 = Expr1(it1, o)
if it2[0] == '!PyObject_Type':
ref2 = Expr1(it2[1], o)
op2 = ConC('(PyObject *)Py_TYPE(',ref2,')')
else:
op2 = ref2 = Expr1(it2, o)
o.Raw(logic, ' = ', op1, oper, op2, ';')
o.Cls(ref1, ref2)
return o, logic
if IsInt(t1) and IsInt(t2):
if op in op_to_oper:
if IsShort(t1):
o1,int1 = shortage(generate_ssize_t_expr(it[1]))
o.extend(o1)
elif current_co.IsIntVar(it[1]):
int1 = CVarName(it[1])
elif current_co.IsBoolVar(it[1]):
int1 = CVarName(it[1])
else:
ref1 = Expr1(it[1],o)
if not istempref(ref1):
int1 = ConC('PyInt_AS_LONG ( ',ref1,' )')
else:
int1 = New('long')
o.Raw(int1, ' = PyInt_AS_LONG ( ',ref1,' );')
Cls1(o, ref1)
if IsShort(t2):
o2,int2 = shortage(generate_ssize_t_expr(it[2]))
o.extend(o2)
elif current_co.IsIntVar(it[2]):
int2 = CVarName(it[2])
elif current_co.IsBoolVar(it[2]):
int2 = CVarName(it[2])
else:
ref2 = Expr1(it[2],o)
if not istempref(ref2):
int2 = ConC('PyInt_AS_LONG ( ',ref2,' )')
else:
int2 = New('long')
o.Raw(int2, ' = PyInt_AS_LONG ( ',ref2,' );')
Cls1(o, ref2)
o.Raw(logic, ' = ', int1, op_to_oper[op], int2, ';')
o.Cls(int1, int2)
return o, logic
if IsBool(t1) and IsBool(t2):
if op in op_to_oper:
if current_co.IsBoolVar(it[1]):
int1 = CVarName(it[1])
else:
o1, int1 = shortage(generate_logical_expr(it[1]))
o.extend(o1)
if current_co.IsBoolVar(it[2]):
int2 = CVarName(it[2])
else:
o2, int2 = shortage(generate_logical_expr(it[2]))
o.extend(o2)
o.Raw(logic, ' = ', int1, op_to_oper[op], int2, ';')
o.Cls(int1, int2)
return o, logic
if IsFloat(t1) and IsFloat(t2):
if op in op_to_oper:
ref1 = Expr1(it[1],o)
if not istempref(ref1):
if it[1][0] == 'CONST' and type(it[1][1]) is float:
f1 = str(it[1][1])
else:
f1 = ConC('PyFloat_AsDouble(',ref1,')')
else:
f1 = New('double')
o.Raw(f1, ' = PyFloat_AsDouble(',ref1,');')
Cls1(o, ref1)
ref2 = Expr1(it[2],o)
if not istempref(ref2):
if it[2][0] == 'CONST' and type(it[2][1]) is float:
f2 = str(it[2][1])
else:
f2 = ConC('PyFloat_AsDouble(',ref2,')')
else:
f2 = New('double')
o.Raw(f2, ' = PyFloat_AsDouble(',ref2,');')
Cls1(o, ref2)
o.Raw(logic, ' = ', f1, op_to_oper[op], f2, ';')
o.Cls(f1, f2)
return o, logic
if IsTuple(t1) and IsTuple(t2):
ref1, ref2 = Expr(o, it[1:3])
if op in ('Py_EQ', 'Py_NE'):
if ref2[0] == 'CONST':
o.Raw('if (PyTuple_GET_SIZE(', ref1,') != ', len(ref2[1]), ') {')
elif ref1[0] == 'CONST':
o.Raw('if (', len(ref1[1]), ' != PyTuple_GET_SIZE(', ref2, ')) {')
else:
o.Raw('if (PyTuple_GET_SIZE(', ref1,') != PyTuple_GET_SIZE(', ref2, ')) {')
if op == 'Py_EQ':
o.Raw(logic, ' = 0;')
else:
o.Raw(logic, ' = 1;')
o.append('} else {')
ref0 = New()
o.Raw(ref0, ' = PyTuple_Type.tp_richcompare(', ref1, ', ', ref2, ', ', op, ');')
ToTrue(o, logic, ref0, it)
o.append('}')
else:
ref0 = New()
o.Raw(ref0, ' = PyTuple_Type.tp_richcompare(', ref1, ', ', ref2, ', ', op, ');')
ToTrue(o, logic, ref0, it)
o.Cls(ref1, ref2)
return o, logic
if t1 is None and IsTuple(t2):
ref1, ref2 = Expr(o, it[1:3])
o.Raw('if (PyTuple_CheckExact(', ref1, ')) {')
ref0 = New()
if op == 'Py_EQ' and ref2[0] == 'CONST':
if len(ref2[1]) == 0:
o.Raw(logic, ' = PyTuple_GET_SIZE(', ref1,') == 0;')
else:
o.Raw('if (PyTuple_GET_SIZE(', ref1,') != ', len(ref2[1]), ') {')
o.Raw(logic, ' = 0;')
o.append('} else {')
o.Raw(ref0, ' = PyTuple_Type.tp_richcompare(', ref1, ', ', ref2, ', ', op, ');')
ToTrue(o, logic, ref0, it)
Cls1(o, ref0)
o.append('}')
elif op == 'Py_NE' and ref2[0] == 'CONST':
if len(ref2[1]) == 0:
o.Raw(logic, ' = PyTuple_GET_SIZE(', ref1,') != 0;')
else:
o.Raw('if (PyTuple_GET_SIZE(', ref1,') != ', len(ref2[1]), ') {')
o.Raw(logic, ' = 1;')
o.append('} else {')
o.Raw(ref0, ' = PyTuple_Type.tp_richcompare(', ref1, ', ', ref2, ', ', op, ');')
ToTrue(o, logic, ref0, it)
Cls1(o, ref0)
o.append('}')
else:
o.Raw(ref0, ' = PyTuple_Type.tp_richcompare(', ref1, ', ', ref2, ', ', op, ');')
ToTrue(o, logic, ref0, it)
Cls1(o, ref0)
o.append('} else {')
o.Stmt(logic, '=', 'PyObject_RichCompareBool', ref1, ref2, it[3])
o.append('}')
o.Cls(ref1, ref2)
return o, logic
if t2 is None and IsTuple(t1):
ref1, ref2 = Expr(o, it[1:3])
o.Raw('if (PyTuple_CheckExact(', ref2, ')) {')
ref0 = New()
o.Raw(ref0, ' = PyTuple_Type.tp_richcompare(', ref1, ', ', ref2, ', ', op, ');')
ToTrue(o, logic, ref0, it)
Cls1(o, ref0)
o.append('} else {')
o.Stmt(logic, '=', 'PyObject_RichCompareBool', ref1, ref2, it[3])
o.append('}')
o.Cls(ref1, ref2)
return o, logic
if t1 == Kl_Char and t2 == Kl_Char:
ref1, ref2 = Expr(o, it[1:3])
if ref2[0] == 'CONST':
o.Raw(logic, ' = *', PyString_AS_STRING(ref1), op_to_oper[op],'\'', ref2[1], '\';')
o.Cls(ref1, ref2)
return o, logic
o.Raw(logic, ' = *', PyString_AS_STRING(ref1),op_to_oper[op],'*', PyString_AS_STRING(ref2), ';')
o.Cls(ref1, ref2)
return o, logic
if IsStr(t1) and IsStr(t2):
ref1, ref2 = Expr(o, it[1:3])
if op == 'Py_EQ':
o.Raw(logic, ' = (PyString_GET_SIZE(', ref1,') == PyString_GET_SIZE(', ref2, ')) && ', \
'(PyString_AS_STRING(',ref1,')[0] == PyString_AS_STRING(',ref2, ')[0]) && ', \
'(memcmp(PyString_AS_STRING(',ref1,'), PyString_AS_STRING(',ref2,'), ',
'PyString_GET_SIZE(', ref1,')) == 0);')
o.Cls(ref1, ref2)
return o, logic
elif op == 'Py_NE':
o.Raw(logic, ' = (PyString_GET_SIZE(', ref1,') != PyString_GET_SIZE(', ref2, ')) || ', \
'(PyString_AS_STRING(',ref1,')[0] != PyString_AS_STRING(',ref2, ')[0]) || ', \
'(memcmp(PyString_AS_STRING(',ref1,'), PyString_AS_STRING(',ref2,'), ',
'PyString_GET_SIZE(', ref1,')) != 0);')
o.Cls(ref1, ref2)
return o, logic
else:
ref0 = New()
o.Raw(ref0, ' = PyString_Type.tp_richcompare(', ref1, ', ', ref2, ', ', op, ');')
ToTrue(o, logic, ref0, it)
Cls1(o, ref0)
o.Cls(ref1, ref2)
return o, logic
if IsStr(t1) and t2 is None and op in ('Py_EQ', 'Py_NE'):
ref1, ref2 = Expr(o, it[1:3])
o.Raw('if (PyString_CheckExact(', ref2, ')) {')
if op == 'Py_EQ':
o.Raw(logic, ' = (PyString_GET_SIZE(', ref1,') == PyString_GET_SIZE(', ref2, ')) && ', \
'(PyString_AS_STRING(',ref1,')[0] == PyString_AS_STRING(',ref2, ')[0]) && ', \
'(memcmp(PyString_AS_STRING(',ref1,'), PyString_AS_STRING(',ref2,'), ',
'PyString_GET_SIZE(', ref1,')) == 0);')
else:
o.Raw(logic, ' = (PyString_GET_SIZE(', ref1,') != PyString_GET_SIZE(', ref2, ')) || ', \
'(PyString_AS_STRING(',ref1,')[0] != PyString_AS_STRING(',ref2, ')[0]) || ', \
'(memcmp(PyString_AS_STRING(',ref1,'), PyString_AS_STRING(',ref2,'), ',
'PyString_GET_SIZE(', ref1,')) != 0);')
o.append('} else {')
o.Stmt(logic, '=', 'PyObject_RichCompareBool', ref1, ref2, it[3])
o.append('}')
o.Cls(ref1, ref2)
return o, logic
if IsStr(t2) and t1 is None and op in ('Py_EQ', 'Py_NE'):
ref1, ref2 = Expr(o, it[1:3])
o.Raw('if (PyString_CheckExact(', ref1, ')) {')
if op == 'Py_EQ':
o.Raw(logic, ' = (PyString_GET_SIZE(', ref1,') == PyString_GET_SIZE(', ref2, ')) && ', \
'(PyString_AS_STRING(',ref1,')[0] == PyString_AS_STRING(',ref2, ')[0]) && ', \
'(memcmp(PyString_AS_STRING(',ref1,'), PyString_AS_STRING(',ref2,'), ',
'PyString_GET_SIZE(', ref1,')) == 0);')
else:
o.Raw(logic, ' = (PyString_GET_SIZE(', ref1,') != PyString_GET_SIZE(', ref2, ')) || ', \
'(PyString_AS_STRING(',ref1,')[0] != PyString_AS_STRING(',ref2, ')[0]) || ', \
'(memcmp(PyString_AS_STRING(',ref1,'), PyString_AS_STRING(',ref2,'), ',
'PyString_GET_SIZE(', ref1,')) != 0);')
o.append('} else {')
o.Stmt(logic, '=', 'PyObject_RichCompareBool', ref1, ref2, it[3])
o.append('}')
o.Cls(ref1, ref2)
return o, logic
if IsStr(t2) and t2 == Kl_Char and t1 is None and op in op_to_oper:
ref1, ref2 = Expr(o, it[1:3])
o.Raw('if (PyString_CheckExact(', ref1, ') && PyString_GET_SIZE(', ref1,') == 1) {')
o.Raw(logic, ' = PyString_AS_STRING(',ref1,')[0] ',op_to_oper[op],' PyString_AS_STRING(',ref2, ')[0];')
o.append('} else {')
o.Stmt(logic, '=', 'PyObject_RichCompareBool', ref1, ref2, it[3])
o.append('}')
o.Cls(ref1, ref2)
return o, logic
if IsIntUndefSize(t1) and IsInt(t2) and it[2][0] == 'CONST' and type(it[2][1]) is int:
if op in op_to_oper:
ref1 = GenExpr(it[1],o, None, None, True)
ref2 = it[2]
o.Raw('if (PyInt_CheckExact( ', ref1, ' )) {')
int1 = ConC('PyInt_AS_LONG ( ',ref1,' )')
int2 = ref2[1]
o.Raw(logic, ' = ', int1, op_to_oper[op], int2, ';')
o.append('} else {')
o.Stmt(logic, '=', 'PyObject_RichCompareBool', ref1, ref2, it[3])
o.append('}')
o.Cls(ref1, ref2)
return o, logic
if t1 is None and t2 == Kl_Int:
if op in op_to_oper and not current_co.IsIntVar(it[2]):
ref1 = GenExpr(it[1],o, None, None, True)
ref2 = Expr1(it[2],o)
o.Raw('if (PyInt_CheckExact( ', ref1, ' )) {')
int1 = ConC('PyInt_AS_LONG ( ',ref1,' )')
int2 = ConC('PyInt_AS_LONG ( ',ref2,' )')
o.Raw(logic, ' = ', int1, op_to_oper[op], int2, ';')
o.append('} else {')
o.Stmt(logic, '=', 'PyObject_RichCompareBool', ref1, ref2, it[3])
o.append('}')
o.Cls(ref1, ref2)
return o, logic
if t1 is None and t2 == Kl_Int:
if op in op_to_oper and current_co.IsIntVar(it[2]):
ref1 = GenExpr(it[1],o, None, None, True)
o.Raw('if (PyInt_CheckExact( ', ref1, ' )) {')
int1 = ConC('PyInt_AS_LONG ( ',ref1,' )')
int2 = CVarName(it[2])
o.Raw(logic, ' = ', int1, op_to_oper[op], int2, ';')
o.append('} else {')
ref2 = Expr1(it[2], o)
o.Stmt(logic, '=', 'PyObject_RichCompareBool', ref1, ref2, it[3])
Cls1(o, ref2)
o.append('}')
Cls1(o, ref1)
return o, logic
if t1 is None and IsFloat(t2):
if op in op_to_oper:
ref1 = Expr1(it[1],o)
ref2 = Expr1(it[2],o)
o.Raw('if (PyFloat_CheckExact(', ref1, ')) {')
f1 = ConC('PyFloat_AsDouble(',ref1,')')
if it[2][0] == 'CONST' and type(it[2][1]) is float:
f2 = str(it[2][1])
else:
f2 = ConC('PyFloat_AsDouble(',ref2,')')
o.Raw(logic, ' = ', f1, op_to_oper[op], f2, ';')
o.Cls(f1, f2)
o.append('} else {')
o.Stmt(logic, '=', 'PyObject_RichCompareBool', ref1, ref2, it[3])
o.append('}')
o.Cls(ref1, ref2)
return o, logic
if IsFloat(t1) and t2 is None:
if op in op_to_oper:
ref1 = Expr1(it[1],o)
ref2 = Expr1(it[2],o)
o.Raw('if (PyFloat_CheckExact(', ref2, ')) {')
if it[1][0] == 'CONST' and type(it[1][1]) is float:
f1 = str(it[1][1])
else:
f1 = ConC('PyFloat_AsDouble(',ref1,')')
f2 = ConC('PyFloat_AsDouble(',ref2,')')
o.Raw(logic, ' = ', f1, op_to_oper[op], f2, ';')
o.Cls(f1, f2)
o.append('} else {')
o.Stmt(logic, '=', 'PyObject_RichCompareBool', ref1, ref2, it[3])
o.append('}')
o.Cls(ref1, ref2)
return o, logic
if IsShort(t1) and t2 is None and op in op_to_oper:
if it1[0] == 'PY_TYPE':
it1 = it1[3]
if current_co.IsIntVar(it1):
o1, size_t_1 = [], CVarName(it1)
else:
o1,size_t_1 = shortage(generate_ssize_t_expr(it1))
o.extend(o1)
ref2 = GenExpr(it[2],o, None, None, True)
o.Raw('if (PyInt_CheckExact( ', ref2, ' )) {')
o.Raw(logic, ' = ', size_t_1, op_to_oper[op], 'PyInt_AS_LONG ( ', ref2, ' );')
o.append('} else {')
ref1 = New()
o.PushInt(ref1, size_t_1)
o.Stmt(logic, '=', 'PyObject_RichCompareBool', ref1, ref2, it[3])
Cls1(o, ref1)
o.append('}')
o.Cls(ref2, size_t_1)
return o, logic
if IsInt(t1) and t2 is None and op in op_to_oper:
ref1 = Expr1(it[1], o)
int_1 = None
ref1, int_1 = to_long(o, ref1, int_1)
ref2 = GenExpr(it[2],o, None, None, True)
o.Raw('if (PyInt_CheckExact( ', ref2, ' )) {')
o.Raw(logic, ' = ', int_1, op_to_oper[op], 'PyInt_AS_LONG ( ', ref2, ' );')
o.append('} else {')
newref = False
if ref1 is None:
newref = True
ref1 = New()
o.PushInt(ref1, int_1)
o.Stmt(logic, '=', 'PyObject_RichCompareBool', ref1, ref2, it[3])
if newref:
Cls1(o, ref1)
o.append('}')
o.Cls(ref1, ref2, int_1)
return o, logic
if IsShort(t2) and t1 is None and op in op_to_oper:
ref1 = GenExpr(it[1],o, None, None, True)
if it[2][0] == 'PY_TYPE' and it[2][3][0] == 'FAST' and not current_co.IsIntVar(it[2][3]):
o.Raw('if (PyInt_CheckExact( ', ref1, ' )) {')
o2,size_t_2 = shortage(generate_ssize_t_expr(it[2]))
o.extend(o2)
o.Raw(logic, ' = PyInt_AS_LONG ( ', ref1, ' )', op_to_oper[op], size_t_2, ';')
Cls1(o, size_t_2)
o.append('} else {')
ref2 = it[2][3]
o.Stmt(logic, '=', 'PyObject_RichCompareBool', ref1, ref2, it[3])
Cls1(o, ref2)
o.append('}')
o.Cls(ref1, size_t_2)
return o, logic
o2,size_t_2 = shortage(generate_ssize_t_expr(it[2]))
o.extend(o2)
o.Raw('if (PyInt_CheckExact( ', ref1, ' )) {')
o.Raw(logic, ' = PyInt_AS_LONG ( ', ref1, ' )', op_to_oper[op], size_t_2, ';')
o.append('} else {')
ref2 = New()
o.PushInt(ref2, size_t_2)
o.Stmt(logic, '=', 'PyObject_RichCompareBool', ref1, ref2, it[3])
Cls1(o, ref2)
o.append('}')
o.Cls(ref1, size_t_2)
return o, logic
if IsInt(t2) and t1 is None and op in op_to_oper:
ref1 = GenExpr(it[1],o, None, None, True)
ref2 = Expr1(it[2], o)
n = New('long')
o.Raw(n, ' = PyInt_AS_LONG ( ', ref2, ' );')
o.Raw('if (PyInt_CheckExact( ', ref1, ' )) {')
o.Raw(logic, ' = PyInt_AS_LONG ( ', ref1, ' )', op_to_oper[op], n, ';')
o.append('} else {')
o.Stmt(logic, '=', 'PyObject_RichCompareBool', ref1, ref2, it[3])
o.append('}')
o.Cls(ref1, ref2, n)
return o, logic
if IsKlNone(t2) and t1 is None and \
op in ('Py_EQ', 'Py_NE') and it[2] == ('CONST', None):
ref1 = Expr1(it[1],o)
o.Raw(logic, ' = ', ref1, op_to_oper[op], ('CONST', None), ';')
Cls1(o, ref1)
return o, logic
if IsBool(t2) and IsBool(t1) and op in ('Py_EQ', 'Py_NE') and it[2][0] == 'CONST':
o_old, n = shortage(generate_logical_expr(it[1]))
val = '0'
if it[2][1]:
val = '1'
o.extend(o_old)
o.Raw(logic, ' = ', n, op_to_oper[op], val, ';')
o.Cls(n)
return o, logic
if t1 is not None and t2 is not None:
if t1 == Kl_String and t2 == Kl_String:
Fatal('Cmp String unrecognized ?', it)
Debug('Typed comparison unrecognized %s %s %s' % (t1, op, t2), it[1], it[2])
elif t1 is not None or t2 is not None:
Debug('Half-typed comparison unrecognized %s %s %s' % (t1, op, t2), it[1], it[2])
ref1, ref2 = Expr(o, it[1:3])
o.Stmt(logic, '=', 'PyObject_RichCompareBool', ref1, ref2, it[3])
o.Cls(ref1, ref2)
return o, logic
def generate_logical_expr(it, logic = None):
assert logic is None or logic[0] == 'TYPED_TEMP'
it0 = it[0]
if type(it0) is str and it0[-1] == '(':
it0 = it0[:-1]
o = Out()
if IsCVar(it) and IsBool(TypeExpr(it)):
return o, CVarName(it)
if logic is None:
logic = New('int')
if it0 == '!PyObject_RichCompare':
return generate_rich_compare(it,logic,o)
if it0 == '!BOOLEAN':
return generate_logical_expr(it[1], logic)
if it0 == 'CONST':
if it[1]:
o.Stmt(logic, '=', 1)
return o, logic
if not it[1]:
o.Stmt(logic, '=', 0)
return o, logic
Fatal('shd', it)
if it0 == '!1NOT':
if it[1] == ('CONST', False):
o.Stmt(logic, '=', 1)
return o, logic
if it[1] == ('CONST', True):
o.Stmt(logic, '=', 0)
return o, logic
if it[1][0] in IsObject and not IsCVar(it[1]):
ref1 = Expr1(it[1], o)
o.Stmt(logic, '=', 'PyObject_Not', ref1)
Cls1(o, ref1)
return o, logic
if IsBool(TypeExpr(it[1])) and IsCVar(it[1]):
o.Raw(logic, ' = !', CVarName(it[1]), ';')
return o, logic
if IsInt(TypeExpr(it[1])) and IsCVar(it[1]):
o.Raw(logic, ' = !', CVarName(it[1]), ';')
return o, logic
if it[1][0] not in IsObject:
o, logic1 = generate_logical_expr(it[1], logic)
o.Raw(logic, ' = !(', logic1, ');')
return o, logic
assert False
if it0 in API_cmp_2_PyObject:
v = []
if TCmp(it, v, ('!PyObject_IsInstance', ('FAST', '?'), ('CALC_CONST', '?'))) and\
v[1] in calc_const_old_class and not is_pypy:
o.Raw(logic, ' = PyInstance_Check(',('FAST', v[0]),') && ((PyInstanceObject *)',('FAST', v[0]),')->in_class == (PyClassObject*)', ('CALC_CONST', v[1]), ';')
return o, logic
v = []
if TCmp(it, v, ('!PySequence_Contains(', ('CONST', '?'), '?')) and \
type(v[0]) is tuple and all([type(x) is str for x in v[0]]):
## v2 = []
t2 = TypeExpr(v[1])
d = {}
ref2 = Expr1(v[1], o)
for ref1 in v[0]:
nc = len(ref1)
const_to(ref1)
if nc != 1:
text = ConC('0 == memcmp(', PyString_AS_STRING(ref2), ' , ', generate_chars_literal(ref1), ' , ',nc, ')')
else:
text = ConC('*', PyString_AS_STRING(ref2), ' == *', generate_chars_literal(ref1))
if nc in d:
d[nc] = d[nc] + ' || (' + text + ')'
else:
d[nc] = '(' + text + ')'
if IsStr(t2):
if len(d) == 1:
k, v = d.items()[0]
o.Raw(logic, ' = PyString_GET_SIZE(', ref2, ') == ', k, ' && (', v, ');')
Cls1(o, ref2)
return o, logic
o.Raw(logic, ' = 0;')
o.Raw('switch (PyString_GET_SIZE(', ref2, ')) {')
for k, v in d.iteritems():
o.Raw('case ', k, ':')
o.Raw(logic, ' = ', v, ';')
o.append('break;')
o.append('default:')
o.append('break;')
o.append('}')
Cls1(o, ref2)
return o, logic
else:
if len(d) == 1:
o.Raw('if (PyString_CheckExact(', ref2, ')) {')
k, v = d.items()[0]
o.Raw(logic, ' = PyString_GET_SIZE(', ref2, ') == ', k, ' && (', v, ');')
o.append('} else {')
o.Stmt(logic, '=', it0[1:], it[1], ref2)
o.append('}')
Cls1(o, ref2)
return o, logic
o.Raw('if (PyString_CheckExact(', ref2, ')) {')
o.Raw(logic, ' = 0;')
o.Raw('switch (PyString_GET_SIZE(', ref2, ')) {')
for k, v in d.iteritems():
o.Raw('case ', k, ':')
o.Raw(logic, ' = ', v, ';')
o.append('break;')
o.append('default:')
o.append('break;')
o.append('}')
o.append('} else {')
o.Stmt(logic, '=', it0[1:], it[1], ref2)
o.append('}')
Cls1(o, ref2)
return o, logic
if TCmp(it, v, ('!PySequence_Contains(', ('CONST', '?'), '?')) and \
type(v[0]) is tuple and not all([type(x) is str for x in v[0]]):
Debug('Contains:Not string tuple in %s', it)
if TCmp(it, v, ('!PySequence_Contains(', ('!BUILD_TUPLE', '?'), '?')) and \
type(v[0]) is tuple and not all([type(x) is str for x in v[0]]):
Debug('Contains:Not const tuple in %s', it)
ref1, ref2 = Expr(o, it[1:3])
o.Stmt(logic, '=', it0[1:], ref1, ref2)
o.Cls(ref1, ref2)
return o, logic
if it0 in ('!_EQ_', '!_NEQ_'):
if it[1][0] == '!PyObject_Type' and it[2][0] == '!LOAD_BUILTIN' and it[2][1] in type_to_check:
ref1 = Expr1(it[1][1], o)
if it0 == '!_EQ_':
o.Raw(logic, ' = ', type_to_check[it[2][1]], '( ', ref1, ' );')
else:
o.Raw(logic, ' = !', type_to_check[it[2][1]], '( ', ref1, ' );')
Cls1(o, ref1)
return o, logic
if it[2][0] == '!PyObject_Type' and it[1][0] == '!LOAD_BUILTIN' and it[1][1] in type_to_check:
ref1 = Expr1(it[2][1], o)
if it0 == '!_EQ_':
o.Raw(logic, ' = ', type_to_check[it[1][1]], '( ', ref1, ' );')
else:
o.Raw(logic, ' = !', type_to_check[it[1][1]], '( ', ref1, ' );')
Cls1(o, ref1)
return o, logic
if it[1][0] == '!PyObject_Type' and it[2][0] == 'CALC_CONST' and IsAnyClass(it[2][1]):
ref1 = Expr1(it[1][1], o)
if it0 == '!_EQ_':
o.Raw(logic, ' = (PyObject *)Py_TYPE(',ref1,') == ', it[2], ';')
else:
o.Raw(logic, ' = (PyObject *)Py_TYPE(',ref1,') != ', it[2], ';')
Cls1(o, ref1)
return o, logic
if it[2][0] == '!PyObject_Type' and it[1][0] == 'CALC_CONST' and IsAnyClass(it[1][1]):
ref1 = Expr1(it[2][1], o)
if it0 == '!_EQ_':
o.Raw(logic, ' = (PyObject *)Py_TYPE(',ref1,') == ', it[1], ';')
else:
o.Raw(logic, ' = (PyObject *)Py_TYPE(',ref1,') != ', it[1], ';')
Cls1(o, ref1)
return o, logic
ref1 = Expr1(it[1], o)
o2 = Out()
ref2 = Expr1(it[2], o2)
skip1 = False
skip2 = False
if istempref(ref1) and o[-1] == ConC('Py_INCREF(', ref1, ');') and len(o2) == 0:
del o[-1]
skip1 = True
if istempref(ref2) and o2[-1] == ConC('Py_INCREF(', ref2, ');') and len(o) == 0:
del o2[-1]
skip2 = True
o.extend(o2)
if it0 == '!_EQ_':
o.Stmt(logic, '=', ref1, '==', ref2)
else:
o.Stmt(logic, '=', ref1, '!=', ref2)
if skip1:
o.ClsFict(ref1)
else:
Cls1(o, ref1)
if skip2:
o.ClsFict(ref2)
else:
Cls1(o, ref2)
return o, logic
if it0 in ('!OR_JUMP', '!OR_BOOLEAN', '!OR_JUMPED_STACKED'):
o = generate_and_or_logical(it[1:], False, logic)
return o, logic
if it0 in ('!AND', '!AND_JUMP', '!AND_BOOLEAN', '!AND_JUMPED_STACKED'):
o = generate_and_or_logical(it[1:], True, logic)
return o, logic
if it0 in ('!SSIZE_T==', '!SSIZE_T>', '!SSIZE_T>=', '!SSIZE_T!=', \
'!SSIZE_T<', '!SSIZE_T<='):
o1,size_t_1 = shortage(generate_ssize_t_expr(it[1]))
o2,size_t_2 = shortage(generate_ssize_t_expr(it[2]))
o1.extend(o2)
o1.Raw(logic, ' = ', size_t_1, ' ', it0[8:], ' ', size_t_2, ';')
o1.Cls(size_t_1, size_t_2)
return o1, logic
if it0 == '!PY_SSIZE_T':
o1,size_t_1 = shortage(generate_ssize_t_expr(it[1]))
o1.Raw(logic, ' = ', size_t_1, ' != ', 0, ';')
o1.Cls(size_t_1)
return o1,logic
if it0 in ('!c_Py_EQ_Int', '!c_Py_NE_Int', '!c_Py_LT_Int', \
'!c_Py_LE_Int', '!c_Py_GT_Int', '!c_Py_GE_Int'):
op = it0[3:-4]
oper = op_to_oper[op]
t = TypeExpr(it[1])
if t is not None and t[0] not in (int, float):
return generate_logical_expr(('!PyObject_RichCompare(', it[1], it[2], op), logic)
ref = Expr1(it[1], o)
if t is not None and not IsInt(t):
Debug('typed compare', t,it)
o2 = Out()
if it[2][0] in ('CONST', 'LOAD_CONST') and type(it[2][1]) is int:
int_t = it[2][1]
int_2 = const_to(int_t)
else:
Fatal('', it, type(it[2][1]))
o.extend(o2)
if IsInt(t):
o.Raw(logic, ' = PyInt_AS_LONG ( ', ref, ' )', oper, int_t, ';')
o.Cls(ref, int_t)
return o,logic
if IsFloat(t):
o.Raw(logic, ' = PyFloat_AS_DOUBLE( ', ref, ' )', oper, int_t, ';')
o.Cls(ref, int_t)
return o,logic
if t is not None:
Debug('Typed %s (%s, %s)' % (it0, t, it[2]), it)
o.Stmt(logic,'=', it0[1:], ref, int_t, int_2)
o.Cls(ref, int_t)
return o,logic
if it0 in ('!c_Py_EQ_String', '!c_Py_NE_String'):
if it[2][0] == 'CONST' and type(it[2][1]) is str:
s_t = it[2][1]
s_2 = const_to(s_t)
else:
Fatal('', it)
t1 = TypeExpr(it[1])
if t1 is not None:
Debug('Typed %s (%s, <str>)' % ( it0, t1), it[1], it[2])
if TypeExpr(it[2]) == Kl_Char and it[1][0] == '!BINARY_SUBSCR_Int' and \
it[1][2][0] == 'CONST' and type(it[1][2][1]) is int and it[1][2][1] >= 0:
t4 = TypeExpr(it[1][1])
## ref3 = Expr1(it[1][1], o)
if t4 == None or t4 == (None, None):
ref3 = Expr1(it[1][1], o)
o.Raw('if ( PyString_CheckExact(', ref3,') && PyString_GET_SIZE(',ref3,') > ', it[1][2][1], ') {')
if it0 == '!c_Py_EQ_String' :
o.Raw(logic,' = ', PyString_AS_STRING(ref3), '[', it[1][2][1], '] == *', generate_chars_literal(s_t), ';')
else:
o.Raw(logic,' = ', PyString_AS_STRING(ref3), '[', it[1][2][1], '] != *', generate_chars_literal(s_t), ';')
o.append('} else {')
ref = New()
o.Stmt(ref, '=', '_c_BINARY_SUBSCR_Int', ref3, it[1][2][1], it[1][2])
o.Raw(logic,' = ', it0[1:], '(', ref, ', ', len(s_t), ', ', generate_chars_literal(s_t), ', ', s_2, ');')
Cls1(o, ref)
o.append('}')
Cls1(o, ref3)
return o,logic
elif IsStr(t4):
ref3 = Expr1(it[1][1], o)
o.Raw('if ( PyString_GET_SIZE(',ref3,') > ', it[1][2][1], ') {')
if it0 == '!c_Py_EQ_String' :
o.Raw(logic,' = ', PyString_AS_STRING(ref3), '[', it[1][2][1], '] == *', generate_chars_literal(s_t), ';')
else:
o.Raw(logic,' = ', PyString_AS_STRING(ref3), '[', it[1][2][1], '] != *', generate_chars_literal(s_t), ';')
o.append('} else {')
ref = New()
o.Stmt(ref, '=', '_c_BINARY_SUBSCR_Int', ref3, it[1][2][1], it[1][2])
o.Raw(logic,' = ', it0[1:], '(', ref, ', ', len(s_t), ', ', generate_chars_literal(s_t), ', ', s_2, ');')
Cls1(o, ref)
o.append('}')
Cls1(o, ref3)
return o,logic
if IsTuple(t4):
ref = Expr1(it[1], o)
## generate_rich_compare(it,logic,o)
o.Raw(logic,' = ', it0[1:], '(', ref, ', ', len(s_t), ', ', generate_chars_literal(s_t), ', ', s_2, ');')
Cls1(o, ref)
return o,logic
if TypeExpr(it[2]) == Kl_String and it[1][0] == '!PySequence_GetSlice' and \
it[2][0] == 'CONST' and it[1][2] == 0 and it[1][3] == len (it[2][1]):
ref3 = Expr1(it[1][1], o)
o.Raw('if ( PyString_CheckExact(', ref3,') ) {')
o.Raw('if (PyString_GET_SIZE(',ref3,') >= ', len (it[2][1]), ') {')
if it0 == '!c_Py_EQ_String' :
o.Raw(logic,' = 0 == memcmp(', PyString_AS_STRING(ref3), ', ', generate_chars_literal(s_t), ' , ',len (it[2][1]), ');')
else:
o.Raw(logic,' = 0 != memcmp(', PyString_AS_STRING(ref3), ', ', generate_chars_literal(s_t), ' , ',len (it[2][1]), ');')
# o.Raw(logic,' = PyString_AS_STRING(', ref3, ')[', it[1][2][1], '] != *', generate_chars_literal(s_t), ';')
o.append('} else {')
if it0 == '!c_Py_EQ_String' :
o.Raw(logic,' = 0;')
else:
o.Raw(logic,' = 1;')
o.append('}')
o.append('} else {')
ref = New()
o.Stmt(ref, '=', 'PySequence_GetSlice', ref3, it[1][2], it[1][3])
o.Raw(logic,' = ', it0[1:], '(', ref, ', ', len(s_t), ', ', generate_chars_literal(s_t), ', ', s_2, ');')
Cls1(o, ref)
o.append('}')
Cls1(o, ref3)
return o,logic
ref = Expr1(it[1], o)
o.Raw(logic,' = ', it0[1:], '(', ref, ', ', len(s_t), ', ', generate_chars_literal(s_t), ', ', s_2, ');')
Cls1(o, ref)
return o,logic
if it0 == '!NCMP':
tu = list(it[1])
to_cls = []
logic2 = New('int')
o.Raw(logic, ' = 0;')
ref1 = Expr1(tu[0], o)
ref2 = Expr1(tu[2], o)
if tu[1] == 'is':
o.Stmt(logic2, '=', ref1, '==', ref2)
elif tu[1] == 'is not':
o.Stmt(logic2, '=', ref1, '!=', ref2)
elif tu[1] == 'in':
o.Stmt(logic2, '=', 'PySequence_Contains', ref2, ref1)
elif tu[1] == 'not in':
o.Stmt(logic2, '=', 'PySequence_Contains', ref2, ref1)
o.Raw(logic2, ' = ! ', logic2, ';')
else:
o.Stmt(logic2, '=', 'PyObject_RichCompareBool', ref1, ref2, op_2_c_op[tu[1]])
del tu[:3]
to_cls.append(ref1)
ref1 = ref2
o.Raw('if (', logic2, ') {')
while len(tu) > 1:
ref2 = Expr1(tu[1], o)
if tu[0] == 'is':
o.Stmt(logic2, '=', ref1, '==', ref2)
elif tu[0] == 'is not':
o.Stmt(logic2, '=', ref1, '!=', ref2)
elif tu[0] == 'in':
o.Stmt(logic2, '=', 'PySequence_Contains', ref2, ref1)
elif tu[0] == 'not in':
o.Stmt(logic2, '=', 'PySequence_Contains', ref2, ref1)
o.Raw(logic2, ' = ! ', logic2, ';')
else:
o.Stmt(logic2, '=', 'PyObject_RichCompareBool', ref1, ref2, op_2_c_op[tu[0]])
del tu[:2]
to_cls.append(ref1)
ref1 = ref2
o.Raw('if (', logic2, ') {')
o.Raw(logic, ' = 1;')
for r in range(len(to_cls)):
o.append('}')
Cls1(o, logic2)
o.Cls(*to_cls)
Cls1(o, ref1)
return o, logic
if it0 == '!COND_METH_EXPR':
return generate_logical_cond_meth_expr(it, logic)
if it0 == '!PyBool_Type.tp_new' and it[2][0] == '!BUILD_TUPLE' and len(it[2][1]) == 1:
return generate_logical_expr(it[2][1][0], logic)
ref1 = Expr1(it, o)
return ToTrue(o,logic,ref1, it)
def ToTrue(o, logic, ref1, it):
last = o[-3:]
del_check = False
if len(last) > 0:
che = ('if ( %s == 0 ) goto %s;' % (CVar(ref1), CVar(labl)))
UseLabl()
if last[-1] == che:
del_check = True
del last[-1]
if len(last) > 0:
beg = CVar(ref1) + ' = PyBool_FromLong ('
if last[-1].startswith(beg) and last[-1].endswith(');'):
if del_check:
del o[-1]
c_expr = o[-1][len(beg):-2]
del o[-1]
o.ClsFict(ref1)
o.Raw(logic, ' = ', c_expr, ';')
return o, logic
beg = CVar(ref1) + ' = PyInt_FromLong ('
if last[-1].startswith(beg) and last[-1].endswith(');'):
if del_check:
del o[-1]
c_expr = o[-1][len(beg):-2]
del o[-1]
o.ClsFict(ref1)
o.Raw(logic, ' = ', c_expr, ';')
return o, logic # Debug('generate_logical_expr', it, o[-3:])
if IsInt(TypeExpr(it)):
o.Raw(logic, ' = PyInt_AS_LONG ( ', ref1, ' ) != 0;')
Cls1(o, ref1)
return o, logic
v2 = []
if len(o) >= 1 and TxMatch(o, len(o) - 1, ('temp[$0] = PyBool_FromLong($2);',), v2):
v2[2] = v2[2].strip()
v2[1] = CVar(logic)
v2[1] = v2[1].strip()
if v2[2] == v2[1]:
TxRepl(o, len(o) - 1, (), v2)
else:
TxRepl(o, len(o) - 1, ('$1 = $2;',), v2)
Cls1(o, ref1)
if istempref(ref1) and o[-1].startswith('CLEARTEMP('):
del o[-1]
return (o, logic)
o.Stmt(logic, '=', 'PyObject_IsTrue', ref1)
Cls1(o, ref1)
return o, logic
def generate_and_or_logical(it, is_and, logic):
assert logic is None or logic[0] == 'TYPED_TEMP'
o,logic1 = generate_logical_expr(it[0], logic)
if len(it) == 1:
if not istemptyped(logic1) and istemptyped(logic) and type(logic1) is str:
o.Raw(logic, ' = ', logic1, ';')
logic1 = logic
return o
if type(logic1) is int:
logic2 = New('int')
o.Stmt(logic2, '=', logic1)
logic1 = logic2
if not istemptyped(logic1) and logic is None:
logic2 = New('int')
o.Stmt(logic2, '=', logic1)
logic1 = logic2
if not istemptyped(logic1) and istemptyped(logic) and type(logic1) is str:
o.Raw(logic, ' = ', logic1, ';')
logic1 = logic
if istemptyped(logic1) and istemptyped(logic):
assert logic1 == logic
if is_and:
o.Stmt('if (', logic1, ') {')
else:
o.Stmt('if (!(', logic1, ')) {')
assert logic1 is None or logic1[0] == 'TYPED_TEMP'
o2 = generate_and_or_logical(it[1:], is_and, logic1)
o.extend(o2)
o.append('}')
return o
def generate_preexpr(it,o):
assert len(it) == 3
assert it[0][0] == '(PREEXPR'
assert it[2][0] == ')PREEXPR'
acc = it[1]
refs = Expr(o, acc) #[Expr1(x, o) for x in acc]
PushAcc(acc, refs)
generate_list(it[1],o)
PopAcc(o, False)
o.Cls(*refs)
## for x in refs:
## Cls1(o, x)
def shortage(l):
o, logic = l
if len(o) == 0:
return o, logic
optimize(o)
if not istemptyped(logic):
return o, logic
if len(o) == 1 and o[0].startswith(ConC(logic, ' = ')) and\
o[0].endswith(';'):
s = o[0].split(' = ')
if len(s) != 2:
return o, logic
if s[0] != ConC(logic):
return o, logic
o2 = Out()
o2.Cls(logic)
return o2, '(' + s[1][:-1] + ')'
if len(o) > 1 and o[-1].startswith(ConC(logic, ' = ')) and\
o[-1].endswith(';'):
s = o[-1].split(' = ')
if len(s) != 2:
return o, logic
if s[0] != ConC(logic):
return o, logic
o2 = Out()
o2.extend(o[:-1])
o2.Cls(logic)
return o2, '(' + s[1][:-1] + ')'
v2 = []
if len(o) >= 3 and o[-1].startswith('CLEARTEMP(') and o[-3].startswith('temp['):
if TxMatch(o, len(o) - 3, ('temp[$0] = PyInt_FromLong ($1);',
'$3 = PyInt_AsSsize_t ( temp[$0] );',
'CLEARTEMP($0);'), v2):
v2[1] = v2[1].strip()
TxRepl(o, len(o) - 3, ('$3 = $1;',), v2)
return shortage((o,logic))
if TxMatch(o, len(o) - 3, ('temp[$0] = PyString_FromStringAndSize(&$2, 1);',
'$3 = c_Py_EQ_String(temp[$0], 1, "$4", $5);',
'CLEARTEMP($0);'), v2):
TxRepl(o, len(o) - 3, ('$3 = $2 == *"$4";',), v2)
return shortage((o,logic))
if TxMatch(o, len(o) - 3, ('temp[$0] = PyString_FromStringAndSize(&$2, 1);',
'$3 = c_Py_NE_String(temp[$0], 1, "$4", $5);',
'CLEARTEMP($0);'), v2):
TxRepl(o, len(o) - 3, ('$3 = $2 != *"$4";',), v2)
return shortage((o,logic))
if TxMatch(o, len(o) - 3, ('temp[$0] = PyInt_FromLong ($1);',
'$2 = PyInt_AS_LONG ( temp[$0] ) $3;',
'CLEARTEMP($0);'), v2):
v2[1] = v2[1].strip()
TxRepl(o, len(o) - 3, ('$2 = ($1) $3;',), v2)
return shortage((o,logic))
if TxMatch(o, len(o) - 3, ('temp[$0] = PyInt_FromLong ($2);',
'if (($3 = PyObject_Not ( temp[$0] )) == -1) goto $11;',
'CLEARTEMP($0);'), v2):
v2[2] = v2[2].strip()
TxRepl(o, len(o) - 3, ('$3 = ! $2;',), v2)
return shortage((o,logic))
if TxMatch(o, len(o) - 3, ('temp[$0] = PyBool_FromLong($2);',
'if (($1 = PyObject_IsTrue ( temp[$0] )) == -1) goto $5;',
'CLEARTEMP($0);'), v2):
v2[2] = v2[2].strip()
if v2[2] == v2[1]:
TxRepl(o, len(o) - 3, (), v2)
else:
TxRepl(o, len(o) - 3, ('$1 = $2;',), v2)
return shortage((o,logic))
if TxMatch(o, len(o) - 3, ('temp[$0] = PyBool_FromLong($2);',
'if (($1 = PyObject_Not ( temp[$0] )) == -1) goto $5;',
'CLEARTEMP($0);'), v2):
v2[2] = v2[2].strip()
TxRepl(o, len(o) - 3, ('$1 = ! $2;',), v2)
return shortage((o,logic))
## if len(o) >= 1:
## pprint(('Shortage----', logic, o))
return o, logic
def is_no_breaked(lis):
srepr = repr(lis)
if 'CONTINUE' in srepr or 'BREAK' in srepr or 'RAISE' in srepr or 'TRY' in srepr:
return False
return True
def generate_simple_efficient_if(expr, stmt, o):
e = []
for i in range(1, len(expr)):
if expr[i][0] == '!BOOLEAN' and expr[i][1][0] == '!AND_BOOLEAN':
for j in range(1, len(expr[i][1])):
e.append(expr[i][1][j])
else:
e.append(expr[i])
skip_e = {}
for e_it in e:
o1, logic = shortage(generate_logical_expr(e_it))
## pprint((logic, o1))
o.extend(o1)
if type(logic) is str and logic.startswith('(') and logic.endswith(')'):
logic = logic[1:-1].strip()
if logic == '1':
skip_e[e_it] = True
else:
o.Stmt('if (', logic, ') {')
Cls1(o, logic)
prev_used_fastloc = current_co.used_fastlocals.copy()
generate_list(stmt, o)
if stmt[-1][0] == 'RETURN_VALUE' and is_no_breaked(stmt):
current_co.used_fastlocals = prev_used_fastloc
for e_it in e:
if e_it not in skip_e:
o.append('}')
return
def generate_simple_efficient_if_not(expr, stmt, o):
o1, logic = shortage(generate_logical_expr(expr))
o.extend(o1)
o.Raw('if ( !(', logic, ') ) {')
Cls1(o, logic)
prev_used_fastloc = current_co.used_fastlocals.copy()
generate_list(stmt, o)
if stmt[-1][0] == 'RETURN_VALUE' and is_no_breaked(stmt):
current_co.used_fastlocals = prev_used_fastloc
o.append('}')
return
def generate_if(it,o):
if it[0][1][0] == '!1NOT' and len(it) > 3:
if_ = list(it[0])
if_[1] = if_[1][1]
it[0] = tuple(if_)
it[1], it[3] = it[3], it[1]
if it[0][1] == ('CONST', True):
generate_list(it[1], o)
return
if it[0][1] == ('CONST', False):
if len(it) == 3:
return
generate_list(it[3], o)
return
if len(it) == 3 and it[0][1][0] == '!BOOLEAN' and it[0][1][1][0] == '!AND_BOOLEAN':
generate_simple_efficient_if(it[0][1][1], it[1], o)
return
if len(it) == 3 and it[0][1][0] == '!AND_JUMP':
generate_simple_efficient_if(it[0][1], it[1], o)
return
if len(it) == 3 and it[0][1][0] == '!1NOT':
generate_simple_efficient_if_not(it[0][1][1], it[1], o)
return
o1, logic = shortage(generate_logical_expr(it[0][1]))
o.extend(o1)
## prev_used_fastloc = current_co.used_fastlocals.copy()
after_condition_used_fastloc = current_co.used_fastlocals.copy()
## pprint(('(THEN ' + current_co.co_name, current_co.used_fastlocals))
if type(logic) is str and logic.startswith('(') and logic.endswith(')'):
logic = logic[1:-1]
o.Stmt('if (', logic, ') {')
Cls1(o, logic)
generate_list(it[1], o)
## pprint((')THEN ' + current_co.co_name, current_co.used_fastlocals))
if it[1][-1][0] == 'RETURN_VALUE' and is_no_breaked(it[1]):
current_co.used_fastlocals = after_condition_used_fastloc.copy()
after_then_used_fastloc = current_co.used_fastlocals.copy()
if len(it) == 3:
o.append('}')
return
assert it[2][0] == ')(ELSE'
o.append('} else {')
current_co.used_fastlocals = after_condition_used_fastloc.copy()
## prev_used_fastloc = after_condition_used_fastloc.copy()
generate_list(it[3], o)
if it[3][-1][0] == 'RETURN_VALUE' and is_no_breaked(it[3]):
current_co.used_fastlocals = after_condition_used_fastloc
for k in after_then_used_fastloc.iterkeys():
current_co.used_fastlocals[k] = True
o.append('}')
assert it[4][0] == ')ENDIF'
def generate_while(it,o):
global try_jump_context, dropped_temp
have_else = it[2][0] == ')(ELSE'
if have_else:
else_cond = New('int')
o.Stmt(else_cond, '=', 1)
try_jump_context.append(False)
dropped_temp.append(('WHILE', ()))
o.append('for (;;) {')
o1, logic = shortage(generate_logical_expr(it[0][1]))
o.extend(o1)
if logic != '1' and logic != '(1)':
if type(logic) is str and logic.startswith('(') and logic.endswith(')'):
logic = logic[1:-1].strip()
o.Stmt('if (!(', logic, ')) break')
Cls1(o, logic)
if have_else:
o.Stmt(else_cond, '=', 0)
generate_list(it[1], o)
o.append('}')
del try_jump_context[-1]
del dropped_temp[-1]
if have_else:
o.Stmt ('if (', else_cond,') {')
Cls1(o, else_cond)
generate_list(it[3], o)
o.append('}')
assert len(it) == 5
return
assert len(it) == 3
def generate_for_and_else_new(it,o):
global try_jump_context, dropped_temp
iter = it[0][2]
riter = Expr1(iter, o)
riter2 = New()
o.Stmt(riter2, '=', 'PyObject_GetIter', riter)
Cls1(o, riter)
try_jump_context.append(False)
to_else = New('int')
o.Raw(to_else, ' = 1;')
dropped_temp.append(('FOR', (riter2,)))
o.append('for (;;) {')
ref = New()
o.Stmt(ref, '=', 'PyIter_Next', riter2)
o.Raw('if (PyErr_Occurred()) goto ', labl, ';')
UseLabl()
o.Stmt('if (!', ref, '){ break; }')
if len(it[0][1]) == 1:
generate_store(it[0][1][0], ref, o, 'PyIter_Next')
else:
generate_store(('SET_VARS', it[0][1]), ref, o, 'PyIter_Next')
Cls1(o, ref)
o.Raw(to_else, ' = 0;')
generate_list(it[1], o)
o.append('}')
del try_jump_context[-1]
del dropped_temp[-1]
Cls1(o, riter2)
o.Stmt('if (', to_else, ') {')
generate_list(it[3], o)
o.append('}')
Cls1(o, to_else)
assert len(it) in (3,5)
def replace_for_index(body, var, typed_index):
if IsCVar(var):
return body
return replace_subexpr(body, var, typed_index)
def generate_for_body_range_one_arg(o, hdr, body, pos_iter):
if len(hdr[1]) == 1 and hdr[1][0][0] == 'STORE_FAST' and not have_subexpr(body, hdr[1][0]):
body2 = replace_for_index(body, ('FAST', hdr[1][0][1]), ('!@PyInt_FromSsize_t', pos_iter, ('FAST', hdr[1][0][1])))
generate_list(body2, o)
else:
generate_list(body, o)
def generate_for_range_one_arg(it, o, range_arg):
global try_jump_context, dropped_temp
try_jump_context.append(False)
if type(range_arg) != int:
ref_arg = Expr1(range_arg, o)
cnt = New('Py_ssize_t')
o.Stmt(cnt, '=', 'PyInt_AsSsize_t', ref_arg)
Cls1(o, ref_arg)
else:
cnt = range_arg
dropped_temp.append(('FOR', ()))
## let = it[0][1][0]
pos_iter = New('Py_ssize_t')
o.Raw('for (', pos_iter, ' = 0; ', pos_iter, ' < ', cnt, '; ', pos_iter, ' ++) {')
ref = New()
o.PushInt(ref, pos_iter)
if len(it[0][1]) == 1:
generate_store(it[0][1][0], ref, o, 'PyInt_FromSsize_t')
else:
generate_store(('SET_VARS', it[0][1]), ref, o, 'PyInt_FromSsize_t')
Cls1(o, ref)
generate_for_body_range_one_arg(o, it[0], it[1], pos_iter)
o.append('}')
del try_jump_context[-1]
del dropped_temp[-1]
o.Cls(pos_iter, cnt)
def generate_for_range_two_arg(it, o, range_arg0, range_arg):
global try_jump_context, dropped_temp
try_jump_context.append(False)
if type(range_arg0) is tuple and range_arg0[0] == 'CONST':
range_arg0 = range_arg0[1]
if type(range_arg) is tuple and range_arg[0] == 'CONST':
range_arg = range_arg[1]
if type(range_arg0) != int:
ref_arg0 = Expr1(range_arg0, o)
cnt0 = New('Py_ssize_t')
o.Stmt(cnt0, '=', 'PyInt_AsSsize_t', ref_arg0)
Cls1(o, ref_arg0)
else:
cnt0 = range_arg0
if type(range_arg) != int:
ref_arg = Expr1(range_arg, o)
cnt = New('Py_ssize_t')
o.Stmt(cnt, '=', 'PyInt_AsSsize_t', ref_arg)
Cls1(o, ref_arg)
else:
cnt = range_arg
dropped_temp.append(('FOR', ()))
pos_iter = New('Py_ssize_t')
o.Raw('for (', pos_iter, ' = ', cnt0, ';', pos_iter, ' < ', cnt, ';', pos_iter, ' ++) {')
ref = New()
o.PushInt(ref, pos_iter)
if len(it[0][1]) == 1:
generate_store(it[0][1][0], ref, o, 'PyInt_FromSsize_t')
else:
generate_store(('SET_VARS', it[0][1]), ref, o, 'PyInt_FromSsize_t')
Cls1(o, ref)
generate_for_body_range_one_arg(o, it[0], it[1], pos_iter)
o.append('}')
del try_jump_context[-1]
del dropped_temp[-1]
o.Cls(pos_iter, cnt)
def generate_for_list_new(it,o):
global try_jump_context, dropped_temp
iter = it[0][2]
t = TypeExpr(iter)
assert IsListAll(t)
v = []
if TCmp(iter, v, ('!PyObject_Call', \
('!LOAD_BUILTIN', 'range'), \
('CONST', ('?',)), ('NULL',))) and\
type(v[0]) is int:
generate_for_range_one_arg(it, o, v[0])
return
if TCmp(iter, v, ('!PyObject_Call', \
('!LOAD_BUILTIN', 'range'), \
('!BUILD_TUPLE', ('?',)), ('NULL',))):
generate_for_range_one_arg(it, o, v[0])
return
if TCmp(iter, v, ('!PyObject_Call', \
('!LOAD_BUILTIN', 'range'), \
('CONST', ('?', '?')), ('NULL',))) and\
type(v[0]) is int and type(v[1]) is int:
generate_for_range_two_arg(it, o, v[0], v[1])
return
if TCmp(iter, v, ('!PyObject_Call', \
('!LOAD_BUILTIN', 'range'), \
('!BUILD_TUPLE', ('?', '?')), ('NULL',))):
generate_for_range_two_arg(it, o, v[0], v[1])
return
riter = Expr1(iter, o)
try_jump_context.append(False)
dropped_temp.append(('FOR', (riter,)))
pos_iter = New('int')
if IsList(t):
o.Raw('assert(PyList_CheckExact(', riter,'));')
o.Raw('for (',pos_iter,' = 0;', pos_iter, ' < PyList_GET_SIZE(', riter, ');',pos_iter, '++) {')
ref = New()
o.Stmt(ref, '=', 'PyList_GET_ITEM', riter, pos_iter)
if len(it[0][1]) == 1:
generate_store(it[0][1][0], ref, o, 'PyList_GET_ITEM')
else:
ty = None
if t[1] is not None:
ty = t[1]
mass_store(o, ref, it[0][1], 'PyList_GET_ITEM', ty)
## generate_store(('SET_VARS', it[0][1]), ref, o, 'PyList_GET_ITEM')
Cls1(o, ref)
generate_list(it[1], o)
o.append('}')
del try_jump_context[-1]
del dropped_temp[-1]
o.Cls(riter, pos_iter)
def generate_for_universal_new(it,o):
global try_jump_context, dropped_temp
iter = it[0][2]
riter = Expr1(iter, o)
riter2 = New()
pos_iter = New('int')
o.Raw(pos_iter, ' = 0;')
o.Raw(riter2, ' = NULL;')
o.Raw('if (!PyList_CheckExact(', riter, ') && !PyTuple_CheckExact(', riter, ')) {')
o.Stmt(riter2, '=', 'PyObject_GetIter', riter)
o.append('}')
try_jump_context.append(False)
dropped_temp.append(('FOR', (riter2, riter)))
o.append('for (;;) {')
ref = New()
o.Raw('if (PyList_CheckExact(', riter, ')) {')
o.Stmt('if (', pos_iter, '>= PyList_GET_SIZE(', riter, ')) break;')
o.Stmt(ref, '=', 'PyList_GET_ITEM', riter, pos_iter)
o.Raw(pos_iter, '++;')
o.Raw('} else if (PyTuple_CheckExact(', riter, ')) {')
o.Stmt('if (', pos_iter, '>= PyTuple_GET_SIZE(', riter, ')) break;')
o.Stmt(ref, '=', 'PyTuple_GET_ITEM', riter, pos_iter)
o.Raw(pos_iter, '++;')
o.append('} else {')
o.Stmt(ref, '=', 'PyIter_Next', riter2)
o.Raw('if (PyErr_Occurred()) goto ', labl, ';')
UseLabl()
o.Stmt('if (!', ref, '){ break; }')
o.append('}')
if len(it[0][1]) == 1:
generate_store(it[0][1][0], ref, o, 'PyIter_Next')
else:
generate_store(('SET_VARS', it[0][1]), ref, o, 'PyIter_Next')
Cls1(o, ref)
generate_list(it[1], o)
o.append('}')
del try_jump_context[-1]
del dropped_temp[-1]
o.Cls(riter, riter2, pos_iter)
def generate_for_file_new(it,o):
global try_jump_context, dropped_temp
iter = it[0][2]
riter = Expr1(iter, o)
riter2 = New()
o.Stmt(riter2, '=', 'PyObject_GetIter', riter)
try_jump_context.append(False)
dropped_temp.append(('FOR', (riter2, riter)))
o.append('for (;;) {')
ref = New()
o.Stmt(ref, '=', 'PyIter_Next', riter2)
o.Raw('if (PyErr_Occurred()) goto ', labl, ';')
UseLabl()
o.Stmt('if (!', ref, '){ break; }')
if len(it[0][1]) == 1:
generate_store(it[0][1][0], ref, o, 'PyIter_Next')
else:
generate_store(('SET_VARS', it[0][1]), ref, o, 'PyIter_Next')
Cls1(o, ref)
generate_list(it[1], o)
o.append('}')
del try_jump_context[-1]
del dropped_temp[-1]
o.Cls(riter, riter2)
def generate_for_fuple_of_int_new(it, o, tupl_int):
global try_jump_context, dropped_temp
try_jump_context.append(False)
pos_iter = New('int')
cnt = len(tupl_int)
val_iter = New('long')
refint = New('longref')
li = ''
for i in tupl_int:
li += str(i) + 'l, '
li = li[:-2]
dropped_temp.append(('FOR', ()))
o.append('{')
o.Raw('static long ', refint, '[] = {', li, '};')
o.Raw('for (', pos_iter, ' = 0;', pos_iter, ' < ', cnt, ';', pos_iter, ' ++) {')
## o.Raw(val_iter, ' = ', refint, '[', pos_iter, '];')
ref = New()
## o.PushInt(ref, val_iter)
o.Raw(ref, ' = PyInt_FromLong ( ', val_iter, ' = ', refint, '[', pos_iter, ']', ' );')
if len(it[0][1]) == 1:
generate_store(it[0][1][0], ref, o, 'PyInt_FromLong')
else:
generate_store(('SET_VARS', it[0][1]), ref, o, 'PyInt_FromLong')
Cls1(o, ref)
generate_for_body_tuple_of_int(o, it[0], it[1], val_iter)
o.append('}')
o.append('}')
del try_jump_context[-1]
del dropped_temp[-1]
o.Cls(pos_iter, val_iter, refint)
def generate_for_body_tuple_of_int(o, hdr, body, pos_iter):
if len(hdr[1]) == 1 and hdr[1][0][0] == 'STORE_FAST' and not have_subexpr(body, hdr[1][0]):
body2 = replace_for_index(body, ('FAST', hdr[1][0][1]), ('!@PyInt_FromSsize_t', pos_iter, ('FAST', hdr[1][0][1])))
generate_list(body2, o)
else:
generate_list(body, o)
def generate_for_tuple_new(it,o):
global try_jump_context, dropped_temp
iter = it[0][2]
if iter[0] == 'CONST' and all([type(x) is int for x in iter[1]]):
generate_for_fuple_of_int_new(it, o, iter[1])
return
riter = Expr1(iter, o)
try_jump_context.append(False)
dropped_temp.append(('FOR', (riter,)))
pos_iter = New('int')
if riter[0] != 'CONST':
o.Raw('assert(PyTuple_CheckExact(', riter,'));')
o.Raw('for (',pos_iter,' = 0;', pos_iter, ' < PyTuple_GET_SIZE(', riter, ');',pos_iter, '++) {')
ref = New()
o.Stmt(ref, '=', 'PyTuple_GET_ITEM', riter, pos_iter)
if len(it[0][1]) == 1:
generate_store(it[0][1][0], ref, o, 'PyTuple_GET_ITEM')
else:
generate_store(('SET_VARS', it[0][1]), ref, o, 'PyTuple_GET_ITEM')
Cls1(o, ref)
generate_list(it[1], o)
o.append('}')
del try_jump_context[-1]
del dropped_temp[-1]
o.Cls(riter, pos_iter)
def generate_for_str_new(it,o):
global try_jump_context, dropped_temp
iter = it[0][2]
riter = Expr1(iter, o)
try_jump_context.append(False)
dropped_temp.append(('FOR', (riter,)))
pos_iter = New('int')
if riter[0] != 'CONST':
o.Raw('assert(PyString_CheckExact(', riter,'));')
o.Raw('for (',pos_iter,' = 0;', pos_iter, ' < PyString_GET_SIZE(', riter, ');',pos_iter, '++) {')
ref = New()
o.Raw(ref, ' = PyString_FromStringAndSize ( PyString_AS_STRING ( ', riter, ' ) + ', pos_iter, ' , 1 );')
if len(it[0][1]) == 1:
generate_store(it[0][1][0], ref, o, 'PyString_FromStringAndSize')
else:
generate_store(('SET_VARS', it[0][1]), ref, o, 'PyString_FromStringAndSize')
Cls1(o, ref)
generate_list(it[1], o)
o.append('}')
del try_jump_context[-1]
del dropped_temp[-1]
o.Cls(riter, pos_iter)
def generate_for_enumerate_new(it,o, store1, store2, iter):
global try_jump_context, dropped_temp
riter = Expr1(iter, o)
riter2 = New()
pos_iter = New('int')
o.Raw(pos_iter, ' = 0;')
o.Raw(riter2, ' = NULL;')
o.Raw('if (!PyList_CheckExact(', riter, ') && !PyTuple_CheckExact(', riter, ')) {')
o.Stmt(riter2, '=', 'PyObject_GetIter', riter)
o.append('}')
try_jump_context.append(False)
dropped_temp.append(('FOR', (riter2, riter)))
o.append('for (;;) {')
ref = New()
o.Raw('if (PyList_CheckExact(', riter, ')) {')
o.Stmt('if (', pos_iter, '>= PyList_GET_SIZE(', riter, ')) break;')
o.Stmt(ref, '=', 'PyList_GET_ITEM', riter, pos_iter)
o.Raw('} else if (PyTuple_CheckExact(', riter, ')) {')
o.Stmt('if (', pos_iter, '>= PyTuple_GET_SIZE(', riter, ')) break;')
o.Stmt(ref, '=', 'PyTuple_GET_ITEM', riter, pos_iter)
o.append('} else {')
o.Stmt(ref, '=', 'PyIter_Next', riter2)
o.Raw('if (PyErr_Occurred()) goto ', labl, ';')
UseLabl()
o.Stmt('if (!', ref, '){ break; }')
o.append('}')
if len(it[0][1]) != 2:
Fatal('Strange enumerate', it[0])
ref_ind = New()
o.PushInt(ref_ind, pos_iter)
generate_store(it[0][1][0], ref_ind, o, 'PyIter_Next')
Cls1(o, ref_ind)
generate_store(it[0][1][1], ref, o, 'PyIter_Next')
Cls1(o, ref)
o.Raw(pos_iter, '++;')
generate_list(it[1], o)
o.append('}')
del try_jump_context[-1]
del dropped_temp[-1]
o.Cls(riter, riter2, pos_iter)
def generate_for_enumerate_list_new(it,o, store1, store2, iter):
global try_jump_context, dropped_temp
riter = Expr1(iter, o)
pos_iter = New('int')
try_jump_context.append(False)
dropped_temp.append(('FOR', (riter,)))
o.Raw('assert(PyList_CheckExact(', riter,'));')
o.Raw('for (',pos_iter,' = 0;', pos_iter, ' < PyList_GET_SIZE(', riter, ');',pos_iter, '++) {')
if len(it[0][1]) != 2:
Fatal('Strange enumerate', it[0])
ref_ind = New()
o.PushInt(ref_ind, pos_iter)
generate_store(it[0][1][0], ref_ind, o, 'PyList_GET_ITEM')
Cls1(o, ref_ind)
ref = New()
o.Stmt(ref, '=', 'PyList_GET_ITEM', riter, pos_iter)
generate_store(it[0][1][1], ref, o, 'PyList_GET_ITEM')
Cls1(o, ref)
generate_list(it[1], o)
o.append('}')
del try_jump_context[-1]
del dropped_temp[-1]
o.Cls(riter, pos_iter)
def generate_for_enumerate_tuple_new(it,o, store1, store2, iter):
global try_jump_context, dropped_temp
riter = Expr1(iter, o)
pos_iter = New('int')
try_jump_context.append(False)
dropped_temp.append(('FOR', (riter,)))
o.Raw('assert(PyTuple_CheckExact(', riter,'));')
o.Raw('for (',pos_iter,' = 0;', pos_iter, ' < PyTuple_GET_SIZE(', riter, ');',pos_iter, '++) {')
if len(it[0][1]) != 2:
Fatal('Strange enumerate', it[0])
ref_ind = New()
o.PushInt(ref_ind, pos_iter)
generate_store(it[0][1][0], ref_ind, o, 'PyTuple_GET_ITEM')
Cls1(o, ref_ind)
ref = New()
o.Stmt(ref, '=', 'PyTuple_GET_ITEM', riter, pos_iter)
generate_store(it[0][1][1], ref, o, 'PyTuple_GET_ITEM')
Cls1(o, ref)
generate_list(it[1], o)
o.append('}')
del try_jump_context[-1]
del dropped_temp[-1]
o.Cls(riter, pos_iter)
def generate_for_iteritems_generator_standard(it,o):
global try_jump_context, dropped_temp
iter = it[0][2]
riter = Expr1(iter, o)
try_jump_context.append(False)
dropped_temp.append(('FOR', (riter,)))
o.append('for (;;) {')
ref = New()
o.Stmt(ref, '=', 'PyIter_Next', riter)
o.Raw('if (PyErr_Occurred()) goto ', labl, ';')
UseLabl()
o.Stmt('if (!', ref, '){ break; }')
assert len(it[0][1]) == 2
ref1 = New()
## o.Stmt(ref1, '=', 'PyTuple_GetItem', ref, 0)
GetTupleItem(o, (tuple, 2), ref1, ref, 0)
generate_store(it[0][1][0], ref1, o, 'PyIter_Next')
Cls1(o, ref1)
ref1 = New()
GetTupleItem(o, (tuple, 2), ref1, ref, 1)
## o.Stmt(ref1, '=', 'PyTuple_GetItem', ref, 1)
generate_store(it[0][1][1], ref1, o, 'PyIter_Next')
Cls1(o, ref1)
Cls1(o, ref)
generate_list(it[1], o)
o.append('}')
del try_jump_context[-1]
del dropped_temp[-1]
Cls1(o, riter)
def generate_for_iteritems_generator_new(it,o, v):
global try_jump_context, dropped_temp
d = Expr1(v[2], o)
pos = New('Py_ssize_t')
try_jump_context.append(False)
dropped_temp.append(('FOR', (d, pos)))
o.Raw(pos, ' = 0;')
k, v = New(), New()
o.Raw('while (PyDict_Next(', d, ', ', ('&', pos), ', ', ('&', k), ', ', ('&', v), ')) {')
assert len(it[0][1]) == 2
o.INCREF(k)
o.INCREF(v)
generate_store(it[0][1][0], k, o, 'PyDict_Next')
generate_store(it[0][1][1], v, o, 'PyDict_Next')
o.Cls(k,v)
generate_list(it[1], o)
o.append('}')
del try_jump_context[-1]
del dropped_temp[-1]
o.Cls(d,pos)
def generate_for_iterkeys_generator_new(it,o, v):
global try_jump_context, dropped_temp
d = Expr1(v[1], o)
pos = New('Py_ssize_t')
try_jump_context.append(False)
dropped_temp.append(('FOR', (d, pos)))
o.Raw(pos, ' = 0;')
k, v = New(), New()
o.Raw('while (PyDict_Next(', d, ', ', ('&', pos), ', ', ('&', k), ', ', ('&', v), ')) {')
assert len(it[0][1]) == 1
o.INCREF(k)
o.INCREF(v)
generate_store(it[0][1][0], k, o, 'PyDict_Next')
o.Cls(k,v)
generate_list(it[1], o)
o.append('}')
del try_jump_context[-1]
del dropped_temp[-1]
o.Cls(d,pos)
def generate_for_itervalues_generator_new(it,o, v):
global try_jump_context, dropped_temp
d = Expr1(v[1], o)
pos = New('Py_ssize_t')
try_jump_context.append(False)
dropped_temp.append(('FOR', (d, pos)))
o.Raw(pos, ' = 0;')
k, v = New(), New()
o.Raw('while (PyDict_Next(', d, ', ', ('&', pos), ', ', ('&', k), ', ', ('&', v), ')) {')
assert len(it[0][1]) == 1
o.INCREF(k)
o.INCREF(v)
generate_store(it[0][1][0], v, o, 'PyDict_Next')
o.Cls(k,v)
generate_list(it[1], o)
o.append('}')
del try_jump_context[-1]
del dropped_temp[-1]
o.Cls(d,pos)
def generate_for_new(it,o):
global try_jump_context, dropped_temp
if len(it) == 5 and it[2][0] == ')(ELSE':
generate_for_and_else_new(it,o)
return
iter = it[0][2]
type_for = TypeExpr(iter)
if IsListAll(type_for):
generate_for_list_new(it,o)
return
if IsStr(type_for):
generate_for_str_new(it,o)
return
if IsTuple(type_for):
generate_for_tuple_new(it,o)
return
if type_for == Kl_File:
generate_for_file_new(it,o)
return
if type_for == Kl_Generator:
v = []
if TCmp(it[0], v, ('(FOR', ('?', '?'), \
('!PyObject_Call', ('!LOAD_BUILTIN', 'enumerate'), \
('!BUILD_TUPLE', ('?',)), ('NULL',)))):
t = TypeExpr(v[2])
if IsList(t):
generate_for_enumerate_list_new(it, o, v[0], v[1], v[2])
elif IsTuple(t):
generate_for_enumerate_tuple_new(it, o, v[0], v[1], v[2])
else:
generate_for_enumerate_new(it, o, v[0], v[1], v[2])
return
elif TCmp(it[0], v, ('(FOR', ('?', '?'), \
('!PyObject_Call', ('!PyObject_GetAttr', '?', ('CONST', 'iteritems')), \
('CONST', ()), ('NULL',)))):
t = TypeExpr(v[2])
if IsDict(t):
if dirty_iteritems:
generate_for_iteritems_generator_new(it,o, v)
return
else:
generate_for_iteritems_generator_standard(it,o)
return
elif TCmp(it[0], v, ('(FOR', ('?',), \
('!PyObject_Call', ('!PyObject_GetAttr', '?', ('CONST', 'iterkeys')), \
('CONST', ()), ('NULL',)))) and dirty_iteritems:
t = TypeExpr(v[1])
if IsDict(t):
generate_for_iterkeys_generator_new(it,o, v)
return
elif TCmp(it[0], v, ('(FOR', ('?',), \
('!PyObject_Call', ('!PyObject_GetAttr', '?', ('CONST', 'itervalues')), \
('CONST', ()), ('NULL',)))) and dirty_iteritems:
t = TypeExpr(v[1])
if IsDict(t):
generate_for_itervalues_generator_new(it,o, v)
return
if type_for == Kl_XRange:
generate_for_xrange_new(it,o)
return
return generate_for_universal_new(it,o)
## def generate_for_generator_new(it,o):
## global try_jump_context, dropped_temp
## iter = it[0][2]
## riter = Expr1(iter, o)
## try_jump_context.append(False)
## dropped_temp.append(('FOR', (riter,)))
## o.append('for (;;) {')
## ref = New()
## o.Stmt(ref, '=', 'PyIter_Next', riter)
## o.Raw('if (PyErr_Occurred()) goto ', labl, ';')
## UseLabl()
## o.Stmt('if (!', ref, '){ break; }')
## if len(it[0][1]) == 1:
## generate_store(it[0][1][0], ref, o, 'PyIter_Next')
## else:
## generate_store(('SET_VARS', it[0][1]), ref, o, 'PyIter_Next')
## Cls1(o, ref)
## generate_list(it[1], o)
## o.append('}')
## del try_jump_context[-1]
## del dropped_temp[-1]
## Cls1(o, riter)
def generate_for_xrange_new(it,o):
global try_jump_context, dropped_temp
iter = it[0][2]
v = []
if TCmp(iter, v, ('!PyObject_Call', \
('!LOAD_BUILTIN', 'xrange'), \
('CONST', ('?',)), ('NULL',))) and\
type(v[0]) is int:
generate_for_range_one_arg(it, o, v[0])
return
if TCmp(iter, v, ('!PyObject_Call', \
('!LOAD_BUILTIN', 'xrange'), \
('!BUILD_TUPLE', ('?',)), ('NULL',))):
generate_for_range_one_arg(it, o, v[0])
return
if TCmp(iter, v, ('!PyObject_Call', \
('!LOAD_BUILTIN', 'xrange'), \
('CONST', ('?', '?')), ('NULL',))) and\
type(v[0]) is int and type(v[1]) is int:
generate_for_range_two_arg(it, o, v[0], v[1])
return
if TCmp(iter, v, ('!PyObject_Call', \
('!LOAD_BUILTIN', 'xrange'), \
('!BUILD_TUPLE', ('?', '?')), ('NULL',))):
generate_for_range_two_arg(it, o, v[0], v[1])
return
riter = Expr1(iter, o)
riter2 = New()
o.Stmt(riter2, '=', 'PyObject_GetIter', riter)
Cls1(o, riter)
try_jump_context.append(False)
dropped_temp.append(('FOR', (riter2,)))
o.append('for (;;) {')
ref = New()
o.Stmt(ref, '=', 'PyIter_Next', riter2)
o.Raw('if (PyErr_Occurred()) goto ', labl, ';')
UseLabl()
o.Stmt('if (!', ref, '){ break; }')
if len(it[0][1]) == 1:
generate_store(it[0][1][0], ref, o, 'PyIter_Next')
else:
generate_store(('SET_VARS', it[0][1]), ref, o, 'PyIter_Next')
Cls1(o, ref)
generate_list(it[1], o)
o.append('}')
del try_jump_context[-1]
del dropped_temp[-1]
Cls1(o, riter2)
assert len(it) in (3,5)
## def expanded_range(iter):
## v = []
## if TCmp(iter, v, ('!BUILD_LIST', '?')):
## li = v[0]
## rn = []
## for it in li:
## if it[0] != 'CONST':
## return None
## rn.append(it[1])
## if tuple(rn) == tuple(range(len(rn))):
## return ('!PyObject_Call', ('!LOAD_BUILTIN', 'range'), ('CONST', ('?',)), ('NULL',))
## return None
def is_like_float(a):
if detect_float and have_floatmul(a):
return True
return False
def have_floatmul(a):
if type(a) is tuple and len(a) > 0 and a != ('NULL',) and \
type(a[0]) is str and IsFloat(TypeExpr(a)):
return True
if type(a) is tuple:
if len(a) > 0 and type(a[0]) is str:
if len(a) >= 2 and a[0] == '!PyNumber_Multiply' and not (a[1][0] in ('!BUILD_LIST', '!BUILD_TUPLE')):
return True
if a[0] == '!PyNumber_Divide':
return True
if a[0] == 'CONST':
return False
for i in a:
if type(i) is tuple and len(i) > 0 and type(i[0]) is str and i[0] != 'NULL':
if have_floatmul(i):
return True
return False
if type(a) is list:
for i in a:
if have_floatmul(i):
return True
return False
return False
def have_subexpr(a,b):
if a is b:
return True
if type(a) is type(b):
if len(a) == len(b) and type(a[0]) is type(b[0]):
if a == b:
return True
if type(a) is tuple:
if len(a) > 0 and type(a[0]) is str and a[0] == 'CONST':
return False
for i in a:
if have_subexpr(i,b):
return True
return False
if type(a) is list:
for i in a:
if have_subexpr(i,b):
return True
return False
return False
def find_statement_calculate_const(a, b):
if type(a) is tuple and len(a) >= 2 and a[1] == b and \
type(a[0]) is str and a[0][:6] == 'STORE_':
return a
if type(a) is tuple and len(a) >= 2 and \
type(a[0]) is str and a[0] == 'IMPORT_FROM_AS' and b in a[3][1]:
return a
if type(a) is tuple:
if len(a) > 0 and a[0] == 'CONST':
return False
for i in a:
ret = find_statement_calculate_const(i,b)
if ret == True:
return
if type(ret) is tuple:
if ret[0] in ('STORE', 'SEQ_ASSIGN', 'SET_EXPRS_TO_VARS'):
return ret
return a
return False
if type(a) is list:
for i in a:
ret = find_statement_calculate_const(i,b)
if type(ret) is tuple:
if ret[0] in ('STORE', 'SEQ_ASSIGN', 'SET_EXPRS_TO_VARS'):
return ret
return ret
return False
def TCmp(e,v,p, trace = None):
assert type(v) is list
if trace is not None:
pprint(( 'Parameters:', e,v,p))
if type(p) is str:
if p == '?':
v.append(e)
if trace is not None: print 'Cmp success ', e,v,p
return True
if type(e) is str and e == p:
if trace is not None: print 'Cmp success ', e,v,p
return True
if p.startswith(':') and p.endswith(':'):
s = p[1:-1]
if Is3(e, s):
v.append((e,s, Val3(e,s)))
if trace != None: print 'Cmp success ', e,v,p
return True
del v[:]
return False
if type(p) is type:
if type(e) is p:
v.append(e)
if trace is not None: print 'Cmp success ', e,v,p
return True
del v[:]
return False
if type(p) is tuple:
if len(p) > 0 and type(p[0]) is str and p[0] == '|':
if e in p[1:]:
if trace is not None: print 'Cmp success ', e,v,p
return True
if type(e) is tuple:
if len(e) != len(p):
del v[:]
return False
for i,p0 in enumerate(p):
if trace is not None: print 'Cmp', i, p0
if p0 is None and e[i] is None:
continue
if type(p0) is str:
if p0 == '*':
v.append(e[i:])
if trace is not None: print 'Cmp success ', e,v,p
return True
if p0 == '?':
v.append(e[i])
continue
if type(e[i]) is str:
if e[i] != p0:
if p0.startswith(':') and p0.endswith(':'):
s = p0[1:-1]
if Is3(e[i], s):
v.append((e[i],s, Val3(e[i],s)))
if trace != None: print 'Cmp success ', e[i],v,p
continue
del v[:]
return False
else:
continue
elif not TCmp(e[i], v, p0, trace):
del v[:]
return False
elif not TCmp(e[i], v, p0, trace):
del v[:]
return False
if trace is not None: print 'Cmp success ', e,v,p
return True
del v[:]
return False
if type(p) is list:
if type(e) == type(p):
if len(e) != len(p):
del v[:]
return False
for i,p0 in enumerate(p):
if not TCmp(e[i], v, p0):
del v[:]
return False
if trace is not None: print 'Cmp success ', e,v,p
return True
del v[:]
return False
if type(p) is dict:
if e in p:
v.append(e)
if trace is not None: print 'Cmp success ', e,v,p
return True
del v[:]
return False
if e == p:
if trace is not None: print 'Cmp success ', e,v,p
return True
del v[:]
return False
def update_v_0_1(v):
try:
if v[0]:
v[0] = True
else:
v[0] = False
except:
pass
def class_create_to_dict_create(nm):
cmd = N2C(nm).cmds[1]
cmd = [x for x in cmd if x[0] != '.L' and x != ('RETURN_VALUE', ('f->f_locals',))]
## ok = True
dic = []
for x in cmd:
v = []
if TCmp(x, v, ('STORE', (('STORE_NAME', '?'),), (('!MK_FUNK', '?', ('CONST', ())),))):
dic.append((('CONST', v[0]), ('!MK_FUNK', v[1], ('CONST', ()))))
continue
v = []
if TCmp(x, v, ('STORE', (('STORE_NAME', '?'),), (('CONST', '?'),))):
dic.append((('CONST', v[0]), ('CONST', v[1])))
continue
return None
return DictFromArgs(tuple(dic))
def repl_list(a, up):
i = 0
assert type(a) is list
aa = a #[:]
updated = False
while i < len(aa):
assert type(i) is int
if i < 0:
i = 0
continue
s = aa[i]
v = []
v0 = []
## v1 = []
v2 = []
if i < len(aa) - 2 and type(s) is tuple and len(s) > 0 and \
type(s[0]) is str and s[0] == '(FOR' and \
TCmp(s, v, ('(FOR', ('?',), \
('!PyObject_Call', ('!LOAD_BUILTIN', 'range'), \
('!BUILD_TUPLE', ('?',)), \
('NULL',)))) and aa[i+1] == [('PASS',)] and\
aa[i+2] == (')ENDFOR',):
s1 = [('(IF', ('!PyObject_RichCompare(', v[1], ('CONST', 0), 'Py_GT')), [('STORE', (v[0],), (('!PyNumber_Subtract', v[1], ('CONST', 1)),))], (')ENDIF',)]
aa[i:i+3] = s1
updated = True
i -= 10
continue
if i < len(aa) - 2 and type(s) is tuple and len(s) > 0 and \
type(s[0]) is str and s[0] == '(FOR' and \
TCmp(s, v, ('(FOR', (('STORE_FAST', '?'),), \
('!PyObject_Call', ('!LOAD_BUILTIN', 'range'), \
('CONST', ('?', '?')), \
('NULL',)))) and type(aa[i+1]) is list and \
aa[i+2] == (')ENDFOR',):
if type(v[1]) is int and type(v[2]) is int and \
v[2] - v[1] < 10 and v[2] - v[1] >= 0 and \
not repr(('STORE_FAST', v[0])) in repr(aa[i+1]):
s1 = []
for i_ in range(v[1], v[2]):
s1.extend(replace_subexpr(aa[i+1], ('FAST', v[0]), ('CONST', i_)))
s1.append(('STORE', (('STORE_FAST', v[0]),), (('CONST', v[2] - 1),)))
aa[i:i+3] = s1
updated = True
i -= 10
continue
if i < len(aa) - 2 and type(s) is tuple and len(s) > 0 and \
type(s[0]) is str and s[0] == '(FOR' and \
TCmp(s, v, ('(FOR', (('?', '?'),), ('CONST', ()))) \
and type(aa[i+1]) is list and \
aa[i+2] == (')ENDFOR',):
aa[i:i+3] = []
updated = True
i -= 10
continue
if type(s) is tuple and len(s) == 3 and type(s[0]) is str and \
s[0] == 'SET_EXPRS_TO_VARS':
if TCmp(s, v, ('SET_EXPRS_TO_VARS', (('STORE_FAST', '?'), '?'), ('CLONE', '?'))):
s1 = [('STORE', (('STORE_FAST', v[0]),), (v[2],)), ('STORE', (v[1],), (('FAST', v[0]),))]
aa[i:i+1] = s1
updated = True
i -= 10
continue
if TCmp(s, v, ('SET_EXPRS_TO_VARS', ('?', '?'), (('CONST', '?'), ('CONST', '?')))):
s1 = [('STORE', (v[0],), (('CONST', v[2]),)), ('STORE', (v[1],), (('CONST', v[3]),))]
aa[i:i+1] = s1
updated = True
i -= 10
continue
if TCmp(s, v, ('SET_EXPRS_TO_VARS', ('?', '?', '?'), (('CONST', '?'), ('CONST', '?'), ('CONST', '?')))):
s1 = [('STORE', (v[0],), (('CONST', v[3]),)), ('STORE', (v[1],), (('CONST', v[4]),)), ('STORE', (v[2],), (('CONST', v[5]),))]
aa[i:i+1] = s1
updated = True
i -= 10
continue
if TCmp(s, v, ('SET_EXPRS_TO_VARS', ('?', '?', '?', '?'), (('CONST', '?'), ('CONST', '?'), ('CONST', '?'), ('CONST', '?')))):
s1 = [('STORE', (v[0],), (('CONST', v[4]),)), ('STORE', (v[1],), (('CONST', v[5]),)), \
('STORE', (v[2],), (('CONST', v[6]),)), ('STORE', (v[3],), (('CONST', v[7]),))]
aa[i:i+1] = s1
updated = True
i -= 10
continue
if TCmp(s, v, ('SET_EXPRS_TO_VARS', ('?', '?'), (('!BUILD_LIST', ()), ('!BUILD_LIST', ())))):
s1 = [('STORE', (v[0],), (('!BUILD_LIST', ()),)), ('STORE', (v[1],), (('!BUILD_LIST', ()),))]
aa[i:i+1] = s1
updated = True
i -= 10
continue
if TCmp(s, v, ('SET_EXPRS_TO_VARS', ('?', '?', '?'), (('!BUILD_LIST', ()), ('!BUILD_LIST', ()), ('!BUILD_LIST', ())))):
s1 = [('STORE', (v[0],), (('!BUILD_LIST', ()),)), ('STORE', (v[1],), (('!BUILD_LIST', ()),)), ('STORE', (v[2],), (('!BUILD_LIST', ()),))]
aa[i:i+1] = s1
updated = True
i -= 10
continue
if TCmp(s, v, ( 'SET_EXPRS_TO_VARS',
(('STORE_FAST', '?'), ('STORE_FAST', '?')),
( '?', '?'))):
if repr(('FAST', v[0])) not in repr([v[2], v[3]]) and repr(('STORE_FAST', v[0])) not in repr([v[2], v[3]]) and \
repr(('FAST', v[1])) not in repr([v[2], v[3]]) and repr(('STORE_FAST', v[1])) not in repr([v[2], v[3]]):
s1 = [('STORE', (('STORE_FAST', v[0]),), (v[2],)),
('STORE', (('STORE_FAST', v[1],),), (v[3],))]
aa[i:i+1] = s1
updated = True
i -= 10
continue
if TCmp(s, v, ( 'SET_EXPRS_TO_VARS',
(('STORE_FAST', '?'), ('STORE_FAST', '?'), ('STORE_FAST', '?')),
( '?', '?', '?'))):
if repr(('FAST', v[0])) not in repr([v[3], v[4], v[5]]) and repr(('STORE_FAST', v[0])) not in repr([v[3], v[4], v[5]]) and \
repr(('FAST', v[1])) not in repr([v[3], v[4], v[5]]) and repr(('STORE_FAST', v[1])) not in repr([v[3], v[4], v[5]]) and \
repr(('FAST', v[2])) not in repr([v[3], v[4], v[5]]) and repr(('STORE_FAST', v[2])) not in repr([v[3], v[4], v[5]]):
s1 = [('STORE', (('STORE_FAST', v[0]),), (v[3],)),
('STORE', (('STORE_FAST', v[1]),), (v[4],)),
('STORE', (('STORE_FAST', v[2]),), (v[5],))]
aa[i:i+1] = s1
updated = True
i -= 10
continue
if TCmp(s, v, ('SET_EXPRS_TO_VARS',
(('STORE_NAME', '?'), ('STORE_NAME', '?')),
(('CONST', '?'), ('CONST', '?')))):
s1 = [('STORE', (('STORE_NAME', v[0]),), (('CONST', v[2]),)), \
('STORE', (('STORE_NAME', v[1]),), (('CONST', v[2]),))]
aa[i:i+1] = s1
updated = True
i -= 10
continue
if TCmp(s, v, ('SET_EXPRS_TO_VARS', '?', '?')):
li = [x for x in v[1] if x[0] != 'FAST']
if len(li) == 0:
li1 = [x for x in v[1]]
li2 = [('STORE_FAST', x[1]) for x in v[1]]
li0 = repr(v[0])
li3 = [x for x in range(len(li1)) if repr(li1[x]) in li0 or repr(li2[x]) in li0]
if len(li3) == 0:
s1 = []
for x in range(len(li1)):
s1.append(('STORE', (v[0][x],), (li1[x],)))
aa[i:i+1] = s1
updated = True
i -= 10
continue
v = []
if type(s) is tuple and len(s) > 0 and type(s[0]) is str and s[0] == 'STORE':
if i < len(aa) - 2 and \
TCmp(s, v, ('STORE', (('STORE_NAME', '?'),), (('!MK_FUNK', '?', ('CONST', ())),))) and\
i+2 < len(aa) and aa[i+1][0] == '.L' and\
TCmp(aa[i+2], v2, ('STORE', ('?',), \
(('!PyObject_Call', ('!LOAD_NAME', v[0]), \
('CONST', ()), ('NULL',)),))):
ret2 = ('!PyObject_Call', ('!LOAD_NAME', v[0]), ('CONST', ()), ('NULL',)) # unchanged
newstor = ('STORE', (v2[0],), (call_calc_const(v[1], ('CONST', ()), ret2),))
if aa[i+2] != newstor:
aa[i+2] = newstor
updated = True
i -= 10
continue
v = []
if TCmp(aa[i:i+3], v, [('STORE', (('STORE_FAST', '?'),), ('?',)),
('.L', '?'),
('RETURN_VALUE', ('FAST', '?'))]):
if v[0] == v[3]:
aa[i:i+2] = [('RETURN_VALUE', v[1])]
updated = True
i -= 10
continue
v = []
if TCmp(aa[i:i+3], v, [('STORE', (('STORE_FAST', '?'),), ('?',)),
('.L', '?'),
('RETURN_VALUE', '?')]):
repr0 = repr(('FAST', v[0]))
repr1 = repr(v[3])
repr2 = repr(v[1])
is1 = 'CALL' in repr1 or 'Call' in repr1
is2 = 'CALL' in repr2 or 'Call' in repr2
if repr1.count(repr0) == 1:
if is1 and is2:
pass
else:
aa[i:i+2] = [('RETURN_VALUE', replace_subexpr(v[3], ('FAST', v[0]), v[1]))]
updated = True
i -= 10
continue
if repr1.count(repr0) == 0:
aa[i:i+2] = [('UNPUSH', v[1]),
('.L', v[2]),
('RETURN_VALUE', v[3])]
updated = True
i -= 10
continue
v = []
if TCmp(s, v, ('STORE',
(('STORE_CALC_CONST', ('STORE_NAME', '?')),),
( ( '!_PyEval_BuildClass',
('!PyObject_Call', ('!MK_FUNK', '?', ('CONST', ())), ('CONST', ()), ('NULL',)),
'?',
('CONST', '?')),))) and v[0] == v[1] and v[1] == v[3]:
dic = class_create_to_dict_create(v[0])
if dic is not None:
aa[i] = ('STORE',
(('STORE_CALC_CONST', ('STORE_NAME', v[0])),),
( ( '!_PyEval_BuildClass',
dic,
v[2],
('CONST', v[3])),))
updated = True
i -= 10
continue
v = []
if TCmp(aa[i:i+3], v, [
( 'STORE',
(('STORE_FAST', '?'),),
( '?',)),
('.L', '?'),
( 'STORE',
(('STORE_FAST', '?'),),
(('!CALL_CALC_CONST', '?', '?'),))]) and v[0] == v[3] and repr(('FAST', v[0])) not in repr(v[5]):
aa[i:i+3] = [
( 'UNPUSH', v[1] ),
('.L', v[2]),
( 'STORE',
(('STORE_FAST', v[0]),),
(('!CALL_CALC_CONST', v[4], v[5]),))]
updated = True
i -= 10
continue
if i < len(aa) - 2 and aa[i+1][0] == '.L' and aa[i+2][0] == 'STORE':
v = []
v2 = []
if TCmp(aa[i:i+3], v, [
('STORE', (('STORE_FAST', '?'),), (('FAST', '?'),)),
('.L', '?'),
('STORE', (('STORE_FAST', '?'),), (('FAST', '?'),))]) and v[0] == v[4]:
aa[i+2] = ('STORE', (('STORE_FAST', v[3]),), (('FAST', v[1]),))
updated = True
i -= 10
continue
if i < len(aa) - 2 and aa[i+1][0] == '.L' and aa[i+2][0] == '(IF':
v = []
v2 = []
srepr = repr(aa[i+2])
if TCmp(aa[i:i+2], v, [
('STORE', (('STORE_FAST', '?'),), (('FAST', '?'),)),
('.L', '?')]) and repr(('FAST', v[0])) in srepr and not 'STORE_FAST' in srepr:
aa[i+2] = replace_subexpr(aa[i+2], ('FAST', v[0]), ('FAST', v[1]))
updated = True
i -= 10
continue
## Commented 11 09 2011 -- illegall execution sequence
## if i < len(aa) - 4 and aa[i+1][0] == '.L' and aa[i+2][0] == '(IF' and aa[i+4][0] == ')ENDIF':
## v = []
## v2 = []
## srepr = repr(aa[i+1:i+5])
## if TCmp(aa[i:i+2], v, [('STORE', (('STORE_FAST', '?'),), ('?',)), ('.L', '?')]) and \
## repr(('FAST', v[0])) not in srepr and repr(('STORE_FAST', v[0])) not in srepr:
## aa[i:i+5] = aa[i+1:i+5] + [aa[i]]
## updated = True
## i -= 10
## continue
## if len(aa[i]) == 0:
## print i
## pprint(aa[:])
if i < len(aa) - 2 and type(aa[i]) is tuple and type(aa[i+1]) is tuple and aa[i][0] == '.L' == aa[i+1][0]:
del aa[i]
updated = True
i -= 10
continue
v = []
v2 = []
if type(s) is tuple and len(s) == 3 and type(s[0]) is str and s[0] == 'STORE' and len(s[1]) == 1 and len(s[2]) == 1:
if s[2][0][0] == '!CALL_CALC_CONST':
expr = subroutine_inlined(s[2][0][1], s[2][0][2])
if expr is not None and expr[-1][0] == 'RETURN_VALUE' and 'RETURN_VALUE' not in repr(expr[:-1]):
aa[i:i+1] = expr[:-1] + [('STORE', s[1], (expr[-1][1],))]
print '~~ proc/store inlined', s[2][0][1], len(repr(expr))
updated = True
i -= 10
continue
if s[2][0][0] == '!COND_METH_EXPR' and len(s[2][0]) == 4:
cond = s[2][0]
condhead = cond[0:3]
condvars = cond[3]
if condhead[1][0] == 'FAST':
if len(condvars) > 1:
arg, action = condvars[0]
nm = arg[1]
isnew = arg[0] == T_NEW_CL_INST
if isnew:
aa[i:i+1] = [('(IF', ('!BOOLEAN', ('!_EQ_', ('!PyObject_Type', condhead[1]), ('CALC_CONST', nm)))),
[('STORE', s[1], (action,))],
(')(ELSE',),
[('STORE', s[1], (condhead + (condvars[1:],),))],
(')ENDIF',)]
updated = True
i -= 10
continue
if len(condvars) == 1:
arg, action = condvars[0]
nm = arg[1]
isnew = arg[0] == T_NEW_CL_INST
if isnew:
aa[i:i+1] = [('(IF', ('!BOOLEAN', ('!_EQ_', ('!PyObject_Type', condhead[1]), ('CALC_CONST', nm)))),
[('STORE', s[1], (action,))],
(')(ELSE',),
[('STORE', s[1], (condhead[2],))],
(')ENDIF',)]
updated = True
i -= 10
continue
if type(s) is tuple and len(s) == 2 and type(s[0]) is str and s[0] == 'RETURN_VALUE':
if s[1][0] == '!CALL_CALC_CONST':
expr = subroutine_inlined(s[1][1], s[1][2])
if expr is not None:
assert expr[-1][0] == 'RETURN_VALUE' and 'RETURN_VALUE' not in repr(expr[:-1])
aa[i:i+1] = expr
print '~~ proc/return inlined', s[1][1], len(repr(expr))
updated = True
i -= 10
continue
if s[1][0] == '!COND_METH_EXPR' and len(s[1]) == 4:
cond = s[1]
condhead = cond[0:3]
condvars = cond[3]
if condhead[1][0] == 'FAST':
if len(condvars) > 1:
arg, action = condvars[0]
nm = arg[1]
isnew = arg[0] == T_NEW_CL_INST
if isnew:
aa[i:i+1] = [('(IF', ('!BOOLEAN', ('!_EQ_', ('!PyObject_Type', condhead[1]), ('CALC_CONST', nm)))),
[('RETURN_VALUE', action)],
(')(ELSE',),
[('RETURN_VALUE', condhead + (condvars[1:],))],
(')ENDIF',)]
updated = True
i -= 10
continue
if len(condvars) == 1:
arg, action = condvars[0]
nm = arg[1]
isnew = arg[0] == T_NEW_CL_INST
if isnew:
aa[i:i+1] = [('(IF', ('!BOOLEAN', ('!_EQ_', ('!PyObject_Type', condhead[1]), ('CALC_CONST', nm)))),
[('RETURN_VALUE', action)],
(')(ELSE',),
[('RETURN_VALUE', condhead[2])],
(')ENDIF',)]
updated = True
i -= 10
continue
if type(s) is tuple and len(s) == 2 and type(s[0]) is str and s[0] == 'UNPUSH':
t = TypeExpr(s[1])
v = []
if TCmp(s, v, ( 'UNPUSH', ('!BOOLEAN', ('!_EQ_', ('!PyObject_Type', ('PY_TYPE', 'NewClassInstance', '?', '?', None)), ('CALC_CONST', '?'))))) and v[0] == v[2]:
del aa[i]
updated = True
i -= 10
continue
if t is not None and t != Kl_None:
if ( IsCType(t) or IsIntUndefSize(t) ) and s[1][0] in ('!PyNumber_Subtract', '!PyNumber_Add', '!PyNumber_And','!PyNumber_Or', '!PyNumber_Divide', '!PyNumber_Multiply'):
aa[i:i+1] = [('UNPUSH', s[1][1]), ('UNPUSH', s[1][2])]
updated = True
i -= 10
continue
if s[1][0] in ('FAST', 'CONST'):
del aa[i]
updated = True
i -= 10
continue
if s[1][0] == 'PY_TYPE':
aa[i:i+1] = [('UNPUSH', s[1][3])]
updated = True
i -= 10
continue
if TCmp(s[1], v, ('CALC_CONST', '?')):
del aa[i]
if len(aa) == 0:
aa.append(('PASS',))
updated = True
i -= 10
continue
if TCmp(s[1], v, ('!COND_EXPR', '?', '?', '?')):
if v[1] != v[2]:
s1 = [('(IF', v[0]), [('UNPUSH', v[1])], (')(ELSE',), [('UNPUSH', (v[2]))], (')ENDIF',)]
aa[i:i+1] = s1
updated = True
i -= 10
continue
if TCmp(s[1], v, ('!PyObject_Call',
('!LOAD_BUILTIN', 'delattr'),
('!BUILD_TUPLE', ('?', '?')), ('NULL',))):
s1 = [('PYAPI_CALL', ('PyObject_SetAttr', v[0], v[1], 'NULL'))]
aa[i:i+1] = s1
updated = True
i -= 10
continue
if s[1][0] == '!CALL_CALC_CONST':
expr = subroutine_inlined(s[1][1], s[1][2])
if expr is not None and expr[-1] == ('RETURN_VALUE', ('CONST', None)):
aa[i:i+1] = expr[:-1]
print '~~ proc inlined', s[1][1], len(repr(expr[:-1]))
updated = True
i -= 10
continue
if expr is not None and expr[-1][0] == 'RETURN_VALUE':
aa[i:i+1] = expr[:-1] + [('UNPUSH', expr[-1][1])]
print '~~ proc inlined', s[1][1], len(repr(expr[:-1] + [('UNPUSH', expr[-1][1])]))
updated = True
i -= 10
continue
if s[1][0] == '!COND_METH_EXPR' and len(s[1]) == 4:
cond = s[1]
condhead = cond[0:3]
condvars = cond[3]
if condhead[1][0] == 'FAST':
if len(condvars) > 1:
arg, action = condvars[0]
nm = arg[1]
isnew = arg[0] == T_NEW_CL_INST
if isnew:
aa[i:i+1] = [('(IF', ('!BOOLEAN', ('!_EQ_', ('!PyObject_Type', condhead[1]), ('CALC_CONST', nm)))),
[('UNPUSH', action)],
(')(ELSE',),
[('UNPUSH', condhead + (condvars[1:],))],
(')ENDIF',)]
updated = True
i -= 10
continue
if len(condvars) == 1:
arg, action = condvars[0]
nm = arg[1]
isnew = arg[0] == T_NEW_CL_INST
if isnew:
aa[i:i+1] = [('(IF', ('!BOOLEAN', ('!_EQ_', ('!PyObject_Type', condhead[1]), ('CALC_CONST', nm)))),
[('UNPUSH', action)],
(')(ELSE',),
[('UNPUSH', condhead[2])],
(')ENDIF',)]
updated = True
i -= 10
continue
s_ = []
if s[1][0] == '!PyObject_Call' and\
TCmp(s[1], s_, ('!PyObject_Call', \
('!PyObject_GetAttr', '?', ('CONST', '?')), '?', ('NULL',))):
s_ = tuple(s_)
if TCmp(s_, v, ('?', 'sort', ('CONST', ()))):
if IsList(TypeExpr(v[0])):
s1 = [('PYAPI_CALL', ('PyList_Sort', v[0]))]
aa[i:i+1] = s1
updated = True
i -= 10
continue
if TCmp(s_, v, ('?', 'append', ('CONST', ('?',)))):
if IsList(TypeExpr(v[0])):
s1 = [('PYAPI_CALL', ('PyList_Append', v[0], ('CONST', v[1])))]
aa[i:i+1] = s1
updated = True
i -= 10
continue
if TCmp(s_, v, ('?', 'append', ('!BUILD_TUPLE', ('?',)))):
if IsList(TypeExpr(v[0])):
s1 = [('PYAPI_CALL', ('PyList_Append', v[0], v[1]))]
aa[i:i+1] = s1
updated = True
i -= 10
continue
v = []
if TCmp(s_, v, ('?', 'clear', ('CONST', ()))):
if IsDict(TypeExpr(v[0])):
s1 = [('PYAPI_CALL', ('PyDict_Clear', v[0]))]
aa[i:i+1] = s1
updated = True
i -= 10
continue
if TCmp(s_, v, ('?', 'reverse', ('CONST', ()))):
if IsList(TypeExpr(v[0])):
s1 = [('PYAPI_CALL', ('PyList_Reverse', v[0]))]
aa[i:i+1] = s1
updated = True
i -= 10
continue
if TCmp(s_, v, ('?', 'insert', ('CONST', ('?', '?')))):
if IsList(TypeExpr(v[0])):
s1 = [('PYAPI_CALL', ('PyList_Insert', v[0], v[1], ('CONST', v[2])))]
aa[i:i+1] = s1
updated = True
i -= 10
continue
if TCmp(s_, v, ('?', 'insert', ('!BUILD_TUPLE', (('CONST', '?'), '?')))):
if IsList(TypeExpr(v[0])):
s1 = [('PYAPI_CALL', ('PyList_Insert', v[0], v[1], v[2]))]
aa[i:i+1] = s1
updated = True
i -= 10
continue
if TCmp(s[1], v, ('CONST', '?')):
aa[i:i+1] = []
if len(aa) == 0:
aa.append(('PASS',))
updated = True
i -= 10
continue
if type(s) is tuple and len(s) == 3 and type(s[0]) is str and \
s[0] == 'STORE' and len(s[1]) == 1 and len(s[2]) == 1:
if s[1][0][0] == 'STORE_FAST':
if TCmp(s, v, ('STORE', (('STORE_FAST', '?'),), \
(('!COND_EXPR', '?', '?', '?'),))):
if v[2] != v[3]:
s1 = [('(IF', v[1]), [('STORE', (('STORE_FAST', v[0]),), (v[2],))], \
(')(ELSE',), [('STORE', (('STORE_FAST', v[0]),), (v[3],))], (')ENDIF',)]
aa[i:i+1] = s1
updated = True
i -= 10
continue
if TCmp(s, v, \
('STORE', \
(('STORE_FAST', '?'),), \
(('!PyNumber_InPlaceAdd', \
('PY_TYPE', '?', None, ('FAST', '?'), None), \
('!BUILD_LIST', '?')),))):
if v[0] == v[2] and v[1] is list:
new_a = []
for li in v[3]:
new_a.append(('PYAPI_CALL', ('PyList_Append', ('FAST', v[0]), li)))
aa[i:i+1] = new_a
updated = True
i -= 10
continue
if s[1][0][0] == 'SET_VARS' and \
TCmp(s, v, ('STORE', (('SET_VARS', '?'),), (('!BUILD_LIST', '?'),))) and \
len(v[0]) == len(v[1]):
if v[0][0][0] == 'STORE_NAME' and not v[0][0][1] in repr(v[1][1:]) and not v[0][0][1] in repr(v[0][1:]):
s1 = [('STORE', (('STORE_NAME', v[0][0][1]),), (v[1][0],))]
if len(v[0]) > 1:
s1.append( ('STORE', (('SET_VARS', v[0][1:]),), (('!BUILD_LIST', v[1][1:]),)) )
aa[i:i+1] = s1
updated = True
i -= 10
continue
if s[1][0][0] == 'SET_VARS' and \
TCmp(s, v, ('STORE', (('SET_VARS', '?'),), (('CONST', '?'),))) and \
type(v[1]) is tuple and len(v[0]) == len(v[1]):
if v[0][0][0] == 'STORE_NAME' and not v[0][0][1] in repr(v[1][1:]) and not v[0][0][1] in repr(v[0][1:]):
s1 = [('STORE', (('STORE_NAME', v[0][0][1]),), (('CONST', v[1][0]),))]
if len(v[0]) > 1:
s1.append( ('STORE', (('SET_VARS', v[0][1:]),), (('CONST', v[1][1:]),)) )
aa[i:i+1] = s1
updated = True
i -= 10
continue
if i+1 < len(aa) and len(s) > 0 and s[0] == 'RETURN_VALUE' and \
aa[i+1][0] in ('STORE', 'UNPUSH', '.L', 'RETURN_VALUE', 'PRINT_ITEM_1', 'PRINT_NEWLINE'):
del aa[i+1]
updated = True
i -= 10
continue
if i+1 < len(aa) and len(s) > 0 and s[0] == 'CONTINUE' and \
aa[i+1][0] in ('STORE', 'UNPUSH', '.L', 'RETURN_VALUE', 'PRINT_ITEM_1', 'PRINT_NEWLINE', 'CONTINUE'):
del aa[i+1]
updated = True
i -= 10
continue
if i+1 < len(aa) and len(s) > 0 and s[0] == 'BREAK' and \
aa[i+1][0] in ('STORE', 'UNPUSH', '.L', 'RETURN_VALUE', 'PRINT_ITEM_1', 'PRINT_NEWLINE'):
del aa[i+1]
updated = True
i -= 10
continue
if i+5 <= len(aa) and s == ('(TRY',) and type(aa[i+1]) is list and \
len(aa[i+1]) == 1 and aa[i+1][0][0] == '.L' and\
aa[i+2][0] == ')(EXCEPT' and type(aa[i+3]) is list and\
aa[i+4] == (')ENDTRY',):
aa[i:i+5] = aa[i+1]
updated = True
i -= 10
continue
v = []
if i+5 <= len(aa) and s == ('(TRY',) and type(aa[i+1]) is list and \
len(aa[i+1]) == 2 and aa[i+1][0][0] == '.L' and\
TCmp(aa[i+1][1], v, ('STORE', (('STORE_FAST', '?'),), (('CALC_CONST', '?'),))) and\
aa[i+2][0] == ')(EXCEPT' and type(aa[i+3]) is list and\
aa[i+4] == (')ENDTRY',):
aa[i:i+5] = aa[i+1]
updated = True
i -= 10
continue
v = []
if i+5 <= len(aa) and s == ('(TRY',) and type(aa[i+1]) is list and \
len(aa[i+1]) == 1 and aa[i+1][0] == ('PASS',) and\
aa[i+2][0] == ')(EXCEPT' and type(aa[i+3]) is list and\
aa[i+4] == (')ENDTRY',):
del aa[i:i+5]
updated = True
i -= 10
continue
if i+7 <= len(aa) and s == ('(TRY',) and type(aa[i+1]) is list and \
len(aa[i+1]) == 1 and aa[i+1][0][0] == '.L' and\
aa[i+2][0] == ')(EXCEPT' and type(aa[i+3]) is list and\
aa[i+4] == (')(ELSE',) and type(aa[i+5]) is list and\
aa[i+6] == (')ENDTRY',):
aa[i:i+7] = aa[i+5]
updated = True
i -= 10
continue
if i+7 <= len(aa) and s == ('(TRY',) and type(aa[i+1]) is list and \
len(aa[i+1]) == 1 and aa[i+1][0] == ('PASS',) and\
aa[i+2][0] == ')(EXCEPT' and type(aa[i+3]) is list and\
aa[i+4] == (')(ELSE',) and type(aa[i+5]) is list and\
aa[i+6] == (')ENDTRY',):
aa[i:i+7] = aa[i+5]
updated = True
i -= 10
continue
if s == ('(TRY',):
i1 = get_closed_pair(aa,i)
stm = aa[i:i1+1]
if stm[-3] == (')(FINALLY',):
tr = stm[1]
if len(stm) == 5:
aa[i:i1+1] = [('(TRY_FINALLY',), stm[1], (')(FINALLY',), stm[3], (')ENDTRY_FINALLY',)]
updated = True
i -= 10
continue
if tr[0] == ('(TRY',) and get_closed_pair(stm[1],0)+1 == len(stm[1]):
old1 = aa[i+1]
new1 = stm[-2]
aa[i:i1+1] = [('(TRY_FINALLY',), old1, (')(FINALLY',), new1, (')ENDTRY_FINALLY',)]
updated = True
i -= 10
continue
new1 = aa[i1-1]
del aa[i1-2:i1-1]
old1 = aa[i:i1-2]
aa[i:i1-2] = [('(TRY_FINALLY',), old1, (')(FINALLY',), new1, (')ENDTRY_FINALLY',)]
updated = True
i -= 10
continue
v = []
if type(s) is tuple and len(s) > 1 and s[0] == '(IF' and s[1][0] == 'CONST':
if TCmp(s, v, ('(IF', ('CONST', '?'), '?')):
if not type(v[0]) is bool: # not in (True, False):
update_v_0_1(v)
aa[i] = ('(IF', ('CONST', v[0]), v[1])
updated = True
i -= 10
continue
v = []
if TCmp(s, v, ('(IF', ('CONST', '?'))):
if not type(v[0]) is bool: # not in (True, False):
update_v_0_1(v)
aa[i] = ('(IF', ('CONST', v[0]))
updated = True
i -= 10
continue
v = []
if TCmp(s, v, ('(IF', ('CONST', False), '?')):
if type(aa[i+1]) is list and TCmp(aa[i+2],v0, (')ENDIF',)):
del aa[i:i+3]
updated = True
i -= 10
continue
if type(aa[i+1]) is list and \
TCmp(aa[i+2],v0, (')(ELSE',)) and type(aa[i+3]) is list and \
TCmp(aa[i+4],v0, (')ENDIF',)):
aa[i:i+5] = aa[i+3]
updated = True
i -= 10
continue
if TCmp(s, v, ('(IF', ('CONST', True), '?')):
if type(aa[i+1]) is list and TCmp(aa[i+2],v0, (')ENDIF',)):
aa[i:i+3] = aa[i+1]
updated = True
i -= 10
continue
if type(aa[i+1]) is list and \
TCmp(aa[i+2],v0, (')(ELSE',)) and type(aa[i+3]) is list and \
TCmp(aa[i+4],v0, (')ENDIF',)):
aa[i:i+5] = aa[i+1]
updated = True
i -= 10
continue
if TCmp(s, v, ('(IF', ('CONST', False))):
if type(aa[i+1]) is list and TCmp(aa[i+2],v0, (')ENDIF',)):
del aa[i:i+3]
updated = True
i -= 10
continue
elif type(aa[i+1]) is list and \
TCmp(aa[i+2],v0, (')(ELSE',)) and type(aa[i+3]) is list and \
TCmp(aa[i+4],v0, (')ENDIF',)):
aa[i:i+5] = aa[i+3]
updated = True
i -= 10
continue
if TCmp(s, v, ('(IF', ('CONST', True))):
if type(aa[i+1]) is list and TCmp(aa[i+2],v0, (')ENDIF',)):
aa[i:i+3] = aa[i+1]
updated = True
i -= 10
continue
elif type(aa[i+1]) is list and \
TCmp(aa[i+2],v0, (')(ELSE',)) and type(aa[i+3]) is list and \
TCmp(aa[i+4],v0, (')ENDIF',)):
aa[i:i+5] = aa[i+1]
updated = True
i -= 10
continue
if i+4 < len(aa) and len(s) >= 2 and s[0] == '(IF':
if type(aa[i+1]) is list and type(aa[i+3]) is list and \
aa[i+2][0] == ')(ELSE' and aa[i+4][0] == ')ENDIF' and aa[i+1] == aa[i+3]:
aa[i:i+5] = [('UNPUSH', s[1])] + aa[i+1]
updated = True
i -= 10
continue
v = []
if i + 10 < len (aa) and \
TCmp(s, v, ('(IF', ('!BOOLEAN', ('!_EQ_', ('!PyObject_Type', ('FAST', '?')), \
('CALC_CONST', '?'))))) and \
aa[i+5][0] == '.L' and \
aa[i+6] == ('(IF', ('!BOOLEAN', ('!_EQ_', ('!PyObject_Type', ('FAST', v[0])), \
('CALC_CONST', v[1])))) and \
type(aa[i+1]) is list and type(aa[i+3]) is list and \
aa[i+2][0] == ')(ELSE' and aa[i+4][0] == ')ENDIF' and \
type(aa[i+7]) is list and type(aa[i+9]) is list and \
aa[i+8][0] == ')(ELSE' and aa[i+10][0] == ')ENDIF':
l1 = aa[i+1] + [aa[i+5]] + aa[i+7]
l2 = aa[i+3] + [aa[i+5]] + aa[i+9]
if 'STORE_FAST' not in repr(l1) and 'STORE_FAST' not in repr(l2):
aa[i:i+11] = [('(IF', ('!BOOLEAN', ('!_EQ_', ('!PyObject_Type', ('FAST', v[0])), \
('CALC_CONST', v[1])))),
l1,
(')(ELSE',),
l2,
(')ENDIF',)]
updated = True
i -= 10
continue
if type(s) is tuple and len(s) > 0 and s[0] == 'RETURN_VALUE':
if TCmp(s, v, ('RETURN_VALUE', \
('!PyObject_Call', \
('!LOAD_BUILTIN', 'setattr'), \
('!BUILD_TUPLE', ('?', '?', '?')), \
('NULL',)))):
aa[i:i+1] = [('UNPUSH', s[1]), (s[0], ('CONST', None))]
updated = True
i -= 10
continue
if type(s) is tuple and len(s) == 3 and s[0] == 'SEQ_ASSIGN':
v = []
if TCmp(s, v, ('SEQ_ASSIGN', (('STORE_FAST', '?'), '?'), '?')):
if repr(('FAST', v[0])) not in repr(v[1]):
aa[i:i+1] = [('STORE', (s[1][0],), (s[2],)), ('STORE', (s[1][1],), (('FAST', v[0]),))]
updated = True
i -= 10
continue
i += 1
if updated:
if len(aa) == 0:
return [('PASS',)]
return aa
return a
is_inlined = False
def subroutine_inlined(nm, tupl):
global is_inlined, inline_flag
if is_inlined or not inline_flag:
return None
## return None
co = N2C(nm)
is_varargs = co.co_flags & 0x4
if co == current_co:
return None
if tupl[0] == '!BUILD_TUPLE':
tupl = tupl[1]
elif tupl[0] == 'CONST':
tupl = [('CONST', x) for x in tupl[1]]
else:
return None
if co.cmds[1][-1][0] != 'RETURN_VALUE':
pprint(('!! no return at last', co.cmds[1]))
return None
## if not all([x[0] == 'CONST' or x[0] == 'FAST' or (x[0] == 'PY_TYPE' and x[3][0] == 'FAST' ) for x in tupl]):
## # pprint((nm, tupl, co.cmds[1]))
## return None
if not is_varargs and nm in default_args:
is_const_default = True
defau = default_args[nm]
if defau[0] != 'CONST':
is_const_default = False
if len(tupl) < co.co_argcount:
if is_const_default:
_refs2 = [('CONST', x) for x in defau[1]]
else:
_refs2 = [x for x in defau[1]]
while (len(tupl) + len(_refs2) ) > co.co_argcount and len(_refs2) > 0:
del _refs2[0]
if (len(tupl) + len(_refs2) ) == co.co_argcount:
tupl = list(tupl) + _refs2
if len(tupl) == co.co_argcount and len(co.co_varnames) > co.co_argcount:
co.strip_unused_fast()
cmds = co.cmds[1]
## pprint((co.co_name, cmds))
if co.co_argcount == co.co_nlocals and \
co.co_argcount == len(co.co_varnames):
if is_varargs:
## print 'No inline - varargs', nm
return None
srepr = repr(cmds)
if len(tupl) == co.co_argcount:
expr = cmds
d = {}
for i in range(co.co_argcount):
ttu = tupl[i]
if ttu[0] == 'PY_TYPE':
ttu = ttu[3]
if ttu[0] == 'PY_TYPE':
ttu = ttu[3]
if srepr.count(repr(('FAST', co.co_varnames[i]))) > 1 and ttu[0] not in ('FAST', 'CONST'):
print 'No inline - have dangerous arg', ('FAST', co.co_varnames[i]), ttu, nm
d = None
break
elif repr(('STORE_FAST', co.co_varnames[i])) in srepr :
d = None
break
else:
d[co.co_varnames[i]] = tupl[i]
if d is None:
return None
expr = replace_fastvar(expr, d)
if (len (repr(expr)) - len(repr(tupl))) > 1024:
print 'No inline - too big', nm
return None
if len(expr) == 2 and expr[0][0] == '.L' and expr[1][0] == 'RETURN_VALUE':
return expr
if len(expr) == 1 and expr[0][0] == 'RETURN_VALUE':
return expr
is_inlined = True
expr1 = tree_pass_upgrade_repl(expr, None, '?')
expr = tree_pass_upgrade_repl(expr1, None, '?')
is_inlined = False
srepr = repr(expr)
if 'CONTINUE' in srepr or 'BREAK' in srepr or 'RETURN_VALUE' in repr(expr[:-1]):
return None
return expr
return None
def to_tuple_const(v):
try:
return ('CONST', tuple(v[0]))
except:
pass
return None
def to_const_meth_1(obj, meth, args):
try:
meth = operator.methodcaller(meth, *args[1])
v_s = meth(obj[2][1][0])
if type(v_s) is list:
v_s = [('CONST', x) for x in v_s]
return ('!BUILD_LIST', tuple(v_s))
assert type(v_s) != dict
try:
if len(v_s) > 5000:
pass
else:
return ('CONST', v_s)
except:
return ('CONST', v_s)
except:
pass
return None
def to_const_meth_2(obj, meth, args):
try:
meth = operator.methodcaller(meth, *args[1])
v_s = meth(obj[1])
if type(v_s) is list:
v_s = [('CONST', x) for x in v_s]
return ('!BUILD_LIST', tuple(v_s))
assert type(v_s) != dict
try:
if len(v_s) > 5000:
pass
else:
return ('CONST', v_s)
except:
return ('CONST', v_s)
except:
pass
return None
def cond_expr_module(t, ret):
this,d2 = MyImport(t[1])
return ret[2]
def if_expr_1(ret):
try:
if ret[0] == '(IF' and ret[1][0] == 'CONST' and ret[1][1]:
ret = list(ret)
ret[1] = ('CONST', True)
return tuple(ret)
if ret[0] == '(IF' and ret[1][0] == 'CONST' and not ret[1][1]:
ret = list(ret)
ret[1] = ('CONST', False)
return tuple(ret)
except:
pass
return None
def calc_expr_1(op, v):
try:
if op == '!PyObject_Repr':
return ('CONST', repr(v))
elif op == '!PyObject_Str':
return ('CONST', str(v))
elif op == '!PyNumber_Negative':
return ('CONST', - v)
elif op == '!PyNumber_Float':
return ('CONST', float(v))
elif op == '!PyNumber_Int':
return ('CONST', int(v))
elif op == '!PyNumber_Long':
return ('CONST', long(v))
elif op == '!PyNumber_Positive':
return ('CONST', + v)
elif op == '!PyNumber_Absolute':
return ('CONST', abs(v))
elif op == '!PyNumber_Invert':
return ('CONST', ~ v)
elif op == '!PyObject_Str':
return ('CONST', str(v))
elif op in ('!ORD_BUILTIN', ):
return ('CONST', ord(v))
elif op in ('!CHR_BUILTIN', ):
return ('CONST', chr(v))
elif op == '!1NOT':
return ('CONST', not v)
elif op in len_family:
return ('CONST', len(v))
elif op == '!PY_SSIZE_T':
ret = ('CONST', v)
elif op == '!PyObject_Type':
if v is not None:
return ('!LOAD_BUILTIN', type_to_check_str[type(v)])
except:
pass
return None
def calc_pow_1(ret):
try:
return ('CONST', pow(ret[1][1],ret[2][1]))
except:
pass
return None
def calc_expr_2(op, v1, v2, ret):
if type(v1) in (float, int) and type(v2) in (float, int):
if op == '!PyNumber_Multiply':
return ('CONST', v1 * v2)
elif op == '!PyNumber_Divide':
if v2 != 0:
return ('CONST', v1 / v2)
else:
return ('!?Raise', ('BUILTIN', 'ZeroDivisionError'), ('CONST', "division by 0"))
elif op == '!PyNumber_FloorDivide':
if v2 != 0:
return ('CONST', v1 // v2)
else:
return ('!?Raise', ('BUILTIN', 'ZeroDivisionError'), ('CONST', "division by 0"))
elif op == '!PyNumber_Remainder':
if type(v1) is int and v2 != 0:
return ('CONST', v1 % v2)
if type(v1) is float and v2 != 0:
return ('CONST', v1 % v2)
if type(v1) is int and v2 == 0:
return ('!?Raise', ('BUILTIN', 'ZeroDivisionError'), ('CONST', "division by 0"))
if type(v1) is float and v2 == 0:
return ('!?Raise', ('BUILTIN', 'ZeroDivisionError'), ('CONST', "division by 0"))
elif op == '!PyNumber_Add':
return ('CONST', v1 + v2)
elif op == '!PyNumber_InPlaceAdd':
return ('CONST', v1 + v2)
elif op == '!PyNumber_Subtract':
return ('CONST', v1 - v2)
elif op == '!PyNumber_Lshift':
return ('CONST', v1 << v2)
elif op == '!PyNumber_Rshift':
return ('CONST', v1 >> v2)
elif op == '!PyNumber_Or':
return ('CONST', v1 | v2)
elif op == '!PyNumber_Xor':
return ('CONST', v1 ^ v2)
elif op == '!PyNumber_And':
return ('CONST', v1 & v2)
elif op == '!OR_JUMP':
return ('CONST', v1 or v2)
elif op == '!AND_JUMP':
return ('CONST', v1 and v2)
elif op in ('!CHR_BUILTIN', ):
return ('CONST', chr(v1))
elif op == '!_EQ_':
return ('CONST', v1 == v2)
elif op == '!_NEQ_':
return ('CONST', v1 != v2)
elif op == '!c_Py_GT_Int':
return ('CONST', v1 > v2)
elif op == '!c_Py_GE_Int':
return ('CONST', v1 >= v2)
elif op == '!c_Py_LT_Int':
return ('CONST', v1 < v2)
elif op == '!c_Py_LE_Int':
return ('CONST', v1 <= v2)
elif op == '!c_Py_EQ_Int':
return ('CONST', v1 == v2)
elif op == '!c_Py_NE_Int':
return ('CONST', v1 != v2)
else:
pass #Debug('rre Constant op2 unhandled', ret)
try:
if op == '!PyNumber_Multiply':
v_2 = ('CONST', v1 * v2)
try:
if len(v_2[1]) > 5000:
pass
else:
return v_2
except:
return v_2
elif op == '!PyNumber_Divide':
if v2 != 0:
return ('CONST', v1 / v2)
else:
return ('!?Raise', ('BUILTIN', 'ZeroDivisionError'), ('CONST', "division by 0"))
elif op == '!PyNumber_FloorDivide':
if v2 != 0:
return ('CONST', v1 // v2)
else:
return ('!?Raise', ('BUILTIN', 'ZeroDivisionError'), ('CONST', "division by 0"))
elif op == '!PyNumber_Remainder':
if type(v1) is int and v2 != 0:
return ('CONST', v1 % v2)
if type(v1) is float and v2 != 0:
return ('CONST', v1 % v2)
if type(v1) is str and len(v1 % v2) <= 255:
return ('CONST', v1 % v2)
if type(v1) is int and v2 == 0:
return ('!?Raise', ('BUILTIN', 'ZeroDivisionError'), ('CONST', "division by 0"))
if type(v1) is float and v2 == 0:
return ('!?Raise', ('BUILTIN', 'ZeroDivisionError'), ('CONST', "division by 0"))
elif op == '!STR_CONCAT':
ret = ('!STR_CONCAT', ('CONST', v1 + v2)) + ret[3:]
if len(ret) == 2:
return ret[1]
else:
return repl(ret)
elif op == '!PyNumber_Add':
return ('CONST', v1 + v2)
elif op == '!PyNumber_InPlaceAdd':
return ('CONST', v1 + v2)
elif op == '!PyNumber_Subtract':
return ('CONST', v1 - v2)
elif op == '!PyNumber_Lshift':
return ('CONST', v1 << v2)
elif op == '!PyNumber_Rshift':
return ('CONST', v1 >> v2)
elif op == '!PyNumber_Or':
return ('CONST', v1 | v2)
elif op == '!PyNumber_Xor':
return ('CONST', v1 ^ v2)
elif op == '!PyNumber_And':
return ('CONST', v1 & v2)
elif op == '!OR_JUMP':
return ('CONST', v1 or v2)
elif op == '!AND_JUMP':
return ('CONST', v1 and v2)
elif op == '!PySequence_Repeat':
ret2 = ('CONST', v2 * v1)
if len(ret2[1]) > 5000:
return ret
return ret2
elif op == '!PyString_Format':
return ('CONST', v1 % v2)
elif op in ('!PySequence_Contains(', '!PySequence_Contains', '!_PyString_Contains'):
return ('CONST', v2 in v1)
elif op == '!PyObject_GetAttr' and v2 == 'join' and type(v1) is str:
pass # _PyString_Join
elif op in ('!BINARY_SUBSCR_Int', '!from_ceval_BINARY_SUBSCR'):
return ('CONST', v1[v2])
elif op in ('!ORD_BUILTIN', ):
return ('CONST', ord(v1))
elif op in ('!CHR_BUILTIN', ):
return ('CONST', chr(v1))
elif op == '!_EQ_':
return ('CONST', v1 == v2)
elif op == '!_NEQ_':
return ('CONST', v1 != v2)
elif op == '!c_Py_GT_Int':
return ('CONST', v1 > v2)
elif op == '!c_Py_GE_Int':
return ('CONST', v1 >= v2)
elif op == '!c_Py_LT_Int':
return ('CONST', v1 < v2)
elif op == '!c_Py_LE_Int':
return ('CONST', v1 <= v2)
elif op == '!c_Py_EQ_Int':
return ('CONST', v1 == v2)
elif op == '!c_Py_NE_Int':
return ('CONST', v1 != v2)
else:
pass #Debug('rre Constant op2 unhandled', ret)
except:
pass
return None
def calc_expr_and(op, v1, ret):
try:
if v1:
if len(ret) == 3:
return ret[2]
else:
lret = list(ret)
del lret[1]
return tuple(lret)
else:
return ('CONST', False)
except:
return None
def calc_expr_or(op, v1, ret):
try:
if not v1:
if len(ret) == 3:
return ret[2]
else:
lret = list(ret)
del lret[1]
return tuple(lret)
else:
return ('CONST', True)
except:
return None
def function_inlined(nm, tupl):
expr = subroutine_inlined(nm, tupl)
if expr is None:
return None
srepr = repr(expr)
if len(expr) == 2 and expr[0][0] == '.L' and expr[1][0] == 'RETURN_VALUE':
print '~~ inline call ', nm, len(srepr)
return expr[1][1]
if len(expr) == 1 and expr[0][0] == 'RETURN_VALUE':
print '~~ inline call ', nm, len(srepr)
return expr[0][1]
if 'STORE' in srepr:
## pprint(('?? inline func', nm, tupl))
print '!! STORE at inlined func', nm
return None
if 'DELETE' in srepr:
## pprint(('?? inline func', nm, tupl))
print '!! DELETE at inlined func', nm
return None
if '(IF' in srepr:
## pprint(('?? inline func', nm, tupl, expr))
print '!! IF at inlined func', nm
return None
if 'PRINT_ITEM' in srepr:
## pprint(('?? inline func', nm, tupl))
print '!! PRINT_ITEM at inlined func', nm
return None
if expr[-1] == ('RETURN_VALUE', ('CONST', None)):
print '!! procedure ', nm, tupl
return None
pprint(('!! undefined unsuccess inline func', nm, tupl, expr))
return None
def call_calc_const(func, tupl, ret):
co = N2C(func)
if subroutine_can_be_direct(func, len(tupl[1])):
add_direct_arg(func, tupl)
inlined = function_inlined(func, tupl)
if inlined is not None:
## pprint(inlined)
return inlined
else:
return ('!CALL_CALC_CONST', func, tupl)
elif co.co_flags & 0x28 == 0 and co.co_flags == 0x43 and \
len(co.co_cellvars) == 0 and len(co.co_freevars) == 0 and co.co_argcount == len(tupl[1]):
return ('!CALL_CALC_CONST_INDIRECT', func, tupl)
elif co.co_flags & CO_GENERATOR: # interpreted generator
return ret
else:
Debug('Unfortunelly ', ret, hex(co.co_flags))
return ret
def repl_if_expr(ret):
updated = False
li = []
if ret[0] == '!AND_JUMP':
for v in ret[1:]:
if v[0] == '!BOOLEAN' and v[1][0] == '!AND_BOOLEAN':
li.extend(v[1][1:])
updated = True
else:
li.append(v)
if updated:
return ('!AND_JUMP',) + tuple(li)
if ret[0] == '!OR_JUMP':
for v in ret[1:]:
if v[0] == '!BOOLEAN' and v[1][0] == '!OR_BOOLEAN':
li.extend(v[1][1:])
updated = True
else:
li.append(v)
if updated:
return ('!OR_JUMP',) + tuple(li)
if ret[0] == '!BOOLEAN' and ret[1][0] == '!AND_BOOLEAN':
return ('!AND_JUMP',) + tuple(ret[1][1:])
if ret[0] == '!BOOLEAN' and ret[1][0] == '!OR_BOOLEAN':
return ('!OR_JUMP',) + tuple(ret[1][1:])
return None
def cond_meth_eq(a,b):
if type(a) is tuple and type(b) is tuple and len(a) > 0 and len(b) > 0 \
and a[0] == b[0] == '!COND_METH_EXPR' and \
a[1] == b[1] and len(a[3]) == len(b[3]) and\
all([ a[3][i][0] == b[3][i][0] for i in range(len(a[3]))]):
return True
return False
## ret, r0, v, methods, i, t, ret3, ret2, tupl, x, codemethnm,
##_isnew, _arg, _ret, cl, slf, _v, tag, args, ret_tupl, v2, obj,
##meth, t1, t2, ret_co, ret_modl, n1, n2, ret_n, pos, op, ret_ret,
##v1, li, n, v0, v1_1, v1_2, der};
def repl(ret): ## can_be_codefunc
if type(ret) is not tuple or len(ret) == 0:
return ret
assert type(ret) is tuple
r0 = ret[0]
if type(r0) is not str:
return ret
assert type(r0) is str
v = []
is_can_be_codefunc = bool(current_co.can_be_codefunc())
if r0 in ('!AND_JUMP', '!OR_JUMP', '!AND_JUMPED_STACKED', '!OR_JUMPED_STACKED'):
if cond_meth_eq(ret[1], ret[2]):
methods = []
if len(ret) == 3:
for i in range(len(ret[1][3])):
methods.append((ret[2][3][i][0], (r0, ret[1][3][i][1], ret[2][3][i][1]) ))
return ('!COND_METH_EXPR', ret[1][1], (r0, ret[1][2], ret[2][2]), tuple(methods))
elif len(ret) == 4 and cond_meth_eq(ret[1], ret[3]):
for i in range(len(ret[1][3])):
methods.append((ret[2][3][i][0], (r0, ret[1][3][i][1], ret[2][3][i][1], ret[3][3][i][1]) ))
return ('!COND_METH_EXPR', ret[1][1], (r0, ret[1][2], ret[2][2], ret[3][2]), tuple(methods))
elif len(ret) == 5 and cond_meth_eq(ret[1], ret[3]) and cond_meth_eq(ret[1], ret[4]):
for i in range(len(ret[1][3])):
methods.append((ret[2][3][i][0], (r0, ret[1][3][i][1], ret[2][3][i][1], ret[3][3][i][1], ret[4][3][i][1]) ))
return ('!COND_METH_EXPR', ret[1][1], (r0, ret[1][2], ret[2][2], ret[3][2], ret[4][2]), tuple(methods))
elif len(ret) == 4 and cond_meth_eq(ret[2], ret[3]) and ret[1][0] != '!COND_METH_EXPR':
methods = []
for i in range(len(ret[2][3])):
methods.append((ret[2][3][i][0], (r0, ret[1], ret[2][3][i][1], ret[3][3][i][1]) ))
return ('!COND_METH_EXPR', ret[2][1], (r0, ret[1], ret[2][2], ret[3][2]), tuple(methods))
elif r0 == '!AND_JUMP':
li = []
_updated = False
for x in ret[1:]:
if x[0] == '!BOOLEAN' and x[1][0] == '!AND_BOOLEAN':
y = x[1]
if len(y) == 3 and y[1][0] == '!BOOLEAN' and y[2][0] == '!BOOLEAN':
li.append(y[1][1])
li.append(y[2][1])
_updated = True
continue
li.append(x)
if _updated:
return (r0,) + tuple(li)
if len(ret) >= 1 and type(r0) is str:
if is_can_be_codefunc and len(ret) == 4 and \
r0 == '!PyObject_Call' and ret[3] == ('NULL',) and \
TCmp(ret[1:-1], v, (('CALC_CONST', '?'), ('CONST', '?'))) :
t = None
if type(v[0]) is tuple and len(v[0]) == 2:
t = (Val3(v[0][0], 'ImportedM'), v[0][1])
else:
t = Val3(v[0], 'ImportedM')
if type(t) is tuple and len(t) == 2 and t[0] == 'math':
return attempt_calc_constant_math(t[1], ret, v[1]) #sqrt
if r0 == '!PyBool_Type.tp_new' and ret[1] == '&PyBool_Type' and \
ret[2][0] == '!BUILD_TUPLE' and len(ret[2][1]) == 1 and \
ret[2][1][0][0] == '!OR_JUMPED_STACKED':
return ('!BOOLEAN', ('!OR_BOOLEAN',) + ret[2][1][0][1:])
if r0 == '!PyBool_Type.tp_new' and ret[1] == '&PyBool_Type' and \
ret[2][0] == '!BUILD_TUPLE' and len(ret[2][1]) == 1 and \
ret[2][1][0][0] == '!AND_JUMPED_STACKED':
return ('!BOOLEAN', ('!AND_BOOLEAN',) + ret[2][1][0][1:])
v = []
if r0 == '!_PyEval_ApplySlice':
if ret[2][0] == 'CONST' and ret[3][0] == 'CONST' and \
type(ret[2][1]) is int and type(ret[3][1]) is int:
return ('!PySequence_GetSlice', ret[1], ret[2][1], ret[3][1])
elif r0 == '!PySequence_Contains(':
if TCmp(ret, v, ('!PySequence_Contains(', '?', '?')) and IsStr(TypeExpr(v[1])) and IsStr(TypeExpr(v[0])) and not is_pypy:
return ('!_PyString_Contains', v[0], v[1])
elif r0 == '!PySequence_GetSlice':
if TCmp(ret, v, ('!PySequence_GetSlice', ('CONST', '?'), \
int, 'PY_SSIZE_T_MAX')):
return ('CONST', v[0][v[1]:])
t = TypeExpr(ret[1])
if IsList(t):
ret3 = ret[3]
ret2 = ret[2]
if (type(ret2) is not int or type(ret3) is not int) and \
ret2 != 'PY_SSIZE_T_MAX' and ret3 != 'PY_SSIZE_T_MAX':
Fatal('Strange slice arg', ret)
return ('!PyList_GetSlice', ret[1], ret2, ret3)
if IsTuple(t):
return ('!PyTuple_GetSlice', ret[1], ret[2], ret[3])
elif r0 == '!AND_JUMPED_STACKED':
isbool = True
for tupl in ret[1:]:
isbool = isbool and IsBool(TypeExpr(tupl))
if isbool:
ret1 = ('!AND_BOOLEAN',) + ret[1:]
return ('!BOOLEAN', ret1)
else:
Debug('Not Is bool', ret, [TypeExpr(x) for x in ret[1:]])
v = []
if TCmp(ret, v, ('!AND_JUMPED_STACKED', ('!BOOLEAN', '?' ), '?' )):
return ('!COND_EXPR', ('!BOOLEAN', v[0]), v[1], ('CONST', False))
elif r0 == '!OR_JUMPED_STACKED':
isbool = True
for tupl in ret[1:]:
isbool = isbool and IsBool(TypeExpr(tupl))
if isbool:
ret1 = ('!OR_BOOLEAN',) + ret[1:]
return ('!BOOLEAN', ret1)
else:
Debug('Not Is bool', ret, [TypeExpr(x) for x in ret[1:]])
v = []
if TCmp(ret, v, ('!OR_JUMPED_STACKED', ('!BOOLEAN', '?' ), '?' )):
return ('!COND_EXPR', ('!BOOLEAN', v[0]), ('CONST', True), v[1])
if r0 == '(FOR' and len(ret) == 3 and ret[2][0] == '!BUILD_LIST' and all([x[0] == 'CONST' for x in ret[2][1]]):
return (r0, ret[1], ('CONST', tuple([x[1] for x in ret[2][1]])))
if r0 == '!PySequence_Contains(' and len(ret) == 3:
if ret[1][0] == '!BUILD_LIST' and all([x[0] == 'CONST' for x in ret[1][1]]):
return (r0, ('CONST', tuple([x[1] for x in ret[1][1]])), ret[2])
if TCmp(ret, v, ('!PySequence_Contains(', '?', '?')):
t = TypeExpr(ret[1])
if IsDict(t):
return ('!PyDict_Contains', ret[1], ret[2])
elif t == Kl_Set:
return ('!PySet_Contains', ret[1], ret[2])
v = []
if TCmp(ret, v, ('!PySequence_Contains(', ('!BUILD_TUPLE', '?'), '?')) and \
type(v[0]) is tuple:
if len(v[0]) == 1:
return ('!PyObject_RichCompare(', v[0][0], v[1], 'Py_EQ')
return ('!OR_BOOLEAN',) + \
tuple([('!PyObject_RichCompare(', x, v[1], 'Py_EQ') for x in v[0]])
if r0 == '!PySequence_Tuple':
t = TypeExpr(ret[1])
if IsTuple(t):
return ret[1]
if IsList(t):
if ret[1][0] == '!BUILD_LIST':
return TupleFromArgs(ret[1][1])
return ('!PyList_AsTuple', ret[1])
if build_executable and (ret == ('!LOAD_GLOBAL', '__name__') or ret == ('!LOAD_NAME', '__name__')):
return ('CONST', '__main__')
if r0 == '!IMPORT_NAME':
CheckExistListImport(dotted_name_to_first_name(ret[1]))
elif r0 == 'IMPORT_FROM_AS':
CheckExistListImport(ret[1], ret[3][1], ret[2][1])
if r0 == '!PyObject_Str':
if len(ret) == 2:
t = TypeExpr(ret[1])
if IsInt(t):
return ('!PyInt_Type.tp_str', ret[1])
if t is not None and t[0] in (T_NEW_CL_INST, T_OLD_CL_INST) and \
IsMethod(t[1], '__str__'):
codemethnm = ValMethod(t[1], '__str__')
tupl = ('!BUILD_TUPLE', (ret[1],))
return call_calc_const(codemethnm, tupl, ret)
if r0 == '!PyInt_Type.tp_str' and ret[1][0] == '!PyNumber_Int' and \
ret[1][1][0] == 'PY_TYPE' and ret[1][1][1] == bool:
return ('!COND_EXPR', ret[1][1], ('CONST', '1'), ('CONST', '0'))
if r0 == '!PyNumber_Remainder' and len(ret) == 3:
t = TypeExpr(ret[1])
if IsStr(t):
return ('!PyString_Format', ret[1], ret[2])
if r0 == '!PyObject_Repr':
if IsInt(TypeExpr(ret[1])) and not is_pypy:
return ('!_PyInt_Format', ret[1], 10, 0)
if len(ret) == 2 and r0 == 'CONST' and type(ret[1]) == type:
if ret[1] in d_built_inv:
return ('!LOAD_BUILTIN', d_built_inv[ret[1]])
else:
Fatal ('???', ret, type(ret[1]))
return ret
if r0 == '!PyObject_RichCompare(' and\
TCmp(ret,v, ('!PyObject_RichCompare(', \
('!COND_EXPR', '?', '?', '?'), \
('CONST', '?'), '?')):
if v[1] != v[2]:
return ('!COND_EXPR', v[0], ('!PyObject_RichCompare(', v[1], ('CONST', v[3]), v[4]),\
('!PyObject_RichCompare(', v[2], ('CONST', v[3]), v[4]))
if direct_call and is_can_be_codefunc:
v = []
if r0 == '!PyObject_Call' and \
TCmp(ret, v, ('!PyObject_Call', ('!MK_FUNK', '?', ('CONST', ())), \
('!BUILD_TUPLE', '?'), ('NULL',))):
return call_calc_const(v[0], ('!BUILD_TUPLE', v[1]), ret)
if r0 == '!COND_METH_EXPR' and ret[2][0] == '!CALL_CALC_CONST':
return ret[2]
if r0 == '!COND_METH_EXPR' and ret[2][0] == '!CALL_CALC_CONST_INDIRECT':
return ret[2]
if r0 == '!COND_METH_EXPR' and ret[1][0] == 'PY_TYPE':
_isnew = None
if ret[1][1] == 'OldClassInstance':
_isnew = False
elif ret[1][1] == 'NewClassInstance':
_isnew = True
## re3 = ret[3]
else:
_isnew = None
if _isnew == None:
return ret[2]
## pprint(ret[3])
for _arg, _ret in ret[3]: ###isnew, cl, bas, _ret in ret[3]:
cl = _arg[1]
isnew = _arg[0] == T_NEW_CL_INST
if isnew == _isnew and cl == ret[1][2]:
return _ret
return ret[2]
if r0 == '!COND_EXPR' and ret[2] == ret[3] and\
ret[2][0] == '!CALL_CALC_CONST' and \
TCmp(ret[1], v, ('!_EQ_', ('!PyObject_Type', ('PY_TYPE', '?', '?', '?', None)), \
('CALC_CONST', '?'))) and\
v[1] == v[3]:
return ret[2]
elif r0 == '!COND_EXPR' and ret[2] == ret[3] and\
ret[2][0] == '!CALL_CALC_CONST' and \
TCmp(ret[1], v, ('!BOOLEAN', ('!PyObject_IsInstance', \
('PY_TYPE', '?', '?', '?', None), \
('CALC_CONST', '?')))) and\
v[1] == v[3]:
return ret[2]
elif r0 == '!CLASS_CALC_CONST' and is_can_be_codefunc:
if TCmp(ret, v, ('!CLASS_CALC_CONST', '?', ('!BUILD_TUPLE', '?'))):
if IsMethod(v[0], '__init__'):
if subroutine_can_be_direct(CodeInit(v[0]),\
len(v[1]) +1):
slf = ('PY_TYPE', T_OLD_CL_INST, v[0], ('PSEVDO', 'self'), None)
add_direct_arg(CodeInit(v[0]), ('!BUILD_TUPLE', (slf,) +v[1]))
return ('!CLASS_CALC_CONST_DIRECT', v[0], \
CodeInit(v[0]), ('!BUILD_TUPLE', v[1]))
elif TCmp(ret, v, ('!CLASS_CALC_CONST', '?', ('CONST', '?'))):
if IsMethod(v[0], '__init__'):
if subroutine_can_be_direct(CodeInit(v[0]), len(v[1])+1):
slf = ('PY_TYPE', T_OLD_CL_INST, v[0], ('PSEVDO', 'self'), None)
add_direct_arg(CodeInit(v[0]), ('!BUILD_TUPLE', (slf,) + tuple([('CONST', x) for x in v[1]])))
return ('!CLASS_CALC_CONST_DIRECT', v[0], \
CodeInit(v[0]), ('CONST', v[1]))
if r0 == '!PyObject_Call':
_v = []
if TCmp(ret, _v, ('!PyObject_Call', ('!LOAD_BUILTIN', '?'), '?', ('NULL',))):
tag,args = _v[0], _v[1]
v = []
if tag == 'apply' and TCmp(args, v, ('!BUILD_TUPLE', ('?', '?'))):
return ('!PyObject_Call', v[0] , v[1], ('NULL',))
elif tag == 'apply' and TCmp(args, v, ('!BUILD_TUPLE', ('?', '?', '?'))):
return ('!PyObject_Call', v[0] , v[1], v[2])
elif tag == 'getattr' and TCmp(args, v, ('!BUILD_TUPLE', ('?', '?'))):
return ('!PyObject_GetAttr', v[0], v[1])
elif tag == 'getattr' and TCmp(args, v, ('!BUILD_TUPLE', ('?', '?', '?'))):
return ('!PyObject_GetAttr3', v[0], v[1], v[2])
elif tag == 'dict' and args == ('CONST', ()):
return ('!PyDict_New', )
elif tag == 'slice' and TCmp(args, v, ('!BUILD_TUPLE', '?')):
if len(v[0]) == 3:
return ('!PySlice_New', v[0][0], v[0][1], v[0][2])
elif len(v[0]) == 2:
return ('!PySlice_New', v[0][0], v[0][1], 'NULL')
elif len(v[0]) == 1:
return ('!PySlice_New', 'NULL', v[0][0], 'NULL')
else:
Fatal('Strange arg Slice', ret)
elif tag == 'slice' and TCmp(args, v, ('CONST', '?')):
if len(v[0]) == 3:
return ('!PySlice_New', ('CONST', v[0][0]), ('CONST', v[0][1]), ('CONST', v[0][2]))
elif len(v[0]) == 2:
return ('!PySlice_New', ('CONST', v[0][0]), ('CONST', v[0][1]), 'NULL')
elif len(v[0]) == 1:
return ('!PySlice_New', 'NULL', ('CONST', v[0][0]), 'NULL')
else:
Fatal('Strange arg Slice', ret)
elif tag == 'tuple' and TCmp(args, v, ('CONST', '?')):
ret_tupl = to_tuple_const(v)
if ret_tupl is not None:
return ret_tupl
elif tag == 'callable':
if args[0] == '!BUILD_TUPLE' and TypeExpr(args[1][0]) is not None:
Debug('callable, ', TypeExpr(args[1][0]))
Debug(args)
elif tag == 'list' and args == ('CONST', ()):
return ('!BUILD_LIST', ())
_v = []
if direct_call and is_can_be_codefunc:
if \
r0 == '!PyObject_Call' and ret[1][0] == '!PyObject_GetAttr':
if ret[2][0] == '!BUILD_TUPLE' and TCmp(ret, v, \
('!PyObject_Call',
('!PyObject_GetAttr', '?', ('CONST', '?')), ('!BUILD_TUPLE', '?'), ('NULL',))):
t = TypeExpr(v[0])
if t is not None and type(t[1]) is str and IsMethod(t[1], v[1]):
classmeth = Is3(t[1], ('ClassMethod', v[1]))
staticmeth = Is3(t[1], ('StaticMethod', v[1]))
codemethnm = ValMethod(t[1], v[1])
isoldclass = t[1] in calc_const_old_class
isnewclass = t[1] in calc_const_new_class
if is_old_class_inst(t) and isoldclass and not isnewclass:
if classmeth:
Debug('No direct call of class method', ret)
elif staticmeth:
tupl = ('!BUILD_TUPLE', v[2])
return call_calc_const(codemethnm, tupl, ret)
else:
tupl = ('!BUILD_TUPLE', (v[0],) + v[2])
return call_calc_const(codemethnm, tupl, ret)
elif is_old_class_typ(t) and isoldclass and not isnewclass:
if classmeth:
tupl = ('!BUILD_TUPLE', (v[0],) + v[2])
return call_calc_const(codemethnm, tupl, ret)
elif staticmeth:
tupl = ('!BUILD_TUPLE', v[2])
return call_calc_const(codemethnm, tupl, ret)
else:
tupl = ('!BUILD_TUPLE', v[2])
return call_calc_const(codemethnm, tupl, ret)
elif is_new_class_inst(t) and isnewclass and not isoldclass:
if classmeth:
Debug('No direct call of class method', ret)
elif staticmeth:
tupl = ('!BUILD_TUPLE', v[2])
return call_calc_const(codemethnm, tupl, ret)
else:
tupl = ('!BUILD_TUPLE', (v[0],) + v[2])
return call_calc_const(codemethnm, tupl, ret)
elif is_new_class_typ(t) and isnewclass and not isoldclass:
if classmeth:
tupl = ('!BUILD_TUPLE', (v[0],) + v[2])
return call_calc_const(codemethnm, tupl, ret)
elif staticmeth:
tupl = ('!BUILD_TUPLE', v[2])
return call_calc_const(codemethnm, tupl, ret)
else:
tupl = ('!BUILD_TUPLE', v[2])
return call_calc_const(codemethnm, tupl, ret)
if ret[2][0] == 'CONST' and TCmp(ret, v, \
('!PyObject_Call', ('!PyObject_GetAttr', '?', ('CONST', '?')), ('CONST', '?'), ('NULL',))):
t = TypeExpr(v[0])
if t is not None and type(t[1]) is str and IsMethod(t[1], v[1]):
classmeth = Is3(t[1], ('ClassMethod', v[1]))
staticmeth = Is3(t[1], ('StaticMethod', v[1]))
codemethnm = ValMethod(t[1], v[1])
isoldclass = t[1] in calc_const_old_class
isnewclass = t[1] in calc_const_new_class
if is_old_class_inst(t) and isoldclass and not isnewclass:
if classmeth:
Debug('No direct call of class method', ret)
elif staticmeth:
tupl = ('CONST', v[2])
return call_calc_const(codemethnm, tupl, ret)
else:
v2 = tuple([('CONST', x) for x in v[2]])
tupl = ('!BUILD_TUPLE', (v[0],) + v2)
return call_calc_const(codemethnm, tupl, ret)
elif is_old_class_typ(t) and isoldclass and not isnewclass:
if classmeth:
Debug('No direct call of class method', ret)
elif staticmeth:
tupl = ('CONST', v[2])
return call_calc_const(codemethnm, tupl, ret)
else:
v2 = tuple([('CONST', x) for x in v[2]])
tupl = ('CONST', v2)
return call_calc_const(codemethnm, tupl, ret)
elif is_new_class_inst(t) and isnewclass and not isoldclass:
if classmeth:
Debug('No direct call of class method', ret)
elif staticmeth:
tupl = ('CONST', v[2])
return call_calc_const(codemethnm, tupl, ret)
else:
v2 = tuple([('CONST', x) for x in v[2]])
tupl = ('!BUILD_TUPLE', (v[0],) + v2)
return call_calc_const(codemethnm, tupl, ret)
elif is_new_class_typ(t) and isnewclass and not isoldclass:
if classmeth:
tupl = ('!BUILD_TUPLE', (v[0],) + v[2])
return call_calc_const(codemethnm, tupl, ret)
elif staticmeth:
tupl = ('CONST', v[2])
return call_calc_const(codemethnm, tupl, ret)
else:
v2 = tuple([('CONST', x) for x in v[2]])
tupl = ('CONST', v2)
return call_calc_const(codemethnm, tupl, ret)
_v = []
v = []
if \
r0 == '!PyObject_Call' and ret[1][0] == '!PyObject_GetAttr' and ret[1][2][0] == 'CONST':
if TCmp(ret, _v, ('!PyObject_Call', ('!PyObject_GetAttr', '?', ('CONST', '?')), '?', ('NULL',))):
obj, meth, args = _v
t = TypeExpr(obj)
if IsListAll(t):
if meth == 'pop':
if TCmp(args, v, ('CONST', ('?',))):
return ('!_PyList_Pop', obj, ('CONST', v[0]))
elif TCmp(args, v, ('CONST', ())):
return ('!_PyList_Pop', obj)
elif TCmp(args, v, ('!BUILD_TUPLE', ('?',))):
return ('!_PyList_Pop', obj, v[0])
elif meth == 'len' and args == ('CONST', ()) :
return ('!PY_SSIZE_T', ('!PyList_GET_SIZE', obj))
elif meth == 'extend' and not is_pypy:
v2 = []
if TCmp(args, v2, ('!BUILD_TUPLE', ('?',))):
return ('!_PyList_Extend', obj, v2[0])
elif IsStr(t):
if meth == 'startswith' and TCmp(args, v, ('CONST', ('?',))) and\
type(v[0]) is str:
return ('!_PyString_StartSwith', obj, ('CONST', v[0]))
if meth == 'endswith' and TCmp(args, v, ('CONST', ('?',))) and\
type(v[0]) is str:
return ('!_PyString_EndSwith', obj, ('CONST', v[0]))
if meth == 'find':
if TCmp(args, v, ('CONST', ('?',))) and type(v[0]) is str:
return ('!_PyString_Find', obj, ('CONST', v[0]))
if TCmp(args, v, ('!BUILD_TUPLE', ('?',))) and IsStr(TypeExpr(v[0])):
return ('!_PyString_Find', obj, v[0])
if meth == 'rfind':
if TCmp(args, v, ('CONST', ('?',))) and type(v[0]) is str:
return ('!_PyString_RFind', obj, ('CONST', v[0]))
if TCmp(args, v, ('!BUILD_TUPLE', ('?',))) and IsStr(TypeExpr(v[0])):
return ('!_PyString_RFind', obj, v[0])
if meth == 'index' and TCmp(args, v, ('CONST', ('?',))) and\
type(v[0]) is str:
return ('!_PyString_Index', obj, ('CONST', v[0]))
if meth == 'rindex' and TCmp(args, v, ('CONST', ('?',))) and\
type(v[0]) is str:
return ('!_PyString_RIndex', obj, ('CONST', v[0]))
if meth == 'index' and TCmp(args, v, ('!BUILD_TUPLE', ('?',))) and\
IsStr(TypeExpr(v[0])):
return ('!_PyString_Index', obj, v[0])
if meth == 'rindex' and TCmp(args, v, ('!BUILD_TUPLE', ('?',))) and\
IsStr(TypeExpr(v[0])):
return ('!_PyString_RIndex', obj, v[0])
if meth in ('isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper'):
if TCmp(args, v, ('CONST', ())):
return ('!_PyString_ctype', obj, meth)
elif IsDict(t):
if meth == 'copy':
if TCmp(args, v, ('CONST', ())):
return ('!PyDict_Copy', obj)
elif meth == 'get':
if TCmp(args, v, ('!BUILD_TUPLE', ('?','?'))):
return ('!_PyDict_Get', obj, v[0], v[1])
elif TCmp(args, v, ('!BUILD_TUPLE', ('?',))):
return ('!_PyDict_Get', obj, v[0], ('CONST', None))
elif TCmp(args, v, ('CONST', ('?','?'))):
return ('!_PyDict_Get', obj, ('CONST',v[0]), ('CONST', v[1]))
elif TCmp(args, v, ('CONST', ('?',))):
return ('!_PyDict_Get', obj, ('CONST',v[0]), ('CONST', None))
elif meth == 'has_key':
if TCmp(args, v, ('!BUILD_TUPLE', ('?',))):
return ('!BOOLEAN', ('!PyDict_Contains', obj, v[0]))
elif TCmp(args, v, ('CONST', ('?',))):
return ('!BOOLEAN', ('!PyDict_Contains', obj, ('CONST', v[0])))
elif meth == 'keys' and args == ('CONST', ()) :
return ('!PyDict_Keys', obj)
elif meth == 'values' and args == ('CONST', ()) :
return ('!PyDict_Values', obj)
elif meth == 'items' and args == ('CONST', ()) :
return ('!PyDict_Items', obj)
elif meth == 'len' and args == ('CONST', ()) :
return ('!PY_SSIZE_T', ('!PyDict_Size', obj))
# TypeError: 'int' object is not iterable !!!!!!!!
if len(obj) == 4 and obj[-1] == 'NULL' and obj[1][0] == '&' and \
obj[0].endswith('.tp_new') and obj[0][0] == '!' and \
obj[0][1:-7] == obj[1][1:] and obj[2][0] == 'CONST' and\
len(obj[2][1]) == 1:
t1 = TypeExpr(obj)
t2 = TypeExpr(('CONST', obj[2][1][0]))
if t1 == t2 and t1 is not None:
if args[0] == 'CONST':
ret_co = to_const_meth_1(obj, meth, args)
if ret_co is not None:
return ret_co
if obj[0] == 'CONST':
if args[0] == 'CONST':
ret_co = to_const_meth_2(obj, meth, args)
if ret_co is not None:
return ret_co
else:
Debug('Call const meth', obj, meth, args)
if ret == ('!BOOLEAN', ('CONST', True)):
return ('CONST', True)
if ret == ('!BOOLEAN', ('CONST', False)):
return ('CONST', False)
v = []
if r0 == '!COND_EXPR' and TCmp(ret,v, ('!COND_EXPR', ('CALC_CONST', '?'), '?', '?')):
t = TypeExpr(ret[1])
if t is not None and t[0] is types.ModuleType and t[1] is not None:
ret_modl = cond_expr_module(t, ret)
if ret_modl is not None:
return ret_modl
if r0 == 'PY_TYPE':
if ret[3][0] == 'CONST':
return ret[3]
v = []
if TCmp(ret, v, ( 'PY_TYPE', '?', '?', ('PY_TYPE', '?', '?', '?', None), None)) and v[0] == v[2] and v[1] == v[3]:
return ('PY_TYPE', v[0], v[1], v[4], None)
v = []
if TCmp(ret, v, ('PY_TYPE', '?', None, ('!PyNumber_Add', '?', '?'), '?')) and v[0] is int:
n1 = v[1]
n2 = v[2]
t = v[3]
if n1[0] not in ('PY_TYPE', 'CONST'):
n1 = ('PY_TYPE', int, None, n1, t)
if n2[0] not in ('PY_TYPE', 'CONST'):
n2 = ('PY_TYPE', int, None, n2, t)
return ('PY_TYPE', int, None, ('!PyNumber_Add', n1, n2), t)
if TCmp(ret, v, ('PY_TYPE', '?', None, ('!PyNumber_Subtract', '?', '?'), '?')) and v[0] is int:
n1 = v[1]
n2 = v[2]
t = v[3]
if n1[0] not in ('PY_TYPE', 'CONST'):
n1 = ('PY_TYPE', int, None, n1, t)
if n2[0] not in ('PY_TYPE', 'CONST'):
n2 = ('PY_TYPE', int, None, n2, t)
return ('PY_TYPE', int, None, ('!PyNumber_Subtract', n1, n2), t)
if TCmp(ret, v, ('PY_TYPE', '?', None, ('!PyNumber_Negative', '?'), '?')) and v[0] is int:
n1 = v[1]
t = v[2]
if n1[0] not in ('PY_TYPE', 'CONST'):
n1 = ('PY_TYPE', int, None, n1, t)
return ('PY_TYPE', int, None, ('!PyNumber_Negative', n1), t)
v = []
if len(ret) >= 2 and r0 == '(IF':
ret_n = repl_if_expr(ret[1])
if ret_n is not None:
return ('(IF', ret_n)
ret_n = if_expr_1(ret)
if ret_n is not None:
return ret_n
v = []
if r0 == '!BINARY_SUBSCR_Int' and ret[1][0] == '!BUILD_LIST' and \
TCmp(ret, v, \
('!BINARY_SUBSCR_Int', ('!BUILD_LIST', '?'), ('CONST', int))):
pos = v[1]
if pos < 0:
pos = pos + len(v[0])
if pos < len(v[0]):
return v[0][v[1]]
v = []
if r0 == '!c_Py_EQ_String' and \
TCmp(ret, v, ('!c_Py_EQ_String', ('CONST', '?'), ('CONST', '?'))):
return ('CONST', v[0] == v[1])
if r0 == '!c_Py_NE_String' and \
TCmp(ret, v, ('!c_Py_NE_String', ('CONST', '?'), ('CONST', '?'))):
return ('CONST', v[0] != v[1])
v = []
if len(ret) == 2 and \
type(ret[1]) is tuple and len(ret[1]) >= 1 and ret[1][0] == 'CONST':
op, v = r0, ret[1][1]
ret_ret = calc_expr_1(op, v)
if ret_ret is not None:
return ret_ret
v = []
if len(ret) == 4 and \
type(ret[1]) is tuple and len(ret[1]) >= 1 and ret[1][0] == 'CONST' and \
type(ret[2]) is tuple and len(ret[2]) >= 1 and ret[2][0] == 'CONST' and\
ret[3] == 'Py_None':
if r0 == '!PyNumber_Power':
ret_ret = calc_pow_1(ret)
if ret_ret is not None:
return ret_ret
v = []
if len(ret) == 3 and \
type(ret[1]) is tuple and len(ret[1]) >= 1 and ret[1][0] == 'CONST' and \
type(ret[2]) is tuple and len(ret[2]) >= 1 and ret[2][0] == 'CONST':
op, v1, v2 = r0, ret[1][1], ret[2][1]
ret_ret = calc_expr_2(op, v1, v2, ret)
if ret_ret is not None:
return ret_ret
if len(ret) == 3 and r0 == '!_EQ_' and \
type(ret[1]) is tuple and len(ret[1]) >= 1 and ret[1][0] == '!LOAD_BUILTIN' and \
type(ret[2]) is tuple and len(ret[2]) >= 1 and ret[2][0] == '!LOAD_BUILTIN':
return ('CONST', ret[1][1] == ret[2][1])
if len(ret) == 3 and r0 == '!_NEQ_' and \
type(ret[1]) is tuple and len(ret[1]) >= 1 and ret[1][0] == '!LOAD_BUILTIN' and \
type(ret[2]) is tuple and len(ret[2]) >= 1 and ret[2][0] == '!LOAD_BUILTIN':
return ('CONST', ret[1][1] != ret[2][1])
if len(ret) == 3 and r0 == '!_EQ_' and \
type(ret[1]) is tuple and len(ret[1]) >= 2 and ret[1][0] == '!PyObject_Type' and \
len(ret[1][1]) == 5 and type(ret[1][1][0]) is str and ret[1][1][0] == 'PY_TYPE' and \
ret[1][1][1] in type_to_check_str and \
type(ret[2]) is tuple and len(ret[2]) >= 1 and ret[2][0] == '!LOAD_BUILTIN':
return ('CONST', type_to_check_str[ret[1][1][1]] == ret[2][1])
if len(ret) == 3 and r0 == '!_NEQ_' and \
type(ret[1]) is tuple and len(ret[1]) >= 2 and ret[1][0] == '!PyObject_Type' and \
len(ret[1][1]) == 5 and type(ret[1][1][0]) is str and ret[1][1][0] == 'PY_TYPE' and \
ret[1][1][1] in type_to_check_str and \
type(ret[2]) is tuple and len(ret[2]) >= 1 and ret[2][0] == '!LOAD_BUILTIN':
return ('CONST', type_to_check_str[ret[1][1][1]] != ret[2][1])
v = []
if len(ret) >= 3 and (r0 == '!AND_BOOLEAN' or r0 == '!AND_JUMP') and \
type(ret[1]) is tuple and len(ret[1]) >= 1 and ret[1][0] == 'CONST':
op, v1 = r0, ret[1][1]
ret_ret = calc_expr_and(op, v1, ret)
if ret_ret is not None:
return ret_ret
v = []
if len(ret) >= 3 and (r0 == '!OR_BOOLEAN' or r0 == '!OR_JUMP') and \
type(ret[1]) is tuple and len(ret[1]) >= 1 and ret[1][0] == 'CONST':
op, v1 = r0, ret[1][1]
ret_ret = calc_expr_or(op, v1, ret)
if ret_ret is not None:
return ret_ret
if r0 == '!PyNumber_Divide' and \
TCmp(ret, v, ('!PyNumber_Divide', '?', ('CONST', 0))):
return ('!?Raise', ('BUILTIN', 'ZeroDivisionError'), ('CONST', "division by 0"), v[0])
v = []
if r0 == '!PySequence_Repeat' and \
TCmp(ret, v, ('!PySequence_Repeat', \
('!BUILD_LIST', (('CONST', '?'),)), \
('CONST', int))) and v[1] >= 0 and v[1] < 256:
return ('!BUILD_LIST', (('CONST', v[0]),) * v[1])
v = []
if r0 == 'UNPUSH':
if TCmp(ret, v, ('UNPUSH', ('!PyObject_Call',
('?', 'setattr'),
('!BUILD_TUPLE', ('?', '?', '?')), ('NULL',)))):
if v[0] == '!LOAD_BUILTIN':
return ('STORE', (('PyObject_SetAttr', v[1], v[2]),), (v[3],))
elif v[0] in ('!LOAD_GLOBAL', '!LOAD_NAME', '!PyDict_GetItem(glob,'):
return ('STORE', (('?PyObject_SetAttr', v[1], v[2], (v[0], 'setattr')),), (v[3],))
else:
return ret
v = []
if r0 == '!PyNumber_InPlaceAdd' and \
TCmp(ret, v, ('!PyNumber_InPlaceAdd', '?', '?')):
t1 = TypeExpr(v[0])
t2 = TypeExpr(v[1])
if IsStr(t1) and IsStr(t2):
if v[0][0] == v[1][0] == 'CONST':
return ('CONST', v[0][1] + v[1][1])
return ('!STR_CONCAT', v[0], v[1])
v = []
if r0 == '!STR_CONCAT':
li = list(ret[1:])
upd = False
for i, v in enumerate(li):
if v[0] == '!STR_CONCAT':
li[i:i+1] = list(v[1:])
upd = True
i = 0
while i+1 < len(li):
if li[i][0] == 'CONST' and li[i+1][0] == 'CONST' and type(li[i][1]) is str and type(li[i+1][1]) is str:
li[i] = ('CONST', li[i][1] + li[i+1][1])
del li[i+1]
upd = True
continue
i += 1
if len(li) == 1 and li[0][0] == 'CONST':
return li[0]
if upd:
return ('!STR_CONCAT',) + tuple(li)
if ret[1][0] == '!STR_CONCAT':
return ('!STR_CONCAT',) + ret[1][1:] + ret[2:]
if len(ret) >= 3 and ret[1][0] == 'CONST' and type(ret[1][1]) is str and ret[2][0] == '!STR_CONCAT':
return ('!STR_CONCAT', ret[1]) + ret[2][1:] + ret[3:]
if r0 == '!PyNumber_Add':
if TCmp(ret, v, ('!PyNumber_Add', ('CONST', str), ('!STR_CONCAT', '*'))):
return ('!STR_CONCAT', ('CONST', v[0])) + v[1]
if TCmp(ret, v, ('!PyNumber_Add', ('CONST', str), '?')):
return ('!STR_CONCAT', ('CONST', v[0]), v[1])
if TCmp(ret, v, ('!PyNumber_Add', ('!STR_CONCAT', '*'), ('CONST', str))):
return ('!STR_CONCAT',) + v[0] + (('CONST', v[1]),)
if TCmp(ret, v, ('!PyNumber_Add', '?', ('CONST', str))):
return ('!STR_CONCAT', v[0], ('CONST', v[1]))
if TCmp(ret, v, ('!PyNumber_Add', ('!STR_CONCAT', '*'), ('!STR_CONCAT', '*'))):
return ('!STR_CONCAT',) + v[0] + v[1]
if TCmp(ret, v, ('!PyNumber_Add', ('!STR_CONCAT', '*'), '?')):
return ('!STR_CONCAT',) + v[0] + (v[1],)
if TCmp(ret, v, ('!PyNumber_Add', '?', ('!STR_CONCAT', '*'))):
return ('!STR_CONCAT', v[0]) + v[1]
if IsStr(TypeExpr(ret[1])):
return ('!STR_CONCAT',) + ret[1:]
if IsStr(TypeExpr(ret[2])):
return ('!STR_CONCAT',) + ret[1:]
if ret[1][0] == '!BUILD_TUPLE' and ret[2][0] == '!BUILD_TUPLE':
return ('!BUILD_TUPLE', ret[1][1] + ret[2][1])
if r0 == '!PyNumber_Multiply':
if TCmp(ret, v, ('!PyNumber_Multiply', ('CONST', str), '?')):
return ('!PySequence_Repeat', ('CONST', v[0]), v[1])
if TCmp(ret, v, ('!PyNumber_Multiply', ('CONST', unicode), '?')):
return ('!PySequence_Repeat', ('CONST', v[0]), v[1])
if TCmp(ret, v, ('!PyNumber_Multiply', ('CONST', list), '?')):
return ('!PySequence_Repeat', ('CONST', v[0]), v[1])
if TCmp(ret, v, ('!PyNumber_Multiply', ('CONST', tuple), '?')):
return ('!PySequence_Repeat', ('CONST', v[0]), v[1])
if TCmp(ret, v, ('!PyNumber_Multiply', ('!STR_CONCAT', '*'), '?')):
return ('!PySequence_Repeat', ('!STR_CONCAT',) + v[0], v[1])
if TCmp(ret, v, ('!PyNumber_Multiply', ('!UNICODE_CONCAT', '*'), '?')):
return ('!PySequence_Repeat', ('!UNICODE_CONCAT',) + v[0], v[1])
if TCmp(ret, v, ('!PyNumber_Multiply', ('!BUILD_LIST', '*'), '?')):
return ('!PySequence_Repeat', ('!BUILD_LIST',) + v[0], v[1])
if TCmp(ret, v, ('!PyNumber_Multiply', ('!BUILD_LIST', '*'), '?')):
return ('!PySequence_Repeat', ('!BUILD_TUPLE',) + v[0], v[1])
if TCmp(ret, v, ('!PyNumber_Multiply', (('CONST', int), ('!BUILD_LIST', '*')))):
return ('!PySequence_Repeat', ('!BUILD_LIST',) + v[1], ('CONST', v[1]))
if len(ret) == 2 and r0 == '!BUILD_TUPLE':
if all([x[0] == 'CONST' for x in ret[1]]):
return ('CONST', tuple([x[1] for x in ret[1]]))
if type(r0) is str:
if r0 == '!PyObject_RichCompare(' and\
TCmp(ret, v, ('!PyObject_RichCompare(', '?', '?', c_2_op_op)):
n = _process_compare_op(c_2_op_op[v[2]], v[0],v[1])
if n is not None:
return n
elif r0 == '!PyObject_RichCompare' and \
TCmp(ret, v, ('!PyObject_RichCompare', '?', '?', c_2_op_op)):
n = _process_compare_op(c_2_op_op[v[2]], v[0],v[1])
if n is not None:
return n
v = []
if r0 == '!_PyEval_BuildClass':
if TCmp(ret, v, ('!_PyEval_BuildClass', \
('!PyObject_Call', \
('!MK_CLOSURE', '?', '?', '?'), \
'?', '?'), '?', ('CONST', '?'))):
_3(v[0], 'IsClassCreator', v[6])
elif TCmp(ret, v, ('!_PyEval_BuildClass', \
('!PyObject_Call', \
('!MK_FUNK', '?', '?'), '?', '?'), \
'?', ('CONST', '?'))):
_3(v[0], 'IsClassCreator', v[5])
v0 = []
if r0 == 'STORE':
if TCmp(ret, v0, ('STORE', (('STORE_CALC_CONST', ('?', '?')),), ('?',))) and \
v0[0] in ('STORE_NAME', 'STORE_GLOBAL') and v0[1] in all_calc_const:
v = [(v0[1], '', all_calc_const[v0[1]]), v0[2]]
if v[1] == ('!MK_FUNK', v[0][0], ('CONST', ())):
val_direct_code[v[0][0]] = v[1]
direct_code[v[0][0]] = v[1][1]
elif v[0][2][0] == '!MK_FUNK' and v[0][2][2] != v[0][0] and v[0][2][2] == ('CONST', ()):
val_direct_code[v[0][0]] = v[0][2]
direct_code[v[0][0]] = v[0][2][1]
elif v[1][0] == '!MK_FUNK' and v[1][1] == v[0][0] and \
v[1][2][0] == 'CONST' and len(v[1][2][1]) > 0:
val_direct_code[v[0][0]] = v[1]
direct_code[v[0][0]] = v[1][1]
default_args[v[0][0]] = v[1][2]
elif v[1][0] == '!_PyEval_BuildClass':
v1 = v[1]
v1_1 = []
v1_2 = []
if TCmp(v1, v1_1, ('!_PyEval_BuildClass',\
('!PyObject_Call',\
('!MK_FUNK', v[0][0], ('CONST', ())),\
('CONST', ()), ('NULL',)),\
'?', ('CONST', v[0][0]))):
if v1_1[0] == ('CONST', ()):
if not Is3(v[0][0], 'HaveMetaClass'):
calc_const_old_class[v[0][0]] = v[1]
elif TCmp(v1, v1_2, ('!_PyEval_BuildClass',\
('!BUILD_MAP', '?'),\
'?', ('CONST', v[0][0]))):
if v1_2[1] == ('CONST', ()):
if not Is3(v[0][0], 'HaveMetaClass'):
calc_const_old_class[v[0][0]] = v[1]
else:
pprint(v1)
Fatal('calcConst???Class', v1)
v0 = []
if len(ret[1]) == 1 and len(ret[1][0]) == 2 and \
ret[1][0][0] in ('STORE_NAME', 'STORE_GLOBAL') and \
ret[1][0][1] in all_calc_const and TCmp(ret, v0, ('STORE', (('?', '?'),), ('?',))):
v = [(v0[1], '', all_calc_const[v0[1]]), v0[2]]
if v[1] == ('!MK_FUNK', v[0][0], ('CONST', ())):
val_direct_code[v[0][0]] = v[1]
direct_code[v[0][0]] = v[1][1]
elif v[0][2][0] == '!MK_FUNK' and v[0][2][2] != v[0][0] and v[0][2][2] == ('CONST', ()):
val_direct_code[v[0][0]] = v[0][2]
direct_code[v[0][0]] = v[0][2][1]
elif v[1][0] == '!MK_FUNK' and v[1][1] == v[0][0] and \
v[1][2][0] == 'CONST' and len(v[1][2][1]) > 0:
val_direct_code[v[0][0]] = v[1]
direct_code[v[0][0]] = v[1][1]
default_args[v[0][0]] = v[1][2]
elif v[1][0] == '!_PyEval_BuildClass':
v1 = v[1]
v1_1 = []
if TCmp(v1, v1_1, ('!_PyEval_BuildClass',\
('!PyObject_Call',\
('!MK_FUNK', v[0][0], ('CONST', ())),\
('CONST', ()), ('NULL',)),\
'?', ('CONST', v[0][0]))):
## vv = []
if v1_1[0] == ('CONST', ()):
if not Is3(v[0][0], 'HaveMetaClass'):
calc_const_old_class[v[0][0]] = v[1]
elif v1_1[0][0] == '!BUILD_TUPLE':
## f = v1_1[0][1]
for der in v1_1[0][1]:
if der[0] == '!LOAD_BUILTIN':
calc_const_new_class[v[0][0]] = v[1]
_3(v[0][0], 'Derived', der)
elif der[0] in ('!LOAD_NAME', '!LOAD_GLOBAL'):
if der[1] in calc_const_old_class:
if not Is3(v[0][0], 'HaveMetaClass'):
calc_const_old_class[v[0][0]] = v[1]
_3(v[0][0], 'Derived', ('!CALC_CONST', der[1]))
if der[1] in calc_const_new_class:
calc_const_new_class[v[0][0]] = v[1]
_3(v[0][0], 'Derived', ('!CALC_CONST', der[1]))
else:
Debug('Not name CalcConst???Class', v1)
elif der[0] == '!PyObject_GetAttr':
pass
elif der[0] == '!PyObject_Type':
Debug('Not name CalcConst???Class', v1)
elif der[0] == '!PyObject_Call':
Debug('Not name CalcConst???Class', v1)
else:
Debug('Not name CalcConst???Class', v1, der)
else:
print v1_1[0], v1_1[0][0], v1_1
Fatal('?k', v1)
else:
Fatal('?k', v1)
return ret
def collect_modules_attr(ret):
v = []
if type(ret) is tuple and len(ret) > 1 and ret[0] == '!PyObject_GetAttr' and\
TCmp(ret, v, ('!PyObject_GetAttr', \
(('|', 'CALC_CONST', \
'!LOAD_NAME', \
'!LOAD_GLOBAL', \
'!PyDict_GetItem(glob,'), \
':ImportedM:'), ('CONST', '?'))) and \
ModuleHaveAttr(v[0][0], v[1]):
if v[0][2][:6] == '__buil' and v[0][2][6:] == 'tin__':
pass
elif v[0][2] == 'sys' and v[1] in sys_const:
return ('CONST', getattr(sys,v[1]))
else:
if v[0][2] != 'sys' and v[0][2] not in variable_module_attr:
v2 = IfConstImp(v[0][0], v[1])
if v2 is not None:
return v2
if ModuleHaveAttr(v[0][0], v[1]) and v[0][2] not in variable_module_attr:
_3(v[0][0], 'ModuleAttr', v[1])
variable_module_attr = ('time', 'strptime', '_strptime', 'textwrap')
sys_const = ('byteorder', 'subversion', 'builtin_module_names',
'copyright', 'hexversion', 'maxint', 'maxsize', 'maxunicode',
'platform', 'version', 'api_version')
def is_right_const_value(v2):
if type(v2) in (int,long,bool,complex,float):
return True
return False
def IfConstImp(imp,nm):
assert imp is not None
v2 = val_imp(imp, nm)
if is_right_const_value(v2):
return ('CONST', v2)
return None
def ModuleHaveAttr(imp,nm):
if imp[:6] == '__buil' and imp[6:] == 'tin__':
return nm in d_built
if imp == 'sys' or imp in variable_module_attr or (imp[:6] == '__buil' and imp[6:] == 'tin__'):
return False
if Is3(imp, 'ImportedM'):
v = Val3(imp, 'ImportedM')
if type(v) is tuple and len(v) == 2:
imp = v[0] + '.' + v[1]
if v[0] in list_import and v[1] in list_import[v[0]] and not IsModule(list_import[v[0]][v[1]]):
return False
elif type(v) is str and v != imp:
imp = v
elif v != imp:
Fatal(imp, v, nm)
if imp == 'sys' or imp in variable_module_attr:
return False
v2 = val_imp(imp, nm)
if v2 is None:
return False
return True
def repl_collected_module_attr(ret):
# global all_calculated_const
if type(ret) is tuple and len(ret) >= 1 and type(ret[0]) is str and ret[0] == '!PyObject_GetAttr':
v = []
if TCmp(ret, v, ('!PyObject_GetAttr', '?', ('CONST', '?'))):
t = TypeExpr(v[0])
if t is not None and t[0] is types.ModuleType and t[1] == 'sys' and v[1] in sys_const:
return ('CONST', getattr(sys,v[1]))
elif t is not None and t[0] is types.ModuleType and t[1] != 'sys' and\
t[1] is not None and t[1] not in variable_module_attr:
v2 = IfConstImp(t[1], v[1])
if v2 is not None:
return v2
v = []
if TCmp(ret, v, ('!PyObject_GetAttr',
(('|', 'CALC_CONST',
'!LOAD_NAME',
'!LOAD_GLOBAL',
'!PyDict_GetItem(glob,'),
':ImportedM:'), ('CONST', '?'))):
if v[0][2] == 'sys' and v[1] in sys_const:
return ('CONST', getattr(sys,v[1]))
elif v[0][2] != 'sys' and v[0][2] not in variable_module_attr:
v2 = IfConstImp(v[0][0], v[1])
if v2 is not None:
return v2
if v[0][2] != 'sys' and ModuleHaveAttr(v[0][0], v[1]) and v[0][2] not in variable_module_attr:
_3(v[0][0], 'ModuleAttr', v[1])
ret = calc_const_to((v[0][0], v[1]))
v = []
if TCmp(ret, v, ('!PyObject_GetAttr', ('CALC_CONST', '?'), ('CONST', '?'))):
t = TypeExpr(('CALC_CONST', v[0]))
if not redefined_attribute and t != None and \
t[0] in (T_NEW_CL_INST, T_OLD_CL_INST) and\
IsAttrInstance(t[1], v[1]) and not is_pypy:
_3(v[0], 'ModuleAttr', '.__dict__')
calc_const_to((v[0], '.__dict__'))
v = []
if type(ret) is tuple and len(ret) == 2 and type(ret[0]) is str and \
ret[0] in ('!LOAD_NAME', '!LOAD_GLOBAL', '!PyDict_GetItem(glob,') and \
ret[1] in all_calc_const:
ret = calc_const_to(ret[1])
return ret
def upgrade_op(ret, nm = None):
if type(ret) is tuple and len(ret) == 2 and \
ret[0] in ('!LOAD_NAME', '!LOAD_GLOBAL', '!PyDict_GetItem(glob,') and \
ret[1] in mnemonic_constant:
return mnemonic_constant[ret[1]]
collect_modules_attr(ret)
return repl(ret)
methods_type = {(Kl_String, 'find'): Kl_Short,
(Kl_String, 'index'): Kl_Short,
(Kl_String, 'split'): Kl_List,
(Kl_String, 'splitlines'): Kl_List,
(Kl_String, 'ljust'): Kl_String,
(Kl_String, 'rjust'): Kl_String,
(Kl_String, 'zfill'): Kl_String,
(Kl_String, 'lower'): Kl_String,
(Kl_String, 'upper'): Kl_String,
(Kl_String, 'encode'): None,
(Kl_String, 'replace'): Kl_String,
(Kl_String, 'strip'): Kl_String,
(Kl_String, 'rstrip'): Kl_String,
(Kl_String, 'lstrip'): Kl_String,
(Kl_String, 'center'): Kl_String,
(Kl_String, 'join'): Kl_String,
(Kl_String, 'startswith'): Kl_Boolean,
(Kl_String, 'endswith'): Kl_Boolean,
(Kl_String, 'isalnum'): Kl_Boolean,
(Kl_String, 'isalpha'): Kl_Boolean,
(Kl_String, 'isdigit'): Kl_Boolean,
(Kl_String, 'islower'): Kl_Boolean,
(Kl_String, 'isspace'): Kl_Boolean,
(Kl_String, 'istitle'): Kl_Boolean,
(Kl_String, 'isupper'): Kl_Boolean,
(Kl_File, 'close'): Kl_None,
(Kl_File, 'write'): Kl_None,
(Kl_File, 'seek'): Kl_None,
(Kl_File, 'fileno'): Kl_Int,
(Kl_File, 'tell'): Kl_Long,
(Kl_File, 'read'): Kl_String,
(Kl_File, 'getvalue'): Kl_String,
(Kl_File, 'readline'): Kl_String,
(Kl_File, 'readlines'): Kl_List,
(Kl_Dict, 'iteritems'): Kl_Generator,
(Kl_Dict, 'iterkeys'): Kl_Generator,
(Kl_Dict, 'copy'): Kl_Dict,
(Kl_Dict, 'keys'): Kl_List,
(Kl_Dict, 'values'): Kl_List,
(Kl_Dict, 'items'): (list, (tuple,(None,None))),
(Kl_Dict, 'itervalues'): Kl_Generator,
(Kl_Dict, 'setdefault'): None,
(Kl_Dict, 'get'): None,
(Kl_List, 'popitem'): Kl_Tuple,
(Kl_List, 'pop'): None,
(Kl_List, 'append'): Kl_None,
(Kl_List, 'insert'): Kl_None,
(Kl_List, 'sort'): Kl_None,
(Kl_List, 'remove'): Kl_None,
(Kl_List, 'index'): Kl_Short,
(Kl_List, 'count'): Kl_Short,
(Kl_List, 'pop'): None,
((T_NEW_CL_INST, 'StringIO'), 'getvalue') : Kl_String,
# (Klass(T_NEW_CL_INST, 'Popen'), 'stdin') : None,
((T_OLD_CL_INST, 'ZipFile'), 'getinfo') : (T_OLD_CL_INST, 'ZipInfo'),
((T_OLD_CL_INST, 'ZipFile'), 'infolist') : Kl_List,
((T_OLD_CL_INST, 'ZipFile'), 'namelist') : Kl_List,
(Kl_MatchObject, 'group'): None,
(Kl_MatchObject, 'groups'): Kl_Tuple,
(Kl_MatchObject, 'span'): Kl_Tuple,
(Kl_RegexObject, 'subn'): Kl_Tuple,
(Kl_RegexObject, 'search'): None,
(Kl_RegexObject, 'finditer'): Kl_Generator,
(Kl_RegexObject, 'findall'): Kl_List,
(Kl_RegexObject, 'split'): Kl_List,
(Kl_RegexObject, 'match'): None,
(Kl_RegexObject, 'sub'): Kl_String
}
klass_attr = {(('NewClassInstance', 'Popen'), 'stdin') : None,
(('NewClassInstance', 'Popen'), 'stdout') : None,
(('NewClassInstance', 'Popen'), 'stderr') : None}
tag_type = {}
def TypeDef(kl, *words):
for w in words:
tag_type[w] = kl
TypeDef(Kl_Char, '!CHR_BUILTIN')
TypeDef(Kl_String, '!_PyString_Join')
TypeDef((list, (tuple,(None,None))), '!PyDict_Items')
TypeDef(Kl_List, '!PyDict_Keys', '!PyDict_Values', '!PyList_GetSlice')
TypeDef(Kl_List, '!BUILD_LIST', \
'!PySequence_List', '!LIST_COMPR', '!PyObject_Dir')
TypeDef(Kl_Tuple, '!BUILD_TUPLE', '!PyList_AsTuple', '!PySequence_Tuple', '!PyTuple_GetSlice')
TypeDef(Kl_Dict, '!BUILD_MAP', '!PyDict_New', '!_PyDict_New', '!_PyDict_NewPresized', '!PyDict_Copy')
TypeDef(Kl_String, '!PyObject_Repr', '!STR_CONCAT2', '!STR_CONCAT_N',\
'!STR_CONCAT3', '!PyString_Format', '!STR_CONCAT', \
'!PyObject_Str', '!PyNumber_ToBase', '!_PyInt_Format', '!PyInt_Type.tp_str')
TypeDef(Kl_Int, '!PyInt_FromLong', '!PyInt_Type.tp_new')
TypeDef(Kl_Short, '!PY_SSIZE_T', '!@PyInt_FromSsize_t', '!ORD_BUILTIN', \
'!PyInt_FromSsize_t', '!_PyString_Find', '!_PyString_RFind', '!_PyString_Index', '!_PyString_RIndex')
TypeDef(Kl_Short, *len_family)
TypeDef(Kl_Long, '!PyLong_Type.tp_new', '!PyNumber_Long')
TypeDef(Kl_Set, '!PySet_New', '!BUILD_SET')
TypeDef(Kl_FrozenSet, '!PyFrozenSet_New')
TypeDef(Kl_Type, '!PyObject_Type')
TypeDef(Kl_Slice, '!PySlice_New')
TypeDef(Kl_Boolean, '!AND_JUMP', '!OR_JUMP', '!PyObject_IsInstance', '!PyObject_IsSubclass', \
'!PySequence_Contains(', '!_EQ_', '!OR_BOOLEAN', '!AND_BOOLEAN', \
'!1NOT', '!_PyString_StartSwith', '!_PyString_EndSwith',\
'!c_Py_EQ_Int', '!c_Py_NE_Int', '!c_Py_LT_Int', \
'!c_Py_LE_Int', '!c_Py_GT_Int', '!c_Py_GE_Int', \
'!c_Py_EQ_String', '!c_Py_NE_String', '!SSIZE_T==', '!SSIZE_T!=',\
'!SSIZE_T>', '!SSIZE_T<', '!SSIZE_T>=', '!SSIZE_T<=', \
'!PyDict_Contains', '!PySequence_Contains', '!PyBool_Type.tp_new',\
'!_NEQ_', '!_EQ_', '!_PyString_Contains', '!_PyString_ctype')
TypeDef(Kl_Float, '!PyFloat_Type.tp_new', '!PyNumber_Float')
TypeDef(Kl_Generator, '!GET_ITER')
tag_builtin = {}
def TypeBuilt(kl, *words):
for w in words:
tag_builtin[w] = kl
TypeBuilt(Kl_Tuple, 'divmod', 'tuple')
TypeBuilt(Kl_List, 'map', 'range', 'zip', 'list', 'dir', 'sorted')
TypeBuilt(Kl_Boolean, 'all', 'any', 'callable', 'isinstance', 'issubclass')
TypeBuilt(Kl_Int, 'hash', 'int')
TypeBuilt(Kl_Short, 'cmp', 'len', 'ord')
TypeBuilt(Kl_Dict, 'dict', 'globals', 'locals', 'vars')
TypeBuilt(Kl_Float, 'float', 'round')
TypeBuilt(Kl_String, 'hex', 'oct', 'str', 'repr', 'raw_input', 'bin', 'bytes')
TypeBuilt(Kl_Char, 'chr')
TypeBuilt(Kl_Unicode, 'unicode', 'unichr')
TypeBuilt(Kl_File, 'file', 'open')
TypeBuilt(Kl_Slice, 'slice')
TypeBuilt(Kl_Buffer, 'buffer')
TypeBuilt(Kl_XRange, 'xrange')
TypeBuilt(Kl_Complex, 'complex')
TypeBuilt(Kl_Set, 'set')
TypeBuilt(Kl_FrozenSet, 'frozenset')
TypeBuilt(Kl_StaticMethod, 'staticmethod')
TypeBuilt(Kl_Module(None), '__import__')
TypeBuilt(Kl_ClassMethod, 'classmethod')
TypeBuilt(Kl_Generator, 'enumerate', 'reversed', 'iter')
TypeBuilt(None, 'min', 'max', 'property', 'reduce', 'eval', 'super', \
'sum', 'compile', 'ValueError', 'IOError', \
'SyntaxError', 'input', 'bytearray', \
'filter')
## def TypeExpr(ret):
## r = _TypeExpr(ret)
## print >>out, ret
## pprint(r, out)
## assert r is None or (len(r) == 2 and type(r) is tuple)
## return r
def TypeExpr(ret):
if ret == 'Py_None':
return Kl_None
if type(ret) != tuple:
return None
if len(ret) < 1:
return None
if ret[0] == '!?Raise':
return ('Raise', ret[1])
if ret[0] == '!LOAD_BUILTIN':
if ret[1] in d_built and type(d_built[ret[1]]) == type(len):
return Kl_BuiltinFunction
elif ret[1] in d_built and type(d_built[ret[1]]) == type(int):
return Kl_Type
if ret == ('!LOAD_NAME', '__name__'):
return Kl_String
if ret[0] == '!LOAD_GLOBAL' and ret[1] in detected_global_type:
return detected_global_type[ret[1]]
if ret[0] == 'FAST':
if ret[1] in current_co.detected_type:
return current_co.detected_type[ret[1]]
if current_co.can_be_codefunc() and hasattr(current_co, 'no_codefunc') and current_co.no_codefunc:
ind = -1
if ret[1] in current_co.co_varnames:
ind = current_co.co_varnames.index(ret[1])
if ind != -1 and ind in current_co.typed_arg_direct:
return current_co.typed_arg_direct[ind]
return current_co.TypeVar(ret)
if ret[0] == '!COND_EXPR':
t1 = TypeExpr(ret[2])
t2 = TypeExpr(ret[3])
if t1 == t2:
return t1
return None
if ret[0] == '!COND_METH_EXPR':
return TypeExpr(ret[2])
if ret[0] == '!PyNumber_Int':
t1 = TypeExpr(ret[1])
if IsBool(t1):
return Kl_Short
if IsInt(t1):
return t1
return Kl_IntUndefSize
if ret[0] == '!PyNumber_Negative':
t1 = TypeExpr(ret[1])
if IsIntOrFloat(t1):
return t1
if ret[0] == '!PyNumber_Remainder':
t1 = TypeExpr(ret[1])
t2 = TypeExpr(ret[2])
if IsInt(t1) and IsShort(t2):
return Kl_Short
if IsInt(t1) and IsIntOnly(t2):
return Kl_Int
if ret[0] == '!PyNumber_Remainder' and IsStr(t1):
return Kl_String
if ret[0] in ('!OR_BOOLEAN', '!AND_BOOLEAN'):
d2 = dict.fromkeys([TypeExpr(x) for x in ret[1:]]).keys()
if len(d2) == 1:
return d2[0]
return None
if ret[0] in ('!OR_JUMPED_STACKED', '!AND_JUMPED_STACKED'):
d2 = dict.fromkeys([TypeExpr(x) for x in ret[1:]]).keys()
if len(d2) == 1:
return d2[0]
return None
if ret[0] == '!MK_FUNK':
return (types.FunctionType, ret[1])
if ret[0] == 'PY_TYPE':
return (ret[1], ret[2])
if ret[0] == 'CONST':
if type(ret[1]) is int and ret[1] >= -30000 and ret[1] <= 30000:
return Kl_Short
if type(ret[1]) is tuple:
return (tuple, tuple([TypeExpr(('CONST', x)) for x in ret[1]]))
if type(ret[1]) is str and len(ret[1]) == 1:
return Kl_Char
return (type(ret[1]), None)
if ret[0] == '!BUILD_TUPLE':
return (tuple, tuple([TypeExpr(x) for x in ret[1]]))
if ret[0] in tag_type:
return tag_type[ret[0]]
if ret[0] == '!CLASS_CALC_CONST':
return (T_OLD_CL_INST, ret[1])
if ret[0] == '!CLASS_CALC_CONST_DIRECT':
return (T_OLD_CL_INST, ret[1])
if ret[0] == '!CLASS_CALC_CONST_NEW':
return (T_NEW_CL_INST, ret[1])
if ret[0] == '!CLASS_CALC_CONST_NEW_DIRECT':
return (T_NEW_CL_INST, ret[1])
if ret[0] == '!_PyEval_BuildClass' and ret[2] == ('CONST', ()) and ret[3][0] == 'CONST':
return (T_OLD_CL_TYP, ret[3][1])
if ret[0] == '!PyObject_GetAttr' and ret[2][0] == 'CONST':
t1 = TypeExpr(ret[1])
if t1 is not None and (t1, ret[2][1]) in klass_attr:
return klass_attr[(t1, ret[2][1])]
if t1 is not None and (t1, ret[2][1]) in methods_type:
return (types.MethodType, None)
if t1 == Kl_Char and (Kl_String, ret[2][1]) in methods_type:
return (types.MethodType, None)
if t1 is not None:
if t1[0] == 'MayBe':
t1 = t1[1]
if IsAnyClass(t1[1]):
pass
elif t1[0] is types.ModuleType:
tupl = (t1[1], ret[2][1], 'val')
if tupl in t_imp:
return t_imp[tupl]
tupl = (t1[1], ret[2][1], '()')
if tupl in t_imp:
return (types.MethodType, None)
if t1[1] in list_import:
d2 = list_import[t1[1]]
if ret[2][1] not in d2 and len(d2) != 0:
Debug('Module attrib is not valid: %s -> %s ()' % (t1, ret[2][1]), ret)
if ret[2][1] in d2:
t2 = d2[ret[2][1]]
if t2[0] is types.ModuleType and t2[1] is None:
nm2 = t1[1] + '.' + ret[2][1]
CheckExistListImport(nm2)
return (types.ModuleType, nm2)
return t2
if len(d2) == 0:
return None
Debug('Undefined type attrib: %s -> %s ()' % (t1, ret[2][1]), ret)
if IsKlNone(t1):
Fatal('')
else:
Debug('Undefined type attrib: %s -> %s ()' % (t1, ret[2][1]), ret)
if IsKlNone(t1):
return None
if ret[2][1] in detected_attr_type:
r = detected_attr_type[ret[2][1]]
if r == Kl_BuiltinFunction and (not IsModule(t1) or 'self' in repr(ret)):
if (IsList(t1) or IsTuple(t1) or IsDict(t1) or t1 == Kl_Set) and ret[2][1][:2] != '__':
return r
if t1 is not None:
Debug('May by CFunction attribute of %s ?' % repr(t1), ret)
return None
return r
return None
if ret[0] == '!CALL_CALC_CONST':
if ret[1] in detected_return_type:
return detected_return_type[ret[1]]
return None
if ret[0] == '!CALL_CALC_CONST_INDIRECT':
if ret[1] in detected_return_type:
return detected_return_type[ret[1]]
return None
if ret[0] == '!1NOT':
t1 = TypeExpr(ret[1])
if IsInt(t1) or IsBool(t1):
return Kl_Boolean
if ret[0] == '!BINARY_SUBSCR_Int':
t1 = TypeExpr(ret[1])
if IsStr(t1) and \
TypeExpr(ret[2]) in (Kl_Short, Kl_Int, Kl_IntUndefSize):
return Kl_Char
elif IsTuple(t1) and t1[1] is not None and ret[2][0] == 'CONST' and type(t1[1]) is tuple:
ind = ret[2][1]
if ind >= 0 and ind < len(t1[1]):
return t1[1][ind]
if ret[0] == '!BINARY_SUBSCR_Int' and IsStr(TypeExpr(ret[1])) and\
TypeExpr(ret[2]) in (Kl_Short, Kl_Int, Kl_IntUndefSize):
return Kl_Char
if ret[0] == '!from_ceval_BINARY_SUBSCR':
t1 = TypeExpr(ret[1])
t2 = TypeExpr(ret[2])
if IsStr(t1) and t2 in (Kl_Short, Kl_Int, Kl_IntUndefSize):
return Kl_Char
if IsStr(t1):
return Kl_String
elif IsTuple(t1) and t1[1] is not None and ret[2][0] == 'CONST':
ind = ret[2][1]
if ind >= 0 and ind < len(t1[1]):
return t1[1][ind]
if ret[0] == 'CALC_CONST':
nm = ret[1]
if type(nm) is tuple and len(nm) == 2:
tupl = (Val3(nm[0], 'ImportedM'), nm[1], 'val')
if tupl in t_imp:
return t_imp[tupl]
tupl = (Val3(nm[0], 'ImportedM'), nm[1], '()')
if tupl in t_imp:
return ('lazycall', t_imp[tupl])
if ret[1] in calc_const_old_class:
return (T_OLD_CL_TYP, ret[1])
if ret[1] in calc_const_new_class:
return (T_NEW_CL_TYP, ret[1])
if ret[1] not in calc_const_value:
return None
return TypeExpr(calc_const_value[ret[1]]) #Klass(ret)
if ret[0] == '!PySequence_Repeat':
t1 = TypeExpr(ret[1])
if t1 == Kl_Char:
return Kl_String
if t1 is not None and t1[0] is tuple:
return Kl_Tuple
return t1
if ret[0] in ('!PyNumber_Lshift', '!PyNumber_Rshift'):
t1 = TypeExpr(ret[1])
if t1 == Kl_Long:
return t1
if IsInt(t1) and ret[0] == '!PyNumber_Rshift' :
return t1
## v = []
if (ret[0] == '!PyNumber_Lshift' or ret[0] == '!PyNumber_InPlaceLshift'):
if ret[2][0] == 'CONST' and type(ret[2][1]) is int and ret[2][1] >= 1 and ret[2][1] <= 31:
t1 = TypeExpr(ret[1])
if IsShort(t1) and ret[2][1] < 16:
return Kl_Int
if ret[0] == '!PyObject_Call':
if ret[1][0] == '!LOAD_BUILTIN':
d2 = ret[1][1]
if d2 in ('max', 'min') and ret[2][0] == '!BUILD_TUPLE' and len (ret[2][1]) == 2:
t1 = TypeExpr(ret[2][1][0])
t2 = TypeExpr(ret[2][1][1])
if t1 == t2:
return t1
if d2 == 'sorted':
if ret[2][0] == '!BUILD_TUPLE' and len(ret[2][1]) == 1 and \
ret[3] == ('NULL',):
t2 = TypeExpr(ret[2][1][0])
if IsList(t2):
return t2
if d2 in tag_builtin:
return tag_builtin[d2]
else:
Debug('Undefined type builtin: %s' % (d2,), ret)
return None
if ret[1][0] == 'CALC_CONST':
nm = ret[1][1]
if type(nm) is tuple and len(nm) == 2:
tuplcall = (Val3(nm[0], 'ImportedM'), nm[1], '()')
if tuplcall in t_imp:
return t_imp[tuplcall]
elif type(nm) is str:
tuplcall = Val3(nm, 'ImportedM')
if type(tuplcall) is tuple:
tuplcall += ('()',)
if tuplcall in t_imp:
return t_imp[tuplcall]
t2 = TypeExpr(ret[1])
if t2 is not None and t2[0] == 'lazycall':
# Debug('Lazycall detected', t2, ret)
return t2[1]
## if ret[1][0] == 'CALC_CONST':
## nm = ret[1][1]
## if type(nm) is tuple and len(nm) == 2:
## tupl = (Val3(nm[0], 'ImportedM'), nm[1], '()')
## elif type(tupl) is str:
## tupl = (Val3(nm, 'ImportedM') + ('()',)
## if tupl in t_imp:
## return t_imp[tupl]
_v = []
if TCmp(ret[1], _v, ('!PyObject_GetAttr', '?', ('CONST', '?'))):
if _v[1] == 'fromkeys' and TCmp(_v[0], [], ('!LOAD_BUILTIN', 'dict')):
return Kl_Dict
t1 = TypeExpr(_v[0])
if t1 is not None and (t1, _v[1]) in methods_type:
return methods_type[(t1, _v[1])]
elif t1 == Kl_Char and (Kl_String, _v[1]) in methods_type:
return methods_type[(Kl_String, _v[1])]
elif t1 is not None:
if type(t1[1]) is str and IsAnyClass(t1[1]):
pass
elif t1[0] is types.ModuleType:
tupl = (t1[1], _v[1], '()')
if tupl in t_imp:
return t_imp[tupl]
tupl = (t1[1], _v[1], 'val')
if tupl in t_imp:
t2 = t_imp[tupl]
if t2[0] == T_OLD_CL_TYP:
return (T_OLD_CL_INST, _v[1])
elif t2[0] == T_NEW_CL_TYP:
return (T_NEW_CL_INST, _v[1])
Debug('Undefined type method: %s -> %s ()' % (t1, _v[1]), ret)
else:
Debug('Undefined type method: %s -> %s ()' % (t1, _v[1]), ret)
return None
if ret[0] == '!PyNumber_Power':
if Kl_Float == TypeExpr(ret[1]) and Kl_Float == TypeExpr(ret[2]):
return Kl_Float
return None
if ret[0] in ('!PyNumber_And', '!PyNumber_Or', '!PyNumber_InPlaceAnd', '!PyNumber_InPlaceOr'):
t1 = TypeExpr(ret[1])
t2 = TypeExpr(ret[2])
if (t1,t2) == (Kl_Short, Kl_Short):
return Kl_Short
if IsInt(t1) and IsInt(t2):
return Kl_Int
if ret[0] == '!PyNumber_Absolute':
return TypeExpr(ret[1])
if ret[0] in ('!PyNumber_Add', '!PyNumber_InPlaceAdd'):
t1 = TypeExpr(ret[1])
t2 = TypeExpr(ret[2])
if Kl_Float == t1 and Kl_Float == t2:
return Kl_Float
if IsTuple(t1) and ret[2][0] == '!PySequence_GetSlice':
return t1
ty = (t1,t2)
if Kl_Boolean in ty and (IsInt(t1) or IsInt(t2)) :
if Kl_Short in ty:
return Kl_Short
return Kl_Int
if IsShort(t1) and IsShort(t2):
return Kl_Int
if t1 is not None and not IsInt(t1) and t1 == t2:
return t1
if IsTuple(t2) and ret[1][0] == '!PySequence_GetSlice':
return t2
if IsFloat(t1) and IsFloat(t2):
return Kl_Float
if IsInt(t1) and IsFloat(t2):
return Kl_Float
if IsInt(t2) and IsFloat(t1):
return Kl_Float
if IsIntUndefSize(t1) and IsFloat(t2):
return Kl_Float
if IsIntUndefSize(t2) and IsFloat(t1):
return Kl_Float
if IsIntOnly(t1) and IsShort(t2) and IsSumShort(ret[1]):
return Kl_Int
if IsIntOnly(t2) and IsShort(t1) and IsSumShort(ret[2]):
return Kl_Int
if IsIntOnly(t1) and IsInt(t2):
return Kl_IntUndefSize
if IsIntOnly(t2) and IsInt(t1):
return Kl_IntUndefSize
if IsIntUndefSize(t1) and IsInt(t2):
return Kl_IntUndefSize
if IsIntUndefSize(t2) and IsInt(t1):
return Kl_IntUndefSize
if IsIntUndefSize(t1) and IsIntUndefSize(t2):
return Kl_IntUndefSize
if IsTuple(t1) and IsTuple(t2):
t1_1 = t1[1]
t2_1 = t2[1]
if t1_1 is not None and t2_1 is not None:
if type(t1_1) is int and type(t2_1) is int:
return (tuple, t1_1 + t2_1)
if type(t1_1) is int and type(t2_1) is tuple:
return (tuple, t1_1 + len(t2_1))
if type(t1_1) is tuple and type(t2_1) is int:
return (tuple, len(t1_1) + t2_1)
if type(t1_1) is tuple and type(t2_1) is tuple:
return (tuple, t1_1 + t2_1)
if t1_1 is None and type(t2_1) is tuple:
return (tuple, len(t2_1))
if t1_1 is None and type(t2_1) is int:
return (tuple, t2_1)
if type(t1_1) is int and t2_1 is None:
return (tuple, t1_1)
if type(t1_1) is tuple and t2_1 is None:
return (tuple, len(t1_1))
return Kl_Tuple
if IsList(t1) and IsList(t2):
return Kl_List
if IsList(t1) or IsList(t2):
return ('Not', (Kl_Int, Kl_IntUndefSize, Kl_Float, Kl_Short))
if IsStr(t1) and IsStr(t2):
return Kl_String
if ret[2][0] == '!PySequence_GetSlice' or ret[1][0] == '!PySequence_GetSlice':
return ('Not', (Kl_Int, Kl_IntUndefSize, Kl_Float, Kl_Short))
if t1 is None and t2 is not None and t2[0] == 'Not':
return t2
if t2 is None and t1 is not None and t1[0] == 'Not':
return t1
return None
if ret[0] in ('!PyNumber_Multiply', '!PyNumber_Divide', '!PyNumber_InPlaceDivide', \
'!PyNumber_Subtract', '!PyNumber_InPlaceSubtract', '!PyNumber_InPlaceMultiply'):
t1 = TypeExpr(ret[1])
t2 = None
if IsFloat(t1):
if t2 is None:
t2 = TypeExpr(ret[2])
if IsFloat(t2):
return Kl_Float
if t2 is None:
t2 = TypeExpr(ret[2])
if IsShort(t1) and IsShort(t2) and ret[0] in \
('!PyNumber_InPlaceMultiply', '!PyNumber_InPlaceSubtract', '!PyNumber_Subtract', '!PyNumber_Multiply'):
return Kl_Int
if ret[0] in ('!PyNumber_InPlaceSubtract', '!PyNumber_Subtract'):
if IsIntOnly(t1) and IsShort(t2) and IsSumShort(ret[1]):
return Kl_Int
if IsIntOnly(t2) and IsShort(t1) and IsSumShort(ret[2]):
return Kl_Int
if IsFloat(t1) and IsFloat(t2):
return Kl_Float
if IsInt(t1) and IsFloat(t2):
return Kl_Float
if IsIntUndefSize(t1) and IsFloat(t2):
return Kl_Float
if IsInt(t2) and IsFloat(t1):
return Kl_Float
if IsIntUndefSize(t2) and IsFloat(t1):
return Kl_Float
if IsIntOnly(t1) and IsShort(t2):
return Kl_IntUndefSize
if IsIntOnly(t2) and IsShort(t1):
return Kl_IntUndefSize
if IsIntOnly(t2) and IsIntOnly(t1):
return Kl_IntUndefSize
if IsIntUndefSize(t1) and IsInt(t2):
return Kl_IntUndefSize
if IsIntUndefSize(t2) and IsInt(t1):
return Kl_IntUndefSize
if IsIntUndefSize(t1) and IsIntUndefSize(t2):
return Kl_IntUndefSize
return None
if ret[0] == '!PyNumber_Multiply':
if IsTuple(t1) and IsIntUndefSize(t2):
return Kl_Tuple
if IsTuple(t2) and IsIntUndefSize(t1):
return Kl_Tuple
if IsList(t1) and IsIntUndefSize(t2):
return t1
if IsList(t2) and IsIntUndefSize(t1):
return t2
if IsTuple(t1) and IsInt(t2):
return Kl_Tuple
if IsTuple(t2) and IsInt(t1):
return Kl_Tuple
if IsList(t1) and IsInt(t2):
return t1
if IsList(t2) and IsInt(t1):
return t2
if IsFloat(t1) and IsFloat(t2):
return Kl_Float
if IsInt(t1) and IsFloat(t2):
return Kl_Float
if IsInt(t2) and IsFloat(t1):
return Kl_Float
if IsIntUndefSize(t2) and IsFloat(t1):
return Kl_Float
if IsIntUndefSize(t1) and IsFloat(t2):
return Kl_Float
if IsIntOnly(t1) and IsShort(t2):
return Kl_IntUndefSize
if IsIntOnly(t2) and IsShort(t1):
return Kl_IntUndefSize
if IsIntOnly(t2) and IsIntOnly(t1):
return Kl_IntUndefSize
if IsIntUndefSize(t1) and IsInt(t2):
return Kl_IntUndefSize
if IsIntUndefSize(t2) and IsInt(t1):
return Kl_IntUndefSize
if IsIntUndefSize(t1) and IsIntUndefSize(t2):
return Kl_IntUndefSize
if IsIntUndefSize(t1) and IsStr(t2):
return Kl_String
if IsIntUndefSize(t2) and IsStr(t1):
return Kl_String
if IsInt(t1) and IsStr(t2):
return Kl_String
if IsInt(t2) and IsStr(t1):
return Kl_String
if ret[0] == '!PyNumber_Divide':
if IsShort(t1) and IsShort(t2):
return Kl_Short
if IsShort(t1) and IsIntOnly(t2):
return Kl_Short
if IsIntOnly(t1) and IsIntOnly(t2):
return Kl_Int
if IsIntOnly(t1) and IsShort(t2):
return Kl_Int
if IsFloat(t1) and IsFloat(t2):
return Kl_Float
if IsInt(t1) and IsFloat(t2):
return Kl_Float
if IsInt(t2) and IsFloat(t1):
return Kl_Float
if IsIntUndefSize(t2) and IsFloat(t1):
return Kl_Float
if IsIntUndefSize(t1) and IsFloat(t2):
return Kl_Float
if IsIntUndefSize(t1) and IsInt(t2):
return Kl_IntUndefSize
if IsIntUndefSize(t2) and IsInt(t1):
return Kl_Int
if IsIntUndefSize(t1) and IsIntUndefSize(t2):
return Kl_IntUndefSize
if IsIntUndefSize(t1) and IsShort(t2):
return Kl_IntUndefSize
if IsIntUndefSize(t2) and IsShort(t1):
return Kl_IntUndefSize
if IsIntUndefSize(t1) and IsInt(t2):
return Kl_IntUndefSize
if IsIntUndefSize(t2) and IsInt(t1):
return Kl_IntUndefSize
if IsIntUndefSize(t1) and IsIntUndefSize(t2):
return Kl_IntUndefSize
if ret[0] == '!PyNumber_Negative':
t1 = TypeExpr(ret[1])
if IsInt(t1) or t1 == Kl_Long or IsFloat(t1):
return t1
if ret[0] in ('!PySequence_GetSlice', '!_PyEval_ApplySlice'):
t2 = TypeExpr(ret[1])
if IsList(t2) or IsTuple(t2) or IsStr(t2):
return t2
return ('Not', (Kl_Int, Kl_IntUndefSize, Kl_Float, Kl_Short))
# return None
if ret[0] == '!BOOLEAN' and IsBool(TypeExpr(ret[1])):
return Kl_Boolean
if ret[0] == '!IMPORT_NAME':
return (types.ModuleType, dotted_name_to_first_name(ret[1]))
if ret[0] == '!PyObject_RichCompare(':
t1 = TypeExpr(ret[1])
t2 = TypeExpr(ret[2])
if t1 == t2 and t1 in _Kl_Simples:
return Kl_Boolean
return None
def IsSumShort(it):
if it[0] not in ('!PyNumber_Subtract', '!PyNumber_InPlaceSubtract', '!PyNumber_Add', '!PyNumber_InPlaceAdd'):
return False
t1 = TypeExpr(it[1])
t2 = TypeExpr(it[2])
if IsShort(t1) and IsShort(t2):
return True
if IsIntOnly(t1) and IsShort(t2) and IsSumShort(it[1]):
return True
if IsIntOnly(t2) and IsShort(t1) and IsSumShort(it[2]):
return True
if IsIntOnly(t2) and IsIntOnly(t1) and IsSumShort(it[2]) and IsSumShort(it[1]):
return True
return False
import math
def attempt_calc_constant_math(t, ret, v1):
try:
return ('CONST', getattr(math, t)(*v1))
except:
return ret
def upgrade_op2(ret, nm = None):
v = []
if direct_call and current_co.can_be_codefunc():
if type(ret) is tuple and len(ret) == 4 and type(ret[0]) is str and \
ret[0] == '!PyObject_Call' and ret[3] == ('NULL',):
if TCmp(ret[1:-1], v, (('!MK_FUNK', '?', ('CONST', ())), \
('!BUILD_TUPLE', '?'))):
return call_calc_const(v[0], ('!BUILD_TUPLE', v[1]), ret)
elif 'MK_FUNK' in repr(ret):
if TCmp(ret[1:-1], v, (('!MK_FUNK', '?', ('CONST', ())), \
('CONST', '?'))):
return call_calc_const(v[0], ('CONST', v[1]), ret)
## pprint(('/////', ret))
elif TCmp(ret[1:-1], v, (('CALC_CONST', '?'),\
('!BUILD_TUPLE', '?'))) and \
v[0] in val_direct_code: ## and \
return call_calc_const(direct_code[v[0]], ('!BUILD_TUPLE', v[1]), ret)
elif TCmp(ret[1:-1], v, (('CALC_CONST', '?'),\
('CONST', '?'))) :
if v[0] in val_direct_code:
return call_calc_const(direct_code[v[0]], ('CONST', v[1]), ret)
t = None
if type(v[0]) is tuple and len(v[0]) == 2:
t = (Val3(v[0][0], 'ImportedM'), v[0][1])
else:
t = Val3(v[0], 'ImportedM')
if type(t) is tuple and len(t) == 2 and t[0] == 'math':
return attempt_calc_constant_math(t[1], ret, v[1]) #sqrt
v = []
if type(ret) is tuple and len(ret) == 4 and type(ret[0]) is str and \
ret[0] == '!PyObject_Call' and ret[3] == ('NULL',):
if TCmp(ret, v, ('!PyObject_Call', ('CALC_CONST', '?'),\
('!BUILD_TUPLE', '?'), ('NULL',))) and v[0] in calc_const_old_class :
if not Is3(v[0], 'HaveMetaClass') and v[0] not in calc_const_new_class: #have_metaclass(v[0][0]):
ret = ('!CLASS_CALC_CONST', v[0], ('!BUILD_TUPLE', v[1]))
elif TCmp(ret, v, ('!PyObject_Call', ('CALC_CONST', '?'),\
('CONST', '?'), ('NULL',))) and v[0] in calc_const_old_class:
if not Is3(v[0], 'HaveMetaClass') and v[0] not in calc_const_new_class: ## and not have_metaclass(v[0][0]):
ret = ('!CLASS_CALC_CONST', v[0], ('CONST', v[1]))
elif TCmp(ret, v, ('!PyObject_Call', ('CALC_CONST', '?'),\
('!BUILD_TUPLE', '?'), ('NULL',))) and v[0] in calc_const_new_class:
if v[0] not in calc_const_old_class:
ret = ('!CLASS_CALC_CONST_NEW', v[0], ('!BUILD_TUPLE', v[1]))
elif TCmp(ret, v, ('!PyObject_Call', ('CALC_CONST', '?'),\
('CONST', '?'), ('NULL',)))and v[0] in calc_const_new_class:
if v[0] not in calc_const_old_class:
ret = ('!CLASS_CALC_CONST_NEW', v[0], ('CONST', v[1]))
v = []
if type(ret) is tuple and len(ret) > 0 and type(ret[0]) is str and \
ret[0] == 'IMPORT_FROM_AS' and \
TCmp(ret, v, ('IMPORT_FROM_AS', '?', ('CONST', -1), ('CONST', '?'), '?')):
sreti = []
imp, consts_, stores = v
for reti in stores:
v = []
if type(reti) is tuple and len(reti) == 2 and \
reti[0] in ('STORE_NAME', 'STORE_GLOBAL') and \
reti[1] in all_calc_const:
reti = ('STORE_CALC_CONST', reti)
sreti.append(reti)
return ret[:4] + (tuple(sreti),)
v0 = []
if len(ret) == 3 and ret[0] == 'SEQ_ASSIGN':
sreti = []
for reti in ret[1]:
v = []
if type(reti) is tuple and len(reti) == 2 and \
reti[0] in ('STORE_NAME', 'STORE_GLOBAL') and \
reti[1] in all_calc_const:
calc_const_value[reti[1]] = ret[2]
reti = ('STORE_CALC_CONST', reti)
elif reti[0] == 'SET_VARS':
sretii = []
for retii in reti[1]:
if type(retii) is tuple and len(retii) == 2 and \
retii[0] in ('STORE_NAME', 'STORE_GLOBAL') and \
retii[1] in all_calc_const:
retii = ('STORE_CALC_CONST', retii)
sretii.append(retii)
reti = ('SET_VARS', tuple(sretii))
sreti.append(reti)
return (ret[0], tuple(sreti), ret[2])
elif len(ret) == 3 and ret[0] == 'SET_EXPRS_TO_VARS':
sretii = []
for retii in ret[1]:
if type(retii) is tuple and len(retii) == 2 and \
retii[0] in ('STORE_NAME', 'STORE_GLOBAL') and \
retii[1] in all_calc_const:
retii = ('STORE_CALC_CONST', retii)
sretii.append(retii)
return ('SET_EXPRS_TO_VARS', tuple(sretii), ret[2])
elif type(ret) is tuple and len(ret) == 3 and \
ret[0] == 'STORE' and len(ret[1]) == 1 and len(ret[1][0]) == 2 and \
ret[1][0][0] in ('STORE_NAME', 'STORE_GLOBAL') and \
ret[1][0][1] in all_calc_const and\
TCmp(ret, v0, ('STORE', (('?', '?'),), ('?',))):
v = [(v0[1], '', all_calc_const[v0[1]]), v0[2]]
calc_const_value[v[0][0]] = v[1]
return ('STORE', (('STORE_CALC_CONST', ret[1][0]),), ret[2])
elif type(ret) is tuple and len(ret) == 2 and \
ret[0] in ('!LOAD_NAME', '!LOAD_GLOBAL', '!PyDict_GetItem(glob,') and \
ret[1] in all_calc_const:
ret = calc_const_to(ret[1])
v = []
ret = repl_collected_module_attr(ret)
ret = repl(ret)
return ret
def class_and_body_meth_by_meth(nm_meth):
islis = IterMethod(nm_meth, None)
if len(islis) == 0:
return {}
di = dict([(a,c) for a,b,c in islis])
while True:
l = len(di)
for k in di.keys():
for a1, b1, c1 in Iter3(None, 'Derived', ('!CALC_CONST', k)):
if a1 not in di:
di[a1] = di[k]
if len(di) == l:
break
return di
def tree_pass__(a, upgrade_op, up, nm):
if type(a) is tuple:
if len(a) > 0 and type(a[0]) is str and a[0] == 'CONST':
return a
r = tuple([tree_pass__(i, upgrade_op,a, nm) for i in a])
notchanged = len(r) == len(a) and all([r[i] is a[i] for i,x in enumerate(r)])
if notchanged:
r = a
r = upgrade_op(r,nm)
return r
if type(a) is list:
assert len(a) > 0
r = [tree_pass__(i, upgrade_op, a, nm) for i in a]
notchanged = len(r) == len(a) and all([r[i] is a[i] for i,x in enumerate(r)])
if notchanged:
r = a
assert len(r) > 0
return r
return a
to_call_1 = {'!PyObject_Hash':('__hash__',), '!PyObject_Str':('__str__',), \
'!PyObject_Repr':('__repr__',), '!PyNumber_Negative':('__neg__',),\
'!PyObject_GetIter':('__iter__',), '!PyObject_Length':('__len__',)}
to_call_2 = {'!PyNumber_Subtract':('__sub__',), '!PyNumber_InPlaceSubtract':('__isub__', '__sub__',),\
'!PyNumber_Add':('__add__',), '!PyNumber_InPlaceAdd':('__iadd__', '__add__',),\
'!PyNumber_Divide':('__div__',), '!PyNumber_InPlaceDivide':('__idiv__', '__div__',),\
'!PyNumber_And':('__and__',), '!PyNumber_InPlaceAnd':('__iand__', '__and__',),\
'!PyNumber_Or':('__or__',), '!PyNumber_InPlaceOr':('__ior__', '__or__',),\
'!PyNumber_Multiply':('__mul__',), '!PyNumber_InPlaceMultiply':('__imul__', '__mul__',)}
def upgrade_repl_if_type_direct_call(ret, nm = None):
v = []
if type(ret) is tuple and len(ret) > 0 and type(ret[0]) is str:
if ret[0] == '!COND_METH_EXPR':
return ret
if len(ret) == 3 and ret[0] in to_call_2:
v = ret
t1 = TypeExpr(v[1])
t2 = TypeExpr(v[2])
_self1 = v[1]
if t1 is None and t2 is None :
nms = to_call_2[v[0]]
for nm_meth in nms:
di = class_and_body_meth_by_meth(nm_meth)
if len(di) == 0:
continue
li = []
for t, codemethnm in di.iteritems():
classmeth = Is3(t, ('ClassMethod', nm_meth))
staticmeth = Is3(t, ('StaticMethod', nm_meth))
isoldclass = t in calc_const_old_class
isnewclass = t in calc_const_new_class
if classmeth or staticmeth:
continue
if ((isoldclass and not isnewclass) or (isnewclass and not isoldclass)):
pass
else:
continue
assert v[1][0] != 'PY_TYPE'
if isoldclass:
_self2 = ('PY_TYPE', T_OLD_CL_INST, t, v[1], None)
if is_pypy:
continue
else:
_self2 = ('PY_TYPE', T_NEW_CL_INST, t, v[1], None)
tupl = ('!BUILD_TUPLE', (_self2, replace_subexpr(v[2], v[1], _self2)))
ret2 = call_calc_const(codemethnm, tupl, ret)
if ret2 == ret:
continue
li.append((_self2[1:3], ret2))
if len(li) > 0:
return ('!COND_METH_EXPR', _self1, ret, tuple(li))
elif len(ret) == 2 and ret[0] in to_call_1:
v = ret
t1 = TypeExpr(v[1])
if t1 is None :
nms = to_call_1[v[0]]
for nm_meth in nms:
di = class_and_body_meth_by_meth(nm_meth)
if len(di) == 0:
continue
li = []
for t, codemethnm in di.iteritems():
classmeth = Is3(t, ('ClassMethod', nm_meth))
staticmeth = Is3(t, ('StaticMethod', nm_meth))
isoldclass = t in calc_const_old_class
isnewclass = t in calc_const_new_class
_self1 = v[1]
if classmeth or staticmeth:
continue
if ((isoldclass and not isnewclass) or (isnewclass and not isoldclass)):
pass
else:
continue
assert v[1][0] != 'PY_TYPE'
if isoldclass:
_self2 = ('PY_TYPE', T_OLD_CL_INST, t, v[1], None)
if is_pypy:
continue
else:
_self2 = ('PY_TYPE', T_NEW_CL_INST, t, v[1], None)
tupl = ('!BUILD_TUPLE', (_self2, ))
ret2 = call_calc_const(codemethnm, tupl, ret)
if ret2 == ret:
continue
li.append((_self2[1:3], ret2))
if len(li) > 0:
return ('!COND_METH_EXPR', _self1, ret, tuple(li))
elif ret[0] == '!PyObject_Call' and ret[1][0] == '!PyObject_GetAttr':
if TCmp(ret, v, \
('!PyObject_Call',
('!PyObject_GetAttr', '?', ('CONST', '?')), ('!BUILD_TUPLE', '?'), ('NULL',)))\
and TypeExpr(v[0]) is None:
di = class_and_body_meth_by_meth(v[1])
li = []
for t, codemethnm in di.iteritems():
classmeth = Is3(t, ('ClassMethod', v[1]))
staticmeth = Is3(t, ('StaticMethod', v[1]))
isoldclass = t in calc_const_old_class
isnewclass = t in calc_const_new_class
_self1 = v[0]
if classmeth or staticmeth:
continue
if ((isoldclass and not isnewclass) or (isnewclass and not isoldclass)):
pass
else:
continue
assert _self1[0] != 'PY_TYPE'
if isoldclass:
_self2 = ('PY_TYPE', T_OLD_CL_INST, t, _self1, None)
if is_pypy:
continue
else:
_self2 = ('PY_TYPE', T_NEW_CL_INST, t, _self1, None)
tupl = ('!BUILD_TUPLE', (_self2,) + replace_subexpr(v[2], _self1, _self2))
ret2 = call_calc_const(codemethnm, tupl, ret)
if ret2 == ret:
continue
li.append((_self2[1:3], ret2))
if len(li) == 0 and v[1] == 'startswith' and len(v[2]) == 1 and IsStr(TypeExpr(v[2][0])):
li.append(((str, None), ('!_PyString_StartSwith', ('PY_TYPE', str, None, v[0], None), v[2][0])))
if len(li) == 0 and v[1] == 'startswith' and len(v[2]) == 1 and TypeExpr(v[2][0]) is None:
li.append(((str, None), ('!COND_EXPR', ('!BOOLEAN', ('!_EQ_', ('!PyObject_Type', v[2][0]), ('!LOAD_BUILTIN', 'str'))),
('!_PyString_StartSwith', ('PY_TYPE', str, None, v[0], None), v[2][0]), ret)))
## if len(li) == 0 and v[1] == 'startswith':
## print '///', ret
if len(li) > 0:
ret = ('!COND_METH_EXPR', v[0], ret, tuple(li))
elif TCmp(ret, v, \
('!PyObject_Call',
('!PyObject_GetAttr', '?', ('CONST', '?')), ('CONST', '?'), ('NULL',)))\
and TypeExpr(v[0]) is None:
di = class_and_body_meth_by_meth(v[1])
li = []
for t, codemethnm in di.iteritems():
classmeth = Is3(t, ('ClassMethod', v[1]))
staticmeth = Is3(t, ('StaticMethod', v[1]))
isoldclass = t in calc_const_old_class
isnewclass = t in calc_const_new_class
_self1 = v[0]
if classmeth or staticmeth:
continue
if ((isoldclass and not isnewclass) or (isnewclass and not isoldclass)):
pass
else:
continue
v2 = tuple([('CONST', x) for x in v[2]])
assert _self1[0] != 'PY_TYPE'
if isoldclass:
_self2 = ('PY_TYPE', T_OLD_CL_INST, t, _self1, None)
if is_pypy:
continue
else:
_self2 = ('PY_TYPE', T_NEW_CL_INST, t, _self1, None)
tupl = ('!BUILD_TUPLE', (_self2,) + replace_subexpr(v2, _self1, _self2))
ret2 = call_calc_const(codemethnm, tupl, ret)
if ret2 == ret:
continue
li.append((_self2[1:3], ret2))
if len(li) == 0 and v[1] == 'startswith' and type(v[2]) is tuple and len(v[2]) == 1 and type(v[2][0]) is str:
li.append(((str, None), ('!_PyString_StartSwith', ('PY_TYPE', str, None, v[0], None), ('CONST', v[2][0]))))
if len(li) == 0 and v[1] == 'endswith' and type(v[2]) is tuple and len(v[2]) == 1 and type(v[2][0]) is str:
li.append(((str, None), ('!_PyString_EndSwith', ('PY_TYPE', str, None, v[0], None), ('CONST', v[2][0]))))
if len(li) > 0:
ret = ('!COND_METH_EXPR', v[0], ret, tuple(li))
return ret
def generate_logical_cond_meth_expr(it, logic):
o = Out()
ref_self = Expr1(it[1], o)
PushAcc([it[1]], [ref_self])
v = []
if TCmp(it[2], v, ('!PyObject_Call', \
('!PyObject_GetAttr', '?', ('CONST', '?')), ('!BUILD_TUPLE', '?'), ('NULL',))):
exprs = [x for x in v[2]]
refs = [Expr1(x, o) for x in exprs]
PushAcc(exprs, refs)
for i in range(len(it[3])):
_self2, it2 = it[3][i]
t2, nmclass = _self2
if type(t2) is str:
isnewclass = t2 == T_NEW_CL_INST
isoldclass = t2 == T_OLD_CL_INST
if isnewclass:
o.Raw('if (((PyObject *)Py_TYPE(',ref_self,')) == ', ('CALC_CONST', nmclass), ') {')
elif isoldclass:
o.Raw('if (PyInstance_Check(', ref_self,') && ((PyInstanceObject *)', ref_self,\
')->in_class == (PyClassObject*)', ('CALC_CONST', nmclass), ') {')
else:
Fatal('Not instance', _self2)
elif t2 in type_to_check_t: #is str:
o.Raw('if (',type_to_check_t[t2],'(', ref_self,')) {')
else:
Fatal('Strange COND_METH', _self2)
o2, logic2 = generate_logical_expr(it2, logic)
o.extend(o2)
assert logic2 == logic
o.Raw('} else')
o.append('{')
it_ = ('!PyObject_Call', ('!PyObject_GetAttr', ref_self, ('CONST', v[1])), ('!BUILD_TUPLE', tuple(refs)), ('NULL',))
ref1 = Expr1(it_, o)
o, logic2 = ToTrue(o,logic,ref1, it_)
assert logic2 == logic
o.append('}')
PopAcc(o)
PopAcc(o)
return o, logic
if TCmp(it[2], v, ('!PyObject_Call', \
('!PyObject_GetAttr', '?', ('CONST', '?')), ('CONST', '?'), ('NULL',))):
exprs = [('CONST', x) for x in v[2]]
refs = [Expr1(x, o) for x in exprs]
PushAcc(exprs, refs)
for i in range(len(it[3])):
_self2, it2 = it[3][i]
t2, nmclass = _self2
if type(t2) is str:
isnewclass = t2 == T_NEW_CL_INST
isoldclass = t2 == T_OLD_CL_INST
if isnewclass:
o.Raw('if (((PyObject *)Py_TYPE(',ref_self,')) == ', ('CALC_CONST', nmclass), ') {')
elif isoldclass:
o.Raw('if (PyInstance_Check(', ref_self,') && ((PyInstanceObject *)', ref_self,\
')->in_class == (PyClassObject*)', ('CALC_CONST', nmclass), ') {')
else:
Fatal('Not instance', _self2)
elif t2 in type_to_check_t: #is str:
o.Raw('if (',type_to_check_t[t2],'(', ref_self,')) {')
else:
Fatal('Strange COND_METH', t2, it[2])
o2, logic2 = generate_logical_expr(it2, logic)
o.extend(o2)
assert logic2 == logic
o.Raw('} else')
o.append('{')
it_ = ('!PyObject_Call', ('!PyObject_GetAttr', ref_self, ('CONST', v[1])), \
('CONST', v[2]), ('NULL',))
ref1 = Expr1(it_, o)
o, logic2 = ToTrue(o,logic,ref1, it_)
assert logic2 == logic
o.append('}')
PopAcc(o)
PopAcc(o)
return o, logic
if it[2][0] in to_call_2 and TCmp(it[2], v, ('?', '?', '?')): # and v[0] in to_call_2:
exprs = [x for x in v[2:]]
refs = [Expr1(x, o) if x[0] != 'FAST' and not current_co.IsCVar(x) else x for x in exprs]
PushAcc(exprs, refs)
for i in range(len(it[3])):
_self2, it2 = it[3][i]
t2, nmclass = _self2
if type(t2) is str:
isnewclass = t2 == T_NEW_CL_INST
isoldclass = t2 == T_OLD_CL_INST
if isnewclass:
o.Raw('if (((PyObject *)Py_TYPE(',ref_self,')) == ', ('CALC_CONST', nmclass), ') {')
elif isoldclass:
o.Raw('if (PyInstance_Check(', ref_self,') && ((PyInstanceObject *)', ref_self,\
')->in_class == (PyClassObject*)', ('CALC_CONST', nmclass), ') {')
else:
Fatal('Not instance', _self2)
elif t2 in type_to_check_t: #is str:
o.Raw('if (',type_to_check_t[t2],'(', ref_self,')) {')
else:
Fatal('Strange COND_METH', _self2)
o2, logic2 = generate_logical_expr(it2, logic)
o.extend(o2)
assert logic2 == logic
o.Raw('} else')
o.append('{')
it_ = (v[0], ref_self, refs[0])
ref1 = Expr1(it_, o)
o, logic2 = ToTrue(o,logic,ref1, it_)
assert logic2 == logic
o.append('}')
PopAcc(o)
PopAcc(o)
return o, logic
if TCmp(it[2], v, ('?', '?')) and v[0] in to_call_1:
for i in range(len(it[3])):
_self2, it2 = it[3][i]
t2, nmclass = _self2
if type(t2) is str:
isnewclass = t2 == T_NEW_CL_INST
isoldclass = t2 == T_OLD_CL_INST
if isnewclass:
o.Raw('if (((PyObject *)Py_TYPE(',ref_self,')) == ', ('CALC_CONST', nmclass), ') {')
elif isoldclass:
o.Raw('if (PyInstance_Check(', ref_self,') && ((PyInstanceObject *)', ref_self,\
')->in_class == (PyClassObject*)', ('CALC_CONST', nmclass), ') {')
else:
Fatal('Not instance', _self2)
elif t2 in type_to_check_t: #is str:
o.Raw('if (',type_to_check_t[t2],'(', ref_self,')) {')
else:
Fatal('Strange COND_METH', _self2)
o2, logic2 = generate_logical_expr(it2, logic)
o.extend(o2)
assert logic2 == logic
o.Raw('} else')
o.append('{')
it_ = (v[0], ref_self)
ref1 = Expr1(it_, o)
o, logic2 = ToTrue(o,logic,ref1, it_)
assert logic2 == logic
o.append('}')
PopAcc(o)
return o, logic
if it[2][0] in ('!OR_JUMP', '!AND_JUMP', '!OR_JUMPED_STACKED', '!AND_JUMPED_STACKED'):
for i in range(len(it[3])):
_self2, it2 = it[3][i]
t2, nmclass = _self2
if type(t2) is str:
isnewclass = t2 == T_NEW_CL_INST
isoldclass = t2 == T_OLD_CL_INST
if isnewclass:
o.Raw('if (((PyObject *)Py_TYPE(',ref_self,')) == ', ('CALC_CONST', nmclass), ') {')
elif isoldclass:
o.Raw('if (PyInstance_Check(', ref_self,') && ((PyInstanceObject *)', ref_self,\
')->in_class == (PyClassObject*)', ('CALC_CONST', nmclass), ') {')
else:
Fatal('Not instance', _self2)
elif t2 in type_to_check_t: #is str:
o.Raw('if (',type_to_check_t[t2],'(', ref_self,')) {')
else:
Fatal('Strange COND_METH', _self2)
o2, logic2 = generate_logical_expr(it2, logic)
o.extend(o2)
assert logic2 == logic
o.Raw('} else')
o.append('{')
## it_ = (v[0], ref_self)
ref1 = Expr1(it[2], o)
o, logic2 = ToTrue(o,logic,ref1, it[2])
assert logic2 == logic
o.append('}')
PopAcc(o)
return o, logic
print it
assert False
def generate_cond_meth_expr_new(it, o, forcenewg, no_return):
ret = New(None, forcenewg)
ref_self = Expr1(it[1], o)
PushAcc([it[1]], [ref_self])
v = []
if TCmp(it[2], v, ('!PyObject_Call', \
('!PyObject_GetAttr', '?', ('CONST', '?')), ('!BUILD_TUPLE', '?'), ('NULL',))):
## pprint(it)
exprs = [x for x in v[2]]
refs = v[2]
li = gen_for_all_known(it, ret, ref_self)
old_o = o
o = Out()
ret2 = GenExpr(('!PyObject_Call', ('!PyObject_GetAttr', ref_self, ('CONST', v[1])), \
('!BUILD_TUPLE', tuple(refs)), ('NULL',)), o, ret)
assert ret2 == ret
## pprint(o)
## pprint(old_o)
join_cond_meth_call(o, li, old_o, no_return, ret)
PopAcc(old_o)
return ret
if TCmp(it[2], v, ('!PyObject_Call', \
('!PyObject_GetAttr', '?', ('CONST', '?')), ('CONST', '?'), ('NULL',))):
exprs = [('CONST', x) for x in v[2]]
refs = exprs
li = gen_for_all_known(it, ret, ref_self)
old_o = o
o = Out()
ret2 = GenExpr(('!PyObject_Call', ('!PyObject_GetAttr', ref_self, ('CONST', v[1])), \
('CONST', v[2]), ('NULL',)), o, ret)
assert ret2 == ret or ret2 == ('CONST', None) ## or ret2[0] == 'CONST'
join_cond_meth_call(o, li, old_o, no_return, ret)
PopAcc(old_o)
return ret
if it[2][0] in to_call_2 and TCmp(it[2], v, ('?', '?', '?')):
exprs = [x for x in v[2:]]
refs = [Expr1(x, o) if x[0] != 'FAST' and not current_co.IsCVar(x) else x for x in exprs]
PushAcc(exprs, refs)
li = gen_for_all_known(it, ret, ref_self)
old_o = o
o = Out()
ret2 = GenExpr((v[0], ref_self, refs[0]), o, ret)
assert ret2 == ret or ret2 == ('CONST', None)
join_cond_meth_call(o, li, old_o, no_return, ret)
PopAcc(old_o)
PopAcc(old_o)
return ret
if TCmp(it[2], v, ('?', '?')) and v[0] in to_call_1:
li = gen_for_all_known(it, ret, ref_self)
old_o = o
o = Out()
ret2 = GenExpr((v[0], ref_self), o, ret)
assert ret2 == ret or ret2 == ('CONST', None)
join_cond_meth_call(o, li, old_o, no_return, ret)
PopAcc(old_o)
return ret
print it
assert False
def join_cond_meth_call(o, li, old_o, no_return, ret):
if no_return:
oo = Out()
oo.Cls(ret)
else:
oo = []
for k,v in li:
v.extend(oo)
## optimize(v)
o.extend(oo)
## optimize(o)
## l = 0
## ## pprint(li)
## while len([1 for k,v in li if v[:l] != o[:l]]) == 0 and l < len(o):
## l += 1
## l -= 1
## if l > 0:
## old_o.extend(o[:l])
## o[:] = o[l:]
## for k,v in li:
## v[:] = v[l:]
## ## assert False
i = 0
for k, v in li:
if i == 0:
old_o.append(k)
else:
old_o.append('} else ' + k)
old_o.extend(v)
i += 1
old_o.append('} else {')
old_o.extend(o)
old_o.append('}')
def gen_for_all_known(it, ret, ref_self):
li = []
for i in range(len(it[3])):
o = Out()
_self2, it2 = it[3][i]
t2, nmclass = _self2
if type(t2) is str:
isnewclass = t2 == T_NEW_CL_INST
isoldclass = t2 == T_OLD_CL_INST
if isnewclass:
o.Raw('if (((PyObject *)Py_TYPE(',ref_self,')) == ', ('CALC_CONST', nmclass), ') {')
elif isoldclass:
o.Raw('if (PyInstance_Check(', ref_self,') && ((PyInstanceObject *)', ref_self,\
')->in_class == (PyClassObject*)', ('CALC_CONST', nmclass), ') {')
else:
Fatal('Not instance', _self2)
elif t2 in type_to_check:
o.Raw('if (', type_to_check[t2], '(', ref_self,')) {')
elif t2 in type_to_check_t:
o.Raw('if (', type_to_check_t[t2], '(', ref_self,')) {')
else:
Fatal('Strange COND_METH', _self2, t2)
if_ = o[0]
assert len(o) == 1
del o[0]
assert len(o) == 0
ret2 = GenExpr(it2, o, ret)
if ret2[0] == 'CONST':
o.INCREF(ret2)
o.Raw(ret, ' = ', ret2, ';')
assert ret2 == ret or ret2[0] == 'CONST'
li.append((if_, o))
return li
## def generate_cond_meth_expr_new_old(it, o, forcenewg, no_return):
## if no_return:
## ret = ('CONST', None)
## else:
## ret = New(None, forcenewg)
## ref_self = Expr1(it[1], o)
## PushAcc([it[1]], [ref_self])
## v = []
## if TCmp(it[2], v, ('!PyObject_Call', \
## ('!PyObject_GetAttr', '?', ('CONST', '?')), ('!BUILD_TUPLE', '?'), ('NULL',))):
## exprs = [x for x in v[2]]
## refs = v[2] #[Expr1(x, o) for x in exprs]
## # PushAcc(exprs, refs)
## for i in range(len(it[3])):
## _self2, it2 = it[3][i]
## t2, nmclass = _self2
## if type(t2) is str:
## isnewclass = t2 == T_NEW_CL_INST
## isoldclass = t2 == T_OLD_CL_INST
## if isnewclass:
## o.Raw('if (((PyObject *)Py_TYPE(',ref_self,')) == ', ('CALC_CONST', nmclass), ') {')
## elif isoldclass:
## o.Raw('if (PyInstance_Check(', ref_self,') && ((PyInstanceObject *)', ref_self,\
## ')->in_class == (PyClassObject*)', ('CALC_CONST', nmclass), ') {')
## else:
## Fatal('Not instance', _self2)
## elif t2 in type_to_check:
## o.Raw('if (', type_to_check[t2], '(', ref_self,')) {')
## elif t2 in type_to_check_t:
## o.Raw('if (', type_to_check_t[t2], '(', ref_self,')) {')
## else:
## Fatal('Strange COND_METH', _self2)
## ret2 = GenExpr(it2, o, ret)
## ## pprint(('ooo', it2, o[leno-1:]))
## ## assert ret2 == ret or ret2 == ('CONST', None)
## if ret2[0] == 'CONST':
## o.INCREF(ret2)
## o.Raw(ret, ' = ', ret2, ';')
## o.Raw('} else')
## o.append('{')
## ret2 = GenExpr(('!PyObject_Call', ('!PyObject_GetAttr', ref_self, ('CONST', v[1])), ('!BUILD_TUPLE', tuple(refs)), ('NULL',)), o, ret)
## assert ret2 == ret
## o.append('}')
## # PopAcc(o)
## PopAcc(o)
## return ret
## if TCmp(it[2], v, ('!PyObject_Call', \
## ('!PyObject_GetAttr', '?', ('CONST', '?')), ('CONST', '?'), ('NULL',))):
## exprs = [('CONST', x) for x in v[2]]
## refs = exprs #v[2] #[Expr1(x, o) for x in exprs]
## # PushAcc(exprs, refs)
## for i in range(len(it[3])):
## _self2, it2 = it[3][i]
## t2, nmclass = _self2
## if type(t2) is str:
## isnewclass = t2 == T_NEW_CL_INST
## isoldclass = t2 == T_OLD_CL_INST
## if isnewclass:
## o.Raw('if (((PyObject *)Py_TYPE(',ref_self,')) == ', ('CALC_CONST', nmclass), ') {')
## elif isoldclass:
## o.Raw('if (PyInstance_Check(', ref_self,') && ((PyInstanceObject *)', ref_self,\
## ')->in_class == (PyClassObject*)', ('CALC_CONST', nmclass), ') {')
## else:
## Fatal('Not instance', _self2)
## elif t2 in type_to_check:
## o.Raw('if (', type_to_check[t2], '(', ref_self,')) {')
## elif t2 in type_to_check_t:
## o.Raw('if (', type_to_check_t[t2], '(', ref_self,')) {')
## else:
## pprint(it)
## Fatal('Strange COND_METH', _self2)
## ## leno = len(o)
## ret2 = GenExpr(it2, o, ret)
## if ret2[0] == 'CONST':
## o.INCREF(ret2)
## o.Raw(ret, ' = ', ret2, ';')
## ## pprint(('ooo', it2, o[leno-1:], it))
## ## print ret2, ret
## assert ret2 == ret or ret2[0] == 'CONST'
## o.Raw('} else')
## o.append('{')
## ret2 = GenExpr(('!PyObject_Call', ('!PyObject_GetAttr', ref_self, ('CONST', v[1])), \
## ('CONST', v[2]), ('NULL',)), o, ret)
## assert ret2 == ret or ret2 == ('CONST', None) ## or ret2[0] == 'CONST'
## o.append('}')
## # PopAcc(o)
## PopAcc(o)
## return ret
## if it[2][0] in to_call_2 and TCmp(it[2], v, ('?', '?', '?')): # and v[0] in to_call_2:
## exprs = [x for x in v[2:]]
## refs = [Expr1(x, o) if x[0] != 'FAST' and not current_co.IsCVar(x) else x for x in exprs]
## PushAcc(exprs, refs)
## for i in range(len(it[3])):
## _self2, it2 = it[3][i]
## t2, nmclass = _self2
## if type(t2) is str:
## isnewclass = t2 == T_NEW_CL_INST
## isoldclass = t2 == T_OLD_CL_INST
## if isnewclass:
## o.Raw('if (((PyObject *)Py_TYPE(',ref_self,')) == ', ('CALC_CONST', nmclass), ') {')
## elif isoldclass:
## o.Raw('if (PyInstance_Check(', ref_self,') && ((PyInstanceObject *)', ref_self,\
## ')->in_class == (PyClassObject*)', ('CALC_CONST', nmclass), ') {')
## else:
## Fatal('Not instance', _self2)
## elif t2 in type_to_check:
## o.Raw('if (', type_to_check[t2], '(', ref_self,')) {')
## elif t2 in type_to_check_t:
## o.Raw('if (', type_to_check_t[t2], '(', ref_self,')) {')
## else:
## Fatal('Strange COND_METH', _self2)
## ret2 = GenExpr(it2, o, ret)
## assert ret2 == ret or ret2 == ('CONST', None)
## o.Raw('} else')
## o.append('{')
## ret2 = GenExpr((v[0], ref_self, refs[0]), o, ret)
## assert ret2 == ret or ret2 == ('CONST', None)
## o.append('}')
## PopAcc(o)
## PopAcc(o)
## return ret
## if TCmp(it[2], v, ('?', '?')) and v[0] in to_call_1:
## for i in range(len(it[3])):
## _self2, it2 = it[3][i]
## t2, nmclass = _self2
## if type(t2) is str:
## isnewclass = t2 == T_NEW_CL_INST
## isoldclass = t2 == T_OLD_CL_INST
## if isnewclass:
## o.Raw('if (((PyObject *)Py_TYPE(',ref_self,')) == ', ('CALC_CONST', nmclass), ') {')
## elif isoldclass:
## o.Raw('if (PyInstance_Check(', ref_self,') && ((PyInstanceObject *)', ref_self,\
## ')->in_class == (PyClassObject*)', ('CALC_CONST', nmclass), ') {')
## else:
## Fatal('Not instance', _self2)
## elif t2 in type_to_check:
## o.Raw('if (', type_to_check[t2], '(', ref_self,')) {')
## elif t2 in type_to_check_t:
## o.Raw('if (', type_to_check_t[t2], '(', ref_self,')) {')
## else:
## Fatal('Strange COND_METH', _self2)
## ret2 = GenExpr(it2, o, ret)
## assert ret2 == ret or ret2 == ('CONST', None)
## o.Raw('} else')
## o.append('{')
## ret2 = GenExpr((v[0], ref_self), o, ret)
## assert ret2 == ret or ret2 == ('CONST', None)
## o.append('}')
## PopAcc(o)
## return ret
## print it
## assert False
def upgrade_repl(ret, nm = None):
## v = []
ret = repl_collected_module_attr(ret)
ret = repl(ret)
return ret
def collect_type_return(ret, nm):
global type_def
## v = []
if type(ret) is tuple and len(ret) == 2 and type(ret[0]) is str and ret[0] == 'RETURN_VALUE':
if nm not in type_def:
type_def[nm] = {}
type_def[nm][TypeExpr(ret[1])] = True
return ret
def attempt_module_import_1(nm):
try:
if nm == filename[:-3]:
return None
this = __import__(nm)
d = this.__dict__
return this, d
except:
Debug('Module %s import unsuccessful1' % nm)
return None
def old_class_1(v):
try:
return (T_OLD_CL_INST, v.__class__.__name__)
except:
pass
return None
def collect_module_type_attr(nm, acc = []):
d = None
if type(nm) is types.ModuleType:
this = nm
d = this.__dict__
elif nm in sys.modules:
this = sys.modules[nm]
d = this.__dict__
else:
ret_ret = attempt_module_import_1(nm)
if ret_ret is None:
return
this, d = ret_ret
if type(this) is types.ModuleType and this in acc:
return
acc.append(this)
for k in d.keys():
v = getattr(this, k)
if type(v) is types.ModuleType and v == this:
continue
t = type(v)
if t is types.ModuleType:
collect_module_type_attr(v, acc)
if t is types.InstanceType:
t2 = old_class_1(v)
if t2 is not None:
t = t2
else:
if type(t) != type:
t = (T_NEW_CL_INST, v.__class__.__name__)
else:
t = (t, None)
if k not in self_attr_type:
pass
else:
self_attr_type[k][t] = True
def collect_set_attr(ret, nm):
global self_attr_type
v = []
if len(ret) > 0 and type(ret[0]) is str and ret[0] == 'STORE':
if nm != 'Init_filename':
if TCmp(ret, v, ('STORE', (('STORE_NAME', '?'),), ('?',))):
if v[0] not in self_attr_type:
self_attr_type[v[0]] = {}
self_attr_type[v[0]][TypeExpr(v[1])] = True
if TCmp(ret, v, ('STORE', (('PyObject_SetAttr', '?', ('CONST', '?')),), ('?',))):
if v[1] not in self_attr_type:
self_attr_type[v[1]] = {}
self_attr_type[v[1]][TypeExpr(v[2])] = True
elif TCmp(ret, v, ('STORE', (('SET_VARS', '?'),), ( '?',))):
if len(v[1]) > 0 and (v[1][0] in tags_one_step_expr or v[1][0][0] == '!'):
for set2 in v[0]:
v2 = []
if TCmp(set2, v2, ('PyObject_SetAttr', '?', ('CONST', '?'))):
if v2[1] not in self_attr_type:
self_attr_type[v2[1]] = {}
self_attr_type[v2[1]][None] = True
else:
Fatal('Unhandled SetAttr in SET_VARS', ret)
elif TCmp(ret, v, ('STORE', '?', '?')):
[ collect_module_type_attr (expr[1]) for expr in v[1] if expr[0] == '!IMPORT_NAME']
if len(v[0]) == 1 and (type(v[0][0][0]) is int or v[0][0][0][0:6] == 'STORE_'):
pass
elif len(v[0]) == 1 and v[0][0][0] == 'PyObject_SetItem':
pass
elif len(v[0]) == 1 and v[0][0][0] == '?PyObject_SetAttr':
pass ##Debug('Variable arg PyObject_SetAttr', ret)
elif len(v[0]) == 1 and v[0][0][0] == 'PyObject_SetAttr':
pass ##Debug('Variable arg PyObject_SetAttr', ret)
elif len(v[0]) == 1 and v[0][0][0] == 'UNPACK_SEQ_AND_STORE' and v[0][0][1] == 0:
for set2 in v[0][0][2]:
v2 = []
if TCmp(set2, v2, ('PyObject_SetAttr', '?', ('CONST', '?'))):
if v2[1] not in self_attr_type:
self_attr_type[v2[1]] = {}
self_attr_type[v2[1]][None] = True
else:
Fatal('Unhandled STORE', ret)
return ret
def collect_default_args(ret, nm):
global default_args
if type(ret) is tuple and len(ret) >= 3:
if ret[0] == '!MK_FUNK':
default_args[ret[1]] = ret[2]
return ret
global_type = {}
detected_global_type = {}
def collect_set_global(ret, nm):
global global_type
v = []
if len(ret) > 0 and type(ret[0]) is str and ret[0] == 'STORE':
if nm == 'Init_filename' and TCmp(ret, v, ('STORE', (('STORE_NAME', '?'),), ('?',))):
if v[0] not in global_type:
global_type[v[0]] = {}
global_type[v[0]][TypeExpr(v[1])] = v[1]
if TypeExpr(v[1]) is None:
Debug('Not detected type %s for %s' % (v[0], v[1]))
return ret
v = []
if nm != 'Init_filename' and TCmp(ret, v, ('STORE', (('STORE_NAME', '?'),), ('?',))):
return ret
v = []
if TCmp(ret, v, ('STORE', (('STORE_GLOBAL', '?'),), ('?',))):
if v[0] not in global_type:
global_type[v[0]] = {}
global_type[v[0]][TypeExpr(v[1])] = v[1]
if TypeExpr(v[1]) is None:
Debug('Not detected type %s for %s' % (v[0], v[1]))
return ret
if TCmp(ret, v, ('STORE', (('STORE_FAST', '?'),), ('?',))):
return ret
v = []
if TCmp(ret, v, ('STORE', (('SET_VARS', '?'),), ('?',))):
t = TypeExpr(v[1])
for i, s in enumerate(v[0]):
if s[0] == 'STORE_GLOBAL':
if s[1] not in global_type:
global_type[s[1]] = {}
if IsTuple(t) and t[1] is not None and i < len(t[1]):
global_type[s[1]][t[1][i]] = True
if t[1][i] is None:
Debug('Not detected type %s for %s' % (s[0], ret))
else:
global_type[s[1]][None] = True
return ret
v = []
if len(ret[1]) == 1 and ret[1][0][0] == 'STORE_CALC_CONST': ##TCmp(ret, v, ('STORE', (('STORE_CALC_CONST', '?'),), '?')):
return ret
v = []
if type(ret) is tuple and len(ret) >= 1 and type(ret[0]) is str and \
(ret[0][0] == '!' or \
ret[0] in ('(IF', ')IF', '(WHILE', ')WHILE', \
')(ELSE', 'RETURN', 'SET_VARS', 'UNPUSH')):
return ret
v = []
if type(ret) is tuple and len(ret) >= 1 and type(ret[0]) is tuple:
return ret
v = []
if TCmp(ret, v, ('CALC_CONST', '?')):
return ret
v = []
if TCmp(ret, v, ('CONST', '?')):
return ret
v = []
if TCmp(ret, v, (('CONST', '?'),)):
return ret
v = []
if TCmp(ret, v, ('STORE_GLOBAL', '?')):
return ret
v = []
if TCmp(ret, v, ('STORE_NAME', '?')):
return ret
v = []
if TCmp(ret, v, ('STORE_CALC_CONST', '?')):
return ret
v = []
if TCmp(ret, v, (('STORE_GLOBAL', '?'),)):
return ret
v = []
if TCmp(ret, v, (('STORE_CALC_CONST', '?'),)):
return ret
v = []
if type(ret) is tuple and len(ret) == 3 and type(ret[0]) is str and \
ret[0] == 'SET_EXPRS_TO_VARS' and \
TCmp(ret, v, ('SET_EXPRS_TO_VARS', '?', '?')):
for i, _v1 in enumerate(v[0]):
_v2 = v[1][i]
if _v1[0] == 'STORE_GLOBAL':
if _v1[1] not in global_type:
global_type[_v1[1]] = {}
global_type[_v1[1]][None] = None
collect_set_global(_v2, nm)
return ret
v = []
if len(ret) > 0 and type(ret[0]) is str and ret[0] == '(FOR':
sets = ret[1]
for sets in ret[1]:
if sets[0] == 'STORE_GLOBAL':
if sets[1] not in global_type:
global_type[sets[1]] = {}
global_type[sets[1]][None] = True
Debug('Not detected FOR type %s for %s' % (sets[1], ret))
return ret
## if TCmp(ret, v, ('(FOR', (('STORE_GLOBAL', '?'),), '?')):
## if v[0] not in global_type:
## global_type[v[0]] = {}
## global_type[v[0]][None] = True
## Debug('Not detected FOR type %s for %s' % (v[0], v[1]))
## return ret
v = []
if type(ret) is tuple and 'STORE_GLOBAL' in repr(ret):
print '<', ret, '>'
Fatal('Can\'t collect type global variables', ret)
return ret
local_type = {}
def not_loc_detec(nm, expr):
Debug('def %s, var %s -- local type not detected (%s)' % (current_co.co_name, nm, expr))
def loc_detec(nm, typ, expr):
Debug('def %s, var %s -- local type %s detected (%s)' % (current_co.co_name, nm, typ, expr))
def loc_type_set(nm, typ, expr):
global local_type
if nm not in local_type:
local_type[nm] = {}
local_type[nm][typ] = expr
if typ is None:
not_loc_detec(nm, expr)
else:
loc_detec(nm, typ, expr)
def collect_set_local(a, nm):
global local_type
if type(a) is tuple:
if len(a) > 0 and type(a[0]) is str and a[0] == 'CONST':
return
if len(a) >= 1 and type(a[0]) is tuple:
for i in a:
collect_set_local(i, nm)
# [collect_set_local(i, nm) for i in a]
return
if len(a) >= 1 and type(a[0]) is str and a[0] in ('!AND_BOOLEAN', '!OR_BOOLEAN'):
for i in a:
collect_set_local(i, nm)
return
# [collect_set_local(i, nm) for i in a]
if len(a) >= 1 and type(a[0]) is str and a[0] == '!PyObject_Call':
collect_set_local(a[1], nm)
if a[2][0] == '!BUILD_TUPLE':
for i in a[2][1]:
collect_set_local(i, nm)
if a[3] != ('NULL',):
collect_set_local(a[3], nm)
# [collect_set_local(i, nm) for i in a]
return
v = []
ret = a
if len(ret) == 2 and type(ret[0]) is str and ret[0] in ('RETURN_VALUE', '(IF', '(WHILE', 'UNPUSH', 'PRINT_ITEM_1', '!BOOLEAN'):
collect_set_local(ret[1], nm)
return
if len(ret) == 3 and type(ret[0]) is str and ret[0] in ('PRINT_ITEM_TO_2',):
collect_set_local(ret[1], nm)
collect_set_local(ret[2], nm)
return
if len(ret) == 3 and type(ret[0]) is str and ret[0] in ('(IF', '(WHILE'):
collect_set_local(ret[1], nm)
return
if len(ret) > 0 and type(ret[0]) is str and ret[0] == 'PYAPI_CALL':
temp = ret[1]
for x in temp[1:]:
if type(x) is tuple:
collect_set_local(x, nm)
# [collect_set_local(x, nm) for x in temp[1:] if type(x) is tuple]
return
if len(ret) > 2 and type(ret[0]) is str and ret[0] == 'RAISE_VARARGS_STMT' and ret[1] == 0:
for x in ret[2:]:
if type(x) is tuple:
collect_set_local(x, nm)
# [collect_set_local(x, nm) for x in ret[2:] if type(x) is tuple]
return
if len(ret) > 2 and type(ret[0]) is str and ret[0] == 'RAISE_VARARGS' and ret[1] == 0:
for x in ret[2:]:
if type(x) is tuple:
collect_set_local(x, nm)
# [collect_set_local(x, nm) for x in ret[2:] if type(x) is tuple]
return
if len(ret) > 0 and type(ret[0]) is str and ret[0] == 'DELETE_FAST':
loc_type_set(ret[1], None, ret)
return
if len(ret) > 0 and type(ret[0]) is str and ret[0] == 'STORE':
if TCmp(ret, v, ('STORE', (('STORE_NAME', '?'),), ('?',))):
collect_set_local(v[1], nm)
return
if TCmp(ret, v, ('STORE', (('STORE_GLOBAL', '?'),), ('?',))):
collect_set_local(v[1], nm)
return
if TCmp(ret, v, ('STORE', (('STORE_DEREF', '?'),), ('?',))):
collect_set_local(v[1], nm)
return
if TCmp(ret, v, ('STORE', (('PyObject_SetItem', '?', '?'),), ('?',))):
collect_set_local(v[0], nm)
collect_set_local(v[1], nm)
collect_set_local(v[2], nm)
return
if TCmp(ret, v, ('STORE', (('PyObject_SetAttr', '?', '?'),), ('?',))):
collect_set_local(v[0], nm)
collect_set_local(v[1], nm)
collect_set_local(v[2], nm)
return
if TCmp(ret, v, ('STORE', (('STORE_SLICE_LV+3', '?', '?', '?'),), ('?',))):
collect_set_local(v[0], nm)
collect_set_local(v[1], nm)
collect_set_local(v[2], nm)
collect_set_local(v[3], nm)
return
if TCmp(ret, v, ('STORE', (('STORE_SLICE_LV+2', '?', '?'),), ('?',))):
collect_set_local(v[0], nm)
collect_set_local(v[1], nm)
collect_set_local(v[2], nm)
return
if TCmp(ret, v, ('STORE', (('STORE_SLICE_LV+1', '?', '?'),), ('?',))):
collect_set_local(v[0], nm)
collect_set_local(v[1], nm)
collect_set_local(v[2], nm)
return
if TCmp(ret, v, ('STORE', (('STORE_SLICE_LV+0', '?'),), ('?',))):
collect_set_local(v[0], nm)
collect_set_local(v[1], nm)
return
if TCmp(ret, v, ('STORE', (('STORE_FAST', '?'),), ('?',))):
loc_type_set(v[0], TypeExpr(v[1]), v[1])
collect_set_local(v[1], nm)
return
if TCmp(ret, v, ('STORE', (('SET_VARS', '?'),), ('?',))):
t = TypeExpr(v[1])
for i, s in enumerate(v[0]):
if s[0] == 'STORE_FAST':
if IsTuple(t) and t[1] is not None and i < len(t[1]):
loc_type_set(s[1], t[1][i], ret)
else:
loc_type_set(s[1], None, ret)
collect_set_local(v[1], nm)
return
v = []
if TCmp(ret, v, ('STORE', (('STORE_CALC_CONST', '?'),), '?')):
collect_set_local(v[1], nm)
return
v = []
if TCmp(ret, v, ('STORE', (('UNPACK_SEQ_AND_STORE', '?', '?'),), ('?',))):
t = TypeExpr(v[2])
for i, s in enumerate(v[1]):
if s[0] == 'STORE_FAST':
if IsTuple(t) and t[1] is not None and i < len(t[1]):
loc_type_set(s[1], t[1][i], ret)
else:
loc_type_set(s[1], None, ret)
collect_set_local(v[2], nm)
return
if type(ret) is tuple and len(ret) == 3 and type(ret[0]) is str and \
ret[0] == 'SET_EXPRS_TO_VARS' and \
TCmp(ret, v, ('SET_EXPRS_TO_VARS', '?', '?')):
for i, _v1 in enumerate(v[0]):
## _v2 = v[1][i]
if _v1[0] == 'STORE_FAST':
loc_type_set(_v1[1], TypeExpr(v[1][i]), v[1][i])
collect_set_local(v[1], nm)
return
if type(ret) is tuple and len(ret) == 3 and type(ret[0]) is str and \
ret[0] == 'SEQ_ASSIGN' and \
TCmp(ret, v, ('SEQ_ASSIGN', '?', '?')):
t = TypeExpr(v[1])
for i, _v1 in enumerate(v[0]):
if _v1[0] == 'STORE_FAST':
loc_type_set(_v1[1], t, v[1])
collect_set_local(v[1], nm)
return
v = []
if type(ret) is tuple and len(ret) >1 and type(ret[0]) is str and \
ret[0] == ')(EXCEPT':
if TCmp(ret, v, (')(EXCEPT', ('?', '?'), (('STORE_FAST', '?'),))) and type(v[1]) is int:
collect_set_local(v[0], nm)
loc_type_set(v[2], None, ret)
return
v = []
if TCmp(ret, v, (')(EXCEPT', ('?',), (('STORE_FAST', '?'),))) :
collect_set_local(v[0], nm)
loc_type_set(v[1], None, ret)
return
v = []
if type(ret) is tuple and len(ret) >1 and type(ret[0]) is str and \
ret[0] == '(WITH':
if TCmp(ret, v, ('(WITH', '?', ('STORE_FAST', '?'))):
collect_set_local(v[0], nm)
loc_type_set(v[1], None, ret)
return
v = []
if TCmp(ret, v, ('(WITH', '?', (('STORE_FAST', '?'),))):
collect_set_local(v[0], nm)
loc_type_set(v[1], None, ret)
return
v = []
if TCmp(ret, v, ('(WITH', '?', ('STORE_DEREF', '?'))):
collect_set_local(v[0], nm)
loc_type_set(v[1], None, ret)
return
v = []
if TCmp(ret, v, ('(WITH', '?', (('STORE_DEREF', '?'),))):
collect_set_local(v[0], nm)
loc_type_set(v[1], None, ret)
return
v = []
if TCmp(ret, v, ('(WITH', '?', (('SET_VARS', '?'),))):
collect_set_local(v[0], nm)
for k in v[1]:
if type(k) is tuple and len(k) == 2 and k[0] == 'STORE_FAST':
loc_type_set(k[1], None, ret)
return
v = []
if TCmp(ret, v, ('(WITH', '?', ('SET_VARS', '?'))):
collect_set_local(v[0], nm)
for k in v[1]:
if type(k) is tuple and len(k) == 2 and k[0] == 'STORE_FAST':
loc_type_set(k[1], None, ret)
return
if TCmp(ret, v, ('(WITH', '?', ())):
collect_set_local(v[0], nm)
return
Fatal('Can\'t collect type local variables WITH', ret)
v = []
if type(ret) is tuple and len(ret) > 0 and type(ret[0]) is str and ret[0] == '(FOR':
if len(ret[1]) == 2 and len(ret[1][0]) == 2 and ret[1][0][0] == 'STORE_FAST':
if TCmp(ret, v, ('(FOR', (('STORE_FAST', '?'), '?'),
('!PyObject_Call', ('!LOAD_BUILTIN', 'enumerate'), \
'?', ('NULL',)))):
loc_type_set(v[0], Kl_Int, ret)
if v[1][0] == 'STORE_FAST':
loc_type_set(v[1][1], None, v[2])
elif v[1][0] == 'UNPACK_SEQ_AND_STORE' and v[1][1] == 0:
t = TypeExpr(v[2])
for i, v5 in enumerate(v[1][2]):
if v5[0] == 'STORE_FAST':
if IsTuple(t) and t[1] is not None and i < len(t[1]):
loc_type_set(v5[1], t[1][i], ret)
else:
loc_type_set(v5[1], None, ret)
else:
if type(v5) is tuple: # and 'STORE_FAST' in repr(v5):
print '<', v5, ':', ret, '>'
Fatal('Can\'t collect FOR unpack type local variables', v5, ret)
return
if len(ret[1]) == 1 and len(ret[1][0]) == 2 and ret[1][0][0] == 'STORE_FAST':
v = [ret[1][0][1], ret[2]] ##if TCmp(ret, v, ('(FOR', (('STORE_FAST', '?'),), '?')):
v2 = []
if v[1][0] == '!PyObject_Call' and 'range' in repr(v[1]):
if TCmp(v[1], v2, ('!PyObject_Call', ('!LOAD_BUILTIN', 'xrange'), ('CONST', (int, int)), \
('NULL',))) or \
TCmp(v[1], v2, \
('!PyObject_Call', ('!LOAD_BUILTIN', 'range'), ('CONST', (int, int)), \
('NULL',))) or \
TCmp(v[1], v2, \
('!PyObject_Call', ('!LOAD_BUILTIN', 'xrange'), ('CONST', (int,)), \
('NULL',))) or \
TCmp(v[1], v2, \
('!PyObject_Call', ('!LOAD_BUILTIN', 'range'), ('CONST', (int,)), \
('NULL',))):
loc_type_set(v[0], Kl_Int, True)
collect_set_local(v[1], nm)
return
v2 = []
if TCmp(v[1], v2, ('!PyObject_Call', ('!LOAD_BUILTIN', 'range'), \
('CONST', ('?',)), ('NULL',))):
if v2[0] is int:
loc_type_set(v[0], Kl_Int, True)
collect_set_local(v[1], nm)
return
if TCmp(v[1], v2, ('!PyObject_Call', ('!LOAD_BUILTIN', 'range'), \
('!BUILD_TUPLE', ('?',)), ('NULL',))):
loc_type_set(v[0], Kl_Int, True)
collect_set_local(v[1], nm)
return
if TCmp(v[1], v2, ('!PyObject_Call', ('!LOAD_BUILTIN', 'range'), \
('!BUILD_TUPLE', ('?', '?')), ('NULL',))):
t = TypeExpr(v2[0])
t2 = TypeExpr(v2[1])
if t is None and t2 is None:
loc_type_set(v[0], Kl_IntUndefSize, True)
else:
if t2 is None:
loc_type_set(v[0], Kl_IntUndefSize, True)
else:
loc_type_set(v[0], t, ret)
collect_set_local(v[1], nm)
return
if TCmp(v[1], v2, ('!PyObject_Call', ('!LOAD_BUILTIN', 'xrange'), \
('!BUILD_TUPLE', ('?',)), ('NULL',))):
t = TypeExpr(v2[0])
if t is None:
loc_type_set(v[0], Kl_IntUndefSize, True)
else:
loc_type_set(v[0], t, ret)
collect_set_local(v[1], nm)
return
if TCmp(v[1], v2, ('!PyObject_Call', ('!LOAD_BUILTIN', 'xrange'), \
('!BUILD_TUPLE', ('?', '?')), ('NULL',))):
t = TypeExpr(v2[0])
t2 = TypeExpr(v2[1])
if t is None and t2 is None:
loc_type_set(v[0], Kl_IntUndefSize, True)
else:
if t2 is None:
loc_type_set(v[0], Kl_IntUndefSize, True)
else:
loc_type_set(v[0], t, ret)
collect_set_local(v[1], nm)
return
loc_type_set(v[0], None, ret)
collect_set_local(v[1], nm)
return
v = []
if TCmp(ret, v, ('(FOR', '?', '?')):
for _v in v[0]:
if type(_v) is tuple and _v[0] == 'STORE_FAST':
loc_type_set(_v[1], None, ret)
elif type(_v) is tuple and _v[0] == 'STORE_GLOBAL':
pass
elif type(_v) is tuple and _v[0] == 'STORE_NAME':
pass
elif type(_v) is tuple and _v[0] == 'STORE_DEREF':
loc_type_set(_v[1], None, ret)
elif type(_v) is tuple and _v[0] == 'PyObject_SetAttr':
pass
elif type(_v) is tuple and _v[0] == 'UNPACK_SEQ_AND_STORE' and _v[1] == 0:
for v5 in _v[2]:
if v5[0] == 'STORE_FAST':
loc_type_set(v5[1], None, ret)
else:
if type(v5) is tuple: # and 'STORE_FAST' in repr(v5):
print '<', v5, ':', ret, '>'
Fatal('Can\'t collect FOR unpack type local variables', v5, ret)
else:
if type(_v) is tuple: # and 'STORE_FAST' in repr(_v):
print '<', _v, ':', ret, '>'
Fatal('Can\'t collect FOR type local variables', _v, ret)
collect_set_local(v[1], nm)
return
v = []
if type(ret) is tuple and len(ret) > 0 and type(ret[0]) is str and ret[0] == '!LIST_COMPR':
# print ret
if TCmp(ret, v, ('!LIST_COMPR', '?', '?')):
varset = False
if len(v[1][0]) == 1 and len(v[1][1]) == 1:
stor, expr = v[1][0][0], v[1][1][0]
if stor[0] == 'STORE_FAST':
v2 = []
if TCmp(expr, v2, ('!PyObject_Call', ('!LOAD_BUILTIN', 'range'), ('!BUILD_TUPLE', ('?',)), ('NULL',))):
loc_type_set(stor[1], Kl_Int, True)
varset = True
elif TCmp(expr, v2, ('!PyObject_Call', ('!LOAD_BUILTIN', 'range'), ('CONST', '?'), ('NULL',))):
loc_type_set(stor[1], Kl_Int, True)
varset = True
temp = v[1]
v = [v[0],None,None, None]
collect_set_local(v[0], nm)
while len(temp) > 0:
v[1:] = temp[:3]
temp = temp[3:]
for _v in v[1]:
if type(_v) is tuple and _v[0] == 'STORE_FAST' and not varset:
loc_type_set(_v[1], None, ret)
collect_set_local(v[2], nm)
collect_set_local(v[3], nm)
return
if type(ret) is tuple and len(ret) > 0 and type(ret[0]) is str and ret[0] == '!SET_COMPR':
if TCmp(ret, v, ('!SET_COMPR', '?', '?')):
temp = v[1]
v = [v[0],None,None, None]
collect_set_local(v[0], nm)
while len(temp) > 0:
v[1:] = temp[:3]
temp = temp[3:]
for _v in v[1]:
if type(_v) is tuple and _v[0] == 'STORE_FAST':
loc_type_set(_v[1], None, ret)
collect_set_local(v[2], nm)
collect_set_local(v[3], nm)
return
if type(ret) is tuple and len(ret) > 0 and type(ret[0]) is str and ret[0] == '!MAP_COMPR':
if TCmp(ret, v, ('!MAP_COMPR', '?', '?')):
temp = v[1]
v = [v[0],None,None, None]
collect_set_local(v[0], nm)
while len(temp) > 0:
v[1:] = temp[:3]
temp = temp[3:]
for _v in v[1]:
if type(_v) is tuple and _v[0] == 'STORE_FAST':
loc_type_set(_v[1], None, ret)
collect_set_local(v[2], nm)
collect_set_local(v[3], nm)
return
if type(ret) is tuple and len(ret) > 0 and type(ret[0]) is str and ret[0] == '!COND_METH_EXPR':
if TCmp(ret, v, ('!COND_METH_EXPR', '?', '?', '?')):
collect_set_local(v[0], nm)
collect_set_local(v[1], nm)
return
if len(ret) > 0 and type(ret[0]) is str and ret[0] == 'IMPORT_FROM_AS':
collect_set_local(ret[2], nm)
collect_set_local(ret[3], nm)
for _v in ret[4]:
if _v[0] == 'STORE_FAST':
loc_type_set(_v[1], None, ret)
elif _v[0] == 'STORE_CALC_CONST':
return
elif _v[0] == 'STORE_NAME':
return
else:
if type(_v) is tuple: # and 'STORE_FAST' in repr(_v):
print '<', _v, ':', ret, '>'
Fatal('Can\'t collect FOR type local variables', _v, ret)
return
# repr_ret = repr(ret)
if type(ret) is tuple and len(ret) > 0: # and 'STORE_FAST' in repr_ret:
if ret[0] == 'PY_TYPE':
collect_set_local(ret[3], nm)
return
if ret[0] in ('DELETE_SUBSCR',):
collect_set_local(ret[1], nm)
collect_set_local(ret[2], nm)
return
if type(ret[0]) is str:
return
if ret[0] in ('(TRY', ')ENDTRY', '.L', 'CALC_CONST', 'NULL', 'FAST'):
return
if type(ret[0]) is not str or ret[0][0] != '!':
pprint(ret)
print '<', ret, '>'
pprint(ret)
Fatal('Can\'t collect type local variables', ret)
return
for i in a:
collect_set_local(i, nm)
# [collect_set_local(i, nm) for i in a]
return
if type(a) is list:
assert len(a) > 0
## pprint(a)
for i in a:
collect_set_local(i, nm)
# [collect_set_local(i, nm) for i in a]
return
def tree_pass(a, upgrade_op, up, nm):
global print_tree_node
if print_tree_node:
print '>> tree_pass', nm, sys.getrefcount(a)
pprint(a)
if type(a) is tuple:
if len(a) > 0 and type(a[0]) is str and a[0] == 'CONST':
return a
while True:
r = tuple([tree_pass(v, upgrade_op,a, nm) for v in a])
notchanged = len(r) == len(a) and all([r[i] is a[i] for i in range(len(r))])
if notchanged:
if print_tree_node:
print '/1', sys.getrefcount(a), sys.getrefcount(r)
r = a
r2 = upgrade_op(r,nm)
notchanged = notchanged and r2 == r
if notchanged:
break
a = r2
return r
if type(a) is list:
assert len(a) > 0
while True:
a = repl_list(a,up)
r = [tree_pass(v, upgrade_op, a, nm) for v in a]
notchanged = len(r) == len(a) and all([r[i] is a[i] for i in range(len(r))])
if notchanged:
if print_tree_node:
print '/2', sys.getrefcount(a), sys.getrefcount(r)
r = a
assert len(r) > 0
r2 = upgrade_op(r,nm)
notchanged = notchanged and r2 == r
if notchanged:
break
a = r2
return r
return a
def tree_pass_upgrade_repl(a, up, nm):
global print_tree_node
if print_tree_node:
print '>> tree_pass_upgrade_repl', nm, sys.getrefcount(a)
pprint(a)
if type(a) is tuple:
if len(a) > 0 and type(a[0]) is str and a[0] == 'CONST':
return a
while True:
r = tuple([tree_pass_upgrade_repl(v,a, nm) for v in a])
notchanged = len(r) == len(a) and all([r[i] is a[i] for i in range(len(r))])
if notchanged:
if print_tree_node:
print '/1', sys.getrefcount(a), sys.getrefcount(r)
r = a
r2 = upgrade_repl(r,nm)
notchanged = notchanged and r2 == r
if notchanged:
break
a = r2
return r
if type(a) is list:
assert len(a) > 0
while True:
a = repl_list(a,up)
r = [tree_pass_upgrade_repl(v, a, nm) for v in a]
notchanged = len(r) == len(a) and all([r[i] is a[i] for i in range(len(r))])
if notchanged:
if print_tree_node:
print '/2', sys.getrefcount(a), sys.getrefcount(r)
r = a
assert len(r) > 0
r2 = upgrade_repl(r,nm)
notchanged = notchanged and r2 == r
if notchanged:
break
a = r2
return r
return a
def tree_pass_upgrade_op2(a, up, nm):
global print_tree_node
if print_tree_node:
print '>> tree_pass_upgrade_op2', nm, sys.getrefcount(a)
pprint(a)
if type(a) is tuple:
if len(a) > 0 and type(a[0]) is str and a[0] == 'CONST':
return a
while True:
r = tuple([tree_pass_upgrade_op2(v,a, nm) for v in a])
notchanged = len(r) == len(a) and all([r[i] is a[i] for i in range(len(r))])
if notchanged:
if print_tree_node:
print '/1', sys.getrefcount(a), sys.getrefcount(r)
r = a
r2 = upgrade_op2(r,nm)
notchanged = notchanged and r2 == r
if notchanged:
break
a = r2
return r
if type(a) is list:
assert len(a) > 0
while True:
a = repl_list(a,up)
r = [tree_pass_upgrade_op2(v, a, nm) for v in a]
notchanged = len(r) == len(a) and all([r[i] is a[i] for i in range(len(r))])
if notchanged:
if print_tree_node:
print '/2', sys.getrefcount(a), sys.getrefcount(r)
r = a
assert len(r) > 0
r2 = upgrade_op2(r,nm)
notchanged = notchanged and r2 == r
if notchanged:
break
a = r2
return r
return a
## def tree_pass_old(a, upgrade_op, up, nm):
## global print_tree_node
## if print_tree_node:
## print '>> tree_pass', nm
## pprint(a)
## if type(a) is tuple:
## if len(a) > 0 and type(a[0]) is str and a[0] == 'CONST':
## return a
## while True:
## r = tuple([tree_pass(i, upgrade_op,a, nm) for i in a])
## notchanged = len(r) == len(a) and all([r[i] is a[i] for i,x in enumerate(r)])
## if notchanged:
## r = a
## r2 = upgrade_op(r,nm)
## notchanged = notchanged and r2 == r
## if notchanged:
## break
## a = r2
## return r
## if type(a) is list:
## assert len(a) > 0
## while True:
## a = repl_list(a,up)
## r = [tree_pass(i, upgrade_op, a, nm) for i in a]
## notchanged = len(r) == len(a) and all([r[i] is a[i] for i,x in enumerate(r)])
## if notchanged:
## r = a
## assert len(r) > 0
## r2 = upgrade_op(r,nm)
## notchanged = notchanged and r2 == r
## if notchanged:
## break
## a = r2
## return r
## return a
def tree_pass_readonly(a, up, nm):
if type(a) is tuple:
if len(a) > 0 and type(a[0]) is str and a[0] == 'CONST':
return
fill_direct_args(a,nm)
[tree_pass_readonly(i, a, nm) for i in a]
return
elif type(a) is list:
if len(a) <= 0:
pprint((up, nm))
assert len(a) > 0
[tree_pass_readonly(i, a, nm) for i in a]
return
def ortogonal(a, upgrade,up=None):
if type(a) is tuple:
if len(a) > 0 and a[0] == 'CONST':
return a
r = tuple([ortogonal(i, upgrade,a) for i in a])
if all([r[i] is a[i] for i,x in enumerate(r)]):
r = a
while True:
r2 = upgrade(r)
if r2 == r:
break
r = r2
return r
if type(a) is list:
a = repl_list(a,up)
r = [ortogonal(i, upgrade, a) for i in a]
if all([r[i] is a[i] for i,x in enumerate(r)]):
r = a
while True:
r2 = upgrade(r)
if r2 == r:
break
r = r2
return r
return a
def eqexpr(a,b):
if type(a) is list:
if type(b) is list and len(a) == len(b):
for i, v in enumerate(a):
if not eqexpr(v, b[i]):
return False
return True
return False
elif type(a) is tuple:
if type(b) is tuple and len(a) == len(b):
for i, v in enumerate(a):
v2 = b[i]
if type(v) == str and type(v2) == str and v != v2:
return False
if type(v) == int and type(v2) == int and v != v2:
return False
if type(v) == bool and type(v2) == bool and v != v2:
return False
if type(v) == tuple and type(v2) == tuple and len(v) != len(v2):
return False
if type(v) != type(v2):
return False
if not eqexpr(v, v2):
return False
return True
return False
elif type(a) == str and type(b) == str:
return a == b
elif type(a) == int and type(b) == int:
return a == b
elif type(a) == bool and type(b) == bool:
return a is b
elif type(a) == type(b) and a == b:
return True
return False
def replace_subexpr(a,b,c):
## print '/1', a
## print '/2', b
## print '/3', c
if type(b) is not tuple or type(c) is not tuple:
Fatal('At replace subexe is not tuple', b, c, a)
return a
if type(a) is tuple and type(b) is tuple and type(c) is tuple:
if c[0] == 'PY_TYPE' and c[3][0] == 'PY_TYPE':
Fatal('Nested PY_TYPE', b, c)
if c[0] == 'PY_TYPE' and b[0] == 'PY_TYPE':
Fatal('replaced PY_TYPE', b, c)
if len(a) > 3 and type(a[0]) is str and a[0] == 'PY_TYPE' and a[3] == b and \
len(c) == 2 and c[0] == 'CONST':
return c
if len(a) == len(b) and type(a[0]) == type(b[0]) and a[0] == b[0] and eqexpr(a,b):
return c
if a is c:
return a
if len(c) >= 4 and type(c[0]) is str and \
c[0] == 'PY_TYPE' and len(a) >= 4 and \
len(a) >= 4 and type(a[0]) is str and a[0] == 'PY_TYPE' and a[3] == b:
return c
if len(a) == len(c) and type(a[0]) == type(c[0]) and a[0] == c[0] and eqexpr(a,c):
return a
return tuple([replace_subexpr(i,b,c) for i in a])
if type(a) is list:
return [replace_subexpr(i,b,c) for i in a]
return a
def replace_fastvar(a, d):
## print '/1', a
## print '/2', b
## print '/3', c
if type(a) is tuple and len(a) > 3 and a[0] == 'PY_TYPE' and a[3] in d:
new = d[a[3]]
if new[0] == 'PY_TYPE':
t1 = list(a)
t2 = list(new)
t1[3] = None
t2[3] = None
if t1 == t2:
return new
if t1 != t2:
Fatal('Illegal replace typed arg', a, new)
if type(a) is tuple and len(a) == 2 and a[0] == 'FAST':
return d[a[1]]
if type(a) is tuple:
return tuple([replace_fastvar(i,d) for i in a])
if type(a) is list:
return [replace_fastvar(i,d) for i in a]
return a
def is_expandable_enumerate(iter):
if not enumerate2for:
return False
v = []
return TCmp(iter, v, ('!PyObject_Call', ('!LOAD_BUILTIN', 'enumerate'), \
('!BUILD_TUPLE', ('?',)), \
('NULL',)))
def generate_list_compr_enumerate(acc, val, store_ind, store_val, enumerated, cond, o):
assert cond is None or len(cond) == 1
ref_expr = Expr1(enumerated, o)
t = TypeExpr(enumerated)
if t is not None:
Debug('Known type enumerate list complete', t, enumerated)
ref_iter = New()
n_iter = New('long')
o.Stmt(ref_iter, '=', 'PyObject_GetIter', ref_expr)
Cls1(o, ref_expr)
o.Stmt(n_iter, '=', 0)
o.append('for (;;) {')
ref_temp = New()
o.Stmt(ref_temp, '=', 'PyIter_Next', ref_iter)
o.Raw('if (PyErr_Occurred()) goto ', labl, ';')
UseLabl()
o.Stmt('if (!', ref_temp, '){ break; }')
generate_store(store_val, ref_temp, o, 'PyIter_Next')
o.ZeroTemp(ref_temp)
ref_int = New()
o.PushInt(ref_int, n_iter)
generate_store(store_ind, ref_int, o, ('PyInt_FromSsize_t', n_iter))
Cls1(o, ref_int)
o.Stmt(n_iter, '++')
if cond is not None:
o1, cond_var = shortage(generate_logical_expr(cond[0]))
o.extend(o1)
o.Stmt('if (', cond_var, '){')
ref_val = Expr1(val[0], o)
o.Stmt('PyList_Append', acc, ref_val)
Cls1(o, ref_val)
if cond is not None:
o.append('}')
Cls1(o, cond_var)
o.append('}')
o.Cls(ref_iter, n_iter, ref_expr)
def generate_list_compr_iteritems(acc, val, store_1, store_2, dic, cond, o):
assert cond is None or len(cond) == 1
ref_expr = Expr1(dic, o)
pos = New('Py_ssize_t')
o.Stmt(pos, '=', 0)
k, v = New(), New()
o.Raw('while (PyDict_Next(', ref_expr, ', ', ('&', pos), ', ', ('&', k), ', ', ('&', v), ')) {')
o.INCREF(k)
o.INCREF(v)
generate_store(store_1, k, o, 'PyDict_Next')
generate_store(store_2, v, o, 'PyDict_Next')
o.Cls(k,v)
if cond is not None:
o1, cond_var = shortage(generate_logical_expr(cond[0]))
o.extend(o1)
o.Stmt('if (', cond_var, '){')
ref_val = Expr1(val[0], o)
o.Stmt('PyList_Append', acc, ref_val)
Cls1(o, ref_val)
if cond is not None:
o.append('}')
Cls1(o, cond_var)
o.append('}')
o.Cls(pos, ref_expr)
def generate_list_compr_iterkeys(acc, val, store, dic, cond, o):
assert cond is None or len(cond) == 1
ref_expr = Expr1(dic, o)
pos = New('Py_ssize_t')
o.Stmt(pos, '=', 0)
k, v = New(), New()
o.Raw('while (PyDict_Next(', ref_expr, ', ', ('&', pos), ', ', ('&', k), ', ', ('&', v), ')) {')
o.INCREF(k)
o.INCREF(v)
generate_store(store, k, o, 'PyDict_Next')
o.Cls(k,v)
if cond is not None:
o1, cond_var = shortage(generate_logical_expr(cond[0]))
o.extend(o1)
o.Stmt('if (', cond_var, '){')
ref_val = Expr1(val[0], o)
o.Stmt('PyList_Append', acc, ref_val)
Cls1(o, ref_val)
if cond is not None:
o.append('}')
Cls1(o, cond_var)
o.append('}')
o.Cls(pos, ref_expr)
def generate_list_compr_itervalues(acc, val, store, dic, cond, o):
assert cond is None or len(cond) == 1
ref_expr = Expr1(dic, o)
pos = New('Py_ssize_t')
o.Stmt(pos, '=', 0)
k, v = New(), New()
o.Raw('while (PyDict_Next(', ref_expr, ', ', ('&', pos), ', ', ('&', k), ', ', ('&', v), ')) {')
o.INCREF(k)
o.INCREF(v)
generate_store(store, v, o, 'PyDict_Next')
o.Cls(k,v)
if cond is not None:
o1, cond_var = shortage(generate_logical_expr(cond[0]))
o.extend(o1)
o.Stmt('if (', cond_var, '){')
ref_val = Expr1(val[0], o)
o.Stmt('PyList_Append', acc, ref_val)
Cls1(o, ref_val)
if cond is not None:
o.append('}')
Cls1(o, cond_var)
o.append('}')
o.Cls(pos, ref_expr)
def generate_list_compr(val, descr_compr, o, forcenewg):
global current_co
prev_compr = current_co.list_compr_in_progress
current_co.list_compr_in_progress = True
acc0 = GenExpr(('!BUILD_LIST', ()),o, forcenewg)
store,expr,cond = descr_compr[0:3]
v = []
if len(descr_compr) == 3 and len(store) == 2 and len(expr) == 1 and \
TCmp(descr_compr, v, (('?', '?'), (('!PyObject_Call', \
('!PyObject_GetAttr', '?', ('CONST', 'iteritems')), \
('CONST', ()), \
('NULL',)),), \
'?')) and IsDict(TypeExpr(v[2])):
generate_list_compr_iteritems(acc0, val, store[0], store[1], v[2], cond, o)
return acc0
if len(descr_compr) == 3 and len(store) == 1 and len(expr) == 1 and \
TCmp(descr_compr, v, (('?',), (('!PyObject_Call', \
('!PyObject_GetAttr', '?', ('CONST', 'iterkeys')), \
('CONST', ()), \
('NULL',)),), \
'?')) and IsDict(TypeExpr(v[1])):
generate_list_compr_iterkeys(acc0, val, store[0], v[1], cond, o)
return acc0
if len(descr_compr) == 3 and len(store) == 1 and len(expr) == 1 and \
TCmp(descr_compr, v, (('?',), (('!PyObject_Call', \
('!PyObject_GetAttr', '?', ('CONST', 'itervalues')), \
('CONST', ()), \
('NULL',)),), \
'?')) and IsDict(TypeExpr(v[1])):
generate_list_compr_itervalues(acc0, val, store[0], v[1], cond, o)
return acc0
if len(descr_compr) == 3 and len(store) == 2 and len(expr) == 1 and \
is_expandable_enumerate(expr[0]):
generate_list_compr_enumerate(acc0, val, store[0], store[1], \
expr[0][2][1][0], cond, o)
return acc0
recursive_gen_func_list_compr(acc0, val, store,expr, cond, descr_compr[3:], o, '')
current_co.list_compr_in_progress = prev_compr
return acc0
def generate_set_compr(val, descr_compr, o, forcenewg):
acc0 = GenExpr(('!BUILD_SET', ()),o, forcenewg)
store,expr,cond = descr_compr[0:3]
recursive_gen_set_compr(acc0, val, store,expr, cond, descr_compr[3:], o)
return acc0
def recursive_gen_set_compr(acc, val, store,expr, cond,tail, o):
assert len(expr) == 1
assert cond is None or len(cond) == 1
ref_iter = Expr1(expr[0], o)
o.append('for (;;) {')
ref_temp = New()
o.Stmt(ref_temp, '=', 'PyIter_Next', ref_iter)
o.Raw('if (PyErr_Occurred()) goto ', labl, ';')
UseLabl()
o.Stmt('if (!', ref_temp, '){ break; }')
if len(store) == 1:
generate_store(store[0], ref_temp, o, 'PyIter_Next')
else:
if store is not None:
generate_store(('SET_VARS', store), ref_temp, o, 'PyIter_Next')
o.ZeroTemp(ref_temp)
if cond is not None:
o1, cond_var = shortage(generate_logical_expr(cond[0]))
o.extend(o1)
o.Stmt('if (', cond_var, '){')
Cls1(o, cond_var)
if len(tail) == 0:
ref_val = Expr1(val[0], o)
o.Stmt('PySet_Add', acc, ref_val)
Cls1(o, ref_val)
else:
store1,expr1, cond1 = tail[0:3]
recursive_gen_set_compr(acc, val, store1,expr1, cond1, tail[3:], o)
if cond is not None:
o.append('}')
o.append('}')
o.Cls(ref_iter)
def generate_map_compr(val, descr_compr, o, forcenewg):
acc0 = GenExpr(('!BUILD_MAP', ()),o, forcenewg)
store,expr,cond = descr_compr[0:3]
## v = []
recursive_gen_map_compr(acc0, val, store,expr, cond, descr_compr[3:], o)
return acc0
def recursive_gen_map_compr(acc, val, store,expr, cond,tail, o):
assert len(expr) == 1
assert cond is None or len(cond) == 1
ref_iter = Expr1(expr[0], o)
o.append('for (;;) {')
ref_temp = New()
o.Stmt(ref_temp, '=', 'PyIter_Next', ref_iter)
o.Raw('if (PyErr_Occurred()) goto ', labl, ';')
UseLabl()
o.Stmt('if (!', ref_temp, '){ break; }')
if len(store) == 1:
generate_store(store[0], ref_temp, o, 'PyIter_Next')
else:
if store is not None:
generate_store(('SET_VARS', store), ref_temp, o, 'PyIter_Next')
o.ZeroTemp(ref_temp)
if cond is not None:
o1, cond_var = shortage(generate_logical_expr(cond[0]))
o.extend(o1)
o.Stmt('if (', cond_var, '){')
Cls1(o, cond_var)
if len(tail) == 0:
ref_k = Expr1(val[0], o)
ref_v = Expr1(val[1], o)
o.Stmt('PyDict_SetItem', acc, ref_k, ref_v)
o.Cls(ref_k, ref_v)
else:
store1,expr1, cond1 = tail[0:3]
recursive_gen_map_compr(acc, val, store1,expr1, cond1, tail[3:], o)
if cond is not None:
o.append('}')
o.append('}')
Cls1(o, ref_iter)
def generate_func_list_compr(val, descr_compr, o, func):
acc0 = New('int')
if func == 'all':
o.Raw(acc0, ' = 1;')
elif func == 'any':
o.Raw(acc0, ' = 0;')
else:
Fatal('456')
store,expr,cond = descr_compr[0:3]
recursive_gen_func_list_compr(acc0, val, store,expr, cond, descr_compr[3:], o, func)
return acc0
def recursive_gen_func_list_compr(acc, val, store,expr, cond,tail, o, func):
assert len(expr) == 1
assert cond is None or len(cond) == 1
t0 = TypeExpr(expr[0])
islist = IsList(t0)
istuple = IsTuple(t0)
ref_iter = New()
pos = None
cnt = None
if islist:
pos = New('int')
v = []
if TCmp(expr[0], v, ('!PyObject_Call', \
('!LOAD_BUILTIN', 'range'), \
('!BUILD_TUPLE', ('?',)), ('NULL',))):
ref_arg = Expr1(v[0], o)
cnt = New('Py_ssize_t')
o.Stmt(cnt, '=', 'PyInt_AsSsize_t', ref_arg)
Cls1(o, ref_arg)
o.Raw('for (', pos, ' = 0;', pos, ' < ', cnt, ';', pos, ' ++) {')
ref_temp = New()
o.Raw(ref_temp, ' = PyInt_FromLong(', pos, ');')
else:
ref_expr = Expr1(expr[0], o)
o.Raw('for (', pos, ' = 0;', pos, ' < PyList_GET_SIZE(', ref_expr, ');', pos, ' ++) {')
ref_temp = New()
o.Raw(ref_temp, ' = PyList_GET_ITEM(', ref_expr, ', ', pos, ');')
o.INCREF(ref_temp)
if len(store) == 1:
generate_store(store[0], ref_temp, o, 'PyList_GET_ITEM')
else:
if store is not None:
generate_store(('SET_VARS', store), ref_temp, o, 'PyList_GET_ITEM')
elif istuple:
ref_expr = Expr1(expr[0], o)
pos = New('int')
o.Raw('for (', pos, ' = 0;', pos, ' < PyTuple_GET_SIZE(', ref_expr, ');', pos, ' ++) {')
ref_temp = New()
o.Raw(ref_temp, ' = PyTuple_GET_ITEM(', ref_expr, ', ', pos, ');')
o.INCREF(ref_temp)
if len(store) == 1:
generate_store(store[0], ref_temp, o, 'PyTuple_GET_ITEM')
else:
if store is not None:
generate_store(('SET_VARS', store), ref_temp, o, 'PyTuple_GET_ITEM')
else:
ref_expr = Expr1(expr[0], o)
o.Stmt(ref_iter, '=', 'PyObject_GetIter', ref_expr)
Cls1(o, ref_expr)
o.append('for (;;) {')
ref_temp = New()
o.Stmt(ref_temp, '=', 'PyIter_Next', ref_iter)
o.Raw('if (PyErr_Occurred()) goto ', labl, ';')
UseLabl()
o.Stmt('if (!', ref_temp, '){ break; }')
if len(store) == 1:
generate_store(store[0], ref_temp, o, 'PyIter_Next')
else:
if store is not None:
generate_store(('SET_VARS', store), ref_temp, o, 'PyIter_Next')
o.ZeroTemp(ref_temp)
if cond is not None:
cond0 = type_in_if(cond[0], {})
o1, cond_var = shortage(generate_logical_expr(cond0))
o.extend(o1)
o.Stmt('if (', cond_var, '){')
Cls1(o, cond_var)
if len(tail) == 0:
if func in ('all', 'any'):
o1, cond_var = shortage(generate_logical_expr(val[0]))
## ref_val = Expr1(val[0], o)
o.extend(o1)
if func == 'all':
o.Raw('if (!(', cond_var,')) {')
o.Raw(acc, ' = 0;')
o.Raw('}')
else:
o.Raw('if (', cond_var,') {')
o.Raw(acc, ' = 1;')
o.Raw('}')
elif func == 'len':
ref_val = Expr1(val[0], o)
Cls1(o, ref_val)
o.Raw(acc, ' += 1;')
elif func == '':
ref_val = Expr1(val[0], o)
o.Stmt('PyList_Append', acc, ref_val)
Cls1(o, ref_val)
else:
Fatal('321')
Cls1(o, cond)
else:
store1,expr1, cond1 = tail[0:3]
recursive_gen_func_list_compr(acc, val, store1,expr1, cond1, tail[3:], o, func)
if cond is not None:
o.append('}')
o.append('}')
o.Cls(ref_iter, pos, cnt)
def generate_len_list_compr(val, descr_compr, o):
acc0 = New('Py_ssize_t')
o.Raw(acc0, ' = 0;')
store,expr,cond = descr_compr[0:3]
## v = []
recursive_gen_func_list_compr(acc0, val, store,expr, cond, descr_compr[3:], o, 'len')
return acc0
def AssignCalcConst(nm, ref, o, expr):
if nm in mnemonic_constant:
## Fatal('??? Assign mnemoconst', nm, ref, expr, o)
return
o.Stmt(calc_const_to(nm), '=', ref);
for a,b,c in Iter3(nm, 'ModuleAttr', None):
if c != '.__dict__' or is_pypy:
r = New()
o.Stmt(r, '=', 'PyObject_GetAttr', ref, ('CONST', c))
o.INCREF(r)
o.Stmt(calc_const_to((nm, c)), '=', r)
Cls1(o, r)
else:
t = TypeExpr(expr)
if t is None:
Fatal('Can\'t detect old/new class of calculated const %s' % nm, expr)
if t[0] == T_NEW_CL_INST:
o.Raw(calc_const_to((nm, c)), ' = *_PyObject_GetDictPtr(', calc_const_to(nm), ');')
elif t[0] == T_OLD_CL_INST:
o.Raw(calc_const_to((nm, c)), ' = ((PyInstanceObject *)', calc_const_to(nm), ')->in_dict;')
else:
Fatal('Can\'t detect any class of calculated const %s' % nm, expr)
def IsCTypedGlobal(k):
return bool(k in detected_global_type and IsCType(detected_global_type[k]))
## def CTypeGlobal(k):
## return Type2CType(detected_global_type[k])
def TypeGlobal(k):
if k in detected_global_type:
return detected_global_type[k]
return None
def IsCVar(it):
if type(it) is tuple and len(it) >= 2:
if it[0] == 'PY_TYPE':
return IsCVar(it[3])
if it[0] == '!@PyInt_FromSsize_t':
return IsCVar(it[2])
head = it[0]
if head == 'FAST':
pos = current_co.co_varnames.index(it[1])
typed_arg = current_co.typed_arg_direct
if pos in typed_arg and is_current & IS_DIRECT:
if IsCType(typed_arg[pos]):
return True
if it[1] in current_co.detected_type:
if IsCType(current_co.detected_type[it[1]]):
return True
if head == '!LOAD_GLOBAL' and it[1] not in d_built and it[1][0] != '_' and not redefined_all:
if build_executable and not global_used_at_generator(it[1]):
if IsCTypedGlobal(it[1]):
return True
return False
def CVarName(it):
assert type(it) is tuple and len(it) >= 2
head = it[0]
if head == 'PY_TYPE':
return CVarName(it[3])
if it[0] == '!@PyInt_FromSsize_t':
return CVarName(it[2])
if head == 'FAST':
pos = current_co.co_varnames.index(it[1])
typed_arg = current_co.typed_arg_direct
if pos in typed_arg and is_current & IS_DIRECT:
t = typed_arg[pos]
if IsCType(t):
return 'Loc_' + Type2CType(t) + '_' + it[1]
if it[1] in current_co.detected_type:
t = current_co.detected_type[it[1]]
if IsCType(t):
return 'Loc_' + Type2CType(t) + '_' + it[1]
if head == '!LOAD_GLOBAL' and it[1] not in d_built and it[1][0] != '_' and not redefined_all:
if build_executable and not global_used_at_generator(it[1]):
if IsCTypedGlobal(it[1]):
t = TypeGlobal(it[1])
return 'Glob_' + Type2CType(t) + '_' + it[1]
if head == 'CALC_CONST' and it[1] not in d_built and it[1][0] != '_' and not redefined_all:
if build_executable and not global_used_at_generator(it[1]):
if IsCTypedGlobal(it[1]):
t = TypeGlobal(it[1])
return 'Glob_' + Type2CType(t) + '_' + it[1]
print head, it
## def is_typed_global(k):
## return bool(k in detected_global_type and IsInt(detected_global_type[k]))
## def is_typed_global_char(k):
## return bool(k in detected_global_type and detected_global_type[k] == Kl_Char)
def CSetVariable(o, var, val):
nm = CVarName(var)
t1 = TypeExpr(var)
t2 = TypeExpr(val)
if IsCType(t2) and Type2CType(t1) == Type2CType(t2):
if val[0] == 'CONST':
generate_store_to_ctype(o, nm, t1, val, val)
return True
if val[0] == '!CALL_CALC_CONST':
generate_call_calc_const(val, o, None, None, nm)
return True
if val[0] == 'PY_TYPE' and IsCVar(val[3]):
o.Raw(nm, ' = ', CVarName(val[3]), ';')
return True
if IsCVar(val):
o.Raw(nm, ' = ', CVarName(val), ';')
return True
return False
def generate_store_to_ctype(o, cnm_, t, ref, expr):
global g_refs2
cnm = cnm_ + ' = '
## if IsCType(TypeExpr(expr)) and expr[0] != 'CONST':
## pprint((cnm_, expr))
if IsInt(t):
if ref[0] == 'CONST':
o.Raw(cnm, ref[1], ';')
else:
o.Raw(cnm, 'PyInt_AsLong(', ref, ');')
if istempref(ref) and ref not in g_refs2:
o.Raw('Py_CLEAR(', ref, ');')
elif IsFloat(t):
if ref[0] == 'CONST':
o.Raw(cnm, ref[1], ';')
else:
o.Raw(cnm, 'PyFloat_AsDouble(', ref, ');')
if istempref(ref) and ref not in g_refs2:
o.Raw('Py_CLEAR(', ref, ');')
elif t == Kl_Char:
if ref[0] == 'CONST':
o.Raw(cnm, charhex(ref[1]), ';')
else:
o.Raw(cnm, '*', PyString_AS_STRING(ref), ';')
if istempref(ref) and ref not in g_refs2:
o.Raw('Py_CLEAR(', ref, ');')
elif t == Kl_Boolean:
if ref[0] == 'CONST':
if ref[1]:
o.Raw(cnm, '1;')
else:
o.Raw(cnm, '0;')
else:
o.Raw(cnm, 'PyObject_IsTrue(', ref, ');')
if istempref(ref) and ref not in g_refs2:
o.Raw('Py_CLEAR(', ref, ');')
else:
assert False
def generate_store(it, ref, o, expr):
global func
assert type(it) is tuple
if it[0] == 'STORE_CALC_CONST':
it = it[1]
AssignCalcConst(it[1], ref, o, expr)
if it[0] == 'STORE_GLOBAL' or (it[0] == 'STORE_NAME' and func == 'Init_filename'):
o.Stmt('PyDict_SetItem', 'glob', ('CONST', it[1]), ref)
if istempref(ref):
Cls1(o, ref)
elif it[0] == 'STORE_NAME':
o.Stmt('PyObject_SetItem', 'f->f_locals', ('CONST', it[1]), ref)
else:
Fatal('generate_store', it)
o.ClsFict(ref)
return
if it[0] == 'STORE_GLOBAL' or (it[0] == 'STORE_NAME' and func == 'Init_filename'):
if build_executable and it[1] not in d_built and it[1][0] != '_' \
and not redefined_all and not global_used_at_generator(it[1]):
if not istempref(ref) and not IsCTypedGlobal(it[1]) :
o.INCREF(ref)
add_fast_glob(it[1])
if IsCTypedGlobal(it[1]):
t = TypeGlobal(it[1])
cnm = CVarName(('!LOAD_GLOBAL', it[1]))
generate_store_to_ctype(o, cnm, t, ref, expr)
else:
o.Stmt('SETSTATIC', it[1], ref)
o.ClsFict(ref)
if istempref(ref) and ref not in g_refs2:
o.Raw(ref, ' = 0;')
else:
o.Stmt('PyDict_SetItem', 'glob', ('CONST', it[1]), ref)
if istempref(ref):
Cls1(o, ref)
o.ClsFict(ref)
return
if it[0] == 'STORE_NAME':
o.Stmt('PyObject_SetItem', 'f->f_locals', ('CONST', it[1]), ref)
Cls1(o, ref)
return
if it[0] == 'STORE_FAST':
## if not istempref(ref):
## o.INCREF(ref)
if it[1] in current_co.detected_type:
t = current_co.detected_type[it[1]]
if IsCType(t):
cnm = CVarName(('FAST', it[1]))
generate_store_to_ctype(o, cnm, t, ref, expr)
else:
if not istempref(ref):
o.INCREF(ref)
o.Stmt('SETLOCAL', it[1], ref)
else:
i = current_co.co_varnames.index(it[1])
typed_arg = current_co.typed_arg_direct
if i in typed_arg and is_current & IS_DIRECT:
t = typed_arg[i]
if IsCType(t):
cnm = CVarName(('FAST', it[1])) + ' = '
generate_store_to_ctype(o, cnm, t, ref, expr)
else:
if not istempref(ref):
o.INCREF(ref)
o.Stmt('SETLOCAL', it[1], ref)
else:
if not istempref(ref):
o.INCREF(ref)
o.Stmt('SETLOCAL', it[1], ref)
o.ClsFict(ref)
if istempref(ref) and ref not in g_refs2:
o.Raw(ref, ' = 0;')
return
if it[0] == 'STORE_DEREF':
o.Stmt('PyCell_Set', ('LOAD_CLOSURE',it[1]), ref)
Cls1(o, ref)
return
if it[0] == 'PyObject_SetAttr':
generate_SetAttr(it, ref, o, expr)
return
if it[0] == '?PyObject_SetAttr':
ref1, ref2 = Expr(o, it[1:3])
o.Stmt('PyObject_SetAttr', ref1, ref2, ref)
proc = Expr1(it[3], o)
o.Stmt('if (', proc, '==', load_builtin(it[3][1]), ') {')
o.Stmt('PyObject_SetAttr', ref1, ref2, ref)
o.Cls(ref, ref1, ref2)
o.append('} else {')
ref4 = New()
tupl = Expr1(('!BUILD_TUPLE', (ref1, ref2, ref)), o)
o.Stmt(ref4, '=', 'PyObject_Call', proc, tupl, ('NULL',))
o.Cls(tupl, ref4)
o.append('}')
Cls1(o, proc)
return
# Code crash unknown -- no crash currently
if it[0] == 'PyObject_SetItem':
it2 = it[2]
if it2[0] == 'PY_TYPE' and it2[1] is int:
it2 = it2[3]
if it2[0] == '!@PyInt_FromSsize_t':
islist = IsList(TypeExpr(it[1]))
if islist:
ref1 = Expr1(it[1], o)
if not istempref(ref):
o.INCREF(ref)
else:
o.ClsFict(ref)
o.Stmt('PyList_SetItem', ref1, it2[1], ref)
Cls1(o, ref1)
return
if not islist:
ref1 = Expr1(it[1], o)
o.Stmt('if (PyList_CheckExact(', ref1, ')) {')
if not istempref(ref):
o.INCREF(ref)
o.Stmt('PyList_SetItem', ref1, it2[1], ref)
o.append('} else {')
ref2 = Expr1(it2[2],o)
o.Stmt('PyObject_SetItem', ref1, ref2, ref)
o.Cls(ref2, ref)
o.append('}')
Cls1(o, ref1)
return
if it[0] == 'PyObject_SetItem' and it[2][0] == 'CONST' and type(it[2][1]) is int:
ref1 = Expr1(it[1], o)
o.ClsFict(ref)
ty = TypeExpr(it[1])
islist = IsList(ty)
if islist:
if not istempref(ref):
o.INCREF(ref)
if it[2][1] >= 0:
o.Stmt('PyList_SetItem', ref1, it[2][1], ref)
else:
n = New('long')
o.Raw(n, ' = PyList_GET_SIZE(', ref1, ') + ', it[2][1], ';')
o.Stmt('PyList_SetItem', ref1, n, ref)
Cls1(o, n)
elif IsDict(ty):
o.Stmt('PyDict_SetItem', ref1, it[2], ref)
else:
if it[2][1] >= 0:
o.Stmt('if (PyList_CheckExact(', ref1, ')) {')
if not istempref(ref):
o.INCREF(ref)
o.Stmt('PyList_SetItem', ref1, it[2][1], ref)
o.append('} else {')
o.Stmt('PyObject_SetItem', ref1, it[2], ref)
if istempref(ref):
o.CLEAR(ref)
o.append('}')
else:
o.Stmt('PyObject_SetItem', ref1, it[2], ref)
Cls1(o, ref1)
return
if it[0] == 'PyObject_SetItem':
ty = TypeExpr(it[1])
ty_ind = TypeExpr(it[2])
if IsDict(ty):
ref1, ref2 = Expr(o, it[1:3])
o.Stmt('PyDict_SetItem', ref1, ref2, ref)
o.Cls(ref, ref1, ref2)
elif IsListAll(ty) and IsInt(ty_ind):
ref1 = Expr1(it[1],o)
if not istempref(ref):
o.INCREF(ref)
o2,ind = shortage(generate_ssize_t_expr(it[2]))
o.extend(o2)
if type(ind) is int:
if ind < 0:
ind2 = New('long')
o.Raw(ind2, ' = ', ind, ' + PyList_GET_SIZE(', ref1, ');')
ind = ind2
else:
pass
else:
if not istemptyped(ind):
ind_ = New('long')
o.Raw(ind_, ' = ', ind, ';')
ind = ind_
o.Stmt('if (', ind, '< 0) {')
o.Raw(ind, ' += PyList_GET_SIZE(', ref1, ');')
o.append('}')
o.Stmt('PyList_SetItem', ref1, ind, ref)
o.ClsFict(ref)
o.Cls(ind, ref, ref1)
elif IsListAll(ty) and ty_ind == Kl_Slice:
ref1, ref2 = Expr(o, it[1:3])
o.Stmt('PyObject_SetItem', ref1, ref2, ref)
o.Cls(ref, ref1, ref2)
elif IsListAll(ty):
ref1 = Expr1(it[1],o)
if not istempref(ref):
o.INCREF(ref)
refind = Expr1(it[2], o)
o.Raw('if (PyInt_CheckExact( ', refind,' )) {')
ind = New('long')
o.Raw(ind, ' = PyInt_AS_LONG ( ', refind,' );')
o.Stmt('if (', ind, '< 0) {')
o.Raw(ind, ' += PyList_GET_SIZE(', ref1, ');')
o.append('}')
o.Stmt('PyList_SetItem', ref1, ind, ref)
Cls1(o, ind)
o.append('} else {')
o.Stmt('PyObject_SetItem', ref1, refind, ref)
o.DECREF(ref)
o.append('}')
o.ClsFict(ref)
o.Cls(ind, ref, ref1, refind)
else:
if ty is not None:
Debug( 'typed SetItem', ty, it)
ref1, ref2 = Expr(o, it[1:3])
o.Stmt('PyObject_SetItem', ref1, ref2, ref)
o.Cls(ref, ref1, ref2)
return
if it[0] == 'STORE_SLICE_LV+0':
t = TypeExpr(it[1])
if IsList(t):
assign_list_slice(it, o, ref)
return
if t is not None:
Debug('typed Store slice', t,it)
ref1 = Expr1(it[1],o)
o.Stmt('_PyEval_AssignSlice', ref1, 'NULL', 'NULL', ref)
o.Cls(ref, ref1)
return
if it[0] == 'STORE_SLICE_LV+3':
t = TypeExpr(it[1])
if IsList(t) and it[2][0] == 'CONST' and it[3][0] == 'CONST' and \
type(it[2][1]) is int and type(it[3][1]) is int and \
it[3][1] >= it[2][1] and it[2][1] >= 0:
ref1 = Expr1(it[1],o)
o.Stmt('PyList_SetSlice', ref1, it[2][1], it[3][1], ref)
o.Cls(ref, ref1)
return
if t is not None:
Debug('typed Store slice', t, it)
ref1, ref2, ref3 = Expr(o, it[1:])
o.Stmt('_PyEval_AssignSlice', ref1, ref2, ref3, ref)
o.Cls(ref, ref1, ref2, ref3)
return
if it[0] == 'STORE_SLICE_LV+1':
t = TypeExpr(it[1])
if IsList(t):
assign_list_slice(it, o, ref)
return
elif t is not None:
Debug('typed Store slice', TypeExpr(it[1]),it)
ref1, ref2 = Expr(o, it[1:])
o.Stmt('_PyEval_AssignSlice', ref1, ref2, 'NULL', ref)
o.Cls(ref, ref1, ref2)
return
if it[0] == 'STORE_SLICE_LV+2':
t = TypeExpr(it[1])
if t is not None:
Debug('typed Store slice', t, it)
ref1, ref2 = Expr(o, it[1:])
o.Stmt('_PyEval_AssignSlice', ref1, 'NULL', ref2, ref)
o.Cls(ref, ref1, ref2)
return
if it[0] == 'SET_VARS':
mass_store(o,ref,it[1],expr)
return
if it[0] == 'UNPACK_SEQ_AND_STORE' and it[1] == 0:
mass_store(o,ref,it[2],expr)
return
Fatal('', it)
def charhex(ch):
if 'A' <= ch <= 'Z':
return '\'' + ch + '\''
if 'a' <= ch <= 'z':
return '\'' + ch + '\''
if '0' <= ch <= '9':
return '\'' + ch + '\''
if ch in '~!@#$%^&*()_+-=[]{};:|/?.>,<':
return '\'' + ch + '\''
v = ord(ch)
if v == 0:
return '\'\\0\''
s = hex(v)[2:]
if len(s) < 2:
s = '0' + s
assert len(s) == 2
return '\'\\x' + s + '\''
def assign_list_slice(it, o, ref, plus_1 = False):
ref1 = Expr1(it[1],o)
if it[0] == 'DELETE_SLICE+0':
ind2 = New('long')
o.Raw(ind2, ' = PyList_GET_SIZE(', ref1, ');')
o.Stmt('PyList_SetSlice', ref1, 0, ind2, 'NULL')
o.Cls(ref1, ind2)
return
if it[0] == 'STORE_SLICE_LV+0':
o.Raw('if ( PyList_SetSlice ( ', ref1, ' , 0 , PyList_GET_SIZE(', ref1, ') , ', ref, ' ) == -1) goto ', labl, ';')
UseLabl()
o.Cls(ref1, ref)
return
o2,ind1 = shortage(generate_ssize_t_expr(it[2]))
o.extend(o2)
ind2 = New('long')
o.Raw(ind2, ' = PyList_GET_SIZE(', ref1, ');')
if type(ind1) is int:
if ind1 < 0:
_ind1 = New('long')
o.Stmt(_ind1, '=', ind1, '+', ind2)
ind1 = _ind1
elif ind1[0] == 'CONST':
if ind1[1] < 0:
_ind1 = New('long')
o.Stmt(_ind1, '=', ind1[1], '+', ind2)
ind1 = _ind1
else:
if not istemptyped(ind1):
ind_ = New('long')
o.Raw(ind_, ' = ', ind1, ';')
ind1 = ind_
o.Stmt('if (', ind1, '< 0) {')
o.Stmt(ind1, '=', ind1, '+', ind2)
o.append('}')
if plus_1:
o.Stmt(ind2, '=', ind1, '+', 1)
o.Stmt('PyList_SetSlice', ref1, ind1, ind2, ref)
o.Cls(ref, ref1, ind1, ind2)
return
def handle_unpack_except(o, src_len, trg_len):
if type(src_len) is int and type(trg_len) is int:
if src_len > trg_len:
o.Raw('PyErr_Format(PyExc_ValueError, "too many values to unpack");')
o.Raw('goto ', labl, ';')
UseLabl()
if src_len < trg_len:
add_s = '%s, %s == 1 ? "" : "s"' % (src_len, src_len)
o.Raw('PyErr_Format(PyExc_ValueError, "need more than %d value%s to unpack", ', add_s, ');')
o.Raw('goto ', labl, ';')
UseLabl()
return
o_2 = Out()
o_2.Raw('PyErr_Format(PyExc_ValueError, "too many values to unpack");')
o_2.Raw('goto ', labl, ';')
tolabl = append_to_exception(o_2)
o.Raw('if (', src_len, ' > ', trg_len, ') goto ', tolabl, ';')
UseLabl()
o_2 = Out()
add_s = '%s, %s == 1 ? "" : "s"' % (CVar(src_len), CVar(src_len))
o_2.Raw('PyErr_Format(PyExc_ValueError, "need more than %d value%s to unpack", ', add_s, ');')
o_2.Raw('goto ', labl, ';')
tolabl = append_to_exception(o_2)
o.Raw('if (', src_len, ' < ', trg_len, ') goto ', tolabl, ';')
UseLabl()
def mass_store(o,ref,its,expr, t = None):
## islist = False
if t is None:
t = TypeExpr(expr)
PushAcc([expr], [ref])
src_len = New('int')
trg_len = len([x for x in its if x is not None])
if IsList(t):
o.Raw(src_len, ' = PyList_GET_SIZE(', ref, ');')
handle_unpack_except(o, src_len, trg_len)
for i,iit in enumerate(its):
if iit is None: continue
ref1 = New()
o.Stmt(ref1, '=', 'PyList_GET_ITEM', ref, i)
generate_store(iit,ref1,o, ('!PyList_GET_ITEM', expr, i))
Cls1(o, ref1)
elif IsTuple(t) or (t is not None and t[0] == 'MayBe' and IsTuple(t[1])):
if (t[0] == 'MayBe' and IsTuple(t[1])):
t = t[1]
if t[1] is None:
o.Stmt(src_len, '=', 'PyTuple_GET_SIZE', ref)
else:
Cls1(o, src_len)
src_len = len(t[1])
handle_unpack_except(o, src_len, trg_len)
for i,iit in enumerate(its):
if iit is None: continue
ref1 = New()
o.Stmt(ref1, '=', 'PyTuple_GET_ITEM', ref, i)
generate_store(iit,ref1,o, ('!PyTuple_GET_ITEM', expr, i))
Cls1(o, ref1)
else:
if t is not None:
## print 'too', t
Debug('UNused type expr in mass store', t, expr)
o.Stmt('if (PyList_CheckExact(', ref, ') ) {')
o.Raw(src_len, ' = PyList_GET_SIZE(', ref, ');')
handle_unpack_except(o, src_len, trg_len)
for i,iit in enumerate(its):
if iit is None: continue
ref1 = New()
o.Stmt(ref1, '=', 'PyList_GET_ITEM', ref, i)
generate_store(iit,ref1,o, ('!PyList_GET_ITEM', expr, i))
Cls1(o, ref1)
o.Stmt('} else if (PyTuple_CheckExact(', ref, ') ) {')
o.Raw(src_len, ' = PyTuple_GET_SIZE(', ref, ');')
handle_unpack_except(o, src_len, trg_len)
for i,iit in enumerate(its):
if iit is None: continue
ref1 = New()
o.Stmt(ref1, '=', 'PyTuple_GET_ITEM', ref, i)
generate_store(iit,ref1,o, ('!PyTuple_GET_ITEM', expr, i))
Cls1(o, ref1)
o.append('} else {')
ref2 = New()
o.Stmt(ref2, '=', 'PySequence_Tuple', ref)
o.Raw(src_len, ' = PyTuple_GET_SIZE(', ref2, ');')
handle_unpack_except(o, src_len, trg_len)
for i,iit in enumerate(its):
if iit is None: continue
ref1 = New()
o.Stmt(ref1, '=', 'PyTuple_GET_ITEM', ref2, i)
generate_store(iit,ref1,o, ('!PyTuple_GET_ITEM', expr, i))
Cls1(o, ref1)
Cls1(o, ref2)
o.append('}')
if istempref(ref):
o.Raw('Py_CLEAR(', ref,');')
PopAcc(o)
o.Cls(ref, src_len)
return
g_acc2 = []
g_refs2 = []
g_len_acc = []
def PopAcc(o, clear = True):
global g_acc2, g_refs2
to_clear = []
if clear:
to_clear = g_refs2[g_len_acc[-1]:]
del g_acc2[g_len_acc[-1]:]
del g_refs2[g_len_acc[-1]:]
del g_len_acc[-1]
for g in to_clear:
if istempref(g):
Cls1(o, g)
def PushAcc(acc,refs):
global g_acc2, g_refs2
g_len_acc.append(len(g_acc2))
g_acc2.extend(acc)
g_refs2.extend(refs)
def PopClearAll(o):
global g_acc2, g_refs2, g_len_acc
grefs = g_refs2[:]
while len(grefs) > 0:
r = grefs[-1]
if istempref(r):
o.CLEAR(r)
del grefs[-1]
predeclared_chars = {}
def add_predeclaration_char_const(ind_const):
global predeclared_chars
predeclared_chars[ind_const] = True
def PyString_AS_STRING(ref0):
if ref0[0] == 'CONST':
assert type(ref0[1]) is str
ind_const = index_const_to(ref0[1])
add_predeclaration_char_const(ind_const)
return ConC('const_string_', ind_const)
return ConC('PyString_AS_STRING ( ', ref0, ' )')
def is_mkfunc_const(proc, expr):
if expr[0] in ('!MK_FUNK', '!_PyEval_BuildClass'):
return True
if len(proc) != 2:
return False
if not (type(proc[0]) is str):
return False
if proc[0] != 'CALC_CONST':
return False
if proc[1] in calc_const_value and \
calc_const_value[proc[1]][0] in ('!MK_FUNK', '!_PyEval_BuildClass'):
return True
return False
## def standart_BINARY_SUBSCR(it, o, forcenewg):
## ref0 = Expr1(it[1], o)
## ref1 = GenExpr(it[2], o, None, None, True)
## ref = New(None, forcenewg)
## if ref1[0] == 'CONST' and type(ref1[1]) is int:
## o.Raw('if ((', ref, ' = _c_BINARY_SUBSCR_Int ( ', ref0, ' , ', ref1[1], ' , ', ref1, ' )) == 0) goto ', labl, ';')
## UseLabl()
## Used('_c_BINARY_SUBSCR_Int')
## else:
## o.Stmt(ref, '=', 'PyObject_GetItem', ref0, ref1)
## o.Cls(ref1, ref0)
## return ref
def Expr1(it, o):
return GenExpr(it, o)
def Expr(o, it):
return [GenExpr(x, o) for x in it]
def Str_for_C(s):
r = ''
for c in s:
h = hex(ord(c))
assert h.startswith('0x')
h = h[2:]
if len(h) < 2:
h = '0' + h
r += '\\x' + h
return '"' + r + '"'
def Char_for_C(s):
r = ''
assert len(s) == 1
c = s[0]
h = hex(ord(c))
assert h.startswith('0x')
h = h[2:]
if len(h) < 2:
h = '0' + h
r += '\\x' + h
return "'" + r + "'"
def generate_SetAttr(it, ref, o, expr):
t = TypeExpr(it[1])
if not redefined_attribute and it[2][0] == 'CONST' and it[2][1][0:2] != '__' and (it[1][0] == 'FAST' or (it[1][0] == 'PY_TYPE' and it[1][3][0] == 'FAST')) and not is_pypy:
isattrs = IsAnyAttrInstance(it[2][1])
ismeth = len (IterMethod(it[2][1], None)) > 0
var = it[1]
isinst = False
if var[0] == 'PY_TYPE':
isinst = var[1] == 'NewClassInstance' or var[1] == 'OldClassInstance'
var = var[3]
if not ismeth and isattrs and var[1] in current_co.co_varnames and \
current_co.co_varnames.index(var[1]) < current_co.co_argcount:
s1 = ('STORE_FAST', var[1])
s2 = ('DELETE_FAST', var[1])
srepr = repr(current_co.cmds[1])
if not repr(s1) in srepr and not repr(s2) in srepr:
if isinst:
o.Raw('if (PyDict_SetItem(_', var[1], '_dict, ', it[2], ', ', ref, ') == -1) goto ', labl, ';')
UseLabl()
current_co.dict_getattr_used[var[1]] = True
Cls1(o, ref)
return
o.Raw('if (_' + var[1] + '_dict) {')
o.Raw('if (PyDict_SetItem(_', var[1], '_dict, ', it[2], ', ', ref, ') == -1) goto ', labl, ';')
UseLabl()
current_co.dict_getattr_used[var[1]] = True
o.append('} else {')
o.Stmt('PyObject_SetAttr', var, it[2], ref)
o.append('}')
Cls1(o, ref)
return
if t is not None and t[0] == T_OLD_CL_INST and not is_pypy:
ismeth = len (IterMethod(it[2][1], None)) > 0
if not ismeth and it[2][0] == 'CONST' and IsAttrInstance(t[1], it[2][1]):
ref1 = Expr1(it[1], o)
o.Stmt('PyDict_SetItem', '((PyInstanceObject *)' + CVar(ref1) + ')->in_dict', it[2], ref)
o.Cls(ref1, ref)
return
elif t is not None and t[0] == T_OLD_CL_INST and it[1][0] == 'CALC_CONST':
if it[2][0] == 'CONST' and IsAttrInstance(t[1], it[2][1]):
if Is3(it[1][1], 'ModuleAttr', '.__dict__'):
o.Stmt('PyDict_SetItem', calc_const_to((it[1][1], '.__dict__')), it[2], ref)
Cls1(o, ref)
return
elif t is not None and t[0] == T_NEW_CL_INST and it[1][0] == 'CALC_CONST':
if it[2][0] == 'CONST' and IsAttrInstance(t[1], it[2][1]):
if Is3(it[1][1], 'ModuleAttr', '.__dict__'):
o.Stmt('PyDict_SetItem', calc_const_to((it[1][1], '.__dict__')), it[2], ref)
Cls1(o, ref)
return
r = Expr1(it[1], o)
dic = New()
o.Raw(dic, ' = *_PyObject_GetDictPtr(',r,');')
o.INCREF(dic)
Cls1(o, r)
o.Stmt('PyDict_SetItem', dic, it[2], ref)
Cls1(o, dic)
Cls1(o, ref)
return
ref1, ref2 = Expr(o, it[1:])
o.Stmt('PyObject_SetAttr', ref1, ref2, ref)
o.Cls(ref, ref1, ref2)
return
def IsMethod(nmcl, nmslot):
assert type(nmcl) is str and type(nmslot) is str
if Is3(nmcl, ('Method', nmslot)):
return True
elif nmslot[0] == '_' and Is3(nmcl, ('Method', '_' + nmcl + nmslot), nmslot):
return True
else:
return False
def IterMethod(nmslot, nmcode):
li = []
for a,b,c in Iter3(None, None, nmcode):
if b == ('Method', nmslot):
li.append((a,b,c))
elif nmslot[0] == '_' and type(b) is tuple and b[0] == 'Method' and b[1] == '_' + a + c:
li.append((a,b,c))
return li
def IsAnyMethod(nmslot, nmcode):
if Is3(None, ('Method', nmslot), nmcode):
return True
elif nmslot[0] == '_':
li = list(Iter3(None, None, nmcode))
for a,b,c in li:
if b == ('Method', '_' + a + c):
return True
return False
def ValMethod(nmcl, nmslot):
if Is3(nmcl, ('Method', nmslot)):
return Val3(nmcl, ('Method', nmslot))
elif nmslot[0] == '_':
li = list(Iter3(nmcl, None, nmslot))
for a,b,c in li:
if b == ('Method', '_' + a + c):
return nmslot
print nmcl, nmslot
assert False
return None
def CodeInit(nmcl):
return ValMethod(nmcl, '__init__')
attr_instance = {}
def SetAttrInstance(nmcl, nmattr):
attr_instance[(nmcl, nmattr)] = True
def IsFatherAttrInstance(nmcl, nmslot):
for a,b,c in Iter3(nmcl, 'Derived', None):
if c[0] == '!CALC_CONST':
if IsAttrInstance(c[1], nmslot):
return True
return False
def IsAttrInstance(nmcl, nmslot):
if (nmcl, nmslot) in attr_instance and nmslot[0:2] != '__':
return True
elif nmcl is not None and nmslot[0] == '_' and (nmcl, '_' + nmcl + nmslot) in attr_instance:
return True
if IsFatherAttrInstance(nmcl, nmslot):
return True
return False
def IsAnyAttrInstance(nmslot):
for a,c in attr_instance.iterkeys():
if c == nmslot and nmslot[0:2] != '__':
return True
elif nmslot[0] == '_' and c == '_' + a + nmslot:
return True
return False
def generate_GetAttr(it,o, forcenewg, typed):
t = TypeExpr(it[1])
## pprint(('ooo1', it, t, typed))
if not redefined_attribute and it[2][0] == 'CONST' and it[2][1][0:2] != '__' and not is_pypy:
ismeth = len (IterMethod(it[2][1], None)) > 0
if it[1][0] == 'FAST' or (it[1][0] == 'PY_TYPE' and it[1][3][0] == 'FAST'):
right_obj = False
if it[1][0] == 'FAST':
nmvar = it[1][1]
else:
if it[1][1] == 'NewClassInstance' or it[1][1] == 'OldClassInstance':
right_obj = True
nmvar = it[1][3][1]
isattrs = IsAnyAttrInstance(it[2][1])
if not ismeth and isattrs and nmvar in current_co.co_varnames and \
len([True for i, nm in enumerate(current_co.co_varnames) \
if i < current_co.co_argcount and nm == nmvar]) > 0:
s1 = ('STORE_FAST', nmvar)
s2 = ('DELETE_FAST', nmvar)
srepr = repr(current_co.cmds[1])
if not repr(s1) in srepr and not repr(s2) in srepr:
if right_obj:
ref = New(None, forcenewg)
## o.Raw('GET_ATTR_LOCAL(', ref[1], ', ',it[1][1], ', ', it[2], ', ', labl, ');')
o.Raw(ref, ' = PyDict_GetItem(_', nmvar, '_dict, ', it[2], ');')
o.INCREF(ref)
current_co.dict_getattr_used[nmvar] = True
return ref
ref = New(None, forcenewg)
## o.Raw('GET_ATTR_LOCAL(', ref[1], ', ',it[1][1], ', ', it[2], ', ', labl, ');')
o.Raw('if (_' + nmvar + '_dict && (',ref, ' = PyDict_GetItem(_', nmvar, '_dict, ', it[2], ')) != 0) {')
o.INCREF(ref)
current_co.dict_getattr_used[nmvar] = True
o.append('} else {')
o.Stmt(ref, '=', 'PyObject_GetAttr', it[1], it[2])
o.append('}')
return ref
if not ismeth and t is not None and t[0] != 'MayBe' and IsAttrInstance(t[1], it[2][1]) and not is_pypy:
if t[0] == T_OLD_CL_INST:
if it[1][0] == 'CALC_CONST':
if Is3(it[1][1], 'ModuleAttr', '.__dict__'):
ref = New(None, forcenewg)
o.Stmt(ref, '=', 'PyDict_GetItem', calc_const_to((it[1][1], '.__dict__')), it[2])
return ref
r = Expr1(it[1], o)
ref = New(None, forcenewg)
o.Stmt(ref, '=', 'PyDict_GetItem', '((PyInstanceObject *)' + CVar(r) + ')->in_dict', it[2])
Cls1(o, r)
return ref
elif t[0] == T_NEW_CL_INST:
if it[1][0] == 'CALC_CONST':
if Is3(it[1][1], 'ModuleAttr', '.__dict__'):
ref = New(None, forcenewg)
o.Stmt(ref, '=', 'PyDict_GetItem', calc_const_to((it[1][1], '.__dict__')), it[2])
return ref
r = Expr1(it[1], o)
dic = New()
o.Raw(dic, ' = *_PyObject_GetDictPtr(',r,');')
o.INCREF(dic)
Cls1(o, r)
ref = New(None, forcenewg)
o.Stmt(ref, '=', 'PyDict_GetItem', dic, it[2])
Cls1(o, dic)
return ref
elif t is not None and t[0] is types.ModuleType:
if t[1] is not None and ModuleHaveAttr(t[1], it[2][1]):
r = Expr1(it[1], o)
ref = New(None, forcenewg)
o.Raw('if ((', ref, ' = PyDict_GetItem(PyModule_GetDict(' + CVar(r) + '), ', it[2], ')) == 0) goto ', labl, ';')
o.INCREF(ref)
Cls1(o, r)
## o.Raw('if (', ref, ' == 0) goto ', labl, ';')
UseLabl()
return ref
if t is not None:
Debug('Non-Generic GetAttr type', t, it[2], it[1], current_co.co_name)
## Fatal('')
if it[2][1] == '?':
Fatal('', it)
Debug('Standard Getattr', it)
ref,attr = [Expr1(x, o) if type(x) is tuple and len(x) > 0 else x \
for i,x in enumerate(it) if i > 0]
newg = New(None, forcenewg)
o.Stmt(newg, '=', 'PyObject_GetAttr', ref, attr)
o.Cls(ref,attr)
return newg
def IsAnyClass(nm):
return nm in calc_const_old_class or nm in calc_const_new_class
def verif(it, o):
if it[0] in ('!MK_FUNK', '!CALL_CALC_CONST', '!STR_CONCAT', '!STR_CONCAT3', '!STR_CONCAT2', '!STR_CONCAT_N', \
'!CLASS_CALC_CONST_NEW', '!IMPORT_NAME', '!PyObject_Call', '!PyDict_GetItem',\
'!PyInt_Type.tp_str', '!PyCFunction_Call', '!_PyEval_BuildClass',\
'!PyDict_Items', '!PyDict_Keys', '!PyList_AsTuple', '!PyString_Format',\
'!_PyList_Extend', '!PyDict_Copy', '!PyDict_Values'):
return
typs = tuple([TypeExpr(x) if type(x) is tuple and len(x) > 0 else None for i,x in enumerate(it) if i > 0])
typs2 = [x for x in typs if x is not None]
if it[0] == '!c_LOAD_NAME' and typs == (None, Kl_String):
return
if len(typs2) > 0:
Debug('Concret type operation %s %s -- %s' % (it[0], tuple(typs), it))
## def find_singles_goto(o):
## li = {}
## for i, s in enumerate(o):
## if s.startswith("goto ") and s.endswith(";") and ' ' not in s[5:-1]:
## li[i] = s[5:-1]
## lii = {}
## for label in li.itervalues():
## if label in lii:
## lii[label] += 1
## else:
## lii[label] = 1
## lis = [label for label in li.itervalues() if lii[label] > 1]
## return li, lis
### UNUSED ??? 01.01.2012
## def join_before_goto(o):
## while True:
## li, lis = find_singles_goto(o)
## toupdate = []
## toappend = []
## for label in lis:
## lines = [line for line in li.iterkeys() if li[line] == label]
## lines,leng = find_like_tail(lines, o)
## if leng > 0 and newlabel is not None:
## newlabel = New('label')
## toappend.append(o[line-leng:line], newlabel)
## for line in lines:
## toupdate.append((line, leng, newlabel))
## if len(toupdate) == 0:
## break
## toupdate.sort()
## update_tailed_gotos(o, toupdate)
## append_extracted(o, toappend)
## def find_like_tail(lines, o):
## if len(lines) <= 1:
## return [], 0
## leng = 2
## while True:
## pass
def check_GenExpr_warn(it, forcenewg):
_v = []
if forcenewg is not None and it[0] in tags_one_step_expr:
Debug('Copy unhandled', forcenewg, '=', it)
if TCmp(it, _v, ('!PyObject_Call', ('!PyObject_GetAttr', '?', ('CONST', '?')), '?', '?')):
t = TypeExpr(_v[0])
if t is not None and _v[3] == ('NULL',):
if t not in _Kl_Simples and type(t[1]) is str:
if IsAnyClass(t[1]) and not Is3(t[1], ('Attribute', _v[1])):
if IsAttrInstance(t[1], _v[1]):
pass
elif not IsMethod(t[1], _v[1]):
Debug( 'Call UNKNOWN method known classes: %s -> %s' % (t, _v[1]),it)
## if _v[1] == 'append':
## Fatal('')
else:
HideDebug( 'Call method known classes: %s -> %s' % (t, _v[1]),it)
if type(it) is tuple and len(it) == 3 and type(it[0]) is str and \
type(it[1]) is tuple and len(it[1]) >= 1 and it[1][0] == 'CONST' and \
type(it[2]) is tuple and len(it[2]) >= 1 and it[2][0] == 'CONST':
if it[2] != ('CONST', 'join'):
Debug('Constant binary operation unhandled', it)
if type(it) is tuple and len(it) == 2 and type(it[0]) is str and \
type(it[1]) is tuple and len(it[1]) >= 1 and it[1][0] == 'CONST':
Debug('Constant unary operation unhandled', it)
if type(it) is tuple:
if len(it) > 1 and IsCVar(it[1]):
Debug('Operation of typed var', it)
if len(it) > 2 and IsCVar(it[2]):
Debug('Operation of typed var', it)
def GenExpr(it,o, forcenewg=None,typed=None, skip_float = None):
global _n2c, g_acc2, g_refs2
if not hide_debug:
check_GenExpr_warn(it, forcenewg)
for ind,x in enumerate(g_acc2):
if it == x:
if it[0] == 'CONST' and type(x[1]) != type(it[1]):
continue
ind = g_acc2.index(it)
assert forcenewg is None or forcenewg == g_refs2[ind]
if forcenewg is None or forcenewg == g_refs2[ind]:
return g_refs2[ind]
if type(it) is int:
return it
head = it[0]
if head == 'PY_TYPE':
if it[3][0] == 'PY_TYPE':
if it[0:3] == it[3][0:3]:
it = it[3]
if it[3][0] == 'PY_TYPE':
pprint(current_co)
pprint(it)
assert it[3][0] != 'PY_TYPE'
if typed is not None:
Debug(typed, it[4], it)
assert typed == it[4]
if typed is None and it[4] is not None:
Debug('Unhandled C-type', it)
if it[1] is float:
return GenExpr(it[3],o,forcenewg, typed, False)
else:
return GenExpr(it[3],o,forcenewg, typed, True)
if not isinstance(head, types.StringTypes) and type(head) != int:
pprint(head)
pprint(it)
assert isinstance(head, types.StringTypes) or type(head) is int
# o.append('/*---*/')
tempor = False
if head == 'FAST':
pos = current_co.co_varnames.index(it[1])
typed_arg = current_co.typed_arg_direct
if pos in typed_arg and is_current & IS_DIRECT:
t = typed_arg[pos]
if IsCType(t):
cnm = CVarName(it)
ref2 = New(None,forcenewg)
CType2Py(o, ref2, cnm, t)
return ref2
if it[1] in current_co.detected_type:
t = current_co.detected_type[it[1]]
if IsCType(t):
cnm = CVarName(it)
ref2 = New(None,forcenewg)
CType2Py(o, ref2, cnm, t)
return ref2
if head[0] == '!':
tempor = True
head = head[1:]
elif head[0] == '=':
head = 'INPLACE_' + head[1:]
tempor = True
if not tempor:
if len(it) > 1:
if not head in tags_one_step_expr:
Fatal('', it, len(it))
assert head in tags_one_step_expr
return it
if tempor and head == 'LOAD_NAME' and func == 'Init_filename':
return GenExpr(('!LOAD_GLOBAL', it[1]),o, forcenewg)
if tempor and head == 'LOAD_NAME':
return GenExpr(('!c_LOAD_NAME', 'f', ('CONST', it[1])),o, forcenewg)
if tempor and head == 'LOAD_GLOBAL' and it[1] not in d_built and it[1][0] != '_' and not redefined_all:
if build_executable and not global_used_at_generator(it[1]):
if IsCTypedGlobal(it[1]):
t = TypeGlobal(it[1])
cnm = CVarName(it)
ref2 = New(None,forcenewg)
CType2Py(o, ref2, cnm, t)
return ref2
## else:
## if is_typed_global(it[1]):
## ref2 = New(None,forcenewg)
## o.PushInt(ref2, 'Glob_long_' + it[1])
## return ref2
## if is_typed_global_char(it[1]):
## ref2 = New(None,forcenewg)
## o.Raw(ref2, ' = PyString_FromStringAndSize(&Glob_char_', it[1], ', 1);')
## return ref2
return it
ref = New(None, forcenewg)
o_2 = Out()
o_2.Raw('PyErr_Format(PyExc_NameError, GLOBAL_NAME_ERROR_MSG, ', '"%s"' % it[1], ');')
o_2.Raw('goto ', labl, ';')
tolabl = append_to_exception(o_2)
o.Raw('if ((', ref, ' = PyDict_GetItem( glob, ', ('CONST', it[1]), ')) == 0) goto ', tolabl, ';')
UseLabl()
o.INCREF(ref)
return ref
if head == 'CALC_CONST' and it[1] not in d_built and it[1][0] != '_' and not redefined_all:
if build_executable and not global_used_at_generator(it[1]):
if IsCTypedGlobal(it[1]):
t = TypeGlobal(it[1])
cnm = CVarName(it)
ref2 = New(None,forcenewg)
CType2Py(o, ref2, cnm, t)
return ref2
if tempor and head == 'LOAD_GLOBAL':
return GenExpr(('!c_LOAD_GLOBAL', ('CONST', it[1]), hash(it[1])),o, forcenewg)
if head == 'LOAD_BUILTIN':
return ('BUILTIN', it[1])
if head in ('OR_JUMPED_STACKED', 'AND_JUMPED_STACKED'):
ref = forcenewg
if ref is None:
ref = New()
return generate_and_or_jumped_stacked(it[1:], o, ref, head == 'AND_JUMPED_STACKED', 0)
if head in ('AND_BOOLEAN', 'OR_BOOLEAN'):
o1, logic = generate_logical_expr(it)
o.extend(o1)
return logic
if head in ('AND_JUMP', 'OR_JUMP'):
o1,logic = shortage(generate_logical_expr(it))
o.extend(o1)
ref = New(None, forcenewg)
o.Stmt(ref, '=','PyBool_FromLong', logic)
Cls1(o, logic)
return ref
if head == 'PyList_GetSlice':
ref1 = Expr1(it[1], o)
if it[2] < 0:
it1 = New('long')
o.Raw(it1, ' = PyList_GET_SIZE( ', ref1, ' ) - ', abs (it[2]), ';')
o.Raw('if (', it1, ' < 0) { ', it1, ' = 0; }')
else:
it1 = it[2]
if it[3] < 0:
it2 = New('long')
o.Raw(it2, ' = PyList_GET_SIZE( ', ref1, ' ) - ', abs (it[3]), ';')
o.Raw('if (', it2, ' < 0) { ', it2, ' = 0; }')
else:
it2 = it[3]
ref = New(None, forcenewg)
o.Raw('if ((', ref, ' = PyList_GetSlice( ', ref1, ' , ', it1, ' , ', it2, ' )) == 0) goto ', labl, ';')
UseLabl()
o.Cls(ref1, it1, it2)
return ref
if head == 'PyTuple_GetSlice':
ref1 = Expr1(it[1], o)
if it[2] < 0:
it1 = New('long')
o.Raw(it1, ' = PyTuple_GET_SIZE( ', ref1, ' ) - ', abs (it[2]), ';')
o.Raw('if (', it1, ' < 0) { ', it1, ' = 0; }')
else:
it1 = it[2]
if it[3] < 0:
it2 = New('long')
o.Raw(it2, ' = PyTuple_GET_SIZE( ', ref1, ' ) - ', abs (it[3]), ';')
o.Raw('if (', it2, ' < 0) { ', it2, ' = 0; }')
else:
it2 = it[3]
ref = New(None, forcenewg)
o.Raw('if ((', ref, ' = PyTuple_GetSlice( ', ref1, ' , ', it1, ' , ', it2, ' )) == 0) goto ', labl, ';')
UseLabl()
o.Cls(ref1, it1, it2)
return ref
if head == 'COND_METH_EXPR':
return generate_cond_meth_expr_new(it, o, forcenewg, False)
if head == 'BUILD_TUPLE':
li = []
repeat_expr = {}
for x in it[1]:
g = Expr1(x, o)
if not istempref(g):
o.INCREF(g)
li.append(g)
elif g in g_refs2:
if g in repeat_expr:
Fatal('Repeated expr', it, repeat_expr, g)
gg = New()
o.Raw(gg, ' = ', g, ';')
o.INCREF(gg)
li.append(gg)
repeat_expr[gg] = True
else:
li.append(g)
newg = New(None,forcenewg)
o.Stmt(newg,'=', 'PyTuple_New', len(it[1]))
for i,g in enumerate(li):
o.Stmt('PyTuple_SET_ITEM', newg, i, g)
if g not in g_refs2:
o.ZeroTemp(g)
o.ClsFict(g)
return newg
if head == 'GET_ITER':
ref = Expr1(it[1], o)
ref2 = New(None,forcenewg)
o.Stmt(ref2, '=', 'PyObject_GetIter', ref)
return ref2
if head == 'PySequence_Repeat':
#### Trouble at count < 0
if IsList(TypeExpr(it[1])) and it[1][0] == '!BUILD_LIST':
Debug('Repeat list n', it[1], it[2])
if it[1][0] == 'CONST' and type(it[1][1]) is str and len(it[1][1]) == 1 and IsInt(TypeExpr(it[2])):
if it[2][0] == 'CONST' and it[2][1] <= 0:
ref2 = New(None,forcenewg)
o.Stmt(ref2, '=', 'PyString_FromStringAndSize', 'NULL', 0)
return ref2
elif it[2][0] == 'CONST' and it[2][1] > 0:
n2 = it[2][1]
ref2 = New(None,forcenewg)
o.Stmt(ref2, '=', 'PyString_FromStringAndSize', 'NULL', n2)
cref = New('charref')
o.Raw(cref, ' = ', PyString_AS_STRING(ref2), ';')
n1 = New('Py_ssize_t')
o.Raw('for(', n1, ' = 0; ', n1, ' < ', n2, '; ', n1, '++){')
o.Raw(cref, '[', n1, '] = ', str(ord(it[1][1])), ';')
o.append('}')
o.Cls(n1, cref)
return ref2
else:
if it[2][0] == 'CONST':
n2 = it[2][1]
else:
n2 = New('Py_ssize_t')
n = Expr1(it[2], o)
o.Stmt(n2, '=', 'PyInt_AsSsize_t', n)
Cls1(o, n)
ref2 = New(None,forcenewg)
o.Raw('if (', n2, ' <= 0) {')
o.Stmt(ref2, '=', 'PyString_FromStringAndSize', 'NULL', 0)
o.append('} else {')
o.Stmt(ref2, '=', 'PyString_FromStringAndSize', 'NULL', n2)
cref = New('charref')
o.Raw(cref, ' = ', PyString_AS_STRING(ref2), ';')
n1 = New('Py_ssize_t')
o.Raw('for(', n1, ' = 0; ', n1, ' < ', n2, '; ', n1, '++){')
o.Raw(cref, '[', n1, '] = ', str(ord(it[1][1])), ';')
o.append('}')
o.Cls(n1, n2, cref)
o.append('}')
return ref2
if IsInt(TypeExpr(it[2])):
ref = Expr1(it[1], o)
if it[2][0] == 'CONST':
n2 = it[2][1]
else:
n = Expr1(it[2], o)
n2 = New('Py_ssize_t')
o.Stmt(n2, '=', 'PyInt_AsSsize_t', n)
Cls1(o, n)
ref2 = New(None,forcenewg)
o.Stmt(ref2, '=', 'PySequence_Repeat', ref, n2)
Cls1(o, ref)
Cls1(o, n2)
return ref2
verif(it, o)
ref1 = Expr1(it[1], o)
ref2 = Expr1(it[2], o)
if forcenewg is not None:
new = forcenewg
else:
new = New()
o.Stmt(new, '=', 'PyNumber_Multiply', ref1, ref2)
o.Cls(ref1, ref2)
return new
if head == 'PySequence_GetSlice' and TypeExpr(it[1]) == Kl_String:
if type(it[2]) is int and it[3] == 'PY_SSIZE_T_MAX' and it[2] >= 0:
ref1 = Expr1(it[1], o)
ref = New()
o.Raw('if (PyString_GET_SIZE(', ref1,') > ', it[2], ') {')
o.Raw(ref, ' = PyString_FromStringAndSize( ', PyString_AS_STRING(ref1), ' + ', it[2], ' , PyString_GET_SIZE(', ref1,') - ', it[2], ');')
o.append('} else {')
o.Raw(ref, ' = PyString_FromStringAndSize( \"\" , 0);')
o.append('}')
Cls1(o, ref1)
return ref
Debug('Typed GetSlice of string', it)
if head == 'BUILD_LIST':
li = []
repeat_expr = {}
for x in it[1]:
g = Expr1(x, o)
if not istempref(g):
o.INCREF(g)
li.append(g)
elif g in g_refs2:
if g in repeat_expr:
Fatal('Repeated expr', it, repeat_expr, g)
gg = New()
o.Raw(gg, ' = ', g, ';')
o.INCREF(gg)
li.append(gg)
repeat_expr[gg] = True
else:
li.append(g)
newg = New(None,forcenewg)
o.Stmt(newg,'=', 'PyList_New', len(it[1]))
for i,g in enumerate(li):
o.Stmt('PyList_SET_ITEM', newg, i, g)
if g not in g_refs2:
o.ZeroTemp(g)
o.ClsFict(g)
return newg
if head == 'IMPORT_NAME':
return generate_import_name(it, o)
if head == 'BUILD_SET':
ret = New(None, forcenewg)
o.Stmt(ret , '=', 'PySet_New', 'NULL')
for v in it[1]:
v = Expr1(v, o)
o.Stmt('PySet_Add', ret, v)
Cls1(o, v)
return ret
if head == 'BUILD_MAP':
ret = New(None, forcenewg)
if len(it[1]) > 5 and not is_pypy:
o.Stmt(ret,'=', '_PyDict_NewPresized', len(it[1]))
else:
o.Stmt(ret,'=', 'PyDict_New')
for k, v in it[1]:
k = Expr1(k, o)
v = Expr1(v, o)
o.Stmt('PyDict_SetItem', ret, k, v)
o.Cls(k, v)
return ret
if head == 'MK_CLOSURE':
assert len(it) == 4
co = _n2c[it[1]]
if not co.can_be_codefunc(): ## co.co_flags & CO_GENERATOR:
ref1 = New()
o.Stmt(ref1, '=', 'PyFunction_New', const_to(co), 'glob')
ref2 = Expr1(it[2], o)
o.Stmt('PyFunction_SetClosure', ref1, ref2)
Cls1(o, ref2)
if it[3][0] == 'CONST' and type(it[3][1]) is tuple:
if len(it[3][1]) > 0:
o.Stmt('PyFunction_SetDefaults', ref1, it[3])
return ref1
if it[3][0] == '!BUILD_TUPLE' and type(it[3][1]) is tuple:
ref2 = Expr1(it[3], o)
o.Stmt('PyFunction_SetDefaults', ref1, ref2)
Cls1(o, ref2)
return ref1
Fatal('GenExpr', it)
ref1 = New()
o.Stmt(ref1, '=', 'Py2CFunction_New', const_to( _n2c[it[1]]))
ref2 = Expr1(it[2], o)
o.Stmt('Py2CFunction_SetClosure', ref1, ref2)
Cls1(o, ref2)
if it[3][0] == 'CONST' and type(it[3][1]) is tuple:
if len(it[3][1]) > 0:
o.Stmt('Py2CFunction_SetDefaults', ref1, it[3])
return ref1
if it[3][0] == '!BUILD_TUPLE' and type(it[3][1]) is tuple:
ref2 = Expr1(it[3], o)
o.Stmt('Py2CFunction_SetDefaults', ref1, ref2)
Cls1(o, ref2)
return ref1
Fatal('GenExpr', it)
if head == 'LOAD_CLOSURE':
return ('LOAD_CLOSURE', it[1])
if head == 'LOAD_DEREF':
return GenExpr(('!PyCell_Get',('LOAD_CLOSURE', it[1])), o, forcenewg, typed)
if head == 'MK_FUNK':
co = _n2c[it[1]]
if not co.can_C():
if len(it) == 3 and it[2][0] == 'CONST' and type(it[2][1]) is tuple:
ref1 = New(None, forcenewg)
if len(it[2][1]) > 0: # or len(co.co_cellvars + co.co_freevars) != 0:
o.Stmt(ref1, '=', 'PyFunction_New', const_to(co), 'glob')
o.Stmt('PyFunction_SetDefaults', ref1, it[2])
else:
o.Stmt(ref1, '=', 'PyFunction_New', const_to( co), 'glob')
return ref1
if len(it) == 3 and it[2][0] == '!BUILD_TUPLE' and type(it[2][1]) is tuple:
ref1 = New(None, forcenewg)
o.Stmt(ref1, '=', 'PyFunction_New', const_to(co), 'glob')
ref2 = Expr1(it[2], o)
o.Stmt('PyFunction_SetDefaults', ref1, ref2)
Cls1(o, ref2)
return ref1
Fatal('GenExpr', it)
return None
if co.can_be_cfunc():
if len(it) == 3 and it[2][0] == '!BUILD_TUPLE' and type(it[2][1]) is tuple and len(it[2][1]) > 0:
ref = Expr1(it[2], o)
if not istempref(ref):
o.INCREF(ref)
nmdefault = '__default_arg___' + co.cmds[0][1]
add_fast_glob(nmdefault)
o.Stmt('SETSTATIC', nmdefault, ref)
o.ClsFict(ref)
if istempref(ref) and ref not in g_refs2:
o.Raw(ref, ' = 0;')
ref = None
ref1 = New(None, forcenewg)
met, ismeth = type_methfunc(co)
if not ismeth:
o.Raw(ref1, ' = PyCFunction_New ( &methfunc_', co.cmds[0][1], ', NULL);')
else:
o.Raw(ref1, ' = __pyx_binding_PyCFunctionType_NewEx ( &methfunc_', co.cmds[0][1], ', NULL, NULL);')
Used('__pyx_binding_PyCFunctionType_NewEx')
return ref1
if co.can_be_codefunc():
if len(it) == 3 and it[2][0] == 'CONST' and type(it[2][1]) is tuple:
ref1 = New(None, forcenewg)
if len(it[2][1]) > 0: # or len(co.co_cellvars + co.co_freevars) != 0:
o.Stmt(ref1, '=', 'Py2CFunction_New', const_to( co))
o.Stmt('Py2CFunction_SetDefaults', ref1, it[2])
else:
o.Stmt(ref1, '=', 'Py2CFunction_New', const_to( co))
return ref1
if len(it) == 3 and it[2][0] == '!BUILD_TUPLE' and type(it[2][1]) is tuple:
ref1 = New(None, forcenewg)
o.Stmt(ref1, '=', 'Py2CFunction_New', const_to(co))
ref2 = Expr1(it[2], o)
o.Stmt('Py2CFunction_SetDefaults', ref1, ref2)
Cls1(o, ref2)
return ref1
Fatal('GenExpr', it)
if head == 'BINARY_SUBSCR_Int':
ref = Expr1(it[1], o)
ref1 = New(None, forcenewg)
t = TypeExpr(it[1])
islist = IsListAll(t)
if IsDict(t):
ref2 = GenExpr(it[2], o, None, None, True)
o_2 = Out()
tupl = New()
o_2.Raw('if ((', tupl, ' = PyTuple_Pack(1, ', ref2, ')) == 0) goto ', labl, ';')
o_2.Raw('PyErr_SetObject(PyExc_KeyError, ', tupl, ');')
Cls1(o_2, tupl)
o_2.Raw('goto ', labl, ';')
tolabl = append_to_exception(o_2)
o.Raw('if ((', ref1, ' = PyDict_GetItem(', ref, ', ', ref2, ')) == 0) goto ', tolabl, ';')
UseLabl()
o.INCREF(ref1)
o.Cls(ref, ref2)
return ref1
elif IsTuple(t):
if it[2][1] >= 0:
## o.Stmt(ref1, '=', 'PyTuple_GetItem', ref, it[2][1])
GetTupleItem(o, t, ref1, ref, it[2][1])
else:
o.Stmt(ref1, '=', 'PyTuple_GetItem', ref, 'PyTuple_GET_SIZE(' + CVar(ref) + ') ' + str(it[2][1]))
elif IsStr(t): # after. Too many low-lewel code.
if it[2][0] == 'CONST' and type(it[2][1]) is int and it[2][1] >= 0:
o.Raw('if (PyString_GET_SIZE( ', ref, ' ) > ', it[2][1], ') {')
o.Raw(ref1, ' = PyString_FromStringAndSize(PyString_AS_STRING(', ref, ')+', it[2][1], ', 1);')
o.append('} else {')
o.Raw('if ((', ref1, ' = PyObject_GetItem (', ref, ' , ', it[2], ' )) == 0) goto ', labl, ';')
UseLabl()
o.append('}')
return ref1
if it[2][0] == 'CONST' and type(it[2][1]) is int and it[2][1] == -1:
o.Raw('if (PyString_GET_SIZE( ', ref, ' ) > 0) {')
o.Raw(ref1, ' = PyString_FromStringAndSize(PyString_AS_STRING(', ref, ')+(PyString_GET_SIZE( ', ref, ' )-1), 1);')
o.append('} else {')
o.Raw('if ((', ref1, ' = PyObject_GetItem (', ref, ' , ', it[2], ' )) == 0) goto ', labl, ';')
UseLabl()
o.append('}')
return ref1
o.Stmt(ref1, '=', 'PyObject_GetItem', ref, it[2])
elif expand_BINARY_SUBSCR or islist:
if not islist:
o.Stmt('if (PyList_CheckExact(', ref, ')) {')
if it[2][1] >= 0:
o.Stmt(ref1, '=', 'PyList_GetItem', ref, it[2][1])
else:
o.Stmt(ref1, '=', 'PyList_GetItem', ref, 'PyList_GET_SIZE(' + CVar(ref) + ') ' + str(it[2][1]))
if not islist:
o.append('} else {')
o.Stmt(ref1, '=', 'PyObject_GetItem', ref, it[2])
o.append('}')
else:
verif(it, o)
if t is not None and t != Kl_Buffer:
Debug('not None', it, t)
o.Stmt(ref1, '=', 'PyObject_GetItem', ref, it[2])
else:
o.Stmt(ref1, '=', '_c_BINARY_SUBSCR_Int', ref, it[2][1], it[2])
Cls1(o, ref)
return ref1
if head == 'from_ceval_BINARY_SUBSCR':
return generate_from_ceval_binary_subscr(it, o, forcenewg)
if head == '_PyString_StartSwith':
assert IsStr(TypeExpr(it[1])) #, TypeExpr(it[1]), it[1]
if it[2][0] == 'CONST' and type(it[2][1]) is str:
ref0 = Expr1(it[1], o)
s_l, s_ref, ref = New('Py_ssize_t'), New('charref'), New(None, forcenewg)
o.Stmt('PyString_AsStringAndSize', ref0, ('&', s_ref), ('&', s_l))
cond = CVar(s_l) + ' >= ' + str(len(it[2][1]))
cond += ' && 0 == memcmp(' + Str_for_C(it[2][1]) + ', ' + CVar(s_ref) + ', ' + str(len(it[2][1])) + ')'
o.Stmt(ref, '=', 'PyBool_FromLong', cond)
o.Cls(s_l, s_ref, ref0)
return ref
ref0 = Expr1(it[1], o)
ref1 = Expr1(it[2], o)
s_l, s_ref, ref = New('Py_ssize_t'), New('charref'), New(None, forcenewg)
o.Stmt('PyString_AsStringAndSize', ref0, ('&', s_ref), ('&', s_l))
s_l_, s_ref_ = New('Py_ssize_t'), New('charref')
o.Stmt('PyString_AsStringAndSize', ref1, ('&', s_ref_), ('&', s_l_))
cond = CVar(s_l) + ' >= ' + CVar(s_l_)
cond += ' && 0 == memcmp(' + CVar(s_ref_) + ', ' + CVar(s_ref) + ', ' + CVar(s_l_) + ')'
o.Stmt(ref, '=', 'PyBool_FromLong', cond)
o.Cls(s_l, s_ref, ref0)
o.Cls(s_l_, s_ref_, ref1)
return ref
if head == '_PyString_Contains':
assert IsStr(TypeExpr(it[1])) #, TypeExpr(it[1]), it[1]
if it[2][0] == 'CONST' and type(it[2][1]) is str:
ref0 = Expr1(it[1], o)
s_l, ref = New('Py_ssize_t'), New(None, forcenewg)
o.Stmt(s_l, '=', 'PyString_GET_SIZE', ref0)
cond = CVar(s_l) + ' >= ' + str(len(it[2][1]))
cond += ' && fastsearch( PyString_AS_STRING(' + CVar(ref0) + '), ' + CVar(s_l) + ', ' + Str_for_C(it[2][1]) + ', ' + str(len(it[2][1])) + ', -1, FAST_SEARCH) >= 0'
Used('fastsearch')
o.Stmt(ref, '=', 'PyBool_FromLong', cond)
o.Cls(s_l, ref0)
return ref
ref0 = Expr1(it[1], o)
ref1 = Expr1(it[2], o)
s_l, s_ref, ref = New('Py_ssize_t'), New('charref'), New(None, forcenewg)
o.Stmt('PyString_AsStringAndSize', ref0, ('&', s_ref), ('&', s_l))
s_l_, s_ref_ = New('Py_ssize_t'), New('charref')
o.Stmt('PyString_AsStringAndSize', ref1, ('&', s_ref_), ('&', s_l_))
## cond = CVar(s_l) + ' >= ' + CVar(s_l_)
## cond += ' && 0 == memcmp(' + CVar(s_ref_) + ', ' + CVar(s_ref) + ', ' + CVar(s_l_) + ')'
cond = CVar(s_l) + ' >= ' + CVar(s_l_)
cond += ' && fastsearch(' + CVar(s_ref) + ', ' + CVar(s_l) + ', ' + CVar(s_ref_) + ', ' + CVar(s_l_) + ', -1, FAST_SEARCH) >= 0'
Used('fastsearch')
o.Stmt(ref, '=', 'PyBool_FromLong', cond)
o.Cls(s_l, s_ref, ref0)
o.Cls(s_l_, s_ref_, ref1)
return ref
if head == '_PyString_Find':
assert IsStr(TypeExpr(it[1])) #, TypeExpr(it[1]), it[1]
if it[2][0] == 'CONST' and type(it[2][1]) is str:
ref0 = Expr1(it[1], o)
s_l, ref = New('Py_ssize_t'), New(None, forcenewg)
o.Stmt(s_l, '=', 'PyString_GET_SIZE', ref0)
cond = 'fastsearch( PyString_AS_STRING(' + CVar(ref0) + '), ' + CVar(s_l) + ', ' + Str_for_C(it[2][1]) + ', ' + str(len(it[2][1])) + ', -1, FAST_SEARCH)'
Used('fastsearch')
o.Stmt(ref, '=', 'PyInt_FromLong', cond)
o.Cls(s_l, ref0)
return ref
ref0 = Expr1(it[1], o)
ref1 = Expr1(it[2], o)
s_l, s_ref, ref = New('Py_ssize_t'), New('charref'), New(None, forcenewg)
o.Stmt('PyString_AsStringAndSize', ref0, ('&', s_ref), ('&', s_l))
s_l_, s_ref_ = New('Py_ssize_t'), New('charref')
o.Stmt('PyString_AsStringAndSize', ref1, ('&', s_ref_), ('&', s_l_))
## cond = CVar(s_l) + ' >= ' + CVar(s_l_)
## cond += ' && 0 == memcmp(' + CVar(s_ref_) + ', ' + CVar(s_ref) + ', ' + CVar(s_l_) + ')'
cond = 'fastsearch(' + CVar(s_ref) + ', ' + CVar(s_l) + ', ' + CVar(s_ref_) + ', ' + CVar(s_l_) + ', -1, FAST_SEARCH)'
Used('fastsearch')
o.Stmt(ref, '=', 'PyInt_FromLong', cond)
o.Cls(s_l, s_ref, ref0)
o.Cls(s_l_, s_ref_, ref1)
return ref
if head == '_PyString_RFind':
assert IsStr(TypeExpr(it[1])) #, TypeExpr(it[1]), it[1]
if it[2][0] == 'CONST' and type(it[2][1]) is str:
ref0 = Expr1(it[1], o)
s_l, ref = New('Py_ssize_t'), New(None, forcenewg)
o.Stmt(s_l, '=', 'PyString_GET_SIZE', ref0)
cond = 'fastsearch( PyString_AS_STRING(' + CVar(ref0) + '), ' + CVar(s_l) + ', ' + Str_for_C(it[2][1]) + ', ' + str(len(it[2][1])) + ', -1, FAST_RSEARCH)'
Used('fastsearch')
o.Stmt(ref, '=', 'PyInt_FromLong', cond)
o.Cls(s_l, ref0)
return ref
ref0 = Expr1(it[1], o)
ref1 = Expr1(it[2], o)
s_l, s_ref, ref = New('Py_ssize_t'), New('charref'), New(None, forcenewg)
o.Stmt('PyString_AsStringAndSize', ref0, ('&', s_ref), ('&', s_l))
s_l_, s_ref_ = New('Py_ssize_t'), New('charref')
o.Stmt('PyString_AsStringAndSize', ref1, ('&', s_ref_), ('&', s_l_))
## cond = CVar(s_l) + ' >= ' + CVar(s_l_)
## cond += ' && 0 == memcmp(' + CVar(s_ref_) + ', ' + CVar(s_ref) + ', ' + CVar(s_l_) + ')'
cond = 'fastsearch(' + CVar(s_ref) + ', ' + CVar(s_l) + ', ' + CVar(s_ref_) + ', ' + CVar(s_l_) + ', -1, FAST_RSEARCH)'
Used('fastsearch')
o.Stmt(ref, '=', 'PyInt_FromLong', cond)
o.Cls(s_l, s_ref, ref0)
o.Cls(s_l_, s_ref_, ref1)
return ref
if head == '_PyString_Index':
assert IsStr(TypeExpr(it[1])) #, TypeExpr(it[1]), it[1]
if it[2][0] == 'CONST' and type(it[2][1]) is str:
ref0 = Expr1(it[1], o)
s_l, ref = New('Py_ssize_t'), New(None, forcenewg)
o.Stmt(s_l, '=', 'PyString_GET_SIZE', ref0)
cond = 'fastsearch( PyString_AS_STRING(' + CVar(ref0) + '), ' + CVar(s_l) + ', ' + Str_for_C(it[2][1]) + ', ' + str(len(it[2][1])) + ', -1, FAST_SEARCH)'
Used('fastsearch')
l_3 = New('Py_ssize_t')
o.Raw('if ((', l_3, ' = ', cond, ') == -1) {')
o.Raw('PyErr_SetString(PyExc_ValueError, "substring not found");')
o.Raw('goto ', labl, ';')
UseLabl()
o.Raw('}')
o.Stmt(ref, '=', 'PyInt_FromLong', l_3)
o.Cls(s_l, ref0, l_3)
return ref
ref0 = Expr1(it[1], o)
ref1 = Expr1(it[2], o)
s_l, s_ref, ref = New('Py_ssize_t'), New('charref'), New(None, forcenewg)
o.Stmt('PyString_AsStringAndSize', ref0, ('&', s_ref), ('&', s_l))
s_l_, s_ref_ = New('Py_ssize_t'), New('charref')
o.Stmt('PyString_AsStringAndSize', ref1, ('&', s_ref_), ('&', s_l_))
## cond = CVar(s_l) + ' >= ' + CVar(s_l_)
## cond += ' && 0 == memcmp(' + CVar(s_ref_) + ', ' + CVar(s_ref) + ', ' + CVar(s_l_) + ')'
cond = 'fastsearch(' + CVar(s_ref) + ', ' + CVar(s_l) + ', ' + CVar(s_ref_) + ', ' + CVar(s_l_) + ', -1, FAST_SEARCH)'
Used('fastsearch')
l_3 = New('Py_ssize_t')
o.Raw('if ((', l_3, ' = ', cond, ') == -1) {')
o.Raw('PyErr_SetString(PyExc_ValueError, "substring not found");')
o.Raw('goto ', labl, ';')
UseLabl()
o.Raw('}')
o.Stmt(ref, '=', 'PyInt_FromLong', l_3)
o.Cls(s_l, s_ref, ref0), l_3
o.Cls(s_l_, s_ref_, ref1)
return ref
if head == '_PyString_ctype':
if TypeExpr(it[1]) == Kl_Char:
ref0 = Expr1(it[1], o)
cond = it[2] + ' ( *PyString_AS_STRING ( ' + CVar(ref0) + ' ) )'
Used('ctype')
ref = New(None, forcenewg)
o.Stmt(ref, '=', 'PyBool_FromLong', cond)
o.Cls(ref0)
return ref
if TypeExpr(it[1]) == Kl_String:
ref0 = Expr1(it[1], o)
ind = New('Py_ssize_t')
isret = New('int')
o.Raw(isret, ' = 0;')
o.Raw('for(', ind, ' = 0; ', ind, ' < PyString_GET_SIZE ( ', ref0, ' ); ', ind, ' ++) {')
cond = it[2] + ' ( PyString_AS_STRING ( ' + CVar(ref0) + ' )[' + CVar(ind) + '] )'
o.Raw('if (!(',isret, ' = ', cond, ')) break;')
o.Raw('}')
Used('ctype')
ref = New(None, forcenewg)
o.Stmt(ref, '=', 'PyBool_FromLong', isret)
o.Cls(ref0, ind, isret)
return ref
if head == 'PyObject_Hash':
verif(it, o)
ref1 = Expr1(it[1], o)
n1 = New('long')
o.Stmt(n1, '=', head, ref1)
Cls1(o, ref1)
ret = New(typed, forcenewg)
o.PushInt(ret, n1)
Cls1(o, n1)
return ret
if head == '_PyObject_Cmp':
verif(it, o)
ref1 = Expr1(it[1], o)
ref2 = Expr1(it[2], o)
n1 = New('int')
o.Stmt('PyObject_Cmp', ref1, ref2, ('&', n1))
o.Cls(ref1, ref2)
ret = New(typed, forcenewg)
o.PushInt(ret, n1)
Cls1(o, n1)
return ret
if head == '_PyString_EndSwith' and IsStr(TypeExpr(it[1])):
if it[2][0] == 'CONST' and type(it[2][1]) is str:
ref0 = Expr1(it[1], o)
s_l, s_ref, ref = New('Py_ssize_t'), New('charref'), New(None, forcenewg)
o.Stmt('PyString_AsStringAndSize', ref0, ('&', s_ref), ('&', s_l))
cond = CVar(s_l) + ' >= ' + str(len(it[2][1]))
s_i2, s_ref2 = New('int'), New('charref')
o.Stmt(s_i2, '=', s_l, '-', len(it[2][1]))
o.Stmt(s_ref2, '=', s_ref, '+', s_i2)
cond += ' && 0 == memcmp(' + Str_for_C(it[2][1]) + ', ' + CVar(s_ref2) + ', ' + str(len(it[2][1])) + ')'
o.Stmt(ref, '=', 'PyBool_FromLong', cond)
o.Cls(s_l, s_ref, ref0, s_i2, s_ref2)
return ref
Fatal('', it)
if head == '_PyList_Pop':
assert IsList(TypeExpr(it[1]))
ref0 = Expr1(it[1], o)
ref = New(None, forcenewg)
if len(it) == 3:
if it[2][0] == 'CONST':
ind1 = New('long')
if it[2][1] < 0:
o.Raw(ind1, ' = PyList_GET_SIZE(', ref0, ') - ', abs(it[2][1]), ';')
else:
o.Stmt(ind1, '=', it[2][1])
else:
o1,ind1 = shortage(generate_ssize_t_expr(it[2]))
o.extend(o1)
if not istemptyped(ind1):
ind_ = New('long')
o.Raw(ind_, ' = ', ind1, ';')
ind1 = ind_
o.Stmt('if (', ind1, '< 0) {')
o.Raw(ind1, ' += PyList_GET_SIZE(', ref0, ');')
o.append('}')
elif len(it) == 2:
ind1 = New('long')
o.Raw(ind1, ' = PyList_GET_SIZE(', ref0, ') - 1;')
o.Stmt(ref, '=', 'PyList_GetItem', ref0, ind1)
ind2 = New('long')
o.Stmt(ind2, '=', ind1, '+', 1)
o.Stmt('PyList_SetSlice', ref0, ind1, ind2, 'NULL')
o.Cls(ind1, ind2, ref0)
return ref
if head == '_PyDict_Get' and IsDict(TypeExpr(it[1])):
ref0, ref1 = Expr(o, it[1:3])
ref = New(None, forcenewg)
if istempref(ref):
o.Raw(ref, ' = PyDict_GetItem(', ref0, ', ', ref1, ');')
o.Raw('if (', ref, ' == 0) {')
ref3 = GenExpr(it[3], o, ref)
if istempref(ref3) and istempref(ref) and ref3 != ref:
Fatal('Not eq tempref', it, ref3, ref, it[3])
elif ref3 != ref:
o.Raw(ref, ' = ', ref3, ';')
o.INCREF(ref)
o.append('} else {')
o.INCREF(ref)
o.append('}')
if ref3 != ref:
Cls1(o, ref3)
else:
Fatal('', it)
o.Cls(ref0, ref1)
return ref
if head == 'PyObject_GetAttr':
return generate_GetAttr(it,o, forcenewg, typed)
if head == 'PyObject_GetAttr3':
t = TypeExpr(it[1])
if t is not None:
Debug('Typed GetAttr3', t, it)
ref0, ref1 = Expr(o, it[1:3])
ref = New(None, forcenewg)
if istempref(ref):
o.Raw(ref, ' = PyObject_GetAttr(', ref0, ', ', ref1, ');')
o.Cls(ref0, ref1)
o.Raw('if (', ref, ' == 0 && PyErr_ExceptionMatches(PyExc_AttributeError)) {')
o.Raw('PyErr_Clear();')
ref3 = GenExpr(it[3], o, ref)
if istempref(ref3) and istempref(ref) and ref3 != ref:
Fatal('Not eq tempref', it, ref3, ref)
elif ref3 != ref:
o.Raw(ref, ' = ', ref3, ';')
o.INCREF(ref)
if ref3 != ref:
Cls1(o, ref3)
o.append('}')
else:
Fatal('', it)
return ref
if head == '@PyInt_FromSsize_t':
return GenExpr(it[2],o, forcenewg)
if head in ('c_Py_EQ_Int', 'c_Py_NE_Int', 'c_Py_LT_Int', 'c_Py_LE_Int', 'c_Py_GT_Int', 'c_Py_GE_Int'):
ref = Expr1(it[1], o)
n = 'NULL'
t = TypeExpr(it[1])
if t is not None:
Debug('typed compare', t, it)
if type(it[2]) is int:
int_t = it[2]
n = const_to(int_t)
elif it[2][0] == 'CONST' and type(it[2][1]) is int:
int_t = it[2][1]
n = const_to(int_t)
elif it[2][0] in ('!PY_SSIZE_T',):
int_t = GenExpr(it[2][1],o, forcenewg, 'Py_ssize_t')
else:
Fatal('CMP', it)
ret = New('int')
o.Stmt(ret,'=', head, ref, int_t, n)
o.Cls(ref, int_t)
return ret
if head == 'CHR_BUILTIN':
t = TypeExpr(it[1])
if not IsNoneOrInt(t) and t != Kl_IntUndefSize:
Fatal('Illegal typed CHR', t, it)
ref = Expr1(it[1],o)
if ref[0] == 'CONST' and type(ref[1]) is int:
n = ref[1]
else:
n = New('long')
o.Stmt(n, '=', 'PyInt_AsLong', ref)
Cls1(o, ref)
v = []
if TCmp(it[1], v, ('!PyNumber_And', '?', ('CONST', 255))) or\
TCmp(it[1], v, ('!PyNumber_And', ('CONST', 255), '?')):
pass
else:
if type(n) is not int or n < 0 or n > 255:
o_2 = Out()
o_2.Raw('PyErr_SetString(PyExc_ValueError, \"chr() arg not in range(256)\");')
o_2.Raw('goto ', labl, ';')
tolabl = append_to_exception(o_2)
o.Raw('if ( ', n, ' < 0 || ', n, ' >= 256 ) goto ', tolabl, ';')
UseLabl()
o.append('{')
o.Raw('char __s[1];')
o.Raw('__s[0] = (unsigned char)', n, ';')
ref = New(None, forcenewg)
o.Stmt(ref, '=', 'PyString_FromStringAndSize', '__s', '1')
o.append('}')
Cls1(o, n)
return ref
if head == 'ORD_BUILTIN':
t = TypeExpr(it[1])
if not IsStr(t):
if t is not None:
Debug('typed ORD', t, it)
ref = Expr1(it[1],o)
n = New('long')
ref2 = New(None, forcenewg)
if t == Kl_Char:
o.Raw(n, ' = (long)((unsigned char)*', PyString_AS_STRING(ref), ');')
o.PushInt(ref2, n)
o.Cls(n, ref)
if istempref(ref):
o.Raw('Py_CLEAR(', ref, ');')
return ref2
if IsStr(t):
o.Stmt('if (PyString_GET_SIZE(', ref,') == 1) {')
o.Raw(n, ' = (long)((unsigned char)*', PyString_AS_STRING( ref), ');')
o.PushInt(ref2, n)
o.append('} else {')
if not is_pypy:
GenExpr(('!PyCFunction_Call', (load_builtin('ord'),), ('!BUILD_TUPLE', (ref,)), ('NULL',)), o, ref2)
else:
GenExpr(('!PyObject_Call', (load_builtin('ord'),), ('!BUILD_TUPLE', (ref,)), ('NULL',)), o, ref2)
o.append('}')
o.Cls(n, ref)
if istempref(ref):
o.Raw('Py_CLEAR(', ref, ');')
return ref2
o.Stmt('if (PyString_Check(', ref, ') && PyString_GET_SIZE(', ref,') == 1) {')
o.Raw(n, ' = (long)((unsigned char)*PyString_AS_STRING(', ref, '));')
## o.Stmt(ref2, '=', 'PyInt_FromLong', Long)
if not is_pypy:
o.Stmt('} else if (PyByteArray_Check(', ref, ') && PyByteArray_GET_SIZE(', ref,') == 1) {')
o.Raw(n, ' = (long)((unsigned char)*PyByteArray_AS_STRING(', ref, '));')
## o.Stmt(ref2, '=', 'PyInt_FromLong', Long)
o.Stmt('} else if (PyUnicode_Check(', ref, ') && PyUnicode_GET_SIZE(', ref,') == 1) {')
o.Raw(n, ' = (long)((wchar_t)*PyUnicode_AS_UNICODE(', ref, '));')
## o.Stmt(ref2, '=', 'PyInt_FromLong', Long)
o.append('} else {')
ref3 = New()
if is_pypy:
GenExpr(('!PyObject_Call', (load_builtin('ord'),), ('!BUILD_TUPLE', (ref,)), ('NULL',)), o, ref3)
else:
GenExpr(('!PyCFunction_Call', (load_builtin('ord'),), ('!BUILD_TUPLE', (ref,)), ('NULL',)), o, ref3)
o.Stmt(n, '=', 'PyInt_AsLong', ref3)
Cls1(o, ref3)
o.append('}')
Cls1(o, ref)
if istempref(ref):
o.Raw('Py_CLEAR(', ref, ');')
o.PushInt(ref2, n)
Cls1(o, n)
return ref2
if head == 'PY_SSIZE_T':
o1,n = shortage(generate_ssize_t_expr(it[1]))
o.extend(o1)
if type(n) is int:
return ('CONST', n)
ref = New(None, forcenewg)
o.PushInt(ref, n)
Cls1(o, n)
return ref
if head == 'STR_CONCAT':
return GenExpr_STR_CONCAT(it, o, forcenewg)
if head == 'LIST_COMPR':
assert len(it) == 3
prev_compr = current_co.list_compr_in_progress
current_co.list_compr_in_progress = True
ref = generate_list_compr(it[1],it[2],o, forcenewg)
current_co.list_compr_in_progress = prev_compr
return ref
if head == 'SET_COMPR':
assert len(it) == 3
prev_compr = current_co.list_compr_in_progress
current_co.list_compr_in_progress = True
ref = generate_set_compr(it[1],it[2],o, forcenewg)
current_co.list_compr_in_progress = prev_compr
return ref
if head == 'MAP_COMPR':
assert len(it) == 3
prev_compr = current_co.list_compr_in_progress
current_co.list_compr_in_progress = True
ref = generate_map_compr(it[1],it[2],o, forcenewg)
current_co.list_compr_in_progress = prev_compr
return ref
if head == 'BOOLEAN':
o1,logic = shortage(generate_logical_expr(it[1]))
o.extend(o1)
ref = New(None, forcenewg)
o.Stmt(ref, '=','PyBool_FromLong', logic)
Cls1(o, logic)
return ref
if head == '1NOT' and it[1][0] == '!BOOLEAN':
o1, int_val = shortage(generate_logical_expr(it[1]))
o.extend(o1)
ref = New(None, forcenewg)
o.Stmt(ref, '=','PyBool_FromLong', ConC('!(', int_val, ')'))
Cls1(o, int_val)
return ref
if head in ('_EQ_', '_NEQ_'):
Fatal('GenExpr', it)
if head == 'AND_BOOLEAN':
Fatal('GenExpr', it)
if head == '1NOT':
ref1 = Expr1(it[1], o)
n = New('int')
o.Stmt(n, '=', 'PyObject_Not', ref1)
Cls1(o, ref1)
ref = New(None, forcenewg)
o.Stmt('if (', n, ') {')
o.Stmt(ref, '=', 'Py_True')
o.append('} else {')
o.Stmt(ref, '=', 'Py_False')
o.append('}')
Cls1(o, n)
o.INCREF(ref)
return ref
if head == '$PyDict_SymmetricUpdate':
if it[1][0] == '!BUILD_MAP':
ref1, ref2 = Expr(o, it[1:3])
o.Stmt('PyDict_Update', ref1, ref2)
Cls1(o, ref2)
return ref1
Fatal('GenExpr', it)
if head == 'CLASS_CALC_CONST':
ref = New(None, forcenewg)
ref1 = Expr1(it[2], o)
o.Stmt(ref, '=', 'PyInstance_New', ('CALC_CONST',it[1]), ref1, 'NULL')
Cls1(o, ref1)
return ref
if head == 'CLASS_CALC_CONST_DIRECT':
ref = New(None, forcenewg)
o.Stmt(ref, '=', 'PyInstance_NewRaw', ('CALC_CONST',it[1]), 'NULL')
if it[3][0] == 'CONST':
tupl = tuple([('CONST', x) for x in it[3][1]])
else:
tupl = it[3][1]
PushAcc([ref],[ref])
ref2 = Expr1(('!CALL_CALC_CONST', it[2], ('!BUILD_TUPLE', (ref,) + tupl)), o)
PopAcc(o, False)
if ref2 == ('CONST', None) or ref2 == 'Py_None':
pass
else:
o.Raw('assert(', ref2, ' == Py_None);')
Cls1(o, ref2)
return ref
if head == 'CLASS_CALC_CONST_NEW':
ref = GenExpr(('!PyObject_Call', ('CALC_CONST', it[1]), it[2], ('NULL',)), o, forcenewg)
return ref
if head == 'CALL_CALC_CONST':
return generate_call_calc_const(it,o, forcenewg, typed)
if head == 'CALL_CALC_CONST_INDIRECT':
return generate_call_calc_const_indirect(it,o, forcenewg, typed)
if head == 'PyObject_Call':
if it[3] == 'NULL' or (len(it[3]) == 1 and it[3][0] == 'NULL'):
return generate_PyObject_Call_nokey(it, o, forcenewg)
if head.startswith('PyNumber_'):
return GenNumberExpr(it, o, forcenewg, typed, skip_float)
if head == '?Raise':
return generate_raise_zerodivision(it, o)
if head == 'COND_EXPR':
o1, logic = shortage(generate_logical_expr(it[1]))
o.extend(o1)
ref_prev = None
if forcenewg is not None:
assert istempref(forcenewg)
ref_prev = forcenewg
o.CLEAR(ref_prev)
else:
ref_prev = New()
assert ref_prev is not None
o.Stmt('if (', logic, ') {')
ref = GenExpr(it[2], o, ref_prev)
if ref != ref_prev:
if istempref(ref):
pprint((ref,ref_prev))
pprint(it)
assert not istempref(ref)
o.Raw(ref_prev, ' = ', ref, ';')
o.INCREF(ref_prev)
o.append('} else {')
ref = GenExpr(it[3], o, ref_prev)
if ref != ref_prev:
assert not istempref(ref)
o.Raw(ref_prev, ' = ', ref, ';')
o.INCREF(ref_prev)
o.append('}')
return ref_prev
#
# Base part
#
return common_call(head, it, o, typed, forcenewg)
def generate_import_name(it, o):
importer = Expr1(('!PyDict_GetItem', 'bdict', ('CONST', '__import__')),o)
if current_co.c_name == 'Init_filename':
loc = 'glob'
else:
loc = 'f->f_locals == 0 ? Py_None : f->f_locals'
if it[2][0] == 'CONST' and it[2][1] == -1:
it3 = it[3]
if it3 == ('CONST', None):
it3 = ('Py_None',)
tupl = ('!BUILD_TUPLE', ( ('CONST',it[1]), \
('glob',), \
(loc,),\
it3))
else:
tupl = ('!BUILD_TUPLE', ( ('CONST',it[1]), \
('glob',), \
(loc,),\
it[3], it[2]))
arg = Expr1(tupl,o)
ret = Expr1(('!PyEval_CallObject', importer, arg),o )
o.Cls(arg, importer)
return ret
def generate_raise_zerodivision(it, o):
gen = [Expr1(x, o) if type(x) is tuple and len(x) > 0 else x \
for i,x in enumerate(it) if i > 2]
o.Cls(*gen)
refs = [('BUILTIN', 'ZeroDivisionError'), ('CONST', "division by 0"), 'NULL']
o.Stmt('_PyEval_DoRaise', refs[0], refs[1], refs[2])
if refs[0] != 'NULL':
o.INCREF(refs[0])
if refs[1] != 'NULL':
o.INCREF(refs[1])
if refs[2] != 'NULL':
o.INCREF(refs[2])
o.Cls(*refs)
o.Stmt('goto', labl)
UseLabl()
return ('CONST', None)
def generate_call_calc_const_indirect(it,o, forcenewg, typed):
d_nm = 'codefunc_' + it[1]
ret = New(None, forcenewg)
if it[2] == ('CONST', ()):
refs = []
elif it[2][0] == '!BUILD_TUPLE':
refs = Expr(o, it[2][1])
elif it[2][0] == 'CONST':
refs = [('CONST', x) for x in it[2][1]]
else:
Fatal('GenExpr', it)
raise
co = N2C(it[1])
argcount = co.co_argcount
assert len(refs) == argcount
tupl = (ret, ' = _Call_CompiledWithFrame(', d_nm, ', ', const_to(co), ', ', argcount)
Used('_Call_CompiledWithFrame')
for ref in refs:
tupl = tupl + (', ', ref)
tupl = tupl + (')',)
tupl = ('if ((',) + tupl + (') == 0) goto ', labl, ';')
o.Raw(*tupl)
UseLabl()
if len(refs) > 0:
o.Cls(*refs)
return ret
def append_to_exception(o_2):
if tuple(o_2) not in current_co.to_exception:
current_co.to_exception[tuple(o_2)] = New('label')
return current_co.to_exception[tuple(o_2)]
def generate_from_ceval_binary_subscr(it, o, forcenewg):
t = TypeExpr(it[1])
ty_ind = TypeExpr(it[2])
islist = IsList(t)
if t is None:
pass
elif t[0] == T_NEW_CL_INST and Is3(t[1], 'Derived', ('!LOAD_BUILTIN', 'list')):
islist = True
if it[2][0] == '!PyInt_FromSsize_t':
if not islist and t is not None:
verif(it, o)
ref = Expr1(it[1], o)
ref1 = New(None, forcenewg)
if not islist:
o.Stmt('if (PyList_CheckExact(', ref, ')) {')
o.Stmt(ref1, '=', 'PyList_GetItem', ref, it[2][1])
if not islist:
o.append('} else {')
ref2 = Expr1(it[2],o)
o.Stmt(ref1, '=', 'PyObject_GetItem', ref, ref2)
Cls1(o, ref2)
o.append('}')
Cls1(o, ref)
return ref1
if it[2][0] == '!@PyInt_FromSsize_t':
if not islist and t is not None and not IsDict(t) and not IsTuple(t):
Debug('not islist? is notdict', it, t)
ref = Expr1(it[1], o)
ref1 = New(None, forcenewg)
if IsDict(t):
ref2 = Expr1(it[2][2], o)
o_2 = Out()
tupl = New()
o_2.Raw('if ((', tupl, ' = PyTuple_Pack(1, ', ref2, ')) == 0) goto ', labl, ';')
o_2.Raw('PyErr_SetObject(PyExc_KeyError, ', tupl, ');')
Cls1(o_2, tupl)
o_2.Raw('goto ', labl, ';')
tolabl = append_to_exception(o_2)
o.Raw('if ((', ref1, ' = PyDict_GetItem(', ref, ', ', ref2, ')) == 0) goto ', tolabl, ';')
UseLabl()
o.INCREF(ref1)
o.Cls(ref, ref2)
return ref1
if IsTuple(t):
GetTupleItem(o, t, ref1, ref, it[2][1])
## o.Stmt(ref1, '=', 'PyTuple_GetItem', ref, it[2][1])
Cls1(o, ref)
return ref1
elif expand_BINARY_SUBSCR or islist:
if not islist:
o.Stmt('if (PyList_CheckExact(', ref, ')) {')
o.Stmt(ref1, '=', 'PyList_GetItem', ref, it[2][1])
if not islist:
verif(it, o)
o.append('} else {')
ref2 = Expr1(it[2][2],o)
o.Stmt(ref1, '=', 'PyObject_GetItem', ref, ref2)
Cls1(o, ref2)
o.append('}')
else:
verif(it, o)
ref2 = Expr1(it[2][2],o)
o.Stmt(ref1, '=', '_c_BINARY_SUBSCR_Int', ref, it[2][1], ref2)
Cls1(o, ref2)
Cls1(o, ref)
return ref1
if islist:
ty_ind = TypeExpr(it[2])
ref0 = Expr1(it[1], o)
ref1 = GenExpr(it[2], o, None, None, True)
ref = New(None, forcenewg)
ind = None
if ty_ind is None or IsInt(ty_ind):
ind = New('long')
if ty_ind is None:
o.Raw('if (PyInt_CheckExact( ', ref1, ' )) {')
if ty_ind is None or IsInt(ty_ind):
if ref1[0] != 'CONST':
o.Stmt(ind, '=', 'PyInt_AS_LONG', ref1)
if IsInt(ty_ind):
Cls1(o, ref1)
o.Stmt('if (', ind, '< 0) {')
o.Raw(ind, ' += PyList_GET_SIZE(', ref0, ');')
o.append('}')
o.Stmt(ref, '=', 'PyList_GetItem', ref0, ind)
Cls1(o, ind)
elif ref1[1] >= 0:
o.Stmt(ref, '=', 'PyList_GetItem', ref0, ref1[1])
Cls1(o, ind)
else: ##if ref1[1] < 0:
o.Raw(ind, ' = PyList_GET_SIZE(', ref0, ') + ', ref1[1], ';')
o.Stmt(ref, '=', 'PyList_GetItem', ref0, ind)
Cls1(o, ind)
if ty_ind is None:
o.append('} else {')
if not IsInt(ty_ind):
o.Stmt(ref, '=', 'PyObject_GetItem', ref0, ref1)
if ty_ind is None:
o.append('}')
Cls1(o, ref1)
Cls1(o, ref0)
return ref
if IsDict(t):
ref0 = Expr1(it[1], o)
ref1 = GenExpr(it[2], o, None, None, True)
ref = New(None, forcenewg)
o_2 = Out()
tupl = New()
o_2.Raw('if ((', tupl, ' = PyTuple_Pack(1, ', ref1, ')) == 0) goto ', labl, ';')
o_2.Raw('PyErr_SetObject(PyExc_KeyError, ', tupl, ');')
Cls1(o_2, tupl)
o_2.Raw('goto ', labl, ';')
tolabl = append_to_exception(o_2)
o.Raw('if ((', ref, ' = PyDict_GetItem(', ref0, ', ', ref1, ')) == 0) goto ', tolabl, ';')
UseLabl()
o.INCREF(ref)
o.Cls(ref0, ref1)
return ref
if IsTuple(t):
ref0 = Expr1(it[1], o)
ref1 = GenExpr(it[2], o, None, None, True)
ref = New(None, forcenewg)
ind = None
if ty_ind is None or IsInt(ty_ind):
if ref1[0] == 'CONST' and type(ref1[1]) is int and ref1[1] >= 0:
ind = ref1[1]
else:
ind = New('long')
if ty_ind is None:
o.Raw('if (PyInt_CheckExact( ', ref1, ' )) {')
if ty_ind is None or IsInt(ty_ind):
if type(ind) is not int:
o.Stmt(ind, '=', 'PyInt_AS_LONG', ref1)
if IsInt(ty_ind):
Cls1(o, ref1)
o.Stmt('if (', ind, '< 0) {')
o.Raw(ind, ' += PyTuple_GET_SIZE(',ref0,');')
o.append('}')
## Cls1(o, ref1)
GetTupleItem(o, t, ref, ref0, ind)
## o.Stmt(ref, '=', 'PyTuple_GetItem', ref0, ind)
Cls1(o, ind)
if ty_ind is None:
o.append('} else {')
if not IsInt(ty_ind):
o.Stmt(ref, '=', 'PyObject_GetItem', ref0, ref1)
if ty_ind is None:
o.append('}')
Cls1(o, ref1)
Cls1(o, ref0)
return ref
if IsStr(t):
ty_ind = TypeExpr(it[2])
ref0 = Expr1(it[1], o)
ref1 = GenExpr(it[2], o, None, None, True)
ref = New(None, forcenewg)
ind = None
if ty_ind is None or IsInt(ty_ind):
ind = New('long')
if ty_ind is None:
o.Raw('if (PyInt_CheckExact( ', ref1, ' )) {')
if ty_ind is None or IsInt(ty_ind):
o.Stmt(ind, '=', 'PyInt_AS_LONG', ref1)
if IsInt(ty_ind):
Cls1(o, ref1)
o.Stmt('if (', ind, '< 0) {')
if ref0[0] == 'CONST':
o.Raw(ind, ' += ', len(ref0[1]), ';')
else:
o.Raw(ind, ' += PyString_GET_SIZE(',ref0,');')
o.append('}')
o_2 = Out()
o_2.Raw('PyErr_SetString(PyExc_IndexError, "string index out of range");')
o_2.Raw('goto ', labl, ';')
tolabl = append_to_exception(o_2)
if ref0[0] == 'CONST':
len_ref0 = len(ref0[1])
o.Raw('if (', ind, ' < 0 || ', ind, ' >= ',len_ref0,') goto ', tolabl, ';')
else:
o.Raw('if (', ind, ' < 0 || ', ind, ' >= PyString_GET_SIZE(',ref0,')) goto ', tolabl, ';')
UseLabl()
ch = ConC('(', PyString_AS_STRING(ref0), ' + ', ind, ')')
o.Raw(ref, ' = PyString_FromStringAndSize(', ch, ', 1);')
Cls1(o, ind)
if ty_ind is None:
o.append('} else {')
if not IsInt(ty_ind):
o.Stmt(ref, '=', 'PyObject_GetItem', ref0, ref1)
if ty_ind is None:
o.append('}')
Cls1(o, ref1)
Cls1(o, ref0)
return ref
verif(it, o)
t = TypeExpr(it[1])
if t is not None and t[0] in ('NewClassInstance', 'OldClassInstance'):
Debug('Typed BINARY_SUBSCR not specialised: %s ( %s, %s )' % (it, t, TypeExpr(it[2])))
ref0 = Expr1(it[1], o)
ref1 = GenExpr(it[2], o, None, None, True)
ref = New(None, forcenewg)
if ref1[0] == 'CONST' and type(ref1[1]) is int:
o.Raw('if ((', ref, ' = _c_BINARY_SUBSCR_Int ( ', ref0, ' , ', ref1[1], ' , ', ref1, ' )) == 0) goto ', labl, ';')
UseLabl()
Used('_c_BINARY_SUBSCR_Int')
elif ref1[0] == 'FAST' and IsInt(ty_ind) and not current_co.IsCVar(ref1):
o.Raw('if ((', ref, ' = _c_BINARY_SUBSCR_Int ( ', ref0, ' , PyInt_AS_LONG ( ', ref1, ' ) , ', ref1, ' )) == 0) goto ', labl, ';')
UseLabl()
Used('_c_BINARY_SUBSCR_Int')
else:
o.Stmt(ref, '=', 'PyObject_GetItem', ref0, ref1)
o.Cls(ref1, ref0)
return ref
def GetTupleItem(o, t, ref, ref0, ind):
assert IsTuple(t)
if type(ind) is int and IsInTupleInd(t, ind):
o.Stmt(ref, '=', 'PyTuple_GET_ITEM', ref0, ind)
else:
o.Stmt(ref, '=', 'PyTuple_GetItem', ref0, ind)
def generate_call_calc_const(it, o, forcenewg, typed, nmtypvar = None):
d_nm = '_Direct_' + it[1]
is_const_default = True
co = N2C(it[1])
argcount = co.co_argcount
is_varargs = co.co_flags & 0x4
hidden = co.hidden_arg_direct
typed_arg = co.typed_arg_direct
ty2 = {}
for k,v in typed_arg.iteritems():
if k not in hidden:
ty2[k] = v
typed_arg = ty2
if it[1] in default_args and default_args[it[1]][0] != 'CONST':
is_const_default = False
if it[2] == ('CONST', ()):
refs = []
elif it[2][0] == '!BUILD_TUPLE':
refs = []
for i, e in enumerate(it[2][1]):
if i in typed_arg and IsCType(typed_arg[i]) and IsCVar(e) and \
Type2CType(typed_arg[i]) == Type2CType(TypeExpr(e)):
ref_0 = CVarName(e)
elif i in typed_arg and typed_arg[i][0] is int:
if e[0] == 'CONST':
ref_0 = e[1]
else:
ref_0 = Expr1(e, o)
typ3 = New('long')
o.Raw(typ3, ' = PyInt_AS_LONG ( ', ref_0, ' );')
Cls1(o, ref_0)
ref_0 = typ3
elif i in typed_arg and typed_arg[i][0] is float:
if e[0] == 'CONST':
ref_0 = e[1]
else:
ref_0 = Expr1(e, o)
typ3 = New('double')
o.Raw(typ3, ' = PyFloat_AS_DOUBLE ( ', ref_0, ' );')
Cls1(o, ref_0)
ref_0 = typ3
elif i in typed_arg and typed_arg[i][0] is bool:
if e[0] == 'CONST':
if e[1]:
ref_0 = 1
else:
ref_0 = 0
else:
typ3 = New('int')
ref_0 = Expr1(e, o)
o.Raw(typ3, ' = PyObject_IsTrue(', ref_0, ');')
Cls1(o, ref_0)
ref_0 = typ3
elif i in typed_arg and typed_arg[i][0] is str and typed_arg[i][1] == 1:
ref_0 = Expr1(e, o)
if ref_0[0] == 'CONST':
ref_0 = charhex(ref_0[1])
else:
typ3 = New('char')
o.Raw(typ3, ' = *', PyString_AS_STRING (ref_0), ';')
Cls1(o, ref_0)
ref_0 = typ3
else:
ref_0 = Expr1(e, o)
refs.append(ref_0)
elif it[2][0] == 'CONST':
refs = []
for i, e in enumerate(it[2][1]):
ref_0 = ('CONST', e)
if i in typed_arg and typed_arg[i][0] is int:
ref_0 = ref_0[1]
elif i in typed_arg and typed_arg[i][0] is float:
ref_0 = ref_0[1]
elif i in typed_arg and typed_arg[i][0] is bool:
if ref_0[1]:
ref_0 = 1
else:
ref_0 = 0
elif i in typed_arg and typed_arg[i][0] is str and typed_arg[i][1] == 1:
if ref_0[0] == 'CONST':
ref_0 = charhex(ref_0[1])
else:
typ3 = New('char')
o.Raw(typ3, ' = *', PyString_AS_STRING(ref_0), ';')
Cls1(o, ref_0)
ref_0 = typ3
refs.append(ref_0)
else:
Fatal('GenExpr', it)
if not is_varargs:
if argcount != len(refs):
if argcount > len(refs):
if it[1] in default_args:
if is_const_default:
_refs2 = [('CONST', x) for x in default_args[it[1]][1]]
else:
_refs2 = [Expr1(x, o) for x in default_args[it[1]][1]]
add_args = argcount - len(refs)
pos_args = len(_refs2) - add_args
len_refs = len(refs)
for i1, ref_0 in enumerate(_refs2[pos_args:]):
i = i1 + len_refs
if i in typed_arg and typed_arg[i][0] is int:
if ref_0[0] == 'CONST':
ref_0 = ref_0[1]
else:
typ3 = New('long')
o.Raw(typ3, ' = PyInt_AS_LONG ( ', ref_0, ' );')
Cls1(o, ref_0)
ref_0 = typ3
elif i in typed_arg and typed_arg[i][0] is bool:
if ref_0[0] == 'CONST':
if ref_0[1]:
ref_0 = 1
else:
ref_0 = 0
else:
typ3 = New('int')
o.Raw(typ3, ' = PyObject_IsTrue(', ref_0, ');')
Cls1(o, ref_0)
ref_0 = typ3
elif i in typed_arg and typed_arg[i][0] is str and typed_arg[i][1] == 1:
if ref_0[0] == 'CONST':
ref_0 = charhex(ref_0[1])
else:
typ3 = New('char')
o.Raw(typ3, ' = *', PyString_AS_STRING(ref_0), ';')
Cls1(o, ref_0)
ref_0 = typ3
refs.append(ref_0)
else:
assert len(hidden) == 0
lenrefs = len(refs)
if argcount > len(refs):
## print argcount, len(refs), refs, default_args[it[1]][1]
if it[1] in default_args:
if is_const_default:
_refs2 = [('CONST', x) for x in default_args[it[1]][1]]
else:
print '/111 !!', 'Strange default value', default_args[it[1]]
_refs2 = [Expr1(x, o) for x in default_args[it[1]]]
add_args = argcount - len(refs)
pos_args = len(_refs2) - add_args
refs = refs + _refs2[pos_args:]
rargs = refs[:argcount]
rtupl = refs[argcount:]
isconst = all([x[0] == 'CONST' for x in rtupl])
if isconst:
rtupl2 = Expr1(('CONST', tuple([x[1] for x in rtupl])), o)
else:
rtupl2 = Expr1(('!BUILD_TUPLE', tuple(rtupl)), o)
argcount += 1
for i, e in enumerate(rargs):
if i < lenrefs:
continue
if i in typed_arg and IsCType(typed_arg[i]) and IsCVar(e) and \
Type2CType(typed_arg[i]) == Type2CType(TypeExpr(e)):
ref_0 = CVarName(e)
elif i in typed_arg and typed_arg[i][0] is int and type(e) is tuple:
if e[0] == 'CONST':
ref_0 = e[1]
else:
ref_0 = Expr1(e, o)
typ3 = New('long')
o.Raw(typ3, ' = PyInt_AS_LONG ( ', ref_0, ' );')
Cls1(o, ref_0)
ref_0 = typ3
elif i in typed_arg and typed_arg[i][0] is float and type(e) is tuple:
if e[0] == 'CONST':
ref_0 = e[1]
else:
ref_0 = Expr1(e, o)
typ3 = New('double')
o.Raw(typ3, ' = PyFloat_AS_DOUBLE ( ', ref_0, ' );')
Cls1(o, ref_0)
ref_0 = typ3
elif i in typed_arg and typed_arg[i][0] is bool and type(e) is tuple:
if e[0] == 'CONST':
if e[1]:
ref_0 = 1
else:
ref_0 = 0
else:
typ3 = New('int')
ref_0 = Expr1(e, o)
o.Raw(typ3, ' = PyObject_IsTrue(', ref_0, ');')
Cls1(o, ref_0)
ref_0 = typ3
elif i in typed_arg and typed_arg[i][0] is str and typed_arg[i][1] == 1 and type(e) is tuple:
ref_0 = Expr1(e, o)
if ref_0[0] == 'CONST':
ref_0 = charhex(ref_0[1])
else:
typ3 = New('char')
o.Raw(typ3, ' = *', PyString_AS_STRING (ref_0), ';')
Cls1(o, ref_0)
ref_0 = typ3
else:
ref_0 = e
rargs[i] = ref_0
refs = rargs + [rtupl2]
## if len(refs) != argcount:
## pprint(('// 1', refs, it, current_co.co_name))
assert len(refs) == argcount
_refs2 = []
for i,x in enumerate(refs):
if i not in hidden:
_refs2.append(x)
co_call = N2C(it[1])
if not co_call.IsRetVoid() and not co_call.IsRetBool() and not co_call.IsRetInt() and not co_call.IsRetFloat() and not co_call.IsRetChar():
ref = New(None, forcenewg)
tupl = (ref, '=', d_nm) + tuple(_refs2)
o.Stmt(*tupl)
if len(_refs2) > 0:
o.Cls(*_refs2)
return ref
elif co_call.IsRetVoid():
tupl = (d_nm,) + tuple(_refs2)
li = ['if (',d_nm, '(']
for i, re in enumerate(_refs2):
if i > 0:
li.append(', ')
li.append(re)
li.append(') == -1) goto ')
li.append(labl)
li.append(';')
UseLabl()
tupl = tuple(li)
o.Raw(*tupl)
if len(_refs2) > 0:
o.Cls(*_refs2)
return ('CONST', None)
elif co_call.IsRetBool():
if nmtypvar is not None:
logical = nmtypvar
else:
logical = New('int')
li = ['if ((',logical, ' = ', d_nm, '(']
for i, re in enumerate(_refs2):
if i > 0:
li.append(', ')
li.append(re)
li.append(')) == -1) goto ')
li.append(labl)
li.append(';')
UseLabl()
tupl = tuple(li)
o.Raw(*tupl)
if len(_refs2) > 0:
o.Cls(*_refs2)
if nmtypvar is None:
ref = New(None, forcenewg)
o.Raw(ref, ' = PyBool_FromLong(', logical, ');')
Cls1(o, logical)
return ref
return
elif co_call.IsRetInt():
if nmtypvar is not None:
logical = nmtypvar
else:
logical = New('long')
li = ['if ((',logical, ' = ', d_nm, '(']
for i, re in enumerate(_refs2):
if i > 0:
li.append(', ')
li.append(re)
li.append(')) == -1 && PyErr_Occurred()) goto ')
li.append(labl)
li.append(';')
UseLabl()
tupl = tuple(li)
o.Raw(*tupl)
if len(_refs2) > 0:
o.Cls(*_refs2)
if nmtypvar is None:
ref = New(None, forcenewg)
o.PushInt(ref, logical)
Cls1(o, logical)
return ref
return
elif co_call.IsRetFloat():
if nmtypvar is not None:
logical = nmtypvar
else:
logical = New('double')
li = ['if ((',logical, ' = ', d_nm, '(']
for i, re in enumerate(_refs2):
if i > 0:
li.append(', ')
li.append(re)
li.append(')) == -1 && PyErr_Occurred()) goto ')
li.append(labl)
li.append(';')
UseLabl()
tupl = tuple(li)
o.Raw(*tupl)
if len(_refs2) > 0:
o.Cls(*_refs2)
if nmtypvar is None:
ref = New(None, forcenewg)
o.Raw(ref, ' = PyFloat_FromDouble (', logical, ');')
Cls1(o, logical)
return ref
return
elif co_call.IsRetChar():
if nmtypvar is not None:
logical = nmtypvar
else:
logical = New('char')
li = ['if ((',logical, ' = ', d_nm, '(']
for i, re in enumerate(_refs2):
if i > 0:
li.append(', ')
li.append(re)
li.append(')) == -1 && PyErr_Occurred()) goto ')
li.append(labl)
li.append(';')
UseLabl()
tupl = tuple(li)
o.Raw(*tupl)
if len(_refs2) > 0:
o.Cls(*_refs2)
if nmtypvar is None:
ref = New(None, forcenewg)
o.Raw(ref, ' = PyString_FromStringAndSize (&', logical, ', 1);')
Cls1(o, logical)
return ref
return
Fatal('')
return None
def GenExpr_STR_CONCAT(it, o, forcenewg):
args = it[1:]
isstr = [IsStr(TypeExpr(x)) for x in args]
if all(isstr):
refs = [Expr1(x, o) for x in args]
## l_const = sum([len(x[1]) for x in args if x[0] == 'CONST' and type(x[1]) is str])
l_vals = []
for i, x in enumerate(args):
ta = TypeExpr(x)
if IsChar(ta):
l_vals.append(1)
elif x[0] != 'CONST' or type(x[1]) is not str:
r0 = New('int')
l_vals.append(r0)
o.Raw(r0, ' = PyString_GET_SIZE ( ', refs[i], ' );')
else:
l_vals.append(len(x[1]))
ref = New(None, forcenewg)
var_len = ' + '.join([CVar(x) for x in l_vals])
## if l_const != 0:
## var_len = var_len + ' + ' + str(l_const)
o.Raw(ref, ' = PyString_FromStringAndSize(NULL, ', var_len, ');')
cref = New('charref')
o.Raw(cref, ' = ', PyString_AS_STRING(ref), ';')
for i, x in enumerate(args):
if l_vals[i] == 0:
pass
elif l_vals[i] == 1:
o.Raw('*', cref, '++ = *', PyString_AS_STRING(refs[i]), ';')
elif l_vals[i] == 2:
o.Raw('*', cref, '++ = ', PyString_AS_STRING(refs[i]), '[0];')
o.Raw('*', cref, '++ = ', PyString_AS_STRING(refs[i]), '[1];')
elif l_vals[i] == 3:
o.Raw('*', cref, '++ = ', PyString_AS_STRING(refs[i]), '[0];')
o.Raw('*', cref, '++ = ', PyString_AS_STRING(refs[i]), '[1];')
o.Raw('*', cref, '++ = ', PyString_AS_STRING(refs[i]), '[2];')
else:
o.Raw('memcpy(', cref, ', ', PyString_AS_STRING(refs[i]), ', ', l_vals[i], ');')
if i == len(args) - 1:
pass
else:
o.Raw(cref, ' += ', l_vals[i], ';')
o.Cls(*refs)
o.Cls(*l_vals)
Cls1(o, cref)
return ref
if len(it) > 4 and len(it) <= 64:
return GenExpr(('!STR_CONCAT_N', len(it)-1) + it[1:], o, forcenewg)
elif len(it) == 4:
return GenExpr(('!STR_CONCAT3', it[1], it[2], it[3]), o, forcenewg)
elif len(it) == 3:
return GenExpr(('!STR_CONCAT2', it[1], it[2]), o, forcenewg)
elif len(it) > 64:
return GenExpr(('!STR_CONCAT_N', len(it[1:63])) + it[1:63] + ((('!STR_CONCAT',) + it[63:]),), o, forcenewg)
else:
Fatal('GenExpr', it)
def call_fastcall(it, o, forcenewg):
## is_const_default = True
ref1 = Expr1(it[1], o)
if it[2] == ('CONST', ()):
refs = []
elif it[2][0] == '!BUILD_TUPLE':
refs = Expr(o, it[2][1])
elif it[2][0] == 'CONST':
refs = [('CONST', x) for x in it[2][1]]
else:
Fatal('GenExpr call fastcall', it)
ref = New(None, forcenewg)
if len(refs) == 0:
tupl = (ref, ' = FastCall0(', ref1, ')')
Used('FastCall0')
else:
tupl = (ref, ' = FastCall(', len(refs), ', ', ref1)
Used('FastCall')
for _r in refs:
tupl = tupl + (', ', _r)
tupl = tupl + (')',)
tupl = ('if ((',) + tupl + (') == 0) goto ', labl, ';')
o.Raw(*tupl)
UseLabl()
if len(refs) > 0:
o.Cls(*refs)
Cls1(o, ref1)
return ref
def generate_PyObject_Call_nokey(it, o, forcenewg):
if it[1][0] == '!LOAD_GLOBAL' and it[1][1] in d_built:
skip_built = False
if it[2][0] == '!BUILD_TUPLE':
args = it[2][1]
elif it[2][0] == 'CONST':
args = [('CONST', x) for x in it[2][1]]
else:
skip_built = True
if not skip_built:
cm = attempt_direct_builtin(it[1][1],args, it[2])
if cm is not None:
proc = Expr1(it[1], o)
o.Stmt('if (', proc, '==', load_builtin(it[1][1]), ') {')
ref = GenExpr(cm, o,forcenewg)
o.append('} else {')
tupl = Expr1(it[2], o)
o.Stmt(ref, '=', 'FirstCFunctionCall', proc, tupl, ('NULL',))
Cls1(o, tupl)
o.append('}')
Cls1(o, proc)
return ref
if it[1][0] == '!LOAD_BUILTIN' and it[2][0] == '!BUILD_TUPLE' and \
len(it[2][1]) == 1 and it[2][1][0][0] == '!LIST_COMPR' and it[1][1] in ('all', 'any'):
prev_compr = current_co.list_compr_in_progress
current_co.list_compr_in_progress = True
it1 = it[2][1][0]
logical = generate_func_list_compr(it1[1],it1[2],o, it[1][1])
current_co.list_compr_in_progress = prev_compr
ref = New(None, forcenewg)
o.Stmt(ref, '=', 'PyBool_FromLong', logical)
o.Cls(logical)
return ref
s = save_tempgen()
o2 = Out()
proc = GenExpr(it[1],o2)
o2.Cls(proc)
restore_tempgen(s)
## if it[1][0] == '!PyObject_GetAttr' and it[1][2][0] == 'CONST' and it[1][2][1] in ('startswith', 'endswith'):
## it1 = it[1][1]
## t1 = TypeExpr(it1)
## meth = it[1][2][1]
## if it[2][0] == 'CONST' and type(it[2][1]) is tuple and len(it[2][1]) == 1 and t not ype(it[2][1][0]) is str:
## it2 = it[2][1][0]
## if type(t1) is not tuple or t1[0] is str:
## r1 = GenExpr(
if TypeExpr(it[1]) != Kl_BuiltinFunction and not is_mkfunc_const(proc, it[1]) and \
it[2][0] in ('!BUILD_TUPLE', 'CONST') and len(it[2][1]) < 15 and it[1][0] != '!LOAD_BUILTIN' and not is_pypy:
return call_fastcall(it, o, forcenewg)
ref = New(None, forcenewg)
tupl = GenExpr(it[2], o)
variant = not is_mkfunc_const(proc, it[1])
proc = GenExpr(it[1], o)
t = TypeExpr(it[1])
if t == Kl_BuiltinFunction and not is_pypy:
o.Stmt(ref, '=', 'PyCFunction_Call', proc, tupl, ('NULL',))
elif variant:
if it[1][0] == '!LOAD_BUILTIN':
if it[1][1] in d_built and type(d_built[it[1][1]]) == type(len) and not is_pypy:
o.Stmt(ref, '=', 'PyCFunction_Call', proc, tupl, ('NULL',))
else:
Debug('+Call PyObject_Call builtin (variant)', it[1], TypeExpr(it[1]))
o.Stmt(ref, '=', 'PyObject_Call', proc, tupl, ('NULL',))
else:
o.Stmt(ref, '=', 'FirstCFunctionCall', proc, tupl, ('NULL',))
else:
o.Stmt(ref, '=', 'PyObject_Call', proc, tupl, ('NULL',))
o.Cls(proc, tupl)
return ref
def common_call(head, it, o, typed, forcenewg):
verif(it, o)
if head == '_PyEval_ApplySlice':
t0 = TypeExpr(it[1])
t1 = TypeExpr(it[2])
t2 = TypeExpr(it[3])
if it[2] == 'NULL' and IsInt(t2):
ref0 = Expr1(it[1], o)
o2,ind2 = shortage(generate_ssize_t_expr(it[3]))
o.extend(o2)
ref = New(None, forcenewg)
if IsStr(t0):
o.Raw('if ( ', ind2, ' >= 0 && ', ind2, ' <= PyString_GET_SIZE ( ', ref0, ' ) ) {')
o.Raw(ref, ' = PyString_FromStringAndSize ( PyString_AS_STRING ( ', ref0, ' ) , ', ind2, ' );')
o.Raw('} else if ( ', ind2, ' < 0 && ', ind2, ' >= -PyString_GET_SIZE ( ', ref0, ' ) ) {')
o.Raw(ref, ' = PyString_FromStringAndSize ( PyString_AS_STRING ( ', ref0, ' ) , PyString_GET_SIZE ( ', ref0, ' ) - ', ind2, ' );')
o.Raw('} else {')
o.Raw(ref, ' = ', ('CONST', ''), ';')
o.INCREF(ref)
o.Raw('}')
else:
o.Stmt(ref, '=', 'PySequence_GetSlice', ref0, '0', ind2)
o.Cls(ind2, ref0)
return ref
if it[3] == 'NULL' and IsInt(t1):
ref0 = Expr1(it[1], o)
o1,ind1 = shortage(generate_ssize_t_expr(it[2]))
o.extend(o1)
ref = New(None, forcenewg)
if IsStr(t0):
o.Raw('if ( ', ind1, ' >= 0 && ', ind1, ' <= PyString_GET_SIZE ( ', ref0, ' ) ) {')
o.Raw(ref, ' = PyString_FromStringAndSize ( PyString_AS_STRING ( ', ref0, ' ) + ', ind1, ' , PyString_GET_SIZE ( ', ref0, ' ) - ', ind1, ' );')
o.Raw('} else if ( ', ind1, ' < 0 && ', ind1, ' >= -PyString_GET_SIZE ( ', ref0, ' ) ) {')
o.Raw(ref, ' = PyString_FromStringAndSize ( PyString_AS_STRING ( ', ref0, ' ) + ( PyString_GET_SIZE ( ', ref0, ' ) + ', ind1, ' ) , - ', ind1, ' );')
o.Raw('} else {')
o.Raw(ref, ' = ', ('CONST', ''), ';')
o.INCREF(ref)
o.Raw('}')
else:
o.Stmt(ref, '=', 'PySequence_GetSlice', ref0, ind1, 'PY_SSIZE_T_MAX')
o.Cls(ind1, ref0)
return ref
elif IsInt(t1) and IsInt(t2):
ref0 = Expr1(it[1], o)
o1,ind1 = shortage(generate_ssize_t_expr(it[2]))
o.extend(o1)
o2,ind2 = shortage(generate_ssize_t_expr(it[3]))
o.extend(o2)
ref = New(None, forcenewg)
assert ind1 != ind2
o.Stmt(ref, '=', 'PySequence_GetSlice', ref0, ind1, ind2)
o.Cls(ind1, ind2, ref0)
return ref
it1 = Expr1(it[1], o)
it2 = it[2]
if it2 != 'NULL':
it2 = GenExpr(it2,o, None,None, True)
it3 = it[3]
if it3 != 'NULL':
it3 = GenExpr(it3,o, None,None, True)
gen = [ it1, it2, it3]
else:
gen = [Expr1(x, o) if type(x) is tuple and len(x) > 0 else x \
for i,x in enumerate(it) if i > 0]
if head == '_PyInt_Format':
gen[0] = ('TYPE_CONVERSION', '(PyIntObject *)', gen[0])
if head == '_PyList_Extend':
gen[0] = ('TYPE_CONVERSION', '(PyListObject *)', gen[0])
newg = New(typed, forcenewg)
args = (newg, '=', head) + tuple(gen)
o.Stmt(*args)
o.Cls(*gen)
return newg
def GenNumberExpr(it, o, forcenewg, typed, skip_float):
head = it[0]
if (head == '!PyNumber_Lshift' or head == '!PyNumber_InPlaceLshift'):
if it[2][0] == 'CONST' and type(it[2][1]) is int and it[2][1] >= 1 and it[2][1] <= 31:
shif = it[2][1]
t1 = TypeExpr(it[1])
if IsShort(t1) and shif < 16:
if it[1][0] == '!@PyInt_FromSsize_t':
ref1 = None
n1 = New('long')
o.Raw(n1, ' = ', it[1][1], ';')
else:
ref1 = Expr1(it[1], o)
n1 = New('long')
o.Raw(n1, ' = PyInt_AS_LONG ( ', ref1, ' );')
Cls1(o, ref1)
if forcenewg is not None:
new = forcenewg
else:
new = New()
# o.Raw(n1, ' = ', n1, ' << ', it[2][1], ';')
o.PushInt(new, ConC('(', n1, ' << ', it[2][1], ')'))
# o.PushInt(new, n1)
Cls1(o, n1)
return new
elif IsInt(t1):
if it[1][0] == '!@PyInt_FromSsize_t':
ref1 = None
n1 = New('long')
o.Raw(n1, ' = ', it[1][1], ';')
else:
ref1 = Expr1(it[1], o)
n1 = New('long')
o.Raw(n1, ' = PyInt_AS_LONG ( ', ref1, ' );')
if forcenewg is not None:
new = forcenewg
else:
new = New()
o.Raw('if (', n1, ' < (INT_MAX >> ', it[2][1], ') && ', n1, ' >= 0) {')
## o.Raw(n1, ' = ', n1, ' << ', it[2][1], ';')
o.PushInt(new, ConC('(', n1, ' << ', it[2][1], ')'))
Cls1(o, n1)
o.Raw('} else {')
o.Raw('if ((', new, ' = ', head[1:], '(', ref1, ', ', it[2], ')) == 0) goto ', labl, ';')
UseLabl()
o.append('}')
Cls1(o, ref1)
return new
elif IsIntUndefSize(t1) or t1 is None:
ref1 = Expr1(it[1], o)
n1 = New('long')
if forcenewg is not None:
new = forcenewg
else:
new = New()
o.Raw('if (PyInt_CheckExact( ', ref1, ' ) && (', n1, ' = PyInt_AS_LONG ( ', ref1, ' )) < (INT_MAX >> ', it[2][1], ') && ', n1, ' >= 0) {')
# o.Raw('if (', n1, ' < (INT_MAX >> ', it[2][1], ') && ', n1, ' >= 0) {')
## o.Raw(n1, ' = ', n1, ' << ', it[2][1], ';')
o.PushInt(new, ConC('(', n1, ' << ', it[2][1], ')'))
Cls1(o, n1)
o.Raw('} else {')
o.Raw('if ((', new, ' = ', head[1:], '(', ref1, ', ', it[2], ')) == 0) goto ', labl, ';')
UseLabl()
o.append('}')
Cls1(o, ref1)
return new
if it[1] == ('CONST', 1) and type(it[1][1]) is int:
t2 = TypeExpr(it[2])
if IsInt(t2):
ref1 = Expr1(it[2], o)
n1 = New('long')
o.Raw(n1, ' = PyInt_AS_LONG ( ', ref1, ' );')
if forcenewg is not None:
new = forcenewg
else:
new = New()
o.Raw('if (', n1, ' < LONG_BIT) {')
# o.Raw(n1, ' = 0x1 << ', n1, ';')
o.PushInt(new, ConC('(0x1 << ', n1, ')'))
Cls1(o, n1)
o.Raw('} else {')
o.Raw('if ((', new, ' = ', head[1:], '(', it[1], ', ', ref1, ')) == 0) goto ', labl, ';')
UseLabl()
o.append('}')
Cls1(o, ref1)
return new
elif IsIntUndefSize(t2) or t2 is None:
ref1 = Expr1(it[2], o)
n1 = New('long')
if forcenewg is not None:
new = forcenewg
else:
new = New()
o.Raw('if (PyInt_CheckExact( ', ref1, ' ) && (', n1, ' = PyInt_AS_LONG ( ', ref1, ' )) < LONG_BIT) {')
o.PushInt(new, ConC('(0x1 << ', n1, ')'))
Cls1(o, n1)
o.Raw('} else {')
o.Raw('if ((', new, ' = ', head[1:], '(', it[1], ', ', ref1, ')) == 0) goto ', labl, ';')
UseLabl()
o.append('}')
Cls1(o, ref1)
return new
## pprint(('Lshift', TypeExpr(it[1]), TypeExpr(it[2]), it))
if head == '!PyNumber_Rshift' or head == '!PyNumber_InPlaceRshift':
t1 = TypeExpr(it[1])
t2 = TypeExpr(it[2])
if it[2][0] == 'CONST' and type(it[2][1]) is int and (31 >= it[2][1] >= 1) and IsInt(t1) and not is_pypy:
if it[1][0] == '!@PyInt_FromSsize_t':
ref1 = None
n1 = New('long')
o.Raw(n1, ' = ', it[1][1], ';')
else:
ref1 = Expr1(it[1], o)
n1 = New('long')
o.Raw(n1, ' = PyInt_AS_LONG ( ', ref1, ' );')
Cls1(o, ref1)
if forcenewg is not None:
new = forcenewg
else:
new = New()
o.Raw(n1, ' = Py_ARITHMETIC_RIGHT_SHIFT(long, ', n1, ', ', it[2][1], ');')
o.PushInt(new, n1)
Cls1(o, n1)
return new
if it[2][0] == 'CONST' and type(it[2][1]) is int and (31 >= it[2][1] >= 1) and t1 is None and not is_pypy:
ref1 = Expr1(it[1], o)
o.Raw('if (PyInt_CheckExact( ', ref1, ' )) {')
n1 = New('long')
o.Raw(n1, ' = PyInt_AS_LONG ( ', ref1, ' );')
if forcenewg is not None:
new = forcenewg
else:
new = New()
o.Raw(n1, ' = Py_ARITHMETIC_RIGHT_SHIFT(long, ', n1, ', ', it[2][1], ');')
o.PushInt(new, n1)
Cls1(o, n1)
o.append('} else {')
o.Raw('if ((', new, ' = ', head[1:], '(', ref1, ', ', it[2], ')) == 0) goto ', labl, ';')
UseLabl()
o.append('}')
Cls1(o, ref1)
return new
Debug('Uneffoicienr rshift(%s, %s) -- %s >> %s' % (t1,t2, it[1], it[2]))
if head == '!PyNumber_Multiply' or head == '!PyNumber_InPlaceMultiply':
ref = GenMultNew1(head,it,o,forcenewg, skip_float)
if ref is not None:
return ref
if head in ('!PyNumber_And', '!PyNumber_InPlaceAnd', \
'!PyNumber_Or', '!PyNumber_InPlaceOr', \
'!PyNumber_Xor', '!PyNumber_InPlaceXor') or\
(head == '!PyNumber_Lshift' and it[1][0] == '!ORD_BUILTIN' and \
it[2][0] == 'CONST' and 0 <= it[2][1] <= 24):
ref1, ref2 = Expr(o, it[1:3])
if forcenewg is not None:
new = forcenewg
else:
new = New()
check = True
skip_int = not_int_op(ref1, ref2, it[1], it[2])
if not skip_int:
t1 = TypeExpr(it[1])
t2 = TypeExpr(it[2])
check = not IsInt(t1) or not IsInt(t2)
if it[1][0] != 'CONST' and it[2][0] != 'CONST':
if check:
if IsInt(t1):
o.Raw('if (PyInt_CheckExact( ', ref2, ' )) {')
elif IsInt(t2):
o.Raw('if (PyInt_CheckExact( ', ref1, ' )) {')
else:
o.Raw('if (PyInt_CheckExact( ', ref1, ' ) && PyInt_CheckExact( ', ref2, ' )) {')
n1 = 'PyInt_AS_LONG ( ' + CVar(ref1) + ' )'
n2 = 'PyInt_AS_LONG ( ' + CVar(ref2) + ' )'
elif it[1][0] == 'CONST' and it[2][0] != 'CONST' and type(it[1][1]) is int:
if check:
o.Raw('if (PyInt_CheckExact( ', ref2, ' )) {')
n1 = str(it[1][1])
n2 = 'PyInt_AS_LONG ( ' + CVar(ref2) + ' )'
elif it[1][0] != 'CONST' and it[2][0] == 'CONST' and type(it[2][1]) is int:
if check:
o.Raw('if (PyInt_CheckExact( ', ref1, ' )) {')
n1 = 'PyInt_AS_LONG ( ' + CVar(ref1) + ' )'
n2 = str(it[2][1])
else:
skip_int = True
op = '???'
if not skip_int:
if head == '!PyNumber_And' or head == '!PyNumber_InPlaceAnd':
op = '&'
elif head == '!PyNumber_Or' or head == '!PyNumber_InPlaceOr':
op = '|'
elif head == '!PyNumber_Xor' or head == '!PyNumber_InPlaceXor':
op = '^'
elif head == '!PyNumber_Rshift' or head == '!PyNumber_InPlaceRshift':
op = '>>'
elif head == '!PyNumber_Lshift' or head == '!PyNumber_InPlaceLshift':
op = '<<'
o.PushInt(new, ConC(n1, ' ', op, ' ', n2))
if check and not skip_int:
o.append('} else {')
o.Stmt(new, '=', head[1:], ref1, ref2)
o.append('}')
elif check and skip_int:
verif(it, o)
o.Stmt(new, '=', head[1:], ref1, ref2)
elif not check and not skip_int:
pass
else:
verif(it, o)
o.Stmt(new, '=', head[1:], ref1, ref2)
o.Cls(ref1, ref2)
return new
arifm = ('!PyNumber_Multiply', '!PyNumber_Divide', '!PyNumber_Add', '!PyNumber_Subtract')
if head in arifm and IsFloat(TypeExpr(it)):
if forcenewg is not None:
new = forcenewg
else:
new = New()
fl = GenFloatExpr(it,o)
o.Stmt(new, '=', 'PyFloat_FromDouble', fl)
Cls1(o, fl)
return new
if head == '!PyNumber_Multiply':
t = TypeExpr(it)
t1 = TypeExpr(it[1])
t2 = TypeExpr(it[2])
is1 = IsInt(t1)
is2 = IsInt(t2)
ref1 = None
ref2 = None
if is1:
if IsCVar(it[1]):
l1 = CVarName(it[1])
if not is2:
ref1 = GenExpr(it[1], o, None, None, skip_float)
else:
ref1 = GenExpr(it[1], o, None, None, skip_float)
if IsList(t2) or IsTuple(t2) or IsStr(t2):
l1 = None
else:
l1 = New('long')
o.Raw(l1, ' = PyInt_AS_LONG ( ', ref1, ' );')
else:
l1 = -999
ref1 = GenExpr(it[1], o, None, None, skip_float)
if is2:
if IsCVar(it[2]):
l2 = CVarName(it[2])
if not is1:
ref2 = GenExpr(it[2], o, None, None, skip_float)
else:
ref2 = GenExpr(it[2], o, None, None, skip_float)
if IsList(t1) or IsTuple(t1) or IsStr(t1):
l2 = None
else:
l2 = New('long')
o.Raw(l2, ' = PyInt_AS_LONG ( ', ref2, ' );')
else:
l2 = -999
ref2 = GenExpr(it[2], o, None, None, skip_float)
if forcenewg is not None:
new = forcenewg
else:
new = New()
if skip_float is None:
skip_float = False
if it[1][0] == '!BUILD_LIST' or it[1][0] == '!BUILD_TUPLE' or it[1][0] == '!ORD_BUILTIN' or it[1][0] == '!PyNumber_Xor' or it[2][0] == '!PyNumber_Xor':
skip_float = True
if not skip_float:
if not_float_op(ref1,ref2):
skip_float = True
if is1 and is2:
skip_float = True
if IsStr(t1) or IsList(t1) or IsTuple(t1) or IsStr(t2) or IsList(t2) or IsTuple(t2):
skip_float = True
skip_int = not_int_op(ref1, ref2, it[1], it[2])
if skip_int and typed == 'Py_ssize_t':
skip_int = False
if not skip_float:
bin_arg_float(o, ref1, ref2, True, t1, t2)
r1 = ref1
r2 = ref2
if r1[0] == 'CONST':
r1 = r1[1]
elif is1:
r1 = ConC('(double)', l1)
else:
r1 = ConC('PyFloat_AS_DOUBLE(', r1, ')')
if r2[0] == 'CONST':
r2 = r2[1]
elif is2:
r2 = ConC('(double)', l2)
else:
r2 = ConC('PyFloat_AS_DOUBLE(', r2, ')')
o.Raw(new, ' = PyFloat_FromDouble(', r1, ' * ', r2, ');')
if not skip_int and skip_float and is1 and is2:
if IsInt(t):
o.PushInt(new, ConC(l1, ' * ', l2))
else:
o.Raw('if (!', l1, ' || !', l2, ' || (', l1, ' * ', l2, ') / ', l2, ' == ', l1, ') {')
o.PushInt(new, ConC(l1, ' * ', l2))
o.append('} else {')
if IsCVar(it[1]):
ref1 = GenExpr(it[1], o, None, None, skip_float)
if IsCVar(it[2]):
ref2 = GenExpr(it[2], o, None, None, skip_float)
o.Raw(new, ' = PyInt_Type.tp_as_number->nb_multiply(', ref1, ', ', ref2, ');')
if IsCVar(it[1]):
o.Cls(ref1)
if IsCVar(it[2]):
o.Cls(ref2)
o.append('}')
o.Cls(l1, l2)
o.Cls(ref1, ref2)
return new
elif not skip_int:
if not skip_float:
if not is1 and not is2:
o.Raw('} else if (PyInt_CheckExact( ', ref1, ' ) && PyInt_CheckExact( ', ref2, ' )) {')
elif not is1 and is2:
o.Raw('} else if (PyInt_CheckExact( ', ref1, ' )) {')
elif is1 and not is2:
o.Raw('} else if (PyInt_CheckExact( ', ref2, ' )) {')
else:
o.append('} else if (1) {')
else:
if not is1 and not is2:
o.Raw('if (PyInt_CheckExact( ', ref1, ' ) && PyInt_CheckExact( ', ref2, ' )) {')
elif not is1 and is2:
o.Raw('if (PyInt_CheckExact( ', ref1, ' )) {')
elif is1 and not is2:
o.Raw('if (PyInt_CheckExact( ', ref2, ' )) {')
else:
o.append('if (1) {')
if not is1:
l1 = New('long')
o.Raw(l1, ' = PyInt_AS_LONG ( ', ref1, ' );')
if not is2:
l2 = New('long')
o.Raw(l2, ' = PyInt_AS_LONG ( ', ref2, ' );')
if IsInt(t):
o.PushInt(new, ConC(l1, ' * ', l2))
else:
o.Raw('if (!', l1, ' || !', l2, ' || (', l1, ' * ', l2, ') / ', l2, ' == ', l1, ') {')
o.PushInt(new, ConC(l1, ' * ', l2))
o.append('} else {')
o.Raw(new, ' = PyInt_Type.tp_as_number->nb_multiply(', ref1, ', ', ref2, ');')
o.append('}')
o.Cls(l1, l2)
o.append('} else {')
else:
if not skip_float:
o.append('} else {')
else:
o.append('{')
o.Stmt(new, '=', head[1:], ref1, ref2)
o.append('}')
o.Cls(ref1, ref2)
return new
if head in ('!PyNumber_Divide', '!PyNumber_Remainder'):
t1 = TypeExpr(it[1])
t2 = TypeExpr(it[2])
if IsInt(t1) and IsInt(t2):
ref1 = GenExpr(it[1], o, None, None, skip_float)
ref2 = GenExpr(it[2], o, None, None, skip_float)
if forcenewg is not None:
new = forcenewg
else:
new = New()
n1,n2,n3 = None,None,None
n3 = New('long')
if ref1[0] == 'CONST':
n1 = ref1[1]
elif ref1[0] == 'FAST' and not current_co.IsCVar(ref1):
n1 = ConC('PyInt_AS_LONG ( ', ref1, ' )')
else:
n1 = New('long')
o.Stmt(n1, '=', 'PyInt_AS_LONG', ref1)
if ref2[0] == 'CONST':
n2 = ref2[1]
elif ref2[0] == 'FAST' and not current_co.IsCVar(ref2):
n2 = ConC('PyInt_AS_LONG ( ', ref2, ' )')
else:
n2 = New('long')
o.Stmt(n2, '=', 'PyInt_AS_LONG', ref2)
if head == '!PyNumber_Divide':
o.Raw(n3, ' = ', n1, ' / ', n2, ';')
elif head == '!PyNumber_Remainder':
o.Raw(n3, ' = ', n1, ' % ', n2, ';')
else:
Fatal('', it)
o.PushInt(new, n3)
o.Cls(n1, n2, n3, ref1, ref2)
return new
if IsInt(t1) and IsFloat(t2) and \
head == '!PyNumber_Divide':
ref1 = GenExpr(it[1], o, None, None, skip_float)
ref2 = GenExpr(it[2], o, None, None, skip_float)
if forcenewg is not None:
new = forcenewg
else:
new = New()
n1,n2,n3 = None,None,None
n3 = New('double')
if ref1[0] == 'CONST':
n1 = ref1[1]
else:
n1 = New('long')
o.Stmt(n1, '=', 'PyInt_AS_LONG', ref1)
if ref2[0] == 'CONST':
n2 = str(ref2[1])
else:
n2 = New('double')
o.Stmt(n2, '=', 'PyFloat_AsDouble', ref2)
o.Stmt(n3, '=', n1, '/', n2)
o.Stmt(new, '=', 'PyFloat_FromDouble', n3)
o.Cls(n1, n2, n3, ref1, ref2)
return new
if ( t1 is None or t1 == Kl_IntUndefSize ) and ( t2 is None or t2 == Kl_IntUndefSize ) and head =='!PyNumber_Divide':
ref1 = GenExpr(it[1], o, None, None, skip_float)
ref2 = GenExpr(it[2], o, None, None, skip_float)
if forcenewg is not None:
new = forcenewg
else:
new = New()
o.Raw('if (PyInt_CheckExact( ', ref1, ' ) && PyInt_CheckExact( ', ref2, ' )) {')
o.PushInt(new, ConC('PyInt_AS_LONG ( ', ref1, ' ) / PyInt_AS_LONG ( ', ref2, ' )'))
o.append('} else {')
o.Stmt(new, '=', head[1:], ref1, ref2)
o.append('}')
UseLabl()
o.Cls(ref1, ref2)
return new
if ( t1 is None or t1 == Kl_IntUndefSize ) and ( t2 is None or t2 == Kl_IntUndefSize ) and head =='!PyNumber_Remainder':
ref1 = GenExpr(it[1], o, None, None, skip_float)
ref2 = GenExpr(it[2], o, None, None, skip_float)
if forcenewg is not None:
new = forcenewg
else:
new = New()
o.Raw('if (PyInt_CheckExact( ', ref1, ' ) && PyInt_CheckExact( ', ref2, ' )) {')
o.PushInt(new, ConC('PyInt_AS_LONG ( ', ref1, ' ) % PyInt_AS_LONG ( ', ref2, ' )'))
o.append('} else {')
o.Stmt(new, '=', head[1:], ref1, ref2)
o.append('}')
UseLabl()
o.Cls(ref1, ref2)
return new
if ( t1 is None or t1 == Kl_IntUndefSize ) and IsInt(t2) and head =='!PyNumber_Remainder':
ref1 = GenExpr(it[1], o, None, None, skip_float)
ref2 = GenExpr(it[2], o, None, None, skip_float)
if forcenewg is not None:
new = forcenewg
else:
new = New()
o.Raw('if (PyInt_CheckExact( ', ref1, ' )) {')
if ref2[0] == 'CONST':
o.PushInt(new, ConC('PyInt_AS_LONG ( ', ref1, ' ) % ', ref2[1]))
else:
o.PushInt(new, ConC('PyInt_AS_LONG ( ', ref1, ' ) % PyInt_AS_LONG ( ', ref2, ' )'))
o.append('} else {')
o.Stmt(new, '=', head[1:], ref1, ref2)
o.append('}')
UseLabl()
o.Cls(ref1, ref2)
return new
if ( t1 is None or t1 == Kl_IntUndefSize ) and IsInt(t2) and head =='!PyNumber_Divide':
ref1 = GenExpr(it[1], o, None, None, skip_float)
ref2 = GenExpr(it[2], o, None, None, skip_float)
if forcenewg is not None:
new = forcenewg
else:
new = New()
o.Raw('if (PyInt_CheckExact( ', ref1, ' )) {')
if ref2[0] == 'CONST':
o.PushInt(new, ConC('PyInt_AS_LONG ( ', ref1, ' ) / ', ref2[1]))
else:
o.PushInt(new, ConC('PyInt_AS_LONG ( ', ref1, ' ) / PyInt_AS_LONG ( ', ref2, ' )'))
o.append('} else {')
o.Stmt(new, '=', head[1:], ref1, ref2)
o.append('}')
UseLabl()
o.Cls(ref1, ref2)
return new
if head == '!PyNumber_Power':
if it[2] == ('CONST', 2) and it[3] == 'Py_None':
ref1 = Expr1(it[1], o)
ref2 = GenExpr(('!PyNumber_Multiply', ref1, ref1), o, forcenewg, typed, skip_float)
Cls1(o, ref1)
return ref2
if IsInt(TypeExpr(it[1])) and IsFloat(TypeExpr(it[2])) and it[3] == 'Py_None':
ref1 = Expr1(it[1], o)
dbl = Expr1(it[2], o)
fl = New('double')
if dbl[0] != 'CONST':
o.Stmt(fl, '=', 'PyFloat_AsDouble', dbl)
else:
o.Raw(fl, ' = ', str(dbl[1]), ';')
o.Raw(fl, ' = pow( (double) PyInt_AsLong(', ref1, '), ', fl, ');')
ref3 = New()
o.Raw(ref3, ' = PyFloat_FromDouble( ', fl, ' );')
o.Cls(ref1, dbl, fl)
return ref3
if head == '!PyNumber_Add' and IsInt(TypeExpr(it[1])) and IsBool(TypeExpr(it[2])):
if it[1][0] == 'CONST':
r2 = Expr1(it[2],o)
add = New('long')
o, add = ToTrue(o,add,r2, it[2])
n1 = str(it[1][1])
o.Stmt(add, '=', add, '+', n1)
new = New(None, forcenewg)
o.PushInt(new, add)
o.Cls(add, n1)
return new
r1,r2 = Expr(o, it[1:])
n1 = New('long')
o.Stmt(n1, '=', 'PyInt_AS_LONG', r1)
add = New('int')
o.Stmt(add, '=', 'PyObject_IsTrue', r2)
o.Stmt(n1, '=', n1, '+', add)
new = New(None, forcenewg)
o.PushInt(new, n1)
o.Cls(r1,r2, add, n1)
return new
if head in ('!PyNumber_Subtract', '!PyNumber_Add', '!PyNumber_InPlaceSubtract', '!PyNumber_InPlaceAdd'):
return GenPlusMinusNew(head[1:],it,o,forcenewg, skip_float)
if head in ('!PyNumber_Negative',):
if len(it) > 3:
Fatal('GenNumberExpr', it)
t = TypeExpr(it)
t1 = TypeExpr(it[1])
ref1 = GenExpr(it[1], o, None, None, skip_float)
if forcenewg is not None:
new = forcenewg
else:
new = New()
n1,n2,n3 = None,None, None
canbeint = IsNoneOrInt(t1)
canbefloat = t1 in (None, Kl_Float) and not skip_float
## act = []
onlyint = False
onlyfloat = False
if canbeint:
cmp = IsInt(t1)
n3 = New('long')
if not cmp:
o.Raw('if (PyInt_CheckExact( ', ref1, ' )) {')
else:
onlyint = True
if ref1[0] == 'CONST':
n1 = ref1[1]
else:
n1 = New('long')
o.Stmt(n1, '=', 'PyInt_AS_LONG', ref1)
o.Stmt(n3, '=', 0, '-', n1)
o.PushInt(new, n3)
o.Cls(n1, n3)
if canbefloat and not onlyint:
cmp = t1 in (Kl_Float,)
if canbeint:
pre = '} else '
else:
pre = ''
if not cmp:
o.Stmt(pre + 'if (PyFloat_CheckExact(', ref1, ')) {')
t1 = Kl_Float
else:
if canbeint:
o.append(pre + 'if (1) {')
else:
onlyfloat = True
if IsFloat(t1):
s1 = 'PyFloat_AS_DOUBLE('+ CVar(ref1)+')'
elif IsInt(t1):
s1 = '(double)PyInt_AS_LONG ( '+ CVar(ref1)+' )'
else:
s1 = 'PyFloat_AsDouble('+ CVar(ref1)+')'
if ref1[0] == 'CONST':
s1 = '((double)' + str(ref1[1]) +')'
o.Raw(new, ' = PyFloat_FromDouble(-(', s1, '));')
if onlyint and t != Kl_Short:
pass
elif onlyint or onlyfloat:
pass
else:
if canbeint:
o.append('} else {')
o.Stmt(new, '=', head[1:], ref1)
o.append('}')
elif canbefloat:
o.append('} else {')
o.Stmt(new, '=', head[1:], ref1)
o.append('}')
else:
o.Stmt(new, '=', head[1:], ref1)
Cls1(o, ref1)
return new
#
# Base part
#
return common_call(head[1:], it, o, typed, forcenewg)
def to_double_0(o, ref2, n2, v2):
n2 = v2[1].strip()
del o[-1]
l = len(o)
Cls1(o, ref2)
if len(o) > l:
assert len(o) == l + 1
del o[-1]
if is_not_active_typed(n2) and n2.startswith('double_'):
n2 = reactivate_typed(n2)
elif n2.startswith('Loc_'):
pass
elif len(o) > 0 and n2.startswith('double_') and (n2 + ' = ') in o[-1]:
_n = New('double')
o[-1] = o[-1].replace(n2 + ' = ', ConC(_n) + ' = ')
assert (ConC(_n) + ' = ') in o[-1]
n2 = _n
else:
_n = New('double')
if CVar(_n) != n2:
o.Raw(_n, ' = ', n2, ';')
n2 = _n
return n2
def to_long_0(o, ref2, n2, v2):
n2 = v2[1].strip()
del o[-1]
l = len(o)
Cls1(o, ref2)
if len(o) > l:
assert len(o) == l + 1
del o[-1]
if is_not_active_typed(n2) and n2.startswith('long_'):
n2 = reactivate_typed(n2)
elif n2.startswith('Loc_'):
pass
elif len(o) > 0 and (n2.startswith('Py_ssize_t_') or n2.startswith('long_')) and (n2 + ' = ') in o[-1]:
_n = New('long')
o[-1] = o[-1].replace(n2 + ' = ', ConC(_n) + ' = ')
assert (ConC(_n) + ' = ') in o[-1]
n2 = _n
else:
_n = New('long')
if CVar(_n) != n2:
o.Raw(_n, ' = ', n2, ';')
n2 = _n
return n2
def to_long(o, ref2, n2):
if not istempref(ref2) and ref2[0] != 'CONST':
## print ConC(ref2)
n2 = New('long')
o.Stmt(n2, '=', 'PyInt_AS_LONG', ref2)
return ref2, n2
v2 = []
tail = []
while len(o) > 0 and (o[-1].startswith('CLEARTEMP') or o[-1].startswith('Py_CLEAR')):
tail = [o[-1]] + tail
del o[-1]
if len(o) > 0 and TextMatch(o[-1], ('temp[', '*', '] = PyInt_FromLong (', '*', ');'), v2) and v2[0] == str(ref2[1]):
ref2, n2 = None, to_long_0(o, ref2, n2, v2)
elif len(o) > 0 and TextMatch(o[-1], ('if ((temp[', '*', '] = PyInt_FromLong ( ', '*', ' )) == 0) goto ', '*', ';'), v2) and v2[0] == str(ref2[1]):
ref2, n2 = None, to_long_0(o, ref2, n2, v2)
## elif len(o) > 0 and 'PyInt_From' in o[-1]:
## Fatal('Not recognised', o1, ref2)
else:
n2 = New('long')
o.Stmt(n2, '=', 'PyInt_AS_LONG', ref2)
o.extend(tail)
return ref2, n2
def can_be_to_long(o, ref2, n2):
v2 = []
tail = []
while len(o) > 0 and (o[-1].startswith('CLEARTEMP') or o[-1].startswith('Py_CLEAR')):
tail = [o[-1]] + tail
del o[-1]
if len(o) > 0 and TextMatch(o[-1], ('temp[', '*', '] = PyInt_FromLong (', '*', ');'), v2) and v2[0] == str(ref2[1]):
ref2, n2 = None, to_long_0(o, ref2, n2, v2)
elif len(o) > 0 and TextMatch(o[-1], ('if ((temp[', '*', '] = PyInt_FromLong ( ', '*', ' )) == 0) goto ', '*', ';'), v2) and v2[0] == str(ref2[1]):
ref2, n2 = None, to_long_0(o, ref2, n2, v2)
elif len(o) > 0 and TextMatch(o[-1], ('temp[', '*', '] = PyInt_FromLong(', '*', ');'), v2) and v2[0] == str(ref2[1]):
ref2, n2 = None, to_long_0(o, ref2, n2, v2)
elif len(o) > 0 and TextMatch(o[-1], ('if ((temp[', '*', '] = PyInt_FromLong( ', '*', ' )) == 0) goto ', '*', ';'), v2) and v2[0] == str(ref2[1]):
ref2, n2 = None, to_long_0(o, ref2, n2, v2)
elif len(o) > 0 and 'PyInt_From' in o[-1]:
Fatal('Not recognised', o, ref2)
## else:
## pprint(o)
o.extend(tail)
return ref2, n2
def can_be_to_double(o, ref2, n2):
v2 = []
tail = []
while len(o) > 0 and (o[-1].startswith('CLEARTEMP') or o[-1].startswith('Py_CLEAR')):
tail = [o[-1]] + tail
del o[-1]
if len(o) > 0 and TextMatch(o[-1], ('temp[', '*', '] = PyFloat_FromDouble (', '*', ');'), v2) and v2[0] == str(ref2[1]):
ref2, n2 = None, to_double_0(o, ref2, n2, v2)
elif len(o) > 0 and TextMatch(o[-1], ('if ((temp[', '*', '] = PyFloat_FromDouble ( ', '*', ' )) == 0) goto ', '*', ';'), v2) and v2[0] == str(ref2[1]):
ref2, n2 = None, to_double_0(o, ref2, n2, v2)
elif len(o) > 0 and TextMatch(o[-1], ('temp[', '*', '] = PyFloat_FromDouble(', '*', ');'), v2) and v2[0] == str(ref2[1]):
ref2, n2 = None, to_double_0(o, ref2, n2, v2)
elif len(o) > 0 and TextMatch(o[-1], ('if ((temp[', '*', '] = PyFloat_FromDouble(', '*', ')) == 0) goto ', '*', ';'), v2) and v2[0] == str(ref2[1]):
ref2, n2 = None, to_double_0(o, ref2, n2, v2)
elif len(o) > 0 and 'PyInt_From' in o[-1]:
Fatal('Not recognised', o, ref2)
## else:
## pprint(o)
o.extend(tail)
return ref2, n2
sequence_op = ('!PyList_GetSlice', '!PyTuple_GetSlice', '!PySequence_GetSlice', '!_PyEval_ApplySlice', '!BUILD_LIST', '!BUILD_TUPLE')
def IsNotIntFloat(t):
return IsStr(t) or IsTuple(t) or IsList(t) or IsLong(t) or ( t is not None and (is_old_class_inst(t) or is_old_class_typ(t))) or (IsNot(t, Kl_Int) and IsNot(t, Kl_Float))
def is_not_int_float(it):
if type(it) is tuple:
if it[0] in sequence_op:
return True
if it[0] == 'CONST' and type(it[1]) in (list, tuple, str, long):
return True
if IsNotIntFloat(TypeExpr(it)):
return True
## pprint(it)
return False
def GenMultNew1(head,it,o,forcenewg, skip_float):
revert = False
if it[1][0] == 'CONST' and type(it[1][1]) is int and head == '!PyNumber_Multiply':
it = (it[0], it[2], it[1])
revert = True
t = TypeExpr(it)
t1 = TypeExpr(it[1])
t2 = TypeExpr(it[2])
n1,n2,n3 = None,None,None
f1, f2 = None, None
## canbeint = CanBeInt(t1,t2)
## canbefloat = CanBeFloat(t1,t2) and not skip_float
## if is_not_int_float(it) or IsStr(t1) or IsTuple(t1) or IsList(t1) or IsStr(t2) or IsTuple(t2) or IsList(t2):
## canbeint = False
## canbefloat = False
if IsChar(t1) and IsInt(t2):
ref1 = Expr1(it[1], o)
n1 = New('char')
o.Raw(n1, ' = PyString_AS_STRING ( ', ref1, ' )[0];')
o.Cls(n1)
ref2 = Expr1(it[2], o)
n2 = New('long')
assert istempref(ref2)
o.Raw(n2, ' = PyInt_AS_LONG ( ', ref2, ' );')
o.Cls(ref2)
if forcenewg is not None:
new = forcenewg
else:
new = New()
o.Raw(new, ' = PyString_FromStringAndSize (NULL, ', n2, ');')
n3 = New('int')
s1 = New('charref')
o.Raw(s1, ' = PyString_AS_STRING ( ', new, ' );')
o.Raw('for (', n3, ' = 0;', n3, ' < ', n2, ';', n3, ' ++) {')
o.Raw(s1, '[', n3, '] = ', n1, ';')
o.Raw('}')
o.Cls(n1, n2, n3, s1)
return new
if IsChar(t2) and IsInt(t1) and it[2][0] == 'CONST':
ref1 = Expr1(it[1], o)
n1 = New('long')
assert istempref(ref1)
o.Raw(n1, ' = PyInt_AS_LONG ( ', ref1, ' );')
o.Cls(ref1)
if forcenewg is not None:
new = forcenewg
else:
new = New()
o.Raw(new, ' = PyString_FromStringAndSize (NULL, ', n1, ');')
h = charhex(it[2][1])
o.Raw('memset (PyString_AS_STRING ( ', new, ' ), ', h, ', ', n1, ');')
o.Cls(n1)
return new
if it[2][0] == 'CONST' and type(it[2][1]) is int and IsInt(t1):
if it[1][0] == '!@PyInt_FromSsize_t' and not current_co.IsCVar(it[1][2]):
ref1 = it[1][2]
n1 = New('long')
o.Raw(n1, ' = ', it[1][1], ';')
else:
ref1 = Expr1(it[1], o)
n1 = New('long')
o.Raw(n1, ' = PyInt_AS_LONG ( ', ref1, ' );')
if forcenewg is not None:
new = forcenewg
else:
new = New()
n2 = New('long')
o.Raw(n2, ' = ',n1, ' * ', it[2][1], ';')
if IsInt(t):
o.PushInt(new, n2)
else:
o.Raw('if (', n2, ' / ', it[2][1], ' == ', n1, ') {')
o.PushInt(new, n2)
o.append('} else {')
if not revert:
o.Raw(new, ' = PyInt_Type.tp_as_number->nb_multiply(', ref1, ', ', it[2], ');')
else:
o.Raw(new, ' = PyInt_Type.tp_as_number->nb_multiply(', it[2], ', ', ref1, ');')
o.append('}')
Cls1(o, ref1)
o.Cls(n1, n2)
return new
if it[2][0] == 'CONST' and type(it[2][1]) is int and (t1 is None or IsIntUndefSize(t1)):
if it[2][1] == 0:
ref1 = Expr1(it[1], o)
o.Raw('if (PyInt_CheckExact( ', ref1, ' )) {')
if forcenewg is not None:
new = forcenewg
else:
new = New()
o.Raw(new, ' = ', it[2], ';')
o.INCREF(new)
o.append('} else {')
if not revert:
o.Raw('if ((', new, ' = ', head[1:], ' ( ', ref1, ' , ', it[2], ' )) == 0) goto ', labl, ';')
else:
o.Raw('if ((', new, ' = ', head[1:], ' ( ', it[2], ' , ', ref1, ' )) == 0) goto ', labl, ';')
UseLabl()
o.append('}')
Cls1(o, ref1)
return new
if it[2][1] == 1:
ref1 = Expr1(it[1], o)
o.Raw('if (PyInt_CheckExact( ', ref1, ' )) {')
if forcenewg is not None:
new = forcenewg
else:
new = New()
o.Raw(new, ' = ', ref1, ';')
if istempref(ref1):
o.Raw(ref1, ' = 0;')
else:
o.INCREF(new)
o.append('} else {')
if not revert:
o.Raw('if ((', new, ' = ', head[1:], ' ( ', ref1, ' , ', it[2], ' )) == 0) goto ', labl, ';')
else:
o.Raw('if ((', new, ' = ', head[1:], ' ( ', it[2], ' , ', ref1, ' )) == 0) goto ', labl, ';')
UseLabl()
Cls1(o, ref1)
o.append('}')
return new
ref1 = Expr1(it[1], o)
n1 = New('long')
o.Raw('if (PyInt_CheckExact( ', ref1, ' ) && ((', n1, ' = PyInt_AS_LONG ( ', ref1, ' )), ', n1, ' == ((', n1, ' * ', it[2][1], ') / ', it[2][1], '))) {')
if forcenewg is not None:
new = forcenewg
else:
new = New()
o.PushInt(new, ConC(n1, ' * ', it[2][1]))
o.append('} else {')
if not revert:
o.Raw('if ((', new, ' = ', head[1:], ' ( ', ref1, ' , ', it[2], ' )) == 0) goto ', labl, ';')
else:
o.Raw('if ((', new, ' = ', head[1:], ' ( ', it[2], ' , ', ref1, ' )) == 0) goto ', labl, ';')
UseLabl()
o.append('}')
Cls1(o, ref1)
Cls1(o, n1)
return new
def GenPlusMinusNew(head,it,o,forcenewg, skip_float):
if len(it) > 3:
Fatal('GenNumberExpr', it)
t = TypeExpr(it)
t1 = TypeExpr(it[1])
t2 = TypeExpr(it[2])
n1,n2,n3 = None,None,None
f1, f2 = None, None
o1 = Out()
o2 = Out()
o_old = o
o = Out()
canbeint = CanBeInt(t1,t2)
canbefloat = CanBeFloat(t1,t2) and not skip_float
if is_not_int_float(it) or IsStr(t1) or IsTuple(t1) or IsList(t1) or IsStr(t2) or IsTuple(t2) or IsList(t2):
canbeint = False
canbefloat = False
## act = []
can_else = True
## incref1 = False
## incref2 = False
if IsCVar(it[1]) and IsInt(t1):
n1 = CVarName(it[1])
ref1 = None
else:
ref1 = GenExpr(it[1], o1, None, None, skip_float)
if canbeint and IsInt(t1) and istempref(ref1):
ref1, n1 = can_be_to_long(o1, ref1, n1)
elif canbefloat and IsFloat(t1) and istempref(ref1):
ref1, f1 = can_be_to_double(o1, ref1, f1)
## if n1 is None and len(o1) > 0 and o1[-1].startswith('Py_INCREF'):
## del o1[-1]
## incref1 = True
if IsCVar(it[2]) and IsInt(t2):
n2 = CVarName(it[2])
ref2 = None
else:
ref2 = GenExpr(it[2], o2, None, None, skip_float)
if canbeint and IsInt(t2) and istempref(ref2):
ref2, n2 = can_be_to_long(o2, ref2, n2)
elif canbefloat and IsFloat(t2) and istempref(ref2):
ref2, f2 = can_be_to_double(o2, ref2, f2)
## if n2 is None and len(o2) > 0 and o2[-1].startswith('Py_INCREF'):
## del o2[-1]
## incref2 = True
if ref1 == ('CONST', None):
return ref1
if ref2 == ('CONST', None):
return ref2
if forcenewg is not None:
new = forcenewg
else:
new = New()
if canbeint:
cmp = (IsInt(t1), IsInt(t2))
## nooverflow = IsShort(t1) and IsShort(t2)
if cmp == (False, False):
o.Raw('if (PyInt_CheckExact( ', ref1, ' ) && PyInt_CheckExact( ', ref2, ' )) {')
elif cmp == (True, False):
o.Raw('if (PyInt_CheckExact( ', ref2, ' )) {')
elif cmp == (False, True):
o.Raw('if (PyInt_CheckExact( ', ref1, ' )) {')
else:
if IsShort(t1) and IsShort(t2) and not canbefloat:
can_else = False
elif IsInt(t1) and IsShort(t2) and IsInt(t) and not canbefloat:
can_else = False
elif IsInt(t2) and IsShort(t1) and IsInt(t) and not canbefloat:
can_else = False
else:
o.append('if (1) {')
if n1 is not None:
pass
elif ref1 is None:
pass
elif ref1[0] == 'CONST':
n1 = ref1[1]
else:
n1 = New('long')
o.Stmt(n1, '=', 'PyInt_AS_LONG', ref1)
if n2 is not None:
pass
elif ref2 is None:
pass
elif ref2[0] == 'CONST':
n2 = ref2[1]
else:
n2 = New('long')
o.Stmt(n2, '=', 'PyInt_AS_LONG', ref2)
nlabel = New('label')
if head in ('PyNumber_Add', 'PyNumber_InPlaceAdd'):
if not can_else:
n3 = '(' + ConC(n1, ' + ', n2) + ')'
else:
n3 = New('long')
o.Raw(n3, ' = ', n1, ' + ', n2, ';')
o.Stmt('if ((', n3, '^', n1, ') < 0 && (', n3, '^', n2, ') < 0) goto', nlabel, ';')
else:
if not can_else:
n3 = '(' + ConC(n1, ' - ', n2) + ')'
else:
n3 = New('long')
o.Raw(n3, ' = ', n1, ' - ', n2, ';')
o.Stmt('if ((', n3, '^', n1, ') < 0 && (', n3, '^~', n2, ') < 0) goto', nlabel, ';')
o.PushInt(new, n3)
o.Cls(n3)
if canbefloat:
cmp = (IsIntOrFloat(t1), IsIntOrFloat(t2))
if canbeint:
pre = '} else '
else:
pre = ''
if cmp == (False, False):
o.Stmt(pre + 'if (PyFloat_CheckExact(', ref1, ') && PyFloat_CheckExact(', ref2, ')) {')
t1 = Kl_Float
t2 = Kl_Float
elif cmp == (True, False):
o.Stmt(pre + 'if (PyFloat_CheckExact(', ref2, ')) {')
t2 = Kl_Float
elif cmp == (False, True):
o.Stmt(pre + 'if (PyFloat_CheckExact(', ref1, ')) {')
t1 = Kl_Float
else:
o.append(pre + 'if (1) {')
if f1 is not None:
s1 = f1
elif IsFloat(t1):
s1 = 'PyFloat_AS_DOUBLE('+ CVar(ref1)+')'
elif IsInt(t1):
s1 = '(double)PyInt_AS_LONG ( '+ CVar(ref1)+' )'
else:
s1 = 'PyFloat_AsDouble('+ CVar(ref1)+')'
if f2 is not None:
s2 = f2
elif IsFloat(t2):
s2 = 'PyFloat_AS_DOUBLE('+ CVar(ref2)+')'
elif IsInt(t2):
s2 = '(double)PyInt_AS_LONG ( '+ CVar(ref2)+' )'
else:
s2 = 'PyFloat_AsDouble('+ CVar(ref2)+')'
if ref1 is None and n1 is not None:
s1 = '((double)' + ConC(n1) +')'
elif ref1 is None and f1 is not None:
s1 = ConC(f1)
elif ref1[0] == 'CONST':
s1 = '((double)' + str(ref1[1]) +')'
if ref2 is None and n2 is not None:
s2 = '((double)' + ConC(n2) +')'
elif ref2 is None and f2 is not None:
s2 = ConC(f2)
elif ref2[0] == 'CONST':
s2 = '((double)' + str(ref2[1]) +')'
if head in ('PyNumber_Add', 'PyNumber_InPlaceAdd'):
o.Raw(new, ' = PyFloat_FromDouble(', s1, ' + ', s2, ');')
else:
o.Raw(new, ' = PyFloat_FromDouble(', s1, ' - ', s2, ');')
_1 = False
_2 = False
if canbeint:
if not canbefloat and not can_else:
pass ##o.append('}')
else:
o.Stmt('} else {', nlabel, ':')
if ref1 is None:
ref1 = New()
o.PushInt(ref1, n1)
_1 = True
if ref2 is None:
ref2 = New()
o.PushInt(ref2, n2)
_2 = True
o.Stmt(new, '=', head, ref1, ref2)
if _1:
o.Cls(ref1)
if _2:
o.Cls(ref2)
o.append('}')
elif canbefloat:
o.append('} else {')
if ref1 is None and f1 is None:
ref1 = New()
o.PushInt(ref1, n1)
_1 = True
if ref2 is None and f2 is None :
ref2 = New()
o.PushInt(ref2, n2)
_2 = True
if ref1 is None and f1 is not None:
ref1 = New()
o.PushFloat(ref1, f1)
_1 = True
if ref2 is None and f2 is not None :
ref2 = New()
o.PushFloat(ref2, f2)
_2 = True
o.Stmt(new, '=', head, ref1, ref2)
if _1:
o.Cls(ref1)
if _2:
o.Cls(ref2)
o.append('}')
else:
verif(it, o)
if ref1 is None:
ref1 = New()
o.PushInt(ref1, n1)
_1 = True
if ref2 is None:
ref2 = New()
o.PushInt(ref2, n2)
_2 = True
o.Stmt(new, '=', head, ref1, ref2)
if _1:
o.Cls(ref1)
if _2:
o.Cls(ref2)
o.Cls(ref1, ref2, n1, n2, f1, f2)
_o = Out()
## if 'PyInt_From' in repr(o1) or 'PyInt_From' in repr(o2) :
## pprint((o1, o2, o))
## pprint( o1[o1+o2+o)
_o.extend(o1 + o2 + o)
v2 = []
## o_old.extend(o)
## return new
## if True: ###len(o1) == 1 and len(o2) == 0 and it[2][0] == 'CONST' and type(it[2][1]) is int and len(o) == 2:
if TxMatch(_o, 0, """
long_$8 = $11;
long_$9 = long_$8 $12 $14;
temp[$0] = PyInt_FromLong ( long_$9 );
""", v2):
v2[11].strip()
TxRepl(_o, 0, """temp[$0] = PyInt_FromLong ( (($11) $12 $14) );""", v2)
o_old.extend(_o)
return new
if TxMatch(_o, 0, """
if ((Py_ssize_t_$8 = $11) == -1) goto label_$15;
long_$9 = Py_ssize_t_$8 $12 $14;
temp[$0] = PyInt_FromLong ( long_$9 );
""", v2):
v2[11].strip()
TxRepl(_o, 0, """if ((Py_ssize_t_$8 = $11) == -1) goto label_$15;
temp[$0] = PyInt_FromLong ( Py_ssize_t_$8 $12 $14 );""", v2)
o_old.extend(_o)
return new
if TxMatch(_o, 0, (
'if ((Py_ssize_t_$5 = $11) == -1) goto label_$0;',
'temp[$1] = PyInt_FromLong ( Py_ssize_t_$5 );',
'if (1) {',
'long_$8 = PyInt_AS_LONG ( temp[$1] );',
'long_$7 = $12 $19 long_$8;',
'if ($14) goto label_$15 ;',
'temp[$2] = PyInt_FromLong ( long_$7 );',
'} else { label_$15 :;',
'temp[$3] = PyInt_FromLong ( $12 );',
'if ((temp[$2] = PyNumber_$18 ( temp[$3] , temp[$1] )) == 0) goto label_$0;',
'CLEARTEMP($3);',
'}',
'CLEARTEMP($1);'), v2):
TxRepl(_o, 0, (
'if ((Py_ssize_t_$5 = $11) == -1) goto label_$0;',
'if (1) {',
'long_$8 = Py_ssize_t_$5;',
'long_$7 = $12 $19 long_$8;',
'if ($14) goto label_$15 ;',
'temp[$2] = PyInt_FromLong ( long_$7 );',
'} else { label_$15 :;',
'temp[$1] = PyInt_FromLong ( Py_ssize_t_$5 );',
'temp[$3] = PyInt_FromLong ( $12 );',
'if ((temp[$2] = PyNumber_$18 ( temp[$3] , temp[$1] )) == 0) goto label_$0;',
'CLEARTEMP($3);',
'CLEARTEMP($1);',
'}'), v2)
o_old.extend(_o)
return new
if TxMatch(_o, 0, (
'temp[$0] = PyInt_FromLong ( $11 );',
'if (PyInt_CheckExact( $17 )) {',
'long_$8 = PyInt_AS_LONG ( temp[$0] );',
'long_$9 = PyInt_AS_LONG ( $17 );',
'long_$7 = long_$8 $15 long_$9;',
'if ($12) goto label_$14 ;',
'temp[$1] = PyInt_FromLong ( long_$7 );',
'} else if (PyFloat_CheckExact( $17 )) {',
'temp[$1] = PyFloat_FromDouble((double)PyInt_AS_LONG ( temp[$0] ) $15 PyFloat_AS_DOUBLE($17));',
'} else { label_$14 :;',
'if ((temp[$1] = PyNumber_$18 ( temp[$0] , $17 )) == 0) goto label_$10;',
'}',
'CLEARTEMP($0);'), v2) and v2[11] != 'long_' + v2[7] and v2[11] != 'long_' + v2[9]:
TxRepl(_o, 0, (
'if (PyInt_CheckExact( $17 )) {',
'long_$8 = $11;',
'long_$9 = PyInt_AS_LONG ( $17 );',
'long_$7 = long_$8 $15 long_$9;',
'if ($12) goto label_$14 ;',
'temp[$1] = PyInt_FromLong ( long_$7 );',
'} else if (PyFloat_CheckExact( $17 )) {',
'temp[$1] = PyFloat_FromDouble((double)($11) $15 PyFloat_AS_DOUBLE($17));',
'} else { label_$14 :;',
'temp[$0] = PyInt_FromLong ( $11 );',
'if ((temp[$1] = PyNumber_$18 ( temp[$0] , $17 )) == 0) goto label_$10;',
'CLEARTEMP($0);',
'}'), v2)
o_old.extend(_o)
return new
if TxMatch(_o, 0, (
'if ((Py_ssize_t_$5 = PyObject_Size ( GETLOCAL(refs) )) == -1) goto label_$10;',
'temp[$0] = PyInt_FromLong ( Py_ssize_t_$5 );',
'if (PyInt_CheckExact( $15 )) {',
'long_$8 = PyInt_AS_LONG ( $15 );',
'long_$9 = PyInt_AS_LONG ( temp[$0] );',
'long_$7 = long_$8 $12 long_$9;',
'if ($11) goto label_$13 ;',
'temp[1] = PyInt_FromLong ( long_$7 );',
'} else if (PyFloat_CheckExact( $15 )) {',
'temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($15) $12 (double)PyInt_AS_LONG ( temp[$0] ));',
'} else { label_$13 :;',
'if ((temp[$1] = PyNumber_$14 ( $15 , temp[$0] )) == 0) goto label_$10;',
'}',
'CLEARTEMP($0);'), v2):
TxRepl(_o, 0, (
'if ((Py_ssize_t_$5 = PyObject_Size ( GETLOCAL(refs) )) == -1) goto label_$10;',
'if (PyInt_CheckExact( $15 )) {',
'long_$8 = PyInt_AS_LONG ( $15 );',
'long_$9 = Py_ssize_t_$5;',
'long_$7 = long_$8 $12 long_$9;',
'if ($11) goto label_$13 ;',
'temp[1] = PyInt_FromLong ( long_$7 );',
'} else if (PyFloat_CheckExact( $15 )) {',
'temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($15) $12 (double)Py_ssize_t_$5);',
'} else { label_$13 :;',
'temp[$0] = PyInt_FromLong ( Py_ssize_t_$5 );',
'if ((temp[$1] = PyNumber_$14 ( $15 , temp[$0] )) == 0) goto label_$10;',
'CLEARTEMP($0);',
'}'), v2)
o_old.extend(_o)
return new
## dsc1 = parse_code_type(o1)
## dsc2 = parse_code_type(o2)
if len(o1) == 0 and len(o2) > 0 and 'PyInt_FromLong' in o2[-1]:
## v3 = []
o2_1 = Out()
o2_1.extend(o2)
o2_1.extend(o)
if TxMatch(o2_1, len(o2_1) - (len(o) + 1), """
temp[$0] = PyInt_FromLong ( $4 );
if (PyInt_CheckExact( $11 )) {
long_$5 = PyInt_AS_LONG ( $11 );
long_$6 = PyInt_AS_LONG ( temp[$0] );
long_$2 = long_$5 $15 long_$6;
if ($12) goto label_$7 ;
temp[$1] = PyInt_FromLong ( long_$2 );
} else if (PyFloat_CheckExact( $11 )) {
temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($11) $15 (double)PyInt_AS_LONG ( temp[$0] ));
} else { label_$7 :;
if ((temp[$1] = PyNumber_$14 ( $11 , temp[$0] )) == 0) goto label_$10;
}
CLEARTEMP($0);
""", v2) and v2[4] != 'long_' + v2[5] and v2[4] != 'long_' + v2[2]:
TxRepl(o2_1, 0, """
if (PyInt_CheckExact( $11 )) {
long_$5 = PyInt_AS_LONG ( $11 );
long_$6 = $4;
long_$2 = long_$5 $15 long_$6;
if ($12) goto label_$7 ;
temp[$1] = PyInt_FromLong ( long_$2 );
} else if (PyFloat_CheckExact( $11 )) {
temp[$1] = PyFloat_FromDouble(PyFloat_AS_DOUBLE($11) $15 (double)($4));
} else { label_$7 :;
temp[$0] = PyInt_FromLong ( $4 );
if ((temp[$1] = PyNumber_$14 ( $11 , temp[$0] )) == 0) goto label_$10;
CLEARTEMP($0);
}
""", v2)
o_old.extend(o2_1)
return new
if TxMatch(o2_1, len(o2_1) - (len(o) + 1), """
temp[$0] = PyInt_FromLong ( $4 );
if (PyInt_CheckExact( $11 )) {
long_$5 = PyInt_AS_LONG ( $11 );
long_$6 = PyInt_AS_LONG ( temp[$0] );
long_$2 = long_$5 $15 long_$6;
if ($12) goto label_$7 ;
temp[$1] = PyInt_FromLong ( long_$2 );
} else { label_$7 :;
if ((temp[$1] = PyNumber_$14 ( $11 , temp[$0] )) == 0) goto label_$10;
}
CLEARTEMP($0);
""", v2) and v2[4] != 'long_' + v2[5] and v2[4] != 'long_' + v2[2]:
TxRepl(o2_1, 0, """
if (PyInt_CheckExact( $11 )) {
long_$5 = PyInt_AS_LONG ( $11 );
long_$6 = $4;
long_$2 = long_$5 $15 long_$6;
if ($12) goto label_$7 ;
temp[$1] = PyInt_FromLong ( long_$2 );
} else { label_$7 :;
temp[$0] = PyInt_FromLong ( $4 );
if ((temp[$1] = PyNumber_$14 ( $11 , temp[$0] )) == 0) goto label_$10;
CLEARTEMP($0);
}
""", v2)
o_old.extend(o2_1)
return new
if TxMatch(o2_1, len(o2_1) - (len(o) + 1), """
temp[$0] = PyInt_FromLong ( $4 );
if (1) {
long_$5 = PyInt_AS_LONG ( $11 );
long_$6 = PyInt_AS_LONG ( temp[$0] );
long_$2 = long_$5 $15 long_$6;
if ($12) goto label_$7 ;
temp[$1] = PyInt_FromLong ( long_$2 );
} else { label_$7 :;
if ((temp[$1] = PyNumber_$14 ( $11 , temp[$0] )) == 0) goto label_$10;
}
CLEARTEMP($0);
""", v2) and v2[4] != 'long_' + v2[5] and v2[4] != 'long_' + v2[2]:
TxRepl(o2_1, 0, """
if (1) {
long_$5 = PyInt_AS_LONG ( $11 );
long_$6 = $4;
long_$2 = long_$5 $15 long_$6;
if ($12) goto label_$7 ;
temp[$1] = PyInt_FromLong ( long_$2 );
} else { label_$7 :;
temp[$0] = PyInt_FromLong ( $4 );
if ((temp[$1] = PyNumber_$14 ( $11 , temp[$0] )) == 0) goto label_$10;
CLEARTEMP($0);
}
""", v2)
o_old.extend(o2_1)
return new
if len(o2) == 0 and len(o1) == 5:
## v3 = []
o2_1 = Out()
o2_1.extend(o1)
o2_1.extend(o)
if TxMatch(o2_1, 0, """
if ($10) {
temp[$4] = PyInt_FromLong ( $11 );
} else {
if ((temp[$4] = $12) == 0) goto label_$0;
}
if (PyInt_CheckExact( temp[$4] )) {
long_$3 = PyInt_AS_LONG ( temp[$4] );
long_$2 = long_$3 $17 $13;
if ($14) goto label_$15 ;
temp[$5] = PyInt_FromLong ( long_$2 );
} else { label_$15 :;
if ((temp[$5] = $16) == 0) goto label_$0;
}
CLEARTEMP($4);
""", v2):
TxRepl(o2_1, 0, """
if ($10) {
long_$3 = $11;
long_$2 = long_$3 $17 $13;
if ($14) goto label_$15 ;
temp[$5] = PyInt_FromLong ( long_$2 );
} else { label_$15 :;
if ((temp[$4] = $12) == 0) goto label_$0;
if ((temp[$5] = $16) == 0) goto label_$0;
CLEARTEMP($4);
}
""", v2)
o_old.extend(o2_1)
return new
if len(o1) == 8 and len(o2) == 8:
## v3 = []
o2_1 = Out()
o2_1.extend(o1)
o2_1.extend(o2)
o2_1.extend(o)
if TxMatch(o2_1, 0, """
if ($10) {
if (($12) goto label_$11;
temp[$0] = PyInt_FromLong ( $14 );
} else {
$16
if ((temp[$0] = $17) == 0) goto label_$11;
CLEARTEMP($18);
if ($10) {
if ($13) goto label_$11;
temp[$1] = PyInt_FromLong ( $15 );
} else {
$19
if ((temp[$1] = $9) == 0) goto label_$11;
CLEARTEMP($8);
""", v2):
TxRepl(o2_1, 0, """
if ($10) {
if (($12) goto label_$11;
temp[$0] = PyInt_FromLong ( $14 );
if ($13) goto label_$11;
temp[$1] = PyInt_FromLong ( $15 );
} else {
$16
if ((temp[$0] = $17) == 0) goto label_$11;
CLEARTEMP($18);
$19
if ((temp[$1] = $9) == 0) goto label_$11;
CLEARTEMP($8);
}
""", v2)
## pprint(o2_1)
o_old.extend(o2_1)
return new
_o = o1 + o2 + o
## if IsTuple(t1) and IsTuple(t2) and it[1][0] in ('!BUILD_TUPLE', 'CONST') and it[2][0] in ('!BUILD_TUPLE', 'CONST'):
## pprint(it)
## print
## oo = "".join(o1 + o2)
## if (len(o1) != 0 or len(o2) != 0) and not IsTuple(t1) and not IsList(t1) and not IsTuple(t2) and not IsList(t2) and not IsStr(t1) and not IsStr(t2) and 'PyInt_FromLong' in oo:
## print '{'
## _o = o1 + o2 + o
## optimize(o1)
## optimize(o2)
## optimize(o)
## pprint((o1, o2, o))
## ## print ':'
## ## pprint(_o)
## ## optimize(_o)
## ## print ':'
## ## pprint(_o)
## print '}'
o_old.extend(_o)
return new
def CanBeFloat(t1, t2):
if IsNoneOrIntOrFloat(t1) and IsNoneOrIntOrFloat(t2):
if t1 == Kl_IntUndefSize and t2 == Kl_IntUndefSize:
return False
if IsInt(t1) and IsInt(t2):
return False
if IsInt(t1) and t2 == Kl_IntUndefSize:
return False
if IsInt(t2) and t1 == Kl_IntUndefSize:
return False
if (not IsInt(t1) or not IsInt(t2)):
return True
## print 'Not float', t1, t2
return False
def CanBeInt(t1, t2):
if (t1 is None or IsInt(t1) or IsIntUndefSize(t1)) and (t2 is None or IsInt(t2) or IsIntUndefSize(t2)):
return True
return False
arifm = ('!PyNumber_Multiply', '!PyNumber_Divide', '!PyNumber_Add', '!PyNumber_Subtract')
def genHalfFloat(it1, o):
t1 = TypeExpr(it1)
if it1[0] == 'CONST' and type(it1[1]) is int:
return repr(float(it1[1]))
if it1[0] == 'CONST' and type(it1[1]) is float:
return repr(it1[1])
if IsFloat(t1) and IsCVar(it1):
return CVarName(it1)
if IsInt(t1) and IsCVar(it1):
return '((double)' + CVarName(it1) + ')'
elif it1[0] in arifm and IsFloat(t1):
return GenFloatExpr(it1, o)
elif it1[0] == '!PyObject_Call' and it1[1][0] == 'CALC_CONST':
t = it1[1][1]
if type(t) is tuple and len(t) == 2:
t = (Val3(t[0], 'ImportedM'), t[1])
if t in CFuncFloatOfFloat:
if it1[2][0] == 'CONST':
s0 = repr(float(it1[2][1][0]))
else:
s0 = genHalfFloat(it1[2][1][0], o)
s1 = New('double')
o.Raw(s1, ' = ', CFuncFloatOfFloat[t], ' ( ', s0, ' );')
Cls1(o, s0)
return s1
t = Val3(t, 'ImportedM')
if t in CFuncFloatOfFloat:
if it1[2][0] == 'CONST':
s0 = repr(float(it1[2][1][0]))
else:
s0 = genHalfFloat(it1[2][1][0], o)
s1 = New('double')
o.Raw(s1, ' = ', CFuncFloatOfFloat[t], ' ( ', s0, ' );')
Cls1(o, s0)
return s1
ref1 = Expr1(it1, o)
if IsFloat(t1):
s1 = New('double')
o.Stmt(s1, '=', 'PyFloat_AsDouble', ref1)
Cls1(o, ref1)
return s1
if IsInt(t1):
s1 = New('double')
o.Raw(s1, ' = (double)PyInt_AsLong ( ', ref1, ' );')
Cls1(o, ref1)
return s1
ref2 = New()
o.Stmt(ref2, '=', 'PyNumber_Float', ref1)
Cls1(o, ref1)
s1 = New('double')
o.Stmt(s1, '=', 'PyFloat_AsDouble', ref2)
Cls1(o, ref2)
return s1
def GenFloatExpr(it, o):
arifm = {'!PyNumber_Multiply':0, '!PyNumber_Divide':1, '!PyNumber_Add':2, '!PyNumber_Subtract':3}
if it[0] in arifm and IsFloat(TypeExpr(it)):
op4 = ('*', '/', '+', '-')
op = op4[arifm[it[0]]]
s1 = genHalfFloat(it[1], o)
s2 = genHalfFloat(it[2], o)
new = New('double')
o.Raw(new, ' = ', s1, ' ', op, ' ', s2, ';')
o.Cls(s1, s2)
return new
Fatal('', it)
def not_float_op(ref1,ref2):
l1 = isconstref(ref1)
l2 = isconstref(ref2)
l1_0 = True
l2_0 = True
if l1:
l1_0 = type(ref1[1]) is float
if l2:
l2_0 = type(ref2[1]) is float
if not l1_0 or not l2_0:
return True
return False
def not_int_op(ref1,ref2, e1,e2):
l1 = isconstref(ref1)
l2 = isconstref(ref2)
l1_0 = True
l2_0 = True
if l1:
l1_0 = type(ref1[1]) is int
if l2:
l2_0 = type(ref2[1]) is int
if not IsNoneOrInt(TypeExpr(e1)):
return True
if not IsNoneOrInt(TypeExpr(e2)):
return True
if not l1_0 or not l2_0:
return True
return False
def bin_arg_float(o, ref1, ref2, first, t1 = None, t2 = None):
l1 = isconstref(ref1)
l2 = isconstref(ref2)
if l1:
l1_0 = type(ref1[1]) is float
if l2:
l2_0 = type(ref2[1]) is float
if not first:
pre = '} else '
else:
pre = ''
if not l1 and not l2:
if IsInt(t1) and IsInt(t2):
o.append(pre + 'if (0) {')
elif not IsInt(t1) and IsInt(t2):
o.Stmt(pre + 'if (PyFloat_CheckExact(', ref1, ')) {')
elif not IsInt(t2) and IsInt(t2):
o.Stmt(pre + 'if (PyFloat_CheckExact(', ref2, ')) {')
else:
o.Stmt(pre + 'if (PyFloat_CheckExact(', ref1, ') && PyFloat_CheckExact(', ref2, ')) {')
elif l1 and l2:
if l1_0 and l2_0:
o.append(pre + 'if (1) {')
else:
o.append(pre + 'if (0) {')
elif l1:
if l1_0:
o.Stmt(pre + 'if (PyFloat_CheckExact(', ref2, ')) {')
else:
o.append(pre + 'if (0) {')
elif l2:
if l2_0:
o.Stmt(pre + 'if (PyFloat_CheckExact(', ref1, ')) {')
else:
o.append(pre + 'if (0) {')
else:
Fatal('bin_arg_float', ref1, ref2, first)
return None
type_recode = {'int': 'PyInt_Type','long':'PyLong_Type',\
'float':'PyFloat_Type', 'bool':'PyBool_Type',\
'object':'PyBaseObject_Type', 'unicode':'PyUnicode_Type',\
'complex':'PyComplex_Type'}
def calc_range_1(tupl):
try:
l = range(*tupl[1])
if len(l) < 16:
ll = [('CONST', x) for x in l]
return ('!BUILD_LIST', tuple(ll))
except:
pass
return None
def attempt_direct_builtin(nm_builtin, args, tupl):
if nm_builtin == 'range' and tupl[0] == 'CONST':
l = calc_range_1(tupl)
if l is not None:
return l
if nm_builtin == 'chr' and len(args) == 1:
return ('!CHR_BUILTIN', args[0])
if nm_builtin == 'ord' and len(args) == 1:
return ('!ORD_BUILTIN', args[0], tupl)
if nm_builtin in type_recode:
if nm_builtin == 'int' and len(args) == 1:
return ('!PyNumber_Int', args[0])
if nm_builtin == 'long' and len(args) == 1:
return ('!PyNumber_Long', args[0])
if nm_builtin == 'float' and len(args) == 1:
return ('!PyNumber_Float', args[0])
typ = type_recode[nm_builtin]
return ('!' + typ + '.tp_new', '&' + typ, tupl, 'NULL')
if nm_builtin == 'dir' and len(args) == 1:
return ('!PyObject_Dir', args[0])
if nm_builtin == 'bin' and len(args) == 1:
return ('!PyNumber_ToBase', args[0], 2)
if nm_builtin == 'id' and len(args) == 1:
return ('!PyLong_FromVoidPtr', args[0])
if nm_builtin == 'set' and len(args) == 0:
return ('!PySet_New', 'NULL')
if nm_builtin == 'set' and len(args) == 1:
return ('!PySet_New', args[0])
if nm_builtin == 'len' and len(args) == 1:
t = TypeExpr(args[0])
if IsList(t):
return ('!PY_SSIZE_T', ('!PyList_GET_SIZE', args[0]))
if IsTuple(t):
return ('!PY_SSIZE_T', ('!PyTuple_GET_SIZE', args[0]))
if IsDict(t):
return ('!PY_SSIZE_T', ('!PyDict_Size', args[0]))
if t == Kl_Set:
return ('!PY_SSIZE_T', ('!PySet_Size', args[0]))
if IsStr(t):
return ('!PY_SSIZE_T', ('!PyString_GET_SIZE', args[0]))
return ('!PY_SSIZE_T', ('!PyObject_Size', args[0]))
if nm_builtin == 'repr' and len(args) == 1:
return ('!PyObject_Repr', args[0])
if nm_builtin == 'str' and len(args) == 1: # test_compile not pass
if IsInt(TypeExpr(args[0])):
return ('!PyInt_Type.tp_str', args[0])
return ('!PyObject_Str', args[0])
if nm_builtin == 'bytes' and len(args) == 1:
return ('!PyObject_Str', args[0])
if nm_builtin == 'unicode' and len(args) == 1:
return ('!PyObject_Unicode', args[0])
if nm_builtin == 'type' and len(args) == 1:
return ('!PyObject_Type', args[0])
if nm_builtin == 'dir' and len(args) == 1:
return ('!PyObject_Dir', args[0])
if nm_builtin == 'iter' and len(args) == 1:
return ('!PyObject_GetIter', args[0])
### !!!!!! replace to direct call !!!!!!
if nm_builtin == 'hash' and len(args) == 1:
return ('!PyObject_Hash', args[0])
if nm_builtin == 'cmp' and len(args) == 2:
return ('!_PyObject_Cmp', args[0], args[1])
if nm_builtin == 'unicode' and len(args) == 1:
return ('!PyObject_Unicode', args[0])
if nm_builtin == 'abs' and len(args) == 1:
return ('!PyNumber_Absolute', args[0])
if nm_builtin == 'format' and len(args) == 1:
return ('!PyObject_Format', args[0], 'NULL')
if nm_builtin == 'format' and len(args) == 2:
return ('!PyObject_Format', args[0], args[1])
if nm_builtin == 'tuple' and len(args) == 1:
if IsList(TypeExpr(args[0])):
if args[0][0] == '!BUILD_LIST':
return TupleFromArgs(args[0][1])
return ('!PyList_AsTuple', args[0])
return ('!PySequence_Tuple', args[0])
if nm_builtin == 'list' and len(args) == 1:
return ('!PySequence_List', args[0])
if nm_builtin == 'pow' and len(args) == 2:
return ('!PyNumber_Power', args[0], args[1], 'Py_None')
if nm_builtin == 'pow' and len(args) == 3:
return ('!PyNumber_Power', args[0], args[1], args[2])
if nm_builtin == 'hasattr' and len(args) == 2:
return ('!BOOLEAN',('!PyObject_HasAttr', args[0], args[1]))
if nm_builtin == 'isinstance' and len(args) == 2:
return ('!BOOLEAN',('!PyObject_IsInstance', args[0], args[1]))
if nm_builtin == 'issubclass' and len(args) == 2:
return ('!BOOLEAN',('!PyObject_IsSubclass', args[0], args[1]))
if nm_builtin == 'getattr' and len(args) == 2:
return ('!PyObject_GetAttr', args[0], args[1])
return None
def generate_and_or_jumped_stacked(it, o, prevref, is_and, n):
## leno = len(o)
ref1 = GenExpr(it[0], o, prevref)
assert istempref(prevref)
if prevref != ref1:
if n == 0:
if istempref(ref1):
Fatal('and_or_jumped_stacked', it)
else:
o.CLEAR(prevref)
o.Raw(prevref, ' = ', ref1, ';')
if istempref(ref1):
assert n != 0
o.Raw(ref1, ' = NULL;')
else:
o.INCREF(prevref)
if len(it) == 1:
return ref1
assert is_and in (True, False)
or_and = New('int')
_prevlast1_1 = ConC('if ((', prevref, ' = PyBool_FromLong (')
_prevlast2_1 = ')) == 0) goto label_0;'
if len(o) >= 1 and \
o[-1].startswith(_prevlast1_1) and o[-1].endswith(_prevlast2_1):
intlast = o[-1][len(_prevlast1_1):-len(_prevlast2_1)]
if is_and:
o.Raw(or_and, ' = ', intlast, ';')
else:
o.Raw(or_and, ' = !', intlast, ';')
else:
if is_and:
o.Stmt(or_and, '=', 'PyObject_IsTrue', prevref)
else:
o.Stmt(or_and, '=', 'PyObject_Not', prevref)
o.Stmt('if (', or_and, ') {')
o.CLEAR(prevref)
generate_and_or_jumped_stacked(it[1:], o, prevref, is_and, n + 1)
o.append('}')
Cls1(o, or_and)
## pprint((o[leno:], it, prevref, is_and, n))
return prevref
def tag_in_expr(tag, expr):
if type(expr) is tuple and len(expr) > 0 and type(expr[0]) is str:
if expr[0] == tag:
return True
if expr[0] == 'CONST':
return False
for r in expr:
if tag_in_expr(tag, r):
return True
return False
if type(expr) is list:
for r in expr:
if tag_in_expr(tag, r):
return True
return False
if type(expr) is tuple:
for r in expr:
if tag_in_expr(tag, r):
return True
return False
return False
def New(type=None, forcenewg=None):
if forcenewg is not None:
return forcenewg
if type is None:
return newgen(forcenewg)
else:
return new_typed(type, forcenewg)
traced_tempgen=[]
def newgen(forcenewg=None):
global tempgen, traced_tempgen
if forcenewg is not None:
assert not tempgen[forcenewg[1]]
return forcenewg
n = None
for i, f in enumerate(tempgen):
if f:
tempgen[i] = not f
n = ('PY_TEMP',i)
break
if n is None:
tempgen.append(False)
n = ('PY_TEMP',len(tempgen)-1)
if len(traced_tempgen) > 0:
dict_tempgen = traced_tempgen[-1]
dict_tempgen[n] = True
return n
def save_tempgen():
return tempgen[:]
def restore_tempgen(_tempgen):
tempgen[:] = _tempgen
def clearref(o,g, fictive=False):
global tempgen
global g_refs2
if g in g_refs2:
return
if type(g) is tuple and g[0] == 'PY_TEMP' and g[1] < len(tempgen) and g[1] >= 0 and \
not tempgen[g[1]]:
if fictive:
tempgen[g[1]] = True
return
tempgen[g[1]] = True
o.Stmt('CLEARREF', g)
def istempref(g):
global tempgen
if type(g) is tuple and len(g) == 2 and g[0] == 'PY_TEMP':
i = g[1]
if i >= 0 and i < len(tempgen):
return True
return False
def isconstref(ref):
return type(ref) is tuple and len(ref) > 1 and ref[0] == 'CONST'
def new_typed(type, forcenewg=None):
global typed_gen
if forcenewg is not None:
assert forcenewg[0] == 'TYPED_TEMP'
return forcenewg
for i, (f, t) in enumerate(typed_gen):
if f and t == type:
typed_gen[i] = (not f, t)
return ('TYPED_TEMP', i)
typed_gen.append((False, type))
return ('TYPED_TEMP', len(typed_gen)-1)
def clear_typed(g):
global typed_gen
if type(g) is tuple and g[0] == 'TYPED_TEMP' and g[1] < len(typed_gen) and g[1] >= 0 and \
not typed_gen[g[1]][0]:
typed_gen[g[1]] = (True, typed_gen[g[1]][1])
def is_not_active_typed(s):
global typed_gen
for i, v in enumerate(typed_gen):
if v[0] and s == (v[1] + '_' + str(i).strip()):
return True
return False
def reactivate_typed(s):
global typed_gen
for i, v in enumerate(typed_gen):
if v[0] and s == (v[1] + '_' + str(i).strip()):
typed_gen[i] = (False, v[1])
return ('TYPED_TEMP', i)
assert False
def istemptyped(g):
global typed_gen
if type(g) is tuple and len(g) == 2 and g[0] == 'TYPED_TEMP':
i = g[1]
if type(i) is int and i >= 0 and i < len(typed_gen):
return True
return False
def IsCalcConst(g):
return g[0] == 'CALC_CONST'
def CVar(g):
global typed_gen
if type(g) is tuple:
len_g = len(g)
if len_g == 2 and g[0] == '&' and istempref(g[1]):
return '(temp + ' + str(g[1][1]) + ')'
if len_g == 2 and g[0] == '&' and istemptyped(g[1]):
return '&' + CVar(g[1])
if istempref(g):
return 'temp[' + str(g[1]) + ']'
if istemptyped(g):
return typed_gen[g[1]][1] + '_' + str(g[1])
if g[0] == 'CALC_CONST':
return 'calculated_const[' + str(calculated_const[g[1]]) + ']' #calc_const_to(g[1])
if g[0] == 'CONST':
return const_to(g[1])
if g[0] == 'BUILTIN':
return load_builtin(g[1])
if g[0] == 'CODEFUNC':
return '(PyObject *)code_' + g[1]
if g[0] == 'TYPE_CONVERSION':
return g[1] + ' ' + CVar(g[2])
if len(g) == 1:
return g[0]
if g[0] == 'FAST':
assert not current_co.IsCVar(g)
return 'GETLOCAL(' + nmvar_to_loc(g[1]) + ')'
## if g[0] == '2FAST':
## assert g[1][0] == 'N' and g[1][1:].isdigit()
## return CVar_get_2FAST(g[1]) #'GETLOCAL(' + nmvar_to_loc(g[1]) + ')'
if g[0] == '!LOAD_GLOBAL' and build_executable and g[1] not in d_built and\
g[1][0] != '_' and not redefined_all and not global_used_at_generator(g[1]):
add_fast_glob(g[1])
return 'GETSTATIC(' + g[1] + ')'
if g[0] == 'LOAD_CLOSURE':
return 'GETFREEVAR(' + g[1] + ')'
if type(g) is int:
return str(g)
if type(g) is float:
return str(g)
if g is None:
return 'Py_None'
return g
dict_global_used_at_generator = {}
def global_used_at_generator(nm):
if nm in dict_global_used_at_generator:
return bool(dict_global_used_at_generator[nm])
load_ = ('!LOAD_GLOBAL', nm)
stor_ = ('STORE_GLOBAL', nm)
dele_ = ('DELETE_GLOBAL', nm)
load = repr(load_)
stor = repr(stor_)
dele = repr(dele_)
for co in all_co.itervalues():
if not co.can_be_codefunc():
scmds = repr(co.cmds[1])
if load in scmds or stor in scmds or dele in scmds:
dict_global_used_at_generator[nm] = True
return True
dict_global_used_at_generator[nm] = False
return False
def load_builtin(c):
global loaded_builtin
assert c in d_built
if c in loaded_builtin:
return 'loaded_builtin[' + str(loaded_builtin.index(c)) + ']'
loaded_builtin.append(c)
return 'loaded_builtin[' + str(loaded_builtin.index(c)) + ']'
def generate_builtin(first2, first3):
if len(loaded_builtin) == 0:
return
first2.print_to('static PyObject * loaded_builtin[' + str(len(loaded_builtin)) + '];')
first3.print_to('static void load_builtin(void){')
for i, c in enumerate(loaded_builtin):
first3.print_to(ConC('loaded_builtin[',i,'] = PyDict_GetItemString(bdict, "' + str(c) + '");' ))
first3.print_to(('if (loaded_builtin[' + str(i) + '] == 0) {printf("no builtin %s\\n");}') %c)
first3.print_to('}')
def generate_calculated_consts(first2):
if len(calculated_const) > 0:
first2.print_to('static PyObject * calculated_const[' + str(len(calculated_const)) + '];')
def expand_const():
const_to(filename)
for k in _n2c.keys():
const_to(k)
i = 0
while i < len(consts):
assert type(i) is int
c,type_c = consts[i]
if type(c) is tuple:
[const_to(x) for x in c]
elif type(c) is code_extended:
if not c.can_be_codefunc() or full_pycode:
const_to(c.co_code)
const_to(c.co_consts)
const_to(c.co_lnotab)
else:
const_to("\x00")
const_to(c.co_consts[:1])
const_to(c.co_name)
const_to(c.co_names)
const_to(tuple(c.co_varnames))
const_to(c.co_freevars)
const_to(c.co_cellvars)
i += 1
def generate_consts(first2, first3):
const_to(())
expand_const()
for i, (c,type_c) in enumerate(consts):
if type(c) is str:
create_chars_const(first2, i, c)
if type(c) is long:
if c <= 30000 and c >= -30000:
pass
elif c > 0:
c = str(c)
create_chars_const(first2, i, c)
else:
c = str(-c)
create_chars_const(first2, i, c)
if type(c) is unicode:
s = ''
for j,code in enumerate(c):
s += str(ord(code))
if j < len(c)-1:
s += ','
lenc = len(c)
if lenc == 0:
lenc = 1
s = '0'
first3.print_to('static wchar_t const_unicode_' + str(i) + \
'[' + str(lenc) + '] = {' + s + '};')
first2.print_to('static PyObject * consts[' + str(len(consts)) + '];')
first3.print_to('static void init_consts(void){')
change_ob = False
for i, (c,type_c) in enumerate(consts):
if type(c) is tuple:
codes = [(j,c1) for j,c1 in enumerate(c) if type(c1) is code_extended]
for j, c1 in codes:
change_ob = True
if change_ob:
first3.print_to('int __ob;')
for i, (c,type_c) in enumerate(consts):
if type(c) is code_extended or type(c) is types.CodeType:
first3.print_to('consts[' + str(i) + '] = Py_None;')
elif type(c) is bool :
if c:
first3.print_to('consts[' + str(i) + '] = Py_True;')
else:
first3.print_to('consts[' + str(i) + '] = Py_False;')
first3.print_to('Py_INCREF(consts[' + str(i) + ']);')
elif type(c) is long:
if c <= 30000 and c >= -30000:
first3.print_to('consts[' + str(i) + '] = PyLong_FromLong(' + str(c) + ');')
elif (c >> 31) <= 1 and (c >> 31) >= 0:
first3.print_to('consts[' + str(i) + '] = PyLong_FromLong(' + str(c) + 'l);')
elif c > 0:
if need_str_name(i, c):
first3.print_to('consts[' + str(i) + '] = PyLong_FromString(const_string_' + str(i) + ',NULL,10);')
else:
first3.print_to('consts[' + str(i) + '] = PyLong_FromString(' + generate_chars_literal(c) + ',NULL,10);')
else:
if need_str_name(i, -c):
first3.print_to('consts[' + str(i) + '] = PyNumber_Negative(PyLong_FromString(const_string_' + str(i) + ',NULL,10));')
else:
first3.print_to('consts[' + str(i) + '] = PyNumber_Negative(PyLong_FromString(' + generate_chars_literal(-c) + ',NULL,10));')
elif type(c) is int:
first3.print_to('consts[' + str(i) + '] = PyInt_FromLong (' + str(c) + 'L);')
elif type(c) is float:
if hasattr(math, 'isnan') and math.isnan(c):
if not '-' in str(c):
first3.print_to('consts[' + str(i) + '] = PyFloat_FromDouble(Py_NAN);')
else:
first3.print_to('consts[' + str(i) + '] = PyFloat_FromDouble(-Py_NAN);')
elif hasattr(math, 'isinf') and math.isinf(c):
if not '-' in str(c):
first3.print_to('consts[' + str(i) + '] = PyFloat_FromDouble(Py_HUGE_VAL);')
else:
first3.print_to('consts[' + str(i) + '] = PyFloat_FromDouble(-Py_HUGE_VAL);')
else:
first3.print_to('consts[' + str(i) + '] = PyFloat_FromDouble(' + repr(c) + ');')
elif type(c) is complex:
first3.print_to('consts[' + str(i) + '] = PyComplex_FromDoubles(' + str(c.real) + ', ' + str(c.imag) + ');')
elif type(c) is str: # and '"' not in c and '\n' not in c:
if need_str_name(i, c):
first3.print_to('consts[' + str(i) + '] = PyString_FromStringAndSize(const_string_' + str(i) + ', '+str(len(c))+');')
else:
first3.print_to('consts[' + str(i) + '] = PyString_FromStringAndSize(' + generate_chars_literal(c) + ', '+str(len(c))+');')
elif type(c) is unicode: # and '"' not in c and '\n' not in c:
first3.print_to('consts[' + str(i) + '] = PyUnicode_FromWideChar(const_unicode_' + str(i) + ', '+str(len(c))+');')
elif type(c) is types.EllipsisType:
first3.print_to('consts[' + str(i) + '] = &_Py_EllipsisObject;')
first3.print_to('Py_INCREF(consts[' + str(i) + ']);')
elif type(c) is tuple:
li = [const_to(x) for x in c]
if len (li) == 0:
first3.print_to('consts[' + str(i) + '] = PyTuple_Pack(0);')
first3.print_to('empty_tuple = consts[' + str(i) + '];')
else:
s = 'consts[' + str(i) + '] = PyTuple_Pack(' + str(len(li)) + ''.join([', ' + str(x) for x in li]) + ');'
## for j,it in enumerate(li):
## s += str(it)
## if j < len(li) - 1:
## s += ', '
## s += ');'
first3.print_to(s)
elif c in d_built_inv:
nm = d_built_inv[c]
first3.print_to('consts[' + str(i) + '] = ' + load_builtin(nm) + ';')
first3.print_to('Py_INCREF(consts[' + str(i) + ']);')
else:
Fatal('', type(c), c)
for i, (c,type_c) in enumerate(consts):
if type(c) is code_extended or type(c) is types.CodeType:
if type(c) is types.CodeType:
c = all_co[c]
nm = c.c_name
co = c
if nm == '':
Fatal('', c)
if not co.can_be_codefunc() or (hasattr(co, 'no_codefunc') and co.no_codefunc) or co.can_be_cfunc(): ##co.co_flags & CO_GENERATOR:
first3.print_to('consts[' + str(i) + '] = (PyObject *)PyCode_New(' +\
str(co.co_argcount) +', ' +\
str(co.co_nlocals) +', ' +\
str(co.co_stacksize) +', ' +\
str(co.co_flags) +', ' +\
const_to(co.co_code) +', ' +\
const_to(co.co_consts) +', ' +\
const_to(co.co_names) +', ' +\
const_to(tuple(co.co_varnames)) +', ' +\
const_to(co.co_freevars) +', ' +\
const_to(co.co_cellvars) +', ' +\
const_to(filename) +', ' +\
const_to(co.co_name) +', ' +\
str(co.co_firstlineno) +', ' +\
const_to(co.co_lnotab) +');')
elif full_pycode:
first3.print_to('consts[' + str(i) + '] = (PyObject *)Py2CCode_New(' +\
str(co.co_argcount) +', ' +\
str(co.co_nlocals) +', ' +\
str(max(co.co_stacksize, co.new_stacksize)) +', ' +\
str(co.co_flags) +', ' +\
const_to(co.co_code) +', ' +\
const_to(co.co_consts) +', ' +\
const_to(co.co_names) +', ' +\
const_to(tuple(co.co_varnames)) +', ' +\
const_to(co.co_freevars) +', ' +\
const_to(co.co_cellvars) +', ' +\
const_to(filename) +', ' +\
const_to(c.co_name) +', ' +\
str(co.co_firstlineno) +', ' +\
const_to(co.co_lnotab) +', codefunc_' + nm +');')
else:
first3.print_to('consts[' + str(i) + '] = (PyObject *)Py2CCode_New(' +\
str(co.co_argcount) +', ' +\
str(co.co_nlocals) +', ' +\
str(max(co.co_stacksize,co.new_stacksize)) +', ' +\
str(co.co_flags) +', ' +\
const_to("\x00") +', ' +\
const_to(co.co_consts[:1]) +', ' +\
const_to(co.co_names) +', ' +\
const_to(tuple(co.co_varnames)) +', ' +\
const_to(co.co_freevars) +', ' +\
const_to(co.co_cellvars) +', ' +\
const_to(filename) +', ' +\
const_to(c.co_name) +', ' +\
str(co.co_firstlineno) +', ' +\
const_to("\x00") +', codefunc_' + nm +');')
## first3.print_to('assert (' + const_to(co.co_names) + ' != NULL);')
## first3.print_to('assert (' + const_to(tuple(co.co_varnames)) + ' != NULL);')
## first3.print_to('assert (' + const_to(co.co_freevars) + ' != NULL);')
## first3.print_to('assert (' + const_to(co.co_cellvars) + ' != NULL);')
## first3.print_to('assert (' + const_to(filename) + ' != NULL);')
## first3.print_to('assert (' + const_to(co.co_name) + ' != NULL);')
for i, (c,type_c) in enumerate(consts):
if type(c) is tuple:
codes = [(j,c1) for j,c1 in enumerate(c) if type(c1) is code_extended]
for j, c1 in codes:
s1 = const_to(c1)
s_inc = 'Py_INCREF(' + s1 + ');'
s2 = const_to(c)
s_set = 'PyTuple_SetItem(' + s2 + ', ' + str(j) + ', ' + s1 + ');'
first3.print_to(s_inc)
first3.print_to('__ob = (' +s2 +')->ob_refcnt;')
first3.print_to('(' +s2 +')->ob_refcnt = 1;')
first3.print_to(s_set)
first3.print_to('(' +s2 +')->ob_refcnt = __ob;')
first3.print_to('}')
visibl = set('-=+_~!@#$%^&*()[]{};:/?.>,< ')
def is_c(c):
for _c in c:
if _c.isalnum() or _c in visibl:
pass
else:
return False
return True
def is_c_2(c):
for _c in c:
if _c.isalnum() or _c in visibl or _c in '\n\r\t':
pass
else:
return False
return True
def str_to_c_2(s):
s2 = ''
for c in s:
if c.isalnum() or c in visibl:
s2 += c
elif c == '\n':
s2 += '\\n'
elif c == '\r':
s2 += '\\r'
elif c == '\t':
s2 += '\\t'
else:
assert False
return s2
def generate_chars_literal(c):
## s = ''
## for j,code in enumerate(c):
## s += str(ord(code))
## if j < len(c)-1:
## s += ','
if type(c) is int:
return '"' + str(c) + '"'
if type(c) is long:
return '"' + str(c) + 'l"'
if is_c(c):
return '"' + c + '"'
elif is_c_2(c):
return '"' + str_to_c_2(c) + '"'
else:
return Str_for_C(c)
def need_str_name(i, c):
if i in predeclared_chars:
return True
if type(c) is int or type(c) is long:
return False
if is_c(c) or is_c_2(c):
return False
return True
def create_chars_const(first2, i, c):
if is_c(c):
if i in predeclared_chars:
first2.print_to('static char const_string_' + str(i) + \
'[' + str(len(c)+1) + '] = "' + c + '";')
elif is_c_2(c):
if i in predeclared_chars:
first2.print_to('static char const_string_' + str(i) + \
'[' + str(len(c)+1) + '] = "' + str_to_c_2(c) + '";')
else:
s = ''
for j,code in enumerate(c):
s += str(ord(code))
if j < len(c)-1:
s += ','
first2.print_to('static char const_string_' + str(i) + \
'[' + str(len(c)) + '] = {' + s + '};')
def print_to(c_f,v):
print >> c_f, v
def index_const_to(c):
global consts
global consts_dict
const_to(c)
c_ = c,const_type(c)
if c_ in consts_dict:
i = consts_dict[c_]
return i
Fatal('',c)
return -1
def const_to(c):
global consts
global consts_dict
if type(c) is code_extended:
## if c.c_name == 'isreadable':
## Fatal('isreadable', c)
return const_to(c.co_original)
if type(c) is tuple and len(c) > 0 and type(c[0]) is tuple and len(c[0]) > 0 and c[0][0] == '!':
Fatal('', c)
if c is None:
return 'Py_None'
c_ = c,const_type(c)
if c_ in consts_dict:
i = consts_dict[c_]
return 'consts[' + str(i) + ']'
if type(c) is tuple:
[const_to(x) for x in c]
if type(c_[0]) is float:
for i, (cc, cc_typ) in enumerate(consts):
if type(cc) is float and hasattr(math, 'isinf') and math.isinf(cc) and math.isinf(c_[0]) and str(cc) == str(c_[0]):
return 'consts[' + str(i) + ']'
if type(cc) is float and hasattr(math, 'isnan') and math.isnan(cc) and math.isnan(c_[0]) and str(cc) == str(c_[0]):
return 'consts[' + str(i) + ']'
consts.append(c_)
consts_dict[c_] = len(consts) - 1
return 'consts[' + str(len(consts)-1) + ']'
def const_type(c):
if type(c) is tuple:
return tuple([const_type(x) for x in c])
if type(c) in (float, complex):
return type(c) , repr(c)
return type(c)
def pregenerate_code_objects():
for co in _n2c.values():
if not co.can_be_codefunc() or full_pycode: ##co.co_flags & CO_GENERATOR:
const_to(co.co_code)
const_to(co.co_consts)
const_to(co.co_lnotab)
else:
const_to(co.co_consts[:1])
const_to(co.co_name)
const_to(co.co_names)
const_to(tuple(co.co_varnames))
const_to(co.co_freevars)
const_to(co.co_cellvars)
const_to(co)
def calc_const_to(k):
global calculated_const
if k in calculated_const:
return ('CALC_CONST', k)
calculated_const[k] = len(calculated_const)
return ('CALC_CONST', k)
if __name__ == "__main__":
## import profile
## profile.runctx('main()', globals(), locals())
main ()
| Python |
import t_const
FPS= t_const.FPS_SERVER
| Python |
#! /usr/bin/env python
#coding=utf-8
#游戏地图事件
data = {
#类型 警告
"warn01":{
"type":"Warning",
"pos":(915,3380), # 坐标
"size":(100), # 范围
"zbpos":(915,2900), #出现僵尸
"zbsize":(800,400), #随机范围
"time":5000, # 持续时间
"zbshow":30, # 僵尸出现机率
},
}
def get_data(id):
return data.get(id)
| Python |
#! /usr/bin/env python
#coding=utf-8
import base_object
import math
import t_const,t_cmd
import random,copy
class CEvent(object):
def __init__(self):
self.time = 0
self.event = None
pass
class CMapEvent(base_object.CObject):
def __init__(self, mapmgr):
self.sizelist = {}
self.timelist = {}
# 触发事件列表
self.on_eventlist = {}
self.entsum = 0
self.mapmgr = mapmgr
pass
def destroy(self):
pass
# 加载相应地图的事件列表
def loadmapevent(self, map_name, dicPlayersuid):
self.dicPlayersuid = dicPlayersuid
self.eventlist = {}
self.entsum = 0
maps = __import__("tgame_map_%s_event"%map_name)
for eventname in maps.data:
self.addevent(maps.data[eventname], eventname)
pass
def addevent(self, event, eventname):
ent = CEvent()
if event["type"] == "Warning":
ent.event = event
self.sizelist[eventname] = ent
self.entsum += 1
pass
# 更新当前已经触发的事件
def event_update(self):
copy_array = copy.copy(self.on_eventlist)
for entn in copy_array:
event = copy_array[entn]
if event.event["type"] == "Warning":
# 出现僵尸
# 得到出现位置
pos = event.event["zbpos"]
# 出现范围
size = event.event["zbsize"]
# 根据范围生成随机坐标
x = random.randint(size[0]/2-size[0], size[0]/2)
y = random.randint(size[1]/2-size[1], size[1]/2)
pos = (pos[0] + x,pos[1] + y)
param = (pos[0], pos[1])
# 向所有玩家广播,param位置出现僵尸
self.send_event( t_cmd.S_GAME_BULZB, param)
#每帧增加相应的时间 毫秒
event.time += 1000 / t_const.FPS_SERVER
#如果到达时间 则事件停止 释放
if event.time >= event.event["time"]:
del self.on_eventlist[entn]
print "event ovent!!!!!!!!!!!!!!!!!"
pass
def update(self):
copy_array = copy.copy(self.sizelist)
for entn in copy_array:
ent = copy_array[entn]
if not ent:
continue
# 判断所有玩家坐标是否达到事件点范围
for uid in self.dicPlayersuid:
pos = self.dicPlayersuid[uid].pos
x = math.fabs(ent.event["pos"][0]-pos[0])
y = math.fabs(ent.event["pos"][1]-pos[1])
length = math.sqrt(x*x + y*y)
if length <= ent.event["size"]:
# 通知所有玩家,事件被触发
param = (uid, entn)
self.send_event( t_cmd.S_GAME_EVENT, param)
# 删除事件
self.sizelist[entn] = None
del self.sizelist[entn]
# 添加事件至已触发事件中
self.on_eventlist[entn] = ent
self.event_update()
def send_event(self, event, param):
self.mapmgr.send_game_event( event, param) | Python |
#! /usr/bin/env python
#coding=utf-8
import base_object
import math
import t_const,t_cmd
import random,copy
class CEvent(object):
def __init__(self):
self.time = 0
self.event = None
pass
class CMapEvent(base_object.CObject):
def __init__(self, mapmgr):
self.sizelist = {}
self.timelist = {}
# 触发事件列表
self.on_eventlist = {}
self.entsum = 0
self.mapmgr = mapmgr
pass
def destroy(self):
pass
# 加载相应地图的事件列表
def loadmapevent(self, map_name, dicPlayersuid):
self.dicPlayersuid = dicPlayersuid
self.eventlist = {}
self.entsum = 0
maps = __import__("tgame_map_%s_event"%map_name)
for eventname in maps.data:
self.addevent(maps.data[eventname], eventname)
pass
def addevent(self, event, eventname):
ent = CEvent()
if event["type"] == "Warning":
ent.event = event
self.sizelist[eventname] = ent
self.entsum += 1
pass
# 更新当前已经触发的事件
def event_update(self):
copy_array = copy.copy(self.on_eventlist)
for entn in copy_array:
event = copy_array[entn]
if event.event["type"] == "Warning":
# 出现僵尸
# 得到出现位置
pos = event.event["zbpos"]
# 出现范围
size = event.event["zbsize"]
# 根据范围生成随机坐标
x = random.randint(size[0]/2-size[0], size[0]/2)
y = random.randint(size[1]/2-size[1], size[1]/2)
pos = (pos[0] + x,pos[1] + y)
param = (pos[0], pos[1])
# 向所有玩家广播,param位置出现僵尸
self.send_event( t_cmd.S_GAME_BULZB, param)
#每帧增加相应的时间 毫秒
event.time += 1000 / t_const.FPS_SERVER
#如果到达时间 则事件停止 释放
if event.time >= event.event["time"]:
del self.on_eventlist[entn]
print "event ovent!!!!!!!!!!!!!!!!!"
pass
def update(self):
copy_array = copy.copy(self.sizelist)
for entn in copy_array:
ent = copy_array[entn]
if not ent:
continue
# 判断所有玩家坐标是否达到事件点范围
for uid in self.dicPlayersuid:
pos = self.dicPlayersuid[uid].pos
x = math.fabs(ent.event["pos"][0]-pos[0])
y = math.fabs(ent.event["pos"][1]-pos[1])
length = math.sqrt(x*x + y*y)
if length <= ent.event["size"]:
# 通知所有玩家,事件被触发
param = (uid, entn)
self.send_event( t_cmd.S_GAME_EVENT, param)
# 删除事件
self.sizelist[entn] = None
del self.sizelist[entn]
# 添加事件至已触发事件中
self.on_eventlist[entn] = ent
self.event_update()
def send_event(self, event, param):
self.mapmgr.send_game_event( event, param) | Python |
#! /usr/bin/env python
#coding=utf-8
#游戏地图事件
data = {
#类型 警告
"warn01":{
"type":"Warning",
"pos":(915,3380), # 坐标
"size":(100), # 范围
"zbpos":(915,2900), #出现僵尸
"zbsize":(800,400), #随机范围
"time":5000, # 持续时间
"zbshow":30, # 僵尸出现机率
},
}
def get_data(id):
return data.get(id)
| Python |
# -*- coding: utf-8 -*-
import hall_callback
import t_const, t_error, t_cmd, tgame_wizard
#import tgame_struct
#import tgame_factroy_s
import game_player_s
#import tgame_sprite_config, tgame_stage_config
import tgame_room
import random, cPickle
import tgame_mapevent_s
#游戏逻辑类,单局游戏的全局数据保存在这里
class CMap(object):
#构造函数
def __init__(self, objRoom):
super(CMap, self).__init__()
self.objRoom = objRoom #房间对象的引用,消息发送和写日志用到
self.objMsgMgr = hall_callback.get_game_room_msgmgr() #传输对象的引用,消息打包的时候用到
self.register_recv() #注册游戏子事件的响应函数
self.reset() #初始化游戏内全局数据
#自我清理的函数,释放此对象前调用
def clean(self):
self.reset_map()
self.reset()
self.objRoom = None
self.objMsgMgr = None
#此函数注册游戏子事件的具体响应函数
def register_recv(self):
self.dicEventFunc = {}
self.dicEventFunc[t_cmd.C_TUREND] = self.on_turend
self.dicEventFunc[t_cmd.C_MOVE] = self.on_move
self.dicEventFunc[t_cmd.C_RUN] = self.on_run
self.dicEventFunc[t_cmd.C_ATK] = self.on_atk
self.dicEventFunc[t_cmd.C_PICKITEM] = self.on_pickitem
#此函数对游戏内全局数据进行初始化或重置
def reset(self):
self.iStatus = t_const.GAME_WAIT #游戏状态,初始化为准备(非进行游戏)
self.gametime = -1 # 游戏计时器
self.iStage = None #当前关卡,初始化为None
self.iCurFrame = 0 #当前帧数,初始化为0
self.objTimeLine = None #管理怪物和阳光刷新数据的对象,初始化为None
self.dicTrackSet = {} #当前关卡的地形数据的字典,key是轨道编号,value是一个代表地形的int,可能为草地、水域或屋顶
self.dicPlayers = {} #管理当前游戏内玩家对象的字典,key是玩家的side,value是游戏内玩家对象
self.dicPlayersuid = {}
#self.iCurFreeID = t_const.ID_START_SERVER #当前已经使用到的最大的精灵id
#self.dicUsedID = {} #管理当前存在的全部精灵id的字典,key是精灵的id,value是1
#self.dicTowerBase = {} #管理当前存在的全部基座(可种植植物的地点)的字典, key是基座的唯一id,value是基座对象
#self.dicTower = {} #管理当前存在的全部植物的字典,key是植物的唯一id,value是植物对象
#self.dicMonster = {} #管理当前存在的全部僵尸的字典,key是僵尸的唯一id,value是僵尸对象
#self.dicMissile = {} #管理当前存在的全部子弹的字典,key是子弹的唯一id,value是子弹对象
#self.dicItem = {} #管理当前存在的全部奖励物品(阳光,银币等)的字典,key是物品的唯一id,value是物品对象
self.iWinScore = 0 #本局的胜利得分
self.iLoseScore = 0 #本局的失败得分"""
#此函数释放和清理游戏内的全局数据,一般在游戏结束的时候调用
def reset_map(self):
self.gametime = None
#清空地形数据字典
#self.dicTrackSet.clear()
#清空玩家字典并释放其中的玩家对象
"""for player in self.dicPlayers.itervalues():
player.clean()
self.dicPlayers.clear()
#清空现存精灵id字典
self.dicUsedID.clear()
#清空基座字典并释放基座对象
for basis in self.dicTowerBase.itervalues():
basis.clean()
self.dicTowerBase.clear()
#清空植物字典并释放植物对象
for tower in self.dicTower.itervalues():
tower.clean()
self.dicTower.clear()
#清空僵尸字典并释放僵尸对象
for monster in self.dicMonster.itervalues():
monster.clean()
self.dicMonster.clear()
#清空子弹字典并释放子弹对象
for missile in self.dicMissile.itervalues():
missile.clean()
self.dicMissile.clear()
#清空物品字典并释放物品对象
for item in self.dicItem.itervalues():
item.clean()
self.dicItem.clear()"""
#此函数生成一个可用的精灵id,并维护精灵id字典,大致算法是对当前已经用到的精灵id进行递增,并加入已用精灵字典,然后返回id
def generate_id(self, iType):
pass
"""for i in xrange(t_const.ID_MAX_GENERATE):
self.iCurFreeID += 1
#精灵id具有区间限制,如果达到了区间的最大值,那么就从最小值开始重新递增,不过设计上单局游戏不应该达到区间最大值,所以同时还要加上特殊的日志,用于调整区间设置的依据
if self.iCurFreeID >= t_const.ID_END_SERVER:
self.iCurFreeID = t_const.ID_START_SERVER
self.objRoom.cglog(t_const.LOGTYPE_DESIGN, "[SPRITE_ID_EXCEED]:[frame=%d;stage=%d]" % (self.iCurFrame, self.iStage))
if self.dicUsedID.has_key(self.iCurFreeID):
continue
self.dicUsedID[self.iCurFreeID] = 1
return self.iCurFreeID
#如果超过最大循环次数依旧无法找到可用的精灵id,说明数值区间设计存在重大问题,必须立刻调整
self.objRoom.cglog(t_const.LOGTYPE_DESIGN, "[NO_AVAILABLE_ID]:[frame=%d;stage=%d]" % (self.iCurFrame, self.iStage))
return None"""
#此函数处理游戏开始的相关逻辑
def on_game_start(self, stage, lstPlayer):
#重置游戏内全局数据
self.reset()
#设置游戏状态为游戏中
self.iStatus = t_const.GAME_PLAYING
#保存当前关卡key
self.iStage = stage
#读取关卡配置
#config = td_stage_config.DATA.get(stage)
#初始化游戏内玩家对象
for room_player in lstPlayer:
objPlayer = game_player_s.CGameplayer(room_player)
objPlayer.init_game(0, "")
self.dicPlayers[objPlayer.iside] = objPlayer
self.dicPlayersuid[objPlayer.uid] = objPlayer
self.game_event = tgame_mapevent_s.CMapEvent(self)
# 加载地图事件
self.game_event.loadmapevent("open", self.dicPlayersuid)
#加载地图信息
#scene = config["scene"]
self.iWinScore = 10#config["win_score"]
self.iLoseScore = 0#config["lose_score"]
#加载地形信息,生成基座字典
#for y in xrange(len(scene)):
# landform = scene[y]
# if not self.dicTrackSet.has_key(landform):
# self.dicTrackSet[landform] = []
# self.dicTrackSet[landform].append(y)
# for x in xrange(td_const.MAP_GRID_WIDTH):
# iID = x + y * td_const.MAP_GRID_WIDTH
# self.dicTowerBase[iID] = td_struct.CTowerBase(iID, landform, x, y, None)
#生成怪物和阳光刷新数据对象
#self.objTimeLine = td_struct.CTimeLine(config)
#发送游戏开始消息
self.send_game_start(stage)
#此函数用于检测是否达到游戏胜利条件
def check_game_end(self, second):
#如果还有固定怪物未刷新,则不算胜利
"""if not self.objTimeLine.is_empty_force(second):
return False
#固定怪物都刷新了,那么消灭所有现存怪物后游戏胜利
if len(self.dicMonster) == 0:
return True
else:
return False"""
pass
#此函数检测游戏中有效(未退出或失败)的玩家是否为0,假如有效玩家为0则游戏强制结束
def check_empty_game(self):
"""total = len(self.dicPlayers)
leave = 0
for player in self.dicPlayers.itervalues():
if player.bIsLeave:
leave += 1
if total - leave <= 1:
return True
else:
return False"""
pass
#此函数用于处理游戏结束的相关逻辑
def game_end(self, win):
#根据玩家当局的具体表现对游戏进行结算,并生成游戏内玩家对象的临时列表
lstPlayer = []
for player in self.dicPlayers.itervalues():
player.on_game_end(win, self.iWinScore, self.iLoseScore)
lstPlayer.append(player)
#游戏状态切换到准备
self.iStatus = t_const.GAME_WAIT
#调用房间逻辑的on_game_end函数,处理需要保留的历史数据
"""self.objRoom.on_game_end(win, lstPlayer)
#重置游戏内全局数据
self.reset_map()"""
return lstPlayer
#此函数每个逻辑帧调用一次,处理时间驱动的逻辑
def logic_frame(self):
#当前帧数递增
self.iCurFrame += 1
#每秒一次发送游戏时间
if (self.iCurFrame % t_const.FPS_SERVER) == 0:
#second = self.iCurFrame / t_const.FPS_SERVER
#print self.iCurFrame
self.send_gametime()
# 事件
self.game_event.update()
pass
#此函数每秒调用一次,根据关卡配置刷新僵尸
def generate_monster(self, second):
#self.send_gametime()
#tgame_mapevent_s.inst.update()
pass
#此函数每秒调用一次,根据关卡配置生成阳光
def generate_sun(self, second):
#获取当前秒需要生成的阳光种类列表
"""lstSun = self.objTimeLine.get_sun(second)
if not lstSun:
return
iMaster = random.choice(self.dicPlayers.keys())
for iJob in lstSun:
iID = self.generate_id(t_const.OBJECT_ITEM)
if iID is None:
continue
sprite = self.new_sprite(iID, t_const.OBJECT_ITEM, iJob, iMaster)
if not sprite:
#无法生成阳光一般说明此阳光种类不存在
self.objRoom.cglog(t_const.LOGTYPE_CONFIG, "[FAIL_TO_CREATE_SPRITE][stage=%d;second=%d;iJob=%d]" % (self.iStage, second, iJob))
continue
sprite.set_mapmgr(self)
#向客户端广播有新阳光生成的消息
self.send_new_item(sprite.iID, sprite.iType, sprite.iJob, sprite.iMaster, -1, -1)"""
pass
#此函数在游戏中玩家离开房间时由房间逻辑调用,记录此玩家不再是“有效玩家”,并判断是否因为全部为无效玩家而结束游戏
def player_leave(self, iSide):
"""objPlayer = self.dicPlayers.get(iSide, None)
if objPlayer:
objPlayer.bIsLeave = True
if self.check_empty_game():
self.game_end(t_const.FACTION_NONE)"""
pass
#此函数在客户端发送游戏子事件时由房间逻辑调用,对子事件进行数据解包并根据子事件类型调用具体的子事件处理函数
def on_game_event(self, iSide, frame, event, data):
#print "server:on_game_event:",iSide,frame,event,data
if self.dicEventFunc.has_key(event):
param = [iSide, ]
param.extend(cPickle.loads(data))
apply(self.dicEventFunc[event], param)
pass
#-------------------------------------------------向客户端广播消息
def on_turend(self, obj, uid, rotate):
#print "send:on_turend",obj,names,rotate
param = (uid,rotate)
self.send_game_event(t_cmd.S_TUREND, param)
def on_move(self,obj, uid, ismove, dirx, diry, speed):
param = (uid, ismove, dirx, diry, speed)
self.send_game_event(t_cmd.S_MOVE, param)
def on_run(self, obj, uid, posx, posy):
param = (uid, posx, posy)
self.dicPlayersuid[uid].pos = (posx,posy)
#print "update%s pos"%uid
self.send_game_event(t_cmd.S_RUN, param)
def on_atk(self, obj, uid, pos, dir, weapon):
param = (uid, pos, dir, weapon)
self.send_game_event(t_cmd.S_ATK, param)
def on_pickitem(self, obj, uid, names):
param = (uid, names)
# 判断拾取
if self.dicPlayersuid[uid].pickItem(names):
self.send_game_event(t_cmd.S_PICKITEM, param)
# 游戏时间发送
def send_gametime(self):
self.gametime += 1
param = (self.gametime, 0)
#print "send_time:",self.gametime
#self.send_game_event(t_cmd.S_GAMETIME, param)
#----------------------------------------------------------------
#打包并发送游戏开始的消息,stage:当前关卡的id;player_list:此局游戏的玩家列表;每个玩家的信息包括:side:玩家标识;energy:起始阳光/能量数量;faxtion:阵营(植物方还是僵尸方);card_list:本局选择的可种植/创建的精灵种类列表
def send_game_start(self, iStage):
_list = []
for player in self.dicPlayers.itervalues():
tmp_list = []
#for iJob in player.lstCanBuild:
# int_obj = self.objMsgMgr.game_single_int(value=iJob)
# tmp_list.append(int_obj)
obj = self.objMsgMgr.game_player_start_info(side=player.iside,ifac=1, money=0, dicsprite=0)
_list.append(obj)
obj = self.objMsgMgr.game_s_game_start(stage=iStage, player_list=_list)
self.objRoom.send_all(obj)
#打包并发送游戏子事件的消息,frame:子事件发生的服务端时间帧;event_id:子事件类型;param:子事件具体参数(使用cPickle打包成一个字符串)
def send_game_event(self, event, param_list):
_str = cPickle.dumps(param_list)
obj = self.objMsgMgr.game_s_game_event(frame=self.iCurFrame, event_id=event, param=_str)
self.objRoom.send_all(obj)
# 除某人外的其它人
def send_game_event_other(self, event, param_list, uid):
_str = cPickle.dumps(param_list)
obj = self.objMsgMgr.game_s_game_event(frame=self.iCurFrame, event_id=event, param=_str)
self.objRoom.send_all(obj, self.dicPlayersuid[uid].hid)
def send_game_event_p(self, event, param_list, uid):
_str = cPickle.dumps(param_list)
obj = self.objMsgMgr.game_s_game_event(frame=self.iCurFrame, event_id=event, param=_str)
self.objRomm.send_to_user(self.dicPlayersuid[uid].hid, obj)
pass | Python |
#-- coding: utf-8 -*-
import t_const
"""巫师指令定义方面客户端和服务端公用,其他的函数为客户端专用"""
WIZARD_CHANGE_SUN = 0x01 #改变阳光数量
WIZARD_END_GAME = 0x02 #立刻结束游戏
WIZARD_ADD_ZOMBIE = 0x03 #立刻刷新僵尸
#帮助文字字典
HELP_TEXT = {WIZARD_CHANGE_SUN : "改变阳光数量指令//change_sun:参数1:整数(可正负,代表阳光数量的改变值),示例://change_sun 100", \
WIZARD_END_GAME : "立刻结束游戏指令//end_game:参数1:0或1(1代表胜利,0代表失败),示例://end_game 1", \
WIZARD_ADD_ZOMBIE : "增加n个僵尸//add_zombie: 参数1:正整数(代表僵尸数量);参数2:正整数(代表僵尸种类,-1代表随机),示例://add_zombie 10 -1", \
}
#对外输出文字,用于向聊天窗口输出帮助文字信息
def out_put(text):
import tgame_ui_wait
tgame_ui_wait.inst.add_notice(text)
#检测某个字符串是否符合某个巫师指令的格式,在发送聊天消息前调用, 用于过滤巫师指令
def check_wizard(text):
#如果空字符串或者为None,返回不是巫师指令
if not text:
return True
#以空格为分隔符进行字符串分解
line = text.split()
#假如是需要显示帮助的指令
if line[0] == "//help":
for text in HELP_TEXT.itervalues():
out_put(text)
return False
#检测是否是游戏中巫师指令
elif check_playing_wizard(line):
return False
#检测是否是准备状态巫师指令
elif check_waiting_wizard(line):
return False
# 输入完后焦点失效
import tgame_game
tgame_game.tgame_API.chat_set_focus(False)
return True
#检测是否是游戏内巫师指令
def check_playing_wizard(line):
import tgame_mapmgr, tgame_command
#如果游戏管理对象不存在,返回false
if not tgame_mapmgr.inst:
return False
#如果并不处于游戏中状态,返回false
if tgame_mapmgr.inst.iStatus != t_const.GAME_PLAYING:
return False
#需要改变阳光数量
if line[0] == "//change_sun":
try:
dEnergy = int(line[1])
except:
out_put(HELP_TEXT[WIZARD_CHANGE_SUN])
return False
tgame_command.inst.send_wizard(WIZARD_CHANGE_SUN, [dEnergy, ])
return True
#需要立刻结束游戏
elif line[0] == "//end_game":
try:
win = int(line[1])
except:
out_put(HELP_TEXT[WIZARD_END_GAME])
return False
tgame_command.inst.send_wizard(WIZARD_END_GAME, [win, ])
return True
#需要立刻刷新僵尸
elif line[0] == "//add_zombie":
try:
iNum = int(line[1])
except:
out_put(HELP_TEXT[WIZARD_ADD_ZOMBIE])
return False
if iNum <= 0:
out_put(HELP_TEXT[WIZARD_ADD_ZOMBIE])
return False
try:
iJob = int(line[2])
except:
iJob = -1
tgame_command.inst.send_wizard(WIZARD_ADD_ZOMBIE, [iNum, iJob])
return True
return False
#检测是否是准备状态巫师指令
def check_waiting_wizard(line):
import tgame_mapmgr, tgame_command
if not tgame_mapmgr.inst:
return False
if tgame_mapmgr.inst.iStatus != t_const.GAME_WAIT:
return False
return False
| Python |
# -*- coding: utf-8 -*-
"""以下是帧数相关配置"""
FPS = 30 #客户端逻辑帧数
FPS_SERVER = 5 #服务端逻辑帧数
FPS_RATE = FPS / FPS_SERVER #客户端服务端帧率比
"""以下是游戏模式相关配置"""
GAME_MODE_SINGLE = 0x01 #单人模式
"""以下是玩家个人数据相关的配置"""
#存关卡完成情况的buff的key
BUFF_COMPLETE = "buf0"
#所有用到的buff的列表
ALL_USED_BUFF = (BUFF_COMPLETE, )
#存关卡完成信息的打包格式
BUFF_COMPLETE_FORMAT_1 = 0x01
#现在使用的打包格式的字典
BUFF_FORMAT_ACTIVE = {
BUFF_COMPLETE : BUFF_COMPLETE_FORMAT_1
}
#存放各种不同打包格式的长度的字典
BUFF_FORMAT_LENGTH = {
BUFF_COMPLETE_FORMAT_1 : 51
}
#存放各种不同打包格式的格式化字符的字典
BUFF_FORMAT_TYPE = {
BUFF_COMPLETE_FORMAT_1 : "=50B"
}
"""以下是游戏状态标识的配置"""
GAME_WAIT = 0x01 #准备状态
GAME_INIT = 0x02 #游戏初始化状态(此时可以选择带入游戏的植物)
GAME_PLAYING = 0x03 #游戏中状态
"""以下是倒数相关的配置"""
WAIT_COUNTDOWN = 5 #游戏开始倒数时间
INIT_COUNTDOWN = 20 #游戏准备(选择卡片带入游戏)倒数时间
"""以下是精灵状态标识的配置"""
STATUS_WAIT = 0x00 #等待(AI做出下个动作的决定后直到服务端返回消息之前的状态)
STATUS_NEW = 0x01 #刚刚创建
STATUS_BORN = 0x02 #出生状态
STATUS_STAND = 0x03 #原地不动
STATUS_ATTACK = 0x04 #攻击状态
STATUS_MOVE = 0x05 #移动
STATUS_DIE = 0x06 #死亡状态
STATUS_SKILL = 0x07 #使用技能
STATUS_FLY_OUT = 0x08 #物品向屏幕外飞行中(阳光被拾取后)
STATUS_GROW = 0x09 #成长状态(土豆地雷)
STATUS_DIGEST = 0x0A #消化状态(食尸花)
STATUS_SWALLOW = 0x0B #吞咽状态(食尸花)
STATUS_JUMP_UP = 0x0C #跳跃上升阶段(撑杆跳僵尸)
STATUS_JUMP_DOWN = 0x0D #跳跃下降阶段(撑杆跳僵尸)
STATUS_JUMP_FAIL = 0x0E #跳跃失败滑下来的阶段(撑杆跳僵尸)
"""以下是增益状态和减益状态的配置"""
DEBUFF_COOL = 0x01 #寒冷状态(移动速度减慢)
DEBUFF_EXPLODE = 0x02 #被炸(如果在此状态下死亡,则化为灰烬)
DEBUFF_DISAPPEAR = 0x03 #消失(如果在此状态下死亡,则直接消失,不播放死亡动画)
#各种增益/减益状态的持续时间(单位秒)
BUFF_TIME = {DEBUFF_COOL : 10, \
}
"""以下是生命和护甲状态的配置(某些植物或者僵尸会根据生命值来切换模型状态)"""
LIFE_STATE_FULL = 0x01 #生命2/3以上
LIFE_STATE_HURT = 0x02 #生命2/3到1/3
LIFE_STATE_WEAK = 0x03 #生命1/3以下
ARMOR_STATE_FULL = 0x04 #护甲2/3以上
ARMOR_STATE_HURT = 0x05 #护甲2/3到1/3
ARMOR_STATE_WEAK = 0x06 #护甲1/3以下
ARMOE_STATE_NONE = 0x07 #护甲为0
"""以下是僵尸移动函数的返回值"""
RESULT_CAN_MOVE = 0x01 #可以正常移动
RESULT_ENEMY_STOP = 0x02 #遇到敌对可以攻击的敌对物体
"""以下是子弹攻击目标类型配置"""
TARGET_SPRITE = 0x01 #精灵
TARGET_AREA = 0x02 #位置
"""以下是精灵移动方向的配置"""
DIR_TO_HOME = (-1, 0)
DIR_TO_ZOMBIE = (1, 0)
"""以下是一些游戏细节内容相关的配置信息"""
##可种植植物卡片槽上最多有多少个可用的显示控件
MAX_SELECT_CARD_VIEW = 6
##可选择植物卡片箱子里最多有多少个可用的显示控件
MAX_TOTAL_CARD_VIEW = 14
##时间槽上最大显示多少波旗子
MAX_FLAG_VIEW = 4
##地图上横向最大的格子数
MAP_GRID_WIDTH = 9
##地图上每个格子的大小
GRID_PIXEL_WIDTH = 79
GRID_PIXEL_HEIGHT = 105
##默认的精灵模型缩放比例
GRID_SPRITE_SCALE = 1.0
#阳光上限
MAX_ENERGY_STORE = 99999
"""以下是游戏区域物件遮挡层次关系相关参数"""
MAX_LAYER_NUM = 3 #游戏区域总共分为多少层
BG_LAYER = 0 #背景层
SPRITE_LAYER = 1 #精灵层
ITEM_LAYER = 2 #物品层
GRID_RLEVEL_OFFSET = 5 #单个逻辑格rlevel分多少层
BACK_RLEVEL = 1 #南瓜后半
PLANT_RLEVEL = 2 #植物层
FRONT_RLEVEL = 3 #南瓜前半
ZOMBIE_RLEVEL = 4 #怪物层
MISSILE_RLEVEL = 5 #子弹层
#每个逻辑行占用的rlevel数
ROW_RLEVEL_OFFSET = (GRID_RLEVEL_OFFSET + 1) * MAP_GRID_WIDTH
"""以下是阵营配置"""
FACTION_PLANT = 0x01 #植物
FACTION_ZOMBIE = 0x02 #僵尸
FACTION_NONE = 0x03 #中立方(平局时候用)
"""以下是和索敌相关的配置"""
#面向的配置
FACE_TO_LEFT = -1 #面向左边
FACE_TO_RIGHT = 1 #面向右边
##索敌类型配置(面向为前方)
SEEK_FORWARD_LINE = 0x01 #当前行自己前方的全部敌人
SEEK_BACKWARD_LINE = 0x02 #当前行自己后方的全部敌人
SEEK_ALL_LINE = 0x03 #当前行全部的敌人
SEEK_DISTANCE = 0x04 #自己前后多少范围内的敌人
SEEK_TRIP_FORWARD = 0x05 #当前行和上下各一行且在自己前方的全部敌人
"""以下是子弹攻击类型配置"""
ATTACK_SINGLE = 0x01 #只命中一个敌人
ATTACK_ALL = 0x02 #命中全部敌人
ATTACK_SPURT = 0x03 #溅射
"""以下是地图上地形的配置"""
TBASE_GRASS = 0x01 #草地
TBASE_WATER = 0x02 #水面
TBASE_ROOF = 0x03 #屋顶
TBASE_OTHER_TOWER = 0x04 #其他植物
"""以下是游戏区域精灵类型的配置"""
OBJECT_TOWER = 0x01 #炮台(植物)
OBJECT_MONSTER = 0x02 #怪物(僵尸)
OBJECT_MISSILE = 0x03 #子弹(飞射物)
OBJECT_ITEM = 0x04 #奖励物品(阳光)
OBJECT_BASIS = 0x05 #基座(主要是僵尸的攻击可以认为是针对基座的)
OBJECT_EFFECT = 0x06 #特效(一般是某个动画文件)
"""以下是地图区域精灵的id上下边界配置"""
ID_MAX_GENERATE = 10000 #获取可用id的时候最多只会尝试获取多少次,多余这个次数会认为本次获取失败
ID_START_SERVER = 255 #前255个id留给地图区域的炮台底座
ID_END_SERVER = 10000000
ID_START_CLIENT = 10000001
ID_END_CLIENT = 20000000
"""以下是地图区域精灵种类的配置"""
#删除植物的操作(注意不能和精灵定义重复)
JOB_DELETE_PLANT = -1
##地图上各类精灵的定义
JOB_TOWER_SUNFLOWER = 0x01 #向日葵
JOB_TOWER_PEA = 0x02 #豌豆射手
JOB_TOWER_LILY = 0x03 #睡莲
JOB_TOWER_POT = 0x04 #花盆
JOB_TOWER_PUMPKIN = 0x05 #南瓜
JOB_TOWER_REPEATER = 0x06 #双发豌豆射手
JOB_TOWER_THREEPEATER = 0x07 #散弹豌豆射手
JOB_TOWER_GATLINGPEA = 0x08 #四联发豌豆射手
JOB_TOWER_SPLITPEA = 0x09 #双向豌豆射手
JOB_TOWER_WALLNUT = 0x0A #小坚果
JOB_TOWER_TALLNUT = 0x0B #大坚果
JOB_TOWER_SNOWPEA = 0x0C #冰冻射手
JOB_TOWER_CHERRYBOMB = 0x0D #草莓炸弹
JOB_TOWER_CHOMPER = 0x0E #食尸花
JOB_TOWER_POTATOMINE = 0x0F #土豆地雷
JOB_MONSTER_NAKED = 0x60 #普通僵尸
JOB_MONSTER_FLAG = 0x61 #旗子僵尸
JOB_MONSTER_CONEHEAD = 0x62 #路障僵尸
JOB_MONSTER_BUCKETHEAD = 0x63 #铁桶僵尸
JOB_MONSTER_SCREENDOOR = 0x64 #门板僵尸
JOB_MONSTER_POLEVAULT = 0x65 #跳高僵尸
JOB_MISSILE_PEA = 0xA0 #豌豆子弹
JOB_MISSILE_SNOWPEA = 0xA1 #冰冻子弹
JOB_ITEM_SUN = 0xE0 #阳光
JOB_ITEM_SILVER = 0xE1 #银币
#所有可选的植物的列表(目前个人信息中没有对可以用哪些植物卡片进行保存,默认所有玩家都可以选择所有可用植物)
ALL_CHOOSE_ABLE_PLANT = (JOB_TOWER_SUNFLOWER, JOB_TOWER_PEA, JOB_TOWER_REPEATER, \
JOB_TOWER_WALLNUT, JOB_TOWER_SNOWPEA, \
JOB_TOWER_CHERRYBOMB, JOB_TOWER_CHOMPER, JOB_TOWER_POTATOMINE, \
)
##地图上植物种植需要的地形配置
BUILD_LAND_DIC = {
JOB_TOWER_SUNFLOWER : TBASE_GRASS, \
JOB_TOWER_PEA : TBASE_GRASS, \
JOB_TOWER_LILY : TBASE_WATER, \
JOB_TOWER_POT : TBASE_ROOF, \
JOB_TOWER_PUMPKIN : TBASE_GRASS, \
JOB_TOWER_REPEATER : TBASE_GRASS, \
JOB_TOWER_WALLNUT : TBASE_GRASS, \
JOB_TOWER_TALLNUT : TBASE_GRASS, \
JOB_TOWER_SNOWPEA : TBASE_GRASS, \
JOB_TOWER_CHERRYBOMB : TBASE_GRASS, \
JOB_TOWER_POTATOMINE : TBASE_GRASS, \
JOB_TOWER_CHOMPER : TBASE_GRASS, \
}
##地图上强化植物需要的原始植物类型
BUILD_PANLT_DIC = {
}
##地图上僵尸能够出现的地形
MONSTER_APPEAR_DIC = {
JOB_MONSTER_NAKED : (TBASE_GRASS, TBASE_ROOF), \
JOB_MONSTER_FLAG : (TBASE_GRASS, TBASE_ROOF), \
JOB_MONSTER_CONEHEAD : (TBASE_GRASS, TBASE_ROOF), \
JOB_MONSTER_BUCKETHEAD : (TBASE_GRASS, TBASE_ROOF), \
JOB_MONSTER_POLEVAULT : (TBASE_GRASS, TBASE_ROOF), \
}
##植物和僵尸技能的配置
SKILL_CREATE_SUN = 0x01 #制造阳光
SKILL_EXPLODE = 0x02 #爆炸
SKILL_EAT = 0x03 #吞吃
SKILL_JUMP = 0x04 #跳跃
##植物死亡方式的配置(成就统计用)
DIE_STYLE_HURT = 0x01 #被僵尸杀掉的
DIE_STYLE_DELETE = 0x02 #玩家自己铲掉的
DIE_STYLE_SUICIDE = 0x03 #自杀(炸弹类的死法)
"""以下是日志相关配置"""
LOGTYPE_DEEP = 0x01 #底层调试用日志(日志等级deep)
LOGTYPE_DEBUG = 0x02 #dubug日志(日志等级debug)
LOGTYPE_KEYPOINT = 0x03 #游戏逻辑关键时间点或关键事件的日志,如玩家登陆等(日志等级info)
LOGTYPE_KEYDATA = 0x04 #游戏关键数据日志,玩家的可积累数据、物品、付费道具等(日志等级info)
LOGTYPE_DESIGN = 0x05 #某些数据超出了游戏设计的边界,如动态id溢出(日志等级warn)
LOGTYPE_CONFIG = 0x06 #某些配置在实际运行中不可用或溢出
LOGTYPE_ERROR = 0x07 #意外错误,一般是因为程序逻辑存在漏洞或者被破解的客户端胡乱发包引起
##日志关键字,用以扫描日志的时候区分不同日志类型
LOG_KEYWORD_DIC = {
LOGTYPE_DEEP : '', \
LOGTYPE_DEBUG : '', \
LOGTYPE_KEYPOINT : '[KP]', \
LOGTYPE_KEYDATA : '[KD]', \
LOGTYPE_DESIGN : '[DESIGN]', \
LOGTYPE_CONFIG : '[CONF]', \
LOGTYPE_ERROR : '[ERROR]'
}
| Python |
#! /usr/bin/env python
#coding=utf-8
# 此方法用于生成寻路网格
import tgame_map
import iworld2d
class rect(object):
def __init__(self, lu, ru, ld, rd):
self.lu = lu
self.ru = ru
self.ld = ld
self.rd = rd
def init():
global g_allpos, g_allsize, possum, sizesum
g_allpos = {}
g_allsize = {}
possum = 0
sizesum = 0
global g_rects
g_rects = {}
pass
def getnaline():
global g_allpos, g_allsize, possum, sizesum, g_rects
# 地形的所有可碰撞物体(不可移动矩形)
for objn in tgame_map.g_objs:
obj = tgame_map.g_objs[objn]
if not obj.face:
continue
# 获取其位置,大小
pos = obj.pos
size = obj.face.size
g_allpos[str(possum)] = pos
g_allsize[str(possum)] = size
possum += 1
sizesum += 1
print "pos:",pos," size:",size
# 获取到的位置为左上角,目前该功能只做无旋转的物体
# 计算也一个物体的4个顶点,连接成一个四边形
lu = pos
ru = (pos[0] + size[0], pos[1])
ld = (pos[0], pos[1] + size[1])
rd = (pos[0] + size[0], pos[1] + size[1])
g_rects[str(possum)] = rect(lu, ru, ld, rd)
for id in g_rects:
print g_rects[id].ld, g_rects[id].rd, g_rects[id].ru, g_rects[id].lu
pass
# 读取地图,获取其信息
def getmap(map_name):
maps = __import__("tgame_map_%s"%map_name)
global g_allpos, g_allsize, possum, sizesum, g_rects
# 循环获取每一层场景 游戏场景固定物体一共4层
icode = 1
for obj in maps.data:
map_obj = maps.data.get(obj)
if map_obj["type"] != "floor" and map_obj["type"] != "za" and map_obj["type"] != "img_tile_p" and map_obj["type"] != "img_tile_p_b":
continue
img = iworld2d.image2d(map_obj["img"])
pos = map_obj["pos"]
size = img.size
if map_obj["type"] == "img_tile_p" or map_obj["type"] == "img_tile_p_b":
size = (img.size[0]*map_obj["w"], img.size[1] * map_obj["h"])
g_allpos[str(possum)] = pos
g_allsize[str(possum)] = size
possum += 1
sizesum += 1
print "pos:",pos," size:",size
# 获取到的位置为左上角,目前该功能只做无旋转的物体
# 计算也一个物体的4个顶点,连接成一个四边形
pc = 0
#if icode%4 == 2:
# pc = 1
#if icode%4 == 3:
# pc = 2
#if icode%4 == 0:
# pc = 3
lu = (pos[0] + pc, pos[1] + pc)
ru = (pos[0] + size[0] + pc, pos[1] + pc)
ld = (pos[0] + pc, pos[1] + size[1] + pc)
rd = (pos[0] + size[0] + pc, pos[1] + size[1] + pc)
g_rects[str(possum)] = rect(lu, ru, ld, rd)
img.destroy()
icode+=1
for id in g_rects:
print g_rects[id].ld, g_rects[id].rd, g_rects[id].ru, g_rects[id].lu
| Python |
#! /usr/bin/env python
#coding=utf-8
# 此方法用于生成寻路网格
import tgame_map
import iworld2d
class rect(object):
def __init__(self, lu, ru, ld, rd):
self.lu = lu
self.ru = ru
self.ld = ld
self.rd = rd
def init():
global g_allpos, g_allsize, possum, sizesum
g_allpos = {}
g_allsize = {}
possum = 0
sizesum = 0
global g_rects
g_rects = {}
pass
def getnaline():
global g_allpos, g_allsize, possum, sizesum, g_rects
# 地形的所有可碰撞物体(不可移动矩形)
for objn in tgame_map.g_objs:
obj = tgame_map.g_objs[objn]
if not obj.face:
continue
# 获取其位置,大小
pos = obj.pos
size = obj.face.size
g_allpos[str(possum)] = pos
g_allsize[str(possum)] = size
possum += 1
sizesum += 1
print "pos:",pos," size:",size
# 获取到的位置为左上角,目前该功能只做无旋转的物体
# 计算也一个物体的4个顶点,连接成一个四边形
lu = pos
ru = (pos[0] + size[0], pos[1])
ld = (pos[0], pos[1] + size[1])
rd = (pos[0] + size[0], pos[1] + size[1])
g_rects[str(possum)] = rect(lu, ru, ld, rd)
for id in g_rects:
print g_rects[id].ld, g_rects[id].rd, g_rects[id].ru, g_rects[id].lu
pass
# 读取地图,获取其信息
def getmap(map_name):
maps = __import__("tgame_map_%s"%map_name)
global g_allpos, g_allsize, possum, sizesum, g_rects
# 循环获取每一层场景 游戏场景固定物体一共4层
icode = 1
for obj in maps.data:
map_obj = maps.data.get(obj)
if map_obj["type"] != "floor" and map_obj["type"] != "za" and map_obj["type"] != "img_tile_p" and map_obj["type"] != "img_tile_p_b":
continue
img = iworld2d.image2d(map_obj["img"])
pos = map_obj["pos"]
size = img.size
if map_obj["type"] == "img_tile_p" or map_obj["type"] == "img_tile_p_b":
size = (img.size[0]*map_obj["w"], img.size[1] * map_obj["h"])
g_allpos[str(possum)] = pos
g_allsize[str(possum)] = size
possum += 1
sizesum += 1
print "pos:",pos," size:",size
# 获取到的位置为左上角,目前该功能只做无旋转的物体
# 计算也一个物体的4个顶点,连接成一个四边形
pc = 0
#if icode%4 == 2:
# pc = 1
#if icode%4 == 3:
# pc = 2
#if icode%4 == 0:
# pc = 3
lu = (pos[0] + pc, pos[1] + pc)
ru = (pos[0] + size[0] + pc, pos[1] + pc)
ld = (pos[0] + pc, pos[1] + size[1] + pc)
rd = (pos[0] + size[0] + pc, pos[1] + size[1] + pc)
g_rects[str(possum)] = rect(lu, ru, ld, rd)
img.destroy()
icode+=1
for id in g_rects:
print g_rects[id].ld, g_rects[id].rd, g_rects[id].ru, g_rects[id].lu
| Python |
data = {
"id0":{
"p1":(0,4099),
"p2":(4099,4099),
"p3":(1534,4096),
"minwidth":3,
"lj":["id12","id13"],
},
"id1":{
"p1":(4099,4099),
"p2":(4099,0),
"p3":(1534,2196),
"minwidth":2869,
"lj":["id2","id8"],
},
"id2":{
"p1":(4099,0),
"p2":(0,0),
"p3":(1534,2196),
"minwidth":2456,
"lj":["id1","id9"],
},
"id3":{
"p1":(0,0),
"p2":(0,4099),
"p3":(337,2196),
"minwidth":376,
"lj":["id18","id19"],
},
"id4":{
"p1":(1411,3672),
"p2":(1000,3672),
"p3":(1446,4096),
"minwidth":316,
"lj":["id11","id34"],
},
"id5":{
"p1":(1411,3435),
"p2":(1411,3672),
"p3":(1446,3146),
"minwidth":17,
"lj":["id11","id35"],
},
"id6":{
"p1":(1000,3435),
"p2":(1411,3435),
"p3":(1143,3301),
"minwidth":149,
"lj":["id29","id36"],
},
"id7":{
"p1":(1000,3672),
"p2":(1000,3435),
"p3":(851,3517),
"minwidth":166,
"lj":["id37","id38"],
},
"id8":{
"p1":(1534,2196),
"p2":(1534,3146),
"p3":(4099,4099),
"minwidth":853,
"lj":["id1","id13"],
},
"id9":{
"p1":(1446,2196),
"p2":(1534,2196),
"p3":(0,0),
"minwidth":80,
"lj":["id2","id39"],
},
"id10":{
"p1":(1446,3146),
"p2":(1446,2196),
"p3":(1258,3130),
"minwidth":210,
"lj":["id31","id32"],
},
"id11":{
"p1":(1446,4096),
"p2":(1446,3146),
"p3":(1411,3672),
"minwidth":39,
"lj":["id4","id5"],
},
"id12":{
"p1":(1534,4096),
"p2":(1446,4096),
"p3":(0,4099),
"minwidth":0,
"lj":["id0","id40"],
},
"id13":{
"p1":(1534,3146),
"p2":(1534,4096),
"p3":(4099,4099),
"minwidth":1062,
"lj":["id0","id8"],
},
"id14":{
"p1":(337,4096),
"p2":(337,3146),
"p3":(0,4099),
"minwidth":376,
"lj":["id15","id19"],
},
"id15":{
"p1":(425,4096),
"p2":(337,4096),
"p3":(0,4099),
"minwidth":0,
"lj":["id14","id40"],
},
"id16":{
"p1":(425,3146),
"p2":(425,4096),
"p3":(440,3517),
"minwidth":16,
"lj":["id24","id25"],
},
"id17":{
"p1":(425,2196),
"p2":(425,3146),
"p3":(890,3120),
"minwidth":477,
"lj":["id41","id42"],
},
"id18":{
"p1":(337,2196),
"p2":(425,2196),
"p3":(0,0),
"minwidth":96,
"lj":["id3","id39"],
},
"id19":{
"p1":(337,3146),
"p2":(337,2196),
"p3":(0,4099),
"minwidth":185,
"lj":["id3","id14"],
},
"id20":{
"p1":(1018,3120),
"p2":(1018,3150),
"p3":(1130,3130),
"minwidth":33,
"lj":["id33","id43"],
},
"id21":{
"p1":(890,3120),
"p2":(1018,3120),
"p3":(1446,2196),
"minwidth":122,
"lj":["id41","id43"],
},
"id22":{
"p1":(890,3190),
"p2":(890,3120),
"p3":(785,3190),
"minwidth":65,
"lj":["id42"],
},
"id23":{
"p1":(785,3280),
"p2":(785,3190),
"p3":(440,3280),
"minwidth":97,
"lj":["id44"],
},
"id24":{
"p1":(440,3517),
"p2":(440,3280),
"p3":(425,3146),
"minwidth":10,
"lj":["id16","id44"],
},
"id25":{
"p1":(851,3517),
"p2":(440,3517),
"p3":(425,4096),
"minwidth":370,
"lj":["id16","id37"],
},
"id26":{
"p1":(851,3341),
"p2":(851,3517),
"p3":(913,3341),
"minwidth":69,
"lj":["id38"],
},
"id27":{
"p1":(913,3271),
"p2":(913,3341),
"p3":(1015,3301),
"minwidth":72,
"lj":["id28","id45"],
},
"id28":{
"p1":(1015,3271),
"p2":(913,3271),
"p3":(1015,3301),
"minwidth":33,
"lj":["id27"],
},
"id29":{
"p1":(1143,3301),
"p2":(1015,3301),
"p3":(1000,3435),
"minwidth":97,
"lj":["id6","id45"],
},
"id30":{
"p1":(1143,3281),
"p2":(1143,3301),
"p3":(1258,3281),
"minwidth":22,
"lj":["id36"],
},
"id31":{
"p1":(1258,3130),
"p2":(1258,3281),
"p3":(1446,3146),
"minwidth":137,
"lj":["id10","id35"],
},
"id32":{
"p1":(1130,3130),
"p2":(1258,3130),
"p3":(1446,2196),
"minwidth":140,
"lj":["id10","id43"],
},
"id33":{
"p1":(1130,3150),
"p2":(1130,3130),
"p3":(1018,3150),
"minwidth":22,
"lj":["id20"],
},
"id34":{
"p1":(1446,4096),
"p2":(1000,3672),
"p3":(425,4096),
"minwidth":474,
"lj":["id4","id37","id40"],
},
"id35":{
"p1":(1411,3435),
"p2":(1446,3146),
"p3":(1258,3281),
"minwidth":190,
"lj":["id5","id31","id36"],
},
"id36":{
"p1":(1143,3301),
"p2":(1411,3435),
"p3":(1258,3281),
"minwidth":77,
"lj":["id6","id30","id35"],
},
"id37":{
"p1":(1000,3672),
"p2":(851,3517),
"p3":(425,4096),
"minwidth":236,
"lj":["id7","id25","id34"],
},
"id38":{
"p1":(851,3517),
"p2":(1000,3435),
"p3":(913,3341),
"minwidth":126,
"lj":["id7","id26","id45"],
},
"id39":{
"p1":(1446,2196),
"p2":(0,0),
"p3":(425,2196),
"minwidth":953,
"lj":["id9","id18","id41"],
},
"id40":{
"p1":(0,4099),
"p2":(1446,4096),
"p3":(425,4096),
"minwidth":2,
"lj":["id12","id15","id34"],
},
"id41":{
"p1":(425,2196),
"p2":(890,3120),
"p3":(1446,2196),
"minwidth":978,
"lj":["id17","id21","id39"],
},
"id42":{
"p1":(890,3120),
"p2":(425,3146),
"p3":(785,3190),
"minwidth":71,
"lj":["id17","id22","id44"],
},
"id43":{
"p1":(1018,3120),
"p2":(1130,3130),
"p3":(1446,2196),
"minwidth":122,
"lj":["id20","id21","id32"],
},
"id44":{
"p1":(440,3280),
"p2":(785,3190),
"p3":(425,3146),
"minwidth":149,
"lj":["id23","id24","id42"],
},
"id45":{
"p1":(1015,3301),
"p2":(913,3341),
"p3":(1000,3435),
"minwidth":108,
"lj":["id27","id29","id38"],
},
}
def get_data(id):
return data.get(id)
| Python |
data = {
"id0":{
"p1":(-1,7200),
"p2":(15300,7200),
"p3":(6976,7190),
"minwidth":11,
"lj":["id8","id188"],
},
"id1":{
"p1":(15300,7200),
"p2":(15300,-1),
"p3":(15217,3645),
"minwidth":92,
"lj":["id93","id189"],
},
"id2":{
"p1":(15300,-1),
"p2":(-1,-1),
"p3":(9555,245),
"minwidth":275,
"lj":["id124","id125"],
},
"id3":{
"p1":(-1,-1),
"p2":(-1,7200),
"p3":(1,2878),
"minwidth":2,
"lj":["id183","id190"],
},
"id4":{
"p1":(1702,5481),
"p2":(1574,5481),
"p3":(1238,5750),
"minwidth":71,
"lj":["id133","id134"],
},
"id5":{
"p1":(1702,3820),
"p2":(1702,5481),
"p3":(1877,3803),
"minwidth":195,
"lj":["id6","id191"],
},
"id6":{
"p1":(1574,3820),
"p2":(1702,3820),
"p3":(1877,3803),
"minwidth":8,
"lj":["id5","id57"],
},
"id7":{
"p1":(1574,5481),
"p2":(1574,3820),
"p3":(1238,4264),
"minwidth":375,
"lj":["id134","id135"],
},
"id8":{
"p1":(6976,7190),
"p2":(6888,7190),
"p3":(-1,7200),
"minwidth":0,
"lj":["id0","id192"],
},
"id9":{
"p1":(6976,6365),
"p2":(6976,7190),
"p3":(9520,6364),
"minwidth":877,
"lj":["id64","id65"],
},
"id10":{
"p1":(6888,6365),
"p2":(6976,6365),
"p3":(3960,6364),
"minwidth":0,
"lj":["id11","id193"],
},
"id11":{
"p1":(6888,7190),
"p2":(6888,6365),
"p3":(3960,6364),
"minwidth":922,
"lj":["id10","id143"],
},
"id12":{
"p1":(9728,315),
"p2":(9728,325),
"p3":(9848,325),
"minwidth":11,
"lj":["id194"],
},
"id13":{
"p1":(9600,315),
"p2":(9728,315),
"p3":(9591,245),
"minwidth":65,
"lj":["id14","id195"],
},
"id14":{
"p1":(9600,466),
"p2":(9600,315),
"p3":(9591,245),
"minwidth":6,
"lj":["id13","id123"],
},
"id15":{
"p1":(9720,466),
"p2":(9600,466),
"p3":(9720,476),
"minwidth":11,
"lj":["id196"],
},
"id16":{
"p1":(9848,476),
"p2":(9720,476),
"p3":(9591,2964),
"minwidth":142,
"lj":["id196","id197"],
},
"id17":{
"p1":(9848,325),
"p2":(9848,476),
"p3":(9850,451),
"minwidth":2,
"lj":["id29","id198"],
},
"id18":{
"p1":(6520,708),
"p2":(8056,708),
"p3":(9520,403),
"minwidth":173,
"lj":["id23","id199"],
},
"id19":{
"p1":(6520,866),
"p2":(6520,708),
"p3":(6264,866),
"minwidth":150,
"lj":["id47","id200"],
},
"id20":{
"p1":(7999,866),
"p2":(6520,866),
"p3":(7999,2840),
"minwidth":1323,
"lj":["id201"],
},
"id21":{
"p1":(8070,2840),
"p2":(7999,2840),
"p3":(8275,2841),
"minwidth":0,
"lj":["id22","id202"],
},
"id22":{
"p1":(8070,708),
"p2":(8070,2840),
"p3":(8275,2841),
"minwidth":228,
"lj":["id21","id203"],
},
"id23":{
"p1":(8056,708),
"p2":(8070,708),
"p3":(9520,403),
"minwidth":3,
"lj":["id18","id204"],
},
"id24":{
"p1":(9910,461),
"p2":(9910,451),
"p3":(9850,451),
"minwidth":11,
"lj":["id198"],
},
"id25":{
"p1":(10038,461),
"p2":(9910,461),
"p3":(9848,476),
"minwidth":11,
"lj":["id198","id205"],
},
"id26":{
"p1":(10038,310),
"p2":(10038,461),
"p3":(10040,245),
"minwidth":1,
"lj":["id157","id206"],
},
"id27":{
"p1":(9978,310),
"p2":(10038,310),
"p3":(9978,300),
"minwidth":11,
"lj":["id206"],
},
"id28":{
"p1":(9850,300),
"p2":(9978,300),
"p3":(10040,245),
"minwidth":39,
"lj":["id206","id207"],
},
"id29":{
"p1":(9850,451),
"p2":(9850,300),
"p3":(9848,325),
"minwidth":2,
"lj":["id17","id194"],
},
"id30":{
"p1":(2930,2269),
"p2":(2859,2269),
"p3":(2930,2275),
"minwidth":6,
"lj":["id40","id208"],
},
"id31":{
"p1":(2930,1063),
"p2":(2930,2269),
"p3":(5204,1063),
"minwidth":1191,
"lj":["id208"],
},
"id32":{
"p1":(5204,905),
"p2":(5204,1063),
"p3":(5460,905),
"minwidth":150,
"lj":["id37","id209"],
},
"id33":{
"p1":(2930,905),
"p2":(5204,905),
"p3":(2417,403),
"minwidth":450,
"lj":["id34","id210"],
},
"id34":{
"p1":(2859,905),
"p2":(2930,905),
"p3":(2417,403),
"minwidth":55,
"lj":["id33","id35"],
},
"id35":{
"p1":(2859,2269),
"p2":(2859,905),
"p3":(2417,403),
"minwidth":351,
"lj":["id34","id117"],
},
"id36":{
"p1":(5460,905),
"p2":(5967,905),
"p3":(5967,708),
"minwidth":205,
"lj":["id209"],
},
"id37":{
"p1":(5460,1063),
"p2":(5460,905),
"p3":(5204,1063),
"minwidth":150,
"lj":["id32","id211"],
},
"id38":{
"p1":(5967,1063),
"p2":(5460,1063),
"p3":(5967,2275),
"minwidth":523,
"lj":["id211"],
},
"id39":{
"p1":(2930,2275),
"p2":(5967,2275),
"p3":(5204,1063),
"minwidth":1355,
"lj":["id208","id211"],
},
"id40":{
"p1":(2859,2275),
"p2":(2930,2275),
"p3":(2859,2269),
"minwidth":6,
"lj":["id30","id212"],
},
"id41":{
"p1":(2859,2398),
"p2":(2859,2275),
"p3":(2417,2841),
"minwidth":84,
"lj":["id42","id212"],
},
"id42":{
"p1":(2900,2398),
"p2":(2859,2398),
"p3":(2417,2841),
"minwidth":30,
"lj":["id41","id116"],
},
"id43":{
"p1":(5967,2398),
"p2":(2900,2398),
"p3":(3923,2841),
"minwidth":495,
"lj":["id44","id213"],
},
"id44":{
"p1":(5967,2840),
"p2":(5967,2398),
"p3":(3923,2841),
"minwidth":483,
"lj":["id43","id73"],
},
"id45":{
"p1":(6038,2840),
"p2":(5967,2840),
"p3":(8275,2841),
"minwidth":0,
"lj":["id73","id202"],
},
"id46":{
"p1":(6038,866),
"p2":(6038,2840),
"p3":(6264,866),
"minwidth":252,
"lj":["id200"],
},
"id47":{
"p1":(6264,708),
"p2":(6264,866),
"p3":(6520,708),
"minwidth":150,
"lj":["id19","id199"],
},
"id48":{
"p1":(6038,708),
"p2":(6264,708),
"p3":(9520,403),
"minwidth":22,
"lj":["id49","id199"],
},
"id49":{
"p1":(5967,708),
"p2":(6038,708),
"p3":(9520,403),
"minwidth":6,
"lj":["id48","id118"],
},
"id50":{
"p1":(1,6320),
"p2":(300,6320),
"p3":(300,3645),
"minwidth":334,
"lj":["id214"],
},
"id51":{
"p1":(1,6557),
"p2":(1,6320),
"p3":(-1,7200),
"minwidth":0,
"lj":["id52","id190"],
},
"id52":{
"p1":(411,6557),
"p2":(1,6557),
"p3":(-1,7200),
"minwidth":386,
"lj":["id51","id215"],
},
"id53":{
"p1":(411,6364),
"p2":(411,6557),
"p3":(3413,6364),
"minwidth":215,
"lj":["id215"],
},
"id54":{
"p1":(3413,6241),
"p2":(3413,6364),
"p3":(3669,6241),
"minwidth":124,
"lj":["id141","id216"],
},
"id55":{
"p1":(371,6241),
"p2":(3413,6241),
"p3":(1238,5925),
"minwidth":353,
"lj":["id137","id138"],
},
"id56":{
"p1":(371,3803),
"p2":(371,6241),
"p3":(1110,4264),
"minwidth":826,
"lj":["id136","id217"],
},
"id57":{
"p1":(1877,3803),
"p2":(371,3803),
"p3":(1574,3820),
"minwidth":19,
"lj":["id6","id217"],
},
"id58":{
"p1":(1877,3645),
"p2":(1877,3803),
"p3":(2133,3645),
"minwidth":150,
"lj":["id131","id218"],
},
"id59":{
"p1":(371,3645),
"p2":(1877,3645),
"p3":(1577,2878),
"minwidth":904,
"lj":["id185","id219"],
},
"id60":{
"p1":(300,3645),
"p2":(371,3645),
"p3":(41,2878),
"minwidth":72,
"lj":["id184","id185"],
},
"id61":{
"p1":(4395,3645),
"p2":(4466,3645),
"p3":(4630,2964),
"minwidth":77,
"lj":["id75","id76"],
},
"id62":{
"p1":(4395,6364),
"p2":(4395,3645),
"p3":(3960,6364),
"minwidth":486,
"lj":["id144","id193"],
},
"id63":{
"p1":(4436,6364),
"p2":(4395,6364),
"p3":(6976,6365),
"minwidth":0,
"lj":["id64","id193"],
},
"id64":{
"p1":(9520,6364),
"p2":(4436,6364),
"p3":(6976,6365),
"minwidth":1,
"lj":["id9","id63"],
},
"id65":{
"p1":(9591,6364),
"p2":(9520,6364),
"p3":(6976,7190),
"minwidth":23,
"lj":["id9","id220"],
},
"id66":{
"p1":(9591,5127),
"p2":(9591,6364),
"p3":(10001,5127),
"minwidth":458,
"lj":["id221"],
},
"id67":{
"p1":(10001,4890),
"p2":(10001,5127),
"p3":(10040,6364),
"minwidth":7,
"lj":["id108","id221"],
},
"id68":{
"p1":(9591,4890),
"p2":(10001,4890),
"p3":(9591,3645),
"minwidth":435,
"lj":["id222"],
},
"id69":{
"p1":(9556,3645),
"p2":(9591,3645),
"p3":(9591,2964),
"minwidth":39,
"lj":["id122","id223"],
},
"id70":{
"p1":(5142,3645),
"p2":(9556,3645),
"p3":(8275,2964),
"minwidth":761,
"lj":["id71","id224"],
},
"id71":{
"p1":(5142,2964),
"p2":(5142,3645),
"p3":(8275,2964),
"minwidth":744,
"lj":["id70"],
},
"id72":{
"p1":(8275,2841),
"p2":(8275,2964),
"p3":(8531,2841),
"minwidth":124,
"lj":["id120","id203"],
},
"id73":{
"p1":(3923,2841),
"p2":(8275,2841),
"p3":(5967,2840),
"minwidth":1,
"lj":["id44","id45"],
},
"id74":{
"p1":(3923,2964),
"p2":(3923,2841),
"p3":(3667,2964),
"minwidth":124,
"lj":["id115","id225"],
},
"id75":{
"p1":(4630,2964),
"p2":(3923,2964),
"p3":(4395,3645),
"minwidth":649,
"lj":["id61","id226"],
},
"id76":{
"p1":(4630,3645),
"p2":(4630,2964),
"p3":(4466,3645),
"minwidth":183,
"lj":["id61"],
},
"id77":{
"p1":(9520,6241),
"p2":(9520,3803),
"p3":(4466,6241),
"minwidth":2456,
"lj":["id78"],
},
"id78":{
"p1":(4466,3803),
"p2":(4466,6241),
"p3":(9520,3803),
"minwidth":2456,
"lj":["id77"],
},
"id79":{
"p1":(12652,3803),
"p2":(12652,6241),
"p3":(15146,3803),
"minwidth":1950,
"lj":["id80"],
},
"id80":{
"p1":(15146,6241),
"p2":(15146,3803),
"p3":(12652,6241),
"minwidth":1950,
"lj":["id79"],
},
"id81":{
"p1":(12652,3645),
"p2":(15182,3645),
"p3":(15146,2964),
"minwidth":745,
"lj":["id169","id170"],
},
"id82":{
"p1":(12581,3645),
"p2":(12652,3645),
"p3":(12622,2964),
"minwidth":79,
"lj":["id168","id169"],
},
"id83":{
"p1":(12581,4644),
"p2":(12581,3645),
"p3":(12503,4552),
"minwidth":87,
"lj":["id84","id85"],
},
"id84":{
"p1":(12503,4644),
"p2":(12581,4644),
"p3":(12503,4552),
"minwidth":66,
"lj":["id83"],
},
"id85":{
"p1":(12375,4552),
"p2":(12503,4552),
"p3":(12581,3645),
"minwidth":142,
"lj":["id83","id227"],
},
"id86":{
"p1":(12375,4703),
"p2":(12375,4552),
"p3":(12164,5346),
"minwidth":43,
"lj":["id104","id228"],
},
"id87":{
"p1":(12477,4703),
"p2":(12375,4703),
"p3":(12477,4795),
"minwidth":76,
"lj":["id229"],
},
"id88":{
"p1":(12581,4795),
"p2":(12477,4795),
"p3":(12392,5300),
"minwidth":114,
"lj":["id101","id102"],
},
"id89":{
"p1":(12581,6364),
"p2":(12581,4795),
"p3":(12392,5451),
"minwidth":211,
"lj":["id101","id230"],
},
"id90":{
"p1":(12622,6364),
"p2":(12581,6364),
"p3":(15300,7200),
"minwidth":13,
"lj":["id91","id231"],
},
"id91":{
"p1":(15146,6364),
"p2":(12622,6364),
"p3":(15300,7200),
"minwidth":841,
"lj":["id90","id92"],
},
"id92":{
"p1":(15217,6364),
"p2":(15146,6364),
"p3":(15300,7200),
"minwidth":78,
"lj":["id91","id93"],
},
"id93":{
"p1":(15217,3645),
"p2":(15217,6364),
"p3":(15300,7200),
"minwidth":70,
"lj":["id1","id92"],
},
"id94":{
"p1":(15182,3645),
"p2":(15217,3645),
"p3":(15217,2964),
"minwidth":39,
"lj":["id170","id189"],
},
"id95":{
"p1":(12093,403),
"p2":(10111,403),
"p3":(12093,2841),
"minwidth":1720,
"lj":["id96"],
},
"id96":{
"p1":(10111,2841),
"p2":(12093,2841),
"p3":(10111,403),
"minwidth":1720,
"lj":["id95"],
},
"id97":{
"p1":(12093,6364),
"p2":(10081,6364),
"p3":(6976,7190),
"minwidth":358,
"lj":["id109","id188"],
},
"id98":{
"p1":(12164,6364),
"p2":(12093,6364),
"p3":(15300,7200),
"minwidth":20,
"lj":["id188","id231"],
},
"id99":{
"p1":(12164,5497),
"p2":(12164,6364),
"p3":(12276,5497),
"minwidth":125,
"lj":["id232"],
},
"id100":{
"p1":(12276,5451),
"p2":(12276,5497),
"p3":(12392,5451),
"minwidth":47,
"lj":["id230"],
},
"id101":{
"p1":(12392,5300),
"p2":(12392,5451),
"p3":(12581,4795),
"minwidth":46,
"lj":["id88","id89"],
},
"id102":{
"p1":(12264,5300),
"p2":(12392,5300),
"p3":(12477,4795),
"minwidth":141,
"lj":["id88","id229"],
},
"id103":{
"p1":(12264,5346),
"p2":(12264,5300),
"p3":(12164,5346),
"minwidth":46,
"lj":["id228"],
},
"id104":{
"p1":(12164,3645),
"p2":(12164,5346),
"p3":(12375,4552),
"minwidth":236,
"lj":["id86","id227"],
},
"id105":{
"p1":(12129,3645),
"p2":(12164,3645),
"p3":(12164,2964),
"minwidth":39,
"lj":["id160","id233"],
},
"id106":{
"p1":(10111,3645),
"p2":(12129,3645),
"p3":(12093,2964),
"minwidth":733,
"lj":["id159","id160"],
},
"id107":{
"p1":(10040,3645),
"p2":(10111,3645),
"p3":(10081,2964),
"minwidth":79,
"lj":["id158","id159"],
},
"id108":{
"p1":(10040,6364),
"p2":(10040,3645),
"p3":(10001,4890),
"minwidth":43,
"lj":["id67","id222"],
},
"id109":{
"p1":(10081,6364),
"p2":(10040,6364),
"p3":(6976,7190),
"minwidth":11,
"lj":["id97","id220"],
},
"id110":{
"p1":(12093,6241),
"p2":(12093,3803),
"p3":(10111,6241),
"minwidth":1720,
"lj":["id111"],
},
"id111":{
"p1":(10111,3803),
"p2":(10111,6241),
"p3":(12093,3803),
"minwidth":1720,
"lj":["id110"],
},
"id112":{
"p1":(3925,3645),
"p2":(3960,3645),
"p3":(3923,2964),
"minwidth":39,
"lj":["id225","id226"],
},
"id113":{
"p1":(3482,3645),
"p2":(3925,3645),
"p3":(3667,2964),
"minwidth":463,
"lj":["id114","id225"],
},
"id114":{
"p1":(3482,2964),
"p2":(3482,3645),
"p3":(3667,2964),
"minwidth":206,
"lj":["id113"],
},
"id115":{
"p1":(3667,2841),
"p2":(3667,2964),
"p3":(3923,2841),
"minwidth":124,
"lj":["id74","id213"],
},
"id116":{
"p1":(2417,2841),
"p2":(3667,2841),
"p3":(2900,2398),
"minwidth":495,
"lj":["id42","id213"],
},
"id117":{
"p1":(2417,403),
"p2":(2417,2841),
"p3":(2859,2269),
"minwidth":494,
"lj":["id35","id212"],
},
"id118":{
"p1":(9520,403),
"p2":(2417,403),
"p3":(5967,708),
"minwidth":341,
"lj":["id49","id210"],
},
"id119":{
"p1":(9520,2841),
"p2":(9520,403),
"p3":(8531,2841),
"minwidth":1106,
"lj":["id204"],
},
"id120":{
"p1":(8531,2964),
"p2":(8531,2841),
"p3":(8275,2964),
"minwidth":124,
"lj":["id72","id224"],
},
"id121":{
"p1":(9520,2964),
"p2":(8531,2964),
"p3":(9556,3645),
"minwidth":612,
"lj":["id122","id224"],
},
"id122":{
"p1":(9591,2964),
"p2":(9520,2964),
"p3":(9556,3645),
"minwidth":79,
"lj":["id69","id121"],
},
"id123":{
"p1":(9591,245),
"p2":(9591,2964),
"p3":(9600,466),
"minwidth":10,
"lj":["id14","id196"],
},
"id124":{
"p1":(9555,245),
"p2":(9591,245),
"p3":(15300,-1),
"minwidth":1,
"lj":["id2","id234"],
},
"id125":{
"p1":(2417,245),
"p2":(9555,245),
"p3":(-1,-1),
"minwidth":205,
"lj":["id2","id126"],
},
"id126":{
"p1":(2346,245),
"p2":(2417,245),
"p3":(-1,-1),
"minwidth":8,
"lj":["id125","id235"],
},
"id127":{
"p1":(2346,2964),
"p2":(2346,245),
"p3":(2124,1695),
"minwidth":248,
"lj":["id179","id180"],
},
"id128":{
"p1":(2387,2964),
"p2":(2346,2964),
"p3":(2133,3645),
"minwidth":43,
"lj":["id130","id236"],
},
"id129":{
"p1":(2970,2964),
"p2":(2387,2964),
"p3":(2970,3645),
"minwidth":495,
"lj":["id130"],
},
"id130":{
"p1":(2133,3645),
"p2":(2970,3645),
"p3":(2387,2964),
"minwidth":711,
"lj":["id128","id129"],
},
"id131":{
"p1":(2133,3803),
"p2":(2133,3645),
"p3":(1877,3803),
"minwidth":150,
"lj":["id58","id191"],
},
"id132":{
"p1":(3889,3803),
"p2":(2133,3803),
"p3":(3889,5750),
"minwidth":1458,
"lj":["id237"],
},
"id133":{
"p1":(1238,5750),
"p2":(3889,5750),
"p3":(1702,5481),
"minwidth":300,
"lj":["id4","id237"],
},
"id134":{
"p1":(1238,4264),
"p2":(1238,5750),
"p3":(1574,5481),
"minwidth":375,
"lj":["id4","id7"],
},
"id135":{
"p1":(1110,4264),
"p2":(1238,4264),
"p3":(1574,3820),
"minwidth":98,
"lj":["id7","id217"],
},
"id136":{
"p1":(1110,5925),
"p2":(1110,4264),
"p3":(371,6241),
"minwidth":650,
"lj":["id56","id137"],
},
"id137":{
"p1":(1238,5925),
"p2":(1110,5925),
"p3":(371,6241),
"minwidth":49,
"lj":["id55","id136"],
},
"id138":{
"p1":(1238,5901),
"p2":(1238,5925),
"p3":(3413,6241),
"minwidth":26,
"lj":["id55","id139"],
},
"id139":{
"p1":(3889,5901),
"p2":(1238,5901),
"p3":(3413,6241),
"minwidth":380,
"lj":["id138","id216"],
},
"id140":{
"p1":(3889,6241),
"p2":(3889,5901),
"p3":(3669,6241),
"minwidth":206,
"lj":["id216"],
},
"id141":{
"p1":(3669,6364),
"p2":(3669,6241),
"p3":(3413,6364),
"minwidth":124,
"lj":["id54","id238"],
},
"id142":{
"p1":(3889,6364),
"p2":(3669,6364),
"p3":(6888,7190),
"minwidth":61,
"lj":["id143","id238"],
},
"id143":{
"p1":(3960,6364),
"p2":(3889,6364),
"p3":(6888,7190),
"minwidth":21,
"lj":["id11","id142"],
},
"id144":{
"p1":(3960,3645),
"p2":(3960,6364),
"p3":(4395,3645),
"minwidth":486,
"lj":["id62","id226"],
},
"id145":{
"p1":(15182,245),
"p2":(15217,245),
"p3":(15300,-1),
"minwidth":37,
"lj":["id146","id171"],
},
"id146":{
"p1":(12652,245),
"p2":(15182,245),
"p3":(15300,-1),
"minwidth":261,
"lj":["id145","id147"],
},
"id147":{
"p1":(12581,245),
"p2":(12652,245),
"p3":(15300,-1),
"minwidth":7,
"lj":["id146","id239"],
},
"id148":{
"p1":(12581,310),
"p2":(12581,245),
"p3":(12500,310),
"minwidth":56,
"lj":["id240"],
},
"id149":{
"p1":(12500,325),
"p2":(12500,310),
"p3":(12403,325),
"minwidth":16,
"lj":["id150"],
},
"id150":{
"p1":(12403,300),
"p2":(12403,325),
"p3":(12500,310),
"minwidth":27,
"lj":["id149","id240"],
},
"id151":{
"p1":(12275,300),
"p2":(12403,300),
"p3":(12164,245),
"minwidth":32,
"lj":["id153","id241"],
},
"id152":{
"p1":(12275,315),
"p2":(12275,300),
"p3":(12164,315),
"minwidth":16,
"lj":["id153"],
},
"id153":{
"p1":(12164,245),
"p2":(12164,315),
"p3":(12275,300),
"minwidth":77,
"lj":["id151","id152"],
},
"id154":{
"p1":(12129,245),
"p2":(12164,245),
"p3":(15300,-1),
"minwidth":3,
"lj":["id155","id239"],
},
"id155":{
"p1":(10111,245),
"p2":(12129,245),
"p3":(15300,-1),
"minwidth":106,
"lj":["id154","id156"],
},
"id156":{
"p1":(10040,245),
"p2":(10111,245),
"p3":(15300,-1),
"minwidth":3,
"lj":["id155","id234"],
},
"id157":{
"p1":(10040,2964),
"p2":(10040,245),
"p3":(10038,461),
"minwidth":2,
"lj":["id26","id205"],
},
"id158":{
"p1":(10081,2964),
"p2":(10040,2964),
"p3":(10040,3645),
"minwidth":45,
"lj":["id107","id242"],
},
"id159":{
"p1":(12093,2964),
"p2":(10081,2964),
"p3":(10111,3645),
"minwidth":731,
"lj":["id106","id107"],
},
"id160":{
"p1":(12164,2964),
"p2":(12093,2964),
"p3":(12129,3645),
"minwidth":79,
"lj":["id105","id106"],
},
"id161":{
"p1":(12164,466),
"p2":(12164,2964),
"p3":(12380,476),
"minwidth":241,
"lj":["id162","id243"],
},
"id162":{
"p1":(12278,466),
"p2":(12164,466),
"p3":(12380,476),
"minwidth":5,
"lj":["id161","id164"],
},
"id163":{
"p1":(12278,451),
"p2":(12278,466),
"p3":(12380,451),
"minwidth":16,
"lj":["id164"],
},
"id164":{
"p1":(12380,476),
"p2":(12380,451),
"p3":(12278,466),
"minwidth":27,
"lj":["id162","id163"],
},
"id165":{
"p1":(12508,476),
"p2":(12380,476),
"p3":(12581,2964),
"minwidth":142,
"lj":["id167","id243"],
},
"id166":{
"p1":(12508,461),
"p2":(12508,476),
"p3":(12581,461),
"minwidth":16,
"lj":["id167"],
},
"id167":{
"p1":(12581,2964),
"p2":(12581,461),
"p3":(12508,476),
"minwidth":82,
"lj":["id165","id166"],
},
"id168":{
"p1":(12622,2964),
"p2":(12581,2964),
"p3":(12581,3645),
"minwidth":45,
"lj":["id82","id244"],
},
"id169":{
"p1":(15146,2964),
"p2":(12622,2964),
"p3":(12652,3645),
"minwidth":743,
"lj":["id81","id82"],
},
"id170":{
"p1":(15217,2964),
"p2":(15146,2964),
"p3":(15182,3645),
"minwidth":79,
"lj":["id81","id94"],
},
"id171":{
"p1":(15217,245),
"p2":(15217,2964),
"p3":(15300,-1),
"minwidth":85,
"lj":["id145","id189"],
},
"id172":{
"p1":(15146,403),
"p2":(12652,403),
"p3":(15146,2841),
"minwidth":1950,
"lj":["id173"],
},
"id173":{
"p1":(12652,2841),
"p2":(15146,2841),
"p3":(12652,403),
"minwidth":1950,
"lj":["id172"],
},
"id174":{
"p1":(2053,1853),
"p2":(71,1853),
"p3":(1577,2755),
"minwidth":1008,
"lj":["id187","id245"],
},
"id175":{
"p1":(2053,2755),
"p2":(2053,1853),
"p3":(1833,2755),
"minwidth":246,
"lj":["id245"],
},
"id176":{
"p1":(1833,2878),
"p2":(1833,2755),
"p3":(1577,2878),
"minwidth":124,
"lj":["id186","id219"],
},
"id177":{
"p1":(2053,2878),
"p2":(1833,2878),
"p3":(1877,3645),
"minwidth":245,
"lj":["id218","id219"],
},
"id178":{
"p1":(2124,2878),
"p2":(2053,2878),
"p3":(2133,3645),
"minwidth":78,
"lj":["id218","id236"],
},
"id179":{
"p1":(2124,1695),
"p2":(2124,2878),
"p3":(2346,2964),
"minwidth":228,
"lj":["id127","id236"],
},
"id180":{
"p1":(2089,1695),
"p2":(2124,1695),
"p3":(2346,245),
"minwidth":38,
"lj":["id127","id235"],
},
"id181":{
"p1":(71,1695),
"p2":(2089,1695),
"p3":(-1,-1),
"minwidth":1422,
"lj":["id182","id235"],
},
"id182":{
"p1":(1,1695),
"p2":(71,1695),
"p3":(-1,-1),
"minwidth":78,
"lj":["id181","id183"],
},
"id183":{
"p1":(1,2878),
"p2":(1,1695),
"p3":(-1,-1),
"minwidth":0,
"lj":["id3","id182"],
},
"id184":{
"p1":(41,2878),
"p2":(1,2878),
"p3":(300,3645),
"minwidth":41,
"lj":["id60","id214"],
},
"id185":{
"p1":(1577,2878),
"p2":(41,2878),
"p3":(371,3645),
"minwidth":922,
"lj":["id59","id60"],
},
"id186":{
"p1":(1577,2755),
"p2":(1577,2878),
"p3":(1833,2755),
"minwidth":124,
"lj":["id176","id245"],
},
"id187":{
"p1":(71,2755),
"p2":(1577,2755),
"p3":(71,1853),
"minwidth":865,
"lj":["id174"],
},
"id188":{
"p1":(6976,7190),
"p2":(15300,7200),
"p3":(12093,6364),
"minwidth":930,
"lj":["id0","id97","id98"],
},
"id189":{
"p1":(15217,3645),
"p2":(15300,-1),
"p3":(15217,2964),
"minwidth":17,
"lj":["id1","id94","id171"],
},
"id190":{
"p1":(1,2878),
"p2":(-1,7200),
"p3":(1,6320),
"minwidth":1,
"lj":["id3","id51","id214"],
},
"id191":{
"p1":(1877,3803),
"p2":(1702,5481),
"p3":(2133,3803),
"minwidth":284,
"lj":["id5","id131","id237"],
},
"id192":{
"p1":(-1,7200),
"p2":(6888,7190),
"p3":(3413,6364),
"minwidth":929,
"lj":["id8","id215","id238"],
},
"id193":{
"p1":(3960,6364),
"p2":(6976,6365),
"p3":(4395,6364),
"minwidth":0,
"lj":["id10","id62","id63"],
},
"id194":{
"p1":(9728,315),
"p2":(9848,325),
"p3":(9850,300),
"minwidth":27,
"lj":["id12","id29","id195"],
},
"id195":{
"p1":(9591,245),
"p2":(9728,315),
"p3":(9850,300),
"minwidth":44,
"lj":["id13","id194","id207"],
},
"id196":{
"p1":(9720,476),
"p2":(9600,466),
"p3":(9591,2964),
"minwidth":134,
"lj":["id15","id16","id123"],
},
"id197":{
"p1":(9848,476),
"p2":(9591,2964),
"p3":(10040,2964),
"minwidth":500,
"lj":["id16","id205","id223"],
},
"id198":{
"p1":(9850,451),
"p2":(9848,476),
"p3":(9910,461),
"minwidth":26,
"lj":["id17","id24","id25"],
},
"id199":{
"p1":(6520,708),
"p2":(9520,403),
"p3":(6264,708),
"minwidth":26,
"lj":["id18","id47","id48"],
},
"id200":{
"p1":(6520,866),
"p2":(6264,866),
"p3":(6038,2840),
"minwidth":284,
"lj":["id19","id46","id201"],
},
"id201":{
"p1":(7999,2840),
"p2":(6520,866),
"p3":(6038,2840),
"minwidth":1755,
"lj":["id20","id200","id202"],
},
"id202":{
"p1":(8275,2841),
"p2":(7999,2840),
"p3":(6038,2840),
"minwidth":0,
"lj":["id21","id45","id201"],
},
"id203":{
"p1":(8070,708),
"p2":(8275,2841),
"p3":(8531,2841),
"minwidth":279,
"lj":["id22","id72","id204"],
},
"id204":{
"p1":(9520,403),
"p2":(8070,708),
"p3":(8531,2841),
"minwidth":1374,
"lj":["id23","id119","id203"],
},
"id205":{
"p1":(10038,461),
"p2":(9848,476),
"p3":(10040,2964),
"minwidth":213,
"lj":["id25","id157","id197"],
},
"id206":{
"p1":(10038,310),
"p2":(10040,245),
"p3":(9978,300),
"minwidth":52,
"lj":["id26","id27","id28"],
},
"id207":{
"p1":(9850,300),
"p2":(10040,245),
"p3":(9591,245),
"minwidth":61,
"lj":["id28","id195","id234"],
},
"id208":{
"p1":(2930,2269),
"p2":(2930,2275),
"p3":(5204,1063),
"minwidth":5,
"lj":["id30","id31","id39"],
},
"id209":{
"p1":(5204,905),
"p2":(5460,905),
"p3":(5967,708),
"minwidth":71,
"lj":["id32","id36","id210"],
},
"id210":{
"p1":(2417,403),
"p2":(5204,905),
"p3":(5967,708),
"minwidth":292,
"lj":["id33","id118","id209"],
},
"id211":{
"p1":(5460,1063),
"p2":(5204,1063),
"p3":(5967,2275),
"minwidth":242,
"lj":["id37","id38","id39"],
},
"id212":{
"p1":(2859,2275),
"p2":(2859,2269),
"p3":(2417,2841),
"minwidth":4,
"lj":["id40","id41","id117"],
},
"id213":{
"p1":(3923,2841),
"p2":(2900,2398),
"p3":(3667,2841),
"minwidth":113,
"lj":["id43","id115","id116"],
},
"id214":{
"p1":(1,6320),
"p2":(300,3645),
"p3":(1,2878),
"minwidth":334,
"lj":["id50","id184","id190"],
},
"id215":{
"p1":(411,6557),
"p2":(-1,7200),
"p3":(3413,6364),
"minwidth":588,
"lj":["id52","id53","id192"],
},
"id216":{
"p1":(3413,6241),
"p2":(3669,6241),
"p3":(3889,5901),
"minwidth":166,
"lj":["id54","id139","id140"],
},
"id217":{
"p1":(371,3803),
"p2":(1110,4264),
"p3":(1574,3820),
"minwidth":503,
"lj":["id56","id57","id135"],
},
"id218":{
"p1":(1877,3645),
"p2":(2133,3645),
"p3":(2053,2878),
"minwidth":284,
"lj":["id58","id177","id178"],
},
"id219":{
"p1":(1577,2878),
"p2":(1877,3645),
"p3":(1833,2878),
"minwidth":266,
"lj":["id59","id176","id177"],
},
"id220":{
"p1":(9591,6364),
"p2":(6976,7190),
"p3":(10040,6364),
"minwidth":130,
"lj":["id65","id109","id221"],
},
"id221":{
"p1":(10001,5127),
"p2":(9591,6364),
"p3":(10040,6364),
"minwidth":501,
"lj":["id66","id67","id220"],
},
"id222":{
"p1":(9591,3645),
"p2":(10001,4890),
"p3":(10040,3645),
"minwidth":477,
"lj":["id68","id108","id242"],
},
"id223":{
"p1":(9591,2964),
"p2":(9591,3645),
"p3":(10040,2964),
"minwidth":419,
"lj":["id69","id197","id242"],
},
"id224":{
"p1":(8275,2964),
"p2":(9556,3645),
"p3":(8531,2964),
"minwidth":134,
"lj":["id70","id120","id121"],
},
"id225":{
"p1":(3923,2964),
"p2":(3667,2964),
"p3":(3925,3645),
"minwidth":267,
"lj":["id74","id112","id113"],
},
"id226":{
"p1":(4395,3645),
"p2":(3923,2964),
"p3":(3960,3645),
"minwidth":399,
"lj":["id75","id112","id144"],
},
"id227":{
"p1":(12375,4552),
"p2":(12581,3645),
"p3":(12164,3645),
"minwidth":454,
"lj":["id85","id104","id244"],
},
"id228":{
"p1":(12375,4703),
"p2":(12164,5346),
"p3":(12264,5300),
"minwidth":90,
"lj":["id86","id103","id229"],
},
"id229":{
"p1":(12477,4795),
"p2":(12375,4703),
"p3":(12264,5300),
"minwidth":130,
"lj":["id87","id102","id228"],
},
"id230":{
"p1":(12581,6364),
"p2":(12392,5451),
"p3":(12276,5497),
"minwidth":139,
"lj":["id89","id100","id232"],
},
"id231":{
"p1":(15300,7200),
"p2":(12581,6364),
"p3":(12164,6364),
"minwidth":120,
"lj":["id90","id98","id232"],
},
"id232":{
"p1":(12276,5497),
"p2":(12164,6364),
"p3":(12581,6364),
"minwidth":440,
"lj":["id99","id230","id231"],
},
"id233":{
"p1":(12164,2964),
"p2":(12164,3645),
"p3":(12581,2964),
"minwidth":397,
"lj":["id105","id243","id244"],
},
"id234":{
"p1":(15300,-1),
"p2":(9591,245),
"p3":(10040,245),
"minwidth":21,
"lj":["id124","id156","id207"],
},
"id235":{
"p1":(2346,245),
"p2":(-1,-1),
"p3":(2089,1695),
"minwidth":1440,
"lj":["id126","id180","id181"],
},
"id236":{
"p1":(2133,3645),
"p2":(2346,2964),
"p3":(2124,2878),
"minwidth":247,
"lj":["id128","id178","id179"],
},
"id237":{
"p1":(3889,5750),
"p2":(2133,3803),
"p3":(1702,5481),
"minwidth":1615,
"lj":["id132","id133","id191"],
},
"id238":{
"p1":(3669,6364),
"p2":(3413,6364),
"p3":(6888,7190),
"minwidth":66,
"lj":["id141","id142","id192"],
},
"id239":{
"p1":(12581,245),
"p2":(15300,-1),
"p3":(12164,245),
"minwidth":36,
"lj":["id147","id154","id241"],
},
"id240":{
"p1":(12500,310),
"p2":(12581,245),
"p3":(12403,300),
"minwidth":42,
"lj":["id148","id150","id241"],
},
"id241":{
"p1":(12164,245),
"p2":(12403,300),
"p3":(12581,245),
"minwidth":61,
"lj":["id151","id239","id240"],
},
"id242":{
"p1":(10040,3645),
"p2":(10040,2964),
"p3":(9591,3645),
"minwidth":419,
"lj":["id158","id222","id223"],
},
"id243":{
"p1":(12380,476),
"p2":(12164,2964),
"p3":(12581,2964),
"minwidth":464,
"lj":["id161","id165","id233"],
},
"id244":{
"p1":(12581,3645),
"p2":(12581,2964),
"p3":(12164,3645),
"minwidth":397,
"lj":["id168","id227","id233"],
},
"id245":{
"p1":(2053,1853),
"p2":(1577,2755),
"p3":(1833,2755),
"minwidth":253,
"lj":["id174","id175","id186"],
},
}
def get_data(id):
return data.get(id)
| Python |
#-- coding: utf-8 -*-
#import tgame_stage_config, tgame_achieve_config
import tgame_stage_config
#房间内玩家对象类
class CPlayer(object):
def __init__(self, objRoom, uid):
super(CPlayer, self).__init__()
self.objRoom = objRoom #房间对象的引用
self.iSide = -1 #玩家的唯一标识
self.hid = -1 #玩家的socket(其实客户端不知道)
self.uid = uid #玩家的uid
self.urs = "" #玩家的账号
self.ip = "" #玩家的ip
self.nickname = "" #玩家的昵称
self.gmlvl = -1 #玩家的gm等级
self.avatar = None #玩家的人物avatar信息
self.pet = None #玩家的宠物avatar信息
self.score = 0 #玩家的总积分
self.win_count = 0 #玩家的胜利局数
self.draw_count = 0 #玩家的平局局数
self.lose_count = 0 #玩家的失败局数
self.break_count = 0 #玩家的断线/逃跑局数
self.yuanbao = 0 #玩家充值人民币代币
self.yuanbao_free = 0 #玩家的获赠人民币代币
self.bIsReady = False #玩家是否准备好进行游戏
self.bIsInit = False #玩家是否发送了本局带入游戏卡片列表
self.iSelectStage = 1 #玩家自己选中的当前关卡
self.lstFinishStage = [] #玩家已经完成的关卡列表
self.lstSelectableStage = [] #玩家可选的关卡列表
self.lstFinishAchieve = [] #玩家已经完成的成就列表
#自清理函数
def clean(self):
#释放对房间对象的引用
self.objRoom = None
#客户端判断是否能够使用巫师指令的函数,目前永远返回True
def can_use_wizard(self):
return True
#加载玩家基本信息的函数
def load_base_data(self, side, urs, uid, nickname, is_ready, gmlvl,hid):
self.iSide = side
self.urs = urs
self.uid = uid
self.nickname = nickname
self.bIsReady = is_ready
self.gmlvl = gmlvl
self.hid = hid
#加载玩家具体信息的函数
def load_detail_data(self, score, win_count, lose_count, draw_count, break_count):
self.score = score
self.win_count = win_count
self.draw_count = draw_count
self.lose_count = lose_count
self.break_count = break_count
#加载玩家avatar信息的函数
def load_avatar_info(self, avatar, pet):
print "avatar = %r; pet = %r" % (avatar, pet)
self.avatar = avatar
self.pet = pet
#加载玩家隐私信息的函数(所谓隐私信息就是不会收到其他玩家的相关信息,只会收到自己的)
def load_secret_info(self, yuanbao, yuanbao_free, finish_stage, finish_achieve):
#玩家的人民币代币信息
self.yuanbao = yuanbao
self.yuanbao_free = yuanbao_free
#保存玩家已经完成关卡的信息
self.lstFinishStage = []
for obj in finish_stage:
self.lstFinishStage.append(obj.value)
#根据玩家已经完成的关卡的信息,生成玩家可选关卡的列表
self.lstSelectableStage = []
for stage, require in tgame_stage_config.STAGE_REQUIRE.iteritems():
flag = True
for rstage in require:
if not rstage in self.lstFinishStage:
flag = False
break
if flag:
self.lstSelectableStage.append(stage)
self.lstSelectableStage.sort()
#保存玩家已经完成的成就的信息
self.lstFinishAchieve = []
for obj in finish_achieve:
self.lstFinishAchieve.append(obj.value)
#返回当前游戏总成就点数的函数
def get_achieve_point(self):
total = 0
for _id in self.lstFinishAchieve:
config = tgame_achieve_config.data.get(_id)
if config:
total += config["AchieveScore"]
return total
#返回总局数的函数
def get_total_round(self):
return self.win_count + self.draw_count + self.lose_count + self.break_count
#返回胜率的函数
def get_win_percent(self):
if self.get_total_round() == 0:
return 0
else:
return 100 * self.win_count / self.get_total_round()
#改变玩家准备状态标志位的函数
def change_ready(self, is_ready):
self.bIsReady = is_ready
#进入游戏初始化状态时调用的函数
def game_init(self):
self.bIsReady = False
#结束游戏,返回游戏准备状态时调用的函数
def game_end(self, stage, rank, score):
#如果玩家当前局的胜利且当前关卡不在已经完成的关卡列表里
"""if rank == 1 and (not stage in self.lstFinishStage):
#更新已经完成的关卡列表
self.lstFinishStage.append(stage)
#已经完成的关卡列表改变了,需要重新生成可选关卡列表
self.lstSelectableStage = []
for stage, require in tgame_stage_config.STAGE_REQUIRE.iteritems():
flag = True
for rstage in require:
if not rstage in self.lstFinishStage:
flag = False
break
if flag:
self.lstSelectableStage.append(stage)
self.lstSelectableStage.sort()
"""
#玩家胜利,胜利局数+1
if rank:
self.win_count += 1
#否则就是负局数+1(游戏目前没有平局)
else:
self.lose_count += 1
#本局得分累加到总积分上
self.score = score
#此函数在收到服务端的得到某个成就的消息的时候调用,更新已经完成的成就信息
def finish_achieve(self, achieve_id):
if not achieve_id in self.lstFinishAchieve:
self.lstFinishAchieve.append(achieve_id)
| Python |
#! /usr/bin/env python
#coding=utf-8
# tgame_entity
import tgame_player
import tgame_map
import tgame_mapmgr
g_builds = {}
g_entitys = {}
g_phys = {}
g_items = {}
ET_Player = 0x01
ET_Zombie = 0x02
ET_Barrier = 0x03
ET_Other = 0x04
def init():
pass
def addentity(playerinfo, AItype = None):
import tgame_player_c
global g_entitys
entity = tgame_player.TGame_Player(playerinfo, AItype)
g_entitys[playerinfo.uid] = entity
g_phys[entity.obj.phy.id] = entity
return g_entitys[playerinfo.uid]
def delentity(uid = None,id = None):
if uid:
# 玩家死亡
if uid == tgame_mapmgr.inst.objMe.player.uid:
tgame_mapmgr.inst.playerdead()
return
id = g_entitys[uid].obj.phy.id
g_entitys[uid].destroy()
g_entitys[uid] = None
g_phys[id] = None
del g_entitys[uid]
del g_phys[id]
elif id:
uid = g_phys[id].player.uid
g_phys[id].destroy()
g_entitys[uid] = None
g_phys[id] = None
del g_entitys[uid]
del g_phys[id]
def destroy():
import copy
copyg_e = copy.copy(g_entitys)
for key in copyg_e:
id = g_entitys[key].obj.phy.id
g_entitys[key].destroy()
del g_entitys[key]
del g_phys[id]
pass
def update():
for entity in g_entitys:
g_entitys[entity].update() | Python |
#! /usr/bin/env python
#coding=utf-8
import tgame_fsm
class PlayerFSMClass(tgame_fsm.IFsmCallbackObj):
TransitionMap = {
('stand', 'onMove'):'move',
('move', 'stopMove'):'stand',
('stand', 'Fire'):'atk',
}
MapState2Look = {
'move' : 'anim_stand_clip1',
'walk' : 'anim_walk_clip1',
'run' : 'anim_run_clip1',
'float' : 'anim_float_clip1',
}
def __init__(self):
self.fsm = tgame_fsm.CFsm(TransitionMap, self)
#self.sprite = # load some super cool model2d
def OnEvent(self, event):
self.fsm.OnEvent(event)
def OnEnterState(self, state):
# 比如进入某状态就切换到对应的动画
self.sprite.change_looks(MapState2Look[state])
def OnLeaveState(self, state):
pass
def OnEvent(self, state, event):
pass
| Python |
#! /usr/bin/env python
#coding=utf-8
import math3d,math
LEFT_SIDE = 0x01
RIGHT_SIDE = 0x02
NONE_SIDE = 0x03
def angle(o, s, e):
cosfi = 0
fi = 0
norm = 0
dsx = s[0] - o[0]
dsy = s[1] - o[1]
dex = e[0] - o[0]
dey = e[1] - o[1]
cosfi = dsx * dex + dsy * dey
norm = (dsx * dsx + dsy * dsy) * (dex * dex + dey * dey)
cosfi /= math.sqrt(norm)
fi = math.acos(cosfi)
if (180 * fi / math.pi < 180):
return 180 * fi / math.pi
else:
return 360 - 180 * fi / math.pi
def angle360(o, s, e):
if postionsame(o, s) or postionsame(o, e) or postionsame(s, e):
return
rotate = angle(o, s, e)
dir = math3d.vector2(e[0], e[1]) - math3d.vector2(s[0], s[1])
dir.normalize(1)
x = 0
y = 0
if dir.x < 0:
rotate = 360 - rotate
return rotate * math.pi/180
# 两点相等
def postionsame(p0,p1):
if p0[0] == p1[0] and p0[1] == p1[1]:
return True
return False
#单位化向量
def normalize(v=[]):
if len(v) == 2:
length = lambda v: (v[0]*v[0] + v[1]*v[1] ) ** 0.5
return ( v[0] / length(v), v[1] / length(v))
else:
return 0
# 计算三点的夹角
def vector3angle(A, B, C):
x1 = A[0]-B[0]
y1 = A[1]-B[1]
x2 = C[0]-B[0]
y2 = C[1]-B[1]
x = x1*x2+y1*y2
y = x1*y2-x2*y1
#if( x> 0 )
# //角度 <90
#else
# //角度> =90
angle = math.acos(x/(x*x+y*y))
#print "vector3angle",angle
angle = math.acos(x/math.sqrt(x*x+y*y))
return angle
#两向量的夹角(渣 无用)
def vector2angle(da, db):
X1 = da[0]
X2 = db[0]
Y1 = da[1]
Y2 = db[1]
angle = (X1*X2+Y1*Y2)/(math.sqrt(X1^2+X2^2)(X2^2+Y2^2))
return angle
# 逆时针 旋转向量
def RotateVectorN(x,y,d):
p = ( x * math.cos(d) - y * math.sin(d) , x * math.sin(d) + y * math.cos(d) )
return p
# 获得角对角d距离的点(渣 无用)
def anglepoint(p1, p2, p3, d):
da = ((p2[0] - p1[0]), (p2[1] - p1[1]))
#单位化
v = [da[0], da[1]]
da = normalize(v)
# 夹角
angle = vector3angle(p1, p2, p3)
ds = da
# 旋转夹角/2,得到中间向量
dirz = RotateVectorN(ds[0], ds[1], angle/2)
# p1的反向量顶点
fp1 = (p2[0] + dirz[0] * d, p2[1] + dirz[1] * d)
return fp1
# 计算线段长度
def linelength(p0, p1):
x = math.fabs(p0[0]-p1[0])
y = math.fabs(p0[1]-p1[1])
length = math.sqrt(x*x + y*y)
return length
# 计算三角形的重心(中心点)
def traingCenter(p0, p1, p2):
x1 = p0[0]
x2 = p1[0]
x3 = p2[0]
y1 = p0[1]
y2 = p1[1]
y3 = p2[1]
pos = ((x1+x2+x3)/3,(y1+y2+y3)/3)
return pos
# 判断相交
def isOnSameSide(x0, y0, x1, y1, x2, y2, x3, y3):
a = y0 - y1
b = x1 - x0
c = x0 * y1 - x1 * y0
if (a * x2 + b * y2 + c) * (a * x3 + b * y3 + c) > 0:
return True
return False
#p是要检测的点,v0,v1,v2是三角形的三个顶点。
# 计算点是否在三角形内
def isPointInside2(p, v0, v1, v2):
if isOnSameSide(p[0] ,p[1] ,v0[0] ,v0[1] ,v1[0] ,v1[1] ,v2[0] ,v2[1]) or \
isOnSameSide(p[0] ,p[1] ,v1[0] ,v1[1] ,v2[0] ,v2[1] ,v0[0] ,v0[1]) or \
isOnSameSide(p[0] ,p[1] ,v2[0] ,v2[1] ,v0[0] ,v0[1] ,v1[0] ,v1[1]):
return False
return True
#线段求交点
def linenode(P1,P2,Q1,Q2):
P1_X = P1[0]
P2_X = P2[0]
Q1_X = Q1[0]
Q2_X = Q2[0]
P1_Y = P1[1]
P2_Y = P2[1]
Q1_Y = Q1[1]
Q2_Y = Q2[1]
tmp11 = (Q1_X - P1_X) * (Q1_Y - Q2_Y) - (Q1_Y - P1_Y) * (Q1_X - Q2_X)
tmp12 = (P2_X - P1_X) * (Q1_Y - Q2_Y) - (P2_Y - P1_Y) * (Q1_X - Q2_X)
tmp13 = (P2_X - P1_X) * (Q1_Y - P1_Y) - (P2_Y - P1_Y) * (Q1_X - P1_X)
tmp14 = (P2_X - P1_X) * (Q1_Y - Q2_Y) - (P2_Y - P1_Y) * (Q1_X - Q2_X)
u = tmp11/tmp12
v = tmp13/tmp14
node = None
#若参数值同时满足0≤u≤1,0≤v≤1,则两线段有交点
if (0 <= u and u <= 1 and 0 <= v and v <= 1):
x = P1_X + (P2_X - P1_X) * u
y = P1_Y + (P2_Y - P1_Y) * u
node = (x,y)
return node
# 顺时针 旋转向量
def RotateVector(x,y,d):
p = ( x * math.cos(-d) - y * math.sin(-d) , x * math.sin(-d) + y * math.cos(-d) )
return p
# 获得一点与边的直角距离
def traingMiniWidth(p1,p2,p3):
x = p1[0] - p2[0]
y = p1[1] - p2[1]
d = 90
# 顺时针
p = RotateVector(x, y, d)
pe = ( p3[0] + p[0] * 1000, p3[1] + p[1] * 1000)
pon = linenode(p1,p2,p3,pe)
#print "xiangjiao:",pon
length = 0
if pon:
length = linelength(pon, p3)
return length
# 两点p1(x1,y1),p2(x2,y2),判断点p(x,y)在线的左边还是右边
def LeftOfLine(p, p1, p2):
x1 = p1[0]
x2 = p2[0]
y1 = p1[1]
y2 = p2[1]
x = p[0]
y = p[1]
#tmpx = (p1[0] - p2[0]) / (p1[1] - p2[1]) * (p[1] - p2[1]) + p2[0];
Tmp = (y1 - y2) * x + (x2 - x1) * y + x1 * y2 - x2 * y1
if Tmp > 0:
return LEFT_SIDE
elif Tmp < 0:
return RIGHT_SIDE
else:
return NONE_SIDE
#if (tmpx > p[0]):#当tmpx>p.x的时候,说明点在线的左边,小于在右边,等于则在线上。
# return True
#return False
#另外一种方法:
#Tmp = (y1 – y2) * x + (x2 – x1) * y + x1 * y2 – x2 * y1
#Tmp > 0 在左侧
#Tmp = 0 在线上
#Tmp < 0 在右侧
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.