public void CheckConditionalStatement(ParserRuleContext context, out ErrorInformation error) { error = null; var relationalExpressionContext = ((Equality_expressionContext)context).relational_expression(); bool isBoolConditional = (context.GetText().Contains("true") || context.GetText().Contains("false")); if (isBoolConditional && relationalExpressionContext.Length == 2) { List <ReplaceCodeInfomation> replaceCodes = new List <ReplaceCodeInfomation>() { new ReplaceCodeInfomation() { Start = context.Start.StartIndex, Length = context.Stop.StopIndex - context.Start.StartIndex + 1, ReplaceCode = ReplaceCode(context.GetText()) } }; error = new ErrorInformation() { ErrorCode = "IF0001", ReplaceCode = replaceCodes, DisplayText = "Simply statement", ErrorMessage = "UIT: Bool return type in conditional statement could be simplied", StartIndex = context.Start.StartIndex, Length = context.Stop.StopIndex - context.Start.StartIndex + 1 }; } }
public virtual void EnterEmoji([NotNull] ParserRuleContext context) { if (emojiMap.ContainsKey(context.GetText())) { Replacements.Push(new Replacement( context.start.StartIndex, context.stop.StopIndex, emojiMap[context.GetText()].ToString() )); } }
private List <Diagnostic> CheckExpression(ParserRuleContext expressionContext, string prefix = "") { var exp = expressionContext.GetText(); var result = new List <Diagnostic>(); if (!exp.EndsWith("}")) { result.Add(BuildLGDiagnostic(TemplateErrors.NoCloseBracket, context: expressionContext)); } else { exp = exp.TrimExpression(); try { ExpressionParser.Parse(exp); } catch (Exception e) { var suffixErrorMsg = Evaluator.ConcatErrorMsg(TemplateErrors.ExpressionParseError(exp), e.Message); var errorMsg = Evaluator.ConcatErrorMsg(prefix, suffixErrorMsg); result.Add(BuildLGDiagnostic(errorMsg, context: expressionContext)); return(result); } } return(result); }
private static void CheckAdd(ParserRuleContext context, string cssClass, List <DiagramItem> items) { if (context != null) { items.Add(TerminalWithClass(context.GetText(), cssClass)); } }
string GetRenameTypes(ParserRuleContext context) { var text = context.GetText(); var split = text.Split(' ', '\t'); return(split[split.Length - 1]); }
private void SematicError(ParserRuleContext ctx, String msg) { m_outStream.WriteLine("Error on line " + ctx.start.Line + ": \n" + msg); m_outStream.WriteLine("Offending Code: "); m_outStream.WriteLine("\b\"" + ctx.GetText() + "\""); throw new SemanticException("Sematic Error"); }
private List <Diagnostic> CheckExpression(ParserRuleContext expressionContext, string prefix = "") { var exp = expressionContext.GetText(); var result = new List <Diagnostic>(); if (!exp.EndsWith("}", StringComparison.Ordinal)) { result.Add(BuildLGDiagnostic(TemplateErrors.NoCloseBracket, context: expressionContext)); } else { exp = exp.TrimExpression(); try { ExpressionParser.Parse(exp); } #pragma warning disable CA1031 // Do not catch general exception types (catch any exception and return it in the result) catch (Exception e) #pragma warning restore CA1031 // Do not catch general exception types { var suffixErrorMsg = Evaluator.ConcatErrorMsg(TemplateErrors.ExpressionParseError(exp), e.Message); var errorMsg = Evaluator.ConcatErrorMsg(prefix, suffixErrorMsg); result.Add(BuildLGDiagnostic(errorMsg, context: expressionContext)); return(result); } } return(result); }
private bool EvalExpressionInCondition(ParserRuleContext expressionContext, string contentLine, string errorPrefix = "") { var exp = expressionContext.GetText().TrimExpression(); var(result, error) = EvalByAdaptiveExpression(exp, CurrentTarget().Scope); if (_lgOptions.StrictMode == true && (error != null || result == null)) { var templateName = CurrentTarget().TemplateName; if (_evaluationTargetStack.Count > 0) { _evaluationTargetStack.Pop(); } CheckExpressionResult(exp, error, result, templateName, contentLine, errorPrefix); } else if (error != null || result == null || (result is bool r1 && r1 == false) || (result is int r2 && r2 == 0)) { return(false); } return(true); }
private void Visit(ParserRuleContext parserRuleContext) { if (IsUnaryResultContext(parserRuleContext)) { VisitUnaryResultContext(parserRuleContext); } else if (parserRuleContext is VBAParser.LExprContext lExpr) { Visit(lExpr); } else if (parserRuleContext is VBAParser.LiteralExprContext litExpr) { Visit(litExpr); } else if (parserRuleContext is VBAParser.CaseClauseContext || parserRuleContext is VBAParser.RangeClauseContext) { VisitImpl(parserRuleContext); StoreVisitResult(parserRuleContext, _inspValueFactory.Create(parserRuleContext.GetText())); } else if (IsBinaryMathContext(parserRuleContext) || IsBinaryLogicalContext(parserRuleContext)) { VisitBinaryOpEvaluationContext(parserRuleContext); } else if (IsUnaryLogicalContext(parserRuleContext) || IsUnaryMathContext(parserRuleContext)) { VisitUnaryOpEvaluationContext(parserRuleContext); } }
public static void ErrorCode(int n, ParserRuleContext prc) { var t = prc.GetText(); var l = prc.Start.Line; var c = prc.Start.Column; /*Console.Write(String.Format("ErrorCode({0}): ", n)); * switch (n) * { * case 1: * Console.WriteLine("Something Error"); * break; * case 2: * Console.WriteLine("Undefine Variable"); * break; * case 3: * Console.WriteLine("Divide By Zero"); * break; * case 4: * Console.WriteLine("Type Error"); * break; * case 5: * Console.WriteLine("Function Parament Count Not Match"); * break; * default: * break; * } * Console.WriteLine(String.Format("#\"{0}\" @line {1}:{2}", t, l, c));*/ Console.WriteLine("error"); Environment.Exit(1); }
public static Range GetRange(ParserRuleContext context) { if (context.stop == null) { Pos pos = new Pos(context.start.Line, context.start.Column); return(new Range(pos, pos)); } if (context.start.Line == context.stop.Line && context.start.Column == context.stop.Column) { return(new Range ( new Pos(context.start.Line - 1, context.start.Column), new Pos(context.stop.Line - 1, context.stop.Column + context.GetText().Length) )); } else { return(new Range ( new Pos(context.start.Line - 1, context.start.Column), new Pos(context.stop.Line - 1, context.stop.Column + 1) )); } }
string GetContentFromCharType(ParserRuleContext context) { var text = context.GetText(); var split = text.Split(' ', '\t', ':'); return(split[split.Length - 1]); }
/// <summary> /// Initializes a new instance of the <see cref="TreeExpressionEvaluator"/> class. /// </summary> /// <param name="requiredPattern">The requiredPattern<see cref="ParserRuleContext"/>.</param> /// <param name="matcher">The <see cref="Matcher"/>.</param> /// <param name="verbose">True to enable verbose logging.</param> public TreeExpressionEvaluator(ParserRuleContext requiredPattern, Matcher matcher, bool verbose) { this.requiredPatternText = requiredPattern.GetText(); this.matcher = matcher; this.verbose = verbose; this.FixedValue = this.CalculateFixedValue(requiredPattern); this.WalkListForUnitTesting = new WalkList(requiredPattern, matcher.Lookups, matcher.LookupSets, verbose); }
public static string GetFunctionName(ParserRuleContext context) { if (context == null) { return("<Empty>"); } return("Unnamed" + HashUtil.Base64SHA256(context.GetText())); }
private Identifier GetIdentifier(ParserRuleContext context) { if (context == null) { return(null); } return(new Identifier(context.GetText(), this.DBMSType)); }
public void AddAttr(string type, string input, ParserRuleContext ctx) { var text = ctx.GetText(input); int start, end; ctx.GetBounds(out start, out end); AddAttrNode(type, text, start, end); }
private RosTypeInfo VisitBuiltInType(ParserRuleContext context) { var rosType = context.GetText(); var typeInfo = RosTypeInfo.CreateBuiltIn(rosType); _listener.OnVisitBuiltInType(typeInfo); return(typeInfo); }
public static QsiLiteralExpressionNode VisitLiteral(ParserRuleContext context) { QsiDataType literalType; object value; switch (context) { case NullLiteralContext _: literalType = QsiDataType.Null; value = null; break; case StringLiteralContext stringLiteral: { value = string.Join("", stringLiteral.STRING_LITERAL() .Select(l => IdentifierUtility.Unescape(l.GetText()))); literalType = QsiDataType.String; break; } case DecimalLiteralContext _: literalType = QsiDataType.Decimal; value = decimal.Parse(context.GetText()); break; case BooleanLiteralContext _: literalType = QsiDataType.Boolean; value = bool.Parse(context.GetText()); break; default: throw TreeHelper.NotSupportedTree(context); } var node = new QsiLiteralExpressionNode { Value = value, Type = literalType }; PrimarSqlTree.PutContextSpan(node, context); return(node); }
public static string GetFullText(this ParserRuleContext context) { if (context.Start == null || context.Stop == null || context.Start.StartIndex < 0 || context.Stop.StopIndex < 0) { return(context.GetText()); // Fallback } return(context.Start.InputStream.GetText(Interval.Of(context.Start.StartIndex, context.Stop.StopIndex))); }
private BinaryExpressionNode CreateBinaryExpressionNode(NodeLocation location, ParserRuleContext operatorContext, DaedalusParser.ExpressionContext[] expressionContexts) { string oper = operatorContext.GetText(); NodeLocation operatorLocation = GetLocation(operatorContext); ExpressionNode leftSide = (ExpressionNode)Visit(expressionContexts[0]); ExpressionNode rightSide = (ExpressionNode)Visit(expressionContexts[1]); return(new BinaryExpressionNode(location, GetBinaryOperator(oper), operatorLocation, leftSide, rightSide)); }
private void ResolveDefault( ParserRuleContext expression, StatementResolutionContext statementContext = StatementResolutionContext.Undefined, bool isAssignmentTarget = false, bool hasExplicitLetStatement = false, bool isSetAssignment = false) { var withExpression = GetInnerMostWithExpression(); var boundExpression = _bindingService.ResolveDefault( _moduleDeclaration, _currentParent, expression, withExpression, statementContext); if (boundExpression.Classification == ExpressionClassification.ResolutionFailed) { var lexpression = expression as VBAParser.LExpressionContext ?? expression.GetChild <VBAParser.LExpressionContext>(0) ?? (expression as VBAParser.LExprContext ?? expression.GetChild <VBAParser.LExprContext>(0))?.lExpression(); if (lexpression != null) { _declarationFinder.AddUnboundContext(_currentParent, lexpression, withExpression); } else { Logger.Warn( $"Default Context: Failed to resolve {expression.GetText()}. Binding as much as we can."); } } IParameterizedDeclaration defaultMember = null; if (boundExpression.ReferencedDeclaration != null && boundExpression.ReferencedDeclaration.DeclarationType != DeclarationType.Project && boundExpression.ReferencedDeclaration.AsTypeDeclaration != null) { var module = boundExpression.ReferencedDeclaration.AsTypeDeclaration; var members = _declarationFinder.Members(module); defaultMember = (IParameterizedDeclaration)members.FirstOrDefault(member => member is IParameterizedDeclaration && member.Attributes.HasDefaultMemberAttribute() && (isAssignmentTarget ? member.DeclarationType.HasFlag(DeclarationType.Procedure) : member.DeclarationType.HasFlag(DeclarationType.Function))); } _boundExpressionVisitor.AddIdentifierReferences( boundExpression, _qualifiedModuleName, _currentScope, _currentParent, isAssignmentTarget && (defaultMember == null || isSetAssignment || defaultMember.Parameters.All(param => param.IsOptional)), hasExplicitLetStatement, isSetAssignment); }
public void EnterNumber([NotNull] ParserRuleContext context) { var literal = context.GetText().ToLowerInvariant(); if (literal.StartsWith("0b")) { var tokens = literal.Substring(2).Split(new char[] { '.' }, StringSplitOptions.None); var integerStr = tokens[0]; var fractionStr = tokens.Length > 1 ? tokens[1] : ""; while (integerStr.Length % 4 != 0) { integerStr = "0" + integerStr; } while (fractionStr.Length % 4 != 0) { fractionStr += "0"; } var str = new StringBuilder("0x"); for (int i = 0; i < integerStr.Length; i += 4) { var num = (integerStr[i + 3] == '1' ? 1 : 0) | (integerStr[i + 2] == '1' ? 2 : 0) | (integerStr[i + 1] == '1' ? 4 : 0) | (integerStr[i + 0] == '1' ? 8 : 0) ; str.Append(num.ToString("x1", CultureInfo.InvariantCulture)); } if (fractionStr.Length > 0) { str.Append("."); for (int i = 0; i < fractionStr.Length; i += 4) { var num = (fractionStr[i + 3] == '1' ? 1 : 0) | (fractionStr[i + 2] == '1' ? 2 : 0) | (fractionStr[i + 1] == '1' ? 4 : 0) | (fractionStr[i + 0] == '1' ? 8 : 0) ; str.Append(num.ToString("x1", CultureInfo.InvariantCulture)); } } Replacements.Push( new Replacement( context.start.StartIndex, context.stop.StopIndex, str.ToString() ) ); } }
public override void ExitEveryRule([NotNull] ParserRuleContext context) { if (this.writer != default) { writer($"{System.Reflection.MethodBase.GetCurrentMethod().Name} | {context.GetText()} | {context.ToStringTree(parser)}"); } base.ExitEveryRule(context); }
public override void EnterEveryRule([NotNull] ParserRuleContext context) { if (context.ChildCount > 1) { if (_isOtherListener == 1) { Rules.Add(new BaseRule(context.SourceInterval, context, context.GetText())); } } }
private void ResolveType(ParserRuleContext expression) { var boundExpression = _bindingService.ResolveType(_moduleDeclaration, _currentParent, expression); if (boundExpression.Classification == ExpressionClassification.ResolutionFailed) { Logger.Warn($"Type Context: Failed to resolve {expression.GetText()}. Binding as much as we can."); } _boundExpressionVisitor.AddIdentifierReferences(boundExpression, _qualifiedModuleName, _currentScope, _currentParent); }
// Checks if the current context is an identifier, and pushes it to the expression stack. private void PushIfIdentifier(ParserRuleContext context) { if (context.ChildCount == 1) { var child = context.GetChild(0) as TerminalNodeImpl; if (child != null && child.Payload.Type == SBP.IDENTIFIER) { m_expressionData.Push(SBExpressionData.CreateIdentifier(context.GetText(), token: child.Payload as CommonToken)); } } }
private IdentifierReference CreateReference(ParserRuleContext callSiteContext, Declaration callee, bool isAssignmentTarget = false, bool hasExplicitLetStatement = false) { if (callSiteContext == null) { return(null); } var name = callSiteContext.GetText(); var selection = callSiteContext.GetSelection(); return(new IdentifierReference(_qualifiedModuleName, name, selection, callSiteContext, callee, isAssignmentTarget, hasExplicitLetStatement)); }
/// <summary> /// Create a node when a rule is visited /// </summary> /// <param name="context"></param> public override void EnterEveryRule([NotNull] ParserRuleContext context) { base.EnterEveryRule(context); //create metadata to save some information of context TreeViewerNodeMeta node = new TreeViewerNodeMeta(); node.StartIndex = context.Start.StartIndex; node.StopIndex = context.Stop.StopIndex; //current node is parent of context, add context to child list of current node if (_currentNode.Text == context.Parent?.GetType().Name) { _currentNode.Nodes.Add(context.GetType().Name); _currentNode = _currentNode.Nodes[_currentNode.Nodes.Count - 1]; _currentNode.Tag = node; } else { //current node is root node if (_currentNode.Parent == null) { _currentNode.Nodes.Add(context.GetType().Name); _currentNode = _currentNode.Nodes[_currentNode.Nodes.Count - 1]; _currentNode.Tag = node; } else { //current node and context node is same lever _currentNode.Parent.Nodes.Add(context.GetType().Name); _currentNode = _currentNode.Parent.Nodes[_currentNode.Parent.Nodes.Count - 1]; _currentNode.Tag = node; } } //context is leaf node if (context.ChildCount == 1 && context.GetChild(0).ChildCount <= 0) { node.Token = context.GetText(); _currentNode.Nodes.Add(context.GetText()); _currentNode.Nodes[0].Tag = node; } }
public static void Context(ParserRuleContext ctx, LogEventLevel level = LogEventLevel.Debug) { Log.Write( level, "[{Depth}:{ContextType}] [{SourceInterval}] | children: {ChildrenCount} | {Code}", ctx.Depth(), ctx.GetType().Name, ctx.SourceInterval, ctx.ChildCount, ctx.GetText() ); }
private void UpdateCondition(ParserRuleContext condition, IModuleRewriter rewriter) { if (condition.GetText().Contains(' ')) { rewriter.InsertBefore(condition.Start.TokenIndex, "Not ("); rewriter.InsertAfter(condition.Stop.TokenIndex, ")"); } else { rewriter.InsertBefore(condition.Start.TokenIndex, "Not "); } }
public void EnterEveryRule(ParserRuleContext ctx) { if (VerboseUpdate != null) { VerboseUpdate(ctx.GetText()); } }
private static ExpressionSyntax Constant(ParserRuleContext node) { return CSharp.ParseExpression(node.GetText()); }
private static ExpressionSyntax Identifer(ParserRuleContext arg) { return CSharp.IdentifierName(arg.GetText()); }
private static ExpressionSyntax StringLiteral(ParserRuleContext arg) { return CSharp.ParseExpression(arg.GetText()); }
private CodeSnippetTypeMember CreateSnippetMember(ParserRuleContext context) { // The original source code String sourceCode = context.GetText(); // CodeSnippetTypeMember snippet = new CodeSnippetTypeMember(sourceCode); FillCodeDomDesignerData(snippet, context.Start.Line, context.Start.Column); return snippet; }
public UntypedFunctionUsageQuickFix(ParserRuleContext context, QualifiedSelection selection) : base(context, selection, string.Format(InspectionsUI.QuickFixUseTypedFunction_, context.GetText())) { }