parse-asm-parse-gen.py 6.49 KB
Newer Older
1
#!/usr/bin/env python
Benoit Perrot's avatar
Benoit Perrot committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
##
## This file is part of Mipsy, a tiny MIPS simulator
## Copyright (C) 2003 Benoit Perrot <benoit@lrde.epita.fr>
##
## Mipsy is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## 
## Mipsy is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
## 
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##
20
21
22
23
24

import sys
import string, re

import mipsy
Benoit Perrot's avatar
Benoit Perrot committed
25
from mipsy import license, depth, define_id
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

parser = mipsy.InstructionSetParser()
instructions = parser.parse(sys.stdin)

#### Mipsy Bison parser generator --------------------------

## Prologue --------------------------
print "%{							// -*- C++ -*-"
print license
print """
#include <string>

#include \"common.hh\"

#include \"inst/label.hh\"
#include \"inst/program_builder.hh\"
#include \"inst/exp.hh\"
#include \"inst/register.hh\"
#include \"inst/all.hh\"

46
47
#include \"vm/cpu.hh\"

48
49
50
51
52
53
54
55
#include \"parse/libparse.hh\"

namespace yy
{
  extern inst::ProgramBuilder program_builder;
}

using namespace inst;
56
using vm::Cpu;
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
%}

%error-verbose
%locations
%debug

%union
{
  int			i;
  std::string		*s;
  inst::Label           *label;
  inst::Register        *reg;
  inst::Exp             *exp;
}
%{
#include \"parse/asm-scan.hh\"
%}

%token <label> LABEL		\"label\"
%token <label> LABEL_DEF	\"label definition\"
%token <i> INTEGER              \"integer\"
%token <s> STRING               \"string\"
%token <reg> REGISTER           \"register\"
%type <exp> exp

%token YYEOF		0 \"end of file\"
%token LPAREN		\"(\"
%token RPAREN		\")\"
%token COMMA		\",\"

%left EXP_ADD EXP_SUB
%left EXP_MUL EXP_DIV
%nonassoc EXP_UMINUS

%token DIR_TEXT         \".text\"
%token DIR_DATA         \".data\"
%token DIR_SPACE        \".space\"
%token DIR_WORD         \".word\"
%token DIR_ASCIIZ       \".asciiz\"
"""
  
for i in instructions:
  print "%token " + define_id(i.opcode) + '\t\t"' + i.opcode + '"'
  
print """
  
%start program
%%
// 
program
:
| program DIR_TEXT instructions
| program DIR_DATA datas


// Data definitions
datas
:
| datas data

data
// Label
:  LABEL_DEF
{ program_builder.add_data_label(* $1); }
// Reserve space
| DIR_SPACE INTEGER
{ program_builder.add_space ($2); }
// Values
| DIR_WORD INTEGER
{ program_builder.add_word ($2); }
| DIR_WORD LABEL
{ program_builder.add_word (*$2); }
| DIR_ASCIIZ STRING
{ program_builder.add_asciiz (* $2); }

// Instruction definitions
instructions
:
| instructions instruction

instruction
// Label
: LABEL_DEF
{ program_builder.add_inst_label(* $1); }

// Opcodes"""

  ## Body ------------------------------
token_map = {
  "register": "REGISTER",
  "immediate": "exp",
148
  "label": "exp",
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
  "address": "REGISTER",
  "hidden": ""
  }

for inst in instructions:
  for syntax in inst.syntaxes:

    ## Build paths from params
    paths = []
    for param in syntax.params:
      token = token_map[param.kind]
      if param.kind == "address":
        paths.append(["LPAREN"])
      else:
        paths.append(["COMMA"])

      if param.value != "":
        token = token + "=" + param.value
      if param.default != "":
        paths.append([token, "=" + param.default])
      else:
        paths.append([token])

      if param.kind == "address":
        paths.append(["RPAREN"])
    ## Expand paths
    paths = depth(paths)


    ## Add opcode and remove useless COMMAs (COMMA before default, etc.)
    prods = []
    if paths == []:
      prods = [[define_id(inst.opcode)]]
    for path in paths:
      prod = [define_id(inst.opcode)]
      for i in range(1, len(path)):
        token = path[i]
        if token == "COMMA":
          if ((i < len(path) - 2) and \
              (path[i + 1][0] == "=") and (path[i + 2] == "COMMA")) or \
              ((i == len(path) - 2) and (path[i + 1][0] == "=")) or \
              ((i == 2) and (path[1][0] == "=")):
            continue
        prod.append(token)
      prods.append(prod)
    
    ## Build action(s) from production(s)
    for prod in prods:
    
      ## Compute values of token
      values = []
      i = 0
      for token in prod:
        token = string.split(token, "=")[0]
        if token != "":
          i = i + 1
          if token in token_map.values():
            if token == "INTEGER":
              values = values + ["$" + str(i)]
            else:
              values = values + ["*$" + str(i)]

      ## Build action, expanding values
      if syntax.alias != "":
        action = syntax.alias + "("
      else:
        action = inst.opcode + "("
      i = 0
      rule = "|"
      for token in prod:
        l = string.split(token, "=")
        value = ""
        if len(l) > 1:
          value = re.sub(r"@([0-9]+)",
                         (lambda m: values[string.atoi(m.groups(0)[0])]),
                         l[1])
        if l[0] != "":
          rule = rule + " " + l[0]
        if value != "":
          action = action + value + ", "
        else:
          if l[0] in token_map.values():
            action = action + values[i] + ", "
            i = i + 1
      action = string.rstrip(action, ", ") + ")"
      
      ## Print production followed by action
      print rule
      print "{ program_builder.add_" + action + "; }"


## Epilogue --------------------------
print """
exp:
  exp EXP_ADD  exp { $$ = new OpExp(*$1, OpExp::add, *$3); }
| exp EXP_SUB  exp { $$ = new OpExp(*$1, OpExp::sub, *$3); }
| exp EXP_MUL  exp { $$ = new OpExp(*$1, OpExp::mul, *$3); }
| exp EXP_DIV  exp { $$ = new OpExp(*$1, OpExp::div, *$3); }
| EXP_SUB exp %prec EXP_UMINUS
        { $$ = new OpExp(*new IntExp(0), OpExp::sub, *$2); }
| LPAREN exp RPAREN { $$ = $2; }
| INTEGER { $$ = new IntExp($1); }
| LABEL { $$ = new LabelExp(*$1); }

%%
void
yy::Parser::error_ ()
{
  std::cerr << location << \": \" << message << std::endl;
  exit_set (exit_parse);
}

void
yy::Parser::print_ ()
{
  std::cerr << ' ' << location;
  switch (looka_)
    {
    case STRING:
      std::cerr << \": \" << *value.s;
      break;
    case INTEGER:
      std::cerr << \": \" << value.i;
      break;
    case REGISTER:
      std::cerr << \": \" << *value.reg;
      break;
    }
}

namespace yy
{
  inst::ProgramBuilder program_builder;
}
"""