-
Notifications
You must be signed in to change notification settings - Fork 1
/
FunctionDeclaration.cs
85 lines (70 loc) · 2.91 KB
/
FunctionDeclaration.cs
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
using Interpreter.Lib.BackEnd.Instructions;
using Interpreter.Lib.IR.Ast.Nodes.Expressions;
using Interpreter.Lib.IR.Ast.Nodes.Statements;
using Interpreter.Lib.IR.CheckSemantics.Exceptions;
using Interpreter.Lib.IR.CheckSemantics.Variables.Symbols;
namespace Interpreter.Lib.IR.Ast.Nodes.Declarations
{
public class FunctionDeclaration : Declaration
{
private readonly FunctionSymbol _function;
private readonly BlockStatement _statements;
public FunctionDeclaration(FunctionSymbol function, BlockStatement statements)
{
_function = function;
function.Body = this;
_statements = statements;
_statements.Parent = this;
}
public bool HasReturnStatement() => _statements.HasReturnStatement();
public void SetArguments(CallExpression call, List<Expression> expressions)
{
if (_function.Type.Arguments.Count == expressions.Count)
{
expressions.Select((e, i) => (e, i)).ToList()
.ForEach(pair =>
{
var (e, i) = pair;
var eType = e.NodeCheck();
if (_function.Type.Arguments[i].Equals(eType))
{
SymbolTable.AddSymbol(_function.Parameters[i]);
}
else throw new WrongTypeOfArgument(e.Segment, _function.Type.Arguments[i], eType);
});
}
else throw new WrongNumberOfArguments(call.Segment, _function.Parameters.Count, expressions.Count);
}
public void Clear()
{
_statements.GetAllNodes().ForEach(x => x.SymbolTable?.Clear());
SymbolTable.Clear();
}
public FunctionSymbol GetSymbol() => _function;
public override IEnumerator<AbstractSyntaxTreeNode> GetEnumerator()
{
yield return _statements;
}
protected override string NodeRepresentation() => $"function {_function.Id}";
public override List<Instruction> ToInstructions(int start)
{
var instructions = new List<Instruction>();
if (_statements.Any())
{
_function.CallInfo.Location = start + 1;
var body = new List<Instruction>
{
new BeginFunction(_function.CallInfo.Location, _function.CallInfo)
};
body.AddRange(_statements.ToInstructions(_function.CallInfo.Location + 1));
if (!_statements.HasReturnStatement())
{
body.Add(new Return(_function.CallInfo.Location, body.Last().Number + 1));
}
instructions.Add(new Goto(body.Last().Number + 1, start));
instructions.AddRange(body);
}
return instructions;
}
}
}