brainfuck  0.1
A full fledged brainfuck compiler
main.c
Go to the documentation of this file.
1 
9 #include <stdlib.h>
10 #include <string.h>
11 #include "common.h"
12 
20 int main(int argc, char **argv)
21 {
22  int stack_size = 1000;
23  int array_size = 1000;
24  int mode = COMPILE | ASSEMBLE | LINK;
25  char *output_file = NULL;
26  char *input_file = NULL;
27  FILE *in = NULL;
28  FILE *out = NULL;
29  int ret = my_getopt(argc, argv, &stack_size, &array_size, &output_file, &input_file, &mode);
30  if (ret < 0)
31  return -1;
32  if (get_in(mode, input_file, &in) < 0)
33  return -1;
34  if (get_as_file(mode, &out, output_file, input_file) < 0)
35  return -1;
36  compile(in, out, stack_size, array_size);
37  if (in != stdin && in != NULL)
38  fclose(in);
39  close_as_file(mode, out);
40 
41  if (!(mode & ASSEMBLE))
42  goto end;
43  char *as_file = NULL;
44  if (get_as(mode, output_file, input_file, &as_file) == NULL && !(mode & PIPE_OUT))
45  return -1;
46  char *obj_file = NULL;
47  if (get_obj(mode, output_file, input_file, &obj_file) == NULL)
48  return -1;
49  if (!(mode & PIPE_OUT))
50  assemble(mode, as_file, obj_file);
51  if (!(mode & LINK)) {
52  if (as_file)
53  free(as_file);
54  if (obj_file)
55  free(obj_file);
56  goto end;
57  }
58  if (as_file) {
59  remove(as_file);
60  free(as_file);
61  }
62  char buf[256];
63  if (output_file == NULL)
64  snprintf(buf, 256, "ld %s", obj_file);
65  else
66  snprintf(buf, 256, "ld %s -o %s", obj_file, output_file);
67  ret = system(buf);
68  if (ret == 0)
69  ret = remove(obj_file);
70  free(obj_file);
71 end:
72  return ret;
73 }
int assemble(int mode, const char *as_file, const char *obj_file)
Wrapper around assembling the assembly code.
Definition: common.c:289
char * get_as(int mode, const char *name, const char *original, char **ret)
Gets the name of the assembly code file.
Definition: common.c:153
#define COMPILE
Macros for determining state of the program.
Definition: common.h:17
int my_getopt(int argc, char **argv, int *stack_size, int *array_size, char **output_file, char **input_file, int *mode)
Custom getopt function.
Definition: common.c:71
char * get_obj(int mode, const char *name, const char *original, char **ret)
Gets the name of the assembled file.
Definition: common.c:184
int get_in(int mode, const char *input_file, FILE **in)
Gets the source code file pointer and deals with IO errors.
Definition: common.c:310
int get_as_file(int mode, FILE **out, const char *name, const char *input_name)
Gets the file pointer to the assembly code file.
Definition: common.c:217
Header for extern functions.
int close_as_file(int mode, FILE *f)
Closes the file pointer to the assembly source file.
Definition: common.c:267
int compile(FILE *in, FILE *out, int stack_size, int array_size)
compiler function
Definition: compiler.c:28
int main(int argc, char **argv)
main
Definition: main.c:20