summaryrefslogtreecommitdiff
path: root/MLKEnvironment.m
blob: e37c888a6d4d2ad9bdb462d351e8eaaa2f839319 (plain)
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
/* -*- mode: objc; coding: utf-8 -*- */
/* Copyright 2008, Matthias Benkard. */

#import <Foundation/NSDictionary.h>
#import <Foundation/NSArray.h>

#import "MLKEnvironment.h"
#import "MLKLinkedList.h"
#import "MLKCons.h"
#import "MLKUndefinedVariableException.h"


@implementation MLKEnvironment
-(MLKEnvironment *) init
{
  _bindings = [[MLKLinkedList alloc] init];
  return self;
}

-(MLKEnvironment *) initWithParent:(MLKEnvironment *)parent bindings:(NSDictionary *)bindings
{
  _bindings = [[MLKLinkedList alloc] initWithCons:[parent->_bindings firstCons]];
  [_bindings push: [NSMutableDictionary dictionaryWithCapacity:10]];
  [self addBindings: bindings];
  return self;
}

-(MLKEnvironment *) initWithParent:(MLKEnvironment *)parent
{
  return [self initWithParent:parent bindings:nil];
}

-(MLKEnvironment *) initWithBindings:(NSDictionary *)bindings
{
  return [self initWithParent:nil bindings:bindings];
}

-(void) setBinding:(MLKSymbol *)symbol to:(id)value
{
  MLKCons *cons;
  for (cons = [_bindings firstCons]; cons; cons = [cons cdr])
    {
      NSMutableDictionary *dict = [cons car];
      if ([[dict allKeys] containsObject:symbol])
        {
          [dict setObject:value forKey:symbol];
          break;
        }
    }
  
  [[[MLKUndefinedVariableException alloc] initWithEnvironment: self
                                          variableName: symbol]
    raise];
}

-(id) valueForBinding:(MLKSymbol *)symbol
{
  MLKCons *cons;
  for (cons = [_bindings firstCons]; cons; cons = [cons cdr])
    {
      NSMutableDictionary *dict = [cons car];
      if ([[dict allKeys] containsObject:symbol])
        {
          return [dict objectForKey:symbol];
        }
    }

  [[[MLKUndefinedVariableException alloc] initWithEnvironment: self
                                          variableName: symbol]
    raise];
  return nil;
}

-(void) addBindings:(NSDictionary *)bindings
{
  int i;
  NSArray *keys = [bindings allKeys];
  int count = [keys count];
  for (i = 0; i < count; i++)
    {
      [self addBinding:[keys objectAtIndex:i] to:[bindings objectForKey:[keys objectAtIndex:i]]];
    }
}

-(void) addBinding:(MLKSymbol *)symbol to:(id)value
{
  NSMutableDictionary *dict = [[_bindings firstCons] car];
  [dict setObject:value forKey:symbol];
}
@end