github.com/yanyiwu/go@v0.0.0-20150106053140-03d6637dbb7f/src/cmd/gc/mkbuiltin1.c (about) 1 // Copyright 2009 The Go 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 // +build ignore 6 7 // Compile .go file, import data from .6 file, and generate C string version. 8 9 #include <stdio.h> 10 #include <stdlib.h> 11 #include <unistd.h> 12 #include <string.h> 13 #include <errno.h> 14 #include <stdarg.h> 15 16 void esc(char*); 17 void fatal(char*, ...); 18 19 int 20 main(int argc, char **argv) 21 { 22 char *name; 23 FILE *fin; 24 char buf[1024], initfunc[1024], *p, *q; 25 26 if(argc != 2) { 27 fprintf(stderr, "usage: mkbuiltin1 sys\n"); 28 fatal("in file $1.6 s/PACKAGE/$1/"); 29 } 30 31 name = argv[1]; 32 snprintf(initfunc, sizeof(initfunc), "init_%s_function", name); 33 34 snprintf(buf, sizeof(buf), "%s.%s", name, getenv("O")); 35 if((fin = fopen(buf, "r")) == NULL) { 36 fatal("open %s: %s", buf, strerror(errno)); 37 } 38 39 // look for $$ that introduces imports 40 while(fgets(buf, sizeof buf, fin) != NULL) 41 if(strstr(buf, "$$")) 42 goto begin; 43 fatal("did not find beginning of imports"); 44 45 begin: 46 printf("char *%simport =\n", name); 47 48 // process imports, stopping at $$ that closes them 49 while(fgets(buf, sizeof buf, fin) != NULL) { 50 buf[strlen(buf)-1] = 0; // chop \n 51 if(strstr(buf, "$$")) 52 goto end; 53 54 // chop leading white space 55 for(p=buf; *p==' ' || *p == '\t'; p++) 56 ; 57 58 // cut out decl of init_$1_function - it doesn't exist 59 if(strstr(buf, initfunc)) 60 continue; 61 62 // sys.go claims to be in package PACKAGE to avoid 63 // conflicts during "6g sys.go". rename PACKAGE to $2. 64 printf("\t\""); 65 while((q = strstr(p, "PACKAGE")) != NULL) { 66 *q = 0; 67 esc(p); // up to the substitution 68 printf("%s", name); // the sub name 69 p = q+7; // continue with rest 70 } 71 72 esc(p); 73 printf("\\n\"\n"); 74 } 75 fatal("did not find end of imports"); 76 77 end: 78 printf("\t\"$$\\n\";\n"); 79 return 0; 80 } 81 82 void 83 esc(char *p) 84 { 85 for(; *p; p++) { 86 if(*p == '\\' || *p == '\"') 87 printf("\\"); 88 putchar(*p); 89 } 90 } 91 92 void 93 fatal(char *msg, ...) 94 { 95 va_list arg; 96 97 va_start(arg, msg); 98 fprintf(stderr, "fatal: "); 99 vfprintf(stderr, msg, arg); 100 fprintf(stderr, "\n"); 101 exit(2); 102 }