@@ -2,19 +2,58 @@ function parseAdd(expression: string): Expression {
2
2
const content = expression . slice ( "(add " . length , - 1 ) ;
3
3
const list = parseList ( "(" + content + ")" ) ;
4
4
console . log ( list ) ;
5
- throw Error ( "Not implemented" ) ;
5
+ if ( Array . isArray ( list ) && list . length !== 2 ) {
6
+ throw Error ( "Invalid expression" ) ;
7
+ }
8
+ return buildExpression ( [ "add" , ...list ] ) ;
6
9
}
7
10
function parseLet ( expression : string ) : Expression {
8
11
const content = expression . slice ( "(let " . length , - 1 ) ;
9
12
const list = parseList ( "(" + content + ")" ) ;
10
13
console . log ( list ) ;
11
- throw Error ( "Not implemented" ) ;
14
+ if ( Array . isArray ( list ) && list . length == 0 ) {
15
+ throw Error ( "Invalid expression" ) ;
16
+ }
17
+ return buildExpression ( [ "let" , ...list ] ) ;
12
18
}
13
19
14
20
function parseMult ( expression : string ) : Expression {
15
21
const content = expression . slice ( "(mult " . length , - 1 ) ;
16
22
const list = parseList ( "(" + content + ")" ) ;
17
23
console . log ( list ) ;
24
+ if ( Array . isArray ( list ) && list . length !== 2 ) {
25
+ throw Error ( "Invalid expression" ) ;
26
+ }
27
+ return buildExpression ( [ "mult" , ...list ] ) ;
28
+ }
29
+ function buildExpression ( list : string | number | ListArray ) : Expression {
30
+ console . log ( list ) ;
31
+ if ( typeof list === "string" ) {
32
+ return { type : "Identifier" , name : list } ;
33
+ }
34
+ if ( typeof list === "number" ) {
35
+ return parseNumeric ( list ) ;
36
+ }
37
+
38
+ if ( Array . isArray ( list ) && list . length == 0 ) {
39
+ throw Error ( "Invalid expression" ) ;
40
+ }
41
+ if ( Array . isArray ( list ) && list [ 0 ] === "mult" ) {
42
+ return {
43
+ type : "MultExpression" ,
44
+
45
+ left : buildExpression ( list [ 1 ] ) ,
46
+ right : buildExpression ( list [ 2 ] ) ,
47
+ } ;
48
+ }
49
+ if ( Array . isArray ( list ) && list [ 0 ] === "add" ) {
50
+ return {
51
+ type : "AddExpression" ,
52
+
53
+ left : buildExpression ( list [ 1 ] ) ,
54
+ right : buildExpression ( list [ 2 ] ) ,
55
+ } ;
56
+ }
18
57
throw Error ( "Not implemented" ) ;
19
58
}
20
59
export type ListArray = Array < ListArray | string | number > ;
@@ -28,11 +67,12 @@ function parseList(expression: string): ListArray {
28
67
) ;
29
68
}
30
69
31
- function parseNumeric ( expression : string ) : Expression {
70
+ function parseNumeric ( expression : string | number ) : Expression {
32
71
return { type : "NumericLiteral" , value : Number ( expression ) } ;
33
72
}
34
73
35
74
function evaluate ( expression : string ) : number {
75
+ console . log ( expression ) ;
36
76
const ast = parse ( expression ) ;
37
77
console . log ( ast ) ;
38
78
return calculate ( ast , new ScopeList ( ) ) ;
0 commit comments