Piethon  1.0
A Python-like interpreter using flex and bison.
function.cpp
Go to the documentation of this file.
1 #include "exception.h"
2 #include "symbolTable.h"
3 #include "functionTable.h"
4 #include "statement.h"
5 #include "expression.h"
6 #include "function.h"
7 
8 unsigned int ParameterList::size() const {
9  return paramList.size();
10 }
11 
12 void ParameterList::add(const string& s) {
13  paramList.push_back(s);
14 }
15 
16 list<string>::const_iterator ParameterList::begin() const {
17  return paramList.begin();
18 }
19 
20 list<string>::const_iterator ParameterList::end() const {
21  return paramList.end();
22 }
23 
25  delete paramList;
26  delete stmtList;
27 }
28 
29 Number Function::apply(const SymbolTable& st, const FunctionTable& ft) const {
30  // create dummy empty expressionList to pass to no-arg function
31  ExpressionList* el = new ExpressionList();
32 
33  // evaluate the function
34  Number n = apply(st, ft, el);
35  delete el;
36  return n;
37 }
38 
39 Number Function::apply(const SymbolTable& st, const FunctionTable& ft, ExpressionList* argList) const {
40 
41  // copy existing symbol and function tables into local tables
42  SymbolTable localST(st);
43  FunctionTable localFT(ft);
44 
45  // ensure the correct number of args were passed
46  if (paramList->size() != argList->size()) {
47  throw ParameterMismatch();
48  }
49 
50  // bind passed arguments to formal parameters in local symbol table
51  list<string>::const_iterator formalIt = paramList->begin();
52  list<Expression*>::const_iterator argIt = argList->begin();
53 
54  while (formalIt != paramList->end()) {
55  localST[*formalIt] = (*argIt)->eval(st, ft);
56  ++formalIt;
57  ++argIt;
58  }
59 
60  // execute all statements in function. If the function throws a return value, return it
61  try {
62  stmtList->eval(localST, localFT);
63  } catch (ReturnValue r) {
64  return r.getValue();
65  }
66 
67  // else, the function had no return statement. Return default 0.
68  return Number(0);
69 }
list< string >::const_iterator begin() const
Definition: function.cpp:16
unsigned int size() const
Definition: expression.cpp:87
Number getValue() const
Definition: exception.cpp:15
list< Expression * >::const_iterator begin() const
Definition: expression.cpp:91
list< string >::const_iterator end() const
Definition: function.cpp:20
unsigned int size() const
Definition: function.cpp:8
Number apply(const SymbolTable &, const FunctionTable &, ExpressionList *) const
Definition: function.cpp:39
Definition: number.h:21
~Function()
Definition: function.cpp:24
void add(const string &)
Definition: function.cpp:12