aboutsummaryrefslogtreecommitdiffstats
path: root/tools/xmlGenerator/PFWScriptGenerator.py
blob: 17640d08274bcc3093ce12fe88a4f4a152c604bb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
#!/usr/bin/python2
# -*-coding:utf-8 -*

# INTEL CONFIDENTIAL
# Copyright  2013 Intel
# Corporation All Rights Reserved.
#
# The source code contained or described herein and all documents related to
# the source code ("Material") are owned by Intel Corporation or its suppliers
# or licensors. Title to the Material remains with Intel Corporation or its
# suppliers and licensors. The Material contains trade secrets and proprietary
# and confidential information of Intel or its suppliers and licensors. The
# Material is protected by worldwide copyright and trade secret laws and
# treaty provisions. No part of the Material may be used, copied, reproduced,
# modified, published, uploaded, posted, transmitted, distributed, or
# disclosed in any way without Intels prior express written permission.
#
# No license under any patent, copyright, trade secret or other intellectual
# property right is granted to or conferred upon you by disclosure or delivery
# of the Materials, either expressly, by implication, inducement, estoppel or
# otherwise. Any license under such intellectual property rights must be
# express and approved by Intel in writing.


import re
import sys
import copy
import imp
from itertools import izip
from itertools import imap

try:
    import argparse
except ImportError:
    import optparse

# =====================================================================
""" Context classes, used during propagation and the "to PFW script" step """
# =====================================================================

class PropagationContextItem(list) :
    """Handle an item during the propagation step"""
    def __copy__(self):
        """C.__copy__() -> a shallow copy of C"""
        return self.__class__(self)

class PropagationContextElement(PropagationContextItem) :
    """Handle an Element during the propagation step"""
    def getElementsFromName(self, name):
        matchingElements = []
        for element in self :
            if element.getName() == name :
                matchingElements.append(element)
        return matchingElements


class PropagationContextOption(PropagationContextItem) :
    """Handle an Option during the propagation step"""
    def getOptionItems (self, itemName):
        items = []
        for options in self :
            items.append(options.getOption(itemName))
        return items


class PropagationContext() :
    """Handle the context during the propagation step"""
    def __init__(self, propagationContext=None) :

        if propagationContext == None :
            self._context = {
                "DomainOptions" : PropagationContextOption() ,
                "Configurations" : PropagationContextElement() ,
                "ConfigurationOptions" : PropagationContextOption() ,
                "Rules" : PropagationContextElement() ,
                "PathOptions" : PropagationContextOption() ,
        }
        else :
            self._context = propagationContext

    def copy(self):
        """return a copy of the context"""
        contextCopy = self._context.copy()

        for key in iter(self._context) :
            contextCopy[key] = contextCopy[key].__copy__()

        return self.__class__(contextCopy)

    def getDomainOptions (self):
        return self._context["DomainOptions"]

    def getConfigurations (self):
        return self._context["Configurations"]

    def getConfigurationOptions (self):
        return self._context["ConfigurationOptions"]

    def getRules (self):
        return self._context["Rules"]

    def getPathOptions (self):
        return self._context["PathOptions"]

# ---------------------------------------------------------------------------

class PFWScriptContext ():
    """handle the context during the PFW script generation"""

    def __init__(self, prefixIncrease="    ") :
        self._context = {
            "Prefix" : "" ,
            "DomainName" : "" ,
            "ConfigurationName" : "" ,
            "SequenceAwareness" : False ,
        }
        self._prefixIncrease = prefixIncrease

    def increasePrefix(self) :
        self._context["Prefix"] = self._prefixIncrease + self._context["Prefix"]

    def getNewLinePrefix(self) :
        """return a prefix with decorative new line

        return r"\"+"\n"+" "*increased prefix length"""
        return "\\\n" + self._prefixIncrease + " "* len(self.getPrefix())

    def copy(self) :
        copy = PFWScriptContext ()
        copy._context = self._context.copy()
        return copy

    def setDomainName (self, name) :
        self._context["DomainName"] = name

    def setConfigurationName (self, name) :
        self._context["ConfigurationName"] = name

    def setSequenceAwareness (self, sequenceAwareness) :
        self._context["SequenceAwareness"] = sequenceAwareness

    def getPrefix(self):
        return self._context["Prefix"]

    def getDomainName (self):
        return self._context["DomainName"]

    def getConfigurationName(self):
        return self._context["ConfigurationName"]

    def getSequenceAwareness(self):
        return self._context["SequenceAwareness"]

# =====================================================
"""Element option container"""
# =====================================================

class Options () :
    """handle element options"""
    def __init__(self, options=[], optionNames=[]) :
        self.options = dict(izip(optionNames, options))
        # print(options,optionNames,self.options)


    def __str__(self) :
        ops2str = []
        for name, argument in self.options.items() :
            ops2str.append(str(name) + "=\"" + str(argument) + "\"")

        return " ".join(ops2str)

    def getOption(self, name):
        """get option by its name, if it does not exist return empty string"""
        return self.options.get(name, "")

    def setOption(self, name, newOption):
        """set option by its name"""
        self.options[name] = newOption

    def copy (self):
        """D.copy() -> a shallow copy of D"""
        copy = Options()
        copy.options = self.options.copy()
        return copy

# ====================================================
"""Definition of all element class"""
# ====================================================

class Element(object):
    """ implement a basic element

    It is the class base for all other elements as Domain, Configuration..."""
    tag = "unknown"
    optionNames = ["Name"]
    childWhiteList = []
    optionDelimiter = " "

    def __init__(self, line=None) :

        if line == None :
            self.option = Options([], self.optionNames)
        else :
            self.option = self.optionFromLine(line)

        self.children = []

    def optionFromLine(self, line) :
        # get ride of spaces
        line = line.strip()

        options = self.extractOptions(line)

        return Options(options, self.optionNames)

    def extractOptions(self, line) :
        """return the line splited by the optionDelimiter atribute

        Option list length is less or equal to the optionNames list length
        """
        options = line.split(self.optionDelimiter, len(self.optionNames) - 1)

        # get ride of leftover spaces
        optionsStrip = list(imap(str.strip, options))

        return optionsStrip

    def addChild(self, child, append=True) :
        """ A.addChid(B) -> add B to A child list if B class name is in A white List"""
        try:
            # Will raise an exception if this child is not in the white list
            self.childWhiteList.index(child.__class__.__name__)
            # If no exception was raised, add child to child list

            if append :
                self.children.append(child)
            else :
                self.children.insert(0, child)

        except ValueError:
            # the child class is not in the white list
            raise ChildNotPermitedError("", self, child)

    def addChildren(self, children, append=True) :
        """Add a list of child"""
        if append:
            # Add children at the end of the child list
            self.children.extend(children)
        else:
            # Add children at the begining of the child list
            self.children = children + self.children

    def childrenToXML(self, prefix=""):
        """return XML printed children"""
        body = ""
        for child in  self.children :
            body = body + child.toXML(prefix)

        return body

    def childrenToString(self, prefix=""):
        """return raw printed children """
        body = ""
        for child in self.children :
            body = body + child.__str__(prefix)

        return body

    def __str__(self, prefix="") :
        """return raw printed element"""
        selfToString = prefix + " " + self.tag + " " + str(self.option)
        return selfToString + "\n" + self.childrenToString(prefix + "\t")

    def toXML(self, prefix="") :
        """return XML printed element"""
        # full = begin:"<tag options" + body:children.toXML + end:"</tag>"
        begin = prefix + "<" + self.tag + " " + str(self.option)
        body = self.childrenToXML(prefix + "\t")

        if body == "" :
            full = begin + "/>"
        else :
            end = prefix + "</" + self.tag + ">"
            full = begin + ">\n" + body + end

        return full + "\n"

    def extractChildrenByClass(self, classTypeList) :
        """return all children whose class is in the list argument

        return a list of all children whose class in the list "classTypeList" (second arguments)"""
        selectedChildren = []

        for child in  self.children :
            for classtype in classTypeList :
                if child.__class__ == classtype :
                    selectedChildren.append(child)
                    break
        return selectedChildren

    def propagate (self, context=PropagationContext()):
        """call the propagate method of all children"""
        for child in  self.children :
            child.propagate(context)

    def getName(self):
        """return name option value. If none return "" """
        return self.option.getOption("Name")

    def setName(self, name):
        self.option.setOption("Name", name)

    def toPFWScript (self, context=PFWScriptContext()) :
        script = ""
        for child in  self.children :
            script += child.toPFWScript(context)
        return script


# ----------------------------------------------------------

class ElementWithTag (Element):
    """Element of this class are declared with a tag  => line == "tag: .*" """
    def extractOptions(self, line) :
        lineWithoutTag = line.split(":", 1)[-1].strip()
        options = super(ElementWithTag, self).extractOptions(lineWithoutTag)
        return options

# ----------------------------------------------------------

class ElementWithInheritance(Element):
    def propagate (self, context=PropagationContext) :
        """propagate some proprieties to children"""

        # copy the context so that everything that hapend next will only affect
        # children
        contextCopy = context.copy()

        # check for inheritance
        self.Inheritance(contextCopy)

        # call the propagate method of all children
        super(ElementWithInheritance, self).propagate(contextCopy)


class ElementWithRuleInheritance(ElementWithInheritance):
    """class that will give to its children its rules"""
    def ruleInheritance(self, context):
        """Add its rules to the context and get context rules"""

        # extract all children rule and operator
        childRules = self.extractChildrenByClass([Operator, Rule])

        # get context rules
        contextRules = context.getRules()

        # adopt rules of the beginning of the context
        self.addChildren(contextRules, append=False)

        # add previously extract rules to the context
        contextRules += childRules


# ----------------------------------------------------------

class EmptyLine (Element) :
    """This class represents an empty line.

    Will raise "EmptyLineWarning" exception at instanciation."""

    tag = "emptyLine"
    match = re.compile(r"[ \t]*\n?$").match
    def __init__ (self, line):
       raise EmptyLineWarning(line)

# ----------------------------------------------------------

class Commentary(Element):
    """This class represents a commentary.

    Will raise "CommentWarning" exception at instanciation."""

    tag = "commentary"
    optionNames = ["comment"]
    match = re.compile(r"#").match
    def __init__ (self, line):
       raise CommentWarning(line)

# ----------------------------------------------------------

class Path (ElementWithInheritance) :
    """class implementing the "path = value" concept"""
    tag = "path"
    optionNames = ["Name", "value"]
    match = re.compile(r".+=").match
    optionDelimiter = "="
    PFWCommandParameter = "setParameter"

    def toPFWScript (self, context=PFWScriptContext()) :

        return context.getPrefix() + \
                self.PFWCommandParameter + " " + \
                self.getName() + " '" + \
                self.option.getOption("value") + "'\n"

    def Inheritance (self, context) :
        """check for path name inheritance"""
        self.OptionsInheritance(context)

    def OptionsInheritance (self, context) :
        """make configuration name inheritance """

        context.getPathOptions().append(self.option.copy())
        self.setName("/".join(context.getPathOptions().getOptionItems("Name")))


class GroupPath (Path, ElementWithTag) :
    tag = "component"
    match = re.compile(tag + r" *:").match
    optionNames = ["Name"]
    childWhiteList = ["Path", "GroupPath"]

    def toPFWScript (self, pfwScriptContext) :
        script = ""

        configurationChildren = self.extractChildrenByClass([GroupPath, Path])

        for configurationChild in configurationChildren :
            # add configuration settings
            script += configurationChild.toPFWScript(pfwScriptContext)

        return script

    def getPathNames (self) :
        """Return the list of all path child name"""

        pathNames = []

        paths = self.extractChildrenByClass([Path])
        for path in paths :
            pathNames.append(path.getName())

        groupPaths = self.extractChildrenByClass([GroupPath])
        for groupPath in groupPaths :
            pathNames += groupPath.getPathNames()

        return pathNames

# ----------------------------------------------------------

class Rule (Element) :
    """class implementing the rule concept

    A rule is composed of a criterion, a rule type and an criterion state.
    It should not have any child and is propagated to all configuration in parent descendants.
    """

    tag = "rule"
    optionNames = ["criterion", "type", "element"]
    match = re.compile(r"[a-zA-Z0-9_.]+ +(Is|IsNot|Includes|Excludes) +[a-zA-Z0-9_.]+").match
    childWhiteList = []

    def PFWSyntax (self, prefix=""):

        script = prefix + \
                    self.option.getOption("criterion") + " " + \
                    self.option.getOption("type") + " " + \
                    self.option.getOption("element")

        return script


class Operator (Rule) :
    """class implementing the operator concept

    An operator contains rules and other operators
    It is as rules propagated to all configuration children in parent descendants.
    It should only have the name ANY or ALL to be understood by PFW.
    """

    tag = "operator"
    optionNames = ["Name"]
    match = re.compile(r"ANY|ALL").match
    childWhiteList = ["Rule", "Operator"]

    PFWCommandRule = "setRule"
    syntax = { "ANY" : "Any" , "ALL" : "All"}

    def toPFWScript (self, context) :
        """ return a pfw commands generated from him and its child options"""
        script = ""

        # add the command name (setRule)
        script += context.getPrefix() + \
                    self.PFWCommandRule + " " + \
                    context.getDomainName() + " " + \
                    context.getConfigurationName() + " "

        # add the rule
        script += self.PFWSyntax (context.getNewLinePrefix())

        script += "\n"

        return script

    def PFWSyntax (self, prefix=""):
        """ return a pfw rule (ex : "Any{criterion1 is state1}") generated from "self" and its children options"""
        script = ""

        script += prefix + \
                    self.syntax[self.getName()] + "{ "

        rules = self.extractChildrenByClass([Rule, Operator])

        PFWRules = []
        for rule in rules :
            PFWRules.append(rule.PFWSyntax(prefix + "    "))

        script += (" , ").join(PFWRules)

        script += prefix + " }"

        return script

# ----------------------------------------------------------

class Configuration (ElementWithRuleInheritance, ElementWithTag) :
    tag = "configuration"
    optionNames = ["Name"]
    match = re.compile(r"conf *:").match
    childWhiteList = ["Rule", "Operator", "Path", "GroupPath"]

    PFWCommandConfiguration = "createConfiguration"
    PFWCommandElementSequence = "setElementSequence"
    PFWCommandSequenceAware = "setSequenceAwareness"

    PFWCommandRestoreConfiguration = "restoreConfiguration"
    PFWCommandSaveConfiguration = "saveConfiguration"

    def composition (self, context):
        """make all needed composition

        Composition is the fact that group configuration with the same name defined
        in a parent will give their rule children to this configuration
        """

        name = self.getName()
        sameNameConf = context.getConfigurations().getElementsFromName(name)

        sameNameConf.reverse()

        for configuration in sameNameConf :
            # add same name configuration rule children to self child list
            self.addChildren(configuration.extractChildrenByClass([Operator, Rule]), append=False)


    def propagate (self, context=PropagationContext) :
        """propagate proprieties to children

        make needed compositions, join ancestor name to its name,
        and add rules previously defined rules"""

        # make all needed composition
        self.composition(context)

        super(Configuration, self).propagate(context)

    def Inheritance (self, context) :
        """make configuration name and rule inheritance"""
        # check for configuration name inheritance
        self.OptionsInheritance(context)

        # check for rule inheritance
        self.ruleInheritance(context)

    def OptionsInheritance (self, context) :
        """make configuration name inheritance """

        context.getConfigurationOptions().append(self.option.copy())
        self.setName(".".join(context.getConfigurationOptions().getOptionItems("Name")))


    def getRootPath (self) :

        paths = self.extractChildrenByClass([Path, GroupPath])

        rootPath = GroupPath()
        rootPath.addChildren(paths)

        return rootPath

    def getConfigurableElements (self) :
        """return all path name defined in this configuration"""

        return self.getRootPath().getPathNames()

    def toPFWScript(self, pfwScriptContext) :
        """Output the PFW commands needed to recreate this configuration

        The PFW commands outputed will recreate this configuration if run
        on a PFW instance"""

        script = ""

        # Copy and update pfwScriptContext for this configuration
        pfwScriptContextAux = pfwScriptContext.copy()
        pfwScriptContextAux.setConfigurationName (self.getName())

        # Add the command to create the configuration
        script += pfwScriptContextAux.getPrefix() + \
                    self.PFWCommandConfiguration + " " + \
                    pfwScriptContextAux.getDomainName() + " " + \
                    pfwScriptContextAux.getConfigurationName() + "\n"

        # encrease prefix
        pfwScriptContextAux.increasePrefix()

        # Create a rootRule
        ruleChildren = self.extractChildrenByClass([Rule, Operator])

        # Do not create a root rule if there is only one fist level Operator rule
        if len(ruleChildren) == 1 and ruleChildren[0].__class__ == Operator :
            ruleroot = ruleChildren[0]

        else :
            ruleroot = Operator()
            ruleroot.setName("ALL")
            ruleroot.addChildren(ruleChildren)


        # Add the command to create the rules of this configuration
        script += ruleroot.toPFWScript(pfwScriptContextAux)


        # Add the command to restore this configuration
        script += pfwScriptContextAux.getPrefix() + \
                    self.PFWCommandRestoreConfiguration + " " + \
                    pfwScriptContextAux.getDomainName() + " " + \
                    pfwScriptContextAux.getConfigurationName() + "\n"

        # Copy pfwScriptContextAux and increase the prefix
        contextAux = pfwScriptContextAux.copy()
        contextAux.increasePrefix()

        # add the parameter settings for this configuration
        paths = self.extractChildrenByClass([Path, GroupPath])
        for path in paths :
            script += path.toPFWScript(contextAux)

        script += pfwScriptContextAux.getPrefix() + \
                    self.PFWCommandSaveConfiguration + " " + \
                    pfwScriptContextAux.getDomainName() + " " + \
                    pfwScriptContextAux.getConfigurationName() + "\n"

        # if domain is sequence aware
        if pfwScriptContextAux.getSequenceAwareness() :

            script += pfwScriptContextAux.getPrefix() + \
                    self.PFWCommandElementSequence + " " + \
                    pfwScriptContextAux.getDomainName() + " " + \
                    pfwScriptContextAux.getConfigurationName() + " "

            for path in paths :
                script += pfwScriptContextAux.getNewLinePrefix() + \
                            path.getName()
            script += "\n"

            script += pfwScriptContextAux.getPrefix() + \
                        self.PFWCommandSequenceAware + " "\
                          + pfwScriptContextAux.getDomainName() + " true \n"

        # for lisibility
        script += "\n"

        return script

    def copy (self) :
        """return a shallow copy of the configuration"""

        # create configuration or subclass copy
        confCopy = self.__class__()

        # add children
        confCopy.children = list(self.children)

        # add option
        confCopy.option = self.option.copy()

        return confCopy

class GroupConfiguration (Configuration) :
    tag = "GroupConfiguration"
    optionNames = ["Name"]
    match = re.compile(r"(supConf|confGroup|confType) *:").match
    childWhiteList = ["Rule", "Operator", "GroupConfiguration", "Configuration", "GroupPath"]

    def composition (self, context) :
        """add itself in context for configuration composition

        Composition is the fact that group configuration with the same name defined
        in a parent will give their rule children to this configuration
        """

        # copyItself
        selfCopy = self.copy()

        # make all needed composition
        super(GroupConfiguration, self).composition(context)

        # add the copy in context for futur configuration composition
        context.getConfigurations().append(selfCopy)


    def toXML(self, context="") :
        return self.childrenToXML(context)

    def getConfigurableElements (self) :
        """return a list. Each elements consist of a list of configurable element of a configuration

        return a list consisting of all configurable elements for each configuration.
        These configurable elements are organized in a list"""
        configurableElements = []

        configurations = self.extractChildrenByClass([Configuration])
        for configuration in configurations :
            configurableElements.append(configuration.getConfigurableElements())

        groudeConfigurations = self.extractChildrenByClass([GroupConfiguration])
        for groudeConfiguration in groudeConfigurations :
            configurableElements += groudeConfiguration.getConfigurableElements()

        return configurableElements

    def toPFWScript (self, pfwScriptContext) :
        script = ""

        configurationChildren = self.extractChildrenByClass([Configuration, GroupConfiguration])

        for configurationChild in configurationChildren :
            # add configuration settings
            script += configurationChild.toPFWScript(pfwScriptContext)

        return script

# ----------------------------------------------------------

class Domain (ElementWithRuleInheritance, ElementWithTag) :
    tag = "domain"
    sequenceAwareKeyword = "sequenceAware"

    match = re.compile(r"domain *:").match
    optionNames = ["Name", sequenceAwareKeyword]
    childWhiteList = ["Configuration", "GroupConfiguration", "Rule", "Operator"]

    PFWCommandConfigurableElement = "addElement"
    PFWCommandDomain = "createDomain"

    def propagate (self, context=PropagationContext) :
        """ propagate name, sequenceAwareness and rule to children"""

        # call the propagate method of all children
        super(Domain, self).propagate(context)

        self.checkConfigurableElementUnicity()

    def Inheritance (self, context) :
        """check for domain name, sequence awarness and rules inheritance"""
        # check for domain name and sequence awarness inheritance
        self.OptionsInheritance(context)

        # check for rule inheritance
        self.ruleInheritance(context)

    def OptionsInheritance(self, context) :
        """ make domain name and sequence awareness inheritance

        join to the domain name all domain names defined in context and
        if any domain in context is sequence aware, set sequenceAwareness to True"""

        # add domain options to context
        context.getDomainOptions().append(self.option.copy())

        # set name to the junction of all domain name in context
        self.setName(".".join(context.getDomainOptions().getOptionItems("Name")))

        # get sequenceAwareness of all domains in context
        sequenceAwareList = context.getDomainOptions().getOptionItems(self.sequenceAwareKeyword)
        # or operation on all booleans in sequenceAwareList
        sequenceAwareness = False
        for sequenceAware in sequenceAwareList :
            sequenceAwareness = sequenceAwareness or sequenceAware
        # current domain sequenceAwareness = sequenceAwareness
        self.option.setOption(self.sequenceAwareKeyword, sequenceAwareness)


    def extractOptions(self, line) :
        """Extract options from the definition line"""
        options = super(Domain, self).extractOptions(line)

        sequenceAwareIndex = self.optionNames.index(self.sequenceAwareKeyword)

        # translate the keyword self.sequenceAwareKeyword if specified to boolean True,
        # to False otherwise
        try :
            if options[sequenceAwareIndex] == self.sequenceAwareKeyword :
               options[sequenceAwareIndex] = True
            else:
               options[sequenceAwareIndex] = False
        except IndexError :
            options = options + [None] * (sequenceAwareIndex - len(options)) + [False]
        return options

    def getRootConfiguration (self) :
        """return the root configuration group"""
        configurations = self.extractChildrenByClass([Configuration, GroupConfiguration])

        configurationRoot = GroupConfiguration()

        configurationRoot.addChildren(configurations)

        return configurationRoot

    def checkConfigurableElementUnicity (self):
        """ check that all configurable elements defined in child configuration are the sames"""

        # get a list. Each elements of is the configurable element list of a configuration
        configurableElementsList = self.getRootConfiguration().getConfigurableElements()

        # if at least two configurations in the domain
        if len(configurableElementsList) > 1 :

            # get first configuration configurable element list sort
            configurableElementsList0 = list(configurableElementsList[0])
            configurableElementsList0.sort()

            for configurableElements in configurableElementsList :
                # sort current configurable element list
                auxConfigurableElements = list(configurableElements)
                auxConfigurableElements.sort()

                if auxConfigurableElements != configurableElementsList0 :
                    # if different, 2 configurations those not have the same configurable element list
                    # => one or more configurable element is missing in one of the 2 configuration
                    raise UndefinedParameter(self.getName())


    def toPFWScript (self, pfwScriptContext=PFWScriptContext()):
        script = ""

        domainName = self.getName()


        script += pfwScriptContext.getPrefix() + \
                    self.PFWCommandDomain + " " + \
                    domainName + "\n"

        # get sequenceAwareness of this domain
        sequenceAwareness = self.option.getOption(self.sequenceAwareKeyword)

        # Copy and update pfwScriptContext for this domain
        pfwScriptContextAux = pfwScriptContext.copy()
        pfwScriptContextAux.setDomainName(domainName)
        pfwScriptContextAux.setSequenceAwareness(sequenceAwareness)
        pfwScriptContextAux.increasePrefix()

        # get configurable elements
        configurationRoot = self.getRootConfiguration()
        configurableElementsList = configurationRoot.getConfigurableElements()

        # add configurable elements
        if len(configurableElementsList) != 0 :

            for configurableElement in configurableElementsList[0] :

                script += pfwScriptContextAux.getPrefix() + \
                            self.PFWCommandConfigurableElement + " " + \
                            domainName + " " + \
                            configurableElement + "\n"

        # new line to be more lisible :
        script += "\n"

        # add configuration settings
        script += configurationRoot.toPFWScript(pfwScriptContextAux)

        # to be more lisible :
        script += "\n"

        return script


class GroupDomain (Domain) :
    tag = "groupDomain"
    match = re.compile(r"(supDomain|domainGroup) *:").match
    childWhiteList = ["GroupDomain", "Domain", "GroupConfiguration", "Rule", "Operator"]
    def toXML(self, context="") :
        return self.childrenToXML(context)

    def toPFWScript (self, context={}):
        script = ""
        children = self.extractChildrenByClass([Domain, GroupDomain])

        for child in children :
            script += child.toPFWScript(context)

        return script

# ----------------------------------------------------------

class Root(Element):
    tag = "root"
    childWhiteList = ["Domain", "GroupDomain"]
    def toXML(self, context="") :
        return self.childrenToXML(context)


# ===========================================
""" Syntax error Exceptions"""
# ===========================================

class MySyntaxProblems(SyntaxError) :
    comment = "syntax error in %(line)s "

    def __init__(self, line=None, num=None):
        self.setLine(line, num)

    def __str__(self):

        if self.line :
            self.comment = self.comment % {"line" : repr(self.line)}
        if self.num :
            self.comment = "Line " + str(self.num) + ", " + self.comment
        return self.comment

    def setLine (self, line, num):
        self.line = str(line)
        self.num = num


# ---------------------------------------------------------

class MyPropagationError(MySyntaxProblems) :
    """ Syntax error Exceptions used in the propagation step"""
    pass

class UndefinedParameter(MyPropagationError) :
    comment = "Configurations in domain '%(domainName)s' do not all set the same parameters "
    def __init__ (self, domainName):
        self.domainName = domainName
    def __str__ (self):
        return self.comment % { "domainName" : self.domainName }


# -----------------------------------------------------
""" Syntax error Exceptions used by parser"""

class MySyntaxError(MySyntaxProblems) :
    """ Syntax error Exceptions used by parser"""
    pass

class MySyntaxWarning(MySyntaxProblems) :
    """ Syntax warning Exceptions used by parser"""
    pass

class IndentationSyntaxError(MySyntaxError) :
    comment = """syntax error in %(line)s has no father element.
    You can only increment indentation by one tabutation per line")"""

class EmptyLineWarning(MySyntaxWarning):
    comment = "warning : %(line)s is an empty line and has been ommited"

class CommentWarning(MySyntaxWarning):
    comment = "warning : %(line)s is a commentary and has been ommited"

class ChildNotPermitedError(MySyntaxError):
    def __init__(self, line, fatherElement, childElement):
        self.comment = "syntax error in %(line)s, " + fatherElement.tag + " should not have a " + childElement.tag + " child."
        super(ChildNotPermitedError, self).__init__(line)


class UnknownElementTypeError(MySyntaxError):
    comment = " error in line %(line)s , not known element type were matched "

class SpaceInIndentationError(MySyntaxError):
    comment = " error in ,%(line)s space is not permited in indentation"


# ============================================
"""Class creating the DOM elements from a stream"""
# ============================================

class ElementsFactory(object)  :
    """Element factory, return an instance of the first matching element

    Test each element list in elementClass and instanciate it if it's methode match returns True
    The method match is called with input line as argument
    """
    def __init__ (self):
        self.elementClass = [
        EmptyLine ,
        Commentary,
        GroupDomain,
        Domain,
        Path,
        GroupConfiguration,
        Configuration,
        Operator,
        Rule,
        GroupPath
        ]

    def createElementFromLine (self, line) :
        """return an instance of the first matching element

        Test each element list in elementClass and instanciate it if it's methode match returns True
        The method match is called with the argument line.
        Raise UnknownElementTypeError if no element matched.
        """
        for element in self.elementClass :
            if element.match(line) :
                # print (line + element.__class__.__name__)
                return element(line)
        # if we have not find any
        raise UnknownElementTypeError(line)

#------------------------------------------------------

class Parser(object) :
    """Class implementing the parser"""
    def __init__(self):
        self.rankPattern = re.compile(r"^([\t ]*)(.*)")
        self.elementFactory = ElementsFactory()
        self.previousRank = 0

    def __parseLine__(self, line):

        rank, rest = self.__getRank__(line)

        # instanciate the coresponding element
        element = self.elementFactory.createElementFromLine(rest)

        self.__checkIndentation__(rank)

        return rank, element

    def __getRank__(self, line):
        """return the rank, the name and the option of the input line

the rank is the number of tabulation (\t) at the line beginning.
the rest is the rest of the line."""
        # split line in rank and rest
        rank = self.rankPattern.match(line)
        if rank :
            rank, rest = rank.group(1, 2)
        else :
            raise MySyntaxError(line)

        # check for empty line
        if rest == "" :
            raise EmptyLineWarning(line)

        # check for space in indentation
        if rank.find(" ") > -1 :
            raise SpaceInIndentationError(line)

        rank = len (rank) + 1  # rank starts at 1


        return rank, rest


    def __checkIndentation__(self, rank):
        """check if indentation > previous indentation + 1. If so, raise IndentationSyntaxError"""
        if (rank > self.previousRank + 1) :
            raise IndentationSyntaxError()
        self.previousRank = rank

    def parse(self, stream, verbose=False):
        """parse a stream, usually a opened file"""
        myroot = Root("root")
        context = [myroot]  # root is element of rank 0
        warnings = ""

        for num, line in enumerate(stream):
            try:
                rank, myelement = self.__parseLine__(line)

                while len(context) > rank :
                    context.pop()
                context.append(myelement)
                context[-2].addChild(myelement)

            except MySyntaxWarning, ex:
                ex.setLine(line, num + 1)
                if verbose :
                    print >>sys.stderr, ex

            except MySyntaxError, ex :
                ex.setLine(line, num + 1)
                raise

        return myroot

# ============================
# command line argument parser
# ============================

class ArgparseArgumentParser(object) :
    """class that parse command line arguments with argparse library

    result of parsing are the class atributs"""
    def __init__(self) :

        myArgParser = argparse.ArgumentParser(description='Process domain scripts.')

        myArgParser.add_argument('inputFile', nargs='?',
                                 type=argparse.FileType('r'), default=sys.stdin,
                                 help="the domain script file, default stdin")

        myArgParser.add_argument('-o', '--output',
                                 dest="outputFile",
                                 type=argparse.FileType('w'), default=sys.stdout,
                                 help="the output file, default stdout")

        myArgParser.add_argument('-d', '--debug',
                                 dest="debugFlag",
                                 action='store_true',
                                 help="print debug warnings")


        outputFormatGroupe = myArgParser.add_mutually_exclusive_group(required=False)

        outputFormatGroupe.add_argument('--pfw',
                                        dest="pfwFlag",
                                        action='store_true',
                                        help="output pfw commands (default)")
        outputFormatGroupe.add_argument('--xml',
                                        dest="xmlFlag",
                                        action='store_true',
                                        help="output XML settings (Not fully implemented yet)")
        outputFormatGroupe.add_argument('--raw',
                                        dest="rawFlag",
                                        action='store_true',
                                        help="output raw domain tree (DEBUG ONLY)")


        # process command line arguments
        options = myArgParser.parse_args()

        # maping to atributs
        self.inputFile = options.inputFile
        self.output = options.outputFile

        self.debug = options.debugFlag

        if not (options.pfwFlag or options.xmlFlag or options.rawFlag) :
             # --pfw is default if none provided
             self.pfw = True
             self.xml = self.raw = False
        else :
            self.pfw = options.pfwFlag
            self.xml = options.xmlFlag
            self.raw = options.rawFlag


class OptParseArgumentParser(object) :
    """class that parse command line arguments with optparse library

    result of parsing are the class atributs"""
    def __init__(self) :

        myOptParser = optparse.OptionParser(usage="usage: [-h] [-d] [--pfw | --xml | --raw] "
                                            "[-o OUTPUTFILE] [INPUTFILE]",
                                            description="Process domain scripts")

        myOptParser.add_option('-o', '--output',
                               dest="outputFile", metavar="FILE",
                               help="the output file, default stdout")

        myOptParser.add_option('-d', '--debug',
                               dest="debugFlag",
                               action='store_true',
                               help="print debug warnings")


        outputFormatGroupe = optparse.OptionGroup(myOptParser, "output format")

        outputFormatGroupe.add_option('--pfw',
                                      dest="pfwFlag",
                                      action='store_true',
                                      help="output pfw commands (default)")
        outputFormatGroupe.add_option('--xml',
                                      dest="xmlFlag",
                                      action='store_true',
                                      help="output XML settings (Not fully implemented yet)")
        outputFormatGroupe.add_option('--raw',
                                      dest="rawFlag",
                                      action='store_true',
                                      help="output raw domain tree (DEBUG ONLY)")


        # process command line arguments
        (options, args) = myOptParser.parse_args()

        # If no input file provided, use default one
        if len(args) == 0:
            args = [None]

        # mapping to attributes
        self.inputFile = self.open_secured(args[0], 'r') or sys.stdin
        self.output = self.open_secured(options.outputFile, 'w') or sys.stdout

        self.debug = options.debugFlag

        if not (options.pfwFlag or options.xmlFlag or options.rawFlag) :
             # --pfw is default if none provided
             # TODO: find a way to do that with argparse directly
             self.pfw = True
             self.xml = self.raw = False
        else :
            self.pfw = options.pfwFlag
            self.xml = options.xmlFlag
            self.raw = options.rawFlag

    @staticmethod
    def open_secured(file, openMode="r"):
        if file:
            return open(file, openMode)

        return None

# ==============
# main function
# ==============

def printE(s):
    """print in stderr"""
    print >>sys.stderr, str(s)

def main ():

    # Get command line arguments
    try:
        imp.find_module("argparse")

    except ImportError:
        printE("Warning: unable to import argparse module, fallback to optparse")
        # Using optparse
        options = OptParseArgumentParser()

    else:
        # Using argparse
        options = ArgparseArgumentParser()

    myparser = Parser()
    try:
        myroot = myparser.parse(options.inputFile, options.debug)

    except MySyntaxError, ex :
        printE(ex)
        printE("EXIT ON FAILURE")
        exit (2)
    else :
        if options.raw :
            options.output.write(str(myroot))
        else :
            try :
                myroot.propagate()

            except MyPropagationError, ex :
                printE(ex)
                printE("EXIT ON FAILURE")
                exit(1)

            else :
                if options.xml :
                    options.output.write(myroot.toXML())

                if options.pfw :
                    options.output.write(myroot.toPFWScript())

# execute main function if the python interpreter is running this module as the main program
if __name__ == "__main__" :
    main()