开发者

Using Preprocessors to change language Syntax [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

I read that Objective-C was made by using preprocessor directives to add features of Smalltalk to C, which got me a little curious so I started tinkering with preprocessors in C++, just because I was bored and came up with this:

#include <iostream>
#include <string>
#define Constant const
#define Integer int
#define Real double
#define Boolean bool
#define Character char
#define String string;
#define System system
#define StandardLibrary std
#define OutputStream cout



int main()
{
   Integer i = 1;
   I开发者_如何学JAVAnteger ii = 2;
   Integer iii = ii + i;
   StandardLibrary::OutputStream<<iii;
   System("pause");
   return 0;
}

So yeah, it's pretty obvious you can change the names using preprocessors, but how is it possible to implement features of one language into another language using preprocessors?

I'm not planning to make my own language through this. I'm just curious as to see how it works.


A language like Objective C can be implemented using a preprocessor, but not the C preprocessor, as the C preprocessor language is fairly limited, if it even is turing complete (it may not be), it's at best a really nasty turing tarpit. A more powerful preprocessor will allow more significant alterations to syntax.

A preprocessor in general is a program that takes a source file and does text transformation according to some rules into some other set of source code, which is then compiled as for example C code.


The idea is to run the C preprocessor (gcc -E), which can be run against any language (or any text file, for that matter), on your source before running the next compilation step. Then, all of your #defines, etc. will be translated before they reach the actual compiler. So, in C#, for example, you could do the following:

// illegal C#, but valid for C preprocessor
#define INT_TYPE Int32      

namespace Test
{
   class Program
   {
      static void Main(string[] args)
      {
         INT_TYPE x = 42;
         Console.WriteLine(x);
      }
   }
}

Then, you'd preprocess the code using the C preprocessor (gcc -E) and then compile the result successfullly using the C# compiler. The INT_TYPE declaration would be replaced by Int32 after the preprocessing stage.

This technique is useful for integrating text macros (at your own risk) in virtually any language.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜