gitlab.com/cznic/ccir@v1.0.0/etc.go (about) 1 // Copyright 2017 The CCIR Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package ccir // import "modernc.org/ccir" 6 7 import ( 8 "go/scanner" 9 "go/token" 10 "strings" 11 12 "modernc.org/cc" 13 "modernc.org/ir" 14 "modernc.org/xc" 15 ) 16 17 var ( 18 dict = xc.Dict 19 20 idBuiltinPrefix = dict.SID("__builtin_") 21 idComplex128 = ir.TypeID(dict.SID("complex128")) 22 idComplex64 = ir.TypeID(dict.SID("complex64")) 23 idEmptyString = dict.SID(`""`) 24 idFloat32 = ir.TypeID(dict.SID("float32")) 25 idFloat64 = ir.TypeID(dict.SID("float64")) 26 idInt16 = ir.TypeID(dict.SID("int16")) 27 idInt32 = ir.TypeID(dict.SID("int32")) 28 idInt64 = ir.TypeID(dict.SID("int64")) 29 idInt8 = ir.TypeID(dict.SID("int8")) 30 idInt8Ptr = ir.TypeID(dict.SID("*int8")) 31 idMain = ir.NameID(dict.SID("main")) 32 idPInt32 = ir.TypeID(dict.SID("*int32")) 33 idUint16 = ir.TypeID(dict.SID("uint16")) 34 idUint32 = ir.TypeID(dict.SID("uint32")) 35 idUint64 = ir.TypeID(dict.SID("uint64")) 36 idUint8 = ir.TypeID(dict.SID("uint8")) 37 idVoid = ir.TypeID(dict.SID("struct{}")) 38 idVoidPtr = ir.TypeID(dict.SID("*struct{}")) 39 ) 40 41 func position(n cc.Node) token.Position { 42 if n != nil { 43 return xc.FileSet.Position(n.Pos()) 44 } 45 46 return token.Position{} 47 } 48 49 func isUnsigned(t cc.Type) bool { 50 switch t.Kind() { 51 case cc.Bool, cc.UChar, cc.UShort, cc.UInt, cc.ULong, cc.ULongLong: 52 return true 53 default: 54 return false 55 } 56 } 57 58 func isOpenMDArray(t cc.Type) bool { 59 if t.Kind() != cc.Ptr { 60 return false 61 } 62 63 et := t.Element() 64 if et.Kind() != cc.Array { 65 return false 66 } 67 68 ts := t.String() 69 es := et.String() 70 r := 1 71 for ts[len(ts)-r] == es[len(es)-r] { 72 r++ 73 } 74 n := len(es) - r + 1 75 return ts[n:n+2] == "[]" 76 } 77 78 func tidyComment(s string) string { 79 switch { 80 case strings.HasPrefix(s, "/*"): 81 a := strings.Split("/"+s[1:len(s)-1], "\n") 82 for i, v := range a { 83 a[i] = "// " + v 84 } 85 return strings.Join(a, "\n") + "/\n" 86 case strings.HasPrefix(s, "//"): 87 return "// " + s[2:] + "\n" 88 default: 89 panic("internal error") 90 } 91 } 92 93 func tidyComments(b []byte) string { 94 var s scanner.Scanner 95 s.Init(token.NewFileSet().AddFile("", -1, len(b)), b, nil, scanner.ScanComments) 96 var a []string 97 for { 98 _, tok, lit := s.Scan() 99 if tok == token.EOF { 100 return "// C comment\n" + strings.Join(a, "") 101 } 102 103 a = append(a, tidyComment(lit)) 104 } 105 }