3

Possible Duplicate:
Detecting programming language from a snippet

Is there a way to identify the following for a text snippet?

  1. Whether it is a piece of code
  2. The programming language in which it is written
Community
  • 1
  • 1
user560913
  • 315
  • 2
  • 6
  • 17
  • Run it through the compiler of the according language and see if there are any errors? Depends on what kind of code snippets we're talking about though. – Voo Sep 24 '11 at 14:26
  • 4
    `1;` is a valid statment (and thus also a valid program in its own right in the many languages where a program may consist of a single top-level statement) of a program in dozens of programming languages. `1` is valid in even more, if you count in expressions (in addition to statements and declarations). –  Sep 24 '11 at 14:27

2 Answers2

1

Not in general.

A large part of the problem is that many programming languages are similar - there are snippets of code that may be valid in mulitple languages.

It all depends on the length of the snippet. If you have enough code, you can probably figure out which language it is written in, but it might require quite a lot of code to correctly identify the language.

Larry Osterman
  • 16,086
  • 32
  • 60
1

Depends on how long is the code snippet, for extremely short code sample it may not be possible at all, and still not easy for long code snippets.

But anything that is developed for this purpose cannot ensure 100% accuracy of detecting the programming language for any length of code snippet (except if everything in the language is in the code snippet).

A lot of the programming languages is similar. One very accurate (not 100% though) is to look for the header files or libraries etc that are included in the code, and how they are added (using, #include etc), it can be a huge and very accurate hint about the programming language.

SpeedBirdNine
  • 4,610
  • 11
  • 49
  • 67