1 using System;
2 using System.Collections;
3
4 namespace Calculator
5 {
6 public class SymbolTable
7 {
8 static SymbolTable() : instance(new SymbolTable())
9 {
10 }
11 public static SymbolTable& Instance()
12 {
13 return *instance;
14 }
15 private SymbolTable() : variableMap()
16 {
17 }
18 public void SetVariable(const ustring& variableName, double variableValue)
19 {
20 variableMap[variableName] = variableValue;
21 }
22 public Result<double> GetVariableValue(const ustring& variableName)
23 {
24 Map<ustring, double>.ConstIterator it = variableMap.CFind(variableName);
25 if (it != variableMap.CEnd())
26 {
27 double value = it->second;
28 return value;
29 }
30 else
31 {
32 auto utf8Result = ToUtf8(variableName);
33 if (utf8Result.Error())
34 {
35 return Result<double>(ErrorId(utf8Result.GetErrorId()));
36 }
37 string variableNameValue = utf8Result.Value();
38 int errorId = AllocateError("variable \'" + variableNameValue + "\' not found");
39 return Result<double>(ErrorId(errorId));
40 }
41 }
42 public void Print()
43 {
44 Console.WriteLine("variables:");
45 for (const Pair<ustring, double>& pair : variableMap)
46 {
47 Console.Out() << pair.first << " = " << pair.second << endl();
48 }
49 }
50 private static UniquePtr<SymbolTable> instance;
51 private Map<ustring, double> variableMap;
52 }