Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'mc'
[simgrid.git] / src / simix / simcalls.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2014. The SimGrid Team.
5 # All rights reserved.
6
7 # This program is free software; you can redistribute it and/or modify it
8 # under the terms of the license (GNU LGPL) which comes with this package.
9
10 import re, glob
11
12 types = [('TCHAR', 'char', 'c')
13         ,('TSTRING', 'const char*', 'cc')
14         ,('TINT', 'int', 'i')
15         ,('TLONG', 'long', 'l')
16         ,('TUCHAR', 'unsigned char', 'uc')
17         ,('TUSHORT', 'unsigned short', 'us')
18         ,('TUINT', 'unsigned int', 'ui')
19         ,('TULONG', 'unsigned long', 'ul')
20         ,('TFLOAT', 'float', 'f')
21         ,('TDOUBLE', 'double', 'd')
22         ,('TDPTR', 'void*', 'dp')
23         ,('TFPTR', 'FPtr', 'fp')
24         ,('TCPTR', 'const void*', 'cp')
25         ,('TSIZE', 'size_t', 'sz')
26         ,('TSGSIZE', 'sg_size_t', 'sgsz')
27         ,('TSGOFF', 'sg_offset_t', 'sgoff')
28         ,('TVOID', 'void', '')
29         ,('TDSPEC', 'void*', 'dp')
30         ,('TFSPEC', 'FPtr', 'fp')]
31
32 class Arg(object):
33   simcall_types = {k:v for _,k,v in types}
34   def __init__(self, name, type, casted=None):
35     self.name = name 
36     self.type = type
37     self.casted = casted
38     assert type in self.simcall_types, '%s not in (%s)'%(type, ', '.join(self.simcall_types.keys()))
39
40   def field(self):
41     return self.simcall_types[self.type]
42
43   def ret(self):
44     return '%s'%self.casted if self.casted else self.type
45
46   def cast(self):
47     return '(%s)'%self.casted if self.casted else '' 
48
49 class Simcall(object):
50   simcalls_BODY = None
51   simcalls_PRE = None
52   def __init__(self, name, res, args, has_answer=True):
53     self.name = name
54     self.res = res
55     self.args = args
56     self.has_answer = has_answer
57
58   def check(self):
59     # smx_user.c  simcall_BODY_
60     # smx_*.c void SIMIX_pre_host_on(smx_simcall_t simcall, smx_host_t h)
61     self.check_body()
62     self.check_pre()
63
64   def check_body(self):
65     if self.simcalls_BODY is None:
66       f = open('smx_user.c')
67       self.simcalls_BODY = set(re.findall('simcall_BODY_(.*?)\(', f.read()))
68       f.close()
69     if self.name not in self.simcalls_BODY:
70       print '# ERROR: No function calling simcall_BODY_%s'%self.name
71       print '# Add something like this to smx_user.c:'
72       print '''%s simcall_%s(%s)
73 {
74   return simcall_BODY_%s(%s);
75 }\n'''%(self.res.ret()
76      ,self.name
77      ,', '.join('%s %s'%(arg.ret(), arg.name)
78                   for arg in self.args)
79      ,self.name
80      ,', '.join(arg.name for arg in self.args))
81       return False
82     return True
83
84   def check_pre(self):
85     if self.simcalls_PRE is None:
86       self.simcalls_PRE = set()
87       for fn in glob.glob('smx_*') + glob.glob('../mc/*'):
88         f = open(fn)
89         self.simcalls_PRE |= set(re.findall('SIMIX_pre_(.*?)\(', f.read()))
90         f.close()
91     if self.name not in self.simcalls_PRE:
92       print '# ERROR: No function called SIMIX_pre_%s'%self.name
93       print '# Add something like this to smx_.*.c:'
94       print '''%s SIMIX_pre_%s(smx_simcall_t simcall%s)
95 {
96   // Your code handling the simcall
97 }\n'''%(self.res.ret()
98        ,self.name
99        ,''.join(', %s %s'%(arg.ret(), arg.name)
100                   for arg in self.args))
101       return False
102     return True
103
104   def enum(self):
105     return 'SIMCALL_%s,'%(self.name.upper())
106
107   def string(self):
108     return '[SIMCALL_%s] = "SIMCALL_%s",'%(self.name.upper(), self.name.upper())        
109   
110   def result_getter_setter(self):
111     return '%s\n%s'%(self.result_getter(), self.result_setter())
112   
113   def result_getter(self):
114     return '' if self.res.type == 'void' else '''static inline %s simcall_%s__get__result(smx_simcall_t simcall){
115   return %s simcall->result.%s;
116 }'''%(self.res.ret(), self.name, self.res.cast(), self.res.field())
117
118   def result_setter(self):
119     return '' if self.res.type == 'void' else '''static inline void simcall_%s__set__result(smx_simcall_t simcall, %s result){
120     simcall->result.%s = result;
121 }'''%(self.name, self.res.type, self.res.field())
122
123   def args_getter_setter(self):
124     res = []
125     for i in range(len(self.args)):
126       res.append(self.arg_getter(i))
127       res.append(self.arg_setter(i))
128     return '\n'.join(res)
129
130   def arg_getter(self, i):
131     arg = self.args[i]
132     return '''static inline %s simcall_%s__get__%s(smx_simcall_t simcall){
133   return %s simcall->args[%i].%s;
134 }'''%(arg.ret(), self.name, arg.name, arg.cast(), i, arg.field())
135
136   def arg_setter(self, i):
137     arg = self.args[i]
138     return '''static inline void simcall_%s__set__%s(smx_simcall_t simcall, %s arg){
139     simcall->args[%i].%s = arg;
140 }'''%(self.name, arg.name, arg.type, i, arg.field())
141
142   def case(self):
143     return '''case SIMCALL_%s:
144       %sSIMIX_pre_%s(simcall %s);
145       %sbreak;  
146 '''%(self.name.upper(), 
147      'simcall->result.%s = '%self.res.field() if self.res.type != 'void' and self.has_answer else ' ',
148      self.name,
149      ''.join(', %s simcall->args[%d].%s'%(arg.cast(), i, arg.field()) 
150              for i, arg in enumerate(self.args)),
151      'SIMIX_simcall_answer(simcall);\n      ' if self.has_answer else ' ')
152
153   def body(self):
154     return '''  inline static %s simcall_BODY_%s(%s) {
155     smx_process_t self = SIMIX_process_self();
156     self->simcall.call = SIMCALL_%s;
157     memset(&self->simcall.result, 0, sizeof(self->simcall.result));
158     memset(self->simcall.args, 0, sizeof(self->simcall.args));
159 %s
160     if (self != simix_global->maestro_process) {
161       XBT_DEBUG("Yield process '%%s' on simcall %%s (%%d)", self->name,
162                 SIMIX_simcall_name(self->simcall.call), (int)self->simcall.call);
163       SIMIX_process_yield(self);
164     } else {
165       SIMIX_simcall_pre(&self->simcall, 0);
166     }    
167     %s
168   }'''%(self.res.ret()
169        ,self.name
170        ,', '.join('%s %s'%(arg.ret(), arg.name)
171                   for arg in self.args)
172        ,self.name.upper()
173        ,'\n'.join('    self->simcall.args[%d].%s = (%s) %s;'%(i, arg.field(), arg.type, arg.name)
174                   for i, arg in enumerate(self.args))
175        ,'' if self.res.type == 'void' else 'return self->simcall.result.%s;'%self.res.field())
176
177 def parse(fn):
178   res = []
179   resdi = None
180   resd = {}
181   for line in open(fn).read().split('\n'):
182     if line.startswith('##'):
183       resdi = []
184       resd[re.search(r'## *(.*)', line).group(1)] = resdi
185     if line.startswith('#') or not line:
186       continue
187     match = re.match(r'(\S*?) *(\S*?) *\((.*?)(?:, *(.*?))?\) *(.*)', line)
188     assert match, line
189     name, ans, rest, resc, args = match.groups()
190     sargs = []
191     for n,t,c in re.findall(r'\((.*?), *(.*?)(?:, *(.*?))?\)', args):
192       sargs.append(Arg(n,t,c))
193     sim = Simcall(name, Arg('result', rest, resc), sargs, ans == 'True')
194     if resdi is None:
195       res.append(sim)
196     else:
197       resdi.append(sim)
198   return res, resd
199
200 def write(fn, func, scs, scd):
201   f = open(fn, 'w')
202   f.write('/*********************************************\n')
203   f.write(' * File Generated by src/simix/simcalls.py   *\n')
204   f.write(' *                from src/simix/simcalls.in *\n')
205   f.write(' * Do not modify this file, add new simcalls *\n')
206   f.write(' * in src/simix/simcalls.in                  *\n')  
207   f.write(' *********************************************/\n\n')
208   f.write('\n'.join(func(sc) for sc in scs))
209   for k, v in scd.items():
210     f.write('\n#ifdef %s\n%s\n#endif\n'%(k, '\n'.join(func(sc) for sc in v)))
211   f.close()
212
213 if __name__=='__main__':
214   import sys
215   simcalls, simcalls_dict = parse('simcalls.in')
216   
217   ok = True
218   ok &= all(map(Simcall.check, simcalls))
219   for k,v in simcalls_dict.items():
220     ok &= all(map(Simcall.check, v))
221   #if not ok:
222   #  sys.exit(1)
223
224   write('simcalls_generated_enum.h', Simcall.enum, simcalls, simcalls_dict)
225   write('simcalls_generated_string.c', Simcall.string, simcalls, simcalls_dict)
226   write('simcalls_generated_res_getter_setter.h', Simcall.result_getter_setter, simcalls, simcalls_dict)
227   write('simcalls_generated_args_getter_setter.h', Simcall.args_getter_setter, simcalls, simcalls_dict)
228   write('simcalls_generated_case.c', Simcall.case, simcalls, simcalls_dict)
229   write('simcalls_generated_body.c', Simcall.body, simcalls, simcalls_dict)