generateWrappers.py 91.5 KB
Newer Older
1
from __future__ import print_function
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
import sys, os
import time
import getopt
import re
import xml.etree.ElementTree as etree

def trimToSingleSpace(text):
    if text is None or len(text) == 0:
        return ""
    t = text.strip()
    if len(t) == 0:
        return t
    if text[0].isspace():
        t = " %s" % t
    if text[-1].isspace():
        t = "%s " % t
    return t

def getNodeText(node):
    if node.text is not None:
        s = node.text
    else:
        s = ""
    for n in node:
        if n.tag == "para":
            s = "%s%s\n\n" % (s, getNodeText(n))
        elif n.tag == "ref":
            s = "%s%s" % (s, getNodeText(n))
        if n.tail is not None:
            s = "%s%s" % (s, n.tail)
    return s

def getText(subNodePath, node):
    s = ""
    for n in node.findall(subNodePath):
        s = "%s%s" % (s, trimToSingleSpace(getNodeText(n)))
        if n.tag == "para":
            s = "%s\n\n" % s
    return s.strip()

def convertOpenMMPrefix(name):
    return name.replace('OpenMM::', 'OpenMM_')

45
OPENMM_RE_PATTERN=re.compile("(.*)OpenMM:[a-zA-Z0-9_:]*:(.*)")
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def stripOpenMMPrefix(name, rePattern=OPENMM_RE_PATTERN):
    try:
        m=rePattern.search(name)
        rValue = "%s%s" % m.group(1,2)
        rValue.strip()
        return rValue
    except:
        return name

def findNodes(parent, path, **args):
    nodes = []
    for node in parent.findall(path):
        match = True
        for arg in args:
            if arg not in node.attrib or node.attrib[arg] != args[arg]:
                match = False
        if match:
            nodes.append(node)
    return nodes

class WrapperGenerator:
peastman's avatar
peastman committed
67
68
    """This is the parent class of generators for various API wrapper files.  It defines functions common to all of them."""
    
69
70
    def __init__(self, inputDirname, output):
        self.skipClasses = ['OpenMM::Vec3', 'OpenMM::XmlSerializer', 'OpenMM::Kernel', 'OpenMM::KernelImpl', 'OpenMM::KernelFactory', 'OpenMM::ContextImpl', 'OpenMM::SerializationNode', 'OpenMM::SerializationProxy']
71
72
73
74
75
76
77
78
        self.skipMethods = ['State OpenMM::Context::getState',
                            'void OpenMM::Context::createCheckpoint',
                            'void OpenMM::Context::loadCheckpoint',
                            'const std::vector<std::vector<int> >& OpenMM::Context::getMolecules',
                            'static std::vector<std::string> OpenMM::Platform::getPluginLoadFailures',
                            'static std::vector<std::string> OpenMM::Platform::loadPluginsFromDirectory',
                            'Vec3 OpenMM::LocalCoordinatesSite::getOriginWeights',
                            'Vec3 OpenMM::LocalCoordinatesSite::getXWeights',
79
80
81
                            'Vec3 OpenMM::LocalCoordinatesSite::getYWeights',
                            'std::vector<double> OpenMM::NoseHooverChain::getDefaultYoshidaSuzukiWeights',
                           ] 
82
83
84
85
86
87
        self.hideClasses = ['Kernel', 'KernelImpl', 'KernelFactory', 'ContextImpl', 'SerializationNode', 'SerializationProxy']
        self.nodeByID={}

        # Read all the XML files and merge them into a single document.
        self.doc = etree.ElementTree(etree.Element('root'))
        for file in os.listdir(inputDirname):
88
89
90
91
            if file.lower().endswith('xml'):
                root = etree.parse(os.path.join(inputDirname, file)).getroot()
                for node in root:
                    self.doc.getroot().append(node)
92

peastman's avatar
peastman committed
93
        self.out = output
94
95

        self.typesByShortName = {}
96
        self._orderedClassNodes = self.buildOrderedClassNodes()
97

98
    def getNodeByID(self, id):
99
100
101
102
103
        if id not in self.nodeByID:
            for node in findNodes(self.doc.getroot(), "compounddef", id=id):
                self.nodeByID[id] = node
        return self.nodeByID[id]

104
    def buildOrderedClassNodes(self):
105
106
        orderedClassNodes=[]
        for node in findNodes(self.doc.getroot(), "compounddef", kind="class", prot="public"):
107
            self.findBaseNodes(node, orderedClassNodes)
108
109
        return orderedClassNodes

110
    def findBaseNodes(self, node, excludedClassNodes=[]):
111
112
113
114
115
116
117
118
119
120
        if node in excludedClassNodes:
            return
        if node.attrib['prot'] == 'private':
            return
        nodeName = getText("compoundname", node)
        if nodeName in self.skipClasses:
            return
        for baseNodePnt in findNodes(node, "basecompoundref", prot="public"):
            if "refid" in baseNodePnt.attrib:
                baseNodeID = baseNodePnt.attrib["refid"]
121
122
                baseNode = self.getNodeByID(baseNodeID)
                self.findBaseNodes(baseNode, excludedClassNodes)
123
124
        excludedClassNodes.append(node)

125
126
127
128
129
130
131
    def getClassMethods(self, classNode):
        className = getText("compoundname", classNode)
        shortClassName = stripOpenMMPrefix(className)
        methodList = []
        for section in findNodes(classNode, "sectiondef", kind="public-static-func")+findNodes(classNode, "sectiondef", kind="public-func"):
            for memberNode in findNodes(section, "memberdef", kind="function", prot="public"):
                methodDefinition = getText("definition", memberNode)
132
                if methodDefinition in self.skipMethods:
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
                    continue
                methodList.append(memberNode)
        return methodList
    
    def shouldHideType(self, typeName):
        if typeName.startswith('const '):
            typeName = typeName[6:].strip()
        if typeName.endswith('&') or typeName.endswith('*'):
            typeName = typeName[:-1].strip()
        return typeName in self.hideClasses
    
    def shouldHideMethod(self, methodNode):
        paramList = findNodes(methodNode, 'param')
        returnType = self.getType(getText("type", methodNode))
        if self.shouldHideType(returnType):
            return True
        for node in paramList:
            try:
                type = getText('type', node)
            except IndexError:
                type = getText('type/ref', node)
            if self.shouldHideType(type):
                return True
        return False

class CHeaderGenerator(WrapperGenerator):
peastman's avatar
peastman committed
159
160
    """This class generates the header file for the C API wrappers."""
    
161
162
    def __init__(self, inputDirname, output):
        WrapperGenerator.__init__(self, inputDirname, output)
163
164
165
166
167
168
169
170
171
172
173
174
        self.typeTranslations = {'bool': 'OpenMM_Boolean',
                                 'Vec3': 'OpenMM_Vec3',
                                 'std::string': 'char*',
                                 'const std::string &': 'const char*',
                                 'std::vector< std::string >': 'OpenMM_StringArray',
                                 'std::vector< Vec3 >': 'OpenMM_Vec3Array',
                                 'std::vector< std::pair< int, int > >': 'OpenMM_BondArray',
                                 'std::map< std::string, double >': 'OpenMM_ParameterArray',
                                 'std::map< std::string, std::string >': 'OpenMM_PropertyArray',
                                 'std::vector< double >': 'OpenMM_DoubleArray',
                                 'std::vector< int >': 'OpenMM_IntArray',
                                 'std::set< int >': 'OpenMM_IntSet'}
175
    
176
    def writeGlobalConstants(self):
peastman's avatar
peastman committed
177
        self.out.write("/* Global Constants */\n\n")
178
179
180
181
182
183
184
        node = next((x for x in findNodes(self.doc.getroot(), "compounddef", kind="namespace") if x.findtext("compoundname") == "OpenMM"))
        for section in findNodes(node, "sectiondef", kind="var"):
            for memberNode in findNodes(section, "memberdef", kind="variable", mutable="no", prot="public", static="yes"):
                vDef = convertOpenMMPrefix(getText("definition", memberNode))
                iDef = getText("initializer", memberNode)
                if iDef.startswith("="):
                    iDef = iDef[1:]
peastman's avatar
peastman committed
185
                self.out.write("static %s = %s;\n" % (vDef, iDef))
186
187

    def writeTypeDeclarations(self):
peastman's avatar
peastman committed
188
        self.out.write("\n/* Type Declarations */\n\n")
189
190
191
192
        for classNode in self._orderedClassNodes:
            className = getText("compoundname", classNode)
            shortName = stripOpenMMPrefix(className)
            typeName = convertOpenMMPrefix(className)
peastman's avatar
peastman committed
193
            self.out.write("typedef struct %s_struct %s;\n" % (typeName, typeName))
194
195
196
197
198
            self.typesByShortName[shortName] = typeName

    def writeClasses(self):
        for classNode in self._orderedClassNodes:
            className = stripOpenMMPrefix(getText("compoundname", classNode))
peastman's avatar
peastman committed
199
            self.out.write("\n/* %s */\n" % className)
200
201
            self.writeEnumerations(classNode)
            self.writeMethods(classNode)
peastman's avatar
peastman committed
202
        self.out.write("\n")
203
204
205
206
207
208
209
210
211
212
213
214

    def writeEnumerations(self, classNode):
        enumNodes = []
        for section in findNodes(classNode, "sectiondef", kind="public-type"):
            for node in findNodes(section, "memberdef", kind="enum", prot="public"):
                enumNodes.append(node)
        className = getText("compoundname", classNode)
        shortClassName = stripOpenMMPrefix(className)
        typeName = convertOpenMMPrefix(className)
        for enumNode in enumNodes:
            enumName = getText("name", enumNode)
            enumTypeName = "%s_%s" % (typeName, enumName)
peastman's avatar
peastman committed
215
            self.out.write("typedef enum {\n  ")
216
217
218
219
220
221
            argSep=""
            for valueNode in findNodes(enumNode, "enumvalue", prot="public"):
                vName = convertOpenMMPrefix(getText("name", valueNode))
                vInit = getText("initializer", valueNode)
                if vInit.startswith("="):
                    vInit = vInit[1:].strip()
peastman's avatar
peastman committed
222
                self.out.write("%s%s_%s = %s" % (argSep, typeName, vName, vInit))
223
                argSep=", "
peastman's avatar
peastman committed
224
            self.out.write("\n} %s;\n" % enumTypeName)
225
            self.typesByShortName[enumName] = enumTypeName
peastman's avatar
peastman committed
226
        if len(enumNodes)>0: self.out.write("\n")
227
228
229
230
231
232
233

    def writeMethods(self, classNode):
        methodList = self.getClassMethods(classNode)
        className = getText("compoundname", classNode)
        shortClassName = stripOpenMMPrefix(className)
        typeName = convertOpenMMPrefix(className)
        destructorName = '~'+shortClassName
234
        isAbstract = any('virt' in method.attrib and method.attrib['virt'] == 'pure-virtual' for method in classNode.getiterator('memberdef'))
235

236
        if not isAbstract:
237
238
239
240
241
242
243
244
245
246
247
248
249
250
            # Write constructors
            numConstructors = 0
            for methodNode in methodList:
                methodDefinition = getText("definition", methodNode)
                shortMethodDefinition = stripOpenMMPrefix(methodDefinition)
                methodName = shortMethodDefinition.split()[-1]
                if methodName == shortClassName:
                    if self.shouldHideMethod(methodNode):
                        continue
                    numConstructors += 1
                    if numConstructors == 1:
                        suffix = ""
                    else:
                        suffix = "_%d" % numConstructors
peastman's avatar
peastman committed
251
                    self.out.write("extern OPENMM_EXPORT %s* %s_create%s(" % (typeName, typeName, suffix))
252
                    self.writeArguments(methodNode, False)
peastman's avatar
peastman committed
253
                    self.out.write(");\n")
254
    
peastman's avatar
peastman committed
255
256
        # Write destructor
        self.out.write("extern OPENMM_EXPORT void %s_destroy(%s* target);\n" % (typeName, typeName))
257

peastman's avatar
peastman committed
258
259
        # Record method names for future reference.
        methodNames = {}
260
261
262
        for methodNode in methodList:
            methodDefinition = getText("definition", methodNode)
            shortMethodDefinition = stripOpenMMPrefix(methodDefinition)
peastman's avatar
peastman committed
263
264
265
266
267
            methodNames[methodNode] = shortMethodDefinition.split()[-1]
        
        # Write other methods
        for methodNode in methodList:
            methodName = methodNames[methodNode]
268
269
270
271
            if methodName in (shortClassName, destructorName):
                continue
            if self.shouldHideMethod(methodNode):
                continue
peastman's avatar
peastman committed
272
273
274
275
            isConstMethod = (methodNode.attrib['const'] == 'yes')
            if isConstMethod and any(methodNames[m] == methodName and m.attrib['const'] == 'no' for m in methodList):
                # There are two identical methods that differ only in whether they are const.  Skip the const one.
                continue
276
            returnType = self.getType(getText("type", methodNode))
peastman's avatar
peastman committed
277
            self.out.write("extern OPENMM_EXPORT %s %s_%s(" % (returnType, typeName, methodName))
278
279
            isInstanceMethod = (methodNode.attrib['static'] != 'yes')
            if isInstanceMethod:
peastman's avatar
peastman committed
280
281
282
                if isConstMethod:
                    self.out.write('const ')
                self.out.write("%s* target" % typeName)
283
            self.writeArguments(methodNode, isInstanceMethod)
peastman's avatar
peastman committed
284
            self.out.write(");\n")
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
    
    def writeArguments(self, methodNode, initialSeparator):
        paramList = findNodes(methodNode, 'param')
        if initialSeparator:
            separator = ", "
        else:
            separator = ""
        for node in paramList:
            try:
                type = getText('type', node)
            except IndexError:
                type = getText('type/ref', node)
            if type == 'void':
                continue
            type = self.getType(type)
            name = getText('declname', node)
peastman's avatar
peastman committed
301
            self.out.write("%s%s %s" % (separator, type, name))
302
303
304
305
306
307
308
309
310
311
312
313
314
            separator = ", "
    
    def getType(self, type):
        if type in self.typeTranslations:
            return self.typeTranslations[type]
        if type in self.typesByShortName:
            return self.typesByShortName[type]
        if type.startswith('const '):
            return 'const '+self.getType(type[6:].strip())
        if type.endswith('&') or type.endswith('*'):
            return self.getType(type[:-1].strip())+'*'
        return type

315
    def writeOutput(self):
316
        print("""
317
318
319
320
321
322
#ifndef OPENMM_CWRAPPER_H_
#define OPENMM_CWRAPPER_H_

#ifndef OPENMM_EXPORT
#define OPENMM_EXPORT
#endif
323
""", file=self.out)
324
325
        self.writeGlobalConstants()
        self.writeTypeDeclarations()
326
        print("""
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
typedef struct OpenMM_Vec3Array_struct OpenMM_Vec3Array;
typedef struct OpenMM_StringArray_struct OpenMM_StringArray;
typedef struct OpenMM_BondArray_struct OpenMM_BondArray;
typedef struct OpenMM_ParameterArray_struct OpenMM_ParameterArray;
typedef struct OpenMM_PropertyArray_struct OpenMM_PropertyArray;
typedef struct OpenMM_DoubleArray_struct OpenMM_DoubleArray;
typedef struct OpenMM_IntArray_struct OpenMM_IntArray;
typedef struct OpenMM_IntSet_struct OpenMM_IntSet;
typedef struct {double x, y, z;} OpenMM_Vec3;

typedef enum {OpenMM_False = 0, OpenMM_True = 1} OpenMM_Boolean;

#if defined(__cplusplus)
extern "C" {
#endif

/* OpenMM_Vec3 */
extern OPENMM_EXPORT OpenMM_Vec3 OpenMM_Vec3_scale(const OpenMM_Vec3 vec, double scale);

/* OpenMM_Vec3Array */
extern OPENMM_EXPORT OpenMM_Vec3Array* OpenMM_Vec3Array_create(int size);
extern OPENMM_EXPORT void OpenMM_Vec3Array_destroy(OpenMM_Vec3Array* array);
extern OPENMM_EXPORT int OpenMM_Vec3Array_getSize(const OpenMM_Vec3Array* array);
extern OPENMM_EXPORT void OpenMM_Vec3Array_resize(OpenMM_Vec3Array* array, int size);
extern OPENMM_EXPORT void OpenMM_Vec3Array_append(OpenMM_Vec3Array* array, const OpenMM_Vec3 vec);
extern OPENMM_EXPORT void OpenMM_Vec3Array_set(OpenMM_Vec3Array* array, int index, const OpenMM_Vec3 vec);
extern OPENMM_EXPORT const OpenMM_Vec3* OpenMM_Vec3Array_get(const OpenMM_Vec3Array* array, int index);

/* OpenMM_StringArray */
extern OPENMM_EXPORT OpenMM_StringArray* OpenMM_StringArray_create(int size);
extern OPENMM_EXPORT void OpenMM_StringArray_destroy(OpenMM_StringArray* array);
extern OPENMM_EXPORT int OpenMM_StringArray_getSize(const OpenMM_StringArray* array);
extern OPENMM_EXPORT void OpenMM_StringArray_resize(OpenMM_StringArray* array, int size);
extern OPENMM_EXPORT void OpenMM_StringArray_append(OpenMM_StringArray* array, const char* string);
extern OPENMM_EXPORT void OpenMM_StringArray_set(OpenMM_StringArray* array, int index, const char* string);
extern OPENMM_EXPORT const char* OpenMM_StringArray_get(const OpenMM_StringArray* array, int index);

/* OpenMM_BondArray */
extern OPENMM_EXPORT OpenMM_BondArray* OpenMM_BondArray_create(int size);
extern OPENMM_EXPORT void OpenMM_BondArray_destroy(OpenMM_BondArray* array);
extern OPENMM_EXPORT int OpenMM_BondArray_getSize(const OpenMM_BondArray* array);
extern OPENMM_EXPORT void OpenMM_BondArray_resize(OpenMM_BondArray* array, int size);
extern OPENMM_EXPORT void OpenMM_BondArray_append(OpenMM_BondArray* array, int particle1, int particle2);
extern OPENMM_EXPORT void OpenMM_BondArray_set(OpenMM_BondArray* array, int index, int particle1, int particle2);
extern OPENMM_EXPORT void OpenMM_BondArray_get(const OpenMM_BondArray* array, int index, int* particle1, int* particle2);

/* OpenMM_ParameterArray */
extern OPENMM_EXPORT int OpenMM_ParameterArray_getSize(const OpenMM_ParameterArray* array);
extern OPENMM_EXPORT double OpenMM_ParameterArray_get(const OpenMM_ParameterArray* array, const char* name);

/* OpenMM_PropertyArray */
extern OPENMM_EXPORT int OpenMM_PropertyArray_getSize(const OpenMM_PropertyArray* array);
379
extern OPENMM_EXPORT const char* OpenMM_PropertyArray_get(const OpenMM_PropertyArray* array, const char* name);""", file=self.out)
380

381
382
383
        for type in ('double', 'int'):
            name = 'OpenMM_%sArray' % type.capitalize()
            values = {'type':type, 'name':name}
384
            print("""
385
386
387
388
389
390
391
/* %(name)s */
extern OPENMM_EXPORT %(name)s* %(name)s_create(int size);
extern OPENMM_EXPORT void %(name)s_destroy(%(name)s* array);
extern OPENMM_EXPORT int %(name)s_getSize(const %(name)s* array);
extern OPENMM_EXPORT void %(name)s_resize(%(name)s* array, int size);
extern OPENMM_EXPORT void %(name)s_append(%(name)s* array, %(type)s value);
extern OPENMM_EXPORT void %(name)s_set(%(name)s* array, int index, %(type)s value);
392
extern OPENMM_EXPORT %(type)s %(name)s_get(const %(name)s* array, int index);""" % values, file=self.out)
393

394
395
396
        for type in ('int',):
            name = 'OpenMM_%sSet' % type.capitalize()
            values = {'type':type, 'name':name}
397
            print("""
398
399
400
401
/* %(name)s */
extern OPENMM_EXPORT %(name)s* %(name)s_create();
extern OPENMM_EXPORT void %(name)s_destroy(%(name)s* set);
extern OPENMM_EXPORT int %(name)s_getSize(const %(name)s* set);
402
extern OPENMM_EXPORT void %(name)s_insert(%(name)s* set, %(type)s value);""" % values, file=self.out)
403

404
        print("""
405
406
407
/* These methods need to be handled specially, since their C++ APIs cannot be directly translated to C.
   Unlike the C++ versions, the return value is allocated on the heap, and you must delete it yourself. */
extern OPENMM_EXPORT OpenMM_State* OpenMM_Context_getState(const OpenMM_Context* target, int types, int enforcePeriodicBox);
408
extern OPENMM_EXPORT OpenMM_State* OpenMM_Context_getState_2(const OpenMM_Context* target, int types, int enforcePeriodicBox, int groups);
409
extern OPENMM_EXPORT OpenMM_StringArray* OpenMM_Platform_loadPluginsFromDirectory(const char* directory);
Robert McGibbon's avatar
Robert McGibbon committed
410
extern OPENMM_EXPORT OpenMM_StringArray* OpenMM_Platform_getPluginLoadFailures();
411
412
413
414
415
extern OPENMM_EXPORT char* OpenMM_XmlSerializer_serializeSystem(const OpenMM_System* system);
extern OPENMM_EXPORT char* OpenMM_XmlSerializer_serializeState(const OpenMM_State* state);
extern OPENMM_EXPORT char* OpenMM_XmlSerializer_serializeIntegrator(const OpenMM_Integrator* integrator);
extern OPENMM_EXPORT OpenMM_System* OpenMM_XmlSerializer_deserializeSystem(const char* xml);
extern OPENMM_EXPORT OpenMM_State* OpenMM_XmlSerializer_deserializeState(const char* xml);
416
extern OPENMM_EXPORT OpenMM_Integrator* OpenMM_XmlSerializer_deserializeIntegrator(const char* xml);""", file=self.out)
417

418
        self.writeClasses()
419

420
        print("""
421
422
423
424
#if defined(__cplusplus)
}
#endif

425
#endif /*OPENMM_CWRAPPER_H_*/""", file=self.out)
426
427
428


class CSourceGenerator(WrapperGenerator):
peastman's avatar
peastman committed
429
430
    """This class generates the source file for the C API wrappers."""

431
432
    def __init__(self, inputDirname, output):
        WrapperGenerator.__init__(self, inputDirname, output)
433
434
435
436
437
438
439
440
441
442
443
444
445
        self.typeTranslations = {'bool': 'OpenMM_Boolean',
                                 'Vec3': 'OpenMM_Vec3',
                                 'std::string': 'char*',
                                 'const std::string &': 'const char*',
                                 'std::vector< std::string >': 'OpenMM_StringArray',
                                 'std::vector< Vec3 >': 'OpenMM_Vec3Array',
                                 'std::vector< std::pair< int, int > >': 'OpenMM_BondArray',
                                 'std::map< std::string, double >': 'OpenMM_ParameterArray',
                                 'std::map< std::string, std::string >': 'OpenMM_PropertyArray',
                                 'std::vector< double >': 'OpenMM_DoubleArray',
                                 'std::vector< int >': 'OpenMM_IntArray',
                                 'std::set< int >': 'OpenMM_IntSet'}
        self.inverseTranslations = dict((self.typeTranslations[key], key) for key in self.typeTranslations)
446
        self.classesByShortName = {}
peastman's avatar
peastman committed
447
        self.enumerationTypes = {}
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
        self.findTypes()
    
    def findTypes(self):
        for classNode in self._orderedClassNodes:
            className = getText("compoundname", classNode)
            shortName = stripOpenMMPrefix(className)
            typeName = convertOpenMMPrefix(className)
            self.typesByShortName[shortName] = typeName
            self.classesByShortName[shortName] = className

    def findEnumerations(self, classNode):
        enumNodes = []
        for section in findNodes(classNode, "sectiondef", kind="public-type"):
            for node in findNodes(section, "memberdef", kind="enum", prot="public"):
                enumNodes.append(node)
        className = getText("compoundname", classNode)
        typeName = convertOpenMMPrefix(className)
        for enumNode in enumNodes:
            enumName = getText("name", enumNode)
peastman's avatar
peastman committed
467
468
469
470
471
            enumTypeName = "%s_%s" % (typeName, enumName)
            enumClassName = "%s::%s" % (className, enumName)
            self.typesByShortName[enumName] = enumTypeName
            self.classesByShortName[enumName] = enumClassName
            self.enumerationTypes[enumClassName] = enumTypeName
472
473
474
475

    def writeClasses(self):
        for classNode in self._orderedClassNodes:
            className = stripOpenMMPrefix(getText("compoundname", classNode))
peastman's avatar
peastman committed
476
            self.out.write("\n/* OpenMM::%s */\n" % className)
477
478
            self.findEnumerations(classNode)
            self.writeMethods(classNode)
peastman's avatar
peastman committed
479
        self.out.write("\n")
480
481
482
483
484
485
486

    def writeMethods(self, classNode):
        methodList = self.getClassMethods(classNode)
        className = getText("compoundname", classNode)
        shortClassName = stripOpenMMPrefix(className)
        typeName = convertOpenMMPrefix(className)
        destructorName = '~'+shortClassName
487
        isAbstract = any('virt' in method.attrib and method.attrib['virt'] == 'pure-virtual' for method in classNode.getiterator('memberdef'))
488

489
        if not isAbstract:
490
491
492
493
494
495
496
497
498
499
500
501
502
503
            # Write constructors
            numConstructors = 0
            for methodNode in methodList:
                methodDefinition = getText("definition", methodNode)
                shortMethodDefinition = stripOpenMMPrefix(methodDefinition)
                methodName = shortMethodDefinition.split()[-1]
                if methodName == shortClassName:
                    if self.shouldHideMethod(methodNode):
                        continue
                    numConstructors += 1
                    if numConstructors == 1:
                        suffix = ""
                    else:
                        suffix = "_%d" % numConstructors
peastman's avatar
peastman committed
504
                    self.out.write("OPENMM_EXPORT %s* %s_create%s(" % (typeName, typeName, suffix))
505
                    self.writeArguments(methodNode, False)
peastman's avatar
peastman committed
506
507
                    self.out.write(") {\n")
                    self.out.write("    return reinterpret_cast<%s*>(new %s(" % (typeName, className))
508
                    self.writeInvocationArguments(methodNode, False)
peastman's avatar
peastman committed
509
510
                    self.out.write("));\n")
                    self.out.write("}\n")
511
    
peastman's avatar
peastman committed
512
513
514
515
        # Write destructor
        self.out.write("OPENMM_EXPORT void %s_destroy(%s* target) {\n" % (typeName, typeName))
        self.out.write("    delete reinterpret_cast<%s*>(target);\n" % className)
        self.out.write("}\n")
516

peastman's avatar
peastman committed
517
518
        # Record method names for future reference.
        methodNames = {}
519
520
521
        for methodNode in methodList:
            methodDefinition = getText("definition", methodNode)
            shortMethodDefinition = stripOpenMMPrefix(methodDefinition)
peastman's avatar
peastman committed
522
523
524
525
526
            methodNames[methodNode] = shortMethodDefinition.split()[-1]
        
        # Write other methods
        for methodNode in methodList:
            methodName = methodNames[methodNode]
527
528
529
530
            if methodName in (shortClassName, destructorName):
                continue
            if self.shouldHideMethod(methodNode):
                continue
peastman's avatar
peastman committed
531
532
533
534
            isConstMethod = (methodNode.attrib['const'] == 'yes')
            if isConstMethod and any(methodNames[m] == methodName and m.attrib['const'] == 'no' for m in methodList):
                # There are two identical methods that differ only in whether they are const.  Skip the const one.
                continue
535
536
537
538
            methodType = getText("type", methodNode)
            returnType = self.getType(methodType)
            if methodType in self.classesByShortName:
                methodType = self.classesByShortName[methodType]
peastman's avatar
peastman committed
539
            self.out.write("OPENMM_EXPORT %s %s_%s(" % (returnType, typeName, methodName))
540
541
542
            isInstanceMethod = (methodNode.attrib['static'] != 'yes')
            if isInstanceMethod:
                if isConstMethod:
peastman's avatar
peastman committed
543
544
                    self.out.write('const ')
                self.out.write("%s* target" % typeName)
545
            self.writeArguments(methodNode, isInstanceMethod)
peastman's avatar
peastman committed
546
547
            self.out.write(") {\n")
            self.out.write("    ")
548
            if returnType != 'void':
peastman's avatar
peastman committed
549
550
551
552
553
                if methodType.endswith('&'):
                    # Convert references to pointers
                    self.out.write('%s* result = &' % methodType[:-1].strip())
                else:
                    self.out.write('%s result = ' % methodType)
554
            if isInstanceMethod:
peastman's avatar
peastman committed
555
                self.out.write('reinterpret_cast<')
556
                if isConstMethod:
peastman's avatar
peastman committed
557
558
                    self.out.write('const ')
                self.out.write('%s*>(target)->' % className)
559
            else:
peastman's avatar
peastman committed
560
561
                self.out.write('%s::' % className)
            self.out.write('%s(' % methodName)
562
            self.writeInvocationArguments(methodNode, False)
peastman's avatar
peastman committed
563
            self.out.write(');\n')
564
            if returnType != 'void':
peastman's avatar
peastman committed
565
566
                self.out.write('    return %s;\n' % self.wrapValue(methodType, 'result'))
            self.out.write("}\n")
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
    
    def writeArguments(self, methodNode, initialSeparator):
        paramList = findNodes(methodNode, 'param')
        if initialSeparator:
            separator = ", "
        else:
            separator = ""
        for node in paramList:
            try:
                type = getText('type', node)
            except IndexError:
                type = getText('type/ref', node)
            if type == 'void':
                continue
            type = self.getType(type)
            name = getText('declname', node)
peastman's avatar
peastman committed
583
            self.out.write("%s%s %s" % (separator, type, name))
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
            separator = ", "
    
    def writeInvocationArguments(self, methodNode, initialSeparator):
        paramList = findNodes(methodNode, 'param')
        if initialSeparator:
            separator = ", "
        else:
            separator = ""
        for node in paramList:
            try:
                type = getText('type', node)
            except IndexError:
                type = getText('type/ref', node)
            if type == 'void':
                continue
            name = getText('declname', node)
peastman's avatar
peastman committed
600
601
602
            if self.getType(type) != type:
                name = self.unwrapValue(type, name)
            self.out.write("%s%s" % (separator, name))
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
            separator = ", "
    
    def getType(self, type):
        if type in self.typeTranslations:
            return self.typeTranslations[type]
        if type in self.typesByShortName:
            return self.typesByShortName[type]
        if type.startswith('const '):
            return 'const '+self.getType(type[6:].strip())
        if type.endswith('&') or type.endswith('*'):
            return self.getType(type[:-1].strip())+'*'
        return type
    
    def wrapValue(self, type, value):
        if type == 'bool':
            return '(%s ? OpenMM_True : OpenMM_False)' % value
        if type == 'std::string':
            return '%s.c_str()' % value
        if type == 'const std::string &':
peastman's avatar
peastman committed
622
623
624
            return '%s->c_str()' % value
        if type in self.enumerationTypes:
            return 'static_cast<%s>(%s)' % (self.enumerationTypes[type], value)
625
626
627
628
629
630
        wrappedType = self.getType(type)
        if wrappedType == type:
            return value;
        if type.endswith('*') or type.endswith('&'):
            return 'reinterpret_cast<%s>(%s)' % (wrappedType, value)
        return 'static_cast<%s>(%s)' % (wrappedType, value)
peastman's avatar
peastman committed
631
632
633
634
635
636
    
    def unwrapValue(self, type, value):
        if type.endswith('&'):
            unwrappedType = type[:-1].strip()
            if unwrappedType in self.classesByShortName:
                unwrappedType  = self.classesByShortName[unwrappedType]
637
638
            if unwrappedType == 'const std::string':
                return 'std::string(%s)' % value
peastman's avatar
peastman committed
639
640
641
642
643
644
            return '*'+self.unwrapValue(unwrappedType+'*', value)
        if type in self.classesByShortName:
            return 'static_cast<%s>(%s)' % (self.classesByShortName[type], value)
        if type == 'bool':
            return value
        return 'reinterpret_cast<%s>(%s)' % (type, value)
645
646

    def writeOutput(self):
647
        print("""
648
649
#include "OpenMM.h"
#include "OpenMMCWrapper.h"
650
#include <cstdlib>
651
#include <cstring>
652
#include <sstream>
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
#include <vector>

using namespace OpenMM;
using namespace std;

extern "C" {

/* OpenMM_Vec3 */
OPENMM_EXPORT OpenMM_Vec3 OpenMM_Vec3_scale(const OpenMM_Vec3 vec, double scale) {
    OpenMM_Vec3 result = {vec.x*scale, vec.y*scale, vec.z*scale};
    return result;
}

/* OpenMM_Vec3Array */
OPENMM_EXPORT OpenMM_Vec3Array* OpenMM_Vec3Array_create(int size) {
    return reinterpret_cast<OpenMM_Vec3Array*>(new vector<Vec3>(size));
}
OPENMM_EXPORT void OpenMM_Vec3Array_destroy(OpenMM_Vec3Array* array) {
    delete reinterpret_cast<vector<Vec3>*>(array);
}
OPENMM_EXPORT int OpenMM_Vec3Array_getSize(const OpenMM_Vec3Array* array) {
    return reinterpret_cast<const vector<Vec3>*>(array)->size();
}
OPENMM_EXPORT void OpenMM_Vec3Array_resize(OpenMM_Vec3Array* array, int size) {
    reinterpret_cast<vector<Vec3>*>(array)->resize(size);
}
OPENMM_EXPORT void OpenMM_Vec3Array_append(OpenMM_Vec3Array* array, const OpenMM_Vec3 vec) {
    reinterpret_cast<vector<Vec3>*>(array)->push_back(Vec3(vec.x, vec.y, vec.z));
}
OPENMM_EXPORT void OpenMM_Vec3Array_set(OpenMM_Vec3Array* array, int index, const OpenMM_Vec3 vec) {
    (*reinterpret_cast<vector<Vec3>*>(array))[index] = Vec3(vec.x, vec.y, vec.z);
}
OPENMM_EXPORT const OpenMM_Vec3* OpenMM_Vec3Array_get(const OpenMM_Vec3Array* array, int index) {
peastman's avatar
peastman committed
686
    return reinterpret_cast<const OpenMM_Vec3*>((&(*reinterpret_cast<const vector<Vec3>*>(array))[index]));
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
}

/* OpenMM_StringArray */
OPENMM_EXPORT OpenMM_StringArray* OpenMM_StringArray_create(int size) {
    return reinterpret_cast<OpenMM_StringArray*>(new vector<string>(size));
}
OPENMM_EXPORT void OpenMM_StringArray_destroy(OpenMM_StringArray* array) {
    delete reinterpret_cast<vector<string>*>(array);
}
OPENMM_EXPORT int OpenMM_StringArray_getSize(const OpenMM_StringArray* array) {
    return reinterpret_cast<const vector<string>*>(array)->size();
}
OPENMM_EXPORT void OpenMM_StringArray_resize(OpenMM_StringArray* array, int size) {
    reinterpret_cast<vector<string>*>(array)->resize(size);
}
OPENMM_EXPORT void OpenMM_StringArray_append(OpenMM_StringArray* array, const char* str) {
    reinterpret_cast<vector<string>*>(array)->push_back(string(str));
}
OPENMM_EXPORT void OpenMM_StringArray_set(OpenMM_StringArray* array, int index, const char* str) {
    (*reinterpret_cast<vector<string>*>(array))[index] = string(str);
}
OPENMM_EXPORT const char* OpenMM_StringArray_get(const OpenMM_StringArray* array, int index) {
    return (*reinterpret_cast<const vector<string>*>(array))[index].c_str();
}

/* OpenMM_BondArray */
OPENMM_EXPORT OpenMM_BondArray* OpenMM_BondArray_create(int size) {
    return reinterpret_cast<OpenMM_BondArray*>(new vector<pair<int, int> >(size));
}
OPENMM_EXPORT void OpenMM_BondArray_destroy(OpenMM_BondArray* array) {
    delete reinterpret_cast<vector<pair<int, int> >*>(array);
}
OPENMM_EXPORT int OpenMM_BondArray_getSize(const OpenMM_BondArray* array) {
    return reinterpret_cast<const vector<pair<int, int> >*>(array)->size();
}
OPENMM_EXPORT void OpenMM_BondArray_resize(OpenMM_BondArray* array, int size) {
    reinterpret_cast<vector<pair<int, int> >*>(array)->resize(size);
}
OPENMM_EXPORT void OpenMM_BondArray_append(OpenMM_BondArray* array, int particle1, int particle2) {
    reinterpret_cast<vector<pair<int, int> >*>(array)->push_back(pair<int, int>(particle1, particle2));
}
OPENMM_EXPORT void OpenMM_BondArray_set(OpenMM_BondArray* array, int index, int particle1, int particle2) {
    (*reinterpret_cast<vector<pair<int, int> >*>(array))[index] = pair<int, int>(particle1, particle2);
}
OPENMM_EXPORT void OpenMM_BondArray_get(const OpenMM_BondArray* array, int index, int* particle1, int* particle2) {
    pair<int, int> particles = (*reinterpret_cast<const vector<pair<int, int> >*>(array))[index];
    *particle1 = particles.first;
    *particle2 = particles.second;
}

/* OpenMM_ParameterArray */
OPENMM_EXPORT int OpenMM_ParameterArray_getSize(const OpenMM_ParameterArray* array) {
    return reinterpret_cast<const map<string, double>*>(array)->size();
}
OPENMM_EXPORT double OpenMM_ParameterArray_get(const OpenMM_ParameterArray* array, const char* name) {
    const map<string, double>* params = reinterpret_cast<const map<string, double>*>(array);
    const map<string, double>::const_iterator iter = params->find(string(name));
    if (iter == params->end())
        throw OpenMMException("OpenMM_ParameterArray_get: No such parameter");
    return iter->second;
}

/* OpenMM_PropertyArray */
OPENMM_EXPORT int OpenMM_PropertyArray_getSize(const OpenMM_PropertyArray* array) {
    return reinterpret_cast<const map<string, double>*>(array)->size();
}
OPENMM_EXPORT const char* OpenMM_PropertyArray_get(const OpenMM_PropertyArray* array, const char* name) {
    const map<string, string>* params = reinterpret_cast<const map<string, string>*>(array);
    const map<string, string>::const_iterator iter = params->find(string(name));
    if (iter == params->end())
        throw OpenMMException("OpenMM_PropertyArray_get: No such property");
    return iter->second.c_str();
759
}""", file=self.out)
760
761
762
763

        for type in ('double', 'int'):
            name = 'OpenMM_%sArray' % type.capitalize()
            values = {'type':type, 'name':name}
764
            print("""
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
/* %(name)s */
OPENMM_EXPORT %(name)s* %(name)s_create(int size) {
    return reinterpret_cast<%(name)s*>(new vector<%(type)s>(size));
}
OPENMM_EXPORT void %(name)s_destroy(%(name)s* array) {
    delete reinterpret_cast<vector<%(type)s>*>(array);
}
OPENMM_EXPORT int %(name)s_getSize(const %(name)s* array) {
    return reinterpret_cast<const vector<%(type)s>*>(array)->size();
}
OPENMM_EXPORT void %(name)s_resize(%(name)s* array, int size) {
    reinterpret_cast<vector<%(type)s>*>(array)->resize(size);
}
OPENMM_EXPORT void %(name)s_append(%(name)s* array, %(type)s value) {
    reinterpret_cast<vector<%(type)s>*>(array)->push_back(value);
}
OPENMM_EXPORT void %(name)s_set(%(name)s* array, int index, %(type)s value) {
    (*reinterpret_cast<vector<%(type)s>*>(array))[index] = value;
}
OPENMM_EXPORT %(type)s %(name)s_get(const %(name)s* array, int index) {
    return (*reinterpret_cast<const vector<%(type)s>*>(array))[index];
786
}""" % values, file=self.out)
787
788
789
790

        for type in ('int',):
            name = 'OpenMM_%sSet' % type.capitalize()
            values = {'type':type, 'name':name}
791
            print("""
792
793
794
795
796
797
798
799
800
801
802
803
/* %(name)s */
OPENMM_EXPORT %(name)s* %(name)s_create() {
    return reinterpret_cast<%(name)s*>(new set<%(type)s>());
}
OPENMM_EXPORT void %(name)s_destroy(%(name)s* s) {
    delete reinterpret_cast<set<%(type)s>*>(s);
}
OPENMM_EXPORT int %(name)s_getSize(const %(name)s* s) {
    return reinterpret_cast<const set<%(type)s>*>(s)->size();
}
OPENMM_EXPORT void %(name)s_insert(%(name)s* s, %(type)s value) {
    reinterpret_cast<set<%(type)s>*>(s)->insert(value);
804
}""" % values, file=self.out)
805

806
        print("""
peastman's avatar
peastman committed
807
808
809
810
811
/* These methods need to be handled specially, since their C++ APIs cannot be directly translated to C.
   Unlike the C++ versions, the return value is allocated on the heap, and you must delete it yourself. */
OPENMM_EXPORT OpenMM_State* OpenMM_Context_getState(const OpenMM_Context* target, int types, int enforcePeriodicBox) {
    State result = reinterpret_cast<const Context*>(target)->getState(types, enforcePeriodicBox);
    return reinterpret_cast<OpenMM_State*>(new State(result));
812
}
813
814
815
816
OPENMM_EXPORT OpenMM_State* OpenMM_Context_getState_2(const OpenMM_Context* target, int types, int enforcePeriodicBox, int groups) {
    State result = reinterpret_cast<const Context*>(target)->getState(types, enforcePeriodicBox, groups);
    return reinterpret_cast<OpenMM_State*>(new State(result));
}
peastman's avatar
peastman committed
817
818
819
OPENMM_EXPORT OpenMM_StringArray* OpenMM_Platform_loadPluginsFromDirectory(const char* directory) {
    vector<string> result = Platform::loadPluginsFromDirectory(string(directory));
    return reinterpret_cast<OpenMM_StringArray*>(new vector<string>(result));
820
}
Robert McGibbon's avatar
Robert McGibbon committed
821
822
OPENMM_EXPORT OpenMM_StringArray* OpenMM_Platform_getPluginLoadFailures() {
    vector<string> result = Platform::getPluginLoadFailures();
Robert McGibbon's avatar
Robert McGibbon committed
823
824
    return reinterpret_cast<OpenMM_StringArray*>(new vector<string>(result));
}
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
static char* createStringFromStream(stringstream& stream) {
    int length = stream.str().size();
    char* result = (char*) malloc(length+1);
    stream.str().copy(result, length);
    result[length] = 0;
    return result;
}
OPENMM_EXPORT char* OpenMM_XmlSerializer_serializeSystem(const OpenMM_System* system) {
    stringstream stream;
    OpenMM::XmlSerializer::serialize<OpenMM::System>(reinterpret_cast<const OpenMM::System*>(system), "System", stream);
    return createStringFromStream(stream);
}
OPENMM_EXPORT char* OpenMM_XmlSerializer_serializeState(const OpenMM_State* state) {
    stringstream stream;
    OpenMM::XmlSerializer::serialize<OpenMM::State>(reinterpret_cast<const OpenMM::State*>(state), "State", stream);
    return createStringFromStream(stream);
}
OPENMM_EXPORT char* OpenMM_XmlSerializer_serializeIntegrator(const OpenMM_Integrator* integrator) {
    stringstream stream;
    OpenMM::XmlSerializer::serialize<OpenMM::Integrator>(reinterpret_cast<const OpenMM::Integrator*>(integrator), "Integrator", stream);
    return createStringFromStream(stream);
}
OPENMM_EXPORT OpenMM_System* OpenMM_XmlSerializer_deserializeSystem(const char* xml) {
    string input(xml);
    stringstream stream(input);
    return reinterpret_cast<OpenMM_System*>(OpenMM::XmlSerializer::deserialize<OpenMM::System>(stream));
}
OPENMM_EXPORT OpenMM_State* OpenMM_XmlSerializer_deserializeState(const char* xml) {
    string input(xml);
    stringstream stream(input);
    return reinterpret_cast<OpenMM_State*>(OpenMM::XmlSerializer::deserialize<OpenMM::State>(stream));
}
OPENMM_EXPORT OpenMM_Integrator* OpenMM_XmlSerializer_deserializeIntegrator(const char* xml) {
    string input(xml);
    stringstream stream(input);
    return reinterpret_cast<OpenMM_Integrator*>(OpenMM::XmlSerializer::deserialize<OpenMM::Integrator>(stream));
861
}""", file=self.out)
862
        self.writeClasses()
863
        print("}\n", file=self.out)
864

865
866
867
868
869
870
871
872
class FortranHeaderGenerator(WrapperGenerator):
    """This class generates the header file for the Fortran API wrappers."""
    
    def __init__(self, inputDirname, output):
        WrapperGenerator.__init__(self, inputDirname, output)
        self.typeTranslations = {'int': 'integer*4',
                                 'bool': 'integer*4',
                                 'double': 'real*8',
873
874
                                 'char *': 'character(*)',
                                 'const char *': 'character(*)',
875
876
877
878
879
880
881
882
883
884
                                 'std::string': 'character(*)',
                                 'const std::string &': 'character(*)',
                                 'std::vector< std::string >': 'type (OpenMM_StringArray)',
                                 'std::vector< Vec3 >': 'type (OpenMM_Vec3Array)',
                                 'std::vector< std::pair< int, int > >': 'type (OpenMM_BondArray)',
                                 'std::map< std::string, double >': 'type (OpenMM_ParameterArray)',
                                 'std::map< std::string, std::string >': 'type (OpenMM_PropertyArray)',
                                 'std::vector< double >': 'type (OpenMM_DoubleArray)',
                                 'std::vector< int >': 'type (OpenMM_IntArray)',
                                 'std::set< int >': 'type (OpenMM_IntSet)'}
885
        self.enumerationTypes = set()
886
887
888
889
890
891
    
    def writeGlobalConstants(self):
        self.out.write("    ! Global Constants\n\n")
        node = next((x for x in findNodes(self.doc.getroot(), "compounddef", kind="namespace") if x.findtext("compoundname") == "OpenMM"))
        for section in findNodes(node, "sectiondef", kind="var"):
            for memberNode in findNodes(section, "memberdef", kind="variable", mutable="no", prot="public", static="yes"):
892
                vDef = convertOpenMMPrefix(getText("name", memberNode))
893
894
895
                iDef = getText("initializer", memberNode)
                if iDef.startswith("="):
                    iDef = iDef[1:]
peastman's avatar
peastman committed
896
                self.out.write("    real*8, parameter :: OpenMM_%s = %s\n" % (vDef, iDef))
897
898
899
900
901
902
903

    def writeTypeDeclarations(self):
        self.out.write("\n    ! Type Declarations\n")
        for classNode in self._orderedClassNodes:
            className = getText("compoundname", classNode)
            shortName = stripOpenMMPrefix(className)
            typeName = convertOpenMMPrefix(className)
904
            self.out.write("\n    type %s\n" % typeName)
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
            self.out.write("        integer*8 :: handle = 0\n")
            self.out.write("    end type\n")
            self.typesByShortName[shortName] = typeName

    def writeClasses(self):
        for classNode in self._orderedClassNodes:
            className = getText("compoundname", classNode)
            self.out.write("\n        ! %s\n" % className)
            self.writeMethods(classNode)
        self.out.write("\n")

    def writeEnumerations(self, classNode):
        enumNodes = []
        for section in findNodes(classNode, "sectiondef", kind="public-type"):
            for node in findNodes(section, "memberdef", kind="enum", prot="public"):
                enumNodes.append(node)
        className = getText("compoundname", classNode)
        typeName = convertOpenMMPrefix(className)
        for enumNode in enumNodes:
            for valueNode in findNodes(enumNode, "enumvalue", prot="public"):
                vName = convertOpenMMPrefix(getText("name", valueNode))
                vInit = getText("initializer", valueNode)
                if vInit.startswith("="):
                    vInit = vInit[1:].strip()
                self.out.write("    integer*4, parameter :: %s_%s = %s\n" % (typeName, vName, vInit))
            enumName = getText("name", enumNode)
            enumTypeName = "%s_%s" % (typeName, enumName)
            self.typesByShortName[enumName] = enumTypeName
933
            self.enumerationTypes.add(enumName)
934
935
936
937
938
939
940
941
        if len(enumNodes)>0: self.out.write("\n")

    def writeMethods(self, classNode):
        methodList = self.getClassMethods(classNode)
        className = getText("compoundname", classNode)
        shortClassName = stripOpenMMPrefix(className)
        typeName = convertOpenMMPrefix(className)
        destructorName = '~'+shortClassName
942
        isAbstract = any('virt' in method.attrib and method.attrib['virt'] == 'pure-virtual' for method in classNode.getiterator('memberdef'))
943

944
        if not isAbstract:
945
946
947
948
949
950
951
952
953
954
955
956
957
958
            # Write constructors
            numConstructors = 0
            for methodNode in methodList:
                methodDefinition = getText("definition", methodNode)
                shortMethodDefinition = stripOpenMMPrefix(methodDefinition)
                methodName = shortMethodDefinition.split()[-1]
                if methodName == shortClassName:
                    if self.shouldHideMethod(methodNode):
                        continue
                    numConstructors += 1
                    if numConstructors == 1:
                        suffix = ""
                    else:
                        suffix = "_%d" % numConstructors
959
960
                    self.out.write("        subroutine %s_create%s(result" % (typeName, suffix))
                    self.writeArguments(methodNode, True)
961
962
963
964
965
966
                    self.out.write(")\n")
                    self.out.write("            use OpenMM_Types; implicit none\n")
                    self.out.write("            type (%s) result\n" % typeName)
                    self.declareArguments(methodNode)
                    self.out.write("        end subroutine\n")
    
peastman's avatar
peastman committed
967
968
969
970
971
        # Write destructor
        self.out.write("        subroutine %s_destroy(destroy)\n" % typeName)
        self.out.write("            use OpenMM_Types; implicit none\n")
        self.out.write("            type (%s) destroy\n" % typeName)
        self.out.write("        end subroutine\n")
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994

        # Record method names for future reference.
        methodNames = {}
        for methodNode in methodList:
            methodDefinition = getText("definition", methodNode)
            shortMethodDefinition = stripOpenMMPrefix(methodDefinition)
            methodNames[methodNode] = shortMethodDefinition.split()[-1]
        
        # Write other methods
        for methodNode in methodList:
            methodName = methodNames[methodNode]
            if methodName in (shortClassName, destructorName):
                continue
            if self.shouldHideMethod(methodNode):
                continue
            isConstMethod = (methodNode.attrib['const'] == 'yes')
            if isConstMethod and any(methodNames[m] == methodName and m.attrib['const'] == 'no' for m in methodList):
                # There are two identical methods that differ only in whether they are const.  Skip the const one.
                continue
            returnType = self.getType(getText("type", methodNode))
            hasReturnValue = (returnType in ('integer*4', 'real*8'))
            hasReturnArg = not (hasReturnValue or returnType == 'void')
            functionName = "%s_%s" % (typeName, methodName)
995
            functionName = functionName[:63]
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
            if hasReturnValue:
                self.out.write("        function ")
            else:
                self.out.write("        subroutine ")
            self.out.write("%s(" % functionName)
            isInstanceMethod = (methodNode.attrib['static'] != 'yes')
            if isInstanceMethod:
                self.out.write("target")
            numArgs = self.writeArguments(methodNode, isInstanceMethod)
            if hasReturnArg:
                if isInstanceMethod or numArgs > 0:
                    self.out.write(", ")
                self.out.write("result")
            self.out.write(")\n")
            self.out.write("            use OpenMM_Types; implicit none\n")
            self.out.write("            type (%s) target\n" % typeName)
            self.declareArguments(methodNode)
            if hasReturnValue:
                self.declareOneArgument(returnType, functionName)
            if hasReturnArg:
                self.declareOneArgument(returnType, 'result')
            if hasReturnValue:
                self.out.write("        end function\n")
            else:
                self.out.write("        end subroutine\n")
    
    def writeArguments(self, methodNode, initialSeparator):
        paramList = findNodes(methodNode, 'param')
        if initialSeparator:
            separator = ", "
        else:
            separator = ""
        numArgs = 0
        for node in paramList:
            try:
                type = getText('type', node)
            except IndexError:
                type = getText('type/ref', node)
            if type == 'void':
                continue
            name = getText('declname', node)
            self.out.write("%s%s" % (separator, name))
1038
            separator = ", &\n"
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
            numArgs += 1
        return numArgs
    
    def declareOneArgument(self, type, name):
        if type == 'void':
            return
        type = self.getType(type)
        if type == 'Vec3':
            self.out.write("            real*8 %s(3)\n" % name)
        else:
            self.out.write("            %s %s\n" % (type, name))
    
    def declareArguments(self, methodNode):
        paramList = findNodes(methodNode, 'param')
        for node in paramList:
            try:
                type = getText('type', node)
            except IndexError:
                type = getText('type/ref', node)
            name = getText('declname', node)
            self.declareOneArgument(type, name)
    
    def getType(self, type):
        if type in self.typeTranslations:
            return self.typeTranslations[type]
1064
1065
        if type in self.enumerationTypes:
            return 'integer*4'
1066
1067
1068
1069
1070
1071
1072
1073
1074
        if type in self.typesByShortName:
            return 'type (%s)' % self.typesByShortName[type]
        if type.startswith('const '):
            return self.getType(type[6:].strip())
        if type.endswith('&') or type.endswith('*'):
            return self.getType(type[:-1].strip())
        return type

    def writeOutput(self):
1075
        print("""
1076
1077
MODULE OpenMM_Types
    implicit none
1078
""", file=self.out)
1079
1080
        self.writeGlobalConstants()
        self.writeTypeDeclarations()
1081
        print("""
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
    type OpenMM_Vec3Array
        integer*8 :: handle = 0
    end type

    type OpenMM_StringArray
        integer*8 :: handle = 0
    end type

    type OpenMM_BondArray
        integer*8 :: handle = 0
    end type

    type OpenMM_ParameterArray
        integer*8 :: handle = 0
    end type

    type OpenMM_PropertyArray
        integer*8 :: handle = 0
    end type

    type OpenMM_DoubleArray
        integer*8 :: handle = 0
    end type

    type OpenMM_IntArray
        integer*8 :: handle = 0
    end type

    type OpenMM_IntSet
        integer*8 :: handle = 0
    end type

    ! Enumerations

    integer*4, parameter :: OpenMM_False = 0
1117
    integer*4, parameter :: OpenMM_True = 1""", file=self.out)
1118
1119
        for classNode in self._orderedClassNodes:
            self.writeEnumerations(classNode)
1120
        print("""
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
END MODULE OpenMM_Types

MODULE OpenMM
    use OpenMM_Types; implicit none
    interface

        ! OpenMM_Vec3
        subroutine OpenMM_Vec3_scale(vec, scale, result)
            use OpenMM_Types; implicit none
            real*8 vec(3)
            real*8 scale
            real*8 result(3)
        end subroutine

        ! OpenMM_Vec3Array
        subroutine OpenMM_Vec3Array_create(result, size)
            use OpenMM_Types; implicit none
            integer*4 size
            type (OpenMM_Vec3Array) result
        end subroutine
        subroutine OpenMM_Vec3Array_destroy(destroy)
            use OpenMM_Types; implicit none
            type (OpenMM_Vec3Array) destroy
        end subroutine
        function OpenMM_Vec3Array_getSize(target)
            use OpenMM_Types; implicit none
            type (OpenMM_Vec3Array) target
            integer*4 OpenMM_Vec3Array_getSize
        end function
        subroutine OpenMM_Vec3Array_resize(target, size)
            use OpenMM_Types; implicit none
            type (OpenMM_Vec3Array) target
            integer*4 size
        end subroutine
        subroutine OpenMM_Vec3Array_append(target, vec)
            use OpenMM_Types; implicit none
            type (OpenMM_Vec3Array) target
            real*8 vec(3)
        end subroutine
        subroutine OpenMM_Vec3Array_set(target, index, vec)
            use OpenMM_Types; implicit none
            type (OpenMM_Vec3Array) target
            integer*4 index
            real*8 vec(3)
        end subroutine
        subroutine OpenMM_Vec3Array_get(target, index, result)
            use OpenMM_Types; implicit none
            type (OpenMM_Vec3Array) target
            integer*4 index
            real*8 result(3)
        end subroutine

        ! OpenMM_StringArray
        subroutine OpenMM_StringArray_create(result, size)
            use OpenMM_Types; implicit none
            integer*4 size
            type (OpenMM_StringArray) result
        end subroutine
        subroutine OpenMM_StringArray_destroy(destroy)
            use OpenMM_Types; implicit none
            type (OpenMM_StringArray) destroy
        end subroutine
        function OpenMM_StringArray_getSize(target)
            use OpenMM_Types; implicit none
            type (OpenMM_StringArray) target
            integer*4 OpenMM_StringArray_getSize
        end function
        subroutine OpenMM_StringArray_resize(target, size)
            use OpenMM_Types; implicit none
            type (OpenMM_StringArray) target
            integer*4 size
        end subroutine
        subroutine OpenMM_StringArray_append(target, str)
            use OpenMM_Types; implicit none
            type (OpenMM_StringArray) target
            character(*) str
        end subroutine
        subroutine OpenMM_StringArray_set(target, index, str)
            use OpenMM_Types; implicit none
            type (OpenMM_StringArray) target
            integer*4 index
            character(*) str
        end subroutine
        subroutine OpenMM_StringArray_get(target, index, result)
            use OpenMM_Types; implicit none
            type (OpenMM_StringArray) target
            integer*4 index
            character(*) result
        end subroutine

        ! OpenMM_BondArray
        subroutine OpenMM_BondArray_create(result, size)
            use OpenMM_Types; implicit none
            integer*4 size
            type (OpenMM_BondArray) result
        end subroutine
        subroutine OpenMM_BondArray_destroy(destroy)
            use OpenMM_Types; implicit none
            type (OpenMM_BondArray) destroy
        end subroutine
        function OpenMM_BondArray_getSize(target)
            use OpenMM_Types; implicit none
            type (OpenMM_BondArray) target
            integer*4 OpenMM_BondArray_getSize
        end function
        subroutine OpenMM_BondArray_resize(target, size)
            use OpenMM_Types; implicit none
            type (OpenMM_BondArray) target
            integer*4 size
        end subroutine
        subroutine OpenMM_BondArray_append(target, particle1, particle2)
            use OpenMM_Types; implicit none
            type (OpenMM_BondArray) target
            integer*4 particle1
            integer*4 particle2
        end subroutine
        subroutine OpenMM_BondArray_set(target, index, particle1, particle2)
            use OpenMM_Types; implicit none
            type (OpenMM_BondArray) target
            integer*4 index
            integer*4 particle1
            integer*4 particle2
        end subroutine
        subroutine OpenMM_BondArray_get(target, index, particle1, particle2)
            use OpenMM_Types; implicit none
            type (OpenMM_BondArray) target
            integer*4 index
            integer*4 particle1
            integer*4 particle2
        end subroutine

        ! OpenMM_ParameterArray
        function OpenMM_ParameterArray_getSize(target)
            use OpenMM_Types; implicit none
            type (OpenMM_ParameterArray) target
            integer*4 OpenMM_ParameterArray_getSize
        end function
        subroutine OpenMM_ParameterArray_get(target, name, result)
            use OpenMM_Types; implicit none
            type (OpenMM_ParameterArray) target
            character(*) name
            character(*) result
        end subroutine

        ! OpenMM_PropertyArray
        function OpenMM_PropertyArray_getSize(target)
            use OpenMM_Types; implicit none
            type (OpenMM_ParameterArray) target
            integer*4 OpenMM_PropertyArray_getSize
        end function
        subroutine OpenMM_PropertyArray_get(target, name, result)
            use OpenMM_Types; implicit none
            type (OpenMM_PropertyArray) target
            character(*) name
            character(*) result
1276
        end subroutine""", file=self.out)
1277
1278
1279
1280

        arrayTypes = {'OpenMM_DoubleArray':'real*8', 'OpenMM_IntArray':'integer*4'}
        for name in arrayTypes:
            values = {'type':arrayTypes[name], 'name':name}
1281
            print("""
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
        ! %(name)s
        subroutine %(name)s_create(result, size)
            use OpenMM_Types; implicit none
            integer*4 size
            type (%(name)s) result
        end subroutine
        subroutine %(name)s_destroy(destroy)
            use OpenMM_Types; implicit none
            type (%(name)s) destroy
        end subroutine
        function %(name)s_getSize(target)
            use OpenMM_Types; implicit none
            type (%(name)s) target
            integer*4 %(name)s_getSize
        end function
        subroutine %(name)s_resize(target, size)
            use OpenMM_Types; implicit none
            type (%(name)s) target
            integer*4 size
        end subroutine
        subroutine %(name)s_append(target, value)
            use OpenMM_Types; implicit none
            type (%(name)s) target
            %(type)s value
        end subroutine
        subroutine %(name)s_set(target, index, value)
            use OpenMM_Types; implicit none
            type (%(name)s) target
            integer*4 index
            %(type)s value
        end subroutine
        subroutine %(name)s_get(target, index, result)
            use OpenMM_Types; implicit none
            type (%(name)s) target
            integer*4 index
            %(type)s result
1318
        end subroutine""" % values, file=self.out)
1319
        
1320
        print("""
1321
1322
1323
1324
1325
1326
1327
        ! These methods need to be handled specially, since their C++ APIs cannot be directly translated to Fortran.
        ! Unlike the C++ versions, the return value is allocated on the heap, and you must delete it yourself.
        subroutine OpenMM_Context_getState(target, types, enforcePeriodicBox, result)
            use OpenMM_Types; implicit none
            type (OpenMM_Context) target
            integer*4 types
            integer*4 enforcePeriodicBox
1328
            type(OpenMM_State) result
1329
        end subroutine
1330
1331
1332
1333
1334
1335
1336
1337
        subroutine OpenMM_Context_getState_2(target, types, enforcePeriodicBox, groups, result)
            use OpenMM_Types; implicit none
            type (OpenMM_Context) target
            integer*4 types
            integer*4 enforcePeriodicBox
            integer*4 groups
            type(OpenMM_State) result
        end subroutine
1338
1339
1340
        subroutine OpenMM_Platform_loadPluginsFromDirectory(directory, result)
            use OpenMM_Types; implicit none
            character(*) directory
1341
1342
            type(OpenMM_StringArray) result
        end subroutine
Robert McGibbon's avatar
Robert McGibbon committed
1343
        subroutine OpenMM_Platform_getPluginLoadFailures(result)
Robert McGibbon's avatar
Robert McGibbon committed
1344
1345
1346
            use OpenMM_Types; implicit none
            type(OpenMM_StringArray) result
        end subroutine
peastman's avatar
peastman committed
1347
        subroutine OpenMM_XmlSerializer_serializeSystemToC(system, result, result_length)
1348
1349
1350
1351
1352
            use iso_c_binding; use OpenMM_Types; implicit none
            type(OpenMM_System), intent(in) :: system
            type(c_ptr), intent(out) :: result
            integer, intent(out) :: result_length
        end subroutine
peastman's avatar
peastman committed
1353
        subroutine OpenMM_XmlSerializer_serializeStateToC(state, result, result_length)
1354
1355
1356
1357
1358
            use iso_c_binding; use OpenMM_Types; implicit none
            type(OpenMM_State), intent(in) :: state
            type(c_ptr), intent(out) :: result
            integer, intent(out) :: result_length
        end subroutine
peastman's avatar
peastman committed
1359
        subroutine OpenMM_XmlSerializer_serializeIntegratorToC(integrator, result, result_length)
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
            use iso_c_binding; use OpenMM_Types; implicit none
            type(OpenMM_Integrator), intent(in) :: integrator
            type(c_ptr), intent(out) :: result
            integer, intent(out) :: result_length
        end subroutine
        subroutine OpenMM_XmlSerializer_deserializeSystem(xml, result)
            use OpenMM_Types; implicit none
            character(*) xml
            type(OpenMM_System) result
        end subroutine
        subroutine OpenMM_XmlSerializer_deserializeState(xml, result)
            use OpenMM_Types; implicit none
            character(*) xml
            type(OpenMM_State) result
        end subroutine
        subroutine OpenMM_XmlSerializer_deserializeIntegrator(xml, result)
            use OpenMM_Types; implicit none
            character(*) xml
            type(OpenMM_Integrator) result
1379
        end subroutine""", file=self.out)
1380
1381
1382
        
        self.writeClasses()
        
1383
        print("""
1384
    end interface
peastman's avatar
peastman committed
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441

contains

    subroutine OpenMM_XmlSerializer_serializeSystem(system, result)
        use iso_c_binding, only: c_ptr, c_int, c_char, c_f_pointer
        type(OpenMM_System), intent(in) :: system
        character(len=1), allocatable, dimension(:), intent(out) :: result

        character(kind=c_char), pointer, dimension(:) :: fstr
        type(c_ptr) :: cstr
        integer :: i
        integer(kind=c_int) :: result_length

        call OpenMM_XmlSerializer_serializeSystemToC(system, cstr, result_length)
        call c_f_pointer(cstr, fstr, [ result_length ])
        allocate(character(len=1) :: result(result_length))
        do i=1,result_length
           result(i) = fstr(i)
        end do
    end subroutine

    subroutine OpenMM_XmlSerializer_serializeState(state, result)
        use iso_c_binding, only: c_ptr, c_int, c_char, c_f_pointer
        type(OpenMM_State), intent(in) :: state
        character(len=1), allocatable, dimension(:), intent(out) :: result

        character(kind=c_char), pointer, dimension(:) :: fstr
        type(c_ptr) :: cstr
        integer :: i
        integer(kind=c_int) :: result_length

        call OpenMM_XmlSerializer_serializeStateToC(state, cstr, result_length)
        call c_f_pointer(cstr, fstr, [ result_length ])
        allocate(character(len=1) :: result(result_length))
        do i=1,result_length
           result(i) = fstr(i)
        end do
    end subroutine

    subroutine OpenMM_XmlSerializer_serializeIntegrator(integrator, result)
        use iso_c_binding, only: c_ptr, c_int, c_char, c_f_pointer
        type(OpenMM_Integrator), intent(in) :: integrator
        character(len=1), allocatable, dimension(:), intent(out) :: result

        character(kind=c_char), pointer, dimension(:) :: fstr
        type(c_ptr) :: cstr
        integer :: i
        integer(kind=c_int) :: result_length

        call OpenMM_XmlSerializer_serializeIntegratorToC(integrator, cstr, result_length)
        call c_f_pointer(cstr, fstr, [ result_length ])
        allocate(character(len=1) :: result(result_length))
        do i=1,result_length
           result(i) = fstr(i)
        end do
    end subroutine

1442
END MODULE OpenMM""", file=self.out)
1443

peastman's avatar
peastman committed
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503

class FortranSourceGenerator(WrapperGenerator):
    """This class generates the source file for the Fortran API wrappers."""

    def __init__(self, inputDirname, output):
        WrapperGenerator.__init__(self, inputDirname, output)
        self.typeTranslations = {'bool': 'OpenMM_Boolean',
                                 'Vec3': 'OpenMM_Vec3',
                                 'std::string': 'char*',
                                 'const std::string &': 'const char*',
                                 'std::vector< std::string >': 'OpenMM_StringArray',
                                 'std::vector< Vec3 >': 'OpenMM_Vec3Array',
                                 'std::vector< std::pair< int, int > >': 'OpenMM_BondArray',
                                 'std::map< std::string, double >': 'OpenMM_ParameterArray',
                                 'std::map< std::string, std::string >': 'OpenMM_PropertyArray',
                                 'std::vector< double >': 'OpenMM_DoubleArray',
                                 'std::vector< int >': 'OpenMM_IntArray',
                                 'std::set< int >': 'OpenMM_IntSet'}
        self.inverseTranslations = dict((self.typeTranslations[key], key) for key in self.typeTranslations)
        self.classesByShortName = {}
        self.enumerationTypes = {}
        self.findTypes()
    
    def findTypes(self):
        for classNode in self._orderedClassNodes:
            className = getText("compoundname", classNode)
            shortName = stripOpenMMPrefix(className)
            typeName = convertOpenMMPrefix(className)
            self.typesByShortName[shortName] = typeName
            self.classesByShortName[shortName] = className

    def findEnumerations(self, classNode):
        enumNodes = []
        for section in findNodes(classNode, "sectiondef", kind="public-type"):
            for node in findNodes(section, "memberdef", kind="enum", prot="public"):
                enumNodes.append(node)
        className = getText("compoundname", classNode)
        typeName = convertOpenMMPrefix(className)
        for enumNode in enumNodes:
            enumName = getText("name", enumNode)
            enumTypeName = "%s_%s" % (typeName, enumName)
            enumClassName = "%s::%s" % (className, enumName)
            self.typesByShortName[enumName] = enumTypeName
            self.classesByShortName[enumName] = enumClassName
            self.enumerationTypes[enumClassName] = enumTypeName

    def writeClasses(self):
        for classNode in self._orderedClassNodes:
            className = stripOpenMMPrefix(getText("compoundname", classNode))
            self.out.write("\n/* OpenMM::%s */\n" % className)
            self.findEnumerations(classNode)
            self.writeMethods(classNode)
        self.out.write("\n")

    def writeMethods(self, classNode):
        methodList = self.getClassMethods(classNode)
        className = getText("compoundname", classNode)
        shortClassName = stripOpenMMPrefix(className)
        typeName = convertOpenMMPrefix(className)
        destructorName = '~'+shortClassName
1504
        isAbstract = any('virt' in method.attrib and method.attrib['virt'] == 'pure-virtual' for method in classNode.getiterator('memberdef'))
peastman's avatar
peastman committed
1505

1506
        if not isAbstract:
peastman's avatar
peastman committed
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
            # Write constructors
            numConstructors = 0
            for methodNode in methodList:
                methodDefinition = getText("definition", methodNode)
                shortMethodDefinition = stripOpenMMPrefix(methodDefinition)
                methodName = shortMethodDefinition.split()[-1]
                if methodName == shortClassName:
                    if self.shouldHideMethod(methodNode):
                        continue
                    numConstructors += 1
                    if numConstructors == 1:
                        suffix = ""
                    else:
                        suffix = "_%d" % numConstructors
                    functionName = "%s_create%s" % (typeName, suffix)
                    self.writeOneConstructor(classNode, methodNode, functionName, functionName.lower()+'_')
                    self.writeOneConstructor(classNode, methodNode, functionName, functionName.upper())
    
        # Write destructor
        functionName = "%s_destroy" % typeName
        self.writeOneDestructor(typeName, functionName.lower()+'_')
        self.writeOneDestructor(typeName, functionName.upper())

        # Record method names for future reference.
        methodNames = {}
        for methodNode in methodList:
            methodDefinition = getText("definition", methodNode)
            shortMethodDefinition = stripOpenMMPrefix(methodDefinition)
            methodNames[methodNode] = shortMethodDefinition.split()[-1]
        
        # Write other methods
        for methodNode in methodList:
            methodName = methodNames[methodNode]
            if methodName in (shortClassName, destructorName):
                continue
            if '~' in methodName:
1543
                print('***', methodName, destructorName)
peastman's avatar
peastman committed
1544
1545
1546
1547
1548
1549
1550
            if self.shouldHideMethod(methodNode):
                continue
            isConstMethod = (methodNode.attrib['const'] == 'yes')
            if isConstMethod and any(methodNames[m] == methodName and m.attrib['const'] == 'no' for m in methodList):
                # There are two identical methods that differ only in whether they are const.  Skip the const one.
                continue
            functionName = "%s_%s" % (typeName, methodName)
1551
1552
1553
            truncatedName = functionName[:63]
            self.writeOneMethod(classNode, methodNode, functionName, truncatedName.lower()+'_')
            self.writeOneMethod(classNode, methodNode, functionName, truncatedName.upper())
peastman's avatar
peastman committed
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
    
    def writeOneConstructor(self, classNode, methodNode, functionName, wrapperFunctionName):
        className = getText("compoundname", classNode)
        shortClassName = stripOpenMMPrefix(className)
        typeName = convertOpenMMPrefix(className)
        self.out.write("OPENMM_EXPORT void %s(%s*& result" % (wrapperFunctionName, typeName))
        self.writeArguments(methodNode, True)
        self.out.write(") {\n")
        self.out.write("    result = %s(" % functionName)
        self.writeInvocationArguments(methodNode, False)
        self.out.write(");\n")
        self.out.write("}\n")
    
    def writeOneDestructor(self, typeName, wrapperFunctionName):
        self.out.write("OPENMM_EXPORT void %s(%s*& destroy) {\n" % (wrapperFunctionName, typeName))
        self.out.write("    %s_destroy(destroy);\n" % typeName)
        self.out.write("    destroy = 0;\n")
        self.out.write("}\n")
    
    def writeOneMethod(self, classNode, methodNode, methodName, wrapperFunctionName):
        className = getText("compoundname", classNode)
        typeName = convertOpenMMPrefix(className)


        isConstMethod = (methodNode.attrib['const'] == 'yes')
        methodType = getText("type", methodNode)
        returnType = self.getType(methodType)
        hasReturnValue = (returnType in ('int', 'bool', 'double'))
        hasReturnArg = not (hasReturnValue or returnType == 'void')
        if methodType in self.classesByShortName:
            methodType = self.classesByShortName[methodType]
        self.out.write("OPENMM_EXPORT ")
        if hasReturnValue:
            self.out.write(returnType)
        else:
            self.out.write('void')
        self.out.write(" %s(" % wrapperFunctionName)
        isInstanceMethod = (methodNode.attrib['static'] != 'yes')
        if isInstanceMethod:
            if isConstMethod:
                self.out.write('const ')
            self.out.write("%s*& target" % typeName)
        returnArg = None
        if hasReturnArg:
            if returnType == 'const char*':
                # We need a non-const buffer to copy the result into
                returnArg = 'char* result'
            else:
                returnArg = "%s& result" % returnType
        numArgs = self.writeArguments(methodNode, isInstanceMethod, returnArg)
        if hasReturnArg and returnType == 'const char*':
            self.out.write(", int result_length")
        self.out.write(") {\n")
        self.out.write("    ")
        if hasReturnValue:
            self.out.write("return ")
        if hasReturnArg:
            if returnType == 'const char*':
                self.out.write("const char* result_chars = ")
            else:
                self.out.write("result = ")
        self.out.write("%s(" % methodName)
        if isInstanceMethod:
            self.out.write("target")
        self.writeInvocationArguments(methodNode, isInstanceMethod)
        self.out.write(');\n')
        if hasReturnArg and returnType == 'const char*':
            self.out.write("    copyAndPadString(result, result_chars, result_length);\n")
        self.out.write("}\n")
    
    def writeArguments(self, methodNode, initialSeparator, extraArg=None):
        paramList = findNodes(methodNode, 'param')
        if initialSeparator:
            separator = ", "
        else:
            separator = ""
        numArgs = 0
        
        # Write the arguments.
        
        for node in paramList:
            try:
                type = getText('type', node)
            except IndexError:
                type = getText('type/ref', node)
            if type == 'void':
                continue
            type = self.getType(type)
            if self.isHandleType(type):
                type = type+'&'
            elif type[-1] not in ('&', '*'):
                type = type+' const&'
            name = getText('declname', node)
            self.out.write("%s%s %s" % (separator, type, name))
            separator = ", "
            numArgs += 1
        
        # If an extra argument is needed for the return value, write it.
        
        if extraArg is not None:
            self.out.write("%s%s" % (separator, extraArg))
            separator = ", "
            numArgs += 1
        
        # Write length arguments for strings.
        
        for node in paramList:
            try:
                type = getText('type', node)
            except IndexError:
                type = getText('type/ref', node)
            if type == 'const std::string &':
                name = getText('declname', node)
                self.out.write(", int %s_length" % name)
                numArgs += 1
        return numArgs
    
    def writeInvocationArguments(self, methodNode, initialSeparator):
        paramList = findNodes(methodNode, 'param')
        if initialSeparator:
            separator = ", "
        else:
            separator = ""
        for node in paramList:
            try:
                type = getText('type', node)
            except IndexError:
                type = getText('type/ref', node)
            if type == 'void':
                continue
            name = getText('declname', node)
            if type == 'const std::string &':
                name = 'makeString(%s, %s_length).c_str()' % (name, name)
            self.out.write("%s%s" % (separator, name))
            separator = ", "
    
    def getType(self, type):
        if type in self.typeTranslations:
            return self.typeTranslations[type]
        if type in self.typesByShortName:
            return self.typesByShortName[type]
        if type.startswith('const '):
            return 'const '+self.getType(type[6:].strip())
        if type.endswith('&') or type.endswith('*'):
            return self.getType(type[:-1].strip())+'*'
        return type
    
    def isHandleType(self, type):
1702
1703
        if type == 'OpenMM_Vec3':
            return False
peastman's avatar
peastman committed
1704
1705
1706
1707
        if type.endswith('*') or type.endswith('&'):
            return self.isHandleType(type[:-1].strip())
        if type.startswith('const '):
            return self.isHandleType(type[6:].strip())
1708
1709
        if type.startswith('OpenMM_'):
            return True;
peastman's avatar
peastman committed
1710
1711
1712
        return False

    def writeOutput(self):
1713
        print("""
peastman's avatar
peastman committed
1714
1715
1716
1717
#include "OpenMM.h"
#include "OpenMMCWrapper.h"
#include <cstring>
#include <vector>
peastman's avatar
peastman committed
1718
#include <cstdlib>
peastman's avatar
peastman committed
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738

using namespace OpenMM;
using namespace std;

/* Utilities for dealing with Fortran's blank-padded strings. */
static void copyAndPadString(char* dest, const char* source, int length) {
    bool reachedEnd = false;
    for (int i = 0; i < length; i++) {
        if (source[i] == 0)
            reachedEnd = true;
        dest[i] = (reachedEnd ? ' ' : source[i]);
    }
}

static string makeString(const char* fsrc, int length) {
    while (length && fsrc[length-1]==' ')
        --length;
    return string(fsrc, length);
}

1739
1740
1741
1742
1743
1744
1745
static void convertStringToChars(char* source, char*& cstr, int& length) {
	length = strlen(source);
	cstr = new char[length+1];
	strcpy(cstr, source);
    free(source);
}

peastman's avatar
peastman committed
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
extern "C" {

/* OpenMM_Vec3 */
OPENMM_EXPORT void openmm_vec3_scale_(const OpenMM_Vec3& vec, double const& scale, OpenMM_Vec3& result) {
    result = OpenMM_Vec3_scale(vec, scale);
}
OPENMM_EXPORT void OPENMM_VEC3_SCALE(const OpenMM_Vec3& vec, double const& scale, OpenMM_Vec3& result) {
    result = OpenMM_Vec3_scale(vec, scale);
}

/* OpenMM_Vec3Array */
OPENMM_EXPORT void openmm_vec3array_create_(OpenMM_Vec3Array*& result, const int& size) {
    result = OpenMM_Vec3Array_create(size);
}
OPENMM_EXPORT void OPENMM_VEC3ARRAY_CREATE(OpenMM_Vec3Array*& result, const int& size) {
    result = OpenMM_Vec3Array_create(size);
}
OPENMM_EXPORT void openmm_vec3array_destroy_(OpenMM_Vec3Array*& array) {
    OpenMM_Vec3Array_destroy(array);
    array = 0;
}
OPENMM_EXPORT void OPENMM_VEC3ARRAY_DESTROY(OpenMM_Vec3Array*& array) {
    OpenMM_Vec3Array_destroy(array);
    array = 0;
}
OPENMM_EXPORT int openmm_vec3array_getsize_(const OpenMM_Vec3Array* const& array) {
    return OpenMM_Vec3Array_getSize(array);
}
OPENMM_EXPORT int OPENMM_VEC3ARRAY_GETSIZE(const OpenMM_Vec3Array* const& array) {
    return OpenMM_Vec3Array_getSize(array);
}
OPENMM_EXPORT void openmm_vec3array_resize_(OpenMM_Vec3Array* const& array, const int& size) {
    OpenMM_Vec3Array_resize(array, size);
}
OPENMM_EXPORT void OPENMM_VEC3ARRAY_RESIZE(OpenMM_Vec3Array* const& array, const int& size) {
    OpenMM_Vec3Array_resize(array, size);
}
OPENMM_EXPORT void openmm_vec3array_append_(OpenMM_Vec3Array* const& array, const OpenMM_Vec3& vec) {
    OpenMM_Vec3Array_append(array, vec);
}
OPENMM_EXPORT void OPENMM_VEC3ARRAY_APPEND(OpenMM_Vec3Array* const& array, const OpenMM_Vec3& vec) {
    OpenMM_Vec3Array_append(array, vec);
}
OPENMM_EXPORT void openmm_vec3array_set_(OpenMM_Vec3Array* const& array, const int& index, const OpenMM_Vec3& vec) {
    OpenMM_Vec3Array_set(array, index-1, vec);
}
OPENMM_EXPORT void OPENMM_VEC3ARRAY_SET(OpenMM_Vec3Array* const& array, const int& index, const OpenMM_Vec3& vec) {
    OpenMM_Vec3Array_set(array, index-1, vec);
}
OPENMM_EXPORT void openmm_vec3array_get_(const OpenMM_Vec3Array* const& array, const int& index, OpenMM_Vec3& result) {
    result = *OpenMM_Vec3Array_get(array, index-1);
}
OPENMM_EXPORT void OPENMM_VEC3ARRAY_GET(const OpenMM_Vec3Array* const& array, const int& index, OpenMM_Vec3& result) {
    result = *OpenMM_Vec3Array_get(array, index-1);
}

/* OpenMM_StringArray */
OPENMM_EXPORT void openmm_stringarray_create_(OpenMM_StringArray*& result, const int& size) {
    result = OpenMM_StringArray_create(size);
}
OPENMM_EXPORT void OPENMM_STRINGARRAY_CREATE(OpenMM_StringArray*& result, const int& size) {
    result = OpenMM_StringArray_create(size);
}
OPENMM_EXPORT void openmm_stringarray_destroy_(OpenMM_StringArray*& array) {
    OpenMM_StringArray_destroy(array);
    array = 0;
}
OPENMM_EXPORT void OPENMM_STRINGARRAY_DESTROY(OpenMM_StringArray*& array) {
    OpenMM_StringArray_destroy(array);
    array = 0;
}
OPENMM_EXPORT int openmm_stringarray_getsize_(const OpenMM_StringArray* const& array) {
    return OpenMM_StringArray_getSize(array);
}
OPENMM_EXPORT int OPENMM_STRINGARRAY_GETSIZE(const OpenMM_StringArray* const& array) {
    return OpenMM_StringArray_getSize(array);
}
OPENMM_EXPORT void openmm_stringarray_resize_(OpenMM_StringArray* const& array, const int& size) {
    OpenMM_StringArray_resize(array, size);
}
OPENMM_EXPORT void OPENMM_STRINGARRAY_RESIZE(OpenMM_StringArray* const& array, const int& size) {
    OpenMM_StringArray_resize(array, size);
}
OPENMM_EXPORT void openmm_stringarray_append_(OpenMM_StringArray* const& array, const char* str, int length) {
    OpenMM_StringArray_append(array, makeString(str, length).c_str());
}
OPENMM_EXPORT void OPENMM_STRINGARRAY_APPEND(OpenMM_StringArray* const& array, const char* str, int length) {
    OpenMM_StringArray_append(array, makeString(str, length).c_str());
}
OPENMM_EXPORT void openmm_stringarray_set_(OpenMM_StringArray* const& array, const int& index, const char* str, int length) {
  OpenMM_StringArray_set(array, index-1, makeString(str, length).c_str());
  }
OPENMM_EXPORT void OPENMM_STRINGARRAY_SET(OpenMM_StringArray* const& array, const int& index, const char* str, int length) {
  OpenMM_StringArray_set(array, index-1, makeString(str, length).c_str());
}
OPENMM_EXPORT void openmm_stringarray_get_(const OpenMM_StringArray* const& array, const int& index, char* result, int length) {
    const char* str = OpenMM_StringArray_get(array, index-1);
    copyAndPadString(result, str, length);
}
OPENMM_EXPORT void OPENMM_STRINGARRAY_GET(const OpenMM_StringArray* const& array, const int& index, char* result, int length) {
    const char* str = OpenMM_StringArray_get(array, index-1);
    copyAndPadString(result, str, length);
}

/* OpenMM_BondArray */
OPENMM_EXPORT void openmm_bondarray_create_(OpenMM_BondArray*& result, const int& size) {
    result = OpenMM_BondArray_create(size);
}
OPENMM_EXPORT void OPENMM_BONDARRAY_CREATE(OpenMM_BondArray*& result, const int& size) {
    result = OpenMM_BondArray_create(size);
}
OPENMM_EXPORT void openmm_bondarray_destroy_(OpenMM_BondArray*& array) {
    OpenMM_BondArray_destroy(array);
    array = 0;
}
OPENMM_EXPORT void OPENMM_BONDARRAY_DESTROY(OpenMM_BondArray*& array) {
    OpenMM_BondArray_destroy(array);
    array = 0;
}
OPENMM_EXPORT int openmm_bondarray_getsize_(const OpenMM_BondArray* const& array) {
    return OpenMM_BondArray_getSize(array);
}
OPENMM_EXPORT int OPENMM_BONDARRAY_GETSIZE(const OpenMM_BondArray* const& array) {
    return OpenMM_BondArray_getSize(array);
}
OPENMM_EXPORT void openmm_bondarray_resize_(OpenMM_BondArray* const& array, const int& size) {
    OpenMM_BondArray_resize(array, size);
}
OPENMM_EXPORT void OPENMM_BONDARRAY_RESIZE(OpenMM_BondArray* const& array, const int& size) {
    OpenMM_BondArray_resize(array, size);
}
OPENMM_EXPORT void openmm_bondarray_append_(OpenMM_BondArray* const& array, const int& particle1, const int& particle2) {
    OpenMM_BondArray_append(array, particle1, particle2);
}
OPENMM_EXPORT void OPENMM_BONDARRAY_APPEND(OpenMM_BondArray* const& array, const int& particle1, const int& particle2) {
    OpenMM_BondArray_append(array, particle1, particle2);
}
OPENMM_EXPORT void openmm_bondarray_set_(OpenMM_BondArray* const& array, const int& index, const int& particle1, const int& particle2) {
    OpenMM_BondArray_set(array, index-1, particle1, particle2);
}
OPENMM_EXPORT void OPENMM_BONDARRAY_SET(OpenMM_BondArray* const& array, const int& index, const int& particle1, const int& particle2) {
    OpenMM_BondArray_set(array, index-1, particle1, particle2);
}
OPENMM_EXPORT void openmm_bondarray_get_(const OpenMM_BondArray* const& array, const int& index, int* particle1, int* particle2) {
    OpenMM_BondArray_get(array, index-1, particle1, particle2);
}
OPENMM_EXPORT void OPENMM_BONDARRAY_GET(const OpenMM_BondArray* const& array, const int& index, int* particle1, int* particle2) {
    OpenMM_BondArray_get(array, index-1, particle1, particle2);
}

/* OpenMM_ParameterArray */
OPENMM_EXPORT int openmm_parameterarray_getsize_(const OpenMM_ParameterArray* const& array) {
    return OpenMM_ParameterArray_getSize(array);
}
OPENMM_EXPORT int OPENMM_PARAMETERARRAY_GETSIZE(const OpenMM_ParameterArray* const& array) {
    return OpenMM_ParameterArray_getSize(array);
}
OPENMM_EXPORT double openmm_parameterarray_get_(const OpenMM_ParameterArray* const& array, const char* name, int length) {
    return OpenMM_ParameterArray_get(array, makeString(name, length).c_str());
}
OPENMM_EXPORT double OPENMM_PARAMETERARRAY_GET(const OpenMM_ParameterArray* const& array, const char* name, int length) {
    return OpenMM_ParameterArray_get(array, makeString(name, length).c_str());
}

/* OpenMM_PropertyArray */
OPENMM_EXPORT int openmm_propertyarray_getsize_(const OpenMM_PropertyArray* const& array) {
    return OpenMM_PropertyArray_getSize(array);
}
OPENMM_EXPORT int OPENMM_PROPERTYARRAY_GETSIZE(const OpenMM_PropertyArray* const& array) {
    return OpenMM_PropertyArray_getSize(array);
}
OPENMM_EXPORT const char* openmm_propertyarray_get_(const OpenMM_PropertyArray* const& array, const char* name, int length) {
    return OpenMM_PropertyArray_get(array, makeString(name, length).c_str());
}
OPENMM_EXPORT const char* OPENMM_PROPERTYARRAY_GET(const OpenMM_PropertyArray* const& array, const char* name, int length) {
    return OpenMM_PropertyArray_get(array, makeString(name, length).c_str());
1922
}""", file=self.out)
peastman's avatar
peastman committed
1923
1924
1925
1926

        for type in ('double', 'int'):
            name = 'OpenMM_%sArray' % type.capitalize()
            values = {'type':type, 'name':name, 'name_lower':name.lower(), 'name_upper':name.upper()}
1927
            print("""
peastman's avatar
peastman committed
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
/* %(name)s */
OPENMM_EXPORT void %(name_lower)s_create_(%(name)s*& result, const int& size) {
    result = %(name)s_create(size);
}
OPENMM_EXPORT void %(name_upper)s_CREATE(%(name)s*& result, const int& size) {
    result = %(name)s_create(size);
}
OPENMM_EXPORT void %(name_lower)s_destroy_(%(name)s*& array) {
    %(name)s_destroy(array);
    array = 0;
}
OPENMM_EXPORT void %(name_upper)s_DESTROY(%(name)s*& array) {
    %(name)s_destroy(array);
    array = 0;
}
OPENMM_EXPORT int %(name_lower)s_getsize_(const %(name)s* const& array) {
    return %(name)s_getSize(array);
}
OPENMM_EXPORT int %(name_upper)s_GETSIZE(const %(name)s* const& array) {
    return %(name)s_getSize(array);
}
OPENMM_EXPORT void %(name_lower)s_resize_(%(name)s* const& array, const int& size) {
    %(name)s_resize(array, size);
}
OPENMM_EXPORT void %(name_upper)s_RESIZE(%(name)s* const& array, const int& size) {
    %(name)s_resize(array, size);
}
OPENMM_EXPORT void %(name_lower)s_append_(%(name)s* const& array, const %(type)s& value) {
    %(name)s_append(array, value);
}
OPENMM_EXPORT void %(name_upper)s_APPEND(%(name)s* const& array, const %(type)s& value) {
    %(name)s_append(array, value);
}
OPENMM_EXPORT void %(name_lower)s_set_(%(name)s* const& array, const int& index, const %(type)s& value) {
    %(name)s_set(array, index-1, value);
}
OPENMM_EXPORT void %(name_upper)s_SET(%(name)s* const& array, const int& index, const %(type)s& value) {
    %(name)s_set(array, index-1, value);
}
OPENMM_EXPORT void %(name_lower)s_get_(const %(name)s* const& array, const int& index, %(type)s& result) {
    result = %(name)s_get(array, index-1);
}
OPENMM_EXPORT void %(name_upper)s_GET(const %(name)s* const& array, const int& index, %(type)s& result) {
    result = %(name)s_get(array, index-1);
1972
}""" % values, file=self.out)
peastman's avatar
peastman committed
1973
1974
1975
1976

        for type in ('int', ):
            name = 'OpenMM_%sSet' % type.capitalize()
            values = {'type':type, 'name':name, 'name_lower':name.lower(), 'name_upper':name.upper()}
1977
            print("""
peastman's avatar
peastman committed
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
/* %(name)s */
OPENMM_EXPORT void %(name_lower)s_create_(%(name)s*& result) {
    result = %(name)s_create();
}
OPENMM_EXPORT void %(name_upper)s_CREATE(%(name)s*& result) {
    result = %(name)s_create();
}
OPENMM_EXPORT void %(name_lower)s_destroy_(%(name)s*& array) {
    %(name)s_destroy(array);
    array = 0;
}
OPENMM_EXPORT void %(name_upper)s_DESTROY(%(name)s*& array) {
    %(name)s_destroy(array);
    array = 0;
}
OPENMM_EXPORT int %(name_lower)s_getsize_(const %(name)s* const& array) {
    return %(name)s_getSize(array);
}
OPENMM_EXPORT int %(name_upper)s_GETSIZE(const %(name)s* const& array) {
    return %(name)s_getSize(array);
}
OPENMM_EXPORT void %(name_lower)s_insert_(%(name)s* const& array, const %(type)s& value) {
    %(name)s_insert(array, value);
}
OPENMM_EXPORT void %(name_upper)s_INSERT(%(name)s* const& array, const %(type)s& value) {
    %(name)s_insert(array, value);
2004
}""" % values, file=self.out)
peastman's avatar
peastman committed
2005

2006
        print("""
peastman's avatar
peastman committed
2007
2008
2009
2010
/* These methods need to be handled specially, since their C++ APIs cannot be directly translated to C.
   Unlike the C++ versions, the return value is allocated on the heap, and you must delete it yourself. */
OPENMM_EXPORT void openmm_context_getstate_(const OpenMM_Context*& target, int const& types, int const& enforcePeriodicBox, OpenMM_State*& result) {
    result = OpenMM_Context_getState(target, types, enforcePeriodicBox);
2011
}
peastman's avatar
peastman committed
2012
2013
OPENMM_EXPORT void OPENMM_CONTEXT_GETSTATE(const OpenMM_Context*& target, int const& types, int const& enforcePeriodicBox, OpenMM_State*& result) {
    result = OpenMM_Context_getState(target, types, enforcePeriodicBox);
2014
}
2015
2016
2017
2018
2019
2020
OPENMM_EXPORT void openmm_context_getstate_2_(const OpenMM_Context*& target, int const& types, int const& enforcePeriodicBox, int const& groups, OpenMM_State*& result) {
    result = OpenMM_Context_getState_2(target, types, enforcePeriodicBox, groups);
}
OPENMM_EXPORT void OPENMM_CONTEXT_GETSTATE_2(const OpenMM_Context*& target, int const& types, int const& enforcePeriodicBox, int const& groups, OpenMM_State*& result) {
    result = OpenMM_Context_getState_2(target, types, enforcePeriodicBox, groups);
}
peastman's avatar
peastman committed
2021
2022
OPENMM_EXPORT void openmm_platform_loadpluginsfromdirectory_(const char* directory, OpenMM_StringArray*& result, int length) {
    result = OpenMM_Platform_loadPluginsFromDirectory(makeString(directory, length).c_str());
2023
}
peastman's avatar
peastman committed
2024
2025
OPENMM_EXPORT void OPENMM_PLATFORM_LOADPLUGINSFROMDIRECTORY(const char* directory, OpenMM_StringArray*& result, int length) {
    result = OpenMM_Platform_loadPluginsFromDirectory(makeString(directory, length).c_str());
2026
}
Robert McGibbon's avatar
Robert McGibbon committed
2027
2028
OPENMM_EXPORT void openmm_platform_getpluginloadfailures_(OpenMM_StringArray*& result) {
    result = OpenMM_Platform_getPluginLoadFailures();
Robert McGibbon's avatar
Robert McGibbon committed
2029
}
Robert McGibbon's avatar
Robert McGibbon committed
2030
2031
OPENMM_EXPORT void OPENMM_PLATFORM_GETPLUGINLOADFAILURES(OpenMM_StringArray*& result) {
    result = OpenMM_Platform_getPluginLoadFailures();
Robert McGibbon's avatar
Robert McGibbon committed
2032
}
peastman's avatar
peastman committed
2033
OPENMM_EXPORT void openmm_xmlserializer_serializesystemtoc_(OpenMM_System*& system, char*& result, int& result_length) {
2034
2035
    convertStringToChars(OpenMM_XmlSerializer_serializeSystem(system), result, result_length);
}
peastman's avatar
peastman committed
2036
OPENMM_EXPORT void OPENMM_XMLSERIALIZER_SERIALIZESYSTEMTOC(OpenMM_System*& system, char*& result, int& result_length) {
2037
2038
    convertStringToChars(OpenMM_XmlSerializer_serializeSystem(system), result, result_length);
}
peastman's avatar
peastman committed
2039
OPENMM_EXPORT void openmm_xmlserializer_serializestatetoc_(OpenMM_State*& state, char*& result, int& result_length) {
2040
2041
    convertStringToChars(OpenMM_XmlSerializer_serializeState(state), result, result_length);
}
peastman's avatar
peastman committed
2042
OPENMM_EXPORT void OPENMM_XMLSERIALIZER_SERIALIZESTATETOC(OpenMM_State*& state, char*& result, int& result_length) {
2043
2044
    convertStringToChars(OpenMM_XmlSerializer_serializeState(state), result, result_length);
}
peastman's avatar
peastman committed
2045
OPENMM_EXPORT void openmm_xmlserializer_serializeintegratortoc_(OpenMM_Integrator*& integrator, char*& result, int& result_length) {
2046
2047
    convertStringToChars(OpenMM_XmlSerializer_serializeIntegrator(integrator), result, result_length);
}
peastman's avatar
peastman committed
2048
OPENMM_EXPORT void OPENMM_XMLSERIALIZER_SERIALIZEINTEGRATORTOC(OpenMM_Integrator*& integrator, char*& result, int& result_length) {
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
    convertStringToChars(OpenMM_XmlSerializer_serializeIntegrator(integrator), result, result_length);
}
OPENMM_EXPORT void openmm_xmlserializer_deserializesystem_(const char* xml, OpenMM_System*& result, int length) {
    result = OpenMM_XmlSerializer_deserializeSystem(makeString(xml, length).c_str());
}
OPENMM_EXPORT void OPENMM_XMLSERIALIZER_DESERIALIZESYSTEM(const char* xml, OpenMM_System*& result, int length) {
    result = OpenMM_XmlSerializer_deserializeSystem(makeString(xml, length).c_str());
}
OPENMM_EXPORT void openmm_xmlserializer_deserializestate_(const char* xml, OpenMM_State*& result, int length) {
    result = OpenMM_XmlSerializer_deserializeState(makeString(xml, length).c_str());
}
OPENMM_EXPORT void OPENMM_XMLSERIALIZER_DESERIALIZESTATE(const char* xml, OpenMM_State*& result, int length) {
    result = OpenMM_XmlSerializer_deserializeState(makeString(xml, length).c_str());
}
OPENMM_EXPORT void openmm_xmlserializer_deserializeintegrator_(const char* xml, OpenMM_Integrator*& result, int length) {
    result = OpenMM_XmlSerializer_deserializeIntegrator(makeString(xml, length).c_str());
}
OPENMM_EXPORT void OPENMM_XMLSERIALIZER_DESERIALIZEINTEGRATOR(const char* xml, OpenMM_Integrator*& result, int length) {
    result = OpenMM_XmlSerializer_deserializeIntegrator(makeString(xml, length).c_str());
2068
}""", file=self.out)
peastman's avatar
peastman committed
2069
2070

        self.writeClasses()
2071
        print("}", file=self.out)
peastman's avatar
peastman committed
2072

peastman's avatar
peastman committed
2073
2074
2075
2076
inputDirname = sys.argv[1]
builder = CHeaderGenerator(inputDirname, open(os.path.join(sys.argv[2], 'OpenMMCWrapper.h'), 'w'))
builder.writeOutput()
builder = CSourceGenerator(inputDirname, open(os.path.join(sys.argv[2], 'OpenMMCWrapper.cpp'), 'w'))
2077
builder.writeOutput()
2078
2079
builder = FortranHeaderGenerator(inputDirname, open(os.path.join(sys.argv[2], 'OpenMMFortranModule.f90'), 'w'))
builder.writeOutput()
peastman's avatar
peastman committed
2080
2081
builder = FortranSourceGenerator(inputDirname, open(os.path.join(sys.argv[2], 'OpenMMFortranWrapper.cpp'), 'w'))
builder.writeOutput()