Salome HOME
fin du menage
[tools/eficas.git] / Noyau / N_ENTITE.py
1 # coding=utf-8
2 # ======================================================================
3 # COPYRIGHT (C) 1991 - 2017  EDF R&D                  WWW.CODE-ASTER.ORG
4 # THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY
5 # IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY
6 # THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR
7 # (AT YOUR OPTION) ANY LATER VERSION.
8 #
9 # THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT
10 # WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF
11 # MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU
12 # GENERAL PUBLIC LICENSE FOR MORE DETAILS.
13 #
14 # YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE
15 # ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER,
16 #    1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE.
17 #
18 #
19 # ======================================================================
20
21
22 """
23     Ce module contient la classe ENTITE qui est la classe de base
24     de toutes les classes de definition d'EFICAS.
25 """
26
27 from __future__ import absolute_import
28 from __future__ import print_function
29 try :
30    from builtins import str
31    from builtins import object
32 except :
33    pass
34 import re
35 from . import N_CR
36 from . import N_OPS
37 from . import N_VALIDATOR
38
39 import six
40 stringTypes = (str, six.text_type)
41
42
43 class ENTITE(object):
44
45     """
46        Classe de base pour tous les objets de definition : mots cles et commandes
47        Cette classe ne contient que des methodes utilitaires
48        Elle ne peut être instanciee et doit d abord être specialisee
49     """
50     CR = N_CR.CR
51     factories = {'validator': N_VALIDATOR.validatorFactory}
52
53     def __init__(self, validators=None):
54         """
55            Initialise les deux attributs regles et entites d'une classe dérivée
56            à : pas de règles et pas de sous-entités.
57
58            L'attribut regles doit contenir la liste des regles qui s'appliquent
59            sur ses sous-entités
60
61            L'attribut entités doit contenir le dictionnaires des sous-entités
62            (clé = nom, valeur=objet)
63         """
64         self.regles = ()
65         self.entites = {}
66         if validators:
67             self.validators = self.factories['validator'](validators)
68         else:
69             self.validators = validators
70         #self.doitSenregistrerComme = None
71         self.txtNomComplet=''
72         self.redefinit=False
73
74     def affecter_parente(self):
75         """
76             Cette methode a pour fonction de donner un nom et un pere aux
77             sous entités qui n'ont aucun moyen pour atteindre leur parent
78             directement
79             Il s'agit principalement des mots cles
80         """
81         for k, v in list(self.entites.items()):
82             #print( k,v)
83             v.pere = self
84             v.nom = k
85
86     def verifCata(self):
87         """
88             Cette methode sert à valider les attributs de l'objet de définition
89         """
90         raise NotImplementedError("La méthode verifCata de la classe %s doit être implémentée"
91                                   % self.__class__.__name__)
92
93     def __call__(self):
94         """
95             Cette methode doit retourner un objet dérivé de la classe OBJECT
96         """
97      
98         raise NotImplementedError("La méthode __call__ de la classe %s doit être implémentée"
99                                   % self.__class__.__name__)
100
101     def report(self):
102         """
103            Cette méthode construit pour tous les objets dérivés de ENTITE un
104            rapport de validation de la définition portée par cet objet
105         """
106         self.cr = self.CR()
107         self.verifCata()
108         for k, v in list(self.entites.items()):
109             try:
110                 cr = v.report()
111                 cr.debut = u"Début " + v.__class__.__name__ + ' : ' + k
112                 cr.fin = u"Fin " + v.__class__.__name__ + ' : ' + k
113                 self.cr.add(cr)
114             except:
115                 self.cr.fatal("Impossible d'obtenir le rapport de %s %s" % (k, repr(v)))
116                 print(("Impossible d'obtenir le rapport de %s %s" % (k, repr(v))))
117                 print(("père =", self))
118         return self.cr
119
120     def verifCataRegles(self):
121         """
122            Cette méthode vérifie pour tous les objets dérivés de ENTITE que
123            les objets REGLES associés ne portent que sur des sous-entités
124            existantes
125         """
126         for regle in self.regles:
127             l = []
128             for mc in regle.mcs:
129                 if not mc in  self.entites :
130                     l.append(mc)
131             if l != []:
132                 txt = str(regle)
133                 self.cr.fatal(
134                     _(u"Argument(s) non permis : %r pour la règle : %s"), l, txt)
135
136     def checkDefinition(self, parent):
137         """Verifie la definition d'un objet composite (commande, fact, bloc)."""
138         args = self.entites.copy()
139         mcs = set()
140         for nom, val in list(args.items()):
141             if val.label == 'SIMP':
142                 mcs.add(nom)
143                 # XXX
144                 # if val.max != 1 and val.type == 'TXM':
145                     # print "#CMD", parent, nom
146             elif val.label == 'FACT':
147                 val.checkDefinition(parent)
148                 # CALC_SPEC !
149                 # assert self.label != 'FACT', \
150                    #'Commande %s : Mot-clef facteur present sous un mot-clef facteur : interdit !' \
151                    #% parent
152             else:
153                 continue
154             del args[nom]
155         # seuls les blocs peuvent entrer en conflit avec les mcs du plus haut
156         # niveau
157         for nom, val in list(args.items()):
158             if val.label == 'BLOC':
159                 mcbloc = val.checkDefinition(parent)
160                 # XXX
161                 # print "#BLOC", parent, re.sub('\s+', ' ', val.condition)
162                 assert mcs.isdisjoint(mcbloc), "Commande %s : Mot(s)-clef(s) vu(s) plusieurs fois : %s" \
163                     % (parent, tuple(mcs.intersection(mcbloc)))
164         return mcs
165
166     def checkOp(self, valmin=-9999, valmax=9999):
167         """Vérifie l'attribut op."""
168         if self.op is not None and \
169            (type(self.op) is not int or self.op < valmin or self.op > valmax):
170             self.cr.fatal(_(u"L'attribut 'op' doit être un entier "
171                             u"compris entre %d et %d : %r"), valmin, valmax, self.op)
172
173     def checkProc(self):
174         """Vérifie l'attribut proc."""
175         if self.proc is not None and not isinstance(self.proc, N_OPS.OPS):
176             self.cr.fatal(
177                 _(u"L'attribut op doit être une instance d'OPS : %r"), self.proc)
178
179     def checkRegles(self):
180         """Vérifie l'attribut regles."""
181         if type(self.regles) is not tuple:
182             self.cr.fatal(_(u"L'attribut 'regles' doit être un tuple : %r"),
183                           self.regles)
184
185     def checkFr(self):
186         """Vérifie l'attribut fr."""
187         if type(self.fr) not in stringTypes:
188             self.cr.fatal(
189                 _(u"L'attribut 'fr' doit être une chaine de caractères : %r"),
190                 self.fr)
191
192     def checkDocu(self):
193         """Vérifie l'attribut docu."""
194         if type(self.docu) not in stringTypes:
195             self.cr.fatal(
196                 _(u"L'attribut 'docu' doit être une chaine de caractères : %r"),
197                 self.docu)
198
199     def checkNom(self):
200         """Vérifie l'attribut proc."""
201         if type(self.nom) is not str:
202             self.cr.fatal(
203                 _(u"L'attribut 'nom' doit être une chaine de caractères : %r"),
204                 self.nom)
205
206     def checkReentrant(self):
207         """Vérifie l'attribut reentrant."""
208         if self.reentrant not in ('o', 'n', 'f'):
209             self.cr.fatal(
210                 _(u"L'attribut 'reentrant' doit valoir 'o','n' ou 'f' : %r"),
211                 self.reentrant)
212
213     def checkStatut(self, into=('o', 'f', 'c', 'd')):
214         """Vérifie l'attribut statut."""
215         if self.statut not in into:
216             self.cr.fatal(_(u"L'attribut 'statut' doit être parmi %s : %r"),
217                           into, self.statut)
218
219     def checkCondition(self):
220         """Vérifie l'attribut condition."""
221         if self.condition != None:
222             if type(self.condition) is not str:
223                 self.cr.fatal(
224                     _(u"L'attribut 'condition' doit être une chaine de caractères : %r"),
225                     self.condition)
226         else:
227             self.cr.fatal(_(u"La condition ne doit pas valoir None !"))
228
229     def checkMinMax(self):
230         """Vérifie les attributs min/max."""
231         if type(self.min) != int:
232             if self.min != '**'and self.min != float('-inf'):
233                 self.cr.fatal(
234                     _(u"L'attribut 'min' doit être un entier : %r"), self.min)
235         if type(self.max) != int:
236             if self.max != '**' and self.max != float('inf'):
237                 self.cr.fatal(
238                     _(u"L'attribut 'max' doit être un entier : %r"), self.max)
239         if self.min > self.max:
240             self.cr.fatal(
241                 _(u"Nombres d'occurrence min et max invalides : %r %r"),
242                 self.min, self.max)
243
244     def checkValidators(self):
245         """Vérifie les validateurs supplémentaires"""
246         if self.validators and not self.validators.verifCata():
247             self.cr.fatal(_(u"Un des validateurs est incorrect. Raison : %s"),
248                           self.validators.cata_info)
249
250     def checkHomo(self):
251         """Vérifie l'attribut homo."""
252         if self.homo != 0 and self.homo != 1:
253             self.cr.fatal(
254                 _(u"L'attribut 'homo' doit valoir 0 ou 1 : %r"), self.homo)
255
256     def checkInto(self):
257         """Vérifie l'attribut into."""
258         if self.into != None:
259             if (type(self.into) not in (list, tuple)) and (type(self.into) != types.FunctionType) :
260                 self.cr.fatal(
261                     _(u"L'attribut 'into' doit être un tuple : %r"), self.into)
262
263     def checkPosition(self):
264         """Vérifie l'attribut position."""
265         if self.position not in ('local', 'global', 'global_jdc'):
266             self.cr.fatal(_(u"L'attribut 'position' doit valoir 'local', 'global' "
267                             u"ou 'global_jdc' : %r"), self.position)
268
269     def nomComplet(self):
270         if self.txtNomComplet  != '' : return self.txtNomComplet
271         qui=self
272         while hasattr(qui, 'pere' ):
273               self.txtNomComplet+='_'+qui.nom
274               qui=qui.pere
275         self.txtNomComplet+='_'+qui.nom
276         return self.txtNomComplet
277
278     def addDefinitionMC(self,listeMCAvant,**args):
279         ouChercher=self
280         for mot in listeMCAvant:
281             try :
282               ouChercher=ouChercher.entites[mot]
283             except :
284               print ('impossible de trouver : ',mot,' ',listeMCAvant)
285         (nomMC,defMC)=args.items()[0]
286         defMC.pere = ouChercher
287         defMC.pere.propageRedefinit()
288         defMC.nom = nomMC
289         cata = CONTEXT.getCurrentCata()
290         print (cata)
291         ouChercher.entites[nomMC]=defMC
292
293     def changeDefinitionMC(self,listeMCAvant,**args):
294         ouChercher=self
295         for mot in listeMCAvant:
296             try :
297               ouChercher=ouChercher.entites[mot]
298             except :
299               print ('impossible de trouver : ',mot,' ',listeMCAvant)
300         monSIMP=ouChercher
301         for (nomAttributDef,valeurAttributDef) in args.items():
302              if hasattr(monSIMP, nomAttributDef) :
303                setattr(monSIMP, nomAttributDef, valeurAttributDef) 
304              else :
305                print ('pb avec ', nomAttributdef,valeurAttributMC)
306         monSIMP.propageRedefinit()
307
308     def propageRedefinit(self):
309    # a reflechir
310        self.redefinit=True
311        # PNPN il faut remonter a l etape
312    
313
314
315     def makeObjetPourVerifSignature(self,**args):
316         etape = self.class_instance(oper=self, args=args)
317         etape.MCBuild()
318         return etape
319