OP-1516 fixed boundf mistake
[librepilot.git] / flight / libraries / PyMite / tools / bcode.py
blobf8ad8a5fad8672a0341da8116c4cfafe9dc6493f
1 #!/usr/bin/env python
3 # This file is Copyright 2003, 2006, 2007, 2009, 2010 Dean Hall.
5 # This file is part of the Python-on-a-Chip program.
6 # Python-on-a-Chip is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU LESSER GENERAL PUBLIC LICENSE Version 2.1.
8 #
9 # Python-on-a-Chip is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12 # A copy of the GNU LESSER GENERAL PUBLIC LICENSE Version 2.1
13 # is seen in the file COPYING in this directory.
15 """
16 Python Byte Code utility functions.
18 count(fn) - count the number of times each byte code
19 appears in a code object.
20 """
22 ## @file
23 # @copybrief bcode
25 ## @package bcode
26 # @brief Python Byte Code utility functions.
28 # count(fn) - count the number of times each byte code
29 # appears in a code object.
33 import dis, types
36 #The highest numbered byte code
37 MAX_BCODE = 150
40 def count(fn):
41 """
42 Compile the python source file named fn.
43 Count all the bytecodes in the file.
44 Return a list of counts indexed by bcode.
45 """
47 #create a code object
48 src = open(fn).read()
49 co = compile(src, fn, "exec")
51 #init list
52 cnt = [0,] * MAX_BCODE
54 #iterate through the nested code objects
55 _rcount(co, cnt)
57 return cnt
60 def _rcount(co, count):
61 """
62 Recursively descend through all the code objects
63 in the given code object, co.
64 Add byte code counts to the count dict.
65 """
66 #current byte code string
67 str = co.co_code
68 strlen = len(str)
70 #count byte codes in current string
71 i = 0
72 while i < strlen:
73 bcode = ord(str[i])
74 i += 1
75 #incr count
76 count[bcode] += 1
78 #if bcode has arg, incr ptr by 2 bytes
79 if bcode >= 90:
80 i += 2
82 #count code objects in constant pool
83 for obj in co.co_consts:
84 if type(obj) == types.CodeType:
85 _rcount(obj, count)
87 return
90 def main(fn):
91 """
92 Count the bytecodes in the file, fn,
93 and print them out in human-readable form.
94 """
95 #count the bytecodes in this file
96 c = count(fn)
98 #print bcode name and count
99 for i in range(len(c)):
100 if c[i]:
101 print dis.opname[i], ":\t", c[i]
102 return
105 if __name__ == "__main__":
106 main("c:\\dwh\\tech\\cis\\py\\snap.py")