3

I was wondering how stackoverflow parses all sorts of different code and identifies keywords, special characters, whitespace formatting, etc. It does this for most code I believe, and I've noticed it's even sophisticated enough to understand the relationships between everything it parses, like so:

String mystring1 = "inquotes"; //incomment
String mystring2 = "inquotes//incomment";
String mystring3 = //incomment"inquotes";

Many IDEs do this also. How is this done?

Edit: Further explaination - I am not asking about the parsing of the text, my question is, once I am past that part.. is there something like a universal XML Scheme, or cross-code format hierarchy that describes which strings are keywords, which characters denote comments, text strings, logic operators, etc. Or must I become a syntax guru for any language I wish to parse accurately?

4

2 に答える 2

3

IDE /コンパイラ/インタプリタにコードを「理解」させて色付けさせるには、コードを解析して、さまざまな構文部分を引き出す必要があります。これに関する古典的なリファレンスは、Dragon Bookの「Compilers:Principles、Techniques、andTools」です。このような構成の難しさのいくつかを見ることができます

i+++++i; 

また

list<list<hash<list<int>,hash<int,<list>>>>>;
//or just matching parens 

これを適切に行うことは難しい 問題です。Javaなどの一部の言語では、CやC ++(どちらも標準があります)やruby(仕様がなく、仕様としての実装に依存している)など、他の言語よりも簡単にこれを実行できます。ただし、ほんの数ビットの強調表示を行いたい場合は、文法の大部分をスキップして、80%のソリューションをより簡単に取得できます。SOエンジンは文字列といくつかの異なるタイプのコメントを認識しており、これはそれらの目的には十分に機能していると思います。

80%から100%の間の難しさは、ほとんどのIDEにC ++の構文強調表示があるが、VisualC++にはまだC++リファクタリングサポートがない理由の1つです。いくつかの間違いを強調するためにおそらく大丈夫です。リファクタリングを行うときは、さまざまな名前空間の変数スコープとあらゆる種類のポインターを本当に理解する必要があります。

于 2010-08-19T00:48:14.137 に答える
2

In order to correctly highlight a language, you have to build a parse tree. This requires first tokenizing the string, and then either performing a top-down or a bottom-up parse. Afterwards, something walks the tree and highlights the portions of the original string corresponding to nodes of a certain sort.

To really understand this, you're going to have to read a book on compiler design/programming language fundamentals. The relevant topics are tokenizers, parsing, and grammars.

于 2010-08-18T23:56:19.557 に答える