MSCC

MSCC is a small 32-bit compiler for a subset of C. It supports all the basic constructs like functions, pointers, arrays, control structures and variable scoping.

The compiler generates MASM32-compatible assembly code, which can be later compiled into an executable file. It is quite portable, only the code generator needs to be modified to support different architectures or even to generate native code instead of assembly source code.

Please note this is just a school project I did in about 3 weeks with little to no experience in compiler design and implementation. It is kinda buggy (for example – try creating an array of arrays), and there is a memory leak somewhere that I didn’t have time to fix, but it works most of the time.

This source code pretty much demonstrates what can be compiled using MSCC:

#ifndef _MSC_VER
forward int printf();
forward int strlen();
forward int scanf();
#endif
 
int global;
 
void testPtrPass(char *x)
{
  *x = 'x';
}
 
void testArith()
{
  int c;
  printf("Enter a number: ");
  scanf("%d", &c);
 
  printf("%d * %d = %d\n", c, c, c * c);
  printf("%d / 3 = %d\n", c, c / 3);
  printf("%d %% 3 = %d\n", c, c % 3);
  printf("&c = %p\n", &c);
  printf("%d + %d = %d\n", c, c, c + c);
  printf("%d - %d = %d\n", c, c, c - c);
  printf("~%d = %d\n", c, ~c);
  printf("!%d = %d\n", c, !c);
  printf("%d & 1 = %d\n", c, c & 1);
  printf("%d | 1 = %d\n", c, c | 1);
}
 
void testGlobal()
{
  printf("Updating variable at %p\n", &global);
  global = 42;
}
 
int factorial(int x)
{
  if (x > 0)
    return x * factorial(x - 1);
  else
    return 1;
}
 
int main()
{
  int i;
  char *a = "abxdef", *b;
 
  // constant expression evaluation
  char name[(5 * 8) - 8];
 
  // pointer arithmetic
  *(a + 2) = 'c';
 
  // I/O
  printf("Enter your name: ");
  scanf("%s", name);
  printf("Hello %s!\n", name);
 
  // recursion & if
  printf("Enter a small positive number: ");
  scanf("%d", &i);
  if (i > 0 && i < 30)
    printf("Factorial of %d is %d\n", i, factorial(i));
  else
    printf("I said small and positive. Never mind.");
 
  // control structures: for
  for (i = strlen(a); i > 0; i = i - 1)
    printf("%c", a[i - 1]);
  printf("\n");
 
  // control structures: while
  b = a;
  while (*b != 0) {
    printf("%c", *b);
    b = b + 1;
  }
  printf("\n");
 
  // variable scoping
  b = name;
  printf("b is now '%s'\n", b);
  {
    char *b = a;
    printf("b is now '%s'\n", b);
  }
  printf("b is now '%s'\n", b);
 
  // global variables
  global = 0;
  printf("global is now %d\n", global);
  testGlobal();
  printf("global is now %d\n", global);
 
  printf("Test arithmetic operations\n");
  testArith();
 
  printf("Test pointer parameters\n");
  printf("a points to %s\n", a);
  testPtrPass(a + 2);
  printf("a points to %s\n", a);
  return 0;
}

Featured project

This is a personal web page, with personal opinions.
Content posted herein does not establish the official position of my employer.