Files
MicroST-Compiler/STCompiler.Compiler/Ast.cs

95 lines
2.6 KiB
C#

namespace STCompiler.Compiler;
using System.Collections.Generic;
using STCompiler.Common;
public abstract class StNode {}
public class ProgramNode:StNode{ public List<VarDecl> Vars=new(); public List<Stmt> Stmts=new(); }
public class VarDecl:StNode{
required public string Name;
public VarType Type;
public Expr? Init;
}
public abstract class Stmt:StNode{}
public class AssignStmt:Stmt{
required public string Target; // Variable name
public Expr? Index; // Array index if this is an array assignment
required public Expr Expr; // Value to assign
}
public class IfStmt:Stmt{
required public Expr Cond;
public List<Stmt> ThenStmts=new();
public List<Stmt> ElseStmts=new();
}
public class WhileStmt:Stmt{
required public Expr Cond;
public List<Stmt> Body=new();
}
public class ForStmt:Stmt{
required public string Var;
required public Expr Start;
required public Expr End;
public Expr Step = new IntExpr(1);
public List<Stmt> Body=new();
}
public abstract class Expr:StNode {
public VarType Type; // Speichert den Typ des Ausdrucks
}
public class IntExpr:Expr {
public long Value;
public IntExpr(long v, VarType type = VarType.DINT) {
Value = v;
Type = type;
}
}
public class RealExpr:Expr {
public double Value;
public RealExpr(double v, VarType type = VarType.REAL) {
Value = v;
Type = type;
}
}
public class VarExpr:Expr {
public string Name;
public VarExpr(string n, VarType type) {
Name = n;
Type = type;
}
}
public class BinaryExpr:Expr {
public Expr L;
public Expr R;
public TokType Op;
public BinaryExpr(Expr l, TokType op, Expr r) {
L = l;
Op = op;
R = r;
Type = DetermineResultType(l.Type, r.Type);
}
private static VarType DetermineResultType(VarType left, VarType right) {
// Wenn einer der Operanden LREAL ist, ist das Ergebnis LREAL
if (left == VarType.LREAL || right == VarType.LREAL)
return VarType.LREAL;
// Wenn einer der Operanden REAL ist, ist das Ergebnis REAL
if (left == VarType.REAL || right == VarType.REAL)
return VarType.REAL;
// Bei gemischten Integer-Typen nehmen wir den größeren
if ((int)left > (int)right)
return left;
return right;
}
}
public class ArrayAccessExpr : Expr {
public string ArrayName;
public Expr Index;
public ArrayAccessExpr(string name, Expr idx, VarType elementType) {
ArrayName = name;
Index = idx;
Type = elementType;
}
}