Best Gauge code snippet using parser.Errors
gengine_parser_listener.go
Source:gengine_parser_listener.go
...12)13func NewGengineParserListener(ctx *base.KnowledgeContext) *GengineParserListener {14 return &GengineParserListener{15 Stack: stack.New(),16 ParseErrors: make([]string, 0),17 KnowledgeContext: ctx,18 }19}20type GengineParserListener struct {21 parser.BasegengineListener22 ParseErrors []string23 KnowledgeContext *base.KnowledgeContext24 Stack *stack.Stack25 ruleName string26 ruleDescription string27 salience int6428}29func (g *GengineParserListener) AddError(e error) {30 g.ParseErrors = append(g.ParseErrors, e.Error())31}32func (g *GengineParserListener) VisitTerminal(node antlr.TerminalNode) {}33func (g *GengineParserListener) VisitErrorNode(node antlr.ErrorNode) {34 g.AddError(errors.New(fmt.Sprintf("cannot recognize token : %s", node.GetText())))35}36func (g *GengineParserListener) EnterEveryRule(ctx antlr.ParserRuleContext) {}37func (g *GengineParserListener) ExitEveryRule(ctx antlr.ParserRuleContext) {}38func (g *GengineParserListener) EnterPrimary(ctx *parser.PrimaryContext) {}39func (g *GengineParserListener) ExitPrimary(ctx *parser.PrimaryContext) {}40func (g *GengineParserListener) EnterRuleEntity(ctx *parser.RuleEntityContext) {41 if len(g.ParseErrors) > 0 {42 return43 }44 entity := &base.RuleEntity{45 Salience: 0,46 }47 //init48 g.ruleName = ""49 g.ruleDescription = ""50 g.salience = 051 g.Stack.Push(entity)52}53func (g *GengineParserListener) ExitRuleEntity(ctx *parser.RuleEntityContext) {54 if len(g.ParseErrors) > 0 {55 return56 }57 entity := g.Stack.Pop().(*base.RuleEntity)58 if _, ok := g.KnowledgeContext.RuleEntities[entity.RuleName]; ok {59 g.AddError(errors.New(fmt.Sprintf("already existed entity's name \"%s\"", entity.RuleName)))60 return61 }62 g.KnowledgeContext.RuleEntities[entity.RuleName] = entity63}64func (g *GengineParserListener) EnterRuleName(ctx *parser.RuleNameContext) {}65func (g *GengineParserListener) ExitRuleName(ctx *parser.RuleNameContext) {66 if len(g.ParseErrors) > 0 {67 return68 }69 text := ctx.GetText()70 ruleName := strings.Trim(text, "\"")71 if len(ruleName) == 0 {72 g.AddError(errors.New("rule name is \"\""))73 return74 }75 entity := g.Stack.Peek().(*base.RuleEntity)76 g.ruleName = ruleName77 entity.RuleName = ruleName78}79func (g *GengineParserListener) EnterSalience(ctx *parser.SalienceContext) {80}81func (g *GengineParserListener) ExitSalience(ctx *parser.SalienceContext) {82 if len(g.ParseErrors) > 0 {83 return84 }85 text := ctx.GetText()86 lower := strings.ToLower(text)87 is := strings.ReplaceAll(lower, "salience", "")88 i, err := strconv.ParseInt(is, 10, 64)89 if err != nil {90 g.AddError(errors.New(fmt.Sprintf("salience is not int, salience = \"%s\"", text)))91 return92 }93 g.salience = i94}95func (g *GengineParserListener) EnterRuleDescription(ctx *parser.RuleDescriptionContext) {}96func (g *GengineParserListener) ExitRuleDescription(ctx *parser.RuleDescriptionContext) {97 if len(g.ParseErrors) > 0 {98 return99 }100 text := ctx.GetText()101 ruleDescription := strings.Trim(text, "\"")102 entity := g.Stack.Peek().(*base.RuleEntity)103 entity.RuleDescription = ruleDescription104 g.ruleDescription = ruleDescription105}106func (g *GengineParserListener) EnterRuleContent(ctx *parser.RuleContentContext) {107 if len(g.ParseErrors) > 0 {108 return109 }110 ruleContent := &base.RuleContent{}111 g.Stack.Push(ruleContent)112}113func (g *GengineParserListener) ExitRuleContent(ctx *parser.RuleContentContext) {114 if len(g.ParseErrors) > 0 {115 return116 }117 ruleContent := g.Stack.Pop().(*base.RuleContent)118 entity := g.Stack.Peek().(*base.RuleEntity)119 entity.RuleContent = ruleContent120}121func (g *GengineParserListener) EnterConcStatement(ctx *parser.ConcStatementContext) {122 if len(g.ParseErrors) > 0 {123 return124 }125 concStatement := &base.ConcStatement{}126 g.Stack.Push(concStatement)127}128func (g *GengineParserListener) ExitConcStatement(ctx *parser.ConcStatementContext) {129 if len(g.ParseErrors) > 0 {130 return131 }132 concStatement := g.Stack.Pop().(*base.ConcStatement)133 statement := g.Stack.Peek().(*base.Statement)134 statement.ConcStatement = concStatement135}136func (g *GengineParserListener) EnterAssignment(ctx *parser.AssignmentContext) {137 if len(g.ParseErrors) > 0 {138 return139 }140 assignment := &base.Assignment{}141 g.Stack.Push(assignment)142}143func (g *GengineParserListener) ExitAssignment(ctx *parser.AssignmentContext) {144 if len(g.ParseErrors) > 0 {145 return146 }147 expr := g.Stack.Pop().(*base.Assignment)148 expr.Code = ctx.GetText()149 expr.LineNum = ctx.GetStart().GetLine()150 expr.Column = ctx.GetStart().GetColumn()151 expr.LineStop = ctx.GetStop().GetColumn()152 holder := g.Stack.Peek().(base.AssignmentHolder)153 err := holder.AcceptAssignment(expr)154 if err != nil {155 g.AddError(err)156 }157}158func (g *GengineParserListener) EnterMathExpression(ctx *parser.MathExpressionContext) {159 if len(g.ParseErrors) > 0 {160 return161 }162 me := &base.MathExpression{}163 g.Stack.Push(me)164}165func (g *GengineParserListener) ExitMathExpression(ctx *parser.MathExpressionContext) {166 if len(g.ParseErrors) > 0 {167 return168 }169 expr := g.Stack.Pop().(*base.MathExpression)170 expr.Code = ctx.GetText()171 expr.LineNum = ctx.GetStart().GetLine()172 expr.Column = ctx.GetStart().GetColumn()173 expr.LineStop = ctx.GetStop().GetColumn()174 holder := g.Stack.Peek().(base.MathExpressionHolder)175 err := holder.AcceptMathExpression(expr)176 if err != nil {177 g.AddError(err)178 }179}180func (g *GengineParserListener) EnterExpression(ctx *parser.ExpressionContext) {181 if len(g.ParseErrors) > 0 {182 return183 }184 expression := &base.Expression{}185 g.Stack.Push(expression)186}187func (g *GengineParserListener) ExitExpression(ctx *parser.ExpressionContext) {188 if len(g.ParseErrors) > 0 {189 return190 }191 expr := g.Stack.Pop().(*base.Expression)192 expr.Code = ctx.GetText()193 expr.LineNum = ctx.GetStart().GetLine()194 expr.Column = ctx.GetStart().GetColumn()195 expr.LineStop = ctx.GetStop().GetColumn()196 holder := g.Stack.Peek().(base.ExpressionHolder)197 err := holder.AcceptExpression(expr)198 if err != nil {199 g.AddError(err)200 }201}202func (g *GengineParserListener) EnterExpressionAtom(ctx *parser.ExpressionAtomContext) {203 if len(g.ParseErrors) > 0 {204 return205 }206 exprAtom := &base.ExpressionAtom{}207 g.Stack.Push(exprAtom)208}209func (g *GengineParserListener) ExitExpressionAtom(ctx *parser.ExpressionAtomContext) {210 if len(g.ParseErrors) > 0 {211 return212 }213 expr := g.Stack.Pop().(*base.ExpressionAtom)214 expr.Code = ctx.GetText()215 expr.LineNum = ctx.GetStart().GetLine()216 expr.Column = ctx.GetStart().GetColumn()217 expr.LineStop = ctx.GetStop().GetColumn()218 holder := g.Stack.Peek().(base.ExpressionAtomHolder)219 err := holder.AcceptExpressionAtom(expr)220 if err != nil {221 g.AddError(err)222 }223}224func (g *GengineParserListener) EnterMethodCall(ctx *parser.MethodCallContext) {225 if len(g.ParseErrors) > 0 {226 return227 }228 funcCall := &base.MethodCall{229 MethodName: ctx.DOTTEDNAME().GetText(),230 }231 g.Stack.Push(funcCall)232}233func (g *GengineParserListener) ExitMethodCall(ctx *parser.MethodCallContext) {234 if len(g.ParseErrors) > 0 {235 return236 }237 expr := g.Stack.Pop().(*base.MethodCall)238 expr.Code = ctx.GetText()239 expr.LineNum = ctx.GetStart().GetLine()240 expr.Column = ctx.GetStart().GetColumn()241 expr.LineStop = ctx.GetStop().GetColumn()242 holder := g.Stack.Peek().(base.MethodCallHolder)243 err := holder.AcceptMethodCall(expr)244 if err != nil {245 g.AddError(err)246 }247}248func (g *GengineParserListener) EnterFunctionCall(ctx *parser.FunctionCallContext) {249 if len(g.ParseErrors) > 0 {250 return251 }252 funcCall := &base.FunctionCall{253 FunctionName: ctx.SIMPLENAME().GetText(),254 }255 g.Stack.Push(funcCall)256}257func (g *GengineParserListener) ExitFunctionCall(ctx *parser.FunctionCallContext) {258 if len(g.ParseErrors) > 0 {259 return260 }261 expr := g.Stack.Pop().(*base.FunctionCall)262 expr.Code = ctx.GetText()263 expr.LineNum = ctx.GetStart().GetLine()264 expr.Column = ctx.GetStart().GetColumn()265 expr.LineStop = ctx.GetStop().GetColumn()266 holder := g.Stack.Peek().(base.FunctionCallHolder)267 err := holder.AcceptFunctionCall(expr)268 if err != nil {269 g.AddError(err)270 }271}272func (g *GengineParserListener) EnterFunctionArgs(ctx *parser.FunctionArgsContext) {273 if len(g.ParseErrors) > 0 {274 return275 }276 funcArg := &base.Args{277 ArgList: make([]*base.Arg, 0),278 }279 g.Stack.Push(funcArg)280}281func (g *GengineParserListener) ExitFunctionArgs(ctx *parser.FunctionArgsContext) {282 if len(g.ParseErrors) > 0 {283 return284 }285 expr := g.Stack.Pop().(*base.Args)286 argHolder := g.Stack.Peek().(base.ArgsHolder)287 err := argHolder.AcceptArgs(expr)288 if err != nil {289 g.AddError(err)290 }291}292func (g *GengineParserListener) EnterLogicalOperator(ctx *parser.LogicalOperatorContext) {}293func (g *GengineParserListener) ExitLogicalOperator(ctx *parser.LogicalOperatorContext) {294 if len(g.ParseErrors) > 0 {295 return296 }297 expr := g.Stack.Peek().(*base.Expression)298 // && and ||299 expr.LogicalOperator = ctx.GetText()300}301func (g *GengineParserListener) EnterNotOperator(ctx *parser.NotOperatorContext) {}302func (g *GengineParserListener) ExitNotOperator(ctx *parser.NotOperatorContext) {303 if len(g.ParseErrors) > 0 {304 return305 }306 expr := g.Stack.Peek().(*base.Expression)307 // !308 expr.NotOperator = ctx.GetText()309}310func (g *GengineParserListener) EnterVariable(ctx *parser.VariableContext) {}311func (g *GengineParserListener) ExitVariable(ctx *parser.VariableContext) {312 if len(g.ParseErrors) > 0 {313 return314 }315 varName := ctx.GetText()316 holder := g.Stack.Peek().(base.VariableHolder)317 err := holder.AcceptVariable(varName)318 if err != nil {319 g.AddError(err)320 }321}322func (g *GengineParserListener) EnterMathPmOperator(ctx *parser.MathPmOperatorContext) {}323func (g *GengineParserListener) ExitMathPmOperator(ctx *parser.MathPmOperatorContext) {324 if len(g.ParseErrors) > 0 {325 return326 }327 expr := g.Stack.Peek().(*base.MathExpression)328 // + -329 expr.MathPmOperator = ctx.GetText()330}331func (g *GengineParserListener) EnterMathMdOperator(ctx *parser.MathMdOperatorContext) {}332func (g *GengineParserListener) ExitMathMdOperator(ctx *parser.MathMdOperatorContext) {333 if len(g.ParseErrors) > 0 {334 return335 }336 expr := g.Stack.Peek().(*base.MathExpression)337 // * /338 expr.MathMdOperator = ctx.GetText()339}340func (g *GengineParserListener) EnterComparisonOperator(ctx *parser.ComparisonOperatorContext) {}341func (g *GengineParserListener) ExitComparisonOperator(ctx *parser.ComparisonOperatorContext) {342 if len(g.ParseErrors) > 0 {343 return344 }345 expr := g.Stack.Peek().(*base.Expression)346 // == != < > <= >=347 expr.ComparisonOperator = ctx.GetText()348}349func (g *GengineParserListener) EnterConstant(ctx *parser.ConstantContext) {350 if len(g.ParseErrors) > 0 {351 return352 }353 cons := &base.Constant{}354 g.Stack.Push(cons)355}356func (g *GengineParserListener) ExitConstant(ctx *parser.ConstantContext) {357 if len(g.ParseErrors) > 0 {358 return359 }360 cons := g.Stack.Pop().(*base.Constant)361 holder := g.Stack.Peek().(base.ConstantHolder)362 err := holder.AcceptConstant(cons)363 if err != nil {364 g.AddError(err)365 }366}367func (g *GengineParserListener) EnterStringLiteral(ctx *parser.StringLiteralContext) {}368func (g *GengineParserListener) ExitStringLiteral(ctx *parser.StringLiteralContext) {369 if len(g.ParseErrors) > 0 {370 return371 }372 holder := g.Stack.Peek().(base.StringHolder)373 text := ctx.GetText()374 txt := strings.Trim(text, "\"")375 if reflect.TypeOf(holder).String() == "*base.MapVar" {376 if txt == "" {377 g.AddError(errors.New("MAP key should not be null string"))378 }379 }380 err := holder.AcceptString(txt)381 if err != nil {382 g.AddError(err)383 }384}385func (g *GengineParserListener) EnterBooleanLiteral(ctx *parser.BooleanLiteralContext) {}386func (g *GengineParserListener) ExitBooleanLiteral(ctx *parser.BooleanLiteralContext) {387 if len(g.ParseErrors) > 0 {388 return389 }390 cons := g.Stack.Peek().(*base.Constant)391 b, e := strconv.ParseBool(ctx.GetText())392 if e != nil {393 g.AddError(e)394 return395 }396 cons.ConstantValue = reflect.ValueOf(b)397}398func (g *GengineParserListener) EnterRealLiteral(ctx *parser.RealLiteralContext) {}399func (g *GengineParserListener) ExitRealLiteral(ctx *parser.RealLiteralContext) {400 if len(g.ParseErrors) > 0 {401 return402 }403 cons := g.Stack.Peek().(*base.Constant)404 flo, err := strconv.ParseFloat(ctx.GetText(), 64)405 if err != nil {406 g.AddError(errors.New(fmt.Sprintf("string to float conversion error. String is not real type '%s'", ctx.GetText())))407 return408 }409 cons.ConstantValue = reflect.ValueOf(flo)410}411func (g *GengineParserListener) EnterIfStmt(ctx *parser.IfStmtContext) {412 if len(g.ParseErrors) > 0 {413 return414 }415 ifStmt := &base.IfStmt{}416 g.Stack.Push(ifStmt)417}418func (g *GengineParserListener) ExitIfStmt(ctx *parser.IfStmtContext) {419 if len(g.ParseErrors) > 0 {420 return421 }422 ifStmt := g.Stack.Pop().(*base.IfStmt)423 statement := g.Stack.Peek().(*base.Statement)424 statement.IfStmt = ifStmt425}426func (g *GengineParserListener) EnterStatement(ctx *parser.StatementContext) {427 if len(g.ParseErrors) > 0 {428 return429 }430 statement := &base.Statement{}431 g.Stack.Push(statement)432}433func (g *GengineParserListener) ExitStatement(ctx *parser.StatementContext) {434 if len(g.ParseErrors) > 0 {435 return436 }437 statement := g.Stack.Pop().(*base.Statement)438 statements := g.Stack.Peek().(*base.Statements)439 statements.StatementList = append(statements.StatementList, statement)440}441func (g *GengineParserListener) EnterStatements(ctx *parser.StatementsContext) {442 if len(g.ParseErrors) > 0 {443 return444 }445 statements := &base.Statements{446 StatementList: make([]*base.Statement, 0),447 }448 g.Stack.Push(statements)449}450func (g *GengineParserListener) ExitStatements(ctx *parser.StatementsContext) {451 if len(g.ParseErrors) > 0 {452 return453 }454 statements := g.Stack.Pop().(*base.Statements)455 holder := g.Stack.Peek().(base.StatementsHolder)456 err := holder.AcceptStatements(statements)457 if err != nil {458 g.AddError(err)459 }460}461func (g *GengineParserListener) EnterAssignOperator(ctx *parser.AssignOperatorContext) {}462func (g *GengineParserListener) ExitAssignOperator(ctx *parser.AssignOperatorContext) {463 if len(g.ParseErrors) > 0 {464 return465 }466 expr := g.Stack.Peek().(*base.Assignment)467 expr.AssignOperator = ctx.GetText()468}469func (g *GengineParserListener) EnterElseIfStmt(ctx *parser.ElseIfStmtContext) {470 if len(g.ParseErrors) > 0 {471 return472 }473 elseIfStmt := &base.ElseIfStmt{}474 g.Stack.Push(elseIfStmt)475}476func (g *GengineParserListener) ExitElseIfStmt(ctx *parser.ElseIfStmtContext) {477 if len(g.ParseErrors) > 0 {478 return479 }480 elseIfStmt := g.Stack.Pop().(*base.ElseIfStmt)481 ifStmt := g.Stack.Peek().(*base.IfStmt)482 ifStmt.ElseIfStmtList = append(ifStmt.ElseIfStmtList, elseIfStmt)483}484func (g *GengineParserListener) EnterElseStmt(ctx *parser.ElseStmtContext) {485 if len(g.ParseErrors) > 0 {486 return487 }488 elseStmt := &base.ElseStmt{}489 g.Stack.Push(elseStmt)490}491func (g *GengineParserListener) ExitElseStmt(ctx *parser.ElseStmtContext) {492 if len(g.ParseErrors) > 0 {493 return494 }495 elseStmt := g.Stack.Pop().(*base.ElseStmt)496 ifStmt := g.Stack.Peek().(*base.IfStmt)497 ifStmt.ElseStmt = elseStmt498}499func (g *GengineParserListener) ExitInteger(ctx *parser.IntegerContext) {500 if len(g.ParseErrors) > 0 {501 return502 }503 val, err := strconv.ParseInt(ctx.GetText(), 10, 64)504 if err != nil {505 g.AddError(err)506 return507 }508 holder := g.Stack.Peek().(base.IntegerHolder)509 err = holder.AcceptInteger(val)510 if err != nil {511 g.AddError(err)512 }513}514func (g *GengineParserListener) EnterInteger(ctx *parser.IntegerContext) {}515func (g *GengineParserListener) EnterAtName(ctx *parser.AtNameContext) {}516func (g *GengineParserListener) ExitAtName(ctx *parser.AtNameContext) {517 if len(g.ParseErrors) > 0 {518 return519 }520 holder := g.Stack.Peek().(base.AtNameHolder)521 err := holder.AcceptName(strings.ReplaceAll(g.ruleName, "\"", ""))522 if err != nil {523 g.AddError(err)524 }525}526func (g *GengineParserListener) EnterAtDesc(ctx *parser.AtDescContext) {}527func (g *GengineParserListener) ExitAtDesc(ctx *parser.AtDescContext) {528 if len(g.ParseErrors) > 0 {529 return530 }531 holder := g.Stack.Peek().(base.AtDescHolder)532 err := holder.AcceptDesc(strings.ReplaceAll(g.ruleDescription, "\"", ""))533 if err != nil {534 g.AddError(err)535 }536}537func (g *GengineParserListener) EnterAtId(ctx *parser.AtIdContext) {}538func (g *GengineParserListener) ExitAtId(ctx *parser.AtIdContext) {539 if len(g.ParseErrors) > 0 {540 return541 }542 holder := g.Stack.Peek().(base.AtIdHolder)543 i, e := strconv.ParseInt(strings.Trim(g.ruleName, " "), 10, 64)544 if e != nil {545 err := holder.AcceptId(0)546 if err != nil {547 g.AddError(err)548 }549 return550 }551 err := holder.AcceptId(i)552 if err != nil {553 g.AddError(err)554 }555}556func (g *GengineParserListener) EnterAtSal(ctx *parser.AtSalContext) {}557func (g *GengineParserListener) ExitAtSal(ctx *parser.AtSalContext) {558 if len(g.ParseErrors) > 0 {559 return560 }561 holder := g.Stack.Peek().(base.AtSalienceHolder)562 err := holder.AcceptSalience(g.salience)563 if err != nil {564 g.AddError(err)565 }566}567func (g *GengineParserListener) EnterMapVar(ctx *parser.MapVarContext) {568 if len(g.ParseErrors) > 0 {569 return570 }571 mapVar := &base.MapVar{}572 g.Stack.Push(mapVar)573}574func (g *GengineParserListener) ExitMapVar(ctx *parser.MapVarContext) {575 if len(g.ParseErrors) > 0 {576 return577 }578 mapVar := g.Stack.Pop().(*base.MapVar)579 holder := g.Stack.Peek().(base.MapVarHolder)580 err := holder.AcceptMapVar(mapVar)581 if err != nil {582 g.AddError(err)583 }584}585func (g *GengineParserListener) EnterReturnStmt(c *parser.ReturnStmtContext) {586 if len(g.ParseErrors) > 0 {587 return588 }589 rs := &base.ReturnStatement{}590 g.Stack.Push(rs)591}592func (g *GengineParserListener) ExitReturnStmt(c *parser.ReturnStmtContext) {593 if len(g.ParseErrors) > 0 {594 return595 }596 rs := g.Stack.Pop().(*base.ReturnStatement)597 stats := g.Stack.Peek().(*base.Statements)598 stats.ReturnStatement = rs599}...
parser.go
Source:parser.go
...40 p.registerInfix(token.GT, p.parseInfixExpression)41 p.registerInfix(token.LPAREN, p.parseCallExpression)42 return p43}44func (p *Parser) Errors() []string {45 return p.errors46}47func (p *Parser) peekError(t token.TokenType) {48 msg := fmt.Sprintf("expected next token to be %s, got %s instead", t, p.peekToken.Type)49 p.errors = append(p.errors, msg)50}51func (p *Parser) nextToken() {52 p.curToken = p.peekToken53 p.peekToken = p.l.NextToken()54}55func (p *Parser) ParseProgram() *ast.Program {56 program := &ast.Program{}57 program.Statements = []ast.Statement{}58 for p.curToken.Type != token.EOF {...
regexp.go
Source:regexp.go
1package parser2import (3 "bytes"4 "fmt"5 "strconv"6)7type _RegExp_parser struct {8 str string9 length int10 chr rune // The current character11 chrOffset int // The offset of current character12 offset int // The offset after current character (may be greater than 1)13 errors []error14 invalid bool // The input is an invalid JavaScript RegExp15 goRegexp *bytes.Buffer16}17// TransformRegExp transforms a JavaScript pattern into a Go "regexp" pattern.18//19// re2 (Go) cannot do backtracking, so the presence of a lookahead (?=) (?!) or20// backreference (\1, \2, ...) will cause an error.21//22// re2 (Go) has a different definition for \s: [\t\n\f\r ].23// The JavaScript definition, on the other hand, also includes \v, Unicode "Separator, Space", etc.24//25// If the pattern is invalid (not valid even in JavaScript), then this function26// returns the empty string and an error.27//28// If the pattern is valid, but incompatible (contains a lookahead or backreference),29// then this function returns the transformation (a non-empty string) AND an error.30func TransformRegExp(pattern string) (string, error) {31 if pattern == "" {32 return "", nil33 }34 // TODO If without \, if without (?=, (?!, then another shortcut35 parser := _RegExp_parser{36 str: pattern,37 length: len(pattern),38 goRegexp: bytes.NewBuffer(make([]byte, 0, 3*len(pattern)/2)),39 }40 parser.read() // Pull in the first character41 parser.scan()42 var err error43 if len(parser.errors) > 0 {44 err = parser.errors[0]45 }46 if parser.invalid {47 return "", err48 }49 // Might not be re2 compatible, but is still a valid JavaScript RegExp50 return parser.goRegexp.String(), err51}52func (self *_RegExp_parser) scan() {53 for self.chr != -1 {54 switch self.chr {55 case '\\':56 self.read()57 self.scanEscape(false)58 case '(':59 self.pass()60 self.scanGroup()61 case '[':62 self.pass()63 self.scanBracket()64 case ')':65 self.error(-1, "Unmatched ')'")66 self.invalid = true67 self.pass()68 default:69 self.pass()70 }71 }72}73// (...)74func (self *_RegExp_parser) scanGroup() {75 str := self.str[self.chrOffset:]76 if len(str) > 1 { // A possibility of (?= or (?!77 if str[0] == '?' {78 if str[1] == '=' || str[1] == '!' {79 self.error(-1, "re2: Invalid (%s) <lookahead>", self.str[self.chrOffset:self.chrOffset+2])80 }81 }82 }83 for self.chr != -1 && self.chr != ')' {84 switch self.chr {85 case '\\':86 self.read()87 self.scanEscape(false)88 case '(':89 self.pass()90 self.scanGroup()91 case '[':92 self.pass()93 self.scanBracket()94 default:95 self.pass()96 continue97 }98 }99 if self.chr != ')' {100 self.error(-1, "Unterminated group")101 self.invalid = true102 return103 }104 self.pass()105}106// [...]107func (self *_RegExp_parser) scanBracket() {108 for self.chr != -1 {109 if self.chr == ']' {110 break111 } else if self.chr == '\\' {112 self.read()113 self.scanEscape(true)114 continue115 }116 self.pass()117 }118 if self.chr != ']' {119 self.error(-1, "Unterminated character class")120 self.invalid = true121 return122 }123 self.pass()124}125// \...126func (self *_RegExp_parser) scanEscape(inClass bool) {127 offset := self.chrOffset128 var length, base uint32129 switch self.chr {130 case '0', '1', '2', '3', '4', '5', '6', '7':131 var value int64132 size := 0133 for {134 digit := int64(digitValue(self.chr))135 if digit >= 8 {136 // Not a valid digit137 break138 }139 value = value*8 + digit140 self.read()141 size += 1142 }143 if size == 1 { // The number of characters read144 _, err := self.goRegexp.Write([]byte{'\\', byte(value) + '0'})145 if err != nil {146 self.errors = append(self.errors, err)147 }148 if value != 0 {149 // An invalid backreference150 self.error(-1, "re2: Invalid \\%d <backreference>", value)151 }152 return153 }154 tmp := []byte{'\\', 'x', '0', 0}155 if value >= 16 {156 tmp = tmp[0:2]157 } else {158 tmp = tmp[0:3]159 }160 tmp = strconv.AppendInt(tmp, value, 16)161 _, err := self.goRegexp.Write(tmp)162 if err != nil {163 self.errors = append(self.errors, err)164 }165 return166 case '8', '9':167 size := 0168 for {169 digit := digitValue(self.chr)170 if digit >= 10 {171 // Not a valid digit172 break173 }174 self.read()175 size += 1176 }177 err := self.goRegexp.WriteByte('\\')178 if err != nil {179 self.errors = append(self.errors, err)180 }181 _, err = self.goRegexp.WriteString(self.str[offset:self.chrOffset])182 if err != nil {183 self.errors = append(self.errors, err)184 }185 self.error(-1, "re2: Invalid \\%s <backreference>", self.str[offset:self.chrOffset])186 return187 case 'x':188 self.read()189 length, base = 2, 16190 case 'u':191 self.read()192 length, base = 4, 16193 case 'b':194 if inClass {195 _, err := self.goRegexp.Write([]byte{'\\', 'x', '0', '8'})196 if err != nil {197 self.errors = append(self.errors, err)198 }199 self.read()200 return201 }202 fallthrough203 case 'B':204 fallthrough205 case 'd', 'D', 's', 'S', 'w', 'W':206 // This is slightly broken, because ECMAScript207 // includes \v in \s, \S, while re2 does not208 fallthrough209 case '\\':210 fallthrough211 case 'f', 'n', 'r', 't', 'v':212 err := self.goRegexp.WriteByte('\\')213 if err != nil {214 self.errors = append(self.errors, err)215 }216 self.pass()217 return218 case 'c':219 self.read()220 var value int64221 if 'a' <= self.chr && self.chr <= 'z' {222 value = int64(self.chr) - 'a' + 1223 } else if 'A' <= self.chr && self.chr <= 'Z' {224 value = int64(self.chr) - 'A' + 1225 } else {226 err := self.goRegexp.WriteByte('c')227 if err != nil {228 self.errors = append(self.errors, err)229 }230 return231 }232 tmp := []byte{'\\', 'x', '0', 0}233 if value >= 16 {234 tmp = tmp[0:2]235 } else {236 tmp = tmp[0:3]237 }238 tmp = strconv.AppendInt(tmp, value, 16)239 _, err := self.goRegexp.Write(tmp)240 if err != nil {241 self.errors = append(self.errors, err)242 }243 self.read()244 return245 default:246 // $ is an identifier character, so we have to have247 // a special case for it here248 if self.chr == '$' || !isIdentifierPart(self.chr) {249 // A non-identifier character needs escaping250 err := self.goRegexp.WriteByte('\\')251 if err != nil {252 self.errors = append(self.errors, err)253 }254 } else {255 // Unescape the character for re2256 }257 self.pass()258 return259 }260 // Otherwise, we're a \u.... or \x...261 valueOffset := self.chrOffset262 var value uint32263 {264 length := length265 for ; length > 0; length-- {266 digit := uint32(digitValue(self.chr))267 if digit >= base {268 // Not a valid digit269 goto skip270 }271 value = value*base + digit272 self.read()273 }274 }275 if length == 4 {276 _, err := self.goRegexp.Write([]byte{277 '\\',278 'x',279 '{',280 self.str[valueOffset+0],281 self.str[valueOffset+1],282 self.str[valueOffset+2],283 self.str[valueOffset+3],284 '}',285 })286 if err != nil {287 self.errors = append(self.errors, err)288 }289 } else if length == 2 {290 _, err := self.goRegexp.Write([]byte{291 '\\',292 'x',293 self.str[valueOffset+0],294 self.str[valueOffset+1],295 })296 if err != nil {297 self.errors = append(self.errors, err)298 }299 } else {300 // Should never, ever get here...301 self.error(-1, "re2: Illegal branch in scanEscape")302 goto skip303 }304 return305skip:306 _, err := self.goRegexp.WriteString(self.str[offset:self.chrOffset])307 if err != nil {308 self.errors = append(self.errors, err)309 }310}311func (self *_RegExp_parser) pass() {312 if self.chr != -1 {313 _, err := self.goRegexp.WriteRune(self.chr)314 if err != nil {315 self.errors = append(self.errors, err)316 }317 }318 self.read()319}320// TODO Better error reporting, use the offset, etc.321func (self *_RegExp_parser) error(offset int, msg string, msgValues ...interface{}) error {322 err := fmt.Errorf(msg, msgValues...)323 self.errors = append(self.errors, err)324 return err325}...
Errors
Using AI Code Generation
1import (2func main() {3 f, err := parser.ParseFile(fset, "1.go", nil, parser.ParseComments)4 if err != nil {5 }6 fmt.Println(f)7}81.go:3:1: expected 'package', found 'import'91.go:4:1: expected 'package', found 'import'101.go:5:1: expected 'package', found 'import'111.go:6:1: expected 'package', found 'import'121.go:7:1: expected 'package', found 'import'131.go:8:1: expected 'package', found 'import'141.go:9:1: expected 'package', found 'import'151.go:10:1: expected 'package', found 'import'161.go:11:1: expected 'package', found 'import'171.go:12:1: expected 'package', found 'import'181.go:13:1: expected 'package', found 'import'191.go:14:1: expected 'package', found 'import'201.go:15:1: expected 'package', found 'import'211.go:16:1: expected 'package', found 'import'221.go:17:1: expected 'package', found 'import'231.go:18:1: expected 'package', found 'import'241.go:19:1: expected 'package', found 'import'251.go:20:1: expected 'package', found 'import'261.go:21:1: expected 'package', found 'import'271.go:22:1: expected 'package', found 'import'281.go:23:1: expected 'package', found 'import'291.go:24:1: expected 'package', found 'import'301.go:25:1: expected 'package', found 'import'311.go:26:1: expected 'package', found 'import'321.go:27:1: expected 'package', found 'import'331.go:28:1: expected 'package', found 'import'341.go:29:1: expected 'package', found 'import'
Errors
Using AI Code Generation
1import (2func main() {3 p := parser.New("1.go")4 p.Parse()5 fmt.Println(p.Errors())6}7import (8type Parser struct {9}10func New(fileName string) *Parser {11 return &Parser{fileName: fileName}12}13func (p *Parser) Parse() {14 f, err := os.Open(p.fileName)15 if err != nil {16 p.errors = append(p.errors, fmt.Sprintf("Error opening file: %s", err))17 }18 defer f.Close()19 r := bufio.NewReader(f)20 for {21 line, err := r.ReadString('22 if err != nil {23 if err == io.EOF {24 }25 p.errors = append(p.errors, fmt.Sprintf("Error reading file: %s", err))26 }27 p.parseLine(line)28 }29}30func (p *Parser) parseLine(line string) {31 if strings.Contains(line, "code to use Errors method of parser class to get the errors") {32 p.errors = append(p.errors, fmt.Sprintf("Found error in line: %s", line))33 }34}35func (p *Parser) Errors() []string {36}37import (38func TestParser(t *testing.T) {39 p := New("1.go")40 p.Parse()41 if len(p.Errors()) != 4 {42 t.Errorf("Expected 4 errors, got %d", len(p.Errors()))43 }44}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!