[c#] 소스 코드를 분석하기위한 정규식
The normal way of doing this would be to get the AST of your program and then simply search for the variable declarations you need. Gramars as suggested are a nice way of generating such AST.
But, if you need to analyse your program on the fly you can't use this option because your code might have parse errors. In this case I feel your pain...
Your only option is to parse your source code and regular expressions might help a bit.
First, I would begin with a regex similar to this:
(double|long|string|bool|object)\s*(\[\s*\])?\s+(YOUR_VARIABLE_TOKEN)
obs: YOUR_VARIABLE_TOKEN is missing because the variable has strong and defined rules about how it can be constructed for each language.
I didn't test this regex and it certainly isn't perfect. It was just to give you an idea.
Second, you would have to validate these matches with certain exception cases. For instance:
- The declaration might be inside a String literal :
"bool a;"
- The declaration might be inside a comment :
/* bool a; */
Also, this is not a very strange request. Eclipse does this kind of evaluation too in some cases like indenting.
This is not an easy task though, specially, finding those exception cases. Good Luck.
-------------------
What you are attempting to do is very difficult, if not impossible with regular expressions, especially as you have support for string constructs. What happens if I do this:
a = 'b = 3;';
I.e. in this case you would need to escape the string for your regular expression to work.
You really need to perform proper parsing of your code before you are going to be able to perform any meaningful analysis.
-------------------
I also doubt that regular expressions are suitable for this.
As Kragen has demonstrated, there are cases where regular expressions will match some piece of source code, but they will ignore the context in which that bit of source code appears. This can lead to errors. While it might be possible to write smarter regular expressions for such cases as Kragen showed, they will quickly become extremely complex and hard to read/maintain/understand, because they have to consider many different possible contexts.
I'd prefer writing a parser using a parser generator (such as Yacc or Bison). But depending on the language of your source code, that can also be quite tricky.
-------------------
What to find exactly?
리터럴 (상수) 만 찾거나 전체 선언을 찾아야합니까? 표현식을 사용하여 리터럴을 찾는 것은 괜찮지 만 전체 코드를 구문 분석하는 것은 조금 더 복잡합니다.
문법에 대한 기회를주세요
모든 코드를 파싱해야한다면 ... 문법 분석기를 아십니까? 내가 '언어 이론'을 공부할 때 우리는 코드 구문 분석을 위해 문법을 사용했습니다. 토큰 (상수, 예약어, 기호 등)에 대한 정규식을 사용하여 기본 분석기를 정의하고 모든 구조에 대해 문법 분석기를 사용할 수 있습니다.Java 옵션은
JavaCC
입니다. .Net 옵션이 있어야합니다.기본적으로 문법 분석기는 복잡한 구조를 구문 분석 할 수 있습니다 ( '메모리'포함). 유한 상태 자동 장치가 정규식과 동일하면 스택이있는 FSA (메모리)는 문법과 동일합니다. 더 많은 처리 능력이 있습니다.-------------------
이것이 .NET이라는 점을 감안할 때 CodeDOM을 사용하여 올바르게 구문 분석 할 수 있습니다.기존
C # CodeDOM 공급자
를 사용하여
Parse 메서드
를 사용하여 소스 코드의 구조화 된 표현을 가져온 다음 트래버스합니다. 이를 통해 거의 모든 .NET 언어에서 작동하는 솔루션을 만들 수 있습니다.컴파일 전에 수행해야한다고 말했지만 임시 메모리 내 컴파일을 사용할 수 있으며 그런 다음 리플렉션을 사용하여 작업 할 수 있습니다. CodeDOM 제공 업체도 도움을 드릴 수 있습니다.-------------------
정규식을 사용하지 마십시오. 당신이하고있는 것은 유형 추론이고, 나는 당신이 학교를 위해 그것을하고 있다고 생각합니다. 그들은 논리 통일과 같은 다른 방법을 배우기를 원할 것입니다.당신은 항상 분명히 다른 모든 유형에 의존하고 있습니다. 부울에 0 또는 1이 할당되면 어떻게됩니까? 정규식은 입력을 줄이는 데 좋지 않습니다. 프로그램은 기껏해야 각 유형의 식별자 목록을 생성합니다. 더 나은 접근 방식이 있습니다.상용 환경에있는 경우 솔루션은 완전히 확장 할 수없고 유지 관리 할 수없고 신뢰할 수 없으며 구현 속도가 느릴 것입니다. 이는 자신의 입장에서 볼 때 강력한 적합하지 않습니다.숙제 만하는 것이 아니라면이 언어에 대한 파서에 액세스 할 수 있어야합니다. 그렇지 않은 경우 Bison과 같은 파서 생성기로 시작해야합니다.숙제를하고 있다면 책을 읽는 것이 좋습니다.
편집 :
Bison : vP로 무엇을해야하는지 말하는 것을 잊었습니다. 각 변수에 대한 데이터 구조가 있습니다. 가능한 유형 세트를 포함해야합니다. 말,
unsigned int
하나의 비트가 각 유형을 대표로,
enum type_bits { double_bit = 1, long_bit = 2, string_bit = 4, … };
. 모든 비트를 1로 설정하여 시작하십시오. 즉
type_map = (type_bits) -1;
. 각 작업이 발생할 때마다 호환되지 않는 비트를 가리십시오. 완료되면 몇 가지 비트가 설정됩니다. 둘 이상의 우선 순위 규칙을 적용하고없는 경우 오류를 생성합니다.-------------------
유용하다고 생각되는 몇 가지 아이디어가있을 수있는 모노 프로젝트 C # 컴파일러의 소스 코드를 살펴 보았습니까?svn co svn : //anonsvn.mono-project.com/source/trunk/mcs
출처
https://stackoverflow.com/questions/2005910