File: FuncPtr.cpp

package info (click to toggle)
freemat 4.0-5
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, wheezy
  • size: 174,736 kB
  • ctags: 67,053
  • sloc: cpp: 351,060; ansic: 255,892; sh: 40,590; makefile: 4,323; perl: 4,058; asm: 3,313; pascal: 2,718; fortran: 1,722; ada: 1,681; ml: 1,360; cs: 879; csh: 795; python: 430; sed: 162; lisp: 160; awk: 5
file content (237 lines) | stat: -rw-r--r-- 8,395 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
/*
 * Copyright (c) 2009 Samit Basu
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */
#include "Array.hpp"
#include "Struct.hpp"
#include "Interpreter.hpp"
#include "Algorithms.hpp"
#include "HandleList.hpp"

#define LOOKUP(x,field) x.constStructPtr()[field].get(1)

// Suppose we have: func1/func2, filename = path1/func1.m
// And we have locally: func1/func2, filename = path2/func1.m
// If we lookup func1/func2, and compare filename to our location indicator
// we can easily spot that we do not have the correct definition for
// the function in question.  But we cannot resurrect the function.  This
// is because if we execute the function in question, it will overwrite
// functions that are locally defined. 

static HandleList<VariableTable*> scopeHandles;

FuncPtr FuncPtrLookup(Interpreter *eval, Array ptr) {
  if ((!ptr.isUserClass()) || (ptr.className() != "functionpointer"))
    throw Exception("expected function pointer here, instead got " + ptr.className());
  QString name = LOOKUP(ptr,"name").asString();
  QString type = LOOKUP(ptr,"type").asString();
  if (type == "builtin") 
    return eval->getContext()->lookupBuiltinFunction(name);
  if (type == "mfunction") {
    // Retrieve it from the cache of 
    QString filename = LOOKUP(ptr,"location").asString();
    FuncPtr val = eval->getContext()->lookupCapturedMFunction(name,filename);
    if (!val)
      throw Exception("Function pointed to by function pointer does not exist!");
    return val;
  }
  throw Exception("Not yet finished");
}

Array FuncPtrConstructor(Interpreter *eval, FuncPtr val) {
  StringVector fields;
  fields.push_back("name");
  fields.push_back("type");
  fields.push_back("location");
  fields.push_back("captured");
  fields.push_back("workspace");
  ArrayVector values;
  values.push_back(Array(val->name));
  QString typecode;
  switch (val->type()) {
  default:
    typecode = "unknown";
    break;
  case FM_M_FUNCTION:
    typecode = "mfunction";
    break;
  case FM_BUILT_IN_FUNCTION:
  case FM_SPECIAL_FUNCTION:
    typecode = "builtin";
    break;
  case FM_IMPORTED_FUNCTION:
    typecode = "import";
    throw Exception("Cannot use function pointers on imported functions");
    break;
  }
  values.push_back(Array(typecode));
  QString location = "";
  if (val->type() == FM_M_FUNCTION) {
    MFunctionDef *mptr;
    mptr = (MFunctionDef *) val;
    eval->getContext()->captureMFunction(val);
    location = mptr->fileName;
  }
  values.push_back(Array(location));
  values.push_back(Array(false));
  values.push_back(EmptyConstructor());
  Array ret(StructConstructor(fields,values));
  ret.structPtr().setClassPath(StringVector() << "functionpointer");
  return ret;
}

//@@Signature
//sfunction @functionpointer:display FuncPtrDispFunction
//input x
//output none
ArrayVector FuncPtrDispFunction(int nargout, const ArrayVector& arg, 
				Interpreter *eval) {
  for (int i=0;i<arg.size();i++) 
    eval->outputMessage(" @" + LOOKUP(arg[i],"name").asString() + "\n");
  return ArrayVector();
}

ArrayVector FevalFunction(int nargout, const ArrayVector& arg, Interpreter* eval);

//@@Signature
//function @functionpointer:horzcat FuncPtrHorzCatFunction
//input varargin
//output x
ArrayVector FuncPtrHorzCatFunction(int nargout, const ArrayVector& arg) {
  for (int i=0;i<arg.size();i++) 
    if ((!arg[i].isUserClass()) || (arg[i].className() != "functionpointer"))
      throw Exception("Cannot concatenate classes of different types");
  ArrayMatrix t;
  t.push_back(arg);
  return MatrixConstructor(t);
}

static ArrayVector FuncPtrCall(int nargout, ArrayVector& args, 
			       FuncPtr fptr, Interpreter* eval, 
			       Array& optr) {
  fptr->updateCode(eval);
  StructArray &rp(optr.structPtr());
  Array wsHandle(rp["workspace"].get(1));
  VariableTable *vtable = NULL;
  if (!wsHandle.isEmpty()) {
    int workspaceHandle = wsHandle.asInteger();
    vtable = scopeHandles.lookupHandle(workspaceHandle);
  }
  return (eval->doFunction(fptr,args,nargout,vtable));
}

//@@Signature
//sfunction @functionpointer:subsref FuncPtrSubsrefFunction
//input x s
//output varargout
ArrayVector FuncPtrSubsrefFunction(int nargout, const ArrayVector& arg, Interpreter* eval) {
  if (arg.size() == 0) return ArrayVector();
  Array mp(arg[0]);
  FuncPtr fptr = FuncPtrLookup(eval,mp);
  if (!fptr)
    throw Exception("Unable to find a definition for function:" + 
		    LOOKUP(mp,"name").asString());
  ArrayVector fevalArgs;
  if (arg.size() == 2) {
    if (LOOKUP(arg[1],"type").asString() != "()")
      throw Exception("for function pointers, only p(x) is defined");
    const Array &sub(LOOKUP(arg[1],"subs"));
    const BasicArray<Array> &rp(sub.constReal<Array>());
    for (index_t i=1;i<=rp.length();i++)
      fevalArgs.push_back(rp[i]);
  }
  return FuncPtrCall(nargout,fevalArgs,fptr,eval,mp);
}

//@@Signature
//sfunction @functionpointer:feval FuncPtrFevalFunction
//input x varargin
//output varargout
ArrayVector FuncPtrFevalFunction(int nargout, const ArrayVector& arg, Interpreter *eval) {
  if (arg.size() == 0) return ArrayVector();
  Array mp(arg[0]);
  FuncPtr fptr = FuncPtrLookup(eval,mp);
  if (!fptr)
    throw Exception("Unable to find a definition for function:" + 
		    LOOKUP(mp,"name").asString());
  ArrayVector fevalArgs;
  for (int i=1;i<arg.size();i++) 
    fevalArgs.push_back(arg[i]);
  return FuncPtrCall(nargout,fevalArgs,fptr,eval,mp);
}

//@@Signature
//sfunction @functionpointer:subsasgn FuncPtrSubsasgnFunction
//input x s y
//output z
ArrayVector FuncPtrSubsasgnFunction(int nargout, const ArrayVector &arg, Interpreter* eval) {
  if (arg.size() < 3) throw Exception("subsasgn requires three input arguments");
  Array x(arg[0]);
  Array s(arg[1]);
  Array y(arg[2]);
  if (!y.isEmpty() && (!y.isUserClass() || y.className() != "functionpointer"))
    throw Exception("cannot convert arrays to function pointer type");
  if (LOOKUP(s,"type").asString() != "()")
    throw Exception("for function pointers, only p(x) = y is defined");
  const Array &sub(LOOKUP(s,"subs"));
  const BasicArray<Array> &rp(sub.constReal<Array>());
  if (rp.length() != 1) throw Exception("Expression p(x) = y is invalid");
  x.set(rp.get(1),y);
  return ArrayVector(x);
}

static void CaptureFunctionPointer(Array &inp, Interpreter *walker,
				   MFunctionDef *parent) {
  if (!(LOOKUP(inp,"type").asString() == "mfunction")) return;
  FuncPtr ptr = FuncPtrLookup(walker,inp);
  MFunctionDef* mptr = (MFunctionDef*) ptr;
  if (LOOKUP(inp,"captured").toClass(Bool).constRealScalar<bool>()) return;
  Context* context = walker->getContext();
  QString myScope = context->scopeName();
  QString parentScope;
  {
    ParentScopeLocker lock(context);
    parentScope = context->scopeName();
  }
  if (!Scope::nests(parentScope,myScope)) {
    // We need to capture the variables referenced by the
    // function into the workspace
    VariableTable* vptr = new VariableTable;
    for (int i=0;i<mptr->variablesAccessed.size();i++) {
      ArrayReference ptr(context->lookupVariable(mptr->variablesAccessed[i]));
      if (ptr.valid())
	vptr->insertSymbol(mptr->variablesAccessed[i],*ptr);
    }
    inp.structPtr()["workspace"].set(1,Array(double(scopeHandles.assignHandle(vptr))));
  }
  inp.structPtr()["captured"].set(1,Array(bool(true)));
}

void CaptureFunctionPointers(ArrayVector& outputs, Interpreter *walker, 
			     MFunctionDef *parent) {
  for (int i=0;i<outputs.size();i++) {
    if (outputs[i].isUserClass() &&
	(outputs[i].className() == "functionpointer")) {
      StructArray &rp(outputs[i].structPtr());
      for (index_t j=1;j<=rp.length();j++) {
	Array fp(outputs[i].get(j));
	CaptureFunctionPointer(fp,walker,parent);
	outputs[i].set(j,fp);
      }
    }
  }
}