Last active
December 9, 2019 13:42
-
-
Save nirlanka/d240786003f00db2d98cbdecd79585b1 to your computer and use it in GitHub Desktop.
A quick & simple high-level parser for C# code (C# code that's standard-formatted)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
lines = ''' | |
using Abc.Def; | |
namespace Abc.Hijk | |
{ | |
public class Haha: ILaugh | |
{ | |
public Haha() | |
{ | |
// Constructor | |
} | |
public void Foo() | |
{ | |
// Foo | |
} | |
private List<Xy.Zw> Bar() | |
{ | |
// Bar | |
} | |
} | |
} | |
'''.split('\n') | |
class Namespace: | |
klasses = [] | |
def __init__(self, name): | |
self.name = name | |
class Klass: | |
methods = [] | |
def __init__(self, signature): | |
self.name = signature | |
class Method: | |
def __init__(self, signature, is_constructor = False): | |
self.name = signature | |
self.is_constructor = is_constructor | |
class Context: | |
def __init(self): | |
self.namespace = Namespace('_') | |
self.klass = None | |
self.method = None | |
ast = [] | |
current = Context() | |
def create_namespace_if_none(): | |
if not current.namespace: | |
current.namespace = Namespace('_') | |
ast.append(current.namespace) | |
import re | |
for l in lines: | |
l += '\n' | |
_namespace = re.findall(r'\s*namespace\s+(.+)\s*\n', l) | |
if len(_namespace) > 0: | |
current.namespace = Namespace(_namespace[0].strip()) | |
ast.append(current.namespace) | |
else: | |
_klass = re.findall(r'\s*class\s+(.+)\s*\n', l) | |
if len(_klass) > 0: | |
current.klass = Klass(_klass[0].strip()) | |
create_namespace_if_none() | |
current.namespace.klasses.append(current.klass) | |
else: | |
_method = re.findall(r'([\w\s\.\<\>]+\([\w\s\.\<\>\,\:\[\]\=]*\))\s*\n', l) | |
if len(_method) > 0: | |
current.method = Method(_method[0].strip()) | |
create_namespace_if_none() | |
if not current.klass: | |
raise 'No class for method' | |
current.klass.methods.append(current.method) | |
for n in ast: | |
print(n.name) | |
for k in n.klasses: | |
print('\t' + k.name) | |
for m in k.methods: | |
print('\t\t' + m.name) | |
# Abc.Hijk | |
# Haha: ILaugh | |
# public Haha() | |
# public void Foo() | |
# private List<Xy.Zw> Bar() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment