How to use checkDupConsts method of compiler Package

Best Syzkaller code snippet using compiler.checkDupConsts

check.go

Source:check.go Github

copy

Full Screen

...25 comp.checkRecursion()26 comp.checkLenTargets()27 comp.checkConstructors()28 comp.checkVarlens()29 comp.checkDupConsts()30}31func (comp *compiler) checkDirectives() {32 includes := make(map[string]bool)33 incdirs := make(map[string]bool)34 defines := make(map[string]bool)35 for _, decl := range comp.desc.Nodes {36 switch n := decl.(type) {37 case *ast.Include:38 name := n.File.Value39 path := n.Pos.File + "/" + name40 if includes[path] {41 comp.error(n.Pos, "duplicate include %q", name)42 }43 includes[path] = true44 case *ast.Incdir:45 name := n.Dir.Value46 path := n.Pos.File + "/" + name47 if incdirs[path] {48 comp.error(n.Pos, "duplicate incdir %q", name)49 }50 incdirs[path] = true51 case *ast.Define:52 name := n.Name.Name53 path := n.Pos.File + "/" + name54 if defines[path] {55 comp.error(n.Pos, "duplicate define %v", name)56 }57 defines[path] = true58 }59 }60}61func (comp *compiler) checkNames() {62 calls := make(map[string]*ast.Call)63 for _, decl := range comp.desc.Nodes {64 switch n := decl.(type) {65 case *ast.Resource, *ast.Struct, *ast.TypeDef:66 pos, typ, name := decl.Info()67 if reservedName[name] {68 comp.error(pos, "%v uses reserved name %v", typ, name)69 continue70 }71 if builtinTypes[name] != nil {72 comp.error(pos, "%v name %v conflicts with builtin type", typ, name)73 continue74 }75 if prev := comp.resources[name]; prev != nil {76 comp.error(pos, "type %v redeclared, previously declared as resource at %v",77 name, prev.Pos)78 continue79 }80 if prev := comp.typedefs[name]; prev != nil {81 comp.error(pos, "type %v redeclared, previously declared as type alias at %v",82 name, prev.Pos)83 continue84 }85 if prev := comp.structs[name]; prev != nil {86 _, typ, _ := prev.Info()87 comp.error(pos, "type %v redeclared, previously declared as %v at %v",88 name, typ, prev.Pos)89 continue90 }91 switch n := decl.(type) {92 case *ast.Resource:93 comp.resources[name] = n94 case *ast.TypeDef:95 comp.typedefs[name] = n96 case *ast.Struct:97 comp.structs[name] = n98 }99 case *ast.IntFlags:100 name := n.Name.Name101 if name == "_" {102 continue103 }104 if reservedName[name] {105 comp.error(n.Pos, "flags uses reserved name %v", name)106 continue107 }108 if prev := comp.intFlags[name]; prev != nil {109 comp.error(n.Pos, "flags %v redeclared, previously declared at %v",110 name, prev.Pos)111 continue112 }113 comp.intFlags[name] = n114 case *ast.StrFlags:115 name := n.Name.Name116 if reservedName[name] {117 comp.error(n.Pos, "string flags uses reserved name %v", name)118 continue119 }120 if prev := comp.strFlags[name]; prev != nil {121 comp.error(n.Pos, "string flags %v redeclared, previously declared at %v",122 name, prev.Pos)123 continue124 }125 comp.strFlags[name] = n126 case *ast.Call:127 name := n.Name.Name128 if prev := calls[name]; prev != nil {129 comp.error(n.Pos, "syscall %v redeclared, previously declared at %v",130 name, prev.Pos)131 }132 calls[name] = n133 }134 }135}136func (comp *compiler) checkFields() {137 for _, decl := range comp.desc.Nodes {138 switch n := decl.(type) {139 case *ast.Struct:140 _, typ, name := n.Info()141 comp.checkStructFields(n, typ, name)142 case *ast.TypeDef:143 if n.Struct != nil {144 _, typ, _ := n.Struct.Info()145 comp.checkStructFields(n.Struct, "template "+typ, n.Name.Name)146 }147 case *ast.Call:148 name := n.Name.Name149 comp.checkFieldGroup(n.Args, "argument", "syscall "+name)150 if len(n.Args) > prog.MaxArgs {151 comp.error(n.Pos, "syscall %v has %v arguments, allowed maximum is %v",152 name, len(n.Args), prog.MaxArgs)153 }154 }155 }156}157func (comp *compiler) checkStructFields(n *ast.Struct, typ, name string) {158 comp.checkFieldGroup(n.Fields, "field", typ+" "+name)159 if len(n.Fields) < 1 {160 comp.error(n.Pos, "%v %v has no fields, need at least 1 field", typ, name)161 }162}163func (comp *compiler) checkFieldGroup(fields []*ast.Field, what, ctx string) {164 existing := make(map[string]bool)165 for _, f := range fields {166 fn := f.Name.Name167 if fn == prog.ParentRef || fn == prog.SyscallRef {168 comp.error(f.Pos, "reserved %v name %v in %v", what, fn, ctx)169 }170 if existing[fn] {171 comp.error(f.Pos, "duplicate %v %v in %v", what, fn, ctx)172 }173 existing[fn] = true174 }175}176const argBase = "BASE"177func (comp *compiler) checkTypedefs() {178 for _, decl := range comp.desc.Nodes {179 switch n := decl.(type) {180 case *ast.TypeDef:181 if len(n.Args) == 0 {182 // Non-template types are fully typed, so we check them ahead of time.183 err0 := comp.errors184 comp.checkType(checkCtx{}, n.Type, checkIsTypedef)185 if err0 != comp.errors {186 // To not produce confusing errors on broken type usage.187 delete(comp.typedefs, n.Name.Name)188 }189 } else {190 // For templates we only do basic checks of arguments.191 names := make(map[string]bool)192 for i, arg := range n.Args {193 if arg.Name == argBase && i != len(n.Args)-1 {194 comp.error(arg.Pos, "type argument BASE must be the last argument")195 }196 if names[arg.Name] {197 comp.error(arg.Pos, "duplicate type argument %v", arg.Name)198 }199 names[arg.Name] = true200 for _, c := range arg.Name {201 if c >= 'A' && c <= 'Z' ||202 c >= '0' && c <= '9' ||203 c == '_' {204 continue205 }206 comp.error(arg.Pos, "type argument %v must be ALL_CAPS",207 arg.Name)208 break209 }210 }211 }212 }213 }214}215func (comp *compiler) checkTypes() {216 for _, decl := range comp.desc.Nodes {217 switch n := decl.(type) {218 case *ast.Resource:219 comp.checkType(checkCtx{}, n.Base, checkIsResourceBase)220 case *ast.Struct:221 comp.checkStruct(checkCtx{}, n)222 case *ast.Call:223 comp.checkCall(n)224 }225 }226}227func (comp *compiler) checkTypeValues() {228 for _, decl := range comp.desc.Nodes {229 switch decl.(type) {230 case *ast.Call, *ast.Struct, *ast.Resource, *ast.TypeDef:231 comp.foreachType(decl, func(t *ast.Type, desc *typeDesc,232 args []*ast.Type, base prog.IntTypeCommon) {233 if desc.CheckConsts != nil {234 desc.CheckConsts(comp, t, args, base)235 }236 for i, arg := range args {237 if check := desc.Args[i].Type.CheckConsts; check != nil {238 check(comp, arg)239 }240 }241 })242 }243 }244}245func (comp *compiler) checkAttributeValues() {246 for _, decl := range comp.desc.Nodes {247 switch n := decl.(type) {248 case *ast.Struct:249 for _, attr := range n.Attrs {250 desc := structOrUnionAttrs(n)[attr.Ident]251 if desc.CheckConsts != nil {252 desc.CheckConsts(comp, n, attr)253 }254 }255 }256 }257}258func (comp *compiler) checkLenTargets() {259 warned := make(map[string]bool)260 for _, decl := range comp.desc.Nodes {261 switch n := decl.(type) {262 case *ast.Call:263 for _, arg := range n.Args {264 checked := make(map[string]bool)265 parents := []parentDesc{{fields: n.Args}}266 comp.checkLenType(arg.Type, arg.Type, parents, checked, warned, true)267 }268 }269 }270}271type parentDesc struct {272 name string273 fields []*ast.Field274}275func parentTargetName(s *ast.Struct) string {276 parentName := s.Name.Name277 if pos := strings.IndexByte(parentName, '['); pos != -1 {278 // For template parents name is "struct_name[ARG1, ARG2]", strip the part after '['.279 parentName = parentName[:pos]280 }281 return parentName282}283func (comp *compiler) checkLenType(t0, t *ast.Type, parents []parentDesc,284 checked, warned map[string]bool, isArg bool) {285 desc := comp.getTypeDesc(t)286 if desc == typeStruct {287 s := comp.structs[t.Ident]288 // Prune recursion, can happen even on correct tree via opt pointers.289 if checked[s.Name.Name] {290 return291 }292 checked[s.Name.Name] = true293 fields := s.Fields294 if s.IsUnion {295 fields = nil296 }297 parentName := parentTargetName(s)298 parents = append(parents, parentDesc{name: parentName, fields: fields})299 for _, fld := range s.Fields {300 comp.checkLenType(fld.Type, fld.Type, parents, checked, warned, false)301 }302 warned[parentName] = true303 return304 }305 _, args, _ := comp.getArgsBase(t, isArg)306 for i, arg := range args {307 argDesc := desc.Args[i]308 if argDesc.Type == typeArgLenTarget {309 comp.checkLenTarget(arg, t0, t, parents, warned)310 } else if argDesc.Type == typeArgType {311 comp.checkLenType(t0, arg, parents, checked, warned, argDesc.IsArg)312 }313 }314}315func (comp *compiler) checkLenTarget(arg, t0, t *ast.Type, parents []parentDesc, warned map[string]bool) {316 targets := append([]*ast.Type{arg}, arg.Colon...)317 for i, target := range targets {318 if target.Ident == prog.ParentRef && len(targets) != 1 {319 comp.error(target.Pos, "%v can't be part of path expressions", prog.ParentRef)320 return321 }322 if target.Ident == prog.SyscallRef {323 if i != 0 {324 comp.error(target.Pos, "syscall can't be in the middle of path expressions")325 return326 }327 if len(targets) == 1 {328 comp.error(targets[0].Pos, "no argument name after syscall reference")329 return330 }331 }332 }333 comp.checkLenTargetRec(t0, t, targets, parents, warned)334}335func (comp *compiler) checkLenTargetRec(t0, t *ast.Type, targets []*ast.Type,336 parents []parentDesc, warned map[string]bool) {337 if len(targets) == 0 {338 return339 }340 target := targets[0]341 targets = targets[1:]342 fields := parents[len(parents)-1].fields343 for _, fld := range fields {344 if target.Ident != fld.Name.Name {345 continue346 }347 if fld.Type == t0 {348 comp.error(target.Pos, "%v target %v refers to itself", t.Ident, target.Ident)349 return350 }351 if len(targets) == 0 {352 if t.Ident == "len" {353 typ, desc := comp.derefPointers(fld.Type)354 if desc == typeArray && comp.isVarlen(typ.Args[0]) {355 // We can reach the same struct multiple times starting from different356 // syscall arguments. Warn only once.357 if !warned[parents[len(parents)-1].name] {358 comp.warning(target.Pos, "len target %v refer to an array with"+359 " variable-size elements (do you mean bytesize?)",360 target.Ident)361 }362 }363 }364 return365 }366 typ, desc := comp.derefPointers(fld.Type)367 if desc != typeStruct {368 comp.error(target.Pos, "%v path %v does not refer to a struct", t.Ident, target.Ident)369 return370 }371 s := comp.structs[typ.Ident]372 if s.IsUnion {373 comp.error(target.Pos, "%v path %v does not refer to a struct", t.Ident, target.Ident)374 return375 }376 parents = append(parents, parentDesc{name: parentTargetName(s), fields: s.Fields})377 comp.checkLenTargetRec(t0, t, targets, parents, warned)378 return379 }380 for pi := len(parents) - 1; pi >= 0; pi-- {381 parent := parents[pi]382 if parent.name != "" && (parent.name == target.Ident || target.Ident == prog.ParentRef) ||383 parent.name == "" && target.Ident == prog.SyscallRef {384 if len(targets) == 0 {385 if t.Ident == "offsetof" {386 comp.error(target.Pos, "%v must refer to fields", t.Ident)387 return388 }389 } else {390 parents1 := make([]parentDesc, pi+1)391 copy(parents1, parents[:pi+1])392 comp.checkLenTargetRec(t0, t, targets, parents1, warned)393 }394 return395 }396 }397 comp.error(target.Pos, "%v target %v does not exist", t.Ident, target.Ident)398}399func CollectUnused(desc *ast.Description, target *targets.Target, eh ast.ErrorHandler) ([]ast.Node, error) {400 comp := createCompiler(desc, target, eh)401 comp.typecheck()402 if comp.errors > 0 {403 return nil, errors.New("typecheck failed")404 }405 nodes := comp.collectUnused()406 if comp.errors > 0 {407 return nil, errors.New("collectUnused failed")408 }409 return nodes, nil410}411func (comp *compiler) collectUnused() []ast.Node {412 var unused []ast.Node413 comp.used, _, _ = comp.collectUsed(false)414 structs, flags, strflags := comp.collectUsed(true)415 note := func(n ast.Node) {416 if pos, _, _ := n.Info(); pos.Builtin() {417 return418 }419 unused = append(unused, n)420 }421 for name, n := range comp.intFlags {422 if !flags[name] {423 note(n)424 }425 }426 for name, n := range comp.strFlags {427 if !strflags[name] {428 note(n)429 }430 }431 for name, n := range comp.resources {432 if !structs[name] {433 note(n)434 }435 }436 for name, n := range comp.structs {437 if !structs[name] {438 note(n)439 }440 }441 for name, n := range comp.typedefs {442 if !comp.usedTypedefs[name] {443 note(n)444 }445 }446 return unused447}448func (comp *compiler) collectUsed(all bool) (structs, flags, strflags map[string]bool) {449 structs = make(map[string]bool)450 flags = make(map[string]bool)451 strflags = make(map[string]bool)452 for _, decl := range comp.desc.Nodes {453 switch n := decl.(type) {454 case *ast.Call:455 if !all && n.NR == ^uint64(0) {456 break457 }458 for _, arg := range n.Args {459 comp.collectUsedType(structs, flags, strflags, arg.Type, true)460 }461 if n.Ret != nil {462 comp.collectUsedType(structs, flags, strflags, n.Ret, true)463 }464 }465 }466 return467}468func (comp *compiler) collectUsedType(structs, flags, strflags map[string]bool, t *ast.Type, isArg bool) {469 desc := comp.getTypeDesc(t)470 if desc == typeResource {471 r := comp.resources[t.Ident]472 for r != nil && !structs[r.Name.Name] {473 structs[r.Name.Name] = true474 r = comp.resources[r.Base.Ident]475 }476 return477 }478 if desc == typeStruct {479 if structs[t.Ident] {480 return481 }482 structs[t.Ident] = true483 s := comp.structs[t.Ident]484 for _, fld := range s.Fields {485 comp.collectUsedType(structs, flags, strflags, fld.Type, false)486 }487 return488 }489 if desc == typeFlags {490 flags[t.Args[0].Ident] = true491 return492 }493 if desc == typeString {494 if len(t.Args) != 0 && t.Args[0].Ident != "" {495 strflags[t.Args[0].Ident] = true496 }497 return498 }499 _, args, _ := comp.getArgsBase(t, isArg)500 for i, arg := range args {501 if desc.Args[i].Type == typeArgType {502 comp.collectUsedType(structs, flags, strflags, arg, desc.Args[i].IsArg)503 }504 }505}506func (comp *compiler) checkUnused() {507 for _, n := range comp.collectUnused() {508 pos, typ, name := n.Info()509 comp.error(pos, fmt.Sprintf("unused %v %v", typ, name))510 }511}512type structDir struct {513 Struct string514 Dir prog.Dir515}516func (comp *compiler) checkConstructors() {517 ctors := make(map[string]bool) // resources for which we have ctors518 checked := make(map[structDir]bool)519 for _, decl := range comp.desc.Nodes {520 switch n := decl.(type) {521 case *ast.Call:522 for _, arg := range n.Args {523 comp.checkTypeCtors(arg.Type, prog.DirIn, true, ctors, checked)524 }525 if n.Ret != nil {526 comp.checkTypeCtors(n.Ret, prog.DirOut, true, ctors, checked)527 }528 }529 }530 for _, decl := range comp.desc.Nodes {531 switch n := decl.(type) {532 case *ast.Resource:533 name := n.Name.Name534 if !ctors[name] && comp.used[name] {535 comp.error(n.Pos, "resource %v can't be created"+536 " (never mentioned as a syscall return value or output argument/field)",537 name)538 }539 }540 }541}542func (comp *compiler) checkTypeCtors(t *ast.Type, dir prog.Dir, isArg bool,543 ctors map[string]bool, checked map[structDir]bool) {544 desc := comp.getTypeDesc(t)545 if desc == typeResource {546 // TODO(dvyukov): consider changing this to "dir == prog.DirOut".547 // We have few questionable cases where resources can be created548 // only by inout struct fields. These structs should be split549 // into two different structs: one is in and second is out.550 // But that will require attaching dir to individual fields.551 if dir != prog.DirIn {552 r := comp.resources[t.Ident]553 for r != nil && !ctors[r.Name.Name] {554 ctors[r.Name.Name] = true555 r = comp.resources[r.Base.Ident]556 }557 }558 return559 }560 if desc == typeStruct {561 s := comp.structs[t.Ident]562 name := s.Name.Name563 key := structDir{name, dir}564 if checked[key] {565 return566 }567 checked[key] = true568 for _, fld := range s.Fields {569 comp.checkTypeCtors(fld.Type, dir, false, ctors, checked)570 }571 return572 }573 if desc == typePtr {574 dir = genDir(t.Args[0])575 }576 _, args, _ := comp.getArgsBase(t, isArg)577 for i, arg := range args {578 if desc.Args[i].Type == typeArgType {579 comp.checkTypeCtors(arg, dir, desc.Args[i].IsArg, ctors, checked)580 }581 }582}583func (comp *compiler) checkRecursion() {584 checked := make(map[string]bool)585 for _, decl := range comp.desc.Nodes {586 switch n := decl.(type) {587 case *ast.Resource:588 comp.checkResourceRecursion(n)589 case *ast.Struct:590 var path []pathElem591 comp.checkStructRecursion(checked, n, path)592 }593 }594}595func (comp *compiler) checkResourceRecursion(n *ast.Resource) {596 var seen []string597 for n != nil {598 if arrayContains(seen, n.Name.Name) {599 chain := ""600 for _, r := range seen {601 chain += r + "->"602 }603 chain += n.Name.Name604 comp.error(n.Pos, "recursive resource %v", chain)605 return606 }607 seen = append(seen, n.Name.Name)608 n = comp.resources[n.Base.Ident]609 }610}611type pathElem struct {612 Pos ast.Pos613 Struct string614 Field string615}616func (comp *compiler) checkStructRecursion(checked map[string]bool, n *ast.Struct, path []pathElem) {617 name := n.Name.Name618 if checked[name] {619 return620 }621 for i, elem := range path {622 if elem.Struct != name {623 continue624 }625 path = path[i:]626 str := ""627 for _, elem := range path {628 str += fmt.Sprintf("%v.%v -> ", elem.Struct, elem.Field)629 }630 str += name631 comp.error(path[0].Pos, "recursive declaration: %v (mark some pointers as opt)", str)632 checked[name] = true633 return634 }635 for _, f := range n.Fields {636 path = append(path, pathElem{637 Pos: f.Pos,638 Struct: name,639 Field: f.Name.Name,640 })641 comp.recurseField(checked, f.Type, path)642 path = path[:len(path)-1]643 }644 checked[name] = true645}646func (comp *compiler) recurseField(checked map[string]bool, t *ast.Type, path []pathElem) {647 desc := comp.getTypeDesc(t)648 if desc == typeStruct {649 comp.checkStructRecursion(checked, comp.structs[t.Ident], path)650 return651 }652 _, args, base := comp.getArgsBase(t, false)653 if desc == typePtr && base.IsOptional {654 return // optional pointers prune recursion655 }656 for i, arg := range args {657 if desc.Args[i].Type == typeArgType {658 comp.recurseField(checked, arg, path)659 }660 }661}662func (comp *compiler) checkStruct(ctx checkCtx, n *ast.Struct) {663 var flags checkFlags664 if !n.IsUnion {665 flags |= checkIsStruct666 }667 for _, f := range n.Fields {668 comp.checkType(ctx, f.Type, flags)669 }670 comp.parseAttrs(structOrUnionAttrs(n), n, n.Attrs)671}672func (comp *compiler) checkCall(n *ast.Call) {673 for _, a := range n.Args {674 comp.checkType(checkCtx{}, a.Type, checkIsArg)675 }676 if n.Ret != nil {677 comp.checkType(checkCtx{}, n.Ret, checkIsArg|checkIsRet)678 }679 comp.parseAttrs(callAttrs, n, n.Attrs)680}681type checkFlags int682const (683 checkIsArg checkFlags = 1 << iota // immediate syscall arg type684 checkIsRet // immediate syscall ret type685 checkIsStruct // immediate struct field type686 checkIsResourceBase // immediate resource base type687 checkIsTypedef // immediate type alias/template type688)689type checkCtx struct {690 instantiationStack []string691}692func (comp *compiler) checkType(ctx checkCtx, t *ast.Type, flags checkFlags) {693 if unexpected, _, ok := checkTypeKind(t, kindIdent); !ok {694 comp.error(t.Pos, "unexpected %v, expect type", unexpected)695 return696 }697 desc := comp.getTypeDesc(t)698 if desc == nil {699 comp.error(t.Pos, "unknown type %v", t.Ident)700 return701 }702 if desc == typeTypedef {703 err0 := comp.errors704 // Replace t with type alias/template target type inplace,705 // and check the replaced type recursively.706 comp.replaceTypedef(&ctx, t, flags)707 if err0 == comp.errors {708 comp.checkType(ctx, t, flags)709 }710 return711 }712 err0 := comp.errors713 comp.checkTypeBasic(t, desc, flags)714 if err0 != comp.errors {715 return716 }717 args := comp.checkTypeArgs(t, desc, flags)718 if err0 != comp.errors {719 return720 }721 for i, arg := range args {722 if desc.Args[i].Type == typeArgType {723 var innerFlags checkFlags724 if desc.Args[i].IsArg {725 innerFlags |= checkIsArg726 }727 comp.checkType(ctx, arg, innerFlags)728 } else {729 comp.checkTypeArg(t, arg, desc.Args[i])730 }731 }732 if err0 != comp.errors {733 return734 }735 if desc.Check != nil {736 _, args, base := comp.getArgsBase(t, flags&checkIsArg != 0)737 desc.Check(comp, t, args, base)738 }739}740func (comp *compiler) checkTypeBasic(t *ast.Type, desc *typeDesc, flags checkFlags) {741 for i, col := range t.Colon {742 if i >= desc.MaxColon {743 comp.error(col.Pos, "unexpected ':'")744 return745 }746 if flags&checkIsStruct == 0 {747 comp.error(col.Pos, "unexpected ':', only struct fields can be bitfields")748 return749 }750 }751 if flags&checkIsTypedef != 0 && !desc.CanBeTypedef {752 comp.error(t.Pos, "%v can't be type alias target", t.Ident)753 return754 }755 if flags&checkIsResourceBase != 0 &&756 (desc.CanBeResourceBase == nil || !desc.CanBeResourceBase(comp, t)) {757 comp.error(t.Pos, "%v can't be resource base (int types can)", t.Ident)758 return759 }760 canBeArg, canBeRet := false, false761 if desc.CanBeArgRet != nil {762 canBeArg, canBeRet = desc.CanBeArgRet(comp, t)763 }764 if flags&checkIsRet != 0 && !canBeRet {765 comp.error(t.Pos, "%v can't be syscall return", t.Ident)766 return767 }768 if flags&checkIsArg != 0 && !canBeArg {769 comp.error(t.Pos, "%v can't be syscall argument", t.Ident)770 return771 }772}773func (comp *compiler) checkTypeArgs(t *ast.Type, desc *typeDesc, flags checkFlags) []*ast.Type {774 args, opt := removeOpt(t)775 if opt != nil {776 if len(opt.Args) != 0 {777 comp.error(opt.Pos, "opt can't have arguments")778 }779 if flags&checkIsResourceBase != 0 || desc.CantBeOpt {780 what := "resource base"781 if desc.CantBeOpt {782 what = t.Ident783 }784 comp.error(opt.Pos, "%v can't be marked as opt", what)785 return nil786 }787 }788 addArgs := 0789 needBase := flags&checkIsArg == 0 && desc.NeedBase790 if needBase {791 addArgs++ // last arg must be base type, e.g. const[0, int32]792 }793 if len(args) > len(desc.Args)+addArgs || len(args) < len(desc.Args)-desc.OptArgs+addArgs {794 comp.error(t.Pos, "wrong number of arguments for type %v, expect %v",795 t.Ident, expectedTypeArgs(desc, needBase))796 return nil797 }798 if needBase {799 base := args[len(args)-1]800 args = args[:len(args)-1]801 comp.checkTypeArg(t, base, typeArgBase)802 }803 return args804}805func (comp *compiler) replaceTypedef(ctx *checkCtx, t *ast.Type, flags checkFlags) {806 typedefName := t.Ident807 comp.usedTypedefs[typedefName] = true808 if len(t.Colon) != 0 {809 comp.error(t.Pos, "type alias %v with ':'", t.Ident)810 return811 }812 typedef := comp.typedefs[typedefName]813 // Handling optional BASE argument.814 if len(typedef.Args) > 0 && typedef.Args[len(typedef.Args)-1].Name == argBase {815 if flags&checkIsArg != 0 && len(t.Args) == len(typedef.Args)-1 {816 t.Args = append(t.Args, &ast.Type{817 Pos: t.Pos,818 Ident: "intptr",819 })820 } else if len(t.Args) == len(typedef.Args) {821 comp.checkTypeArg(t, t.Args[len(t.Args)-1], typeArgBase)822 }823 }824 fullTypeName := ast.SerializeNode(t)825 for i, prev := range ctx.instantiationStack {826 if prev == fullTypeName {827 ctx.instantiationStack = append(ctx.instantiationStack, fullTypeName)828 path := ""829 for j := i; j < len(ctx.instantiationStack); j++ {830 if j != i {831 path += " -> "832 }833 path += ctx.instantiationStack[j]834 }835 comp.error(t.Pos, "type instantiation loop: %v", path)836 return837 }838 }839 ctx.instantiationStack = append(ctx.instantiationStack, fullTypeName)840 nargs := len(typedef.Args)841 args := t.Args842 if nargs != len(t.Args) {843 if nargs == 0 {844 comp.error(t.Pos, "type %v is not a template", typedefName)845 } else {846 if flags&checkIsArg != 0 && typedef.Args[len(typedef.Args)-1].Name == argBase {847 nargs--848 }849 comp.error(t.Pos, "template %v needs %v arguments instead of %v",850 typedefName, nargs, len(t.Args))851 }852 return853 }854 pos0 := t.Pos855 if typedef.Type != nil {856 *t = *typedef.Type.Clone().(*ast.Type)857 if !comp.instantiate(t, typedef.Args, args) {858 return859 }860 } else {861 if comp.structs[fullTypeName] == nil {862 inst := typedef.Struct.Clone().(*ast.Struct)863 inst.Name.Name = fullTypeName864 if !comp.instantiate(inst, typedef.Args, args) {865 return866 }867 comp.checkStruct(*ctx, inst)868 comp.desc.Nodes = append(comp.desc.Nodes, inst)869 comp.structs[fullTypeName] = inst870 }871 *t = ast.Type{872 Ident: fullTypeName,873 }874 }875 t.Pos = pos0876 // Remove base type if it's not needed in this context.877 // If desc is nil, will return an error later when we typecheck the result.878 desc := comp.getTypeDesc(t)879 if desc != nil && flags&checkIsArg != 0 && desc.NeedBase {880 baseTypePos := len(t.Args) - 1881 if t.Args[baseTypePos].Ident == "opt" {882 baseTypePos--883 }884 copy(t.Args[baseTypePos:], t.Args[baseTypePos+1:])885 t.Args = t.Args[:len(t.Args)-1]886 }887}888func (comp *compiler) instantiate(templ ast.Node, params []*ast.Ident, args []*ast.Type) bool {889 if len(params) == 0 {890 return true891 }892 argMap := make(map[string]*ast.Type)893 for i, param := range params {894 argMap[param.Name] = args[i]895 }896 argUsed := make(map[string]bool)897 err0 := comp.errors898 ast.PostRecursive(func(n ast.Node) {899 templArg, ok := n.(*ast.Type)900 if !ok {901 return902 }903 if concreteArg := argMap[templArg.Ident]; concreteArg != nil {904 argUsed[templArg.Ident] = true905 origArgs := templArg.Args906 if len(origArgs) != 0 && len(concreteArg.Args) != 0 {907 comp.error(templArg.Pos, "both template parameter %v and its usage"+908 " have sub-arguments", templArg.Ident)909 return910 }911 *templArg = *concreteArg.Clone().(*ast.Type)912 if len(origArgs) != 0 {913 templArg.Args = origArgs914 }915 }916 // TODO(dvyukov): somewhat hacky, but required for int8[0:CONST_ARG]917 // Need more checks here. E.g. that CONST_ARG does not have subargs.918 // And if CONST_ARG is a value, then use concreteArg.Value.919 // Also need to error if CONST_ARG is a string.920 if len(templArg.Colon) != 0 {921 col := templArg.Colon[0]922 if concreteArg := argMap[col.Ident]; concreteArg != nil {923 argUsed[col.Ident] = true924 col.Ident = concreteArg.Ident925 col.Pos = concreteArg.Pos926 }927 }928 })(templ)929 for _, param := range params {930 if !argUsed[param.Name] {931 comp.error(argMap[param.Name].Pos,932 "template argument %v is not used", param.Name)933 }934 }935 return err0 == comp.errors936}937func (comp *compiler) checkTypeArg(t, arg *ast.Type, argDesc namedArg) {938 desc := argDesc.Type939 if len(desc.Names) != 0 {940 if unexpected, _, ok := checkTypeKind(arg, kindIdent); !ok {941 comp.error(arg.Pos, "unexpected %v for %v argument of %v type, expect %+v",942 unexpected, argDesc.Name, t.Ident, desc.Names)943 return944 }945 if !arrayContains(desc.Names, arg.Ident) {946 comp.error(arg.Pos, "unexpected value %v for %v argument of %v type, expect %+v",947 arg.Ident, argDesc.Name, t.Ident, desc.Names)948 return949 }950 } else {951 if unexpected, expect, ok := checkTypeKind(arg, desc.Kind); !ok {952 comp.error(arg.Pos, "unexpected %v for %v argument of %v type, expect %v",953 unexpected, argDesc.Name, t.Ident, expect)954 return955 }956 }957 for i, col := range arg.Colon {958 if i >= desc.MaxColon {959 comp.error(col.Pos, "unexpected ':'")960 return961 }962 if desc.Kind == kindIdent {963 if unexpected, expect, ok := checkTypeKind(col, kindIdent); !ok {964 comp.error(arg.Pos, "unexpected %v after colon, expect %v", unexpected, expect)965 return966 }967 }968 }969 if len(arg.Args) > desc.MaxArgs {970 comp.error(arg.Pos, "%v argument has subargs", argDesc.Name)971 return972 }973 if desc.Check != nil {974 desc.Check(comp, arg)975 }976}977func expectedTypeArgs(desc *typeDesc, needBase bool) string {978 expect := ""979 for i, arg := range desc.Args {980 if expect != "" {981 expect += ", "982 }983 opt := i >= len(desc.Args)-desc.OptArgs984 if opt {985 expect += "["986 }987 expect += arg.Name988 if opt {989 expect += "]"990 }991 }992 if needBase {993 if expect != "" {994 expect += ", "995 }996 expect += typeArgBase.Name997 }998 if !desc.CantBeOpt {999 if expect != "" {1000 expect += ", "1001 }1002 expect += "[opt]"1003 }1004 if expect == "" {1005 expect = "no arguments"1006 }1007 return expect1008}1009func checkTypeKind(t *ast.Type, kind int) (unexpected string, expect string, ok bool) {1010 switch {1011 case kind == kindAny:1012 ok = true1013 case t.HasString:1014 ok = kind == kindString1015 if !ok {1016 unexpected = fmt.Sprintf("string %q", t.String)1017 }1018 case t.Ident != "":1019 ok = kind == kindIdent || kind == kindInt1020 if !ok {1021 unexpected = fmt.Sprintf("identifier %v", t.Ident)1022 }1023 default:1024 ok = kind == kindInt1025 if !ok {1026 unexpected = fmt.Sprintf("int %v", t.Value)1027 }1028 }1029 if !ok {1030 switch kind {1031 case kindString:1032 expect = "string"1033 case kindIdent:1034 expect = "identifier"1035 case kindInt:1036 expect = "int"1037 }1038 }1039 return1040}1041func (comp *compiler) checkVarlens() {1042 for _, decl := range comp.desc.Nodes {1043 switch n := decl.(type) {1044 case *ast.Struct:1045 comp.checkVarlen(n)1046 }1047 }1048}1049func (comp *compiler) isVarlen(t *ast.Type) bool {1050 desc, args, _ := comp.getArgsBase(t, false)1051 return desc.Varlen != nil && desc.Varlen(comp, t, args)1052}1053func (comp *compiler) isZeroSize(t *ast.Type) bool {1054 desc, args, _ := comp.getArgsBase(t, false)1055 return desc.ZeroSize != nil && desc.ZeroSize(comp, t, args)1056}1057func (comp *compiler) checkVarlen(n *ast.Struct) {1058 // Non-varlen unions can't have varlen fields.1059 // Non-packed structs can't have varlen fields in the middle.1060 if n.IsUnion {1061 attrs := comp.parseAttrs(unionAttrs, n, n.Attrs)1062 if attrs[attrVarlen] != 0 {1063 return1064 }1065 } else {1066 attrs := comp.parseAttrs(structAttrs, n, n.Attrs)1067 if attrs[attrPacked] != 0 {1068 return1069 }1070 }1071 for i, f := range n.Fields {1072 if !n.IsUnion && i == len(n.Fields)-1 {1073 break1074 }1075 if comp.isVarlen(f.Type) {1076 if n.IsUnion {1077 comp.error(f.Pos, "variable size field %v in non-varlen union %v",1078 f.Name.Name, n.Name.Name)1079 } else {1080 comp.error(f.Pos, "variable size field %v in the middle of non-packed struct %v",1081 f.Name.Name, n.Name.Name)1082 }1083 }1084 }1085}1086func (comp *compiler) checkDupConsts() {1087 // The idea is to detect copy-paste errors in const arguments, e.g.:1088 // call$FOO(fd fd, arg const[FOO])1089 // call$BAR(fd fd, arg const[FOO])1090 // The second one is meant to be const[BAR],1091 // Unfortunately, this does not fully work as it detects lots of false positives.1092 // But was useful to find real bugs as well. So for now it's disabled, but can be run manually.1093 if true {1094 return1095 }1096 dups := make(map[string]map[string]dupConstArg)1097 for _, decl := range comp.desc.Nodes {1098 switch n := decl.(type) {1099 case *ast.Call:1100 comp.checkDupConstsCall(n, dups)1101 }1102 }1103}1104type dupConstArg struct {1105 pos ast.Pos1106 name string1107}1108func (comp *compiler) checkDupConstsCall(n *ast.Call, dups map[string]map[string]dupConstArg) {1109 if n.NR == ^uint64(0) {1110 return1111 }1112 for dups[n.CallName] == nil {1113 dups[n.CallName] = make(map[string]dupConstArg)1114 }1115 hasConsts := false1116 constArgID := ""1117 for i, arg := range n.Args {1118 desc := comp.getTypeDesc(arg.Type)1119 if desc == typeConst {1120 v := arg.Type.Args[0].Value1121 if v != 0 && v != 18446744073709551516 { // AT_FDCWD1122 constArgID += fmt.Sprintf("(%v-%v)", i, fmt.Sprintf("%v", v))...

Full Screen

Full Screen

checkDupConsts

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 f, err := parser.ParseFile(fset, "2.go", nil, parser.ParseComments)4 if err != nil {5 log.Fatal(err)6 }7 fmt.Println("Imports:")8 for _, s := range f.Imports {9 fmt.Println(s.Path.Value)10 }11 ast.Inspect(f, checkDupConsts)12}13func checkDupConsts(n ast.Node) bool {14 switch x := n.(type) {15 if x.Tok == token.CONST {16 for _, spec := range x.Specs {17 if valueSpec, ok := spec.(*ast.ValueSpec); ok {18 if len(valueSpec.Values) > 0 {19 fmt.Printf("valueSpec.Names: %v\n", valueSpec.Names)20 fmt.Printf("valueSpec.Values: %v\n", valueSpec.Values)21 }22 }23 }24 }25 }26}

Full Screen

Full Screen

checkDupConsts

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fset := token.NewFileSet()4 f, err := parser.ParseFile(fset, path, nil, parser.ParseComments)5 if err != nil {6 log.Fatal(err)7 }8 c := new(compiler)9 c.checkDupConsts(f)10}11type compiler struct {12}13func (c *compiler) checkDupConsts(f *ast.File) {14 m := make(map[string]bool)15 for _, d := range f.Decls {16 if gd, ok := d.(*ast.GenDecl); ok {17 if gd.Tok == token.CONST {18 for _, s := range gd.Specs {19 if vs, ok := s.(*ast.ValueSpec); ok {20 for _, n := range vs.Names {21 if m[n.Name] {22 fmt.Println("Error: Duplicate constant name", n.Name)23 } else {24 }25 }26 }27 }28 }29 }30 }31}

Full Screen

Full Screen

checkDupConsts

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 c := new(p1.Compiler)4 c.CheckDupConsts()5}6import (7type Compiler struct {8}9func (c *Compiler) CheckDupConsts() {10 c.constants = append(c.constants, "A")11 c.constants = append(c.constants, "B")12 c.constants = append(c.constants, "C")13 c.constants = append(c.constants, "D")14 c.constants = append(c.constants, "A")15 c.constants = append(c.constants, "B")16 c.constants = append(c.constants, "C")17 c.constants = append(c.constants, "D")18 c.constants = append(c.constants, "E")19 c.constants = append(c.constants, "F")20 c.constants = append(c.constants, "G")21 c.constants = append(c.constants, "H")22 c.constants = append(c.constants, "I")23 c.constants = append(c.constants, "J")24 c.constants = append(c.constants, "K")25 c.constants = append(c.constants, "L")26 c.constants = append(c.constants, "M")27 c.constants = append(c.constants, "N")28 c.constants = append(c.constants, "O")29 c.constants = append(c.constants, "P")30 c.constants = append(c.constants, "Q")31 c.constants = append(c.constants, "R")32 c.constants = append(c.constants, "S")33 c.constants = append(c.constants, "T")34 c.constants = append(c.constants, "U")35 c.constants = append(c.constants, "V")36 c.constants = append(c.constants, "W")37 c.constants = append(c.constants, "X")38 c.constants = append(c.constants, "Y")39 c.constants = append(c.constants, "Z")40 c.constants = append(c.constants, "A")41 c.constants = append(c.constants, "B")42 c.constants = append(c.constants, "C")43 c.constants = append(c.constants, "D")44 c.constants = append(c.constants, "E")45 c.constants = append(c.constants, "F")46 c.constants = append(c.constants, "G")47 c.constants = append(c.constants, "H")48 c.constants = append(c.constants, "I")49 c.constants = append(c.constants, "J")50 c.constants = append(c.constants, "K")51 c.constants = append(c.constants, "L")

Full Screen

Full Screen

checkDupConsts

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 comp.CheckDupConsts()4 fmt.Println(comp.ErrorList)5}6import (7func main() {8 comp.CheckDupVars()9 fmt.Println(comp.ErrorList)10}11import (12func main() {13 comp.CheckDupFuncs()14 fmt.Println(comp.ErrorList)15}16import (17func main() {18 comp.CheckDupProcs()19 fmt.Println(comp.ErrorList)20}21import (22func main() {23 comp.CheckDupParams()24 fmt.Println(comp.ErrorList)25}26import (27func main() {28 comp.CheckDupLocals()29 fmt.Println(comp.ErrorList)30}31import (32func main() {33 comp.CheckDupTypes()34 fmt.Println(comp.ErrorList)35}36import (37func main() {38 comp.CheckDupFields()39 fmt.Println(comp.ErrorList)40}41import (42func main() {43 comp.CheckDupMethods()44 fmt.Println(comp.ErrorList)45}46import (

Full Screen

Full Screen

checkDupConsts

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if len(os.Args) < 2 {4 fmt.Println("No file name provided!")5 }6 compiler := new(Compiler)7 compiler.checkDupConsts(os.Args[1])8}

Full Screen

Full Screen

checkDupConsts

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fset := token.NewFileSet()4 node, err := parser.ParseFile(fset, "2.go", nil, parser.ParseComments)5 if err != nil {6 fmt.Println(err)7 }8 c := new(compiler)9 c.checkDupConsts(node)10}11type compiler struct {12}13func (c *compiler) checkDupConsts(node *ast.File) {14 c.consts = make(map[string]*ast.ValueSpec)15 for _, decl := range node.Decls {16 if gd, ok := decl.(*ast.GenDecl); ok && gd.Tok == token.CONST {17 for _, spec := range gd.Specs {18 if vs, ok := spec.(*ast.ValueSpec); ok {19 for _, id := range vs.Names {20 if prev, ok := c.consts[id.Name]; ok {21 fmt.Printf("duplicate constant: %s\n", id.Name)22 fmt.Printf("\tprevious definition at %s\n", fset.Position(prev.Pos()))23 } else {24 }25 }26 }27 }28 }29 }30}

Full Screen

Full Screen

checkDupConsts

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 c := comp.NewCompiler()4 c.CheckDupConsts("3.go")5 fmt.Println("Done!")6}

Full Screen

Full Screen

checkDupConsts

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 comp := new(compiler)4 file, err := os.Open(os.Args[1])5 if err != nil {6 fmt.Println("Error opening file")7 }8 scanner := bufio.NewScanner(file)9 for scanner.Scan() {10 line := scanner.Text()11 comp.checkDupConsts(line)12 }13}14type compiler struct {15}16func (comp *compiler) checkDupConsts(line string) {17 if line == "" {18 }19 if comp.constMap == nil {20 comp.constMap = make(map[string]int)21 }22 if strings.Contains(line, "const") {23 splitLine := strings.Split(line, " ")24 constVal, err := strconv.Atoi(splitLine[3])25 if err != nil {26 fmt.Println("Error converting string to int")27 }28 if _, ok := comp.constMap[constName]; ok {29 fmt.Println("Line", comp.lineNum, ":", constName, "is a duplicate constant")30 } else {

Full Screen

Full Screen

checkDupConsts

Using AI Code Generation

copy

Full Screen

1import "fmt"2import "strings"3import "os"4import "bufio"5import "io"6type compiler struct {7 checkDupConsts func() int8}9func main() {10 c.checkDupConsts = func() int {

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Syzkaller automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful