~romain-bouqueau-pro/abstract/master

« back to all changes in this revision

Viewing changes to src/backend.d

  • Committer: rbouqueau
  • Date: 2014-12-16 19:53:14 UTC
  • Revision ID: romain.bouqueau.pro@gmail.com-20141216195314-nw9mv4hf2imp0dgx
allow multiple backends (still using mixins)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/**
2
2
 * @file backend.d
3
3
 * @brief Representation of a generated D program
4
 
 * @author Sebastien Alaiwan
 
4
 * @author Sebastien Alaiwan - Romain Bouqueau
5
5
 * @date 2014-12-02
6
6
 */
7
7
 
37
37
  string[] codelines;
38
38
}
39
39
 
40
 
void printCode(const GProgram p, CodeStream s)
 
40
interface Backend
41
41
{
42
 
  foreach(gstruct; p.structs)
43
 
    printStruct(gstruct, s);
44
 
 
45
 
  foreach(gfunction; p.functions)
46
 
    printFunction(gfunction, s);
47
 
}
 
42
  void printCode(const GProgram p, CodeStream s);
48
43
 
49
44
private:
50
 
void printStruct(const GStruct gstruct, CodeStream s)
51
 
{
52
 
  assert(gstruct.name != "");
53
 
  s.writefln("struct %s", gstruct.name);
54
 
  s.writefln("{");
55
 
  s.indent();
56
 
 
57
 
  foreach(memberDesc; gstruct.members)
58
 
    printMember(memberDesc, s);
59
 
 
60
 
  s.unindent();
61
 
  s.writefln("}");
62
 
  s.writefln("");
63
 
}
64
 
 
65
 
void printFunction(const GFunction gfunction, CodeStream s)
66
 
{
67
 
  const retType = firstNotEmpty(gfunction.retType, "void");
68
 
 
69
 
  s.writefln("%s %s(%s)", retType, gfunction.name,
70
 
             myJoin(gfunction.args, ", "));
71
 
  s.writefln("{");
72
 
  s.indent();
73
 
 
74
 
  if(gfunction.retType != "")
75
 
    s.writefln("%s r;", gfunction.retType);
76
 
 
77
 
  foreach(line; gfunction.codelines)
78
 
    s.writefln("%s", line);
79
 
 
80
 
  if(gfunction.retType != "")
81
 
    s.writefln("return r;");
82
 
 
83
 
  s.unindent();
84
 
  s.writefln("}");
85
 
  s.writefln("");
86
 
}
87
 
 
88
 
string firstNotEmpty(string a, string b)
89
 
{
90
 
  if(a != "")
91
 
    return a;
92
 
  else
93
 
    return b;
94
 
}
95
 
 
96
 
string myJoin(const string[] tab, string sep)
97
 
{
98
 
  string r;
99
 
 
100
 
  foreach(i, element; tab)
101
 
  {
102
 
    if(i > 0)
103
 
      r ~= sep;
104
 
 
105
 
    r ~= element;
106
 
  }
107
 
 
108
 
  return r;
109
 
}
110
 
 
111
 
void printMember(const GStructMember desc, CodeStream s)
112
 
{
113
 
  string line;
114
 
  line ~= format("%s %s", desc.type, desc.name);
115
 
 
116
 
  if(desc.arrayLength > 1)
117
 
    line ~= format("[%s]", desc.arrayLength);
118
 
 
119
 
  line ~= ";";
120
 
 
121
 
  if(desc.comment != "")
122
 
    line ~= format("// %s", desc.comment);
123
 
 
124
 
  s.writefln("%s", line);
 
45
  void printStruct(const GStruct gstruct, CodeStream s);
 
46
  void printFunction(const GFunction gfunction, CodeStream s);
125
47
}
126
48