Simon Van Mierlo 6 jaren geleden
bovenliggende
commit
d389d3e79c

+ 2 - 0
.gitignore

@@ -1,3 +1,5 @@
+.idea/*
+
 *.pyc
 .metadata*
 *.dll

+ 9 - 5
examples/tanks/AIMap.py

@@ -1,6 +1,6 @@
 from random import choice
 import heapq
-from mymath import D60, D105, D360
+from examples.tanks.mymath import D60, D105, D360
 import math
 
 FREE, OBSTACLE = range(2)    
@@ -14,7 +14,7 @@ class AIMap():
         obstacleMap = level.structure
         self.cellsX = self.totalWidth // self.cellSize
         self.cellsY = self.totalHeight // self.cellSize
-        self.structure = [[ OBSTACLE if obstacleMap[x][y] else FREE for y in xrange(self.cellsY)] for x in xrange(self.cellsX)]     
+        self.structure = [[ OBSTACLE if obstacleMap[x][y] else FREE for y in range(self.cellsY)] for x in range(self.cellsX)]
         
     def getNewExplore(self, position, tankAngle):
         cell = self.calculateCell(position)
@@ -44,8 +44,9 @@ class AIMap():
         return self.calculateCoords(choice(result))
         
         
-    def getSuccessors(self, (xpos,ypos)):
+    def getSuccessors(self, pos):
         successors = []
+        (xpos, ypos) = pos
         i = 0
         for y in range(ypos-1,ypos+2):
             for x in range(xpos-1,xpos+2):
@@ -66,13 +67,16 @@ class AIMap():
                             if self.structure[x-1][y] == FREE and self.structure[x][y-1] == FREE : successors.append(((x,y),1.4))
         return successors
 
-    def calculateCell(self, (xp,yp)):
+    def calculateCell(self, p):
+        (xp, yp) = p
         return ( int(xp / self.cellSize) , int(yp / self.cellSize) )
         
     def calculateCoords(self,cell):
         return (self.cellSize * (cell[0]+0.5),self.cellSize * (cell[1]+0.5))
     
-    def getAngleToDest(self,(xpos,ypos),(xdes,ydes)):        
+    def getAngleToDest(self,pos, des):
+        (xpos, ypos) = pos
+        (xdes, ydes) = des
         return math.atan2(ypos-ydes, xdes-xpos) % D360
     
     #------PathFinding----#

+ 1 - 1
examples/tanks/Level.py

@@ -9,7 +9,7 @@ class Level():
         self.canvas = field.canvas
         self.cellsX = self.totalWidth // self.cellSize
         self.cellsY = self.totalHeight // self.cellSize
-        self.structure = [[0 for x in xrange(self.cellsY)] for x in xrange(self.cellsX)] 
+        self.structure = [[0 for x in range(self.cellsY)] for x in range(self.cellsX)]
         self.obstacles = []
         
     def addObstacles(self, obstacle_list):

+ 10 - 4
src/python_sccd/python_sccd_compiler/generic_language_constructs.py

@@ -727,10 +727,16 @@ class NoneExpression(SimpleExpression):
 # helpers
 
 def MakeExpression(expr):
+
+	try:
+		if isinstance(expr, basestring):
+			return Literal(expr)
+	except NameError:
+		if isinstance(expr, str):
+			return Literal(expr)
+
 	if isinstance(expr, Expression):
 		return expr
-	elif isinstance(expr, basestring):
-		return Literal(expr)
 	elif expr is None:
 		return None
 	else:
@@ -746,7 +752,7 @@ def MakeExpressionList(l):
 def MakeExpressionMap(m):
 	if not isinstance(m, dict):
 		raise Exception("Expected argument of type 'dict'.")
-	for key in m.keys():
+	for key in list(m.keys()):
 		m[key] = MakeExpression(m[key])
 	return m
 
@@ -764,7 +770,7 @@ def MakeDeclaration(obj):
 	if isinstance(obj, DeclarationBase):
 		return obj
 	else:
-		raise Exception("Can't turn argument of type '" + str(type(stmt)) + "' into DeclarationBase.")
+		raise Exception("Can't turn argument of type '" + str(type(obj)) + "' into DeclarationBase.")
 
 def MakeActualParameters(obj):
 	if isinstance(obj, ActualParameters):

+ 1 - 1
src/python_sccd/python_sccd_compiler/javascript_writer.py

@@ -158,7 +158,7 @@ class JavascriptWriter(CLikeWriterBase):
             self.out.extendWrite("new Object()")
         else:
             self.out.extendWrite("{")
-            keys = elements.keys()
+            keys = list(elements.keys())
             for i in range(len(keys)):
                 if i != 0:
                     self.out.extendWrite(", ")            

+ 1 - 1
src/python_sccd/python_sccd_compiler/python_writer.py

@@ -201,7 +201,7 @@ class PythonWriter(GenericWriterBase):
 	def visit_MapExpression(self, m):
 		elements = m.getElements()
 		self.out.extendWrite("{")
-		keys = elements.keys()
+		keys = list(elements.keys())
 		for i in range(len(keys)):
 			if i != 0:
 				self.out.extendWrite(", ")			

+ 14 - 4
src/python_sccd/python_sccd_compiler/sccd_constructs.py

@@ -875,7 +875,11 @@ class Class(Visitable):
         for i in inheritances :
             self.super_classes.append((i.get("class",""),i.get("priority",1)))
 
-        self.super_classes.sort(lambda a, b: cmp(b[1], a[1])) # sort from high priority to low priority
+        try:
+            self.super_classes.sort(lambda a, b: cmp(b[1], a[1])) # sort from high priority to low priority
+        except TypeError:
+            self.super_classes = sorted(self.super_classes, key=lambda x: x[1], reverse = True)
+
         priorityChecker = {}
         for super_class, priority in self.super_classes:
             if priority in priorityChecker:
@@ -885,7 +889,8 @@ class Class(Visitable):
             if super_class not in checkIt:
                 checkIt.append(super_class)
             priorityChecker[priority] = checkIt
-        for priority, checkIt in priorityChecker.iteritems():
+
+        for priority, checkIt in list(priorityChecker.items()):
             if len(checkIt) > 1:
                 Logger.showWarning("Class <" + self.name + "> inherits from classes <" + ", ".join(checkIt) + "> with same priority <" + str(priority) + ">. Document inheritance order is used.")
 
@@ -1010,6 +1015,7 @@ class ClassDiagram(Visitable):
         # unique class names
         self.class_names = []
         substituted_xml_classes = []
+        default_substituted_xml_classes = []
         for xml_class in xml_classes :
             class_src = xml_class.get("src", "")
             class_default = xml_class.get("default", "")
@@ -1019,7 +1025,10 @@ class ClassDiagram(Visitable):
                 substituted_xml_class = ET.parse(class_src).getroot()
             else:
                 substituted_xml_class = xml_class
-            substituted_xml_class.is_default = (class_default.lower() == "true")
+
+            if class_default.lower() == "true":
+                default_substituted_xml_classes.append(substituted_xml_class)
+
             name = substituted_xml_class.get("name", "")
             if name == "" :
                 raise CompilerException("Missing or emtpy class name.")
@@ -1073,7 +1082,8 @@ class ClassDiagram(Visitable):
             # let user know this class was successfully loaded
             Logger.showInfo("Class <" + processed_class.name + "> has been successfully loaded.")
             self.classes.append(processed_class)
-            if xml_class.is_default :
+
+            if xml_class in default_substituted_xml_classes:
                 default_classes.append(processed_class)
             
         if not default_classes or len(default_classes) > 1:

+ 1 - 1
src/python_sccd/python_sccd_compiler/super_class_linker.py

@@ -27,7 +27,7 @@ class SuperClassLinker(Visitor):
 		c.abstract_method_names = getClassAbstractMethodNames(c)
 
 		# check if <super> tags exist for all inherited classes
-		for name,obj in c.super_class_objs.iteritems():
+		for name,obj in list(c.super_class_objs.items()):
 			if obj:
 				if name not in c.constructors[0].super_class_parameters:
 					num_params = len(obj.constructors[0].parameters)

+ 3 - 3
src/python_sccd/python_sccd_compiler/utils.py

@@ -11,17 +11,17 @@ class Logger(object):
 	@staticmethod   
 	def showError(error):
 		if(Logger.verbose > -1) :
-			print "ERROR : " + error
+			print("ERROR : " + error)
 				
 	@staticmethod
 	def showWarning(warning):
 		if(Logger.verbose > 0) :
-			print "WARNING : " + warning
+			print("WARNING : " + warning)
 			
 	@staticmethod	
 	def showInfo(info):
 		if(Logger.verbose > 1) :
-			print "INFO : " + info
+			print("INFO : " + info)
 
 #######################
 

+ 1 - 1
src/python_sccd/python_sccd_runtime/libs/ordered_set.py

@@ -163,7 +163,7 @@ class OrderedSet(collections.MutableSet):
             i = self.items.index(key)
             del self.items[i]
             del self.map[key]
-            for k, v in self.map.items():
+            for k, v in list(self.map.items()):
                 if v >= i:
                     self.map[k] = v - 1
 

+ 8 - 3
src/python_sccd/python_sccd_runtime/libs/ui.py

@@ -7,9 +7,14 @@
  Date: 2014/08/21
 """
 
-import Tkinter as tk
-from drawing import drawing
-from utils import utils
+
+try:
+    import Tkinter as tk
+except ImportError:
+    import tkinter as tk
+
+from src.python_sccd.python_sccd_runtime.libs.drawing import drawing
+from src.python_sccd.python_sccd_runtime.libs.utils import utils
 
 from sccd.runtime.statecharts_core import Event
 

+ 2 - 2
src/python_sccd/python_sccd_runtime/libs/utils.py

@@ -15,5 +15,5 @@ class utils:
 			after:  d['a'] = d.a
 	"""
 	class _bunch:
-  		def __init__(self, **kwds):
- 			self.__dict__.update(kwds)
+		def __init__(self, **kwds):
+			self.__dict__.update(kwds)

+ 7 - 1
src/python_sccd/python_sccd_runtime/socket2event.py

@@ -13,6 +13,7 @@ thread, you will need to start the code by running
 import threading
 from sccd.runtime.statecharts_core import Event
 import socket
+import sys
 
 send_data_queues = {}
 send_events = {}
@@ -51,7 +52,12 @@ def send_to_socket(controller, sock, data_queue, send_event):
         send_event.wait()
         send_event.clear()
         while data_queue:
-            send = sock.send(data_queue.pop(0))
+            data = data_queue.pop(0)
+            if sys.version_info[0] > 2:
+                if isinstance(data, str):
+                    data = data.encode()
+            send = sock.send(data)
+
             controller.addInput(Event("sent_socket", "socket_in", [sock, send]))
         if not run_sockets[sock]:
             break

+ 42 - 11
src/python_sccd/python_sccd_runtime/statecharts_core.py

@@ -5,22 +5,37 @@ The classes and functions needed to run (compiled) SCCD models.
 import abc
 import re
 import threading
-import thread
+import sys
+
+try:
+    import thread
+except ImportError:
+    import threading as thread
+
 import traceback
 import math
 from heapq import heappush, heappop, heapify
-from infinity import INFINITY
-from Queue import Queue, Empty 
+try:
+    from sccd.runtime.infinity import INFINITY
+except ImportError:
+    from infinity import INFINITY
+
+try:
+    from queue import Queue, Empty
+except ImportError:
+    from Queue import Queue, Empty
 
 from sccd.runtime.event_queue import EventQueue
 from sccd.runtime.accurate_time import AccurateTime
 
+from time import time
+
 DEBUG = False
 ELSE_GUARD = "ELSE_GUARD"
 
 def print_debug(msg):
     if DEBUG:
-        print msg
+        print(msg)
 
 class RuntimeException(Exception):
     """
@@ -393,6 +408,11 @@ class Event(object):
         self.parameters = parameters
         self.port = port
 
+    #for comparisons in heaps
+    def __lt__(self, other):
+        s = str(self.name) + str(self.parameters) + str(self.port)
+        return len(s)
+
     def getName(self):
         return self.name
 
@@ -703,7 +723,7 @@ class ThreadsControllerBase(ControllerBase):
                 if self.behind:                
                     self.behind = False
                 with self.input_condition:
-                    if earliest_event_time == self.getEarliestEventTime():
+                    if earliest_event_time == self.getEarliestEventTime() and not earliest_event_time == INFINITY:
                         self.input_condition.wait((earliest_event_time - now) / 1000.0)
                     else:
                         # Something happened that made the queue fill up already, but we were not yet waiting for the Condition...
@@ -882,7 +902,7 @@ class Transition:
                 f = lambda s0: s0.ancestors and s0.parent == s
                 if isinstance(h, DeepHistoryState):
                     f = lambda s0: not s0.descendants and s0 in s.descendants
-                self.obj.history_values[h.state_id] = filter(f, self.obj.configuration)
+                self.obj.history_values[h.state_id] = list(filter(f, self.obj.configuration))
         for s in exit_set:
             print_debug('EXIT: %s::%s' % (self.obj.__class__.__name__, s.name))
             self.obj.eventless_states -= s.has_eventless_transitions
@@ -918,7 +938,7 @@ class Transition:
         try:
             self.obj.configuration = self.obj.config_mem[self.obj.configuration_bitmap]
         except:
-            self.obj.configuration = self.obj.config_mem[self.obj.configuration_bitmap] = sorted([s for s in self.obj.states.itervalues() if 2**s.state_id & self.obj.configuration_bitmap], key=lambda s: s.state_id)
+            self.obj.configuration = self.obj.config_mem[self.obj.configuration_bitmap] = sorted([s for s in list(self.obj.states.values()) if 2**s.state_id & self.obj.configuration_bitmap], key=lambda s: s.state_id)
         self.enabled_event = None
     
     def __getEffectiveTargetStates(self):
@@ -991,6 +1011,11 @@ class RuntimeClassBase(object):
 
         self.semantics = StatechartSemantics()
 
+    #to break ties in the heap,
+    #compare by number of events in the list
+    def __lt__(self, other):
+        return len(self.events.event_list) < len(other.events.event_list)
+
     def start(self):
         self.configuration = []
         
@@ -1076,7 +1101,7 @@ class RuntimeClassBase(object):
                 due = [self.events.pop()]
             is_stable = not self.bigStep(due)
             self.processBigStepOutput()
-        for index, entry in self.timers_to_add.iteritems():
+        for index, entry in list(self.timers_to_add.items()):
             self.timers[index] = self.events.add(*entry)
         self.timers_to_add = {}
         self.__set_stable(True)
@@ -1106,7 +1131,7 @@ class RuntimeClassBase(object):
         while self.smallStep():
             self.combo_step.has_stepped = True
         return self.combo_step.has_stepped
-	
+
     # generate transition candidates for current small step
     # @profile
     def generateCandidates(self):
@@ -1121,7 +1146,7 @@ class RuntimeClassBase(object):
         enabledTransitions = []
         for t in transitions:
             if t.isEnabled(enabledEvents, enabledTransitions):
-				enabledTransitions.append(t)
+                enabledTransitions.append(t)
         return enabledTransitions
 
     # @profile
@@ -1147,7 +1172,13 @@ class RuntimeClassBase(object):
                         if c2.source in c1.source.ancestors or c1.source in c2.source.ancestors:
                             conflict.append(c2)
                             to_skip.add(c2)
-                    conflicting.append(sorted(conflict, cmp=__younger_than))
+
+                    if sys.version_info[0] < 3:
+                        conflicting.append(sorted(conflict, cmp=__younger_than))
+                    else:
+                        import functools
+                        conflicting.append(sorted(conflict, key=functools.cmp_to_key(__younger_than)))
+
             if self.semantics.concurrency == StatechartSemantics.Single:
                 candidate = conflicting[0]
                 if self.semantics.priority == StatechartSemantics.SourceParent:

+ 3 - 0
src/setup.sh

@@ -0,0 +1,3 @@
+python2 setup.py install --user
+python3 setup.py install --user
+pypy setup.py install --user

+ 1 - 1
test/run_tests.py

@@ -55,7 +55,7 @@ class PyTestCase(unittest.TestCase):
                     compare_parameters = output_event.getParameters()
                     if len(entry.parameters) != len(compare_parameters) :
                         matches = False
-                    for index in xrange(len(entry.parameters)) :
+                    for index in range(len(entry.parameters)) :
                         if entry.parameters[index] !=  compare_parameters[index]:
                             matches = False
 

File diff suppressed because it is too large
+ 1286 - 1286
textualnotations/bouncing_balls.py


File diff suppressed because it is too large
+ 1286 - 1286
textualnotations/launcher_examples/bouncing_balls.py


+ 18 - 18
textualnotations/mvk_loader.py

@@ -101,15 +101,15 @@ class ClassRepresenter(object):
 	def store(self, context, target):
 
 		location = context.location + '.' + self.name
- 		self.create(context.mvk, MappingValue({CreateConstants.TYPE_KEY: LocationValue(location),
- 			CreateConstants.LOCATION_KEY: LocationValue(target),
- 			CreateConstants.ATTRS_KEY: MappingValue(
- 				self.buildDict(context.mvk, target, location, self.body)
- 			)}))
+		self.create(context.mvk, MappingValue({CreateConstants.TYPE_KEY: LocationValue(location),
+			CreateConstants.LOCATION_KEY: LocationValue(target),
+			CreateConstants.ATTRS_KEY: MappingValue(
+				self.buildDict(context.mvk, target, location, self.body)
+			)}))
 
- 		key = self.getIdField(context, target, location)
- 		element = target + '.' + str(self.body[key])
- 		self.classname = element
+		key = self.getIdField(context, target, location)
+		element = target + '.' + str(self.body[key])
+		self.classname = element
 
 	def getNthOfType(self, context, index, typename):
 		searchid = 0
@@ -304,14 +304,14 @@ class ModelRepresenter(ClassRepresenter):
 
 	def store(self, context, target):
 		location = context.location
- 		self.create(context.mvk, MappingValue({CreateConstants.TYPE_KEY: LocationValue(location),
- 			CreateConstants.LOCATION_KEY: LocationValue(target),
- 			CreateConstants.ATTRS_KEY: MappingValue(
- 				self.buildDict(context.mvk, target, location, self.body)
- 			)}))
+		self.create(context.mvk, MappingValue({CreateConstants.TYPE_KEY: LocationValue(location),
+			CreateConstants.LOCATION_KEY: LocationValue(target),
+			CreateConstants.ATTRS_KEY: MappingValue(
+				self.buildDict(context.mvk, target, location, self.body)
+			)}))
 
- 		key = self.getIdField(context, target, location)
- 		self.modelname = str(self.body[key])
+		key = self.getIdField(context, target, location)
+		self.modelname = str(self.body[key])
 
 class AssociationRepresenter(ClassRepresenter):
 	def __init__(self, name, body, fromid, toid):
@@ -355,9 +355,9 @@ class AssociationRepresenter(ClassRepresenter):
 					})
 
 
- 		self.create(context.mvk, MappingValue({CreateConstants.TYPE_KEY: LocationValue(location),
- 			CreateConstants.LOCATION_KEY: LocationValue(target),
- 			CreateConstants.ATTRS_KEY: MappingValue(values)}))
+		self.create(context.mvk, MappingValue({CreateConstants.TYPE_KEY: LocationValue(location),
+			CreateConstants.LOCATION_KEY: LocationValue(target),
+			CreateConstants.ATTRS_KEY: MappingValue(values)}))