1 // idlc.h -- Definitions used throughout idlc.
2 // A lot of this should probably be factored out into more specific headers.
4 // This software is copyright (c) 2006 Scott Wood <scott@buserror.net>.
6 // This software is provided 'as-is', without any express or implied warranty.
7 // In no event will the authors or contributors be held liable for any damages
8 // arising from the use of this software.
10 // Permission is hereby granted to everyone, free of charge, to use, copy,
11 // modify, prepare derivative works of, publish, distribute, perform,
12 // sublicense, and/or sell copies of the Software, provided that the above
13 // copyright notice and disclaimer of warranty be included in all copies or
14 // substantial portions of this software.
19 // inttypes.h on OSX assumes it can use restrict, but C++ doesn't have it.
20 // Hopefully C++ will catch up to C soon...
34 #include "compileddef.h"
45 #define cdl_lex idl_lex
46 void idl_error(const char *s);
48 #define cdl_error idl_error
50 void setup_idlparse();
51 void setup_cdlparse();
54 void yyerrorf(const char *s, ...) __attribute__((format(printf, 1, 2)));
55 void yyerrorfl(const char *file, int line, const char *s, ...)
56 __attribute__((format(printf, 3, 4)));
58 void yyerrorf(const char *s, ...);
59 void yyerrorfl(const char *file, int line, const char *s, ...);
66 extern int idl_debug, cdl_debug, curline, impl, num_err;
67 extern int current_pass;
69 extern unsigned int enum_pos;
70 extern const char *cur_input_file;
71 extern int compiling_idl, compiling_cdl;
76 // Location in the IDLC source of the BUG()
80 InternalError(const char *file, int line) :
81 file(file), line(line)
87 throw InternalError(__FILE__, __LINE__); \
92 #define assert(x) do { \
100 virtual ~Releasable()
104 Releasable(int COUNT) : count(COUNT)
111 fprintf(stderr, "Reference count is %d in release\n", count);
120 class AutoReleasePool {
121 list<const Releasable *> pool;
124 void add(const Releasable *obj)
131 for (list<const Releasable *>::iterator i = pool.begin();
132 i != pool.end(); ++i)
134 const Releasable *obj = *i;
142 extern AutoReleasePool autorelease_pool;
144 template <typename T>
145 class RefCountable : public Releasable {
147 // RefCountable objects should never be assigned to,
148 // as there could be references to the object remaining.
149 // The private assignment operator prevents this, unless
150 // a subclass defines its own assigment operator (don't
152 void operator =(const RefCountable &rc)
157 RefCountable(const RefCountable &rc) : Releasable(1)
163 RefCountable() : Releasable(1)
165 // Normally, this wouldn't be automatic, but this is what most
166 // things in IDLC are going to want, and it elimanates problems
167 // with needing to cast the return type of autorelease().
169 // The automatic autorelease() means that all refcountable objects
170 // must be allocated with "new", not on the stack, as global
171 // data, or as a class member.
176 virtual ~RefCountable()
180 const T *retain() const
183 fprintf(stderr, "Reference count is %d in retain\n", count);
188 return static_cast<const T *>(this);
194 fprintf(stderr, "Reference count is %d in retain\n", count);
199 return static_cast<T *>(this);
202 const T *autorelease() const
204 autorelease_pool.add(static_cast<Releasable *>(this));
205 return static_cast<T *>(this);
210 autorelease_pool.add(static_cast<Releasable *>(this));
211 return static_cast<T *>(this);
214 // This is only here because C++ obnoxiously requires it to
215 // be just because it's "called" from code excluded with an
216 // if (0) in a template. No code is ever generated that calls
217 // it, but it still must exist.
219 bool operator < (const RefCountable &rc)
225 // T must be RefCountable
226 template<typename T, bool compare_ptrs = true>
228 // STL containers like to use const on the items they
229 // contain; the mutable allows such containers to hold
230 // pointers to non-const data. For truly const Refs,
231 // make T const, as in StringRef. Unfortunately,
232 // it cannot be done in a more fine-grained manner,
244 Ref(T *data) : data(data)
250 Ref(Ref &le) : data(le.data)
256 Ref &operator =(const Ref &le)
258 // The retain must come first, in case both Refs are the same
269 Ref &operator =(T *new_data)
271 // The retain must come first, in case both Refs are the same
298 T *operator *() const
303 T *operator ->() const
308 bool operator == (const Ref &le) const
311 return data == le.data;
313 return *data == *le.data;
316 bool operator != (const Ref &le) const
319 return data != le.data;
321 return *data != *le.data;
324 bool operator < (const Ref &le) const
327 return reinterpret_cast<intptr_t>(data) <
328 reinterpret_cast<intptr_t>(le.data);
330 return *data < *le.data;
334 class String : public string, public RefCountable<String> {
336 // Origin of the string, if from the IDL file.
337 // Otherwise, fill both values with zero.
343 String(const char *s = "") : string(s)
350 String(const String &s) : string(s)
357 String(const char *s, const char *file, int line, int token) :
358 string(s), file(file), line(line), token(token)
362 extern String **yylval_string;
363 typedef Ref<const String, false> StringRef;
365 /* If a StrList is used for a namespace-qualified identifier, and
366 said identifier begins with ".." (i.e. starts from the root
367 namespace), the leading ".." is represented by a zero-length
370 Note that list doesn't have a virtual destructor, so all deletions
371 should happen through either RefCountable or the wrapper List
374 class StrList : public list<StringRef>, public RefCountable<StrList> {
380 // Parse a flat String into a StrList, using the specified delimeter.
381 StrList(const String *input, char delimiter = '.');
383 // Turn a StrList into a flat String, using the specified delimiter.
384 String *flatten(const char *delimiter = ".");
387 typedef Ref<StrList> StrListRef;
389 // ConList is like StrList, but with constant initializers
399 // FIXME: handle platforms with weird floating point endianness
405 // TOK_ICON, TOK_UCON, TOK_FCON, TOK_BOOL, TOK_DCON,
406 // TOK_INVALID, or TOK_NONE
407 // Constants are stored as signed (ICON) unless too
408 // large to fit in a signed 64-bit integer. Additional size and
409 // signedness checks are mode when down casting to a smaller size
410 // to fit into a particular datum; such constants will have a
413 // TOK_NONE is valid for maybeconst and size. TOK_INVALID
414 // indicates a previously detected error; don't emit any further
415 // errors due to this constant.
417 // TOK_DCON is used for symbolic constants, whose value may
423 extern Con *yylval_con;
429 ConInit(const String *str, Con &con) : str(str), con(con)
433 ConInit(const ConInit &coninit)
439 class ConList : public list<ConInit>, public RefCountable<ConList> {};
440 typedef Ref<ConList> ConListRef;
442 // Like StrList, but is a list of possibly namespace-qualified identifiers.
443 class IDList : public list<StrListRef>, public RefCountable<IDList> {};
444 typedef Ref<IDList> IDListRef;
450 typedef Ref<NameSpace> NameSpaceRef;
452 // This is incremented when a chain of symbols is traversed to reset
453 // detection of already-visited symbols. It is assumed that this
454 // will not have to happen billions of times.
456 extern int traversal;
458 class Symbol : public RefCountable<Symbol> {
472 // Symbol was loaded externally
475 // If set, the symbol is private, and will not be available
476 // for lookups except those made directly in the context of
477 // the containing namespace. Private symbols do not get
478 // outputted. They are used to implement imports of specific
479 // symbols (as aliases), rather than entire namespaces.
483 // Reserved for language binding use.
484 Releasable *lang_priv;
491 Symbol(const String *_name) : name(_name)
498 NameSpace *get_ns() const
503 const String *get_name() const
508 // If append is non-NULL, it is appended to non-user namespaces,
509 // to facilitate a language binding that cannot place nested types
510 // in the same language construct as the actual interface. The
511 // recommended suffix is "_ns", which is a reserved ending in the
512 // IDL. No suffix is placed on the final component of the name,
513 // even if it is a non-user namespace. The not_last field is used
514 // to detect whether it is the final component; it is only used
515 // internally, and should always be false when called externally.
517 // This function does *NOT* add a null first element to indicate
518 // that the name is fully qualified. If you need that, you have
519 // to add it yourself (call 'push_front(new String(""))' on the
522 StrList *get_fq_name(const char *append = NULL,
523 bool not_last = false) const;
525 virtual void lookup_imports()
529 virtual void lookup_chain()
533 virtual void lookup_misc()
537 virtual void final_analysis()
541 // These two methods must be implemented by all IDL symbols, but are
542 // not needed in CDL symbols (and therefore are not pure virtual).
544 virtual void output(const char *root)
548 virtual void output_lang(LangCallback *lcb, int arg = 0, void *arg2 = NULL)
552 // Find and return the topmost symbol other than a user namespace
553 // containing this symbol. If this symbol's parent is a user
554 // namespace, it returns itself. May not be called on the
555 // toplevel namespace.
557 Symbol *find_toplevel_type();
559 // Get the true type of the symbol, regardless of whether it is an
562 virtual Symbol *get_concrete_sym(bool follow_typedefs = true)
567 friend class NameSpace;
570 typedef Ref<Symbol> SymbolRef;
572 class SymList : public list<SymbolRef>, public RefCountable<SymList> {};
573 typedef Ref<SymList> SymListRef;
575 struct SymbolNotFound {
578 struct DuplicateSymbol {
581 struct InvalidArgument {
587 class NameSpace : public virtual Symbol {
589 // Filesystem path to the external symbol storage, or NULL
590 // if not an import namespace.
592 // Import namespaces are read-only namespaces which are created
593 // for the importation of externally-declared symbols. One is
594 // initially created for each "mount point" specified by the user;
595 // whenever such a namespace is searched, it checks the external
596 // storage, and if the lookup succeeds, the symbol is loaded and
597 // added to the namespace. Failed lookups could be cached with a
598 // special BadSymbol or some such, as the imported namespace is
599 // assumed to be constant, but I don't think such an optimization
600 // is worthwhile, at least at this point.
604 // Load a symbol from external storage, constructing the relevant type
605 // of object, and adding it to this namespace. Only called for
606 // import namespaces.
608 Symbol *load(const String *symname);
610 typedef map<StringRef, SymbolRef> tbl_type;
613 list<StrListRef> import_strs;
614 list<NameSpaceRef> imports;
617 // This is a counter for generating unique names for anonymous
618 // members of the namespace.
621 NameSpace() : anon(0)
625 virtual ~NameSpace();
627 // Return a description of the type of namespace, for
629 virtual const char *description()
634 virtual void output(const char *root);
636 typedef tbl_type::const_iterator const_iterator;
637 typedef tbl_type::value_type value_type;
639 // Derived classes can throw InvalidArgument if you give them
640 // a type of Symbol that they don't accept; see their comments
641 // for more details. Unfortunately, this cannot be done
642 // with static type-checking, as there are places that know
643 // they've been given a namespace that can accept a particular
644 // type of symbol, but they don't know exactly what kind of
645 // namespace it is. C++'s type system is not sufficient to
646 // express this (at least not while retaining any semblance
649 // DuplicateSymbol is thrown if sym already exists in this namespace.
650 virtual void add(Symbol *sym, bool from_import)
652 if (path && !from_import)
653 throw InvalidArgument();
656 sym->external = true;
661 pair<const_iterator, bool> ret = tbl.insert(value_type(sym->name, sym));
666 throw DuplicateSymbol();
670 // Add the symbol to this namespace, handling duplicate symbols by
671 // printing an error and throwing a UserError(). This should not be
672 // done in the symbol's constructor, as the parent may not accept
673 // the symbol until it is fully constructed (the RTTI information
674 // changes, and in general partially constructed objects shouldn't
675 // be exposed to the rest of the system).
677 void add_user(Symbol *sym);
679 // Like add_user, but used by the import code. Duplicate
680 // symbols result in internal errors, and the add is done with
681 // from_import set to true. InvalidArgument results in an error
682 // message and a reraise as UserError.
684 // All conditions checked by the parent namespace's add() method
685 // (such as constness of data) must be satisfied prior to calling
686 // add_import(). On the other hand, add_import() must be called
687 // before any recursive importation is done which could
688 // conceivably try to import the current symbol (thus causing
689 // infinite recursion).
691 void add_import(Symbol *sym, const char *filename);
693 // SymbolNotFound is thrown if sym is not in this namespace.
694 virtual void del(Symbol *sym)
697 throw SymbolNotFound();
700 int ret = tbl.erase(sym->name);
705 Symbol *lookup_noex_noimport(const String *symname)
707 const_iterator ret = tbl.find(symname);
709 if (ret != tbl.end())
710 return (*ret).second;
716 Symbol *lookup_noex(const String *symname, bool priv_ok = false)
718 Symbol *ret = NameSpace::lookup_noex_noimport(symname);
723 if (ret && !priv_ok && ret->priv)
729 Symbol *lookup(const String *symname, bool priv_ok = false)
731 Symbol *ret = lookup_noex(symname, priv_ok);
734 throw SymbolNotFound();
739 // Like lookup_noex, but also checks imported namespaces,
740 // and returns the namespace containing the match rather
741 // than the match itself.
743 NameSpace *search(const String *name, Symbol *exclude);
745 void add_search(StrList *ns)
747 import_strs.push_back(ns);
750 // Return a string containing case information manglement.
751 // See input.cc for more information.
753 static const String *mangle(const String *name);
755 const String *get_path()
760 // Import all members of this namespace. A no-op if not an import
764 // As import_all, but also recursively applies to any sub-namespaces.
765 void import_all_recursive();
767 const_iterator begin()
777 virtual void lookup_imports();
779 virtual void lookup_chain()
781 for (const_iterator i = begin(); i != end(); ++i) {
782 Symbol *sym = (*i).second;
787 virtual void lookup_misc()
789 for (const_iterator i = begin(); i != end(); ++i) {
790 Symbol *sym = (*i).second;
795 virtual void final_analysis()
797 for (const_iterator i = begin(); i != end(); ++i) {
798 Symbol *sym = (*i).second;
799 sym->final_analysis();
805 extern NameSpaceRef cur_nspace;
806 extern list<NameSpaceRef> nspace_stack;
808 typedef std::vector<StringRef> StringVec;
810 string *stringvec_to_path(StringVec &stringvec, const char *prepend);
812 // lookup_sym and lookup_type throw UserError on user error
813 // The context namespace is required for the proper
814 // set of namespaces to be searched.
816 Symbol *lookup_sym(NameSpace *topns, StrList *name, NameSpace *ctx,
817 Symbol *exclude = NULL);
820 const char *self; // Pointer to the type-specific struct
821 int self_len; // Length of the type-specific struct
824 CompiledDefHeader hdr;
826 // sym is the symbol from which to get the path/name, and
827 // dir is true if it should be "name/.self" rather than
829 void output_self(const char *dir, Symbol *sym, bool dir);
832 Def(const char *self, int self_len, CompiledDefHeader::Type type) :
833 self(self), self_len(self_len)
835 hdr.magic = CompiledDefHeader::magic_normal;
843 // Specific types may override this to output extra data
844 // to the .self file without having to reopen the file.
846 // Returns false on error.
848 virtual bool output_extra(FILE *f)
854 // Internal context struct used by input.cc to avoid passing
855 // lots of parameters around
856 struct ImportContext;
858 // This represents an actual IDL namespace {}, rather than
859 // a derived namespace such as a Struct or Interface.
861 class UserNameSpace : public NameSpace, public Def {
863 CompiledNameSpace def;
864 StringRef mountpoint_name;
866 UserNameSpace(const String *name = NULL) :
868 Def((const char *)&def, sizeof(def), CompiledDefHeader::NameSpace)
870 mountpoint_name = get_fq_name()->flatten();
871 def.length = mountpoint_name->length();
874 virtual void output(const char *root);
875 bool output_extra(FILE *f);
877 static void declare_import(const char *path);
879 static UserNameSpace *import(ImportContext &ctx);
880 virtual void output_lang(LangCallback *lcb, int arg = 0, void *arg2 = NULL);
883 typedef Ref<UserNameSpace> UserNameSpaceRef;
884 extern UserNameSpaceRef toplevel, cdl_toplevel;
885 extern UserNameSpace *output_ns;
887 class Type : public virtual Symbol {
897 virtual int get_default_bf_size()
899 // Only allow types in bitfields that explicitly
906 typedef Ref<Type> TypeRef;
908 // ctx can be NULL if basic_types_only is true
909 Type *lookup_type(StrList *sl, NameSpace *ctx, bool basic_types_only = false);
911 class BasicType : public Type, public Def {
913 CompiledBasicType def;
916 BasicType(const String *name) :
918 Def((const char *)&def, sizeof(def), CompiledDefHeader::BasicType)
921 memset(&def, 0, sizeof(def));
924 void init(CompiledBasicType &DEF)
932 static BasicType *declare(const String *name, NameSpace *parent,
933 CompiledBasicType &DEF)
935 BasicType *bt = new BasicType(name);
939 parent->add_user(bt);
944 virtual void output(const char *root);
946 static BasicType *import(ImportContext &ctx);
947 virtual void output_lang(LangCallback *lcb, int arg = 0, void *arg2 = NULL);
950 static inline bool is_array(CompiledBasicType &bt)
952 return bt.array.bounds[0] || bt.array.bounds[1];
955 static inline bool is_array(CompiledBasicType *bt)
957 return is_array(*bt);
960 typedef Ref<Datum> DatumRef;
962 class Array : public RefCountable<Array>
964 NameSpace *lookup_ctx;
967 // lower is [0], upper is [1]
971 // Strings for error reporting on each constant. If the constant
972 // is symbolic, then this is the fully qualified symbol name.
973 // Otherwise, it is the numerical value converted to a string. In
974 // each case, the file/line shall correspond to where the array
975 // bound was specified.
980 // ca is not valid until after final_analysis() is called.
983 Array(NameSpace *LOOKUP_CTX);
984 void set_bound(Con &con, int bound);
985 void final_analysis();
987 void set_unbounded();
990 typedef Ref<Array> ArrayRef;
992 class Datum : public Symbol, public Def {
993 StrListRef type_name;
995 StringRef type_fq_name;
997 StrListRef const_val_name;
998 SymbolRef const_val_sym;
1001 bool basic; // Datum is of a BasicType
1003 bool const_init; // Datum's constant has been initialized; this is
1004 // true after a successful verify_const().
1005 CompiledBasicType *cbt;
1009 int chain_traversed;
1011 // Recursively retrieve the actual value of a const datum
1012 // initialized with another named const datum. Returns
1013 // the "end" of an infinite loop, if one is found. Once
1014 // the full infinite loop has been printed, UserError is
1017 Datum *resolve_constant_chain();
1019 void init_const_early(Con *con);
1021 void use_anon_type(const CompiledBasicType &CBT)
1023 def.basictype = CBT;
1024 cbt = &def.basictype;
1027 def.type.length = 0;
1030 void process_type();
1032 void set_array(Array *ARRAY)
1042 int con_type; // Used to store the TOK_[IUF]CON of the Con struct
1043 // for type checking once the type is known.
1045 Datum(const String *name) :
1047 Def((const char *)&def, sizeof(def), CompiledDefHeader::Datum)
1051 chain_traversed = 0;
1052 memset(&def, 0, sizeof(def));
1055 void init(StrList *type, Array *ARRAY, Con *con = NULL);
1056 void init(CompiledBasicType &cbt, Array *ARRAY, Con *con = NULL);
1058 static Datum *declare(const String *name, NameSpace *parent,
1059 StrList *type, Array *ARRAY,
1064 Datum *d = new Datum(name);
1065 d->init(type, ARRAY, con);
1067 parent->add_user(d);
1071 static Datum *declare(const String *name, NameSpace *parent,
1072 CompiledBasicType &type,
1073 Array *ARRAY, Con *con = NULL)
1077 Datum *d = new Datum(name);
1078 d->init(type, ARRAY, con);
1080 parent->add_user(d);
1086 def.flags.field.Inline = 1;
1091 return def.flags.field.Inline;
1094 void set_immutable()
1096 def.flags.field.Immutable = 1;
1101 return def.flags.field.Immutable;
1104 // Returns true if the constant was acceptable, false otherwise (an
1105 // error is also output to the user in this case).
1107 bool verify_const();
1109 virtual void lookup_chain()
1114 const_val_sym = lookup_sym(toplevel, const_val_name, get_ns());
1118 type_sym = lookup_type(type_name, get_ns(), true);
1120 type_sym = lookup_sym(toplevel, type_name, get_ns());
1126 virtual void lookup_misc()
1128 if (def.flags.field.Const) {
1130 assert(def.flags.field.Const);
1133 Datum *d = resolve_constant_chain();
1143 virtual void final_analysis();
1145 virtual void output(const char *root);
1146 bool output_extra(FILE *f);
1148 static Datum *import(ImportContext &ctx);
1149 virtual void output_lang(LangCallback *lcb, int arg = 0, void *arg2 = NULL);
1151 uint64_t get_ucon(const String *err_str)
1153 if (!def.flags.field.Const) {
1154 yyerrorfl(err_str->file, err_str->line,
1155 "\"%s\" is not a const Datum.\n",
1156 get_fq_name()->flatten()->c_str());
1166 return ::is_array(def.basictype);
1170 template<typename T>
1171 bool output_list(T *sym, FILE *f);
1173 class BitField : public NameSpace, public Type, public Def {
1174 list<DatumRef> entries;
1176 void add_elem(Datum *d);
1179 CompiledBitField def;
1182 BitField(const String *name) :
1184 Def((const char *)&def, sizeof(def), CompiledDefHeader::BitField)
1186 memset(&def, 0, sizeof(def));
1189 void init(int bits, NameSpace *parent)
1191 if (bits < 0 || bits > 64) {
1192 yyerrorf("\"%s\" has invalid bitfield size %d",
1193 name->c_str(), bits);
1195 bits = bits < 0 ? 0 : 64;
1201 static BitField *declare(const String *name, NameSpace *parent,
1206 BitField *bf = new BitField(name);
1207 bf->init(bits, parent);
1209 parent->add_user(bf);
1213 // Only integral Datums, Enums, and BitFields can be added.
1215 void add(Symbol *sym, bool from_import);
1217 virtual const char *description()
1222 virtual void lookup_misc()
1224 NameSpace::lookup_misc();
1227 virtual void final_analysis()
1229 // FIXME: check total size of elements
1231 NameSpace::final_analysis();
1234 int get_default_bf_size()
1239 virtual void output(const char *root);
1240 bool output_extra(FILE *f);
1242 static BitField *import(ImportContext &ctx);
1243 virtual void output_lang(LangCallback *lcb, int arg = 0, void *arg2 = NULL);
1245 typedef list<DatumRef>::const_iterator entries_iterator;
1246 typedef list<DatumRef>::const_reverse_iterator entries_reverse_iterator;
1248 entries_iterator entries_begin()
1250 return entries.begin();
1253 entries_iterator entries_end()
1255 return entries.end();
1258 entries_reverse_iterator entries_rbegin()
1260 return entries.rbegin();
1263 entries_reverse_iterator entries_rend()
1265 return entries.rend();
1270 typedef Ref<Struct> StructRef;
1271 extern StructRef System_VStruct;
1273 // FIXME: typedefed superstructs
1274 class Struct : public NameSpace, public Type, public Def {
1275 list<DatumRef> entries;
1278 StrListRef supername;
1279 bool attrs_resolved;
1281 // 0 = unknown, 1 = yes, 2 = no
1284 void add_elem(Datum *d);
1286 void resolve_attrs()
1291 if (super && !super->attrs_resolved)
1292 super->resolve_attrs();
1294 if (super && super->def.flags.field.Virtual)
1295 def.flags.field.Virtual = 1;
1297 attrs_resolved = true;
1303 // This is not maintained by the generic code, but can be
1304 // used by language bindings to cache the result of the
1309 Struct(const String *name) :
1311 Def((const char *)&def, sizeof(def), CompiledDefHeader::Struct)
1313 memset(&def, 0, sizeof(def));
1317 void init(StrList *SUPERNAME)
1319 supername = SUPERNAME;
1322 static Struct *declare(const String *name, NameSpace *parent,
1327 Struct *st = new Struct(name);
1328 st->init(SUPERNAME);
1330 parent->add_user(st);
1336 def.flags.field.Virtual = 1;
1341 def.flags.field.Inline = 1;
1346 return def.flags.field.Virtual;
1351 return def.flags.field.Inline;
1354 // Only Datums and Types can be added.
1356 void add(Symbol *sym, bool from_import);
1358 virtual const char *description()
1365 assert(current_pass >= 4);
1369 virtual void lookup_chain()
1372 supersym = lookup_sym(toplevel, supername, get_ns());
1376 NameSpace::lookup_chain();
1382 if (supersym && !super) {
1383 super = dynamic_cast<Struct *>(supersym->get_concrete_sym());
1386 const String *str = supername->back();
1387 yyerrorfl(str->file, str->line,
1388 "\"%s\" is not a struct.",
1389 supersym->get_fq_name()->flatten()->c_str());
1392 def.flags.field.Super = 1;
1393 super->lookup_super();
1395 if (super->is_virtual())
1399 if (is_virtual() && !supersym && !super) {
1400 assert(System_VStruct);
1401 if (this != System_VStruct) {
1402 def.flags.field.Super = 1;
1403 super = System_VStruct;
1409 virtual void lookup_misc()
1413 if (is_virtual() && def.guid[0] == 0 && def.guid[1] == 0)
1414 yyerrorfl(name->file, name->line,
1415 "Virtual struct \"%s\" is missing a GUID.",
1416 get_fq_name()->flatten()->c_str());
1418 NameSpace::lookup_misc();
1421 virtual void final_analysis()
1423 // FIXME: check for infinite loops in struct inheritance
1426 NameSpace::final_analysis();
1429 virtual void output(const char *root);
1430 bool output_extra(FILE *f);
1432 static Struct *import(ImportContext &ctx);
1433 virtual void output_lang(LangCallback *lcb, int arg = 0, void *arg2 = NULL);
1435 typedef list<DatumRef>::const_iterator entries_iterator;
1437 entries_iterator entries_begin()
1439 return entries.begin();
1442 entries_iterator entries_end()
1444 return entries.end();
1447 void set_guid(uint64_t guid[2])
1449 if (def.guid[0] || def.guid[1])
1450 yyerrorf("\"%s\" already has a GUID.",
1451 get_fq_name()->flatten()->c_str());
1453 def.guid[0] = guid[0];
1454 def.guid[1] = guid[1];
1457 // A struct is "plain data" if it contains no object references,
1458 // no non-inline arrays or structs, and no inline non-plain structs.
1459 bool is_plain_data();
1462 class Param : public Symbol, public Def {
1463 StrListRef type_name;
1464 StringRef type_fq_name;
1466 bool basic; // Datum is of a BasicType
1471 void use_named_type(BasicType *bt)
1473 assert(!bt || bt->def.flags.field.TypeDef);
1477 type_fq_name = type->get_fq_name()->flatten();
1478 def.type.length = type_fq_name->length();
1481 void use_anon_type(const CompiledBasicType &cbt)
1483 def.basictype = cbt;
1488 void set_array(Array *ARRAY)
1498 Param(const String *name) :
1500 Def((const char *)&def, sizeof(def), CompiledDefHeader::Param)
1502 memset(&def, 0, sizeof(def));
1505 void init(StrList *TYPE, CompiledParam::Flags flags, Array *ARRAY)
1512 static Param *declare(const String *name, NameSpace *parent,
1513 StrList *TYPE, CompiledParam::Flags flags,
1516 virtual void lookup_misc()
1518 type = lookup_type(type_name, get_ns());
1521 virtual void final_analysis()
1523 BasicType *bt = dynamic_cast<BasicType *>(type->get_concrete_sym());
1525 if (bt && !bt->def.flags.field.TypeDef) {
1526 use_anon_type(bt->def);
1530 Struct *str = dynamic_cast<Struct *>(*type);
1531 if (str && str->is_inline())
1534 if (!str && is_inline()) {
1535 yyerrorfl(name->file, name->line,
1536 "\"%s\" is static but not a struct.",
1537 get_fq_name()->flatten()->c_str());
1542 array->final_analysis();
1543 def.basictype.array = array->ca;
1545 def.basictype.array.bounds[0] = 0;
1546 def.basictype.array.bounds[1] = 0;
1552 def.flags.field.Inline = 1;
1557 return def.flags.field.Inline;
1562 return def.flags.field.In;
1567 return def.flags.field.Out;
1570 virtual void output(const char *root);
1571 bool output_extra(FILE *f);
1573 static Param *import(ImportContext &ctx);
1574 virtual void output_lang(LangCallback *lcb, int arg = 0, void *arg2 = NULL);
1578 return ::is_array(def.basictype);
1582 typedef Ref<Param> ParamRef;
1584 class Method : public NameSpace, public Def {
1585 list<ParamRef> entries;
1587 void add_elem(Param *p);
1592 Method(const String *name) :
1594 Def((const char *)&def, sizeof(def), CompiledDefHeader::Method)
1596 memset(&def, 0, sizeof(def));
1601 def.flags.field.Async = 1;
1606 return def.flags.field.Async;
1609 static Method *declare(const String *name, NameSpace *parent);
1611 void add(Symbol *sym, bool from_import);
1613 virtual const char *description()
1618 virtual void output(const char *root);
1619 bool output_extra(FILE *f);
1621 static Method *import(ImportContext &ctx);
1622 virtual void output_lang(LangCallback *lcb, int arg = 0, void *arg2 = NULL);
1624 typedef list<ParamRef>::const_iterator entries_iterator;
1626 entries_iterator entries_begin()
1628 return entries.begin();
1631 entries_iterator entries_end()
1633 return entries.end();
1637 typedef Ref<Method> MethodRef;
1640 typedef Ref<Interface> InterfaceRef;
1642 extern InterfaceRef System_Object;
1644 // FIXME: typedefed superinterfaces
1645 class Interface : public NameSpace, public Type, public Def {
1646 list<MethodRef> methods;
1647 list<InterfaceRef> supers;
1648 IDListRef supernames;
1650 void add_elem(Method *m);
1652 // This is like Symbol::traversed[], but used internally by the
1653 // for_each_super function to ensure that common ancestors are only
1656 int traversed_all_supers;
1657 static int all_supers_traversal;
1660 typedef void (*callback)(Interface *i, void *arg);
1663 template<callback cb>
1664 void for_each_super_internal(void *arg)
1666 for (supers_iterator i = supers_begin(); i != supers_end(); ++i) {
1667 Interface *iface = *i;
1669 if (iface->traversed_all_supers < all_supers_traversal) {
1670 iface->traversed_all_supers = all_supers_traversal;
1672 iface->for_each_super_internal<cb>(arg);
1677 // All interfaces in the map and vector are supers of this
1678 // interface, and thus retained that way, so plain pointers
1679 // can be used here.
1681 typedef map<Interface *, int> chain_map_type;
1682 typedef chain_map_type::value_type chain_valtype;
1683 typedef chain_map_type::const_iterator chain_iter;
1685 chain_map_type super_to_chain_map;
1689 vector<Interface *> chain_heads;
1692 int super_to_chain(Interface *iface, bool must_find_it = true)
1694 chain_iter ret = super_to_chain_map.find(iface);
1696 if (ret == super_to_chain_map.end()) {
1697 assert(!must_find_it);
1701 return (*ret).second;
1704 Interface *get_chain_head(int chain)
1706 return chain_heads[chain];
1709 int get_num_chains()
1715 void set_chain(Interface *iface, int chain)
1717 pair<chain_iter, bool> ret =
1718 super_to_chain_map.insert(chain_valtype(iface, chain));
1722 // This is the inner depth-first search, which terminates
1723 // at each level upon finding that the node it had previously
1724 // recursed into found an unchained node.
1726 void pick_chain(Interface *iface, int chain)
1728 assert(super_to_chain(iface, false) == -1);
1729 chain_heads.push_back(iface);
1732 set_chain(iface, chain);
1734 if (iface->supers.empty())
1737 iface = iface->supers.front();
1738 } while (super_to_chain(iface, false) == -1);
1741 // This is the outer breadth-first-search, making sure every
1742 // super is assigned to a chain.
1746 list<Interface *> bfs;
1749 bfs.push_back(this);
1751 while (!bfs.empty()) {
1752 Interface *iface = bfs.front();
1755 for (supers_iterator i = iface->supers_begin();
1756 i != iface->supers_end(); ++i)
1759 if (super_to_chain(iface, false) == -1)
1760 pick_chain(iface, num_chains++);
1765 // Do not call after lookup_misc
1766 void add_super(Interface *i)
1768 assert(current_pass != 1);
1770 supers.push_back(i);
1774 CompiledInterface def;
1776 Interface(const String *name) :
1778 Def((const char *)&def, sizeof(def), CompiledDefHeader::Interface)
1780 memset(&def, 0, sizeof(def));
1781 traversed_all_supers = 0;
1784 void init(IDList *SUPERNAMES)
1786 supernames = SUPERNAMES;
1789 static Interface *declare(const String *name, NameSpace *parent,
1794 Interface *i = new Interface(name);
1795 i->init(SUPERNAMES);
1797 parent->add_user(i);
1801 // Only Methods, Types, and const BasicType Datums can be added.
1803 void add(Symbol *sym, bool from_import);
1805 virtual const char *description()
1811 void add_object_super()
1813 assert(System_Object);
1814 if (this != System_Object && supers.empty())
1815 add_super(System_Object);
1819 virtual void lookup_misc()
1821 if (def.guid[0] == 0 && def.guid[1] == 0)
1822 yyerrorfl(name->file, name->line,
1823 "Interface \"%s\" is missing a GUID.",
1824 get_fq_name()->flatten()->c_str());
1827 for (IDList::iterator i = supernames->begin();
1828 i != supernames->end(); ++i)
1830 Symbol *sym = lookup_sym(toplevel, *i, get_ns());
1832 dynamic_cast<Interface *>(sym->get_concrete_sym());
1835 const String *str = (*i)->back();
1836 yyerrorfl(str->file, str->line,
1837 "\"%s\" is not an interface.\n",
1838 sym->get_fq_name()->flatten()->c_str());
1848 NameSpace::lookup_misc();
1851 virtual void final_analysis()
1853 // FIXME: check for infinite loops in inheritance
1856 NameSpace::final_analysis();
1859 virtual void output(const char *root);
1860 bool output_extra(FILE *f);
1862 static Interface *import(ImportContext &ctx);
1863 virtual void output_lang(LangCallback *lcb, int arg = 0, void *arg2 = NULL);
1865 typedef list<MethodRef>::const_iterator methods_iterator;
1866 typedef list<InterfaceRef>::const_iterator supers_iterator;
1868 supers_iterator supers_begin()
1870 assert(current_pass != 1);
1871 return supers.begin();
1874 supers_iterator supers_end()
1876 return supers.end();
1881 assert(current_pass != 1);
1882 return supers.empty();
1885 methods_iterator methods_begin()
1887 return methods.begin();
1890 methods_iterator methods_end()
1892 return methods.end();
1895 template<callback cb>
1896 void for_each_super(void *arg)
1898 assert(current_pass >= 4);
1900 all_supers_traversal++;
1901 for_each_super_internal<cb>(arg);
1904 void finalize_class_iface()
1910 void set_guid(uint64_t guid[2])
1912 if (def.guid[0] || def.guid[1])
1913 yyerrorf("\"%s\" already has a GUID.",
1914 get_fq_name()->flatten()->c_str());
1916 def.guid[0] = guid[0];
1917 def.guid[1] = guid[1];
1921 class IFaceList : public list<InterfaceRef>,
1922 public RefCountable<IFaceList> {};
1924 class Enum : public NameSpace, public Type, public Def {
1925 list<DatumRef> entries;
1927 void add_elem(Datum *d);
1930 unsigned int next_val;
1933 Enum(const String *name) :
1935 Def((const char *)&def, sizeof(def), CompiledDefHeader::Enum),
1938 memset(&def, 0, sizeof(def));
1943 if (bits < 0 || bits > 64) {
1944 yyerrorf("\"%s\" has invalid enum size %d",
1945 name->c_str(), bits);
1947 bits = bits < 0 ? 0 : 64;
1953 static Enum *declare(const String *name, NameSpace *parent,
1958 Enum *e = new Enum(name);
1961 parent->add_user(e);
1965 // Only const unsigned integer BasicType Datums are allowed.
1967 void add(Symbol *sym, bool from_import);
1969 virtual const char *description()
1971 return "enumeration";
1974 int get_default_bf_size()
1979 virtual void output(const char *root);
1980 bool output_extra(FILE *f);
1982 static Enum *import(ImportContext &ctx);
1983 virtual void output_lang(LangCallback *lcb, int arg = 0, void *arg2 = NULL);
1985 typedef list<DatumRef>::const_iterator entries_iterator;
1987 entries_iterator entries_begin()
1989 return entries.begin();
1992 entries_iterator entries_end()
1994 return entries.end();
1998 class Alias : public Symbol, public Def {
2004 Cycle(Alias *END) : end(END)
2013 StringRef sym_fq_name;
2014 StrListRef sym_name;
2016 Alias(const String *name) :
2018 Def((const char *)&def, sizeof(def), CompiledDefHeader::Alias)
2020 memset(&def, 0, sizeof(def));
2021 lookup_begun = false;
2024 void init(StrList *symname, bool is_private)
2030 static Alias *declare(const String *name, NameSpace *parent,
2031 StrList *symname, bool is_private = false)
2034 Alias *a = new Alias(name);
2035 a->init(symname, is_private);
2037 parent->add_user(a);
2041 void resolve_chain()
2045 yyerrorfl(name->file, name->line,
2046 "Alias loop defining \"%s\"",
2047 get_fq_name()->flatten()->c_str());
2052 lookup_begun = true;
2055 real_sym = lookup_sym(toplevel, sym_name, get_ns(), this);
2059 yyerrorfl(name->file, name->line, " ...referenced by \"%s\"",
2060 get_fq_name()->flatten()->c_str());
2070 virtual Symbol *get_concrete_sym(bool follow_typedefs = true)
2073 return real_sym->get_concrete_sym(follow_typedefs);
2076 virtual void lookup_chain()
2078 get_concrete_sym(true);
2081 virtual void lookup_misc()
2083 real_sym = real_sym->get_concrete_sym(false);
2084 sym_fq_name = real_sym->get_fq_name()->flatten();
2086 def.length = sym_fq_name->length();
2089 virtual void output(const char *root);
2090 bool output_extra(FILE *f);
2092 static Alias *import(ImportContext &ctx);
2093 virtual void output_lang(LangCallback *lcb, int arg = 0, void *arg2 = NULL);
2096 class TypeDef : public Alias {
2098 TypeDef(const String *name) : Alias(name)
2100 memset(&def, 0, sizeof(def));
2101 hdr.type = CompiledDefHeader::TypeDef;
2104 static TypeDef *declare(const String *name, NameSpace *parent,
2108 TypeDef *td = new TypeDef(name);
2109 td->init(symname, false);
2111 parent->add_user(td);
2115 virtual Symbol *get_concrete_sym(bool follow_typedefs = true)
2117 if (follow_typedefs) {
2119 return real_sym->get_concrete_sym(follow_typedefs);
2125 static TypeDef *import(ImportContext &ctx);
2126 virtual void output_lang(LangCallback *lcb, int arg = 0, void *arg2 = NULL);
2129 NameSpace *add_nspace(StrList *name, bool push);
2132 // Declare an instance of "type" in "ns" for each element of "ids".
2133 // This function will report any errors, but not throw UserError.
2135 void declare_data(NameSpace *ns, StrList *ids, StrList *type,
2136 Array *array, StrList *attr);
2137 void declare_aliases(NameSpace *ns, StrList *ids, StrList *type,
2139 void declare_basictypes(NameSpace *ns, StrList *ids,
2140 BasicType *type, bool is_typedef);
2142 // You'd think they'd have standard functions to do this these days.
2143 // All I could find that come close are the network-byte-order
2144 // functions, and they're no-ops on big-endian machines.
2146 static inline uint32_t swap32(uint32_t in, bool swap)
2149 return ((in & 0x000000ff) << 24) |
2150 ((in & 0x0000ff00) << 8) |
2151 ((in & 0x00ff0000) >> 8) |
2152 ((in & 0xff000000) >> 24);
2157 static inline uint64_t swap64(uint64_t in, bool swap)
2160 return (((uint64_t)swap32((uint32_t)in, true)) << 32) |
2161 swap32((uint32_t)(in >> 32), true);
2179 File *operator =(FILE *F)
2197 // Verify that a prospective new import (or output namespace)
2198 // does not overlap an existing import. Returns the conflicting
2199 // import, or NULL if none found.
2201 NameSpace *check_for_imports(NameSpace *ns);