code stringlengths 1 1.49M | vector listlengths 0 7.38k | snippet listlengths 0 7.38k |
|---|---|---|
import os
import io
class TestCase(object):
pass
def calculateMatches(testCase):
firstCandidates = set(testCase.cardgrid1[testCase.row1 - 1])
secondCandidates = set(testCase.cardgrid2[testCase.row2 - 1])
return list(firstCandidates.intersection(secondCandidates))
pass
def parseInput(fileIn):
numCases = int(fileIn.readline())
testCases = [TestCase() for _ in range(numCases)]
for i, testCase in enumerate(testCases):
testCase.row1 = int(fileIn.readline())
testCase.cardgrid1 = []
for _ in range(4):
rowStr = fileIn.readline()
rowCards = str.split(rowStr)
testCase.cardgrid1.append([int(card) for card in rowCards])
testCase.row2 = int(fileIn.readline())
testCase.cardgrid2 = []
for _ in range(4):
rowStr = fileIn.readline()
rowCards = str.split(rowStr)
testCase.cardgrid2.append([int(card) for card in rowCards])
return testCases
def write_output(fileOut, caseNum, cards):
cardStr = "Volunteer cheated!"
if len(cards) == 1:
cardStr = str(cards[0])
elif len(cards) > 1:
cardStr = "Bad magician!"
fileOut.write(str.format("Case #{0}: {1}\n", caseNum, cardStr))
pass
if __name__ == "__main__":
fileIn = open("CodeJamSolutions\\Input\\magictrick.txt")
fileOut = open("CodeJamSolutions\\Output\\magictrick.txt", "w")
testCases = parseInput(fileIn)
for i, testCase in enumerate(testCases):
matches = calculateMatches(testCase)
write_output(fileOut, i+1, matches)
fileIn.close()
fileOut.close()
#Recently you went to a magic show. You were very impressed by one of the
#tricks, so you decided to try to figure out the secret behind it!
#The magician starts by arranging 16 cards in a square grid: 4 rows of
#cards, with 4 cards in each row. Each card has a different number from
#1 to 16 written on the side that is showing. Next, the magician asks a
#volunteer to choose a card, and to tell him which row that card is in.
#Finally, the magician arranges the 16 cards in a square grid again,
#possibly in a different order. Once again, he asks the volunteer which
#row her card is in. With only the answers to these two questions, the
#magician then correctly determines which card the volunteer chose.
#Amazing, right?
#You decide to write a program to help you understand the magician's
#technique. The program will be given the two arrangements of the
#cards, and the volunteer's answers to the two questions: the row
#number of the selected card in the first arrangement, and the row
#number of the selected card in the second arrangement. The rows are
#numbered 1 to 4 from top to bottom.
#Your program should determine which card the volunteer chose; or
#if there is more than one card the volunteer might have chosen
#(the magician did a bad job); or if there's no card consistent with
#the volunteer's answers (the volunteer cheated). | [
[
1,
0,
0.013,
0.013,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.026,
0.013,
0,
0.66,
0.1667,
518,
0,
1,
0,
0,
518,
0,
0
],
[
3,
0,
0.0584,
0.026,
0,
0.66,... | [
"import os",
"import io",
"class TestCase(object):\n pass",
"def calculateMatches(testCase):\n firstCandidates = set(testCase.cardgrid1[testCase.row1 - 1])\n secondCandidates = set(testCase.cardgrid2[testCase.row2 - 1])\n return list(firstCandidates.intersection(secondCandidates))\n pass",
" ... |
def matrix_to_string(M, padfunc=None):
"""Return a string representation of a matrix with each row on a new line,
and padding between columns determined by the optional padfunc argument.
If provided, padfunc must accept row and column indicies as input and produce
an int output.
"""
rowstrs = []
for i in range(len(M)):
rowstr = ""
if padfunc:
for j in range(len(M[0])):
rowstr = rowstr + repr(M[i][j]).rjust(padfunc(i,j))
else:
rowstr = repr(M[i])
rowstrs.append(rowstr)
return '\n'.join(rowstrs)
def print_matrix(M, padfunc=None):
"""Print a matrix with each row on a new line, and padding between columns
determined by the optional padfunc argument. If provided, padfunc must
accept row and column indicies as input and produce an int output.
"""
print(matrix_to_string(M, padfunc)) | [
[
2,
0,
0.3958,
0.6667,
0,
0.66,
0,
810,
0,
2,
1,
0,
0,
0,
10
],
[
8,
1,
0.2083,
0.2083,
1,
0.8,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
1,
0.3333,
0.0417,
1,
0.8,
0... | [
"def matrix_to_string(M, padfunc=None):\n \"\"\"Return a string representation of a matrix with each row on a new line, \n and padding between columns determined by the optional padfunc argument. \n If provided, padfunc must accept row and column indicies as input and produce \n an int output.\n \"\"... |
import random
def sort(toSort):
"""Sorts all of the elements in the provided list using only three stacks, and
no additional memory."""
a = []
b = []
c = toSort[:]
# This problem appears in the ACM. We must sort the elements in the given list
# using no memory other than the three stacks, and at each step, we can only
# inspect the top element of each stack and respond by moving a single card from
# one stack to another. We make use of an "alarm" that triggers when all of the
# elements appear in sorted order in the first stack. This alarm is not subject
# to the same constraints.
while not isFinished(a,b,c):
if len(a) == 0 or (len(b) == 0 or b[-1] < a[-1]) and (len(c) == 0 or c[-1] < a[-1]):
# both b and c are < a, so move the greater of the two to a
if len(b) == 0 or (len(c) != 0 and c[-1] > b[-1]):
a.append(c.pop())
else:
a.append(b.pop())
else:
# one of b and c is greater than a. move a on top of the lower of the two
if len(b) == 0 or (len(c) != 0 and c[-1] > b[-1]):
b.append(a.pop())
else:
c.append(a.pop())
return a
def sort_harder(toSort):
"""Sorts all of the elements in the provided list using only two stacks, a single
int variable, and no additional memory."""
a = []
b = []
c = toSort[:]
# This version of the problem has the same constraints, except that the stack 'b'
# may only contain a single element at a time (in other words it's just an nullable int)
# Interestingly, this additional constraint forces an even more elegant solution.
# We take the same approach of maintaining 'a' in decending sorted order. Whenever
# we see an element at the top of 'c' that's greater than the top element of 'a',
# we stash it in 'b' and move elements from 'a' to 'c' until it is less than the element
# at the top of 'a' or 'a' is empty. At this point we will have found the correct position
# in 'a' for that element in 'b', and it get's moved to 'a'.
while not isFinished(a,b,c):
if len(b) > 0:
if len(a) == 0 or b[-1] < a[-1]:
a.append(b.pop())
else:
c.append(a.pop())
elif len(a) == 0 or c[-1] < a[-1]:
a.append(c.pop())
else:
b.append(c.pop())
return a
def isFinished(a,b,c):
if (len(b) > 0 or len(c) > 0):
return False
for i in range(len(a) - 1):
if a[i] < a[i+1]:
return false
return True
if __name__ == "__main__":
toSort = random.sample(range(1000), 20)
print(toSort)
print(sort(toSort))
print(sort_harder(toSort)) | [
[
1,
0,
0.0128,
0.0128,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
2,
0,
0.2244,
0.3846,
0,
0.66,
0.25,
489,
0,
1,
1,
0,
0,
0,
16
],
[
8,
1,
0.0577,
0.0256,
1,
0.7... | [
"import random",
"def sort(toSort):\n \"\"\"Sorts all of the elements in the provided list using only three stacks, and \n no additional memory.\"\"\"\n\n a = []\n b = []\n c = toSort[:]",
" \"\"\"Sorts all of the elements in the provided list using only three stacks, and \n no additional m... |
import sys
import testutils
def lis(input):
"""Find and return the longest increasing subsequence (LIS) in the given
list
Note: This algorithm demonstrates the use of dynamic programming. There is,
however, a more efficient solution to the LIS problem. See:
http://en.wikipedia.org/wiki/Longest_increasing_subsequence"""
# pad the list with a -infinity at the beginning
l = [-sys.maxsize - 1] + input
n = len(l)
# Allocate an n by n matrix of lists to store results. The i,jth element
# of M will store the longest incresing subsequence in l[i:], such that
# every element of the subsequence is greater than l[j]. Padding the
# beginning of the list with -infinity is a convenient way to avoid extra
# processing at the end of this process.
# Note that only two rows of this matrix are in use at any point, so if
# we wanted to be more space efficient we could store only two lists.
M = [[[] for i in range(len(l))] for i in range(len(l))]
for j in range(n):
if l[j] < l[n-1]:
M[n-1][j] = [l[n-1]]
else:
M[n-1][j] = []
for i in range(n-2, -1, -1):
for j in range(i+1):
if l[i] <= l[j]:
M[i][j] = M[i+1][j]
else:
candidate1 = M[i+1][j]
candidate2 = M[i+1][i]
if len(candidate1) > len(candidate2) + 1:
M[i][j] = candidate1
else:
M[i][j] = [l[i]] + candidate2
#testutils.print_matrix(M)
return M[0][0]
if __name__ == '__main__':
seq = []
if len(sys.argv) > 1:
for item in sys.argv[1:]:
seq.append(int(item))
else:
seq = [6,4,12,6,2,8,9,7,14]
print("for example, on input:")
print(seq)
print("lis returns:")
print(lis(seq)) | [
[
1,
0,
0.0179,
0.0179,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0357,
0.0179,
0,
0.66,
0.3333,
536,
0,
1,
0,
0,
536,
0,
0
],
[
2,
0,
0.4196,
0.7143,
0,
... | [
"import sys",
"import testutils",
"def lis(input):\n \"\"\"Find and return the longest increasing subsequence (LIS) in the given\n list\n Note: This algorithm demonstrates the use of dynamic programming. There is,\n however, a more efficient solution to the LIS problem. See:\n http://en.wikipedia... |
class LinkedList(object):
"""description of class"""
class LinkedListNode(object):
def __init__(self, value):
self.next = None
self.value = value
def __init__(self):
self.head = None
def add(self, value):
newNode = LinkedList.LinkedListNode(value)
if self.head is not None:
newNode.next = self.head
self.head = newNode
def reverse(self):
"""Reverses this linked list so that self.head points to what used to be
the tail and the order of the elements is reversed."""
prev = None
cur = self.head
while cur is not None:
next = cur.next
cur.next = prev
prev = cur
cur = next
self.head = prev
def print_list(self):
cur = self.head
while cur is not None:
print(cur.value, end=',')
cur = cur.next
print() #newline
if __name__ == '__main__':
myLinkedList = LinkedList()
myLinkedList.add(1)
myLinkedList.add(2)
myLinkedList.add(3)
myLinkedList.add(4)
myLinkedList.add(5)
myLinkedList.add(6)
myLinkedList.print_list()
myLinkedList.reverse()
myLinkedList.print_list()
| [
[
3,
0,
0.3571,
0.6964,
0,
0.66,
0,
353,
0,
5,
0,
0,
186,
0,
3
],
[
8,
1,
0.0357,
0.0179,
1,
0.47,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
3,
1,
0.0982,
0.0714,
1,
0.47,
... | [
"class LinkedList(object):\n \"\"\"description of class\"\"\"\n\n class LinkedListNode(object):\n def __init__(self, value):\n self.next = None\n self.value = value",
" \"\"\"description of class\"\"\"",
" class LinkedListNode(object):\n def __init__(self, value):... |
def count_substring_matches(s, w):
i = j = 0
matches = 0
while i <= len(s) - len(w) or j > 0:
if j == len(w):
matches += 1
i -= (j - 1)
j = 0
else:
if s[i] == w[j]:
i += 1
j += 1
else:
i -= (j - 1)
j = 0
return matches
def fast_count_substring_matches(s, w, t):
i = j = 0
matches = 0
while True:
if j == len(w):
# check for match
matches += 1
j = t[j-1]
if i == len(s):
# reached the end
return matches
if s[i] == w[j]:
# so far so good, on to the next one
i += 1
j += 1
else:
# no match, backtrack in w if we're not at the beginning
# already, else advance in s.
if j == 0:
i += 1
else:
j = t[j-1]
def compute_backtrack_array(w):
t = [0 for _ in range(len(w))]
t[0] = 0
for i in range(1, len(t)):
backtrack = t[i-1]
while True:
if w[backtrack] == w[i]:
t[i] = backtrack + 1
break
elif backtrack == 0:
break
else:
backtrack = t[backtrack]
return t
if __name__ == "__main__":
s = "ABCBBBAAABCABABCABCCACCCAABBCABCC"
w = "CC"
print(count_substring_matches(s, w))
s = "abababcabacababcababab"
w = "ababcabab"
t = compute_backtrack_array(w)
print(t)
print(fast_count_substring_matches(s,w,t)) | [
[
2,
0,
0.1389,
0.2361,
0,
0.66,
0,
193,
0,
2,
1,
0,
0,
0,
3
],
[
14,
1,
0.0417,
0.0139,
1,
0.88,
0,
826,
1,
0,
0,
0,
0,
1,
0
],
[
14,
1,
0.0556,
0.0139,
1,
0.88,
... | [
"def count_substring_matches(s, w):\n i = j = 0\n matches = 0\n while i <= len(s) - len(w) or j > 0:\n if j == len(w):\n matches += 1\n i -= (j - 1)\n j = 0",
" i = j = 0",
" matches = 0",
" while i <= len(s) - len(w) or j > 0:\n if j == len(w):... |
import random
class Subarray:
def __init__(self):
self.start = 0 # inclusive
self.end = 0 # exclusive
self.val = 0
def highest_value_subarray(arr):
best = Subarray()
bestWithK = Subarray()
if len(arr) == 0:
return best
# init base case
if arr[0] > 0:
best.end = 1
best.val = arr[0]
bestWithK.end = 1
bestWithK.val = arr[0]
# after each iteration, best will contain the highest-value
# subarray using elements from 0 to k inclusive, and bestWithK
# will contain the highest-vlue subbarray that contains the kth
# element and uses elements from 0 to k inclusive.
for k in range(1, len(arr)):
bestWithK.end = k + 1
if bestWithK.val > 0:
bestWithK.val += arr[k]
else:
bestWithK.start = k
bestWithK.val = arr[k]
if bestWithK.val > best.val:
best.start = bestWithK.start
best.end = bestWithK.end
best.val = bestWithK.val
return best
if __name__ == "__main__":
l = random.sample(set(range(-100,100)), 20)
print(l)
print("highest-value subarray:")
best = highest_value_subarray(l)
print(l[best.start : best.end])
print("value:")
print(str(best.val))
| [
[
1,
0,
0.0196,
0.0196,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
3,
0,
0.098,
0.098,
0,
0.66,
0.3333,
186,
0,
1,
0,
0,
0,
0,
0
],
[
2,
1,
0.1078,
0.0784,
1,
0.71... | [
"import random",
"class Subarray:\n def __init__(self):\n self.start = 0 # inclusive\n self.end = 0 # exclusive\n self.val = 0",
" def __init__(self):\n self.start = 0 # inclusive\n self.end = 0 # exclusive\n self.val = 0",
" self.start = 0 # inc... |
import sys
#This file used for testing ideas
#clearly some dynamic programming is required. is it enough to track the lis
# up to the current point in the list then for the current element, add it to
# each subsequence for which it is greater than the last element? No, because
# it may be best for the lis to exclude a large element so that smaller elements
# later in the list can be included.
# Possible approaches:
# 1. Divide the list into two parts. Compute all increasing subsequences on each
# then try every combination. A list with n elements may have 2^n different
# like a poor choice (merging two 2^n candidate lists => exponential time,
# obviously)
# 2. The above approach illustrates the fundamental problem here. If we start at
# the beginning of the list, and for each subsequent element, choose whether
# or not to include it in each subsequence we have constructed so far, there
# are 2^n possible choices. So we need to find a way to eliminate whole
# sequences and exclude them from future consideration. What if we compute
# for each i,j, the lis including only elements between i and j (inclusive).
# Start by filling in the diagonal where i=j. then move to the next diagonal
# over and compute j = i+1. Each element can be computed by considering all
# of the longest increasing subsequences for the O(n^2) subranges, and adding
# the current element if possible. Total running time would be O(n^3)
def lis(list):
M = [[] for i in range(len(list))]
for i in range(len(list)):
M[i][i] = [list[i]]
for offset in range(1, len(list)):
for i in range(len(list) - offset):
j = i+offset
# compute M[i][i+offset]
bestCandidate = [0]
bestCandidateLen = 0
for innerOffset in range(offset-1):
for ii in range(i, 1 + offset - innerOffset):
jj = ii + innerOffset
candidate = M[ii][jj]
candidateLen = len(candidate)
if list[j] > candidate[-1]:
candidate
if __name__ == '__main__':
seq = []
if len(sys.argv) > 1:
for item in sys.argv[1:]:
seq.append(int(item))
else:
seq = [4,12,6,2,8,9,7,14]
print("for example, on input:")
print(seq)
print("lis returns:")
print(lis(seq)) | [
[
1,
0,
0.0169,
0.0169,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
2,
0,
0.5763,
0.322,
0,
0.66,
0.5,
96,
0,
1,
0,
0,
0,
0,
11
],
[
14,
1,
0.4407,
0.0169,
1,
0.57,... | [
"import sys",
"def lis(list):\n M = [[] for i in range(len(list))]\n\n for i in range(len(list)):\n M[i][i] = [list[i]]\n\n for offset in range(1, len(list)):\n for i in range(len(list) - offset):",
" M = [[] for i in range(len(list))]",
" for i in range(len(list)):\n M[i][... |
import random
def _randomize(l):
for i in range(len(l)):
toSwap = random.randrange(i, len(l))
l[i], l[toSwap] = l[toSwap], l[i]
return l
if __name__ == "__main__":
sortedArray = list(range(100))
for _ in range(10):
print(_randomize(sortedArray)); | [
[
1,
0,
0.0714,
0.0714,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
2,
0,
0.3571,
0.3571,
0,
0.66,
0.5,
787,
0,
1,
1,
0,
0,
0,
4
],
[
6,
1,
0.3571,
0.2143,
1,
0.29,... | [
"import random",
"def _randomize(l):\n for i in range(len(l)):\n toSwap = random.randrange(i, len(l))\n l[i], l[toSwap] = l[toSwap], l[i]\n return l",
" for i in range(len(l)):\n toSwap = random.randrange(i, len(l))\n l[i], l[toSwap] = l[toSwap], l[i]",
" toSwap = r... |
import sys
import random
def find_rank_in_union(A, B, k):
"""Given two ordered lists A and B, find the value of the element with rank
k in the ordered set A U B"""
# Error Cases
if len(A) + len(B) < k:
print("The given rank was larger than the rank of the set A U B")
return -1
if k < 1:
print("The given rank must be a positive integer")
return -1
# Base Cases
if not A:
return B[k-1]
elif not B:
return A[k-1]
# Recursive Cases
if B[len(B)/2] < A[len(A)/2]:
# swap so that A is the list with lesser mid element
A, B = B, A
imidA = len(A)/2
imidB = len(B)/2
rank_barier = imidA + imidB + 1
if k > rank_barier:
return find_rank(A[(imidA+1):], B, k - (imidA+1))
else:
return find_rank(A, B[:imidB], k) | [
[
1,
0,
0.0294,
0.0294,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0588,
0.0294,
0,
0.66,
0.5,
715,
0,
1,
0,
0,
715,
0,
0
],
[
2,
0,
0.5588,
0.9118,
0,
0.6... | [
"import sys",
"import random",
"def find_rank_in_union(A, B, k):\n \"\"\"Given two ordered lists A and B, find the value of the element with rank\n k in the ordered set A U B\"\"\"\n \n # Error Cases\n if len(A) + len(B) < k:\n print(\"The given rank was larger than the rank of the set ... |
import random
import itertools
def quicksort(input):
"""Performs an in-place quicksort."""
if len(input) <= 1:
return input
leftPivot, rightPivot = partition(input)
quicksort(itertools.islice(input, 0, leftPivot))
quicksort(itertools.islice(input, rightPivot+1, len(input)))
return input
def partition(input):
pivotVal = input[0]
leftPivot = rightPivot = 0
left = 0
right = len(input) - 1
# we're maintaining the list in the format
# [ only items < pivotVal ... only items = pivotVal ... unsorted items]
while input[right] > pivotVal:
right -= 1
while left < leftPivot or right > rightPivot:
if input[left] > pivotVal and input[right] < pivotVal:
_swap(input,left,right)
elif input[left] == pivotVal and input[right] < pivotVal:
_swap(input, left, right)
_swap(input, rightPivot + 1, right)
leftPivot += 1
rightPivot += 1
elif input[left] > pivotVal and input[right] == pivotVal:
_swap(input, left, right)
_swap(input, left, leftPivot - 1)
leftPivot -= 1
elif input[left] == pivotVal and input[right] == pivotVal:
_swap(input, right, rightPivot + 1)
rightPivot += 1
while input[left] < pivotVal:
left += 1
while input[right] > pivotVal:
right -= 1
return leftPivot, rightPivot
def _swap(list, i, j):
tmp = list[i]
list[i] = list[j]
list[j] = tmp
if __name__ == "__main__":
randList = [random.randrange(0,1000) for _ in range(1000)]
print(randList)
print()
print(quicksort(randList))
| [
[
1,
0,
0.0164,
0.0164,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0328,
0.0164,
0,
0.66,
0.2,
808,
0,
1,
0,
0,
808,
0,
0
],
[
2,
0,
0.123,
0.1311,
0,
0.66... | [
"import random",
"import itertools",
"def quicksort(input):\n \"\"\"Performs an in-place quicksort.\"\"\"\n if len(input) <= 1:\n return input\n leftPivot, rightPivot = partition(input)\n quicksort(itertools.islice(input, 0, leftPivot))\n quicksort(itertools.islice(input, rightPivot+1, len... |
import sys
import functools
import itertools
import random
import heap
__all__ = ['Graph', 'Edge', 'Node', 'topological_sort', 'post_order_sort', 'get_reachable', 'strongly_connected_components', 'shortest_path', 'generate_rand_edges']
@functools.total_ordering
class Node:
def __init__(self, key, value=None):
self._key = key
self._value = value
def set_value(self, value):
self._value = value
def value(self):
return self._value
def key(self):
return self._key
def __str__(self):
valueStr = ""
if self._value is not None:
valueStr = ": " + str(self._value)
return str(self._key) + valueStr
def __repr__(self):
if self._value is None:
return "Node({})".format(self._key)
else:
return "Node({}, {})".format(self._key, self._value)
def __eq__(self, other):
return self._key == other.key()
def __lt__(self, other):
return self._key < other.key()
def __hash__(self):
return self._key.__hash__()
class Edge:
def __init__(self, endpoint1: Node, endpoint2: Node, isDirected: bool, value=None):
self._value = value
self._endpoint1 = endpoint1
self._endpoint2 = endpoint2
self._isDirected = isDirected
def is_directed(self):
return self._isDirected
def set_value(self, value):
self._value = value
def value(self):
return self._value
def endpoints(self):
return (self._endpoint1, self._endpoint2)
def __str__(self):
valueStr = ""
if self._value is not None:
valueStr = ": " + str(self._value)
if self._isDirected:
return "({} --> {}){}".format(str(self._endpoint1), str(self._endpoint2), valueStr)
else:
return "({} -- {}){}".format(str(self._endpoint1), str(self._endpoint2), valueStr)
def __eq__(self, other):
otherEndpoint1, otherEndpoint2 = other.endpoints()
if self._endpoint1 == otherEndpoint1 and self._endpoint2 == otherEndpoint2:
return True
elif self._isDirected and self._endpoint1 == otherEndpoint2 and self._endpoint2 == otherEndpoint1:
return True
return False
def __hash__(self):
return hash(self._endpoint1.__hash__() + self._endpoint2.__hash__())
class Graph(object):
"""A graph consisting of a set of nodes and a set of edges. Each
node and each edge may have an associated value, which may be
updated. The graph may be directed or undirected.
"""
def __init__(self, nodes, edges):
"""Graph initializer. Builds a graph from a set of nodes and edges."""
if len(edges) > 0:
self._isDirected = next(iter(edges)).is_directed()
for e in edges:
if e.is_directed() != self._isDirected:
raise Exception("edge types are inconsistent")
self._nodes = nodes
self._edges = edges
self._initAdjacencyList()
def _initAdjacencyList(self):
self._adjacencyList = {node: set() for node in self._nodes}
for edge in self._edges:
endpoint1, endpoint2 = edge.endpoints()
self._adjacencyList[endpoint1].add(edge)
if not self._isDirected:
self._adjacencyList[endpoint2].add(edge)
def is_directed(self):
return len(self._edges) == 0 or self._isDirected
def nodes(self):
"""Returns an iterable over the nodes of the graph."""
return (n for n in self._nodes);
def edges(self):
"""Returns an iterable over the edges of the graph."""
return (e for e in self._edges)
def edges(self, source: Node):
"""Returns an iterable over all of the set of dest nodes
{dest | (source, dest) exists in self._edges}
"""
return (e for e in self._adjacencyList[source])
def reverse(self):
"""Returns a graph with all edges reversed in direction,
or simply returns this graph if it is not a directed graph.
"""
if not self.is_directed() : return self
return (Graph(self._nodes,
[Edge(e.endpoints()[1], e.endpoints()[0], True, e.value()) for e in self._edges]))
def __str__(self):
nodeStr = '\n'.join((str(node) for node in self._nodes))
edgeStr = '\n'.join(
("+++ From {} +++\n{}".format(
str(node),
'\n'.join(str(edge) for edge in self.edges(node)))
for node in self._nodes))
return "{}\n{}\n{}\n{}".format("-----Nodes-----", nodeStr, "-----Edges-----", edgeStr)
def has_cycle(g: Graph):
"""Returns True if the specified graph has a cycle, or False otherwise."""
result = False
counter = [0]
for node in g.nodes():
node.x_entered = None
node.x_exited = None
def detectCycle(source: Node):
foundCycle = False
if source.x_exited is not None:
return False
if source.x_entered is not None:
return True
source.x_entered = counter[0]
counter[0] += 1
edgesFromSource = g.edges(source)
for edgeFromSource in edgesFromSource:
_, dest = edgeFromSource.endpoints()
if detectCycle(dest):
foundCycle = True
break
source.x_exited = counter[0]
counter[0] += 1
return foundCycle
for node in g.nodes():
if detectCycle(node):
result = True
break
for node in g.nodes():
del node.x_entered
del node.x_exited
return result
def topological_sort(g: Graph):
"""Returns a list of the nodes in the specified graph in topological
sort order. If no topological sort is possible, raises an Exception.
"""
if not g.is_directed:
raise Exception("Cannot topologically sort an undirected graph")
if has_cycle(g):
raise Exception("Cannot topologically sort a graph with a cycle")
sortedNodes = post_order_sort(g)
sortedNodes.reverse()
return sortedNodes
def post_order_sort(g: Graph):
"""Returns a list of the nodes in the specified graph in the order
that they are post processed by a depth-first-search."""
sortedNodes = []
for node in g.nodes():
sortedNodes += _explore(g, node, False)
for node in sortedNodes:
del node.x_visited
return sortedNodes
def get_reachable(g: Graph, source: Node):
"""Returns a list of the nodes in the given graph that are reachable from the
given source node, in the order that they are post-processed by depth-first
search.
"""
return _explore(g, source)
def _explore(g: Graph, source: Node, doClearReachableFlag: bool = True):
"""Helper function that returns a list of nodes in g reachable from source,
in order that they are post-processed by depth-first search.
"""
reachableNodes = []
if not hasattr(source, 'x_visited'):
source.x_visited = True
edgesFromSource = g.edges(source)
for edgeFromSource in edgesFromSource:
_, dest = edgeFromSource.endpoints()
_explore(g, dest, False)
reachableNodes.append(source)
if doClearReachableFlag:
for node in reachableNodes:
del node.x_visited
return reachableNodes
def strongly_connected_components(g: Graph):
"""Returns a DAG, where each node is a strongly connected component in g."""
# Performing a depth-first search on a given source node is guaranteed to
# discover all nodes in the source node's strongly component, but unless
# it is in a sink strongly connected component (one that has no path to
# another strongly connected component) the DFS will also reveal nodes that
# aren't in it's SCC. Our algorithm therefore looks like this:
# Let G' be the subgraph consisting soley of nodes whose SCC has not been
# identified.
# while G' is not empty
# find a node s in a sink SCC in G'
# perform a dfs on s, and add s and all of the nodes reachable from s
# to a new SCC.
# remove those nodes from G'
#
# To assist in finding nodes in snk SCCs, we first perform a DFS on the
# reversed graph G_r and record the post numbers for each node. The node
# in G' with the highest of these post numbers is guaranteed to be in a
# sink SCC.
if not g.is_directed():
raise Exception("Strongly connected components are only applicable to directed graphs.")
stronglyConnectedComponents = []
sccConnections = set()
sinkOrderedNodes = post_order_sort(g.reverse())
sinkOrderedNodes.reverse()
for source in sinkOrderedNodes:
reachableNodes = _explore(g, source, False)
if len(reachableNodes) > 0:
scc = Node(len(stronglyConnectedComponents), reachableNodes)
for node in reachableNodes:
node.x_scc = scc
stronglyConnectedComponents.append(scc)
# Now build the DAG by recording the connections between various SCCs
for node in g.nodes():
scc = node.x_scc
connectedNodes = g.edges(node)
for connectedNode in connectedNodes:
connectedScc = connectedNode.x_scc
sccConnections.add(Edge(scc, connectedScc, True))
for node in g.nodes():
del node.x_visited
del node.x_scc
return Graph(stronglyConnectedComponents, sccConnections)
def shortest_path(g: Graph, source: Node):
"""Returns a dict mapping the length of the shortest path from
the specified source node to each node reachable from that source node.
"""
distances = {}
# we want a min priority queue
q = heap.PriorityQueueInverter(heap.PriorityQueue())
q.insert(source, 0)
while len(q) > 0:
node, dist = q.pop()
if node in distances.keys():
continue
distances[node] = dist
nextEdges = g.edges(node)
for nextEdge in nextEdges:
_ , nextNode = nextEdge.endpoints()
if nextNode in distances.keys():
continue
edgeLen = nextEdge.value()
nextDist = dist + edgeLen
# note: nextNode may already be in the queue. Rather than check
# for this condition and call decrease_key, which would require
# a special heap implementation, we'll simply insert the node
# again with it's new value. The node may end up being inserted
# once per incoming edge, but the instance that is popped first
# will represent the shortest path, and will be the one recorded
# in the distances dict
q.insert(nextNode, nextDist)
return distances
def generate_rand_edges(nodes, isDirected: bool, minValue: int = None, maxValue: int = None):
valueIter = None
if minValue is None or maxValue is None:
valueIter = (None for _ in range(sys.maxsize))
else:
valueIter = (random.randrange(minValue, maxValue+1) for _ in range(sys.maxsize))
edges = set([])
for i, node in enumerate(nodes):
sampleSpace = list(range(i)) + list(range(i+1, len(nodes)))
numSamples = random.randrange(0, len(nodes))
for dest in random.sample(sampleSpace, numSamples):
edges.add(Edge(node, nodes[dest], isDirected, valueIter.__next__()))
return edges
if __name__ == "__main__":
isDirected = True;
nodes = [Node(i) for i in range(2)]
edges = generate_rand_edges(nodes, isDirected, 0, 100)
g = Graph(nodes, edges)
print(g)
distances = shortest_path(g, nodes[0])
print()
print(distances)
print()
g_r = g.reverse()
print(g_r)
print(has_cycle(g))
print()
print(strongly_connected_components(g))
| [
[
1,
0,
0.0027,
0.0027,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0055,
0.0027,
0,
0.66,
0.0588,
711,
0,
1,
0,
0,
711,
0,
0
],
[
1,
0,
0.0082,
0.0027,
0,
... | [
"import sys",
"import functools",
"import itertools",
"import random",
"import heap",
"__all__ = ['Graph', 'Edge', 'Node', 'topological_sort', 'post_order_sort', 'get_reachable', 'strongly_connected_components', 'shortest_path', 'generate_rand_edges']",
"class Node:\n\n def __init__(self, key, value=... |
import random
import testutils
import bestsubarray
class Submatrix:
def __init__(self, mat):
self.mat = mat
self.start_row = 0 # inclusive
self.start_col = 0
self.end_row = 0 # exclusive
self.end_col = 0
self.val = 0
def get_copy(self):
return [row[self.start_col : self.end_col] for row in self.mat[self.start_row : self.end_row]]
def __str__(self):
return testutils.matrix_to_string(self.get_copy())
def __repr__(self):
return repr(self.get_copy())
def highest_value_submatrix_brute_force(mat):
"""Given a matrix of integers, finds the submatrix with the largest
sum of element values. This brute force algorithm simply calculates the
sum value of every possible submatrix and takes the largest one. The
running time is O(N^3 * M^3), where N and M are the dimensions of the
matrix.
"""
numrows = len(mat)
if numrows == 0:
return [[]]
numcols = len(mat[0])
if numcols == 0:
return [[]]
best = Submatrix(mat)
for start_row in range(numrows):
for start_col in range(numcols):
for end_row in range(start_row, numrows):
for end_col in range(start_col, numcols):
val = _sum_matrix(mat, start_row, end_row, start_col, end_col)
if val > best.val:
best.val = val
best.start_row = start_row
best.end_row = end_row + 1
best.start_col = start_col
best.end_col = end_col + 1
return best
def highest_value_submatrix(mat):
"""Given a matrix of integers, finds the submatrix with the largest
sum of element values. This optimized algorithm has complexity
O(min(M,N)^2 * max(M,N)), where M and N are the dimensions of the matrix.
"""
is_transverse = False
numrows = len(mat)
if numrows == 0:
return [[]]
numcols = len(mat[0])
if numcols == 0:
return [[]]
is_transverse = False
if numrows > numcols:
# Since the algorithm is O(numrows^2 * numcols), we want to make sure
# numrows < numcols.
is_transverse = True
mat = list(zip(*mat))
numrows, numcols = numcols, numrows
best = Submatrix(mat)
for start_row in range(numrows):
colsums = [0 for _ in range(numcols)]
for end_row in range(start_row, numrows):
for i in range(numcols):
colsums[i] += mat[end_row][i]
best_arr = bestsubarray.highest_value_subarray(colsums)
if best_arr.val > best.val:
best.val = best_arr.val
best.start_row = start_row
best.end_row = end_row + 1
best.start_col = best_arr.start
best.end_col = best_arr.end
if is_transverse:
mat = list(zip(*mat))
transverse_best = best
best = Submatrix(mat)
best.val = transverse_best.val
best.start_row = transverse_best.start_col
best.end_row = transverse_best.end_col
best.start_col = transverse_best.start_row
best.end_col = transverse_best.end_row
return best
def _sum_matrix(mat, i_bl, i_tr, j_bl, j_tr):
if len(mat) == 0:
return 0
return sum((sum(row[j_bl : j_tr + 1]) for row in mat[i_bl : i_tr + 1]))
if __name__ == "__main__":
numrows = 10
numcols = 12
domain = list(range(-1000,1000))
mat = []
for _ in range(numrows):
mat.append(random.sample(domain, numcols))
testutils.print_matrix(mat)
# compute the highest value submatrix using both algorithms. The
# results should be identical.
print()
print(highest_value_submatrix_brute_force(mat))
print()
print(highest_value_submatrix(mat)) | [
[
1,
0,
0.0082,
0.0082,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0164,
0.0082,
0,
0.66,
0.1429,
536,
0,
1,
0,
0,
536,
0,
0
],
[
1,
0,
0.0246,
0.0082,
0,
... | [
"import random",
"import testutils",
"import bestsubarray",
"class Submatrix:\n def __init__(self, mat):\n self.mat = mat\n self.start_row = 0 # inclusive\n self.start_col = 0\n self.end_row = 0 # exclusive\n self.end_col = 0\n self.val = 0",
" def __init__(se... |
import sys
__all__ = ['Heap', 'PriorityQueue']
class NodeHeap(object):
"""An ordered set optimized for finding the greatest value element.
This is a binary max heap."""
class heapNode(object):
def __init__(self, value):
self.parent = None
self.left = None
self.right = None
self.value = value
def __init__(self):
self.root = None
self.last = None
def find_max(self):
return self.root.value
def pop_max(self):
toReturn = self.root
newRoot = self.last
self._delete_last()
newRoot.left = self.root.left
newRoot.right = self.root.right
newRoot.parent = None
if self.root.left is not None:
self.root.left.parent = newRoot
if self.root.right is not None:
self.root.right.parent = newRoot
self.root = newRoot
self._bubble_down(self.root)
return toReturn.value
def insert(self, value):
node = NodeHeap.heapNode(value)
if self.root is None:
self.root = node
self.last = node
return
parent = self._find_next_open()
node.parent = parent
if parent.left is None:
parent.left = node
else:
parent.right = node
self.last = node
self._bubble_up(node)
def _bubble_up(self, node):
while node.parent is not None and node.parent.value < node.value:
if node == self.last:
self.last = node.parent
if node.parent == self.root:
self.root = node
parent = node.parent
grandparent = parent.parent
parent.parent = node
node.parent = grandparent
if node.left is not None:
node.left.parent = parent
if node.right is not None:
node.right.parent = parent
if parent.right == node:
parentLeft = parent.left
parent.left = node.left
parent.right = node.right
node.left = parentLeft
node.right = parent
if parentLeft is not None:
parentLeft.parent = node
else:
parentRight = parent.right
parent.left = node.left
parent.right = node.right
node.left = parent
node.right = parentRight
if parentRight is not None:
parentRight.parent = node
if grandparent is not None:
if grandparent.right == parent:
grandparent.right = node
else:
grandparent.left = node
def _bubble_down(self, node):
swapNode = None
while node.left is not None or node.right is not None:
if node.left is None or (node.right is not None and node.right.value > node.left.value):
swapNode = node.right
else:
swapNode = node.left
if node.value > swapNode.value:
break
else:
self._bubble_up(swapNode)
def _find_next_open(self):
node = self.last
while node.parent is not None and node.parent.right == node:
node = node.parent
if node.parent is None:
# tree is full. add to the bottom left
while node.left is not None:
node = node.left
else:
# since the tree is always filled from left to right, if we started
# at the rightmost node on the bottom level and we've found that we
# were on the left side of a subtree, there must be space on the bottom
# level of the corresponding right subtree
node = node.parent
if node.right is not None:
node = node.right
while node.left is not None:
node = node.left
return node
def _delete_last(self):
node = self.last
while node.parent is not None and node.parent.left == node:
node = node.parent
if node.parent is None:
# last was the first node on its level. new last is the node
# on the far right
while node.right is not None:
node = node.right
else:
node = node.parent.left
while node.right is not None:
node = node.right
# remove from the tree
if self.last.parent is not None:
if self.last.parent.left == self.last:
self.last.parent.left = None
else:
self.last.parent.right = None
# save new last node
self.last = node
class Heap:
"""An ordered set optimized for finding the greatest value element.
This is a binary max heap."""
def __init__(self):
self._arr = []
def find_max(self):
if len(self._arr) > 0:
return self._arr[0]
else:
return None
def pop(self):
if len(self._arr) == 0:
return None
toReturn = self._arr[0]
self._arr[0] = self._arr[-1]
del self._arr[-1]
if len(self._arr) > 0:
self._bubble_down(0)
return toReturn
def insert(self, value):
self._arr.append(value)
self._bubble_up(len(self._arr) - 1)
def _bubble_down(self, index):
val = self._arr[index]
iLeft, left = self._get_left(index)
iRight, right = self._get_right(index)
while ((left is not None and val < left) or (right is not None and val < right)):
if right is None or left > right:
self._arr[iLeft], self._arr[index] = self._arr[index], self._arr[iLeft]
index = iLeft
elif left is None or right >= left:
self._arr[iRight], self._arr[index] = self._arr[index], self._arr[iRight]
index = iRight
iLeft, left = self._get_left(index)
iRight, right = self._get_right(index)
return index
def _bubble_up(self, index):
val = self._arr[index]
iParent, parent = self._get_parent(index)
while (parent is not None and val > parent):
self._arr[index], self._arr[iParent] = self._arr[iParent], self._arr[index]
index = iParent
iParent, parent = self._get_parent(index)
return index
def _get_parent_index(self, childIndex):
return ((childIndex + 1) // 2) - 1
def _get_left_index(self, parentIndex):
return parentIndex * 2 + 1
def _get_right_index(self, parentIndex):
return parentIndex * 2 + 2
def _get_parent(self, index):
if index == 0:
return (None, None)
iParent = self._get_parent_index(index)
return iParent, self._arr[iParent]
def _get_left(self, parentIndex):
iLeft = self._get_left_index(parentIndex)
if iLeft < len(self._arr):
return iLeft, self._arr[iLeft]
else:
return (None, None)
def _get_right(self, parentIndex):
iRight = self._get_right_index(parentIndex)
if iRight < len(self._arr):
return iRight, self._arr[iRight]
else:
return (None, None)
def __len__(self):
return len(self._arr)
class PriorityQueue:
"""A max priority queue"""
def __init__(self):
self._heap = Heap()
def pop(self):
priority, key = self._heap.pop()
return (key, priority)
def peek(self):
priority, key = self._heap.find_max()
return (key, priority)
def insert(self, key, priority):
self._heap.insert((priority, key))
def __len__(self):
return len(self._heap)
class PriorityQueueInverter:
"""A wrapper that inverts the priority ordering of the inner PriorityQueue"""
def __init__(self, innerQueue):
self._innerQueue = innerQueue
def pop(self):
"""Remove and return the item at the front of the queue"""
key, priority = self._innerQueue.pop()
return (key, -priority)
def peek(self):
return self._innerQueue.peek()
def insert(self, key, priority):
"""Insert the key item with the given priority."""
self._innerQueue.insert(key, -priority)
def __len__(self):
return len(self._innerQueue)
if __name__ == '__main__':
myHeap = Heap()
myHeap.insert(12)
myHeap.insert(8)
myHeap.insert(2)
myHeap.insert(14)
myHeap.insert(20)
myHeap.insert(7)
print(myHeap.pop())
print(myHeap.pop())
print(myHeap.pop())
print(myHeap.pop())
myHeap.insert(100)
myHeap.insert(1)
myHeap.insert(99)
myHeap.insert(2)
myHeap.insert(98)
myHeap.insert(3)
print(myHeap.pop())
print(myHeap.pop())
print(myHeap.pop())
print(myHeap.pop())
print(myHeap.pop())
print(myHeap.pop())
print(myHeap.pop())
print(myHeap.pop())
| [
[
1,
0,
0.003,
0.003,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.0091,
0.003,
0,
0.66,
0.1667,
272,
0,
0,
0,
0,
0,
5,
0
],
[
3,
0,
0.2561,
0.4848,
0,
0.66... | [
"import sys",
"__all__ = ['Heap', 'PriorityQueue']",
"class NodeHeap(object):\n \"\"\"An ordered set optimized for finding the greatest value element.\n \n This is a binary max heap.\"\"\"\n\n class heapNode(object):\n\n def __init__(self, value):",
" \"\"\"An ordered set optimized for f... |
def generate_paren_combos(n):
"""Generate the set of all possible valid arrangements of n pairs
of parentheses. Note, we have to use sets to store the results
because we'll end up with duplicates otherwise.
"""
if n == 0:
return ""
curCombos = set(["()"])
for i in range(1, n):
combos = set()
for smaller_combo in curCombos:
for i in range(len(smaller_combo)):
combos.add("{}(){}".format(''.join(smaller_combo[:i]), ''.join(smaller_combo[i:])))
curCombos = combos
return curCombos
def build_paren_combos(n):
"""Generate the set of all possible valid arrangements of n pairs
of parentheses. This approach builds all possible strings one
character at a time, and avoids the duplicate generation of
the generate_paren_combos method above.
"""
combos = []
charbuf = ['' for _ in range(n*2)]
return addChar(combos, charbuf, 0, n, n)
def addChar(combos: list, charbuf: list, i: int, left_remaining: int, right_remaining: int):
"""Helper method to recursively build valid arrangements of pairs
of parentheses. You may imagine this process to be a depth-first
exploration of the tree of all valid parentheses pairs where the
left branch always adds an open paren and the right branch a close
paren.
"""
if left_remaining == 0 and right_remaining == 0:
combos.append(''.join(charbuf))
else:
if left_remaining > 0:
charbuf[i] = '('
addChar(combos, charbuf, i+1, left_remaining - 1, right_remaining)
if right_remaining > left_remaining:
charbuf[i] = ')'
addChar(combos, charbuf, i+1, left_remaining, right_remaining - 1)
return combos
if __name__ == "__main__":
combos1 = generate_paren_combos(4)
print(combos1)
print()
combos2 = set(build_paren_combos(4))
print(combos2)
print()
print(set.difference(combos2, combos1))
| [
[
2,
0,
0.1552,
0.2586,
0,
0.66,
0,
599,
0,
1,
1,
0,
0,
0,
9
],
[
8,
1,
0.0776,
0.069,
1,
0.15,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
4,
1,
0.1293,
0.0345,
1,
0.15,
0.... | [
"def generate_paren_combos(n):\n \"\"\"Generate the set of all possible valid arrangements of n pairs\n of parentheses. Note, we have to use sets to store the results\n because we'll end up with duplicates otherwise.\n \"\"\"\n if n == 0:\n return \"\"\n curCombos = set([\"()\"])",
" \... |
if __name__ == "__main__":
# determine the number of units of water that would be trapped in a landscape
# defined by the the waterTable array
waterTable = [ 3, 5, 0, 3, 7, 1, 4, 2, 9, 8, 7, 3, 2, 9, 1, 6, 2, 3, 5, 4, 8, 1, 4, 7, 1]
maxHeight = max(waterTable)
totalWater = 0
leftMaxIndex = -1
rightMaxIndex = -1
index = 0
maxFromEdge = 0
while waterTable[index] != maxHeight:
maxFromEdge = max(maxFromEdge, waterTable[index])
totalWater += maxFromEdge - waterTable[index]
index += 1
leftMaxIndex = index
index = len(waterTable) - 1
maxFromEdge = 0
while waterTable[index] != maxHeight:
maxFromEdge = max(maxFromEdge, waterTable[index])
totalWater += maxFromEdge - waterTable[index]
index -= 1
rightMaxIndex = index
for index in range(leftMaxIndex + 1, rightMaxIndex):
totalWater += maxHeight - waterTable[index]
print(totalWater)
# Alternatively...
# We'll start with the total volume of the bounding rect for the water table,
# then subtract all of the area we know not to be filled.
maxHeight = max(waterTable)
totalWater = maxHeight * len(waterTable)
# subract the volume of the steps
totalWater -= sum(waterTable)
index = 0;
maxFromEdge = 0
while waterTable[index] != maxHeight:
# This position and everything to the right of here will be filled in at
# least up to maxFromEdge
maxFromEdge = max(maxFromEdge, waterTable[index])
# We know how high the water is here, so we can subtract all of the space
# that is not filled
totalWater -= (maxHeight - maxFromEdge)
index += 1
index = len(waterTable) - 1
maxFromEdge = 0
while waterTable[index] != maxHeight:
maxFromEdge = max(maxFromEdge, waterTable[index])
totalWater -= (maxHeight - maxFromEdge)
index -= 1
print(totalWater)
| [
[
4,
0,
0.4922,
0.9375,
0,
0.66,
0,
0,
0,
0,
0,
0,
0,
0,
13
],
[
14,
1,
0.0938,
0.0156,
1,
0.71,
0,
301,
0,
0,
0,
0,
0,
5,
0
],
[
14,
1,
0.125,
0.0156,
1,
0.71,
... | [
"if __name__ == \"__main__\":\n # determine the number of units of water that would be trapped in a landscape\n # defined by the the waterTable array\n\n waterTable = [ 3, 5, 0, 3, 7, 1, 4, 2, 9, 8, 7, 3, 2, 9, 1, 6, 2, 3, 5, 4, 8, 1, 4, 7, 1]\n\n maxHeight = max(waterTable)\n totalWater = 0",
" ... |
from partie2 import *
#====Test de la resolution de l'equation du modele de Malthus======#
gamma = 0.007
h = 0.1
t0 = 0
y0 = 30000000
N = 1000
y = malthus(gamma , h , t0 , y0 , N , step_midpoint)#Exemple credible
x=np.linspace(0,100,len(y))
#mal = mp.plot(x,y)
#mp.show()
#====Test de la resolution de l'equation du modele de Verhulst======#
kappa = 400000000
y = verhulst(gamma, kappa, h, t0, y0, N, step_midpoint)
x = np.linspace(0,100,len(y))
#v2 = mp.plot(x,y)
#mp.xlabel("y(t)")
#mp.ylabel("t")
#mp.show()
#====Test de la resolution du systeme de Lotka-Volterra======#
ylv0 = (500.0 , 25.0)
a=2.5; # taux de reproduction des proies en l absence de predateurs
b=0.01; # taux de mortalite des proies due aux predateurs
c=0.01; # taux de reproduction des predateurs en fonction des proies mangees
d=2.5; # taux de mortalite des predateurs en l absence de proies
#====Graphe des solutions en fonction du temps======#
y = lotka_volterra(a, b, c, d, t0, ylv0, h, N, step_midpoint)
#solution constante:
#y = lotka_volterra(a, b, c, d, t0, np.array([d/c,a/b]), h, N, step_midpoint)
x = np.linspace(0, 100, len(y))
#mp.title("Variation des population des proies et des predateurs en fonction du temps")
#mp.ylabel("y(t)")
#mp.xlabel("t")
#c = mp.plot(x,y)
#mp.legend(c, ("proies" , "predateurs"))
#mp.show()
#====Graphe de variation du couple (N(t),P(t))======#
#lotka_volterra_2dim(a, b, c, d, t0, ylv0, h, N, step_midpoint, "b.")
#point singulier(solution constante):
#lotka_volterra_2dim(a, b, c, d, t0, np.array([d/c,a/b]), h, N, step_midpoint, "b.")
#====Graphe de variation du couple (N(t),P(t)) en fonction du temps dans l'espace de dimension 3======#
#lotka_volterra_3dim(a, b, c, d, t0, ylv0, h, N, step_midpoint)
#point singulier(solution constante):
#lotka_volterra_3dim(a, b, c, d, t0, np.array([d/c,a/b]), h, N, step_midpoint)
#====Test du calcul de la periode de la solution du systeme de Lotka-Volterra======#
#print periode(a, b, c, d, t0, ylv0, h, N, step_midpoint)
#====Test de l'affichage des graphes des fonctions solutions du systeme Lotka-Volterra en fonction du temps en faisant varier la condition initiale autour d'une valeur y0======#
pas = 0.01
diff_max = 0.03
#autour d'un point quelconque:
#local(a, b, c, d, t0, ylv0, h, N, pas, diff_max, step_midpoint)
#autour d'un point singulier:
#local(a, b, c, d, t0, np.array([d/c,a/b]), h, N, pas, diff_max, step_midpoint)
#====Test de l'affichage des graphes de variations du couple (N(t),P(t)) solution du systeme Lotka-Volterra en fonction du temps en faisant varier la condition initiale autour d'une valeur y0======#
#autour d'un point quelconque:
#local_2d(a, b, c, d, t0, ylv0, h, N, pas, diff_max, step_midpoint)
#autour d'un point singulier:
#local_2d(a, b, c, d, t0, np.array([d/c,a/b]), h, N, pas, diff_max, step_midpoint)
| [
[
1,
0,
0.012,
0.012,
0,
0.66,
0,
48,
0,
1,
0,
0,
48,
0,
0
],
[
14,
0,
0.0602,
0.012,
0,
0.66,
0.0526,
400,
1,
0,
0,
0,
0,
2,
0
],
[
14,
0,
0.0723,
0.012,
0,
0.66,
... | [
"from partie2 import *",
"gamma = 0.007",
"h = 0.1",
"t0 = 0",
"y0 = 30000000",
"N = 1000",
"y = malthus(gamma , h , t0 , y0 , N , step_midpoint)#Exemple credible",
"x=np.linspace(0,100,len(y))",
"kappa = 400000000",
"y = verhulst(gamma, kappa, h, t0, y0, N, step_midpoint)",
"x = np.linspace(0,... |
# -*coding:utf-8 -*
import numpy as np
import matplotlib.pyplot as mp
from scipy.integrate import odeint
#------------------------#
# projet 6 #
# #
# partie 1 #
#------------------------#
# Implementation des differentes methodes de resolutions
# methode d'Euler
def step_euler(y,t,h,f) :
return y + h * f(y,t)
#methode du point milieu
def step_midpoint(y,t,h,f):
return y + h * f(y + (h * f(y,t) / 2), t+(h/2))
#methode de Heun
def step_heun(y,t,h,f) :
return y + 0.5 * h * (f(y,t) + f(y+h*f(y,t) , t+h))
# methode de Runge-Kutta d'ordre 4
def step_RK4(y,t,h,f) :
k1 = f(y,t)
k2 = f(y +(h * k1 / 2), t+(h/2))
k3 = f( y + (h * k2 /2), t + (h/2))
k4 = f( y+ h*k3, t+h)
return y + h*(k1+ 2*k2 + 2*k3 + k4) /6.
#Premier algorithme de resolution
def meth_n_step(y0, t0, N,h,f, meth) :
y = y0
t = t0
res = []
for i in range (N) :
res.append(y)
y = meth(y,t,h,f)
t += h
return res
#Deuxieme algorithme de resolution
def meth_epsilon(y0, t0, tf, eps, f, meth):
h = 1.0
y2 = meth_n_step(y0, t0, np.rint(tf/h), h, f, meth)
e = 10000000.0
while (e > eps):
y1 = y2
h = h / 2
y2 = meth_n_step(y0, t0, np.rint(tf/h), h, f, meth)
max1 = len(y1)
max2 = len(y2)
e =y2[max2-1] - y1[max1-1]
return y2
#Question 3
def champ_tangente(f,x1,x2,h,y0,meth):
"fonction qui trace le champ des tangentes de l'équation différentielle passée en paramètre d'entrée"
x = np.arange(x1,x2,h)
y = np.arange(x1,x2,h)
n = x.size
for i in range (1,n) :
for j in range(1,n) :
X = np.array([[x[i]]])
Y = np.array([[y[j]]])
norme = np.sqrt(1.0 + (f(y[j],x[i]))**2)
V = np.array([ [f(y[j],x[i])] /norme ])
U = np.array([ [1.0] / norme ])
mp.quiver(X,Y,U, V, color="k", width = .002, scale = 50)
abs = np.arange(x1, x2, .01)
ord = np.arange(x1, x2, .01)
for i in range(0, len(ord)):
abs[i] = 0.0
mp.plot(abs, ord,color= "k", linewidth=1.0)
t = np.arange(x1, x1 + len(y) * h, h)
sol1 = meth_n_step(-0.5, x1, np.rint((x2-x1)/h), h, f, meth)
curve1 =mp.plot (t, sol1, linewidth=1.0)
sol2 = meth_n_step(0., x1, np.rint((x2-x1)/h), h, f, meth)
curve2=mp.plot (t, sol2, linewidth=1.0)
sol3 = meth_n_step(0.5, x1, np.rint((x2-x1)/h), h, f, meth)
curve3=mp.plot (t, sol3, linewidth=1.0)
mp.ylim([x1,x2])
mp.xlim([x1,x2])
mp.xlabel('t')
mp.ylabel('y')
mp.title("Graphe du champ des tangentes de l'equation differentielle")
mp.legend((curve1,curve2,curve3),('y0 = -0.5','y0 = 0','y0 = 0.5'))
mp.show()
# Question 4
#fonction qui trace les courbes obtenues et les comprae avec la solution theorique
def graphe_dim1(f,y0,t0,h):
mp.title("Tracage des courbes de l'equation differentielle")
mp.xlabel("t")
mp.ylabel("y")
de = meth_n_step(y0,t0,100,h,f,step_euler)
dm = meth_n_step(y0,t0,100,h,f,step_midpoint)
dh = meth_n_step(y0,t0,100,h,f,step_heun)
d4 = meth_n_step(y0,t0,100,h,f,step_RK4)
t = np.linspace(t0,10.,len(de))
dt = odeint(f,1.,t)
e_curve = mp.plot(t,de)
m_curve = mp.plot(t,dm)
h_curve = mp.plot(t,dh)
r_curve = mp.plot(t,d4)
t_curve = mp.plot(t,dt)
mp.legend((e_curve,m_curve,h_curve,r_curve, t_curve),('Euler','point milieu','Heun', 'Runge Kutta 4','solution theorique'))
mp.show()
#============= fonction qui trace la solution en dimension 2 =======#
def graphe_dim2 (f,y0,t0,h):
mp.title("Tracage des courbes de l'equation differentielle en dimension 2")
mp.xlabel("t")
mp.ylabel("y")
de = meth_n_step(y0,t0,100,h,f,step_euler)
dm = meth_n_step(y0,t0,100,h,f,step_midpoint)
dh = meth_n_step(y0,t0,100,h,f,step_heun)
d4 = meth_n_step(y0,t0,100,h,f,step_RK4)
t = np.linspace(t0,10.,len(de))
#e_curve = mp.plot(t,de)
#m_curve = mp.plot(t,dm)
h_curve = mp.plot(t,dh)
r_curve = mp.plot(t,d4)
mp.legend((h_curve,r_curve),('Heun (1)', 'Heun (2)','Runge Kutta 4 (1)','Runge Kutta (2)'))
mp.show()
#=============fonction qui trace y2 en fonction de y1============#
def graphe2(f,h):
y1_euler = np.arange(0.0, 10.0, h)
y2_euler = np.arange(0.0, 10.0, h)
y1_milieu = np.arange(0.0, 10.0, h)
y2_milieu = np.arange(0.0, 10.0, h)
y1_heun = np.arange(0.0, 10.0, h)
y2_heun = np.arange(0.0, 10.0, h)
y1_runge = np.arange(0.0, 10.0, h)
y2_runge = np.arange(0.0, 10.0, h)
y1_euler[0] = np.array([1.0])
y2_euler[0] = np.array([0.0])
y1_milieu[0] = np.array([1.0])
y2_milieu[0] = np.array([0.0])
y1_heun[0] = np.array([1.0])
y2_heun[0] = np.array([0.0])
y1_runge[0] = np.array([1.0])
y2_runge[0] = np.array([0.0])
for i in range (1, len(y1_euler)):
y_euler = np.array([y1_euler[i-1], y2_euler[i-1]])
vect_euler = step_euler(y_euler, 0.0, h, f)
[y1_euler[i], y2_euler[i]] = vect_euler
y_milieu = np.array([y1_milieu[i-1], y2_milieu[i-1]])
vect_milieu = step_midpoint(y_milieu, 0.0, h, f)
[y1_milieu[i], y2_milieu[i]] = vect_milieu
y_heun = np.array([y1_heun[i-1], y2_heun[i-1]])
vect_heun = step_heun(y_heun, 0.0, h, f)
[y1_heun[i], y2_heun[i]] = vect_heun
y_runge = np.array([y1_runge[i-1], y2_runge[i-1]])
vect_runge = step_RK4(y_runge, 0.0, h, f)
[y1_runge[i], y2_runge[i]] = vect_runge
mp.plot (y1_euler, y2_euler, 'r', label = 'Euler')
mp.plot (y1_milieu, y2_milieu, 'b', label = 'Point milieu')
mp.plot (y1_heun, y2_heun, 'g', label = 'Heun')
mp.plot (y1_runge, y2_runge, 'k', label = 'Runge-Kutta')
y1 = np.arange(0.0, 10.0, .01)
y2 = np.arange(0.0, 10.0, .01)
t = np.arange(0.0, 10.0, .01)
for i in range (0, len(t)):
y1[i] = np.cos(t[i])
y2[i] = np.sin(t[i])
mp.plot (y1, y2, label = 'Solution exacte')
mp.xlabel('y1')
mp.ylabel('y2')
mp.legend()
mp.title("y2 en fonction de y1")
mp.show()
| [
[
1,
0,
0.0136,
0.0045,
0,
0.66,
0,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.0182,
0.0045,
0,
0.66,
0.0833,
596,
0,
1,
0,
0,
596,
0,
0
],
[
1,
0,
0.0227,
0.0045,
0,
... | [
"import numpy as np",
"import matplotlib.pyplot as mp",
"from scipy.integrate import odeint",
"def step_euler(y,t,h,f) : \n return y + h * f(y,t)",
" return y + h * f(y,t)",
"def step_midpoint(y,t,h,f):\n return y + h * f(y + (h * f(y,t) / 2), t+(h/2))",
" return y + h * f(y + (h * f(y,t) ... |
from partie3 import *
#=======resolution du systeme et tracage de la solution========#
I=array([1,0,0])
#y = resoudre(I, 0.1 , 0.1 , 1. , 2.)
#courbe = mp.plot(y[0],y[1])
#mp.legend(courbe ,("X","Y","Z"))
#xlabel("t")
#ylabel("y(t)")
#mp.show()
#======calcul du temps du debut de la phase periodique========#
#y = meth_epsilon(definir_sys(0.12),I,1. ,2.,0.1,"rk4","non")
#print partie_periodique(definir_sys(0.12),0.,y)
b=0.1
eps=0.1
debut=1.
end=1.
#=======Tracage du diagramme de bifurcation======#
B=linspace(0.1,0.2,20)
#bifurcation (I,B,0.1,1.,2.)
| [
[
1,
0,
0.0357,
0.0357,
0,
0.66,
0,
658,
0,
1,
0,
0,
658,
0,
0
],
[
14,
0,
0.2143,
0.0357,
0,
0.66,
0.1667,
134,
3,
1,
0,
0,
80,
10,
1
],
[
14,
0,
0.6786,
0.0357,
0,
... | [
"from partie3 import *",
"I=array([1,0,0])",
"b=0.1",
"eps=0.1",
"debut=1.",
"end=1.",
"B=linspace(0.1,0.2,20)"
] |
import numpy as np
import pylab as plt
from matplotlib.collections import *
import matplotlib.pyplot as mp
from mpl_toolkits.mplot3d import Axes3D
import mpl_toolkits.mplot3d as M3
from partie1 import *
from scipy.integrate import odeint
#------------------------#
# projet 6 #
# #
# partie 2 #
#------------------------#
#Modele Malthusien: b=naissances/N (taux de natalite)
#d=morts/N (taux de mortalite)
#gamma=(b-d)pourcentage de l'evolution
def malthus(gamma, h, t0, y0, N, meth):
"resout l'equation du modele de Malthus avec la methode passee en entree"
def f(y,t):
return (gamma * y)
return meth_n_step(y0, t0 , N , h , f , meth)
#kappa: capacite d'accueil
def verhulst(gamma, kappa, h, t0, y0, N, meth):
"resout l'equation du modele de Verhulst"
def f(y,t):
return (gamma*y*(1-(y/kappa)))
return meth_n_step(y0, t0, N, h, f, meth)
def lotka_volterra(a, b, c, d, t0, y0, h, N, meth):
"resout le systeme de Lotka-Volterra"
#y[0] -> N
#y[1] -> P
def f(y,t):
if(y[0]<0):
y[0]=0
if(y[1]<0):
y[1]=0
return np.array([y[0]*(a-b*y[1]) , y[1]*(c*y[0]-d)])
return meth_n_step(y0, t0, N, h, f, meth)
def lotka_volterra_2dim(a, b, c, d, t0, y0, h, N, meth, coul):
"resout le systeme de Lotka-Volterra et affiche la variation du couple (N(t),P(t)) sur un plan"
y = lotka_volterra(a, b, c, d, t0, y0, h, N, meth)
mp.xlabel("proie")
mp.ylabel("predateur")
for i in range(len(y)):
mp.plot([y[i][0]],[y[i][1]],coul)
mp.show()
def lotka_volterra_3dim(a, b, c, d, t0, y0, h, N, meth):
"resout le systeme de Lotka-Volterra et affiche la variation du couple (N(t),P(t)) en fonction du temps dans l'espace a 3 dimensions"
y = lotka_volterra(a, b, c, d, t0, y0, h, N, meth)
fig = plt.figure()
ax = Axes3D(fig)
y0= np.arange(len(y))
y1= np.arange(len(y))
for i in range(len(y)):
y0[i] = y[i][0]
y1[i] = y[i][1]
t = np.linspace(0,100,len(y))
ax.scatter(y0, y1, t)
ax.set_xlabel("proie")
ax.set_ylabel("predateurs")
ax.set_zlabel("t")
mp.show()
def pics(y):
"genere la liste des maximums de la fonction representee par y"
pic=np.zeros(len(y))
j=0;
for i in np.arange(1,len(y)-1,1):
if((y[i][0]>= y[i-1][0]) and (y[i][0]>= y[i+1][0])):
pic[j]=i
j=j+1
return (pic,j)
def periode(a, b, c, d, t0, y0, h, N, meth):
"utilise la fonction pics pour calculer une valeur approchee de la periode de la fonction solution de lotka-volterra"
y = lotka_volterra(a, b, c, d, t0, y0, h, N, meth)
(tab_pics,j)=pics(y)
p=0
for i in np.arange(1, j, 1):
p = p + tab_pics[i]-tab_pics[i-1]
return (p/(j-1))
def local(a, b, c, d, t0, ylv0, h, N, pas, diff_max, meth):
"affiche les graphes des fonctions solutions du systeme Lotka-Volterra en fonction du temps en faisant varier la condition initiale autour d'une valeur ylv0 et avec un pas pris en entree"
for i in np.arange(0, diff_max, pas):
y = lotka_volterra(a, b, c, d, t0, [i+ylv0[0],i+ylv0[1]], h, N, meth)
x = np.linspace(0, 0.001, len(y))
mp.plot(x,y, "k-")
y = lotka_volterra(a, b, c, d, t0, [ylv0[0]-i, ylv0[1]-i], h, N, meth)
x = np.linspace(0, 0.001, len(y))
mp.plot(x,y, "k-")
mp.xlabel("y(t)")
mp.ylabel("t")
mp.show()
def local_2d(a, b, c, d, t0, ylv0, h, N, pas, diff_max, meth):
"affiche les graphes de variations du couple (N(t),P(t)) solution du systeme Lotka-Volterra dans le plan en faisant varier la condition initiale autour d'une valeur ylv0 et avec un pas pris en entree"
pal=["b.","c.","m.","g.","k.","r.","y."]
ind = 0
for i in np.arange(0, diff_max, pas):
y = lotka_volterra(a, b, c, d, t0, ylv0, h, N, meth)
for j in range(len(y)):
mp.plot([y[j][0]+i],[y[j][1]+i], pal[ind] )
if (ind < 6 ):
ind = ind + 1
else:
ind = 0
mp.xlabel("proie")
mp.ylabel("predateur")
mp.show()
#Q8: Les points singuliers du systeme Lotka-Volterra sont les points qui verifient
#P(t)=a/b et N(t)=d/c
| [
[
1,
0,
0.0071,
0.0071,
0,
0.66,
0,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.0142,
0.0071,
0,
0.66,
0.0625,
735,
0,
1,
0,
0,
735,
0,
0
],
[
1,
0,
0.0213,
0.0071,
0,
... | [
"import numpy as np",
"import pylab as plt",
"from matplotlib.collections import *",
"import matplotlib.pyplot as mp",
"from mpl_toolkits.mplot3d import Axes3D",
"import mpl_toolkits.mplot3d as M3",
"from partie1 import *",
"from scipy.integrate import odeint",
"def malthus(gamma, h, t0, y0, N, meth... |
import random
def generateRandomList(size):
'''return a list, contains 'size' of random number
'''
list=[]
while size>0:
list.append(random.randint(1,99))
size-=1
return list
def test(result, expectation,type):
'''test if the result equals expectation
'''
if result==expectation:
print type,'OK, result:', result
else:
print type,'Failed!!!\n', 'Expect: ', expectation, '\nBut got:', result
def exchange(a,i,j):
'''swap element with index i and element with index j in the list a
'''
temp=a[i]
a[i]=a[j]
a[j]=temp
def shell_sort(list):
'''Shell sort using Shell's (original) gap sequence: n/2, n/4, ..., 1.'''
gap = len(list) / 2
# loop over the gaps
while gap > 0:
# do the insertion sort
efficency_insertion_sort(list,gap)
gap /= 2
return list
def insertion_sort(list):
'''left to right for inner loop, need many reallocation
'''
i=0
while i<len(list):
j=0
while j<i+1:
if list[i]<list[j]:
temp=list.pop(i)
list.insert(j, temp)
j=i+1 #break the look
j+=1
i+=1
return list
def efficency_insertion_sort(list,gap=1):
''' right to left for inner loop, much better than previous one
takes linear time when input is already sorted'''
for i in range(gap,len(list)):
temp = list[i]
while temp<list[i-gap] and i>0:
list[i]=list[i-gap]
i-=gap
list[i]=temp
return list
def selection_sort(list):
''' always takes N^2 time no matter what the input is'''
i=0
while i<len(list):
j=i
index=i
while j<len(list):
if list[j]<list[index]:
index=j
j+=1
exchange(list, index, i)
i+=1
return list
def main():
lenth=10
list = generateRandomList(lenth)
print 'Original: ', list,''
test(selection_sort(list), sorted(list),'selection sort')
list = generateRandomList(lenth)
print 'Original: ', list,''
test(insertion_sort(list), sorted(list),'insertion sort')
list = generateRandomList(lenth)
print 'Original: ', list,''
test(efficency_insertion_sort(list), sorted(list),'efficency_insertion_sort')
list = generateRandomList(lenth)
print 'Original: ', list,''
test(shell_sort(list), sorted(list),'shell_sort')
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0088,
0.0088,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
2,
0,
0.0482,
0.0702,
0,
0.66,
0.1111,
868,
0,
1,
1,
0,
0,
0,
2
],
[
8,
1,
0.0307,
0.0175,
1,
0.... | [
"import random",
"def generateRandomList(size):\n\t'''return a list, contains 'size' of random number\n\t'''\n\tlist=[]\n\twhile size>0:\n\t\tlist.append(random.randint(1,99))\n\t\tsize-=1\n\treturn list",
"\t'''return a list, contains 'size' of random number\n\t'''",
"\tlist=[]",
"\twhile size>0:\n\t\tlist... |
#The TSP problem
#created by logan rooper- Riverdale High School - logan.rooper@gmail.com
#Random walk
import random
import math
################################################################################################
cycles = int(input("How many iterations do you want? >")) #INCREASE THIS TO INCREASE ITERATIONS#
num_cities = int(input("How many cites do you want? >")) #SET NUMBER OF CITIES
population = int(input("What population in the generations? Recommended: 50 >"))
################################################################################################
#Setting up the problem
print("Setting up the problem")
cities=[] #the regular city map
h_cities=[] #the highscore city map
#Generate num_cities random cities
#Cities should be in a X by Y array (0-9 coordinates
#Coordinates can be 101 through 199 (1 is the octal padding bit)
print("There are "+str(len(cities))+" cities.")
cities=(random.sample(range(100,199), num_cities))
for x in range(0,num_cities):
print("Making city "+str(x)+".")
print("City "+str(x)+" is X: "+str(cities[x])[1]+" and Y:"+str(cities[x])[2])
print("There are now "+str(len(cities))+" cities.")
#draw city map
print("PRINT MAP")
#iterate through all coordinates
row = ""
count = 1
for z in range(100,199):
if z in cities:
row += "--*--|"
else:
row += "-----|"
if count == 9: #rows is the width of the map...unsused because of our integer data limits
row += "\n"
count = 0
count += 1
print(row)
print("Ready to create and run the algorithm??")
i = input(">")
#Create and run the algorithm
print("Creating/running the algorithm.")
high = 10000000.0 #arbitrarily high float value
done = False
i = 0
########ALGORITHM START##########
#create a list of paths (a generation)
generation = []
mid = []
sub = []
member = []
elite = []
'''GENERATION STRUCTURE
generation[member_number] --> mid[0,1] --> sub[0xy]
fitness
&calling member's fitness is
generation[member_number][1]
&a member's path item is
generation[member_number][0][i]
'''
fitness = 0
elite_fitness = 0
elite_data = []
#populate first generation with $population random induviduals
for x in range(0,population):
#shuffle the member
member = cities
random.shuffle(member)
#print(repr(member))
#add the member's path to mid
sub.insert(0,member)
#calculate the member's fitness
distance = 0
for index, city in enumerate(member):
cx = int(str(city)[1]) #currentX
cy = int(str(city)[2]) #currentY
if index != 0:
#measure the absolute distance between c* and p* if it's not the first city
distance += math.sqrt(abs((cx-px))**2+abs((cy-py))**2)
px = cx
py = cy
fitness = 10/distance
#find dat elite member and save him
if fitness > elite_fitness:
elite_fitness = fitness
elite_data = member
#add the member's fitness to mid
sub.insert(1,fitness)
mid.append(sub)
#push the member (mid) to generation
generation.insert(x,mid)
#print(repr(generation)) warning! takes forever...
#we now how our first generation, each member has values and fitnesses, and an elite member
#we now need to begin the full reprodcution loop, which takes a generation and returns a new generation
for x in range(0,cycles):
#print("starting reproduction cycle "+str(x))
#generate a pie for this generation: the pie determines the chance of being mate-selected
pie = []
for y in range(0,population):
for y in range(0,len(generation[0])):
pie.append(generation[0][0][
for z in range(0,population):
#print("mating event "+str(y))
#select two members randomly and based on fitness
if distance < high:
high = distance
h_cities = cities
print("NEW HIGHSCORE FOUND ------------")
print(repr(h_cities))
i += 1
if i >= cycles:
done = True
#########ALGORITHM END###########
print("Shortest path found was "+str(high)+" units long.")
print()
print("PRINT MAP") #map of h_cities
print("--> X axis")
print("|")
print("| Y axis")
print("V")
row = ""
count = 1
for z in range(100,199):
if z in h_cities:
if cities.index(z) < 10:
cit = "0"+str(cities.index(z))
else:
cit = str(cities.index(z))
row += "--"+cit+"-|"
else:
row += "-----|"
if count == 10:
row += "\n"
count = 0
count += 1
print(row)
#EOF
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.6667,
0.3333,
0,
0.66,
1,
526,
0,
1,
0,
0,
526,
0,
0
]
] | [
"import random",
"import math"
] |
#The TSP problem
#created by logan rooper- Riverdale High School - logan.rooper@gmail.com
#Random walk
import random
import math
################################################################################################
cycles = int(input("How many iterations do you want? >")) #INCREASE THIS TO INCREASE ITERATIONS#
num_cities = int(input("How many cites do you want? >")) #SET NUMBER OF CITIES #
################################################################################################
#Setting up the problem
print("Setting up the problem")
cities=[] #the regular city map
h_cities=[] #the highscore city map
#Generate num_cities random cities
#Cities should be in a X by Y array (0-9 coordinates
#Coordinates can be 101 through 199 (1 is the octal padding bit)
print("There are "+str(len(cities))+" cities.")
cities=(random.sample(range(100,199), num_cities))
for x in range(0,num_cities):
print("Making city "+str(x)+".")
print("City "+str(x)+" is X: "+str(cities[x])[2]+" and Y:"+str(cities[x])[1])
print("There are now "+str(len(cities))+" cities.")
#draw city map
print("PRINT MAP")
print("--> X axis")
print("|")
print("| Y axis")
print("V")
#iterate through all coordinates
row = ""
count = 1
for z in range(100,199):
if z in cities:
row += "--*--|"
else:
row += "-----|"
if count == 10: #rows is the width of the map...unsused because of our integer data limits
row += "\n"
count = 0
count += 1
print(row)
print("Ready to create and run the algorithm??")
i = input(">")
#Create and run the algorithm
print("Creating/running the algorithm.")
high = 10000000.0 #arbitrarily high float value
done = False
i = 0
while (done != True):
print("Starting iteration "+str(i))
########ALGORITHM START##########
#create a list of paths (a generation)
generation = []
mid = []
sub = []
'''GENERATION STRUCTURE
generation[member_number] --> mid[0,1] --> sub[0xy]
fitness
&calling member's fitness is
generation[member_number][1]
&a member's path item is
generation[member_number][0][i]
'''
#populate first generation with 50 random induviduals
for x in range(0,50):
generation = []
mid = []
sub = []
#shuffle the member
member[] = random.shuffle(cities)
#add the member's path to mid
mid.insert(0,member)
#calculate the member's fitness
distance = 0
for index, city in enumerate(member):
cx = int(str(city)[1]) #currentX
cy = int(str(city)[2]) #currentY
if index != 0:
#measure the absolute distance between c* and p* if it's not the first city
distance += math.sqrt(abs((cx-px))**2+abs((cy-py))**2)
px = cx
py = cy
fitness = 10/distance
#add the member's fitness to mid
mid.insert(1,fitness)
#push the member (mid) to generation
generation.append(mid)
#
mid.insert(0,sub)
generation.insert(x,mid)
#########ALGORITHM END###########
if distance < high:
high = distance
h_cities = cities
print("NEW HIGHSCORE FOUND ------------")
print(repr(h_cities))
i += 1
if i >= cycles:
done = True
print()
print("Shortest path found was "+str(high)+" units long.")
print("PRINT MAP") #map of h_cities
print("--> X axis")
print("|")
print("| Y axis")
print("V")
row = ""
count = 1
for z in range(100,199):
if z in h_cities:
if cities.index(z) < 10:
cit = "0"+str(cities.index(z))
else:
cit = str(cities.index(z))
row += "--"+cit+"-"
else:
row += "-----"
if count == 10:
row += "\n"
count = 0
count += 1
print(row)
#EOF
| [
[
1,
0,
0.0284,
0.0071,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0355,
0.0071,
0,
0.66,
0.027,
526,
0,
1,
0,
0,
526,
0,
0
],
[
14,
0,
0.0567,
0.0071,
0,
... | [
"import random",
"import math",
"cycles = int(input(\"How many iterations do you want? >\")) #INCREASE THIS TO INCREASE ITERATIONS#",
"num_cities = int(input(\"How many cites do you want? >\")) #SET NUMBER OF CITIES #",
"print(\"Setting up the problem\")",
"cities=[] #the regular city map"... |
"""
start north rotate clockwise
0 = out, circle
1 = out, square
2 = in, circle
3 = in, square
0, 2 go together
1, 3 go together
puzzle:
0 1
2 3
"""
import random
#VARIABLE DECLARATION
pieces = [
[1,0,1,1],
[0,2,3,2],
[1,1,1,0],
[3,1,2,0],
[1,3,0,3],
[3,2,2,1],
#[0,1,0,1],
#[2,2,2,3],
#[0,2,0,0]
]
connections = []
solved = False
#FUNCTION DECLARATION
def rotate(x):
#rotate
for i in range(0,3):
z = random.randint(0,3)
count = 0
while count < z:
top = x[i][0]
x[i].pop(0)
x[i].append(top)
count += 1
return x
def flip(x):
for i in range(0,3):
z = random.randint(0,1)
if z == 1:
top = x[i][0]
x[i][0] = x[i][2]
x[i][2] = top
return x
# this function shuffles the puzzle randomly
def rand_s(p):
random.shuffle(p)
p = rotate(p)
p = flip(p)
return p
# next there should be a function which checks to see if the value is valid
def is_solved(x):
if not are_connected(x[0][1],x[1][3]):
return False
if not are_connected(x[1][1],x[2][3]):
return False
if not are_connected(x[0][2],x[3][0]):
return False
if not are_connected(x[1][2],x[4][0]):
return False
if not are_connected(x[2][2],x[5][0]):
return False
if not are_connected(x[3][1],x[4][3]):
return False
if not are_connected(x[4][1],x[5][3]):
return False
'''if not are_connected(x[3][2],x[6][0]):
return False
if not are_connected(x[4][2],x[7][0]):
return False
if not are_connected(x[5][2],x[8][0]):
return False
if not are_connected(x[6][1],x[7][3]):
return False
if not are_connected(x[7][1],x[8][3]):
return False'''
else:
return True
def are_connected(x,y):
if (x == 0 and y == 2 or x == 1 and y == 3 or x == 2 and y == 0 or x == 3 and y == 1):
return True
return False
#MAIN LOOP
while not(solved):
#pieces = rand_s(pieces)
#print("not solved.")
if is_solved(pieces):
solved = True
print("solved.")
print(str(pieces))
| [
[
8,
0,
0.0802,
0.1509,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1604,
0.0094,
0,
0.66,
0.1,
715,
0,
1,
0,
0,
715,
0,
0
],
[
14,
0,
0.2453,
0.1038,
0,
0.66,
... | [
"\"\"\"\nstart north rotate clockwise\n0 = out, circle\n1 = out, square\n2 = in, circle\n3 = in, square\n0, 2 go together\n1, 3 go together",
"import random",
"pieces = [\n [1,0,1,1],\n [0,2,3,2],\n [1,1,1,0],\n [3,1,2,0],\n [1,3,0,3],\n [3,2,2,1],\n #[0,1,0,1],",
"connections = []",
"s... |
import random
from time import localtime
f = open("output.txt", "w")
"""
start north rotate clockwise
0 = out, circle
1 = out, square
2 = in, circle
3 = in, square
0, 2 go together
1, 3 go together
puzzle:
0 1
2 3
"""
#VARIABLE DECLARATION
pieces = [
[1,0,1,1],
[0,2,3,2],
[3,1,2,0],
[1,3,0,3],
]
connections = []
solved = False
#FUNCTION DECLARATION
def rotate(x):
#rotate
for i in range(0,3):
z = random.randint(0,3)
count = 0
while count < z:
top = x[i][0]
x[i].pop(0)
x[i].append(top)
count += 1
return x
def flip(x):
for i in range(0,3):
z = random.randint(0,1)
if z == 1:
top = x[i][0]
x[i][0] = x[i][2]
x[i][2] = top
return x
# this function shuffles the puzzle randomly
def rand_s(p):
random.shuffle(p)
p = rotate(p)
p = flip(p)
return p
# next there should be a function which checks to see if the value is valid
def is_solved(x):
if not are_connected(x[0][1],x[1][3]):
return False
if not are_connected(x[1][2],x[3][0]):
return False
if not are_connected(x[2][1],x[3][3]):
return False
if not are_connected(x[2][0],x[0][2]):
return False
return True
def are_connected(x,y):
if (x == 0 and y == 2 or x == 1 and y == 3):
return True
return False
#MAIN LOOP
count = 0
s = 0
#time = localtime()
while not(solved):
pieces = rand_s(pieces)
#print("not solved.")
count += 1
if is_solved(pieces):
print("solved.")
s += 1
f.write("Solved " + s + "\n")
f.write("data: " + str(repr(pieces)) + "\n")
f.write("count: " + str(count)+"\n")
#f.write("time (s): " + (str(localtime())-str(time)))
f.write("\n\n")
count = 0
| [
[
1,
0,
0.0104,
0.0104,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0208,
0.0104,
0,
0.66,
0.0714,
654,
0,
1,
0,
0,
654,
0,
0
],
[
14,
0,
0.0312,
0.0104,
0,
... | [
"import random",
"from time import localtime",
"f = open(\"output.txt\", \"w\")",
"\"\"\"\nstart north rotate clockwise\n0 = out, circle\n1 = out, square\n2 = in, circle\n3 = in, square\n0, 2 go together\n1, 3 go together",
"pieces = [\n [1,0,1,1],\n [0,2,3,2],\n [3,1,2,0],\n [1,3,0,3],\n ]",... |
"""
start north rotate clockwise
0 = in arrow pointing in
1 = out arrow pointing out
2 = in arrow pointing out
3 = out arrow pointing in
4 = out cross
5 = in cross
6 = out hexagon
7 = in hexagon
0, 1 go together
2, 3 go together
4, 5 go together
6, 7 go together
puzzle:
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
"""
import random
#VARIABLE DECLARATION
pieces = [
[0,5,3,3],
[1,0,7,4],
[4,2,5,1],
[3,5,7,3],
[2,5,3,6],
[6,7,5,4],
[4,0,0,6],
[6,7,0,1],
[2,3,4,0],
[4,6,7,2],
[1,1,2,7],
[1,3,7,0],
[5,7,6,1],
[6,7,0,6],
[3,2,0,6],
[6,5,7,3]
]
connections = []
solved = False
#FUNCTION DECLARATION
def rotate(x):
#rotate
for i in range(0,3):
z = random.randint(0,3)
count = 0
while count < z:
top = x[i][0]
x[i].pop(0)
x[i].append(top)
count += 1
return x
def flip(x):
for i in range(0,3):
z = random.randint(0,1)
if z == 1:
top = x[i][0]
x[i][0] = x[i][2]
x[i][2] = top
return x
# this function shuffles the puzzle randomly
def rand_s(p):
random.shuffle(p)
p = rotate(p)
p = flip(p)
return p
# next there should be a function which checks to see if the value is valid
def is_solved(x):
if not are_connected(x[0][1],x[1][3]):
return False
if not are_connected(x[1][1],x[2][3]):
return False
if not are_connected(x[2][1],x[3][3]):
return False
if not are_connected(x[0][2],x[4][0]):
return False
if not are_connected(x[1][2],x[5][0]):
return False
if not are_connected(x[2][2],x[6][0]):
return False
if not are_connected(x[3][2],x[7][0]):
return False
if not are_connected(x[4][1],x[5][3]):
return False
if not are_connected(x[5][1],x[6][3]):
return False
if not are_connected(x[6][1],x[7][3]):
return False
if not are_connected(x[4][2],x[8][0]):
return False
if not are_connected(x[5][2],x[9][0]):
return False
if not are_connected(x[6][2],x[10][0]):
return False
if not are_connected(x[7][2],x[11][0]):
return False
if not are_connected(x[8][1],x[9][3]):
return False
if not are_connected(x[9][1],x[10][3]):
return False
if not are_connected(x[10][1],x[11][3]):
return False
if not are_connected(x[8][2],x[12][0]):
return False
if not are_connected(x[9][2],x[13][0]):
return False
if not are_connected(x[10][2],x[14][0]):
return False
if not are_connected(x[11][2],x[15][0]):
return False
if not are_connected(x[12][1],x[13][3]):
return False
if not are_connected(x[13][1],x[14][3]):
return False
if not are_connected(x[14][1],x[15][3]):
return False
else:
return True
def are_connected(x,y):
if (x == 0 and y == 1 or x == 1 and y == 0 or x == 2 and y == 3 or x == 3 and y == 2 or x == 4 and y == 5 or x == 5 and y == 4 or x == 6 and y == 7 or x == 7 and y == 6):
return True
return False
#MAIN LOOP
count = 0
while not(solved):
pieces = rand_s(pieces)
#print("not solved.")
count += 1
if is_solved(pieces):
solved = True
print("solved.")
print(str(pieces))
print(count)
| [
[
8,
0,
0.0968,
0.1871,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1935,
0.0065,
0,
0.66,
0.0909,
715,
0,
1,
0,
0,
715,
0,
0
],
[
14,
0,
0.2742,
0.1161,
0,
0.6... | [
"\"\"\"\nstart north rotate clockwise\n\n0 = in arrow pointing in\n1 = out arrow pointing out\n2 = in arrow pointing out\n3 = out arrow pointing in\n4 = out cross",
"import random",
"pieces = [\n [0,5,3,3],\n [1,0,7,4],\n [4,2,5,1],\n [3,5,7,3],\n [2,5,3,6],\n [6,7,5,4],\n [4,0,0,6],",
"c... |
"""
start north rotate clockwise
0 = in arrow pointing in
1 = out arrow pointing out
2 = in arrow pointing out
3 = out arrow pointing in
4 = out cross
5 = in cross
6 = out hexagon
7 = in hexagon
0, 1 go together
2, 3 go together
4, 5 go together
6, 7 go together
puzzle:
0 1 2
3 4 5
6 7 8
"""
import random
f = open("output.txt", "w")
#VARIABLE DECLARATION
pieces = [
[0,5,3,3],
[1,0,7,4],
[4,2,5,1],
[2,5,3,6],
[6,7,5,4],
[4,0,0,6],
[2,3,4,0],
[4,6,7,2],
[1,1,2,7]
]
connections = []
solved = False
#FUNCTION DECLARATION
def rotate(x):
#rotate
for i in range(0,3):
z = random.randint(0,3)
count = 0
while count < z:
top = x[i][0]
x[i].pop(0)
x[i].append(top)
count += 1
return x
def flip(x):
for i in range(0,3):
z = random.randint(0,1)
if z == 1:
top = x[i][0]
x[i][0] = x[i][2]
x[i][2] = top
return x
# this function shuffles the puzzle randomly
def rand_s(p):
random.shuffle(p)
p = rotate(p)
p = flip(p)
return p
# next there should be a function which checks to see if the value is valid
def is_solved(x):
if not are_connected(x[0][1],x[1][3]):
return False
if not are_connected(x[1][1],x[2][3]):
return False
if not are_connected(x[0][2],x[3][0]):
return False
if not are_connected(x[1][2],x[4][0]):
return False
if not are_connected(x[2][2],x[5][0]):
return False
if not are_connected(x[3][1],x[4][3]):
return False
if not are_connected(x[4][1],x[5][3]):
return False
if not are_connected(x[3][2],x[6][0]):
return False
if not are_connected(x[4][2],x[7][0]):
return False
if not are_connected(x[5][2],x[8][0]):
return False
if not are_connected(x[6][1],x[7][3]):
return False
if not are_connected(x[7][1],x[8][3]):
return False
else:
return True
def are_connected(x,y):
if (x == 0 and y == 1 or x == 1 and y == 0 or x == 2 and y == 3 or x == 3 and y == 2 or x == 4 and y == 5 or x == 5 and y == 4 or x == 6 and y == 7 or x == 7 and y == 6):
return True
return False
#MAIN LOOP
count = 0
s = 0
while not(solved):
pieces = rand_s(pieces)
#print("not solved.")
count += 1
if is_solved(pieces):
print("solved.")
s += 1
f.write("Solved " + str(s) + "\n")
f.write("data: " + repr(str(pieces)) + "\n")
f.write("count: " + str(count) + "\n")
f.write("\n\n")
f.flush()
count = 0 | [
[
8,
0,
0.1102,
0.2126,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2205,
0.0079,
0,
0.66,
0.0769,
715,
0,
1,
0,
0,
715,
0,
0
],
[
14,
0,
0.2283,
0.0079,
0,
0.6... | [
"\"\"\"\nstart north rotate clockwise\n\n0 = in arrow pointing in\n1 = out arrow pointing out\n2 = in arrow pointing out\n3 = out arrow pointing in\n4 = out cross",
"import random",
"f = open(\"output.txt\", \"w\")",
"pieces = [\n [0,5,3,3],\n [1,0,7,4],\n [4,2,5,1],\n [2,5,3,6],\n [6,7,5,4],\n... |
#The TSP problem
#created by Logan Rooper/Quinn Millegan - Riverdale High School - logan.rooper@gmail.com
#Hill Climber
#JusticeForAaronSwartz
import random
import math
################################################################################################
cycles = int(input("How many iterations do you want? >")) #INCREASE THIS TO INCREASE ITERATIONS#
num_cities = int(input("How many cities do you want? >")) #SET NUMBER OF CITIES #
################################################################################################
#Setting up the problem
print("Setting up the problem")
cities=[] #the regular city map
h_cities=[] #the highscore city map
#Generate num_cities random cities
#Cities should be in a X by Y array (0-9 coordinates
#Coordinates can be 101 through 199 (1 is the octal padding bit)
print("There are "+str(len(cities))+" cities.")
citiesX=(random.sample(range(0,9),num_cities))
citiesY=(random.sample(range(0,9),num_cities))
print(str(citiesX))
print(str(citiesY))
for i in (range(0,num_cities)):
print("City "+str(i+1)+" is X: "+str(citiesX[i])+" Y: "+str(citiesY[i]))
'''
cities=(random.sample(range(100,199), num_cities))
for x in range(0,num_cities):
print("Making city "+str(x)+".")
print("City "+str(x)+" is X: "+str(cities[x])[1]+" and Y:"+str(cities[x])[2])
'''
print("There are now "+str(num_cities)+" cities.")
#draw city map
'''
print("PRINT MAP")
#iterate through all coordinates
row = ""
count = 1
for z in range(100,199):
if z in cities:
row += "--*--|"
else:
row += "-----|"
if count == 10: #rows is the width of the map...unsused because of our integer data limits
row += "\n"
count = 0
count += 1
print(row)
'''
print("Ready to create and run the Hill Climber algorithm??")
i = input(">")
#Create and run the algorithm
print("Creating/running the algorithm.")
high = 10000000.0 #arbitrarily high float value
done = False
i = 0
while (done != True):
print("Finding first path "+str(i))
helpnum=random.randint(0,num_cities-1)
print(str(helpnum))
p1x=citiesX[helpnum]
p1y=citiesY[helpnum]
print(str(p1x))
print(str(p1y))
#x2=citiesX[]
x1=p1x
#y2=citiesY[]
y1=p1y
for x in range(0,num_cities-1):
maybe = math.sqrt(abs(int(citiesX[x])-int(x1))**2+abs(int(citiesY[x])-int(y1))**2)
print(str(maybe))
if maybe <= high:
high = maybe
print("High is "+str(high))
p1x = citiesX[x]
p1y = citiesY[x]
print()
print("Shortest path found was "+str(high)+" units long.")
'''
print("PRINT MAP") #map of h_cities
row = ""
count = 1
for z in range(100,199):
if z in h_cities:
if cities.index(z) < 10:
cit = "0"+str(cities.index(z))
else:
cit = str(cities.index(z))
row += "--"+cit+"-|"
else:
row += "-----|"
if count == 10:
row += "\n"
count = 0
count += 1
print(row)
'''
#EOF
| [
[
1,
0,
0.0459,
0.0092,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.055,
0.0092,
0,
0.66,
0.04,
526,
0,
1,
0,
0,
526,
0,
0
],
[
14,
0,
0.0826,
0.0092,
0,
0.... | [
"import random",
"import math",
"cycles = int(input(\"How many iterations do you want? >\")) #INCREASE THIS TO INCREASE ITERATIONS#",
"num_cities = int(input(\"How many cities do you want? >\")) #SET NUMBER OF CITIES #",
"print(\"Setting up the problem\")",
"cities=[] #the regular city map... |
# Ler um vetor de 10 nomes
nome = 10*[""]
for i in range(10):
nome[i] = input('Nome: ')
nome_a_procurar = input('Nome a pesquisar: ')
encontrado = False
for j in range(10):
if nome[j] == nome_a_procurar:
encontrado = True
if encontrado:
print('Nome encontrado.')
else:
print('Nome não encontrado.')
| [
[
14,
0,
0.15,
0.05,
0,
0.66,
0,
525,
4,
0,
0,
0,
0,
0,
0
],
[
6,
0,
0.275,
0.1,
0,
0.66,
0.2,
826,
3,
0,
0,
0,
0,
0,
2
],
[
14,
1,
0.3,
0.05,
1,
0.09,
0,
0... | [
"nome = 10*[\"\"]",
"for i in range(10):\n nome[i] = input('Nome: ')",
" nome[i] = input('Nome: ')",
"nome_a_procurar = input('Nome a pesquisar: ')",
"encontrado = False",
"for j in range(10):\n if nome[j] == nome_a_procurar:\n encontrado = True",
" if nome[j] == nome_a_procurar:\n ... |
'''
Fazer um programa que leia 4 notas de 5 alunos e, ao final, informe:
* A média de notas de cada um dos alunos
* A maior nota de cada um deles
* Em que mês (0, 1, 2 ou 3) os alunos obtiveram as melhores notas, na média.
'''
| [
[
8,
0,
0.5833,
1,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
]
] | [
"'''\nFazer um programa que leia 4 notas de 5 alunos e, ao final, informe:\n * A média de notas de cada um dos alunos\n * A maior nota de cada um deles\n * Em que mês (0, 1, 2 ou 3) os alunos obtiveram as melhores notas, na média.\n'''"
] |
'''
Fazer um programa que leia 8 notas de um aluno e informe:
* maior nota
* menor nota
* média das notas
* bimestre da maior nota
'''
# Criação do vetor de notas
nota = 8*[0]
# Leitura do vetor de notas
for k in range(8):
print('Nota[', i+1,'] = ', end='')
nota[k] = int(input())
# Processamento das notas
maior_nota = nota[0]
pos_maior = nota[0]
menor_nota = nota[0]
soma_notas = nota[0]
for i in range(8):
# soma_notas = nota[0] + nota[1] + ... + nota[7]
soma_notas += nota[i]
if nota[i] > maior_nota:
maior_nota = nota[i]
pos_maior = nota[0]
if nota[i] < menor_nota:
menor_nota = nota[i]
# fim-laço
media_notas = soma_notas/8
print('A maior nota lida foi', maior_nota)
print('A menor nota lida foi', menor_nota)
print('A média das notas vale', media_notas)
print('A maior nota pertence ao ',
(pos_maior//2)+1,
'º bimestre.',
end='')
| [
[
8,
0,
0.093,
0.1628,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.2326,
0.0233,
0,
0.66,
0.0833,
686,
4,
0,
0,
0,
0,
0,
0
],
[
6,
0,
0.3256,
0.0698,
0,
0.66,
... | [
"'''\nFazer um programa que leia 8 notas de um aluno e informe:\n * maior nota\n * menor nota\n * média das notas\n * bimestre da maior nota\n'''",
"nota = 8*[0]",
"for k in range(8):\n print('Nota[', i+1,'] = ', end='')\n nota[k] = int(input())",
" print('Nota[', i+1,'] = ', end='')",
" not... |
cont = 0
numero = 10*[0]
while cont < 10:
numero[cont] = int(input('Entre com um número: '))
cont += 1
cont = 9
while cont >= 0:
print(numero[cont])
cont -= 1
| [
[
14,
0,
0.1111,
0.1111,
0,
0.66,
0,
729,
1,
0,
0,
0,
0,
1,
0
],
[
14,
0,
0.2222,
0.1111,
0,
0.66,
0.25,
400,
4,
0,
0,
0,
0,
0,
0
],
[
5,
0,
0.4444,
0.3333,
0,
0.66... | [
"cont = 0",
"numero = 10*[0]",
"while cont < 10:\n numero[cont] = int(input('Entre com um número: '))\n cont += 1",
" numero[cont] = int(input('Entre com um número: '))",
"cont = 9",
"while cont >= 0:\n print(numero[cont])\n cont -= 1",
" print(numero[cont])"
] |
# Faça um Programa que leia um vetor de 5
# números inteiros e mostre-os.
cont = 0
vetor_numeros = 5*[0]
# Ler os elementos do vetor
while cont < 5:
vetor_numeros[cont] = int(input('Entre com um número: '))
cont += 1
cont = 0
while cont < 5:
print(vetor_numeros[cont])
cont += 1
| [
[
14,
0,
0.2353,
0.0588,
0,
0.66,
0,
729,
1,
0,
0,
0,
0,
1,
0
],
[
14,
0,
0.2941,
0.0588,
0,
0.66,
0.25,
676,
4,
0,
0,
0,
0,
0,
0
],
[
5,
0,
0.5294,
0.1765,
0,
0.66... | [
"cont = 0",
"vetor_numeros = 5*[0]",
"while cont < 5:\n vetor_numeros[cont] = int(input('Entre com um número: '))\n cont += 1",
" vetor_numeros[cont] = int(input('Entre com um número: '))",
"cont = 0",
"while cont < 5:\n print(vetor_numeros[cont])\n cont += 1",
" print(vetor_numeros[co... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# Programa que cria uma pasta para salvar os exemplos de aula de hoje
import os, time
nomePasta = time.strftime("%Y-%m-%d")
if not os.path.exists(nomePasta):
os.mkdir(nomePasta)
os.chdir(nomePasta)
os.system('/bin/bash')
| [
[
1,
0,
0.3333,
0.0667,
0,
0.66,
0,
688,
0,
2,
0,
0,
688,
0,
0
],
[
14,
0,
0.4667,
0.0667,
0,
0.66,
0.25,
720,
3,
1,
0,
0,
668,
10,
1
],
[
4,
0,
0.6333,
0.1333,
0,
... | [
"import os, time",
"nomePasta = time.strftime(\"%Y-%m-%d\")",
"if not os.path.exists(nomePasta):\n os.mkdir(nomePasta)",
" os.mkdir(nomePasta)",
"os.chdir(nomePasta)",
"os.system('/bin/bash')"
] |
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
import sys
import os
import http.server
import webbrowser
print('Executando o servidor Web na pasta "{}"'.format(os.getcwd()))
if webbrowser.open('http://127.0.0.1:8000'):
http.server.test(HandlerClass=http.server.CGIHTTPRequestHandler)
| [
[
1,
0,
0.3333,
0.0833,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.4167,
0.0833,
0,
0.66,
0.2,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.5,
0.0833,
0,
0.66,
... | [
"import sys",
"import os",
"import http.server",
"import webbrowser",
"print('Executando o servidor Web na pasta \"{}\"'.format(os.getcwd()))",
"if webbrowser.open('http://127.0.0.1:8000'):\n http.server.test(HandlerClass=http.server.CGIHTTPRequestHandler)",
" http.server.test(HandlerClass=http.se... |
# Faça um programa que leia duas matrizes 2x2 e
# mostre o resultado da soma delas.
from pprint import pprint
matrizA = [[0,0],
[0, 0]]
matrizB = [[0, 0],
[0, 0]]
matrizC = [[0, 0],
[0, 0]]
# Leitura da matrizA
for i in range(2):
for j in range(2):
print('matrizA[', i, '][', j, '] = ', sep='', end='')
matrizA[i][j] = int(input())
# Leitura da matrizB
for i in range(2):
for j in range(2):
print('matrizB[', i, '][', j, '] = ', sep='', end='')
matrizB[i][j] = int(input())
for i in range(2):
for j in range(2):
matrizC[i][j] = matrizA[i][j] + matrizB[i][j]
pprint(matrizC)
| [
[
1,
0,
0.1333,
0.0333,
0,
0.66,
0,
276,
0,
1,
0,
0,
276,
0,
0
],
[
14,
0,
0.1833,
0.0667,
0,
0.66,
0.1429,
496,
0,
0,
0,
0,
0,
5,
0
],
[
14,
0,
0.2833,
0.0667,
0,
... | [
"from pprint import pprint",
"matrizA = [[0,0],\n [0, 0]]",
"matrizB = [[0, 0],\n [0, 0]]",
"matrizC = [[0, 0],\n [0, 0]]",
"for i in range(2):\n for j in range(2):\n print('matrizA[', i, '][', j, '] = ', sep='', end='')\n matrizA[i][j] = int(input())",
" ... |
matriz = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]]
for i in range(3):
for j in range(4):
print(matriz[i][j], end='\t')
#print('{0:2}'.format(matriz[i][j]),
# end=' ')
print()
| [
[
14,
0,
0.1818,
0.2727,
0,
0.66,
0,
24,
0,
0,
0,
0,
0,
5,
0
],
[
6,
0,
0.6818,
0.5455,
0,
0.66,
1,
826,
3,
0,
0,
0,
0,
0,
4
],
[
6,
1,
0.5909,
0.1818,
1,
0.03,
... | [
"matriz = [[1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12]]",
"for i in range(3):\n for j in range(4):\n print(matriz[i][j], end='\\t')\n #print('{0:2}'.format(matriz[i][j]),\n # end=' ')\n print()",
" for j in range(4):\n print(matriz[i][j], end='\\t'... |
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
# Faça um programa para ler e uma matriz 4x4 e exibi-la ao final.
matrizA = [4*[0] for i in range(4)]
# Leitura da matriz
for i in range(4):
for j in range(4):
print('matriz[',i,'][', j, '] = ', sep='', end='')
matrizA[i][j] = tipo(input())
for i in range(4):
for j in range(4):
print(matrizA[i][j], end=' ')
print()
| [
[
14,
0,
0.3158,
0.0526,
0,
0.66,
0,
496,
5,
0,
0,
0,
0,
0,
1
],
[
6,
0,
0.5526,
0.2105,
0,
0.66,
0.5,
826,
3,
0,
0,
0,
0,
0,
5
],
[
6,
1,
0.5789,
0.1579,
1,
0.37,
... | [
"matrizA = [4*[0] for i in range(4)]",
"for i in range(4):\n for j in range(4):\n print('matriz[',i,'][', j, '] = ', sep='', end='')\n matrizA[i][j] = tipo(input())",
" for j in range(4):\n print('matriz[',i,'][', j, '] = ', sep='', end='')\n matrizA[i][j] = tipo(input())",
"... |
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
# Faça um programa para ler duas matrizes 4x4 e mostrar sua soma.
matrizA = [4*[0] for i in range(4)]
matrizB = [4*[0] for i in range(4)]
matrizC = [4*[0] for i in range(4)]
# Leitura das matrizes
for i in range(4):
for j in range(4):
print('matrizA[',i,'][', j, '] = ', sep='', end='')
matrizA[i][j] = tipo(input())
for i in range(4):
for j in range(4):
print('matrizB[',i,'][', j, '] = ', sep='', end='')
matrizB[i][j] = tipo(input())
# Cálculo da soma
for i in range(4):
for j in range(4):
matrizC[i][j] = matrizA[i][j] + matrizB[i][j]
for i in range(4):
for j in range(4):
print(matrizC[i][j], end=' ')
print()
| [
[
14,
0,
0.2,
0.0333,
0,
0.66,
0,
496,
5,
0,
0,
0,
0,
0,
1
],
[
14,
0,
0.2333,
0.0333,
0,
0.66,
0.1667,
961,
5,
0,
0,
0,
0,
0,
1
],
[
14,
0,
0.2667,
0.0333,
0,
0.66... | [
"matrizA = [4*[0] for i in range(4)]",
"matrizB = [4*[0] for i in range(4)]",
"matrizC = [4*[0] for i in range(4)]",
"for i in range(4):\n for j in range(4):\n print('matrizA[',i,'][', j, '] = ', sep='', end='')\n matrizA[i][j] = tipo(input())",
" for j in range(4):\n print('matri... |
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
# Faça um programa para ler uma matriz n(x)m e mostrar o resultado de seu produto por um número real "x".
matrizA = [4*[0] for i in range(4)]
x = float(input('Entre com um número real: '))
# Leitura da matriz
for i in range(4):
for j in range(4):
print('matriz[',i,'][', j, '] = ', sep='', end='')
matrizA[i][j] = tipo(input())
for i in range(4):
for j in range(4):
print(x*matrizA[i][j], end=' ')
print()
| [
[
14,
0,
0.3,
0.05,
0,
0.66,
0,
496,
5,
0,
0,
0,
0,
0,
1
],
[
14,
0,
0.35,
0.05,
0,
0.66,
0.3333,
190,
3,
1,
0,
0,
639,
10,
2
],
[
6,
0,
0.575,
0.2,
0,
0.66,
0.... | [
"matrizA = [4*[0] for i in range(4)]",
"x = float(input('Entre com um número real: '))",
"for i in range(4):\n for j in range(4):\n print('matriz[',i,'][', j, '] = ', sep='', end='')\n matrizA[i][j] = tipo(input())",
" for j in range(4):\n print('matriz[',i,'][', j, '] = ', sep='', ... |
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
# Faça um programa para ler duas matrizes 4x4 e mostrar seu produto.
matrizA = [4*[0] for i in range(4)]
matrizB = [4*[0] for i in range(4)]
matrizC = [4*[0] for i in range(4)]
# Leitura das matrizes
for i in range(4):
for j in range(4):
print('matrizA[',i,'][', j, '] = ', sep='', end='')
matrizA[i][j] = tipo(input())
for i in range(4):
for j in range(4):
print('matrizB[',i,'][', j, '] = ', sep='', end='')
matrizB[i][j] = tipo(input())
# Cálculo da produto
for i in range(4):
for j in range(4):
matrizC[i][j] = 0
for k in range(4):
# Se não for isso, é algo parecido
matrizC[i][j] += matrizA[i][k]*matrizB[k][j]
for i in range(4):
for j in range(4):
print(matrizC[i][j], end=' ')
print()
| [
[
14,
0,
0.1818,
0.0303,
0,
0.66,
0,
496,
5,
0,
0,
0,
0,
0,
1
],
[
14,
0,
0.2121,
0.0303,
0,
0.66,
0.1667,
961,
5,
0,
0,
0,
0,
0,
1
],
[
14,
0,
0.2424,
0.0303,
0,
0... | [
"matrizA = [4*[0] for i in range(4)]",
"matrizB = [4*[0] for i in range(4)]",
"matrizC = [4*[0] for i in range(4)]",
"for i in range(4):\n for j in range(4):\n print('matrizA[',i,'][', j, '] = ', sep='', end='')\n matrizA[i][j] = tipo(input())",
" for j in range(4):\n print('matri... |
#Criação de uma matriz:
'''
identificadorMatriz = [
num_colunas*[valorNuloTipo]
for _ in range(num_linhas)
]
Onde:
* identificadorMatriz: nome da variável que guardará matriz
* num_colunas: número de colunas da matriz
* num_linhas: número de linhas da matriz
* valorNuloTipo:
- 0 para o tipo inteiro
- 0.0 para o tipo real
- '' para o tipo cadeia de caracteres
- False para o tipo lógico
'''
# Leitura dos elementos de uma matriz
for i in range(num_linhas):
for j in range(num_colunas):
print('identificadorMatriz[',i,'][', j, '] = ',
sep='',
end='')
identificadorMatriz[i][j] = tipo(input())
#Exibição de uma matriz de maneira bonita:
for i in range(num_linhas):
for j in range(num_colunas):
print(identificadorMatriz[i][j], end=' ')
print()
# Faça um programa para ler e uma matriz 4x4 e exibi-la ao final.
# Faça um programa para ler uma matriz n(x)m e exibi-la ao final.
# Faça um programa para ler duas matrizes 4x4 e mostrar sua soma.
# Faça um programa para ler uma matriz n(x)m e mostrar o resultado de seu produto por um número real "x".
# Faça um programa para ler duas matrizes 4x4 e mostrar seu produto.
| [
[
8,
0,
0.2432,
0.4054,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
6,
0,
0.5541,
0.1622,
0,
0.66,
0.5,
826,
3,
0,
0,
0,
0,
0,
5
],
[
6,
1,
0.5676,
0.1351,
1,
0.8,
... | [
"'''\n identificadorMatriz = [\n num_colunas*[valorNuloTipo] \n for _ in range(num_linhas) \n ]\n Onde:\n * identificadorMatriz: nome da variável que guardará matriz\n * num_colunas: número de colunas da matriz",
"for i in range(... |
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
# Faça um programa para ler uma matriz n(x)m e exibi-la ao final.
num_linhas = int(input('Número de linhas da matriz: '))
num_colunas = int(input('Número de colunas da matriz: '))
matrizA = [num_colunas*[0] for i in range(num_linhas)]
# Leitura da matriz
for i in range(num_linhas):
for j in range(num_colunas):
print('matrizA[',i,'][', j, '] = ', sep='', end='')
matrizA[i][j] = tipo(input())
for i in range(num_linhas):
for j in range(num_colunas):
print(matrizA[i][j], end=' ')
print()
| [
[
14,
0,
0.3,
0.05,
0,
0.66,
0,
109,
3,
1,
0,
0,
901,
10,
2
],
[
14,
0,
0.35,
0.05,
0,
0.66,
0.25,
762,
3,
1,
0,
0,
901,
10,
2
],
[
14,
0,
0.45,
0.05,
0,
0.66,
... | [
"num_linhas = int(input('Número de linhas da matriz: '))",
"num_colunas = int(input('Número de colunas da matriz: '))",
"matrizA = [num_colunas*[0] for i in range(num_linhas)]",
"for i in range(num_linhas):\n for j in range(num_colunas):\n print('matrizA[',i,'][', j, '] = ', sep='', end='')\n ... |
# Série de Fibonacci exibida em ordem inversa
n = int(input('Número de elementos a exibir: '))
termo = n*[0]
# Gera os termos da sequencia
if n == 1:
termo[0] = 1
elif n >= 2:
termo[0] = 1
termo[1] = 1
for i in range(2,n):
termo[i] = termo[i-1] + termo[i-2]
# Exibe os termos em ordem inversa
for k in range(n-1, -1, -1):
print(termo[k], end=' ')
print()
| [
[
14,
0,
0.1905,
0.0476,
0,
0.66,
0,
773,
3,
1,
0,
0,
901,
10,
2
],
[
14,
0,
0.2857,
0.0476,
0,
0.66,
0.25,
781,
4,
0,
0,
0,
0,
0,
0
],
[
4,
0,
0.5714,
0.3333,
0,
0... | [
"n = int(input('Número de elementos a exibir: '))",
"termo = n*[0]",
"if n == 1:\n termo[0] = 1\nelif n >= 2:\n termo[0] = 1\n termo[1] = 1\n for i in range(2,n):\n termo[i] = termo[i-1] + termo[i-2]",
" termo[0] = 1",
"elif n >= 2:\n termo[0] = 1\n termo[1] = 1\n for i in ran... |
# Ler 10 números e exibi-los em ordem inversa à da leitura
numero = 10*[0]
# Leitura dos 10 números
for k in range(0, 10, 1):
numero[k] = int(input())
# Exibição em ordem inversa
for i in range(9, -1, -1):
print(numero[i])
| [
[
14,
0,
0.2667,
0.0667,
0,
0.66,
0,
400,
4,
0,
0,
0,
0,
0,
0
],
[
6,
0,
0.5,
0.1333,
0,
0.66,
0.5,
954,
3,
0,
0,
0,
0,
0,
3
],
[
14,
1,
0.5333,
0.0667,
1,
0.75,
... | [
"numero = 10*[0]",
"for k in range(0, 10, 1):\n numero[k] = int(input())",
" numero[k] = int(input())",
"for i in range(9, -1, -1):\n print(numero[i])",
" print(numero[i])"
] |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
'''Faça um programa que leia vários números inteiros e ao final mostre a soma dos números pares
lidos. Seu programa deverá encerrar quando o usuário entrar com o número 0.'''
print ('Entre com vaŕios números inteiros para somar os pares.')
print ('Digite o número "0" para sair.')
numero = int(input('Número inteiro: '))
soma = 0
while numero != 0:
if (numero % 2) == 0:
soma += numero
numero = int(input('Número inteiro: '))
print ('A soma dos números pares lidos é', soma)
| [
[
8,
0,
0.1731,
0.0769,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
8,
0,
0.2692,
0.0385,
0,
0.66,
0.1667,
535,
3,
1,
0,
0,
0,
0,
1
],
[
8,
0,
0.3077,
0.0385,
0,
0.66,
... | [
"'''Faça um programa que leia vários números inteiros e ao final mostre a soma dos números pares\nlidos. Seu programa deverá encerrar quando o usuário entrar com o número 0.'''",
"print ('Entre com vaŕios números inteiros para somar os pares.')",
"print ('Digite o número \"0\" para sair.')",
"numero = int(inp... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
'''Faça um programa que leia os votos para 3 candidatos.
Ao final, seu programa deverá mostrar:
* o nome do candidato eleito,
* a quantidade de votos obtidos e
* o percentual de votos obtidos.
Seu programa encerrará quando o usuário entrar com o voto 0.
Os votos vão de 1 a 3, e o nome dos candidatos são:
1- Maria, 2- João e 3- Pedro'''
votosMaria = 0
votosJoao = 0
votosPedro = 0
votosNulo = 0
avisoEntrada = '''Em quem você deseja votar?
1- Maria
2- João
3- Pedro
0- Sair
Seu voto: '''
voto = int(input(avisoEntrada))
while voto != 0:
if voto == 1:
votosMaria += 1
elif voto == 2:
votosJoao += 1
elif voto == 3:
votosPedro += 1
else:
votosNulo += 1
#fim-se
voto = int(input(avisoEntrada))
# fim-enquanto
totalVotos = votosMaria + votosJoao + votosPedro + votosNulo
if (votosMaria > votosJoao) and (votosMaria > votosPedro):
print('Maria foi a vencedora. Ela obteve', votosMaria,
'votos de um total de', totalVotos)
print('Maria venceu com', votosMaria/totalVotos*100, '% dos votos', sep='')
elif (votosJoao > votosMaria) and (votosJoao > votosPedro):
print('João foi o vencedor. Ele obteve', votosJoao,
'votos de um total de', totalVotos)
print('João venceu com', votosJoao/totalVotos*100, '% dos votos', sep='')
elif (votosPedro > votosMaria) and (votosPedro > votosJoao):
print('Pedro foi o vencedor. Ele obteve', votosPedro,
'votos de um total de', totalVotos)
print('Pedro venceu com', votosPedro/totalVotos*100, '% dos votos', sep='')
else:
print('Houve empate. Teremos segundo turno.')
| [
[
8,
0,
0.1466,
0.1724,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.2586,
0.0172,
0,
0.66,
0.1111,
183,
1,
0,
0,
0,
0,
1,
0
],
[
14,
0,
0.2759,
0.0172,
0,
0.66... | [
"'''Faça um programa que leia os votos para 3 candidatos.\nAo final, seu programa deverá mostrar:\n* o nome do candidato eleito,\n* a quantidade de votos obtidos e\n* o percentual de votos obtidos.\n\nSeu programa encerrará quando o usuário entrar com o voto 0.",
"votosMaria = 0",
"votosJoao = 0",
"votosPedro... |
import turtle
turtle.shape('turtle')
for i in range(4):
turtle.forward(100)
turtle.right(90)
turtle.done()
| [
[
1,
0,
0.1429,
0.1429,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
8,
0,
0.2857,
0.1429,
0,
0.66,
0.3333,
381,
3,
1,
0,
0,
0,
0,
1
],
[
6,
0,
0.5714,
0.4286,
0,
0.... | [
"import turtle",
"turtle.shape('turtle')",
"for i in range(4):\n turtle.forward(100)\n turtle.right(90)",
" turtle.forward(100)",
" turtle.right(90)",
"turtle.done()"
] |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# Exemplo de contador
contador = 0
while contador < 3:
contador += 1
| [
[
14,
0,
0.75,
0.125,
0,
0.66,
0,
265,
1,
0,
0,
0,
0,
1,
0
],
[
5,
0,
0.9375,
0.25,
0,
0.66,
1,
0,
0,
0,
0,
0,
0,
0,
0
]
] | [
"contador = 0",
"while contador < 3:\n contador += 1"
] |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# Exemplo de acumulador
contador = 0
acumulador = 0
while contador < 3:
contador += 1
num = int(input())
acumulador += num
| [
[
14,
0,
0.4286,
0.0714,
0,
0.66,
0,
265,
1,
0,
0,
0,
0,
1,
0
],
[
14,
0,
0.5,
0.0714,
0,
0.66,
0.5,
935,
1,
0,
0,
0,
0,
1,
0
],
[
5,
0,
0.75,
0.2857,
0,
0.66,
... | [
"contador = 0",
"acumulador = 0",
"while contador < 3:\n contador += 1\n num = int(input())\n acumulador += num",
" num = int(input())"
] |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
num = 1
soma = 0
produto = 1
while num <= 10:
if num % 2 == 0:
soma += num
else:
produto *= num
num += 1
| [
[
14,
0,
0.2857,
0.0714,
0,
0.66,
0,
328,
1,
0,
0,
0,
0,
1,
0
],
[
14,
0,
0.3571,
0.0714,
0,
0.66,
0.3333,
767,
1,
0,
0,
0,
0,
1,
0
],
[
14,
0,
0.4286,
0.0714,
0,
0... | [
"num = 1",
"soma = 0",
"produto = 1",
"while num <= 10:\n if num % 2 == 0:\n soma += num\n else:\n produto *= num\n \n num += 1",
" if num % 2 == 0:\n soma += num\n else:\n produto *= num"
] |
n = int(input('Quantos cadastros você deseja fazer? '))
nome = n*['']
for i in range(n):
nome[i] = input('Nome: ')
| [
[
14,
0,
0.25,
0.25,
0,
0.66,
0,
773,
3,
1,
0,
0,
901,
10,
2
],
[
14,
0,
0.5,
0.25,
0,
0.66,
0.5,
525,
4,
0,
0,
0,
0,
0,
0
],
[
6,
0,
0.875,
0.5,
0,
0.66,
1,
... | [
"n = int(input('Quantos cadastros você deseja fazer? '))",
"nome = n*['']",
"for i in range(n):\n nome[i] = input('Nome: ')",
" nome[i] = input('Nome: ')"
] |
cont = 0
n = 1
for letra in 'abcdefghijklmnopqrstuvwxyz':
print(letra, end=' ')
cont += 1
if (cont % n) == 0:
print()
cont = 0
n += 1
| [
[
14,
0,
0.1111,
0.1111,
0,
0.66,
0,
729,
1,
0,
0,
0,
0,
1,
0
],
[
14,
0,
0.2222,
0.1111,
0,
0.66,
0.5,
773,
1,
0,
0,
0,
0,
1,
0
],
[
6,
0,
0.6667,
0.7778,
0,
0.66,... | [
"cont = 0",
"n = 1",
"for letra in 'abcdefghijklmnopqrstuvwxyz':\n print(letra, end=' ')\n cont += 1\n if (cont % n) == 0:\n print()\n cont = 0\n n += 1",
" print(letra, end=' ')",
" if (cont % n) == 0:\n print()\n cont = 0\n n += 1",
" print... |
'''Faça um programa que leia os dados abaixo para 10 pessoas:
* nome
* altura
* idade
'''
# Iniciar os vetores
nome = 5*['']
idade = 5*[0]
altura = 5*[0.0]
# Popular os vetores
for i in range(5):
print('Entre com os dados da ', i+1, 'ª pessoa...', sep='')
nome[i] = input('Nome: ')
idade[i] = int(input('Idade: '))
altura[i] = float(input('Altura: '))
| [
[
8,
0,
0.1765,
0.2941,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.4706,
0.0588,
0,
0.66,
0.25,
525,
4,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.5294,
0.0588,
0,
0.66,
... | [
"'''Faça um programa que leia os dados abaixo para 10 pessoas:\n * nome\n * altura\n * idade\n'''",
"nome = 5*['']",
"idade = 5*[0]",
"altura = 5*[0.0]",
"for i in range(5):\n print('Entre com os dados da ', i+1, 'ª pessoa...', sep='')\n nome[i] = input('Nome: ')\n idade[i] = int(input('Id... |
numero = 1
while numero < 17:
print(numero, end=' ')
numero += 1
| [
[
14,
0,
0.25,
0.25,
0,
0.66,
0,
400,
1,
0,
0,
0,
0,
1,
0
],
[
5,
0,
0.75,
0.75,
0,
0.66,
1,
0,
0,
0,
0,
0,
0,
0,
1
],
[
8,
1,
0.75,
0.25,
1,
0.31,
0,
535,
... | [
"numero = 1",
"while numero < 17:\n print(numero, end=' ')\n numero += 1",
" print(numero, end=' ')"
] |
# Faça um programa em Python que mostre os números
# inteiros de 1 a 20
# Faça um programa em Python que mostre os números
# inteiros de 20 a 1
# Faça um programa que mostre a tabuada de adição do
# número 3.
# Faça um programa que mostre a tabuada de adição dos
# números de 1 a 9
| [] | [] |
# O que faz este programa?
nome = input('Nome: ')
while nome != '':
print(nome)
nome = input('Nome: ') | [
[
14,
0,
0.5,
0.125,
0,
0.66,
0,
525,
3,
1,
0,
0,
930,
10,
1
],
[
5,
0,
0.875,
0.375,
0,
0.66,
1,
0,
0,
0,
0,
0,
0,
0,
2
],
[
8,
1,
0.875,
0.125,
1,
0.76,
0,
... | [
"nome = input('Nome: ')",
"while nome != '':\n print(nome)\n nome = input('Nome: ')",
" print(nome)",
" nome = input('Nome: ')"
] |
numero = int(input('Entre com um número: '))
while numero != 0:
termo = 1
while termo <= 10:
print(numero, 'x', termo, '=', numero*termo)
termo += 1
numero = int(input('Entre com um número: '))
| [
[
14,
0,
0.0909,
0.0909,
0,
0.66,
0,
400,
3,
1,
0,
0,
901,
10,
2
],
[
5,
0,
0.5909,
0.7273,
0,
0.66,
1,
0,
0,
0,
0,
0,
0,
0,
3
],
[
14,
1,
0.3636,
0.0909,
1,
0.86,
... | [
"numero = int(input('Entre com um número: '))",
"while numero != 0:\n termo = 1\n\n while termo <= 10:\n print(numero, 'x', termo, '=', numero*termo)\n termo += 1\n\n numero = int(input('Entre com um número: '))",
" termo = 1",
" while termo <= 10:\n print(numero, 'x', term... |
# Faça um programa em Python que mostre os números
# inteiros de 1 a 20
num = 1
while num <= 20:
print(num, end=' ')
num += 1 | [
[
14,
0,
0.5714,
0.1429,
0,
0.66,
0,
328,
1,
0,
0,
0,
0,
1,
0
],
[
5,
0,
0.8571,
0.4286,
0,
0.66,
1,
0,
0,
0,
0,
0,
0,
0,
1
],
[
8,
1,
0.8571,
0.1429,
1,
0.26,
... | [
"num = 1",
"while num <= 20:\n print(num, end=' ')\n num += 1",
" print(num, end=' ')"
] |
# Faça um programa que mostre a tabuada de adição dos
# números de 1 a 9
termo1 = 1
while termo1 <= 10:
print('TABUADA DE ADIÇÃO DO NÚMERO', termo1)
termo2 = 1
while termo2 <= 10:
print(' ', termo1, '+', termo2, '=', termo1+termo2)
termo2 += 1
print()
termo1 += 1
# for termo1 in range(1, 11):
# for termo2 in range(1, 11):
# print(' ', termo1, '+', termo2, '=', termo1+termo2)
| [
[
14,
0,
0.2222,
0.0556,
0,
0.66,
0,
966,
1,
0,
0,
0,
0,
1,
0
],
[
5,
0,
0.5278,
0.5556,
0,
0.66,
1,
0,
0,
0,
0,
0,
0,
0,
3
],
[
8,
1,
0.3333,
0.0556,
1,
0.81,
... | [
"termo1 = 1",
"while termo1 <= 10:\n print('TABUADA DE ADIÇÃO DO NÚMERO', termo1)\n\n termo2 = 1\n while termo2 <= 10:\n print(' ', termo1, '+', termo2, '=', termo1+termo2)\n termo2 += 1",
" print('TABUADA DE ADIÇÃO DO NÚMERO', termo1)",
" termo2 = 1",
" while termo2 <= 10... |
numero = int(input('Entre com um número: '))
termo = 1
while termo <= 10:
print(numero, 'x', termo, '=', numero*termo)
termo += 1 | [
[
14,
0,
0.1429,
0.1429,
0,
0.66,
0,
400,
3,
1,
0,
0,
901,
10,
2
],
[
14,
0,
0.4286,
0.1429,
0,
0.66,
0.5,
781,
1,
0,
0,
0,
0,
1,
0
],
[
5,
0,
0.8571,
0.4286,
0,
0.... | [
"numero = int(input('Entre com um número: '))",
"termo = 1",
"while termo <= 10:\n print(numero, 'x', termo, '=', numero*termo)\n termo += 1",
" print(numero, 'x', termo, '=', numero*termo)"
] |
def soma(a: int, b: int) -> int:
return (a+b)
def principal():
x = int(input('x: '))
y = int(input('y: '))
print('A soma de', x, 'e', y, 'dá', soma(x,y))
if __name__ == '__main__':
principal()
else:
pass
| [
[
2,
0,
0.1071,
0.1429,
0,
0.66,
0,
767,
0,
2,
2,
0,
0,
0,
0
],
[
13,
1,
0.1429,
0.0714,
1,
0.85,
0,
0,
4,
0,
0,
0,
0,
0,
0
],
[
2,
0,
0.3929,
0.2857,
0,
0.66,
... | [
"def soma(a: int, b: int) -> int:\n return (a+b)",
" return (a+b)",
"def principal():\n x = int(input('x: '))\n y = int(input('y: '))\n print('A soma de', x, 'e', y, 'dá', soma(x,y))",
" x = int(input('x: '))",
" y = int(input('y: '))",
" print('A soma de', x, 'e', y, 'dá', soma(x,... |
# Faça um programa que mostre a tabuada de adição do
# número 3.
termo = 1
while termo <= 10:
print('3 +', termo, '=', 3+termo)
termo += 1 | [
[
14,
0,
0.5714,
0.1429,
0,
0.66,
0,
781,
1,
0,
0,
0,
0,
1,
0
],
[
5,
0,
0.8571,
0.4286,
0,
0.66,
1,
0,
0,
0,
0,
0,
0,
0,
1
],
[
8,
1,
0.8571,
0.1429,
1,
0.32,
... | [
"termo = 1",
"while termo <= 10:\n print('3 +', termo, '=', 3+termo)\n termo += 1",
" print('3 +', termo, '=', 3+termo)"
] |
# O que faz este programa?
nome = input('Nome: ')
while nome == '':
nome = input('Nome: ') | [
[
14,
0,
0.5714,
0.1429,
0,
0.66,
0,
525,
3,
1,
0,
0,
930,
10,
1
],
[
5,
0,
0.9286,
0.2857,
0,
0.66,
1,
0,
0,
0,
0,
0,
0,
0,
1
],
[
14,
1,
1,
0.1429,
1,
0.76,
0... | [
"nome = input('Nome: ')",
"while nome == '':\n nome = input('Nome: ')",
" nome = input('Nome: ')"
] |
altura = 1
largura = int(input('Largura: '))
while largura*altura != 0:
altura = int(input('Altura: '))
if altura != 0:
for i in range(largura):
print('+', end='')
print()
for j in range(altura-2):
print('+', end='')
for i in range(largura-2):
print(' ', end='')
print('+')
for i in range(largura):
print('+', end='')
print()
largura = int(input('Largura: '))
pass
| [
[
14,
0,
0.0526,
0.0526,
0,
0.66,
0,
190,
1,
0,
0,
0,
0,
1,
0
],
[
14,
0,
0.1053,
0.0526,
0,
0.66,
0.5,
615,
3,
1,
0,
0,
901,
10,
2
],
[
5,
0,
0.5789,
0.8947,
0,
0.... | [
"altura = 1",
"largura = int(input('Largura: '))",
"while largura*altura != 0:\n altura = int(input('Altura: '))\n if altura != 0:\n for i in range(largura):\n print('+', end='')\n print()\t\n for j in range(altura-2):\n print('+', end='')",
" altura = i... |
cont_pares = 0
cont_impares = 0
# inicialização da variável de controle *num*
num = int(input('Entre com um número inteiro: '))
# teste de interrupção do laço: num != 0
while 0 != num:
# bloco_enquanto
# se o número é par
if (num%2) == 0:
cont_pares = cont_pares+1
# se ele não é par, é porque ele é ímpar
else:
cont_impares = cont_impares+1
# atualização da variável de controle *num*
num = int(input('Entre com um número inteiro: '))
| [
[
14,
0,
0.0952,
0.0476,
0,
0.66,
0,
503,
1,
0,
0,
0,
0,
1,
0
],
[
14,
0,
0.1429,
0.0476,
0,
0.66,
0.3333,
75,
1,
0,
0,
0,
0,
1,
0
],
[
14,
0,
0.2857,
0.0476,
0,
0.... | [
"cont_pares = 0",
"cont_impares = 0",
"num = int(input('Entre com um número inteiro: '))",
"while 0 != num:\n # bloco_enquanto\n \n # se o número é par\n if (num%2) == 0:\n cont_pares = cont_pares+1\n # se ele não é par, é porque ele é ímpar\n else:",
" if (num%2) == 0:\n ... |
import cPickle;
usermod = None;
gatherEdges = 1; # by default: gather on incoming edges
scatterEdges = 2; # by default: scatter on outgoing edges
def initUserModule(name):
global usermod;
usermod = __import__(name);
global gatherEdges;
if "gatherEdges" in dir(usermod):
gatherEdges = usermod.gatherEdges;
global scatterEdges;
if "scatterEdges" in dir(usermod):
scatterEdges = usermod.scatterEdges;
return "edgeDataClass" in dir(usermod);
def newVertex():
return usermod.vertexDataClass();
def loadVertex(vertexWrap):
return cPickle.loads(vertexWrap);
def storeVertex(vertex):
return cPickle.dumps(vertex);
def newEdge():
return usermod.edgeDataClass();
def loadEdge(edgeWrap):
return cPickle.loads(edgeWrap);
def storeEdge(edge):
return cPickle.dumps(edge);
def newAgg():
return usermod.aggregatorClass();
def loadAgg(aggWrap):
return cPickle.loads(aggWrap);
def storeAgg(agg):
return cPickle.dumps(agg);
def gatherAgg(agg1, agg2):
agg1.merge(agg2);
return agg1;
def transformVertex(vertex):
return usermod.transformVertex(vertex);
def transformEdge(edge):
return usermod.transformEdge(edge);
def saveVertex(vertex):
return usermod.saveVertex(vertex);
def saveEdge(src, target, edge):
return usermod.saveEdge(src, target, edge);
def gather(srcData, targetData, edgeData, numIn, numOut):
return usermod.gather(srcData, targetData, edgeData, numIn, numOut);
def apply(targetData, agg, numIn, numOut):
return usermod.apply(targetData, agg, numIn, numOut);
def scatter(srcData, targetData, edgeData, numIn, numOut):
return usermod.scatter(srcData, targetData, edgeData, numIn, numOut);
def parseEdge(file, line):
return usermod.parseEdge(file, line);
| [
[
1,
0,
0.0135,
0.0135,
0,
0.66,
0,
279,
0,
1,
0,
0,
279,
0,
0
],
[
14,
0,
0.0405,
0.0135,
0,
0.66,
0.0455,
644,
1,
0,
0,
0,
0,
9,
0
],
[
14,
0,
0.0676,
0.0135,
0,
... | [
"import cPickle;",
"usermod = None;",
"gatherEdges = 1; # by default: gather on incoming edges",
"scatterEdges = 2; # by default: scatter on outgoing edges",
"def initUserModule(name):\n\tglobal usermod;\n\tusermod = __import__(name);\n\n\tglobal gatherEdges;\n\tif \"gatherEdges\" in dir(usermod):\n\t\tgat... |
class vertexDataClass:
pr = 1.0;
prDelta = 0.0;
def __init__(self, pr_new=1.0, delta_new=0.0):
self.pr = pr_new;
self.prDelta = delta_new;
class aggregatorClass:
sum = 0.0;
def __init__(self, sum_new=0.0):
self.sum = sum_new;
def merge(self, x):
self.sum += x.sum;
def parseEdge(file, line):
s = line.split();
srcId = int(s[0]);
destId = int(s[1]);
return (srcId, destId, None);
def transformVertex(vertex):
return vertexDataClass();
def saveVertex(vertex):
return str(vertex.pr)+":"+str(vertex.prDelta);
def gather(srcData, targetData, edgeData, numIn, numOut):
return aggregatorClass(0.85*srcData.pr/numOut);
def apply(targetData, aggInst, numIn, numOut):
newval = aggInst.sum+0.15;
delta = newval-targetData.pr;
return vertexDataClass(newval, delta);
def scatter(srcData, targetData, edgeData, numIn, numOut):
if abs(srcData.prDelta) > 0.01:
return (1.0, None, None);
else:
return (-1.0, None, None);
| [
[
3,
0,
0.0875,
0.15,
0,
0.66,
0,
760,
0,
1,
0,
0,
0,
0,
0
],
[
14,
1,
0.05,
0.025,
1,
0.75,
0,
37,
1,
0,
0,
0,
0,
2,
0
],
[
14,
1,
0.075,
0.025,
1,
0.75,
0.5,
... | [
"class vertexDataClass:\n\tpr = 1.0;\n\tprDelta = 0.0;\n\tdef __init__(self, pr_new=1.0, delta_new=0.0):\n\t\tself.pr = pr_new;\n\t\tself.prDelta = delta_new;",
"\tpr = 1.0;",
"\tprDelta = 0.0;",
"\tdef __init__(self, pr_new=1.0, delta_new=0.0):\n\t\tself.pr = pr_new;\n\t\tself.prDelta = delta_new;",
"\t\ts... |
#!/usr/bin/python
import sys
import os
import string
import subprocess
import time
"""
Usage: rpcexec -n n_to_start -f [hostsfile] [program] [options]
To start local only: rpcexec [program] [options]
"""
def escape(s):
s = string.replace(s, '"', '\\"')
s = string.replace(s, "'", "\\'")
return s
#enddef
# gui: if xterm should run
# machines: a vector of all the machines
# port: a vector of the port number for ssh to connect to. must be same length as machines
# machineid: The machineid to generate
# prog: program to run
# opts: options for the program
def get_ssh_cmd(gui, machines, port, machineid, prog, opts):
allmachines = '"' + string.join(machines, ',') + '"'
# construct the command line
cwd = os.getcwd()
if (gui):
sshcmd = 'ssh -X -Y -n -q '
else:
sshcmd = 'ssh -n -q '
#endif
guicmd = ''
if (gui):
guicmd = 'xterm -geometry 120x60 -e '
#endif
if (machines[i] == "localhost" or machines[i].startswith("127.")):
cmd = 'env SPAWNNODES=%s SPAWNID=%d %s %s' % (allmachines,i, prog, opts)
elif (port[i] == 22):
cmd = sshcmd + '%s "cd %s ; env SPAWNNODES=%s SPAWNID=%d %s %s %s"' % \
(machines[machineid], escape(cwd), escape(allmachines),machineid, \
guicmd, escape(prog), escape(opts))
else:
cmd = sshcmd + '-oPort=%d %s "cd %s ; env SPAWNNODES=%s SPAWNID=%d %s %s %s"' % \
(port[machineid], machines[machineid], escape(cwd), escape(allmachines), \
machineid, guicmd, escape(prog), escape(opts))
#endif
return cmd
#enddef
def get_screen_cmd(gui, machines, port, machineid, prog, opts):
allmachines = '"' + string.join(machines, ',') + '"'
# construct the command line
cwd = os.getcwd()
sshcmd = 'ssh -t '
#endif
guicmd = ''
if (machines[i] == "localhost" or machines[i].startswith("127.")):
cmd = ['export SPAWNNODES=%s SPAWNID=%d ; %s %s' % (allmachines,i, prog, opts)]
elif (port[i] == 22):
cmd = [sshcmd + '%s "cd %s ; export SPAWNNODES=%s SPAWNID=%d; %s %s %s ; bash -il"' % \
(machines[machineid], escape(cwd), escape(allmachines),machineid, \
guicmd, escape(prog), escape(opts))]
else:
cmd = [sshcmd + '-oPort=%d %s "cd %s ; export SPAWNNODES=%s SPAWNID=%d; %s %s %s ; bash -il"' % \
(port[machineid], machines[machineid], escape(cwd), escape(allmachines), \
machineid, guicmd, escape(prog), escape(opts))]
#endif
return cmd
#enddef
def shell_popen(cmd):
print cmd
return subprocess.Popen(cmd, shell=True)
#endif
def shell_wait_native(cmd):
print cmd
pid = subprocess.Popen(cmd, shell=True)
os.waitpid(pid.pid, 0)
#time.sleep(0.5)
#endif
nmachines = 0
hostsfile = ''
prog = ''
opts = ''
gui = 0
inscreen = 0
screenname = ''
printhelp = 0
i = 1
while(i < len(sys.argv)):
if sys.argv[i] == '-h' or sys.argv[i] == '--help':
printhelp = 1
break
elif sys.argv[i] == '-n':
nmachines = int(sys.argv[i+1])
i = i + 2
elif sys.argv[i] == '-f':
hostsfile = sys.argv[i+1]
i = i + 2
elif sys.argv[i] == '-g':
gui = 1
i = i + 1
elif sys.argv[i] == '-s':
inscreen = 1
screenname = sys.argv[i+1]
i = i + 2
else:
prog = sys.argv[i]
if (len(sys.argv) > i+1):
opts = string.join(sys.argv[(i+1):])
#endif
break
#endif
#endwhile
if inscreen and gui:
print ("-s and -g are mutually exclusive")
exit(0)
#endif
if (printhelp):
print
print("Usage: rpcexec -n [n_to_start] -f [hostsfile] [program] [options]")
print("To start local only: rpcexec [program] [options]")
print("Optional Arguments:")
print("-g: Launch the command within Xterm on all machines. ")
print("-s [screenname] : Launch a screen session and launch the")
print(" commands in each window in each window. Any ssh connections")
print(" are preserved on termination of the program with environment")
print(" properly set up for subsequent executions")
print("")
print("Note: -s [screenname] and -g are mutually exclusive")
exit(0)
#endif
if (nmachines == 0 and hostsfile == ''):
cmd = 'env SPAWNNODES=localhost SPAWNID=0 %s %s' % (prog, opts)
p = shell_popen(cmd)
os.waitpid(p.pid, 0)
exit(0)
#endif
print('Starting ' + str(nmachines) + ' machines')
print('Hosts file: ' + hostsfile)
print('Command Line to run: ' + prog + ' ' + opts)
# open the hosts file and read the machines
try:
f = open(hostsfile, 'r')
except:
print
print("Unable to open hosts file")
print
exit(0)
#endtry
machines = [''] * nmachines
port = [22] * nmachines
for i in range(nmachines):
try:
machines[i] = string.strip(f.readline())
colonsplit = string.split(machines[i], ':')
if (len(colonsplit) == 2):
machines[i] = string.strip(colonsplit[0])
port[i] = int(colonsplit[1])
#endif
except:
print
print("Unable to read line " + str(i+1) + " of hosts file")
print
exit(0)
#endfor
f.close()
# the commands to run to start for each node
cmd = [None] * nmachines
for i in range(nmachines):
if (inscreen == 0):
cmd[i] = get_ssh_cmd(gui, machines, port, i, prog, opts)
else:
cmd[i] = get_screen_cmd(gui, machines, port, i, prog, opts)
print cmd[i]
#endif
#endfor
if (inscreen == 0):
# now issue the ssh commands
procs = [None] * nmachines
for i in range(nmachines):
procs[i] = shell_popen(cmd[i])
#endfor
for i in range(nmachines):
os.waitpid(procs[i].pid, 0)
#endfor
else:
# create a new empty screen with the screen name
shell_wait_native("screen -h 10000 -d -m -S " + screenname)
shell_wait_native("screen -h 10000 -x %s -p 0 -X title %s" % (screenname, machines[0][0:8]))
# start a bunch of empty screens
for i in range(nmachines - 1):
shell_wait_native("screen -x %s -X screen -t %s" % (screenname, machines[i+1][0:8]))
#endfor
# set the titles in each one and run the program
# we stripe it across windows so if there are ssh commands they will
# have time to finish running first
for j in range(2):
for i in range(nmachines):
if (len(cmd[i]) > j and cmd[i][j] != None):
shell_wait_native("screen -x %s -p %d -X stuff %s" % (screenname, i, "'"+cmd[i][j]+"\n'"))
#endif
#endfor
#endfor
#endif
| [
[
1,
0,
0.0087,
0.0044,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0131,
0.0044,
0,
0.66,
0.0294,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0175,
0.0044,
0,
... | [
"import sys",
"import os",
"import string",
"import subprocess",
"import time",
"\"\"\"\nUsage: rpcexec -n n_to_start -f [hostsfile] [program] [options]\nTo start local only: rpcexec [program] [options]\n\"\"\"",
"def escape(s):\n s = string.replace(s, '\"', '\\\\\"')\n s = string.replace(s, \"'\", \"... |
#! python
import cxxtest.cxxtestgen
cxxtest.cxxtestgen.main()
| [
[
1,
0,
0.6,
0.2,
0,
0.66,
0,
686,
0,
1,
0,
0,
686,
0,
0
],
[
8,
0,
1,
0.2,
0,
0.66,
1,
624,
3,
0,
0,
0,
0,
0,
1
]
] | [
"import cxxtest.cxxtestgen",
"cxxtest.cxxtestgen.main()"
] |
#-------------------------------------------------------------------------
# CxxTest: A lightweight C++ unit testing library.
# Copyright (c) 2008 Sandia Corporation.
# This software is distributed under the LGPL License v2.1
# For more information, see the COPYING file in the top CxxTest directory.
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains certain rights in this software.
#-------------------------------------------------------------------------
import codecs
import re
#import sys
#import getopt
#import glob
from cxxtest.cxxtest_misc import abort
# Global variables
suites = []
suite = None
inBlock = 0
options=None
def scanInputFiles(files, _options):
'''Scan all input files for test suites'''
global options
options=_options
for file in files:
scanInputFile(file)
global suites
if len(suites) is 0 and not options.root:
abort( 'No tests defined' )
return [options,suites]
lineCont_re = re.compile('(.*)\\\s*$')
def scanInputFile(fileName):
'''Scan single input file for test suites'''
# mode 'rb' is problematic in python3 - byte arrays don't behave the same as
# strings.
# As far as the choice of the default encoding: utf-8 chews through
# everything that the previous ascii codec could, plus most of new code.
# TODO: figure out how to do this properly - like autodetect encoding from
# file header.
file = codecs.open(fileName, mode='r', encoding='utf-8')
prev = ""
lineNo = 0
contNo = 0
while 1:
line = file.readline()
if not line:
break
lineNo += 1
m = lineCont_re.match(line)
if m:
prev += m.group(1) + " "
contNo += 1
else:
scanInputLine( fileName, lineNo - contNo, prev + line )
contNo = 0
prev = ""
if contNo:
scanInputLine( fileName, lineNo - contNo, prev + line )
closeSuite()
file.close()
def scanInputLine( fileName, lineNo, line ):
'''Scan single input line for interesting stuff'''
scanLineForExceptionHandling( line )
scanLineForStandardLibrary( line )
scanLineForSuiteStart( fileName, lineNo, line )
global suite
if suite:
scanLineInsideSuite( suite, lineNo, line )
def scanLineInsideSuite( suite, lineNo, line ):
'''Analyze line which is part of a suite'''
global inBlock
if lineBelongsToSuite( suite, lineNo, line ):
scanLineForTest( suite, lineNo, line )
scanLineForCreate( suite, lineNo, line )
scanLineForDestroy( suite, lineNo, line )
def lineBelongsToSuite( suite, lineNo, line ):
'''Returns whether current line is part of the current suite.
This can be false when we are in a generated suite outside of CXXTEST_CODE() blocks
If the suite is generated, adds the line to the list of lines'''
if not suite['generated']:
return 1
global inBlock
if not inBlock:
inBlock = lineStartsBlock( line )
if inBlock:
inBlock = addLineToBlock( suite, lineNo, line )
return inBlock
std_re = re.compile( r"\b(std\s*::|CXXTEST_STD|using\s+namespace\s+std\b|^\s*\#\s*include\s+<[a-z0-9]+>)" )
def scanLineForStandardLibrary( line ):
'''Check if current line uses standard library'''
global options
if not options.haveStandardLibrary and std_re.search(line):
if not options.noStandardLibrary:
options.haveStandardLibrary = 1
exception_re = re.compile( r"\b(throw|try|catch|TSM?_ASSERT_THROWS[A-Z_]*)\b" )
def scanLineForExceptionHandling( line ):
'''Check if current line uses exception handling'''
global options
if not options.haveExceptionHandling and exception_re.search(line):
if not options.noExceptionHandling:
options.haveExceptionHandling = 1
classdef = '(?:::\s*)?(?:\w+\s*::\s*)*\w+'
baseclassdef = '(?:public|private|protected)\s+%s' % (classdef,)
general_suite = r"\bclass\s+(%s)\s*:(?:\s*%s\s*,)*\s*public\s+" \
% (classdef, baseclassdef,)
testsuite = '(?:(?:::)?\s*CxxTest\s*::\s*)?TestSuite'
suites_re = { re.compile( general_suite + testsuite ) : None }
generatedSuite_re = re.compile( r'\bCXXTEST_SUITE\s*\(\s*(\w*)\s*\)' )
def scanLineForSuiteStart( fileName, lineNo, line ):
'''Check if current line starts a new test suite'''
for i in list(suites_re.items()):
m = i[0].search( line )
if m:
suite = startSuite( m.group(1), fileName, lineNo, 0 )
if i[1] is not None:
for test in i[1]['tests']:
addTest(suite, test['name'], test['line'])
break
m = generatedSuite_re.search( line )
if m:
sys.stdout.write( "%s:%s: Warning: Inline test suites are deprecated.\n" % (fileName, lineNo) )
startSuite( m.group(1), fileName, lineNo, 1 )
def startSuite( name, file, line, generated ):
'''Start scanning a new suite'''
global suite
closeSuite()
object_name = name.replace(':',"_")
suite = { 'name' : name,
'file' : file,
'cfile' : cstr(file),
'line' : line,
'generated' : generated,
'object' : 'suite_%s' % object_name,
'dobject' : 'suiteDescription_%s' % object_name,
'tlist' : 'Tests_%s' % object_name,
'tests' : [],
'lines' : [] }
suites_re[re.compile( general_suite + name )] = suite
return suite
def lineStartsBlock( line ):
'''Check if current line starts a new CXXTEST_CODE() block'''
return re.search( r'\bCXXTEST_CODE\s*\(', line ) is not None
test_re = re.compile( r'^([^/]|/[^/])*\bvoid\s+([Tt]est\w+)\s*\(\s*(void)?\s*\)' )
def scanLineForTest( suite, lineNo, line ):
'''Check if current line starts a test'''
m = test_re.search( line )
if m:
addTest( suite, m.group(2), lineNo )
def addTest( suite, name, line ):
'''Add a test function to the current suite'''
test = { 'name' : name,
'suite' : suite,
'class' : 'TestDescription_%s_%s' % (suite['object'], name),
'object' : 'testDescription_%s_%s' % (suite['object'], name),
'line' : line,
}
suite['tests'].append( test )
def addLineToBlock( suite, lineNo, line ):
'''Append the line to the current CXXTEST_CODE() block'''
line = fixBlockLine( suite, lineNo, line )
line = re.sub( r'^.*\{\{', '', line )
e = re.search( r'\}\}', line )
if e:
line = line[:e.start()]
suite['lines'].append( line )
return e is None
def fixBlockLine( suite, lineNo, line):
'''Change all [E]TS_ macros used in a line to _[E]TS_ macros with the correct file/line'''
return re.sub( r'\b(E?TSM?_(ASSERT[A-Z_]*|FAIL))\s*\(',
r'_\1(%s,%s,' % (suite['cfile'], lineNo),
line, 0 )
create_re = re.compile( r'\bstatic\s+\w+\s*\*\s*createSuite\s*\(\s*(void)?\s*\)' )
def scanLineForCreate( suite, lineNo, line ):
'''Check if current line defines a createSuite() function'''
if create_re.search( line ):
addSuiteCreateDestroy( suite, 'create', lineNo )
destroy_re = re.compile( r'\bstatic\s+void\s+destroySuite\s*\(\s*\w+\s*\*\s*\w*\s*\)' )
def scanLineForDestroy( suite, lineNo, line ):
'''Check if current line defines a destroySuite() function'''
if destroy_re.search( line ):
addSuiteCreateDestroy( suite, 'destroy', lineNo )
def cstr( s ):
'''Convert a string to its C representation'''
return '"' + s.replace( '\\', '\\\\' ) + '"'
def addSuiteCreateDestroy( suite, which, line ):
'''Add createSuite()/destroySuite() to current suite'''
if which in suite:
abort( '%s:%s: %sSuite() already declared' % ( suite['file'], str(line), which ) )
suite[which] = line
def closeSuite():
'''Close current suite and add it to the list if valid'''
global suite
if suite is not None:
if len(suite['tests']) is not 0:
verifySuite(suite)
rememberSuite(suite)
suite = None
def verifySuite(suite):
'''Verify current suite is legal'''
if 'create' in suite and 'destroy' not in suite:
abort( '%s:%s: Suite %s has createSuite() but no destroySuite()' %
(suite['file'], suite['create'], suite['name']) )
elif 'destroy' in suite and 'create' not in suite:
abort( '%s:%s: Suite %s has destroySuite() but no createSuite()' %
(suite['file'], suite['destroy'], suite['name']) )
def rememberSuite(suite):
'''Add current suite to list'''
global suites
suites.append( suite )
| [
[
1,
0,
0.0496,
0.0041,
0,
0.66,
0,
220,
0,
1,
0,
0,
220,
0,
0
],
[
1,
0,
0.0537,
0.0041,
0,
0.66,
0.0256,
540,
0,
1,
0,
0,
540,
0,
0
],
[
1,
0,
0.0702,
0.0041,
0,
... | [
"import codecs",
"import re",
"from cxxtest.cxxtest_misc import abort",
"suites = []",
"suite = None",
"inBlock = 0",
"options=None",
"def scanInputFiles(files, _options):\n '''Scan all input files for test suites'''\n global options\n options=_options\n for file in files:\n scanInp... |
#-------------------------------------------------------------------------
# CxxTest: A lightweight C++ unit testing library.
# Copyright (c) 2008 Sandia Corporation.
# This software is distributed under the LGPL License v2.1
# For more information, see the COPYING file in the top CxxTest directory.
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains certain rights in this software.
#-------------------------------------------------------------------------
""" Release Information for cxxtest """
__version__ = '4.0.2'
__date__ = "2012-01-02"
| [
[
8,
0,
0.7692,
0.0769,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.9231,
0.0769,
0,
0.66,
0.5,
162,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
1,
0.0769,
0,
0.66,
1,... | [
"\"\"\" Release Information for cxxtest \"\"\"",
"__version__ = '4.0.2'",
"__date__ = \"2012-01-02\""
] |
#-------------------------------------------------------------------------
# CxxTest: A lightweight C++ unit testing library.
# Copyright (c) 2008 Sandia Corporation.
# This software is distributed under the LGPL License v2.1
# For more information, see the COPYING file in the top CxxTest directory.
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains certain rights in this software.
#-------------------------------------------------------------------------
# vim: fileencoding=utf-8
#
# This is a PLY parser for the entire ANSI C++ grammar. This grammar was
# adapted from the FOG grammar developed by E. D. Willink. See
#
# http://www.computing.surrey.ac.uk/research/dsrg/fog/
#
# for further details.
#
# The goal of this grammar is to extract information about class, function and
# class method declarations, along with their associated scope. Thus, this
# grammar can be used to analyze classes in an inheritance heirarchy, and then
# enumerate the methods in a derived class.
#
# This grammar parses blocks of <>, (), [] and {} in a generic manner. Thus,
# There are several capabilities that this grammar does not support:
#
# 1. Ambiguous template specification. This grammar cannot parse template
# specifications that do not have paired <>'s in their declaration. In
# particular, ambiguous declarations like
#
# foo<A, c<3 >();
#
# cannot be correctly parsed.
#
# 2. Template class specialization. Although the goal of this grammar is to
# extract class information, specialization of templated classes is
# not supported. When a template class definition is parsed, it's
# declaration is archived without information about the template
# parameters. Class specializations will be stored separately, and
# thus they can be processed after the fact. However, this grammar
# does not attempt to correctly process properties of class inheritence
# when template class specialization is employed.
#
#
# TODO: document usage of this file
#
import os
import ply.lex as lex
import ply.yacc as yacc
import re
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
lexer = None
scope_lineno = 0
identifier_lineno = {}
_parse_info=None
_parsedata=None
noExceptionLogic = True
def ply_init(data):
global _parsedata
_parsedata=data
class Scope(object):
def __init__(self,name,abs_name,scope_t,base_classes,lineno):
self.function=[]
self.name=name
self.scope_t=scope_t
self.sub_scopes=[]
self.base_classes=base_classes
self.abs_name=abs_name
self.lineno=lineno
def insert(self,scope):
self.sub_scopes.append(scope)
class CppInfo(object):
def __init__(self, filter=None):
self.verbose=0
if filter is None:
self.filter=re.compile("[Tt][Ee][Ss][Tt]|createSuite|destroySuite")
else:
self.filter=filter
self.scopes=[""]
self.index=OrderedDict()
self.index[""]=Scope("","::","namespace",[],1)
self.function=[]
def push_scope(self,ns,scope_t,base_classes=[]):
name = self.scopes[-1]+"::"+ns
if self.verbose>=2:
print("-- Starting "+scope_t+" "+name)
self.scopes.append(name)
self.index[name] = Scope(ns,name,scope_t,base_classes,scope_lineno-1)
def pop_scope(self):
scope = self.scopes.pop()
if self.verbose>=2:
print("-- Stopping "+scope)
return scope
def add_function(self, fn):
fn = str(fn)
if self.filter.search(fn):
self.index[self.scopes[-1]].function.append((fn, identifier_lineno.get(fn,lexer.lineno-1)))
tmp = self.scopes[-1]+"::"+fn
if self.verbose==2:
print("-- Function declaration "+fn+" "+tmp)
elif self.verbose==1:
print("-- Function declaration "+tmp)
def get_functions(self,name,quiet=False):
if name == "::":
name = ""
scope = self.index[name]
fns=scope.function
for key in scope.base_classes:
cname = self.find_class(key,scope)
if cname is None:
if not quiet:
print("Defined classes: ",list(self.index.keys()))
print("WARNING: Unknown class "+key)
else:
fns += self.get_functions(cname,quiet)
return fns
def find_class(self,name,scope):
if ':' in name:
if name in self.index:
return name
else:
return None
tmp = scope.abs_name.split(':')
name1 = ":".join(tmp[:-1] + [name])
if name1 in self.index:
return name1
name2 = "::"+name
if name2 in self.index:
return name2
return None
def __repr__(self):
return str(self)
def is_baseclass(self,cls,base):
'''Returns true if base is a base-class of cls'''
if cls in self.index:
bases = self.index[cls]
elif "::"+cls in self.index:
bases = self.index["::"+cls]
else:
return False
#raise IOError, "Unknown class "+cls
if base in bases.base_classes:
return True
for name in bases.base_classes:
if self.is_baseclass(name,base):
return True
return False
def __str__(self):
ans=""
keys = list(self.index.keys())
keys.sort()
for key in keys:
scope = self.index[key]
ans += scope.scope_t+" "+scope.abs_name+"\n"
if scope.scope_t == "class":
ans += " Base Classes: "+str(scope.base_classes)+"\n"
for fn in self.get_functions(scope.abs_name):
ans += " "+fn+"\n"
else:
for fn in scope.function:
ans += " "+fn+"\n"
return ans
def flatten(x):
"""Flatten nested list"""
try:
strtypes = str
except: # for python3 etc
strtypes = (str, bytes)
result = []
for el in x:
if hasattr(el, "__iter__") and not isinstance(el, strtypes):
result.extend(flatten(el))
else:
result.append(el)
return result
#
# The lexer (and/or a preprocessor) is expected to identify the following
#
# Punctuation:
#
#
literals = "+-*/%^&|~!<>=:()?.\'\"\\@$;,"
#
reserved = {
'private' : 'PRIVATE',
'protected' : 'PROTECTED',
'public' : 'PUBLIC',
'bool' : 'BOOL',
'char' : 'CHAR',
'double' : 'DOUBLE',
'float' : 'FLOAT',
'int' : 'INT',
'long' : 'LONG',
'short' : 'SHORT',
'signed' : 'SIGNED',
'unsigned' : 'UNSIGNED',
'void' : 'VOID',
'wchar_t' : 'WCHAR_T',
'class' : 'CLASS',
'enum' : 'ENUM',
'namespace' : 'NAMESPACE',
'struct' : 'STRUCT',
'typename' : 'TYPENAME',
'union' : 'UNION',
'const' : 'CONST',
'volatile' : 'VOLATILE',
'auto' : 'AUTO',
'explicit' : 'EXPLICIT',
'export' : 'EXPORT',
'extern' : 'EXTERN',
'__extension__' : 'EXTENSION',
'friend' : 'FRIEND',
'inline' : 'INLINE',
'mutable' : 'MUTABLE',
'register' : 'REGISTER',
'static' : 'STATIC',
'template' : 'TEMPLATE',
'typedef' : 'TYPEDEF',
'using' : 'USING',
'virtual' : 'VIRTUAL',
'asm' : 'ASM',
'break' : 'BREAK',
'case' : 'CASE',
'catch' : 'CATCH',
'const_cast' : 'CONST_CAST',
'continue' : 'CONTINUE',
'default' : 'DEFAULT',
'delete' : 'DELETE',
'do' : 'DO',
'dynamic_cast' : 'DYNAMIC_CAST',
'else' : 'ELSE',
'false' : 'FALSE',
'for' : 'FOR',
'goto' : 'GOTO',
'if' : 'IF',
'new' : 'NEW',
'operator' : 'OPERATOR',
'reinterpret_cast' : 'REINTERPRET_CAST',
'return' : 'RETURN',
'sizeof' : 'SIZEOF',
'static_cast' : 'STATIC_CAST',
'switch' : 'SWITCH',
'this' : 'THIS',
'throw' : 'THROW',
'true' : 'TRUE',
'try' : 'TRY',
'typeid' : 'TYPEID',
'while' : 'WHILE',
'"C"' : 'CLiteral',
'"C++"' : 'CppLiteral',
'__attribute__' : 'ATTRIBUTE',
'__cdecl__' : 'CDECL',
'__typeof' : 'uTYPEOF',
'typeof' : 'TYPEOF',
'CXXTEST_STD' : 'CXXTEST_STD'
}
tokens = [
"CharacterLiteral",
"FloatingLiteral",
"Identifier",
"IntegerLiteral",
"StringLiteral",
"RBRACE",
"LBRACE",
"RBRACKET",
"LBRACKET",
"ARROW",
"ARROW_STAR",
"DEC",
"EQ",
"GE",
"INC",
"LE",
"LOG_AND",
"LOG_OR",
"NE",
"SHL",
"SHR",
"ASS_ADD",
"ASS_AND",
"ASS_DIV",
"ASS_MOD",
"ASS_MUL",
"ASS_OR",
"ASS_SHL",
"ASS_SHR",
"ASS_SUB",
"ASS_XOR",
"DOT_STAR",
"ELLIPSIS",
"SCOPE",
] + list(reserved.values())
t_ignore = " \t\r"
t_LBRACE = r"(\{)|(<%)"
t_RBRACE = r"(\})|(%>)"
t_LBRACKET = r"(\[)|(<:)"
t_RBRACKET = r"(\])|(:>)"
t_ARROW = r"->"
t_ARROW_STAR = r"->\*"
t_DEC = r"--"
t_EQ = r"=="
t_GE = r">="
t_INC = r"\+\+"
t_LE = r"<="
t_LOG_AND = r"&&"
t_LOG_OR = r"\|\|"
t_NE = r"!="
t_SHL = r"<<"
t_SHR = r">>"
t_ASS_ADD = r"\+="
t_ASS_AND = r"&="
t_ASS_DIV = r"/="
t_ASS_MOD = r"%="
t_ASS_MUL = r"\*="
t_ASS_OR = r"\|="
t_ASS_SHL = r"<<="
t_ASS_SHR = r">>="
t_ASS_SUB = r"-="
t_ASS_XOR = r"^="
t_DOT_STAR = r"\.\*"
t_ELLIPSIS = r"\.\.\."
t_SCOPE = r"::"
# Discard comments
def t_COMMENT(t):
r'(/\*(.|\n)*?\*/)|(//.*?\n)|(\#.*?\n)'
t.lexer.lineno += t.value.count("\n")
t_IntegerLiteral = r'(0x[0-9A-F]+)|([0-9]+(L){0,1})'
t_FloatingLiteral = r"[0-9]+[eE\.\+-]+[eE\.\+\-0-9]+"
t_CharacterLiteral = r'\'([^\'\\]|\\.)*\''
#t_StringLiteral = r'"([^"\\]|\\.)*"'
def t_StringLiteral(t):
r'"([^"\\]|\\.)*"'
t.type = reserved.get(t.value,'StringLiteral')
return t
def t_Identifier(t):
r"[a-zA-Z_][a-zA-Z_0-9\.]*"
t.type = reserved.get(t.value,'Identifier')
return t
def t_error(t):
print("Illegal character '%s'" % t.value[0])
#raise IOError, "Parse error"
#t.lexer.skip()
def t_newline(t):
r'[\n]+'
t.lexer.lineno += len(t.value)
precedence = (
( 'right', 'SHIFT_THERE', 'REDUCE_HERE_MOSTLY', 'SCOPE'),
( 'nonassoc', 'ELSE', 'INC', 'DEC', '+', '-', '*', '&', 'LBRACKET', 'LBRACE', '<', ':', ')')
)
start = 'translation_unit'
#
# The %prec resolves the 14.2-3 ambiguity:
# Identifier '<' is forced to go through the is-it-a-template-name test
# All names absorb TEMPLATE with the name, so that no template_test is
# performed for them. This requires all potential declarations within an
# expression to perpetuate this policy and thereby guarantee the ultimate
# coverage of explicit_instantiation.
#
# The %prec also resolves a conflict in identifier : which is forced to be a
# shift of a label for a labeled-statement rather than a reduction for the
# name of a bit-field or generalised constructor. This is pretty dubious
# syntactically but correct for all semantic possibilities. The shift is
# only activated when the ambiguity exists at the start of a statement.
# In this context a bit-field declaration or constructor definition are not
# allowed.
#
def p_identifier(p):
'''identifier : Identifier
| CXXTEST_STD '(' Identifier ')'
'''
if p[1][0] in ('t','T','c','d'):
identifier_lineno[p[1]] = p.lineno(1)
p[0] = p[1]
def p_id(p):
'''id : identifier %prec SHIFT_THERE
| template_decl
| TEMPLATE id
'''
p[0] = get_rest(p)
def p_global_scope(p):
'''global_scope : SCOPE
'''
p[0] = get_rest(p)
def p_id_scope(p):
'''id_scope : id SCOPE'''
p[0] = get_rest(p)
def p_id_scope_seq(p):
'''id_scope_seq : id_scope
| id_scope id_scope_seq
'''
p[0] = get_rest(p)
#
# A :: B :: C; is ambiguous How much is type and how much name ?
# The %prec maximises the (type) length which is the 7.1-2 semantic constraint.
#
def p_nested_id(p):
'''nested_id : id %prec SHIFT_THERE
| id_scope nested_id
'''
p[0] = get_rest(p)
def p_scoped_id(p):
'''scoped_id : nested_id
| global_scope nested_id
| id_scope_seq
| global_scope id_scope_seq
'''
global scope_lineno
scope_lineno = lexer.lineno
data = flatten(get_rest(p))
if data[0] != None:
p[0] = "".join(data)
#
# destructor_id has to be held back to avoid a conflict with a one's
# complement as per 5.3.1-9, It gets put back only when scoped or in a
# declarator_id, which is only used as an explicit member name.
# Declarations of an unscoped destructor are always parsed as a one's
# complement.
#
def p_destructor_id(p):
'''destructor_id : '~' id
| TEMPLATE destructor_id
'''
p[0]=get_rest(p)
#def p_template_id(p):
# '''template_id : empty
# | TEMPLATE
# '''
# pass
def p_template_decl(p):
'''template_decl : identifier '<' nonlgt_seq_opt '>'
'''
#
# WEH: should we include the lt/gt symbols to indicate that this is a
# template class? How is that going to be used later???
#
#p[0] = [p[1] ,"<",">"]
p[0] = p[1]
def p_special_function_id(p):
'''special_function_id : conversion_function_id
| operator_function_id
| TEMPLATE special_function_id
'''
p[0]=get_rest(p)
def p_nested_special_function_id(p):
'''nested_special_function_id : special_function_id
| id_scope destructor_id
| id_scope nested_special_function_id
'''
p[0]=get_rest(p)
def p_scoped_special_function_id(p):
'''scoped_special_function_id : nested_special_function_id
| global_scope nested_special_function_id
'''
p[0]=get_rest(p)
# declarator-id is all names in all scopes, except reserved words
def p_declarator_id(p):
'''declarator_id : scoped_id
| scoped_special_function_id
| destructor_id
'''
p[0]=p[1]
#
# The standard defines pseudo-destructors in terms of type-name, which is
# class/enum/typedef, of which class-name is covered by a normal destructor.
# pseudo-destructors are supposed to support ~int() in templates, so the
# grammar here covers built-in names. Other names are covered by the lack
# of identifier/type discrimination.
#
def p_built_in_type_id(p):
'''built_in_type_id : built_in_type_specifier
| built_in_type_id built_in_type_specifier
'''
pass
def p_pseudo_destructor_id(p):
'''pseudo_destructor_id : built_in_type_id SCOPE '~' built_in_type_id
| '~' built_in_type_id
| TEMPLATE pseudo_destructor_id
'''
pass
def p_nested_pseudo_destructor_id(p):
'''nested_pseudo_destructor_id : pseudo_destructor_id
| id_scope nested_pseudo_destructor_id
'''
pass
def p_scoped_pseudo_destructor_id(p):
'''scoped_pseudo_destructor_id : nested_pseudo_destructor_id
| global_scope scoped_pseudo_destructor_id
'''
pass
#-------------------------------------------------------------------------------
# A.2 Lexical conventions
#-------------------------------------------------------------------------------
#
def p_literal(p):
'''literal : IntegerLiteral
| CharacterLiteral
| FloatingLiteral
| StringLiteral
| TRUE
| FALSE
'''
pass
#-------------------------------------------------------------------------------
# A.3 Basic concepts
#-------------------------------------------------------------------------------
def p_translation_unit(p):
'''translation_unit : declaration_seq_opt
'''
pass
#-------------------------------------------------------------------------------
# A.4 Expressions
#-------------------------------------------------------------------------------
#
# primary_expression covers an arbitrary sequence of all names with the
# exception of an unscoped destructor, which is parsed as its unary expression
# which is the correct disambiguation (when ambiguous). This eliminates the
# traditional A(B) meaning A B ambiguity, since we never have to tack an A
# onto the front of something that might start with (. The name length got
# maximised ab initio. The downside is that semantic interpretation must split
# the names up again.
#
# Unification of the declaration and expression syntax means that unary and
# binary pointer declarator operators:
# int * * name
# are parsed as binary and unary arithmetic operators (int) * (*name). Since
# type information is not used
# ambiguities resulting from a cast
# (cast)*(value)
# are resolved to favour the binary rather than the cast unary to ease AST
# clean-up. The cast-call ambiguity must be resolved to the cast to ensure
# that (a)(b)c can be parsed.
#
# The problem of the functional cast ambiguity
# name(arg)
# as call or declaration is avoided by maximising the name within the parsing
# kernel. So primary_id_expression picks up
# extern long int const var = 5;
# as an assignment to the syntax parsed as "extern long int const var". The
# presence of two names is parsed so that "extern long into const" is
# distinguished from "var" considerably simplifying subsequent
# semantic resolution.
#
# The generalised name is a concatenation of potential type-names (scoped
# identifiers or built-in sequences) plus optionally one of the special names
# such as an operator-function-id, conversion-function-id or destructor as the
# final name.
#
def get_rest(p):
return [p[i] for i in range(1, len(p))]
def p_primary_expression(p):
'''primary_expression : literal
| THIS
| suffix_decl_specified_ids
| abstract_expression %prec REDUCE_HERE_MOSTLY
'''
p[0] = get_rest(p)
#
# Abstract-expression covers the () and [] of abstract-declarators.
#
def p_abstract_expression(p):
'''abstract_expression : parenthesis_clause
| LBRACKET bexpression_opt RBRACKET
| TEMPLATE abstract_expression
'''
pass
def p_postfix_expression(p):
'''postfix_expression : primary_expression
| postfix_expression parenthesis_clause
| postfix_expression LBRACKET bexpression_opt RBRACKET
| postfix_expression LBRACKET bexpression_opt RBRACKET attributes
| postfix_expression '.' declarator_id
| postfix_expression '.' scoped_pseudo_destructor_id
| postfix_expression ARROW declarator_id
| postfix_expression ARROW scoped_pseudo_destructor_id
| postfix_expression INC
| postfix_expression DEC
| DYNAMIC_CAST '<' nonlgt_seq_opt '>' '(' expression ')'
| STATIC_CAST '<' nonlgt_seq_opt '>' '(' expression ')'
| REINTERPRET_CAST '<' nonlgt_seq_opt '>' '(' expression ')'
| CONST_CAST '<' nonlgt_seq_opt '>' '(' expression ')'
| TYPEID parameters_clause
'''
#print "HERE",str(p[1])
p[0] = get_rest(p)
def p_bexpression_opt(p):
'''bexpression_opt : empty
| bexpression
'''
pass
def p_bexpression(p):
'''bexpression : nonbracket_seq
| nonbracket_seq bexpression_seq bexpression_clause nonbracket_seq_opt
| bexpression_seq bexpression_clause nonbracket_seq_opt
'''
pass
def p_bexpression_seq(p):
'''bexpression_seq : empty
| bexpression_seq bexpression_clause nonbracket_seq_opt
'''
pass
def p_bexpression_clause(p):
'''bexpression_clause : LBRACKET bexpression_opt RBRACKET
'''
pass
def p_expression_list_opt(p):
'''expression_list_opt : empty
| expression_list
'''
pass
def p_expression_list(p):
'''expression_list : assignment_expression
| expression_list ',' assignment_expression
'''
pass
def p_unary_expression(p):
'''unary_expression : postfix_expression
| INC cast_expression
| DEC cast_expression
| ptr_operator cast_expression
| suffix_decl_specified_scope star_ptr_operator cast_expression
| '+' cast_expression
| '-' cast_expression
| '!' cast_expression
| '~' cast_expression
| SIZEOF unary_expression
| new_expression
| global_scope new_expression
| delete_expression
| global_scope delete_expression
'''
p[0] = get_rest(p)
def p_delete_expression(p):
'''delete_expression : DELETE cast_expression
'''
pass
def p_new_expression(p):
'''new_expression : NEW new_type_id new_initializer_opt
| NEW parameters_clause new_type_id new_initializer_opt
| NEW parameters_clause
| NEW parameters_clause parameters_clause new_initializer_opt
'''
pass
def p_new_type_id(p):
'''new_type_id : type_specifier ptr_operator_seq_opt
| type_specifier new_declarator
| type_specifier new_type_id
'''
pass
def p_new_declarator(p):
'''new_declarator : ptr_operator new_declarator
| direct_new_declarator
'''
pass
def p_direct_new_declarator(p):
'''direct_new_declarator : LBRACKET bexpression_opt RBRACKET
| direct_new_declarator LBRACKET bexpression RBRACKET
'''
pass
def p_new_initializer_opt(p):
'''new_initializer_opt : empty
| '(' expression_list_opt ')'
'''
pass
#
# cast-expression is generalised to support a [] as well as a () prefix. This covers the omission of
# DELETE[] which when followed by a parenthesised expression was ambiguous. It also covers the gcc
# indexed array initialisation for free.
#
def p_cast_expression(p):
'''cast_expression : unary_expression
| abstract_expression cast_expression
'''
p[0] = get_rest(p)
def p_pm_expression(p):
'''pm_expression : cast_expression
| pm_expression DOT_STAR cast_expression
| pm_expression ARROW_STAR cast_expression
'''
p[0] = get_rest(p)
def p_multiplicative_expression(p):
'''multiplicative_expression : pm_expression
| multiplicative_expression star_ptr_operator pm_expression
| multiplicative_expression '/' pm_expression
| multiplicative_expression '%' pm_expression
'''
p[0] = get_rest(p)
def p_additive_expression(p):
'''additive_expression : multiplicative_expression
| additive_expression '+' multiplicative_expression
| additive_expression '-' multiplicative_expression
'''
p[0] = get_rest(p)
def p_shift_expression(p):
'''shift_expression : additive_expression
| shift_expression SHL additive_expression
| shift_expression SHR additive_expression
'''
p[0] = get_rest(p)
# | relational_expression '<' shift_expression
# | relational_expression '>' shift_expression
# | relational_expression LE shift_expression
# | relational_expression GE shift_expression
def p_relational_expression(p):
'''relational_expression : shift_expression
'''
p[0] = get_rest(p)
def p_equality_expression(p):
'''equality_expression : relational_expression
| equality_expression EQ relational_expression
| equality_expression NE relational_expression
'''
p[0] = get_rest(p)
def p_and_expression(p):
'''and_expression : equality_expression
| and_expression '&' equality_expression
'''
p[0] = get_rest(p)
def p_exclusive_or_expression(p):
'''exclusive_or_expression : and_expression
| exclusive_or_expression '^' and_expression
'''
p[0] = get_rest(p)
def p_inclusive_or_expression(p):
'''inclusive_or_expression : exclusive_or_expression
| inclusive_or_expression '|' exclusive_or_expression
'''
p[0] = get_rest(p)
def p_logical_and_expression(p):
'''logical_and_expression : inclusive_or_expression
| logical_and_expression LOG_AND inclusive_or_expression
'''
p[0] = get_rest(p)
def p_logical_or_expression(p):
'''logical_or_expression : logical_and_expression
| logical_or_expression LOG_OR logical_and_expression
'''
p[0] = get_rest(p)
def p_conditional_expression(p):
'''conditional_expression : logical_or_expression
| logical_or_expression '?' expression ':' assignment_expression
'''
p[0] = get_rest(p)
#
# assignment-expression is generalised to cover the simple assignment of a braced initializer in order to
# contribute to the coverage of parameter-declaration and init-declaration.
#
# | logical_or_expression assignment_operator assignment_expression
def p_assignment_expression(p):
'''assignment_expression : conditional_expression
| logical_or_expression assignment_operator nonsemicolon_seq
| logical_or_expression '=' braced_initializer
| throw_expression
'''
p[0]=get_rest(p)
def p_assignment_operator(p):
'''assignment_operator : '='
| ASS_ADD
| ASS_AND
| ASS_DIV
| ASS_MOD
| ASS_MUL
| ASS_OR
| ASS_SHL
| ASS_SHR
| ASS_SUB
| ASS_XOR
'''
pass
#
# expression is widely used and usually single-element, so the reductions are arranged so that a
# single-element expression is returned as is. Multi-element expressions are parsed as a list that
# may then behave polymorphically as an element or be compacted to an element.
#
def p_expression(p):
'''expression : assignment_expression
| expression_list ',' assignment_expression
'''
p[0] = get_rest(p)
def p_constant_expression(p):
'''constant_expression : conditional_expression
'''
pass
#---------------------------------------------------------------------------------------------------
# A.5 Statements
#---------------------------------------------------------------------------------------------------
# Parsing statements is easy once simple_declaration has been generalised to cover expression_statement.
#
#
# The use of extern here is a hack. The 'extern "C" {}' block gets parsed
# as a function, so when nested 'extern "C"' declarations exist, they don't
# work because the block is viewed as a list of statements... :(
#
def p_statement(p):
'''statement : compound_statement
| declaration_statement
| try_block
| labeled_statement
| selection_statement
| iteration_statement
| jump_statement
'''
pass
def p_compound_statement(p):
'''compound_statement : LBRACE statement_seq_opt RBRACE
'''
pass
def p_statement_seq_opt(p):
'''statement_seq_opt : empty
| statement_seq_opt statement
'''
pass
#
# The dangling else conflict is resolved to the innermost if.
#
def p_selection_statement(p):
'''selection_statement : IF '(' condition ')' statement %prec SHIFT_THERE
| IF '(' condition ')' statement ELSE statement
| SWITCH '(' condition ')' statement
'''
pass
def p_condition_opt(p):
'''condition_opt : empty
| condition
'''
pass
def p_condition(p):
'''condition : nonparen_seq
| nonparen_seq condition_seq parameters_clause nonparen_seq_opt
| condition_seq parameters_clause nonparen_seq_opt
'''
pass
def p_condition_seq(p):
'''condition_seq : empty
| condition_seq parameters_clause nonparen_seq_opt
'''
pass
def p_labeled_statement(p):
'''labeled_statement : identifier ':' statement
| CASE constant_expression ':' statement
| DEFAULT ':' statement
'''
pass
def p_try_block(p):
'''try_block : TRY compound_statement handler_seq
'''
global noExceptionLogic
noExceptionLogic=False
def p_jump_statement(p):
'''jump_statement : BREAK ';'
| CONTINUE ';'
| RETURN nonsemicolon_seq ';'
| GOTO identifier ';'
'''
pass
def p_iteration_statement(p):
'''iteration_statement : WHILE '(' condition ')' statement
| DO statement WHILE '(' expression ')' ';'
| FOR '(' nonparen_seq_opt ')' statement
'''
pass
def p_declaration_statement(p):
'''declaration_statement : block_declaration
'''
pass
#---------------------------------------------------------------------------------------------------
# A.6 Declarations
#---------------------------------------------------------------------------------------------------
def p_compound_declaration(p):
'''compound_declaration : LBRACE declaration_seq_opt RBRACE
'''
pass
def p_declaration_seq_opt(p):
'''declaration_seq_opt : empty
| declaration_seq_opt declaration
'''
pass
def p_declaration(p):
'''declaration : block_declaration
| function_definition
| template_declaration
| explicit_specialization
| specialised_declaration
'''
pass
def p_specialised_declaration(p):
'''specialised_declaration : linkage_specification
| namespace_definition
| TEMPLATE specialised_declaration
'''
pass
def p_block_declaration(p):
'''block_declaration : simple_declaration
| specialised_block_declaration
'''
pass
def p_specialised_block_declaration(p):
'''specialised_block_declaration : asm_definition
| namespace_alias_definition
| using_declaration
| using_directive
| TEMPLATE specialised_block_declaration
'''
pass
def p_simple_declaration(p):
'''simple_declaration : ';'
| init_declaration ';'
| init_declarations ';'
| decl_specifier_prefix simple_declaration
'''
global _parse_info
if len(p) == 3:
if p[2] == ";":
decl = p[1]
else:
decl = p[2]
if decl is not None:
fp = flatten(decl)
if len(fp) >= 2 and fp[0] is not None and fp[0]!="operator" and fp[1] == '(':
p[0] = fp[0]
_parse_info.add_function(fp[0])
#
# A decl-specifier following a ptr_operator provokes a shift-reduce conflict for * const name which is resolved in favour of the pointer, and implemented by providing versions of decl-specifier guaranteed not to start with a cv_qualifier. decl-specifiers are implemented type-centrically. That is the semantic constraint that there must be a type is exploited to impose structure, but actually eliminate very little syntax. built-in types are multi-name and so need a different policy.
#
# non-type decl-specifiers are bound to the left-most type in a decl-specifier-seq, by parsing from the right and attaching suffixes to the right-hand type. Finally residual prefixes attach to the left.
#
def p_suffix_built_in_decl_specifier_raw(p):
'''suffix_built_in_decl_specifier_raw : built_in_type_specifier
| suffix_built_in_decl_specifier_raw built_in_type_specifier
| suffix_built_in_decl_specifier_raw decl_specifier_suffix
'''
pass
def p_suffix_built_in_decl_specifier(p):
'''suffix_built_in_decl_specifier : suffix_built_in_decl_specifier_raw
| TEMPLATE suffix_built_in_decl_specifier
'''
pass
# | id_scope_seq
# | SCOPE id_scope_seq
def p_suffix_named_decl_specifier(p):
'''suffix_named_decl_specifier : scoped_id
| elaborate_type_specifier
| suffix_named_decl_specifier decl_specifier_suffix
'''
p[0]=get_rest(p)
def p_suffix_named_decl_specifier_bi(p):
'''suffix_named_decl_specifier_bi : suffix_named_decl_specifier
| suffix_named_decl_specifier suffix_built_in_decl_specifier_raw
'''
p[0] = get_rest(p)
#print "HERE",get_rest(p)
def p_suffix_named_decl_specifiers(p):
'''suffix_named_decl_specifiers : suffix_named_decl_specifier_bi
| suffix_named_decl_specifiers suffix_named_decl_specifier_bi
'''
p[0] = get_rest(p)
def p_suffix_named_decl_specifiers_sf(p):
'''suffix_named_decl_specifiers_sf : scoped_special_function_id
| suffix_named_decl_specifiers
| suffix_named_decl_specifiers scoped_special_function_id
'''
#print "HERE",get_rest(p)
p[0] = get_rest(p)
def p_suffix_decl_specified_ids(p):
'''suffix_decl_specified_ids : suffix_built_in_decl_specifier
| suffix_built_in_decl_specifier suffix_named_decl_specifiers_sf
| suffix_named_decl_specifiers_sf
'''
if len(p) == 3:
p[0] = p[2]
else:
p[0] = p[1]
def p_suffix_decl_specified_scope(p):
'''suffix_decl_specified_scope : suffix_named_decl_specifiers SCOPE
| suffix_built_in_decl_specifier suffix_named_decl_specifiers SCOPE
| suffix_built_in_decl_specifier SCOPE
'''
p[0] = get_rest(p)
def p_decl_specifier_affix(p):
'''decl_specifier_affix : storage_class_specifier
| function_specifier
| FRIEND
| TYPEDEF
| cv_qualifier
'''
pass
def p_decl_specifier_suffix(p):
'''decl_specifier_suffix : decl_specifier_affix
'''
pass
def p_decl_specifier_prefix(p):
'''decl_specifier_prefix : decl_specifier_affix
| TEMPLATE decl_specifier_prefix
'''
pass
def p_storage_class_specifier(p):
'''storage_class_specifier : REGISTER
| STATIC
| MUTABLE
| EXTERN %prec SHIFT_THERE
| EXTENSION
| AUTO
'''
pass
def p_function_specifier(p):
'''function_specifier : EXPLICIT
| INLINE
| VIRTUAL
'''
pass
def p_type_specifier(p):
'''type_specifier : simple_type_specifier
| elaborate_type_specifier
| cv_qualifier
'''
pass
def p_elaborate_type_specifier(p):
'''elaborate_type_specifier : class_specifier
| enum_specifier
| elaborated_type_specifier
| TEMPLATE elaborate_type_specifier
'''
pass
def p_simple_type_specifier(p):
'''simple_type_specifier : scoped_id
| scoped_id attributes
| built_in_type_specifier
'''
p[0] = p[1]
def p_built_in_type_specifier(p):
'''built_in_type_specifier : Xbuilt_in_type_specifier
| Xbuilt_in_type_specifier attributes
'''
pass
def p_attributes(p):
'''attributes : attribute
| attributes attribute
'''
pass
def p_attribute(p):
'''attribute : ATTRIBUTE '(' parameters_clause ')'
'''
def p_Xbuilt_in_type_specifier(p):
'''Xbuilt_in_type_specifier : CHAR
| WCHAR_T
| BOOL
| SHORT
| INT
| LONG
| SIGNED
| UNSIGNED
| FLOAT
| DOUBLE
| VOID
| uTYPEOF parameters_clause
| TYPEOF parameters_clause
'''
pass
#
# The over-general use of declaration_expression to cover decl-specifier-seq_opt declarator in a function-definition means that
# class X { };
# could be a function-definition or a class-specifier.
# enum X { };
# could be a function-definition or an enum-specifier.
# The function-definition is not syntactically valid so resolving the false conflict in favour of the
# elaborated_type_specifier is correct.
#
def p_elaborated_type_specifier(p):
'''elaborated_type_specifier : class_key scoped_id %prec SHIFT_THERE
| elaborated_enum_specifier
| TYPENAME scoped_id
'''
pass
def p_elaborated_enum_specifier(p):
'''elaborated_enum_specifier : ENUM scoped_id %prec SHIFT_THERE
'''
pass
def p_enum_specifier(p):
'''enum_specifier : ENUM scoped_id enumerator_clause
| ENUM enumerator_clause
'''
pass
def p_enumerator_clause(p):
'''enumerator_clause : LBRACE enumerator_list_ecarb
| LBRACE enumerator_list enumerator_list_ecarb
| LBRACE enumerator_list ',' enumerator_definition_ecarb
'''
pass
def p_enumerator_list_ecarb(p):
'''enumerator_list_ecarb : RBRACE
'''
pass
def p_enumerator_definition_ecarb(p):
'''enumerator_definition_ecarb : RBRACE
'''
pass
def p_enumerator_definition_filler(p):
'''enumerator_definition_filler : empty
'''
pass
def p_enumerator_list_head(p):
'''enumerator_list_head : enumerator_definition_filler
| enumerator_list ',' enumerator_definition_filler
'''
pass
def p_enumerator_list(p):
'''enumerator_list : enumerator_list_head enumerator_definition
'''
pass
def p_enumerator_definition(p):
'''enumerator_definition : enumerator
| enumerator '=' constant_expression
'''
pass
def p_enumerator(p):
'''enumerator : identifier
'''
pass
def p_namespace_definition(p):
'''namespace_definition : NAMESPACE scoped_id push_scope compound_declaration
| NAMESPACE push_scope compound_declaration
'''
global _parse_info
scope = _parse_info.pop_scope()
def p_namespace_alias_definition(p):
'''namespace_alias_definition : NAMESPACE scoped_id '=' scoped_id ';'
'''
pass
def p_push_scope(p):
'''push_scope : empty'''
global _parse_info
if p[-2] == "namespace":
scope=p[-1]
else:
scope=""
_parse_info.push_scope(scope,"namespace")
def p_using_declaration(p):
'''using_declaration : USING declarator_id ';'
| USING TYPENAME declarator_id ';'
'''
pass
def p_using_directive(p):
'''using_directive : USING NAMESPACE scoped_id ';'
'''
pass
# '''asm_definition : ASM '(' StringLiteral ')' ';'
def p_asm_definition(p):
'''asm_definition : ASM '(' nonparen_seq_opt ')' ';'
'''
pass
def p_linkage_specification(p):
'''linkage_specification : EXTERN CLiteral declaration
| EXTERN CLiteral compound_declaration
| EXTERN CppLiteral declaration
| EXTERN CppLiteral compound_declaration
'''
pass
#---------------------------------------------------------------------------------------------------
# A.7 Declarators
#---------------------------------------------------------------------------------------------------
#
# init-declarator is named init_declaration to reflect the embedded decl-specifier-seq_opt
#
def p_init_declarations(p):
'''init_declarations : assignment_expression ',' init_declaration
| init_declarations ',' init_declaration
'''
p[0]=get_rest(p)
def p_init_declaration(p):
'''init_declaration : assignment_expression
'''
p[0]=get_rest(p)
def p_star_ptr_operator(p):
'''star_ptr_operator : '*'
| star_ptr_operator cv_qualifier
'''
pass
def p_nested_ptr_operator(p):
'''nested_ptr_operator : star_ptr_operator
| id_scope nested_ptr_operator
'''
pass
def p_ptr_operator(p):
'''ptr_operator : '&'
| nested_ptr_operator
| global_scope nested_ptr_operator
'''
pass
def p_ptr_operator_seq(p):
'''ptr_operator_seq : ptr_operator
| ptr_operator ptr_operator_seq
'''
pass
#
# Independently coded to localise the shift-reduce conflict: sharing just needs another %prec
#
def p_ptr_operator_seq_opt(p):
'''ptr_operator_seq_opt : empty %prec SHIFT_THERE
| ptr_operator ptr_operator_seq_opt
'''
pass
def p_cv_qualifier_seq_opt(p):
'''cv_qualifier_seq_opt : empty
| cv_qualifier_seq_opt cv_qualifier
'''
pass
# TODO: verify that we should include attributes here
def p_cv_qualifier(p):
'''cv_qualifier : CONST
| VOLATILE
| attributes
'''
pass
def p_type_id(p):
'''type_id : type_specifier abstract_declarator_opt
| type_specifier type_id
'''
pass
def p_abstract_declarator_opt(p):
'''abstract_declarator_opt : empty
| ptr_operator abstract_declarator_opt
| direct_abstract_declarator
'''
pass
def p_direct_abstract_declarator_opt(p):
'''direct_abstract_declarator_opt : empty
| direct_abstract_declarator
'''
pass
def p_direct_abstract_declarator(p):
'''direct_abstract_declarator : direct_abstract_declarator_opt parenthesis_clause
| direct_abstract_declarator_opt LBRACKET RBRACKET
| direct_abstract_declarator_opt LBRACKET bexpression RBRACKET
'''
pass
def p_parenthesis_clause(p):
'''parenthesis_clause : parameters_clause cv_qualifier_seq_opt
| parameters_clause cv_qualifier_seq_opt exception_specification
'''
p[0] = ['(',')']
def p_parameters_clause(p):
'''parameters_clause : '(' condition_opt ')'
'''
p[0] = ['(',')']
#
# A typed abstract qualifier such as
# Class * ...
# looks like a multiply, so pointers are parsed as their binary operation equivalents that
# ultimately terminate with a degenerate right hand term.
#
def p_abstract_pointer_declaration(p):
'''abstract_pointer_declaration : ptr_operator_seq
| multiplicative_expression star_ptr_operator ptr_operator_seq_opt
'''
pass
def p_abstract_parameter_declaration(p):
'''abstract_parameter_declaration : abstract_pointer_declaration
| and_expression '&'
| and_expression '&' abstract_pointer_declaration
'''
pass
def p_special_parameter_declaration(p):
'''special_parameter_declaration : abstract_parameter_declaration
| abstract_parameter_declaration '=' assignment_expression
| ELLIPSIS
'''
pass
def p_parameter_declaration(p):
'''parameter_declaration : assignment_expression
| special_parameter_declaration
| decl_specifier_prefix parameter_declaration
'''
pass
#
# function_definition includes constructor, destructor, implicit int definitions too. A local destructor is successfully parsed as a function-declaration but the ~ was treated as a unary operator. constructor_head is the prefix ambiguity between a constructor and a member-init-list starting with a bit-field.
#
def p_function_definition(p):
'''function_definition : ctor_definition
| func_definition
'''
pass
def p_func_definition(p):
'''func_definition : assignment_expression function_try_block
| assignment_expression function_body
| decl_specifier_prefix func_definition
'''
global _parse_info
if p[2] is not None and p[2][0] == '{':
decl = flatten(p[1])
#print "HERE",decl
if decl[-1] == ')':
decl=decl[-3]
else:
decl=decl[-1]
p[0] = decl
if decl != "operator":
_parse_info.add_function(decl)
else:
p[0] = p[2]
def p_ctor_definition(p):
'''ctor_definition : constructor_head function_try_block
| constructor_head function_body
| decl_specifier_prefix ctor_definition
'''
if p[2] is None or p[2][0] == "try" or p[2][0] == '{':
p[0]=p[1]
else:
p[0]=p[1]
def p_constructor_head(p):
'''constructor_head : bit_field_init_declaration
| constructor_head ',' assignment_expression
'''
p[0]=p[1]
def p_function_try_block(p):
'''function_try_block : TRY function_block handler_seq
'''
global noExceptionLogic
noExceptionLogic=False
p[0] = ['try']
def p_function_block(p):
'''function_block : ctor_initializer_opt function_body
'''
pass
def p_function_body(p):
'''function_body : LBRACE nonbrace_seq_opt RBRACE
'''
p[0] = ['{','}']
def p_initializer_clause(p):
'''initializer_clause : assignment_expression
| braced_initializer
'''
pass
def p_braced_initializer(p):
'''braced_initializer : LBRACE initializer_list RBRACE
| LBRACE initializer_list ',' RBRACE
| LBRACE RBRACE
'''
pass
def p_initializer_list(p):
'''initializer_list : initializer_clause
| initializer_list ',' initializer_clause
'''
pass
#---------------------------------------------------------------------------------------------------
# A.8 Classes
#---------------------------------------------------------------------------------------------------
#
# An anonymous bit-field declaration may look very like inheritance:
# const int B = 3;
# class A : B ;
# The two usages are too distant to try to create and enforce a common prefix so we have to resort to
# a parser hack by backtracking. Inheritance is much the most likely so we mark the input stream context
# and try to parse a base-clause. If we successfully reach a { the base-clause is ok and inheritance was
# the correct choice so we unmark and continue. If we fail to find the { an error token causes
# back-tracking to the alternative parse in elaborated_type_specifier which regenerates the : and
# declares unconditional success.
#
def p_class_specifier_head(p):
'''class_specifier_head : class_key scoped_id ':' base_specifier_list LBRACE
| class_key ':' base_specifier_list LBRACE
| class_key scoped_id LBRACE
| class_key LBRACE
'''
global _parse_info
base_classes=[]
if len(p) == 6:
scope = p[2]
base_classes = p[4]
elif len(p) == 4:
scope = p[2]
elif len(p) == 5:
base_classes = p[3]
else:
scope = ""
_parse_info.push_scope(scope,p[1],base_classes)
def p_class_key(p):
'''class_key : CLASS
| STRUCT
| UNION
'''
p[0] = p[1]
def p_class_specifier(p):
'''class_specifier : class_specifier_head member_specification_opt RBRACE
'''
scope = _parse_info.pop_scope()
def p_member_specification_opt(p):
'''member_specification_opt : empty
| member_specification_opt member_declaration
'''
pass
def p_member_declaration(p):
'''member_declaration : accessibility_specifier
| simple_member_declaration
| function_definition
| using_declaration
| template_declaration
'''
p[0] = get_rest(p)
#print "Decl",get_rest(p)
#
# The generality of constructor names (there need be no parenthesised argument list) means that that
# name : f(g), h(i)
# could be the start of a constructor or the start of an anonymous bit-field. An ambiguity is avoided by
# parsing the ctor-initializer of a function_definition as a bit-field.
#
def p_simple_member_declaration(p):
'''simple_member_declaration : ';'
| assignment_expression ';'
| constructor_head ';'
| member_init_declarations ';'
| decl_specifier_prefix simple_member_declaration
'''
global _parse_info
decl = flatten(get_rest(p))
if len(decl) >= 4 and decl[-3] == "(":
_parse_info.add_function(decl[-4])
def p_member_init_declarations(p):
'''member_init_declarations : assignment_expression ',' member_init_declaration
| constructor_head ',' bit_field_init_declaration
| member_init_declarations ',' member_init_declaration
'''
pass
def p_member_init_declaration(p):
'''member_init_declaration : assignment_expression
| bit_field_init_declaration
'''
pass
def p_accessibility_specifier(p):
'''accessibility_specifier : access_specifier ':'
'''
pass
def p_bit_field_declaration(p):
'''bit_field_declaration : assignment_expression ':' bit_field_width
| ':' bit_field_width
'''
if len(p) == 4:
p[0]=p[1]
def p_bit_field_width(p):
'''bit_field_width : logical_or_expression
| logical_or_expression '?' bit_field_width ':' bit_field_width
'''
pass
def p_bit_field_init_declaration(p):
'''bit_field_init_declaration : bit_field_declaration
| bit_field_declaration '=' initializer_clause
'''
pass
#---------------------------------------------------------------------------------------------------
# A.9 Derived classes
#---------------------------------------------------------------------------------------------------
def p_base_specifier_list(p):
'''base_specifier_list : base_specifier
| base_specifier_list ',' base_specifier
'''
if len(p) == 2:
p[0] = [p[1]]
else:
p[0] = p[1]+[p[3]]
def p_base_specifier(p):
'''base_specifier : scoped_id
| access_specifier base_specifier
| VIRTUAL base_specifier
'''
if len(p) == 2:
p[0] = p[1]
else:
p[0] = p[2]
def p_access_specifier(p):
'''access_specifier : PRIVATE
| PROTECTED
| PUBLIC
'''
pass
#---------------------------------------------------------------------------------------------------
# A.10 Special member functions
#---------------------------------------------------------------------------------------------------
def p_conversion_function_id(p):
'''conversion_function_id : OPERATOR conversion_type_id
'''
p[0] = ['operator']
def p_conversion_type_id(p):
'''conversion_type_id : type_specifier ptr_operator_seq_opt
| type_specifier conversion_type_id
'''
pass
#
# Ctor-initialisers can look like a bit field declaration, given the generalisation of names:
# Class(Type) : m1(1), m2(2) { }
# NonClass(bit_field) : int(2), second_variable, ...
# The grammar below is used within a function_try_block or function_definition.
# See simple_member_declaration for use in normal member function_definition.
#
def p_ctor_initializer_opt(p):
'''ctor_initializer_opt : empty
| ctor_initializer
'''
pass
def p_ctor_initializer(p):
'''ctor_initializer : ':' mem_initializer_list
'''
pass
def p_mem_initializer_list(p):
'''mem_initializer_list : mem_initializer
| mem_initializer_list_head mem_initializer
'''
pass
def p_mem_initializer_list_head(p):
'''mem_initializer_list_head : mem_initializer_list ','
'''
pass
def p_mem_initializer(p):
'''mem_initializer : mem_initializer_id '(' expression_list_opt ')'
'''
pass
def p_mem_initializer_id(p):
'''mem_initializer_id : scoped_id
'''
pass
#---------------------------------------------------------------------------------------------------
# A.11 Overloading
#---------------------------------------------------------------------------------------------------
def p_operator_function_id(p):
'''operator_function_id : OPERATOR operator
| OPERATOR '(' ')'
| OPERATOR LBRACKET RBRACKET
| OPERATOR '<'
| OPERATOR '>'
| OPERATOR operator '<' nonlgt_seq_opt '>'
'''
p[0] = ["operator"]
#
# It is not clear from the ANSI standard whether spaces are permitted in delete[]. If not then it can
# be recognised and returned as DELETE_ARRAY by the lexer. Assuming spaces are permitted there is an
# ambiguity created by the over generalised nature of expressions. operator new is a valid delarator-id
# which we may have an undimensioned array of. Semantic rubbish, but syntactically valid. Since the
# array form is covered by the declarator consideration we can exclude the operator here. The need
# for a semantic rescue can be eliminated at the expense of a couple of shift-reduce conflicts by
# removing the comments on the next four lines.
#
def p_operator(p):
'''operator : NEW
| DELETE
| '+'
| '-'
| '*'
| '/'
| '%'
| '^'
| '&'
| '|'
| '~'
| '!'
| '='
| ASS_ADD
| ASS_SUB
| ASS_MUL
| ASS_DIV
| ASS_MOD
| ASS_XOR
| ASS_AND
| ASS_OR
| SHL
| SHR
| ASS_SHR
| ASS_SHL
| EQ
| NE
| LE
| GE
| LOG_AND
| LOG_OR
| INC
| DEC
| ','
| ARROW_STAR
| ARROW
'''
p[0]=p[1]
# | IF
# | SWITCH
# | WHILE
# | FOR
# | DO
def p_reserved(p):
'''reserved : PRIVATE
| CLiteral
| CppLiteral
| IF
| SWITCH
| WHILE
| FOR
| DO
| PROTECTED
| PUBLIC
| BOOL
| CHAR
| DOUBLE
| FLOAT
| INT
| LONG
| SHORT
| SIGNED
| UNSIGNED
| VOID
| WCHAR_T
| CLASS
| ENUM
| NAMESPACE
| STRUCT
| TYPENAME
| UNION
| CONST
| VOLATILE
| AUTO
| EXPLICIT
| EXPORT
| EXTERN
| FRIEND
| INLINE
| MUTABLE
| REGISTER
| STATIC
| TEMPLATE
| TYPEDEF
| USING
| VIRTUAL
| ASM
| BREAK
| CASE
| CATCH
| CONST_CAST
| CONTINUE
| DEFAULT
| DYNAMIC_CAST
| ELSE
| FALSE
| GOTO
| OPERATOR
| REINTERPRET_CAST
| RETURN
| SIZEOF
| STATIC_CAST
| THIS
| THROW
| TRUE
| TRY
| TYPEID
| ATTRIBUTE
| CDECL
| TYPEOF
| uTYPEOF
'''
if p[1] in ('try', 'catch', 'throw'):
global noExceptionLogic
noExceptionLogic=False
#---------------------------------------------------------------------------------------------------
# A.12 Templates
#---------------------------------------------------------------------------------------------------
def p_template_declaration(p):
'''template_declaration : template_parameter_clause declaration
| EXPORT template_declaration
'''
pass
def p_template_parameter_clause(p):
'''template_parameter_clause : TEMPLATE '<' nonlgt_seq_opt '>'
'''
pass
#
# Generalised naming makes identifier a valid declaration, so TEMPLATE identifier is too.
# The TEMPLATE prefix is therefore folded into all names, parenthesis_clause and decl_specifier_prefix.
#
# explicit_instantiation: TEMPLATE declaration
#
def p_explicit_specialization(p):
'''explicit_specialization : TEMPLATE '<' '>' declaration
'''
pass
#---------------------------------------------------------------------------------------------------
# A.13 Exception Handling
#---------------------------------------------------------------------------------------------------
def p_handler_seq(p):
'''handler_seq : handler
| handler handler_seq
'''
pass
def p_handler(p):
'''handler : CATCH '(' exception_declaration ')' compound_statement
'''
global noExceptionLogic
noExceptionLogic=False
def p_exception_declaration(p):
'''exception_declaration : parameter_declaration
'''
pass
def p_throw_expression(p):
'''throw_expression : THROW
| THROW assignment_expression
'''
global noExceptionLogic
noExceptionLogic=False
def p_exception_specification(p):
'''exception_specification : THROW '(' ')'
| THROW '(' type_id_list ')'
'''
global noExceptionLogic
noExceptionLogic=False
def p_type_id_list(p):
'''type_id_list : type_id
| type_id_list ',' type_id
'''
pass
#---------------------------------------------------------------------------------------------------
# Misc productions
#---------------------------------------------------------------------------------------------------
def p_nonsemicolon_seq(p):
'''nonsemicolon_seq : empty
| nonsemicolon_seq nonsemicolon
'''
pass
def p_nonsemicolon(p):
'''nonsemicolon : misc
| '('
| ')'
| '<'
| '>'
| LBRACKET nonbracket_seq_opt RBRACKET
| LBRACE nonbrace_seq_opt RBRACE
'''
pass
def p_nonparen_seq_opt(p):
'''nonparen_seq_opt : empty
| nonparen_seq_opt nonparen
'''
pass
def p_nonparen_seq(p):
'''nonparen_seq : nonparen
| nonparen_seq nonparen
'''
pass
def p_nonparen(p):
'''nonparen : misc
| '<'
| '>'
| ';'
| LBRACKET nonbracket_seq_opt RBRACKET
| LBRACE nonbrace_seq_opt RBRACE
'''
pass
def p_nonbracket_seq_opt(p):
'''nonbracket_seq_opt : empty
| nonbracket_seq_opt nonbracket
'''
pass
def p_nonbracket_seq(p):
'''nonbracket_seq : nonbracket
| nonbracket_seq nonbracket
'''
pass
def p_nonbracket(p):
'''nonbracket : misc
| '<'
| '>'
| '('
| ')'
| ';'
| LBRACKET nonbracket_seq_opt RBRACKET
| LBRACE nonbrace_seq_opt RBRACE
'''
pass
def p_nonbrace_seq_opt(p):
'''nonbrace_seq_opt : empty
| nonbrace_seq_opt nonbrace
'''
pass
def p_nonbrace(p):
'''nonbrace : misc
| '<'
| '>'
| '('
| ')'
| ';'
| LBRACKET nonbracket_seq_opt RBRACKET
| LBRACE nonbrace_seq_opt RBRACE
'''
pass
def p_nonlgt_seq_opt(p):
'''nonlgt_seq_opt : empty
| nonlgt_seq_opt nonlgt
'''
pass
def p_nonlgt(p):
'''nonlgt : misc
| '('
| ')'
| LBRACKET nonbracket_seq_opt RBRACKET
| '<' nonlgt_seq_opt '>'
| ';'
'''
pass
def p_misc(p):
'''misc : operator
| identifier
| IntegerLiteral
| CharacterLiteral
| FloatingLiteral
| StringLiteral
| reserved
| '?'
| ':'
| '.'
| SCOPE
| ELLIPSIS
| EXTENSION
'''
pass
def p_empty(p):
'''empty : '''
pass
#
# Compute column.
# input is the input text string
# token is a token instance
#
def _find_column(input,token):
''' TODO '''
i = token.lexpos
while i > 0:
if input[i] == '\n': break
i -= 1
column = (token.lexpos - i)+1
return column
def p_error(p):
if p is None:
tmp = "Syntax error at end of file."
else:
tmp = "Syntax error at token "
if p.type is "":
tmp = tmp + "''"
else:
tmp = tmp + str(p.type)
tmp = tmp + " with value '"+str(p.value)+"'"
tmp = tmp + " in line " + str(lexer.lineno-1)
tmp = tmp + " at column "+str(_find_column(_parsedata,p))
raise IOError( tmp )
#
# The function that performs the parsing
#
def parse_cpp(data=None, filename=None, debug=0, optimize=0, verbose=False, func_filter=None):
if debug > 0:
print("Debugging parse_cpp!")
#
# Always remove the parser.out file, which is generated to create debugging
#
if os.path.exists("parser.out"):
os.remove("parser.out")
#
# Remove the parsetab.py* files. These apparently need to be removed
# to ensure the creation of a parser.out file.
#
if os.path.exists("parsetab.py"):
os.remove("parsetab.py")
if os.path.exists("parsetab.pyc"):
os.remove("parsetab.pyc")
global debugging
debugging=True
#
# Build lexer
#
global lexer
lexer = lex.lex()
#
# Initialize parse object
#
global _parse_info
_parse_info = CppInfo(filter=func_filter)
_parse_info.verbose=verbose
#
# Build yaccer
#
write_table = not os.path.exists("parsetab.py")
yacc.yacc(debug=debug, optimize=optimize, write_tables=write_table)
#
# Parse the file
#
global _parsedata
if not data is None:
_parsedata=data
ply_init(_parsedata)
yacc.parse(data,debug=debug)
elif not filename is None:
f = open(filename)
data = f.read()
f.close()
_parsedata=data
ply_init(_parsedata)
yacc.parse(data, debug=debug)
else:
return None
#
if not noExceptionLogic:
_parse_info.noExceptionLogic = False
else:
for key in identifier_lineno:
if 'ASSERT_THROWS' in key:
_parse_info.noExceptionLogic = False
break
_parse_info.noExceptionLogic = True
#
return _parse_info
import sys
if __name__ == '__main__':
#
# This MAIN routine parses a sequence of files provided at the command
# line. If '-v' is included, then a verbose parsing output is
# generated.
#
for arg in sys.argv[1:]:
if arg == "-v":
continue
print("Parsing file '"+arg+"'")
if '-v' in sys.argv:
parse_cpp(filename=arg,debug=2,verbose=2)
else:
parse_cpp(filename=arg,verbose=2)
#
# Print the _parse_info object summary for this file.
# This illustrates how class inheritance can be used to
# deduce class members.
#
print(str(_parse_info))
| [
[
1,
0,
0.0238,
0.0005,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0242,
0.0005,
0,
0.66,
0.004,
837,
0,
1,
0,
0,
837,
0,
0
],
[
1,
0,
0.0247,
0.0005,
0,
0... | [
"import os",
"import ply.lex as lex",
"import ply.yacc as yacc",
"import re",
"try:\n from collections import OrderedDict\nexcept ImportError:\n from ordereddict import OrderedDict",
" from collections import OrderedDict",
" from ordereddict import OrderedDict",
"lexer = None",
"scope_li... |
#-------------------------------------------------------------------------
# CxxTest: A lightweight C++ unit testing library.
# Copyright (c) 2008 Sandia Corporation.
# This software is distributed under the LGPL License v2.1
# For more information, see the COPYING file in the top CxxTest directory.
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains certain rights in this software.
#-------------------------------------------------------------------------
"""cxxtest: A Python package that supports the CxxTest test framework for C/C++.
.. _CxxTest: http://cxxtest.tigris.org/
CxxTest is a unit testing framework for C++ that is similar in
spirit to JUnit, CppUnit, and xUnit. CxxTest is easy to use because
it does not require precompiling a CxxTest testing library, it
employs no advanced features of C++ (e.g. RTTI) and it supports a
very flexible form of test discovery.
The cxxtest Python package includes capabilities for parsing C/C++ source files and generating
CxxTest drivers.
"""
from cxxtest.__release__ import __version__, __date__
__date__
__version__
__maintainer__ = "William E. Hart"
__maintainer_email__ = "whart222@gmail.com"
__license__ = "LGPL"
__url__ = "http://cxxtest.tigris.org/"
from cxxtest.cxxtestgen import *
| [
[
8,
0,
0.4848,
0.3939,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.7273,
0.0303,
0,
0.66,
0.125,
129,
0,
2,
0,
0,
129,
0,
0
],
[
8,
0,
0.7576,
0.0303,
0,
0.66,... | [
"\"\"\"cxxtest: A Python package that supports the CxxTest test framework for C/C++.\n\n.. _CxxTest: http://cxxtest.tigris.org/\n\nCxxTest is a unit testing framework for C++ that is similar in\nspirit to JUnit, CppUnit, and xUnit. CxxTest is easy to use because\nit does not require precompiling a CxxTest testing l... |
#!/usr/bin/python
#-------------------------------------------------------------------------
# CxxTest: A lightweight C++ unit testing library.
# Copyright (c) 2008 Sandia Corporation.
# This software is distributed under the LGPL License v2.1
# For more information, see the COPYING file in the top CxxTest directory.
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains certain rights in this software.
#-------------------------------------------------------------------------
import sys
def abort( problem ):
'''Print error message and exit'''
sys.stderr.write( '\n' )
sys.stderr.write( problem )
sys.stderr.write( '\n\n' )
sys.exit(2)
| [
[
1,
0,
0.5789,
0.0526,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
2,
0,
0.8158,
0.3158,
0,
0.66,
1,
299,
0,
1,
0,
0,
0,
0,
4
],
[
8,
1,
0.7368,
0.0526,
1,
0.11,
... | [
"import sys",
"def abort( problem ):\n '''Print error message and exit'''\n sys.stderr.write( '\\n' )\n sys.stderr.write( problem )\n sys.stderr.write( '\\n\\n' )\n sys.exit(2)",
" '''Print error message and exit'''",
" sys.stderr.write( '\\n' )",
" sys.stderr.write( problem )",
" ... |
#-------------------------------------------------------------------------
# CxxTest: A lightweight C++ unit testing library.
# Copyright (c) 2008 Sandia Corporation.
# This software is distributed under the LGPL License v2.1
# For more information, see the COPYING file in the top CxxTest directory.
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains certain rights in this software.
#-------------------------------------------------------------------------
#
# TODO: add line number info
# TODO: add test function names
#
import sys
import re
#from os.path import abspath, dirname
#sys.path.insert(0, dirname(dirname(abspath(__file__))))
#sys.path.insert(0, dirname(dirname(abspath(__file__)))+"/cxx_parse")
from .cxxtest_misc import abort
from . import cxx_parser
import re
def cstr( str ):
'''Convert a string to its C representation'''
return '"' + re.sub('\\\\', '\\\\\\\\', str ) + '"'
def scanInputFiles(files, _options):
'''Scan all input files for test suites'''
suites=[]
for file in files:
try:
print("Parsing file "+file, end=' ')
sys.stdout.flush()
parse_info = cxx_parser.parse_cpp(filename=file,optimize=1)
except IOError as err:
print(" error.")
print(str(err))
continue
print("done.")
sys.stdout.flush()
#
# WEH: see if it really makes sense to use parse information to
# initialize this data. I don't think so...
#
_options.haveStandardLibrary=1
if not parse_info.noExceptionLogic:
_options.haveExceptionHandling=1
#
keys = list(parse_info.index.keys())
tpat = re.compile("[Tt][Ee][Ss][Tt]")
for key in keys:
if parse_info.index[key].scope_t == "class" and parse_info.is_baseclass(key,"CxxTest::TestSuite"):
name=parse_info.index[key].name
suite = { 'name' : name,
'file' : file,
'cfile' : cstr(file),
'line' : str(parse_info.index[key].lineno),
'generated' : 0,
'object' : 'suite_%s' % name,
'dobject' : 'suiteDescription_%s' % name,
'tlist' : 'Tests_%s' % name,
'tests' : [],
'lines' : [] }
for fn in parse_info.get_functions(key,quiet=True):
tname = fn[0]
lineno = str(fn[1])
if tname.startswith('createSuite'):
# Indicate that we're using a dynamically generated test suite
suite['create'] = str(lineno) # (unknown line)
if tname.startswith('destroySuite'):
# Indicate that we're using a dynamically generated test suite
suite['destroy'] = str(lineno) # (unknown line)
if not tpat.match(tname):
# Skip non-test methods
continue
test = { 'name' : tname,
'suite' : suite,
'class' : 'TestDescription_suite_%s_%s' % (suite['name'], tname),
'object' : 'testDescription_suite_%s_%s' % (suite['name'], tname),
'line' : lineno,
}
suite['tests'].append(test)
suites.append(suite)
if not _options.root:
ntests = 0
for suite in suites:
ntests += len(suite['tests'])
if ntests == 0:
abort( 'No tests defined' )
#
return [_options, suites]
| [
[
1,
0,
0.1771,
0.0104,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.1875,
0.0104,
0,
0.66,
0.1667,
540,
0,
1,
0,
0,
540,
0,
0
],
[
1,
0,
0.2292,
0.0104,
0,
... | [
"import sys",
"import re",
"from .cxxtest_misc import abort",
"from . import cxx_parser",
"import re",
"def cstr( str ):\n '''Convert a string to its C representation'''\n return '\"' + re.sub('\\\\\\\\', '\\\\\\\\\\\\\\\\', str ) + '\"'",
" '''Convert a string to its C representation'''",
" ... |
#-------------------------------------------------------------------------
# CxxTest: A lightweight C++ unit testing library.
# Copyright (c) 2008 Sandia Corporation.
# This software is distributed under the LGPL License v2.1
# For more information, see the COPYING file in the top CxxTest directory.
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains certain rights in this software.
#-------------------------------------------------------------------------
# vim: fileencoding=utf-8
# the above import important for forward-compatibility with python3,
# which is already the default in archlinux!
__all__ = ['main']
from . import __release__
import os
import sys
import re
import glob
from optparse import OptionParser
from . import cxxtest_parser
try:
from . import cxxtest_fog
imported_fog=True
except ImportError:
imported_fog=False
from .cxxtest_misc import abort
options = []
suites = []
wrotePreamble = 0
wroteWorld = 0
lastIncluded = ''
def main(args=sys.argv):
'''The main program'''
#
# Reset global state
#
global wrotePreamble
wrotePreamble=0
global wroteWorld
wroteWorld=0
global lastIncluded
lastIncluded = ''
global suites
global options
files = parseCommandline(args)
if imported_fog and options.fog:
[options,suites] = cxxtest_fog.scanInputFiles( files, options )
else:
[options,suites] = cxxtest_parser.scanInputFiles( files, options )
writeOutput()
def parseCommandline(args):
'''Analyze command line arguments'''
global imported_fog
global options
parser = OptionParser("%prog [options] [<filename> ...]")
parser.add_option("--version",
action="store_true", dest="version", default=False,
help="Write the CxxTest version.")
parser.add_option("-o", "--output",
dest="outputFileName", default=None, metavar="NAME",
help="Write output to file NAME.")
parser.add_option("-w","--world", dest="world", default="cxxtest",
help="The label of the tests, used to name the XML results.")
parser.add_option("", "--include", action="append",
dest="headers", default=[], metavar="HEADER",
help="Include file HEADER in the test runner before other headers.")
parser.add_option("", "--abort-on-fail",
action="store_true", dest="abortOnFail", default=False,
help="Abort tests on failed asserts (like xUnit).")
parser.add_option("", "--main",
action="store", dest="main", default="main",
help="Specify an alternative name for the main() function.")
parser.add_option("", "--headers",
action="store", dest="header_filename", default=None,
help="Specify a filename that contains a list of header files that are processed to generate a test runner.")
parser.add_option("", "--runner",
dest="runner", default="", metavar="CLASS",
help="Create a test runner that processes test events using the class CxxTest::CLASS.")
parser.add_option("", "--gui",
dest="gui", metavar="CLASS",
help="Create a GUI test runner that processes test events using the class CxxTest::CLASS. (deprecated)")
parser.add_option("", "--error-printer",
action="store_true", dest="error_printer", default=False,
help="Create a test runner using the ErrorPrinter class, and allow the use of the standard library.")
parser.add_option("", "--xunit-printer",
action="store_true", dest="xunit_printer", default=False,
help="Create a test runner using the XUnitPrinter class.")
parser.add_option("", "--xunit-file", dest="xunit_file", default="",
help="The file to which the XML summary is written for test runners using the XUnitPrinter class. The default XML filename is TEST-<world>.xml, where <world> is the value of the --world option. (default: cxxtest)")
parser.add_option("", "--have-std",
action="store_true", dest="haveStandardLibrary", default=False,
help="Use the standard library (even if not found in tests).")
parser.add_option("", "--no-std",
action="store_true", dest="noStandardLibrary", default=False,
help="Do not use standard library (even if found in tests).")
parser.add_option("", "--have-eh",
action="store_true", dest="haveExceptionHandling", default=False,
help="Use exception handling (even if not found in tests).")
parser.add_option("", "--no-eh",
action="store_true", dest="noExceptionHandling", default=False,
help="Do not use exception handling (even if found in tests).")
parser.add_option("", "--longlong",
dest="longlong", default=None, metavar="TYPE",
help="Use TYPE as for long long integers. (default: not supported)")
parser.add_option("", "--no-static-init",
action="store_true", dest="noStaticInit", default=False,
help="Do not rely on static initialization in the test runner.")
parser.add_option("", "--template",
dest="templateFileName", default=None, metavar="TEMPLATE",
help="Generate the test runner using file TEMPLATE to define a template.")
parser.add_option("", "--root",
action="store_true", dest="root", default=False,
help="Write the main() function and global data for a test runner.")
parser.add_option("", "--part",
action="store_true", dest="part", default=False,
help="Write the tester classes for a test runner.")
#parser.add_option("", "--factor",
#action="store_true", dest="factor", default=False,
#help="Declare the _CXXTEST_FACTOR macro. (deprecated)")
if imported_fog:
fog_help = "Use new FOG C++ parser"
else:
fog_help = "Use new FOG C++ parser (disabled)"
parser.add_option("-f", "--fog-parser",
action="store_true",
dest="fog",
default=False,
help=fog_help
)
(options, args) = parser.parse_args(args=args)
if not options.header_filename is None:
if not os.path.exists(options.header_filename):
abort( "ERROR: the file '%s' does not exist!" % options.header_filename )
INPUT = open(options.header_filename)
headers = [line.strip() for line in INPUT]
args.extend( headers )
INPUT.close()
if options.fog and not imported_fog:
abort( "Cannot use the FOG parser. Check that the 'ply' package is installed. The 'ordereddict' package is also required if running Python 2.6")
if options.version:
printVersion()
# the cxxtest builder relies on this behaviour! don't remove
if options.runner == 'none':
options.runner = None
if options.xunit_printer or options.runner == "XUnitPrinter":
options.xunit_printer=True
options.runner="XUnitPrinter"
if len(args) > 1:
if options.xunit_file == "":
if options.world == "":
options.world = "cxxtest"
options.xunit_file="TEST-"+options.world+".xml"
elif options.xunit_file == "":
if options.world == "":
options.world = "cxxtest"
options.xunit_file="TEST-"+options.world+".xml"
if options.error_printer:
options.runner= "ErrorPrinter"
options.haveStandardLibrary = True
if options.noStaticInit and (options.root or options.part):
abort( '--no-static-init cannot be used with --root/--part' )
if options.gui and not options.runner:
options.runner = 'StdioPrinter'
files = setFiles(args[1:])
if len(files) == 0 and not options.root:
sys.stderr.write(parser.error("No input files found"))
return files
def printVersion():
'''Print CxxTest version and exit'''
sys.stdout.write( "This is CxxTest version %s.\n" % __release__.__version__ )
sys.exit(0)
def setFiles(patterns ):
'''Set input files specified on command line'''
files = expandWildcards( patterns )
return files
def expandWildcards( patterns ):
'''Expand all wildcards in an array (glob)'''
fileNames = []
for pathName in patterns:
patternFiles = glob.glob( pathName )
for fileName in patternFiles:
fileNames.append( fixBackslashes( fileName ) )
return fileNames
def fixBackslashes( fileName ):
'''Convert backslashes to slashes in file name'''
return re.sub( r'\\', '/', fileName, 0 )
def writeOutput():
'''Create output file'''
if options.templateFileName:
writeTemplateOutput()
else:
writeSimpleOutput()
def writeSimpleOutput():
'''Create output not based on template'''
output = startOutputFile()
writePreamble( output )
if options.root or not options.part:
writeMain( output )
if len(suites) > 0:
output.write("bool "+suites[0]['object']+"_init = false;\n")
writeWorld( output )
output.close()
include_re = re.compile( r"\s*\#\s*include\s+<cxxtest/" )
preamble_re = re.compile( r"^\s*<CxxTest\s+preamble>\s*$" )
world_re = re.compile( r"^\s*<CxxTest\s+world>\s*$" )
def writeTemplateOutput():
'''Create output based on template file'''
template = open(options.templateFileName)
output = startOutputFile()
while 1:
line = template.readline()
if not line:
break;
if include_re.search( line ):
writePreamble( output )
output.write( line )
elif preamble_re.search( line ):
writePreamble( output )
elif world_re.search( line ):
if len(suites) > 0:
output.write("bool "+suites[0]['object']+"_init = false;\n")
writeWorld( output )
else:
output.write( line )
template.close()
output.close()
def startOutputFile():
'''Create output file and write header'''
if options.outputFileName is not None:
output = open( options.outputFileName, 'w' )
else:
output = sys.stdout
output.write( "/* Generated file, do not edit */\n\n" )
return output
def writePreamble( output ):
'''Write the CxxTest header (#includes and #defines)'''
global wrotePreamble
if wrotePreamble: return
output.write( "#ifndef CXXTEST_RUNNING\n" )
output.write( "#define CXXTEST_RUNNING\n" )
output.write( "#endif\n" )
output.write( "\n" )
if options.xunit_printer:
output.write( "#include <fstream>\n" )
if options.haveStandardLibrary:
output.write( "#define _CXXTEST_HAVE_STD\n" )
if options.haveExceptionHandling:
output.write( "#define _CXXTEST_HAVE_EH\n" )
if options.abortOnFail:
output.write( "#define _CXXTEST_ABORT_TEST_ON_FAIL\n" )
if options.longlong:
output.write( "#define _CXXTEST_LONGLONG %s\n" % options.longlong )
#if options.factor:
#output.write( "#define _CXXTEST_FACTOR\n" )
for header in options.headers:
output.write( "#include \"%s\"\n" % header )
output.write( "#include <cxxtest/TestListener.h>\n" )
output.write( "#include <cxxtest/TestTracker.h>\n" )
output.write( "#include <cxxtest/TestRunner.h>\n" )
output.write( "#include <cxxtest/RealDescriptions.h>\n" )
output.write( "#include <cxxtest/TestMain.h>\n" )
if options.runner:
output.write( "#include <cxxtest/%s.h>\n" % options.runner )
if options.gui:
output.write( "#include <cxxtest/%s.h>\n" % options.gui )
output.write( "\n" )
wrotePreamble = 1
def writeMain( output ):
'''Write the main() function for the test runner'''
if not (options.gui or options.runner):
return
output.write( 'int %s( int argc, char *argv[] ) {\n' % options.main )
output.write( ' int status;\n' )
if options.noStaticInit:
output.write( ' CxxTest::initialize();\n' )
if options.gui:
tester_t = "CxxTest::GuiTuiRunner<CxxTest::%s, CxxTest::%s> " % (options.gui, options.runner)
else:
tester_t = "CxxTest::%s" % (options.runner)
if options.xunit_printer:
output.write( ' std::ofstream ofstr("%s");\n' % options.xunit_file )
output.write( ' %s tmp(ofstr);\n' % tester_t )
output.write( ' CxxTest::RealWorldDescription::_worldName = "%s";\n' % options.world )
else:
output.write( ' %s tmp;\n' % tester_t )
output.write( ' status = CxxTest::Main<%s>( tmp, argc, argv );\n' % tester_t )
output.write( ' return status;\n')
output.write( '}\n' )
def writeWorld( output ):
'''Write the world definitions'''
global wroteWorld
if wroteWorld: return
writePreamble( output )
writeSuites( output )
if options.root or not options.part:
writeRoot( output )
writeWorldDescr( output )
if options.noStaticInit:
writeInitialize( output )
wroteWorld = 1
def writeSuites(output):
'''Write all TestDescriptions and SuiteDescriptions'''
for suite in suites:
writeInclude( output, suite['file'] )
if isGenerated(suite):
generateSuite( output, suite )
if isDynamic(suite):
writeSuitePointer( output, suite )
else:
writeSuiteObject( output, suite )
writeTestList( output, suite )
writeSuiteDescription( output, suite )
writeTestDescriptions( output, suite )
def isGenerated(suite):
'''Checks whether a suite class should be created'''
return suite['generated']
def isDynamic(suite):
'''Checks whether a suite is dynamic'''
return 'create' in suite
def writeInclude(output, file):
'''Add #include "file" statement'''
global lastIncluded
if file == lastIncluded: return
output.writelines( [ '#include "', file, '"\n\n' ] )
lastIncluded = file
def generateSuite( output, suite ):
'''Write a suite declared with CXXTEST_SUITE()'''
output.write( 'class %s : public CxxTest::TestSuite {\n' % suite['name'] )
output.write( 'public:\n' )
for line in suite['lines']:
output.write(line)
output.write( '};\n\n' )
def writeSuitePointer( output, suite ):
'''Create static suite pointer object for dynamic suites'''
if options.noStaticInit:
output.write( 'static %s *%s;\n\n' % (suite['name'], suite['object']) )
else:
output.write( 'static %s *%s = 0;\n\n' % (suite['name'], suite['object']) )
def writeSuiteObject( output, suite ):
'''Create static suite object for non-dynamic suites'''
output.writelines( [ "static ", suite['name'], " ", suite['object'], ";\n\n" ] )
def writeTestList( output, suite ):
'''Write the head of the test linked list for a suite'''
if options.noStaticInit:
output.write( 'static CxxTest::List %s;\n' % suite['tlist'] )
else:
output.write( 'static CxxTest::List %s = { 0, 0 };\n' % suite['tlist'] )
def writeWorldDescr( output ):
'''Write the static name of the world name'''
if options.noStaticInit:
output.write( 'const char* CxxTest::RealWorldDescription::_worldName;\n' )
else:
output.write( 'const char* CxxTest::RealWorldDescription::_worldName = "cxxtest";\n' )
def writeTestDescriptions( output, suite ):
'''Write all test descriptions for a suite'''
for test in suite['tests']:
writeTestDescription( output, suite, test )
def writeTestDescription( output, suite, test ):
'''Write test description object'''
output.write( 'static class %s : public CxxTest::RealTestDescription {\n' % test['class'] )
output.write( 'public:\n' )
if not options.noStaticInit:
output.write( ' %s() : CxxTest::RealTestDescription( %s, %s, %s, "%s" ) {}\n' %
(test['class'], suite['tlist'], suite['dobject'], test['line'], test['name']) )
output.write( ' void runTest() { %s }\n' % runBody( suite, test ) )
output.write( '} %s;\n\n' % test['object'] )
def runBody( suite, test ):
'''Body of TestDescription::run()'''
if isDynamic(suite): return dynamicRun( suite, test )
else: return staticRun( suite, test )
def dynamicRun( suite, test ):
'''Body of TestDescription::run() for test in a dynamic suite'''
return 'if ( ' + suite['object'] + ' ) ' + suite['object'] + '->' + test['name'] + '();'
def staticRun( suite, test ):
'''Body of TestDescription::run() for test in a non-dynamic suite'''
return suite['object'] + '.' + test['name'] + '();'
def writeSuiteDescription( output, suite ):
'''Write SuiteDescription object'''
if isDynamic( suite ):
writeDynamicDescription( output, suite )
else:
writeStaticDescription( output, suite )
def writeDynamicDescription( output, suite ):
'''Write SuiteDescription for a dynamic suite'''
output.write( 'CxxTest::DynamicSuiteDescription<%s> %s' % (suite['name'], suite['dobject']) )
if not options.noStaticInit:
output.write( '( %s, %s, "%s", %s, %s, %s, %s )' %
(suite['cfile'], suite['line'], suite['name'], suite['tlist'],
suite['object'], suite['create'], suite['destroy']) )
output.write( ';\n\n' )
def writeStaticDescription( output, suite ):
'''Write SuiteDescription for a static suite'''
output.write( 'CxxTest::StaticSuiteDescription %s' % suite['dobject'] )
if not options.noStaticInit:
output.write( '( %s, %s, "%s", %s, %s )' %
(suite['cfile'], suite['line'], suite['name'], suite['object'], suite['tlist']) )
output.write( ';\n\n' )
def writeRoot(output):
'''Write static members of CxxTest classes'''
output.write( '#include <cxxtest/Root.cpp>\n' )
def writeInitialize(output):
'''Write CxxTest::initialize(), which replaces static initialization'''
output.write( 'namespace CxxTest {\n' )
output.write( ' void initialize()\n' )
output.write( ' {\n' )
for suite in suites:
output.write( ' %s.initialize();\n' % suite['tlist'] )
if isDynamic(suite):
output.write( ' %s = 0;\n' % suite['object'] )
output.write( ' %s.initialize( %s, %s, "%s", %s, %s, %s, %s );\n' %
(suite['dobject'], suite['cfile'], suite['line'], suite['name'],
suite['tlist'], suite['object'], suite['create'], suite['destroy']) )
else:
output.write( ' %s.initialize( %s, %s, "%s", %s, %s );\n' %
(suite['dobject'], suite['cfile'], suite['line'], suite['name'],
suite['object'], suite['tlist']) )
for test in suite['tests']:
output.write( ' %s.initialize( %s, %s, %s, "%s" );\n' %
(test['object'], suite['tlist'], suite['dobject'], test['line'], test['name']) )
output.write( ' }\n' )
output.write( '}\n' )
| [
[
14,
0,
0.0333,
0.0021,
0,
0.66,
0,
272,
0,
0,
0,
0,
0,
5,
0
],
[
1,
0,
0.0375,
0.0021,
0,
0.66,
0.0204,
0,
0,
1,
0,
0,
0,
0,
0
],
[
1,
0,
0.0396,
0.0021,
0,
0.66,... | [
"__all__ = ['main']",
"from . import __release__",
"import os",
"import sys",
"import re",
"import glob",
"from optparse import OptionParser",
"from . import cxxtest_parser",
"try:\n from . import cxxtest_fog\n imported_fog=True\nexcept ImportError:\n imported_fog=False",
" from . impo... |
#
# Execute this script to copy the cxxtest/*.py files
# and run 2to3 to convert them to Python 3.
#
import glob
import subprocess
import os
import shutil
os.chdir('cxxtest')
for file in glob.glob('*.py'):
shutil.copyfile(file, '../python3/cxxtest/'+file)
#
os.chdir('../python3/cxxtest')
#
for file in glob.glob('*.py'):
subprocess.call('2to3 -w '+file, shell=True)
| [
[
1,
0,
0.3158,
0.0526,
0,
0.66,
0,
958,
0,
1,
0,
0,
958,
0,
0
],
[
1,
0,
0.3684,
0.0526,
0,
0.66,
0.1429,
394,
0,
1,
0,
0,
394,
0,
0
],
[
1,
0,
0.4211,
0.0526,
0,
... | [
"import glob",
"import subprocess",
"import os",
"import shutil",
"os.chdir('cxxtest')",
"for file in glob.glob('*.py'):\n shutil.copyfile(file, '../python3/cxxtest/'+file)",
" shutil.copyfile(file, '../python3/cxxtest/'+file)",
"os.chdir('../python3/cxxtest')",
"for file in glob.glob('*.py'):... |
#! python
import cxxtest.cxxtestgen
cxxtest.cxxtestgen.main()
| [
[
1,
0,
0.6,
0.2,
0,
0.66,
0,
686,
0,
1,
0,
0,
686,
0,
0
],
[
8,
0,
1,
0.2,
0,
0.66,
1,
624,
3,
0,
0,
0,
0,
0,
1
]
] | [
"import cxxtest.cxxtestgen",
"cxxtest.cxxtestgen.main()"
] |
"""
Script to generate the installer for cxxtest.
"""
classifiers = """\
Development Status :: 4 - Beta
Intended Audience :: End Users/Desktop
License :: OSI Approved :: LGPL License
Natural Language :: English
Operating System :: Microsoft :: Windows
Operating System :: Unix
Programming Language :: Python
Topic :: Software Development :: Libraries :: Python Modules
"""
import os
import sys
from os.path import realpath, dirname
if sys.version_info >= (3,0):
sys.path.insert(0, dirname(realpath(__file__))+os.sep+'python3')
os.chdir('python3')
import cxxtest
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
doclines = cxxtest.__doc__.split("\n")
setup(name="cxxtest",
version=cxxtest.__version__,
maintainer=cxxtest.__maintainer__,
maintainer_email=cxxtest.__maintainer_email__,
url = cxxtest.__url__,
license = cxxtest.__license__,
platforms = ["any"],
description = doclines[0],
classifiers = filter(None, classifiers.split("\n")),
long_description = "\n".join(doclines[2:]),
packages=['cxxtest'],
keywords=['utility'],
scripts=['scripts/cxxtestgen']
#
# The entry_points option is not supported by distutils.core
#
#entry_points="""
#[console_scripts]
#cxxtestgen = cxxtest.cxxtestgen:main
#"""
)
| [
[
8,
0,
0.0377,
0.0566,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.1792,
0.1887,
0,
0.66,
0.1111,
963,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.3019,
0.0189,
0,
0.66,... | [
"\"\"\"\nScript to generate the installer for cxxtest.\n\"\"\"",
"classifiers = \"\"\"\\\nDevelopment Status :: 4 - Beta\nIntended Audience :: End Users/Desktop\nLicense :: OSI Approved :: LGPL License\nNatural Language :: English\nOperating System :: Microsoft :: Windows\nOperating System :: Unix\nProgramming La... |
#-------------------------------------------------------------------------
# CxxTest: A lightweight C++ unit testing library.
# Copyright (c) 2008 Sandia Corporation.
# This software is distributed under the LGPL License v2.1
# For more information, see the COPYING file in the top CxxTest directory.
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains certain rights in this software.
#-------------------------------------------------------------------------
from __future__ import division
import codecs
import re
#import sys
#import getopt
#import glob
from cxxtest.cxxtest_misc import abort
# Global variables
suites = []
suite = None
inBlock = 0
options=None
def scanInputFiles(files, _options):
'''Scan all input files for test suites'''
global options
options=_options
for file in files:
scanInputFile(file)
global suites
if len(suites) is 0 and not options.root:
abort( 'No tests defined' )
return [options,suites]
lineCont_re = re.compile('(.*)\\\s*$')
def scanInputFile(fileName):
'''Scan single input file for test suites'''
# mode 'rb' is problematic in python3 - byte arrays don't behave the same as
# strings.
# As far as the choice of the default encoding: utf-8 chews through
# everything that the previous ascii codec could, plus most of new code.
# TODO: figure out how to do this properly - like autodetect encoding from
# file header.
file = codecs.open(fileName, mode='r', encoding='utf-8')
prev = ""
lineNo = 0
contNo = 0
while 1:
line = file.readline()
if not line:
break
lineNo += 1
m = lineCont_re.match(line)
if m:
prev += m.group(1) + " "
contNo += 1
else:
scanInputLine( fileName, lineNo - contNo, prev + line )
contNo = 0
prev = ""
if contNo:
scanInputLine( fileName, lineNo - contNo, prev + line )
closeSuite()
file.close()
def scanInputLine( fileName, lineNo, line ):
'''Scan single input line for interesting stuff'''
scanLineForExceptionHandling( line )
scanLineForStandardLibrary( line )
scanLineForSuiteStart( fileName, lineNo, line )
global suite
if suite:
scanLineInsideSuite( suite, lineNo, line )
def scanLineInsideSuite( suite, lineNo, line ):
'''Analyze line which is part of a suite'''
global inBlock
if lineBelongsToSuite( suite, lineNo, line ):
scanLineForTest( suite, lineNo, line )
scanLineForCreate( suite, lineNo, line )
scanLineForDestroy( suite, lineNo, line )
def lineBelongsToSuite( suite, lineNo, line ):
'''Returns whether current line is part of the current suite.
This can be false when we are in a generated suite outside of CXXTEST_CODE() blocks
If the suite is generated, adds the line to the list of lines'''
if not suite['generated']:
return 1
global inBlock
if not inBlock:
inBlock = lineStartsBlock( line )
if inBlock:
inBlock = addLineToBlock( suite, lineNo, line )
return inBlock
std_re = re.compile( r"\b(std\s*::|CXXTEST_STD|using\s+namespace\s+std\b|^\s*\#\s*include\s+<[a-z0-9]+>)" )
def scanLineForStandardLibrary( line ):
'''Check if current line uses standard library'''
global options
if not options.haveStandardLibrary and std_re.search(line):
if not options.noStandardLibrary:
options.haveStandardLibrary = 1
exception_re = re.compile( r"\b(throw|try|catch|TSM?_ASSERT_THROWS[A-Z_]*)\b" )
def scanLineForExceptionHandling( line ):
'''Check if current line uses exception handling'''
global options
if not options.haveExceptionHandling and exception_re.search(line):
if not options.noExceptionHandling:
options.haveExceptionHandling = 1
classdef = '(?:::\s*)?(?:\w+\s*::\s*)*\w+'
baseclassdef = '(?:public|private|protected)\s+%s' % (classdef,)
general_suite = r"\bclass\s+(%s)\s*:(?:\s*%s\s*,)*\s*public\s+" \
% (classdef, baseclassdef,)
testsuite = '(?:(?:::)?\s*CxxTest\s*::\s*)?TestSuite'
suites_re = { re.compile( general_suite + testsuite ) : None }
generatedSuite_re = re.compile( r'\bCXXTEST_SUITE\s*\(\s*(\w*)\s*\)' )
def scanLineForSuiteStart( fileName, lineNo, line ):
'''Check if current line starts a new test suite'''
for i in list(suites_re.items()):
m = i[0].search( line )
if m:
suite = startSuite( m.group(1), fileName, lineNo, 0 )
if i[1] is not None:
for test in i[1]['tests']:
addTest(suite, test['name'], test['line'])
break
m = generatedSuite_re.search( line )
if m:
sys.stdout.write( "%s:%s: Warning: Inline test suites are deprecated.\n" % (fileName, lineNo) )
startSuite( m.group(1), fileName, lineNo, 1 )
def startSuite( name, file, line, generated ):
'''Start scanning a new suite'''
global suite
closeSuite()
object_name = name.replace(':',"_")
suite = { 'name' : name,
'file' : file,
'cfile' : cstr(file),
'line' : line,
'generated' : generated,
'object' : 'suite_%s' % object_name,
'dobject' : 'suiteDescription_%s' % object_name,
'tlist' : 'Tests_%s' % object_name,
'tests' : [],
'lines' : [] }
suites_re[re.compile( general_suite + name )] = suite
return suite
def lineStartsBlock( line ):
'''Check if current line starts a new CXXTEST_CODE() block'''
return re.search( r'\bCXXTEST_CODE\s*\(', line ) is not None
test_re = re.compile( r'^([^/]|/[^/])*\bvoid\s+([Tt]est\w+)\s*\(\s*(void)?\s*\)' )
def scanLineForTest( suite, lineNo, line ):
'''Check if current line starts a test'''
m = test_re.search( line )
if m:
addTest( suite, m.group(2), lineNo )
def addTest( suite, name, line ):
'''Add a test function to the current suite'''
test = { 'name' : name,
'suite' : suite,
'class' : 'TestDescription_%s_%s' % (suite['object'], name),
'object' : 'testDescription_%s_%s' % (suite['object'], name),
'line' : line,
}
suite['tests'].append( test )
def addLineToBlock( suite, lineNo, line ):
'''Append the line to the current CXXTEST_CODE() block'''
line = fixBlockLine( suite, lineNo, line )
line = re.sub( r'^.*\{\{', '', line )
e = re.search( r'\}\}', line )
if e:
line = line[:e.start()]
suite['lines'].append( line )
return e is None
def fixBlockLine( suite, lineNo, line):
'''Change all [E]TS_ macros used in a line to _[E]TS_ macros with the correct file/line'''
return re.sub( r'\b(E?TSM?_(ASSERT[A-Z_]*|FAIL))\s*\(',
r'_\1(%s,%s,' % (suite['cfile'], lineNo),
line, 0 )
create_re = re.compile( r'\bstatic\s+\w+\s*\*\s*createSuite\s*\(\s*(void)?\s*\)' )
def scanLineForCreate( suite, lineNo, line ):
'''Check if current line defines a createSuite() function'''
if create_re.search( line ):
addSuiteCreateDestroy( suite, 'create', lineNo )
destroy_re = re.compile( r'\bstatic\s+void\s+destroySuite\s*\(\s*\w+\s*\*\s*\w*\s*\)' )
def scanLineForDestroy( suite, lineNo, line ):
'''Check if current line defines a destroySuite() function'''
if destroy_re.search( line ):
addSuiteCreateDestroy( suite, 'destroy', lineNo )
def cstr( s ):
'''Convert a string to its C representation'''
return '"' + s.replace( '\\', '\\\\' ) + '"'
def addSuiteCreateDestroy( suite, which, line ):
'''Add createSuite()/destroySuite() to current suite'''
if which in suite:
abort( '%s:%s: %sSuite() already declared' % ( suite['file'], str(line), which ) )
suite[which] = line
def closeSuite():
'''Close current suite and add it to the list if valid'''
global suite
if suite is not None:
if len(suite['tests']) is not 0:
verifySuite(suite)
rememberSuite(suite)
suite = None
def verifySuite(suite):
'''Verify current suite is legal'''
if 'create' in suite and 'destroy' not in suite:
abort( '%s:%s: Suite %s has createSuite() but no destroySuite()' %
(suite['file'], suite['create'], suite['name']) )
elif 'destroy' in suite and 'create' not in suite:
abort( '%s:%s: Suite %s has destroySuite() but no createSuite()' %
(suite['file'], suite['destroy'], suite['name']) )
def rememberSuite(suite):
'''Add current suite to list'''
global suites
suites.append( suite )
| [
[
1,
0,
0.0413,
0.0041,
0,
0.66,
0,
777,
0,
1,
0,
0,
777,
0,
0
],
[
1,
0,
0.0496,
0.0041,
0,
0.66,
0.025,
220,
0,
1,
0,
0,
220,
0,
0
],
[
1,
0,
0.0537,
0.0041,
0,
0... | [
"from __future__ import division",
"import codecs",
"import re",
"from cxxtest.cxxtest_misc import abort",
"suites = []",
"suite = None",
"inBlock = 0",
"options=None",
"def scanInputFiles(files, _options):\n '''Scan all input files for test suites'''\n global options\n options=_options\n ... |
#-------------------------------------------------------------------------
# CxxTest: A lightweight C++ unit testing library.
# Copyright (c) 2008 Sandia Corporation.
# This software is distributed under the LGPL License v2.1
# For more information, see the COPYING file in the top CxxTest directory.
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains certain rights in this software.
#-------------------------------------------------------------------------
""" Release Information for cxxtest """
__version__ = '4.0.2'
__date__ = "2012-01-02"
| [
[
8,
0,
0.7692,
0.0769,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.9231,
0.0769,
0,
0.66,
0.5,
162,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
1,
0.0769,
0,
0.66,
1,... | [
"\"\"\" Release Information for cxxtest \"\"\"",
"__version__ = '4.0.2'",
"__date__ = \"2012-01-02\""
] |
#-------------------------------------------------------------------------
# CxxTest: A lightweight C++ unit testing library.
# Copyright (c) 2008 Sandia Corporation.
# This software is distributed under the LGPL License v2.1
# For more information, see the COPYING file in the top CxxTest directory.
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains certain rights in this software.
#-------------------------------------------------------------------------
# vim: fileencoding=utf-8
#
# This is a PLY parser for the entire ANSI C++ grammar. This grammar was
# adapted from the FOG grammar developed by E. D. Willink. See
#
# http://www.computing.surrey.ac.uk/research/dsrg/fog/
#
# for further details.
#
# The goal of this grammar is to extract information about class, function and
# class method declarations, along with their associated scope. Thus, this
# grammar can be used to analyze classes in an inheritance heirarchy, and then
# enumerate the methods in a derived class.
#
# This grammar parses blocks of <>, (), [] and {} in a generic manner. Thus,
# There are several capabilities that this grammar does not support:
#
# 1. Ambiguous template specification. This grammar cannot parse template
# specifications that do not have paired <>'s in their declaration. In
# particular, ambiguous declarations like
#
# foo<A, c<3 >();
#
# cannot be correctly parsed.
#
# 2. Template class specialization. Although the goal of this grammar is to
# extract class information, specialization of templated classes is
# not supported. When a template class definition is parsed, it's
# declaration is archived without information about the template
# parameters. Class specializations will be stored separately, and
# thus they can be processed after the fact. However, this grammar
# does not attempt to correctly process properties of class inheritence
# when template class specialization is employed.
#
#
# TODO: document usage of this file
#
from __future__ import division
import os
import ply.lex as lex
import ply.yacc as yacc
import re
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
lexer = None
scope_lineno = 0
identifier_lineno = {}
_parse_info=None
_parsedata=None
noExceptionLogic = True
def ply_init(data):
global _parsedata
_parsedata=data
class Scope(object):
def __init__(self,name,abs_name,scope_t,base_classes,lineno):
self.function=[]
self.name=name
self.scope_t=scope_t
self.sub_scopes=[]
self.base_classes=base_classes
self.abs_name=abs_name
self.lineno=lineno
def insert(self,scope):
self.sub_scopes.append(scope)
class CppInfo(object):
def __init__(self, filter=None):
self.verbose=0
if filter is None:
self.filter=re.compile("[Tt][Ee][Ss][Tt]|createSuite|destroySuite")
else:
self.filter=filter
self.scopes=[""]
self.index=OrderedDict()
self.index[""]=Scope("","::","namespace",[],1)
self.function=[]
def push_scope(self,ns,scope_t,base_classes=[]):
name = self.scopes[-1]+"::"+ns
if self.verbose>=2:
print "-- Starting "+scope_t+" "+name
self.scopes.append(name)
self.index[name] = Scope(ns,name,scope_t,base_classes,scope_lineno-1)
def pop_scope(self):
scope = self.scopes.pop()
if self.verbose>=2:
print "-- Stopping "+scope
return scope
def add_function(self, fn):
fn = str(fn)
if self.filter.search(fn):
self.index[self.scopes[-1]].function.append((fn, identifier_lineno.get(fn,lexer.lineno-1)))
tmp = self.scopes[-1]+"::"+fn
if self.verbose==2:
print "-- Function declaration "+fn+" "+tmp
elif self.verbose==1:
print "-- Function declaration "+tmp
def get_functions(self,name,quiet=False):
if name == "::":
name = ""
scope = self.index[name]
fns=scope.function
for key in scope.base_classes:
cname = self.find_class(key,scope)
if cname is None:
if not quiet:
print "Defined classes: ",list(self.index.keys())
print "WARNING: Unknown class "+key
else:
fns += self.get_functions(cname,quiet)
return fns
def find_class(self,name,scope):
if ':' in name:
if name in self.index:
return name
else:
return None
tmp = scope.abs_name.split(':')
name1 = ":".join(tmp[:-1] + [name])
if name1 in self.index:
return name1
name2 = "::"+name
if name2 in self.index:
return name2
return None
def __repr__(self):
return str(self)
def is_baseclass(self,cls,base):
'''Returns true if base is a base-class of cls'''
if cls in self.index:
bases = self.index[cls]
elif "::"+cls in self.index:
bases = self.index["::"+cls]
else:
return False
#raise IOError, "Unknown class "+cls
if base in bases.base_classes:
return True
for name in bases.base_classes:
if self.is_baseclass(name,base):
return True
return False
def __str__(self):
ans=""
keys = list(self.index.keys())
keys.sort()
for key in keys:
scope = self.index[key]
ans += scope.scope_t+" "+scope.abs_name+"\n"
if scope.scope_t == "class":
ans += " Base Classes: "+str(scope.base_classes)+"\n"
for fn in self.get_functions(scope.abs_name):
ans += " "+fn+"\n"
else:
for fn in scope.function:
ans += " "+fn+"\n"
return ans
def flatten(x):
"""Flatten nested list"""
try:
strtypes = basestring
except: # for python3 etc
strtypes = (str, bytes)
result = []
for el in x:
if hasattr(el, "__iter__") and not isinstance(el, strtypes):
result.extend(flatten(el))
else:
result.append(el)
return result
#
# The lexer (and/or a preprocessor) is expected to identify the following
#
# Punctuation:
#
#
literals = "+-*/%^&|~!<>=:()?.\'\"\\@$;,"
#
reserved = {
'private' : 'PRIVATE',
'protected' : 'PROTECTED',
'public' : 'PUBLIC',
'bool' : 'BOOL',
'char' : 'CHAR',
'double' : 'DOUBLE',
'float' : 'FLOAT',
'int' : 'INT',
'long' : 'LONG',
'short' : 'SHORT',
'signed' : 'SIGNED',
'unsigned' : 'UNSIGNED',
'void' : 'VOID',
'wchar_t' : 'WCHAR_T',
'class' : 'CLASS',
'enum' : 'ENUM',
'namespace' : 'NAMESPACE',
'struct' : 'STRUCT',
'typename' : 'TYPENAME',
'union' : 'UNION',
'const' : 'CONST',
'volatile' : 'VOLATILE',
'auto' : 'AUTO',
'explicit' : 'EXPLICIT',
'export' : 'EXPORT',
'extern' : 'EXTERN',
'__extension__' : 'EXTENSION',
'friend' : 'FRIEND',
'inline' : 'INLINE',
'mutable' : 'MUTABLE',
'register' : 'REGISTER',
'static' : 'STATIC',
'template' : 'TEMPLATE',
'typedef' : 'TYPEDEF',
'using' : 'USING',
'virtual' : 'VIRTUAL',
'asm' : 'ASM',
'break' : 'BREAK',
'case' : 'CASE',
'catch' : 'CATCH',
'const_cast' : 'CONST_CAST',
'continue' : 'CONTINUE',
'default' : 'DEFAULT',
'delete' : 'DELETE',
'do' : 'DO',
'dynamic_cast' : 'DYNAMIC_CAST',
'else' : 'ELSE',
'false' : 'FALSE',
'for' : 'FOR',
'goto' : 'GOTO',
'if' : 'IF',
'new' : 'NEW',
'operator' : 'OPERATOR',
'reinterpret_cast' : 'REINTERPRET_CAST',
'return' : 'RETURN',
'sizeof' : 'SIZEOF',
'static_cast' : 'STATIC_CAST',
'switch' : 'SWITCH',
'this' : 'THIS',
'throw' : 'THROW',
'true' : 'TRUE',
'try' : 'TRY',
'typeid' : 'TYPEID',
'while' : 'WHILE',
'"C"' : 'CLiteral',
'"C++"' : 'CppLiteral',
'__attribute__' : 'ATTRIBUTE',
'__cdecl__' : 'CDECL',
'__typeof' : 'uTYPEOF',
'typeof' : 'TYPEOF',
'CXXTEST_STD' : 'CXXTEST_STD'
}
tokens = [
"CharacterLiteral",
"FloatingLiteral",
"Identifier",
"IntegerLiteral",
"StringLiteral",
"RBRACE",
"LBRACE",
"RBRACKET",
"LBRACKET",
"ARROW",
"ARROW_STAR",
"DEC",
"EQ",
"GE",
"INC",
"LE",
"LOG_AND",
"LOG_OR",
"NE",
"SHL",
"SHR",
"ASS_ADD",
"ASS_AND",
"ASS_DIV",
"ASS_MOD",
"ASS_MUL",
"ASS_OR",
"ASS_SHL",
"ASS_SHR",
"ASS_SUB",
"ASS_XOR",
"DOT_STAR",
"ELLIPSIS",
"SCOPE",
] + list(reserved.values())
t_ignore = " \t\r"
t_LBRACE = r"(\{)|(<%)"
t_RBRACE = r"(\})|(%>)"
t_LBRACKET = r"(\[)|(<:)"
t_RBRACKET = r"(\])|(:>)"
t_ARROW = r"->"
t_ARROW_STAR = r"->\*"
t_DEC = r"--"
t_EQ = r"=="
t_GE = r">="
t_INC = r"\+\+"
t_LE = r"<="
t_LOG_AND = r"&&"
t_LOG_OR = r"\|\|"
t_NE = r"!="
t_SHL = r"<<"
t_SHR = r">>"
t_ASS_ADD = r"\+="
t_ASS_AND = r"&="
t_ASS_DIV = r"/="
t_ASS_MOD = r"%="
t_ASS_MUL = r"\*="
t_ASS_OR = r"\|="
t_ASS_SHL = r"<<="
t_ASS_SHR = r">>="
t_ASS_SUB = r"-="
t_ASS_XOR = r"^="
t_DOT_STAR = r"\.\*"
t_ELLIPSIS = r"\.\.\."
t_SCOPE = r"::"
# Discard comments
def t_COMMENT(t):
r'(/\*(.|\n)*?\*/)|(//.*?\n)|(\#.*?\n)'
t.lexer.lineno += t.value.count("\n")
t_IntegerLiteral = r'(0x[0-9A-F]+)|([0-9]+(L){0,1})'
t_FloatingLiteral = r"[0-9]+[eE\.\+-]+[eE\.\+\-0-9]+"
t_CharacterLiteral = r'\'([^\'\\]|\\.)*\''
#t_StringLiteral = r'"([^"\\]|\\.)*"'
def t_StringLiteral(t):
r'"([^"\\]|\\.)*"'
t.type = reserved.get(t.value,'StringLiteral')
return t
def t_Identifier(t):
r"[a-zA-Z_][a-zA-Z_0-9\.]*"
t.type = reserved.get(t.value,'Identifier')
return t
def t_error(t):
print "Illegal character '%s'" % t.value[0]
#raise IOError, "Parse error"
#t.lexer.skip()
def t_newline(t):
r'[\n]+'
t.lexer.lineno += len(t.value)
precedence = (
( 'right', 'SHIFT_THERE', 'REDUCE_HERE_MOSTLY', 'SCOPE'),
( 'nonassoc', 'ELSE', 'INC', 'DEC', '+', '-', '*', '&', 'LBRACKET', 'LBRACE', '<', ':', ')')
)
start = 'translation_unit'
#
# The %prec resolves the 14.2-3 ambiguity:
# Identifier '<' is forced to go through the is-it-a-template-name test
# All names absorb TEMPLATE with the name, so that no template_test is
# performed for them. This requires all potential declarations within an
# expression to perpetuate this policy and thereby guarantee the ultimate
# coverage of explicit_instantiation.
#
# The %prec also resolves a conflict in identifier : which is forced to be a
# shift of a label for a labeled-statement rather than a reduction for the
# name of a bit-field or generalised constructor. This is pretty dubious
# syntactically but correct for all semantic possibilities. The shift is
# only activated when the ambiguity exists at the start of a statement.
# In this context a bit-field declaration or constructor definition are not
# allowed.
#
def p_identifier(p):
'''identifier : Identifier
| CXXTEST_STD '(' Identifier ')'
'''
if p[1][0] in ('t','T','c','d'):
identifier_lineno[p[1]] = p.lineno(1)
p[0] = p[1]
def p_id(p):
'''id : identifier %prec SHIFT_THERE
| template_decl
| TEMPLATE id
'''
p[0] = get_rest(p)
def p_global_scope(p):
'''global_scope : SCOPE
'''
p[0] = get_rest(p)
def p_id_scope(p):
'''id_scope : id SCOPE'''
p[0] = get_rest(p)
def p_id_scope_seq(p):
'''id_scope_seq : id_scope
| id_scope id_scope_seq
'''
p[0] = get_rest(p)
#
# A :: B :: C; is ambiguous How much is type and how much name ?
# The %prec maximises the (type) length which is the 7.1-2 semantic constraint.
#
def p_nested_id(p):
'''nested_id : id %prec SHIFT_THERE
| id_scope nested_id
'''
p[0] = get_rest(p)
def p_scoped_id(p):
'''scoped_id : nested_id
| global_scope nested_id
| id_scope_seq
| global_scope id_scope_seq
'''
global scope_lineno
scope_lineno = lexer.lineno
data = flatten(get_rest(p))
if data[0] != None:
p[0] = "".join(data)
#
# destructor_id has to be held back to avoid a conflict with a one's
# complement as per 5.3.1-9, It gets put back only when scoped or in a
# declarator_id, which is only used as an explicit member name.
# Declarations of an unscoped destructor are always parsed as a one's
# complement.
#
def p_destructor_id(p):
'''destructor_id : '~' id
| TEMPLATE destructor_id
'''
p[0]=get_rest(p)
#def p_template_id(p):
# '''template_id : empty
# | TEMPLATE
# '''
# pass
def p_template_decl(p):
'''template_decl : identifier '<' nonlgt_seq_opt '>'
'''
#
# WEH: should we include the lt/gt symbols to indicate that this is a
# template class? How is that going to be used later???
#
#p[0] = [p[1] ,"<",">"]
p[0] = p[1]
def p_special_function_id(p):
'''special_function_id : conversion_function_id
| operator_function_id
| TEMPLATE special_function_id
'''
p[0]=get_rest(p)
def p_nested_special_function_id(p):
'''nested_special_function_id : special_function_id
| id_scope destructor_id
| id_scope nested_special_function_id
'''
p[0]=get_rest(p)
def p_scoped_special_function_id(p):
'''scoped_special_function_id : nested_special_function_id
| global_scope nested_special_function_id
'''
p[0]=get_rest(p)
# declarator-id is all names in all scopes, except reserved words
def p_declarator_id(p):
'''declarator_id : scoped_id
| scoped_special_function_id
| destructor_id
'''
p[0]=p[1]
#
# The standard defines pseudo-destructors in terms of type-name, which is
# class/enum/typedef, of which class-name is covered by a normal destructor.
# pseudo-destructors are supposed to support ~int() in templates, so the
# grammar here covers built-in names. Other names are covered by the lack
# of identifier/type discrimination.
#
def p_built_in_type_id(p):
'''built_in_type_id : built_in_type_specifier
| built_in_type_id built_in_type_specifier
'''
pass
def p_pseudo_destructor_id(p):
'''pseudo_destructor_id : built_in_type_id SCOPE '~' built_in_type_id
| '~' built_in_type_id
| TEMPLATE pseudo_destructor_id
'''
pass
def p_nested_pseudo_destructor_id(p):
'''nested_pseudo_destructor_id : pseudo_destructor_id
| id_scope nested_pseudo_destructor_id
'''
pass
def p_scoped_pseudo_destructor_id(p):
'''scoped_pseudo_destructor_id : nested_pseudo_destructor_id
| global_scope scoped_pseudo_destructor_id
'''
pass
#-------------------------------------------------------------------------------
# A.2 Lexical conventions
#-------------------------------------------------------------------------------
#
def p_literal(p):
'''literal : IntegerLiteral
| CharacterLiteral
| FloatingLiteral
| StringLiteral
| TRUE
| FALSE
'''
pass
#-------------------------------------------------------------------------------
# A.3 Basic concepts
#-------------------------------------------------------------------------------
def p_translation_unit(p):
'''translation_unit : declaration_seq_opt
'''
pass
#-------------------------------------------------------------------------------
# A.4 Expressions
#-------------------------------------------------------------------------------
#
# primary_expression covers an arbitrary sequence of all names with the
# exception of an unscoped destructor, which is parsed as its unary expression
# which is the correct disambiguation (when ambiguous). This eliminates the
# traditional A(B) meaning A B ambiguity, since we never have to tack an A
# onto the front of something that might start with (. The name length got
# maximised ab initio. The downside is that semantic interpretation must split
# the names up again.
#
# Unification of the declaration and expression syntax means that unary and
# binary pointer declarator operators:
# int * * name
# are parsed as binary and unary arithmetic operators (int) * (*name). Since
# type information is not used
# ambiguities resulting from a cast
# (cast)*(value)
# are resolved to favour the binary rather than the cast unary to ease AST
# clean-up. The cast-call ambiguity must be resolved to the cast to ensure
# that (a)(b)c can be parsed.
#
# The problem of the functional cast ambiguity
# name(arg)
# as call or declaration is avoided by maximising the name within the parsing
# kernel. So primary_id_expression picks up
# extern long int const var = 5;
# as an assignment to the syntax parsed as "extern long int const var". The
# presence of two names is parsed so that "extern long into const" is
# distinguished from "var" considerably simplifying subsequent
# semantic resolution.
#
# The generalised name is a concatenation of potential type-names (scoped
# identifiers or built-in sequences) plus optionally one of the special names
# such as an operator-function-id, conversion-function-id or destructor as the
# final name.
#
def get_rest(p):
return [p[i] for i in range(1, len(p))]
def p_primary_expression(p):
'''primary_expression : literal
| THIS
| suffix_decl_specified_ids
| abstract_expression %prec REDUCE_HERE_MOSTLY
'''
p[0] = get_rest(p)
#
# Abstract-expression covers the () and [] of abstract-declarators.
#
def p_abstract_expression(p):
'''abstract_expression : parenthesis_clause
| LBRACKET bexpression_opt RBRACKET
| TEMPLATE abstract_expression
'''
pass
def p_postfix_expression(p):
'''postfix_expression : primary_expression
| postfix_expression parenthesis_clause
| postfix_expression LBRACKET bexpression_opt RBRACKET
| postfix_expression LBRACKET bexpression_opt RBRACKET attributes
| postfix_expression '.' declarator_id
| postfix_expression '.' scoped_pseudo_destructor_id
| postfix_expression ARROW declarator_id
| postfix_expression ARROW scoped_pseudo_destructor_id
| postfix_expression INC
| postfix_expression DEC
| DYNAMIC_CAST '<' nonlgt_seq_opt '>' '(' expression ')'
| STATIC_CAST '<' nonlgt_seq_opt '>' '(' expression ')'
| REINTERPRET_CAST '<' nonlgt_seq_opt '>' '(' expression ')'
| CONST_CAST '<' nonlgt_seq_opt '>' '(' expression ')'
| TYPEID parameters_clause
'''
#print "HERE",str(p[1])
p[0] = get_rest(p)
def p_bexpression_opt(p):
'''bexpression_opt : empty
| bexpression
'''
pass
def p_bexpression(p):
'''bexpression : nonbracket_seq
| nonbracket_seq bexpression_seq bexpression_clause nonbracket_seq_opt
| bexpression_seq bexpression_clause nonbracket_seq_opt
'''
pass
def p_bexpression_seq(p):
'''bexpression_seq : empty
| bexpression_seq bexpression_clause nonbracket_seq_opt
'''
pass
def p_bexpression_clause(p):
'''bexpression_clause : LBRACKET bexpression_opt RBRACKET
'''
pass
def p_expression_list_opt(p):
'''expression_list_opt : empty
| expression_list
'''
pass
def p_expression_list(p):
'''expression_list : assignment_expression
| expression_list ',' assignment_expression
'''
pass
def p_unary_expression(p):
'''unary_expression : postfix_expression
| INC cast_expression
| DEC cast_expression
| ptr_operator cast_expression
| suffix_decl_specified_scope star_ptr_operator cast_expression
| '+' cast_expression
| '-' cast_expression
| '!' cast_expression
| '~' cast_expression
| SIZEOF unary_expression
| new_expression
| global_scope new_expression
| delete_expression
| global_scope delete_expression
'''
p[0] = get_rest(p)
def p_delete_expression(p):
'''delete_expression : DELETE cast_expression
'''
pass
def p_new_expression(p):
'''new_expression : NEW new_type_id new_initializer_opt
| NEW parameters_clause new_type_id new_initializer_opt
| NEW parameters_clause
| NEW parameters_clause parameters_clause new_initializer_opt
'''
pass
def p_new_type_id(p):
'''new_type_id : type_specifier ptr_operator_seq_opt
| type_specifier new_declarator
| type_specifier new_type_id
'''
pass
def p_new_declarator(p):
'''new_declarator : ptr_operator new_declarator
| direct_new_declarator
'''
pass
def p_direct_new_declarator(p):
'''direct_new_declarator : LBRACKET bexpression_opt RBRACKET
| direct_new_declarator LBRACKET bexpression RBRACKET
'''
pass
def p_new_initializer_opt(p):
'''new_initializer_opt : empty
| '(' expression_list_opt ')'
'''
pass
#
# cast-expression is generalised to support a [] as well as a () prefix. This covers the omission of
# DELETE[] which when followed by a parenthesised expression was ambiguous. It also covers the gcc
# indexed array initialisation for free.
#
def p_cast_expression(p):
'''cast_expression : unary_expression
| abstract_expression cast_expression
'''
p[0] = get_rest(p)
def p_pm_expression(p):
'''pm_expression : cast_expression
| pm_expression DOT_STAR cast_expression
| pm_expression ARROW_STAR cast_expression
'''
p[0] = get_rest(p)
def p_multiplicative_expression(p):
'''multiplicative_expression : pm_expression
| multiplicative_expression star_ptr_operator pm_expression
| multiplicative_expression '/' pm_expression
| multiplicative_expression '%' pm_expression
'''
p[0] = get_rest(p)
def p_additive_expression(p):
'''additive_expression : multiplicative_expression
| additive_expression '+' multiplicative_expression
| additive_expression '-' multiplicative_expression
'''
p[0] = get_rest(p)
def p_shift_expression(p):
'''shift_expression : additive_expression
| shift_expression SHL additive_expression
| shift_expression SHR additive_expression
'''
p[0] = get_rest(p)
# | relational_expression '<' shift_expression
# | relational_expression '>' shift_expression
# | relational_expression LE shift_expression
# | relational_expression GE shift_expression
def p_relational_expression(p):
'''relational_expression : shift_expression
'''
p[0] = get_rest(p)
def p_equality_expression(p):
'''equality_expression : relational_expression
| equality_expression EQ relational_expression
| equality_expression NE relational_expression
'''
p[0] = get_rest(p)
def p_and_expression(p):
'''and_expression : equality_expression
| and_expression '&' equality_expression
'''
p[0] = get_rest(p)
def p_exclusive_or_expression(p):
'''exclusive_or_expression : and_expression
| exclusive_or_expression '^' and_expression
'''
p[0] = get_rest(p)
def p_inclusive_or_expression(p):
'''inclusive_or_expression : exclusive_or_expression
| inclusive_or_expression '|' exclusive_or_expression
'''
p[0] = get_rest(p)
def p_logical_and_expression(p):
'''logical_and_expression : inclusive_or_expression
| logical_and_expression LOG_AND inclusive_or_expression
'''
p[0] = get_rest(p)
def p_logical_or_expression(p):
'''logical_or_expression : logical_and_expression
| logical_or_expression LOG_OR logical_and_expression
'''
p[0] = get_rest(p)
def p_conditional_expression(p):
'''conditional_expression : logical_or_expression
| logical_or_expression '?' expression ':' assignment_expression
'''
p[0] = get_rest(p)
#
# assignment-expression is generalised to cover the simple assignment of a braced initializer in order to
# contribute to the coverage of parameter-declaration and init-declaration.
#
# | logical_or_expression assignment_operator assignment_expression
def p_assignment_expression(p):
'''assignment_expression : conditional_expression
| logical_or_expression assignment_operator nonsemicolon_seq
| logical_or_expression '=' braced_initializer
| throw_expression
'''
p[0]=get_rest(p)
def p_assignment_operator(p):
'''assignment_operator : '='
| ASS_ADD
| ASS_AND
| ASS_DIV
| ASS_MOD
| ASS_MUL
| ASS_OR
| ASS_SHL
| ASS_SHR
| ASS_SUB
| ASS_XOR
'''
pass
#
# expression is widely used and usually single-element, so the reductions are arranged so that a
# single-element expression is returned as is. Multi-element expressions are parsed as a list that
# may then behave polymorphically as an element or be compacted to an element.
#
def p_expression(p):
'''expression : assignment_expression
| expression_list ',' assignment_expression
'''
p[0] = get_rest(p)
def p_constant_expression(p):
'''constant_expression : conditional_expression
'''
pass
#---------------------------------------------------------------------------------------------------
# A.5 Statements
#---------------------------------------------------------------------------------------------------
# Parsing statements is easy once simple_declaration has been generalised to cover expression_statement.
#
#
# The use of extern here is a hack. The 'extern "C" {}' block gets parsed
# as a function, so when nested 'extern "C"' declarations exist, they don't
# work because the block is viewed as a list of statements... :(
#
def p_statement(p):
'''statement : compound_statement
| declaration_statement
| try_block
| labeled_statement
| selection_statement
| iteration_statement
| jump_statement
'''
pass
def p_compound_statement(p):
'''compound_statement : LBRACE statement_seq_opt RBRACE
'''
pass
def p_statement_seq_opt(p):
'''statement_seq_opt : empty
| statement_seq_opt statement
'''
pass
#
# The dangling else conflict is resolved to the innermost if.
#
def p_selection_statement(p):
'''selection_statement : IF '(' condition ')' statement %prec SHIFT_THERE
| IF '(' condition ')' statement ELSE statement
| SWITCH '(' condition ')' statement
'''
pass
def p_condition_opt(p):
'''condition_opt : empty
| condition
'''
pass
def p_condition(p):
'''condition : nonparen_seq
| nonparen_seq condition_seq parameters_clause nonparen_seq_opt
| condition_seq parameters_clause nonparen_seq_opt
'''
pass
def p_condition_seq(p):
'''condition_seq : empty
| condition_seq parameters_clause nonparen_seq_opt
'''
pass
def p_labeled_statement(p):
'''labeled_statement : identifier ':' statement
| CASE constant_expression ':' statement
| DEFAULT ':' statement
'''
pass
def p_try_block(p):
'''try_block : TRY compound_statement handler_seq
'''
global noExceptionLogic
noExceptionLogic=False
def p_jump_statement(p):
'''jump_statement : BREAK ';'
| CONTINUE ';'
| RETURN nonsemicolon_seq ';'
| GOTO identifier ';'
'''
pass
def p_iteration_statement(p):
'''iteration_statement : WHILE '(' condition ')' statement
| DO statement WHILE '(' expression ')' ';'
| FOR '(' nonparen_seq_opt ')' statement
'''
pass
def p_declaration_statement(p):
'''declaration_statement : block_declaration
'''
pass
#---------------------------------------------------------------------------------------------------
# A.6 Declarations
#---------------------------------------------------------------------------------------------------
def p_compound_declaration(p):
'''compound_declaration : LBRACE declaration_seq_opt RBRACE
'''
pass
def p_declaration_seq_opt(p):
'''declaration_seq_opt : empty
| declaration_seq_opt declaration
'''
pass
def p_declaration(p):
'''declaration : block_declaration
| function_definition
| template_declaration
| explicit_specialization
| specialised_declaration
'''
pass
def p_specialised_declaration(p):
'''specialised_declaration : linkage_specification
| namespace_definition
| TEMPLATE specialised_declaration
'''
pass
def p_block_declaration(p):
'''block_declaration : simple_declaration
| specialised_block_declaration
'''
pass
def p_specialised_block_declaration(p):
'''specialised_block_declaration : asm_definition
| namespace_alias_definition
| using_declaration
| using_directive
| TEMPLATE specialised_block_declaration
'''
pass
def p_simple_declaration(p):
'''simple_declaration : ';'
| init_declaration ';'
| init_declarations ';'
| decl_specifier_prefix simple_declaration
'''
global _parse_info
if len(p) == 3:
if p[2] == ";":
decl = p[1]
else:
decl = p[2]
if decl is not None:
fp = flatten(decl)
if len(fp) >= 2 and fp[0] is not None and fp[0]!="operator" and fp[1] == '(':
p[0] = fp[0]
_parse_info.add_function(fp[0])
#
# A decl-specifier following a ptr_operator provokes a shift-reduce conflict for * const name which is resolved in favour of the pointer, and implemented by providing versions of decl-specifier guaranteed not to start with a cv_qualifier. decl-specifiers are implemented type-centrically. That is the semantic constraint that there must be a type is exploited to impose structure, but actually eliminate very little syntax. built-in types are multi-name and so need a different policy.
#
# non-type decl-specifiers are bound to the left-most type in a decl-specifier-seq, by parsing from the right and attaching suffixes to the right-hand type. Finally residual prefixes attach to the left.
#
def p_suffix_built_in_decl_specifier_raw(p):
'''suffix_built_in_decl_specifier_raw : built_in_type_specifier
| suffix_built_in_decl_specifier_raw built_in_type_specifier
| suffix_built_in_decl_specifier_raw decl_specifier_suffix
'''
pass
def p_suffix_built_in_decl_specifier(p):
'''suffix_built_in_decl_specifier : suffix_built_in_decl_specifier_raw
| TEMPLATE suffix_built_in_decl_specifier
'''
pass
# | id_scope_seq
# | SCOPE id_scope_seq
def p_suffix_named_decl_specifier(p):
'''suffix_named_decl_specifier : scoped_id
| elaborate_type_specifier
| suffix_named_decl_specifier decl_specifier_suffix
'''
p[0]=get_rest(p)
def p_suffix_named_decl_specifier_bi(p):
'''suffix_named_decl_specifier_bi : suffix_named_decl_specifier
| suffix_named_decl_specifier suffix_built_in_decl_specifier_raw
'''
p[0] = get_rest(p)
#print "HERE",get_rest(p)
def p_suffix_named_decl_specifiers(p):
'''suffix_named_decl_specifiers : suffix_named_decl_specifier_bi
| suffix_named_decl_specifiers suffix_named_decl_specifier_bi
'''
p[0] = get_rest(p)
def p_suffix_named_decl_specifiers_sf(p):
'''suffix_named_decl_specifiers_sf : scoped_special_function_id
| suffix_named_decl_specifiers
| suffix_named_decl_specifiers scoped_special_function_id
'''
#print "HERE",get_rest(p)
p[0] = get_rest(p)
def p_suffix_decl_specified_ids(p):
'''suffix_decl_specified_ids : suffix_built_in_decl_specifier
| suffix_built_in_decl_specifier suffix_named_decl_specifiers_sf
| suffix_named_decl_specifiers_sf
'''
if len(p) == 3:
p[0] = p[2]
else:
p[0] = p[1]
def p_suffix_decl_specified_scope(p):
'''suffix_decl_specified_scope : suffix_named_decl_specifiers SCOPE
| suffix_built_in_decl_specifier suffix_named_decl_specifiers SCOPE
| suffix_built_in_decl_specifier SCOPE
'''
p[0] = get_rest(p)
def p_decl_specifier_affix(p):
'''decl_specifier_affix : storage_class_specifier
| function_specifier
| FRIEND
| TYPEDEF
| cv_qualifier
'''
pass
def p_decl_specifier_suffix(p):
'''decl_specifier_suffix : decl_specifier_affix
'''
pass
def p_decl_specifier_prefix(p):
'''decl_specifier_prefix : decl_specifier_affix
| TEMPLATE decl_specifier_prefix
'''
pass
def p_storage_class_specifier(p):
'''storage_class_specifier : REGISTER
| STATIC
| MUTABLE
| EXTERN %prec SHIFT_THERE
| EXTENSION
| AUTO
'''
pass
def p_function_specifier(p):
'''function_specifier : EXPLICIT
| INLINE
| VIRTUAL
'''
pass
def p_type_specifier(p):
'''type_specifier : simple_type_specifier
| elaborate_type_specifier
| cv_qualifier
'''
pass
def p_elaborate_type_specifier(p):
'''elaborate_type_specifier : class_specifier
| enum_specifier
| elaborated_type_specifier
| TEMPLATE elaborate_type_specifier
'''
pass
def p_simple_type_specifier(p):
'''simple_type_specifier : scoped_id
| scoped_id attributes
| built_in_type_specifier
'''
p[0] = p[1]
def p_built_in_type_specifier(p):
'''built_in_type_specifier : Xbuilt_in_type_specifier
| Xbuilt_in_type_specifier attributes
'''
pass
def p_attributes(p):
'''attributes : attribute
| attributes attribute
'''
pass
def p_attribute(p):
'''attribute : ATTRIBUTE '(' parameters_clause ')'
'''
def p_Xbuilt_in_type_specifier(p):
'''Xbuilt_in_type_specifier : CHAR
| WCHAR_T
| BOOL
| SHORT
| INT
| LONG
| SIGNED
| UNSIGNED
| FLOAT
| DOUBLE
| VOID
| uTYPEOF parameters_clause
| TYPEOF parameters_clause
'''
pass
#
# The over-general use of declaration_expression to cover decl-specifier-seq_opt declarator in a function-definition means that
# class X { };
# could be a function-definition or a class-specifier.
# enum X { };
# could be a function-definition or an enum-specifier.
# The function-definition is not syntactically valid so resolving the false conflict in favour of the
# elaborated_type_specifier is correct.
#
def p_elaborated_type_specifier(p):
'''elaborated_type_specifier : class_key scoped_id %prec SHIFT_THERE
| elaborated_enum_specifier
| TYPENAME scoped_id
'''
pass
def p_elaborated_enum_specifier(p):
'''elaborated_enum_specifier : ENUM scoped_id %prec SHIFT_THERE
'''
pass
def p_enum_specifier(p):
'''enum_specifier : ENUM scoped_id enumerator_clause
| ENUM enumerator_clause
'''
pass
def p_enumerator_clause(p):
'''enumerator_clause : LBRACE enumerator_list_ecarb
| LBRACE enumerator_list enumerator_list_ecarb
| LBRACE enumerator_list ',' enumerator_definition_ecarb
'''
pass
def p_enumerator_list_ecarb(p):
'''enumerator_list_ecarb : RBRACE
'''
pass
def p_enumerator_definition_ecarb(p):
'''enumerator_definition_ecarb : RBRACE
'''
pass
def p_enumerator_definition_filler(p):
'''enumerator_definition_filler : empty
'''
pass
def p_enumerator_list_head(p):
'''enumerator_list_head : enumerator_definition_filler
| enumerator_list ',' enumerator_definition_filler
'''
pass
def p_enumerator_list(p):
'''enumerator_list : enumerator_list_head enumerator_definition
'''
pass
def p_enumerator_definition(p):
'''enumerator_definition : enumerator
| enumerator '=' constant_expression
'''
pass
def p_enumerator(p):
'''enumerator : identifier
'''
pass
def p_namespace_definition(p):
'''namespace_definition : NAMESPACE scoped_id push_scope compound_declaration
| NAMESPACE push_scope compound_declaration
'''
global _parse_info
scope = _parse_info.pop_scope()
def p_namespace_alias_definition(p):
'''namespace_alias_definition : NAMESPACE scoped_id '=' scoped_id ';'
'''
pass
def p_push_scope(p):
'''push_scope : empty'''
global _parse_info
if p[-2] == "namespace":
scope=p[-1]
else:
scope=""
_parse_info.push_scope(scope,"namespace")
def p_using_declaration(p):
'''using_declaration : USING declarator_id ';'
| USING TYPENAME declarator_id ';'
'''
pass
def p_using_directive(p):
'''using_directive : USING NAMESPACE scoped_id ';'
'''
pass
# '''asm_definition : ASM '(' StringLiteral ')' ';'
def p_asm_definition(p):
'''asm_definition : ASM '(' nonparen_seq_opt ')' ';'
'''
pass
def p_linkage_specification(p):
'''linkage_specification : EXTERN CLiteral declaration
| EXTERN CLiteral compound_declaration
| EXTERN CppLiteral declaration
| EXTERN CppLiteral compound_declaration
'''
pass
#---------------------------------------------------------------------------------------------------
# A.7 Declarators
#---------------------------------------------------------------------------------------------------
#
# init-declarator is named init_declaration to reflect the embedded decl-specifier-seq_opt
#
def p_init_declarations(p):
'''init_declarations : assignment_expression ',' init_declaration
| init_declarations ',' init_declaration
'''
p[0]=get_rest(p)
def p_init_declaration(p):
'''init_declaration : assignment_expression
'''
p[0]=get_rest(p)
def p_star_ptr_operator(p):
'''star_ptr_operator : '*'
| star_ptr_operator cv_qualifier
'''
pass
def p_nested_ptr_operator(p):
'''nested_ptr_operator : star_ptr_operator
| id_scope nested_ptr_operator
'''
pass
def p_ptr_operator(p):
'''ptr_operator : '&'
| nested_ptr_operator
| global_scope nested_ptr_operator
'''
pass
def p_ptr_operator_seq(p):
'''ptr_operator_seq : ptr_operator
| ptr_operator ptr_operator_seq
'''
pass
#
# Independently coded to localise the shift-reduce conflict: sharing just needs another %prec
#
def p_ptr_operator_seq_opt(p):
'''ptr_operator_seq_opt : empty %prec SHIFT_THERE
| ptr_operator ptr_operator_seq_opt
'''
pass
def p_cv_qualifier_seq_opt(p):
'''cv_qualifier_seq_opt : empty
| cv_qualifier_seq_opt cv_qualifier
'''
pass
# TODO: verify that we should include attributes here
def p_cv_qualifier(p):
'''cv_qualifier : CONST
| VOLATILE
| attributes
'''
pass
def p_type_id(p):
'''type_id : type_specifier abstract_declarator_opt
| type_specifier type_id
'''
pass
def p_abstract_declarator_opt(p):
'''abstract_declarator_opt : empty
| ptr_operator abstract_declarator_opt
| direct_abstract_declarator
'''
pass
def p_direct_abstract_declarator_opt(p):
'''direct_abstract_declarator_opt : empty
| direct_abstract_declarator
'''
pass
def p_direct_abstract_declarator(p):
'''direct_abstract_declarator : direct_abstract_declarator_opt parenthesis_clause
| direct_abstract_declarator_opt LBRACKET RBRACKET
| direct_abstract_declarator_opt LBRACKET bexpression RBRACKET
'''
pass
def p_parenthesis_clause(p):
'''parenthesis_clause : parameters_clause cv_qualifier_seq_opt
| parameters_clause cv_qualifier_seq_opt exception_specification
'''
p[0] = ['(',')']
def p_parameters_clause(p):
'''parameters_clause : '(' condition_opt ')'
'''
p[0] = ['(',')']
#
# A typed abstract qualifier such as
# Class * ...
# looks like a multiply, so pointers are parsed as their binary operation equivalents that
# ultimately terminate with a degenerate right hand term.
#
def p_abstract_pointer_declaration(p):
'''abstract_pointer_declaration : ptr_operator_seq
| multiplicative_expression star_ptr_operator ptr_operator_seq_opt
'''
pass
def p_abstract_parameter_declaration(p):
'''abstract_parameter_declaration : abstract_pointer_declaration
| and_expression '&'
| and_expression '&' abstract_pointer_declaration
'''
pass
def p_special_parameter_declaration(p):
'''special_parameter_declaration : abstract_parameter_declaration
| abstract_parameter_declaration '=' assignment_expression
| ELLIPSIS
'''
pass
def p_parameter_declaration(p):
'''parameter_declaration : assignment_expression
| special_parameter_declaration
| decl_specifier_prefix parameter_declaration
'''
pass
#
# function_definition includes constructor, destructor, implicit int definitions too. A local destructor is successfully parsed as a function-declaration but the ~ was treated as a unary operator. constructor_head is the prefix ambiguity between a constructor and a member-init-list starting with a bit-field.
#
def p_function_definition(p):
'''function_definition : ctor_definition
| func_definition
'''
pass
def p_func_definition(p):
'''func_definition : assignment_expression function_try_block
| assignment_expression function_body
| decl_specifier_prefix func_definition
'''
global _parse_info
if p[2] is not None and p[2][0] == '{':
decl = flatten(p[1])
#print "HERE",decl
if decl[-1] == ')':
decl=decl[-3]
else:
decl=decl[-1]
p[0] = decl
if decl != "operator":
_parse_info.add_function(decl)
else:
p[0] = p[2]
def p_ctor_definition(p):
'''ctor_definition : constructor_head function_try_block
| constructor_head function_body
| decl_specifier_prefix ctor_definition
'''
if p[2] is None or p[2][0] == "try" or p[2][0] == '{':
p[0]=p[1]
else:
p[0]=p[1]
def p_constructor_head(p):
'''constructor_head : bit_field_init_declaration
| constructor_head ',' assignment_expression
'''
p[0]=p[1]
def p_function_try_block(p):
'''function_try_block : TRY function_block handler_seq
'''
global noExceptionLogic
noExceptionLogic=False
p[0] = ['try']
def p_function_block(p):
'''function_block : ctor_initializer_opt function_body
'''
pass
def p_function_body(p):
'''function_body : LBRACE nonbrace_seq_opt RBRACE
'''
p[0] = ['{','}']
def p_initializer_clause(p):
'''initializer_clause : assignment_expression
| braced_initializer
'''
pass
def p_braced_initializer(p):
'''braced_initializer : LBRACE initializer_list RBRACE
| LBRACE initializer_list ',' RBRACE
| LBRACE RBRACE
'''
pass
def p_initializer_list(p):
'''initializer_list : initializer_clause
| initializer_list ',' initializer_clause
'''
pass
#---------------------------------------------------------------------------------------------------
# A.8 Classes
#---------------------------------------------------------------------------------------------------
#
# An anonymous bit-field declaration may look very like inheritance:
# const int B = 3;
# class A : B ;
# The two usages are too distant to try to create and enforce a common prefix so we have to resort to
# a parser hack by backtracking. Inheritance is much the most likely so we mark the input stream context
# and try to parse a base-clause. If we successfully reach a { the base-clause is ok and inheritance was
# the correct choice so we unmark and continue. If we fail to find the { an error token causes
# back-tracking to the alternative parse in elaborated_type_specifier which regenerates the : and
# declares unconditional success.
#
def p_class_specifier_head(p):
'''class_specifier_head : class_key scoped_id ':' base_specifier_list LBRACE
| class_key ':' base_specifier_list LBRACE
| class_key scoped_id LBRACE
| class_key LBRACE
'''
global _parse_info
base_classes=[]
if len(p) == 6:
scope = p[2]
base_classes = p[4]
elif len(p) == 4:
scope = p[2]
elif len(p) == 5:
base_classes = p[3]
else:
scope = ""
_parse_info.push_scope(scope,p[1],base_classes)
def p_class_key(p):
'''class_key : CLASS
| STRUCT
| UNION
'''
p[0] = p[1]
def p_class_specifier(p):
'''class_specifier : class_specifier_head member_specification_opt RBRACE
'''
scope = _parse_info.pop_scope()
def p_member_specification_opt(p):
'''member_specification_opt : empty
| member_specification_opt member_declaration
'''
pass
def p_member_declaration(p):
'''member_declaration : accessibility_specifier
| simple_member_declaration
| function_definition
| using_declaration
| template_declaration
'''
p[0] = get_rest(p)
#print "Decl",get_rest(p)
#
# The generality of constructor names (there need be no parenthesised argument list) means that that
# name : f(g), h(i)
# could be the start of a constructor or the start of an anonymous bit-field. An ambiguity is avoided by
# parsing the ctor-initializer of a function_definition as a bit-field.
#
def p_simple_member_declaration(p):
'''simple_member_declaration : ';'
| assignment_expression ';'
| constructor_head ';'
| member_init_declarations ';'
| decl_specifier_prefix simple_member_declaration
'''
global _parse_info
decl = flatten(get_rest(p))
if len(decl) >= 4 and decl[-3] == "(":
_parse_info.add_function(decl[-4])
def p_member_init_declarations(p):
'''member_init_declarations : assignment_expression ',' member_init_declaration
| constructor_head ',' bit_field_init_declaration
| member_init_declarations ',' member_init_declaration
'''
pass
def p_member_init_declaration(p):
'''member_init_declaration : assignment_expression
| bit_field_init_declaration
'''
pass
def p_accessibility_specifier(p):
'''accessibility_specifier : access_specifier ':'
'''
pass
def p_bit_field_declaration(p):
'''bit_field_declaration : assignment_expression ':' bit_field_width
| ':' bit_field_width
'''
if len(p) == 4:
p[0]=p[1]
def p_bit_field_width(p):
'''bit_field_width : logical_or_expression
| logical_or_expression '?' bit_field_width ':' bit_field_width
'''
pass
def p_bit_field_init_declaration(p):
'''bit_field_init_declaration : bit_field_declaration
| bit_field_declaration '=' initializer_clause
'''
pass
#---------------------------------------------------------------------------------------------------
# A.9 Derived classes
#---------------------------------------------------------------------------------------------------
def p_base_specifier_list(p):
'''base_specifier_list : base_specifier
| base_specifier_list ',' base_specifier
'''
if len(p) == 2:
p[0] = [p[1]]
else:
p[0] = p[1]+[p[3]]
def p_base_specifier(p):
'''base_specifier : scoped_id
| access_specifier base_specifier
| VIRTUAL base_specifier
'''
if len(p) == 2:
p[0] = p[1]
else:
p[0] = p[2]
def p_access_specifier(p):
'''access_specifier : PRIVATE
| PROTECTED
| PUBLIC
'''
pass
#---------------------------------------------------------------------------------------------------
# A.10 Special member functions
#---------------------------------------------------------------------------------------------------
def p_conversion_function_id(p):
'''conversion_function_id : OPERATOR conversion_type_id
'''
p[0] = ['operator']
def p_conversion_type_id(p):
'''conversion_type_id : type_specifier ptr_operator_seq_opt
| type_specifier conversion_type_id
'''
pass
#
# Ctor-initialisers can look like a bit field declaration, given the generalisation of names:
# Class(Type) : m1(1), m2(2) { }
# NonClass(bit_field) : int(2), second_variable, ...
# The grammar below is used within a function_try_block or function_definition.
# See simple_member_declaration for use in normal member function_definition.
#
def p_ctor_initializer_opt(p):
'''ctor_initializer_opt : empty
| ctor_initializer
'''
pass
def p_ctor_initializer(p):
'''ctor_initializer : ':' mem_initializer_list
'''
pass
def p_mem_initializer_list(p):
'''mem_initializer_list : mem_initializer
| mem_initializer_list_head mem_initializer
'''
pass
def p_mem_initializer_list_head(p):
'''mem_initializer_list_head : mem_initializer_list ','
'''
pass
def p_mem_initializer(p):
'''mem_initializer : mem_initializer_id '(' expression_list_opt ')'
'''
pass
def p_mem_initializer_id(p):
'''mem_initializer_id : scoped_id
'''
pass
#---------------------------------------------------------------------------------------------------
# A.11 Overloading
#---------------------------------------------------------------------------------------------------
def p_operator_function_id(p):
'''operator_function_id : OPERATOR operator
| OPERATOR '(' ')'
| OPERATOR LBRACKET RBRACKET
| OPERATOR '<'
| OPERATOR '>'
| OPERATOR operator '<' nonlgt_seq_opt '>'
'''
p[0] = ["operator"]
#
# It is not clear from the ANSI standard whether spaces are permitted in delete[]. If not then it can
# be recognised and returned as DELETE_ARRAY by the lexer. Assuming spaces are permitted there is an
# ambiguity created by the over generalised nature of expressions. operator new is a valid delarator-id
# which we may have an undimensioned array of. Semantic rubbish, but syntactically valid. Since the
# array form is covered by the declarator consideration we can exclude the operator here. The need
# for a semantic rescue can be eliminated at the expense of a couple of shift-reduce conflicts by
# removing the comments on the next four lines.
#
def p_operator(p):
'''operator : NEW
| DELETE
| '+'
| '-'
| '*'
| '/'
| '%'
| '^'
| '&'
| '|'
| '~'
| '!'
| '='
| ASS_ADD
| ASS_SUB
| ASS_MUL
| ASS_DIV
| ASS_MOD
| ASS_XOR
| ASS_AND
| ASS_OR
| SHL
| SHR
| ASS_SHR
| ASS_SHL
| EQ
| NE
| LE
| GE
| LOG_AND
| LOG_OR
| INC
| DEC
| ','
| ARROW_STAR
| ARROW
'''
p[0]=p[1]
# | IF
# | SWITCH
# | WHILE
# | FOR
# | DO
def p_reserved(p):
'''reserved : PRIVATE
| CLiteral
| CppLiteral
| IF
| SWITCH
| WHILE
| FOR
| DO
| PROTECTED
| PUBLIC
| BOOL
| CHAR
| DOUBLE
| FLOAT
| INT
| LONG
| SHORT
| SIGNED
| UNSIGNED
| VOID
| WCHAR_T
| CLASS
| ENUM
| NAMESPACE
| STRUCT
| TYPENAME
| UNION
| CONST
| VOLATILE
| AUTO
| EXPLICIT
| EXPORT
| EXTERN
| FRIEND
| INLINE
| MUTABLE
| REGISTER
| STATIC
| TEMPLATE
| TYPEDEF
| USING
| VIRTUAL
| ASM
| BREAK
| CASE
| CATCH
| CONST_CAST
| CONTINUE
| DEFAULT
| DYNAMIC_CAST
| ELSE
| FALSE
| GOTO
| OPERATOR
| REINTERPRET_CAST
| RETURN
| SIZEOF
| STATIC_CAST
| THIS
| THROW
| TRUE
| TRY
| TYPEID
| ATTRIBUTE
| CDECL
| TYPEOF
| uTYPEOF
'''
if p[1] in ('try', 'catch', 'throw'):
global noExceptionLogic
noExceptionLogic=False
#---------------------------------------------------------------------------------------------------
# A.12 Templates
#---------------------------------------------------------------------------------------------------
def p_template_declaration(p):
'''template_declaration : template_parameter_clause declaration
| EXPORT template_declaration
'''
pass
def p_template_parameter_clause(p):
'''template_parameter_clause : TEMPLATE '<' nonlgt_seq_opt '>'
'''
pass
#
# Generalised naming makes identifier a valid declaration, so TEMPLATE identifier is too.
# The TEMPLATE prefix is therefore folded into all names, parenthesis_clause and decl_specifier_prefix.
#
# explicit_instantiation: TEMPLATE declaration
#
def p_explicit_specialization(p):
'''explicit_specialization : TEMPLATE '<' '>' declaration
'''
pass
#---------------------------------------------------------------------------------------------------
# A.13 Exception Handling
#---------------------------------------------------------------------------------------------------
def p_handler_seq(p):
'''handler_seq : handler
| handler handler_seq
'''
pass
def p_handler(p):
'''handler : CATCH '(' exception_declaration ')' compound_statement
'''
global noExceptionLogic
noExceptionLogic=False
def p_exception_declaration(p):
'''exception_declaration : parameter_declaration
'''
pass
def p_throw_expression(p):
'''throw_expression : THROW
| THROW assignment_expression
'''
global noExceptionLogic
noExceptionLogic=False
def p_exception_specification(p):
'''exception_specification : THROW '(' ')'
| THROW '(' type_id_list ')'
'''
global noExceptionLogic
noExceptionLogic=False
def p_type_id_list(p):
'''type_id_list : type_id
| type_id_list ',' type_id
'''
pass
#---------------------------------------------------------------------------------------------------
# Misc productions
#---------------------------------------------------------------------------------------------------
def p_nonsemicolon_seq(p):
'''nonsemicolon_seq : empty
| nonsemicolon_seq nonsemicolon
'''
pass
def p_nonsemicolon(p):
'''nonsemicolon : misc
| '('
| ')'
| '<'
| '>'
| LBRACKET nonbracket_seq_opt RBRACKET
| LBRACE nonbrace_seq_opt RBRACE
'''
pass
def p_nonparen_seq_opt(p):
'''nonparen_seq_opt : empty
| nonparen_seq_opt nonparen
'''
pass
def p_nonparen_seq(p):
'''nonparen_seq : nonparen
| nonparen_seq nonparen
'''
pass
def p_nonparen(p):
'''nonparen : misc
| '<'
| '>'
| ';'
| LBRACKET nonbracket_seq_opt RBRACKET
| LBRACE nonbrace_seq_opt RBRACE
'''
pass
def p_nonbracket_seq_opt(p):
'''nonbracket_seq_opt : empty
| nonbracket_seq_opt nonbracket
'''
pass
def p_nonbracket_seq(p):
'''nonbracket_seq : nonbracket
| nonbracket_seq nonbracket
'''
pass
def p_nonbracket(p):
'''nonbracket : misc
| '<'
| '>'
| '('
| ')'
| ';'
| LBRACKET nonbracket_seq_opt RBRACKET
| LBRACE nonbrace_seq_opt RBRACE
'''
pass
def p_nonbrace_seq_opt(p):
'''nonbrace_seq_opt : empty
| nonbrace_seq_opt nonbrace
'''
pass
def p_nonbrace(p):
'''nonbrace : misc
| '<'
| '>'
| '('
| ')'
| ';'
| LBRACKET nonbracket_seq_opt RBRACKET
| LBRACE nonbrace_seq_opt RBRACE
'''
pass
def p_nonlgt_seq_opt(p):
'''nonlgt_seq_opt : empty
| nonlgt_seq_opt nonlgt
'''
pass
def p_nonlgt(p):
'''nonlgt : misc
| '('
| ')'
| LBRACKET nonbracket_seq_opt RBRACKET
| '<' nonlgt_seq_opt '>'
| ';'
'''
pass
def p_misc(p):
'''misc : operator
| identifier
| IntegerLiteral
| CharacterLiteral
| FloatingLiteral
| StringLiteral
| reserved
| '?'
| ':'
| '.'
| SCOPE
| ELLIPSIS
| EXTENSION
'''
pass
def p_empty(p):
'''empty : '''
pass
#
# Compute column.
# input is the input text string
# token is a token instance
#
def _find_column(input,token):
''' TODO '''
i = token.lexpos
while i > 0:
if input[i] == '\n': break
i -= 1
column = (token.lexpos - i)+1
return column
def p_error(p):
if p is None:
tmp = "Syntax error at end of file."
else:
tmp = "Syntax error at token "
if p.type is "":
tmp = tmp + "''"
else:
tmp = tmp + str(p.type)
tmp = tmp + " with value '"+str(p.value)+"'"
tmp = tmp + " in line " + str(lexer.lineno-1)
tmp = tmp + " at column "+str(_find_column(_parsedata,p))
raise IOError( tmp )
#
# The function that performs the parsing
#
def parse_cpp(data=None, filename=None, debug=0, optimize=0, verbose=False, func_filter=None):
if debug > 0:
print "Debugging parse_cpp!"
#
# Always remove the parser.out file, which is generated to create debugging
#
if os.path.exists("parser.out"):
os.remove("parser.out")
#
# Remove the parsetab.py* files. These apparently need to be removed
# to ensure the creation of a parser.out file.
#
if os.path.exists("parsetab.py"):
os.remove("parsetab.py")
if os.path.exists("parsetab.pyc"):
os.remove("parsetab.pyc")
global debugging
debugging=True
#
# Build lexer
#
global lexer
lexer = lex.lex()
#
# Initialize parse object
#
global _parse_info
_parse_info = CppInfo(filter=func_filter)
_parse_info.verbose=verbose
#
# Build yaccer
#
write_table = not os.path.exists("parsetab.py")
yacc.yacc(debug=debug, optimize=optimize, write_tables=write_table)
#
# Parse the file
#
global _parsedata
if not data is None:
_parsedata=data
ply_init(_parsedata)
yacc.parse(data,debug=debug)
elif not filename is None:
f = open(filename)
data = f.read()
f.close()
_parsedata=data
ply_init(_parsedata)
yacc.parse(data, debug=debug)
else:
return None
#
if not noExceptionLogic:
_parse_info.noExceptionLogic = False
else:
for key in identifier_lineno:
if 'ASSERT_THROWS' in key:
_parse_info.noExceptionLogic = False
break
_parse_info.noExceptionLogic = True
#
return _parse_info
import sys
if __name__ == '__main__':
#
# This MAIN routine parses a sequence of files provided at the command
# line. If '-v' is included, then a verbose parsing output is
# generated.
#
for arg in sys.argv[1:]:
if arg == "-v":
continue
print "Parsing file '"+arg+"'"
if '-v' in sys.argv:
parse_cpp(filename=arg,debug=2,verbose=2)
else:
parse_cpp(filename=arg,verbose=2)
#
# Print the _parse_info object summary for this file.
# This illustrates how class inheritance can be used to
# deduce class members.
#
print str(_parse_info)
| [
[
1,
0,
0.0228,
0.0005,
0,
0.66,
0,
777,
0,
1,
0,
0,
777,
0,
0
],
[
1,
0,
0.0238,
0.0005,
0,
0.66,
0.004,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0242,
0.0005,
0,
0... | [
"from __future__ import division",
"import os",
"import ply.lex as lex",
"import ply.yacc as yacc",
"import re",
"try:\n from collections import OrderedDict\nexcept ImportError:\n from ordereddict import OrderedDict",
" from collections import OrderedDict",
" from ordereddict import Ordere... |
#-------------------------------------------------------------------------
# CxxTest: A lightweight C++ unit testing library.
# Copyright (c) 2008 Sandia Corporation.
# This software is distributed under the LGPL License v2.1
# For more information, see the COPYING file in the top CxxTest directory.
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains certain rights in this software.
#-------------------------------------------------------------------------
"""cxxtest: A Python package that supports the CxxTest test framework for C/C++.
.. _CxxTest: http://cxxtest.tigris.org/
CxxTest is a unit testing framework for C++ that is similar in
spirit to JUnit, CppUnit, and xUnit. CxxTest is easy to use because
it does not require precompiling a CxxTest testing library, it
employs no advanced features of C++ (e.g. RTTI) and it supports a
very flexible form of test discovery.
The cxxtest Python package includes capabilities for parsing C/C++ source files and generating
CxxTest drivers.
"""
from cxxtest.__release__ import __version__, __date__
__date__
__version__
__maintainer__ = "William E. Hart"
__maintainer_email__ = "whart222@gmail.com"
__license__ = "LGPL"
__url__ = "http://cxxtest.tigris.org/"
from cxxtest.cxxtestgen import *
| [
[
8,
0,
0.4848,
0.3939,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.7273,
0.0303,
0,
0.66,
0.125,
129,
0,
2,
0,
0,
129,
0,
0
],
[
8,
0,
0.7576,
0.0303,
0,
0.66,... | [
"\"\"\"cxxtest: A Python package that supports the CxxTest test framework for C/C++.\n\n.. _CxxTest: http://cxxtest.tigris.org/\n\nCxxTest is a unit testing framework for C++ that is similar in\nspirit to JUnit, CppUnit, and xUnit. CxxTest is easy to use because\nit does not require precompiling a CxxTest testing l... |
#!/usr/bin/python
#-------------------------------------------------------------------------
# CxxTest: A lightweight C++ unit testing library.
# Copyright (c) 2008 Sandia Corporation.
# This software is distributed under the LGPL License v2.1
# For more information, see the COPYING file in the top CxxTest directory.
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains certain rights in this software.
#-------------------------------------------------------------------------
import sys
def abort( problem ):
'''Print error message and exit'''
sys.stderr.write( '\n' )
sys.stderr.write( problem )
sys.stderr.write( '\n\n' )
sys.exit(2)
| [
[
1,
0,
0.5789,
0.0526,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
2,
0,
0.8158,
0.3158,
0,
0.66,
1,
299,
0,
1,
0,
0,
0,
0,
4
],
[
8,
1,
0.7368,
0.0526,
1,
0.86,
... | [
"import sys",
"def abort( problem ):\n '''Print error message and exit'''\n sys.stderr.write( '\\n' )\n sys.stderr.write( problem )\n sys.stderr.write( '\\n\\n' )\n sys.exit(2)",
" '''Print error message and exit'''",
" sys.stderr.write( '\\n' )",
" sys.stderr.write( problem )",
" ... |
#-------------------------------------------------------------------------
# CxxTest: A lightweight C++ unit testing library.
# Copyright (c) 2008 Sandia Corporation.
# This software is distributed under the LGPL License v2.1
# For more information, see the COPYING file in the top CxxTest directory.
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains certain rights in this software.
#-------------------------------------------------------------------------
# vim: fileencoding=utf-8
from __future__ import division
# the above import important for forward-compatibility with python3,
# which is already the default in archlinux!
__all__ = ['main']
import __release__
import os
import sys
import re
import glob
from optparse import OptionParser
import cxxtest_parser
try:
import cxxtest_fog
imported_fog=True
except ImportError:
imported_fog=False
from cxxtest_misc import abort
options = []
suites = []
wrotePreamble = 0
wroteWorld = 0
lastIncluded = ''
def main(args=sys.argv):
'''The main program'''
#
# Reset global state
#
global wrotePreamble
wrotePreamble=0
global wroteWorld
wroteWorld=0
global lastIncluded
lastIncluded = ''
global suites
global options
files = parseCommandline(args)
if imported_fog and options.fog:
[options,suites] = cxxtest_fog.scanInputFiles( files, options )
else:
[options,suites] = cxxtest_parser.scanInputFiles( files, options )
writeOutput()
def parseCommandline(args):
'''Analyze command line arguments'''
global imported_fog
global options
parser = OptionParser("%prog [options] [<filename> ...]")
parser.add_option("--version",
action="store_true", dest="version", default=False,
help="Write the CxxTest version.")
parser.add_option("-o", "--output",
dest="outputFileName", default=None, metavar="NAME",
help="Write output to file NAME.")
parser.add_option("-w","--world", dest="world", default="cxxtest",
help="The label of the tests, used to name the XML results.")
parser.add_option("", "--include", action="append",
dest="headers", default=[], metavar="HEADER",
help="Include file HEADER in the test runner before other headers.")
parser.add_option("", "--abort-on-fail",
action="store_true", dest="abortOnFail", default=False,
help="Abort tests on failed asserts (like xUnit).")
parser.add_option("", "--main",
action="store", dest="main", default="main",
help="Specify an alternative name for the main() function.")
parser.add_option("", "--headers",
action="store", dest="header_filename", default=None,
help="Specify a filename that contains a list of header files that are processed to generate a test runner.")
parser.add_option("", "--runner",
dest="runner", default="", metavar="CLASS",
help="Create a test runner that processes test events using the class CxxTest::CLASS.")
parser.add_option("", "--gui",
dest="gui", metavar="CLASS",
help="Create a GUI test runner that processes test events using the class CxxTest::CLASS. (deprecated)")
parser.add_option("", "--error-printer",
action="store_true", dest="error_printer", default=False,
help="Create a test runner using the ErrorPrinter class, and allow the use of the standard library.")
parser.add_option("", "--xunit-printer",
action="store_true", dest="xunit_printer", default=False,
help="Create a test runner using the XUnitPrinter class.")
parser.add_option("", "--xunit-file", dest="xunit_file", default="",
help="The file to which the XML summary is written for test runners using the XUnitPrinter class. The default XML filename is TEST-<world>.xml, where <world> is the value of the --world option. (default: cxxtest)")
parser.add_option("", "--have-std",
action="store_true", dest="haveStandardLibrary", default=False,
help="Use the standard library (even if not found in tests).")
parser.add_option("", "--no-std",
action="store_true", dest="noStandardLibrary", default=False,
help="Do not use standard library (even if found in tests).")
parser.add_option("", "--have-eh",
action="store_true", dest="haveExceptionHandling", default=False,
help="Use exception handling (even if not found in tests).")
parser.add_option("", "--no-eh",
action="store_true", dest="noExceptionHandling", default=False,
help="Do not use exception handling (even if found in tests).")
parser.add_option("", "--longlong",
dest="longlong", default=None, metavar="TYPE",
help="Use TYPE as for long long integers. (default: not supported)")
parser.add_option("", "--no-static-init",
action="store_true", dest="noStaticInit", default=False,
help="Do not rely on static initialization in the test runner.")
parser.add_option("", "--template",
dest="templateFileName", default=None, metavar="TEMPLATE",
help="Generate the test runner using file TEMPLATE to define a template.")
parser.add_option("", "--root",
action="store_true", dest="root", default=False,
help="Write the main() function and global data for a test runner.")
parser.add_option("", "--part",
action="store_true", dest="part", default=False,
help="Write the tester classes for a test runner.")
#parser.add_option("", "--factor",
#action="store_true", dest="factor", default=False,
#help="Declare the _CXXTEST_FACTOR macro. (deprecated)")
if imported_fog:
fog_help = "Use new FOG C++ parser"
else:
fog_help = "Use new FOG C++ parser (disabled)"
parser.add_option("-f", "--fog-parser",
action="store_true",
dest="fog",
default=False,
help=fog_help
)
(options, args) = parser.parse_args(args=args)
if not options.header_filename is None:
if not os.path.exists(options.header_filename):
abort( "ERROR: the file '%s' does not exist!" % options.header_filename )
INPUT = open(options.header_filename)
headers = [line.strip() for line in INPUT]
args.extend( headers )
INPUT.close()
if options.fog and not imported_fog:
abort( "Cannot use the FOG parser. Check that the 'ply' package is installed. The 'ordereddict' package is also required if running Python 2.6")
if options.version:
printVersion()
# the cxxtest builder relies on this behaviour! don't remove
if options.runner == 'none':
options.runner = None
if options.xunit_printer or options.runner == "XUnitPrinter":
options.xunit_printer=True
options.runner="XUnitPrinter"
if len(args) > 1:
if options.xunit_file == "":
if options.world == "":
options.world = "cxxtest"
options.xunit_file="TEST-"+options.world+".xml"
elif options.xunit_file == "":
if options.world == "":
options.world = "cxxtest"
options.xunit_file="TEST-"+options.world+".xml"
if options.error_printer:
options.runner= "ErrorPrinter"
options.haveStandardLibrary = True
if options.noStaticInit and (options.root or options.part):
abort( '--no-static-init cannot be used with --root/--part' )
if options.gui and not options.runner:
options.runner = 'StdioPrinter'
files = setFiles(args[1:])
if len(files) == 0 and not options.root:
sys.stderr.write(parser.error("No input files found"))
return files
def printVersion():
'''Print CxxTest version and exit'''
sys.stdout.write( "This is CxxTest version %s.\n" % __release__.__version__ )
sys.exit(0)
def setFiles(patterns ):
'''Set input files specified on command line'''
files = expandWildcards( patterns )
return files
def expandWildcards( patterns ):
'''Expand all wildcards in an array (glob)'''
fileNames = []
for pathName in patterns:
patternFiles = glob.glob( pathName )
for fileName in patternFiles:
fileNames.append( fixBackslashes( fileName ) )
return fileNames
def fixBackslashes( fileName ):
'''Convert backslashes to slashes in file name'''
return re.sub( r'\\', '/', fileName, 0 )
def writeOutput():
'''Create output file'''
if options.templateFileName:
writeTemplateOutput()
else:
writeSimpleOutput()
def writeSimpleOutput():
'''Create output not based on template'''
output = startOutputFile()
writePreamble( output )
if options.root or not options.part:
writeMain( output )
if len(suites) > 0:
output.write("bool "+suites[0]['object']+"_init = false;\n")
writeWorld( output )
output.close()
include_re = re.compile( r"\s*\#\s*include\s+<cxxtest/" )
preamble_re = re.compile( r"^\s*<CxxTest\s+preamble>\s*$" )
world_re = re.compile( r"^\s*<CxxTest\s+world>\s*$" )
def writeTemplateOutput():
'''Create output based on template file'''
template = open(options.templateFileName)
output = startOutputFile()
while 1:
line = template.readline()
if not line:
break;
if include_re.search( line ):
writePreamble( output )
output.write( line )
elif preamble_re.search( line ):
writePreamble( output )
elif world_re.search( line ):
if len(suites) > 0:
output.write("bool "+suites[0]['object']+"_init = false;\n")
writeWorld( output )
else:
output.write( line )
template.close()
output.close()
def startOutputFile():
'''Create output file and write header'''
if options.outputFileName is not None:
output = open( options.outputFileName, 'w' )
else:
output = sys.stdout
output.write( "/* Generated file, do not edit */\n\n" )
return output
def writePreamble( output ):
'''Write the CxxTest header (#includes and #defines)'''
global wrotePreamble
if wrotePreamble: return
output.write( "#ifndef CXXTEST_RUNNING\n" )
output.write( "#define CXXTEST_RUNNING\n" )
output.write( "#endif\n" )
output.write( "\n" )
if options.xunit_printer:
output.write( "#include <fstream>\n" )
if options.haveStandardLibrary:
output.write( "#define _CXXTEST_HAVE_STD\n" )
if options.haveExceptionHandling:
output.write( "#define _CXXTEST_HAVE_EH\n" )
if options.abortOnFail:
output.write( "#define _CXXTEST_ABORT_TEST_ON_FAIL\n" )
if options.longlong:
output.write( "#define _CXXTEST_LONGLONG %s\n" % options.longlong )
#if options.factor:
#output.write( "#define _CXXTEST_FACTOR\n" )
for header in options.headers:
output.write( "#include \"%s\"\n" % header )
output.write( "#include <cxxtest/TestListener.h>\n" )
output.write( "#include <cxxtest/TestTracker.h>\n" )
output.write( "#include <cxxtest/TestRunner.h>\n" )
output.write( "#include <cxxtest/RealDescriptions.h>\n" )
output.write( "#include <cxxtest/TestMain.h>\n" )
if options.runner:
output.write( "#include <cxxtest/%s.h>\n" % options.runner )
if options.gui:
output.write( "#include <cxxtest/%s.h>\n" % options.gui )
output.write( "\n" )
wrotePreamble = 1
def writeMain( output ):
'''Write the main() function for the test runner'''
if not (options.gui or options.runner):
return
output.write( 'int %s( int argc, char *argv[] ) {\n' % options.main )
output.write( ' int status;\n' )
if options.noStaticInit:
output.write( ' CxxTest::initialize();\n' )
if options.gui:
tester_t = "CxxTest::GuiTuiRunner<CxxTest::%s, CxxTest::%s> " % (options.gui, options.runner)
else:
tester_t = "CxxTest::%s" % (options.runner)
if options.xunit_printer:
output.write( ' std::ofstream ofstr("%s");\n' % options.xunit_file )
output.write( ' %s tmp(ofstr);\n' % tester_t )
output.write( ' CxxTest::RealWorldDescription::_worldName = "%s";\n' % options.world )
else:
output.write( ' %s tmp;\n' % tester_t )
output.write( ' status = CxxTest::Main<%s>( tmp, argc, argv );\n' % tester_t )
output.write( ' return status;\n')
output.write( '}\n' )
def writeWorld( output ):
'''Write the world definitions'''
global wroteWorld
if wroteWorld: return
writePreamble( output )
writeSuites( output )
if options.root or not options.part:
writeRoot( output )
writeWorldDescr( output )
if options.noStaticInit:
writeInitialize( output )
wroteWorld = 1
def writeSuites(output):
'''Write all TestDescriptions and SuiteDescriptions'''
for suite in suites:
writeInclude( output, suite['file'] )
if isGenerated(suite):
generateSuite( output, suite )
if isDynamic(suite):
writeSuitePointer( output, suite )
else:
writeSuiteObject( output, suite )
writeTestList( output, suite )
writeSuiteDescription( output, suite )
writeTestDescriptions( output, suite )
def isGenerated(suite):
'''Checks whether a suite class should be created'''
return suite['generated']
def isDynamic(suite):
'''Checks whether a suite is dynamic'''
return 'create' in suite
def writeInclude(output, file):
'''Add #include "file" statement'''
global lastIncluded
if file == lastIncluded: return
output.writelines( [ '#include "', file, '"\n\n' ] )
lastIncluded = file
def generateSuite( output, suite ):
'''Write a suite declared with CXXTEST_SUITE()'''
output.write( 'class %s : public CxxTest::TestSuite {\n' % suite['name'] )
output.write( 'public:\n' )
for line in suite['lines']:
output.write(line)
output.write( '};\n\n' )
def writeSuitePointer( output, suite ):
'''Create static suite pointer object for dynamic suites'''
if options.noStaticInit:
output.write( 'static %s *%s;\n\n' % (suite['name'], suite['object']) )
else:
output.write( 'static %s *%s = 0;\n\n' % (suite['name'], suite['object']) )
def writeSuiteObject( output, suite ):
'''Create static suite object for non-dynamic suites'''
output.writelines( [ "static ", suite['name'], " ", suite['object'], ";\n\n" ] )
def writeTestList( output, suite ):
'''Write the head of the test linked list for a suite'''
if options.noStaticInit:
output.write( 'static CxxTest::List %s;\n' % suite['tlist'] )
else:
output.write( 'static CxxTest::List %s = { 0, 0 };\n' % suite['tlist'] )
def writeWorldDescr( output ):
'''Write the static name of the world name'''
if options.noStaticInit:
output.write( 'const char* CxxTest::RealWorldDescription::_worldName;\n' )
else:
output.write( 'const char* CxxTest::RealWorldDescription::_worldName = "cxxtest";\n' )
def writeTestDescriptions( output, suite ):
'''Write all test descriptions for a suite'''
for test in suite['tests']:
writeTestDescription( output, suite, test )
def writeTestDescription( output, suite, test ):
'''Write test description object'''
output.write( 'static class %s : public CxxTest::RealTestDescription {\n' % test['class'] )
output.write( 'public:\n' )
if not options.noStaticInit:
output.write( ' %s() : CxxTest::RealTestDescription( %s, %s, %s, "%s" ) {}\n' %
(test['class'], suite['tlist'], suite['dobject'], test['line'], test['name']) )
output.write( ' void runTest() { %s }\n' % runBody( suite, test ) )
output.write( '} %s;\n\n' % test['object'] )
def runBody( suite, test ):
'''Body of TestDescription::run()'''
if isDynamic(suite): return dynamicRun( suite, test )
else: return staticRun( suite, test )
def dynamicRun( suite, test ):
'''Body of TestDescription::run() for test in a dynamic suite'''
return 'if ( ' + suite['object'] + ' ) ' + suite['object'] + '->' + test['name'] + '();'
def staticRun( suite, test ):
'''Body of TestDescription::run() for test in a non-dynamic suite'''
return suite['object'] + '.' + test['name'] + '();'
def writeSuiteDescription( output, suite ):
'''Write SuiteDescription object'''
if isDynamic( suite ):
writeDynamicDescription( output, suite )
else:
writeStaticDescription( output, suite )
def writeDynamicDescription( output, suite ):
'''Write SuiteDescription for a dynamic suite'''
output.write( 'CxxTest::DynamicSuiteDescription<%s> %s' % (suite['name'], suite['dobject']) )
if not options.noStaticInit:
output.write( '( %s, %s, "%s", %s, %s, %s, %s )' %
(suite['cfile'], suite['line'], suite['name'], suite['tlist'],
suite['object'], suite['create'], suite['destroy']) )
output.write( ';\n\n' )
def writeStaticDescription( output, suite ):
'''Write SuiteDescription for a static suite'''
output.write( 'CxxTest::StaticSuiteDescription %s' % suite['dobject'] )
if not options.noStaticInit:
output.write( '( %s, %s, "%s", %s, %s )' %
(suite['cfile'], suite['line'], suite['name'], suite['object'], suite['tlist']) )
output.write( ';\n\n' )
def writeRoot(output):
'''Write static members of CxxTest classes'''
output.write( '#include <cxxtest/Root.cpp>\n' )
def writeInitialize(output):
'''Write CxxTest::initialize(), which replaces static initialization'''
output.write( 'namespace CxxTest {\n' )
output.write( ' void initialize()\n' )
output.write( ' {\n' )
for suite in suites:
output.write( ' %s.initialize();\n' % suite['tlist'] )
if isDynamic(suite):
output.write( ' %s = 0;\n' % suite['object'] )
output.write( ' %s.initialize( %s, %s, "%s", %s, %s, %s, %s );\n' %
(suite['dobject'], suite['cfile'], suite['line'], suite['name'],
suite['tlist'], suite['object'], suite['create'], suite['destroy']) )
else:
output.write( ' %s.initialize( %s, %s, "%s", %s, %s );\n' %
(suite['dobject'], suite['cfile'], suite['line'], suite['name'],
suite['object'], suite['tlist']) )
for test in suite['tests']:
output.write( ' %s.initialize( %s, %s, %s, "%s" );\n' %
(test['object'], suite['tlist'], suite['dobject'], test['line'], test['name']) )
output.write( ' }\n' )
output.write( '}\n' )
| [
[
1,
0,
0.025,
0.0021,
0,
0.66,
0,
777,
0,
1,
0,
0,
777,
0,
0
],
[
14,
0,
0.0333,
0.0021,
0,
0.66,
0.02,
272,
0,
0,
0,
0,
0,
5,
0
],
[
1,
0,
0.0375,
0.0021,
0,
0.66... | [
"from __future__ import division",
"__all__ = ['main']",
"import __release__",
"import os",
"import sys",
"import re",
"import glob",
"from optparse import OptionParser",
"import cxxtest_parser",
"try:\n import cxxtest_fog\n imported_fog=True\nexcept ImportError:\n imported_fog=False",
... |
#-------------------------------------------------------------------------
# CxxTest: A lightweight C++ unit testing library.
# Copyright (c) 2008 Sandia Corporation.
# This software is distributed under the LGPL License v2.1
# For more information, see the COPYING file in the top CxxTest directory.
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains certain rights in this software.
#-------------------------------------------------------------------------
from __future__ import division
import codecs
import re
#import sys
#import getopt
#import glob
from cxxtest.cxxtest_misc import abort
# Global variables
suites = []
suite = None
inBlock = 0
options=None
def scanInputFiles(files, _options):
'''Scan all input files for test suites'''
global options
options=_options
for file in files:
scanInputFile(file)
global suites
if len(suites) is 0 and not options.root:
abort( 'No tests defined' )
return [options,suites]
lineCont_re = re.compile('(.*)\\\s*$')
def scanInputFile(fileName):
'''Scan single input file for test suites'''
# mode 'rb' is problematic in python3 - byte arrays don't behave the same as
# strings.
# As far as the choice of the default encoding: utf-8 chews through
# everything that the previous ascii codec could, plus most of new code.
# TODO: figure out how to do this properly - like autodetect encoding from
# file header.
file = codecs.open(fileName, mode='r', encoding='utf-8')
prev = ""
lineNo = 0
contNo = 0
while 1:
line = file.readline()
if not line:
break
lineNo += 1
m = lineCont_re.match(line)
if m:
prev += m.group(1) + " "
contNo += 1
else:
scanInputLine( fileName, lineNo - contNo, prev + line )
contNo = 0
prev = ""
if contNo:
scanInputLine( fileName, lineNo - contNo, prev + line )
closeSuite()
file.close()
def scanInputLine( fileName, lineNo, line ):
'''Scan single input line for interesting stuff'''
scanLineForExceptionHandling( line )
scanLineForStandardLibrary( line )
scanLineForSuiteStart( fileName, lineNo, line )
global suite
if suite:
scanLineInsideSuite( suite, lineNo, line )
def scanLineInsideSuite( suite, lineNo, line ):
'''Analyze line which is part of a suite'''
global inBlock
if lineBelongsToSuite( suite, lineNo, line ):
scanLineForTest( suite, lineNo, line )
scanLineForCreate( suite, lineNo, line )
scanLineForDestroy( suite, lineNo, line )
def lineBelongsToSuite( suite, lineNo, line ):
'''Returns whether current line is part of the current suite.
This can be false when we are in a generated suite outside of CXXTEST_CODE() blocks
If the suite is generated, adds the line to the list of lines'''
if not suite['generated']:
return 1
global inBlock
if not inBlock:
inBlock = lineStartsBlock( line )
if inBlock:
inBlock = addLineToBlock( suite, lineNo, line )
return inBlock
std_re = re.compile( r"\b(std\s*::|CXXTEST_STD|using\s+namespace\s+std\b|^\s*\#\s*include\s+<[a-z0-9]+>)" )
def scanLineForStandardLibrary( line ):
'''Check if current line uses standard library'''
global options
if not options.haveStandardLibrary and std_re.search(line):
if not options.noStandardLibrary:
options.haveStandardLibrary = 1
exception_re = re.compile( r"\b(throw|try|catch|TSM?_ASSERT_THROWS[A-Z_]*)\b" )
def scanLineForExceptionHandling( line ):
'''Check if current line uses exception handling'''
global options
if not options.haveExceptionHandling and exception_re.search(line):
if not options.noExceptionHandling:
options.haveExceptionHandling = 1
classdef = '(?:::\s*)?(?:\w+\s*::\s*)*\w+'
baseclassdef = '(?:public|private|protected)\s+%s' % (classdef,)
general_suite = r"\bclass\s+(%s)\s*:(?:\s*%s\s*,)*\s*public\s+" \
% (classdef, baseclassdef,)
testsuite = '(?:(?:::)?\s*CxxTest\s*::\s*)?TestSuite'
suites_re = { re.compile( general_suite + testsuite ) : None }
generatedSuite_re = re.compile( r'\bCXXTEST_SUITE\s*\(\s*(\w*)\s*\)' )
def scanLineForSuiteStart( fileName, lineNo, line ):
'''Check if current line starts a new test suite'''
for i in list(suites_re.items()):
m = i[0].search( line )
if m:
suite = startSuite( m.group(1), fileName, lineNo, 0 )
if i[1] is not None:
for test in i[1]['tests']:
addTest(suite, test['name'], test['line'])
break
m = generatedSuite_re.search( line )
if m:
sys.stdout.write( "%s:%s: Warning: Inline test suites are deprecated.\n" % (fileName, lineNo) )
startSuite( m.group(1), fileName, lineNo, 1 )
def startSuite( name, file, line, generated ):
'''Start scanning a new suite'''
global suite
closeSuite()
object_name = name.replace(':',"_")
suite = { 'name' : name,
'file' : file,
'cfile' : cstr(file),
'line' : line,
'generated' : generated,
'object' : 'suite_%s' % object_name,
'dobject' : 'suiteDescription_%s' % object_name,
'tlist' : 'Tests_%s' % object_name,
'tests' : [],
'lines' : [] }
suites_re[re.compile( general_suite + name )] = suite
return suite
def lineStartsBlock( line ):
'''Check if current line starts a new CXXTEST_CODE() block'''
return re.search( r'\bCXXTEST_CODE\s*\(', line ) is not None
test_re = re.compile( r'^([^/]|/[^/])*\bvoid\s+([Tt]est\w+)\s*\(\s*(void)?\s*\)' )
def scanLineForTest( suite, lineNo, line ):
'''Check if current line starts a test'''
m = test_re.search( line )
if m:
addTest( suite, m.group(2), lineNo )
def addTest( suite, name, line ):
'''Add a test function to the current suite'''
test = { 'name' : name,
'suite' : suite,
'class' : 'TestDescription_%s_%s' % (suite['object'], name),
'object' : 'testDescription_%s_%s' % (suite['object'], name),
'line' : line,
}
suite['tests'].append( test )
def addLineToBlock( suite, lineNo, line ):
'''Append the line to the current CXXTEST_CODE() block'''
line = fixBlockLine( suite, lineNo, line )
line = re.sub( r'^.*\{\{', '', line )
e = re.search( r'\}\}', line )
if e:
line = line[:e.start()]
suite['lines'].append( line )
return e is None
def fixBlockLine( suite, lineNo, line):
'''Change all [E]TS_ macros used in a line to _[E]TS_ macros with the correct file/line'''
return re.sub( r'\b(E?TSM?_(ASSERT[A-Z_]*|FAIL))\s*\(',
r'_\1(%s,%s,' % (suite['cfile'], lineNo),
line, 0 )
create_re = re.compile( r'\bstatic\s+\w+\s*\*\s*createSuite\s*\(\s*(void)?\s*\)' )
def scanLineForCreate( suite, lineNo, line ):
'''Check if current line defines a createSuite() function'''
if create_re.search( line ):
addSuiteCreateDestroy( suite, 'create', lineNo )
destroy_re = re.compile( r'\bstatic\s+void\s+destroySuite\s*\(\s*\w+\s*\*\s*\w*\s*\)' )
def scanLineForDestroy( suite, lineNo, line ):
'''Check if current line defines a destroySuite() function'''
if destroy_re.search( line ):
addSuiteCreateDestroy( suite, 'destroy', lineNo )
def cstr( s ):
'''Convert a string to its C representation'''
return '"' + s.replace( '\\', '\\\\' ) + '"'
def addSuiteCreateDestroy( suite, which, line ):
'''Add createSuite()/destroySuite() to current suite'''
if which in suite:
abort( '%s:%s: %sSuite() already declared' % ( suite['file'], str(line), which ) )
suite[which] = line
def closeSuite():
'''Close current suite and add it to the list if valid'''
global suite
if suite is not None:
if len(suite['tests']) is not 0:
verifySuite(suite)
rememberSuite(suite)
suite = None
def verifySuite(suite):
'''Verify current suite is legal'''
if 'create' in suite and 'destroy' not in suite:
abort( '%s:%s: Suite %s has createSuite() but no destroySuite()' %
(suite['file'], suite['create'], suite['name']) )
elif 'destroy' in suite and 'create' not in suite:
abort( '%s:%s: Suite %s has destroySuite() but no createSuite()' %
(suite['file'], suite['destroy'], suite['name']) )
def rememberSuite(suite):
'''Add current suite to list'''
global suites
suites.append( suite )
| [
[
1,
0,
0.0413,
0.0041,
0,
0.66,
0,
777,
0,
1,
0,
0,
777,
0,
0
],
[
1,
0,
0.0496,
0.0041,
0,
0.66,
0.025,
220,
0,
1,
0,
0,
220,
0,
0
],
[
1,
0,
0.0537,
0.0041,
0,
0... | [
"from __future__ import division",
"import codecs",
"import re",
"from cxxtest.cxxtest_misc import abort",
"suites = []",
"suite = None",
"inBlock = 0",
"options=None",
"def scanInputFiles(files, _options):\n '''Scan all input files for test suites'''\n global options\n options=_options\n ... |
#-------------------------------------------------------------------------
# CxxTest: A lightweight C++ unit testing library.
# Copyright (c) 2008 Sandia Corporation.
# This software is distributed under the LGPL License v2.1
# For more information, see the COPYING file in the top CxxTest directory.
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains certain rights in this software.
#-------------------------------------------------------------------------
""" Release Information for cxxtest """
__version__ = '4.0.2'
__date__ = "2012-01-02"
| [
[
8,
0,
0.7692,
0.0769,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.9231,
0.0769,
0,
0.66,
0.5,
162,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
1,
0.0769,
0,
0.66,
1,... | [
"\"\"\" Release Information for cxxtest \"\"\"",
"__version__ = '4.0.2'",
"__date__ = \"2012-01-02\""
] |
#-------------------------------------------------------------------------
# CxxTest: A lightweight C++ unit testing library.
# Copyright (c) 2008 Sandia Corporation.
# This software is distributed under the LGPL License v2.1
# For more information, see the COPYING file in the top CxxTest directory.
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains certain rights in this software.
#-------------------------------------------------------------------------
# vim: fileencoding=utf-8
#
# This is a PLY parser for the entire ANSI C++ grammar. This grammar was
# adapted from the FOG grammar developed by E. D. Willink. See
#
# http://www.computing.surrey.ac.uk/research/dsrg/fog/
#
# for further details.
#
# The goal of this grammar is to extract information about class, function and
# class method declarations, along with their associated scope. Thus, this
# grammar can be used to analyze classes in an inheritance heirarchy, and then
# enumerate the methods in a derived class.
#
# This grammar parses blocks of <>, (), [] and {} in a generic manner. Thus,
# There are several capabilities that this grammar does not support:
#
# 1. Ambiguous template specification. This grammar cannot parse template
# specifications that do not have paired <>'s in their declaration. In
# particular, ambiguous declarations like
#
# foo<A, c<3 >();
#
# cannot be correctly parsed.
#
# 2. Template class specialization. Although the goal of this grammar is to
# extract class information, specialization of templated classes is
# not supported. When a template class definition is parsed, it's
# declaration is archived without information about the template
# parameters. Class specializations will be stored separately, and
# thus they can be processed after the fact. However, this grammar
# does not attempt to correctly process properties of class inheritence
# when template class specialization is employed.
#
#
# TODO: document usage of this file
#
from __future__ import division
import os
import ply.lex as lex
import ply.yacc as yacc
import re
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
lexer = None
scope_lineno = 0
identifier_lineno = {}
_parse_info=None
_parsedata=None
noExceptionLogic = True
def ply_init(data):
global _parsedata
_parsedata=data
class Scope(object):
def __init__(self,name,abs_name,scope_t,base_classes,lineno):
self.function=[]
self.name=name
self.scope_t=scope_t
self.sub_scopes=[]
self.base_classes=base_classes
self.abs_name=abs_name
self.lineno=lineno
def insert(self,scope):
self.sub_scopes.append(scope)
class CppInfo(object):
def __init__(self, filter=None):
self.verbose=0
if filter is None:
self.filter=re.compile("[Tt][Ee][Ss][Tt]|createSuite|destroySuite")
else:
self.filter=filter
self.scopes=[""]
self.index=OrderedDict()
self.index[""]=Scope("","::","namespace",[],1)
self.function=[]
def push_scope(self,ns,scope_t,base_classes=[]):
name = self.scopes[-1]+"::"+ns
if self.verbose>=2:
print "-- Starting "+scope_t+" "+name
self.scopes.append(name)
self.index[name] = Scope(ns,name,scope_t,base_classes,scope_lineno-1)
def pop_scope(self):
scope = self.scopes.pop()
if self.verbose>=2:
print "-- Stopping "+scope
return scope
def add_function(self, fn):
fn = str(fn)
if self.filter.search(fn):
self.index[self.scopes[-1]].function.append((fn, identifier_lineno.get(fn,lexer.lineno-1)))
tmp = self.scopes[-1]+"::"+fn
if self.verbose==2:
print "-- Function declaration "+fn+" "+tmp
elif self.verbose==1:
print "-- Function declaration "+tmp
def get_functions(self,name,quiet=False):
if name == "::":
name = ""
scope = self.index[name]
fns=scope.function
for key in scope.base_classes:
cname = self.find_class(key,scope)
if cname is None:
if not quiet:
print "Defined classes: ",list(self.index.keys())
print "WARNING: Unknown class "+key
else:
fns += self.get_functions(cname,quiet)
return fns
def find_class(self,name,scope):
if ':' in name:
if name in self.index:
return name
else:
return None
tmp = scope.abs_name.split(':')
name1 = ":".join(tmp[:-1] + [name])
if name1 in self.index:
return name1
name2 = "::"+name
if name2 in self.index:
return name2
return None
def __repr__(self):
return str(self)
def is_baseclass(self,cls,base):
'''Returns true if base is a base-class of cls'''
if cls in self.index:
bases = self.index[cls]
elif "::"+cls in self.index:
bases = self.index["::"+cls]
else:
return False
#raise IOError, "Unknown class "+cls
if base in bases.base_classes:
return True
for name in bases.base_classes:
if self.is_baseclass(name,base):
return True
return False
def __str__(self):
ans=""
keys = list(self.index.keys())
keys.sort()
for key in keys:
scope = self.index[key]
ans += scope.scope_t+" "+scope.abs_name+"\n"
if scope.scope_t == "class":
ans += " Base Classes: "+str(scope.base_classes)+"\n"
for fn in self.get_functions(scope.abs_name):
ans += " "+fn+"\n"
else:
for fn in scope.function:
ans += " "+fn+"\n"
return ans
def flatten(x):
"""Flatten nested list"""
try:
strtypes = basestring
except: # for python3 etc
strtypes = (str, bytes)
result = []
for el in x:
if hasattr(el, "__iter__") and not isinstance(el, strtypes):
result.extend(flatten(el))
else:
result.append(el)
return result
#
# The lexer (and/or a preprocessor) is expected to identify the following
#
# Punctuation:
#
#
literals = "+-*/%^&|~!<>=:()?.\'\"\\@$;,"
#
reserved = {
'private' : 'PRIVATE',
'protected' : 'PROTECTED',
'public' : 'PUBLIC',
'bool' : 'BOOL',
'char' : 'CHAR',
'double' : 'DOUBLE',
'float' : 'FLOAT',
'int' : 'INT',
'long' : 'LONG',
'short' : 'SHORT',
'signed' : 'SIGNED',
'unsigned' : 'UNSIGNED',
'void' : 'VOID',
'wchar_t' : 'WCHAR_T',
'class' : 'CLASS',
'enum' : 'ENUM',
'namespace' : 'NAMESPACE',
'struct' : 'STRUCT',
'typename' : 'TYPENAME',
'union' : 'UNION',
'const' : 'CONST',
'volatile' : 'VOLATILE',
'auto' : 'AUTO',
'explicit' : 'EXPLICIT',
'export' : 'EXPORT',
'extern' : 'EXTERN',
'__extension__' : 'EXTENSION',
'friend' : 'FRIEND',
'inline' : 'INLINE',
'mutable' : 'MUTABLE',
'register' : 'REGISTER',
'static' : 'STATIC',
'template' : 'TEMPLATE',
'typedef' : 'TYPEDEF',
'using' : 'USING',
'virtual' : 'VIRTUAL',
'asm' : 'ASM',
'break' : 'BREAK',
'case' : 'CASE',
'catch' : 'CATCH',
'const_cast' : 'CONST_CAST',
'continue' : 'CONTINUE',
'default' : 'DEFAULT',
'delete' : 'DELETE',
'do' : 'DO',
'dynamic_cast' : 'DYNAMIC_CAST',
'else' : 'ELSE',
'false' : 'FALSE',
'for' : 'FOR',
'goto' : 'GOTO',
'if' : 'IF',
'new' : 'NEW',
'operator' : 'OPERATOR',
'reinterpret_cast' : 'REINTERPRET_CAST',
'return' : 'RETURN',
'sizeof' : 'SIZEOF',
'static_cast' : 'STATIC_CAST',
'switch' : 'SWITCH',
'this' : 'THIS',
'throw' : 'THROW',
'true' : 'TRUE',
'try' : 'TRY',
'typeid' : 'TYPEID',
'while' : 'WHILE',
'"C"' : 'CLiteral',
'"C++"' : 'CppLiteral',
'__attribute__' : 'ATTRIBUTE',
'__cdecl__' : 'CDECL',
'__typeof' : 'uTYPEOF',
'typeof' : 'TYPEOF',
'CXXTEST_STD' : 'CXXTEST_STD'
}
tokens = [
"CharacterLiteral",
"FloatingLiteral",
"Identifier",
"IntegerLiteral",
"StringLiteral",
"RBRACE",
"LBRACE",
"RBRACKET",
"LBRACKET",
"ARROW",
"ARROW_STAR",
"DEC",
"EQ",
"GE",
"INC",
"LE",
"LOG_AND",
"LOG_OR",
"NE",
"SHL",
"SHR",
"ASS_ADD",
"ASS_AND",
"ASS_DIV",
"ASS_MOD",
"ASS_MUL",
"ASS_OR",
"ASS_SHL",
"ASS_SHR",
"ASS_SUB",
"ASS_XOR",
"DOT_STAR",
"ELLIPSIS",
"SCOPE",
] + list(reserved.values())
t_ignore = " \t\r"
t_LBRACE = r"(\{)|(<%)"
t_RBRACE = r"(\})|(%>)"
t_LBRACKET = r"(\[)|(<:)"
t_RBRACKET = r"(\])|(:>)"
t_ARROW = r"->"
t_ARROW_STAR = r"->\*"
t_DEC = r"--"
t_EQ = r"=="
t_GE = r">="
t_INC = r"\+\+"
t_LE = r"<="
t_LOG_AND = r"&&"
t_LOG_OR = r"\|\|"
t_NE = r"!="
t_SHL = r"<<"
t_SHR = r">>"
t_ASS_ADD = r"\+="
t_ASS_AND = r"&="
t_ASS_DIV = r"/="
t_ASS_MOD = r"%="
t_ASS_MUL = r"\*="
t_ASS_OR = r"\|="
t_ASS_SHL = r"<<="
t_ASS_SHR = r">>="
t_ASS_SUB = r"-="
t_ASS_XOR = r"^="
t_DOT_STAR = r"\.\*"
t_ELLIPSIS = r"\.\.\."
t_SCOPE = r"::"
# Discard comments
def t_COMMENT(t):
r'(/\*(.|\n)*?\*/)|(//.*?\n)|(\#.*?\n)'
t.lexer.lineno += t.value.count("\n")
t_IntegerLiteral = r'(0x[0-9A-F]+)|([0-9]+(L){0,1})'
t_FloatingLiteral = r"[0-9]+[eE\.\+-]+[eE\.\+\-0-9]+"
t_CharacterLiteral = r'\'([^\'\\]|\\.)*\''
#t_StringLiteral = r'"([^"\\]|\\.)*"'
def t_StringLiteral(t):
r'"([^"\\]|\\.)*"'
t.type = reserved.get(t.value,'StringLiteral')
return t
def t_Identifier(t):
r"[a-zA-Z_][a-zA-Z_0-9\.]*"
t.type = reserved.get(t.value,'Identifier')
return t
def t_error(t):
print "Illegal character '%s'" % t.value[0]
#raise IOError, "Parse error"
#t.lexer.skip()
def t_newline(t):
r'[\n]+'
t.lexer.lineno += len(t.value)
precedence = (
( 'right', 'SHIFT_THERE', 'REDUCE_HERE_MOSTLY', 'SCOPE'),
( 'nonassoc', 'ELSE', 'INC', 'DEC', '+', '-', '*', '&', 'LBRACKET', 'LBRACE', '<', ':', ')')
)
start = 'translation_unit'
#
# The %prec resolves the 14.2-3 ambiguity:
# Identifier '<' is forced to go through the is-it-a-template-name test
# All names absorb TEMPLATE with the name, so that no template_test is
# performed for them. This requires all potential declarations within an
# expression to perpetuate this policy and thereby guarantee the ultimate
# coverage of explicit_instantiation.
#
# The %prec also resolves a conflict in identifier : which is forced to be a
# shift of a label for a labeled-statement rather than a reduction for the
# name of a bit-field or generalised constructor. This is pretty dubious
# syntactically but correct for all semantic possibilities. The shift is
# only activated when the ambiguity exists at the start of a statement.
# In this context a bit-field declaration or constructor definition are not
# allowed.
#
def p_identifier(p):
'''identifier : Identifier
| CXXTEST_STD '(' Identifier ')'
'''
if p[1][0] in ('t','T','c','d'):
identifier_lineno[p[1]] = p.lineno(1)
p[0] = p[1]
def p_id(p):
'''id : identifier %prec SHIFT_THERE
| template_decl
| TEMPLATE id
'''
p[0] = get_rest(p)
def p_global_scope(p):
'''global_scope : SCOPE
'''
p[0] = get_rest(p)
def p_id_scope(p):
'''id_scope : id SCOPE'''
p[0] = get_rest(p)
def p_id_scope_seq(p):
'''id_scope_seq : id_scope
| id_scope id_scope_seq
'''
p[0] = get_rest(p)
#
# A :: B :: C; is ambiguous How much is type and how much name ?
# The %prec maximises the (type) length which is the 7.1-2 semantic constraint.
#
def p_nested_id(p):
'''nested_id : id %prec SHIFT_THERE
| id_scope nested_id
'''
p[0] = get_rest(p)
def p_scoped_id(p):
'''scoped_id : nested_id
| global_scope nested_id
| id_scope_seq
| global_scope id_scope_seq
'''
global scope_lineno
scope_lineno = lexer.lineno
data = flatten(get_rest(p))
if data[0] != None:
p[0] = "".join(data)
#
# destructor_id has to be held back to avoid a conflict with a one's
# complement as per 5.3.1-9, It gets put back only when scoped or in a
# declarator_id, which is only used as an explicit member name.
# Declarations of an unscoped destructor are always parsed as a one's
# complement.
#
def p_destructor_id(p):
'''destructor_id : '~' id
| TEMPLATE destructor_id
'''
p[0]=get_rest(p)
#def p_template_id(p):
# '''template_id : empty
# | TEMPLATE
# '''
# pass
def p_template_decl(p):
'''template_decl : identifier '<' nonlgt_seq_opt '>'
'''
#
# WEH: should we include the lt/gt symbols to indicate that this is a
# template class? How is that going to be used later???
#
#p[0] = [p[1] ,"<",">"]
p[0] = p[1]
def p_special_function_id(p):
'''special_function_id : conversion_function_id
| operator_function_id
| TEMPLATE special_function_id
'''
p[0]=get_rest(p)
def p_nested_special_function_id(p):
'''nested_special_function_id : special_function_id
| id_scope destructor_id
| id_scope nested_special_function_id
'''
p[0]=get_rest(p)
def p_scoped_special_function_id(p):
'''scoped_special_function_id : nested_special_function_id
| global_scope nested_special_function_id
'''
p[0]=get_rest(p)
# declarator-id is all names in all scopes, except reserved words
def p_declarator_id(p):
'''declarator_id : scoped_id
| scoped_special_function_id
| destructor_id
'''
p[0]=p[1]
#
# The standard defines pseudo-destructors in terms of type-name, which is
# class/enum/typedef, of which class-name is covered by a normal destructor.
# pseudo-destructors are supposed to support ~int() in templates, so the
# grammar here covers built-in names. Other names are covered by the lack
# of identifier/type discrimination.
#
def p_built_in_type_id(p):
'''built_in_type_id : built_in_type_specifier
| built_in_type_id built_in_type_specifier
'''
pass
def p_pseudo_destructor_id(p):
'''pseudo_destructor_id : built_in_type_id SCOPE '~' built_in_type_id
| '~' built_in_type_id
| TEMPLATE pseudo_destructor_id
'''
pass
def p_nested_pseudo_destructor_id(p):
'''nested_pseudo_destructor_id : pseudo_destructor_id
| id_scope nested_pseudo_destructor_id
'''
pass
def p_scoped_pseudo_destructor_id(p):
'''scoped_pseudo_destructor_id : nested_pseudo_destructor_id
| global_scope scoped_pseudo_destructor_id
'''
pass
#-------------------------------------------------------------------------------
# A.2 Lexical conventions
#-------------------------------------------------------------------------------
#
def p_literal(p):
'''literal : IntegerLiteral
| CharacterLiteral
| FloatingLiteral
| StringLiteral
| TRUE
| FALSE
'''
pass
#-------------------------------------------------------------------------------
# A.3 Basic concepts
#-------------------------------------------------------------------------------
def p_translation_unit(p):
'''translation_unit : declaration_seq_opt
'''
pass
#-------------------------------------------------------------------------------
# A.4 Expressions
#-------------------------------------------------------------------------------
#
# primary_expression covers an arbitrary sequence of all names with the
# exception of an unscoped destructor, which is parsed as its unary expression
# which is the correct disambiguation (when ambiguous). This eliminates the
# traditional A(B) meaning A B ambiguity, since we never have to tack an A
# onto the front of something that might start with (. The name length got
# maximised ab initio. The downside is that semantic interpretation must split
# the names up again.
#
# Unification of the declaration and expression syntax means that unary and
# binary pointer declarator operators:
# int * * name
# are parsed as binary and unary arithmetic operators (int) * (*name). Since
# type information is not used
# ambiguities resulting from a cast
# (cast)*(value)
# are resolved to favour the binary rather than the cast unary to ease AST
# clean-up. The cast-call ambiguity must be resolved to the cast to ensure
# that (a)(b)c can be parsed.
#
# The problem of the functional cast ambiguity
# name(arg)
# as call or declaration is avoided by maximising the name within the parsing
# kernel. So primary_id_expression picks up
# extern long int const var = 5;
# as an assignment to the syntax parsed as "extern long int const var". The
# presence of two names is parsed so that "extern long into const" is
# distinguished from "var" considerably simplifying subsequent
# semantic resolution.
#
# The generalised name is a concatenation of potential type-names (scoped
# identifiers or built-in sequences) plus optionally one of the special names
# such as an operator-function-id, conversion-function-id or destructor as the
# final name.
#
def get_rest(p):
return [p[i] for i in range(1, len(p))]
def p_primary_expression(p):
'''primary_expression : literal
| THIS
| suffix_decl_specified_ids
| abstract_expression %prec REDUCE_HERE_MOSTLY
'''
p[0] = get_rest(p)
#
# Abstract-expression covers the () and [] of abstract-declarators.
#
def p_abstract_expression(p):
'''abstract_expression : parenthesis_clause
| LBRACKET bexpression_opt RBRACKET
| TEMPLATE abstract_expression
'''
pass
def p_postfix_expression(p):
'''postfix_expression : primary_expression
| postfix_expression parenthesis_clause
| postfix_expression LBRACKET bexpression_opt RBRACKET
| postfix_expression LBRACKET bexpression_opt RBRACKET attributes
| postfix_expression '.' declarator_id
| postfix_expression '.' scoped_pseudo_destructor_id
| postfix_expression ARROW declarator_id
| postfix_expression ARROW scoped_pseudo_destructor_id
| postfix_expression INC
| postfix_expression DEC
| DYNAMIC_CAST '<' nonlgt_seq_opt '>' '(' expression ')'
| STATIC_CAST '<' nonlgt_seq_opt '>' '(' expression ')'
| REINTERPRET_CAST '<' nonlgt_seq_opt '>' '(' expression ')'
| CONST_CAST '<' nonlgt_seq_opt '>' '(' expression ')'
| TYPEID parameters_clause
'''
#print "HERE",str(p[1])
p[0] = get_rest(p)
def p_bexpression_opt(p):
'''bexpression_opt : empty
| bexpression
'''
pass
def p_bexpression(p):
'''bexpression : nonbracket_seq
| nonbracket_seq bexpression_seq bexpression_clause nonbracket_seq_opt
| bexpression_seq bexpression_clause nonbracket_seq_opt
'''
pass
def p_bexpression_seq(p):
'''bexpression_seq : empty
| bexpression_seq bexpression_clause nonbracket_seq_opt
'''
pass
def p_bexpression_clause(p):
'''bexpression_clause : LBRACKET bexpression_opt RBRACKET
'''
pass
def p_expression_list_opt(p):
'''expression_list_opt : empty
| expression_list
'''
pass
def p_expression_list(p):
'''expression_list : assignment_expression
| expression_list ',' assignment_expression
'''
pass
def p_unary_expression(p):
'''unary_expression : postfix_expression
| INC cast_expression
| DEC cast_expression
| ptr_operator cast_expression
| suffix_decl_specified_scope star_ptr_operator cast_expression
| '+' cast_expression
| '-' cast_expression
| '!' cast_expression
| '~' cast_expression
| SIZEOF unary_expression
| new_expression
| global_scope new_expression
| delete_expression
| global_scope delete_expression
'''
p[0] = get_rest(p)
def p_delete_expression(p):
'''delete_expression : DELETE cast_expression
'''
pass
def p_new_expression(p):
'''new_expression : NEW new_type_id new_initializer_opt
| NEW parameters_clause new_type_id new_initializer_opt
| NEW parameters_clause
| NEW parameters_clause parameters_clause new_initializer_opt
'''
pass
def p_new_type_id(p):
'''new_type_id : type_specifier ptr_operator_seq_opt
| type_specifier new_declarator
| type_specifier new_type_id
'''
pass
def p_new_declarator(p):
'''new_declarator : ptr_operator new_declarator
| direct_new_declarator
'''
pass
def p_direct_new_declarator(p):
'''direct_new_declarator : LBRACKET bexpression_opt RBRACKET
| direct_new_declarator LBRACKET bexpression RBRACKET
'''
pass
def p_new_initializer_opt(p):
'''new_initializer_opt : empty
| '(' expression_list_opt ')'
'''
pass
#
# cast-expression is generalised to support a [] as well as a () prefix. This covers the omission of
# DELETE[] which when followed by a parenthesised expression was ambiguous. It also covers the gcc
# indexed array initialisation for free.
#
def p_cast_expression(p):
'''cast_expression : unary_expression
| abstract_expression cast_expression
'''
p[0] = get_rest(p)
def p_pm_expression(p):
'''pm_expression : cast_expression
| pm_expression DOT_STAR cast_expression
| pm_expression ARROW_STAR cast_expression
'''
p[0] = get_rest(p)
def p_multiplicative_expression(p):
'''multiplicative_expression : pm_expression
| multiplicative_expression star_ptr_operator pm_expression
| multiplicative_expression '/' pm_expression
| multiplicative_expression '%' pm_expression
'''
p[0] = get_rest(p)
def p_additive_expression(p):
'''additive_expression : multiplicative_expression
| additive_expression '+' multiplicative_expression
| additive_expression '-' multiplicative_expression
'''
p[0] = get_rest(p)
def p_shift_expression(p):
'''shift_expression : additive_expression
| shift_expression SHL additive_expression
| shift_expression SHR additive_expression
'''
p[0] = get_rest(p)
# | relational_expression '<' shift_expression
# | relational_expression '>' shift_expression
# | relational_expression LE shift_expression
# | relational_expression GE shift_expression
def p_relational_expression(p):
'''relational_expression : shift_expression
'''
p[0] = get_rest(p)
def p_equality_expression(p):
'''equality_expression : relational_expression
| equality_expression EQ relational_expression
| equality_expression NE relational_expression
'''
p[0] = get_rest(p)
def p_and_expression(p):
'''and_expression : equality_expression
| and_expression '&' equality_expression
'''
p[0] = get_rest(p)
def p_exclusive_or_expression(p):
'''exclusive_or_expression : and_expression
| exclusive_or_expression '^' and_expression
'''
p[0] = get_rest(p)
def p_inclusive_or_expression(p):
'''inclusive_or_expression : exclusive_or_expression
| inclusive_or_expression '|' exclusive_or_expression
'''
p[0] = get_rest(p)
def p_logical_and_expression(p):
'''logical_and_expression : inclusive_or_expression
| logical_and_expression LOG_AND inclusive_or_expression
'''
p[0] = get_rest(p)
def p_logical_or_expression(p):
'''logical_or_expression : logical_and_expression
| logical_or_expression LOG_OR logical_and_expression
'''
p[0] = get_rest(p)
def p_conditional_expression(p):
'''conditional_expression : logical_or_expression
| logical_or_expression '?' expression ':' assignment_expression
'''
p[0] = get_rest(p)
#
# assignment-expression is generalised to cover the simple assignment of a braced initializer in order to
# contribute to the coverage of parameter-declaration and init-declaration.
#
# | logical_or_expression assignment_operator assignment_expression
def p_assignment_expression(p):
'''assignment_expression : conditional_expression
| logical_or_expression assignment_operator nonsemicolon_seq
| logical_or_expression '=' braced_initializer
| throw_expression
'''
p[0]=get_rest(p)
def p_assignment_operator(p):
'''assignment_operator : '='
| ASS_ADD
| ASS_AND
| ASS_DIV
| ASS_MOD
| ASS_MUL
| ASS_OR
| ASS_SHL
| ASS_SHR
| ASS_SUB
| ASS_XOR
'''
pass
#
# expression is widely used and usually single-element, so the reductions are arranged so that a
# single-element expression is returned as is. Multi-element expressions are parsed as a list that
# may then behave polymorphically as an element or be compacted to an element.
#
def p_expression(p):
'''expression : assignment_expression
| expression_list ',' assignment_expression
'''
p[0] = get_rest(p)
def p_constant_expression(p):
'''constant_expression : conditional_expression
'''
pass
#---------------------------------------------------------------------------------------------------
# A.5 Statements
#---------------------------------------------------------------------------------------------------
# Parsing statements is easy once simple_declaration has been generalised to cover expression_statement.
#
#
# The use of extern here is a hack. The 'extern "C" {}' block gets parsed
# as a function, so when nested 'extern "C"' declarations exist, they don't
# work because the block is viewed as a list of statements... :(
#
def p_statement(p):
'''statement : compound_statement
| declaration_statement
| try_block
| labeled_statement
| selection_statement
| iteration_statement
| jump_statement
'''
pass
def p_compound_statement(p):
'''compound_statement : LBRACE statement_seq_opt RBRACE
'''
pass
def p_statement_seq_opt(p):
'''statement_seq_opt : empty
| statement_seq_opt statement
'''
pass
#
# The dangling else conflict is resolved to the innermost if.
#
def p_selection_statement(p):
'''selection_statement : IF '(' condition ')' statement %prec SHIFT_THERE
| IF '(' condition ')' statement ELSE statement
| SWITCH '(' condition ')' statement
'''
pass
def p_condition_opt(p):
'''condition_opt : empty
| condition
'''
pass
def p_condition(p):
'''condition : nonparen_seq
| nonparen_seq condition_seq parameters_clause nonparen_seq_opt
| condition_seq parameters_clause nonparen_seq_opt
'''
pass
def p_condition_seq(p):
'''condition_seq : empty
| condition_seq parameters_clause nonparen_seq_opt
'''
pass
def p_labeled_statement(p):
'''labeled_statement : identifier ':' statement
| CASE constant_expression ':' statement
| DEFAULT ':' statement
'''
pass
def p_try_block(p):
'''try_block : TRY compound_statement handler_seq
'''
global noExceptionLogic
noExceptionLogic=False
def p_jump_statement(p):
'''jump_statement : BREAK ';'
| CONTINUE ';'
| RETURN nonsemicolon_seq ';'
| GOTO identifier ';'
'''
pass
def p_iteration_statement(p):
'''iteration_statement : WHILE '(' condition ')' statement
| DO statement WHILE '(' expression ')' ';'
| FOR '(' nonparen_seq_opt ')' statement
'''
pass
def p_declaration_statement(p):
'''declaration_statement : block_declaration
'''
pass
#---------------------------------------------------------------------------------------------------
# A.6 Declarations
#---------------------------------------------------------------------------------------------------
def p_compound_declaration(p):
'''compound_declaration : LBRACE declaration_seq_opt RBRACE
'''
pass
def p_declaration_seq_opt(p):
'''declaration_seq_opt : empty
| declaration_seq_opt declaration
'''
pass
def p_declaration(p):
'''declaration : block_declaration
| function_definition
| template_declaration
| explicit_specialization
| specialised_declaration
'''
pass
def p_specialised_declaration(p):
'''specialised_declaration : linkage_specification
| namespace_definition
| TEMPLATE specialised_declaration
'''
pass
def p_block_declaration(p):
'''block_declaration : simple_declaration
| specialised_block_declaration
'''
pass
def p_specialised_block_declaration(p):
'''specialised_block_declaration : asm_definition
| namespace_alias_definition
| using_declaration
| using_directive
| TEMPLATE specialised_block_declaration
'''
pass
def p_simple_declaration(p):
'''simple_declaration : ';'
| init_declaration ';'
| init_declarations ';'
| decl_specifier_prefix simple_declaration
'''
global _parse_info
if len(p) == 3:
if p[2] == ";":
decl = p[1]
else:
decl = p[2]
if decl is not None:
fp = flatten(decl)
if len(fp) >= 2 and fp[0] is not None and fp[0]!="operator" and fp[1] == '(':
p[0] = fp[0]
_parse_info.add_function(fp[0])
#
# A decl-specifier following a ptr_operator provokes a shift-reduce conflict for * const name which is resolved in favour of the pointer, and implemented by providing versions of decl-specifier guaranteed not to start with a cv_qualifier. decl-specifiers are implemented type-centrically. That is the semantic constraint that there must be a type is exploited to impose structure, but actually eliminate very little syntax. built-in types are multi-name and so need a different policy.
#
# non-type decl-specifiers are bound to the left-most type in a decl-specifier-seq, by parsing from the right and attaching suffixes to the right-hand type. Finally residual prefixes attach to the left.
#
def p_suffix_built_in_decl_specifier_raw(p):
'''suffix_built_in_decl_specifier_raw : built_in_type_specifier
| suffix_built_in_decl_specifier_raw built_in_type_specifier
| suffix_built_in_decl_specifier_raw decl_specifier_suffix
'''
pass
def p_suffix_built_in_decl_specifier(p):
'''suffix_built_in_decl_specifier : suffix_built_in_decl_specifier_raw
| TEMPLATE suffix_built_in_decl_specifier
'''
pass
# | id_scope_seq
# | SCOPE id_scope_seq
def p_suffix_named_decl_specifier(p):
'''suffix_named_decl_specifier : scoped_id
| elaborate_type_specifier
| suffix_named_decl_specifier decl_specifier_suffix
'''
p[0]=get_rest(p)
def p_suffix_named_decl_specifier_bi(p):
'''suffix_named_decl_specifier_bi : suffix_named_decl_specifier
| suffix_named_decl_specifier suffix_built_in_decl_specifier_raw
'''
p[0] = get_rest(p)
#print "HERE",get_rest(p)
def p_suffix_named_decl_specifiers(p):
'''suffix_named_decl_specifiers : suffix_named_decl_specifier_bi
| suffix_named_decl_specifiers suffix_named_decl_specifier_bi
'''
p[0] = get_rest(p)
def p_suffix_named_decl_specifiers_sf(p):
'''suffix_named_decl_specifiers_sf : scoped_special_function_id
| suffix_named_decl_specifiers
| suffix_named_decl_specifiers scoped_special_function_id
'''
#print "HERE",get_rest(p)
p[0] = get_rest(p)
def p_suffix_decl_specified_ids(p):
'''suffix_decl_specified_ids : suffix_built_in_decl_specifier
| suffix_built_in_decl_specifier suffix_named_decl_specifiers_sf
| suffix_named_decl_specifiers_sf
'''
if len(p) == 3:
p[0] = p[2]
else:
p[0] = p[1]
def p_suffix_decl_specified_scope(p):
'''suffix_decl_specified_scope : suffix_named_decl_specifiers SCOPE
| suffix_built_in_decl_specifier suffix_named_decl_specifiers SCOPE
| suffix_built_in_decl_specifier SCOPE
'''
p[0] = get_rest(p)
def p_decl_specifier_affix(p):
'''decl_specifier_affix : storage_class_specifier
| function_specifier
| FRIEND
| TYPEDEF
| cv_qualifier
'''
pass
def p_decl_specifier_suffix(p):
'''decl_specifier_suffix : decl_specifier_affix
'''
pass
def p_decl_specifier_prefix(p):
'''decl_specifier_prefix : decl_specifier_affix
| TEMPLATE decl_specifier_prefix
'''
pass
def p_storage_class_specifier(p):
'''storage_class_specifier : REGISTER
| STATIC
| MUTABLE
| EXTERN %prec SHIFT_THERE
| EXTENSION
| AUTO
'''
pass
def p_function_specifier(p):
'''function_specifier : EXPLICIT
| INLINE
| VIRTUAL
'''
pass
def p_type_specifier(p):
'''type_specifier : simple_type_specifier
| elaborate_type_specifier
| cv_qualifier
'''
pass
def p_elaborate_type_specifier(p):
'''elaborate_type_specifier : class_specifier
| enum_specifier
| elaborated_type_specifier
| TEMPLATE elaborate_type_specifier
'''
pass
def p_simple_type_specifier(p):
'''simple_type_specifier : scoped_id
| scoped_id attributes
| built_in_type_specifier
'''
p[0] = p[1]
def p_built_in_type_specifier(p):
'''built_in_type_specifier : Xbuilt_in_type_specifier
| Xbuilt_in_type_specifier attributes
'''
pass
def p_attributes(p):
'''attributes : attribute
| attributes attribute
'''
pass
def p_attribute(p):
'''attribute : ATTRIBUTE '(' parameters_clause ')'
'''
def p_Xbuilt_in_type_specifier(p):
'''Xbuilt_in_type_specifier : CHAR
| WCHAR_T
| BOOL
| SHORT
| INT
| LONG
| SIGNED
| UNSIGNED
| FLOAT
| DOUBLE
| VOID
| uTYPEOF parameters_clause
| TYPEOF parameters_clause
'''
pass
#
# The over-general use of declaration_expression to cover decl-specifier-seq_opt declarator in a function-definition means that
# class X { };
# could be a function-definition or a class-specifier.
# enum X { };
# could be a function-definition or an enum-specifier.
# The function-definition is not syntactically valid so resolving the false conflict in favour of the
# elaborated_type_specifier is correct.
#
def p_elaborated_type_specifier(p):
'''elaborated_type_specifier : class_key scoped_id %prec SHIFT_THERE
| elaborated_enum_specifier
| TYPENAME scoped_id
'''
pass
def p_elaborated_enum_specifier(p):
'''elaborated_enum_specifier : ENUM scoped_id %prec SHIFT_THERE
'''
pass
def p_enum_specifier(p):
'''enum_specifier : ENUM scoped_id enumerator_clause
| ENUM enumerator_clause
'''
pass
def p_enumerator_clause(p):
'''enumerator_clause : LBRACE enumerator_list_ecarb
| LBRACE enumerator_list enumerator_list_ecarb
| LBRACE enumerator_list ',' enumerator_definition_ecarb
'''
pass
def p_enumerator_list_ecarb(p):
'''enumerator_list_ecarb : RBRACE
'''
pass
def p_enumerator_definition_ecarb(p):
'''enumerator_definition_ecarb : RBRACE
'''
pass
def p_enumerator_definition_filler(p):
'''enumerator_definition_filler : empty
'''
pass
def p_enumerator_list_head(p):
'''enumerator_list_head : enumerator_definition_filler
| enumerator_list ',' enumerator_definition_filler
'''
pass
def p_enumerator_list(p):
'''enumerator_list : enumerator_list_head enumerator_definition
'''
pass
def p_enumerator_definition(p):
'''enumerator_definition : enumerator
| enumerator '=' constant_expression
'''
pass
def p_enumerator(p):
'''enumerator : identifier
'''
pass
def p_namespace_definition(p):
'''namespace_definition : NAMESPACE scoped_id push_scope compound_declaration
| NAMESPACE push_scope compound_declaration
'''
global _parse_info
scope = _parse_info.pop_scope()
def p_namespace_alias_definition(p):
'''namespace_alias_definition : NAMESPACE scoped_id '=' scoped_id ';'
'''
pass
def p_push_scope(p):
'''push_scope : empty'''
global _parse_info
if p[-2] == "namespace":
scope=p[-1]
else:
scope=""
_parse_info.push_scope(scope,"namespace")
def p_using_declaration(p):
'''using_declaration : USING declarator_id ';'
| USING TYPENAME declarator_id ';'
'''
pass
def p_using_directive(p):
'''using_directive : USING NAMESPACE scoped_id ';'
'''
pass
# '''asm_definition : ASM '(' StringLiteral ')' ';'
def p_asm_definition(p):
'''asm_definition : ASM '(' nonparen_seq_opt ')' ';'
'''
pass
def p_linkage_specification(p):
'''linkage_specification : EXTERN CLiteral declaration
| EXTERN CLiteral compound_declaration
| EXTERN CppLiteral declaration
| EXTERN CppLiteral compound_declaration
'''
pass
#---------------------------------------------------------------------------------------------------
# A.7 Declarators
#---------------------------------------------------------------------------------------------------
#
# init-declarator is named init_declaration to reflect the embedded decl-specifier-seq_opt
#
def p_init_declarations(p):
'''init_declarations : assignment_expression ',' init_declaration
| init_declarations ',' init_declaration
'''
p[0]=get_rest(p)
def p_init_declaration(p):
'''init_declaration : assignment_expression
'''
p[0]=get_rest(p)
def p_star_ptr_operator(p):
'''star_ptr_operator : '*'
| star_ptr_operator cv_qualifier
'''
pass
def p_nested_ptr_operator(p):
'''nested_ptr_operator : star_ptr_operator
| id_scope nested_ptr_operator
'''
pass
def p_ptr_operator(p):
'''ptr_operator : '&'
| nested_ptr_operator
| global_scope nested_ptr_operator
'''
pass
def p_ptr_operator_seq(p):
'''ptr_operator_seq : ptr_operator
| ptr_operator ptr_operator_seq
'''
pass
#
# Independently coded to localise the shift-reduce conflict: sharing just needs another %prec
#
def p_ptr_operator_seq_opt(p):
'''ptr_operator_seq_opt : empty %prec SHIFT_THERE
| ptr_operator ptr_operator_seq_opt
'''
pass
def p_cv_qualifier_seq_opt(p):
'''cv_qualifier_seq_opt : empty
| cv_qualifier_seq_opt cv_qualifier
'''
pass
# TODO: verify that we should include attributes here
def p_cv_qualifier(p):
'''cv_qualifier : CONST
| VOLATILE
| attributes
'''
pass
def p_type_id(p):
'''type_id : type_specifier abstract_declarator_opt
| type_specifier type_id
'''
pass
def p_abstract_declarator_opt(p):
'''abstract_declarator_opt : empty
| ptr_operator abstract_declarator_opt
| direct_abstract_declarator
'''
pass
def p_direct_abstract_declarator_opt(p):
'''direct_abstract_declarator_opt : empty
| direct_abstract_declarator
'''
pass
def p_direct_abstract_declarator(p):
'''direct_abstract_declarator : direct_abstract_declarator_opt parenthesis_clause
| direct_abstract_declarator_opt LBRACKET RBRACKET
| direct_abstract_declarator_opt LBRACKET bexpression RBRACKET
'''
pass
def p_parenthesis_clause(p):
'''parenthesis_clause : parameters_clause cv_qualifier_seq_opt
| parameters_clause cv_qualifier_seq_opt exception_specification
'''
p[0] = ['(',')']
def p_parameters_clause(p):
'''parameters_clause : '(' condition_opt ')'
'''
p[0] = ['(',')']
#
# A typed abstract qualifier such as
# Class * ...
# looks like a multiply, so pointers are parsed as their binary operation equivalents that
# ultimately terminate with a degenerate right hand term.
#
def p_abstract_pointer_declaration(p):
'''abstract_pointer_declaration : ptr_operator_seq
| multiplicative_expression star_ptr_operator ptr_operator_seq_opt
'''
pass
def p_abstract_parameter_declaration(p):
'''abstract_parameter_declaration : abstract_pointer_declaration
| and_expression '&'
| and_expression '&' abstract_pointer_declaration
'''
pass
def p_special_parameter_declaration(p):
'''special_parameter_declaration : abstract_parameter_declaration
| abstract_parameter_declaration '=' assignment_expression
| ELLIPSIS
'''
pass
def p_parameter_declaration(p):
'''parameter_declaration : assignment_expression
| special_parameter_declaration
| decl_specifier_prefix parameter_declaration
'''
pass
#
# function_definition includes constructor, destructor, implicit int definitions too. A local destructor is successfully parsed as a function-declaration but the ~ was treated as a unary operator. constructor_head is the prefix ambiguity between a constructor and a member-init-list starting with a bit-field.
#
def p_function_definition(p):
'''function_definition : ctor_definition
| func_definition
'''
pass
def p_func_definition(p):
'''func_definition : assignment_expression function_try_block
| assignment_expression function_body
| decl_specifier_prefix func_definition
'''
global _parse_info
if p[2] is not None and p[2][0] == '{':
decl = flatten(p[1])
#print "HERE",decl
if decl[-1] == ')':
decl=decl[-3]
else:
decl=decl[-1]
p[0] = decl
if decl != "operator":
_parse_info.add_function(decl)
else:
p[0] = p[2]
def p_ctor_definition(p):
'''ctor_definition : constructor_head function_try_block
| constructor_head function_body
| decl_specifier_prefix ctor_definition
'''
if p[2] is None or p[2][0] == "try" or p[2][0] == '{':
p[0]=p[1]
else:
p[0]=p[1]
def p_constructor_head(p):
'''constructor_head : bit_field_init_declaration
| constructor_head ',' assignment_expression
'''
p[0]=p[1]
def p_function_try_block(p):
'''function_try_block : TRY function_block handler_seq
'''
global noExceptionLogic
noExceptionLogic=False
p[0] = ['try']
def p_function_block(p):
'''function_block : ctor_initializer_opt function_body
'''
pass
def p_function_body(p):
'''function_body : LBRACE nonbrace_seq_opt RBRACE
'''
p[0] = ['{','}']
def p_initializer_clause(p):
'''initializer_clause : assignment_expression
| braced_initializer
'''
pass
def p_braced_initializer(p):
'''braced_initializer : LBRACE initializer_list RBRACE
| LBRACE initializer_list ',' RBRACE
| LBRACE RBRACE
'''
pass
def p_initializer_list(p):
'''initializer_list : initializer_clause
| initializer_list ',' initializer_clause
'''
pass
#---------------------------------------------------------------------------------------------------
# A.8 Classes
#---------------------------------------------------------------------------------------------------
#
# An anonymous bit-field declaration may look very like inheritance:
# const int B = 3;
# class A : B ;
# The two usages are too distant to try to create and enforce a common prefix so we have to resort to
# a parser hack by backtracking. Inheritance is much the most likely so we mark the input stream context
# and try to parse a base-clause. If we successfully reach a { the base-clause is ok and inheritance was
# the correct choice so we unmark and continue. If we fail to find the { an error token causes
# back-tracking to the alternative parse in elaborated_type_specifier which regenerates the : and
# declares unconditional success.
#
def p_class_specifier_head(p):
'''class_specifier_head : class_key scoped_id ':' base_specifier_list LBRACE
| class_key ':' base_specifier_list LBRACE
| class_key scoped_id LBRACE
| class_key LBRACE
'''
global _parse_info
base_classes=[]
if len(p) == 6:
scope = p[2]
base_classes = p[4]
elif len(p) == 4:
scope = p[2]
elif len(p) == 5:
base_classes = p[3]
else:
scope = ""
_parse_info.push_scope(scope,p[1],base_classes)
def p_class_key(p):
'''class_key : CLASS
| STRUCT
| UNION
'''
p[0] = p[1]
def p_class_specifier(p):
'''class_specifier : class_specifier_head member_specification_opt RBRACE
'''
scope = _parse_info.pop_scope()
def p_member_specification_opt(p):
'''member_specification_opt : empty
| member_specification_opt member_declaration
'''
pass
def p_member_declaration(p):
'''member_declaration : accessibility_specifier
| simple_member_declaration
| function_definition
| using_declaration
| template_declaration
'''
p[0] = get_rest(p)
#print "Decl",get_rest(p)
#
# The generality of constructor names (there need be no parenthesised argument list) means that that
# name : f(g), h(i)
# could be the start of a constructor or the start of an anonymous bit-field. An ambiguity is avoided by
# parsing the ctor-initializer of a function_definition as a bit-field.
#
def p_simple_member_declaration(p):
'''simple_member_declaration : ';'
| assignment_expression ';'
| constructor_head ';'
| member_init_declarations ';'
| decl_specifier_prefix simple_member_declaration
'''
global _parse_info
decl = flatten(get_rest(p))
if len(decl) >= 4 and decl[-3] == "(":
_parse_info.add_function(decl[-4])
def p_member_init_declarations(p):
'''member_init_declarations : assignment_expression ',' member_init_declaration
| constructor_head ',' bit_field_init_declaration
| member_init_declarations ',' member_init_declaration
'''
pass
def p_member_init_declaration(p):
'''member_init_declaration : assignment_expression
| bit_field_init_declaration
'''
pass
def p_accessibility_specifier(p):
'''accessibility_specifier : access_specifier ':'
'''
pass
def p_bit_field_declaration(p):
'''bit_field_declaration : assignment_expression ':' bit_field_width
| ':' bit_field_width
'''
if len(p) == 4:
p[0]=p[1]
def p_bit_field_width(p):
'''bit_field_width : logical_or_expression
| logical_or_expression '?' bit_field_width ':' bit_field_width
'''
pass
def p_bit_field_init_declaration(p):
'''bit_field_init_declaration : bit_field_declaration
| bit_field_declaration '=' initializer_clause
'''
pass
#---------------------------------------------------------------------------------------------------
# A.9 Derived classes
#---------------------------------------------------------------------------------------------------
def p_base_specifier_list(p):
'''base_specifier_list : base_specifier
| base_specifier_list ',' base_specifier
'''
if len(p) == 2:
p[0] = [p[1]]
else:
p[0] = p[1]+[p[3]]
def p_base_specifier(p):
'''base_specifier : scoped_id
| access_specifier base_specifier
| VIRTUAL base_specifier
'''
if len(p) == 2:
p[0] = p[1]
else:
p[0] = p[2]
def p_access_specifier(p):
'''access_specifier : PRIVATE
| PROTECTED
| PUBLIC
'''
pass
#---------------------------------------------------------------------------------------------------
# A.10 Special member functions
#---------------------------------------------------------------------------------------------------
def p_conversion_function_id(p):
'''conversion_function_id : OPERATOR conversion_type_id
'''
p[0] = ['operator']
def p_conversion_type_id(p):
'''conversion_type_id : type_specifier ptr_operator_seq_opt
| type_specifier conversion_type_id
'''
pass
#
# Ctor-initialisers can look like a bit field declaration, given the generalisation of names:
# Class(Type) : m1(1), m2(2) { }
# NonClass(bit_field) : int(2), second_variable, ...
# The grammar below is used within a function_try_block or function_definition.
# See simple_member_declaration for use in normal member function_definition.
#
def p_ctor_initializer_opt(p):
'''ctor_initializer_opt : empty
| ctor_initializer
'''
pass
def p_ctor_initializer(p):
'''ctor_initializer : ':' mem_initializer_list
'''
pass
def p_mem_initializer_list(p):
'''mem_initializer_list : mem_initializer
| mem_initializer_list_head mem_initializer
'''
pass
def p_mem_initializer_list_head(p):
'''mem_initializer_list_head : mem_initializer_list ','
'''
pass
def p_mem_initializer(p):
'''mem_initializer : mem_initializer_id '(' expression_list_opt ')'
'''
pass
def p_mem_initializer_id(p):
'''mem_initializer_id : scoped_id
'''
pass
#---------------------------------------------------------------------------------------------------
# A.11 Overloading
#---------------------------------------------------------------------------------------------------
def p_operator_function_id(p):
'''operator_function_id : OPERATOR operator
| OPERATOR '(' ')'
| OPERATOR LBRACKET RBRACKET
| OPERATOR '<'
| OPERATOR '>'
| OPERATOR operator '<' nonlgt_seq_opt '>'
'''
p[0] = ["operator"]
#
# It is not clear from the ANSI standard whether spaces are permitted in delete[]. If not then it can
# be recognised and returned as DELETE_ARRAY by the lexer. Assuming spaces are permitted there is an
# ambiguity created by the over generalised nature of expressions. operator new is a valid delarator-id
# which we may have an undimensioned array of. Semantic rubbish, but syntactically valid. Since the
# array form is covered by the declarator consideration we can exclude the operator here. The need
# for a semantic rescue can be eliminated at the expense of a couple of shift-reduce conflicts by
# removing the comments on the next four lines.
#
def p_operator(p):
'''operator : NEW
| DELETE
| '+'
| '-'
| '*'
| '/'
| '%'
| '^'
| '&'
| '|'
| '~'
| '!'
| '='
| ASS_ADD
| ASS_SUB
| ASS_MUL
| ASS_DIV
| ASS_MOD
| ASS_XOR
| ASS_AND
| ASS_OR
| SHL
| SHR
| ASS_SHR
| ASS_SHL
| EQ
| NE
| LE
| GE
| LOG_AND
| LOG_OR
| INC
| DEC
| ','
| ARROW_STAR
| ARROW
'''
p[0]=p[1]
# | IF
# | SWITCH
# | WHILE
# | FOR
# | DO
def p_reserved(p):
'''reserved : PRIVATE
| CLiteral
| CppLiteral
| IF
| SWITCH
| WHILE
| FOR
| DO
| PROTECTED
| PUBLIC
| BOOL
| CHAR
| DOUBLE
| FLOAT
| INT
| LONG
| SHORT
| SIGNED
| UNSIGNED
| VOID
| WCHAR_T
| CLASS
| ENUM
| NAMESPACE
| STRUCT
| TYPENAME
| UNION
| CONST
| VOLATILE
| AUTO
| EXPLICIT
| EXPORT
| EXTERN
| FRIEND
| INLINE
| MUTABLE
| REGISTER
| STATIC
| TEMPLATE
| TYPEDEF
| USING
| VIRTUAL
| ASM
| BREAK
| CASE
| CATCH
| CONST_CAST
| CONTINUE
| DEFAULT
| DYNAMIC_CAST
| ELSE
| FALSE
| GOTO
| OPERATOR
| REINTERPRET_CAST
| RETURN
| SIZEOF
| STATIC_CAST
| THIS
| THROW
| TRUE
| TRY
| TYPEID
| ATTRIBUTE
| CDECL
| TYPEOF
| uTYPEOF
'''
if p[1] in ('try', 'catch', 'throw'):
global noExceptionLogic
noExceptionLogic=False
#---------------------------------------------------------------------------------------------------
# A.12 Templates
#---------------------------------------------------------------------------------------------------
def p_template_declaration(p):
'''template_declaration : template_parameter_clause declaration
| EXPORT template_declaration
'''
pass
def p_template_parameter_clause(p):
'''template_parameter_clause : TEMPLATE '<' nonlgt_seq_opt '>'
'''
pass
#
# Generalised naming makes identifier a valid declaration, so TEMPLATE identifier is too.
# The TEMPLATE prefix is therefore folded into all names, parenthesis_clause and decl_specifier_prefix.
#
# explicit_instantiation: TEMPLATE declaration
#
def p_explicit_specialization(p):
'''explicit_specialization : TEMPLATE '<' '>' declaration
'''
pass
#---------------------------------------------------------------------------------------------------
# A.13 Exception Handling
#---------------------------------------------------------------------------------------------------
def p_handler_seq(p):
'''handler_seq : handler
| handler handler_seq
'''
pass
def p_handler(p):
'''handler : CATCH '(' exception_declaration ')' compound_statement
'''
global noExceptionLogic
noExceptionLogic=False
def p_exception_declaration(p):
'''exception_declaration : parameter_declaration
'''
pass
def p_throw_expression(p):
'''throw_expression : THROW
| THROW assignment_expression
'''
global noExceptionLogic
noExceptionLogic=False
def p_exception_specification(p):
'''exception_specification : THROW '(' ')'
| THROW '(' type_id_list ')'
'''
global noExceptionLogic
noExceptionLogic=False
def p_type_id_list(p):
'''type_id_list : type_id
| type_id_list ',' type_id
'''
pass
#---------------------------------------------------------------------------------------------------
# Misc productions
#---------------------------------------------------------------------------------------------------
def p_nonsemicolon_seq(p):
'''nonsemicolon_seq : empty
| nonsemicolon_seq nonsemicolon
'''
pass
def p_nonsemicolon(p):
'''nonsemicolon : misc
| '('
| ')'
| '<'
| '>'
| LBRACKET nonbracket_seq_opt RBRACKET
| LBRACE nonbrace_seq_opt RBRACE
'''
pass
def p_nonparen_seq_opt(p):
'''nonparen_seq_opt : empty
| nonparen_seq_opt nonparen
'''
pass
def p_nonparen_seq(p):
'''nonparen_seq : nonparen
| nonparen_seq nonparen
'''
pass
def p_nonparen(p):
'''nonparen : misc
| '<'
| '>'
| ';'
| LBRACKET nonbracket_seq_opt RBRACKET
| LBRACE nonbrace_seq_opt RBRACE
'''
pass
def p_nonbracket_seq_opt(p):
'''nonbracket_seq_opt : empty
| nonbracket_seq_opt nonbracket
'''
pass
def p_nonbracket_seq(p):
'''nonbracket_seq : nonbracket
| nonbracket_seq nonbracket
'''
pass
def p_nonbracket(p):
'''nonbracket : misc
| '<'
| '>'
| '('
| ')'
| ';'
| LBRACKET nonbracket_seq_opt RBRACKET
| LBRACE nonbrace_seq_opt RBRACE
'''
pass
def p_nonbrace_seq_opt(p):
'''nonbrace_seq_opt : empty
| nonbrace_seq_opt nonbrace
'''
pass
def p_nonbrace(p):
'''nonbrace : misc
| '<'
| '>'
| '('
| ')'
| ';'
| LBRACKET nonbracket_seq_opt RBRACKET
| LBRACE nonbrace_seq_opt RBRACE
'''
pass
def p_nonlgt_seq_opt(p):
'''nonlgt_seq_opt : empty
| nonlgt_seq_opt nonlgt
'''
pass
def p_nonlgt(p):
'''nonlgt : misc
| '('
| ')'
| LBRACKET nonbracket_seq_opt RBRACKET
| '<' nonlgt_seq_opt '>'
| ';'
'''
pass
def p_misc(p):
'''misc : operator
| identifier
| IntegerLiteral
| CharacterLiteral
| FloatingLiteral
| StringLiteral
| reserved
| '?'
| ':'
| '.'
| SCOPE
| ELLIPSIS
| EXTENSION
'''
pass
def p_empty(p):
'''empty : '''
pass
#
# Compute column.
# input is the input text string
# token is a token instance
#
def _find_column(input,token):
''' TODO '''
i = token.lexpos
while i > 0:
if input[i] == '\n': break
i -= 1
column = (token.lexpos - i)+1
return column
def p_error(p):
if p is None:
tmp = "Syntax error at end of file."
else:
tmp = "Syntax error at token "
if p.type is "":
tmp = tmp + "''"
else:
tmp = tmp + str(p.type)
tmp = tmp + " with value '"+str(p.value)+"'"
tmp = tmp + " in line " + str(lexer.lineno-1)
tmp = tmp + " at column "+str(_find_column(_parsedata,p))
raise IOError( tmp )
#
# The function that performs the parsing
#
def parse_cpp(data=None, filename=None, debug=0, optimize=0, verbose=False, func_filter=None):
if debug > 0:
print "Debugging parse_cpp!"
#
# Always remove the parser.out file, which is generated to create debugging
#
if os.path.exists("parser.out"):
os.remove("parser.out")
#
# Remove the parsetab.py* files. These apparently need to be removed
# to ensure the creation of a parser.out file.
#
if os.path.exists("parsetab.py"):
os.remove("parsetab.py")
if os.path.exists("parsetab.pyc"):
os.remove("parsetab.pyc")
global debugging
debugging=True
#
# Build lexer
#
global lexer
lexer = lex.lex()
#
# Initialize parse object
#
global _parse_info
_parse_info = CppInfo(filter=func_filter)
_parse_info.verbose=verbose
#
# Build yaccer
#
write_table = not os.path.exists("parsetab.py")
yacc.yacc(debug=debug, optimize=optimize, write_tables=write_table)
#
# Parse the file
#
global _parsedata
if not data is None:
_parsedata=data
ply_init(_parsedata)
yacc.parse(data,debug=debug)
elif not filename is None:
f = open(filename)
data = f.read()
f.close()
_parsedata=data
ply_init(_parsedata)
yacc.parse(data, debug=debug)
else:
return None
#
if not noExceptionLogic:
_parse_info.noExceptionLogic = False
else:
for key in identifier_lineno:
if 'ASSERT_THROWS' in key:
_parse_info.noExceptionLogic = False
break
_parse_info.noExceptionLogic = True
#
return _parse_info
import sys
if __name__ == '__main__':
#
# This MAIN routine parses a sequence of files provided at the command
# line. If '-v' is included, then a verbose parsing output is
# generated.
#
for arg in sys.argv[1:]:
if arg == "-v":
continue
print "Parsing file '"+arg+"'"
if '-v' in sys.argv:
parse_cpp(filename=arg,debug=2,verbose=2)
else:
parse_cpp(filename=arg,verbose=2)
#
# Print the _parse_info object summary for this file.
# This illustrates how class inheritance can be used to
# deduce class members.
#
print str(_parse_info)
| [
[
1,
0,
0.0228,
0.0005,
0,
0.66,
0,
777,
0,
1,
0,
0,
777,
0,
0
],
[
1,
0,
0.0238,
0.0005,
0,
0.66,
0.004,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0242,
0.0005,
0,
0... | [
"from __future__ import division",
"import os",
"import ply.lex as lex",
"import ply.yacc as yacc",
"import re",
"try:\n from collections import OrderedDict\nexcept ImportError:\n from ordereddict import OrderedDict",
" from collections import OrderedDict",
" from ordereddict import Ordere... |
#-------------------------------------------------------------------------
# CxxTest: A lightweight C++ unit testing library.
# Copyright (c) 2008 Sandia Corporation.
# This software is distributed under the LGPL License v2.1
# For more information, see the COPYING file in the top CxxTest directory.
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains certain rights in this software.
#-------------------------------------------------------------------------
"""cxxtest: A Python package that supports the CxxTest test framework for C/C++.
.. _CxxTest: http://cxxtest.tigris.org/
CxxTest is a unit testing framework for C++ that is similar in
spirit to JUnit, CppUnit, and xUnit. CxxTest is easy to use because
it does not require precompiling a CxxTest testing library, it
employs no advanced features of C++ (e.g. RTTI) and it supports a
very flexible form of test discovery.
The cxxtest Python package includes capabilities for parsing C/C++ source files and generating
CxxTest drivers.
"""
from cxxtest.__release__ import __version__, __date__
__date__
__version__
__maintainer__ = "William E. Hart"
__maintainer_email__ = "whart222@gmail.com"
__license__ = "LGPL"
__url__ = "http://cxxtest.tigris.org/"
from cxxtest.cxxtestgen import *
| [
[
8,
0,
0.4848,
0.3939,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.7273,
0.0303,
0,
0.66,
0.125,
129,
0,
2,
0,
0,
129,
0,
0
],
[
8,
0,
0.7576,
0.0303,
0,
0.66,... | [
"\"\"\"cxxtest: A Python package that supports the CxxTest test framework for C/C++.\n\n.. _CxxTest: http://cxxtest.tigris.org/\n\nCxxTest is a unit testing framework for C++ that is similar in\nspirit to JUnit, CppUnit, and xUnit. CxxTest is easy to use because\nit does not require precompiling a CxxTest testing l... |
#!/usr/bin/python
#-------------------------------------------------------------------------
# CxxTest: A lightweight C++ unit testing library.
# Copyright (c) 2008 Sandia Corporation.
# This software is distributed under the LGPL License v2.1
# For more information, see the COPYING file in the top CxxTest directory.
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains certain rights in this software.
#-------------------------------------------------------------------------
import sys
def abort( problem ):
'''Print error message and exit'''
sys.stderr.write( '\n' )
sys.stderr.write( problem )
sys.stderr.write( '\n\n' )
sys.exit(2)
| [
[
1,
0,
0.5789,
0.0526,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
2,
0,
0.8158,
0.3158,
0,
0.66,
1,
299,
0,
1,
0,
0,
0,
0,
4
],
[
8,
1,
0.7368,
0.0526,
1,
0.59,
... | [
"import sys",
"def abort( problem ):\n '''Print error message and exit'''\n sys.stderr.write( '\\n' )\n sys.stderr.write( problem )\n sys.stderr.write( '\\n\\n' )\n sys.exit(2)",
" '''Print error message and exit'''",
" sys.stderr.write( '\\n' )",
" sys.stderr.write( problem )",
" ... |
#-------------------------------------------------------------------------
# CxxTest: A lightweight C++ unit testing library.
# Copyright (c) 2008 Sandia Corporation.
# This software is distributed under the LGPL License v2.1
# For more information, see the COPYING file in the top CxxTest directory.
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains certain rights in this software.
#-------------------------------------------------------------------------
# vim: fileencoding=utf-8
from __future__ import division
# the above import important for forward-compatibility with python3,
# which is already the default in archlinux!
__all__ = ['main']
import __release__
import os
import sys
import re
import glob
from optparse import OptionParser
import cxxtest_parser
try:
import cxxtest_fog
imported_fog=True
except ImportError:
imported_fog=False
from cxxtest_misc import abort
options = []
suites = []
wrotePreamble = 0
wroteWorld = 0
lastIncluded = ''
def main(args=sys.argv):
'''The main program'''
#
# Reset global state
#
global wrotePreamble
wrotePreamble=0
global wroteWorld
wroteWorld=0
global lastIncluded
lastIncluded = ''
global suites
global options
files = parseCommandline(args)
if imported_fog and options.fog:
[options,suites] = cxxtest_fog.scanInputFiles( files, options )
else:
[options,suites] = cxxtest_parser.scanInputFiles( files, options )
writeOutput()
def parseCommandline(args):
'''Analyze command line arguments'''
global imported_fog
global options
parser = OptionParser("%prog [options] [<filename> ...]")
parser.add_option("--version",
action="store_true", dest="version", default=False,
help="Write the CxxTest version.")
parser.add_option("-o", "--output",
dest="outputFileName", default=None, metavar="NAME",
help="Write output to file NAME.")
parser.add_option("-w","--world", dest="world", default="cxxtest",
help="The label of the tests, used to name the XML results.")
parser.add_option("", "--include", action="append",
dest="headers", default=[], metavar="HEADER",
help="Include file HEADER in the test runner before other headers.")
parser.add_option("", "--abort-on-fail",
action="store_true", dest="abortOnFail", default=False,
help="Abort tests on failed asserts (like xUnit).")
parser.add_option("", "--main",
action="store", dest="main", default="main",
help="Specify an alternative name for the main() function.")
parser.add_option("", "--headers",
action="store", dest="header_filename", default=None,
help="Specify a filename that contains a list of header files that are processed to generate a test runner.")
parser.add_option("", "--runner",
dest="runner", default="", metavar="CLASS",
help="Create a test runner that processes test events using the class CxxTest::CLASS.")
parser.add_option("", "--gui",
dest="gui", metavar="CLASS",
help="Create a GUI test runner that processes test events using the class CxxTest::CLASS. (deprecated)")
parser.add_option("", "--error-printer",
action="store_true", dest="error_printer", default=False,
help="Create a test runner using the ErrorPrinter class, and allow the use of the standard library.")
parser.add_option("", "--xunit-printer",
action="store_true", dest="xunit_printer", default=False,
help="Create a test runner using the XUnitPrinter class.")
parser.add_option("", "--xunit-file", dest="xunit_file", default="",
help="The file to which the XML summary is written for test runners using the XUnitPrinter class. The default XML filename is TEST-<world>.xml, where <world> is the value of the --world option. (default: cxxtest)")
parser.add_option("", "--have-std",
action="store_true", dest="haveStandardLibrary", default=False,
help="Use the standard library (even if not found in tests).")
parser.add_option("", "--no-std",
action="store_true", dest="noStandardLibrary", default=False,
help="Do not use standard library (even if found in tests).")
parser.add_option("", "--have-eh",
action="store_true", dest="haveExceptionHandling", default=False,
help="Use exception handling (even if not found in tests).")
parser.add_option("", "--no-eh",
action="store_true", dest="noExceptionHandling", default=False,
help="Do not use exception handling (even if found in tests).")
parser.add_option("", "--longlong",
dest="longlong", default=None, metavar="TYPE",
help="Use TYPE as for long long integers. (default: not supported)")
parser.add_option("", "--no-static-init",
action="store_true", dest="noStaticInit", default=False,
help="Do not rely on static initialization in the test runner.")
parser.add_option("", "--template",
dest="templateFileName", default=None, metavar="TEMPLATE",
help="Generate the test runner using file TEMPLATE to define a template.")
parser.add_option("", "--root",
action="store_true", dest="root", default=False,
help="Write the main() function and global data for a test runner.")
parser.add_option("", "--part",
action="store_true", dest="part", default=False,
help="Write the tester classes for a test runner.")
#parser.add_option("", "--factor",
#action="store_true", dest="factor", default=False,
#help="Declare the _CXXTEST_FACTOR macro. (deprecated)")
if imported_fog:
fog_help = "Use new FOG C++ parser"
else:
fog_help = "Use new FOG C++ parser (disabled)"
parser.add_option("-f", "--fog-parser",
action="store_true",
dest="fog",
default=False,
help=fog_help
)
(options, args) = parser.parse_args(args=args)
if not options.header_filename is None:
if not os.path.exists(options.header_filename):
abort( "ERROR: the file '%s' does not exist!" % options.header_filename )
INPUT = open(options.header_filename)
headers = [line.strip() for line in INPUT]
args.extend( headers )
INPUT.close()
if options.fog and not imported_fog:
abort( "Cannot use the FOG parser. Check that the 'ply' package is installed. The 'ordereddict' package is also required if running Python 2.6")
if options.version:
printVersion()
# the cxxtest builder relies on this behaviour! don't remove
if options.runner == 'none':
options.runner = None
if options.xunit_printer or options.runner == "XUnitPrinter":
options.xunit_printer=True
options.runner="XUnitPrinter"
if len(args) > 1:
if options.xunit_file == "":
if options.world == "":
options.world = "cxxtest"
options.xunit_file="TEST-"+options.world+".xml"
elif options.xunit_file == "":
if options.world == "":
options.world = "cxxtest"
options.xunit_file="TEST-"+options.world+".xml"
if options.error_printer:
options.runner= "ErrorPrinter"
options.haveStandardLibrary = True
if options.noStaticInit and (options.root or options.part):
abort( '--no-static-init cannot be used with --root/--part' )
if options.gui and not options.runner:
options.runner = 'StdioPrinter'
files = setFiles(args[1:])
if len(files) == 0 and not options.root:
sys.stderr.write(parser.error("No input files found"))
return files
def printVersion():
'''Print CxxTest version and exit'''
sys.stdout.write( "This is CxxTest version %s.\n" % __release__.__version__ )
sys.exit(0)
def setFiles(patterns ):
'''Set input files specified on command line'''
files = expandWildcards( patterns )
return files
def expandWildcards( patterns ):
'''Expand all wildcards in an array (glob)'''
fileNames = []
for pathName in patterns:
patternFiles = glob.glob( pathName )
for fileName in patternFiles:
fileNames.append( fixBackslashes( fileName ) )
return fileNames
def fixBackslashes( fileName ):
'''Convert backslashes to slashes in file name'''
return re.sub( r'\\', '/', fileName, 0 )
def writeOutput():
'''Create output file'''
if options.templateFileName:
writeTemplateOutput()
else:
writeSimpleOutput()
def writeSimpleOutput():
'''Create output not based on template'''
output = startOutputFile()
writePreamble( output )
if options.root or not options.part:
writeMain( output )
if len(suites) > 0:
output.write("bool "+suites[0]['object']+"_init = false;\n")
writeWorld( output )
output.close()
include_re = re.compile( r"\s*\#\s*include\s+<cxxtest/" )
preamble_re = re.compile( r"^\s*<CxxTest\s+preamble>\s*$" )
world_re = re.compile( r"^\s*<CxxTest\s+world>\s*$" )
def writeTemplateOutput():
'''Create output based on template file'''
template = open(options.templateFileName)
output = startOutputFile()
while 1:
line = template.readline()
if not line:
break;
if include_re.search( line ):
writePreamble( output )
output.write( line )
elif preamble_re.search( line ):
writePreamble( output )
elif world_re.search( line ):
if len(suites) > 0:
output.write("bool "+suites[0]['object']+"_init = false;\n")
writeWorld( output )
else:
output.write( line )
template.close()
output.close()
def startOutputFile():
'''Create output file and write header'''
if options.outputFileName is not None:
output = open( options.outputFileName, 'w' )
else:
output = sys.stdout
output.write( "/* Generated file, do not edit */\n\n" )
return output
def writePreamble( output ):
'''Write the CxxTest header (#includes and #defines)'''
global wrotePreamble
if wrotePreamble: return
output.write( "#ifndef CXXTEST_RUNNING\n" )
output.write( "#define CXXTEST_RUNNING\n" )
output.write( "#endif\n" )
output.write( "\n" )
if options.xunit_printer:
output.write( "#include <fstream>\n" )
if options.haveStandardLibrary:
output.write( "#define _CXXTEST_HAVE_STD\n" )
if options.haveExceptionHandling:
output.write( "#define _CXXTEST_HAVE_EH\n" )
if options.abortOnFail:
output.write( "#define _CXXTEST_ABORT_TEST_ON_FAIL\n" )
if options.longlong:
output.write( "#define _CXXTEST_LONGLONG %s\n" % options.longlong )
#if options.factor:
#output.write( "#define _CXXTEST_FACTOR\n" )
for header in options.headers:
output.write( "#include \"%s\"\n" % header )
output.write( "#include <cxxtest/TestListener.h>\n" )
output.write( "#include <cxxtest/TestTracker.h>\n" )
output.write( "#include <cxxtest/TestRunner.h>\n" )
output.write( "#include <cxxtest/RealDescriptions.h>\n" )
output.write( "#include <cxxtest/TestMain.h>\n" )
if options.runner:
output.write( "#include <cxxtest/%s.h>\n" % options.runner )
if options.gui:
output.write( "#include <cxxtest/%s.h>\n" % options.gui )
output.write( "\n" )
wrotePreamble = 1
def writeMain( output ):
'''Write the main() function for the test runner'''
if not (options.gui or options.runner):
return
output.write( 'int %s( int argc, char *argv[] ) {\n' % options.main )
output.write( ' int status;\n' )
if options.noStaticInit:
output.write( ' CxxTest::initialize();\n' )
if options.gui:
tester_t = "CxxTest::GuiTuiRunner<CxxTest::%s, CxxTest::%s> " % (options.gui, options.runner)
else:
tester_t = "CxxTest::%s" % (options.runner)
if options.xunit_printer:
output.write( ' std::ofstream ofstr("%s");\n' % options.xunit_file )
output.write( ' %s tmp(ofstr);\n' % tester_t )
output.write( ' CxxTest::RealWorldDescription::_worldName = "%s";\n' % options.world )
else:
output.write( ' %s tmp;\n' % tester_t )
output.write( ' status = CxxTest::Main<%s>( tmp, argc, argv );\n' % tester_t )
output.write( ' return status;\n')
output.write( '}\n' )
def writeWorld( output ):
'''Write the world definitions'''
global wroteWorld
if wroteWorld: return
writePreamble( output )
writeSuites( output )
if options.root or not options.part:
writeRoot( output )
writeWorldDescr( output )
if options.noStaticInit:
writeInitialize( output )
wroteWorld = 1
def writeSuites(output):
'''Write all TestDescriptions and SuiteDescriptions'''
for suite in suites:
writeInclude( output, suite['file'] )
if isGenerated(suite):
generateSuite( output, suite )
if isDynamic(suite):
writeSuitePointer( output, suite )
else:
writeSuiteObject( output, suite )
writeTestList( output, suite )
writeSuiteDescription( output, suite )
writeTestDescriptions( output, suite )
def isGenerated(suite):
'''Checks whether a suite class should be created'''
return suite['generated']
def isDynamic(suite):
'''Checks whether a suite is dynamic'''
return 'create' in suite
def writeInclude(output, file):
'''Add #include "file" statement'''
global lastIncluded
if file == lastIncluded: return
output.writelines( [ '#include "', file, '"\n\n' ] )
lastIncluded = file
def generateSuite( output, suite ):
'''Write a suite declared with CXXTEST_SUITE()'''
output.write( 'class %s : public CxxTest::TestSuite {\n' % suite['name'] )
output.write( 'public:\n' )
for line in suite['lines']:
output.write(line)
output.write( '};\n\n' )
def writeSuitePointer( output, suite ):
'''Create static suite pointer object for dynamic suites'''
if options.noStaticInit:
output.write( 'static %s *%s;\n\n' % (suite['name'], suite['object']) )
else:
output.write( 'static %s *%s = 0;\n\n' % (suite['name'], suite['object']) )
def writeSuiteObject( output, suite ):
'''Create static suite object for non-dynamic suites'''
output.writelines( [ "static ", suite['name'], " ", suite['object'], ";\n\n" ] )
def writeTestList( output, suite ):
'''Write the head of the test linked list for a suite'''
if options.noStaticInit:
output.write( 'static CxxTest::List %s;\n' % suite['tlist'] )
else:
output.write( 'static CxxTest::List %s = { 0, 0 };\n' % suite['tlist'] )
def writeWorldDescr( output ):
'''Write the static name of the world name'''
if options.noStaticInit:
output.write( 'const char* CxxTest::RealWorldDescription::_worldName;\n' )
else:
output.write( 'const char* CxxTest::RealWorldDescription::_worldName = "cxxtest";\n' )
def writeTestDescriptions( output, suite ):
'''Write all test descriptions for a suite'''
for test in suite['tests']:
writeTestDescription( output, suite, test )
def writeTestDescription( output, suite, test ):
'''Write test description object'''
output.write( 'static class %s : public CxxTest::RealTestDescription {\n' % test['class'] )
output.write( 'public:\n' )
if not options.noStaticInit:
output.write( ' %s() : CxxTest::RealTestDescription( %s, %s, %s, "%s" ) {}\n' %
(test['class'], suite['tlist'], suite['dobject'], test['line'], test['name']) )
output.write( ' void runTest() { %s }\n' % runBody( suite, test ) )
output.write( '} %s;\n\n' % test['object'] )
def runBody( suite, test ):
'''Body of TestDescription::run()'''
if isDynamic(suite): return dynamicRun( suite, test )
else: return staticRun( suite, test )
def dynamicRun( suite, test ):
'''Body of TestDescription::run() for test in a dynamic suite'''
return 'if ( ' + suite['object'] + ' ) ' + suite['object'] + '->' + test['name'] + '();'
def staticRun( suite, test ):
'''Body of TestDescription::run() for test in a non-dynamic suite'''
return suite['object'] + '.' + test['name'] + '();'
def writeSuiteDescription( output, suite ):
'''Write SuiteDescription object'''
if isDynamic( suite ):
writeDynamicDescription( output, suite )
else:
writeStaticDescription( output, suite )
def writeDynamicDescription( output, suite ):
'''Write SuiteDescription for a dynamic suite'''
output.write( 'CxxTest::DynamicSuiteDescription<%s> %s' % (suite['name'], suite['dobject']) )
if not options.noStaticInit:
output.write( '( %s, %s, "%s", %s, %s, %s, %s )' %
(suite['cfile'], suite['line'], suite['name'], suite['tlist'],
suite['object'], suite['create'], suite['destroy']) )
output.write( ';\n\n' )
def writeStaticDescription( output, suite ):
'''Write SuiteDescription for a static suite'''
output.write( 'CxxTest::StaticSuiteDescription %s' % suite['dobject'] )
if not options.noStaticInit:
output.write( '( %s, %s, "%s", %s, %s )' %
(suite['cfile'], suite['line'], suite['name'], suite['object'], suite['tlist']) )
output.write( ';\n\n' )
def writeRoot(output):
'''Write static members of CxxTest classes'''
output.write( '#include <cxxtest/Root.cpp>\n' )
def writeInitialize(output):
'''Write CxxTest::initialize(), which replaces static initialization'''
output.write( 'namespace CxxTest {\n' )
output.write( ' void initialize()\n' )
output.write( ' {\n' )
for suite in suites:
output.write( ' %s.initialize();\n' % suite['tlist'] )
if isDynamic(suite):
output.write( ' %s = 0;\n' % suite['object'] )
output.write( ' %s.initialize( %s, %s, "%s", %s, %s, %s, %s );\n' %
(suite['dobject'], suite['cfile'], suite['line'], suite['name'],
suite['tlist'], suite['object'], suite['create'], suite['destroy']) )
else:
output.write( ' %s.initialize( %s, %s, "%s", %s, %s );\n' %
(suite['dobject'], suite['cfile'], suite['line'], suite['name'],
suite['object'], suite['tlist']) )
for test in suite['tests']:
output.write( ' %s.initialize( %s, %s, %s, "%s" );\n' %
(test['object'], suite['tlist'], suite['dobject'], test['line'], test['name']) )
output.write( ' }\n' )
output.write( '}\n' )
| [
[
1,
0,
0.025,
0.0021,
0,
0.66,
0,
777,
0,
1,
0,
0,
777,
0,
0
],
[
14,
0,
0.0333,
0.0021,
0,
0.66,
0.02,
272,
0,
0,
0,
0,
0,
5,
0
],
[
1,
0,
0.0375,
0.0021,
0,
0.66... | [
"from __future__ import division",
"__all__ = ['main']",
"import __release__",
"import os",
"import sys",
"import re",
"import glob",
"from optparse import OptionParser",
"import cxxtest_parser",
"try:\n import cxxtest_fog\n imported_fog=True\nexcept ImportError:\n imported_fog=False",
... |
#! /usr/bin/env python
#
# The CxxTest driver script, which uses the cxxtest Python package.
#
import sys
import os
from os.path import realpath, dirname
if sys.version_info < (3,0):
sys.path.insert(0, dirname(dirname(realpath(__file__)))+os.sep+'python')
else:
sys.path.insert(0, dirname(dirname(realpath(__file__)))+os.sep+'python'+os.sep+'python3')
sys.path.append(".")
import cxxtest
cxxtest.main(sys.argv)
| [
[
1,
0,
0.3333,
0.0556,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.3889,
0.0556,
0,
0.66,
0.1667,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.4444,
0.0556,
0,
... | [
"import sys",
"import os",
"from os.path import realpath, dirname",
"if sys.version_info < (3,0):\n sys.path.insert(0, dirname(dirname(realpath(__file__)))+os.sep+'python')\nelse:\n sys.path.insert(0, dirname(dirname(realpath(__file__)))+os.sep+'python'+os.sep+'python3')",
" sys.path.insert(0, dirn... |
from Carta import Carta
class Jugador(object):
"""Clase que representa a un jugador de Corazones"""
def __init__(self, id_jugador, nombre):
"""Crea el jugador desde su id y su nombre. El id es un numero en el rango 0..3"""
self.id_jugador = id_jugador
self.nombre = nombre
self.mano = []
def obtener_id_jugador(self):
"""Devuelve el id del jugador"""
return self.id_jugador
def recibir_carta(self, carta):
"""Recibe una carta y la agrega a su mano"""
self.mano.append(carta)
def es_primero(self):
"""Devuelve True si el usuario tiene el 2 de treboles"""
return Carta(2, Carta.TREBOLES) in self.mano
def devolver_cartas_a_pasar(self, id_jugador): #########################
"""Antes de comenzar la mano, retira de su mano y devuelve 3 cartas para
pasarle al oponente con id id_jugador"""
cartas_a_pasar=self.mano[0:3]
del self.mano[0:3]
return cartas_a_pasar
def recibir_cartas_pasadas(self, id_jugador, cartas):
"""Antes de comenzar la mano y despues de haber devuelto sus cartas, recibe
3 cartas del oponente con id id_jugador"""
self.mano += cartas
def jugar_carta(self, nro_mano, nro_jugada, cartas_jugadas, corazon_jugado): ####################
"""Saca una carta de su mano y la devuelve jugandola. Recibe el numero de
mano, el numero de jugada, las cartas ya jugadas en la mesa en esa jugada
y un booleano que indica si ya se jugaron corazones en las jugadas previas.
Si ya hay cartas_jugadas y el jugador posee una carta del palo de la primer
carta debe jugarla obligatoriamente.
Si nro_jugada es 1 y no hay cartas_jugadas, el jugador debe jugar el 2 de
treboles.
Si nro_jugada es 1 el jugador no puede jugar ni un corazon ni la Q de picas.
Si no hay cartas_jugadas y corazon_jugado es False el jugador no podra jugar
un corazon salvo que no tenga otra carta."""
if nro_jugada==1 and Carta(2, Carta.TREBOLES) in self.mano:
indice=self.mano.index(Carta(2, Carta.TREBOLES))
carta_dos_trebol=self.mano[indice]
del self.mano[indice]
return carta_dos_trebol
if nro_jugada==1:
for i in range(len(self.mano)):
carta=self.mano[i]
if carta.obtener_palo() == 3:
del self.mano[i]
return carta
for i in range(len(self.mano)):
carta=self.mano[i]
if not carta == Carta(12, Carta.PICAS) and not carta.obtener_palo() == 0:
del self.mano[i]
return carta
if not len(cartas_jugadas) == 0:
palo_mano=cartas_jugadas[0].obtener_palo()
for i in range(len(self.mano)):
carta=self.mano[i]
if carta.obtener_palo()== palo_mano:
del self.mano[i]
return carta
carta=self.mano[0]
del self.mano[0]
return carta
else:
carta=self.mano[0]
del self.mano[0]
return carta
def conocer_jugada(self, cartas_jugadas, id_primer_jugador, id_jugador_que_levanto): ########################
"""Luego de terminada la jugada, se informa al jugador sobre las cartas que
se jugaron, en que orden y cual fue el id del jugador que levanto las cartas
del juego."""
pass
def __str__(self):
"""Representacion del jugador"""
return "%s (%d)" % (self.nombre, self.id_jugador)
| [
[
1,
0,
0.01,
0.01,
0,
0.66,
0,
238,
0,
1,
0,
0,
238,
0,
0
],
[
3,
0,
0.515,
0.98,
0,
0.66,
1,
639,
0,
9,
0,
0,
186,
0,
17
],
[
8,
1,
0.04,
0.01,
1,
0.28,
0,
... | [
"from Carta import Carta",
"class Jugador(object):\n\t\"\"\"Clase que representa a un jugador de Corazones\"\"\"\n\n\tdef __init__(self, id_jugador, nombre):\n\t\t\"\"\"Crea el jugador desde su id y su nombre. El id es un numero en el rango 0..3\"\"\"\n\t\tself.id_jugador = id_jugador\n\t\tself.nombre = nombre\n\... |
class Carta(object):
"""Representa a una carta de la baraja inglesa"""
# Constantes para los palos
CORAZONES = 0
DIAMANTES = 1
PICAS = 2
TREBOLES = 3
# Diccionarios para la impresion:
NUMEROS = ["A"] + [str(n) for n in xrange(2, 11)] + ["J", "Q", "K"]
PALOS = ['corazones', 'diamantes', 'picas', 'treboles']
def __init__(self, numero, palo):
"""Crea una carta desde su numero y su palo"""
if not 1 <= numero <= 13 or not 0 <= palo <= 3:
raise ValueError
self.palo = palo
self.numero = numero
def obtener_palo(self):
return self.palo
def obtener_numero(self):
return self.numero
def __eq__(self, otro):
return self.palo == otro.palo and self.numero == otro.numero
def __str__(self):
return "%s de %s" % (Carta.NUMEROS[self.numero - 1], Carta.PALOS[self.palo])
| [
[
3,
0,
0.5,
0.9697,
0,
0.66,
0,
238,
0,
5,
0,
0,
186,
0,
2
],
[
8,
1,
0.0606,
0.0303,
1,
0.19,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
1,
0.1515,
0.0303,
1,
0.19,
0... | [
"class Carta(object):\n\t\"\"\"Representa a una carta de la baraja inglesa\"\"\"\n\n\t# Constantes para los palos\n\tCORAZONES = 0\n\tDIAMANTES = 1\n\tPICAS = 2\n\tTREBOLES = 3",
"\t\"\"\"Representa a una carta de la baraja inglesa\"\"\"",
"\tCORAZONES = 0",
"\tDIAMANTES = 1",
"\tPICAS = 2",
"\tTREBOLES =... |
from Carta import Carta
from Mazo import Mazo
from Jugador import Jugador
class JuegoCorazones(object):
"""Clase que representa un juego de Corazones"""
def __init__(self, jugadores):
"""Crea un juego en base a 4 jugadores"""
for jugador in jugadores:
if not isinstance(jugador,Jugador):
raise TypeError
self.jugadores=jugadores
self.puntaje=[0,0,0,0]
self.puntaje_mano=[0,0,0,0]
def termino(self):
"""Devuelve True si alguno de los jugadores alcanzo los 100 puntos"""
if (self.puntaje[0] > 99) or (self.puntaje[1] > 99) or (self.puntaje[2] > 99) or (self.puntaje[3] > 99):
return True
else:
return False
def imprimir_puntajes(self):
"""Imprime los puntajes de cada jugador hasta el momento"""
print "Jugador 1(%s): %s - Jugador 2(%s): %s - Jugador 3(%s): %s - Jugador 4(%s): %s" % (self.jugadores[0],self.puntaje[0],self.jugadores[1],self.puntaje[1],self.jugadores[2],self.puntaje[2],self.jugadores[3],self.puntaje[3])
def barajar(self):
"""Crea un mazo nuevo, lo mezcla y le reparte una carta a cada jugador hasta
que el mismo queda vacio."""
mazo=Mazo()
mazo.mezclar()
while not mazo.es_vacio():
self.jugadores[0].recibir_carta(mazo.obtener_tope())
self.jugadores[1].recibir_carta(mazo.obtener_tope())
self.jugadores[2].recibir_carta(mazo.obtener_tope())
self.jugadores[3].recibir_carta(mazo.obtener_tope())
def identificar_jugador_que_inicia(self):
"""Se fija cual de los 4 jugadores es primero y devuelve su id."""
for jugador in self.jugadores:
if jugador.es_primero():
return jugador.obtener_id_jugador()
def identificar_jugador_que_perdio(self, cartas_jugadas, id_primero):
"""Recibe las 4 cartas jugadas en la mano y el id del jugador que abrio
la jugada. Devuelve el id del jugador que perdio.
Pierde el jugador que juega la carta mas alta del palo con el que inicio
la jugada el primer jugador.
Las cartas por orden creciente son: 2, 3,..., 10, J, Q, K, A."""
palo_mano=cartas_jugadas[0].obtener_palo()
mayor_num=0
for i in xrange(1,len(cartas_jugadas)):
if palo_mano==cartas_jugadas[i].obtener_palo():
if cartas_jugadas[i].obtener_numero() == 1:
mayor_num=i
elif not cartas_jugadas[mayor_num].obtener_numero()==1 and cartas_jugadas[i].obtener_numero() > cartas_jugadas[mayor_num].obtener_numero():
mayor_num=i
else:
pass
if (id_primero+mayor_num) >= 4:
return id_primero+mayor_num-4
else:
return id_primero+mayor_num
def procesar_e_informar_resultado(self, cartas_jugadas, id_primero, id_perdedor):
"""Recibe las cartas de la jugada, el id del primer jugador, y el id del
jugador que perdio.
Almacena lo necesario para llevar la cuenta de puntos e informa a todos
los jugadores del resultado de la jugada."""
if Carta(12, Carta.PICAS) in cartas_jugadas:
self.puntaje_mano[id_perdedor]+=13
for carta in cartas_jugadas:
if carta.obtener_palo() == 0:
self.puntaje_mano[id_perdedor]+=1
for jugador in self.jugadores:
jugador.conocer_jugada(cartas_jugadas,id_primero,id_perdedor)
def hay_corazones(self, cartas):
"""Devuelve True si hay algun corazon entre las cartas pasadas"""
for carta in cartas:
if carta.obtener_palo() == 0:
return True
def realizar_jugada(self, nro_mano, nro_jugada, id_primero, corazon_jugado):
"""Recibe el numero de mano, de jugada, el id del primer jugador y si ya
se jugaron corazones hasta el momento.
Hace jugar una carta a cada uno de los jugadores empezando por el primero.
Devuelve las 4 cartas jugadas."""
cartas_jugadas=[]
cont=0
for i in xrange(id_primero,4):
cartas_jugadas.append(self.jugadores[i].jugar_carta(nro_mano,nro_jugada,cartas_jugadas,corazon_jugado))
cont+=1
if cont < 4:
for i in xrange(0,4-cont):
cartas_jugadas.append(self.jugadores[i].jugar_carta(nro_mano,nro_jugada,cartas_jugadas,corazon_jugado))
return cartas_jugadas
def calcular_puntajes(self):
"""Al finalizar la mano, calcula y actualiza los puntajes de los jugadores.
Cada jugador suma un punto por cada corazon levantado en la mano y 13 puntos
si levanto la Q de picas, salvo en el caso de que un solo jugador haya
levantado todos los corazones y la Q de picas, caso en el cual todos los
jugadores salvo el suman 26 puntos."""
if 26 in self.puntaje_mano:
indice=self.puntaje_mano.index(26)
for i in xrange(4):
if not i == indice:
self.puntaje[i]+=26
else:
for i in xrange(4):
self.puntaje[i]+=self.puntaje_mano[i]
for i in xrange(4):
self.puntaje_mano[i]=0
def intercambiar_cartas(self, nro_mano):
"""Antes de hacer la primer jugada se pasan 3 cartas entre los rivales.
En la primer mano, las cartas se pasan al jugador de la izquierda; en la
segunda al jugador de la derecha; en la tercera al jugador del frente y
en la cuarta no se pasan cartas. A partir de la quinta mano, se repite el
mismo ciclo.
El metodo debe primero pedirle las 3 cartas a pasar a cada oponente y luego
entregarle las cartas que le fueron pasadas."""
izquierda=[1,5,9,13]
derecha=[2,6,10]
frente=[3,7,11]
cartas=[0,0,0,0]
if nro_mano in izquierda:
for i in xrange(1,4):
cartas[i]=self.jugadores[i].devolver_cartas_a_pasar(i-1)
cartas[0]=self.jugadores[0].devolver_cartas_a_pasar(3)
for i in xrange(2,-1,-1):
self.jugadores[i].recibir_cartas_pasadas(i+1,cartas[i+1])
self.jugadores[3].recibir_cartas_pasadas(0,cartas[0])
elif nro_mano in derecha:
for i in xrange(2,-1,-1):
cartas[i]=self.jugadores[i].devolver_cartas_a_pasar(i+1)
cartas[3]=self.jugadores[3].devolver_cartas_a_pasar(0)
for i in xrange(1,4):
self.jugadores[i].recibir_cartas_pasadas(i-1,cartas[i-1])
self.jugadores[0].recibir_cartas_pasadas(3,cartas[3])
elif nro_mano in frente:
cartas[0]=self.jugadores[0].devolver_cartas_a_pasar(2)
cartas[1]=self.jugadores[1].devolver_cartas_a_pasar(3)
cartas[2]=self.jugadores[2].devolver_cartas_a_pasar(0)
cartas[3]=self.jugadores[3].devolver_cartas_a_pasar(1)
self.jugadores[0].recibir_cartas_pasadas(2,cartas[2])
self.jugadores[2].recibir_cartas_pasadas(0,cartas[0])
self.jugadores[3].recibir_cartas_pasadas(1,cartas[1])
self.jugadores[1].recibir_cartas_pasadas(3,cartas[3])
def ganadores(self):
"""Una vez terminado el juego, devuelve la lista de ganadores.
Son ganadores todos los jugadores que hayan alcanzado el menor puntaje."""
raise NotImplementedError
def jugar_mano(self, nro_mano):
"""Realiza las 13 jugadas que corresponden a una mano completa."""
corazon_jugado = False
id_primero = self.identificar_jugador_que_inicia()
# INICIO: Chequeos de trampa
palos_faltantes = [[], [], [], []]
cartas_en_mesa = []
# FIN: Chequeos de trampa
for nro_jugada in xrange(1, 13 + 1):
print "Jugada %i" % nro_jugada
print "Empieza %s" % self.jugadores[id_primero]
cartas_jugadas = self.realizar_jugada(nro_mano, nro_jugada, id_primero, corazon_jugado)
corazon_jugado = self.hay_corazones(cartas_jugadas)
id_perdedor = self.identificar_jugador_que_perdio(cartas_jugadas, id_primero)
print "Levanta %s" % self.jugadores[id_perdedor]
self.procesar_e_informar_resultado(cartas_jugadas, id_primero, id_perdedor)
# INICIO: Chequeos de trampa
if nro_jugada == 1 and not cartas_jugadas[0] == Carta(2, Carta.TREBOLES):
raise Exception("El primer jugador no jugo el 2 de treboles""")
if nro_jugada == 1 and (corazon_jugado or Carta(12, Carta.PICAS) in cartas_jugadas):
raise Exception("Jugador jugo carta especial en primer juego""")
for i in xrange(4):
if cartas_jugadas[i].obtener_palo() in palos_faltantes[(i + id_primero) % 4]:
raise Exception("El jugador %s dijo que no tenia %s" % (self.jugadores[(i + id_primero) % 4], Carta.PALOS[cartas_jugadas[i].obtener_palo()]))
palo_jugada = cartas_jugadas[0].obtener_palo()
for i in xrange(1, 4):
if cartas_jugadas[i].obtener_palo() != palo_jugada and palo_jugada not in palos_faltantes[(i + id_primero) % 4]:
palos_faltantes[(i + id_primero) % 4].append(palo_jugada)
for carta in cartas_jugadas:
if carta in cartas_en_mesa:
raise Exception("Alguien se matufio el %s" % carta)
cartas_en_mesa.append(carta)
# FIN: Chequeos de trampa
id_primero = id_perdedor
def jugar(self):
"""Juega una partida completa de Corazones."""
nro_mano = 1
while not self.termino():
print "Mano %d" % nro_mano
self.barajar()
self.intercambiar_cartas(nro_mano)
self.jugar_mano(nro_mano)
self.calcular_puntajes()
self.imprimir_puntajes()
nro_mano += 1
martin=Jugador(0,"martin")
daniel=Jugador(1,"daniel")
gaby=Jugador(2,"gaby")
marce=Jugador(3,"marce")
juego=JuegoCorazones([martin,daniel,gaby,marce])
juego.jugar()
| [
[
1,
0,
0.0041,
0.0041,
0,
0.66,
0,
238,
0,
1,
0,
0,
238,
0,
0
],
[
1,
0,
0.0082,
0.0041,
0,
0.66,
0.1111,
240,
0,
1,
0,
0,
240,
0,
0
],
[
1,
0,
0.0122,
0.0041,
0,
... | [
"from Carta import Carta",
"from Mazo import Mazo",
"from Jugador import Jugador",
"class JuegoCorazones(object):\n\t\"\"\"Clase que representa un juego de Corazones\"\"\"\n\n\tdef __init__(self, jugadores):\n\t\t\"\"\"Crea un juego en base a 4 jugadores\"\"\"\n\t\t\n\t\tfor jugador in jugadores:\n\t\t\tif no... |
from random import shuffle
from Carta import Carta
class Mazo(object):
"""Representa a un mazo de barajas inglesas"""
def __init__(self):
"""Inicializa un mazo con sus 52 cartas"""
self.cartas = []
for numero in xrange(1, 13 + 1):
for palo in (Carta.CORAZONES, Carta.DIAMANTES, Carta.PICAS, Carta.TREBOLES):
self.cartas.append(Carta(numero, palo))
def mezclar(self):
"""Mezcla el mazo"""
shuffle(self.cartas)
def obtener_tope(self):
"""Quita la carta que esta encima del mazo y la devuelve"""
return self.cartas.pop()
def es_vacio(self):
"""Devuelve True si al mazo no le quedan cartas, False caso contrario"""
return len(self.cartas) == 0
| [
[
1,
0,
0.0417,
0.0417,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0833,
0.0417,
0,
0.66,
0.5,
238,
0,
1,
0,
0,
238,
0,
0
],
[
3,
0,
0.5833,
0.875,
0,
0.66... | [
"from random import shuffle",
"from Carta import Carta",
"class Mazo(object):\n\t\"\"\"Representa a un mazo de barajas inglesas\"\"\"\n\tdef __init__(self):\n\t\t\"\"\"Inicializa un mazo con sus 52 cartas\"\"\"\n\t\tself.cartas = []\n\n\t\tfor numero in xrange(1, 13 + 1):\n\t\t\tfor palo in (Carta.CORAZONES, Ca... |
from Carta import Carta
class Jugador(object):
"""Clase que representa a un jugador de Corazones"""
def __init__(self, id_jugador, nombre):
"""Crea el jugador desde su id y su nombre. El id es un numero en el rango 0..3"""
self.id_jugador = id_jugador
self.nombre = nombre
self.mano = []
def obtener_id_jugador(self):
"""Devuelve el id del jugador"""
return self.id_jugador
def recibir_carta(self, carta):
"""Recibe una carta y la agrega a su mano"""
self.mano.append(carta)
def es_primero(self):
"""Devuelve True si el usuario tiene el 2 de treboles"""
return Carta(2, Carta.TREBOLES) in self.mano
def devolver_cartas_a_pasar(self, id_jugador): #########################
"""Antes de comenzar la mano, retira de su mano y devuelve 3 cartas para
pasarle al oponente con id id_jugador"""
cartas_a_pasar=self.mano[0:3]
del self.mano[0:3]
return cartas_a_pasar
def recibir_cartas_pasadas(self, id_jugador, cartas):
"""Antes de comenzar la mano y despues de haber devuelto sus cartas, recibe
3 cartas del oponente con id id_jugador"""
self.mano += cartas
def jugar_carta(self, nro_mano, nro_jugada, cartas_jugadas, corazon_jugado): ####################
"""Saca una carta de su mano y la devuelve jugandola. Recibe el numero de
mano, el numero de jugada, las cartas ya jugadas en la mesa en esa jugada
y un booleano que indica si ya se jugaron corazones en las jugadas previas.
Si ya hay cartas_jugadas y el jugador posee una carta del palo de la primer
carta debe jugarla obligatoriamente.
Si nro_jugada es 1 y no hay cartas_jugadas, el jugador debe jugar el 2 de
treboles.
Si nro_jugada es 1 el jugador no puede jugar ni un corazon ni la Q de picas.
Si no hay cartas_jugadas y corazon_jugado es False el jugador no podra jugar
un corazon salvo que no tenga otra carta."""
if nro_jugada==1 and Carta(2, Carta.TREBOLES) in self.mano:
indice=self.mano.index(Carta(2, Carta.TREBOLES))
carta_dos_trebol=self.mano[indice]
del self.mano[indice]
return carta_dos_trebol
if nro_jugada==1:
for i in range(len(self.mano)):
carta=self.mano[i]
if carta.obtener_palo() == 3:
del self.mano[i]
return carta
for i in range(len(self.mano)):
carta=self.mano[i]
if not carta == Carta(12, Carta.PICAS) and not carta.obtener_palo() == 0:
del self.mano[i]
return carta
if not len(cartas_jugadas) == 0:
palo_mano=cartas_jugadas[0].obtener_palo()
for i in range(len(self.mano)):
carta=self.mano[i]
if carta.obtener_palo()== palo_mano:
del self.mano[i]
return carta
carta=self.mano[0]
del self.mano[0]
return carta
else:
carta=self.mano[0]
del self.mano[0]
return carta
def conocer_jugada(self, cartas_jugadas, id_primer_jugador, id_jugador_que_levanto): ########################
"""Luego de terminada la jugada, se informa al jugador sobre las cartas que
se jugaron, en que orden y cual fue el id del jugador que levanto las cartas
del juego."""
pass
def __str__(self):
"""Representacion del jugador"""
return "%s (%d)" % (self.nombre, self.id_jugador)
| [
[
1,
0,
0.0109,
0.0109,
0,
0.66,
0,
238,
0,
1,
0,
0,
238,
0,
0
],
[
3,
0,
0.5163,
0.9783,
0,
0.66,
1,
639,
0,
9,
0,
0,
186,
0,
17
],
[
8,
1,
0.0435,
0.0109,
1,
0.42... | [
"from Carta import Carta",
"class Jugador(object):\n\t\"\"\"Clase que representa a un jugador de Corazones\"\"\"\n\n\tdef __init__(self, id_jugador, nombre):\n\t\t\"\"\"Crea el jugador desde su id y su nombre. El id es un numero en el rango 0..3\"\"\"\n\t\tself.id_jugador = id_jugador\n\t\tself.nombre = nombre\n\... |
class Carta(object):
"""Representa a una carta de la baraja inglesa"""
# Constantes para los palos
CORAZONES = 0
DIAMANTES = 1
PICAS = 2
TREBOLES = 3
# Diccionarios para la impresion:
NUMEROS = ["A"] + [str(n) for n in xrange(2, 11)] + ["J", "Q", "K"]
PALOS = ['corazones', 'diamantes', 'picas', 'treboles']
def __init__(self, numero, palo):
"""Crea una carta desde su numero y su palo"""
if not 1 <= numero <= 13 or not 0 <= palo <= 3:
raise ValueError
self.palo = palo
self.numero = numero
def obtener_palo(self):
return self.palo
def obtener_numero(self):
return self.numero
def __eq__(self, otro):
return self.palo == otro.palo and self.numero == otro.numero
def __str__(self):
return "%s de %s" % (Carta.NUMEROS[self.numero - 1], Carta.PALOS[self.palo])
| [
[
3,
0,
0.5,
0.9697,
0,
0.66,
0,
238,
0,
5,
0,
0,
186,
0,
2
],
[
8,
1,
0.0606,
0.0303,
1,
0.05,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
1,
0.1515,
0.0303,
1,
0.05,
0... | [
"class Carta(object):\n\t\"\"\"Representa a una carta de la baraja inglesa\"\"\"\n\n\t# Constantes para los palos\n\tCORAZONES = 0\n\tDIAMANTES = 1\n\tPICAS = 2\n\tTREBOLES = 3",
"\t\"\"\"Representa a una carta de la baraja inglesa\"\"\"",
"\tCORAZONES = 0",
"\tDIAMANTES = 1",
"\tPICAS = 2",
"\tTREBOLES =... |
from Carta import Carta
from Mazo import Mazo
from Jugador import Jugador
class JuegoCorazones(object):
"""Clase que representa un juego de Corazones"""
def __init__(self, jugadores):
"""Crea un juego en base a 4 jugadores"""
for jugador in jugadores:
if not isinstance(jugador,Jugador):
raise TypeError
self.jugadores=jugadores
self.puntaje=[0,0,0,0]
self.puntaje_mano=[0,0,0,0]
def termino(self):
"""Devuelve True si alguno de los jugadores alcanzo los 100 puntos"""
if (self.puntaje[0] > 99) or (self.puntaje[1] > 99) or (self.puntaje[2] > 99) or (self.puntaje[3] > 99):
return True
else:
return False
def imprimir_puntajes(self):
"""Imprime los puntajes de cada jugador hasta el momento"""
print "Jugador 1(%s): %s - Jugador 2(%s): %s - Jugador 3(%s): %s - Jugador 4(%s): %s" % (self.jugadores[0],self.puntaje[0],self.jugadores[1],self.puntaje[1],self.jugadores[2],self.puntaje[2],self.jugadores[3],self.puntaje[3])
def barajar(self):
"""Crea un mazo nuevo, lo mezcla y le reparte una carta a cada jugador hasta
que el mismo queda vacio."""
mazo=Mazo()
mazo.mezclar()
while not mazo.es_vacio():
self.jugadores[0].recibir_carta(mazo.obtener_tope())
self.jugadores[1].recibir_carta(mazo.obtener_tope())
self.jugadores[2].recibir_carta(mazo.obtener_tope())
self.jugadores[3].recibir_carta(mazo.obtener_tope())
def identificar_jugador_que_inicia(self):
"""Se fija cual de los 4 jugadores es primero y devuelve su id."""
for jugador in self.jugadores:
if jugador.es_primero():
return jugador.obtener_id_jugador()
def identificar_jugador_que_perdio(self, cartas_jugadas, id_primero):
"""Recibe las 4 cartas jugadas en la mano y el id del jugador que abrio
la jugada. Devuelve el id del jugador que perdio.
Pierde el jugador que juega la carta mas alta del palo con el que inicio
la jugada el primer jugador.
Las cartas por orden creciente son: 2, 3,..., 10, J, Q, K, A."""
palo_mano=cartas_jugadas[0].obtener_palo()
mayor_num=0
for i in xrange(1,len(cartas_jugadas)):
if palo_mano==cartas_jugadas[i].obtener_palo():
if cartas_jugadas[i].obtener_numero() == 1:
mayor_num=i
elif not cartas_jugadas[mayor_num].obtener_numero()==1 and cartas_jugadas[i].obtener_numero() > cartas_jugadas[mayor_num].obtener_numero():
mayor_num=i
else:
pass
if (id_primero+mayor_num) >= 4:
return id_primero+mayor_num-4
else:
return id_primero+mayor_num
def procesar_e_informar_resultado(self, cartas_jugadas, id_primero, id_perdedor):
"""Recibe las cartas de la jugada, el id del primer jugador, y el id del
jugador que perdio.
Almacena lo necesario para llevar la cuenta de puntos e informa a todos
los jugadores del resultado de la jugada."""
if Carta(12, Carta.PICAS) in cartas_jugadas:
self.puntaje_mano[id_perdedor]+=13
for carta in cartas_jugadas:
if carta.obtener_palo() == 0:
self.puntaje_mano[id_perdedor]+=1
for jugador in self.jugadores:
jugador.conocer_jugada(cartas_jugadas,id_primero,id_perdedor)
def hay_corazones(self, cartas):
"""Devuelve True si hay algun corazon entre las cartas pasadas"""
for carta in cartas:
if carta.obtener_palo() == 0:
return True
def realizar_jugada(self, nro_mano, nro_jugada, id_primero, corazon_jugado):
"""Recibe el numero de mano, de jugada, el id del primer jugador y si ya
se jugaron corazones hasta el momento.
Hace jugar una carta a cada uno de los jugadores empezando por el primero.
Devuelve las 4 cartas jugadas."""
cartas_jugadas=[]
cont=0
for i in xrange(id_primero,4):
cartas_jugadas.append(self.jugadores[i].jugar_carta(nro_mano,nro_jugada,cartas_jugadas,corazon_jugado))
cont+=1
if cont < 4:
for i in xrange(0,4-cont):
cartas_jugadas.append(self.jugadores[i].jugar_carta(nro_mano,nro_jugada,cartas_jugadas,corazon_jugado))
return cartas_jugadas
def calcular_puntajes(self):
"""Al finalizar la mano, calcula y actualiza los puntajes de los jugadores.
Cada jugador suma un punto por cada corazon levantado en la mano y 13 puntos
si levanto la Q de picas, salvo en el caso de que un solo jugador haya
levantado todos los corazones y la Q de picas, caso en el cual todos los
jugadores salvo el suman 26 puntos."""
if 26 in self.puntaje_mano:
indice=self.puntaje_mano.index(26)
for i in xrange(4):
if not i == indice:
self.puntaje[i]+=26
else:
for i in xrange(4):
self.puntaje[i]+=self.puntaje_mano[i]
for i in xrange(4):
self.puntaje_mano[i]=0
def intercambiar_cartas(self, nro_mano):
"""Antes de hacer la primer jugada se pasan 3 cartas entre los rivales.
En la primer mano, las cartas se pasan al jugador de la izquierda; en la
segunda al jugador de la derecha; en la tercera al jugador del frente y
en la cuarta no se pasan cartas. A partir de la quinta mano, se repite el
mismo ciclo.
El metodo debe primero pedirle las 3 cartas a pasar a cada oponente y luego
entregarle las cartas que le fueron pasadas."""
izquierda=[1,5,9,13]
derecha=[2,6,10]
frente=[3,7,11]
cartas=[0,0,0,0]
if nro_mano in izquierda:
for i in xrange(1,4):
cartas[i]=self.jugadores[i].devolver_cartas_a_pasar(i-1)
cartas[0]=self.jugadores[0].devolver_cartas_a_pasar(3)
for i in xrange(2,-1,-1):
self.jugadores[i].recibir_cartas_pasadas(i+1,cartas[i+1])
self.jugadores[3].recibir_cartas_pasadas(0,cartas[0])
elif nro_mano in derecha:
for i in xrange(2,-1,-1):
cartas[i]=self.jugadores[i].devolver_cartas_a_pasar(i+1)
cartas[3]=self.jugadores[3].devolver_cartas_a_pasar(0)
for i in xrange(1,4):
self.jugadores[i].recibir_cartas_pasadas(i-1,cartas[i-1])
self.jugadores[0].recibir_cartas_pasadas(3,cartas[3])
elif nro_mano in frente:
cartas[0]=self.jugadores[0].devolver_cartas_a_pasar(2)
cartas[1]=self.jugadores[1].devolver_cartas_a_pasar(3)
cartas[2]=self.jugadores[2].devolver_cartas_a_pasar(0)
cartas[3]=self.jugadores[3].devolver_cartas_a_pasar(1)
self.jugadores[0].recibir_cartas_pasadas(2,cartas[2])
self.jugadores[2].recibir_cartas_pasadas(0,cartas[0])
self.jugadores[3].recibir_cartas_pasadas(1,cartas[1])
self.jugadores[1].recibir_cartas_pasadas(3,cartas[3])
def ganadores(self):
"""Una vez terminado el juego, devuelve la lista de ganadores.
Son ganadores todos los jugadores que hayan alcanzado el menor puntaje."""
raise NotImplementedError
def jugar_mano(self, nro_mano):
"""Realiza las 13 jugadas que corresponden a una mano completa."""
corazon_jugado = False
id_primero = self.identificar_jugador_que_inicia()
# INICIO: Chequeos de trampa
palos_faltantes = [[], [], [], []]
cartas_en_mesa = []
# FIN: Chequeos de trampa
for nro_jugada in xrange(1, 13 + 1):
print "Jugada %i" % nro_jugada
print "Empieza %s" % self.jugadores[id_primero]
cartas_jugadas = self.realizar_jugada(nro_mano, nro_jugada, id_primero, corazon_jugado)
corazon_jugado = self.hay_corazones(cartas_jugadas)
id_perdedor = self.identificar_jugador_que_perdio(cartas_jugadas, id_primero)
print "Levanta %s" % self.jugadores[id_perdedor]
self.procesar_e_informar_resultado(cartas_jugadas, id_primero, id_perdedor)
# INICIO: Chequeos de trampa
if nro_jugada == 1 and not cartas_jugadas[0] == Carta(2, Carta.TREBOLES):
raise Exception("El primer jugador no jugo el 2 de treboles""")
if nro_jugada == 1 and (corazon_jugado or Carta(12, Carta.PICAS) in cartas_jugadas):
raise Exception("Jugador jugo carta especial en primer juego""")
for i in xrange(4):
if cartas_jugadas[i].obtener_palo() in palos_faltantes[(i + id_primero) % 4]:
raise Exception("El jugador %s dijo que no tenia %s" % (self.jugadores[(i + id_primero) % 4], Carta.PALOS[cartas_jugadas[i].obtener_palo()]))
palo_jugada = cartas_jugadas[0].obtener_palo()
for i in xrange(1, 4):
if cartas_jugadas[i].obtener_palo() != palo_jugada and palo_jugada not in palos_faltantes[(i + id_primero) % 4]:
palos_faltantes[(i + id_primero) % 4].append(palo_jugada)
for carta in cartas_jugadas:
if carta in cartas_en_mesa:
raise Exception("Alguien se matufio el %s" % carta)
cartas_en_mesa.append(carta)
# FIN: Chequeos de trampa
id_primero = id_perdedor
def jugar(self):
"""Juega una partida completa de Corazones."""
nro_mano = 1
while not self.termino():
print "Mano %d" % nro_mano
self.barajar()
self.intercambiar_cartas(nro_mano)
self.jugar_mano(nro_mano)
self.calcular_puntajes()
self.imprimir_puntajes()
nro_mano += 1
martin=Jugador(0,"martin")
daniel=Jugador(1,"daniel")
gaby=Jugador(2,"gaby")
marce=Jugador(3,"marce")
juego=JuegoCorazones([martin,daniel,gaby,marce])
juego.jugar()
| [
[
1,
0,
0.0041,
0.0041,
0,
0.66,
0,
238,
0,
1,
0,
0,
238,
0,
0
],
[
1,
0,
0.0082,
0.0041,
0,
0.66,
0.1111,
240,
0,
1,
0,
0,
240,
0,
0
],
[
1,
0,
0.0122,
0.0041,
0,
... | [
"from Carta import Carta",
"from Mazo import Mazo",
"from Jugador import Jugador",
"class JuegoCorazones(object):\n\t\"\"\"Clase que representa un juego de Corazones\"\"\"\n\n\tdef __init__(self, jugadores):\n\t\t\"\"\"Crea un juego en base a 4 jugadores\"\"\"\n\t\t\n\t\tfor jugador in jugadores:\n\t\t\tif no... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.