bool IParseNodeValidator.Validate(ParseNode node, CompilerOptions options, IErrorHandler errorHandler) { CompilationUnitNode compilationUnitNode = (CompilationUnitNode)node; foreach (AttributeBlockNode attribBlock in compilationUnitNode.Attributes) { AttributeNode scriptNamespaceNode = AttributeNode.FindAttribute(attribBlock.Attributes, "ScriptNamespace"); if (scriptNamespaceNode != null) { string scriptNamespace = (string)((LiteralNode)scriptNamespaceNode.Arguments[0]).Value; if (Utility.IsValidScriptNamespace(scriptNamespace) == false) { errorHandler.ReportError("A script namespace must be a valid script identifier.", scriptNamespaceNode.Token.Location); } } } foreach (ParseNode childNode in compilationUnitNode.Members) { if (!(childNode is NamespaceNode)) { errorHandler.ReportError("Non-namespaced types are not supported.", childNode.Token.Location); return(false); } } return(true); }
// private void button_Execute_Click(object sender, EventArgs e) { // ParserRunner pr = new ParserRunner(); try { List <Parser.Error> errors = new List <Parser.Error>(); CompilationUnitNode cn = ParserRunner.ParseFile(this.comboBox_csfile.Text, out errors); // this.textBox1.Text = ""; if (errors.Count > 0) { StringBuilder sb = new StringBuilder(); foreach (var v in errors) { sb.AppendLine(string.Format("({0},{1} token:{2}) {3}", v.Line, v.Column, v.Token, v.Message)); } this.textBox1.Text = sb.ToString(); } else { StringBuilder sb = new StringBuilder(); cn.ToSource(sb); this.textBox1.Text = sb.ToString(); } } catch (Exception ee) { MessageBox.Show(ee.ToString()); } }
public static Iterable <TypeMemberNode> getTypeMembers(CompilationUnitNode compilationUnit) { var result = new ArrayList <TypeMemberNode>(); addTypeMembers(compilationUnit.getBody(), result); return(result); }
private void button_Parser_Click(object sender, EventArgs e) { try { string file = this.comboBox_csfile.Text; Parser parser = new Parser(file); DDW.Collections.TokenCollection tc = new DDW.Collections.TokenCollection(); List <string> strs = new List <string>(); CompilationUnitNode cn = parser.Parse(tc, strs); this.textBox1.Text = ""; if (parser.Errors.Count > 0) { StringBuilder sb = new StringBuilder(); foreach (var v in parser.Errors) { sb.AppendLine(string.Format("({0},{1} token:{2}) {3}", v.Line, v.Column, v.Token, v.Message)); } this.textBox1.Text = sb.ToString(); } else { StringBuilder sb = new StringBuilder(); cn.ToSource(sb); this.textBox1.Text = sb.ToString(); } } catch (Exception ex) { } }
public void MethodDefWithReturnType() { String contents = "class MyClass \r\n" + "" + " def self.method1() : int" + " end " + "" + "end \r\n"; CompilationUnitNode unit = RookParser.ParseContents(contents); Assert.IsNotNull(unit); Assert.AreEqual(0, unit.Namespaces.Count); Assert.AreEqual(1, unit.ClassesTypes.Count); ClassDefinitionStatement ClassDefinitionStatement = unit.ClassesTypes[0] as ClassDefinitionStatement; Assert.IsNotNull(ClassDefinitionStatement); Assert.AreEqual("MyClass", ClassDefinitionStatement.Name); Assert.AreEqual(0, ClassDefinitionStatement.BaseTypes.Count); Assert.AreEqual(1, ClassDefinitionStatement.Statements.Count); MethodDefinitionStatement stmt = ClassDefinitionStatement.Statements[0] as MethodDefinitionStatement; Assert.IsNotNull(stmt); }
/*namespace-body: | '{' optional-using-directive optional-namespace-member-declaration '}' */ private void namespace_body(ref CompilationUnitNode compilation, ref NamespaceNode currentNamespace) { printIfDebug("namespace_body"); if (!pass(TokenType.PUNT_CURLY_BRACKET_OPEN)) { throwError("'{' expected"); } consumeToken(); if (pass(TokenType.RW_USING)) { var usingDirectives = optional_using_directive(); currentNamespace.setUsings(usingDirectives); } if (pass(namespaceOption, encapsulationOptions, typesDeclarationOptions)) { optional_namespace_or_type_member_declaration(ref compilation, ref currentNamespace); } else { //EPSILON } if (!pass(TokenType.PUNT_CURLY_BRACKET_CLOSE)) { throwError("'}' expected"); } consumeToken(); }
public void MethodDefAndStatements3() { String contents = "class MyClass \r\n" + "" + " def method1(x, y, z: int): System.Int32" + " " + " self.method2(10, 11)" + " self.propertyx.save(100)" + " self(100)" + " " + " end " + "" + "end \r\n"; CompilationUnitNode unit = RookParser.ParseContents(contents); Assert.IsNotNull(unit); Assert.AreEqual(0, unit.Namespaces.Count); Assert.AreEqual(1, unit.ClassesTypes.Count); ClassDefinitionStatement ClassDefinitionStatement = unit.ClassesTypes[0] as ClassDefinitionStatement; Assert.IsNotNull(ClassDefinitionStatement); Assert.AreEqual("MyClass", ClassDefinitionStatement.Name); Assert.AreEqual(0, ClassDefinitionStatement.BaseTypes.Count); }
public void Block() { String contents = "class MyClass \r\n" + "" + " def method1() : void" + " " + " do " + " method(10, 12); " + " end " + " " + " end " + "" + "end \r\n"; CompilationUnitNode unit = RookParser.ParseContents(contents); Assert.IsNotNull(unit); Assert.AreEqual(0, unit.Namespaces.Count); Assert.AreEqual(1, unit.ClassesTypes.Count); ClassDefinitionStatement ClassDefinitionStatement = unit.ClassesTypes[0] as ClassDefinitionStatement; Assert.IsNotNull(ClassDefinitionStatement); Assert.AreEqual("MyClass", ClassDefinitionStatement.Name); Assert.AreEqual(0, ClassDefinitionStatement.BaseTypes.Count); }
bool IParseNodeValidator.Validate(ParseNode node, CompilerOptions options, IErrorHandler errorHandler) { CompilationUnitNode compilationUnitNode = (CompilationUnitNode)node; foreach (AttributeBlockNode attribBlock in compilationUnitNode.Attributes) { AttributeNode scriptNamespaceNode = AttributeNode.FindAttribute(attribBlock.Attributes, DSharpStringResources.SCRIPT_NAMESPACE_ATTRIBUTE); if (scriptNamespaceNode != null) { string scriptNamespace = (string)((LiteralNode)scriptNamespaceNode.Arguments[0]).Value; if (Utility.IsValidScriptNamespace(scriptNamespace) == false) { errorHandler.ReportNodeValidationError(DSharpStringResources.SCRIPT_NAMESPACE_VIOLATION, scriptNamespaceNode); } } } foreach (ParseNode childNode in compilationUnitNode.Members) { if (!(childNode is NamespaceNode)) { errorHandler.ReportNodeValidationError(DSharpStringResources.SCRIPT_NAMESPACE_TYPE_VIOLATION, childNode); return(false); } } return(true); }
public void StaticFields() { String contents = "class MyClass \r\n" + " @@myfield = 1 " + " @@otherfield = 22 " + "end \r\n"; CompilationUnitNode unit = RookParser.ParseContents(contents); Assert.IsNotNull(unit); Assert.AreEqual(0, unit.Namespaces.Count); Assert.AreEqual(1, unit.ClassesTypes.Count); ClassDefinitionStatement ClassDefinitionStatement = unit.ClassesTypes[0] as ClassDefinitionStatement; Assert.IsNotNull(ClassDefinitionStatement); Assert.AreEqual("MyClass", ClassDefinitionStatement.Name); Assert.AreEqual(0, ClassDefinitionStatement.BaseTypes.Count); Assert.AreEqual(2, ClassDefinitionStatement.Statements.Count); FieldDeclarationStatement stmt = ClassDefinitionStatement.Statements[0] as FieldDeclarationStatement; Assert.IsNotNull(stmt); Assert.AreEqual("@@myfield", (stmt.Target as StaticFieldReferenceExpression).Name); Assert.AreEqual("1", (stmt.Value as LiteralExpression).Value); stmt = ClassDefinitionStatement.Statements[1] as FieldDeclarationStatement; Assert.IsNotNull(stmt); Assert.AreEqual("@@otherfield", (stmt.Target as StaticFieldReferenceExpression).Name); Assert.AreEqual("22", (stmt.Value as LiteralExpression).Value); }
public void NestedDeclarations() { String contents = "namespace My \r\n" + " namespace Nested \r\n" + " namespace Declaration \r\n" + " end \r\n" + " end \r\n" + "end \r\n"; CompilationUnitNode unit = RookParser.ParseContents(contents); Assert.IsNotNull(unit); Assert.AreEqual(1, unit.Namespaces.Count); NamespaceNode ns = unit.Namespaces[0] as NamespaceNode; Assert.IsNotNull(ns); Assert.AreEqual("My", ns.Identifier.Name); Assert.AreEqual(1, ns.Namespaces.Count); ns = ns.Namespaces[0] as NamespaceNode; Assert.IsNotNull(ns); Assert.AreEqual("Nested", ns.Identifier.Name); Assert.AreEqual(1, ns.Namespaces.Count); ns = ns.Namespaces[0] as NamespaceNode; Assert.IsNotNull(ns); Assert.AreEqual("Declaration", ns.Identifier.Name); Assert.AreEqual(0, ns.Namespaces.Count); }
/*namespace-or-type-member-declaration: | namespace-declaration optional-namespace-or-type-member-declaration | type-declaration-list optional-namespace-or-type-member-declaration */ private void namespace_or_type_member_declaration(ref CompilationUnitNode compilation, ref NamespaceNode currentNamespace) { printIfDebug("namespace_or_type_member_declaration"); if (pass(TokenType.RW_NAMESPACE)) { var namespaceDeclared = namespace_declaration(ref compilation); if (currentNamespace.Identifier.Name != "default") { // namespaceDeclared.setParentNamePrefix(currentNamespace.Identifier); namespaceDeclared.setParentNamespace(ref currentNamespace); // namespaceDeclared.addFatherUsings(currentNamespace.usingDirectives); } // else{ // namespaceDeclared.addFatherUsings(compilation.usingDirectives); // } compilation.addNamespace(namespaceDeclared); optional_namespace_or_type_member_declaration(ref compilation, ref currentNamespace); } else { var listTypeDeclared = type_declaration_list(); currentNamespace.addTypeList(listTypeDeclared); optional_namespace_or_type_member_declaration(ref compilation, ref currentNamespace); } }
public void MethodDefAndStatements() { String contents = "class MyClass \r\n" + "" + " def method1(x, y, z:int):int" + " " + " def method1(x, y, z:int):int " + " end " + " myvariable = 1 " + " end " + "" + "end \r\n"; CompilationUnitNode unit = RookParser.ParseContents(contents); Assert.IsNotNull(unit); Assert.AreEqual(0, unit.Namespaces.Count); Assert.AreEqual(1, unit.ClassesTypes.Count); ClassDefinitionStatement ClassDefinitionStatement = unit.ClassesTypes[0] as ClassDefinitionStatement; Assert.IsNotNull(ClassDefinitionStatement); Assert.AreEqual("MyClass", ClassDefinitionStatement.Name); Assert.AreEqual(0, ClassDefinitionStatement.BaseTypes.Count); }
: super("Semantic Highlight") { this.editor = editor; this.text = text; this.compilationUnit = compilationUnit; this.typeSystem = typeSystem; this.annotatedTypeSystem = annotatedTypeSystem; }
public CompilationUnitNode CreateCompilation(CompilationUnitSyntax compilation) { var kCompilation = new CompilationUnitNode(); var kMembers = ParseMembers(compilation.Members.ToList()); kCompilation.WithMembers(kMembers); return(kCompilation); }
/*compilation-unit: | optional-using-directive optional-namespace-or-type-member-declaration | optional-namespace-or-type-member-declaration | EPSILON */ private CompilationUnitNode compilation_unit() { printIfDebug("compilation_unit"); var usingList = optional_using_directive(); var compilation = new CompilationUnitNode(usingList); optional_namespace_or_type_member_declaration(ref compilation, ref compilation.defaultNamespace); return(compilation); }
/// <summary> /// Preprocesses, Lexes and Parses a C# compilation unit. Subscribe to the OnError /// event before calling this method to receive error notifications. /// After calling Parse, the Defines property contains the list of preprocessor /// symbols defined as a result of #define and #undef directives in this /// compilation unit. /// </summary> public CompilationUnitNode Parse(Token[] tokens, LineMap lineMap) { this.lineMap = lineMap; CompilationUnitNode parseTree = parser.Parse(tokens); this.lineMap = null; return(parseTree); }
public CompilationUnitNode BuildCodeModel(IStreamSource source) { hasErrors = false; string filePath = source.FullName; char[] buffer = GetBuffer(source); if (buffer == null) { errorHandler.ReportInputError(filePath); return(null); } IDictionary definesTable = new Hashtable(); if (options.Defines != null && options.Defines.Count != 0) { foreach (string s in options.Defines) { definesTable[s] = null; } } NameTable nameTable = new NameTable(); LineMap lineMap = new LineMap(filePath); FileLexer lexer = new FileLexer(nameTable, filePath); lexer.OnError += OnError; Token[] tokens = lexer.Lex(buffer, definesTable, lineMap, /* includeComments */ false); if (hasErrors == false) { FileParser parser = new FileParser(nameTable, filePath); parser.OnError += OnError; CompilationUnitNode compilationUnit = parser.Parse(tokens, lineMap); foreach (ParseNode node in compilationUnit.Members) { if (node is NamespaceNode namespaceNode) { namespaceNode.IncludeCompilationUnitUsingClauses(); } } if (hasErrors == false) { return(compilationUnit); } } return(null); }
private static void serializeCode(CompilationUnitNode code, string path) { // Insert code to set properties and fields of the object. XmlSerializer mySerializer = new XmlSerializer(typeof(CompilationUnitNode), types()); // To write to a file, create a StreamWriter object. StreamWriter myWriter = new StreamWriter(File.Create(path)); mySerializer.Serialize(myWriter, code); // myWriter.Close(); }
private void BuilderNameSpace(NamespaceNode cn, CompilationUnitNode unit) { NamespaceNode nspace = new NamespaceNode(new Token(TokenID.Namespace)); nspace.Name = cn.Name; mEntityUnit.Namespaces.Add(nspace); foreach (InterfaceNode item in cn.Interfaces) { BuilderType(item, nspace); } }
public override void Process(CompilationContext context) { foreach (TextReader reader in context.Sources) { CompilationUnitNode unit = RookParser.ParseContents(reader); context["unit"] = unit; ProcessNext(context); } }
/*optional-namespace-or-type-member-declaration: | namespace-or-type-member-declaration | EPSILON */ private void optional_namespace_or_type_member_declaration(ref CompilationUnitNode compilation, ref NamespaceNode currentNamespace) { printIfDebug("optional_namespace_or_type_member_declaration"); if (pass(namespaceOption, encapsulationOptions, typesDeclarationOptions)) { namespace_or_type_member_declaration(ref compilation, ref currentNamespace); } else { //EPSILON } }
public static Assembly Compile(CompilationUnitNode ast) { var errors = ast.Validate(); errors.Count.Should().Be(0, errors.FirstOrDefault()?.ErrorMessage); var code = CSharpTranspileVisitor.ToString(ast); Debug.WriteLine(code); var testAssemblyName = GetTestAssemblyName(); return(Compile(code, testAssemblyName)); }
public void SimpleDeclaration2() { String contents = "namespace My.qualified.name \r\n" + "end \r\n"; CompilationUnitNode unit = RookParser.ParseContents(contents); Assert.IsNotNull(unit); Assert.AreEqual(1, unit.Namespaces.Count); NamespaceNode ns = unit.Namespaces[0] as NamespaceNode; Assert.IsNotNull(ns); Assert.AreEqual("My.qualified.name", ns.Identifier.Name); }
static void setup(CompilationUnitNode cu) { foreach (var ns in cu.Namespaces) { foreach (var cs in ns.Classes) { classes[cs.Name.Identifier] = new Class() { classnode = cs }; } foreach (var cs in ns.Classes) { var cls = classes[cs.Name.Identifier]; //"register" the class function symbols foreach (var method in cs.Methods) { var f = new Function() { method = method, ownerClass = cls }; f.Params = new Parameters(); //!!! we assume csparser has given us the args in the right order (we establish both the string name key AND integer index access methods) foreach (var param in method.Params) { string typename = ((dynamic)param).Type.Identifier.GenericIdentifier; f.Params[param.Name] = new ObjectInstance(typename, param.Name); } f.Params.isInit = false; cls.functions[f.name] = f; cls._functionOverloads.Add(f); } } foreach (var cs in ns.Classes) { var cls = classes[cs.Name.Identifier]; cls.initFields(staticInit: true); } } }
public System.IO.Stream Builder(System.IO.Stream stream) { CodeDomProvider proider = new Microsoft.CSharp.CSharpCodeProvider(); System.IO.StringWriter sw = new System.IO.StringWriter(); Console.SetOut(sw); Console.SetError(sw); // CSharpParser p = new CSharpParser(null, stream, null); System.IO.Stream result = new System.IO.MemoryStream(); System.IO.StreamWriter writer = new System.IO.StreamWriter(result, Encoding.UTF8); CompilationUnitNode unit = null; using (System.IO.StreamReader sr = new StreamReader(stream, Encoding.UTF8)) { Lexer lexer = new Lexer(sr); TokenCollection tc = lexer.Lex(); Parser parser = new Parser(); unit = parser.Parse(tc, lexer.StringLiterals); } if (unit != null) { try { Microsoft.CSharp.CSharpCodeProvider csp = new Microsoft.CSharp.CSharpCodeProvider(); foreach (UsingDirectiveNode item in unit.DefaultNamespace.UsingDirectives) { mEntityUnit.DefaultNamespace.UsingDirectives.Add(item); } foreach (NamespaceNode cn in unit.Namespaces) { BuilderNameSpace(cn, unit); } StringBuilder sb = new StringBuilder(); mEntityUnit.ToSource(sb); writer.Write(sb.ToString()); } catch (Exception e_) { writer.WriteLine(e_.Message + e_.StackTrace); } writer.Flush(); } return(result); }
public static BoundTree BindCompilationUnit(CompilationUnitNode compilationUnit) { var rootScope = CreateRootScope(); var binder = new Binder(rootScope, function: null); // First let's add the functions var functions = new List <FunctionDefinition>(); foreach (var functionDeclarationNode in compilationUnit.Members.OfType <FunctionDeclarationNode>()) { var declaration = binder.BindFunctionDeclaration(functionDeclarationNode); if (declaration == null) // Most probably function re-definition { continue; } var bodyBinder = new Binder(rootScope, declaration); var body = bodyBinder.BindBlock(functionDeclarationNode.Body, isFunctionTopmostBlock: true); bodyBinder.FixGotoStatements(body); // TODO: lower + check the function returns on all its paths // Retrieve the diagnostics _ = binder.diagnostics.AddRange(bodyBinder.Diagnostics); var function = new FunctionDefinition(declaration, body); functions.Add(function); } // The the free-floating code (global statements, including global variables) var statements = new List <Statement>(); foreach (var globalStatement in compilationUnit.Members.OfType <GlobalStatementNode>()) { var statement = binder.BindStatement(globalStatement.Statement); statements.Add(statement); } return(new BoundTree( rootScope, functions, binder.Scope.GetDeclaredVariables(), statements, binder.Diagnostics)); }
private void BuildCodeModel() { CodeModelBuilder codeModelBuilder = new CodeModelBuilder(options, this); CodeModelValidator codeModelValidator = new CodeModelValidator(this); CodeModelProcessor validationProcessor = new CodeModelProcessor(codeModelValidator, options); foreach (IStreamSource source in options.Sources) { CompilationUnitNode compilationUnit = codeModelBuilder.BuildCodeModel(source); if (compilationUnit != null) { validationProcessor.Process(compilationUnit); compilationUnitList.Add(compilationUnit); } } }
public void AssignmentsAndAccessLevels() { String contents = "class MyClass \r\n" + "private \r\n" + " @@myfield = 1 \r\n" + "public \r\n" + " @@otherfield = 2 \r\n" + " @@someother = 3 \r\n" + "end \r\n"; CompilationUnitNode unit = RookParser.ParseContents(contents); Assert.IsNotNull(unit); Assert.AreEqual(0, unit.Namespaces.Count); Assert.AreEqual(1, unit.ClassesTypes.Count); ClassDefinitionStatement ClassDefinitionStatement = unit.ClassesTypes[0] as ClassDefinitionStatement; Assert.IsNotNull(ClassDefinitionStatement); Assert.AreEqual("MyClass", ClassDefinitionStatement.Name); Assert.AreEqual(0, ClassDefinitionStatement.BaseTypes.Count); Assert.AreEqual(3, ClassDefinitionStatement.Statements.Count); FieldDeclarationStatement stmt = ClassDefinitionStatement.Statements[0] as FieldDeclarationStatement; Assert.IsNotNull(stmt); Assert.AreEqual(AccessLevel.Private, stmt.ScopeAccessLevel); Assert.AreEqual("@@myfield", (stmt.Target as StaticFieldReferenceExpression).Name); Assert.AreEqual("1", (stmt.Value as LiteralExpression).Value); stmt = ClassDefinitionStatement.Statements[1] as FieldDeclarationStatement; Assert.IsNotNull(stmt); Assert.AreEqual(AccessLevel.Public, stmt.ScopeAccessLevel); Assert.AreEqual("@@otherfield", (stmt.Target as StaticFieldReferenceExpression).Name); Assert.AreEqual("2", (stmt.Value as LiteralExpression).Value); stmt = ClassDefinitionStatement.Statements[2] as FieldDeclarationStatement; Assert.IsNotNull(stmt); Assert.AreEqual(AccessLevel.Public, stmt.ScopeAccessLevel); Assert.AreEqual("@@someother", (stmt.Target as StaticFieldReferenceExpression).Name); Assert.AreEqual("3", (stmt.Value as LiteralExpression).Value); }
public void SimpleDeclaration() { String contents = "class MyClass \r\n" + "" + "" + "end \r\n"; CompilationUnitNode unit = RookParser.ParseContents(contents); Assert.IsNotNull(unit); Assert.AreEqual(0, unit.Namespaces.Count); Assert.AreEqual(1, unit.ClassesTypes.Count); ClassDefinitionStatement ClassDefinitionStatement = unit.ClassesTypes[0] as ClassDefinitionStatement; Assert.IsNotNull(ClassDefinitionStatement); Assert.AreEqual("MyClass", ClassDefinitionStatement.Name); Assert.AreEqual(0, ClassDefinitionStatement.BaseTypes.Count); }
public static bool Parse(string filePath, TextReader reader, LoadingContext context, out CompilationUnitNode result) { return Instance.CompilationUnit(filePath, reader, context, out result); }
private bool Namespace(CompilationUnitNode cu) { if (Keyword(ParserConstants.NamespaceKeyword)) { var uri = UriExpected(); TokenExpected('{'); var ns = new NamespaceNode(uri); while (Import(ns)) ; while (GlobalType(ns)) ; TokenExpected('}'); cu.NamespaceList.Add(ns); return true; } return false; }
private bool CompilationUnit(string filePath, TextReader reader, LoadingContext context, out CompilationUnitNode result) { try { Init(filePath, reader, context); var cu = new CompilationUnitNode(); while (Namespace(cu)) ; EndOfFileExpected(); result = cu; return true; } catch (LoadingException) { } finally { Clear(); } result = null; return false; }
private String translate(char[] text, CompilationUnitNode compilationUnit) { translate(compilationUnit.Body); return new CompilationUnitPrinter().print(text, compilationUnit); }
public override object VisitCompilationUnit(CompilationUnitNode compilationUnit, object data) { base.VisitCompilationUnit(compilationUnit, data); return CompiledResult; }