public ConditionalArrayFunction(string name, string description, ArrayType arrayType, string parameterDescription, CodeType returnType) : base(name, description, arrayType) { ReturnType = returnType; Parameters = new CodeParameter[] { new CodeParameter("conditionLambda", parameterDescription, new MacroLambda(null, arrayType.ArrayOfType)) }; }
/// <summary> /// Finds the function code element. /// </summary> /// <param name="cc">The cc.</param> /// <param name="functionName">Name of the function.</param> /// <param name="arguments">The arguments.</param> /// <returns></returns> internal static CodeFunction2 FindFunctionCodeElement(CodeClass cc, string functionName, List <Argument> arguments) { foreach (CodeElement ce in cc.Members) { if (ce is CodeFunction2 && functionName == ce.Name) { CodeFunction2 cf = ce as CodeFunction2; if (arguments == null) { return(cf); } if (cf.Parameters.Count == arguments.Count) { // On regarde si les paramètres correspondent for (int i = 0; i < arguments.Count; i++) { CodeParameter param = (CodeParameter)cf.Parameters.Item(i + 1); if (param.Name != arguments[i].Name) { return(null); } } return(cf); } } } return(null); }
public bool appParameters(ref CodeFunction cf, SqlParameterCollection spc) { CodeParameter cp = null; string pname; foreach (SqlParameter p in spc) { pname = p.ParameterName.Remove(0, 1); if (p.Direction != System.Data.ParameterDirection.ReturnValue) { if (p.Direction == ParameterDirection.Output) { cp = cf.AddParameter(pname, "out " + HandleTypes(p.SqlDbType), -1); } else { if (p.Direction == ParameterDirection.InputOutput) { cp = cf.AddParameter(pname, "ref " + HandleTypes(p.SqlDbType), -1); } else { cp = cf.AddParameter(pname, HandleTypes(p.SqlDbType), -1); } } } } return(true); }
public void Execute(string[] args) { HideAfterExecuting = false; var Calc = new CalculatorManager(); var command = $"Calc.Value = {Calc.CorrectedExpression(GetStringByTokens(args))};"; using (var sandBox = new Sandbox()) { var d = CodeGenerator.CreateCode <double> (sandBox, CS.Compiler, command, null, null, CodeParameter.Create("Calc", Calc )); d.Execute(Calc); } var result = $" = {Calc.FinalCorrection(Calc.Value.ToString())}"; Intermediary.MustBeHidden = HideAfterExecuting; Intermediary.CommandTextChanged = true; Intermediary.CommandText = result; Intermediary.CaretOffset = result.Length; }
/// <summary> /// /// </summary> /// <param name="templatePath">模板路径</param> /// <param name="savePath">保存路径</param> /// <param name="tables">表名集合</param> /// <param name="SolutionName">解决方案的名称</param> /// <param name="classNamespace">db库中的实体类的命名空间</param> /// <param name="ModelsNamespace">试图实体类的命名空间</param> /// <param name="Suffix">生成文件的后缀名称</param> /// <param name="IsInterface">是否生成接口文件</param> public static void CreateCode(string templatePath, string savePath, List <string> tables, string SolutionName, string classNamespace, string ModelsNamespace, string Suffix, bool IsInterface) { string template = System.IO.File.ReadAllText(templatePath); //从文件中读出模板内容 string templateKey = "code"; //取个名字 ,不能重复 string i = IsInterface ? "I" : string.Empty; foreach (var item in tables) { CodeParameter model = new CodeParameter() { Name = item, ClassNamespace = classNamespace, ModelsNamespace = ModelsNamespace, SolutionName = SolutionName }; templateKey = $"{i}" + item + $"{Suffix}"; var result = Engine.Razor.RunCompile(template, templateKey, model.GetType(), model); string cp = savePath + "\\" + $"{i}" + item + $"{Suffix}.cs"; if (FileHelper.IsExistFile(cp) == false) { FileHelper.CreateFile(cp, result, System.Text.Encoding.UTF8); } } }
} // end of function - Process /*----------------------- InsertParamComment ----------------------------*/ /// <summary> /// /// </summary> /// <param name="ep"></param> protected virtual void InsertParamComment(EditPoint ep, int offset) { var f = Context.CodeElement as CodeFunction; Debug.WriteLine("CodeFunction.DocComment (initially): " + f.DocComment); if (f != null) { ep.InsertLine(""); ep.PadToColumn(offset); ep.InsertLine("/// <summary>"); ep.PadToColumn(offset); ep.InsertLine("/// "); ep.PadToColumn(offset); ep.Insert("/// </summary>"); foreach (var parm in f.Parameters) { CodeParameter codeParam = parm as CodeParameter; ep.InsertLine(""); ep.PadToColumn(offset); ep.Insert("/// <param name=\"" + codeParam.Name + "\"></param>"); } Debug.WriteLine("CodeFunction.DocComment: " + f.DocComment); } return; } // end of function - InsertParamComment
public override bool IsEnabledFor(object target) { if (string.IsNullOrEmpty(constructorParameterType)) { return(false); } ProjectItem untypedProvider = target as ProjectItem; if (untypedProvider != null && untypedProvider.FileCodeModel != null) { CodeClass untypedProviderClass = ProjectItemHelper.GetClass(untypedProvider); if (untypedProviderClass == null || untypedProviderClass.Children == null) { return(false); } foreach (CodeElement codeElement in untypedProviderClass.Children) { CodeFunction codeFunction = codeElement as CodeFunction; if (codeFunction != null) { if (vsCMFunction.vsCMFunctionConstructor.Equals(codeFunction.FunctionKind) && (codeFunction.Parameters.Count == 1)) { CodeParameter codeParameter = (CodeParameter)codeFunction.Parameters.Item(1); if (!string.IsNullOrEmpty(codeParameter.Type.AsFullName) && codeParameter.Type.AsFullName.EndsWith(constructorParameterType)) { return(true); } } } } } return(false); }
public static CodeProperty GetHeadersProperty(this CodeParameter parameter) { return(parameter?.Type is CodeType type && type.TypeDefinition is CodeClass cls && cls.IsOfKind(CodeClassKind.RequestConfiguration) && cls.Properties.FirstOrDefault(p => p.IsOfKind(CodePropertyKind.Headers)) is CodeProperty headersProperty ? headersProperty :
internal EnvDTE.CodeParameter AddParameter(EnvDTE.CodeElement parent, SyntaxNode containerNode, string name, object type, object position) { var typeSymbol = CodeModelService.GetTypeSymbol(type, this.GetSemanticModel(), containerNode.SpanStart); var typeName = typeSymbol.GetEscapedFullName(); var parameterNode = CodeModelService.CreateParameterNode(CodeModelService.GetUnescapedName(name), typeName); var insertionIndex = CodeModelService.PositionVariantToParameterInsertionIndex(position, containerNode, fileCodeModel: this); var newNode = InsertParameter(containerNode, parameterNode, insertionIndex); // Since parameters form part of the NodeKey for functions, delegates, and indexers, // creating a CodeParameter hooked up to the correct parent is a little tricky. After // the call to InsertParameter, the syntax tree has been updated, but not the NodeKey // map or the NodeKey in the parent CodeParameter. If we delegate the creation of the // CodeParameter to CodeModelService.CreateInternalCodeElement, it will attempt to // look up an element in the NodeKey map based on the new syntax tree. This will fail, // causing it to create a new, duplicate element for the parent. Later, when we // reacquire the NodeKeys, the original element will get the proper NodeKey, while the // duplicate will be updated to a meaningless NodeKey. Since the duplicate is the one // being used by the CodeParameter, most operations on it will then fail. // Instead, we need to have the parent passed in to us. var parentObj = ComAggregate.GetManagedObject <AbstractCodeMember>(parent); return(CodeParameter.Create(this.State, parentObj, CodeModelService.GetParameterName(newNode))); }
/// <summary> /// Tries to generate parameter description comment. /// </summary> /// <param name="parent">Parent function.</param> /// <param name="param">Parameter for which to generate the comment.</param> /// <returns>Generated text.</returns> private string TryGenerateParamDesc(CodeFunction parent, CodeParameter param) { ThreadHelper.ThrowIfNotOnUIThread(); string desc = ""; // If the function is a setter or getter, we can try to derive a description for the parameter. bool setter = parent.Name.StartsWith("set"); bool getter = parent.Name.StartsWith("get"); bool isBoolean = param.Type.AsString == "bool"; string[] words = StringHelper.SplitCamelCase(param.Name); if (isBoolean) { desc = StringHelper.Capitalize(String.Format(Config.ParamBooleanFormat, UnabbreviateAndJoin(words))); } else if (setter) { desc = StringHelper.Capitalize(String.Format(Config.ParamSetterDescFormat, UnabbreviateAndJoin(words))); } else if (getter && GetParamDirection(parent, param, null) != ParamDirection.In) { desc = StringHelper.Capitalize(String.Format(Config.ReturnDescFormat, UnabbreviateAndJoin(words))); } return(desc); }
public void WritesApiConstructorWithBackingStore() { method.Kind = CodeMethodKind.ClientConstructor; var coreProp = parentClass.AddProperty(new CodeProperty { Name = "core", Kind = CodePropertyKind.RequestAdapter, }).First(); coreProp.Type = new CodeType { Name = "HttpCore", IsExternal = true, }; method.AddParameter(new CodeParameter { Name = "core", Kind = CodeParameterKind.RequestAdapter, Type = coreProp.Type, }); var backingStoreParam = new CodeParameter { Name = "backingStore", Kind = CodeParameterKind.BackingStore, }; backingStoreParam.Type = new CodeType { Name = "IBackingStore", IsExternal = true, }; method.AddParameter(backingStoreParam); var tempWriter = LanguageWriter.GetLanguageWriter(GenerationLanguage.Go, DefaultPath, DefaultName); tempWriter.SetTextWriter(tw); tempWriter.Write(method); var result = tw.ToString(); Assert.Contains("EnableBackingStore", result); }
private bool compareSingleParameter(CodeParameter codeParameter, string parameter) { Debug.Assert(codeParameter != null); Debug.Assert(parameter != null); if (parameter.Equals(codeParameter.Type.AsString)) { return(true); } if (parameter.StartsWith(codeParameter.Type.AsFullName)) { return(true); // so we also get the REF Parameters } if (parameter.Equals("ubyte") && "System.Byte".Equals(codeParameter.Type.AsFullName)) { return(true); } if (parameter.Equals("byte") && "System.SByte".Equals(codeParameter.Type.AsFullName)) { return(true); } if (parameter.Equals("boolean") && "System.Boolean".Equals(codeParameter.Type.AsFullName)) { return(true); } return(false); }
private void Button_Click(object sender, RoutedEventArgs e) { LS = new OxyPlot.Series.LineSeries(); double Xmin = Convert.ToDouble(rangeA.Text), Xmax = Convert.ToDouble(rangeB.Text); var Calc = new CalculatorManager(); var InputExpression = Calc.CorrectedExpression(formulaTextBox.Text); InputExpression = $"Calc.Value = {InputExpression};"; using (var sndBox = new Sandbox()) { var d = CodeGenerator.CreateCode <double>(sndBox, CS.Compiler, InputExpression, null, null, CodeParameter.Create("Calc", Calc), new CodeParameter("x", typeof(double))); const double delta = 0.01d; for (double i = Xmin; i < Xmax; i += delta) { d.Execute(Calc, i); LS.Points.Add(new DataPoint(i, Calc.Value)); } } Grapher.Model.Series.Clear(); Grapher.Model.Series.Add(LS); }
public void WritesMethodAsyncDescription() { method.Description = methodDescription; var parameter = new CodeParameter(method) { Description = paramDescription, Name = paramName }; parameter.Type = new CodeType(parameter) { Name = "string" }; method.AddParameter(parameter); writer.Write(method); var result = tw.ToString(); Assert.Contains("/**", result); Assert.Contains(methodDescription, result); Assert.Contains("@param ", result); Assert.Contains(paramName, result); Assert.Contains(paramDescription, result); Assert.Contains("@returns a Promise of", result); Assert.Contains("*/", result); AssertExtensions.CurlyBracesAreClosed(result); }
public void AddsInnerClasses() { var model = root.AddClass(new CodeClass { Name = "model", Kind = CodeClassKind.Model }).First(); var method = model.AddMethod(new CodeMethod { Name = "method1", ReturnType = new CodeType { Name = "string", IsExternal = true } }).First(); var parameter = new CodeParameter { Name = "param1", Kind = CodeParameterKind.RequestConfiguration, Type = new CodeType { Name = "SomeCustomType", ActionOf = true, TypeDefinition = new CodeClass { Name = "SomeCustomType" } } }; method.AddParameter(parameter); ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.Java }, root); Assert.Equal(2, model.GetChildElements(true).Count()); }
public static string GetLabel(string name, CodeParameter[] parameters, bool markdown, StringOrMarkupContent description) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } string result = ""; if (markdown) { result += "```ostw\n"; } result += name + CodeParameter.GetLabels(parameters, false); if (markdown) { result += "\n\r```"; } if (markdown && description != null) { result += "\n\r ----- \n\r" + (description.HasString ? description.String : description.MarkupContent.Value); } return(result); }
public static string GetLabel(string type, string name, CodeParameter[] parameters, bool markdown, string description) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } string result = ""; if (markdown) { result += "```ostw\n"; result += type ?? "void"; result += " "; } result += name + CodeParameter.GetLabels(parameters, false); if (markdown) { result += "\n\r```"; } if (markdown && description != null) { result += "\n\r ----- \n\r" + description; } return(result); }
private bool IsInput(CodeParameter parameter) { ThreadHelper.ThrowIfNotOnUIThread(); bool isConst = false; bool isRef = false; string typeName = parameter.Type.AsString; string[] expressions = typeName.Split(' '); foreach (var e in expressions) { if (e == "const") { isConst = true; break; } else if (e == "&" || e == "*") { isRef = true; } } if (typeName.EndsWith("&") || typeName.EndsWith("*")) { isRef = true; } return(isConst || !isRef); }
private string DelegateToString(CodeDelegate codeDelegate) { try { string s = ""; s = s + codeDelegate.Type.AsString + " ("; for (int i = 1; i <= codeDelegate.Parameters.Count; i++) { CodeElement codeElement = codeDelegate.Parameters.Item(i); if (codeElement.Kind == vsCMElement.vsCMElementParameter) { CodeParameter codeParameter = (CodeParameter)codeElement; s = s + codeParameter.Type.AsString + " " + codeParameter.Name; if (i != codeDelegate.Parameters.Count) { s = s + ", "; } } } s = s + ")"; return(s); } catch (Exception e) { System.Diagnostics.Trace.WriteLine(e.Message, "AS VS Expert: DelegateToString"); return(""); } }
public PathmapClassConstructor(PathmapClass pathMapClass) : base(pathMapClass, null, AccessLevel.Public) { Parameters = new CodeParameter[] { new PathmapFileParameter("pathmapFile", "File path of the pathmap to use. Must be a `.pathmap` file.") }; Documentation = "Creates a pathmap from a `.pathmap` file."; }
private bool compareParameterList(CodeElements codeElements, string[] parameters) { Debug.Assert(codeElements != null); Debug.Assert(parameters != null); // only look further if the parameter counts match if (codeElements.Count != parameters.Length) { return(false); } //string modifiedParameter; int i = 0; bool match = true; foreach (CodeElement element in codeElements) { CodeParameter codeParameter = (CodeParameter)element; //modifiedParameter = indexOfMultipleParams.Replace(parameters[i], ""); if (!compareSingleParameter(codeParameter, parameters[i])) { //log(String.Format(Context.LOG_INFO + "Parameter[{0}]: types dont match {1}!={2}", i, codeParameter.Type.AsString, modifiedParameter)); match = false; break; } i++; } return(match); }
public void WritesMethodAsyncDescription() { method.Description = methodDescription; var parameter = new CodeParameter(method) { Description = paramDescription, Name = paramName }; parameter.Type = new CodeType(parameter) { Name = "string" }; method.AddParameter(parameter); writer.Write(method); var result = tw.ToString(); Assert.Contains("/// <summary>", result); Assert.Contains(methodDescription, result); Assert.Contains("<param name=", result); Assert.Contains("</param>", result); Assert.Contains(paramName, result); Assert.Contains(paramDescription, result); Assert.Contains("</summary>", result); AssertExtensions.CurlyBracesAreClosed(result); }
/// <summary> /// /// </summary> /// <param name="Name">Required. The name of the parameter.</param> /// <param name="Type">Required. A vsCMTypeRef constant indicating the data type that the function returns. This can be a CodeTypeRef object, a vsCMTypeRef constant, or a fully qualified type name.</param> /// <param name="Position">Optional. Default = 0. The code element after which to add the new element. If the value is a CodeElement, then the new element is added immediately after it. /// /// If the value is a Long, then AddParameter indicates the element after which to add the new element. /// /// Because collections begin their count at 1, passing 0 indicates that the new element should be placed at the beginning of the collection. A value of -1 means the element should be placed at the end. /// </param> /// <returns>A CodeParameter object. </returns> public CodeParameter AddParameter(string Name, object Type, object Position) { CodeParameter res = AddParameter(CodeObject.Parameters, Name, Type, Position); CommitChanges(); return(res); }
/// <summary> /// <see cref="IAction.Execute"/> /// </summary> public override void Execute() { this.Parameter = this.Method.AddParameter( this.ParameterName, this.ParameterType, this.Position); }
public void WritesSerializerBody() { var parameter = new CodeParameter(method) { Description = paramDescription, Name = paramName }; parameter.Type = new CodeType(parameter) { Name = "string" }; method.MethodKind = CodeMethodKind.Serializer; method.IsAsync = false; AddSerializationProperties(); writer.Write(method); var result = tw.ToString(); Assert.Contains("WriteStringValue", result); Assert.Contains("WriteCollectionOfPrimitiveValues", result); Assert.Contains("WriteCollectionOfObjectValues", result); Assert.Contains("WriteEnumValue", result); Assert.Contains("WriteAdditionalData(additionalData);", result); AssertExtensions.CurlyBracesAreClosed(result); }
private void WriteRequestGeneratorBody(CodeMethod codeElement, CodeParameter requestBodyParam, CodeParameter queryStringParam, CodeParameter headersParam, LanguageWriter writer) { if (codeElement.HttpMethod == null) { throw new InvalidOperationException("http method cannot be null"); } writer.WriteLines("request_info = RequestInfo.new()", $"request_info.URI = {conventions.CurrentPathPropertyName} + {conventions.PathSegmentPropertyName}", $"request_info.http_method = :{codeElement.HttpMethod?.ToString().ToUpperInvariant()}"); if (headersParam != null) { writer.WriteLine($"request_info.set_headers_from_raw_object(h)"); } if (queryStringParam != null) { writer.WriteLines($"request_info.set_query_string_parameters_from_raw_object(q)"); } if (requestBodyParam != null) { if (requestBodyParam.Type.Name.Equals(conventions.StreamTypeName, StringComparison.OrdinalIgnoreCase)) { writer.WriteLine($"request_info.set_stream_content({requestBodyParam.Name})"); } else { writer.WriteLine($"request_info.set_content_from_parsable({requestBodyParam.Name}, self.{RubyConventionService.SerializerFactoryPropertyName}, \"{codeElement.ContentType}\")"); } } writer.WriteLine("return request_info;"); }
private void WriteRequestExecutorBody(CodeMethod codeElement, CodeParameter requestBodyParam, CodeParameter queryStringParam, CodeParameter headersParam, LanguageWriter writer) { if (codeElement.HttpMethod == null) { throw new InvalidOperationException("http method cannot be null"); } var generatorMethodName = (codeElement.Parent as CodeClass) .GetChildElements(true) .OfType <CodeMethod>() .FirstOrDefault(x => x.IsOfKind(CodeMethodKind.RequestGenerator) && x.HttpMethod == codeElement.HttpMethod) ?.Name ?.ToFirstCharacterLowerCase(); writer.WriteLine($"request_info = self.{generatorMethodName.ToSnakeCase()}("); var requestInfoParameters = new List <string> { requestBodyParam?.Name, queryStringParam?.Name, headersParam?.Name }.Where(x => x != null); if (requestInfoParameters.Any()) { writer.IncreaseIndent(); writer.WriteLine(requestInfoParameters.Aggregate((x, y) => $"{x.ToSnakeCase()}, {y.ToSnakeCase()}")); writer.DecreaseIndent(); } writer.WriteLine(")"); var isStream = conventions.StreamTypeName.Equals(StringComparison.OrdinalIgnoreCase); var genericTypeForSendMethod = GetSendRequestMethodName(isStream); writer.WriteLine($"return self.http_core.{genericTypeForSendMethod}(request_info, response_handler)"); }
private string GetFunctionSignature(CodeFunction codeFunction) { string signature = null; if (codeFunction != null) { if (string.IsNullOrEmpty(codeFunction.Type.AsFullName)) { signature = "System.Void"; } else { var type = ResolveType(codeFunction.Type.AsFullName); signature = (type == null ? codeFunction.Type.AsFullName : type.FullName); } foreach (CodeElement element in codeFunction.Parameters) { CodeParameter parameter = element as CodeParameter; if (parameter != null) { var type = ResolveType(parameter.Type.AsFullName); signature = signature + "," + (type == null ? parameter.Type.AsFullName : type.FullName); } } } return(signature); }
public void DoesNotKeepCancellationParametersInRequestExecutors() { var model = root.AddClass(new CodeClass { Name = "model", Kind = CodeClassKind.RequestBuilder }).First(); var method = model.AddMethod(new CodeMethod { Name = "getMethod", Kind = CodeMethodKind.RequestExecutor, ReturnType = new CodeType { Name = "string" } }).First(); var cancellationParam = new CodeParameter { Name = "cancelletionToken", Optional = true, Kind = CodeParameterKind.Cancellation, Description = "Cancellation token to use when cancelling requests", Type = new CodeType { Name = "CancelletionToken", IsExternal = true }, }; method.AddParameter(cancellationParam); ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.TypeScript }, root); //using CSharp so the cancelletionToken doesn't get removed Assert.False(method.Parameters.Any()); Assert.DoesNotContain(cancellationParam, method.Parameters); }
private String createJavaStyleComment(CodeElement codeElement, string lineOffset) { StringBuilder stringBuilder = new StringBuilder("/** "); stringBuilder.AppendFormat("\r\n" + lineOffset + "* "); stringBuilder.AppendFormat("\r\n" + lineOffset + "* "); if (codeElement != null && codeElement is CodeFunction) { CodeFunction codeFunction = codeElement as CodeFunction; foreach (CodeElement codeElementChild in codeElement.Children) { CodeParameter codeParameter = codeElementChild as CodeParameter; if (codeParameter != null) { stringBuilder.AppendFormat("\r\n" + lineOffset + "* @param {0} ", codeParameter.FullName); } } stringBuilder.AppendFormat("\r\n" + lineOffset + "* "); if (codeFunction.Type.AsString != "void") { stringBuilder.AppendFormat("\r\n" + lineOffset + "* @return "); stringBuilder.AppendFormat("\r\n" + lineOffset + "* "); } stringBuilder.AppendFormat("\r\n" + lineOffset + "*/"); } return(stringBuilder.ToString()); }
protected virtual void VisitParameter(CodeParameter codeParameter) { }
public IBindingParameter CreateBindingParameter(CodeParameter codeParameter) { return new BindingParameter( CreateBindingType(codeParameter.Type), codeParameter.Name); }
public VsBindingParameter(CodeParameter codeParameter) { ParameterName = codeParameter.Name; Type = new VsBindingType(codeParameter.Type); }
public MetaColumnInfo(CodeParameter property) : this(property.Name, property.Type.AsString, false) { }
protected override CodeElement CreateCodeElement(string name, string fullName, CodeLocation location, CodeElement parent) { CodeParameter parameter = new CodeParameter(name, fullName, location, parent); return parameter; }