00001: package clogs.transform; 00002: 00003: import clogs.ast.*; 00004: import clogs.util.List; 00005: import clogs.util.Optional; 00006: 00007: 00008: public class EliminateInitializers extends Phase 00009: { 00010: public List<ExtDecl> transform (List<ExtDecl> edecls) 00011: { 00012: List<ExtDecl> result = List.nil (); 00013: 00014: for (ExtDecl edecl : edecls) { 00015: if (edecl instanceof Decl) { 00016: result = result.snoc (edecl); 00017: 00018: } else if (edecl instanceof FunDef) { 00019: FunDef fundef = (FunDef) edecl; 00020: result = result.snoc (new FunDef (fundef.type, fundef.name, fundef.params, transformBody (fundef.body))); 00021: 00022: } else { 00023: throw new RuntimeException ("Missing ExtDecl case: " + edecl.getClass ().getName ()); 00024: } 00025: } 00026: 00027: return result; 00028: } 00029: 00030: 00031: StatCompound transformBody (StatCompound statC) { 00032: List<Decl> declsNew = List.nil (); 00033: List<Stat> statsNew = List.nil (); 00034: 00035: for (Decl decl : statC.decls) { 00036: if (decl.eo.isEmpty ()) { 00037: declsNew = declsNew.snoc (decl); 00038: } else { 00039: declsNew = declsNew.snoc (new Decl (decl.type, decl.name, new Optional<Exp> ())); 00040: statsNew = statsNew.snoc (new StatExp (new ExpAssign (new ExpVar (decl.name), decl.eo.get ()))); 00041: } 00042: } 00043: 00044: for (Stat stat : statC.stats) { 00045: statsNew = statsNew.snoc (transformStat (stat)); 00046: } 00047: 00048: return new StatCompound (declsNew, statsNew); 00049: } 00050: 00051: 00052: Stat transformStat (Stat stat) 00053: { 00054: if (stat instanceof StatCompound) { 00055: StatCompound statC = (StatCompound) stat; 00056: return transformBody (statC).addLabels (statC.labels); 00057: 00058: } else if (stat instanceof StatExp) { 00059: return stat; 00060: 00061: } else if (stat instanceof StatGoto) { 00062: return stat; 00063: 00064: } else if (stat instanceof StatIf) { 00065: StatIf statI = (StatIf) stat; 00066: return new StatIf (statI.exp, transformStat (statI.statT), transformStat (statI.statF)).addLabels (statI.labels); 00067: 00068: } else if (stat instanceof StatReturn) { 00069: return stat; 00070: 00071: } else if (stat instanceof StatSkip) { 00072: return stat; 00073: 00074: } else if (stat instanceof StatWhile) { 00075: StatWhile statW = (StatWhile) stat; 00076: return new StatWhile (statW.exp, transformStat (statW.stat)).addLabels (statW.labels); 00077: 00078: } else { 00079: throw new RuntimeException ("Missing Stat case: " + stat.getClass ().getName ()); 00080: } 00081: } 00082: } 00083: 00084: