internal static bool Identify( ClassStatement classStatement ) { var methodArgumentUsedClasses = classStatement.PublicMethodStatements.Aggregate( new List <string>(), (acc, method) => acc.Concat( method.Arguments.Aggregate( new List <string>(), (argAcc, arg) => argAcc.Concat( new List <string> { arg.Type.Name } ).ToList() ) ).ToList() ); var constructorUsedClasses = classStatement.ConstructorStatement.Arguments.Aggregate( new List <string>(), (argAcc, arg) => argAcc.Concat( new List <string> { arg.Type.Name } ).ToList() ); var argumentUsedClasses = methodArgumentUsedClasses.Concat( constructorUsedClasses ); return(argumentUsedClasses.Any( a => a == GenerationIdentifiedTypes.Action )); }
public object VisitClassStatement(ClassStatement statement) { scope.Initialize(statement.Name); var classType = Scope.ClassType.Class; if (statement.Superclass != null) { classType = Scope.ClassType.Subclass; if (statement.Name.Lexeme == statement.Superclass.Name.Lexeme) { Interpreter.ScopeError(statement.Superclass.Name, "A class cannot inherit from itself."); } Resolve(statement.Superclass); scope.EnterSuperclass(); } scope.EnterClass(classType); foreach (var method in statement.Methods) { var type = LoxClass.IsInitializer(method) ? Scope.FunctionType.Initializer : Scope.FunctionType.Method; ResolveFunction(method, type); } scope.ExitClass(); if (statement.Superclass != null) { scope.ExitSuperclass(); } return(null); }
public object VisitClassStatement(ClassStatement s, object context) { StringBuilder.Append("class "); StringBuilder.Append(s.Name.Content); if (s.SuperclassName != null) { StringBuilder.Append(" : "); StringBuilder.Append(s.SuperclassName.Content); } StringBuilder.AppendLine(" {"); PushIndent(); foreach (PropertyStatement property in s.Properties) { StringBuilder.Append(IndentationContents); property.AcceptVisitor(this, context); StringBuilder.AppendLine(); } foreach (SubroutineStatement method in s.Methods) { StringBuilder.AppendLine(IndentationContents); StringBuilder.Append(IndentationContents); StringBuilder.Append("method "); method.AcceptVisitor(this, context); StringBuilder.AppendLine(); } PopIndent(); StringBuilder.Append(IndentationContents); StringBuilder.Append("}"); return(null); }
private ClassStatement ParseClassStatement() { var stmt = new ClassStatement { Token = CurToken }; if (!ExpectPeek(TokenType.Constant)) { return(null); } stmt.Name = new Constant { Token = CurToken, Value = CurToken.Literal }; if (PeekTokenIs(TokenType.Lt)) { NextToken(); NextToken(); stmt.SuperClass = new Constant { Token = CurToken, Value = CurToken.Literal }; } stmt.Body = ParseBlockStatement(); return(stmt); }
public void CloseBlockStatementShouldSetParentToTopParent() { ClassStatement classStatement = StatementCreator.CreateClassStatement(); _manager.Encountered(new[] { classStatement }, TokenCreator.Created().Count(), TokenCreator.Created()); OpenBlockStatement openBlock = StatementCreator.CreateOpenBlockStatement(); _manager.Encountered(new[] { openBlock }, TokenCreator.Created().Count(), TokenCreator.Created()); ClassStatement internalClassStatement = StatementCreator.CreateClassStatement(); _manager.Encountered(new[] { internalClassStatement }, TokenCreator.Created().Count(), TokenCreator.Created()); OpenBlockStatement secondOpenBlock = StatementCreator.CreateOpenBlockStatement(); _manager.Encountered(new[] { secondOpenBlock }, TokenCreator.Created().Count(), TokenCreator.Created()); CloseBlockStatement closeBlock = StatementCreator.CreateCloseBlockStatement(); CollectionAssert.AreEquivalent(new[] { new StatementParent(new[] { classStatement }, openBlock), new StatementParent(new[] { internalClassStatement }, secondOpenBlock) }, _manager.GetContext(closeBlock.Tokens).Parents); _manager.Encountered(new[] { closeBlock }, TokenCreator.Created().Count(), TokenCreator.Created()); CollectionAssert.AreEquivalent(new[] { new StatementParent(new[] { classStatement }, openBlock) }, _manager.GetContext(openBlock.Tokens).Parents); _manager.Encountered(new[] { closeBlock }, TokenCreator.Created().Count(), TokenCreator.Created()); }
public GeneratedStatement( ClassStatement classStatement, string generatedString ) { ClassStatement = classStatement; GeneratedString = generatedString; }
public void OpenBlockStatementForClassShouldSetParentContextToClass() { ClassStatement classStatement = StatementCreator.CreateClassStatement(); _manager.Encountered(new[] { classStatement }, TokenCreator.Created().Count(), TokenCreator.Created()); Assert.AreEqual(0, _manager.GetContext(classStatement.Tokens).Parents.Count()); OpenBlockStatement openBlock = StatementCreator.CreateOpenBlockStatement(); _manager.Encountered(new[] { openBlock }, TokenCreator.Created().Count(), TokenCreator.Created()); Assert.AreEqual(new [] { new StatementParent(new[] { classStatement }, openBlock) }, _manager.GetContext(openBlock.Tokens).Parents); }
/// <summary> /// : classStatement.ExtendedClassNames /// </summary> /// <param name="classStatement"></param> /// <returns></returns> private static string BuildExtendedClassesSection( ClassStatement classStatement ) { // Check if extendedClassName is interface // If all are interfaces, add ClientEntity var interfaceTypes = classStatement.ImplementedInterfaces; if (classStatement.IsInterface) { // The classStatament if for an interface, so the class will postfixed with an identifier. // And will need to be inherited from its created interface. interfaceTypes.Add( new TypeStatement { Name = classStatement.Name, GenericTypes = classStatement.GenericTypes, } ); } if (classStatement.ExtendedType == null && !interfaceTypes.Any()) { return(" : CachedEntityObject"); } if (classStatement.ExtendedType == null) { classStatement.ExtendedType = new TypeStatement { Name = "CachedEntityObject", }; } return(" : " + string.Join( ", ", new List <string> { TypeStatementWriter.Write( classStatement.ExtendedType, true ) }.Concat( interfaceTypes.Select( interfaceType => TypeStatementWriter.Write( interfaceType, true, true ) ) ).Distinct() )); }
public static string GenerateString( ClassStatement classStatement ) { // Templates var classGenerationTemplates = ReadTemplates.Read(); return(classGenerationTemplates.ClassShim.Replace( "[[CLASS_NAME]]", classStatement.Name )); }
private void CompileClassStmt(ClassStatement stmt, Scope scope) { scope = new Scope { Out = scope, LocalTable = new LocalTable(), Self = stmt, Line = 0 }; var instructionSet = new InstructionSet(); instructionSet.SetLabel($"{InstructionType.LabelDefClass}:{stmt.Name.Value}"); CompileBlockStatement(instructionSet, stmt.Body, scope, scope.LocalTable); instructionSet.Define(InstructionType.Leave); InstructionSets.Add(instructionSet); }
//public override bool Valid(Statement s) //{ // if (s is ClassStatement || s is StateStatement || s is TransitionStatement || s is TestStatement) // { // return true; // } // return base.Valid(s); //} public override void VisitClassStatement(ClassStatement s) { base.VisitClassStatement(s); stream.WriteLine("\tFSM::StateDelegateT<" + ClassName + "> FSMDelegate;"); stream.WriteLine("\tFSM::StateMachine FSM;"); stream.WriteLine("protected:"); stream.WriteLine("\tvirtual FSM::StateMachine* getFSM() { return &FSM; }"); stream.WriteLine("private:"); stream.WriteLine("\tvoid onEnterFSM();"); stream.WriteLine("\tvoid onExitFSM();"); stream.WriteLine(); }
private static string BuildJsonConvertClassGenerics( ClassStatement classStatement ) { var template = "<[[TYPE]]>"; if (!classStatement.GenericTypes.Any()) { return(string.Empty); } return(template.Replace( "[[TYPE]]", GenerationIdentifiedTypes.CachedEntity )); }
public string VisitClassStatement(ClassStatement statement) { var builder = new StringBuilder(); builder.Append($"(class {statement.Name.Lexeme}"); if (statement.BaseClass != null) { builder.Append($" < {Print(statement.BaseClass)}"); } foreach (var method in statement.Methods) { builder.Append($"< {Print(method)}"); } builder.Append(')'); return(builder.ToString()); }
public LangClass(ClassStatement _stat, ClassInitStatement _call, Interpreter _inter) : base(ObjectType.CLASS, _inter) { vars = new ValueContainer <Hashtable>(); vars.Value = new Hashtable(); permissions = new ValueContainer <Hashtable>(); permissions.Value = new Hashtable(); foreach (ClassMember str in _stat.vars) { vars.Value[str.name] = new LangNumber(0, handler); permissions.Value[str.name] = str.Modifiers; } methods = new ValueContainer <Hashtable>(); methods.Value = _stat.methods; constructors = new ValueContainer <ArrayList>(); constructors.Value = _stat.constructors; name = new ValueContainer <string>(); name.Value = _stat.name; }
public object VisitClassStatement(ClassStatement statement) { object superclass = null; if (statement.Superclass != null) { superclass = Evaluate(statement.Superclass); if (!(superclass is LoxClass)) { throw new LoxRunTimeException(statement.Superclass.Name, "Superclass must be a class."); } } environment.Define(statement.Name, null); if (statement.Superclass != null) { environment = new Environment(environment); environment.Define(superToken, superclass); } var methods = new Dictionary <string, LoxFunction>(); foreach (var method in statement.Methods) { var function = new LoxFunction(method, environment, LoxClass.IsInitializer(method)); methods.Add(method.Name.Lexeme, function); } var loxClass = new LoxClass(statement.Name.Lexeme, (LoxClass)superclass, methods); if (superclass != null) { environment = environment.Enclosing; } environment.Assign(statement.Name, loxClass); return(null); }
public Unit VisitClassStatement(ClassStatement statement) { var enclosingClass = _currentClass; _currentClass = ClassType.Class; Declare(statement.Identifier); Define(statement.Identifier); BeginScope(); _scopes.Peek().TryAdd("this", true); foreach (var method in statement.Methods) { var type = method.Token.Lexeme == "constructor" ? FunctionType.Constructor : FunctionType.Method; ResolveFunction(method, type); } EndScope(); _currentClass = enclosingClass; return(Unit.Value); }
private static string BuildClassGenerics( ClassStatement classStatement ) { var template = "<[[TYPE]]>"; if (!classStatement.GenericTypes.Any()) { return(string.Empty); } return(template.Replace( "[[TYPE]]", string.Join( ", ", classStatement.GenericTypes.Select( genericType => TypeStatementWriter.Write( genericType ) ) ) )); }
public static string Write( ClassStatement classStatement, ClassGenerationTemplates classGenerationTemplates ) { // TODO: Check if class is an interface if (classStatement.IsInterface) { GlobalLogger.Info($"Generating Interface: {classStatement}"); var className = TypeStatementWriter.Write(new TypeStatement { Name = classStatement.Name, GenericTypes = classStatement.GenericTypes, }); // Get Interface Section Template var template = "public interface [[CLASS_NAME]] : ICachedEntity { }"; return(template.Replace( "[[CLASS_NAME]]", className )); } return(string.Empty); }
internal static string Write( ClassStatement classStatement, ConstructorStatement constructorDetails, ClassGenerationTemplates templates ) { GlobalLogger.Info($"Generating Base Constructor: {constructorDetails}"); var template = templates.Constructor; var extendsClass = classStatement.ExtendedType != null; if (extendsClass) { template = templates.ConstructorToBase; } return(template.Replace( "[[CLASS_NAME]]", classStatement.Name ).Replace( "[[BASE_CLASS_CALL]]", extendsClass ? " : base()" : string.Empty )); }
public ClassInfo(ClassStatement classStatement, IEnvironment environment, SymbolTable methodsSymbolTable, SymbolTable fieldsSymbolTable) { this.Definition = classStatement; this.Environment = environment; object superClass = string.IsNullOrEmpty(classStatement.SuperClass) ? null : environment.Get(classStatement.SuperClass); if (superClass == null) { this.SuperClass = null; } else if (superClass is ClassInfo) { this.SuperClass = (ClassInfo)superClass; } else { throw new StoneException(string.Format("Unknown super class: {0}", classStatement.SuperClass), classStatement); } this.MethodsSymbolTable = methodsSymbolTable; this.FieldsSymbolTable = fieldsSymbolTable; }
public override object Visit(ClassStatement that, object value) { _symbols.EnterBlock(that.Name.Symbol, that); /** \note No need to visit the base class; it is declared somewhere. */ foreach (Statement statement in that.Statements) { switch (statement.Kind) { case NodeKind.ClassStatement: case NodeKind.ConstructorStatement: case NodeKind.DelegateStatement: case NodeKind.DestructorStatement: case NodeKind.ExternalStatement: /** \note We mangle the externals even though this is not currently used for anything... */ case NodeKind.FieldStatement: case NodeKind.FunctionStatement: case NodeKind.InterfaceStatement: case NodeKind.MethodStatement: statement.Visit(this); break; default: continue; } } _symbols.LeaveBlock(that.Name.Symbol); return null; }
public override object Visit(ClassStatement that, object value) { if (that.Bases.Length == 0) _writer.Write("record"); else _writer.Write("class"); _writer.Write(' '); _writer.Write(BackquoteNameOpt(that.Name.Symbol)); if (that.Bases.Length > 1) { _writer.Write(" is "); foreach (Reference @base in that.Bases) @base.Visit(this); } _writer.WriteLine(":"); _writer.WriteLine(); _writer.Indent(); foreach (Statement statement in that.Statements) { if (statement != that.Statements[0]) _writer.WriteLine(); statement.Visit(this); } _writer.Dedent(); _writer.WriteLine(); return null; }
/** Recursively enters the encountered (nested) \c ClassStatement nodes into the symbol table. */ public override object Visit(ClassStatement that, object value) { _symbols.EnterBlock(that.Name.Symbol, that); foreach (Statement statement in that.Statements) { switch (statement.Kind) { case NodeKind.ClassStatement: case NodeKind.EnumerationStatement: case NodeKind.FieldStatement: case NodeKind.GuardStatement: case NodeKind.InterfaceStatement: case NodeKind.TypeStatement: case NodeKind.ValueStatement: statement.Visit(this); break; default: continue; } } _symbols.LeaveBlock(that.Name.Symbol); return null; }
public static string Write( ClassStatement classStatement, ConstructorStatement constructorDetails, ClassGenerationTemplates templates ) { var arguments = constructorDetails.Arguments; if (arguments.Any()) { GlobalLogger.Info($"Generating Argument Constructor: {constructorDetails}"); var template = templates.ConstructorWithArgumentsTemplate; var extendsClass = classStatement.ExtendedType != null; // Argument String Generation var argumentStrings = new List <string>(); foreach (var argument in arguments.OrderBy(a => a.IsOptional)) { argumentStrings.Add( ArgumentWriter.Write( argument, true, " = null", ignorePrefix: true ) ); } var constructorArguments = string.Join( ", ", argumentStrings ); var propertyArguments = string.Join( ", ", arguments.Select( argument => DotNetNormalizer.Normalize( argument.Name ) ) ); // Generate Namespace var entityNamespace = string.Join( ", ", classStatement.Namespace .Split(".") .Select(part => @$ "" "{part}" "") ); return(template.Replace( "[[CLASS_NAME]]", classStatement.Name ).Replace( "[[ARGUMENTS]]", constructorArguments ).Replace( "[[PROPERTY_NAMESPACE]]", entityNamespace ).Replace( "[[PROPERTY_ARGUMENTS]]", propertyArguments ).Replace( "[[BASE_CLASS_CALL]]", extendsClass ? " : base()" : string.Empty )); } return(string.Empty); }
public override object Visit(ClassStatement that, object value = null) { PrintPrologue(that); PrintDefinition(that); PrintSequence("Bases", that.Bases); PrintSequence("Statements", that.Statements); PrintEpilogue(that); that.Name.Visit(this); foreach (Reference @base in that.Bases) @base.Visit(this); foreach (Statement statement in that.Statements) statement.Visit(this); return null; }
//public override bool Valid(Statement s) //{ // if (s is ClassStatement || s is StateStatement || s is TransitionStatement || s is TestStatement) // { // return true; // } // return base.Valid(s); //} public override void VisitClassStatement(ClassStatement s) { base.VisitClassStatement(s); stream.WriteLine("\t\tFSM_INIT();"); stream.WriteLine(); }
public override object Visit(ClassStatement that, object value = null) { _symbols.EnterBlock(that.Name.Symbol, that); // Process the references to base classes right away as we have already resolved all classes in the program. foreach (Expression @base in that.Bases) @base.Visit(this); that.Name.Visit(this); foreach (Node below in that.Statements) below.Visit(this); _symbols.LeaveBlock(that.Name.Symbol); return null; }
public virtual void VisitClassStatement(ClassStatement s) { ClassName = s.name; }
public static string Write( ClassStatement classStatement, IEnumerable <PublicMethodStatement> methods, ClassGenerationTemplates templates ) { if (methods.Count() == 0) { return(string.Empty); } var section = new StringBuilder(); var current = 1; foreach (var method in methods) { GlobalLogger.Info($"Generating Method: {method}"); var isLast = current == methods.Count(); var isClassResponse = ClassResponseIdentifier.Identify( method.Type, method.UsedClassNames ); var isArray = ArrayResponseIdentifier.Identify( method.Type ); var template = templates.Method; var methodType = method.Type; var type = TypeStatementWriter.Write( methodType ); var typeNoModifier = TypeStatementWriter.Write( methodType, false ); var propertyArguments = string.Empty; var isNotSupported = NotSupportedIdentifier.Identify( method ); var isTask = method.Type.IsTask; var isEnum = TypeEnumIdentifier.Identify( method.Type ); var isAction = method.Type.Name == GenerationIdentifiedTypes.Action || (method.Arguments.Take(1).Any(a => a.Type.IsAction && a.Name == "callback")); var bodyTemplate = templates.ReturnTypePrimitiveTemplate; var returnTypeContent = templates.InteropFunc; var arguments = string.Empty; var argumentStrings = new List <string>(); var classNamespace = classStatement.Namespace; var namespacedMethod = string.Join( ".", classNamespace, classStatement.Name, method.Name ); var propertyIdentifier = "this.___guid"; // [[FUNCTION_GENERICS]] = functionGenerics = T, EventState, Task var functionGenerics = string.Empty; var genericSection = string.Empty; var whereConstraint = string.Empty; var taskType = TypeStatementWriter.Write( methodType, false ); var taskAsync = string.Empty; var taskAwait = string.Empty; if (classNamespace == string.Empty) { namespacedMethod = string.Join( ".", classStatement.Name, method.Name ); } // Argument Generation if (isAction) { var functionGenericsStrings = new List <string>(); var actionArgument = method.Arguments.FirstOrDefault( argument => argument.Type.Name == GenerationIdentifiedTypes.Action ); if (actionArgument != null) { foreach (var genericType in actionArgument.Type.GenericTypes) { functionGenericsStrings.Add( TypeStatementWriter.Write( genericType, ignorePrefix: true ) ); } // [[ARGUMENTS]] = arguments = T eventData, EventState eventState foreach (var argument in actionArgument.Type.Arguments.OrderBy(a => a.IsOptional)) { argumentStrings.Add( ArgumentWriter.Write( argument, true, string.Empty, ignorePrefix: false ) ); } // [[PROPERTY_ARGUMENTS]] = propertyArguments = eventData, eventState propertyArguments = string.Join( ", ", actionArgument.Type.Arguments.Select( argument => DotNetNormalizer.Normalize(argument.Name) ) ); } functionGenericsStrings.Add( "Task" ); functionGenerics = string.Join( ", ", functionGenericsStrings ); } else { // TODO: [Re-factor] : Move to Writer foreach (var argument in method.Arguments.OrderBy(a => a.IsOptional)) { argumentStrings.Add( ArgumentWriter.Write( argument, true, " = null" ) ); } propertyArguments = method.Arguments.Any() ? ", " + string.Join( ", ", method.Arguments.Select( argument => DotNetNormalizer.Normalize(argument.Name) ) ) : string.Empty; if (VoidArgumentIdenfifier.Identify(method.Arguments)) { GlobalLogger.Error( $"Found void argument in method: {method.Name}" ); continue; } } arguments = string.Join( ", ", argumentStrings ); // Template/ReturnTypeContent Dictation if (isAction) { template = templates.MethodActionTemplate; bodyTemplate = templates.ReturnTypeVoidTemplate; if (method.IsStatic) { template = templates.MethodStaticActionTemplate; } } if (isEnum) { returnTypeContent = templates.InteropFunc; } else if (isClassResponse && isArray) { returnTypeContent = templates.InteropFuncArrayClass; } else if (isClassResponse) { returnTypeContent = templates.InteropFuncClass; } else if (isArray) { returnTypeContent = templates.InteropFuncArray; } if (isTask) { returnTypeContent = templates.InteropTask; if (isClassResponse && isArray) { returnTypeContent = templates.InteropTaskArrayClass; } else if (isClassResponse || taskType == GenerationIdentifiedTypes.CachedEntity) { returnTypeContent = templates.InteropTaskClass; } else if (isArray) { returnTypeContent = templates.InteropTaskArray; } // Change up the taskType if 'void'; if (taskType == GenerationIdentifiedTypes.Void) { bodyTemplate = templates.ReturnTypeVoidTemplate; taskType = GenerationIdentifiedTypes.CachedEntity; taskAsync = "async "; taskAwait = "await "; } } if (method.IsStatic) { var classStatementIdentitiferList = new string[] { classStatement.Name, }; if (classNamespace != string.Empty) { classStatementIdentitiferList = new string[] { classStatement.Namespace, classStatement.Name, }; } propertyIdentifier = string.Join( ", ", string.Join( ".", classStatementIdentitiferList ).Split(".").Select(part => @$ "" "{part}" "") ); } // Replace the Type in the Return TypeContent to Object // This is to avoid parsing errors and just get a generic object back from method calls. if (method.Type.Name == GenerationIdentifiedTypes.Void) { bodyTemplate = templates.ReturnTypeVoidTemplate; returnTypeContent = returnTypeContent.Replace( "[[ARRAY_TYPE]]", GenerationIdentifiedTypes.CachedEntity ).Replace( "[[NEW_TYPE]]", GenerationIdentifiedTypes.CachedEntity ); } if (method.GenericTypes.Any()) { var genericTypeString = string.Join( ", ", method.GenericTypes ); // TODO: [Template] : Move to templates genericSection = $"<{genericTypeString}>"; if (isClassResponse && method.GenericTypes.Any( genericType => genericType == typeNoModifier ) ) { // TODO: [Template] : Move to templates whereConstraint = string.Join( "", method.GenericTypes.Select( genericType => $" where {genericType} : CachedEntity, new()" ) ); } } if (isNotSupported) { template = "// [[NAME]] is not supported by the platform yet"; } template = template.Replace( "[[BODY]]", bodyTemplate ).Replace( "[[RETURN_TYPE_CONTENT]]", returnTypeContent ).Replace( "[[NAMESPACED_METHOD]]", namespacedMethod ) //.Replace( // "[[CACHE_SECTION]]", // string.Empty //).Replace( // "[[CACHE_SETTTER_SECTION]]", // string.Empty //) .Replace( "[[ARRAY]]", string.Empty ).Replace( "[[STATIC]]", method.IsStatic ? "static " : string.Empty ).Replace( "[[NAME]]", DotNetNormalizer.Normalize( method.Name ) ).Replace( "[[NAME_CAPTIALIZED]]", method.Name.Captialize() ).Replace( "[[CLASS_NAME]]", classStatement.Name ).Replace( "[[TYPE]]", TypeStatementWriter.Write( methodType ) ).Replace( "[[ARRAY_TYPE]]", TypeStatementWriter.Write( methodType, false ) ).Replace( "[[NEW_TYPE]]", TypeStatementWriter.Write( methodType, false ) ).Replace( "[[TASK_TYPE]]", taskType ).Replace( "[[GENERIC_SECTION]]", genericSection ).Replace( "[[ARGUMENTS]]", arguments ).Replace( "[[WHERE_CONSTRAINT]]", whereConstraint ).Replace( "[[PROPERTY_IDENTIFIER]]", propertyIdentifier ).Replace( "[[PROPERTY]]", DotNetNormalizer.Normalize( method.Name ) ).Replace( "[[PROPERTY_ARGUMENTS]]", propertyArguments ).Replace( "[[INTERFACE_POSTFIX]]", method.IsInterfaceResponse ? Constants.INTERFACE_POSTFIX : string.Empty ).Replace( "[[FUNCTION_GENERICS]]", functionGenerics ).Replace( "[[TASK_ASYNC]]", taskAsync ).Replace( "[[TASK_AWAIT]]", taskAwait ); section.Append( template ); if (!isLast) { section.Append( Environment.NewLine ).Append( Environment.NewLine ); } current++; } return(section.ToString()); }
public void SetUp(List <string> args) { if (verbose) { Console.WriteLine("import path:"); foreach (string directory in pathResolver.Directories) { Console.WriteLine(" " + directory); } } AppDomain domain = Thread.GetDomain(); rootModule = new Module(null, null); foreach (Assembly assembly in domain.GetAssemblies()) { AssemblyLoaded(assembly); } domain.AssemblyLoad += OnDomainAssemblyLoad; rootModule.SetName("null", null); rootModule.SetName("true", true); rootModule.SetName("false", false); rootModule.SetName("args", args); DefaultWhitespace.SetUp(rootModule, grammar); LineComment.SetUp(rootModule, grammar); BlockComment.SetUp(rootModule, grammar); Whitespace.SetUp(rootModule, grammar); Name.SetUp(rootModule, grammar); Name.SetUp(rootModule, grammar); Number.SetUp(rootModule, grammar); Base.String.SetUp(rootModule, grammar); Expression.SetUp(rootModule, grammar); ValueExpression.SetUp(rootModule, grammar); NameExpression.SetUp(rootModule, grammar); ParenExpression.SetUp(rootModule, grammar); MemberExpression.SetUp(rootModule, grammar); CallExpression.SetUp(rootModule, grammar); CallInParentScopeExpression.SetUp(rootModule, grammar); NewExpression.SetUp(rootModule, grammar); TypeExpression.SetUp(rootModule, grammar); IsExpression.SetUp(rootModule, grammar); AsExpression.SetUp(rootModule, grammar); UnaryExpression.SetUp(rootModule, grammar); NotExpression.SetUp(rootModule, grammar); MultiplicativeExpression.SetUp(rootModule, grammar); MultiplyExpression.SetUp(rootModule, grammar); DivideExpression.SetUp(rootModule, grammar); AdditiveExpression.SetUp(rootModule, grammar); AddExpression.SetUp(rootModule, grammar); SubtractExpression.SetUp(rootModule, grammar); ComparisonExpression.SetUp(rootModule, grammar); LessExpression.SetUp(rootModule, grammar); LessOrEqualExpression.SetUp(rootModule, grammar); EqualityExpression.SetUp(rootModule, grammar); InequalityExpression.SetUp(rootModule, grammar); GreaterExpression.SetUp(rootModule, grammar); GreaterOrEqualExpression.SetUp(rootModule, grammar); JunctionExpression.SetUp(rootModule, grammar); AndExpression.SetUp(rootModule, grammar); AssignmentExpression.SetUp(rootModule, grammar); AssignExpression.SetUp(rootModule, grammar); /* * NameExpression = ValueExpression * ParenExpression = ValueExpression * * CallExpression < ValueExpression * CallInParentScopeExpression = CallExpression * MemberExpression = CallExpression * * NewExpression < CallExpression * TypeExpression < NewExpression * UnaryExpression < TypeExpression * MultiplicativeExpression < UnaryExpression * AdditiveExpression < MultiplicativeExpression * ComparisonExpression < AdditiveExpression * JunctionExpression < ComparisonExpression * AssignmentExpression < JunctionExpression */ Precedence.SetPrecedence(NameExpression.pattern.Precedence, ValueExpression.pattern.Precedence, Relation.Equal); Precedence.SetPrecedence(ParenExpression.pattern.Precedence, ValueExpression.pattern.Precedence, Relation.Equal); Precedence.SetPrecedence(CallExpression.pattern.Precedence, ValueExpression.pattern.Precedence, Relation.Lower); Precedence.SetPrecedence(CallInParentScopeExpression.pattern.Precedence, CallExpression.pattern.Precedence, Relation.Equal); Precedence.SetPrecedence(MemberExpression.pattern.Precedence, CallExpression.pattern.Precedence, Relation.Equal); Precedence.SetPrecedence(NewExpression.pattern.Precedence, CallExpression.pattern.Precedence, Relation.Lower); Precedence.SetPrecedence(TypeExpression.pattern.Precedence, NewExpression.pattern.Precedence, Relation.Lower); Precedence.SetPrecedence(UnaryExpression.pattern.Precedence, TypeExpression.pattern.Precedence, Relation.Lower); Precedence.SetPrecedence(MultiplicativeExpression.pattern.Precedence, UnaryExpression.pattern.Precedence, Relation.Lower); Precedence.SetPrecedence(AdditiveExpression.pattern.Precedence, MultiplicativeExpression.pattern.Precedence, Relation.Lower); Precedence.SetPrecedence(ComparisonExpression.pattern.Precedence, AdditiveExpression.pattern.Precedence, Relation.Lower); Precedence.SetPrecedence(JunctionExpression.pattern.Precedence, ComparisonExpression.pattern.Precedence, Relation.Lower); Precedence.SetPrecedence(AssignmentExpression.pattern.Precedence, JunctionExpression.pattern.Precedence, Relation.Lower); Grammar.PatternChanged(ValueExpression.pattern, NameExpression.pattern, ParenExpression.pattern, MemberExpression.pattern, CallExpression.pattern, NewExpression.pattern, TypeExpression.pattern, UnaryExpression.pattern, MultiplicativeExpression.pattern, AdditiveExpression.pattern, ComparisonExpression.pattern, JunctionExpression.pattern, AssignmentExpression.pattern); PatternExpression.SetUp(rootModule, grammar); ReferencePatternExpression.SetUp(rootModule, grammar); AnyPatternExpression.SetUp(rootModule, grammar); TextPatternExpression.SetUp(rootModule, grammar); Option.SetUp(rootModule, grammar); BlockPatternExpression.SetUp(rootModule, grammar); ParenPatternExpression.SetUp(rootModule, grammar); TokenPatternExpression.SetUp(rootModule, grammar); RangePatternExpression.SetUp(rootModule, grammar); RepeatPatternExpression.SetUp(rootModule, grammar); AndPatternExpression.SetUp(rootModule, grammar); NotPatternExpression.SetUp(rootModule, grammar); LabelPatternExpression.SetUp(rootModule, grammar); SequencePatternExpression.SetUp(rootModule, grammar); AltPatternExpression.SetUp(rootModule, grammar); /* * EndPatternExpression = ReferencePatternExpression * AnyPatternExpression = ReferencePatternExpression * TextPatternExpression = ReferencePatternExpression * BlockPatternExpression = ReferencePatternExpression * ParenPatternExpression = ReferencePatternExpression * TokenPatternExpression = ReferencePatternExpression * * RangePatternExpression < ReferencePatternExpression * * AndPatternExpression < RangePatternExpression * NotPatternExpression = AndPatternExpression * RepeatPatternExpression = AndPatternExpression * * LabelPatternExpression < AndPatternExpression * SequencePatternExpression < LabelPatternExpression * AltPatternExpression < SequencePatternExpression */ Precedence.SetPrecedence(AnyPatternExpression.pattern.Precedence, ReferencePatternExpression.pattern.Precedence, Relation.Equal); Precedence.SetPrecedence(TextPatternExpression.pattern.Precedence, ReferencePatternExpression.pattern.Precedence, Relation.Equal); Precedence.SetPrecedence(BlockPatternExpression.pattern.Precedence, ReferencePatternExpression.pattern.Precedence, Relation.Equal); Precedence.SetPrecedence(ParenPatternExpression.pattern.Precedence, ReferencePatternExpression.pattern.Precedence, Relation.Equal); Precedence.SetPrecedence(TokenPatternExpression.pattern.Precedence, ReferencePatternExpression.pattern.Precedence, Relation.Equal); Precedence.SetPrecedence(RangePatternExpression.pattern.Precedence, ReferencePatternExpression.pattern.Precedence, Relation.Lower); Precedence.SetPrecedence(AndPatternExpression.pattern.Precedence, RangePatternExpression.pattern.Precedence, Relation.Lower); Precedence.SetPrecedence(NotPatternExpression.pattern.Precedence, AndPatternExpression.pattern.Precedence, Relation.Equal); Precedence.SetPrecedence(RepeatPatternExpression.pattern.Precedence, AndPatternExpression.pattern.Precedence, Relation.Equal); Precedence.SetPrecedence(LabelPatternExpression.pattern.Precedence, AndPatternExpression.pattern.Precedence, Relation.Lower); Precedence.SetPrecedence(SequencePatternExpression.pattern.Precedence, LabelPatternExpression.pattern.Precedence, Relation.Lower); Precedence.SetPrecedence(AltPatternExpression.pattern.Precedence, SequencePatternExpression.pattern.Precedence, Relation.Lower); Grammar.PatternChanged(ReferencePatternExpression.pattern, AnyPatternExpression.pattern, TextPatternExpression.pattern, BlockPatternExpression.pattern, ParenPatternExpression.pattern, TokenPatternExpression.pattern, RangePatternExpression.pattern, RepeatPatternExpression.pattern, AndPatternExpression.pattern, NotPatternExpression.pattern, LabelPatternExpression.pattern, SequencePatternExpression.pattern, AltPatternExpression.pattern); Statement.SetUp(rootModule, grammar); ExpressionStatement.SetUp(rootModule, grammar); CompoundStatement.SetUp(rootModule, grammar); PrintStatement.SetUp(rootModule, grammar); IfStatement.SetUp(rootModule, grammar); WhileStatement.SetUp(rootModule, grammar); ReturnStatement.SetUp(rootModule, grammar); ThrowStatement.SetUp(rootModule, grammar); TryStatement.SetUp(rootModule, grammar); ModuleStatement.SetUp(rootModule, grammar); FunctionStatement.SetUp(rootModule, grammar); Member.SetUp(rootModule, grammar); PatternMember.SetUp(rootModule, grammar); FieldMember.SetUp(rootModule, grammar); ConstructorMember.SetUp(rootModule, grammar); MethodMember.SetUp(rootModule, grammar); ClassStatement.SetUp(rootModule, grammar); SetPrecedenceStatement.SetUp(rootModule, grammar); UsingStatement.SetUp(rootModule, grammar); ImportStatement.SetUp(rootModule, grammar); TopLevelStatement.SetUp(rootModule, grammar); Program.SetUp(rootModule, grammar); Grammar.PatternChanged(Member.pattern, Statement.pattern); grammar.RootPattern = Program.pattern; hasBeenSetUp = true; }
public static string Generate( ClassStatement classStatement, TextFormatter textFormatter ) { var classTokenMap = new Dictionary <string, string> { { "[[INTERFACE_SECTION]]", string.Empty }, { "[[EXTENDED_CLASSES_SECTION]]", string.Empty }, { "[[WHERE_CONSTRAINT]]", string.Empty }, { "[[CLASS_GENERICS]]", string.Empty }, { "[[STATIC_ACCESSORS]]", string.Empty }, { "[[STATIC_PROPERTIES]]", string.Empty }, { "[[STATIC_METHODS]]", string.Empty }, { "[[ACCESSORS]]", string.Empty }, { "[[PROPERTIES]]", string.Empty }, { "[[CONSTRUCTOR]]", string.Empty }, { "[[METHODS]]", string.Empty }, { "[[ASSEMBLY]]", classStatement.ProjectAssembly }, { "[[CLASS_NAME]]", string.Empty }, { "[[NAMESPACE]]", string.Empty }, { "[[BASE_CONSTRUCTOR]]", string.Empty }, { "[[INTERFACE_POSTFIX]]", string.Empty }, }; // Group Parts of the Class var staticAccessors = classStatement.AccessorStatements.Where(a => a.IsStatic); var staticProperties = classStatement.PublicPropertyStatements.Where(a => a.IsStatic); var staticMethods = classStatement.PublicMethodStatements.Where(a => a.IsStatic).Distinct(); var accessors = classStatement.AccessorStatements.Where(a => !a.IsStatic); var properties = classStatement.PublicPropertyStatements.Where(a => !a.IsStatic); var constructorDetails = classStatement.ConstructorStatement; var methods = classStatement.PublicMethodStatements.Where(a => !a.IsStatic).Distinct(); // Templates var classGenerationTemplates = ReadTemplates.Read(); var classTemplate = classGenerationTemplates.Class; // Generate Tokens var namespaceReplaced = classStatement.Namespace; if (string.IsNullOrWhiteSpace(namespaceReplaced)) { namespaceReplaced = string.Empty; classTemplate = classGenerationTemplates.ClassWithNoNamespace; } classTokenMap["[[NAMESPACE]]"] = namespaceReplaced; classTokenMap["[[CLASS_NAME]]"] = classStatement.Name; classTokenMap["[[INTERFACE_SECTION]]"] = InterfaceSectionWriter.Write( classStatement, classGenerationTemplates ); classTokenMap["[[INTERFACE_POSTFIX]]"] = classStatement.IsInterface ? Constants.INTERFACE_POSTFIX : string.Empty; classTokenMap["[[CLASS_GENERICS]]"] = BuildClassGenerics( classStatement ); classTokenMap["[[JSON_CONVERTER_CLASS_GENERICS]]"] = BuildJsonConvertClassGenerics( classStatement ); classTokenMap["[[EXTENDED_CLASSES_SECTION]]"] = BuildExtendedClassesSection( classStatement ); classTokenMap["[[WHERE_CONSTRAINT]]"] = classStatement.GenericTypes.Any() ? string.Join( "", classStatement.GenericTypes.Select( genericType => $" where {genericType.Name} : CachedEntity, new()" ) ) : string.Empty; classTokenMap["[[STATIC_ACCESSORS]]"] = AccessorsSectionWriter.Write( classStatement, staticAccessors, classGenerationTemplates ); classTokenMap["[[STATIC_PROPERTIES]]"] = PropertiesSectionWriter.Write( classStatement, staticProperties, classGenerationTemplates ); classTokenMap["[[STATIC_METHODS]]"] = MethodsSectionWriter.Write( classStatement, staticMethods, classGenerationTemplates ); classTokenMap["[[ACCESSORS]]"] = AccessorsSectionWriter.Write( classStatement, accessors, classGenerationTemplates ); classTokenMap["[[PROPERTIES]]"] = PropertiesSectionWriter.Write( classStatement, properties, classGenerationTemplates ); classTokenMap["[[CONSTRUCTOR]]"] = ConstructorSectionWriter.Write( classStatement, constructorDetails, classGenerationTemplates ); classTokenMap["[[BASE_CONSTRUCTOR]]"] = BaseConstructorSectionWriter.Write( classStatement, constructorDetails, classGenerationTemplates ); classTokenMap["[[METHODS]]"] = MethodsSectionWriter.Write( classStatement, methods, classGenerationTemplates ); var classStringBuilder = new StringBuilder( classTemplate ); classStringBuilder = classTokenMap.Aggregate( classStringBuilder, (acc, token) => acc.Replace( token.Key, token.Value ) ); return(textFormatter.Format( classStringBuilder.ToString() )); }
public override object Visit(ClassStatement that, object value) { // output inner classes before the outer class itself foreach (Statement statement in that.Statements) { if (statement.Kind != NodeKind.ClassStatement) continue; statement.Visit(this); } // output the class definition as a simple structure string name = EncodeAbsolute(that.Name.Path); _writer.Write("%" + name + " = type { "); /** \todo Output inherited class data members. */ foreach (Statement statement in that.Statements) { // don't output methods and inner classes just yet if (statement.Kind != NodeKind.ValueStatement) continue; statement.Visit(this); } _writer.WriteLine(" }"); _writer.WriteLine(); // output the code blocks of the class foreach (Statement statement in that.Statements) { if (statement.Kind == NodeKind.ValueStatement) continue; if (statement.Kind == NodeKind.ClassStatement) continue; statement.Visit(this); } return null; }
public static string Write( ClassStatement classStatement, IEnumerable <AccessorStatement> accessors, ClassGenerationTemplates templates ) { if (accessors.Count() == 0) { return(string.Empty); } var section = new StringBuilder(); var current = 1; foreach (var accessor in accessors) { GlobalLogger.Info($"Generating Accessor: {accessor}"); var isLast = current == accessors.Count(); var isClassResponse = ClassResponseIdentifier.Identify( accessor.Type, accessor.UsedClassNames ); var isArray = ArrayResponseIdentifier.Identify( accessor.Type ); var isEnum = TypeEnumIdentifier.Identify( accessor.Type ); var template = templates.Accessor; var propertyGetterResultType = templates.InteropGet; var root = "this.___guid"; var namespaceParts = classStatement.Namespace.Split("."); var entityNamespace = string.Join( ", ", namespaceParts.Select(part => @$ "" "{part}" "") ); var property = accessor.Name; var propertyGetterTemplate = templates.ReturnTypePrimitiveTemplate; var cacheSection = string.Empty; var cacheSetterSection = string.Empty; if (accessor.HasSetter) { template = templates.AccessorWithSetter; } if (accessor.IsStatic) { root = $"\"{namespaceParts.FirstOrDefault()}\""; property = string.Join( ".", namespaceParts .Skip(1) .Select(part => @$ "{part}") ); if (property.Length > 0) { property += $".{classStatement.Name}.{accessor.Name}"; } else { property = $"{classStatement.Name}.{accessor.Name}"; } } if (isEnum) { propertyGetterResultType = templates.InteropGet; } else if (isClassResponse && isArray) { propertyGetterResultType = templates.InteropGetArrayClass; } else if (isClassResponse) { propertyGetterTemplate = templates.ReturnTypeClass; propertyGetterResultType = templates.InteropGetClass; cacheSection = "private [[STATIC]][[TYPE]] __[[CACHE_NAME]];"; cacheSetterSection = "__[[CACHE_NAME]] = null;"; } else if (isArray) { propertyGetterResultType = templates.InteropGetArray; } template = template .Replace( "[[PROPERTY_GETTER]]", propertyGetterTemplate ).Replace( "[[PROPERTY_SETTER]]", templates.InteropSet ).Replace( "[[RETURN_TYPE_CONTENT]]", propertyGetterResultType ).Replace( "[[PROPERTY_NAMESPACE]]", entityNamespace ).Replace( "[[CACHE_SECTION]]", cacheSection ).Replace( "[[CACHE_SETTTER_SECTION]]", cacheSetterSection ).Replace( "[[CACHE_NAME]]", accessor.Name ).Replace( "[[PROPERTYTYPE]]", classStatement.Name ).Replace( "[[STATIC]]", accessor.IsStatic ? "static " : string.Empty ).Replace( "[[ARRAY]]", string.Empty ).Replace( "[[NAME]]", DotNetNormalizer.Normalize( accessor.Name ) ).Replace( "[[NAME_CAPTIALIZED]]", accessor.Name.Captialize() ).Replace( "[[TYPE]]", TypeStatementWriter.Write( accessor.Type ) ).Replace( "[[ARRAY_TYPE]]", TypeStatementWriter.Write( accessor.Type, false ) ).Replace( "[[NEW_TYPE]]", TypeStatementWriter.Write( accessor.Type, false ) ).Replace( "[[PROPERTY]]", property ).Replace( "[[PROPERTY_ARGUMENTS]]", string.Empty ).Replace( "[[ROOT]]", root ).Replace( "[[INTERFACE_POSTFIX]]", accessor.IsInterfaceResponse ? Constants.INTERFACE_POSTFIX : string.Empty ) ; section.Append( template ); if (!isLast) { section.Append( Environment.NewLine ).Append( Environment.NewLine ); } current++; } return(section.ToString()); }
private static IEnumerable <string> GetAllUsedClasses(ClassStatement generated) { var list = new List <string>(); if (generated.ExtendedType != null) { var usedClassNames = UsedClassNamesIdentifier.Identify( generated.ExtendedType ); foreach (var usedClassName in usedClassNames) { if (!list.Contains(usedClassName)) { list.Add(usedClassName); } } } foreach (var extendedType in generated.GenericTypes) { var usedClassNames = UsedClassNamesIdentifier.Identify(extendedType); foreach (var usedClassName in usedClassNames) { if (!list.Contains(usedClassName)) { list.Add(usedClassName); } } } foreach (var interfaceType in generated.ImplementedInterfaces) { var usedClassNames = UsedClassNamesIdentifier.Identify( interfaceType ); foreach (var usedClassName in usedClassNames) { if (!list.Contains(usedClassName)) { list.Add(usedClassName); } } } foreach (var argument in generated.ConstructorStatement.Arguments) { foreach (var argClassName in argument.UsedClassNames) { if (!list.Contains(argClassName)) { list.Add(argClassName); } } } foreach (var statement in generated.AccessorStatements) { foreach (var className in statement.UsedClassNames) { if (!list.Contains(className)) { list.Add(className); } } } foreach (var statement in generated.PublicMethodStatements) { foreach (var className in statement.UsedClassNames) { if (!list.Contains(className)) { list.Add(className); } } foreach (var argument in statement.Arguments) { foreach (var argClassName in argument.UsedClassNames) { if (!list.Contains(argClassName)) { list.Add(argClassName); } } } } foreach (var statement in generated.PublicPropertyStatements) { foreach (var className in statement.UsedClassNames) { if (!list.Contains(className)) { list.Add(className); } } } return(list); }
public virtual object Visit(ClassStatement that, object value = null) { throw new System.NotImplementedException(); }